@widgetic/embed-sdk 2.0.8 → 2.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import{_ as e}from"./vendor.js";import{Configuration as t,TokensApi as n}from"@widgetic/api-sdk";const i="https://api.axiom.co/v1",o="widgetic-performance",r="https://events.statsigapi.net/v1/custom",s=!0,a=1,c=1e3,h="",u=2500,d=2e3,l=100,T=50,E=.1,p=.05,_=1800,k=1200,A=800,f=600,v=3e3,g=2e3,R=5e5,I=3e5,O="50px",y=.1,N=3,P=3,D=1e3,L=10,S=5e3,C=36e5,K=6,w=!0,U=!0,b=!1,m="info",x="2.0.3",H="2.0.3";function F(){var e;return`${"undefined"!=typeof process&&"development"===(null===(e={NODE_ENV:"production"})||void 0===e?void 0:e.NODE_ENV)?M.DEV_API_URL:M.PROD_API_URL}${M.VERSION}`}const M={DEV_API_URL:"http://localhost:3000",PROD_API_URL:"https://api.widgetic.com",PROD_CLIENT_URL:"https://widgetic.com",PROD_CDN_URL:"https://cdn.widgetic.com",VERSION:"/api/v1",ENABLE_EDITING:!0},V="auto",G="inline",B="fixed",Y=350,$=200,W=!1,j={CUSTOM_ELEMENTS:"undefined"!=typeof customElements,HTTP3:!1,RESIZE_OBSERVER:"undefined"!=typeof ResizeObserver},X=10,z=5e3,Z=3;let J=b;const q={get enabled(){return J},logLevel:m},Q=["apikey","api_key","api-key","servicekey","service_key","service-key","token","access_token","auth_token","secret","password","private_key","authorization","bearer","internal_key","public_api_key","public_internal_key"];function ee(e){if("string"==typeof e){const t=e.toLowerCase();for(const n of Q)if(t.includes(n))return e.replace(/([a-zA-Z_-]*(?:key|token|secret|password)[a-zA-Z_-]*[:\s=]+)([^\s,}]+)/gi,"$1[REDACTED]");return e}if(null==e)return e;if(Array.isArray(e))return e.map(ee);if("object"==typeof e){const t={};for(const[n,i]of Object.entries(e)){const e=n.toLowerCase();Q.some((t=>e.includes(t.toLowerCase())||e===t.toLowerCase()))&&"string"==typeof i&&i.length>0?t[n]=`[REDACTED_${i.length}_CHARS]`:t[n]=ee(i)}return t}return e}const te=new class{constructor(e=q.logLevel){this.logLevels={debug:0,info:1,warn:2,error:3},this.currentLevel=this.logLevels[e]}shouldLog(e){return q.enabled&&this.logLevels[e]>=this.currentLevel}formatMessage(e,t,...n){const i=(new Date).toISOString();return[`${`[Widgetic SDK] [${e.toUpperCase()}] [${i}]`} ${t}`,...n.map(ee)]}debug(e,...t){this.shouldLog("debug")}info(e,...t){this.shouldLog("info")}warn(e,...t){this.shouldLog("warn")}error(e,...t){this.shouldLog("error")}setLevel(e){this.currentLevel=this.logLevels[e]}setDebug(e){!function(e){J=e}(e)}},ne={debug:(e,...t)=>te.debug(e,...t),info:(e,...t)=>te.info(e,...t),warn:(e,...t)=>te.warn(e,...t),error:(e,...t)=>te.error(e,...t),setLevel:e=>te.setLevel(e)};class ie{constructor(e){this.apiKey=e}getToken(){return e(this,void 0,void 0,(function*(){return this.apiKey}))}isTokenValid(){return e(this,void 0,void 0,(function*(){return!!this.apiKey}))}}class oe{constructor(e){this.tokenEndpoint=e.tokenEndpoint||e.endpoint||"",this.refreshEndpoint=e.refreshEndpoint,this.headers=e.headers||{},e.apiKey&&!this.headers.Authorization&&(this.headers.Authorization=`Bearer ${e.apiKey}`)}getToken(){return e(this,void 0,void 0,(function*(){if(this.cachedToken&&(yield this.isTokenValid()))return this.cachedToken;const e=yield fetch(this.tokenEndpoint,{method:"POST",headers:Object.assign({"Content-Type":"application/json"},this.headers)});if(!e.ok)throw new Error(`Failed to fetch token: ${e.status} ${e.statusText}`);const t=yield e.json();if(this.cachedToken=t.token||t.access_token||t.apiKey,t.expires_in?this.tokenExpiry=Date.now()+1e3*t.expires_in:t.expires_at&&(this.tokenExpiry=new Date(t.expires_at).getTime()),!this.cachedToken)throw new Error("Invalid token response: no token found");return this.cachedToken}))}refreshToken(){return e(this,void 0,void 0,(function*(){if(!this.refreshEndpoint)return this.getToken();const e=yield fetch(this.refreshEndpoint,{method:"POST",headers:Object.assign({"Content-Type":"application/json",Authorization:`Bearer ${this.cachedToken}`},this.headers)});if(!e.ok)throw new Error(`Failed to refresh token: ${e.status} ${e.statusText}`);const t=yield e.json();if(this.cachedToken=t.token||t.access_token||t.apiKey,t.expires_in&&(this.tokenExpiry=Date.now()+1e3*t.expires_in),!this.cachedToken)throw new Error("Invalid token response: no token found");return this.cachedToken}))}isTokenValid(){return e(this,void 0,void 0,(function*(){return!!this.cachedToken&&(!this.tokenExpiry||Date.now()<this.tokenExpiry)}))}}class re{constructor(e,t){this.tokenFunction=e,this.validationFunction=t}getToken(){return e(this,void 0,void 0,(function*(){return yield this.tokenFunction()}))}isTokenValid(){return e(this,void 0,void 0,(function*(){return!this.validationFunction||(yield this.validationFunction())}))}}class se{constructor(e){this.apiKey=e}getToken(){return e(this,void 0,void 0,(function*(){if(!this.apiKey)throw new Error("No API key available. Please configure a TokenProvider or set API keys.");return this.apiKey}))}isTokenValid(){return e(this,void 0,void 0,(function*(){return!!this.apiKey}))}}class ae extends Error{constructor(e,t,n){super(e),this.code=t,this.statusCode=n,this.name="AuthError"}}class ce{constructor(e={}){var t,n;this.currentToken=null,this.apiKey=null,this.refreshTimer=null,this.config=Object.assign({apiUrl:e.apiUrl||F(),debug:e.debug||!1},e),this.apiKey=e.apiKey||"undefined"!=typeof process&&((null===(t={NODE_ENV:"production"})||void 0===t?void 0:t.PUBLIC_API_KEY)||(null===(n={NODE_ENV:"production"})||void 0===n?void 0:n.API_KEY))||null}createTokensApiForApiKey(i){const o=new t({basePath:this.config.apiUrl,apiKey:()=>e(this,void 0,void 0,(function*(){return i})),headers:{"X-SDK-Version":`embed-sdk/${H}`}});return new n(o)}createTokensApiForAccessToken(i){const o=new t({basePath:this.config.apiUrl,accessToken:()=>e(this,void 0,void 0,(function*(){return i})),headers:{"X-SDK-Version":`embed-sdk/${H}`}});return new n(o)}setApiKey(e){this.apiKey=e,this.currentToken={token:e,tokenType:"API-Key",expiresAt:null,scopes:[]},this.config.debug&&ne.debug("AuthManager: API key set")}getValidToken(t){return e(this,void 0,void 0,(function*(){if(this.currentToken&&this.isTokenValid(this.currentToken)){if(ce.validatedTokens.has(this.currentToken.token))return this.currentToken.token;if(yield this.validateToken())return this.currentToken.token}if(this.apiKey)return yield this.exchangeApiKeyForJWT(t),this.currentToken.token;throw new ae("No authentication method available","NO_AUTH_METHOD")}))}exchangeApiKeyForJWT(t){return e(this,void 0,void 0,(function*(){var e;if(!this.apiKey)throw new ae("No API key available for exchange","NO_API_KEY");const n={scopes:(null==t?void 0:t.scopes)||this.getDefaultScopes(),expiresIn:(null==t?void 0:t.expiresIn)||1800};try{const t=this.createTokensApiForApiKey(this.apiKey),i=yield t.exchangeToken({exchangeTokenRequest:n}),o=(null===(e=null==i?void 0:i.data)||void 0===e?void 0:e.token)||(null==i?void 0:i.token);if(!o)throw new ae("Token exchange response missing token","INVALID_RESPONSE");const r=(null==i?void 0:i.data)||i,s={token:o,tokenType:r.tokenType||"Bearer",expiresAt:r.expiresAt?r.expiresAt instanceof Date?r.expiresAt.toISOString():String(r.expiresAt):null,scopes:r.scopes||[]};return this.setToken(s),this.config.debug&&ne.info("AuthManager: Token exchanged successfully",{scopes:s.scopes,expiresAt:s.expiresAt}),s}catch(e){const t=e instanceof ae?e:new ae(`Token exchange failed: ${e instanceof Error?e.message:String(e)}`,"TOKEN_EXCHANGE_ERROR");throw this.config.onAuthError&&this.config.onAuthError(t),t}}))}validateToken(){return e(this,void 0,void 0,(function*(){var e;if(!this.currentToken)return!1;if(ce.validatedTokens.has(this.currentToken.token))return!0;try{const t=this.createTokensApiForAccessToken(this.currentToken.token),n=yield t.validateToken();return!0===(null==n?void 0:n.success)&&!0===(null===(e=n.data)||void 0===e?void 0:e.valid)||!0===(null==n?void 0:n.valid)?(ce.validatedTokens.add(this.currentToken.token),!0):(this.clearToken(),!1)}catch(e){return this.config.debug&&ne.warn("AuthManager: Token validation failed",e),!1}}))}setToken(e){this.currentToken=e,e.expiresAt&&this.scheduleTokenRefresh(e),this.config.onTokenRefreshed&&this.config.onTokenRefreshed(e.token)}clearToken(){this.currentToken&&ce.validatedTokens.delete(this.currentToken.token),this.currentToken=null,this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null)}isTokenValid(e){if(!e.expiresAt)return!0;const t=new Date(e.expiresAt).getTime();return Date.now()<t-6e4}scheduleTokenRefresh(t){if(!t.expiresAt||!this.apiKey)return;const n=new Date(t.expiresAt).getTime()-Date.now()-3e5;n>0&&(this.refreshTimer=setTimeout((()=>e(this,void 0,void 0,(function*(){try{yield this.exchangeApiKeyForJWT({scopes:t.scopes}),this.config.debug&&ne.info("AuthManager: Token refreshed automatically")}catch(e){this.config.debug&&ne.error("AuthManager: Automatic token refresh failed",e),this.config.onTokenExpired&&this.config.onTokenExpired()}}))),n))}getDefaultScopes(){return["compositions:read","widgets:read","projects:read"]}getCurrentTokenInfo(){return this.currentToken}hasAuthMethod(){return!(!this.apiKey&&!this.currentToken)}dispose(){this.clearToken(),this.apiKey=null,this.config.debug&&ne.debug("AuthManager: Disposed")}}ce.validatedTokens=new Set;const he=x,ue={};let de=null,le=null;const Te={API_URL:M.PROD_API_URL,API_VERSION:M.VERSION,CLIENT_URL:M.PROD_CLIENT_URL,PRODUCTION_URL:M.PROD_CDN_URL,NODE_ENV:"production",ENABLE_EDITING:M.ENABLE_EDITING,API_KEY:ue.PUBLIC_API_KEY,AXIOM_API_KEY:ue.PUBLIC_AXIOM_API_KEY,STATSIG_KEY:ue.PUBLIC_STATSIG_KEY};function Ee(e){de=e}function pe(){return de}function _e(){return le||(le=new ce({apiUrl:ve(),debug:Pe.enabled})),le}function ke(e){_e().setApiKey(e)}function Ae(){return e(this,void 0,void 0,(function*(){if(le&&le.hasAuthMethod())try{return yield le.getValidToken()}catch(e){}if(de)return yield de.getToken();const e=Te.API_KEY;if(!e)throw new Error("No authentication method available. Please configure an API key, TokenProvider, or set PUBLIC_API_KEY in environment variables.");return e}))}function fe(e){const t=(null==e?void 0:e.tokenProvider)||de;if(!t){const t=(null==e?void 0:e.apiKey)||Te.API_KEY;return{apiKey:t,basePath:(null==e?void 0:e.basePath)||ve(),tokenProvider:t?new se(t):void 0}}return{basePath:(null==e?void 0:e.basePath)||ve(),tokenProvider:t}}function ve(){return Te.API_URL}function ge(){return Te.PRODUCTION_URL}function Re(){return`${ve()}${Te.API_VERSION}`}const Ie={isProduction:"production"===Te.NODE_ENV,apiUrl:ve(),apiKey:Te.API_KEY},Oe={renderMode:V,displayMode:G,resize:B,width:Y,height:$,autoscale:W},ye={customElements:j.CUSTOM_ELEMENTS,http3:j.HTTP3,resizeObserver:j.RESIZE_OBSERVER},Ne={batchSize:X,loadTimeout:z,retryAttempts:Z},Pe={enabled:b,logLevel:m},De={AXIOM_API_KEY:Te.AXIOM_API_KEY||"",AXIOM_DATASET:o,AXIOM_API_ENDPOINT:i,STATSIG_API_KEY:Te.STATSIG_KEY||"",STATSIG_API_ENDPOINT:r,ENABLE_PERFORMANCE_TRACKING:s,PERFORMANCE_SAMPLE_RATE:a,PERFORMANCE_REPORTING_ENDPOINT:h,LCP_THRESHOLD:u,LCP_WARNING_THRESHOLD:d,FID_THRESHOLD:l,FID_WARNING_THRESHOLD:T,CLS_THRESHOLD:E,CLS_WARNING_THRESHOLD:p,FCP_THRESHOLD:_,FCP_WARNING_THRESHOLD:k,TTFB_THRESHOLD:A,TTFB_WARNING_THRESHOLD:f,WIDGET_LOAD_THRESHOLD:v,WIDGET_LOAD_WARNING_THRESHOLD:g,BUNDLE_SIZE_THRESHOLD:R,BUNDLE_SIZE_WARNING_THRESHOLD:I,MAX_METRICS_BUFFER:c},Le={ROOT_MARGIN:O,THRESHOLD:y,MAX_CONCURRENT:N,RETRY_ATTEMPTS:P,RETRY_DELAY:D},Se={MAX_PRELOAD_REQUESTS:L,PREFETCH_TIMEOUT:S,CACHE_DURATION:C,MAX_CONCURRENT_REQUESTS:K,DNS_PREFETCH_ENABLED:w,PRECONNECT_ENABLED:U},Ce={DEBUG:b,LOG_LEVEL:m,VERSION:x};function Ke(){return fe()}var we=Object.freeze({__proto__:null,BROWSER_FEATURES:ye,DEBUG:Pe,DEFAULT_WIDGET_CONFIG:Oe,LAZY_LOADING_CONFIG:Le,PERFORMANCE:Ne,PERFORMANCE_CONFIG:De,RESOURCE_CONFIG:Se,SDK_CONFIG:Ce,VERSION:he,config:Te,createSdkConfig:fe,environment:Ie,getApiUrl:ve,getAuthManager:_e,getAuthToken:Ae,getCdnUrl:ge,getConfiguration:Ke,getTokenProvider:pe,getVersionedApiUrl:Re,setApiKey:ke,setTokenProvider:Ee});export{ce as A,Oe as D,oe as E,re as F,De as P,ie as S,he as V,Re as a,ge as b,Te as c,te as d,Pe as e,Ke as f,Ae as g,ke as h,se as i,pe as j,ve as k,ne as l,M as m,fe as n,ae as o,_e as p,we as q,Ee as s};
1
+ import{_ as e}from"./vendor.js";import{A as t,D as o}from"./api.js";const n="https://api.axiom.co/v1",r="widgetic-performance",E="https://events.statsigapi.net/v1/custom",i=!0,_=1,s=1e3,a="",R=2500,A=2e3,I=100,u=50,L=.1,T=.05,l=1800,N=1200,O=800,c=600,D=3e3,d=2e3,P=5e5,S=3e5,p="50px",C=.1,f=3,g=3,h=1e3,v=10,U=5e3,H=36e5,y=6,G=!0,M=!0,b=!1,k="info",m="2.0.3",w="2.0.3";function F(){var e;return`${"undefined"!=typeof process&&"development"===(null===(e={NODE_ENV:"production"})||void 0===e?void 0:e.NODE_ENV)?K.DEV_API_URL:K.PROD_API_URL}${K.VERSION}`}const K={DEV_API_URL:"http://localhost:3000",DEV_CLIENT_URL:"http://localhost:5173",PROD_API_URL:"https://api.widgetic.com",PROD_CLIENT_URL:"https://widgetic.com",PROD_CDN_URL:"https://cdn.widgetic.com",VERSION:"/api/v1",NODE_ENV:"development",ENABLE_EDITING:!0},V="auto",B="inline",Y="fixed",W=350,X=200,$=!1,z={CUSTOM_ELEMENTS:"undefined"!=typeof customElements,HTTP3:!1,RESIZE_OBSERVER:"undefined"!=typeof ResizeObserver},Z=10,j=5e3,x=3;let Q=b;const q={get enabled(){return Q},logLevel:k},J=["apikey","api_key","api-key","servicekey","service_key","service-key","token","access_token","auth_token","secret","password","private_key","authorization","bearer","internal_key","public_api_key","public_internal_key"];function ee(e){if("string"==typeof e){const t=e.toLowerCase();for(const o of J)if(t.includes(o))return e.replace(/([a-zA-Z_-]*(?:key|token|secret|password)[a-zA-Z_-]*[:\s=]+)([^\s,}]+)/gi,"$1[REDACTED]");return e}if(null==e)return e;if(Array.isArray(e))return e.map(ee);if("object"==typeof e){const t={};for(const[o,n]of Object.entries(e)){const e=o.toLowerCase();J.some((t=>e.includes(t.toLowerCase())||e===t.toLowerCase()))&&"string"==typeof n&&n.length>0?t[o]=`[REDACTED_${n.length}_CHARS]`:t[o]=ee(n)}return t}return e}const te=new class{constructor(e=q.logLevel){this.logLevels={debug:0,info:1,warn:2,error:3},this.currentLevel=this.logLevels[e]}shouldLog(e){return q.enabled&&this.logLevels[e]>=this.currentLevel}formatMessage(e,t,...o){const n=(new Date).toISOString();return[`${`[Widgetic SDK] [${e.toUpperCase()}] [${n}]`} ${t}`,...o.map(ee)]}debug(e,...t){this.shouldLog("debug")}info(e,...t){this.shouldLog("info")}warn(e,...t){this.shouldLog("warn")}error(e,...t){this.shouldLog("error")}setLevel(e){this.currentLevel=this.logLevels[e]}setDebug(e){!function(e){Q=e}(e)}},oe={debug:(e,...t)=>te.debug(e,...t),info:(e,...t)=>te.info(e,...t),warn:(e,...t)=>te.warn(e,...t),error:(e,...t)=>te.error(e,...t),setLevel:e=>te.setLevel(e)},ne=m,re={NODE_ENV:"production"};let Ee=null,ie=null;const _e={API_URL:K.PROD_API_URL,API_VERSION:K.VERSION,CLIENT_URL:K.PROD_CLIENT_URL,PRODUCTION_URL:K.PROD_CDN_URL,NODE_ENV:"production",ENABLE_EDITING:K.ENABLE_EDITING,API_KEY:re.PUBLIC_API_KEY,AXIOM_API_KEY:re.PUBLIC_AXIOM_API_KEY,STATSIG_KEY:re.PUBLIC_STATSIG_KEY};function se(e){Ee=e}function ae(){return Ee}function Re(){return ie||(ie=new t({apiUrl:Le(),debug:de.enabled})),ie}function Ae(e){Re().setApiKey(e)}function Ie(){return e(this,void 0,void 0,(function*(){if(ie&&ie.hasAuthMethod())try{return yield ie.getValidToken()}catch(e){}if(Ee)return yield Ee.getToken();const e=_e.API_KEY;if(!e)throw new Error("No authentication method available. Please configure an API key, TokenProvider, or set PUBLIC_API_KEY in environment variables.");return e}))}function ue(e){const t=(null==e?void 0:e.tokenProvider)||Ee;if(!t){const t=(null==e?void 0:e.apiKey)||_e.API_KEY;return{apiKey:t,basePath:(null==e?void 0:e.basePath)||Le(),tokenProvider:t?new o(t):void 0}}return{basePath:(null==e?void 0:e.basePath)||Le(),tokenProvider:t}}function Le(){return _e.API_URL}function Te(){return _e.PRODUCTION_URL}function le(){return`${Le()}${_e.API_VERSION}`}const Ne={isProduction:"production"===_e.NODE_ENV,apiUrl:Le(),apiKey:_e.API_KEY},Oe={renderMode:V,displayMode:B,resize:Y,width:W,height:X,autoscale:$},ce={customElements:z.CUSTOM_ELEMENTS,http3:z.HTTP3,resizeObserver:z.RESIZE_OBSERVER},De={batchSize:Z,loadTimeout:j,retryAttempts:x},de={enabled:b,logLevel:k},Pe={AXIOM_API_KEY:_e.AXIOM_API_KEY||"",AXIOM_DATASET:r,AXIOM_API_ENDPOINT:n,STATSIG_API_KEY:_e.STATSIG_KEY||"",STATSIG_API_ENDPOINT:E,ENABLE_PERFORMANCE_TRACKING:i,PERFORMANCE_SAMPLE_RATE:_,PERFORMANCE_REPORTING_ENDPOINT:a,LCP_THRESHOLD:R,LCP_WARNING_THRESHOLD:A,FID_THRESHOLD:I,FID_WARNING_THRESHOLD:u,CLS_THRESHOLD:L,CLS_WARNING_THRESHOLD:T,FCP_THRESHOLD:l,FCP_WARNING_THRESHOLD:N,TTFB_THRESHOLD:O,TTFB_WARNING_THRESHOLD:c,WIDGET_LOAD_THRESHOLD:D,WIDGET_LOAD_WARNING_THRESHOLD:d,BUNDLE_SIZE_THRESHOLD:P,BUNDLE_SIZE_WARNING_THRESHOLD:S,MAX_METRICS_BUFFER:s},Se={ROOT_MARGIN:p,THRESHOLD:C,MAX_CONCURRENT:f,RETRY_ATTEMPTS:g,RETRY_DELAY:h},pe={MAX_PRELOAD_REQUESTS:v,PREFETCH_TIMEOUT:U,CACHE_DURATION:H,MAX_CONCURRENT_REQUESTS:y,DNS_PREFETCH_ENABLED:G,PRECONNECT_ENABLED:M},Ce={DEBUG:b,LOG_LEVEL:k,VERSION:m};function fe(){return ue()}var ge=Object.freeze({__proto__:null,BROWSER_FEATURES:ce,DEBUG:de,DEFAULT_WIDGET_CONFIG:Oe,LAZY_LOADING_CONFIG:Se,PERFORMANCE:De,PERFORMANCE_CONFIG:Pe,RESOURCE_CONFIG:pe,SDK_CONFIG:Ce,VERSION:ne,config:_e,createSdkConfig:ue,environment:Ne,getApiUrl:Le,getAuthManager:Re,getAuthToken:Ie,getCdnUrl:Te,getConfiguration:fe,getTokenProvider:ae,getVersionedApiUrl:le,setApiKey:Ae,setTokenProvider:se});export{K as A,de as D,Pe as P,w as S,ne as V,_e as a,Le as b,ue as c,Ie as d,le as e,Te as f,F as g,te as h,se as i,fe as j,ae as k,oe as l,Oe as m,Re as n,ge as o,Ae as s};
@@ -1 +1 @@
1
- import{l as e}from"./core.js";import{_ as t}from"./vendor.js";import{c as i}from"./advanced.js";class n{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 s=null;function o(e){return s||(s=new n(e)),s}class r{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.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 a=null;function l(e){return a||(a=new r(e)),a}var d=Object.freeze({__proto__:null,DisplayManager:r,getDisplayManager:l,resetDisplayManager:function(){a&&(a.cleanupAll(),a=null)}});const c={mobile:480,tablet:768,desktop:1024},h={MANUAL:"manual",EXIT_INTENT:"exit-intent",ON_SCROLL:"on-scroll",TIME_DELAY:"time-delay",ENGAGEMENT_THRESHOLD:"engagement",EXTERNAL_TRIGGER:"external"},g={DEFAULT_ANIMATION:"fade",DEFAULT_DELAY_MS:1e3,SUPPORTED_ANIMATIONS:["fade","slide-up","slide-down","slide-left","slide-right","zoom","bounce"]};class p{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:c.mobile,tablet:c.tablet,desktop:c.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(h).includes(i.displayMode)||(i.displayMode=h.MANUAL),i.animation&&g.SUPPORTED_ANIMATIONS.includes(i.animation)||(i.animation=g.DEFAULT_ANIMATION,e.debug("Using default animation for overlay",{provided:t.animation,defaultUsed:g.DEFAULT_ANIMATION})),i.delay||(i.delay=g.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||g.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" aria-label="Close">&times;</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.addEventListener("click",(()=>this.hideOverlay())),t.addEventListener("click",(i=>{i.target===t&&!1!==e.showBackdrop&&this.hideOverlay()}));const n=e=>{"Escape"===e.key&&(this.hideOverlay(),document.removeEventListener("keydown",n))};return document.addEventListener("keydown",n),t}generateResponsiveCSS(){const e=this.config.breakpoints;if(!e||!e.useBreakpoints)return"/* No mobile responsive styles - breakpoints disabled */";const t=e.mobile||c.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||c.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:g.DEFAULT_ANIMATION,delay:g.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 u=null;function v(e){return u||(u=new p(e)),u}export{r as D,n as R,o as a,v as b,d,l as g};
1
+ import{l as e}from"./core.js";import{_ as t}from"./vendor.js";import{c as i}from"./advanced.js";class n{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 s=null;function o(e){return s||(s=new n(e)),s}class r{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.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 a=null;function l(e){return a||(a=new r(e)),a}var d=Object.freeze({__proto__:null,DisplayManager:r,getDisplayManager:l,resetDisplayManager:function(){a&&(a.cleanupAll(),a=null)}});const c={mobile:480,tablet:768,desktop:1024},h={MANUAL:"manual",EXIT_INTENT:"exit-intent",ON_SCROLL:"on-scroll",TIME_DELAY:"time-delay",ENGAGEMENT_THRESHOLD:"engagement",EXTERNAL_TRIGGER:"external"},g={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 p{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:c.mobile,tablet:c.tablet,desktop:c.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(h).includes(i.displayMode)||(i.displayMode=h.MANUAL),i.animation&&g.SUPPORTED_ANIMATIONS.includes(i.animation)||(i.animation=g.DEFAULT_ANIMATION,e.debug("Using default animation for overlay",{provided:t.animation,defaultUsed:g.DEFAULT_ANIMATION})),i.delay||(i.delay=g.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||g.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" aria-label="Close">&times;</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.addEventListener("click",(()=>this.hideOverlay())),t.addEventListener("click",(i=>{i.target===t&&!1!==e.showBackdrop&&this.hideOverlay()}));const n=e=>{"Escape"===e.key&&(this.hideOverlay(),document.removeEventListener("keydown",n))};return document.addEventListener("keydown",n),t}generateResponsiveCSS(){const e=this.config.breakpoints;if(!e||!e.useBreakpoints)return"/* No mobile responsive styles - breakpoints disabled */";const t=e.mobile||c.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||c.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:g.DEFAULT_ANIMATION,delay:g.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 u=null;function v(e){return u||(u=new p(e)),u}export{r as D,n as R,o as a,v as b,d,l as g};
@@ -1 +1 @@
1
- import{c as t}from"./core.js";class e{static getInstance(){return e.instance||(e.instance=new e),e.instance}constructor(){this.playingWidgets=new Map,this.widgetConfigs=new Map,this.storageKey="widgetic_media_state",this.globalVolumeKey="widgetic_global_volume",this.storageVersion="2.0",this.eventListeners=new Map,this.autoResumeEnabled=!0,this.defaultAutoResumeTimeout=18e5,this.globalVolumeEnabled=!0,this.globalVolumeState={volume:1,muted:!1,lastUpdated:Date.now()},this.loadPersistedState(),this.loadGlobalVolumeState(),this.setupVisibilityHandler(),this.setupUnloadHandler(),setTimeout((()=>{this.autoResumeWidgets()}),1e3)}registerWidget(t,e={}){const s=Object.assign({autoPause:!0,mediaType:"both",priority:5,persistState:!0,allowSimultaneous:[],autoResume:!1,autoResumeTimeout:this.defaultAutoResumeTimeout,globalVolume:!0},e);this.widgetConfigs.set(t,s);const i=this.playingWidgets.get(t);i&&s.persistState?(s.globalVolume&&this.globalVolumeEnabled&&(i.volume=this.globalVolumeState.muted?0:this.globalVolumeState.volume),setTimeout((()=>{this.sendRestoreStateCommand(t,i)}),100)):s.globalVolume&&this.globalVolumeEnabled&&setTimeout((()=>{this.sendVolumeCommand(t,this.globalVolumeState.muted?0:this.globalVolumeState.volume)}),100)}unregisterWidget(t){this.handleMediaEvent({type:"stop",compositionId:t,config:this.widgetConfigs.get(t)||{}}),this.playingWidgets.delete(t),this.widgetConfigs.delete(t),this.eventListeners.delete(t)}handleMediaEvent(t){const{type:e,compositionId:s,config:i,data:a}=t;switch(e){case"play":this.handlePlayEvent(s,i,a);break;case"pause":this.handlePauseEvent(s,a);break;case"stop":case"ended":this.handleStopEvent(s);break;case"seeking":this.handleSeekingEvent(s,null==a?void 0:a.position);break;case"volumechange":this.handleVolumeEvent(s,null==a?void 0:a.volume);break;case"trackchange":this.handleTrackChangeEvent(s,a);break;case"playlistchange":this.handlePlaylistChangeEvent(s,a)}this.emitToListeners(s,t),i.persistState&&this.persistState(),this.dispatchGlobalEvent(t)}handlePlayEvent(t,e,s={}){const i=s.mediaType||e.mediaType||"both",a=e.priority||5,o={compositionId:t,mediaType:i,state:"playing",priority:a,startedAt:Date.now(),duration:s.duration,position:s.position||0,title:s.title,volume:s.volume,playlist:s.playlist,autoResume:e.autoResume,lastInteraction:Date.now()};!1!==e.autoPause&&this.pauseConflictingWidgets(t,i,a,e.allowSimultaneous||[]),this.playingWidgets.set(t,o)}handlePauseEvent(t,e={}){const s=this.playingWidgets.get(t);s&&(s.state="paused",s.position=e.position||s.position,s.volume=e.volume||s.volume,s.lastInteraction=Date.now())}handleStopEvent(t){const e=this.playingWidgets.get(t);e&&(e.state="stopped",e.position=0,e.lastInteraction=Date.now())}handleSeekingEvent(t,e){const s=this.playingWidgets.get(t);s&&void 0!==e&&(s.position=e,s.lastInteraction=Date.now())}handleVolumeEvent(t,e){const s=this.playingWidgets.get(t),i=this.widgetConfigs.get(t);s&&void 0!==e&&(s.lastInteraction=Date.now(),(null==i?void 0:i.globalVolume)&&this.globalVolumeEnabled?(this.globalVolumeState={volume:e>0?e:this.globalVolumeState.volume,muted:0===e,lastUpdated:Date.now(),lastChangedBy:t},this.persistGlobalVolumeState(),this.syncGlobalVolumeToWidgets(t),s.volume=this.globalVolumeState.muted?0:this.globalVolumeState.volume):s.volume=e)}handleTrackChangeEvent(t,e={}){const s=this.playingWidgets.get(t);s&&e.playlist&&(s.playlist=Object.assign(Object.assign({},s.playlist),e.playlist),s.position=0,s.title=e.playlist.trackTitle||s.title,s.lastInteraction=Date.now())}handlePlaylistChangeEvent(t,e={}){const s=this.playingWidgets.get(t);s&&e.playlist&&(s.playlist=Object.assign(Object.assign({},s.playlist),e.playlist),s.lastInteraction=Date.now())}pauseConflictingWidgets(t,e,s,i){const a=[];for(const[o,n]of this.playingWidgets){if(o===t||"playing"!==n.state)continue;this.isSimultaneousAllowed(n.mediaType,e,i)||(s>n.priority||s===n.priority&&Date.now()>n.startedAt)&&a.push(o)}for(const t of a)this.sendPauseCommand(t);a.length}isSimultaneousAllowed(t,e,s){return"both"!==t&&"both"!==e&&(t!==e&&(s.includes(t)&&s.includes(e)))}sendPauseCommand(e){var s;const i=document.querySelector(`[data-widgetic-id="${e}"], [data-composition-id="${e}"]`);if(i){if("iframe"===i.tagName.toLowerCase()){const a=i,o=t.CLIENT_URL||"*";null===(s=a.contentWindow)||void 0===s||s.postMessage({type:"widgetic:media:command",command:"pause",compositionId:e},o)}i.dispatchEvent(new CustomEvent("widgetic:media:command",{detail:{command:"pause",compositionId:e}}));const a=this.playingWidgets.get(e);a&&(a.state="paused")}}getPlayingWidgets(){return Array.from(this.playingWidgets.values()).filter((t=>"playing"===t.state))}getAllMediaWidgets(){return Array.from(this.playingWidgets.values())}pauseAll(){const t=this.getPlayingWidgets();for(const e of t)this.sendPauseCommand(e.compositionId)}resumeLastPlayed(){const t=Array.from(this.playingWidgets.values()).filter((t=>"paused"===t.state)).sort(((t,e)=>e.startedAt-t.startedAt));if(t.length>0){const e=t[0];this.sendResumeCommand(e.compositionId)}}sendResumeCommand(e){var s;const i=document.querySelector(`[data-widgetic-id="${e}"], [data-composition-id="${e}"]`);if(i){if("iframe"===i.tagName.toLowerCase()){const a=i,o=t.CLIENT_URL||"*";null===(s=a.contentWindow)||void 0===s||s.postMessage({type:"widgetic:media:command",command:"play",compositionId:e},o)}i.dispatchEvent(new CustomEvent("widgetic:media:command",{detail:{command:"play",compositionId:e}}))}}addEventListener(t,e){return this.eventListeners.has(t)||this.eventListeners.set(t,[]),this.eventListeners.get(t).push(e),()=>{const s=this.eventListeners.get(t);if(s){const t=s.indexOf(e);t>-1&&s.splice(t,1)}}}emitToListeners(t,e){const s=this.eventListeners.get(t);if(s)for(const t of s)try{t(e)}catch(t){}}dispatchGlobalEvent(t){document.dispatchEvent(new CustomEvent(`widgetic:media:${t.type}`,{detail:{compositionId:t.compositionId,config:t.config,data:t.data},bubbles:!0}))}loadPersistedState(){if("undefined"!=typeof localStorage)try{const t=localStorage.getItem(this.storageKey);if(t){const e=JSON.parse(t);if(e.version!==this.storageVersion)return void this.clearPersistedState();const s=864e5;if(e.timestamp&&Date.now()-e.timestamp>s)return void this.clearPersistedState();for(const[t,s]of Object.entries(e.playingWidgets||{})){const e=s;e.compositionId&&e.mediaType&&e.state&&this.playingWidgets.set(t,e)}}}catch(t){this.clearPersistedState()}}persistState(){try{const t={version:this.storageVersion,playingWidgets:Object.fromEntries(this.playingWidgets),timestamp:Date.now(),autoResumeEnabled:this.autoResumeEnabled};localStorage.setItem(this.storageKey,JSON.stringify(t))}catch(t){}}setupVisibilityHandler(){"undefined"!=typeof document&&document.addEventListener("visibilitychange",(()=>{document.hidden&&this.pauseAll()}))}setupUnloadHandler(){"undefined"!=typeof window&&window.addEventListener("beforeunload",(()=>{this.persistState()}))}clearPersistedState(t=!1){try{localStorage.removeItem(this.storageKey),t&&(localStorage.removeItem(this.globalVolumeKey),this.globalVolumeState={volume:1,muted:!1,lastUpdated:Date.now()})}catch(t){}}getStats(){const t=this.getPlayingWidgets(),e=Array.from(this.playingWidgets.values()).filter((t=>"paused"===t.state)),s=Array.from(this.playingWidgets.values()).filter((t=>t.playlist)),i=Array.from(this.widgetConfigs.values()).filter((t=>t.globalVolume)).length;return{totalWidgets:this.widgetConfigs.size,playingWidgets:t.length,pausedWidgets:e.length,registeredWidgets:this.playingWidgets.size,widgetsWithPlaylists:s.length,globalVolumeWidgets:i,autoResumeEnabled:this.autoResumeEnabled,globalVolumeEnabled:this.globalVolumeEnabled,globalVolume:{volume:this.globalVolumeState.volume,muted:this.globalVolumeState.muted,lastUpdated:this.globalVolumeState.lastUpdated,lastChangedBy:this.globalVolumeState.lastChangedBy},storageVersion:this.storageVersion,currentlyPlaying:t.map((t=>({compositionId:t.compositionId,mediaType:t.mediaType,priority:t.priority,duration:t.startedAt?Date.now()-t.startedAt:0,position:t.position,volume:t.volume,playlist:t.playlist?{currentTrack:t.playlist.currentTrack,totalTracks:t.playlist.totalTracks,trackTitle:t.playlist.trackTitle}:void 0}))),allWidgets:Array.from(this.playingWidgets.values()).map((t=>{var e;return{compositionId:t.compositionId,state:t.state,mediaType:t.mediaType,priority:t.priority,position:t.position,volume:t.volume,lastInteraction:t.lastInteraction,playlist:t.playlist,autoResume:t.autoResume,globalVolume:(null===(e=this.widgetConfigs.get(t.compositionId))||void 0===e?void 0:e.globalVolume)||!1}}))}}destroy(){this.pauseAll(),this.playingWidgets.clear(),this.widgetConfigs.clear(),this.eventListeners.clear(),this.persistState(),this.persistGlobalVolumeState()}autoResumeWidgets(t={}){if(!this.autoResumeEnabled)return;const{autoResumePlayback:e=!0,maxStateAge:s=this.defaultAutoResumeTimeout,respectTimeouts:i=!0}=t,a=Date.now(),o=[];for(const[t,n]of this.playingWidgets){const l=this.widgetConfigs.get(t);(null==l?void 0:l.autoResume)&&l.persistState&&n.lastInteraction&&(!i||a-n.lastInteraction<=(l.autoResumeTimeout||s))&&("playing"===n.state||e&&"paused"===n.state)&&o.push(n)}o.length>0&&(o.sort(((t,e)=>t.priority!==e.priority?e.priority-t.priority:(e.lastInteraction||0)-(t.lastInteraction||0))),e&&"playing"===o[0].state&&this.resumeWidget(o[0].compositionId))}resumeWidget(t){const e=this.playingWidgets.get(t),s=this.widgetConfigs.get(t);return!(!e||!s)&&(this.sendRestoreStateCommand(t,e),"playing"===e.state&&setTimeout((()=>{this.sendPlayCommand(t,e.position)}),100),!0)}sendRestoreStateCommand(e,s){var i;const a=document.querySelector(`[data-widgetic-id="${e}"], [data-composition-id="${e}"]`);if(a){const o={type:"widgetic:media:command",command:"restore",compositionId:e,state:{position:s.position||0,volume:s.volume||1,title:s.title,playlist:s.playlist,duration:s.duration}};if("iframe"===a.tagName.toLowerCase()){const e=a,s=t.CLIENT_URL||"*";null===(i=e.contentWindow)||void 0===i||i.postMessage(o,s)}a.dispatchEvent(new CustomEvent("widgetic:media:command",{detail:o}))}}sendPlayCommand(e,s){var i;const a=document.querySelector(`[data-widgetic-id="${e}"], [data-composition-id="${e}"]`);if(a){const o={type:"widgetic:media:command",command:"play",compositionId:e,position:s};if("iframe"===a.tagName.toLowerCase()){const e=a,s=t.CLIENT_URL||"*";null===(i=e.contentWindow)||void 0===i||i.postMessage(o,s)}a.dispatchEvent(new CustomEvent("widgetic:media:command",{detail:o}))}}getPersistedState(t){return this.playingWidgets.get(t)||null}updateWidgetState(t,e){const s=this.playingWidgets.get(t);if(s){const i=Object.assign(Object.assign(Object.assign({},s),e),{lastInteraction:Date.now()});this.playingWidgets.set(t,i);const a=this.widgetConfigs.get(t);(null==a?void 0:a.persistState)&&this.persistState()}}setAutoResumeEnabled(t){this.autoResumeEnabled=t}triggerAutoResume(t={}){this.autoResumeWidgets(t)}loadGlobalVolumeState(){if("undefined"!=typeof localStorage)try{const t=localStorage.getItem(this.globalVolumeKey);if(t){const e=JSON.parse(t);"number"==typeof e.volume&&"boolean"==typeof e.muted&&(this.globalVolumeState={volume:Math.max(0,Math.min(1,e.volume)),muted:e.muted,lastUpdated:e.lastUpdated||Date.now(),lastChangedBy:e.lastChangedBy})}}catch(t){}}persistGlobalVolumeState(){try{localStorage.setItem(this.globalVolumeKey,JSON.stringify(this.globalVolumeState))}catch(t){}}syncGlobalVolumeToWidgets(t){const e=this.globalVolumeState.muted?0:this.globalVolumeState.volume;for(const[s,i]of this.widgetConfigs)if(s!==t&&i.globalVolume){this.sendVolumeCommand(s,e);const t=this.playingWidgets.get(s);t&&(t.volume=e)}}sendVolumeCommand(e,s){var i;const a=document.querySelector(`[data-widgetic-id="${e}"], [data-composition-id="${e}"]`);if(a){const o={type:"widgetic:media:command",command:"setVolume",compositionId:e,volume:Math.max(0,Math.min(1,s))};if("iframe"===a.tagName.toLowerCase()){const e=a,s=t.CLIENT_URL||"*";null===(i=e.contentWindow)||void 0===i||i.postMessage(o,s)}a.dispatchEvent(new CustomEvent("widgetic:media:command",{detail:o}))}}getGlobalVolumeState(){return Object.assign({},this.globalVolumeState)}setGlobalVolume(t,e){const s=Math.max(0,Math.min(1,t));this.globalVolumeState={volume:s,muted:0===s,lastUpdated:Date.now(),lastChangedBy:e||"api"},this.persistGlobalVolumeState(),this.syncGlobalVolumeToWidgets()}toggleGlobalMute(t){return this.globalVolumeState=Object.assign(Object.assign({},this.globalVolumeState),{muted:!this.globalVolumeState.muted,lastUpdated:Date.now(),lastChangedBy:t||"api"}),this.persistGlobalVolumeState(),this.syncGlobalVolumeToWidgets(),this.globalVolumeState.muted}setGlobalVolumeEnabled(t){const e=this.globalVolumeEnabled;this.globalVolumeEnabled=t,t&&!e&&this.syncGlobalVolumeToWidgets()}isGlobalVolumeEnabled(){return this.globalVolumeEnabled}}let s=null;function i(){return s||(s=e.getInstance()),s}var a=Object.freeze({__proto__:null,MediaManager:e,getMediaManager:i,resetMediaManager:function(){s&&(s.destroy(),s=null)}});class o{static getInstance(){return o.instance||(o.instance=new o),o.instance}constructor(){this.contentStates=new Map,this.widgetConfigs=new Map,this.storageKey="widgetic_content_positions",this.storageVersion="1.0",this.eventListeners=new Map,this.autoResumeEnabled=!0,this.defaultAutoResumeTimeout=864e5,this.debounceTimers=new Map,this.loadPersistedState(),this.setupUnloadHandler(),setTimeout((()=>{this.autoResumePositions()}),1e3)}registerWidget(t,e={}){const s=Object.assign({contentType:"custom",persistState:!0,autoResume:!1,autoResumeTimeout:this.defaultAutoResumeTimeout,debounceDelay:500,trackMetadata:!1},e);this.widgetConfigs.set(t,s);const i=this.contentStates.get(t);i&&s.persistState&&setTimeout((()=>{this.sendRestorePositionCommand(t,i)}),100)}unregisterWidget(t){const e=this.debounceTimers.get(t);e&&(clearTimeout(e),this.debounceTimers.delete(t)),this.contentStates.delete(t),this.widgetConfigs.delete(t),this.eventListeners.delete(t)}handleContentPositionEvent(t){const{type:e,compositionId:s,config:i,data:a}=t;switch(e){case"position":case"navigate":this.handlePositionChangeEvent(s,i,a);break;case"complete":this.handleCompleteEvent(s,a);break;case"reset":this.handleResetEvent(s);break;case"metadata":this.handleMetadataEvent(s,a)}this.emitToListeners(s,t),i.persistState&&this.debouncedPersistState(s,i.debounceDelay||500),this.dispatchGlobalEvent(t)}handlePositionChangeEvent(t,e,s={}){const i=this.contentStates.get(t),a={compositionId:t,contentType:e.contentType||"custom",currentIndex:void 0!==s.currentIndex?s.currentIndex:(null==i?void 0:i.currentIndex)||0,totalItems:void 0!==s.totalItems?s.totalItems:(null==i?void 0:i.totalItems)||0,currentItemId:s.currentItemId||(null==i?void 0:i.currentItemId),currentItemTitle:s.currentItemTitle||(null==i?void 0:i.currentItemTitle),lastUpdated:Date.now(),autoResume:e.autoResume,lastInteraction:Date.now(),metadata:e.trackMetadata?Object.assign(Object.assign({},null==i?void 0:i.metadata),s.metadata):void 0};this.contentStates.set(t,a)}handleCompleteEvent(t,e={}){const s=this.contentStates.get(t);s&&(s.lastInteraction=Date.now(),s.metadata&&(s.metadata.completed=!0,s.metadata.completedAt=Date.now(),e.metadata&&Object.assign(s.metadata,e.metadata)))}handleResetEvent(t){const e=this.contentStates.get(t);e&&(e.currentIndex=0,e.currentItemId=void 0,e.currentItemTitle=void 0,e.lastInteraction=Date.now(),e.metadata&&(e.metadata.completed=!1,delete e.metadata.completedAt))}handleMetadataEvent(t,e={}){const s=this.contentStates.get(t);s&&e.metadata&&(s.metadata||(s.metadata={}),Object.assign(s.metadata,e.metadata),s.lastInteraction=Date.now())}loadPersistedState(){if("undefined"!=typeof localStorage)try{const t=localStorage.getItem(this.storageKey);if(t){const e=JSON.parse(t);if(e.version!==this.storageVersion)return void this.clearPersistedState();const s=6048e5;if(e.timestamp&&Date.now()-e.timestamp>s)return void this.clearPersistedState();for(const[t,s]of Object.entries(e.contentStates||{})){const e=s;e.compositionId&&e.contentType&&void 0!==e.currentIndex&&this.contentStates.set(t,e)}}}catch(t){this.clearPersistedState()}}debouncedPersistState(t,e){const s=this.debounceTimers.get(t);s&&clearTimeout(s);const i=setTimeout((()=>{this.persistState(),this.debounceTimers.delete(t)}),e);this.debounceTimers.set(t,i)}persistState(){try{const t={version:this.storageVersion,contentStates:Object.fromEntries(this.contentStates),timestamp:Date.now(),autoResumeEnabled:this.autoResumeEnabled};localStorage.setItem(this.storageKey,JSON.stringify(t))}catch(t){}}setupUnloadHandler(){"undefined"!=typeof window&&window.addEventListener("beforeunload",(()=>{for(const t of this.debounceTimers.values())clearTimeout(t);this.debounceTimers.clear(),this.persistState()}))}autoResumePositions(t={}){if(!this.autoResumeEnabled)return;const{autoResumePosition:e=!0,maxStateAge:s=this.defaultAutoResumeTimeout,respectTimeouts:i=!0}=t,a=Date.now(),o=[];for(const[t,n]of this.contentStates){const l=this.widgetConfigs.get(t);(null==l?void 0:l.autoResume)&&l.persistState&&n.lastInteraction&&(!i||a-n.lastInteraction<=(l.autoResumeTimeout||s))&&e&&o.push(n)}o.length>0&&o.forEach((t=>{this.resumeWidgetPosition(t.compositionId)}))}resumeWidgetPosition(t){const e=this.contentStates.get(t),s=this.widgetConfigs.get(t);return!(!e||!s)&&(this.sendRestorePositionCommand(t,e),!0)}sendRestorePositionCommand(e,s){var i;const a=document.querySelector(`[data-widgetic-id="${e}"], [data-composition-id="${e}"]`);if(a){const o={type:"widgetic:content:command",command:"restorePosition",compositionId:e,state:{currentIndex:s.currentIndex,totalItems:s.totalItems,currentItemId:s.currentItemId,currentItemTitle:s.currentItemTitle,metadata:s.metadata}};if("iframe"===a.tagName.toLowerCase()){const e=a,s=t.CLIENT_URL||"*";null===(i=e.contentWindow)||void 0===i||i.postMessage(o,s)}a.dispatchEvent(new CustomEvent("widgetic:content:command",{detail:o}))}}getAllContentWidgets(){return Array.from(this.contentStates.values())}getPersistedPosition(t){return this.contentStates.get(t)||null}updateWidgetPosition(t,e){const s=this.contentStates.get(t);if(s){const i=Object.assign(Object.assign(Object.assign({},s),e),{lastInteraction:Date.now()});this.contentStates.set(t,i);const a=this.widgetConfigs.get(t);(null==a?void 0:a.persistState)&&this.debouncedPersistState(t,a.debounceDelay||500)}}clearPersistedState(){try{localStorage.removeItem(this.storageKey)}catch(t){}}getStats(){const t=Array.from(this.contentStates.values()),e=t.reduce(((t,e)=>(t[e.contentType]=(t[e.contentType]||0)+1,t)),{});return{totalWidgets:this.widgetConfigs.size,trackedWidgets:this.contentStates.size,autoResumeEnabled:this.autoResumeEnabled,storageVersion:this.storageVersion,contentTypes:e,allWidgets:t.map((t=>({compositionId:t.compositionId,contentType:t.contentType,currentIndex:t.currentIndex,totalItems:t.totalItems,progress:t.totalItems>0?Math.round(t.currentIndex/(t.totalItems-1)*100):0,lastInteraction:t.lastInteraction,autoResume:t.autoResume,metadata:t.metadata})))}}addEventListener(t,e){return this.eventListeners.has(t)||this.eventListeners.set(t,[]),this.eventListeners.get(t).push(e),()=>{const s=this.eventListeners.get(t);if(s){const t=s.indexOf(e);t>-1&&s.splice(t,1)}}}emitToListeners(t,e){const s=this.eventListeners.get(t);if(s)for(const t of s)try{t(e)}catch(t){}}dispatchGlobalEvent(t){document.dispatchEvent(new CustomEvent(`widgetic:content:${t.type}`,{detail:{compositionId:t.compositionId,config:t.config,data:t.data},bubbles:!0}))}setAutoResumeEnabled(t){this.autoResumeEnabled=t}triggerAutoResume(t={}){this.autoResumePositions(t)}destroy(){for(const t of this.debounceTimers.values())clearTimeout(t);this.contentStates.clear(),this.widgetConfigs.clear(),this.eventListeners.clear(),this.debounceTimers.clear(),this.persistState()}}let n=null;function l(){return n||(n=o.getInstance()),n}export{l as a,i as g,a as m};
1
+ import{a as t}from"./core.js";class e{static getInstance(){return e.instance||(e.instance=new e),e.instance}constructor(){this.playingWidgets=new Map,this.widgetConfigs=new Map,this.storageKey="widgetic_media_state",this.globalVolumeKey="widgetic_global_volume",this.storageVersion="2.0",this.eventListeners=new Map,this.autoResumeEnabled=!0,this.defaultAutoResumeTimeout=18e5,this.globalVolumeEnabled=!0,this.globalVolumeState={volume:1,muted:!1,lastUpdated:Date.now()},this.loadPersistedState(),this.loadGlobalVolumeState(),this.setupVisibilityHandler(),this.setupUnloadHandler(),setTimeout((()=>{this.autoResumeWidgets()}),1e3)}registerWidget(t,e={}){const s=Object.assign({autoPause:!0,mediaType:"both",priority:5,persistState:!0,allowSimultaneous:[],autoResume:!1,autoResumeTimeout:this.defaultAutoResumeTimeout,globalVolume:!0},e);this.widgetConfigs.set(t,s);const i=this.playingWidgets.get(t);i&&s.persistState?(s.globalVolume&&this.globalVolumeEnabled&&(i.volume=this.globalVolumeState.muted?0:this.globalVolumeState.volume),setTimeout((()=>{this.sendRestoreStateCommand(t,i)}),100)):s.globalVolume&&this.globalVolumeEnabled&&setTimeout((()=>{this.sendVolumeCommand(t,this.globalVolumeState.muted?0:this.globalVolumeState.volume)}),100)}unregisterWidget(t){this.handleMediaEvent({type:"stop",compositionId:t,config:this.widgetConfigs.get(t)||{}}),this.playingWidgets.delete(t),this.widgetConfigs.delete(t),this.eventListeners.delete(t)}handleMediaEvent(t){const{type:e,compositionId:s,config:i,data:a}=t;switch(e){case"play":this.handlePlayEvent(s,i,a);break;case"pause":this.handlePauseEvent(s,a);break;case"stop":case"ended":this.handleStopEvent(s);break;case"seeking":this.handleSeekingEvent(s,null==a?void 0:a.position);break;case"volumechange":this.handleVolumeEvent(s,null==a?void 0:a.volume);break;case"trackchange":this.handleTrackChangeEvent(s,a);break;case"playlistchange":this.handlePlaylistChangeEvent(s,a)}this.emitToListeners(s,t),i.persistState&&this.persistState(),this.dispatchGlobalEvent(t)}handlePlayEvent(t,e,s={}){const i=s.mediaType||e.mediaType||"both",a=e.priority||5,o={compositionId:t,mediaType:i,state:"playing",priority:a,startedAt:Date.now(),duration:s.duration,position:s.position||0,title:s.title,volume:s.volume,playlist:s.playlist,autoResume:e.autoResume,lastInteraction:Date.now()};!1!==e.autoPause&&this.pauseConflictingWidgets(t,i,a,e.allowSimultaneous||[]),this.playingWidgets.set(t,o)}handlePauseEvent(t,e={}){const s=this.playingWidgets.get(t);s&&(s.state="paused",s.position=e.position||s.position,s.volume=e.volume||s.volume,s.lastInteraction=Date.now())}handleStopEvent(t){const e=this.playingWidgets.get(t);e&&(e.state="stopped",e.position=0,e.lastInteraction=Date.now())}handleSeekingEvent(t,e){const s=this.playingWidgets.get(t);s&&void 0!==e&&(s.position=e,s.lastInteraction=Date.now())}handleVolumeEvent(t,e){const s=this.playingWidgets.get(t),i=this.widgetConfigs.get(t);s&&void 0!==e&&(s.lastInteraction=Date.now(),(null==i?void 0:i.globalVolume)&&this.globalVolumeEnabled?(this.globalVolumeState={volume:e>0?e:this.globalVolumeState.volume,muted:0===e,lastUpdated:Date.now(),lastChangedBy:t},this.persistGlobalVolumeState(),this.syncGlobalVolumeToWidgets(t),s.volume=this.globalVolumeState.muted?0:this.globalVolumeState.volume):s.volume=e)}handleTrackChangeEvent(t,e={}){const s=this.playingWidgets.get(t);s&&e.playlist&&(s.playlist=Object.assign(Object.assign({},s.playlist),e.playlist),s.position=0,s.title=e.playlist.trackTitle||s.title,s.lastInteraction=Date.now())}handlePlaylistChangeEvent(t,e={}){const s=this.playingWidgets.get(t);s&&e.playlist&&(s.playlist=Object.assign(Object.assign({},s.playlist),e.playlist),s.lastInteraction=Date.now())}pauseConflictingWidgets(t,e,s,i){const a=[];for(const[o,n]of this.playingWidgets){if(o===t||"playing"!==n.state)continue;this.isSimultaneousAllowed(n.mediaType,e,i)||(s>n.priority||s===n.priority&&Date.now()>n.startedAt)&&a.push(o)}for(const t of a)this.sendPauseCommand(t);a.length}isSimultaneousAllowed(t,e,s){return"both"!==t&&"both"!==e&&(t!==e&&(s.includes(t)&&s.includes(e)))}sendPauseCommand(e){var s;const i=document.querySelector(`[data-widgetic-id="${e}"], [data-composition-id="${e}"]`);if(i){if("iframe"===i.tagName.toLowerCase()){const a=i,o=t.CLIENT_URL||"*";null===(s=a.contentWindow)||void 0===s||s.postMessage({type:"widgetic:media:command",command:"pause",compositionId:e},o)}i.dispatchEvent(new CustomEvent("widgetic:media:command",{detail:{command:"pause",compositionId:e}}));const a=this.playingWidgets.get(e);a&&(a.state="paused")}}getPlayingWidgets(){return Array.from(this.playingWidgets.values()).filter((t=>"playing"===t.state))}getAllMediaWidgets(){return Array.from(this.playingWidgets.values())}pauseAll(){const t=this.getPlayingWidgets();for(const e of t)this.sendPauseCommand(e.compositionId)}resumeLastPlayed(){const t=Array.from(this.playingWidgets.values()).filter((t=>"paused"===t.state)).sort(((t,e)=>e.startedAt-t.startedAt));if(t.length>0){const e=t[0];this.sendResumeCommand(e.compositionId)}}sendResumeCommand(e){var s;const i=document.querySelector(`[data-widgetic-id="${e}"], [data-composition-id="${e}"]`);if(i){if("iframe"===i.tagName.toLowerCase()){const a=i,o=t.CLIENT_URL||"*";null===(s=a.contentWindow)||void 0===s||s.postMessage({type:"widgetic:media:command",command:"play",compositionId:e},o)}i.dispatchEvent(new CustomEvent("widgetic:media:command",{detail:{command:"play",compositionId:e}}))}}addEventListener(t,e){return this.eventListeners.has(t)||this.eventListeners.set(t,[]),this.eventListeners.get(t).push(e),()=>{const s=this.eventListeners.get(t);if(s){const t=s.indexOf(e);t>-1&&s.splice(t,1)}}}emitToListeners(t,e){const s=this.eventListeners.get(t);if(s)for(const t of s)try{t(e)}catch(t){}}dispatchGlobalEvent(t){document.dispatchEvent(new CustomEvent(`widgetic:media:${t.type}`,{detail:{compositionId:t.compositionId,config:t.config,data:t.data},bubbles:!0}))}loadPersistedState(){if("undefined"!=typeof localStorage)try{const t=localStorage.getItem(this.storageKey);if(t){const e=JSON.parse(t);if(e.version!==this.storageVersion)return void this.clearPersistedState();const s=864e5;if(e.timestamp&&Date.now()-e.timestamp>s)return void this.clearPersistedState();for(const[t,s]of Object.entries(e.playingWidgets||{})){const e=s;e.compositionId&&e.mediaType&&e.state&&this.playingWidgets.set(t,e)}}}catch(t){this.clearPersistedState()}}persistState(){try{const t={version:this.storageVersion,playingWidgets:Object.fromEntries(this.playingWidgets),timestamp:Date.now(),autoResumeEnabled:this.autoResumeEnabled};localStorage.setItem(this.storageKey,JSON.stringify(t))}catch(t){}}setupVisibilityHandler(){"undefined"!=typeof document&&document.addEventListener("visibilitychange",(()=>{document.hidden&&this.pauseAll()}))}setupUnloadHandler(){"undefined"!=typeof window&&window.addEventListener("beforeunload",(()=>{this.persistState()}))}clearPersistedState(t=!1){try{localStorage.removeItem(this.storageKey),t&&(localStorage.removeItem(this.globalVolumeKey),this.globalVolumeState={volume:1,muted:!1,lastUpdated:Date.now()})}catch(t){}}getStats(){const t=this.getPlayingWidgets(),e=Array.from(this.playingWidgets.values()).filter((t=>"paused"===t.state)),s=Array.from(this.playingWidgets.values()).filter((t=>t.playlist)),i=Array.from(this.widgetConfigs.values()).filter((t=>t.globalVolume)).length;return{totalWidgets:this.widgetConfigs.size,playingWidgets:t.length,pausedWidgets:e.length,registeredWidgets:this.playingWidgets.size,widgetsWithPlaylists:s.length,globalVolumeWidgets:i,autoResumeEnabled:this.autoResumeEnabled,globalVolumeEnabled:this.globalVolumeEnabled,globalVolume:{volume:this.globalVolumeState.volume,muted:this.globalVolumeState.muted,lastUpdated:this.globalVolumeState.lastUpdated,lastChangedBy:this.globalVolumeState.lastChangedBy},storageVersion:this.storageVersion,currentlyPlaying:t.map((t=>({compositionId:t.compositionId,mediaType:t.mediaType,priority:t.priority,duration:t.startedAt?Date.now()-t.startedAt:0,position:t.position,volume:t.volume,playlist:t.playlist?{currentTrack:t.playlist.currentTrack,totalTracks:t.playlist.totalTracks,trackTitle:t.playlist.trackTitle}:void 0}))),allWidgets:Array.from(this.playingWidgets.values()).map((t=>{var e;return{compositionId:t.compositionId,state:t.state,mediaType:t.mediaType,priority:t.priority,position:t.position,volume:t.volume,lastInteraction:t.lastInteraction,playlist:t.playlist,autoResume:t.autoResume,globalVolume:(null===(e=this.widgetConfigs.get(t.compositionId))||void 0===e?void 0:e.globalVolume)||!1}}))}}destroy(){this.pauseAll(),this.playingWidgets.clear(),this.widgetConfigs.clear(),this.eventListeners.clear(),this.persistState(),this.persistGlobalVolumeState()}autoResumeWidgets(t={}){if(!this.autoResumeEnabled)return;const{autoResumePlayback:e=!0,maxStateAge:s=this.defaultAutoResumeTimeout,respectTimeouts:i=!0}=t,a=Date.now(),o=[];for(const[t,n]of this.playingWidgets){const l=this.widgetConfigs.get(t);(null==l?void 0:l.autoResume)&&l.persistState&&n.lastInteraction&&(!i||a-n.lastInteraction<=(l.autoResumeTimeout||s))&&("playing"===n.state||e&&"paused"===n.state)&&o.push(n)}o.length>0&&(o.sort(((t,e)=>t.priority!==e.priority?e.priority-t.priority:(e.lastInteraction||0)-(t.lastInteraction||0))),e&&"playing"===o[0].state&&this.resumeWidget(o[0].compositionId))}resumeWidget(t){const e=this.playingWidgets.get(t),s=this.widgetConfigs.get(t);return!(!e||!s)&&(this.sendRestoreStateCommand(t,e),"playing"===e.state&&setTimeout((()=>{this.sendPlayCommand(t,e.position)}),100),!0)}sendRestoreStateCommand(e,s){var i;const a=document.querySelector(`[data-widgetic-id="${e}"], [data-composition-id="${e}"]`);if(a){const o={type:"widgetic:media:command",command:"restore",compositionId:e,state:{position:s.position||0,volume:s.volume||1,title:s.title,playlist:s.playlist,duration:s.duration}};if("iframe"===a.tagName.toLowerCase()){const e=a,s=t.CLIENT_URL||"*";null===(i=e.contentWindow)||void 0===i||i.postMessage(o,s)}a.dispatchEvent(new CustomEvent("widgetic:media:command",{detail:o}))}}sendPlayCommand(e,s){var i;const a=document.querySelector(`[data-widgetic-id="${e}"], [data-composition-id="${e}"]`);if(a){const o={type:"widgetic:media:command",command:"play",compositionId:e,position:s};if("iframe"===a.tagName.toLowerCase()){const e=a,s=t.CLIENT_URL||"*";null===(i=e.contentWindow)||void 0===i||i.postMessage(o,s)}a.dispatchEvent(new CustomEvent("widgetic:media:command",{detail:o}))}}getPersistedState(t){return this.playingWidgets.get(t)||null}updateWidgetState(t,e){const s=this.playingWidgets.get(t);if(s){const i=Object.assign(Object.assign(Object.assign({},s),e),{lastInteraction:Date.now()});this.playingWidgets.set(t,i);const a=this.widgetConfigs.get(t);(null==a?void 0:a.persistState)&&this.persistState()}}setAutoResumeEnabled(t){this.autoResumeEnabled=t}triggerAutoResume(t={}){this.autoResumeWidgets(t)}loadGlobalVolumeState(){if("undefined"!=typeof localStorage)try{const t=localStorage.getItem(this.globalVolumeKey);if(t){const e=JSON.parse(t);"number"==typeof e.volume&&"boolean"==typeof e.muted&&(this.globalVolumeState={volume:Math.max(0,Math.min(1,e.volume)),muted:e.muted,lastUpdated:e.lastUpdated||Date.now(),lastChangedBy:e.lastChangedBy})}}catch(t){}}persistGlobalVolumeState(){try{localStorage.setItem(this.globalVolumeKey,JSON.stringify(this.globalVolumeState))}catch(t){}}syncGlobalVolumeToWidgets(t){const e=this.globalVolumeState.muted?0:this.globalVolumeState.volume;for(const[s,i]of this.widgetConfigs)if(s!==t&&i.globalVolume){this.sendVolumeCommand(s,e);const t=this.playingWidgets.get(s);t&&(t.volume=e)}}sendVolumeCommand(e,s){var i;const a=document.querySelector(`[data-widgetic-id="${e}"], [data-composition-id="${e}"]`);if(a){const o={type:"widgetic:media:command",command:"setVolume",compositionId:e,volume:Math.max(0,Math.min(1,s))};if("iframe"===a.tagName.toLowerCase()){const e=a,s=t.CLIENT_URL||"*";null===(i=e.contentWindow)||void 0===i||i.postMessage(o,s)}a.dispatchEvent(new CustomEvent("widgetic:media:command",{detail:o}))}}getGlobalVolumeState(){return Object.assign({},this.globalVolumeState)}setGlobalVolume(t,e){const s=Math.max(0,Math.min(1,t));this.globalVolumeState={volume:s,muted:0===s,lastUpdated:Date.now(),lastChangedBy:e||"api"},this.persistGlobalVolumeState(),this.syncGlobalVolumeToWidgets()}toggleGlobalMute(t){return this.globalVolumeState=Object.assign(Object.assign({},this.globalVolumeState),{muted:!this.globalVolumeState.muted,lastUpdated:Date.now(),lastChangedBy:t||"api"}),this.persistGlobalVolumeState(),this.syncGlobalVolumeToWidgets(),this.globalVolumeState.muted}setGlobalVolumeEnabled(t){const e=this.globalVolumeEnabled;this.globalVolumeEnabled=t,t&&!e&&this.syncGlobalVolumeToWidgets()}isGlobalVolumeEnabled(){return this.globalVolumeEnabled}}let s=null;function i(){return s||(s=e.getInstance()),s}var a=Object.freeze({__proto__:null,MediaManager:e,getMediaManager:i,resetMediaManager:function(){s&&(s.destroy(),s=null)}});class o{static getInstance(){return o.instance||(o.instance=new o),o.instance}constructor(){this.contentStates=new Map,this.widgetConfigs=new Map,this.storageKey="widgetic_content_positions",this.storageVersion="1.0",this.eventListeners=new Map,this.autoResumeEnabled=!0,this.defaultAutoResumeTimeout=864e5,this.debounceTimers=new Map,this.loadPersistedState(),this.setupUnloadHandler(),setTimeout((()=>{this.autoResumePositions()}),1e3)}registerWidget(t,e={}){const s=Object.assign({contentType:"custom",persistState:!0,autoResume:!1,autoResumeTimeout:this.defaultAutoResumeTimeout,debounceDelay:500,trackMetadata:!1},e);this.widgetConfigs.set(t,s);const i=this.contentStates.get(t);i&&s.persistState&&setTimeout((()=>{this.sendRestorePositionCommand(t,i)}),100)}unregisterWidget(t){const e=this.debounceTimers.get(t);e&&(clearTimeout(e),this.debounceTimers.delete(t)),this.contentStates.delete(t),this.widgetConfigs.delete(t),this.eventListeners.delete(t)}handleContentPositionEvent(t){const{type:e,compositionId:s,config:i,data:a}=t;switch(e){case"position":case"navigate":this.handlePositionChangeEvent(s,i,a);break;case"complete":this.handleCompleteEvent(s,a);break;case"reset":this.handleResetEvent(s);break;case"metadata":this.handleMetadataEvent(s,a)}this.emitToListeners(s,t),i.persistState&&this.debouncedPersistState(s,i.debounceDelay||500),this.dispatchGlobalEvent(t)}handlePositionChangeEvent(t,e,s={}){const i=this.contentStates.get(t),a={compositionId:t,contentType:e.contentType||"custom",currentIndex:void 0!==s.currentIndex?s.currentIndex:(null==i?void 0:i.currentIndex)||0,totalItems:void 0!==s.totalItems?s.totalItems:(null==i?void 0:i.totalItems)||0,currentItemId:s.currentItemId||(null==i?void 0:i.currentItemId),currentItemTitle:s.currentItemTitle||(null==i?void 0:i.currentItemTitle),lastUpdated:Date.now(),autoResume:e.autoResume,lastInteraction:Date.now(),metadata:e.trackMetadata?Object.assign(Object.assign({},null==i?void 0:i.metadata),s.metadata):void 0};this.contentStates.set(t,a)}handleCompleteEvent(t,e={}){const s=this.contentStates.get(t);s&&(s.lastInteraction=Date.now(),s.metadata&&(s.metadata.completed=!0,s.metadata.completedAt=Date.now(),e.metadata&&Object.assign(s.metadata,e.metadata)))}handleResetEvent(t){const e=this.contentStates.get(t);e&&(e.currentIndex=0,e.currentItemId=void 0,e.currentItemTitle=void 0,e.lastInteraction=Date.now(),e.metadata&&(e.metadata.completed=!1,delete e.metadata.completedAt))}handleMetadataEvent(t,e={}){const s=this.contentStates.get(t);s&&e.metadata&&(s.metadata||(s.metadata={}),Object.assign(s.metadata,e.metadata),s.lastInteraction=Date.now())}loadPersistedState(){if("undefined"!=typeof localStorage)try{const t=localStorage.getItem(this.storageKey);if(t){const e=JSON.parse(t);if(e.version!==this.storageVersion)return void this.clearPersistedState();const s=6048e5;if(e.timestamp&&Date.now()-e.timestamp>s)return void this.clearPersistedState();for(const[t,s]of Object.entries(e.contentStates||{})){const e=s;e.compositionId&&e.contentType&&void 0!==e.currentIndex&&this.contentStates.set(t,e)}}}catch(t){this.clearPersistedState()}}debouncedPersistState(t,e){const s=this.debounceTimers.get(t);s&&clearTimeout(s);const i=setTimeout((()=>{this.persistState(),this.debounceTimers.delete(t)}),e);this.debounceTimers.set(t,i)}persistState(){try{const t={version:this.storageVersion,contentStates:Object.fromEntries(this.contentStates),timestamp:Date.now(),autoResumeEnabled:this.autoResumeEnabled};localStorage.setItem(this.storageKey,JSON.stringify(t))}catch(t){}}setupUnloadHandler(){"undefined"!=typeof window&&window.addEventListener("beforeunload",(()=>{for(const t of this.debounceTimers.values())clearTimeout(t);this.debounceTimers.clear(),this.persistState()}))}autoResumePositions(t={}){if(!this.autoResumeEnabled)return;const{autoResumePosition:e=!0,maxStateAge:s=this.defaultAutoResumeTimeout,respectTimeouts:i=!0}=t,a=Date.now(),o=[];for(const[t,n]of this.contentStates){const l=this.widgetConfigs.get(t);(null==l?void 0:l.autoResume)&&l.persistState&&n.lastInteraction&&(!i||a-n.lastInteraction<=(l.autoResumeTimeout||s))&&e&&o.push(n)}o.length>0&&o.forEach((t=>{this.resumeWidgetPosition(t.compositionId)}))}resumeWidgetPosition(t){const e=this.contentStates.get(t),s=this.widgetConfigs.get(t);return!(!e||!s)&&(this.sendRestorePositionCommand(t,e),!0)}sendRestorePositionCommand(e,s){var i;const a=document.querySelector(`[data-widgetic-id="${e}"], [data-composition-id="${e}"]`);if(a){const o={type:"widgetic:content:command",command:"restorePosition",compositionId:e,state:{currentIndex:s.currentIndex,totalItems:s.totalItems,currentItemId:s.currentItemId,currentItemTitle:s.currentItemTitle,metadata:s.metadata}};if("iframe"===a.tagName.toLowerCase()){const e=a,s=t.CLIENT_URL||"*";null===(i=e.contentWindow)||void 0===i||i.postMessage(o,s)}a.dispatchEvent(new CustomEvent("widgetic:content:command",{detail:o}))}}getAllContentWidgets(){return Array.from(this.contentStates.values())}getPersistedPosition(t){return this.contentStates.get(t)||null}updateWidgetPosition(t,e){const s=this.contentStates.get(t);if(s){const i=Object.assign(Object.assign(Object.assign({},s),e),{lastInteraction:Date.now()});this.contentStates.set(t,i);const a=this.widgetConfigs.get(t);(null==a?void 0:a.persistState)&&this.debouncedPersistState(t,a.debounceDelay||500)}}clearPersistedState(){try{localStorage.removeItem(this.storageKey)}catch(t){}}getStats(){const t=Array.from(this.contentStates.values()),e=t.reduce(((t,e)=>(t[e.contentType]=(t[e.contentType]||0)+1,t)),{});return{totalWidgets:this.widgetConfigs.size,trackedWidgets:this.contentStates.size,autoResumeEnabled:this.autoResumeEnabled,storageVersion:this.storageVersion,contentTypes:e,allWidgets:t.map((t=>({compositionId:t.compositionId,contentType:t.contentType,currentIndex:t.currentIndex,totalItems:t.totalItems,progress:t.totalItems>0?Math.round(t.currentIndex/(t.totalItems-1)*100):0,lastInteraction:t.lastInteraction,autoResume:t.autoResume,metadata:t.metadata})))}}addEventListener(t,e){return this.eventListeners.has(t)||this.eventListeners.set(t,[]),this.eventListeners.get(t).push(e),()=>{const s=this.eventListeners.get(t);if(s){const t=s.indexOf(e);t>-1&&s.splice(t,1)}}}emitToListeners(t,e){const s=this.eventListeners.get(t);if(s)for(const t of s)try{t(e)}catch(t){}}dispatchGlobalEvent(t){document.dispatchEvent(new CustomEvent(`widgetic:content:${t.type}`,{detail:{compositionId:t.compositionId,config:t.config,data:t.data},bubbles:!0}))}setAutoResumeEnabled(t){this.autoResumeEnabled=t}triggerAutoResume(t={}){this.autoResumePositions(t)}destroy(){for(const t of this.debounceTimers.values())clearTimeout(t);this.contentStates.clear(),this.widgetConfigs.clear(),this.eventListeners.clear(),this.debounceTimers.clear(),this.persistState()}}let n=null;function l(){return n||(n=o.getInstance()),n}export{l as a,i as g,a as m};
@@ -1 +1 @@
1
- import{_ as e}from"./vendor.js";import{l as t,c as s}from"./core.js";import"@widgetic/api-sdk";class n{constructor(e={}){this.messageHandlers=new Map,this.messageQueue=new Map,this.pendingMessages=new Map,this.heartbeatIntervals=new Map,this.sequenceNumbers=new Map,this.allowedOrigins=new Set,this.customEventSubscriptions=new Map,this.functionCallHandlers=new Map,this.pendingFunctionCalls=new Map,this.widgetControllers=new Map,this.securityOptions=Object.assign({enableSignatureValidation:!1,allowedOrigins:[],messageTimeout:3e4,enableHeartbeat:!1,heartbeatInterval:3e4},e),this.setupAllowedOrigins(this.securityOptions.allowedOrigins),this.setupGlobalMessageListener(),t.info("WidgeticMessenger initialized",{securityOptions:this.securityOptions})}setupAllowedOrigins(e){s.CLIENT_URL&&this.allowedOrigins.add(s.CLIENT_URL),"undefined"!=typeof window&&window.location&&this.allowedOrigins.add(window.location.origin),e&&e.forEach((e=>this.allowedOrigins.add(e)));const n=new Set;this.allowedOrigins.forEach((e=>{try{const t=new URL(e);n.add(t.origin)}catch(t){n.add(e)}})),this.allowedOrigins=n,t.debug("Allowed origins configured",{origins:Array.from(this.allowedOrigins)})}setupGlobalMessageListener(){"undefined"!=typeof window&&window.addEventListener("message",(e=>{this.handleIncomingMessage(e)}))}validateMessage(e){if(!this.allowedOrigins.has(e.origin))return t.warn("Message from unauthorized origin",{origin:e.origin}),null;try{const s="string"==typeof e.data?JSON.parse(e.data):e.data;return this.isValidWidgeticMessage(s)?this.securityOptions.enableSignatureValidation&&!this.validateSignature(s)?(t.warn("Message signature validation failed",{instanceId:s.instanceId}),null):s:(t.warn("Invalid message structure",{message:s}),null)}catch(s){return t.warn("Failed to parse message",{error:s,data:e.data}),null}}isValidWidgeticMessage(e){return e&&"string"==typeof e.type&&"string"==typeof e.instanceId&&"number"==typeof e.timestamp&&"string"==typeof e.version&&void 0!==e.payload}validateSignature(e){return!0}generateSignature(e){const t=JSON.stringify(Object.assign({},e));return btoa(t).substring(0,16)}handleIncomingMessage(e){const s=this.validateMessage(e);if(!s)return;switch(t.debug("Received valid message",{type:s.type,instanceId:s.instanceId}),s.type){case"heartbeat":return void this.handleHeartbeat(s);case"auth":return void this.handleAuthentication(s);case"custom-event":return void this.handleCustomEvent(s);case"function-call":return void this.handleFunctionCall(s);case"function-response":return void this.handleFunctionResponse(s);case"text-field-change":return void this.handleTextFieldChange(s)}const n=this.messageHandlers.get(s.instanceId);if(n)try{n(s)}catch(e){t.error("Message handler error",{error:e,instanceId:s.instanceId})}else t.debug("No handler for message",{instanceId:s.instanceId,type:s.type})}handleHeartbeat(e){t.debug("Heartbeat received",{instanceId:e.instanceId}),this.sendMessage(e.instanceId,{type:"heartbeat",instanceId:e.instanceId,payload:{response:!0},timestamp:Date.now(),version:"1.0"})}handleAuthentication(e){t.debug("Authentication message received",{instanceId:e.instanceId})}handleTextFieldChange(e){const{fieldId:s,text:n,metadata:i}=e.payload;s&&"string"==typeof n?(import("./security.js").then((function(e){return e.s})).then((({getSecurityManager:a})=>{const r=a().validateTextFieldUpdate(e.instanceId,s,n,i);if(!r.allowed)return t.warn("Text field change blocked by security",{instanceId:e.instanceId,fieldId:s,reason:r.reason,severity:r.severity}),void document.dispatchEvent(new CustomEvent("widgetic:text-field-security-blocked",{detail:{instanceId:e.instanceId,compositionId:e.compositionId,fieldId:s,reason:r.reason,severity:r.severity,originalTextLength:n.length,timestamp:Date.now()},bubbles:!0}));t.debug("Text field change received",{instanceId:e.instanceId,fieldId:s,textLength:n.length,sanitized:!(!r.sanitizedText||r.sanitizedText===n)}),import("./security.js").then((function(e){return e.t})).then((({getTextFieldManager:t})=>{const a=t(),o=r.sanitizedText||n;a.updateTextField(e.instanceId,s,o,{autoPersist:!0,persistState:!0,textType:(null==i?void 0:i.textType)||"custom",debounceDelay:(null==i?void 0:i.debounceDelay)||1e3,maxLength:null==i?void 0:i.maxLength},Object.assign(Object.assign({},i),{securityValidated:!0,sanitized:o!==n}))})).catch((s=>{t.warn("Failed to handle text field change",{error:s,instanceId:e.instanceId})}))})).catch((s=>{t.warn("Failed to validate text field security",{error:s,instanceId:e.instanceId})})),document.dispatchEvent(new CustomEvent("widgetic:text-field-change",{detail:{instanceId:e.instanceId,compositionId:e.compositionId,fieldId:s,text:n,metadata:i},bubbles:!0}))):t.warn("Invalid text field change message",{instanceId:e.instanceId,payload:e.payload})}handleCustomEvent(e){const{eventName:s,eventData:n,metadata:i}=e.payload,a=this.customEventSubscriptions.get(e.instanceId);if(!a)return;const r=a.get(s);r&&0!==r.size&&(t.debug("Dispatching custom event",{instanceId:e.instanceId,eventName:s,subscriberCount:r.size}),r.forEach((a=>{try{a(n,i)}catch(n){t.error("Custom event callback error",{error:n,eventName:s,instanceId:e.instanceId})}})),document.dispatchEvent(new CustomEvent(`widgetic:custom:${s}`,{detail:{instanceId:e.instanceId,compositionId:e.compositionId,eventName:s,eventData:n,metadata:i},bubbles:!0})))}handleFunctionCall(e){const{functionName:s,args:n,requestId:i}=e.payload,a=this.functionCallHandlers.get(e.instanceId);if(!a)return void this.sendFunctionResponse(e.instanceId,i,!1,void 0,"No function handlers registered");const r=a.get(s);if(r){t.debug("Executing function call",{instanceId:e.instanceId,functionName:s,args:n});try{const t=r(...n);t&&"function"==typeof t.then?t.then((t=>this.sendFunctionResponse(e.instanceId,i,!0,t))).catch((t=>this.sendFunctionResponse(e.instanceId,i,!1,void 0,t.message||"Function execution failed"))):this.sendFunctionResponse(e.instanceId,i,!0,t)}catch(t){this.sendFunctionResponse(e.instanceId,i,!1,void 0,t instanceof Error?t.message:"Function execution failed")}}else this.sendFunctionResponse(e.instanceId,i,!1,void 0,`Function '${s}' not found`)}handleFunctionResponse(e){const{requestId:s,success:n,result:i,error:a}=e.payload,r=this.pendingFunctionCalls.get(s);r?(clearTimeout(r.timeout),this.pendingFunctionCalls.delete(s),n?r.resolve(i):r.reject(new Error(a||"Function call failed"))):t.warn("Received response for unknown function call",{requestId:s})}sendFunctionResponse(e,t,s,n,i){this.sendMessage(e,{type:"function-response",instanceId:e,payload:{requestId:t,success:s,result:n,error:i},timestamp:Date.now(),version:"1.0"})}registerHandler(e,s){this.messageHandlers.set(e,s),t.debug("Message handler registered",{instanceId:e}),this.messageQueue.has(e)||this.messageQueue.set(e,[]),this.sequenceNumbers.set(e,0),this.securityOptions.enableHeartbeat&&this.startHeartbeat(e)}unregisterHandler(e){this.messageHandlers.delete(e),this.messageQueue.delete(e),this.sequenceNumbers.delete(e),this.stopHeartbeat(e),t.debug("Message handler unregistered",{instanceId:e})}sendMessage(e,s){const n=document.querySelector(`[data-widgetic-id="${e}"]`);if(!n||!n.contentWindow)return t.warn("Cannot send message - iframe not found",{instanceId:e}),void this.queueMessage(e,s);const i=this.getNextSequence(e),a=Object.assign(Object.assign({},s),{sequence:i});this.securityOptions.enableSignatureValidation&&(a.signature=this.generateSignature(a));try{n.contentWindow.postMessage(JSON.stringify(a),"*"),t.debug("Message sent",{instanceId:e,type:a.type,sequence:i})}catch(n){t.error("Failed to send message",{error:n,instanceId:e}),this.queueMessage(e,s)}}queueMessage(e,t){const s=this.messageQueue.get(e)||[];s.push({message:t,retryCount:0,maxRetries:3,timestamp:Date.now()}),this.messageQueue.set(e,s),this.scheduleRetry(e)}scheduleRetry(e){if(this.pendingMessages.has(e))return;const t=setTimeout((()=>{this.processMessageQueue(e),this.pendingMessages.delete(e)}),1e3);this.pendingMessages.set(e,t)}processMessageQueue(e){const s=this.messageQueue.get(e);if(!s||0===s.length)return;const n=[];s.forEach((s=>{s.retryCount<s.maxRetries?(s.retryCount++,this.sendMessage(e,s.message),s.retryCount<s.maxRetries&&n.push(s)):t.warn("Message retry limit exceeded",{instanceId:e,message:s.message})})),this.messageQueue.set(e,n)}getNextSequence(e){const t=(this.sequenceNumbers.get(e)||0)+1;return this.sequenceNumbers.set(e,t),t}startHeartbeat(e){if(this.heartbeatIntervals.has(e))return;const s=setInterval((()=>{this.sendMessage(e,{type:"heartbeat",instanceId:e,payload:{ping:Date.now()},timestamp:Date.now(),version:"1.0"})}),this.securityOptions.heartbeatInterval);this.heartbeatIntervals.set(e,s),t.debug("Heartbeat started",{instanceId:e,interval:this.securityOptions.heartbeatInterval})}stopHeartbeat(e){const s=this.heartbeatIntervals.get(e);s&&(clearInterval(s),this.heartbeatIntervals.delete(e),t.debug("Heartbeat stopped",{instanceId:e}))}cleanup(){this.heartbeatIntervals.forEach((e=>clearInterval(e))),this.heartbeatIntervals.clear(),this.pendingMessages.forEach((e=>clearTimeout(e))),this.pendingMessages.clear(),this.messageHandlers.clear(),this.messageQueue.clear(),this.sequenceNumbers.clear(),t.info("WidgeticMessenger cleanup complete")}createWidgetController(t,s){const n={subscribe:(e,s)=>this.subscribeToCustomEvent(t,e,s),unsubscribe:(e,s)=>{this.unsubscribeFromCustomEvent(t,e,s)},callFunction:(e,...s)=>this.callWidgetFunction(t,e,s),getState:e=>this.callWidgetFunction(t,"getState",e?[e]:[]),setState:(e,s)=>this.callWidgetFunction(t,"setState",[e,s]),updateConfig:e=>this.callWidgetFunction(t,"updateConfig",[e]),refresh:()=>this.callWidgetFunction(t,"refresh",[]),destroy:()=>this.callWidgetFunction(t,"destroy",[]),emit:(e,s,n)=>{this.sendCustomEvent(t,e,s,n)},registerTextField:(s,n)=>e(this,void 0,void 0,(function*(){const{getTextFieldManager:e}=yield import("./security.js").then((function(e){return e.t}));return e().registerTextField(t,s,n)})),updateTextField:(s,n,i)=>e(this,void 0,void 0,(function*(){const{getTextFieldManager:e}=yield import("./security.js").then((function(e){return e.t}));e().updateTextField(t,s,n,{autoPersist:!0,persistState:!0},i)})),getTextField:s=>e(this,void 0,void 0,(function*(){const{getTextFieldManager:e}=yield import("./security.js").then((function(e){return e.t}));return e().getTextField(t,s)})),clearTextField:s=>e(this,void 0,void 0,(function*(){const{getTextFieldManager:e}=yield import("./security.js").then((function(e){return e.t}));e().clearTextField(t,s)})),getTextFields:()=>e(this,void 0,void 0,(function*(){const{getTextFieldManager:e}=yield import("./security.js").then((function(e){return e.t}));return e().getWidgetTextFields(t)})),clearAllTextFields:()=>e(this,void 0,void 0,(function*(){const{getTextFieldManager:e}=yield import("./security.js").then((function(e){return e.t}));e().clearWidgetTextFields(t)}))};return this.widgetControllers.set(t,n),n}subscribeToCustomEvent(e,s,n){this.customEventSubscriptions.has(e)||this.customEventSubscriptions.set(e,new Map);const i=this.customEventSubscriptions.get(e);i.has(s)||i.set(s,new Set);const a=i.get(s);return a.add(n),t.debug("Subscribed to custom event",{instanceId:e,eventName:s,totalSubscribers:a.size}),()=>{a.delete(n),0===a.size&&i.delete(s),0===i.size&&this.customEventSubscriptions.delete(e)}}unsubscribeFromCustomEvent(e,s,n){const i=this.customEventSubscriptions.get(e);if(!i)return;const a=i.get(s);a&&(n?a.delete(n):a.clear(),0===a.size&&i.delete(s),0===i.size&&this.customEventSubscriptions.delete(e),t.debug("Unsubscribed from custom event",{instanceId:e,eventName:s}))}callWidgetFunction(e,s,n,i=1e4){return new Promise(((a,r)=>{const o=`${e}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,d=setTimeout((()=>{this.pendingFunctionCalls.delete(o),r(new Error(`Function call timeout: ${s}`))}),i);this.pendingFunctionCalls.set(o,{resolve:a,reject:r,timeout:d}),this.sendMessage(e,{type:"function-call",instanceId:e,payload:{functionName:s,args:n,requestId:o},timestamp:Date.now(),version:"1.0"}),t.debug("Sent function call",{instanceId:e,functionName:s,args:n,requestId:o})}))}sendCustomEvent(e,s,n,i){this.sendMessage(e,{type:"custom-event",instanceId:e,payload:{eventName:s,eventData:n,metadata:i},timestamp:Date.now(),version:"1.0"}),t.debug("Sent custom event",{instanceId:e,eventName:s})}registerFunctionHandlers(e,s){this.functionCallHandlers.has(e)||this.functionCallHandlers.set(e,new Map);const n=this.functionCallHandlers.get(e);Object.entries(s).forEach((([e,t])=>{n.set(e,t)})),t.debug("Registered function handlers",{instanceId:e,functions:Object.keys(s)})}unregisterFunctionHandlers(e,s){const n=this.functionCallHandlers.get(e);n&&(s?s.forEach((e=>n.delete(e))):n.clear(),0===n.size&&this.functionCallHandlers.delete(e),t.debug("Unregistered function handlers",{instanceId:e,functions:s||"all"}))}getWidgetController(e){return this.widgetControllers.get(e)||null}removeWidgetController(e){this.customEventSubscriptions.delete(e),this.functionCallHandlers.delete(e);const s=[];this.pendingFunctionCalls.forEach(((t,n)=>{n.startsWith(e)&&(clearTimeout(t.timeout),t.reject(new Error("Widget controller removed")),s.push(n))})),s.forEach((e=>this.pendingFunctionCalls.delete(e))),this.widgetControllers.delete(e),t.debug("Removed widget controller",{instanceId:e})}isActive(){return this.messageHandlers.size>0||this.widgetControllers.size>0}getCustomEventSubscriptions(){let e=0;return this.customEventSubscriptions.forEach((t=>{t.forEach((t=>{e+=t.size}))})),e}getFunctionHandlers(){let e=0;return this.functionCallHandlers.forEach((t=>{e+=t.size})),e}getMessagingStats(){return{activeHandlers:this.messageHandlers.size,widgetControllers:this.widgetControllers.size,customEventSubscriptions:this.getCustomEventSubscriptions(),functionHandlers:this.getFunctionHandlers(),pendingFunctionCalls:this.pendingFunctionCalls.size,heartbeatIntervals:this.heartbeatIntervals.size,messageQueues:Array.from(this.messageQueue.entries()).map((([e,t])=>({instanceId:e,queuedMessages:t.length})))}}}let i=null;function a(e){return i||(i=new n(e)),i}function r(){i&&(i.cleanup(),i=null)}export{n as WidgeticMessenger,a as getMessenger,r as resetMessenger};
1
+ import{_ as e}from"./vendor.js";import{l as t,a as s}from"./core.js";import"./api.js";import"./renderers.js";import"./media.js";import"./messaging.js";import"./display.js";import"./advanced.js";import"./scanner.js";import"./performance.js";import"./security.js";class n{constructor(e={}){this.messageHandlers=new Map,this.messageQueue=new Map,this.pendingMessages=new Map,this.heartbeatIntervals=new Map,this.sequenceNumbers=new Map,this.allowedOrigins=new Set,this.customEventSubscriptions=new Map,this.functionCallHandlers=new Map,this.pendingFunctionCalls=new Map,this.widgetControllers=new Map,this.securityOptions=Object.assign({enableSignatureValidation:!1,allowedOrigins:[],messageTimeout:3e4,enableHeartbeat:!1,heartbeatInterval:3e4},e),this.setupAllowedOrigins(this.securityOptions.allowedOrigins),this.setupGlobalMessageListener(),t.info("WidgeticMessenger initialized",{securityOptions:this.securityOptions})}setupAllowedOrigins(e){s.CLIENT_URL&&this.allowedOrigins.add(s.CLIENT_URL),"undefined"!=typeof window&&window.location&&this.allowedOrigins.add(window.location.origin),e&&e.forEach((e=>this.allowedOrigins.add(e)));const n=new Set;this.allowedOrigins.forEach((e=>{try{const t=new URL(e);n.add(t.origin)}catch(t){n.add(e)}})),this.allowedOrigins=n,t.debug("Allowed origins configured",{origins:Array.from(this.allowedOrigins)})}setupGlobalMessageListener(){"undefined"!=typeof window&&window.addEventListener("message",(e=>{this.handleIncomingMessage(e)}))}validateMessage(e){if(!this.allowedOrigins.has(e.origin))return t.warn("Message from unauthorized origin",{origin:e.origin}),null;try{const s="string"==typeof e.data?JSON.parse(e.data):e.data;return this.isValidWidgeticMessage(s)?this.securityOptions.enableSignatureValidation&&!this.validateSignature(s)?(t.warn("Message signature validation failed",{instanceId:s.instanceId}),null):s:(t.warn("Invalid message structure",{message:s}),null)}catch(s){return t.warn("Failed to parse message",{error:s,data:e.data}),null}}isValidWidgeticMessage(e){return e&&"string"==typeof e.type&&"string"==typeof e.instanceId&&"number"==typeof e.timestamp&&"string"==typeof e.version&&void 0!==e.payload}validateSignature(e){return!0}generateSignature(e){const t=JSON.stringify(Object.assign({},e));return btoa(t).substring(0,16)}handleIncomingMessage(e){const s=this.validateMessage(e);if(!s)return;switch(t.debug("Received valid message",{type:s.type,instanceId:s.instanceId}),s.type){case"heartbeat":return void this.handleHeartbeat(s);case"auth":return void this.handleAuthentication(s);case"custom-event":return void this.handleCustomEvent(s);case"function-call":return void this.handleFunctionCall(s);case"function-response":return void this.handleFunctionResponse(s);case"text-field-change":return void this.handleTextFieldChange(s)}const n=this.messageHandlers.get(s.instanceId);if(n)try{n(s)}catch(e){t.error("Message handler error",{error:e,instanceId:s.instanceId})}else t.debug("No handler for message",{instanceId:s.instanceId,type:s.type})}handleHeartbeat(e){t.debug("Heartbeat received",{instanceId:e.instanceId}),this.sendMessage(e.instanceId,{type:"heartbeat",instanceId:e.instanceId,payload:{response:!0},timestamp:Date.now(),version:"1.0"})}handleAuthentication(e){t.debug("Authentication message received",{instanceId:e.instanceId})}handleTextFieldChange(e){const{fieldId:s,text:n,metadata:i}=e.payload;s&&"string"==typeof n?(import("./security.js").then((function(e){return e.s})).then((({getSecurityManager:a})=>{const r=a().validateTextFieldUpdate(e.instanceId,s,n,i);if(!r.allowed)return t.warn("Text field change blocked by security",{instanceId:e.instanceId,fieldId:s,reason:r.reason,severity:r.severity}),void document.dispatchEvent(new CustomEvent("widgetic:text-field-security-blocked",{detail:{instanceId:e.instanceId,compositionId:e.compositionId,fieldId:s,reason:r.reason,severity:r.severity,originalTextLength:n.length,timestamp:Date.now()},bubbles:!0}));t.debug("Text field change received",{instanceId:e.instanceId,fieldId:s,textLength:n.length,sanitized:!(!r.sanitizedText||r.sanitizedText===n)}),import("./security.js").then((function(e){return e.t})).then((({getTextFieldManager:t})=>{const a=t(),o=r.sanitizedText||n;a.updateTextField(e.instanceId,s,o,{autoPersist:!0,persistState:!0,textType:(null==i?void 0:i.textType)||"custom",debounceDelay:(null==i?void 0:i.debounceDelay)||1e3,maxLength:null==i?void 0:i.maxLength},Object.assign(Object.assign({},i),{securityValidated:!0,sanitized:o!==n}))})).catch((s=>{t.warn("Failed to handle text field change",{error:s,instanceId:e.instanceId})}))})).catch((s=>{t.warn("Failed to validate text field security",{error:s,instanceId:e.instanceId})})),document.dispatchEvent(new CustomEvent("widgetic:text-field-change",{detail:{instanceId:e.instanceId,compositionId:e.compositionId,fieldId:s,text:n,metadata:i},bubbles:!0}))):t.warn("Invalid text field change message",{instanceId:e.instanceId,payload:e.payload})}handleCustomEvent(e){const{eventName:s,eventData:n,metadata:i}=e.payload,a=this.customEventSubscriptions.get(e.instanceId);if(!a)return;const r=a.get(s);r&&0!==r.size&&(t.debug("Dispatching custom event",{instanceId:e.instanceId,eventName:s,subscriberCount:r.size}),r.forEach((a=>{try{a(n,i)}catch(n){t.error("Custom event callback error",{error:n,eventName:s,instanceId:e.instanceId})}})),document.dispatchEvent(new CustomEvent(`widgetic:custom:${s}`,{detail:{instanceId:e.instanceId,compositionId:e.compositionId,eventName:s,eventData:n,metadata:i},bubbles:!0})))}handleFunctionCall(e){const{functionName:s,args:n,requestId:i}=e.payload,a=this.functionCallHandlers.get(e.instanceId);if(!a)return void this.sendFunctionResponse(e.instanceId,i,!1,void 0,"No function handlers registered");const r=a.get(s);if(r){t.debug("Executing function call",{instanceId:e.instanceId,functionName:s,args:n});try{const t=r(...n);t&&"function"==typeof t.then?t.then((t=>this.sendFunctionResponse(e.instanceId,i,!0,t))).catch((t=>this.sendFunctionResponse(e.instanceId,i,!1,void 0,t.message||"Function execution failed"))):this.sendFunctionResponse(e.instanceId,i,!0,t)}catch(t){this.sendFunctionResponse(e.instanceId,i,!1,void 0,t instanceof Error?t.message:"Function execution failed")}}else this.sendFunctionResponse(e.instanceId,i,!1,void 0,`Function '${s}' not found`)}handleFunctionResponse(e){const{requestId:s,success:n,result:i,error:a}=e.payload,r=this.pendingFunctionCalls.get(s);r?(clearTimeout(r.timeout),this.pendingFunctionCalls.delete(s),n?r.resolve(i):r.reject(new Error(a||"Function call failed"))):t.warn("Received response for unknown function call",{requestId:s})}sendFunctionResponse(e,t,s,n,i){this.sendMessage(e,{type:"function-response",instanceId:e,payload:{requestId:t,success:s,result:n,error:i},timestamp:Date.now(),version:"1.0"})}registerHandler(e,s){this.messageHandlers.set(e,s),t.debug("Message handler registered",{instanceId:e}),this.messageQueue.has(e)||this.messageQueue.set(e,[]),this.sequenceNumbers.set(e,0),this.securityOptions.enableHeartbeat&&this.startHeartbeat(e)}unregisterHandler(e){this.messageHandlers.delete(e),this.messageQueue.delete(e),this.sequenceNumbers.delete(e),this.stopHeartbeat(e),t.debug("Message handler unregistered",{instanceId:e})}sendMessage(e,s){const n=document.querySelector(`[data-widgetic-id="${e}"]`);if(!n||!n.contentWindow)return t.warn("Cannot send message - iframe not found",{instanceId:e}),void this.queueMessage(e,s);const i=this.getNextSequence(e),a=Object.assign(Object.assign({},s),{sequence:i});this.securityOptions.enableSignatureValidation&&(a.signature=this.generateSignature(a));try{n.contentWindow.postMessage(JSON.stringify(a),"*"),t.debug("Message sent",{instanceId:e,type:a.type,sequence:i})}catch(n){t.error("Failed to send message",{error:n,instanceId:e}),this.queueMessage(e,s)}}queueMessage(e,t){const s=this.messageQueue.get(e)||[];s.push({message:t,retryCount:0,maxRetries:3,timestamp:Date.now()}),this.messageQueue.set(e,s),this.scheduleRetry(e)}scheduleRetry(e){if(this.pendingMessages.has(e))return;const t=setTimeout((()=>{this.processMessageQueue(e),this.pendingMessages.delete(e)}),1e3);this.pendingMessages.set(e,t)}processMessageQueue(e){const s=this.messageQueue.get(e);if(!s||0===s.length)return;const n=[];s.forEach((s=>{s.retryCount<s.maxRetries?(s.retryCount++,this.sendMessage(e,s.message),s.retryCount<s.maxRetries&&n.push(s)):t.warn("Message retry limit exceeded",{instanceId:e,message:s.message})})),this.messageQueue.set(e,n)}getNextSequence(e){const t=(this.sequenceNumbers.get(e)||0)+1;return this.sequenceNumbers.set(e,t),t}startHeartbeat(e){if(this.heartbeatIntervals.has(e))return;const s=setInterval((()=>{this.sendMessage(e,{type:"heartbeat",instanceId:e,payload:{ping:Date.now()},timestamp:Date.now(),version:"1.0"})}),this.securityOptions.heartbeatInterval);this.heartbeatIntervals.set(e,s),t.debug("Heartbeat started",{instanceId:e,interval:this.securityOptions.heartbeatInterval})}stopHeartbeat(e){const s=this.heartbeatIntervals.get(e);s&&(clearInterval(s),this.heartbeatIntervals.delete(e),t.debug("Heartbeat stopped",{instanceId:e}))}cleanup(){this.heartbeatIntervals.forEach((e=>clearInterval(e))),this.heartbeatIntervals.clear(),this.pendingMessages.forEach((e=>clearTimeout(e))),this.pendingMessages.clear(),this.messageHandlers.clear(),this.messageQueue.clear(),this.sequenceNumbers.clear(),t.info("WidgeticMessenger cleanup complete")}createWidgetController(t,s){const n={subscribe:(e,s)=>this.subscribeToCustomEvent(t,e,s),unsubscribe:(e,s)=>{this.unsubscribeFromCustomEvent(t,e,s)},callFunction:(e,...s)=>this.callWidgetFunction(t,e,s),getState:e=>this.callWidgetFunction(t,"getState",e?[e]:[]),setState:(e,s)=>this.callWidgetFunction(t,"setState",[e,s]),updateConfig:e=>this.callWidgetFunction(t,"updateConfig",[e]),refresh:()=>this.callWidgetFunction(t,"refresh",[]),destroy:()=>this.callWidgetFunction(t,"destroy",[]),emit:(e,s,n)=>{this.sendCustomEvent(t,e,s,n)},registerTextField:(s,n)=>e(this,void 0,void 0,(function*(){const{getTextFieldManager:e}=yield import("./security.js").then((function(e){return e.t}));return e().registerTextField(t,s,n)})),updateTextField:(s,n,i)=>e(this,void 0,void 0,(function*(){const{getTextFieldManager:e}=yield import("./security.js").then((function(e){return e.t}));e().updateTextField(t,s,n,{autoPersist:!0,persistState:!0},i)})),getTextField:s=>e(this,void 0,void 0,(function*(){const{getTextFieldManager:e}=yield import("./security.js").then((function(e){return e.t}));return e().getTextField(t,s)})),clearTextField:s=>e(this,void 0,void 0,(function*(){const{getTextFieldManager:e}=yield import("./security.js").then((function(e){return e.t}));e().clearTextField(t,s)})),getTextFields:()=>e(this,void 0,void 0,(function*(){const{getTextFieldManager:e}=yield import("./security.js").then((function(e){return e.t}));return e().getWidgetTextFields(t)})),clearAllTextFields:()=>e(this,void 0,void 0,(function*(){const{getTextFieldManager:e}=yield import("./security.js").then((function(e){return e.t}));e().clearWidgetTextFields(t)}))};return this.widgetControllers.set(t,n),n}subscribeToCustomEvent(e,s,n){this.customEventSubscriptions.has(e)||this.customEventSubscriptions.set(e,new Map);const i=this.customEventSubscriptions.get(e);i.has(s)||i.set(s,new Set);const a=i.get(s);return a.add(n),t.debug("Subscribed to custom event",{instanceId:e,eventName:s,totalSubscribers:a.size}),()=>{a.delete(n),0===a.size&&i.delete(s),0===i.size&&this.customEventSubscriptions.delete(e)}}unsubscribeFromCustomEvent(e,s,n){const i=this.customEventSubscriptions.get(e);if(!i)return;const a=i.get(s);a&&(n?a.delete(n):a.clear(),0===a.size&&i.delete(s),0===i.size&&this.customEventSubscriptions.delete(e),t.debug("Unsubscribed from custom event",{instanceId:e,eventName:s}))}callWidgetFunction(e,s,n,i=1e4){return new Promise(((a,r)=>{const o=`${e}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,d=setTimeout((()=>{this.pendingFunctionCalls.delete(o),r(new Error(`Function call timeout: ${s}`))}),i);this.pendingFunctionCalls.set(o,{resolve:a,reject:r,timeout:d}),this.sendMessage(e,{type:"function-call",instanceId:e,payload:{functionName:s,args:n,requestId:o},timestamp:Date.now(),version:"1.0"}),t.debug("Sent function call",{instanceId:e,functionName:s,args:n,requestId:o})}))}sendCustomEvent(e,s,n,i){this.sendMessage(e,{type:"custom-event",instanceId:e,payload:{eventName:s,eventData:n,metadata:i},timestamp:Date.now(),version:"1.0"}),t.debug("Sent custom event",{instanceId:e,eventName:s})}registerFunctionHandlers(e,s){this.functionCallHandlers.has(e)||this.functionCallHandlers.set(e,new Map);const n=this.functionCallHandlers.get(e);Object.entries(s).forEach((([e,t])=>{n.set(e,t)})),t.debug("Registered function handlers",{instanceId:e,functions:Object.keys(s)})}unregisterFunctionHandlers(e,s){const n=this.functionCallHandlers.get(e);n&&(s?s.forEach((e=>n.delete(e))):n.clear(),0===n.size&&this.functionCallHandlers.delete(e),t.debug("Unregistered function handlers",{instanceId:e,functions:s||"all"}))}getWidgetController(e){return this.widgetControllers.get(e)||null}removeWidgetController(e){this.customEventSubscriptions.delete(e),this.functionCallHandlers.delete(e);const s=[];this.pendingFunctionCalls.forEach(((t,n)=>{n.startsWith(e)&&(clearTimeout(t.timeout),t.reject(new Error("Widget controller removed")),s.push(n))})),s.forEach((e=>this.pendingFunctionCalls.delete(e))),this.widgetControllers.delete(e),t.debug("Removed widget controller",{instanceId:e})}isActive(){return this.messageHandlers.size>0||this.widgetControllers.size>0}getCustomEventSubscriptions(){let e=0;return this.customEventSubscriptions.forEach((t=>{t.forEach((t=>{e+=t.size}))})),e}getFunctionHandlers(){let e=0;return this.functionCallHandlers.forEach((t=>{e+=t.size})),e}getMessagingStats(){return{activeHandlers:this.messageHandlers.size,widgetControllers:this.widgetControllers.size,customEventSubscriptions:this.getCustomEventSubscriptions(),functionHandlers:this.getFunctionHandlers(),pendingFunctionCalls:this.pendingFunctionCalls.size,heartbeatIntervals:this.heartbeatIntervals.size,messageQueues:Array.from(this.messageQueue.entries()).map((([e,t])=>({instanceId:e,queuedMessages:t.length})))}}}let i=null;function a(e){return i||(i=new n(e)),i}function r(){i&&(i.cleanup(),i=null)}export{n as WidgeticMessenger,a as getMessenger,r as resetMessenger};