obi-sdk 0.13.1 → 0.13.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/modular/chunks/index-a668ac46.js +6 -0
- package/dist/modular/chunks/index-a668ac46.js.map +1 -0
- package/dist/modular/chunks/{obi-widget-d596380b.js → obi-widget-d8354869.js} +9 -2
- package/dist/modular/chunks/{obi-widget-d596380b.js.map → obi-widget-d8354869.js.map} +1 -1
- package/dist/modular/index.js +1 -1
- package/dist/modular/ui.js +10 -10
- package/dist/obi-sdk.standalone.iife.js +1 -1
- package/dist/obi-sdk.standalone.iife.js.map +1 -1
- package/dist/react.es.js +4 -4
- package/dist/react.es.js.map +1 -1
- package/dist/react.umd.js +1 -1
- package/dist/react.umd.js.map +1 -1
- package/package.json +3 -3
- package/dist/modular/chunks/index-14b8cc26.js +0 -6
- package/dist/modular/chunks/index-14b8cc26.js.map +0 -1
package/dist/modular/index.js
CHANGED
|
@@ -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-
|
|
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";
|
|
2
2
|
import "./chunks/types-f38a47f6.js";
|
|
3
3
|
class ConfigLogger {
|
|
4
4
|
constructor() {
|
package/dist/modular/ui.js
CHANGED
|
@@ -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-
|
|
3
|
-
import { A, C, e, f, D, N, d, O, S } from "./chunks/obi-widget-
|
|
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";
|
|
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-
|
|
89
|
-
import("./chunks/obi-widget-
|
|
90
|
-
import("./chunks/obi-widget-
|
|
91
|
-
import("./chunks/obi-widget-
|
|
92
|
-
import("./chunks/obi-widget-
|
|
93
|
-
import("./chunks/obi-widget-
|
|
94
|
-
import("./chunks/obi-widget-
|
|
95
|
-
import("./chunks/obi-widget-
|
|
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);
|
|
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.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.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,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){if("experiences"===A)return this.showCourseModal=!0,void(this.showShareMicModal=!1);La([A,t]).with(["pause",!0],(()=>{this.activeSession?.pauseRecording()})).with(["pause",!1],(()=>{this.activeSession?.resumeRecording()})).with(["activate",!1],(()=>{this.terminateSession()})).otherwise((()=>{}))}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.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`
|
|
2349
2349
|
<div
|
|
2350
2350
|
class="${a}"
|
|
2351
2351
|
@mouseenter=${this.handleMouseEnter}
|