@eshal-bot/chat-widget 0.1.34 → 0.1.35
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/chat-widget.umd.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t(require("react"),require("react-dom/client"),require("react/jsx-runtime"),require("react-dom")):"function"==typeof define&&define.amd?define(["react","react-dom/client","react/jsx-runtime","react-dom"],t):(e="undefined"!=typeof globalThis?globalThis:e||self).ChatWidget=t(e.React,e.client,e.jsxRuntime,e.ReactDOM)}(this,function(e,t,n,r){"use strict";function a(e,t){return t.forEach(function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach(function(n){if("default"!==n&&!(n in e)){var r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,r.get?r:{enumerable:!0,get:function(){return t[n]}})}})}),Object.freeze(e)}function o(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function s(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?i(Object(n),!0).forEach(function(t){o(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):i(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function l(e,t){if(null==e)return{};var n,r,a=function(e,t){if(null==e)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(-1!==t.indexOf(r))continue;n[r]=e[r]}return n}(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(r=0;r<o.length;r++)n=o[r],-1===t.indexOf(n)&&{}.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}const c="processing_start",u="text_chunk",d="processing_end",p="complete",g="error",m="human_decision_required",f=e=>{if(!e||"string"!=typeof e)return null;if("[DONE]"===e||"[PROCESSING]"===e)return null;try{const n=JSON.parse(e);if(!n||"object"!=typeof n)return null;const r=n.type||n.event_type;if(r===u||n.content){var t;const e=n.content||(null===(t=n.choices)||void 0===t||null===(t=t[0])||void 0===t||null===(t=t.delta)||void 0===t?void 0:t.content)||"";return s({type:u,content:e},n)}return r===c||"processing_start"===n.type?s({type:c},n):r===d||"processing_end"===n.type?s({type:d},n):r===p||"complete"===n.type?s({type:p,finalContent:n.finalContent||n.content||""},n):r===g||"error"===n.type?s({type:g,error:n.error||n.message||"Unknown error"},n):r===m||"human_decision_required"===n.type?s({type:m,decisionId:n.decisionId||n.decision_id,question:n.question||"",options:n.options||[],context:n.context||{}},n):r?s({type:r},n):n}catch(e){return null}},h=["prompts"],b=()=>({id:"skeleton-".concat(Date.now()),role:"assistant",content:"",timestamp:new Date,isProcessing:!0}),y=e=>{if(!Array.isArray(e)||0===e.length)return;const t=e.map(e=>({type:e.type||"prompt",text:"string"==typeof e.text?e.text:"",confidence:"number"==typeof e.confidence?e.confidence:void 0})).filter(e=>e.text);return t.length?t:void 0},w=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};e(e=>{const r=[...e||[]],a=r[r.length-1];if("assistant"===(null==a?void 0:a.role)){const e=n||{},{prompts:o}=e,i=l(e,h);r[r.length-1]=s(s(s({},a),i),{},{content:t,isProcessing:!1},null!=o&&{prompts:y(o)})}return r})},E=(e,t,n,r,a)=>{var o;if(e&&e.type)switch(e.type){case c:break;case u:a.current||(a.current=!0,t(e=>{const t=e[e.length-1];if(!t||"assistant"!==t.role||!t.isProcessing){return[...e||[],b()]}return e}));const i=e.content||(null===(o=e.choices)||void 0===o||null===(o=o[0])||void 0===o||null===(o=o.delta)||void 0===o?void 0:o.content)||"";i&&(n.current+=i,r(n.current));break;case d:(e=>{e(e=>{const t=[...e||[]],n=t[t.length-1];return null!=n&&n.isProcessing&&(t[t.length-1]=s(s({},n),{},{isProcessing:!1})),t})})(t);break;case p:{const r=e.finalContent||n.current,a={};"boolean"==typeof e.conclusionDetected?a.conclusionDetected=e.conclusionDetected:"boolean"==typeof e.conclusion_detected&&(a.conclusionDetected=e.conclusion_detected);const o=s(s({},a),{},{prompts:e.prompts});w(t,r,o);break}case g:((e,t)=>{e(e=>{const n=[...e||[]],r=n[n.length-1];return"assistant"===(null==r?void 0:r.role)&&(n[n.length-1]=s(s({},r),{},{content:(r.content||"")+"\n\nError: ".concat(t),isProcessing:!1})),n})})(t,e.error||"Unknown error occurred");break;case m:{const n={id:"decision-".concat(Date.now()),role:"assistant",content:e.question||"",timestamp:new Date,isProcessing:!1,requiresDecision:!0,decisionData:{decisionId:e.decisionId,question:e.question,options:e.options||[],context:e.context||{}}};t(e=>[...(e||[]).filter(e=>!e.isProcessing||e.content),n]);break}default:console.warn("Unknown stream event type:",e.type)}},v=async(e,t)=>{const n=(e=>{let t=null,n=null,r=0;const a=o=>{if(o-r<16)n=requestAnimationFrame(a);else{if(null!==t){const n=t;t=null,r=o,e(e=>{const t=[...e||[]],r=t[t.length-1];return"assistant"===(null==r?void 0:r.role)&&(t[t.length-1]=s(s({},r),{},{content:n})),t})}n=null}};return e=>{t=e,null===n&&(n=requestAnimationFrame(a))}})(t),r=e.getReader(),a=new TextDecoder;let o="";const i={current:""},l={current:!1};try{for(;;){const{value:e,done:h}=await r.read();if(h)break;o+=a.decode(e,{stream:!0});const y=o.split(/\r?\n\r?\n/);o=y.pop()||"";for(const e of y){var c,u;const r=e.split(/\r?\n/).map(e=>e.trim()).filter(Boolean);if(0===r.length)continue;const a=r.filter(e=>e.startsWith("data:")).map(e=>e.slice(5).trim());if(0===a.length)continue;const o=a.join("\n");if("[DONE]"===o)continue;let h;try{h=JSON.parse(o)}catch(e){continue}if(h){if(h.type){if("processing_start"===h.type||"processing_end"===h.type)continue;if("text_chunk"===h.type){var d;const e=(null===(d=h.choices)||void 0===d||null===(d=d[0])||void 0===d||null===(d=d.delta)||void 0===d?void 0:d.content)||h.content;e&&(l.current||(l.current=!0,t(e=>{const t=e[e.length-1];if(!t||"assistant"!==t.role||!t.isProcessing){return[...e||[],b()]}return e})),i.current+=e,n(i.current));continue}if("complete"===h.type){var p,g,m;const e=null!==(p=null!==(g=h.Sources)&&void 0!==g?g:h.sources)&&void 0!==p?p:[],n=Array.isArray(e)?e.map(e=>{var t,n,r,a,o;return{source_type:null!==(t=null!==(n=e.source_type)&&void 0!==n?n:e.sourceType)&&void 0!==t?t:"website",source_id:null!==(r=e.sourceid)&&void 0!==r?r:e.source_id,source_name:null!==(a=null!==(o=e.source_name)&&void 0!==o?o:e.sourceName)&&void 0!==a?a:"",url:e.url}}).filter(e=>e.source_id||e.url):[],r=(null===(m=h.choices)||void 0===m||null===(m=m[0])||void 0===m||null===(m=m.delta)||void 0===m?void 0:m.content)||h.finalContent||i.current,a={};"boolean"==typeof h.conclusionDetected?a.conclusionDetected=h.conclusionDetected:"boolean"==typeof h.conclusion_detected&&(a.conclusionDetected=h.conclusion_detected);const o=s(s({},a),{},{prompts:h.prompts});w(t,r,o),n.length>0&&t(e=>{const t=[...e||[]],a=t[t.length-1];return"assistant"===(null==a?void 0:a.role)&&(t[t.length-1]=s(s({},a),{},{sources:n,content:r,isProcessing:!1})),t});continue}if("error"===h.type){t(e=>{const t=[...e||[]],n=t[t.length-1];return"assistant"===(null==n?void 0:n.role)&&(t[t.length-1]=s(s({},n),{},{content:(n.content||"")+"\n\nError: ".concat(h.error||"Unknown error occurred"),isProcessing:!1})),t});continue}const e=f(o);if(e&&e.type){console.log("🔍 Parsed stream event:",e.type,e),E(e,t,i,n,l);continue}}if("chat.completion.chunk"===h.object&&null!==(c=h.choices)&&void 0!==c&&null!==(c=c[0])&&void 0!==c&&null!==(c=c.delta)&&void 0!==c&&c.content)l.current||(l.current=!0,t(e=>{const t=e[e.length-1];if(!t||"assistant"!==t.role||!t.isProcessing){return[...e||[],b()]}return e})),i.current+=h.choices[0].delta.content,n(i.current);else if(null!==(u=h.choices)&&void 0!==u&&null!==(u=u[0])&&void 0!==u&&u.finish_reason&&null!==h.choices[0].finish_reason){const e={prompts:h.prompts};w(t,i.current,e)}}}}}finally{r.releaseLock()}};async function S(e){if("undefined"==typeof window)throw new Error("Audio recorder can only run in the browser");const t=new AudioContext({sampleRate:16e3}),n=new Blob(["\n class PCMRecorderProcessor extends AudioWorkletProcessor {\n process(inputs) {\n if (!inputs.length || !inputs[0].length) {\n return true;\n }\n const inputChannel = inputs[0][0];\n this.port.postMessage(new Float32Array(inputChannel));\n return true;\n }\n }\n registerProcessor('pcm-recorder-processor', PCMRecorderProcessor);\n "],{type:"application/javascript"}),r=URL.createObjectURL(n);await t.audioWorklet.addModule(r),URL.revokeObjectURL(r);const a=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1}}),o=t.createMediaStreamSource(a),i=new AudioWorkletNode(t,"pcm-recorder-processor");return i.port.onmessage=t=>{const n=function(e){const t=new Int16Array(e.length);for(let n=0;n<e.length;n+=1)t[n]=Math.max(-1,Math.min(1,e[n]))*T;return t.buffer}(t.data);e(n)},o.connect(i),[i,t,a]}function k(e){e&&e.getTracks().forEach(e=>e.stop())}const T=32767;const A=e=>e.replace(/([\u3000-\u303f\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uff00-\uffef])\s+([\u3000-\u303f\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uff00-\uffef])/g,"$1$2"),x=e=>{const t=(e||"").trim();return t?/^https?:\/\//i.test(t)||/^[a-z][a-z0-9+.-]*:/i.test(t)?t:"https://".concat(t.replace(/^\/+/,"")):""},C=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return t.filter(Boolean).join(" ")},R={fullname:0,name:0,username:0,email:1,phone:2,mobileno:2},I=e=>{var t;if(!e)return 99;const n=String(e).toLowerCase();return null!==(t=R[n])&&void 0!==t?t:99},N="eshal_chat_session",_=(e,t)=>{if(null==e||!t)return null;const n={MINUTES:6e4,HOURS:36e5,DAYS:864e5}[t.toUpperCase()];return void 0===n?(console.warn("[Session] Unknown timeout unit: ".concat(t)),null):Number(e)*n},O=e=>{try{const t=localStorage.getItem("".concat(N,"_").concat(e));return t?JSON.parse(t):null}catch(e){return null}},L=(e,t,n)=>{if(!e||!e.lastActivity)return!1;if(null==t||0===t)return!0;if(null!==t&&null!==n){const r=JSON.stringify({value:t,unit:null==n?void 0:n.toUpperCase()});if(e.settingsSnapshot&&e.settingsSnapshot!==r)return console.log("[Session] Timeout settings changed — treating session as invalid."),!1}if(null===e.firstInteractionAt)return!0;const r=_(t,n);if(!r)return!0;const a=new Date(e.lastActivity).getTime(),o=Date.now()-a,i=o<r;return i||console.log("[Session] Session expired. Elapsed: ".concat(Math.floor(o/1e3),"s, Timeout: ").concat(Math.floor(r/1e3),"s")),i},D=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};try{const r=(new Date).toISOString();console.log("[Session] Saving new session: ".concat(t," for org: ").concat(e)),localStorage.setItem("".concat(N,"_").concat(e),JSON.stringify(s({conversationId:t,lastActivity:r,createdAt:r,firstInteractionAt:null},n)))}catch(e){}},P=e=>{try{const t=O(e);if(!t)return;const n=(new Date).toISOString();t.lastActivity=n,t.firstInteractionAt||(t.firstInteractionAt=n),localStorage.setItem("".concat(N,"_").concat(e),JSON.stringify(t))}catch(e){}},M=e=>{try{const t=O(e);if(!t)return;t.csatSubmitted=!0,localStorage.setItem("".concat(N,"_").concat(e),JSON.stringify(t))}catch(e){}},F=(e,t)=>{try{if(!e)return;if(!Array.isArray(t)||0===t.length)return void localStorage.removeItem("".concat(N,"_prompts_").concat(e));localStorage.setItem("".concat(N,"_prompts_").concat(e),JSON.stringify(t))}catch(e){}},B=e=>{let{id:t,role:n,content:r,isProcessing:a=!1,metadata:o}=e;return{id:t,role:n,content:r,timestamp:new Date,isProcessing:a,metadata:o}},U=e=>e&&e.length>0?e:[],z=t=>{let{welcomeMessage:n,quickQuestions:r=[],apiBaseUrl:a,wsBaseUrl:o,apiKey:i,organizationId:l,autoOpen:c,openDelay:u,darkMode:d,enableVoiceInteraction:p=!1,onboardingQuestions:g=[],onboardingEnabled:m=!1,collectionPrompt:f,inactivityTimeoutValue:h,inactivityTimeoutUnit:b}=t;const[y,w]=e.useState(c),[E,T]=e.useState(!1),[x,C]=e.useState(d),[R,M]=e.useState(()=>{try{const e=O(l);if(void 0!==h&&e&&L(e,h,b))return[]}catch(e){}return n?[s(s({},B({id:Date.now().toString(),role:"assistant",content:n})),{},{isWelcome:!0})]:[]}),[z,j]=e.useState(""),[G,$]=e.useState(!1),q=e.useRef(null),V=e.useRef(1),[H,W]=e.useState(!1),[Y,K]=e.useState(()=>{try{const e=O(l);if(e&&e.onboardingCompleted)return!0}catch(e){}return!1}),[Z,X]=e.useState(null),[Q,J]=e.useState({}),ee=e.useRef(!1),[te,ne]=e.useState(!1),[re,ae]=e.useState(!1),[oe,ie]=e.useState([]),[se,le]=e.useState("idle"),[ce,ue]=e.useState(null),[de,pe]=e.useState(!1),[ge,me]=e.useState(()=>{try{const e=O(l);if(void 0!==h&&e&&L(e,h,b))return e.conversationId}catch(e){}return"widget-session-".concat(Math.random().toString(36).slice(2,9))}),fe=e.useRef(null),he=e.useRef(null),be=e.useRef(null),ye=e.useRef(null),we=e.useRef(null),Ee=e.useRef(null),ve=e.useRef(null),Se=e.useRef(null),ke=e.useRef(!1),Te=e.useRef(!1);e.useRef(null);const Ae=e.useRef(null);e.useRef(null);const xe=e.useRef(!1),Ce=e.useRef(null),Re=e.useRef(!1),Ie=e.useRef(!1),Ne=e.useRef(null),_e=e.useRef(null),Oe=e.useMemo(()=>{if(!l)return null;const e=((e,t)=>{if(t)return t.replace(/\/$/,"");if(!e)return"wss://dev.eshal.ai/knowledge-api/ws";try{const t=new URL(e);return t.protocol=t.protocol.replace(/^http/,"ws"),t.pathname="/knowledge-api/ws",t.toString().replace(/\/$/,"")}catch(e){return console.error("Invalid API base URL provided for WebSocket:",e),"wss://dev.eshal.ai/knowledge-api/ws"}})(a,o);return"".concat(e,"/").concat(l,"/").concat(ge)},[a,l,ge]),Le=e.useCallback(()=>{const e="msg-".concat(V.current);return V.current+=1,e},[]);e.useEffect(()=>{if(c&&u>0){const e=setTimeout(()=>w(!0),u);return()=>clearTimeout(e)}},[c,u]),e.useEffect(()=>{C(d)},[d]);const De=e.useRef(!1),Pe=e.useRef(!1),Me=e.useRef(!1),Fe=e.useRef({value:null,unit:null});e.useEffect(()=>{if(!l||!ge||void 0===h)return;const e=O(l);if(e&&L(e,h,b)){if(ge!==e.conversationId)return void me(e.conversationId);!De.current&&a&&(De.current=!0,ne(!0),(async(e,t,n)=>{if(!e||!t||!n)throw new Error("apiBaseUrl, orgId, and conversationId are required");const r="".concat(e.replace(/\/$/,""),"/api/v1/conversations/").concat(t,"/").concat(n),a=await fetch(r,{method:"GET",headers:{"Content-Type":"application/json"},credentials:"include"});if(404===a.status)return[];if(!a.ok)throw new Error("HTTP error! status: ".concat(a.status));return(await a.json()).messages||[]})(a,l,ge).then(e=>{const t=["userName","email","phone","fullname","mobileno","name"],r=e.filter(e=>{const n=e.type||e.messageType;return!n||!t.includes(n)});if(r.length>0){Pe.current=!0;const e=r.map((e,t)=>{var n;const r=null!==(n=e.Sources)&&void 0!==n?n:e.sources,a=Array.isArray(r)?r.map(e=>{var t,n,r,a,o;return{source_type:null!==(t=null!==(n=e.source_type)&&void 0!==n?n:e.sourceType)&&void 0!==t?t:"website",source_id:null!==(r=e.source_id)&&void 0!==r?r:e.sourceid,source_name:null!==(a=null!==(o=e.source_name)&&void 0!==o?o:e.sourceName)&&void 0!==a?a:"",url:e.url}}).filter(e=>e.source_id||e.url):[];return s(s(s({},B({id:e.id||"history-".concat(t,"-").concat(Date.now()),role:e.role||("user"===e.sender?"user":"assistant"),content:e.message||e.content||""})),{},{timestamp:e.time?new Date(e.time):new Date},Array.isArray(e.prompts)&&e.prompts.length>0?{prompts:e.prompts}:{}),a.length>0?{sources:a}:{})});if(!e.some(e=>"assistant"===e.role&&Array.isArray(e.prompts)&&e.prompts.length>0)){const t=(e=>{try{const t=localStorage.getItem("".concat(N,"_prompts_").concat(e));return t&&JSON.parse(t)||[]}catch(e){return[]}})(l);if(t.length>0)for(let n=e.length-1;n>=0;n-=1)if("assistant"===e[n].role){e[n]=s(s({},e[n]),{},{prompts:t});break}}if(n){var a;const t=null===(a=e[0])||void 0===a?void 0:a.timestamp,r=t instanceof Date?t.getTime():t?new Date(t).getTime():Date.now(),o=s(s({},B({id:"welcome-restored",role:"assistant",content:n})),{},{isWelcome:!0,timestamp:new Date(r-1)});M([o,...e])}else M(e)}}).catch(e=>{console.error("[Session] History fetch failed:",e)}).finally(()=>{ne(!1)}))}else if(De.current||(De.current=!0),e&&ge===e.conversationId){const e="widget-session-".concat(Math.random().toString(36).slice(2,9));console.warn("[Session] Rotating expired ID ".concat(ge," -> ").concat(e)),me(e)}else e&&e.conversationId===ge||D(l,ge,{settingsSnapshot:JSON.stringify({value:h,unit:null==b?void 0:b.toUpperCase()})})},[l,ge,a,h,b]),e.useEffect(()=>{if(l&&R&&0!==R.length)for(let e=R.length-1;e>=0;e-=1){const t=R[e];if("assistant"===(null==t?void 0:t.role)&&Array.isArray(t.prompts)&&t.prompts.length>0)return void F(l,t.prompts)}},[R,l]),e.useEffect(()=>{if(!m||Y)return;U(g).length>0&&W(!0)},[m,Y,g]),e.useEffect(()=>{n&&!Pe.current&&M(e=>{if(!e.length)return[s(s({},B({id:Date.now().toString(),role:"assistant",content:n})),{},{isWelcome:!0})];const[t,...r]=e;return t.isWelcome?[s(s({},t),{},{content:n}),...r]:e})},[n]),e.useCallback(e=>{M(t=>t.map(t=>t.id===e.id?s(s({},t),e.update(t)):t))},[]);const Be=e.useCallback(async(e,t)=>{const n=e.trim();if(!n)return{success:!1,error:"Message cannot be empty"};if(!a)return M(e=>[...e||[],B({id:Le(),role:"assistant",content:"Sorry, I'm having trouble connecting right now. Please try again.",isProcessing:!1})]),console.error("Chat widget configuration error: apiBaseUrl is required for streaming."),{success:!1,error:"API base URL is required"};const r=["inquiry","complaint","technical","userName","email","phone","fullname","mobileno"];let o="inquiry";if(t){const e=t.toLowerCase();"fullname"===e||"name"===e?o="userName":"email"===e?o="email":"phone"===e||"mobileno"===e?o="phone":r.includes(e)&&(o=e)}if("inquiry"===o||"complaint"===o||"technical"===o){const e=B({id:Le(),role:"user",content:n});M(t=>[...(t||[]).map(e=>{var t;return"assistant"===e.role&&null!==(t=e.prompts)&&void 0!==t&&t.length?s(s({},e),{},{prompts:void 0}):e}),e]),j(""),$(!0)}else j("");try{const e={message:n,type:o,conversationId:ge,channel:"widget",messageHistory:R.filter(e=>!e.isProcessing&&e.content&&e.content.trim()&&!["userName","email","phone"].includes(e.type)).map(e=>{let t;return t=e.timestamp instanceof Date?e.timestamp.toISOString():"string"==typeof e.timestamp?e.timestamp:e.timestamp?new Date(e.timestamp).toISOString():(new Date).toISOString(),{id:e.id,role:e.role,content:e.content,timestamp:t,isProcessing:!1}})},t=await(async(e,t,n)=>{const r={"Content-Type":"application/json",Accept:"text/event-stream"};n&&(r["x-eshal-org"]=n);const a=await fetch("".concat(t.replace(/\/$/,""),"/api/v1/support"),{method:"POST",headers:r,credentials:"include",body:JSON.stringify(e)});if(!a.ok)throw new Error("HTTP error! status: ".concat(a.status));if(!a.body)throw new Error("Response body is null");return a.body})(e,a,l);if("userName"===o||"email"===o||"phone"===o){const e=t.getReader(),n=new TextDecoder;for(;;){const{done:t,value:r}=await e.read();if(t)break;n.decode(r)}return{success:!0}}return"inquiry"===o||"complaint"===o||"technical"===o?(await v(t,M),P(l),{success:!0}):(P(l),{success:!0})}catch(e){return console.error("Error sending message:",e),"inquiry"!==o&&"complaint"!==o&&"technical"!==o||($(!1),M(e=>[...(e||[]).filter(e=>!e.isProcessing),B({id:Le(),role:"assistant",content:"Sorry, I'm having trouble connecting right now. Please try again.",isProcessing:!1})])),{success:!1,error:e instanceof Error?e.message:"Failed to send message"}}finally{"inquiry"!==o&&"complaint"!==o&&"technical"!==o||$(!1)}},[a,i,Le,l,R,ge]),Ue=e.useCallback(async e=>{const t=U(g);if(0===t.length)return;const n=[...t].sort((e,t)=>I(e.fieldType)-I(t.fieldType));for(const t of n){var r;const n=t.fieldType||"question",a=(null!==(r=e[n])&&void 0!==r?r:"").trim();if(!a)continue;const o=await Be(a,n);if(null==o||!o.success){const e=B({id:Le(),role:"assistant",content:(null==o?void 0:o.error)||"Something went wrong. Please try again.",isProcessing:!1});return void M(t=>[...t,e])}}W(!1),K(!0),(e=>{try{const t=O(e);if(!t)return;t.onboardingCompleted=!0,localStorage.setItem("".concat(N,"_").concat(e),JSON.stringify(t))}catch(e){}})(l),J(t=>s(s({},t),e)),Z&&!ee.current&&(ee.current=!0,setTimeout(()=>{j(Z),X(null)},500))},[g,Be,Le,Z,l]),ze=e.useCallback(async()=>{const e=z.trim();e&&await Be(e)},[z,Be]),je=e.useCallback(async()=>{await ze()},[ze]),Ge=e.useCallback(async e=>{const t=null==e?void 0:e.trim();t&&await Be(t)},[Be]),$e=e.useCallback(async(e,t,n)=>{if(M(t=>t.filter(t=>{var n;return(null===(n=t.decisionData)||void 0===n?void 0:n.decisionId)!==e})),"connect_agent"===n){const e=B({id:Le(),role:"assistant",content:"Great! I'm setting up a connection with a live customer service agent. Please hold on for a moment while I transfer you."});M(t=>[...t,e])}else if("decline"===n){const e=B({id:Le(),role:"assistant",content:"I understand. I apologize that I don't have specific information about your query in my knowledge base. Is there anything else I can help you with?"});M(t=>[...t,e])}},[Le]);e.useCallback(()=>{ve.current&&(ie(e=>e.map(e=>e.id===ve.current?s(s({},e),{},{isProcessing:!1}):e)),ve.current=null)},[]);const qe=e.useCallback(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(Re.current=!0,!e||"string"==typeof e&&!e.trim())return void(t&&ve.current&&(ie(e=>e.map(e=>e.id===ve.current?s(s({},e),{},{isProcessing:!1}):e)),ve.current=null));const n=A(e);ie(e=>{const r=e.length;let a=[...e];if(ve.current){if(a.some(e=>e.id===ve.current))a=a.map(e=>{if(e.id!==ve.current)return e;const r=A("".concat(e.content||"").concat(n));return s(s({},e),{},{content:r,isProcessing:!t,metadata:s(s({},e.metadata),{},{transcriptionType:"input"})})});else{console.error("[BIDI] appendUserTranscription: ERROR - user message not found!",{expectedId:ve.current,existingIds:a.map(e=>e.id)});const e="bidi-input-".concat(Date.now());ve.current=e;const r=B({id:e,role:"user",content:n,isProcessing:!t,metadata:{source:"bidi",transcriptionType:"input"}});a=[...a,r],console.log("[BIDI] appendUserTranscription: recreated lost user message",{messageId:e})}}else{const r="bidi-input-".concat(Date.now()),o=Date.now(),i=e.filter(e=>{var t;return"assistant"===e.role&&"bidi"===(null===(t=e.metadata)||void 0===t?void 0:t.source)}).sort((e,t)=>{const n=e.timestamp instanceof Date?e.timestamp.getTime():new Date(e.timestamp).getTime();return(t.timestamp instanceof Date?t.timestamp.getTime():new Date(t.timestamp).getTime())-n})[0];let l;if(i){const e=i.timestamp instanceof Date?i.timestamp.getTime():new Date(i.timestamp).getTime();l=new Date(e-1)}else l=new Date(o);const c=B({id:r,role:"user",content:n,isProcessing:!t,timestamp:l,metadata:{source:"bidi",transcriptionType:"input"}});a.some(e=>e.id===r)?(console.warn("[BIDI] appendUserTranscription: message already exists, updating instead",{messageId:r}),ve.current=r,a=a.map(e=>e.id===r?s(s({},e),{},{content:"".concat(e.content||"").concat(n),isProcessing:!t}):e)):(a=[...a,c],ve.current=r)}return a.length<r?(console.error("[BIDI] appendUserTranscription: CRITICAL ERROR - losing messages!",{prevLength:r,resultLength:a.length,prevIds:e.map(e=>{var t;return{id:e.id,role:e.role,content:null===(t=e.content)||void 0===t?void 0:t.substring(0,30)}}),resultIds:a.map(e=>{var t;return{id:e.id,role:e.role,content:null===(t=e.content)||void 0===t?void 0:t.substring(0,30)}})}),e):a}),t&&(ve.current=null,$(!0))},[]),Ve=e.useCallback(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if($(!1),console.log("[BIDI] appendAssistantContent called",{text:null==e?void 0:e.substring(0,50),finished:t,currentAssistantId:Se.current,currentInputId:ve.current}),!e||"string"==typeof e&&!e.trim())return console.log("[BIDI] appendAssistantContent: skipping empty text"),void(t&&Se.current&&(ie(e=>e.map(e=>e.id!==Se.current?e:s(s({},e),{},{isProcessing:!1}))),Se.current=null,Ae.current=null));const n="".concat(Se.current||"new","-").concat(e.substring(0,100),"-").concat(t);if(xe.current&&Ce.current===n)return;xe.current=!0,Ce.current=n;const r=ve.current;if(ie(n=>{const a=n.length;let o=[...n];if(console.log("[BIDI] appendAssistantContent: starting update",{prevLength:a,prevMessageIds:n.map(e=>e.id),inputMessageIdToFinalize:r,currentAssistantId:Se.current,textLength:e.length}),r){o.some(e=>e.id===r)?o=o.map(e=>e.id===r?s(s({},e),{},{isProcessing:!1}):e):console.warn("[BIDI] appendAssistantContent: input message not found for finalization",{inputMessageId:r,existingIds:o.map(e=>e.id)})}if(Se.current){if(o.some(e=>e.id===Se.current))o=o.map(n=>{var r;if(n.id!==Se.current)return n;const a="".concat(n.content||"").concat(e);return console.log("[BIDI] appendAssistantContent: updating existing message",{messageId:n.id,oldContentLength:(null===(r=n.content)||void 0===r?void 0:r.length)||0,newContentLength:a.length,textLength:e.length}),s(s({},n),{},{content:a,isProcessing:!t},Array.isArray(_e.current)&&_e.current.length>0?{sources:_e.current}:{})}),Array.isArray(_e.current)&&_e.current.length>0&&(_e.current=null);else{console.error("[BIDI] appendAssistantContent: ERROR - assistant message not found!",{expectedId:Se.current,existingIds:o.map(e=>e.id)});const n="bidi-assistant-".concat(Date.now());Se.current=n;const r=B({id:n,role:"assistant",content:e,isProcessing:!t,metadata:{source:"bidi"}});Array.isArray(_e.current)&&_e.current.length>0&&(r.sources=_e.current,_e.current=null),o=[...o,r],console.log("[BIDI] appendAssistantContent: recreated lost assistant message",{messageId:n})}}else{const n="bidi-assistant-".concat(Date.now()),a=Date.now(),i=r?new Date(a):new Date(a+1e3),l=B({id:n,role:"assistant",content:e,isProcessing:!t,timestamp:i,metadata:{source:"bidi"}});Array.isArray(_e.current)&&_e.current.length>0&&(l.sources=_e.current,_e.current=null);o.some(e=>e.id===n)?(console.error("[BIDI] appendAssistantContent: ERROR - message ID collision!",{messageId:n,existingIds:o.map(e=>e.id)}),o=o.map(r=>r.id===n?s(s({},r),{},{content:"".concat(r.content||"").concat(e),isProcessing:!t},Array.isArray(_e.current)&&_e.current.length>0?{sources:_e.current}:{}):r),Array.isArray(_e.current)&&_e.current.length>0&&(_e.current=null),Se.current=n):(o=[...o,l],Se.current=n)}return console.log("[BIDI] appendAssistantContent: atomic state update complete",{prevLength:a,newLength:o.length,finished:t,messageIds:o.map(e=>e.id),messageRoles:o.map(e=>e.role)}),o.length<a?(console.error("[BIDI] appendAssistantContent: CRITICAL ERROR - losing messages!",{prevLength:a,resultLength:o.length,prevIds:n.map(e=>{var t;return{id:e.id,role:e.role,content:null===(t=e.content)||void 0===t?void 0:t.substring(0,30)}}),resultIds:o.map(e=>{var t;return{id:e.id,role:e.role,content:null===(t=e.content)||void 0===t?void 0:t.substring(0,30)}})}),n):o}),r&&(ve.current=null),t)console.log("[BIDI] appendAssistantContent: finalizing message",{messageId:Se.current}),Se.current=null,Ae.current=null;else{const e=updateKey;Promise.resolve().then(()=>{Ae.current===e&&(Ae.current=null)})}},[]),He=e.useCallback(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(console.log("[BIDI] handleContentParts called",{partsCount:null==e?void 0:e.length,finished:t,audioOnly:n}),!e||!Array.isArray(e))return void console.warn("[BIDI] handleContentParts: invalid parts",e);let r="";e.forEach((e,t)=>{var a,o;null!==(a=e.inlineData)&&void 0!==a&&a.data&&null!==(o=e.inlineData.mimeType)&&void 0!==o&&o.startsWith("audio/pcm")&&(console.log("[BIDI] handleContentParts: sending audio data to player"),he.current?he.current.port.postMessage((e=>{if("undefined"==typeof window)return new ArrayBuffer(0);let t=e.replace(/-/g,"+").replace(/_/g,"/");for(;t.length%4!=0;)t+="=";const n=window.atob(t),r=n.length,a=new Uint8Array(r);for(let e=0;e<r;e+=1)a[e]=n.charCodeAt(e);return a.buffer})(e.inlineData.data)):console.warn("[BIDI] handleContentParts: audioPlayerNodeRef is null")),!n&&e.text&&(r+=e.text,console.log("[BIDI] handleContentParts: accumulated text part",{text:e.text.substring(0,50),index:t,totalAccumulated:r.length}))}),r&&(console.log("[BIDI] handleContentParts: calling appendAssistantContent once",{textLength:r.length,finished:t}),Ve(r,t))},[Ve]),We=e.useCallback(()=>{$(!1),console.log("[BIDI] handleTurnComplete called",{currentAssistantId:Se.current,currentInputId:ve.current}),ie(e=>{const t=e.map(e=>{var t;return"bidi"===(null===(t=e.metadata)||void 0===t?void 0:t.source)&&e.isProcessing?s(s({},e),{},{isProcessing:!1}):e});return console.log("[BIDI] handleTurnComplete: state update",{prevLength:e.length,newLength:t.length,finalizedCount:e.filter(e=>{var t;return"bidi"===(null===(t=e.metadata)||void 0===t?void 0:t.source)&&e.isProcessing}).length}),t}),Se.current=null,ve.current=null,Ie.current=!1,_e.current=null},[]),Ye=e.useCallback(()=>{$(!1),he.current&&he.current.port.postMessage({command:"endOfAudio"}),Se.current=null,ve.current=null,_e.current=null,ie(e=>e.map(e=>{var t;return"bidi"===(null===(t=e.metadata)||void 0===t?void 0:t.source)?s(s({},e),{},{isProcessing:!1,metadata:s(s({},e.metadata),{},{interrupted:!0})}):e}))},[]),Ke=e.useCallback(()=>{var e,t,n,r;ae(!1),$(!1),Te.current=!1,le("idle"),ue(null),Re.current=!1,_e.current=null,fe.current&&fe.current.readyState===WebSocket.OPEN&&fe.current.close(),fe.current=null,null===(e=he.current)||void 0===e||e.disconnect(),null===(t=be.current)||void 0===t||t.close(),he.current=null,be.current=null,null===(n=ye.current)||void 0===n||n.disconnect(),null===(r=we.current)||void 0===r||r.close(),ye.current=null,we.current=null,k(Ee.current),Ee.current=null,ke.current=!1},[]),Ze=e.useCallback(e=>{var t,n,r,a,o;if(console.log("[BIDI] handleBidiEvent called",{event:e,isVoiceSessionActive:Te.current,hasTurnComplete:!(null==e||!e.turnComplete),hasInterrupted:!(null==e||!e.interrupted),hasInputTranscription:!(null==e||!e.inputTranscription),hasOutputTranscription:!(null==e||!e.outputTranscription),hasContentParts:!(null==e||null===(t=e.content)||void 0===t||!t.parts)}),!e)return void console.warn("[BIDI] handleBidiEvent: received null/undefined event");const i=null!==(n=e.conclusion_detected)&&void 0!==n?n:e.conclusionDetected;var c;"boolean"==typeof i&&i&&(null===(c=Ne.current)||void 0===c||c.call(Ne),pe(!0));if("boolean"==typeof i&&i)return Ke(),void ie(e=>{const t=[...e];for(let e=t.length-1;e>=0;e--)if("assistant"===t[e].role){t[e]=s(s({},t[e]),{},{conclusionDetected:!0});break}return t});if(e.interrupted)return console.log("[BIDI] handleBidiEvent: processing interrupted"),void Ye();if(e.inputTranscription){const t=e.inputTranscription.text||"",n=Boolean(e.inputTranscription.finished);console.log("[BIDI] handleBidiEvent: processing inputTranscription",{text:t.substring(0,50),textLength:t.length,finished:n,hasText:!!t}),t||n?(P(l),qe(t,n)):console.warn("[BIDI] handleBidiEvent: inputTranscription event has no text and not finished",e.inputTranscription)}const u=null!==(r=e.sources)&&void 0!==r?r:e.Sources;if(Array.isArray(u)&&u.length>0){const e=u.map(e=>{var t,n,r,a,o,i;return{source_type:null!==(t=null!==(n=e.source_type)&&void 0!==n?n:e.sourceType)&&void 0!==t?t:"file",source_id:null!==(r=null!==(a=e.source_id)&&void 0!==a?a:e.sourceid)&&void 0!==r?r:e.sourceId,source_name:null!==(o=null!==(i=e.source_name)&&void 0!==i?i:e.sourceName)&&void 0!==o?o:"",url:e.url}}).filter(e=>e.source_id||e.url);if(0===e.length)return;ie(t=>{const n=[...t];let r=!1;for(let t=n.length-1;t>=0;t--)if("assistant"===n[t].role){n[t]=s(s({},n[t]),{},{sources:e}),r=!0;break}return r||(_e.current=e),n})}var d,p;if(!Re.current&&(null!==(d=e.outputTranscription)&&void 0!==d&&d.text||null!==(p=e.content)&&void 0!==p&&p.parts))return void(e.turnComplete&&We());if(null!==(a=e.outputTranscription)&&void 0!==a&&a.text&&(Ie.current=!0,Ve(e.outputTranscription.text,Boolean(e.outputTranscription.finished))),null!==(o=e.content)&&void 0!==o&&o.parts){var g;const t=(null===(g=e.content)||void 0===g?void 0:g.finished)||e.finished||!1;He(e.content.parts,t,Ie.current)}if(e.prompts&&Array.isArray(e.prompts)&&e.prompts.length>0){console.log("[BIDI] handleBidiEvent: attaching prompts to last assistant message",{count:e.prompts.length}),ie(t=>{const n=[...t];for(let t=n.length-1;t>=0;t--)if("assistant"===n[t].role){n[t]=s(s({},n[t]),{},{prompts:e.prompts});break}return n});try{F(l,e.prompts)}catch(e){}}e.turnComplete?We():e.interrupted||e.inputTranscription||e.outputTranscription||e.content||e.prompts||console.warn("[BIDI] handleBidiEvent: event had no recognized fields",e)},[Ve,qe,He,Ye,We,Ke]),Xe=e.useCallback(e=>{const t=fe.current;Te.current&&t&&t.readyState===WebSocket.OPEN&&t.send(e)},[]),Qe=e.useCallback(async()=>{if(!ke.current&&"undefined"!=typeof window)try{const[e,t]=await async function(){if("undefined"==typeof window)throw new Error("Audio player can only be initialized in the browser");const e=new AudioContext({sampleRate:24e3}),t=new Blob(["\n class PCMPlayerProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n this.bufferSize = 24000 * 180;\n this.buffer = new Float32Array(this.bufferSize);\n this.writeIndex = 0;\n this.readIndex = 0;\n this.port.onmessage = (event) => {\n if (event.data?.command === 'endOfAudio') {\n this.readIndex = this.writeIndex;\n return;\n }\n const int16Samples = new Int16Array(event.data);\n this.enqueue(int16Samples);\n };\n }\n\n enqueue(samples) {\n for (let i = 0; i < samples.length; i += 1) {\n const floatVal = samples[i] / 32768;\n this.buffer[this.writeIndex] = floatVal;\n this.writeIndex = (this.writeIndex + 1) % this.bufferSize;\n if (this.writeIndex === this.readIndex) {\n this.readIndex = (this.readIndex + 1) % this.bufferSize;\n }\n }\n }\n\n process(inputs, outputs) {\n const output = outputs[0];\n const framesPerBlock = output[0].length;\n for (let frame = 0; frame < framesPerBlock; frame += 1) {\n output[0][frame] = this.buffer[this.readIndex];\n if (output.length > 1) {\n output[1][frame] = this.buffer[this.readIndex];\n }\n if (this.readIndex !== this.writeIndex) {\n this.readIndex = (this.readIndex + 1) % this.bufferSize;\n }\n }\n return true;\n }\n }\n\n registerProcessor('pcm-player-processor', PCMPlayerProcessor);\n "],{type:"application/javascript"}),n=URL.createObjectURL(t);await e.audioWorklet.addModule(n);const r=new AudioWorkletNode(e,"pcm-player-processor");return r.connect(e.destination),URL.revokeObjectURL(n),[r,e]}();he.current=e,be.current=t,await t.resume();const[n,r,a]=await S(Xe);ye.current=n,we.current=r,Ee.current=a,await r.resume(),ke.current=!0}catch(e){throw console.error("Failed to initialize audio pipeline",e),e}},[Xe]),Je=e.useCallback(()=>{if("undefined"!=typeof window&&Oe&&(!fe.current||fe.current.readyState!==WebSocket.OPEN)){le("connecting"),ue(null);try{const e=new WebSocket(Oe);fe.current=e,e.onopen=()=>{le("connected")},e.onmessage=e=>{try{var t,n;const r="string"==typeof e.data?e.data.substring(0,200):"binary";console.log("[BIDI] WebSocket message received",{dataLength:null===(t=e.data)||void 0===t?void 0:t.length,dataPreview:r});const a=JSON.parse(e.data);console.log("[BIDI] WebSocket message parsed",{hasTurnComplete:!!a.turnComplete,hasInterrupted:!!a.interrupted,hasInputTranscription:!!a.inputTranscription,hasOutputTranscription:!!a.outputTranscription,hasContentParts:!(null===(n=a.content)||void 0===n||!n.parts),payload:a}),Ze(a)}catch(t){console.error("[BIDI] Failed to parse WebSocket event",{error:t,data:e.data})}},e.onerror=()=>{le("error"),ue("Voice session connection error"),$(!1)},e.onclose=()=>{fe.current=null,le("idle"),$(!1),Te.current&&setTimeout(()=>{Je()},5e3)}}catch(e){console.error("Failed to open voice websocket",e),le("error"),ue(e instanceof Error?e.message:"Unable to start voice session")}}},[Ze,Oe]),et=e.useCallback(async()=>{if(p&&l){ue(null),le(e=>"connected"===e?e:"connecting"),ae(!0),Te.current=!0,pe(!1),Re.current=!1,ie(e=>{if(e.length>0||R.length>0)return e;if(!n||""===n.trim())return[];return[B({id:"bidi-welcome-".concat(Date.now()),role:"assistant",content:n,metadata:{source:"bidi"}})]}),Je();try{await Qe()}catch(e){console.error("Failed to start audio pipeline",e),ue(e instanceof Error?e.message:"Unable to access microphone"),le("error")}}},[p,l,n,Je,Qe,R]),tt=e.useCallback(()=>{re?Ke():"connecting"!==se&&et()},[re,et,Ke,se]),nt=e.useCallback(e=>{const t=e.trim();if(!t)return;Re.current=!0;const n=fe.current;if(!n||n.readyState!==WebSocket.OPEN)return void ue("Voice session is not connected yet");n.send(JSON.stringify({type:"text",text:t})),P(l),$(!0);const r=B({id:"bidi-user-".concat(Date.now()),role:"user",content:t,metadata:{source:"bidi"}});ie(e=>[...e,r]),j("")},[]);e.useEffect(()=>{Te.current=re},[re]),e.useEffect(()=>()=>{var e,t,n,r;fe.current&&fe.current.readyState===WebSocket.OPEN&&fe.current.close(),null===(e=he.current)||void 0===e||e.disconnect(),null===(t=be.current)||void 0===t||t.close(),null===(n=ye.current)||void 0===n||n.disconnect(),null===(r=we.current)||void 0===r||r.close(),k(Ee.current),Ee.current=null,ke.current=!1},[]);const rt=e.useCallback(()=>{(e=>{try{localStorage.removeItem("".concat(N,"_").concat(e))}catch(e){}})(l),F(l,[]),M([]),ie([]),W(!1),K(!1),J({}),X(null),ee.current=!1,Re.current=!1,De.current=!1,Pe.current=!1;const e="widget-session-".concat(Math.random().toString(36).slice(2,9));if(D(l,e,{settingsSnapshot:JSON.stringify({value:h,unit:null==b?void 0:b.toUpperCase()})}),me(e),n&&""!==n.trim()&&M([s(s({},B({id:Date.now().toString(),role:"assistant",content:n})),{},{isWelcome:!0})]),m){U(g).length>0&&W(!0)}},[l,n,m,g]),at=e.useRef(rt);e.useEffect(()=>{at.current=rt},[rt]),e.useEffect(()=>{Me.current=!1,Fe.current={value:null,unit:null}},[l]),e.useEffect(()=>{if(!l||!h)return;const e=_(h,b);if(!e)return;const t=Fe.current,n=Me.current&&(t.value!==h||t.unit!==b);if(Me.current=!0,Fe.current={value:h,unit:b},n)return console.warn("[Session] Inactivity timeout config changed — resetting conversation."),void at.current();let r=null;const a=()=>{const t=O(l);if(!t)return;if(!t.firstInteractionAt)return void(r=setTimeout(a,e));const n=new Date(t.lastActivity).getTime(),o=Date.now()-n,i=e-o;if(i<=0)return console.warn("[Session] Inactivity timeout reached! Resetting conversation immediately."),void at.current();r=setTimeout(a,i)};return a(),()=>{r&&clearTimeout(r)}},[l,h,b,ge]);const ot=e.useMemo(()=>r,[r]),it=e.useMemo(()=>{const e=[...R.map(e=>s(s({},e),{},{metadata:e.metadata||{source:"sse"}})),...oe];return Array.from(new Map(e.map(e=>[e.id,e])).values()).sort((e,t)=>(e.timestamp instanceof Date?e.timestamp.getTime():new Date(e.timestamp).getTime())-(t.timestamp instanceof Date?t.timestamp.getTime():new Date(t.timestamp).getTime()))},[oe,R]);return e.useEffect(()=>{re&&console.log("[BIDI] bidiMessages state changed",{count:oe.length,messages:oe.map(e=>{var t,n;return{id:e.id,role:e.role,contentLength:(null===(t=e.content)||void 0===t?void 0:t.length)||0,isProcessing:e.isProcessing,hasContent:!!e.content,contentPreview:null===(n=e.content)||void 0===n?void 0:n.substring(0,50)}})})},[oe,re]),{conversationId:ge,isOpen:y,isMinimized:E,isDark:x,messages:it,inputValue:z,isLoading:G,isConversationLoading:te,widgetRef:q,quickQuestions:ot,isVoiceSessionActive:re,voiceStatus:se,voiceError:ce,voiceConclusionForCsat:de,onboardingQuestions:g,onboardingActive:H,onboardingCompleted:Y,handleOnboardingFormSubmit:Ue,setInputValue:j,handleSend:je,handleQuickQuestion:Ge,sendMessage:Be,toggleChat:()=>{w(e=>!e),T(!1)},toggleTheme:()=>{C(e=>!e)},toggleMinimize:()=>{T(e=>!e)},closeChat:()=>{w(!1)},handleDecision:$e,handleVoiceToggle:tt,sendBidiTextMessage:nt,resetConversation:rt}},j=(...e)=>e.filter((e,t,n)=>Boolean(e)&&""!==e.trim()&&n.indexOf(e)===t).join(" ").trim(),G=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),$=e=>{const t=(e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,t,n)=>n?n.toUpperCase():t.toLowerCase()))(e);return t.charAt(0).toUpperCase()+t.slice(1)};
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t(require("react"),require("react-dom/client"),require("react/jsx-runtime"),require("react-dom")):"function"==typeof define&&define.amd?define(["react","react-dom/client","react/jsx-runtime","react-dom"],t):(e="undefined"!=typeof globalThis?globalThis:e||self).ChatWidget=t(e.React,e.client,e.jsxRuntime,e.ReactDOM)}(this,function(e,t,n,r){"use strict";function a(e,t){return t.forEach(function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach(function(n){if("default"!==n&&!(n in e)){var r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,r.get?r:{enumerable:!0,get:function(){return t[n]}})}})}),Object.freeze(e)}function o(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function s(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?i(Object(n),!0).forEach(function(t){o(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):i(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function l(e,t){if(null==e)return{};var n,r,a=function(e,t){if(null==e)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(-1!==t.indexOf(r))continue;n[r]=e[r]}return n}(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(r=0;r<o.length;r++)n=o[r],-1===t.indexOf(n)&&{}.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}const c="processing_start",u="text_chunk",d="processing_end",p="complete",g="error",m="human_decision_required",f=e=>{if(!e||"string"!=typeof e)return null;if("[DONE]"===e||"[PROCESSING]"===e)return null;try{const n=JSON.parse(e);if(!n||"object"!=typeof n)return null;const r=n.type||n.event_type;if(r===u||n.content){var t;const e=n.content||(null===(t=n.choices)||void 0===t||null===(t=t[0])||void 0===t||null===(t=t.delta)||void 0===t?void 0:t.content)||"";return s({type:u,content:e},n)}return r===c||"processing_start"===n.type?s({type:c},n):r===d||"processing_end"===n.type?s({type:d},n):r===p||"complete"===n.type?s({type:p,finalContent:n.finalContent||n.content||""},n):r===g||"error"===n.type?s({type:g,error:n.error||n.message||"Unknown error"},n):r===m||"human_decision_required"===n.type?s({type:m,decisionId:n.decisionId||n.decision_id,question:n.question||"",options:n.options||[],context:n.context||{}},n):r?s({type:r},n):n}catch(e){return null}},h=["prompts"],b=()=>({id:"skeleton-".concat(Date.now()),role:"assistant",content:"",timestamp:new Date,isProcessing:!0}),y=e=>{if(!Array.isArray(e)||0===e.length)return;const t=e.map(e=>({type:e.type||"prompt",text:"string"==typeof e.text?e.text:"",confidence:"number"==typeof e.confidence?e.confidence:void 0})).filter(e=>e.text);return t.length?t:void 0},w=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};e(e=>{const r=[...e||[]],a=r[r.length-1];if("assistant"===(null==a?void 0:a.role)){const e=n||{},{prompts:o}=e,i=l(e,h);r[r.length-1]=s(s(s({},a),i),{},{content:t,isProcessing:!1},null!=o&&{prompts:y(o)})}return r})},E=(e,t,n,r,a)=>{var o;if(e&&e.type)switch(e.type){case c:break;case u:a.current||(a.current=!0,t(e=>{const t=e[e.length-1];if(!t||"assistant"!==t.role||!t.isProcessing){return[...e||[],b()]}return e}));const i=e.content||(null===(o=e.choices)||void 0===o||null===(o=o[0])||void 0===o||null===(o=o.delta)||void 0===o?void 0:o.content)||"";i&&(n.current+=i,r(n.current));break;case d:(e=>{e(e=>{const t=[...e||[]],n=t[t.length-1];return null!=n&&n.isProcessing&&(t[t.length-1]=s(s({},n),{},{isProcessing:!1})),t})})(t);break;case p:{const r=e.finalContent||n.current,a={};"boolean"==typeof e.conclusionDetected?a.conclusionDetected=e.conclusionDetected:"boolean"==typeof e.conclusion_detected&&(a.conclusionDetected=e.conclusion_detected);const o=s(s({},a),{},{prompts:e.prompts});w(t,r,o);break}case g:((e,t)=>{e(e=>{const n=[...e||[]],r=n[n.length-1];return"assistant"===(null==r?void 0:r.role)&&(n[n.length-1]=s(s({},r),{},{content:(r.content||"")+"\n\nError: ".concat(t),isProcessing:!1})),n})})(t,e.error||"Unknown error occurred");break;case m:{const n={id:"decision-".concat(Date.now()),role:"assistant",content:e.question||"",timestamp:new Date,isProcessing:!1,requiresDecision:!0,decisionData:{decisionId:e.decisionId,question:e.question,options:e.options||[],context:e.context||{}}};t(e=>[...(e||[]).filter(e=>!e.isProcessing||e.content),n]);break}default:console.warn("Unknown stream event type:",e.type)}},v=async(e,t)=>{const n=(e=>{let t=null,n=null,r=0;const a=o=>{if(o-r<16)n=requestAnimationFrame(a);else{if(null!==t){const n=t;t=null,r=o,e(e=>{const t=[...e||[]],r=t[t.length-1];return"assistant"===(null==r?void 0:r.role)&&(t[t.length-1]=s(s({},r),{},{content:n})),t})}n=null}};return e=>{t=e,null===n&&(n=requestAnimationFrame(a))}})(t),r=e.getReader(),a=new TextDecoder;let o="";const i={current:""},l={current:!1};try{for(;;){const{value:e,done:h}=await r.read();if(h)break;o+=a.decode(e,{stream:!0});const y=o.split(/\r?\n\r?\n/);o=y.pop()||"";for(const e of y){var c,u;const r=e.split(/\r?\n/).map(e=>e.trim()).filter(Boolean);if(0===r.length)continue;const a=r.filter(e=>e.startsWith("data:")).map(e=>e.slice(5).trim());if(0===a.length)continue;const o=a.join("\n");if("[DONE]"===o)continue;let h;try{h=JSON.parse(o)}catch(e){continue}if(h){if(h.type){if("processing_start"===h.type||"processing_end"===h.type)continue;if("text_chunk"===h.type){var d;const e=(null===(d=h.choices)||void 0===d||null===(d=d[0])||void 0===d||null===(d=d.delta)||void 0===d?void 0:d.content)||h.content;e&&(l.current||(l.current=!0,t(e=>{const t=e[e.length-1];if(!t||"assistant"!==t.role||!t.isProcessing){return[...e||[],b()]}return e})),i.current+=e,n(i.current));continue}if("complete"===h.type){var p,g,m;const e=null!==(p=null!==(g=h.Sources)&&void 0!==g?g:h.sources)&&void 0!==p?p:[],n=Array.isArray(e)?e.map(e=>{var t,n,r,a,o;return{source_type:null!==(t=null!==(n=e.source_type)&&void 0!==n?n:e.sourceType)&&void 0!==t?t:"website",source_id:null!==(r=e.sourceid)&&void 0!==r?r:e.source_id,source_name:null!==(a=null!==(o=e.source_name)&&void 0!==o?o:e.sourceName)&&void 0!==a?a:"",url:e.url}}).filter(e=>e.source_id||e.url):[],r=(null===(m=h.choices)||void 0===m||null===(m=m[0])||void 0===m||null===(m=m.delta)||void 0===m?void 0:m.content)||h.finalContent||i.current,a={};"boolean"==typeof h.conclusionDetected?a.conclusionDetected=h.conclusionDetected:"boolean"==typeof h.conclusion_detected&&(a.conclusionDetected=h.conclusion_detected);const o=s(s({},a),{},{prompts:h.prompts});w(t,r,o),n.length>0&&t(e=>{const t=[...e||[]],a=t[t.length-1];return"assistant"===(null==a?void 0:a.role)&&(t[t.length-1]=s(s({},a),{},{sources:n,content:r,isProcessing:!1})),t});continue}if("error"===h.type){t(e=>{const t=[...e||[]],n=t[t.length-1];return"assistant"===(null==n?void 0:n.role)&&(t[t.length-1]=s(s({},n),{},{content:(n.content||"")+"\n\nError: ".concat(h.error||"Unknown error occurred"),isProcessing:!1})),t});continue}const e=f(o);if(e&&e.type){console.log("🔍 Parsed stream event:",e.type,e),E(e,t,i,n,l);continue}}if("chat.completion.chunk"===h.object&&null!==(c=h.choices)&&void 0!==c&&null!==(c=c[0])&&void 0!==c&&null!==(c=c.delta)&&void 0!==c&&c.content)l.current||(l.current=!0,t(e=>{const t=e[e.length-1];if(!t||"assistant"!==t.role||!t.isProcessing){return[...e||[],b()]}return e})),i.current+=h.choices[0].delta.content,n(i.current);else if(null!==(u=h.choices)&&void 0!==u&&null!==(u=u[0])&&void 0!==u&&u.finish_reason&&null!==h.choices[0].finish_reason){const e={prompts:h.prompts};w(t,i.current,e)}}}}}finally{r.releaseLock()}};async function S(e){if("undefined"==typeof window)throw new Error("Audio recorder can only run in the browser");const t=new AudioContext({sampleRate:16e3}),n=new Blob(["\n class PCMRecorderProcessor extends AudioWorkletProcessor {\n process(inputs) {\n if (!inputs.length || !inputs[0].length) {\n return true;\n }\n const inputChannel = inputs[0][0];\n this.port.postMessage(new Float32Array(inputChannel));\n return true;\n }\n }\n registerProcessor('pcm-recorder-processor', PCMRecorderProcessor);\n "],{type:"application/javascript"}),r=URL.createObjectURL(n);await t.audioWorklet.addModule(r),URL.revokeObjectURL(r);const a=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1}}),o=t.createMediaStreamSource(a),i=new AudioWorkletNode(t,"pcm-recorder-processor");return i.port.onmessage=t=>{const n=function(e){const t=new Int16Array(e.length);for(let n=0;n<e.length;n+=1)t[n]=Math.max(-1,Math.min(1,e[n]))*T;return t.buffer}(t.data);e(n)},o.connect(i),[i,t,a]}function k(e){e&&e.getTracks().forEach(e=>e.stop())}const T=32767;const A=e=>e.replace(/([\u3000-\u303f\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uff00-\uffef])\s+([\u3000-\u303f\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uff00-\uffef])/g,"$1$2"),x=e=>{const t=(e||"").trim();return t?/^https?:\/\//i.test(t)||/^[a-z][a-z0-9+.-]*:/i.test(t)?t:"https://".concat(t.replace(/^\/+/,"")):""},C=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return t.filter(Boolean).join(" ")},R={fullname:0,name:0,username:0,email:1,phone:2,mobileno:2},I=e=>{var t;if(!e)return 99;const n=String(e).toLowerCase();return null!==(t=R[n])&&void 0!==t?t:99},N="eshal_chat_session",_=(e,t)=>{if(null==e||!t)return null;const n={MINUTES:6e4,HOURS:36e5,DAYS:864e5}[t.toUpperCase()];return void 0===n?(console.warn("[Session] Unknown timeout unit: ".concat(t)),null):Number(e)*n},O=e=>{try{const t=localStorage.getItem("".concat(N,"_").concat(e));return t?JSON.parse(t):null}catch(e){return null}},L=(e,t,n)=>{if(!e||!e.lastActivity)return!1;if(null==t||0===t)return!0;if(null!==t&&null!==n){const r=JSON.stringify({value:t,unit:null==n?void 0:n.toUpperCase()});if(e.settingsSnapshot&&e.settingsSnapshot!==r)return console.log("[Session] Timeout settings changed — treating session as invalid."),!1}if(null===e.firstInteractionAt)return!0;const r=_(t,n);if(!r)return!0;const a=new Date(e.lastActivity).getTime(),o=Date.now()-a,i=o<r;return i||console.log("[Session] Session expired. Elapsed: ".concat(Math.floor(o/1e3),"s, Timeout: ").concat(Math.floor(r/1e3),"s")),i},D=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};try{const r=(new Date).toISOString();console.log("[Session] Saving new session: ".concat(t," for org: ").concat(e)),localStorage.setItem("".concat(N,"_").concat(e),JSON.stringify(s({conversationId:t,lastActivity:r,createdAt:r,firstInteractionAt:null},n)))}catch(e){}},P=e=>{try{const t=O(e);if(!t)return;const n=(new Date).toISOString();t.lastActivity=n,t.firstInteractionAt||(t.firstInteractionAt=n),localStorage.setItem("".concat(N,"_").concat(e),JSON.stringify(t))}catch(e){}},M=e=>{try{const t=O(e);if(!t)return;t.csatSubmitted=!0,localStorage.setItem("".concat(N,"_").concat(e),JSON.stringify(t))}catch(e){}},F=(e,t)=>{try{if(!e)return;if(!Array.isArray(t)||0===t.length)return void localStorage.removeItem("".concat(N,"_prompts_").concat(e));localStorage.setItem("".concat(N,"_prompts_").concat(e),JSON.stringify(t))}catch(e){}},B=e=>{let{id:t,role:n,content:r,isProcessing:a=!1,metadata:o}=e;return{id:t,role:n,content:r,timestamp:new Date,isProcessing:a,metadata:o}},U=e=>e&&e.length>0?e:[],z=t=>{let{welcomeMessage:n,quickQuestions:r=[],apiBaseUrl:a,wsBaseUrl:o,apiKey:i,organizationId:l,autoOpen:c,openDelay:u,darkMode:d,enableVoiceInteraction:p=!1,onboardingQuestions:g=[],onboardingEnabled:m=!1,collectionPrompt:f,inactivityTimeoutValue:h,inactivityTimeoutUnit:b}=t;const[y,w]=e.useState(c),[E,T]=e.useState(!1),[x,C]=e.useState(d),[R,M]=e.useState(()=>{try{const e=O(l);if(void 0!==h&&e&&L(e,h,b))return[]}catch(e){}return n?[s(s({},B({id:Date.now().toString(),role:"assistant",content:n})),{},{isWelcome:!0})]:[]}),[z,j]=e.useState(""),[G,$]=e.useState(!1),q=e.useRef(null),V=e.useRef(1),[H,W]=e.useState(!1),[Y,K]=e.useState(()=>{try{const e=O(l);if(e&&e.onboardingCompleted)return!0}catch(e){}return!1}),[Z,X]=e.useState(null),[Q,J]=e.useState({}),ee=e.useRef(!1),[te,ne]=e.useState(!1),[re,ae]=e.useState(!1),[oe,ie]=e.useState([]),[se,le]=e.useState("idle"),[ce,ue]=e.useState(null),[de,pe]=e.useState(!1),[ge,me]=e.useState(()=>{try{const e=O(l);if(void 0!==h&&e&&L(e,h,b))return e.conversationId}catch(e){}return"widget-session-".concat(Math.random().toString(36).slice(2,9))}),fe=e.useRef(null),he=e.useRef(null),be=e.useRef(null),ye=e.useRef(null),we=e.useRef(null),Ee=e.useRef(null),ve=e.useRef(null),Se=e.useRef(null),ke=e.useRef(!1),Te=e.useRef(!1);e.useRef(null);const Ae=e.useRef(null);e.useRef(null);const xe=e.useRef(!1),Ce=e.useRef(null),Re=e.useRef(!1),Ie=e.useRef(!1),Ne=e.useRef(null),_e=e.useRef(null),Oe=e.useMemo(()=>{if(!l)return null;const e=((e,t)=>{if(t)return t.replace(/\/$/,"");if(!e)return"wss://dev.eshal.ai/knowledge-api/ws";try{const t=new URL(e);return t.protocol=t.protocol.replace(/^http/,"ws"),t.pathname="/knowledge-api/ws",t.toString().replace(/\/$/,"")}catch(e){return console.error("Invalid API base URL provided for WebSocket:",e),"wss://dev.eshal.ai/knowledge-api/ws"}})(a,o);return"".concat(e,"/").concat(l,"/").concat(ge)},[a,l,ge]),Le=e.useCallback(()=>{const e="msg-".concat(V.current);return V.current+=1,e},[]);e.useEffect(()=>{if(c&&u>0){const e=setTimeout(()=>w(!0),u);return()=>clearTimeout(e)}},[c,u]),e.useEffect(()=>{C(d)},[d]);const De=e.useRef(!1),Pe=e.useRef(!1),Me=e.useRef(!1),Fe=e.useRef({value:null,unit:null});e.useEffect(()=>{if(!l||!ge||void 0===h)return;const e=O(l);if(e&&L(e,h,b)){if(ge!==e.conversationId)return void me(e.conversationId);!De.current&&a&&(De.current=!0,ne(!0),(async(e,t,n)=>{if(!e||!t||!n)throw new Error("apiBaseUrl, orgId, and conversationId are required");const r="".concat(e.replace(/\/$/,""),"/api/v1/conversations/").concat(t,"/").concat(n),a=await fetch(r,{method:"GET",headers:{"Content-Type":"application/json"},credentials:"include"});if(404===a.status)return[];if(!a.ok)throw new Error("HTTP error! status: ".concat(a.status));return(await a.json()).messages||[]})(a,l,ge).then(e=>{const t=["userName","email","phone","fullname","mobileno","name"],r=e.filter(e=>{const n=e.type||e.messageType;return!n||!t.includes(n)});if(r.length>0){Pe.current=!0;const e=r.map((e,t)=>{var n;const r=null!==(n=e.Sources)&&void 0!==n?n:e.sources,a=Array.isArray(r)?r.map(e=>{var t,n,r,a,o;return{source_type:null!==(t=null!==(n=e.source_type)&&void 0!==n?n:e.sourceType)&&void 0!==t?t:"website",source_id:null!==(r=e.source_id)&&void 0!==r?r:e.sourceid,source_name:null!==(a=null!==(o=e.source_name)&&void 0!==o?o:e.sourceName)&&void 0!==a?a:"",url:e.url}}).filter(e=>e.source_id||e.url):[];return s(s(s({},B({id:e.id||"history-".concat(t,"-").concat(Date.now()),role:e.role||("user"===e.sender?"user":"assistant"),content:e.message||e.content||""})),{},{timestamp:e.time?new Date(e.time):new Date},Array.isArray(e.prompts)&&e.prompts.length>0?{prompts:e.prompts}:{}),a.length>0?{sources:a}:{})});if(!e.some(e=>"assistant"===e.role&&Array.isArray(e.prompts)&&e.prompts.length>0)){const t=(e=>{try{const t=localStorage.getItem("".concat(N,"_prompts_").concat(e));return t&&JSON.parse(t)||[]}catch(e){return[]}})(l);if(t.length>0)for(let n=e.length-1;n>=0;n-=1)if("assistant"===e[n].role){e[n]=s(s({},e[n]),{},{prompts:t});break}}if(n){var a;const t=null===(a=e[0])||void 0===a?void 0:a.timestamp,r=t instanceof Date?t.getTime():t?new Date(t).getTime():Date.now(),o=s(s({},B({id:"welcome-restored",role:"assistant",content:n})),{},{isWelcome:!0,timestamp:new Date(r-1)});M([o,...e])}else M(e)}}).catch(e=>{console.error("[Session] History fetch failed:",e)}).finally(()=>{ne(!1)}))}else if(De.current||(De.current=!0),e&&ge===e.conversationId){const e="widget-session-".concat(Math.random().toString(36).slice(2,9));console.warn("[Session] Rotating expired ID ".concat(ge," -> ").concat(e)),me(e)}else e&&e.conversationId===ge||D(l,ge,{settingsSnapshot:JSON.stringify({value:h,unit:null==b?void 0:b.toUpperCase()})})},[l,ge,a,h,b]),e.useEffect(()=>{if(l&&R&&0!==R.length)for(let e=R.length-1;e>=0;e-=1){const t=R[e];if("assistant"===(null==t?void 0:t.role)&&Array.isArray(t.prompts)&&t.prompts.length>0)return void F(l,t.prompts)}},[R,l]),e.useEffect(()=>{if(!m||Y)return;U(g).length>0&&W(!0)},[m,Y,g]),e.useEffect(()=>{n&&!Pe.current&&M(e=>{if(!e.length)return[s(s({},B({id:Date.now().toString(),role:"assistant",content:n})),{},{isWelcome:!0})];const[t,...r]=e;return t.isWelcome?[s(s({},t),{},{content:n}),...r]:e})},[n]),e.useCallback(e=>{M(t=>t.map(t=>t.id===e.id?s(s({},t),e.update(t)):t))},[]);const Be=e.useCallback(async(e,t)=>{const n=e.trim();if(!n)return{success:!1,error:"Message cannot be empty"};if(!a)return M(e=>[...e||[],B({id:Le(),role:"assistant",content:"Sorry, I'm having trouble connecting right now. Please try again.",isProcessing:!1})]),console.error("Chat widget configuration error: apiBaseUrl is required for streaming."),{success:!1,error:"API base URL is required"};const r=["inquiry","complaint","technical","userName","email","phone","fullname","mobileno"];let o="inquiry";if(t){const e=t.toLowerCase();"fullname"===e||"name"===e?o="userName":"email"===e?o="email":"phone"===e||"mobileno"===e?o="phone":r.includes(e)&&(o=e)}if("inquiry"===o||"complaint"===o||"technical"===o){const e=B({id:Le(),role:"user",content:n});M(t=>[...(t||[]).map(e=>{var t;return"assistant"===e.role&&null!==(t=e.prompts)&&void 0!==t&&t.length?s(s({},e),{},{prompts:void 0}):e}),e]),j(""),$(!0)}else j("");try{const e={message:n,type:o,conversationId:ge,channel:"WIDGET",messageHistory:R.filter(e=>!e.isProcessing&&e.content&&e.content.trim()&&!["userName","email","phone"].includes(e.type)).map(e=>{let t;return t=e.timestamp instanceof Date?e.timestamp.toISOString():"string"==typeof e.timestamp?e.timestamp:e.timestamp?new Date(e.timestamp).toISOString():(new Date).toISOString(),{id:e.id,role:e.role,content:e.content,timestamp:t,isProcessing:!1}})},t=await(async(e,t,n)=>{const r={"Content-Type":"application/json",Accept:"text/event-stream"};n&&(r["x-eshal-org"]=n);const a=await fetch("".concat(t.replace(/\/$/,""),"/api/v1/support"),{method:"POST",headers:r,credentials:"include",body:JSON.stringify(e)});if(!a.ok)throw new Error("HTTP error! status: ".concat(a.status));if(!a.body)throw new Error("Response body is null");return a.body})(e,a,l);if("userName"===o||"email"===o||"phone"===o){const e=t.getReader(),n=new TextDecoder;for(;;){const{done:t,value:r}=await e.read();if(t)break;n.decode(r)}return{success:!0}}return"inquiry"===o||"complaint"===o||"technical"===o?(await v(t,M),P(l),{success:!0}):(P(l),{success:!0})}catch(e){return console.error("Error sending message:",e),"inquiry"!==o&&"complaint"!==o&&"technical"!==o||($(!1),M(e=>[...(e||[]).filter(e=>!e.isProcessing),B({id:Le(),role:"assistant",content:"Sorry, I'm having trouble connecting right now. Please try again.",isProcessing:!1})])),{success:!1,error:e instanceof Error?e.message:"Failed to send message"}}finally{"inquiry"!==o&&"complaint"!==o&&"technical"!==o||$(!1)}},[a,i,Le,l,R,ge]),Ue=e.useCallback(async e=>{const t=U(g);if(0===t.length)return;const n=[...t].sort((e,t)=>I(e.fieldType)-I(t.fieldType));for(const t of n){var r;const n=t.fieldType||"question",a=(null!==(r=e[n])&&void 0!==r?r:"").trim();if(!a)continue;const o=await Be(a,n);if(null==o||!o.success){const e=B({id:Le(),role:"assistant",content:(null==o?void 0:o.error)||"Something went wrong. Please try again.",isProcessing:!1});return void M(t=>[...t,e])}}W(!1),K(!0),(e=>{try{const t=O(e);if(!t)return;t.onboardingCompleted=!0,localStorage.setItem("".concat(N,"_").concat(e),JSON.stringify(t))}catch(e){}})(l),J(t=>s(s({},t),e)),Z&&!ee.current&&(ee.current=!0,setTimeout(()=>{j(Z),X(null)},500))},[g,Be,Le,Z,l]),ze=e.useCallback(async()=>{const e=z.trim();e&&await Be(e)},[z,Be]),je=e.useCallback(async()=>{await ze()},[ze]),Ge=e.useCallback(async e=>{const t=null==e?void 0:e.trim();t&&await Be(t)},[Be]),$e=e.useCallback(async(e,t,n)=>{if(M(t=>t.filter(t=>{var n;return(null===(n=t.decisionData)||void 0===n?void 0:n.decisionId)!==e})),"connect_agent"===n){const e=B({id:Le(),role:"assistant",content:"Great! I'm setting up a connection with a live customer service agent. Please hold on for a moment while I transfer you."});M(t=>[...t,e])}else if("decline"===n){const e=B({id:Le(),role:"assistant",content:"I understand. I apologize that I don't have specific information about your query in my knowledge base. Is there anything else I can help you with?"});M(t=>[...t,e])}},[Le]);e.useCallback(()=>{ve.current&&(ie(e=>e.map(e=>e.id===ve.current?s(s({},e),{},{isProcessing:!1}):e)),ve.current=null)},[]);const qe=e.useCallback(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(Re.current=!0,!e||"string"==typeof e&&!e.trim())return void(t&&ve.current&&(ie(e=>e.map(e=>e.id===ve.current?s(s({},e),{},{isProcessing:!1}):e)),ve.current=null));const n=A(e);ie(e=>{const r=e.length;let a=[...e];if(ve.current){if(a.some(e=>e.id===ve.current))a=a.map(e=>{if(e.id!==ve.current)return e;const r=A("".concat(e.content||"").concat(n));return s(s({},e),{},{content:r,isProcessing:!t,metadata:s(s({},e.metadata),{},{transcriptionType:"input"})})});else{console.error("[BIDI] appendUserTranscription: ERROR - user message not found!",{expectedId:ve.current,existingIds:a.map(e=>e.id)});const e="bidi-input-".concat(Date.now());ve.current=e;const r=B({id:e,role:"user",content:n,isProcessing:!t,metadata:{source:"bidi",transcriptionType:"input"}});a=[...a,r],console.log("[BIDI] appendUserTranscription: recreated lost user message",{messageId:e})}}else{const r="bidi-input-".concat(Date.now()),o=Date.now(),i=e.filter(e=>{var t;return"assistant"===e.role&&"bidi"===(null===(t=e.metadata)||void 0===t?void 0:t.source)}).sort((e,t)=>{const n=e.timestamp instanceof Date?e.timestamp.getTime():new Date(e.timestamp).getTime();return(t.timestamp instanceof Date?t.timestamp.getTime():new Date(t.timestamp).getTime())-n})[0];let l;if(i){const e=i.timestamp instanceof Date?i.timestamp.getTime():new Date(i.timestamp).getTime();l=new Date(e-1)}else l=new Date(o);const c=B({id:r,role:"user",content:n,isProcessing:!t,timestamp:l,metadata:{source:"bidi",transcriptionType:"input"}});a.some(e=>e.id===r)?(console.warn("[BIDI] appendUserTranscription: message already exists, updating instead",{messageId:r}),ve.current=r,a=a.map(e=>e.id===r?s(s({},e),{},{content:"".concat(e.content||"").concat(n),isProcessing:!t}):e)):(a=[...a,c],ve.current=r)}return a.length<r?(console.error("[BIDI] appendUserTranscription: CRITICAL ERROR - losing messages!",{prevLength:r,resultLength:a.length,prevIds:e.map(e=>{var t;return{id:e.id,role:e.role,content:null===(t=e.content)||void 0===t?void 0:t.substring(0,30)}}),resultIds:a.map(e=>{var t;return{id:e.id,role:e.role,content:null===(t=e.content)||void 0===t?void 0:t.substring(0,30)}})}),e):a}),t&&(ve.current=null,$(!0))},[]),Ve=e.useCallback(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if($(!1),console.log("[BIDI] appendAssistantContent called",{text:null==e?void 0:e.substring(0,50),finished:t,currentAssistantId:Se.current,currentInputId:ve.current}),!e||"string"==typeof e&&!e.trim())return console.log("[BIDI] appendAssistantContent: skipping empty text"),void(t&&Se.current&&(ie(e=>e.map(e=>e.id!==Se.current?e:s(s({},e),{},{isProcessing:!1}))),Se.current=null,Ae.current=null));const n="".concat(Se.current||"new","-").concat(e.substring(0,100),"-").concat(t);if(xe.current&&Ce.current===n)return;xe.current=!0,Ce.current=n;const r=ve.current;if(ie(n=>{const a=n.length;let o=[...n];if(console.log("[BIDI] appendAssistantContent: starting update",{prevLength:a,prevMessageIds:n.map(e=>e.id),inputMessageIdToFinalize:r,currentAssistantId:Se.current,textLength:e.length}),r){o.some(e=>e.id===r)?o=o.map(e=>e.id===r?s(s({},e),{},{isProcessing:!1}):e):console.warn("[BIDI] appendAssistantContent: input message not found for finalization",{inputMessageId:r,existingIds:o.map(e=>e.id)})}if(Se.current){if(o.some(e=>e.id===Se.current))o=o.map(n=>{var r;if(n.id!==Se.current)return n;const a="".concat(n.content||"").concat(e);return console.log("[BIDI] appendAssistantContent: updating existing message",{messageId:n.id,oldContentLength:(null===(r=n.content)||void 0===r?void 0:r.length)||0,newContentLength:a.length,textLength:e.length}),s(s({},n),{},{content:a,isProcessing:!t},Array.isArray(_e.current)&&_e.current.length>0?{sources:_e.current}:{})}),Array.isArray(_e.current)&&_e.current.length>0&&(_e.current=null);else{console.error("[BIDI] appendAssistantContent: ERROR - assistant message not found!",{expectedId:Se.current,existingIds:o.map(e=>e.id)});const n="bidi-assistant-".concat(Date.now());Se.current=n;const r=B({id:n,role:"assistant",content:e,isProcessing:!t,metadata:{source:"bidi"}});Array.isArray(_e.current)&&_e.current.length>0&&(r.sources=_e.current,_e.current=null),o=[...o,r],console.log("[BIDI] appendAssistantContent: recreated lost assistant message",{messageId:n})}}else{const n="bidi-assistant-".concat(Date.now()),a=Date.now(),i=r?new Date(a):new Date(a+1e3),l=B({id:n,role:"assistant",content:e,isProcessing:!t,timestamp:i,metadata:{source:"bidi"}});Array.isArray(_e.current)&&_e.current.length>0&&(l.sources=_e.current,_e.current=null);o.some(e=>e.id===n)?(console.error("[BIDI] appendAssistantContent: ERROR - message ID collision!",{messageId:n,existingIds:o.map(e=>e.id)}),o=o.map(r=>r.id===n?s(s({},r),{},{content:"".concat(r.content||"").concat(e),isProcessing:!t},Array.isArray(_e.current)&&_e.current.length>0?{sources:_e.current}:{}):r),Array.isArray(_e.current)&&_e.current.length>0&&(_e.current=null),Se.current=n):(o=[...o,l],Se.current=n)}return console.log("[BIDI] appendAssistantContent: atomic state update complete",{prevLength:a,newLength:o.length,finished:t,messageIds:o.map(e=>e.id),messageRoles:o.map(e=>e.role)}),o.length<a?(console.error("[BIDI] appendAssistantContent: CRITICAL ERROR - losing messages!",{prevLength:a,resultLength:o.length,prevIds:n.map(e=>{var t;return{id:e.id,role:e.role,content:null===(t=e.content)||void 0===t?void 0:t.substring(0,30)}}),resultIds:o.map(e=>{var t;return{id:e.id,role:e.role,content:null===(t=e.content)||void 0===t?void 0:t.substring(0,30)}})}),n):o}),r&&(ve.current=null),t)console.log("[BIDI] appendAssistantContent: finalizing message",{messageId:Se.current}),Se.current=null,Ae.current=null;else{const e=updateKey;Promise.resolve().then(()=>{Ae.current===e&&(Ae.current=null)})}},[]),He=e.useCallback(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(console.log("[BIDI] handleContentParts called",{partsCount:null==e?void 0:e.length,finished:t,audioOnly:n}),!e||!Array.isArray(e))return void console.warn("[BIDI] handleContentParts: invalid parts",e);let r="";e.forEach((e,t)=>{var a,o;null!==(a=e.inlineData)&&void 0!==a&&a.data&&null!==(o=e.inlineData.mimeType)&&void 0!==o&&o.startsWith("audio/pcm")&&(console.log("[BIDI] handleContentParts: sending audio data to player"),he.current?he.current.port.postMessage((e=>{if("undefined"==typeof window)return new ArrayBuffer(0);let t=e.replace(/-/g,"+").replace(/_/g,"/");for(;t.length%4!=0;)t+="=";const n=window.atob(t),r=n.length,a=new Uint8Array(r);for(let e=0;e<r;e+=1)a[e]=n.charCodeAt(e);return a.buffer})(e.inlineData.data)):console.warn("[BIDI] handleContentParts: audioPlayerNodeRef is null")),!n&&e.text&&(r+=e.text,console.log("[BIDI] handleContentParts: accumulated text part",{text:e.text.substring(0,50),index:t,totalAccumulated:r.length}))}),r&&(console.log("[BIDI] handleContentParts: calling appendAssistantContent once",{textLength:r.length,finished:t}),Ve(r,t))},[Ve]),We=e.useCallback(()=>{$(!1),console.log("[BIDI] handleTurnComplete called",{currentAssistantId:Se.current,currentInputId:ve.current}),ie(e=>{const t=e.map(e=>{var t;return"bidi"===(null===(t=e.metadata)||void 0===t?void 0:t.source)&&e.isProcessing?s(s({},e),{},{isProcessing:!1}):e});return console.log("[BIDI] handleTurnComplete: state update",{prevLength:e.length,newLength:t.length,finalizedCount:e.filter(e=>{var t;return"bidi"===(null===(t=e.metadata)||void 0===t?void 0:t.source)&&e.isProcessing}).length}),t}),Se.current=null,ve.current=null,Ie.current=!1,_e.current=null},[]),Ye=e.useCallback(()=>{$(!1),he.current&&he.current.port.postMessage({command:"endOfAudio"}),Se.current=null,ve.current=null,_e.current=null,ie(e=>e.map(e=>{var t;return"bidi"===(null===(t=e.metadata)||void 0===t?void 0:t.source)?s(s({},e),{},{isProcessing:!1,metadata:s(s({},e.metadata),{},{interrupted:!0})}):e}))},[]),Ke=e.useCallback(()=>{var e,t,n,r;ae(!1),$(!1),Te.current=!1,le("idle"),ue(null),Re.current=!1,_e.current=null,fe.current&&fe.current.readyState===WebSocket.OPEN&&fe.current.close(),fe.current=null,null===(e=he.current)||void 0===e||e.disconnect(),null===(t=be.current)||void 0===t||t.close(),he.current=null,be.current=null,null===(n=ye.current)||void 0===n||n.disconnect(),null===(r=we.current)||void 0===r||r.close(),ye.current=null,we.current=null,k(Ee.current),Ee.current=null,ke.current=!1},[]),Ze=e.useCallback(e=>{var t,n,r,a,o;if(console.log("[BIDI] handleBidiEvent called",{event:e,isVoiceSessionActive:Te.current,hasTurnComplete:!(null==e||!e.turnComplete),hasInterrupted:!(null==e||!e.interrupted),hasInputTranscription:!(null==e||!e.inputTranscription),hasOutputTranscription:!(null==e||!e.outputTranscription),hasContentParts:!(null==e||null===(t=e.content)||void 0===t||!t.parts)}),!e)return void console.warn("[BIDI] handleBidiEvent: received null/undefined event");const i=null!==(n=e.conclusion_detected)&&void 0!==n?n:e.conclusionDetected;var c;"boolean"==typeof i&&i&&(null===(c=Ne.current)||void 0===c||c.call(Ne),pe(!0));if("boolean"==typeof i&&i)return Ke(),void ie(e=>{const t=[...e];for(let e=t.length-1;e>=0;e--)if("assistant"===t[e].role){t[e]=s(s({},t[e]),{},{conclusionDetected:!0});break}return t});if(e.interrupted)return console.log("[BIDI] handleBidiEvent: processing interrupted"),void Ye();if(e.inputTranscription){const t=e.inputTranscription.text||"",n=Boolean(e.inputTranscription.finished);console.log("[BIDI] handleBidiEvent: processing inputTranscription",{text:t.substring(0,50),textLength:t.length,finished:n,hasText:!!t}),t||n?(P(l),qe(t,n)):console.warn("[BIDI] handleBidiEvent: inputTranscription event has no text and not finished",e.inputTranscription)}const u=null!==(r=e.sources)&&void 0!==r?r:e.Sources;if(Array.isArray(u)&&u.length>0){const e=u.map(e=>{var t,n,r,a,o,i;return{source_type:null!==(t=null!==(n=e.source_type)&&void 0!==n?n:e.sourceType)&&void 0!==t?t:"file",source_id:null!==(r=null!==(a=e.source_id)&&void 0!==a?a:e.sourceid)&&void 0!==r?r:e.sourceId,source_name:null!==(o=null!==(i=e.source_name)&&void 0!==i?i:e.sourceName)&&void 0!==o?o:"",url:e.url}}).filter(e=>e.source_id||e.url);if(0===e.length)return;ie(t=>{const n=[...t];let r=!1;for(let t=n.length-1;t>=0;t--)if("assistant"===n[t].role){n[t]=s(s({},n[t]),{},{sources:e}),r=!0;break}return r||(_e.current=e),n})}var d,p;if(!Re.current&&(null!==(d=e.outputTranscription)&&void 0!==d&&d.text||null!==(p=e.content)&&void 0!==p&&p.parts))return void(e.turnComplete&&We());if(null!==(a=e.outputTranscription)&&void 0!==a&&a.text&&(Ie.current=!0,Ve(e.outputTranscription.text,Boolean(e.outputTranscription.finished))),null!==(o=e.content)&&void 0!==o&&o.parts){var g;const t=(null===(g=e.content)||void 0===g?void 0:g.finished)||e.finished||!1;He(e.content.parts,t,Ie.current)}if(e.prompts&&Array.isArray(e.prompts)&&e.prompts.length>0){console.log("[BIDI] handleBidiEvent: attaching prompts to last assistant message",{count:e.prompts.length}),ie(t=>{const n=[...t];for(let t=n.length-1;t>=0;t--)if("assistant"===n[t].role){n[t]=s(s({},n[t]),{},{prompts:e.prompts});break}return n});try{F(l,e.prompts)}catch(e){}}e.turnComplete?We():e.interrupted||e.inputTranscription||e.outputTranscription||e.content||e.prompts||console.warn("[BIDI] handleBidiEvent: event had no recognized fields",e)},[Ve,qe,He,Ye,We,Ke]),Xe=e.useCallback(e=>{const t=fe.current;Te.current&&t&&t.readyState===WebSocket.OPEN&&t.send(e)},[]),Qe=e.useCallback(async()=>{if(!ke.current&&"undefined"!=typeof window)try{const[e,t]=await async function(){if("undefined"==typeof window)throw new Error("Audio player can only be initialized in the browser");const e=new AudioContext({sampleRate:24e3}),t=new Blob(["\n class PCMPlayerProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n this.bufferSize = 24000 * 180;\n this.buffer = new Float32Array(this.bufferSize);\n this.writeIndex = 0;\n this.readIndex = 0;\n this.port.onmessage = (event) => {\n if (event.data?.command === 'endOfAudio') {\n this.readIndex = this.writeIndex;\n return;\n }\n const int16Samples = new Int16Array(event.data);\n this.enqueue(int16Samples);\n };\n }\n\n enqueue(samples) {\n for (let i = 0; i < samples.length; i += 1) {\n const floatVal = samples[i] / 32768;\n this.buffer[this.writeIndex] = floatVal;\n this.writeIndex = (this.writeIndex + 1) % this.bufferSize;\n if (this.writeIndex === this.readIndex) {\n this.readIndex = (this.readIndex + 1) % this.bufferSize;\n }\n }\n }\n\n process(inputs, outputs) {\n const output = outputs[0];\n const framesPerBlock = output[0].length;\n for (let frame = 0; frame < framesPerBlock; frame += 1) {\n output[0][frame] = this.buffer[this.readIndex];\n if (output.length > 1) {\n output[1][frame] = this.buffer[this.readIndex];\n }\n if (this.readIndex !== this.writeIndex) {\n this.readIndex = (this.readIndex + 1) % this.bufferSize;\n }\n }\n return true;\n }\n }\n\n registerProcessor('pcm-player-processor', PCMPlayerProcessor);\n "],{type:"application/javascript"}),n=URL.createObjectURL(t);await e.audioWorklet.addModule(n);const r=new AudioWorkletNode(e,"pcm-player-processor");return r.connect(e.destination),URL.revokeObjectURL(n),[r,e]}();he.current=e,be.current=t,await t.resume();const[n,r,a]=await S(Xe);ye.current=n,we.current=r,Ee.current=a,await r.resume(),ke.current=!0}catch(e){throw console.error("Failed to initialize audio pipeline",e),e}},[Xe]),Je=e.useCallback(()=>{if("undefined"!=typeof window&&Oe&&(!fe.current||fe.current.readyState!==WebSocket.OPEN)){le("connecting"),ue(null);try{const e=new WebSocket(Oe);fe.current=e,e.onopen=()=>{le("connected")},e.onmessage=e=>{try{var t,n;const r="string"==typeof e.data?e.data.substring(0,200):"binary";console.log("[BIDI] WebSocket message received",{dataLength:null===(t=e.data)||void 0===t?void 0:t.length,dataPreview:r});const a=JSON.parse(e.data);console.log("[BIDI] WebSocket message parsed",{hasTurnComplete:!!a.turnComplete,hasInterrupted:!!a.interrupted,hasInputTranscription:!!a.inputTranscription,hasOutputTranscription:!!a.outputTranscription,hasContentParts:!(null===(n=a.content)||void 0===n||!n.parts),payload:a}),Ze(a)}catch(t){console.error("[BIDI] Failed to parse WebSocket event",{error:t,data:e.data})}},e.onerror=()=>{le("error"),ue("Voice session connection error"),$(!1)},e.onclose=()=>{fe.current=null,le("idle"),$(!1),Te.current&&setTimeout(()=>{Je()},5e3)}}catch(e){console.error("Failed to open voice websocket",e),le("error"),ue(e instanceof Error?e.message:"Unable to start voice session")}}},[Ze,Oe]),et=e.useCallback(async()=>{if(p&&l){ue(null),le(e=>"connected"===e?e:"connecting"),ae(!0),Te.current=!0,pe(!1),Re.current=!1,ie(e=>{if(e.length>0||R.length>0)return e;if(!n||""===n.trim())return[];return[B({id:"bidi-welcome-".concat(Date.now()),role:"assistant",content:n,metadata:{source:"bidi"}})]}),Je();try{await Qe()}catch(e){console.error("Failed to start audio pipeline",e),ue(e instanceof Error?e.message:"Unable to access microphone"),le("error")}}},[p,l,n,Je,Qe,R]),tt=e.useCallback(()=>{re?Ke():"connecting"!==se&&et()},[re,et,Ke,se]),nt=e.useCallback(e=>{const t=e.trim();if(!t)return;Re.current=!0;const n=fe.current;if(!n||n.readyState!==WebSocket.OPEN)return void ue("Voice session is not connected yet");n.send(JSON.stringify({type:"text",text:t})),P(l),$(!0);const r=B({id:"bidi-user-".concat(Date.now()),role:"user",content:t,metadata:{source:"bidi"}});ie(e=>[...e,r]),j("")},[]);e.useEffect(()=>{Te.current=re},[re]),e.useEffect(()=>()=>{var e,t,n,r;fe.current&&fe.current.readyState===WebSocket.OPEN&&fe.current.close(),null===(e=he.current)||void 0===e||e.disconnect(),null===(t=be.current)||void 0===t||t.close(),null===(n=ye.current)||void 0===n||n.disconnect(),null===(r=we.current)||void 0===r||r.close(),k(Ee.current),Ee.current=null,ke.current=!1},[]);const rt=e.useCallback(()=>{(e=>{try{localStorage.removeItem("".concat(N,"_").concat(e))}catch(e){}})(l),F(l,[]),M([]),ie([]),W(!1),K(!1),J({}),X(null),ee.current=!1,Re.current=!1,De.current=!1,Pe.current=!1;const e="widget-session-".concat(Math.random().toString(36).slice(2,9));if(D(l,e,{settingsSnapshot:JSON.stringify({value:h,unit:null==b?void 0:b.toUpperCase()})}),me(e),n&&""!==n.trim()&&M([s(s({},B({id:Date.now().toString(),role:"assistant",content:n})),{},{isWelcome:!0})]),m){U(g).length>0&&W(!0)}},[l,n,m,g]),at=e.useRef(rt);e.useEffect(()=>{at.current=rt},[rt]),e.useEffect(()=>{Me.current=!1,Fe.current={value:null,unit:null}},[l]),e.useEffect(()=>{if(!l||!h)return;const e=_(h,b);if(!e)return;const t=Fe.current,n=Me.current&&(t.value!==h||t.unit!==b);if(Me.current=!0,Fe.current={value:h,unit:b},n)return console.warn("[Session] Inactivity timeout config changed — resetting conversation."),void at.current();let r=null;const a=()=>{const t=O(l);if(!t)return;if(!t.firstInteractionAt)return void(r=setTimeout(a,e));const n=new Date(t.lastActivity).getTime(),o=Date.now()-n,i=e-o;if(i<=0)return console.warn("[Session] Inactivity timeout reached! Resetting conversation immediately."),void at.current();r=setTimeout(a,i)};return a(),()=>{r&&clearTimeout(r)}},[l,h,b,ge]);const ot=e.useMemo(()=>r,[r]),it=e.useMemo(()=>{const e=[...R.map(e=>s(s({},e),{},{metadata:e.metadata||{source:"sse"}})),...oe];return Array.from(new Map(e.map(e=>[e.id,e])).values()).sort((e,t)=>(e.timestamp instanceof Date?e.timestamp.getTime():new Date(e.timestamp).getTime())-(t.timestamp instanceof Date?t.timestamp.getTime():new Date(t.timestamp).getTime()))},[oe,R]);return e.useEffect(()=>{re&&console.log("[BIDI] bidiMessages state changed",{count:oe.length,messages:oe.map(e=>{var t,n;return{id:e.id,role:e.role,contentLength:(null===(t=e.content)||void 0===t?void 0:t.length)||0,isProcessing:e.isProcessing,hasContent:!!e.content,contentPreview:null===(n=e.content)||void 0===n?void 0:n.substring(0,50)}})})},[oe,re]),{conversationId:ge,isOpen:y,isMinimized:E,isDark:x,messages:it,inputValue:z,isLoading:G,isConversationLoading:te,widgetRef:q,quickQuestions:ot,isVoiceSessionActive:re,voiceStatus:se,voiceError:ce,voiceConclusionForCsat:de,onboardingQuestions:g,onboardingActive:H,onboardingCompleted:Y,handleOnboardingFormSubmit:Ue,setInputValue:j,handleSend:je,handleQuickQuestion:Ge,sendMessage:Be,toggleChat:()=>{w(e=>!e),T(!1)},toggleTheme:()=>{C(e=>!e)},toggleMinimize:()=>{T(e=>!e)},closeChat:()=>{w(!1)},handleDecision:$e,handleVoiceToggle:tt,sendBidiTextMessage:nt,resetConversation:rt}},j=(...e)=>e.filter((e,t,n)=>Boolean(e)&&""!==e.trim()&&n.indexOf(e)===t).join(" ").trim(),G=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),$=e=>{const t=(e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,t,n)=>n?n.toUpperCase():t.toLowerCase()))(e);return t.charAt(0).toUpperCase()+t.slice(1)};
|
|
2
2
|
/**
|
|
3
3
|
* @license lucide-react v0.575.0 - ISC
|
|
4
4
|
*
|