@widgetic/embed-sdk 2.1.0 → 2.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import{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{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(),_.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};
@@ -9,16 +9,28 @@ declare const BaseHTMLElement: {
9
9
  /**
10
10
  * A/B Testing Custom Element
11
11
  * <widgetic-abtest experiment-id="12345"></widgetic-abtest>
12
+ * <widgetic-abtest experiment-id="12345" consent="pending"></widgetic-abtest> (until the visitor allows analytics)
12
13
  */
13
14
  export declare class ABTestElement extends BaseHTMLElement {
14
15
  private manager;
15
16
  private widgetManager;
16
- private analyticsTracker;
17
17
  private experimentId;
18
18
  private assignment;
19
19
  private widgetInstance;
20
20
  private impressionTracked;
21
21
  private conversionListeners;
22
+ /** The version drawn in the element right now, so a version that is already shown is not drawn again. */
23
+ private renderedVariantId;
24
+ /** Whether the visitor is in the test (assigned and counted): false while they have not allowed analytics. */
25
+ private isRecording;
26
+ /** Set when the element first connects: before it, `connectedCallback` reads every attribute itself. */
27
+ private hasStarted;
28
+ /** Counts the starts: a start that is not the latest (or one that came before the element left the page) gives up. */
29
+ private currentRunId;
30
+ /** Whether the widget shown said it reports which element was used. The widget says it once, when it is ready. */
31
+ private widgetReportsGoals;
32
+ /** The element of the widget that said it was ready, so a visitor who allows analytics later can still be told the goal. */
33
+ private readyWidgetHost;
22
34
  constructor();
23
35
  /**
24
36
  * Observed attributes for reactivity
@@ -35,15 +47,43 @@ export declare class ABTestElement extends BaseHTMLElement {
35
47
  /**
36
48
  * Called when attributes change
37
49
  */
38
- attributeChangedCallback(name: string, oldValue: string, newValue: string): void;
50
+ attributeChangedCallback(name: string, oldValue: string | null, newValue: string | null): void;
51
+ /**
52
+ * What the tag says about the visitor's analytics. A tag without the attribute is the embed as it has always been: the
53
+ * visitor is in the test. Any value other than `granted` and `denied` waits for an answer, like `pending`.
54
+ */
55
+ private readConsent;
56
+ /**
57
+ * Starts the element for the test and the consent the tag says now. It runs again when either changes, so a start that
58
+ * is no longer the latest stops waiting for its answers as soon as they come.
59
+ */
60
+ private start;
61
+ /**
62
+ * The visitor is in the test: they are assigned a version, shown it, and counted.
63
+ * A visitor who was looking at the original (they had not answered yet) keeps it when it is the version they are given.
64
+ */
65
+ private startRecorded;
66
+ /**
67
+ * The visitor has not allowed analytics (or has not answered yet): they are shown the original version, and nothing is
68
+ * assigned, stored, counted or sent for them. A visitor who said no also has what the browser kept of them removed.
69
+ */
70
+ private startUnrecorded;
39
71
  /**
40
72
  * Setup event listeners for A/B testing
41
73
  */
42
74
  private setupEventListeners;
43
75
  /**
44
- * Render the assigned variant
76
+ * Render the assigned variant (the original one, while the visitor has not allowed analytics)
45
77
  */
46
78
  private renderVariant;
79
+ /**
80
+ * Tells the page which version is shown (`variant-rendered`). `recorded` says whether the visitor is in the test: it is false
81
+ * for the original version shown to a visitor who has not allowed analytics, and a listener that needs a visitor who was
82
+ * assigned (the order snippet of the Shopify app) waits for the event where it is true.
83
+ */
84
+ private announceVariant;
85
+ /** Takes the widget of the shown version down (it is made again for the next one). */
86
+ private removeWidgetInstance;
47
87
  /**
48
88
  * Create embed element from embed code
49
89
  */
@@ -71,11 +111,20 @@ export declare class ABTestElement extends BaseHTMLElement {
71
111
  /**
72
112
  * Tells the widget which goal this test measures and which element counts (`widgetic:ab-goal`).
73
113
  * The widget answers with `widgetic:goal` when that element is used, if it can (see `goal-reporter`).
114
+ * Only a visitor who is in the test has a goal: the original shown to one who has not allowed analytics measures nothing.
74
115
  */
75
116
  private sendGoalToWidget;
117
+ /**
118
+ * Hands the widget its goal, and tells the manager whether the widget reports which element was used. It runs when the
119
+ * widget is ready and the visitor is in the test, in whichever order those two happen: a visitor who allows analytics
120
+ * after the widget was ready must not be left without them, because the widget says it is ready once.
121
+ */
122
+ private applyWidgetReadiness;
76
123
  /**
77
124
  * Setup the listeners for what the widget inside the iframe tells the page. A widget in a frame cannot be clicked
78
125
  * through the page's DOM, so its interactions arrive as `widgetic:*` events from the host bridge.
126
+ * They stay for as long as the version is shown, whether or not the visitor is in the test: what the widget said when it
127
+ * was ready is needed when they enter it. What the visitor does is passed on only while they are in the test.
79
128
  */
80
129
  private setupGoalListeners;
81
130
  /**
@@ -106,6 +155,11 @@ export declare class ABTestElement extends BaseHTMLElement {
106
155
  * Render error state
107
156
  */
108
157
  private renderError;
158
+ /**
159
+ * Stops listening for what the visitor does in the version: a visitor who is not in the test is not counted.
160
+ * The listeners for what the widget says about itself (`goal`) stay unless `includingWidgetListeners` is set.
161
+ */
162
+ private removeConversionListeners;
109
163
  /**
110
164
  * Cleanup resources
111
165
  */
@@ -61,6 +61,7 @@ export declare class ABTestManager extends EventEmitter {
61
61
  private conversionSetups;
62
62
  private trackedConversions;
63
63
  private visitors;
64
+ private heldExperiments;
64
65
  private constructor();
65
66
  /**
66
67
  * Get singleton instance
@@ -75,6 +76,30 @@ export declare class ABTestManager extends EventEmitter {
75
76
  * This method uses a public, non-workspace-specific endpoint.
76
77
  */
77
78
  getTestConfig(experimentId: string): Promise<ABTestConfig | null>;
79
+ /**
80
+ * Holds recording for a test: the visitor has not allowed analytics (yet), so nothing about them is read, stored or sent
81
+ * for it. The visitor id is not created, the version is not assigned, and no impression or conversion is sent.
82
+ * What the browser already holds from an earlier visit is left alone (see `forgetVisitor` for taking it away).
83
+ */
84
+ holdRecording(experimentId: string): void;
85
+ /** Lets a test record again: the visitor allowed analytics. */
86
+ resumeRecording(experimentId: string): void;
87
+ /** Whether recording is held for a test (the visitor has not allowed analytics). */
88
+ isRecordingHeld(experimentId: string): boolean;
89
+ /**
90
+ * Forgets this visitor for a test: the version and the conversion mark the browser kept, and the id of the browser itself
91
+ * once no other test of the page still records with it. For a visitor who said no to analytics, or took it back.
92
+ * Nothing is sent: what the backend already holds is not this method's to remove.
93
+ */
94
+ forgetVisitor(experimentId: string, userContext?: {
95
+ userId?: string;
96
+ }): void;
97
+ /**
98
+ * The version shown to a visitor who has not allowed analytics: the test's original (the first version, the one every
99
+ * other is compared with). Nothing is assigned, stored or sent: the test's public configuration is the only thing read,
100
+ * and it holds nothing about the visitor.
101
+ */
102
+ getUnrecordedVariant(experimentId: string): Promise<ABTestAssignment | null>;
78
103
  /**
79
104
  * The identity of a visitor for a test: the user id when the page has one, and the stable per-browser id otherwise.
80
105
  * Never "anonymous": that would put every visitor of every page in the same bucket.
@@ -151,6 +176,8 @@ export declare class ABTestManager extends EventEmitter {
151
176
  private handleClickEvent;
152
177
  /** The key a visitor's conversion is remembered under: one per visitor and test, whatever they did. */
153
178
  private conversionKeyFor;
179
+ /** The same key, from the id a visitor is named by (the user id when there is one, the browser's id otherwise). */
180
+ private conversionKeyForVisitorKey;
154
181
  /**
155
182
  * Track a conversion: at most one per visitor and test, and only of the goal the test measures.
156
183
  *
@@ -93,6 +93,12 @@ export declare class AnalyticsTracker {
93
93
  * Get or create analytics tracker instance
94
94
  */
95
95
  static getInstance(config?: AnalyticsTrackerConfig): AnalyticsTracker;
96
+ /**
97
+ * The tracker if one was set up, and null if not. For code that has to work without one: `getInstance()` throws when
98
+ * nothing created the tracker, and nothing does for a page that only embeds an A/B test (it needs a composition and an
99
+ * endpoint that only the page knows). A custom element that called `getInstance()` in its constructor never got built.
100
+ */
101
+ static peekInstance(): AnalyticsTracker | null;
96
102
  /**
97
103
  * Initialize or restore session ID
98
104
  */
@@ -21,7 +21,19 @@ export declare class TranslationElement extends BaseHTMLElement {
21
21
  private experimentId;
22
22
  private selectedLanguage;
23
23
  private translationData;
24
+ /** The view could not be reported yet because the visitor has not allowed analytics: it is reported when they do. */
25
+ private viewIsWaitingForConsent;
24
26
  constructor();
27
+ /**
28
+ * `consent` is read the way the A/B element reads it: no attribute or `granted` means the visitor allows analytics, and
29
+ * anything else (`pending`, `denied`) means they have not. Which language is shown does not depend on it: that comes from
30
+ * the browser's language list, and nothing about the visitor is kept.
31
+ */
32
+ static get observedAttributes(): string[];
33
+ /** The page's visitor answered: a view that was waiting for their consent is reported now. */
34
+ attributeChangedCallback(name: string, oldValue: string | null, newValue: string | null): void;
35
+ /** Whether the visitor allows analytics: a tag without `consent` is a page that does not ask. */
36
+ private isAnalyticsAllowed;
25
37
  connectedCallback(): void;
26
38
  disconnectedCallback(): void;
27
39
  /**
@@ -3,6 +3,23 @@
3
3
  */
4
4
  import type { HostBridgeValidationResult } from "./host-bridge-validation.js";
5
5
  export declare const HOST_BRIDGE_MESSAGE_VERSION = 1;
6
+ /**
7
+ * Where the gateway is, for a widget whose adapter modules call it: the address a visitor's entries are saved to and
8
+ * the address of the adapter operations (`{url}/{adapterId}/{operation}`). They come from the public lookup of the
9
+ * composition, never from the page, and they are the only two things a snapshot carries that the page did not write.
10
+ */
11
+ export type WidgeticHostServices = {
12
+ entries?: {
13
+ url: string;
14
+ writeToken?: string;
15
+ };
16
+ adapters?: {
17
+ url: string;
18
+ captcha?: {
19
+ siteKey: string;
20
+ };
21
+ };
22
+ };
6
23
  export type WidgeticHostMessage = {
7
24
  type: "widgetic:host";
8
25
  version: typeof HOST_BRIDGE_MESSAGE_VERSION;
@@ -10,5 +27,21 @@ export type WidgeticHostMessage = {
10
27
  context: Record<string, string | number> | null;
11
28
  values: Record<string, string | number | boolean> | null;
12
29
  mediaResolver: string | null;
30
+ /** Present only when the lookup gave an address; a widget without one reports its saving as unavailable. */
31
+ entries?: {
32
+ url: string;
33
+ writeToken?: string;
34
+ };
35
+ adapters?: {
36
+ url: string;
37
+ captcha?: {
38
+ siteKey: string;
39
+ };
40
+ };
13
41
  };
14
- export declare function buildWidgeticHostMessage(compositionId: string, fields: HostBridgeValidationResult): WidgeticHostMessage;
42
+ /**
43
+ * The addresses of a lookup answer (`entries`, `adapters`) and nothing else from it: the one piece of the answer a
44
+ * snapshot, or a directly mounted widget, is given besides what the page itself wrote.
45
+ */
46
+ export declare function hostServicesOf(lookup: WidgeticHostServices): WidgeticHostServices;
47
+ export declare function buildWidgeticHostMessage(compositionId: string, fields: HostBridgeValidationResult, services?: WidgeticHostServices): WidgeticHostMessage;
@@ -13,6 +13,13 @@ export type DirectWidgetModule = {
13
13
  contractVersion: number;
14
14
  getStyles: () => string;
15
15
  mount: (target: HTMLElement, props: Record<string, unknown>) => DirectWidgetInstance;
16
+ /**
17
+ * True for a module that reads where the gateway is (`compositionId`, `entries`, `adapters`) from the props of
18
+ * `mount` and `update`. A module without the flag (one built before it did, or one that calls nothing: they cannot
19
+ * be told apart) is taken to listen for a `widgetic:host` message on the page's window instead (the way a widget in
20
+ * the gateway's frame page is told); see `postWindowSnapshots`.
21
+ */
22
+ acceptsHostProps?: boolean;
16
23
  };
17
24
  type DirectModuleLoader = (url: string) => Promise<DirectWidgetModule>;
18
25
  /**
@@ -46,6 +46,17 @@ export type PublicEmbedPayload = PublicEmbedOverlay & {
46
46
  url: string;
47
47
  writeToken?: string;
48
48
  };
49
+ /**
50
+ * Where the widget's adapter modules call the gateway (`{url}/{adapterId}/{operation}`), and the public key of the
51
+ * CAPTCHA an operation may ask a visitor to solve. The lookup of a gateway from before this field has none: then the
52
+ * address is the sibling of `entries.url`, and a CAPTCHA operation reports itself unavailable.
53
+ */
54
+ adapters?: {
55
+ url: string;
56
+ captcha?: {
57
+ siteKey: string;
58
+ };
59
+ };
49
60
  /** The owner's choice for image delivery, from the lookup answer (see `image-delivery.ts`). */
50
61
  media?: PublicEmbedMedia;
51
62
  };
@@ -1,6 +1,7 @@
1
1
  /**
2
2
  * Relays `widgetic:host` into the gateway frame and wrapper events back to the page.
3
3
  */
4
+ import { type WidgeticHostServices } from "./host-bridge-snapshot.js";
4
5
  import { type WorkflowWatch } from "./host-workflow-watch.js";
5
6
  /** What the page tells a widget about the A/B test it is part of. */
6
7
  export interface AbGoalAssignment {
@@ -16,13 +17,14 @@ declare class PublishedHostBridge {
16
17
  private readonly iframe;
17
18
  private readonly gatewayOrigin;
18
19
  private readonly compositionId;
20
+ private readonly services?;
19
21
  private readyDispatched;
20
22
  private latestAbGoal;
21
23
  private latestWorkflowWatch;
22
24
  private attributeFlushScheduled;
23
25
  private attributeObserver;
24
26
  private readonly onWindowMessage;
25
- constructor(host: HTMLElement, iframe: HTMLIFrameElement, gatewayOrigin: string, compositionId: string);
27
+ constructor(host: HTMLElement, iframe: HTMLIFrameElement, gatewayOrigin: string, compositionId: string, services?: WidgeticHostServices);
26
28
  private observeHostAttributes;
27
29
  private scheduleHostSnapshot;
28
30
  postHostSnapshot(): void;
@@ -49,8 +51,14 @@ declare class PublishedHostBridge {
49
51
  private dispatchHostEvent;
50
52
  destroy(): void;
51
53
  }
52
- /** Attaches the host bridge for a published iframe mount. */
53
- export declare function attachPublishedHostBridge(host: HTMLElement, iframe: HTMLIFrameElement, embedUrl: string, compositionId: string): void;
54
+ /**
55
+ * Attaches the host bridge for a published iframe mount.
56
+ *
57
+ * `services` is the gateway's address for entries and adapter operations, from the public lookup: a widget that
58
+ * keeps visitors' answers (or calls an adapter) learns where from the snapshot, and has nowhere to send them
59
+ * without it. It is posted only to the iframe's own origin, like the rest of the snapshot.
60
+ */
61
+ export declare function attachPublishedHostBridge(host: HTMLElement, iframe: HTMLIFrameElement, embedUrl: string, compositionId: string, services?: WidgeticHostServices): void;
54
62
  export declare function getPublishedHostBridge(host: HTMLElement): PublishedHostBridge | undefined;
55
63
  export declare function detachPublishedHostBridge(host: HTMLElement): void;
56
64
  /** Dispatches a host-level embed error (lookup refusal, not found, device restriction). */