@widgetic/embed-sdk 2.1.1 → 2.1.3

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.
Files changed (31) hide show
  1. package/README.md +8 -6
  2. package/dist/browser/chunks/ABTestManager.js +1 -1
  3. package/dist/browser/chunks/advanced.js +1 -1
  4. package/dist/browser/chunks/api.js +1 -1
  5. package/dist/browser/chunks/core.js +1 -1
  6. package/dist/browser/chunks/renderers.js +1 -1
  7. package/dist/browser/embed-bootstrap.js +1 -1
  8. package/dist/browser/embed-sdk.js +1 -1
  9. package/dist/esm/chunks/ABTestManager.js +1 -1
  10. package/dist/esm/chunks/advanced.js +1 -1
  11. package/dist/esm/chunks/api.js +1 -1
  12. package/dist/esm/chunks/core.js +1 -1
  13. package/dist/esm/chunks/renderers.js +1 -1
  14. package/dist/esm/embed-bootstrap.js +1 -1
  15. package/dist/esm/embed-sdk.js +1 -1
  16. package/dist/esm/types/abTesting/ABTestElement.d.ts +57 -3
  17. package/dist/esm/types/abTesting/ABTestManager.d.ts +27 -0
  18. package/dist/esm/types/core/analytics-tracker.d.ts +6 -0
  19. package/dist/esm/types/core/auth-detector.d.ts +2 -0
  20. package/dist/esm/types/core/constants.d.ts +1 -1
  21. package/dist/esm/types/core/version.d.ts +1 -0
  22. package/dist/esm/types/translations/TranslationElement.d.ts +12 -0
  23. package/dist/esm/types/utils/editor-session-access.d.ts +15 -0
  24. package/dist/esm/types/utils/editor-session-response.d.ts +21 -0
  25. package/dist/esm/types/utils/gateway-request.d.ts +29 -0
  26. package/dist/esm/types/utils/mount-direct-widget.d.ts +23 -0
  27. package/dist/esm/types/utils/public-embed-lookup.d.ts +8 -2
  28. package/dist/esm/types/utils/published-host-bridge.d.ts +26 -5
  29. package/dist/umd/embed-bootstrap.js +1 -1
  30. package/dist/umd/embed-sdk.js +1 -1
  31. package/package.json +6 -4
