UNPKG

mm-app-analytics-js-sdk

Version:
1 lines 111 kB
this.MMAppAnalyticsSDK=function(){"use strict";class e{constructor(e){if(!e||"object"!=typeof e)throw new Error("Configuration must be an object");if(!e.customerId)throw new Error("Customer ID is required");if(!e.appId)throw new Error("App ID is required");if(!e.appName)throw new Error("App Name is required");if(!e.appVersion)throw new Error("App Version is required");this._config={customerId:e.customerId,appId:e.appId,appName:e.appName,appVersion:e.appVersion,sdkVersion:"1.0.0",platform:"web",dataSrc:"Application",sessionId:this._generateUUID(),...e},this._initializeStaticMetadata()}_initializeStaticMetadata(){const e=navigator.userAgent,t=window.screen;/iPad|Android|Tablet/i.test(e)?this.setDeviceType("tablet"):/Mobile|Android|iPhone|iPod/i.test(e)?this.setDeviceType("mobile"):this.setDeviceType("desktop"),/Chrome/i.test(e)?(this.setBrowser("Chrome"),this.setBrowserVersion(e.match(/Chrome\/(\d+\.\d+\.\d+\.\d+)/)?.[1])):/Firefox/i.test(e)?(this.setBrowser("Firefox"),this.setBrowserVersion(e.match(/Firefox\/(\d+\.\d+)/)?.[1])):/Safari/i.test(e)&&!/Chrome/i.test(e)?(this.setBrowser("Safari"),this.setBrowserVersion(e.match(/Version\/(\d+\.\d+\.\d+)/)?.[1])):/Edge/i.test(e)&&(this.setBrowser("Edge"),this.setBrowserVersion(e.match(/Edge\/(\d+\.\d+\.\d+\.\d+)/)?.[1])),/Windows/i.test(e)?(this.setOS("Windows"),this.setOSVersion(e.match(/Windows NT (\d+\.\d+)/)?.[1])):/Mac OS X/i.test(e)?(this.setOS("MacOS"),this.setOSVersion(e.match(/Mac OS X (\d+[._]\d+)/)?.[1]?.replace("_","."))):/Linux/i.test(e)?(this.setOS("Linux"),this.setOSVersion("Unknown")):/Android/i.test(e)?(this.setOS("Android"),this.setOSVersion(e.match(/Android (\d+\.\d+)/)?.[1])):/iOS|iPhone|iPad|iPod/i.test(e)&&(this.setOS("iOS"),this.setOSVersion(e.match(/OS (\d+[._]\d+)/)?.[1]?.replace("_","."))),this.setScreenRes(`${t.width}x${t.height}`),this.setScreenWidth(t.width),this.setScreenHeight(t.height),this.setColorDepth(t.colorDepth),this.setPixelRatio(window.devicePixelRatio),this.setViewportWidth(window.innerWidth),this.setViewportHeight(window.innerHeight),this.setLanguage(navigator.language),this.setTimezone(Intl.DateTimeFormat().resolvedOptions().timeZone),this.setDeviceId(this._generateUUID()),this.setUserAgent(e)}setDeviceType(e){this._config.deviceType=e}setBrowser(e){this._config.browser=e}setBrowserVersion(e){this._config.browserVersion=e}setOS(e){this._config.os=e}setOSVersion(e){this._config.osVersion=e}setScreenRes(e){this._config.screenRes=e}setScreenWidth(e){this._config.screenWidth=e}setScreenHeight(e){this._config.screenHeight=e}setColorDepth(e){this._config.colorDepth=e}setPixelRatio(e){this._config.pixelRatio=e}setViewportWidth(e){this._config.viewportWidth=e}setViewportHeight(e){this._config.viewportHeight=e}setLanguage(e){this._config.language=e}setTimezone(e){this._config.timezone=e}setDeviceId(e){this._config.deviceId=e}setUserAgent(e){this._config.userAgent=e}_generateUUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){const t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}))}getEventMetadata(){return{deviceType:this._config.deviceType,browser:this._config.browser,browserVersion:this._config.browserVersion,os:this._config.os,osVersion:this._config.osVersion,screenRes:this._config.screenRes,screenWidth:this._config.screenWidth,screenHeight:this._config.screenHeight,colorDepth:this._config.colorDepth,pixelRatio:this._config.pixelRatio,viewportWidth:this._config.viewportWidth,viewportHeight:this._config.viewportHeight,language:this._config.language,timezone:this._config.timezone,deviceId:this._config.deviceId,userAgent:this._config.userAgent,timestamp:Date.now(),platform:this._config.platform,sdkVersion:this._config.sdkVersion,dataSrc:this._config.dataSrc}}get(e){return this._config[e]}set(e,t){this._config[e]=t}getConfig(){return{...this._config}}getDeviceInfo(){return{deviceType:this._config.deviceType,browser:this._config.browser,browserVersion:this._config.browserVersion,os:this._config.os,osVersion:this._config.osVersion,screenRes:this._config.screenRes,screenWidth:this._config.screenWidth,screenHeight:this._config.screenHeight,colorDepth:this._config.colorDepth,pixelRatio:this._config.pixelRatio,viewportWidth:this._config.viewportWidth,viewportHeight:this._config.viewportHeight,language:this._config.language,timezone:this._config.timezone,deviceId:this._config.deviceId,userAgent:this._config.userAgent}}getAppInfo(){return{customerId:this._config.customerId,appId:this._config.appId,appName:this._config.appName,appVersion:this._config.appVersion,platform:this._config.platform,sdkVersion:this._config.sdkVersion,dataSrc:this._config.dataSrc}}getSessionId(){return this._config.sessionId}updateSessionId(e){this._config.sessionId=e}}class t{constructor(){this._states={app:{current:{state:"foreground",timestamp:Date.now()},previous:null,history:[]},video:{current:{state:"idle",timestamp:Date.now()},previous:null,history:[]},screen:{current:null,previous:null,history:[]},user:{current:null,previous:null,history:[]},payment:{current:null,previous:null,history:[]},subscription:{current:null,previous:null,history:[]}},this._states.app.history.push(this._states.app.current),this._states.video.history.push(this._states.video.current),this._maxHistoryLength=10,this._stateChangeCallbacks=new Map}getAppState(){return this._states.app.current?.state||"foreground"}getVideoState(){return this._states.video.current?.state||"idle"}getScreenState(){return this._states.screen.current?.state||null}getVideoData(){return this._states.video.current?.metadata||null}getScreenData(){return this._states.screen.current?.metadata||null}getVideoStateHistory(){return this._states.video.history}getAppStateHistory(){return this._states.app.history}getScreenStateHistory(){return this._states.screen.history}updateAppState(e,t={}){return this._updateState("app",e,t)}updateVideoState(e,t={}){return this._updateState("video",e,t)}updateScreenState(e,t={}){return this._updateState("screen",e,t)}updateUserState(e){return this._updateState("user","identified",e)}getUserState(){return this._states.user.current}getUserStateHistory(){return this._states.user.history}getCurrentState(e){return this._states[e]?.current||null}getPreviousState(e){return this._states[e]?.previous||null}getStateHistory(e){return[...this._states[e]?.history||[]]}onStateChange(e,t){this._stateChangeCallbacks.has(e)||this._stateChangeCallbacks.set(e,new Set),this._stateChangeCallbacks.get(e).add(t)}offStateChange(e,t){const r=this._stateChangeCallbacks.get(e);r&&r.delete(t)}clearStates(){this._states={app:{current:{state:"foreground",timestamp:Date.now()},previous:null,history:[]},video:{current:{state:"idle",timestamp:Date.now()},previous:null,history:[]},screen:{current:null,previous:null,history:[]},user:{current:null,previous:null,history:[]},payment:{current:null,previous:null,history:[]},subscription:{current:null,previous:null,history:[]}}}_updateState(e,t,r){try{if(!this._states[e])throw new Error(`Invalid state type: ${e}`);if(!this._isValidStateTransition(e,t))return!1;const a={state:t,timestamp:Date.now(),metadata:r};return this._states[e].previous=this._states[e].current,this._states[e].current=a,this._states[e].history.push(a),this._states[e].history.length>this._maxHistoryLength&&this._states[e].history.shift(),this._notifyStateChange(e,a),!0}catch(t){return console.error(`State update failed for ${e}:`,t),!1}}_isValidStateTransition(e,t){const r=this._states[e].current?.state||null,a={app:{null:["foreground","background"],foreground:["background"],background:["foreground"]},video:{null:["idle","loading","playing"],idle:["loading","playing"],loading:["playing","error"],playing:["paused","ended","error"],paused:["playing","ended"],ended:["idle","loading"],error:["idle"]},screen:{null:["active"],active:["inactive"],inactive:["active"]},payment:{null:["initiated","processing"],initiated:["processing","failed"],processing:["success","failed","refunded"],success:["refunded"],failed:["initiated"],refunded:["initiated"]},subscription:{null:["trial","active"],trial:["active","expired"],active:["cancelled","expired","upgraded","downgraded"],cancelled:["active","expired"],expired:["active"],upgraded:["active"],downgraded:["active"]}}[e];return!!a&&(a[r]||[]).includes(t)}_notifyStateChange(e,t){const r=this._stateChangeCallbacks.get(e);r&&r.forEach((r=>{try{r(t,this._states[e].previous)}catch(t){console.error(`Error in state change callback for ${e}:`,t)}}))}updatePaymentState(e,t={}){return this._updateState("payment",e,t)}getPaymentState(){return this._states.payment.current}getPaymentStateHistory(){return this._states.payment.history}updateSubscriptionState(e,t={}){return this._updateState("subscription",e,t)}getSubscriptionState(){return this._states.subscription.current}getSubscriptionStateHistory(){return this._states.subscription.history}}const r={getItem(e){try{return localStorage.getItem(e)}catch(e){return console.error("Failed to get item from storage:",e),null}},setItem(e,t){try{return localStorage.setItem(e,t),!0}catch(e){return console.error("Failed to set item in storage:",e),!1}},removeItem(e){try{return localStorage.removeItem(e),!0}catch(e){return console.error("Failed to remove item from storage:",e),!1}}};class a{constructor(e={}){this._config={batchSize:e.batchSize||10,flushInterval:e.flushInterval||5e3,maxRetries:e.maxRetries||3,retryDelay:e.retryDelay||1e3,getConfig:()=>({batchSize:this._config.batchSize,flushInterval:this._config.flushInterval,maxRetries:this._config.maxRetries,retryDelay:this._config.retryDelay})},this.events=[],this._flushTimer=null,this._producerURL="https://streamproducer-lcrr.mediamelon.com",this._processingQueue=[],this._retryTimeouts=new Map,this._isProcessing=!1,this._stats={successfulEvents:0,failedEvents:0,totalProcessed:0,lastProcessTime:0},this._loadStoredEvents(),this._startFlushTimer(),console.log("EventQueue initialized with config:",this._config.getConfig())}setProducerURL(e){if(!e||"string"!=typeof e)throw new Error("Valid producer URL is required");this._producerURL=e}getProducerURL(){return this._producerURL}updateConfig(e){this._config={...e,getConfig:()=>e},this._flushTimer&&clearInterval(this._flushTimer),this._startFlushTimer()}_loadStoredEvents(){const e=r.getItem("mm_analytics_event_queue");if(e)try{this.events=JSON.parse(e)}catch(e){console.error("Failed to parse stored events:",e),this.events=[]}}addEvent(e){if(!e||"object"!=typeof e)throw new Error("Invalid event");e.eventId||(e.eventId=this._generateUUID()),console.log("Adding event to queue:",e.type),this.events.push(e),this._persistEvents(),this.events.length>=this._config.batchSize&&(console.log("Batch size reached, triggering immediate flush"),this._flush())}getNextEvent(){return this.events.length>0?this.events[0]:null}removeEvent(){this.events.length>0&&(this.events.shift(),this._persistEvents())}clear(){if(this.events=[],this._config){this._processingQueue=[],this._stats={successfulEvents:0,failedEvents:0,totalProcessed:0,lastProcessTime:0},this._flushTimer&&(clearInterval(this._flushTimer),this._flushTimer=null);for(const e of this._retryTimeouts.values())clearTimeout(e);this._retryTimeouts.clear()}r.removeItem("mm_analytics_event_queue")}isEmpty(){return 0===this.events.length}getSize(){return this.events.length}getStatus(){if(!this._config)return{queueLength:this.events.length,processingLength:0,retryCount:0,successfulEvents:0,failedEvents:0,totalProcessed:0,processingTime:0,isProcessing:!1};for(const[e,t]of this._retryTimeouts.entries())(t._destroyed||t._called)&&this._retryTimeouts.delete(e);return{queueLength:this.events.length,processingLength:this._processingQueue.length,retryCount:this._retryTimeouts.size,successfulEvents:this._stats.successfulEvents,failedEvents:this._stats.failedEvents,totalProcessed:this._stats.totalProcessed,processingTime:this._stats.lastProcessTime,isProcessing:this._isProcessing}}_startFlushTimer(){this._flushTimer&&clearInterval(this._flushTimer);const e=this._config.flushInterval;console.log("Starting flush timer with interval:",e),this._flushTimer=setInterval((()=>{this.events.length>0&&(console.log("Flush timer triggered, queue size:",this.events.length),this._flush())}),e)}_persistEvents(){r.setItem("mm_analytics_event_queue",JSON.stringify(this.events))}async _flush(){if(this._isProcessing)return void console.log("Already processing events, skipping flush");if(0===this.events.length)return void console.log("No events to flush");console.log("Starting flush of",this.events.length,"events"),console.log("[EVENT QUEUE] Events in queue:",this.events.map((e=>({type:e.type,timestamp:e.timestamp}))));const e=this._config.batchSize,t=this.events.splice(0,e);console.log("Prepared batch of",t.length,"events for processing");try{await this._sendBatch(t),console.log("Successfully processed batch of",t.length,"events")}catch(e){console.error("Error during flush:",e),t&&t.length>0&&(console.log("Putting failed events back in queue"),this.events.unshift(...t))}}async _sendBatch(e){if(e&&0!==e.length)if(this._isProcessing)console.log("Already processing events, skipping batch");else{this._isProcessing=!0,console.log("Starting batch processing of",e.length,"events");try{for(const t of e)try{if(!t){console.error("Invalid event: null or undefined");continue}let e;if(t.qubitData)e={timestamp:t.timestamp,qubitData:t.qubitData};else{console.log("Formatting event without qubitData:",t.type);const r=t.data?.currentPayload||{};e={timestamp:t.timestamp||Date.now(),qubitData:[{streamID:{custId:r.customerId||r.custId||t.data?.customerId||t.data?.custId||"",subscriberId:r.subscriberId||t.data?.subscriberId||"",subscriberType:r.subscriberType||t.data?.subscriberType||"",subscriberTag:r.subscriberTag||t.data?.subscriberTag||"",sessionId:r.sessionId||t.data?.sessionId||t.sessionId||this._config?.getSessionId?.()||"",pId:r.profileId||t.data?.profileId||"",dataSrc:"Application"},sdkInfo:{sdkVersion:r.sdkVersion||t.data?.sdkVersion||"JSSDK1.0.0"},appEventInfo:{eventName:this._getEventName(t),eventType:this._getEventType(t),currentScreen:r.currentScreen||t.data?.currentScreen||"",isGraceful:r.isGraceful||t.data?.isGraceful||!1,eventData:r.eventData||t.data?.eventData||{}},userInfo:{profileId:r.profileId||t.data?.profileId||"",userData:r.userData||t.data?.userData||{},referralId:r.referralId||t.data?.referralId||"",referralData:r.referralData||t.data?.referralData||{}},clientInfo:{appName:r.appName||t.data?.appName||"",appVersion:r.appVersion||t.data?.appVersion||"",scrnRes:r.screenRes||r.scrnRes||t.data?.screenRes||t.data?.scrnRes||this._getScreenResolution(),deviceId:r.deviceId||t.data?.deviceId||"",deviceType:r.deviceType||t.data?.deviceType||"",deviceBrand:r.deviceBrand||t.data?.deviceBrand||"",deviceModel:r.deviceModel||t.data?.deviceModel||"",deviceMarketingName:r.deviceMarketingName||t.data?.deviceMarketingName||"",osVersion:r.osVersion||t.data?.osVersion||"",platform:r.platform||t.data?.platform||"",ua:r.userAgent||t.data?.userAgent||t.data?.clientInfo?.ua||""},customTags:r.customTags||t.data?.customTags||{}}]},e.qubitData[0].clientInfo.ua?console.log("[DEBUG] ua found in clientInfo:",e.qubitData[0].clientInfo.ua):(console.warn("[DEBUG] ua missing from clientInfo!"),console.warn("currentPayload:",JSON.stringify(r,null,2)),console.warn("event.data:",JSON.stringify(t.data,null,2)))}if(this._removeEmptyFields(e),!t.qubitData&&!e.qubitData?.[0]?.streamID?.custId){console.error("Missing required field: custId");continue}console.log("About to make network call to:",this._producerURL),console.log("Event payload:",JSON.stringify(e,null,2)),console.log("Making fetch request...");const r=await fetch(this._producerURL,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e)});if(console.log("Fetch request completed"),console.log("Response status:",r.status,r.statusText),!r.ok){const e=await r.text();throw console.error("Server response:",e),new Error(`HTTP error! status: ${r.status}, message: ${e}`)}const a=await r.text();let i=null;if(a&&a.trim())try{i=JSON.parse(a),console.log("Server response data:",i)}catch(e){console.warn("Failed to parse response as JSON:",a),console.warn("Parse error:",e),i={success:!0,message:"Response received but not JSON"}}else console.log("Empty response received from server"),i={success:!0,message:"Empty response received"};this.removeEvent(),this._stats.successfulEvents++,this._stats.totalProcessed++,console.log("Event successfully processed and removed from queue")}catch(e){if(console.error("Error sending event:",e),this._stats.failedEvents++,this._stats.totalProcessed++,t.retryCount=(t.retryCount||0)+1,t.retryCount<this._config.maxRetries){console.log("Scheduling retry for event, attempt:",t.retryCount),this._scheduleRetry(t);continue}console.log("Max retries reached for event, removing from queue")}console.log("Successfully processed batch of",e.length,"events")}catch(e){console.error("Error processing batch:",e)}finally{console.log("Resetting processing state"),this._isProcessing=!1,this.events.length>0&&(console.log("More events in queue, scheduling next batch"),this._scheduleNextBatch())}}else console.log("Empty batch, skipping processing")}_removeEmptyFields(e){for(const t in e)null===e[t]||void 0===e[t]||""===e[t]?delete e[t]:"object"==typeof e[t]&&(this._removeEmptyFields(e[t]),0===Object.keys(e[t]).length&&delete e[t])}_getEventName(e){if(e.eventName)return e.eventName;switch(e.type){case"APP_STATE":return"foreground"===e.state?"APP_FOREGROUND":"APP_BACKGROUND";case"USER_IDENTIFICATION":return"USER_IDENTIFICATION";case"SESSION_START":return"SESSION_START";case"HEART_BEAT":return"STATS";case"USER_SIGN_UP":return"USER_SIGN_UP";case"USER_SIGN_IN":return"USER_SIGN_IN";case"USER_SIGN_OUT":return"USER_SIGN_OUT";case"USER_PROFILE_UPDATE":return"USER_PROFILE_UPDATE";case"USER_PREFERENCE_UPDATE":return"USER_PREFERENCE_UPDATE";case"USER_SESSION_END":return"USER_SESSION_END";case"USER_INFO":return"USER_INFO";case"APP_PERFORMANCE":return"APP_PERFORMANCE";case"SUBSCRIPTION_VIEWED":return"SUBSCRIPTION_VIEWED";case"FEATURE_USAGE":return"FEATURE_USAGE";case"VIDEO_BUFFERING":return"VIDEO_BUFFERING";default:return e.type||""}}_getEventType(e){if(e.eventType)return e.eventType;switch(e.type){case"APP_STATE":return"APP_STATE";case"USER_IDENTIFICATION":return"USER_IDENTIFICATION";case"SESSION_START":return"SESSION_START";case"HEART_BEAT":return"HEART_BEAT";case"USER_SIGN_UP":return"USER_SIGN_UP";case"USER_SIGN_IN":return"USER_SIGN_IN";case"USER_SIGN_OUT":return"USER_SIGN_OUT";case"USER_PROFILE_UPDATE":return"USER_PROFILE_UPDATE";case"USER_PREFERENCE_UPDATE":return"USER_PREFERENCE_UPDATE";case"USER_SESSION_END":return"USER_SESSION_END";case"USER_INFO":return"USER_INFO";case"APP_PERFORMANCE":return"APP_PERFORMANCE";case"SUBSCRIPTION_VIEWED":return"SUBSCRIPTION_VIEWED";case"FEATURE_USAGE":return"FEATURE_USAGE";case"VIDEO_BUFFERING":return"VIDEO_BUFFERING";default:return e.type||""}}_getEventData(e){const t={type:e.type||e.eventType||"",timestamp:e.timestamp||Date.now(),payloadId:e.payloadId||this._generateUUID(),dataSrc:"Application",sessionId:e.sessionId||""};switch(e.type||e.eventType){case"APP_STATE":return{...t,state:e.state,appId:e.appId};case"USER_IDENTIFICATION":return{...t,userId:e.userId,email:e.email,demographics:e.demographics};case"SESSION_START":return{...t,sessionId:e.sessionId};case"HEART_BEAT":return{...t,eventName:"STATS"};default:return t}}_generateUUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}_getScreenResolution(){return"undefined"!=typeof window&&window.screen?`${window.screen.width}x${window.screen.height}`:""}_scheduleRetry(e){const t=this._config.getConfig().retryDelay*Math.pow(2,(e.retryCount||0)-1),r=setTimeout((()=>{this.events.push(e),this._retryTimeouts.delete(e.eventId),this.events.length>=this._config.getConfig().batchSize&&this._flush()}),t);this._retryTimeouts.set(e.eventId,r)}async destroy(){if(this._config){this._flushTimer&&(clearInterval(this._flushTimer),this._flushTimer=null),this.events.length>0&&await this._flush();for(const e of this._retryTimeouts.values())clearTimeout(e);this._retryTimeouts.clear(),r.removeItem("mm_analytics_event_queue")}}_shouldProcessBatch(){return!!this._config&&this.events.length>=this._getBatchSize()}_getBatchSize(){return this._config.getConfig().batchSize}_getRetryDelay(){return this._config.getConfig().retryDelay}_getEndpoint(){return this._producerURL}async _processBatch(){try{const e=this._getBatchSize(),t=this.events.splice(0,e),r=Date.now();await this._sendBatch(t),this._stats.lastProcessTime=Date.now()-r}catch(e){this._handleError(e,"_processBatch")}}async _retryFailedEvents(){try{this._config.getConfig().retryDelay}catch(e){this._handleError(e,"_retryFailedEvents")}}_scheduleNextBatch(){this._isProcessing?console.log("Already processing events, skipping next batch"):(console.log("Scheduling next batch processing"),setTimeout((()=>{this.events.length>0&&(console.log("Processing next batch of",this.events.length,"events"),this._flush())}),this._config.getConfig().flushInterval))}_handleError(e,t){console.error(`Error in EventQueue (${t}):`,e)}}class i{constructor(e,t){if(!e)throw new Error("Event queue is required");this._eventQueue=e,this._config=t,this._producerURL="https://streamproducer-lcrr.mediamelon.com",this._statsInterval=-1,this._heartbeatIntervalId=null,this._isHeartbeatRunning=!1,this._currentPayload=null,this._eventPayloadKeys={streamID:{fields:["customerId","subscriberId","subscriberType","subscriberTag","sessionId","payloadId","dataSrc"],mappings:{customerId:"custId",payloadId:"pId"}},sdkInfo:{fields:["sdkVersion"]},appEventInfo:{fields:["eventName","eventType","eventData","currentScreen","isGraceful"]},userInfo:{fields:["profileId","userData","referralId","referralData"]},clientInfo:{fields:["appName","appVersion","deviceId","deviceType","deviceBrand","deviceModel","deviceMarketingName","osVersion","platform","screenRes","userAgent"],mappings:{screenRes:"scrnRes",userAgent:"ua"}},customTags:{fields:["customTags"]}}}setProducerURL(e){if(!e||"string"!=typeof e)throw new Error("Valid producer URL is required");this._producerURL=e,this._eventQueue.setProducerURL(e)}setStatsInterval(e){if("number"!=typeof e)throw new Error("Stats interval must be a number");this._statsInterval=e}startSendingHeartBeatPayload(){}stopSendingHeartBeatPayload(){this._isHeartbeatRunning=!1,this._heartbeatIntervalId&&(clearInterval(this._heartbeatIntervalId),this._heartbeatIntervalId=null)}updateCurrentPayload(e){if(!e)return void console.warn("MM SDK: Attempting to update current payload with null/undefined value");const t=["customerId","appName","appVersion"].filter((t=>!e[t]));t.length>0&&console.warn(`MM SDK: Missing required fields in payload: ${t.join(", ")}`),this._currentPayload={...this._currentPayload,...e,customerId:e.customerId||this._currentPayload?.customerId||"",appName:e.appName||this._currentPayload?.appName||"",appVersion:e.appVersion||this._currentPayload?.appVersion||"",sdkVersion:e.sdkVersion||this._currentPayload?.sdkVersion||"JSSDK1.0.0",sessionId:e.sessionId||this._currentPayload?.sessionId||"",screenRes:e.screenRes||this._currentPayload?.screenRes||this._getScreenResolution(),custId:e.customerId||e.custId||this._currentPayload?.custId||"",subscriberId:e.subscriberId||this._currentPayload?.subscriberId||"",subscriberType:e.subscriberType||this._currentPayload?.subscriberType||"",subscriberTag:e.subscriberTag||this._currentPayload?.subscriberTag||"",clientInfo:{appName:e.appName||this._currentPayload?.clientInfo?.appName||"",appVersion:e.appVersion||this._currentPayload?.clientInfo?.appVersion||"",scrnRes:e.screenRes||e.scrnRes||this._currentPayload?.clientInfo?.scrnRes||this._getScreenResolution(),ua:e.userAgent||this._currentPayload?.clientInfo?.ua||""},userInfo:{profileId:e.profileId||this._currentPayload?.userInfo?.profileId||"",userData:e.userData||this._currentPayload?.userInfo?.userData||{},referralId:e.referralId||this._currentPayload?.userInfo?.referralId||"",referralData:e.referralData||this._currentPayload?.userInfo?.referralData||{}},customTags:e.customTags||this._currentPayload?.customTags||{}}}publishEvent(e,t){if(!this._currentPayload)return void console.warn("MM SDK: Cannot publish event - current payload is not set");console.log(`[DEBUG] Publishing event: ${e}`),console.log(`[DEBUG] Current payload sessionId: ${this._currentPayload.sessionId}`),console.log(`[DEBUG] Event data sessionId: ${t?.sessionId}`);const r={...this._currentPayload,...t,eventType:e,timestamp:Date.now(),payloadId:this._generateUUID(),pId:this._generateUUID(),dataSrc:"Application"};if(this._currentPayload.customerId&&(r.customerId=this._currentPayload.customerId),console.log(`[DEBUG] Final payload sessionId: ${r.sessionId}`),!r.sessionId){const e=this._config?.getSessionId?.();e?(r.sessionId=e,console.log(`[DEBUG] Using session ID from config: ${e}`)):console.warn("[DEBUG] No session ID available from config or payload")}const a={timestamp:r.timestamp,qubitData:[{streamID:{custId:r.customerId||r.custId||"",subscriberId:t.subscriberId||r.subscriberId||"",subscriberType:t.subscriberType||r.subscriberType||"",subscriberTag:t.subscriberTag||r.subscriberTag||"",sessionId:r.sessionId||"",pId:r.pId||"",dataSrc:"Application"},sdkInfo:{sdkVersion:r.sdkVersion||"JSSDK1.0.0"},appEventInfo:{eventName:this._getEventName(e,t),eventType:this._getEventType(e,t),currentScreen:r.currentScreen||"",isGraceful:r.isGraceful||!1,eventData:this._getEventSpecificData({...r,type:e,customerId:t.customerId},this._getEventType(e,t))},userInfo:{profileId:t.profileId||r.profileId||"",referralId:t.referralId||r.referralId||"",userData:t.userData||r.userData||{},referralData:t.referralData||r.referralData||{}},clientInfo:{appName:r.appName||"",appVersion:r.appVersion||"",deviceId:t.deviceId||r.deviceId||"",deviceType:t.deviceType||r.deviceType||"",deviceBrand:t.deviceBrand||r.deviceBrand||"",deviceModel:t.deviceModel||r.deviceModel||"",deviceMarketingName:t.deviceMarketingName||r.deviceMarketingName||"",osVersion:t.osVersion||r.osVersion||"",platform:t.platform||r.platform||"",scrnRes:r.screenRes||r.scrnRes||this._getScreenResolution(),ua:r.userAgent||r.ua||""},customTags:r.customTags||{}}]};console.log("[DEBUG] Before _removeEmptyFields:",JSON.stringify(a,null,2)),this._removeEmptyFields(a),console.log("[DEBUG] After _removeEmptyFields:",JSON.stringify(a,null,2)),this._eventQueue.addEvent({type:e,qubitData:a.qubitData,timestamp:r.timestamp})}_getEventName(e,t){if(t.eventName)return t.eventName;const r={app_state:e=>"foreground"===e.state?"APP_FOREGROUND":"APP_BACKGROUND",APP_STATE:e=>"foreground"===e.state?"APP_FOREGROUND":"APP_BACKGROUND",user_identification:()=>"USER_IDENTIFICATION",user_preference_change:()=>"USER_PREFERENCE_CHANGE",session_start:()=>"SESSION_START",screen_view:()=>"SCREEN_VIEW",screen_exit:()=>"SCREEN_EXIT",HEART_BEAT:()=>"STATS",user_sign_up:()=>"USER_SIGN_UP",user_sign_in:()=>"USER_SIGN_IN",user_sign_out:()=>"USER_SIGN_OUT",user_profile_update:()=>"USER_PROFILE_UPDATE",user_preference_update:()=>"USER_PREFERENCE_UPDATE",user_session_start:()=>"USER_SESSION_START",user_session_end:()=>"USER_SESSION_END",user_info:()=>"USER_INFO",app_performance:()=>"APP_PERFORMANCE",subscription_viewed:()=>"SUBSCRIPTION_VIEWED",subscription_start:()=>"SUBSCRIPTION_START",subscription_renewal:()=>"SUBSCRIPTION_RENEWAL",subscription_cancellation:()=>"SUBSCRIPTION_CANCELLATION",subscription_upgrade:()=>"SUBSCRIPTION_UPGRADE",subscription_downgrade:()=>"SUBSCRIPTION_DOWNGRADE",payment_initiation:()=>"PAYMENT_INITIATION",payment_success:()=>"PAYMENT_SUCCESS",payment_failure:()=>"PAYMENT_FAILURE",payment_refund:()=>"PAYMENT_REFUND",ad_impression:()=>"AD_IMPRESSION",ad_click:()=>"AD_CLICK",ad_start:()=>"AD_START",ad_complete:()=>"AD_COMPLETE",ad_skip:()=>"AD_SKIP",ad_error:()=>"AD_ERROR",experiment_exposure:()=>"EXPERIMENT_EXPOSURE",experiment_activation:()=>"EXPERIMENT_ACTIVATION",feature_flag_evaluation:()=>"FEATURE_FLAG_EVALUATION",experiment_results:()=>"EXPERIMENT_RESULTS",feature_usage:()=>"FEATURE_USAGE",video_start:()=>"VIDEO_START",video_play:()=>"VIDEO_PLAY",video_pause:()=>"VIDEO_PAUSE",video_resume:()=>"VIDEO_RESUME",video_stop:()=>"VIDEO_STOP",video_complete:()=>"VIDEO_COMPLETE",video_seek:()=>"VIDEO_SEEK",video_buffering:()=>"VIDEO_BUFFERING",video_error:()=>"VIDEO_ERROR",video_quality_change:()=>"VIDEO_QUALITY_CHANGE",video_fullscreen:()=>"VIDEO_FULLSCREEN",video_exit_fullscreen:()=>"VIDEO_EXIT_FULLSCREEN",video_end:()=>"VIDEO_END",video_skip:()=>"VIDEO_SKIP",video_shared:()=>"VIDEO_SHARED",video_bookmarked:()=>"VIDEO_BOOKMARKED",video_liked:()=>"VIDEO_LIKED",video_commented:()=>"VIDEO_COMMENTED",video_rated:()=>"VIDEO_RATED",video_playback_speed_changed:()=>"VIDEO_PLAYBACK_SPEED_CHANGED",user_click:()=>"USER_CLICK",user_scroll:()=>"USER_SCROLL"}[e];return"function"==typeof r?r(t):r||e.toUpperCase()}_getEventType(e,t){if(t.eventType)return t.eventType;if("app_state"===e)return"APP_STATE";const r={app_error:"APP_ERROR",user_identification:"USER_IDENTIFICATION",user_preference_change:"USER_PREFERENCE_CHANGE",session_start:"SESSION_START",screen_view:"SCREEN_VIEW",screen_exit:"SCREEN_EXIT",HEART_BEAT:"HEART_BEAT",user_sign_up:"USER_SIGN_UP",user_sign_in:"USER_SIGN_IN",user_sign_out:"USER_SIGN_OUT",user_profile_update:"USER_PROFILE_UPDATE",user_preference_update:"USER_PREFERENCE_UPDATE",user_session_start:"USER_SESSION_START",user_session_end:"USER_SESSION_END",user_info:"USER_INFO",app_performance:"APP_PERFORMANCE",subscription_viewed:"SUBSCRIPTION_VIEWED",subscription_start:"SUBSCRIPTION_START",subscription_renewal:"SUBSCRIPTION_RENEWAL",subscription_cancellation:"SUBSCRIPTION_CANCELLATION",subscription_upgrade:"SUBSCRIPTION_UPGRADE",subscription_downgrade:"SUBSCRIPTION_DOWNGRADE",payment_initiation:"PAYMENT_INITIATION",payment_success:"PAYMENT_SUCCESS",payment_failure:"PAYMENT_FAILURE",payment_refund:"PAYMENT_REFUND",ad_impression:"AD_IMPRESSION",ad_click:"AD_CLICK",ad_start:"AD_START",ad_complete:"AD_COMPLETE",ad_skip:"AD_SKIP",ad_error:"AD_ERROR",experiment_exposure:"EXPERIMENT_EXPOSURE",experiment_activation:"EXPERIMENT_ACTIVATION",feature_flag_evaluation:"FEATURE_FLAG_EVALUATION",experiment_results:"EXPERIMENT_RESULTS",feature_usage:"FEATURE_USAGE",video_start:"VIDEO_START",video_play:"VIDEO_PLAY",video_pause:"VIDEO_PAUSE",video_resume:"VIDEO_RESUME",video_stop:"VIDEO_STOP",video_complete:"VIDEO_COMPLETE",video_seek:"VIDEO_SEEK",video_buffering:"VIDEO_BUFFERING",video_error:"VIDEO_ERROR",video_quality_change:"VIDEO_QUALITY_CHANGE",video_fullscreen:"VIDEO_FULLSCREEN",video_exit_fullscreen:"VIDEO_EXIT_FULLSCREEN",video_end:"VIDEO_END",video_skip:"VIDEO_SKIP",video_shared:"VIDEO_SHARED",video_bookmarked:"VIDEO_BOOKMARKED",video_liked:"VIDEO_LIKED",video_commented:"VIDEO_COMMENTED",video_rated:"VIDEO_RATED",video_playback_speed_changed:"VIDEO_PLAYBACK_SPEED_CHANGED",user_click:"USER_CLICK",user_scroll:"USER_SCROLL"}[e];return"function"==typeof r?r(t):r||e.toUpperCase()}_getEventSpecificData(e,t){console.log(`[DEBUG] _getEventSpecificData called with eventType: ${t}`);const r={SESSION_START:{sessionId:e.sessionId,startTime:e.startTime||e.timestamp,source:e.source,deviceInfo:e.deviceInfo,appInfo:e.appInfo},SESSION_END:{sessionId:e.sessionId,endTime:e.endTime||e.timestamp,sessionDuration:e.sessionDuration,source:e.source},APP_STATE:{state:e.state,timestamp:e.timestamp,metadata:e.metadata||{},trigger:e.trigger,sessionId:e.sessionId},NAVIGATION:{fromUrl:e.fromUrl,toUrl:e.toUrl,navigationType:e.navigationType,referrer:e.referrer,pageUrl:e.pageUrl},CLICK:{elementId:e.elementId,elementType:e.elementType,pageUrl:e.pageUrl,position:e.position,elementText:e.elementText,elementClass:e.elementClass},SCROLL_DEPTH:{scrollDepth:e.scrollDepth,scrollPercentage:e.scrollPercentage,pageUrl:e.pageUrl,scrollDirection:e.scrollDirection,scrollDistance:e.scrollDistance},PAYMENT_INITIATION:{paymentId:e.paymentId,amount:e.amount,currency:e.currency,method:e.method||e.paymentMethod,status:e.status||"initiated",transactionId:e.transactionId,orderId:e.orderId,customerId:e.customerId},PAYMENT_SUCCESS:{paymentId:e.paymentId,amount:e.amount,currency:e.currency,method:e.method||e.paymentMethod,status:e.status||"completed",transactionId:e.transactionId,receiptUrl:e.receiptUrl},PAYMENT_FAILURE:{paymentId:e.paymentId,amount:e.amount,currency:e.currency,method:e.method||e.paymentMethod,status:e.status||"failed",errorType:e.errorType,message:e.message,metadata:e.metadata||{}},PAYMENT_REFUND:{paymentId:e.paymentId,amount:e.amount,currency:e.currency,method:e.method||e.paymentMethod,status:e.status||"refunded",transactionId:e.transactionId,refundReason:e.refundReason,metadata:e.metadata||{}},SUBSCRIPTION_START:{subscriptionId:e.subscriptionId,planId:e.planId,planName:e.planName,amount:e.amount,currency:e.currency,duration:e.duration,measure:e.measure,status:e.status||"active"},SUBSCRIPTION_RENEWAL:{subscriptionId:e.subscriptionId,planId:e.planId,planName:e.planName,amount:e.amount,currency:e.currency,renewalDate:e.renewalDate,nextRenewalDate:e.nextRenewalDate},SUBSCRIPTION_CANCELLATION:{subscriptionId:e.subscriptionId,planId:e.planId,planName:e.planName,cancellationReason:e.cancellationReason,cancellationDate:e.cancellationDate,endDate:e.endDate},SUBSCRIPTION_EXPIRATION:{subscriptionId:e.subscriptionId,planId:e.planId,planName:e.planName,expirationDate:e.expirationDate,reason:e.reason},SUBSCRIPTION_UPGRADE:{subscriptionId:e.subscriptionId,oldPlanId:e.oldPlanId,oldPlanName:e.oldPlanName,newPlanId:e.newPlanId,newPlanName:e.newPlanName,upgradeReason:e.upgradeReason},SUBSCRIPTION_DOWNGRADE:{subscriptionId:e.subscriptionId,oldPlanId:e.oldPlanId,oldPlanName:e.oldPlanName,newPlanId:e.newPlanId,newPlanName:e.newPlanName,downgradeReason:e.downgradeReason},SUBSCRIPTION_VIEWED:{subscriptionId:e.subscriptionId,planId:e.planId,planName:e.planName,viewSource:e.viewSource,pageUrl:e.pageUrl},AD_IMPRESSION:{adId:e.adId,adType:e.adType,duration:e.duration},AD_CLICK:{adId:e.adId,adType:e.adType},AD_START:{adId:e.adId,adType:e.adType,duration:e.duration},AD_COMPLETE:{adId:e.adId,adType:e.adType,duration:e.duration,completionPercentage:e.completionPercentage},AD_SKIP:{adId:e.adId,adType:e.adType,skipTime:e.skipTime,skipReason:e.skipReason},AD_ERROR:{adId:e.adId,adType:e.adType,errorType:e.errorType,errorMessage:e.errorMessage},EXPERIMENT_EXPOSURE:{experimentId:e.experimentId,experimentName:e.experimentName,variantId:e.variantId,variantName:e.variantName,exposureType:e.exposureType,source:e.source,context:e.context},FEATURE_FLAG_EVALUATION:{experimentId:e.experimentId,experimentName:e.experimentName,variantId:e.variantId,variantName:e.variantName,evaluationType:e.evaluationType,source:e.source,context:e.context},EXPERIMENT_ACTIVATION:{experimentId:e.experimentId,experimentName:e.experimentName,variantId:e.variantId,variantName:e.variantName,activationType:e.activationType,source:e.source,context:e.context},EXPERIMENT_RESULTS:{experimentId:e.experimentId,experimentName:e.experimentName,variantId:e.variantId,variantName:e.variantName,resultType:e.resultType,resultValue:e.resultValue},FEATURE_USAGE:{featureId:e.featureId,featureName:e.featureName,action:e.action,usageType:e.usageType,source:e.source},APP_PERFORMANCE:{loadTime:e.loadTime,renderTime:e.renderTime,memoryUsage:e.memoryUsage,timestamp:e.timestamp,metadata:e.metadata},APP_FOREGROUND:{state:e.state,appId:e.appId,isGraceful:e.isGraceful||!1,timestamp:e.timestamp,metadata:e.metadata},APP_BACKGROUND:{state:e.state,appId:e.appId,isGraceful:e.isGraceful||!1,timestamp:e.timestamp,metadata:e.metadata},APP_ERROR:{errorCode:e.errorCode,errorMessage:e.errorMessage,stackTrace:e.stackTrace,timestamp:e.timestamp,metadata:e.metadata},APP_INTERRUPTION:{interruptionType:e.interruptionType,reason:e.reason,timestamp:e.timestamp,sessionId:e.sessionId,metadata:e.metadata||{}},VIDEO_START:{assetId:e.assetId,assetName:e.assetName,duration:e.duration,position:e.position,quality:e.quality,reason:e.reason},VIDEO_PLAY:{assetId:e.assetId,assetName:e.assetName,position:e.position,quality:e.quality},VIDEO_PAUSE:{assetId:e.assetId,assetName:e.assetName,position:e.position,reason:e.reason},VIDEO_RESUME:{assetId:e.assetId,assetName:e.assetName,position:e.position,quality:e.quality},VIDEO_STOP:{assetId:e.assetId,assetName:e.assetName,position:e.position,reason:e.reason},VIDEO_COMPLETE:{assetId:e.assetId,assetName:e.assetName,duration:e.duration,position:e.position,quality:e.quality},VIDEO_SEEK:{assetId:e.assetId,assetName:e.assetName,fromPosition:e.fromPosition,toPosition:e.toPosition,reason:e.reason},VIDEO_BUFFERING:{assetId:e.assetId,assetName:e.assetName,position:e.position,bufferTime:e.bufferTime,reason:e.reason},VIDEO_ERROR:{assetId:e.assetId,assetName:e.assetName,position:e.position,errorType:e.errorType,errorMessage:e.errorMessage},VIDEO_QUALITY_CHANGE:{assetId:e.assetId,assetName:e.assetName,position:e.position,fromQuality:e.fromQuality,toQuality:e.toQuality,reason:e.reason},VIDEO_QUALITY_CHANGED:{assetId:e.assetId,assetName:e.assetName,position:e.position,fromQuality:e.fromQuality,toQuality:e.toQuality,reason:e.reason},VIDEO_FULLSCREEN:{assetId:e.assetId,assetName:e.assetName,position:e.position,isFullscreen:e.isFullscreen},VIDEO_EXIT_FULLSCREEN:{assetId:e.assetId,assetName:e.assetName,position:e.position,isFullscreen:e.isFullscreen},VIDEO_END:{assetId:e.assetId,assetName:e.assetName,duration:e.duration,position:e.position,reason:e.reason},VIDEO_STATE:{assetId:e.assetId,assetName:e.assetName,state:e.state,position:e.position,quality:e.quality,reason:e.reason,metadata:e.metadata||{}},VIDEO_SKIP:{assetId:e.assetId,assetName:e.assetName,position:e.position,reason:e.reason},VIDEO_SHARED:{assetId:e.assetId,assetName:e.assetName,position:e.position,platform:e.platform,method:e.method},VIDEO_BOOKMARKED:{assetId:e.assetId,assetName:e.assetName,position:e.position,action:e.action},VIDEO_LIKED:{assetId:e.assetId,assetName:e.assetName,position:e.position,action:e.action},VIDEO_COMMENTED:{assetId:e.assetId,assetName:e.assetName,position:e.position,commentLength:e.commentLength,hasAttachment:e.hasAttachment},VIDEO_RATED:{assetId:e.assetId,assetName:e.assetName,position:e.position,rating:e.rating,maxRating:e.maxRating},VIDEO_PLAYBACK_SPEED_CHANGED:{assetId:e.assetId,assetName:e.assetName,position:e.position,fromSpeed:e.fromSpeed,toSpeed:e.toSpeed,reason:e.reason},USER_IDENTIFICATION:{userId:e.userId,email:e.email,name:e.name,age:e.age,location:e.location,userData:e.userData},USER_INFO:{userId:e.userId,email:e.email,name:e.name,age:e.age,location:e.location,userData:e.userData},SUBSCRIBER_INFO:{subscriberId:e.subscriberId,subscriberType:e.subscriberType,subscriberTag:e.subscriberTag,profileId:e.profileId,userData:e.userData},REFERRAL_INFO:{referralId:e.referralId,referralData:e.referralData,source:e.source,campaign:e.campaign,userData:e.userData},USER_SIGN_UP:{userId:e.userId,email:e.email,signUpMethod:e.signUpMethod,source:e.source,userData:e.userData},USER_SIGN_IN:{userId:e.userId,email:e.email,signInMethod:e.signInMethod,source:e.source,userData:e.userData},USER_SIGN_OUT:{userId:e.userId,signOutMethod:e.signOutMethod,sessionDuration:e.sessionDuration,userData:e.userData},USER_SESSION_START:{userId:e.userId,sessionId:e.sessionId,startTime:e.startTime,source:e.source,userData:e.userData},USER_SESSION_END:{userId:e.userId,sessionId:e.sessionId,endTime:e.endTime,sessionDuration:e.sessionDuration,userData:e.userData},USER_PREFERENCE_UPDATE:{userId:e.userId,preferenceType:e.preferenceType,oldValue:e.oldValue,newValue:e.newValue,userData:e.userData},USER_PROFILE_UPDATE:{userId:e.userId,updatedFields:e.updatedFields,oldValues:e.oldValues,newValues:e.newValues,userData:e.userData},USER_CLICK:{userId:e.userId,elementId:e.elementId,elementType:e.elementType,pageUrl:e.pageUrl,userData:e.userData},USER_SCROLL:{userId:e.userId,scrollDirection:e.scrollDirection,scrollDistance:e.scrollDistance,pageUrl:e.pageUrl,userData:e.userData},USER_PREFERENCE_CHANGE:{userId:e.userId,preferenceType:e.preferenceType,oldValue:e.oldValue,newValue:e.newValue,userData:e.userData},USER_INTERACTION:{userId:e.userId,interactionType:e.interactionType,elementId:e.elementId,elementType:e.elementType,pageUrl:e.pageUrl,userData:e.userData},USER_PREFERENCE:{userId:e.userId,preferenceType:e.preferenceType,preferenceValue:e.preferenceValue,pageUrl:e.pageUrl,userData:e.userData},USER_FEEDBACK:{userId:e.userId,feedbackType:e.feedbackType,feedbackValue:e.feedbackValue,feedbackText:e.feedbackText,pageUrl:e.pageUrl,userData:e.userData},SCREEN_VIEW:{screenName:e.screenName||e.currentScreen,screenId:e.screenId,previousScreen:e.previousScreen,screenType:e.screenType,timestamp:e.timestamp,metadata:e.metadata},SCREEN_EXIT:{screenName:e.screenName,screenId:e.screenId,duration:e.duration,timestamp:e.timestamp,metadata:e.metadata},SDK_SHUTDOWN:{timestamp:e.timestamp,sessionId:e.sessionId,reason:e.reason||"normal"},SDK_ERROR:{errorCode:e.errorCode,errorMessage:e.errorMessage,stackTrace:e.stackTrace,timestamp:e.timestamp,sessionId:e.sessionId,metadata:e.metadata||{}},STATS:{timestamp:e.timestamp,sessionId:e.sessionId,statsType:e.statsType||"heartbeat",metadata:e.metadata||{}}};console.log(`[DEBUG] Looking up eventType: '${t}' in eventDataMap`),console.log("[DEBUG] Available keys in eventDataMap:",Object.keys(r));const a=r[t]||{};return console.log(`[DEBUG] _getEventSpecificData returning eventData for ${t}:`,a),this._convertEventDataToStrings(a)}_convertEventDataToStrings(e){console.log("[DEBUG] _convertEventDataToStrings input:",e);const t={};for(const[r,a]of Object.entries(e))"metadata"!==r?null==a?(t[r]="",console.log(`[DEBUG] Converting ${r}: null/undefined -> ''`)):"object"!=typeof a||Array.isArray(a)?Array.isArray(a)?(t[r]=JSON.stringify(a),console.log(`[DEBUG] Converting ${r}: array -> '${JSON.stringify(a)}'`)):(t[r]=String(a),console.log(`[DEBUG] Converting ${r}: ${typeof a} -> '${String(a)}'`)):(t[r]=JSON.stringify(a),console.log(`[DEBUG] Converting ${r}: object -> '${JSON.stringify(a)}'`)):console.log(`[DEBUG] Skipping metadata field: ${r}`);return console.log("[DEBUG] _convertEventDataToStrings output:",t),t}_removeEmptyFields(e){for(const t in e)null===e[t]||void 0===e[t]||""===e[t]?delete e[t]:"object"!=typeof e[t]||Array.isArray(e[t])||(this._removeEmptyFields(e[t]),0===Object.keys(e[t]).length&&delete e[t])}_generateUUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}_getScreenResolution(){return"undefined"!=typeof window&&window.screen?`${window.screen.width}x${window.screen.height}`:""}}class s{constructor(e){this._config=e,this._errorCallbacks=new Map,this._recoveryStrategies=new Map,this._errorHistory=[],this._maxHistorySize=100}handleError(e,t,r={}){const a=this._categorizeError(e,t,r);return this._addToHistory(a),this._recoveryStrategies.has(a.category)&&this._recoveryStrategies.get(a.category)(a),this._notifyErrorCallbacks(a),this._shouldReportError(e)&&this._reportError(a),!0}onError(e,t){this._errorCallbacks.has(e)||this._errorCallbacks.set(e,new Set),this._errorCallbacks.get(e).add(t)}registerRecoveryStrategy(e,t){this._recoveryStrategies.set(e,t)}getErrorHistory(){return[...this._errorHistory]}clearErrorHistory(){this._errorHistory=[]}_categorizeError(e,t,r){let a="unknown",i="error";return"NetworkError"===e.name||e.message.includes("network")?a="network":"ValidationError"===e.name||e.message.includes("validation")?a="validation":"StateError"===e.name||e.message.includes("state")?a="state":"ConfigurationError"===e.name||e.message.includes("config")?a="configuration":("StorageError"===e.name||e.message.includes("storage"))&&(a="storage"),e.critical||e.message.includes("critical")?i="critical":e.warning||e.message.includes("warning")?i="warning":(e.info||e.message.includes("info"))&&(i="info"),{timestamp:Date.now(),category:a,severity:i,context:t,message:e.message,stack:e.stack,...r}}_addToHistory(e){this._errorHistory.unshift(e),this._errorHistory.length>this._maxHistorySize&&this._errorHistory.pop()}_notifyErrorCallbacks(e){this._errorCallbacks.has(e.category)&&this._errorCallbacks.get(e.category).forEach((t=>{try{t(e)}catch(e){console.error("Error in error callback:",e)}})),this._errorCallbacks.has("*")&&this._errorCallbacks.get("*").forEach((t=>{try{t(e)}catch(e){console.error("Error in global error callback:",e)}}))}async _reportError(e){try{const t=this._getErrorEndpoint(),r=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({error:e,metadata:this._config.getEventMetadata()})});if(!r.ok)throw new Error(`Failed to report error: ${r.status}`)}catch(e){console.error("Error reporting to backend:",e)}}_shouldReportError(e){return this._config.getConfig().errorReporting}_getErrorEndpoint(){return this._config.getConfig().errorEndpoint}_createErrorEvent(e,t,r){return{error:e.message,context:t,timestamp:Date.now(),stack:e.stack,metadata:this._config.getEventMetadata()}}}const n={DEBUG:"debug",INFO:"info",WARN:"warn",ERROR:"error"},o={[n.DEBUG]:0,[n.INFO]:1,[n.WARN]:2,[n.ERROR]:3};class d{constructor(e={}){this._config=e,this._logHistory=[],this._logCallbacks=new Map,this._maxHistorySize=e.maxLogHistorySize||1e3,this._enabled=!0,this._currentLevel=n.INFO,this._userId=null}updateConfig(e){this._config=e,this._maxHistorySize=e.maxLogHistorySize||1e3}setUserId(e){this._userId=e}debug(e,t={}){this._log(n.DEBUG,e,t)}info(e,t={}){this._log(n.INFO,e,t)}warn(e,t={}){this._log(n.WARN,e,t)}error(e,t={}){this._log(n.ERROR,e,t)}setLogLevel(e){n[e.toUpperCase()]&&(this._currentLevel=e.toLowerCase())}setEnabled(e){this._enabled=e}onLog(e,t){this._logCallbacks.has(e)||this._logCallbacks.set(e,new Set),this._logCallbacks.get(e).add(t)}_log(e,t,r){if(!this._enabled||o[e]<o[this._currentLevel])return;const a={timestamp:Date.now(),level:e,message:t,data:r,userId:this._userId,context:this._getContext()};this._notifyCallbacks(a),this._consoleOutput(a)}_getContext(){return{sdkVersion:this._config.getAppInfo().sdkVersion,environment:this._config.getConfig().environment,appVersion:this._config.getAppInfo().appVersion,timestamp:Date.now()}}_notifyCallbacks(e){this._logCallbacks.has(e.level)&&this._logCallbacks.get(e.level).forEach((t=>{try{t(e)}catch(e){console.error("Error in log callback:",e)}})),this._logCallbacks.has("*")&&this._logCallbacks.get("*").forEach((t=>{try{t(e)}catch(e){console.error("Error in global log callback:",e)}}))}_consoleOutput(e){const t=new Date(e.timestamp).toISOString(),r=e.userId?`[User: ${e.userId}]`:"",a=`[${t}] [${e.level.toUpperCase()}] ${r} ${e.message}`;switch(e.level){case n.DEBUG:console.debug(a,e.data);break;case n.INFO:console.info(a,e.data);break;case n.WARN:console.warn(a,e.data);break;case n.ERROR:console.error(a,e.data)}}_createLogEntry(e,t,r){return{level:e,message:t,data:r,timestamp:Date.now(),sdkVersion:this._config.getAppInfo().sdkVersion,environment:this._config.getConfig().environment,appVersion:this._config.getAppInfo().appVersion}}}const l="type",c="format",u="range",h="state",p={video:{states:["idle","loading","playing","paused","ended","error"],transitions:{null:["idle","loading","playing"],idle:["loading","playing"],loading:["playing","error"],playing:["paused","ended","error"],paused:["playing","ended"],ended:["idle","loading"],error:["idle"]}},app:{states:["foreground","background"],transitions:{null:["foreground","background"],foreground:["background"],background:["foreground"]}},screen:{states:["active","inactive"],transitions:{null:["active"],active:["inactive"],inactive:["active"]}}};class _{constructor(e={}){if(!e)throw new Error("Config is required for Validator");this._config=e}updateConfig(e){this._config=e}validateInitParams(e){if(!e||"object"!=typeof e)throw this._createError(l,"Initialization parameters must be an object");const{customerId:t,appId:r,appName:a,appVersion:i}=e;this._validateRequired({customerId:t,appId:r,appName:a,appVersion:i}),this._validateType({customerId:{value:t,type:"string"},appId:{value:r,type:"string"},appName:{value:a,type:"string"},appVersion:{value:i,type:"string"}}),this._validateFormat({appVersion:{value:i,pattern:/^\d+\.\d+\.\d+$/}})}validateEventData(e,t){if(!e||"string"!=typeof e)throw this._createError(l,"eventName must be a string");if(!t||"object"!=typeof t)throw this._createError(l,"eventData must be an object");switch(e){case"VIDEO_START":case"VIDEO_PAUSE":case"VIDEO_RESUME":case"VIDEO_SKIP":case"VIDEO_STOP":case"VIDEO_END":case"VIDEO_BUFFERING":case"VIDEO_STATE":this._validateVideoEvent(e,t);break;case"VIDEO_QUALITY_CHANGE":this._validateVideoQualityChange(t);break;case"SCREEN_VIEW":this._validateScreenView(t);break;case"SCREEN_EXIT":this._validateScreenExit(t);break;case"APP_STATE":this._validateAppState(t);break;case"APP_ERROR":case"ERROR":this._validateAppError(t);break;case"APP_PERFORMANCE":case"PERFORMANCE_METRICS":this._validatePerformanceMetrics(t);break;case"SUBSCRIPTION_START":case"SUBSCRIPTION_RENEWAL":case"SUBSCRIPTION_CANCELLATION":case"SUBSCRIPTION":const{type:r,...a}=t;this._validateSubscriptionEvent(e,a);break;case"EXPERIMENT_EXPOSURE":case"EXPERIMENT_ACTIVATION":case"FEATURE_FLAG_EVALUATION":this._validateExperimentEvent(e,t);break;case"USER_INFO":this._validateUserInfo(t);break;case"USER_SIGN_UP":case"USER_SIGN_IN":case"USER_SIGN_OUT":this._validateUserAuth(t);break;case"USER_SESSION_START":case"USER_PREFERENCE_CHANGE":this._validateUserEvent(t);break;case"PAYMENT_SUCCESS":case"PAYMENT_INITIATION":case"PAYMENT_FAILURE":case"PAYMENT_REFUND":this._validatePaymentEvent(t);break;case"AD_IMPRESSION":case"AD_CLICK":case"AD_START":case"AD_COMPLETE":case"AD_SKIP":case"AD_ERROR":this._validateAdEvent(t);break;case"USER_CLICK":this._validateUserClick(t);break;case"USER_SCROLL":this._validateUserSc