getu-attribution-v2-sdk 0.5.0 → 0.5.2
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/dist/core/AttributionSDK.d.ts.map +1 -1
- package/dist/core/AttributionSDK.js +12 -3
- package/dist/getuai-attribution.min.js +1 -1
- package/dist/index.esm.js +141 -3
- package/dist/index.esm.js.map +1 -1
- package/dist/index.js +146 -3
- package/dist/queue/index.d.ts.map +1 -1
- package/dist/queue/index.js +30 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/types/index.d.ts.map +1 -1
- package/dist/utils/index.d.ts +3 -0
- package/dist/utils/index.d.ts.map +1 -1
- package/dist/utils/index.js +104 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +1 -1
|
@@ -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;
|
|
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;AA8BlB,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,CAAC,iBAAiB,CAAyC;IAClE,OAAO,CAAC,oBAAoB,CAA4C;IACxE,OAAO,CAAC,eAAe,CAAiD;gBAE5D,MAAM,EAAE,SAAS;IA+CvB,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAqGrB,UAAU,CACd,SAAS,EAAE,SAAS,EACpB,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAC/B,gBAAgB,CAAC,EAAE,MAAM,EACzB,OAAO,CAAC,EAAE,MAAM,EAChB,QAAQ,GAAE,QAAuB,EACjC,iBAAiB,CAAC,EAAE,MAAM,GACzB,OAAO,CAAC,IAAI,CAAC;IAgEV,gBAAgB,CACpB,eAAe,EAAE,MAAM,EACvB,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAC/B,gBAAgB,CAAC,EAAE,MAAM,EACzB,OAAO,CAAC,EAAE,MAAM,EAChB,QAAQ,GAAE,QAAuB,GAChC,OAAO,CAAC,IAAI,CAAC;IAgBV,aAAa,CACjB,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAC9B,gBAAgB,CAAC,EAAE,MAAM,GACxB,OAAO,CAAC,IAAI,CAAC;IAoChB,OAAO,CAAC,yBAAyB;IASjC,OAAO,CAAC,qBAAqB;YAmBf,aAAa;IAsBrB,aAAa,CACjB,gBAAgB,EAAE,MAAM,EACxB,OAAO,EAAE,MAAM,EACf,QAAQ,GAAE,QAAuB,EACjC,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GACjC,OAAO,CAAC,IAAI,CAAC;IAWV,UAAU,CACd,gBAAgB,EAAE,MAAM,EACxB,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAC9B,OAAO,CAAC,IAAI,CAAC;IAKV,WAAW,CACf,gBAAgB,EAAE,MAAM,EACxB,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAC/B,OAAO,CAAC,IAAI,CAAC;IAKV,eAAe,CACnB,gBAAgB,CAAC,EAAE,MAAM,EACzB,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAC7B,OAAO,CAAC,IAAI,CAAC;IAKV,cAAc,CAClB,gBAAgB,CAAC,EAAE,MAAM,EACzB,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAC9B,OAAO,CAAC,IAAI,CAAC;IAKV,sBAAsB,CAC1B,gBAAgB,EAAE,MAAM,EACxB,gBAAgB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GACrC,OAAO,CAAC,IAAI,CAAC;IASV,kBAAkB,CACtB,gBAAgB,EAAE,MAAM,EACxB,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAC9B,OAAO,CAAC,IAAI,CAAC;IASV,iBAAiB,CAAC,OAAO,EAAE;QAC/B,OAAO,EAAE,MAAM,CAAC;QAChB,QAAQ,CAAC,EAAE,QAAQ,CAAC;QACpB,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;QACnC,gBAAgB,CAAC,EAAE,MAAM,CAAC;KAC3B,GAAG,OAAO,CAAC,IAAI,CAAC;IAkBX,cAAc,CAAC,OAAO,EAAE;QAC5B,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;QAChC,gBAAgB,CAAC,EAAE,MAAM,CAAC;KAC3B,GAAG,OAAO,CAAC,IAAI,CAAC;IAYX,eAAe,CAAC,OAAO,EAAE;QAC7B,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;QACjC,gBAAgB,CAAC,EAAE,MAAM,CAAC;KAC3B,GAAG,OAAO,CAAC,IAAI,CAAC;IAYX,0BAA0B,CAAC,OAAO,EAAE;QACxC,gBAAgB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;QACvC,gBAAgB,CAAC,EAAE,MAAM,CAAC;KAC3B,GAAG,OAAO,CAAC,IAAI,CAAC;IAgBX,gBAAgB,CACpB,gBAAgB,CAAC,EAAE,MAAM,EACzB,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAChC,OAAO,CAAC,IAAI,CAAC;IASV,cAAc,CAClB,gBAAgB,CAAC,EAAE,MAAM,EACzB,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAC7B,OAAO,CAAC,IAAI,CAAC;IAKV,cAAc,CAClB,gBAAgB,CAAC,EAAE,MAAM,EACzB,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAC9B,OAAO,CAAC,IAAI,CAAC;IAKV,gBAAgB,CACpB,UAAU,CAAC,EAAE,MAAM,EACnB,gBAAgB,CAAC,EAAE,MAAM,EACzB,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAC9B,OAAO,CAAC,IAAI,CAAC;IAShB,kBAAkB,IAAI,eAAe,GAAG,IAAI;IAK5C,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM;IAmBhC,mBAAmB,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC;IAa7C,OAAO,CAAC,YAAY;IAkDpB,OAAO,CAAC,WAAW;IA0BnB,OAAO,CAAC,gBAAgB;IAsBxB,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IAgD/B,OAAO,CAAC,aAAa;IAarB,SAAS,IAAI,MAAM,GAAG,IAAI;IAK1B,cAAc,IAAI,MAAM;IAKxB,YAAY,IAAI,IAAI;IAKpB;;;;;;;;;;;;;OAaG;IACG,QAAQ,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC;IAgClE;;OAEG;IACH,aAAa,IAAI,UAAU,GAAG,IAAI;IAIlC;;OAEG;IACH,YAAY,IAAI,MAAM,GAAG,IAAI;IAK7B,OAAO,CAAC,iBAAiB;IAmDzB,OAAO,CAAC,sBAAsB;IA8D9B,OAAO,CAAC,iBAAiB;IAazB,OAAO,CAAC,iBAAiB;IAkCzB,OAAO,CAAC,mBAAmB;IAiK3B,OAAO,CAAC,eAAe;IA6BvB,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"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { EventType, Currency, defaultEndpoint, DEFAULT_FIELD_MAPPINGS, } from "../types";
|
|
2
2
|
import { AttributionStorageManager } from "../storage";
|
|
3
3
|
import { EventQueueManager, EventHttpClient } from "../queue";
|
|
4
|
-
import { generateId, getTimestamp, extractUTMParams, extractAdParams, detectDevice, getCurrentUrl, getReferrer, getUserAgent, getPageTitle, generateSessionId, isOnline, ConsoleLogger, addUTMToURL, shouldExcludeDomain, isExternalURL, filterUTMParams, cleanURL, getQueryString, getQueryParams, } from "../utils";
|
|
4
|
+
import { generateId, getTimestamp, extractUTMParams, extractAdParams, detectDevice, getCurrentUrl, getBestUTMSourceUrl, getReferrer, getUserAgent, getPageTitle, generateSessionId, isOnline, ConsoleLogger, addUTMToURL, shouldExcludeDomain, isExternalURL, filterUTMParams, cleanURL, getQueryString, getQueryParams, } from "../utils";
|
|
5
5
|
import { detectCookieDomain, normaliseDomain, } from "../utils/rootDomain";
|
|
6
6
|
export class AttributionSDK {
|
|
7
7
|
constructor(config) {
|
|
@@ -141,6 +141,10 @@ export class AttributionSDK {
|
|
|
141
141
|
querystring: getQueryString(currentUrl),
|
|
142
142
|
query_params: getQueryParams(currentUrl),
|
|
143
143
|
ip_address: ip_address,
|
|
144
|
+
// Raw User-Agent on EVERY event (not just page_view): the lossless
|
|
145
|
+
// device signal that lets the backend re-derive any future device
|
|
146
|
+
// classification. Rides in context.page, persisted per-event server-side.
|
|
147
|
+
user_agent: getUserAgent(),
|
|
144
148
|
};
|
|
145
149
|
const sessionContext = {
|
|
146
150
|
session_id: this.session?.sessionId,
|
|
@@ -598,9 +602,14 @@ export class AttributionSDK {
|
|
|
598
602
|
this.storage.storeSession(this.session);
|
|
599
603
|
this.logger.debug("Session initialized:", this.session);
|
|
600
604
|
}
|
|
601
|
-
// Extract and store UTM data from current URL
|
|
605
|
+
// Extract and store UTM data from current URL.
|
|
606
|
+
//
|
|
607
|
+
// Uses getBestUTMSourceUrl() (current href → module-load snapshot →
|
|
608
|
+
// Performance Navigation Timing entry) so attribution survives a host
|
|
609
|
+
// framework (e.g. Nuxt router) stripping UTM params via
|
|
610
|
+
// history.replaceState before our init() runs.
|
|
602
611
|
extractAndStoreUTMData() {
|
|
603
|
-
const currentUrl =
|
|
612
|
+
const currentUrl = getBestUTMSourceUrl();
|
|
604
613
|
const utmParams = extractUTMParams(currentUrl);
|
|
605
614
|
const adParams = extractAdParams(currentUrl);
|
|
606
615
|
this.logger.debug("Extracting UTM params from URL:", currentUrl);
|
|
@@ -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:()=>ft}),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",o=[t.PURCHASE,t.LOGIN,t.SIGNUP,t.FORM_SUBMIT,t.EMAIL_VERIFICATION,t.AUDIT_APPROVED],s={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 a(){return Math.floor(Date.now()/1e3)}const c=["adgroup_id","ad_group_id","adgroupid","adset_id","tt_adgroup_id","adgroup"],u=["ad_id","adid","creative_id","creative","tt_ad_id"],l=["gclid","gbraid","wbraid","fbclid","ttclid","msclkid","twclid","li_fat_id"],d=/^\d{7,15}$/;function g(t,e){const i=e.toLowerCase();for(const e of Object.keys(t))if(e.toLowerCase()===i){const i=t[e];for(const t of i)if(t&&""!==t.trim())return t.trim()}}function h(){const t="undefined"!=typeof navigator&&navigator.userAgent||"";return/iPad|Tablet|PlayBook|Silk/i.test(t)?"tablet":/Mobi|Android|iPhone|iPod/i.test(t)?"mobile":"desktop"}function m(){try{const t="__localStorage_test__";return localStorage.setItem(t,t),localStorage.removeItem(t),!0}catch{return!1}}class f{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 p(){return document.referrer||""}function _(){return window.location.href}function y(){return document.title||""}function w(){return`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}function S(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 k(t,e=["utm_source","utm_medium","utm_campaign"]){const i={};return e.forEach(e=>{t[e]&&(i[e]=t[e])}),i}function E(t){try{const e=t||window.location.href;return new URL(e).search}catch(t){return""}}function v(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{}}}const I="ga_anon_id",b="ga_anon_id",T="anon_";function A(){if("undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID)return T+crypto.randomUUID().replace(/-/g,"");let t="";for(let e=0;e<32;e++)t+=Math.floor(16*Math.random()).toString(16);return T+t}class D{constructor(t){this.logger=t}get(t){try{if(!m())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(!m())return void this.logger.warn("LocalStorage not supported");localStorage.setItem(t,JSON.stringify(e))}catch(t){this.logger.error("Error writing to localStorage:",t),this.handleQuotaExceeded()}}remove(t){try{m()&&localStorage.removeItem(t)}catch(t){this.logger.error("Error removing from localStorage:",t)}}clear(){try{m()&&localStorage.clear()}catch(t){this.logger.error("Error clearing localStorage:",t)}}handleQuotaExceeded(){try{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 P{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},o=r.add(n);o.onsuccess=()=>{this.logger.debug("Event added to IndexedDB queue"),e()},o.onerror=()=>{this.logger.error("Failed to add event to IndexedDB:",o.error),i(o.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,o=!1;t.forEach(s=>{const a=r.get(s);a.onsuccess=()=>{if(a.result){const s={...a.result,sent:!0},c=r.put(s);c.onsuccess=()=>{n++,n!==t.length||o||e()},c.onerror=()=>{o=!0,this.logger.error("Failed to mark event as sent:",c.error),i(c.error)}}else n++,n!==t.length||o||e()},a.onerror=()=>{o=!0,this.logger.error("Failed to get event for marking as sent:",a.error),i(a.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 U{constructor(t){this.UTM_STORAGE_KEY="attribution_utm_data",this.SESSION_STORAGE_KEY="attribution_session",this.SESSION_COOKIE_KEY="_getuai_session",this.ATTRIB_COOKIE_KEY="_getuai_attrib",this.USER_ID_KEY="getuai_user_id",this.PENDING_EVENTS_KEY="getuai_pending_events_v1",this.USER_TRAITS_KEY="getuai_user_traits",this.USER_ID_COOKIE_EXPIRES=365,this.ATTRIB_COOKIE_EXPIRES=30,this.SESSION_COOKIE_EXPIRES=1,this.cookieDomain=null,this.logger=t,this.localStorage=new D(t),this.indexedDB=new P(t)}setCookieDomain(t){this.cookieDomain=t,this.logger.debug(t?`🍪 Cookie domain set to ${t} (cross-subdomain sharing enabled)`:"🍪 Cookie domain not set — using host-only cookies")}setUserId(t){if(!t||""===t.trim())return void this.logger.warn("Cannot set empty user ID");const e=t.trim();try{this.setCookie(this.USER_ID_KEY,e,{days:this.USER_ID_COOKIE_EXPIRES,domain:this.cookieDomain}),this.logger.debug(`👤 User ID stored in cookie: ${e}`)}catch(t){this.logger.error("Failed to store user ID in cookie:",t)}try{"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(){let t=null;try{t=this.getCookie(this.USER_ID_KEY)}catch(t){this.logger.debug("Failed to get user ID from cookie:",t)}if(t){try{"undefined"!=typeof localStorage&&localStorage.getItem(this.USER_ID_KEY)!==t&&localStorage.setItem(this.USER_ID_KEY,t)}catch(t){}return t}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)}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)}}getAnonymousId(){try{const t=this.getCookie(I);if(t&&t.startsWith(T)){try{localStorage.setItem(b,t)}catch{}return t}}catch(t){this.logger.debug("anonymous_id cookie read failed",t)}try{const t="undefined"!=typeof localStorage?localStorage.getItem(b):null;if(t&&t.startsWith(T))return this.setAnonymousId(t),t}catch(t){this.logger.debug("anonymous_id localStorage read failed",t)}const t=A();return this.setAnonymousId(t),this.logger.info(`🆔 Generated new anonymous_id: ${t}`),t}setAnonymousId(t){if(t&&t.startsWith(T)){try{this.setCookie(I,t,{days:365,domain:this.cookieDomain})}catch(t){this.logger.error("anonymous_id cookie write failed",t)}try{"undefined"!=typeof localStorage&&localStorage.setItem(b,t)}catch(t){this.logger.error("anonymous_id localStorage write failed",t)}}else this.logger.warn(`Refusing to set malformed anonymous_id: ${t}`)}rotateAnonymousId(){const t=A();return this.setAnonymousId(t),this.logger.info(`🔄 Rotated anonymous_id: ${t}`),t}setCookie(t,e,i={}){try{const r="number"==typeof i?{days:i}:i,n=r.days??this.USER_ID_COOKIE_EXPIRES,o=new Date;o.setTime(o.getTime()+24*n*60*60*1e3);const s=r.secure??("undefined"!=typeof location&&"https:"===location.protocol),a=r.domain??this.cookieDomain,c=[`${t}=${encodeURIComponent(e)}`,`expires=${o.toUTCString()}`,"path=/","SameSite=Lax"];return a&&c.push(`domain=${a}`),s&&c.push("Secure"),document.cookie=c.join(";"),!0}catch(t){return this.logger.error("Failed to set cookie:",t),!1}}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=/;`,this.cookieDomain&&(document.cookie=`${t}=;expires=Thu, 01 Jan 1970 00:00:00 UTC;path=/;domain=${this.cookieDomain};`)}catch(t){this.logger.error("Failed to delete cookie:",t)}}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.writeAttribution(r),this.logger.debug("UTM data stored successfully:",{firstTouch:r.firstTouch,lastTouch:r.lastTouch,touchpointsCount:r.touchpoints.length,expiresAt:new Date(r.expiresAt).toISOString()})}catch(t){this.logger.error("Failed to store UTM data:",t)}}getUTMData(){const t=this.readAttributionFromCookie();if(t&&t.expiresAt&&t.expiresAt>Date.now())return t;t&&this.deleteCookie(this.ATTRIB_COOKIE_KEY);const e=this.localStorage.get(this.UTM_STORAGE_KEY);return e&&e.expiresAt&&e.expiresAt>Date.now()?e:(e&&this.localStorage.remove(this.UTM_STORAGE_KEY),null)}storeSession(t){try{const e=JSON.stringify(t);this.setCookie(this.SESSION_COOKIE_KEY,e,{days:this.SESSION_COOKIE_EXPIRES,domain:this.cookieDomain})}catch(t){this.logger.debug("Failed to store session in cookie:",t)}this.localStorage.set(this.SESSION_STORAGE_KEY,t)}getSession(){try{const t=this.getCookie(this.SESSION_COOKIE_KEY);if(t)return JSON.parse(t)}catch(t){this.logger.debug("Failed to parse session cookie:",t)}return this.localStorage.get(this.SESSION_STORAGE_KEY)}migrateLegacyStorage(){try{if(!this.getCookie(this.SESSION_COOKIE_KEY)){const t=this.localStorage.get(this.SESSION_STORAGE_KEY);t&&(this.setCookie(this.SESSION_COOKIE_KEY,JSON.stringify(t),{days:this.SESSION_COOKIE_EXPIRES,domain:this.cookieDomain}),this.logger.debug("↗️ Migrated legacy session to cookie"))}}catch(t){this.logger.debug("Session migration skipped:",t)}try{if(!this.getCookie(this.ATTRIB_COOKIE_KEY)){const t=this.localStorage.get(this.UTM_STORAGE_KEY);t&&t.expiresAt&&t.expiresAt>Date.now()&&(this.writeAttribution(t),this.logger.debug("↗️ Migrated legacy attribution data to cookie"))}}catch(t){this.logger.debug("Attribution migration skipped:",t)}try{if(this.cookieDomain){const t=this.getCookie(this.USER_ID_KEY),e="undefined"!=typeof localStorage?localStorage.getItem(this.USER_ID_KEY):null;!t&&e&&(this.setCookie(this.USER_ID_KEY,e,{days:this.USER_ID_COOKIE_EXPIRES,domain:this.cookieDomain}),this.logger.debug("↗️ Migrated legacy user ID to cross-subdomain cookie"))}}catch(t){this.logger.debug("User ID migration skipped:",t)}}writeAttribution(t){this.localStorage.set(this.UTM_STORAGE_KEY,t);const e=Math.max(0,t.expiresAt-Date.now()),i=Math.max(1,Math.ceil(e/864e5));let r=encodeURIComponent(JSON.stringify(t));if(r.length>3800){const e={...t,touchpoints:(t.touchpoints||[]).slice(-20)};if(r=encodeURIComponent(JSON.stringify(e)),r.length>3800){const t={...e,touchpoints:[]};r=encodeURIComponent(JSON.stringify(t))}return this.logger.debug("Attribution cookie payload trimmed to fit size limit"),void this.setCookie(this.ATTRIB_COOKIE_KEY,decodeURIComponent(r),{days:i,domain:this.cookieDomain})}this.setCookie(this.ATTRIB_COOKIE_KEY,JSON.stringify(t),{days:i,domain:this.cookieDomain})}readAttributionFromCookie(){try{const t=this.getCookie(this.ATTRIB_COOKIE_KEY);return t?JSON.parse(t):null}catch(t){return this.logger.debug("Failed to parse attribution cookie:",t),null}}async queueEvent(t){try{await this.indexedDB.addEvent(t)}catch(t){throw this.logger.error("Failed to queue event:",t),t}}async getUnsentEvents(t=100){return await this.indexedDB.getUnsentEvents(t)}async markEventsAsSent(t){await this.indexedDB.markEventsAsSent(t)}async getQueueSize(){return await this.indexedDB.getQueueSize()}async cleanupOldEvents(){await this.indexedDB.cleanupOldEvents()}async clearQueue(){await this.indexedDB.clear()}cleanupExpiredData(){this.getUTMData()}setUserTraits(t){try{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 C="0.5.0";class O{constructor(t,e,i,r=100,n=2e3,o=3,s=1e3,a){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=o,this.retryDelay=s,this.sendEvents=a,this.debouncedProcess=function(t){let e;return(...i)=>{clearTimeout(e),e=setTimeout(()=>t(...i),100)}}(this.process.bind(this))}add(t){if(o.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,anonymous_id:t.anonymous_id,tracking_user_id:t.tracking_user_id,utm_source:t.utm_source||null,utm_medium:t.utm_medium||null,utm_campaign:t.utm_campaign||null,utm_term:t.utm_term||null,utm_content:t.utm_content||null,revenue:t.revenue||null,currency:t.currency||null,event_data:t.event_data||null,context:t.context||null,timestamp:t.timestamp||a(),custom_event_name:t.custom_event_name||void 0})),sdk_version:C};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 o=i*Math.pow(2,n);await new Promise(t=>setTimeout(t,o))}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,anonymous_id:t.anonymous_id,tracking_user_id:t.tracking_user_id,utm_source:t.utm_source||null,utm_medium:t.utm_medium||null,utm_campaign:t.utm_campaign||null,utm_term:t.utm_term||null,utm_content:t.utm_content||null,revenue:t.revenue||null,currency:t.currency||null,event_data:t.event_data||null,context:t.context||null,timestamp:t.timestamp||a(),custom_event_name:t.custom_event_name||void 0})),sdk_version:C},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,anonymous_id:t.anonymous_id,tracking_user_id:t.tracking_user_id,utm_source:t.utm_source||null,utm_medium:t.utm_medium||null,utm_campaign:t.utm_campaign||null,utm_term:t.utm_term||null,utm_content:t.utm_content||null,revenue:t.revenue||null,currency:t.currency||null,event_data:t.event_data||null,context:t.context||null,timestamp:t.timestamp||a(),custom_event_name:t.custom_event_name||void 0})),sdk_version:C},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}}}const R="__getuai_probe";function x(t){try{document.cookie=`${R}=1;domain=${t};path=/;SameSite=Lax`;const e=document.cookie.split(";").some(t=>t.trim().startsWith(`${R}=`));return e&&(document.cookie=`${R}=;domain=${t};path=/;expires=Thu, 01 Jan 1970 00:00:00 GMT`),e}catch{return!1}}class N{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 f(this.config.enableDebug),this.storage=new U(this.logger),this.httpClient=new K(this.logger,this.config.apiKey,this.config.apiEndpoint||n,this.config.maxRetries,this.config.retryDelay),this.queue=new O(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");const t=function(t){if(!t)return null;const e=t.trim();return e?e.startsWith(".")?e:"."+e:null}(this.config.domain)??function(){if(!function(){try{return"undefined"!=typeof document&&"string"==typeof document.cookie}catch{return!1}}())return null;const t="undefined"!=typeof location&&location.hostname||"";if(!t)return null;if("localhost"===t)return null;if(function(t){return!!/^\d+\.\d+\.\d+\.\d+$/.test(t)||!!t.includes(":")}(t))return null;const e=t.split(".").filter(Boolean);if(e.length<2)return null;for(let t=e.length-2;t>=0;t--){const i="."+e.slice(t).join(".");if(x(i))return i}return null}();this.storage.setCookieDomain(t),this.storage.init().catch(t=>{this.logger.warn("Storage initialization failed (IndexedDB may be unavailable), continuing with basic features:",t)});try{this.storage.migrateLegacyStorage()}catch(t){this.logger.debug("Legacy storage migration skipped:",t)}this.initializeUserId(),this.initializeSession(),this.extractAndStoreUTMData(),this.config.autoTrack&&this.setupAutoTracking(),this.setupNetworkHandlers(),this.setupVisibilityHandlers(),this.setupBeforeUnloadHandler(),this.initialized=!0,this.logger.info("🚀 GetuAI Attribution SDK initialized successfully"),this.logger.info("📄 Auto track page view = "+this.config.autoTrackPageView),this.retryPendingEvents().catch(t=>{this.logger.warn("⚠️ Pending events retry failed",t)}),this.config.autoTrackPageView&&(this.logger.info("📄 Auto track page view enabled (including SPA route tracking)"),this.lastTrackedPath=this.getCurrentPath(),this.setupSPATracking(),this.initialPageViewTriggered||(this.initialPageViewTriggered=!0,Promise.resolve().then(()=>this.trackPageView()).then(()=>this.queue.process()).then(()=>{this.logger.info("✅ Auto track page view completed")}).catch(t=>this.logger.error("❌ Auto track page view failed:",t))))}catch(t){throw this.logger.error("Failed to initialize SDK:",t),t}}async trackEvent(i,r,n,o,s=e.USD,c){if(this.initialized)try{const e=_(),u=this.cachedPublicIP;this.ensurePublicIPFetched();const l={domain:"undefined"!=typeof window?window.location.hostname:null,path:"undefined"!=typeof window?window.location.pathname:null,title:y(),referrer:p(),url:e.split("?")[0],querystring:E(e),query_params:v(e),ip_address:u},d={session_id:this.session?.sessionId,start_time:this.session?.startTime,last_activity:this.session?.lastActivity,page_views:this.session?.pageViews},g=this.storage.getAnonymousId(),m=n||this.getUserId(),f={event_id:"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)}),event_type:i,anonymous_id:g,tracking_user_id:m||void 0,timestamp:a(),event_data:r,context:{page:l,session:d},revenue:o,currency:s,...i===t.CUSTOM&&c?{custom_event_name:c}:{},...this.getUTMParams(),device:h(),...this.getAdParams()};this.logger.debug(`Tracking event: ${i}`,f),this.queue.add(f)}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,o,s=e.USD){i&&""!==i.trim()?await this.trackEvent(t.CUSTOM,r,n,o,s,i.trim()):this.logger.error("trackCustomEvent requires a non-empty customEventName")}async trackPageView(e,i){const r=_(),n=r.split("?")[0],o=Date.now(),s=this.config.pageViewDebounceInterval||5e3,a=this.pageViewTrackTimes.get(n);if(a&&o-a<s)return void this.logger.debug(`Page view debounced: ${n} (last tracked ${o-a}ms ago)`);const c={url:r,title:y(),referrer:p(),user_agent:navigator.userAgent||"",...e};await this.trackEvent(t.PAGE_VIEW,c,i),this.pageViewTrackTimes.set(n,o),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,o){await this.trackEvent(t.PURCHASE,o,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?S(t,k(e.lastTouch,this.config.crossDomainUTMParams)):t}getCurrentUTMParams(){const t=this.getAttributionData();return t?k(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}getAdParams(){const t=this.getAttributionData();if(!t)return{};const e=t.lastTouch,i=t=>t&&"string"==typeof t&&""!==t.trim()?t:null;return{adgroup_id:i(e.adgroup_id),ad_id:i(e.ad_id),adgroup_id_source:i(e.adgroup_id_source),ad_id_source:i(e.ad_id_source),click_id:i(e.click_id),click_id_source:i(e.click_id_source)}}initializeUserId(){if(this.config.userId)this.setUserId(this.config.userId),this.logger.info(`👤 User ID initialized from config: ${this.config.userId}`);else{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){if(!t||""===t.trim())return void this.logger.warn("Cannot set empty user ID");const e=t.trim(),i=this.storage.getUserId();if(i!==e){if(i&&i!==e&&(this.logger.info(`👥 User changed (${i} → ${e}) — rotating anonymous_id + session`),this.storage.rotateAnonymousId()),this.storage.setUserId(e),this.session){const t=this.session.userId;t&&t!==e?(this.logger.info(`🔄 Session previously owned by ${t} — rotating session for ${e}`),this.rotateSession(e)):t!==e&&(this.session={...this.session,userId:e},this.storage.storeSession(this.session))}this.logger.info(`👤 User ID set: ${e}`)}}rotateSession(t){const e=Date.now();this.session={sessionId:w(),startTime:e,lastActivity:e,pageViews:0,userId:t},this.storage.storeSession(this.session)}getUserId(){return this.storage.getUserId()}getAnonymousId(){return this.storage.getAnonymousId()}removeUserId(){this.storage.removeUserId(),this.logger.info("👤 User ID removed")}async identify(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(),i=this.storage.getUserId()??void 0,r=t&&e-t.lastActivity<this.config.sessionTimeout,n=!(!t?.userId||!i||t.userId===i);r&&!n?this.session={...t,lastActivity:e,userId:t.userId??i}:(n&&this.logger.info(`🔄 Session owner changed (${t?.userId} → ${i}) — starting new session`),this.session={sessionId:w(),startTime:e,lastActivity:e,pageViews:0,userId:i}),this.storage.storeSession(this.session),this.logger.debug("Session initialized:",this.session)}extractAndStoreUTMData(){const t=_(),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),i=function(t){const e=function(t){const e={};try{const i=new URL(t),r=new Set;i.searchParams.forEach((t,e)=>{r.add(e)}),r.forEach(t=>{const r=i.searchParams.getAll(t);e[t]=r.filter(t=>null!=t&&""!==t)})}catch(t){}return e}(t),i={};for(const t of c){const r=g(e,t);if(void 0!==r){/^\{.+\}$/.test(r)?(i.adgroup_id=r,i.adgroup_id_source="valuetrack"):(i.adgroup_id=r,i.adgroup_id_source="explicit");break}}if(!i.adgroup_id){const t=g(e,"utm_term")?e[Object.keys(e).find(t=>"utm_term"===t.toLowerCase())]:[];for(const e of t){const t=(e||"").trim();if(d.test(t)){i.adgroup_id=t,i.adgroup_id_source="utm_term_numeric";break}}}for(const t of u){const r=g(e,t);if(void 0!==r){/^\{.+\}$/.test(r)?(i.ad_id=r,i.ad_id_source="valuetrack"):(i.ad_id=r,i.ad_id_source="explicit");break}}if(!i.ad_id){const t=g(e,"utm_content")?e[Object.keys(e).find(t=>"utm_content"===t.toLowerCase())]:[];for(const e of t){const t=(e||"").trim();if(d.test(t)){i.ad_id=t,i.ad_id_source="utm_content_numeric";break}}}for(const t of l){const r=g(e,t);if(r&&""!==r.trim()){i.click_id=r.trim(),i.click_id_source=t;break}}return i}(t);if(this.logger.debug("Extracting UTM params from URL:",t),this.logger.debug("Found UTM params:",e),this.logger.debug("Found ad params:",i),0===Object.keys(e).length&&!i.adgroup_id&&!i.ad_id&&!i.click_id)return void this.logger.debug("No UTM, ad, or click parameters found in URL");const r={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||"",adgroup_id:i.adgroup_id||"",ad_id:i.ad_id||"",adgroup_id_source:i.adgroup_id_source||"",ad_id_source:i.ad_id_source||"",click_id:i.click_id||"",click_id_source:i.click_id_source||"",timestamp:Date.now()},n=this.getAttributionData(),o={firstTouch:n?.firstTouch||r,lastTouch:r,touchpoints:n?.touchpoints||[],expiresAt:Date.now()+2592e6};n&&n.lastTouch.utm_source===r.utm_source&&n.lastTouch.utm_campaign===r.utm_campaign||o.touchpoints.push(r),this.storage.storeUTMData(o),this.logger.info("UTM data extracted and stored successfully:",r),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(),o=e.type?.toLowerCase();if("button"===i||"submit"===o||"reset"===o)continue;const s=this.getFormFieldKey(e,t);s&&(n.has(s)||n.set(s,[]),n.get(s).push(e))}n.forEach((t,i)=>{const r=t.some(t=>"radio"===t.type),n=t.some(t=>"checkbox"===t.type),o=t.some(t=>"file"===t.type),s=t.some(t=>"SELECT"===t.tagName&&t.multiple),a=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(s){const r=t.find(t=>"SELECT"===t.tagName&&t.multiple);if(r){const t=Array.from(r.selectedOptions).map(t=>t.value);return void(Object.prototype.hasOwnProperty.call(e,i)||(e[i]=t))}}if(o){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(a)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(s))if(!e[i])for(const n of r||[]){const r=n.toLowerCase();for(const[n,o]of Object.entries(t))if((n.toLowerCase()===r||n.toLowerCase().includes(r))&&o&&"string"==typeof o&&o.trim()){e[i]=o.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=k(r.lastTouch,this.config.crossDomainUTMParams);if(0===Object.keys(n).length)return void this.logger.debug("No UTM parameters to pass");const o=S(i,n);o!==i&&(t.href=o,this.logger.debug("UTM parameters added to external link:",{original:i,enhanced:o,utmParams:n}),this.logger.debug("Cross-domain UTM passed:",{link_url:o,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 F=null;async function M(t){if(F)return console.warn("GetuAI SDK: Already initialized"),F;try{if(F=new N(t),await F.init(),t.enableDebug&&(window.GetuAISDK=F),console.log("GetuAI Attribution SDK initialized successfully"),"undefined"!=typeof window){const t=new CustomEvent("getuaiSDKReady",{detail:{sdk:F}});window.dispatchEvent(t)}return F}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 L(){return F}function z(){return new Promise((t,e)=>{if(F)return void t(F);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 $(t,i,r,n,o=e.USD){const s=L();s?await s.trackEvent(t,i,r,n,o):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function V(t,e){const i=L();i?await i.trackPageView(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function G(t,i,r=e.USD,n){const o=L();o?await o.trackPurchase(t,i,r,n):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function B(t,e){const i=L();i?await i.trackLogin(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function q(t,e){const i=L();i?await i.trackSignup(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function Y(t,e){const i=L();i?await i.trackFormSubmit(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function j(t,e){const i=L();i?await i.trackVideoPlay(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function H(t,e){const i=L();i?await i.trackEmailVerification(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function J(t,e){const i=L();i?await i.trackAuditApproved(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function W(t){const e=L();e?await e.trackPurchaseAuto(t):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function X(t){const e=L();e?await e.trackLoginAuto(t):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function Q(t){const e=L();e?await e.trackSignupAuto(t):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function Z(t){const e=L();e?await e.trackEmailVerificationAuto(t):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function tt(t,i,r,n,o=e.USD){const s=L();s?await s.trackCustomEvent(t,i,r,n,o):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function et(t,e){const i=L();i?await i.trackProductView(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function it(t,e){const i=L();i?await i.trackAddToCart(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function rt(t,e){const i=L();i?await i.trackPageClick(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function nt(t,e,i){const r=L();r?await r.trackButtonClick(t,e,i):console.warn("GetuAI SDK: Not initialized. Call init() first.")}function ot(){const t=L();return t?t.getAttributionData():null}async function st(){const t=L();t?await t.flush():console.warn("GetuAI SDK: Not initialized. Call init() first.")}function at(){const t=L();return t?t.getStatus():null}function ct(t){const e=L();return e?e.addUTMToURL(t):(console.warn("GetuAI SDK: Not initialized. Call init() first."),t)}function ut(){const t=L();return t?t.getCurrentUTMParams():{}}function lt(t){const e=L();e?e.setUserId(t):console.warn("GetuAI SDK: Not initialized. Call init() first.")}function dt(){const t=L();return t?t.getUserId():(console.warn("GetuAI SDK: Not initialized. Call init() first."),null)}function gt(){const t=L();t?t.removeUserId():console.warn("GetuAI SDK: Not initialized. Call init() first.")}function ht(){F&&(F.destroy(),F=null,console.log("GetuAI SDK destroyed"))}class mt extends N{static async init(t){return await M(t)}static async trackEvent(t,i,r,n,o=e.USD){return await $(t,i,r,n,o)}static async trackPageView(t,e){return await V(t,e)}static async trackPurchase(t,i,r=e.USD,n){return await G(t,i,r,n)}static async trackLogin(t,e){return await B(t,e)}static async trackSignup(t,e){return await q(t,e)}static async trackFormSubmit(t,e){return await Y(t,e)}static async trackVideoPlay(t,e){return await j(t,e)}static async trackEmailVerification(t,e){return await H(t,e)}static async trackPurchaseAuto(t){return await W(t)}static async trackLoginAuto(t){return await X(t)}static async trackSignupAuto(t){return await Q(t)}static async trackEmailVerificationAuto(t){return await Z(t)}static async trackCustomEvent(t,i,r,n,o=e.USD){return await tt(t,i,r,n,o)}static async trackProductView(t,e){return await et(t,e)}static async trackAddToCart(t,e){return await it(t,e)}static async trackPageClick(t,e){return await rt(t,e)}static async trackButtonClick(t,e,i){return await nt(t,e,i)}static getAttributionData(){return ot()}static async flush(){return await st()}static getStatus(){return at()}static addUTMToURL(t){return ct(t)}static getCurrentUTMParams(){return ut()}static setUserId(t){lt(t)}static getUserId(){return dt()}static removeUserId(){gt()}static destroy(){ht()}static getSDK(){return L()}static waitForSDK(){return z()}}"undefined"!=typeof document&&function(){if(F)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?M({apiKey:e,apiEndpoint:t.getAttribute("data-api-endpoint")||n,enableDebug:"true"===t.getAttribute("data-debug"),autoTrack:"true"===t.getAttribute("data-auto-track"),autoTrackPageView:"true"===t.getAttribute("data-auto-track-page-view"),autoCleanUTM:"false"!==t.getAttribute("data-auto-clean-utm"),batchSize:parseInt(t.getAttribute("data-batch-size")||"100"),batchInterval:parseInt(t.getAttribute("data-batch-interval")||"2000"),userId:t.getAttribute("data-user-id")||void 0,domain:t.getAttribute("data-domain")||void 0}):console.warn("GetuAI SDK: No API key provided. Please add data-api-key attribute to script tag.")}(),"undefined"!=typeof window&&(window.getuaiSDK={init:M,getSDK:L,waitForSDK:z,trackEvent:$,trackPageView:V,trackPageClick:rt,trackButtonClick:nt,trackPurchase:G,trackLogin:B,trackSignup:q,trackFormSubmit:Y,trackVideoPlay:j,trackEmailVerification:H,trackAuditApproved:J,trackCustomEvent:tt,trackProductView:et,trackAddToCart:it,trackPurchaseAuto:W,trackLoginAuto:X,trackSignupAuto:Q,trackEmailVerificationAuto:Z,getAttributionData:ot,flush:st,getStatus:at,addUTMToURL:ct,getCurrentUTMParams:ut,setUserId:lt,getUserId:dt,removeUserId:gt,destroy:ht,EventType:t,Currency:e,AttributionSDK:mt},window.init=M,window.waitForSDK=z,window.trackEvent=$,window.trackPageView=V,window.trackPageClick=rt,window.trackButtonClick=nt,window.trackPurchase=G,window.trackLogin=B,window.trackSignup=q,window.trackFormSubmit=Y,window.trackVideoPlay=j,window.trackEmailVerification=H,window.trackProductView=et,window.trackAddToCart=it,window.trackPurchaseAuto=W,window.trackLoginAuto=X,window.trackSignupAuto=Q,window.trackEmailVerificationAuto=Z,window.getAttributionData=ot,window.flush=st,window.getStatus=at,window.addUTMToURL=ct,window.getCurrentUTMParams=ut,window.setUserId=lt,window.getUserId=dt,window.removeUserId=gt,window.destroy=ht,window.AttributionSDK=mt);const ft={init:M,getSDK:L,waitForSDK:z,trackEvent:$,trackPageView:V,trackPageClick:rt,trackButtonClick:nt,trackPurchase:G,trackLogin:B,trackSignup:q,trackFormSubmit:Y,trackVideoPlay:j,trackEmailVerification:H,trackAuditApproved:J,trackCustomEvent:tt,trackProductView:et,trackAddToCart:it,trackPurchaseAuto:W,trackLoginAuto:X,trackSignupAuto:Q,trackEmailVerificationAuto:Z,getAttributionData:ot,flush:st,getStatus:at,addUTMToURL:ct,getCurrentUTMParams:ut,setUserId:lt,getUserId:dt,removeUserId:gt,destroy:ht,EventType:t,Currency:e,AttributionSDK:mt};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:()=>St}),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",o=[t.PURCHASE,t.LOGIN,t.SIGNUP,t.FORM_SUBMIT,t.EMAIL_VERIFICATION,t.AUDIT_APPROVED],s={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 a(){return Math.floor(Date.now()/1e3)}const c=["adgroup_id","ad_group_id","adgroupid","adset_id","tt_adgroup_id","adgroup"],u=["ad_id","adid","creative_id","creative","tt_ad_id"],l=["gclid","gbraid","wbraid","fbclid","ttclid","msclkid","twclid","li_fat_id"],d=/^\d{7,15}$/;function g(t,e){const i=e.toLowerCase();for(const e of Object.keys(t))if(e.toLowerCase()===i){const i=t[e];for(const t of i)if(t&&""!==t.trim())return t.trim()}}function h(t){const e=function(t){const e={};try{const i=new URL(t),r=new Set;i.searchParams.forEach((t,e)=>{r.add(e)}),r.forEach(t=>{const r=i.searchParams.getAll(t);e[t]=r.filter(t=>null!=t&&""!==t)})}catch(t){}return e}(t),i={};for(const t of c){const r=g(e,t);if(void 0!==r){/^\{.+\}$/.test(r)?(i.adgroup_id=r,i.adgroup_id_source="valuetrack"):(i.adgroup_id=r,i.adgroup_id_source="explicit");break}}if(!i.adgroup_id){const t=g(e,"utm_term")?e[Object.keys(e).find(t=>"utm_term"===t.toLowerCase())]:[];for(const e of t){const t=(e||"").trim();if(d.test(t)){i.adgroup_id=t,i.adgroup_id_source="utm_term_numeric";break}}}for(const t of u){const r=g(e,t);if(void 0!==r){/^\{.+\}$/.test(r)?(i.ad_id=r,i.ad_id_source="valuetrack"):(i.ad_id=r,i.ad_id_source="explicit");break}}if(!i.ad_id){const t=g(e,"utm_content")?e[Object.keys(e).find(t=>"utm_content"===t.toLowerCase())]:[];for(const e of t){const t=(e||"").trim();if(d.test(t)){i.ad_id=t,i.ad_id_source="utm_content_numeric";break}}}for(const t of l){const r=g(e,t);if(r&&""!==r.trim()){i.click_id=r.trim(),i.click_id_source=t;break}}return i}function m(){const t="undefined"!=typeof navigator&&navigator.userAgent||"";return/iPad|Tablet|PlayBook|Silk/i.test(t)?"tablet":/Mobi|Android|iPhone|iPod/i.test(t)?"mobile":"desktop"}function _(){try{const t="__localStorage_test__";return localStorage.setItem(t,t),localStorage.removeItem(t),!0}catch{return!1}}class f{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 p(){return navigator.userAgent||""}function y(){return document.referrer||""}function w(){return window.location.href}function k(){if("undefined"==typeof window)return"";try{const t=window.location;return t&&"string"==typeof t.href?t.href:""}catch{return""}}let S=k()||null;const v=["utm_source","utm_medium","utm_campaign","utm_term","utm_content"];function E(t){if(!t)return!1;try{const e=new URL(t);if(v.some(t=>{const i=e.searchParams.get(t);return null!==i&&""!==i.trim()}))return!0;const i=h(t);return Boolean(i.adgroup_id||i.ad_id||i.click_id)}catch{return!1}}function I(){return document.title||""}function b(){return`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}function T(t,e){try{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 A(t,e=["utm_source","utm_medium","utm_campaign"]){const i={};return e.forEach(e=>{t[e]&&(i[e]=t[e])}),i}function D(t){try{const e=t||window.location.href;return new URL(e).search}catch(t){return""}}function P(t){try{const e=t||window.location.href,i=new URL(e),r={};return i.searchParams.forEach((t,e)=>{r[e]=t}),r}catch(t){return{}}}const U="ga_anon_id",C="ga_anon_id",O="anon_";function K(){if("undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID)return O+crypto.randomUUID().replace(/-/g,"");let t="";for(let e=0;e<32;e++)t+=Math.floor(16*Math.random()).toString(16);return O+t}class R{constructor(t){this.logger=t}get(t){try{if(!_())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(!_())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{_()&&localStorage.removeItem(t)}catch(t){this.logger.error("Error removing from localStorage:",t)}}clear(){try{_()&&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 x{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},o=r.add(n);o.onsuccess=()=>{this.logger.debug("Event added to IndexedDB queue"),e()},o.onerror=()=>{this.logger.error("Failed to add event to IndexedDB:",o.error),i(o.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,o=!1;t.forEach(s=>{const a=r.get(s);a.onsuccess=()=>{if(a.result){const s={...a.result,sent:!0},c=r.put(s);c.onsuccess=()=>{n++,n!==t.length||o||e()},c.onerror=()=>{o=!0,this.logger.error("Failed to mark event as sent:",c.error),i(c.error)}}else n++,n!==t.length||o||e()},a.onerror=()=>{o=!0,this.logger.error("Failed to get event for marking as sent:",a.error),i(a.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 N{constructor(t){this.UTM_STORAGE_KEY="attribution_utm_data",this.SESSION_STORAGE_KEY="attribution_session",this.SESSION_COOKIE_KEY="_getuai_session",this.ATTRIB_COOKIE_KEY="_getuai_attrib",this.USER_ID_KEY="getuai_user_id",this.PENDING_EVENTS_KEY="getuai_pending_events_v1",this.USER_TRAITS_KEY="getuai_user_traits",this.USER_ID_COOKIE_EXPIRES=365,this.ATTRIB_COOKIE_EXPIRES=30,this.SESSION_COOKIE_EXPIRES=1,this.cookieDomain=null,this.logger=t,this.localStorage=new R(t),this.indexedDB=new x(t)}setCookieDomain(t){this.cookieDomain=t,this.logger.debug(t?`🍪 Cookie domain set to ${t} (cross-subdomain sharing enabled)`:"🍪 Cookie domain not set — using host-only cookies")}setUserId(t){if(!t||""===t.trim())return void this.logger.warn("Cannot set empty user ID");const e=t.trim();try{this.setCookie(this.USER_ID_KEY,e,{days:this.USER_ID_COOKIE_EXPIRES,domain:this.cookieDomain}),this.logger.debug(`👤 User ID stored in cookie: ${e}`)}catch(t){this.logger.error("Failed to store user ID in cookie:",t)}try{"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(){let t=null;try{t=this.getCookie(this.USER_ID_KEY)}catch(t){this.logger.debug("Failed to get user ID from cookie:",t)}if(t){try{"undefined"!=typeof localStorage&&localStorage.getItem(this.USER_ID_KEY)!==t&&localStorage.setItem(this.USER_ID_KEY,t)}catch(t){}return t}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)}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)}}getAnonymousId(){try{const t=this.getCookie(U);if(t&&t.startsWith(O)){try{localStorage.setItem(C,t)}catch{}return t}}catch(t){this.logger.debug("anonymous_id cookie read failed",t)}try{const t="undefined"!=typeof localStorage?localStorage.getItem(C):null;if(t&&t.startsWith(O))return this.setAnonymousId(t),t}catch(t){this.logger.debug("anonymous_id localStorage read failed",t)}const t=K();return this.setAnonymousId(t),this.logger.info(`🆔 Generated new anonymous_id: ${t}`),t}setAnonymousId(t){if(t&&t.startsWith(O)){try{this.setCookie(U,t,{days:365,domain:this.cookieDomain})}catch(t){this.logger.error("anonymous_id cookie write failed",t)}try{"undefined"!=typeof localStorage&&localStorage.setItem(C,t)}catch(t){this.logger.error("anonymous_id localStorage write failed",t)}}else this.logger.warn(`Refusing to set malformed anonymous_id: ${t}`)}rotateAnonymousId(){const t=K();return this.setAnonymousId(t),this.logger.info(`🔄 Rotated anonymous_id: ${t}`),t}setCookie(t,e,i={}){try{const r="number"==typeof i?{days:i}:i,n=r.days??this.USER_ID_COOKIE_EXPIRES,o=new Date;o.setTime(o.getTime()+24*n*60*60*1e3);const s=r.secure??("undefined"!=typeof location&&"https:"===location.protocol),a=r.domain??this.cookieDomain,c=[`${t}=${encodeURIComponent(e)}`,`expires=${o.toUTCString()}`,"path=/","SameSite=Lax"];return a&&c.push(`domain=${a}`),s&&c.push("Secure"),document.cookie=c.join(";"),!0}catch(t){return this.logger.error("Failed to set cookie:",t),!1}}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=/;`,this.cookieDomain&&(document.cookie=`${t}=;expires=Thu, 01 Jan 1970 00:00:00 UTC;path=/;domain=${this.cookieDomain};`)}catch(t){this.logger.error("Failed to delete cookie:",t)}}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.writeAttribution(r),this.logger.debug("UTM data stored successfully:",{firstTouch:r.firstTouch,lastTouch:r.lastTouch,touchpointsCount:r.touchpoints.length,expiresAt:new Date(r.expiresAt).toISOString()})}catch(t){this.logger.error("Failed to store UTM data:",t)}}getUTMData(){const t=this.readAttributionFromCookie();if(t&&t.expiresAt&&t.expiresAt>Date.now())return t;t&&this.deleteCookie(this.ATTRIB_COOKIE_KEY);const e=this.localStorage.get(this.UTM_STORAGE_KEY);return e&&e.expiresAt&&e.expiresAt>Date.now()?e:(e&&this.localStorage.remove(this.UTM_STORAGE_KEY),null)}storeSession(t){try{const e=JSON.stringify(t);this.setCookie(this.SESSION_COOKIE_KEY,e,{days:this.SESSION_COOKIE_EXPIRES,domain:this.cookieDomain})}catch(t){this.logger.debug("Failed to store session in cookie:",t)}this.localStorage.set(this.SESSION_STORAGE_KEY,t)}getSession(){try{const t=this.getCookie(this.SESSION_COOKIE_KEY);if(t)return JSON.parse(t)}catch(t){this.logger.debug("Failed to parse session cookie:",t)}return this.localStorage.get(this.SESSION_STORAGE_KEY)}migrateLegacyStorage(){try{if(!this.getCookie(this.SESSION_COOKIE_KEY)){const t=this.localStorage.get(this.SESSION_STORAGE_KEY);t&&(this.setCookie(this.SESSION_COOKIE_KEY,JSON.stringify(t),{days:this.SESSION_COOKIE_EXPIRES,domain:this.cookieDomain}),this.logger.debug("↗️ Migrated legacy session to cookie"))}}catch(t){this.logger.debug("Session migration skipped:",t)}try{if(!this.getCookie(this.ATTRIB_COOKIE_KEY)){const t=this.localStorage.get(this.UTM_STORAGE_KEY);t&&t.expiresAt&&t.expiresAt>Date.now()&&(this.writeAttribution(t),this.logger.debug("↗️ Migrated legacy attribution data to cookie"))}}catch(t){this.logger.debug("Attribution migration skipped:",t)}try{if(this.cookieDomain){const t=this.getCookie(this.USER_ID_KEY),e="undefined"!=typeof localStorage?localStorage.getItem(this.USER_ID_KEY):null;!t&&e&&(this.setCookie(this.USER_ID_KEY,e,{days:this.USER_ID_COOKIE_EXPIRES,domain:this.cookieDomain}),this.logger.debug("↗️ Migrated legacy user ID to cross-subdomain cookie"))}}catch(t){this.logger.debug("User ID migration skipped:",t)}}writeAttribution(t){this.localStorage.set(this.UTM_STORAGE_KEY,t);const e=Math.max(0,t.expiresAt-Date.now()),i=Math.max(1,Math.ceil(e/864e5));let r=encodeURIComponent(JSON.stringify(t));if(r.length>3800){const e={...t,touchpoints:(t.touchpoints||[]).slice(-20)};if(r=encodeURIComponent(JSON.stringify(e)),r.length>3800){const t={...e,touchpoints:[]};r=encodeURIComponent(JSON.stringify(t))}return this.logger.debug("Attribution cookie payload trimmed to fit size limit"),void this.setCookie(this.ATTRIB_COOKIE_KEY,decodeURIComponent(r),{days:i,domain:this.cookieDomain})}this.setCookie(this.ATTRIB_COOKIE_KEY,JSON.stringify(t),{days:i,domain:this.cookieDomain})}readAttributionFromCookie(){try{const t=this.getCookie(this.ATTRIB_COOKIE_KEY);return t?JSON.parse(t):null}catch(t){return this.logger.debug("Failed to parse attribution cookie:",t),null}}async queueEvent(t){try{await this.indexedDB.addEvent(t)}catch(t){throw this.logger.error("Failed to queue event:",t),t}}async getUnsentEvents(t=100){return await this.indexedDB.getUnsentEvents(t)}async markEventsAsSent(t){await this.indexedDB.markEventsAsSent(t)}async getQueueSize(){return await this.indexedDB.getQueueSize()}async cleanupOldEvents(){await this.indexedDB.cleanupOldEvents()}async clearQueue(){await this.indexedDB.clear()}cleanupExpiredData(){this.getUTMData()}setUserTraits(t){try{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 F="0.5.2";class L{constructor(t,e,i,r=100,n=2e3,o=3,s=1e3,a){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=o,this.retryDelay=s,this.sendEvents=a,this.debouncedProcess=function(t){let e;return(...i)=>{clearTimeout(e),e=setTimeout(()=>t(...i),100)}}(this.process.bind(this))}add(t){if(o.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 M{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,anonymous_id:t.anonymous_id,tracking_user_id:t.tracking_user_id,utm_source:t.utm_source||null,utm_medium:t.utm_medium||null,utm_campaign:t.utm_campaign||null,utm_term:t.utm_term||null,utm_content:t.utm_content||null,revenue:t.revenue||null,currency:t.currency||null,event_data:t.event_data||null,context:t.context||null,timestamp:t.timestamp||a(),device:t.device||null,adgroup_id:t.adgroup_id||null,ad_id:t.ad_id||null,adgroup_id_source:t.adgroup_id_source||null,ad_id_source:t.ad_id_source||null,click_id:t.click_id||null,click_id_source:t.click_id_source||null,custom_event_name:t.custom_event_name||void 0})),sdk_version:F};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 o=i*Math.pow(2,n);await new Promise(t=>setTimeout(t,o))}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,anonymous_id:t.anonymous_id,tracking_user_id:t.tracking_user_id,utm_source:t.utm_source||null,utm_medium:t.utm_medium||null,utm_campaign:t.utm_campaign||null,utm_term:t.utm_term||null,utm_content:t.utm_content||null,revenue:t.revenue||null,currency:t.currency||null,event_data:t.event_data||null,context:t.context||null,timestamp:t.timestamp||a(),device:t.device||null,adgroup_id:t.adgroup_id||null,ad_id:t.ad_id||null,adgroup_id_source:t.adgroup_id_source||null,ad_id_source:t.ad_id_source||null,click_id:t.click_id||null,click_id_source:t.click_id_source||null,custom_event_name:t.custom_event_name||void 0})),sdk_version:F},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,anonymous_id:t.anonymous_id,tracking_user_id:t.tracking_user_id,utm_source:t.utm_source||null,utm_medium:t.utm_medium||null,utm_campaign:t.utm_campaign||null,utm_term:t.utm_term||null,utm_content:t.utm_content||null,revenue:t.revenue||null,currency:t.currency||null,event_data:t.event_data||null,context:t.context||null,timestamp:t.timestamp||a(),device:t.device||null,adgroup_id:t.adgroup_id||null,ad_id:t.ad_id||null,adgroup_id_source:t.adgroup_id_source||null,ad_id_source:t.ad_id_source||null,click_id:t.click_id||null,click_id_source:t.click_id_source||null,custom_event_name:t.custom_event_name||void 0})),sdk_version:F},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}}}const z="__getuai_probe";function $(t){try{document.cookie=`${z}=1;domain=${t};path=/;SameSite=Lax`;const e=document.cookie.split(";").some(t=>t.trim().startsWith(`${z}=`));return e&&(document.cookie=`${z}=;domain=${t};path=/;expires=Thu, 01 Jan 1970 00:00:00 GMT`),e}catch{return!1}}class V{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 f(this.config.enableDebug),this.storage=new N(this.logger),this.httpClient=new M(this.logger,this.config.apiKey,this.config.apiEndpoint||n,this.config.maxRetries,this.config.retryDelay),this.queue=new L(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");const t=function(t){if(!t)return null;const e=t.trim();return e?e.startsWith(".")?e:"."+e:null}(this.config.domain)??function(){if(!function(){try{return"undefined"!=typeof document&&"string"==typeof document.cookie}catch{return!1}}())return null;const t="undefined"!=typeof location&&location.hostname||"";if(!t)return null;if("localhost"===t)return null;if(function(t){return!!/^\d+\.\d+\.\d+\.\d+$/.test(t)||!!t.includes(":")}(t))return null;const e=t.split(".").filter(Boolean);if(e.length<2)return null;for(let t=e.length-2;t>=0;t--){const i="."+e.slice(t).join(".");if($(i))return i}return null}();this.storage.setCookieDomain(t),this.storage.init().catch(t=>{this.logger.warn("Storage initialization failed (IndexedDB may be unavailable), continuing with basic features:",t)});try{this.storage.migrateLegacyStorage()}catch(t){this.logger.debug("Legacy storage migration skipped:",t)}this.initializeUserId(),this.initializeSession(),this.extractAndStoreUTMData(),this.config.autoTrack&&this.setupAutoTracking(),this.setupNetworkHandlers(),this.setupVisibilityHandlers(),this.setupBeforeUnloadHandler(),this.initialized=!0,this.logger.info("🚀 GetuAI Attribution SDK initialized successfully"),this.logger.info("📄 Auto track page view = "+this.config.autoTrackPageView),this.retryPendingEvents().catch(t=>{this.logger.warn("⚠️ Pending events retry failed",t)}),this.config.autoTrackPageView&&(this.logger.info("📄 Auto track page view enabled (including SPA route tracking)"),this.lastTrackedPath=this.getCurrentPath(),this.setupSPATracking(),this.initialPageViewTriggered||(this.initialPageViewTriggered=!0,Promise.resolve().then(()=>this.trackPageView()).then(()=>this.queue.process()).then(()=>{this.logger.info("✅ Auto track page view completed")}).catch(t=>this.logger.error("❌ Auto track page view failed:",t))))}catch(t){throw this.logger.error("Failed to initialize SDK:",t),t}}async trackEvent(i,r,n,o,s=e.USD,c){if(this.initialized)try{const e=w(),u=this.cachedPublicIP;this.ensurePublicIPFetched();const l={domain:"undefined"!=typeof window?window.location.hostname:null,path:"undefined"!=typeof window?window.location.pathname:null,title:I(),referrer:y(),url:e.split("?")[0],querystring:D(e),query_params:P(e),ip_address:u,user_agent:p()},d={session_id:this.session?.sessionId,start_time:this.session?.startTime,last_activity:this.session?.lastActivity,page_views:this.session?.pageViews},g=this.storage.getAnonymousId(),h=n||this.getUserId(),_={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,anonymous_id:g,tracking_user_id:h||void 0,timestamp:a(),event_data:r,context:{page:l,session:d},revenue:o,currency:s,...i===t.CUSTOM&&c?{custom_event_name:c}:{},...this.getUTMParams(),device:m(),...this.getAdParams()};this.logger.debug(`Tracking event: ${i}`,_),this.queue.add(_)}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,o,s=e.USD){i&&""!==i.trim()?await this.trackEvent(t.CUSTOM,r,n,o,s,i.trim()):this.logger.error("trackCustomEvent requires a non-empty customEventName")}async trackPageView(e,i){const r=w(),n=r.split("?")[0],o=Date.now(),s=this.config.pageViewDebounceInterval||5e3,a=this.pageViewTrackTimes.get(n);if(a&&o-a<s)return void this.logger.debug(`Page view debounced: ${n} (last tracked ${o-a}ms ago)`);const c={url:r,title:I(),referrer:y(),user_agent:p(),...e};await this.trackEvent(t.PAGE_VIEW,c,i),this.pageViewTrackTimes.set(n,o),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,o){await this.trackEvent(t.PURCHASE,o,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?T(t,A(e.lastTouch,this.config.crossDomainUTMParams)):t}getCurrentUTMParams(){const t=this.getAttributionData();return t?A(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}getAdParams(){const t=this.getAttributionData();if(!t)return{};const e=t.lastTouch,i=t=>t&&"string"==typeof t&&""!==t.trim()?t:null;return{adgroup_id:i(e.adgroup_id),ad_id:i(e.ad_id),adgroup_id_source:i(e.adgroup_id_source),ad_id_source:i(e.ad_id_source),click_id:i(e.click_id),click_id_source:i(e.click_id_source)}}initializeUserId(){if(this.config.userId)this.setUserId(this.config.userId),this.logger.info(`👤 User ID initialized from config: ${this.config.userId}`);else{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){if(!t||""===t.trim())return void this.logger.warn("Cannot set empty user ID");const e=t.trim(),i=this.storage.getUserId();if(i!==e){if(i&&i!==e&&(this.logger.info(`👥 User changed (${i} → ${e}) — rotating anonymous_id + session`),this.storage.rotateAnonymousId()),this.storage.setUserId(e),this.session){const t=this.session.userId;t&&t!==e?(this.logger.info(`🔄 Session previously owned by ${t} — rotating session for ${e}`),this.rotateSession(e)):t!==e&&(this.session={...this.session,userId:e},this.storage.storeSession(this.session))}this.logger.info(`👤 User ID set: ${e}`)}}rotateSession(t){const e=Date.now();this.session={sessionId:b(),startTime:e,lastActivity:e,pageViews:0,userId:t},this.storage.storeSession(this.session)}getUserId(){return this.storage.getUserId()}getAnonymousId(){return this.storage.getAnonymousId()}removeUserId(){this.storage.removeUserId(),this.logger.info("👤 User ID removed")}async identify(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(),i=this.storage.getUserId()??void 0,r=t&&e-t.lastActivity<this.config.sessionTimeout,n=!(!t?.userId||!i||t.userId===i);r&&!n?this.session={...t,lastActivity:e,userId:t.userId??i}:(n&&this.logger.info(`🔄 Session owner changed (${t?.userId} → ${i}) — starting new session`),this.session={sessionId:b(),startTime:e,lastActivity:e,pageViews:0,userId:i}),this.storage.storeSession(this.session),this.logger.debug("Session initialized:",this.session)}extractAndStoreUTMData(){const t=function(){const t=k();if(E(t))return t;if(E(S))return S;const e=function(){if("undefined"==typeof performance)return null;const t=performance.getEntriesByType;if("function"!=typeof t)return null;try{const e=t.call(performance,"navigation");if(e&&e.length>0){const t=e[0].name;if("string"==typeof t&&t.length>0)return t}}catch{}return null}();return E(e)?e:t}(),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),i=h(t);if(this.logger.debug("Extracting UTM params from URL:",t),this.logger.debug("Found UTM params:",e),this.logger.debug("Found ad params:",i),0===Object.keys(e).length&&!i.adgroup_id&&!i.ad_id&&!i.click_id)return void this.logger.debug("No UTM, ad, or click parameters found in URL");const r={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||"",adgroup_id:i.adgroup_id||"",ad_id:i.ad_id||"",adgroup_id_source:i.adgroup_id_source||"",ad_id_source:i.ad_id_source||"",click_id:i.click_id||"",click_id_source:i.click_id_source||"",timestamp:Date.now()},n=this.getAttributionData(),o={firstTouch:n?.firstTouch||r,lastTouch:r,touchpoints:n?.touchpoints||[],expiresAt:Date.now()+2592e6};n&&n.lastTouch.utm_source===r.utm_source&&n.lastTouch.utm_campaign===r.utm_campaign||o.touchpoints.push(r),this.storage.storeUTMData(o),this.logger.info("UTM data extracted and stored successfully:",r),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(),o=e.type?.toLowerCase();if("button"===i||"submit"===o||"reset"===o)continue;const s=this.getFormFieldKey(e,t);s&&(n.has(s)||n.set(s,[]),n.get(s).push(e))}n.forEach((t,i)=>{const r=t.some(t=>"radio"===t.type),n=t.some(t=>"checkbox"===t.type),o=t.some(t=>"file"===t.type),s=t.some(t=>"SELECT"===t.tagName&&t.multiple),a=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(s){const r=t.find(t=>"SELECT"===t.tagName&&t.multiple);if(r){const t=Array.from(r.selectedOptions).map(t=>t.value);return void(Object.prototype.hasOwnProperty.call(e,i)||(e[i]=t))}}if(o){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(a)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(s))if(!e[i])for(const n of r||[]){const r=n.toLowerCase();for(const[n,o]of Object.entries(t))if((n.toLowerCase()===r||n.toLowerCase().includes(r))&&o&&"string"==typeof o&&o.trim()){e[i]=o.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=A(r.lastTouch,this.config.crossDomainUTMParams);if(0===Object.keys(n).length)return void this.logger.debug("No UTM parameters to pass");const o=T(i,n);o!==i&&(t.href=o,this.logger.debug("UTM parameters added to external link:",{original:i,enhanced:o,utmParams:n}),this.logger.debug("Cross-domain UTM passed:",{link_url:o,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 G=null;async function B(t){if(G)return console.warn("GetuAI SDK: Already initialized"),G;try{if(G=new V(t),await G.init(),t.enableDebug&&(window.GetuAISDK=G),console.log("GetuAI Attribution SDK initialized successfully"),"undefined"!=typeof window){const t=new CustomEvent("getuaiSDKReady",{detail:{sdk:G}});window.dispatchEvent(t)}return G}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 q(){return G}function Y(){return new Promise((t,e)=>{if(G)return void t(G);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 j(t,i,r,n,o=e.USD){const s=q();s?await s.trackEvent(t,i,r,n,o):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function H(t,e){const i=q();i?await i.trackPageView(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function J(t,i,r=e.USD,n){const o=q();o?await o.trackPurchase(t,i,r,n):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function W(t,e){const i=q();i?await i.trackLogin(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function X(t,e){const i=q();i?await i.trackSignup(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function Q(t,e){const i=q();i?await i.trackFormSubmit(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function Z(t,e){const i=q();i?await i.trackVideoPlay(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function tt(t,e){const i=q();i?await i.trackEmailVerification(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function et(t,e){const i=q();i?await i.trackAuditApproved(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function it(t){const e=q();e?await e.trackPurchaseAuto(t):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function rt(t){const e=q();e?await e.trackLoginAuto(t):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function nt(t){const e=q();e?await e.trackSignupAuto(t):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function ot(t){const e=q();e?await e.trackEmailVerificationAuto(t):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function st(t,i,r,n,o=e.USD){const s=q();s?await s.trackCustomEvent(t,i,r,n,o):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function at(t,e){const i=q();i?await i.trackProductView(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function ct(t,e){const i=q();i?await i.trackAddToCart(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function ut(t,e){const i=q();i?await i.trackPageClick(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function lt(t,e,i){const r=q();r?await r.trackButtonClick(t,e,i):console.warn("GetuAI SDK: Not initialized. Call init() first.")}function dt(){const t=q();return t?t.getAttributionData():null}async function gt(){const t=q();t?await t.flush():console.warn("GetuAI SDK: Not initialized. Call init() first.")}function ht(){const t=q();return t?t.getStatus():null}function mt(t){const e=q();return e?e.addUTMToURL(t):(console.warn("GetuAI SDK: Not initialized. Call init() first."),t)}function _t(){const t=q();return t?t.getCurrentUTMParams():{}}function ft(t){const e=q();e?e.setUserId(t):console.warn("GetuAI SDK: Not initialized. Call init() first.")}function pt(){const t=q();return t?t.getUserId():(console.warn("GetuAI SDK: Not initialized. Call init() first."),null)}function yt(){const t=q();t?t.removeUserId():console.warn("GetuAI SDK: Not initialized. Call init() first.")}function wt(){G&&(G.destroy(),G=null,console.log("GetuAI SDK destroyed"))}class kt extends V{static async init(t){return await B(t)}static async trackEvent(t,i,r,n,o=e.USD){return await j(t,i,r,n,o)}static async trackPageView(t,e){return await H(t,e)}static async trackPurchase(t,i,r=e.USD,n){return await J(t,i,r,n)}static async trackLogin(t,e){return await W(t,e)}static async trackSignup(t,e){return await X(t,e)}static async trackFormSubmit(t,e){return await Q(t,e)}static async trackVideoPlay(t,e){return await Z(t,e)}static async trackEmailVerification(t,e){return await tt(t,e)}static async trackPurchaseAuto(t){return await it(t)}static async trackLoginAuto(t){return await rt(t)}static async trackSignupAuto(t){return await nt(t)}static async trackEmailVerificationAuto(t){return await ot(t)}static async trackCustomEvent(t,i,r,n,o=e.USD){return await st(t,i,r,n,o)}static async trackProductView(t,e){return await at(t,e)}static async trackAddToCart(t,e){return await ct(t,e)}static async trackPageClick(t,e){return await ut(t,e)}static async trackButtonClick(t,e,i){return await lt(t,e,i)}static getAttributionData(){return dt()}static async flush(){return await gt()}static getStatus(){return ht()}static addUTMToURL(t){return mt(t)}static getCurrentUTMParams(){return _t()}static setUserId(t){ft(t)}static getUserId(){return pt()}static removeUserId(){yt()}static destroy(){wt()}static getSDK(){return q()}static waitForSDK(){return Y()}}"undefined"!=typeof document&&function(){if(G)return;const t=document.currentScript;if(!t)return void console.warn("GetuAI SDK: Could not find script tag for auto-initialization");const e=t.getAttribute("data-api-key");e?B({apiKey:e,apiEndpoint:t.getAttribute("data-api-endpoint")||n,enableDebug:"true"===t.getAttribute("data-debug"),autoTrack:"true"===t.getAttribute("data-auto-track"),autoTrackPageView:"true"===t.getAttribute("data-auto-track-page-view"),autoCleanUTM:"false"!==t.getAttribute("data-auto-clean-utm"),batchSize:parseInt(t.getAttribute("data-batch-size")||"100"),batchInterval:parseInt(t.getAttribute("data-batch-interval")||"2000"),userId:t.getAttribute("data-user-id")||void 0,domain:t.getAttribute("data-domain")||void 0}):console.warn("GetuAI SDK: No API key provided. Please add data-api-key attribute to script tag.")}(),"undefined"!=typeof window&&(window.getuaiSDK={init:B,getSDK:q,waitForSDK:Y,trackEvent:j,trackPageView:H,trackPageClick:ut,trackButtonClick:lt,trackPurchase:J,trackLogin:W,trackSignup:X,trackFormSubmit:Q,trackVideoPlay:Z,trackEmailVerification:tt,trackAuditApproved:et,trackCustomEvent:st,trackProductView:at,trackAddToCart:ct,trackPurchaseAuto:it,trackLoginAuto:rt,trackSignupAuto:nt,trackEmailVerificationAuto:ot,getAttributionData:dt,flush:gt,getStatus:ht,addUTMToURL:mt,getCurrentUTMParams:_t,setUserId:ft,getUserId:pt,removeUserId:yt,destroy:wt,EventType:t,Currency:e,AttributionSDK:kt},window.init=B,window.waitForSDK=Y,window.trackEvent=j,window.trackPageView=H,window.trackPageClick=ut,window.trackButtonClick=lt,window.trackPurchase=J,window.trackLogin=W,window.trackSignup=X,window.trackFormSubmit=Q,window.trackVideoPlay=Z,window.trackEmailVerification=tt,window.trackProductView=at,window.trackAddToCart=ct,window.trackPurchaseAuto=it,window.trackLoginAuto=rt,window.trackSignupAuto=nt,window.trackEmailVerificationAuto=ot,window.getAttributionData=dt,window.flush=gt,window.getStatus=ht,window.addUTMToURL=mt,window.getCurrentUTMParams=_t,window.setUserId=ft,window.getUserId=pt,window.removeUserId=yt,window.destroy=wt,window.AttributionSDK=kt);const St={init:B,getSDK:q,waitForSDK:Y,trackEvent:j,trackPageView:H,trackPageClick:ut,trackButtonClick:lt,trackPurchase:J,trackLogin:W,trackSignup:X,trackFormSubmit:Q,trackVideoPlay:Z,trackEmailVerification:tt,trackAuditApproved:et,trackCustomEvent:st,trackProductView:at,trackAddToCart:ct,trackPurchaseAuto:it,trackLoginAuto:rt,trackSignupAuto:nt,trackEmailVerificationAuto:ot,getAttributionData:dt,flush:gt,getStatus:ht,addUTMToURL:mt,getCurrentUTMParams:_t,setUserId:ft,getUserId:pt,removeUserId:yt,destroy:wt,EventType:t,Currency:e,AttributionSDK:kt};return r.default})());
|
package/dist/index.esm.js
CHANGED
|
@@ -339,6 +339,105 @@ function getReferrer() {
|
|
|
339
339
|
function getCurrentUrl() {
|
|
340
340
|
return window.location.href;
|
|
341
341
|
}
|
|
342
|
+
// ---------------------------------------------------------------------------
|
|
343
|
+
// UTM recovery for late-init scenarios
|
|
344
|
+
// ---------------------------------------------------------------------------
|
|
345
|
+
//
|
|
346
|
+
// When the SDK is bundled into a host framework (e.g. Nuxt) and init() runs
|
|
347
|
+
// after the framework's router has already stripped UTM from the URL via
|
|
348
|
+
// history.replaceState(), reading window.location.href alone loses the
|
|
349
|
+
// attribution. Two fallbacks recover it without any caller cooperation:
|
|
350
|
+
//
|
|
351
|
+
// 1. INITIAL_URL_SNAPSHOT — captured at module-load time. As long as the
|
|
352
|
+
// SDK module is parsed before the host's router runs (the common case
|
|
353
|
+
// for eager-bundled main chunks), this holds the unstripped URL.
|
|
354
|
+
// 2. Performance Navigation Timing — entry.name is pinned to the original
|
|
355
|
+
// navigation URL and is NOT mutated by later history.replaceState calls.
|
|
356
|
+
// This is the last-resort recovery and works even if the SDK module
|
|
357
|
+
// itself is loaded via a lazy chunk after the strip.
|
|
358
|
+
// Safe read of window.location.href — returns "" if access throws (e.g.
|
|
359
|
+
// cross-origin sandboxed iframe, throwing location/href getter) or if
|
|
360
|
+
// window/location are unavailable (SSR). All location access is inside the
|
|
361
|
+
// try so even a throwing `window.location` getter cannot escape.
|
|
362
|
+
function safeCurrentHref() {
|
|
363
|
+
if (typeof window === "undefined")
|
|
364
|
+
return "";
|
|
365
|
+
try {
|
|
366
|
+
const loc = window.location;
|
|
367
|
+
return loc && typeof loc.href === "string" ? loc.href : "";
|
|
368
|
+
}
|
|
369
|
+
catch {
|
|
370
|
+
return "";
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
let INITIAL_URL_SNAPSHOT = safeCurrentHref() || null;
|
|
374
|
+
const UTM_KEYS_FOR_DETECTION = [
|
|
375
|
+
"utm_source",
|
|
376
|
+
"utm_medium",
|
|
377
|
+
"utm_campaign",
|
|
378
|
+
"utm_term",
|
|
379
|
+
"utm_content",
|
|
380
|
+
];
|
|
381
|
+
// Detects any attribution signal — UTM keys OR ad/click identifiers
|
|
382
|
+
// (gclid, fbclid, adgroup_id, ad_id, etc.). Both are extracted later by
|
|
383
|
+
// extractAndStoreUTMData(), so the URL chooser must treat either as
|
|
384
|
+
// "worth recovering" — otherwise a ?gclid=... URL stripped before init
|
|
385
|
+
// would still lose attribution.
|
|
386
|
+
function urlHasAttributionSignal(url) {
|
|
387
|
+
if (!url)
|
|
388
|
+
return false;
|
|
389
|
+
try {
|
|
390
|
+
const u = new URL(url);
|
|
391
|
+
const hasUTM = UTM_KEYS_FOR_DETECTION.some((k) => {
|
|
392
|
+
const v = u.searchParams.get(k);
|
|
393
|
+
return v !== null && v.trim() !== "";
|
|
394
|
+
});
|
|
395
|
+
if (hasUTM)
|
|
396
|
+
return true;
|
|
397
|
+
const ad = extractAdParams(url);
|
|
398
|
+
return Boolean(ad.adgroup_id || ad.ad_id || ad.click_id);
|
|
399
|
+
}
|
|
400
|
+
catch {
|
|
401
|
+
return false;
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
// Read the original navigation URL from the Performance Navigation Timing API.
|
|
405
|
+
// Survives history.replaceState — useful when the host framework strips UTM
|
|
406
|
+
// during hydration before the SDK has a chance to read it.
|
|
407
|
+
function getNavigationUrl() {
|
|
408
|
+
if (typeof performance === "undefined")
|
|
409
|
+
return null;
|
|
410
|
+
const getter = performance.getEntriesByType;
|
|
411
|
+
if (typeof getter !== "function")
|
|
412
|
+
return null;
|
|
413
|
+
try {
|
|
414
|
+
const entries = getter.call(performance, "navigation");
|
|
415
|
+
if (entries && entries.length > 0) {
|
|
416
|
+
const name = entries[0].name;
|
|
417
|
+
if (typeof name === "string" && name.length > 0)
|
|
418
|
+
return name;
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
catch {
|
|
422
|
+
/* ignore */
|
|
423
|
+
}
|
|
424
|
+
return null;
|
|
425
|
+
}
|
|
426
|
+
// Pick the URL most likely to still carry attribution signal (UTM or ad/click
|
|
427
|
+
// IDs): current location → module-load snapshot → navigation timing entry.
|
|
428
|
+
// Falls back to current location if none carry signal (preserves original
|
|
429
|
+
// behavior — extractAndStoreUTMData will then early-return on empty params).
|
|
430
|
+
function getBestUTMSourceUrl() {
|
|
431
|
+
const current = safeCurrentHref();
|
|
432
|
+
if (urlHasAttributionSignal(current))
|
|
433
|
+
return current;
|
|
434
|
+
if (urlHasAttributionSignal(INITIAL_URL_SNAPSHOT))
|
|
435
|
+
return INITIAL_URL_SNAPSHOT;
|
|
436
|
+
const nav = getNavigationUrl();
|
|
437
|
+
if (urlHasAttributionSignal(nav))
|
|
438
|
+
return nav;
|
|
439
|
+
return current;
|
|
440
|
+
}
|
|
342
441
|
// Get page title
|
|
343
442
|
function getPageTitle() {
|
|
344
443
|
return document.title || "";
|
|
@@ -1330,7 +1429,7 @@ class AttributionStorageManager {
|
|
|
1330
1429
|
* This version is automatically updated from package.json during build
|
|
1331
1430
|
* DO NOT manually edit this file - it will be overwritten during build
|
|
1332
1431
|
*/
|
|
1333
|
-
const SDK_VERSION = "0.5.
|
|
1432
|
+
const SDK_VERSION = "0.5.2";
|
|
1334
1433
|
|
|
1335
1434
|
class EventQueueManager {
|
|
1336
1435
|
constructor(logger, apiKey, apiEndpoint, batchSize = 100, batchInterval = 2000, maxRetries = 3, retryDelay = 1000, sendEvents) {
|
|
@@ -1503,6 +1602,16 @@ class EventHttpClient {
|
|
|
1503
1602
|
event_data: event.event_data || null,
|
|
1504
1603
|
context: event.context || null,
|
|
1505
1604
|
timestamp: event.timestamp || getTimestamp(), // Convert to seconds
|
|
1605
|
+
device: event.device || null,
|
|
1606
|
+
// Ad-tracking dimensions flow from STORED last-touch attribution, so they
|
|
1607
|
+
// survive on conversion events whose current page URL has no ad params —
|
|
1608
|
+
// the backend cannot re-derive those from the current page. Forward them.
|
|
1609
|
+
adgroup_id: event.adgroup_id || null,
|
|
1610
|
+
ad_id: event.ad_id || null,
|
|
1611
|
+
adgroup_id_source: event.adgroup_id_source || null,
|
|
1612
|
+
ad_id_source: event.ad_id_source || null,
|
|
1613
|
+
click_id: event.click_id || null,
|
|
1614
|
+
click_id_source: event.click_id_source || null,
|
|
1506
1615
|
custom_event_name: event.custom_event_name || undefined,
|
|
1507
1616
|
}));
|
|
1508
1617
|
const batchRequest = {
|
|
@@ -1553,6 +1662,16 @@ class EventHttpClient {
|
|
|
1553
1662
|
event_data: event.event_data || null,
|
|
1554
1663
|
context: event.context || null,
|
|
1555
1664
|
timestamp: event.timestamp || getTimestamp(),
|
|
1665
|
+
device: event.device || null,
|
|
1666
|
+
// Ad-tracking dimensions flow from STORED last-touch attribution, so they
|
|
1667
|
+
// survive on conversion events whose current page URL has no ad params —
|
|
1668
|
+
// the backend cannot re-derive those from the current page. Forward them.
|
|
1669
|
+
adgroup_id: event.adgroup_id || null,
|
|
1670
|
+
ad_id: event.ad_id || null,
|
|
1671
|
+
adgroup_id_source: event.adgroup_id_source || null,
|
|
1672
|
+
ad_id_source: event.ad_id_source || null,
|
|
1673
|
+
click_id: event.click_id || null,
|
|
1674
|
+
click_id_source: event.click_id_source || null,
|
|
1556
1675
|
custom_event_name: event.custom_event_name || undefined,
|
|
1557
1676
|
}));
|
|
1558
1677
|
const batchRequest = {
|
|
@@ -1604,6 +1723,16 @@ class EventHttpClient {
|
|
|
1604
1723
|
event_data: event.event_data || null,
|
|
1605
1724
|
context: event.context || null,
|
|
1606
1725
|
timestamp: event.timestamp || getTimestamp(),
|
|
1726
|
+
device: event.device || null,
|
|
1727
|
+
// Ad-tracking dimensions flow from STORED last-touch attribution, so they
|
|
1728
|
+
// survive on conversion events whose current page URL has no ad params —
|
|
1729
|
+
// the backend cannot re-derive those from the current page. Forward them.
|
|
1730
|
+
adgroup_id: event.adgroup_id || null,
|
|
1731
|
+
ad_id: event.ad_id || null,
|
|
1732
|
+
adgroup_id_source: event.adgroup_id_source || null,
|
|
1733
|
+
ad_id_source: event.ad_id_source || null,
|
|
1734
|
+
click_id: event.click_id || null,
|
|
1735
|
+
click_id_source: event.click_id_source || null,
|
|
1607
1736
|
custom_event_name: event.custom_event_name || undefined,
|
|
1608
1737
|
}));
|
|
1609
1738
|
const payload = {
|
|
@@ -1858,6 +1987,10 @@ class AttributionSDK {
|
|
|
1858
1987
|
querystring: getQueryString(currentUrl),
|
|
1859
1988
|
query_params: getQueryParams(currentUrl),
|
|
1860
1989
|
ip_address: ip_address,
|
|
1990
|
+
// Raw User-Agent on EVERY event (not just page_view): the lossless
|
|
1991
|
+
// device signal that lets the backend re-derive any future device
|
|
1992
|
+
// classification. Rides in context.page, persisted per-event server-side.
|
|
1993
|
+
user_agent: getUserAgent(),
|
|
1861
1994
|
};
|
|
1862
1995
|
const sessionContext = {
|
|
1863
1996
|
session_id: this.session?.sessionId,
|
|
@@ -2315,9 +2448,14 @@ class AttributionSDK {
|
|
|
2315
2448
|
this.storage.storeSession(this.session);
|
|
2316
2449
|
this.logger.debug("Session initialized:", this.session);
|
|
2317
2450
|
}
|
|
2318
|
-
// Extract and store UTM data from current URL
|
|
2451
|
+
// Extract and store UTM data from current URL.
|
|
2452
|
+
//
|
|
2453
|
+
// Uses getBestUTMSourceUrl() (current href → module-load snapshot →
|
|
2454
|
+
// Performance Navigation Timing entry) so attribution survives a host
|
|
2455
|
+
// framework (e.g. Nuxt router) stripping UTM params via
|
|
2456
|
+
// history.replaceState before our init() runs.
|
|
2319
2457
|
extractAndStoreUTMData() {
|
|
2320
|
-
const currentUrl =
|
|
2458
|
+
const currentUrl = getBestUTMSourceUrl();
|
|
2321
2459
|
const utmParams = extractUTMParams(currentUrl);
|
|
2322
2460
|
const adParams = extractAdParams(currentUrl);
|
|
2323
2461
|
this.logger.debug("Extracting UTM params from URL:", currentUrl);
|