@widgetic/embed-sdk 2.0.10 → 2.0.12
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/LICENSE +122 -0
- package/README.md +6 -2
- package/dist/browser/chunks/advanced.js +1 -1
- package/dist/browser/chunks/api.js +1 -1
- package/dist/browser/chunks/display.js +1 -1
- package/dist/browser/chunks/renderers.js +1 -1
- package/dist/browser/chunks/scanner.js +1 -1
- package/dist/browser/embed-bootstrap.js +1 -1
- package/dist/browser/embed-sdk.js +1 -1
- package/dist/esm/chunks/advanced.js +1 -1
- package/dist/esm/chunks/api.js +1 -1
- package/dist/esm/chunks/display.js +1 -1
- package/dist/esm/chunks/renderers.js +1 -1
- package/dist/esm/chunks/scanner.js +1 -1
- package/dist/esm/embed-bootstrap.js +1 -1
- package/dist/esm/embed-sdk.js +1 -1
- package/dist/esm/types/utils/chrome-labels.d.ts +26 -0
- package/dist/esm/types/utils/hydrate-published-host.d.ts +3 -2
- package/dist/esm/types/utils/mount-direct-widget.d.ts +25 -0
- package/dist/esm/types/utils/public-embed-lookup.d.ts +6 -0
- package/dist/umd/embed-bootstrap.js +1 -1
- package/dist/umd/embed-sdk.js +1 -1
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
import{_ as t}from"./chunks/vendor.js";import{l as e,h as i,a as n}from"./chunks/core.js";import"./chunks/api.js";import"./chunks/renderers.js";import"./chunks/media.js";import"./chunks/messaging.js";import"./chunks/display.js";import"./chunks/advanced.js";import"./chunks/scanner.js";import"./chunks/performance.js";import"./chunks/security.js";class s{constructor(){this.foundWidgets=[],this.scanStartTime=0}scan(){this.scanStartTime=performance.now();const t=["[data-composition-id]","[data-widget-id]","widgetic-widget","widgetic"],i=[];for(const e of t){const t=document.querySelectorAll(e);for(const e of Array.from(t))this.isValidWidget(e)&&i.push(e)}this.foundWidgets=i;const n=performance.now()-this.scanStartTime;return e.info(`FastScanner: Found ${i.length} widgets in ${n.toFixed(2)}ms`),i}isValidWidget(t){return t.hasAttribute("data-composition-id")||t.hasAttribute("data-widget-id")||t.hasAttribute("composition-id")}getScanTime(){return this.scanStartTime>0?performance.now()-this.scanStartTime:0}}class a{constructor(){this.loadedChunks=new Set,this.loadingPromises=new Map,this.loadStartTime=0,this.loadStartTime=performance.now()}loadCoreChunks(){return t(this,void 0,void 0,(function*(){const t=[this.loadChunk("core",(()=>import("./chunks/core.js").then((function(t){return t.o})))),this.loadChunk("scanner",(()=>import("./chunks/scanner.js").then((function(t){return t.c})))),this.loadChunk("scanner",(()=>import("./chunks/scanner.js").then((function(t){return t.e}))))];yield Promise.all(t),e.debug("ProgressiveLoader: Core chunks loaded")}))}loadRenderingChunks(){return t(this,void 0,void 0,(function*(){const t=[this.loadChunk("renderers",(()=>import("./chunks/renderers.js").then((function(t){return t.w})))),this.loadChunk("renderers",(()=>import("./chunks/renderers.js").then((function(t){return t.c})))),this.loadChunk("renderers",(()=>import("./chunks/renderers.js").then((function(t){return t.i}))))];yield Promise.all(t),e.debug("ProgressiveLoader: Rendering chunks loaded")}))}loadApiChunks(){return t(this,void 0,void 0,(function*(){const t=[this.loadChunk("api",(()=>import("./chunks/api.js").then((function(t){return t.
|
|
1
|
+
import{_ as t}from"./chunks/vendor.js";import{l as e,h as i,a as n}from"./chunks/core.js";import"./chunks/api.js";import"./chunks/renderers.js";import"./chunks/media.js";import"./chunks/messaging.js";import"./chunks/display.js";import"./chunks/advanced.js";import"./chunks/scanner.js";import"./chunks/performance.js";import"./chunks/security.js";class s{constructor(){this.foundWidgets=[],this.scanStartTime=0}scan(){this.scanStartTime=performance.now();const t=["[data-composition-id]","[data-widget-id]","widgetic-widget","widgetic"],i=[];for(const e of t){const t=document.querySelectorAll(e);for(const e of Array.from(t))this.isValidWidget(e)&&i.push(e)}this.foundWidgets=i;const n=performance.now()-this.scanStartTime;return e.info(`FastScanner: Found ${i.length} widgets in ${n.toFixed(2)}ms`),i}isValidWidget(t){return t.hasAttribute("data-composition-id")||t.hasAttribute("data-widget-id")||t.hasAttribute("composition-id")}getScanTime(){return this.scanStartTime>0?performance.now()-this.scanStartTime:0}}class a{constructor(){this.loadedChunks=new Set,this.loadingPromises=new Map,this.loadStartTime=0,this.loadStartTime=performance.now()}loadCoreChunks(){return t(this,void 0,void 0,(function*(){const t=[this.loadChunk("core",(()=>import("./chunks/core.js").then((function(t){return t.o})))),this.loadChunk("scanner",(()=>import("./chunks/scanner.js").then((function(t){return t.c})))),this.loadChunk("scanner",(()=>import("./chunks/scanner.js").then((function(t){return t.e}))))];yield Promise.all(t),e.debug("ProgressiveLoader: Core chunks loaded")}))}loadRenderingChunks(){return t(this,void 0,void 0,(function*(){const t=[this.loadChunk("renderers",(()=>import("./chunks/renderers.js").then((function(t){return t.w})))),this.loadChunk("renderers",(()=>import("./chunks/renderers.js").then((function(t){return t.c})))),this.loadChunk("renderers",(()=>import("./chunks/renderers.js").then((function(t){return t.i}))))];yield Promise.all(t),e.debug("ProgressiveLoader: Rendering chunks loaded")}))}loadApiChunks(){return t(this,void 0,void 0,(function*(){const t=[this.loadChunk("api",(()=>import("./chunks/api.js").then((function(t){return t.y})))),this.loadChunk("api",(()=>import("./chunks/api.js").then((function(t){return t.z}))))];yield Promise.all(t),e.debug("ProgressiveLoader: API chunks loaded")}))}loadFeatureChunk(i){return t(this,void 0,void 0,(function*(){switch(i){case"messaging":return this.loadChunk("messaging",(()=>import("./chunks/messaging.js")));case"media":return this.loadChunk("media",(()=>import("./chunks/media.js").then((function(t){return t.m}))));case"performance":return this.loadChunk("performance",(()=>import("./chunks/performance.js").then((function(t){return t.p}))));case"advanced":return this.loadChunk("advanced",(()=>import("./chunks/advanced.js").then((function(t){return t.i}))));case"security":return this.loadChunk("security",(()=>import("./chunks/security.js").then((function(t){return t.a}))));case"display":return this.loadChunk("display",(()=>import("./chunks/display.js").then((function(t){return t.d}))));case"abTesting":return this.loadChunk("abTesting",(()=>import("./chunks/ABTestManager.js")));default:return e.warn(`ProgressiveLoader: Unknown feature '${i}'`),null}}))}loadChunk(i,n){return t(this,void 0,void 0,(function*(){if(this.loadedChunks.has(i))return;if(this.loadingPromises.has(i))return this.loadingPromises.get(i);const t=n().then((t=>(this.loadedChunks.add(i),e.debug(`ProgressiveLoader: Loaded chunk '${i}'`),t))).catch((t=>{throw e.error(`ProgressiveLoader: Failed to load chunk '${i}'`,t),t}));return this.loadingPromises.set(i,t),t}))}getLoadedChunks(){return Array.from(this.loadedChunks)}getTotalLoadTime(){return performance.now()-this.loadStartTime}}class r{constructor(t={}){this.scanner=new s,this.loader=new a,this.config=Object.assign({debug:!1,preloadCritical:!0,scanInterval:0,enableLazyLoading:!0},t),this.initStartTime=performance.now(),this.stats={scanTime:0,widgetsFound:0,chunksLoaded:[],totalLoadTime:0},this.config.debug&&(i.setDebug(!0),i.setLevel("debug"))}initialize(){return t(this,void 0,void 0,(function*(){try{e.info("WidgeticBootstrap: Starting fast initialization...");const t=this.scanner.scan();if(this.stats.widgetsFound=t.length,this.stats.scanTime=this.scanner.getScanTime(),0===t.length)return e.info("WidgeticBootstrap: No widgets found, minimal initialization"),this.finalizeStats(),this.stats;this.config.preloadCritical&&(yield this.loader.loadCoreChunks());const i=this.analyzeWidgetRequirements(t);let n=[];try{const{analyzeWidgetRequirementsEnhanced:e}=yield import("./chunks/scanner.js").then((function(t){return t.w}));n=e(t)}catch(t){}const s=[...new Set([...i,...n])];return yield this.loadRequiredChunks(s),yield this.initializeFullSDK(t),this.finalizeStats(),e.info(`WidgeticBootstrap: Initialization complete in ${this.stats.totalLoadTime.toFixed(2)}ms`),this.stats}catch(t){throw e.error("WidgeticBootstrap: Initialization failed",t),t}}))}analyzeWidgetRequirements(t){const i=new Set;i.add("rendering"),i.add("api");for(const e of t){("widgetic-abtest"===e.tagName.toLowerCase()||e.hasAttribute("experiment-id")||e.hasAttribute("data-ab-test"))&&(i.add("abTesting"),i.add("messaging")),e.hasAttribute("data-interactive")&&i.add("messaging");const t=this.extractWidgetCapabilities(e);t.length>0&&t.forEach((t=>i.add(t)));const n=e.getAttribute("data-widget-id")||"",s=e.getAttribute("data-widget-type")||"";(n.includes("video")||n.includes("audio")||n.includes("media")||"media"===s)&&i.add("media"),(e.hasAttribute("data-editing")||"editing"===e.getAttribute("data-render-mode"))&&i.add("advanced");const a=e.getAttribute("data-display-mode");"overlay"!==a&&"popup"!==a&&"fullscreen"!==a||i.add("display"),(n.includes("form")||n.includes("input")||n.includes("contact")||"form"===s)&&i.add("security"),"gallery"!==s&&"interactive"!==s||i.add("messaging")}return e.debug("WidgeticBootstrap: Required features:",Array.from(i)),Array.from(i)}extractWidgetCapabilities(t){var i;const n=[];try{const e=t.getAttribute("data-widget-meta");if(e){const t=JSON.parse(e);(t.mediaCapabilities||t.supportsMedia)&&n.push("media"),(t.textCapabilities||t.supportsText||t.hasTextFields)&&n.push("security"),(t.supportsInteraction||t.hasInteractiveElements)&&n.push("messaging"),(t.supportsFullscreen||t.supportsOverlay)&&n.push("display"),(t.supportsABTesting||t.trackingCapabilities)&&n.push("abTesting")}const s=t.getAttribute("data-widget-type");if(s)switch(s){case"media":n.push("media");break;case"form":n.push("security","messaging");break;case"gallery":case"interactive":n.push("messaging")}if(t.matches("widgetic-widget[data-capabilities]")){const e=(null===(i=t.getAttribute("data-capabilities"))||void 0===i?void 0:i.split(","))||[];n.push(...e.map((t=>t.trim())))}}catch(t){e.debug("Failed to parse widget metadata, using fallback detection",{error:t})}return n}loadRequiredChunks(e){return t(this,void 0,void 0,(function*(){const t=[];for(const i of e)switch(i){case"rendering":t.push(this.loader.loadRenderingChunks());break;case"api":t.push(this.loader.loadApiChunks());break;default:t.push(this.loader.loadFeatureChunk(i))}yield Promise.all(t)}))}initializeFullSDK(i){return t(this,void 0,void 0,(function*(){var t;const{getSDK:n}=yield import("./chunks/api.js").then((function(t){return t.G})),s=n({debug:this.config.debug,lazyLoading:{enabled:null===(t=this.config.enableLazyLoading)||void 0===t||t,config:{}}});yield s.init(),e.info(`WidgeticBootstrap: Processing ${i.length} widgets through full SDK`)}))}finalizeStats(){this.stats.totalLoadTime=performance.now()-this.initStartTime,this.stats.chunksLoaded=this.loader.getLoadedChunks()}getStats(){return Object.assign({},this.stats)}}let o=null;function d(i){return t(this,void 0,void 0,(function*(){return o?(e.warn("WidgeticBootstrap: Already initialized"),o.getStats()):(o=new r(i),yield o.initialize())}))}function u(){return(null==o?void 0:o.getStats())||null}if("undefined"!=typeof document){const t=()=>{window.__WIDGETIC_SDK_INITIALIZED__||d({debug:"development"===n.NODE_ENV,preloadCritical:!0}).catch((t=>{e.error("WidgeticBootstrap: Auto-initialization failed",t)}))};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",t):setTimeout(t,0)}"undefined"!=typeof window&&(window.WidgeticBootstrap={init:d,getStats:u,version:"1.0.0"});export{r as BootstrapManager,s as FastWidgetScanner,a as ProgressiveChunkLoader,u as getBootstrapStats,d as initializeWidgeticFast};
|
package/dist/esm/embed-sdk.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{h as e,W as r,i as c,j as l,k as h,l as y}from"./chunks/api.js";export{n as AuthError,A as AuthManager,B as BatchApiClient,C as CSSDebugger,D as DefaultTokenProvider,m as EndpointTokenProvider,F as FunctionTokenProvider,H as HighLevelAPI,L as LowLevelAPI,w as MidLevelAPI,p as ModuleLoader,S as StaticApiKeyProvider,u as analyzeWidgetCSS,t as disableCSSDebug,s as enableCSSDebug,g as getBatchClient,b as getModuleLoader,v as monitorWidgetCSS,o as resetBatchClient,q as resetModuleLoader}from"./chunks/api.js";import{l as E,d as T,V as x,h as _,e as R,a as M}from"./chunks/core.js";export{b as getApiUrl,n as getAuthManager,f as getCdnUrl,j as getConfiguration,k as getTokenProvider,s as setApiKey,i as setTokenProvider}from"./chunks/core.js";import{r as O,W as N}from"./chunks/renderers.js";export{C as CustomElementRenderer,I as IframeRenderer,a as WidgetRenderer,g as getWidgetRenderer,b as resetWidgetRenderer}from"./chunks/renderers.js";export{WidgeticMessenger,getMessenger,resetMessenger}from"./chunks/messaging.js";import{ABTestManager as W}from"./chunks/ABTestManager.js";import{_ as z}from"./chunks/vendor.js";import{C as P,A as Q,e as K}from"./chunks/advanced.js";export{f as toCamel,t as toSnake}from"./chunks/advanced.js";import{g as U}from"./chunks/scanner.js";export{d as detectBrowserCapabilities,a as determineBestRenderMode,i as isValidWidgetElement,p as parseWidgetConfig}from"./chunks/scanner.js";import"./chunks/display.js";import"./chunks/performance.js";import"./chunks/security.js";import"./chunks/media.js";class V{constructor(t){this.deviceDetector=e(),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},t),this.sessionId=this.initializeSession(),this.rateLimitState={eventCounts:new Map,windowStart:Date.now(),windowDurationMs:6e4},this.setupEventListeners(),this.loadQueuedEvents(),E.debug("[AnalyticsTracker] Initialized",{compositionId:this.config.compositionId,sessionId:this.sessionId})}static getInstance(e){if(!V.instance&&e&&(V.instance=new V(e)),!V.instance)throw new Error("AnalyticsTracker must be initialized with config first");return V.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){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){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?(E.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(),E.debug("[AnalyticsTracker] Event queued",{eventType:e.eventType,queueSize:this.eventQueue.length})):E.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 z(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(),E.debug("[AnalyticsTracker] Batch sent successfully",{batchSize:e.length,remainingQueue:this.eventQueue.length})}catch(t){E.error("[AnalyticsTracker] Failed to send batch",{error:t,batchSize:e.length}),this.eventQueue.unshift(...e),setTimeout((()=>this.processBatch()),5e3)}}))}sendEventBatch(e){return z(this,void 0,void 0,(function*(){if(!this.config.apiEndpoint)return void E.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 T(),n=new P({basePath:this.config.apiEndpoint,accessToken:()=>z(this,void 0,void 0,(function*(){return i})),headers:{"X-SDK-Version":`embed-sdk/${x}`}}),s=new Q(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){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||[],E.debug("[AnalyticsTracker] Loaded queued events from storage",{count:this.eventQueue.length})):localStorage.removeItem(this.STORAGE_KEY)}}catch(e){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),E.debug("[AnalyticsTracker] Configuration updated",e)}clearQueue(){this.eventQueue=[],this.config.enableLocalStorage&&localStorage.removeItem(this.STORAGE_KEY),E.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)),V.instance=null,E.debug("[AnalyticsTracker] Destroyed")}}const $="undefined"!=typeof HTMLElement?HTMLElement:class{};class Y extends ${constructor(){super(),this.experimentId=null,this.assignment=null,this.widgetInstance=null,this.impressionTracked=!1,this.conversionListeners=new Map,this.manager=W.getInstance(),this.widgetManager=r.getInstance(),this.analyticsTracker=V.getInstance(),this.attachShadow({mode:"open"}),this.setupEventListeners()}static get observedAttributes(){return["experiment-id","user-id","session-id"]}connectedCallback(){return z(this,void 0,void 0,(function*(){try{if(this.experimentId=this.getAttribute("experiment-id"),!this.experimentId)return _.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 _.warn("No variant assignment received",{experimentId:this.experimentId}),void this.renderError("Test not available");yield this.renderVariant(),yield this.trackImpression(),this.setupConversionTracking(),_.info("A/B test element initialized",{experimentId:this.experimentId,variantId:this.assignment.variantId})}catch(e){_.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 z(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),this.dispatchEvent(new CustomEvent("variant-rendered",{detail:{experimentId:this.experimentId,variantId:this.assignment.variantId,compositionId:this.assignment.compositionId},bubbles:!0}))}catch(e){_.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 _.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 _.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(),_.debug("Conversion tracking setup complete",{experimentId:this.experimentId,variantId:this.assignment.variantId})}catch(e){_.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;this.isClickableElement(i)&&this.manager.trackConversion(this.experimentId,this.assignment.variantId,"clicks",{element:i.tagName.toLowerCase(),text:(null===(t=i.textContent)||void 0===t?void 0:t.slice(0,100))||"",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;"FORM"===t.tagName&&this.manager.trackConversion(this.experimentId,this.assignment.variantId,"submissions",{formId:t.id||"unknown",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;"VIDEO"!==t.tagName&&"AUDIO"!==t.tagName||this.manager.trackConversion(this.experimentId,this.assignment.variantId,"plays",{mediaType:t.tagName.toLowerCase(),duration:t.duration||0,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)})))}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 z(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}),_.debug("Impression tracked",{experimentId:this.experimentId,variantId:this.assignment.variantId})}catch(e){_.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;_.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;_.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){_.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",Y))}}Y.register();const G="undefined"!=typeof HTMLElement?HTMLElement:class{};class J extends G{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=c(),E.debug("[TranslationElement] Created translation element")}connectedCallback(){if(this.isInitialized)E.debug("[TranslationElement] Already initialized, skipping");else{if(this.experimentId=this.getAttribute("experiment-id"),!this.experimentId)return E.error("[TranslationElement] Missing experiment-id attribute"),void this.displayError("Missing experiment-id attribute");E.debug(`[TranslationElement] Connected with experiment ID: ${this.experimentId}`),this.initializeTranslation()}}disconnectedCallback(){E.debug("[TranslationElement] Disconnected"),this.cleanup()}initializeTranslation(){return z(this,void 0,void 0,(function*(){try{this.isInitialized=!0;const e=this.detectBrowserLanguages();if(E.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),E.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),E.info("[TranslationElement] Translation experiment loaded successfully",{experimentId:this.experimentId,selectedLanguage:this.selectedLanguage,compositionId:t})}catch(e){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 z(this,void 0,void 0,(function*(){try{const t=R(),i=new P({basePath:t,headers:{"X-SDK-Version":"embed-sdk/translations"}}),n=new K(i),s=yield n.getTranslationConfig({id:e});return(null==s?void 0:s.data)||null}catch(e){throw E.error("[TranslationElement] Error fetching translation experiment:",e),e}}))}findBestLanguageMatch(e,t){const i=Object.keys(t.languageCompositions||{}),n=t.rootLanguage||"en";E.debug("[TranslationElement] Available languages:",i),E.debug("[TranslationElement] Root language:",n);for(const t of e)if(i.includes(t))return E.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 E.debug("[TranslationElement] Found base language match:",n),this.trackFallbackUsage(t,n,"language_family").catch((e=>{E.debug("[TranslationElement] Failed to track language family fallback:",e)})),n}E.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=>{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 z(this,void 0,void 0,(function*(){const t=U(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=>{E.warn("[TranslationElement] Failed to send analytics:",e)}))}catch(e){E.warn("[TranslationElement] Error in analytics tracking:",e)}}sendAnalytics(e){return z(this,void 0,void 0,(function*(){try{const t=R(),i=new P({basePath:t,headers:{"X-SDK-Version":"embed-sdk/translations"}}),n=new K(i);yield n.submitTranslationAnalyticsEvent({id:this.experimentId,submitTranslationAnalyticsEventRequest:e})}catch(e){E.debug("[TranslationElement] Analytics request failed:",e)}}))}trackFallbackUsage(e,t,i){return z(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),E.debug("[TranslationElement] Fallback usage tracked:",{requested:e,selected:t,fallbackType:i})}catch(e){E.debug("[TranslationElement] Failed to track fallback usage:",e)}}))}handleInitializationError(e){return z(this,void 0,void 0,(function*(){if(this.retryCount<this.maxRetries){this.retryCount++,E.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){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",J),E.info("[TranslationElement] Custom element registered")))}catch(e){E.error("[TranslationElement] Failed to register custom element:",e)}}}J.register();const X=l();"undefined"!=typeof window&&"undefined"!=typeof customElements&&(O(),Y.register(),J.register()),"undefined"!=typeof window&&(window.WidgeticEmbedSDK=X,window.Widgetic={SDK:X,getSDK:l,EmbedSDK:h,config:{API_URL:M.API_URL,API_VERSION:M.API_VERSION,CLIENT_URL:M.CLIENT_URL,PRODUCTION_URL:M.PRODUCTION_URL,NODE_ENV:M.NODE_ENV},log:E,WidgeticWidget:N,registerWidgeticWidget:O,cssDebugger:y,enableCSSDebug:()=>y.enableDebugMode(),disableCSSDebug:()=>y.disableDebugMode(),analyzeWidget:e=>y.analyzeWidget(e),ABTestManager:W,ABTestElement:Y,TranslationElement:J});export{Y as ABTestElement,W as ABTestManager,h as EmbedSDK,J as TranslationElement,h as WidgeticEmbedSDK,N as WidgeticWidget,M as config,y as cssDebugger,X as default,U as generateInstanceId,T as getAuthToken,l as getSDK,E as log,O as registerWidgeticWidget};
|
|
1
|
+
import{i as e,W as r,j as c,k as l,l as h,m}from"./chunks/api.js";export{o as AuthError,A as AuthManager,B as BatchApiClient,C as CSSDebugger,D as DefaultTokenProvider,n as EndpointTokenProvider,F as FunctionTokenProvider,H as HighLevelAPI,L as LowLevelAPI,x as MidLevelAPI,q as ModuleLoader,S as StaticApiKeyProvider,v as analyzeWidgetCSS,u as disableCSSDebug,t as enableCSSDebug,g as getBatchClient,d as getModuleLoader,w as monitorWidgetCSS,p as resetBatchClient,s as resetModuleLoader}from"./chunks/api.js";import{l as y,d as E,V as T,h as _,e as R,a as M}from"./chunks/core.js";export{b as getApiUrl,n as getAuthManager,f as getCdnUrl,j as getConfiguration,k as getTokenProvider,s as setApiKey,i as setTokenProvider}from"./chunks/core.js";import{r as O,W as N}from"./chunks/renderers.js";export{C as CustomElementRenderer,I as IframeRenderer,a as WidgetRenderer,g as getWidgetRenderer,b as resetWidgetRenderer}from"./chunks/renderers.js";export{WidgeticMessenger,getMessenger,resetMessenger}from"./chunks/messaging.js";import{ABTestManager as W}from"./chunks/ABTestManager.js";import{_ as z}from"./chunks/vendor.js";import{C as P,A as Q,e as K}from"./chunks/advanced.js";export{f as toCamel,t as toSnake}from"./chunks/advanced.js";import{g as U}from"./chunks/scanner.js";export{d as detectBrowserCapabilities,a as determineBestRenderMode,i as isValidWidgetElement,p as parseWidgetConfig}from"./chunks/scanner.js";import"./chunks/display.js";import"./chunks/performance.js";import"./chunks/security.js";import"./chunks/media.js";class V{constructor(t){this.deviceDetector=e(),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},t),this.sessionId=this.initializeSession(),this.rateLimitState={eventCounts:new Map,windowStart:Date.now(),windowDurationMs:6e4},this.setupEventListeners(),this.loadQueuedEvents(),y.debug("[AnalyticsTracker] Initialized",{compositionId:this.config.compositionId,sessionId:this.sessionId})}static getInstance(e){if(!V.instance&&e&&(V.instance=new V(e)),!V.instance)throw new Error("AnalyticsTracker must be initialized with config first");return V.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){y.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){y.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?(y.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(),y.debug("[AnalyticsTracker] Event queued",{eventType:e.eventType,queueSize:this.eventQueue.length})):y.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 z(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(),y.debug("[AnalyticsTracker] Batch sent successfully",{batchSize:e.length,remainingQueue:this.eventQueue.length})}catch(t){y.error("[AnalyticsTracker] Failed to send batch",{error:t,batchSize:e.length}),this.eventQueue.unshift(...e),setTimeout((()=>this.processBatch()),5e3)}}))}sendEventBatch(e){return z(this,void 0,void 0,(function*(){if(!this.config.apiEndpoint)return void y.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 E(),n=new P({basePath:this.config.apiEndpoint,accessToken:()=>z(this,void 0,void 0,(function*(){return i})),headers:{"X-SDK-Version":`embed-sdk/${T}`}}),s=new Q(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){y.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||[],y.debug("[AnalyticsTracker] Loaded queued events from storage",{count:this.eventQueue.length})):localStorage.removeItem(this.STORAGE_KEY)}}catch(e){y.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),y.debug("[AnalyticsTracker] Configuration updated",e)}clearQueue(){this.eventQueue=[],this.config.enableLocalStorage&&localStorage.removeItem(this.STORAGE_KEY),y.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)),V.instance=null,y.debug("[AnalyticsTracker] Destroyed")}}const $="undefined"!=typeof HTMLElement?HTMLElement:class{};class Y extends ${constructor(){super(),this.experimentId=null,this.assignment=null,this.widgetInstance=null,this.impressionTracked=!1,this.conversionListeners=new Map,this.manager=W.getInstance(),this.widgetManager=r.getInstance(),this.analyticsTracker=V.getInstance(),this.attachShadow({mode:"open"}),this.setupEventListeners()}static get observedAttributes(){return["experiment-id","user-id","session-id"]}connectedCallback(){return z(this,void 0,void 0,(function*(){try{if(this.experimentId=this.getAttribute("experiment-id"),!this.experimentId)return _.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 _.warn("No variant assignment received",{experimentId:this.experimentId}),void this.renderError("Test not available");yield this.renderVariant(),yield this.trackImpression(),this.setupConversionTracking(),_.info("A/B test element initialized",{experimentId:this.experimentId,variantId:this.assignment.variantId})}catch(e){_.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 z(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),this.dispatchEvent(new CustomEvent("variant-rendered",{detail:{experimentId:this.experimentId,variantId:this.assignment.variantId,compositionId:this.assignment.compositionId},bubbles:!0}))}catch(e){_.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 _.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 _.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(),_.debug("Conversion tracking setup complete",{experimentId:this.experimentId,variantId:this.assignment.variantId})}catch(e){_.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;this.isClickableElement(i)&&this.manager.trackConversion(this.experimentId,this.assignment.variantId,"clicks",{element:i.tagName.toLowerCase(),text:(null===(t=i.textContent)||void 0===t?void 0:t.slice(0,100))||"",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;"FORM"===t.tagName&&this.manager.trackConversion(this.experimentId,this.assignment.variantId,"submissions",{formId:t.id||"unknown",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;"VIDEO"!==t.tagName&&"AUDIO"!==t.tagName||this.manager.trackConversion(this.experimentId,this.assignment.variantId,"plays",{mediaType:t.tagName.toLowerCase(),duration:t.duration||0,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)})))}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 z(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}),_.debug("Impression tracked",{experimentId:this.experimentId,variantId:this.assignment.variantId})}catch(e){_.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;_.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;_.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){_.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",Y))}}Y.register();const G="undefined"!=typeof HTMLElement?HTMLElement:class{};class J extends G{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=c(),y.debug("[TranslationElement] Created translation element")}connectedCallback(){if(this.isInitialized)y.debug("[TranslationElement] Already initialized, skipping");else{if(this.experimentId=this.getAttribute("experiment-id"),!this.experimentId)return y.error("[TranslationElement] Missing experiment-id attribute"),void this.displayError("Missing experiment-id attribute");y.debug(`[TranslationElement] Connected with experiment ID: ${this.experimentId}`),this.initializeTranslation()}}disconnectedCallback(){y.debug("[TranslationElement] Disconnected"),this.cleanup()}initializeTranslation(){return z(this,void 0,void 0,(function*(){try{this.isInitialized=!0;const e=this.detectBrowserLanguages();if(y.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),y.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),y.info("[TranslationElement] Translation experiment loaded successfully",{experimentId:this.experimentId,selectedLanguage:this.selectedLanguage,compositionId:t})}catch(e){y.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 z(this,void 0,void 0,(function*(){try{const t=R(),i=new P({basePath:t,headers:{"X-SDK-Version":"embed-sdk/translations"}}),n=new K(i),s=yield n.getTranslationConfig({id:e});return(null==s?void 0:s.data)||null}catch(e){throw y.error("[TranslationElement] Error fetching translation experiment:",e),e}}))}findBestLanguageMatch(e,t){const i=Object.keys(t.languageCompositions||{}),n=t.rootLanguage||"en";y.debug("[TranslationElement] Available languages:",i),y.debug("[TranslationElement] Root language:",n);for(const t of e)if(i.includes(t))return y.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 y.debug("[TranslationElement] Found base language match:",n),this.trackFallbackUsage(t,n,"language_family").catch((e=>{y.debug("[TranslationElement] Failed to track language family fallback:",e)})),n}y.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=>{y.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 z(this,void 0,void 0,(function*(){const t=U(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=>{y.warn("[TranslationElement] Failed to send analytics:",e)}))}catch(e){y.warn("[TranslationElement] Error in analytics tracking:",e)}}sendAnalytics(e){return z(this,void 0,void 0,(function*(){try{const t=R(),i=new P({basePath:t,headers:{"X-SDK-Version":"embed-sdk/translations"}}),n=new K(i);yield n.submitTranslationAnalyticsEvent({id:this.experimentId,submitTranslationAnalyticsEventRequest:e})}catch(e){y.debug("[TranslationElement] Analytics request failed:",e)}}))}trackFallbackUsage(e,t,i){return z(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),y.debug("[TranslationElement] Fallback usage tracked:",{requested:e,selected:t,fallbackType:i})}catch(e){y.debug("[TranslationElement] Failed to track fallback usage:",e)}}))}handleInitializationError(e){return z(this,void 0,void 0,(function*(){if(this.retryCount<this.maxRetries){this.retryCount++,y.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){y.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",J),y.info("[TranslationElement] Custom element registered")))}catch(e){y.error("[TranslationElement] Failed to register custom element:",e)}}}J.register();const X=l();"undefined"!=typeof window&&"undefined"!=typeof customElements&&(O(),Y.register(),J.register()),"undefined"!=typeof window&&(window.WidgeticEmbedSDK=X,window.Widgetic={SDK:X,getSDK:l,EmbedSDK:h,config:{API_URL:M.API_URL,API_VERSION:M.API_VERSION,CLIENT_URL:M.CLIENT_URL,PRODUCTION_URL:M.PRODUCTION_URL,NODE_ENV:M.NODE_ENV},log:y,WidgeticWidget:N,registerWidgeticWidget:O,cssDebugger:m,enableCSSDebug:()=>m.enableDebugMode(),disableCSSDebug:()=>m.disableDebugMode(),analyzeWidget:e=>m.analyzeWidget(e),ABTestManager:W,ABTestElement:Y,TranslationElement:J});export{Y as ABTestElement,W as ABTestManager,h as EmbedSDK,J as TranslationElement,h as WidgeticEmbedSDK,N as WidgeticWidget,M as config,m as cssDebugger,X as default,U as generateInstanceId,E as getAuthToken,l as getSDK,y as log,O as registerWidgeticWidget};
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The few words the script draws itself on a partner's page: the accessible names of its close buttons and of the
|
|
3
|
+
* frame a widget sits in. They are not the widget's words (a widget keeps the language its author gave it) and not an
|
|
4
|
+
* editor's words (those are `@widgetic/ui-sdk`'s and follow the partner's `locale`): they belong to the page the
|
|
5
|
+
* script was put on, so they follow that page's own `lang`.
|
|
6
|
+
*
|
|
7
|
+
* Twelve languages are built in, the same twelve `@widgetic/ui-sdk` ships packs for, picked by the same rules: the
|
|
8
|
+
* language part of the tag decides (`pt-PT` and `pt_BR` read as Brazilian Portuguese, `zh-Hans-CN` as simplified
|
|
9
|
+
* Chinese, `iw` as Hebrew). English, traditional Chinese, a blank tag and a language not listed all stay English.
|
|
10
|
+
* Nothing is fetched. Like the ui-sdk packs, the translations are provisional until a native speaker has read them.
|
|
11
|
+
*/
|
|
12
|
+
export type ChromeLabelKey = "close" | "closeOverlay" | "interactiveWidget";
|
|
13
|
+
/** The languages the words are built in for, in the order the `@widgetic/ui-sdk` packs list them. */
|
|
14
|
+
export declare const CHROME_LABEL_LANGUAGES: readonly string[];
|
|
15
|
+
/**
|
|
16
|
+
* The built-in language that reads `tag`, or `null` when the words stay English. A tag is a page's `lang` and may
|
|
17
|
+
* be spelled with `_`, in any case, with a region (`fr-CA`) or a script (`zh-Hant-TW`).
|
|
18
|
+
*/
|
|
19
|
+
export declare function resolveChromeLanguage(tag: string | null | undefined): string | null;
|
|
20
|
+
/** The language the page says it is written in: its `<body lang>` when it has one, else its `<html lang>`. */
|
|
21
|
+
export declare function pageLanguage(): string;
|
|
22
|
+
/**
|
|
23
|
+
* One of the script's own words in the page's language, or in `language` when it is given.
|
|
24
|
+
* A page that does not say its language gets English.
|
|
25
|
+
*/
|
|
26
|
+
export declare function chromeLabel(key: ChromeLabelKey, language?: string | null | undefined): string;
|
|
@@ -3,8 +3,9 @@
|
|
|
3
3
|
* Customer tag is one word: `<widgetic>`. No `<widgetic-widget>`, no render-mode.
|
|
4
4
|
*
|
|
5
5
|
* Copy iframe = raw `<iframe src>` without SDK.
|
|
6
|
-
* Copy web component = SDK + `<widgetic composition-id
|
|
7
|
-
*
|
|
6
|
+
* Copy web component = SDK + `<widgetic composition-id>`. When the published
|
|
7
|
+
* version has a direct module, the SDK mounts it in a shadow root. A version
|
|
8
|
+
* with only widget.html asks for a republish and does not insert an iframe.
|
|
8
9
|
*/
|
|
9
10
|
import { REFUSED_HOST_ATTRIBUTE } from "./host-bridge-markers.js";
|
|
10
11
|
export { REFUSED_HOST_ATTRIBUTE };
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Mount a published direct module inside `<widgetic>`.
|
|
3
|
+
* The tag has no hyphen, so the shadow root sits on a child.
|
|
4
|
+
*/
|
|
5
|
+
import type { PublicEmbedPayload } from "./public-embed-lookup.js";
|
|
6
|
+
export declare const DIRECT_CONTRACT_VERSION = 2;
|
|
7
|
+
export type DirectWidgetInstance = {
|
|
8
|
+
update: (next: Record<string, unknown>) => void;
|
|
9
|
+
destroy: () => void;
|
|
10
|
+
};
|
|
11
|
+
export type DirectWidgetModule = {
|
|
12
|
+
contractVersion: number;
|
|
13
|
+
getStyles: () => string;
|
|
14
|
+
mount: (target: HTMLElement, props: Record<string, unknown>) => DirectWidgetInstance;
|
|
15
|
+
};
|
|
16
|
+
type DirectModuleLoader = (url: string) => Promise<DirectWidgetModule>;
|
|
17
|
+
/** Tests replace the network import. Pass null to restore it. */
|
|
18
|
+
export declare function setDirectModuleLoader(loader: DirectModuleLoader | null): void;
|
|
19
|
+
export declare function destroyDirectMount(host: HTMLElement): void;
|
|
20
|
+
/**
|
|
21
|
+
* Loads the module and mounts it. Returns false when the module is missing,
|
|
22
|
+
* the contract is not 2, the load fails, or the host changed while loading.
|
|
23
|
+
*/
|
|
24
|
+
export declare function mountDirectWidget(host: HTMLElement, payload: PublicEmbedPayload, width: string | undefined, markMounted: (host: HTMLElement) => void): Promise<boolean>;
|
|
25
|
+
export {};
|
|
@@ -30,9 +30,15 @@ export type PublicEmbedOverlay = {
|
|
|
30
30
|
content?: Record<string, unknown>;
|
|
31
31
|
contentItems?: unknown[];
|
|
32
32
|
};
|
|
33
|
+
export type PublicEmbedDirect = {
|
|
34
|
+
moduleUrl: string;
|
|
35
|
+
contractVersion: number;
|
|
36
|
+
moduleHash?: string | null;
|
|
37
|
+
};
|
|
33
38
|
export type PublicEmbedPayload = PublicEmbedOverlay & {
|
|
34
39
|
embedUrl: string;
|
|
35
40
|
compositionId?: string;
|
|
41
|
+
direct?: PublicEmbedDirect;
|
|
36
42
|
};
|
|
37
43
|
/** The gateway's refusal: the owner limited this embed to listed websites and this page is not listed. */
|
|
38
44
|
export type PublishedEmbedRefusal = {
|