@@ -1 +1 @@
1
- import{j as n,k as r,i as l,G as w,l as b,m as T,n as D,E as _}from"./chunks/api.js";export{B as BatchApiClient,C as CSSDebugger,H as HighLevelAPI,L as LowLevelAPI,M as MidLevelAPI,o as ModuleLoader,p as analyzeWidgetCSS,q as disableCSSDebug,t as enableCSSDebug,g as getBatchClient,a as getModuleLoader,u as monitorWidgetCSS,v as resetBatchClient,x as resetModuleLoader,y as sendWorkflowEvent}from"./chunks/api.js";import{l as R,g as O,C as W,V as N,u as z,e as P,t as Q,a as K,T as U,d as V}from"./chunks/core.js";export{v as AuthError,A as AuthManager,j as DefaultTokenProvider,E as EndpointTokenProvider,F as FunctionTokenProvider,S as StaticApiKeyProvider,m as getApiUrl,x as getAuthManager,c as getCdnUrl,h as getConfiguration,k as getTokenProvider,i as setApiKey,s as setTokenProvider}from"./chunks/core.js";import{e as $,W as G}from"./chunks/renderers.js";export{C as CustomElementRenderer,I as IframeRenderer,f as WidgetRenderer,g as getWidgetRenderer,i as resetWidgetRenderer}from"./chunks/renderers.js";export{WidgeticMessenger,getMessenger,resetMessenger}from"./chunks/messaging.js";import{ABTestManager as Y}from"./chunks/ABTestManager.js";import{_ as J}from"./chunks/vendor.js";import{k as X}from"./chunks/scanner.js";export{e as detectBrowserCapabilities,j as determineBestRenderMode,f as isValidWidgetElement,p as parseWidgetConfig}from"./chunks/scanner.js";export{d as toCamel,t as toSnake}from"./chunks/advanced.js";import"./chunks/media.js";import"./chunks/display.js";import"./chunks/performance.js";import"./chunks/security.js";class Z{constructor(e){this.deviceDetector=n(),this.privacyCompliance=null,this.eventQueue=[],this.batchTimer=null,this.isOnline=navigator.onLine,this.sessionStartTime=Date.now(),this.lastActivityTime=Date.now(),this.isSessionActive=!1,this.interactionCount=0,this.viewStartTime=Date.now(),this.STORAGE_KEY="widgetic_analytics_queue",this.SESSION_KEY="widgetic_session_id",this.config=Object.assign({batchSize:10,batchTimeout:5e3,maxRetries:3,rateLimitPerMinute:100,enableLocalStorage:!0,enableDeviceTracking:!0,enableInteractionTracking:!0,trackOnlyClicks:!0},e),this.sessionId=this.initializeSession(),this.rateLimitState={eventCounts:new Map,windowStart:Date.now(),windowDurationMs:6e4},this.setupEventListeners(),this.loadQueuedEvents(),R.debug("[AnalyticsTracker] Initialized",{compositionId:this.config.compositionId,sessionId:this.sessionId})}static getInstance(e){if(!Z.instance&&e&&(Z.instance=new Z(e)),!Z.instance)throw new Error("AnalyticsTracker must be initialized with config first");return Z.instance}initializeSession(){if(this.config.enableLocalStorage){const e=localStorage.getItem(this.SESSION_KEY);if(e)try{const t=JSON.parse(e);if(Date.now()-t.timestamp<18e5)return t.sessionId}catch(e){R.warn("[AnalyticsTracker] Failed to parse stored session",{error:e})}}const e=`sess_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;if(this.config.enableLocalStorage)try{localStorage.setItem(this.SESSION_KEY,JSON.stringify({sessionId:e,timestamp:Date.now()}))}catch(e){R.warn("[AnalyticsTracker] Failed to store session ID",{error:e})}return e}setPrivacyCompliance(e){this.privacyCompliance=e}isTrackingAllowed(){return!this.privacyCompliance||this.privacyCompliance.hasConsent("analytics")}setupEventListeners(){window.addEventListener("online",(()=>{this.isOnline=!0,this.processBatch()})),window.addEventListener("offline",(()=>{this.isOnline=!1})),["mousedown","mousemove","keypress","scroll","touchstart"].forEach((e=>{document.addEventListener(e,(()=>this.updateActivity()),{passive:!0})})),document.addEventListener("visibilitychange",(()=>{document.hidden?this.trackSessionEnd("visibility_hidden"):this.trackSessionStart()})),window.addEventListener("beforeunload",(()=>{this.trackSessionEnd("navigation"),this.flushEvents()}))}updateActivity(){this.lastActivityTime=Date.now(),this.isSessionActive||this.trackSessionStart()}isRateLimited(e){const t=Date.now();t-this.rateLimitState.windowStart>=this.rateLimitState.windowDurationMs&&(this.rateLimitState.eventCounts.clear(),this.rateLimitState.windowStart=t);const i=this.rateLimitState.eventCounts.get(e)||0;return i>=this.config.rateLimitPerMinute?(R.warn("[AnalyticsTracker] Rate limit exceeded",{eventType:e,currentCount:i}),!0):(this.rateLimitState.eventCounts.set(e,i+1),!1)}generateEventId(){return`evt_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}createBaseEvent(e,t={}){const i=this.config.enableDeviceTracking?this.deviceDetector.getDeviceInfo():void 0;return{id:this.generateEventId(),eventType:e,compositionId:this.config.compositionId,timestamp:Date.now(),sessionId:this.sessionId,data:t,deviceInfo:i,referrer:document.referrer||void 0,userAgent:navigator.userAgent,url:window.location.href}}queueEvent(e){this.isTrackingAllowed()?this.isRateLimited(e.eventType)||(this.eventQueue.push(e),this.config.enableLocalStorage&&this.saveQueueToStorage(),this.scheduleBatch(),R.debug("[AnalyticsTracker] Event queued",{eventType:e.eventType,queueSize:this.eventQueue.length})):R.debug("[AnalyticsTracker] Tracking not allowed, skipping event",{eventType:e.eventType})}scheduleBatch(){this.eventQueue.length>=this.config.batchSize?this.processBatch():this.batchTimer||(this.batchTimer=setTimeout((()=>{this.processBatch()}),this.config.batchTimeout))}processBatch(){return J(this,void 0,void 0,(function*(){if(this.batchTimer&&(clearTimeout(this.batchTimer),this.batchTimer=null),0===this.eventQueue.length||!this.isOnline)return;const e=this.eventQueue.splice(0,this.config.batchSize);try{yield this.sendEventBatch(e),this.config.enableLocalStorage&&this.saveQueueToStorage(),R.debug("[AnalyticsTracker] Batch sent successfully",{batchSize:e.length,remainingQueue:this.eventQueue.length})}catch(t){R.error("[AnalyticsTracker] Failed to send batch",{error:t,batchSize:e.length}),this.eventQueue.unshift(...e),setTimeout((()=>this.processBatch()),5e3)}}))}sendEventBatch(e){return J(this,void 0,void 0,(function*(){if(!this.config.apiEndpoint)return void R.warn("[AnalyticsTracker] No API endpoint configured");const t=e.map((e=>({composition_id:e.compositionId,event_type:e.eventType,event_data:e.data,user_id:e.userId,session_id:e.sessionId,user_agent:e.userAgent,referrer:e.referrer,ip_address:void 0}))),i=yield O(),n=new W({basePath:this.config.apiEndpoint,accessToken:()=>J(this,void 0,void 0,(function*(){return i})),headers:{"X-SDK-Version":`embed-sdk/${N}`}}),s=new z(n);yield s.analyticsEventsBulkPost({analyticsEventsBulkPostRequest:{events:t}})}))}saveQueueToStorage(){if(this.config.enableLocalStorage)try{const e={events:this.eventQueue,timestamp:Date.now()};localStorage.setItem(this.STORAGE_KEY,JSON.stringify(e))}catch(e){R.warn("[AnalyticsTracker] Failed to save queue to storage",{error:e})}}loadQueuedEvents(){if(this.config.enableLocalStorage)try{const e=localStorage.getItem(this.STORAGE_KEY);if(e){const t=JSON.parse(e);Date.now()-t.timestamp<864e5?(this.eventQueue=t.events||[],R.debug("[AnalyticsTracker] Loaded queued events from storage",{count:this.eventQueue.length})):localStorage.removeItem(this.STORAGE_KEY)}}catch(e){R.warn("[AnalyticsTracker] Failed to load queued events from storage",{error:e}),localStorage.removeItem(this.STORAGE_KEY)}}flushEvents(){if(0!==this.eventQueue.length&&navigator.sendBeacon&&this.config.apiEndpoint){const e=this.eventQueue.map((e=>({composition_id:e.compositionId,event_type:e.eventType,event_data:e.data,user_id:e.userId,session_id:e.sessionId,user_agent:e.userAgent,referrer:e.referrer})));navigator.sendBeacon(`${this.config.apiEndpoint}/analytics/events/bulk`,JSON.stringify({events:e})),this.eventQueue=[]}}trackCompositionView(e={}){const t=Object.assign({viewportSize:{width:window.innerWidth,height:window.innerHeight},scrollPosition:{x:window.scrollX,y:window.scrollY},loadTime:Date.now()-this.viewStartTime},e),i=this.createBaseEvent("composition_view",t);this.queueEvent(i)}trackCompositionInteraction(e){if(this.config.trackOnlyClicks&&"hover"===e.interactionType)return;this.interactionCount++,this.updateActivity();const t=this.createBaseEvent("composition_interaction",e);this.queueEvent(t)}trackSessionStart(){if(this.isSessionActive)return;this.isSessionActive=!0,this.sessionStartTime=Date.now();const e=this.createBaseEvent("session_start",{sessionDuration:0,pageViews:1,interactions:0});this.queueEvent(e)}trackSessionEnd(e="user_close"){if(!this.isSessionActive)return;this.isSessionActive=!1;const t={sessionDuration:Date.now()-this.sessionStartTime,interactions:this.interactionCount,exitReason:e},i=this.createBaseEvent("session_end",t);this.queueEvent(i)}trackDeviceInfo(){if(!this.config.enableDeviceTracking)return;const e=this.deviceDetector.getDeviceInfo(),t=this.createBaseEvent("device_info",e);this.queueEvent(t)}trackReferrerInfo(){const e={referrer:document.referrer,referrer_domain:document.referrer?new URL(document.referrer).hostname:null,current_url:window.location.href,current_domain:window.location.hostname},t=this.createBaseEvent("referrer_info",e);this.queueEvent(t)}getSessionInfo(){return{sessionId:this.sessionId,isActive:this.isSessionActive,startTime:this.sessionStartTime,lastActivity:this.lastActivityTime,interactionCount:this.interactionCount,duration:Date.now()-this.sessionStartTime}}updateConfig(e){this.config=Object.assign(Object.assign({},this.config),e),R.debug("[AnalyticsTracker] Configuration updated",e)}clearQueue(){this.eventQueue=[],this.config.enableLocalStorage&&localStorage.removeItem(this.STORAGE_KEY),R.debug("[AnalyticsTracker] Event queue cleared")}getStats(){return{queueSize:this.eventQueue.length,sessionInfo:this.getSessionInfo(),rateLimits:Object.fromEntries(this.rateLimitState.eventCounts),isOnline:this.isOnline,trackingAllowed:this.isTrackingAllowed()}}destroy(){this.trackSessionEnd("destroy"),this.flushEvents(),this.batchTimer&&clearTimeout(this.batchTimer),this.config.enableLocalStorage&&(localStorage.removeItem(this.STORAGE_KEY),localStorage.removeItem(this.SESSION_KEY)),Z.instance=null,R.debug("[AnalyticsTracker] Destroyed")}}const ee="undefined"!=typeof HTMLElement?HTMLElement:class{};class te extends ee{constructor(){super(),this.experimentId=null,this.assignment=null,this.widgetInstance=null,this.impressionTracked=!1,this.conversionListeners=new Map,this.manager=Y.getInstance(),this.widgetManager=r.getInstance(),this.analyticsTracker=Z.getInstance(),this.attachShadow({mode:"open"}),this.setupEventListeners()}static get observedAttributes(){return["experiment-id","user-id","session-id"]}connectedCallback(){return J(this,void 0,void 0,(function*(){try{if(this.experimentId=this.getAttribute("experiment-id"),!this.experimentId)return P.error("A/B test element missing experiment-id attribute"),void this.renderError("Missing experiment-id attribute");const e={userId:this.getAttribute("user-id")||void 0,sessionId:this.getAttribute("session-id")||void 0,userAgent:navigator.userAgent,ipAddress:void 0};if(this.renderLoading(),this.assignment=yield this.manager.getVariantAssignment(this.experimentId,e),!this.assignment)return P.warn("No variant assignment received",{experimentId:this.experimentId}),void this.renderError("Test not available");this.setupGoalListeners(),yield this.renderVariant(),yield this.trackImpression(),this.setupConversionTracking(),P.info("A/B test element initialized",{experimentId:this.experimentId,variantId:this.assignment.variantId})}catch(e){P.error("Failed to initialize A/B test element",{experimentId:this.experimentId,error:e}),this.renderError("Failed to load test")}}))}disconnectedCallback(){this.cleanup()}attributeChangedCallback(e,t,i){t!==i&&"experiment-id"===e&&this.connectedCallback()}setupEventListeners(){this.manager.on("conversion",(e=>{e.experimentId===this.experimentId&&this.handleConversionEvent(e)})),this.widgetManager.addEventListener("widget_ready",(e=>{this.widgetInstance&&e.widgetId===this.widgetInstance.id&&this.onWidgetReady(e)})),this.widgetManager.addEventListener("widget_error",(e=>{this.widgetInstance&&e.widgetId===this.widgetInstance.id&&this.onWidgetError(e)}))}renderVariant(){return J(this,void 0,void 0,(function*(){var e,t,i;if(this.assignment&&this.shadowRoot)try{const i=document.createElement("div");i.style.cssText="\n width: 100%;\n height: 100%;\n position: relative;\n ",i.setAttribute("data-ab-experiment",this.experimentId||""),i.setAttribute("data-ab-variant",this.assignment.variantId);const n=this.createEmbedElement(this.assignment.embedCode);if(n){i.appendChild(n);const s={compositionId:this.assignment.compositionId,renderMode:"auto",displayMode:"inline",resize:"fill-width",width:800,height:600};this.widgetInstance=yield this.widgetManager.registerWidget(`abtest_${this.experimentId}_${this.assignment.variantId}_${Date.now()}`,s,n),this.widgetInstance&&(null===(e=this.widgetInstance.element)||void 0===e||e.setAttribute("data-ab-experiment-id",this.experimentId||""),null===(t=this.widgetInstance.element)||void 0===t||t.setAttribute("data-ab-variant-id",this.assignment.variantId))}this.shadowRoot.innerHTML="",this.shadowRoot.appendChild(i),n&&this.sendGoalToWidget(n),this.dispatchEvent(new CustomEvent("variant-rendered",{detail:{experimentId:this.experimentId,variantId:this.assignment.variantId,compositionId:this.assignment.compositionId},bubbles:!0}))}catch(e){P.error("Failed to render variant",{experimentId:this.experimentId,variantId:null===(i=this.assignment)||void 0===i?void 0:i.variantId,error:e}),this.renderError("Failed to render variant")}}))}createEmbedElement(e){var t;try{const i=new DOMParser,n=i.parseFromString(e,"text/html").body.firstElementChild;if(!n)return P.warn("No element found in embed code",{embedCode:e}),null;const s=n.cloneNode(!0);return s.setAttribute("data-ab-experiment",this.experimentId||""),s.setAttribute("data-ab-variant",(null===(t=this.assignment)||void 0===t?void 0:t.variantId)||""),s}catch(t){return P.error("Failed to parse embed code",{embedCode:e,error:t}),null}}setupConversionTracking(){if(this.assignment&&this.widgetInstance)try{this.setupClickTracking(),this.setupFormTracking(),this.setupMediaTracking(),this.setupCustomEventTracking(),P.debug("Conversion tracking setup complete",{experimentId:this.experimentId,variantId:this.assignment.variantId})}catch(e){P.error("Failed to setup conversion tracking",{experimentId:this.experimentId,error:e})}}setupClickTracking(){const e=e=>{var t;if(!this.experimentId||!this.assignment)return;const i=e.target,n=this.assignment.goalTarget||null;(n?Q(i,n):this.isClickableElement(i))&&this.manager.trackConversion(this.experimentId,this.assignment.variantId,"clicks",Object.assign(Object.assign({element:i.tagName.toLowerCase(),text:(null===(t=i.textContent)||void 0===t?void 0:t.slice(0,100))||""},n?{goalTarget:n}:{}),{timestamp:Date.now()}))};this.shadowRoot&&(this.shadowRoot.addEventListener("click",e),this.conversionListeners.set("click",(()=>{var t;null===(t=this.shadowRoot)||void 0===t||t.removeEventListener("click",e)})))}setupFormTracking(){const e=e=>{if(!this.experimentId||!this.assignment)return;const t=e.target,i=this.assignment.goalTarget||null;"FORM"!==t.tagName||i&&!Q(t,i)||this.manager.trackConversion(this.experimentId,this.assignment.variantId,"submissions",Object.assign(Object.assign({formId:t.id||"unknown"},i?{goalTarget:i}:{}),{timestamp:Date.now()}))};this.shadowRoot&&(this.shadowRoot.addEventListener("submit",e),this.conversionListeners.set("submit",(()=>{var t;null===(t=this.shadowRoot)||void 0===t||t.removeEventListener("submit",e)})))}setupMediaTracking(){const e=e=>{if(!this.experimentId||!this.assignment)return;const t=e.target,i=this.assignment.goalTarget||null;"VIDEO"!==t.tagName&&"AUDIO"!==t.tagName||i&&!Q(t,i)||this.manager.trackConversion(this.experimentId,this.assignment.variantId,"plays",Object.assign(Object.assign({mediaType:t.tagName.toLowerCase(),duration:t.duration||0},i?{goalTarget:i}:{}),{timestamp:Date.now()}))};this.shadowRoot&&(this.shadowRoot.addEventListener("play",e),this.conversionListeners.set("play",(()=>{var t;null===(t=this.shadowRoot)||void 0===t||t.removeEventListener("play",e)})))}setupCustomEventTracking(){const e=e=>{if(!this.experimentId||!this.assignment)return;const t=e.detail;this.manager.trackConversion(this.experimentId,this.assignment.variantId,t.type||"conversions",Object.assign(Object.assign({},t),{timestamp:Date.now()}))};this.shadowRoot&&(this.shadowRoot.addEventListener("widgetic:conversion",e),this.conversionListeners.set("conversion",(()=>{var t;null===(t=this.shadowRoot)||void 0===t||t.removeEventListener("widgetic:conversion",e)})))}sendGoalToWidget(e){var t;if(this.experimentId&&this.assignment)try{const i=this.manager.getPrimaryMetric(this.experimentId);if(!i)return;null===(t=l(e))||void 0===t||t.sendAbGoal({metric:i,goalTarget:this.assignment.goalTarget||null})}catch(e){P.warn("Failed to tell the widget its A/B test goal",{experimentId:this.experimentId,error:e})}}setupGoalListeners(){if(!this.shadowRoot||this.conversionListeners.has("goal"))return;const e=this.shadowRoot,t=e=>{var t;if(!this.experimentId||!this.assignment)return;const i=null===(t=e.detail)||void 0===t?void 0:t.capabilities,n=Array.isArray(i)&&i.includes(w);this.manager.setWidgetReportsGoals(this.experimentId,n),this.assignment.goalTarget&&!n&&P.warn("This widget cannot report which element was used: the goal counts any use of its metric",{experimentId:this.experimentId,goalTarget:this.assignment.goalTarget}),this.sendGoalToWidget(e.target)},i=e=>{if(!this.experimentId||!this.assignment)return;const t=e.detail||{},i=t.metric||this.manager.getPrimaryMetric(this.experimentId);i&&this.manager.trackConversion(this.experimentId,this.assignment.variantId,i,{goalTarget:t.goalTarget,timestamp:Date.now()})},n=e=>t=>{var i;if(!this.experimentId||!this.assignment)return;const n=null===(i=t.detail)||void 0===i?void 0:i.type;"clicks"===e&&void 0!==n&&"click"!==n||this.manager.trackConversion(this.experimentId,this.assignment.variantId,e,{timestamp:Date.now()})},s=n("clicks"),a=n("submissions"),r=n("plays");e.addEventListener("widgetic:ready",t),e.addEventListener("widgetic:goal",i),e.addEventListener("widgetic:interaction",s),e.addEventListener("widgetic:form-submit",a),e.addEventListener("widgetic:media:play",r),this.conversionListeners.set("goal",(()=>{e.removeEventListener("widgetic:ready",t),e.removeEventListener("widgetic:goal",i),e.removeEventListener("widgetic:interaction",s),e.removeEventListener("widgetic:form-submit",a),e.removeEventListener("widgetic:media:play",r)}))}isClickableElement(e){return["BUTTON","A","INPUT"].includes(e.tagName)||e.hasAttribute("onclick")||e.hasAttribute("data-click-track")||"INPUT"===e.tagName&&["button","submit"].includes(e.type)||"button"===e.getAttribute("role")}trackImpression(){return J(this,void 0,void 0,(function*(){if(!this.impressionTracked&&this.experimentId&&this.assignment)try{const e={userId:this.getAttribute("user-id")||void 0,sessionId:this.getAttribute("session-id")||void 0};yield this.manager.trackImpression(this.experimentId,this.assignment.variantId,e),this.impressionTracked=!0,this.analyticsTracker.trackCompositionView({experiment_id:this.experimentId,variant_id:this.assignment.variantId,composition_id:this.assignment.compositionId}),P.debug("Impression tracked",{experimentId:this.experimentId,variantId:this.assignment.variantId})}catch(e){P.error("Failed to track impression",{experimentId:this.experimentId,error:e})}}))}handleConversionEvent(e){this.dispatchEvent(new CustomEvent("conversion",{detail:e,bubbles:!0})),this.analyticsTracker.trackCompositionInteraction({interactionType:"click",elementType:"ab_test_conversion",elementId:e.experimentId,coordinates:{x:0,y:0},duration:0})}onWidgetReady(e){var t,i;P.debug("Widget ready for A/B test",{experimentId:this.experimentId,variantId:null===(t=this.assignment)||void 0===t?void 0:t.variantId,widgetId:e.widgetId}),this.dispatchEvent(new CustomEvent("widget-ready",{detail:{experimentId:this.experimentId,variantId:null===(i=this.assignment)||void 0===i?void 0:i.variantId,widgetId:e.widgetId},bubbles:!0}))}onWidgetError(e){var t;P.error("Widget error in A/B test",{experimentId:this.experimentId,variantId:null===(t=this.assignment)||void 0===t?void 0:t.variantId,error:e.details}),this.renderError("Widget failed to load")}renderLoading(){this.shadowRoot&&(this.shadowRoot.innerHTML='\n <style>\n .ab-test-loading {\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100px;\n color: #666;\n font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, sans-serif;\n }\n .spinner {\n width: 20px;\n height: 20px;\n border: 2px solid #e0e0e0;\n border-top: 2px solid #007cba;\n border-radius: 50%;\n animation: spin 1s linear infinite;\n margin-right: 10px;\n }\n @keyframes spin {\n 0% { transform: rotate(0deg); }\n 100% { transform: rotate(360deg); }\n }\n </style>\n <div class="ab-test-loading">\n <div class="spinner"></div>\n Loading test...\n </div>\n ')}renderError(e){this.shadowRoot&&(this.shadowRoot.innerHTML=`\n <style>\n .ab-test-error {\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100px;\n color: #d32f2f;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n background-color: #ffebee;\n border: 1px solid #ffcdd2;\n border-radius: 4px;\n padding: 16px;\n text-align: center;\n }\n </style>\n <div class="ab-test-error">\n ${e}\n </div>\n `,this.dispatchEvent(new CustomEvent("error",{detail:{message:e},bubbles:!0})))}cleanup(){if(this.conversionListeners.forEach((e=>e())),this.conversionListeners.clear(),this.widgetInstance)try{this.widgetManager.unregisterWidget(this.widgetInstance.id)}catch(e){P.warn("Failed to cleanup widget instance",{error:e})}this.impressionTracked=!1,this.assignment=null,this.widgetInstance=null}trackConversion(e="custom",t){return this.experimentId&&this.assignment?this.manager.trackConversion(this.experimentId,this.assignment.variantId,e,t):Promise.reject(new Error("A/B test not initialized"))}getAssignment(){return this.assignment?Object.assign({},this.assignment):null}getExperimentId(){return this.experimentId}static register(){"undefined"!=typeof window&&window.customElements&&(customElements.get("widgetic-abtest")||customElements.define("widgetic-abtest",te))}}te.register();const ie="undefined"!=typeof HTMLElement?HTMLElement:class{};class ne extends ie{constructor(){super(),this.widgetInstance=null,this.isInitialized=!1,this.retryCount=0,this.maxRetries=3,this.retryDelay=1e3,this.experimentId=null,this.selectedLanguage=null,this.translationData=null,this.widgetManager=b(),R.debug("[TranslationElement] Created translation element")}connectedCallback(){if(this.isInitialized)R.debug("[TranslationElement] Already initialized, skipping");else{if(this.experimentId=this.getAttribute("experiment-id"),!this.experimentId)return R.error("[TranslationElement] Missing experiment-id attribute"),void this.displayError("Missing experiment-id attribute");R.debug(`[TranslationElement] Connected with experiment ID: ${this.experimentId}`),this.initializeTranslation()}}disconnectedCallback(){R.debug("[TranslationElement] Disconnected"),this.cleanup()}initializeTranslation(){return J(this,void 0,void 0,(function*(){try{this.isInitialized=!0;const e=this.detectBrowserLanguages();if(R.debug("[TranslationElement] Detected user languages:",e),this.translationData=yield this.fetchTranslationExperiment(this.experimentId),!this.translationData)throw new Error("Failed to fetch translation experiment data");this.selectedLanguage=this.findBestLanguageMatch(e,this.translationData),R.debug("[TranslationElement] Selected language:",this.selectedLanguage);const t=this.getCompositionForLanguage(this.selectedLanguage);if(!t)throw new Error(`No composition found for language: ${this.selectedLanguage}`);yield this.loadWidget(t),R.info("[TranslationElement] Translation experiment loaded successfully",{experimentId:this.experimentId,selectedLanguage:this.selectedLanguage,compositionId:t})}catch(e){R.error("[TranslationElement] Failed to initialize translation:",e),yield this.handleInitializationError(e)}}))}detectBrowserLanguages(){var e;const t=navigator.language.toLowerCase(),i=((null===(e=navigator.languages)||void 0===e?void 0:e.map((e=>e.toLowerCase())))||[t]).flatMap((e=>{const t=[e];return e.includes("-")&&t.push(e.split("-")[0]),t}));return[...new Set(i)]}fetchTranslationExperiment(e){return J(this,void 0,void 0,(function*(){try{const t=K(),i=new W({basePath:t,headers:{"X-SDK-Version":"embed-sdk/translations"}}),n=new U(i),s=yield n.getTranslationConfig({id:e});return(null==s?void 0:s.data)||null}catch(e){throw R.error("[TranslationElement] Error fetching translation experiment:",e),e}}))}findBestLanguageMatch(e,t){const i=Object.keys(t.languageCompositions||{}),n=t.rootLanguage||"en";R.debug("[TranslationElement] Available languages:",i),R.debug("[TranslationElement] Root language:",n);for(const t of e)if(i.includes(t))return R.debug("[TranslationElement] Found exact match:",t),t;for(const t of e){const e=t.split("-")[0],n=i.find((t=>t.startsWith(e+"-")||t===e));if(n)return R.debug("[TranslationElement] Found base language match:",n),this.trackFallbackUsage(t,n,"language_family").catch((e=>{R.debug("[TranslationElement] Failed to track language family fallback:",e)})),n}R.debug("[TranslationElement] No matches found, falling back to root language:",n);const s=e[0]||"unknown";return this.trackFallbackUsage(s,n,"root_fallback").catch((e=>{R.debug("[TranslationElement] Failed to track root fallback:",e)})),n}getCompositionForLanguage(e){if(!this.translationData)return null;if(e===this.translationData.rootLanguage)return this.translationData.rootCompositionId;return(this.translationData.languageCompositions||{})[e]||this.translationData.rootCompositionId}loadWidget(e){return J(this,void 0,void 0,(function*(){const t=X(e),i={compositionId:e,renderMode:"auto",displayMode:"inline",resize:"fill-width",width:800,height:600};this.widgetInstance=yield this.widgetManager.registerWidget(t,i,this),this.trackTranslationView()}))}trackTranslationView(){try{const e={experimentId:this.experimentId,selectedLanguage:this.selectedLanguage,userLanguages:this.detectBrowserLanguages(),timestamp:(new Date).toISOString(),userAgent:navigator.userAgent,referrer:document.referrer,url:window.location.href};this.sendAnalytics(e).catch((e=>{R.warn("[TranslationElement] Failed to send analytics:",e)}))}catch(e){R.warn("[TranslationElement] Error in analytics tracking:",e)}}sendAnalytics(e){return J(this,void 0,void 0,(function*(){try{const t=K(),i=new W({basePath:t,headers:{"X-SDK-Version":"embed-sdk/translations"}}),n=new U(i);yield n.submitTranslationAnalyticsEvent({id:this.experimentId,submitTranslationAnalyticsEventRequest:e})}catch(e){R.debug("[TranslationElement] Analytics request failed:",e)}}))}trackFallbackUsage(e,t,i){return J(this,void 0,void 0,(function*(){try{const n={eventType:"fallback_used",language:t,compositionId:this.getCompositionForLanguage(t)||"",metadata:{requestedLanguage:e,selectedLanguage:t,fallbackType:i,userAgent:navigator.userAgent,timestamp:(new Date).toISOString()},timestamp:(new Date).toISOString()};yield this.sendAnalytics(n),R.debug("[TranslationElement] Fallback usage tracked:",{requested:e,selected:t,fallbackType:i})}catch(e){R.debug("[TranslationElement] Failed to track fallback usage:",e)}}))}handleInitializationError(e){return J(this,void 0,void 0,(function*(){if(this.retryCount<this.maxRetries){this.retryCount++,R.warn(`[TranslationElement] Retrying initialization (${this.retryCount}/${this.maxRetries}):`,e.message),yield new Promise((e=>setTimeout(e,this.retryDelay*this.retryCount)));try{return void(yield this.initializeTranslation())}catch(e){R.error("[TranslationElement] Retry failed:",e)}}this.displayError(`Translation loading failed: ${e.message}`)}))}displayError(e){this.innerHTML=`\n <div style="\n padding: 1rem;\n border: 1px solid #ef4444;\n border-radius: 0.5rem;\n background-color: #fef2f2;\n color: #dc2626;\n font-family: system-ui, -apple-system, sans-serif;\n font-size: 0.875rem;\n margin: 1rem 0;\n ">\n <strong>Translation Error:</strong> ${e}\n </div>\n `}cleanup(){this.widgetInstance&&(this.widgetManager.unregisterWidget(this.widgetInstance.id),this.widgetInstance=null),this.isInitialized=!1,this.retryCount=0}switchLanguage(e){if(!this.translationData)throw new Error("Translation data not loaded");const t=this.getCompositionForLanguage(e);if(!t)throw new Error(`No composition found for language: ${e}`);return this.cleanup(),this.selectedLanguage=e,this.loadWidget(t)}getSelectedLanguage(){return this.selectedLanguage}getAvailableLanguages(){return this.translationData?Object.keys(this.translationData.languageCompositions||{}):[]}static register(){try{"undefined"!=typeof window&&"undefined"!=typeof customElements&&(customElements.get("widgetic-translations")||(customElements.define("widgetic-translations",ne),R.info("[TranslationElement] Custom element registered")))}catch(e){R.error("[TranslationElement] Failed to register custom element:",e)}}}ne.register();const se=T();"undefined"!=typeof window&&"undefined"!=typeof customElements&&($(),te.register(),ne.register()),"undefined"!=typeof window&&(window.WidgeticEmbedSDK=se,window.Widgetic={SDK:se,getSDK:T,EmbedSDK:_,config:{API_URL:V.API_URL,API_VERSION:V.API_VERSION,CLIENT_URL:V.CLIENT_URL,PRODUCTION_URL:V.PRODUCTION_URL,NODE_ENV:V.NODE_ENV},log:R,WidgeticWidget:G,registerWidgeticWidget:$,cssDebugger:D,enableCSSDebug:()=>D.enableDebugMode(),disableCSSDebug:()=>D.disableDebugMode(),analyzeWidget:e=>D.analyzeWidget(e),ABTestManager:Y,ABTestElement:te,TranslationElement:ne});export{te as ABTestElement,Y as ABTestManager,_ as EmbedSDK,ne as TranslationElement,_ as WidgeticEmbedSDK,G as WidgeticWidget,V as config,D as cssDebugger,se as default,X as generateInstanceId,O as getAuthToken,T as getSDK,R as log,$ as registerWidgeticWidget};
1
+ import{j as n,k as r,i as l,G as w,l as b,m as T,n as R,E as D}from"./chunks/api.js";export{B as BatchApiClient,C as CSSDebugger,H as HighLevelAPI,L as LowLevelAPI,M as MidLevelAPI,o as ModuleLoader,p as analyzeWidgetCSS,q as disableCSSDebug,t as enableCSSDebug,g as getBatchClient,a as getModuleLoader,u as monitorWidgetCSS,v as resetBatchClient,x as resetModuleLoader,y as sendWorkflowEvent}from"./chunks/api.js";import{l as _,g as O,C as W,V as N,u as V,e as z,t as P,a as Q,T as U,d as G}from"./chunks/core.js";export{v as AuthError,A as AuthManager,j as DefaultTokenProvider,E as EndpointTokenProvider,F as FunctionTokenProvider,S as StaticApiKeyProvider,m as getApiUrl,x as getAuthManager,c as getCdnUrl,h as getConfiguration,k as getTokenProvider,i as setApiKey,s as setTokenProvider}from"./chunks/core.js";import{e as K,W as $}from"./chunks/renderers.js";export{C as CustomElementRenderer,I as IframeRenderer,f as WidgetRenderer,g as getWidgetRenderer,i as resetWidgetRenderer}from"./chunks/renderers.js";export{WidgeticMessenger,getMessenger,resetMessenger}from"./chunks/messaging.js";import{ABTestManager as Y}from"./chunks/ABTestManager.js";import{_ as J}from"./chunks/vendor.js";import{k as X}from"./chunks/scanner.js";export{e as detectBrowserCapabilities,j as determineBestRenderMode,f as isValidWidgetElement,p as parseWidgetConfig}from"./chunks/scanner.js";export{t as toCamel,d as toSnake}from"./chunks/advanced.js";import"./chunks/media.js";import"./chunks/display.js";import"./chunks/performance.js";import"./chunks/security.js";class Z{constructor(e){this.deviceDetector=n(),this.privacyCompliance=null,this.eventQueue=[],this.batchTimer=null,this.isOnline=navigator.onLine,this.sessionStartTime=Date.now(),this.lastActivityTime=Date.now(),this.isSessionActive=!1,this.interactionCount=0,this.viewStartTime=Date.now(),this.STORAGE_KEY="widgetic_analytics_queue",this.SESSION_KEY="widgetic_session_id",this.config=Object.assign({batchSize:10,batchTimeout:5e3,maxRetries:3,rateLimitPerMinute:100,enableLocalStorage:!0,enableDeviceTracking:!0,enableInteractionTracking:!0,trackOnlyClicks:!0},e),this.sessionId=this.initializeSession(),this.rateLimitState={eventCounts:new Map,windowStart:Date.now(),windowDurationMs:6e4},this.setupEventListeners(),this.loadQueuedEvents(),_.debug("[AnalyticsTracker] Initialized",{compositionId:this.config.compositionId,sessionId:this.sessionId})}static getInstance(e){if(!Z.instance&&e&&(Z.instance=new Z(e)),!Z.instance)throw new Error("AnalyticsTracker must be initialized with config first");return Z.instance}static peekInstance(){var e;return null!==(e=Z.instance)&&void 0!==e?e:null}initializeSession(){if(this.config.enableLocalStorage){const e=localStorage.getItem(this.SESSION_KEY);if(e)try{const t=JSON.parse(e);if(Date.now()-t.timestamp<18e5)return t.sessionId}catch(e){_.warn("[AnalyticsTracker] Failed to parse stored session",{error:e})}}const e=`sess_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;if(this.config.enableLocalStorage)try{localStorage.setItem(this.SESSION_KEY,JSON.stringify({sessionId:e,timestamp:Date.now()}))}catch(e){_.warn("[AnalyticsTracker] Failed to store session ID",{error:e})}return e}setPrivacyCompliance(e){this.privacyCompliance=e}isTrackingAllowed(){return!this.privacyCompliance||this.privacyCompliance.hasConsent("analytics")}setupEventListeners(){window.addEventListener("online",(()=>{this.isOnline=!0,this.processBatch()})),window.addEventListener("offline",(()=>{this.isOnline=!1})),["mousedown","mousemove","keypress","scroll","touchstart"].forEach((e=>{document.addEventListener(e,(()=>this.updateActivity()),{passive:!0})})),document.addEventListener("visibilitychange",(()=>{document.hidden?this.trackSessionEnd("visibility_hidden"):this.trackSessionStart()})),window.addEventListener("beforeunload",(()=>{this.trackSessionEnd("navigation"),this.flushEvents()}))}updateActivity(){this.lastActivityTime=Date.now(),this.isSessionActive||this.trackSessionStart()}isRateLimited(e){const t=Date.now();t-this.rateLimitState.windowStart>=this.rateLimitState.windowDurationMs&&(this.rateLimitState.eventCounts.clear(),this.rateLimitState.windowStart=t);const i=this.rateLimitState.eventCounts.get(e)||0;return i>=this.config.rateLimitPerMinute?(_.warn("[AnalyticsTracker] Rate limit exceeded",{eventType:e,currentCount:i}),!0):(this.rateLimitState.eventCounts.set(e,i+1),!1)}generateEventId(){return`evt_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}createBaseEvent(e,t={}){const i=this.config.enableDeviceTracking?this.deviceDetector.getDeviceInfo():void 0;return{id:this.generateEventId(),eventType:e,compositionId:this.config.compositionId,timestamp:Date.now(),sessionId:this.sessionId,data:t,deviceInfo:i,referrer:document.referrer||void 0,userAgent:navigator.userAgent,url:window.location.href}}queueEvent(e){this.isTrackingAllowed()?this.isRateLimited(e.eventType)||(this.eventQueue.push(e),this.config.enableLocalStorage&&this.saveQueueToStorage(),this.scheduleBatch(),_.debug("[AnalyticsTracker] Event queued",{eventType:e.eventType,queueSize:this.eventQueue.length})):_.debug("[AnalyticsTracker] Tracking not allowed, skipping event",{eventType:e.eventType})}scheduleBatch(){this.eventQueue.length>=this.config.batchSize?this.processBatch():this.batchTimer||(this.batchTimer=setTimeout((()=>{this.processBatch()}),this.config.batchTimeout))}processBatch(){return J(this,void 0,void 0,(function*(){if(this.batchTimer&&(clearTimeout(this.batchTimer),this.batchTimer=null),0===this.eventQueue.length||!this.isOnline)return;const e=this.eventQueue.splice(0,this.config.batchSize);try{yield this.sendEventBatch(e),this.config.enableLocalStorage&&this.saveQueueToStorage(),_.debug("[AnalyticsTracker] Batch sent successfully",{batchSize:e.length,remainingQueue:this.eventQueue.length})}catch(t){_.error("[AnalyticsTracker] Failed to send batch",{error:t,batchSize:e.length}),this.eventQueue.unshift(...e),setTimeout((()=>this.processBatch()),5e3)}}))}sendEventBatch(e){return J(this,void 0,void 0,(function*(){if(!this.config.apiEndpoint)return void _.warn("[AnalyticsTracker] No API endpoint configured");const t=e.map((e=>({composition_id:e.compositionId,event_type:e.eventType,event_data:e.data,user_id:e.userId,session_id:e.sessionId,user_agent:e.userAgent,referrer:e.referrer,ip_address:void 0}))),i=yield O(),n=new W({basePath:this.config.apiEndpoint,accessToken:()=>J(this,void 0,void 0,(function*(){return i})),headers:{"X-SDK-Version":`embed-sdk/${N}`}}),s=new V(n);yield s.analyticsEventsBulkPost({analyticsEventsBulkPostRequest:{events:t}})}))}saveQueueToStorage(){if(this.config.enableLocalStorage)try{const e={events:this.eventQueue,timestamp:Date.now()};localStorage.setItem(this.STORAGE_KEY,JSON.stringify(e))}catch(e){_.warn("[AnalyticsTracker] Failed to save queue to storage",{error:e})}}loadQueuedEvents(){if(this.config.enableLocalStorage)try{const e=localStorage.getItem(this.STORAGE_KEY);if(e){const t=JSON.parse(e);Date.now()-t.timestamp<864e5?(this.eventQueue=t.events||[],_.debug("[AnalyticsTracker] Loaded queued events from storage",{count:this.eventQueue.length})):localStorage.removeItem(this.STORAGE_KEY)}}catch(e){_.warn("[AnalyticsTracker] Failed to load queued events from storage",{error:e}),localStorage.removeItem(this.STORAGE_KEY)}}flushEvents(){if(0!==this.eventQueue.length&&navigator.sendBeacon&&this.config.apiEndpoint){const e=this.eventQueue.map((e=>({composition_id:e.compositionId,event_type:e.eventType,event_data:e.data,user_id:e.userId,session_id:e.sessionId,user_agent:e.userAgent,referrer:e.referrer})));navigator.sendBeacon(`${this.config.apiEndpoint}/analytics/events/bulk`,JSON.stringify({events:e})),this.eventQueue=[]}}trackCompositionView(e={}){const t=Object.assign({viewportSize:{width:window.innerWidth,height:window.innerHeight},scrollPosition:{x:window.scrollX,y:window.scrollY},loadTime:Date.now()-this.viewStartTime},e),i=this.createBaseEvent("composition_view",t);this.queueEvent(i)}trackCompositionInteraction(e){if(this.config.trackOnlyClicks&&"hover"===e.interactionType)return;this.interactionCount++,this.updateActivity();const t=this.createBaseEvent("composition_interaction",e);this.queueEvent(t)}trackSessionStart(){if(this.isSessionActive)return;this.isSessionActive=!0,this.sessionStartTime=Date.now();const e=this.createBaseEvent("session_start",{sessionDuration:0,pageViews:1,interactions:0});this.queueEvent(e)}trackSessionEnd(e="user_close"){if(!this.isSessionActive)return;this.isSessionActive=!1;const t={sessionDuration:Date.now()-this.sessionStartTime,interactions:this.interactionCount,exitReason:e},i=this.createBaseEvent("session_end",t);this.queueEvent(i)}trackDeviceInfo(){if(!this.config.enableDeviceTracking)return;const e=this.deviceDetector.getDeviceInfo(),t=this.createBaseEvent("device_info",e);this.queueEvent(t)}trackReferrerInfo(){const e={referrer:document.referrer,referrer_domain:document.referrer?new URL(document.referrer).hostname:null,current_url:window.location.href,current_domain:window.location.hostname},t=this.createBaseEvent("referrer_info",e);this.queueEvent(t)}getSessionInfo(){return{sessionId:this.sessionId,isActive:this.isSessionActive,startTime:this.sessionStartTime,lastActivity:this.lastActivityTime,interactionCount:this.interactionCount,duration:Date.now()-this.sessionStartTime}}updateConfig(e){this.config=Object.assign(Object.assign({},this.config),e),_.debug("[AnalyticsTracker] Configuration updated",e)}clearQueue(){this.eventQueue=[],this.config.enableLocalStorage&&localStorage.removeItem(this.STORAGE_KEY),_.debug("[AnalyticsTracker] Event queue cleared")}getStats(){return{queueSize:this.eventQueue.length,sessionInfo:this.getSessionInfo(),rateLimits:Object.fromEntries(this.rateLimitState.eventCounts),isOnline:this.isOnline,trackingAllowed:this.isTrackingAllowed()}}destroy(){this.trackSessionEnd("destroy"),this.flushEvents(),this.batchTimer&&clearTimeout(this.batchTimer),this.config.enableLocalStorage&&(localStorage.removeItem(this.STORAGE_KEY),localStorage.removeItem(this.SESSION_KEY)),Z.instance=null,_.debug("[AnalyticsTracker] Destroyed")}}const ee="undefined"!=typeof HTMLElement?HTMLElement:class{};class te extends ee{constructor(){super(),this.experimentId=null,this.assignment=null,this.widgetInstance=null,this.impressionTracked=!1,this.conversionListeners=new Map,this.renderedVariantId=null,this.isRecording=!1,this.hasStarted=!1,this.currentRunId=0,this.widgetReportsGoals=!1,this.readyWidgetHost=null,this.manager=Y.getInstance(),this.widgetManager=r.getInstance(),this.attachShadow({mode:"open"}),this.setupEventListeners()}static get observedAttributes(){return["experiment-id","user-id","session-id","consent"]}connectedCallback(){return J(this,void 0,void 0,(function*(){this.hasStarted=!0,yield this.start()}))}disconnectedCallback(){this.cleanup()}attributeChangedCallback(e,t,i){this.hasStarted&&this.isConnected&&t!==i&&("experiment-id"===e?(this.cleanup(),this.start()):"consent"===e&&this.start())}readConsent(){const e=this.getAttribute("consent");return null===e||"granted"===e?"granted":"denied"===e?"denied":"pending"}start(){return J(this,void 0,void 0,(function*(){const e=++this.currentRunId,t=()=>e!==this.currentRunId;try{if(this.experimentId=this.getAttribute("experiment-id"),!this.experimentId)return z.error("A/B test element missing experiment-id attribute"),void this.renderError("Missing experiment-id attribute");"granted"===this.readConsent()?yield this.startRecorded(t):yield this.startUnrecorded(t)}catch(e){z.error("Failed to initialize A/B test element",{experimentId:this.experimentId,error:e}),this.renderError("Failed to load test")}}))}startRecorded(e){return J(this,void 0,void 0,(function*(){const t=this.experimentId;this.manager.resumeRecording(t);const i={userId:this.getAttribute("user-id")||void 0,sessionId:this.getAttribute("session-id")||void 0,userAgent:navigator.userAgent,ipAddress:void 0};this.renderedVariantId||this.renderLoading();const n=yield this.manager.getVariantAssignment(t,i);if(!e()){if(!n)return z.warn("No variant assignment received",{experimentId:t}),this.assignment=null,this.isRecording=!1,void this.renderError("Test not available");if(this.assignment=n,this.isRecording=!0,this.impressionTracked=!1,this.setupGoalListeners(),this.renderedVariantId===n.variantId)this.announceVariant();else if(yield this.renderVariant(),e())return;yield this.trackImpression(),this.setupConversionTracking(),this.applyWidgetReadiness(),z.info("A/B test element initialized",{experimentId:t,variantId:n.variantId})}}))}startUnrecorded(e){return J(this,void 0,void 0,(function*(){const t=this.experimentId,i=this.readConsent();this.isRecording=!1,this.removeConversionListeners(),this.impressionTracked=!1,this.manager.holdRecording(t),"denied"===i&&this.manager.forgetVisitor(t,{userId:this.getAttribute("user-id")||void 0}),this.renderedVariantId||this.renderLoading(),this.setupGoalListeners();const n=yield this.manager.getUnrecordedVariant(t);if(!e()){if(!n)return z.warn("No original version received for the A/B test",{experimentId:t}),this.assignment=null,void this.renderError("Test not available");this.assignment=n,this.renderedVariantId===n.variantId?this.announceVariant():yield this.renderVariant(),z.info("A/B test element shows the original version: analytics is not allowed",{experimentId:t,variantId:n.variantId,consent:i})}}))}setupEventListeners(){this.manager.on("conversion",(e=>{e.experimentId===this.experimentId&&this.handleConversionEvent(e)})),this.widgetManager.addEventListener("widget_ready",(e=>{this.widgetInstance&&e.widgetId===this.widgetInstance.id&&this.onWidgetReady(e)})),this.widgetManager.addEventListener("widget_error",(e=>{this.widgetInstance&&e.widgetId===this.widgetInstance.id&&this.onWidgetError(e)}))}renderVariant(){return J(this,void 0,void 0,(function*(){var e,t;if(!this.assignment||!this.shadowRoot)return;const i=this.assignment,n=this.currentRunId;try{this.removeWidgetInstance(),this.widgetReportsGoals=!1,this.readyWidgetHost=null;const s=document.createElement("div");s.style.cssText="\n width: 100%;\n height: 100%;\n position: relative;\n ",s.setAttribute("data-ab-experiment",this.experimentId||""),s.setAttribute("data-ab-variant",i.variantId);const a=this.createEmbedElement(i.embedCode,i.variantId);if(a){s.appendChild(a);const r={compositionId:i.compositionId,renderMode:"auto",displayMode:"inline",resize:"fill-width",width:800,height:600};if(this.widgetInstance=yield this.widgetManager.registerWidget(`abtest_${this.experimentId}_${i.variantId}_${Date.now()}`,r,a),n!==this.currentRunId)return void this.removeWidgetInstance();this.widgetInstance&&(null===(e=this.widgetInstance.element)||void 0===e||e.setAttribute("data-ab-experiment-id",this.experimentId||""),null===(t=this.widgetInstance.element)||void 0===t||t.setAttribute("data-ab-variant-id",i.variantId))}this.shadowRoot.innerHTML="",this.shadowRoot.appendChild(s),this.renderedVariantId=i.variantId,a&&this.sendGoalToWidget(a),this.announceVariant()}catch(e){z.error("Failed to render variant",{experimentId:this.experimentId,variantId:i.variantId,error:e}),this.renderError("Failed to render variant")}}))}announceVariant(){this.assignment&&this.dispatchEvent(new CustomEvent("variant-rendered",{detail:{experimentId:this.experimentId,variantId:this.assignment.variantId,compositionId:this.assignment.compositionId,recorded:this.isRecording},bubbles:!0}))}removeWidgetInstance(){if(this.widgetInstance){try{this.widgetManager.unregisterWidget(this.widgetInstance.id)}catch(e){z.warn("Failed to cleanup widget instance",{error:e})}this.widgetInstance=null}}createEmbedElement(e,t){try{const i=new DOMParser,n=i.parseFromString(e,"text/html").body.firstElementChild;if(!n)return z.warn("No element found in embed code",{embedCode:e}),null;const s=n.cloneNode(!0);return s.setAttribute("data-ab-experiment",this.experimentId||""),s.setAttribute("data-ab-variant",t),s}catch(t){return z.error("Failed to parse embed code",{embedCode:e,error:t}),null}}setupConversionTracking(){if(this.assignment&&this.widgetInstance)try{this.setupClickTracking(),this.setupFormTracking(),this.setupMediaTracking(),this.setupCustomEventTracking(),z.debug("Conversion tracking setup complete",{experimentId:this.experimentId,variantId:this.assignment.variantId})}catch(e){z.error("Failed to setup conversion tracking",{experimentId:this.experimentId,error:e})}}setupClickTracking(){const e=e=>{var t;if(!this.experimentId||!this.assignment)return;const i=e.target,n=this.assignment.goalTarget||null;(n?P(i,n):this.isClickableElement(i))&&this.manager.trackConversion(this.experimentId,this.assignment.variantId,"clicks",Object.assign(Object.assign({element:i.tagName.toLowerCase(),text:(null===(t=i.textContent)||void 0===t?void 0:t.slice(0,100))||""},n?{goalTarget:n}:{}),{timestamp:Date.now()}))};this.shadowRoot&&(this.shadowRoot.addEventListener("click",e),this.conversionListeners.set("click",(()=>{var t;null===(t=this.shadowRoot)||void 0===t||t.removeEventListener("click",e)})))}setupFormTracking(){const e=e=>{if(!this.experimentId||!this.assignment)return;const t=e.target,i=this.assignment.goalTarget||null;"FORM"!==t.tagName||i&&!P(t,i)||this.manager.trackConversion(this.experimentId,this.assignment.variantId,"submissions",Object.assign(Object.assign({formId:t.id||"unknown"},i?{goalTarget:i}:{}),{timestamp:Date.now()}))};this.shadowRoot&&(this.shadowRoot.addEventListener("submit",e),this.conversionListeners.set("submit",(()=>{var t;null===(t=this.shadowRoot)||void 0===t||t.removeEventListener("submit",e)})))}setupMediaTracking(){const e=e=>{if(!this.experimentId||!this.assignment)return;const t=e.target,i=this.assignment.goalTarget||null;"VIDEO"!==t.tagName&&"AUDIO"!==t.tagName||i&&!P(t,i)||this.manager.trackConversion(this.experimentId,this.assignment.variantId,"plays",Object.assign(Object.assign({mediaType:t.tagName.toLowerCase(),duration:t.duration||0},i?{goalTarget:i}:{}),{timestamp:Date.now()}))};this.shadowRoot&&(this.shadowRoot.addEventListener("play",e),this.conversionListeners.set("play",(()=>{var t;null===(t=this.shadowRoot)||void 0===t||t.removeEventListener("play",e)})))}setupCustomEventTracking(){const e=e=>{if(!this.experimentId||!this.assignment)return;const t=e.detail;this.manager.trackConversion(this.experimentId,this.assignment.variantId,t.type||"conversions",Object.assign(Object.assign({},t),{timestamp:Date.now()}))};this.shadowRoot&&(this.shadowRoot.addEventListener("widgetic:conversion",e),this.conversionListeners.set("conversion",(()=>{var t;null===(t=this.shadowRoot)||void 0===t||t.removeEventListener("widgetic:conversion",e)})))}sendGoalToWidget(e){var t;if(this.experimentId&&this.assignment&&this.isRecording)try{const i=this.manager.getPrimaryMetric(this.experimentId);if(!i)return;null===(t=l(e))||void 0===t||t.sendAbGoal({metric:i,goalTarget:this.assignment.goalTarget||null})}catch(e){z.warn("Failed to tell the widget its A/B test goal",{experimentId:this.experimentId,error:e})}}applyWidgetReadiness(){this.experimentId&&this.assignment&&this.isRecording&&this.readyWidgetHost&&(this.manager.setWidgetReportsGoals(this.experimentId,this.widgetReportsGoals),this.assignment.goalTarget&&!this.widgetReportsGoals&&z.warn("This widget cannot report which element was used: the goal counts any use of its metric",{experimentId:this.experimentId,goalTarget:this.assignment.goalTarget}),this.sendGoalToWidget(this.readyWidgetHost))}setupGoalListeners(){if(!this.shadowRoot||this.conversionListeners.has("goal"))return;const e=this.shadowRoot,t=e=>{var t;const i=null===(t=e.detail)||void 0===t?void 0:t.capabilities;this.widgetReportsGoals=Array.isArray(i)&&i.includes(w),this.readyWidgetHost=e.target,this.applyWidgetReadiness()},i=e=>{if(!this.experimentId||!this.assignment||!this.isRecording)return;const t=e.detail||{},i=t.metric||this.manager.getPrimaryMetric(this.experimentId);i&&this.manager.trackConversion(this.experimentId,this.assignment.variantId,i,{goalTarget:t.goalTarget,timestamp:Date.now()})},n=e=>t=>{var i;if(!this.experimentId||!this.assignment||!this.isRecording)return;const n=null===(i=t.detail)||void 0===i?void 0:i.type;"clicks"===e&&void 0!==n&&"click"!==n||this.manager.trackConversion(this.experimentId,this.assignment.variantId,e,{timestamp:Date.now()})},s=n("clicks"),a=n("submissions"),r=n("plays");e.addEventListener("widgetic:ready",t),e.addEventListener("widgetic:goal",i),e.addEventListener("widgetic:interaction",s),e.addEventListener("widgetic:form-submit",a),e.addEventListener("widgetic:media:play",r),this.conversionListeners.set("goal",(()=>{e.removeEventListener("widgetic:ready",t),e.removeEventListener("widgetic:goal",i),e.removeEventListener("widgetic:interaction",s),e.removeEventListener("widgetic:form-submit",a),e.removeEventListener("widgetic:media:play",r)}))}isClickableElement(e){return["BUTTON","A","INPUT"].includes(e.tagName)||e.hasAttribute("onclick")||e.hasAttribute("data-click-track")||"INPUT"===e.tagName&&["button","submit"].includes(e.type)||"button"===e.getAttribute("role")}trackImpression(){return J(this,void 0,void 0,(function*(){var e;if(this.impressionTracked||!this.isRecording||!this.experimentId||!this.assignment)return;const t=this.experimentId,i=this.assignment;try{const n={userId:this.getAttribute("user-id")||void 0,sessionId:this.getAttribute("session-id")||void 0};this.impressionTracked=!0,yield this.manager.trackImpression(t,i.variantId,n),null===(e=Z.peekInstance())||void 0===e||e.trackCompositionView({experiment_id:t,variant_id:i.variantId,composition_id:i.compositionId}),z.debug("Impression tracked",{experimentId:t,variantId:i.variantId})}catch(e){z.error("Failed to track impression",{experimentId:t,error:e})}}))}handleConversionEvent(e){var t;this.dispatchEvent(new CustomEvent("conversion",{detail:e,bubbles:!0})),null===(t=Z.peekInstance())||void 0===t||t.trackCompositionInteraction({interactionType:"click",elementType:"ab_test_conversion",elementId:e.experimentId,coordinates:{x:0,y:0},duration:0})}onWidgetReady(e){var t,i;z.debug("Widget ready for A/B test",{experimentId:this.experimentId,variantId:null===(t=this.assignment)||void 0===t?void 0:t.variantId,widgetId:e.widgetId}),this.dispatchEvent(new CustomEvent("widget-ready",{detail:{experimentId:this.experimentId,variantId:null===(i=this.assignment)||void 0===i?void 0:i.variantId,widgetId:e.widgetId},bubbles:!0}))}onWidgetError(e){var t;z.error("Widget error in A/B test",{experimentId:this.experimentId,variantId:null===(t=this.assignment)||void 0===t?void 0:t.variantId,error:e.details}),this.renderError("Widget failed to load")}renderLoading(){this.shadowRoot&&(this.shadowRoot.innerHTML='\n <style>\n .ab-test-loading {\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100px;\n color: #666;\n font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, sans-serif;\n }\n .spinner {\n width: 20px;\n height: 20px;\n border: 2px solid #e0e0e0;\n border-top: 2px solid #007cba;\n border-radius: 50%;\n animation: spin 1s linear infinite;\n margin-right: 10px;\n }\n @keyframes spin {\n 0% { transform: rotate(0deg); }\n 100% { transform: rotate(360deg); }\n }\n </style>\n <div class="ab-test-loading">\n <div class="spinner"></div>\n Loading test...\n </div>\n ')}renderError(e){this.shadowRoot&&(this.renderedVariantId=null,this.shadowRoot.innerHTML=`\n <style>\n .ab-test-error {\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100px;\n color: #d32f2f;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n background-color: #ffebee;\n border: 1px solid #ffcdd2;\n border-radius: 4px;\n padding: 16px;\n text-align: center;\n }\n </style>\n <div class="ab-test-error">\n ${e}\n </div>\n `,this.dispatchEvent(new CustomEvent("error",{detail:{message:e},bubbles:!0})))}removeConversionListeners(e=!1){this.conversionListeners.forEach(((t,i)=>{("goal"!==i||e)&&(t(),this.conversionListeners.delete(i))}))}cleanup(){this.currentRunId++,this.removeConversionListeners(!0),this.removeWidgetInstance(),this.impressionTracked=!1,this.isRecording=!1,this.renderedVariantId=null,this.widgetReportsGoals=!1,this.readyWidgetHost=null,this.assignment=null}trackConversion(e="custom",t){return this.experimentId&&this.assignment?this.isRecording?this.manager.trackConversion(this.experimentId,this.assignment.variantId,e,t):(z.debug("Conversion not recorded: the visitor has not allowed analytics",{experimentId:this.experimentId}),Promise.resolve()):Promise.reject(new Error("A/B test not initialized"))}getAssignment(){return this.assignment?Object.assign({},this.assignment):null}getExperimentId(){return this.experimentId}static register(){"undefined"!=typeof window&&window.customElements&&(customElements.get("widgetic-abtest")||customElements.define("widgetic-abtest",te))}}te.register();const ie="undefined"!=typeof HTMLElement?HTMLElement:class{};class ne extends ie{constructor(){super(),this.widgetInstance=null,this.isInitialized=!1,this.retryCount=0,this.maxRetries=3,this.retryDelay=1e3,this.experimentId=null,this.selectedLanguage=null,this.translationData=null,this.viewIsWaitingForConsent=!1,this.widgetManager=b(),_.debug("[TranslationElement] Created translation element")}static get observedAttributes(){return["consent"]}attributeChangedCallback(e,t,i){"consent"===e&&t!==i&&this.isAnalyticsAllowed()&&this.viewIsWaitingForConsent&&(this.viewIsWaitingForConsent=!1,this.trackTranslationView())}isAnalyticsAllowed(){const e=this.getAttribute("consent");return null===e||"granted"===e}connectedCallback(){if(this.isInitialized)_.debug("[TranslationElement] Already initialized, skipping");else{if(this.experimentId=this.getAttribute("experiment-id"),!this.experimentId)return _.error("[TranslationElement] Missing experiment-id attribute"),void this.displayError("Missing experiment-id attribute");_.debug(`[TranslationElement] Connected with experiment ID: ${this.experimentId}`),this.initializeTranslation()}}disconnectedCallback(){_.debug("[TranslationElement] Disconnected"),this.cleanup()}initializeTranslation(){return J(this,void 0,void 0,(function*(){try{this.isInitialized=!0;const e=this.detectBrowserLanguages();if(_.debug("[TranslationElement] Detected user languages:",e),this.translationData=yield this.fetchTranslationExperiment(this.experimentId),!this.translationData)throw new Error("Failed to fetch translation experiment data");this.selectedLanguage=this.findBestLanguageMatch(e,this.translationData),_.debug("[TranslationElement] Selected language:",this.selectedLanguage);const t=this.getCompositionForLanguage(this.selectedLanguage);if(!t)throw new Error(`No composition found for language: ${this.selectedLanguage}`);yield this.loadWidget(t),_.info("[TranslationElement] Translation experiment loaded successfully",{experimentId:this.experimentId,selectedLanguage:this.selectedLanguage,compositionId:t})}catch(e){_.error("[TranslationElement] Failed to initialize translation:",e),yield this.handleInitializationError(e)}}))}detectBrowserLanguages(){var e;const t=navigator.language.toLowerCase(),i=((null===(e=navigator.languages)||void 0===e?void 0:e.map((e=>e.toLowerCase())))||[t]).flatMap((e=>{const t=[e];return e.includes("-")&&t.push(e.split("-")[0]),t}));return[...new Set(i)]}fetchTranslationExperiment(e){return J(this,void 0,void 0,(function*(){try{const t=Q(),i=new W({basePath:t,headers:{"X-SDK-Version":"embed-sdk/translations"}}),n=new U(i),s=yield n.getTranslationConfig({id:e});return(null==s?void 0:s.data)||null}catch(e){throw _.error("[TranslationElement] Error fetching translation experiment:",e),e}}))}findBestLanguageMatch(e,t){const i=Object.keys(t.languageCompositions||{}),n=t.rootLanguage||"en";_.debug("[TranslationElement] Available languages:",i),_.debug("[TranslationElement] Root language:",n);for(const t of e)if(i.includes(t))return _.debug("[TranslationElement] Found exact match:",t),t;for(const t of e){const e=t.split("-")[0],n=i.find((t=>t.startsWith(e+"-")||t===e));if(n)return _.debug("[TranslationElement] Found base language match:",n),this.trackFallbackUsage(t,n,"language_family").catch((e=>{_.debug("[TranslationElement] Failed to track language family fallback:",e)})),n}_.debug("[TranslationElement] No matches found, falling back to root language:",n);const s=e[0]||"unknown";return this.trackFallbackUsage(s,n,"root_fallback").catch((e=>{_.debug("[TranslationElement] Failed to track root fallback:",e)})),n}getCompositionForLanguage(e){if(!this.translationData)return null;if(e===this.translationData.rootLanguage)return this.translationData.rootCompositionId;return(this.translationData.languageCompositions||{})[e]||this.translationData.rootCompositionId}loadWidget(e){return J(this,void 0,void 0,(function*(){const t=X(e),i={compositionId:e,renderMode:"auto",displayMode:"inline",resize:"fill-width",width:800,height:600};this.widgetInstance=yield this.widgetManager.registerWidget(t,i,this),this.trackTranslationView()}))}trackTranslationView(){if(!this.isAnalyticsAllowed())return this.viewIsWaitingForConsent=!0,void _.debug("[TranslationElement] View not reported: analytics is not allowed yet");try{const e={experimentId:this.experimentId,selectedLanguage:this.selectedLanguage,userLanguages:this.detectBrowserLanguages(),timestamp:(new Date).toISOString(),userAgent:navigator.userAgent,referrer:document.referrer,url:window.location.href};this.sendAnalytics(e).catch((e=>{_.warn("[TranslationElement] Failed to send analytics:",e)}))}catch(e){_.warn("[TranslationElement] Error in analytics tracking:",e)}}sendAnalytics(e){return J(this,void 0,void 0,(function*(){if(this.isAnalyticsAllowed())try{const t=Q(),i=new W({basePath:t,headers:{"X-SDK-Version":"embed-sdk/translations"}}),n=new U(i);yield n.submitTranslationAnalyticsEvent({id:this.experimentId,submitTranslationAnalyticsEventRequest:e})}catch(e){_.debug("[TranslationElement] Analytics request failed:",e)}}))}trackFallbackUsage(e,t,i){return J(this,void 0,void 0,(function*(){try{const n={eventType:"fallback_used",language:t,compositionId:this.getCompositionForLanguage(t)||"",metadata:{requestedLanguage:e,selectedLanguage:t,fallbackType:i,userAgent:navigator.userAgent,timestamp:(new Date).toISOString()},timestamp:(new Date).toISOString()};yield this.sendAnalytics(n),_.debug("[TranslationElement] Fallback usage tracked:",{requested:e,selected:t,fallbackType:i})}catch(e){_.debug("[TranslationElement] Failed to track fallback usage:",e)}}))}handleInitializationError(e){return J(this,void 0,void 0,(function*(){if(this.retryCount<this.maxRetries){this.retryCount++,_.warn(`[TranslationElement] Retrying initialization (${this.retryCount}/${this.maxRetries}):`,e.message),yield new Promise((e=>setTimeout(e,this.retryDelay*this.retryCount)));try{return void(yield this.initializeTranslation())}catch(e){_.error("[TranslationElement] Retry failed:",e)}}this.displayError(`Translation loading failed: ${e.message}`)}))}displayError(e){this.innerHTML=`\n <div style="\n padding: 1rem;\n border: 1px solid #ef4444;\n border-radius: 0.5rem;\n background-color: #fef2f2;\n color: #dc2626;\n font-family: system-ui, -apple-system, sans-serif;\n font-size: 0.875rem;\n margin: 1rem 0;\n ">\n <strong>Translation Error:</strong> ${e}\n </div>\n `}cleanup(){this.widgetInstance&&(this.widgetManager.unregisterWidget(this.widgetInstance.id),this.widgetInstance=null),this.isInitialized=!1,this.retryCount=0}switchLanguage(e){if(!this.translationData)throw new Error("Translation data not loaded");const t=this.getCompositionForLanguage(e);if(!t)throw new Error(`No composition found for language: ${e}`);return this.cleanup(),this.selectedLanguage=e,this.loadWidget(t)}getSelectedLanguage(){return this.selectedLanguage}getAvailableLanguages(){return this.translationData?Object.keys(this.translationData.languageCompositions||{}):[]}static register(){try{"undefined"!=typeof window&&"undefined"!=typeof customElements&&(customElements.get("widgetic-translations")||(customElements.define("widgetic-translations",ne),_.info("[TranslationElement] Custom element registered")))}catch(e){_.error("[TranslationElement] Failed to register custom element:",e)}}}ne.register();const se=T();"undefined"!=typeof window&&"undefined"!=typeof customElements&&(K(),te.register(),ne.register()),"undefined"!=typeof window&&(window.WidgeticEmbedSDK=se,window.Widgetic={SDK:se,getSDK:T,EmbedSDK:D,config:{API_URL:G.API_URL,API_VERSION:G.API_VERSION,CLIENT_URL:G.CLIENT_URL,PRODUCTION_URL:G.PRODUCTION_URL,NODE_ENV:G.NODE_ENV},log:_,WidgeticWidget:$,registerWidgeticWidget:K,cssDebugger:R,enableCSSDebug:()=>R.enableDebugMode(),disableCSSDebug:()=>R.disableDebugMode(),analyzeWidget:e=>R.analyzeWidget(e),ABTestManager:Y,ABTestElement:te,TranslationElement:ne});export{te as ABTestElement,Y as ABTestManager,D as EmbedSDK,ne as TranslationElement,D as WidgeticEmbedSDK,$ as WidgeticWidget,G as config,R as cssDebugger,se as default,X as generateInstanceId,O as getAuthToken,T as getSDK,_ as log,K as registerWidgeticWidget};
@@ -1 +1 @@
1
- import{_ as e}from"./vendor.js";import{C as t,a as i,y as s,b as n,e as r,z as o,r as a,w as d,B as c}from"./core.js";import{k as l}from"./api.js";import{WidgeticMessenger as u}from"./messaging.js";import{t as v}from"./advanced.js";import"./renderers.js";import"./scanner.js";import"./media.js";import"./display.js";import"./performance.js";import"./security.js";class m{constructor(){this.listeners=new Map}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),this}off(e,t){const i=this.listeners.get(e);return i&&(i.delete(t),0===i.size&&this.listeners.delete(e)),this}addListener(e,t){return this.on(e,t)}removeListener(e,t){return this.off(e,t)}emit(e,...t){const i=this.listeners.get(e);return!(!i||0===i.size)&&(i.forEach((e=>{try{e(...t)}catch(e){}})),!0)}removeAllListeners(e){return e?this.listeners.delete(e):this.listeners.clear(),this}}class p extends m{constructor(){super(),this.assignments=new Map,this.conversionSetups=new Map,this.trackedConversions=new Set,this.visitors=new Map;const e=new t({basePath:i()});this.abTestingApi=new s(e),this.compositionsApi=new n(e),this.widgetManager=l.getInstance(),this.messenger=new u,this.setupEventListeners()}static getInstance(){return p.instance||(p.instance=new p),p.instance}setupEventListeners(){this.widgetManager.addEventListener("widget_ready",(e=>{this.setupWidgetConversionTracking(e.widgetId)})),this.widgetManager.addEventListener("custom_event",(e=>{this.handleWidgetCustomEvent(e)})),this.widgetManager.addEventListener("media_play",(e=>{this.handleMediaEvent("plays",e)})),this.widgetManager.addEventListener("form_submit",(e=>{this.handleFormEvent("submissions",e)})),this.widgetManager.addEventListener("widget_click",(e=>{this.handleClickEvent(e)}))}getTestConfig(t){return e(this,void 0,void 0,(function*(){var i;try{const s=yield this.abTestingApi.getABTestConfig({id:t});if(!s)return r.warn("A/B test not found",{experimentId:t}),null;const n=(yield Promise.all((s.variants||[]).map((t=>e(this,void 0,void 0,(function*(){try{const e=t.composition_id||t.compositionId||"";return{id:t.id||"",compositionId:e,embedCode:this.generateEmbedCode(e),trafficPercentage:t.traffic_percentage||t.trafficPercentage||0,goalTarget:t.goal_target||t.goalTarget||null}}catch(e){return r.error("Failed to fetch composition for variant",{variantId:t.id,compositionId:t.compositionId,error:e}),null}})))))).filter((e=>null!==e));if(0===n.length)return r.warn("No valid variants found for A/B test",{experimentId:t}),null;const o={experimentId:s.test_id||t,isActive:"running"===s.status,winningVariant:void 0,variants:n,successMetrics:s.success_metrics||["impressions"],primaryMetric:s.primary_metric||(null===(i=s.success_metrics)||void 0===i?void 0:i[0])||"impressions"};return r.info("A/B test config loaded",{experimentId:t,config:o}),o}catch(e){return e&&"object"==typeof e&&"status"in e&&404===e.status?(r.warn("A/B test not found",{experimentId:t}),null):(r.error("Failed to load A/B test config",{experimentId:t,error:e}),null)}}))}resolveVisitor(e){return{userId:(null==e?void 0:e.userId)||void 0,sessionId:(null==e?void 0:e.sessionId)||o()}}visitorFor(e,t){var i;return(null==t?void 0:t.userId)||(null==t?void 0:t.sessionId)?this.resolveVisitor(t):null!==(i=this.visitors.get(e))&&void 0!==i?i:this.resolveVisitor()}readStoredAssignment(e,t){try{const i=a(`ab_test_${e}`);if(!i)return null;const s=JSON.parse(i),n=t.variants.find((e=>e.id===s.variantId));return n?{variantId:n.id,compositionId:n.compositionId,embedCode:n.embedCode,goalTarget:n.goalTarget,recorded:!0===s.recorded}:(r.info("Stored A/B test assignment is no longer a version of the test; assigning again",{experimentId:e}),null)}catch(t){return r.warn("Stored A/B test assignment is unreadable; assigning again",{experimentId:e,error:t}),null}}storeAssignment(e,t){d(`ab_test_${e}`,JSON.stringify(t)),this.assignments.set(e,t)}getVariantAssignment(t,i){return e(this,void 0,void 0,(function*(){try{const e=yield this.getTestConfig(t);if(!e)return null;const s=this.resolveVisitor(i);if(this.visitors.set(t,s),e.winningVariant){const i=e.variants.find((t=>t.id===e.winningVariant));if(i){const e={variantId:i.id,compositionId:i.compositionId,embedCode:i.embedCode,goalTarget:i.goalTarget};return this.storeAssignment(t,e),e}}let n=this.readStoredAssignment(t,e);if(!n){const i=this.selectVariant(t,e.variants,s);if(!i)return null;n={variantId:i.id,compositionId:i.compositionId,embedCode:i.embedCode,goalTarget:i.goalTarget,recorded:!1},this.storeAssignment(t,n)}if(!n.recorded){(yield this.createAssignment(t,n,s))&&(n=Object.assign(Object.assign({},n),{recorded:!0}),this.storeAssignment(t,n))}return this.assignments.set(t,n),yield this.setupConversionTracking(t,e,n),n}catch(e){return r.error("Failed to get variant assignment",{experimentId:t,error:e}),null}}))}setupConversionTracking(t,i,s){return e(this,void 0,void 0,(function*(){var e,n,o;try{const a=[i.primaryMetric],d=yield this.findTrackingTargets(s.compositionId,a),c={experimentId:t,variantId:s.variantId,metrics:a,trackingTargets:d,primaryMetric:i.primaryMetric,goalTarget:null!==(e=s.goalTarget)&&void 0!==e?e:null,widgetReportsGoals:null!==(o=null===(n=this.conversionSetups.get(t))||void 0===n?void 0:n.widgetReportsGoals)&&void 0!==o&&o};this.conversionSetups.set(t,c),r.debug("Conversion tracking setup complete",{experimentId:t,trackedMetrics:a,trackingTargets:d})}catch(e){r.error("Failed to setup conversion tracking",{experimentId:t,error:e})}}))}getPrimaryMetric(e){var t,i;return null!==(i=null===(t=this.conversionSetups.get(e))||void 0===t?void 0:t.primaryMetric)&&void 0!==i?i:null}setWidgetReportsGoals(e,t){const i=this.conversionSetups.get(e);i&&(i.widgetReportsGoals=t,r.debug("Widget goal reporting capability set",{experimentId:e,widgetReportsGoals:t}))}findTrackingTargets(t,i){return e(this,void 0,void 0,(function*(){try{const e={},t={clicks:["button","a","[data-click-track]","[onclick]"],conversions:["form",'button[type="submit"]',"[data-conversion]"],plays:["video","audio","[data-play]",".play-button"],submissions:["form","[data-form]"],downloads:["a[download]","[data-download]"],signups:["form","[data-signup]",".signup-form"]};for(const s of i){const i=t[s]||[];e[s]=i}return e}catch(e){return r.error("Failed to find tracking targets",{compositionId:t,error:e}),{}}}))}selectorExistsInContent(e,t){const i=e.toLowerCase();if(t.startsWith("[")&&t.endsWith("]")){const e=t.slice(1,-1);return i.includes(e)}if(t.startsWith(".")){const e=t.slice(1);return i.includes(`class="${e}"`)||i.includes(`class='${e}'`)}return i.includes(`<${t}`)}setupWidgetConversionTracking(t){return e(this,void 0,void 0,(function*(){for(const[e,i]of Array.from(this.conversionSetups.entries()))try{if(!this.widgetManager.getWidget(t))continue;const s=this.messenger.createWidgetController(t);i.metrics.includes("clicks")&&(yield this.setupClickTracking(s,e,i.variantId)),(i.metrics.includes("submissions")||i.metrics.includes("conversions"))&&(yield this.setupFormTracking(s,e,i.variantId)),i.metrics.includes("plays")&&(yield this.setupMediaTracking(s,e,i.variantId)),r.debug("Widget conversion tracking setup",{widgetId:t,experimentId:e})}catch(i){r.error("Failed to setup widget conversion tracking",{widgetId:t,experimentId:e,error:i})}}))}setupClickTracking(t,i,s){return e(this,void 0,void 0,(function*(){t.subscribe("click",(t=>e(this,void 0,void 0,(function*(){yield this.trackConversion(i,s,"clicks",{element:t.element,timestamp:t.timestamp})})))),yield t.callFunction("setupEventListener","click",(e=>{var t;this.trackConversion(i,s,"clicks",{target:null===(t=e.target)||void 0===t?void 0:t.tagName,timestamp:Date.now()})}))}))}setupFormTracking(t,i,s){return e(this,void 0,void 0,(function*(){t.subscribe("form-submit",(t=>e(this,void 0,void 0,(function*(){yield this.trackConversion(i,s,"submissions",{formData:t.formData,timestamp:t.timestamp})})))),t.subscribe("conversion",(t=>e(this,void 0,void 0,(function*(){yield this.trackConversion(i,s,"conversions",{conversionType:t.type,value:t.value,timestamp:t.timestamp})}))))}))}setupMediaTracking(t,i,s){return e(this,void 0,void 0,(function*(){t.subscribe("media-play",(t=>e(this,void 0,void 0,(function*(){yield this.trackConversion(i,s,"plays",{mediaType:t.mediaType,duration:t.duration,timestamp:t.timestamp})}))))}))}handleWidgetCustomEvent(t){return e(this,void 0,void 0,(function*(){var e;for(const[i,s]of Array.from(this.conversionSetups.entries()))if((null===(e=t.data)||void 0===e?void 0:e.experimentId)===i){const e=t.data.conversionType||"custom";yield this.trackConversion(i,s.variantId,e,t.data)}}))}handleMediaEvent(t,i){return e(this,void 0,void 0,(function*(){for(const[e,s]of Array.from(this.conversionSetups.entries()))s.metrics.includes(t)&&(yield this.trackConversion(e,s.variantId,t,i.data))}))}handleFormEvent(t,i){return e(this,void 0,void 0,(function*(){for(const[e,s]of Array.from(this.conversionSetups.entries()))s.metrics.includes(t)&&(yield this.trackConversion(e,s.variantId,t,i.data))}))}handleClickEvent(t){return e(this,void 0,void 0,(function*(){for(const[e,i]of Array.from(this.conversionSetups.entries()))i.metrics.includes("clicks")&&(yield this.trackConversion(e,i.variantId,"clicks",t.data))}))}conversionKeyFor(e,t){return`ab_converted_${e}_${t.userId||t.sessionId}`}trackConversion(t,i,s,n,o){return e(this,void 0,void 0,(function*(){const e=this.conversionSetups.get(t),c=this.visitorFor(t,o),l=this.conversionKeyFor(t,c);let u=!1;try{if(!e)return void r.warn("Conversion ignored: the test has no assignment in this page yet",{experimentId:t,conversionType:s});if(s!==e.primaryMetric)return void r.debug("Conversion ignored: not the goal this test measures",{experimentId:t,conversionType:s,primaryMetric:e.primaryMetric});const o=null==n?void 0:n.goalTarget;if(e.goalTarget&&e.widgetReportsGoals&&o!==e.goalTarget)return void r.debug("Conversion ignored: not the element this version measures",{experimentId:t,goalTarget:e.goalTarget,reportedGoalTarget:o});if(this.trackedConversions.has(l)||"1"===a(l))return r.debug("Conversion already tracked for this visitor",{experimentId:t,variantId:i,conversionType:s}),void this.trackedConversions.add(l);this.trackedConversions.add(l),u=!0;const m={experimentId:t,variantId:e.variantId||i,userId:c.userId,sessionId:c.sessionId,conversionType:s,goalTarget:e.goalTarget||void 0,timestamp:(new Date).toISOString()},p={event_type:"conversion",data:v(m)};yield this.abTestingApi.trackABTestEvent({trackABTestEventRequest:p}),d(l,"1"),this.emit("conversion",{experimentId:t,variantId:i,conversionType:s,data:n}),r.info("Conversion tracked",{experimentId:t,variantId:i,conversionType:s,data:n})}catch(e){u&&this.trackedConversions.delete(l),r.error("Failed to track conversion",{experimentId:t,variantId:i,conversionType:s,error:e})}}))}trackImpression(t,i,s){return e(this,void 0,void 0,(function*(){try{const e=this.visitorFor(t,s),n={experimentId:t,variantId:i,userId:e.userId,sessionId:e.sessionId,timestamp:(new Date).toISOString()},o={event_type:"impression",data:v(n)};yield this.abTestingApi.trackABTestEvent({trackABTestEventRequest:o}),r.debug("Impression tracked",{experimentId:t,variantId:i})}catch(e){r.error("Failed to track impression",{experimentId:t,variantId:i,error:e})}}))}validateGoalTracking(t,i){return e(this,void 0,void 0,(function*(){const e=[],s=[];try{for(const s of t){const t=yield this.validateVariantCapabilities(s,i);e.push(...t)}if(e.length>0){const t=Array.from(new Set(e.map((e=>e.metric))));s.push(`Consider adding trackable elements to your compositions for: ${t.join(", ")}`),t.includes("clicks")&&s.push("Add clickable elements like buttons, links, or interactive components"),t.includes("submissions")&&s.push("Add form elements to track form submissions"),t.includes("plays")&&s.push("Add media elements (audio/video) to track media plays"),t.includes("conversions")&&s.push("Implement custom conversion tracking using widgetic:conversion events")}const n=0===e.length;return r.info("Goal tracking validation completed",{variants:t.length,successMetrics:i,issues:e.length,isValid:n}),{isValid:n,issues:e,recommendations:s}}catch(e){return r.error("Goal tracking validation failed",{error:e}),{isValid:!1,issues:[{variant:"all",metric:"system",reason:"Validation system error"}],recommendations:["Please try again or contact support"]}}}))}validateVariantCapabilities(t,i){return e(this,void 0,void 0,(function*(){const e=[];try{const s=document.createElement("div");s.style.cssText="position: absolute; top: -9999px; left: -9999px; width: 1px; height: 1px;",document.body.appendChild(s);try{const n={compositionId:t.composition_id,renderMode:"auto",displayMode:"inline",resize:"fill-width",width:1,height:1},o=`validation_${t.composition_id}_${Date.now()}`;if(yield this.widgetManager.registerWidget(o,n,s)){const s=this.messenger.getWidgetController(o);let n=null;if(s)try{n=yield s.callFunction("getCapabilities",[])}catch(e){r.warn("Widget does not expose getCapabilities method",{compositionId:t.composition_id})}for(const s of i){const i=this.checkMetricSupport(t,s,n);i&&e.push(i)}yield this.widgetManager.unregisterWidget(o)}else for(const s of i)e.push({variant:t.name,metric:s,reason:"Widget failed to load for validation"})}finally{document.body.removeChild(s)}}catch(s){r.error("Failed to validate variant capabilities",{variant:t.name,error:s});for(const s of i)e.push({variant:t.name,metric:s,reason:"Validation error occurred"})}return e}))}checkMetricSupport(e,t,i){var s;if(!i)return{variant:e.name,metric:t,reason:"Widget capabilities could not be determined"};switch(t){case"clicks":if(!this.hasClickableCapabilities(i))return{variant:e.name,metric:t,reason:"No clickable elements or interactive capabilities found"};break;case"submissions":if(!i.textCapabilities||!(null===(s=i.textCapabilities.fields)||void 0===s?void 0:s.length))return{variant:e.name,metric:t,reason:"No form fields or text input capabilities found"};break;case"plays":if(!i.mediaCapabilities||!i.mediaCapabilities.supportsPlay)return{variant:e.name,metric:t,reason:"No media playback capabilities found"};break;case"conversions":if("static"===i.type||!i.supportsEvents)return{variant:e.name,metric:t,reason:"Widget may not support custom conversion events"};break;default:return{variant:e.name,metric:t,reason:`Unknown success metric: ${t}`}}return null}hasClickableCapabilities(e){var t,i,s,n;if(["interactive","form","media","gallery"].includes(e.type))return!0;if(null===(t=e.mediaCapabilities)||void 0===t?void 0:t.supportsPlay)return!0;if(null===(i=e.contentCapabilities)||void 0===i?void 0:i.supportsNavigation)return!0;if(null===(n=null===(s=e.textCapabilities)||void 0===s?void 0:s.fields)||void 0===n?void 0:n.length)return!0;const r=["play","pause","next","previous","goTo","setText","submit","click","interact"];return!!e.exposedFunctions&&r.some((t=>e.exposedFunctions.includes(t)))}selectVariant(e,t,i){return c(t,i.userId||i.sessionId,e)}createAssignment(t,i,s){return e(this,void 0,void 0,(function*(){try{const e="undefined"!=typeof navigator?navigator.userAgent:void 0,n={experimentId:t,variantId:i.variantId,userId:s.userId,sessionId:s.sessionId,userAgent:e,deviceType:this.detectDeviceType(e)},o=v(n);return yield this.abTestingApi.createABTestAssignment({createABTestAssignmentRequest:o}),r.debug("Assignment created in backend",{experimentId:t,variantId:i.variantId}),!0}catch(e){return r.error("Failed to create assignment in backend",{experimentId:t,error:e}),!1}}))}generateEmbedCode(e){return`<widgetic-widget composition-id="${e}"></widgetic-widget>`}getSessionId(){return o()}detectDeviceType(e){if(!e)return"desktop";const t=e.toLowerCase();return/tablet|ipad|playbook|silk/.test(t)?"tablet":/mobile|iphone|ipod|android|blackberry|opera|mini|windows\sce|palm|smartphone|iemobile/.test(t)?"mobile":"desktop"}}p.instance=null;export{p as ABTestManager};
1
+ import{_ as e}from"./vendor.js";import{C as t,a as i,y as s,b as n,e as r,r as o,z as a,q as d,B as c,w as l,G as u}from"./core.js";import{k as m}from"./api.js";import{WidgeticMessenger as v}from"./messaging.js";import{d as p}from"./advanced.js";import"./renderers.js";import"./scanner.js";import"./media.js";import"./display.js";import"./performance.js";import"./security.js";class g{constructor(){this.listeners=new Map}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),this}off(e,t){const i=this.listeners.get(e);return i&&(i.delete(t),0===i.size&&this.listeners.delete(e)),this}addListener(e,t){return this.on(e,t)}removeListener(e,t){return this.off(e,t)}emit(e,...t){const i=this.listeners.get(e);return!(!i||0===i.size)&&(i.forEach((e=>{try{e(...t)}catch(e){}})),!0)}removeAllListeners(e){return e?this.listeners.delete(e):this.listeners.clear(),this}}class h extends g{constructor(){super(),this.assignments=new Map,this.conversionSetups=new Map,this.trackedConversions=new Set,this.visitors=new Map,this.heldExperiments=new Set;const e=new t({basePath:i()});this.abTestingApi=new s(e),this.compositionsApi=new n(e),this.widgetManager=m.getInstance(),this.messenger=new v,this.setupEventListeners()}static getInstance(){return h.instance||(h.instance=new h),h.instance}setupEventListeners(){this.widgetManager.addEventListener("widget_ready",(e=>{this.setupWidgetConversionTracking(e.widgetId)})),this.widgetManager.addEventListener("custom_event",(e=>{this.handleWidgetCustomEvent(e)})),this.widgetManager.addEventListener("media_play",(e=>{this.handleMediaEvent("plays",e)})),this.widgetManager.addEventListener("form_submit",(e=>{this.handleFormEvent("submissions",e)})),this.widgetManager.addEventListener("widget_click",(e=>{this.handleClickEvent(e)}))}getTestConfig(t){return e(this,void 0,void 0,(function*(){var i;try{const s=yield this.abTestingApi.getABTestConfig({id:t});if(!s)return r.warn("A/B test not found",{experimentId:t}),null;const n=(yield Promise.all((s.variants||[]).map((t=>e(this,void 0,void 0,(function*(){try{const e=t.composition_id||t.compositionId||"";return{id:t.id||"",compositionId:e,embedCode:this.generateEmbedCode(e),trafficPercentage:t.traffic_percentage||t.trafficPercentage||0,goalTarget:t.goal_target||t.goalTarget||null}}catch(e){return r.error("Failed to fetch composition for variant",{variantId:t.id,compositionId:t.compositionId,error:e}),null}})))))).filter((e=>null!==e));if(0===n.length)return r.warn("No valid variants found for A/B test",{experimentId:t}),null;const o={experimentId:s.test_id||t,isActive:"running"===s.status,winningVariant:void 0,variants:n,successMetrics:s.success_metrics||["impressions"],primaryMetric:s.primary_metric||(null===(i=s.success_metrics)||void 0===i?void 0:i[0])||"impressions"};return r.info("A/B test config loaded",{experimentId:t,config:o}),o}catch(e){return e&&"object"==typeof e&&"status"in e&&404===e.status?(r.warn("A/B test not found",{experimentId:t}),null):(r.error("Failed to load A/B test config",{experimentId:t,error:e}),null)}}))}holdRecording(e){this.heldExperiments.has(e)||(this.heldExperiments.add(e),r.debug("A/B test recording is held until analytics is allowed",{experimentId:e}))}resumeRecording(e){this.heldExperiments.delete(e)&&r.debug("A/B test recording resumed: analytics is allowed",{experimentId:e})}isRecordingHeld(e){return this.heldExperiments.has(e)}forgetVisitor(e,t){const i=this.visitors.get(e),s=i?i.userId||i.sessionId:(null==t?void 0:t.userId)||o(a);if(d(`ab_test_${e}`),s){const t=this.conversionKeyForVisitorKey(e,s);d(t),this.trackedConversions.delete(t)}this.assignments.delete(e),this.visitors.delete(e),this.conversionSetups.delete(e),0===this.visitors.size&&d(a),r.debug("A/B test visitor forgotten",{experimentId:e})}getUnrecordedVariant(t){return e(this,void 0,void 0,(function*(){try{const e=yield this.getTestConfig(t),i=null==e?void 0:e.variants[0];return e&&i?{variantId:i.id,compositionId:i.compositionId,embedCode:i.embedCode,goalTarget:null,recorded:!1}:null}catch(e){return r.error("Failed to get the original version of the A/B test",{experimentId:t,error:e}),null}}))}resolveVisitor(e){return{userId:(null==e?void 0:e.userId)||void 0,sessionId:(null==e?void 0:e.sessionId)||c()}}visitorFor(e,t){var i;return(null==t?void 0:t.userId)||(null==t?void 0:t.sessionId)?this.resolveVisitor(t):null!==(i=this.visitors.get(e))&&void 0!==i?i:this.resolveVisitor()}readStoredAssignment(e,t){try{const i=o(`ab_test_${e}`);if(!i)return null;const s=JSON.parse(i),n=t.variants.find((e=>e.id===s.variantId));return n?{variantId:n.id,compositionId:n.compositionId,embedCode:n.embedCode,goalTarget:n.goalTarget,recorded:!0===s.recorded}:(r.info("Stored A/B test assignment is no longer a version of the test; assigning again",{experimentId:e}),null)}catch(t){return r.warn("Stored A/B test assignment is unreadable; assigning again",{experimentId:e,error:t}),null}}storeAssignment(e,t){l(`ab_test_${e}`,JSON.stringify(t)),this.assignments.set(e,t)}getVariantAssignment(t,i){return e(this,void 0,void 0,(function*(){if(this.isRecordingHeld(t))return r.warn("Variant assignment refused: the visitor has not allowed analytics",{experimentId:t}),null;try{const e=yield this.getTestConfig(t);if(!e)return null;if(this.isRecordingHeld(t))return r.debug("Variant assignment dropped: the visitor said no to analytics meanwhile",{experimentId:t}),null;const s=this.resolveVisitor(i);if(this.visitors.set(t,s),e.winningVariant){const i=e.variants.find((t=>t.id===e.winningVariant));if(i){const e={variantId:i.id,compositionId:i.compositionId,embedCode:i.embedCode,goalTarget:i.goalTarget};return this.storeAssignment(t,e),e}}let n=this.readStoredAssignment(t,e);if(!n){const i=this.selectVariant(t,e.variants,s);if(!i)return null;n={variantId:i.id,compositionId:i.compositionId,embedCode:i.embedCode,goalTarget:i.goalTarget,recorded:!1},this.storeAssignment(t,n)}if(!n.recorded){const e=yield this.createAssignment(t,n,s);if(this.isRecordingHeld(t))return r.debug("Assignment not kept: the visitor said no to analytics meanwhile",{experimentId:t}),null;e&&(n=Object.assign(Object.assign({},n),{recorded:!0}),this.storeAssignment(t,n))}return this.assignments.set(t,n),yield this.setupConversionTracking(t,e,n),n}catch(e){return r.error("Failed to get variant assignment",{experimentId:t,error:e}),null}}))}setupConversionTracking(t,i,s){return e(this,void 0,void 0,(function*(){var e,n,o;try{const a=[i.primaryMetric],d=yield this.findTrackingTargets(s.compositionId,a),c={experimentId:t,variantId:s.variantId,metrics:a,trackingTargets:d,primaryMetric:i.primaryMetric,goalTarget:null!==(e=s.goalTarget)&&void 0!==e?e:null,widgetReportsGoals:null!==(o=null===(n=this.conversionSetups.get(t))||void 0===n?void 0:n.widgetReportsGoals)&&void 0!==o&&o};this.conversionSetups.set(t,c),r.debug("Conversion tracking setup complete",{experimentId:t,trackedMetrics:a,trackingTargets:d})}catch(e){r.error("Failed to setup conversion tracking",{experimentId:t,error:e})}}))}getPrimaryMetric(e){var t,i;return null!==(i=null===(t=this.conversionSetups.get(e))||void 0===t?void 0:t.primaryMetric)&&void 0!==i?i:null}setWidgetReportsGoals(e,t){const i=this.conversionSetups.get(e);i&&(i.widgetReportsGoals=t,r.debug("Widget goal reporting capability set",{experimentId:e,widgetReportsGoals:t}))}findTrackingTargets(t,i){return e(this,void 0,void 0,(function*(){try{const e={},t={clicks:["button","a","[data-click-track]","[onclick]"],conversions:["form",'button[type="submit"]',"[data-conversion]"],plays:["video","audio","[data-play]",".play-button"],submissions:["form","[data-form]"],downloads:["a[download]","[data-download]"],signups:["form","[data-signup]",".signup-form"]};for(const s of i){const i=t[s]||[];e[s]=i}return e}catch(e){return r.error("Failed to find tracking targets",{compositionId:t,error:e}),{}}}))}selectorExistsInContent(e,t){const i=e.toLowerCase();if(t.startsWith("[")&&t.endsWith("]")){const e=t.slice(1,-1);return i.includes(e)}if(t.startsWith(".")){const e=t.slice(1);return i.includes(`class="${e}"`)||i.includes(`class='${e}'`)}return i.includes(`<${t}`)}setupWidgetConversionTracking(t){return e(this,void 0,void 0,(function*(){for(const[e,i]of Array.from(this.conversionSetups.entries()))try{if(!this.widgetManager.getWidget(t))continue;const s=this.messenger.createWidgetController(t);i.metrics.includes("clicks")&&(yield this.setupClickTracking(s,e,i.variantId)),(i.metrics.includes("submissions")||i.metrics.includes("conversions"))&&(yield this.setupFormTracking(s,e,i.variantId)),i.metrics.includes("plays")&&(yield this.setupMediaTracking(s,e,i.variantId)),r.debug("Widget conversion tracking setup",{widgetId:t,experimentId:e})}catch(i){r.error("Failed to setup widget conversion tracking",{widgetId:t,experimentId:e,error:i})}}))}setupClickTracking(t,i,s){return e(this,void 0,void 0,(function*(){t.subscribe("click",(t=>e(this,void 0,void 0,(function*(){yield this.trackConversion(i,s,"clicks",{element:t.element,timestamp:t.timestamp})})))),yield t.callFunction("setupEventListener","click",(e=>{var t;this.trackConversion(i,s,"clicks",{target:null===(t=e.target)||void 0===t?void 0:t.tagName,timestamp:Date.now()})}))}))}setupFormTracking(t,i,s){return e(this,void 0,void 0,(function*(){t.subscribe("form-submit",(t=>e(this,void 0,void 0,(function*(){yield this.trackConversion(i,s,"submissions",{formData:t.formData,timestamp:t.timestamp})})))),t.subscribe("conversion",(t=>e(this,void 0,void 0,(function*(){yield this.trackConversion(i,s,"conversions",{conversionType:t.type,value:t.value,timestamp:t.timestamp})}))))}))}setupMediaTracking(t,i,s){return e(this,void 0,void 0,(function*(){t.subscribe("media-play",(t=>e(this,void 0,void 0,(function*(){yield this.trackConversion(i,s,"plays",{mediaType:t.mediaType,duration:t.duration,timestamp:t.timestamp})}))))}))}handleWidgetCustomEvent(t){return e(this,void 0,void 0,(function*(){var e;for(const[i,s]of Array.from(this.conversionSetups.entries()))if((null===(e=t.data)||void 0===e?void 0:e.experimentId)===i){const e=t.data.conversionType||"custom";yield this.trackConversion(i,s.variantId,e,t.data)}}))}handleMediaEvent(t,i){return e(this,void 0,void 0,(function*(){for(const[e,s]of Array.from(this.conversionSetups.entries()))s.metrics.includes(t)&&(yield this.trackConversion(e,s.variantId,t,i.data))}))}handleFormEvent(t,i){return e(this,void 0,void 0,(function*(){for(const[e,s]of Array.from(this.conversionSetups.entries()))s.metrics.includes(t)&&(yield this.trackConversion(e,s.variantId,t,i.data))}))}handleClickEvent(t){return e(this,void 0,void 0,(function*(){for(const[e,i]of Array.from(this.conversionSetups.entries()))i.metrics.includes("clicks")&&(yield this.trackConversion(e,i.variantId,"clicks",t.data))}))}conversionKeyFor(e,t){return this.conversionKeyForVisitorKey(e,t.userId||t.sessionId)}conversionKeyForVisitorKey(e,t){return`ab_converted_${e}_${t}`}trackConversion(t,i,s,n,a){return e(this,void 0,void 0,(function*(){if(this.isRecordingHeld(t))return void r.debug("Conversion ignored: the visitor has not allowed analytics",{experimentId:t,conversionType:s});const e=this.conversionSetups.get(t),d=this.visitorFor(t,a),c=this.conversionKeyFor(t,d);let u=!1;try{if(!e)return void r.warn("Conversion ignored: the test has no assignment in this page yet",{experimentId:t,conversionType:s});if(s!==e.primaryMetric)return void r.debug("Conversion ignored: not the goal this test measures",{experimentId:t,conversionType:s,primaryMetric:e.primaryMetric});const a=null==n?void 0:n.goalTarget;if(e.goalTarget&&e.widgetReportsGoals&&a!==e.goalTarget)return void r.debug("Conversion ignored: not the element this version measures",{experimentId:t,goalTarget:e.goalTarget,reportedGoalTarget:a});if(this.trackedConversions.has(c)||"1"===o(c))return r.debug("Conversion already tracked for this visitor",{experimentId:t,variantId:i,conversionType:s}),void this.trackedConversions.add(c);this.trackedConversions.add(c),u=!0;const m={experimentId:t,variantId:e.variantId||i,userId:d.userId,sessionId:d.sessionId,conversionType:s,goalTarget:e.goalTarget||void 0,timestamp:new Date},v={event_type:"conversion",data:p(m)};yield this.abTestingApi.trackABTestEvent({trackABTestEventRequest:v}),l(c,"1"),this.emit("conversion",{experimentId:t,variantId:i,conversionType:s,data:n}),r.info("Conversion tracked",{experimentId:t,variantId:i,conversionType:s,data:n})}catch(e){u&&this.trackedConversions.delete(c),r.error("Failed to track conversion",{experimentId:t,variantId:i,conversionType:s,error:e})}}))}trackImpression(t,i,s){return e(this,void 0,void 0,(function*(){if(this.isRecordingHeld(t))r.debug("Impression ignored: the visitor has not allowed analytics",{experimentId:t,variantId:i});else try{const e=this.visitorFor(t,s),n={experimentId:t,variantId:i,userId:e.userId,sessionId:e.sessionId,timestamp:new Date},o={event_type:"impression",data:p(n)};yield this.abTestingApi.trackABTestEvent({trackABTestEventRequest:o}),r.debug("Impression tracked",{experimentId:t,variantId:i})}catch(e){r.error("Failed to track impression",{experimentId:t,variantId:i,error:e})}}))}validateGoalTracking(t,i){return e(this,void 0,void 0,(function*(){const e=[],s=[];try{for(const s of t){const t=yield this.validateVariantCapabilities(s,i);e.push(...t)}if(e.length>0){const t=Array.from(new Set(e.map((e=>e.metric))));s.push(`Consider adding trackable elements to your compositions for: ${t.join(", ")}`),t.includes("clicks")&&s.push("Add clickable elements like buttons, links, or interactive components"),t.includes("submissions")&&s.push("Add form elements to track form submissions"),t.includes("plays")&&s.push("Add media elements (audio/video) to track media plays"),t.includes("conversions")&&s.push("Implement custom conversion tracking using widgetic:conversion events")}const n=0===e.length;return r.info("Goal tracking validation completed",{variants:t.length,successMetrics:i,issues:e.length,isValid:n}),{isValid:n,issues:e,recommendations:s}}catch(e){return r.error("Goal tracking validation failed",{error:e}),{isValid:!1,issues:[{variant:"all",metric:"system",reason:"Validation system error"}],recommendations:["Please try again or contact support"]}}}))}validateVariantCapabilities(t,i){return e(this,void 0,void 0,(function*(){const e=[];try{const s=document.createElement("div");s.style.cssText="position: absolute; top: -9999px; left: -9999px; width: 1px; height: 1px;",document.body.appendChild(s);try{const n={compositionId:t.composition_id,renderMode:"auto",displayMode:"inline",resize:"fill-width",width:1,height:1},o=`validation_${t.composition_id}_${Date.now()}`;if(yield this.widgetManager.registerWidget(o,n,s)){const s=this.messenger.getWidgetController(o);let n=null;if(s)try{n=yield s.callFunction("getCapabilities",[])}catch(e){r.warn("Widget does not expose getCapabilities method",{compositionId:t.composition_id})}for(const s of i){const i=this.checkMetricSupport(t,s,n);i&&e.push(i)}yield this.widgetManager.unregisterWidget(o)}else for(const s of i)e.push({variant:t.name,metric:s,reason:"Widget failed to load for validation"})}finally{document.body.removeChild(s)}}catch(s){r.error("Failed to validate variant capabilities",{variant:t.name,error:s});for(const s of i)e.push({variant:t.name,metric:s,reason:"Validation error occurred"})}return e}))}checkMetricSupport(e,t,i){var s;if(!i)return{variant:e.name,metric:t,reason:"Widget capabilities could not be determined"};switch(t){case"clicks":if(!this.hasClickableCapabilities(i))return{variant:e.name,metric:t,reason:"No clickable elements or interactive capabilities found"};break;case"submissions":if(!i.textCapabilities||!(null===(s=i.textCapabilities.fields)||void 0===s?void 0:s.length))return{variant:e.name,metric:t,reason:"No form fields or text input capabilities found"};break;case"plays":if(!i.mediaCapabilities||!i.mediaCapabilities.supportsPlay)return{variant:e.name,metric:t,reason:"No media playback capabilities found"};break;case"conversions":if("static"===i.type||!i.supportsEvents)return{variant:e.name,metric:t,reason:"Widget may not support custom conversion events"};break;default:return{variant:e.name,metric:t,reason:`Unknown success metric: ${t}`}}return null}hasClickableCapabilities(e){var t,i,s,n;if(["interactive","form","media","gallery"].includes(e.type))return!0;if(null===(t=e.mediaCapabilities)||void 0===t?void 0:t.supportsPlay)return!0;if(null===(i=e.contentCapabilities)||void 0===i?void 0:i.supportsNavigation)return!0;if(null===(n=null===(s=e.textCapabilities)||void 0===s?void 0:s.fields)||void 0===n?void 0:n.length)return!0;const r=["play","pause","next","previous","goTo","setText","submit","click","interact"];return!!e.exposedFunctions&&r.some((t=>e.exposedFunctions.includes(t)))}selectVariant(e,t,i){return u(t,i.userId||i.sessionId,e)}createAssignment(t,i,s){return e(this,void 0,void 0,(function*(){try{const e="undefined"!=typeof navigator?navigator.userAgent:void 0,n={experimentId:t,variantId:i.variantId,userId:s.userId,sessionId:s.sessionId,userAgent:e,deviceType:this.detectDeviceType(e)},o=p(n);return yield this.abTestingApi.createABTestAssignment({createABTestAssignmentRequest:o}),r.debug("Assignment created in backend",{experimentId:t,variantId:i.variantId}),!0}catch(e){return r.error("Failed to create assignment in backend",{experimentId:t,error:e}),!1}}))}generateEmbedCode(e){return`<widgetic-widget composition-id="${e}"></widgetic-widget>`}getSessionId(){return c()}detectDeviceType(e){if(!e)return"desktop";const t=e.toLowerCase();return/tablet|ipad|playbook|silk/.test(t)?"tablet":/mobile|iphone|ipod|android|blackberry|opera|mini|windows\sce|palm|smartphone|iemobile/.test(t)?"mobile":"desktop"}}h.instance=null;export{h as ABTestManager};
@@ -1 +1 @@
1
- import{_ as t}from"./vendor.js";import{C as e,o as i,b as o,l as n,d as s,p as r}from"./core.js";import{getMessenger as a}from"./messaging.js";const d=t=>null!==t&&"object"==typeof t&&!Array.isArray(t)&&"[object Object]"===Object.prototype.toString.call(t);function c(t){if(Array.isArray(t))return t.map(c);if(!d(t))return t;const e={};for(const[i,o]of Object.entries(t)){e[i.replace(/[_-](\w)/g,((t,e)=>e?e.toUpperCase():""))]=Array.isArray(o)?o.map(c):d(o)?c(o):o}return e}function l(t){if(Array.isArray(t))return t.map(l);if(!d(t))return t;const e={};for(const[i,o]of Object.entries(t)){e[i.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[\s-]+/g,"_").toLowerCase()]=Array.isArray(o)?o.map(l):d(o)?l(o):o}return e}class h{constructor(){this.sessionCache=null,this.sessionCacheExpiry=0,this.ownershipCache=new Map;const t=r(),n=new e({basePath:t.basePath,apiKey:t.apiKey,credentials:"include"});this.authApi=new i(n),this.compositionsApi=new o(n)}checkAuthentication(){return t(this,void 0,void 0,(function*(){try{if(this.sessionCache&&Date.now()<this.sessionCacheExpiry)return{isAuthenticated:!0,session:this.sessionCache,user:this.sessionCache.user,canEdit:!0};const t=c(yield this.authApi.getSession());return t&&t.accessToken&&t.user?(this.sessionCache=t,this.sessionCacheExpiry=Date.now()+3e5,n.info("User authenticated for editing",{userId:t.user.id,email:t.user.email}),{isAuthenticated:!0,session:t,user:t.user,canEdit:!0}):{isAuthenticated:!1,canEdit:!1}}catch(t){return n.debug("Authentication check failed",{error:t}),t instanceof Response&&t.status,{isAuthenticated:!1,canEdit:!1}}}))}checkCompositionOwnership(e){return t(this,void 0,void 0,(function*(){var t;try{const i=this.ownershipCache.get(e);if(i)return i;const o=yield this.checkAuthentication();if(!o.isAuthenticated||!(null===(t=o.session)||void 0===t?void 0:t.user)){const t={isOwner:!1,canEdit:!1,error:"User not authenticated"};return this.ownershipCache.set(e,t),t}const s=c(yield this.compositionsApi.getCompositionById({id:e}));if(!s){const t={isOwner:!1,canEdit:!1,error:"Composition not found"};return this.ownershipCache.set(e,t),t}const r=s.creatorId===o.session.user.id,a={isOwner:r,canEdit:r,composition:s,error:r?void 0:"User does not own this composition"};return this.ownershipCache.set(e,a),setTimeout((()=>{this.ownershipCache.delete(e)}),12e4),n.debug("Composition ownership checked",{compositionId:e,isOwner:r,userId:o.session.user.id,compositionCreatorId:s.creatorId}),a}catch(t){n.warn("Failed to check composition ownership",{compositionId:e,error:t});const i={isOwner:!1,canEdit:!1,error:t instanceof Error?t.message:"Unknown error"};return this.ownershipCache.set(e,i),i}}))}canEditComposition(e){return t(this,void 0,void 0,(function*(){return(yield this.checkCompositionOwnership(e)).canEdit}))}getCurrentUser(){return t(this,void 0,void 0,(function*(){return(yield this.checkAuthentication()).user||null}))}clearCache(){this.sessionCache=null,this.sessionCacheExpiry=0,this.ownershipCache.clear(),n.debug("Authentication cache cleared")}checkMultipleCompositions(e){return t(this,void 0,void 0,(function*(){const i=new Map;return(yield this.checkAuthentication()).isAuthenticated?(yield Promise.all(e.map((e=>t(this,void 0,void 0,(function*(){const t=yield this.checkCompositionOwnership(e);i.set(e,t)}))))),i):(e.forEach((t=>{i.set(t,{isOwner:!1,canEdit:!1,error:"User not authenticated"})})),i)}))}isEditingEnabled(){return s.ENABLE_EDITING}}let u=null;function p(){return u||(u=new h),u}class g{constructor(t={}){this.host=null,this.container=null,this.content=null,this.destroyed=!1,this.options=Object.assign({target:"widgetic-portal",className:"",style:"",clickThrough:!1,zIndex:99999999},t),this.createPortal()}createPortal(){this.host=this.findOrCreateHost(),this.container=document.createElement("div"),this.container.className=(this.options.className?this.options.className+" ":"")+"widgetic-portal-contents",this.container.style.cssText=`\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n z-index: ${this.options.zIndex};\n pointer-events: ${this.options.clickThrough?"none":"auto"};\n ${this.options.style}\n `,this.options.clickThrough?this.container.style.pointerEvents="none":this.container.style.pointerEvents="auto",this.host.appendChild(this.container),n.debug("Portal created",{target:this.options.target,host:this.host,container:this.container})}findOrCreateHost(){let t=null;if(this.options.target instanceof HTMLElement)return this.options.target;if("string"==typeof this.options.target){const e=`.${this.options.target}`;t=document.querySelector(e)}return t||(t=document.createElement("div"),t.classList.add("string"==typeof this.options.target?this.options.target:"widgetic-portal"),document.body.appendChild(t),n.debug("Portal host created",{target:this.options.target,host:t})),t}mount(t){this.destroyed?n.warn("Cannot mount content to destroyed portal"):this.container?(this.content&&this.unmount(),t.style.pointerEvents="auto",this.content=t,this.container.appendChild(t),n.debug("Content mounted to portal",{content:t})):n.error("Portal container not available")}unmount(){this.content&&this.container&&this.container.contains(this.content)&&(this.container.removeChild(this.content),this.content=null,n.debug("Content unmounted from portal"))}destroy(){if(!this.destroyed){if(this.unmount(),this.container&&this.host&&this.host.contains(this.container)&&this.host.removeChild(this.container),this.host&&0===this.host.childNodes.length&&this.host.parentNode){const t="string"==typeof this.options.target?this.options.target:"widgetic-portal";this.host.classList.contains(t)&&this.host.parentNode.removeChild(this.host)}this.destroyed=!0,this.host=null,this.container=null,this.content=null,n.debug("Portal destroyed")}}getContainer(){return this.container}isDestroyed(){return this.destroyed}updateOptions(t){this.destroyed?n.warn("Cannot update options on destroyed portal"):(this.options=Object.assign(Object.assign({},this.options),t),this.container&&(void 0!==t.className&&(this.container.className=(t.className?t.className+" ":"")+"widgetic-portal-contents"),void 0!==t.style&&(this.container.style.cssText=`\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n z-index: ${this.options.zIndex};\n pointer-events: ${this.options.clickThrough,"none"};\n ${this.options.style}\n `),void 0!==t.clickThrough&&(this.container.style.pointerEvents=(t.clickThrough,"none"))),n.debug("Portal options updated",{options:this.options}))}}function y(t){return new g(t)}class m{constructor(t={}){this.config=t,this.loadPromise=null,this.sdkInstance=null,this.isLoading=!1,this.loadTimeout=3e4,this.config=Object.assign({basePath:t.basePath||this.getUISdkBaseUrl(),version:t.version||"latest",debug:t.debug||!1},t)}getUISdkBaseUrl(){return"development"===s.NODE_ENV?s.CLIENT_URL:`${s.PRODUCTION_URL}/ui-sdk`}loadUISdk(){return t(this,void 0,void 0,(function*(){if(this.sdkInstance)return this.sdkInstance;if(this.loadPromise)return this.loadPromise;this.isLoading=!0,this.loadPromise=this.performLoad();try{return this.sdkInstance=yield this.loadPromise,n.info("UI SDK loaded successfully",{basePath:this.config.basePath,version:this.config.version}),this.sdkInstance}catch(t){throw n.error("Failed to load UI SDK",{error:t,config:this.config}),this.loadPromise=null,t}finally{this.isLoading=!1}}))}performLoad(){return t(this,void 0,void 0,(function*(){return new Promise(((t,e)=>{const i=setTimeout((()=>{e(new Error("UI SDK load timeout"))}),this.loadTimeout);try{if(window.WidgeticUI)return clearTimeout(i),void t(window.WidgeticUI);const o=document.createElement("script");o.src=`${this.config.basePath}/widgetic-ui.js`,o.async=!0,o.crossOrigin="anonymous",o.onload=()=>{clearTimeout(i),window.WidgeticUI?(n.debug("UI SDK script loaded from external source"),t(window.WidgeticUI)):e(new Error("UI SDK script loaded but WidgeticUI not available"))},o.onerror=()=>{clearTimeout(i),e(new Error("Failed to load UI SDK script"))},document.head.appendChild(o),n.debug("Loading UI SDK",{src:o.src})}catch(t){clearTimeout(i),e(t)}}))}))}isLoaded(){return null!==this.sdkInstance}isLoadingState(){return this.isLoading}getInstance(){return this.sdkInstance}initializeUISdk(e){return t(this,void 0,void 0,(function*(){const t=yield this.loadUISdk();return yield t.init(Object.assign(Object.assign({},this.config),e)),n.info("UI SDK initialized",{config:Object.assign(Object.assign({},this.config),e)}),t}))}cleanup(){return t(this,void 0,void 0,(function*(){if(this.sdkInstance){try{yield this.sdkInstance.destroy()}catch(t){n.warn("Error during UI SDK cleanup",{error:t})}this.sdkInstance=null}this.loadPromise=null,this.isLoading=!1,window.WidgeticUI&&delete window.WidgeticUI,n.debug("UI SDK cleanup complete")}))}preload(){return t(this,void 0,void 0,(function*(){try{yield this.loadUISdk(),n.debug("UI SDK preloaded successfully")}catch(t){n.warn("UI SDK preload failed",{error:t})}}))}}let v=null;function f(t){return v||(v=new m(t)),v}class w{constructor(t={}){this.options=t,this.sessions=new Map,this.defaultOptions={showEditButton:!0,editButtonText:"✏️ Edit",editButtonPosition:"top-right",enableClickToEdit:!0,autoDetectAuth:!0},this.options=Object.assign(Object.assign({},this.defaultOptions),t)}addOverlay(e,i){return t(this,void 0,void 0,(function*(){try{if(!this.options.autoDetectAuth)return void(yield this.createOverlay(e,i,!0));const t=p(),o=yield t.checkCompositionOwnership(i);o.canEdit?(yield this.createOverlay(e,i,!0),n.debug("Editor overlay added for owned composition",{compositionId:i})):n.debug("Editor overlay not added - user cannot edit",{compositionId:i,reason:o.error})}catch(t){n.warn("Failed to add editor overlay",{compositionId:i,error:t})}}))}createOverlay(e,i,o){return t(this,void 0,void 0,(function*(){if(this.sessions.has(i))return;const t=document.createElement("div");if(t.className="widgetic-editor-overlay",t.style.cssText=`\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n z-index: 10000;\n pointer-events: none;\n ${this.getOverlayStyles()}\n `,this.options.showEditButton&&o){const e=this.createEditButton(i);t.appendChild(e)}this.options.enableClickToEdit&&o&&this.addClickToEdit(t,i);const s=e.parentElement;if(s){"static"===window.getComputedStyle(s).position&&(s.style.position="relative"),s.appendChild(t)}else e.style.position="relative",e.appendChild(t);const r={compositionId:i,isOpen:!1,overlay:t};this.sessions.set(i,r),n.debug("Editor overlay created",{compositionId:i})}))}createEditButton(e){const i=document.createElement("button");return i.className="widgetic-edit-button",i.textContent=this.options.editButtonText||"✏️ Edit",i.style.cssText=`\n position: absolute;\n ${this.getButtonPositionStyles()}\n background: #007bff;\n color: white;\n border: none;\n border-radius: 4px;\n padding: 8px 12px;\n font-size: 12px;\n font-weight: 500;\n cursor: pointer;\n pointer-events: auto;\n box-shadow: 0 2px 4px rgba(0,0,0,0.1);\n transition: all 0.2s ease;\n z-index: 10001;\n ${this.getCustomButtonStyles()}\n `,i.addEventListener("mouseenter",(()=>{i.style.background="#0056b3",i.style.transform="scale(1.05)"})),i.addEventListener("mouseleave",(()=>{i.style.background="#007bff",i.style.transform="scale(1)"})),i.addEventListener("click",(i=>t(this,void 0,void 0,(function*(){i.preventDefault(),i.stopPropagation(),yield this.openEditor(e)})))),i}getButtonPositionStyles(){const t="10px";switch(this.options.editButtonPosition||"top-right"){case"top-left":return`top: ${t}; left: ${t};`;case"top-right":default:return`top: ${t}; right: ${t};`;case"bottom-left":return`bottom: ${t}; left: ${t};`;case"bottom-right":return`bottom: ${t}; right: ${t};`}}getCustomButtonStyles(){return this.options.editButtonStyle?Object.entries(this.options.editButtonStyle).map((([t,e])=>`${this.camelToKebab(t)}: ${e};`)).join(" "):""}getOverlayStyles(){return this.options.overlayStyle?Object.entries(this.options.overlayStyle).map((([t,e])=>`${this.camelToKebab(t)}: ${e};`)).join(" "):""}camelToKebab(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}addClickToEdit(e,i){e.style.cursor="pointer",e.style.pointerEvents="auto",e.addEventListener("click",(o=>t(this,void 0,void 0,(function*(){o.target===e&&(o.preventDefault(),o.stopPropagation(),yield this.openEditor(i))})))),e.addEventListener("mouseenter",(()=>{e.style.backgroundColor="rgba(0, 123, 255, 0.1)",e.style.border="2px dashed #007bff"})),e.addEventListener("mouseleave",(()=>{e.style.backgroundColor="transparent",e.style.border="none"}))}createEditorContainer(){const t=new g({target:"widgetic-editor-portal",className:"widgetic-editor-modal",zIndex:1e5,clickThrough:!1});const e=document.createElement("div");e.className="widgetic-editor-modal-backdrop",e.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n background: rgba(0, 0, 0, 0.8);\n display: flex;\n align-items: center;\n justify-content: center;\n ";const i=document.createElement("div");return i.className="widgetic-editor-content",i.style.cssText="\n width: 90vw;\n height: 90vh;\n max-width: 1200px;\n max-height: 800px;\n background: white;\n border-radius: 8px;\n overflow: hidden;\n position: relative;\n ",e.appendChild(i),t.mount(e),{container:e,portal:t}}openEditor(e){return t(this,void 0,void 0,(function*(){try{const t=this.sessions.get(e);if(!t)return void n.warn("No editor session found",{compositionId:e});if(t.isOpen)return void n.debug("Editor already open",{compositionId:e});n.info("Opening composition editor",{compositionId:e});const i=f(),o=yield i.initializeUISdk(),{container:s,portal:r}=this.createEditorContainer(),d=yield o.mountCompositionEditor(s.querySelector(".widgetic-editor-content"),e,{onSave:t=>this.handleEditorSave(e,t),onClose:()=>this.closeEditor(e),onPreview:t=>this.handleEditorPreview(e,t)}),c=a().createWidgetController(e);if(t.isOpen=!0,t.editorContainer=s,t.editorInstance=d,t.widgetController=c,t.portal=r,t.overlay){const e=t.overlay.querySelector(".widgetic-edit-button");e&&(e.style.display="none")}n.info("Composition editor opened successfully",{compositionId:e})}catch(t){n.error("Failed to open editor",{compositionId:e,error:t}),this.showError("Failed to open editor. Please try again.",e)}}))}handleEditorSave(e,i){return t(this,void 0,void 0,(function*(){try{n.info("Saving composition changes",{compositionId:e,data:i});const t=this.sessions.get(e);(null==t?void 0:t.widgetController)&&(yield t.widgetController.updateConfig(i),yield t.widgetController.refresh()),yield this.closeEditor(e),n.info("Composition saved successfully",{compositionId:e})}catch(t){n.error("Failed to save composition",{compositionId:e,error:t}),this.showError("Failed to save changes. Please try again.",e)}}))}handleEditorPreview(e,i){return t(this,void 0,void 0,(function*(){try{const t=this.sessions.get(e);(null==t?void 0:t.widgetController)&&(yield t.widgetController.callFunction("preview",i))}catch(t){n.warn("Preview update failed",{compositionId:e,error:t})}}))}closeEditor(e){return t(this,void 0,void 0,(function*(){const t=this.sessions.get(e);if(t&&t.isOpen)try{if(t.editorInstance&&t.editorContainer){const e=f().getInstance();e&&(yield e.unmountCompositionEditor(t.editorContainer))}if(t.portal&&t.portal.destroy(),t.overlay){const e=t.overlay.querySelector(".widgetic-edit-button");e&&(e.style.display="block")}t.isOpen=!1,t.editorContainer=void 0,t.editorInstance=void 0,t.portal=void 0,n.info("Editor closed",{compositionId:e})}catch(t){n.error("Error closing editor",{compositionId:e,error:t})}}))}showError(t,e){const i=document.createElement("div");i.style.cssText="\n position: fixed;\n top: 20px;\n right: 20px;\n background: #dc3545;\n color: white;\n padding: 12px 16px;\n border-radius: 4px;\n z-index: 100001;\n font-size: 14px;\n max-width: 300px;\n ",i.textContent=t,document.body.appendChild(i),setTimeout((()=>{i.parentNode&&i.parentNode.removeChild(i)}),5e3)}removeOverlay(t){const e=this.sessions.get(t);e&&(e.isOpen&&this.closeEditor(t),e.overlay&&e.overlay.parentNode&&e.overlay.parentNode.removeChild(e.overlay),e.portal&&e.portal.destroy(),this.sessions.delete(t),n.debug("Editor overlay removed",{compositionId:t}))}isEditorOpen(t){var e;return(null===(e=this.sessions.get(t))||void 0===e?void 0:e.isOpen)||!1}getActiveSessions(){return Array.from(this.sessions.keys())}cleanup(){for(const t of this.sessions.keys())this.removeOverlay(t);n.debug("Editor overlay cleanup complete")}}let b=null;function E(t){return b||(b=new w(t)),b}var C=Object.freeze({__proto__:null,EditorOverlay:w,getEditorOverlay:E,resetEditorOverlay:function(){b&&(b.cleanup(),b=null)}});export{E as a,f as b,y as c,c as d,C as e,p as g,l as t};
1
+ import{_ as t}from"./vendor.js";import{n as e,C as i,o,b as n,l as s,d as r,p as a,a as d}from"./core.js";import{getMessenger as c}from"./messaging.js";const l=t=>null!==t&&"object"==typeof t&&!Array.isArray(t)&&"[object Object]"===Object.prototype.toString.call(t);function h(t){if(Array.isArray(t))return t.map(h);if(!l(t))return t;const e={};for(const[i,o]of Object.entries(t)){e[i.replace(/[_-](\w)/g,((t,e)=>e?e.toUpperCase():""))]=Array.isArray(o)?o.map(h):l(o)?h(o):o}return e}function u(t){if(Array.isArray(t))return t.map(u);if(!l(t))return t;const e={};for(const[i,o]of Object.entries(t)){e[i.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[\s-]+/g,"_").toLowerCase()]=Array.isArray(o)?o.map(u):l(o)?u(o):o}return e}function p(t){if(!t)return"";try{return new URL(t).hostname.toLowerCase()}catch(t){return""}}function g(t){return null!==t&&"object"==typeof t&&!Array.isArray(t)}function y(t){return g(t)&&"boolean"==typeof t.success&&"data"in t?t.data:t}class m{constructor(){var t;this.sessionCache=null,this.sessionCacheExpiry=0,this.ownershipCache=new Map;const e=a({basePath:d()});this.apiUrl=null!==(t=e.basePath)&&void 0!==t?t:"";const s=new i({basePath:e.basePath,apiKey:e.apiKey,credentials:"include"});this.authApi=new o(s),this.compositionsApi=new n(s)}checkAuthentication(){return t(this,void 0,void 0,(function*(){var t,i;try{const o="undefined"!=typeof window&&null!==(i=null===(t=window.location)||void 0===t?void 0:t.hostname)&&void 0!==i?i:"";if(!function(t){var i,o,n;const s=p(t.apiUrl),r=p(null!==(i=t.productionApiUrl)&&void 0!==i?i:e.PROD_API_URL);if(!s||!r||s!==r)return!0;const a=String(null!==(o=t.pageHostname)&&void 0!==o?o:"").trim().toLowerCase();if(!a)return!1;if(function(t){const e=t.replace(/^\[|\]$/g,"");return"localhost"===e||e.endsWith(".localhost")||"127.0.0.1"===e||"::1"===e}(a))return!0;const d=p(null!==(n=t.widgeticSiteUrl)&&void 0!==n?n:e.PROD_CLIENT_URL);return!d||a===d||a.endsWith(`.${d}`)}({pageHostname:o,apiUrl:this.apiUrl}))return s.debug("Editor session check skipped: this website cannot read the API's answer",{pageHostname:o}),{isAuthenticated:!1,canEdit:!1};if(this.sessionCache&&Date.now()<this.sessionCacheExpiry)return{isAuthenticated:!0,session:this.sessionCache,user:this.sessionCache.user,canEdit:!0};const n=yield this.authApi.getSessionRaw(),r=function(t){const e=y(t);if(!g(e))return null;const i=h(e),o=i.user;return"string"!=typeof i.accessToken||""===i.accessToken?null:g(o)&&"string"==typeof o.id&&""!==o.id?i:null}(yield n.raw.json().catch((()=>null)));return r?(this.sessionCache=r,this.sessionCacheExpiry=Date.now()+3e5,s.info("User authenticated for editing",{userId:r.user.id,email:r.user.email}),{isAuthenticated:!0,session:r,user:r.user,canEdit:!0}):{isAuthenticated:!1,canEdit:!1}}catch(t){return s.debug("Authentication check failed",{error:t}),t instanceof Response&&t.status,{isAuthenticated:!1,canEdit:!1}}}))}checkCompositionOwnership(e){return t(this,void 0,void 0,(function*(){var t;try{const i=this.ownershipCache.get(e);if(i)return i;const o=yield this.checkAuthentication();if(!o.isAuthenticated||!(null===(t=o.session)||void 0===t?void 0:t.user)){const t={isOwner:!1,canEdit:!1,error:"User not authenticated"};return this.ownershipCache.set(e,t),t}const n=h(y(yield this.compositionsApi.getCompositionById({id:e})));if(!n){const t={isOwner:!1,canEdit:!1,error:"Composition not found"};return this.ownershipCache.set(e,t),t}const r=n.creatorId===o.session.user.id,a={isOwner:r,canEdit:r,composition:n,error:r?void 0:"User does not own this composition"};return this.ownershipCache.set(e,a),setTimeout((()=>{this.ownershipCache.delete(e)}),12e4),s.debug("Composition ownership checked",{compositionId:e,isOwner:r,userId:o.session.user.id,compositionCreatorId:n.creatorId}),a}catch(t){s.warn("Failed to check composition ownership",{compositionId:e,error:t});const i={isOwner:!1,canEdit:!1,error:t instanceof Error?t.message:"Unknown error"};return this.ownershipCache.set(e,i),i}}))}canEditComposition(e){return t(this,void 0,void 0,(function*(){return(yield this.checkCompositionOwnership(e)).canEdit}))}getCurrentUser(){return t(this,void 0,void 0,(function*(){return(yield this.checkAuthentication()).user||null}))}clearCache(){this.sessionCache=null,this.sessionCacheExpiry=0,this.ownershipCache.clear(),s.debug("Authentication cache cleared")}checkMultipleCompositions(e){return t(this,void 0,void 0,(function*(){const i=new Map;return(yield this.checkAuthentication()).isAuthenticated?(yield Promise.all(e.map((e=>t(this,void 0,void 0,(function*(){const t=yield this.checkCompositionOwnership(e);i.set(e,t)}))))),i):(e.forEach((t=>{i.set(t,{isOwner:!1,canEdit:!1,error:"User not authenticated"})})),i)}))}isEditingEnabled(){return r.ENABLE_EDITING}}let v=null;function f(){return v||(v=new m),v}class w{constructor(t={}){this.host=null,this.container=null,this.content=null,this.destroyed=!1,this.options=Object.assign({target:"widgetic-portal",className:"",style:"",clickThrough:!1,zIndex:99999999},t),this.createPortal()}createPortal(){this.host=this.findOrCreateHost(),this.container=document.createElement("div"),this.container.className=(this.options.className?this.options.className+" ":"")+"widgetic-portal-contents",this.container.style.cssText=`\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n z-index: ${this.options.zIndex};\n pointer-events: ${this.options.clickThrough?"none":"auto"};\n ${this.options.style}\n `,this.options.clickThrough?this.container.style.pointerEvents="none":this.container.style.pointerEvents="auto",this.host.appendChild(this.container),s.debug("Portal created",{target:this.options.target,host:this.host,container:this.container})}findOrCreateHost(){let t=null;if(this.options.target instanceof HTMLElement)return this.options.target;if("string"==typeof this.options.target){const e=`.${this.options.target}`;t=document.querySelector(e)}return t||(t=document.createElement("div"),t.classList.add("string"==typeof this.options.target?this.options.target:"widgetic-portal"),document.body.appendChild(t),s.debug("Portal host created",{target:this.options.target,host:t})),t}mount(t){this.destroyed?s.warn("Cannot mount content to destroyed portal"):this.container?(this.content&&this.unmount(),t.style.pointerEvents="auto",this.content=t,this.container.appendChild(t),s.debug("Content mounted to portal",{content:t})):s.error("Portal container not available")}unmount(){this.content&&this.container&&this.container.contains(this.content)&&(this.container.removeChild(this.content),this.content=null,s.debug("Content unmounted from portal"))}destroy(){if(!this.destroyed){if(this.unmount(),this.container&&this.host&&this.host.contains(this.container)&&this.host.removeChild(this.container),this.host&&0===this.host.childNodes.length&&this.host.parentNode){const t="string"==typeof this.options.target?this.options.target:"widgetic-portal";this.host.classList.contains(t)&&this.host.parentNode.removeChild(this.host)}this.destroyed=!0,this.host=null,this.container=null,this.content=null,s.debug("Portal destroyed")}}getContainer(){return this.container}isDestroyed(){return this.destroyed}updateOptions(t){this.destroyed?s.warn("Cannot update options on destroyed portal"):(this.options=Object.assign(Object.assign({},this.options),t),this.container&&(void 0!==t.className&&(this.container.className=(t.className?t.className+" ":"")+"widgetic-portal-contents"),void 0!==t.style&&(this.container.style.cssText=`\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n z-index: ${this.options.zIndex};\n pointer-events: ${this.options.clickThrough,"none"};\n ${this.options.style}\n `),void 0!==t.clickThrough&&(this.container.style.pointerEvents=(t.clickThrough,"none"))),s.debug("Portal options updated",{options:this.options}))}}function b(t){return new w(t)}class E{constructor(t={}){this.config=t,this.loadPromise=null,this.sdkInstance=null,this.isLoading=!1,this.loadTimeout=3e4,this.config=Object.assign({basePath:t.basePath||this.getUISdkBaseUrl(),version:t.version||"latest",debug:t.debug||!1},t)}getUISdkBaseUrl(){return"development"===r.NODE_ENV?r.CLIENT_URL:`${r.PRODUCTION_URL}/ui-sdk`}loadUISdk(){return t(this,void 0,void 0,(function*(){if(this.sdkInstance)return this.sdkInstance;if(this.loadPromise)return this.loadPromise;this.isLoading=!0,this.loadPromise=this.performLoad();try{return this.sdkInstance=yield this.loadPromise,s.info("UI SDK loaded successfully",{basePath:this.config.basePath,version:this.config.version}),this.sdkInstance}catch(t){throw s.error("Failed to load UI SDK",{error:t,config:this.config}),this.loadPromise=null,t}finally{this.isLoading=!1}}))}performLoad(){return t(this,void 0,void 0,(function*(){return new Promise(((t,e)=>{const i=setTimeout((()=>{e(new Error("UI SDK load timeout"))}),this.loadTimeout);try{if(window.WidgeticUI)return clearTimeout(i),void t(window.WidgeticUI);const o=document.createElement("script");o.src=`${this.config.basePath}/widgetic-ui.js`,o.async=!0,o.crossOrigin="anonymous",o.onload=()=>{clearTimeout(i),window.WidgeticUI?(s.debug("UI SDK script loaded from external source"),t(window.WidgeticUI)):e(new Error("UI SDK script loaded but WidgeticUI not available"))},o.onerror=()=>{clearTimeout(i),e(new Error("Failed to load UI SDK script"))},document.head.appendChild(o),s.debug("Loading UI SDK",{src:o.src})}catch(t){clearTimeout(i),e(t)}}))}))}isLoaded(){return null!==this.sdkInstance}isLoadingState(){return this.isLoading}getInstance(){return this.sdkInstance}initializeUISdk(e){return t(this,void 0,void 0,(function*(){const t=yield this.loadUISdk();return yield t.init(Object.assign(Object.assign({},this.config),e)),s.info("UI SDK initialized",{config:Object.assign(Object.assign({},this.config),e)}),t}))}cleanup(){return t(this,void 0,void 0,(function*(){if(this.sdkInstance){try{yield this.sdkInstance.destroy()}catch(t){s.warn("Error during UI SDK cleanup",{error:t})}this.sdkInstance=null}this.loadPromise=null,this.isLoading=!1,window.WidgeticUI&&delete window.WidgeticUI,s.debug("UI SDK cleanup complete")}))}preload(){return t(this,void 0,void 0,(function*(){try{yield this.loadUISdk(),s.debug("UI SDK preloaded successfully")}catch(t){s.warn("UI SDK preload failed",{error:t})}}))}}let C=null;function I(t){return C||(C=new E(t)),C}class k{constructor(t={}){this.options=t,this.sessions=new Map,this.defaultOptions={showEditButton:!0,editButtonText:"✏️ Edit",editButtonPosition:"top-right",enableClickToEdit:!0,autoDetectAuth:!0},this.options=Object.assign(Object.assign({},this.defaultOptions),t)}addOverlay(e,i){return t(this,void 0,void 0,(function*(){try{if(!this.options.autoDetectAuth)return void(yield this.createOverlay(e,i,!0));const t=f(),o=yield t.checkCompositionOwnership(i);o.canEdit?(yield this.createOverlay(e,i,!0),s.debug("Editor overlay added for owned composition",{compositionId:i})):s.debug("Editor overlay not added - user cannot edit",{compositionId:i,reason:o.error})}catch(t){s.warn("Failed to add editor overlay",{compositionId:i,error:t})}}))}createOverlay(e,i,o){return t(this,void 0,void 0,(function*(){if(this.sessions.has(i))return;const t=document.createElement("div");if(t.className="widgetic-editor-overlay",t.style.cssText=`\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n z-index: 10000;\n pointer-events: none;\n ${this.getOverlayStyles()}\n `,this.options.showEditButton&&o){const e=this.createEditButton(i);t.appendChild(e)}this.options.enableClickToEdit&&o&&this.addClickToEdit(t,i);const n=e.parentElement;if(n){"static"===window.getComputedStyle(n).position&&(n.style.position="relative"),n.appendChild(t)}else e.style.position="relative",e.appendChild(t);const r={compositionId:i,isOpen:!1,overlay:t};this.sessions.set(i,r),s.debug("Editor overlay created",{compositionId:i})}))}createEditButton(e){const i=document.createElement("button");return i.className="widgetic-edit-button",i.textContent=this.options.editButtonText||"✏️ Edit",i.style.cssText=`\n position: absolute;\n ${this.getButtonPositionStyles()}\n background: #007bff;\n color: white;\n border: none;\n border-radius: 4px;\n padding: 8px 12px;\n font-size: 12px;\n font-weight: 500;\n cursor: pointer;\n pointer-events: auto;\n box-shadow: 0 2px 4px rgba(0,0,0,0.1);\n transition: all 0.2s ease;\n z-index: 10001;\n ${this.getCustomButtonStyles()}\n `,i.addEventListener("mouseenter",(()=>{i.style.background="#0056b3",i.style.transform="scale(1.05)"})),i.addEventListener("mouseleave",(()=>{i.style.background="#007bff",i.style.transform="scale(1)"})),i.addEventListener("click",(i=>t(this,void 0,void 0,(function*(){i.preventDefault(),i.stopPropagation(),yield this.openEditor(e)})))),i}getButtonPositionStyles(){const t="10px";switch(this.options.editButtonPosition||"top-right"){case"top-left":return`top: ${t}; left: ${t};`;case"top-right":default:return`top: ${t}; right: ${t};`;case"bottom-left":return`bottom: ${t}; left: ${t};`;case"bottom-right":return`bottom: ${t}; right: ${t};`}}getCustomButtonStyles(){return this.options.editButtonStyle?Object.entries(this.options.editButtonStyle).map((([t,e])=>`${this.camelToKebab(t)}: ${e};`)).join(" "):""}getOverlayStyles(){return this.options.overlayStyle?Object.entries(this.options.overlayStyle).map((([t,e])=>`${this.camelToKebab(t)}: ${e};`)).join(" "):""}camelToKebab(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}addClickToEdit(e,i){e.style.cursor="pointer",e.style.pointerEvents="auto",e.addEventListener("click",(o=>t(this,void 0,void 0,(function*(){o.target===e&&(o.preventDefault(),o.stopPropagation(),yield this.openEditor(i))})))),e.addEventListener("mouseenter",(()=>{e.style.backgroundColor="rgba(0, 123, 255, 0.1)",e.style.border="2px dashed #007bff"})),e.addEventListener("mouseleave",(()=>{e.style.backgroundColor="transparent",e.style.border="none"}))}createEditorContainer(){const t=new w({target:"widgetic-editor-portal",className:"widgetic-editor-modal",zIndex:1e5,clickThrough:!1});const e=document.createElement("div");e.className="widgetic-editor-modal-backdrop",e.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n background: rgba(0, 0, 0, 0.8);\n display: flex;\n align-items: center;\n justify-content: center;\n ";const i=document.createElement("div");return i.className="widgetic-editor-content",i.style.cssText="\n width: 90vw;\n height: 90vh;\n max-width: 1200px;\n max-height: 800px;\n background: white;\n border-radius: 8px;\n overflow: hidden;\n position: relative;\n ",e.appendChild(i),t.mount(e),{container:e,portal:t}}openEditor(e){return t(this,void 0,void 0,(function*(){try{const t=this.sessions.get(e);if(!t)return void s.warn("No editor session found",{compositionId:e});if(t.isOpen)return void s.debug("Editor already open",{compositionId:e});s.info("Opening composition editor",{compositionId:e});const i=I(),o=yield i.initializeUISdk(),{container:n,portal:r}=this.createEditorContainer(),a=yield o.mountCompositionEditor(n.querySelector(".widgetic-editor-content"),e,{onSave:t=>this.handleEditorSave(e,t),onClose:()=>this.closeEditor(e),onPreview:t=>this.handleEditorPreview(e,t)}),d=c().createWidgetController(e);if(t.isOpen=!0,t.editorContainer=n,t.editorInstance=a,t.widgetController=d,t.portal=r,t.overlay){const e=t.overlay.querySelector(".widgetic-edit-button");e&&(e.style.display="none")}s.info("Composition editor opened successfully",{compositionId:e})}catch(t){s.error("Failed to open editor",{compositionId:e,error:t}),this.showError("Failed to open editor. Please try again.",e)}}))}handleEditorSave(e,i){return t(this,void 0,void 0,(function*(){try{s.info("Saving composition changes",{compositionId:e,data:i});const t=this.sessions.get(e);(null==t?void 0:t.widgetController)&&(yield t.widgetController.updateConfig(i),yield t.widgetController.refresh()),yield this.closeEditor(e),s.info("Composition saved successfully",{compositionId:e})}catch(t){s.error("Failed to save composition",{compositionId:e,error:t}),this.showError("Failed to save changes. Please try again.",e)}}))}handleEditorPreview(e,i){return t(this,void 0,void 0,(function*(){try{const t=this.sessions.get(e);(null==t?void 0:t.widgetController)&&(yield t.widgetController.callFunction("preview",i))}catch(t){s.warn("Preview update failed",{compositionId:e,error:t})}}))}closeEditor(e){return t(this,void 0,void 0,(function*(){const t=this.sessions.get(e);if(t&&t.isOpen)try{if(t.editorInstance&&t.editorContainer){const e=I().getInstance();e&&(yield e.unmountCompositionEditor(t.editorContainer))}if(t.portal&&t.portal.destroy(),t.overlay){const e=t.overlay.querySelector(".widgetic-edit-button");e&&(e.style.display="block")}t.isOpen=!1,t.editorContainer=void 0,t.editorInstance=void 0,t.portal=void 0,s.info("Editor closed",{compositionId:e})}catch(t){s.error("Error closing editor",{compositionId:e,error:t})}}))}showError(t,e){const i=document.createElement("div");i.style.cssText="\n position: fixed;\n top: 20px;\n right: 20px;\n background: #dc3545;\n color: white;\n padding: 12px 16px;\n border-radius: 4px;\n z-index: 100001;\n font-size: 14px;\n max-width: 300px;\n ",i.textContent=t,document.body.appendChild(i),setTimeout((()=>{i.parentNode&&i.parentNode.removeChild(i)}),5e3)}removeOverlay(t){const e=this.sessions.get(t);e&&(e.isOpen&&this.closeEditor(t),e.overlay&&e.overlay.parentNode&&e.overlay.parentNode.removeChild(e.overlay),e.portal&&e.portal.destroy(),this.sessions.delete(t),s.debug("Editor overlay removed",{compositionId:t}))}isEditorOpen(t){var e;return(null===(e=this.sessions.get(t))||void 0===e?void 0:e.isOpen)||!1}getActiveSessions(){return Array.from(this.sessions.keys())}cleanup(){for(const t of this.sessions.keys())this.removeOverlay(t);s.debug("Editor overlay cleanup complete")}}let O=null;function x(t){return O||(O=new k(t)),O}var U=Object.freeze({__proto__:null,EditorOverlay:k,getEditorOverlay:x,resetEditorOverlay:function(){O&&(O.cleanup(),O=null)}});export{x as a,I as b,b as c,u as d,U as e,f as g,h as t};