@flowengage/react-chatbot 0.2.9 → 0.2.11
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/flowengage-embed.js +17 -17
- package/dist/flowengage-react-chatbot.cjs +3 -3
- package/dist/flowengage-react-chatbot.mjs +1578 -1488
- package/package.json +1 -1
|
@@ -315,15 +315,15 @@ class ScribeAudioProcessor extends AudioWorkletProcessor {
|
|
|
315
315
|
|
|
316
316
|
registerProcessor("scribeAudioProcessor", ScribeAudioProcessor);
|
|
317
317
|
|
|
318
|
-
`),uh,dh;(function(e){e.PCM_8000=`pcm_8000`,e.PCM_16000=`pcm_16000`,e.PCM_22050=`pcm_22050`,e.PCM_24000=`pcm_24000`,e.PCM_44100=`pcm_44100`,e.PCM_48000=`pcm_48000`,e.ULAW_8000=`ulaw_8000`})(uh||={}),function(e){e.MANUAL=`manual`,e.VAD=`vad`}(dh||={});var fh=class e{static getWebSocketUri(t=e.DEFAULT_BASE_URI){return`${t}/v1/speech-to-text/realtime`}static buildWebSocketUri(t){let n=e.getWebSocketUri(t.baseUri),r=new URLSearchParams;if(r.append(`model_id`,t.modelId),r.append(`token`,t.token),t.commitStrategy!==void 0&&r.append(`commit_strategy`,t.commitStrategy),t.audioFormat!==void 0&&r.append(`audio_format`,t.audioFormat),t.vadSilenceThresholdSecs!==void 0){if(t.vadSilenceThresholdSecs<=.3||t.vadSilenceThresholdSecs>3)throw Error(`vadSilenceThresholdSecs must be between 0.3 and 3.0`);r.append(`vad_silence_threshold_secs`,t.vadSilenceThresholdSecs.toString())}if(t.vadThreshold!==void 0){if(t.vadThreshold<.1||t.vadThreshold>.9)throw Error(`vadThreshold must be between 0.1 and 0.9`);r.append(`vad_threshold`,t.vadThreshold.toString())}if(t.minSpeechDurationMs!==void 0){if(t.minSpeechDurationMs<=50||t.minSpeechDurationMs>2e3)throw Error(`minSpeechDurationMs must be between 50 and 2000`);r.append(`min_speech_duration_ms`,t.minSpeechDurationMs.toString())}if(t.minSilenceDurationMs!==void 0){if(t.minSilenceDurationMs<=50||t.minSilenceDurationMs>2e3)throw Error(`minSilenceDurationMs must be between 50 and 2000`);r.append(`min_silence_duration_ms`,t.minSilenceDurationMs.toString())}t.languageCode!==void 0&&r.append(`language_code`,t.languageCode),t.includeTimestamps!==void 0&&r.append(`include_timestamps`,t.includeTimestamps?`true`:`false`);let i=r.toString();return i?`${n}?${i}`:n}static connect(t){if(!t.modelId)throw Error(`modelId is required`);let n=new ch(`microphone`in t&&t.microphone?16e3:t.sampleRate),r=e.buildWebSocketUri(t),i=new WebSocket(r);return`microphone`in t&&t.microphone&&i.addEventListener(`open`,()=>{e.streamFromMicrophone(t,n)}),n.setWebSocket(i),n}static async streamFromMicrophone(e,t){try{var n,r,i;let a=await navigator.mediaDevices.getUserMedia({audio:{deviceId:e.microphone?.deviceId,echoCancellation:(n=e.microphone?.echoCancellation)==null||n,noiseSuppression:(r=e.microphone?.noiseSuppression)==null||r,autoGainControl:(i=e.microphone?.autoGainControl)==null||i,channelCount:e.microphone?.channelCount??1,sampleRate:{ideal:16e3}}}),o=new AudioContext({sampleRate:16e3});await lh(o.audioWorklet);let s=o.createMediaStreamSource(a),c=new AudioWorkletNode(o,`scribeAudioProcessor`);c.port.onmessage=e=>{let{audioData:n}=e.data,r=new Uint8Array(n),i=``;for(let e=0;e<r.length;e++)i+=String.fromCharCode(r[e]);let a=btoa(i);t.send({audioBase64:a})},s.connect(c),o.state===`suspended`&&await o.resume(),t._audioCleanup=()=>{a.getTracks().forEach(e=>{e.stop()}),s.disconnect(),c.disconnect(),o.close()}}catch(e){throw console.error(`Failed to start microphone streaming:`,e),e}}};fh.DEFAULT_BASE_URI=`wss://api.elevenlabs.io`;var ph=class extends Rm{static startSession(e){return e.textOnly?th.startSession(e):oh.startSession(e)}};function $(...e){Jt()&&console.log(`[FlowEngage:voice-tools]`,...e)}var mh=`#flowengage-root, .flowengage-shell`;function hh(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(mh)}catch{return!1}}function gh(e){if(e.labels&&e.labels.length)return e.labels[0].textContent?.trim()||null;let t=e.id;if(t)try{let e=document.querySelector(`label[for="${CSS.escape(t)}"]`);if(e)return e.textContent?.trim()||null}catch{let e=document.querySelector(`label[for="${t.replace(/"/g,`\\"`)}"]`);if(e)return e.textContent?.trim()||null}let n=e.parentElement;for(let e=0;e<4&&n;e+=1){if(n.tagName===`LABEL`)return n.textContent?.trim()||null;n=n.parentElement}return null}function _h(){return Array.from(document.querySelectorAll(`input, select, textarea`)).filter(e=>{if(hh(e))return!1;let t=(e.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`image`].includes(t)||e.disabled)return!1;try{let t=window.getComputedStyle(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0})}function vh(){return _h().map((e,t)=>({formIndex:0,fieldIndex:t,tag:e.tagName,type:e.type||`text`,name:e.name||null,id:e.id||null,label:gh(e),placeholder:e.placeholder||null}))}function yh(){return Array.from(document.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(hh(e)||e.disabled)return!1;try{let t=window.getComputedStyle(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}).slice(0,60).map((e,t)=>({index:t,text:(e.textContent||e.value||``).replace(/\s+/g,` `).trim().slice(0,120)||null,ariaLabel:e.getAttribute(`aria-label`),type:e.type||e.tagName}))}function bh(e,t){let n=String(t||``).toLowerCase().trim();if(!n)return 0;let r=[e.name,e.id,e.placeholder,gh(e),e.getAttribute(`aria-label`),e.getAttribute(`title`),e.getAttribute(`data-testid`)].filter(Boolean).map(e=>String(e).toLowerCase()),i=0;for(let e of r){if(!e)continue;if(e.includes(n)||n.includes(e)){i=Math.max(i,100);continue}let t=n.split(/\s+/).filter(e=>e.length>1);if(!t.length)continue;let r=0;for(let n of t)e.includes(n)&&(r+=1);i=Math.max(i,r/t.length*88)}return i}var xh=28;function Sh(e,t){let n=null,r=0;for(let i of e){let e=bh(i,t);e>r&&(r=e,n=i)}return!n||r<xh?null:n}function Ch(e,t,n){let r=String(t||``).toLowerCase().trim(),i=String(n||``).trim();if(!(/^https?:\/\//i.test(i)||/\.\w{2,}(\/|\s|$)/.test(i)||r.includes(`url`)||r.includes(`website`)||r.includes(`domain`)||r.includes(`site`)))return null;let a=null,o=0;for(let t of e){if(t.tagName!==`INPUT`&&t.tagName!==`TEXTAREA`)continue;let e=(t.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`checkbox`,`radio`].includes(e))continue;let n=0;(e===`url`||e===`text`||e===`search`)&&(n+=45);let r=[t.name,t.id,t.placeholder,gh(t),t.getAttribute(`aria-label`),t.getAttribute(`autocomplete`)].filter(Boolean).join(` `).toLowerCase();/(website|url|domain|site\s*url)/.test(r)&&(n+=55),n>o&&(o=n,a=t)}return!a||o<50?null:a}function wh(e,t){let n=String(t||``).toLowerCase().trim();if(!n)return 0;let r=[e.textContent,e.value,e.getAttribute(`aria-label`),e.getAttribute(`title`)].filter(Boolean).join(` `).toLowerCase().replace(/\s+/g,` `);if(r.includes(n))return 100;let i=n.split(/\s+/).filter(e=>e.length>1);if(!i.length)return 0;let a=0;for(let e of i)r.includes(e)&&(a+=1);return a/i.length*92}function Th(e){let t=Array.from(document.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(hh(e)||e.disabled)return!1;try{let t=window.getComputedStyle(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}),n=null,r=0;for(let i of t){let t=wh(i,e);t>r&&(r=t,n=i)}return!n||r<36?null:n}function Eh(e){if(e==null)return{};if(typeof e==`string`){let t=e.trim();if(!t)return{};try{return JSON.parse(t)}catch{return{url:t}}}return e}function Dh(e){if(!e||typeof e!=`object`)return null;let t=e.url??e.target_url??e.page_url??e.pageUrl??e.link??e.href??e.path;return t==null?null:String(t).trim()||null}function Oh(e){if(!e||typeof e!=`object`)return null;let t=e.query??e.q??e.search??e.text??e.keywords;return t==null?null:String(t).trim()||null}function kh(e,t){try{e.scrollIntoView({block:`center`,inline:`nearest`})}catch{try{e.scrollIntoView(!0)}catch{}}try{e.focus({preventScroll:!0})}catch{try{e.focus()}catch{}}let n=e.tagName,r=(e.type||``).toLowerCase();if(n===`SELECT`)return e.value=String(t),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;if(r===`checkbox`||r===`radio`)return e.checked=[`1`,`true`,`yes`,`on`].includes(String(t).toLowerCase().trim()),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;let i=String(t);if(n===`INPUT`||n===`TEXTAREA`){let t=n===`TEXTAREA`?window.HTMLTextAreaElement.prototype:window.HTMLInputElement.prototype,r=Object.getOwnPropertyDescriptor(t,`value`);r?.set?r.set.call(e,i):e.value=i}else e.value=i;try{e.dispatchEvent(new InputEvent(`input`,{bubbles:!0,cancelable:!0,inputType:`insertText`,data:i}))}catch{e.dispatchEvent(new Event(`input`,{bubbles:!0}))}return e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0}function Ah(e){let t=e.siteId||null,n=(e.apiBaseUrl||``).replace(/\/$/,``);return{navigate_to_page:async e=>{$(`navigate_to_page ▶ raw parameters:`,e);let t=Eh(e),n=Dh(t),r=t.section_text??t.sectionText??t.section;if($(`navigate_to_page · coerced:`,{url:n,sectionText:r}),!n){let e=`Missing url: pass a string url, path like /pricing, or JSON with a url field.`;return $(`navigate_to_page ✖`,e),e}try{if($(`navigate_to_page → shadowNavigate`,n),await tn(n),await new Promise(e=>setTimeout(e,400)),r&&typeof r==`string`){let e=Zt(null,r);e&&Qt(e),$(`navigate_to_page · highlight`,{sectionText:r,found:!!e})}let e=`OK_NAVIGATION ${n}`;return $(`navigate_to_page ✓`,e),e}catch(e){let t=`Navigation error: ${e?.message||String(e)}`;return $(`navigate_to_page ✖`,t),t}},highlight_on_page:async e=>{$(`highlight_on_page ▶`,e);let t=Eh(e),n=t?.section_id||t?.sectionId,r=t?.section_text||t?.sectionText,i=Zt(n||null,r||null);return i?(Qt(i),$(`highlight_on_page ✓`),`Highlighted the section.`):($(`highlight_on_page ✖ no element`),`Could not find that section on the page.`)},search_site_content:async e=>{$(`search_site_content ▶`,e);let r=Oh(Eh(e));if($(`search_site_content · query:`,r,`siteId:`,t,`apiBase:`,n||`(empty)`),!r)return $(`search_site_content ✖ missing query`),`Missing query parameter.`;if(!t)return $(`search_site_content ✖ no siteId`),`Site is not configured for search.`;if(!n)return $(`search_site_content ✖ no api base`),`API base URL is missing; cannot search.`;try{let e=`${n}/api/site-tools/search`;$(`search_site_content → POST`,e);let i=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,query:r,currentUrl:typeof window<`u`?window.location.href:``})}),a=await i.json();if($(`search_site_content · HTTP`,i.status,`success:`,a.success),!a.success){let e=a.error||`Search failed.`;return $(`search_site_content ✖`,e),e}let o=a.results||[];return $(`search_site_content ✓`,`${o.length} result(s)`,o.slice(0,3).map(e=>e?.url||e)),JSON.stringify(o)}catch(e){let t=`Search error: ${e.message||`network`}`;return $(`search_site_content ✖`,t),t}},list_page_forms:async()=>{let e=vh(),t=yh();return $(`list_page_forms ✓`,`${e.length} field(s)`,`${t.length} button(s)`),JSON.stringify({fields:e,buttons:t,hint:`field_key can be label text, placeholder (e.g. Enter Website URL), name, or id. After filling, use click_page_button with button_text (e.g. Conduct Audit) to submit.`})},fill_form_fields:async e=>{try{let t=Eh(e),n=t?.fields;if(!n&&Array.isArray(t)&&t.length>0&&t[0]?.field_key!=null&&(n=t),$(`fill_form_fields ▶`,{fieldCount:Array.isArray(n)?n.length:0}),!Array.isArray(n)||n.length===0)return`No fields provided. Use list_page_forms first.`;let r=[];for(let e of n){let t=e?.field_key??e?.fieldKey,n=e?.value;if(t==null||n==null)continue;let i=_h(),a=Sh(i,String(t));a||=Ch(i,String(t),n),a&&(kh(a,n),r.push(String(t)))}if(!r.length)return $(`fill_form_fields ✖ no matches`),`Could not match any fields. Call list_page_forms and use field_key values that match placeholder, label, name, or id (e.g. Enter Website URL). Ensure the form is on the page, not the chat panel.`;let i=`Filled fields: ${r.join(`, `)}`;return $(`fill_form_fields ✓`,i),i}catch(e){let t=`fill_form_fields error: ${e?.message||String(e)}`;return $(`fill_form_fields ✖`,t),t}},click_page_button:async e=>{let t=Eh(e),n=(t.button_text??t.buttonText??t.text??``).trim();if($(`click_page_button ▶`,n),!n)return`Missing button_text: pass the visible label, e.g. Conduct Audit.`;let r=Th(n);if(!r)return $(`click_page_button ✖ no match`),`Could not find a button matching "${n}". Call list_page_forms to see button texts.`;try{try{r.scrollIntoView({block:`center`,inline:`nearest`})}catch{r.scrollIntoView(!0)}r.focus?.(),r.click();let e=`OK_CLICK ${(r.textContent||r.value||r.getAttribute(`aria-label`)||``).trim().slice(0,80)||`button`}`;return $(`click_page_button ✓`,e),e}catch(e){let t=`Click failed: ${e?.message||String(e)}`;return $(`click_page_button ✖`,t),t}}}}var jh={idle:`rgba(99,102,241,0.18)`,listening:`rgba(16,185,129,0.25)`,speaking:`rgba(245,158,11,0.25)`,error:`rgba(239,68,68,0.2)`},Mh={idle:`#6366f1`,listening:`#10b981`,speaking:`#f59e0b`,error:`#ef4444`};function Nh({agentId:e,chatId:t,siteId:n,apiBaseUrl:r,onEnd:i,historyRef:a,hasSyncedRef:o,onMessageSync:s,onStartSync:c}){let[d,f]=(0,l.useState)(`idle`),[p,m]=(0,l.useState)(null),[h,ee]=(0,l.useState)(!1),[te,ne]=(0,l.useState)([]),re=(0,l.useRef)(null),ie=(0,l.useRef)(null);(0,l.useEffect)(()=>{let t=!1,i=null;return(async()=>{try{if(await navigator.mediaDevices.getUserMedia({audio:!0}),t)return;ne([]);let o=Ah({siteId:n||null,apiBaseUrl:r||null}),s=await ph.startSession({agentId:e,clientTools:o,onModeChange:({mode:e})=>{t||f(e===`speaking`?`speaking`:`listening`)},onMessage:e=>{if(t)return;let n=e.role===`user`?`user`:`bot`,r=e.message||e.text||e.content||``;if(!r)return;let i={sender:n,message:r,timestamp:new Date().toISOString()};a.current=[...a.current,i],ne(e=>[...e,i])},onError:e=>{t||(console.error(`[VoiceInterface] ElevenLabs error`,e),f(`error`),m(`Voice session encountered an error.`))},onDisconnect:()=>{t||(console.log(`[VoiceInterface] session disconnected`),ee(!1),f(`idle`))}});if(t){s.endSession().catch(()=>{});return}i=s,re.current=s,ee(!0),f(`listening`);try{let e=typeof window<`u`?window.location.href:``,t=``;try{t=await o.list_page_forms()}catch{t=`[]`}s.sendContextualUpdate(`Current page URL: ${e}. Site ID: ${n||`unknown`}. Page fields/buttons JSON: ${t}. Navigation: search_site_content then navigate_to_page with section_text when relevant — no permission ask. Forms: use fill_form_fields then click_page_button (e.g. Conduct Audit) when the user wants to submit.`)}catch{}typeof c==`function`&&c()}catch(e){t||(console.error(`[VoiceInterface] startSession failed`,e),f(`error`),m(`Could not start voice session. Please try again.`))}})(),()=>{t=!0,i?i.endSession().catch(()=>{}):re.current&&re.current.endSession().catch(()=>{})}},[e,n,r,a,c]);let g=(0,l.useCallback)(async()=>{try{await re.current?.endSession?.()}catch{}re.current=null,ee(!1),f(`idle`),typeof s==`function`&&await s(a.current),typeof i==`function`&&i()},[a,s,i]),ae=d===`listening`||d===`speaking`,oe=Mh[d]||Mh.idle,se=jh[d]||jh.idle;return(0,u.jsxs)(`div`,{ref:ie,style:{display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,flex:1,gap:`24px`,padding:`24px 20px`,background:`transparent`},children:[(0,u.jsxs)(`div`,{style:{position:`relative`,width:`140px`,height:`140px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:[ae&&(0,u.jsx)(`div`,{style:{position:`absolute`,inset:`-16px`,borderRadius:`50%`,border:`2px solid ${oe}`,animation:`fe-orb-pulse 1.4s ease-in-out infinite`,opacity:.6}}),ae&&(0,u.jsx)(`div`,{style:{position:`absolute`,inset:`-8px`,borderRadius:`50%`,border:`2px solid ${oe}`,animation:`fe-orb-pulse 1.4s ease-in-out 0.35s infinite`,opacity:.4}}),(0,u.jsx)(`div`,{style:{width:`140px`,height:`140px`,borderRadius:`50%`,background:se,border:`3px solid ${oe}`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`all 0.35s ease`,transform:d===`speaking`?`scale(1.08)`:`scale(1)`,boxShadow:`0 0 40px ${se}, 0 8px 32px rgba(0,0,0,0.08)`},children:(0,u.jsx)(dn,{size:44,color:oe})})]}),(0,u.jsxs)(`div`,{style:{fontSize:`15px`,fontWeight:600,color:d===`error`?`#ef4444`:`#374151`,letterSpacing:`0.01em`,textAlign:`center`},children:[d===`idle`&&`Starting voice session…`,d===`listening`&&`Listening…`,d===`speaking`&&`AI is speaking…`,d===`error`&&(p||`Error`)]}),te.length>0&&(0,u.jsx)(`div`,{style:{width:`100%`,maxHeight:`160px`,overflowY:`auto`,display:`flex`,flexDirection:`column`,gap:`8px`,padding:`0 4px`},children:te.map((e,t)=>(0,u.jsx)(`div`,{style:{display:`flex`,justifyContent:e.sender===`user`?`flex-end`:`flex-start`},children:(0,u.jsx)(`div`,{style:{maxWidth:`85%`,padding:`8px 12px`,borderRadius:`14px`,fontSize:`13px`,lineHeight:1.5,background:e.sender===`user`?`var(--flowengage-primary)`:`#f3f4f6`,color:e.sender===`user`?`#fff`:`#111827`},children:e.message})},t))}),(0,u.jsxs)(`button`,{onClick:g,style:{display:`flex`,alignItems:`center`,gap:`8px`,padding:`12px 24px`,borderRadius:`999px`,background:`#fee2e2`,color:`#dc2626`,border:`1px solid #fca5a5`,fontWeight:600,fontSize:`14px`,cursor:`pointer`,transition:`all 0.2s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`#fecaca`},onMouseLeave:e=>{e.currentTarget.style.background=`#fee2e2`},children:[(0,u.jsx)(fn,{size:18}),`End Voice Session`]}),(0,u.jsx)(`style`,{children:`
|
|
318
|
+
`),uh,dh;(function(e){e.PCM_8000=`pcm_8000`,e.PCM_16000=`pcm_16000`,e.PCM_22050=`pcm_22050`,e.PCM_24000=`pcm_24000`,e.PCM_44100=`pcm_44100`,e.PCM_48000=`pcm_48000`,e.ULAW_8000=`ulaw_8000`})(uh||={}),function(e){e.MANUAL=`manual`,e.VAD=`vad`}(dh||={});var fh=class e{static getWebSocketUri(t=e.DEFAULT_BASE_URI){return`${t}/v1/speech-to-text/realtime`}static buildWebSocketUri(t){let n=e.getWebSocketUri(t.baseUri),r=new URLSearchParams;if(r.append(`model_id`,t.modelId),r.append(`token`,t.token),t.commitStrategy!==void 0&&r.append(`commit_strategy`,t.commitStrategy),t.audioFormat!==void 0&&r.append(`audio_format`,t.audioFormat),t.vadSilenceThresholdSecs!==void 0){if(t.vadSilenceThresholdSecs<=.3||t.vadSilenceThresholdSecs>3)throw Error(`vadSilenceThresholdSecs must be between 0.3 and 3.0`);r.append(`vad_silence_threshold_secs`,t.vadSilenceThresholdSecs.toString())}if(t.vadThreshold!==void 0){if(t.vadThreshold<.1||t.vadThreshold>.9)throw Error(`vadThreshold must be between 0.1 and 0.9`);r.append(`vad_threshold`,t.vadThreshold.toString())}if(t.minSpeechDurationMs!==void 0){if(t.minSpeechDurationMs<=50||t.minSpeechDurationMs>2e3)throw Error(`minSpeechDurationMs must be between 50 and 2000`);r.append(`min_speech_duration_ms`,t.minSpeechDurationMs.toString())}if(t.minSilenceDurationMs!==void 0){if(t.minSilenceDurationMs<=50||t.minSilenceDurationMs>2e3)throw Error(`minSilenceDurationMs must be between 50 and 2000`);r.append(`min_silence_duration_ms`,t.minSilenceDurationMs.toString())}t.languageCode!==void 0&&r.append(`language_code`,t.languageCode),t.includeTimestamps!==void 0&&r.append(`include_timestamps`,t.includeTimestamps?`true`:`false`);let i=r.toString();return i?`${n}?${i}`:n}static connect(t){if(!t.modelId)throw Error(`modelId is required`);let n=new ch(`microphone`in t&&t.microphone?16e3:t.sampleRate),r=e.buildWebSocketUri(t),i=new WebSocket(r);return`microphone`in t&&t.microphone&&i.addEventListener(`open`,()=>{e.streamFromMicrophone(t,n)}),n.setWebSocket(i),n}static async streamFromMicrophone(e,t){try{var n,r,i;let a=await navigator.mediaDevices.getUserMedia({audio:{deviceId:e.microphone?.deviceId,echoCancellation:(n=e.microphone?.echoCancellation)==null||n,noiseSuppression:(r=e.microphone?.noiseSuppression)==null||r,autoGainControl:(i=e.microphone?.autoGainControl)==null||i,channelCount:e.microphone?.channelCount??1,sampleRate:{ideal:16e3}}}),o=new AudioContext({sampleRate:16e3});await lh(o.audioWorklet);let s=o.createMediaStreamSource(a),c=new AudioWorkletNode(o,`scribeAudioProcessor`);c.port.onmessage=e=>{let{audioData:n}=e.data,r=new Uint8Array(n),i=``;for(let e=0;e<r.length;e++)i+=String.fromCharCode(r[e]);let a=btoa(i);t.send({audioBase64:a})},s.connect(c),o.state===`suspended`&&await o.resume(),t._audioCleanup=()=>{a.getTracks().forEach(e=>{e.stop()}),s.disconnect(),c.disconnect(),o.close()}}catch(e){throw console.error(`Failed to start microphone streaming:`,e),e}}};fh.DEFAULT_BASE_URI=`wss://api.elevenlabs.io`;var ph=class extends Rm{static startSession(e){return e.textOnly?th.startSession(e):oh.startSession(e)}};function $(...e){Jt()&&console.log(`[FlowEngage:voice-tools]`,...e)}var mh=`#flowengage-root, .flowengage-shell`;function hh(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(mh)}catch{return!1}}function gh(e){try{let t=e.ownerDocument?.defaultView;if(t)return t.getComputedStyle(e)}catch{}return window.getComputedStyle(e)}function _h(e){let t=new Set;function n(r){if(!r||t.has(r))return;t.add(r),e(r);let i=r.querySelectorAll(`iframe`);for(let e of i)if(!hh(e))try{let t=e.contentDocument;t&&n(t)}catch{}}typeof document<`u`&&n(document)}function vh(e){let t=e.ownerDocument||document;if(e.labels&&e.labels.length)return e.labels[0].textContent?.trim()||null;let n=e.id;if(n)try{let e=t.querySelector(`label[for="${CSS.escape(n)}"]`);if(e)return e.textContent?.trim()||null}catch{let e=t.querySelector(`label[for="${n.replace(/"/g,`\\"`)}"]`);if(e)return e.textContent?.trim()||null}let r=e.parentElement;for(let e=0;e<4&&r;e+=1){if(r.tagName===`LABEL`)return r.textContent?.trim()||null;r=r.parentElement}return null}function yh(){let e=[];return _h(t=>{e.push(...Array.from(t.querySelectorAll(`input, select, textarea`)).filter(e=>{if(hh(e))return!1;let t=(e.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`image`].includes(t)||e.disabled)return!1;try{let t=gh(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e}function bh(){return yh().map((e,t)=>({formIndex:0,fieldIndex:t,tag:e.tagName,type:e.type||`text`,name:e.name||null,id:e.id||null,label:vh(e),placeholder:e.placeholder||null}))}function xh(){let e=[];return _h(t=>{e.push(...Array.from(t.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(hh(e)||e.disabled)return!1;try{let t=gh(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e.slice(0,60).map((e,t)=>({index:t,text:(e.textContent||e.value||``).replace(/\s+/g,` `).trim().slice(0,120)||null,ariaLabel:e.getAttribute(`aria-label`),type:e.type||e.tagName}))}function Sh(e,t){let n=String(t||``).toLowerCase().trim();if(!n)return 0;let r=(e.name||``).toLowerCase(),i=(e.id||``).toLowerCase();if(r===`url`&&/url|website|domain|site|audit/.test(n)||(i===`url-input`||i.endsWith(`-url-input`))&&/url|website|domain|site|audit/.test(n))return 100;let a=[e.name,e.id,e.placeholder,vh(e),e.getAttribute(`aria-label`),e.getAttribute(`title`),e.getAttribute(`data-testid`)].filter(Boolean).map(e=>String(e).toLowerCase()),o=0;for(let e of a){if(!e)continue;if(e.includes(n)||n.includes(e)){o=Math.max(o,100);continue}let t=n.split(/\s+/).filter(e=>e.length>1);if(!t.length)continue;let r=0;for(let n of t)e.includes(n)&&(r+=1);o=Math.max(o,r/t.length*88)}return o}var Ch=28;function wh(e,t){let n=null,r=0;for(let i of e){let e=Sh(i,t);e>r&&(r=e,n=i)}return!n||r<Ch?null:n}function Th(e,t,n){let r=String(t||``).toLowerCase().trim(),i=String(n||``).trim();if(!(/^https?:\/\//i.test(i)||/\.\w{2,}(\/|\s|$)/.test(i)||r.includes(`url`)||r.includes(`website`)||r.includes(`domain`)||r.includes(`site`)))return null;let a=null,o=0;for(let t of e){if(t.tagName!==`INPUT`&&t.tagName!==`TEXTAREA`)continue;let e=(t.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`checkbox`,`radio`].includes(e))continue;let n=0;(e===`url`||e===`text`||e===`search`)&&(n+=45);let r=[t.name,t.id,t.placeholder,vh(t),t.getAttribute(`aria-label`),t.getAttribute(`autocomplete`)].filter(Boolean).join(` `).toLowerCase();/(website|url|domain|site\s*url)/.test(r)&&(n+=55),n>o&&(o=n,a=t)}return!a||o<42?null:a}function Eh(e){if(!e||typeof e!=`string`)return null;let t=null;return _h(n=>{try{let r=n.getElementById(e);r&&!hh(r)&&r.matches?.(`input, select, textarea`)&&(t=r)}catch{}}),t}function Dh(e,t){let n=String(t??``).trim();if(!n)return null;let r=n.match(/^name:\s*([\w.-]+)$/i);if(r){let t=r[1];for(let n of e)if(n.name===t)return n}let i=n.match(/^id:\s*([\w.-]+)$/i);if(i){let e=Eh(i[1]);if(e)return e}let a=n.startsWith(`#`)?n.slice(1):n;if(/^[\w-]+$/.test(a)){let e=Eh(a);if(e)return e}let o=n.toLowerCase().replace(/\s+/g,` `);if(o===`url`||o===`website`||o===`website url`||o===`website_url`||o===`enter website url`)for(let t of e){let e=(t.name||``).toLowerCase(),n=(t.id||``).toLowerCase();if(e===`url`||n===`url-input`||n.endsWith(`-url-input`))return t}return null}function Oh(e,t){let n=String(t||``).toLowerCase().trim();if(!n)return 0;let r=[e.textContent,e.value,e.getAttribute(`aria-label`),e.getAttribute(`title`)].filter(Boolean).join(` `).toLowerCase().replace(/\s+/g,` `);if(r.includes(n))return 100;let i=n.split(/\s+/).filter(e=>e.length>1);if(!i.length)return 0;let a=0;for(let e of i)r.includes(e)&&(a+=1);return a/i.length*92}function kh(e){let t=[];_h(e=>{t.push(...Array.from(e.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(hh(e)||e.disabled)return!1;try{let t=gh(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))});let n=null,r=0;for(let i of t){let t=Oh(i,e);t>r&&(r=t,n=i)}return!n||r<36?null:n}function Ah(e){if(e==null)return{};if(typeof e==`string`){let t=e.trim();if(!t)return{};try{return JSON.parse(t)}catch{return{url:t}}}return e}function jh(e){if(!e||typeof e!=`object`)return null;let t=e.url??e.target_url??e.page_url??e.pageUrl??e.link??e.href??e.path;return t==null?null:String(t).trim()||null}function Mh(e){if(!e||typeof e!=`object`)return null;let t=e.query??e.q??e.search??e.text??e.keywords;return t==null?null:String(t).trim()||null}function Nh(e,t){try{e.scrollIntoView({block:`center`,inline:`nearest`})}catch{try{e.scrollIntoView(!0)}catch{}}try{e.focus({preventScroll:!0})}catch{try{e.focus()}catch{}}let n=e.tagName,r=(e.type||``).toLowerCase();if(n===`SELECT`)return e.value=String(t),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;if(r===`checkbox`||r===`radio`)return e.checked=[`1`,`true`,`yes`,`on`].includes(String(t).toLowerCase().trim()),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;let i=String(t);if(n===`INPUT`||n===`TEXTAREA`){let t=e.ownerDocument?.defaultView||window,r=n===`TEXTAREA`?t.HTMLTextAreaElement.prototype:t.HTMLInputElement.prototype,a=Object.getOwnPropertyDescriptor(r,`value`);a?.set?a.set.call(e,i):e.value=i}else e.value=i;try{e.dispatchEvent(new InputEvent(`input`,{bubbles:!0,cancelable:!0,inputType:`insertText`,data:i}))}catch{e.dispatchEvent(new Event(`input`,{bubbles:!0}))}return e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0}function Ph(e){let t=e.siteId||null,n=(e.apiBaseUrl||``).replace(/\/$/,``),r={navigate_to_page:async e=>{$(`navigate_to_page ▶ raw parameters:`,e);let t=Ah(e),n=jh(t),r=t.section_text??t.sectionText??t.section;if($(`navigate_to_page · coerced:`,{url:n,sectionText:r}),!n){let e=`Missing url: pass a string url, path like /pricing, or JSON with a url field.`;return $(`navigate_to_page ✖`,e),e}try{if($(`navigate_to_page → shadowNavigate`,n),await tn(n),await new Promise(e=>setTimeout(e,400)),r&&typeof r==`string`){let e=Zt(null,r);e&&Qt(e),$(`navigate_to_page · highlight`,{sectionText:r,found:!!e})}let e=`OK_NAVIGATION ${n}`;return $(`navigate_to_page ✓`,e),e}catch(e){let t=`Navigation error: ${e?.message||String(e)}`;return $(`navigate_to_page ✖`,t),t}},highlight_on_page:async e=>{$(`highlight_on_page ▶`,e);let t=Ah(e),n=t?.section_id||t?.sectionId,r=t?.section_text||t?.sectionText,i=Zt(n||null,r||null);return i?(Qt(i),$(`highlight_on_page ✓`),`Highlighted the section.`):($(`highlight_on_page ✖ no element`),`Could not find that section on the page.`)},search_site_content:async e=>{$(`search_site_content ▶`,e);let r=Mh(Ah(e));if($(`search_site_content · query:`,r,`siteId:`,t,`apiBase:`,n||`(empty)`),!r)return $(`search_site_content ✖ missing query`),`Missing query parameter.`;if(!t)return $(`search_site_content ✖ no siteId`),`Site is not configured for search.`;if(!n)return $(`search_site_content ✖ no api base`),`API base URL is missing; cannot search.`;try{let e=`${n}/api/site-tools/search`;$(`search_site_content → POST`,e);let i=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,query:r,currentUrl:typeof window<`u`?window.location.href:``})}),a=await i.json();if($(`search_site_content · HTTP`,i.status,`success:`,a.success),!a.success){let e=a.error||`Search failed.`;return $(`search_site_content ✖`,e),e}let o=a.results||[];return $(`search_site_content ✓`,`${o.length} result(s)`,o.slice(0,3).map(e=>e?.url||e)),JSON.stringify(o)}catch(e){let t=`Search error: ${e.message||`network`}`;return $(`search_site_content ✖`,t),t}},list_page_forms:async()=>{let e=bh(),t=xh();return $(`list_page_forms ✓`,`${e.length} field(s)`,`${t.length} button(s)`),JSON.stringify({fields:e,buttons:t,hint:`field_key: use placeholder/label text, name (e.g. url), id (e.g. url-input or #url-input), or name:url / id:url-input. Then click_page_button (e.g. Conduct Audit).`})},fill_form_fields:async e=>{try{let t=Ah(e),n=t?.fields;if(typeof n==`string`)try{n=JSON.parse(n)}catch{n=null}if(!n&&Array.isArray(t)&&t.length>0&&t[0]?.field_key!=null&&(n=t),!n&&Array.isArray(t)&&t.length>0&&t[0]?.fieldKey!=null&&(n=t.map(e=>({field_key:e.field_key??e.fieldKey,value:e.value}))),!n&&(t.field_key!=null||t.fieldKey!=null)&&t.value!=null&&(n=[{field_key:t.field_key??t.fieldKey,value:t.value}]),$(`fill_form_fields ▶`,{fieldCount:Array.isArray(n)?n.length:0}),!Array.isArray(n)||n.length===0)return`No fields provided. Use list_page_forms first.`;let r=[];for(let e of n){let t=e?.field_key??e?.fieldKey,n=e?.value;if(t==null||n==null)continue;let i=yh(),a=Dh(i,String(t));a||=wh(i,String(t)),a||=Th(i,String(t),n),a&&(Nh(a,n),r.push(String(t)))}if(!r.length)return $(`fill_form_fields ✖ no matches`),`Could not match any fields. Call list_page_forms and use field_key values that match placeholder, label, name, or id (e.g. Enter Website URL). Ensure the form is on the page, not the chat panel.`;let i=`OK_FILLED: ${r.join(`, `)}`;return $(`fill_form_fields ✓`,i),i}catch(e){let t=`fill_form_fields error: ${e?.message||String(e)}`;return $(`fill_form_fields ✖`,t),t}},click_page_button:async e=>{let t=Ah(e),n=(t.button_text??t.buttonText??t.text??``).trim();if($(`click_page_button ▶`,n),!n)return`Missing button_text: pass the visible label, e.g. Conduct Audit.`;let r=kh(n);if(!r)return $(`click_page_button ✖ no match`),`Could not find a button matching "${n}". Call list_page_forms to see button texts.`;try{try{r.scrollIntoView({block:`center`,inline:`nearest`})}catch{r.scrollIntoView(!0)}r.focus?.(),r.click();let e=`OK_CLICK ${(r.textContent||r.value||r.getAttribute(`aria-label`)||``).trim().slice(0,80)||`button`}`;return $(`click_page_button ✓`,e),e}catch(e){let t=`Click failed: ${e?.message||String(e)}`;return $(`click_page_button ✖`,t),t}}};return{...r,navigateToPage:r.navigate_to_page,highlightOnPage:r.highlight_on_page,searchSiteContent:r.search_site_content,listPageForms:r.list_page_forms,fillFormFields:r.fill_form_fields,clickPageButton:r.click_page_button}}var Fh={idle:`rgba(99,102,241,0.18)`,listening:`rgba(16,185,129,0.25)`,speaking:`rgba(245,158,11,0.25)`,error:`rgba(239,68,68,0.2)`},Ih={idle:`#6366f1`,listening:`#10b981`,speaking:`#f59e0b`,error:`#ef4444`};function Lh({agentId:e,chatId:t,siteId:n,apiBaseUrl:r,onEnd:i,historyRef:a,hasSyncedRef:o,onMessageSync:s,onStartSync:c}){let[d,f]=(0,l.useState)(`idle`),[p,m]=(0,l.useState)(null),[h,ee]=(0,l.useState)(!1),[te,ne]=(0,l.useState)([]),re=(0,l.useRef)(null),ie=(0,l.useRef)(null);(0,l.useEffect)(()=>{let t=!1,i=null;return(async()=>{try{if(await navigator.mediaDevices.getUserMedia({audio:!0}),t)return;ne([]);let o=Ph({siteId:n||null,apiBaseUrl:r||null}),s=await ph.startSession({agentId:e,clientTools:o,onUnhandledClientToolCall:e=>{console.error(`[VoiceInterface] ElevenLabs requested a client tool that is not registered in the widget:`,e?.tool_name,e?.parameters,`Add a matching handler in voiceClientTools (snake_case and camelCase are both supported).`)},onModeChange:({mode:e})=>{t||f(e===`speaking`?`speaking`:`listening`)},onMessage:e=>{if(t)return;let n=e.role===`user`?`user`:`bot`,r=e.message||e.text||e.content||``;if(!r)return;let i={sender:n,message:r,timestamp:new Date().toISOString()};a.current=[...a.current,i],ne(e=>[...e,i])},onError:e=>{t||(console.error(`[VoiceInterface] ElevenLabs error`,e),f(`error`),m(`Voice session encountered an error.`))},onDisconnect:()=>{t||(console.log(`[VoiceInterface] session disconnected`),ee(!1),f(`idle`))}});if(t){s.endSession().catch(()=>{});return}i=s,re.current=s,ee(!0),f(`listening`);try{let e=typeof window<`u`?window.location.href:``,t=``;try{t=await o.list_page_forms()}catch{t=`[]`}s.sendContextualUpdate(`Current page URL: ${e}. Site ID: ${n||`unknown`}. Page fields/buttons JSON: ${t}. Navigation: search_site_content then navigate_to_page with section_text when relevant — no permission ask. Forms: use fill_form_fields then click_page_button (e.g. Conduct Audit) when the user wants to submit.`)}catch{}typeof c==`function`&&c()}catch(e){t||(console.error(`[VoiceInterface] startSession failed`,e),f(`error`),m(`Could not start voice session. Please try again.`))}})(),()=>{t=!0,i?i.endSession().catch(()=>{}):re.current&&re.current.endSession().catch(()=>{})}},[e,n,r,a,c]);let g=(0,l.useCallback)(async()=>{try{await re.current?.endSession?.()}catch{}re.current=null,ee(!1),f(`idle`),typeof s==`function`&&await s(a.current),typeof i==`function`&&i()},[a,s,i]),ae=d===`listening`||d===`speaking`,oe=Ih[d]||Ih.idle,se=Fh[d]||Fh.idle;return(0,u.jsxs)(`div`,{ref:ie,style:{display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,flex:1,gap:`24px`,padding:`24px 20px`,background:`transparent`},children:[(0,u.jsxs)(`div`,{style:{position:`relative`,width:`140px`,height:`140px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:[ae&&(0,u.jsx)(`div`,{style:{position:`absolute`,inset:`-16px`,borderRadius:`50%`,border:`2px solid ${oe}`,animation:`fe-orb-pulse 1.4s ease-in-out infinite`,opacity:.6}}),ae&&(0,u.jsx)(`div`,{style:{position:`absolute`,inset:`-8px`,borderRadius:`50%`,border:`2px solid ${oe}`,animation:`fe-orb-pulse 1.4s ease-in-out 0.35s infinite`,opacity:.4}}),(0,u.jsx)(`div`,{style:{width:`140px`,height:`140px`,borderRadius:`50%`,background:se,border:`3px solid ${oe}`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`all 0.35s ease`,transform:d===`speaking`?`scale(1.08)`:`scale(1)`,boxShadow:`0 0 40px ${se}, 0 8px 32px rgba(0,0,0,0.08)`},children:(0,u.jsx)(dn,{size:44,color:oe})})]}),(0,u.jsxs)(`div`,{style:{fontSize:`15px`,fontWeight:600,color:d===`error`?`#ef4444`:`#374151`,letterSpacing:`0.01em`,textAlign:`center`},children:[d===`idle`&&`Starting voice session…`,d===`listening`&&`Listening…`,d===`speaking`&&`AI is speaking…`,d===`error`&&(p||`Error`)]}),te.length>0&&(0,u.jsx)(`div`,{style:{width:`100%`,maxHeight:`160px`,overflowY:`auto`,display:`flex`,flexDirection:`column`,gap:`8px`,padding:`0 4px`},children:te.map((e,t)=>(0,u.jsx)(`div`,{style:{display:`flex`,justifyContent:e.sender===`user`?`flex-end`:`flex-start`},children:(0,u.jsx)(`div`,{style:{maxWidth:`85%`,padding:`8px 12px`,borderRadius:`14px`,fontSize:`13px`,lineHeight:1.5,background:e.sender===`user`?`var(--flowengage-primary)`:`#f3f4f6`,color:e.sender===`user`?`#fff`:`#111827`},children:e.message})},t))}),(0,u.jsxs)(`button`,{onClick:g,style:{display:`flex`,alignItems:`center`,gap:`8px`,padding:`12px 24px`,borderRadius:`999px`,background:`#fee2e2`,color:`#dc2626`,border:`1px solid #fca5a5`,fontWeight:600,fontSize:`14px`,cursor:`pointer`,transition:`all 0.2s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`#fecaca`},onMouseLeave:e=>{e.currentTarget.style.background=`#fee2e2`},children:[(0,u.jsx)(fn,{size:18}),`End Voice Session`]}),(0,u.jsx)(`style`,{children:`
|
|
319
319
|
@keyframes fe-orb-pulse {
|
|
320
320
|
0% { transform: scale(1); opacity: 0.6; }
|
|
321
321
|
50% { transform: scale(1.18); opacity: 0.15; }
|
|
322
322
|
100% { transform: scale(1); opacity: 0.6; }
|
|
323
323
|
}
|
|
324
|
-
`})]})}var
|
|
324
|
+
`})]})}var Rh=[{key:`become_client`,label:`Become a Client`},{key:`sales_enquiry`,label:`Sales Enquiry`},{key:`learn_services`,label:`Learn about our Services`},{key:`get_support`,label:`Get Support`},{key:`looking_for_job`,label:`Looking for a Job`}],zh=()=>(0,u.jsx)(`div`,{style:{display:`flex`,marginBottom:`12px`,justifyContent:`flex-start`},children:(0,u.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`5px`,padding:`12px 16px`,borderRadius:`18px`,background:`#fff`,color:`#111827`,boxShadow:`0 2px 6px rgba(0,0,0,0.04)`},children:[[0,1,2].map(e=>(0,u.jsx)(`span`,{style:{width:`7px`,height:`7px`,borderRadius:`50%`,background:`#9ca3af`,animation:`fe-dot-bounce 1.2s ease-in-out ${e*.2}s infinite`,display:`inline-block`}},e)),(0,u.jsx)(`style`,{children:`
|
|
325
325
|
@keyframes fe-dot-bounce {
|
|
326
326
|
0%, 80%, 100% { transform: translateY(0); opacity: 0.5; }
|
|
327
327
|
40% { transform: translateY(-5px); opacity: 1; }
|
|
328
328
|
}
|
|
329
|
-
`})]})});function
|
|
329
|
+
`})]})});function Bh(){let{status:e,runtimeConfig:t,resolvedConfig:n,chatId:r,chatHistory:i,isOpen:a,activeScreen:o,isHumanHandled:s,agentName:c,visitorEmail:d,isAgentTyping:f,isAiTyping:p,isLoading:m,isVoiceMode:h,isRateLimited:ee,rateLimitMessage:te,isConversationEnded:ne,incomingCall:re,activeCallId:ie,callConnectionState:g,callConnectedAt:ae,isCallMuted:oe,webRTCError:se,language:_,historyRef:v,onMessageSync:ce,endConversation:le,acceptCall:ue,rejectCall:de,endWebRTCCall:fe,toggleCallMute:pe,dismissCallError:me,captureVisitorEmail:he,openWidget:ge,closeWidget:_e,sendMessage:ve,setVoiceMode:ye,startTyping:be,stopTyping:xe,updateTypingDraft:Se}=qt(),[Ce,we]=(0,l.useState)(``),[Te,Ee]=(0,l.useState)(null),[De,Oe]=(0,l.useState)(null),[ke,Ae]=(0,l.useState)(null),[je,y]=(0,l.useState)(0),[Me,Ne]=(0,l.useState)(d||``),[Pe,b]=(0,l.useState)(``),Fe=t?.widgetSettings||{},Ie=n?.widgetSettings||{},Le={...Fe.branding||{},...Ie.branding||{}},Re={...Fe.theme||{},...Ie.theme||{}},ze=Re.primaryColor||`#3B82F6`,Be=Re.accentColor||`#1D4ED8`,Ve=(Re.position||`bottom-right`)===`bottom-left`?{left:`1.5rem`,bottom:`1.5rem`}:{right:`1.5rem`,bottom:`1.5rem`},He={"--flowengage-primary":ze,"--flowengage-accent":Be,position:`fixed`,zIndex:999999,border:`none`,outline:`none`,fontFamily:`ui-sans-serif, system-ui, sans-serif`,...a?{}:Ve},Ue=Ie.recommendations?.[_]||Fe.recommendations?.[_]||Rh,We=Ie.greetings?.[_]||Fe.greetings?.[_],Ge=Le.chatButtonText||`Chat with us`,x=Le.headerName||t?.websiteName||`OpenSense Labs`,S=Le.logoUrl||null,C=Le.hideWatermark||!1,Ke=Ie.elevenLabsAgentId||t?.elevenLabsAgentId||null,qe=t?.siteId||n?.siteId||null,Je=t?.apiBaseUrl||``,Ye=Le.fallbackAgentName||`Agent`,Xe=Le.botLabel||`AI`,Ze=re?.agentName||c||Ye,Qe=!d&&i.length===0;(0,l.useEffect)(()=>{Ne(d||``),d&&b(``)},[d]),(0,l.useEffect)(()=>{if(!ae||g!==`connected`){y(0);return}let e=()=>{let e=new Date(ae).getTime();isNaN(e)||y(Math.max(0,Math.floor((Date.now()-e)/1e3)))};e();let t=window.setInterval(e,1e3);return()=>window.clearInterval(t)},[ae,g]),(0,l.useEffect)(()=>{if(!s||h||ne){Se(``),xe();return}if(!Ce.trim()){Se(``),xe();return}be();let e=window.setTimeout(()=>{Se(Ce)},120),t=window.setTimeout(()=>{xe()},1200);return()=>{window.clearTimeout(e),window.clearTimeout(t)}},[Ce,s,h,ne,be,xe,Se]);let $e=e=>e?{replyTo:e.messageId||e.id||null,replyToContent:(e.replyToContent||e.message||``).replace(/<[^>]+>/g,``).trim().slice(0,200),replyToSender:e.sender||null}:null,et=async e=>{if(e.preventDefault(),ne)return;if(Qe){let e=Me.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)){b(`Please enter a valid email to start the chat.`);return}await he(e),b(``);return}if(!Ce.trim())return;let t=Ce.trim(),n=$e(ke);we(``),Ae(null),await ve(t,``,n)},tt=async()=>{if(Qe){b(`Please share your email before starting a call.`);return}if(h){ye(!1);return}Oe(null);try{Ee(await navigator.mediaDevices.getUserMedia({audio:!0})),ye(!0)}catch(e){Oe(e.message||`Could not access microphone.`)}},nt=()=>{Te&&(Te.getTracks().forEach(e=>e.stop()),Ee(null)),ye(!1)},rt=e=>{let t=Math.floor(e/60),n=e%60;return`${t.toString().padStart(2,`0`)}:${n.toString().padStart(2,`0`)}`};return e===`ready`?(0,u.jsxs)(`div`,{className:`flowengage-shell`,"data-open":a?`true`:`false`,style:He,children:[(0,u.jsx)(yn,{isOpen:a,openWidget:ge,launcherText:Ge,primaryColor:ze,posInline:Ve}),a&&(0,u.jsxs)(`div`,{className:`flowengage-chat-panel`,style:{background:i.length===0&&!h?`linear-gradient(to bottom, ${ze} 0%, ${ze} 70%, white 85%)`:`white`},children:[(0,u.jsx)(Sn,{logoUrl:S,brandName:x,agentName:c,fallbackAgentName:Ye,activeScreen:o,branding:Le,isConversationEnded:ne,endConversation:le,closeWidget:_e,isInitial:i.length===0&&!h,botLabel:Xe}),(0,u.jsx)(`div`,{style:{flex:1,overflowY:`auto`,display:`flex`,flexDirection:`column`},className:`flowengage-content-wrapper`,children:h?(0,u.jsx)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`},className:`fe-screen-fade-in`,children:(0,u.jsx)(Lh,{agentId:Ke,chatId:r,siteId:qe,apiBaseUrl:Je,historyRef:v,onMessageSync:ce,onEnd:nt})},`voice`):i.length===0?(0,u.jsx)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`},className:`fe-screen-fade-in`,children:(0,u.jsx)(Dn,{greetings:We,recommendations:Ue,onSendMessage:ve,visitorEmail:d,emailInput:Me,setEmailInput:Ne,emailError:Pe,setEmailError:b,onCaptureEmail:he,botLabel:Xe})},`welcome`):(0,u.jsx)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`},className:`fe-screen-fade-in`,children:(0,u.jsx)(En,{chatHistory:i,isAiTyping:p,isAgentTyping:f,setReplyContext:Ae,TypingDots:zh})},`history`)}),(0,u.jsx)(jn,{webRTCError:se,micError:De,setMicError:Oe,dismissCallError:me,incomingCall:re,rejectCall:de,acceptCall:ue,activeCallId:ie,callConnectionState:g,formatCallDuration:rt,callDurationSeconds:je,endWebRTCCall:fe,isCallMuted:oe,toggleCallMute:pe,isAIVoiceActive:h,currentCallAgentName:Ze,isRateLimited:ee,rateLimitMessage:te}),!h&&(0,u.jsx)(`div`,{style:{position:`relative`,zIndex:1},children:(0,u.jsx)(On,{input:Ce,setInput:we,onSubmit:et,isConversationEnded:ne,callUiActive:!!(re||ie),handleToggleVoice:tt,activeScreen:o,inputDisabled:m||ee||ne,replyContext:ke,clearReplyContext:()=>Ae(null),requiresEmail:Qe,emailInput:Me,setEmailInput:Ne,emailError:Pe})}),!C&&(0,u.jsx)(`div`,{style:{position:`relative`,zIndex:1,display:`flex`,alignItems:`center`,justifyContent:`center`,gap:`12px`,paddingTop:`12px`,paddingBottom:`16px`,fontSize:`12px`,color:`#9ca3af`},children:(0,u.jsxs)(`div`,{children:[`Powered by `,(0,u.jsx)(`span`,{style:{color:`#3b82f6`},children:`Flow`}),(0,u.jsx)(`span`,{style:{color:`#ef4444`},children:`Engage`})]})})]})]}):null}exports.FlowEngageProvider=ln,exports.FlowEngageWidget=Bh,exports.useFlowEngage=qt;
|