@widgetic/embed-sdk 2.0.12 → 2.0.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser/chunks/ABTestManager.js +1 -1
- package/dist/browser/chunks/advanced.js +1 -1
- package/dist/browser/chunks/api.js +1 -1
- package/dist/browser/chunks/media.js +1 -1
- package/dist/browser/chunks/messaging.js +1 -1
- package/dist/browser/chunks/renderers.js +1 -1
- package/dist/browser/chunks/scanner.js +1 -1
- package/dist/browser/chunks/security.js +1 -1
- package/dist/browser/embed-bootstrap.js +1 -1
- package/dist/browser/embed-sdk.js +1 -1
- package/dist/esm/chunks/ABTestManager.js +1 -1
- package/dist/esm/chunks/advanced.js +1 -1
- package/dist/esm/chunks/api.js +1 -1
- package/dist/esm/chunks/media.js +1 -1
- package/dist/esm/chunks/messaging.js +1 -1
- package/dist/esm/chunks/renderers.js +1 -1
- package/dist/esm/chunks/scanner.js +1 -1
- package/dist/esm/chunks/security.js +1 -1
- package/dist/esm/embed-bootstrap.js +1 -1
- package/dist/esm/embed-sdk.js +1 -1
- package/dist/esm/types/core/content-position-manager.d.ts +4 -0
- package/dist/esm/types/core/media-manager.d.ts +18 -1
- package/dist/esm/types/core/realtime-manager.d.ts +9 -2
- package/dist/esm/types/utils/declarative-embed-parser.d.ts +84 -0
- package/dist/esm/types/utils/hydrate-published-host.d.ts +14 -0
- package/dist/esm/types/utils/mount-direct-widget.d.ts +9 -0
- package/dist/esm/types/utils/public-embed-lookup.d.ts +11 -0
- package/dist/esm/types/utils/published-host-bridge.d.ts +24 -0
- package/dist/umd/embed-bootstrap.js +1 -1
- package/dist/umd/embed-sdk.js +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{g as e,W as t,r as i,a as n,C as o,I as s}from"./renderers.js";import{_ as r,a}from"./vendor.js";import{g as d,S as c,l,b as h,A as g,d as u,e as p,V as m,f as v,a as f,P as y,h as w,D as b,s as I,i as T,j as S,k}from"./core.js";import{p as E,d as M,i as C,a as D,g as A}from"./scanner.js";import{getMessenger as W,WidgeticMessenger as O}from"./messaging.js";import{C as x,T as L,a as R,W as U,c as z,t as P,g as _,b as j,d as F}from"./advanced.js";import{D as H,g as B,a as $,b as N}from"./display.js";import{g as K,i as V,a as q,b as Y,c as Q,d as G}from"./performance.js";import{g as J,S as X}from"./security.js";class Z{constructor(e){this.apiKey=e}getToken(){return r(this,void 0,void 0,(function*(){return this.apiKey}))}isTokenValid(){return r(this,void 0,void 0,(function*(){return!!this.apiKey}))}}class ee{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 r(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 r(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 r(this,void 0,void 0,(function*(){return!!this.cachedToken&&(!this.tokenExpiry||Date.now()<this.tokenExpiry)}))}}class te{constructor(e,t){this.tokenFunction=e,this.validationFunction=t}getToken(){return r(this,void 0,void 0,(function*(){return yield this.tokenFunction()}))}isTokenValid(){return r(this,void 0,void 0,(function*(){return!this.validationFunction||(yield this.validationFunction())}))}}class ie{constructor(e){this.apiKey=e}getToken(){return r(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 r(this,void 0,void 0,(function*(){return!!this.apiKey}))}}class ne extends Error{constructor(e,t,i){super(e),this.code=t,this.statusCode=i,this.name="AuthError"}}class oe{constructor(e={}){var t,i;this.currentToken=null,this.apiKey=null,this.refreshTimer=null,this.config=Object.assign({apiUrl:e.apiUrl||d(),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===(i={NODE_ENV:"production"})||void 0===i?void 0:i.API_KEY))||null}createTokensApiForApiKey(e){const t=new x({basePath:this.config.apiUrl,apiKey:()=>r(this,void 0,void 0,(function*(){return e})),headers:{"X-SDK-Version":`embed-sdk/${c}`}});return new L(t)}createTokensApiForAccessToken(e){const t=new x({basePath:this.config.apiUrl,accessToken:()=>r(this,void 0,void 0,(function*(){return e})),headers:{"X-SDK-Version":`embed-sdk/${c}`}});return new L(t)}setApiKey(e){this.apiKey=e,this.currentToken={token:e,tokenType:"API-Key",expiresAt:null,scopes:[]},this.config.debug&&l.debug("AuthManager: API key set")}getValidToken(e){return r(this,void 0,void 0,(function*(){if(this.currentToken&&this.isTokenValid(this.currentToken)){if(oe.validatedTokens.has(this.currentToken.token))return this.currentToken.token;if(yield this.validateToken())return this.currentToken.token}if(this.apiKey)return yield this.exchangeApiKeyForJWT(e),this.currentToken.token;throw new ne("No authentication method available","NO_AUTH_METHOD")}))}exchangeApiKeyForJWT(e){return r(this,void 0,void 0,(function*(){var t;if(!this.apiKey)throw new ne("No API key available for exchange","NO_API_KEY");const i={scopes:(null==e?void 0:e.scopes)||this.getDefaultScopes(),expiresIn:(null==e?void 0:e.expiresIn)||1800};try{const e=this.createTokensApiForApiKey(this.apiKey),n=yield e.exchangeToken({exchangeTokenRequest:i}),o=(null===(t=null==n?void 0:n.data)||void 0===t?void 0:t.token)||(null==n?void 0:n.token);if(!o)throw new ne("Token exchange response missing token","INVALID_RESPONSE");const s=(null==n?void 0:n.data)||n,r={token:o,tokenType:s.tokenType||"Bearer",expiresAt:s.expiresAt?s.expiresAt instanceof Date?s.expiresAt.toISOString():String(s.expiresAt):null,scopes:s.scopes||[]};return this.setToken(r),this.config.debug&&l.info("AuthManager: Token exchanged successfully",{scopes:r.scopes,expiresAt:r.expiresAt}),r}catch(e){const t=e instanceof ne?e:new ne(`Token exchange failed: ${e instanceof Error?e.message:String(e)}`,"TOKEN_EXCHANGE_ERROR");throw this.config.onAuthError&&this.config.onAuthError(t),t}}))}validateToken(){return r(this,void 0,void 0,(function*(){var e;if(!this.currentToken)return!1;if(oe.validatedTokens.has(this.currentToken.token))return!0;try{const t=this.createTokensApiForAccessToken(this.currentToken.token),i=yield t.validateToken();return!0===(null==i?void 0:i.success)&&!0===(null===(e=i.data)||void 0===e?void 0:e.valid)||!0===(null==i?void 0:i.valid)?(oe.validatedTokens.add(this.currentToken.token),!0):(this.clearToken(),!1)}catch(e){return this.config.debug&&l.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&&oe.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(e){if(!e.expiresAt||!this.apiKey)return;const t=new Date(e.expiresAt).getTime()-Date.now()-3e5;t>0&&(this.refreshTimer=setTimeout((()=>r(this,void 0,void 0,(function*(){try{yield this.exchangeApiKeyForJWT({scopes:e.scopes}),this.config.debug&&l.info("AuthManager: Token refreshed automatically")}catch(e){this.config.debug&&l.error("AuthManager: Automatic token refresh failed",e),this.config.onTokenExpired&&this.config.onTokenExpired()}}))),t))}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&&l.debug("AuthManager: Disposed")}}oe.validatedTokens=new Set;const se=3e3,re=864e5,ae=100,de=2147483647,ce=["DOMAIN_NOT_ALLOWED","UNPUBLISHED","SUSPENDED","NOT_FOUND","RATE_LIMITED"],le={DOMAIN_NOT_ALLOWED:"domain_not_allowed",UNPUBLISHED:"unpublished",SUSPENDED:"suspended",NOT_FOUND:"not_found",RATE_LIMITED:"rate_limited"};function he(e){return ce.includes(e)?le[e]:null}const ge="DOMAIN_NOT_ALLOWED",ue="This embed is not authorized to be shown on this website.";function pe(){if("undefined"==typeof document)return[];const e=[],t=document.querySelectorAll("script[src*='embed-sdk']");for(const i of Array.from(t)){const t=i.getAttribute("data-api-url");t&&t.trim()&&e.push(t.trim().replace(/\/+$/,""))}const i=window.WIDGETIC_EMBED_API;return i&&String(i).trim()&&e.push(String(i).trim().replace(/\/+$/,"")),e}function me(e){var t;if("undefined"==typeof window)return null;const i=window.__WIDGETIC_EMBED_LOOKUP__;return(null===(t=null==i?void 0:i[e])||void 0===t?void 0:t.embedUrl)||null}function ve(e){if(!e||"object"!=typeof e)return null;const t="string"==typeof e.embedUrl?e.embedUrl:"";if(!t)return null;const i=function(e){if(!e||"object"!=typeof e)return;const t=e;return"string"!=typeof t.moduleUrl||"number"!=typeof t.contractVersion?void 0:{moduleUrl:t.moduleUrl,contractVersion:t.contractVersion,moduleHash:"string"==typeof t.moduleHash?t.moduleHash:null}}(e.direct);return Object.assign({embedUrl:t,compositionId:"string"==typeof e.compositionId?e.compositionId:void 0,design:e.design&&"object"==typeof e.design?e.design:{},content:e.content&&"object"==typeof e.content?e.content:{},contentItems:Array.isArray(e.contentItems)?e.contentItems:[]},i?{direct:i}:{})}function fe(e){return r(this,void 0,void 0,(function*(){let t=null;try{t=yield e.json()}catch(e){t=null}const i=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return null;const t=e.code;return"string"==typeof t&&t.length>0&&t.length<=64?t:null}(t),n=(i&&he(i)?i:null)||(429===(o=e.status)?"RATE_LIMITED":404===o?"NOT_FOUND":null);var o;if(!n)return null;const s=he(n);return s?{gatewayCode:n,stateCode:s}:null}))}function ye(e){return r(this,void 0,void 0,(function*(){let t="";try{t=new URL(e).origin}catch(e){t=""}try{const i=yield fetch(e,{method:"GET",mode:"cors"});if(!i.ok){const e=yield function(e){return r(this,void 0,void 0,(function*(){if(403!==e.status)return null;try{const t=yield e.json();if(!t||"object"!=typeof t||t.code!==ge)return null;const i=t.details&&"object"==typeof t.details?t.details:null,n="string"==typeof(null==i?void 0:i.reason)?i.reason.slice(0,80):void 0;return{code:ge,reason:n}}catch(e){return null}}))}(i);if(e)return{kind:"refused",refusal:e};const t=yield fe(i);return t?{kind:"failed",failure:t}:{kind:"unavailable"}}const n=ve(yield i.json());return n?{kind:"payload",payload:n,gatewayOrigin:t}:{kind:"unavailable"}}catch(e){return{kind:"unavailable"}}}))}function we(e){return"refused"===e.kind?{status:"refused",refusal:e.refusal}:"failed"===e.kind?{status:"failed",failure:e.failure}:{status:"found",payload:e.payload,gatewayOrigin:e.gatewayOrigin||void 0}}function be(e){const t=`/embed/compositions/${e}`,i=[];for(const e of pe())i.push(`${e}${t}`);const n=h().replace(/\/+$/,"");i.push(`${n}${t}`);const o=String(g.PROD_API_URL).replace(/\/+$/,"");return o&&i.push(`${o}${t}`),[...new Set(i)]}function Ie(e){return r(this,void 0,void 0,(function*(){const t=pe();for(const i of t){const t=yield ye(`${i}/embed/compositions/${e}`);if("unavailable"!==t.kind)return we(t)}const i=yield function(e){const t=me(e);return t?Promise.resolve(t):"undefined"==typeof document?Promise.resolve(null):new Promise((t=>{const i=document.createElement("script");i.src=`https://cdn.widgetic.com/embed/compositions/${e}.js`,i.async=!0,i.onload=()=>t(me(e)),i.onerror=()=>t(null),document.head.appendChild(i)}))}(e);if(i){for(const t of be(e)){const e=yield ye(t);if("refused"===e.kind)return we(e);if("failed"!==e.kind&&"payload"===e.kind){const t=e.payload;return{status:"found",payload:Object.assign(Object.assign({},t),{embedUrl:t.embedUrl||i}),gatewayOrigin:e.gatewayOrigin||void 0}}}return{status:"found",payload:{embedUrl:i,compositionId:e}}}let n=null;for(const t of be(e)){const e=yield ye(t);if("refused"===e.kind)return we(e);if("failed"!==e.kind){if("payload"===e.kind)return we(e)}else n=e.failure}return n?{status:"failed",failure:n}:{status:"not-found"}}))}const Te=new Set;function Se(e,t){var i;if(Te.has(e))return;Te.add(e);"undefined"!=typeof window&&(null===(i=window.location)||void 0===i?void 0:i.hostname)&&window.location.hostname,t.reason&&t.reason}function ke(e,t,i,n,o){const s=document.createElement("iframe");return s.src=e,s.width=t,s.height=i,s.setAttribute("frameborder","0"),s.setAttribute("allowfullscreen",""),s.style.border="0",s.style.display="block",s.style.maxWidth="100%",n&&s.setAttribute("data-composition-id",n),function(e,t){if(!t)return;const i=t.design&&Object.keys(t.design).length>0?t.design:null,n=t.content&&Object.keys(t.content).length>0?t.content:null,o=t.contentItems&&t.contentItems.length>0?t.contentItems:null;if(!i&&!n&&!o)return;const s=()=>{const t=e.contentWindow;if(!t)return;const s={type:"widgetic:update"};i&&(s.design=i),n&&(s.content=n),o&&(s.contentItems=o),t.postMessage(s,"*")};window.addEventListener("message",(t=>{t.source===e.contentWindow&&"widgetic:ready"===(t.data&&t.data.type||"")&&s()})),e.addEventListener("load",(()=>{s(),window.setTimeout(s,80),window.setTimeout(s,400)}))}(s,o),s}class Ee{constructor(){this.deviceInfo=null}static getInstance(){return Ee.instance||(Ee.instance=new Ee),Ee.instance}getDeviceInfo(){return this.deviceInfo||(this.deviceInfo=this.detectDevice()),this.deviceInfo}getDeviceType(){return this.getDeviceInfo().type}isMobile(){return this.getDeviceInfo().isMobile}isTablet(){return this.getDeviceInfo().isTablet}isDesktop(){return this.getDeviceInfo().isDesktop}hasTouch(){return this.getDeviceInfo().hasTouch}detectDevice(){const e=navigator.userAgent||"",t=navigator.platform||"",i=navigator.vendor||"",n=navigator.maxTouchPoints||0,o=navigator.hardwareConcurrency||1,s=navigator.deviceMemory,r=this.detectTouchCapability(),a=this.determineDeviceType(e,t,r,n),d={type:a,isMobile:"mobile"===a,isTablet:"tablet"===a,isDesktop:"desktop"===a||"tablet"===a,hasTouch:r,userAgent:e,platform:t,vendor:i,maxTouchPoints:n,hardwareConcurrency:o,deviceMemory:s};return l.debug("Device detected",d),d}detectTouchCapability(){if("ontouchstart"in window)return!0;if(navigator.maxTouchPoints&&navigator.maxTouchPoints>0)return!0;if("onpointerdown"in window)return!0;try{if(void 0!==window.DocumentTouch&&document instanceof window.DocumentTouch)return!0}catch(e){}return!1}determineDeviceType(e,t,i,n){const o=e.toLowerCase(),s=t.toLowerCase();return[/android.*mobile/,/iphone/,/ipod/,/blackberry/,/bb10/,/windows phone/,/iemobile/,/mobile/,/phone/].some((e=>e.test(o)))?"mobile":[/ipad/,/android(?!.*mobile)/,/kindle/,/silk/,/playbook/,/tablet/].some((e=>e.test(o)))?"tablet":[/windows nt/,/macintosh/,/mac os x/,/linux/,/x11/,/cros/].some((e=>e.test(o)))?"desktop":/^(iphone|ipod|android)/.test(s)?"mobile":/^(ipad)/.test(s)?"tablet":/^(win|mac|linux)/.test(s)?"desktop":i?n>=5?"tablet":n<=2?"mobile":"tablet":"desktop"}checkDeviceRestrictions(e=!0,t=!0){const i=this.getDeviceInfo();return i.isMobile&&!e?(l.debug("Widget restricted on mobile device"),!1):!(i.isDesktop&&!t)||(l.debug("Widget restricted on desktop/tablet device"),!1)}getDeviceCapabilities(){const e={userAgent:navigator.userAgent,platform:navigator.platform,vendor:navigator.vendor,language:navigator.language,languages:navigator.languages,cookieEnabled:navigator.cookieEnabled,onLine:navigator.onLine,maxTouchPoints:navigator.maxTouchPoints,hardwareConcurrency:navigator.hardwareConcurrency,deviceMemory:navigator.deviceMemory,connection:navigator.connection,standalone:navigator.standalone,webdriver:navigator.webdriver};return e.screen={width:screen.width,height:screen.height,availWidth:screen.availWidth,availHeight:screen.availHeight,colorDepth:screen.colorDepth,pixelDepth:screen.pixelDepth,orientation:screen.orientation},e.touch={hasTouch:this.hasTouch(),hasTouchEvents:"ontouchstart"in window,hasPointerEvents:"onpointerdown"in window,hasGestureEvents:"ongesturestart"in window},window.matchMedia&&(e.mediaQueries={hover:window.matchMedia("(hover: hover)").matches,pointer:window.matchMedia("(pointer: fine)").matches?"fine":"coarse",anyHover:window.matchMedia("(any-hover: hover)").matches,anyPointer:window.matchMedia("(any-pointer: fine)").matches?"fine":"coarse"}),e}reset(){this.deviceInfo=null}}function Me(){return Ee.getInstance()}function Ce(e=!0,t=!0){return Me().checkDeviceRestrictions(e,t)}const De="data-widgetic-overlay",Ae="data-device-restricted",We=new WeakMap,Oe=new WeakMap,xe=new Map;function Le(e,t,i){if(We.has(e))return;const n=e.getAttribute("composition-id")||"widget",o=function(e,t){const i=Oe.get(e);if(i)return i;const n=(xe.get(t)||0)+1;xe.set(t,n);const o=1===n?t:`${t}-${n}`;return Oe.set(e,o),o}(e,n);let s=()=>{};if(i){const e=e=>{var t;(null===(t=e.detail)||void 0===t?void 0:t.widgetId)===o&&(s(),i())};document.addEventListener("widgetic:overlay-shown",e),s=()=>document.removeEventListener("widgetic:overlay-shown",e)}Promise.resolve().then((function(){return Ct})).then((({TriggerManager:i})=>{if(We.has(e))return void s();const n=new i({widgetId:o,element:e,config:t,displayWhenShown:"block"});We.set(e,n),e.hasAttribute(De)&&e.setAttribute(De,"armed"),l.debug("[published-host-display] Trigger manager armed",{widgetId:o,mode:t.mode,eventTrigger:t.eventTrigger})})).catch((e=>{s(),l.error("[published-host-display] Could not load the overlay triggers; the embed stays hidden",{widgetId:o,error:e})}))}const Re=/^[A-Za-z0-9_.-]{1,64}$/;function Ue(e){return(new TextEncoder).encode(JSON.stringify(e)).length}function ze(e){if(!e||!e.trim())return null;try{const t=JSON.parse(e);return!t||"object"!=typeof t||Array.isArray(t)?null:t}catch(e){return null}}function Pe(e){const t=ze(e);if(!t)return null;const i=Object.keys(t);if(i.length>50)return null;if(Ue(t)>8192)return null;const n={};for(const e of i){if(!Re.test(e))return null;const i=t[e];if("boolean"==typeof i)n[e]=i;else if("number"==typeof i){if(!Number.isFinite(i))return null;n[e]=i}else{if("string"!=typeof i)return null;if(i.length>2e3)return null;n[e]=i}}return n}function _e(e){if(!(null==e?void 0:e.trim()))return null;const t=e.trim();if(t.length>2048)return null;try{return"https:"!==new URL(t).protocol?null:t}catch(e){return null}}const je=new WeakMap;function Fe(e){const t=e.getAttribute("context"),i=function(e){const t=ze(e);if((null==e?void 0:e.trim())&&!t)return{value:null,invalid:!0};if(!t)return{value:null,invalid:!1};const i=Object.keys(t);if(i.length>20)return{value:null,invalid:!0};if(Ue(t)>2048)return{value:null,invalid:!0};const n={};for(const e of i){if(!Re.test(e))return{value:null,invalid:!0};const i=t[e];if("number"==typeof i){if(!Number.isFinite(i))return{value:null,invalid:!0};n[e]=i}else{if("string"!=typeof i)return{value:null,invalid:!0};if(i.length>500)return{value:null,invalid:!0};n[e]=i}}return{value:n,invalid:!1}}(t);return i.invalid&&function(e,t){const i=null!=t?t:"";let n=je.get(e);n||(n=new Set,je.set(e,n)),n.has(i)||n.add(i)}(e,t),{context:i.invalid?null:i.value,contextInvalid:i.invalid,values:Pe(e.getAttribute("values")),mediaResolver:_e(e.getAttribute("media-resolver"))}}const He="data-widgetic-context-invalid";const Be=new WeakMap;function $e(e){const t=Be.get(e);if(t){Be.delete(e);try{t.instance.destroy()}catch(e){}t.stop()}for(const t of Array.from(e.querySelectorAll("[data-widgetic-direct]")))t.remove()}function Ne(e,t){const i=Fe(e);i.contextInvalid?e.setAttribute(He,""):e.removeAttribute(He);const n=Object.assign(Object.assign({},t.content||{}),i.values||{});return{design:t.design||{},content:n,contentItems:t.contentItems||[],context:i.context,mediaResolver:i.mediaResolver}}function Ke(e,t,i,n){return r(this,void 0,void 0,(function*(){const o=e.getAttribute("composition-id")||"",s=t.direct;if(!s||2!==s.contractVersion||!s.moduleUrl)return!1;let r;try{r=yield(a=s.moduleUrl,import(a))}catch(e){return!1}var a;if(!e.isConnected||e.getAttribute("composition-id")!==o)return!1;if(2!==r.contractVersion)return!1;$e(e);const d=document.createElement("div");d.setAttribute("data-widgetic-direct","1"),d.setAttribute("width",i||e.getAttribute("width")||"400");const c=e.getAttribute("height");c&&d.setAttribute("height",c);const l=d.attachShadow({mode:"open"}),h=document.createElement("style");h.textContent=r.getStyles();const g=document.createElement("div");g.className="widgetic-direct-target",l.append(h,g);const u=r.mount(g,Ne(e,t)),p=function(e,t,i){const n="undefined"!=typeof MutationObserver?MutationObserver:null;if(!n)return()=>{};let o;try{o=new n((()=>{i.update(Ne(e,t))}))}catch(e){return()=>{}}return o.observe(e,{attributes:!0,attributeFilter:["values","context","media-resolver"]}),()=>o.disconnect()}(e,t,u);return Be.set(e,{compositionId:o,instance:u,stop:p}),e.appendChild(d),n(e),e.dispatchEvent(new CustomEvent("widgetic:ready",{bubbles:!0,composed:!0,detail:{compositionId:o}})),!0}))}const Ve="data-widgetic-refused",qe="data-widgetic-context-invalid",Ye="data-widgetic-composition-tracked";function Qe(e,t){const i=e.getAttribute(Ye);if(i&&i!==t){!function(e){e.removeAttribute("data-widgetic-mounting"),e.removeAttribute("data-widgetic-mounted"),e.removeAttribute(Ae),e.removeAttribute(Ve),e.removeAttribute(qe)}(e),$e(e);for(const t of Array.from(e.querySelectorAll("iframe")))t.remove();e.style.display="",e.removeAttribute("data-widgetic-overlay")}e.setAttribute(Ye,t)}const Ge=["context","values","media-resolver"],Je=new Set(["widgetic:ready","widgetic:error","widgetic:submitted","widgetic:resize","widgetic:data","widgetic:interaction","widgetic:form-submit"]),Xe=new WeakMap;class Ze{constructor(e,t,i,n){this.host=e,this.iframe=t,this.gatewayOrigin=i,this.compositionId=n,this.readyDispatched=!1,this.attributeFlushScheduled=!1,this.attributeObserver=null,this.onWindowMessage=e=>this.handleWrapperMessage(e),window.addEventListener("message",this.onWindowMessage),this.iframe.addEventListener("load",(()=>this.postHostSnapshot())),this.observeHostAttributes()}observeHostAttributes(){const e="undefined"!=typeof MutationObserver?MutationObserver:null;if(!e)return;let t;try{t=new e((e=>{e.some((e=>"attributes"===e.type&&e.attributeName&&Ge.includes(e.attributeName)))&&this.scheduleHostSnapshot()}))}catch(e){return}t.observe(this.host,{attributes:!0,attributeFilter:[...Ge]}),this.attributeObserver=t}scheduleHostSnapshot(){this.attributeFlushScheduled||(this.attributeFlushScheduled=!0,queueMicrotask((()=>{this.attributeFlushScheduled=!1,this.postHostSnapshot()})))}postHostSnapshot(){try{const e=Fe(this.host);e.contextInvalid?this.host.setAttribute(qe,"1"):this.host.removeAttribute(qe);const t=this.iframe.contentWindow;if(!t)return;const i=function(e,t){return{type:"widgetic:host",version:1,compositionId:e,context:t.context,values:t.values,mediaResolver:t.mediaResolver}}(this.compositionId,e);t.postMessage(i,this.gatewayOrigin)}catch(e){}}handleWrapperMessage(e){if(e.source!==this.iframe.contentWindow)return;if(e.origin!==this.gatewayOrigin)return;const t=e.data;if(!t||"object"!=typeof t||Array.isArray(t))return;const i=t.type;if("string"!=typeof i||!Je.has(i))return;const n=t.compositionId;if("string"==typeof n&&n!==this.compositionId)return;const o=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return{};try{const t=JSON.stringify(e);return(new TextEncoder).encode(t).length>8192?{}:e}catch(e){return{}}}(t.detail),s=Object.assign({compositionId:this.compositionId},o);if("widgetic:ready"===i){if(this.readyDispatched)return;return this.readyDispatched=!0,this.postHostSnapshot(),void this.dispatchHostEvent("widgetic:ready",{compositionId:this.compositionId})}this.dispatchHostEvent(i,s)}dispatchHostEvent(e,t){this.host.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:!0}))}destroy(){var e;window.removeEventListener("message",this.onWindowMessage),null===(e=this.attributeObserver)||void 0===e||e.disconnect(),this.attributeObserver=null}}function et(e,t,i){e.dispatchEvent(new CustomEvent("widgetic:error",{detail:{compositionId:t,code:i},bubbles:!0,composed:!0}))}function tt(e){e.setAttribute("data-widgetic-mounted","1"),e.removeAttribute("data-widgetic-mounting"),e.hasAttribute(De)||(e.style.display="block")}function it(e,t,i,n){tt(e);const o=ke(t,n||e.getAttribute("width")||"400",e.getAttribute("height")||"300",e.getAttribute("composition-id")||void 0,i);e.appendChild(o);const s=e.getAttribute("composition-id");if(s)try{!function(e,t,i,n){let o;try{o=new URL(i).origin}catch(e){return}const s=Xe.get(e);s&&s.destroy();const r=new Ze(e,t,o,n);Xe.set(e,r),r.postHostSnapshot()}(e,o,t,s)}catch(e){}}function nt(e,t,i){const n=e.getAttribute("composition-id")||"";Ke(e,t,i,tt).then((t=>{t||e.isConnected&&e.getAttribute("composition-id")===n&&(e.getAttribute("data-widgetic-mounted")||ot(e,n,"REPUBLISH_REQUIRED","republish_required"))}))}function ot(e,t,i,n){e.removeAttribute("data-widgetic-mounting"),e.setAttribute(Ve,i),et(e,t,n)}function st(e){const t=e.getAttribute("composition-id");if(t&&Qe(e,t),e.getAttribute("data-widgetic-mounted")||e.getAttribute("data-widgetic-mounting")||e.getAttribute(Ae)||e.getAttribute(Ve))return!0;const i=e.getAttribute("src");if(i)return it(e,i),!0;if(!t)return!1;const n=e.hasAttribute(Ae),o=function(e){var t,i,n,o,s;let r;try{r=E(e)}catch(e){return l.warn("[published-host-display] Could not read the embed's display settings",{error:e}),{suppressed:!1}}return Ce(null===(i=null===(t=r.device)||void 0===t?void 0:t.mobileEnabled)||void 0===i||i,null===(o=null===(n=r.device)||void 0===n?void 0:n.desktopEnabled)||void 0===o||o)?("overlay"===(null===(s=r.triggers)||void 0===s?void 0:s.mode)&&(e.style.display="none",e.setAttribute(De,"pending")),{suppressed:!1,triggers:r.triggers}):(e.style.display="none",e.setAttribute(Ae,"true"),l.debug("[published-host-display] Embed skipped: this device is switched off",{compositionId:r.compositionId,device:r.device}),{suppressed:!0})}(e);return o.suppressed?(n||et(e,t,"device_restricted"),!0):(e.setAttribute("data-widgetic-mounting","1"),Ie(t).then((i=>{var n;if(e.getAttribute("data-widgetic-mounted"))return;if("refused"===i.status)return e.removeAttribute("data-widgetic-mounting"),e.setAttribute(Ve,i.refusal.code),Se(t,i.refusal),void et(e,t,he(i.refusal.code)||"domain_not_allowed");if("failed"===i.status)return void ot(e,t,i.failure.gatewayCode,i.failure.stateCode);const s="found"===i.status?i.payload:null;if(!(null==s?void 0:s.embedUrl))return e.removeAttribute("data-widgetic-mounting"),void ot(e,t,"NOT_FOUND","not_found");const{triggers:r}=o;if("overlay"!==(null==r?void 0:r.mode))nt(e,s),r&&Le(e,r);else{const t=(null===(n=r.overlay)||void 0===n?void 0:n.fullWidth)?"100%":void 0;Le(e,r,(()=>nt(e,s,t)))}})),!0)}function rt(e=document){const t=e.querySelectorAll("widgetic");let i=0;for(const e of Array.from(t))e instanceof HTMLElement&&st(e)&&(i+=1);return i}const at={maxBatchSize:50,debounceDelay:10,retryAttempts:3,retryBaseDelay:1e3,cacheTTL:3e5};class dt{constructor(e={}){this.compositionCache=new Map,this.widgetCache=new Map,this.pendingCompositionRequests=new Map,this.pendingWidgetRequests=new Map,this.compositionResolvers=new Map,this.widgetResolvers=new Map,this.compositionBatchQueue=[],this.widgetBatchQueue=[],this.compositionBatchTimer=null,this.widgetBatchTimer=null,this.lastBatchError=null,this.config=Object.assign(Object.assign({},at),e)}getCompositions(e){return r(this,void 0,void 0,(function*(){"undefined"!=typeof performance&&"function"==typeof performance.mark&&performance.mark("api-batch-compositions-start");try{const t=[],i=[];for(const n of e){const e=this.getCachedComposition(n);if(e){t.push(e);continue}const o=this.pendingCompositionRequests.get(n);if(o)try{const e=yield o;t.push(e);continue}catch(e){}i.push(n)}if(i.length>0){const e=yield this.batchCompositions(i);t.push(...e)}return Object.defineProperty(t,"compositions",{get(){return this},enumerable:!1,configurable:!0}),Object.defineProperty(t,"success",{value:!this.lastBatchError,enumerable:!1,configurable:!0}),Object.defineProperty(t,"error",{value:this.lastBatchError||void 0,enumerable:!1,configurable:!0}),t}finally{"undefined"!=typeof performance&&"function"==typeof performance.mark&&performance.mark("api-batch-compositions-end")}}))}getWidgets(e){return r(this,void 0,void 0,(function*(){const t=[],i=[];for(const n of e){const e=this.getCachedWidget(n);if(e){t.push(e);continue}const o=this.pendingWidgetRequests.get(n);if(o)try{const e=yield o;t.push(e);continue}catch(e){}i.push(n)}if(i.length>0){const e=yield this.batchWidgets(i);t.push(...e)}return t}))}getComposition(e){return r(this,void 0,void 0,(function*(){const t=yield this.getCompositions([e]);if(0===t.length)throw new Error(`Composition not found: ${e}`);return t[0]}))}getWidget(e){return r(this,void 0,void 0,(function*(){const t=yield this.getWidgets([e]);if(0===t.length)throw new Error(`Widget not found: ${e}`);return t[0]}))}batchCompositions(e){return r(this,void 0,void 0,(function*(){var t;const i=[];for(const t of e)if(this.pendingCompositionRequests.has(t))i.push(this.pendingCompositionRequests.get(t));else{const e=new Promise(((e,i)=>{this.compositionBatchQueue.push(t),this.scheduleCompositionBatch(),this.compositionResolvers.set(t,{resolve:e,reject:i})}));this.pendingCompositionRequests.set(t,e),i.push(e)}const n=yield Promise.allSettled(i),o=n.find((e=>"rejected"===e.status));return this.lastBatchError=o?(null===(t=o.reason)||void 0===t?void 0:t.message)||String(o.reason):null,n.filter((e=>"fulfilled"===e.status)).map((e=>e.value))}))}batchWidgets(e){return r(this,void 0,void 0,(function*(){const t=[];for(const i of e)if(this.pendingWidgetRequests.has(i))t.push(this.pendingWidgetRequests.get(i));else{const e=new Promise(((e,t)=>{this.widgetBatchQueue.push(i),this.scheduleWidgetBatch(),this.widgetResolvers.set(i,{resolve:e,reject:t})}));this.pendingWidgetRequests.set(i,e),t.push(e)}return(yield Promise.allSettled(t)).filter((e=>"fulfilled"===e.status)).map((e=>e.value))}))}scheduleCompositionBatch(){this.compositionBatchTimer||(this.compositionBatchTimer=window.setTimeout((()=>{this.executeCompositionBatch()}),this.config.debounceDelay))}scheduleWidgetBatch(){this.widgetBatchTimer||(this.widgetBatchTimer=window.setTimeout((()=>{this.executeWidgetBatch()}),this.config.debounceDelay))}executeCompositionBatch(){return r(this,void 0,void 0,(function*(){const e=[...this.compositionBatchQueue];if(this.compositionBatchQueue=[],this.compositionBatchTimer=null,0!==e.length)try{const t=yield this.fetchCompositionsBatch(e);for(const e of t.compositions){this.cacheComposition(e);const t=this.compositionResolvers.get(e.id);t&&(t.resolve(e),this.compositionResolvers.delete(e.id)),this.pendingCompositionRequests.delete(e.id)}if(t.errors)for(const e of t.errors){const t=this.compositionResolvers.get(e.id);t&&(t.reject(new Error(e.error)),this.compositionResolvers.delete(e.id)),this.pendingCompositionRequests.delete(e.id)}for(const t of e){const e=this.compositionResolvers.get(t);e&&(e.reject(new Error(`Composition not found in batch response: ${t}`)),this.compositionResolvers.delete(t)),this.pendingCompositionRequests.delete(t)}}catch(t){for(const i of e){const e=this.compositionResolvers.get(i);e&&(e.reject(t),this.compositionResolvers.delete(i)),this.pendingCompositionRequests.delete(i)}}}))}executeWidgetBatch(){return r(this,void 0,void 0,(function*(){const e=[...this.widgetBatchQueue];if(this.widgetBatchQueue=[],this.widgetBatchTimer=null,0!==e.length)try{const t=yield this.fetchWidgetsBatch(e);for(const e of t.widgets){this.cacheWidget(e);const t=this.widgetResolvers.get(e.id);t&&(t.resolve(e),this.widgetResolvers.delete(e.id)),this.pendingWidgetRequests.delete(e.id)}if(t.errors)for(const e of t.errors){const t=this.widgetResolvers.get(e.id);t&&(t.reject(new Error(e.error)),this.widgetResolvers.delete(e.id)),this.pendingWidgetRequests.delete(e.id)}for(const t of e){const e=this.widgetResolvers.get(t);e&&(e.reject(new Error(`Widget not found in batch response: ${t}`)),this.widgetResolvers.delete(t)),this.pendingWidgetRequests.delete(t)}}catch(t){for(const i of e){const e=this.widgetResolvers.get(i);e&&(e.reject(t),this.widgetResolvers.delete(i)),this.pendingWidgetRequests.delete(i)}}}))}fetchCompositionsBatch(e){return r(this,arguments,void 0,(function*(e,t=1){var i,n,o;try{const t=yield u(),n=new x({basePath:p(),apiKey:()=>r(this,void 0,void 0,(function*(){return t})),headers:{"X-SDK-Version":`embed-sdk/${m}`}}),o=new R(n),s=yield o.getCompositionsBatch({getCompositionsBatchRequest:{compositionIds:e}}),d=s.compositions||[];return{compositions:d.map((e=>{if(!e||"object"!=typeof e)return e;const{internalConfig:t,adminNotes:i}=e;return a(e,["internalConfig","adminNotes"])})),errors:null===(i=s.errors)||void 0===i?void 0:i.filter((e=>(null==e?void 0:e.id)&&(null==e?void 0:e.error))).map((e=>({id:e.id,error:e.error})))}}catch(i){if(t<this.config.retryAttempts){const i=this.config.retryBaseDelay*Math.pow(2,t-1);return yield new Promise((e=>setTimeout(e,i))),this.fetchCompositionsBatch(e,t+1)}const s=null===(n=null==i?void 0:i.response)||void 0===n?void 0:n.status,r=null===(o=null==i?void 0:i.response)||void 0===o?void 0:o.statusText;if("number"==typeof s){let e=`HTTP ${s}: ${r||"Request failed"}`;switch(s){case 401:e="Unauthorized: API key is invalid or missing";break;case 403:e="Forbidden: Access denied to these compositions";break;case 404:e="Composition not found: One or more compositions do not exist";break;case 429:e="Rate limit exceeded: Too many requests";break;case 500:e="Server error: Internal server error occurred";break;case 503:e="Service unavailable: API is temporarily down"}throw new Error(e)}throw i}}))}fetchWidgetsBatch(e){return r(this,arguments,void 0,(function*(e,t=1){var i,n,o;try{const t=yield u(),n=new x({basePath:p(),apiKey:()=>r(this,void 0,void 0,(function*(){return t})),headers:{"X-SDK-Version":`embed-sdk/${m}`}}),o=new U(n),s=yield o.getWidgetsBatch({getWidgetsBatchRequest:{widgetIds:e}});return{widgets:s.widgets||[],errors:null===(i=s.errors)||void 0===i?void 0:i.filter((e=>(null==e?void 0:e.id)&&(null==e?void 0:e.error))).map((e=>({id:e.id,error:e.error})))}}catch(i){if(t<this.config.retryAttempts){const i=this.config.retryBaseDelay*Math.pow(2,t-1);return yield new Promise((e=>setTimeout(e,i))),this.fetchWidgetsBatch(e,t+1)}const s=null===(n=null==i?void 0:i.response)||void 0===n?void 0:n.status,r=null===(o=null==i?void 0:i.response)||void 0===o?void 0:o.statusText;if("number"==typeof s){let e=`HTTP ${s}: ${r||"Request failed"}`;switch(s){case 401:e="Unauthorized: API key is invalid or missing";break;case 403:e="Forbidden: Access denied to these widgets";break;case 404:e="Widget not found: One or more widgets do not exist";break;case 429:e="Rate limit exceeded: Too many requests";break;case 500:e="Server error: Internal server error occurred";break;case 503:e="Service unavailable: API is temporarily down"}throw new Error(e)}throw i}}))}getCachedComposition(e){const t=this.compositionCache.get(e);if(!t)return null;return Date.now()-t.timestamp>t.ttl?(this.compositionCache.delete(e),null):t.data}getCachedWidget(e){const t=this.widgetCache.get(e);if(!t)return null;return Date.now()-t.timestamp>t.ttl?(this.widgetCache.delete(e),null):t.data}cacheComposition(e){this.compositionCache.set(e.id,{data:e,timestamp:Date.now(),ttl:this.config.cacheTTL})}cacheWidget(e){this.widgetCache.set(e.id,{data:e,timestamp:Date.now(),ttl:this.config.cacheTTL})}clearCache(){this.compositionCache.clear(),this.widgetCache.clear()}getCacheStats(){return{compositions:{size:this.compositionCache.size,entries:Array.from(this.compositionCache.entries()).map((([e,t])=>({id:e,age:Date.now()-t.timestamp,ttl:t.ttl})))},widgets:{size:this.widgetCache.size,entries:Array.from(this.widgetCache.entries()).map((([e,t])=>({id:e,age:Date.now()-t.timestamp,ttl:t.ttl})))},pending:{compositions:this.pendingCompositionRequests.size,widgets:this.pendingWidgetRequests.size},queues:{compositions:this.compositionBatchQueue.length,widgets:this.widgetBatchQueue.length}}}}let ct=null;function lt(){return ct||(ct=new dt),ct}function ht(){ct=null}var gt=Object.freeze({__proto__:null,BatchApiClient:dt,getBatchClient:lt,resetBatchClient:ht});const ut={cacheTTL:18e5,loadTimeout:1e4,maxRetries:3,retryDelay:1e3,enableHttp3:!0,cdnBaseUrl:v()};class pt{constructor(e={}){this.moduleCache=new Map,this.loadingPromises=new Map,this.dependencyGraph=new Map,this.http3Supported=null,this.config=Object.assign(Object.assign({},ut),e)}loadModule(e){return r(this,arguments,void 0,(function*(e,t={}){const i=this.getModuleKey(e.id,t.version||e.version),n=this.loadingPromises.get(i);if(n&&!t.force)return n;if(!t.force){const e=this.getCachedModule(i);if(e)return{module:e.module,url:e.url,loadTime:0,cached:!0}}const o=this.doLoadModule(e,t);this.loadingPromises.set(i,o);try{const e=yield o;return this.loadingPromises.delete(i),e}catch(e){throw this.loadingPromises.delete(i),e}}))}loadModules(e){return r(this,arguments,void 0,(function*(e,t={}){const i=new Map,n=new Map;for(const t of e)if(n.set(t.id,t),t.dependencies){this.dependencyGraph.set(t.id,new Set(t.dependencies));for(const e of t.dependencies)i.set(e,t)}const o=this.resolveDependencyOrder(e),s=[];for(const e of o)try{const i=yield this.loadModule(e,t);s.push(i)}catch(e){}return s}))}getLatestVersion(e){return r(this,void 0,void 0,(function*(){try{const t=`${this.config.cdnBaseUrl}/${e}/latest`,i=yield this.fetchWithHttp3(t,{timeout:5e3});if(i.ok){return(yield i.json()).version}}catch(e){}return null}))}preloadModules(e){return r(this,void 0,void 0,(function*(){const t=e.map((e=>this.loadModule(e,{timeout:3e4}).catch((e=>{}))));yield Promise.allSettled(t)}))}invalidateModule(e,t){if(t){const i=this.getModuleKey(e,t);this.moduleCache.delete(i)}else{Array.from(this.moduleCache.keys()).filter((t=>t.startsWith(`${e}@`))).forEach((e=>this.moduleCache.delete(e)))}}clearCache(){this.moduleCache.clear(),this.loadingPromises.clear()}getCacheStats(){return{size:this.moduleCache.size,entries:Array.from(this.moduleCache.entries()).map((([e,t])=>({key:e,version:t.version,age:Date.now()-t.timestamp,ttl:t.ttl,url:t.url}))),loading:this.loadingPromises.size,http3Supported:this.http3Supported}}doLoadModule(e,t){return r(this,void 0,void 0,(function*(){const i=Date.now(),n=t.version||e.version,o=this.resolveModuleUrl(e,n);try{e.dependencies&&e.dependencies.length>0&&(yield this.loadDependencies(e.dependencies));const s=yield this.loadModuleFromUrl(o,{timeout:t.timeout||this.config.loadTimeout,retries:t.retries||this.config.maxRetries});if(!this.validateModule(s))throw new Error(`Invalid module structure for ${e.id}`);const r=this.getModuleKey(e.id,n);return this.cacheModule(r,{module:s,url:o,timestamp:Date.now(),version:n,ttl:this.config.cacheTTL}),{module:s,url:o,loadTime:Date.now()-i,cached:!1}}catch(t){const i=t instanceof Error?t.message:String(t);throw new Error(`Failed to load module ${e.id}@${n}: ${i}`)}}))}loadModuleFromUrl(e,t){return r(this,void 0,void 0,(function*(){let i=null;for(let n=1;n<=t.retries;n++)try{if(e.endsWith(".mjs")||e.includes("type=module")){const i=yield this.loadEsModule(e,t.timeout);return this.extractWidgetFromEsModule(i)}const i=yield this.fetchModuleText(e,t.timeout);return this.evaluateUmdModule(i,e)}catch(e){if(i=e instanceof Error?e:new Error(String(e)),n<t.retries){const e=this.config.retryDelay*Math.pow(2,n-1);yield new Promise((t=>setTimeout(t,e)))}}throw i||new Error("Module loading failed")}))}loadEsModule(e,t){return r(this,void 0,void 0,(function*(){return new Promise(((i,n)=>{const o=setTimeout((()=>{n(new Error(`Module load timeout: ${e}`))}),t);import(e).then((e=>{clearTimeout(o),i(e)})).catch((e=>{clearTimeout(o),n(e)}))}))}))}fetchModuleText(e,t){return r(this,void 0,void 0,(function*(){const i=yield this.fetchWithHttp3(e,{timeout:t});if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);return yield i.text()}))}fetchWithHttp3(e,t){return r(this,void 0,void 0,(function*(){null===this.http3Supported&&(this.http3Supported=yield this.detectHttp3Support());const i={signal:AbortSignal.timeout(t.timeout)};return fetch(e,i)}))}detectHttp3Support(){return r(this,void 0,void 0,(function*(){var e;try{if("connection"in navigator&&"effectiveType"in navigator.connection){const e=navigator.connection;return"4g"===e.effectiveType||"5g"===e.effectiveType}const t=`${this.config.cdnBaseUrl}/test-http3`,i=yield fetch(t,{method:"HEAD",signal:AbortSignal.timeout(2e3)}).catch((()=>null));return(null===(e=null==i?void 0:i.headers.get("alt-svc"))||void 0===e?void 0:e.includes("h3"))||!1}catch(e){return!1}}))}extractWidgetFromEsModule(e){const t=e.default||e.Widget||e.widget||e;if(!t)throw new Error("No widget found in module exports");return{id:t.id||"unknown",version:t.version||"1.0.0",component:t.component||t,metadata:t.metadata,dependencies:t.dependencies}}evaluateUmdModule(e,t){const i={window:"undefined"!=typeof window?window:{},document:"undefined"!=typeof document?document:{},console:console,setTimeout:setTimeout,clearTimeout:clearTimeout,setInterval:setInterval,clearInterval:clearInterval},n=new Function("window","document","console","setTimeout","clearTimeout","setInterval","clearInterval",`\n let module = { exports: {} };\n let exports = module.exports;\n \n ${e}\n \n return module.exports.default || module.exports;\n `)(i.window,i.document,i.console,i.setTimeout,i.clearTimeout,i.setInterval,i.clearInterval);if(!n)throw new Error(`Module evaluation failed: ${t}`);return{id:n.id||"unknown",version:n.version||"1.0.0",component:n.component||n,metadata:n.metadata,dependencies:n.dependencies}}loadDependencies(e){return r(this,void 0,void 0,(function*(){const t=e.map((e=>r(this,void 0,void 0,(function*(){try{if("undefined"!=typeof window&&window[e])return}catch(e){}}))));yield Promise.allSettled(t)}))}resolveDependencyOrder(e){const t=new Set,i=new Set,n=[],o=new Map(e.map((e=>[e.id,e]))),s=e=>{if(i.has(e.id))throw new Error(`Circular dependency detected: ${e.id}`);if(!t.has(e.id)){if(i.add(e.id),e.dependencies)for(const t of e.dependencies){const e=o.get(t);e&&s(e)}i.delete(e.id),t.add(e.id),n.push(e)}};for(const i of e)t.has(i.id)||s(i);return n}resolveModuleUrl(e,t){return e.moduleUrl?e.moduleUrl.replace("{{version}}",t):`${this.config.cdnBaseUrl}/${e.id}/${t}/widget.mjs`}validateModule(e){return!!(e&&e.id&&e.version&&e.component)}getModuleKey(e,t){return`${e}@${t}`}getCachedModule(e){const t=this.moduleCache.get(e);if(!t)return null;return Date.now()-t.timestamp>t.ttl?(this.moduleCache.delete(e),null):t}cacheModule(e,t){this.moduleCache.set(e,t)}}let mt=null;function vt(){return mt||(mt=new pt),mt}function ft(){mt=null}var yt=Object.freeze({__proto__:null,ModuleLoader:pt,getModuleLoader:vt,resetModuleLoader:ft});const wt={close:"Close",closeOverlay:"Close overlay",interactiveWidget:"Interactive widget"},bt=new Map([["fr",{close:"Fermer",closeOverlay:"Fermer la fenêtre",interactiveWidget:"Widget interactif"}],["de",{close:"Schließen",closeOverlay:"Fenster schließen",interactiveWidget:"Interaktives Widget"}],["es",{close:"Cerrar",closeOverlay:"Cerrar ventana",interactiveWidget:"Widget interactivo"}],["pt",{close:"Fechar",closeOverlay:"Fechar janela",interactiveWidget:"Widget interativo"}],["nl",{close:"Sluiten",closeOverlay:"Venster sluiten",interactiveWidget:"Interactieve widget"}],["da",{close:"Luk",closeOverlay:"Luk vinduet",interactiveWidget:"Interaktiv widget"}],["sv",{close:"Stäng",closeOverlay:"Stäng fönstret",interactiveWidget:"Interaktiv widget"}],["zh",{close:"关闭",closeOverlay:"关闭窗口",interactiveWidget:"交互式小组件"}],["ar",{close:"إغلاق",closeOverlay:"إغلاق النافذة",interactiveWidget:"ويجت تفاعلي"}],["he",{close:"סגירה",closeOverlay:"סגירת החלון",interactiveWidget:"וידג'ט אינטראקטיבי"}],["fa",{close:"بستن",closeOverlay:"بستن پنجره",interactiveWidget:"ویجت تعاملی"}],["ur",{close:"بند کریں",closeOverlay:"ونڈو بند کریں",interactiveWidget:"انٹرایکٹو ویجٹ"}]]);function It(e,t=function(){var e,t;return"undefined"==typeof document?"":(null===(e=document.body)||void 0===e?void 0:e.getAttribute("lang"))||(null===(t=document.documentElement)||void 0===t?void 0:t.getAttribute("lang"))||""}()){const i=function(e){var t,i;const n=(null!=e?e:"").trim().replace(/_/g,"-").toLowerCase().split("-"),o="iw"===n[0]?"he":null!==(t=n[0])&&void 0!==t?t:"",s=null!==(i=n[1])&&void 0!==i?i:"";return("zh"!==o||"tw"!==s&&"hk"!==s&&"hant"!==s)&&bt.has(o)?o:null}(t),n=null===i?void 0:bt.get(i);return(null!=n?n:wt)[e]}bt.keys();class Tt{constructor(e){this.intersectionObserver=null,this.isInViewport=!0,this.hasBeenInViewport=!1,this.scrollListener=null,this.lastScrollY=0,this.scrollDistance=0,this.isTriggered=!1,this.debounceTimer=null,this.rafId=null,this.isDestroyed=!1,this.stats={triggeredCount:0,lastTriggeredAt:null,totalScrollDistance:0,viewportChanges:0},this.widgetId=e.widgetId,this.element=e.element,this.type=e.type,this.config=Object.assign(Object.assign({},this.getDefaultConfig()),e.config),this.initialize()}getDefaultConfig(){return{enabled:!0,threshold:.1,distance:100,direction:"down",debounce:100}}initialize(){this.config.enabled&&(l.debug("Initializing ScrollTrigger",{widgetId:this.widgetId,type:this.type,config:this.config}),this.lastScrollY=window.scrollY,"viewport"===this.type?this.initializeViewportDetection():"distance"===this.type&&this.initializeScrollDistance())}initializeViewportDetection(){this.intersectionObserver=new IntersectionObserver(this.handleIntersection.bind(this),{threshold:this.config.threshold||.1,rootMargin:"0px"}),this.intersectionObserver.observe(this.element),l.debug("Viewport detection initialized",{widgetId:this.widgetId,threshold:this.config.threshold})}initializeScrollDistance(){this.scrollListener=this.debounce(this.handleScrollDistance.bind(this),this.config.debounce||100),window.addEventListener("scroll",this.scrollListener,{passive:!0}),l.debug("Scroll distance tracking initialized",{widgetId:this.widgetId,distance:this.config.distance})}handleIntersection(e){if(this.isDestroyed)return;const t=e[e.length-1];if(!t)return;const i=this.isInViewport;if(this.isInViewport=t.isIntersecting,t.isIntersecting&&(this.hasBeenInViewport=!0),this.stats.viewportChanges++,l.debug("Viewport intersection changed",{widgetId:this.widgetId,isIntersecting:this.isInViewport,intersectionRatio:t.intersectionRatio}),i&&!this.isInViewport){if(!this.hasBeenInViewport)return;this.triggerActivated("scroll-out-of-view",{intersectionRatio:t.intersectionRatio,boundingClientRect:t.boundingClientRect})}else!i&&this.isInViewport&&this.triggerDeactivated("scroll-back-in-view",{intersectionRatio:t.intersectionRatio,boundingClientRect:t.boundingClientRect})}observeElement(e){!this.isDestroyed&&"viewport"===this.type&&this.intersectionObserver&&e!==this.element&&(this.intersectionObserver.unobserve(this.element),this.element=e,this.intersectionObserver.observe(e),l.debug("ScrollTrigger now watching another element",{widgetId:this.widgetId}))}handleScrollDistance(){this.isDestroyed||(this.rafId&&cancelAnimationFrame(this.rafId),this.rafId=requestAnimationFrame((()=>{const e=window.scrollY,t=e-this.lastScrollY;this.stats.totalScrollDistance+=Math.abs(t);const i=t>0,n=t<0;"down"===this.config.direction&&i?this.scrollDistance+=t:("up"===this.config.direction&&n||"any"===this.config.direction)&&(this.scrollDistance+=Math.abs(t));const o=this.config.distance||100;!this.isTriggered&&this.scrollDistance>=o&&(this.isTriggered=!0,this.triggerActivated("scroll-distance",{scrollDistance:this.scrollDistance,direction:i?"down":"up",scrollY:e})),this.lastScrollY=e,l.debug("Scroll distance updated",{widgetId:this.widgetId,scrollDistance:this.scrollDistance,requiredDistance:o,isTriggered:this.isTriggered})})))}triggerActivated(e,t){this.stats.triggeredCount++,this.stats.lastTriggeredAt=new Date;const i=new CustomEvent("widgetic:trigger-activated",{detail:{widgetId:this.widgetId,triggerType:e,triggerData:t}});document.dispatchEvent(i),l.debug("Scroll trigger activated",{widgetId:this.widgetId,triggerType:e,triggerData:t})}triggerDeactivated(e,t){const i=new CustomEvent("widgetic:trigger-deactivated",{detail:{widgetId:this.widgetId,triggerType:e,triggerData:t}});document.dispatchEvent(i),l.debug("Scroll trigger deactivated",{widgetId:this.widgetId,triggerType:e,triggerData:t})}debounce(e,t){return i=>{this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=window.setTimeout((()=>{e()}),t)}}updateConfig(e){if(this.isDestroyed)return;const t=Object.assign({},this.config);this.config=Object.assign(Object.assign({},this.config),e),void 0!==e.threshold&&"viewport"===this.type&&(this.destroy(),this.isDestroyed=!1,this.initializeViewportDetection()),void 0!==e.distance&&"distance"===this.type&&(this.scrollDistance=0,this.isTriggered=!1),l.debug("ScrollTrigger config updated",{widgetId:this.widgetId,oldConfig:t,newConfig:this.config})}reset(){this.isDestroyed||(this.scrollDistance=0,this.isTriggered=!1,this.lastScrollY=window.scrollY,l.debug("ScrollTrigger reset",{widgetId:this.widgetId}))}getStats(){return Object.assign(Object.assign({},this.stats),{type:this.type,isInViewport:this.isInViewport,scrollDistance:this.scrollDistance,isTriggered:this.isTriggered,currentScrollY:window.scrollY})}isActive(){return"viewport"===this.type?!this.isInViewport:"distance"===this.type&&this.isTriggered}forceActivate(){"viewport"===this.type?this.triggerActivated("scroll-out-of-view",{manual:!0}):"distance"===this.type&&(this.isTriggered=!0,this.triggerActivated("scroll-distance",{manual:!0}))}forceDeactivate(){"viewport"===this.type&&this.triggerDeactivated("scroll-back-in-view",{manual:!0})}destroy(){this.isDestroyed||(this.intersectionObserver&&(this.intersectionObserver.disconnect(),this.intersectionObserver=null),this.scrollListener&&(window.removeEventListener("scroll",this.scrollListener),this.scrollListener=null),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null),this.isDestroyed=!0,l.debug("ScrollTrigger destroyed",{widgetId:this.widgetId}))}}class St{constructor(e){this.mouseLeaveListener=null,this.lastMouseY=0,this.isTriggered=!1,this.scrollUpListener=null,this.visibilityChangeListener=null,this.backButtonListener=null,this.touchStartListener=null,this.touchEndListener=null,this.lastScrollY=0,this.scrollUpDistance=0,this.touchStartY=0,this.touchStartTime=0,this.isScrollingUp=!1,this.debounceTimer=null,this.isDestroyed=!1,this.stats={triggeredCount:0,lastTriggeredAt:null,desktopTriggers:0,mobileTriggers:0,backButtonTriggers:0,scrollUpTriggers:0,tabSwitchTriggers:0},this.widgetId=e.widgetId,this.config=Object.assign(Object.assign({},this.getDefaultConfig()),e.config),this.initialize()}getDefaultConfig(){return{enabled:!0,desktop:{enabled:!0,sensitivity:10,delay:100},mobile:{enabled:!0,backButton:!0,scrollUp:!0,tabSwitch:!0,sensitivity:50}}}initialize(){var e,t;this.config.enabled&&(l.debug("Initializing ExitIntentTrigger",{widgetId:this.widgetId,config:this.config}),this.lastScrollY=window.scrollY,(null===(e=this.config.desktop)||void 0===e?void 0:e.enabled)&&this.isDesktop()&&this.initializeDesktopTriggers(),(null===(t=this.config.mobile)||void 0===t?void 0:t.enabled)&&this.isMobile()&&this.initializeMobileTriggers())}isDesktop(){return!("ontouchstart"in window)&&!navigator.maxTouchPoints}isMobile(){return"ontouchstart"in window||navigator.maxTouchPoints>0}initializeDesktopTriggers(){var e,t;this.mouseLeaveListener=this.debounce(this.handleMouseLeave.bind(this),(null===(e=this.config.desktop)||void 0===e?void 0:e.delay)||100),this.mouseLeaveListener&&(document.addEventListener("mouseleave",this.mouseLeaveListener),document.addEventListener("mouseout",this.mouseLeaveListener)),l.debug("Desktop exit intent triggers initialized",{widgetId:this.widgetId,sensitivity:null===(t=this.config.desktop)||void 0===t?void 0:t.sensitivity})}initializeMobileTriggers(){const e=this.config.mobile;e.backButton&&(this.backButtonListener=this.handleBackButton.bind(this),window.addEventListener("popstate",this.backButtonListener),history.pushState({widgeticExitIntent:!0},"",window.location.href)),e.scrollUp&&(this.scrollUpListener=this.debounce(this.handleScrollUp.bind(this),50),this.scrollUpListener&&window.addEventListener("scroll",this.scrollUpListener,{passive:!0}),this.touchStartListener=this.handleTouchStart.bind(this),this.touchEndListener=this.handleTouchEnd.bind(this),document.addEventListener("touchstart",this.touchStartListener,{passive:!0}),document.addEventListener("touchend",this.touchEndListener,{passive:!0})),e.tabSwitch&&(this.visibilityChangeListener=this.handleVisibilityChange.bind(this),document.addEventListener("visibilitychange",this.visibilityChangeListener)),l.debug("Mobile exit intent triggers initialized",{widgetId:this.widgetId,backButton:e.backButton,scrollUp:e.scrollUp,tabSwitch:e.tabSwitch})}handleMouseLeave(e){var t;if(this.isDestroyed||this.isTriggered)return;const i=(null===(t=this.config.desktop)||void 0===t?void 0:t.sensitivity)||10;e.clientY<=i&&null===e.relatedTarget&&(this.isTriggered=!0,this.stats.desktopTriggers++,this.triggerActivated("exit-intent",{source:"desktop",method:"mouse-leave",mouseY:e.clientY,sensitivity:i}))}handleBackButton(e){var t;this.isDestroyed||(null===(t=e.state)||void 0===t?void 0:t.widgeticExitIntent)&&(this.stats.backButtonTriggers++,this.triggerActivated("exit-intent",{source:"mobile",method:"back-button"}),history.pushState({widgeticExitIntent:!0},"",window.location.href))}handleScrollUp(){var e;if(this.isDestroyed)return;const t=window.scrollY,i=t-this.lastScrollY;if(i<0){this.scrollUpDistance+=Math.abs(i),this.isScrollingUp=!0;const n=(null===(e=this.config.mobile)||void 0===e?void 0:e.sensitivity)||50;this.scrollUpDistance>=n&&t<=100&&(this.stats.scrollUpTriggers++,this.triggerActivated("exit-intent",{source:"mobile",method:"scroll-up",scrollUpDistance:this.scrollUpDistance,currentScrollY:t,sensitivity:n}),this.scrollUpDistance=0)}else this.scrollUpDistance=0,this.isScrollingUp=!1;this.lastScrollY=t}handleTouchStart(e){if(this.isDestroyed||1!==e.touches.length)return;const t=e.touches[0];this.touchStartY=t.clientY,this.touchStartTime=Date.now()}handleTouchEnd(e){if(this.isDestroyed||1!==e.changedTouches.length)return;const t=e.changedTouches[0].clientY,i=Date.now()-this.touchStartTime,n=t-this.touchStartY;n>100&&i<300&&window.scrollY<=50&&(this.stats.scrollUpTriggers++,this.triggerActivated("exit-intent",{source:"mobile",method:"swipe-up",swipeDistance:n,touchDuration:i,scrollY:window.scrollY}))}handleVisibilityChange(){this.isDestroyed||document.hidden&&(this.stats.tabSwitchTriggers++,this.triggerActivated("exit-intent",{source:"mobile",method:"tab-switch",visibilityState:document.visibilityState}))}triggerActivated(e,t){this.stats.triggeredCount++,this.stats.lastTriggeredAt=new Date;const i=new CustomEvent("widgetic:trigger-activated",{detail:{widgetId:this.widgetId,triggerType:e,triggerData:t}});document.dispatchEvent(i),l.debug("Exit intent trigger activated",{widgetId:this.widgetId,triggerType:e,triggerData:t})}debounce(e,t){return(...i)=>{this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=window.setTimeout((()=>{e.apply(this,i)}),t)}}updateConfig(e){var t,i;if(this.isDestroyed)return;const n=Object.assign({},this.config);this.config=Object.assign(Object.assign({},this.config),e),void 0===e.enabled&&void 0===(null===(t=e.desktop)||void 0===t?void 0:t.enabled)&&void 0===(null===(i=e.mobile)||void 0===i?void 0:i.enabled)||(this.destroy(),this.isDestroyed=!1,this.initialize()),l.debug("ExitIntentTrigger config updated",{widgetId:this.widgetId,oldConfig:n,newConfig:this.config})}reset(){this.isDestroyed||(this.isTriggered=!1,this.scrollUpDistance=0,this.isScrollingUp=!1,this.lastScrollY=window.scrollY,l.debug("ExitIntentTrigger reset",{widgetId:this.widgetId}))}getStats(){return Object.assign(Object.assign({},this.stats),{isTriggered:this.isTriggered,scrollUpDistance:this.scrollUpDistance,isScrollingUp:this.isScrollingUp,currentScrollY:window.scrollY,isDesktop:this.isDesktop(),isMobile:this.isMobile()})}isActive(){return this.isTriggered}forceActivate(e="desktop"){this.triggerActivated("exit-intent",{source:e,method:"manual",manual:!0})}destroy(){this.isDestroyed||(this.mouseLeaveListener&&(document.removeEventListener("mouseleave",this.mouseLeaveListener),document.removeEventListener("mouseout",this.mouseLeaveListener),this.mouseLeaveListener=null),this.backButtonListener&&(window.removeEventListener("popstate",this.backButtonListener),this.backButtonListener=null),this.scrollUpListener&&(window.removeEventListener("scroll",this.scrollUpListener),this.scrollUpListener=null),this.visibilityChangeListener&&(document.removeEventListener("visibilitychange",this.visibilityChangeListener),this.visibilityChangeListener=null),this.touchStartListener&&(document.removeEventListener("touchstart",this.touchStartListener),this.touchStartListener=null),this.touchEndListener&&(document.removeEventListener("touchend",this.touchEndListener),this.touchEndListener=null),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.isDestroyed=!0,l.debug("ExitIntentTrigger destroyed",{widgetId:this.widgetId}))}}const kt={"top-left":["top","left"],"top-center":["top","center"],"top-right":["top","right"],"center-left":["center","left"],center:["center","center"],"center-center":["center","center"],"center-right":["center","right"],"bottom-left":["bottom","left"],"bottom-center":["bottom","center"],"bottom-right":["bottom","right"]};class Et{constructor(){this.storageKey="widgetic-overlay-views",this.storageVersion="1.0"}static getInstance(){return Et.instance||(Et.instance=new Et),Et.instance}canShowOverlay(e,t){if(!(null==t?void 0:t.enabled))return!0;const i=this.getViewHistory(e,t),n=Date.now(),o=60*t.timePeriodHours*60*1e3,s=i.filter((e=>n-e.timestamp<=o)),r=s.length<t.maxViews;return l.debug(`[RecurrenceManager] Recurrence check for ${e}`,{maxViews:t.maxViews,timePeriodHours:t.timePeriodHours,recentViews:s.length,canShow:r}),r}recordView(e,t){if(!(null==t?void 0:t.enabled))return;const i={timestamp:Date.now(),widgetId:e},n=this.getViewHistory(e,t);n.push(i);const o=60*t.timePeriodHours*60*1e3,s=Date.now(),r=n.filter((e=>s-e.timestamp<=o));this.saveViewHistory(e,t,r),l.debug(`[RecurrenceManager] Recorded view for ${e}`,{totalViews:r.length,timePeriodHours:t.timePeriodHours})}getViewHistory(e,t){if(!this.isLocalStorageAvailable())return[];try{const i=this.getStorageKey(e,t),n=localStorage.getItem(i);if(!n)return[];const o=JSON.parse(n);return o.version!==this.storageVersion?[]:Array.isArray(o.views)?o.views:[]}catch(t){return l.warn(`[RecurrenceManager] Failed to load view history for ${e}`,{error:t}),[]}}saveViewHistory(e,t,i){if(this.isLocalStorageAvailable())try{const n=this.getStorageKey(e,t),o={version:this.storageVersion,widgetId:e,views:i,lastUpdated:Date.now()};localStorage.setItem(n,JSON.stringify(o))}catch(t){l.warn(`[RecurrenceManager] Failed to save view history for ${e}`,{error:t})}}getStorageKey(e,t){const i=(null==t?void 0:t.storageKeySuffix)?`-${t.storageKeySuffix}`:"";return`${this.storageKey}-${e}${i}`}isLocalStorageAvailable(){try{const e="__localStorage_test__";return localStorage.setItem(e,e),localStorage.removeItem(e),!0}catch(e){return!1}}getStats(e,t){if(!(null==t?void 0:t.enabled))return null;const i=this.getViewHistory(e,t),n=Date.now(),o=60*t.timePeriodHours*60*1e3,s=i.filter((e=>n-e.timestamp<=o));return{maxViews:t.maxViews,timePeriodHours:t.timePeriodHours,recentViews:s.length,remainingViews:Math.max(0,t.maxViews-s.length),canShow:s.length<t.maxViews,lastView:s.length>0?s[s.length-1].timestamp:null,viewHistory:s.map((e=>e.timestamp))}}clearHistory(e,t){if(!(null==t?void 0:t.enabled)||!this.isLocalStorageAvailable())return;const i=this.getStorageKey(e,t);localStorage.removeItem(i),l.debug(`[RecurrenceManager] Cleared view history for ${e}`)}cleanup(){if(!this.isLocalStorageAvailable())return;const e=[];for(let t=0;t<localStorage.length;t++){const i=localStorage.key(t);if(null==i?void 0:i.startsWith(this.storageKey))try{const t=JSON.parse(localStorage.getItem(i)||"{}"),n=Date.now()-864e5;t.lastUpdated<n&&e.push(i)}catch(t){e.push(i)}}e.forEach((e=>localStorage.removeItem(e))),e.length>0&&l.debug(`[RecurrenceManager] Cleaned up ${e.length} old view records`)}}class Mt{constructor(e){var t;this.scrollTrigger=null,this.exitIntentTrigger=null,this.portal=null,this.overlayContainer=null,this.originalParent=null,this.originalNextSibling=null,this.placeholder=null,this.isInOverlay=!1,this.isDestroyed=!1,this.triggerInstances=new Map,this.keydownListener=null,this.recurrenceManager=Et.getInstance(),this.delayTimer=null,this.domReadyListener=null,this.fullWidthRestore=null,this.onTriggerActivated=e=>this.handleTriggerActivated(e),this.onTriggerDeactivated=e=>this.handleTriggerDeactivated(e),this.onOverlayClose=e=>this.handleOverlayClose(e),this.widgetId=e.widgetId,this.element=e.element,this.config=Object.assign(Object.assign({},this.getDefaultConfig()),e.config),this.mode=this.config.mode||"site",this.displayWhenShown=null!==(t=e.displayWhenShown)&&void 0!==t?t:"",this.originalParent=this.element.parentElement,this.originalNextSibling=this.element.nextSibling,this.initialize()}getDefaultConfig(){return{mode:"site",scroll:{enabled:!0,threshold:.1,distance:100,direction:"down"},exitIntent:{enabled:!0,desktop:{enabled:!0,sensitivity:10,delay:100},mobile:{enabled:!0,backButton:!0,scrollUp:!0,tabSwitch:!0,sensitivity:50}},overlay:{position:"bottom-right",offset:{x:20,y:20},className:"",style:"",closeButton:!0,backdrop:!1,animation:"slide",background:{enabled:!0,color:"#000",opacity:.5}},recurrence:{enabled:!1,maxViews:1,timePeriodHours:24}}}initialize(){switch(l.debug("Initializing TriggerManager",{widgetId:this.widgetId,mode:this.mode,config:this.config}),this.mode){case"site":break;case"mixed":this.initializeScrollTrigger("viewport");break;case"overlay":this.hideWidget(),this.armOverlayEventTrigger()}this.bindEvents()}armOverlayEventTrigger(){switch(this.config.eventTrigger){case"pageLoad":this.showOnLoad();break;case"delay":this.showAfterDelay();break;case"scroll":this.initializeScrollTrigger("distance");break;default:this.initializeScrollTrigger("distance"),this.initializeExitIntentTrigger()}}whenDomReady(e){this.isDestroyed||("loading"===document.readyState?(this.domReadyListener=()=>{this.domReadyListener=null,this.isDestroyed||e()},document.addEventListener("DOMContentLoaded",this.domReadyListener,{once:!0})):e())}showOnLoad(){this.whenDomReady((()=>this.showOverlay()))}showAfterDelay(){var e,t;if(!1===(null===(e=this.config.delay)||void 0===e?void 0:e.enabled))return;const i=null===(t=this.config.delay)||void 0===t?void 0:t.delayMs,n="number"==typeof i&&Number.isFinite(i)&&i>=0?i:3e3;this.whenDomReady((()=>{null===this.delayTimer&&(this.delayTimer=setTimeout((()=>{this.delayTimer=null,this.showOverlay()}),n),l.debug("Delay trigger armed",{widgetId:this.widgetId,delayMs:n}))}))}initializeScrollTrigger(e){var t;(null===(t=this.config.scroll)||void 0===t?void 0:t.enabled)&&(this.scrollTrigger=new Tt({widgetId:this.widgetId,element:this.element,type:e,config:this.config.scroll}),this.triggerInstances.set("scroll",this.scrollTrigger))}initializeExitIntentTrigger(){var e;(null===(e=this.config.exitIntent)||void 0===e?void 0:e.enabled)&&(this.exitIntentTrigger=new St({widgetId:this.widgetId,config:this.config.exitIntent}),this.triggerInstances.set("exitIntent",this.exitIntentTrigger))}bindEvents(){document.addEventListener("widgetic:trigger-activated",this.onTriggerActivated),document.addEventListener("widgetic:trigger-deactivated",this.onTriggerDeactivated),document.addEventListener("widgetic:overlay-close",this.onOverlayClose),this.keydownListener=this.handleEscapeKey.bind(this),document.addEventListener("keydown",this.keydownListener)}handleTriggerActivated(e){const t=e;if(t.detail.widgetId!==this.widgetId)return;if("trigger-manager"===t.detail.source)return;const{triggerType:i,triggerData:n}=t.detail;l.debug("Trigger activated",{widgetId:this.widgetId,triggerType:i,triggerData:n}),"mixed"===this.mode&&"scroll-out-of-view"===i?this.showOverlay():"overlay"!==this.mode||"scroll-distance"!==i&&"exit-intent"!==i||this.showOverlay(),this.dispatchTriggerEvent("activated",i,n)}handleTriggerDeactivated(e){const t=e;if(t.detail.widgetId!==this.widgetId)return;if("trigger-manager"===t.detail.source)return;const{triggerType:i,triggerData:n}=t.detail;l.debug("Trigger deactivated",{widgetId:this.widgetId,triggerType:i,triggerData:n}),"mixed"===this.mode&&"scroll-back-in-view"===i&&this.hideOverlay(),this.dispatchTriggerEvent("deactivated",i,n)}handleOverlayClose(e){var t;(null===(t=e.detail)||void 0===t?void 0:t.widgetId)===this.widgetId&&(this.hideOverlay(),"overlay"===this.mode&&this.hideWidget())}handleEscapeKey(e){"Escape"===e.key&&this.isInOverlay&&(this.hideOverlay(),"overlay"===this.mode&&this.hideWidget())}showOverlay(){var e,t,i,n,o;if(!this.isInOverlay&&!this.isDestroyed){if("overlay"===this.mode&&(null===(e=this.config.recurrence)||void 0===e?void 0:e.enabled)){if(!this.recurrenceManager.canShowOverlay(this.widgetId,this.config.recurrence))return l.debug("Overlay blocked by recurrence limits",{widgetId:this.widgetId,recurrenceConfig:this.config.recurrence}),void this.dispatchEvent("overlay-blocked",{reason:"recurrence-limit",recurrenceStats:this.recurrenceManager.getStats(this.widgetId,this.config.recurrence)})}this.portal||(this.portal=z({target:"widgetic-trigger-portal",className:(null===(t=this.config.overlay)||void 0===t?void 0:t.className)||"",style:(null===(i=this.config.overlay)||void 0===i?void 0:i.style)||"",zIndex:this.getOverlayZIndex(),clickThrough:!this.hasOverlayBackground()})),this.overlayContainer=this.createOverlayContainer(),this.portal.mount(this.overlayContainer),this.leavePlaceholder(),this.overlayContainer.appendChild(this.element),this.element.style.display=this.displayWhenShown,this.applyFullWidthSizing(),this.isInOverlay=!0,"overlay"===this.mode&&(null===(n=this.config.recurrence)||void 0===n?void 0:n.enabled)&&this.recurrenceManager.recordView(this.widgetId,this.config.recurrence),l.debug("Widget moved to overlay",{widgetId:this.widgetId}),this.dispatchEvent("overlay-shown",{mode:this.mode,position:null===(o=this.config.overlay)||void 0===o?void 0:o.position})}}leavePlaceholder(){var e;if("mixed"!==this.mode||this.placeholder)return;const t=this.element.parentNode;if(!t)return;const{width:i,height:n}=this.element.getBoundingClientRect(),o=document.createElement("div");o.setAttribute("data-widgetic-placeholder",this.widgetId),o.setAttribute("aria-hidden","true"),o.style.cssText=`display:block;visibility:hidden;pointer-events:none;width:${i}px;height:${n}px;`,t.insertBefore(o,this.element),this.placeholder=o,null===(e=this.scrollTrigger)||void 0===e||e.observeElement(o)}returnToPlaceholder(){const e=this.placeholder;return!!e&&(this.placeholder=null,!!e.parentNode&&(e.parentNode.replaceChild(this.element,e),!0))}hideOverlay(){var e;this.isInOverlay&&!this.isDestroyed&&(this.restoreFullWidthSizing(),!this.returnToPlaceholder()&&this.originalParent&&(this.originalNextSibling?this.originalParent.insertBefore(this.element,this.originalNextSibling):this.originalParent.appendChild(this.element)),"mixed"===this.mode&&(null===(e=this.scrollTrigger)||void 0===e||e.observeElement(this.element)),this.portal&&this.portal.unmount(),this.overlayContainer=null,this.isInOverlay=!1,l.debug("Widget returned to original position",{widgetId:this.widgetId}),this.dispatchEvent("overlay-hidden",{mode:this.mode}))}hideWidget(){this.element.style.display="none"}createOverlayContainer(){var e,t,i,n,o;const s=document.createElement("div");s.className="widgetic-trigger-overlay";const r=(null===(e=this.config.overlay)||void 0===e?void 0:e.position)||"bottom-right",a=(null===(t=this.config.overlay)||void 0===t?void 0:t.offset)||{x:20,y:20},d=this.hasOverlayBackground(),c=!!(null===(i=this.config.overlay)||void 0===i?void 0:i.fullWidth),l=this.getOverlayStyles(r,a,this.getOverlayZIndex(),c);if(s.style.cssText=l,d&&this.applyBackgroundStyling(s),null===(n=this.config.overlay)||void 0===n?void 0:n.closeButton){const e=this.createCloseButton(d,c);s.appendChild(e)}return(null===(o=this.config.overlay)||void 0===o?void 0:o.animation)&&s.classList.add(`widgetic-trigger-overlay-${this.config.overlay.animation}`),this.applyOverlayWidgetStyling(s),s}applyBackgroundStyling(e){var t,i;const n=null===(t=this.config.overlay)||void 0===t?void 0:t.background,o=(null==n?void 0:n.color)||"#000000",s=null!==(i=null==n?void 0:n.opacity)&&void 0!==i?i:.5,r=document.createElement("div");r.className="widgetic-trigger-overlay-backdrop",r.style.cssText=`\n position: fixed;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n background-color: ${o};\n opacity: ${s};\n pointer-events: auto;\n z-index: -1;\n `,r.addEventListener("click",(e=>{e.target===r&&this.dispatchEvent("overlay-close",{widgetId:this.widgetId})})),e.insertBefore(r,e.firstChild),e.classList.add("widgetic-trigger-overlay-has-background")}hasOverlayBackground(){var e,t,i;return!(!(null===(t=null===(e=this.config.overlay)||void 0===e?void 0:e.background)||void 0===t?void 0:t.enabled)&&!(null===(i=this.config.overlay)||void 0===i?void 0:i.backdrop))}getOverlayZIndex(){var e;const t=null===(e=this.config.overlay)||void 0===e?void 0:e.zIndex;return"number"!=typeof t||!Number.isFinite(t)||t<=0?99999999:Math.min(Math.floor(t),de)}getOverlayStyles(e,t,i,n){const[o,s]=kt[e]||kt["bottom-right"];let r=`\n position: fixed;\n z-index: ${i};\n pointer-events: auto;\n max-height: 90vh;\n `;return n?r+="left: 0; right: 0; width: 100%; max-width: 100vw;":(r+="max-width: 90vw;",r+="left"===s?`left: ${t.x}px;`:"right"===s?`right: ${t.x}px;`:"left: 0; right: 0; margin-left: auto; margin-right: auto; width: -moz-fit-content; width: fit-content;"),r+="top"===o?`top: ${n?0:t.y}px;`:"bottom"===o?`bottom: ${n?0:t.y}px;`:"top: 0; bottom: 0; margin-top: auto; margin-bottom: auto; height: -moz-fit-content; height: fit-content;",r}applyFullWidthSizing(){var e;if(!(null===(e=this.config.overlay)||void 0===e?void 0:e.fullWidth)||this.fullWidthRestore)return;const t=Array.from(this.element.querySelectorAll("iframe"));this.fullWidthRestore={elementWidth:this.element.style.width,iframes:t.map((e=>({iframe:e,width:e.style.width})))},this.element.style.width="100%",t.forEach((e=>{e.style.width="100%"}))}restoreFullWidthSizing(){this.fullWidthRestore&&(this.element.style.width=this.fullWidthRestore.elementWidth,this.fullWidthRestore.iframes.forEach((({iframe:e,width:t})=>{e.style.width=t})),this.fullWidthRestore=null)}createCloseButton(e,t=!1){const i=document.createElement("button");i.className="widgetic-trigger-overlay-close",i.setAttribute("aria-label",It("closeOverlay")),i.setAttribute("type","button");const n=this.createCloseSVG();i.appendChild(n);const o=t?"\n position: absolute;\n top: 8px;\n right: 8px;\n ":e?"\n position: absolute;\n top: 20px;\n right: 20px;\n ":"\n position: absolute;\n top: -16px;\n right: -16px;\n ";return i.style.cssText=o+"\n width: 32px;\n height: 32px;\n border-radius: 50%;\n border: none;\n background: #000000;\n color: #ffffff;\n cursor: pointer;\n z-index: 1;\n display: flex;\n align-items: center;\n justify-content: center;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);\n transition: all 0.2s ease;\n ",i.addEventListener("mouseenter",(()=>{i.style.backgroundColor="#333333",i.style.transform="scale(1.1)"})),i.addEventListener("mouseleave",(()=>{i.style.backgroundColor="#000000",i.style.transform="scale(1)"})),i.addEventListener("click",(e=>{e.stopPropagation(),this.dispatchEvent("overlay-close",{widgetId:this.widgetId})})),i}createCloseSVG(){const e=document.createElementNS("http://www.w3.org/2000/svg","svg");e.setAttribute("width","16"),e.setAttribute("height","16"),e.setAttribute("viewBox","0 0 16 16"),e.setAttribute("fill","none"),e.style.pointerEvents="none";const t=document.createElementNS("http://www.w3.org/2000/svg","path");return t.setAttribute("d","M12 4L4 12M4 4l8 8"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","2"),t.setAttribute("stroke-linecap","round"),t.setAttribute("stroke-linejoin","round"),e.appendChild(t),e}dispatchTriggerEvent(e,t,i){this.dispatchEvent(`trigger-${e}`,{triggerType:t,triggerData:i,mode:this.mode,isInOverlay:this.isInOverlay})}dispatchEvent(e,t){const i=new CustomEvent(`widgetic:${e}`,{detail:Object.assign(Object.assign({widgetId:this.widgetId},t),{source:"trigger-manager"})});document.dispatchEvent(i)}updateConfig(e){this.isDestroyed||(this.config=Object.assign(Object.assign({},this.config),e),this.triggerInstances.forEach(((e,t)=>{"scroll"===t&&this.config.scroll?e.updateConfig(this.config.scroll):"exitIntent"===t&&this.config.exitIntent&&e.updateConfig(this.config.exitIntent)})),l.debug("TriggerManager config updated",{widgetId:this.widgetId,config:this.config}))}getStats(){var e;const t={widgetId:this.widgetId,mode:this.mode,isInOverlay:this.isInOverlay,isDestroyed:this.isDestroyed,triggerInstances:Array.from(this.triggerInstances.keys())};return this.triggerInstances.forEach(((e,i)=>{"function"==typeof e.getStats&&(t[`${i}Stats`]=e.getStats())})),(null===(e=this.config.recurrence)||void 0===e?void 0:e.enabled)&&(t.recurrenceStats=this.recurrenceManager.getStats(this.widgetId,this.config.recurrence)),t}forceShowOverlay(){this.showOverlay()}forceHideOverlay(){this.hideOverlay()}getRecurrenceStats(){var e;return(null===(e=this.config.recurrence)||void 0===e?void 0:e.enabled)?this.recurrenceManager.getStats(this.widgetId,this.config.recurrence):null}clearRecurrenceHistory(){var e;(null===(e=this.config.recurrence)||void 0===e?void 0:e.enabled)&&(this.recurrenceManager.clearHistory(this.widgetId,this.config.recurrence),l.debug("Recurrence history cleared",{widgetId:this.widgetId}))}canShowOverlay(){var e;return"overlay"!==this.mode||!(null===(e=this.config.recurrence)||void 0===e?void 0:e.enabled)||this.recurrenceManager.canShowOverlay(this.widgetId,this.config.recurrence)}destroy(){this.isDestroyed||(null!==this.delayTimer&&(clearTimeout(this.delayTimer),this.delayTimer=null),this.domReadyListener&&(document.removeEventListener("DOMContentLoaded",this.domReadyListener),this.domReadyListener=null),this.isInOverlay&&this.hideOverlay(),this.placeholder&&(this.placeholder.remove(),this.placeholder=null),this.triggerInstances.forEach((e=>{"function"==typeof e.destroy&&e.destroy()})),this.triggerInstances.clear(),this.portal&&(this.portal.destroy(),this.portal=null),document.removeEventListener("widgetic:trigger-activated",this.onTriggerActivated),document.removeEventListener("widgetic:trigger-deactivated",this.onTriggerDeactivated),document.removeEventListener("widgetic:overlay-close",this.onOverlayClose),this.keydownListener&&(document.removeEventListener("keydown",this.keydownListener),this.keydownListener=null),this.recurrenceManager.cleanup(),this.isDestroyed=!0,this.overlayContainer=null,this.originalParent=null,this.originalNextSibling=null,l.debug("TriggerManager destroyed",{widgetId:this.widgetId}))}applyOverlayWidgetStyling(e){var t;if(!("mixed"===this.mode))return;if(!1!==(null===(t=this.config.overlay)||void 0===t?void 0:t.keepDimensions))return;const i=this.config.overlay;if(i){if(i.overlayWidth){const t="number"==typeof i.overlayWidth?`${i.overlayWidth}px`:i.overlayWidth;e.style.width=t,e.style.maxWidth=t}if(i.overlayHeight){const t="number"==typeof i.overlayHeight?`${i.overlayHeight}px`:i.overlayHeight;e.style.height=t,e.style.maxHeight=t}i.overlayResize&&this.applyOverlayResizeMode(e,i.overlayResize)}}applyOverlayResizeMode(e,t){switch(t){case"fill-width":e.style.width="90vw",e.style.height="auto",e.style.maxWidth="90vw";break;case"fill-height":e.style.height="90vh",e.style.width="auto",e.style.maxHeight="90vh";break;case"fixed":e.style.flexShrink="0";break;case"fixed-height":e.style.width="90vw",e.style.maxWidth="90vw";break;case"fixed-width":e.style.height="90vh",e.style.maxHeight="90vh";break;case"allow-scale-down":e.style.maxWidth="90vw",e.style.maxHeight="90vh";break;case"fill":e.style.width="90vw",e.style.height="90vh",e.style.maxWidth="90vw",e.style.maxHeight="90vh"}}}var Ct=Object.freeze({__proto__:null,TriggerManager:Mt});class Dt{constructor(e,t){this._active=!0,this.id=`sub_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,this.compositionId=e,this.handler=t}isActive(){return this._active}unsubscribe(){this._active=!1}}class At{constructor(e){this.pollTimer=null,this.lastPoll=0,this.interval=e.interval,this.endpoint=e.endpoint,this.subscriptions=e.subscriptions,this.realtimeManager=e.realtimeManager}start(){return r(this,void 0,void 0,(function*(){this.pollTimer||(l.info("[PollingFallback] Starting polling fallback",{interval:this.interval,subscriptions:this.subscriptions.size}),this.pollTimer=setInterval((()=>{this.pollForUpdates()}),this.interval),yield this.pollForUpdates())}))}stop(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null),l.info("[PollingFallback] Polling fallback stopped")}pollForUpdates(){return r(this,void 0,void 0,(function*(){if(0!==this.subscriptions.size)try{const e=yield fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":this.realtimeManager.getApiKey()},body:JSON.stringify({compositionIds:Array.from(this.subscriptions),since:this.lastPoll})});if(!e.ok)throw new Error(`Polling failed: ${e.status}`);const t=yield e.json();for(const e of t.updates||[])yield this.realtimeManager.handlePolledUpdate(e);this.lastPoll=Date.now()}catch(e){l.error("[PollingFallback] Polling error:",e)}}))}}class Wt{constructor(e){this.socket=null,this.connectionState="disconnected",this.connectionId=null,this.subscriptions=new Map,this.allSubscriptions=new Map,this.reconnectAttempts=0,this.reconnectTimer=null,this.messageQueue=new Map,this.retryTimer=null,this.heartbeatTimer=null,this.lastHeartbeat=0,this.heartbeatTimeout=null,this.pollingFallback=null,this.connectionStartTime=0,this.messageStats={sent:0,received:0,errors:0};const t={enabled:!0,wsUrl:"wss://realtime.widgetic.com",authentication:{type:"apikey",credentials:""},features:{contentUpdates:!0,styleUpdates:!0,configUpdates:!1,dataUpdates:!0},security:{validateUpdates:!0,rateLimitPerMinute:30,allowedUpdateTypes:["content","style","data"]},reconnection:{enabled:!0,maxAttempts:5,baseDelay:1e3,maxDelay:3e4},fallback:{enabled:!0,pollInterval:5e3},heartbeat:{enabled:!0,interval:3e4,timeout:1e4}};this.config=Object.assign(Object.assign(Object.assign({},t),e),{authentication:Object.assign(Object.assign({},t.authentication),e.authentication),features:Object.assign(Object.assign({},t.features),e.features),security:Object.assign(Object.assign({},t.security),e.security),reconnection:Object.assign(Object.assign({},t.reconnection),e.reconnection),fallback:Object.assign(Object.assign({},t.fallback),e.fallback),heartbeat:Object.assign(Object.assign({},t.heartbeat),e.heartbeat)}),this.securityManager=J(),this.performanceMonitor=K(),this.setupEventListeners()}static getInstance(e){return Wt.instance||(Wt.instance=new Wt(e||{})),Wt.instance}initialize(){return r(this,void 0,void 0,(function*(){this.config.enabled?"connected"!==this.connectionState&&"connecting"!==this.connectionState&&(l.info("[RealtimeManager] Initializing real-time connection"),yield this.connect()):l.info("[RealtimeManager] Real-time updates disabled")}))}connect(){return r(this,void 0,void 0,(function*(){if("connected"!==this.connectionState&&"connecting"!==this.connectionState){this.connectionState="connecting",this.connectionStartTime=Date.now();try{const e=this.buildWebSocketUrl();l.info("[RealtimeManager] Connecting to WebSocket:",e),this.socket=new WebSocket(e),this.socket.onopen=this.handleConnect.bind(this),this.socket.onmessage=this.handleMessage.bind(this),this.socket.onclose=this.handleDisconnect.bind(this),this.socket.onerror=this.handleError.bind(this)}catch(e){throw this.connectionState="error",l.error("[RealtimeManager] Connection failed:",e),yield this.handleConnectionError(e),e}}}))}subscribe(e,t){const i=new Dt(e,t);return this.subscriptions.has(e)||this.subscriptions.set(e,new Set),this.subscriptions.get(e).add(i),this.allSubscriptions.set(i.id,i),"connected"===this.connectionState?this.sendMessage({type:"subscribe",compositionId:e,subscriptionId:i.id,timestamp:Date.now()}):this.queueMessage(e,{type:"subscribe",compositionId:e,subscriptionId:i.id,timestamp:Date.now()}),l.info("[RealtimeManager] Subscribed to composition:",{compositionId:e,subscriptionId:i.id,totalSubscriptions:this.allSubscriptions.size}),i}unsubscribe(e){e.unsubscribe();const t=this.subscriptions.get(e.compositionId);t&&(t.delete(e),0===t.size&&this.subscriptions.delete(e.compositionId)),this.allSubscriptions.delete(e.id),"connected"===this.connectionState&&this.sendMessage({type:"unsubscribe",compositionId:e.compositionId,subscriptionId:e.id,timestamp:Date.now()}),l.info("[RealtimeManager] Unsubscribed from composition:",{compositionId:e.compositionId,subscriptionId:e.id,remainingSubscriptions:this.allSubscriptions.size})}getActiveSubscriptions(){return new Set(this.subscriptions.keys())}getApiKey(){return this.config.authentication.credentials}handlePolledUpdate(e){return r(this,void 0,void 0,(function*(){try{const t={type:e.type,compositionId:e.compositionId,data:e.data,userId:e.userId,timestamp:e.timestamp,version:e.version,partial:e.partial};yield this.processUpdate(t,{fromPolling:!0})}catch(e){l.error("[RealtimeManager] Failed to process polled update:",e)}}))}buildWebSocketUrl(){const e=this.config.wsUrl,t=new URLSearchParams;switch(this.config.authentication.type){case"apikey":t.append("apikey",this.config.authentication.credentials);break;case"jwt":t.append("token",this.config.authentication.credentials);break;case"session":t.append("session",this.config.authentication.credentials)}return t.append("client","embed-sdk"),t.append("version","1.0.0"),`${e}?${t.toString()}`}handleConnect(){var e;this.connectionState="connected",this.reconnectAttempts=0;const t=Date.now()-this.connectionStartTime;l.info("[RealtimeManager] Connected to real-time service",{connectionTime:t,subscriptions:this.subscriptions.size}),null===(e=this.performanceMonitor)||void 0===e||e.recordCustomMetric("realtime_connection_time",t),this.pollingFallback&&(this.pollingFallback.stop(),this.pollingFallback=null),this.startHeartbeat(),this.processMessageQueue(),this.reestablishSubscriptions(),this.emitEvent("connected",{connectionTime:t})}handleMessage(e){return r(this,void 0,void 0,(function*(){this.messageStats.received++;try{const t=JSON.parse(e.data);switch(t.type){case"widget_update":yield this.handleWidgetUpdate(t);break;case"subscription_confirmed":this.handleSubscriptionConfirmed(t);break;case"heartbeat":this.handleHeartbeat(t);break;case"error":this.handleServerError(t);break;case"authentication":this.handleAuthentication(t);break;default:l.warn("[RealtimeManager] Unknown message type:",t.type)}}catch(e){this.messageStats.errors++,l.error("[RealtimeManager] Message parsing failed:",e)}}))}handleWidgetUpdate(e){return r(this,void 0,void 0,(function*(){const{compositionId:t,updateType:i,data:n,userId:o,timestamp:s,version:r,partial:a}=e;if(!this.config.features[`${i}Updates`])return void l.warn("[RealtimeManager] Update type disabled:",i);if(!this.config.security.allowedUpdateTypes.includes(i))return void l.warn("[RealtimeManager] Update type not allowed:",i);const d=this.subscriptions.get(t);if(!d||0===d.size)return void l.debug("[RealtimeManager] No subscriptions for composition:",t);const c={type:i,compositionId:t,data:n,userId:o,timestamp:s,version:r,partial:a};yield this.processUpdate(c,{fromWebSocket:!0})}))}processUpdate(e){return r(this,arguments,void 0,(function*(e,t={}){var i;try{if(this.config.security.validateUpdates){const t=yield this.securityManager.validateContent(e.compositionId,JSON.stringify(e.data),{userId:e.userId});if(!t.allowed)return l.warn("[RealtimeManager] Update blocked by security:",{compositionId:e.compositionId,violations:t.violations}),void this.emitEvent("security_violation",{compositionId:e.compositionId,violations:t.violations,update:e});if(t.filteredContent)try{e.data=JSON.parse(t.filteredContent)}catch(e){l.warn("[RealtimeManager] Failed to parse filtered content, using original")}}const n=this.subscriptions.get(e.compositionId);if(!n)return;const o=[];for(const t of n)t.isActive()&&o.push(t.handler(e).catch((i=>{l.error("[RealtimeManager] Handler execution failed:",{subscriptionId:t.id,compositionId:e.compositionId,error:i})})));yield Promise.allSettled(o),l.debug("[RealtimeManager] Update applied:",{compositionId:e.compositionId,type:e.type,handlerCount:o.length,source:t.fromWebSocket?"websocket":"polling"}),null===(i=this.performanceMonitor)||void 0===i||i.recordCustomMetric("realtime_updates_processed",1),this.emitEvent("update_applied",{compositionId:e.compositionId,type:e.type,handlerCount:o.length})}catch(t){l.error("[RealtimeManager] Update processing failed:",t),this.emitEvent("update_error",{compositionId:e.compositionId,error:t instanceof Error?t.message:"Unknown error",update:e})}}))}handleSubscriptionConfirmed(e){l.info("[RealtimeManager] Subscription confirmed:",{compositionId:e.compositionId,subscriptionId:e.subscriptionId})}handleHeartbeat(e){this.lastHeartbeat=Date.now(),this.heartbeatTimeout&&(clearTimeout(this.heartbeatTimeout),this.heartbeatTimeout=null),this.sendMessage({type:"heartbeat_response",timestamp:Date.now()})}handleServerError(e){l.error("[RealtimeManager] Server error:",e.data),this.emitEvent("server_error",{error:e.data})}handleAuthentication(e){var t,i,n;(null===(t=e.data)||void 0===t?void 0:t.success)?(this.connectionId=e.data.connectionId,l.info("[RealtimeManager] Authentication successful:",{connectionId:this.connectionId})):(l.error("[RealtimeManager] Authentication failed:",null===(i=e.data)||void 0===i?void 0:i.error),null===(n=this.socket)||void 0===n||n.close())}handleDisconnect(e){this.connectionState="disconnected",this.connectionId=null,l.warn("[RealtimeManager] Disconnected from real-time service:",{code:e.code,reason:e.reason,wasClean:e.wasClean}),this.stopHeartbeat(),this.config.reconnection.enabled&&!e.wasClean&&this.scheduleReconnection(),this.config.fallback.enabled&&this.subscriptions.size>0&&this.enablePollingFallback(),this.emitEvent("disconnected",{code:e.code,reason:e.reason,wasClean:e.wasClean})}handleError(e){var t;this.messageStats.errors++,l.error("[RealtimeManager] WebSocket error:",e),null===(t=this.performanceMonitor)||void 0===t||t.recordCustomMetric("realtime_errors",1),this.emitEvent("error",{event:e})}handleConnectionError(e){return r(this,void 0,void 0,(function*(){l.error("[RealtimeManager] Connection error:",e),this.config.reconnection.enabled?yield this.scheduleReconnection():this.config.fallback.enabled&&this.enablePollingFallback()}))}scheduleReconnection(){return r(this,void 0,void 0,(function*(){if(this.reconnectAttempts>=this.config.reconnection.maxAttempts)return l.error("[RealtimeManager] Max reconnection attempts reached"),this.config.fallback.enabled&&this.enablePollingFallback(),void this.emitEvent("max_reconnect_attempts",{attempts:this.reconnectAttempts});this.connectionState="reconnecting",this.reconnectAttempts++;const e=Math.min(this.config.reconnection.baseDelay*Math.pow(2,this.reconnectAttempts-1),this.config.reconnection.maxDelay);l.info("[RealtimeManager] Scheduling reconnection:",{attempt:this.reconnectAttempts,delay:e,maxAttempts:this.config.reconnection.maxAttempts}),this.reconnectTimer=setTimeout((()=>r(this,void 0,void 0,(function*(){try{yield this.connect()}catch(e){l.error("[RealtimeManager] Reconnection failed:",e),yield this.scheduleReconnection()}}))),e)}))}enablePollingFallback(){!this.pollingFallback&&this.config.fallback.enabled&&(l.info("[RealtimeManager] Enabling polling fallback"),this.pollingFallback=new At({interval:this.config.fallback.pollInterval||5e3,endpoint:"/api/widgets/updates",subscriptions:this.getActiveSubscriptions(),realtimeManager:this}),this.pollingFallback.start(),this.emitEvent("fallback_enabled",{interval:this.config.fallback.pollInterval}))}sendMessage(e){if("connected"===this.connectionState&&this.socket)try{this.socket.send(JSON.stringify(e)),this.messageStats.sent++}catch(t){this.messageStats.errors++,l.error("[RealtimeManager] Failed to send message:",t),this.queueMessage(e.compositionId||"global",e)}else this.queueMessage(e.compositionId||"global",e)}queueMessage(e,t){this.messageQueue.has(e)||this.messageQueue.set(e,[]);this.messageQueue.get(e).push({message:t,retryCount:0,maxRetries:3,timestamp:Date.now(),nextRetry:Date.now()+1e3}),this.retryTimer||(this.retryTimer=setTimeout((()=>this.processRetryQueue()),1e3))}processRetryQueue(){const e=Date.now();let t=!1;for(const[i,n]of this.messageQueue){const o=[];for(const i of n)e>=i.nextRetry?i.retryCount<i.maxRetries?(i.retryCount++,i.nextRetry=e+1e3*Math.pow(2,i.retryCount),this.sendMessage(i.message),i.retryCount<i.maxRetries&&o.push(i)):l.warn("[RealtimeManager] Message retry limit exceeded:",i.message):(o.push(i),t=!0);o.length>0?this.messageQueue.set(i,o):this.messageQueue.delete(i)}this.retryTimer=null,t&&(this.retryTimer=setTimeout((()=>this.processRetryQueue()),1e3))}processMessageQueue(){if("connected"===this.connectionState){l.info("[RealtimeManager] Processing queued messages:",{queueSize:Array.from(this.messageQueue.values()).reduce(((e,t)=>e+t.length),0)});for(const[e,t]of this.messageQueue)for(const e of t)this.sendMessage(e.message);this.messageQueue.clear(),this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null)}}reestablishSubscriptions(){if(0!==this.subscriptions.size){l.info("[RealtimeManager] Re-establishing subscriptions:",{count:this.subscriptions.size});for(const[e,t]of this.subscriptions)for(const i of t)i.isActive()&&this.sendMessage({type:"subscribe",compositionId:e,subscriptionId:i.id,timestamp:Date.now()})}}startHeartbeat(){this.config.heartbeat.enabled&&(this.stopHeartbeat(),this.heartbeatTimer=setInterval((()=>{"connected"===this.connectionState&&(this.sendMessage({type:"heartbeat",timestamp:Date.now()}),this.heartbeatTimeout=setTimeout((()=>{var e;l.warn("[RealtimeManager] Heartbeat timeout"),null===(e=this.socket)||void 0===e||e.close()}),this.config.heartbeat.timeout))}).bind(this),2*this.config.heartbeat.interval),this.lastHeartbeat=Date.now())}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.heartbeatTimeout&&(clearTimeout(this.heartbeatTimeout),this.heartbeatTimeout=null)}setupEventListeners(){"undefined"!=typeof document&&document.addEventListener("visibilitychange",(()=>{document.hidden?this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval((()=>{"connected"===this.connectionState&&this.sendMessage({type:"heartbeat",timestamp:Date.now()})}).bind(this),2*this.config.heartbeat.interval)):this.startHeartbeat()})),"undefined"!=typeof navigator&&"onLine"in navigator&&(window.addEventListener("online",(()=>{l.info("[RealtimeManager] Network back online"),"disconnected"===this.connectionState&&this.connect()})),window.addEventListener("offline",(()=>{l.warn("[RealtimeManager] Network offline"),this.pollingFallback&&this.pollingFallback.stop()})))}emitEvent(e,t){"undefined"!=typeof document&&document.dispatchEvent(new CustomEvent(`widgetic:realtime:${e}`,{detail:Object.assign({manager:this,timestamp:Date.now()},t)}))}getConnectionState(){return this.connectionState}getStats(){return{connectionState:this.connectionState,subscriptions:this.allSubscriptions.size,messageStats:Object.assign({},this.messageStats),reconnectAttempts:this.reconnectAttempts,lastHeartbeat:this.lastHeartbeat,queuedMessages:Array.from(this.messageQueue.values()).reduce(((e,t)=>e+t.length),0)}}disconnect(){l.info("[RealtimeManager] Disconnecting"),this.pollingFallback&&(this.pollingFallback.stop(),this.pollingFallback=null),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null),this.stopHeartbeat(),this.socket&&(this.socket.close(),this.socket=null),this.connectionState="disconnected",this.subscriptions.clear(),this.allSubscriptions.clear(),this.messageQueue.clear(),this.emitEvent("manual_disconnect",{})}}Wt.instance=null;class Ot{constructor(e={}){var t,i,n,o;this.widgets=new Map,this.widgetConfigs=new Map,this.compositionData=new Map,this.triggerManagers=new Map,this.compositionSubscriptions=new Map,this.compositionWidgets=new Map,this.eventListeners=new Map,this.errorHandlers=new Set,this.isInitialized=!1,this.responsiveState=null,this.config=Object.assign(Object.assign({},e),{security:Object.assign({enableSanitization:!0,enableRateLimit:!0,enableBotDetection:!0},e.security)}),this.apiConfig=new x(Object.assign(Object.assign({basePath:this.config.apiBaseUrl||("undefined"!=typeof window?window.location.origin:"http://localhost:3000")},this.config.apiKey&&{apiKey:this.config.apiKey}),this.config.accessToken&&{accessToken:this.config.accessToken})),this.widgetsApi=new U(this.apiConfig),this.compositionsApi=new R(this.apiConfig),this.securityManager=X.getInstance(this.config.security||{}),this.displayManager=new H,this.performanceMonitor=K(),(null===(t=e.realtime)||void 0===t?void 0:t.enabled)&&(this.realtimeManager=function(e){return Wt.getInstance(e)}(e.realtime)),this.setupResponsiveTracking(),this.setupEventListeners(),l.info("[WidgetManager] Initialized with config:",{realtimeEnabled:!!(null===(i=e.realtime)||void 0===i?void 0:i.enabled),securityEnabled:!!(null===(n=e.security)||void 0===n?void 0:n.enableSanitization),performanceEnabled:!!(null===(o=e.performance)||void 0===o?void 0:o.enabled)})}static getInstance(e){return Ot.instance||(Ot.instance=new Ot(e)),Ot.instance}initialize(){return r(this,void 0,void 0,(function*(){if(this.isInitialized)l.warn("[WidgetManager] Already initialized");else try{this.realtimeManager&&(yield this.realtimeManager.initialize(),l.info("[WidgetManager] Real-time manager initialized")),this.setupResponsiveTracking(),this.isInitialized=!0,this.emitEvent({type:"manager_initialized",widgetId:"system",timestamp:Date.now()}),l.info("[WidgetManager] Successfully initialized")}catch(e){throw l.error("[WidgetManager] Initialization failed:",e),this.emitError({code:"INIT_FAILED",message:"Widget manager initialization failed",widgetId:"system",timestamp:Date.now(),details:{error:e instanceof Error?e.message:"Unknown error"}}),e}}))}registerWidget(e,t,i){return r(this,void 0,void 0,(function*(){try{const n=yield this.validateWidgetConfig(t);if(!n.allowed)throw new Error(`Widget validation failed: ${n.reason}`);const o={id:e,config:t,element:i,state:{ready:!1,error:null,width:t.width,height:t.height},displayState:{mode:t.displayMode,isFullscreen:!1,isOverlay:!1,isPopup:!1},updateHandlers:new Map,lastUpdate:Date.now()},s=this.displayManager.initializeWidget(e,t,i);if(o.displayState=s,t.triggers)try{const n=new Mt({widgetId:e,element:i,config:t.triggers});this.triggerManagers.set(e,n),l.debug("[WidgetManager] Trigger manager setup completed:",{widgetId:e,triggers:t.triggers})}catch(t){l.warn("[WidgetManager] Failed to setup trigger manager:",{widgetId:e,error:t instanceof Error?t.message:"Unknown error"})}return this.realtimeManager&&t.compositionId&&(yield this.setupRealtimeUpdates(o)),this.widgets.set(e,o),this.widgetConfigs.set(e,t),o.state.ready=!0,l.info("[WidgetManager] Widget registered:",{widgetId:e,compositionId:t.compositionId,realtimeEnabled:!!o.realtimeSubscription}),this.emitEvent({type:"widget_registered",widgetId:e,data:{config:t},timestamp:Date.now()}),o}catch(t){throw l.error("[WidgetManager] Widget registration failed:",t),this.emitError({code:"REGISTRATION_FAILED",message:"Widget registration failed",widgetId:e,timestamp:Date.now(),details:{error:t instanceof Error?t.message:"Unknown error"}}),t}}))}setupRealtimeUpdates(e){return r(this,void 0,void 0,(function*(){if(this.realtimeManager&&e.config.compositionId)try{const t=e.config.compositionId;if(this.compositionWidgets.has(t)||this.compositionWidgets.set(t,new Set),this.compositionWidgets.get(t).add(e.id),this.compositionSubscriptions.has(t))l.info("[WidgetManager] Using existing real-time subscription for composition:",{compositionId:t,widgetCount:this.compositionWidgets.get(t).size});else{const e=e=>r(this,void 0,void 0,(function*(){yield this.handleCompositionUpdate(t,e)})),i=this.realtimeManager.subscribe(t,e);this.compositionSubscriptions.set(t,i),l.info("[WidgetManager] Real-time subscription created for composition:",{compositionId:t,subscriptionId:i.id,widgetCount:this.compositionWidgets.get(t).size})}e.realtimeSubscription=this.compositionSubscriptions.get(t)}catch(e){throw l.error("[WidgetManager] Failed to setup real-time updates:",e),e}}))}handleCompositionUpdate(e,t){return r(this,void 0,void 0,(function*(){var i,n;try{l.debug("[WidgetManager] Processing composition update:",{compositionId:e,updateType:t.type,timestamp:t.timestamp,affectedWidgets:(null===(i=this.compositionWidgets.get(e))||void 0===i?void 0:i.size)||0});const o=this.compositionWidgets.get(e);if(!o||0===o.size)return void l.warn("[WidgetManager] No widgets found for composition:",e);const s=[];for(const e of o){const i=this.widgets.get(e);i&&s.push(this.handleWidgetUpdate(i,t))}if(yield Promise.allSettled(s),"content"===t.type||"data"===t.type){const i=this.compositionData.get(e),n={id:e,widgetId:e,content:"content"===t.type?t.data:(null==i?void 0:i.content)||{},theme:(null==i?void 0:i.theme)||{},version:t.version||"1.0.0"};"data"===t.type&&(null==i?void 0:i.content)&&(n.content=Object.assign(Object.assign({},i.content),t.data)),this.compositionData.set(e,n)}this.emitEvent({type:"composition_updated",widgetId:e,data:{compositionId:e,updateType:t.type,updateData:t.data,timestamp:t.timestamp,affectedWidgets:Array.from(o)},timestamp:Date.now()}),null===(n=this.performanceMonitor)||void 0===n||n.recordCustomMetric("composition_updates_applied",1)}catch(i){l.error("[WidgetManager] Composition update failed:",i),this.emitError({code:"COMPOSITION_UPDATE_FAILED",message:"Composition update processing failed",widgetId:e,timestamp:Date.now(),details:{compositionId:e,updateType:t.type,error:i instanceof Error?i.message:"Unknown error"}})}}))}handleWidgetUpdate(e,t){return r(this,void 0,void 0,(function*(){try{switch(e.lastUpdate=Date.now(),t.type){case"content":yield this.handleContentUpdate(e,t);break;case"style":yield this.handleStyleUpdate(e,t);break;case"config":yield this.handleConfigUpdate(e,t);break;case"data":yield this.handleDataUpdate(e,t);break;default:l.warn("[WidgetManager] Unknown update type:",t.type)}this.emitEvent({type:"widget_updated",widgetId:e.id,data:{compositionId:e.config.compositionId,updateType:t.type,updateData:t.data,timestamp:t.timestamp},timestamp:Date.now()})}catch(i){l.error("[WidgetManager] Widget update failed:",i),this.emitError({code:"WIDGET_UPDATE_FAILED",message:"Widget update processing failed",widgetId:e.id,timestamp:Date.now(),details:{compositionId:e.config.compositionId,updateType:t.type,error:i instanceof Error?i.message:"Unknown error"}})}}))}handleContentUpdate(e,t){return r(this,void 0,void 0,(function*(){var i;if(e.config.compositionId){const i=this.compositionData.get(e.config.compositionId),n={id:e.config.compositionId,widgetId:e.config.compositionId,content:t.data,theme:(null==i?void 0:i.theme)||{},version:t.version||(null==i?void 0:i.version)||"1.0.0"};this.compositionData.set(e.config.compositionId,n)}yield this.applyContentToWidget(e,t.data);const n=null===(i=e.updateHandlers)||void 0===i?void 0:i.get("content");n&&(yield n(t.data))}))}handleStyleUpdate(e,t){return r(this,void 0,void 0,(function*(){var i;yield this.applyStylesToWidget(e,t.data);const n=null===(i=e.updateHandlers)||void 0===i?void 0:i.get("style");n&&(yield n(t.data))}))}handleConfigUpdate(e,t){return r(this,void 0,void 0,(function*(){var i;const n=Object.assign(Object.assign({},e.config),t.data),o=yield this.validateWidgetConfig(n);if(!o.allowed)throw new Error(`Config update validation failed: ${o.reason}`);if(e.config=n,this.widgetConfigs.set(e.id,n),t.data.displayMode||t.data.resize||t.data.width||t.data.height)try{this.displayManager.cleanup(e.id);const t=this.displayManager.initializeWidget(e.id,n,e.element);e.displayState=t,l.debug("[WidgetManager] Display management updated:",{widgetId:e.id,displayMode:n.displayMode})}catch(t){l.warn("[WidgetManager] Failed to update display management:",{widgetId:e.id,error:t instanceof Error?t.message:"Unknown error"})}const s=null===(i=e.updateHandlers)||void 0===i?void 0:i.get("config");s&&(yield s(t.data))}))}handleDataUpdate(e,t){return r(this,void 0,void 0,(function*(){var i;const n=null===(i=e.updateHandlers)||void 0===i?void 0:i.get("data");n?yield n(t.data):yield this.applyContentToWidget(e,t.data)}))}applyContentToWidget(e,t){return r(this,void 0,void 0,(function*(){try{if("string"==typeof t)if("iframe"===e.element.tagName.toLowerCase()){const i=e.element;i.contentWindow&&i.contentWindow.postMessage({type:"widgetic_content_update",content:t},f.CLIENT_URL||"*")}else{const i=yield this.sanitizeContent(t,e.id);e.element.innerHTML=i}else if("object"==typeof t)if("iframe"===e.element.tagName.toLowerCase()){const i=e.element;i.contentWindow&&i.contentWindow.postMessage({type:"widgetic_data_update",data:t},f.CLIENT_URL||"*")}else e.element.dispatchEvent(new CustomEvent("widgetic:data-update",{detail:t}));l.debug("[WidgetManager] Content applied to widget:",{widgetId:e.id,contentType:typeof t})}catch(e){throw l.error("[WidgetManager] Failed to apply content:",e),e}}))}applyStylesToWidget(e,t){return r(this,void 0,void 0,(function*(){try{"object"==typeof t?Object.entries(t).forEach((([t,i])=>{"string"!=typeof i&&"number"!=typeof i||(e.element.style[t]=i)})):"string"==typeof t&&(e.element.style.cssText+=t),l.debug("[WidgetManager] Styles applied to widget:",{widgetId:e.id,stylesType:typeof t})}catch(e){throw l.error("[WidgetManager] Failed to apply styles:",e),e}}))}sanitizeContent(e,t){return r(this,void 0,void 0,(function*(){const i=this.securityManager.validateTextFieldUpdate(t,"content",e);if(!i.allowed)throw new Error(`Content blocked by security: ${i.reason}`);return i.sanitizedText||e}))}validateWidgetConfig(e){return r(this,void 0,void 0,(function*(){var t;if(!e.compositionId)return{allowed:!1,reason:"Missing composition ID",severity:"high"};if(null===(t=this.config.security)||void 0===t?void 0:t.enableSanitization){const t=JSON.stringify(e),i=this.securityManager.validateTextFieldUpdate(e.compositionId,"config",t);if(!i.allowed)return{allowed:!1,reason:i.reason,severity:i.severity||"medium"}}return{allowed:!0}}))}setContent(e,t){return r(this,arguments,void 0,(function*(e,t,i={}){var n;try{l.debug("[WidgetManager] Setting dynamic content:",{compositionId:e,contentType:typeof t,options:i});const o={content:t};void 0!==i.validate&&(o.validate=i.validate),void 0!==i.partial&&(o.partial=i.partial),void 0!==i.version&&(o.version=i.version),void 0!==i.source&&(o.source=i.source);const s=yield this.compositionsApi.setDynamicContent({id:e,setDynamicContentRequest:P(o)}),a=this.getWidgetsByComposition(e),d=this.compositionData.get(e);let c=t;i.partial&&(null==d?void 0:d.content)&&(c=this.mergeContent(d.content,t));const h={id:e,widgetId:e,content:c,theme:(null==d?void 0:d.theme)||{},version:i.version||(null==d?void 0:d.version)||"1.0.0"};this.compositionData.set(e,h);const g=a.map((t=>r(this,void 0,void 0,(function*(){var n;try{yield this.applyContentToWidget(t,c);const o=null===(n=t.updateHandlers)||void 0===n?void 0:n.get("content");o&&(yield o(c)),t.lastUpdate=Date.now(),l.debug("[WidgetManager] Content applied to widget:",{widgetId:t.id,compositionId:e,source:i.source})}catch(e){throw l.error("[WidgetManager] Failed to update widget content:",{widgetId:t.id,error:e instanceof Error?e.message:"Unknown error"}),e}}))));return yield Promise.all(g),this.emitEvent({type:"content_updated",widgetId:e,data:{content:c,source:i.source,version:i.version,partial:i.partial},timestamp:Date.now()}),l.info("[WidgetManager] Content updated successfully via API:",{compositionId:e,widgetCount:a.length,source:i.source,realtimeUpdateSent:s.realtimeUpdateSent}),{success:null!==(n=s.success)&&void 0!==n&&n,validationResult:s.validationResult}}catch(t){const n=t instanceof Error?t.message:"Unknown error";return this.emitError({code:"CONTENT_UPDATE_FAILED",message:`Failed to set content: ${n}`,widgetId:e,timestamp:Date.now(),details:{error:n,options:i}}),{success:!1,error:n}}}))}getContentSchema(e){return r(this,void 0,void 0,(function*(){try{l.debug("[WidgetManager] Getting widget content schema:",{widgetId:e});const t=yield this.widgetsApi.getWidgetContentSchema({id:e});return l.debug("[WidgetManager] Content schema retrieved:",{widgetId:e,schema:t}),t}catch(t){throw l.error("[WidgetManager] Failed to get content schema:",t),this.emitError({code:"SCHEMA_FETCH_FAILED",message:`Failed to get content schema: ${t instanceof Error?t.message:"Unknown error"}`,widgetId:e,timestamp:Date.now()}),t}}))}getDesignSchema(e){return r(this,void 0,void 0,(function*(){try{l.debug("[WidgetManager] Getting widget design schema:",{widgetId:e});const t=yield this.widgetsApi.getWidgetDesignSchema({id:e});return l.debug("[WidgetManager] Design schema retrieved:",{widgetId:e,schema:t}),t}catch(t){throw l.error("[WidgetManager] Failed to get design schema:",t),this.emitError({code:"SCHEMA_FETCH_FAILED",message:`Failed to get design schema: ${t instanceof Error?t.message:"Unknown error"}`,widgetId:e,timestamp:Date.now()}),t}}))}validateContent(e,t){return r(this,void 0,void 0,(function*(){var i,n;try{l.debug("[WidgetManager] Validating content:",{compositionId:e});const o=yield this.compositionsApi.validateCompositionContent({id:e,body:P(t)});return l.debug("[WidgetManager] Content validation completed:",{compositionId:e,valid:null!==(i=o.valid)&&void 0!==i&&i}),{valid:null!==(n=o.valid)&&void 0!==n&&n,errors:o.errors,warnings:o.warnings,sanitizedContent:o.sanitizedContent}}catch(e){throw l.error("[WidgetManager] Content validation failed:",e),e}}))}getContent(e){const t=this.compositionData.get(e);return(null==t?void 0:t.content)||null}mergeContent(e,t){if(!e||"object"!=typeof e)return t;if(!t||"object"!=typeof t)return e;const i=Object.assign({},e);for(const[e,n]of Object.entries(t))n&&"object"==typeof n&&!Array.isArray(n)?i[e]=this.mergeContent(i[e],n):i[e]=n;return i}registerUpdateHandler(e,t,i){const n=this.widgets.get(e);if(!n)throw new Error(`Widget not found: ${e}`);n.updateHandlers||(n.updateHandlers=new Map),n.updateHandlers.set(t,i),l.info("[WidgetManager] Update handler registered:",{widgetId:e,updateType:t})}unregisterWidget(e){return r(this,void 0,void 0,(function*(){var t,i;const n=this.widgets.get(e);if(n)try{const o=n.config.compositionId;if(o&&this.compositionWidgets.has(o)&&(this.compositionWidgets.get(o).delete(e),0===this.compositionWidgets.get(o).size)){const e=this.compositionSubscriptions.get(o);e&&(null===(t=this.realtimeManager)||void 0===t||t.unsubscribe(e),this.compositionSubscriptions.delete(o),this.compositionWidgets.delete(o),l.info("[WidgetManager] Cleaned up composition subscription:",{compositionId:o,subscriptionId:e.id}))}try{this.displayManager.cleanup(e),l.debug("[WidgetManager] Display management cleaned up:",{widgetId:e})}catch(t){l.warn("[WidgetManager] Failed to cleanup display management:",{widgetId:e,error:t instanceof Error?t.message:"Unknown error"})}const s=this.triggerManagers.get(e);if(s)try{s.destroy(),this.triggerManagers.delete(e),l.debug("[WidgetManager] Trigger manager cleaned up:",{widgetId:e})}catch(t){l.warn("[WidgetManager] Failed to cleanup trigger manager:",{widgetId:e,error:t instanceof Error?t.message:"Unknown error"})}this.widgets.delete(e),this.widgetConfigs.delete(e),l.info("[WidgetManager] Widget unregistered:",{widgetId:e,compositionId:o,remainingWidgetsForComposition:(null===(i=this.compositionWidgets.get(o||""))||void 0===i?void 0:i.size)||0}),this.emitEvent({type:"widget_unregistered",widgetId:e,data:{compositionId:o},timestamp:Date.now()})}catch(t){l.error("[WidgetManager] Widget unregistration failed:",t),this.emitError({code:"UNREGISTRATION_FAILED",message:"Widget unregistration failed",widgetId:e,timestamp:Date.now(),details:{error:t instanceof Error?t.message:"Unknown error"}})}else l.warn("[WidgetManager] Widget not found for unregistration:",e)}))}getWidget(e){return this.widgets.get(e)}getAllWidgets(){return Array.from(this.widgets.values())}getWidgetsByComposition(e){const t=this.compositionWidgets.get(e);return t?Array.from(t).map((e=>this.widgets.get(e))).filter((e=>void 0!==e)):[]}setupResponsiveTracking(){if("undefined"==typeof window)return;const e=()=>{const e={mode:"mobile"===Me().getDeviceType()?"mobile":"desktop",breakpoint:768,width:window.innerWidth,timestamp:Date.now()};this.responsiveState&&this.responsiveState.mode===e.mode||(this.responsiveState=e,this.emitEvent({type:"responsive_change",widgetId:"system",data:e,timestamp:Date.now()}),this.handleResponsiveChange(e))};let t;e(),window.addEventListener("resize",(()=>{clearTimeout(t),t=setTimeout(e,250)}))}handleResponsiveChange(e){for(const t of this.widgets.values())try{const i=this.widgetConfigs.get(t.id);if(i&&t.displayState){this.displayManager.cleanup(t.id);const n=this.displayManager.initializeWidget(t.id,i,t.element);t.displayState=n,l.debug("[WidgetManager] Responsive update applied:",{widgetId:t.id,mode:e.mode,width:e.width})}this.emitEvent({type:"widget_responsive_change",widgetId:t.id,data:e,timestamp:Date.now()})}catch(e){l.error("[WidgetManager] Responsive change handling failed for widget:",{widgetId:t.id,error:e})}}addEventListener(e,t){this.eventListeners.has(e)||this.eventListeners.set(e,new Set),this.eventListeners.get(e).add(t)}removeEventListener(e,t){const i=this.eventListeners.get(e);i&&i.delete(t)}addErrorHandler(e){this.errorHandlers.add(e)}removeErrorHandler(e){this.errorHandlers.delete(e)}emitEvent(e){const t=this.eventListeners.get(e.type);t&&t.forEach((t=>{try{t(e)}catch(e){l.error("[WidgetManager] Event handler failed:",e)}}))}emitError(e){this.errorHandlers.forEach((t=>{try{t(e)}catch(e){l.error("[WidgetManager] Error handler failed:",e)}}))}setupEventListeners(){"undefined"!=typeof window&&(this.realtimeManager&&(document.addEventListener("widgetic:realtime:connected",(()=>{this.emitEvent({type:"realtime_connected",widgetId:"system",timestamp:Date.now()})})),document.addEventListener("widgetic:realtime:disconnected",(()=>{this.emitEvent({type:"realtime_disconnected",widgetId:"system",timestamp:Date.now()})})),document.addEventListener("widgetic:realtime:error",(e=>{this.emitError({code:"REALTIME_ERROR",message:"Real-time connection error",widgetId:"system",timestamp:Date.now(),details:e.detail})}))),document.addEventListener("visibilitychange",(()=>{const e=!document.hidden;this.emitEvent({type:"page_visibility_change",widgetId:"system",data:{visible:e},timestamp:Date.now()})})))}getTriggerManager(e){return this.triggerManagers.get(e)}getAllTriggerManagers(){return new Map(this.triggerManagers)}getStats(){return{widgets:this.widgets.size,compositions:this.compositionWidgets.size,compositionSubscriptions:this.compositionSubscriptions.size,triggerManagers:this.triggerManagers.size,responsiveState:this.responsiveState,isInitialized:this.isInitialized}}destroy(){return r(this,void 0,void 0,(function*(){l.info("[WidgetManager] Destroying widget manager");const e=Array.from(this.widgets.keys());yield Promise.allSettled(e.map((e=>this.unregisterWidget(e))));for(const[e,t]of this.triggerManagers)try{t.destroy(),l.debug("[WidgetManager] Trigger manager destroyed:",{widgetId:e})}catch(t){l.warn("[WidgetManager] Failed to destroy trigger manager:",{widgetId:e,error:t instanceof Error?t.message:"Unknown error"})}this.triggerManagers.clear();try{this.displayManager.cleanupAll(),l.debug("[WidgetManager] Display manager cleaned up")}catch(e){l.warn("[WidgetManager] Failed to cleanup display manager:",{error:e instanceof Error?e.message:"Unknown error"})}this.realtimeManager&&this.realtimeManager.disconnect(),this.eventListeners.clear(),this.errorHandlers.clear(),this.compositionSubscriptions.clear(),this.compositionWidgets.clear(),this.compositionData.clear(),this.isInitialized=!1,this.responsiveState=null,Ot.instance=null,l.info("[WidgetManager] Widget manager destroyed")}))}getActiveCompositions(){return Array.from(this.compositionWidgets.keys()).filter((e=>this.compositionWidgets.get(e).size>0))}getCompositionData(e){return this.compositionData.get(e)}}function xt(e){return Ot.getInstance(e)}Ot.instance=null;var Lt=Object.freeze({__proto__:null,WidgetManager:Ot,getWidgetManager:xt});let Rt=!1;class Ut{constructor(t={}){var i,n,o,s,r,a,d,c,h,g,u,p,v,f,I,T,S,k,E,C,D;this.version=m,this.instances=new Map,this.isInitialized=!1,this.renderer=e(),this.widgetControllers=new Map,this.authDetector=_(),this.editorOverlay=j(),this.displayManager=B(),this.resizeHandler=$(),this.authenticationStatus=null,this.overlayManager=null,this.hostObserverStarted=!1,this.config=Object.assign({renderMode:"auto",performance:{enabled:!1,config:{}},lazyLoading:{enabled:!0,config:{}}},t),this.browserCapabilities=M(),this.messenger=W(this.config.messagingOptions);const A=this.config.logLevel||(this.config.debug?"debug":"info");if(l.setLevel(A),b.enabled&&l.info("Initializing EmbedSDK",{version:m,config:this.config,browserCapabilities:this.browserCapabilities}),"updateConfig"in this.displayManager&&"function"==typeof this.displayManager.updateConfig&&this.displayManager.updateConfig(this.config.displayOptions||{}),"updateConfig"in this.resizeHandler&&"function"==typeof this.resizeHandler.updateConfig&&this.resizeHandler.updateConfig(this.config.resizeOptions||{}),!1!==(null===(i=this.config.performance)||void 0===i?void 0:i.enabled)){const e=Object.assign({enableTracking:y.ENABLE_PERFORMANCE_TRACKING,axiomApiKey:y.AXIOM_API_KEY,axiomDataset:y.AXIOM_DATASET,axiomApiEndpoint:y.AXIOM_API_ENDPOINT,statsigKey:y.STATSIG_API_KEY,statsigApiEndpoint:y.STATSIG_API_ENDPOINT},null===(n=this.config.performance)||void 0===n?void 0:n.config);V(e)}!1!==(null===(o=this.config.lazyLoading)||void 0===o?void 0:o.enabled)&&q((null===(s=this.config.lazyLoading)||void 0===s?void 0:s.config)||{}),void 0!==this.config.debug&&(w.setDebug(this.config.debug),this.config.debug&&w.setLevel("debug")),!1!==(null===(r=this.config.resourceOptimization)||void 0===r?void 0:r.enabled)&&Y((null===(a=this.config.resourceOptimization)||void 0===a?void 0:a.config)||{}),this.config.editorOptions&&(this.editorOverlay=j(this.config.editorOptions)),!1!==(null===(d=this.config.overlayConfig)||void 0===d?void 0:d.enabled)&&(this.overlayManager=N({enabled:!0,defaultMode:null===(c=this.config.overlayConfig)||void 0===c?void 0:c.defaultMode,exitIntentEnabled:null===(h=this.config.overlayConfig)||void 0===h?void 0:h.exitIntentEnabled,scrollTriggerEnabled:null===(g=this.config.overlayConfig)||void 0===g?void 0:g.scrollTriggerEnabled,timeTriggerEnabled:null===(u=this.config.overlayConfig)||void 0===u?void 0:u.timeTriggerEnabled,engagementThresholdEnabled:null===(p=this.config.overlayConfig)||void 0===p?void 0:p.engagementThresholdEnabled,externalTriggerEnabled:null===(v=this.config.overlayConfig)||void 0===v?void 0:v.externalTriggerEnabled,breakpoints:{useBreakpoints:(null===(I=null===(f=this.config.overlayConfig)||void 0===f?void 0:f.breakpoints)||void 0===I?void 0:I.useBreakpoints)||!1,mobile:(null===(S=null===(T=this.config.overlayConfig)||void 0===T?void 0:T.breakpoints)||void 0===S?void 0:S.mobile)||480,tablet:(null===(E=null===(k=this.config.overlayConfig)||void 0===k?void 0:k.breakpoints)||void 0===E?void 0:E.tablet)||768,desktop:(null===(D=null===(C=this.config.overlayConfig)||void 0===C?void 0:C.breakpoints)||void 0===D?void 0:D.desktop)||1024}})),l.info("Widgetic Embed SDK v1.0 initialized",{version:m,capabilities:this.browserCapabilities,editingEnabled:!1!==this.config.enableEditing,overlayEnabled:null!==this.overlayManager}),this.config.debug&&l.info("EmbedSDK initialized in debug mode",{config:this.config})}init(){return r(this,void 0,void 0,(function*(){var e,t;if(this.watchPublishedHosts(),yield this.scanPage(),this.isInitialized)l.warn("SDK already initialized");else if(Rt||"undefined"!=typeof window&&window.__WIDGETIC_SDK_INITIALIZED__)l.warn("SDK initialization detected, skipping duplicate setup");else try{if(this.isInitialized=!0,Rt=!0,"undefined"!=typeof window&&(window.__WIDGETIC_SDK_INITIALIZED__=!0),!1!==this.config.enableEditing&&this.checkAuthentication().catch((e=>{l.warn("Background authentication check failed",{error:e})})),this.config.preloadUISDK&&(null===(e=this.authenticationStatus)||void 0===e?void 0:e.isAuthenticated))try{const e=F();yield e.preload(),l.info("UI SDK preloaded successfully")}catch(e){l.warn("Failed to preload UI SDK",{error:e})}yield this.scanPage(),l.info("Widgetic Embed SDK initialized successfully",{version:m,capabilities:this.browserCapabilities,authenticationStatus:null===(t=this.authenticationStatus)||void 0===t?void 0:t.isAuthenticated}),yield this.scanPage()}catch(e){throw l.error("SDK initialization failed",{error:e}),e}}))}checkAuthentication(){return r(this,void 0,void 0,(function*(){var e;try{this.authenticationStatus=yield this.authDetector.checkAuthentication(),this.authenticationStatus.isAuthenticated?l.info("User authenticated for editing",{userId:null===(e=this.authenticationStatus.user)||void 0===e?void 0:e.id}):l.debug("User not authenticated for editing")}catch(e){l.debug("Authentication check failed",{error:e}),this.authenticationStatus={isAuthenticated:!1,canEdit:!1}}}))}enhance(){return r(this,void 0,void 0,(function*(){yield this.scanPage()}))}refresh(){return r(this,void 0,void 0,(function*(){l.info("Refreshing widgets"),yield this.scanPage()}))}watchPublishedHosts(){rt(),this.hostObserverStarted||"undefined"!=typeof MutationObserver&&"undefined"!=typeof document&&(this.hostObserverStarted=!0,new MutationObserver((()=>{rt()})).observe(document.documentElement,{childList:!0,subtree:!0}))}scanPage(){return r(this,void 0,void 0,(function*(){var e,t,i,n;const o=document.querySelectorAll("widgetic");if(l.debug("Found widgetic host elements",{count:o.length}),0===o.length)return void l.info("No widgets found on page");const s=[];for(const r of Array.from(o))if(C(r)&&r instanceof HTMLElement){if(st(r))continue;try{const o=E(r),a=null===(t=null===(e=o.device)||void 0===e?void 0:e.mobileEnabled)||void 0===t||t;if(!Ce(a,null===(n=null===(i=o.device)||void 0===i?void 0:i.desktopEnabled)||void 0===n||n)){l.debug("Widget skipped due to device restrictions",{compositionId:o.compositionId,deviceRestrictions:o.device,element:r.outerHTML.substring(0,100)+"..."}),r.style.display="none",r.setAttribute("data-device-restricted","true");continue}s.push({element:r,config:o})}catch(e){l.error("Failed to parse widget configuration",{element:r.outerHTML,error:e})}}0!==s.length?yield this.renderWidgetsBatch(s):l.warn("No valid widget configurations found")}))}renderWidgetsBatch(e){return r(this,void 0,void 0,(function*(){try{const t=[],i=e.map((({element:e,config:i})=>{let n=e;if(e.parentNode){const t=document.createElement("div");t.className=`widgetic-host ${e.className}`.trim(),e.getAttribute("style")&&(t.style.cssText=e.getAttribute("style")||""),e.parentNode.replaceChild(t,e),n=t}return t.push(n),{compositionId:i.compositionId,renderMode:D(i.renderMode,this.browserCapabilities),width:i.width,height:i.height,resize:i.resize,autoscale:i.autoscale,adaptive:i.adaptive,container:n}})),n=yield this.renderer.renderWidgets(i);for(let i=0;i<n.length;i++){const o=n[i],{config:s}=e[i],r=t[i],a=A(s.compositionId),d=this.displayManager.initializeWidget(a,s,o.element);o.element instanceof HTMLElement&&r instanceof HTMLElement&&this.resizeHandler.registerWidget(a,o.element,r.parentElement||r,s);const c={id:a,config:s,element:o.element,displayState:d,state:{ready:!0,error:null,width:"number"==typeof s.width?s.width:parseInt(String(s.width)),height:"number"==typeof s.height?s.height:parseInt(String(s.height))},enterFullscreen:()=>this.displayManager.enterFullscreen(a),exitFullscreen:()=>this.displayManager.exitFullscreen(a),showOverlay:()=>this.displayManager.showOverlay(a),hideOverlay:()=>this.displayManager.hideOverlay(a),openPopup:()=>this.displayManager.openPopup(a),closePopup:()=>this.displayManager.closePopup(a)};this.instances.set(c.id,c),yield this.maybeAddEditorOverlay(o.element,s.compositionId),l.debug("Widget rendered successfully",{instanceId:c.id,compositionId:s.compositionId,renderMode:o.renderMode,displayMode:s.displayMode})}l.info("Batch widget rendering complete",{rendered:n.length,total:e.length})}catch(t){l.error("Batch widget rendering failed",{error:t});for(const{element:t,config:i}of e)try{yield this.renderSingleWidget(t,i)}catch(e){l.error("Individual widget rendering failed",{compositionId:i.compositionId,error:e})}}}))}renderSingleWidget(e,t){return r(this,void 0,void 0,(function*(){try{performance.now(),K(),Q();const i=G();if(this.shouldUseLazyLoading(e,t))return void i.register(e,t.compositionId,(()=>r(this,void 0,void 0,(function*(){yield this.performActualWidgetRender(e,t)}))),{config:t,priority:this.getWidgetPriority(t),resourceUrls:this.getWidgetResourceUrls(t)});yield this.performActualWidgetRender(e,t)}catch(e){const i=K(),n=e instanceof Error?e.message:"Render failed";throw i.recordWidgetError(t.compositionId,n),i.endWidgetLoad(t.compositionId,!1),l.error("Widget rendering failed",{error:e,config:t}),e}}))}performActualWidgetRender(e,t){return r(this,void 0,void 0,(function*(){const i=performance.now(),n=K(),o=Q();try{const s=this.getWidgetResourceUrls(t);if(s.length>0&&(yield o.loadResources(s,{type:"script",priority:"high",compositionId:t.compositionId})),!("render"in this.renderer)||"function"!=typeof this.renderer.render)throw new Error("Widget renderer does not support render method");{const{widgetElement:o,instance:s}=yield this.renderer.render(e,t);if(!o)throw new Error("Widget element not created");const r=performance.now()-i;n.recordWidgetRender(t.compositionId,r),n.endWidgetLoad(t.compositionId,!0),this.instances.set(s.id,s)}}catch(e){const i=K(),n=e instanceof Error?e.message:"Render failed";throw i.recordWidgetError(t.compositionId,n),i.endWidgetLoad(t.compositionId,!1),l.error("Widget rendering failed",{error:e,config:t}),e}}))}shouldUseLazyLoading(e,t){var i;if(!1===(null===(i=this.config.lazyLoading)||void 0===i?void 0:i.enabled))return!1;if("critical"===t.priority||!0===t.preload)return!1;const n=e.getBoundingClientRect();return!(n.top<window.innerHeight&&n.bottom>0)}getWidgetPriority(e){switch(e.priority){case"critical":return 10;case"high":return 7;case"medium":default:return 5;case"low":return 2}}getWidgetResourceUrls(e){const t=[];return e.scriptUrl&&t.push(e.scriptUrl),e.styleUrl&&t.push(e.styleUrl),e.resourceUrls&&Array.isArray(e.resourceUrls)&&t.push(...e.resourceUrls),t}maybeAddEditorOverlay(e,t){return r(this,void 0,void 0,(function*(){if(!1!==this.config.enableEditing)try{yield this.editorOverlay.addOverlay(e,t)}catch(e){l.debug("Failed to add editor overlay",{compositionId:t,error:e})}}))}getInstances(){return Array.from(this.instances.values())}getInstance(e){return this.instances.get(e)||null}getInstancesByComposition(e){return this.getInstances().filter((t=>t.config.compositionId===e))}getStats(){const e=this.renderer.getStats();return{version:m,widgetsRendered:this.instances.size,renderMode:"auto",cacheStats:e.batchCache,messagingActive:this.messenger.isActive(),customEventSubscriptions:this.messenger.getCustomEventSubscriptions(),functionHandlers:this.messenger.getFunctionHandlers(),authenticationStatus:this.authenticationStatus||void 0,editingSessions:this.editorOverlay.getActiveSessions().length}}createWidgetController(e){const t=Array.from(this.instances.values()).find((t=>t.config.compositionId===e));if(!t)return l.warn("Widget instance not found for controller creation",{compositionId:e}),null;const i=this.messenger.createWidgetController(t.id,e);return this.widgetControllers.set(e,i),l.info("Widget controller created",{compositionId:e,instanceId:t.id}),i}getWidgetController(e){return this.widgetControllers.get(e)||null}subscribeToWidget(e,t,i){let n=this.getWidgetController(e);if(!n&&(n=this.createWidgetController(e),!n))throw new Error(`Cannot create controller for widget: ${e}`);return n.subscribe(t,i)}callWidgetFunction(e,t,...i){return r(this,void 0,void 0,(function*(){let n=this.getWidgetController(e);if(!n&&(n=this.createWidgetController(e),!n))throw new Error(`Cannot create controller for widget: ${e}`);return n.callFunction(t,...i)}))}updateWidgetConfig(e,t){return r(this,void 0,void 0,(function*(){let i=this.getWidgetController(e);if(!i&&(i=this.createWidgetController(e),!i))throw new Error(`Cannot create controller for widget: ${e}`);return i.updateConfig(t)}))}getWidgetState(e,t){return r(this,void 0,void 0,(function*(){let i=this.getWidgetController(e);if(!i&&(i=this.createWidgetController(e),!i))throw new Error(`Cannot create controller for widget: ${e}`);return i.getState(t)}))}setWidgetState(e,t,i){return r(this,void 0,void 0,(function*(){let n=this.getWidgetController(e);if(!n&&(n=this.createWidgetController(e),!n))throw new Error(`Cannot create controller for widget: ${e}`);return n.setState(t,i)}))}emitToWidget(e,t,i,n){let o=this.getWidgetController(e);o||(o=this.createWidgetController(e),o)?o.emit(t,i,n):l.warn(`Cannot create controller for widget: ${e}`)}canEditComposition(e){return r(this,void 0,void 0,(function*(){return this.authDetector.canEditComposition(e)}))}getAuthenticationStatus(){return this.authenticationStatus}refreshAuthentication(){return r(this,void 0,void 0,(function*(){return yield this.checkAuthentication(),this.authenticationStatus}))}openEditor(e){return r(this,void 0,void 0,(function*(){if(!(yield this.canEditComposition(e)))throw new Error(`User cannot edit composition: ${e}`);yield this.editorOverlay.openEditor(e)}))}isEditorOpen(e){return this.editorOverlay.isEditorOpen(e)}closeEditor(e){return r(this,void 0,void 0,(function*(){yield this.editorOverlay.closeEditor(e)}))}setEditingEnabled(e){this.config.enableEditing=e,l.info("Editing mode changed",{enabled:e})}setContent(e,t){return r(this,arguments,void 0,(function*(e,t,i={}){try{const{getWidgetManager:n}=yield Promise.resolve().then((function(){return Lt})),o=n();return yield o.setContent(e,t,i)}catch(e){return l.error("[EmbedSDK] Failed to set content:",e),{success:!1,error:e instanceof Error?e.message:"Unknown error"}}}))}getContentSchema(e){return r(this,void 0,void 0,(function*(){try{const t=this.getInstancesByComposition(e)[0];if(!t)throw new Error("No widget instance found for composition");const{getWidgetManager:i}=yield Promise.resolve().then((function(){return Lt})),n=i();return yield n.getContentSchema(t.config.compositionId)}catch(e){throw l.error("[EmbedSDK] Failed to get content schema:",e),e}}))}getDesignSchema(e){return r(this,void 0,void 0,(function*(){try{const t=this.getInstancesByComposition(e)[0];if(!t)throw new Error("No widget instance found for composition");const{getWidgetManager:i}=yield Promise.resolve().then((function(){return Lt})),n=i();return yield n.getDesignSchema(t.config.compositionId)}catch(e){throw l.error("[EmbedSDK] Failed to get design schema:",e),e}}))}validateContent(e,t){return r(this,void 0,void 0,(function*(){try{const{getWidgetManager:i}=yield Promise.resolve().then((function(){return Lt})),n=i();return yield n.validateContent(e,t)}catch(e){throw l.error("[EmbedSDK] Failed to validate content:",e),e}}))}getContent(e){try{return xt().getContent(e)}catch(e){return l.error("[EmbedSDK] Failed to get content:",e),null}}onContentUpdate(e,t){return this.subscribeToWidget(e,"content_updated",t)}scan(){return r(this,void 0,void 0,(function*(){if(!this.isInitialized)throw new Error("SDK not initialized. Call init() first.");try{const e=document.querySelectorAll("[data-widgetic]"),t=Array.from(e).map((e=>{const t=e.getAttribute("data-widgetic"),i=e.getAttribute("data-id");return t&&i?{id:t,dataId:i,element:e}:null})).filter(Boolean);return yield this.loadWidgets(t),{success:!0,widgets:t,errors:[]}}catch(e){return{success:!1,widgets:[],errors:[e instanceof Error?e.message:"Unknown error"]}}}))}loadWidgets(e){return r(this,void 0,void 0,(function*(){for(const t of e)try{yield this.loadWidget(t)}catch(e){}}))}loadWidget(e){return r(this,void 0,void 0,(function*(){yield new Promise((e=>setTimeout(e,100*Math.random())));const t=this.determineRenderMode();"iframe"===t?this.renderIframe(e):"custom-element"===t&&this.renderCustomElement(e)}))}determineRenderMode(){return"iframe"===this.config.renderMode?"iframe":"custom-element"===this.config.renderMode||"undefined"!=typeof customElements?"custom-element":"iframe"}renderIframe(e){const t=document.createElement("iframe");t.src=`https://widgetic.com/widget/${e.dataId}`,t.style.width=e.element.style.width||"400px",t.style.height=e.element.style.height||"300px",t.style.border="none",e.element.appendChild(t)}renderCustomElement(e){if("undefined"!=typeof customElements){customElements.get("widgetic-widget")||customElements.define("widgetic-widget",class extends HTMLElement{connectedCallback(){this.innerHTML=`<div>Widgetic Widget: ${this.getAttribute("data-widget-id")}</div>`}});const t=document.createElement("widgetic-widget");t.setAttribute("data-widget-id",e.dataId),e.element.appendChild(t)}}getConfig(){return Object.assign({},this.config)}showOverlay(e){this.overlayManager?this.overlayManager.showOverlay(e):l.warn("Overlay manager not initialized")}hideOverlay(){this.overlayManager?this.overlayManager.hideOverlay():l.warn("Overlay manager not initialized")}triggerOverlay(e,t={}){this.overlayManager?this.overlayManager.triggerOverlay(e,t):l.warn("Overlay manager not initialized")}isOverlayActive(){var e;return(null===(e=this.overlayManager)||void 0===e?void 0:e.isOverlayActive())||!1}destroy(){document.querySelectorAll("iframe").forEach((e=>e.remove()));document.querySelectorAll("widgetic-widget").forEach((e=>e.remove())),this.overlayManager&&(this.overlayManager.destroy(),this.overlayManager=null),this.isInitialized=!1}}let zt=null;function Pt(e){return zt||(zt=new Ut(e)),zt}"undefined"!=typeof document&&(rt(),"undefined"!=typeof MutationObserver&&new MutationObserver((()=>{rt()})).observe(document.documentElement,{childList:!0,subtree:!0}),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",(()=>{b.enabled&&l.info("DOM ready, auto-initializing SDK"),Pt().init().catch((e=>{l.error("Auto-initialization failed",{error:e})}))})):(b.enabled&&l.info("DOM already ready, auto-initializing SDK"),setTimeout((()=>{Pt().init().catch((e=>{l.error("Auto-initialization failed",{error:e})}))}),0)));var _t=Object.freeze({__proto__:null,EmbedSDK:Ut,getSDK:Pt});class jt{constructor(){this.debugMode=!1,this.trackedElements=new WeakSet}static getInstance(){return jt.instance||(jt.instance=new jt),jt.instance}enableDebugMode(){this.debugMode=!0,this.addDebugStyles(),l.info("CSS debugging mode enabled")}disableDebugMode(){this.debugMode=!1,this.removeDebugStyles(),l.info("CSS debugging mode disabled")}analyzeWidget(e){const t=e.getAttribute("data-widgetic-instance")||"unknown",i=[],n=[];this.detectCSSConflicts(e,i),this.checkStyleIsolation(e,n);const o={widgetId:t,conflicts:i,isolationScore:this.calculateIsolationScore(e,i),recommendations:n};return this.debugMode&&this.displayDebugReport(o),o}detectCSSConflicts(e,t){const i=window.getComputedStyle(e);["font-family","font-size","color","background-color","margin","padding","border","box-sizing"].forEach((n=>{const o=i.getPropertyValue(n);i.getPropertyPriority(n),this.isExternalStyle(e,n,o)&&t.push({property:n,widgetValue:this.getWidgetStyleValue(e,n),externalValue:o,specificity:this.calculateSpecificity(e,n),source:this.getStyleSource(e,n)})}))}checkStyleIsolation(e,t){e.getAttribute("data-widgetic-instance")||t.push("Add data-widgetic-instance attribute for proper namespace isolation");const i=window.getComputedStyle(e);Array.from(i).some((e=>e.startsWith("--widgetic-")))||t.push("Use CSS custom properties (--widgetic-*) for better theme isolation");const n=i.getPropertyValue("contain");n.includes("layout")&&n.includes("style")||t.push("Apply CSS containment (contain: layout style paint) for better isolation");"auto"===i.getPropertyValue("z-index")&&this.hasStackingContext(e)&&t.push("Consider explicit z-index management to prevent stacking conflicts")}calculateIsolationScore(e,t){let i=100;i-=10*t.length;const n=window.getComputedStyle(e),o=n.getPropertyValue("contain");o.includes("layout")||(i-=15),o.includes("style")||(i-=15),o.includes("paint")||(i-=10);"isolate"!==n.getPropertyValue("isolation")&&(i-=10);e.getAttribute("data-widgetic-instance")||(i-=15);return"border-box"!==n.getPropertyValue("box-sizing")&&(i-=5),Math.max(0,i)}isExternalStyle(e,t,i){const n=document.createElement(e.tagName.toLowerCase());n.style.cssText=e.getAttribute("style")||"",document.body.appendChild(n);const o=window.getComputedStyle(n).getPropertyValue(t);return document.body.removeChild(n),i!==o&&!this.isWidgetStyle(e,t)}isWidgetStyle(e,t){const i=e.getAttribute("data-widgetic-instance");if(!i)return!1;return this.getMatchingCSSRules(e).some((e=>{var n;return(null===(n=e.selectorText)||void 0===n?void 0:n.includes(`[data-widgetic-instance="${i}"]`))&&e.style.getPropertyValue(t)}))}getWidgetStyleValue(e,t){const i=e.getAttribute("data-widgetic-instance");if(!i)return"";const n=this.getMatchingCSSRules(e).find((e=>{var t;return null===(t=e.selectorText)||void 0===t?void 0:t.includes(`[data-widgetic-instance="${i}"]`)}));return(null==n?void 0:n.style.getPropertyValue(t))||""}calculateSpecificity(e,t){const i=this.getMatchingCSSRules(e).find((e=>e.style.getPropertyValue(t)));if(!i)return 0;const n=i.selectorText||"";let o=0;return o+=100*(n.match(/#/g)||[]).length,o+=10*(n.match(/[\.\[]/g)||[]).length,o+=(n.match(/[a-zA-Z]/g)||[]).length,o}getStyleSource(e,t){const i=this.getMatchingCSSRules(e).find((e=>e.style.getPropertyValue(t)));if(!i)return"unknown";if(i.parentStyleSheet){const e=i.parentStyleSheet;if(e.href)return e.href;if(e.ownerNode)return"inline styles"}return"unknown"}getMatchingCSSRules(e){const t=[];try{for(let i=0;i<document.styleSheets.length;i++){const n=document.styleSheets[i];try{const i=n.cssRules||n.rules;for(let n=0;n<i.length;n++){const o=i[n];o.selectorText&&e.matches(o.selectorText)&&t.push(o)}}catch(e){continue}}}catch(e){l.warn("Failed to analyze CSS rules",{error:e})}return t}hasStackingContext(e){const t=window.getComputedStyle(e),i=t.getPropertyValue("position"),n=t.getPropertyValue("z-index"),o=t.getPropertyValue("transform"),s=t.getPropertyValue("opacity");return"static"!==i&&"auto"!==n||"none"!==o||parseFloat(s)<1}addDebugStyles(){const e="widgetic-css-debug-styles";if(document.getElementById(e))return;const t=document.createElement("style");t.id=e,t.textContent='\n /* CSS Debug Mode Styles */\n widgetic-widget[data-widgetic-instance] {\n outline: 2px dashed #007bff !important;\n outline-offset: 2px !important;\n position: relative !important;\n }\n\n widgetic-widget[data-widgetic-instance]::before {\n content: "Widget: " attr(data-widgetic-instance) !important;\n position: absolute !important;\n top: -20px !important;\n left: 0 !important;\n background: #007bff !important;\n color: white !important;\n padding: 2px 6px !important;\n font-size: 10px !important;\n font-family: monospace !important;\n z-index: 10000 !important;\n pointer-events: none !important;\n }\n\n widgetic-widget[data-error="true"] {\n outline-color: #dc3545 !important;\n }\n\n widgetic-widget[data-loading="true"] {\n outline-color: #ffc107 !important;\n }\n\n widgetic-widget[data-ready="true"] {\n outline-color: #28a745 !important;\n }\n ',document.head.appendChild(t)}removeDebugStyles(){const e=document.getElementById("widgetic-css-debug-styles");e&&e.remove()}displayDebugReport(e){}monitorWidget(e){if(this.trackedElements.has(e))return;this.trackedElements.add(e);new MutationObserver((e=>{e.forEach((e=>{"attributes"!==e.type||"style"!==e.attributeName&&"class"!==e.attributeName||this.debugMode}))})).observe(e,{attributes:!0,attributeOldValue:!0,attributeFilter:["style","class"]})}}jt.instance=null;const Ft=jt.getInstance();function Ht(){Ft.enableDebugMode()}function Bt(){Ft.disableDebugMode()}function $t(e){return Ft.analyzeWidget(e)}function Nt(e){Ft.monitorWidget(e)}const Kt={WidgeticWidget:t,registerWidgeticWidget:i,getSDK:Pt,setApiKey:I,setTokenProvider:T,StaticApiKeyProvider:Z,EndpointTokenProvider:ee,FunctionTokenProvider:te,getConfiguration:S},Vt={WidgetRenderer:n,getWidgetRenderer:e,CustomElementRenderer:o,IframeRenderer:s,AuthManager:oe,detectBrowserCapabilities:M,determineBestRenderMode:D,parseWidgetConfig:E,generateInstanceId:A,isValidWidgetElement:C},qt={BatchApiClient:dt,getBatchClient:lt,ModuleLoader:pt,getModuleLoader:vt,WidgeticMessenger:O,getMessenger:W,config:f,getApiUrl:h,getCdnUrl:v,getTokenProvider:k,getAuthToken:u,DefaultTokenProvider:ie,CSSDebugger:jt,cssDebugger:Ft,enableCSSDebug:Ht,disableCSSDebug:Bt,log:l};export{oe as A,dt as B,jt as C,ie as D,ue as E,te as F,_t as G,Kt as H,qt as L,de as M,Z as S,Ot as W,Se as a,ke as b,It as c,vt as d,se as e,re as f,lt as g,ae as h,Me as i,xt as j,Pt as k,Ut as l,Ft as m,ee as n,ne as o,ht as p,pt as q,Ie as r,ft as s,Ht as t,Bt as u,$t as v,Nt as w,Vt as x,gt as y,yt as z};
|
|
1
|
+
import{g as e,W as t,r as i,a as n,C as o,I as s}from"./renderers.js";import{_ as r,a}from"./vendor.js";import{g as d,S as c,l,b as h,A as u,d as g,e as p,V as m,f as v,a as f,P as y,h as w,D as b,s as I,i as T,j as S,k}from"./core.js";import{p as E,a as M,i as C,g as D,h as A,b as W,c as O,s as x,m as R,o as L,d as U,e as P,f as _,j as z}from"./scanner.js";import{g as j,a as $}from"./media.js";import{g as F,S as H}from"./security.js";import{g as B,i as N,a as K,b as V,c as q,d as Y}from"./performance.js";import{getMessenger as Q,WidgeticMessenger as G}from"./messaging.js";import{C as J,T as X,a as Z,W as ee,c as te,t as ie,g as ne,b as oe,d as se}from"./advanced.js";import{D as re,g as ae,a as de,b as ce}from"./display.js";class le{constructor(e){this.apiKey=e}getToken(){return r(this,void 0,void 0,(function*(){return this.apiKey}))}isTokenValid(){return r(this,void 0,void 0,(function*(){return!!this.apiKey}))}}class he{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 r(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 r(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 r(this,void 0,void 0,(function*(){return!!this.cachedToken&&(!this.tokenExpiry||Date.now()<this.tokenExpiry)}))}}class ue{constructor(e,t){this.tokenFunction=e,this.validationFunction=t}getToken(){return r(this,void 0,void 0,(function*(){return yield this.tokenFunction()}))}isTokenValid(){return r(this,void 0,void 0,(function*(){return!this.validationFunction||(yield this.validationFunction())}))}}class ge{constructor(e){this.apiKey=e}getToken(){return r(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 r(this,void 0,void 0,(function*(){return!!this.apiKey}))}}class pe extends Error{constructor(e,t,i){super(e),this.code=t,this.statusCode=i,this.name="AuthError"}}class me{constructor(e={}){var t,i;this.currentToken=null,this.apiKey=null,this.refreshTimer=null,this.config=Object.assign({apiUrl:e.apiUrl||d(),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===(i={NODE_ENV:"production"})||void 0===i?void 0:i.API_KEY))||null}createTokensApiForApiKey(e){const t=new J({basePath:this.config.apiUrl,apiKey:()=>r(this,void 0,void 0,(function*(){return e})),headers:{"X-SDK-Version":`embed-sdk/${c}`}});return new X(t)}createTokensApiForAccessToken(e){const t=new J({basePath:this.config.apiUrl,accessToken:()=>r(this,void 0,void 0,(function*(){return e})),headers:{"X-SDK-Version":`embed-sdk/${c}`}});return new X(t)}setApiKey(e){this.apiKey=e,this.currentToken={token:e,tokenType:"API-Key",expiresAt:null,scopes:[]},this.config.debug&&l.debug("AuthManager: API key set")}getValidToken(e){return r(this,void 0,void 0,(function*(){if(this.currentToken&&this.isTokenValid(this.currentToken)){if(me.validatedTokens.has(this.currentToken.token))return this.currentToken.token;if(yield this.validateToken())return this.currentToken.token}if(this.apiKey)return yield this.exchangeApiKeyForJWT(e),this.currentToken.token;throw new pe("No authentication method available","NO_AUTH_METHOD")}))}exchangeApiKeyForJWT(e){return r(this,void 0,void 0,(function*(){var t;if(!this.apiKey)throw new pe("No API key available for exchange","NO_API_KEY");const i={scopes:(null==e?void 0:e.scopes)||this.getDefaultScopes(),expiresIn:(null==e?void 0:e.expiresIn)||1800};try{const e=this.createTokensApiForApiKey(this.apiKey),n=yield e.exchangeToken({exchangeTokenRequest:i}),o=(null===(t=null==n?void 0:n.data)||void 0===t?void 0:t.token)||(null==n?void 0:n.token);if(!o)throw new pe("Token exchange response missing token","INVALID_RESPONSE");const s=(null==n?void 0:n.data)||n,r={token:o,tokenType:s.tokenType||"Bearer",expiresAt:s.expiresAt?s.expiresAt instanceof Date?s.expiresAt.toISOString():String(s.expiresAt):null,scopes:s.scopes||[]};return this.setToken(r),this.config.debug&&l.info("AuthManager: Token exchanged successfully",{scopes:r.scopes,expiresAt:r.expiresAt}),r}catch(e){const t=e instanceof pe?e:new pe(`Token exchange failed: ${e instanceof Error?e.message:String(e)}`,"TOKEN_EXCHANGE_ERROR");throw this.config.onAuthError&&this.config.onAuthError(t),t}}))}validateToken(){return r(this,void 0,void 0,(function*(){var e;if(!this.currentToken)return!1;if(me.validatedTokens.has(this.currentToken.token))return!0;try{const t=this.createTokensApiForAccessToken(this.currentToken.token),i=yield t.validateToken();return!0===(null==i?void 0:i.success)&&!0===(null===(e=i.data)||void 0===e?void 0:e.valid)||!0===(null==i?void 0:i.valid)?(me.validatedTokens.add(this.currentToken.token),!0):(this.clearToken(),!1)}catch(e){return this.config.debug&&l.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&&me.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(e){if(!e.expiresAt||!this.apiKey)return;const t=new Date(e.expiresAt).getTime()-Date.now()-3e5;t>0&&(this.refreshTimer=setTimeout((()=>r(this,void 0,void 0,(function*(){try{yield this.exchangeApiKeyForJWT({scopes:e.scopes}),this.config.debug&&l.info("AuthManager: Token refreshed automatically")}catch(e){this.config.debug&&l.error("AuthManager: Automatic token refresh failed",e),this.config.onTokenExpired&&this.config.onTokenExpired()}}))),t))}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&&l.debug("AuthManager: Disposed")}}me.validatedTokens=new Set;const ve=3e3,fe=864e5,ye=100,we=2147483647,be=["DOMAIN_NOT_ALLOWED","UNPUBLISHED","SUSPENDED","NOT_FOUND","RATE_LIMITED"],Ie={DOMAIN_NOT_ALLOWED:"domain_not_allowed",UNPUBLISHED:"unpublished",SUSPENDED:"suspended",NOT_FOUND:"not_found",RATE_LIMITED:"rate_limited"};function Te(e){return be.includes(e)?Ie[e]:null}const Se="https://cdn.widgetic.com",ke="DOMAIN_NOT_ALLOWED",Ee="This embed is not authorized to be shown on this website.";function Me(){if("undefined"==typeof document)return[];const e=[],t=document.querySelectorAll("script[src*='embed-sdk']");for(const i of Array.from(t)){const t=i.getAttribute("data-api-url");t&&t.trim()&&e.push(t.trim().replace(/\/+$/,""))}const i=window.WIDGETIC_EMBED_API;return i&&String(i).trim()&&e.push(String(i).trim().replace(/\/+$/,"")),e}function Ce(e){var t;if("undefined"==typeof window)return null;const i=window.__WIDGETIC_EMBED_LOOKUP__;return(null===(t=null==i?void 0:i[e])||void 0===t?void 0:t.embedUrl)||null}function De(e,t){if(!e||"object"!=typeof e)return null;let i="string"==typeof e.embedUrl?e.embedUrl:"";if(!i&&"string"==typeof e.js_path&&e.js_path.trim()){const t=e.js_path.trim();i=/^https?:\/\//i.test(t)?t:`${Se}${t.startsWith("/")?"":"/"}${t}`}else!i&&"string"==typeof e.embed_url&&e.embed_url.trim()&&(i=e.embed_url.trim());if(!i)return null;const n=function(e){if(!e||"object"!=typeof e)return;const t=e;return"string"!=typeof t.moduleUrl||"number"!=typeof t.contractVersion?void 0:{moduleUrl:t.moduleUrl,contractVersion:t.contractVersion,moduleHash:"string"==typeof t.moduleHash?t.moduleHash:null}}(e.direct),o="string"==typeof e.compositionId?e.compositionId:void 0,s="string"==typeof e.widgetId?e.widgetId:"string"==typeof e.id?e.id:void 0,r="string"==typeof e.entryWriteToken?e.entryWriteToken:void 0;let a;if(e.entries&&"object"==typeof e.entries){const t=e.entries;"string"==typeof t.url&&(a=Object.assign({url:t.url},"string"==typeof t.writeToken?{writeToken:t.writeToken}:r?{writeToken:r}:{}))}else r&&o&&t&&(a={url:`${t.replace(/\/+$/,"")}/embed/compositions/${o}/entries`,writeToken:r});return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({embedUrl:i,compositionId:o},s?{widgetId:s}:{}),{design:e.design&&"object"==typeof e.design?e.design:{},content:e.content&&"object"==typeof e.content?e.content:{},contentItems:Array.isArray(e.contentItems)?e.contentItems:[]}),n?{direct:n}:{}),r?{entryWriteToken:r}:{}),a?{entries:a}:{})}function Ae(e){return r(this,void 0,void 0,(function*(){let t=null;try{t=yield e.json()}catch(e){t=null}const i=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return null;const t=e.code;return"string"==typeof t&&t.length>0&&t.length<=64?t:null}(t),n=(i&&Te(i)?i:null)||(429===(o=e.status)?"RATE_LIMITED":404===o?"NOT_FOUND":null);var o;if(!n)return null;const s=Te(n);return s?{gatewayCode:n,stateCode:s}:null}))}function We(e){return r(this,void 0,void 0,(function*(){let t="";try{t=new URL(e).origin}catch(e){t=""}try{const i=yield fetch(e,{method:"GET",mode:"cors"});if(!i.ok){const e=yield function(e){return r(this,void 0,void 0,(function*(){if(403!==e.status)return null;try{const t=yield e.json();if(!t||"object"!=typeof t||t.code!==ke)return null;const i=t.details&&"object"==typeof t.details?t.details:null,n="string"==typeof(null==i?void 0:i.reason)?i.reason.slice(0,80):void 0;return{code:ke,reason:n}}catch(e){return null}}))}(i);if(e)return{kind:"refused",refusal:e};const t=yield Ae(i);return t?{kind:"failed",failure:t}:{kind:"unavailable"}}const n=De(yield i.json(),t);return n?{kind:"payload",payload:n,gatewayOrigin:t}:{kind:"unavailable"}}catch(e){return{kind:"unavailable"}}}))}function Oe(e){return"refused"===e.kind?{status:"refused",refusal:e.refusal}:"failed"===e.kind?{status:"failed",failure:e.failure}:{status:"found",payload:e.payload,gatewayOrigin:e.gatewayOrigin||void 0}}function xe(e){const t=`/embed/compositions/${e}`,i=[];for(const e of Me())i.push(`${e}${t}`);const n=h().replace(/\/+$/,"");i.push(`${n}${t}`);const o=String(u.PROD_API_URL).replace(/\/+$/,"");return o&&i.push(`${o}${t}`),[...new Set(i)]}function Re(e){return r(this,void 0,void 0,(function*(){const t=Me();for(const i of t){const t=yield We(`${i}/embed/compositions/${e}`);if("unavailable"!==t.kind)return Oe(t)}const i=yield function(e){const t=Ce(e);return t?Promise.resolve(t):"undefined"==typeof document?Promise.resolve(null):new Promise((t=>{const i=document.createElement("script");i.src=`${Se}/embed/compositions/${e}.js`,i.async=!0,i.onload=()=>t(Ce(e)),i.onerror=()=>t(null),document.head.appendChild(i)}))}(e);if(i){for(const t of xe(e)){const e=yield We(t);if("refused"===e.kind)return Oe(e);if("failed"!==e.kind&&"payload"===e.kind){const t=e.payload;return{status:"found",payload:Object.assign(Object.assign({},t),{embedUrl:t.embedUrl||i}),gatewayOrigin:e.gatewayOrigin||void 0}}}return{status:"found",payload:{embedUrl:i,compositionId:e}}}let n=null;for(const t of xe(e)){const e=yield We(t);if("refused"===e.kind)return Oe(e);if("failed"!==e.kind){if("payload"===e.kind)return Oe(e)}else n=e.failure}return n?{status:"failed",failure:n}:{status:"not-found"}}))}function Le(e){return r(this,void 0,void 0,(function*(){const t=Me();for(const i of t){const t=yield We(`${i}/widgets/${encodeURIComponent(e)}`);if("unavailable"!==t.kind)return Oe(t)}const i=Ce(e);let n=null;for(const t of function(e){const t=`/widgets/${encodeURIComponent(e)}`,i=[];for(const e of Me())i.push(`${e}${t}`);const n=h().replace(/\/+$/,"");i.push(`${n}${t}`);const o=String(u.PROD_API_URL).replace(/\/+$/,"");return o&&i.push(`${o}${t}`),[...new Set(i)]}(e)){const e=yield We(t);if("refused"===e.kind)return Oe(e);if("failed"!==e.kind){if("payload"===e.kind)return Oe(e)}else n=e.failure}return i?{status:"found",payload:{embedUrl:i,widgetId:e}}:n?{status:"failed",failure:n}:{status:"not-found"}}))}const Ue=new Set;function Pe(e,t){var i;if(Ue.has(e))return;Ue.add(e);"undefined"!=typeof window&&(null===(i=window.location)||void 0===i?void 0:i.hostname)&&window.location.hostname,t.reason&&t.reason}function _e(e,t,i,n,o){const s=document.createElement("iframe");return s.src=e,s.width=t,s.height=i,s.setAttribute("frameborder","0"),s.setAttribute("allowfullscreen",""),s.style.border="0",s.style.display="block",s.style.maxWidth="100%",n&&s.setAttribute("data-composition-id",n),function(e,t){if(!t)return;const i=t.design&&Object.keys(t.design).length>0?t.design:null,n=t.content&&Object.keys(t.content).length>0?t.content:null,o=t.contentItems&&t.contentItems.length>0?t.contentItems:null;if(!i&&!n&&!o)return;const s=()=>{const t=e.contentWindow;if(!t)return;const s={type:"widgetic:update"};i&&(s.design=i),n&&(s.content=n),o&&(s.contentItems=o),t.postMessage(s,"*")};window.addEventListener("message",(t=>{t.source===e.contentWindow&&"widgetic:ready"===(t.data&&t.data.type||"")&&s()})),e.addEventListener("load",(()=>{s(),window.setTimeout(s,80),window.setTimeout(s,400)}))}(s,o),s}class ze{constructor(){this.deviceInfo=null}static getInstance(){return ze.instance||(ze.instance=new ze),ze.instance}getDeviceInfo(){return this.deviceInfo||(this.deviceInfo=this.detectDevice()),this.deviceInfo}getDeviceType(){return this.getDeviceInfo().type}isMobile(){return this.getDeviceInfo().isMobile}isTablet(){return this.getDeviceInfo().isTablet}isDesktop(){return this.getDeviceInfo().isDesktop}hasTouch(){return this.getDeviceInfo().hasTouch}detectDevice(){const e=navigator.userAgent||"",t=navigator.platform||"",i=navigator.vendor||"",n=navigator.maxTouchPoints||0,o=navigator.hardwareConcurrency||1,s=navigator.deviceMemory,r=this.detectTouchCapability(),a=this.determineDeviceType(e,t,r,n),d={type:a,isMobile:"mobile"===a,isTablet:"tablet"===a,isDesktop:"desktop"===a||"tablet"===a,hasTouch:r,userAgent:e,platform:t,vendor:i,maxTouchPoints:n,hardwareConcurrency:o,deviceMemory:s};return l.debug("Device detected",d),d}detectTouchCapability(){if("ontouchstart"in window)return!0;if(navigator.maxTouchPoints&&navigator.maxTouchPoints>0)return!0;if("onpointerdown"in window)return!0;try{if(void 0!==window.DocumentTouch&&document instanceof window.DocumentTouch)return!0}catch(e){}return!1}determineDeviceType(e,t,i,n){const o=e.toLowerCase(),s=t.toLowerCase();return[/android.*mobile/,/iphone/,/ipod/,/blackberry/,/bb10/,/windows phone/,/iemobile/,/mobile/,/phone/].some((e=>e.test(o)))?"mobile":[/ipad/,/android(?!.*mobile)/,/kindle/,/silk/,/playbook/,/tablet/].some((e=>e.test(o)))?"tablet":[/windows nt/,/macintosh/,/mac os x/,/linux/,/x11/,/cros/].some((e=>e.test(o)))?"desktop":/^(iphone|ipod|android)/.test(s)?"mobile":/^(ipad)/.test(s)?"tablet":/^(win|mac|linux)/.test(s)?"desktop":i?n>=5?"tablet":n<=2?"mobile":"tablet":"desktop"}checkDeviceRestrictions(e=!0,t=!0){const i=this.getDeviceInfo();return i.isMobile&&!e?(l.debug("Widget restricted on mobile device"),!1):!(i.isDesktop&&!t)||(l.debug("Widget restricted on desktop/tablet device"),!1)}getDeviceCapabilities(){const e={userAgent:navigator.userAgent,platform:navigator.platform,vendor:navigator.vendor,language:navigator.language,languages:navigator.languages,cookieEnabled:navigator.cookieEnabled,onLine:navigator.onLine,maxTouchPoints:navigator.maxTouchPoints,hardwareConcurrency:navigator.hardwareConcurrency,deviceMemory:navigator.deviceMemory,connection:navigator.connection,standalone:navigator.standalone,webdriver:navigator.webdriver};return e.screen={width:screen.width,height:screen.height,availWidth:screen.availWidth,availHeight:screen.availHeight,colorDepth:screen.colorDepth,pixelDepth:screen.pixelDepth,orientation:screen.orientation},e.touch={hasTouch:this.hasTouch(),hasTouchEvents:"ontouchstart"in window,hasPointerEvents:"onpointerdown"in window,hasGestureEvents:"ongesturestart"in window},window.matchMedia&&(e.mediaQueries={hover:window.matchMedia("(hover: hover)").matches,pointer:window.matchMedia("(pointer: fine)").matches?"fine":"coarse",anyHover:window.matchMedia("(any-hover: hover)").matches,anyPointer:window.matchMedia("(any-pointer: fine)").matches?"fine":"coarse"}),e}reset(){this.deviceInfo=null}}function je(){return ze.getInstance()}function $e(e=!0,t=!0){return je().checkDeviceRestrictions(e,t)}const Fe="data-widgetic-overlay",He="data-device-restricted",Be=new WeakMap,Ne=new WeakMap,Ke=new Map;function Ve(e,t,i){if(Be.has(e))return;const n=e.getAttribute("composition-id")||"widget",o=function(e,t){const i=Ne.get(e);if(i)return i;const n=(Ke.get(t)||0)+1;Ke.set(t,n);const o=1===n?t:`${t}-${n}`;return Ne.set(e,o),o}(e,n);let s=()=>{};if(i){const e=e=>{var t;(null===(t=e.detail)||void 0===t?void 0:t.widgetId)===o&&(s(),i())};document.addEventListener("widgetic:overlay-shown",e),s=()=>document.removeEventListener("widgetic:overlay-shown",e)}Promise.resolve().then((function(){return Vt})).then((({TriggerManager:i})=>{if(Be.has(e))return void s();const n=new i({widgetId:o,element:e,config:t,displayWhenShown:"block"});Be.set(e,n),e.hasAttribute(Fe)&&e.setAttribute(Fe,"armed"),l.debug("[published-host-display] Trigger manager armed",{widgetId:o,mode:t.mode,eventTrigger:t.eventTrigger})})).catch((e=>{s(),l.error("[published-host-display] Could not load the overlay triggers; the embed stays hidden",{widgetId:o,error:e})}))}const qe=/^[A-Za-z0-9_.-]{1,64}$/;function Ye(e){return(new TextEncoder).encode(JSON.stringify(e)).length}function Qe(e){if(!e||!e.trim())return null;try{const t=JSON.parse(e);return!t||"object"!=typeof t||Array.isArray(t)?null:t}catch(e){return null}}function Ge(e){const t=Qe(e);if(!t)return null;const i=Object.keys(t);if(i.length>50)return null;if(Ye(t)>8192)return null;const n={};for(const e of i){if(!qe.test(e))return null;const i=t[e];if("boolean"==typeof i)n[e]=i;else if("number"==typeof i){if(!Number.isFinite(i))return null;n[e]=i}else{if("string"!=typeof i)return null;if(i.length>2e3)return null;n[e]=i}}return n}function Je(e){if(!(null==e?void 0:e.trim()))return null;const t=e.trim();if(t.length>2048)return null;try{return"https:"!==new URL(t).protocol?null:t}catch(e){return null}}const Xe=new WeakMap;function Ze(e){var t;const i=e.getAttribute("context"),n=function(e){const t=Qe(e);if((null==e?void 0:e.trim())&&!t)return{value:null,invalid:!0};if(!t)return{value:null,invalid:!1};const i=Object.keys(t);if(i.length>20)return{value:null,invalid:!0};if(Ye(t)>2048)return{value:null,invalid:!0};const n={};for(const e of i){if(!qe.test(e))return{value:null,invalid:!0};const i=t[e];if("number"==typeof i){if(!Number.isFinite(i))return{value:null,invalid:!0};n[e]=i}else{if("string"!=typeof i)return{value:null,invalid:!0};if(i.length>500)return{value:null,invalid:!0};n[e]=i}}return{value:n,invalid:!1}}(i);return n.invalid&&function(e,t){const i=null!=t?t:"";let n=Xe.get(e);n||(n=new Set,Xe.set(e,n)),n.has(i)||n.add(i)}(e,i),{context:n.invalid?null:n.value,contextInvalid:n.invalid,values:Ge(e.getAttribute("values")),mediaResolver:Je(null!==(t=e.getAttribute("media-resolver"))&&void 0!==t?t:e.getAttribute("mediaresolver"))}}const et="data-widgetic-context-invalid";const tt=new WeakMap;function it(e,t){const i=tt.get(e);if(!i)return!1;t.design&&(i.payload=Object.assign(Object.assign({},i.payload),{design:Object.assign(Object.assign({},i.payload.design||{}),t.design)})),t.content&&(i.payload=Object.assign(Object.assign({},i.payload),{content:Object.assign(Object.assign({},i.payload.content||{}),t.content)})),Array.isArray(t.contentItems)&&(i.payload=Object.assign(Object.assign({},i.payload),{contentItems:t.contentItems}));try{return i.instance.update(ot(e,i.payload)),!0}catch(e){return!1}}function nt(e){const t=tt.get(e);if(t){tt.delete(e);try{t.instance.destroy()}catch(e){}t.stop()}for(const t of Array.from(e.querySelectorAll("[data-widgetic-direct]")))t.remove()}function ot(e,t){const i=Ze(e);i.contextInvalid?e.setAttribute(et,""):e.removeAttribute(et);const n=M(e,t),o=Object.assign(Object.assign(Object.assign({},t.content||{}),n.content),i.values||{}),s=Object.assign(Object.assign({},t.design||{}),n.design),r=n.contentItems&&n.contentItems.length>0?n.contentItems:t.contentItems||[];return Object.assign({design:s,content:o,contentItems:r,context:i.context,mediaResolver:i.mediaResolver},t.entries?{entries:t.entries}:{})}function st(e,t,i,n){return r(this,void 0,void 0,(function*(){C(e);const o=D(e)||"",s=t.direct;if(!s||2!==s.contractVersion||!s.moduleUrl)return!1;let r;try{r=yield(a=s.moduleUrl,import(a))}catch(e){return!1}var a;if(!e.isConnected||(D(e)||"")!==o)return!1;if(2!==r.contractVersion)return!1;nt(e);const d=document.createElement("div");d.setAttribute("data-widgetic-direct","1"),d.setAttribute("width",i||e.getAttribute("width")||"400");const c=e.getAttribute("height");c&&d.setAttribute("height",c);const l=d.attachShadow({mode:"open"}),h=document.createElement("style");h.textContent=r.getStyles();const u=document.createElement("div");u.className="widgetic-direct-target",l.append(h,u);const g={compositionId:o,payload:t,instance:null,stop:()=>{}},p=r.mount(u,ot(e,g.payload));g.instance=p;const m=function(e,t,i){const n="undefined"!=typeof MutationObserver?MutationObserver:null;if(!n)return()=>{};let o;try{o=new n((n=>{A(n)&&i.update(ot(e,t()))}))}catch(e){return()=>{}}return o.observe(e,{attributes:!0,childList:!0,subtree:!0,characterData:!0}),()=>o.disconnect()}(e,(()=>g.payload),p),v=["play","pause","ended","seeking","seeked","timeupdate","progress","volumechange","trackchange","playlistchange"],f=["position","navigate","complete","reset","metadata"],y=[];for(const t of v){const i=`widgetic:media:${t}`,n=e=>{const i=e,n=i.detail&&"object"==typeof i.detail?i.detail:{};try{$().handleMediaEvent({type:t,compositionId:o,config:{persistState:!0,autoResume:!0},data:n})}catch(e){}};u.addEventListener(i,n),e.addEventListener(i,n),y.push((()=>{u.removeEventListener(i,n),e.removeEventListener(i,n)}))}for(const t of f){const i=`widgetic:content:${t}`,n=e=>{const i=e,n=i.detail&&"object"==typeof i.detail?i.detail:{};try{j().handleContentPositionEvent({type:t,compositionId:o,config:{contentType:"custom",persistState:!0,autoResume:!0},data:n})}catch(e){}};u.addEventListener(i,n),e.addEventListener(i,n),y.push((()=>{u.removeEventListener(i,n),e.removeEventListener(i,n)}))}g.stop=()=>{m();for(const e of y)e()},tt.set(e,g),e.appendChild(d),n(e);try{j().resumeWidgetPosition(o)}catch(e){}try{$().resumeWidget(o)}catch(e){}return e.dispatchEvent(new CustomEvent("widgetic:ready",{bubbles:!0,composed:!0,detail:{compositionId:o}})),!0}))}const rt="data-widgetic-refused",at="data-widgetic-context-invalid",dt="data-widgetic-composition-tracked";function ct(e){e.removeAttribute("data-widgetic-mounting"),e.removeAttribute("data-widgetic-mounted"),e.removeAttribute(He),e.removeAttribute(rt),e.removeAttribute(at)}const lt=["context","values","media-resolver"],ht=new Set(["widgetic:ready","widgetic:error","widgetic:submitted","widgetic:resize","widgetic:data","widgetic:interaction","widgetic:form-submit"]),ut=new WeakMap;class gt{constructor(e,t,i,n){this.host=e,this.iframe=t,this.gatewayOrigin=i,this.compositionId=n,this.readyDispatched=!1,this.attributeFlushScheduled=!1,this.attributeObserver=null,C(this.host),this.onWindowMessage=e=>this.handleWrapperMessage(e),window.addEventListener("message",this.onWindowMessage),this.iframe.addEventListener("load",(()=>this.postHostSnapshot())),this.observeHostAttributes()}observeHostAttributes(){const e="undefined"!=typeof MutationObserver?MutationObserver:null;if(!e)return;let t;try{t=new e((e=>{e.some((e=>"attributes"===e.type&&e.attributeName&<.includes(e.attributeName)))&&this.scheduleHostSnapshot()}))}catch(e){return}t.observe(this.host,{attributes:!0,attributeFilter:[...lt]}),this.attributeObserver=t}scheduleHostSnapshot(){this.attributeFlushScheduled||(this.attributeFlushScheduled=!0,queueMicrotask((()=>{this.attributeFlushScheduled=!1,this.postHostSnapshot()})))}postHostSnapshot(){try{const e=Ze(this.host);e.contextInvalid?this.host.setAttribute(at,"1"):this.host.removeAttribute(at);const t=this.iframe.contentWindow;if(!t)return;const i=function(e,t){return{type:"widgetic:host",version:1,compositionId:e,context:t.context,values:t.values,mediaResolver:t.mediaResolver}}(this.compositionId,e);t.postMessage(i,this.gatewayOrigin)}catch(e){}}sendWidgetUpdate(e){try{const t=this.iframe.contentWindow;if(!t)return;t.postMessage(Object.assign(Object.assign(Object.assign({type:"widgetic:update",compositionId:this.compositionId},e.design?{design:e.design}:{}),e.content?{content:e.content}:{}),e.contentItems?{contentItems:e.contentItems}:{}),this.gatewayOrigin)}catch(e){}}handleWrapperMessage(e){var t,i;if(e.source!==this.iframe.contentWindow)return;if(e.origin!==this.gatewayOrigin)return;const n=e.data;if(!n||"object"!=typeof n||Array.isArray(n))return;const o=n.type;if("string"!=typeof o)return;const s=n.compositionId;if("string"==typeof s&&s!==this.compositionId)return;let r=null!==(i=null!==(t=n.detail)&&void 0!==t?t:n.payload)&&void 0!==i?i:n.data;if(void 0===r){const e={};for(const t of Object.keys(n))"type"!==t&&"compositionId"!==t&&(e[t]=n[t]);Object.keys(e).length>0&&(r=e)}const a=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return{};try{const t=JSON.stringify(e);return(new TextEncoder).encode(t).length>8192?{}:e}catch(e){return{}}}(r),d=Object.assign({compositionId:this.compositionId},a);if(o.startsWith("widgetic:media:")){const e=o.replace("widgetic:media:","");try{$().handleMediaEvent({type:e,compositionId:this.compositionId,config:{persistState:!0,autoResume:!0},data:a})}catch(e){}this.dispatchHostEvent(o,d)}else if(o.startsWith("widgetic:content:")){const e=o.replace("widgetic:content:","");try{j().handleContentPositionEvent({type:e,compositionId:this.compositionId,config:{contentType:"custom",persistState:!0,autoResume:!0},data:a})}catch(e){}this.dispatchHostEvent(o,d)}else if(ht.has(o)){if("widgetic:ready"===o){try{j().resumeWidgetPosition(this.compositionId)}catch(e){}try{$().resumeWidget(this.compositionId)}catch(e){}if(this.readyDispatched)return;return this.readyDispatched=!0,this.postHostSnapshot(),void this.dispatchHostEvent("widgetic:ready",{compositionId:this.compositionId})}this.dispatchHostEvent(o,d)}}dispatchHostEvent(e,t){this.host.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:!0}))}destroy(){var e;window.removeEventListener("message",this.onWindowMessage),null===(e=this.attributeObserver)||void 0===e||e.disconnect(),this.attributeObserver=null}}function pt(e,t,i){e.dispatchEvent(new CustomEvent("widgetic:error",{detail:{compositionId:t,code:i},bubbles:!0,composed:!0}))}class mt{constructor(e,t){this._active=!0,this.id=`sub_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,this.compositionId=e,this.handler=t}isActive(){return this._active}unsubscribe(){this._active=!1}}class vt{constructor(e){this.pollTimer=null,this.lastPoll=0,this.interval=e.interval,this.endpoint=e.endpoint,this.subscriptions=e.subscriptions,this.realtimeManager=e.realtimeManager}start(){return r(this,void 0,void 0,(function*(){this.pollTimer||(l.info("[PollingFallback] Starting polling fallback",{interval:this.interval,subscriptions:this.subscriptions.size}),this.pollTimer=setInterval((()=>{this.pollForUpdates()}),this.interval),yield this.pollForUpdates())}))}stop(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null),l.info("[PollingFallback] Polling fallback stopped")}pollForUpdates(){return r(this,void 0,void 0,(function*(){if(0!==this.subscriptions.size)try{const e=yield fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":this.realtimeManager.getApiKey()},body:JSON.stringify({compositionIds:Array.from(this.subscriptions),since:this.lastPoll})});if(!e.ok)throw new Error(`Polling failed: ${e.status}`);const t=yield e.json();for(const e of t.updates||[])yield this.realtimeManager.handlePolledUpdate(e);this.lastPoll=Date.now()}catch(e){l.error("[PollingFallback] Polling error:",e)}}))}}class ft{constructor(e){this.socket=null,this.connectionState="disconnected",this.connectionId=null,this.subscriptions=new Map,this.allSubscriptions=new Map,this.reconnectAttempts=0,this.reconnectTimer=null,this.messageQueue=new Map,this.retryTimer=null,this.heartbeatTimer=null,this.lastHeartbeat=0,this.heartbeatTimeout=null,this.pollingFallback=null,this.connectionStartTime=0,this.messageStats={sent:0,received:0,errors:0};const t={enabled:!0,wsUrl:"wss://realtime.widgetic.com",authentication:{type:"apikey",credentials:""},features:{contentUpdates:!0,styleUpdates:!0,configUpdates:!1,dataUpdates:!0,publishUpdates:!0},security:{validateUpdates:!0,rateLimitPerMinute:30,allowedUpdateTypes:["content","style","data","published"]},reconnection:{enabled:!0,maxAttempts:5,baseDelay:1e3,maxDelay:3e4},fallback:{enabled:!0,pollInterval:5e3},heartbeat:{enabled:!0,interval:3e4,timeout:1e4}};this.config=Object.assign(Object.assign(Object.assign({},t),e),{authentication:Object.assign(Object.assign({},t.authentication),e.authentication),features:Object.assign(Object.assign({},t.features),e.features),security:Object.assign(Object.assign({},t.security),e.security),reconnection:Object.assign(Object.assign({},t.reconnection),e.reconnection),fallback:Object.assign(Object.assign({},t.fallback),e.fallback),heartbeat:Object.assign(Object.assign({},t.heartbeat),e.heartbeat)}),this.securityManager=F(),this.performanceMonitor=B(),this.setupEventListeners()}static getInstance(e){return ft.instance||(ft.instance=new ft(e||{})),ft.instance}initialize(){return r(this,void 0,void 0,(function*(){this.config.enabled?"connected"!==this.connectionState&&"connecting"!==this.connectionState&&(l.info("[RealtimeManager] Initializing real-time connection"),yield this.connect()):l.info("[RealtimeManager] Real-time updates disabled")}))}connect(){return r(this,void 0,void 0,(function*(){if("connected"!==this.connectionState&&"connecting"!==this.connectionState){this.connectionState="connecting",this.connectionStartTime=Date.now();try{const e=this.buildWebSocketUrl();l.info("[RealtimeManager] Connecting to WebSocket:",e),this.socket=new WebSocket(e),this.socket.onopen=this.handleConnect.bind(this),this.socket.onmessage=this.handleMessage.bind(this),this.socket.onclose=this.handleDisconnect.bind(this),this.socket.onerror=this.handleError.bind(this)}catch(e){throw this.connectionState="error",l.error("[RealtimeManager] Connection failed:",e),yield this.handleConnectionError(e),e}}}))}subscribe(e,t){const i=new mt(e,t);return this.subscriptions.has(e)||this.subscriptions.set(e,new Set),this.subscriptions.get(e).add(i),this.allSubscriptions.set(i.id,i),"connected"===this.connectionState?this.sendMessage({type:"subscribe",compositionId:e,subscriptionId:i.id,timestamp:Date.now()}):this.queueMessage(e,{type:"subscribe",compositionId:e,subscriptionId:i.id,timestamp:Date.now()}),l.info("[RealtimeManager] Subscribed to composition:",{compositionId:e,subscriptionId:i.id,totalSubscriptions:this.allSubscriptions.size}),i}unsubscribe(e){e.unsubscribe();const t=this.subscriptions.get(e.compositionId);t&&(t.delete(e),0===t.size&&this.subscriptions.delete(e.compositionId)),this.allSubscriptions.delete(e.id),"connected"===this.connectionState&&this.sendMessage({type:"unsubscribe",compositionId:e.compositionId,subscriptionId:e.id,timestamp:Date.now()}),l.info("[RealtimeManager] Unsubscribed from composition:",{compositionId:e.compositionId,subscriptionId:e.id,remainingSubscriptions:this.allSubscriptions.size})}getActiveSubscriptions(){return new Set(this.subscriptions.keys())}getApiKey(){return this.config.authentication.credentials}handlePolledUpdate(e){return r(this,void 0,void 0,(function*(){try{const t={type:e.type,compositionId:e.compositionId,data:e.data,userId:e.userId,timestamp:e.timestamp,version:e.version,partial:e.partial};yield this.processUpdate(t,{fromPolling:!0})}catch(e){l.error("[RealtimeManager] Failed to process polled update:",e)}}))}buildWebSocketUrl(){const e=this.config.wsUrl,t=new URLSearchParams;switch(this.config.authentication.type){case"apikey":t.append("apikey",this.config.authentication.credentials);break;case"jwt":t.append("token",this.config.authentication.credentials);break;case"session":t.append("session",this.config.authentication.credentials)}return t.append("client","embed-sdk"),t.append("version","1.0.0"),`${e}?${t.toString()}`}handleConnect(){var e;this.connectionState="connected",this.reconnectAttempts=0;const t=Date.now()-this.connectionStartTime;l.info("[RealtimeManager] Connected to real-time service",{connectionTime:t,subscriptions:this.subscriptions.size}),null===(e=this.performanceMonitor)||void 0===e||e.recordCustomMetric("realtime_connection_time",t),this.pollingFallback&&(this.pollingFallback.stop(),this.pollingFallback=null),this.startHeartbeat(),this.processMessageQueue(),this.reestablishSubscriptions(),this.emitEvent("connected",{connectionTime:t})}handleMessage(e){return r(this,void 0,void 0,(function*(){this.messageStats.received++;try{const t=JSON.parse(e.data);switch(t.type){case"widget_update":yield this.handleWidgetUpdate(t);break;case"widget.published":case"publish:complete":yield this.handlePublishComplete(t);break;case"subscription_confirmed":this.handleSubscriptionConfirmed(t);break;case"heartbeat":this.handleHeartbeat(t);break;case"error":this.handleServerError(t);break;case"authentication":this.handleAuthentication(t);break;default:l.warn("[RealtimeManager] Unknown message type:",t.type)}}catch(e){this.messageStats.errors++,l.error("[RealtimeManager] Message parsing failed:",e)}}))}handleWidgetUpdate(e){return r(this,void 0,void 0,(function*(){const{compositionId:t,updateType:i,data:n,userId:o,timestamp:s,version:r,partial:a}=e;if(!this.config.features[`${i}Updates`])return void l.warn("[RealtimeManager] Update type disabled:",i);if(!this.config.security.allowedUpdateTypes.includes(i))return void l.warn("[RealtimeManager] Update type not allowed:",i);const d=this.subscriptions.get(t);if(!d||0===d.size)return void l.debug("[RealtimeManager] No subscriptions for composition:",t);const c={type:i,compositionId:t,data:n,userId:o,timestamp:s,version:r,partial:a};yield this.processUpdate(c,{fromWebSocket:!0})}))}handlePublishComplete(e){return r(this,void 0,void 0,(function*(){var t,i,n,o;const s=e.compositionId||(null===(t=e.data)||void 0===t?void 0:t.compositionId)||(null===(i=e.data)||void 0===i?void 0:i.widgetId)||e.widgetId||e.id;if(!s)return void l.warn("[RealtimeManager] Received publish message without composition/widget ID:",e);const r=this.subscriptions.get(s);if(!r||0===r.size)return void l.debug("[RealtimeManager] No subscriptions for published composition:",s);const a=(null===(n=e.data)||void 0===n?void 0:n.versionPublished)||(null===(o=e.data)||void 0===o?void 0:o.version)||e.version,d={type:"published",compositionId:s,data:e.data||{},timestamp:e.timestamp||Date.now(),version:a?String(a):void 0};l.info("[RealtimeManager] Processing publish event for composition:",{compositionId:s,version:d.version}),yield this.processUpdate(d,{fromWebSocket:!0})}))}processUpdate(e){return r(this,arguments,void 0,(function*(e,t={}){var i;try{if(this.config.security.validateUpdates&&"published"!==e.type){const t=yield this.securityManager.validateContent(e.compositionId,JSON.stringify(e.data),{userId:e.userId});if(!t.allowed)return l.warn("[RealtimeManager] Update blocked by security:",{compositionId:e.compositionId,violations:t.violations}),void this.emitEvent("security_violation",{compositionId:e.compositionId,violations:t.violations,update:e});if(t.filteredContent)try{e.data=JSON.parse(t.filteredContent)}catch(e){l.warn("[RealtimeManager] Failed to parse filtered content, using original")}}const n=this.subscriptions.get(e.compositionId);if(!n)return;const o=[];for(const t of n)t.isActive()&&o.push(t.handler(e).catch((i=>{l.error("[RealtimeManager] Handler execution failed:",{subscriptionId:t.id,compositionId:e.compositionId,error:i})})));yield Promise.allSettled(o),l.debug("[RealtimeManager] Update applied:",{compositionId:e.compositionId,type:e.type,handlerCount:o.length,source:t.fromWebSocket?"websocket":"polling"}),null===(i=this.performanceMonitor)||void 0===i||i.recordCustomMetric("realtime_updates_processed",1),this.emitEvent("update_applied",{compositionId:e.compositionId,type:e.type,handlerCount:o.length})}catch(t){l.error("[RealtimeManager] Update processing failed:",t),this.emitEvent("update_error",{compositionId:e.compositionId,error:t instanceof Error?t.message:"Unknown error",update:e})}}))}handleSubscriptionConfirmed(e){l.info("[RealtimeManager] Subscription confirmed:",{compositionId:e.compositionId,subscriptionId:e.subscriptionId})}handleHeartbeat(e){this.lastHeartbeat=Date.now(),this.heartbeatTimeout&&(clearTimeout(this.heartbeatTimeout),this.heartbeatTimeout=null),this.sendMessage({type:"heartbeat_response",timestamp:Date.now()})}handleServerError(e){l.error("[RealtimeManager] Server error:",e.data),this.emitEvent("server_error",{error:e.data})}handleAuthentication(e){var t,i,n;(null===(t=e.data)||void 0===t?void 0:t.success)?(this.connectionId=e.data.connectionId,l.info("[RealtimeManager] Authentication successful:",{connectionId:this.connectionId})):(l.error("[RealtimeManager] Authentication failed:",null===(i=e.data)||void 0===i?void 0:i.error),null===(n=this.socket)||void 0===n||n.close())}handleDisconnect(e){this.connectionState="disconnected",this.connectionId=null,l.warn("[RealtimeManager] Disconnected from real-time service:",{code:e.code,reason:e.reason,wasClean:e.wasClean}),this.stopHeartbeat(),this.config.reconnection.enabled&&!e.wasClean&&this.scheduleReconnection(),this.config.fallback.enabled&&this.subscriptions.size>0&&this.enablePollingFallback(),this.emitEvent("disconnected",{code:e.code,reason:e.reason,wasClean:e.wasClean})}handleError(e){var t;this.messageStats.errors++,l.error("[RealtimeManager] WebSocket error:",e),null===(t=this.performanceMonitor)||void 0===t||t.recordCustomMetric("realtime_errors",1),this.emitEvent("error",{event:e})}handleConnectionError(e){return r(this,void 0,void 0,(function*(){l.error("[RealtimeManager] Connection error:",e),this.config.reconnection.enabled?yield this.scheduleReconnection():this.config.fallback.enabled&&this.enablePollingFallback()}))}scheduleReconnection(){return r(this,void 0,void 0,(function*(){if(this.reconnectAttempts>=this.config.reconnection.maxAttempts)return l.error("[RealtimeManager] Max reconnection attempts reached"),this.config.fallback.enabled&&this.enablePollingFallback(),void this.emitEvent("max_reconnect_attempts",{attempts:this.reconnectAttempts});this.connectionState="reconnecting",this.reconnectAttempts++;const e=Math.min(this.config.reconnection.baseDelay*Math.pow(2,this.reconnectAttempts-1),this.config.reconnection.maxDelay);l.info("[RealtimeManager] Scheduling reconnection:",{attempt:this.reconnectAttempts,delay:e,maxAttempts:this.config.reconnection.maxAttempts}),this.reconnectTimer=setTimeout((()=>r(this,void 0,void 0,(function*(){try{yield this.connect()}catch(e){l.error("[RealtimeManager] Reconnection failed:",e),yield this.scheduleReconnection()}}))),e)}))}enablePollingFallback(){!this.pollingFallback&&this.config.fallback.enabled&&(l.info("[RealtimeManager] Enabling polling fallback"),this.pollingFallback=new vt({interval:this.config.fallback.pollInterval||5e3,endpoint:"/api/widgets/updates",subscriptions:this.getActiveSubscriptions(),realtimeManager:this}),this.pollingFallback.start(),this.emitEvent("fallback_enabled",{interval:this.config.fallback.pollInterval}))}sendMessage(e){if("connected"===this.connectionState&&this.socket)try{this.socket.send(JSON.stringify(e)),this.messageStats.sent++}catch(t){this.messageStats.errors++,l.error("[RealtimeManager] Failed to send message:",t),this.queueMessage(e.compositionId||"global",e)}else this.queueMessage(e.compositionId||"global",e)}queueMessage(e,t){this.messageQueue.has(e)||this.messageQueue.set(e,[]);this.messageQueue.get(e).push({message:t,retryCount:0,maxRetries:3,timestamp:Date.now(),nextRetry:Date.now()+1e3}),this.retryTimer||(this.retryTimer=setTimeout((()=>this.processRetryQueue()),1e3))}processRetryQueue(){const e=Date.now();let t=!1;for(const[i,n]of this.messageQueue){const o=[];for(const i of n)e>=i.nextRetry?i.retryCount<i.maxRetries?(i.retryCount++,i.nextRetry=e+1e3*Math.pow(2,i.retryCount),this.sendMessage(i.message),i.retryCount<i.maxRetries&&o.push(i)):l.warn("[RealtimeManager] Message retry limit exceeded:",i.message):(o.push(i),t=!0);o.length>0?this.messageQueue.set(i,o):this.messageQueue.delete(i)}this.retryTimer=null,t&&(this.retryTimer=setTimeout((()=>this.processRetryQueue()),1e3))}processMessageQueue(){if("connected"===this.connectionState){l.info("[RealtimeManager] Processing queued messages:",{queueSize:Array.from(this.messageQueue.values()).reduce(((e,t)=>e+t.length),0)});for(const[e,t]of this.messageQueue)for(const e of t)this.sendMessage(e.message);this.messageQueue.clear(),this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null)}}reestablishSubscriptions(){if(0!==this.subscriptions.size){l.info("[RealtimeManager] Re-establishing subscriptions:",{count:this.subscriptions.size});for(const[e,t]of this.subscriptions)for(const i of t)i.isActive()&&this.sendMessage({type:"subscribe",compositionId:e,subscriptionId:i.id,timestamp:Date.now()})}}startHeartbeat(){this.config.heartbeat.enabled&&(this.stopHeartbeat(),this.heartbeatTimer=setInterval((()=>{"connected"===this.connectionState&&(this.sendMessage({type:"heartbeat",timestamp:Date.now()}),this.heartbeatTimeout=setTimeout((()=>{var e;l.warn("[RealtimeManager] Heartbeat timeout"),null===(e=this.socket)||void 0===e||e.close()}),this.config.heartbeat.timeout))}).bind(this),2*this.config.heartbeat.interval),this.lastHeartbeat=Date.now())}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.heartbeatTimeout&&(clearTimeout(this.heartbeatTimeout),this.heartbeatTimeout=null)}setupEventListeners(){"undefined"!=typeof document&&document.addEventListener("visibilitychange",(()=>{document.hidden?this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval((()=>{"connected"===this.connectionState&&this.sendMessage({type:"heartbeat",timestamp:Date.now()})}).bind(this),2*this.config.heartbeat.interval)):this.startHeartbeat()})),"undefined"!=typeof navigator&&"onLine"in navigator&&(window.addEventListener("online",(()=>{l.info("[RealtimeManager] Network back online"),"disconnected"===this.connectionState&&this.connect()})),window.addEventListener("offline",(()=>{l.warn("[RealtimeManager] Network offline"),this.pollingFallback&&this.pollingFallback.stop()})))}emitEvent(e,t){"undefined"!=typeof document&&document.dispatchEvent(new CustomEvent(`widgetic:realtime:${e}`,{detail:Object.assign({manager:this,timestamp:Date.now()},t)}))}getConnectionState(){return this.connectionState}getStats(){return{connectionState:this.connectionState,subscriptions:this.allSubscriptions.size,messageStats:Object.assign({},this.messageStats),reconnectAttempts:this.reconnectAttempts,lastHeartbeat:this.lastHeartbeat,queuedMessages:Array.from(this.messageQueue.values()).reduce(((e,t)=>e+t.length),0)}}disconnect(){l.info("[RealtimeManager] Disconnecting"),this.pollingFallback&&(this.pollingFallback.stop(),this.pollingFallback=null),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null),this.stopHeartbeat(),this.socket&&(this.socket.close(),this.socket=null),this.connectionState="disconnected",this.subscriptions.clear(),this.allSubscriptions.clear(),this.messageQueue.clear(),this.emitEvent("manual_disconnect",{})}}function yt(e){return ft.getInstance(e)}function wt(e){e.setAttribute("data-widgetic-mounted","1"),e.removeAttribute("data-widgetic-mounting"),e.hasAttribute(Fe)||(e.style.display="block")}function bt(e,t,i,n){wt(e);const o=D(e),s=R(e,i),r=_e(t,n||e.getAttribute("width")||"400",e.getAttribute("height")||"300",o||void 0,s);if(e.appendChild(r),o)try{!function(e,t,i,n){let o;try{o=new URL(i).origin}catch(e){return}const s=ut.get(e);s&&s.destroy();const r=new gt(e,t,o,n);ut.set(e,r),r.postHostSnapshot()}(e,r,t,o)}catch(e){}try{L(e,i,(t=>{const i=function(e){return ut.get(e)}(e);if(i)i.sendWidgetUpdate({design:t.design,content:t.content,contentItems:t.contentItems});else if(r.contentWindow)try{r.contentWindow.postMessage(Object.assign(Object.assign(Object.assign({type:"widgetic:update"},t.design?{design:t.design}:{}),t.content?{content:t.content}:{}),t.contentItems?{contentItems:t.contentItems}:{}),"*")}catch(e){}}))}catch(e){}}ft.instance=null;function It(e,t,i){var n;const o=D(e)||"",s=R(e,t);("iframe"===e.getAttribute("render-mode")||"true"===e.getAttribute("use-iframe")||!e.getAttribute("composition-id")&&Boolean(o)&&!(null===(n=s.direct)||void 0===n?void 0:n.moduleUrl))&&s.embedUrl?bt(e,s.embedUrl,s,i):st(e,s,i,wt).then((t=>{t||e.isConnected&&(D(e)||"")===o&&(e.getAttribute("data-widgetic-mounted")||Tt(e,o,"REPUBLISH_REQUIRED","republish_required"))}))}function Tt(e,t,i,n){e.removeAttribute("data-widgetic-mounting"),e.setAttribute(rt,i),pt(e,t,n)}function St(e){var t;C(e);const i=W(e),n=null!==(t=null==i?void 0:i.id)&&void 0!==t?t:null;if(O(e),n){!function(e,t){const i=e.getAttribute(dt);if(i&&i!==t){ct(e),nt(e);for(const t of Array.from(e.querySelectorAll("iframe")))t.remove();e.style.display="",e.removeAttribute("data-widgetic-overlay")}e.setAttribute(dt,t)}(e,n);try{!function(e){const t=D(e);if(!t)return()=>{};const i=Et.get(e);if(i)return i;let n;try{n=yt()}catch(e){return()=>{}}const o=n.subscribe(t,(t=>r(this,void 0,void 0,(function*(){"published"===t.type?yield function(e){return r(this,void 0,void 0,(function*(){const t=D(e);if(!t||!e.isConnected)return!1;try{const e=$();e.getPersistedState(t)&&e.updateWidgetState(t,{lastInteraction:Date.now()})}catch(e){}try{const e=j();e.getPersistedPosition(t)&&e.updateWidgetPosition(t,{lastInteraction:Date.now()})}catch(e){}!function(e){const t=Et.get(e);t&&t();x(e),nt(e),function(e){const t=ut.get(e);t&&(t.destroy(),ut.delete(e))}(e)}(e),ct(e);for(const t of Array.from(e.querySelectorAll("iframe")))t.remove();return St(e)}))}(e):"content"===t.type||"data"===t.type?function(e,t){const i=D(e);if(!i||!t)return;const n="object"==typeof t&&null!==t&&!Array.isArray(t),o=n?t:null,s=Array.isArray(t)?t:o&&Array.isArray(o.contentItems)?o.contentItems:void 0,r=o?"object"!=typeof o.content||null===o.content||Array.isArray(o.content)?o:o.content:{content:t};it(e,Object.assign({content:r},s?{contentItems:s}:{}));const a=e.querySelector("iframe");if(null==a?void 0:a.contentWindow){const e="*";try{a.contentWindow.postMessage(Object.assign({type:"widgetic:update",content:r},s?{contentItems:s}:{}),e),a.contentWindow.postMessage({type:"widgetic_content_update",content:t},e),a.contentWindow.postMessage({type:"widgetic_data_update",data:t},e)}catch(e){}}if(n&&o)try{let t={};const i=e.getAttribute("values");if(i)try{t=JSON.parse(i)}catch(e){}const n=Object.assign(Object.assign({},t),o);e.setAttribute("values",JSON.stringify(n))}catch(e){}}(e,t.data):"style"===t.type&&function(e,t){const i=D(e);if(!i||!t)return;"object"!=typeof t||null===t||Array.isArray(t)||it(e,{design:t});const n=e.querySelector("iframe");if(null==n?void 0:n.contentWindow){const e="*";try{n.contentWindow.postMessage({type:"widgetic:update",design:t},e),n.contentWindow.postMessage({type:"widgetic_style_update",styles:t},e)}catch(e){}}}(e,t.data)})))),s=()=>{o.unsubscribe(),Et.delete(e)};Et.set(e,s)}(e)}catch(e){}}if(e.getAttribute("data-widgetic-mounted")||e.getAttribute("data-widgetic-mounting")||e.getAttribute(He)||e.getAttribute(rt))return!0;const o=e.getAttribute("src");if(o)return bt(e,o),!0;if(!i||!n)return!1;const s=e.hasAttribute(He),a=function(e){var t,i,n,o,s;let r;try{r=E(e)}catch(e){return l.warn("[published-host-display] Could not read the embed's display settings",{error:e}),{suppressed:!1}}return $e(null===(i=null===(t=r.device)||void 0===t?void 0:t.mobileEnabled)||void 0===i||i,null===(o=null===(n=r.device)||void 0===n?void 0:n.desktopEnabled)||void 0===o||o)?("overlay"===(null===(s=r.triggers)||void 0===s?void 0:s.mode)&&(e.style.display="none",e.setAttribute(Fe,"pending")),{suppressed:!1,triggers:r.triggers}):(e.style.display="none",e.setAttribute(He,"true"),l.debug("[published-host-display] Embed skipped: this device is switched off",{compositionId:r.compositionId,device:r.device}),{suppressed:!0})}(e);if(a.suppressed)return s||pt(e,n,"device_restricted"),!0;e.setAttribute("data-widgetic-mounting","1");return("widget"===i.kind?Le(n):Re(n)).then((t=>{var i;if(e.getAttribute("data-widgetic-mounted"))return;if("refused"===t.status)return e.removeAttribute("data-widgetic-mounting"),e.setAttribute(rt,t.refusal.code),Pe(n,t.refusal),void pt(e,n,Te(t.refusal.code)||"domain_not_allowed");if("failed"===t.status)return void Tt(e,n,t.failure.gatewayCode,t.failure.stateCode);const o="found"===t.status?t.payload:null;if(!(null==o?void 0:o.embedUrl))return e.removeAttribute("data-widgetic-mounting"),void Tt(e,n,"NOT_FOUND","not_found");const{triggers:s}=a;if("overlay"!==(null==s?void 0:s.mode))It(e,o),s&&Ve(e,s);else{const t=(null===(i=s.overlay)||void 0===i?void 0:i.fullWidth)?"100%":void 0;Ve(e,s,(()=>It(e,o,t)))}})),!0}function kt(e=document){const t=e.querySelectorAll("widgetic, widgetic-embed");let i=0;for(const e of Array.from(t))e instanceof HTMLElement&&St(e)&&(i+=1);return i}const Et=new WeakMap;const Mt={maxBatchSize:50,debounceDelay:10,retryAttempts:3,retryBaseDelay:1e3,cacheTTL:3e5};class Ct{constructor(e={}){this.compositionCache=new Map,this.widgetCache=new Map,this.pendingCompositionRequests=new Map,this.pendingWidgetRequests=new Map,this.compositionResolvers=new Map,this.widgetResolvers=new Map,this.compositionBatchQueue=[],this.widgetBatchQueue=[],this.compositionBatchTimer=null,this.widgetBatchTimer=null,this.lastBatchError=null,this.config=Object.assign(Object.assign({},Mt),e)}getCompositions(e){return r(this,void 0,void 0,(function*(){"undefined"!=typeof performance&&"function"==typeof performance.mark&&performance.mark("api-batch-compositions-start");try{const t=[],i=[];for(const n of e){const e=this.getCachedComposition(n);if(e){t.push(e);continue}const o=this.pendingCompositionRequests.get(n);if(o)try{const e=yield o;t.push(e);continue}catch(e){}i.push(n)}if(i.length>0){const e=yield this.batchCompositions(i);t.push(...e)}return Object.defineProperty(t,"compositions",{get(){return this},enumerable:!1,configurable:!0}),Object.defineProperty(t,"success",{value:!this.lastBatchError,enumerable:!1,configurable:!0}),Object.defineProperty(t,"error",{value:this.lastBatchError||void 0,enumerable:!1,configurable:!0}),t}finally{"undefined"!=typeof performance&&"function"==typeof performance.mark&&performance.mark("api-batch-compositions-end")}}))}getWidgets(e){return r(this,void 0,void 0,(function*(){const t=[],i=[];for(const n of e){const e=this.getCachedWidget(n);if(e){t.push(e);continue}const o=this.pendingWidgetRequests.get(n);if(o)try{const e=yield o;t.push(e);continue}catch(e){}i.push(n)}if(i.length>0){const e=yield this.batchWidgets(i);t.push(...e)}return t}))}getComposition(e){return r(this,void 0,void 0,(function*(){const t=yield this.getCompositions([e]);if(0===t.length)throw new Error(`Composition not found: ${e}`);return t[0]}))}getWidget(e){return r(this,void 0,void 0,(function*(){const t=yield this.getWidgets([e]);if(0===t.length)throw new Error(`Widget not found: ${e}`);return t[0]}))}batchCompositions(e){return r(this,void 0,void 0,(function*(){var t;const i=[];for(const t of e)if(this.pendingCompositionRequests.has(t))i.push(this.pendingCompositionRequests.get(t));else{const e=new Promise(((e,i)=>{this.compositionBatchQueue.push(t),this.scheduleCompositionBatch(),this.compositionResolvers.set(t,{resolve:e,reject:i})}));this.pendingCompositionRequests.set(t,e),i.push(e)}const n=yield Promise.allSettled(i),o=n.find((e=>"rejected"===e.status));return this.lastBatchError=o?(null===(t=o.reason)||void 0===t?void 0:t.message)||String(o.reason):null,n.filter((e=>"fulfilled"===e.status)).map((e=>e.value))}))}batchWidgets(e){return r(this,void 0,void 0,(function*(){const t=[];for(const i of e)if(this.pendingWidgetRequests.has(i))t.push(this.pendingWidgetRequests.get(i));else{const e=new Promise(((e,t)=>{this.widgetBatchQueue.push(i),this.scheduleWidgetBatch(),this.widgetResolvers.set(i,{resolve:e,reject:t})}));this.pendingWidgetRequests.set(i,e),t.push(e)}return(yield Promise.allSettled(t)).filter((e=>"fulfilled"===e.status)).map((e=>e.value))}))}scheduleCompositionBatch(){this.compositionBatchTimer||(this.compositionBatchTimer=window.setTimeout((()=>{this.executeCompositionBatch()}),this.config.debounceDelay))}scheduleWidgetBatch(){this.widgetBatchTimer||(this.widgetBatchTimer=window.setTimeout((()=>{this.executeWidgetBatch()}),this.config.debounceDelay))}executeCompositionBatch(){return r(this,void 0,void 0,(function*(){const e=[...this.compositionBatchQueue];if(this.compositionBatchQueue=[],this.compositionBatchTimer=null,0!==e.length)try{const t=yield this.fetchCompositionsBatch(e);for(const e of t.compositions){this.cacheComposition(e);const t=this.compositionResolvers.get(e.id);t&&(t.resolve(e),this.compositionResolvers.delete(e.id)),this.pendingCompositionRequests.delete(e.id)}if(t.errors)for(const e of t.errors){const t=this.compositionResolvers.get(e.id);t&&(t.reject(new Error(e.error)),this.compositionResolvers.delete(e.id)),this.pendingCompositionRequests.delete(e.id)}for(const t of e){const e=this.compositionResolvers.get(t);e&&(e.reject(new Error(`Composition not found in batch response: ${t}`)),this.compositionResolvers.delete(t)),this.pendingCompositionRequests.delete(t)}}catch(t){for(const i of e){const e=this.compositionResolvers.get(i);e&&(e.reject(t),this.compositionResolvers.delete(i)),this.pendingCompositionRequests.delete(i)}}}))}executeWidgetBatch(){return r(this,void 0,void 0,(function*(){const e=[...this.widgetBatchQueue];if(this.widgetBatchQueue=[],this.widgetBatchTimer=null,0!==e.length)try{const t=yield this.fetchWidgetsBatch(e);for(const e of t.widgets){this.cacheWidget(e);const t=this.widgetResolvers.get(e.id);t&&(t.resolve(e),this.widgetResolvers.delete(e.id)),this.pendingWidgetRequests.delete(e.id)}if(t.errors)for(const e of t.errors){const t=this.widgetResolvers.get(e.id);t&&(t.reject(new Error(e.error)),this.widgetResolvers.delete(e.id)),this.pendingWidgetRequests.delete(e.id)}for(const t of e){const e=this.widgetResolvers.get(t);e&&(e.reject(new Error(`Widget not found in batch response: ${t}`)),this.widgetResolvers.delete(t)),this.pendingWidgetRequests.delete(t)}}catch(t){for(const i of e){const e=this.widgetResolvers.get(i);e&&(e.reject(t),this.widgetResolvers.delete(i)),this.pendingWidgetRequests.delete(i)}}}))}fetchCompositionsBatch(e){return r(this,arguments,void 0,(function*(e,t=1){var i,n,o;try{const t=yield g(),n=new J({basePath:p(),apiKey:()=>r(this,void 0,void 0,(function*(){return t})),headers:{"X-SDK-Version":`embed-sdk/${m}`}}),o=new Z(n),s=yield o.getCompositionsBatch({getCompositionsBatchRequest:{compositionIds:e}}),d=s.compositions||[];return{compositions:d.map((e=>{if(!e||"object"!=typeof e)return e;const{internalConfig:t,adminNotes:i}=e;return a(e,["internalConfig","adminNotes"])})),errors:null===(i=s.errors)||void 0===i?void 0:i.filter((e=>(null==e?void 0:e.id)&&(null==e?void 0:e.error))).map((e=>({id:e.id,error:e.error})))}}catch(i){if(t<this.config.retryAttempts){const i=this.config.retryBaseDelay*Math.pow(2,t-1);return yield new Promise((e=>setTimeout(e,i))),this.fetchCompositionsBatch(e,t+1)}const s=null===(n=null==i?void 0:i.response)||void 0===n?void 0:n.status,r=null===(o=null==i?void 0:i.response)||void 0===o?void 0:o.statusText;if("number"==typeof s){let e=`HTTP ${s}: ${r||"Request failed"}`;switch(s){case 401:e="Unauthorized: API key is invalid or missing";break;case 403:e="Forbidden: Access denied to these compositions";break;case 404:e="Composition not found: One or more compositions do not exist";break;case 429:e="Rate limit exceeded: Too many requests";break;case 500:e="Server error: Internal server error occurred";break;case 503:e="Service unavailable: API is temporarily down"}throw new Error(e)}throw i}}))}fetchWidgetsBatch(e){return r(this,arguments,void 0,(function*(e,t=1){var i,n,o;try{const t=yield g(),n=new J({basePath:p(),apiKey:()=>r(this,void 0,void 0,(function*(){return t})),headers:{"X-SDK-Version":`embed-sdk/${m}`}}),o=new ee(n),s=yield o.getWidgetsBatch({getWidgetsBatchRequest:{widgetIds:e}});return{widgets:s.widgets||[],errors:null===(i=s.errors)||void 0===i?void 0:i.filter((e=>(null==e?void 0:e.id)&&(null==e?void 0:e.error))).map((e=>({id:e.id,error:e.error})))}}catch(i){if(t<this.config.retryAttempts){const i=this.config.retryBaseDelay*Math.pow(2,t-1);return yield new Promise((e=>setTimeout(e,i))),this.fetchWidgetsBatch(e,t+1)}const s=null===(n=null==i?void 0:i.response)||void 0===n?void 0:n.status,r=null===(o=null==i?void 0:i.response)||void 0===o?void 0:o.statusText;if("number"==typeof s){let e=`HTTP ${s}: ${r||"Request failed"}`;switch(s){case 401:e="Unauthorized: API key is invalid or missing";break;case 403:e="Forbidden: Access denied to these widgets";break;case 404:e="Widget not found: One or more widgets do not exist";break;case 429:e="Rate limit exceeded: Too many requests";break;case 500:e="Server error: Internal server error occurred";break;case 503:e="Service unavailable: API is temporarily down"}throw new Error(e)}throw i}}))}getCachedComposition(e){const t=this.compositionCache.get(e);if(!t)return null;return Date.now()-t.timestamp>t.ttl?(this.compositionCache.delete(e),null):t.data}getCachedWidget(e){const t=this.widgetCache.get(e);if(!t)return null;return Date.now()-t.timestamp>t.ttl?(this.widgetCache.delete(e),null):t.data}cacheComposition(e){this.compositionCache.set(e.id,{data:e,timestamp:Date.now(),ttl:this.config.cacheTTL})}cacheWidget(e){this.widgetCache.set(e.id,{data:e,timestamp:Date.now(),ttl:this.config.cacheTTL})}clearCache(){this.compositionCache.clear(),this.widgetCache.clear()}getCacheStats(){return{compositions:{size:this.compositionCache.size,entries:Array.from(this.compositionCache.entries()).map((([e,t])=>({id:e,age:Date.now()-t.timestamp,ttl:t.ttl})))},widgets:{size:this.widgetCache.size,entries:Array.from(this.widgetCache.entries()).map((([e,t])=>({id:e,age:Date.now()-t.timestamp,ttl:t.ttl})))},pending:{compositions:this.pendingCompositionRequests.size,widgets:this.pendingWidgetRequests.size},queues:{compositions:this.compositionBatchQueue.length,widgets:this.widgetBatchQueue.length}}}}let Dt=null;function At(){return Dt||(Dt=new Ct),Dt}function Wt(){Dt=null}var Ot=Object.freeze({__proto__:null,BatchApiClient:Ct,getBatchClient:At,resetBatchClient:Wt});const xt={cacheTTL:18e5,loadTimeout:1e4,maxRetries:3,retryDelay:1e3,enableHttp3:!0,cdnBaseUrl:v()};class Rt{constructor(e={}){this.moduleCache=new Map,this.loadingPromises=new Map,this.dependencyGraph=new Map,this.http3Supported=null,this.config=Object.assign(Object.assign({},xt),e)}loadModule(e){return r(this,arguments,void 0,(function*(e,t={}){const i=this.getModuleKey(e.id,t.version||e.version),n=this.loadingPromises.get(i);if(n&&!t.force)return n;if(!t.force){const e=this.getCachedModule(i);if(e)return{module:e.module,url:e.url,loadTime:0,cached:!0}}const o=this.doLoadModule(e,t);this.loadingPromises.set(i,o);try{const e=yield o;return this.loadingPromises.delete(i),e}catch(e){throw this.loadingPromises.delete(i),e}}))}loadModules(e){return r(this,arguments,void 0,(function*(e,t={}){const i=new Map,n=new Map;for(const t of e)if(n.set(t.id,t),t.dependencies){this.dependencyGraph.set(t.id,new Set(t.dependencies));for(const e of t.dependencies)i.set(e,t)}const o=this.resolveDependencyOrder(e),s=[];for(const e of o)try{const i=yield this.loadModule(e,t);s.push(i)}catch(e){}return s}))}getLatestVersion(e){return r(this,void 0,void 0,(function*(){try{const t=`${this.config.cdnBaseUrl}/${e}/latest`,i=yield this.fetchWithHttp3(t,{timeout:5e3});if(i.ok){return(yield i.json()).version}}catch(e){}return null}))}preloadModules(e){return r(this,void 0,void 0,(function*(){const t=e.map((e=>this.loadModule(e,{timeout:3e4}).catch((e=>{}))));yield Promise.allSettled(t)}))}invalidateModule(e,t){if(t){const i=this.getModuleKey(e,t);this.moduleCache.delete(i)}else{Array.from(this.moduleCache.keys()).filter((t=>t.startsWith(`${e}@`))).forEach((e=>this.moduleCache.delete(e)))}}clearCache(){this.moduleCache.clear(),this.loadingPromises.clear()}getCacheStats(){return{size:this.moduleCache.size,entries:Array.from(this.moduleCache.entries()).map((([e,t])=>({key:e,version:t.version,age:Date.now()-t.timestamp,ttl:t.ttl,url:t.url}))),loading:this.loadingPromises.size,http3Supported:this.http3Supported}}doLoadModule(e,t){return r(this,void 0,void 0,(function*(){const i=Date.now(),n=t.version||e.version,o=this.resolveModuleUrl(e,n);try{e.dependencies&&e.dependencies.length>0&&(yield this.loadDependencies(e.dependencies));const s=yield this.loadModuleFromUrl(o,{timeout:t.timeout||this.config.loadTimeout,retries:t.retries||this.config.maxRetries});if(!this.validateModule(s))throw new Error(`Invalid module structure for ${e.id}`);const r=this.getModuleKey(e.id,n);return this.cacheModule(r,{module:s,url:o,timestamp:Date.now(),version:n,ttl:this.config.cacheTTL}),{module:s,url:o,loadTime:Date.now()-i,cached:!1}}catch(t){const i=t instanceof Error?t.message:String(t);throw new Error(`Failed to load module ${e.id}@${n}: ${i}`)}}))}loadModuleFromUrl(e,t){return r(this,void 0,void 0,(function*(){let i=null;for(let n=1;n<=t.retries;n++)try{if(e.endsWith(".mjs")||e.includes("type=module")){const i=yield this.loadEsModule(e,t.timeout);return this.extractWidgetFromEsModule(i)}const i=yield this.fetchModuleText(e,t.timeout);return this.evaluateUmdModule(i,e)}catch(e){if(i=e instanceof Error?e:new Error(String(e)),n<t.retries){const e=this.config.retryDelay*Math.pow(2,n-1);yield new Promise((t=>setTimeout(t,e)))}}throw i||new Error("Module loading failed")}))}loadEsModule(e,t){return r(this,void 0,void 0,(function*(){return new Promise(((i,n)=>{const o=setTimeout((()=>{n(new Error(`Module load timeout: ${e}`))}),t);import(e).then((e=>{clearTimeout(o),i(e)})).catch((e=>{clearTimeout(o),n(e)}))}))}))}fetchModuleText(e,t){return r(this,void 0,void 0,(function*(){const i=yield this.fetchWithHttp3(e,{timeout:t});if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);return yield i.text()}))}fetchWithHttp3(e,t){return r(this,void 0,void 0,(function*(){null===this.http3Supported&&(this.http3Supported=yield this.detectHttp3Support());const i={signal:AbortSignal.timeout(t.timeout)};return fetch(e,i)}))}detectHttp3Support(){return r(this,void 0,void 0,(function*(){var e;try{if("connection"in navigator&&"effectiveType"in navigator.connection){const e=navigator.connection;return"4g"===e.effectiveType||"5g"===e.effectiveType}const t=`${this.config.cdnBaseUrl}/test-http3`,i=yield fetch(t,{method:"HEAD",signal:AbortSignal.timeout(2e3)}).catch((()=>null));return(null===(e=null==i?void 0:i.headers.get("alt-svc"))||void 0===e?void 0:e.includes("h3"))||!1}catch(e){return!1}}))}extractWidgetFromEsModule(e){const t=e.default||e.Widget||e.widget||e;if(!t)throw new Error("No widget found in module exports");return{id:t.id||"unknown",version:t.version||"1.0.0",component:t.component||t,metadata:t.metadata,dependencies:t.dependencies}}evaluateUmdModule(e,t){const i={window:"undefined"!=typeof window?window:{},document:"undefined"!=typeof document?document:{},console:console,setTimeout:setTimeout,clearTimeout:clearTimeout,setInterval:setInterval,clearInterval:clearInterval},n=new Function("window","document","console","setTimeout","clearTimeout","setInterval","clearInterval",`\n let module = { exports: {} };\n let exports = module.exports;\n \n ${e}\n \n return module.exports.default || module.exports;\n `)(i.window,i.document,i.console,i.setTimeout,i.clearTimeout,i.setInterval,i.clearInterval);if(!n)throw new Error(`Module evaluation failed: ${t}`);return{id:n.id||"unknown",version:n.version||"1.0.0",component:n.component||n,metadata:n.metadata,dependencies:n.dependencies}}loadDependencies(e){return r(this,void 0,void 0,(function*(){const t=e.map((e=>r(this,void 0,void 0,(function*(){try{if("undefined"!=typeof window&&window[e])return}catch(e){}}))));yield Promise.allSettled(t)}))}resolveDependencyOrder(e){const t=new Set,i=new Set,n=[],o=new Map(e.map((e=>[e.id,e]))),s=e=>{if(i.has(e.id))throw new Error(`Circular dependency detected: ${e.id}`);if(!t.has(e.id)){if(i.add(e.id),e.dependencies)for(const t of e.dependencies){const e=o.get(t);e&&s(e)}i.delete(e.id),t.add(e.id),n.push(e)}};for(const i of e)t.has(i.id)||s(i);return n}resolveModuleUrl(e,t){return e.moduleUrl?e.moduleUrl.replace("{{version}}",t):`${this.config.cdnBaseUrl}/${e.id}/${t}/widget.mjs`}validateModule(e){return!!(e&&e.id&&e.version&&e.component)}getModuleKey(e,t){return`${e}@${t}`}getCachedModule(e){const t=this.moduleCache.get(e);if(!t)return null;return Date.now()-t.timestamp>t.ttl?(this.moduleCache.delete(e),null):t}cacheModule(e,t){this.moduleCache.set(e,t)}}let Lt=null;function Ut(){return Lt||(Lt=new Rt),Lt}function Pt(){Lt=null}var _t=Object.freeze({__proto__:null,ModuleLoader:Rt,getModuleLoader:Ut,resetModuleLoader:Pt});const zt={close:"Close",closeOverlay:"Close overlay",interactiveWidget:"Interactive widget"},jt=new Map([["fr",{close:"Fermer",closeOverlay:"Fermer la fenêtre",interactiveWidget:"Widget interactif"}],["de",{close:"Schließen",closeOverlay:"Fenster schließen",interactiveWidget:"Interaktives Widget"}],["es",{close:"Cerrar",closeOverlay:"Cerrar ventana",interactiveWidget:"Widget interactivo"}],["pt",{close:"Fechar",closeOverlay:"Fechar janela",interactiveWidget:"Widget interativo"}],["nl",{close:"Sluiten",closeOverlay:"Venster sluiten",interactiveWidget:"Interactieve widget"}],["da",{close:"Luk",closeOverlay:"Luk vinduet",interactiveWidget:"Interaktiv widget"}],["sv",{close:"Stäng",closeOverlay:"Stäng fönstret",interactiveWidget:"Interaktiv widget"}],["zh",{close:"关闭",closeOverlay:"关闭窗口",interactiveWidget:"交互式小组件"}],["ar",{close:"إغلاق",closeOverlay:"إغلاق النافذة",interactiveWidget:"ويجت تفاعلي"}],["he",{close:"סגירה",closeOverlay:"סגירת החלון",interactiveWidget:"וידג'ט אינטראקטיבי"}],["fa",{close:"بستن",closeOverlay:"بستن پنجره",interactiveWidget:"ویجت تعاملی"}],["ur",{close:"بند کریں",closeOverlay:"ونڈو بند کریں",interactiveWidget:"انٹرایکٹو ویجٹ"}]]);function $t(e,t=function(){var e,t;return"undefined"==typeof document?"":(null===(e=document.body)||void 0===e?void 0:e.getAttribute("lang"))||(null===(t=document.documentElement)||void 0===t?void 0:t.getAttribute("lang"))||""}()){const i=function(e){var t,i;const n=(null!=e?e:"").trim().replace(/_/g,"-").toLowerCase().split("-"),o="iw"===n[0]?"he":null!==(t=n[0])&&void 0!==t?t:"",s=null!==(i=n[1])&&void 0!==i?i:"";return("zh"!==o||"tw"!==s&&"hk"!==s&&"hant"!==s)&&jt.has(o)?o:null}(t),n=null===i?void 0:jt.get(i);return(null!=n?n:zt)[e]}jt.keys();class Ft{constructor(e){this.intersectionObserver=null,this.isInViewport=!0,this.hasBeenInViewport=!1,this.scrollListener=null,this.lastScrollY=0,this.scrollDistance=0,this.isTriggered=!1,this.debounceTimer=null,this.rafId=null,this.isDestroyed=!1,this.stats={triggeredCount:0,lastTriggeredAt:null,totalScrollDistance:0,viewportChanges:0},this.widgetId=e.widgetId,this.element=e.element,this.type=e.type,this.config=Object.assign(Object.assign({},this.getDefaultConfig()),e.config),this.initialize()}getDefaultConfig(){return{enabled:!0,threshold:.1,distance:100,direction:"down",debounce:100}}initialize(){this.config.enabled&&(l.debug("Initializing ScrollTrigger",{widgetId:this.widgetId,type:this.type,config:this.config}),this.lastScrollY=window.scrollY,"viewport"===this.type?this.initializeViewportDetection():"distance"===this.type&&this.initializeScrollDistance())}initializeViewportDetection(){this.intersectionObserver=new IntersectionObserver(this.handleIntersection.bind(this),{threshold:this.config.threshold||.1,rootMargin:"0px"}),this.intersectionObserver.observe(this.element),l.debug("Viewport detection initialized",{widgetId:this.widgetId,threshold:this.config.threshold})}initializeScrollDistance(){this.scrollListener=this.debounce(this.handleScrollDistance.bind(this),this.config.debounce||100),window.addEventListener("scroll",this.scrollListener,{passive:!0}),l.debug("Scroll distance tracking initialized",{widgetId:this.widgetId,distance:this.config.distance})}handleIntersection(e){if(this.isDestroyed)return;const t=e[e.length-1];if(!t)return;const i=this.isInViewport;if(this.isInViewport=t.isIntersecting,t.isIntersecting&&(this.hasBeenInViewport=!0),this.stats.viewportChanges++,l.debug("Viewport intersection changed",{widgetId:this.widgetId,isIntersecting:this.isInViewport,intersectionRatio:t.intersectionRatio}),i&&!this.isInViewport){if(!this.hasBeenInViewport)return;this.triggerActivated("scroll-out-of-view",{intersectionRatio:t.intersectionRatio,boundingClientRect:t.boundingClientRect})}else!i&&this.isInViewport&&this.triggerDeactivated("scroll-back-in-view",{intersectionRatio:t.intersectionRatio,boundingClientRect:t.boundingClientRect})}observeElement(e){!this.isDestroyed&&"viewport"===this.type&&this.intersectionObserver&&e!==this.element&&(this.intersectionObserver.unobserve(this.element),this.element=e,this.intersectionObserver.observe(e),l.debug("ScrollTrigger now watching another element",{widgetId:this.widgetId}))}handleScrollDistance(){this.isDestroyed||(this.rafId&&cancelAnimationFrame(this.rafId),this.rafId=requestAnimationFrame((()=>{const e=window.scrollY,t=e-this.lastScrollY;this.stats.totalScrollDistance+=Math.abs(t);const i=t>0,n=t<0;"down"===this.config.direction&&i?this.scrollDistance+=t:("up"===this.config.direction&&n||"any"===this.config.direction)&&(this.scrollDistance+=Math.abs(t));const o=this.config.distance||100;!this.isTriggered&&this.scrollDistance>=o&&(this.isTriggered=!0,this.triggerActivated("scroll-distance",{scrollDistance:this.scrollDistance,direction:i?"down":"up",scrollY:e})),this.lastScrollY=e,l.debug("Scroll distance updated",{widgetId:this.widgetId,scrollDistance:this.scrollDistance,requiredDistance:o,isTriggered:this.isTriggered})})))}triggerActivated(e,t){this.stats.triggeredCount++,this.stats.lastTriggeredAt=new Date;const i=new CustomEvent("widgetic:trigger-activated",{detail:{widgetId:this.widgetId,triggerType:e,triggerData:t}});document.dispatchEvent(i),l.debug("Scroll trigger activated",{widgetId:this.widgetId,triggerType:e,triggerData:t})}triggerDeactivated(e,t){const i=new CustomEvent("widgetic:trigger-deactivated",{detail:{widgetId:this.widgetId,triggerType:e,triggerData:t}});document.dispatchEvent(i),l.debug("Scroll trigger deactivated",{widgetId:this.widgetId,triggerType:e,triggerData:t})}debounce(e,t){return i=>{this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=window.setTimeout((()=>{e()}),t)}}updateConfig(e){if(this.isDestroyed)return;const t=Object.assign({},this.config);this.config=Object.assign(Object.assign({},this.config),e),void 0!==e.threshold&&"viewport"===this.type&&(this.destroy(),this.isDestroyed=!1,this.initializeViewportDetection()),void 0!==e.distance&&"distance"===this.type&&(this.scrollDistance=0,this.isTriggered=!1),l.debug("ScrollTrigger config updated",{widgetId:this.widgetId,oldConfig:t,newConfig:this.config})}reset(){this.isDestroyed||(this.scrollDistance=0,this.isTriggered=!1,this.lastScrollY=window.scrollY,l.debug("ScrollTrigger reset",{widgetId:this.widgetId}))}getStats(){return Object.assign(Object.assign({},this.stats),{type:this.type,isInViewport:this.isInViewport,scrollDistance:this.scrollDistance,isTriggered:this.isTriggered,currentScrollY:window.scrollY})}isActive(){return"viewport"===this.type?!this.isInViewport:"distance"===this.type&&this.isTriggered}forceActivate(){"viewport"===this.type?this.triggerActivated("scroll-out-of-view",{manual:!0}):"distance"===this.type&&(this.isTriggered=!0,this.triggerActivated("scroll-distance",{manual:!0}))}forceDeactivate(){"viewport"===this.type&&this.triggerDeactivated("scroll-back-in-view",{manual:!0})}destroy(){this.isDestroyed||(this.intersectionObserver&&(this.intersectionObserver.disconnect(),this.intersectionObserver=null),this.scrollListener&&(window.removeEventListener("scroll",this.scrollListener),this.scrollListener=null),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null),this.isDestroyed=!0,l.debug("ScrollTrigger destroyed",{widgetId:this.widgetId}))}}class Ht{constructor(e){this.mouseLeaveListener=null,this.lastMouseY=0,this.isTriggered=!1,this.scrollUpListener=null,this.visibilityChangeListener=null,this.backButtonListener=null,this.touchStartListener=null,this.touchEndListener=null,this.lastScrollY=0,this.scrollUpDistance=0,this.touchStartY=0,this.touchStartTime=0,this.isScrollingUp=!1,this.debounceTimer=null,this.isDestroyed=!1,this.stats={triggeredCount:0,lastTriggeredAt:null,desktopTriggers:0,mobileTriggers:0,backButtonTriggers:0,scrollUpTriggers:0,tabSwitchTriggers:0},this.widgetId=e.widgetId,this.config=Object.assign(Object.assign({},this.getDefaultConfig()),e.config),this.initialize()}getDefaultConfig(){return{enabled:!0,desktop:{enabled:!0,sensitivity:10,delay:100},mobile:{enabled:!0,backButton:!0,scrollUp:!0,tabSwitch:!0,sensitivity:50}}}initialize(){var e,t;this.config.enabled&&(l.debug("Initializing ExitIntentTrigger",{widgetId:this.widgetId,config:this.config}),this.lastScrollY=window.scrollY,(null===(e=this.config.desktop)||void 0===e?void 0:e.enabled)&&this.isDesktop()&&this.initializeDesktopTriggers(),(null===(t=this.config.mobile)||void 0===t?void 0:t.enabled)&&this.isMobile()&&this.initializeMobileTriggers())}isDesktop(){return!("ontouchstart"in window)&&!navigator.maxTouchPoints}isMobile(){return"ontouchstart"in window||navigator.maxTouchPoints>0}initializeDesktopTriggers(){var e,t;this.mouseLeaveListener=this.debounce(this.handleMouseLeave.bind(this),(null===(e=this.config.desktop)||void 0===e?void 0:e.delay)||100),this.mouseLeaveListener&&(document.addEventListener("mouseleave",this.mouseLeaveListener),document.addEventListener("mouseout",this.mouseLeaveListener)),l.debug("Desktop exit intent triggers initialized",{widgetId:this.widgetId,sensitivity:null===(t=this.config.desktop)||void 0===t?void 0:t.sensitivity})}initializeMobileTriggers(){const e=this.config.mobile;e.backButton&&(this.backButtonListener=this.handleBackButton.bind(this),window.addEventListener("popstate",this.backButtonListener),history.pushState({widgeticExitIntent:!0},"",window.location.href)),e.scrollUp&&(this.scrollUpListener=this.debounce(this.handleScrollUp.bind(this),50),this.scrollUpListener&&window.addEventListener("scroll",this.scrollUpListener,{passive:!0}),this.touchStartListener=this.handleTouchStart.bind(this),this.touchEndListener=this.handleTouchEnd.bind(this),document.addEventListener("touchstart",this.touchStartListener,{passive:!0}),document.addEventListener("touchend",this.touchEndListener,{passive:!0})),e.tabSwitch&&(this.visibilityChangeListener=this.handleVisibilityChange.bind(this),document.addEventListener("visibilitychange",this.visibilityChangeListener)),l.debug("Mobile exit intent triggers initialized",{widgetId:this.widgetId,backButton:e.backButton,scrollUp:e.scrollUp,tabSwitch:e.tabSwitch})}handleMouseLeave(e){var t;if(this.isDestroyed||this.isTriggered)return;const i=(null===(t=this.config.desktop)||void 0===t?void 0:t.sensitivity)||10;e.clientY<=i&&null===e.relatedTarget&&(this.isTriggered=!0,this.stats.desktopTriggers++,this.triggerActivated("exit-intent",{source:"desktop",method:"mouse-leave",mouseY:e.clientY,sensitivity:i}))}handleBackButton(e){var t;this.isDestroyed||(null===(t=e.state)||void 0===t?void 0:t.widgeticExitIntent)&&(this.stats.backButtonTriggers++,this.triggerActivated("exit-intent",{source:"mobile",method:"back-button"}),history.pushState({widgeticExitIntent:!0},"",window.location.href))}handleScrollUp(){var e;if(this.isDestroyed)return;const t=window.scrollY,i=t-this.lastScrollY;if(i<0){this.scrollUpDistance+=Math.abs(i),this.isScrollingUp=!0;const n=(null===(e=this.config.mobile)||void 0===e?void 0:e.sensitivity)||50;this.scrollUpDistance>=n&&t<=100&&(this.stats.scrollUpTriggers++,this.triggerActivated("exit-intent",{source:"mobile",method:"scroll-up",scrollUpDistance:this.scrollUpDistance,currentScrollY:t,sensitivity:n}),this.scrollUpDistance=0)}else this.scrollUpDistance=0,this.isScrollingUp=!1;this.lastScrollY=t}handleTouchStart(e){if(this.isDestroyed||1!==e.touches.length)return;const t=e.touches[0];this.touchStartY=t.clientY,this.touchStartTime=Date.now()}handleTouchEnd(e){if(this.isDestroyed||1!==e.changedTouches.length)return;const t=e.changedTouches[0].clientY,i=Date.now()-this.touchStartTime,n=t-this.touchStartY;n>100&&i<300&&window.scrollY<=50&&(this.stats.scrollUpTriggers++,this.triggerActivated("exit-intent",{source:"mobile",method:"swipe-up",swipeDistance:n,touchDuration:i,scrollY:window.scrollY}))}handleVisibilityChange(){this.isDestroyed||document.hidden&&(this.stats.tabSwitchTriggers++,this.triggerActivated("exit-intent",{source:"mobile",method:"tab-switch",visibilityState:document.visibilityState}))}triggerActivated(e,t){this.stats.triggeredCount++,this.stats.lastTriggeredAt=new Date;const i=new CustomEvent("widgetic:trigger-activated",{detail:{widgetId:this.widgetId,triggerType:e,triggerData:t}});document.dispatchEvent(i),l.debug("Exit intent trigger activated",{widgetId:this.widgetId,triggerType:e,triggerData:t})}debounce(e,t){return(...i)=>{this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=window.setTimeout((()=>{e.apply(this,i)}),t)}}updateConfig(e){var t,i;if(this.isDestroyed)return;const n=Object.assign({},this.config);this.config=Object.assign(Object.assign({},this.config),e),void 0===e.enabled&&void 0===(null===(t=e.desktop)||void 0===t?void 0:t.enabled)&&void 0===(null===(i=e.mobile)||void 0===i?void 0:i.enabled)||(this.destroy(),this.isDestroyed=!1,this.initialize()),l.debug("ExitIntentTrigger config updated",{widgetId:this.widgetId,oldConfig:n,newConfig:this.config})}reset(){this.isDestroyed||(this.isTriggered=!1,this.scrollUpDistance=0,this.isScrollingUp=!1,this.lastScrollY=window.scrollY,l.debug("ExitIntentTrigger reset",{widgetId:this.widgetId}))}getStats(){return Object.assign(Object.assign({},this.stats),{isTriggered:this.isTriggered,scrollUpDistance:this.scrollUpDistance,isScrollingUp:this.isScrollingUp,currentScrollY:window.scrollY,isDesktop:this.isDesktop(),isMobile:this.isMobile()})}isActive(){return this.isTriggered}forceActivate(e="desktop"){this.triggerActivated("exit-intent",{source:e,method:"manual",manual:!0})}destroy(){this.isDestroyed||(this.mouseLeaveListener&&(document.removeEventListener("mouseleave",this.mouseLeaveListener),document.removeEventListener("mouseout",this.mouseLeaveListener),this.mouseLeaveListener=null),this.backButtonListener&&(window.removeEventListener("popstate",this.backButtonListener),this.backButtonListener=null),this.scrollUpListener&&(window.removeEventListener("scroll",this.scrollUpListener),this.scrollUpListener=null),this.visibilityChangeListener&&(document.removeEventListener("visibilitychange",this.visibilityChangeListener),this.visibilityChangeListener=null),this.touchStartListener&&(document.removeEventListener("touchstart",this.touchStartListener),this.touchStartListener=null),this.touchEndListener&&(document.removeEventListener("touchend",this.touchEndListener),this.touchEndListener=null),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.isDestroyed=!0,l.debug("ExitIntentTrigger destroyed",{widgetId:this.widgetId}))}}const Bt={"top-left":["top","left"],"top-center":["top","center"],"top-right":["top","right"],"center-left":["center","left"],center:["center","center"],"center-center":["center","center"],"center-right":["center","right"],"bottom-left":["bottom","left"],"bottom-center":["bottom","center"],"bottom-right":["bottom","right"]};class Nt{constructor(){this.storageKey="widgetic-overlay-views",this.storageVersion="1.0"}static getInstance(){return Nt.instance||(Nt.instance=new Nt),Nt.instance}canShowOverlay(e,t){if(!(null==t?void 0:t.enabled))return!0;const i=this.getViewHistory(e,t),n=Date.now(),o=60*t.timePeriodHours*60*1e3,s=i.filter((e=>n-e.timestamp<=o)),r=s.length<t.maxViews;return l.debug(`[RecurrenceManager] Recurrence check for ${e}`,{maxViews:t.maxViews,timePeriodHours:t.timePeriodHours,recentViews:s.length,canShow:r}),r}recordView(e,t){if(!(null==t?void 0:t.enabled))return;const i={timestamp:Date.now(),widgetId:e},n=this.getViewHistory(e,t);n.push(i);const o=60*t.timePeriodHours*60*1e3,s=Date.now(),r=n.filter((e=>s-e.timestamp<=o));this.saveViewHistory(e,t,r),l.debug(`[RecurrenceManager] Recorded view for ${e}`,{totalViews:r.length,timePeriodHours:t.timePeriodHours})}getViewHistory(e,t){if(!this.isLocalStorageAvailable())return[];try{const i=this.getStorageKey(e,t),n=localStorage.getItem(i);if(!n)return[];const o=JSON.parse(n);return o.version!==this.storageVersion?[]:Array.isArray(o.views)?o.views:[]}catch(t){return l.warn(`[RecurrenceManager] Failed to load view history for ${e}`,{error:t}),[]}}saveViewHistory(e,t,i){if(this.isLocalStorageAvailable())try{const n=this.getStorageKey(e,t),o={version:this.storageVersion,widgetId:e,views:i,lastUpdated:Date.now()};localStorage.setItem(n,JSON.stringify(o))}catch(t){l.warn(`[RecurrenceManager] Failed to save view history for ${e}`,{error:t})}}getStorageKey(e,t){const i=(null==t?void 0:t.storageKeySuffix)?`-${t.storageKeySuffix}`:"";return`${this.storageKey}-${e}${i}`}isLocalStorageAvailable(){try{const e="__localStorage_test__";return localStorage.setItem(e,e),localStorage.removeItem(e),!0}catch(e){return!1}}getStats(e,t){if(!(null==t?void 0:t.enabled))return null;const i=this.getViewHistory(e,t),n=Date.now(),o=60*t.timePeriodHours*60*1e3,s=i.filter((e=>n-e.timestamp<=o));return{maxViews:t.maxViews,timePeriodHours:t.timePeriodHours,recentViews:s.length,remainingViews:Math.max(0,t.maxViews-s.length),canShow:s.length<t.maxViews,lastView:s.length>0?s[s.length-1].timestamp:null,viewHistory:s.map((e=>e.timestamp))}}clearHistory(e,t){if(!(null==t?void 0:t.enabled)||!this.isLocalStorageAvailable())return;const i=this.getStorageKey(e,t);localStorage.removeItem(i),l.debug(`[RecurrenceManager] Cleared view history for ${e}`)}cleanup(){if(!this.isLocalStorageAvailable())return;const e=[];for(let t=0;t<localStorage.length;t++){const i=localStorage.key(t);if(null==i?void 0:i.startsWith(this.storageKey))try{const t=JSON.parse(localStorage.getItem(i)||"{}"),n=Date.now()-864e5;t.lastUpdated<n&&e.push(i)}catch(t){e.push(i)}}e.forEach((e=>localStorage.removeItem(e))),e.length>0&&l.debug(`[RecurrenceManager] Cleaned up ${e.length} old view records`)}}class Kt{constructor(e){var t;this.scrollTrigger=null,this.exitIntentTrigger=null,this.portal=null,this.overlayContainer=null,this.originalParent=null,this.originalNextSibling=null,this.placeholder=null,this.isInOverlay=!1,this.isDestroyed=!1,this.triggerInstances=new Map,this.keydownListener=null,this.recurrenceManager=Nt.getInstance(),this.delayTimer=null,this.domReadyListener=null,this.fullWidthRestore=null,this.onTriggerActivated=e=>this.handleTriggerActivated(e),this.onTriggerDeactivated=e=>this.handleTriggerDeactivated(e),this.onOverlayClose=e=>this.handleOverlayClose(e),this.widgetId=e.widgetId,this.element=e.element,this.config=Object.assign(Object.assign({},this.getDefaultConfig()),e.config),this.mode=this.config.mode||"site",this.displayWhenShown=null!==(t=e.displayWhenShown)&&void 0!==t?t:"",this.originalParent=this.element.parentElement,this.originalNextSibling=this.element.nextSibling,this.initialize()}getDefaultConfig(){return{mode:"site",scroll:{enabled:!0,threshold:.1,distance:100,direction:"down"},exitIntent:{enabled:!0,desktop:{enabled:!0,sensitivity:10,delay:100},mobile:{enabled:!0,backButton:!0,scrollUp:!0,tabSwitch:!0,sensitivity:50}},overlay:{position:"bottom-right",offset:{x:20,y:20},className:"",style:"",closeButton:!0,backdrop:!1,animation:"slide",background:{enabled:!0,color:"#000",opacity:.5}},recurrence:{enabled:!1,maxViews:1,timePeriodHours:24}}}initialize(){switch(l.debug("Initializing TriggerManager",{widgetId:this.widgetId,mode:this.mode,config:this.config}),this.mode){case"site":break;case"mixed":this.initializeScrollTrigger("viewport");break;case"overlay":this.hideWidget(),this.armOverlayEventTrigger()}this.bindEvents()}armOverlayEventTrigger(){switch(this.config.eventTrigger){case"pageLoad":this.showOnLoad();break;case"delay":this.showAfterDelay();break;case"scroll":this.initializeScrollTrigger("distance");break;default:this.initializeScrollTrigger("distance"),this.initializeExitIntentTrigger()}}whenDomReady(e){this.isDestroyed||("loading"===document.readyState?(this.domReadyListener=()=>{this.domReadyListener=null,this.isDestroyed||e()},document.addEventListener("DOMContentLoaded",this.domReadyListener,{once:!0})):e())}showOnLoad(){this.whenDomReady((()=>this.showOverlay()))}showAfterDelay(){var e,t;if(!1===(null===(e=this.config.delay)||void 0===e?void 0:e.enabled))return;const i=null===(t=this.config.delay)||void 0===t?void 0:t.delayMs,n="number"==typeof i&&Number.isFinite(i)&&i>=0?i:3e3;this.whenDomReady((()=>{null===this.delayTimer&&(this.delayTimer=setTimeout((()=>{this.delayTimer=null,this.showOverlay()}),n),l.debug("Delay trigger armed",{widgetId:this.widgetId,delayMs:n}))}))}initializeScrollTrigger(e){var t;(null===(t=this.config.scroll)||void 0===t?void 0:t.enabled)&&(this.scrollTrigger=new Ft({widgetId:this.widgetId,element:this.element,type:e,config:this.config.scroll}),this.triggerInstances.set("scroll",this.scrollTrigger))}initializeExitIntentTrigger(){var e;(null===(e=this.config.exitIntent)||void 0===e?void 0:e.enabled)&&(this.exitIntentTrigger=new Ht({widgetId:this.widgetId,config:this.config.exitIntent}),this.triggerInstances.set("exitIntent",this.exitIntentTrigger))}bindEvents(){document.addEventListener("widgetic:trigger-activated",this.onTriggerActivated),document.addEventListener("widgetic:trigger-deactivated",this.onTriggerDeactivated),document.addEventListener("widgetic:overlay-close",this.onOverlayClose),this.keydownListener=this.handleEscapeKey.bind(this),document.addEventListener("keydown",this.keydownListener)}handleTriggerActivated(e){const t=e;if(t.detail.widgetId!==this.widgetId)return;if("trigger-manager"===t.detail.source)return;const{triggerType:i,triggerData:n}=t.detail;l.debug("Trigger activated",{widgetId:this.widgetId,triggerType:i,triggerData:n}),"mixed"===this.mode&&"scroll-out-of-view"===i?this.showOverlay():"overlay"!==this.mode||"scroll-distance"!==i&&"exit-intent"!==i||this.showOverlay(),this.dispatchTriggerEvent("activated",i,n)}handleTriggerDeactivated(e){const t=e;if(t.detail.widgetId!==this.widgetId)return;if("trigger-manager"===t.detail.source)return;const{triggerType:i,triggerData:n}=t.detail;l.debug("Trigger deactivated",{widgetId:this.widgetId,triggerType:i,triggerData:n}),"mixed"===this.mode&&"scroll-back-in-view"===i&&this.hideOverlay(),this.dispatchTriggerEvent("deactivated",i,n)}handleOverlayClose(e){var t;(null===(t=e.detail)||void 0===t?void 0:t.widgetId)===this.widgetId&&(this.hideOverlay(),"overlay"===this.mode&&this.hideWidget())}handleEscapeKey(e){"Escape"===e.key&&this.isInOverlay&&(this.hideOverlay(),"overlay"===this.mode&&this.hideWidget())}showOverlay(){var e,t,i,n,o;if(!this.isInOverlay&&!this.isDestroyed){if("overlay"===this.mode&&(null===(e=this.config.recurrence)||void 0===e?void 0:e.enabled)){if(!this.recurrenceManager.canShowOverlay(this.widgetId,this.config.recurrence))return l.debug("Overlay blocked by recurrence limits",{widgetId:this.widgetId,recurrenceConfig:this.config.recurrence}),void this.dispatchEvent("overlay-blocked",{reason:"recurrence-limit",recurrenceStats:this.recurrenceManager.getStats(this.widgetId,this.config.recurrence)})}this.portal||(this.portal=te({target:"widgetic-trigger-portal",className:(null===(t=this.config.overlay)||void 0===t?void 0:t.className)||"",style:(null===(i=this.config.overlay)||void 0===i?void 0:i.style)||"",zIndex:this.getOverlayZIndex(),clickThrough:!this.hasOverlayBackground()})),this.overlayContainer=this.createOverlayContainer(),this.portal.mount(this.overlayContainer),this.leavePlaceholder(),this.overlayContainer.appendChild(this.element),this.element.style.display=this.displayWhenShown,this.applyFullWidthSizing(),this.isInOverlay=!0,"overlay"===this.mode&&(null===(n=this.config.recurrence)||void 0===n?void 0:n.enabled)&&this.recurrenceManager.recordView(this.widgetId,this.config.recurrence),l.debug("Widget moved to overlay",{widgetId:this.widgetId}),this.dispatchEvent("overlay-shown",{mode:this.mode,position:null===(o=this.config.overlay)||void 0===o?void 0:o.position})}}leavePlaceholder(){var e;if("mixed"!==this.mode||this.placeholder)return;const t=this.element.parentNode;if(!t)return;const{width:i,height:n}=this.element.getBoundingClientRect(),o=document.createElement("div");o.setAttribute("data-widgetic-placeholder",this.widgetId),o.setAttribute("aria-hidden","true"),o.style.cssText=`display:block;visibility:hidden;pointer-events:none;width:${i}px;height:${n}px;`,t.insertBefore(o,this.element),this.placeholder=o,null===(e=this.scrollTrigger)||void 0===e||e.observeElement(o)}returnToPlaceholder(){const e=this.placeholder;return!!e&&(this.placeholder=null,!!e.parentNode&&(e.parentNode.replaceChild(this.element,e),!0))}hideOverlay(){var e;this.isInOverlay&&!this.isDestroyed&&(this.restoreFullWidthSizing(),!this.returnToPlaceholder()&&this.originalParent&&(this.originalNextSibling?this.originalParent.insertBefore(this.element,this.originalNextSibling):this.originalParent.appendChild(this.element)),"mixed"===this.mode&&(null===(e=this.scrollTrigger)||void 0===e||e.observeElement(this.element)),this.portal&&this.portal.unmount(),this.overlayContainer=null,this.isInOverlay=!1,l.debug("Widget returned to original position",{widgetId:this.widgetId}),this.dispatchEvent("overlay-hidden",{mode:this.mode}))}hideWidget(){this.element.style.display="none"}createOverlayContainer(){var e,t,i,n,o;const s=document.createElement("div");s.className="widgetic-trigger-overlay";const r=(null===(e=this.config.overlay)||void 0===e?void 0:e.position)||"bottom-right",a=(null===(t=this.config.overlay)||void 0===t?void 0:t.offset)||{x:20,y:20},d=this.hasOverlayBackground(),c=!!(null===(i=this.config.overlay)||void 0===i?void 0:i.fullWidth),l=this.getOverlayStyles(r,a,this.getOverlayZIndex(),c);if(s.style.cssText=l,d&&this.applyBackgroundStyling(s),null===(n=this.config.overlay)||void 0===n?void 0:n.closeButton){const e=this.createCloseButton(d,c);s.appendChild(e)}return(null===(o=this.config.overlay)||void 0===o?void 0:o.animation)&&s.classList.add(`widgetic-trigger-overlay-${this.config.overlay.animation}`),this.applyOverlayWidgetStyling(s),s}applyBackgroundStyling(e){var t,i;const n=null===(t=this.config.overlay)||void 0===t?void 0:t.background,o=(null==n?void 0:n.color)||"#000000",s=null!==(i=null==n?void 0:n.opacity)&&void 0!==i?i:.5,r=document.createElement("div");r.className="widgetic-trigger-overlay-backdrop",r.style.cssText=`\n position: fixed;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n background-color: ${o};\n opacity: ${s};\n pointer-events: auto;\n z-index: -1;\n `,r.addEventListener("click",(e=>{e.target===r&&this.dispatchEvent("overlay-close",{widgetId:this.widgetId})})),e.insertBefore(r,e.firstChild),e.classList.add("widgetic-trigger-overlay-has-background")}hasOverlayBackground(){var e,t,i;return!(!(null===(t=null===(e=this.config.overlay)||void 0===e?void 0:e.background)||void 0===t?void 0:t.enabled)&&!(null===(i=this.config.overlay)||void 0===i?void 0:i.backdrop))}getOverlayZIndex(){var e;const t=null===(e=this.config.overlay)||void 0===e?void 0:e.zIndex;return"number"!=typeof t||!Number.isFinite(t)||t<=0?99999999:Math.min(Math.floor(t),we)}getOverlayStyles(e,t,i,n){const[o,s]=Bt[e]||Bt["bottom-right"];let r=`\n position: fixed;\n z-index: ${i};\n pointer-events: auto;\n max-height: 90vh;\n `;return n?r+="left: 0; right: 0; width: 100%; max-width: 100vw;":(r+="max-width: 90vw;",r+="left"===s?`left: ${t.x}px;`:"right"===s?`right: ${t.x}px;`:"left: 0; right: 0; margin-left: auto; margin-right: auto; width: -moz-fit-content; width: fit-content;"),r+="top"===o?`top: ${n?0:t.y}px;`:"bottom"===o?`bottom: ${n?0:t.y}px;`:"top: 0; bottom: 0; margin-top: auto; margin-bottom: auto; height: -moz-fit-content; height: fit-content;",r}applyFullWidthSizing(){var e;if(!(null===(e=this.config.overlay)||void 0===e?void 0:e.fullWidth)||this.fullWidthRestore)return;const t=Array.from(this.element.querySelectorAll("iframe"));this.fullWidthRestore={elementWidth:this.element.style.width,iframes:t.map((e=>({iframe:e,width:e.style.width})))},this.element.style.width="100%",t.forEach((e=>{e.style.width="100%"}))}restoreFullWidthSizing(){this.fullWidthRestore&&(this.element.style.width=this.fullWidthRestore.elementWidth,this.fullWidthRestore.iframes.forEach((({iframe:e,width:t})=>{e.style.width=t})),this.fullWidthRestore=null)}createCloseButton(e,t=!1){const i=document.createElement("button");i.className="widgetic-trigger-overlay-close",i.setAttribute("aria-label",$t("closeOverlay")),i.setAttribute("type","button");const n=this.createCloseSVG();i.appendChild(n);const o=t?"\n position: absolute;\n top: 8px;\n right: 8px;\n ":e?"\n position: absolute;\n top: 20px;\n right: 20px;\n ":"\n position: absolute;\n top: -16px;\n right: -16px;\n ";return i.style.cssText=o+"\n width: 32px;\n height: 32px;\n border-radius: 50%;\n border: none;\n background: #000000;\n color: #ffffff;\n cursor: pointer;\n z-index: 1;\n display: flex;\n align-items: center;\n justify-content: center;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);\n transition: all 0.2s ease;\n ",i.addEventListener("mouseenter",(()=>{i.style.backgroundColor="#333333",i.style.transform="scale(1.1)"})),i.addEventListener("mouseleave",(()=>{i.style.backgroundColor="#000000",i.style.transform="scale(1)"})),i.addEventListener("click",(e=>{e.stopPropagation(),this.dispatchEvent("overlay-close",{widgetId:this.widgetId})})),i}createCloseSVG(){const e=document.createElementNS("http://www.w3.org/2000/svg","svg");e.setAttribute("width","16"),e.setAttribute("height","16"),e.setAttribute("viewBox","0 0 16 16"),e.setAttribute("fill","none"),e.style.pointerEvents="none";const t=document.createElementNS("http://www.w3.org/2000/svg","path");return t.setAttribute("d","M12 4L4 12M4 4l8 8"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","2"),t.setAttribute("stroke-linecap","round"),t.setAttribute("stroke-linejoin","round"),e.appendChild(t),e}dispatchTriggerEvent(e,t,i){this.dispatchEvent(`trigger-${e}`,{triggerType:t,triggerData:i,mode:this.mode,isInOverlay:this.isInOverlay})}dispatchEvent(e,t){const i=new CustomEvent(`widgetic:${e}`,{detail:Object.assign(Object.assign({widgetId:this.widgetId},t),{source:"trigger-manager"})});document.dispatchEvent(i)}updateConfig(e){this.isDestroyed||(this.config=Object.assign(Object.assign({},this.config),e),this.triggerInstances.forEach(((e,t)=>{"scroll"===t&&this.config.scroll?e.updateConfig(this.config.scroll):"exitIntent"===t&&this.config.exitIntent&&e.updateConfig(this.config.exitIntent)})),l.debug("TriggerManager config updated",{widgetId:this.widgetId,config:this.config}))}getStats(){var e;const t={widgetId:this.widgetId,mode:this.mode,isInOverlay:this.isInOverlay,isDestroyed:this.isDestroyed,triggerInstances:Array.from(this.triggerInstances.keys())};return this.triggerInstances.forEach(((e,i)=>{"function"==typeof e.getStats&&(t[`${i}Stats`]=e.getStats())})),(null===(e=this.config.recurrence)||void 0===e?void 0:e.enabled)&&(t.recurrenceStats=this.recurrenceManager.getStats(this.widgetId,this.config.recurrence)),t}forceShowOverlay(){this.showOverlay()}forceHideOverlay(){this.hideOverlay()}getRecurrenceStats(){var e;return(null===(e=this.config.recurrence)||void 0===e?void 0:e.enabled)?this.recurrenceManager.getStats(this.widgetId,this.config.recurrence):null}clearRecurrenceHistory(){var e;(null===(e=this.config.recurrence)||void 0===e?void 0:e.enabled)&&(this.recurrenceManager.clearHistory(this.widgetId,this.config.recurrence),l.debug("Recurrence history cleared",{widgetId:this.widgetId}))}canShowOverlay(){var e;return"overlay"!==this.mode||!(null===(e=this.config.recurrence)||void 0===e?void 0:e.enabled)||this.recurrenceManager.canShowOverlay(this.widgetId,this.config.recurrence)}destroy(){this.isDestroyed||(null!==this.delayTimer&&(clearTimeout(this.delayTimer),this.delayTimer=null),this.domReadyListener&&(document.removeEventListener("DOMContentLoaded",this.domReadyListener),this.domReadyListener=null),this.isInOverlay&&this.hideOverlay(),this.placeholder&&(this.placeholder.remove(),this.placeholder=null),this.triggerInstances.forEach((e=>{"function"==typeof e.destroy&&e.destroy()})),this.triggerInstances.clear(),this.portal&&(this.portal.destroy(),this.portal=null),document.removeEventListener("widgetic:trigger-activated",this.onTriggerActivated),document.removeEventListener("widgetic:trigger-deactivated",this.onTriggerDeactivated),document.removeEventListener("widgetic:overlay-close",this.onOverlayClose),this.keydownListener&&(document.removeEventListener("keydown",this.keydownListener),this.keydownListener=null),this.recurrenceManager.cleanup(),this.isDestroyed=!0,this.overlayContainer=null,this.originalParent=null,this.originalNextSibling=null,l.debug("TriggerManager destroyed",{widgetId:this.widgetId}))}applyOverlayWidgetStyling(e){var t;if(!("mixed"===this.mode))return;if(!1!==(null===(t=this.config.overlay)||void 0===t?void 0:t.keepDimensions))return;const i=this.config.overlay;if(i){if(i.overlayWidth){const t="number"==typeof i.overlayWidth?`${i.overlayWidth}px`:i.overlayWidth;e.style.width=t,e.style.maxWidth=t}if(i.overlayHeight){const t="number"==typeof i.overlayHeight?`${i.overlayHeight}px`:i.overlayHeight;e.style.height=t,e.style.maxHeight=t}i.overlayResize&&this.applyOverlayResizeMode(e,i.overlayResize)}}applyOverlayResizeMode(e,t){switch(t){case"fill-width":e.style.width="90vw",e.style.height="auto",e.style.maxWidth="90vw";break;case"fill-height":e.style.height="90vh",e.style.width="auto",e.style.maxHeight="90vh";break;case"fixed":e.style.flexShrink="0";break;case"fixed-height":e.style.width="90vw",e.style.maxWidth="90vw";break;case"fixed-width":e.style.height="90vh",e.style.maxHeight="90vh";break;case"allow-scale-down":e.style.maxWidth="90vw",e.style.maxHeight="90vh";break;case"fill":e.style.width="90vw",e.style.height="90vh",e.style.maxWidth="90vw",e.style.maxHeight="90vh"}}}var Vt=Object.freeze({__proto__:null,TriggerManager:Kt});class qt{constructor(e={}){var t,i,n,o;this.widgets=new Map,this.widgetConfigs=new Map,this.compositionData=new Map,this.triggerManagers=new Map,this.compositionSubscriptions=new Map,this.compositionWidgets=new Map,this.eventListeners=new Map,this.errorHandlers=new Set,this.isInitialized=!1,this.responsiveState=null,this.config=Object.assign(Object.assign({},e),{security:Object.assign({enableSanitization:!0,enableRateLimit:!0,enableBotDetection:!0},e.security)}),this.apiConfig=new J(Object.assign(Object.assign({basePath:this.config.apiBaseUrl||("undefined"!=typeof window?window.location.origin:"http://localhost:3000")},this.config.apiKey&&{apiKey:this.config.apiKey}),this.config.accessToken&&{accessToken:this.config.accessToken})),this.widgetsApi=new ee(this.apiConfig),this.compositionsApi=new Z(this.apiConfig),this.securityManager=H.getInstance(this.config.security||{}),this.displayManager=new re,this.performanceMonitor=B(),(null===(t=e.realtime)||void 0===t?void 0:t.enabled)&&(this.realtimeManager=yt(e.realtime)),this.setupResponsiveTracking(),this.setupEventListeners(),l.info("[WidgetManager] Initialized with config:",{realtimeEnabled:!!(null===(i=e.realtime)||void 0===i?void 0:i.enabled),securityEnabled:!!(null===(n=e.security)||void 0===n?void 0:n.enableSanitization),performanceEnabled:!!(null===(o=e.performance)||void 0===o?void 0:o.enabled)})}static getInstance(e){return qt.instance||(qt.instance=new qt(e)),qt.instance}initialize(){return r(this,void 0,void 0,(function*(){if(this.isInitialized)l.warn("[WidgetManager] Already initialized");else try{this.realtimeManager&&(yield this.realtimeManager.initialize(),l.info("[WidgetManager] Real-time manager initialized")),this.setupResponsiveTracking(),this.isInitialized=!0,this.emitEvent({type:"manager_initialized",widgetId:"system",timestamp:Date.now()}),l.info("[WidgetManager] Successfully initialized")}catch(e){throw l.error("[WidgetManager] Initialization failed:",e),this.emitError({code:"INIT_FAILED",message:"Widget manager initialization failed",widgetId:"system",timestamp:Date.now(),details:{error:e instanceof Error?e.message:"Unknown error"}}),e}}))}registerWidget(e,t,i){return r(this,void 0,void 0,(function*(){try{const n=yield this.validateWidgetConfig(t);if(!n.allowed)throw new Error(`Widget validation failed: ${n.reason}`);const o={id:e,config:t,element:i,state:{ready:!1,error:null,width:t.width,height:t.height},displayState:{mode:t.displayMode,isFullscreen:!1,isOverlay:!1,isPopup:!1},updateHandlers:new Map,lastUpdate:Date.now()},s=this.displayManager.initializeWidget(e,t,i);if(o.displayState=s,t.triggers)try{const n=new Kt({widgetId:e,element:i,config:t.triggers});this.triggerManagers.set(e,n),l.debug("[WidgetManager] Trigger manager setup completed:",{widgetId:e,triggers:t.triggers})}catch(t){l.warn("[WidgetManager] Failed to setup trigger manager:",{widgetId:e,error:t instanceof Error?t.message:"Unknown error"})}return this.realtimeManager&&t.compositionId&&(yield this.setupRealtimeUpdates(o)),this.widgets.set(e,o),this.widgetConfigs.set(e,t),o.state.ready=!0,l.info("[WidgetManager] Widget registered:",{widgetId:e,compositionId:t.compositionId,realtimeEnabled:!!o.realtimeSubscription}),this.emitEvent({type:"widget_registered",widgetId:e,data:{config:t},timestamp:Date.now()}),o}catch(t){throw l.error("[WidgetManager] Widget registration failed:",t),this.emitError({code:"REGISTRATION_FAILED",message:"Widget registration failed",widgetId:e,timestamp:Date.now(),details:{error:t instanceof Error?t.message:"Unknown error"}}),t}}))}setupRealtimeUpdates(e){return r(this,void 0,void 0,(function*(){if(this.realtimeManager&&e.config.compositionId)try{const t=e.config.compositionId;if(this.compositionWidgets.has(t)||this.compositionWidgets.set(t,new Set),this.compositionWidgets.get(t).add(e.id),this.compositionSubscriptions.has(t))l.info("[WidgetManager] Using existing real-time subscription for composition:",{compositionId:t,widgetCount:this.compositionWidgets.get(t).size});else{const e=e=>r(this,void 0,void 0,(function*(){yield this.handleCompositionUpdate(t,e)})),i=this.realtimeManager.subscribe(t,e);this.compositionSubscriptions.set(t,i),l.info("[WidgetManager] Real-time subscription created for composition:",{compositionId:t,subscriptionId:i.id,widgetCount:this.compositionWidgets.get(t).size})}e.realtimeSubscription=this.compositionSubscriptions.get(t)}catch(e){throw l.error("[WidgetManager] Failed to setup real-time updates:",e),e}}))}handleCompositionUpdate(e,t){return r(this,void 0,void 0,(function*(){var i,n;try{l.debug("[WidgetManager] Processing composition update:",{compositionId:e,updateType:t.type,timestamp:t.timestamp,affectedWidgets:(null===(i=this.compositionWidgets.get(e))||void 0===i?void 0:i.size)||0});const o=this.compositionWidgets.get(e);if(!o||0===o.size)return void l.warn("[WidgetManager] No widgets found for composition:",e);const s=[];for(const e of o){const i=this.widgets.get(e);i&&s.push(this.handleWidgetUpdate(i,t))}if(yield Promise.allSettled(s),"content"===t.type||"data"===t.type){const i=this.compositionData.get(e),n={id:e,widgetId:e,content:"content"===t.type?t.data:(null==i?void 0:i.content)||{},theme:(null==i?void 0:i.theme)||{},version:t.version||"1.0.0"};"data"===t.type&&(null==i?void 0:i.content)&&(n.content=Object.assign(Object.assign({},i.content),t.data)),this.compositionData.set(e,n)}this.emitEvent({type:"composition_updated",widgetId:e,data:{compositionId:e,updateType:t.type,updateData:t.data,timestamp:t.timestamp,affectedWidgets:Array.from(o)},timestamp:Date.now()}),null===(n=this.performanceMonitor)||void 0===n||n.recordCustomMetric("composition_updates_applied",1)}catch(i){l.error("[WidgetManager] Composition update failed:",i),this.emitError({code:"COMPOSITION_UPDATE_FAILED",message:"Composition update processing failed",widgetId:e,timestamp:Date.now(),details:{compositionId:e,updateType:t.type,error:i instanceof Error?i.message:"Unknown error"}})}}))}handleWidgetUpdate(e,t){return r(this,void 0,void 0,(function*(){try{switch(e.lastUpdate=Date.now(),t.type){case"content":yield this.handleContentUpdate(e,t);break;case"style":yield this.handleStyleUpdate(e,t);break;case"config":yield this.handleConfigUpdate(e,t);break;case"data":yield this.handleDataUpdate(e,t);break;default:l.warn("[WidgetManager] Unknown update type:",t.type)}this.emitEvent({type:"widget_updated",widgetId:e.id,data:{compositionId:e.config.compositionId,updateType:t.type,updateData:t.data,timestamp:t.timestamp},timestamp:Date.now()})}catch(i){l.error("[WidgetManager] Widget update failed:",i),this.emitError({code:"WIDGET_UPDATE_FAILED",message:"Widget update processing failed",widgetId:e.id,timestamp:Date.now(),details:{compositionId:e.config.compositionId,updateType:t.type,error:i instanceof Error?i.message:"Unknown error"}})}}))}handleContentUpdate(e,t){return r(this,void 0,void 0,(function*(){var i;if(e.config.compositionId){const i=this.compositionData.get(e.config.compositionId),n={id:e.config.compositionId,widgetId:e.config.compositionId,content:t.data,theme:(null==i?void 0:i.theme)||{},version:t.version||(null==i?void 0:i.version)||"1.0.0"};this.compositionData.set(e.config.compositionId,n)}yield this.applyContentToWidget(e,t.data);const n=null===(i=e.updateHandlers)||void 0===i?void 0:i.get("content");n&&(yield n(t.data))}))}handleStyleUpdate(e,t){return r(this,void 0,void 0,(function*(){var i;yield this.applyStylesToWidget(e,t.data);const n=null===(i=e.updateHandlers)||void 0===i?void 0:i.get("style");n&&(yield n(t.data))}))}handleConfigUpdate(e,t){return r(this,void 0,void 0,(function*(){var i;const n=Object.assign(Object.assign({},e.config),t.data),o=yield this.validateWidgetConfig(n);if(!o.allowed)throw new Error(`Config update validation failed: ${o.reason}`);if(e.config=n,this.widgetConfigs.set(e.id,n),t.data.displayMode||t.data.resize||t.data.width||t.data.height)try{this.displayManager.cleanup(e.id);const t=this.displayManager.initializeWidget(e.id,n,e.element);e.displayState=t,l.debug("[WidgetManager] Display management updated:",{widgetId:e.id,displayMode:n.displayMode})}catch(t){l.warn("[WidgetManager] Failed to update display management:",{widgetId:e.id,error:t instanceof Error?t.message:"Unknown error"})}const s=null===(i=e.updateHandlers)||void 0===i?void 0:i.get("config");s&&(yield s(t.data))}))}handleDataUpdate(e,t){return r(this,void 0,void 0,(function*(){var i;const n=null===(i=e.updateHandlers)||void 0===i?void 0:i.get("data");n?yield n(t.data):yield this.applyContentToWidget(e,t.data)}))}applyContentToWidget(e,t){return r(this,void 0,void 0,(function*(){try{if("string"==typeof t)if("iframe"===e.element.tagName.toLowerCase()){const i=e.element;i.contentWindow&&i.contentWindow.postMessage({type:"widgetic_content_update",content:t},f.CLIENT_URL||"*")}else{const i=yield this.sanitizeContent(t,e.id);e.element.innerHTML=i}else if("object"==typeof t)if("iframe"===e.element.tagName.toLowerCase()){const i=e.element;i.contentWindow&&i.contentWindow.postMessage({type:"widgetic_data_update",data:t},f.CLIENT_URL||"*")}else e.element.dispatchEvent(new CustomEvent("widgetic:data-update",{detail:t}));l.debug("[WidgetManager] Content applied to widget:",{widgetId:e.id,contentType:typeof t})}catch(e){throw l.error("[WidgetManager] Failed to apply content:",e),e}}))}applyStylesToWidget(e,t){return r(this,void 0,void 0,(function*(){try{"object"==typeof t?Object.entries(t).forEach((([t,i])=>{"string"!=typeof i&&"number"!=typeof i||(e.element.style[t]=i)})):"string"==typeof t&&(e.element.style.cssText+=t),l.debug("[WidgetManager] Styles applied to widget:",{widgetId:e.id,stylesType:typeof t})}catch(e){throw l.error("[WidgetManager] Failed to apply styles:",e),e}}))}sanitizeContent(e,t){return r(this,void 0,void 0,(function*(){const i=this.securityManager.validateTextFieldUpdate(t,"content",e);if(!i.allowed)throw new Error(`Content blocked by security: ${i.reason}`);return i.sanitizedText||e}))}validateWidgetConfig(e){return r(this,void 0,void 0,(function*(){var t;if(!e.compositionId)return{allowed:!1,reason:"Missing composition ID",severity:"high"};if(null===(t=this.config.security)||void 0===t?void 0:t.enableSanitization){const t=JSON.stringify(e),i=this.securityManager.validateTextFieldUpdate(e.compositionId,"config",t);if(!i.allowed)return{allowed:!1,reason:i.reason,severity:i.severity||"medium"}}return{allowed:!0}}))}setContent(e,t){return r(this,arguments,void 0,(function*(e,t,i={}){var n;try{l.debug("[WidgetManager] Setting dynamic content:",{compositionId:e,contentType:typeof t,options:i});const o={content:t};void 0!==i.validate&&(o.validate=i.validate),void 0!==i.partial&&(o.partial=i.partial),void 0!==i.version&&(o.version=i.version),void 0!==i.source&&(o.source=i.source);const s=yield this.compositionsApi.setDynamicContent({id:e,setDynamicContentRequest:ie(o)}),a=this.getWidgetsByComposition(e),d=this.compositionData.get(e);let c=t;i.partial&&(null==d?void 0:d.content)&&(c=this.mergeContent(d.content,t));const h={id:e,widgetId:e,content:c,theme:(null==d?void 0:d.theme)||{},version:i.version||(null==d?void 0:d.version)||"1.0.0"};this.compositionData.set(e,h);const u=a.map((t=>r(this,void 0,void 0,(function*(){var n;try{yield this.applyContentToWidget(t,c);const o=null===(n=t.updateHandlers)||void 0===n?void 0:n.get("content");o&&(yield o(c)),t.lastUpdate=Date.now(),l.debug("[WidgetManager] Content applied to widget:",{widgetId:t.id,compositionId:e,source:i.source})}catch(e){throw l.error("[WidgetManager] Failed to update widget content:",{widgetId:t.id,error:e instanceof Error?e.message:"Unknown error"}),e}}))));return yield Promise.all(u),this.emitEvent({type:"content_updated",widgetId:e,data:{content:c,source:i.source,version:i.version,partial:i.partial},timestamp:Date.now()}),l.info("[WidgetManager] Content updated successfully via API:",{compositionId:e,widgetCount:a.length,source:i.source,realtimeUpdateSent:s.realtimeUpdateSent}),{success:null!==(n=s.success)&&void 0!==n&&n,validationResult:s.validationResult}}catch(t){const n=t instanceof Error?t.message:"Unknown error";return this.emitError({code:"CONTENT_UPDATE_FAILED",message:`Failed to set content: ${n}`,widgetId:e,timestamp:Date.now(),details:{error:n,options:i}}),{success:!1,error:n}}}))}getContentSchema(e){return r(this,void 0,void 0,(function*(){try{l.debug("[WidgetManager] Getting widget content schema:",{widgetId:e});const t=yield this.widgetsApi.getWidgetContentSchema({id:e});return l.debug("[WidgetManager] Content schema retrieved:",{widgetId:e,schema:t}),t}catch(t){throw l.error("[WidgetManager] Failed to get content schema:",t),this.emitError({code:"SCHEMA_FETCH_FAILED",message:`Failed to get content schema: ${t instanceof Error?t.message:"Unknown error"}`,widgetId:e,timestamp:Date.now()}),t}}))}getDesignSchema(e){return r(this,void 0,void 0,(function*(){try{l.debug("[WidgetManager] Getting widget design schema:",{widgetId:e});const t=yield this.widgetsApi.getWidgetDesignSchema({id:e});return l.debug("[WidgetManager] Design schema retrieved:",{widgetId:e,schema:t}),t}catch(t){throw l.error("[WidgetManager] Failed to get design schema:",t),this.emitError({code:"SCHEMA_FETCH_FAILED",message:`Failed to get design schema: ${t instanceof Error?t.message:"Unknown error"}`,widgetId:e,timestamp:Date.now()}),t}}))}validateContent(e,t){return r(this,void 0,void 0,(function*(){var i,n;try{l.debug("[WidgetManager] Validating content:",{compositionId:e});const o=yield this.compositionsApi.validateCompositionContent({id:e,body:ie(t)});return l.debug("[WidgetManager] Content validation completed:",{compositionId:e,valid:null!==(i=o.valid)&&void 0!==i&&i}),{valid:null!==(n=o.valid)&&void 0!==n&&n,errors:o.errors,warnings:o.warnings,sanitizedContent:o.sanitizedContent}}catch(e){throw l.error("[WidgetManager] Content validation failed:",e),e}}))}getContent(e){const t=this.compositionData.get(e);return(null==t?void 0:t.content)||null}mergeContent(e,t){if(!e||"object"!=typeof e)return t;if(!t||"object"!=typeof t)return e;const i=Object.assign({},e);for(const[e,n]of Object.entries(t))n&&"object"==typeof n&&!Array.isArray(n)?i[e]=this.mergeContent(i[e],n):i[e]=n;return i}registerUpdateHandler(e,t,i){const n=this.widgets.get(e);if(!n)throw new Error(`Widget not found: ${e}`);n.updateHandlers||(n.updateHandlers=new Map),n.updateHandlers.set(t,i),l.info("[WidgetManager] Update handler registered:",{widgetId:e,updateType:t})}unregisterWidget(e){return r(this,void 0,void 0,(function*(){var t,i;const n=this.widgets.get(e);if(n)try{const o=n.config.compositionId;if(o&&this.compositionWidgets.has(o)&&(this.compositionWidgets.get(o).delete(e),0===this.compositionWidgets.get(o).size)){const e=this.compositionSubscriptions.get(o);e&&(null===(t=this.realtimeManager)||void 0===t||t.unsubscribe(e),this.compositionSubscriptions.delete(o),this.compositionWidgets.delete(o),l.info("[WidgetManager] Cleaned up composition subscription:",{compositionId:o,subscriptionId:e.id}))}try{this.displayManager.cleanup(e),l.debug("[WidgetManager] Display management cleaned up:",{widgetId:e})}catch(t){l.warn("[WidgetManager] Failed to cleanup display management:",{widgetId:e,error:t instanceof Error?t.message:"Unknown error"})}const s=this.triggerManagers.get(e);if(s)try{s.destroy(),this.triggerManagers.delete(e),l.debug("[WidgetManager] Trigger manager cleaned up:",{widgetId:e})}catch(t){l.warn("[WidgetManager] Failed to cleanup trigger manager:",{widgetId:e,error:t instanceof Error?t.message:"Unknown error"})}this.widgets.delete(e),this.widgetConfigs.delete(e),l.info("[WidgetManager] Widget unregistered:",{widgetId:e,compositionId:o,remainingWidgetsForComposition:(null===(i=this.compositionWidgets.get(o||""))||void 0===i?void 0:i.size)||0}),this.emitEvent({type:"widget_unregistered",widgetId:e,data:{compositionId:o},timestamp:Date.now()})}catch(t){l.error("[WidgetManager] Widget unregistration failed:",t),this.emitError({code:"UNREGISTRATION_FAILED",message:"Widget unregistration failed",widgetId:e,timestamp:Date.now(),details:{error:t instanceof Error?t.message:"Unknown error"}})}else l.warn("[WidgetManager] Widget not found for unregistration:",e)}))}getWidget(e){return this.widgets.get(e)}getAllWidgets(){return Array.from(this.widgets.values())}getWidgetsByComposition(e){const t=this.compositionWidgets.get(e);return t?Array.from(t).map((e=>this.widgets.get(e))).filter((e=>void 0!==e)):[]}setupResponsiveTracking(){if("undefined"==typeof window)return;const e=()=>{const e={mode:"mobile"===je().getDeviceType()?"mobile":"desktop",breakpoint:768,width:window.innerWidth,timestamp:Date.now()};this.responsiveState&&this.responsiveState.mode===e.mode||(this.responsiveState=e,this.emitEvent({type:"responsive_change",widgetId:"system",data:e,timestamp:Date.now()}),this.handleResponsiveChange(e))};let t;e(),window.addEventListener("resize",(()=>{clearTimeout(t),t=setTimeout(e,250)}))}handleResponsiveChange(e){for(const t of this.widgets.values())try{const i=this.widgetConfigs.get(t.id);if(i&&t.displayState){this.displayManager.cleanup(t.id);const n=this.displayManager.initializeWidget(t.id,i,t.element);t.displayState=n,l.debug("[WidgetManager] Responsive update applied:",{widgetId:t.id,mode:e.mode,width:e.width})}this.emitEvent({type:"widget_responsive_change",widgetId:t.id,data:e,timestamp:Date.now()})}catch(e){l.error("[WidgetManager] Responsive change handling failed for widget:",{widgetId:t.id,error:e})}}addEventListener(e,t){this.eventListeners.has(e)||this.eventListeners.set(e,new Set),this.eventListeners.get(e).add(t)}removeEventListener(e,t){const i=this.eventListeners.get(e);i&&i.delete(t)}addErrorHandler(e){this.errorHandlers.add(e)}removeErrorHandler(e){this.errorHandlers.delete(e)}emitEvent(e){const t=this.eventListeners.get(e.type);t&&t.forEach((t=>{try{t(e)}catch(e){l.error("[WidgetManager] Event handler failed:",e)}}))}emitError(e){this.errorHandlers.forEach((t=>{try{t(e)}catch(e){l.error("[WidgetManager] Error handler failed:",e)}}))}setupEventListeners(){"undefined"!=typeof window&&(this.realtimeManager&&(document.addEventListener("widgetic:realtime:connected",(()=>{this.emitEvent({type:"realtime_connected",widgetId:"system",timestamp:Date.now()})})),document.addEventListener("widgetic:realtime:disconnected",(()=>{this.emitEvent({type:"realtime_disconnected",widgetId:"system",timestamp:Date.now()})})),document.addEventListener("widgetic:realtime:error",(e=>{this.emitError({code:"REALTIME_ERROR",message:"Real-time connection error",widgetId:"system",timestamp:Date.now(),details:e.detail})}))),document.addEventListener("visibilitychange",(()=>{const e=!document.hidden;this.emitEvent({type:"page_visibility_change",widgetId:"system",data:{visible:e},timestamp:Date.now()})})))}getTriggerManager(e){return this.triggerManagers.get(e)}getAllTriggerManagers(){return new Map(this.triggerManagers)}getStats(){return{widgets:this.widgets.size,compositions:this.compositionWidgets.size,compositionSubscriptions:this.compositionSubscriptions.size,triggerManagers:this.triggerManagers.size,responsiveState:this.responsiveState,isInitialized:this.isInitialized}}destroy(){return r(this,void 0,void 0,(function*(){l.info("[WidgetManager] Destroying widget manager");const e=Array.from(this.widgets.keys());yield Promise.allSettled(e.map((e=>this.unregisterWidget(e))));for(const[e,t]of this.triggerManagers)try{t.destroy(),l.debug("[WidgetManager] Trigger manager destroyed:",{widgetId:e})}catch(t){l.warn("[WidgetManager] Failed to destroy trigger manager:",{widgetId:e,error:t instanceof Error?t.message:"Unknown error"})}this.triggerManagers.clear();try{this.displayManager.cleanupAll(),l.debug("[WidgetManager] Display manager cleaned up")}catch(e){l.warn("[WidgetManager] Failed to cleanup display manager:",{error:e instanceof Error?e.message:"Unknown error"})}this.realtimeManager&&this.realtimeManager.disconnect(),this.eventListeners.clear(),this.errorHandlers.clear(),this.compositionSubscriptions.clear(),this.compositionWidgets.clear(),this.compositionData.clear(),this.isInitialized=!1,this.responsiveState=null,qt.instance=null,l.info("[WidgetManager] Widget manager destroyed")}))}getActiveCompositions(){return Array.from(this.compositionWidgets.keys()).filter((e=>this.compositionWidgets.get(e).size>0))}getCompositionData(e){return this.compositionData.get(e)}}function Yt(e){return qt.getInstance(e)}qt.instance=null;var Qt=Object.freeze({__proto__:null,WidgetManager:qt,getWidgetManager:Yt});let Gt=!1;class Jt{constructor(t={}){var i,n,o,s,r,a,d,c,h,u,g,p,v,f,I,T,S,k,E,M,C;this.version=m,this.instances=new Map,this.isInitialized=!1,this.renderer=e(),this.widgetControllers=new Map,this.authDetector=ne(),this.editorOverlay=oe(),this.displayManager=ae(),this.resizeHandler=de(),this.authenticationStatus=null,this.overlayManager=null,this.hostObserverStarted=!1,this.config=Object.assign({renderMode:"auto",performance:{enabled:!1,config:{}},lazyLoading:{enabled:!0,config:{}}},t),this.browserCapabilities=U(),this.messenger=Q(this.config.messagingOptions);const D=this.config.logLevel||(this.config.debug?"debug":"info");if(l.setLevel(D),b.enabled&&l.info("Initializing EmbedSDK",{version:m,config:this.config,browserCapabilities:this.browserCapabilities}),"updateConfig"in this.displayManager&&"function"==typeof this.displayManager.updateConfig&&this.displayManager.updateConfig(this.config.displayOptions||{}),"updateConfig"in this.resizeHandler&&"function"==typeof this.resizeHandler.updateConfig&&this.resizeHandler.updateConfig(this.config.resizeOptions||{}),!1!==(null===(i=this.config.performance)||void 0===i?void 0:i.enabled)){const e=Object.assign({enableTracking:y.ENABLE_PERFORMANCE_TRACKING,axiomApiKey:y.AXIOM_API_KEY,axiomDataset:y.AXIOM_DATASET,axiomApiEndpoint:y.AXIOM_API_ENDPOINT,statsigKey:y.STATSIG_API_KEY,statsigApiEndpoint:y.STATSIG_API_ENDPOINT},null===(n=this.config.performance)||void 0===n?void 0:n.config);N(e)}!1!==(null===(o=this.config.lazyLoading)||void 0===o?void 0:o.enabled)&&K((null===(s=this.config.lazyLoading)||void 0===s?void 0:s.config)||{}),void 0!==this.config.debug&&(w.setDebug(this.config.debug),this.config.debug&&w.setLevel("debug")),!1!==(null===(r=this.config.resourceOptimization)||void 0===r?void 0:r.enabled)&&V((null===(a=this.config.resourceOptimization)||void 0===a?void 0:a.config)||{}),this.config.editorOptions&&(this.editorOverlay=oe(this.config.editorOptions)),!1!==(null===(d=this.config.overlayConfig)||void 0===d?void 0:d.enabled)&&(this.overlayManager=ce({enabled:!0,defaultMode:null===(c=this.config.overlayConfig)||void 0===c?void 0:c.defaultMode,exitIntentEnabled:null===(h=this.config.overlayConfig)||void 0===h?void 0:h.exitIntentEnabled,scrollTriggerEnabled:null===(u=this.config.overlayConfig)||void 0===u?void 0:u.scrollTriggerEnabled,timeTriggerEnabled:null===(g=this.config.overlayConfig)||void 0===g?void 0:g.timeTriggerEnabled,engagementThresholdEnabled:null===(p=this.config.overlayConfig)||void 0===p?void 0:p.engagementThresholdEnabled,externalTriggerEnabled:null===(v=this.config.overlayConfig)||void 0===v?void 0:v.externalTriggerEnabled,breakpoints:{useBreakpoints:(null===(I=null===(f=this.config.overlayConfig)||void 0===f?void 0:f.breakpoints)||void 0===I?void 0:I.useBreakpoints)||!1,mobile:(null===(S=null===(T=this.config.overlayConfig)||void 0===T?void 0:T.breakpoints)||void 0===S?void 0:S.mobile)||480,tablet:(null===(E=null===(k=this.config.overlayConfig)||void 0===k?void 0:k.breakpoints)||void 0===E?void 0:E.tablet)||768,desktop:(null===(C=null===(M=this.config.overlayConfig)||void 0===M?void 0:M.breakpoints)||void 0===C?void 0:C.desktop)||1024}})),l.info("Widgetic Embed SDK v1.0 initialized",{version:m,capabilities:this.browserCapabilities,editingEnabled:!1!==this.config.enableEditing,overlayEnabled:null!==this.overlayManager}),this.config.debug&&l.info("EmbedSDK initialized in debug mode",{config:this.config})}init(){return r(this,void 0,void 0,(function*(){var e,t;if(this.watchPublishedHosts(),yield this.scanPage(),this.isInitialized)l.warn("SDK already initialized");else if(Gt||"undefined"!=typeof window&&window.__WIDGETIC_SDK_INITIALIZED__)l.warn("SDK initialization detected, skipping duplicate setup");else try{if(this.isInitialized=!0,Gt=!0,"undefined"!=typeof window&&(window.__WIDGETIC_SDK_INITIALIZED__=!0),!1!==this.config.enableEditing&&this.checkAuthentication().catch((e=>{l.warn("Background authentication check failed",{error:e})})),this.config.preloadUISDK&&(null===(e=this.authenticationStatus)||void 0===e?void 0:e.isAuthenticated))try{const e=se();yield e.preload(),l.info("UI SDK preloaded successfully")}catch(e){l.warn("Failed to preload UI SDK",{error:e})}yield this.scanPage(),l.info("Widgetic Embed SDK initialized successfully",{version:m,capabilities:this.browserCapabilities,authenticationStatus:null===(t=this.authenticationStatus)||void 0===t?void 0:t.isAuthenticated}),yield this.scanPage()}catch(e){throw l.error("SDK initialization failed",{error:e}),e}}))}checkAuthentication(){return r(this,void 0,void 0,(function*(){var e;try{this.authenticationStatus=yield this.authDetector.checkAuthentication(),this.authenticationStatus.isAuthenticated?l.info("User authenticated for editing",{userId:null===(e=this.authenticationStatus.user)||void 0===e?void 0:e.id}):l.debug("User not authenticated for editing")}catch(e){l.debug("Authentication check failed",{error:e}),this.authenticationStatus={isAuthenticated:!1,canEdit:!1}}}))}enhance(){return r(this,void 0,void 0,(function*(){yield this.scanPage()}))}refresh(){return r(this,void 0,void 0,(function*(){l.info("Refreshing widgets"),yield this.scanPage()}))}watchPublishedHosts(){kt(),this.hostObserverStarted||"undefined"!=typeof MutationObserver&&"undefined"!=typeof document&&(this.hostObserverStarted=!0,new MutationObserver((()=>{kt()})).observe(document.documentElement,{childList:!0,subtree:!0}))}scanPage(){return r(this,void 0,void 0,(function*(){var e,t,i,n;const o=document.querySelectorAll("widgetic");if(l.debug("Found widgetic host elements",{count:o.length}),0===o.length)return void l.info("No widgets found on page");const s=[];for(const r of Array.from(o))if(P(r)&&r instanceof HTMLElement){if(St(r))continue;try{const o=E(r),a=null===(t=null===(e=o.device)||void 0===e?void 0:e.mobileEnabled)||void 0===t||t;if(!$e(a,null===(n=null===(i=o.device)||void 0===i?void 0:i.desktopEnabled)||void 0===n||n)){l.debug("Widget skipped due to device restrictions",{compositionId:o.compositionId,deviceRestrictions:o.device,element:r.outerHTML.substring(0,100)+"..."}),r.style.display="none",r.setAttribute("data-device-restricted","true");continue}s.push({element:r,config:o})}catch(e){l.error("Failed to parse widget configuration",{element:r.outerHTML,error:e})}}0!==s.length?yield this.renderWidgetsBatch(s):l.warn("No valid widget configurations found")}))}renderWidgetsBatch(e){return r(this,void 0,void 0,(function*(){try{const t=[],i=e.map((({element:e,config:i})=>{let n=e;if(e.parentNode){const t=document.createElement("div");t.className=`widgetic-host ${e.className}`.trim(),e.getAttribute("style")&&(t.style.cssText=e.getAttribute("style")||""),e.parentNode.replaceChild(t,e),n=t}return t.push(n),{compositionId:i.compositionId,renderMode:_(i.renderMode,this.browserCapabilities),width:i.width,height:i.height,resize:i.resize,autoscale:i.autoscale,adaptive:i.adaptive,container:n}})),n=yield this.renderer.renderWidgets(i);for(let i=0;i<n.length;i++){const o=n[i],{config:s}=e[i],r=t[i],a=z(s.compositionId),d=this.displayManager.initializeWidget(a,s,o.element);o.element instanceof HTMLElement&&r instanceof HTMLElement&&this.resizeHandler.registerWidget(a,o.element,r.parentElement||r,s);const c={id:a,config:s,element:o.element,displayState:d,state:{ready:!0,error:null,width:"number"==typeof s.width?s.width:parseInt(String(s.width)),height:"number"==typeof s.height?s.height:parseInt(String(s.height))},enterFullscreen:()=>this.displayManager.enterFullscreen(a),exitFullscreen:()=>this.displayManager.exitFullscreen(a),showOverlay:()=>this.displayManager.showOverlay(a),hideOverlay:()=>this.displayManager.hideOverlay(a),openPopup:()=>this.displayManager.openPopup(a),closePopup:()=>this.displayManager.closePopup(a)};this.instances.set(c.id,c),yield this.maybeAddEditorOverlay(o.element,s.compositionId),l.debug("Widget rendered successfully",{instanceId:c.id,compositionId:s.compositionId,renderMode:o.renderMode,displayMode:s.displayMode})}l.info("Batch widget rendering complete",{rendered:n.length,total:e.length})}catch(t){l.error("Batch widget rendering failed",{error:t});for(const{element:t,config:i}of e)try{yield this.renderSingleWidget(t,i)}catch(e){l.error("Individual widget rendering failed",{compositionId:i.compositionId,error:e})}}}))}renderSingleWidget(e,t){return r(this,void 0,void 0,(function*(){try{performance.now(),B(),q();const i=Y();if(this.shouldUseLazyLoading(e,t))return void i.register(e,t.compositionId,(()=>r(this,void 0,void 0,(function*(){yield this.performActualWidgetRender(e,t)}))),{config:t,priority:this.getWidgetPriority(t),resourceUrls:this.getWidgetResourceUrls(t)});yield this.performActualWidgetRender(e,t)}catch(e){const i=B(),n=e instanceof Error?e.message:"Render failed";throw i.recordWidgetError(t.compositionId,n),i.endWidgetLoad(t.compositionId,!1),l.error("Widget rendering failed",{error:e,config:t}),e}}))}performActualWidgetRender(e,t){return r(this,void 0,void 0,(function*(){const i=performance.now(),n=B(),o=q();try{const s=this.getWidgetResourceUrls(t);if(s.length>0&&(yield o.loadResources(s,{type:"script",priority:"high",compositionId:t.compositionId})),!("render"in this.renderer)||"function"!=typeof this.renderer.render)throw new Error("Widget renderer does not support render method");{const{widgetElement:o,instance:s}=yield this.renderer.render(e,t);if(!o)throw new Error("Widget element not created");const r=performance.now()-i;n.recordWidgetRender(t.compositionId,r),n.endWidgetLoad(t.compositionId,!0),this.instances.set(s.id,s)}}catch(e){const i=B(),n=e instanceof Error?e.message:"Render failed";throw i.recordWidgetError(t.compositionId,n),i.endWidgetLoad(t.compositionId,!1),l.error("Widget rendering failed",{error:e,config:t}),e}}))}shouldUseLazyLoading(e,t){var i;if(!1===(null===(i=this.config.lazyLoading)||void 0===i?void 0:i.enabled))return!1;if("critical"===t.priority||!0===t.preload)return!1;const n=e.getBoundingClientRect();return!(n.top<window.innerHeight&&n.bottom>0)}getWidgetPriority(e){switch(e.priority){case"critical":return 10;case"high":return 7;case"medium":default:return 5;case"low":return 2}}getWidgetResourceUrls(e){const t=[];return e.scriptUrl&&t.push(e.scriptUrl),e.styleUrl&&t.push(e.styleUrl),e.resourceUrls&&Array.isArray(e.resourceUrls)&&t.push(...e.resourceUrls),t}maybeAddEditorOverlay(e,t){return r(this,void 0,void 0,(function*(){if(!1!==this.config.enableEditing)try{yield this.editorOverlay.addOverlay(e,t)}catch(e){l.debug("Failed to add editor overlay",{compositionId:t,error:e})}}))}getInstances(){return Array.from(this.instances.values())}getInstance(e){return this.instances.get(e)||null}getInstancesByComposition(e){return this.getInstances().filter((t=>t.config.compositionId===e))}getStats(){const e=this.renderer.getStats();return{version:m,widgetsRendered:this.instances.size,renderMode:"auto",cacheStats:e.batchCache,messagingActive:this.messenger.isActive(),customEventSubscriptions:this.messenger.getCustomEventSubscriptions(),functionHandlers:this.messenger.getFunctionHandlers(),authenticationStatus:this.authenticationStatus||void 0,editingSessions:this.editorOverlay.getActiveSessions().length}}createWidgetController(e){const t=Array.from(this.instances.values()).find((t=>t.config.compositionId===e));if(!t)return l.warn("Widget instance not found for controller creation",{compositionId:e}),null;const i=this.messenger.createWidgetController(t.id,e);return this.widgetControllers.set(e,i),l.info("Widget controller created",{compositionId:e,instanceId:t.id}),i}getWidgetController(e){return this.widgetControllers.get(e)||null}subscribeToWidget(e,t,i){let n=this.getWidgetController(e);if(!n&&(n=this.createWidgetController(e),!n))throw new Error(`Cannot create controller for widget: ${e}`);return n.subscribe(t,i)}callWidgetFunction(e,t,...i){return r(this,void 0,void 0,(function*(){let n=this.getWidgetController(e);if(!n&&(n=this.createWidgetController(e),!n))throw new Error(`Cannot create controller for widget: ${e}`);return n.callFunction(t,...i)}))}updateWidgetConfig(e,t){return r(this,void 0,void 0,(function*(){let i=this.getWidgetController(e);if(!i&&(i=this.createWidgetController(e),!i))throw new Error(`Cannot create controller for widget: ${e}`);return i.updateConfig(t)}))}getWidgetState(e,t){return r(this,void 0,void 0,(function*(){let i=this.getWidgetController(e);if(!i&&(i=this.createWidgetController(e),!i))throw new Error(`Cannot create controller for widget: ${e}`);return i.getState(t)}))}setWidgetState(e,t,i){return r(this,void 0,void 0,(function*(){let n=this.getWidgetController(e);if(!n&&(n=this.createWidgetController(e),!n))throw new Error(`Cannot create controller for widget: ${e}`);return n.setState(t,i)}))}emitToWidget(e,t,i,n){let o=this.getWidgetController(e);o||(o=this.createWidgetController(e),o)?o.emit(t,i,n):l.warn(`Cannot create controller for widget: ${e}`)}canEditComposition(e){return r(this,void 0,void 0,(function*(){return this.authDetector.canEditComposition(e)}))}getAuthenticationStatus(){return this.authenticationStatus}refreshAuthentication(){return r(this,void 0,void 0,(function*(){return yield this.checkAuthentication(),this.authenticationStatus}))}openEditor(e){return r(this,void 0,void 0,(function*(){if(!(yield this.canEditComposition(e)))throw new Error(`User cannot edit composition: ${e}`);yield this.editorOverlay.openEditor(e)}))}isEditorOpen(e){return this.editorOverlay.isEditorOpen(e)}closeEditor(e){return r(this,void 0,void 0,(function*(){yield this.editorOverlay.closeEditor(e)}))}setEditingEnabled(e){this.config.enableEditing=e,l.info("Editing mode changed",{enabled:e})}setContent(e,t){return r(this,arguments,void 0,(function*(e,t,i={}){try{const{getWidgetManager:n}=yield Promise.resolve().then((function(){return Qt})),o=n();return yield o.setContent(e,t,i)}catch(e){return l.error("[EmbedSDK] Failed to set content:",e),{success:!1,error:e instanceof Error?e.message:"Unknown error"}}}))}getContentSchema(e){return r(this,void 0,void 0,(function*(){try{const t=this.getInstancesByComposition(e)[0];if(!t)throw new Error("No widget instance found for composition");const{getWidgetManager:i}=yield Promise.resolve().then((function(){return Qt})),n=i();return yield n.getContentSchema(t.config.compositionId)}catch(e){throw l.error("[EmbedSDK] Failed to get content schema:",e),e}}))}getDesignSchema(e){return r(this,void 0,void 0,(function*(){try{const t=this.getInstancesByComposition(e)[0];if(!t)throw new Error("No widget instance found for composition");const{getWidgetManager:i}=yield Promise.resolve().then((function(){return Qt})),n=i();return yield n.getDesignSchema(t.config.compositionId)}catch(e){throw l.error("[EmbedSDK] Failed to get design schema:",e),e}}))}validateContent(e,t){return r(this,void 0,void 0,(function*(){try{const{getWidgetManager:i}=yield Promise.resolve().then((function(){return Qt})),n=i();return yield n.validateContent(e,t)}catch(e){throw l.error("[EmbedSDK] Failed to validate content:",e),e}}))}getContent(e){try{return Yt().getContent(e)}catch(e){return l.error("[EmbedSDK] Failed to get content:",e),null}}onContentUpdate(e,t){return this.subscribeToWidget(e,"content_updated",t)}scan(){return r(this,void 0,void 0,(function*(){if(!this.isInitialized)throw new Error("SDK not initialized. Call init() first.");try{const e=document.querySelectorAll("[data-widgetic]"),t=Array.from(e).map((e=>{const t=e.getAttribute("data-widgetic"),i=e.getAttribute("data-id");return t&&i?{id:t,dataId:i,element:e}:null})).filter(Boolean);return yield this.loadWidgets(t),{success:!0,widgets:t,errors:[]}}catch(e){return{success:!1,widgets:[],errors:[e instanceof Error?e.message:"Unknown error"]}}}))}loadWidgets(e){return r(this,void 0,void 0,(function*(){for(const t of e)try{yield this.loadWidget(t)}catch(e){}}))}loadWidget(e){return r(this,void 0,void 0,(function*(){yield new Promise((e=>setTimeout(e,100*Math.random())));const t=this.determineRenderMode();"iframe"===t?this.renderIframe(e):"custom-element"===t&&this.renderCustomElement(e)}))}determineRenderMode(){return"iframe"===this.config.renderMode?"iframe":"custom-element"===this.config.renderMode||"undefined"!=typeof customElements?"custom-element":"iframe"}renderIframe(e){const t=document.createElement("iframe");t.src=`https://widgetic.com/widget/${e.dataId}`,t.style.width=e.element.style.width||"400px",t.style.height=e.element.style.height||"300px",t.style.border="none",e.element.appendChild(t)}renderCustomElement(e){if("undefined"!=typeof customElements){customElements.get("widgetic-widget")||customElements.define("widgetic-widget",class extends HTMLElement{connectedCallback(){this.innerHTML=`<div>Widgetic Widget: ${this.getAttribute("data-widget-id")}</div>`}});const t=document.createElement("widgetic-widget");t.setAttribute("data-widget-id",e.dataId),e.element.appendChild(t)}}getConfig(){return Object.assign({},this.config)}showOverlay(e){this.overlayManager?this.overlayManager.showOverlay(e):l.warn("Overlay manager not initialized")}hideOverlay(){this.overlayManager?this.overlayManager.hideOverlay():l.warn("Overlay manager not initialized")}triggerOverlay(e,t={}){this.overlayManager?this.overlayManager.triggerOverlay(e,t):l.warn("Overlay manager not initialized")}isOverlayActive(){var e;return(null===(e=this.overlayManager)||void 0===e?void 0:e.isOverlayActive())||!1}destroy(){document.querySelectorAll("iframe").forEach((e=>e.remove()));document.querySelectorAll("widgetic-widget").forEach((e=>e.remove())),this.overlayManager&&(this.overlayManager.destroy(),this.overlayManager=null),this.isInitialized=!1}}let Xt=null;function Zt(e){return Xt||(Xt=new Jt(e)),Xt}"undefined"!=typeof document&&(kt(),"undefined"!=typeof MutationObserver&&new MutationObserver((()=>{kt()})).observe(document.documentElement,{childList:!0,subtree:!0}),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",(()=>{b.enabled&&l.info("DOM ready, auto-initializing SDK"),Zt().init().catch((e=>{l.error("Auto-initialization failed",{error:e})}))})):(b.enabled&&l.info("DOM already ready, auto-initializing SDK"),setTimeout((()=>{Zt().init().catch((e=>{l.error("Auto-initialization failed",{error:e})}))}),0)));var ei=Object.freeze({__proto__:null,EmbedSDK:Jt,getSDK:Zt});class ti{constructor(){this.debugMode=!1,this.trackedElements=new WeakSet}static getInstance(){return ti.instance||(ti.instance=new ti),ti.instance}enableDebugMode(){this.debugMode=!0,this.addDebugStyles(),l.info("CSS debugging mode enabled")}disableDebugMode(){this.debugMode=!1,this.removeDebugStyles(),l.info("CSS debugging mode disabled")}analyzeWidget(e){const t=e.getAttribute("data-widgetic-instance")||"unknown",i=[],n=[];this.detectCSSConflicts(e,i),this.checkStyleIsolation(e,n);const o={widgetId:t,conflicts:i,isolationScore:this.calculateIsolationScore(e,i),recommendations:n};return this.debugMode&&this.displayDebugReport(o),o}detectCSSConflicts(e,t){const i=window.getComputedStyle(e);["font-family","font-size","color","background-color","margin","padding","border","box-sizing"].forEach((n=>{const o=i.getPropertyValue(n);i.getPropertyPriority(n),this.isExternalStyle(e,n,o)&&t.push({property:n,widgetValue:this.getWidgetStyleValue(e,n),externalValue:o,specificity:this.calculateSpecificity(e,n),source:this.getStyleSource(e,n)})}))}checkStyleIsolation(e,t){e.getAttribute("data-widgetic-instance")||t.push("Add data-widgetic-instance attribute for proper namespace isolation");const i=window.getComputedStyle(e);Array.from(i).some((e=>e.startsWith("--widgetic-")))||t.push("Use CSS custom properties (--widgetic-*) for better theme isolation");const n=i.getPropertyValue("contain");n.includes("layout")&&n.includes("style")||t.push("Apply CSS containment (contain: layout style paint) for better isolation");"auto"===i.getPropertyValue("z-index")&&this.hasStackingContext(e)&&t.push("Consider explicit z-index management to prevent stacking conflicts")}calculateIsolationScore(e,t){let i=100;i-=10*t.length;const n=window.getComputedStyle(e),o=n.getPropertyValue("contain");o.includes("layout")||(i-=15),o.includes("style")||(i-=15),o.includes("paint")||(i-=10);"isolate"!==n.getPropertyValue("isolation")&&(i-=10);e.getAttribute("data-widgetic-instance")||(i-=15);return"border-box"!==n.getPropertyValue("box-sizing")&&(i-=5),Math.max(0,i)}isExternalStyle(e,t,i){const n=document.createElement(e.tagName.toLowerCase());n.style.cssText=e.getAttribute("style")||"",document.body.appendChild(n);const o=window.getComputedStyle(n).getPropertyValue(t);return document.body.removeChild(n),i!==o&&!this.isWidgetStyle(e,t)}isWidgetStyle(e,t){const i=e.getAttribute("data-widgetic-instance");if(!i)return!1;return this.getMatchingCSSRules(e).some((e=>{var n;return(null===(n=e.selectorText)||void 0===n?void 0:n.includes(`[data-widgetic-instance="${i}"]`))&&e.style.getPropertyValue(t)}))}getWidgetStyleValue(e,t){const i=e.getAttribute("data-widgetic-instance");if(!i)return"";const n=this.getMatchingCSSRules(e).find((e=>{var t;return null===(t=e.selectorText)||void 0===t?void 0:t.includes(`[data-widgetic-instance="${i}"]`)}));return(null==n?void 0:n.style.getPropertyValue(t))||""}calculateSpecificity(e,t){const i=this.getMatchingCSSRules(e).find((e=>e.style.getPropertyValue(t)));if(!i)return 0;const n=i.selectorText||"";let o=0;return o+=100*(n.match(/#/g)||[]).length,o+=10*(n.match(/[\.\[]/g)||[]).length,o+=(n.match(/[a-zA-Z]/g)||[]).length,o}getStyleSource(e,t){const i=this.getMatchingCSSRules(e).find((e=>e.style.getPropertyValue(t)));if(!i)return"unknown";if(i.parentStyleSheet){const e=i.parentStyleSheet;if(e.href)return e.href;if(e.ownerNode)return"inline styles"}return"unknown"}getMatchingCSSRules(e){const t=[];try{for(let i=0;i<document.styleSheets.length;i++){const n=document.styleSheets[i];try{const i=n.cssRules||n.rules;for(let n=0;n<i.length;n++){const o=i[n];o.selectorText&&e.matches(o.selectorText)&&t.push(o)}}catch(e){continue}}}catch(e){l.warn("Failed to analyze CSS rules",{error:e})}return t}hasStackingContext(e){const t=window.getComputedStyle(e),i=t.getPropertyValue("position"),n=t.getPropertyValue("z-index"),o=t.getPropertyValue("transform"),s=t.getPropertyValue("opacity");return"static"!==i&&"auto"!==n||"none"!==o||parseFloat(s)<1}addDebugStyles(){const e="widgetic-css-debug-styles";if(document.getElementById(e))return;const t=document.createElement("style");t.id=e,t.textContent='\n /* CSS Debug Mode Styles */\n widgetic-widget[data-widgetic-instance] {\n outline: 2px dashed #007bff !important;\n outline-offset: 2px !important;\n position: relative !important;\n }\n\n widgetic-widget[data-widgetic-instance]::before {\n content: "Widget: " attr(data-widgetic-instance) !important;\n position: absolute !important;\n top: -20px !important;\n left: 0 !important;\n background: #007bff !important;\n color: white !important;\n padding: 2px 6px !important;\n font-size: 10px !important;\n font-family: monospace !important;\n z-index: 10000 !important;\n pointer-events: none !important;\n }\n\n widgetic-widget[data-error="true"] {\n outline-color: #dc3545 !important;\n }\n\n widgetic-widget[data-loading="true"] {\n outline-color: #ffc107 !important;\n }\n\n widgetic-widget[data-ready="true"] {\n outline-color: #28a745 !important;\n }\n ',document.head.appendChild(t)}removeDebugStyles(){const e=document.getElementById("widgetic-css-debug-styles");e&&e.remove()}displayDebugReport(e){}monitorWidget(e){if(this.trackedElements.has(e))return;this.trackedElements.add(e);new MutationObserver((e=>{e.forEach((e=>{"attributes"!==e.type||"style"!==e.attributeName&&"class"!==e.attributeName||this.debugMode}))})).observe(e,{attributes:!0,attributeOldValue:!0,attributeFilter:["style","class"]})}}ti.instance=null;const ii=ti.getInstance();function ni(){ii.enableDebugMode()}function oi(){ii.disableDebugMode()}function si(e){return ii.analyzeWidget(e)}function ri(e){ii.monitorWidget(e)}const ai={WidgeticWidget:t,registerWidgeticWidget:i,getSDK:Zt,setApiKey:I,setTokenProvider:T,StaticApiKeyProvider:le,EndpointTokenProvider:he,FunctionTokenProvider:ue,getConfiguration:S},di={WidgetRenderer:n,getWidgetRenderer:e,CustomElementRenderer:o,IframeRenderer:s,AuthManager:me,detectBrowserCapabilities:U,determineBestRenderMode:_,parseWidgetConfig:E,generateInstanceId:z,isValidWidgetElement:P},ci={BatchApiClient:Ct,getBatchClient:At,ModuleLoader:Rt,getModuleLoader:Ut,WidgeticMessenger:G,getMessenger:Q,config:f,getApiUrl:h,getCdnUrl:v,getTokenProvider:k,getAuthToken:g,DefaultTokenProvider:ge,CSSDebugger:ti,cssDebugger:ii,enableCSSDebug:ni,disableCSSDebug:oi,log:l};export{me as A,Ct as B,ti as C,ge as D,Ee as E,ue as F,_t as G,ai as H,ei as I,ci as L,we as M,le as S,qt as W,Re as a,Pe as b,$t as c,_e as d,Ut as e,ve as f,At as g,fe as h,ye as i,je as j,Yt as k,Zt as l,Jt as m,ii as n,he as o,pe as p,Wt as q,Le as r,Rt as s,Pt as t,ni as u,oi as v,si as w,ri as x,di as y,Ot as z};
|