@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.
- package/README.md +8 -6
- package/dist/browser/chunks/ABTestManager.js +1 -1
- package/dist/browser/chunks/advanced.js +1 -1
- package/dist/browser/chunks/api.js +1 -1
- package/dist/browser/chunks/core.js +1 -1
- package/dist/browser/chunks/renderers.js +1 -1
- package/dist/browser/embed-bootstrap.js +1 -1
- package/dist/browser/embed-sdk.js +1 -1
- package/dist/esm/chunks/ABTestManager.js +1 -1
- package/dist/esm/chunks/advanced.js +1 -1
- package/dist/esm/chunks/api.js +1 -1
- package/dist/esm/chunks/core.js +1 -1
- package/dist/esm/chunks/renderers.js +1 -1
- package/dist/esm/embed-bootstrap.js +1 -1
- package/dist/esm/embed-sdk.js +1 -1
- package/dist/esm/types/abTesting/ABTestElement.d.ts +57 -3
- package/dist/esm/types/abTesting/ABTestManager.d.ts +27 -0
- package/dist/esm/types/core/analytics-tracker.d.ts +6 -0
- package/dist/esm/types/core/auth-detector.d.ts +2 -0
- package/dist/esm/types/core/constants.d.ts +1 -1
- package/dist/esm/types/core/version.d.ts +1 -0
- package/dist/esm/types/translations/TranslationElement.d.ts +12 -0
- package/dist/esm/types/utils/editor-session-access.d.ts +15 -0
- package/dist/esm/types/utils/editor-session-response.d.ts +21 -0
- package/dist/esm/types/utils/gateway-request.d.ts +29 -0
- package/dist/esm/types/utils/mount-direct-widget.d.ts +23 -0
- package/dist/esm/types/utils/public-embed-lookup.d.ts +8 -2
- package/dist/esm/types/utils/published-host-bridge.d.ts +26 -5
- package/dist/umd/embed-bootstrap.js +1 -1
- package/dist/umd/embed-sdk.js +1 -1
- package/package.json +6 -4
package/dist/esm/embed-sdk.js
CHANGED
|
@@ -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};
|
|
@@ -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
|
*/
|
|
@@ -22,6 +22,8 @@ export interface CompositionOwnership {
|
|
|
22
22
|
export declare class AuthDetector {
|
|
23
23
|
private authApi;
|
|
24
24
|
private compositionsApi;
|
|
25
|
+
/** The API the clients below talk to: whether a page can read its answer to the session check depends on it. */
|
|
26
|
+
private readonly apiUrl;
|
|
25
27
|
private sessionCache;
|
|
26
28
|
private sessionCacheExpiry;
|
|
27
29
|
private ownershipCache;
|
|
@@ -43,7 +43,7 @@ export declare const SDK_DEFAULTS: {
|
|
|
43
43
|
LOG_LEVEL: "info";
|
|
44
44
|
VERSION: string;
|
|
45
45
|
};
|
|
46
|
-
export declare const SDK_VERSION = "2.
|
|
46
|
+
export declare const SDK_VERSION = "2.1.3";
|
|
47
47
|
export declare function getDefaultVersionedApiUrl(): string;
|
|
48
48
|
export declare const API_DEFAULTS: {
|
|
49
49
|
DEV_API_URL: string;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const PACKAGE_VERSION = "2.1.3";
|
|
@@ -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
|
/**
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export interface EditorSessionAccessInput {
|
|
2
|
+
/** `window.location.hostname` of the page the SDK runs on. */
|
|
3
|
+
pageHostname: string;
|
|
4
|
+
/** The API the SDK talks to (`getApiUrl()`). */
|
|
5
|
+
apiUrl: string;
|
|
6
|
+
/** Widgetic's production API; defaults to the SDK's constant. Tests pass their own. */
|
|
7
|
+
productionApiUrl?: string;
|
|
8
|
+
/** Widgetic's own site; its host and every subdomain of it count as Widgetic's own pages. Defaults to the SDK's constant. */
|
|
9
|
+
widgeticSiteUrl?: string;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Whether a page can read the API's answer to "who is logged in", so that asking is worth a request.
|
|
13
|
+
* Everything unknown is answered "yes": the SDK stays quiet only where it knows the answer cannot be read.
|
|
14
|
+
*/
|
|
15
|
+
export declare function canReadEditorSession(input: EditorSessionAccessInput): boolean;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/** What the SDK keeps of the person logged in. The API's session is Supabase's: `access_token` and `user` come back camel-cased. */
|
|
2
|
+
export interface EditorSession {
|
|
3
|
+
accessToken: string;
|
|
4
|
+
user: {
|
|
5
|
+
id: string;
|
|
6
|
+
email?: string;
|
|
7
|
+
[field: string]: unknown;
|
|
8
|
+
};
|
|
9
|
+
[field: string]: unknown;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* The payload of an API answer: `data` of the `{ success, data }` envelope, or the value itself when it is not wrapped.
|
|
13
|
+
* An object counts as the envelope only when it has a boolean `success` and a `data` field, so a composition or a
|
|
14
|
+
* session that happens to have a `data` field of its own is never unwrapped by mistake.
|
|
15
|
+
*/
|
|
16
|
+
export declare function unwrapApiData(body: unknown): unknown;
|
|
17
|
+
/**
|
|
18
|
+
* The logged-in person from the body of `GET /auth/session`, or `null` when nobody is logged in or the body is not a
|
|
19
|
+
* session (an empty `data`, an HTML page, a login answer without a user). It never throws.
|
|
20
|
+
*/
|
|
21
|
+
export declare function readEditorSession(body: unknown): EditorSession | null;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Small helpers for the calls the SDK makes to the gateway's authenticated routes through the generated API client.
|
|
3
|
+
*/
|
|
4
|
+
/**
|
|
5
|
+
* A new `Idempotency-Key` for one call.
|
|
6
|
+
*
|
|
7
|
+
* The gateway refuses a POST or a PUT on the content routes that carries none (400 `VALIDATION_FIELD_REQUIRED`,
|
|
8
|
+
* "Idempotency-Key header is required"), including the check that saves nothing, and it accepts 8 to 50 letters, digits,
|
|
9
|
+
* dashes and underscores. A UUID fits. `crypto.randomUUID` is missing in older browsers and outside secure contexts, so
|
|
10
|
+
* the fallback builds a version 4 shaped key from `Math.random`: the gateway only compares keys, it does not need them
|
|
11
|
+
* to be unguessable, and a key is never reused for a second call (a reused key would replay the first answer).
|
|
12
|
+
*/
|
|
13
|
+
export declare function createIdempotencyKey(): string;
|
|
14
|
+
/**
|
|
15
|
+
* The part of a gateway answer that holds the result.
|
|
16
|
+
*
|
|
17
|
+
* The gateway wraps an answer as `{ success, data }`. This returns `data` when the answer has one and the answer itself
|
|
18
|
+
* when it does not (an operation the gateway answers unwrapped), so a caller reads the same fields either way.
|
|
19
|
+
*/
|
|
20
|
+
export declare function unwrapGatewayAnswer(answer: Record<string, unknown>): Record<string, unknown>;
|
|
21
|
+
/**
|
|
22
|
+
* The result of a call made through the generated client's `...Raw` method, as the gateway sent it.
|
|
23
|
+
*
|
|
24
|
+
* The client's typed value is not used for these operations: it keeps only the fields its model names at the top of the
|
|
25
|
+
* body, and for `validateCompositionContent` and `setDynamicContent` the model describes what is inside `data` while
|
|
26
|
+
* the gateway sends it wrapped (`{ success, data }`), so `valid` and `validationResult` came back missing and every
|
|
27
|
+
* check read as invalid. An answer that is not a JSON object is read as empty.
|
|
28
|
+
*/
|
|
29
|
+
export declare function readGatewayAnswer(rawResponse: Response): Promise<Record<string, unknown>>;
|
|
@@ -45,6 +45,29 @@ export declare function updateDirectMount(host: HTMLElement, nextOverlay: {
|
|
|
45
45
|
contentItems?: unknown[];
|
|
46
46
|
}): boolean;
|
|
47
47
|
export declare function destroyDirectMount(host: HTMLElement): void;
|
|
48
|
+
/**
|
|
49
|
+
* The size the iframe of the same tag gets when the embed code names none (`mountIframeInto` in
|
|
50
|
+
* hydrate-published-host.ts passes "400" and "300"). A widget mounted in the page has the box it would have had in the
|
|
51
|
+
* frame, whichever way the tag is rendered, so removing `render-mode="iframe"` does not change how big the widget is.
|
|
52
|
+
*/
|
|
53
|
+
export declare const DIRECT_BOX_DEFAULTS: {
|
|
54
|
+
readonly WIDTH_PIXELS: 400;
|
|
55
|
+
readonly HEIGHT_PIXELS: 300;
|
|
56
|
+
};
|
|
57
|
+
/**
|
|
58
|
+
* The CSS length for a `width` or `height` of an embed code. An iframe reads `height="405"` as 405px and `width="100%"`
|
|
59
|
+
* as a percentage; the `div` that is the box of a widget mounted in the page reads neither, so the box says it in CSS.
|
|
60
|
+
* A value that is not a number or a number with a unit gives the fallback, in pixels.
|
|
61
|
+
*/
|
|
62
|
+
export declare function cssLengthOfEmbedAttribute(value: string | null | undefined, fallbackPixels: number): string;
|
|
63
|
+
/**
|
|
64
|
+
* The rules, in the shadow root and ahead of the module's own, that make the mount target what `#app.widgetic-root-el`
|
|
65
|
+
* is in the widget's frame page: it fills the box, and so does the first thing the module puts in it (the widget's root;
|
|
66
|
+
* a second node, such as a portal container, keeps its own size). A rule of the module's own with the same weight,
|
|
67
|
+
* written after these, wins. A module built before this has none of these rules of its own, which is why the SDK has
|
|
68
|
+
* them and not only newer builds.
|
|
69
|
+
*/
|
|
70
|
+
export declare const DIRECT_BOX_STYLES = ".widgetic-direct-target { width: 100%; height: 100%; }\n.widgetic-direct-target > :first-child { width: 100%; height: 100%; min-width: 0; min-height: 0; }\n";
|
|
48
71
|
/**
|
|
49
72
|
* Loads the module and mounts it. Returns false when the module is missing,
|
|
50
73
|
* the contract is not 2, the load fails, or the host changed while loading.
|
|
@@ -4,8 +4,14 @@
|
|
|
4
4
|
*
|
|
5
5
|
* Order:
|
|
6
6
|
* 1. <script data-api-url> / window.WIDGETIC_EMBED_API (explicit override: local runs, tests)
|
|
7
|
-
* 2.
|
|
8
|
-
*
|
|
7
|
+
* 2. getApiUrl() / api.widgetic.com (new platform API): its answer carries the embed's address, its entries and its
|
|
8
|
+
* adapters, and is read as soon as it comes
|
|
9
|
+
* 3. The CDN copy of the address (a lookup script, no CORS: it works on CodePen), for a gateway that gave no answer. A
|
|
10
|
+
* copy the page already holds (the script's global is set) is known before step 2 and costs nothing; one that is not
|
|
11
|
+
* there is requested only after step 2. Asked first, it is a round trip made before the gateway's own, and where the
|
|
12
|
+
* CDN holds no copy it answers 404 with an HTML page (checked on 27 October 2026 for two widgets, a quarter of a
|
|
13
|
+
* second each) that the browser refuses as a script (`net::ERR_BLOCKED_BY_ORB`): the wait comes before every embed,
|
|
14
|
+
* and the failed request shows in the console of the customer's page.
|
|
9
15
|
*
|
|
10
16
|
* api.widgetic.com is the new API host. Legacy REST is widgetic.com/api/v2.
|
|
11
17
|
* The development gateways (the Render service, localhost:3000) are no longer
|
|
@@ -12,6 +12,12 @@ export interface AbGoalAssignment {
|
|
|
12
12
|
}
|
|
13
13
|
/** The capability a widget lists in `widgetic:ready` when it reports which element of a goal was used. */
|
|
14
14
|
export declare const GOAL_REPORTER_CAPABILITY = "goal-reporter";
|
|
15
|
+
/** What the page changes in a running widget (`widgetic:update`): its design, its content, its list of items. */
|
|
16
|
+
interface WidgetUpdate {
|
|
17
|
+
design?: Record<string, string>;
|
|
18
|
+
content?: Record<string, unknown>;
|
|
19
|
+
contentItems?: unknown[];
|
|
20
|
+
}
|
|
15
21
|
declare class PublishedHostBridge {
|
|
16
22
|
private readonly host;
|
|
17
23
|
private readonly iframe;
|
|
@@ -19,6 +25,7 @@ declare class PublishedHostBridge {
|
|
|
19
25
|
private readonly compositionId;
|
|
20
26
|
private readonly services?;
|
|
21
27
|
private readyDispatched;
|
|
28
|
+
private pendingWidgetUpdate;
|
|
22
29
|
private latestAbGoal;
|
|
23
30
|
private latestWorkflowWatch;
|
|
24
31
|
private attributeFlushScheduled;
|
|
@@ -42,15 +49,29 @@ declare class PublishedHostBridge {
|
|
|
42
49
|
*/
|
|
43
50
|
sendWorkflowWatch(watch: WorkflowWatch): void;
|
|
44
51
|
private postWorkflowWatch;
|
|
45
|
-
sendWidgetUpdate(payload:
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
52
|
+
sendWidgetUpdate(payload: WidgetUpdate): void;
|
|
53
|
+
/** Sends the update the page asked for while the frame was blank, if there is one and the frame can take it now. */
|
|
54
|
+
private flushPendingWidgetUpdate;
|
|
55
|
+
/**
|
|
56
|
+
* Whether the frame can be written to. A frame that holds only its blank first document is on the page's own origin,
|
|
57
|
+
* so it refuses every message addressed to the gateway, with a warning in the customer's console (see
|
|
58
|
+
* `iframeStillBlank`).
|
|
59
|
+
*/
|
|
60
|
+
private frameCanReceive;
|
|
50
61
|
private handleWrapperMessage;
|
|
51
62
|
private dispatchHostEvent;
|
|
52
63
|
destroy(): void;
|
|
53
64
|
}
|
|
65
|
+
/**
|
|
66
|
+
* True while the iframe still holds its initial blank document. A message addressed to the gateway has nowhere to go
|
|
67
|
+
* then: that window's origin is the page's own, not the gateway's, so the browser refuses it with a warning in the
|
|
68
|
+
* customer's console. Every default embed code met it (the page's own change of the host, such as the SDK marking it
|
|
69
|
+
* mounted, sent a widget update a moment after the frame was added). The bridge holds its snapshot, goal, watch and
|
|
70
|
+
* updates back while this is true; the `load` listener and `widgetic:ready` send them once the frame page is there. A frame
|
|
71
|
+
* that has gone on to the gateway is cross-origin and refuses to say where it is, and so does anything else that cannot be
|
|
72
|
+
* read: those are treated as loaded, which is what the bridge did before.
|
|
73
|
+
*/
|
|
74
|
+
export declare function iframeStillBlank(iframe: HTMLIFrameElement): boolean;
|
|
54
75
|
/**
|
|
55
76
|
* Attaches the host bridge for a published iframe mount.
|
|
56
77
|
*
|