@widgetic/embed-sdk 2.0.12 → 2.0.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import{a as t}from"./core.js";class e{static getInstance(){return e.instance||(e.instance=new e),e.instance}constructor(){this.playingWidgets=new Map,this.widgetConfigs=new Map,this.storageKey="widgetic_media_state",this.globalVolumeKey="widgetic_global_volume",this.storageVersion="2.0",this.eventListeners=new Map,this.autoResumeEnabled=!0,this.defaultAutoResumeTimeout=18e5,this.globalVolumeEnabled=!0,this.globalVolumeState={volume:1,muted:!1,lastUpdated:Date.now()},this.loadPersistedState(),this.loadGlobalVolumeState(),this.setupVisibilityHandler(),this.setupUnloadHandler(),setTimeout((()=>{this.autoResumeWidgets()}),1e3)}registerWidget(t,e={}){const s=Object.assign({autoPause:!0,mediaType:"both",priority:5,persistState:!0,allowSimultaneous:[],autoResume:!1,autoResumeTimeout:this.defaultAutoResumeTimeout,globalVolume:!0},e);this.widgetConfigs.set(t,s);const i=this.playingWidgets.get(t);i&&s.persistState?(s.globalVolume&&this.globalVolumeEnabled&&(i.volume=this.globalVolumeState.muted?0:this.globalVolumeState.volume),setTimeout((()=>{this.sendRestoreStateCommand(t,i)}),100)):s.globalVolume&&this.globalVolumeEnabled&&setTimeout((()=>{this.sendVolumeCommand(t,this.globalVolumeState.muted?0:this.globalVolumeState.volume)}),100)}unregisterWidget(t){this.handleMediaEvent({type:"stop",compositionId:t,config:this.widgetConfigs.get(t)||{}}),this.playingWidgets.delete(t),this.widgetConfigs.delete(t),this.eventListeners.delete(t)}handleMediaEvent(t){const{type:e,compositionId:s,config:i,data:a}=t;switch(e){case"play":this.handlePlayEvent(s,i,a);break;case"pause":this.handlePauseEvent(s,a);break;case"stop":case"ended":this.handleStopEvent(s);break;case"seeking":this.handleSeekingEvent(s,null==a?void 0:a.position);break;case"volumechange":this.handleVolumeEvent(s,null==a?void 0:a.volume);break;case"trackchange":this.handleTrackChangeEvent(s,a);break;case"playlistchange":this.handlePlaylistChangeEvent(s,a)}this.emitToListeners(s,t),i.persistState&&this.persistState(),this.dispatchGlobalEvent(t)}handlePlayEvent(t,e,s={}){const i=s.mediaType||e.mediaType||"both",a=e.priority||5,o={compositionId:t,mediaType:i,state:"playing",priority:a,startedAt:Date.now(),duration:s.duration,position:s.position||0,title:s.title,volume:s.volume,playlist:s.playlist,autoResume:e.autoResume,lastInteraction:Date.now()};!1!==e.autoPause&&this.pauseConflictingWidgets(t,i,a,e.allowSimultaneous||[]),this.playingWidgets.set(t,o)}handlePauseEvent(t,e={}){const s=this.playingWidgets.get(t);s&&(s.state="paused",s.position=e.position||s.position,s.volume=e.volume||s.volume,s.lastInteraction=Date.now())}handleStopEvent(t){const e=this.playingWidgets.get(t);e&&(e.state="stopped",e.position=0,e.lastInteraction=Date.now())}handleSeekingEvent(t,e){const s=this.playingWidgets.get(t);s&&void 0!==e&&(s.position=e,s.lastInteraction=Date.now())}handleVolumeEvent(t,e){const s=this.playingWidgets.get(t),i=this.widgetConfigs.get(t);s&&void 0!==e&&(s.lastInteraction=Date.now(),(null==i?void 0:i.globalVolume)&&this.globalVolumeEnabled?(this.globalVolumeState={volume:e>0?e:this.globalVolumeState.volume,muted:0===e,lastUpdated:Date.now(),lastChangedBy:t},this.persistGlobalVolumeState(),this.syncGlobalVolumeToWidgets(t),s.volume=this.globalVolumeState.muted?0:this.globalVolumeState.volume):s.volume=e)}handleTrackChangeEvent(t,e={}){const s=this.playingWidgets.get(t);s&&e.playlist&&(s.playlist=Object.assign(Object.assign({},s.playlist),e.playlist),s.position=0,s.title=e.playlist.trackTitle||s.title,s.lastInteraction=Date.now())}handlePlaylistChangeEvent(t,e={}){const s=this.playingWidgets.get(t);s&&e.playlist&&(s.playlist=Object.assign(Object.assign({},s.playlist),e.playlist),s.lastInteraction=Date.now())}pauseConflictingWidgets(t,e,s,i){const a=[];for(const[o,n]of this.playingWidgets){if(o===t||"playing"!==n.state)continue;this.isSimultaneousAllowed(n.mediaType,e,i)||(s>n.priority||s===n.priority&&Date.now()>n.startedAt)&&a.push(o)}for(const t of a)this.sendPauseCommand(t);a.length}isSimultaneousAllowed(t,e,s){return"both"!==t&&"both"!==e&&(t!==e&&(s.includes(t)&&s.includes(e)))}sendPauseCommand(e){var s;const i=document.querySelector(`[data-widgetic-id="${e}"], [data-composition-id="${e}"]`);if(i){if("iframe"===i.tagName.toLowerCase()){const a=i,o=t.CLIENT_URL||"*";null===(s=a.contentWindow)||void 0===s||s.postMessage({type:"widgetic:media:command",command:"pause",compositionId:e},o)}i.dispatchEvent(new CustomEvent("widgetic:media:command",{detail:{command:"pause",compositionId:e}}));const a=this.playingWidgets.get(e);a&&(a.state="paused")}}getPlayingWidgets(){return Array.from(this.playingWidgets.values()).filter((t=>"playing"===t.state))}getAllMediaWidgets(){return Array.from(this.playingWidgets.values())}pauseAll(){const t=this.getPlayingWidgets();for(const e of t)this.sendPauseCommand(e.compositionId)}resumeLastPlayed(){const t=Array.from(this.playingWidgets.values()).filter((t=>"paused"===t.state)).sort(((t,e)=>e.startedAt-t.startedAt));if(t.length>0){const e=t[0];this.sendResumeCommand(e.compositionId)}}sendResumeCommand(e){var s;const i=document.querySelector(`[data-widgetic-id="${e}"], [data-composition-id="${e}"]`);if(i){if("iframe"===i.tagName.toLowerCase()){const a=i,o=t.CLIENT_URL||"*";null===(s=a.contentWindow)||void 0===s||s.postMessage({type:"widgetic:media:command",command:"play",compositionId:e},o)}i.dispatchEvent(new CustomEvent("widgetic:media:command",{detail:{command:"play",compositionId:e}}))}}addEventListener(t,e){return this.eventListeners.has(t)||this.eventListeners.set(t,[]),this.eventListeners.get(t).push(e),()=>{const s=this.eventListeners.get(t);if(s){const t=s.indexOf(e);t>-1&&s.splice(t,1)}}}emitToListeners(t,e){const s=this.eventListeners.get(t);if(s)for(const t of s)try{t(e)}catch(t){}}dispatchGlobalEvent(t){document.dispatchEvent(new CustomEvent(`widgetic:media:${t.type}`,{detail:{compositionId:t.compositionId,config:t.config,data:t.data},bubbles:!0}))}loadPersistedState(){if("undefined"!=typeof localStorage)try{const t=localStorage.getItem(this.storageKey);if(t){const e=JSON.parse(t);if(e.version!==this.storageVersion)return void this.clearPersistedState();const s=864e5;if(e.timestamp&&Date.now()-e.timestamp>s)return void this.clearPersistedState();for(const[t,s]of Object.entries(e.playingWidgets||{})){const e=s;e.compositionId&&e.mediaType&&e.state&&this.playingWidgets.set(t,e)}}}catch(t){this.clearPersistedState()}}persistState(){try{const t={version:this.storageVersion,playingWidgets:Object.fromEntries(this.playingWidgets),timestamp:Date.now(),autoResumeEnabled:this.autoResumeEnabled};localStorage.setItem(this.storageKey,JSON.stringify(t))}catch(t){}}setupVisibilityHandler(){"undefined"!=typeof document&&document.addEventListener("visibilitychange",(()=>{document.hidden&&this.pauseAll()}))}setupUnloadHandler(){"undefined"!=typeof window&&window.addEventListener("beforeunload",(()=>{this.persistState()}))}clearPersistedState(t=!1){try{localStorage.removeItem(this.storageKey),t&&(localStorage.removeItem(this.globalVolumeKey),this.globalVolumeState={volume:1,muted:!1,lastUpdated:Date.now()})}catch(t){}}getStats(){const t=this.getPlayingWidgets(),e=Array.from(this.playingWidgets.values()).filter((t=>"paused"===t.state)),s=Array.from(this.playingWidgets.values()).filter((t=>t.playlist)),i=Array.from(this.widgetConfigs.values()).filter((t=>t.globalVolume)).length;return{totalWidgets:this.widgetConfigs.size,playingWidgets:t.length,pausedWidgets:e.length,registeredWidgets:this.playingWidgets.size,widgetsWithPlaylists:s.length,globalVolumeWidgets:i,autoResumeEnabled:this.autoResumeEnabled,globalVolumeEnabled:this.globalVolumeEnabled,globalVolume:{volume:this.globalVolumeState.volume,muted:this.globalVolumeState.muted,lastUpdated:this.globalVolumeState.lastUpdated,lastChangedBy:this.globalVolumeState.lastChangedBy},storageVersion:this.storageVersion,currentlyPlaying:t.map((t=>({compositionId:t.compositionId,mediaType:t.mediaType,priority:t.priority,duration:t.startedAt?Date.now()-t.startedAt:0,position:t.position,volume:t.volume,playlist:t.playlist?{currentTrack:t.playlist.currentTrack,totalTracks:t.playlist.totalTracks,trackTitle:t.playlist.trackTitle}:void 0}))),allWidgets:Array.from(this.playingWidgets.values()).map((t=>{var e;return{compositionId:t.compositionId,state:t.state,mediaType:t.mediaType,priority:t.priority,position:t.position,volume:t.volume,lastInteraction:t.lastInteraction,playlist:t.playlist,autoResume:t.autoResume,globalVolume:(null===(e=this.widgetConfigs.get(t.compositionId))||void 0===e?void 0:e.globalVolume)||!1}}))}}destroy(){this.pauseAll(),this.playingWidgets.clear(),this.widgetConfigs.clear(),this.eventListeners.clear(),this.persistState(),this.persistGlobalVolumeState()}autoResumeWidgets(t={}){if(!this.autoResumeEnabled)return;const{autoResumePlayback:e=!0,maxStateAge:s=this.defaultAutoResumeTimeout,respectTimeouts:i=!0}=t,a=Date.now(),o=[];for(const[t,n]of this.playingWidgets){const l=this.widgetConfigs.get(t);(null==l?void 0:l.autoResume)&&l.persistState&&n.lastInteraction&&(!i||a-n.lastInteraction<=(l.autoResumeTimeout||s))&&("playing"===n.state||e&&"paused"===n.state)&&o.push(n)}o.length>0&&(o.sort(((t,e)=>t.priority!==e.priority?e.priority-t.priority:(e.lastInteraction||0)-(t.lastInteraction||0))),e&&"playing"===o[0].state&&this.resumeWidget(o[0].compositionId))}resumeWidget(t){const e=this.playingWidgets.get(t),s=this.widgetConfigs.get(t);return!(!e||!s)&&(this.sendRestoreStateCommand(t,e),"playing"===e.state&&setTimeout((()=>{this.sendPlayCommand(t,e.position)}),100),!0)}sendRestoreStateCommand(e,s){var i;const a=document.querySelector(`[data-widgetic-id="${e}"], [data-composition-id="${e}"]`);if(a){const o={type:"widgetic:media:command",command:"restore",compositionId:e,state:{position:s.position||0,volume:s.volume||1,title:s.title,playlist:s.playlist,duration:s.duration}};if("iframe"===a.tagName.toLowerCase()){const e=a,s=t.CLIENT_URL||"*";null===(i=e.contentWindow)||void 0===i||i.postMessage(o,s)}a.dispatchEvent(new CustomEvent("widgetic:media:command",{detail:o}))}}sendPlayCommand(e,s){var i;const a=document.querySelector(`[data-widgetic-id="${e}"], [data-composition-id="${e}"]`);if(a){const o={type:"widgetic:media:command",command:"play",compositionId:e,position:s};if("iframe"===a.tagName.toLowerCase()){const e=a,s=t.CLIENT_URL||"*";null===(i=e.contentWindow)||void 0===i||i.postMessage(o,s)}a.dispatchEvent(new CustomEvent("widgetic:media:command",{detail:o}))}}getPersistedState(t){return this.playingWidgets.get(t)||null}updateWidgetState(t,e){const s=this.playingWidgets.get(t);if(s){const i=Object.assign(Object.assign(Object.assign({},s),e),{lastInteraction:Date.now()});this.playingWidgets.set(t,i);const a=this.widgetConfigs.get(t);(null==a?void 0:a.persistState)&&this.persistState()}}setAutoResumeEnabled(t){this.autoResumeEnabled=t}triggerAutoResume(t={}){this.autoResumeWidgets(t)}loadGlobalVolumeState(){if("undefined"!=typeof localStorage)try{const t=localStorage.getItem(this.globalVolumeKey);if(t){const e=JSON.parse(t);"number"==typeof e.volume&&"boolean"==typeof e.muted&&(this.globalVolumeState={volume:Math.max(0,Math.min(1,e.volume)),muted:e.muted,lastUpdated:e.lastUpdated||Date.now(),lastChangedBy:e.lastChangedBy})}}catch(t){}}persistGlobalVolumeState(){try{localStorage.setItem(this.globalVolumeKey,JSON.stringify(this.globalVolumeState))}catch(t){}}syncGlobalVolumeToWidgets(t){const e=this.globalVolumeState.muted?0:this.globalVolumeState.volume;for(const[s,i]of this.widgetConfigs)if(s!==t&&i.globalVolume){this.sendVolumeCommand(s,e);const t=this.playingWidgets.get(s);t&&(t.volume=e)}}sendVolumeCommand(e,s){var i;const a=document.querySelector(`[data-widgetic-id="${e}"], [data-composition-id="${e}"]`);if(a){const o={type:"widgetic:media:command",command:"setVolume",compositionId:e,volume:Math.max(0,Math.min(1,s))};if("iframe"===a.tagName.toLowerCase()){const e=a,s=t.CLIENT_URL||"*";null===(i=e.contentWindow)||void 0===i||i.postMessage(o,s)}a.dispatchEvent(new CustomEvent("widgetic:media:command",{detail:o}))}}getGlobalVolumeState(){return Object.assign({},this.globalVolumeState)}setGlobalVolume(t,e){const s=Math.max(0,Math.min(1,t));this.globalVolumeState={volume:s,muted:0===s,lastUpdated:Date.now(),lastChangedBy:e||"api"},this.persistGlobalVolumeState(),this.syncGlobalVolumeToWidgets()}toggleGlobalMute(t){return this.globalVolumeState=Object.assign(Object.assign({},this.globalVolumeState),{muted:!this.globalVolumeState.muted,lastUpdated:Date.now(),lastChangedBy:t||"api"}),this.persistGlobalVolumeState(),this.syncGlobalVolumeToWidgets(),this.globalVolumeState.muted}setGlobalVolumeEnabled(t){const e=this.globalVolumeEnabled;this.globalVolumeEnabled=t,t&&!e&&this.syncGlobalVolumeToWidgets()}isGlobalVolumeEnabled(){return this.globalVolumeEnabled}}let s=null;function i(){return s||(s=e.getInstance()),s}var a=Object.freeze({__proto__:null,MediaManager:e,getMediaManager:i,resetMediaManager:function(){s&&(s.destroy(),s=null)}});class o{static getInstance(){return o.instance||(o.instance=new o),o.instance}constructor(){this.contentStates=new Map,this.widgetConfigs=new Map,this.storageKey="widgetic_content_positions",this.storageVersion="1.0",this.eventListeners=new Map,this.autoResumeEnabled=!0,this.defaultAutoResumeTimeout=864e5,this.debounceTimers=new Map,this.loadPersistedState(),this.setupUnloadHandler(),setTimeout((()=>{this.autoResumePositions()}),1e3)}registerWidget(t,e={}){const s=Object.assign({contentType:"custom",persistState:!0,autoResume:!1,autoResumeTimeout:this.defaultAutoResumeTimeout,debounceDelay:500,trackMetadata:!1},e);this.widgetConfigs.set(t,s);const i=this.contentStates.get(t);i&&s.persistState&&setTimeout((()=>{this.sendRestorePositionCommand(t,i)}),100)}unregisterWidget(t){const e=this.debounceTimers.get(t);e&&(clearTimeout(e),this.debounceTimers.delete(t)),this.contentStates.delete(t),this.widgetConfigs.delete(t),this.eventListeners.delete(t)}handleContentPositionEvent(t){const{type:e,compositionId:s,config:i,data:a}=t;switch(e){case"position":case"navigate":this.handlePositionChangeEvent(s,i,a);break;case"complete":this.handleCompleteEvent(s,a);break;case"reset":this.handleResetEvent(s);break;case"metadata":this.handleMetadataEvent(s,a)}this.emitToListeners(s,t),i.persistState&&this.debouncedPersistState(s,i.debounceDelay||500),this.dispatchGlobalEvent(t)}handlePositionChangeEvent(t,e,s={}){const i=this.contentStates.get(t),a={compositionId:t,contentType:e.contentType||"custom",currentIndex:void 0!==s.currentIndex?s.currentIndex:(null==i?void 0:i.currentIndex)||0,totalItems:void 0!==s.totalItems?s.totalItems:(null==i?void 0:i.totalItems)||0,currentItemId:s.currentItemId||(null==i?void 0:i.currentItemId),currentItemTitle:s.currentItemTitle||(null==i?void 0:i.currentItemTitle),lastUpdated:Date.now(),autoResume:e.autoResume,lastInteraction:Date.now(),metadata:e.trackMetadata?Object.assign(Object.assign({},null==i?void 0:i.metadata),s.metadata):void 0};this.contentStates.set(t,a)}handleCompleteEvent(t,e={}){const s=this.contentStates.get(t);s&&(s.lastInteraction=Date.now(),s.metadata&&(s.metadata.completed=!0,s.metadata.completedAt=Date.now(),e.metadata&&Object.assign(s.metadata,e.metadata)))}handleResetEvent(t){const e=this.contentStates.get(t);e&&(e.currentIndex=0,e.currentItemId=void 0,e.currentItemTitle=void 0,e.lastInteraction=Date.now(),e.metadata&&(e.metadata.completed=!1,delete e.metadata.completedAt))}handleMetadataEvent(t,e={}){const s=this.contentStates.get(t);s&&e.metadata&&(s.metadata||(s.metadata={}),Object.assign(s.metadata,e.metadata),s.lastInteraction=Date.now())}loadPersistedState(){if("undefined"!=typeof localStorage)try{const t=localStorage.getItem(this.storageKey);if(t){const e=JSON.parse(t);if(e.version!==this.storageVersion)return void this.clearPersistedState();const s=6048e5;if(e.timestamp&&Date.now()-e.timestamp>s)return void this.clearPersistedState();for(const[t,s]of Object.entries(e.contentStates||{})){const e=s;e.compositionId&&e.contentType&&void 0!==e.currentIndex&&this.contentStates.set(t,e)}}}catch(t){this.clearPersistedState()}}debouncedPersistState(t,e){const s=this.debounceTimers.get(t);s&&clearTimeout(s);const i=setTimeout((()=>{this.persistState(),this.debounceTimers.delete(t)}),e);this.debounceTimers.set(t,i)}persistState(){try{const t={version:this.storageVersion,contentStates:Object.fromEntries(this.contentStates),timestamp:Date.now(),autoResumeEnabled:this.autoResumeEnabled};localStorage.setItem(this.storageKey,JSON.stringify(t))}catch(t){}}setupUnloadHandler(){"undefined"!=typeof window&&window.addEventListener("beforeunload",(()=>{for(const t of this.debounceTimers.values())clearTimeout(t);this.debounceTimers.clear(),this.persistState()}))}autoResumePositions(t={}){if(!this.autoResumeEnabled)return;const{autoResumePosition:e=!0,maxStateAge:s=this.defaultAutoResumeTimeout,respectTimeouts:i=!0}=t,a=Date.now(),o=[];for(const[t,n]of this.contentStates){const l=this.widgetConfigs.get(t);(null==l?void 0:l.autoResume)&&l.persistState&&n.lastInteraction&&(!i||a-n.lastInteraction<=(l.autoResumeTimeout||s))&&e&&o.push(n)}o.length>0&&o.forEach((t=>{this.resumeWidgetPosition(t.compositionId)}))}resumeWidgetPosition(t){const e=this.contentStates.get(t),s=this.widgetConfigs.get(t);return!(!e||!s)&&(this.sendRestorePositionCommand(t,e),!0)}sendRestorePositionCommand(e,s){var i;const a=document.querySelector(`[data-widgetic-id="${e}"], [data-composition-id="${e}"]`);if(a){const o={type:"widgetic:content:command",command:"restorePosition",compositionId:e,state:{currentIndex:s.currentIndex,totalItems:s.totalItems,currentItemId:s.currentItemId,currentItemTitle:s.currentItemTitle,metadata:s.metadata}};if("iframe"===a.tagName.toLowerCase()){const e=a,s=t.CLIENT_URL||"*";null===(i=e.contentWindow)||void 0===i||i.postMessage(o,s)}a.dispatchEvent(new CustomEvent("widgetic:content:command",{detail:o}))}}getAllContentWidgets(){return Array.from(this.contentStates.values())}getPersistedPosition(t){return this.contentStates.get(t)||null}updateWidgetPosition(t,e){const s=this.contentStates.get(t);if(s){const i=Object.assign(Object.assign(Object.assign({},s),e),{lastInteraction:Date.now()});this.contentStates.set(t,i);const a=this.widgetConfigs.get(t);(null==a?void 0:a.persistState)&&this.debouncedPersistState(t,a.debounceDelay||500)}}clearPersistedState(){try{localStorage.removeItem(this.storageKey)}catch(t){}}getStats(){const t=Array.from(this.contentStates.values()),e=t.reduce(((t,e)=>(t[e.contentType]=(t[e.contentType]||0)+1,t)),{});return{totalWidgets:this.widgetConfigs.size,trackedWidgets:this.contentStates.size,autoResumeEnabled:this.autoResumeEnabled,storageVersion:this.storageVersion,contentTypes:e,allWidgets:t.map((t=>({compositionId:t.compositionId,contentType:t.contentType,currentIndex:t.currentIndex,totalItems:t.totalItems,progress:t.totalItems>0?Math.round(t.currentIndex/(t.totalItems-1)*100):0,lastInteraction:t.lastInteraction,autoResume:t.autoResume,metadata:t.metadata})))}}addEventListener(t,e){return this.eventListeners.has(t)||this.eventListeners.set(t,[]),this.eventListeners.get(t).push(e),()=>{const s=this.eventListeners.get(t);if(s){const t=s.indexOf(e);t>-1&&s.splice(t,1)}}}emitToListeners(t,e){const s=this.eventListeners.get(t);if(s)for(const t of s)try{t(e)}catch(t){}}dispatchGlobalEvent(t){document.dispatchEvent(new CustomEvent(`widgetic:content:${t.type}`,{detail:{compositionId:t.compositionId,config:t.config,data:t.data},bubbles:!0}))}setAutoResumeEnabled(t){this.autoResumeEnabled=t}triggerAutoResume(t={}){this.autoResumePositions(t)}destroy(){for(const t of this.debounceTimers.values())clearTimeout(t);this.contentStates.clear(),this.widgetConfigs.clear(),this.eventListeners.clear(),this.debounceTimers.clear(),this.persistState()}}let n=null;function l(){return n||(n=o.getInstance()),n}export{l as a,i as g,a as m};
1
+ class t{static getInstance(){return t.instance||(t.instance=new t),t.instance}constructor(){this.playingWidgets=new Map,this.widgetConfigs=new Map,this.storageKey="widgetic_media_state",this.globalVolumeKey="widgetic_global_volume",this.storageVersion="2.0",this.eventListeners=new Map,this.autoResumeEnabled=!0,this.defaultAutoResumeTimeout=18e5,this.globalVolumeEnabled=!0,this.isPageUnloading=!1,this.globalVolumeState={volume:1,muted:!1,lastUpdated:Date.now()},this.loadPersistedState(),this.loadGlobalVolumeState(),this.setupVisibilityHandler(),this.setupUnloadHandler(),setTimeout((()=>{this.autoResumeWidgets()}),1e3)}registerWidget(t,e={}){const i=Object.assign({autoPause:!0,mediaType:"both",priority:5,persistState:!0,allowSimultaneous:[],autoResume:!1,autoResumeTimeout:this.defaultAutoResumeTimeout,globalVolume:!0},e);this.widgetConfigs.set(t,i);const s=this.playingWidgets.get(t);s&&i.persistState?(i.globalVolume&&this.globalVolumeEnabled&&(s.volume=this.globalVolumeState.muted?0:this.globalVolumeState.volume),setTimeout((()=>{this.sendRestoreStateCommand(t,s)}),100)):i.globalVolume&&this.globalVolumeEnabled&&setTimeout((()=>{this.sendVolumeCommand(t,this.globalVolumeState.muted?0:this.globalVolumeState.volume)}),100)}unregisterWidget(t){this.handleMediaEvent({type:"stop",compositionId:t,config:this.widgetConfigs.get(t)||{}}),this.playingWidgets.delete(t),this.widgetConfigs.delete(t),this.eventListeners.delete(t)}handleMediaEvent(t){var e;const{type:i,compositionId:s,config:o,data:a}=t;if(o&&Object.keys(o).length>0){const t=this.widgetConfigs.get(s)||{autoPause:!0,mediaType:"both",priority:5,persistState:!0,allowSimultaneous:[],autoResume:!0,autoResumeTimeout:this.defaultAutoResumeTimeout,globalVolume:!0};this.widgetConfigs.set(s,Object.assign(Object.assign({},t),o))}switch(i){case"play":this.handlePlayEvent(s,o,a);break;case"pause":this.handlePauseEvent(s,a,o);break;case"stop":case"ended":this.handleStopEvent(s);break;case"seeking":case"seeked":this.handleSeekingEvent(s,null!==(e=null==a?void 0:a.position)&&void 0!==e?e:null==a?void 0:a.currentTime,o,a);break;case"timeupdate":case"progress":case"durationchange":case"loadedmetadata":this.handleTimeUpdateEvent(s,o,a);break;case"volumechange":this.handleVolumeEvent(s,null==a?void 0:a.volume,o);break;case"trackchange":this.handleTrackChangeEvent(s,a,o);break;case"playlistchange":this.handlePlaylistChangeEvent(s,a,o)}this.emitToListeners(s,t),!1!==(null==o?void 0:o.persistState)&&this.persistState(),this.dispatchGlobalEvent(t)}getOrCreateMediaState(t,e={},i="paused",s={}){var o;const a=this.playingWidgets.get(t);if(a)return a;const n={compositionId:t,mediaType:(null==s?void 0:s.mediaType)||e.mediaType||"both",state:i,priority:e.priority||5,startedAt:Date.now(),duration:"number"==typeof(null==s?void 0:s.duration)?s.duration:void 0,position:"number"==typeof(null==s?void 0:s.position)?s.position:"number"==typeof(null==s?void 0:s.currentTime)?s.currentTime:0,title:null==s?void 0:s.title,volume:"number"==typeof(null==s?void 0:s.volume)?s.volume:void 0,playlist:null==s?void 0:s.playlist,autoResume:null===(o=e.autoResume)||void 0===o||o,lastInteraction:Date.now()};return this.playingWidgets.set(t,n),n}handlePlayEvent(t,e={},i={}){var s,o,a,n;const l=this.playingWidgets.get(t),d=i.mediaType||e.mediaType||(null==l?void 0:l.mediaType)||"both",u=e.priority||(null==l?void 0:l.priority)||5,r="number"==typeof i.position?i.position:"number"==typeof i.currentTime?i.currentTime:null!==(s=null==l?void 0:l.position)&&void 0!==s?s:0,m={compositionId:t,mediaType:d,state:"playing",priority:u,startedAt:Date.now(),duration:"number"==typeof i.duration?i.duration:null==l?void 0:l.duration,position:r,title:null!==(o=i.title)&&void 0!==o?o:null==l?void 0:l.title,volume:"number"==typeof i.volume?i.volume:null==l?void 0:l.volume,playlist:i.playlist?Object.assign(Object.assign({},null==l?void 0:l.playlist),i.playlist):null==l?void 0:l.playlist,autoResume:null===(n=null!==(a=e.autoResume)&&void 0!==a?a:null==l?void 0:l.autoResume)||void 0===n||n,lastInteraction:Date.now()};!1!==e.autoPause&&this.pauseConflictingWidgets(t,d,u,e.allowSimultaneous||[]),this.playingWidgets.set(t,m)}handlePauseEvent(t,e={},i={}){const s=this.getOrCreateMediaState(t,i,"paused",e);s.state="paused";const o="number"==typeof(null==e?void 0:e.position)?e.position:null==e?void 0:e.currentTime;"number"==typeof o&&(s.position=o),"number"==typeof(null==e?void 0:e.duration)&&(s.duration=e.duration),"number"==typeof(null==e?void 0:e.volume)&&(s.volume=e.volume),(null==e?void 0:e.title)&&(s.title=e.title),(null==e?void 0:e.playlist)&&(s.playlist=Object.assign(Object.assign({},s.playlist),e.playlist)),s.lastInteraction=Date.now()}handleStopEvent(t){const e=this.playingWidgets.get(t);e&&(e.state="stopped",e.position=0,e.lastInteraction=Date.now())}handleSeekingEvent(t,e,i={},s={}){const o=this.getOrCreateMediaState(t,i,"paused",s);"number"==typeof e&&(o.position=e),"number"==typeof(null==s?void 0:s.duration)&&(o.duration=s.duration),(null==s?void 0:s.playlist)&&(o.playlist=Object.assign(Object.assign({},o.playlist),s.playlist)),o.lastInteraction=Date.now()}handleTimeUpdateEvent(t,e={},i={}){const s=!0===(null==i?void 0:i.playing)?"playing":"paused",o=this.getOrCreateMediaState(t,e,s,i),a="number"==typeof(null==i?void 0:i.position)?i.position:null==i?void 0:i.currentTime;"number"==typeof a&&(o.position=a),"number"==typeof(null==i?void 0:i.duration)&&Number.isFinite(i.duration)&&(o.duration=i.duration),"number"==typeof(null==i?void 0:i.volume)&&(o.volume=i.volume),"boolean"==typeof(null==i?void 0:i.playing)?o.state=i.playing?"playing":"paused":"playing"!==(null==i?void 0:i.state)&&"paused"!==(null==i?void 0:i.state)&&"stopped"!==(null==i?void 0:i.state)||(o.state=i.state),(null==i?void 0:i.title)&&(o.title=i.title),(null==i?void 0:i.playlist)&&(o.playlist=Object.assign(Object.assign({},o.playlist),i.playlist)),o.lastInteraction=Date.now()}handleVolumeEvent(t,e,i={}){const s=this.getOrCreateMediaState(t,i,"paused",{volume:e}),o=this.widgetConfigs.get(t)||i;s&&"number"==typeof e&&(s.lastInteraction=Date.now(),(null==o?void 0:o.globalVolume)&&this.globalVolumeEnabled?(this.globalVolumeState={volume:e>0?e:this.globalVolumeState.volume,muted:0===e,lastUpdated:Date.now(),lastChangedBy:t},this.persistGlobalVolumeState(),this.syncGlobalVolumeToWidgets(t),s.volume=this.globalVolumeState.muted?0:this.globalVolumeState.volume):s.volume=e)}handleTrackChangeEvent(t,e={},i={}){const s=this.getOrCreateMediaState(t,i,"paused",e),o=(null==e?void 0:e.playlist)||Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"number"==typeof(null==e?void 0:e.currentTrack)?{currentTrack:e.currentTrack}:{}),"number"==typeof(null==e?void 0:e.trackIndex)?{currentTrack:e.trackIndex}:{}),"number"==typeof(null==e?void 0:e.totalTracks)?{totalTracks:e.totalTracks}:{}),(null==e?void 0:e.trackId)?{trackId:e.trackId}:{}),(null==e?void 0:e.trackTitle)||(null==e?void 0:e.title)?{trackTitle:e.trackTitle||e.title}:{});Object.keys(o).length>0&&(s.playlist=Object.assign(Object.assign({currentTrack:0,totalTracks:1},s.playlist),o),s.title=o.trackTitle||(null==e?void 0:e.title)||s.title),s.position="number"==typeof(null==e?void 0:e.position)?e.position:0,"boolean"==typeof(null==e?void 0:e.playing)&&(s.state=e.playing?"playing":"paused"),s.lastInteraction=Date.now()}handlePlaylistChangeEvent(t,e={},i={}){const s=this.getOrCreateMediaState(t,i,"paused",e);(null==e?void 0:e.playlist)&&(s.playlist=Object.assign(Object.assign({},s.playlist),e.playlist),s.lastInteraction=Date.now())}pauseConflictingWidgets(t,e,i,s){const o=[];for(const[a,n]of this.playingWidgets){if(a===t||"playing"!==n.state)continue;this.isSimultaneousAllowed(n.mediaType,e,s)||(i>n.priority||i===n.priority&&Date.now()>n.startedAt)&&o.push(a)}for(const t of o)this.sendPauseCommand(t);o.length}isSimultaneousAllowed(t,e,i){return"both"!==t&&"both"!==e&&(t!==e&&(i.includes(t)&&i.includes(e)))}resolveHostElement(t){return"undefined"==typeof document?null:document.querySelector(`[data-widgetic-id="${t}"], [data-composition-id="${t}"], [composition-id="${t}"], widgetic[composition-id="${t}"], [widget="${t}"], [widget-id="${t}"], widgetic[widget="${t}"], widgetic[widget-id="${t}"]`)}resolveIframeTargetOrigin(t){var e;const i=t.getAttribute("src")||t.src;if(i)try{const t=new URL(i,"undefined"!=typeof window&&(null===(e=window.location)||void 0===e?void 0:e.href)?window.location.href:"https://widgetic.com").origin;if(t&&"null"!==t)return t}catch(t){}return"*"}dispatchCommandToHostAndIframe(t,e){var i;const s=this.resolveHostElement(t);if(!s)return!1;const o="iframe"===s.tagName.toLowerCase()?s:s.querySelector("iframe");if(null==o?void 0:o.contentWindow){const t=this.resolveIframeTargetOrigin(o);try{o.contentWindow.postMessage(e,t)}catch(t){try{o.contentWindow.postMessage(e,"*")}catch(t){}}}s.dispatchEvent(new CustomEvent("widgetic:media:command",{detail:e}));const a=s.querySelector("[data-widgetic-direct]"),n=null===(i=null==a?void 0:a.shadowRoot)||void 0===i?void 0:i.querySelector(".widgetic-direct-target");return n&&n.dispatchEvent(new CustomEvent("widgetic:media:command",{detail:e,bubbles:!0,composed:!0})),!0}sendPauseCommand(t,e,i=!0){if(this.dispatchCommandToHostAndIframe(t,Object.assign({type:"widgetic:media:command",command:"pause",compositionId:t},"number"==typeof e?{position:e}:{}))&&i){const e=this.playingWidgets.get(t);e&&(e.state="paused")}}getPlayingWidgets(){return Array.from(this.playingWidgets.values()).filter((t=>"playing"===t.state))}getAllMediaWidgets(){return Array.from(this.playingWidgets.values())}pauseAll(){const t=this.getPlayingWidgets();for(const e of t)this.sendPauseCommand(e.compositionId)}resumeLastPlayed(){const t=Array.from(this.playingWidgets.values()).filter((t=>"paused"===t.state)).sort(((t,e)=>e.startedAt-t.startedAt));if(t.length>0){const e=t[0];this.sendResumeCommand(e.compositionId)}}sendResumeCommand(t){const e=this.playingWidgets.get(t);this.dispatchCommandToHostAndIframe(t,Object.assign({type:"widgetic:media:command",command:"play",compositionId:t},"number"==typeof(null==e?void 0:e.position)?{position:e.position}:{}))}addEventListener(t,e){return this.eventListeners.has(t)||this.eventListeners.set(t,[]),this.eventListeners.get(t).push(e),()=>{const i=this.eventListeners.get(t);if(i){const t=i.indexOf(e);t>-1&&i.splice(t,1)}}}emitToListeners(t,e){const i=this.eventListeners.get(t);if(i)for(const t of i)try{t(e)}catch(t){}}dispatchGlobalEvent(t){document.dispatchEvent(new CustomEvent(`widgetic:media:${t.type}`,{detail:{compositionId:t.compositionId,config:t.config,data:t.data},bubbles:!0}))}loadPersistedState(){if("undefined"!=typeof localStorage)try{const t=localStorage.getItem(this.storageKey);if(t){const e=JSON.parse(t);if(e.version!==this.storageVersion)return void this.clearPersistedState();const i=864e5;if(e.timestamp&&Date.now()-e.timestamp>i)return void this.clearPersistedState();for(const[t,i]of Object.entries(e.playingWidgets||{})){const e=i;e.compositionId&&e.mediaType&&e.state&&this.playingWidgets.set(t,e)}}}catch(t){this.clearPersistedState()}}persistState(){try{const t={version:this.storageVersion,playingWidgets:Object.fromEntries(this.playingWidgets),timestamp:Date.now(),autoResumeEnabled:this.autoResumeEnabled};localStorage.setItem(this.storageKey,JSON.stringify(t))}catch(t){}}setupVisibilityHandler(){"undefined"!=typeof document&&document.addEventListener("visibilitychange",(()=>{if(document.hidden&&!this.isPageUnloading){const t=this.getPlayingWidgets();for(const e of t)this.sendPauseCommand(e.compositionId,e.position,!1)}}))}setupUnloadHandler(){if("undefined"==typeof window)return;const t=()=>{this.isPageUnloading=!0,this.persistState()};window.addEventListener("beforeunload",t),window.addEventListener("pagehide",t)}clearPersistedState(t=!1){try{localStorage.removeItem(this.storageKey),t&&(localStorage.removeItem(this.globalVolumeKey),this.globalVolumeState={volume:1,muted:!1,lastUpdated:Date.now()})}catch(t){}}getStats(){const t=this.getPlayingWidgets(),e=Array.from(this.playingWidgets.values()).filter((t=>"paused"===t.state)),i=Array.from(this.playingWidgets.values()).filter((t=>t.playlist)),s=Array.from(this.widgetConfigs.values()).filter((t=>t.globalVolume)).length;return{totalWidgets:this.widgetConfigs.size,playingWidgets:t.length,pausedWidgets:e.length,registeredWidgets:this.playingWidgets.size,widgetsWithPlaylists:i.length,globalVolumeWidgets:s,autoResumeEnabled:this.autoResumeEnabled,globalVolumeEnabled:this.globalVolumeEnabled,globalVolume:{volume:this.globalVolumeState.volume,muted:this.globalVolumeState.muted,lastUpdated:this.globalVolumeState.lastUpdated,lastChangedBy:this.globalVolumeState.lastChangedBy},storageVersion:this.storageVersion,currentlyPlaying:t.map((t=>({compositionId:t.compositionId,mediaType:t.mediaType,priority:t.priority,duration:t.startedAt?Date.now()-t.startedAt:0,position:t.position,volume:t.volume,playlist:t.playlist?{currentTrack:t.playlist.currentTrack,totalTracks:t.playlist.totalTracks,trackTitle:t.playlist.trackTitle}:void 0}))),allWidgets:Array.from(this.playingWidgets.values()).map((t=>{var e;return{compositionId:t.compositionId,state:t.state,mediaType:t.mediaType,priority:t.priority,position:t.position,volume:t.volume,lastInteraction:t.lastInteraction,playlist:t.playlist,autoResume:t.autoResume,globalVolume:(null===(e=this.widgetConfigs.get(t.compositionId))||void 0===e?void 0:e.globalVolume)||!1}}))}}destroy(){this.pauseAll(),this.playingWidgets.clear(),this.widgetConfigs.clear(),this.eventListeners.clear(),this.persistState(),this.persistGlobalVolumeState()}autoResumeWidgets(t={}){var e,i;if(!this.autoResumeEnabled)return;const{autoResumePlayback:s=!0,maxStateAge:o=this.defaultAutoResumeTimeout,respectTimeouts:a=!0}=t,n=Date.now(),l=[];for(const[t,d]of this.playingWidgets){const u=this.widgetConfigs.get(t)||{autoPause:!0,persistState:!0,autoResume:null===(e=d.autoResume)||void 0===e||e};(null!==(i=u.autoResume)&&void 0!==i?i:d.autoResume)&&!1!==u.persistState&&d.lastInteraction&&(!a||n-d.lastInteraction<=(u.autoResumeTimeout||o))&&("playing"===d.state||s&&"paused"===d.state)&&l.push(d)}if(l.length>0){l.sort(((t,e)=>t.priority!==e.priority?e.priority-t.priority:(e.lastInteraction||0)-(t.lastInteraction||0)));let t=!1;for(const e of l)s&&"playing"===e.state&&!t?(t=!0,this.resumeWidget(e.compositionId)):this.sendRestoreStateCommand(e.compositionId,Object.assign(Object.assign({},e),{state:"paused"}))}}resumeWidget(t){const e=this.playingWidgets.get(t);return!!e&&(this.sendRestoreStateCommand(t,e),"playing"===e.state?setTimeout((()=>{this.sendPlayCommand(t,e.position)}),100):"paused"===e.state&&setTimeout((()=>{this.sendPauseCommand(t,e.position,!1)}),100),!0)}sendRestoreStateCommand(t,e){const i={type:"widgetic:media:command",command:"restore",compositionId:t,state:{state:e.state,playing:"playing"===e.state,position:"number"==typeof e.position?e.position:0,volume:"number"==typeof e.volume?e.volume:1,title:e.title,playlist:e.playlist,duration:e.duration}};this.dispatchCommandToHostAndIframe(t,i)}sendPlayCommand(t,e){const i={type:"widgetic:media:command",command:"play",compositionId:t,position:e};this.dispatchCommandToHostAndIframe(t,i)}getPersistedState(t){return this.playingWidgets.get(t)||null}updateWidgetState(t,e){const i=this.playingWidgets.get(t);if(i){const s=Object.assign(Object.assign(Object.assign({},i),e),{lastInteraction:Date.now()});this.playingWidgets.set(t,s);const o=this.widgetConfigs.get(t);!1!==(null==o?void 0:o.persistState)&&this.persistState()}}setAutoResumeEnabled(t){this.autoResumeEnabled=t}triggerAutoResume(t={}){this.autoResumeWidgets(t)}loadGlobalVolumeState(){if("undefined"!=typeof localStorage)try{const t=localStorage.getItem(this.globalVolumeKey);if(t){const e=JSON.parse(t);"number"==typeof e.volume&&"boolean"==typeof e.muted&&(this.globalVolumeState={volume:Math.max(0,Math.min(1,e.volume)),muted:e.muted,lastUpdated:e.lastUpdated||Date.now(),lastChangedBy:e.lastChangedBy})}}catch(t){}}persistGlobalVolumeState(){try{localStorage.setItem(this.globalVolumeKey,JSON.stringify(this.globalVolumeState))}catch(t){}}syncGlobalVolumeToWidgets(t){const e=this.globalVolumeState.muted?0:this.globalVolumeState.volume;for(const[i,s]of this.widgetConfigs)if(i!==t&&s.globalVolume){this.sendVolumeCommand(i,e);const t=this.playingWidgets.get(i);t&&(t.volume=e)}}sendVolumeCommand(t,e){const i={type:"widgetic:media:command",command:"setVolume",compositionId:t,volume:Math.max(0,Math.min(1,e))};this.dispatchCommandToHostAndIframe(t,i)}getGlobalVolumeState(){return Object.assign({},this.globalVolumeState)}setGlobalVolume(t,e){const i=Math.max(0,Math.min(1,t));this.globalVolumeState={volume:i,muted:0===i,lastUpdated:Date.now(),lastChangedBy:e||"api"},this.persistGlobalVolumeState(),this.syncGlobalVolumeToWidgets()}toggleGlobalMute(t){return this.globalVolumeState=Object.assign(Object.assign({},this.globalVolumeState),{muted:!this.globalVolumeState.muted,lastUpdated:Date.now(),lastChangedBy:t||"api"}),this.persistGlobalVolumeState(),this.syncGlobalVolumeToWidgets(),this.globalVolumeState.muted}setGlobalVolumeEnabled(t){const e=this.globalVolumeEnabled;this.globalVolumeEnabled=t,t&&!e&&this.syncGlobalVolumeToWidgets()}isGlobalVolumeEnabled(){return this.globalVolumeEnabled}}let e=null;function i(){return e||(e=t.getInstance()),e}var s=Object.freeze({__proto__:null,MediaManager:t,getMediaManager:i,resetMediaManager:function(){e&&(e.destroy(),e=null)}});class o{static getInstance(){return o.instance||(o.instance=new o),o.instance}constructor(){this.contentStates=new Map,this.widgetConfigs=new Map,this.storageKey="widgetic_content_positions",this.storageVersion="1.0",this.eventListeners=new Map,this.autoResumeEnabled=!0,this.defaultAutoResumeTimeout=864e5,this.debounceTimers=new Map,this.loadPersistedState(),this.setupUnloadHandler(),setTimeout((()=>{this.autoResumePositions()}),1e3)}registerWidget(t,e={}){const i=Object.assign({contentType:"custom",persistState:!0,autoResume:!1,autoResumeTimeout:this.defaultAutoResumeTimeout,debounceDelay:500,trackMetadata:!1},e);this.widgetConfigs.set(t,i);const s=this.contentStates.get(t);s&&i.persistState&&setTimeout((()=>{this.sendRestorePositionCommand(t,s)}),100)}unregisterWidget(t){const e=this.debounceTimers.get(t);e&&(clearTimeout(e),this.debounceTimers.delete(t)),this.contentStates.delete(t),this.widgetConfigs.delete(t),this.eventListeners.delete(t)}handleContentPositionEvent(t){const{type:e,compositionId:i,config:s,data:o}=t,a=Object.assign(Object.assign({contentType:"custom",persistState:!0,autoResume:!0,debounceDelay:500,trackMetadata:!0},this.widgetConfigs.get(i)),s);switch(void 0!==a.autoResumePosition&&void 0===s.autoResume&&(a.autoResume=a.autoResumePosition),this.widgetConfigs.set(i,a),e){case"position":case"navigate":this.handlePositionChangeEvent(i,a,o);break;case"complete":this.handleCompleteEvent(i,o);break;case"reset":this.handleResetEvent(i);break;case"metadata":this.handleMetadataEvent(i,o)}this.emitToListeners(i,t),!1!==a.persistState&&this.persistState(),this.dispatchGlobalEvent(t)}handlePositionChangeEvent(t,e,i={}){var s,o,a,n,l,d,u,r,m,c;const g=this.contentStates.get(t),p="number"==typeof(null==i?void 0:i.currentIndex)?i.currentIndex:"number"==typeof(null==i?void 0:i.index)?i.index:null!==(s=null==g?void 0:g.currentIndex)&&void 0!==s?s:0,h="number"==typeof(null==i?void 0:i.totalItems)?i.totalItems:"number"==typeof(null==i?void 0:i.total)?i.total:null!==(o=null==g?void 0:g.totalItems)&&void 0!==o?o:0,v=void 0!==(null==i?void 0:i.metadata)||void 0!==(null==g?void 0:g.metadata)?Object.assign(Object.assign({},null==g?void 0:g.metadata),null==i?void 0:i.metadata):void 0,y={compositionId:t,contentType:e.contentType||(null==g?void 0:g.contentType)||"custom",currentIndex:p,totalItems:h,currentItemId:null!==(n=null!==(a=null==i?void 0:i.currentItemId)&&void 0!==a?a:null==i?void 0:i.itemId)&&void 0!==n?n:null==g?void 0:g.currentItemId,currentItemTitle:null!==(u=null!==(d=null!==(l=null==i?void 0:i.currentItemTitle)&&void 0!==l?l:null==i?void 0:i.itemTitle)&&void 0!==d?d:null==i?void 0:i.title)&&void 0!==u?u:null==g?void 0:g.currentItemTitle,lastUpdated:Date.now(),autoResume:null===(c=null!==(m=null!==(r=e.autoResume)&&void 0!==r?r:e.autoResumePosition)&&void 0!==m?m:null==g?void 0:g.autoResume)||void 0===c||c,lastInteraction:Date.now(),metadata:v};this.contentStates.set(t,y)}handleCompleteEvent(t,e={}){const i=this.contentStates.get(t);i&&(i.lastInteraction=Date.now(),i.metadata&&(i.metadata.completed=!0,i.metadata.completedAt=Date.now(),e.metadata&&Object.assign(i.metadata,e.metadata)))}handleResetEvent(t){const e=this.contentStates.get(t);e&&(e.currentIndex=0,e.currentItemId=void 0,e.currentItemTitle=void 0,e.lastInteraction=Date.now(),e.metadata&&(e.metadata.completed=!1,delete e.metadata.completedAt))}handleMetadataEvent(t,e={}){const i=this.contentStates.get(t);i&&e.metadata&&(i.metadata||(i.metadata={}),Object.assign(i.metadata,e.metadata),i.lastInteraction=Date.now())}loadPersistedState(){if("undefined"!=typeof localStorage)try{const t=localStorage.getItem(this.storageKey);if(t){const e=JSON.parse(t);if(e.version!==this.storageVersion)return void this.clearPersistedState();const i=6048e5;if(e.timestamp&&Date.now()-e.timestamp>i)return void this.clearPersistedState();for(const[t,i]of Object.entries(e.contentStates||{})){const e=i;e.compositionId&&e.contentType&&void 0!==e.currentIndex&&this.contentStates.set(t,e)}}}catch(t){this.clearPersistedState()}}debouncedPersistState(t,e){const i=this.debounceTimers.get(t);i&&clearTimeout(i);const s=setTimeout((()=>{this.persistState(),this.debounceTimers.delete(t)}),e);this.debounceTimers.set(t,s)}persistState(){try{const t={version:this.storageVersion,contentStates:Object.fromEntries(this.contentStates),timestamp:Date.now(),autoResumeEnabled:this.autoResumeEnabled};localStorage.setItem(this.storageKey,JSON.stringify(t))}catch(t){}}setupUnloadHandler(){"undefined"!=typeof window&&window.addEventListener("beforeunload",(()=>{for(const t of this.debounceTimers.values())clearTimeout(t);this.debounceTimers.clear(),this.persistState()}))}autoResumePositions(t={}){var e,i,s,o;if(!this.autoResumeEnabled)return;const{autoResumePosition:a=!0,maxStateAge:n=this.defaultAutoResumeTimeout,respectTimeouts:l=!0}=t,d=Date.now(),u=[];for(const[t,r]of this.contentStates){const m=this.widgetConfigs.get(t),c=null!==(s=null!==(i=null!==(e=null==m?void 0:m.autoResume)&&void 0!==e?e:null==m?void 0:m.autoResumePosition)&&void 0!==i?i:r.autoResume)&&void 0!==s&&s,g=null===(o=null==m?void 0:m.persistState)||void 0===o||o;c&&g&&r.lastInteraction&&(!l||d-r.lastInteraction<=((null==m?void 0:m.autoResumeTimeout)||n))&&a&&u.push(r)}u.length>0&&u.forEach((t=>{this.resumeWidgetPosition(t.compositionId)}))}resumeWidgetPosition(t){const e=this.contentStates.get(t);return!!e&&(this.sendRestorePositionCommand(t,e),!0)}resolveHostElement(t){return"undefined"==typeof document?null:document.querySelector(`[data-widgetic-id="${t}"], [data-composition-id="${t}"], [composition-id="${t}"], widgetic[composition-id="${t}"], [widget="${t}"], [widget-id="${t}"], widgetic[widget="${t}"], widgetic[widget-id="${t}"]`)}resolveIframeTargetOrigin(t){var e;const i=t.getAttribute("src")||t.src;if(i)try{const t=new URL(i,"undefined"!=typeof window&&(null===(e=window.location)||void 0===e?void 0:e.href)?window.location.href:"https://widgetic.com").origin;if(t&&"null"!==t)return t}catch(t){}return"*"}sendRestorePositionCommand(t,e){var i;const s=this.resolveHostElement(t);if(s){const o={type:"widgetic:content:command",command:"restorePosition",compositionId:t,state:{currentIndex:e.currentIndex,totalItems:e.totalItems,currentItemId:e.currentItemId,currentItemTitle:e.currentItemTitle,metadata:e.metadata}},a="iframe"===s.tagName.toLowerCase()?s:s.querySelector("iframe");if(null==a?void 0:a.contentWindow){const t=this.resolveIframeTargetOrigin(a);try{a.contentWindow.postMessage(o,t)}catch(t){try{a.contentWindow.postMessage(o,"*")}catch(t){}}}s.dispatchEvent(new CustomEvent("widgetic:content:command",{detail:o}));const n=s.querySelector("[data-widgetic-direct]"),l=null===(i=null==n?void 0:n.shadowRoot)||void 0===i?void 0:i.querySelector(".widgetic-direct-target");l&&l.dispatchEvent(new CustomEvent("widgetic:content:command",{detail:o,bubbles:!0,composed:!0}))}}getAllContentWidgets(){return Array.from(this.contentStates.values())}getPersistedPosition(t){return this.contentStates.get(t)||null}updateWidgetPosition(t,e){const i=this.contentStates.get(t);if(i){const s=Object.assign(Object.assign(Object.assign({},i),e),{lastInteraction:Date.now()});this.contentStates.set(t,s);const o=this.widgetConfigs.get(t);!1!==(null==o?void 0:o.persistState)&&this.persistState()}}clearPersistedState(){try{localStorage.removeItem(this.storageKey)}catch(t){}}getStats(){const t=Array.from(this.contentStates.values()),e=t.reduce(((t,e)=>(t[e.contentType]=(t[e.contentType]||0)+1,t)),{});return{totalWidgets:this.widgetConfigs.size,trackedWidgets:this.contentStates.size,autoResumeEnabled:this.autoResumeEnabled,storageVersion:this.storageVersion,contentTypes:e,allWidgets:t.map((t=>({compositionId:t.compositionId,contentType:t.contentType,currentIndex:t.currentIndex,totalItems:t.totalItems,progress:t.totalItems>0?Math.round(t.currentIndex/(t.totalItems-1)*100):0,lastInteraction:t.lastInteraction,autoResume:t.autoResume,metadata:t.metadata})))}}addEventListener(t,e){return this.eventListeners.has(t)||this.eventListeners.set(t,[]),this.eventListeners.get(t).push(e),()=>{const i=this.eventListeners.get(t);if(i){const t=i.indexOf(e);t>-1&&i.splice(t,1)}}}emitToListeners(t,e){const i=this.eventListeners.get(t);if(i)for(const t of i)try{t(e)}catch(t){}}dispatchGlobalEvent(t){document.dispatchEvent(new CustomEvent(`widgetic:content:${t.type}`,{detail:{compositionId:t.compositionId,config:t.config,data:t.data},bubbles:!0}))}setAutoResumeEnabled(t){this.autoResumeEnabled=t}triggerAutoResume(t={}){this.autoResumePositions(t)}destroy(){for(const t of this.debounceTimers.values())clearTimeout(t);this.contentStates.clear(),this.widgetConfigs.clear(),this.eventListeners.clear(),this.debounceTimers.clear(),this.persistState()}}let a=null;function n(){return a||(a=o.getInstance()),a}export{i as a,n as g,s as m};
@@ -1 +1 @@
1
- import{_ as e}from"./vendor.js";import{l as t,a as s}from"./core.js";import"./api.js";import"./renderers.js";import"./media.js";import"./messaging.js";import"./display.js";import"./advanced.js";import"./scanner.js";import"./performance.js";import"./security.js";class n{constructor(e={}){this.messageHandlers=new Map,this.messageQueue=new Map,this.pendingMessages=new Map,this.heartbeatIntervals=new Map,this.sequenceNumbers=new Map,this.allowedOrigins=new Set,this.customEventSubscriptions=new Map,this.functionCallHandlers=new Map,this.pendingFunctionCalls=new Map,this.widgetControllers=new Map,this.securityOptions=Object.assign({enableSignatureValidation:!1,allowedOrigins:[],messageTimeout:3e4,enableHeartbeat:!1,heartbeatInterval:3e4},e),this.setupAllowedOrigins(this.securityOptions.allowedOrigins),this.setupGlobalMessageListener(),t.info("WidgeticMessenger initialized",{securityOptions:this.securityOptions})}setupAllowedOrigins(e){s.CLIENT_URL&&this.allowedOrigins.add(s.CLIENT_URL),"undefined"!=typeof window&&window.location&&this.allowedOrigins.add(window.location.origin),e&&e.forEach((e=>this.allowedOrigins.add(e)));const n=new Set;this.allowedOrigins.forEach((e=>{try{const t=new URL(e);n.add(t.origin)}catch(t){n.add(e)}})),this.allowedOrigins=n,t.debug("Allowed origins configured",{origins:Array.from(this.allowedOrigins)})}setupGlobalMessageListener(){"undefined"!=typeof window&&window.addEventListener("message",(e=>{this.handleIncomingMessage(e)}))}validateMessage(e){if(!this.allowedOrigins.has(e.origin))return t.warn("Message from unauthorized origin",{origin:e.origin}),null;try{const s="string"==typeof e.data?JSON.parse(e.data):e.data;return this.isValidWidgeticMessage(s)?this.securityOptions.enableSignatureValidation&&!this.validateSignature(s)?(t.warn("Message signature validation failed",{instanceId:s.instanceId}),null):s:(t.warn("Invalid message structure",{message:s}),null)}catch(s){return t.warn("Failed to parse message",{error:s,data:e.data}),null}}isValidWidgeticMessage(e){return e&&"string"==typeof e.type&&"string"==typeof e.instanceId&&"number"==typeof e.timestamp&&"string"==typeof e.version&&void 0!==e.payload}validateSignature(e){return!0}generateSignature(e){const t=JSON.stringify(Object.assign({},e));return btoa(t).substring(0,16)}handleIncomingMessage(e){const s=this.validateMessage(e);if(!s)return;switch(t.debug("Received valid message",{type:s.type,instanceId:s.instanceId}),s.type){case"heartbeat":return void this.handleHeartbeat(s);case"auth":return void this.handleAuthentication(s);case"custom-event":return void this.handleCustomEvent(s);case"function-call":return void this.handleFunctionCall(s);case"function-response":return void this.handleFunctionResponse(s);case"text-field-change":return void this.handleTextFieldChange(s)}const n=this.messageHandlers.get(s.instanceId);if(n)try{n(s)}catch(e){t.error("Message handler error",{error:e,instanceId:s.instanceId})}else t.debug("No handler for message",{instanceId:s.instanceId,type:s.type})}handleHeartbeat(e){t.debug("Heartbeat received",{instanceId:e.instanceId}),this.sendMessage(e.instanceId,{type:"heartbeat",instanceId:e.instanceId,payload:{response:!0},timestamp:Date.now(),version:"1.0"})}handleAuthentication(e){t.debug("Authentication message received",{instanceId:e.instanceId})}handleTextFieldChange(e){const{fieldId:s,text:n,metadata:i}=e.payload;s&&"string"==typeof n?(import("./security.js").then((function(e){return e.s})).then((({getSecurityManager:a})=>{const r=a().validateTextFieldUpdate(e.instanceId,s,n,i);if(!r.allowed)return t.warn("Text field change blocked by security",{instanceId:e.instanceId,fieldId:s,reason:r.reason,severity:r.severity}),void document.dispatchEvent(new CustomEvent("widgetic:text-field-security-blocked",{detail:{instanceId:e.instanceId,compositionId:e.compositionId,fieldId:s,reason:r.reason,severity:r.severity,originalTextLength:n.length,timestamp:Date.now()},bubbles:!0}));t.debug("Text field change received",{instanceId:e.instanceId,fieldId:s,textLength:n.length,sanitized:!(!r.sanitizedText||r.sanitizedText===n)}),import("./security.js").then((function(e){return e.t})).then((({getTextFieldManager:t})=>{const a=t(),o=r.sanitizedText||n;a.updateTextField(e.instanceId,s,o,{autoPersist:!0,persistState:!0,textType:(null==i?void 0:i.textType)||"custom",debounceDelay:(null==i?void 0:i.debounceDelay)||1e3,maxLength:null==i?void 0:i.maxLength},Object.assign(Object.assign({},i),{securityValidated:!0,sanitized:o!==n}))})).catch((s=>{t.warn("Failed to handle text field change",{error:s,instanceId:e.instanceId})}))})).catch((s=>{t.warn("Failed to validate text field security",{error:s,instanceId:e.instanceId})})),document.dispatchEvent(new CustomEvent("widgetic:text-field-change",{detail:{instanceId:e.instanceId,compositionId:e.compositionId,fieldId:s,text:n,metadata:i},bubbles:!0}))):t.warn("Invalid text field change message",{instanceId:e.instanceId,payload:e.payload})}handleCustomEvent(e){const{eventName:s,eventData:n,metadata:i}=e.payload,a=this.customEventSubscriptions.get(e.instanceId);if(!a)return;const r=a.get(s);r&&0!==r.size&&(t.debug("Dispatching custom event",{instanceId:e.instanceId,eventName:s,subscriberCount:r.size}),r.forEach((a=>{try{a(n,i)}catch(n){t.error("Custom event callback error",{error:n,eventName:s,instanceId:e.instanceId})}})),document.dispatchEvent(new CustomEvent(`widgetic:custom:${s}`,{detail:{instanceId:e.instanceId,compositionId:e.compositionId,eventName:s,eventData:n,metadata:i},bubbles:!0})))}handleFunctionCall(e){const{functionName:s,args:n,requestId:i}=e.payload,a=this.functionCallHandlers.get(e.instanceId);if(!a)return void this.sendFunctionResponse(e.instanceId,i,!1,void 0,"No function handlers registered");const r=a.get(s);if(r){t.debug("Executing function call",{instanceId:e.instanceId,functionName:s,args:n});try{const t=r(...n);t&&"function"==typeof t.then?t.then((t=>this.sendFunctionResponse(e.instanceId,i,!0,t))).catch((t=>this.sendFunctionResponse(e.instanceId,i,!1,void 0,t.message||"Function execution failed"))):this.sendFunctionResponse(e.instanceId,i,!0,t)}catch(t){this.sendFunctionResponse(e.instanceId,i,!1,void 0,t instanceof Error?t.message:"Function execution failed")}}else this.sendFunctionResponse(e.instanceId,i,!1,void 0,`Function '${s}' not found`)}handleFunctionResponse(e){const{requestId:s,success:n,result:i,error:a}=e.payload,r=this.pendingFunctionCalls.get(s);r?(clearTimeout(r.timeout),this.pendingFunctionCalls.delete(s),n?r.resolve(i):r.reject(new Error(a||"Function call failed"))):t.warn("Received response for unknown function call",{requestId:s})}sendFunctionResponse(e,t,s,n,i){this.sendMessage(e,{type:"function-response",instanceId:e,payload:{requestId:t,success:s,result:n,error:i},timestamp:Date.now(),version:"1.0"})}registerHandler(e,s){this.messageHandlers.set(e,s),t.debug("Message handler registered",{instanceId:e}),this.messageQueue.has(e)||this.messageQueue.set(e,[]),this.sequenceNumbers.set(e,0),this.securityOptions.enableHeartbeat&&this.startHeartbeat(e)}unregisterHandler(e){this.messageHandlers.delete(e),this.messageQueue.delete(e),this.sequenceNumbers.delete(e),this.stopHeartbeat(e),t.debug("Message handler unregistered",{instanceId:e})}sendMessage(e,s){const n=document.querySelector(`[data-widgetic-id="${e}"]`);if(!n||!n.contentWindow)return t.warn("Cannot send message - iframe not found",{instanceId:e}),void this.queueMessage(e,s);const i=this.getNextSequence(e),a=Object.assign(Object.assign({},s),{sequence:i});this.securityOptions.enableSignatureValidation&&(a.signature=this.generateSignature(a));try{n.contentWindow.postMessage(JSON.stringify(a),"*"),t.debug("Message sent",{instanceId:e,type:a.type,sequence:i})}catch(n){t.error("Failed to send message",{error:n,instanceId:e}),this.queueMessage(e,s)}}queueMessage(e,t){const s=this.messageQueue.get(e)||[];s.push({message:t,retryCount:0,maxRetries:3,timestamp:Date.now()}),this.messageQueue.set(e,s),this.scheduleRetry(e)}scheduleRetry(e){if(this.pendingMessages.has(e))return;const t=setTimeout((()=>{this.processMessageQueue(e),this.pendingMessages.delete(e)}),1e3);this.pendingMessages.set(e,t)}processMessageQueue(e){const s=this.messageQueue.get(e);if(!s||0===s.length)return;const n=[];s.forEach((s=>{s.retryCount<s.maxRetries?(s.retryCount++,this.sendMessage(e,s.message),s.retryCount<s.maxRetries&&n.push(s)):t.warn("Message retry limit exceeded",{instanceId:e,message:s.message})})),this.messageQueue.set(e,n)}getNextSequence(e){const t=(this.sequenceNumbers.get(e)||0)+1;return this.sequenceNumbers.set(e,t),t}startHeartbeat(e){if(this.heartbeatIntervals.has(e))return;const s=setInterval((()=>{this.sendMessage(e,{type:"heartbeat",instanceId:e,payload:{ping:Date.now()},timestamp:Date.now(),version:"1.0"})}),this.securityOptions.heartbeatInterval);this.heartbeatIntervals.set(e,s),t.debug("Heartbeat started",{instanceId:e,interval:this.securityOptions.heartbeatInterval})}stopHeartbeat(e){const s=this.heartbeatIntervals.get(e);s&&(clearInterval(s),this.heartbeatIntervals.delete(e),t.debug("Heartbeat stopped",{instanceId:e}))}cleanup(){this.heartbeatIntervals.forEach((e=>clearInterval(e))),this.heartbeatIntervals.clear(),this.pendingMessages.forEach((e=>clearTimeout(e))),this.pendingMessages.clear(),this.messageHandlers.clear(),this.messageQueue.clear(),this.sequenceNumbers.clear(),t.info("WidgeticMessenger cleanup complete")}createWidgetController(t,s){const n={subscribe:(e,s)=>this.subscribeToCustomEvent(t,e,s),unsubscribe:(e,s)=>{this.unsubscribeFromCustomEvent(t,e,s)},callFunction:(e,...s)=>this.callWidgetFunction(t,e,s),getState:e=>this.callWidgetFunction(t,"getState",e?[e]:[]),setState:(e,s)=>this.callWidgetFunction(t,"setState",[e,s]),updateConfig:e=>this.callWidgetFunction(t,"updateConfig",[e]),refresh:()=>this.callWidgetFunction(t,"refresh",[]),destroy:()=>this.callWidgetFunction(t,"destroy",[]),emit:(e,s,n)=>{this.sendCustomEvent(t,e,s,n)},registerTextField:(s,n)=>e(this,void 0,void 0,(function*(){const{getTextFieldManager:e}=yield import("./security.js").then((function(e){return e.t}));return e().registerTextField(t,s,n)})),updateTextField:(s,n,i)=>e(this,void 0,void 0,(function*(){const{getTextFieldManager:e}=yield import("./security.js").then((function(e){return e.t}));e().updateTextField(t,s,n,{autoPersist:!0,persistState:!0},i)})),getTextField:s=>e(this,void 0,void 0,(function*(){const{getTextFieldManager:e}=yield import("./security.js").then((function(e){return e.t}));return e().getTextField(t,s)})),clearTextField:s=>e(this,void 0,void 0,(function*(){const{getTextFieldManager:e}=yield import("./security.js").then((function(e){return e.t}));e().clearTextField(t,s)})),getTextFields:()=>e(this,void 0,void 0,(function*(){const{getTextFieldManager:e}=yield import("./security.js").then((function(e){return e.t}));return e().getWidgetTextFields(t)})),clearAllTextFields:()=>e(this,void 0,void 0,(function*(){const{getTextFieldManager:e}=yield import("./security.js").then((function(e){return e.t}));e().clearWidgetTextFields(t)}))};return this.widgetControllers.set(t,n),n}subscribeToCustomEvent(e,s,n){this.customEventSubscriptions.has(e)||this.customEventSubscriptions.set(e,new Map);const i=this.customEventSubscriptions.get(e);i.has(s)||i.set(s,new Set);const a=i.get(s);return a.add(n),t.debug("Subscribed to custom event",{instanceId:e,eventName:s,totalSubscribers:a.size}),()=>{a.delete(n),0===a.size&&i.delete(s),0===i.size&&this.customEventSubscriptions.delete(e)}}unsubscribeFromCustomEvent(e,s,n){const i=this.customEventSubscriptions.get(e);if(!i)return;const a=i.get(s);a&&(n?a.delete(n):a.clear(),0===a.size&&i.delete(s),0===i.size&&this.customEventSubscriptions.delete(e),t.debug("Unsubscribed from custom event",{instanceId:e,eventName:s}))}callWidgetFunction(e,s,n,i=1e4){return new Promise(((a,r)=>{const o=`${e}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,d=setTimeout((()=>{this.pendingFunctionCalls.delete(o),r(new Error(`Function call timeout: ${s}`))}),i);this.pendingFunctionCalls.set(o,{resolve:a,reject:r,timeout:d}),this.sendMessage(e,{type:"function-call",instanceId:e,payload:{functionName:s,args:n,requestId:o},timestamp:Date.now(),version:"1.0"}),t.debug("Sent function call",{instanceId:e,functionName:s,args:n,requestId:o})}))}sendCustomEvent(e,s,n,i){this.sendMessage(e,{type:"custom-event",instanceId:e,payload:{eventName:s,eventData:n,metadata:i},timestamp:Date.now(),version:"1.0"}),t.debug("Sent custom event",{instanceId:e,eventName:s})}registerFunctionHandlers(e,s){this.functionCallHandlers.has(e)||this.functionCallHandlers.set(e,new Map);const n=this.functionCallHandlers.get(e);Object.entries(s).forEach((([e,t])=>{n.set(e,t)})),t.debug("Registered function handlers",{instanceId:e,functions:Object.keys(s)})}unregisterFunctionHandlers(e,s){const n=this.functionCallHandlers.get(e);n&&(s?s.forEach((e=>n.delete(e))):n.clear(),0===n.size&&this.functionCallHandlers.delete(e),t.debug("Unregistered function handlers",{instanceId:e,functions:s||"all"}))}getWidgetController(e){return this.widgetControllers.get(e)||null}removeWidgetController(e){this.customEventSubscriptions.delete(e),this.functionCallHandlers.delete(e);const s=[];this.pendingFunctionCalls.forEach(((t,n)=>{n.startsWith(e)&&(clearTimeout(t.timeout),t.reject(new Error("Widget controller removed")),s.push(n))})),s.forEach((e=>this.pendingFunctionCalls.delete(e))),this.widgetControllers.delete(e),t.debug("Removed widget controller",{instanceId:e})}isActive(){return this.messageHandlers.size>0||this.widgetControllers.size>0}getCustomEventSubscriptions(){let e=0;return this.customEventSubscriptions.forEach((t=>{t.forEach((t=>{e+=t.size}))})),e}getFunctionHandlers(){let e=0;return this.functionCallHandlers.forEach((t=>{e+=t.size})),e}getMessagingStats(){return{activeHandlers:this.messageHandlers.size,widgetControllers:this.widgetControllers.size,customEventSubscriptions:this.getCustomEventSubscriptions(),functionHandlers:this.getFunctionHandlers(),pendingFunctionCalls:this.pendingFunctionCalls.size,heartbeatIntervals:this.heartbeatIntervals.size,messageQueues:Array.from(this.messageQueue.entries()).map((([e,t])=>({instanceId:e,queuedMessages:t.length})))}}}let i=null;function a(e){return i||(i=new n(e)),i}function r(){i&&(i.cleanup(),i=null)}export{n as WidgeticMessenger,a as getMessenger,r as resetMessenger};
1
+ import{_ as e}from"./vendor.js";import{l as t,a as s}from"./core.js";import"./api.js";import"./renderers.js";import"./scanner.js";import"./media.js";import"./messaging.js";import"./display.js";import"./advanced.js";import"./security.js";import"./performance.js";class n{constructor(e={}){this.messageHandlers=new Map,this.messageQueue=new Map,this.pendingMessages=new Map,this.heartbeatIntervals=new Map,this.sequenceNumbers=new Map,this.allowedOrigins=new Set,this.customEventSubscriptions=new Map,this.functionCallHandlers=new Map,this.pendingFunctionCalls=new Map,this.widgetControllers=new Map,this.securityOptions=Object.assign({enableSignatureValidation:!1,allowedOrigins:[],messageTimeout:3e4,enableHeartbeat:!1,heartbeatInterval:3e4},e),this.setupAllowedOrigins(this.securityOptions.allowedOrigins),this.setupGlobalMessageListener(),t.info("WidgeticMessenger initialized",{securityOptions:this.securityOptions})}setupAllowedOrigins(e){s.CLIENT_URL&&this.allowedOrigins.add(s.CLIENT_URL),"undefined"!=typeof window&&window.location&&this.allowedOrigins.add(window.location.origin),e&&e.forEach((e=>this.allowedOrigins.add(e)));const n=new Set;this.allowedOrigins.forEach((e=>{try{const t=new URL(e);n.add(t.origin)}catch(t){n.add(e)}})),this.allowedOrigins=n,t.debug("Allowed origins configured",{origins:Array.from(this.allowedOrigins)})}setupGlobalMessageListener(){"undefined"!=typeof window&&window.addEventListener("message",(e=>{this.handleIncomingMessage(e)}))}validateMessage(e){if(!this.allowedOrigins.has(e.origin))return t.warn("Message from unauthorized origin",{origin:e.origin}),null;try{const s="string"==typeof e.data?JSON.parse(e.data):e.data;return this.isValidWidgeticMessage(s)?this.securityOptions.enableSignatureValidation&&!this.validateSignature(s)?(t.warn("Message signature validation failed",{instanceId:s.instanceId}),null):s:(t.warn("Invalid message structure",{message:s}),null)}catch(s){return t.warn("Failed to parse message",{error:s,data:e.data}),null}}isValidWidgeticMessage(e){return e&&"string"==typeof e.type&&"string"==typeof e.instanceId&&"number"==typeof e.timestamp&&"string"==typeof e.version&&void 0!==e.payload}validateSignature(e){return!0}generateSignature(e){const t=JSON.stringify(Object.assign({},e));return btoa(t).substring(0,16)}handleIncomingMessage(e){const s=this.validateMessage(e);if(!s)return;switch(t.debug("Received valid message",{type:s.type,instanceId:s.instanceId}),s.type){case"heartbeat":return void this.handleHeartbeat(s);case"auth":return void this.handleAuthentication(s);case"custom-event":return void this.handleCustomEvent(s);case"function-call":return void this.handleFunctionCall(s);case"function-response":return void this.handleFunctionResponse(s);case"text-field-change":return void this.handleTextFieldChange(s)}const n=this.messageHandlers.get(s.instanceId);if(n)try{n(s)}catch(e){t.error("Message handler error",{error:e,instanceId:s.instanceId})}else t.debug("No handler for message",{instanceId:s.instanceId,type:s.type})}handleHeartbeat(e){t.debug("Heartbeat received",{instanceId:e.instanceId}),this.sendMessage(e.instanceId,{type:"heartbeat",instanceId:e.instanceId,payload:{response:!0},timestamp:Date.now(),version:"1.0"})}handleAuthentication(e){t.debug("Authentication message received",{instanceId:e.instanceId})}handleTextFieldChange(e){const{fieldId:s,text:n,metadata:i}=e.payload;s&&"string"==typeof n?(import("./security.js").then((function(e){return e.s})).then((({getSecurityManager:a})=>{const r=a().validateTextFieldUpdate(e.instanceId,s,n,i);if(!r.allowed)return t.warn("Text field change blocked by security",{instanceId:e.instanceId,fieldId:s,reason:r.reason,severity:r.severity}),void document.dispatchEvent(new CustomEvent("widgetic:text-field-security-blocked",{detail:{instanceId:e.instanceId,compositionId:e.compositionId,fieldId:s,reason:r.reason,severity:r.severity,originalTextLength:n.length,timestamp:Date.now()},bubbles:!0}));t.debug("Text field change received",{instanceId:e.instanceId,fieldId:s,textLength:n.length,sanitized:!(!r.sanitizedText||r.sanitizedText===n)}),import("./security.js").then((function(e){return e.t})).then((({getTextFieldManager:t})=>{const a=t(),o=r.sanitizedText||n;a.updateTextField(e.instanceId,s,o,{autoPersist:!0,persistState:!0,textType:(null==i?void 0:i.textType)||"custom",debounceDelay:(null==i?void 0:i.debounceDelay)||1e3,maxLength:null==i?void 0:i.maxLength},Object.assign(Object.assign({},i),{securityValidated:!0,sanitized:o!==n}))})).catch((s=>{t.warn("Failed to handle text field change",{error:s,instanceId:e.instanceId})}))})).catch((s=>{t.warn("Failed to validate text field security",{error:s,instanceId:e.instanceId})})),document.dispatchEvent(new CustomEvent("widgetic:text-field-change",{detail:{instanceId:e.instanceId,compositionId:e.compositionId,fieldId:s,text:n,metadata:i},bubbles:!0}))):t.warn("Invalid text field change message",{instanceId:e.instanceId,payload:e.payload})}handleCustomEvent(e){const{eventName:s,eventData:n,metadata:i}=e.payload,a=this.customEventSubscriptions.get(e.instanceId);if(!a)return;const r=a.get(s);r&&0!==r.size&&(t.debug("Dispatching custom event",{instanceId:e.instanceId,eventName:s,subscriberCount:r.size}),r.forEach((a=>{try{a(n,i)}catch(n){t.error("Custom event callback error",{error:n,eventName:s,instanceId:e.instanceId})}})),document.dispatchEvent(new CustomEvent(`widgetic:custom:${s}`,{detail:{instanceId:e.instanceId,compositionId:e.compositionId,eventName:s,eventData:n,metadata:i},bubbles:!0})))}handleFunctionCall(e){const{functionName:s,args:n,requestId:i}=e.payload,a=this.functionCallHandlers.get(e.instanceId);if(!a)return void this.sendFunctionResponse(e.instanceId,i,!1,void 0,"No function handlers registered");const r=a.get(s);if(r){t.debug("Executing function call",{instanceId:e.instanceId,functionName:s,args:n});try{const t=r(...n);t&&"function"==typeof t.then?t.then((t=>this.sendFunctionResponse(e.instanceId,i,!0,t))).catch((t=>this.sendFunctionResponse(e.instanceId,i,!1,void 0,t.message||"Function execution failed"))):this.sendFunctionResponse(e.instanceId,i,!0,t)}catch(t){this.sendFunctionResponse(e.instanceId,i,!1,void 0,t instanceof Error?t.message:"Function execution failed")}}else this.sendFunctionResponse(e.instanceId,i,!1,void 0,`Function '${s}' not found`)}handleFunctionResponse(e){const{requestId:s,success:n,result:i,error:a}=e.payload,r=this.pendingFunctionCalls.get(s);r?(clearTimeout(r.timeout),this.pendingFunctionCalls.delete(s),n?r.resolve(i):r.reject(new Error(a||"Function call failed"))):t.warn("Received response for unknown function call",{requestId:s})}sendFunctionResponse(e,t,s,n,i){this.sendMessage(e,{type:"function-response",instanceId:e,payload:{requestId:t,success:s,result:n,error:i},timestamp:Date.now(),version:"1.0"})}registerHandler(e,s){this.messageHandlers.set(e,s),t.debug("Message handler registered",{instanceId:e}),this.messageQueue.has(e)||this.messageQueue.set(e,[]),this.sequenceNumbers.set(e,0),this.securityOptions.enableHeartbeat&&this.startHeartbeat(e)}unregisterHandler(e){this.messageHandlers.delete(e),this.messageQueue.delete(e),this.sequenceNumbers.delete(e),this.stopHeartbeat(e),t.debug("Message handler unregistered",{instanceId:e})}sendMessage(e,s){const n=document.querySelector(`[data-widgetic-id="${e}"]`);if(!n||!n.contentWindow)return t.warn("Cannot send message - iframe not found",{instanceId:e}),void this.queueMessage(e,s);const i=this.getNextSequence(e),a=Object.assign(Object.assign({},s),{sequence:i});this.securityOptions.enableSignatureValidation&&(a.signature=this.generateSignature(a));try{n.contentWindow.postMessage(JSON.stringify(a),"*"),t.debug("Message sent",{instanceId:e,type:a.type,sequence:i})}catch(n){t.error("Failed to send message",{error:n,instanceId:e}),this.queueMessage(e,s)}}queueMessage(e,t){const s=this.messageQueue.get(e)||[];s.push({message:t,retryCount:0,maxRetries:3,timestamp:Date.now()}),this.messageQueue.set(e,s),this.scheduleRetry(e)}scheduleRetry(e){if(this.pendingMessages.has(e))return;const t=setTimeout((()=>{this.processMessageQueue(e),this.pendingMessages.delete(e)}),1e3);this.pendingMessages.set(e,t)}processMessageQueue(e){const s=this.messageQueue.get(e);if(!s||0===s.length)return;const n=[];s.forEach((s=>{s.retryCount<s.maxRetries?(s.retryCount++,this.sendMessage(e,s.message),s.retryCount<s.maxRetries&&n.push(s)):t.warn("Message retry limit exceeded",{instanceId:e,message:s.message})})),this.messageQueue.set(e,n)}getNextSequence(e){const t=(this.sequenceNumbers.get(e)||0)+1;return this.sequenceNumbers.set(e,t),t}startHeartbeat(e){if(this.heartbeatIntervals.has(e))return;const s=setInterval((()=>{this.sendMessage(e,{type:"heartbeat",instanceId:e,payload:{ping:Date.now()},timestamp:Date.now(),version:"1.0"})}),this.securityOptions.heartbeatInterval);this.heartbeatIntervals.set(e,s),t.debug("Heartbeat started",{instanceId:e,interval:this.securityOptions.heartbeatInterval})}stopHeartbeat(e){const s=this.heartbeatIntervals.get(e);s&&(clearInterval(s),this.heartbeatIntervals.delete(e),t.debug("Heartbeat stopped",{instanceId:e}))}cleanup(){this.heartbeatIntervals.forEach((e=>clearInterval(e))),this.heartbeatIntervals.clear(),this.pendingMessages.forEach((e=>clearTimeout(e))),this.pendingMessages.clear(),this.messageHandlers.clear(),this.messageQueue.clear(),this.sequenceNumbers.clear(),t.info("WidgeticMessenger cleanup complete")}createWidgetController(t,s){const n={subscribe:(e,s)=>this.subscribeToCustomEvent(t,e,s),unsubscribe:(e,s)=>{this.unsubscribeFromCustomEvent(t,e,s)},callFunction:(e,...s)=>this.callWidgetFunction(t,e,s),getState:e=>this.callWidgetFunction(t,"getState",e?[e]:[]),setState:(e,s)=>this.callWidgetFunction(t,"setState",[e,s]),updateConfig:e=>this.callWidgetFunction(t,"updateConfig",[e]),refresh:()=>this.callWidgetFunction(t,"refresh",[]),destroy:()=>this.callWidgetFunction(t,"destroy",[]),emit:(e,s,n)=>{this.sendCustomEvent(t,e,s,n)},registerTextField:(s,n)=>e(this,void 0,void 0,(function*(){const{getTextFieldManager:e}=yield import("./security.js").then((function(e){return e.t}));return e().registerTextField(t,s,n)})),updateTextField:(s,n,i)=>e(this,void 0,void 0,(function*(){const{getTextFieldManager:e}=yield import("./security.js").then((function(e){return e.t}));e().updateTextField(t,s,n,{autoPersist:!0,persistState:!0},i)})),getTextField:s=>e(this,void 0,void 0,(function*(){const{getTextFieldManager:e}=yield import("./security.js").then((function(e){return e.t}));return e().getTextField(t,s)})),clearTextField:s=>e(this,void 0,void 0,(function*(){const{getTextFieldManager:e}=yield import("./security.js").then((function(e){return e.t}));e().clearTextField(t,s)})),getTextFields:()=>e(this,void 0,void 0,(function*(){const{getTextFieldManager:e}=yield import("./security.js").then((function(e){return e.t}));return e().getWidgetTextFields(t)})),clearAllTextFields:()=>e(this,void 0,void 0,(function*(){const{getTextFieldManager:e}=yield import("./security.js").then((function(e){return e.t}));e().clearWidgetTextFields(t)}))};return this.widgetControllers.set(t,n),n}subscribeToCustomEvent(e,s,n){this.customEventSubscriptions.has(e)||this.customEventSubscriptions.set(e,new Map);const i=this.customEventSubscriptions.get(e);i.has(s)||i.set(s,new Set);const a=i.get(s);return a.add(n),t.debug("Subscribed to custom event",{instanceId:e,eventName:s,totalSubscribers:a.size}),()=>{a.delete(n),0===a.size&&i.delete(s),0===i.size&&this.customEventSubscriptions.delete(e)}}unsubscribeFromCustomEvent(e,s,n){const i=this.customEventSubscriptions.get(e);if(!i)return;const a=i.get(s);a&&(n?a.delete(n):a.clear(),0===a.size&&i.delete(s),0===i.size&&this.customEventSubscriptions.delete(e),t.debug("Unsubscribed from custom event",{instanceId:e,eventName:s}))}callWidgetFunction(e,s,n,i=1e4){return new Promise(((a,r)=>{const o=`${e}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,d=setTimeout((()=>{this.pendingFunctionCalls.delete(o),r(new Error(`Function call timeout: ${s}`))}),i);this.pendingFunctionCalls.set(o,{resolve:a,reject:r,timeout:d}),this.sendMessage(e,{type:"function-call",instanceId:e,payload:{functionName:s,args:n,requestId:o},timestamp:Date.now(),version:"1.0"}),t.debug("Sent function call",{instanceId:e,functionName:s,args:n,requestId:o})}))}sendCustomEvent(e,s,n,i){this.sendMessage(e,{type:"custom-event",instanceId:e,payload:{eventName:s,eventData:n,metadata:i},timestamp:Date.now(),version:"1.0"}),t.debug("Sent custom event",{instanceId:e,eventName:s})}registerFunctionHandlers(e,s){this.functionCallHandlers.has(e)||this.functionCallHandlers.set(e,new Map);const n=this.functionCallHandlers.get(e);Object.entries(s).forEach((([e,t])=>{n.set(e,t)})),t.debug("Registered function handlers",{instanceId:e,functions:Object.keys(s)})}unregisterFunctionHandlers(e,s){const n=this.functionCallHandlers.get(e);n&&(s?s.forEach((e=>n.delete(e))):n.clear(),0===n.size&&this.functionCallHandlers.delete(e),t.debug("Unregistered function handlers",{instanceId:e,functions:s||"all"}))}getWidgetController(e){return this.widgetControllers.get(e)||null}removeWidgetController(e){this.customEventSubscriptions.delete(e),this.functionCallHandlers.delete(e);const s=[];this.pendingFunctionCalls.forEach(((t,n)=>{n.startsWith(e)&&(clearTimeout(t.timeout),t.reject(new Error("Widget controller removed")),s.push(n))})),s.forEach((e=>this.pendingFunctionCalls.delete(e))),this.widgetControllers.delete(e),t.debug("Removed widget controller",{instanceId:e})}isActive(){return this.messageHandlers.size>0||this.widgetControllers.size>0}getCustomEventSubscriptions(){let e=0;return this.customEventSubscriptions.forEach((t=>{t.forEach((t=>{e+=t.size}))})),e}getFunctionHandlers(){let e=0;return this.functionCallHandlers.forEach((t=>{e+=t.size})),e}getMessagingStats(){return{activeHandlers:this.messageHandlers.size,widgetControllers:this.widgetControllers.size,customEventSubscriptions:this.getCustomEventSubscriptions(),functionHandlers:this.getFunctionHandlers(),pendingFunctionCalls:this.pendingFunctionCalls.size,heartbeatIntervals:this.heartbeatIntervals.size,messageQueues:Array.from(this.messageQueue.entries()).map((([e,t])=>({instanceId:e,queuedMessages:t.length})))}}}let i=null;function a(e){return i||(i=new n(e)),i}function r(){i&&(i.cleanup(),i=null)}export{n as WidgeticMessenger,a as getMessenger,r as resetMessenger};
@@ -1 +1 @@
1
- import{_ as e}from"./vendor.js";import{r as t,a as i,E as n,b as o,g as s,d as a,c as d}from"./api.js";import{l as r,a as c,b as l,d as u}from"./core.js";import{g,a as h}from"./media.js";import{getMessenger as m}from"./messaging.js";import{R as p}from"./display.js";const b="undefined"!=typeof HTMLElement?HTMLElement:class{};class f extends b{static get observedAttributes(){return["composition-id","width","height","resize","autoscale","adaptive","theme"]}constructor(){super(),this.svelteComponent=null,this.compositionData=null,this.widgetData=null,this.loadedModule=null,this.isInitialized=!1,this.isWidgetConnected=!1,this.resizeObserver=null,this.eventListeners=new Map,this.widgetState={ready:!1,error:null,loading:!1,data:{}},this.instanceId=this.generateInstanceId(),this.cssNamespace=`widgetic-${this.instanceId}`,this.initializeCSSIsolation(),r.debug("WidgeticWidget created",{instanceId:this.instanceId})}connectedCallback(){return e(this,void 0,void 0,(function*(){if(!this.isWidgetConnected){this.isWidgetConnected=!0,r.debug("WidgeticWidget connected",{instanceId:this.instanceId});try{this.setLoadingState(!0);const e=this.getAttribute("composition-id");if(!e)throw new Error("composition-id attribute is required");const s=yield t(e);if("refused"===s.status)throw i(e,s.refusal),new Error(n);const a="found"===s.status?s.payload:null;if(null==a?void 0:a.embedUrl)return this.innerHTML="",this.appendChild(o(a.embedUrl,this.getAttribute("width")||"400",this.getAttribute("height")||"300",e,a)),void this.setWidgetReady();yield this.loadWidgetData(e),this.widgetData&&(yield this.loadWidgetModule()),yield this.initializeWidget(),this.setupResponsiveBehavior(),this.setupEventHandling(),this.setWidgetReady()}catch(e){r.error("WidgeticWidget initialization failed",{instanceId:this.instanceId,error:e}),this.setErrorState(e)}}}))}disconnectedCallback(){this.isWidgetConnected&&(r.debug("WidgeticWidget disconnected",{instanceId:this.instanceId}),this.cleanup(),this.isWidgetConnected=!1)}attributeChangedCallback(e,t,i){if(this.isInitialized&&t!==i){switch(r.debug("WidgeticWidget attribute changed",{instanceId:this.instanceId,attribute:e,oldValue:t,newValue:i}),e){case"width":case"height":this.updateDimensions();break;case"resize":this.updateResizeMode();break;case"autoscale":this.updateAutoscale();break;case"adaptive":this.updateAdaptive();break;case"theme":this.updateTheme()}this.notifyWidgetPropsChanged()}}initializeCSSIsolation(){this.setAttribute("data-widgetic-instance",this.instanceId),this.addBaseStyles(),this.initializeCSSCustomProperties()}addBaseStyles(){const e=`widgetic-base-styles-${this.instanceId}`;if(document.getElementById(e))return;const t=document.createElement("style");t.id=e,t.textContent=`\n /* Widget base styles with namespace isolation */\n widgetic-widget[data-widgetic-instance="${this.instanceId}"] {\n /* CSS Reset for widget container */\n all: initial;\n \n /* Widget container properties */\n display: block;\n box-sizing: border-box;\n position: relative;\n \n /* CSS custom properties with namespacing */\n --widgetic-instance: ${this.instanceId};\n --widgetic-primary: var(--widgetic-${this.instanceId}-primary, #007bff);\n --widgetic-secondary: var(--widgetic-${this.instanceId}-secondary, #6c757d);\n --widgetic-background: var(--widgetic-${this.instanceId}-background, #ffffff);\n --widgetic-text: var(--widgetic-${this.instanceId}-text, #333333);\n --widgetic-border: var(--widgetic-${this.instanceId}-border, #dee2e6);\n \n /* Widget content isolation */\n contain: layout style paint;\n isolation: isolate;\n }\n\n /* Prevent external CSS interference */\n widgetic-widget[data-widgetic-instance="${this.instanceId}"] * {\n box-sizing: border-box;\n }\n\n /* Loading state styles */\n widgetic-widget[data-widgetic-instance="${this.instanceId}"][data-loading="true"] {\n min-height: 120px;\n background: linear-gradient(90deg, #f0f0f0 25%, transparent 37%, #f0f0f0 63%);\n background-size: 400% 100%;\n animation: widgetic-loading-${this.instanceId} 1.5s ease-in-out infinite;\n }\n\n @keyframes widgetic-loading-${this.instanceId} {\n 0% { background-position: 100% 50%; }\n 100% { background-position: 0% 50%; }\n }\n\n /* Error state styles */\n widgetic-widget[data-widgetic-instance="${this.instanceId}"][data-error="true"] {\n border: 2px dashed #dc3545;\n background-color: #f8d7da;\n color: #721c24;\n padding: 16px;\n text-align: center;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;\n }\n `,document.head.appendChild(t)}initializeCSSCustomProperties(){const e=this.getAttribute("theme");if(e)try{const t=JSON.parse(e);Object.entries(t).forEach((([e,t])=>{this.style.setProperty(`--widgetic-${this.instanceId}-${e}`,String(t))}))}catch(t){r.warn("Invalid theme attribute",{instanceId:this.instanceId,theme:e})}}loadWidgetData(t){return e(this,void 0,void 0,(function*(){const e=s();this.compositionData=yield e.getComposition(t),this.widgetData=yield e.getWidget(this.compositionData.widgetId),r.debug("Widget data loaded",{instanceId:this.instanceId,compositionId:t,widgetId:this.compositionData.widgetId})}))}loadWidgetModule(){return e(this,void 0,void 0,(function*(){if(!this.widgetData)return;const e=a();this.loadedModule=yield e.loadModule(this.widgetData),r.debug("Widget module loaded",{instanceId:this.instanceId,moduleUrl:this.widgetData.moduleUrl,loadTime:this.loadedModule.loadTime})}))}initializeWidget(){return e(this,void 0,void 0,(function*(){if(!this.loadedModule||!this.compositionData)throw new Error("Widget module or composition data not loaded");try{const{component:e}=this.loadedModule.module,t=document.createElement("div");if(t.className=`widgetic-content-${this.instanceId}`,this.applyWidgetProperties(t),e.$$typeof)yield this.initializeReactComponent(t,e);else if(e._isVue||e.__isVue)yield this.initializeVueComponent(t,e);else{if("function"!=typeof e)throw new Error("Unsupported component type");yield this.initializeSvelteOrVanillaComponent(t,e)}this.innerHTML="",this.appendChild(t),this.isInitialized=!0,r.debug("Widget initialized successfully",{instanceId:this.instanceId})}catch(e){throw r.error("Widget initialization failed",{instanceId:this.instanceId,error:e}),e}}))}initializeReactComponent(t,i){return e(this,void 0,void 0,(function*(){if("undefined"==typeof window||!window.React||!window.ReactDOM)throw new Error("React not available globally");{const e=window.React,n=window.ReactDOM,o=this.getWidgetProps(),s=e.createElement(i,o);n.render(s,t)}}))}initializeVueComponent(t,i){return e(this,void 0,void 0,(function*(){if("undefined"==typeof window||!window.Vue)throw new Error("Vue not available globally");{const e=window.Vue,n=this.getWidgetProps();new e({el:t,render:e=>e(i,{props:n})})}}))}initializeSvelteOrVanillaComponent(t,i){return e(this,void 0,void 0,(function*(){var e;const n=this.getWidgetProps();if(i.$$prop_def||(null===(e=i.prototype)||void 0===e?void 0:e.$$prop_def))this.svelteComponent=new i({target:t,props:n});else if(i.prototype&&i.prototype.constructor===i){const e=new i(t,n);"function"==typeof e.render&&(yield e.render())}else if("function"==typeof i)yield i(t,n);else{if(!i||"function"!=typeof i.init)throw new Error("Unknown component type");yield i.init(t,n)}}))}getWidgetProps(){var e,t;return{config:(null===(e=this.compositionData)||void 0===e?void 0:e.config)||{},metadata:(null===(t=this.compositionData)||void 0===t?void 0:t.metadata)||{},instance:this.instanceId,element:this,dimensions:{width:this.getAttribute("width")||"100%",height:this.getAttribute("height")||"400"},resize:this.getAttribute("resize")||"responsive",autoscale:"true"===this.getAttribute("autoscale"),adaptive:parseInt(this.getAttribute("adaptive")||"768"),state:this.widgetState,onStateChange:this.handleStateChange.bind(this),onResize:this.handleResize.bind(this),onError:this.handleError.bind(this)}}applyWidgetProperties(e){var t;const i=this.getAttribute("width")||"100%",n=this.getAttribute("height")||"400",o=this.getAttribute("resize")||"responsive";switch(e.style.width="number"==typeof i?`${i}px`:i,e.style.height="number"==typeof n?`${n}px`:n,o){case"fill-width":e.style.width="100%";break;case"responsive":e.style.maxWidth="100%",e.style.height="auto"}e.classList.add(`widgetic-widget-${(null===(t=this.widgetData)||void 0===t?void 0:t.type)||"unknown"}`)}setupResponsiveBehavior(){const e=parseInt(this.getAttribute("adaptive")||"768"),t="true"===this.getAttribute("autoscale"),i=this.getAttribute("resize")||"responsive";t&&"ResizeObserver"in window&&(this.resizeObserver=new ResizeObserver((e=>{for(const t of e)this.handleAutoscale(t)})),this.resizeObserver.observe(this)),"responsive"!==i&&"fill-width"!==i||this.setupAdaptiveBehavior(e)}setupAdaptiveBehavior(e){const t=window.matchMedia(`(max-width: ${e}px)`),i=t=>{this.setAttribute("data-mobile",t.matches?"true":"false"),this.dispatchEvent(new CustomEvent("widgetic:adaptive",{detail:{isMobile:t.matches,breakpoint:e}}))};i(t),t.addEventListener("change",i),this.eventListeners.set("adaptive",(()=>{t.removeEventListener("change",i)}))}handleAutoscale(e){const{width:t,height:i}=e.contentRect;this.dispatchEvent(new CustomEvent("widgetic:resize",{detail:{width:t,height:i}})),this.widgetState.data.dimensions={width:t,height:i}}setupEventHandling(){const e=e=>{this.dispatchEvent(new CustomEvent("widgetic:interaction",{detail:{type:"click",originalEvent:e},bubbles:!0}))};this.addEventListener("click",e),this.eventListeners.set("click",(()=>{this.removeEventListener("click",e)}));const t=e=>{e.target instanceof HTMLFormElement&&this.handleFormSubmission(e)};this.addEventListener("submit",t),this.eventListeners.set("submit",(()=>{this.removeEventListener("submit",t)}))}handleFormSubmission(e){e.preventDefault();const t=e.target,i=new FormData(t),n={};i.forEach(((e,t)=>{n[t]=e})),this.widgetState.data.formData=n,this.dispatchEvent(new CustomEvent("widgetic:form-submit",{detail:{data:n,form:t},bubbles:!0})),r.debug("Form submitted",{instanceId:this.instanceId,data:n})}handleStateChange(e){this.widgetState.data=Object.assign(Object.assign({},this.widgetState.data),e),this.dispatchEvent(new CustomEvent("widgetic:state-change",{detail:{state:this.widgetState.data},bubbles:!0}))}handleResize(e){this.dispatchEvent(new CustomEvent("widgetic:resize",{detail:e,bubbles:!0}))}handleError(e){this.setErrorState(e)}updateDimensions(){const e=this.querySelector(`.widgetic-content-${this.instanceId}`);e&&this.applyWidgetProperties(e)}updateResizeMode(){this.updateDimensions(),this.setupResponsiveBehavior()}updateAutoscale(){this.setupResponsiveBehavior()}updateAdaptive(){const e=parseInt(this.getAttribute("adaptive")||"768");this.setupAdaptiveBehavior(e)}updateTheme(){this.initializeCSSCustomProperties()}notifyWidgetPropsChanged(){this.svelteComponent&&"function"==typeof this.svelteComponent.$set&&this.svelteComponent.$set(this.getWidgetProps()),this.dispatchEvent(new CustomEvent("widgetic:props-changed",{detail:{props:this.getWidgetProps()}}))}setLoadingState(e){this.widgetState.loading=e,this.setAttribute("data-loading",e?"true":"false"),e&&(this.innerHTML=`\n <div class="widgetic-loading-${this.instanceId}">\n <div>Loading widget...</div>\n </div>\n `)}setWidgetReady(){this.widgetState.ready=!0,this.widgetState.loading=!1,this.widgetState.error=null,this.setAttribute("data-ready","true"),this.removeAttribute("data-loading"),this.removeAttribute("data-error"),this.dispatchEvent(new CustomEvent("widgetic:ready",{detail:{instanceId:this.instanceId},bubbles:!0})),r.info("Widget ready",{instanceId:this.instanceId})}setErrorState(e){this.widgetState.error=e,this.widgetState.loading=!1,this.widgetState.ready=!1,this.setAttribute("data-error","true"),this.removeAttribute("data-loading"),this.removeAttribute("data-ready"),this.innerHTML=`\n <div class="widgetic-error-${this.instanceId}">\n <strong>Widget Error</strong><br>\n <small>${e.message}</small>\n </div>\n `,this.dispatchEvent(new CustomEvent("widgetic:error",{detail:{error:e.message,instanceId:this.instanceId},bubbles:!0})),r.error("Widget error",{instanceId:this.instanceId,error:e})}getState(){return Object.assign({},this.widgetState.data)}setState(e){this.handleStateChange(e)}refresh(){return e(this,void 0,void 0,(function*(){this.cleanup(),this.isInitialized=!1,this.isWidgetConnected=!1,yield this.connectedCallback()}))}cleanup(){this.svelteComponent&&"function"==typeof this.svelteComponent.$destroy&&(this.svelteComponent.$destroy(),this.svelteComponent=null),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.eventListeners.forEach((e=>{if("function"==typeof e)try{e()}catch(e){r.warn("Failed to cleanup event listener",{instanceId:this.instanceId,error:e})}})),this.eventListeners.clear();const e=document.getElementById(`widgetic-base-styles-${this.instanceId}`);e&&e.remove(),r.debug("Widget cleanup complete",{instanceId:this.instanceId})}generateInstanceId(){return`${Date.now()}-${Math.random().toString(36).substring(2,11)}`}}function w(){"undefined"!=typeof window&&"undefined"!=typeof customElements&&(customElements.get("widgetic-widget")||(customElements.define("widgetic-widget",f),r.info("WidgeticWidget custom element registered")))}class v{constructor(){this.observers=new Map,this.mutationObservers=new Map,this.timeouts=new Map,this.animationIds=new Map,this.storageKey="widgetic_autoscale_heights"}static getInstance(){return v.instance||(v.instance=new v),v.instance}enableAutoScale(e,t,i={enabled:!0}){if(!i.enabled)return;const n=Object.assign({minHeight:i.minHeight||50,maxHeight:i.maxHeight||2e3,debounceDelay:i.debounceDelay||150,threshold:i.threshold||5,animate:!1!==i.animate,animationDuration:i.animationDuration||300},i),o=e.offsetHeight,s=this.getStoredHeight(t);s&&s!==o&&this.setElementHeight(e,s,n.animate,n.animationDuration),this.setupContentMonitoring(e,t,n,o)}disableAutoScale(e){const t=this.observers.get(e);t&&(t.disconnect(),this.observers.delete(e));const i=this.mutationObservers.get(e);i&&(i.disconnect(),this.mutationObservers.delete(e));const n=this.timeouts.get(e);n&&(clearTimeout(n),this.timeouts.delete(e));const o=this.animationIds.get(e);o&&(cancelAnimationFrame(o),this.animationIds.delete(e));const s=document.querySelector(`iframe[data-widgetic-id="${e}"], iframe[data-composition-id="${e}"]`);s&&s._autoscaleMessageCleanup&&(s._autoscaleMessageCleanup(),delete s._autoscaleMessageCleanup)}getStoredHeight(e){try{const t=localStorage.getItem(this.storageKey);if(!t)return null;const i=JSON.parse(t),n=i[e];if(!n)return null;const o=864e5;return Date.now()-n.lastUpdated>o?(delete i[e],localStorage.setItem(this.storageKey,JSON.stringify(i)),null):n.height}catch(e){return null}}storeHeight(e,t,i){try{const n=localStorage.getItem(this.storageKey),o=n?JSON.parse(n):{};o[e]={compositionId:e,height:t,originalHeight:i,lastUpdated:Date.now()},localStorage.setItem(this.storageKey,JSON.stringify(o))}catch(e){}}setupContentMonitoring(e,t,i,n){const o=this.findContentElement(e);if(!o)return void e.tagName.toLowerCase();const s=this.createDebouncedHeightUpdate(e,t,i,n);if("undefined"!=typeof ResizeObserver){const e=new ResizeObserver((e=>{for(const t of e){const e=t.target.scrollHeight;s(e)}}));e.observe(o),this.observers.set(t,e)}const a=new MutationObserver((()=>{const e=o.scrollHeight;s(e)}));a.observe(o,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","class","height"]}),this.mutationObservers.set(t,a);const d=o.scrollHeight;s(d)}findContentElement(e){var t;if("iframe"===e.tagName.toLowerCase())try{const i=e,n=i.contentDocument||(null===(t=i.contentWindow)||void 0===t?void 0:t.document);if(null==n?void 0:n.body)return n.body}catch(t){return this.setupIframePostMessageListener(e),null}const i=e.tagName.toLowerCase();if("widgetic"===i||"widgetic-widget"===i||e.classList.contains("widgetic-widget")){return e.querySelector(".widget-content, .widgetic-content, [data-content]")||e}return e}setupIframePostMessageListener(e){const t=e.getAttribute("data-widgetic-id")||e.getAttribute("data-composition-id")||"unknown",i=i=>{var n,o;if(i.source===e.contentWindow&&("widgetic:autoscale"===(null===(n=i.data)||void 0===n?void 0:n.type)||"autoscale"===(null===(o=i.data)||void 0===o?void 0:o.type))){const{height:n,contentHeight:o}=i.data.payload||i.data;if("number"==typeof n&&n>0){const i=this.getConfigForWidget(t),s=Math.max(i.minHeight||50,Math.min(i.maxHeight||2e3,n));this.setElementHeight(e,s,i.animate,i.animationDuration),this.storeHeight(t,s,e.offsetHeight),e.dispatchEvent(new CustomEvent("widgetic:autoscale",{detail:{compositionId:t,oldHeight:e.offsetHeight,newHeight:s,contentHeight:o||n}}))}}};window.addEventListener("message",i),e._autoscaleMessageCleanup=()=>{window.removeEventListener("message",i)}}getConfigForWidget(e){return{enabled:!0,minHeight:50,maxHeight:2e3,animate:!0,animationDuration:300,debounceDelay:150,threshold:5}}createDebouncedHeightUpdate(e,t,i,n){let o=e.offsetHeight;return s=>{const a=this.timeouts.get(t);a&&clearTimeout(a);const d=setTimeout((()=>{const a=Math.max(i.minHeight,Math.min(i.maxHeight,s));Math.abs(a-o)>=i.threshold&&(this.setElementHeight(e,a,i.animate,i.animationDuration),this.storeHeight(t,a,n),o=a,e.dispatchEvent(new CustomEvent("widgetic:autoscale",{detail:{compositionId:t,oldHeight:o,newHeight:a,contentHeight:s}}))),this.timeouts.delete(t)}),i.debounceDelay);this.timeouts.set(t,d)}}setElementHeight(e,t,i=!0,n=300){if(!i)return void(e.style.height=`${t}px`);const o=e.offsetHeight,s=t-o;if(Math.abs(s)<1)return;const a=this.animationIds.get(e.id||e.tagName);a&&cancelAnimationFrame(a);const d=performance.now(),r=o,c=i=>{const o=i-d,a=Math.min(o/n,1),l=1-Math.pow(1-a,3),u=r+s*l;if(e.style.height=`${u}px`,a<1){const t=requestAnimationFrame(c);this.animationIds.set(e.id||e.tagName,t)}else e.style.height=`${t}px`,this.animationIds.delete(e.id||e.tagName)},l=requestAnimationFrame(c);this.animationIds.set(e.id||e.tagName,l)}clearStoredHeights(){try{localStorage.removeItem(this.storageKey)}catch(e){}}getStoredHeights(){try{const e=localStorage.getItem(this.storageKey);return e?JSON.parse(e):{}}catch(e){return{}}}destroy(){this.observers.forEach((e=>e.disconnect())),this.observers.clear(),this.mutationObservers.forEach((e=>e.disconnect())),this.mutationObservers.clear(),this.timeouts.forEach((e=>clearTimeout(e))),this.timeouts.clear(),this.animationIds.forEach((e=>cancelAnimationFrame(e))),this.animationIds.clear()}}class y{constructor(){this.autoScaleManager=v.getInstance(),w()}render(t){return e(this,void 0,void 0,(function*(){const{compositionId:e,width:i="100%",height:n="400",resize:o="responsive",autoscale:s=!0,adaptive:a=768,media:d,content:r}=t,c=document.createElement("widgetic-widget");if(c.setAttribute("composition-id",e),c.setAttribute("width",String(i)),c.setAttribute("height",String(n)),c.setAttribute("resize",o),"boolean"==typeof s?c.setAttribute("autoscale",s?"true":"false"):s&&"object"==typeof s?(c.setAttribute("autoscale","true"),void 0!==s.minHeight&&c.setAttribute("autoscale-min-height",String(s.minHeight)),void 0!==s.maxHeight&&c.setAttribute("autoscale-max-height",String(s.maxHeight)),void 0!==s.debounceDelay&&c.setAttribute("autoscale-debounce",String(s.debounceDelay)),void 0!==s.threshold&&c.setAttribute("autoscale-threshold",String(s.threshold)),void 0!==s.animate&&c.setAttribute("autoscale-animate",String(s.animate)),void 0!==s.animationDuration&&c.setAttribute("autoscale-animation-duration",String(s.animationDuration))):c.setAttribute("autoscale","false"),c.setAttribute("adaptive",String(a)),d&&Object.keys(d).length>0){g().registerWidget(e,d),this.setupCustomElementMediaListener(c,e)}if(r&&Object.keys(r).length>0){h().registerWidget(e,r),this.setupCustomElementContentListener(c,e)}return{id:`custom-${e}-${Date.now()}`,element:c,compositionData:{id:e,name:`Composition ${e}`,widgetId:`widget-${e}`,config:{}},widgetData:{id:`widget-${e}`,name:`Widget ${e}`,type:"custom-element",version:"1.0",moduleUrl:"",dependencies:[]},renderMode:"custom-element",cleanup:()=>{c._mediaCommandCleanup&&c._mediaCommandCleanup(),c._mediaObserverCleanup&&c._mediaObserverCleanup(),c._contentPositionCleanup&&c._contentPositionCleanup()}}}))}initializeWidget(t,i,n){return e(this,void 0,void 0,(function*(){}))}renderFrameworkComponent(t,i,n){return e(this,void 0,void 0,(function*(){if(i.$$typeof&&"undefined"!=typeof window&&window.React&&window.ReactDOM){const e=window.React,o=window.ReactDOM,s=e.createElement(i,{config:n.config,metadata:n.metadata});o.render(s,t)}else{if(!i._isVue&&!i.__isVue||"undefined"==typeof window||!window.Vue)throw new Error("Framework component detected but framework not available");new(0,window.Vue)({el:t,render:e=>e(i,{props:{config:n.config,metadata:n.metadata}})})}}))}applyElementStyling(e,t,i){const{width:n,height:o,resize:s,autoscale:a,adaptive:d}=i;switch(e.style.width="number"==typeof n?`${n}px`:n,e.style.height="number"==typeof o?`${o}px`:o,e.style.display="block",e.style.overflow="hidden",s){case"fill-width":e.style.width="100%";break;case"responsive":this.makeResponsive(e,d||768)}if(a){("boolean"==typeof a?a:a&&"object"==typeof a&&a.enabled)&&this.enableAutoscale(e,t,a)}e.classList.add("widgetic-widget","widgetic-custom-element")}makeResponsive(e,t){const i=window.matchMedia(`(max-width: ${t}px)`),n=()=>{i.matches?(e.style.width="100%",e.style.height="auto",e.style.minHeight="200px",e.classList.add("widgetic-mobile")):e.classList.remove("widgetic-mobile")};n(),i.addEventListener?i.addEventListener("change",n):i.addListener(n),e._responsiveCleanup=()=>{i.removeEventListener?i.removeEventListener("change",n):i.removeListener(n)}}enableAutoscale(e,t,i){const n="boolean"==typeof i?{enabled:i}:i;n.enabled&&(this.autoScaleManager.enableAutoScale(e,t,n),e._autoscaleCleanup=()=>{this.autoScaleManager.disableAutoScale(t)})}showLoadingState(e){e.innerHTML='\n <div class="widgetic-loading" style="\n display: flex;\n align-items: center;\n justify-content: center;\n height: 100%;\n background: #f8f9fa;\n border: 1px solid #e9ecef;\n border-radius: 4px;\n ">\n <div style="text-align: center; color: #6c757d;">\n <div style="\n width: 20px;\n height: 20px;\n border: 2px solid #dee2e6;\n border-top: 2px solid #007bff;\n border-radius: 50%;\n animation: spin 1s linear infinite;\n margin: 0 auto 8px;\n "></div>\n <small>Loading widget...</small>\n </div>\n </div>\n <style>\n @keyframes spin {\n 0% { transform: rotate(0deg); }\n 100% { transform: rotate(360deg); }\n }\n </style>\n '}showErrorState(e,t){const i=t instanceof Error?t.message:"Unknown error";e.innerHTML=`\n <div class="widgetic-error" style="\n display: flex;\n align-items: center;\n justify-content: center;\n height: 100%;\n background: #fff5f5;\n border: 1px solid #fed7d7;\n border-radius: 4px;\n color: #c53030;\n ">\n <div style="text-align: center; padding: 20px;">\n <div style="font-size: 24px; margin-bottom: 8px;">⚠️</div>\n <div style="font-weight: 500; margin-bottom: 4px;">Widget Error</div>\n <small style="color: #718096;">${i}</small>\n </div>\n </div>\n `,e.setAttribute("data-error","true"),e.dispatchEvent(new CustomEvent("widgetic:error",{detail:{error:i}}))}setupCustomElementMediaListener(e,t){const i=g(),n=t=>{const{command:i}=t.detail;if("pause"===i){const t=e.querySelectorAll("audio"),i=e.querySelectorAll("video");t.forEach((e=>{e.paused||e.pause()})),i.forEach((e=>{e.paused||e.pause()}))}else if("play"===i){const t=e.querySelectorAll("audio"),i=e.querySelectorAll("video"),n=Array.from(t).concat(Array.from(i)).find((e=>e.currentTime>0&&!e.ended));n&&n.play().catch((()=>{}))}};e.addEventListener("widgetic:media:command",n),e._mediaCommandCleanup=()=>{e.removeEventListener("widgetic:media:command",n)};const o=(n,o)=>s=>{const a=(e.__widgetConfig||{}).media||{},d="audio"===n.tagName.toLowerCase()?"audio":"video";i.handleMediaEvent({type:o,compositionId:t,config:a,data:{position:n.currentTime,duration:n.duration,volume:n.volume,mediaType:d,title:n.title||n.getAttribute("data-title")||void 0}})},s=()=>{const t=e.querySelectorAll("audio"),i=e.querySelectorAll("video");Array.from(t).concat(Array.from(i)).forEach((e=>{e.addEventListener("play",o(e,"play")),e.addEventListener("pause",o(e,"pause")),e.addEventListener("ended",o(e,"ended")),e.addEventListener("seeked",o(e,"seeking")),e.addEventListener("volumechange",o(e,"volumechange"))}))};s();const a=new MutationObserver((()=>{s()}));a.observe(e,{childList:!0,subtree:!0}),e._mediaObserverCleanup=()=>{a.disconnect()}}setupCustomElementContentListener(e,t){const i=h(),n=n=>{if(n.detail&&n.detail.type){const o=n.detail.type,s=n.detail.data||n.detail;let a={};try{const t=e.getAttribute("data-content-config");t&&(a=JSON.parse(t))}catch(e){a={contentType:"custom",persistState:!0}}i.handleContentPositionEvent({type:o,compositionId:t,config:a,data:s})}};e.addEventListener("widgetic:content:position",n),e.addEventListener("widgetic:content:navigate",n),e.addEventListener("widgetic:content:complete",n),e.addEventListener("widgetic:content:reset",n),e.addEventListener("widgetic:content:metadata",n),e._contentPositionCleanup=()=>{e.removeEventListener("widgetic:content:position",n),e.removeEventListener("widgetic:content:navigate",n),e.removeEventListener("widgetic:content:complete",n),e.removeEventListener("widgetic:content:reset",n),e.removeEventListener("widgetic:content:metadata",n)}}}var I=Object.freeze({__proto__:null,CustomElementRenderer:y});class E{constructor(){this.observers=new Map,this.callbacks=new Map,this.currentStates=new Map,this.debounceTimers=new Map,"undefined"==typeof ResizeObserver&&r.warn("ResizeObserver not available, responsive breakpoints will not work")}registerWidget(e,t,i,n){if("undefined"==typeof ResizeObserver)return void r.warn("ResizeObserver not available, skipping responsive registration",{widgetId:e});this.unregisterWidget(e);const o=t.getBoundingClientRect().width,s=i.initialMode||(o<i.breakpoint?"mobile":"desktop"),a={mode:s,breakpoint:i.breakpoint,width:o,timestamp:Date.now()};this.currentStates.set(e,a),this.callbacks.set(e,n);const d=new ResizeObserver((t=>{this.handleResize(e,t,i)}));d.observe(t),this.observers.set(e,d),n(a),r.debug("Widget registered for responsive monitoring",{widgetId:e,breakpoint:i.breakpoint,initialMode:s,containerWidth:o})}unregisterWidget(e){const t=this.debounceTimers.get(e);t&&(clearTimeout(t),this.debounceTimers.delete(e));const i=this.observers.get(e);i&&(i.disconnect(),this.observers.delete(e)),this.callbacks.delete(e),this.currentStates.delete(e),r.debug("Widget unregistered from responsive monitoring",{widgetId:e})}getCurrentState(e){return this.currentStates.get(e)||null}checkResponsiveState(e,t){const i=this.currentStates.get(e),n=this.callbacks.get(e);if(!i||!n)return void r.warn("Widget not registered for responsive monitoring",{widgetId:e});const o=t<i.breakpoint?"mobile":"desktop";if(o!==i.mode){const s={mode:o,breakpoint:i.breakpoint,width:t,timestamp:Date.now()};this.currentStates.set(e,s),n(s),r.info("Responsive state changed manually",{widgetId:e,from:i.mode,to:o,width:t,breakpoint:i.breakpoint})}}handleResize(e,t,i){const n=this.debounceTimers.get(e);n&&clearTimeout(n);const o=setTimeout((()=>{this.processResize(e,t,i),this.debounceTimers.delete(e)}),i.debounceDelay||150);this.debounceTimers.set(e,o)}processResize(e,t,i){const n=this.currentStates.get(e),o=this.callbacks.get(e);if(!n||!o)return;const s=t[t.length-1];if(!s)return;const a=s.contentRect.width,d=a<i.breakpoint?"mobile":"desktop";if(d!==n.mode){const t={mode:d,breakpoint:i.breakpoint,width:a,timestamp:Date.now()};this.currentStates.set(e,t),o(t),r.info("Responsive breakpoint crossed",{widgetId:e,from:n.mode,to:d,width:a,breakpoint:i.breakpoint})}else if(Math.abs(a-n.width)>10){const t=Object.assign(Object.assign({},n),{width:a,timestamp:Date.now()});this.currentStates.set(e,t),r.debug("Container width updated",{widgetId:e,width:a,mode:n.mode,breakpoint:i.breakpoint})}}getRegisteredWidgets(){return Array.from(this.observers.keys())}cleanup(){const e=this.getRegisteredWidgets();for(const t of e)this.unregisterWidget(t);r.debug("ResponsiveManager cleanup complete")}}let x=null;function k(){return x||(x=new E),x}class C{constructor(){this.messageQueue=new Map,this.iframeRegistry=new Map,this.loadingTimeouts=new Map,this.autoScaleManager=v.getInstance()}renderWidget(t){return e(this,void 0,void 0,(function*(){const{compositionId:e,width:i,height:n,resize:o="fixed",autoscale:s=!1,adaptive:a,responsive:c,container:l,allowFullscreen:u=!0,sandbox:m=this.getDefaultSandboxPermissions(),allowedFeatures:b=this.getDefaultAllowedFeatures(),loading:f="lazy",enableResize:w=!0,compositionData:v,widgetData:y,security:I={},fallback:E={enabled:!0,timeout:1e4,retryCount:3},media:x}=t;if(!i||!n||!l)throw new Error("Missing required parameters: width, height, and container are required");const k=v||{id:e,name:`Composition ${e}`,widgetId:`widget-${e}`,config:{}},C=y||{id:k.widgetId,name:`Widget ${e}`,type:"iframe",version:"1.0",moduleUrl:"",dependencies:[]};try{const v=this.createSecureIframe(e,t);v.src=yield this.buildSecureIframeUrl(e,t),v.title=`Widgetic Widget: ${k.name||e}`,v.loading=f,this.applySandboxSecurity(v,m,b),v.width=i.toString(),v.height=n.toString(),v.frameBorder="0",v.scrolling="no",u&&(v.allowFullscreen=!0,v.setAttribute("allowfullscreen","")),v.title=`Widgetic Widget ${e}`,v.setAttribute("aria-label",`${d("interactiveWidget")}: ${e}`);const y={compositionId:e,renderMode:"iframe",displayMode:"inline",resize:o,width:"number"==typeof i?i:parseInt(i.toString()),height:"number"==typeof n?n:parseInt(n.toString()),autoscale:s,adaptive:a,responsive:c,media:x},S=p.generateIframeCSS(y);S&&(v.style.cssText+=S),this.applyIframeStyling(v,e,{width:i,height:n,resize:o,autoscale:s,adaptive:a}),v.style.visibility="hidden",v.style.opacity="0",v.style.transition="opacity 0.3s ease",this.addLoadingIndicator(l,y),this.setupEnhancedIframeMessaging(v,e,I),this.setupLoadingOptimization(v,e,E);const W="lazy"===f,M=new Promise(((t,i)=>{let n=null;W||(n=setTimeout((()=>{i(new Error(`Iframe load timeout for composition: ${e}`))}),E.timeout||1e4)),v.onload=()=>{n&&clearTimeout(n),this.removeLoadingIndicator(l),v.style.visibility="visible",v.style.opacity="1",t()},v.onerror=()=>{n&&clearTimeout(n),this.removeLoadingIndicator(l),i(new Error(`Failed to load iframe for composition: ${e}`))}}));if(l.appendChild(v),w&&"undefined"!=typeof ResizeObserver){const t=new p({observeResize:!0}),i=`iframe-${e}-${Date.now()}`;v.setAttribute("data-widget-id",i),t.registerWidget(i,v,l,y),v.__resizeHandler=t,v.__widgetId=i}c&&"number"==typeof c&&c>0&&this.setupResponsiveMonitoring(v,l,e,c),this.iframeRegistry.set(e,v),v.classList.add("widgetic-widget","widgetic-iframe","widgetic-enhanced"),W||(yield M);const L=`iframe-${e}-${Date.now()}`;if(r.info("Enhanced iframe widget rendered successfully",{compositionId:e,size:{width:i,height:n},resize:o,autoscale:s,responsive:c,sandbox:m.join(" "),features:b.join("; ")}),y.media&&Object.keys(y.media).length>0){g().registerWidget(e,y.media),this.setupIframeMediaListener(v,e)}if(t.content&&Object.keys(t.content).length>0){h().registerWidget(e,t.content),this.setupIframeContentListener(v,e)}return{id:L,element:v,compositionData:k,widgetData:C,renderMode:"iframe",cleanup:()=>this.cleanupWidget(v)}}catch(t){throw r.error("Enhanced iframe widget rendering failed",{compositionId:e,error:t}),this.removeLoadingIndicator(l),t}}))}renderWidgets(t){return e(this,void 0,void 0,(function*(){r.debug("Rendering multiple iframe widgets",{count:t.length});const e=t.map((e=>this.renderWidget(e))),i=yield Promise.allSettled(e),n=[];for(let e=0;e<i.length;e++){const o=i[e],s=t[e];if("fulfilled"===o.status)n.push(o.value);else{r.error("Iframe widget rendering failed in batch",{compositionId:s.compositionId,error:o.reason});const e=`error-${s.compositionId}-${Date.now()}`;n.push({id:e,element:this.createErrorElement(s,o.reason),compositionData:{id:s.compositionId,name:`Composition ${s.compositionId}`,widgetId:`widget-${s.compositionId}`,config:{}},widgetData:{id:`widget-${s.compositionId}`,name:`Widget ${s.compositionId}`,type:"iframe",version:"1.0",moduleUrl:"",dependencies:[]},renderMode:"iframe",cleanup:()=>{}})}}return r.info("Iframe batch rendering complete",{total:t.length,successful:n.filter((e=>"IFRAME"===e.element.tagName)).length,failed:n.filter((e=>"IFRAME"!==e.element.tagName)).length}),n}))}createSecureIframe(e,t){var i;const n=document.createElement("iframe");return n.style.border="none",n.style.display="block",n.style.overflow="hidden",n.setAttribute("referrerpolicy","strict-origin-when-cross-origin"),n.setAttribute("crossorigin","anonymous"),(null===(i=t.security)||void 0===i?void 0:i.enableCSP)&&n.setAttribute("csp",this.generateCSP(t.security.allowedOrigins)),n.setAttribute("data-widgetic-id",e),n.setAttribute("data-enhanced","true"),n}getDefaultSandboxPermissions(){return["allow-scripts","allow-same-origin","allow-forms","allow-popups","allow-presentation","allow-downloads"]}getDefaultAllowedFeatures(){return["autoplay","encrypted-media","picture-in-picture","fullscreen","clipboard-read","clipboard-write"]}applySandboxSecurity(e,t,i){e.setAttribute("sandbox",t.join(" ")),e.setAttribute("allow",i.join("; ")),e.setAttribute("fetchpriority","high")}generateCSP(e){const t=e||[c.CLIENT_URL];return[`default-src 'self' ${t.join(" ")}`,`script-src 'self' 'unsafe-inline' ${t.join(" ")}`,`style-src 'self' 'unsafe-inline' ${t.join(" ")}`,`img-src 'self' data: blob: ${t.join(" ")}`,`media-src 'self' blob: ${t.join(" ")}`,"object-src 'none'","base-uri 'self'","form-action 'self'"].join("; ")}buildSecureIframeUrl(t,i){return e(this,void 0,void 0,(function*(){var e;const n=`${c.CLIENT_URL}/embed/${t}`,o=new URLSearchParams;i.width&&o.set("width","number"==typeof i.width?i.width.toString():i.width),i.height&&o.set("height","number"==typeof i.height?i.height.toString():i.height),i.resize&&o.set("resize",i.resize),i.autoscale&&o.set("autoscale","true"),i.adaptive&&o.set("adaptive",i.adaptive.toString()),i.responsive&&"number"==typeof i.responsive&&o.set("responsive",i.responsive.toString()),(null===(e=i.security)||void 0===e?void 0:e.signatureValidation)&&o.set("validateSignature","true"),o.set("sdkVersion","1.0"),o.set("mode","iframe");try{const e=yield u();o.set("apiKey",e)}catch(e){r.warn("Failed to get auth token for iframe",e),c.API_KEY&&o.set("apiKey",c.API_KEY)}const s=`${n}?${o.toString()}`;return r.debug("Built secure iframe URL",{compositionId:t,url:s}),s}))}applyIframeStyling(e,t,i){const{width:n,height:o,resize:s,autoscale:a,adaptive:d}=i;if(e.style.width="number"==typeof n?`${n}px`:n,e.style.height="number"==typeof o?`${o}px`:o,"fill-width"===s)e.style.width="100%",e.style.height="auto",e.style.minHeight="number"==typeof o?`${o}px`:o;a&&this.enableIframeAutoscale(e,t,a),d&&this.makeIframeResponsive(e,d)}makeIframeResponsive(e,t){const i=window.matchMedia(`(max-width: ${t}px)`),n=()=>{i.matches?(e.style.width="100%",e.style.height="auto",e.style.minHeight="200px",e.classList.add("widgetic-mobile")):e.classList.remove("widgetic-mobile")};n(),i.addEventListener?i.addEventListener("change",n):i.addListener(n),e._responsiveCleanup=()=>{i.removeEventListener?i.removeEventListener("change",n):i.removeListener(n)}}enableIframeAutoscale(e,t,i){const n="boolean"==typeof i?{enabled:i}:i;n.enabled&&(this.autoScaleManager.enableAutoScale(e,t,n),e._autoscaleCleanup=()=>{this.autoScaleManager.disableAutoScale(t)},r.debug("AutoScale enabled for iframe",{compositionId:t,config:n}))}setupLoadingOptimization(e,t,i){if(!i.enabled)return;const n=i.timeout||1e4,o=i.retryCount||3;let s=0;const a=()=>{s<o?(s++,r.warn(`Iframe loading failed, retrying (${s}/${o})`,{compositionId:t}),setTimeout((()=>{e.src=e.src+"&retry="+s}),1e3*s)):(r.error("Iframe loading failed after retries",{compositionId:t,retryCount:o}),this.handleIframeFallback(e,t))},d=setTimeout((()=>{r.warn("Iframe loading timeout",{compositionId:t,timeout:n}),a()}),n);this.loadingTimeouts.set(t,d),e.addEventListener("load",(()=>{const e=this.loadingTimeouts.get(t);e&&(clearTimeout(e),this.loadingTimeouts.delete(t)),r.debug("Iframe loaded successfully",{compositionId:t})})),e.addEventListener("error",(()=>{r.error("Iframe error occurred",{compositionId:t}),a()}))}handleIframeFallback(e,t){const i=document.createElement("div");i.className="widgetic-iframe-fallback",i.innerHTML='\n <div style="\n display: flex;\n align-items: center;\n justify-content: center;\n height: 100%;\n background: #f8f9fa;\n border: 1px solid #e9ecef;\n border-radius: 4px;\n color: #6c757d;\n text-align: center;\n padding: 20px;\n ">\n <div>\n <div style="font-size: 24px; margin-bottom: 8px;">⚠️</div>\n <div style="font-weight: 500; margin-bottom: 4px;">Widget Unavailable</div>\n <small>The widget could not be loaded. Please try refreshing the page.</small>\n </div>\n </div>\n ',e.parentNode&&(e.parentNode.insertBefore(i,e),e.parentNode.removeChild(e)),i.dispatchEvent(new CustomEvent("widgetic:fallback",{detail:{compositionId:t,reason:"loading_failed"},bubbles:!0}))}setupEnhancedIframeMessaging(e,t,i={}){const n=m({enableSignatureValidation:i.signatureValidation||!1,allowedOrigins:i.allowedOrigins,enableHeartbeat:!0,heartbeatInterval:3e4});n.registerHandler(t,(t=>{this.handleEnhancedIframeMessage(e,t)})),e.addEventListener("load",(()=>{n.sendMessage(t,{type:"config",instanceId:t,payload:{compositionId:t,apiUrl:l(),timestamp:Date.now(),sdkVersion:"2.0",mode:"iframe"},timestamp:Date.now(),version:"1.0"}),r.debug("Initial config sent to iframe",{compositionId:t})})),e.__messenger=n,e.__messagingCompositionId=t,r.debug("Enhanced iframe messaging setup complete",{compositionId:t})}handleEnhancedIframeMessage(e,t){switch(r.debug("Enhanced iframe message received",{type:t.type,instanceId:t.instanceId,sequence:t.sequence}),t.type){case"resize":this.handleResizeMessage(e,t);break;case"ready":this.handleReadyMessage(e,t);break;case"error":this.handleErrorMessage(e,t);break;case"data":this.handleDataMessage(e,t);break;case"event":this.handleEventMessage(e,t);break;default:r.debug("Unknown enhanced message type",{type:t.type,instanceId:t.instanceId})}}handleResizeMessage(e,t){const{width:i,height:n}=t.payload;i&&n&&(e.style.width=`${i}px`,e.style.height=`${n}px`,e.dispatchEvent(new CustomEvent("widgetic:resize",{detail:{width:i,height:n,instanceId:t.instanceId},bubbles:!0})),r.debug("Iframe resized",{width:i,height:n,instanceId:t.instanceId}))}handleReadyMessage(e,t){e.setAttribute("data-ready","true"),e.dispatchEvent(new CustomEvent("widgetic:ready",{detail:{instanceId:t.instanceId,compositionId:t.compositionId,payload:t.payload},bubbles:!0})),r.info("Iframe widget ready",{instanceId:t.instanceId})}handleErrorMessage(e,t){e.setAttribute("data-error","true"),e.dispatchEvent(new CustomEvent("widgetic:error",{detail:{instanceId:t.instanceId,compositionId:t.compositionId,error:t.payload.error,code:t.payload.code},bubbles:!0})),r.error("Iframe widget error",{instanceId:t.instanceId,error:t.payload.error})}handleDataMessage(e,t){e.dispatchEvent(new CustomEvent("widgetic:data",{detail:{instanceId:t.instanceId,compositionId:t.compositionId,data:t.payload},bubbles:!0})),r.debug("Iframe data received",{instanceId:t.instanceId,dataType:t.payload.type})}handleEventMessage(e,t){e.dispatchEvent(new CustomEvent("widgetic:interaction",{detail:{instanceId:t.instanceId,compositionId:t.compositionId,eventType:t.payload.type,eventData:t.payload.data},bubbles:!0})),r.debug("Iframe interaction event",{instanceId:t.instanceId,eventType:t.payload.type})}sendMessageToIframe(e,t,i){m().sendMessage(e,{type:t,instanceId:e,payload:i,timestamp:Date.now(),version:"1.0"})}addLoadingIndicator(e,t){const i=document.createElement("div");i.className="widgetic-loading-indicator",i.style.cssText=`\n display: flex;\n align-items: center;\n justify-content: center;\n width: ${t.width}px;\n height: ${t.height}px;\n background: #f5f5f5;\n color: #666;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n font-size: 14px;\n border: 1px solid #e0e0e0;\n border-radius: 4px;\n position: relative;\n `,i.innerHTML='\n <div style="text-align: center;">\n <div style="\n width: 20px;\n height: 20px;\n border: 2px solid #e0e0e0;\n border-top: 2px solid #666;\n border-radius: 50%;\n animation: widgetic-spin 1s linear infinite;\n margin: 0 auto 8px;\n "></div>\n <div>Loading widget...</div>\n </div>\n ';const n=document.createElement("style");n.textContent="\n @keyframes widgetic-spin {\n 0% { transform: rotate(0deg); }\n 100% { transform: rotate(360deg); }\n }\n ",document.head.appendChild(n),e.appendChild(i)}removeLoadingIndicator(e){const t=e.querySelector(".widgetic-loading-indicator");t&&t.parentNode&&t.parentNode.removeChild(t)}createErrorElement(e,t){const i=document.createElement("div");return i.className="widgetic-error",i.style.cssText=`\n display: flex;\n align-items: center;\n justify-content: center;\n width: ${e.width}px;\n height: ${e.height}px;\n background: #fff5f5;\n color: #e53e3e;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n font-size: 14px;\n border: 1px solid #fed7d7;\n border-radius: 4px;\n text-align: center;\n padding: 16px;\n box-sizing: border-box;\n `,i.innerHTML=`\n <div>\n <div style="font-weight: 600; margin-bottom: 4px;">Widget Error</div>\n <div style="font-size: 12px; opacity: 0.8;">Failed to load composition: ${e.compositionId}</div>\n </div>\n `,i}cleanupWidget(e){const t=e.__resizeHandler,i=e.__widgetId;t&&i&&t.unregisterWidget(i);const n=e.__responsiveManager,o=e.__responsiveId;n&&o&&n.unregisterWidget(o);const s=e.__messenger,a=e.__messagingCompositionId;s&&a&&s.unregisterHandler(a);const d=this.loadingTimeouts.get(a);d&&(clearTimeout(d),this.loadingTimeouts.delete(a)),a&&this.iframeRegistry.delete(a),e._responsiveCleanup&&e._responsiveCleanup(),e._autoscaleCleanup&&e._autoscaleCleanup(),e.parentNode&&e.parentNode.removeChild(e),r.debug("Iframe cleanup complete",{compositionId:a})}cleanupIframe(e){const t=this.iframeRegistry.get(e);t&&this.cleanupWidget(t)}setupResponsiveMonitoring(e,t,i,n){const o=k(),s=m(),a={breakpoint:n,debounceDelay:150},d=`responsive-${i}`;o.registerWidget(d,t,a,(t=>{r.debug("Responsive state changed, notifying iframe",{compositionId:i,mode:t.mode,breakpoint:t.breakpoint,width:t.width}),s.sendMessage(i,{type:"responsive",instanceId:i,compositionId:i,payload:{mode:t.mode,breakpoint:t.breakpoint,width:t.width,timestamp:t.timestamp},timestamp:Date.now(),version:"1.0"}),e.dispatchEvent(new CustomEvent("widgetic:responsive",{detail:{instanceId:i,compositionId:i,mode:t.mode,breakpoint:t.breakpoint,width:t.width},bubbles:!0}))})),e.__responsiveId=d,e.__responsiveManager=o,r.info("Responsive monitoring enabled for iframe",{compositionId:i,breakpoint:n,containerId:d})}setupIframeMediaListener(e,t){const i=g(),n=n=>{var o,s;if(n.source===e.contentWindow&&(null===(s=null===(o=n.data)||void 0===o?void 0:o.type)||void 0===s?void 0:s.startsWith("widgetic:media:"))){const o=n.data.type.replace("widgetic:media:","");if(["play","pause","stop","ended","seeking","volumechange"].includes(o)){const s=e.getAttribute("data-widget-config"),a=s?JSON.parse(s):{};i.handleMediaEvent({type:o,compositionId:t,config:a.media||{},data:n.data.payload||n.data.data||{}})}}};window.addEventListener("message",n),e._mediaListenerCleanup=()=>{window.removeEventListener("message",n)}}setupIframeContentListener(e,t){const i=h(),n=n=>{var o,s;if(n.source===e.contentWindow&&(null===(s=null===(o=n.data)||void 0===o?void 0:o.type)||void 0===s?void 0:s.startsWith("widgetic:content:"))){const o=n.data.type.replace("widgetic:content:","");if(["position","navigate","complete","reset","metadata"].includes(o)){const s=e.getAttribute("data-widgetic-config");let a={};if(s)try{a=JSON.parse(s).content||{}}catch(e){a={contentType:"custom",persistState:!0}}i.handleContentPositionEvent({type:o,compositionId:t,config:a,data:n.data.payload||n.data.data||{}})}}};window.addEventListener("message",n),e._contentListenerCleanup=()=>{window.removeEventListener("message",n)}}}let S=null;var W=Object.freeze({__proto__:null,IframeRenderer:C,getIframeRenderer:function(){return S||(S=new C),S}});class M{constructor(){this.batchClient=s(),this.moduleLoader=a(),this.customElementRenderer=new y,this.iframeRenderer=new C,this.renderedWidgets=new Map}renderWidget(t){return e(this,void 0,void 0,(function*(){const e=this.generateWidgetId(t.compositionId),i=this.createLoadingElement(t.container);t.container&&i&&t.container.appendChild(i);try{const n=yield this.batchClient.getComposition(t.compositionId),o=yield this.batchClient.getWidget(n.widgetId),s=this.determineRenderMode(t.renderMode,o);let a;if("custom-element"===s)try{a=yield this.moduleLoader.loadModule(o)}catch(s){const a=yield this.renderWithIframe(e,t,n,o);return this.removeLoadingElement(i),a}const d="iframe"===s?yield this.renderWithIframe(e,t,n,o):yield this.renderWithCustomElement(e,t,n,o,a);return this.removeLoadingElement(i),this.renderedWidgets.set(e,d),this.emitWidgetEvent("ready",{widgetId:e,compositionId:t.compositionId,renderMode:d.renderMode,loadTime:(null==a?void 0:a.loadTime)||0,cached:(null==a?void 0:a.cached)||!1}),d}catch(n){if(this.removeLoadingElement(i),this.emitWidgetEvent("error",{widgetId:e,compositionId:t.compositionId,error:n instanceof Error?n.message:String(n),fallback:"iframe"}),t.container){const e=this.createErrorElement(t.compositionId,n);t.container.appendChild(e)}try{const i=yield this.renderFallback(e,t);if(t.container){const e=t.container.querySelector(".widgetic-error");e&&e.remove()}return i}catch(e){throw new Error(`Widget rendering failed: ${n}. Fallback also failed: ${e}`)}}}))}renderWidgets(t){return e(this,void 0,void 0,(function*(){const i=t.map((e=>e.compositionId)),n=yield this.batchClient.getCompositions(i),o=new Map(n.map((e=>[e.id,e]))),s=new Set;for(const e of t)if("iframe"!==e.renderMode){const t=o.get(e.compositionId);t&&t.widgetId&&s.add(t.widgetId)}const a=s.size>0?yield this.batchClient.getWidgets(Array.from(s)):[],d=new Map(a.map((e=>[e.id,e]))),r=a.filter((e=>"custom-element"===this.determineRenderMode("auto",e)));r.length>0&&(yield this.moduleLoader.preloadModules(r));const c=t.map((t=>e(this,void 0,void 0,(function*(){const e=o.get(t.compositionId)||{id:t.compositionId,widgetId:"default",name:"Composition",settings:{},config:{},version:"1.0.0"},i=d.get(e.widgetId)||{id:e.widgetId||"default",name:"Widget",type:"iframe",version:"1.0.0",moduleUrl:"",dependencies:[]};return this.renderSingleWidgetWithData(t,e,i)}))));return(yield Promise.allSettled(c)).filter((e=>"rejected"!==e.status)).map((e=>e.value))}))}getWidget(e){return this.renderedWidgets.get(e)||null}getAllWidgets(){return Array.from(this.renderedWidgets.values())}refreshWidget(t){return e(this,void 0,void 0,(function*(){const e=this.renderedWidgets.get(t);if(!e)return null;e.cleanup(),this.renderedWidgets.delete(t);const i={compositionId:e.compositionData.id,renderMode:e.renderMode,container:e.element.parentElement||void 0};return this.batchClient.clearCache(),this.moduleLoader.invalidateModule(e.widgetData.id),this.renderWidget(i)}))}cleanupWidget(e){const t=this.renderedWidgets.get(e);t&&(t.cleanup(),this.renderedWidgets.delete(e))}cleanupAll(){const e=Array.from(this.renderedWidgets.values());for(const t of e)t.cleanup();this.renderedWidgets.clear()}getStats(){return{renderedWidgets:this.renderedWidgets.size,batchCache:this.batchClient.getCacheStats(),moduleCache:this.moduleLoader.getCacheStats(),widgets:Array.from(this.renderedWidgets.entries()).map((([e,t])=>({id:e,compositionId:t.compositionData.id,widgetType:t.widgetData.type,renderMode:t.renderMode,hasModule:!!t.loadedModule})))}}renderSingleWidgetWithData(t,i,n){return e(this,void 0,void 0,(function*(){const e=this.generateWidgetId(t.compositionId);if("custom-element"===this.determineRenderMode(t.renderMode,n))try{const o=yield this.moduleLoader.loadModule(n);return this.renderWithCustomElement(e,t,i,n,o)}catch(e){}return this.renderWithIframe(e,t,i,n)}))}renderWithCustomElement(t,i,n,o,s){return e(this,void 0,void 0,(function*(){const e=yield this.customElementRenderer.render({compositionId:i.compositionId,compositionData:n,widgetData:o,loadedModule:s,width:i.width,height:i.height,resize:i.resize,autoscale:i.autoscale,adaptive:i.adaptive});return i.container&&i.container.appendChild(e.element),{id:t,element:e.element,compositionData:n,widgetData:o,loadedModule:s,renderMode:"custom-element",cleanup:()=>{e.element.remove()}}}))}renderWithIframe(t,i,n,o){return e(this,void 0,void 0,(function*(){return yield this.iframeRenderer.renderWidget({compositionId:i.compositionId,compositionData:n,widgetData:o,width:i.width,height:i.height,resize:i.resize,autoscale:i.autoscale,adaptive:i.adaptive,container:i.container})}))}renderFallback(t,i){return e(this,void 0,void 0,(function*(){const e=document.createElement("div");return e.className="widgetic-fallback",e.innerHTML=`\n <div style="\n padding: 20px; \n text-align: center; \n background: #f5f5f5; \n border: 1px solid #ddd; \n border-radius: 4px;\n color: #666;\n ">\n <p>Widget temporarily unavailable</p>\n <small>Composition ID: ${i.compositionId}</small>\n </div>\n `,i.container&&i.container.appendChild(e),{id:t,element:e,compositionData:{id:i.compositionId,name:"Fallback",widgetId:"fallback",config:{}},widgetData:{id:"fallback",name:"Fallback Widget",type:"fallback",version:"1.0.0",moduleUrl:""},renderMode:"iframe",cleanup:()=>{e.remove()}}}))}determineRenderMode(e="auto",t){var i;if("auto"!==e)return e;const n="undefined"!=typeof customElements&&"function"==typeof customElements.define,o=(null==t?void 0:t.moduleUrl)||(null===(i=null==t?void 0:t.metadata)||void 0===i?void 0:i.supportsCustomElements);return n&&o?"custom-element":"iframe"}generateWidgetId(e){return`widget-${e}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}emitWidgetEvent(e,t){const i=new CustomEvent(`widgetic:${e}`,{detail:t,bubbles:!0});document.dispatchEvent(i)}createLoadingElement(e){if(!e)return null;const t=document.createElement("div");return t.className="widgetic-loading",t.style.cssText="\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100px;\n background: #f8f9fa;\n border: 1px solid #e9ecef;\n border-radius: 4px;\n color: #6c757d;\n ",t.innerHTML='\n <div style="text-align: center;">\n <div style="\n width: 20px;\n height: 20px;\n border: 2px solid #f3f3f3;\n border-top: 2px solid #007bff;\n border-radius: 50%;\n animation: widgetic-spin 1s linear infinite;\n margin: 0 auto 8px;\n "></div>\n <div style="font-size: 14px;">Loading widget...</div>\n </div>\n ',this.addLoadingStyles(),t}removeLoadingElement(e){e&&e.parentNode&&e.parentNode.removeChild(e)}createErrorElement(e,t){const i=document.createElement("div");i.className="widgetic-error",i.style.cssText="\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100px;\n padding: 20px;\n text-align: center;\n background: #fff5f5;\n border: 1px solid #fed7d7;\n border-radius: 4px;\n color: #742a2a;\n ";const n=t instanceof Error?t.message:"Unknown error occurred",o=this.analyzeError(n,t);return i.innerHTML=`\n <div>\n <div style="font-size: 24px; margin-bottom: 8px;">${o.icon}</div>\n <div style="font-weight: 500; margin-bottom: 8px;">${o.title}</div>\n <div style="font-size: 14px; margin-bottom: 12px; color: #666;">\n ${o.description}\n </div>\n <div style="font-size: 12px; margin-bottom: 16px; color: #888;">\n Widget ID: ${e}\n </div>\n ${o.actionHtml}\n </div>\n `,i}analyzeError(e,t){const i=e.toLowerCase();return i.includes("composition not found")||i.includes("404")?{icon:"🔍",title:"Widget Not Found",description:"This widget may have been removed or the ID is incorrect.",actionHtml:`\n <button \n onclick="window.open('mailto:support@widgetic.com?subject=Widget%20Not%20Found%20-%20${encodeURIComponent(t.compositionId||"Unknown")}&body=Widget%20ID:%20${encodeURIComponent(t.compositionId||"Unknown")}%0AThe%20widget%20could%20not%20be%20found.%20Please%20check%20if%20it%20was%20deleted%20or%20if%20the%20ID%20is%20correct.', '_blank')"\n style="\n background: #007bff;\n color: white;\n border: none;\n padding: 8px 16px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 14px;\n text-decoration: none;\n display: inline-block;\n "\n onmouseover="this.style.background='#0056b3'"\n onmouseout="this.style.background='#007bff'"\n >\n 📧 Contact Support\n </button>\n `}:i.includes("unauthorized")||i.includes("forbidden")||i.includes("401")||i.includes("403")||i.includes("permission")||i.includes("access denied")?{icon:"🔒",title:"Access Restricted",description:"This widget requires an active subscription or has been restricted.",actionHtml:`\n <div style="margin-bottom: 12px;">\n <a \n href="https://widgetic.com/pricing" \n target="_blank"\n style="\n background: #28a745;\n color: white;\n border: none;\n padding: 8px 16px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 14px;\n text-decoration: none;\n display: inline-block;\n "\n onmouseover="this.style.background='#218838'"\n onmouseout="this.style.background='#28a745'"\n >\n ⭐ Upgrade Plan\n </a>\n </div>\n <button \n onclick="window.open('mailto:support@widgetic.com?subject=Widget%20Access%20Issue%20-%20${encodeURIComponent(t.compositionId||"Unknown")}&body=Widget%20ID:%20${encodeURIComponent(t.compositionId||"Unknown")}%0AI%20am%20having%20trouble%20accessing%20this%20widget.%20Please%20check%20my%20account%20status%20and%20permissions.', '_blank')"\n style="\n background: transparent;\n color: #007bff;\n border: 1px solid #007bff;\n padding: 6px 12px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 12px;\n "\n onmouseover="this.style.background='#007bff'; this.style.color='white'"\n onmouseout="this.style.background='transparent'; this.style.color='#007bff'"\n >\n 📧 Contact Support\n </button>\n `}:i.includes("deleted")||i.includes("expired")||i.includes("no longer available")?{icon:"🗑️",title:"Widget Deleted",description:"This widget has been permanently removed.",actionHtml:`\n <button \n onclick="window.open('mailto:support@widgetic.com?subject=Deleted%20Widget%20-%20${encodeURIComponent(t.compositionId||"Unknown")}&body=Widget%20ID:%20${encodeURIComponent(t.compositionId||"Unknown")}%0AThis%20widget%20appears%20to%20have%20been%20deleted.%20Can%20you%20help%20me%20restore%20it%20or%20find%20an%20alternative?', '_blank')"\n style="\n background: #007bff;\n color: white;\n border: none;\n padding: 8px 16px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 14px;\n text-decoration: none;\n display: inline-block;\n "\n onmouseover="this.style.background='#0056b3'"\n onmouseout="this.style.background='#007bff'"\n >\n 📧 Contact Support\n </button>\n `}:i.includes("subscription")||i.includes("billing")||i.includes("payment")||i.includes("plan")||i.includes("downgrade")?{icon:"💳",title:"Subscription Required",description:"This widget requires an active subscription to display.",actionHtml:`\n <div style="margin-bottom: 12px;">\n <a \n href="https://widgetic.com/pricing" \n target="_blank"\n style="\n background: #28a745;\n color: white;\n border: none;\n padding: 8px 16px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 14px;\n text-decoration: none;\n display: inline-block;\n margin-right: 8px;\n "\n onmouseover="this.style.background='#218838'"\n onmouseout="this.style.background='#28a745'"\n >\n ⭐ View Plans\n </a>\n <a \n href="https://widgetic.com/dashboard/billing" \n target="_blank"\n style="\n background: #6c757d;\n color: white;\n border: none;\n padding: 8px 16px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 14px;\n text-decoration: none;\n display: inline-block;\n "\n onmouseover="this.style.background='#5a6268'"\n onmouseout="this.style.background='#6c757d'"\n >\n 💳 Billing\n </a>\n </div>\n <div style="font-size: 12px; color: #888; margin-top: 8px;">\n Need help? Contact support below\n </div>\n <button \n onclick="window.open('mailto:support@widgetic.com?subject=Subscription%20Issue%20-%20${encodeURIComponent(t.compositionId||"Unknown")}&body=Widget%20ID:%20${encodeURIComponent(t.compositionId||"Unknown")}%0AI%20need%20help%20with%20my%20subscription%20to%20access%20this%20widget.', '_blank')"\n style="\n background: transparent;\n color: #007bff;\n border: 1px solid #007bff;\n padding: 4px 8px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 11px;\n margin-top: 4px;\n "\n onmouseover="this.style.background='#007bff'; this.style.color='white'"\n onmouseout="this.style.background='transparent'; this.style.color='#007bff'"\n >\n 📧 Contact Support\n </button>\n `}:i.includes("timeout")||i.includes("network")||i.includes("connection")||i.includes("fetch")?{icon:"🌐",title:"Connection Issue",description:"Unable to load widget due to network connectivity.",actionHtml:`\n <button \n onclick="window.location.reload()"\n style="\n background: #28a745;\n color: white;\n border: none;\n padding: 8px 16px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 14px;\n margin-right: 8px;\n "\n onmouseover="this.style.background='#218838'"\n onmouseout="this.style.background='#28a745'"\n >\n 🔄 Retry\n </button>\n <button \n onclick="window.open('mailto:support@widgetic.com?subject=Widget%20Connection%20Issue%20-%20${encodeURIComponent(t.compositionId||"Unknown")}&body=Widget%20ID:%20${encodeURIComponent(t.compositionId||"Unknown")}%0AError:%20${encodeURIComponent(e)}%0A%0AI%20am%20experiencing%20connection%20issues%20loading%20this%20widget.', '_blank')"\n style="\n background: transparent;\n color: #007bff;\n border: 1px solid #007bff;\n padding: 6px 12px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 12px;\n "\n onmouseover="this.style.background='#007bff'; this.style.color='white'"\n onmouseout="this.style.background='transparent'; this.style.color='#007bff'"\n >\n 📧 Contact Support\n </button>\n `}:{icon:"⚠️",title:"Widget Unavailable",description:e||"An unknown error occurred while loading this widget.",actionHtml:`\n <button \n onclick="window.open('mailto:support@widgetic.com?subject=Widget%20Error%20-%20${encodeURIComponent(t.compositionId||"Unknown")}&body=Widget%20ID:%20${encodeURIComponent(t.compositionId||"Unknown")}%0AError:%20${encodeURIComponent(e)}', '_blank')"\n style="\n background: #007bff;\n color: white;\n border: none;\n padding: 8px 16px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 14px;\n text-decoration: none;\n display: inline-block;\n "\n onmouseover="this.style.background='#0056b3'"\n onmouseout="this.style.background='#007bff'"\n >\n 📧 Contact Support\n </button>\n <div style="margin-top: 8px;">\n <button \n onclick="window.location.reload()"\n style="\n background: transparent;\n color: #007bff;\n border: 1px solid #007bff;\n padding: 6px 12px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 12px;\n margin-left: 8px;\n "\n onmouseover="this.style.background='#007bff'; this.style.color='white'"\n onmouseout="this.style.background='transparent'; this.style.color='#007bff'"\n >\n 🔄 Refresh Page\n </button>\n </div>\n `}}addLoadingStyles(){const e="widgetic-loading-styles";if(document.getElementById(e))return;const t=document.createElement("style");t.id=e,t.textContent="\n @keyframes widgetic-spin {\n 0% { transform: rotate(0deg); }\n 100% { transform: rotate(360deg); }\n }\n ",document.head.appendChild(t)}}let L=null;function $(){return L||(L=new M),L}function A(){L&&L.cleanupAll(),L=null}var z=Object.freeze({__proto__:null,WidgetRenderer:M,getWidgetRenderer:$,resetWidgetRenderer:A});export{y as C,C as I,f as W,M as a,A as b,I as c,$ as g,W as i,w as r,z as w};
1
+ import{_ as e}from"./vendor.js";import{r as t,a as i,b as n,E as o,d as s,g as a,e as d,c as r}from"./api.js";import{l as c,a as l,b as u,d as g}from"./core.js";import{b as h,c as m,m as p}from"./scanner.js";import{a as b,g as f}from"./media.js";import{getMessenger as w}from"./messaging.js";import{R as v}from"./display.js";const y="undefined"!=typeof HTMLElement?HTMLElement:class{};class I extends y{static get observedAttributes(){return["composition-id","width","height","resize","autoscale","adaptive","theme"]}constructor(){super(),this.svelteComponent=null,this.compositionData=null,this.widgetData=null,this.loadedModule=null,this.isInitialized=!1,this.isWidgetConnected=!1,this.resizeObserver=null,this.eventListeners=new Map,this.widgetState={ready:!1,error:null,loading:!1,data:{}},this.instanceId=this.generateInstanceId(),this.cssNamespace=`widgetic-${this.instanceId}`,this.initializeCSSIsolation(),c.debug("WidgeticWidget created",{instanceId:this.instanceId})}connectedCallback(){return e(this,void 0,void 0,(function*(){var e;if(!this.isWidgetConnected){this.isWidgetConnected=!0,c.debug("WidgeticWidget connected",{instanceId:this.instanceId});try{this.setLoadingState(!0);const a=h(this),d=null!==(e=null==a?void 0:a.id)&&void 0!==e?e:this.getAttribute("composition-id");if(!d)throw new Error("composition-id attribute is required");m(this);const r="widget"===(null==a?void 0:a.kind)?yield t(d):yield i(d);if("refused"===r.status)throw n(d,r.refusal),new Error(o);const c="found"===r.status?r.payload:null;if(null==c?void 0:c.embedUrl){const e=p(this,c);return this.innerHTML="",this.appendChild(s(c.embedUrl,this.getAttribute("width")||"400",this.getAttribute("height")||"300",d,e)),void this.setWidgetReady()}yield this.loadWidgetData(d),this.widgetData&&(yield this.loadWidgetModule()),yield this.initializeWidget(),this.setupResponsiveBehavior(),this.setupEventHandling(),this.setWidgetReady()}catch(e){c.error("WidgeticWidget initialization failed",{instanceId:this.instanceId,error:e}),this.setErrorState(e)}}}))}disconnectedCallback(){this.isWidgetConnected&&(c.debug("WidgeticWidget disconnected",{instanceId:this.instanceId}),this.cleanup(),this.isWidgetConnected=!1)}attributeChangedCallback(e,t,i){if(this.isInitialized&&t!==i){switch(c.debug("WidgeticWidget attribute changed",{instanceId:this.instanceId,attribute:e,oldValue:t,newValue:i}),e){case"width":case"height":this.updateDimensions();break;case"resize":this.updateResizeMode();break;case"autoscale":this.updateAutoscale();break;case"adaptive":this.updateAdaptive();break;case"theme":this.updateTheme()}this.notifyWidgetPropsChanged()}}initializeCSSIsolation(){this.setAttribute("data-widgetic-instance",this.instanceId),this.addBaseStyles(),this.initializeCSSCustomProperties()}addBaseStyles(){const e=`widgetic-base-styles-${this.instanceId}`;if(document.getElementById(e))return;const t=document.createElement("style");t.id=e,t.textContent=`\n /* Widget base styles with namespace isolation */\n widgetic-widget[data-widgetic-instance="${this.instanceId}"] {\n /* CSS Reset for widget container */\n all: initial;\n \n /* Widget container properties */\n display: block;\n box-sizing: border-box;\n position: relative;\n \n /* CSS custom properties with namespacing */\n --widgetic-instance: ${this.instanceId};\n --widgetic-primary: var(--widgetic-${this.instanceId}-primary, #007bff);\n --widgetic-secondary: var(--widgetic-${this.instanceId}-secondary, #6c757d);\n --widgetic-background: var(--widgetic-${this.instanceId}-background, #ffffff);\n --widgetic-text: var(--widgetic-${this.instanceId}-text, #333333);\n --widgetic-border: var(--widgetic-${this.instanceId}-border, #dee2e6);\n \n /* Widget content isolation */\n contain: layout style paint;\n isolation: isolate;\n }\n\n /* Prevent external CSS interference */\n widgetic-widget[data-widgetic-instance="${this.instanceId}"] * {\n box-sizing: border-box;\n }\n\n /* Loading state styles */\n widgetic-widget[data-widgetic-instance="${this.instanceId}"][data-loading="true"] {\n min-height: 120px;\n background: linear-gradient(90deg, #f0f0f0 25%, transparent 37%, #f0f0f0 63%);\n background-size: 400% 100%;\n animation: widgetic-loading-${this.instanceId} 1.5s ease-in-out infinite;\n }\n\n @keyframes widgetic-loading-${this.instanceId} {\n 0% { background-position: 100% 50%; }\n 100% { background-position: 0% 50%; }\n }\n\n /* Error state styles */\n widgetic-widget[data-widgetic-instance="${this.instanceId}"][data-error="true"] {\n border: 2px dashed #dc3545;\n background-color: #f8d7da;\n color: #721c24;\n padding: 16px;\n text-align: center;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;\n }\n `,document.head.appendChild(t)}initializeCSSCustomProperties(){const e=this.getAttribute("theme");if(e)try{const t=JSON.parse(e);Object.entries(t).forEach((([e,t])=>{this.style.setProperty(`--widgetic-${this.instanceId}-${e}`,String(t))}))}catch(t){c.warn("Invalid theme attribute",{instanceId:this.instanceId,theme:e})}}loadWidgetData(t){return e(this,void 0,void 0,(function*(){const e=a();this.compositionData=yield e.getComposition(t),this.widgetData=yield e.getWidget(this.compositionData.widgetId),c.debug("Widget data loaded",{instanceId:this.instanceId,compositionId:t,widgetId:this.compositionData.widgetId})}))}loadWidgetModule(){return e(this,void 0,void 0,(function*(){if(!this.widgetData)return;const e=d();this.loadedModule=yield e.loadModule(this.widgetData),c.debug("Widget module loaded",{instanceId:this.instanceId,moduleUrl:this.widgetData.moduleUrl,loadTime:this.loadedModule.loadTime})}))}initializeWidget(){return e(this,void 0,void 0,(function*(){if(!this.loadedModule||!this.compositionData)throw new Error("Widget module or composition data not loaded");try{const{component:e}=this.loadedModule.module,t=document.createElement("div");if(t.className=`widgetic-content-${this.instanceId}`,this.applyWidgetProperties(t),e.$$typeof)yield this.initializeReactComponent(t,e);else if(e._isVue||e.__isVue)yield this.initializeVueComponent(t,e);else{if("function"!=typeof e)throw new Error("Unsupported component type");yield this.initializeSvelteOrVanillaComponent(t,e)}this.innerHTML="",this.appendChild(t),this.isInitialized=!0,c.debug("Widget initialized successfully",{instanceId:this.instanceId})}catch(e){throw c.error("Widget initialization failed",{instanceId:this.instanceId,error:e}),e}}))}initializeReactComponent(t,i){return e(this,void 0,void 0,(function*(){if("undefined"==typeof window||!window.React||!window.ReactDOM)throw new Error("React not available globally");{const e=window.React,n=window.ReactDOM,o=this.getWidgetProps(),s=e.createElement(i,o);n.render(s,t)}}))}initializeVueComponent(t,i){return e(this,void 0,void 0,(function*(){if("undefined"==typeof window||!window.Vue)throw new Error("Vue not available globally");{const e=window.Vue,n=this.getWidgetProps();new e({el:t,render:e=>e(i,{props:n})})}}))}initializeSvelteOrVanillaComponent(t,i){return e(this,void 0,void 0,(function*(){var e;const n=this.getWidgetProps();if(i.$$prop_def||(null===(e=i.prototype)||void 0===e?void 0:e.$$prop_def))this.svelteComponent=new i({target:t,props:n});else if(i.prototype&&i.prototype.constructor===i){const e=new i(t,n);"function"==typeof e.render&&(yield e.render())}else if("function"==typeof i)yield i(t,n);else{if(!i||"function"!=typeof i.init)throw new Error("Unknown component type");yield i.init(t,n)}}))}getWidgetProps(){var e,t;return{config:(null===(e=this.compositionData)||void 0===e?void 0:e.config)||{},metadata:(null===(t=this.compositionData)||void 0===t?void 0:t.metadata)||{},instance:this.instanceId,element:this,dimensions:{width:this.getAttribute("width")||"100%",height:this.getAttribute("height")||"400"},resize:this.getAttribute("resize")||"responsive",autoscale:"true"===this.getAttribute("autoscale"),adaptive:parseInt(this.getAttribute("adaptive")||"768"),state:this.widgetState,onStateChange:this.handleStateChange.bind(this),onResize:this.handleResize.bind(this),onError:this.handleError.bind(this)}}applyWidgetProperties(e){var t;const i=this.getAttribute("width")||"100%",n=this.getAttribute("height")||"400",o=this.getAttribute("resize")||"responsive";switch(e.style.width="number"==typeof i?`${i}px`:i,e.style.height="number"==typeof n?`${n}px`:n,o){case"fill-width":e.style.width="100%";break;case"responsive":e.style.maxWidth="100%",e.style.height="auto"}e.classList.add(`widgetic-widget-${(null===(t=this.widgetData)||void 0===t?void 0:t.type)||"unknown"}`)}setupResponsiveBehavior(){const e=parseInt(this.getAttribute("adaptive")||"768"),t="true"===this.getAttribute("autoscale"),i=this.getAttribute("resize")||"responsive";t&&"ResizeObserver"in window&&(this.resizeObserver=new ResizeObserver((e=>{for(const t of e)this.handleAutoscale(t)})),this.resizeObserver.observe(this)),"responsive"!==i&&"fill-width"!==i||this.setupAdaptiveBehavior(e)}setupAdaptiveBehavior(e){const t=window.matchMedia(`(max-width: ${e}px)`),i=t=>{this.setAttribute("data-mobile",t.matches?"true":"false"),this.dispatchEvent(new CustomEvent("widgetic:adaptive",{detail:{isMobile:t.matches,breakpoint:e}}))};i(t),t.addEventListener("change",i),this.eventListeners.set("adaptive",(()=>{t.removeEventListener("change",i)}))}handleAutoscale(e){const{width:t,height:i}=e.contentRect;this.dispatchEvent(new CustomEvent("widgetic:resize",{detail:{width:t,height:i}})),this.widgetState.data.dimensions={width:t,height:i}}setupEventHandling(){const e=e=>{this.dispatchEvent(new CustomEvent("widgetic:interaction",{detail:{type:"click",originalEvent:e},bubbles:!0}))};this.addEventListener("click",e),this.eventListeners.set("click",(()=>{this.removeEventListener("click",e)}));const t=e=>{e.target instanceof HTMLFormElement&&this.handleFormSubmission(e)};this.addEventListener("submit",t),this.eventListeners.set("submit",(()=>{this.removeEventListener("submit",t)}))}handleFormSubmission(e){e.preventDefault();const t=e.target,i=new FormData(t),n={};i.forEach(((e,t)=>{n[t]=e})),this.widgetState.data.formData=n,this.dispatchEvent(new CustomEvent("widgetic:form-submit",{detail:{data:n,form:t},bubbles:!0})),c.debug("Form submitted",{instanceId:this.instanceId,data:n})}handleStateChange(e){this.widgetState.data=Object.assign(Object.assign({},this.widgetState.data),e),this.dispatchEvent(new CustomEvent("widgetic:state-change",{detail:{state:this.widgetState.data},bubbles:!0}))}handleResize(e){this.dispatchEvent(new CustomEvent("widgetic:resize",{detail:e,bubbles:!0}))}handleError(e){this.setErrorState(e)}updateDimensions(){const e=this.querySelector(`.widgetic-content-${this.instanceId}`);e&&this.applyWidgetProperties(e)}updateResizeMode(){this.updateDimensions(),this.setupResponsiveBehavior()}updateAutoscale(){this.setupResponsiveBehavior()}updateAdaptive(){const e=parseInt(this.getAttribute("adaptive")||"768");this.setupAdaptiveBehavior(e)}updateTheme(){this.initializeCSSCustomProperties()}notifyWidgetPropsChanged(){this.svelteComponent&&"function"==typeof this.svelteComponent.$set&&this.svelteComponent.$set(this.getWidgetProps()),this.dispatchEvent(new CustomEvent("widgetic:props-changed",{detail:{props:this.getWidgetProps()}}))}setLoadingState(e){this.widgetState.loading=e,this.setAttribute("data-loading",e?"true":"false"),e&&(this.innerHTML=`\n <div class="widgetic-loading-${this.instanceId}">\n <div>Loading widget...</div>\n </div>\n `)}setWidgetReady(){this.widgetState.ready=!0,this.widgetState.loading=!1,this.widgetState.error=null,this.setAttribute("data-ready","true"),this.removeAttribute("data-loading"),this.removeAttribute("data-error"),this.dispatchEvent(new CustomEvent("widgetic:ready",{detail:{instanceId:this.instanceId},bubbles:!0})),c.info("Widget ready",{instanceId:this.instanceId})}setErrorState(e){this.widgetState.error=e,this.widgetState.loading=!1,this.widgetState.ready=!1,this.setAttribute("data-error","true"),this.removeAttribute("data-loading"),this.removeAttribute("data-ready"),this.innerHTML=`\n <div class="widgetic-error-${this.instanceId}">\n <strong>Widget Error</strong><br>\n <small>${e.message}</small>\n </div>\n `,this.dispatchEvent(new CustomEvent("widgetic:error",{detail:{error:e.message,instanceId:this.instanceId},bubbles:!0})),c.error("Widget error",{instanceId:this.instanceId,error:e})}getState(){return Object.assign({},this.widgetState.data)}setState(e){this.handleStateChange(e)}refresh(){return e(this,void 0,void 0,(function*(){this.cleanup(),this.isInitialized=!1,this.isWidgetConnected=!1,yield this.connectedCallback()}))}cleanup(){this.svelteComponent&&"function"==typeof this.svelteComponent.$destroy&&(this.svelteComponent.$destroy(),this.svelteComponent=null),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.eventListeners.forEach((e=>{if("function"==typeof e)try{e()}catch(e){c.warn("Failed to cleanup event listener",{instanceId:this.instanceId,error:e})}})),this.eventListeners.clear();const e=document.getElementById(`widgetic-base-styles-${this.instanceId}`);e&&e.remove(),c.debug("Widget cleanup complete",{instanceId:this.instanceId})}generateInstanceId(){return`${Date.now()}-${Math.random().toString(36).substring(2,11)}`}}function E(){"undefined"!=typeof window&&"undefined"!=typeof customElements&&(customElements.get("widgetic-widget")||(customElements.define("widgetic-widget",I),c.info("WidgeticWidget custom element registered")))}class x{constructor(){this.observers=new Map,this.mutationObservers=new Map,this.timeouts=new Map,this.animationIds=new Map,this.storageKey="widgetic_autoscale_heights"}static getInstance(){return x.instance||(x.instance=new x),x.instance}enableAutoScale(e,t,i={enabled:!0}){if(!i.enabled)return;const n=Object.assign({minHeight:i.minHeight||50,maxHeight:i.maxHeight||2e3,debounceDelay:i.debounceDelay||150,threshold:i.threshold||5,animate:!1!==i.animate,animationDuration:i.animationDuration||300},i),o=e.offsetHeight,s=this.getStoredHeight(t);s&&s!==o&&this.setElementHeight(e,s,n.animate,n.animationDuration),this.setupContentMonitoring(e,t,n,o)}disableAutoScale(e){const t=this.observers.get(e);t&&(t.disconnect(),this.observers.delete(e));const i=this.mutationObservers.get(e);i&&(i.disconnect(),this.mutationObservers.delete(e));const n=this.timeouts.get(e);n&&(clearTimeout(n),this.timeouts.delete(e));const o=this.animationIds.get(e);o&&(cancelAnimationFrame(o),this.animationIds.delete(e));const s=document.querySelector(`iframe[data-widgetic-id="${e}"], iframe[data-composition-id="${e}"]`);s&&s._autoscaleMessageCleanup&&(s._autoscaleMessageCleanup(),delete s._autoscaleMessageCleanup)}getStoredHeight(e){try{const t=localStorage.getItem(this.storageKey);if(!t)return null;const i=JSON.parse(t),n=i[e];if(!n)return null;const o=864e5;return Date.now()-n.lastUpdated>o?(delete i[e],localStorage.setItem(this.storageKey,JSON.stringify(i)),null):n.height}catch(e){return null}}storeHeight(e,t,i){try{const n=localStorage.getItem(this.storageKey),o=n?JSON.parse(n):{};o[e]={compositionId:e,height:t,originalHeight:i,lastUpdated:Date.now()},localStorage.setItem(this.storageKey,JSON.stringify(o))}catch(e){}}setupContentMonitoring(e,t,i,n){const o=this.findContentElement(e);if(!o)return void e.tagName.toLowerCase();const s=this.createDebouncedHeightUpdate(e,t,i,n);if("undefined"!=typeof ResizeObserver){const e=new ResizeObserver((e=>{for(const t of e){const e=t.target.scrollHeight;s(e)}}));e.observe(o),this.observers.set(t,e)}const a=new MutationObserver((()=>{const e=o.scrollHeight;s(e)}));a.observe(o,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","class","height"]}),this.mutationObservers.set(t,a);const d=o.scrollHeight;s(d)}findContentElement(e){var t;if("iframe"===e.tagName.toLowerCase())try{const i=e,n=i.contentDocument||(null===(t=i.contentWindow)||void 0===t?void 0:t.document);if(null==n?void 0:n.body)return n.body}catch(t){return this.setupIframePostMessageListener(e),null}const i=e.tagName.toLowerCase();if("widgetic"===i||"widgetic-widget"===i||e.classList.contains("widgetic-widget")){return e.querySelector(".widget-content, .widgetic-content, [data-content]")||e}return e}setupIframePostMessageListener(e){const t=e.getAttribute("data-widgetic-id")||e.getAttribute("data-composition-id")||"unknown",i=i=>{var n,o;if(i.source===e.contentWindow&&("widgetic:autoscale"===(null===(n=i.data)||void 0===n?void 0:n.type)||"autoscale"===(null===(o=i.data)||void 0===o?void 0:o.type))){const{height:n,contentHeight:o}=i.data.payload||i.data;if("number"==typeof n&&n>0){const i=this.getConfigForWidget(t),s=Math.max(i.minHeight||50,Math.min(i.maxHeight||2e3,n));this.setElementHeight(e,s,i.animate,i.animationDuration),this.storeHeight(t,s,e.offsetHeight),e.dispatchEvent(new CustomEvent("widgetic:autoscale",{detail:{compositionId:t,oldHeight:e.offsetHeight,newHeight:s,contentHeight:o||n}}))}}};window.addEventListener("message",i),e._autoscaleMessageCleanup=()=>{window.removeEventListener("message",i)}}getConfigForWidget(e){return{enabled:!0,minHeight:50,maxHeight:2e3,animate:!0,animationDuration:300,debounceDelay:150,threshold:5}}createDebouncedHeightUpdate(e,t,i,n){let o=e.offsetHeight;return s=>{const a=this.timeouts.get(t);a&&clearTimeout(a);const d=setTimeout((()=>{const a=Math.max(i.minHeight,Math.min(i.maxHeight,s));Math.abs(a-o)>=i.threshold&&(this.setElementHeight(e,a,i.animate,i.animationDuration),this.storeHeight(t,a,n),o=a,e.dispatchEvent(new CustomEvent("widgetic:autoscale",{detail:{compositionId:t,oldHeight:o,newHeight:a,contentHeight:s}}))),this.timeouts.delete(t)}),i.debounceDelay);this.timeouts.set(t,d)}}setElementHeight(e,t,i=!0,n=300){if(!i)return void(e.style.height=`${t}px`);const o=e.offsetHeight,s=t-o;if(Math.abs(s)<1)return;const a=this.animationIds.get(e.id||e.tagName);a&&cancelAnimationFrame(a);const d=performance.now(),r=o,c=i=>{const o=i-d,a=Math.min(o/n,1),l=1-Math.pow(1-a,3),u=r+s*l;if(e.style.height=`${u}px`,a<1){const t=requestAnimationFrame(c);this.animationIds.set(e.id||e.tagName,t)}else e.style.height=`${t}px`,this.animationIds.delete(e.id||e.tagName)},l=requestAnimationFrame(c);this.animationIds.set(e.id||e.tagName,l)}clearStoredHeights(){try{localStorage.removeItem(this.storageKey)}catch(e){}}getStoredHeights(){try{const e=localStorage.getItem(this.storageKey);return e?JSON.parse(e):{}}catch(e){return{}}}destroy(){this.observers.forEach((e=>e.disconnect())),this.observers.clear(),this.mutationObservers.forEach((e=>e.disconnect())),this.mutationObservers.clear(),this.timeouts.forEach((e=>clearTimeout(e))),this.timeouts.clear(),this.animationIds.forEach((e=>cancelAnimationFrame(e))),this.animationIds.clear()}}class k{constructor(){this.autoScaleManager=x.getInstance(),E()}render(t){return e(this,void 0,void 0,(function*(){const{compositionId:e,width:i="100%",height:n="400",resize:o="responsive",autoscale:s=!0,adaptive:a=768,media:d,content:r}=t,c=document.createElement("widgetic-widget");if(c.setAttribute("composition-id",e),c.setAttribute("width",String(i)),c.setAttribute("height",String(n)),c.setAttribute("resize",o),"boolean"==typeof s?c.setAttribute("autoscale",s?"true":"false"):s&&"object"==typeof s?(c.setAttribute("autoscale","true"),void 0!==s.minHeight&&c.setAttribute("autoscale-min-height",String(s.minHeight)),void 0!==s.maxHeight&&c.setAttribute("autoscale-max-height",String(s.maxHeight)),void 0!==s.debounceDelay&&c.setAttribute("autoscale-debounce",String(s.debounceDelay)),void 0!==s.threshold&&c.setAttribute("autoscale-threshold",String(s.threshold)),void 0!==s.animate&&c.setAttribute("autoscale-animate",String(s.animate)),void 0!==s.animationDuration&&c.setAttribute("autoscale-animation-duration",String(s.animationDuration))):c.setAttribute("autoscale","false"),c.setAttribute("adaptive",String(a)),d&&Object.keys(d).length>0){b().registerWidget(e,d),this.setupCustomElementMediaListener(c,e)}if(r&&Object.keys(r).length>0){f().registerWidget(e,r),this.setupCustomElementContentListener(c,e)}return{id:`custom-${e}-${Date.now()}`,element:c,compositionData:{id:e,name:`Composition ${e}`,widgetId:`widget-${e}`,config:{}},widgetData:{id:`widget-${e}`,name:`Widget ${e}`,type:"custom-element",version:"1.0",moduleUrl:"",dependencies:[]},renderMode:"custom-element",cleanup:()=>{c._mediaCommandCleanup&&c._mediaCommandCleanup(),c._mediaObserverCleanup&&c._mediaObserverCleanup(),c._contentPositionCleanup&&c._contentPositionCleanup()}}}))}initializeWidget(t,i,n){return e(this,void 0,void 0,(function*(){}))}renderFrameworkComponent(t,i,n){return e(this,void 0,void 0,(function*(){if(i.$$typeof&&"undefined"!=typeof window&&window.React&&window.ReactDOM){const e=window.React,o=window.ReactDOM,s=e.createElement(i,{config:n.config,metadata:n.metadata});o.render(s,t)}else{if(!i._isVue&&!i.__isVue||"undefined"==typeof window||!window.Vue)throw new Error("Framework component detected but framework not available");new(0,window.Vue)({el:t,render:e=>e(i,{props:{config:n.config,metadata:n.metadata}})})}}))}applyElementStyling(e,t,i){const{width:n,height:o,resize:s,autoscale:a,adaptive:d}=i;switch(e.style.width="number"==typeof n?`${n}px`:n,e.style.height="number"==typeof o?`${o}px`:o,e.style.display="block",e.style.overflow="hidden",s){case"fill-width":e.style.width="100%";break;case"responsive":this.makeResponsive(e,d||768)}if(a){("boolean"==typeof a?a:a&&"object"==typeof a&&a.enabled)&&this.enableAutoscale(e,t,a)}e.classList.add("widgetic-widget","widgetic-custom-element")}makeResponsive(e,t){const i=window.matchMedia(`(max-width: ${t}px)`),n=()=>{i.matches?(e.style.width="100%",e.style.height="auto",e.style.minHeight="200px",e.classList.add("widgetic-mobile")):e.classList.remove("widgetic-mobile")};n(),i.addEventListener?i.addEventListener("change",n):i.addListener(n),e._responsiveCleanup=()=>{i.removeEventListener?i.removeEventListener("change",n):i.removeListener(n)}}enableAutoscale(e,t,i){const n="boolean"==typeof i?{enabled:i}:i;n.enabled&&(this.autoScaleManager.enableAutoScale(e,t,n),e._autoscaleCleanup=()=>{this.autoScaleManager.disableAutoScale(t)})}showLoadingState(e){e.innerHTML='\n <div class="widgetic-loading" style="\n display: flex;\n align-items: center;\n justify-content: center;\n height: 100%;\n background: #f8f9fa;\n border: 1px solid #e9ecef;\n border-radius: 4px;\n ">\n <div style="text-align: center; color: #6c757d;">\n <div style="\n width: 20px;\n height: 20px;\n border: 2px solid #dee2e6;\n border-top: 2px solid #007bff;\n border-radius: 50%;\n animation: spin 1s linear infinite;\n margin: 0 auto 8px;\n "></div>\n <small>Loading widget...</small>\n </div>\n </div>\n <style>\n @keyframes spin {\n 0% { transform: rotate(0deg); }\n 100% { transform: rotate(360deg); }\n }\n </style>\n '}showErrorState(e,t){const i=t instanceof Error?t.message:"Unknown error";e.innerHTML=`\n <div class="widgetic-error" style="\n display: flex;\n align-items: center;\n justify-content: center;\n height: 100%;\n background: #fff5f5;\n border: 1px solid #fed7d7;\n border-radius: 4px;\n color: #c53030;\n ">\n <div style="text-align: center; padding: 20px;">\n <div style="font-size: 24px; margin-bottom: 8px;">⚠️</div>\n <div style="font-weight: 500; margin-bottom: 4px;">Widget Error</div>\n <small style="color: #718096;">${i}</small>\n </div>\n </div>\n `,e.setAttribute("data-error","true"),e.dispatchEvent(new CustomEvent("widgetic:error",{detail:{error:i}}))}setupCustomElementMediaListener(e,t){const i=b(),n=t=>{const{command:i}=t.detail;if("pause"===i){const t=e.querySelectorAll("audio"),i=e.querySelectorAll("video");t.forEach((e=>{e.paused||e.pause()})),i.forEach((e=>{e.paused||e.pause()}))}else if("play"===i){const t=e.querySelectorAll("audio"),i=e.querySelectorAll("video"),n=Array.from(t).concat(Array.from(i)).find((e=>e.currentTime>0&&!e.ended));n&&n.play().catch((()=>{}))}};e.addEventListener("widgetic:media:command",n),e._mediaCommandCleanup=()=>{e.removeEventListener("widgetic:media:command",n)};const o=(n,o)=>s=>{const a=(e.__widgetConfig||{}).media||{},d="audio"===n.tagName.toLowerCase()?"audio":"video";i.handleMediaEvent({type:o,compositionId:t,config:a,data:{position:n.currentTime,duration:n.duration,volume:n.volume,mediaType:d,title:n.title||n.getAttribute("data-title")||void 0}})},s=()=>{const t=e.querySelectorAll("audio"),i=e.querySelectorAll("video");Array.from(t).concat(Array.from(i)).forEach((e=>{e.addEventListener("play",o(e,"play")),e.addEventListener("pause",o(e,"pause")),e.addEventListener("ended",o(e,"ended")),e.addEventListener("seeked",o(e,"seeking")),e.addEventListener("volumechange",o(e,"volumechange"))}))};s();const a=new MutationObserver((()=>{s()}));a.observe(e,{childList:!0,subtree:!0}),e._mediaObserverCleanup=()=>{a.disconnect()}}setupCustomElementContentListener(e,t){const i=f(),n=n=>{if(n.detail&&n.detail.type){const o=n.detail.type,s=n.detail.data||n.detail;let a={};try{const t=e.getAttribute("data-content-config");t&&(a=JSON.parse(t))}catch(e){a={contentType:"custom",persistState:!0}}i.handleContentPositionEvent({type:o,compositionId:t,config:a,data:s})}};e.addEventListener("widgetic:content:position",n),e.addEventListener("widgetic:content:navigate",n),e.addEventListener("widgetic:content:complete",n),e.addEventListener("widgetic:content:reset",n),e.addEventListener("widgetic:content:metadata",n),e._contentPositionCleanup=()=>{e.removeEventListener("widgetic:content:position",n),e.removeEventListener("widgetic:content:navigate",n),e.removeEventListener("widgetic:content:complete",n),e.removeEventListener("widgetic:content:reset",n),e.removeEventListener("widgetic:content:metadata",n)}}}var C=Object.freeze({__proto__:null,CustomElementRenderer:k});class S{constructor(){this.observers=new Map,this.callbacks=new Map,this.currentStates=new Map,this.debounceTimers=new Map,"undefined"==typeof ResizeObserver&&c.warn("ResizeObserver not available, responsive breakpoints will not work")}registerWidget(e,t,i,n){if("undefined"==typeof ResizeObserver)return void c.warn("ResizeObserver not available, skipping responsive registration",{widgetId:e});this.unregisterWidget(e);const o=t.getBoundingClientRect().width,s=i.initialMode||(o<i.breakpoint?"mobile":"desktop"),a={mode:s,breakpoint:i.breakpoint,width:o,timestamp:Date.now()};this.currentStates.set(e,a),this.callbacks.set(e,n);const d=new ResizeObserver((t=>{this.handleResize(e,t,i)}));d.observe(t),this.observers.set(e,d),n(a),c.debug("Widget registered for responsive monitoring",{widgetId:e,breakpoint:i.breakpoint,initialMode:s,containerWidth:o})}unregisterWidget(e){const t=this.debounceTimers.get(e);t&&(clearTimeout(t),this.debounceTimers.delete(e));const i=this.observers.get(e);i&&(i.disconnect(),this.observers.delete(e)),this.callbacks.delete(e),this.currentStates.delete(e),c.debug("Widget unregistered from responsive monitoring",{widgetId:e})}getCurrentState(e){return this.currentStates.get(e)||null}checkResponsiveState(e,t){const i=this.currentStates.get(e),n=this.callbacks.get(e);if(!i||!n)return void c.warn("Widget not registered for responsive monitoring",{widgetId:e});const o=t<i.breakpoint?"mobile":"desktop";if(o!==i.mode){const s={mode:o,breakpoint:i.breakpoint,width:t,timestamp:Date.now()};this.currentStates.set(e,s),n(s),c.info("Responsive state changed manually",{widgetId:e,from:i.mode,to:o,width:t,breakpoint:i.breakpoint})}}handleResize(e,t,i){const n=this.debounceTimers.get(e);n&&clearTimeout(n);const o=setTimeout((()=>{this.processResize(e,t,i),this.debounceTimers.delete(e)}),i.debounceDelay||150);this.debounceTimers.set(e,o)}processResize(e,t,i){const n=this.currentStates.get(e),o=this.callbacks.get(e);if(!n||!o)return;const s=t[t.length-1];if(!s)return;const a=s.contentRect.width,d=a<i.breakpoint?"mobile":"desktop";if(d!==n.mode){const t={mode:d,breakpoint:i.breakpoint,width:a,timestamp:Date.now()};this.currentStates.set(e,t),o(t),c.info("Responsive breakpoint crossed",{widgetId:e,from:n.mode,to:d,width:a,breakpoint:i.breakpoint})}else if(Math.abs(a-n.width)>10){const t=Object.assign(Object.assign({},n),{width:a,timestamp:Date.now()});this.currentStates.set(e,t),c.debug("Container width updated",{widgetId:e,width:a,mode:n.mode,breakpoint:i.breakpoint})}}getRegisteredWidgets(){return Array.from(this.observers.keys())}cleanup(){const e=this.getRegisteredWidgets();for(const t of e)this.unregisterWidget(t);c.debug("ResponsiveManager cleanup complete")}}let W=null;function M(){return W||(W=new S),W}class L{constructor(){this.messageQueue=new Map,this.iframeRegistry=new Map,this.loadingTimeouts=new Map,this.autoScaleManager=x.getInstance()}renderWidget(t){return e(this,void 0,void 0,(function*(){const{compositionId:e,width:i,height:n,resize:o="fixed",autoscale:s=!1,adaptive:a,responsive:d,container:l,allowFullscreen:u=!0,sandbox:g=this.getDefaultSandboxPermissions(),allowedFeatures:h=this.getDefaultAllowedFeatures(),loading:m="lazy",enableResize:p=!0,compositionData:w,widgetData:y,security:I={},fallback:E={enabled:!0,timeout:1e4,retryCount:3},media:x}=t;if(!i||!n||!l)throw new Error("Missing required parameters: width, height, and container are required");const k=w||{id:e,name:`Composition ${e}`,widgetId:`widget-${e}`,config:{}},C=y||{id:k.widgetId,name:`Widget ${e}`,type:"iframe",version:"1.0",moduleUrl:"",dependencies:[]};try{const w=this.createSecureIframe(e,t);w.src=yield this.buildSecureIframeUrl(e,t),w.title=`Widgetic Widget: ${k.name||e}`,w.loading=m,this.applySandboxSecurity(w,g,h),w.width=i.toString(),w.height=n.toString(),w.frameBorder="0",w.scrolling="no",u&&(w.allowFullscreen=!0,w.setAttribute("allowfullscreen","")),w.title=`Widgetic Widget ${e}`,w.setAttribute("aria-label",`${r("interactiveWidget")}: ${e}`);const y={compositionId:e,renderMode:"iframe",displayMode:"inline",resize:o,width:"number"==typeof i?i:parseInt(i.toString()),height:"number"==typeof n?n:parseInt(n.toString()),autoscale:s,adaptive:a,responsive:d,media:x},S=v.generateIframeCSS(y);S&&(w.style.cssText+=S),this.applyIframeStyling(w,e,{width:i,height:n,resize:o,autoscale:s,adaptive:a}),w.style.visibility="hidden",w.style.opacity="0",w.style.transition="opacity 0.3s ease",this.addLoadingIndicator(l,y),this.setupEnhancedIframeMessaging(w,e,I),this.setupLoadingOptimization(w,e,E);const W="lazy"===m,M=new Promise(((t,i)=>{let n=null;W||(n=setTimeout((()=>{i(new Error(`Iframe load timeout for composition: ${e}`))}),E.timeout||1e4)),w.onload=()=>{n&&clearTimeout(n),this.removeLoadingIndicator(l),w.style.visibility="visible",w.style.opacity="1",t()},w.onerror=()=>{n&&clearTimeout(n),this.removeLoadingIndicator(l),i(new Error(`Failed to load iframe for composition: ${e}`))}}));if(l.appendChild(w),p&&"undefined"!=typeof ResizeObserver){const t=new v({observeResize:!0}),i=`iframe-${e}-${Date.now()}`;w.setAttribute("data-widget-id",i),t.registerWidget(i,w,l,y),w.__resizeHandler=t,w.__widgetId=i}d&&"number"==typeof d&&d>0&&this.setupResponsiveMonitoring(w,l,e,d),this.iframeRegistry.set(e,w),w.classList.add("widgetic-widget","widgetic-iframe","widgetic-enhanced"),W||(yield M);const L=`iframe-${e}-${Date.now()}`;if(c.info("Enhanced iframe widget rendered successfully",{compositionId:e,size:{width:i,height:n},resize:o,autoscale:s,responsive:d,sandbox:g.join(" "),features:h.join("; ")}),y.media&&Object.keys(y.media).length>0){b().registerWidget(e,y.media),this.setupIframeMediaListener(w,e)}if(t.content&&Object.keys(t.content).length>0){f().registerWidget(e,t.content),this.setupIframeContentListener(w,e)}return{id:L,element:w,compositionData:k,widgetData:C,renderMode:"iframe",cleanup:()=>this.cleanupWidget(w)}}catch(t){throw c.error("Enhanced iframe widget rendering failed",{compositionId:e,error:t}),this.removeLoadingIndicator(l),t}}))}renderWidgets(t){return e(this,void 0,void 0,(function*(){c.debug("Rendering multiple iframe widgets",{count:t.length});const e=t.map((e=>this.renderWidget(e))),i=yield Promise.allSettled(e),n=[];for(let e=0;e<i.length;e++){const o=i[e],s=t[e];if("fulfilled"===o.status)n.push(o.value);else{c.error("Iframe widget rendering failed in batch",{compositionId:s.compositionId,error:o.reason});const e=`error-${s.compositionId}-${Date.now()}`;n.push({id:e,element:this.createErrorElement(s,o.reason),compositionData:{id:s.compositionId,name:`Composition ${s.compositionId}`,widgetId:`widget-${s.compositionId}`,config:{}},widgetData:{id:`widget-${s.compositionId}`,name:`Widget ${s.compositionId}`,type:"iframe",version:"1.0",moduleUrl:"",dependencies:[]},renderMode:"iframe",cleanup:()=>{}})}}return c.info("Iframe batch rendering complete",{total:t.length,successful:n.filter((e=>"IFRAME"===e.element.tagName)).length,failed:n.filter((e=>"IFRAME"!==e.element.tagName)).length}),n}))}createSecureIframe(e,t){var i;const n=document.createElement("iframe");return n.style.border="none",n.style.display="block",n.style.overflow="hidden",n.setAttribute("referrerpolicy","strict-origin-when-cross-origin"),n.setAttribute("crossorigin","anonymous"),(null===(i=t.security)||void 0===i?void 0:i.enableCSP)&&n.setAttribute("csp",this.generateCSP(t.security.allowedOrigins)),n.setAttribute("data-widgetic-id",e),n.setAttribute("data-enhanced","true"),n}getDefaultSandboxPermissions(){return["allow-scripts","allow-same-origin","allow-forms","allow-popups","allow-presentation","allow-downloads"]}getDefaultAllowedFeatures(){return["autoplay","encrypted-media","picture-in-picture","fullscreen","clipboard-read","clipboard-write"]}applySandboxSecurity(e,t,i){e.setAttribute("sandbox",t.join(" ")),e.setAttribute("allow",i.join("; ")),e.setAttribute("fetchpriority","high")}generateCSP(e){const t=e||[l.CLIENT_URL];return[`default-src 'self' ${t.join(" ")}`,`script-src 'self' 'unsafe-inline' ${t.join(" ")}`,`style-src 'self' 'unsafe-inline' ${t.join(" ")}`,`img-src 'self' data: blob: ${t.join(" ")}`,`media-src 'self' blob: ${t.join(" ")}`,"object-src 'none'","base-uri 'self'","form-action 'self'"].join("; ")}buildSecureIframeUrl(t,i){return e(this,void 0,void 0,(function*(){var e;const n=`${l.CLIENT_URL}/embed/${t}`,o=new URLSearchParams;i.width&&o.set("width","number"==typeof i.width?i.width.toString():i.width),i.height&&o.set("height","number"==typeof i.height?i.height.toString():i.height),i.resize&&o.set("resize",i.resize),i.autoscale&&o.set("autoscale","true"),i.adaptive&&o.set("adaptive",i.adaptive.toString()),i.responsive&&"number"==typeof i.responsive&&o.set("responsive",i.responsive.toString()),(null===(e=i.security)||void 0===e?void 0:e.signatureValidation)&&o.set("validateSignature","true"),o.set("sdkVersion","1.0"),o.set("mode","iframe");try{const e=yield g();o.set("apiKey",e)}catch(e){c.warn("Failed to get auth token for iframe",e),l.API_KEY&&o.set("apiKey",l.API_KEY)}const s=`${n}?${o.toString()}`;return c.debug("Built secure iframe URL",{compositionId:t,url:s}),s}))}applyIframeStyling(e,t,i){const{width:n,height:o,resize:s,autoscale:a,adaptive:d}=i;if(e.style.width="number"==typeof n?`${n}px`:n,e.style.height="number"==typeof o?`${o}px`:o,"fill-width"===s)e.style.width="100%",e.style.height="auto",e.style.minHeight="number"==typeof o?`${o}px`:o;a&&this.enableIframeAutoscale(e,t,a),d&&this.makeIframeResponsive(e,d)}makeIframeResponsive(e,t){const i=window.matchMedia(`(max-width: ${t}px)`),n=()=>{i.matches?(e.style.width="100%",e.style.height="auto",e.style.minHeight="200px",e.classList.add("widgetic-mobile")):e.classList.remove("widgetic-mobile")};n(),i.addEventListener?i.addEventListener("change",n):i.addListener(n),e._responsiveCleanup=()=>{i.removeEventListener?i.removeEventListener("change",n):i.removeListener(n)}}enableIframeAutoscale(e,t,i){const n="boolean"==typeof i?{enabled:i}:i;n.enabled&&(this.autoScaleManager.enableAutoScale(e,t,n),e._autoscaleCleanup=()=>{this.autoScaleManager.disableAutoScale(t)},c.debug("AutoScale enabled for iframe",{compositionId:t,config:n}))}setupLoadingOptimization(e,t,i){if(!i.enabled)return;const n=i.timeout||1e4,o=i.retryCount||3;let s=0;const a=()=>{s<o?(s++,c.warn(`Iframe loading failed, retrying (${s}/${o})`,{compositionId:t}),setTimeout((()=>{e.src=e.src+"&retry="+s}),1e3*s)):(c.error("Iframe loading failed after retries",{compositionId:t,retryCount:o}),this.handleIframeFallback(e,t))},d=setTimeout((()=>{c.warn("Iframe loading timeout",{compositionId:t,timeout:n}),a()}),n);this.loadingTimeouts.set(t,d),e.addEventListener("load",(()=>{const e=this.loadingTimeouts.get(t);e&&(clearTimeout(e),this.loadingTimeouts.delete(t)),c.debug("Iframe loaded successfully",{compositionId:t})})),e.addEventListener("error",(()=>{c.error("Iframe error occurred",{compositionId:t}),a()}))}handleIframeFallback(e,t){const i=document.createElement("div");i.className="widgetic-iframe-fallback",i.innerHTML='\n <div style="\n display: flex;\n align-items: center;\n justify-content: center;\n height: 100%;\n background: #f8f9fa;\n border: 1px solid #e9ecef;\n border-radius: 4px;\n color: #6c757d;\n text-align: center;\n padding: 20px;\n ">\n <div>\n <div style="font-size: 24px; margin-bottom: 8px;">⚠️</div>\n <div style="font-weight: 500; margin-bottom: 4px;">Widget Unavailable</div>\n <small>The widget could not be loaded. Please try refreshing the page.</small>\n </div>\n </div>\n ',e.parentNode&&(e.parentNode.insertBefore(i,e),e.parentNode.removeChild(e)),i.dispatchEvent(new CustomEvent("widgetic:fallback",{detail:{compositionId:t,reason:"loading_failed"},bubbles:!0}))}setupEnhancedIframeMessaging(e,t,i={}){const n=w({enableSignatureValidation:i.signatureValidation||!1,allowedOrigins:i.allowedOrigins,enableHeartbeat:!0,heartbeatInterval:3e4});n.registerHandler(t,(t=>{this.handleEnhancedIframeMessage(e,t)})),e.addEventListener("load",(()=>{n.sendMessage(t,{type:"config",instanceId:t,payload:{compositionId:t,apiUrl:u(),timestamp:Date.now(),sdkVersion:"2.0",mode:"iframe"},timestamp:Date.now(),version:"1.0"}),c.debug("Initial config sent to iframe",{compositionId:t})})),e.__messenger=n,e.__messagingCompositionId=t,c.debug("Enhanced iframe messaging setup complete",{compositionId:t})}handleEnhancedIframeMessage(e,t){switch(c.debug("Enhanced iframe message received",{type:t.type,instanceId:t.instanceId,sequence:t.sequence}),t.type){case"resize":this.handleResizeMessage(e,t);break;case"ready":this.handleReadyMessage(e,t);break;case"error":this.handleErrorMessage(e,t);break;case"data":this.handleDataMessage(e,t);break;case"event":this.handleEventMessage(e,t);break;default:c.debug("Unknown enhanced message type",{type:t.type,instanceId:t.instanceId})}}handleResizeMessage(e,t){const{width:i,height:n}=t.payload;i&&n&&(e.style.width=`${i}px`,e.style.height=`${n}px`,e.dispatchEvent(new CustomEvent("widgetic:resize",{detail:{width:i,height:n,instanceId:t.instanceId},bubbles:!0})),c.debug("Iframe resized",{width:i,height:n,instanceId:t.instanceId}))}handleReadyMessage(e,t){e.setAttribute("data-ready","true"),e.dispatchEvent(new CustomEvent("widgetic:ready",{detail:{instanceId:t.instanceId,compositionId:t.compositionId,payload:t.payload},bubbles:!0})),c.info("Iframe widget ready",{instanceId:t.instanceId})}handleErrorMessage(e,t){e.setAttribute("data-error","true"),e.dispatchEvent(new CustomEvent("widgetic:error",{detail:{instanceId:t.instanceId,compositionId:t.compositionId,error:t.payload.error,code:t.payload.code},bubbles:!0})),c.error("Iframe widget error",{instanceId:t.instanceId,error:t.payload.error})}handleDataMessage(e,t){e.dispatchEvent(new CustomEvent("widgetic:data",{detail:{instanceId:t.instanceId,compositionId:t.compositionId,data:t.payload},bubbles:!0})),c.debug("Iframe data received",{instanceId:t.instanceId,dataType:t.payload.type})}handleEventMessage(e,t){e.dispatchEvent(new CustomEvent("widgetic:interaction",{detail:{instanceId:t.instanceId,compositionId:t.compositionId,eventType:t.payload.type,eventData:t.payload.data},bubbles:!0})),c.debug("Iframe interaction event",{instanceId:t.instanceId,eventType:t.payload.type})}sendMessageToIframe(e,t,i){w().sendMessage(e,{type:t,instanceId:e,payload:i,timestamp:Date.now(),version:"1.0"})}addLoadingIndicator(e,t){const i=document.createElement("div");i.className="widgetic-loading-indicator",i.style.cssText=`\n display: flex;\n align-items: center;\n justify-content: center;\n width: ${t.width}px;\n height: ${t.height}px;\n background: #f5f5f5;\n color: #666;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n font-size: 14px;\n border: 1px solid #e0e0e0;\n border-radius: 4px;\n position: relative;\n `,i.innerHTML='\n <div style="text-align: center;">\n <div style="\n width: 20px;\n height: 20px;\n border: 2px solid #e0e0e0;\n border-top: 2px solid #666;\n border-radius: 50%;\n animation: widgetic-spin 1s linear infinite;\n margin: 0 auto 8px;\n "></div>\n <div>Loading widget...</div>\n </div>\n ';const n=document.createElement("style");n.textContent="\n @keyframes widgetic-spin {\n 0% { transform: rotate(0deg); }\n 100% { transform: rotate(360deg); }\n }\n ",document.head.appendChild(n),e.appendChild(i)}removeLoadingIndicator(e){const t=e.querySelector(".widgetic-loading-indicator");t&&t.parentNode&&t.parentNode.removeChild(t)}createErrorElement(e,t){const i=document.createElement("div");return i.className="widgetic-error",i.style.cssText=`\n display: flex;\n align-items: center;\n justify-content: center;\n width: ${e.width}px;\n height: ${e.height}px;\n background: #fff5f5;\n color: #e53e3e;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n font-size: 14px;\n border: 1px solid #fed7d7;\n border-radius: 4px;\n text-align: center;\n padding: 16px;\n box-sizing: border-box;\n `,i.innerHTML=`\n <div>\n <div style="font-weight: 600; margin-bottom: 4px;">Widget Error</div>\n <div style="font-size: 12px; opacity: 0.8;">Failed to load composition: ${e.compositionId}</div>\n </div>\n `,i}cleanupWidget(e){const t=e.__resizeHandler,i=e.__widgetId;t&&i&&t.unregisterWidget(i);const n=e.__responsiveManager,o=e.__responsiveId;n&&o&&n.unregisterWidget(o);const s=e.__messenger,a=e.__messagingCompositionId;s&&a&&s.unregisterHandler(a);const d=this.loadingTimeouts.get(a);d&&(clearTimeout(d),this.loadingTimeouts.delete(a)),a&&this.iframeRegistry.delete(a),e._responsiveCleanup&&e._responsiveCleanup(),e._autoscaleCleanup&&e._autoscaleCleanup(),e.parentNode&&e.parentNode.removeChild(e),c.debug("Iframe cleanup complete",{compositionId:a})}cleanupIframe(e){const t=this.iframeRegistry.get(e);t&&this.cleanupWidget(t)}setupResponsiveMonitoring(e,t,i,n){const o=M(),s=w(),a={breakpoint:n,debounceDelay:150},d=`responsive-${i}`;o.registerWidget(d,t,a,(t=>{c.debug("Responsive state changed, notifying iframe",{compositionId:i,mode:t.mode,breakpoint:t.breakpoint,width:t.width}),s.sendMessage(i,{type:"responsive",instanceId:i,compositionId:i,payload:{mode:t.mode,breakpoint:t.breakpoint,width:t.width,timestamp:t.timestamp},timestamp:Date.now(),version:"1.0"}),e.dispatchEvent(new CustomEvent("widgetic:responsive",{detail:{instanceId:i,compositionId:i,mode:t.mode,breakpoint:t.breakpoint,width:t.width},bubbles:!0}))})),e.__responsiveId=d,e.__responsiveManager=o,c.info("Responsive monitoring enabled for iframe",{compositionId:i,breakpoint:n,containerId:d})}setupIframeMediaListener(e,t){const i=b(),n=n=>{var o,s;if(n.source===e.contentWindow&&(null===(s=null===(o=n.data)||void 0===o?void 0:o.type)||void 0===s?void 0:s.startsWith("widgetic:media:"))){const o=n.data.type.replace("widgetic:media:","");if(["play","pause","stop","ended","seeking","volumechange"].includes(o)){const s=e.getAttribute("data-widget-config"),a=s?JSON.parse(s):{};i.handleMediaEvent({type:o,compositionId:t,config:a.media||{},data:n.data.payload||n.data.data||{}})}}};window.addEventListener("message",n),e._mediaListenerCleanup=()=>{window.removeEventListener("message",n)}}setupIframeContentListener(e,t){const i=f(),n=n=>{var o,s;if(n.source===e.contentWindow&&(null===(s=null===(o=n.data)||void 0===o?void 0:o.type)||void 0===s?void 0:s.startsWith("widgetic:content:"))){const o=n.data.type.replace("widgetic:content:","");if(["position","navigate","complete","reset","metadata"].includes(o)){const s=e.getAttribute("data-widgetic-config");let a={};if(s)try{a=JSON.parse(s).content||{}}catch(e){a={contentType:"custom",persistState:!0}}i.handleContentPositionEvent({type:o,compositionId:t,config:a,data:n.data.payload||n.data.data||{}})}}};window.addEventListener("message",n),e._contentListenerCleanup=()=>{window.removeEventListener("message",n)}}}let $=null;var A=Object.freeze({__proto__:null,IframeRenderer:L,getIframeRenderer:function(){return $||($=new L),$}});class z{constructor(){this.batchClient=a(),this.moduleLoader=d(),this.customElementRenderer=new k,this.iframeRenderer=new L,this.renderedWidgets=new Map}renderWidget(t){return e(this,void 0,void 0,(function*(){const e=this.generateWidgetId(t.compositionId),i=this.createLoadingElement(t.container);t.container&&i&&t.container.appendChild(i);try{const n=yield this.batchClient.getComposition(t.compositionId),o=yield this.batchClient.getWidget(n.widgetId),s=this.determineRenderMode(t.renderMode,o);let a;if("custom-element"===s)try{a=yield this.moduleLoader.loadModule(o)}catch(s){const a=yield this.renderWithIframe(e,t,n,o);return this.removeLoadingElement(i),a}const d="iframe"===s?yield this.renderWithIframe(e,t,n,o):yield this.renderWithCustomElement(e,t,n,o,a);return this.removeLoadingElement(i),this.renderedWidgets.set(e,d),this.emitWidgetEvent("ready",{widgetId:e,compositionId:t.compositionId,renderMode:d.renderMode,loadTime:(null==a?void 0:a.loadTime)||0,cached:(null==a?void 0:a.cached)||!1}),d}catch(n){if(this.removeLoadingElement(i),this.emitWidgetEvent("error",{widgetId:e,compositionId:t.compositionId,error:n instanceof Error?n.message:String(n),fallback:"iframe"}),t.container){const e=this.createErrorElement(t.compositionId,n);t.container.appendChild(e)}try{const i=yield this.renderFallback(e,t);if(t.container){const e=t.container.querySelector(".widgetic-error");e&&e.remove()}return i}catch(e){throw new Error(`Widget rendering failed: ${n}. Fallback also failed: ${e}`)}}}))}renderWidgets(t){return e(this,void 0,void 0,(function*(){const i=t.map((e=>e.compositionId)),n=yield this.batchClient.getCompositions(i),o=new Map(n.map((e=>[e.id,e]))),s=new Set;for(const e of t)if("iframe"!==e.renderMode){const t=o.get(e.compositionId);t&&t.widgetId&&s.add(t.widgetId)}const a=s.size>0?yield this.batchClient.getWidgets(Array.from(s)):[],d=new Map(a.map((e=>[e.id,e]))),r=a.filter((e=>"custom-element"===this.determineRenderMode("auto",e)));r.length>0&&(yield this.moduleLoader.preloadModules(r));const c=t.map((t=>e(this,void 0,void 0,(function*(){const e=o.get(t.compositionId)||{id:t.compositionId,widgetId:"default",name:"Composition",settings:{},config:{},version:"1.0.0"},i=d.get(e.widgetId)||{id:e.widgetId||"default",name:"Widget",type:"iframe",version:"1.0.0",moduleUrl:"",dependencies:[]};return this.renderSingleWidgetWithData(t,e,i)}))));return(yield Promise.allSettled(c)).filter((e=>"rejected"!==e.status)).map((e=>e.value))}))}getWidget(e){return this.renderedWidgets.get(e)||null}getAllWidgets(){return Array.from(this.renderedWidgets.values())}refreshWidget(t){return e(this,void 0,void 0,(function*(){const e=this.renderedWidgets.get(t);if(!e)return null;e.cleanup(),this.renderedWidgets.delete(t);const i={compositionId:e.compositionData.id,renderMode:e.renderMode,container:e.element.parentElement||void 0};return this.batchClient.clearCache(),this.moduleLoader.invalidateModule(e.widgetData.id),this.renderWidget(i)}))}cleanupWidget(e){const t=this.renderedWidgets.get(e);t&&(t.cleanup(),this.renderedWidgets.delete(e))}cleanupAll(){const e=Array.from(this.renderedWidgets.values());for(const t of e)t.cleanup();this.renderedWidgets.clear()}getStats(){return{renderedWidgets:this.renderedWidgets.size,batchCache:this.batchClient.getCacheStats(),moduleCache:this.moduleLoader.getCacheStats(),widgets:Array.from(this.renderedWidgets.entries()).map((([e,t])=>({id:e,compositionId:t.compositionData.id,widgetType:t.widgetData.type,renderMode:t.renderMode,hasModule:!!t.loadedModule})))}}renderSingleWidgetWithData(t,i,n){return e(this,void 0,void 0,(function*(){const e=this.generateWidgetId(t.compositionId);if("custom-element"===this.determineRenderMode(t.renderMode,n))try{const o=yield this.moduleLoader.loadModule(n);return this.renderWithCustomElement(e,t,i,n,o)}catch(e){}return this.renderWithIframe(e,t,i,n)}))}renderWithCustomElement(t,i,n,o,s){return e(this,void 0,void 0,(function*(){const e=yield this.customElementRenderer.render({compositionId:i.compositionId,compositionData:n,widgetData:o,loadedModule:s,width:i.width,height:i.height,resize:i.resize,autoscale:i.autoscale,adaptive:i.adaptive});return i.container&&i.container.appendChild(e.element),{id:t,element:e.element,compositionData:n,widgetData:o,loadedModule:s,renderMode:"custom-element",cleanup:()=>{e.element.remove()}}}))}renderWithIframe(t,i,n,o){return e(this,void 0,void 0,(function*(){return yield this.iframeRenderer.renderWidget({compositionId:i.compositionId,compositionData:n,widgetData:o,width:i.width,height:i.height,resize:i.resize,autoscale:i.autoscale,adaptive:i.adaptive,container:i.container})}))}renderFallback(t,i){return e(this,void 0,void 0,(function*(){const e=document.createElement("div");return e.className="widgetic-fallback",e.innerHTML=`\n <div style="\n padding: 20px; \n text-align: center; \n background: #f5f5f5; \n border: 1px solid #ddd; \n border-radius: 4px;\n color: #666;\n ">\n <p>Widget temporarily unavailable</p>\n <small>Composition ID: ${i.compositionId}</small>\n </div>\n `,i.container&&i.container.appendChild(e),{id:t,element:e,compositionData:{id:i.compositionId,name:"Fallback",widgetId:"fallback",config:{}},widgetData:{id:"fallback",name:"Fallback Widget",type:"fallback",version:"1.0.0",moduleUrl:""},renderMode:"iframe",cleanup:()=>{e.remove()}}}))}determineRenderMode(e="auto",t){var i;if("auto"!==e)return e;const n="undefined"!=typeof customElements&&"function"==typeof customElements.define,o=(null==t?void 0:t.moduleUrl)||(null===(i=null==t?void 0:t.metadata)||void 0===i?void 0:i.supportsCustomElements);return n&&o?"custom-element":"iframe"}generateWidgetId(e){return`widget-${e}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}emitWidgetEvent(e,t){const i=new CustomEvent(`widgetic:${e}`,{detail:t,bubbles:!0});document.dispatchEvent(i)}createLoadingElement(e){if(!e)return null;const t=document.createElement("div");return t.className="widgetic-loading",t.style.cssText="\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100px;\n background: #f8f9fa;\n border: 1px solid #e9ecef;\n border-radius: 4px;\n color: #6c757d;\n ",t.innerHTML='\n <div style="text-align: center;">\n <div style="\n width: 20px;\n height: 20px;\n border: 2px solid #f3f3f3;\n border-top: 2px solid #007bff;\n border-radius: 50%;\n animation: widgetic-spin 1s linear infinite;\n margin: 0 auto 8px;\n "></div>\n <div style="font-size: 14px;">Loading widget...</div>\n </div>\n ',this.addLoadingStyles(),t}removeLoadingElement(e){e&&e.parentNode&&e.parentNode.removeChild(e)}createErrorElement(e,t){const i=document.createElement("div");i.className="widgetic-error",i.style.cssText="\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100px;\n padding: 20px;\n text-align: center;\n background: #fff5f5;\n border: 1px solid #fed7d7;\n border-radius: 4px;\n color: #742a2a;\n ";const n=t instanceof Error?t.message:"Unknown error occurred",o=this.analyzeError(n,t);return i.innerHTML=`\n <div>\n <div style="font-size: 24px; margin-bottom: 8px;">${o.icon}</div>\n <div style="font-weight: 500; margin-bottom: 8px;">${o.title}</div>\n <div style="font-size: 14px; margin-bottom: 12px; color: #666;">\n ${o.description}\n </div>\n <div style="font-size: 12px; margin-bottom: 16px; color: #888;">\n Widget ID: ${e}\n </div>\n ${o.actionHtml}\n </div>\n `,i}analyzeError(e,t){const i=e.toLowerCase();return i.includes("composition not found")||i.includes("404")?{icon:"🔍",title:"Widget Not Found",description:"This widget may have been removed or the ID is incorrect.",actionHtml:`\n <button \n onclick="window.open('mailto:support@widgetic.com?subject=Widget%20Not%20Found%20-%20${encodeURIComponent(t.compositionId||"Unknown")}&body=Widget%20ID:%20${encodeURIComponent(t.compositionId||"Unknown")}%0AThe%20widget%20could%20not%20be%20found.%20Please%20check%20if%20it%20was%20deleted%20or%20if%20the%20ID%20is%20correct.', '_blank')"\n style="\n background: #007bff;\n color: white;\n border: none;\n padding: 8px 16px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 14px;\n text-decoration: none;\n display: inline-block;\n "\n onmouseover="this.style.background='#0056b3'"\n onmouseout="this.style.background='#007bff'"\n >\n 📧 Contact Support\n </button>\n `}:i.includes("unauthorized")||i.includes("forbidden")||i.includes("401")||i.includes("403")||i.includes("permission")||i.includes("access denied")?{icon:"🔒",title:"Access Restricted",description:"This widget requires an active subscription or has been restricted.",actionHtml:`\n <div style="margin-bottom: 12px;">\n <a \n href="https://widgetic.com/pricing" \n target="_blank"\n style="\n background: #28a745;\n color: white;\n border: none;\n padding: 8px 16px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 14px;\n text-decoration: none;\n display: inline-block;\n "\n onmouseover="this.style.background='#218838'"\n onmouseout="this.style.background='#28a745'"\n >\n ⭐ Upgrade Plan\n </a>\n </div>\n <button \n onclick="window.open('mailto:support@widgetic.com?subject=Widget%20Access%20Issue%20-%20${encodeURIComponent(t.compositionId||"Unknown")}&body=Widget%20ID:%20${encodeURIComponent(t.compositionId||"Unknown")}%0AI%20am%20having%20trouble%20accessing%20this%20widget.%20Please%20check%20my%20account%20status%20and%20permissions.', '_blank')"\n style="\n background: transparent;\n color: #007bff;\n border: 1px solid #007bff;\n padding: 6px 12px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 12px;\n "\n onmouseover="this.style.background='#007bff'; this.style.color='white'"\n onmouseout="this.style.background='transparent'; this.style.color='#007bff'"\n >\n 📧 Contact Support\n </button>\n `}:i.includes("deleted")||i.includes("expired")||i.includes("no longer available")?{icon:"🗑️",title:"Widget Deleted",description:"This widget has been permanently removed.",actionHtml:`\n <button \n onclick="window.open('mailto:support@widgetic.com?subject=Deleted%20Widget%20-%20${encodeURIComponent(t.compositionId||"Unknown")}&body=Widget%20ID:%20${encodeURIComponent(t.compositionId||"Unknown")}%0AThis%20widget%20appears%20to%20have%20been%20deleted.%20Can%20you%20help%20me%20restore%20it%20or%20find%20an%20alternative?', '_blank')"\n style="\n background: #007bff;\n color: white;\n border: none;\n padding: 8px 16px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 14px;\n text-decoration: none;\n display: inline-block;\n "\n onmouseover="this.style.background='#0056b3'"\n onmouseout="this.style.background='#007bff'"\n >\n 📧 Contact Support\n </button>\n `}:i.includes("subscription")||i.includes("billing")||i.includes("payment")||i.includes("plan")||i.includes("downgrade")?{icon:"💳",title:"Subscription Required",description:"This widget requires an active subscription to display.",actionHtml:`\n <div style="margin-bottom: 12px;">\n <a \n href="https://widgetic.com/pricing" \n target="_blank"\n style="\n background: #28a745;\n color: white;\n border: none;\n padding: 8px 16px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 14px;\n text-decoration: none;\n display: inline-block;\n margin-right: 8px;\n "\n onmouseover="this.style.background='#218838'"\n onmouseout="this.style.background='#28a745'"\n >\n ⭐ View Plans\n </a>\n <a \n href="https://widgetic.com/dashboard/billing" \n target="_blank"\n style="\n background: #6c757d;\n color: white;\n border: none;\n padding: 8px 16px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 14px;\n text-decoration: none;\n display: inline-block;\n "\n onmouseover="this.style.background='#5a6268'"\n onmouseout="this.style.background='#6c757d'"\n >\n 💳 Billing\n </a>\n </div>\n <div style="font-size: 12px; color: #888; margin-top: 8px;">\n Need help? Contact support below\n </div>\n <button \n onclick="window.open('mailto:support@widgetic.com?subject=Subscription%20Issue%20-%20${encodeURIComponent(t.compositionId||"Unknown")}&body=Widget%20ID:%20${encodeURIComponent(t.compositionId||"Unknown")}%0AI%20need%20help%20with%20my%20subscription%20to%20access%20this%20widget.', '_blank')"\n style="\n background: transparent;\n color: #007bff;\n border: 1px solid #007bff;\n padding: 4px 8px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 11px;\n margin-top: 4px;\n "\n onmouseover="this.style.background='#007bff'; this.style.color='white'"\n onmouseout="this.style.background='transparent'; this.style.color='#007bff'"\n >\n 📧 Contact Support\n </button>\n `}:i.includes("timeout")||i.includes("network")||i.includes("connection")||i.includes("fetch")?{icon:"🌐",title:"Connection Issue",description:"Unable to load widget due to network connectivity.",actionHtml:`\n <button \n onclick="window.location.reload()"\n style="\n background: #28a745;\n color: white;\n border: none;\n padding: 8px 16px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 14px;\n margin-right: 8px;\n "\n onmouseover="this.style.background='#218838'"\n onmouseout="this.style.background='#28a745'"\n >\n 🔄 Retry\n </button>\n <button \n onclick="window.open('mailto:support@widgetic.com?subject=Widget%20Connection%20Issue%20-%20${encodeURIComponent(t.compositionId||"Unknown")}&body=Widget%20ID:%20${encodeURIComponent(t.compositionId||"Unknown")}%0AError:%20${encodeURIComponent(e)}%0A%0AI%20am%20experiencing%20connection%20issues%20loading%20this%20widget.', '_blank')"\n style="\n background: transparent;\n color: #007bff;\n border: 1px solid #007bff;\n padding: 6px 12px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 12px;\n "\n onmouseover="this.style.background='#007bff'; this.style.color='white'"\n onmouseout="this.style.background='transparent'; this.style.color='#007bff'"\n >\n 📧 Contact Support\n </button>\n `}:{icon:"⚠️",title:"Widget Unavailable",description:e||"An unknown error occurred while loading this widget.",actionHtml:`\n <button \n onclick="window.open('mailto:support@widgetic.com?subject=Widget%20Error%20-%20${encodeURIComponent(t.compositionId||"Unknown")}&body=Widget%20ID:%20${encodeURIComponent(t.compositionId||"Unknown")}%0AError:%20${encodeURIComponent(e)}', '_blank')"\n style="\n background: #007bff;\n color: white;\n border: none;\n padding: 8px 16px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 14px;\n text-decoration: none;\n display: inline-block;\n "\n onmouseover="this.style.background='#0056b3'"\n onmouseout="this.style.background='#007bff'"\n >\n 📧 Contact Support\n </button>\n <div style="margin-top: 8px;">\n <button \n onclick="window.location.reload()"\n style="\n background: transparent;\n color: #007bff;\n border: 1px solid #007bff;\n padding: 6px 12px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 12px;\n margin-left: 8px;\n "\n onmouseover="this.style.background='#007bff'; this.style.color='white'"\n onmouseout="this.style.background='transparent'; this.style.color='#007bff'"\n >\n 🔄 Refresh Page\n </button>\n </div>\n `}}addLoadingStyles(){const e="widgetic-loading-styles";if(document.getElementById(e))return;const t=document.createElement("style");t.id=e,t.textContent="\n @keyframes widgetic-spin {\n 0% { transform: rotate(0deg); }\n 100% { transform: rotate(360deg); }\n }\n ",document.head.appendChild(t)}}let R=null;function D(){return R||(R=new z),R}function _(){R&&R.cleanupAll(),R=null}var H=Object.freeze({__proto__:null,WidgetRenderer:z,getWidgetRenderer:D,resetWidgetRenderer:_});export{k as C,L as I,I as W,z as a,_ as b,C as c,D as g,A as i,E as r,H as w};