@vanira/sdk 0.0.43 β 0.0.44
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/vanira-sdk.es.js +11 -4
- package/dist/vanira-sdk.js +1 -1
- package/dist/vanira-sdk.js.map +1 -1
- package/dist/vanira-sdk.umd.js +2 -2
- package/package.json +1 -1
package/dist/vanira-sdk.es.js
CHANGED
|
@@ -2687,9 +2687,16 @@ const D = class D extends $ {
|
|
|
2687
2687
|
if (console.log("[VaniraAI Widget] Tool call received:", r.name, r.arguments), (c = this.presetRenderer) == null ? void 0 : c.handle(
|
|
2688
2688
|
r,
|
|
2689
2689
|
(b) => {
|
|
2690
|
-
var
|
|
2691
|
-
const u =
|
|
2692
|
-
|
|
2690
|
+
var y, w;
|
|
2691
|
+
const u = r.arguments || r.args || {};
|
|
2692
|
+
let v = u;
|
|
2693
|
+
if (typeof u == "string")
|
|
2694
|
+
try {
|
|
2695
|
+
v = JSON.parse(u);
|
|
2696
|
+
} catch {
|
|
2697
|
+
}
|
|
2698
|
+
const f = ((y = r.client_fields) == null ? void 0 : y.preset_id) || (v == null ? void 0 : v.preset_id), x = ((w = r.client_fields) == null ? void 0 : w.action_name) || (f === "vanira_calendar" ? "calendar_slot_selected" : `user_submitted_${r.name}`);
|
|
2699
|
+
A.triggerInterrupt(x, b);
|
|
2693
2700
|
},
|
|
2694
2701
|
(b) => {
|
|
2695
2702
|
const u = r.tool_call_id;
|
|
@@ -3142,7 +3149,7 @@ const ve = ({
|
|
|
3142
3149
|
p.triggerActionInterrupt && (console.log("β‘ [PresetRenderer Wrapper] Triggering action interrupt to wake AI..."), p.triggerActionInterrupt());
|
|
3143
3150
|
const m = typeof c == "string" ? { response: c } : c;
|
|
3144
3151
|
if (p.sendActionTrigger) {
|
|
3145
|
-
const g = d.action_name || `user_submitted_${s.name}
|
|
3152
|
+
const g = d.action_name || (A === "vanira_calendar" ? "calendar_slot_selected" : `user_submitted_${s.name}`);
|
|
3146
3153
|
console.log(`π€ [PresetRenderer Wrapper] Submitting preset data via sendActionTrigger (${g})...`), p.sendActionTrigger(g, m);
|
|
3147
3154
|
} else
|
|
3148
3155
|
console.log(`π€ [PresetRenderer Wrapper] Submitting tool result for ID: ${r}`), p.sendToolResult(r, m);
|
package/dist/vanira-sdk.js
CHANGED
|
@@ -1449,7 +1449,7 @@ overflow: hidden;
|
|
|
1449
1449
|
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
|
|
1450
1450
|
</button>
|
|
1451
1451
|
</div>
|
|
1452
|
-
`,p.querySelector("#vnr-remove-file").addEventListener("click",()=>{r=null,p.style.display="none",A.style.display="block",m.disabled=!0}),m.disabled=!1};A.addEventListener("click",()=>g.click()),A.addEventListener("dragover",f=>{f.preventDefault(),A.classList.add("drag")}),A.addEventListener("dragleave",()=>A.classList.remove("drag")),A.addEventListener("drop",f=>{var y;f.preventDefault(),A.classList.remove("drag");const b=(y=f.dataTransfer)==null?void 0:y.files[0];b&&w(b)}),g.addEventListener("change",()=>{var b;const f=(b=g.files)==null?void 0:b[0];f&&w(f)}),m.addEventListener("click",async()=>{if(!r)return;const f=r;A.style.display="none",p.style.display="none",x.style.display="block",x.innerHTML='<div class="vnr-center"><div class="vnr-spinner" style="margin:0 auto 8px"></div>Uploadingβ¦</div>',m.disabled=!0;try{if(s&&typeof s.uploadMedia=="function"){const{media_id:b,url:y}=await s.uploadMedia(f,d,`User uploaded: ${f.name}`);x.innerHTML='<div class="vnr-center" style="color:#22c55e">β File sent!</div>',setTimeout(()=>{this.dismiss(),e({file_name:f.name,file_type:f.type,file_size:f.size,media_id:b,url:y,message:`User uploaded: ${f.name}`})},400)}else{const b=new FileReader;b.onload=y=>{x.innerHTML='<div class="vnr-center" style="color:#22c55e">β File ready!</div>',setTimeout(()=>{this.dismiss(),e({file_name:f.name,file_type:f.type,file_size:f.size,data_url:y.target.result,message:`User uploaded: ${f.name}`})},400)},b.readAsDataURL(f)}}catch(b){x.innerHTML=`<div class="vnr-center" style="color:#ef4444">${(b==null?void 0:b.message)||"Upload failed. Please try again."}</div>`,m.disabled=!1}})}renderNavigate(t,e,i){var o,d;const s=String(((o=t.clientFields)==null?void 0:o.target_url)||((d=t.args)==null?void 0:d.target_url)||"/");if(console.log(`π [WidgetPresetRenderer] Navigating to: ${s}`),s.startsWith("http://")||s.startsWith("https://"))window.open(s,"_blank","noopener,noreferrer");else{const l=window.location.href;window.dispatchEvent(new CustomEvent("vanira:navigate",{detail:{url:s}})),setTimeout(()=>{window.location.href===l&&(window.location.href=s)},150)}e({navigated_to:s,status:"success"})}renderHighlight(t,e,i){const s=t.args||{},n=t.clientFields||{},o=String(s.css_selector||n.css_selector||s.selector||n.selector||""),d=String(s.highlight_color||n.highlight_color||"#a855f7"),l=Number(s.duration_ms||n.duration_ms||3e3);if(console.log("π¦ [WidgetPresetRenderer] renderHighlight triggered"),console.log(` β selector: "${o}"`),console.log(` β color: "${d}"`),console.log(` β duration: ${l}ms`),!o){console.warn("β οΈ [WidgetPresetRenderer] No css_selector provided for highlight"),i("No css_selector provided for highlight");return}const r=document.querySelector(o);if(console.log(`π¦ [WidgetPresetRenderer] querySelector("${o}") β`,r),!r){console.warn(`β οΈ [WidgetPresetRenderer] Element not found for selector: "${o}"`),i(`Element not found for selector: "${o}"`);return}const h=r.style.outline,c=r.style.outlineOffset,A=r.style.boxShadow,g=r.style.transition,p=r.style.scrollMarginTop;r.style.transition="outline 0.2s ease, box-shadow 0.2s ease",r.style.outline=`3px solid ${d}`,r.style.outlineOffset="6px",r.style.boxShadow=`0 0 0 8px ${d}33, 0 0 32px ${d}88`,r.style.scrollMarginTop="100px",console.log("β
[WidgetPresetRenderer] Highlight applied to:",r),r.scrollIntoView({behavior:"smooth",block:"center"}),setTimeout(()=>{r.style.outline=h,r.style.outlineOffset=c,r.style.boxShadow=A,r.style.transition=g,r.style.scrollMarginTop=p,console.log(`π¦ [WidgetPresetRenderer] Highlight removed from: "${o}"`)},l),e({status:"success",message:`Element highlighted: ${o}`})}renderTypeText(t,e,i){const s=t.args||{},n=t.clientFields||{},o=String(s.element_id||n.element_id||s.css_selector||n.css_selector||s.selector||n.selector||"").trim(),d=String(s.text_to_type||n.text_to_type||""),l=Number(s.delay_ms!==void 0?s.delay_ms:n.delay_ms!==void 0?n.delay_ms:50);console.log("βοΈ [WidgetPresetRenderer] renderTypeText triggered"),console.log(` β idOrSelector: "${o}"`),console.log(` β text_to_type: "${d}"`),console.log(` β delayMs: ${l}ms`);let r=null;if(o){try{r=document.querySelector(o)}catch{}r||(r=document.getElementById(o))}const h=()=>{console.log("βΉοΈ [WidgetPresetRenderer] Target element not found or selector not provided. Displaying fallback popup.");const m="Text Input Simulation",w=o?`Target element "${o}" not found on the page. Typing is simulated below:`:"No target input ID/selector was provided. Typing is simulated below:",f=this.createOverlay(),b=this.createModal(f,m,w),y=document.createElement("div");y.style.marginTop="14px",y.style.display="flex",y.style.flexDirection="column",y.style.gap="12px";const v=document.createElement("textarea");v.style.width="100%",v.style.height="120px",v.style.background="#f9fafb",v.style.border="1px solid #e5e7eb",v.style.borderRadius="10px",v.style.padding="12px",v.style.fontSize="14px",v.style.color="#111",v.style.outline="none",v.style.resize="none",v.style.boxSizing="border-box",v.placeholder="Simulating typing...",y.appendChild(v);const C=document.createElement("button");C.style.width="100%",C.style.padding="10px 16px",C.style.background="#111",C.style.color="#fff",C.style.border="none",C.style.borderRadius="10px",C.style.fontSize="14px",C.style.fontWeight="600",C.style.cursor="pointer",C.style.transition="background 0.2s",C.textContent="Submit",y.appendChild(C),b.appendChild(y);const P=b.querySelector(".vnr-close-btn");if(P&&(P.onclick=()=>{this.dismiss(),i("User dismissed typing popup")}),C.onclick=()=>{const Q=v.value;this.dismiss(),e({status:"success",text:Q,message:"Text submitted via popup simulation"})},v.focus(),l<=0)v.value=d;else{let Q="",M=0;const k=()=>{this.overlay&&M<d.length&&(Q+=d[M],v.value=Q,M++,setTimeout(k,l))};k()}};if(!r){h();return}if(r.focus(),!(r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement||"value"in r)){console.log("βΉοΈ [WidgetPresetRenderer] Target is not a form input. Setting textContent directly."),r.textContent=d,e({status:"success",message:`Text set on element: ${o}`});return}const A=r;if(l<=0){A.value=d,A.dispatchEvent(new Event("input",{bubbles:!0})),A.dispatchEvent(new Event("change",{bubbles:!0})),e({status:"success",message:`Text entered instantly in: ${o}`});return}let g="",p=0;const x=()=>{p<d.length?(g+=d[p],A.value=g,A.dispatchEvent(new Event("input",{bubbles:!0})),p++,setTimeout(x,l)):(A.dispatchEvent(new Event("change",{bubbles:!0})),e({status:"success",message:`Text typed completely in: ${o}`}))};x()}}const Y=class Y extends re{constructor(e){super(e);a(this,"vaniraClient",null);a(this,"currentView",null);a(this,"presetRenderer",null);a(this,"isPanelOpen",!1);a(this,"callActive",!1);a(this,"eventSource",null);a(this,"floatingButton",null);a(this,"floatingWelcomeChips",null);a(this,"panel",null);a(this,"welcomeChipsData",[]);a(this,"chatAdapter");a(this,"sessionManager",null);a(this,"sessionActive",!1);a(this,"widgetMode","voice_only");a(this,"agentId","");a(this,"prospectGroupId","");a(this,"chatServerUrl","");a(this,"prospectId","");a(this,"chatId",null);a(this,"conversationId",null);a(this,"widgetId","");a(this,"pkKey","");a(this,"chatInitialized",!1);a(this,"primaryColor","#000000");a(this,"secondaryColor","#111111");a(this,"gradient",null);a(this,"positionType","fixed");a(this,"position","bottom-right");a(this,"widgetIcon",null);a(this,"iconConfig",null);a(this,"chatWelcomeMessage",null);this.chatAdapter=new fe,this.processConfig(e)}initSessionManager(){const e=this.widgetId||this.agentId||"default";this.sessionManager=new R(e),this.sessionManager.on("tab_took_over",()=>{console.warn("[VaniraAI] Session taken over by another tab."),this.sessionActive=!1,this.showTabConflictBanner("taken_over")}),this.sessionManager.on("session_cleared",()=>{console.log("[VaniraAI] Session cleared externally.")});const i=this.sessionManager.claimSession();return this.sessionActive=i,i}restoreSessionMessages(){var l,r,h;const e=(l=this.sessionManager)==null?void 0:l.getSession();if(!e)return;const i=(h=(r=this.currentView)==null?void 0:r.getChatWindow)==null?void 0:h.call(r);if(!i)return;const s=e.messages.filter(c=>c.content.trim()!==""),n=`vanira_calls_${this.widgetId||this.agentId}`,o=JSON.parse(localStorage.getItem(n)||"[]");if(s.length===0&&o.length===0)return;i.clearMessages();const d=[...s.map((c,A)=>({type:"msg",role:c.role,content:c.content,ts:c.timestamp??A})),...o.map(c=>({type:"call",durationMs:c.durationMs,startedAt:c.startedAt,ts:c.startedAt}))];d.sort((c,A)=>c.ts-A.ts),d.forEach(c=>{c.type==="msg"?i.addMessage(c.role,c.content,c.ts):i.addCallRecord(c.durationMs,c.startedAt)}),console.log(`[VaniraAI] Restored ${s.length} messages + ${o.length} call records from session.`)}showTabConflictBanner(e){var i,s;this.root&&((i=this.root.querySelector(".vanira-tab-conflict-banner"))==null||i.remove(),e==="conflict"&&((s=this.sessionManager)==null||s.forceClaimSession(),this.sessionActive=!0,this.widgetMode.includes("chat")&&this.initializeChatSession(!1)))}playMessageSound(e){try{if(!Y.audioContext){const d=window.AudioContext||window.webkitAudioContext;if(!d)return;Y.audioContext=new d}const i=Y.audioContext;i.state==="suspended"&&i.resume().catch(()=>{});const s=i.createOscillator(),n=i.createGain();s.connect(n),n.connect(i.destination);const o=i.currentTime;e==="send"?(s.type="sine",s.frequency.setValueAtTime(300,o),s.frequency.exponentialRampToValueAtTime(500,o+.05),n.gain.setValueAtTime(0,o),n.gain.linearRampToValueAtTime(.1,o+.01),n.gain.exponentialRampToValueAtTime(.001,o+.1),s.start(o),s.stop(o+.1)):(s.type="sine",s.frequency.setValueAtTime(500,o),s.frequency.exponentialRampToValueAtTime(800,o+.1),n.gain.setValueAtTime(0,o),n.gain.linearRampToValueAtTime(.15,o+.02),n.gain.exponentialRampToValueAtTime(.001,o+.2),s.start(o),s.stop(o+.2))}catch(i){console.warn("[VaniraAI] Audio feedback failed",i)}}handleWelcomePayload(e,i="assistant"){var o,d,l,r,h,c,A,g;if(!e||this.widgetMode==="voice_only")return;e.buttons&&Array.isArray(e.buttons)?this.welcomeChipsData=e.buttons:((o=e.widget)==null?void 0:o.type)==="button_list"&&((d=e.widget.data)!=null&&d.buttons)&&(this.welcomeChipsData=e.widget.data.buttons),this.updateWelcomeChipsVisibility();const s=(r=(l=this.currentView)==null?void 0:l.getChatWindow)==null?void 0:r.call(l);let n=e.text||e.response||e.content||e.message||"";if(!n&&!this.welcomeChipsData.length&&(n="Hey! how can I help you ?"),!n&&typeof e=="string"&&e.trim().startsWith("{"))try{const p=JSON.parse(e);n=p.text||p.response||p.content||p.message||"",((h=p.widget)==null?void 0:h.type)==="button_list"&&((c=p.widget.data)!=null&&c.buttons)&&(this.welcomeChipsData=p.widget.data.buttons)}catch{}if(console.log("[VaniraAI] Processing Welcome Payload:",{hasText:!!n,chipsCount:this.welcomeChipsData.length,hasChatWindow:!!s,mode:this.widgetMode}),s){if(!n&&this.welcomeChipsData.length===0)return;const p=(A=this.sessionManager)==null?void 0:A.getSession();(p==null?void 0:p.messages.some(m=>m.content===n&&m.role===i))||(n&&(s.addMessage(i,n),(g=this.sessionManager)==null||g.pushMessage(i,n)),this.welcomeChipsData.length>0&&s.addButtons(this.welcomeChipsData))}}async initializeChatSession(e=!1){var i,s,n,o,d,l;if(this.sessionActive&&!this.chatInitialized){this.chatInitialized=!0;try{T.setChatUrl(this.chatServerUrl);const r=(i=this.sessionManager)==null?void 0:i.getSession();if(!e&&(r!=null&&r.prospectId)){this.prospectId=r.prospectId,this.chatId=r.chatId,this.conversationId=r.conversationId||null,console.log(`[VaniraAI] Session restored β tab: ${(s=this.sessionManager)==null?void 0:s.getTabId()}, prospect: ${this.prospectId}`),this.restoreSessionMessages(),this.chatId&&!this.eventSource&&(this.eventSource=T.listenForAdminReplies(this.chatId,this.prospectId,c=>{var A,g,p;(g=(A=this.currentView)==null?void 0:A.getChatWindow)==null||g.call(A).addMessage("assistant",c),(p=this.sessionManager)==null||p.pushMessage("assistant",c),this.playMessageSound("receive")}));return}this.prospectId||(this.prospectGroupId?this.prospectId=await T.createChatProspect(this.prospectGroupId):this.prospectId=`anon_${Date.now()}_${Math.random().toString(36).substr(2,9)}`);const h=await T.fetchWelcomeMessage(this.agentId,this.prospectId,this.widgetId||void 0,this.pkKey||void 0);h&&(this.handleWelcomePayload(h),h.chatId&&!this.chatId&&(this.chatId=h.chatId,this.eventSource||(this.eventSource=T.listenForAdminReplies(this.chatId,this.prospectId,c=>{var A,g,p;(g=(A=this.currentView)==null?void 0:A.getChatWindow)==null||g.call(A).addMessage("assistant",c),(p=this.sessionManager)==null||p.pushMessage("assistant",c),this.playMessageSound("receive")}))),h.conversationId&&(this.conversationId=h.conversationId)),(n=this.sessionManager)==null||n.saveIds(this.prospectId,this.chatId,this.conversationId)}catch(r){console.error("[VaniraAI] Chat init failed",r);const h="Hey! how can I help you ?";(d=(o=this.currentView)==null?void 0:o.getChatWindow)==null||d.call(o).addMessage("assistant",h),(l=this.sessionManager)==null||l.pushMessage("assistant",h)}}}async initialize(e){await super.initialize(e),this.processConfig(e),this.root&&this.ui_renderer(this.root)}processConfig(e){var i,s;if(this.widgetId=e.widgetId||e.widget_id||this.widgetId||"",this.agentId=e.agentId||e.agent_id||this.agentId||"",this.prospectGroupId=e.prospectGroupId||((i=e.client)==null?void 0:i.base_prospect_group_id)||this.prospectGroupId||"",this.widgetMode=e.widgetMode||e.mode||this.widgetMode||"voice_only",this.pkKey=e.pkKey||e.pk_key||e.publicKey||e.public_key||this.pkKey||"",this.primaryColor=e.primaryColor||e.primary_color||"#000000",this.secondaryColor=e.secondaryColor||e.secondary_color||"#111111",this.gradient=e.gradient||null,this.position=e.position||"bottom-right",this.positionType=e.positionType||"fixed",this.widgetIcon=e.widgetIcon||e.icon||null,this.iconConfig=e.iconConfig||e.icon_config||null,this.chatWelcomeMessage=e.chatWelcomeMessage||e.chat_welcome_message||((s=e.agent)==null?void 0:s.chat_welcome_message)||null,console.log("[VaniraAI] processConfig:",{hasPrimary:!!this.primaryColor,hasSecondary:!!this.secondaryColor,hasWelcome:!!this.chatWelcomeMessage}),typeof this.chatWelcomeMessage=="string")try{this.chatWelcomeMessage=JSON.parse(this.chatWelcomeMessage)}catch(n){console.warn("[VaniraAI] Failed to parse chatWelcomeMessage string",n)}this.chatServerUrl=e.serverUrl||e.chatServerUrl||"https://inboxapi.travelr.club",this.updateWelcomeChipsVisibility()}async create_call(e="continue"){var i,s,n;if(!(this.callActive||!this.agentId)){this.sessionActive||((i=this.sessionManager)==null||i.forceClaimSession(),this.sessionActive=!0);try{this.callActive=!0,this.updateViewCallState(!0),this.updateViewStatus("connecting");const o=((s=this.config)==null?void 0:s.serverUrl)||((n=this.config)==null?void 0:n.chatServerUrl),d=o&&!o.includes("travelr.club")?o:"https://api.vanira.io",l=new O({agentId:this.agentId,apiKey:this.pkKey||void 0,sessionBehavior:e,prospectId:this.prospectId||void 0,backendUrl:d});l.on("session_started",({prospectId:r})=>{var h;r&&(this.prospectId=r,(h=this.sessionManager)==null||h.saveIds(r,this.chatId))}),l.on("connected",()=>this.updateViewStatus("connected")).on("disconnected",()=>this.end_call()).on("error",r=>{console.error("[VaniraAI Widget] Call error:",r),this.updateViewStatus("error",r)}).on("transcription",({text:r,isFinal:h})=>{var c,A;(A=(c=this.currentView)==null?void 0:c.setTranscription)==null||A.call(c,r,h)}).on("track",({track:r})=>{var h;this.widgetMode.includes("avatar")&&r.kind==="video"&&((h=this.currentView)!=null&&h.setVideoTrack)&&this.currentView.setVideoTrack(r)}).on("tool_call",r=>{var A,g,p;if(console.log("[VaniraAI Widget] Tool call received:",r.name,r.arguments),(A=this.presetRenderer)==null?void 0:A.handle(r,x=>{var w;const m=((w=r.client_fields)==null?void 0:w.action_name)||`user_submitted_${r.name}`;l.triggerInterrupt(m,x)},x=>{const m=r.tool_call_id;try{l.sendToolResult(m,{status:"cancelled",reason:"User dismissed"})}catch{}},l))return;const c=new CustomEvent("vaniraai:tool_call",{detail:r,bubbles:!0,composed:!0});(p=(g=this.root)==null?void 0:g.host)==null||p.dispatchEvent(c)}),this.vaniraClient=l,await l.start()}catch(o){console.error("[VaniraAI Widget] Call failed",o),this.updateViewStatus("error",(o==null?void 0:o.message)||String(o))}}}end_call(){var i;this.callActive=!1;const e=this.vaniraClient;this.vaniraClient=null,e&&e.stop(),(i=this.presetRenderer)==null||i.dismiss(),this.updateViewCallState(!1)}updateViewCallState(e){var i;(i=this.currentView)!=null&&i.setCallActive&&this.currentView.setCallActive(e)}updateViewStatus(e,i){var s;(s=this.currentView)!=null&&s.setStatus&&this.currentView.setStatus(e,i)}ui_renderer(e){var r,h,c;this.root=e,this.root.innerHTML="",this.presetRenderer=new ve(e),this.root.host&&(this.positionType==="fixed"?this.root.host.classList.add("vanira-portal"):this.root.host.classList.remove("vanira-portal"));const i=document.createElement("style");i.textContent=`@keyframes vanira-slide-up {
|
|
1452
|
+
`,p.querySelector("#vnr-remove-file").addEventListener("click",()=>{r=null,p.style.display="none",A.style.display="block",m.disabled=!0}),m.disabled=!1};A.addEventListener("click",()=>g.click()),A.addEventListener("dragover",f=>{f.preventDefault(),A.classList.add("drag")}),A.addEventListener("dragleave",()=>A.classList.remove("drag")),A.addEventListener("drop",f=>{var y;f.preventDefault(),A.classList.remove("drag");const b=(y=f.dataTransfer)==null?void 0:y.files[0];b&&w(b)}),g.addEventListener("change",()=>{var b;const f=(b=g.files)==null?void 0:b[0];f&&w(f)}),m.addEventListener("click",async()=>{if(!r)return;const f=r;A.style.display="none",p.style.display="none",x.style.display="block",x.innerHTML='<div class="vnr-center"><div class="vnr-spinner" style="margin:0 auto 8px"></div>Uploadingβ¦</div>',m.disabled=!0;try{if(s&&typeof s.uploadMedia=="function"){const{media_id:b,url:y}=await s.uploadMedia(f,d,`User uploaded: ${f.name}`);x.innerHTML='<div class="vnr-center" style="color:#22c55e">β File sent!</div>',setTimeout(()=>{this.dismiss(),e({file_name:f.name,file_type:f.type,file_size:f.size,media_id:b,url:y,message:`User uploaded: ${f.name}`})},400)}else{const b=new FileReader;b.onload=y=>{x.innerHTML='<div class="vnr-center" style="color:#22c55e">β File ready!</div>',setTimeout(()=>{this.dismiss(),e({file_name:f.name,file_type:f.type,file_size:f.size,data_url:y.target.result,message:`User uploaded: ${f.name}`})},400)},b.readAsDataURL(f)}}catch(b){x.innerHTML=`<div class="vnr-center" style="color:#ef4444">${(b==null?void 0:b.message)||"Upload failed. Please try again."}</div>`,m.disabled=!1}})}renderNavigate(t,e,i){var o,d;const s=String(((o=t.clientFields)==null?void 0:o.target_url)||((d=t.args)==null?void 0:d.target_url)||"/");if(console.log(`π [WidgetPresetRenderer] Navigating to: ${s}`),s.startsWith("http://")||s.startsWith("https://"))window.open(s,"_blank","noopener,noreferrer");else{const l=window.location.href;window.dispatchEvent(new CustomEvent("vanira:navigate",{detail:{url:s}})),setTimeout(()=>{window.location.href===l&&(window.location.href=s)},150)}e({navigated_to:s,status:"success"})}renderHighlight(t,e,i){const s=t.args||{},n=t.clientFields||{},o=String(s.css_selector||n.css_selector||s.selector||n.selector||""),d=String(s.highlight_color||n.highlight_color||"#a855f7"),l=Number(s.duration_ms||n.duration_ms||3e3);if(console.log("π¦ [WidgetPresetRenderer] renderHighlight triggered"),console.log(` β selector: "${o}"`),console.log(` β color: "${d}"`),console.log(` β duration: ${l}ms`),!o){console.warn("β οΈ [WidgetPresetRenderer] No css_selector provided for highlight"),i("No css_selector provided for highlight");return}const r=document.querySelector(o);if(console.log(`π¦ [WidgetPresetRenderer] querySelector("${o}") β`,r),!r){console.warn(`β οΈ [WidgetPresetRenderer] Element not found for selector: "${o}"`),i(`Element not found for selector: "${o}"`);return}const h=r.style.outline,c=r.style.outlineOffset,A=r.style.boxShadow,g=r.style.transition,p=r.style.scrollMarginTop;r.style.transition="outline 0.2s ease, box-shadow 0.2s ease",r.style.outline=`3px solid ${d}`,r.style.outlineOffset="6px",r.style.boxShadow=`0 0 0 8px ${d}33, 0 0 32px ${d}88`,r.style.scrollMarginTop="100px",console.log("β
[WidgetPresetRenderer] Highlight applied to:",r),r.scrollIntoView({behavior:"smooth",block:"center"}),setTimeout(()=>{r.style.outline=h,r.style.outlineOffset=c,r.style.boxShadow=A,r.style.transition=g,r.style.scrollMarginTop=p,console.log(`π¦ [WidgetPresetRenderer] Highlight removed from: "${o}"`)},l),e({status:"success",message:`Element highlighted: ${o}`})}renderTypeText(t,e,i){const s=t.args||{},n=t.clientFields||{},o=String(s.element_id||n.element_id||s.css_selector||n.css_selector||s.selector||n.selector||"").trim(),d=String(s.text_to_type||n.text_to_type||""),l=Number(s.delay_ms!==void 0?s.delay_ms:n.delay_ms!==void 0?n.delay_ms:50);console.log("βοΈ [WidgetPresetRenderer] renderTypeText triggered"),console.log(` β idOrSelector: "${o}"`),console.log(` β text_to_type: "${d}"`),console.log(` β delayMs: ${l}ms`);let r=null;if(o){try{r=document.querySelector(o)}catch{}r||(r=document.getElementById(o))}const h=()=>{console.log("βΉοΈ [WidgetPresetRenderer] Target element not found or selector not provided. Displaying fallback popup.");const m="Text Input Simulation",w=o?`Target element "${o}" not found on the page. Typing is simulated below:`:"No target input ID/selector was provided. Typing is simulated below:",f=this.createOverlay(),b=this.createModal(f,m,w),y=document.createElement("div");y.style.marginTop="14px",y.style.display="flex",y.style.flexDirection="column",y.style.gap="12px";const v=document.createElement("textarea");v.style.width="100%",v.style.height="120px",v.style.background="#f9fafb",v.style.border="1px solid #e5e7eb",v.style.borderRadius="10px",v.style.padding="12px",v.style.fontSize="14px",v.style.color="#111",v.style.outline="none",v.style.resize="none",v.style.boxSizing="border-box",v.placeholder="Simulating typing...",y.appendChild(v);const C=document.createElement("button");C.style.width="100%",C.style.padding="10px 16px",C.style.background="#111",C.style.color="#fff",C.style.border="none",C.style.borderRadius="10px",C.style.fontSize="14px",C.style.fontWeight="600",C.style.cursor="pointer",C.style.transition="background 0.2s",C.textContent="Submit",y.appendChild(C),b.appendChild(y);const P=b.querySelector(".vnr-close-btn");if(P&&(P.onclick=()=>{this.dismiss(),i("User dismissed typing popup")}),C.onclick=()=>{const Q=v.value;this.dismiss(),e({status:"success",text:Q,message:"Text submitted via popup simulation"})},v.focus(),l<=0)v.value=d;else{let Q="",M=0;const k=()=>{this.overlay&&M<d.length&&(Q+=d[M],v.value=Q,M++,setTimeout(k,l))};k()}};if(!r){h();return}if(r.focus(),!(r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement||"value"in r)){console.log("βΉοΈ [WidgetPresetRenderer] Target is not a form input. Setting textContent directly."),r.textContent=d,e({status:"success",message:`Text set on element: ${o}`});return}const A=r;if(l<=0){A.value=d,A.dispatchEvent(new Event("input",{bubbles:!0})),A.dispatchEvent(new Event("change",{bubbles:!0})),e({status:"success",message:`Text entered instantly in: ${o}`});return}let g="",p=0;const x=()=>{p<d.length?(g+=d[p],A.value=g,A.dispatchEvent(new Event("input",{bubbles:!0})),p++,setTimeout(x,l)):(A.dispatchEvent(new Event("change",{bubbles:!0})),e({status:"success",message:`Text typed completely in: ${o}`}))};x()}}const Y=class Y extends re{constructor(e){super(e);a(this,"vaniraClient",null);a(this,"currentView",null);a(this,"presetRenderer",null);a(this,"isPanelOpen",!1);a(this,"callActive",!1);a(this,"eventSource",null);a(this,"floatingButton",null);a(this,"floatingWelcomeChips",null);a(this,"panel",null);a(this,"welcomeChipsData",[]);a(this,"chatAdapter");a(this,"sessionManager",null);a(this,"sessionActive",!1);a(this,"widgetMode","voice_only");a(this,"agentId","");a(this,"prospectGroupId","");a(this,"chatServerUrl","");a(this,"prospectId","");a(this,"chatId",null);a(this,"conversationId",null);a(this,"widgetId","");a(this,"pkKey","");a(this,"chatInitialized",!1);a(this,"primaryColor","#000000");a(this,"secondaryColor","#111111");a(this,"gradient",null);a(this,"positionType","fixed");a(this,"position","bottom-right");a(this,"widgetIcon",null);a(this,"iconConfig",null);a(this,"chatWelcomeMessage",null);this.chatAdapter=new fe,this.processConfig(e)}initSessionManager(){const e=this.widgetId||this.agentId||"default";this.sessionManager=new R(e),this.sessionManager.on("tab_took_over",()=>{console.warn("[VaniraAI] Session taken over by another tab."),this.sessionActive=!1,this.showTabConflictBanner("taken_over")}),this.sessionManager.on("session_cleared",()=>{console.log("[VaniraAI] Session cleared externally.")});const i=this.sessionManager.claimSession();return this.sessionActive=i,i}restoreSessionMessages(){var l,r,h;const e=(l=this.sessionManager)==null?void 0:l.getSession();if(!e)return;const i=(h=(r=this.currentView)==null?void 0:r.getChatWindow)==null?void 0:h.call(r);if(!i)return;const s=e.messages.filter(c=>c.content.trim()!==""),n=`vanira_calls_${this.widgetId||this.agentId}`,o=JSON.parse(localStorage.getItem(n)||"[]");if(s.length===0&&o.length===0)return;i.clearMessages();const d=[...s.map((c,A)=>({type:"msg",role:c.role,content:c.content,ts:c.timestamp??A})),...o.map(c=>({type:"call",durationMs:c.durationMs,startedAt:c.startedAt,ts:c.startedAt}))];d.sort((c,A)=>c.ts-A.ts),d.forEach(c=>{c.type==="msg"?i.addMessage(c.role,c.content,c.ts):i.addCallRecord(c.durationMs,c.startedAt)}),console.log(`[VaniraAI] Restored ${s.length} messages + ${o.length} call records from session.`)}showTabConflictBanner(e){var i,s;this.root&&((i=this.root.querySelector(".vanira-tab-conflict-banner"))==null||i.remove(),e==="conflict"&&((s=this.sessionManager)==null||s.forceClaimSession(),this.sessionActive=!0,this.widgetMode.includes("chat")&&this.initializeChatSession(!1)))}playMessageSound(e){try{if(!Y.audioContext){const d=window.AudioContext||window.webkitAudioContext;if(!d)return;Y.audioContext=new d}const i=Y.audioContext;i.state==="suspended"&&i.resume().catch(()=>{});const s=i.createOscillator(),n=i.createGain();s.connect(n),n.connect(i.destination);const o=i.currentTime;e==="send"?(s.type="sine",s.frequency.setValueAtTime(300,o),s.frequency.exponentialRampToValueAtTime(500,o+.05),n.gain.setValueAtTime(0,o),n.gain.linearRampToValueAtTime(.1,o+.01),n.gain.exponentialRampToValueAtTime(.001,o+.1),s.start(o),s.stop(o+.1)):(s.type="sine",s.frequency.setValueAtTime(500,o),s.frequency.exponentialRampToValueAtTime(800,o+.1),n.gain.setValueAtTime(0,o),n.gain.linearRampToValueAtTime(.15,o+.02),n.gain.exponentialRampToValueAtTime(.001,o+.2),s.start(o),s.stop(o+.2))}catch(i){console.warn("[VaniraAI] Audio feedback failed",i)}}handleWelcomePayload(e,i="assistant"){var o,d,l,r,h,c,A,g;if(!e||this.widgetMode==="voice_only")return;e.buttons&&Array.isArray(e.buttons)?this.welcomeChipsData=e.buttons:((o=e.widget)==null?void 0:o.type)==="button_list"&&((d=e.widget.data)!=null&&d.buttons)&&(this.welcomeChipsData=e.widget.data.buttons),this.updateWelcomeChipsVisibility();const s=(r=(l=this.currentView)==null?void 0:l.getChatWindow)==null?void 0:r.call(l);let n=e.text||e.response||e.content||e.message||"";if(!n&&!this.welcomeChipsData.length&&(n="Hey! how can I help you ?"),!n&&typeof e=="string"&&e.trim().startsWith("{"))try{const p=JSON.parse(e);n=p.text||p.response||p.content||p.message||"",((h=p.widget)==null?void 0:h.type)==="button_list"&&((c=p.widget.data)!=null&&c.buttons)&&(this.welcomeChipsData=p.widget.data.buttons)}catch{}if(console.log("[VaniraAI] Processing Welcome Payload:",{hasText:!!n,chipsCount:this.welcomeChipsData.length,hasChatWindow:!!s,mode:this.widgetMode}),s){if(!n&&this.welcomeChipsData.length===0)return;const p=(A=this.sessionManager)==null?void 0:A.getSession();(p==null?void 0:p.messages.some(m=>m.content===n&&m.role===i))||(n&&(s.addMessage(i,n),(g=this.sessionManager)==null||g.pushMessage(i,n)),this.welcomeChipsData.length>0&&s.addButtons(this.welcomeChipsData))}}async initializeChatSession(e=!1){var i,s,n,o,d,l;if(this.sessionActive&&!this.chatInitialized){this.chatInitialized=!0;try{T.setChatUrl(this.chatServerUrl);const r=(i=this.sessionManager)==null?void 0:i.getSession();if(!e&&(r!=null&&r.prospectId)){this.prospectId=r.prospectId,this.chatId=r.chatId,this.conversationId=r.conversationId||null,console.log(`[VaniraAI] Session restored β tab: ${(s=this.sessionManager)==null?void 0:s.getTabId()}, prospect: ${this.prospectId}`),this.restoreSessionMessages(),this.chatId&&!this.eventSource&&(this.eventSource=T.listenForAdminReplies(this.chatId,this.prospectId,c=>{var A,g,p;(g=(A=this.currentView)==null?void 0:A.getChatWindow)==null||g.call(A).addMessage("assistant",c),(p=this.sessionManager)==null||p.pushMessage("assistant",c),this.playMessageSound("receive")}));return}this.prospectId||(this.prospectGroupId?this.prospectId=await T.createChatProspect(this.prospectGroupId):this.prospectId=`anon_${Date.now()}_${Math.random().toString(36).substr(2,9)}`);const h=await T.fetchWelcomeMessage(this.agentId,this.prospectId,this.widgetId||void 0,this.pkKey||void 0);h&&(this.handleWelcomePayload(h),h.chatId&&!this.chatId&&(this.chatId=h.chatId,this.eventSource||(this.eventSource=T.listenForAdminReplies(this.chatId,this.prospectId,c=>{var A,g,p;(g=(A=this.currentView)==null?void 0:A.getChatWindow)==null||g.call(A).addMessage("assistant",c),(p=this.sessionManager)==null||p.pushMessage("assistant",c),this.playMessageSound("receive")}))),h.conversationId&&(this.conversationId=h.conversationId)),(n=this.sessionManager)==null||n.saveIds(this.prospectId,this.chatId,this.conversationId)}catch(r){console.error("[VaniraAI] Chat init failed",r);const h="Hey! how can I help you ?";(d=(o=this.currentView)==null?void 0:o.getChatWindow)==null||d.call(o).addMessage("assistant",h),(l=this.sessionManager)==null||l.pushMessage("assistant",h)}}}async initialize(e){await super.initialize(e),this.processConfig(e),this.root&&this.ui_renderer(this.root)}processConfig(e){var i,s;if(this.widgetId=e.widgetId||e.widget_id||this.widgetId||"",this.agentId=e.agentId||e.agent_id||this.agentId||"",this.prospectGroupId=e.prospectGroupId||((i=e.client)==null?void 0:i.base_prospect_group_id)||this.prospectGroupId||"",this.widgetMode=e.widgetMode||e.mode||this.widgetMode||"voice_only",this.pkKey=e.pkKey||e.pk_key||e.publicKey||e.public_key||this.pkKey||"",this.primaryColor=e.primaryColor||e.primary_color||"#000000",this.secondaryColor=e.secondaryColor||e.secondary_color||"#111111",this.gradient=e.gradient||null,this.position=e.position||"bottom-right",this.positionType=e.positionType||"fixed",this.widgetIcon=e.widgetIcon||e.icon||null,this.iconConfig=e.iconConfig||e.icon_config||null,this.chatWelcomeMessage=e.chatWelcomeMessage||e.chat_welcome_message||((s=e.agent)==null?void 0:s.chat_welcome_message)||null,console.log("[VaniraAI] processConfig:",{hasPrimary:!!this.primaryColor,hasSecondary:!!this.secondaryColor,hasWelcome:!!this.chatWelcomeMessage}),typeof this.chatWelcomeMessage=="string")try{this.chatWelcomeMessage=JSON.parse(this.chatWelcomeMessage)}catch(n){console.warn("[VaniraAI] Failed to parse chatWelcomeMessage string",n)}this.chatServerUrl=e.serverUrl||e.chatServerUrl||"https://inboxapi.travelr.club",this.updateWelcomeChipsVisibility()}async create_call(e="continue"){var i,s,n;if(!(this.callActive||!this.agentId)){this.sessionActive||((i=this.sessionManager)==null||i.forceClaimSession(),this.sessionActive=!0);try{this.callActive=!0,this.updateViewCallState(!0),this.updateViewStatus("connecting");const o=((s=this.config)==null?void 0:s.serverUrl)||((n=this.config)==null?void 0:n.chatServerUrl),d=o&&!o.includes("travelr.club")?o:"https://api.vanira.io",l=new O({agentId:this.agentId,apiKey:this.pkKey||void 0,sessionBehavior:e,prospectId:this.prospectId||void 0,backendUrl:d});l.on("session_started",({prospectId:r})=>{var h;r&&(this.prospectId=r,(h=this.sessionManager)==null||h.saveIds(r,this.chatId))}),l.on("connected",()=>this.updateViewStatus("connected")).on("disconnected",()=>this.end_call()).on("error",r=>{console.error("[VaniraAI Widget] Call error:",r),this.updateViewStatus("error",r)}).on("transcription",({text:r,isFinal:h})=>{var c,A;(A=(c=this.currentView)==null?void 0:c.setTranscription)==null||A.call(c,r,h)}).on("track",({track:r})=>{var h;this.widgetMode.includes("avatar")&&r.kind==="video"&&((h=this.currentView)!=null&&h.setVideoTrack)&&this.currentView.setVideoTrack(r)}).on("tool_call",r=>{var A,g,p;if(console.log("[VaniraAI Widget] Tool call received:",r.name,r.arguments),(A=this.presetRenderer)==null?void 0:A.handle(r,x=>{var y,v;const m=r.arguments||r.args||{};let w=m;if(typeof m=="string")try{w=JSON.parse(m)}catch{}const f=((y=r.client_fields)==null?void 0:y.preset_id)||(w==null?void 0:w.preset_id),b=((v=r.client_fields)==null?void 0:v.action_name)||(f==="vanira_calendar"?"calendar_slot_selected":`user_submitted_${r.name}`);l.triggerInterrupt(b,x)},x=>{const m=r.tool_call_id;try{l.sendToolResult(m,{status:"cancelled",reason:"User dismissed"})}catch{}},l))return;const c=new CustomEvent("vaniraai:tool_call",{detail:r,bubbles:!0,composed:!0});(p=(g=this.root)==null?void 0:g.host)==null||p.dispatchEvent(c)}),this.vaniraClient=l,await l.start()}catch(o){console.error("[VaniraAI Widget] Call failed",o),this.updateViewStatus("error",(o==null?void 0:o.message)||String(o))}}}end_call(){var i;this.callActive=!1;const e=this.vaniraClient;this.vaniraClient=null,e&&e.stop(),(i=this.presetRenderer)==null||i.dismiss(),this.updateViewCallState(!1)}updateViewCallState(e){var i;(i=this.currentView)!=null&&i.setCallActive&&this.currentView.setCallActive(e)}updateViewStatus(e,i){var s;(s=this.currentView)!=null&&s.setStatus&&this.currentView.setStatus(e,i)}ui_renderer(e){var r,h,c;this.root=e,this.root.innerHTML="",this.presetRenderer=new ve(e),this.root.host&&(this.positionType==="fixed"?this.root.host.classList.add("vanira-portal"):this.root.host.classList.remove("vanira-portal"));const i=document.createElement("style");i.textContent=`@keyframes vanira-slide-up {
|
|
1453
1453
|
from { opacity:0; transform:translateY(16px); }
|
|
1454
1454
|
to { opacity:1; transform:translateY(0); }
|
|
1455
1455
|
}`,this.root.appendChild(i);const s=document.createElement("style");s.textContent=`
|