obi-sdk 0.13.2 → 0.13.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.
@@ -1,4 +1,4 @@
1
- import { O as ObiWidget, s as setGlobalContext, t as trackEvent, c as captureException, w as withSentryAsyncHandler, a as withSentryHandler } from "./chunks/obi-widget-d8354869.js";
1
+ import { O as ObiWidget, s as setGlobalContext, t as trackEvent, c as captureException, w as withSentryAsyncHandler, a as withSentryHandler } from "./chunks/obi-widget-222a1e0d.js";
2
2
  import "./chunks/types-f38a47f6.js";
3
3
  class ConfigLogger {
4
4
  constructor() {
@@ -1,6 +1,6 @@
1
1
  import { S as SDKState } from "./chunks/types-f38a47f6.js";
2
- import { i, n, b as i$1, x } from "./chunks/obi-widget-d8354869.js";
3
- import { A, C, e, f, D, N, d, O, S } from "./chunks/obi-widget-d8354869.js";
2
+ import { i, n, b as i$1, x } from "./chunks/obi-widget-222a1e0d.js";
3
+ import { A, C, e, f, D, N, d, O, S } from "./chunks/obi-widget-222a1e0d.js";
4
4
  var __defProp = Object.defineProperty;
5
5
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
6
  var __decorateClass = (decorators, target, key, kind) => {
@@ -85,14 +85,14 @@ if (!customElements.get("obi-status-widget")) {
85
85
  const statusWidget = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, ObiStatusWidget }, Symbol.toStringTag, { value: "Module" }));
86
86
  function defineCustomElements() {
87
87
  Promise.resolve().then(() => statusWidget);
88
- import("./chunks/index-a668ac46.js");
89
- import("./chunks/obi-widget-d8354869.js").then((n2) => n2.l);
90
- import("./chunks/obi-widget-d8354869.js").then((n2) => n2.m);
91
- import("./chunks/obi-widget-d8354869.js").then((n2) => n2.g);
92
- import("./chunks/obi-widget-d8354869.js").then((n2) => n2.h);
93
- import("./chunks/obi-widget-d8354869.js").then((n2) => n2.o);
94
- import("./chunks/obi-widget-d8354869.js").then((n2) => n2.j);
95
- import("./chunks/obi-widget-d8354869.js").then((n2) => n2.k);
88
+ import("./chunks/index-dcd6962d.js");
89
+ import("./chunks/obi-widget-222a1e0d.js").then((n2) => n2.l);
90
+ import("./chunks/obi-widget-222a1e0d.js").then((n2) => n2.m);
91
+ import("./chunks/obi-widget-222a1e0d.js").then((n2) => n2.g);
92
+ import("./chunks/obi-widget-222a1e0d.js").then((n2) => n2.h);
93
+ import("./chunks/obi-widget-222a1e0d.js").then((n2) => n2.o);
94
+ import("./chunks/obi-widget-222a1e0d.js").then((n2) => n2.j);
95
+ import("./chunks/obi-widget-222a1e0d.js").then((n2) => n2.k);
96
96
  }
97
97
  export {
98
98
  A as AudioEqualizer,
@@ -2345,7 +2345,7 @@
2345
2345
  .disabled=${this.disabled}
2346
2346
  ></obi-voice-guidance-content>
2347
2347
  </obi-base-onboarding-modal>
2348
- `}}Xy.styles=[CU],Jy([LC({type:Object})],Xy.prototype,"session",2),Jy([LC({type:Boolean,reflect:!0})],Xy.prototype,"open",2),Jy([LC()],Xy.prototype,"color",2),Jy([LC({type:Boolean,reflect:!0})],Xy.prototype,"disabled",2),Jy([LC({type:Boolean,reflect:!0})],Xy.prototype,"loading",2),Jy([LC({type:Boolean,attribute:"close-disabled"})],Xy.prototype,"closeDisabled",2),customElements.get("obi-voice-guidance-modal")||customElements.define("obi-voice-guidance-modal",Xy);var Yy=Object.defineProperty,Wy=Object.getOwnPropertyDescriptor,Zy=(A,t,e,i)=>{for(var n,s=i>1?void 0:i?Wy(t,e):t,r=A.length-1;r>=0;r--)(n=A[r])&&(s=(i?n(t,e,s):n(s))||s);return i&&s&&Yy(t,e,s),s};class qy extends Ap{constructor(){super(),this.apiKey="",this.isActive=!0,this.linkOnlyAccess=!1,this.urlBlacklist=[],this.position="bottom-right",this.user=null,this.state=Ra.READY,this.storedActiveState=void 0,this.showCourseModal=!1,this.showSessionStartModal=!1,this.showShareMicModal=!1,this.micShareEnabled=!1,this.showVoiceGuidanceModal=!1,this.voiceGuidanceEnabled=!1,this.selectedCourse=null,this.isHovering=!1,this.navVisible=!1,this.activeSession=null,this.volume={speaker:"ASSISTANT",volume:0,spectrum:[]},this.databaseConfig=null,this.configLoaded=!1,this.configAllInCode=!1,this.primaryColor="#9500FF",this.sessionToken=null,this.roomToken=null,this.roomUrl=null,this.boundSaveSessionData=null,this.obiClient=null,this.closeNavTimeoutRef=null,this.researchingTimeoutRef=null,this.urlCheckInterval=null,this.currentUrl="",this.connectObi=mQ((async A=>{if(this.activeSession)return pQ("connection_already_exists",{sessionToken:A},"ObiWidget"),void console.log("Connection already exists");pQ("session_connection_started",{sessionToken:A},"ObiWidget"),vQ({sessionId:A});try{const t=this.createSession(A);if(!t)return void this.handleSessionCreationFailure((()=>this.removeSessionUrlParams()));this.setupSessionEventListeners(t,(()=>this.removeSessionUrlParams())),t.on("screenCaptureRequested",mQ((async()=>{pQ("screen_capture_requested",{},"ObiWidget");try{const A=(await(t=document.documentElement,e={useCORS:!0,allowTaint:!0,foreignObjectRendering:!0},void 0===e&&(e={}),(function(A,t){return qa(void 0,void 0,void 0,(function(){var e,i,n,s,r,o,a,c,h,u,l,d,f,B,g,w,p,v,m,b,Q,C,U,y,F,E,k,I,H,S,T,x,O,K,D,M,L,_;return za(this,(function(N){switch(N.label){case 0:if(!A||"object"!=typeof A)return[2,Promise.reject("Invalid element provided as first argument")];if(!(e=A.ownerDocument))throw new Error("Element is not attached to a Document");if(!(i=e.defaultView))throw new Error("Document is not attached to a Window");return n={allowTaint:null!==(C=t.allowTaint)&&void 0!==C&&C,imageTimeout:null!==(U=t.imageTimeout)&&void 0!==U?U:15e3,proxy:t.proxy,useCORS:null!==(y=t.useCORS)&&void 0!==y&&y,customIsSameOrigin:t.customIsSameOrigin},s=Za({logging:null===(F=t.logging)||void 0===F||F,cache:t.cache},n),r={windowWidth:null!==(E=t.windowWidth)&&void 0!==E?E:i.innerWidth,windowHeight:null!==(k=t.windowHeight)&&void 0!==k?k:i.innerHeight,scrollX:null!==(I=t.scrollX)&&void 0!==I?I:i.pageXOffset,scrollY:null!==(H=t.scrollY)&&void 0!==H?H:i.pageYOffset},o=new tc(r.scrollX,r.scrollY,r.windowWidth,r.windowHeight),a=new Jg(s,o),c=null!==(S=t.foreignObjectRendering)&&void 0!==S&&S,h={allowTaint:null!==(T=t.allowTaint)&&void 0!==T&&T,onclone:t.onclone,ignoreElements:t.ignoreElements,inlineImages:c,copyStyles:c},a.logger.debug("Starting document clone with size ".concat(o.width,"x").concat(o.height," scrolled to ").concat(-o.left,",").concat(-o.top)),u=new xB(a,A,h),(l=u.clonedReferenceElement)?[4,u.toIFrame(e,o)]:[2,Promise.reject("Unable to find element in cloned iframe")];case 1:return d=N.sent(),f=oB(l)||"HTML"===l.tagName?(function(A){var t=A.body,e=A.documentElement;if(!t||!e)throw new Error("Unable to get document size");var i=Math.max(Math.max(t.scrollWidth,e.scrollWidth),Math.max(t.offsetWidth,e.offsetWidth),Math.max(t.clientWidth,e.clientWidth)),n=Math.max(Math.max(t.scrollHeight,e.scrollHeight),Math.max(t.offsetHeight,e.offsetHeight),Math.max(t.clientHeight,e.clientHeight));return new tc(0,0,i,n)})(l.ownerDocument):ec(a,l),B=f.width,g=f.height,w=f.left,p=f.top,v=(function(A,t,e){var i=t.ownerDocument,n=i.documentElement?Yu(A,getComputedStyle(i.documentElement).backgroundColor):Wu.TRANSPARENT,s=i.body?Yu(A,getComputedStyle(i.body).backgroundColor):Wu.TRANSPARENT,r="string"==typeof e?Yu(A,e):null===e?Wu.TRANSPARENT:4294967295;return t===i.documentElement?du(n)?du(s)?r:s:n:r})(a,l,t.backgroundColor),m={canvas:t.canvas,backgroundColor:v,scale:null!==(O=null!==(x=t.scale)&&void 0!==x?x:i.devicePixelRatio)&&void 0!==O?O:1,x:(null!==(K=t.x)&&void 0!==K?K:0)+w,y:(null!==(D=t.y)&&void 0!==D?D:0)+p,width:null!==(M=t.width)&&void 0!==M?M:Math.ceil(B),height:null!==(L=t.height)&&void 0!==L?L:Math.ceil(g)},c?(a.logger.debug("Document cloned, using foreign object rendering"),[4,new Gg(a,m).render(l)]):[3,3];case 2:return b=N.sent(),[3,5];case 3:return a.logger.debug("Document cloned, element located at ".concat(w,",").concat(p," with size ").concat(B,"x").concat(g," using computed rendering")),a.logger.debug("Starting DOM parsing"),Q=Wf(a,l),v===Q.styles.backgroundColor&&(Q.styles.backgroundColor=Wu.TRANSPARENT),a.logger.debug("Starting renderer for element at ".concat(m.x,",").concat(m.y," with size ").concat(m.width,"x").concat(m.height)),[4,new Lg(a,m).render(Q)];case 4:b=N.sent(),N.label=5;case 5:return(null===(_=t.removeContainer)||void 0===_||_)&&(xB.destroy(d)||a.logger.error("Cannot detach cloned iframe as it is not in the DOM anymore")),a.logger.debug("Finished rendering"),[2,b]}}))}))})(t,e))).toDataURL("image/png");this.activeSession.emit("screenCaptureComplete",A),pQ("screen_capture_completed",{},"ObiWidget")}catch(i){wQ(i,{componentName:"ObiWidget",handlerName:"screenCaptureRequested",sessionToken:A}),console.error("[obi] error capturing screen:",i),this.activeSession.emit("screenCaptureComplete","error"),pQ("screen_capture_failed",{error:i instanceof Error?i.message:String(i)},"ObiWidget")}var t,e}),"screenCaptureRequested","ObiWidget"));const e=await t.connect();e&&(this.sessionToken=A,this.roomToken=e.token,this.roomUrl=e.url,vQ({sessionId:A,widgetState:this.state.toString()}),this.removeSessionUrlParams(),pQ("session_connection_established",{sessionToken:A,hasRoomToken:!!e.token},"ObiWidget")),this.activeSession=t}catch(t){console.error("Failed to start session:",t),wQ(t,{componentName:"ObiWidget",handlerName:"connectObi",sessionToken:A}),this.handleSessionCreationFailure((()=>this.removeSessionUrlParams()))}}),"connectObi","ObiWidget"),this.handleCloseModals=()=>{this.activeSession&&(this.activeSession.disconnect(),this.activeSession=null),this.state=Ra.READY,this.terminateSession(),this.showCourseModal=!1,this.showSessionStartModal=!1,this.showShareMicModal=!1},this.handleCourseSelectEvent=A=>{const t=A;this.selectedCourse=t.detail,this.showCourseModal=!1,this.showSessionStartModal=!0,this.showShareMicModal=!1,this.micShareEnabled=!1,this.showVoiceGuidanceModal=!1,this.voiceGuidanceEnabled=!1},this.handleUrlSessionEvent=mQ((async A=>{pQ("url_session_event",{sessionToken:A},"ObiWidget");try{if(!this.obiClient)return wQ(new Error("ObiClient not initialized"),{componentName:"ObiWidget",handlerName:"handleUrlSessionEvent",sessionToken:A}),void console.error("ObiClient not initialized");const t=await this.obiClient.startSession(A,this.apiKey);if(t.data){const{session:e}=t.data;if(console.log("[obi-sdk] session:",e),pQ("session_started",{sessionId:e?.id,sessionToken:A},"ObiWidget"),e){const t=e;this.selectedCourse={id:A,name:t.onboarding_plan?.name||"",description:t.onboarding_plan?.description||""},this.state=Ra.LOADING,this.showSessionStartModal=!0,this.showShareMicModal=!1,this.micShareEnabled=!1,this.showVoiceGuidanceModal=!1,this.voiceGuidanceEnabled=!1,pQ("matching_session_found",{sessionToken:A,hasOnboardingPlan:!!t.onboarding_plan},"ObiWidget")}else console.log("[obi-sdk] no session found with token:",A),pQ("no_matching_session",{sessionToken:A},"ObiWidget")}}catch(t){console.error("Failed to fetch session details:",t),wQ(t,{componentName:"ObiWidget",handlerName:"handleUrlSessionEvent",sessionToken:A})}}),"handleUrlSessionEvent","ObiWidget"),this.handleSessionStart=mQ((async A=>{pQ("session_start_requested",{sessionToken:A},"ObiWidget"),this.activeSession&&(pQ("session_start_blocked",{sessionToken:A},"ObiWidget"),wQ(new Error("Session start blocked"),{componentName:"ObiWidget",handlerName:"handleSessionStart",sessionToken:A}),this.activeSession.disconnect(),this.activeSession=null),this.showSessionStartModal=!1,this.showShareMicModal=!0,this.state=Ra.LOADING,vQ({widgetState:this.state.toString()}),await this.connectObi(A)}),"handleSessionStart","ObiWidget"),this.handleSessionModalStart=A=>{const{sessionId:t,attempt:e}=A.detail;if(console.log("[SessionStartModal] Start button clicked",{sessionId:t,hasSession:!!this.selectedCourse,startAttempts:e,timestamp:(new Date).toISOString()}),pQ("session_start_modal_continue_clicked",{sessionId:t,sessionName:this.selectedCourse?.name},"SessionStartModal"),!this.selectedCourse){const A="Session data is missing.";return console.error("[SessionStartModal] Validation failed:",A),void wQ(A,{componentName:"SessionStartModal",handlerName:"handleSessionModalStart",sessionData:this.selectedCourse})}if(!this.selectedCourse.id){const A="Session ID is missing.";return console.error("[SessionStartModal] Validation failed:",A,{session:this.selectedCourse}),void wQ(A,{componentName:"SessionStartModal",handlerName:"handleSessionModalStart",sessionData:this.selectedCourse})}console.log("[SessionStartModal] Starting session attempt",{attempt:e,sessionId:this.selectedCourse.id}),pQ("session_start_modal_calling_onStart",{sessionId:this.selectedCourse.id},"SessionStartModal"),this.handleSessionStart(this.selectedCourse.id),console.log("[SessionStartModal] Session start completed successfully",{sessionId:this.selectedCourse.id,attempt:e}),pQ("session_start_modal_onStart_called",{sessionId:this.selectedCourse.id},"SessionStartModal")},this.handleSessionModalClose=()=>{console.log("[SessionStartModal] Close button clicked",{sessionId:this.selectedCourse?.id}),this.handleCloseModals(),this.selectedCourse=null,this.removeSessionUrlParams()},this.handleSessionModalError=A=>{const{error:t,sessionId:e}=A.detail;console.error("[SessionStartModal] Error occurred",{error:t instanceof Error?t.message:String(t),sessionId:e}),wQ(t,{componentName:"SessionStartModal",handlerName:"handleSessionModalError",sessionId:e})},this.handleShareMicModalContinue=async A=>{const{session:t,micPermissionGranted:e}=A.detail;console.log("[ShareMicModal] Continue button clicked",{sessionId:t?.id,micPermissionGranted:e,timestamp:(new Date).toISOString()}),pQ("share_mic_modal_continue_clicked",{sessionId:t?.id,micPermissionGranted:e},"ShareMicModal"),this.activeSession?(await this.activeSession.shareMic(),this.showShareMicModal=!1,this.showVoiceGuidanceModal=!0):console.error("[obi] no active session during microphone sharing")},this.handleShareMicModalClose=()=>{console.log("[ShareMicModal] Close button clicked",{sessionId:this.selectedCourse?.id}),this.handleCloseModals()},this.handleVoiceGuidanceModalContinue=async()=>{console.log("[obi] voice guidance modal continue",{sessionId:this.selectedCourse?.id,timestamp:(new Date).toISOString()}),pQ("voice_guidance_modal_continue_clicked",{sessionId:this.selectedCourse?.id},"ShareMicModal"),await(this.activeSession?.promptContinue()),this.showVoiceGuidanceModal=!1},this.handleVoiceGuidanceModalClose=()=>{console.log("[obi] voice guidance modal close",{sessionId:this.selectedCourse?.id}),this.handleCloseModals()},this.checkExistingSession=mQ((async()=>{pQ("checking_existing_session",{},"ObiWidget");try{const A=JSON.parse(UQ.getItem(CQ)||"{}"),{sessionToken:t,roomToken:e,roomUrl:i,sessionExpiry:n,obiState:s}=A;if(!t||!e||!i)return void pQ("no_existing_session_data",{},"ObiWidget");if(console.log("[obi-sdk] using existing session"),pQ("existing_session_data_found",{sessionToken:t,hasExpiry:!!n,obiState:s},"ObiWidget"),n&&new Date(n)<new Date)return this.clearSessionStorage(),void pQ("session_expired",{sessionToken:t},"ObiWidget");this.state=Ra.LOADING,vQ({sessionId:t,widgetState:this.state.toString()});const r=this.createSession(t);if(!r)return void this.handleSessionCreationFailure((()=>this.clearSessionStorage()));this.setupSessionEventListeners(r,(()=>this.clearSessionStorage())),await r.reconnect(i,e,s)?(this.activeSession=r,this.sessionToken=t,this.roomToken=e,this.roomUrl=i,this.state=s,this.storedActiveState=s,pQ("session_reconnected",{sessionToken:t,obiState:s},"ObiWidget")):(this.clearSessionStorage(),pQ("session_reconnection_failed",{sessionToken:t},"ObiWidget"))}catch(A){console.error("Error reconnecting to session:",A),wQ(A,{componentName:"ObiWidget",handlerName:"checkExistingSession"}),this.handleSessionCreationFailure((()=>this.clearSessionStorage()))}}),"checkExistingSession","ObiWidget");try{QQ("ObiWidget").setContext(),this.obiClient=new h({baseUrl:t}),this.currentUrl=window.location.href;const A=()=>{try{this.activeSession&&this.sessionToken&&this.roomToken&&this.roomUrl&&this.saveSessionData()}catch(A){wQ(A,{componentName:"ObiWidget",handlerName:"handleUnload"})}};window.addEventListener("beforeunload",A),window.addEventListener("pagehide",A),pQ("ObiWidget_constructor_completed",{},"ObiWidget")}catch(A){throw wQ(A,{componentName:"ObiWidget",lifecycle:"constructor"}),A}}updateFromConfig(){if(window.obiWidgetConfig){this.apiKey=window.obiWidgetConfig.apiKey||this.apiKey,void 0!==window.obiWidgetConfig.position&&(this.position=window.obiWidgetConfig.position,this.setAttribute("position",this.position)),void 0!==window.obiWidgetConfig.primaryColor&&(this.style.setProperty("--obi-primary",window.obiWidgetConfig.primaryColor),this.generateColorVariables(window.obiWidgetConfig.primaryColor)),void 0!==window.obiWidgetConfig.user&&(this.user=window.obiWidgetConfig.user),void 0!==window.obiWidgetConfig.isActive&&(this.isActive=window.obiWidgetConfig.isActive),void 0!==window.obiWidgetConfig.linkOnlyAccess&&(this.linkOnlyAccess=window.obiWidgetConfig.linkOnlyAccess),void 0!==window.obiWidgetConfig.urlBlacklist&&(this.urlBlacklist=window.obiWidgetConfig.urlBlacklist);const A=void 0!==window.obiWidgetConfig.position,t=void 0!==window.obiWidgetConfig.primaryColor,e=void 0!==window.obiWidgetConfig.linkOnlyAccess,i=void 0!==window.obiWidgetConfig.urlBlacklist;this.configAllInCode=A&&t&&e&&i,this.configAllInCode?(this.configLoaded=!0,this.applyFinalConfiguration()):this.configLoaded||this.fetchDatabaseConfig(),!0===window.obiWidgetConfig.showMenu&&(this.state=Ra.LOADING,this.showCourseModal=!0,window.obiWidgetConfig.showMenu=!1)}else this.configLoaded||this.fetchDatabaseConfig()}generateColorVariables(A){try{this.primaryColor=A;const t=Ja(A,"#c4b5fd"),e=Ja(A,"#c76cff"),i=(function(A){try{const t={h:Va(A).h,s:100,l:96};return $a(t.h,t.s,t.l)}catch(t){return console.warn("Failed to transform to light tint, using fallback:",t),A}})(A),n=Ja(A,"#A06DF9");this.style.setProperty("--obi-secondary",t),this.style.setProperty("--obi-course-selected",e),this.style.setProperty("--obi-course-selected-bg",i),this.style.setProperty("--obi-paused-pulse",n)}catch(t){console.warn("Failed to generate color variables:",t),this.style.setProperty("--obi-secondary","#c4b5fd"),this.style.setProperty("--obi-course-selected","#c76cff"),this.style.setProperty("--obi-course-selected-bg","#fbf3ff"),this.style.setProperty("--obi-paused-pulse","#A06DF9")}}removeSessionUrlParams(){const A=new URL(window.location.href);A.searchParams.delete(Xa),window.history.replaceState({},"",A.toString()),localStorage.removeItem("obi-url-params")}createSession(A){try{return new Pa({sessionId:A,apiBaseUrl:t,...this.user&&{user:this.user}})||(console.error("Failed to create session"),null)}catch(e){return console.error("Error creating session:",e),null}}setupSessionEventListeners(A,t){A.on("stateChanged",(t=>{if(t===Ra.RESEARCHING)return this.researchingTimeoutRef&&window.clearTimeout(this.researchingTimeoutRef),this.state=t,this.researchingTimeoutRef=window.setTimeout((()=>{this.researchingTimeoutRef=null;const t=A.getCurrentState();this.state=t,t!==Ra.READY&&(this.storedActiveState=t)}),1500),void(this.storedActiveState=t);null===this.researchingTimeoutRef&&(this.state=t,t!==Ra.READY&&(this.storedActiveState=t))})),A.on("volume",(({speaker:A,spectrum:t,volume:e})=>{this.volume={speaker:A,spectrum:t,volume:e}})),A.on("error",(A=>{console.error("Session error:",A),this.state=Ra.ERROR,this.activeSession=null,t&&t()})),A.on("micShareRequested",(()=>{this.micShareEnabled=!0})),A.on("promptUser",(()=>{this.voiceGuidanceEnabled=!0}))}handleSessionCreationFailure(A){this.state=Ra.ERROR,this.activeSession=null,A&&A()}clearSessionStorage(){UQ.removeItem(CQ)}handleUrlChange(){this.requestUpdate(),yQ(this.urlBlacklist)&&this.activeSession&&this.terminateSession()}saveSessionData(){if(this.activeSession&&this.sessionToken&&this.roomToken&&this.roomUrl){const A=new Date;A.setMinutes(A.getMinutes()+5);const t={sessionToken:this.sessionToken,roomToken:this.roomToken,roomUrl:this.roomUrl,obiState:this.storedActiveState??this.state,sessionExpiry:A.toISOString()};UQ.setItem(CQ,JSON.stringify(t))}}async sessionConnectionCheck(){const A=(function(){let A={};return A=JSON.parse(localStorage.getItem("obi-url-params")||"{}"),0===Object.keys(A).length&&new URLSearchParams(window.location.search).forEach(((t,e)=>{A[e]=t})),A[Xa]})();A?(console.log("[obi-sdk] using magic link"),this.apiKey?await this.handleUrlSessionEvent(A):(console.log("[obi-sdk] API key not ready, retrying..."),setTimeout((()=>{this.apiKey&&this.handleUrlSessionEvent(A)}),100))):await this.checkExistingSession()}connectedCallback(){super.connectedCallback(),this.updateFromConfig(),this.addEventListener("obi-config-updated",this.handleConfigUpdate.bind(this)),this.setAttribute("position",this.position),this.boundSaveSessionData=this.saveSessionData.bind(this),window.addEventListener("beforeunload",this.boundSaveSessionData),window.addEventListener("pagehide",this.boundSaveSessionData),this.isActive&&(this.urlCheckInterval=window.setInterval((()=>{this.currentUrl!==window.location.href&&(this.currentUrl=window.location.href,this.handleUrlChange())}),1e3)),this.addEventListener("course-select",this.handleCourseSelectEvent)}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("obi-config-updated",this.handleConfigUpdate.bind(this)),null!==this.closeNavTimeoutRef&&window.clearTimeout(this.closeNavTimeoutRef),null!==this.researchingTimeoutRef&&(window.clearTimeout(this.researchingTimeoutRef),this.researchingTimeoutRef=null),this.boundSaveSessionData&&(window.removeEventListener("beforeunload",this.boundSaveSessionData),window.removeEventListener("pagehide",this.boundSaveSessionData)),null!==this.urlCheckInterval&&(clearInterval(this.urlCheckInterval),this.urlCheckInterval=null),this.removeSessionUrlParams()}async handleConfigUpdate(A){const t=A.detail,e=t.isActive&&!this.isActive,i=this.user;if(this.updateFromConfig(),this.activeSession&&void 0!==t.user){const A=t.user;if(JSON.stringify(i)!==JSON.stringify(A))try{await this.activeSession.updateUser(A)}catch(n){console.error("Failed to update session user data:",n)}}!e||yQ(this.urlBlacklist)||this.activeSession||this.sessionConnectionCheck(),this.requestUpdate()}handleMouseEnter(){this.isHovering=!0,this.navVisible=!0}handleMouseLeave(){this.isHovering=!1,null!==this.closeNavTimeoutRef&&window.clearTimeout(this.closeNavTimeoutRef),this.closeNavTimeoutRef=window.setTimeout((()=>{this.isHovering||(this.navVisible=!1),this.closeNavTimeoutRef=null}),300)}terminateSession(){this.clearSessionStorage(),this.sessionToken=null,this.roomToken=null,this.roomUrl=null,null!==this.researchingTimeoutRef&&(window.clearTimeout(this.researchingTimeoutRef),this.researchingTimeoutRef=null),this.activeSession&&(this.activeSession.disconnect(),this.activeSession=null),this.state=Ra.READY}handleItemSelect(A,t){"experiences"!==A?La([A,t]).with(["pause",!0],(()=>{this.activeSession?.pauseRecording()})).with(["pause",!1],(()=>{this.activeSession?.resumeRecording()})).with(["activate",!1],(()=>{this.terminateSession()})).otherwise((()=>{})):this.showCourseModal=!0}async fetchDatabaseConfig(){if(!this.apiKey)return this.configLoaded=!0,void this.applyFinalConfiguration();try{const A=`obi-widget-config-${this.apiKey}`,t=localStorage.getItem(A),e=localStorage.getItem(`${A}-timestamp`);if(t&&e&&Date.now()-parseInt(e,10)<6e5){const A=JSON.parse(t);return this.databaseConfig=A,this.configLoaded=!0,void this.applyFinalConfiguration()}const i=new AbortController,n=setTimeout((()=>i.abort()),3e3),s=await this.obiClient.getOnboardeeWidgetConfig(this.apiKey,i.signal);if(clearTimeout(n),s.error){if(404===s.response?.status)return localStorage.removeItem(A),localStorage.removeItem(`${A}-timestamp`),this.databaseConfig=null,this.configLoaded=!0,void this.applyFinalConfiguration();throw new Error(`HTTP ${s.response?.status||"Unknown error"}`)}const r=s.data;localStorage.setItem(A,JSON.stringify(r)),localStorage.setItem(`${A}-timestamp`,Date.now().toString()),this.databaseConfig=r,this.configLoaded=!0,this.applyFinalConfiguration()}catch(A){A instanceof Error&&"AbortError"===A.name?console.warn("Widget config fetch timed out, using defaults"):console.warn("Failed to fetch widget config from database:",A),this.databaseConfig=null,this.configLoaded=!0,this.applyFinalConfiguration()}}applyFinalConfiguration(){const A=window.obiWidgetConfig,t=this.databaseConfig;this.user=A?.user||this.user,this.position=A?.position||t?.position||this.position,this.setAttribute("position",this.position),void 0!==A?.isActive&&(this.isActive=A.isActive),void 0!==A?.linkOnlyAccess?this.linkOnlyAccess=A.linkOnlyAccess:void 0!==t?.linkOnlyAccess&&(this.linkOnlyAccess=t.linkOnlyAccess);const e=A?.urlBlacklist||[],i=t?.urlBlacklist||[];if(e.length>0||i.length>0){const A=[...e,...i];this.urlBlacklist=[...new Set(A)]}const n=A?.primaryColor||t?.primaryColor||Ga;this.primaryColor=n,this.style.setProperty("--obi-primary",n),this.generateColorVariables(n),!this.isActive||yQ(this.urlBlacklist)||this.activeSession||this.sessionConnectionCheck()}render(){if(!this.configLoaded)return _w;if(!this.isActive)return _w;if(this.linkOnlyAccess&&this.state===Ra.READY)return _w;if(yQ(this.urlBlacklist))return _w;const A=La(this.state).with(Ra.LOADING,(()=>Dw`<obi-dot-loader></obi-dot-loader>`)).with(Ra.RESEARCHING,(()=>Dw`<obi-searching-loader></obi-searching-loader>`)).with(Ka.union(Ra.USER_SPEAKING,Ra.AGENT_SPEAKING),(()=>Dw`<obi-audio-equalizer .volume=${this.volume}></obi-audio-equalizer>`)).with(Ra.THINKING,(()=>Dw`<obi-dot-loader></obi-dot-loader>`)).with(Ra.PAUSED,(()=>DQ)).otherwise((()=>DQ)),t=this.state===Ra.USER_SPEAKING||this.state===Ra.AGENT_SPEAKING,e=this.state===Ra.PAUSED,i=this.state===Ra.RESEARCHING,n=this.state===Ra.USER_SPEAKING,s=this.state!==Ra.READY||this.navVisible,r=this.state!==Ra.READY||this.navVisible,o=this.position.includes("top")?"down":"up",a=["widget-container",s?"rotated":"",t?"pulse":"",e?"paused-pulse":"",i?"researching":"",n?"user-speaking":""].filter(Boolean).join(" ");return Dw`
2348
+ `}}Xy.styles=[CU],Jy([LC({type:Object})],Xy.prototype,"session",2),Jy([LC({type:Boolean,reflect:!0})],Xy.prototype,"open",2),Jy([LC()],Xy.prototype,"color",2),Jy([LC({type:Boolean,reflect:!0})],Xy.prototype,"disabled",2),Jy([LC({type:Boolean,reflect:!0})],Xy.prototype,"loading",2),Jy([LC({type:Boolean,attribute:"close-disabled"})],Xy.prototype,"closeDisabled",2),customElements.get("obi-voice-guidance-modal")||customElements.define("obi-voice-guidance-modal",Xy);var Yy=Object.defineProperty,Wy=Object.getOwnPropertyDescriptor,Zy=(A,t,e,i)=>{for(var n,s=i>1?void 0:i?Wy(t,e):t,r=A.length-1;r>=0;r--)(n=A[r])&&(s=(i?n(t,e,s):n(s))||s);return i&&s&&Yy(t,e,s),s};class qy extends Ap{constructor(){super(),this.apiKey="",this.isActive=!0,this.linkOnlyAccess=!1,this.urlBlacklist=[],this.position="bottom-right",this.user=null,this.state=Ra.READY,this.storedActiveState=void 0,this.showCourseModal=!1,this.showSessionStartModal=!1,this.showShareMicModal=!1,this.micShareEnabled=!1,this.showVoiceGuidanceModal=!1,this.voiceGuidanceEnabled=!1,this.selectedCourse=null,this.isHovering=!1,this.navVisible=!1,this.activeSession=null,this.volume={speaker:"ASSISTANT",volume:0,spectrum:[]},this.databaseConfig=null,this.configLoaded=!1,this.primaryColor="#9500FF",this.sessionToken=null,this.roomToken=null,this.roomUrl=null,this.boundSaveSessionData=null,this.obiClient=null,this.closeNavTimeoutRef=null,this.researchingTimeoutRef=null,this.urlCheckInterval=null,this.currentUrl="",this.connectObi=mQ((async A=>{if(this.activeSession)return pQ("connection_already_exists",{sessionToken:A},"ObiWidget"),void console.log("Connection already exists");pQ("session_connection_started",{sessionToken:A},"ObiWidget"),vQ({sessionId:A});try{const t=this.createSession(A);if(!t)return void this.handleSessionCreationFailure((()=>this.removeSessionUrlParams()));this.setupSessionEventListeners(t,(()=>this.removeSessionUrlParams())),t.on("screenCaptureRequested",mQ((async()=>{pQ("screen_capture_requested",{},"ObiWidget");try{const A=(await(t=document.documentElement,e={useCORS:!0,allowTaint:!0,foreignObjectRendering:!0},void 0===e&&(e={}),(function(A,t){return qa(void 0,void 0,void 0,(function(){var e,i,n,s,r,o,a,c,h,u,l,d,f,B,g,w,p,v,m,b,Q,C,U,y,F,E,k,I,H,S,T,x,O,K,D,M,L,_;return za(this,(function(N){switch(N.label){case 0:if(!A||"object"!=typeof A)return[2,Promise.reject("Invalid element provided as first argument")];if(!(e=A.ownerDocument))throw new Error("Element is not attached to a Document");if(!(i=e.defaultView))throw new Error("Document is not attached to a Window");return n={allowTaint:null!==(C=t.allowTaint)&&void 0!==C&&C,imageTimeout:null!==(U=t.imageTimeout)&&void 0!==U?U:15e3,proxy:t.proxy,useCORS:null!==(y=t.useCORS)&&void 0!==y&&y,customIsSameOrigin:t.customIsSameOrigin},s=Za({logging:null===(F=t.logging)||void 0===F||F,cache:t.cache},n),r={windowWidth:null!==(E=t.windowWidth)&&void 0!==E?E:i.innerWidth,windowHeight:null!==(k=t.windowHeight)&&void 0!==k?k:i.innerHeight,scrollX:null!==(I=t.scrollX)&&void 0!==I?I:i.pageXOffset,scrollY:null!==(H=t.scrollY)&&void 0!==H?H:i.pageYOffset},o=new tc(r.scrollX,r.scrollY,r.windowWidth,r.windowHeight),a=new Jg(s,o),c=null!==(S=t.foreignObjectRendering)&&void 0!==S&&S,h={allowTaint:null!==(T=t.allowTaint)&&void 0!==T&&T,onclone:t.onclone,ignoreElements:t.ignoreElements,inlineImages:c,copyStyles:c},a.logger.debug("Starting document clone with size ".concat(o.width,"x").concat(o.height," scrolled to ").concat(-o.left,",").concat(-o.top)),u=new xB(a,A,h),(l=u.clonedReferenceElement)?[4,u.toIFrame(e,o)]:[2,Promise.reject("Unable to find element in cloned iframe")];case 1:return d=N.sent(),f=oB(l)||"HTML"===l.tagName?(function(A){var t=A.body,e=A.documentElement;if(!t||!e)throw new Error("Unable to get document size");var i=Math.max(Math.max(t.scrollWidth,e.scrollWidth),Math.max(t.offsetWidth,e.offsetWidth),Math.max(t.clientWidth,e.clientWidth)),n=Math.max(Math.max(t.scrollHeight,e.scrollHeight),Math.max(t.offsetHeight,e.offsetHeight),Math.max(t.clientHeight,e.clientHeight));return new tc(0,0,i,n)})(l.ownerDocument):ec(a,l),B=f.width,g=f.height,w=f.left,p=f.top,v=(function(A,t,e){var i=t.ownerDocument,n=i.documentElement?Yu(A,getComputedStyle(i.documentElement).backgroundColor):Wu.TRANSPARENT,s=i.body?Yu(A,getComputedStyle(i.body).backgroundColor):Wu.TRANSPARENT,r="string"==typeof e?Yu(A,e):null===e?Wu.TRANSPARENT:4294967295;return t===i.documentElement?du(n)?du(s)?r:s:n:r})(a,l,t.backgroundColor),m={canvas:t.canvas,backgroundColor:v,scale:null!==(O=null!==(x=t.scale)&&void 0!==x?x:i.devicePixelRatio)&&void 0!==O?O:1,x:(null!==(K=t.x)&&void 0!==K?K:0)+w,y:(null!==(D=t.y)&&void 0!==D?D:0)+p,width:null!==(M=t.width)&&void 0!==M?M:Math.ceil(B),height:null!==(L=t.height)&&void 0!==L?L:Math.ceil(g)},c?(a.logger.debug("Document cloned, using foreign object rendering"),[4,new Gg(a,m).render(l)]):[3,3];case 2:return b=N.sent(),[3,5];case 3:return a.logger.debug("Document cloned, element located at ".concat(w,",").concat(p," with size ").concat(B,"x").concat(g," using computed rendering")),a.logger.debug("Starting DOM parsing"),Q=Wf(a,l),v===Q.styles.backgroundColor&&(Q.styles.backgroundColor=Wu.TRANSPARENT),a.logger.debug("Starting renderer for element at ".concat(m.x,",").concat(m.y," with size ").concat(m.width,"x").concat(m.height)),[4,new Lg(a,m).render(Q)];case 4:b=N.sent(),N.label=5;case 5:return(null===(_=t.removeContainer)||void 0===_||_)&&(xB.destroy(d)||a.logger.error("Cannot detach cloned iframe as it is not in the DOM anymore")),a.logger.debug("Finished rendering"),[2,b]}}))}))})(t,e))).toDataURL("image/png");this.activeSession.emit("screenCaptureComplete",A),pQ("screen_capture_completed",{},"ObiWidget")}catch(i){wQ(i,{componentName:"ObiWidget",handlerName:"screenCaptureRequested",sessionToken:A}),console.error("[obi] error capturing screen:",i),this.activeSession.emit("screenCaptureComplete","error"),pQ("screen_capture_failed",{error:i instanceof Error?i.message:String(i)},"ObiWidget")}var t,e}),"screenCaptureRequested","ObiWidget"));const e=await t.connect();e&&(this.sessionToken=A,this.roomToken=e.token,this.roomUrl=e.url,vQ({sessionId:A,widgetState:this.state.toString()}),this.removeSessionUrlParams(),pQ("session_connection_established",{sessionToken:A,hasRoomToken:!!e.token},"ObiWidget")),this.activeSession=t}catch(t){console.error("Failed to start session:",t),wQ(t,{componentName:"ObiWidget",handlerName:"connectObi",sessionToken:A}),this.handleSessionCreationFailure((()=>this.removeSessionUrlParams()))}}),"connectObi","ObiWidget"),this.handleCloseModals=()=>{this.activeSession&&(this.activeSession.disconnect(),this.activeSession=null),this.state=Ra.READY,this.terminateSession(),this.showCourseModal=!1,this.showSessionStartModal=!1,this.showShareMicModal=!1},this.handleCourseSelectEvent=A=>{const t=A;this.selectedCourse=t.detail,this.showCourseModal=!1,this.showSessionStartModal=!0,this.showShareMicModal=!1,this.micShareEnabled=!1,this.showVoiceGuidanceModal=!1,this.voiceGuidanceEnabled=!1},this.handleUrlSessionEvent=mQ((async A=>{pQ("url_session_event",{sessionToken:A},"ObiWidget");try{if(!this.obiClient)return wQ(new Error("ObiClient not initialized"),{componentName:"ObiWidget",handlerName:"handleUrlSessionEvent",sessionToken:A}),void console.error("ObiClient not initialized");const t=await this.obiClient.startSession(A,this.apiKey);if(t.data){const{session:e}=t.data;if(console.log("[obi-sdk] session:",e),pQ("session_started",{sessionId:e?.id,sessionToken:A},"ObiWidget"),e){const t=e;this.selectedCourse={id:A,name:t.onboarding_plan?.name||"",description:t.onboarding_plan?.description||""},this.state=Ra.LOADING,this.showSessionStartModal=!0,this.showShareMicModal=!1,this.micShareEnabled=!1,this.showVoiceGuidanceModal=!1,this.voiceGuidanceEnabled=!1,pQ("matching_session_found",{sessionToken:A,hasOnboardingPlan:!!t.onboarding_plan},"ObiWidget")}else console.log("[obi-sdk] no session found with token:",A),pQ("no_matching_session",{sessionToken:A},"ObiWidget")}}catch(t){console.error("Failed to fetch session details:",t),wQ(t,{componentName:"ObiWidget",handlerName:"handleUrlSessionEvent",sessionToken:A})}}),"handleUrlSessionEvent","ObiWidget"),this.handleSessionStart=mQ((async A=>{pQ("session_start_requested",{sessionToken:A},"ObiWidget"),this.activeSession&&(pQ("session_start_blocked",{sessionToken:A},"ObiWidget"),wQ(new Error("Session start blocked"),{componentName:"ObiWidget",handlerName:"handleSessionStart",sessionToken:A}),this.activeSession.disconnect(),this.activeSession=null),this.showSessionStartModal=!1,this.showShareMicModal=!0,this.state=Ra.LOADING,vQ({widgetState:this.state.toString()}),await this.connectObi(A)}),"handleSessionStart","ObiWidget"),this.handleSessionModalStart=A=>{const{sessionId:t,attempt:e}=A.detail;if(console.log("[SessionStartModal] Start button clicked",{sessionId:t,hasSession:!!this.selectedCourse,startAttempts:e,timestamp:(new Date).toISOString()}),pQ("session_start_modal_continue_clicked",{sessionId:t,sessionName:this.selectedCourse?.name},"SessionStartModal"),!this.selectedCourse){const A="Session data is missing.";return console.error("[SessionStartModal] Validation failed:",A),void wQ(A,{componentName:"SessionStartModal",handlerName:"handleSessionModalStart",sessionData:this.selectedCourse})}if(!this.selectedCourse.id){const A="Session ID is missing.";return console.error("[SessionStartModal] Validation failed:",A,{session:this.selectedCourse}),void wQ(A,{componentName:"SessionStartModal",handlerName:"handleSessionModalStart",sessionData:this.selectedCourse})}console.log("[SessionStartModal] Starting session attempt",{attempt:e,sessionId:this.selectedCourse.id}),pQ("session_start_modal_calling_onStart",{sessionId:this.selectedCourse.id},"SessionStartModal"),this.handleSessionStart(this.selectedCourse.id),console.log("[SessionStartModal] Session start completed successfully",{sessionId:this.selectedCourse.id,attempt:e}),pQ("session_start_modal_onStart_called",{sessionId:this.selectedCourse.id},"SessionStartModal")},this.handleSessionModalClose=()=>{console.log("[SessionStartModal] Close button clicked",{sessionId:this.selectedCourse?.id}),this.handleCloseModals(),this.selectedCourse=null,this.removeSessionUrlParams()},this.handleSessionModalError=A=>{const{error:t,sessionId:e}=A.detail;console.error("[SessionStartModal] Error occurred",{error:t instanceof Error?t.message:String(t),sessionId:e}),wQ(t,{componentName:"SessionStartModal",handlerName:"handleSessionModalError",sessionId:e})},this.handleShareMicModalContinue=async A=>{const{session:t,micPermissionGranted:e}=A.detail;console.log("[ShareMicModal] Continue button clicked",{sessionId:t?.id,micPermissionGranted:e,timestamp:(new Date).toISOString()}),pQ("share_mic_modal_continue_clicked",{sessionId:t?.id,micPermissionGranted:e},"ShareMicModal"),this.activeSession?(await this.activeSession.shareMic(),this.showShareMicModal=!1,this.showVoiceGuidanceModal=!0):console.error("[obi] no active session during microphone sharing")},this.handleShareMicModalClose=()=>{console.log("[ShareMicModal] Close button clicked",{sessionId:this.selectedCourse?.id}),this.handleCloseModals()},this.handleVoiceGuidanceModalContinue=async()=>{console.log("[obi] voice guidance modal continue",{sessionId:this.selectedCourse?.id,timestamp:(new Date).toISOString()}),pQ("voice_guidance_modal_continue_clicked",{sessionId:this.selectedCourse?.id},"ShareMicModal"),await(this.activeSession?.promptContinue()),this.showVoiceGuidanceModal=!1},this.handleVoiceGuidanceModalClose=()=>{console.log("[obi] voice guidance modal close",{sessionId:this.selectedCourse?.id}),this.handleCloseModals()},this.checkExistingSession=mQ((async()=>{pQ("checking_existing_session",{},"ObiWidget");try{const A=JSON.parse(UQ.getItem(CQ)||"{}"),{sessionToken:t,roomToken:e,roomUrl:i,sessionExpiry:n,obiState:s}=A;if(!t||!e||!i)return void pQ("no_existing_session_data",{},"ObiWidget");if(console.log("[obi-sdk] using existing session"),pQ("existing_session_data_found",{sessionToken:t,hasExpiry:!!n,obiState:s},"ObiWidget"),n&&new Date(n)<new Date)return this.clearSessionStorage(),void pQ("session_expired",{sessionToken:t},"ObiWidget");this.state=Ra.LOADING,vQ({sessionId:t,widgetState:this.state.toString()});const r=this.createSession(t);if(!r)return void this.handleSessionCreationFailure((()=>this.clearSessionStorage()));this.setupSessionEventListeners(r,(()=>this.clearSessionStorage())),await r.reconnect(i,e,s)?(this.activeSession=r,this.sessionToken=t,this.roomToken=e,this.roomUrl=i,this.state=s,this.storedActiveState=s,pQ("session_reconnected",{sessionToken:t,obiState:s},"ObiWidget")):(this.clearSessionStorage(),pQ("session_reconnection_failed",{sessionToken:t},"ObiWidget"))}catch(A){console.error("Error reconnecting to session:",A),wQ(A,{componentName:"ObiWidget",handlerName:"checkExistingSession"}),this.handleSessionCreationFailure((()=>this.clearSessionStorage()))}}),"checkExistingSession","ObiWidget");try{QQ("ObiWidget").setContext(),this.obiClient=new h({baseUrl:t}),this.currentUrl=window.location.href;const A=()=>{try{this.activeSession&&this.sessionToken&&this.roomToken&&this.roomUrl&&this.saveSessionData()}catch(A){wQ(A,{componentName:"ObiWidget",handlerName:"handleUnload"})}};window.addEventListener("beforeunload",A),window.addEventListener("pagehide",A),pQ("ObiWidget_constructor_completed",{},"ObiWidget")}catch(A){throw wQ(A,{componentName:"ObiWidget",lifecycle:"constructor"}),A}}updateFromConfig(){window.obiWidgetConfig?(this.apiKey=window.obiWidgetConfig.apiKey||this.apiKey,void 0!==window.obiWidgetConfig.position&&(this.position=window.obiWidgetConfig.position,this.setAttribute("position",this.position)),void 0!==window.obiWidgetConfig.primaryColor&&(this.style.setProperty("--obi-primary",window.obiWidgetConfig.primaryColor),this.generateColorVariables(window.obiWidgetConfig.primaryColor)),void 0!==window.obiWidgetConfig.user&&(this.user=window.obiWidgetConfig.user),void 0!==window.obiWidgetConfig.isActive&&(this.isActive=window.obiWidgetConfig.isActive),void 0!==window.obiWidgetConfig.linkOnlyAccess&&(this.linkOnlyAccess=window.obiWidgetConfig.linkOnlyAccess),void 0!==window.obiWidgetConfig.urlBlacklist&&(this.urlBlacklist=window.obiWidgetConfig.urlBlacklist),this.fetchDatabaseConfig(),!0===window.obiWidgetConfig.showMenu&&(this.state=Ra.LOADING,this.showCourseModal=!0,window.obiWidgetConfig.showMenu=!1)):this.configLoaded||this.fetchDatabaseConfig()}generateColorVariables(A){try{this.primaryColor=A;const t=Ja(A,"#c4b5fd"),e=Ja(A,"#c76cff"),i=(function(A){try{const t={h:Va(A).h,s:100,l:96};return $a(t.h,t.s,t.l)}catch(t){return console.warn("Failed to transform to light tint, using fallback:",t),A}})(A),n=Ja(A,"#A06DF9");this.style.setProperty("--obi-secondary",t),this.style.setProperty("--obi-course-selected",e),this.style.setProperty("--obi-course-selected-bg",i),this.style.setProperty("--obi-paused-pulse",n)}catch(t){console.warn("Failed to generate color variables:",t),this.style.setProperty("--obi-secondary","#c4b5fd"),this.style.setProperty("--obi-course-selected","#c76cff"),this.style.setProperty("--obi-course-selected-bg","#fbf3ff"),this.style.setProperty("--obi-paused-pulse","#A06DF9")}}removeSessionUrlParams(){const A=new URL(window.location.href);A.searchParams.delete(Xa),window.history.replaceState({},"",A.toString()),localStorage.removeItem("obi-url-params")}createSession(A){try{return new Pa({sessionId:A,apiBaseUrl:t,...this.user&&{user:this.user}})||(console.error("Failed to create session"),null)}catch(e){return console.error("Error creating session:",e),null}}setupSessionEventListeners(A,t){A.on("stateChanged",(t=>{if(t===Ra.RESEARCHING)return this.researchingTimeoutRef&&window.clearTimeout(this.researchingTimeoutRef),this.state=t,this.researchingTimeoutRef=window.setTimeout((()=>{this.researchingTimeoutRef=null;const t=A.getCurrentState();this.state=t,t!==Ra.READY&&(this.storedActiveState=t)}),1500),void(this.storedActiveState=t);null===this.researchingTimeoutRef&&(this.state=t,t!==Ra.READY&&(this.storedActiveState=t))})),A.on("volume",(({speaker:A,spectrum:t,volume:e})=>{this.volume={speaker:A,spectrum:t,volume:e}})),A.on("error",(A=>{console.error("Session error:",A),this.state=Ra.ERROR,this.activeSession=null,t&&t()})),A.on("micShareRequested",(()=>{this.micShareEnabled=!0})),A.on("promptUser",(()=>{this.voiceGuidanceEnabled=!0}))}handleSessionCreationFailure(A){this.state=Ra.ERROR,this.activeSession=null,A&&A()}clearSessionStorage(){UQ.removeItem(CQ)}handleUrlChange(){this.requestUpdate(),yQ(this.urlBlacklist)&&this.activeSession&&this.terminateSession()}saveSessionData(){if(this.activeSession&&this.sessionToken&&this.roomToken&&this.roomUrl){const A=new Date;A.setMinutes(A.getMinutes()+5);const t={sessionToken:this.sessionToken,roomToken:this.roomToken,roomUrl:this.roomUrl,obiState:this.storedActiveState??this.state,sessionExpiry:A.toISOString()};UQ.setItem(CQ,JSON.stringify(t))}}async sessionConnectionCheck(){const A=(function(){let A={};return A=JSON.parse(localStorage.getItem("obi-url-params")||"{}"),0===Object.keys(A).length&&new URLSearchParams(window.location.search).forEach(((t,e)=>{A[e]=t})),A[Xa]})();A?(console.log("[obi-sdk] using magic link"),this.apiKey?await this.handleUrlSessionEvent(A):(console.log("[obi-sdk] API key not ready, retrying..."),setTimeout((()=>{this.apiKey&&this.handleUrlSessionEvent(A)}),100))):await this.checkExistingSession()}connectedCallback(){super.connectedCallback(),this.updateFromConfig(),this.addEventListener("obi-config-updated",this.handleConfigUpdate.bind(this)),this.setAttribute("position",this.position),this.boundSaveSessionData=this.saveSessionData.bind(this),window.addEventListener("beforeunload",this.boundSaveSessionData),window.addEventListener("pagehide",this.boundSaveSessionData),this.isActive&&(this.urlCheckInterval=window.setInterval((()=>{this.currentUrl!==window.location.href&&(this.currentUrl=window.location.href,this.handleUrlChange())}),1e3)),this.addEventListener("course-select",this.handleCourseSelectEvent)}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("obi-config-updated",this.handleConfigUpdate.bind(this)),null!==this.closeNavTimeoutRef&&window.clearTimeout(this.closeNavTimeoutRef),null!==this.researchingTimeoutRef&&(window.clearTimeout(this.researchingTimeoutRef),this.researchingTimeoutRef=null),this.boundSaveSessionData&&(window.removeEventListener("beforeunload",this.boundSaveSessionData),window.removeEventListener("pagehide",this.boundSaveSessionData)),null!==this.urlCheckInterval&&(clearInterval(this.urlCheckInterval),this.urlCheckInterval=null),this.removeSessionUrlParams()}async handleConfigUpdate(A){const t=A.detail,e=t.isActive&&!this.isActive,i=this.user;if(this.updateFromConfig(),this.activeSession&&void 0!==t.user){const A=t.user;if(JSON.stringify(i)!==JSON.stringify(A))try{await this.activeSession.updateUser(A)}catch(n){console.error("Failed to update session user data:",n)}}!e||yQ(this.urlBlacklist)||this.activeSession||this.sessionConnectionCheck(),this.requestUpdate()}handleMouseEnter(){this.isHovering=!0,this.navVisible=!0}handleMouseLeave(){this.isHovering=!1,null!==this.closeNavTimeoutRef&&window.clearTimeout(this.closeNavTimeoutRef),this.closeNavTimeoutRef=window.setTimeout((()=>{this.isHovering||(this.navVisible=!1),this.closeNavTimeoutRef=null}),300)}terminateSession(){this.clearSessionStorage(),this.sessionToken=null,this.roomToken=null,this.roomUrl=null,null!==this.researchingTimeoutRef&&(window.clearTimeout(this.researchingTimeoutRef),this.researchingTimeoutRef=null),this.activeSession&&(this.activeSession.disconnect(),this.activeSession=null),this.state=Ra.READY}handleItemSelect(A,t){"experiences"!==A?La([A,t]).with(["pause",!0],(()=>{this.activeSession?.pauseRecording()})).with(["pause",!1],(()=>{this.activeSession?.resumeRecording()})).with(["activate",!1],(()=>{this.terminateSession()})).otherwise((()=>{})):this.showCourseModal=!0}async fetchDatabaseConfig(){if(!this.apiKey)return this.configLoaded=!0,void this.applyFinalConfiguration();try{const A=`obi-widget-config-${this.apiKey}`,t=localStorage.getItem(A),e=localStorage.getItem(`${A}-timestamp`);if(t&&e&&Date.now()-parseInt(e,10)<6e5){const A=JSON.parse(t);return this.databaseConfig=A,this.configLoaded=!0,void this.applyFinalConfiguration()}const i=new AbortController,n=setTimeout((()=>i.abort()),3e3),s=await this.obiClient.getOnboardeeWidgetConfig(this.apiKey,i.signal);if(clearTimeout(n),s.error){if(404===s.response?.status)return localStorage.removeItem(A),localStorage.removeItem(`${A}-timestamp`),this.databaseConfig=null,this.configLoaded=!0,void this.applyFinalConfiguration();throw new Error(`HTTP ${s.response?.status||"Unknown error"}`)}const r=s.data;localStorage.setItem(A,JSON.stringify(r)),localStorage.setItem(`${A}-timestamp`,Date.now().toString()),this.databaseConfig=r,this.configLoaded=!0,this.applyFinalConfiguration()}catch(A){A instanceof Error&&"AbortError"===A.name?console.warn("Widget config fetch timed out, using defaults"):console.warn("Failed to fetch widget config from database:",A),this.databaseConfig=null,this.configLoaded=!0,this.applyFinalConfiguration()}}applyFinalConfiguration(){const A=window.obiWidgetConfig,t=this.databaseConfig;this.user=A?.user||this.user,this.position=A?.position||t?.position||this.position,this.setAttribute("position",this.position),void 0!==A?.isActive&&(this.isActive=A.isActive),void 0!==A?.linkOnlyAccess?this.linkOnlyAccess=A.linkOnlyAccess:void 0!==t?.linkOnlyAccess&&(this.linkOnlyAccess=t.linkOnlyAccess);const e=A?.urlBlacklist||[],i=t?.urlBlacklist||[];if(e.length>0||i.length>0){const A=[...e,...i];this.urlBlacklist=[...new Set(A)]}const n=A?.primaryColor||t?.primaryColor||Ga;this.primaryColor=n,this.style.setProperty("--obi-primary",n),this.generateColorVariables(n),!this.isActive||yQ(this.urlBlacklist)||this.activeSession||this.sessionConnectionCheck()}render(){if(!this.configLoaded)return _w;if(!this.isActive)return _w;if(this.linkOnlyAccess&&this.state===Ra.READY)return _w;if(yQ(this.urlBlacklist))return _w;const A=La(this.state).with(Ra.LOADING,(()=>Dw`<obi-dot-loader></obi-dot-loader>`)).with(Ra.RESEARCHING,(()=>Dw`<obi-searching-loader></obi-searching-loader>`)).with(Ka.union(Ra.USER_SPEAKING,Ra.AGENT_SPEAKING),(()=>Dw`<obi-audio-equalizer .volume=${this.volume}></obi-audio-equalizer>`)).with(Ra.THINKING,(()=>Dw`<obi-dot-loader></obi-dot-loader>`)).with(Ra.PAUSED,(()=>DQ)).otherwise((()=>DQ)),t=this.state===Ra.USER_SPEAKING||this.state===Ra.AGENT_SPEAKING,e=this.state===Ra.PAUSED,i=this.state===Ra.RESEARCHING,n=this.state===Ra.USER_SPEAKING,s=this.state!==Ra.READY||this.navVisible,r=this.state!==Ra.READY||this.navVisible,o=this.position.includes("top")?"down":"up",a=["widget-container",s?"rotated":"",t?"pulse":"",e?"paused-pulse":"",i?"researching":"",n?"user-speaking":""].filter(Boolean).join(" ");return Dw`
2349
2349
  <div
2350
2350
  class="${a}"
2351
2351
  @mouseenter=${this.handleMouseEnter}
@@ -2362,48 +2362,45 @@
2362
2362
  ></obi-navigation-bar>
2363
2363
  `:_w}
2364
2364
  </div>
2365
-
2365
+
2366
2366
  ${this.showCourseModal?Dw`<obi-course-modal
2367
2367
  .onClose=${this.handleCloseModals.bind(this)}
2368
2368
  .apiKey=${this.apiKey}
2369
2369
  @course-select=${this.handleCourseSelectEvent}
2370
2370
  ></obi-course-modal>`:_w}
2371
-
2372
2371
  ${this.showSessionStartModal&&this.selectedCourse?Dw`
2373
- <obi-session-start-modal
2374
- .session=${this.selectedCourse?{id:this.selectedCourse.id,name:this.selectedCourse.name,description:this.selectedCourse.description,agentName:this.databaseConfig?.agentName}:{}}
2375
- ?open=${this.showSessionStartModal&&!!this.selectedCourse}
2376
- color=${this.primaryColor}
2377
- @obi-start=${this.handleSessionModalStart}
2378
- @obi-close=${this.handleSessionModalClose}
2379
- @obi-error=${this.handleSessionModalError}
2380
- >
2381
- </obi-session-start-modal>
2382
- `:_w}
2383
-
2372
+ <obi-session-start-modal
2373
+ .session=${this.selectedCourse?{id:this.selectedCourse.id,name:this.selectedCourse.name,description:this.selectedCourse.description,agentName:this.databaseConfig?.agentName}:{}}
2374
+ ?open=${this.showSessionStartModal&&!!this.selectedCourse}
2375
+ color=${this.primaryColor}
2376
+ @obi-start=${this.handleSessionModalStart}
2377
+ @obi-close=${this.handleSessionModalClose}
2378
+ @obi-error=${this.handleSessionModalError}
2379
+ >
2380
+ </obi-session-start-modal>
2381
+ `:_w}
2384
2382
  ${this.showShareMicModal?Dw`
2385
- <obi-share-mic-modal
2386
- .session=${this.selectedCourse?{id:this.selectedCourse.id,name:this.selectedCourse.name,description:this.selectedCourse.description,agentName:this.databaseConfig?.agentName}:{}}
2387
- ?open=${this.showShareMicModal}
2388
- ?disabled=${!this.micShareEnabled}
2389
- color=${this.primaryColor}
2390
- @obi-continue=${this.handleShareMicModalContinue}
2391
- @obi-close=${this.handleShareMicModalClose}
2392
- >
2393
- </obi-share-mic-modal>
2394
- `:_w}
2395
-
2383
+ <obi-share-mic-modal
2384
+ .session=${this.selectedCourse?{id:this.selectedCourse.id,name:this.selectedCourse.name,description:this.selectedCourse.description,agentName:this.databaseConfig?.agentName}:{}}
2385
+ ?open=${this.showShareMicModal}
2386
+ ?disabled=${!this.micShareEnabled}
2387
+ color=${this.primaryColor}
2388
+ @obi-continue=${this.handleShareMicModalContinue}
2389
+ @obi-close=${this.handleShareMicModalClose}
2390
+ >
2391
+ </obi-share-mic-modal>
2392
+ `:_w}
2396
2393
  ${this.showVoiceGuidanceModal?Dw`
2397
- <obi-voice-guidance-modal
2398
- .session=${this.selectedCourse?{id:this.selectedCourse.id,name:this.selectedCourse.name,description:this.selectedCourse.description,agentName:this.databaseConfig?.agentName}:{}}
2399
- ?open=${this.showVoiceGuidanceModal}
2400
- ?disabled=${!this.voiceGuidanceEnabled}
2401
- color=${this.primaryColor}
2402
- @obi-continue=${this.handleVoiceGuidanceModalContinue}
2403
- @obi-close=${this.handleVoiceGuidanceModalClose}
2404
- >
2405
- </obi-voice-guidance-modal>
2406
- `:_w}
2394
+ <obi-voice-guidance-modal
2395
+ .session=${this.selectedCourse?{id:this.selectedCourse.id,name:this.selectedCourse.name,description:this.selectedCourse.description,agentName:this.databaseConfig?.agentName}:{}}
2396
+ ?open=${this.showVoiceGuidanceModal}
2397
+ ?disabled=${!this.voiceGuidanceEnabled}
2398
+ color=${this.primaryColor}
2399
+ @obi-continue=${this.handleVoiceGuidanceModalContinue}
2400
+ @obi-close=${this.handleVoiceGuidanceModalClose}
2401
+ >
2402
+ </obi-voice-guidance-modal>
2403
+ `:_w}
2407
2404
  `}}qy.styles=zg`
