@widgetic/embed-sdk 2.0.14 → 2.0.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +31 -9
- package/dist/browser/chunks/ABTestManager.js +1 -1
- package/dist/browser/chunks/advanced.js +1 -1
- package/dist/browser/chunks/api.js +1 -1
- package/dist/browser/chunks/core.js +1 -1
- package/dist/browser/chunks/display.js +1 -1
- package/dist/browser/chunks/media.js +1 -1
- package/dist/browser/chunks/messaging.js +1 -1
- package/dist/browser/chunks/renderers.js +1 -1
- package/dist/browser/chunks/scanner.js +1 -1
- package/dist/browser/chunks/security.js +1 -1
- package/dist/browser/embed-bootstrap.js +1 -1
- package/dist/browser/embed-sdk.js +1 -1
- package/dist/esm/chunks/ABTestManager.js +1 -1
- package/dist/esm/chunks/advanced.js +1 -1
- package/dist/esm/chunks/api.js +1 -1
- package/dist/esm/chunks/core.js +1 -1
- package/dist/esm/chunks/display.js +1 -1
- package/dist/esm/chunks/media.js +1 -1
- package/dist/esm/chunks/messaging.js +1 -1
- package/dist/esm/chunks/renderers.js +1 -1
- package/dist/esm/chunks/scanner.js +1 -1
- package/dist/esm/chunks/security.js +1 -1
- package/dist/esm/embed-bootstrap.js +1 -1
- package/dist/esm/embed-sdk.js +1 -1
- package/dist/esm/types/abTesting/ABTestElement.d.ts +10 -0
- package/dist/esm/types/abTesting/ABTestManager.d.ts +54 -12
- package/dist/esm/types/abTesting/abVisitor.d.ts +31 -0
- package/dist/esm/types/core/advanced-security-manager.d.ts +3 -0
- package/dist/esm/types/core/widget-manager.d.ts +8 -43
- package/dist/esm/types/utils/declarative-embed-parser.d.ts +14 -0
- package/dist/esm/types/utils/hydrate-published-host.d.ts +7 -4
- package/dist/esm/types/utils/image-delivery.d.ts +54 -0
- package/dist/esm/types/utils/lookup-cache.d.ts +34 -0
- package/dist/esm/types/utils/preload-content-images.d.ts +21 -0
- package/dist/esm/types/utils/public-embed-lookup.d.ts +3 -0
- package/dist/esm/types/utils/published-host-bridge.d.ts +16 -0
- package/dist/umd/embed-bootstrap.js +1 -1
- package/dist/umd/embed-sdk.js +1 -1
- package/package.json +1 -1
- package/dist/esm/types/core/realtime-manager.d.ts +0 -286
|
@@ -1 +1 @@
|
|
|
1
|
-
import{l as e}from"./core.js";import{_ as t}from"./vendor.js";import{c as i}from"./advanced.js";import{c as n}from"./api.js";class s{constructor(e={}){this.options=e,this.resizeObserver=null,this.instances=new Map,this.debounceTimers=new Map,this.options=Object.assign({observeResize:!0,debounceMs:100,enableAdaptive:!0},e),this.options.observeResize&&"undefined"!=typeof ResizeObserver&&(this.resizeObserver=new ResizeObserver(this.handleResize.bind(this)))}registerWidget(t,i,n,s){const o={widgetId:t,element:i,container:n,config:s,originalWidth:s.width,originalHeight:s.height,aspectRatio:s.width/s.height,isObserving:!1};this.instances.set(t,o),this.applyResizeMode(o),this.resizeObserver&&this.options.observeResize&&(this.resizeObserver.observe(n),o.isObserving=!0),e.debug("Widget registered for resize handling",{widgetId:t,resizeMode:s.resize,originalSize:{width:s.width,height:s.height}})}unregisterWidget(t){const i=this.instances.get(t);if(!i)return;this.resizeObserver&&i.isObserving&&this.resizeObserver.unobserve(i.container);const n=this.debounceTimers.get(t);n&&(clearTimeout(n),this.debounceTimers.delete(t)),this.instances.delete(t),e.debug("Widget unregistered from resize handling",{widgetId:t})}static generateIframeCSS(e){const{resize:t,width:i,height:n,autoscale:s}=e;let o="";switch(t){case"fill-width":o=`\n width: 100% !important;\n height: ${n/i*100}vw !important;\n max-height: ${n}px !important;\n object-fit: ${s?"contain":"cover"};\n `;break;case"fill-height":o=`\n height: 100% !important;\n width: ${i/n*100}vh !important;\n max-width: ${i}px !important;\n object-fit: ${s?"contain":"cover"};\n `;break;case"fixed":default:o=`\n width: ${i}px !important;\n height: ${n}px !important;\n flex-shrink: 0;\n object-fit: cover;\n `;break;case"fixed-height":o=`\n width: 100% !important;\n height: ${n}px !important;\n object-fit: ${s?"contain":"cover"};\n `;break;case"fixed-width":o=`\n width: ${i}px !important;\n height: 100% !important;\n object-fit: ${s?"contain":"cover"};\n `;break;case"allow-scale-down":o=`\n max-width: ${i}px !important;\n max-height: ${n}px !important;\n width: 100% !important;\n height: auto !important;\n object-fit: contain;\n `;break;case"fill":o=`\n width: 100% !important;\n height: 100% !important;\n object-fit: ${s?"contain":"cover"};\n `}return o.trim()}applyResizeMode(t){const{element:i,container:n,config:s}=t,{resize:o,autoscale:r}=s,a=n.getBoundingClientRect(),l=a.width,d=a.height;let c,h;switch(o){case"fill-width":c=l,h=c/t.aspectRatio,r&&h>d&&(h=d,c=h*t.aspectRatio);break;case"fill-height":h=d,c=h*t.aspectRatio,r&&c>l&&(c=l,h=c/t.aspectRatio);break;case"fixed":default:c=t.originalWidth,h=t.originalHeight;break;case"fixed-height":c=l,h=t.originalHeight;break;case"fixed-width":c=t.originalWidth,h=d;break;case"allow-scale-down":const e=l/t.originalWidth,i=d/t.originalHeight,n=Math.min(1,Math.min(e,i));c=t.originalWidth*n,h=t.originalHeight*n;break;case"fill":c=l,h=d}this.setElementSize(i,c,h,s),this.options.enableAdaptive&&s.adaptive&&this.handleAdaptiveBreakpoint(t,l),e.debug("Resize mode applied",{widgetId:t.widgetId,resizeMode:o,containerSize:{width:l,height:d},newSize:{width:c,height:h}})}setElementSize(e,t,i,n){switch(e.style.width=`${Math.round(t)}px`,e.style.height=`${Math.round(i)}px`,n.resize){case"fill":case"fill-width":case"fill-height":e.style.objectFit=n.autoscale?"contain":"cover";break;default:e.style.objectFit="contain"}e.style.boxSizing="border-box",e.style.display="block"}handleAdaptiveBreakpoint(e,t){if(!e.config.adaptive)return;const i=t<=e.config.adaptive,n=e.element;i?(n.classList.add("widgetic-adaptive-mobile"),n.classList.remove("widgetic-adaptive-desktop"),n.style.maxWidth="100%",n.style.fontSize="14px"):(n.classList.add("widgetic-adaptive-desktop"),n.classList.remove("widgetic-adaptive-mobile"),n.style.fontSize="")}handleResize(e){for(const t of e){const e=t.target;for(const[t,i]of this.instances)if(i.container===e){const e=this.debounceTimers.get(t);e&&clearTimeout(e);const n=window.setTimeout((()=>{this.applyResizeMode(i),this.debounceTimers.delete(t)}),this.options.debounceMs);this.debounceTimers.set(t,n)}}}forceResize(e){const t=this.instances.get(e);t&&this.applyResizeMode(t)}forceResizeAll(){for(const e of this.instances.values())this.applyResizeMode(e)}cleanup(){for(const e of this.debounceTimers.values())clearTimeout(e);this.debounceTimers.clear(),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.instances.clear()}}let o=null;function r(e){return o||(o=new s(e)),o}class a{constructor(e={}){this.options=e,this.instances=new Map,this.widgetElements=new Map,this.widgetConfigs=new Map,this.fullscreenListeners=new Map,this.keyboardListeners=new Map,this.options=Object.assign({enableFullscreen:!0,enableOverlay:!0,enablePopup:!0,defaultOverlayZIndex:5e4,defaultPopupFeatures:"width=800,height=600,scrollbars=yes,resizable=yes"},e),this.setupGlobalKeyHandlers()}initializeWidget(e,t,i){const n={mode:t.displayMode||"inline",isFullscreen:!1,isOverlay:!1,isPopup:!1};return this.instances.set(e,n),this.widgetElements.set(e,i),this.widgetConfigs.set(e,t),this.setupDisplayMode(e,t,i),n}setupDisplayMode(e,t,i){const{displayMode:n}=t;switch(n){case"fullscreen":this.setupFullscreenMode(e,t,i);break;case"overlay":case"modal":this.setupOverlayMode(e,t,i);break;case"popup":this.setupPopupMode(e,t,i)}}setupFullscreenMode(e,t,i){var n;if(!this.options.enableFullscreen||!(null===(n=t.fullscreen)||void 0===n?void 0:n.enabled))return;const s=t.fullscreen.trigger||"click";"manual"!==s&&this.addFullscreenTrigger(e,i,s),t.fullscreen.showControls&&this.addFullscreenControls(e,i)}setupOverlayMode(e,t,i){var n;if(!this.options.enableOverlay||!(null===(n=t.overlay)||void 0===n?void 0:n.enabled))return;const s=t.overlay.trigger||"click";"auto"===s?setTimeout((()=>this.showOverlay(e)),100):"manual"!==s&&this.addOverlayTrigger(e,i,s)}setupPopupMode(e,t,i){var n;if(!this.options.enablePopup||!(null===(n=t.popup)||void 0===n?void 0:n.enabled))return;const s=t.popup.trigger||"click";"manual"!==s&&this.addPopupTrigger(e,i,s)}enterFullscreen(n){return t(this,void 0,void 0,(function*(){const t=this.instances.get(n);if(t&&!t.isFullscreen)try{const s=this.getWidgetElement(n);if(!s)throw new Error(`Widget element not found: ${n}`);const o=i({target:"widgetic-fullscreen",zIndex:100001,className:"fullscreen-widget"}),r=document.createElement("div");r.className="widgetic-fullscreen-container",r.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n background: #000;\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: 100001;\n ",t.originalStyle=s.style.cssText;const a=document.createComment(`widgetic-fullscreen-placeholder-${n}`);s.parentNode&&(s.parentNode.replaceChild(a,s),t.originalPlaceholder=a),s.style.cssText="\n width: 100%;\n height: 100%;\n max-width: 100vw;\n max-height: 100vh;\n border: none;\n ",r.appendChild(s);const l=this.createExitButton((()=>this.exitFullscreen(n)));if(r.appendChild(l),o.mount(r),t.isFullscreen=!0,t.overlayPortal=o,t.fullscreenElement=r,this.setupFullscreenKeyHandler(n),document.documentElement.requestFullscreen)try{yield document.documentElement.requestFullscreen()}catch(t){e.warn("Native fullscreen failed, using CSS fullscreen",{error:t})}e.info("Widget entered fullscreen mode",{widgetId:n})}catch(t){throw e.error("Failed to enter fullscreen",{widgetId:n,error:t}),t}}))}exitFullscreen(i){return t(this,void 0,void 0,(function*(){const t=this.instances.get(i);if(t&&t.isFullscreen)try{const n=this.getWidgetElement(i);n&&t.originalPlaceholder&&t.originalPlaceholder.parentNode&&(t.originalPlaceholder.parentNode.replaceChild(n,t.originalPlaceholder),t.originalPlaceholder=void 0,void 0!==t.originalStyle&&(n.style.cssText=t.originalStyle,t.originalStyle=void 0)),t.overlayPortal&&t.overlayPortal.destroy(),document.fullscreenElement&&document.exitFullscreen&&(yield document.exitFullscreen()),t.isFullscreen=!1,t.overlayPortal=void 0,t.fullscreenElement=void 0,this.removeFullscreenKeyHandler(i),e.info("Widget exited fullscreen mode",{widgetId:i})}catch(t){throw e.error("Failed to exit fullscreen",{widgetId:i,error:t}),t}}))}showOverlay(n){return t(this,void 0,void 0,(function*(){const t=this.instances.get(n);if(t&&!t.isOverlay)try{const s=this.getWidgetConfig(n),o=null==s?void 0:s.overlay;if(!o)throw new Error(`No overlay configuration for widget: ${n}`);const r=i({target:"widgetic-overlay",zIndex:o.zIndex||this.options.defaultOverlayZIndex,className:"overlay-widget"}),a=this.createOverlayContainer(n,o),l=this.getWidgetElement(n);if(l){t.originalStyle=l.style.cssText;const e=document.createComment(`widgetic-overlay-placeholder-${n}`);l.parentNode&&(l.parentNode.replaceChild(e,l),t.originalPlaceholder=e),this.styleOverlayWidget(l,o);a.querySelector(".overlay-content").appendChild(l)}r.mount(a),t.isOverlay=!0,t.overlayPortal=r,this.setupOverlayCloseHandlers(n,a,o),e.info("Widget shown in overlay mode",{widgetId:n})}catch(t){throw e.error("Failed to show overlay",{widgetId:n,error:t}),t}}))}hideOverlay(i){return t(this,void 0,void 0,(function*(){const t=this.instances.get(i);if(t&&t.isOverlay)try{const n=this.getWidgetElement(i);n&&t.originalPlaceholder&&t.originalPlaceholder.parentNode&&(t.originalPlaceholder.parentNode.replaceChild(n,t.originalPlaceholder),t.originalPlaceholder=void 0,void 0!==t.originalStyle&&(n.style.cssText=t.originalStyle,t.originalStyle=void 0)),t.overlayPortal&&t.overlayPortal.destroy(),t.isOverlay=!1,t.overlayPortal=void 0,this.removeOverlayKeyHandler(i),e.info("Widget overlay hidden",{widgetId:i})}catch(t){throw e.error("Failed to hide overlay",{widgetId:i,error:t}),t}}))}openPopup(i){return t(this,void 0,void 0,(function*(){const t=this.instances.get(i);if(!t||t.isPopup)return(null==t?void 0:t.popupWindow)||null;try{const n=this.getWidgetConfig(i),s=null==n?void 0:n.popup;if(!s)throw new Error(`No popup configuration for widget: ${i}`);const o=this.buildPopupFeatures(s),r=this.generatePopupUrl(i),a=window.open(r,s.target||`widgetic_${i}`,o);if(!a)throw new Error("Popup blocked by browser");return t.isPopup=!0,t.popupWindow=a,this.monitorPopupClose(i,a),e.info("Widget opened in popup",{widgetId:i}),a}catch(t){throw e.error("Failed to open popup",{widgetId:i,error:t}),t}}))}closePopup(t){const i=this.instances.get(t);if(i&&i.isPopup&&i.popupWindow)try{i.popupWindow.close(),i.isPopup=!1,i.popupWindow=null,e.info("Widget popup closed",{widgetId:t})}catch(i){e.error("Failed to close popup",{widgetId:t,error:i})}}getDisplayState(e){return this.instances.get(e)||null}cleanup(e){const t=this.instances.get(e);t&&(t.isFullscreen&&this.exitFullscreen(e),t.isOverlay&&this.hideOverlay(e),t.isPopup&&this.closePopup(e),this.instances.delete(e),this.removeFullscreenKeyHandler(e),this.removeOverlayKeyHandler(e))}cleanupAll(){for(const e of this.instances.keys())this.cleanup(e)}getWidgetElement(e){return this.widgetElements.has(e)?this.widgetElements.get(e):document.querySelector(`[data-widget-id="${e}"]`)||document.querySelector(`[data-widgetic-id="${e}"]`)||document.querySelector(`[composition-id="${e}"]`)||null}getWidgetConfig(e){return this.widgetConfigs.get(e)||null}addFullscreenTrigger(e,t,i){const n=()=>this.enterFullscreen(e);switch(i){case"click":t.addEventListener("click",n);break;case"double-click":t.addEventListener("dblclick",n);break;case"hover":t.addEventListener("mouseenter",n)}}addOverlayTrigger(e,t,i){const n=()=>this.showOverlay(e);switch(i){case"click":t.addEventListener("click",n);break;case"hover":t.addEventListener("mouseenter",n)}}addPopupTrigger(e,t,i){const n=()=>this.openPopup(e);"click"===i&&t.addEventListener("click",n)}createExitButton(e){const t=document.createElement("button");return t.className="widgetic-exit-fullscreen",t.innerHTML="✕",t.setAttribute("aria-label",n("close")),t.style.cssText="\n position: absolute;\n top: 20px;\n right: 20px;\n background: rgba(0, 0, 0, 0.7);\n color: white;\n border: none;\n border-radius: 50%;\n width: 40px;\n height: 40px;\n font-size: 20px;\n cursor: pointer;\n z-index: 100002;\n ",t.addEventListener("click",e),t}createOverlayContainer(e,t){const i=document.createElement("div");i.className="widgetic-overlay-container",i.style.cssText=`\n position: fixed;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n display: flex;\n align-items: center;\n justify-content: center;\n background: ${t.backdrop?"rgba(0, 0, 0, 0.8)":"transparent"};\n `;const n=document.createElement("div");if(n.className="overlay-content",n.style.cssText=`\n max-width: ${t.maxWidth||"90vw"};\n max-height: ${t.maxHeight||"90vh"};\n background: white;\n border-radius: 8px;\n overflow: hidden;\n position: relative;\n `,t.showCloseButton){const t=this.createExitButton((()=>this.hideOverlay(e)));n.appendChild(t)}return i.appendChild(n),i}styleOverlayWidget(e,t){const i="mixed"===t.embedTarget&&!t.keepDimensions;let n=t.width||"100%",s=t.height||"100%";i&&(t.overlayWidth||t.overlayHeight)&&(n=t.overlayWidth||n,s=t.overlayHeight||s),e.style.cssText=`\n width: ${n};\n height: ${s};\n border: none;\n display: block;\n `,i&&t.overlayResize&&this.applyOverlayResizeMode(e,t.overlayResize)}applyOverlayResizeMode(e,t){if(e.parentElement)switch(t){case"fill-width":e.style.width="100%",e.style.height="auto",e.style.aspectRatio="auto";break;case"fill-height":e.style.height="100%",e.style.width="auto",e.style.aspectRatio="auto";break;case"fixed":e.style.flexShrink="0";break;case"fixed-height":e.style.width="100%";break;case"fixed-width":e.style.height="100%";break;case"allow-scale-down":e.style.maxWidth="100%",e.style.maxHeight="100%",e.style.objectFit="contain";break;case"fill":e.style.width="100%",e.style.height="100%",e.style.objectFit="cover"}}buildPopupFeatures(e){const t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.centerScreen&&t.push("location=center"),e.allowResize&&t.push("resizable=yes"),e.showToolbar&&t.push("toolbar=yes"),t.length>0?t.join(","):this.options.defaultPopupFeatures||""}generatePopupUrl(e){return"about:blank"}setupGlobalKeyHandlers(){"undefined"!=typeof document&&document.addEventListener("keydown",(e=>{if("Escape"===e.key)for(const[e,t]of this.instances)t.isFullscreen?this.exitFullscreen(e):t.isOverlay&&this.hideOverlay(e)}))}setupFullscreenKeyHandler(e){const t=t=>{"Escape"===t.key&&this.exitFullscreen(e)};this.keyboardListeners.set(`${e}-fullscreen`,t),document.addEventListener("keydown",t)}removeFullscreenKeyHandler(e){const t=this.keyboardListeners.get(`${e}-fullscreen`);t&&(document.removeEventListener("keydown",t),this.keyboardListeners.delete(`${e}-fullscreen`))}setupOverlayCloseHandlers(e,t,i){if(i.closeOnBackdropClick&&t.addEventListener("click",(i=>{i.target===t&&this.hideOverlay(e)})),i.closeOnEscape){const t=t=>{"Escape"===t.key&&this.hideOverlay(e)};this.keyboardListeners.set(`${e}-overlay`,t),document.addEventListener("keydown",t)}}removeOverlayKeyHandler(e){const t=this.keyboardListeners.get(`${e}-overlay`);t&&(document.removeEventListener("keydown",t),this.keyboardListeners.delete(`${e}-overlay`))}monitorPopupClose(e,t){const i=()=>{if(t.closed){const t=this.instances.get(e);t&&(t.isPopup=!1,t.popupWindow=null)}else setTimeout(i,1e3)};setTimeout(i,1e3)}addFullscreenControls(e,t){const i=document.createElement("div");i.className="widgetic-fullscreen-controls",i.style.cssText="\n position: absolute;\n bottom: 10px;\n right: 10px;\n background: rgba(0, 0, 0, 0.7);\n border-radius: 4px;\n padding: 5px;\n z-index: 1000;\n ";const n=document.createElement("button");n.innerHTML="⛶",n.style.cssText="\n background: none;\n border: none;\n color: white;\n cursor: pointer;\n font-size: 16px;\n ",n.addEventListener("click",(()=>this.enterFullscreen(e))),i.appendChild(n),t.style.position="relative",t.appendChild(i)}}let l=null;function d(e){return l||(l=new a(e)),l}var c=Object.freeze({__proto__:null,DisplayManager:a,getDisplayManager:d,resetDisplayManager:function(){l&&(l.cleanupAll(),l=null)}});const h={mobile:480,tablet:768,desktop:1024},g={MANUAL:"manual",EXIT_INTENT:"exit-intent",ON_SCROLL:"on-scroll",TIME_DELAY:"time-delay",ENGAGEMENT_THRESHOLD:"engagement",EXTERNAL_TRIGGER:"external"},p={DEFAULT_ANIMATION:"fade",DEFAULT_DELAY_MS:1e3,DEFAULT_MOBILE_BREAKPOINT:768,SUPPORTED_ANIMATIONS:["fade","slide-up","slide-down","slide-left","slide-right","zoom","bounce"]};class u{constructor(t={enabled:!0}){var i;this.isEnabled=!1,this.activeOverlay=null,this.exitIntentListener=null,this.scrollListener=null,this.engagementStartTime=null,this.timeoutId=null,this.config=Object.assign(Object.assign({exitIntentEnabled:!0,scrollTriggerEnabled:!0,timeTriggerEnabled:!0,engagementThresholdEnabled:!0,externalTriggerEnabled:!0},t),{enabled:null===(i=t.enabled)||void 0===i||i}),this.config.breakpoints||(this.config.breakpoints={useBreakpoints:!1,mobile:h.mobile,tablet:h.tablet,desktop:h.desktop}),this.isEnabled=this.config.enabled,this.isEnabled&&this.initializeEventListeners(),e.debug("OverlayManager initialized",{config:this.config})}initializeEventListeners(){"undefined"!=typeof window&&(this.config.exitIntentEnabled&&this.initializeExitIntent(),this.config.scrollTriggerEnabled&&this.initializeScrollTrigger(),this.config.engagementThresholdEnabled&&this.startEngagementTracking())}initializeExitIntent(){"undefined"!=typeof document&&(this.exitIntentListener=e=>{e.clientY<=0&&e.movementY<0&&this.emitOverlayTrigger("exit-intent",{mousePosition:{x:e.clientX,y:e.clientY},movementY:e.movementY})},document.addEventListener("mouseleave",this.exitIntentListener))}initializeScrollTrigger(){"undefined"!=typeof window&&(this.scrollListener=()=>{const e=window.scrollY/(document.documentElement.scrollHeight-window.innerHeight)*100;e>=25&&e<30?this.emitOverlayTrigger("scroll-25",{scrollPercentage:e}):e>=50&&e<55?this.emitOverlayTrigger("scroll-50",{scrollPercentage:e}):e>=75&&e<80&&this.emitOverlayTrigger("scroll-75",{scrollPercentage:e})},window.addEventListener("scroll",this.scrollListener,{passive:!0}))}startEngagementTracking(){this.engagementStartTime=Date.now();setInterval((()=>{if(!this.engagementStartTime)return;const e=Date.now()-this.engagementStartTime;e>=3e4?this.emitOverlayTrigger("engagement-30s",{engagementTimeMs:e}):e>=6e4?this.emitOverlayTrigger("engagement-1m",{engagementTimeMs:e}):e>=12e4&&this.emitOverlayTrigger("engagement-2m",{engagementTimeMs:e})}),1e4)}showOverlay(t){if(this.isEnabled){this.activeOverlay&&(e.debug("Overlay already active, closing previous"),this.hideOverlay());try{const i=this.validateOverlayConfig(t),n=this.createOverlayElement(i);document.body.appendChild(n),this.activeOverlay=n,setTimeout((()=>{n.classList.add("widgetic-overlay-visible")}),50),i.autoClose&&i.autoClose>0&&(this.timeoutId=window.setTimeout((()=>{this.hideOverlay()}),i.autoClose)),e.info("Overlay displayed",{displayMode:i.displayMode,animation:i.animation,autoClose:i.autoClose}),this.emitOverlayEvent("overlay-shown",i)}catch(i){e.error("Failed to show overlay",{error:i,config:t})}}else e.warn("Overlay manager is disabled")}validateOverlayConfig(t){const i=Object.assign({},t);return i.displayMode&&Object.values(g).includes(i.displayMode)||(i.displayMode=g.MANUAL),i.animation&&p.SUPPORTED_ANIMATIONS.includes(i.animation)||(i.animation=p.DEFAULT_ANIMATION,e.debug("Using default animation for overlay",{provided:t.animation,defaultUsed:p.DEFAULT_ANIMATION})),i.delay||(i.delay=p.DEFAULT_DELAY_MS),void 0===i.showBackdrop&&(i.showBackdrop=!0),i}hideOverlay(){if(!this.activeOverlay)return;this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null);const t=this.activeOverlay;t.classList.remove("widgetic-overlay-visible"),t.classList.add("widgetic-overlay-hiding"),setTimeout((()=>{t.parentNode&&t.parentNode.removeChild(t)}),300),this.activeOverlay=null,e.debug("Overlay hidden"),this.emitOverlayEvent("overlay-hidden",{})}createOverlayElement(e){const t=document.createElement("div");t.className=`widgetic-overlay widgetic-overlay-${e.animation||p.DEFAULT_ANIMATION}`,!1!==e.showBackdrop&&t.classList.add("widgetic-overlay-backdrop"),t.innerHTML=`\n <div class="widgetic-overlay-content">\n <button class="widgetic-overlay-close">×</button>\n <div class="widgetic-overlay-body">\n ${e.content}\n </div>\n </div>\n `,this.addOverlayStyles();const i=t.querySelector(".widgetic-overlay-close");i&&(i.setAttribute("aria-label",n("close")),i.addEventListener("click",(()=>this.hideOverlay()))),t.addEventListener("click",(i=>{i.target===t&&!1!==e.showBackdrop&&this.hideOverlay()}));const s=e=>{"Escape"===e.key&&(this.hideOverlay(),document.removeEventListener("keydown",s))};return document.addEventListener("keydown",s),t}generateResponsiveCSS(){const e=this.config.breakpoints;if(!e||!e.useBreakpoints)return"/* No mobile responsive styles - breakpoints disabled */";const t=e.mobile||h.mobile;return`\n /* Mobile responsive styles */\n @media (max-width: ${t}px) {\n .widgetic-overlay-content {\n max-width: 95vw;\n margin: 10px;\n }\n \n .widgetic-overlay-body {\n padding: 15px;\n }\n }\n \n /* Tablet responsive styles */\n @media (min-width: ${t+1}px) and (max-width: ${e.tablet||h.tablet}px) {\n .widgetic-overlay-content {\n max-width: 90vw;\n margin: 15px;\n }\n \n .widgetic-overlay-body {\n padding: 18px;\n }\n }\n `}addOverlayStyles(){const e="widgetic-overlay-styles";if(document.getElementById(e))return;const t=document.createElement("style");t.id=e,t.textContent=`\n .widgetic-overlay {\n position: fixed;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n z-index: 10000;\n display: flex;\n align-items: center;\n justify-content: center;\n opacity: 0;\n transition: opacity 0.3s ease;\n }\n \n .widgetic-overlay-backdrop {\n background: rgba(0, 0, 0, 0.5);\n }\n \n .widgetic-overlay-visible {\n opacity: 1;\n }\n \n .widgetic-overlay-hiding {\n opacity: 0;\n }\n \n .widgetic-overlay-content {\n position: relative;\n background: white;\n border-radius: 8px;\n max-width: 90vw;\n max-height: 90vh;\n overflow: auto;\n transition: all 0.3s ease;\n }\n \n .widgetic-overlay-close {\n position: absolute;\n top: 10px;\n right: 15px;\n background: none;\n border: none;\n font-size: 24px;\n cursor: pointer;\n z-index: 1;\n color: #6b7280;\n line-height: 1;\n padding: 4px;\n }\n \n .widgetic-overlay-close:hover {\n color: #374151;\n }\n \n .widgetic-overlay-body {\n padding: 20px;\n }\n \n /* Fade animation (default) */\n .widgetic-overlay-fade .widgetic-overlay-content {\n transform: scale(0.95);\n opacity: 0;\n }\n \n .widgetic-overlay-fade.widgetic-overlay-visible .widgetic-overlay-content {\n transform: scale(1);\n opacity: 1;\n }\n \n /* Slide animations */\n .widgetic-overlay-slide-up .widgetic-overlay-content {\n transform: translateY(50px);\n opacity: 0;\n }\n \n .widgetic-overlay-slide-up.widgetic-overlay-visible .widgetic-overlay-content {\n transform: translateY(0);\n opacity: 1;\n }\n \n .widgetic-overlay-slide-down .widgetic-overlay-content {\n transform: translateY(-50px);\n opacity: 0;\n }\n \n .widgetic-overlay-slide-down.widgetic-overlay-visible .widgetic-overlay-content {\n transform: translateY(0);\n opacity: 1;\n }\n \n .widgetic-overlay-slide-left .widgetic-overlay-content {\n transform: translateX(-50px);\n opacity: 0;\n }\n \n .widgetic-overlay-slide-left.widgetic-overlay-visible .widgetic-overlay-content {\n transform: translateX(0);\n opacity: 1;\n }\n \n .widgetic-overlay-slide-right .widgetic-overlay-content {\n transform: translateX(50px);\n opacity: 0;\n }\n \n .widgetic-overlay-slide-right.widgetic-overlay-visible .widgetic-overlay-content {\n transform: translateX(0);\n opacity: 1;\n }\n \n /* Zoom animation */\n .widgetic-overlay-zoom .widgetic-overlay-content {\n transform: scale(0.7);\n opacity: 0;\n }\n \n .widgetic-overlay-zoom.widgetic-overlay-visible .widgetic-overlay-content {\n transform: scale(1);\n opacity: 1;\n }\n \n /* Bounce animation */\n .widgetic-overlay-bounce .widgetic-overlay-content {\n transform: scale(0.3);\n opacity: 0;\n transition: all 0.5s cubic-bezier(0.68, -0.55, 0.265, 1.55);\n }\n \n .widgetic-overlay-bounce.widgetic-overlay-visible .widgetic-overlay-content {\n transform: scale(1);\n opacity: 1;\n }\n \n /* Mobile responsive */\n ${this.generateResponsiveCSS()}\n `,document.head.appendChild(t)}emitOverlayTrigger(e,t){"undefined"!=typeof window&&window.dispatchEvent(new CustomEvent("widgetic:overlay-trigger",{detail:{triggerType:e,data:t,timestamp:(new Date).toISOString()}}))}emitOverlayEvent(e,t){"undefined"!=typeof window&&window.dispatchEvent(new CustomEvent("widgetic:overlay-event",{detail:{eventType:e,data:t,timestamp:(new Date).toISOString()}}))}triggerOverlay(e,t={}){const i=Object.assign({displayMode:e,animation:p.DEFAULT_ANIMATION,delay:p.DEFAULT_DELAY_MS,content:"Default overlay content"},t);i.delay&&i.delay>0?setTimeout((()=>{this.showOverlay(i)}),i.delay):this.showOverlay(i)}isOverlayActive(){return null!==this.activeOverlay}updateConfig(t){this.config=Object.assign(Object.assign({},this.config),t),this.isEnabled=this.config.enabled,e.debug("OverlayManager config updated",{config:this.config})}destroy(){this.activeOverlay&&this.hideOverlay(),this.exitIntentListener&&document.removeEventListener("mouseleave",this.exitIntentListener),this.scrollListener&&window.removeEventListener("scroll",this.scrollListener),this.timeoutId&&clearTimeout(this.timeoutId),e.debug("OverlayManager destroyed")}}let v=null;function y(e){return v||(v=new u(e)),v}export{a as D,s as R,r as a,y as b,c as d,d as g};
|
|
1
|
+
import{l as e}from"./core.js";import{_ as t}from"./vendor.js";import{c as i}from"./advanced.js";import{d as n}from"./renderers.js";class s{constructor(e={}){this.options=e,this.resizeObserver=null,this.instances=new Map,this.debounceTimers=new Map,this.options=Object.assign({observeResize:!0,debounceMs:100,enableAdaptive:!0},e),this.options.observeResize&&"undefined"!=typeof ResizeObserver&&(this.resizeObserver=new ResizeObserver(this.handleResize.bind(this)))}registerWidget(t,i,n,s){const o={widgetId:t,element:i,container:n,config:s,originalWidth:s.width,originalHeight:s.height,aspectRatio:s.width/s.height,isObserving:!1};this.instances.set(t,o),this.applyResizeMode(o),this.resizeObserver&&this.options.observeResize&&(this.resizeObserver.observe(n),o.isObserving=!0),e.debug("Widget registered for resize handling",{widgetId:t,resizeMode:s.resize,originalSize:{width:s.width,height:s.height}})}unregisterWidget(t){const i=this.instances.get(t);if(!i)return;this.resizeObserver&&i.isObserving&&this.resizeObserver.unobserve(i.container);const n=this.debounceTimers.get(t);n&&(clearTimeout(n),this.debounceTimers.delete(t)),this.instances.delete(t),e.debug("Widget unregistered from resize handling",{widgetId:t})}static generateIframeCSS(e){const{resize:t,width:i,height:n,autoscale:s}=e;let o="";switch(t){case"fill-width":o=`\n width: 100% !important;\n height: ${n/i*100}vw !important;\n max-height: ${n}px !important;\n object-fit: ${s?"contain":"cover"};\n `;break;case"fill-height":o=`\n height: 100% !important;\n width: ${i/n*100}vh !important;\n max-width: ${i}px !important;\n object-fit: ${s?"contain":"cover"};\n `;break;case"fixed":default:o=`\n width: ${i}px !important;\n height: ${n}px !important;\n flex-shrink: 0;\n object-fit: cover;\n `;break;case"fixed-height":o=`\n width: 100% !important;\n height: ${n}px !important;\n object-fit: ${s?"contain":"cover"};\n `;break;case"fixed-width":o=`\n width: ${i}px !important;\n height: 100% !important;\n object-fit: ${s?"contain":"cover"};\n `;break;case"allow-scale-down":o=`\n max-width: ${i}px !important;\n max-height: ${n}px !important;\n width: 100% !important;\n height: auto !important;\n object-fit: contain;\n `;break;case"fill":o=`\n width: 100% !important;\n height: 100% !important;\n object-fit: ${s?"contain":"cover"};\n `}return o.trim()}applyResizeMode(t){const{element:i,container:n,config:s}=t,{resize:o,autoscale:r}=s,a=n.getBoundingClientRect(),l=a.width,d=a.height;let c,h;switch(o){case"fill-width":c=l,h=c/t.aspectRatio,r&&h>d&&(h=d,c=h*t.aspectRatio);break;case"fill-height":h=d,c=h*t.aspectRatio,r&&c>l&&(c=l,h=c/t.aspectRatio);break;case"fixed":default:c=t.originalWidth,h=t.originalHeight;break;case"fixed-height":c=l,h=t.originalHeight;break;case"fixed-width":c=t.originalWidth,h=d;break;case"allow-scale-down":const e=l/t.originalWidth,i=d/t.originalHeight,n=Math.min(1,Math.min(e,i));c=t.originalWidth*n,h=t.originalHeight*n;break;case"fill":c=l,h=d}this.setElementSize(i,c,h,s),this.options.enableAdaptive&&s.adaptive&&this.handleAdaptiveBreakpoint(t,l),e.debug("Resize mode applied",{widgetId:t.widgetId,resizeMode:o,containerSize:{width:l,height:d},newSize:{width:c,height:h}})}setElementSize(e,t,i,n){switch(e.style.width=`${Math.round(t)}px`,e.style.height=`${Math.round(i)}px`,n.resize){case"fill":case"fill-width":case"fill-height":e.style.objectFit=n.autoscale?"contain":"cover";break;default:e.style.objectFit="contain"}e.style.boxSizing="border-box",e.style.display="block"}handleAdaptiveBreakpoint(e,t){if(!e.config.adaptive)return;const i=t<=e.config.adaptive,n=e.element;i?(n.classList.add("widgetic-adaptive-mobile"),n.classList.remove("widgetic-adaptive-desktop"),n.style.maxWidth="100%",n.style.fontSize="14px"):(n.classList.add("widgetic-adaptive-desktop"),n.classList.remove("widgetic-adaptive-mobile"),n.style.fontSize="")}handleResize(e){for(const t of e){const e=t.target;for(const[t,i]of this.instances)if(i.container===e){const e=this.debounceTimers.get(t);e&&clearTimeout(e);const n=window.setTimeout((()=>{this.applyResizeMode(i),this.debounceTimers.delete(t)}),this.options.debounceMs);this.debounceTimers.set(t,n)}}}forceResize(e){const t=this.instances.get(e);t&&this.applyResizeMode(t)}forceResizeAll(){for(const e of this.instances.values())this.applyResizeMode(e)}cleanup(){for(const e of this.debounceTimers.values())clearTimeout(e);this.debounceTimers.clear(),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.instances.clear()}}let o=null;function r(e){return o||(o=new s(e)),o}class a{constructor(e={}){this.options=e,this.instances=new Map,this.widgetElements=new Map,this.widgetConfigs=new Map,this.fullscreenListeners=new Map,this.keyboardListeners=new Map,this.options=Object.assign({enableFullscreen:!0,enableOverlay:!0,enablePopup:!0,defaultOverlayZIndex:5e4,defaultPopupFeatures:"width=800,height=600,scrollbars=yes,resizable=yes"},e),this.setupGlobalKeyHandlers()}initializeWidget(e,t,i){const n={mode:t.displayMode||"inline",isFullscreen:!1,isOverlay:!1,isPopup:!1};return this.instances.set(e,n),this.widgetElements.set(e,i),this.widgetConfigs.set(e,t),this.setupDisplayMode(e,t,i),n}setupDisplayMode(e,t,i){const{displayMode:n}=t;switch(n){case"fullscreen":this.setupFullscreenMode(e,t,i);break;case"overlay":case"modal":this.setupOverlayMode(e,t,i);break;case"popup":this.setupPopupMode(e,t,i)}}setupFullscreenMode(e,t,i){var n;if(!this.options.enableFullscreen||!(null===(n=t.fullscreen)||void 0===n?void 0:n.enabled))return;const s=t.fullscreen.trigger||"click";"manual"!==s&&this.addFullscreenTrigger(e,i,s),t.fullscreen.showControls&&this.addFullscreenControls(e,i)}setupOverlayMode(e,t,i){var n;if(!this.options.enableOverlay||!(null===(n=t.overlay)||void 0===n?void 0:n.enabled))return;const s=t.overlay.trigger||"click";"auto"===s?setTimeout((()=>this.showOverlay(e)),100):"manual"!==s&&this.addOverlayTrigger(e,i,s)}setupPopupMode(e,t,i){var n;if(!this.options.enablePopup||!(null===(n=t.popup)||void 0===n?void 0:n.enabled))return;const s=t.popup.trigger||"click";"manual"!==s&&this.addPopupTrigger(e,i,s)}enterFullscreen(n){return t(this,void 0,void 0,(function*(){const t=this.instances.get(n);if(t&&!t.isFullscreen)try{const s=this.getWidgetElement(n);if(!s)throw new Error(`Widget element not found: ${n}`);const o=i({target:"widgetic-fullscreen",zIndex:100001,className:"fullscreen-widget"}),r=document.createElement("div");r.className="widgetic-fullscreen-container",r.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n background: #000;\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: 100001;\n ",t.originalStyle=s.style.cssText;const a=document.createComment(`widgetic-fullscreen-placeholder-${n}`);s.parentNode&&(s.parentNode.replaceChild(a,s),t.originalPlaceholder=a),s.style.cssText="\n width: 100%;\n height: 100%;\n max-width: 100vw;\n max-height: 100vh;\n border: none;\n ",r.appendChild(s);const l=this.createExitButton((()=>this.exitFullscreen(n)));if(r.appendChild(l),o.mount(r),t.isFullscreen=!0,t.overlayPortal=o,t.fullscreenElement=r,this.setupFullscreenKeyHandler(n),document.documentElement.requestFullscreen)try{yield document.documentElement.requestFullscreen()}catch(t){e.warn("Native fullscreen failed, using CSS fullscreen",{error:t})}e.info("Widget entered fullscreen mode",{widgetId:n})}catch(t){throw e.error("Failed to enter fullscreen",{widgetId:n,error:t}),t}}))}exitFullscreen(i){return t(this,void 0,void 0,(function*(){const t=this.instances.get(i);if(t&&t.isFullscreen)try{const n=this.getWidgetElement(i);n&&t.originalPlaceholder&&t.originalPlaceholder.parentNode&&(t.originalPlaceholder.parentNode.replaceChild(n,t.originalPlaceholder),t.originalPlaceholder=void 0,void 0!==t.originalStyle&&(n.style.cssText=t.originalStyle,t.originalStyle=void 0)),t.overlayPortal&&t.overlayPortal.destroy(),document.fullscreenElement&&document.exitFullscreen&&(yield document.exitFullscreen()),t.isFullscreen=!1,t.overlayPortal=void 0,t.fullscreenElement=void 0,this.removeFullscreenKeyHandler(i),e.info("Widget exited fullscreen mode",{widgetId:i})}catch(t){throw e.error("Failed to exit fullscreen",{widgetId:i,error:t}),t}}))}showOverlay(n){return t(this,void 0,void 0,(function*(){const t=this.instances.get(n);if(t&&!t.isOverlay)try{const s=this.getWidgetConfig(n),o=null==s?void 0:s.overlay;if(!o)throw new Error(`No overlay configuration for widget: ${n}`);const r=i({target:"widgetic-overlay",zIndex:o.zIndex||this.options.defaultOverlayZIndex,className:"overlay-widget"}),a=this.createOverlayContainer(n,o),l=this.getWidgetElement(n);if(l){t.originalStyle=l.style.cssText;const e=document.createComment(`widgetic-overlay-placeholder-${n}`);l.parentNode&&(l.parentNode.replaceChild(e,l),t.originalPlaceholder=e),this.styleOverlayWidget(l,o);a.querySelector(".overlay-content").appendChild(l)}r.mount(a),t.isOverlay=!0,t.overlayPortal=r,this.setupOverlayCloseHandlers(n,a,o),e.info("Widget shown in overlay mode",{widgetId:n})}catch(t){throw e.error("Failed to show overlay",{widgetId:n,error:t}),t}}))}hideOverlay(i){return t(this,void 0,void 0,(function*(){const t=this.instances.get(i);if(t&&t.isOverlay)try{const n=this.getWidgetElement(i);n&&t.originalPlaceholder&&t.originalPlaceholder.parentNode&&(t.originalPlaceholder.parentNode.replaceChild(n,t.originalPlaceholder),t.originalPlaceholder=void 0,void 0!==t.originalStyle&&(n.style.cssText=t.originalStyle,t.originalStyle=void 0)),t.overlayPortal&&t.overlayPortal.destroy(),t.isOverlay=!1,t.overlayPortal=void 0,this.removeOverlayKeyHandler(i),e.info("Widget overlay hidden",{widgetId:i})}catch(t){throw e.error("Failed to hide overlay",{widgetId:i,error:t}),t}}))}openPopup(i){return t(this,void 0,void 0,(function*(){const t=this.instances.get(i);if(!t||t.isPopup)return(null==t?void 0:t.popupWindow)||null;try{const n=this.getWidgetConfig(i),s=null==n?void 0:n.popup;if(!s)throw new Error(`No popup configuration for widget: ${i}`);const o=this.buildPopupFeatures(s),r=this.generatePopupUrl(i),a=window.open(r,s.target||`widgetic_${i}`,o);if(!a)throw new Error("Popup blocked by browser");return t.isPopup=!0,t.popupWindow=a,this.monitorPopupClose(i,a),e.info("Widget opened in popup",{widgetId:i}),a}catch(t){throw e.error("Failed to open popup",{widgetId:i,error:t}),t}}))}closePopup(t){const i=this.instances.get(t);if(i&&i.isPopup&&i.popupWindow)try{i.popupWindow.close(),i.isPopup=!1,i.popupWindow=null,e.info("Widget popup closed",{widgetId:t})}catch(i){e.error("Failed to close popup",{widgetId:t,error:i})}}getDisplayState(e){return this.instances.get(e)||null}cleanup(e){const t=this.instances.get(e);t&&(t.isFullscreen&&this.exitFullscreen(e),t.isOverlay&&this.hideOverlay(e),t.isPopup&&this.closePopup(e),this.instances.delete(e),this.removeFullscreenKeyHandler(e),this.removeOverlayKeyHandler(e))}cleanupAll(){for(const e of this.instances.keys())this.cleanup(e)}getWidgetElement(e){return this.widgetElements.has(e)?this.widgetElements.get(e):document.querySelector(`[data-widget-id="${e}"]`)||document.querySelector(`[data-widgetic-id="${e}"]`)||document.querySelector(`[composition-id="${e}"]`)||null}getWidgetConfig(e){return this.widgetConfigs.get(e)||null}addFullscreenTrigger(e,t,i){const n=()=>this.enterFullscreen(e);switch(i){case"click":t.addEventListener("click",n);break;case"double-click":t.addEventListener("dblclick",n);break;case"hover":t.addEventListener("mouseenter",n)}}addOverlayTrigger(e,t,i){const n=()=>this.showOverlay(e);switch(i){case"click":t.addEventListener("click",n);break;case"hover":t.addEventListener("mouseenter",n)}}addPopupTrigger(e,t,i){const n=()=>this.openPopup(e);"click"===i&&t.addEventListener("click",n)}createExitButton(e){const t=document.createElement("button");return t.className="widgetic-exit-fullscreen",t.innerHTML="✕",t.setAttribute("aria-label",n("close")),t.style.cssText="\n position: absolute;\n top: 20px;\n right: 20px;\n background: rgba(0, 0, 0, 0.7);\n color: white;\n border: none;\n border-radius: 50%;\n width: 40px;\n height: 40px;\n font-size: 20px;\n cursor: pointer;\n z-index: 100002;\n ",t.addEventListener("click",e),t}createOverlayContainer(e,t){const i=document.createElement("div");i.className="widgetic-overlay-container",i.style.cssText=`\n position: fixed;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n display: flex;\n align-items: center;\n justify-content: center;\n background: ${t.backdrop?"rgba(0, 0, 0, 0.8)":"transparent"};\n `;const n=document.createElement("div");if(n.className="overlay-content",n.style.cssText=`\n max-width: ${t.maxWidth||"90vw"};\n max-height: ${t.maxHeight||"90vh"};\n background: white;\n border-radius: 8px;\n overflow: hidden;\n position: relative;\n `,t.showCloseButton){const t=this.createExitButton((()=>this.hideOverlay(e)));n.appendChild(t)}return i.appendChild(n),i}styleOverlayWidget(e,t){const i="mixed"===t.embedTarget&&!t.keepDimensions;let n=t.width||"100%",s=t.height||"100%";i&&(t.overlayWidth||t.overlayHeight)&&(n=t.overlayWidth||n,s=t.overlayHeight||s),e.style.cssText=`\n width: ${n};\n height: ${s};\n border: none;\n display: block;\n `,i&&t.overlayResize&&this.applyOverlayResizeMode(e,t.overlayResize)}applyOverlayResizeMode(e,t){if(e.parentElement)switch(t){case"fill-width":e.style.width="100%",e.style.height="auto",e.style.aspectRatio="auto";break;case"fill-height":e.style.height="100%",e.style.width="auto",e.style.aspectRatio="auto";break;case"fixed":e.style.flexShrink="0";break;case"fixed-height":e.style.width="100%";break;case"fixed-width":e.style.height="100%";break;case"allow-scale-down":e.style.maxWidth="100%",e.style.maxHeight="100%",e.style.objectFit="contain";break;case"fill":e.style.width="100%",e.style.height="100%",e.style.objectFit="cover"}}buildPopupFeatures(e){const t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.centerScreen&&t.push("location=center"),e.allowResize&&t.push("resizable=yes"),e.showToolbar&&t.push("toolbar=yes"),t.length>0?t.join(","):this.options.defaultPopupFeatures||""}generatePopupUrl(e){return"about:blank"}setupGlobalKeyHandlers(){"undefined"!=typeof document&&document.addEventListener("keydown",(e=>{if("Escape"===e.key)for(const[e,t]of this.instances)t.isFullscreen?this.exitFullscreen(e):t.isOverlay&&this.hideOverlay(e)}))}setupFullscreenKeyHandler(e){const t=t=>{"Escape"===t.key&&this.exitFullscreen(e)};this.keyboardListeners.set(`${e}-fullscreen`,t),document.addEventListener("keydown",t)}removeFullscreenKeyHandler(e){const t=this.keyboardListeners.get(`${e}-fullscreen`);t&&(document.removeEventListener("keydown",t),this.keyboardListeners.delete(`${e}-fullscreen`))}setupOverlayCloseHandlers(e,t,i){if(i.closeOnBackdropClick&&t.addEventListener("click",(i=>{i.target===t&&this.hideOverlay(e)})),i.closeOnEscape){const t=t=>{"Escape"===t.key&&this.hideOverlay(e)};this.keyboardListeners.set(`${e}-overlay`,t),document.addEventListener("keydown",t)}}removeOverlayKeyHandler(e){const t=this.keyboardListeners.get(`${e}-overlay`);t&&(document.removeEventListener("keydown",t),this.keyboardListeners.delete(`${e}-overlay`))}monitorPopupClose(e,t){const i=()=>{if(t.closed){const t=this.instances.get(e);t&&(t.isPopup=!1,t.popupWindow=null)}else setTimeout(i,1e3)};setTimeout(i,1e3)}addFullscreenControls(e,t){const i=document.createElement("div");i.className="widgetic-fullscreen-controls",i.style.cssText="\n position: absolute;\n bottom: 10px;\n right: 10px;\n background: rgba(0, 0, 0, 0.7);\n border-radius: 4px;\n padding: 5px;\n z-index: 1000;\n ";const n=document.createElement("button");n.innerHTML="⛶",n.style.cssText="\n background: none;\n border: none;\n color: white;\n cursor: pointer;\n font-size: 16px;\n ",n.addEventListener("click",(()=>this.enterFullscreen(e))),i.appendChild(n),t.style.position="relative",t.appendChild(i)}}let l=null;function d(e){return l||(l=new a(e)),l}var c=Object.freeze({__proto__:null,DisplayManager:a,getDisplayManager:d,resetDisplayManager:function(){l&&(l.cleanupAll(),l=null)}});const h={mobile:480,tablet:768,desktop:1024},g={MANUAL:"manual",EXIT_INTENT:"exit-intent",ON_SCROLL:"on-scroll",TIME_DELAY:"time-delay",ENGAGEMENT_THRESHOLD:"engagement",EXTERNAL_TRIGGER:"external"},p={DEFAULT_ANIMATION:"fade",DEFAULT_DELAY_MS:1e3,SUPPORTED_ANIMATIONS:["fade","slide-up","slide-down","slide-left","slide-right","zoom","bounce"]};class u{constructor(t={enabled:!0}){var i;this.isEnabled=!1,this.activeOverlay=null,this.exitIntentListener=null,this.scrollListener=null,this.engagementStartTime=null,this.timeoutId=null,this.config=Object.assign(Object.assign({exitIntentEnabled:!0,scrollTriggerEnabled:!0,timeTriggerEnabled:!0,engagementThresholdEnabled:!0,externalTriggerEnabled:!0},t),{enabled:null===(i=t.enabled)||void 0===i||i}),this.config.breakpoints||(this.config.breakpoints={useBreakpoints:!1,mobile:h.mobile,tablet:h.tablet,desktop:h.desktop}),this.isEnabled=this.config.enabled,this.isEnabled&&this.initializeEventListeners(),e.debug("OverlayManager initialized",{config:this.config})}initializeEventListeners(){"undefined"!=typeof window&&(this.config.exitIntentEnabled&&this.initializeExitIntent(),this.config.scrollTriggerEnabled&&this.initializeScrollTrigger(),this.config.engagementThresholdEnabled&&this.startEngagementTracking())}initializeExitIntent(){"undefined"!=typeof document&&(this.exitIntentListener=e=>{e.clientY<=0&&e.movementY<0&&this.emitOverlayTrigger("exit-intent",{mousePosition:{x:e.clientX,y:e.clientY},movementY:e.movementY})},document.addEventListener("mouseleave",this.exitIntentListener))}initializeScrollTrigger(){"undefined"!=typeof window&&(this.scrollListener=()=>{const e=window.scrollY/(document.documentElement.scrollHeight-window.innerHeight)*100;e>=25&&e<30?this.emitOverlayTrigger("scroll-25",{scrollPercentage:e}):e>=50&&e<55?this.emitOverlayTrigger("scroll-50",{scrollPercentage:e}):e>=75&&e<80&&this.emitOverlayTrigger("scroll-75",{scrollPercentage:e})},window.addEventListener("scroll",this.scrollListener,{passive:!0}))}startEngagementTracking(){this.engagementStartTime=Date.now();setInterval((()=>{if(!this.engagementStartTime)return;const e=Date.now()-this.engagementStartTime;e>=3e4?this.emitOverlayTrigger("engagement-30s",{engagementTimeMs:e}):e>=6e4?this.emitOverlayTrigger("engagement-1m",{engagementTimeMs:e}):e>=12e4&&this.emitOverlayTrigger("engagement-2m",{engagementTimeMs:e})}),1e4)}showOverlay(t){if(this.isEnabled){this.activeOverlay&&(e.debug("Overlay already active, closing previous"),this.hideOverlay());try{const i=this.validateOverlayConfig(t),n=this.createOverlayElement(i);document.body.appendChild(n),this.activeOverlay=n,setTimeout((()=>{n.classList.add("widgetic-overlay-visible")}),50),i.autoClose&&i.autoClose>0&&(this.timeoutId=window.setTimeout((()=>{this.hideOverlay()}),i.autoClose)),e.info("Overlay displayed",{displayMode:i.displayMode,animation:i.animation,autoClose:i.autoClose}),this.emitOverlayEvent("overlay-shown",i)}catch(i){e.error("Failed to show overlay",{error:i,config:t})}}else e.warn("Overlay manager is disabled")}validateOverlayConfig(t){const i=Object.assign({},t);return i.displayMode&&Object.values(g).includes(i.displayMode)||(i.displayMode=g.MANUAL),i.animation&&p.SUPPORTED_ANIMATIONS.includes(i.animation)||(i.animation=p.DEFAULT_ANIMATION,e.debug("Using default animation for overlay",{provided:t.animation,defaultUsed:p.DEFAULT_ANIMATION})),i.delay||(i.delay=p.DEFAULT_DELAY_MS),void 0===i.showBackdrop&&(i.showBackdrop=!0),i}hideOverlay(){if(!this.activeOverlay)return;this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null);const t=this.activeOverlay;t.classList.remove("widgetic-overlay-visible"),t.classList.add("widgetic-overlay-hiding"),setTimeout((()=>{t.parentNode&&t.parentNode.removeChild(t)}),300),this.activeOverlay=null,e.debug("Overlay hidden"),this.emitOverlayEvent("overlay-hidden",{})}createOverlayElement(e){const t=document.createElement("div");t.className=`widgetic-overlay widgetic-overlay-${e.animation||p.DEFAULT_ANIMATION}`,!1!==e.showBackdrop&&t.classList.add("widgetic-overlay-backdrop"),t.innerHTML=`\n <div class="widgetic-overlay-content">\n <button class="widgetic-overlay-close">×</button>\n <div class="widgetic-overlay-body">\n ${e.content}\n </div>\n </div>\n `,this.addOverlayStyles();const i=t.querySelector(".widgetic-overlay-close");i&&(i.setAttribute("aria-label",n("close")),i.addEventListener("click",(()=>this.hideOverlay()))),t.addEventListener("click",(i=>{i.target===t&&!1!==e.showBackdrop&&this.hideOverlay()}));const s=e=>{"Escape"===e.key&&(this.hideOverlay(),document.removeEventListener("keydown",s))};return document.addEventListener("keydown",s),t}generateResponsiveCSS(){const e=this.config.breakpoints;if(!e||!e.useBreakpoints)return"/* No mobile responsive styles - breakpoints disabled */";const t=e.mobile||h.mobile;return`\n /* Mobile responsive styles */\n @media (max-width: ${t}px) {\n .widgetic-overlay-content {\n max-width: 95vw;\n margin: 10px;\n }\n \n .widgetic-overlay-body {\n padding: 15px;\n }\n }\n \n /* Tablet responsive styles */\n @media (min-width: ${t+1}px) and (max-width: ${e.tablet||h.tablet}px) {\n .widgetic-overlay-content {\n max-width: 90vw;\n margin: 15px;\n }\n \n .widgetic-overlay-body {\n padding: 18px;\n }\n }\n `}addOverlayStyles(){const e="widgetic-overlay-styles";if(document.getElementById(e))return;const t=document.createElement("style");t.id=e,t.textContent=`\n .widgetic-overlay {\n position: fixed;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n z-index: 10000;\n display: flex;\n align-items: center;\n justify-content: center;\n opacity: 0;\n transition: opacity 0.3s ease;\n }\n \n .widgetic-overlay-backdrop {\n background: rgba(0, 0, 0, 0.5);\n }\n \n .widgetic-overlay-visible {\n opacity: 1;\n }\n \n .widgetic-overlay-hiding {\n opacity: 0;\n }\n \n .widgetic-overlay-content {\n position: relative;\n background: white;\n border-radius: 8px;\n max-width: 90vw;\n max-height: 90vh;\n overflow: auto;\n transition: all 0.3s ease;\n }\n \n .widgetic-overlay-close {\n position: absolute;\n top: 10px;\n right: 15px;\n background: none;\n border: none;\n font-size: 24px;\n cursor: pointer;\n z-index: 1;\n color: #6b7280;\n line-height: 1;\n padding: 4px;\n }\n \n .widgetic-overlay-close:hover {\n color: #374151;\n }\n \n .widgetic-overlay-body {\n padding: 20px;\n }\n \n /* Fade animation (default) */\n .widgetic-overlay-fade .widgetic-overlay-content {\n transform: scale(0.95);\n opacity: 0;\n }\n \n .widgetic-overlay-fade.widgetic-overlay-visible .widgetic-overlay-content {\n transform: scale(1);\n opacity: 1;\n }\n \n /* Slide animations */\n .widgetic-overlay-slide-up .widgetic-overlay-content {\n transform: translateY(50px);\n opacity: 0;\n }\n \n .widgetic-overlay-slide-up.widgetic-overlay-visible .widgetic-overlay-content {\n transform: translateY(0);\n opacity: 1;\n }\n \n .widgetic-overlay-slide-down .widgetic-overlay-content {\n transform: translateY(-50px);\n opacity: 0;\n }\n \n .widgetic-overlay-slide-down.widgetic-overlay-visible .widgetic-overlay-content {\n transform: translateY(0);\n opacity: 1;\n }\n \n .widgetic-overlay-slide-left .widgetic-overlay-content {\n transform: translateX(-50px);\n opacity: 0;\n }\n \n .widgetic-overlay-slide-left.widgetic-overlay-visible .widgetic-overlay-content {\n transform: translateX(0);\n opacity: 1;\n }\n \n .widgetic-overlay-slide-right .widgetic-overlay-content {\n transform: translateX(50px);\n opacity: 0;\n }\n \n .widgetic-overlay-slide-right.widgetic-overlay-visible .widgetic-overlay-content {\n transform: translateX(0);\n opacity: 1;\n }\n \n /* Zoom animation */\n .widgetic-overlay-zoom .widgetic-overlay-content {\n transform: scale(0.7);\n opacity: 0;\n }\n \n .widgetic-overlay-zoom.widgetic-overlay-visible .widgetic-overlay-content {\n transform: scale(1);\n opacity: 1;\n }\n \n /* Bounce animation */\n .widgetic-overlay-bounce .widgetic-overlay-content {\n transform: scale(0.3);\n opacity: 0;\n transition: all 0.5s cubic-bezier(0.68, -0.55, 0.265, 1.55);\n }\n \n .widgetic-overlay-bounce.widgetic-overlay-visible .widgetic-overlay-content {\n transform: scale(1);\n opacity: 1;\n }\n \n /* Mobile responsive */\n ${this.generateResponsiveCSS()}\n `,document.head.appendChild(t)}emitOverlayTrigger(e,t){"undefined"!=typeof window&&window.dispatchEvent(new CustomEvent("widgetic:overlay-trigger",{detail:{triggerType:e,data:t,timestamp:(new Date).toISOString()}}))}emitOverlayEvent(e,t){"undefined"!=typeof window&&window.dispatchEvent(new CustomEvent("widgetic:overlay-event",{detail:{eventType:e,data:t,timestamp:(new Date).toISOString()}}))}triggerOverlay(e,t={}){const i=Object.assign({displayMode:e,animation:p.DEFAULT_ANIMATION,delay:p.DEFAULT_DELAY_MS,content:"Default overlay content"},t);i.delay&&i.delay>0?setTimeout((()=>{this.showOverlay(i)}),i.delay):this.showOverlay(i)}isOverlayActive(){return null!==this.activeOverlay}updateConfig(t){this.config=Object.assign(Object.assign({},this.config),t),this.isEnabled=this.config.enabled,e.debug("OverlayManager config updated",{config:this.config})}destroy(){this.activeOverlay&&this.hideOverlay(),this.exitIntentListener&&document.removeEventListener("mouseleave",this.exitIntentListener),this.scrollListener&&window.removeEventListener("scroll",this.scrollListener),this.timeoutId&&clearTimeout(this.timeoutId),e.debug("OverlayManager destroyed")}}let v=null;function y(e){return v||(v=new u(e)),v}export{a as D,s as R,r as a,y as b,c as d,d as g};
|
package/dist/esm/chunks/media.js
CHANGED
|
@@ -1 +1 @@
|
|
|
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.pausedByManagerAt=new Map,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;this.pausedByManagerAt.delete(t);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={}){var s;const o="playing"===(null===(s=this.playingWidgets.get(t))||void 0===s?void 0:s.state),a=!0===(null==i?void 0:i.playing)?"playing":"paused",n=this.getOrCreateMediaState(t,e,a,i),l="number"==typeof(null==i?void 0:i.position)?i.position:null==i?void 0:i.currentTime;"number"==typeof l&&(n.position=l),"number"==typeof(null==i?void 0:i.duration)&&Number.isFinite(i.duration)&&(n.duration=i.duration),"number"==typeof(null==i?void 0:i.volume)&&(n.volume=i.volume);const d=!0===(null==i?void 0:i.playing)||"boolean"!=typeof(null==i?void 0:i.playing)&&"playing"===(null==i?void 0:i.state),u=!1===(null==i?void 0:i.playing)||"paused"===(null==i?void 0:i.state)||"stopped"===(null==i?void 0:i.state);if(d){const i=this.pausedByManagerAt.get(t);i&&Date.now()-i<500?(n.state="paused",this.sendPauseCommand(t,void 0,!1)):(n.state="playing",o||!1===e.autoPause||this.pauseConflictingWidgets(t,n.mediaType,n.priority,e.allowSimultaneous||[]))}else u&&(n.state="stopped"===(null==i?void 0:i.state)?"stopped":"paused");(null==i?void 0:i.title)&&(n.title=i.title),(null==i?void 0:i.playlist)&&(n.playlist=Object.assign(Object.assign({},n.playlist),i.playlist)),n.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}:{});if(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)){const o="playing"===s.state;s.state=e.playing?"playing":"paused",e.playing&&(this.pausedByManagerAt.delete(t),o||!1===i.autoPause||this.pauseConflictingWidgets(t,s.mediaType,s.priority,i.allowSimultaneous||[]))}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[i,a]of this.playingWidgets){if(i===t||"playing"!==a.state)continue;this.isSimultaneousAllowed(a.mediaType,e,s)||o.push(i)}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)))}resolveHostElements(t){if("undefined"==typeof document)return[];const e=[`[data-widgetic-id="${t}"]`,`[data-composition-id="${t}"]`,`[composition-id="${t}"]`,`[compositionid="${t}"]`,`[composition="${t}"]`,`widgetic[composition-id="${t}"]`,`[widget="${t}"]`,`[widget-id="${t}"]`,`[widgetid="${t}"]`,`[data-widget-id="${t}"]`,`widgetic[widget="${t}"]`,`widgetic[widget-id="${t}"]`].join(", ");return Array.from(document.querySelectorAll(e))}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.resolveHostElements(t);if(0===s.length)return!1;for(const t of s){const s="iframe"===t.tagName.toLowerCase()?t:t.querySelector("iframe");if(null==s?void 0:s.contentWindow){const t=this.resolveIframeTargetOrigin(s);try{s.contentWindow.postMessage(e,t)}catch(t){try{s.contentWindow.postMessage(e,"*")}catch(t){}}}t.dispatchEvent(new CustomEvent("widgetic:media:command",{detail:e}));const o=t.querySelector("[data-widgetic-direct]"),a=null===(i=null==o?void 0:o.shadowRoot)||void 0===i?void 0:i.querySelector(".widgetic-direct-target");a&&a.dispatchEvent(new CustomEvent("widgetic:media:command",{detail:e,bubbles:!0,composed:!0}))}return!0}sendPauseCommand(t,e,i=!0){if(i){this.pausedByManagerAt.set(t,Date.now());const e=this.playingWidgets.get(t);e&&(e.state="paused")}this.dispatchCommandToHostAndIframe(t,Object.assign({type:"widgetic:media:command",command:"pause",compositionId:t},"number"==typeof e?{position:e}:{}))}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(){var t;if("undefined"!=typeof localStorage)try{const e=localStorage.getItem(this.storageKey);if(e){const i=JSON.parse(e);if(i.version!==this.storageVersion)return void this.clearPersistedState();const s=864e5;if(i.timestamp&&Date.now()-i.timestamp>s)return void this.clearPersistedState();const o=[];for(const[t,e]of Object.entries(i.playingWidgets||{})){const t=e;t.compositionId&&t.mediaType&&t.state&&o.push(t)}const a=null===(t=o.filter((t=>"playing"===t.state)).sort(((t,e)=>{const i=t.lastInteraction||t.startedAt||0,s=e.lastInteraction||e.startedAt||0;return s!==i?s-i:(e.priority||5)-(t.priority||5)}))[0])||void 0===t?void 0:t.compositionId;for(const t of o)"playing"===t.state&&t.compositionId!==a&&(t.state="paused"),this.playingWidgets.set(t.compositionId,t)}}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);if(!e)return!1;if("playing"===e.state){this.pausedByManagerAt.delete(t);const i=this.widgetConfigs.get(t);!1!==(null==i?void 0:i.autoPause)&&this.pauseConflictingWidgets(t,e.mediaType,e.priority,(null==i?void 0:i.allowSimultaneous)||[])}return this.sendRestoreStateCommand(t,e),"playing"===e.state?setTimeout((()=>{var i;"playing"===(null===(i=this.playingWidgets.get(t))||void 0===i?void 0:i.state)&&this.sendPlayCommand(t,e.position)}),100):"paused"===e.state&&setTimeout((()=>{var i;"playing"!==(null===(i=this.playingWidgets.get(t))||void 0===i?void 0:i.state)&&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,y=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,v={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:y};this.contentStates.set(t,v)}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
|
+
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.pausedByManagerAt=new Map,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;this.pausedByManagerAt.delete(t);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={}){var s;const o="playing"===(null===(s=this.playingWidgets.get(t))||void 0===s?void 0:s.state),a=!0===(null==i?void 0:i.playing)?"playing":"paused",n=this.getOrCreateMediaState(t,e,a,i),l="number"==typeof(null==i?void 0:i.position)?i.position:null==i?void 0:i.currentTime;"number"==typeof l&&(n.position=l),"number"==typeof(null==i?void 0:i.duration)&&Number.isFinite(i.duration)&&(n.duration=i.duration),"number"==typeof(null==i?void 0:i.volume)&&(n.volume=i.volume);const d=!0===(null==i?void 0:i.playing)||"boolean"!=typeof(null==i?void 0:i.playing)&&"playing"===(null==i?void 0:i.state),u=!1===(null==i?void 0:i.playing)||"paused"===(null==i?void 0:i.state)||"stopped"===(null==i?void 0:i.state);if(d){const i=this.pausedByManagerAt.get(t);i&&Date.now()-i<500?(n.state="paused",this.sendPauseCommand(t,void 0,!1)):(n.state="playing",o||!1===e.autoPause||this.pauseConflictingWidgets(t,n.mediaType,n.priority,e.allowSimultaneous||[]))}else u&&(n.state="stopped"===(null==i?void 0:i.state)?"stopped":"paused");(null==i?void 0:i.title)&&(n.title=i.title),(null==i?void 0:i.playlist)&&(n.playlist=Object.assign(Object.assign({},n.playlist),i.playlist)),n.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}:{});if(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)){const o="playing"===s.state;s.state=e.playing?"playing":"paused",e.playing&&(this.pausedByManagerAt.delete(t),o||!1===i.autoPause||this.pauseConflictingWidgets(t,s.mediaType,s.priority,i.allowSimultaneous||[]))}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[i,a]of this.playingWidgets){if(i===t||"playing"!==a.state)continue;this.isSimultaneousAllowed(a.mediaType,e,s)||o.push(i)}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)))}resolveHostElements(t){if("undefined"==typeof document)return[];const e=[`[data-widgetic-id="${t}"]`,`[data-composition-id="${t}"]`,`[composition-id="${t}"]`,`[compositionid="${t}"]`,`[composition="${t}"]`,`widgetic[composition-id="${t}"]`,`[widget="${t}"]`,`[widget-id="${t}"]`,`[widgetid="${t}"]`,`[data-widget-id="${t}"]`,`widgetic[widget="${t}"]`,`widgetic[widget-id="${t}"]`].join(", ");return Array.from(document.querySelectorAll(e))}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.resolveHostElements(t);if(0===s.length)return!1;for(const t of s){const s="iframe"===t.tagName.toLowerCase()?t:t.querySelector("iframe");if(null==s?void 0:s.contentWindow){const t=this.resolveIframeTargetOrigin(s);try{s.contentWindow.postMessage(e,t)}catch(t){try{s.contentWindow.postMessage(e,"*")}catch(t){}}}t.dispatchEvent(new CustomEvent("widgetic:media:command",{detail:e}));const o=t.querySelector("[data-widgetic-direct]"),a=null===(i=null==o?void 0:o.shadowRoot)||void 0===i?void 0:i.querySelector(".widgetic-direct-target");a&&a.dispatchEvent(new CustomEvent("widgetic:media:command",{detail:e,bubbles:!0,composed:!0}))}return!0}sendPauseCommand(t,e,i=!0){if(i){this.pausedByManagerAt.set(t,Date.now());const e=this.playingWidgets.get(t);e&&(e.state="paused")}this.dispatchCommandToHostAndIframe(t,Object.assign({type:"widgetic:media:command",command:"pause",compositionId:t},"number"==typeof e?{position:e}:{}))}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(){var t;if("undefined"!=typeof localStorage)try{const e=localStorage.getItem(this.storageKey);if(e){const i=JSON.parse(e);if(i.version!==this.storageVersion)return void this.clearPersistedState();const s=864e5;if(i.timestamp&&Date.now()-i.timestamp>s)return void this.clearPersistedState();const o=[];for(const[t,e]of Object.entries(i.playingWidgets||{})){const t=e;t.compositionId&&t.mediaType&&t.state&&o.push(t)}const a=null===(t=o.filter((t=>"playing"===t.state)).sort(((t,e)=>{const i=t.lastInteraction||t.startedAt||0,s=e.lastInteraction||e.startedAt||0;return s!==i?s-i:(e.priority||5)-(t.priority||5)}))[0])||void 0===t?void 0:t.compositionId;for(const t of o)"playing"===t.state&&t.compositionId!==a&&(t.state="paused"),this.playingWidgets.set(t.compositionId,t)}}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)||{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);if(!e)return!1;if("playing"===e.state){this.pausedByManagerAt.delete(t);const i=this.widgetConfigs.get(t);!1!==(null==i?void 0:i.autoPause)&&this.pauseConflictingWidgets(t,e.mediaType,e.priority,(null==i?void 0:i.allowSimultaneous)||[])}return this.sendRestoreStateCommand(t,e),"playing"===e.state?setTimeout((()=>{var i;"playing"===(null===(i=this.playingWidgets.get(t))||void 0===i?void 0:i.state)&&this.sendPlayCommand(t,e.position)}),100):"paused"===e.state&&setTimeout((()=>{var i;"playing"!==(null===(i=this.playingWidgets.get(t))||void 0===i?void 0:i.state)&&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,y=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,v={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:y};this.contentStates.set(t,v)}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"./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
|
+
import{_ as e}from"./vendor.js";import{l as t,d as s}from"./core.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};
|