@flowengage/react-chatbot 0.2.12 → 0.2.15
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
CHANGED
|
@@ -323,16 +323,16 @@ class ScribeAudioProcessor extends AudioWorkletProcessor {
|
|
|
323
323
|
|
|
324
324
|
registerProcessor("scribeAudioProcessor", ScribeAudioProcessor);
|
|
325
325
|
|
|
326
|
-
`),bh,xh;(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`})(bh||={}),function(e){e.MANUAL=`manual`,e.VAD=`vad`}(xh||={});var Sh=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 vh(`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 yh(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}}};Sh.DEFAULT_BASE_URI=`wss://api.elevenlabs.io`;var Ch=class extends Jm{static startSession(e){return e.textOnly?dh.startSession(e):gh.startSession(e)}};function wh(...e){$t()&&console.log(`[FlowEngage:voice-tools]`,...e)}var Th=`#flowengage-root, .flowengage-shell`;function Eh(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(Th)}catch{return!1}}function Dh(e){try{let t=e.ownerDocument?.defaultView;if(t)return t.getComputedStyle(e)}catch{}return window.getComputedStyle(e)}function Oh(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(!Eh(e))try{let t=e.contentDocument;t&&n(t)}catch{}}typeof document<`u`&&n(document)}function kh(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 Ah(){let e=[];return Oh(t=>{e.push(...Array.from(t.querySelectorAll(`input, select, textarea`)).filter(e=>{if(Eh(e))return!1;let t=(e.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`image`].includes(t)||e.disabled)return!1;try{let t=Dh(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e}function jh(){return Ah().map((e,t)=>({formIndex:0,fieldIndex:t,tag:e.tagName,type:e.type||`text`,name:e.name||null,id:e.id||null,label:kh(e),placeholder:e.placeholder||null}))}function Mh(){let e=[];return Oh(t=>{e.push(...Array.from(t.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(Eh(e)||e.disabled)return!1;try{let t=Dh(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 Nh(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,kh(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 Ph=28;function Fh(e,t){let n=null,r=0;for(let i of e){let e=Nh(i,t);e>r&&(r=e,n=i)}return!n||r<Ph?null:n}function Ih(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,kh(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 Lh(e){if(!e||typeof e!=`string`)return null;let t=null;return Oh(n=>{try{let r=n.getElementById(e);r&&!Eh(r)&&r.matches?.(`input, select, textarea`)&&(t=r)}catch{}}),t}function Rh(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=Lh(i[1]);if(e)return e}let a=n.startsWith(`#`)?n.slice(1):n;if(/^[\w-]+$/.test(a)){let e=Lh(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 zh(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 Bh(e){let t=[];Oh(e=>{t.push(...Array.from(e.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(Eh(e)||e.disabled)return!1;try{let t=Dh(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=zh(i,e);t>r&&(r=t,n=i)}return!n||r<36?null:n}function Vh(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 Hh(e){let t=Vh(e);if(Array.isArray(t)&&t.length>0){let e=t[0];if(e?.field_key!=null||e?.fieldKey!=null)return t.map(e=>({field_key:e.field_key??e.fieldKey,value:e.value}))}if(!t||typeof t!=`object`)return[];let n=t.fields??t.Fields??t.field_list??t.fieldList??t.data?.fields;if(typeof n==`string`)try{n=JSON.parse(n)}catch{n=null}n&&!Array.isArray(n)&&typeof n==`object`&&(n=Object.values(n)),(!n||n.length===0)&&(t.field_key!=null||t.fieldKey!=null)&&t.value!=null&&(n=[{field_key:t.field_key??t.fieldKey,value:t.value}]);let r=t.website_url??t.websiteUrl??t.url??t.website??t.domain??t.site_url??t.siteUrl;return(!n||n.length===0)&&r!=null&&String(r).trim()&&(n=[{field_key:t.field_key??t.fieldKey??`url`,value:String(r).trim()}]),Array.isArray(n)?n.map(e=>({field_key:e?.field_key??e?.fieldKey,value:e?.value??e?.Value})):[]}function Uh(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 Wh(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 Gh(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;let a={bubbles:!0,cancelable:!0,composed:!0};try{e.dispatchEvent(new InputEvent(`input`,{...a,inputType:`insertText`,data:i}))}catch{e.dispatchEvent(new Event(`input`,a))}e.dispatchEvent(new Event(`change`,a));try{queueMicrotask(()=>{try{e.dispatchEvent(new Event(`input`,a)),e.dispatchEvent(new Event(`change`,a))}catch{}})}catch{}return!0}function Kh(e){let t=e.siteId||null,n=(e.apiBaseUrl||``).replace(/\/$/,``),r={navigate_to_page:async e=>{wh(`navigate_to_page ▶ raw parameters:`,e);let t=Vh(e),n=Uh(t),r=t.section_text??t.sectionText??t.section;if(wh(`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 wh(`navigate_to_page ✖`,e),e}try{if(wh(`navigate_to_page → shadowNavigate`,n),await sn(n),await new Promise(e=>setTimeout(e,400)),r&&typeof r==`string`){let e=nn(null,r);e&&rn(e),wh(`navigate_to_page · highlight`,{sectionText:r,found:!!e})}let e=`OK_NAVIGATION ${n}`;return wh(`navigate_to_page ✓`,e),e}catch(e){let t=`Navigation error: ${e?.message||String(e)}`;return wh(`navigate_to_page ✖`,t),t}},highlight_on_page:async e=>{wh(`highlight_on_page ▶`,e);let t=Vh(e),n=t?.section_id||t?.sectionId,r=t?.section_text||t?.sectionText,i=nn(n||null,r||null);return i?(rn(i),wh(`highlight_on_page ✓`),`Highlighted the section.`):(wh(`highlight_on_page ✖ no element`),`Could not find that section on the page.`)},search_site_content:async e=>{wh(`search_site_content ▶`,e);let r=Wh(Vh(e));if(wh(`search_site_content · query:`,r,`siteId:`,t,`apiBase:`,n||`(empty)`),!r)return wh(`search_site_content ✖ missing query`),`Missing query parameter.`;if(!t)return wh(`search_site_content ✖ no siteId`),`Site is not configured for search.`;if(!n)return wh(`search_site_content ✖ no api base`),`API base URL is missing; cannot search.`;try{let e=`${n}/api/site-tools/search`;wh(`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(wh(`search_site_content · HTTP`,i.status,`success:`,a.success),!a.success){let e=a.error||`Search failed.`;return wh(`search_site_content ✖`,e),e}let o=a.results||[];return wh(`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 wh(`search_site_content ✖`,t),t}},list_page_forms:async()=>{let e=jh(),t=Mh();return wh(`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{wh(`fill_form_fields ▶ raw:`,e);let t=Hh(e);if(wh(`fill_form_fields · normalized fields:`,t),!t.length)return`No fields provided. Call list_page_forms, then fill_form_fields with { "fields": [ { "field_key": "url or Enter Website URL", "value": "https://..." } ] }.`;let n=[];for(let e of t){let t=e?.field_key??e?.fieldKey,r=e?.value;if(t==null||r==null)continue;let i=Ah(),a=Rh(i,String(t));a||=Fh(i,String(t)),a||=Ih(i,String(t),r),a&&(Gh(a,r),n.push(String(t)))}if(!n.length)return wh(`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 r=`OK_FILLED: ${n.join(`, `)}`;return wh(`fill_form_fields ✓`,r),r}catch(e){let t=`fill_form_fields error: ${e?.message||String(e)}`;return wh(`fill_form_fields ✖`,t),t}},click_page_button:async e=>{let t=Vh(e),n=(t.button_text??t.buttonText??t.text??``).trim();if(wh(`click_page_button ▶`,n),!n)return`Missing button_text: pass the visible label, e.g. Conduct Audit.`;let r=Bh(n);if(!r)return wh(`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 wh(`click_page_button ✓`,e),e}catch(e){let t=`Click failed: ${e?.message||String(e)}`;return wh(`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}}function qh(e){return!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,async n=>{let r=$t();r?console.log(`[FlowEngage:voice-tool] ▶`,e,n):console.info(`[FlowEngage] voice tool » ${e}`);let i=await t(n),a=typeof i==`string`?i.length>220?`${i.slice(0,220)}…`:i:String(i);return r?console.log(`[FlowEngage:voice-tool] ◀`,e,a):console.info(`[FlowEngage] voice tool « ${e}:`,a),i}]))}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)`},Yh={idle:`#6366f1`,listening:`#10b981`,speaking:`#f59e0b`,error:`#ef4444`};function Xh({agentId:e,chatId:t,siteId:n,apiBaseUrl:r,onEnd:i,historyRef:a,hasSyncedRef:o,onMessageSync:s,onStartSync:c}){let[l,u]=(0,v.useState)(`idle`),[d,f]=(0,v.useState)(null),[p,m]=(0,v.useState)(!1),[h,g]=(0,v.useState)([]),_=(0,v.useRef)(null),y=(0,v.useRef)(null);(0,v.useEffect)(()=>{let t=!1,i=null;return(async()=>{try{if(await navigator.mediaDevices.getUserMedia({audio:!0}),t)return;g([]);let o=qh(Kh({siteId:n||null,apiBaseUrl:r||null})),s=await Ch.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||u(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],g(e=>[...e,i])},onError:e=>{t||(console.error(`[VoiceInterface] ElevenLabs error`,e),u(`error`),f(`Voice session encountered an error.`))},onDisconnect:()=>{t||(console.log(`[VoiceInterface] session disconnected`),m(!1),u(`idle`))}});if(t){s.endSession().catch(()=>{});return}i=s,_.current=s,m(!0),u(`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),u(`error`),f(`Could not start voice session. Please try again.`))}})(),()=>{t=!0,i?i.endSession().catch(()=>{}):_.current&&_.current.endSession().catch(()=>{})}},[e,n,r,a,c]);let b=(0,v.useCallback)(async()=>{try{await _.current?.endSession?.()}catch{}_.current=null,m(!1),u(`idle`),typeof s==`function`&&await s(a.current),typeof i==`function`&&i()},[a,s,i]),x=l===`listening`||l===`speaking`,ee=Yh[l]||Yh.idle,te=Jh[l]||Jh.idle;return(0,k.jsxs)(`div`,{ref:y,style:{display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,flex:1,gap:`24px`,padding:`24px 20px`,background:`transparent`},children:[(0,k.jsxs)(`div`,{style:{position:`relative`,width:`140px`,height:`140px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:[x&&(0,k.jsx)(`div`,{style:{position:`absolute`,inset:`-16px`,borderRadius:`50%`,border:`2px solid ${ee}`,animation:`fe-orb-pulse 1.4s ease-in-out infinite`,opacity:.6}}),x&&(0,k.jsx)(`div`,{style:{position:`absolute`,inset:`-8px`,borderRadius:`50%`,border:`2px solid ${ee}`,animation:`fe-orb-pulse 1.4s ease-in-out 0.35s infinite`,opacity:.4}}),(0,k.jsx)(`div`,{style:{width:`140px`,height:`140px`,borderRadius:`50%`,background:te,border:`3px solid ${ee}`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`all 0.35s ease`,transform:l===`speaking`?`scale(1.08)`:`scale(1)`,boxShadow:`0 0 40px ${te}, 0 8px 32px rgba(0,0,0,0.08)`},children:(0,k.jsx)(_n,{size:44,color:ee})})]}),(0,k.jsxs)(`div`,{style:{fontSize:`15px`,fontWeight:600,color:l===`error`?`#ef4444`:`#374151`,letterSpacing:`0.01em`,textAlign:`center`},children:[l===`idle`&&`Starting voice session…`,l===`listening`&&`Listening…`,l===`speaking`&&`AI is speaking…`,l===`error`&&(d||`Error`)]}),h.length>0&&(0,k.jsx)(`div`,{style:{width:`100%`,maxHeight:`160px`,overflowY:`auto`,display:`flex`,flexDirection:`column`,gap:`8px`,padding:`0 4px`},children:h.map((e,t)=>(0,k.jsx)(`div`,{style:{display:`flex`,justifyContent:e.sender===`user`?`flex-end`:`flex-start`},children:(0,k.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,k.jsxs)(`button`,{onClick:b,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,k.jsx)(vn,{size:18}),`End Voice Session`]}),(0,k.jsx)(`style`,{children:`
|
|
326
|
+
`),bh,xh;(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`})(bh||={}),function(e){e.MANUAL=`manual`,e.VAD=`vad`}(xh||={});var Sh=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 vh(`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 yh(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}}};Sh.DEFAULT_BASE_URI=`wss://api.elevenlabs.io`;var Ch=class extends Jm{static startSession(e){return e.textOnly?dh.startSession(e):gh.startSession(e)}};function wh(...e){$t()&&console.log(`[FlowEngage:voice-tools]`,...e)}var Th=`#flowengage-root, .flowengage-shell`;function Eh(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(Th)}catch{return!1}}function Dh(e){try{let t=e.ownerDocument?.defaultView;if(t)return t.getComputedStyle(e)}catch{}return window.getComputedStyle(e)}function Oh(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(!Eh(e))try{let t=e.contentDocument;t&&n(t)}catch{}}typeof document<`u`&&n(document)}function kh(e){return e==null?null:String(e).replace(/\u00a0/g,` `).replace(/\s*\*+\s*$/u,``).replace(/\s+/g,` `).trim()}function Ah(e){let t=e.ownerDocument||document,n=e.getAttribute(`aria-labelledby`);if(n){let e=n.trim().split(/\s+/).filter(Boolean),r=[];for(let n of e)try{let e=t.getElementById(n);e?.textContent&&r.push(e.textContent.trim())}catch{}if(r.length)return kh(r.join(` `))}if(e.labels&&e.labels.length)return kh(e.labels[0].textContent);let r=e.id;if(r)try{let e=t.querySelector(`label[for="${CSS.escape(r)}"]`);if(e)return kh(e.textContent)}catch{let e=t.querySelector(`label[for="${r.replace(/"/g,`\\"`)}"]`);if(e)return kh(e.textContent)}let i=e.previousElementSibling;for(let e=0;e<6&&i;e+=1){if(i.tagName===`LABEL`)return kh(i.textContent);let e=(i.className||``).toString().toLowerCase();if(/chakra-form__label|formlabel|field-label|form-label|mui-form-label/.test(e)){let e=kh(i.textContent);if(e)return e}i=i.previousElementSibling}let a=e.parentElement;for(let e=0;e<5&&a;e+=1){if(a.tagName===`LABEL`)return kh(a.textContent);let e=a.querySelector?.(`:scope > label, :scope > [class*='FormLabel'], :scope > [class*='form__label']`);if(e?.textContent)return kh(e.textContent);a=a.parentElement}let o=e.getAttribute(`aria-label`);return o?kh(o):null}function jh(){let e=[];return Oh(t=>{e.push(...Array.from(t.querySelectorAll(`input, select, textarea`)).filter(e=>{if(Eh(e))return!1;let t=(e.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`image`].includes(t)||e.disabled||e.readOnly)return!1;try{let t=Dh(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e}function Mh(){return jh().map((e,t)=>({formIndex:0,fieldIndex:t,tag:e.tagName,type:e.type||`text`,name:e.name||null,id:e.id||null,label:Ah(e),placeholder:e.placeholder||null}))}function Nh(){let e=[];return Oh(t=>{e.push(...Array.from(t.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(Eh(e)||e.disabled)return!1;try{let t=Dh(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 Ph(e){return String(e||``).toLowerCase().replace(/\u00a0/g,` `).replace(/\*/g,``).replace(/\s+/g,` `).trim()}function Fh(e){let t=Ph(e);return t=t.replace(/\s+field\s*$/i,``).trim(),t}function Ih(e,t){let n=Fh(t);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,Ah(e),e.getAttribute(`aria-label`),e.getAttribute(`title`),e.getAttribute(`data-testid`),e.getAttribute(`autocomplete`)].filter(Boolean).map(e=>Ph(e)),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 Lh=28;function Rh(e,t){let n=null,r=0;for(let i of e){let e=Ih(i,t);e>r&&(r=e,n=i)}return!n||r<Lh?null:n}function zh(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,Ah(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 Bh(e){let t=String(e??``).trim();return t?/^https?:\/\//i.test(t)?!0:/\.\w{2,}(\/|\s|$)/.test(t):!1}function Vh(e){let t=String(e??``).toLowerCase().trim();return t?!!(t===`url`||t===`website`||t===`website url`||t===`website_url`||t===`enter website url`||t.includes(`website`)||t.includes(`domain`)||/(enter\s+website|site\s*url|page\s*url)/.test(t)):!1}function Hh(e){if(!e||e.tagName!==`INPUT`&&e.tagName!==`TEXTAREA`)return!1;let t=(e.type||``).toLowerCase();return![`hidden`,`submit`,`button`,`checkbox`,`radio`,`file`].includes(t)}function Uh(e){if(!Hh(e))return!1;let t=(e.name||``).toLowerCase(),n=(e.id||``).toLowerCase(),r=[e.name,e.id,e.placeholder,Ah(e),e.getAttribute(`aria-label`)].filter(Boolean).join(` `).toLowerCase();return t===`url`||n===`url-input`||n.endsWith(`-url-input`)||/(website\s*url|enter\s+website|site\s*url)/.test(r)||/(website|domain)/.test(r)&&/(url|site)/.test(r)}function Wh(e,t,n){let r=String(t??``),i=String(n??``),a=qh(e,r)||Rh(e,r)||zh(e,r,i);if(!a)return[];let o=new Set([a]);if(Bh(i)&&Vh(r))for(let t of e)t!==a&&Uh(t)&&o.add(t);let s=Array.from(o);return s.sort((e,t)=>{if(e===t)return 0;let n=e.compareDocumentPosition(t);return n&Node.DOCUMENT_POSITION_FOLLOWING?-1:n&Node.DOCUMENT_POSITION_PRECEDING?1:0}),s}function Gh(e,t){try{if(!e?.getBoundingClientRect||!t?.getBoundingClientRect)return 1/0;let n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),i={x:n.left+n.width/2,y:n.top+n.height/2},a={x:r.left+r.width/2,y:r.top+r.height/2};return Math.hypot(i.x-a.x,i.y-a.y)}catch{return 1/0}}function Kh(e){if(!e||typeof e!=`string`)return null;let t=null;return Oh(n=>{try{let r=n.getElementById(e);r&&!Eh(r)&&r.matches?.(`input, select, textarea`)&&(t=r)}catch{}}),t}function qh(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=Kh(i[1]);if(e)return e}let a=n.startsWith(`#`)?n.slice(1):n;if(/^[\w-]+$/.test(a)){let e=Kh(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 Jh(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 Yh(e,t){let n=[];Oh(e=>{n.push(...Array.from(e.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(Eh(e)||e.disabled)return!1;try{let t=Dh(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))});let r=0,i=n.map(t=>({el:t,s:Jh(t,e)}));for(let{s:e}of i)e>r&&(r=e);if(r<36)return null;let a=i.filter(({s:e})=>e===r).map(({el:e})=>e);if(a.length===1)return a[0];let o=Array.isArray(t)?t.filter(e=>e&&e.isConnected):[];if(o.length){let e=a[0],t=1/0;for(let n of a)for(let r of o){let i=Gh(n,r);i<t&&(t=i,e=n)}return e}return a[0]}function Xh(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 Zh(e){let t=Xh(e);if(Array.isArray(t)&&t.length>0){let e=t[0];if(e?.field_key!=null||e?.fieldKey!=null)return t.map(e=>({field_key:e.field_key??e.fieldKey,value:e.value}))}if(!t||typeof t!=`object`)return[];let n=t.fields??t.Fields??t.field_list??t.fieldList??t.data?.fields;if(typeof n==`string`)try{n=JSON.parse(n)}catch{n=null}n&&!Array.isArray(n)&&typeof n==`object`&&(n=Object.values(n)),(!n||n.length===0)&&(t.field_key!=null||t.fieldKey!=null)&&t.value!=null&&(n=[{field_key:t.field_key??t.fieldKey,value:t.value}]);let r=t.website_url??t.websiteUrl??t.url??t.website??t.domain??t.site_url??t.siteUrl;return(!n||n.length===0)&&r!=null&&String(r).trim()&&(n=[{field_key:t.field_key??t.fieldKey??`url`,value:String(r).trim()}]),Array.isArray(n)?n.map(e=>({field_key:e?.field_key??e?.fieldKey,value:e?.value??e?.Value})):[]}function Qh(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t)return[];let n=t.match(/https?:\/\/[^\s<>"']+/i);if(n)return[{field_key:`url`,value:n[0].replace(/[.,;:)]+$/,``)}];let r=t.match(/\b(?:[\w-]+\.)+[a-z]{2,}\b/i);if(r){let e=r[0].replace(/[.,;:)]+$/,``);return/^https?:/i.test(e)||(e=`https://${e}`),[{field_key:`url`,value:e}]}return[]}function $h(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t)return[];let n=[],r=new Set,i=(e,t)=>{let i=String(t??``).trim().replace(/^["']|["']$/g,``);if(!i||i.length>800)return;let a=`${e}\0${i}`;r.has(a)||(r.add(a),n.push({field_key:e,value:i}))},a=t.match(/\b(?:please\s+)?(?:enter|type|put)\s+(.+?)\s+in(?:to)?\s+(?:the\s+)?(?:full\s*name|full\s*name\s*field|name\s*field)\b/i);if(a&&i(`Full Name`,a[1]),a=t.match(/\bfull\s*name,?\s*(?:please\s+)?(?:enter|type|put)\s+(.+?)(?:\.|$|!|\?)/i),a&&i(`Full Name`,a[1]),a=t.match(/\bfull\s*name\s*(?:is|:|please\s+enter|-)\s*(.+?)(?:\.|$|(?=\s+(?:and|my\s+email|email|message))\b)/i),a&&i(`Full Name`,a[1]),a=t.match(/\b(.+?)\s+for\s+(?:the\s+)?full\s*name\b/i),a){let e=a[1].trim();e.length>1&&e.length<120&&!/@/.test(e)&&i(`Full Name`,e)}if(a=t.match(/\b(?:email|e-mail)(?:\s*address)?\s*(?:is|:|please\s+use|enter|-)\s*([^\s@]+@[^\s@]+\.[^\s,]+)/i),a&&i(`Email Address`,a[1]),a=t.match(/\b(?:enter|type|put)\s+([^\s@]+@[^\s@]+\.[^\s,]+)\s+in(?:to)?\s+(?:the\s+)?(?:email|e-mail)/i),a&&i(`Email Address`,a[1]),a=t.match(/\b(?:message|comment)\s*(?:is|:|please\s+enter|-)\s*(.+)$/is),a){let e=a[1].trim();e.length>0&&i(`Message`,e)}return n}function eg(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 tg(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 ng(e,t,n){if(!n?.skipScroll)try{e.scrollIntoView({block:`center`,inline:`nearest`})}catch{try{e.scrollIntoView(!0)}catch{}}try{e.focus({preventScroll:!0})}catch{try{e.focus()}catch{}}let r=e.tagName,i=(e.type||``).toLowerCase();if(r===`SELECT`)return e.value=String(t),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;if(i===`checkbox`||i===`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 a=String(t);if(r===`INPUT`||r===`TEXTAREA`){let t=e.ownerDocument?.defaultView||window,n=r===`TEXTAREA`?t.HTMLTextAreaElement.prototype:t.HTMLInputElement.prototype,i=Object.getOwnPropertyDescriptor(n,`value`);i?.set?i.set.call(e,a):e.value=a}else e.value=a;let o={bubbles:!0,cancelable:!0,composed:!0};try{e.dispatchEvent(new InputEvent(`input`,{...o,inputType:`insertText`,data:a}))}catch{e.dispatchEvent(new Event(`input`,o))}e.dispatchEvent(new Event(`change`,o));try{queueMicrotask(()=>{try{e.dispatchEvent(new Event(`input`,o)),e.dispatchEvent(new Event(`change`,o))}catch{}})}catch{}return!0}function rg(e){let t=e.siteId||null,n=(e.apiBaseUrl||``).replace(/\/$/,``),r=typeof e.getLastUserVoiceText==`function`?e.getLastUserVoiceText:null,i=[],a={navigate_to_page:async e=>{wh(`navigate_to_page ▶ raw parameters:`,e);let t=Xh(e),n=eg(t),r=t.section_text??t.sectionText??t.section;if(wh(`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 wh(`navigate_to_page ✖`,e),e}try{if(wh(`navigate_to_page → shadowNavigate`,n),await sn(n),await new Promise(e=>setTimeout(e,400)),r&&typeof r==`string`){let e=nn(null,r);e&&rn(e),wh(`navigate_to_page · highlight`,{sectionText:r,found:!!e})}let e=`OK_NAVIGATION ${n}`;return wh(`navigate_to_page ✓`,e),e}catch(e){let t=`Navigation error: ${e?.message||String(e)}`;return wh(`navigate_to_page ✖`,t),t}},highlight_on_page:async e=>{wh(`highlight_on_page ▶`,e);let t=Xh(e),n=t?.section_id||t?.sectionId,r=t?.section_text||t?.sectionText,i=nn(n||null,r||null);return i?(rn(i),wh(`highlight_on_page ✓`),`Highlighted the section.`):(wh(`highlight_on_page ✖ no element`),`Could not find that section on the page.`)},search_site_content:async e=>{wh(`search_site_content ▶`,e);let r=tg(Xh(e));if(wh(`search_site_content · query:`,r,`siteId:`,t,`apiBase:`,n||`(empty)`),!r)return wh(`search_site_content ✖ missing query`),`Missing query parameter.`;if(!t)return wh(`search_site_content ✖ no siteId`),`Site is not configured for search.`;if(!n)return wh(`search_site_content ✖ no api base`),`API base URL is missing; cannot search.`;try{let e=`${n}/api/site-tools/search`;wh(`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(wh(`search_site_content · HTTP`,i.status,`success:`,a.success),!a.success){let e=a.error||`Search failed.`;return wh(`search_site_content ✖`,e),e}let o=a.results||[];return wh(`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 wh(`search_site_content ✖`,t),t}},list_page_forms:async()=>{let e=Mh(),t=Nh();return wh(`list_page_forms ✓`,`${e.length} field(s)`,`${t.length} button(s)`),JSON.stringify({fields:e,buttons:t,hint:`field_key: placeholder/label, name (e.g. url), id (e.g. url-input). If the page has two URL boxes, fill_form_fields sets all matching URL inputs. click_page_button picks the Conduct Audit nearest the filled field when labels duplicate.`})},fill_form_fields:async e=>{try{wh(`fill_form_fields ▶ raw:`,e);let t=Zh(e);if(!t.length&&r){let e=r(),n=Qh(e);n.length?wh(`fill_form_fields · inferred URL from last user utterance (model omitted usable fields):`,n):(n=$h(e),n.length&&wh(`fill_form_fields · inferred contact fields from last user utterance (empty tool params):`,n)),n.length&&(t=n)}if(wh(`fill_form_fields · normalized fields:`,t),!t.length)return`No fields provided. Call list_page_forms, then fill_form_fields with { "fields": [ { "field_key": "url or Enter Website URL", "value": "https://..." } ] }. Do not call with empty {}.`;let n=[];for(let e of t){let t=e?.field_key??e?.fieldKey,r=e?.value;if(t==null||r==null)continue;let a=jh(),o=Wh(a,String(t),r);if(o.length){o.forEach((e,t)=>{ng(e,r,{skipScroll:t>0})}),i=o,n.push(String(t));continue}let s=qh(a,String(t));s||=Rh(a,String(t)),s||=zh(a,String(t),r),s&&(ng(s,r),i=[s],n.push(String(t)))}if(!n.length)return wh(`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 a=`OK_FILLED: ${n.join(`, `)}`;return wh(`fill_form_fields ✓`,a),a}catch(e){let t=`fill_form_fields error: ${e?.message||String(e)}`;return wh(`fill_form_fields ✖`,t),t}},click_page_button:async e=>{let t=Xh(e),n=(t.button_text??t.buttonText??t.text??``).trim();if(wh(`click_page_button ▶`,n),!n)return`Missing button_text: pass the visible label, e.g. Conduct Audit.`;let r=Yh(n,i);if(!r)return wh(`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 wh(`click_page_button ✓`,e),e}catch(e){let t=`Click failed: ${e?.message||String(e)}`;return wh(`click_page_button ✖`,t),t}}};return{...a,navigateToPage:a.navigate_to_page,highlightOnPage:a.highlight_on_page,searchSiteContent:a.search_site_content,listPageForms:a.list_page_forms,fillFormFields:a.fill_form_fields,clickPageButton:a.click_page_button}}function ig(e){return!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,async n=>{let r=$t();r?console.log(`[FlowEngage:voice-tool] ▶`,e,n):console.info(`[FlowEngage] voice tool » ${e}`);let i=await t(n),a=typeof i==`string`?i.length>220?`${i.slice(0,220)}…`:i:String(i);return r?console.log(`[FlowEngage:voice-tool] ◀`,e,a):console.info(`[FlowEngage] voice tool « ${e}:`,a),i}]))}var ag={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)`},og={idle:`#6366f1`,listening:`#10b981`,speaking:`#f59e0b`,error:`#ef4444`};function sg({agentId:e,chatId:t,siteId:n,apiBaseUrl:r,onEnd:i,historyRef:a,hasSyncedRef:o,onMessageSync:s,onStartSync:c}){let[l,u]=(0,v.useState)(`idle`),[d,f]=(0,v.useState)(null),[p,m]=(0,v.useState)(!1),[h,g]=(0,v.useState)([]),_=(0,v.useRef)(null),y=(0,v.useRef)(null),b=(0,v.useRef)(``);(0,v.useEffect)(()=>{let t=!1,i=null;return(async()=>{try{if(await navigator.mediaDevices.getUserMedia({audio:!0}),t)return;g([]),b.current=``;let o=ig(rg({siteId:n||null,apiBaseUrl:r||null,getLastUserVoiceText:()=>b.current})),s=await Ch.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||u(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()};n===`user`&&(b.current=r),a.current=[...a.current,i],g(e=>[...e,i])},onError:e=>{t||(console.error(`[VoiceInterface] ElevenLabs error`,e),u(`error`),f(`Voice session encountered an error.`))},onDisconnect:()=>{t||(console.log(`[VoiceInterface] session disconnected`),m(!1),u(`idle`))}});if(t){s.endSession().catch(()=>{});return}i=s,_.current=s,m(!0),u(`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),u(`error`),f(`Could not start voice session. Please try again.`))}})(),()=>{t=!0,i?i.endSession().catch(()=>{}):_.current&&_.current.endSession().catch(()=>{})}},[e,n,r,a,c]);let x=(0,v.useCallback)(async()=>{try{await _.current?.endSession?.()}catch{}_.current=null,m(!1),u(`idle`),typeof s==`function`&&await s(a.current),typeof i==`function`&&i()},[a,s,i]),ee=l===`listening`||l===`speaking`,te=og[l]||og.idle,S=ag[l]||ag.idle;return(0,k.jsxs)(`div`,{ref:y,style:{display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,flex:1,gap:`24px`,padding:`24px 20px`,background:`transparent`},children:[(0,k.jsxs)(`div`,{style:{position:`relative`,width:`140px`,height:`140px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:[ee&&(0,k.jsx)(`div`,{style:{position:`absolute`,inset:`-16px`,borderRadius:`50%`,border:`2px solid ${te}`,animation:`fe-orb-pulse 1.4s ease-in-out infinite`,opacity:.6}}),ee&&(0,k.jsx)(`div`,{style:{position:`absolute`,inset:`-8px`,borderRadius:`50%`,border:`2px solid ${te}`,animation:`fe-orb-pulse 1.4s ease-in-out 0.35s infinite`,opacity:.4}}),(0,k.jsx)(`div`,{style:{width:`140px`,height:`140px`,borderRadius:`50%`,background:S,border:`3px solid ${te}`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`all 0.35s ease`,transform:l===`speaking`?`scale(1.08)`:`scale(1)`,boxShadow:`0 0 40px ${S}, 0 8px 32px rgba(0,0,0,0.08)`},children:(0,k.jsx)(_n,{size:44,color:te})})]}),(0,k.jsxs)(`div`,{style:{fontSize:`15px`,fontWeight:600,color:l===`error`?`#ef4444`:`#374151`,letterSpacing:`0.01em`,textAlign:`center`},children:[l===`idle`&&`Starting voice session…`,l===`listening`&&`Listening…`,l===`speaking`&&`AI is speaking…`,l===`error`&&(d||`Error`)]}),h.length>0&&(0,k.jsx)(`div`,{style:{width:`100%`,maxHeight:`160px`,overflowY:`auto`,display:`flex`,flexDirection:`column`,gap:`8px`,padding:`0 4px`},children:h.map((e,t)=>(0,k.jsx)(`div`,{style:{display:`flex`,justifyContent:e.sender===`user`?`flex-end`:`flex-start`},children:(0,k.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,k.jsxs)(`button`,{onClick:x,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,k.jsx)(vn,{size:18}),`End Voice Session`]}),(0,k.jsx)(`style`,{children:`
|
|
327
327
|
@keyframes fe-orb-pulse {
|
|
328
328
|
0% { transform: scale(1); opacity: 0.6; }
|
|
329
329
|
50% { transform: scale(1.18); opacity: 0.15; }
|
|
330
330
|
100% { transform: scale(1); opacity: 0.6; }
|
|
331
331
|
}
|
|
332
|
-
`})]})}var
|
|
332
|
+
`})]})}var cg=[{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`}],lg=()=>(0,k.jsx)(`div`,{style:{display:`flex`,marginBottom:`12px`,justifyContent:`flex-start`},children:(0,k.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,k.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,k.jsx)(`style`,{children:`
|
|
333
333
|
@keyframes fe-dot-bounce {
|
|
334
334
|
0%, 80%, 100% { transform: translateY(0); opacity: 0.5; }
|
|
335
335
|
40% { transform: translateY(-5px); opacity: 1; }
|
|
336
336
|
}
|
|
337
|
-
`})]})});function
|
|
338
|
-
@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-border-style:solid;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-ease:initial}}:root,:host{--spacing:.25rem;--ease-in-out:cubic-bezier(.4, 0, .2, 1);--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1)}.visible{visibility:visible}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.start{inset-inline-start:var(--spacing)}.end{inset-inline-end:var(--spacing)}.container{width:100%}@media (width>=40rem){.container{max-width:40rem}}@media (width>=48rem){.container{max-width:48rem}}@media (width>=64rem){.container{max-width:64rem}}@media (width>=80rem){.container{max-width:80rem}}@media (width>=96rem){.container{max-width:96rem}}.block{display:block}.flex{display:flex}.hidden{display:none}.inline{display:inline}.inline-block{display:inline-block}.inline-flex{display:inline-flex}.transform{transform:var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,)}.border{border-style:var(--tw-border-style);border-width:1px}.uppercase{text-transform:uppercase}.ring{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.filter{filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.ease-in-out{--tw-ease:var(--ease-in-out);transition-timing-function:var(--ease-in-out)}.flowengage-shell,.flowengage-shell *{font-family:inherit}.flowengage-chat-panel{border:none;border-radius:0;outline:none;flex-direction:column;width:100%;height:100%;display:flex;position:relative;overflow:hidden;box-shadow:0 20px 50px #00000026}@media (width>=768px){.flowengage-chat-panel{border-radius:24px;width:min(423px,100vw - 40px);height:min(700px,100vh - 120px)}}.flowengage-shell[data-open=true]{inset:0}@media (width>=768px){.flowengage-shell[data-open=true]{inset:auto 1.5rem 1.5rem auto}}.flowengage-logo-fallback{background:conic-gradient(from 180deg, var(--flowengage-primary) 0%, #2b70b5 50%, #f59e0b 100%)}.fe-bot-message p{margin:0 0 .5em}.fe-bot-message p:last-child{margin-bottom:0}.fe-bot-message ul,.fe-bot-message ol{margin:.4em 0 .4em 1.2em;padding:0}.fe-bot-message li{margin-bottom:.25em}.fe-bot-message strong{font-weight:600}.fe-bot-message a{color:var(--flowengage-primary);text-decoration:underline}.fe-bot-message a:hover{opacity:.8}.incoming-call-overlay{z-index:1000;-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);background:#1a1a2ef2;justify-content:center;align-items:center;transition:all .3s ease-in-out;display:flex;position:absolute;left:0;right:0}.incoming-call-overlay.bottom-mode{border-top:2px solid #ffffff1a;min-height:120px;animation:.4s cubic-bezier(.16,1,.3,1) slideUpBanner;top:auto;bottom:0;box-shadow:0 -10px 30px #00000080}.incoming-call-overlay.header-mode{border-bottom:2px solid #ffffff1a;min-height:80px;animation:.4s cubic-bezier(.16,1,.3,1) slideDownBanner;top:0;bottom:auto;box-shadow:0 10px 30px #00000080}.incoming-call-container{justify-content:space-between;align-items:center;gap:14px;width:100%;padding:14px 16px;display:flex}.incoming-call-container.connected-layout{flex-direction:column;justify-content:center;align-items:stretch;gap:14px}.call-connected-top{justify-content:space-between;align-items:center;gap:16px;width:100%;display:flex}.call-connected-identity{flex:1;align-items:center;gap:14px;min-width:0;display:flex}.call-icon-wrapper{color:#fff;z-index:1;border-radius:9999px;flex-shrink:0;justify-content:center;align-items:center;width:54px;height:54px;margin-right:4px;display:flex;position:relative}.call-icon-wrapper.incoming{background:linear-gradient(135deg,#4caf50,#45a049);animation:1s ease-in-out infinite bounce}.call-icon-wrapper.connecting{background:linear-gradient(135deg,#2196f3,#1976d2)}.call-icon-wrapper.connected{background:linear-gradient(135deg,#4caf50,#45a049)}.call-pulse-animation{z-index:-1;background:#4caf504d;border-radius:50%;width:120px;height:120px;animation:1.5s ease-out infinite pulse;position:absolute}.call-connecting-animation{z-index:-1;border:3px solid #0000;border-top-color:#2196f3;border-radius:50%;width:100px;height:100px;animation:1s linear infinite spin;position:absolute}.call-info-group{flex-direction:column;flex:1;min-width:0;margin-right:8px;display:flex}.call-title{color:#fff;white-space:normal;text-overflow:clip;margin:0;font-size:16px;font-weight:700;line-height:1.2;overflow:visible}.call-subtitle{color:#ffffffb3;white-space:normal;text-overflow:clip;margin:4px 0 0;font-size:12px;line-height:1.35;overflow:visible}.call-timer{text-align:center;color:#fff;flex-shrink:0;min-width:54px;font-size:13px;font-weight:700}.call-actions{flex-shrink:0;align-items:center;gap:8px;display:flex}.call-actions.connected{justify-content:center;width:100%}.flowengage-call-btn{cursor:pointer;color:#fff;border:none;border-radius:8px;justify-content:center;align-items:center;gap:6px;min-width:92px;padding:8px 12px;font-size:12px;font-weight:600;line-height:1;transition:transform .2s,box-shadow .2s,background .2s;display:flex}.flowengage-call-btn svg{flex-shrink:0;display:block}.flowengage-call-btn span{justify-content:center;align-items:center;line-height:1;display:flex}.flowengage-call-btn.icon-only{border-radius:9999px;width:46px;min-width:46px;height:46px;padding:0}.flowengage-call-btn-accept{background:linear-gradient(135deg,#4caf50,#45a049);box-shadow:0 8px 24px #4caf5066}.flowengage-call-btn-reject,.flowengage-call-btn-end{background:linear-gradient(135deg,#f44336,#d32f2f);box-shadow:0 4px 12px #f4433666}.flowengage-call-btn-mute{background:#ffffff1a;border:2px solid #fff3}.flowengage-call-btn-mute.active{background:#f443364d;border-color:#f44336}.flowengage-call-btn:hover:not(:disabled){transform:scale(1.05)}.incoming-call-overlay.header-mode .flowengage-call-btn{border-radius:9999px!important;width:36px!important;min-width:36px!important;height:36px!important;padding:0!important}.incoming-call-overlay.header-mode .flowengage-call-btn span{display:none!important}.incoming-call-overlay.header-mode .call-icon-wrapper{width:40px;height:40px;margin-right:0}.incoming-call-overlay.header-mode .call-info-group{min-width:0}.incoming-call-overlay.header-mode .call-title,.incoming-call-overlay.header-mode .call-subtitle{white-space:nowrap;text-overflow:ellipsis;overflow:hidden}@media (width<=640px){.incoming-call-container{align-items:flex-start;gap:10px;padding:12px 14px}.incoming-call-container.connected-layout{align-items:stretch}.call-connected-top{flex-direction:column;align-items:flex-start;gap:10px}.call-connected-identity{width:100%}.call-info-group{margin-right:0}.call-actions{flex-wrap:wrap;align-self:stretch;gap:6px}.call-actions.connected{justify-content:stretch}.call-actions.connected .flowengage-call-btn{flex:1}.flowengage-call-btn{min-width:78px;padding:8px 10px}}@keyframes slideUpBanner{0%{transform:translateY(100%)}to{transform:translateY(0)}}@keyframes slideDownBanner{0%{transform:translateY(-100%)}to{transform:translateY(0)}}@keyframes bounce{0%,to{animation-timing-function:cubic-bezier(.8,0,1,1);transform:translateY(-25%)}50%{animation-timing-function:cubic-bezier(0,0,.2,1);transform:none}}@keyframes pulse{50%{opacity:.5}}@keyframes spin{to{transform:rotate(360deg)}}.fe-screen-fade-in{animation:.4s cubic-bezier(.16,1,.3,1) forwards feFadeIn}@keyframes feFadeIn{0%{opacity:0;transform:translateY(12px)}to{opacity:1;transform:translateY(0)}}.flowengage-initial-bg{background-color:#fff;position:relative;overflow:hidden}.flowengage-initial-bg:before{content:"";background:linear-gradient(to bottom, var(--flowengage-primary) 0%, var(--flowengage-primary) 55%, white 82%);opacity:0;pointer-events:none;z-index:0;transition:opacity .6s cubic-bezier(.4,0,.2,1);position:absolute;inset:0}.flowengage-initial-bg.is-initial:before{opacity:1}.flowengage-content-wrapper{z-index:1;flex-direction:column;flex:1;min-height:0;display:flex;position:relative}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"<length>";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}@property --tw-ease{syntax:"*";inherits:false}`,tg=null,ng=!1;function rg(){if(typeof document>`u`||document.getElementById(`flowengage-styles`))return;let e=document.createElement(`style`);e.id=`flowengage-styles`,e.innerHTML=eg,document.head.appendChild(e)}function ig(e){if(document.body){e();return}let t=new MutationObserver(()=>{document.body&&(t.disconnect(),e())});t.observe(document.documentElement,{childList:!0})}function ag({siteId:e,language:t=`en`,widgetSettings:n={},apiBaseUrl:r}){if(ng){console.warn(`[FlowEngage] Already initialized. Call FlowEngage.destroy() first to re-initialize.`);return}if(!e){console.error(`[FlowEngage] siteId is required. Pass it via data-site-id attribute or FlowEngage.init({ siteId: 'YOUR_SITE_ID' }).`);return}if(!document.body){console.error(`[FlowEngage] document.body is not available yet. The widget will auto-retry once the DOM is ready.`),ig(()=>ag({siteId:e,language:t,widgetSettings:n,apiBaseUrl:r}));return}if(document.getElementById(`flowengage-root`)){console.warn(`[FlowEngage] #flowengage-root already exists. Skipping duplicate mount.`);return}let i=document.createElement(`div`);i.id=`flowengage-root`,document.body.appendChild(i),rg(),tg=(0,y.createRoot)(i);let a={widgetSettings:n,...r&&{apiBaseUrl:r}};tg.render(v.createElement(hn,{siteId:e,language:t,config:a},v.createElement($h))),ng=!0}var og={init({siteId:e,language:t=`en`,widgetSettings:n={},apiBaseUrl:r}={}){document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>ig(()=>ag({siteId:e,language:t,widgetSettings:n,apiBaseUrl:r}))):ig(()=>ag({siteId:e,language:t,widgetSettings:n,apiBaseUrl:r}))},destroy(){tg&&=(tg.unmount(),null);let e=document.getElementById(`flowengage-root`);e&&e.remove();let t=document.getElementById(`flowengage-styles`);t&&t.remove(),ng=!1}},sg=()=>{let e=document.currentScript;(!e||!e.getAttribute(`data-site-id`))&&(e=document.querySelector(`script[data-site-id]`));let t=e?.getAttribute(`data-site-id`);if(!t)return;let n=e?.getAttribute(`data-language`)||`en`,r=e?.getAttribute(`data-api-url`)||void 0,i={};try{let t=e?.getAttribute(`data-widget-settings`);t&&(i=JSON.parse(t))}catch{}let a={widgetSettings:i,...r&&{apiBaseUrl:r}};ig(()=>ag({siteId:t,language:n,widgetSettings:a.widgetSettings,apiBaseUrl:r}))};return document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,sg):sg(),typeof window<`u`&&(window.FlowEngage=og),og})();
|
|
337
|
+
`})]})});function ug(){let{status:e,runtimeConfig:t,resolvedConfig:n,chatId:r,chatHistory:i,isOpen:a,activeScreen:o,isHumanHandled:s,agentName:c,visitorEmail:l,isAgentTyping:u,isAiTyping:d,isLoading:f,isVoiceMode:p,isRateLimited:m,rateLimitMessage:h,isConversationEnded:g,incomingCall:_,activeCallId:y,callConnectionState:b,callConnectedAt:x,isCallMuted:ee,webRTCError:te,language:S,historyRef:ne,onMessageSync:re,endConversation:ie,acceptCall:ae,rejectCall:oe,endWebRTCCall:se,toggleCallMute:ce,dismissCallError:le,captureVisitorEmail:ue,openWidget:de,closeWidget:fe,sendMessage:C,setVoiceMode:w,startTyping:pe,stopTyping:me,updateTypingDraft:he}=Qt(),[ge,_e]=(0,v.useState)(``),[T,ve]=(0,v.useState)(null),[ye,be]=(0,v.useState)(null),[xe,Se]=(0,v.useState)(null),[Ce,we]=(0,v.useState)(0),[Te,Ee]=(0,v.useState)(l||``),[De,E]=(0,v.useState)(``),Oe=t?.widgetSettings||{},ke=n?.widgetSettings||{},Ae={...Oe.branding||{},...ke.branding||{}},je={...Oe.theme||{},...ke.theme||{}},Me=je.primaryColor||`#3B82F6`,Ne=je.accentColor||`#1D4ED8`,Pe=(je.position||`bottom-right`)===`bottom-left`?{left:`1.5rem`,bottom:`1.5rem`}:{right:`1.5rem`,bottom:`1.5rem`},Fe={"--flowengage-primary":Me,"--flowengage-accent":Ne,position:`fixed`,zIndex:999999,border:`none`,outline:`none`,fontFamily:`ui-sans-serif, system-ui, sans-serif`,...a?{}:Pe},Ie=ke.recommendations?.[S]||Oe.recommendations?.[S]||cg,Le=ke.greetings?.[S]||Oe.greetings?.[S],Re=Ae.chatButtonText||`Chat with us`,ze=Ae.headerName||t?.websiteName||`OpenSense Labs`,Be=Ae.logoUrl||null,D=Ae.hideWatermark||!1,Ve=ke.elevenLabsAgentId||t?.elevenLabsAgentId||null,He=t?.siteId||n?.siteId||null,Ue=t?.apiBaseUrl||``,We=Ae.fallbackAgentName||`Agent`,Ge=Ae.botLabel||`AI`,Ke=_?.agentName||c||We,qe=!l&&i.length===0;(0,v.useEffect)(()=>{Ee(l||``),l&&E(``)},[l]),(0,v.useEffect)(()=>{if(!x||b!==`connected`){we(0);return}let e=()=>{let e=new Date(x).getTime();isNaN(e)||we(Math.max(0,Math.floor((Date.now()-e)/1e3)))};e();let t=window.setInterval(e,1e3);return()=>window.clearInterval(t)},[x,b]),(0,v.useEffect)(()=>{if(!s||p||g){he(``),me();return}if(!ge.trim()){he(``),me();return}pe();let e=window.setTimeout(()=>{he(ge)},120),t=window.setTimeout(()=>{me()},1200);return()=>{window.clearTimeout(e),window.clearTimeout(t)}},[ge,s,p,g,pe,me,he]);let Je=e=>e?{replyTo:e.messageId||e.id||null,replyToContent:(e.replyToContent||e.message||``).replace(/<[^>]+>/g,``).trim().slice(0,200),replyToSender:e.sender||null}:null,Ye=async e=>{if(e.preventDefault(),g)return;if(qe){let e=Te.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)){E(`Please enter a valid email to start the chat.`);return}await ue(e),E(``);return}if(!ge.trim())return;let t=ge.trim(),n=Je(xe);_e(``),Se(null),await C(t,``,n)},Xe=async()=>{if(qe){E(`Please share your email before starting a call.`);return}if(p){w(!1);return}be(null);try{ve(await navigator.mediaDevices.getUserMedia({audio:!0})),w(!0)}catch(e){be(e.message||`Could not access microphone.`)}},Ze=()=>{T&&(T.getTracks().forEach(e=>e.stop()),ve(null)),w(!1)},Qe=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,k.jsxs)(`div`,{className:`flowengage-shell`,"data-open":a?`true`:`false`,style:Fe,children:[(0,k.jsx)(Tn,{isOpen:a,openWidget:de,launcherText:Re,primaryColor:Me,posInline:Pe}),a&&(0,k.jsxs)(`div`,{className:`flowengage-chat-panel`,style:{background:i.length===0&&!p?`linear-gradient(to bottom, ${Me} 0%, ${Me} 70%, white 85%)`:`white`},children:[(0,k.jsx)(On,{logoUrl:Be,brandName:ze,agentName:c,fallbackAgentName:We,activeScreen:o,branding:Ae,isConversationEnded:g,endConversation:ie,closeWidget:fe,isInitial:i.length===0&&!p,botLabel:Ge}),(0,k.jsx)(`div`,{style:{flex:1,overflowY:`auto`,display:`flex`,flexDirection:`column`},className:`flowengage-content-wrapper`,children:p?(0,k.jsx)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`},className:`fe-screen-fade-in`,children:(0,k.jsx)(sg,{agentId:Ve,chatId:r,siteId:He,apiBaseUrl:Ue,historyRef:ne,onMessageSync:re,onEnd:Ze})},`voice`):i.length===0?(0,k.jsx)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`},className:`fe-screen-fade-in`,children:(0,k.jsx)(Nn,{greetings:Le,recommendations:Ie,onSendMessage:C,visitorEmail:l,emailInput:Te,setEmailInput:Ee,emailError:De,setEmailError:E,onCaptureEmail:ue,botLabel:Ge})},`welcome`):(0,k.jsx)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`},className:`fe-screen-fade-in`,children:(0,k.jsx)(Mn,{chatHistory:i,isAiTyping:d,isAgentTyping:u,setReplyContext:Se,TypingDots:lg})},`history`)}),(0,k.jsx)(Ln,{webRTCError:te,micError:ye,setMicError:be,dismissCallError:le,incomingCall:_,rejectCall:oe,acceptCall:ae,activeCallId:y,callConnectionState:b,formatCallDuration:Qe,callDurationSeconds:Ce,endWebRTCCall:se,isCallMuted:ee,toggleCallMute:ce,isAIVoiceActive:p,currentCallAgentName:Ke,isRateLimited:m,rateLimitMessage:h}),!p&&(0,k.jsx)(`div`,{style:{position:`relative`,zIndex:1},children:(0,k.jsx)(Pn,{input:ge,setInput:_e,onSubmit:Ye,isConversationEnded:g,callUiActive:!!(_||y),handleToggleVoice:Xe,activeScreen:o,inputDisabled:f||m||g,replyContext:xe,clearReplyContext:()=>Se(null),requiresEmail:qe,emailInput:Te,setEmailInput:Ee,emailError:De})}),!D&&(0,k.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,k.jsxs)(`div`,{children:[`Powered by `,(0,k.jsx)(`span`,{style:{color:`#3b82f6`},children:`Flow`}),(0,k.jsx)(`span`,{style:{color:`#ef4444`},children:`Engage`})]})})]})]}):null}var dg=`/*! tailwindcss v4.2.2 | MIT License | https://tailwindcss.com */
|
|
338
|
+
@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-border-style:solid;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-ease:initial}}:root,:host{--spacing:.25rem;--ease-in-out:cubic-bezier(.4, 0, .2, 1);--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1)}.visible{visibility:visible}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.start{inset-inline-start:var(--spacing)}.end{inset-inline-end:var(--spacing)}.container{width:100%}@media (width>=40rem){.container{max-width:40rem}}@media (width>=48rem){.container{max-width:48rem}}@media (width>=64rem){.container{max-width:64rem}}@media (width>=80rem){.container{max-width:80rem}}@media (width>=96rem){.container{max-width:96rem}}.block{display:block}.flex{display:flex}.hidden{display:none}.inline{display:inline}.inline-block{display:inline-block}.inline-flex{display:inline-flex}.transform{transform:var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,)}.border{border-style:var(--tw-border-style);border-width:1px}.uppercase{text-transform:uppercase}.ring{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.filter{filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.ease-in-out{--tw-ease:var(--ease-in-out);transition-timing-function:var(--ease-in-out)}.flowengage-shell,.flowengage-shell *{font-family:inherit}.flowengage-chat-panel{border:none;border-radius:0;outline:none;flex-direction:column;width:100%;height:100%;display:flex;position:relative;overflow:hidden;box-shadow:0 20px 50px #00000026}@media (width>=768px){.flowengage-chat-panel{border-radius:24px;width:min(423px,100vw - 40px);height:min(700px,100vh - 120px)}}.flowengage-shell[data-open=true]{inset:0}@media (width>=768px){.flowengage-shell[data-open=true]{inset:auto 1.5rem 1.5rem auto}}.flowengage-logo-fallback{background:conic-gradient(from 180deg, var(--flowengage-primary) 0%, #2b70b5 50%, #f59e0b 100%)}.fe-bot-message p{margin:0 0 .5em}.fe-bot-message p:last-child{margin-bottom:0}.fe-bot-message ul,.fe-bot-message ol{margin:.4em 0 .4em 1.2em;padding:0}.fe-bot-message li{margin-bottom:.25em}.fe-bot-message strong{font-weight:600}.fe-bot-message a{color:var(--flowengage-primary);text-decoration:underline}.fe-bot-message a:hover{opacity:.8}.incoming-call-overlay{z-index:1000;-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);background:#1a1a2ef2;justify-content:center;align-items:center;transition:all .3s ease-in-out;display:flex;position:absolute;left:0;right:0}.incoming-call-overlay.bottom-mode{border-top:2px solid #ffffff1a;min-height:120px;animation:.4s cubic-bezier(.16,1,.3,1) slideUpBanner;top:auto;bottom:0;box-shadow:0 -10px 30px #00000080}.incoming-call-overlay.header-mode{border-bottom:2px solid #ffffff1a;min-height:80px;animation:.4s cubic-bezier(.16,1,.3,1) slideDownBanner;top:0;bottom:auto;box-shadow:0 10px 30px #00000080}.incoming-call-container{justify-content:space-between;align-items:center;gap:14px;width:100%;padding:14px 16px;display:flex}.incoming-call-container.connected-layout{flex-direction:column;justify-content:center;align-items:stretch;gap:14px}.call-connected-top{justify-content:space-between;align-items:center;gap:16px;width:100%;display:flex}.call-connected-identity{flex:1;align-items:center;gap:14px;min-width:0;display:flex}.call-icon-wrapper{color:#fff;z-index:1;border-radius:9999px;flex-shrink:0;justify-content:center;align-items:center;width:54px;height:54px;margin-right:4px;display:flex;position:relative}.call-icon-wrapper.incoming{background:linear-gradient(135deg,#4caf50,#45a049);animation:1s ease-in-out infinite bounce}.call-icon-wrapper.connecting{background:linear-gradient(135deg,#2196f3,#1976d2)}.call-icon-wrapper.connected{background:linear-gradient(135deg,#4caf50,#45a049)}.call-pulse-animation{z-index:-1;background:#4caf504d;border-radius:50%;width:120px;height:120px;animation:1.5s ease-out infinite pulse;position:absolute}.call-connecting-animation{z-index:-1;border:3px solid #0000;border-top-color:#2196f3;border-radius:50%;width:100px;height:100px;animation:1s linear infinite spin;position:absolute}.call-info-group{flex-direction:column;flex:1;min-width:0;margin-right:8px;display:flex}.call-title{color:#fff;white-space:normal;text-overflow:clip;margin:0;font-size:16px;font-weight:700;line-height:1.2;overflow:visible}.call-subtitle{color:#ffffffb3;white-space:normal;text-overflow:clip;margin:4px 0 0;font-size:12px;line-height:1.35;overflow:visible}.call-timer{text-align:center;color:#fff;flex-shrink:0;min-width:54px;font-size:13px;font-weight:700}.call-actions{flex-shrink:0;align-items:center;gap:8px;display:flex}.call-actions.connected{justify-content:center;width:100%}.flowengage-call-btn{cursor:pointer;color:#fff;border:none;border-radius:8px;justify-content:center;align-items:center;gap:6px;min-width:92px;padding:8px 12px;font-size:12px;font-weight:600;line-height:1;transition:transform .2s,box-shadow .2s,background .2s;display:flex}.flowengage-call-btn svg{flex-shrink:0;display:block}.flowengage-call-btn span{justify-content:center;align-items:center;line-height:1;display:flex}.flowengage-call-btn.icon-only{border-radius:9999px;width:46px;min-width:46px;height:46px;padding:0}.flowengage-call-btn-accept{background:linear-gradient(135deg,#4caf50,#45a049);box-shadow:0 8px 24px #4caf5066}.flowengage-call-btn-reject,.flowengage-call-btn-end{background:linear-gradient(135deg,#f44336,#d32f2f);box-shadow:0 4px 12px #f4433666}.flowengage-call-btn-mute{background:#ffffff1a;border:2px solid #fff3}.flowengage-call-btn-mute.active{background:#f443364d;border-color:#f44336}.flowengage-call-btn:hover:not(:disabled){transform:scale(1.05)}.incoming-call-overlay.header-mode .flowengage-call-btn{border-radius:9999px!important;width:36px!important;min-width:36px!important;height:36px!important;padding:0!important}.incoming-call-overlay.header-mode .flowengage-call-btn span{display:none!important}.incoming-call-overlay.header-mode .call-icon-wrapper{width:40px;height:40px;margin-right:0}.incoming-call-overlay.header-mode .call-info-group{min-width:0}.incoming-call-overlay.header-mode .call-title,.incoming-call-overlay.header-mode .call-subtitle{white-space:nowrap;text-overflow:ellipsis;overflow:hidden}@media (width<=640px){.incoming-call-container{align-items:flex-start;gap:10px;padding:12px 14px}.incoming-call-container.connected-layout{align-items:stretch}.call-connected-top{flex-direction:column;align-items:flex-start;gap:10px}.call-connected-identity{width:100%}.call-info-group{margin-right:0}.call-actions{flex-wrap:wrap;align-self:stretch;gap:6px}.call-actions.connected{justify-content:stretch}.call-actions.connected .flowengage-call-btn{flex:1}.flowengage-call-btn{min-width:78px;padding:8px 10px}}@keyframes slideUpBanner{0%{transform:translateY(100%)}to{transform:translateY(0)}}@keyframes slideDownBanner{0%{transform:translateY(-100%)}to{transform:translateY(0)}}@keyframes bounce{0%,to{animation-timing-function:cubic-bezier(.8,0,1,1);transform:translateY(-25%)}50%{animation-timing-function:cubic-bezier(0,0,.2,1);transform:none}}@keyframes pulse{50%{opacity:.5}}@keyframes spin{to{transform:rotate(360deg)}}.fe-screen-fade-in{animation:.4s cubic-bezier(.16,1,.3,1) forwards feFadeIn}@keyframes feFadeIn{0%{opacity:0;transform:translateY(12px)}to{opacity:1;transform:translateY(0)}}.flowengage-initial-bg{background-color:#fff;position:relative;overflow:hidden}.flowengage-initial-bg:before{content:"";background:linear-gradient(to bottom, var(--flowengage-primary) 0%, var(--flowengage-primary) 55%, white 82%);opacity:0;pointer-events:none;z-index:0;transition:opacity .6s cubic-bezier(.4,0,.2,1);position:absolute;inset:0}.flowengage-initial-bg.is-initial:before{opacity:1}.flowengage-content-wrapper{z-index:1;flex-direction:column;flex:1;min-height:0;display:flex;position:relative}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"<length>";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}@property --tw-ease{syntax:"*";inherits:false}`,fg=null,pg=!1;function mg(){if(typeof document>`u`||document.getElementById(`flowengage-styles`))return;let e=document.createElement(`style`);e.id=`flowengage-styles`,e.innerHTML=dg,document.head.appendChild(e)}function hg(e){if(document.body){e();return}let t=new MutationObserver(()=>{document.body&&(t.disconnect(),e())});t.observe(document.documentElement,{childList:!0})}function gg({siteId:e,language:t=`en`,widgetSettings:n={},apiBaseUrl:r}){if(pg){console.warn(`[FlowEngage] Already initialized. Call FlowEngage.destroy() first to re-initialize.`);return}if(!e){console.error(`[FlowEngage] siteId is required. Pass it via data-site-id attribute or FlowEngage.init({ siteId: 'YOUR_SITE_ID' }).`);return}if(!document.body){console.error(`[FlowEngage] document.body is not available yet. The widget will auto-retry once the DOM is ready.`),hg(()=>gg({siteId:e,language:t,widgetSettings:n,apiBaseUrl:r}));return}if(document.getElementById(`flowengage-root`)){console.warn(`[FlowEngage] #flowengage-root already exists. Skipping duplicate mount.`);return}let i=document.createElement(`div`);i.id=`flowengage-root`,document.body.appendChild(i),mg(),fg=(0,y.createRoot)(i);let a={widgetSettings:n,...r&&{apiBaseUrl:r}};fg.render(v.createElement(hn,{siteId:e,language:t,config:a},v.createElement(ug))),pg=!0}var _g={init({siteId:e,language:t=`en`,widgetSettings:n={},apiBaseUrl:r}={}){document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>hg(()=>gg({siteId:e,language:t,widgetSettings:n,apiBaseUrl:r}))):hg(()=>gg({siteId:e,language:t,widgetSettings:n,apiBaseUrl:r}))},destroy(){fg&&=(fg.unmount(),null);let e=document.getElementById(`flowengage-root`);e&&e.remove();let t=document.getElementById(`flowengage-styles`);t&&t.remove(),pg=!1}},vg=()=>{let e=document.currentScript;(!e||!e.getAttribute(`data-site-id`))&&(e=document.querySelector(`script[data-site-id]`));let t=e?.getAttribute(`data-site-id`);if(!t)return;let n=e?.getAttribute(`data-language`)||`en`,r=e?.getAttribute(`data-api-url`)||void 0,i={};try{let t=e?.getAttribute(`data-widget-settings`);t&&(i=JSON.parse(t))}catch{}let a={widgetSettings:i,...r&&{apiBaseUrl:r}};hg(()=>gg({siteId:t,language:n,widgetSettings:a.widgetSettings,apiBaseUrl:r}))};return document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,vg):vg(),typeof window<`u`&&(window.FlowEngage=_g),_g})();
|
|
@@ -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){Yt()&&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){let t=Ah(e);if(Array.isArray(t)&&t.length>0){let e=t[0];if(e?.field_key!=null||e?.fieldKey!=null)return t.map(e=>({field_key:e.field_key??e.fieldKey,value:e.value}))}if(!t||typeof t!=`object`)return[];let n=t.fields??t.Fields??t.field_list??t.fieldList??t.data?.fields;if(typeof n==`string`)try{n=JSON.parse(n)}catch{n=null}n&&!Array.isArray(n)&&typeof n==`object`&&(n=Object.values(n)),(!n||n.length===0)&&(t.field_key!=null||t.fieldKey!=null)&&t.value!=null&&(n=[{field_key:t.field_key??t.fieldKey,value:t.value}]);let r=t.website_url??t.websiteUrl??t.url??t.website??t.domain??t.site_url??t.siteUrl;return(!n||n.length===0)&&r!=null&&String(r).trim()&&(n=[{field_key:t.field_key??t.fieldKey??`url`,value:String(r).trim()}]),Array.isArray(n)?n.map(e=>({field_key:e?.field_key??e?.fieldKey,value:e?.value??e?.Value})):[]}function Mh(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 Nh(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 Ph(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;let a={bubbles:!0,cancelable:!0,composed:!0};try{e.dispatchEvent(new InputEvent(`input`,{...a,inputType:`insertText`,data:i}))}catch{e.dispatchEvent(new Event(`input`,a))}e.dispatchEvent(new Event(`change`,a));try{queueMicrotask(()=>{try{e.dispatchEvent(new Event(`input`,a)),e.dispatchEvent(new Event(`change`,a))}catch{}})}catch{}return!0}function Fh(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=Mh(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 nn(n),await new Promise(e=>setTimeout(e,400)),r&&typeof r==`string`){let e=Qt(null,r);e&&$t(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=Qt(n||null,r||null);return i?($t(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=Nh(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{$(`fill_form_fields ▶ raw:`,e);let t=jh(e);if($(`fill_form_fields · normalized fields:`,t),!t.length)return`No fields provided. Call list_page_forms, then fill_form_fields with { "fields": [ { "field_key": "url or Enter Website URL", "value": "https://..." } ] }.`;let n=[];for(let e of t){let t=e?.field_key??e?.fieldKey,r=e?.value;if(t==null||r==null)continue;let i=yh(),a=Dh(i,String(t));a||=wh(i,String(t)),a||=Th(i,String(t),r),a&&(Ph(a,r),n.push(String(t)))}if(!n.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 r=`OK_FILLED: ${n.join(`, `)}`;return $(`fill_form_fields ✓`,r),r}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}}function Ih(e){return!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,async n=>{let r=Yt();r?console.log(`[FlowEngage:voice-tool] ▶`,e,n):console.info(`[FlowEngage] voice tool » ${e}`);let i=await t(n),a=typeof i==`string`?i.length>220?`${i.slice(0,220)}…`:i:String(i);return r?console.log(`[FlowEngage:voice-tool] ◀`,e,a):console.info(`[FlowEngage] voice tool « ${e}:`,a),i}]))}var Lh={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)`},Rh={idle:`#6366f1`,listening:`#10b981`,speaking:`#f59e0b`,error:`#ef4444`};function zh({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,ee]=(0,l.useState)(null),[m,te]=(0,l.useState)(!1),[ne,re]=(0,l.useState)([]),ie=(0,l.useRef)(null),ae=(0,l.useRef)(null);(0,l.useEffect)(()=>{let t=!1,i=null;return(async()=>{try{if(await navigator.mediaDevices.getUserMedia({audio:!0}),t)return;re([]);let o=Ih(Fh({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],re(e=>[...e,i])},onError:e=>{t||(console.error(`[VoiceInterface] ElevenLabs error`,e),f(`error`),ee(`Voice session encountered an error.`))},onDisconnect:()=>{t||(console.log(`[VoiceInterface] session disconnected`),te(!1),f(`idle`))}});if(t){s.endSession().catch(()=>{});return}i=s,ie.current=s,te(!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`),ee(`Could not start voice session. Please try again.`))}})(),()=>{t=!0,i?i.endSession().catch(()=>{}):ie.current&&ie.current.endSession().catch(()=>{})}},[e,n,r,a,c]);let h=(0,l.useCallback)(async()=>{try{await ie.current?.endSession?.()}catch{}ie.current=null,te(!1),f(`idle`),typeof s==`function`&&await s(a.current),typeof i==`function`&&i()},[a,s,i]),oe=d===`listening`||d===`speaking`,se=Rh[d]||Rh.idle,ce=Lh[d]||Lh.idle;return(0,u.jsxs)(`div`,{ref:ae,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:[oe&&(0,u.jsx)(`div`,{style:{position:`absolute`,inset:`-16px`,borderRadius:`50%`,border:`2px solid ${se}`,animation:`fe-orb-pulse 1.4s ease-in-out infinite`,opacity:.6}}),oe&&(0,u.jsx)(`div`,{style:{position:`absolute`,inset:`-8px`,borderRadius:`50%`,border:`2px solid ${se}`,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:ce,border:`3px solid ${se}`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`all 0.35s ease`,transform:d===`speaking`?`scale(1.08)`:`scale(1)`,boxShadow:`0 0 40px ${ce}, 0 8px 32px rgba(0,0,0,0.08)`},children:(0,u.jsx)(fn,{size:44,color:se})})]}),(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`)]}),ne.length>0&&(0,u.jsx)(`div`,{style:{width:`100%`,maxHeight:`160px`,overflowY:`auto`,display:`flex`,flexDirection:`column`,gap:`8px`,padding:`0 4px`},children:ne.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:h,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)(pn,{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){Yt()&&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){return e==null?null:String(e).replace(/\u00a0/g,` `).replace(/\s*\*+\s*$/u,``).replace(/\s+/g,` `).trim()}function yh(e){let t=e.ownerDocument||document,n=e.getAttribute(`aria-labelledby`);if(n){let e=n.trim().split(/\s+/).filter(Boolean),r=[];for(let n of e)try{let e=t.getElementById(n);e?.textContent&&r.push(e.textContent.trim())}catch{}if(r.length)return vh(r.join(` `))}if(e.labels&&e.labels.length)return vh(e.labels[0].textContent);let r=e.id;if(r)try{let e=t.querySelector(`label[for="${CSS.escape(r)}"]`);if(e)return vh(e.textContent)}catch{let e=t.querySelector(`label[for="${r.replace(/"/g,`\\"`)}"]`);if(e)return vh(e.textContent)}let i=e.previousElementSibling;for(let e=0;e<6&&i;e+=1){if(i.tagName===`LABEL`)return vh(i.textContent);let e=(i.className||``).toString().toLowerCase();if(/chakra-form__label|formlabel|field-label|form-label|mui-form-label/.test(e)){let e=vh(i.textContent);if(e)return e}i=i.previousElementSibling}let a=e.parentElement;for(let e=0;e<5&&a;e+=1){if(a.tagName===`LABEL`)return vh(a.textContent);let e=a.querySelector?.(`:scope > label, :scope > [class*='FormLabel'], :scope > [class*='form__label']`);if(e?.textContent)return vh(e.textContent);a=a.parentElement}let o=e.getAttribute(`aria-label`);return o?vh(o):null}function bh(){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||e.readOnly)return!1;try{let t=gh(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e}function xh(){return bh().map((e,t)=>({formIndex:0,fieldIndex:t,tag:e.tagName,type:e.type||`text`,name:e.name||null,id:e.id||null,label:yh(e),placeholder:e.placeholder||null}))}function Sh(){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 Ch(e){return String(e||``).toLowerCase().replace(/\u00a0/g,` `).replace(/\*/g,``).replace(/\s+/g,` `).trim()}function wh(e){let t=Ch(e);return t=t.replace(/\s+field\s*$/i,``).trim(),t}function Th(e,t){let n=wh(t);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,yh(e),e.getAttribute(`aria-label`),e.getAttribute(`title`),e.getAttribute(`data-testid`),e.getAttribute(`autocomplete`)].filter(Boolean).map(e=>Ch(e)),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 Eh=28;function Dh(e,t){let n=null,r=0;for(let i of e){let e=Th(i,t);e>r&&(r=e,n=i)}return!n||r<Eh?null:n}function Oh(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,yh(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 kh(e){let t=String(e??``).trim();return t?/^https?:\/\//i.test(t)?!0:/\.\w{2,}(\/|\s|$)/.test(t):!1}function Ah(e){let t=String(e??``).toLowerCase().trim();return t?!!(t===`url`||t===`website`||t===`website url`||t===`website_url`||t===`enter website url`||t.includes(`website`)||t.includes(`domain`)||/(enter\s+website|site\s*url|page\s*url)/.test(t)):!1}function jh(e){if(!e||e.tagName!==`INPUT`&&e.tagName!==`TEXTAREA`)return!1;let t=(e.type||``).toLowerCase();return![`hidden`,`submit`,`button`,`checkbox`,`radio`,`file`].includes(t)}function Mh(e){if(!jh(e))return!1;let t=(e.name||``).toLowerCase(),n=(e.id||``).toLowerCase(),r=[e.name,e.id,e.placeholder,yh(e),e.getAttribute(`aria-label`)].filter(Boolean).join(` `).toLowerCase();return t===`url`||n===`url-input`||n.endsWith(`-url-input`)||/(website\s*url|enter\s+website|site\s*url)/.test(r)||/(website|domain)/.test(r)&&/(url|site)/.test(r)}function Nh(e,t,n){let r=String(t??``),i=String(n??``),a=Ih(e,r)||Dh(e,r)||Oh(e,r,i);if(!a)return[];let o=new Set([a]);if(kh(i)&&Ah(r))for(let t of e)t!==a&&Mh(t)&&o.add(t);let s=Array.from(o);return s.sort((e,t)=>{if(e===t)return 0;let n=e.compareDocumentPosition(t);return n&Node.DOCUMENT_POSITION_FOLLOWING?-1:n&Node.DOCUMENT_POSITION_PRECEDING?1:0}),s}function Ph(e,t){try{if(!e?.getBoundingClientRect||!t?.getBoundingClientRect)return 1/0;let n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),i={x:n.left+n.width/2,y:n.top+n.height/2},a={x:r.left+r.width/2,y:r.top+r.height/2};return Math.hypot(i.x-a.x,i.y-a.y)}catch{return 1/0}}function Fh(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 Ih(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=Fh(i[1]);if(e)return e}let a=n.startsWith(`#`)?n.slice(1):n;if(/^[\w-]+$/.test(a)){let e=Fh(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 Lh(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 Rh(e,t){let n=[];_h(e=>{n.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 r=0,i=n.map(t=>({el:t,s:Lh(t,e)}));for(let{s:e}of i)e>r&&(r=e);if(r<36)return null;let a=i.filter(({s:e})=>e===r).map(({el:e})=>e);if(a.length===1)return a[0];let o=Array.isArray(t)?t.filter(e=>e&&e.isConnected):[];if(o.length){let e=a[0],t=1/0;for(let n of a)for(let r of o){let i=Ph(n,r);i<t&&(t=i,e=n)}return e}return a[0]}function zh(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 Bh(e){let t=zh(e);if(Array.isArray(t)&&t.length>0){let e=t[0];if(e?.field_key!=null||e?.fieldKey!=null)return t.map(e=>({field_key:e.field_key??e.fieldKey,value:e.value}))}if(!t||typeof t!=`object`)return[];let n=t.fields??t.Fields??t.field_list??t.fieldList??t.data?.fields;if(typeof n==`string`)try{n=JSON.parse(n)}catch{n=null}n&&!Array.isArray(n)&&typeof n==`object`&&(n=Object.values(n)),(!n||n.length===0)&&(t.field_key!=null||t.fieldKey!=null)&&t.value!=null&&(n=[{field_key:t.field_key??t.fieldKey,value:t.value}]);let r=t.website_url??t.websiteUrl??t.url??t.website??t.domain??t.site_url??t.siteUrl;return(!n||n.length===0)&&r!=null&&String(r).trim()&&(n=[{field_key:t.field_key??t.fieldKey??`url`,value:String(r).trim()}]),Array.isArray(n)?n.map(e=>({field_key:e?.field_key??e?.fieldKey,value:e?.value??e?.Value})):[]}function Vh(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t)return[];let n=t.match(/https?:\/\/[^\s<>"']+/i);if(n)return[{field_key:`url`,value:n[0].replace(/[.,;:)]+$/,``)}];let r=t.match(/\b(?:[\w-]+\.)+[a-z]{2,}\b/i);if(r){let e=r[0].replace(/[.,;:)]+$/,``);return/^https?:/i.test(e)||(e=`https://${e}`),[{field_key:`url`,value:e}]}return[]}function Hh(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t)return[];let n=[],r=new Set,i=(e,t)=>{let i=String(t??``).trim().replace(/^["']|["']$/g,``);if(!i||i.length>800)return;let a=`${e}\0${i}`;r.has(a)||(r.add(a),n.push({field_key:e,value:i}))},a=t.match(/\b(?:please\s+)?(?:enter|type|put)\s+(.+?)\s+in(?:to)?\s+(?:the\s+)?(?:full\s*name|full\s*name\s*field|name\s*field)\b/i);if(a&&i(`Full Name`,a[1]),a=t.match(/\bfull\s*name,?\s*(?:please\s+)?(?:enter|type|put)\s+(.+?)(?:\.|$|!|\?)/i),a&&i(`Full Name`,a[1]),a=t.match(/\bfull\s*name\s*(?:is|:|please\s+enter|-)\s*(.+?)(?:\.|$|(?=\s+(?:and|my\s+email|email|message))\b)/i),a&&i(`Full Name`,a[1]),a=t.match(/\b(.+?)\s+for\s+(?:the\s+)?full\s*name\b/i),a){let e=a[1].trim();e.length>1&&e.length<120&&!/@/.test(e)&&i(`Full Name`,e)}if(a=t.match(/\b(?:email|e-mail)(?:\s*address)?\s*(?:is|:|please\s+use|enter|-)\s*([^\s@]+@[^\s@]+\.[^\s,]+)/i),a&&i(`Email Address`,a[1]),a=t.match(/\b(?:enter|type|put)\s+([^\s@]+@[^\s@]+\.[^\s,]+)\s+in(?:to)?\s+(?:the\s+)?(?:email|e-mail)/i),a&&i(`Email Address`,a[1]),a=t.match(/\b(?:message|comment)\s*(?:is|:|please\s+enter|-)\s*(.+)$/is),a){let e=a[1].trim();e.length>0&&i(`Message`,e)}return n}function Uh(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 Wh(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 Gh(e,t,n){if(!n?.skipScroll)try{e.scrollIntoView({block:`center`,inline:`nearest`})}catch{try{e.scrollIntoView(!0)}catch{}}try{e.focus({preventScroll:!0})}catch{try{e.focus()}catch{}}let r=e.tagName,i=(e.type||``).toLowerCase();if(r===`SELECT`)return e.value=String(t),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;if(i===`checkbox`||i===`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 a=String(t);if(r===`INPUT`||r===`TEXTAREA`){let t=e.ownerDocument?.defaultView||window,n=r===`TEXTAREA`?t.HTMLTextAreaElement.prototype:t.HTMLInputElement.prototype,i=Object.getOwnPropertyDescriptor(n,`value`);i?.set?i.set.call(e,a):e.value=a}else e.value=a;let o={bubbles:!0,cancelable:!0,composed:!0};try{e.dispatchEvent(new InputEvent(`input`,{...o,inputType:`insertText`,data:a}))}catch{e.dispatchEvent(new Event(`input`,o))}e.dispatchEvent(new Event(`change`,o));try{queueMicrotask(()=>{try{e.dispatchEvent(new Event(`input`,o)),e.dispatchEvent(new Event(`change`,o))}catch{}})}catch{}return!0}function Kh(e){let t=e.siteId||null,n=(e.apiBaseUrl||``).replace(/\/$/,``),r=typeof e.getLastUserVoiceText==`function`?e.getLastUserVoiceText:null,i=[],a={navigate_to_page:async e=>{$(`navigate_to_page ▶ raw parameters:`,e);let t=zh(e),n=Uh(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 nn(n),await new Promise(e=>setTimeout(e,400)),r&&typeof r==`string`){let e=Qt(null,r);e&&$t(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=zh(e),n=t?.section_id||t?.sectionId,r=t?.section_text||t?.sectionText,i=Qt(n||null,r||null);return i?($t(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=Wh(zh(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=xh(),t=Sh();return $(`list_page_forms ✓`,`${e.length} field(s)`,`${t.length} button(s)`),JSON.stringify({fields:e,buttons:t,hint:`field_key: placeholder/label, name (e.g. url), id (e.g. url-input). If the page has two URL boxes, fill_form_fields sets all matching URL inputs. click_page_button picks the Conduct Audit nearest the filled field when labels duplicate.`})},fill_form_fields:async e=>{try{$(`fill_form_fields ▶ raw:`,e);let t=Bh(e);if(!t.length&&r){let e=r(),n=Vh(e);n.length?$(`fill_form_fields · inferred URL from last user utterance (model omitted usable fields):`,n):(n=Hh(e),n.length&&$(`fill_form_fields · inferred contact fields from last user utterance (empty tool params):`,n)),n.length&&(t=n)}if($(`fill_form_fields · normalized fields:`,t),!t.length)return`No fields provided. Call list_page_forms, then fill_form_fields with { "fields": [ { "field_key": "url or Enter Website URL", "value": "https://..." } ] }. Do not call with empty {}.`;let n=[];for(let e of t){let t=e?.field_key??e?.fieldKey,r=e?.value;if(t==null||r==null)continue;let a=bh(),o=Nh(a,String(t),r);if(o.length){o.forEach((e,t)=>{Gh(e,r,{skipScroll:t>0})}),i=o,n.push(String(t));continue}let s=Ih(a,String(t));s||=Dh(a,String(t)),s||=Oh(a,String(t),r),s&&(Gh(s,r),i=[s],n.push(String(t)))}if(!n.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 a=`OK_FILLED: ${n.join(`, `)}`;return $(`fill_form_fields ✓`,a),a}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=zh(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=Rh(n,i);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{...a,navigateToPage:a.navigate_to_page,highlightOnPage:a.highlight_on_page,searchSiteContent:a.search_site_content,listPageForms:a.list_page_forms,fillFormFields:a.fill_form_fields,clickPageButton:a.click_page_button}}function qh(e){return!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,async n=>{let r=Yt();r?console.log(`[FlowEngage:voice-tool] ▶`,e,n):console.info(`[FlowEngage] voice tool » ${e}`);let i=await t(n),a=typeof i==`string`?i.length>220?`${i.slice(0,220)}…`:i:String(i);return r?console.log(`[FlowEngage:voice-tool] ◀`,e,a):console.info(`[FlowEngage] voice tool « ${e}:`,a),i}]))}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)`},Yh={idle:`#6366f1`,listening:`#10b981`,speaking:`#f59e0b`,error:`#ef4444`};function Xh({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,ee]=(0,l.useState)(null),[m,te]=(0,l.useState)(!1),[ne,re]=(0,l.useState)([]),ie=(0,l.useRef)(null),ae=(0,l.useRef)(null),h=(0,l.useRef)(``);(0,l.useEffect)(()=>{let t=!1,i=null;return(async()=>{try{if(await navigator.mediaDevices.getUserMedia({audio:!0}),t)return;re([]),h.current=``;let o=qh(Kh({siteId:n||null,apiBaseUrl:r||null,getLastUserVoiceText:()=>h.current})),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()};n===`user`&&(h.current=r),a.current=[...a.current,i],re(e=>[...e,i])},onError:e=>{t||(console.error(`[VoiceInterface] ElevenLabs error`,e),f(`error`),ee(`Voice session encountered an error.`))},onDisconnect:()=>{t||(console.log(`[VoiceInterface] session disconnected`),te(!1),f(`idle`))}});if(t){s.endSession().catch(()=>{});return}i=s,ie.current=s,te(!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`),ee(`Could not start voice session. Please try again.`))}})(),()=>{t=!0,i?i.endSession().catch(()=>{}):ie.current&&ie.current.endSession().catch(()=>{})}},[e,n,r,a,c]);let oe=(0,l.useCallback)(async()=>{try{await ie.current?.endSession?.()}catch{}ie.current=null,te(!1),f(`idle`),typeof s==`function`&&await s(a.current),typeof i==`function`&&i()},[a,s,i]),se=d===`listening`||d===`speaking`,ce=Yh[d]||Yh.idle,g=Jh[d]||Jh.idle;return(0,u.jsxs)(`div`,{ref:ae,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:[se&&(0,u.jsx)(`div`,{style:{position:`absolute`,inset:`-16px`,borderRadius:`50%`,border:`2px solid ${ce}`,animation:`fe-orb-pulse 1.4s ease-in-out infinite`,opacity:.6}}),se&&(0,u.jsx)(`div`,{style:{position:`absolute`,inset:`-8px`,borderRadius:`50%`,border:`2px solid ${ce}`,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:g,border:`3px solid ${ce}`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`all 0.35s ease`,transform:d===`speaking`?`scale(1.08)`:`scale(1)`,boxShadow:`0 0 40px ${g}, 0 8px 32px rgba(0,0,0,0.08)`},children:(0,u.jsx)(fn,{size:44,color:ce})})]}),(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`)]}),ne.length>0&&(0,u.jsx)(`div`,{style:{width:`100%`,maxHeight:`160px`,overflowY:`auto`,display:`flex`,flexDirection:`column`,gap:`8px`,padding:`0 4px`},children:ne.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:oe,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)(pn,{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 Zh=[{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`}],Qh=()=>(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 $h(){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:ee,isVoiceMode:m,isRateLimited:te,rateLimitMessage:ne,isConversationEnded:re,incomingCall:ie,activeCallId:ae,callConnectionState:h,callConnectedAt:oe,isCallMuted:se,webRTCError:ce,language:g,historyRef:_,onMessageSync:le,endConversation:ue,acceptCall:de,rejectCall:fe,endWebRTCCall:pe,toggleCallMute:me,dismissCallError:he,captureVisitorEmail:ge,openWidget:_e,closeWidget:ve,sendMessage:ye,setVoiceMode:be,startTyping:xe,stopTyping:Se,updateTypingDraft:Ce}=Jt(),[we,Te]=(0,l.useState)(``),[Ee,De]=(0,l.useState)(null),[Oe,ke]=(0,l.useState)(null),[Ae,je]=(0,l.useState)(null),[Me,v]=(0,l.useState)(0),[Ne,Pe]=(0,l.useState)(d||``),[Fe,y]=(0,l.useState)(``),Ie=t?.widgetSettings||{},Le=n?.widgetSettings||{},Re={...Ie.branding||{},...Le.branding||{}},ze={...Ie.theme||{},...Le.theme||{}},Be=ze.primaryColor||`#3B82F6`,Ve=ze.accentColor||`#1D4ED8`,He=(ze.position||`bottom-right`)===`bottom-left`?{left:`1.5rem`,bottom:`1.5rem`}:{right:`1.5rem`,bottom:`1.5rem`},Ue={"--flowengage-primary":Be,"--flowengage-accent":Ve,position:`fixed`,zIndex:999999,border:`none`,outline:`none`,fontFamily:`ui-sans-serif, system-ui, sans-serif`,...a?{}:He},We=Le.recommendations?.[g]||Ie.recommendations?.[g]||Zh,Ge=Le.greetings?.[g]||Ie.greetings?.[g],Ke=Re.chatButtonText||`Chat with us`,b=Re.headerName||t?.websiteName||`OpenSense Labs`,x=Re.logoUrl||null,S=Re.hideWatermark||!1,qe=Le.elevenLabsAgentId||t?.elevenLabsAgentId||null,Je=t?.siteId||n?.siteId||null,Ye=t?.apiBaseUrl||``,Xe=Re.fallbackAgentName||`Agent`,Ze=Re.botLabel||`AI`,Qe=ie?.agentName||c||Xe,$e=!d&&i.length===0;(0,l.useEffect)(()=>{Pe(d||``),d&&y(``)},[d]),(0,l.useEffect)(()=>{if(!oe||h!==`connected`){v(0);return}let e=()=>{let e=new Date(oe).getTime();isNaN(e)||v(Math.max(0,Math.floor((Date.now()-e)/1e3)))};e();let t=window.setInterval(e,1e3);return()=>window.clearInterval(t)},[oe,h]),(0,l.useEffect)(()=>{if(!s||m||re){Ce(``),Se();return}if(!we.trim()){Ce(``),Se();return}xe();let e=window.setTimeout(()=>{Ce(we)},120),t=window.setTimeout(()=>{Se()},1200);return()=>{window.clearTimeout(e),window.clearTimeout(t)}},[we,s,m,re,xe,Se,Ce]);let et=e=>e?{replyTo:e.messageId||e.id||null,replyToContent:(e.replyToContent||e.message||``).replace(/<[^>]+>/g,``).trim().slice(0,200),replyToSender:e.sender||null}:null,tt=async e=>{if(e.preventDefault(),re)return;if($e){let e=Ne.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)){y(`Please enter a valid email to start the chat.`);return}await ge(e),y(``);return}if(!we.trim())return;let t=we.trim(),n=et(Ae);Te(``),je(null),await ye(t,``,n)},nt=async()=>{if($e){y(`Please share your email before starting a call.`);return}if(m){be(!1);return}ke(null);try{De(await navigator.mediaDevices.getUserMedia({audio:!0})),be(!0)}catch(e){ke(e.message||`Could not access microphone.`)}},rt=()=>{Ee&&(Ee.getTracks().forEach(e=>e.stop()),De(null)),be(!1)},it=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:Ue,children:[(0,u.jsx)(bn,{isOpen:a,openWidget:_e,launcherText:Ke,primaryColor:Be,posInline:He}),a&&(0,u.jsxs)(`div`,{className:`flowengage-chat-panel`,style:{background:i.length===0&&!m?`linear-gradient(to bottom, ${Be} 0%, ${Be} 70%, white 85%)`:`white`},children:[(0,u.jsx)(Cn,{logoUrl:x,brandName:b,agentName:c,fallbackAgentName:Xe,activeScreen:o,branding:Re,isConversationEnded:re,endConversation:ue,closeWidget:ve,isInitial:i.length===0&&!m,botLabel:Ze}),(0,u.jsx)(`div`,{style:{flex:1,overflowY:`auto`,display:`flex`,flexDirection:`column`},className:`flowengage-content-wrapper`,children:m?(0,u.jsx)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`},className:`fe-screen-fade-in`,children:(0,u.jsx)(Xh,{agentId:qe,chatId:r,siteId:Je,apiBaseUrl:Ye,historyRef:_,onMessageSync:le,onEnd:rt})},`voice`):i.length===0?(0,u.jsx)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`},className:`fe-screen-fade-in`,children:(0,u.jsx)(On,{greetings:Ge,recommendations:We,onSendMessage:ye,visitorEmail:d,emailInput:Ne,setEmailInput:Pe,emailError:Fe,setEmailError:y,onCaptureEmail:ge,botLabel:Ze})},`welcome`):(0,u.jsx)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`},className:`fe-screen-fade-in`,children:(0,u.jsx)(Dn,{chatHistory:i,isAiTyping:p,isAgentTyping:f,setReplyContext:je,TypingDots:Qh})},`history`)}),(0,u.jsx)(Mn,{webRTCError:ce,micError:Oe,setMicError:ke,dismissCallError:he,incomingCall:ie,rejectCall:fe,acceptCall:de,activeCallId:ae,callConnectionState:h,formatCallDuration:it,callDurationSeconds:Me,endWebRTCCall:pe,isCallMuted:se,toggleCallMute:me,isAIVoiceActive:m,currentCallAgentName:Qe,isRateLimited:te,rateLimitMessage:ne}),!m&&(0,u.jsx)(`div`,{style:{position:`relative`,zIndex:1},children:(0,u.jsx)(kn,{input:we,setInput:Te,onSubmit:tt,isConversationEnded:re,callUiActive:!!(ie||ae),handleToggleVoice:nt,activeScreen:o,inputDisabled:ee||te||re,replyContext:Ae,clearReplyContext:()=>je(null),requiresEmail:$e,emailInput:Ne,setEmailInput:Pe,emailError:Fe})}),!S&&(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=un,exports.FlowEngageWidget=$h,exports.useFlowEngage=Jt;
|