2408
2405
  :host {
2409
2406
  display: block;
@@ -2553,4 +2550,4 @@
2553
2550
  box-shadow: 0px 0px 18px 6px
2554
2551
  color-mix(in srgb, var(--obi-paused-pulse, #a06df9) 75%, transparent);
2555
2552
  }
2556
- `,Zy([sp()],qy.prototype,"apiKey",2),Zy([sp()],qy.prototype,"isActive",2),Zy([sp()],qy.prototype,"linkOnlyAccess",2),Zy([sp()],qy.prototype,"urlBlacklist",2),Zy([sp()],qy.prototype,"position",2),Zy([sp()],qy.prototype,"user",2),Zy([sp()],qy.prototype,"state",2),Zy([sp()],qy.prototype,"storedActiveState",2),Zy([sp()],qy.prototype,"showCourseModal",2),Zy([sp()],qy.prototype,"showSessionStartModal",2),Zy([sp()],qy.prototype,"showShareMicModal",2),Zy([sp()],qy.prototype,"micShareEnabled",2),Zy([sp()],qy.prototype,"showVoiceGuidanceModal",2),Zy([sp()],qy.prototype,"voiceGuidanceEnabled",2),Zy([sp()],qy.prototype,"selectedCourse",2),Zy([sp()],qy.prototype,"isHovering",2),Zy([sp()],qy.prototype,"navVisible",2),Zy([sp()],qy.prototype,"activeSession",2),Zy([sp()],qy.prototype,"volume",2),Zy([sp()],qy.prototype,"databaseConfig",2),Zy([sp()],qy.prototype,"configLoaded",2),Zy([sp()],qy.prototype,"configAllInCode",2),Zy([sp()],qy.prototype,"primaryColor",2),customElements.get("obi-widget")||customElements.define("obi-widget",qy);class zy{constructor(){this.history=[],this.currentConfig=null}logInitialConfig(A){const t={timestamp:Date.now(),source:"initial",previousConfig:null,newConfig:this.deepClone(A),diff:this.calculateDiff(null,A)};this.history.push(t),this.currentConfig=this.deepClone(A)}logConfigUpdate(A){const t=this.currentConfig,e={timestamp:Date.now(),source:"update",previousConfig:t?this.deepClone(t):null,newConfig:this.deepClone(A),diff:this.calculateDiff(t,A)};this.history.push(e),this.currentConfig=this.deepClone(A)}getHistory(){return this.history.map((A=>this.deepClone(A)))}getLatest(){return this.currentConfig?this.deepClone(this.currentConfig):null}getDiff(A){return A<0||A>=this.history.length?null:this.deepClone(this.history[A].diff)}clear(){this.history=[],this.currentConfig=null}getFormattedHistory(){return this.history.map(((A,t)=>{const e=new Date(A.timestamp).toISOString(),i=Object.keys(A.diff.added).concat(Object.keys(A.diff.modified),Object.keys(A.diff.removed));return`${t+1}. [${e}] ${A.source.toUpperCase()}: ${i.length>0?i.join(", "):"No changes"}`})).join("\n")}deepClone(A){if(null===A||"object"!=typeof A)return A;if(A instanceof Date)return new Date(A.getTime());if(Array.isArray(A))return A.map((A=>this.deepClone(A)));const t={};for(const e in A)A.hasOwnProperty(e)&&(t[e]=this.deepClone(A[e]));return t}calculateDiff(A,t){const e={added:{},modified:{},removed:{}},i=A?Object.keys(A):[],n=Object.keys(t);for(const s of n)A&&s in A?this.isEqual(A[s],t[s])||(e.modified[s]={from:A[s],to:t[s]}):e.added[s]=t[s];if(A)for(const s of i)s in t||(e.removed[s]=A[s]);return e}isEqual(A,t){if(A===t)return!0;if(null===A||null===t)return A===t;if(typeof A!=typeof t)return!1;if("object"!=typeof A)return A===t;if(Array.isArray(A)!==Array.isArray(t))return!1;if(Array.isArray(A))return A.length===t.length&&A.every(((A,e)=>this.isEqual(A,t[e])));const e=Object.keys(A),i=Object.keys(t);return e.length===i.length&&e.every((e=>this.isEqual(A[e],t[e])))}}customElements.get("obi-widget")||customElements.define("obi-widget",qy);let AF=null;function tF(A){return new Promise((t=>setTimeout(t,A)))}function eF(A){const t=200*Math.pow(2,A);return Math.min(t,2e3)}async function iF(A,t,e=3){let i=null;for(let r=0;r<e;r++)try{return pQ(`${t}_attempt`,{attempt:r+1},"init"),await A()}catch(s){if(i=s,console.warn(`[obi-sdk] ${t} failed (attempt ${r+1}/${e}):`,s),pQ(`${t}_failed`,{error:s instanceof Error?s.message:String(s),attempt:r+1,maxAttempts:e},"init"),r<e-1){const A=eF(r);await tF(A)}}const n=new Error(`${t} failed after ${e} attempts: ${i?.message}`);throw wQ(n,{componentName:"init",handlerName:"retryOperation",operationName:t,maxAttempts:e,lastErrorMessage:i?.message}),n}const nF=bQ((function(){const A=window;let t=[];"function"!=typeof A.ObiSDK&&"object"!=typeof A.ObiSDK||(t=A.ObiSDK.q||[]),AF=new zy,A.obiWidgetConfig&&(vQ({apiKey:A.obiWidgetConfig.apiKey,userId:A.obiWidgetConfig.user?.id,userEmail:A.obiWidgetConfig.user?.email,userMetadata:A.obiWidgetConfig.user?.metadata}),AF.logInitialConfig(A.obiWidgetConfig)),A.ObiSDK=function(t,e){try{if("update"===t&&e){const t={...A.obiWidgetConfig,...e};AF&&AF.logConfigUpdate(t),A.obiWidgetConfig=t,e.user&&vQ({userId:e.user.id,userEmail:e.user.email,userMetadata:e.user.metadata}),document.querySelectorAll("obi-widget").forEach((A=>{A.dispatchEvent(new CustomEvent("obi-config-updated",{detail:e,bubbles:!0,composed:!0}))})),pQ("SDK_config_updated",{hasUser:!!e.user,configKeys:Object.keys(e)},"init")}}catch(i){throw wQ(i,{componentName:"init",handlerName:"ObiSDK.update",command:t}),i}},A.ObiSDK.q=t,A.ObiSDK.log=AF}),"mountSDK","init"),sF=mQ((async function(){return iF((async()=>{if(document.querySelector("obi-widget"))return void pQ("widget_already_exists",{},"init");if(!document.body)throw new Error("document.body not available");const A=document.createElement("obi-widget");document.body.appendChild(A),console.log("[obi-sdk] widget mounted"),pQ("widget_mounted",{},"init")}),"widget mounting")}),"mountWidget","init"),rF=bQ((function(){const A=window;if(A.ObiSDK&&Array.isArray(A.ObiSDK.q)){const t=A.ObiSDK.q.length;pQ("queue_processing",{queueLength:t},"init"),(A.ObiSDK.q||[]).forEach((t=>{A.ObiSDK(...t)})),A.ObiSDK.q=[],t>0&&pQ("queue_processed",{queueLength:t},"init")}}),"processQueue","init"),oF=mQ((async function(){await aF("https://fonts.cdnfonts.com/css/satoshi"),await aF("https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap")}),"loadFonts","init"),aF=mQ((async function(A){return iF((async()=>{if(!document.head)throw new Error("document.head not available");const t=document.createElement("link");t.href=A,t.rel="stylesheet",document.head.appendChild(t),pQ("font_loaded",{fontUrl:A},"init")}),"font loading")}),"loadFont","init"),cF=mQ((async function(){pQ("SDK_initialization_started",{},"init"),await new Promise((A=>setTimeout(A,500))),nF(),await oF(),await sF(),rF(),pQ("SDK_initialization_completed",{},"init")}),"safeInitialize","init"),hF=mQ((async function(){"loading"===document.readyState?(pQ("DOM_not_ready",{},"init"),document.addEventListener("DOMContentLoaded",(async()=>{try{await cF()}catch(A){wQ(A,{componentName:"init",handlerName:"DOMContentLoaded"}),console.error("[obi-sdk] initialization failed:",A)}}))):(pQ("DOM_ready",{},"init"),await cF())}),"initializeObiWidget","init");try{vQ({componentName:"init"}),pQ("SDK_script_loaded",{},"init"),hF().catch((A=>{wQ(A,{componentName:"init",handlerName:"initializeObiWidget"}),console.error("[obi-sdk] initialization failed:",A)}))}catch(uF){wQ(uF,{componentName:"init",handlerName:"top-level"}),console.error("[obi-sdk] initialization failed:",uF)}A.ObiWidget=qy,Object.defineProperty(A,Symbol.toStringTag,{value:"Module"})})({});//# sourceMappingURL=obi-sdk.standalone.iife.js.map
2553
+ `,Zy([sp()],qy.prototype,"apiKey",2),Zy([sp()],qy.prototype,"isActive",2),Zy([sp()],qy.prototype,"linkOnlyAccess",2),Zy([sp()],qy.prototype,"urlBlacklist",2),Zy([sp()],qy.prototype,"position",2),Zy([sp()],qy.prototype,"user",2),Zy([sp()],qy.prototype,"state",2),Zy([sp()],qy.prototype,"storedActiveState",2),Zy([sp()],qy.prototype,"showCourseModal",2),Zy([sp()],qy.prototype,"showSessionStartModal",2),Zy([sp()],qy.prototype,"showShareMicModal",2),Zy([sp()],qy.prototype,"micShareEnabled",2),Zy([sp()],qy.prototype,"showVoiceGuidanceModal",2),Zy([sp()],qy.prototype,"voiceGuidanceEnabled",2),Zy([sp()],qy.prototype,"selectedCourse",2),Zy([sp()],qy.prototype,"isHovering",2),Zy([sp()],qy.prototype,"navVisible",2),Zy([sp()],qy.prototype,"activeSession",2),Zy([sp()],qy.prototype,"volume",2),Zy([sp()],qy.prototype,"databaseConfig",2),Zy([sp()],qy.prototype,"configLoaded",2),Zy([sp()],qy.prototype,"primaryColor",2),customElements.get("obi-widget")||customElements.define("obi-widget",qy);class zy{constructor(){this.history=[],this.currentConfig=null}logInitialConfig(A){const t={timestamp:Date.now(),source:"initial",previousConfig:null,newConfig:this.deepClone(A),diff:this.calculateDiff(null,A)};this.history.push(t),this.currentConfig=this.deepClone(A)}logConfigUpdate(A){const t=this.currentConfig,e={timestamp:Date.now(),source:"update",previousConfig:t?this.deepClone(t):null,newConfig:this.deepClone(A),diff:this.calculateDiff(t,A)};this.history.push(e),this.currentConfig=this.deepClone(A)}getHistory(){return this.history.map((A=>this.deepClone(A)))}getLatest(){return this.currentConfig?this.deepClone(this.currentConfig):null}getDiff(A){return A<0||A>=this.history.length?null:this.deepClone(this.history[A].diff)}clear(){this.history=[],this.currentConfig=null}getFormattedHistory(){return this.history.map(((A,t)=>{const e=new Date(A.timestamp).toISOString(),i=Object.keys(A.diff.added).concat(Object.keys(A.diff.modified),Object.keys(A.diff.removed));return`${t+1}. [${e}] ${A.source.toUpperCase()}: ${i.length>0?i.join(", "):"No changes"}`})).join("\n")}deepClone(A){if(null===A||"object"!=typeof A)return A;if(A instanceof Date)return new Date(A.getTime());if(Array.isArray(A))return A.map((A=>this.deepClone(A)));const t={};for(const e in A)A.hasOwnProperty(e)&&(t[e]=this.deepClone(A[e]));return t}calculateDiff(A,t){const e={added:{},modified:{},removed:{}},i=A?Object.keys(A):[],n=Object.keys(t);for(const s of n)A&&s in A?this.isEqual(A[s],t[s])||(e.modified[s]={from:A[s],to:t[s]}):e.added[s]=t[s];if(A)for(const s of i)s in t||(e.removed[s]=A[s]);return e}isEqual(A,t){if(A===t)return!0;if(null===A||null===t)return A===t;if(typeof A!=typeof t)return!1;if("object"!=typeof A)return A===t;if(Array.isArray(A)!==Array.isArray(t))return!1;if(Array.isArray(A))return A.length===t.length&&A.every(((A,e)=>this.isEqual(A,t[e])));const e=Object.keys(A),i=Object.keys(t);return e.length===i.length&&e.every((e=>this.isEqual(A[e],t[e])))}}customElements.get("obi-widget")||customElements.define("obi-widget",qy);let AF=null;function tF(A){return new Promise((t=>setTimeout(t,A)))}function eF(A){const t=200*Math.pow(2,A);return Math.min(t,2e3)}async function iF(A,t,e=3){let i=null;for(let r=0;r<e;r++)try{return pQ(`${t}_attempt`,{attempt:r+1},"init"),await A()}catch(s){if(i=s,console.warn(`[obi-sdk] ${t} failed (attempt ${r+1}/${e}):`,s),pQ(`${t}_failed`,{error:s instanceof Error?s.message:String(s),attempt:r+1,maxAttempts:e},"init"),r<e-1){const A=eF(r);await tF(A)}}const n=new Error(`${t} failed after ${e} attempts: ${i?.message}`);throw wQ(n,{componentName:"init",handlerName:"retryOperation",operationName:t,maxAttempts:e,lastErrorMessage:i?.message}),n}const nF=bQ((function(){const A=window;let t=[];"function"!=typeof A.ObiSDK&&"object"!=typeof A.ObiSDK||(t=A.ObiSDK.q||[]),AF=new zy,A.obiWidgetConfig&&(vQ({apiKey:A.obiWidgetConfig.apiKey,userId:A.obiWidgetConfig.user?.id,userEmail:A.obiWidgetConfig.user?.email,userMetadata:A.obiWidgetConfig.user?.metadata}),AF.logInitialConfig(A.obiWidgetConfig)),A.ObiSDK=function(t,e){try{if("update"===t&&e){const t={...A.obiWidgetConfig,...e};AF&&AF.logConfigUpdate(t),A.obiWidgetConfig=t,e.user&&vQ({userId:e.user.id,userEmail:e.user.email,userMetadata:e.user.metadata}),document.querySelectorAll("obi-widget").forEach((A=>{A.dispatchEvent(new CustomEvent("obi-config-updated",{detail:e,bubbles:!0,composed:!0}))})),pQ("SDK_config_updated",{hasUser:!!e.user,configKeys:Object.keys(e)},"init")}}catch(i){throw wQ(i,{componentName:"init",handlerName:"ObiSDK.update",command:t}),i}},A.ObiSDK.q=t,A.ObiSDK.log=AF}),"mountSDK","init"),sF=mQ((async function(){return iF((async()=>{if(document.querySelector("obi-widget"))return void pQ("widget_already_exists",{},"init");if(!document.body)throw new Error("document.body not available");const A=document.createElement("obi-widget");document.body.appendChild(A),console.log("[obi-sdk] widget mounted"),pQ("widget_mounted",{},"init")}),"widget mounting")}),"mountWidget","init"),rF=bQ((function(){const A=window;if(A.ObiSDK&&Array.isArray(A.ObiSDK.q)){const t=A.ObiSDK.q.length;pQ("queue_processing",{queueLength:t},"init"),(A.ObiSDK.q||[]).forEach((t=>{A.ObiSDK(...t)})),A.ObiSDK.q=[],t>0&&pQ("queue_processed",{queueLength:t},"init")}}),"processQueue","init"),oF=mQ((async function(){await aF("https://fonts.cdnfonts.com/css/satoshi"),await aF("https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap")}),"loadFonts","init"),aF=mQ((async function(A){return iF((async()=>{if(!document.head)throw new Error("document.head not available");const t=document.createElement("link");t.href=A,t.rel="stylesheet",document.head.appendChild(t),pQ("font_loaded",{fontUrl:A},"init")}),"font loading")}),"loadFont","init"),cF=mQ((async function(){pQ("SDK_initialization_started",{},"init"),await new Promise((A=>setTimeout(A,500))),nF(),await oF(),await sF(),rF(),pQ("SDK_initialization_completed",{},"init")}),"safeInitialize","init"),hF=mQ((async function(){"loading"===document.readyState?(pQ("DOM_not_ready",{},"init"),document.addEventListener("DOMContentLoaded",(async()=>{try{await cF()}catch(A){wQ(A,{componentName:"init",handlerName:"DOMContentLoaded"}),console.error("[obi-sdk] initialization failed:",A)}}))):(pQ("DOM_ready",{},"init"),await cF())}),"initializeObiWidget","init");try{vQ({componentName:"init"}),pQ("SDK_script_loaded",{},"init"),hF().catch((A=>{wQ(A,{componentName:"init",handlerName:"initializeObiWidget"}),console.error("[obi-sdk] initialization failed:",A)}))}catch(uF){wQ(uF,{componentName:"init",handlerName:"top-level"}),console.error("[obi-sdk] initialization failed:",uF)}A.ObiWidget=qy,Object.defineProperty(A,Symbol.toStringTag,{value:"Module"})})({});//# sourceMappingURL=obi-sdk.standalone.iife.js.map