mm-app-analytics-js-sdk
Version:
MediaMelon Application Analytics SDK
3 lines • 111 kB
JavaScript
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._validateUserScroll(t);break;case"USER_SESSION_END":this._validateUserSessionEnd(t);break;case"FEATURE_USAGE":this._validateFeatureUsage(t);break;case"custom":this._validateCustomEvent(t);break;default:t.type&&this._validateType({type:{value:t.type,type:"string"}})}}validateStateTransition(e,t,r){if(!r||"string"!=typeof r)throw this._createError(l,"stateType must be a string");if(!t||"string"!=typeof t)throw this._createError(l,"newState must be a string");const a=p[r];if(!a)throw this._createError(h,`Invalid state type: ${r}`);if(!a.states.includes(t))throw this._createError(h,`Invalid state: ${t}. Must be one of: ${a.states.join(", ")}`);const i=e||"null",s=a.transitions[i];if(!s||!s.includes(t))throw this._createError(h,`Invalid transition from ${e||"null"} to ${t} for ${r}`)}validateConfig(e){if(!e||"object"!=typeof e)throw this._createError(l,"Configuration must be an object");this._validateRequired({endpoint:e.endpoint,batchSize:e.batchSize,flushInterval:e.flushInterval}),this._validateType({endpoint:{value:e.endpoint,type:"string"},batchSize:{value:e.batchSize,type:"number"},flushInterval:{value:e.flushInterval,type:"number"},maxRetries:{value:e.maxRetries,type:"number"},retryDelay:{value:e.retryDelay,type:"number"}}),this._validateRange({batchSize:{value:e.batchSize,min:1,max:1e3},flushInterval:{value:e.flushInterval,min:1e3,max:6e4},maxRetries:{value:e.maxRetries,min:0,max:10},retryDelay:{value:e.retryDelay,min:1e3,max:3e4}})}_validateRequired(e){Object.entries(e).forEach((([e,t])=>{if(null==t||""===t)throw this._createError("required",`${e} is required`)}))}_validateType(e){Object.entries(e).forEach((([e,{value:t,type:r}])=>{if(null!=t){const a=typeof t;if(a!==r)throw this._createError(l,`${e} must be of type ${r}, got ${a}`)}}))}_validateFormat(e){Object.entries(e).forEach((([e,{value:t,pattern:r}])=>{if(null!=t&&!r.test(t))throw this._createError(c,`${e} has invalid format`)}))}_validateRange(e){Object.entries(e).forEach((([e,{value:t,min:r,max:a}])=>{if(null!=t&&(t<r||t>a))throw this._createError(u,`${e} must be between ${r} and ${a}`)}))}_validateEnum(e){Object.entries(e).forEach((([e,{value:t,values:r}])=>{if(null!=t&&!r.includes(t))throw this._createError("enum",`${e} must be one of: ${r.join(", ")}`)}))}_validateVideoState(e){this._validateRequired({state:e.state}),this._validateEnum({state:{value:e.state,values:p.video.states}}),void 0!==e.duration&&(this._validateType({duration:{value:e.duration,type:"number"}}),this._validateRange({duration:{value:e.duration,min:0,max:Number.MAX_SAFE_INTEGER}})),void 0!==e.currentTime&&(this._validateType({currentTime:{value:e.currentTime,type:"number"}}),this._validateRange({currentTime:{value:e.currentTime,min:0,max:e.duration||Number.MAX_SAFE_INTEGER}}))}_validateScreenView(e){this._validateRequired({screenName:e.screenName}),this._validateType({screenName:{value:e.screenName,type:"string"},screenId:{value:e.screenId,type:"string"},previousScreen:{value:e.previousScreen,type:"string"}})}_validateScreenExit(e){if(this._validateRequired({screenName:e.screenName,screenId:e.screenId,duration:e.duration}),this._validateType({screenName:{value:e.screenName,type:"string"},screenId:{value:e.screenId,type:"string"},duration:{value:e.duration,type:"number"},timestamp:{value:e.timestamp,type:"number"}}),e.duration<0)throw this._createError(u,`duration must be non-negative, got: ${e.duration}`);e.metadata&&this._validateType({metadata:{value:e.metadata,type:"object"}})}_validateAppState(e){this._validateRequired({state:e.state}),this._validateEnum({state:{value:e.state,values:p.app.states}}),void 0!==e.timestamp&&this._validateType({timestamp:{value:e.timestamp,type:"number"}})}_validateAppError(e){this._validateRequired({errorCode:e.errorCode,errorMessage:e.errorMessage}),this._validateType({errorCode:{value:e.errorCode,type:"string"},errorMessage:{value:e.errorMessage,type:"string"},stackTrace:{value:e.stackTrace,type:"string"},timestamp:{value:e.timestamp,type:"number"}}),e.metadata&&this._validateType({metadata:{value:e.metadata,type:"object"}})}_validateUserInfo(e){this._validateRequired({userId:e.userId}),this._validateType({userId:{value:e.userId,type:"string"},userType:{value:e.userType,type:"string"},deviceId:{value:e.deviceId,type:"string"}})}_validateUserAuth(e){if(this._validateRequired({userId:e.userId,email:e.email}),this._validateType({userId:{value:e.userId,type:"string"},email:{value:e.email,type:"string"},timestamp:{value:e.timestamp,type:"number"}}),!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e.email))throw this._createError(c,`Invalid email format: ${e.email}`);e.metadata&&this._validateType({metadata:{value:e.metadata,type:"object"}})}_validateUserEvent(e){this._validateRequired({userId:e.userId}),this._validateType({userId:{value:e.userId,type:"string"},timestamp:{value:e.timestamp,type:"number"}}),e.metadata&&this._validateType({metadata:{value:e.metadata,type:"object"}})}_validatePaymentEvent(e){this._validateRequired({paymentId:e.paymentId,amount:e.amount,currency:e.currency}),this._validateType({paymentId:{value:e.paymentId,type:"string"},amount:{value:e.amount,type:"number"},currency:{value:e.currency,type:"string"},timestamp:{value:e.timestamp,type:"number"}}),e.metadata&&this._validateType({metadata:{value:e.metadata,type:"object"}})}_validateAdEvent(e){this._validateRequired({adId:e.adId,adType:e.adType}),this._validateType({adId:{value:e.adId,type:"string"},adType:{value:e.adType,type:"string"},adUnit:{value:e.adUnit,type:"string"},adNetwork:{value:e.adNetwork,type:"string"},duration:{value:e.duration,type:"number"},timestamp:{value:e.timestamp,type:"number"}}),e.metadata&&this._validateType({metadata:{value:e.metadata,type:"object"}}),e.clickPosition&&this._validateType({"clickPosition.x":{value:e.clickPosition.x,type:"number"},"clickPosition.y":{value:e.clickPosition.y,type:"number"}}),e.errorType&&this._validateType({errorType:{value:e.errorType,type:"string"},message:{value:e.message,type:"string"}})}_validateCustomEvent(e){this._validateRequired({eventName:e.eventName}),this._validateType({eventName:{value:e.eventName,type:"string"}}),void 0!==e.eventData&&this._validateType({eventData:{value:e.eventData,type:"object"}})}_validateVideoEvent(e,t){if(this._validateRequired({assetId:t.assetId,assetName:t.assetName,duration:t.duration,position:t.position,quality:t.quality,reason:t.reason}),this._validateType({assetId:{value:t.assetId,type:"string"},assetName:{value:t.assetName,type:"string"},duration:{value:t.duration,type:"number"},position:{value:t.position,type:"number"},quality:{value:t.quality,type:"string"},reason:{value:t.reason,type:"string"}}),this._validateRange({duration:{value:t.duration,min:0,max:Number.MAX_SAFE_INTEGER},position:{value:t.position,min:0,max:t.duration||Number.MAX_SAFE_INTEGER}}),t.metadata){this._validateType({metadata:{value:t.metadata,type:"object"}});const e=["playbackSpeed","bufferingTime","bitrate","resolution","playerVersion","playerType","category","language","subtitles","reason"];Object.keys(t.metadata).forEach((t=>{if(!e.includes(t))throw this._createError(c,`Invalid metadata field: ${t}. Must be one of: ${e.join(", ")}`)})),void 0!==t.metadata.playbackSpeed&&this._validateType({"metadata.playbackSpeed":{value:t.metadata.playbackSpeed,type:"number"}}),void 0!==t.metadata.bufferingTime&&this._validateType({"metadata.bufferingTime":{value:t.metadata.bufferingTime,type:"number"}}),void 0!==t.metadata.bitrate&&this._validateType({"metadata.bitrate":{value:t.metadata.bitrate,type:"number"}}),void 0!==t.metadata.resolution&&this._validateType({"metadata.resolution":{value:t.metadata.resolution,type:"string"}}),void 0!==t.metadata.playerVersion&&this._validateType({"metadata.playerVersion":{value:t.metadata.playerVersion,type:"string"}}),void 0!==t.metadata.playerType&&this._validateType({"metadata.playerType":{value:t.metadata.playerType,type:"string"}})}}_validateVideoQualityChange(e){if(this._validateRequired({assetId:e.assetId,assetName:e.assetName,quality:e.quality,reason:e.reason}),this._validateType({assetId:{value:e.assetId,type:"string"},assetName:{value:e.assetName,type:"string"},quality:{value:e.quality,type:"string"},reason:{value:e.reason,type:"string"}}),e.metadata){this._validateType({metadata:{value:e.metadata,type:"object"}});const t=["playbackSpeed","bufferingTime","bitrate","resolution","playerVersion","playerType","previousQuality"];Object.keys(e.metadata).forEach((e=>{if(!t.includes(e))throw this._createError(c,`Invalid metadata field: ${e}. Must be one of: ${t.join(", ")}`)})),void 0!==e.metadata.previousQuality&&this._validateType({"metadata.previousQuality":{value:e.metadata.previousQuality,type:"string"}})}}_validatePerformanceMetrics(e){this._validateRequired({timestamp:e.timestamp,metrics:e.metrics}),this._validateType({timestamp:{value:e.timestamp,type:"number"},metrics:{value:e.metrics,type:"object"}});const t=["memoryUsage","cpuUsage","networkLatency","frameRate","loadTime","renderTime","jsHeapSize","jsHeapSizeLimit"];Object.keys(e.metrics).forEach((r=>{if(!t.includes(r))throw this._createError(c,`Invalid metric field: ${r}. Must be one of: ${t.join(", ")}`);this._validateType({[`metrics.${r}`]:{value:e.metrics[r],type:"number"}})})),e.metadata&&this._validateType({metadata:{value:e.metadata,type:"object"}})}_validateSubscriptionEvent(e,t){if(this._validateRequired({subscriptionId:t.subscriptionId,planId:t.planId,planName:t.planName,amount:t.amount,currency:t.currency,duration:t.duration,measure:t.measure,status:t.status}),this._validateType({subscriptionId:{value:t.subscriptionId,type:"string"},planId:{value:t.planId,type:"string"},planName:{value:t.planName,type:"string"},amount:{value:t.amount,type:"number"},currency:{value:t.currency,type:"string"},duration:{value:t.duration,type:"number"},measure:{value:t.measure,type:"string"},status:{value:t.status,type:"string"}}),t.metadata){this._validateType({metadata:{value:t.metadata,type:"object"}});const e=["paymentMethod","autoRenew","trialPeriod","startDate","endDate","cancellationReason","source"];Object.keys(t.metadata).forEach((t=>{if(!e.includes(t))throw this._createError(c,`Invalid metadata field: ${t}. Must be one of: ${e.join(", ")}`)}))}}_validateExperimentEvent(e,t){if(this._validateRequired({experimentId:t.experimentId,experimentName:t.experimentName,variantId:t.variantId,variantName:t.variantName,timestamp:t.timestamp}),this._validateType({experimentId:{value:t.experimentId,type:"string"},experimentName:{value:t.experimentName,type:"string"},variantId:{value:t.variantId,type:"string"},variantName:{value:t.variantName,type:"string"},timestamp:{value:t.timestamp,type:"number"}}),t.metadata){this._validateType({metadata:{value:t.metadata,type:"object"}});const e=["exposureType","source","context","activationType","sessionId"];Object.keys(t.metadata).forEach((t=>{if(!e.includes(t))throw this._createError(c,`Invalid metadata field: ${t}. Must be one of: ${e.join(", ")}`)})),t.metadata.context&&this._validateType({"metadata.context":{value:t.metadata.context,type:"object"}})}}_validateUserClick(e){this._validateRequired({elementId:e.elementId,elementType:e.elementType}),this._validateType({elementId:{value:e.elementId,type:"string"},elementType:{value:e.elementType,type:"string"},pageUrl:{value:e.pageUrl,type:"string"},position:{value:e.position,type:"object"},timestamp:{value:e.timestamp,type:"number"}}),e.position&&this._validateType({"position.x":{value:e.position.x,type:"number"},"position.y":{value:e.position.y,type:"number"}})}_validateUserScroll(e){this._validateRequired({scrollDepth:e.scrollDepth}),this._validateType({scrollDepth:{value:e.scrollDepth,type:"number"},scrollPercentage:{value:e.scrollPercentage,type:"number"},pageUrl:{value:e.pageUrl,type:"string"},timestamp:{value:e.timestamp,type:"number"}}),void 0!==e.scrollPercentage&&this._validateRange({scrollPercentage:{value:e.scrollPercentage,min:0,max:100}})}_validateUserSessionEnd(e){this._validateRequired({userId:e.userId,sessionId:e.sessionId,timestamp:e.timestamp}),this._validateType({userId:{value:e.userId,type:"string"},sessionId:{value:e.sessionId,type:"string"},timestamp:{value:e.timestamp,type:"number"}}),e.metadata&&this._validateType({metadata:{value:e.metadata,type:"object"}})}_validateFeatureUsage(e){this._validateRequired({featureId:e.featureId,featureName:e.featureName,action:e.action}),this._validateType({featureId:{value:e.featureId,type:"string"},featureName:{value:e.featureName,type:"string"},action:{value:e.action,type:"string"},timestamp:{value:e.timestamp,type:"number"}}),e.metadata&&this._validateType({metadata:{value:e.metadata,type:"object"}})}_createError(e,t){const r=new Error(t);return r.type=e,r}}class g{constructor(e){if(!e)throw new Error("Dependencies are required for tracker initialization");const{config:t,eventPublisher:r,logger:a,validator:i,errorHandler:s,stateManager:n}=e;if(!t)throw new Error("Config is required");if(!r)throw new Error("Event publisher is required");if(!a)throw new Error("Logger is required");if(!i)throw new Error("Validator is required");if(!s)throw new Error("Error handler is required");this._config=t,this._eventPublisher=r,this._logger=a,this._validator=i,this._errorHandler=s,this._stateManager=n}updateConfig(e){this._config=e}_createEventData(e){const t=this._config.getDeviceInfo(),r=this._config.getAppInfo();return{...e,timestamp:this._getTimestamp(),sessionId:this._config.getSessionId(),deviceInfo:t,appInfo:r,deviceId:t?.deviceId||"",deviceType:t?.deviceType||"",deviceBrand:t?.deviceBrand||"",deviceModel:t?.deviceModel||"",deviceMarketingName:t?.deviceMarketingName||"",osVersion:t?.osVersion||"",platform:t?.platform||"",profileId:this._config.get&&this._config.get("profileId")||"",userData:this._config.get&&this._config.get("userData")||{},referralId:this._config.get&&this._config.get("referralId")||"",referralData:this._config.get&&this._config.get("referralData")||{},subscriberId:this._config.get&&this._config.get("subscriberId")||"",subscriberType:this._config.get&&this._config.get("subscriberType")||"",subscriberTag:this._config.get&&this._config.get("subscriberTag")||"",pId:this._config.get&&this._config.get("pId")||this._config.get&&this._config.get("profileId")||""}}_publishEvent(e,t){try{this._eventPublisher.publishEvent(e,t),this._logger.debug(`Event published: ${e}`,t)}catch(t){this._handleError(t,"_publishEvent",`${e}_error`)}}_handleError(e,t,r="tracker_error"){this._logger.error(`Error in ${t}:`,e),this._errorHandler.handleError(e,t,{eventType:r,tracker:this.constructor.name})}_getTimestamp(){return Date.now()}}class E extends g{constructor(e){super({...e,stateManager:e.stateManager||new t})}reportVideoStart(e){try{this._validator.validateEventData("VIDEO_START",e);const t=this._createEventData({...e,timestamp:Date.now()});this._publishEvent("VIDEO_START",t),this._logger.debug("Video start reported",t)}catch(e){this._handleError(e,"reportVideoStart","video_error")}}reportVideoPause(e){try{this._validator.validateEventData("VIDEO_PAUSE",e);const t=this._createEventData({...e,timestamp:Date.now()});this._publishEvent("VIDEO_PAUSE",t),this._logger.debug("Video pause reported",t)}catch(e){this._handleError(e,"reportVideoPause","video_error")}}reportVideoResume(e){try{this._validator.validateEventData("VIDEO_RESUME",e);const t=this._createEventData({...e,timestamp:Date.now()});this._publishEvent("VIDEO_RESUME",t),this._logger.debug("Video resume reported",t)}catch(e){this._handleError(e,"reportVideoResume","video_error")}}reportVideoSkip(e){try{this._validator.validateEventData("VIDEO_SKIP",e);const t=this._createEventData({...e,timestamp:Date.now()});this._publishEvent("VIDEO_SKIP",t),this._logger.debug("Video skip reported",t)}catch(e){this._handleError(e,"reportVideoSkip","video_error")}}reportVideoStop(e){try{this._validator.validateEventData("VIDEO_STOP",e);const t=this._createEventData({...e,timestamp:Date.now()});this._publishEvent("VIDEO_STOP",t),this._logger.debug("Video stop reported",t)}catch(e){this._handleError(e,"reportVideoStop","video_error")}}reportVideoEnd(e){try{this._validator.validateEventData("VIDEO_END",e);const t=this._createEventData({...e,timestamp:Date.now()});this._publishEvent("VIDEO_END",t),this._logger.debug("Video end reported",t)}catch(e){this._handleError(e,"reportVideoEnd","video_error")}}reportVideoQualityChange(e){try{this._validator.validateEventData("VIDEO_QUALITY_CHANGE",e);const t=this._createEventData(e);this._publishEvent("VIDEO_QUALITY_CHANGE",t),this._logger.debug("Video quality change reported",t)}catch(e){throw this._handleError(e,"reportVideoQualityChange","video_error"),e}}reportVideoBuffering(e){try{this._validator.validateEventData("VIDEO_BUFFERING",e);const t=this._createEventData({...e,timestamp:Date.now()});this._publishEvent("VIDEO_BUFFERING",t),this._logger.debug("Video buffering reported",t)}catch(e){throw this._handleError(e,"reportVideoBuffering","video_error"),e}}reportVideoSeek(e){try{this._validator.validateEventData("VIDEO_SEEK",e);const t=this._createEventData({...e,timestamp:Date.now()});this._publishEvent("VIDEO_SEEK",t),this._logger.debug("Video seek reported",t)}catch(e){this._handleError(e,"reportVideoSeek","video_error")}}reportVideoFullscreen(e){try{this._validator.validateEventData("VIDEO_FULLSCREEN",e);const t=this._createEventData({...e,timestamp:Date.now()});this._publishEvent("VIDEO_FULLSCREEN",t),this._logger.debug("Video fullscreen reported",t)}catch(e){this._handleError(e,"reportVideoFullscreen","video_error")}}reportVideoExitFullscreen(e){try{this._validator.validateEventData("VIDEO_EXIT_FULLSCREEN",e);const t=this._createEventData({...e,timestamp:Date.now()});this._publishEvent("VIDEO_EXIT_FULLSCREEN",t),this._logger.debug("Video exit fullscreen reported",t)}catch(e){this._handleError(e,"reportVideoExitFullscreen","video_error")}}reportVideoState(e){try{if(this._validator.validateEventData("VIDEO_STATE",e),e.state){const t=this._stateManager.getVideoState();if(this._validator.validateStateTransition(t,e.state,"video"),!this._stateManager.updateVideoState(e.state,e))throw new Error("Invalid state transition")}const t=this._createEventData({...e,timestamp:Date.now()});this._publishEvent("VIDEO_STATE",t),this._logger.debug("Video state reported",t)}catch(e){throw this._handleError(e,"reportVideoState","video_error"),e}}getVideoState(){return this._stateManager.getVideoState()}}class v extends g{constructor(e){super(e)}reportScreenView(e){try{this._validator.validateEventData("SCREEN_VIEW",e);const t=this._createEventData(e);this._publishEvent("SCREEN_VIEW",t),this._logger.debug("Screen view reported",t)}catch(e){throw this._handleError(e,"reportScreenView","screen_error"),e}}reportScreenExit(e){try{this._validator.validateEventData("screen_exit",e);const t=this._createEventData(e);this._publishEvent("screen_exit",t),this._logger.debug("Screen exit reported",t)}catch(e){throw this._handleError(e,"reportScreenExit","screen_error"),e}}getScreenState(){return this._stateManager.getScreenState()}}const m="VIDEO_SHARED",I="VIDEO_BOOKMARKED",f="VIDEO_LIKED",y="VIDEO_COMMENTED",S="VIDEO_RATED",T="VIDEO_QUALITY_CHANGED",b="VIDEO_PLAYBACK_SPEED_CHANGED",D="APP_STATE",R="APP_ERROR",N="APP_PERFORMANCE",w="USER_SIGN_UP",U="USER_SESSION_START",P="USER_SESSION_END",A="USER_PREFERENCE_UPDATE",O="USER_PROFILE_UPDATE",C="SUBSCRIPTION_START",V="SUBSCRIPTION_RENEWAL",k="SUBSCRIPTION_CANCELLATION",x="SUBSCRIPTION_UPGRADE",M="SUBSCRIPTION_DOWNGRADE",F="SUBSCRIPTION_EXPIRATION",L="PAYMENT_SUCCESS",B="PAYMENT_INITIATION",z="PAYMENT_FAILURE",G="PAYMENT_REFUND",H="AD_START",q="AD_COMPLETE",j="AD_ERROR",K="AD_IMPRESSION",$="AD_CLICK",Q="AD_SKIP",W="EXPERIMENT_EXPOSURE";class Y extends g{constructor(e){super(e)}reportAppState(e){try{this._validator.validateEventData(D,e);const t=this._createEventData(e);this._publishEvent(D,t),this._logger.debug("Application state reported",t)}catch(e){this._handleError(e,"reportAppState","app_error")}}reportAppError(e){try{this._validator.validateEventData(R,e);const t=this._createEventData(e);this._publishEvent(R,t),this._logger.debug("Application error reported",t)}catch(e){this._handleError(e,"reportAppError","app_error")}}reportPerformanceMetrics(e){try{this._validator.validateEventData(N,e);const t=this._createEventData(e);this._publishEvent(N,t),this._logger.debug("Application performance metrics reported",t)}catch(e){this._handleError(e,"reportPerformanceMetrics","app_error")}}getAppState(){return this._stateManager.getAppState()}_validateAppData(e,t){if(!e||"object"!=typeof e)throw new Error("Invalid application data");this._validator.validateEventData(t,e)}}class X extends g{constructor(e){super(e)}reportUserIdentification(e){try{this._validator.validateEventData(w,e);const t=this._createEventData(e);this._publishEvent(w,t)}catch(e){this._handleError(e,"reportUserIdentification","user_error")}}reportUserProfileUpdate(e){try{this._validator.validateEventData(O,e);const t=this._createEventData(e);this._publishEvent(O,t)}catch(e){this._handleError(e,"reportUserProfileUpdate","user_error")}}reportUserPreferenceUpdate(e){try{this._validator.validateEventData(A,e);const t=this._createEventData(e);this._publishEvent(A,t)}catch(e){this._handleError(e,"reportUserPreferenceUpdate","user_error")}}reportUserSessionEnd(e){try{this._validator.validateEventData(P,e);const t=this._createEventData(e);this._publishEvent(P,t)}catch(e){this._handleError(e,"reportUserSessionEnd","user_error")}}reportUserSessionStart(e){try{this._validator.validateEventData(U,e);const t=this._createEventData(e);this._publishEvent(U,t)}catch(e){this._handleError(e,"reportUserSessionStart","user_error")}}reportUserPreferenceChange(e){try{this._validator.validateEventData(A,e);const t=this._createEventData(e);this._publishEvent(A,t)}catch(e){this._handleError(e,"reportUserPreferenceChange","user_error")}}}class J{constructor(e){this.sdk=e}reportSubscriberInfo(e){if(!e||"object"!=typeof e)throw new Error("data must be an object");if(!e.subscriberId||"string"!=typeof e.subscriberId)throw new Error("data.subscriberId must be a string");if(!e.planType||"string"!=typeof e.planType)throw new Error("data.planType must be a string");if(!e.segment||"string"!=typeof e.segment)throw new Error("data.segment must be a string");if(!e.profileId||"string"!=typeof e.profileId)throw new Error("data.profileId must be a string");this.sdk._eventPublisher.publishEvent("SUBSCRIBER_INFO",{...e,timestamp:Date.now()})}reportReferralInfo(e){if(!e||"object"!=typeof e)throw new Error("data must be an object");if(!e.referralId||"string"!=typeof e.referralId)throw new Error("data.referralId must be a string");if(!e.source||"string"!=typeof e.source)throw new Error("data.source must be a string");if(!e.medium||"string"!=typeof e.medium)throw new Error("data.medium must be a string");if(!e.campaign||"string"!=typeof e.campaign)throw new Error("data.campaign must be a string");this.sdk._eventPublisher.publishEvent("REFERRAL_INFO",{...e,timestamp:Date.now()})}}class Z{constructor(e){const{config:t,eventPublisher:r,logger:a,validator:i,errorHandler:s,stateManager:n}=e;if(!t)throw new Error("Config is required");if(!r)throw new Error("Event publisher is required");if(!a)throw new Error("Logger is required");if(!i)throw new Error("Validator is required");if(!s)throw new Error("Error handler is required");if(!n)throw new Error("State manager is required");this._config=t,this._eventPublisher=r,this._logger=a,this._validator=i,this._errorHandler=s,this._stateManager=n,this._enabled=!1,this._isTracking=!1,this._lastActivity=Date.now(),this._activityTimeout=null,this._sessionTimeout=null,this._sessionStartTime=null,this._lastActivityTime=null,this._currentPath=null,this._previousPath=null,this._navigationStartTime=null,this._clickCount=0,this._lastClickTime=null,this._scrollDepth=0,this._maxScrollDepth=0,this._scrollStartTime=null,this._boundHandleSessionStart=this._handleSessionStart.bind(this),this._boundHandleSessionEnd=this._handleSessionEnd.bind(this),this._boundHandleNavigation=this._handleNavigation.bind(this),this._boundHandleClick=this._handleClick.bind(this),this._boundHandleScroll=this._handleScroll.bind(this)}_initializeEventListeners(){if("undefined"!=typeof window){if(window.addEventListener("load",this._boundHandleSessionStart),window.addEventListener("beforeunload",this._boundHandleSessionEnd),window.addEventListener("popstate",this._boundHandleNavigation),"undefined"!=typeof history){const e=history.pushState;history.pushState=(...t)=>{e.apply(history,t),this._boundHandleNavigation()}}document.addEventListener("click",this._boundHandleClick),window.addEventListener("scroll",this._boundHandleScroll)}}_handleSessionStart(){if(console.log("[AUTO-COLLECTION] _handleSessionStart called, _enabled:",this._enabled),this._enabled&&!this._isTracking){this._isTracking=!0,this._lastActivity=Date.now(),this._resetTimers();try{this._sessionStartTime=Date.now(),this._lastActivityTime=this._sessionStartTime;const e=this._createEventData("session_start",{sessionId:this._config.getSessionId(),deviceInfo:this._config.getDeviceInfo(),appInfo:this._config.getAppInfo()});this._eventPublisher.publishEvent("session_start",e),this._logger.debug("Session started",{sessionId:this._config.getSessionId()})}catch(e){this._handleError(e,"session_start")}}}_handleSessionEnd(){if(this._enabled&&this._isTracking)try{const e=Date.now()-this._sessionStartTime,t=this._createEventData("session_end",{sessionId:this._config.getSessionId(),deviceInfo:this._config.getDeviceInfo(),appInfo:this._config.getAppInfo(),duration:e});this._eventPublisher.publishEvent("session_end",t),this._logger.debug("Session ended",{sessionId:this._config.getSessionId()}),this._isTracking=!1,this._clearTimers()}catch(e){this._handleError(e,"session_end")}}_handleNavigation(){if(this._enabled)try{const e=window.location.pathname;if(e===this._currentPath)return;this._previousPath=this._currentPath,this._currentPath=e,this._navigationStartTime=Date.now();const t=this._createEventData("navigation",{currentPath:this._currentPath,previousPath:this._previousPath,referrer:document.referrer});this._eventPublisher.publishEvent("navigation",t),this._logger.debug("Navigation tracked",{path:this._currentPath})}catch(e){this._handleError(e,"navigation")}}_handleClick(e){if(console.log("[AUTO-COLLECTION] _handleClick called, _enabled:",this._enabled),this._enabled)try{this._clickCount++,this._lastClickTime=Date.now(),this._lastActivityTime=this._lastClickTime;const t=e.target,r=this._createEventData("click",{position:{x:e.clientX,y:e.clientY},target:{tagName:t.tagName,id:t.id,className:t.className,text:t.textContent?.trim().substring(0,100),href:t.href,type:t.type}});this._eventPublisher.publishEvent("click",r),this._logger.debug("Click tracked",{position:{x:e.clientX,y:e.clientY}})}catch(e){this._handleError(e,"click")}}_handleScroll(){if(this._enabled)if(this._config&&this._logger&&this._eventPublisher)try{const e=window.pageYOffset||document.documentElement.scrollTop,t=document.documentElement.scrollHeight||document.body.scrollHeight,r=document.documentElement.clientHeight;if(t<=0||r<=0)return;const a=(e+r)/t*100;if(a>this._maxScrollDepth){this._maxScrollDepth=a,this._scrollStartTime=this._scrollStartTime||Date.now(),this._lastActivityTime=Date.now();const i=this._createEventData("scroll_depth",{depth:a,scrollTop:e,scrollHeight:t,clientHeight:r});this._eventPublisher.publishEvent("scroll_depth",i),this._logger.debug("Scroll tracked",{depth:a})}}catch(e){this._handleError(e,"scroll")}else console.warn("AutoCollectionManager not fully initialized")}_handleError(e,t){try{const r=e instanceof Error?e.message:String(e);this._logger&&this._logger.error(`Error in ${t}:`,e),this._eventPublisher&&this._eventPublisher.publishEvent("auto_collection_error",{error:r,context:t,timestamp:Date.now()})}catch(r){console.error("Error in error handler:",r),console.error("Original error:",e),console.error("Context:",t)}}getSessionInfo(){return{sessionId:this._config.getSessionId(),startTime:this._sessionStartTime,lastActivityTime:this._lastActivityTime,clickCount:this._clickCount,maxScrollDepth:this._maxScrollDepth}}getNavigationInfo(){return{currentPath:this._currentPath,previousPath:this._previousPath,navigationStartTime:this._navigationStartTime}}setEnabled(e){console.log("[AUTO-COLLECTION] setEnabled called with:",e),this._enabled=e,e?(console.log("[AUTO-COLLECTION] Initializing event listeners"),this._initializeEventListeners()):(console.log("[AUTO-COLLECTION] Removing event listeners"),this._removeEventListeners())}_removeEventListeners(){"undefined"!=typeof window&&(window.removeEventListener("load",this._boundHandleSessionStart),window.removeEventListener("beforeunload",this._boundHandleSessionEnd),window.removeEventListener("popstate",this._boundHandleNavigation),document.removeEventListener("click",this._boundHandleClick),window.removeEventListener("scroll",this._boundHandleScroll))}_resetTimers(){this._activityTimeout=setTimeout((()=>{this._endSession()}),this._config.getActivityTimeout()),this._sessionTimeout=setTimeout((()=>{this._endSession()}),this._config.getSessionTimeout())}_clearTimers(){clearTimeout(this._activityTimeout),clearTimeout(this._sessionTimeout)}_createEventData(e,t={}){return{timestamp:Date.now(),sessionId:this._config.getSessionId(),deviceInfo:this._config.getDeviceInfo(),appInfo:this._config.getAppInfo(),...t}}}class ee extends g{constructor(e){super(e)}reportSubscriptionStart(e){try{this._validator.validateEventData(C,e);const t=this._createEventData(e);this._publishEvent(C,t)}catch(e){this._handleError(e,"reportSubscriptionStart","subscription_error")}}reportSubscriptionRenewal(e){try{const{metadata:t,...r}=e,a={paymentMethod:t?.paymentMethod,autoRenew:t?.autoRenew,trialPeriod:t?.trialPeriod,startDate:t?.renewalDate||t?.startDate,endDate:t?.nextRenewalDate||t?.endDate},i=this._createEventData({...r,metadata:a});this._validator.validateEventData(V,i),this._publishEvent(V,i)}catch(e){this._handleError(e,"reportSubscriptionRenewal","subscription_error")}}reportSubscriptionCancellation(e){try{const{metadata:t,...r}=e,a={paymentMethod:t?.paymentMethod,autoRenew:t?.autoRenew,trialPeriod:t?.trialPeriod,startDate:t?.startDate,endDate:t?.cancellationDate||t?.endDate,cancellationReason:t?.reason||t?.cancellationReason},i=this._createEventData({...r,metadata:a});this._validator.validateEventData(k,i),this._publishEvent(k,i)}catch(e){this._handleError(e,"reportSubscriptionCancellation","subscription_error")}}reportSubscriptionExpiration(e){try{this._validator.validateEventData(F,e);const t=this._createEventData(e);this._publishEvent(F,t)}catch(e){this._handleError(e,"reportSubscriptionExpiration","subscription_error")}}reportSubscriptionUpgrade(e){try{this._validator.validateEventData(x,e);const t=this._createEventData(e);this._publishEvent(x,t)}catch(e){this._handleError(e,"reportSubscriptionUpgrade","subscription_error")}}reportSubscriptionDowngrade(e){try{this._validator.validateEventData(M,e);const t=this._createEventData(e);this._publishEvent(M,t)}catch(e){this._handleError(e,"reportSubscriptionDowngrade","subscription_error")}}reportSubscriptionViewed(e){try{if(!e||"object"!=typeof e)throw new Error("data must be an object");if(!e.planId||"string"!=typeof e.planId)throw new Error("data.planId must be a string");const t=this._createEventData(e);this._validator.validateEventData("SUBSCRIPTION_VIEWED",t),this._publishEvent("SUBSCRIPTION_VIEWED",t)}catch(e){this._handleError(e,"reportSubscriptionViewed","subscription_error")}}getSubscriptionState(){return this._stateManager.getSubscriptionState()}_validateSubscriptionData(e){if(!e||"object"!=typeof e)throw new Error("Invalid subscription data");const t=["subscriptionId","planId","planName","amount","currency","duration","measure","status"];for(const r of t)if(!e[r])throw new Error(`Missing required field: ${r}`);if(e.metadata){const t=["trialPeriod","renewalDate","cancellationDate","paymentMethod","billingCycle","discountCode","promotionId"];for(const r of Object.keys(e.metadata))if(!t.includes(r))throw new Error(`Invalid metadata field: ${r}`)}}}class te extends g{constructor(e){super(e)}reportPaymentInitiation(e){try{this._validator.validateEventData(B,e);const t=this._createEventData(e);this._publishEvent(B,t),this._stateManager.updatePaymentState("initiated",e),this._logger.debug("Payment initiation reported",e)}catch(e){this._handleError(e,"reportPaymentInitiation","payment_error")}}reportPaymentSuccess(e){try{this._validator.validateEventData(L,e);const t=this._createEventData(e);this._publishEvent(L,t),this._stateManager.updatePaymentState("success",e),this._logger.debug("Payment success reported",e)}catch(e){this._handleError(e,"reportPaymentSuccess","payment_error")}}reportPaymentFailure(e){try{this._validator.validateEventData(z,e);const t=this._createEventData(e);this._publishEvent(z,t),this._stateManager.updatePaymentState("failed",e),this._logger.debug("Payment failure reported",e)}catch(e){this._handleError(e,"reportPaymentFailure","payment_error")}}reportPaymentRefund(e){try{this._validator.validateEventData(G,e);const t=this._createEventData(e);this._publishEvent(G,t),this._stateManager.updatePaymentState("refunded",e),this._logger.debug("Payment refund reported",e)}catch(e){this._handleError(e,"reportPaymentRefund","payment_error")}}getPaymentState(){try{return this._stateManager.getPaymentState()}catch(e){return this._handleError(e,"getPaymentState","payment_error"),null}}}class re extends g{constructor(e){super(e)}reportAdStart(e){try{this._validator.validateEventData(H,e);const t=this._createEventData(e);this._publishEvent(H,t)}catch(e){this._handleError(e,"reportAdStart","ad_error")}}reportAdImpression(e){try{this._validator.validateEventData(K,e);const t=this._createEventData(e);this._publishEvent(K,t)}catch(e){this._handleError(e,"reportAdImpression","ad_error")}}reportAdClick(e){try{this._validator.validateEventData($,e);const t=this._createEventData(e);this._publishEvent($,t)}catch(e){this._handleError(e,"reportAdClick","ad_error")}}reportAdComplete(e){try{this._validator.validateEventData(q,e);const t=this._createEventData(e);this._publishEvent(q,t)}catch(e){this._handleError(e,"reportAdComplete","ad_error")}}reportAdSkip(e){try{this._validator.validateEventData(Q,e);const t=this._createEventData(e);this._publishEvent(Q,t)}catch(e){this._handleError(e,"reportAdSkip","ad_error")}}reportAdError(e){try{this._validator.validateEventData(j,e);const t=this._createEventData(e);this._publishEvent(j,t)}catch(e){this._handleError(e,"reportAdError","ad_error")}}getAdState(){return this._stateManager.getAdState()}}class ae extends g{constructor(e){super(e)}reportExperimentExposure(e){this._validator.validateEventData(W,e);const t=this._createEventData(e);this._publishEvent(W,t),this._logger.debug("Experiment exposure reported",t)}reportExperimentActivation(e){this._validator.validateEventData("experiment_activation",e);const t=this._createEventData(e);this._publishEvent("experiment_activation",t),this._logger.debug("Experiment activation reported",t)}reportFeatureFlagEvaluation(e){this._validator.validateEventData("feature_flag_evaluation",e);const t=this._createEventData(e);this._publishEvent("feature_flag_evaluation",t),this._logger.debug("Feature flag evaluation reported",t)}}class ie extends g{constructor(e){super(e)}reportUserSignUp(e){this._validator.validateEventData("user_sign_up",e);const t=this._createEventData(e);this._publishEvent("user_sign_up",t),this._logger.debug("User sign up reported",t)}reportUserSignIn(e){this._validator.validateEventData("user_sign_in",e);const t=this._createEventData(e);this._publishEvent("user_sign_in",t),this._logger.debug("User sign in reported",t)}reportUserSignOut(e){this._validator.validateEventData("user_sign_out",e);const t=this._createEventData(e);this._publishEvent("user_sign_out",t),this._logger.debug("User sign out reported",t)}reportUserProfileUpdate(e){this._validator.validateEventData("user_profile_update",e);const t=this._createEventData(e);this._publishEvent("user_profile_update",t),this._logger.debug("User profile update reported",t)}}class se extends g{constructor(e){super(e)}reportFeatureUsage(e){try{this._validator.validateEventData("feature_usage",e);const t=this._createEventData(e);this._publishEvent("feature_usage",t),this._logger.debug("Feature usage reported",t)}catch(e){this._handleError(e,"reportFeatureUsage","feature_usage_error")}}}class ne extends g{constructor(e){super(e)}reportUserInteraction(e){try{this._validator.validateEventData("user_interaction",e);const t=this._createEventData(e);this._publishEvent("user_interaction",t),this._logger.debug("User interaction reported",t)}catch(e){this._handleError(e,"reportUserInteraction","user_interaction_error")}}reportUserPreference(e){try{this._validator.validateEventData("user_preference",e);const t=this._createEventData(e);this._publishEvent("user_preference",t),this._logger.debug("User preference reported",t)}catch(e){this._handleError(e,"reportUserPreference","user_preference_error")}}reportUserFeedback(e){try{this._validator.validateEventData("user_feedback",e);const t=this._createEventData(e);this._publishEvent("user_feedback",t),this._logger.debug("User feedback reported",t)}catch(e){this._handleError(e,"reportUserFeedback","user_feedback_error")}}reportUserClick(e){try{this._validator.validateEventData("user_click",e);const t=this._createEventData(e);this._publishEvent("user_click",t),this._logger.debug("User click reported",t)}catch(e){throw this._handleError(e,"reportUserClick","user_click_error"),e}}reportUserScroll(e){try{this._validator.validateEventData("user_scroll",e);const t=this._createEventData(e);this._publishEvent("user_scroll",t),this._logger.debug("User scroll reported",t)}catch(e){throw this._handleError(e,"reportUserScroll","user_scroll_error"),e}}}class oe extends g{constructor(e){super(e)}reportVideoShared(e){try{if(!e||"object"!=typeof e)throw new Error("data must be an object");if(!e.assetId||"string"!=typeof e.assetId)throw new Error("data.assetId must be a string");const t=this._createEventData({type:m,...e,timestamp:Date.now()});this._validator.validateEventData(m,t),this._publishEvent(m,t),this._logger.debug("Video shared reported",t)}catch(e){this._handleError(e,"reportVideoShared","video_engagement_error")}}reportVideoBookmarked(e){try{this._validator.validateEventData(I,e);const t=this._createEventData({...e,timestamp:Date.now()});this._publishEvent(I,t),this._logger.debug("Video bookmarked reported",t)}catch(e){this._handleError(e,"reportVideoBookmarked","video_engagement_error")}}reportVideoLiked(e){try{this._validator.validateEventData(f,e);const t=this._createEventData({...e,timestamp:Date.now()});this._publishEvent(f,t),this._logger.debug("Video liked reported",t)}catch(e){this._handleError(e,"reportVideoLiked","video_engagement_error")}}reportVideoComment(e){try{this._validator.validateEventData(y,e);const t=this._createEventData({...e,timestamp:Date.now()});this._publishEvent(y,t),this._logger.debug("Video comment reported",t)}catch(e){this._handleError(e,"reportVideoComment","video_engagement_error")}}reportVideoRating(e){try{this._validator.validateEventData(S,e);const t=this._createEventData({...e,timestamp:Date.now()});this._publishEvent(S,t),this._logger.debug("Video rating reported",t)}catch(e){this._handleError(e,"reportVideoRating","video_engagement_error")}}reportVideoQualityChange(e){try{this._validator.validateEventData(T,e);const t=this._createEventData({...e,timestamp:Date.now()});this._publishEvent(T,t),this._logger.debug("Video quality change reported",t)}catch(e){this._handleError(e,"reportVideoQualityChange","video_engagement_error")}}reportVideoPlaybackSpeedChange(e){try{this._validator.validateEventData(b,e);const t=this._createEventData({...e,timestamp:Date.now()});this._publishEvent(b,t),this._logger.debug("Video playback speed change reported",t)}catch(e){this._handleError(e,"reportVideoPlaybackSpeedChange","video_engagement_error")}}reportCustomEngagement(e,t){try{this._validator.validateEventData(e,t);const r=this._createEventData(t);this._publishEvent(e,r),this._logger.debug(`Custom video engagement reported: ${e}`,r)}catch(e){this._handleError(e,"reportCustomEngagement","video_engagement_error")}}}class de{constructor(){this._version="1.0.0",this._isInitialized=!1,this._initializationInProgress=!1,this._registrationRetryCount=2,this._config=null,this._stateManager=null,this._eventQueue=null,this._eventPublisher=null,this._errorHandler=null,this._logger=null,this._validator=null,this._videoTracker=null,this._screenTracker=null,this._appTracker=null,this._userTracker=null,this._autoCollection=null,this._subscriptionTracker=null,this._paymentTracker=null,this._adTracker=null,this._experimentTracker=null,this._userAuthTracker=null,this._featureUsageTracker=null,this._userInteractionTracker=null,this._videoEngagementTracker=null,this._userInfoTracker=null}async initialize(r,n,o,l,c={},u={}){try{if(console.log("[SDK INIT] initialize called with sdkConfig:",u),console.log("[SDK INIT] _isInitialized:",this._isInitialized),console.log("[SDK INIT] _initializationInProgress:",this._initializationInProgress),this._isInitialized)return console.log("[SDK INIT] SDK already initialized - skipping"),void this._logger?.warn("SDK already initialized");if(this._initializationInProgress)return console.log("[SDK INIT] SDK initialization in progress - skipping"),void this._logger?.warn("SDK initialization in progress");this._validateInitParams(r,n,o,l),this._initializationInProgress=!0,this._config=new e({customerId:r,appId:n,appName:o,appVersion:l,...u}),this._stateManager=new t,this._eventQueue=new a(this._config),!1===u.autoCollect&&(console.log("[SDK INIT] Clearing stored events for e2e testing"),this._eventQueue.clear()),this._eventPublisher=new i(this._eventQueue,this._config),this._errorHandler=new s(this._config),this._logger=new d(this._config),this._validator=new _(this._config);const h={customerId:r,appId:n,appName:o,appVersion:l,sdkVersion:this._config.sdkVersion,sessionId:this._config.sessionId,screenRes:this._getScreenResolution(),timestamp:Date.now(),custId:r,subscriberId:c.subscriberId||"",subscriberType:c.subscriberType||"",subscriberTag:c.subscriberTag||"",clientInfo:{appName:o,appVersion:l,scrnRes:this._getScreenResolution(),ua:this._config.get("userAgent")||""},userInfo:{profileId:c.profileId||"",userData:c.userData||{},referralId:c.referralId||"",referralData:c.referralData||{}},customTags:c.customTags||{}};this._eventPublisher.updateCurrentPayload(h);const p={config:this._config,eventPublisher:this._eventPublisher,logger:this._logger,validator:this._validator,errorHandler:this._errorHandler,stateManager:this._stateManager};this._videoTracker=new E(p),this._screenTracker=new v(p),this._appTracker=new Y(p),this._userTracker=new X(p),this._userInfoTracker=new J(this),this._userInteractionTracker=new ne(p),this._videoEngagementTracker=new oe(p),this._autoCollection=new Z({config:this._config,eventPublisher:this._eventPublisher,logger:this._logger,validator:this._validator,errorHandler:this._errorHandler,stateManager:this._stateManager}),this._autoCollection.setEnabled(u.autoCollect??!0),this._subscriptionTracker=new ee(p),this._paymentTracker=new te(p),this._adTracker=new re(p),this._experimentTracker=new ae(p),this._userAuthTracker=new ie(p),this._featureUsageTracker=new se(p);try{const e=await this._registerWithBackend(r);this._eventPublisher.setProducerURL(e.producerURL||"https://streamproducer-lcrr.mediamelon.com"),this._eventPublisher.setStatsInterval(e.statsInterval)}catch(e){if(console.warn("Backend registration failed, continuing with default settings:",e.message),this._eventPublisher.setProducerURL("https://streamproducer-lcrr.mediamelon.com"),this._eventPublisher.setStatsInterval(30),this._registrationRetryCount>0&&!e.message.includes("422"))return this._registrationRetryCount--,this._initializationInProgress=!1,void await this.initialize(r,n,o,l,c,u)}this._isInitialized=!0,this._initializationInProgress=!1,this._logger.debug("SDK initialized successfully");const g=u.autoCollect??!0;if(console.log("[SDK DEBUG] autoCollect setting:",g),console.log("[SDK DEBUG] sdkConfig:",u),console.log("[SDK DEBUG] About to check autoCollect condition..."),g){console.log("[SDK DEBUG] autoCollect is TRUE - will send initial events");const e=[];e.push({type:"APP_STATE",data:{type:"APP_STATE",customerId:r,appId:n,appName:o,appVersion:l,state:"foreground",timestamp:Date.now(),sessionId:this._config.sessionId,sdkVersion:this._config.sdkVersion,screenRes:this._getScreenResolution(),custId:r,subscriberId:c.subscriberId||"",subscriberType:c.subscriberType||"",subscriberTag:c.subscriberTag||"",clientInfo:{appName:o,appVersion:l,scrnRes:this._getScreenResolution(),ua:this._config.get("userAgent")||""},userInfo:{profileId:c.profileId||"",userData:c.userData||{},referralId:c.referralId||"",referralData:c.referralData||{}},customTags:c.customTags||{}}}),c&&Object.keys(c).length>0&&e.push({type:"USER_IDENTIFICATION",data:{type:"USER_IDENTIFICATION",customerId:r,appId:n,appName:o,appVersion:l,timestamp:Date.now(),sessionId:this._config.sessionId,sdkVersion:this._config.sdkVersion,screenRes:this._getScreenResolution(),custId:r,subscriberId:c.subscriberId||"",subscriberType:c.subscriberType||"",subscriberTag:c.subscriberTag||"",clientInfo:{appName:o,appVersion:l,scrnRes:this._getScreenResolution(),ua:this._config.get("userAgent")||""},userInfo:{profileId:c.profileId||"",userData:c.userData||{},referralId:c.referralId||"",referralData:c.referralData||{}},customTags:c.customTags||{}}}),e.push({type:"SESSION_START",data:{type:"SESSION_START",customerId:r,appId:n,appName:o,appVersion:l,timestamp:Date.now(),sessionId:this._config.sessionId,sdkVersion:this._config.sdkVersion,screenRes:this._getScreenResolution(),custId:r,subscriberId:c.subscriberId||"",subscriberType:c.subscriberType||"",subscriberTag:c.subscriberTag||"",clientInfo:{appName:o,appVersion:l,scrnRes:this._getScreenResolution(),ua:this._config.get("userAgent")||""},userInfo:{profileId:c.profileId||"",userData:c.userData||{},referralId:c.referralId||"",referralData:c.referralData||{}},customTags:c.customTags||{}}}),console.log("[SDK INIT] User agent in config:",this._config.get("userAgent")),console.log("[SDK INIT] Sending initial events:",e.map((e=>e.type))),e.forEach((e=>{console.log("[SDK INIT] Publishing event:",e.type),this._eventPublisher.publishEvent(e.type,e.data)}))}else console.log("[SDK DEBUG] autoCollect is FALSE - skipping initial events"),console.log("[SDK INIT] Auto-collection disabled - skipping initial events")}catch(e){throw this._initializationInProgress=!1,this._handleError(e,"initialize"),e}}isInitialized(){return!0===this._isInitialized}destroy(){if(this._isInitialized)try{this._autoCollection&&this._autoCollection._enabled&&this._sendEvent("SESSION_END",{timestamp:Date.now(),sessionId:this._config?.sessionId,isGraceful:!0}),this._sendEvent("SDK_SHUTDOWN",{timestamp:Date.now()}),this._eventQueue&&this._eventQueue.destroy(),this._stateManager&&this._stateManager.clearStates(),this._logger&&this._logger.info("SDK destroyed"),this._isInitialized=!1,this._config=null,this._stateManager=null,this._eventQueue=null,this._errorHandler=null,this._logger=null,this._validator=null}catch(e){this._logger?this._logger.error("Error during SDK destruction:",e):console.error("Error during SDK destruction:",e)}}reportVideoState(e){this._validateInitialization();try{if(!e||"object"!=typeof e)throw new Error("Invalid video state data");this._videoTracker.reportVideoState(e)}catch(e){throw this._handleError(e,"reportVideoState"),e}}reportScreenView(e){this._validateInitialization();try{if(!e||"object"!=typeof e)throw new Error("Invalid screen view data");this._screenTracker.reportScreenView(e)}catch(e){throw this._handleError(e,"reportScreenView"),e}}reportAppState(e){this._validateInitialization();try{if(!e||"object"!=typeof e)throw new Error("Invalid app state data");this._appTracker.reportAppState(e)}catch(e){throw this._handleError(e,"reportAppState"),e}}reportAppError(e){this._validateInitialization();try{if(!e||"object"!=typeof e)throw new Error("Invalid error data");this._appTracker.reportAppError(e)}catch(e){throw this._handleError(e,"reportAppError"),e}}reportUserInfo(e){this._validateInitialization();try{if(!e||"object"!=typeof e)throw new Error("Invalid user info data");this._validator.validateEventData("USER_INFO",e),this._logger&&this._logger.setUserId(e.userId),this._sendEvent("USER_INFO",e)}catch(e){throw this._handleError(e,"reportUserInfo"),e}}reportEvent(e){this._validateInitialization();try{if(!e||"object"!=typeof e)throw new Error("Invalid event data");this._sendEvent(e.type||"custom",e)}catch(e){throw this._handleError(e,"reportEvent"),e}}getStatus(){return{version:this._version,isInitialized:this._isInitialized,config:this._config?.getConfig(),eventQueue:this._eventQueue?.getStatus()}}onError(e,t){this._validateInitialization(),this._errorHandler.onError(e,t)}getErrorHistory(){return this._validateInitialization(),this._errorHandler.getErrorHistory()}clearErrorHistory(){this._validateInitialization(),this._errorHandler.clearErrorHistory()}setLogLevel(e){this._validateInitialization(),this._logger.setLogLevel(e)}setLoggingEnabled(e){this._validateInitialization(),this._logger.setEnabled(e)}onLog(e,t){this._validateInitialization(),this._logger.onLog(e,t)}getLogHistory(){return this._validateInitialization(),this._logger.getLogHistory()}clearLogHistory(){this._validateInitialization(),this._logger.clearLogHistory()}getPerformanceMetrics(){return this._validateInitialization(),{eventQueue:this._eventQueue?this._eventQueue.getStatus():{queueLength:0,successfulEvents:0,failedEvents:0,processingTime:0},timestamp:Date.now()}}getSessionInfo(){return this._autoCollection.getSessionInfo()}getNavigationInfo(){return this._autoCollection.getNavigationInfo()}setAutoCollectionEnabled(e){this._autoCollection.setEnabled(e),this._logger.debug("Auto-collection "+(e?"enabled":"disabled"))}isAutoCollectionEnabled(){return!!this._autoCollection&&this._autoCollection._enabled}_validateInitialization(){if(!this._isInitialized)throw new Error("SDK not initialized")}_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)}))}async _registerWithBackend(e){const t=`https://register.mediamelon.com/mm-apis/register/${e}?platform=Browser&component=HTML5JSSDK`;return new Promise(((e,r)=>{const a=new XMLHttpRequest;a.open("GET",t,!0),a.onload=function(){if(a.status>=200&&a.status<300)try{const t=JSON.parse(a.responseText);e(t)}catch(e){r(new Error("Invalid registration response"))}else r(new Error(`Registration failed with status: ${a.status}`))},a.onerror=function(){r(new Error("Registration request failed"))},a.send()}))}_sendEvent(e,t){if(!this._eventQueue)throw new Error("Event queue not initialized");this._eventPublisher.publishEvent(e,t)}_handleError(e,t,r={}){this._logger&&this._logger.error(`Error in ${t}:`,e),this._errorHandler&&this._errorHandler.handleError(e,t,r),this._eventQueue&&this._isInitialized&&this._sendEvent("SDK_ERROR",{context:t,error:{name:e.name,message:e.message,stack:e.stack},metadata:r})}_validateInitParams(e,t,r,a){if(!e||"string"!=typeof e)throw new Error("Invalid customer ID");if(!t||"string"!=typeof t)throw new Error("Invalid application ID");if(!r||"string"!=typeof r)throw new Error("Invalid application name");if(!a||"string"!=typeof a)throw new Error("Invalid application version")}reportVideoStart(e){this._validateInitialization();try{if(console.log("MMAppAnalyticsSDK.reportVideoStart received:",JSON.stringify(e)),!e||"object"!=typeof e)throw new Error("Invalid video start data");this._videoTracker.reportVideoStart(e)}catch(e){throw this._handleError(e,"reportVideoStart"),e}}reportVideoPause(e){return this._videoTracker.reportVideoPause(e)}reportVideoResume(e){return this._videoTracker.reportVideoResume(e)}reportVideoSkip(e){return this._videoTracker.reportVideoSkip(e)}reportVideoStop(e){return this._videoTracker.reportVideoStop(e)}reportVideoEnd(e){return this._videoTracker.reportVideoEnd(e)}reportVideoQuality(e){return this._validateInitialization(),this._videoTracker.reportVideoQualityChange(e)}reportVideoQualityChange(e){return this._validateInitialization(),this._videoTracker.reportVideoQualityChange(e)}reportVideoBuffering(e){return this._videoTracker.reportVideoBuffering(e)}reportVideoSeek(e){return this._videoTracker.reportVideoSeek(e)}reportVideoFullscreen(e){return this._videoTracker.reportVideoFullscreen(e)}reportVideoExitFullscreen(e){return this._videoTracker.reportVideoExitFullscreen(e)}reportScreenExit(e){return this._screenTracker.reportScreenExit(e)}reportPerformanceMetrics(e){return this._appTracker.reportPerformanceMetrics(e)}reportUserIdentification(e){this._validateInitialization();try{if(!e||"object"!=typeof e)throw new Error("Invalid user identification data");this._userTracker.reportUserIdentification(e)}catch(e){throw this._handleError(e,"reportUserIdentification"),e}}reportUserSessionStart(e){return this._userTracker.reportUserSessionStart(e)}reportUserSessionEnd(e){return this._userTracker.reportUserSessionEnd(e)}reportUserPreferenceChange(e){return this._userTracker.reportUserPreferenceChange(e)}reportUserSignUp(e){this._validateInitialization();try{this._userAuthTracker.reportUserSignUp(e)}catch(e){throw this._handleError(e,"reportUserSignUp"),e}}reportUserSignIn(e){this._validateInitialization();try{this._userAuthTracker.reportUserSignIn(e)}catch(e){throw this._handleError(e,"reportUserSignIn"),e}}reportUserSignOut(e){this._validateInitialization();try{this._userAuthTracker.reportUserSignOut(e)}catch(e){throw this._handleError(e,"reportUserSignOut"),e}}getVideoState(){return this._videoTracker.getVideoState()}getScreenState(){return this._screenTracker.getScreenState()}getAppState(){return this._appTracker.getAppState()}getUserState(){return this._userTracker.getUserState()}reportSubscriptionStart(e){return this._subscriptionTracker.reportSubscriptionStart(e)}reportSubscriptionRenewal(e){return this._subscriptionTracker.reportSubscriptionRenewal(e)}reportSubscriptionCancellation(e){return this._subscriptionTracker.reportSubscriptionCancellation(e)}reportSubscriptionUpgrade(e){return this._subscriptionTracker.reportSubscriptionUpgrade(e)}reportSubscriptionDowngrade(e){return this._subscriptionTracker.reportSubscriptionDowngrade(e)}reportPaymentInitiation(e){this._validateInitialization();try{if(!e||"object"!=typeof e)throw new Error("Invalid payment initiation data");this._paymentTracker.reportPaymentInitiation(e)}catch(e){throw this._handleError(e,"reportPaymentInitiation"),e}}reportPaymentSuccess(e){this._validateInitialization();try{if(!e||"object"!=typeof e)throw new Error("Invalid payment success data");this._paymentTracker.reportPaymentSuccess(e)}catch(e){throw this._handleError(e,"reportPaymentSuccess"),e}}reportPaymentFailure(e){this._validateInitialization();try{if(!e||"object"!=typeof e)throw new Error("Invalid payment failure data");this._paymentTracker.reportPaymentFailure(e)}catch(e){throw this._handleError(e,"reportPaymentFailure"),e}}reportPaymentRefund(e){this._validateInitialization();try{if(!e||"object"!=typeof e)throw new Error("Invalid payment refund data");this._paymentTracker.reportPaymentRefund(e)}catch(e){throw this._handleError(e,"reportPaymentRefund"),e}}reportAdImpression(e){this._validateInitialization();try{if(!e||"object"!=typeof e)throw new Error("Invalid ad impression data");this._adTracker.reportAdImpression(e)}catch(e){throw this._handleError(e,"reportAdImpression"),e}}reportAdClick(e){this._validateInitialization();try{if(!e||"object"!=typeof e)throw new Error("Invalid ad click data");this._adTracker.reportAdClick(e)}catch(e){throw this._handleError(e,"reportAdClick"),e}}reportAdStart(e){this._validateInitialization();try{if(!e||"object"!=typeof e)throw new Error("Invalid ad start data");this._adTracker.reportAdStart(e)}catch(e){throw this._handleError(e,"reportAdStart"),e}}reportAdComplete(e){this._validateInitialization();try{if(!e||"object"!=typeof e)throw new Error("Invalid ad complete data");this._adTracker.reportAdComplete(e)}catch(e){throw this._handleError(e,"reportAdComplete"),e}}reportAdSkip(e){this._validateInitialization();try{if(!e||"object"!=typeof e)throw new Error("Invalid ad skip data");this._adTracker.reportAdSkip(e)}catch(e){throw this._handleError(e,"reportAdSkip"),e}}reportAdError(e){this._validateInitialization();try{if(!e||"object"!=typeof e)throw new Error("Invalid ad error data");this._adTracker.reportAdError(e)}catch(e){throw this._handleError(e,"reportAdError"),e}}getSubscriptionState(){return this._subscriptionTracker.getSubscriptionState()}getPaymentState(){return this._paymentTracker.getPaymentState()}getAdState(){return this._adTracker.getAdState()}reportExperimentExposure(e){this._validateInitialization();try{if(!e||"object"!=typeof e)throw new Error("Invalid experiment exposure data");this._experimentTracker.reportExperimentExposure(e)}catch(e){throw this._handleError(e,"reportExperimentExposure"),e}}reportExperimentActivation(e){this._validateInitialization();try{if(!e||"object"!=typeof e)throw new Error("Invalid experiment activation data");this._experimentTracker.reportExperimentActivation(e)}catch(e){throw this._handleError(e,"reportExperimentActivation"),e}}reportFeatureFlagEvaluation(e){this._validateInitialization();try{if(!e||"object"!=typeof e)throw new Error("Invalid feature flag evaluation data");this._experimentTracker.reportFeatureFlagEvaluation(e)}catch(e){throw this._handleError(e,"reportFeatureFlagEvaluation"),e}}reportExperimentResults(e){this._validateInitialization();try{if(!e||"object"!=typeof e)throw new Error("Invalid experiment results data");this._experimentTracker.reportExperimentResults(e)}catch(e){throw this._handleError(e,"reportExperimentResults"),e}}getExperimentState(e){return this._experimentTracker.getExperimentState(e)}getActiveExperiments(){return this._experimentTracker.getActiveExperiments()}reportUserProfileUpdate(e){this._validateInitialization();try{this._userTracker.reportUserProfileUpdate(e)}catch(e){throw this._handleError(e,"reportUserProfileUpdate"),e}}reportFeatureUsage(e){this._validateInitialization();try{this._featureUsageTracker.reportFeatureUsage(e)}catch(e){throw this._handleError(e,"reportFeatureUsage"),e}}reportSubscriptionViewed(e){this._subscriptionTracker.reportSubscriptionViewed(e)}reportSubscriberInfo(e){this._validateInitialization();try{if(!e||"object"!=typeof e)throw new Error("Invalid subscriber info data");if(!(e.subscriberId&&e.planType&&e.segment&&e.profileId))throw new Error("Missing required fields: subscriberId, planType, segment, profileId");this._userInfoTracker.reportSubscriberInfo(e)}catch(e){throw this._handleError(e,"reportSubscriberInfo"),e}}reportReferralInfo(e){this._validateInitialization();try{if(!e||"object"!=typeof e)throw new Error("Invalid referral info data");if(!(e.referralId&&e.source&&e.medium&&e.campaign))throw new Error("Missing required fields: referralId, source, medium, campaign");this._userInfoTracker.reportReferralInfo(e)}catch(e){throw this._handleError(e,"reportReferralInfo"),e}}reportUserClick(e){this._validateInitialization();try{if(!e||"object"!=typeof e)throw new Error("Invalid click metadata");this._userInteractionTracker.reportUserClick(e)}catch(e){throw this._handleError(e,"reportUserClick"),e}}reportUserScroll(e){this._validateInitialization();try{if(!e||"object"!=typeof e)throw new Error("Invalid scroll metadata");this._userInteractionTracker.reportUserScroll(e)}catch(e){throw this._handleError(e,"reportUserScroll"),e}}reportVideoShared(e){return this._validateInitialization(),this._videoEngagementTracker.reportVideoShared(e)}reportVideoBookmarked(e){return this._validateInitialization(),this._videoEngagementTracker.reportVideoBookmarked(e)}reportVideoLiked(e){return this._validateInitialization(),this._videoEngagementTracker.reportVideoLiked(e)}reportVideoComment(e){return this._validateInitialization(),this._videoEngagementTracker.reportVideoComment(e)}reportVideoRating(e){return this._validateInitialization(),this._videoEngagementTracker.reportVideoRating(e)}reportVideoPlaybackSpeedChange(e){return this._validateInitialization(),this._videoEngagementTracker.reportVideoPlaybackSpeedChange(e)}_createEvent(e,t){return{type:e,data:t,timestamp:Date.now(),sessionId:this._config.getSessionId(),config:this._config.getConfig(),metadata:this._config.getEventMetadata()}}_initializeSession(){const e=this._config.getSessionId();return this._config.updateSessionId(e),e}_getScreenResolution(){return"undefined"!=typeof window&&window.screen?`${window.screen.width}x${window.screen.height}`:""}}export{e as Config,s as ErrorHandler,i as EventPublisher,a as EventQueue,d as Logger,de as MMAppAnalyticsSDK,t as StateManager,_ as Validator};
//# sourceMappingURL=mm-app-analytics-js-sdk.esm.js.map