@characterxyz/widget 0.7.2 → 0.8.0

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/cx.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var CharacterXYZWidget=(()=>{var ze=Object.defineProperty;var ii=Object.getOwnPropertyDescriptor;var ai=Object.getOwnPropertyNames;var ri=Object.prototype.hasOwnProperty;var si=(t,e,n)=>e in t?ze(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var oi=(t,e)=>{for(var n in e)ze(t,n,{get:e[n],enumerable:!0})},li=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of ai(e))!ri.call(t,a)&&a!==n&&ze(t,a,{get:()=>e[a],enumerable:!(i=ii(e,a))||i.enumerable});return t};var ci=t=>li(ze({},"__esModule",{value:!0}),t);var V=(t,e,n)=>si(t,typeof e!="symbol"?e+"":e,n);var ga={};oi(ga,{mount:()=>Ze});var ce={position:"bottom-right",mode:"auto",launcher:"bubble",display:"bubble",accent:"#7c5cff",radius:24,font:"",subtitle:null,greeting:"",greetingDelay:3,suggestions:[],placeholder:"Message",showChat:!0,showCall:!0,branding:!0,offsetX:20,offsetY:20,zIndex:2147483e3,open:!1,face:!0,faceUrl:"https://www.character.xyz/embed/face"},ye=(t,e,n)=>{let i=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;return Number.isFinite(i)?Math.min(n,Math.max(e,i)):void 0},ke=t=>{if(typeof t=="boolean")return t;if(t==="true"||t===""||t==="1")return!0;if(t==="false"||t==="0")return!1},ct=(t,e=200)=>typeof t=="string"?t.slice(0,e):void 0;function di(t){if(typeof t!="string")return;let e=t.trim();if(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(e)||/^(rgb|rgba|hsl|hsla|oklch|oklab)\([0-9.,%\s/+-]+\)$/i.test(e)||/^[a-z]{3,20}$/i.test(e))return e}function pi(t){if(typeof t!="string")return;let e=t.trim();return/^[\w\s,"'-]{1,120}$/.test(e)?e:void 0}function he(t,e){if(!e||typeof e!="object")return t;let n={...t};return(e.position==="bottom-left"||e.position==="bottom-right")&&(n.position=e.position),(e.mode==="light"||e.mode==="dark"||e.mode==="auto")&&(n.mode=e.mode),(e.launcher==="bubble"||e.launcher==="actions")&&(n.launcher=e.launcher),(e.display==="bubble"||e.display==="half"||e.display==="full")&&(n.display=e.display),n.accent=di(e.accent)??n.accent,n.radius=ye(e.radius,0,40)??n.radius,n.font=pi(e.font)??n.font,e.subtitle===null?n.subtitle=null:n.subtitle=ct(e.subtitle,80)??n.subtitle,n.greeting=ct(e.greeting,160)??n.greeting,n.greetingDelay=ye(e.greetingDelay,0,120)??n.greetingDelay,Array.isArray(e.suggestions)?n.suggestions=e.suggestions.filter(i=>typeof i=="string"&&i.trim()!=="").map(i=>i.slice(0,80)).slice(0,4):typeof e.suggestions=="string"&&(n.suggestions=e.suggestions.split("|").map(i=>i.trim()).filter(Boolean).slice(0,4)),n.placeholder=ct(e.placeholder,60)??n.placeholder,n.showChat=ke(e.showChat)??n.showChat,n.showCall=ke(e.showCall)??n.showCall,n.branding=ke(e.branding)??n.branding,n.offsetX=ye(e.offsetX,0,200)??n.offsetX,n.offsetY=ye(e.offsetY,0,200)??n.offsetY,n.zIndex=ye(e.zIndex,0,2147483647)??n.zIndex,n.open=ke(e.open)??n.open,n.face=ke(e.face)??n.face,typeof e.faceUrl=="string"&&/^https?:\/\/[^\s"'<>]+$/.test(e.faceUrl.trim())&&(n.faceUrl=e.faceUrl.trim()),n}function De(t){let e={};for(let{name:n,value:i}of t){let a=n.replace(/^data-/,"").replace(/-([a-z])/g,(s,o)=>o.toUpperCase());e[a]=i}return e}var ui=Object.defineProperty,hi=(t,e,n)=>e in t?ui(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,v=(t,e,n)=>hi(t,typeof e!="symbol"?e+"":e,n),fe=null;function Dt(){return(!fe||fe.state==="closed")&&(fe=new AudioContext({latencyHint:"interactive"})),fe.state==="suspended"&&fe.resume().catch(()=>{}),fe}var fi=class{constructor(t={}){v(this,"opts",t),v(this,"ctx"),v(this,"gain"),v(this,"analyser"),v(this,"data"),v(this,"nextAt",0),v(this,"started",!1),v(this,"ended",!1),v(this,"finishing",!1),v(this,"sources",new Set),v(this,"startedAt",0),v(this,"sampleRate"),this.ctx=Dt(),this.sampleRate=t.sampleRate??16e3,this.gain=this.ctx.createGain(),this.gain.gain.value=t.volume??1,this.analyser=this.ctx.createAnalyser(),this.analyser.fftSize=512,this.data=new Uint8Array(new ArrayBuffer(this.analyser.fftSize)),this.gain.connect(this.analyser).connect(this.ctx.destination)}enqueue(t){if(this.ended||t.byteLength<2)return;let e=Math.floor(t.byteLength/2),n=new DataView(t.buffer,t.byteOffset,e*2),i=this.ctx.createBuffer(1,e,this.sampleRate),a=i.getChannelData(0);for(let l=0;l<e;l++)a[l]=n.getInt16(l*2,!0)/32768;let s=this.ctx.createBufferSource();s.buffer=i,s.connect(this.gain);let o=this.ctx.currentTime;if(this.nextAt<o&&(this.nextAt=o+(this.started?.02:.12)),s.start(this.nextAt),!this.started){this.started=!0;let l=Math.max(0,(this.nextAt-o)*1e3);this.startedAt=performance.now()+l,setTimeout(()=>this.opts.onStart?.(),l)}this.nextAt+=i.duration,this.sources.add(s),s.onended=()=>{this.sources.delete(s),this.finishing&&this.sources.size===0&&this.finish()}}end(){this.finishing=!0,this.sources.size===0&&this.finish()}stop(){this.ended=!0;for(let t of this.sources)try{t.stop()}catch{}this.sources.clear(),this.gain.disconnect()}playedMs(){return this.started?Math.max(0,performance.now()-this.startedAt):0}level(){this.analyser.getByteTimeDomainData(this.data);let t=0;for(let e=0;e<this.data.length;e++){let n=(this.data[e]-128)/128;t+=n*n}return Math.min(1,Math.sqrt(t/this.data.length)*3)}finish(){this.ended||(this.ended=!0,this.gain.disconnect(),this.opts.onEnd?.())}},gi=`
1
+ "use strict";var CharacterXYZWidget=(()=>{var ze=Object.defineProperty;var ii=Object.getOwnPropertyDescriptor;var ai=Object.getOwnPropertyNames;var ri=Object.prototype.hasOwnProperty;var si=(t,e,n)=>e in t?ze(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var oi=(t,e)=>{for(var n in e)ze(t,n,{get:e[n],enumerable:!0})},li=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of ai(e))!ri.call(t,a)&&a!==n&&ze(t,a,{get:()=>e[a],enumerable:!(i=ii(e,a))||i.enumerable});return t};var ci=t=>li(ze({},"__esModule",{value:!0}),t);var j=(t,e,n)=>si(t,typeof e!="symbol"?e+"":e,n);var ga={};oi(ga,{mount:()=>Ge});var de={position:"bottom-right",mode:"auto",launcher:"bubble",display:"bubble",accent:"#7c5cff",radius:24,font:"",subtitle:null,greeting:"",greetingDelay:3,suggestions:[],placeholder:"Message",showChat:!0,showCall:!0,branding:!0,offsetX:20,offsetY:20,zIndex:2147483e3,open:!1,face:!0,faceUrl:"https://www.character.xyz/embed/face"},ke=(t,e,n)=>{let i=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;return Number.isFinite(i)?Math.min(n,Math.max(e,i)):void 0},we=t=>{if(typeof t=="boolean")return t;if(t==="true"||t===""||t==="1")return!0;if(t==="false"||t==="0")return!1},ut=(t,e=200)=>typeof t=="string"?t.slice(0,e):void 0;function di(t){if(typeof t!="string")return;let e=t.trim();if(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(e)||/^(rgb|rgba|hsl|hsla|oklch|oklab)\([0-9.,%\s/+-]+\)$/i.test(e)||/^[a-z]{3,20}$/i.test(e))return e}function pi(t){if(typeof t!="string")return;let e=t.trim();return/^[\w\s,"'-]{1,120}$/.test(e)?e:void 0}function fe(t,e){if(!e||typeof e!="object")return t;let n={...t};return(e.position==="bottom-left"||e.position==="bottom-right")&&(n.position=e.position),(e.mode==="light"||e.mode==="dark"||e.mode==="auto")&&(n.mode=e.mode),(e.launcher==="bubble"||e.launcher==="actions")&&(n.launcher=e.launcher),(e.display==="bubble"||e.display==="half"||e.display==="full")&&(n.display=e.display),n.accent=di(e.accent)??n.accent,n.radius=ke(e.radius,0,40)??n.radius,n.font=pi(e.font)??n.font,e.subtitle===null?n.subtitle=null:n.subtitle=ut(e.subtitle,80)??n.subtitle,n.greeting=ut(e.greeting,160)??n.greeting,n.greetingDelay=ke(e.greetingDelay,0,120)??n.greetingDelay,Array.isArray(e.suggestions)?n.suggestions=e.suggestions.filter(i=>typeof i=="string"&&i.trim()!=="").map(i=>i.slice(0,80)).slice(0,4):typeof e.suggestions=="string"&&(n.suggestions=e.suggestions.split("|").map(i=>i.trim()).filter(Boolean).slice(0,4)),n.placeholder=ut(e.placeholder,60)??n.placeholder,n.showChat=we(e.showChat)??n.showChat,n.showCall=we(e.showCall)??n.showCall,n.branding=we(e.branding)??n.branding,n.offsetX=ke(e.offsetX,0,200)??n.offsetX,n.offsetY=ke(e.offsetY,0,200)??n.offsetY,n.zIndex=ke(e.zIndex,0,2147483647)??n.zIndex,n.open=we(e.open)??n.open,n.face=we(e.face)??n.face,typeof e.faceUrl=="string"&&/^https?:\/\/[^\s"'<>]+$/.test(e.faceUrl.trim())&&(n.faceUrl=e.faceUrl.trim()),n}function De(t){let e={};for(let{name:n,value:i}of t){let a=n.replace(/^data-/,"").replace(/-([a-z])/g,(s,o)=>o.toUpperCase());e[a]=i}return e}var ui=Object.defineProperty,hi=(t,e,n)=>e in t?ui(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,y=(t,e,n)=>hi(t,typeof e!="symbol"?e+"":e,n),ge=null;function Pt(){return(!ge||ge.state==="closed")&&(ge=new AudioContext({latencyHint:"interactive"})),ge.state==="suspended"&&ge.resume().catch(()=>{}),ge}var fi=class{constructor(t={}){y(this,"opts",t),y(this,"ctx"),y(this,"gain"),y(this,"analyser"),y(this,"data"),y(this,"nextAt",0),y(this,"started",!1),y(this,"ended",!1),y(this,"finishing",!1),y(this,"sources",new Set),y(this,"startedAt",0),y(this,"sampleRate"),this.ctx=Pt(),this.sampleRate=t.sampleRate??16e3,this.gain=this.ctx.createGain(),this.gain.gain.value=t.volume??1,this.analyser=this.ctx.createAnalyser(),this.analyser.fftSize=512,this.data=new Uint8Array(new ArrayBuffer(this.analyser.fftSize)),this.gain.connect(this.analyser).connect(this.ctx.destination)}enqueue(t){if(this.ended||t.byteLength<2)return;let e=Math.floor(t.byteLength/2),n=new DataView(t.buffer,t.byteOffset,e*2),i=this.ctx.createBuffer(1,e,this.sampleRate),a=i.getChannelData(0);for(let l=0;l<e;l++)a[l]=n.getInt16(l*2,!0)/32768;let s=this.ctx.createBufferSource();s.buffer=i,s.connect(this.gain);let o=this.ctx.currentTime;if(this.nextAt<o&&(this.nextAt=o+(this.started?.02:.12)),s.start(this.nextAt),!this.started){this.started=!0;let l=Math.max(0,(this.nextAt-o)*1e3);this.startedAt=performance.now()+l,setTimeout(()=>this.opts.onStart?.(),l)}this.nextAt+=i.duration,this.sources.add(s),s.onended=()=>{this.sources.delete(s),this.finishing&&this.sources.size===0&&this.finish()}}end(){this.finishing=!0,this.sources.size===0&&this.finish()}stop(){this.ended=!0;for(let t of this.sources)try{t.stop()}catch{}this.sources.clear(),this.gain.disconnect()}playedMs(){return this.started?Math.max(0,performance.now()-this.startedAt):0}level(){this.analyser.getByteTimeDomainData(this.data);let t=0;for(let e=0;e<this.data.length;e++){let n=(this.data[e]-128)/128;t+=n*n}return Math.min(1,Math.sqrt(t/this.data.length)*3)}finish(){this.ended||(this.ended=!0,this.gain.disconnect(),this.opts.onEnd?.())}},gi=`
2
2
  class CxyzMic extends AudioWorkletProcessor {
3
3
  constructor(o) {
4
4
  super();
@@ -30,16 +30,16 @@ class CxyzMic extends AudioWorkletProcessor {
30
30
  }
31
31
  }
32
32
  registerProcessor('cxyz-mic', CxyzMic);
33
- `;function mi(t){let e=new Int16Array(t);if(!e.length)return 0;let n=0;for(let i=0;i<e.length;i++){let a=e[i]/32768;n+=a*a}return Math.sqrt(n/e.length)}async function _i(t){if(!navigator.mediaDevices?.getUserMedia)throw new Error("This browser cannot use a microphone here.");let e=await navigator.mediaDevices.getUserMedia({audio:{deviceId:t.deviceId?{exact:t.deviceId}:void 0,channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}),n=new AudioContext({latencyHint:"interactive"}),i=n.createMediaStreamSource(e),a=!1,s=d=>{if(a){t.onFrame(new ArrayBuffer(d.byteLength),0);return}t.onFrame(d,mi(d))},o,l;try{let d=URL.createObjectURL(new Blob([gi],{type:"application/javascript"}));try{await n.audioWorklet.addModule(d)}finally{URL.revokeObjectURL(d)}let f=new AudioWorkletNode(n,"cxyz-mic");f.port.onmessage=m=>s(m.data),o=f,l=()=>{f.port.onmessage=null}}catch{let d=n.createScriptProcessor(4096,1,1),f=n.sampleRate/16e3,m=0,c=new Int16Array(480),g=0;d.onaudioprocess=x=>{let b=x.inputBuffer.getChannelData(0);for(let _=0;_<b.length;_++)if(m+=1,m>=f){m-=f;let k=Math.max(-1,Math.min(1,b[_]));c[g++]=k<0?k*32768:k*32767,g===480&&(s(c.buffer),c=new Int16Array(480),g=0)}},o=d,l=()=>{d.onaudioprocess=null}}i.connect(o);let p=n.createGain();return p.gain.value=0,o.connect(p).connect(n.destination),n.state==="suspended"&&await n.resume().catch(()=>{}),{get muted(){return a},setMuted(d){a=d;for(let f of e.getAudioTracks())f.enabled=!d},stop(){l();try{i.disconnect(),o.disconnect()}catch{}for(let d of e.getTracks())d.stop();n.close().catch(()=>{})}}}var dt=class{constructor(){v(this,"handlers",{})}on(t,e){var n;return((n=this.handlers)[t]??(n[t]=new Set)).add(e),()=>this.handlers[t]?.delete(e)}emit(t,e){for(let n of this.handlers[t]??[])try{n(e)}catch(i){console.error("[characterxyz] listener threw",i)}}clear(){this.handlers={}}},U=class extends Error{constructor(t,e,n=0,i={}){super(e),v(this,"code"),v(this,"status"),v(this,"fields"),this.name="CxError",this.code=t,this.status=n,this.fields=i}};function xi(t){switch(t){case 401:return"unauthorized";case 403:return"forbidden";case 404:return"not_found";case 402:return"payment_required";case 422:return"invalid";case 429:return"rate_limited";case 503:return"unavailable";default:return"unknown"}}async function bi(t){let e="",n={};try{let i=await t.json();typeof i?.message=="string"&&(e=i.message);for(let a of Array.isArray(i?.errors)?i.errors:[])typeof a?.path=="string"&&typeof a?.message=="string"&&(n[a.path]=a.message)}catch{}return new U(xi(t.status),e||`Request failed (${t.status})`,t.status,n)}async function we(t,e,n={}){let i={};n.body!==void 0&&(i["Content-Type"]="application/json"),n.token&&(i.Authorization=`Bearer ${n.token}`);let a;try{a=await fetch(t+e,{method:n.method??(n.body===void 0?"GET":"POST"),headers:i,body:n.body===void 0?void 0:JSON.stringify(n.body),signal:n.signal,keepalive:n.keepalive,credentials:"omit",cache:"no-store"})}catch(s){throw s?.name==="AbortError"?s:new U("network","Could not reach Character XYZ. Check your connection.")}if(!a.ok)throw await bi(a);return a}async function G(t,e,n={}){return(await(await we(t,e,n)).json()).data}async function Rt(t,e,n){let i=t.body;if(!i)return;let a=i.getReader(),s=new TextDecoder,o="",l=()=>{a.cancel().catch(()=>{})};n?.addEventListener("abort",l);try{for(;;){let{value:p,done:d}=await a.read();if(d)break;o+=s.decode(p,{stream:!0}),o=Lt(o,e)}o+=s.decode(),Lt(o+`
33
+ `;function mi(t){let e=new Int16Array(t);if(!e.length)return 0;let n=0;for(let i=0;i<e.length;i++){let a=e[i]/32768;n+=a*a}return Math.sqrt(n/e.length)}async function _i(t){if(!navigator.mediaDevices?.getUserMedia)throw new Error("This browser cannot use a microphone here.");let e=await navigator.mediaDevices.getUserMedia({audio:{deviceId:t.deviceId?{exact:t.deviceId}:void 0,channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}),n=new AudioContext({latencyHint:"interactive"}),i=n.createMediaStreamSource(e),a=!1,s=d=>{if(a){t.onFrame(new ArrayBuffer(d.byteLength),0);return}t.onFrame(d,mi(d))},o,l;try{let d=URL.createObjectURL(new Blob([gi],{type:"application/javascript"}));try{await n.audioWorklet.addModule(d)}finally{URL.revokeObjectURL(d)}let f=new AudioWorkletNode(n,"cxyz-mic");f.port.onmessage=_=>s(_.data),o=f,l=()=>{f.port.onmessage=null}}catch{let d=n.createScriptProcessor(4096,1,1),f=n.sampleRate/16e3,_=0,c=new Int16Array(480),g=0;d.onaudioprocess=b=>{let x=b.inputBuffer.getChannelData(0);for(let m=0;m<x.length;m++)if(_+=1,_>=f){_-=f;let k=Math.max(-1,Math.min(1,x[m]));c[g++]=k<0?k*32768:k*32767,g===480&&(s(c.buffer),c=new Int16Array(480),g=0)}},o=d,l=()=>{d.onaudioprocess=null}}i.connect(o);let p=n.createGain();return p.gain.value=0,o.connect(p).connect(n.destination),n.state==="suspended"&&await n.resume().catch(()=>{}),{get muted(){return a},setMuted(d){a=d;for(let f of e.getAudioTracks())f.enabled=!d},stop(){l();try{i.disconnect(),o.disconnect()}catch{}for(let d of e.getTracks())d.stop();n.close().catch(()=>{})}}}var ht=class{constructor(){y(this,"handlers",{})}on(t,e){var n;return((n=this.handlers)[t]??(n[t]=new Set)).add(e),()=>this.handlers[t]?.delete(e)}emit(t,e){for(let n of this.handlers[t]??[])try{n(e)}catch(i){console.error("[characterxyz] listener threw",i)}}clear(){this.handlers={}}},P=class extends Error{constructor(t,e,n=0,i={}){super(e),y(this,"code"),y(this,"status"),y(this,"fields"),this.name="CxError",this.code=t,this.status=n,this.fields=i}};function xi(t){switch(t){case 401:return"unauthorized";case 403:return"forbidden";case 404:return"not_found";case 402:return"payment_required";case 422:return"invalid";case 429:return"rate_limited";case 503:return"unavailable";default:return"unknown"}}async function bi(t){let e="",n={};try{let i=await t.json();typeof i?.message=="string"&&(e=i.message);for(let a of Array.isArray(i?.errors)?i.errors:[])typeof a?.path=="string"&&typeof a?.message=="string"&&(n[a.path]=a.message)}catch{}return new P(xi(t.status),e||`Request failed (${t.status})`,t.status,n)}async function Ce(t,e,n={}){let i={};n.body!==void 0&&(i["Content-Type"]="application/json"),n.token&&(i.Authorization=`Bearer ${n.token}`);let a;try{a=await fetch(t+e,{method:n.method??(n.body===void 0?"GET":"POST"),headers:i,body:n.body===void 0?void 0:JSON.stringify(n.body),signal:n.signal,keepalive:n.keepalive,credentials:"omit",cache:"no-store"})}catch(s){throw s?.name==="AbortError"?s:new P("network","Could not reach Character XYZ. Check your connection.")}if(!a.ok)throw await bi(a);return a}async function X(t,e,n={}){return(await(await Ce(t,e,n)).json()).data}async function Ut(t,e,n){let i=t.body;if(!i)return;let a=i.getReader(),s=new TextDecoder,o="",l=()=>{a.cancel().catch(()=>{})};n?.addEventListener("abort",l);try{for(;;){let{value:p,done:d}=await a.read();if(d)break;o+=s.decode(p,{stream:!0}),o=zt(o,e)}o+=s.decode(),zt(o+`
34
34
 
35
- `,e)}finally{n?.removeEventListener("abort",l)}}function Lt(t,e){let n=t.replace(/\r\n/g,`
35
+ `,e)}finally{n?.removeEventListener("abort",l)}}function zt(t,e){let n=t.replace(/\r\n/g,`
36
36
  `),i;for(;(i=n.indexOf(`
37
37
 
38
38
  `))!==-1;){let a=n.slice(0,i);n=n.slice(i+2);let s="message",o=[];for(let d of a.split(`
39
- `)){if(!d||d.startsWith(":"))continue;let f=d.indexOf(":"),m=f===-1?d:d.slice(0,f),c=f===-1?"":d.slice(f+1).replace(/^ /,"");m==="event"?s=c:m==="data"&&o.push(c)}if(!o.length)continue;let l=o.join(`
40
- `),p=l;try{p=JSON.parse(l)}catch{}e({event:s,data:p})}return n}function vi(t){if(t.byteLength<25)return null;let e=new DataView(t);if(e.getUint8(0)!==67||e.getUint8(1)!==88||e.getUint8(2)!==89||e.getUint8(3)!==90||e.getUint8(4)!==1)return null;let n=e.getUint8(5),i=(e.getUint8(6)&1)!==0,a=7,s=e.getUint16(a,!0);if(a+=2,a+s+20>t.byteLength)return null;let o=new TextDecoder().decode(new Uint8Array(t,a,s));a+=s+4+8+4;let l=e.getUint32(a,!0);return a+=4,a+l>t.byteLength?null:{kind:n,final:i,corr:o,payload:new Uint8Array(t,a,l)}}var yi=.09,ki=350,wi=25e3,Ci=()=>({phase:"idle",callId:null,position:null,etaSeconds:null,holdSeconds:null,maxSeconds:null,startedAt:null,endReason:null,muted:!1,speaking:!1,agentState:"idle",error:null}),Si=class extends dt{constructor(t,e,n,i={}){super(),v(this,"apiUrl",t),v(this,"session",e),v(this,"agentId",n),v(this,"opts",i),v(this,"s",Ci()),v(this,"ticket",null),v(this,"eventsAbort",null),v(this,"ws",null),v(this,"mic",null),v(this,"players",new Map),v(this,"sampleRates",new Map),v(this,"cancelled",new Set),v(this,"speakingCorr",null),v(this,"heartbeat",null),v(this,"loudSince",null)}get state(){return this.s}audible(){let t=this.speakingCorr,e=t?this.players.get(t):void 0;return t&&e?{corr:t,ms:e.playedMs()}:null}voiceLevel(){let t=this.speakingCorr?this.players.get(this.speakingCorr):void 0;return t?t.level():0}set(t){this.s={...this.s,...t},this.emit("state",this.s)}async start(){if(this.s.phase==="idle"){this.set({phase:"joining"}),Dt();try{this.mic=await _i({deviceId:this.opts.deviceId,onFrame:(t,e)=>this.onMicFrame(t,e)})}catch{this.finish("mic-denied","Allow the microphone to talk, or chat instead.");return}try{let t=await this.session.token(),e=await G(this.apiUrl,"/sdk/v1/calls",{method:"POST",body:{},token:t});this.set({callId:e.callId,phase:e.state==="ready"?"joining":"queued",position:e.position??null,etaSeconds:e.etaSeconds??null}),this.follow()}catch(t){let e=t instanceof U?t:new U("unknown","Could not start the call."),n=e.code==="rate_limited"?"busy":"unavailable";this.finish(n,e.message),this.emit("error",e)}}}async follow(){let t=0;for(;this.s.callId&&this.s.phase!=="ended"&&this.s.phase!=="idle";){this.eventsAbort=new AbortController;try{let e=await this.session.token(),n=await we(this.apiUrl,`/sdk/v1/calls/${encodeURIComponent(this.s.callId)}/events`,{token:e,signal:this.eventsAbort.signal});t=0,await Rt(n,i=>this.onServerEvent(i.event,i.data),this.eventsAbort.signal)}catch(e){if(e?.name==="AbortError")return;if(e instanceof U&&e.code==="not_found"){this.finish("failed","The call ended.");return}if(t+=1,t>5){this.finish("failed","Lost the connection to the call.");return}}if(this.ended())return;await new Promise(e=>setTimeout(e,Math.min(4e3,500*2**t)))}}onServerEvent(t,e){switch(t){case"queued":(this.s.phase==="joining"||this.s.phase==="queued")&&this.set({phase:"queued",position:Number(e.position)||1,etaSeconds:Number(e.etaSeconds)||null});break;case"ready":{typeof e.ticket=="string"&&e.ticket&&(this.ticket=e.ticket);let n=Number(e.holdSeconds)||0;this.s.phase!=="ready"&&this.s.phase!=="connecting"&&this.s.phase!=="live"?(this.set({phase:"ready",holdSeconds:n,position:null,etaSeconds:null}),this.emit("ready",{holdSeconds:n}),this.opts.autoAccept!==!1&&this.accept()):this.s.phase==="ready"&&this.set({holdSeconds:n});break}case"live":this.set({phase:"live",maxSeconds:Number(e.maxSeconds)||null,startedAt:this.s.startedAt??Date.now()-(Number(e.elapsedSeconds)||0)*1e3});break;case"ended":this.finish(String(e.reason||"hangup")||"hangup",null);break}}ended(){return this.s.phase==="ended"}accept(){if(this.s.phase!=="ready"||!this.ticket||this.ws)return;this.set({phase:"connecting"});let t=this.apiUrl.replace(/^http/,"ws")+"/sdk/v1/calls/socket",e=new WebSocket(t,[`cxyz-ticket.${this.ticket}`]);this.ticket=null,e.binaryType="arraybuffer",this.ws=e,e.onopen=()=>{let n=this.opts.face,i=n?.emotion?.()??null;e.send(JSON.stringify({type:"agent_identity",agent_id:this.agentId,skin_index:0,blendshapes:!!n,...n?{blendshape_stream:!0}:{},...n&&i?{face_emotion:i}:{}})),e.send(JSON.stringify({type:"mic_state",silero:"off",denoise:!1})),this.heartbeat=setInterval(()=>this.sendJson({type:"heartbeat"}),wi),this.set({phase:"live",startedAt:this.s.startedAt??Date.now()})},e.onmessage=n=>this.onSocket(n.data),e.onclose=()=>{this.ws=null,setTimeout(()=>{(this.s.phase==="live"||this.s.phase==="connecting")&&this.finish("hangup",null)},1500)}}sendJson(t){this.ws?.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify(t))}onMicFrame(t,e){let n=this.ws;if(!(!n||n.readyState!==WebSocket.OPEN)){if(this.speakingCorr){let i=performance.now();if(e>yi){if(this.loudSince??(this.loudSince=i),i-this.loudSince>=ki){this.loudSince=null,this.interrupt(),n.send(t);return}}else this.loudSince=null;n.send(new ArrayBuffer(t.byteLength));return}n.send(t)}}onSocket(t){if(t instanceof ArrayBuffer){let n=vi(t);if(!n||this.cancelled.has(n.corr))return;if(n.kind===3){this.opts.face&&this.emit("face",{corr:n.corr,payload:n.payload.slice()});return}if(n.kind!==1)return;let i=this.players.get(n.corr);if(!i){for(let[s,o]of this.players)o.stop(),this.players.delete(s);let a=n.corr;i=new fi({sampleRate:this.sampleRates.get(a)??16e3,onStart:()=>{this.speakingCorr=a,this.set({speaking:!0}),this.emit("line",{corr:a,event:"audible"}),this.sendJson({type:"playback_started",correlationId:a,timestampMs:Date.now()})},onEnd:()=>{this.players.delete(a),this.speakingCorr===a&&(this.speakingCorr=null),this.set({speaking:!1}),this.emit("line",{corr:a,event:"end"}),this.sendJson({type:"playback_ended",correlationId:a,timestampMs:Date.now(),reason:"natural"}),this.sendJson({type:"speech_ended"})}}),this.players.set(a,i)}i.enqueue(n.payload),n.final&&i.end();return}if(typeof t!="string")return;let e;try{e=JSON.parse(t)}catch{return}if("AgentSpeechMeta"in e){let n=e.AgentSpeechMeta;n?.correlation_id&&n.sample_rate&&this.sampleRates.set(n.correlation_id,n.sample_rate);return}if("InteractorTranscript"in e){let n=e.InteractorTranscript;n?.text&&this.emit("caption",{id:`v:${n.correlation_id}`,role:"visitor",text:n.text});return}if("AgentReplyTranscript"in e){let n=e.AgentReplyTranscript;n?.text&&!this.cancelled.has(n.correlation_id)&&this.emit("caption",{id:`a:${n.correlation_id}`,role:"agent",text:n.text});return}if(e.type==="turn_cancelled"&&typeof e.correlationId=="string"){let n=e.correlationId;this.cancelled.add(n),this.players.get(n)?.stop(),this.players.delete(n),this.emit("line",{corr:n,event:"end"}),this.speakingCorr===n&&(this.speakingCorr=null,this.set({speaking:!1})),this.emit("captionRemoved",`a:${n}`);return}e.kind==="agent_status"&&typeof e.state=="string"&&this.set({agentState:e.state.toLowerCase()})}interrupt(){let t=this.speakingCorr;if(!t)return;let e=this.players.get(t),n=Math.round(e?.playedMs()??0);e?.stop(),this.players.delete(t),this.cancelled.add(t),this.speakingCorr=null,this.set({speaking:!1}),this.emit("line",{corr:t,event:"end"}),this.sendJson({type:"playback_ended",correlationId:t,timestampMs:Date.now(),reason:"interrupted"}),this.sendJson({type:"interrupt",correlationId:t,heardMs:n,timestampMs:Date.now()})}setMuted(t){this.mic?.setMuted(t),this.set({muted:t})}async hangUp(){let t=this.s.callId,e=this.s.phase;if(this.finish(e==="live"?"hangup":"left",null),!!t)try{let n=await this.session.token();await we(this.apiUrl,`/sdk/v1/calls/${encodeURIComponent(t)}`,{method:"DELETE",token:n})}catch{}}finish(t,e){if(this.s.phase==="ended")return;this.eventsAbort?.abort(),this.eventsAbort=null,this.heartbeat&&clearInterval(this.heartbeat),this.heartbeat=null;for(let i of this.players.values())i.stop();this.players.clear(),this.speakingCorr=null,this.mic?.stop(),this.mic=null;let n=this.ws;this.ws=null,n&&n.readyState<=WebSocket.OPEN&&n.close(1e3),this.ticket=null,this.set({phase:"ended",endReason:t,speaking:!1,holdSeconds:null,error:e})}},Ti=0,zt=t=>`${t}_${Date.now().toString(36)}_${(Ti++).toString(36)}`,Ai=class extends dt{constructor(t,e){super(),v(this,"apiUrl",t),v(this,"session",e),v(this,"list",[]),v(this,"loaded",!1),v(this,"busy",!1),v(this,"abort",null)}get messages(){return this.list}get isBusy(){return this.busy}publish(){this.list=[...this.list],this.emit("messages",this.list)}applySiteEvent(t){let e=!1;t.event&&!this.list.some(n=>n.id===t.event.id)&&(this.list.push(t.event),e=!0),t.message&&!this.list.some(n=>n.id===t.message.id)&&(this.list.push({...t.message,...t.suggestions?.length?{suggestions:t.suggestions}:{},...t.askDetails?{askDetails:t.askDetails}:{}}),e=!0),e&&this.publish()}async load(){if(this.loaded)return this.list;let t=await this.session.token(),e=await G(this.apiUrl,"/sdk/v1/chat/messages?limit=50",{token:t}),n=this.list;return this.list=[...e?.messages??[],...n],this.loaded=!0,this.publish(),this.list}async send(t){let e=t.trim();if(!e)throw new U("invalid","Say something first.");if(this.busy)throw new U("rate_limited","Wait for the reply first.");this.setBusy(!0);let n={id:zt("local"),role:"visitor",text:e,createdAt:new Date().toISOString()},i={id:zt("reply"),role:"agent",text:"",createdAt:new Date().toISOString(),streaming:!0};this.list.push(n,i),this.publish(),this.abort=new AbortController;try{let a=await this.session.token(),s=await we(this.apiUrl,"/sdk/v1/chat/messages",{method:"POST",body:{text:e},token:a,signal:this.abort.signal}),o=null,l=null;if(await Rt(s,({event:d,data:f})=>{let m=f;if(d==="delta"&&typeof m?.text=="string")i.text+=m.text,this.publish();else if(d==="done"){let c=Array.isArray(m.suggestions)?m.suggestions.filter(g=>typeof g=="string"&&g.trim()!==""):[];o={id:String(m.id),role:"agent",text:String(m.text??i.text),createdAt:String(m.createdAt??i.createdAt),...c.length?{suggestions:c}:{},...m.askDetails&&typeof m.askDetails=="object"?{askDetails:m.askDetails}:{},...m.detailsForm&&typeof m.detailsForm=="object"?{detailsForm:m.detailsForm}:{}}}else d==="error"&&(l=typeof m?.message=="string"?m.message:"Something went wrong.")},this.abort.signal),l||!o)throw new U("unknown",l??"The reply was cut off. Try again.");let p=o;return this.replace(i.id,p),p}catch(a){let s=a instanceof U?a:new U("network","The reply was cut off. Try again.");this.list=this.list.filter(l=>l.id!==i.id);let o=this.list.findIndex(l=>l.id===n.id);throw o!==-1&&(this.list[o]={...n,failed:!0,...s.status===429?{error:s.message}:{}}),this.publish(),a?.name!=="AbortError"&&this.emit("error",s),s}finally{this.abort=null,this.setBusy(!1)}}async reset(){this.stop();let t=await this.session.token();await we(this.apiUrl,"/sdk/v1/chat/messages",{method:"DELETE",token:t}),this.list=[],this.loaded=!0,this.publish()}retry(t){let e=this.list.find(n=>n.id===t&&n.failed);if(!e)throw new U("not_found","Nothing to retry.");return this.list=this.list.filter(n=>n.id!==t),this.publish(),this.send(e.text)}stop(){this.abort?.abort()}replace(t,e){let n=this.list.findIndex(i=>i.id===t);n!==-1&&(this.list[n]=e),this.publish()}setBusy(t){this.busy=t,this.emit("busy",t)}},Mi=()=>{let t=new Map;return{get:e=>t.get(e)??null,set:(e,n)=>{t.set(e,n)}}},Ei=()=>({get(t){try{return globalThis.localStorage?.getItem(t)??null}catch{return null}},set(t,e){try{globalThis.localStorage?.setItem(t,e)}catch{}}}),Fi=60,Ii=class{constructor(t){if(v(this,"src",t),v(this,"current",null),v(this,"inflight",null),!t.publishableKey&&!t.getSessionToken)throw new U("invalid","Pass a publishableKey, or getSessionToken for sessions your server mints.")}visitorKey(){return`cxyz:visitor:${(this.src.publishableKey??"server").slice(-12)}`}get info(){return this.current}async token(){let t=Date.now()/1e3;return this.current&&this.current.expiresAt-Fi>t?this.current.token:(await this.refresh()).token}refresh(){return this.inflight??(this.inflight=this.mint().finally(()=>{this.inflight=null})),this.inflight}async mint(){let t;if(this.src.getSessionToken){let e=await this.src.getSessionToken();typeof e=="string"?t=await this.describe(e):t=e}else{let e=this.src.store.get(this.visitorKey())??void 0;t=await G(this.src.apiUrl,"/sdk/v1/sessions",{method:"POST",body:{publishableKey:this.src.publishableKey,agentId:this.src.agentId,visitorId:e}}),this.src.store.set(this.visitorKey(),t.visitorId)}return this.current=t,t}async describe(t){return{...await G(this.src.apiUrl,"/sdk/v1/session",{token:t}),token:t}}},Li="https://api.character.xyz",Pt=class Ut extends dt{constructor(e,n,i){super(),v(this,"apiUrl",e),v(this,"session",n),v(this,"info",i),v(this,"chat"),v(this,"currentCall",null),v(this,"destroyed",!1),v(this,"openingP",null),v(this,"actionHandlers",new Map),this.chat=new Ai(e,n)}static async init(e){let n=(e.apiUrl??Li).replace(/\/+$/,"");if(e.publishableKey&&/^cxyz_sk_/.test(e.publishableKey))throw new U("invalid","That is a SECRET key. Never put it in a web page: use a publishable key (cxyz_pk_\u2026). Revoke the secret key now.");let i=e.storage==="memory"?Mi():e.storage&&typeof e.storage=="object"?e.storage:Ei(),a=new Ii({apiUrl:n,agentId:e.agentId,publishableKey:e.publishableKey,getSessionToken:e.getSessionToken,store:i}),s=await a.refresh();return new Ut(n,a,s)}get agent(){return(this.session.info??this.info).agent}get features(){return(this.session.info??this.info).features}get appearance(){return(this.session.info??this.info).appearance??{}}get visitorId(){return(this.session.info??this.info).visitorId}get mode(){return(this.session.info??this.info).mode}get call(){return this.currentCall&&this.currentCall.state.phase!=="ended"?this.currentCall:null}async videoAvatar(){let e=await this.session.token();return G(this.apiUrl,"/sdk/v1/agent/video-avatar",{token:e})}opening(e=!1){return e&&(this.openingP=null),this.openingP??(this.openingP=this.session.token().then(n=>{let i=typeof navigator>"u"?"":navigator.language||"",a=i?`/sdk/v1/agent/opening?locale=${encodeURIComponent(i)}`:"/sdk/v1/agent/opening";return G(this.apiUrl,a,{token:n})}).catch(()=>null)),this.openingP}async sendDetails(e){let n=await this.session.token(),i=typeof location<"u"?location.href:void 0;await G(this.apiUrl,"/sdk/v1/lead",{token:n,body:{...e,consent:!0,...i?{page:i}:{}}})}async declineDetails(){let e=await this.session.token();await G(this.apiUrl,"/sdk/v1/lead/decline",{token:e,method:"POST",body:{}})}async identify(e){let n=await this.session.token();await G(this.apiUrl,"/sdk/v1/context",{token:n,method:"POST",body:{visitor:e}})}async setContext(e){let n=await this.session.token();await G(this.apiUrl,"/sdk/v1/context",{token:n,method:"POST",body:{context:e}})}async track(e,n={},i={}){let a=await this.session.token(),s=i.id??zi(),o=await G(this.apiUrl,"/sdk/v1/track",{token:a,method:"POST",body:{name:e,data:n,id:s},keepalive:!0});this.emit("siteEvent",o),!o.accepted&&o.ignored&&o.ignored!=="duplicate"&&console.warn(`[characterxyz] event "${e}" ignored: ${o.ignored}`);for(let p of o.actions??[])this.runAction(p);let l=0;for(;o.action&&l++<4;){let p=o.action,d=await this.runAction(p);o=await G(this.apiUrl,`/sdk/v1/actions/${encodeURIComponent(p.id)}`,{token:a,method:"POST",body:d}),this.emit("siteEvent",o)}return this.chat.applySiteEvent(o),o}registerAction(e,n){return this.actionHandlers.set(e,n),()=>{this.actionHandlers.get(e)===n&&this.actionHandlers.delete(e)}}async runAction(e){let n=this.actionHandlers.get(e.name);if(!n)return{ok:!1,error:`no handler registered for "${e.name}"`};try{return{ok:!0,result:await n(e.inputs??{},e.name)??null}}catch(i){return{ok:!1,error:String(i?.message??i)}}}async startCall(e={}){if(this.destroyed)throw new U("invalid","This client was destroyed.");if(!this.features.call)throw new U("forbidden","Calls are not available on this site.");if(this.call)return this.call;let n=new Si(this.apiUrl,this.session,this.agent.id,e);return this.currentCall=n,n.on("state",i=>{i.phase==="ended"&&this.currentCall===n&&this.emit("call",null)}),n.on("error",i=>this.emit("error",i)),this.emit("call",n),await n.start(),n}destroy(){this.destroyed=!0,this.currentCall?.hangUp(),this.chat.stop(),this.chat.clear(),this.actionHandlers.clear(),this.clear()}};function zi(){let t=typeof crypto<"u"?crypto:void 0;return t&&typeof t.randomUUID=="function"?`evt_${t.randomUUID()}`:`evt_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`}var We,M,Wt,Di,oe,Ot,Bt,Yt,pt,Pe,Ce,jt,ft,ut,ht,Ri,$e={},Ne=[],Pi=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Be=Array.isArray;function ie(t,e){for(var n in e)t[n]=e[n];return t}function gt(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function Ui(t,e,n){var i,a,s,o={};for(s in e)s=="key"?i=e[s]:s=="ref"?a=e[s]:o[s]=e[s];if(arguments.length>2&&(o.children=arguments.length>3?We.call(arguments,2):n),typeof t=="function"&&t.defaultProps!=null)for(s in t.defaultProps)o[s]===void 0&&(o[s]=t.defaultProps[s]);return Ue(t,o,i,a,null)}function Ue(t,e,n,i,a){var s={type:t,props:e,key:n,ref:i,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:a??++Wt,__i:-1,__u:0};return a==null&&M.vnode!=null&&M.vnode(s),s}function F(t){return t.children}function Oe(t,e){this.props=t,this.context=e}function de(t,e){if(e==null)return t.__?de(t.__,t.__i+1):null;for(var n;e<t.__k.length;e++)if((n=t.__k[e])!=null&&n.__e!=null)return n.__e;return typeof t.type=="function"?de(t):null}function Oi(t){if(t.__P&&t.__d){var e=t.__v,n=e.__e,i=[],a=[],s=ie({},e);s.__v=e.__v+1,M.vnode&&M.vnode(s),mt(t.__P,s,e,t.__n,t.__P.namespaceURI,32&e.__u?[n]:null,i,n??de(e),!!(32&e.__u),a),s.__v=e.__v,s.__.__k[s.__i]=s,Zt(i,s,a),e.__e=e.__=null,s.__e!=n&&qt(s)}}function qt(t){if((t=t.__)!=null&&t.__c!=null)return t.__e=t.__c.base=null,t.__k.some(function(e){if(e!=null&&e.__e!=null)return t.__e=t.__c.base=e.__e}),qt(t)}function $t(t){(!t.__d&&(t.__d=!0)&&oe.push(t)&&!He.__r++||Ot!=M.debounceRendering)&&((Ot=M.debounceRendering)||Bt)(He)}function He(){try{for(var t,e=1;oe.length;)oe.length>e&&oe.sort(Yt),t=oe.shift(),e=oe.length,Oi(t)}finally{oe.length=He.__r=0}}function Vt(t,e,n,i,a,s,o,l,p,d,f){var m,c,g,x,b,_,k=i&&i.__k||Ne,w=e.length;for(p=$i(n,e,k,p,w),m=0;m<w;m++)(g=n.__k[m])!=null&&(c=g.__i!=-1&&k[g.__i]||$e,g.__i=m,_=mt(t,g,c,a,s,o,l,p,d,f),x=g.__e,g.ref&&c.ref!=g.ref&&(c.ref&&_t(c.ref,null,g),f.push(g.ref,g.__c||x,g)),b==null&&x!=null&&(b=x),4&g.__u?(p=Kt(g,p,t),c.__e&&(c.__e=null)):typeof g.type=="function"&&_!==void 0?p=_:x&&(p=x.nextSibling),g.__u&=-7);return n.__e=b,p}function $i(t,e,n,i,a){var s,o,l,p,d,f=n.length,m=f,c=0;for(t.__k=new Array(a),s=0;s<a;s++)(o=e[s])!=null&&typeof o!="boolean"&&typeof o!="function"?(typeof o=="string"||typeof o=="number"||typeof o=="bigint"||o.constructor==String?o=t.__k[s]=Ue(null,o,null,null,null):Be(o)?o=t.__k[s]=Ue(F,{children:o},null,null,null):o.constructor===void 0&&o.__b>0?o=t.__k[s]=Ue(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):t.__k[s]=o,p=s+c,o.__=t,o.__b=t.__b+1,l=null,(d=o.__i=Ni(o,n,p,m))!=-1&&(m--,(l=n[d])&&(l.__u|=2)),l==null||l.__v==null?(d==-1&&(a>f?c--:a<f&&c++),typeof o.type!="function"&&(o.__u|=4)):d!=p&&(d==p-1?c--:d==p+1?c++:(d>p?c--:c++,o.__u|=4))):t.__k[s]=null;if(m)for(s=0;s<f;s++)(l=n[s])!=null&&(2&l.__u)==0&&(l.__e==i&&(i=de(l)),Gt(l,l));return i}function Kt(t,e,n){var i,a;if(typeof t.type=="function"){for(i=t.__k,a=0;i&&a<i.length;a++)i[a]&&(i[a].__=t,e=Kt(i[a],e,n));return e}t.__e!=e&&(e&&t.type&&!e.parentNode&&(e=de(t)),e=n.insertBefore(t.__e,e||null));do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function Ni(t,e,n,i){var a,s,o,l=t.key,p=t.type,d=e[n],f=d!=null&&(2&d.__u)==0;if(d===null&&l==null||f&&l==d.key&&p==d.type)return n;if(i>(f?1:0)){for(a=n-1,s=n+1;a>=0||s<e.length;)if((d=e[o=a>=0?a--:s++])!=null&&(2&d.__u)==0&&l==d.key&&p==d.type)return o}return-1}function Nt(t,e,n){e[0]=="-"?t.setProperty(e,n??""):t[e]=n==null?"":typeof n!="number"||Pi.test(e)?n:n+"px"}function Re(t,e,n,i,a){var s,o;e:if(e=="style")if(typeof n=="string")t.style.cssText=n;else{if(typeof i=="string"&&(t.style.cssText=i=""),i)for(e in i)n&&e in n||Nt(t.style,e,"");if(n)for(e in n)i&&n[e]==i[e]||Nt(t.style,e,n[e])}else if(e[0]=="o"&&e[1]=="n")s=e!=(e=e.replace(jt,"$1")),o=e.toLowerCase(),e=o in t||e=="onFocusOut"||e=="onFocusIn"?o.slice(2):e.slice(2),t.l||(t.l={}),t.l[e+s]=n,n?i?n[Ce]=i[Ce]:(n[Ce]=ft,t.addEventListener(e,s?ht:ut,s)):t.removeEventListener(e,s?ht:ut,s);else{if(a=="http://www.w3.org/2000/svg")e=e.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(e!="width"&&e!="height"&&e!="href"&&e!="list"&&e!="form"&&e!="tabIndex"&&e!="download"&&e!="rowSpan"&&e!="colSpan"&&e!="role"&&e!="popover"&&e in t)try{t[e]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&e[4]!="-"?t.removeAttribute(e):t.setAttribute(e,e=="popover"&&n==1?"":n))}}function Ht(t){return function(e){if(this.l){var n=this.l[e.type+t];if(e[Pe]==null)e[Pe]=ft++;else if(e[Pe]<n[Ce])return;return n(M.event?M.event(e):e)}}}function mt(t,e,n,i,a,s,o,l,p,d){var f,m,c,g,x,b,_,k,w,$,R,N,j,B,O,X,y=e.type;if(e.constructor!==void 0)return null;128&n.__u&&(p=!!(32&n.__u),s=[l=e.__e=n.__e]),(f=M.__b)&&f(e);e:if(typeof y=="function"){m=o.length;try{if(w=e.props,$=y.prototype&&y.prototype.render,R=(f=y.contextType)&&i[f.__c],N=f?R?R.props.value:f.__:i,n.__c?k=(c=e.__c=n.__c).__=c.__E:($?e.__c=c=new y(w,N):(e.__c=c=new Oe(w,N),c.constructor=y,c.render=Wi),R&&R.sub(c),c.state||(c.state={}),c.__n=i,g=c.__d=!0,c.__h=[],c._sb=[]),$&&c.__s==null&&(c.__s=c.state),$&&y.getDerivedStateFromProps!=null&&(c.__s==c.state&&(c.__s=ie({},c.__s)),ie(c.__s,y.getDerivedStateFromProps(w,c.__s))),x=c.props,b=c.state,c.__v=e,g)$&&y.getDerivedStateFromProps==null&&c.componentWillMount!=null&&c.componentWillMount(),$&&c.componentDidMount!=null&&c.__h.push(c.componentDidMount);else{if($&&y.getDerivedStateFromProps==null&&w!==x&&c.componentWillReceiveProps!=null&&c.componentWillReceiveProps(w,N),e.__v==n.__v||!c.__e&&c.shouldComponentUpdate!=null&&c.shouldComponentUpdate(w,c.__s,N)===!1){e.__v!=n.__v&&(c.props=w,c.state=c.__s,c.__d=!1),e.__e=n.__e,e.__k=n.__k,e.__k.some(function(H){H&&(H.__=e)}),Ne.push.apply(c.__h,c._sb),c._sb=[],c.__h.length&&o.push(c),l=de(n);break e}c.componentWillUpdate!=null&&c.componentWillUpdate(w,c.__s,N),$&&c.componentDidUpdate!=null&&c.__h.push(function(){c.componentDidUpdate(x,b,_)})}if(c.context=N,c.props=w,c.__P=t,c.__e=!1,j=M.__r,B=0,$)c.state=c.__s,c.__d=!1,j&&j(e),f=c.render(c.props,c.state,c.context),Ne.push.apply(c.__h,c._sb),c._sb=[];else do c.__d=!1,j&&j(e),f=c.render(c.props,c.state,c.context),c.state=c.__s;while(c.__d&&++B<25);c.state=c.__s,c.getChildContext!=null&&(i=ie(ie({},i),c.getChildContext())),$&&!g&&c.getSnapshotBeforeUpdate!=null&&(_=c.getSnapshotBeforeUpdate(x,b)),O=f!=null&&f.type===F&&f.key==null?Jt(f.props.children):f,l=Vt(t,Be(O)?O:[O],e,n,i,a,s,o,l,p,d),c.base=e.__e,e.__u&=-161,c.__h.length&&o.push(c),k&&(c.__E=c.__=null)}catch(H){if(o.length=m,e.__v=null,p||s!=null){if(H.then){for(e.__u|=p?160:128;l&&l.nodeType==8&&l.nextSibling;)l=l.nextSibling;s!=null&&(s[s.indexOf(l)]=null),e.__e=l}else if(s!=null)for(X=s.length;X--;)gt(s[X])}else e.__e=n.__e;e.__k==null&&(e.__k=n.__k||[]),H.then||Xt(e),M.__e(H,e,n)}}else s==null&&e.__v==n.__v?(e.__k=n.__k,e.__e=n.__e):l=e.__e=Hi(n.__e,e,n,i,a,s,o,p,d);return(f=M.diffed)&&f(e),128&e.__u?void 0:l}function Xt(t){t&&(t.__c&&(t.__c.__e=!0),t.__k&&t.__k.some(Xt))}function Zt(t,e,n){for(var i=0;i<n.length;i++)_t(n[i],n[++i],n[++i]);M.__c&&M.__c(e,t),t.some(function(a){try{t=a.__h,a.__h=[],t.some(function(s){s.call(a)})}catch(s){M.__e(s,a.__v)}})}function Jt(t){return typeof t!="object"||t==null||t.__b>0?t:Be(t)?t.map(Jt):t.constructor!==void 0?null:ie({},t)}function Hi(t,e,n,i,a,s,o,l,p){var d,f,m,c,g,x,b,_=n.props||$e,k=e.props,w=e.type;if(w=="svg"?a="http://www.w3.org/2000/svg":w=="math"?a="http://www.w3.org/1998/Math/MathML":a||(a="http://www.w3.org/1999/xhtml"),s!=null){for(d=0;d<s.length;d++)if((g=s[d])&&"setAttribute"in g==!!w&&(w?g.localName==w:g.nodeType==3)){t=g,s[d]=null;break}}if(t==null){if(w==null)return document.createTextNode(k);t=document.createElementNS(a,w,k.is&&k),l&&(M.__m&&M.__m(e,s),l=!1),s=null}if(w==null)_===k||l&&t.data==k||(t.data=k);else{if(s=w=="textarea"&&k.defaultValue!=null?null:s&&We.call(t.childNodes),!l&&s!=null)for(_={},d=0;d<t.attributes.length;d++)_[(g=t.attributes[d]).name]=g.value;for(d in _)g=_[d],d=="dangerouslySetInnerHTML"?m=g:d=="children"||d in k||d=="value"&&"defaultValue"in k||d=="checked"&&"defaultChecked"in k||Re(t,d,null,g,a);for(d in k)g=k[d],d=="children"?c=g:d=="dangerouslySetInnerHTML"?f=g:d=="value"?x=g:d=="checked"?b=g:l&&typeof g!="function"||_[d]===g||Re(t,d,g,_[d],a);if(f)l||m&&(f.__html==m.__html||f.__html==t.innerHTML)||(t.innerHTML=f.__html),e.__k=[];else if(m&&(t.innerHTML=""),Vt(e.type=="template"?t.content:t,Be(c)?c:[c],e,n,i,w=="foreignObject"?"http://www.w3.org/1999/xhtml":a,s,o,s?s[0]:n.__k&&de(n,0),l,p),s!=null)for(d=s.length;d--;)gt(s[d]);l&&w!="textarea"||(d="value",w=="progress"&&x==null?t.removeAttribute("value"):x!=null&&(x!==t[d]||w=="progress"&&!x||w=="option"&&x!=_[d])&&Re(t,d,x,_[d],a),d="checked",b!=null&&b!=t[d]&&Re(t,d,b,_[d],a))}return t}function _t(t,e,n){try{if(typeof t=="function"){var i=typeof t.__u=="function";i&&t.__u(),i&&e==null||(t.__u=t(e))}else t.current=e}catch(a){M.__e(a,n)}}function Gt(t,e,n){var i,a;if(M.unmount&&M.unmount(t),(i=t.ref)&&(i.current&&i.current!=t.__e||_t(i,null,e)),(i=t.__c)!=null){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(s){M.__e(s,e)}i.base=i.__P=i.__n=null}if(i=t.__k)for(a=0;a<i.length;a++)i[a]&&Gt(i[a],e,n||typeof t.type!="function");n||gt(t.__e),t.__c=t.__=t.__e=void 0}function Wi(t,e,n){return this.constructor(t,n)}function xt(t,e,n){var i,a,s,o;e==document&&(e=document.documentElement),M.__&&M.__(t,e),a=(i=typeof n=="function")?null:n&&n.__k||e.__k,s=[],o=[],mt(e,t=(!i&&n||e).__k=Ui(F,null,[t]),a||$e,$e,e.namespaceURI,!i&&n?[n]:a?null:e.firstChild?We.call(e.childNodes):null,s,!i&&n?n:a?a.__e:e.firstChild,i,o),Zt(s,t,o),t.props.children=null}We=Ne.slice,M={__e:function(t,e,n,i){for(var a,s,o;e=e.__;)if((a=e.__c)&&!a.__)try{if((s=a.constructor)&&s.getDerivedStateFromError!=null&&(a.setState(s.getDerivedStateFromError(t)),o=a.__d),a.componentDidCatch!=null&&(a.componentDidCatch(t,i||{}),o=a.__d),o)return a.__E=a}catch(l){t=l}throw t}},Wt=0,Di=function(t){return t!=null&&t.constructor===void 0},Oe.prototype.setState=function(t,e){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=ie({},this.state),typeof t=="function"&&(t=t(ie({},n),this.props)),t&&ie(n,t),t!=null&&this.__v&&(e&&this._sb.push(e),$t(this))},Oe.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),$t(this))},Oe.prototype.render=F,oe=[],Bt=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Yt=function(t,e){return t.__v.__b-e.__v.__b},He.__r=0,pt=Math.random().toString(8),Pe="__d"+pt,Ce="__a"+pt,jt=/(PointerCapture)$|Capture$/i,ft=0,ut=Ht(!1),ht=Ht(!0),Ri=0;var ge,D,bt,Qt,Se=0,ln=[],P=M,en=P.__b,tn=P.__r,nn=P.diffed,an=P.__c,rn=P.unmount,sn=P.__;function je(t,e){P.__h&&P.__h(D,t,Se||e),Se=0;var n=D.__H||(D.__H={__:[],__h:[]});return t>=n.__.length&&n.__.push({}),n.__[t]}function C(t){return Se=1,Bi(pn,t)}function Bi(t,e,n){var i=je(ge++,2);if(i.t=t,!i.__c&&(i.__=[n?n(e):pn(void 0,e),function(l){var p=i.__N?i.__N[0]:i.__[0],d=i.t(p,l);p!==d&&(i.__N=[d,i.__[1]],i.__c.setState({}))}],i.__c=D,!D.__f)){var a=function(l,p,d){if(!i.__c.__H)return!0;var f=!1,m=i.__c.props!==l;if(i.__c.__H.__.some(function(g){if(g.__N){f=!0;var x=g.__[0];g.__=g.__N,g.__N=void 0,x!==g.__[0]&&(m=!0)}}),s){var c=s.call(this,l,p,d);return f?c||m:c}return!f||m};D.__f=!0;var s=D.shouldComponentUpdate,o=D.componentWillUpdate;D.componentWillUpdate=function(l,p,d){if(this.__e){var f=s;s=void 0,a(l,p,d),s=f}o&&o.call(this,l,p,d)},D.shouldComponentUpdate=a}return i.__N||i.__}function I(t,e){var n=je(ge++,3);!P.__s&&yt(n.__H,e)&&(n.__=t,n.u=e,D.__H.__h.push(n))}function cn(t,e){var n=je(ge++,4);!P.__s&&yt(n.__H,e)&&(n.__=t,n.u=e,D.__h.push(n))}function K(t){return Se=5,dn(function(){return{current:t}},[])}function dn(t,e){var n=je(ge++,7);return yt(n.__H,e)&&(n.__=t(),n.__H=e,n.__h=t),n.__}function Te(t,e){return Se=8,dn(function(){return t},e)}function Yi(){for(var t;t=ln.shift();){var e=t.__H;if(t.__P&&e)try{e.__h.some(Ye),e.__h.some(vt),e.__h=[]}catch(n){e.__h=[],P.__e(n,t.__v)}}}P.__b=function(t){D=null,en&&en(t)},P.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),sn&&sn(t,e)},P.__r=function(t){tn&&tn(t),ge=0;var e=(D=t.__c).__H;e&&(bt===D?(e.__h=[],D.__h=[],e.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(e.__h.some(Ye),e.__h.some(vt),e.__h=[],ge=0)),bt=D},P.diffed=function(t){nn&&nn(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(ln.push(e)!==1&&Qt===P.requestAnimationFrame||((Qt=P.requestAnimationFrame)||ji)(Yi)),e.__H.__.some(function(n){n.u&&(n.__H=n.u,n.u=void 0)})),bt=D=null},P.__c=function(t,e){e.some(function(n){try{n.__h.some(Ye),n.__h=n.__h.filter(function(i){return!i.__||vt(i)})}catch(i){e.some(function(a){a.__h&&(a.__h=[])}),e=[],P.__e(i,n.__v)}}),an&&an(t,e)},P.unmount=function(t){rn&&rn(t);var e,n=t.__c;n&&n.__H&&(n.__H.__.some(function(i){try{Ye(i)}catch(a){e=a}}),n.__H=void 0,e&&P.__e(e,n.__v))};var on=typeof requestAnimationFrame=="function";function ji(t){var e,n=function(){clearTimeout(i),on&&cancelAnimationFrame(e),setTimeout(t)},i=setTimeout(n,35);on&&(e=requestAnimationFrame(n))}function Ye(t){var e=D,n=t.__c;typeof n=="function"&&(t.__c=void 0,n()),D=e}function vt(t){var e=D;t.__c=t.__(),D=e}function yt(t,e){return!t||t.length!==e.length||e.some(function(n,i){return n!==t[i]})}function pn(t,e){return typeof e=="function"?e(t):e}function hn(t){let e=t%100;if(e>=11&&e<=13)return`${t}th`;switch(t%10){case 1:return`${t}st`;case 2:return`${t}nd`;case 3:return`${t}rd`;default:return`${t}th`}}function qe(t){let e=Math.max(0,Math.floor(t)),n=Math.floor(e/3600),i=Math.floor(e%3600/60),a=String(e%60).padStart(2,"0");return n?`${n}:${String(i).padStart(2,"0")}:${a}`:`${i}:${a}`}function un(t){let e=[],n=/(\*\*[^*]+\*\*|`[^`]+`|\[[^\]]+\]\((https?:\/\/[^)\s]+)\)|https?:\/\/[^\s<>()]+[^\s<>().,;:!?'"]|\*[^*\s][^*]*\*)/g,i=0,a;for(;a=n.exec(t);){a.index>i&&e.push({t:"text",v:t.slice(i,a.index)});let s=a[0];s.startsWith("**")?e.push({t:"b",v:s.slice(2,-2)}):s.startsWith("`")?e.push({t:"code",v:s.slice(1,-1)}):s.startsWith("[")?e.push({t:"link",v:s.slice(1,s.indexOf("]")),href:a[2]}):s.startsWith("http")?e.push({t:"link",v:s,href:s}):e.push({t:"i",v:s.slice(1,-1)}),i=a.index+s.length}return i<t.length&&e.push({t:"text",v:t.slice(i)}),e}function fn(t){let e=[];for(let n of t.split(/\n{2,}/)){let i=n.split(`
41
- `);i.length&&i.every(a=>/^\s*[-*•]\s+/.test(a))?e.push({t:"ul",items:i.map(a=>un(a.replace(/^\s*[-*•]\s+/,"")))}):e.push({t:"p",parts:un(n)})}return e}var qi={assistant:"Assistant",online:"Online",typing:"Typing\u2026",typingName:"{name} is typing",message:"Message",send:"Send",sending:"Sending\u2026",close:"Close",minimise:"Minimise",dismiss:"Dismiss",notNow:"Not now",newConversation:"Start a new conversation",chat:"Chat",chatWith:"Chat with {name}",call:"Call",callName:"Call {name}",callWith:"Call with {name}",startCall:"Start call",callAgain:"Call again",joinCall:"Join call",join:"Join",view:"View",onCall:"On call",backToCall:"Back to your call",backToCallWith:"Back to your call with {name}",callTime:"Call time",timeLeft:"{time} left",endCall:"End call",end:"End",mute:"Mute",unmute:"Unmute",muted:"You are muted",interrupt:"Interrupt",interruptName:"Interrupt {name}",connecting:"Connecting\u2026",joining:"Joining\u2026",speaking:"Speaking",thinking:"Thinking\u2026",listening:"Listening",you:"You: {text}",inLine:"{position} in line",lineLabel:"in line",inLineFor:"You're {position} in line for a call \xB7 {eta}",inLineToCall:"You are {position} in line to call {name}. Open",inLineOpen:"You are {position} in line. Open your call",inLineEta:"You are {position} in line, {eta}",onOtherCalls:"{name} is on other calls",yourTurn:"Your turn in {eta}. We'll chime when it's time.",yourTurnChat:"Your turn in {eta}. We'll chime when it's time, so feel free to keep chatting.",keepChatting:"Keep chatting",leaveLine:"Leave line",readyForYou:"{name} is ready for you",secondsToJoin:"{seconds}s to join",joinWithin:"Join within {seconds} seconds.",talkWith:"Talk with {name} in real time.",etaSoon:"less than a minute",etaMin:"about {n} min",etaHr:"about {n} hr",notSent:"Not sent \xB7 Retry",beforeYouCall:"Before you call {name}",leaveDetails:"Leave your details",confirmDetails:"Confirm your details",detailsWhy:"So the team can follow up, even if the line drops.",detailsTyped:"From what you typed. Check them and send.",reasonField:"Reason",reasonChoose:"Choose a reason",reasonOther:"Something else",reasonPlaceholder:"Tell us in a few words",reasonInferred:"I'll tell the team this is about",reasonFromConversation:"From your conversation",reasonFromPage:"From this page",change:"Change",skipAndCall:"Skip and call",optional:"optional",privacyPolicy:"Privacy policy",thanks:"Thanks. The team will be in touch.",thanksName:"Thanks, {name}. The team will be in touch.",sendFailed:"Could not send. Try again.",nameField:"Name",emailField:"Email",phoneField:"Phone",companyField:"Company",poweredBy:"Powered by {brand}",greetingDefault:"Hi, I'm {name}. How can I help you today?",endedTitle:"Call ended",endedBody:"Thanks for talking with {name}.",leftTitle:"You left the line",leftBody:"You can call again whenever you like.",missedTitle:"You missed your turn",missedBody:"{name} was ready, but the call wasn't joined in time.",stillBusyTitle:"Still busy",stillBusyBody:"Sorry for the wait. {name} is still on other calls. Chat is open meanwhile.",limitTitle:"Time is up",limitBody:"This call reached its time limit.",busyTitle:"All lines are busy",busyBody:"Try again in a few minutes, or keep chatting.",micTitle:"Microphone needed",micBody:"Allow the microphone in your browser to talk, or keep chatting.",silenceBody:"The line was quiet for a minute, so {name} hung up. Call again any time.",restingTitle:"Calls are resting",restingBody:"Calls are done for today. Chat is open.",unavailableTitle:"Calls are unavailable",unavailableBody:"Calls are not available right now. Chat is open.",droppedTitle:"The call dropped",droppedBody:"Something interrupted the call. Try again."},gn={},mn=!0;function _n(t){gn=t??{},mn=!t||!Object.keys(t).length}function h(t,e){let n=gn[t]??qi[t];if(e)for(let i in e)n=n.split(`{${i}}`).join(String(e[i]));return n}function le(t){return mn?hn(t):String(t)}function Ve(t){if(t==null)return"";if(t<60)return h("etaSoon");let e=Math.round(t/60);return e<60?h("etaMin",{n:e}):h("etaHr",{n:Math.round(e/60)})}function xn(t,e){let n=(i,a)=>({title:h(i),body:h(a,{name:e})});switch(t){case"hangup":return n("endedTitle","endedBody");case"left":return n("leftTitle","leftBody");case"missed":return n("missedTitle","missedBody");case"timeout":return n("stillBusyTitle","stillBusyBody");case"limit":return n("limitTitle","limitBody");case"busy":return n("busyTitle","busyBody");case"mic-denied":return n("micTitle","micBody");case"silence":return n("endedTitle","silenceBody");case"daily_limit":return n("restingTitle","restingBody");case"credits":case"unavailable":return n("unavailableTitle","unavailableBody");default:return n("droppedTitle","droppedBody")}}var bn={cx:.5,cy:.12,span:.06};function yn(t,e,n){let i=t?.face?.eyes,a=t?.face?.chin;if(!i||!a||!e||!n)return bn;let s=(i.left.x+i.right.x)/2,o=(i.left.y+i.right.y)/2,l=(a.y-o)/n;return l>.005&&l<.5?{cx:s/e,cy:(o+a.y)/2/n,span:l}:bn}var Ke={faceFraction:.26,at:{x:.5,y:.5}},kn={faceFraction:.14,at:{x:.5,y:.34},keepCrown:!0},wn={faceFraction:.16,at:{x:.5,y:.22},keepCrown:!0},Cn={fit:"height"},Vi=1.8,vn=.04;function Sn(t,e,n,i,a){if("fit"in a){let d=i*e;return{width:d,height:i,left:n/2-t.cx*d,top:0}}let s=i*a.faceFraction/t.span,o=s*e,l=i*a.at.y-t.cy*s,p=l+(t.cy-t.span*Vi)*s;return a.keepCrown&&p<i*vn&&(l+=i*vn-p),{width:o,height:s,left:n*a.at.x-t.cx*o,top:l}}var Tn=/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/,Ki=/\+?\d[\d\s().-]{5,}\d/g,Xi=/\b(?:my name is|i am|i'm|im|this is|name\s*[:-])\s+([A-Za-z][A-Za-z'’-]+(?:\s+[A-Za-z][A-Za-z'’-]+)?)/i,Zi=new Set(["interested","looking","from","with","here","trying","not","a","an","the","just","also","happy","keen","curious","calling","sure","fine","good","okay","ok"]);function An(t){let e={},n=t.match(Tn)?.[0];n&&(e.email=n.replace(/[.,;:]+$/,""));for(let a of t.replace(Tn," ").matchAll(Ki)){let s=a[0].replace(/\D/g,"");if(s.length>=7&&s.length<=15){e.phone=a[0].trim();break}}if(!e.email&&!e.phone)return null;let i=t.match(Xi)?.[1];if(i){let a=i.split(/\s+/).filter(o=>!Zi.has(o.toLowerCase())),s=[];for(let o of a){if(["and","here","at","from"].includes(o.toLowerCase()))break;s.push(o)}s.length&&s[0].length>1&&(e.name=s.map(o=>o[0].toUpperCase()+o.slice(1)).join(" "))}return e}var Ji=0;function r(t,e,n,i,a,s){e||(e={});var o,l,p=e;if("ref"in p)for(l in p={},e)l=="ref"?o=e[l]:p[l]=e[l];var d={type:t,props:p,key:n,ref:o,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--Ji,__i:-1,__u:0,__source:a,__self:s};if(typeof t=="function"&&(o=t.defaultProps))for(l in o)p[l]===void 0&&(p[l]=o[l]);return M.vnode&&M.vnode(d),d}var ee=(t,e)=>r("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"1.9","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",focusable:"false",children:e}),Ae=({size:t=20})=>ee(t,r("path",{d:"M4 5.5A2.5 2.5 0 0 1 6.5 3h11A2.5 2.5 0 0 1 20 5.5v8a2.5 2.5 0 0 1-2.5 2.5H10l-4.2 3.6a.5.5 0 0 1-.8-.4V16h0A2.5 2.5 0 0 1 4 13.5z"})),me=({size:t=20})=>ee(t,r("path",{d:"M5.2 3.5h3l1.6 4.2-2 1.4a12 12 0 0 0 7.1 7.1l1.4-2 4.2 1.6v3a1.7 1.7 0 0 1-1.8 1.7A16.6 16.6 0 0 1 3.5 5.3 1.7 1.7 0 0 1 5.2 3.5z"})),Mn=({size:t=22})=>ee(t,r("path",{d:"M3 13.6c5-4.4 13-4.4 18 0l-1.7 2.6-3.6-1.3v-2.6a11 11 0 0 0-7.4 0v2.6l-3.6 1.3z"})),En=({size:t=20})=>ee(t,r(F,{children:[r("rect",{x:"9",y:"3",width:"6",height:"11",rx:"3"}),r("path",{d:"M5.5 11a6.5 6.5 0 0 0 13 0M12 17.5V21"})]})),Fn=({size:t=20})=>ee(t,r(F,{children:[r("path",{d:"M9 9v2a3 3 0 0 0 5.1 2.1M15 9.4V6a3 3 0 0 0-5.7-1.3"}),r("path",{d:"M5.5 11a6.5 6.5 0 0 0 10.6 5M18.4 12.5a6.5 6.5 0 0 0 .1-1.5M12 17.5V21M3 3l18 18"})]})),Xe=({size:t=18})=>ee(t,r("path",{d:"M6 6l12 12M18 6L6 18"})),In=({size:t=18})=>ee(t,r("path",{d:"M12 19V5M5.5 11.5L12 5l6.5 6.5"})),Ln=({size:t=18})=>ee(t,r("path",{d:"M15 5l-7 7 7 7"}));var zn=({size:t=18})=>ee(t,r("path",{d:"M12 4H6.5A2.5 2.5 0 0 0 4 6.5v11A2.5 2.5 0 0 0 6.5 20h11a2.5 2.5 0 0 0 2.5-2.5V12M17.5 3.5a2.1 2.1 0 0 1 3 3L13 14l-4 1 1-4z"})),Dn=({size:t=14})=>ee(t,r("path",{d:"M5 12.5l4.2 4.2L19 7"})),Rn=({size:t=14})=>ee(t,r("path",{d:"M4 12a8 8 0 1 0 2.3-5.6M4 4v4h4"}));var kt={current:null};function Gi(t){return t?t.speaking?"speaking":t.agentState==="thinking"?"reasoning":t.agentState==="listening"||t.phase==="live"?"listening":"idle":"idle"}function Pn({client:t,call:e,state:n,src:i,onStatus:a}){let s=K(null),[o,l]=C(!1),p=K(!1),d=(()=>{try{return new URL(i).origin}catch{return null}})(),f=(c,g)=>{let x=s.current?.contentWindow;x&&d&&x.postMessage({cx:"face",...c},d,g??[])};I(()=>{if(!d){a("unavailable");return}let c=!1,g=b=>{if(b.source!==s.current?.contentWindow||b.origin!==d)return;let _=b.data;_?.cx==="face"&&(_.type==="loaded"?(p.current=!0,l(!0),t.videoAvatar().then(k=>{c||(k?f({type:"init",avatar:k}):a("unavailable"))}).catch(()=>!c&&a("unavailable"))):_.type==="ready"?(kt.current=typeof _.faceEmotion=="string"?_.faceEmotion:null,a("ready")):_.type==="unavailable"&&a("unavailable"))};window.addEventListener("message",g);let x=setTimeout(()=>!c&&!p.current&&a("unavailable"),15e3);return()=>{c=!0,clearTimeout(x),window.removeEventListener("message",g)}},[t,d]);let m=Gi(n);return I(()=>{o&&f({type:"state",state:m})},[m,o]),I(()=>{if(!e||!o)return;let c=[e.on("face",({corr:b,payload:_})=>f({type:"batch",corr:b,payload:_},[_.buffer])),e.on("line",({corr:b,event:_})=>{f(_==="audible"?{type:"audible",corr:b,ms:e.audible()?.ms??0}:{type:"end",corr:b})})],g=0,x=()=>{let b=e.audible();b&&f({type:"clock",corr:b.corr,ms:b.ms}),g=requestAnimationFrame(x)};return g=requestAnimationFrame(x),()=>{c.forEach(b=>b()),cancelAnimationFrame(g)}},[e,o]),d?r("iframe",{ref:s,class:"face-frame",src:i,title:"","aria-hidden":"true",tabIndex:-1,allow:"autoplay",sandbox:"allow-scripts allow-same-origin",referrerpolicy:"strict-origin"}):null}function Qi(){if(typeof document>"u")return!1;let t=navigator.userAgent;return/Safari\//.test(t)&&!/(Chrome|Chromium|Edg|OPR|Firefox)\//.test(t)?!1:document.createElement("video").canPlayType('video/webm; codecs="vp9"')!==""}var ea=()=>typeof matchMedia<"u"&&matchMedia("(prefers-reduced-motion: reduce)").matches;function Me({agent:t,shot:e,talking:n=!1,still:i=!1,full:a=!1,class:s}){let o=K(null),[l,p]=C({w:0,h:0}),[d,f]=C(null),[m,c]=C({}),[g,x]=C({}),b=t.video,_=(L,z,ne)=>!a&&L&&!g[ne]?L:z,k=b?.anchor?.alphaUrl??b?.anchor?.url??null,w=_(b?.anchor?.smallUrl,k,"anchor"),$=w!==k,R=!i&&!ea()&&Qi(),N=b?.clips.idle,j=b?.clips.talking??N,B=_(N?.smallUrl,N?.alphaUrl??null,"idle"),O=_(j?.smallUrl,j?.alphaUrl??null,"talk")??B,[X,y]=C(a);if(I(()=>{n&&y(!0)},[n]),cn(()=>{let L=o.current;if(!L)return;let z=()=>p({w:L.clientWidth,h:L.clientHeight});if(z(),typeof ResizeObserver>"u")return;let ne=new ResizeObserver(z);return ne.observe(L),()=>ne.disconnect()},[]),!b||!w)return r("div",{ref:o,class:`portrait portrait--initial ${s??""}`,"aria-hidden":"true",children:r("span",{children:(t.name||"?").slice(0,1).toUpperCase()})});let Z=(b.anchor?.width&&b.anchor?.height?{w:b.anchor.width,h:b.anchor.height}:null)??(d&&!$?d:null),re=yn(b,Z?.w??0,Z?.h??0),Y=l.w&&l.h&&Z?Sn(re,Z.w/Z.h,l.w,l.h,e):null,se=Y?{width:`${Y.width}px`,height:`${Y.height}px`,left:`${Y.left}px`,top:`${Y.top}px`}:{},E=!!Y&&R&&!!B&&!!m.idle,W=!!Y&&R&&!!O&&O!==B&&!!m.talk&&n,J=!!Y&&(!!d||E);return r("div",{ref:o,class:`portrait ${s??""}`,"aria-hidden":"true",children:[r("img",{class:"portrait__media",src:w,alt:"",draggable:!1,style:{...se,opacity:Y&&d&&!E?1:0},onLoad:L=>{let z=L.currentTarget;f({w:z.naturalWidth,h:z.naturalHeight})},onError:()=>$&&x(L=>({...L,anchor:!0}))}),R&&B?r(Un,{src:B,style:se,visible:E&&!W,onReady:()=>c(L=>({...L,idle:!0})),onFail:()=>x(L=>({...L,idle:!0}))}):null,R&&X&&O&&O!==B?r(Un,{src:O,style:se,visible:W,onReady:()=>c(L=>({...L,talk:!0})),onFail:()=>x(L=>({...L,talk:!0}))}):null,r("span",{class:`portrait__sparkle${J?" is-done":""}`,children:[r("i",{}),r("i",{}),r("i",{})]})]})}function Un({src:t,style:e,visible:n,onReady:i,onFail:a}){let s=K(null);return I(()=>{let o=s.current;o&&(n?o.play().catch(()=>{}):o.pause())},[n]),r("video",{ref:s,class:"portrait__media portrait__clip",src:t,muted:!0,loop:!0,playsInline:!0,preload:"auto",style:{...e,opacity:n?1:0},onLoadedData:i,onError:a})}var wt="cxyz:greeted",On="cxyz:introduced";function Ee(t,e){try{return e!==void 0&&localStorage.setItem(t,e),localStorage.getItem(t)}catch{return null}}function ta(){try{let t=window.AudioContext??window.webkitAudioContext,e=new t,n=e.currentTime;[660,880].forEach((i,a)=>{let s=e.createOscillator(),o=e.createGain();s.type="sine",s.frequency.value=i,o.gain.setValueAtTime(0,n+a*.16),o.gain.linearRampToValueAtTime(.18,n+a*.16+.02),o.gain.exponentialRampToValueAtTime(1e-4,n+a*.16+.5),s.connect(o).connect(e.destination),s.start(n+a*.16),s.stop(n+a*.16+.55)}),setTimeout(()=>{e.close()},1200)}catch{}}function na(t){let[e,n]=C(t.chat.messages),[i,a]=C(t.chat.isBusy);return I(()=>{let s=t.chat.on("messages",n),o=t.chat.on("busy",a);return()=>{s(),o()}},[t]),{messages:e,busy:i}}function ia(t){let[e,n]=C(t.call),[i,a]=C(t.call?.state??null),[s,o]=C([]);return I(()=>t.on("call",l=>l&&n(l)),[t]),I(()=>{if(!e)return;a(e.state),o([]);let l=[e.on("state",a),e.on("caption",p=>o(d=>[...d.filter(f=>f.id!==p.id),p].slice(-4))),e.on("captionRemoved",p=>o(d=>d.filter(f=>f.id!==p)))];return()=>l.forEach(p=>p())},[e]),{call:e,state:i,captions:s,reset:()=>n(null)}}function aa(t,e){let[n,i]=C(Date.now());return I(()=>{if(!e)return;let a=setInterval(()=>i(Date.now()),1e3);return()=>clearInterval(a)},[e]),t?Math.max(0,(n-t)/1e3):0}function ra(t,e,n){I(()=>{if(!t||!n)return;let i=0,a=0,s=()=>{let o=t.voiceLevel();a=a*.7+o*.3,e.current?.style.setProperty("--cx-lvl",a.toFixed(3)),i=requestAnimationFrame(s)};return i=requestAnimationFrame(s),()=>cancelAnimationFrame(i)},[t,n,e])}function $n({parts:t}){return r(F,{children:t.map((e,n)=>e.t==="b"?r("strong",{children:e.v},n):e.t==="i"?r("em",{children:e.v},n):e.t==="code"?r("code",{children:e.v},n):e.t==="link"?r("a",{href:e.href,target:"_blank",rel:"noopener noreferrer nofollow",children:e.v},n):e.v.split(`
42
- `).map((i,a,s)=>r(F,{children:[i,a<s.length-1?r("br",{}):null]},`${n}.${a}`)))})}var sa={name:{label:"nameField",type:"text",auto:"name"},email:{label:"emailField",type:"email",auto:"email"},phone:{label:"phoneField",type:"tel",auto:"tel"},company:{label:"companyField",type:"text",auto:"organization"},reason:{label:"reasonField",type:"text",auto:"off"}};function oa(){try{let t=new URLSearchParams(location.search).get("reason")??new URLSearchParams(location.search).get("intent");return t&&t.trim()?t.trim().slice(0,120):(document.querySelector("character-xyz")?.getAttribute("data-reason")??"").trim().slice(0,120)}catch{return""}}function la({form:t,title:e,note:n,onSend:i,onSkip:a,skipLabel:s,initial:o,hasHistory:l}){let[p,d]=C(()=>({...o??{}})),f=t.reasonOptions??[],m=t.fields.includes("reason"),c=m&&!l?oa():"",g=t.reasonDefault||c||"",[x,b]=C(g),[_,k]=C(t.reasonDefault?t.reasonSource??"conversation":c?"cta":""),[w,$]=C(m&&!g),[R,N]=C(!1),[j,B]=C(""),[O,X]=C({}),[y,H]=C(null),[Z,re]=C(!1),Y=K(null),se=K(null);return I(()=>{setTimeout(()=>Y.current?.focus({preventScroll:!0}),80)},[]),I(()=>{let E=requestAnimationFrame(()=>{let W=se.current?.closest(".log");W&&(W.scrollTop=W.scrollHeight)});return()=>cancelAnimationFrame(E)},[w,R]),r("form",{class:"card",part:"details",ref:se,onSubmit:async E=>{E.preventDefault(),re(!0),X({}),H(null);try{let W=(R?j:x).trim();await i({name:p.name??"",email:p.email??"",...p.phone?{phone:p.phone}:{},...p.company?{company:p.company}:{},...m&&W?{reason:W}:{}})}catch(W){let J=W.fields??{};Object.keys(J).length?X(J):H(W.message||h("sendFailed"))}finally{re(!1)}},children:[r("div",{class:"card__title",children:e}),n?r("div",{class:"card__note",children:n}):null,t.fields.map((E,W)=>{if(E==="reason")return r("div",{class:"card__field card__field--reason",children:[!w&&x?null:r("span",{class:"card__reason-label",children:t.reasonLabel||h("reasonField")}),!w&&x?r(F,{children:[r("div",{class:"card__reason-line",children:[r("span",{class:"card__reason-said",children:h("reasonInferred")}),r("strong",{children:x}),r("button",{type:"button",class:"card__change",onClick:()=>$(!0),children:h("change")})]}),_?r("span",{class:"card__reason-src",children:_==="cta"?h("reasonFromPage"):_==="conversation"?h("reasonFromConversation"):null}):null]}):r("div",{class:"card__reason-edit",children:[f.length?r("div",{class:"card__chips",role:"group","aria-label":t.reasonLabel||h("reasonField"),children:[f.map(z=>r("button",{type:"button",class:"card__chip","aria-pressed":!R&&x===z,onClick:()=>{b(z),N(!1),k("user"),$(!1)},children:z},z)),r("button",{type:"button",class:"card__chip","aria-pressed":R,onClick:()=>{N(!0),b("")},children:h("reasonOther")})]}):null,R||!f.length?r("input",{type:"text",maxLength:500,placeholder:h("reasonPlaceholder"),value:j,onInput:z=>B(z.currentTarget.value)}):null]}),O.reason?r("em",{children:O.reason}):null]},E);let J=sa[E],L=h(J.label);return r("label",{class:"card__field",children:[r("span",{children:[L,E==="phone"||E==="company"?r("i",{children:[" \xB7 ",h("optional")]}):null]}),r("input",{ref:W===0?Y:void 0,type:J.type,autocomplete:J.auto,required:E==="name"||E==="email",maxLength:E==="email"?254:120,value:p[E]??"","aria-invalid":O[E]?"true":void 0,onInput:z=>d(ne=>({...ne,[E]:z.currentTarget.value}))}),O[E]?r("em",{children:O[E]}):null]},E)}),r("div",{class:"card__consent",children:[t.consent,t.privacyUrl?r(F,{children:[" ",r("a",{href:t.privacyUrl,target:"_blank",rel:"noopener noreferrer",children:h("privacyPolicy")})]}):null]}),y?r("div",{class:"card__failed",children:y}):null,r("div",{class:"card__actions",children:[r("button",{type:"submit",class:"btn btn--accent btn--sm",disabled:Z,children:Z?h("sending"):h("send")}),r("button",{type:"button",class:"btn btn--ghost btn--sm",onClick:a,disabled:Z,children:s})]})]})}function Ct({items:t,onPick:e,children:n}){return!t.length&&!n?null:r("div",{class:"chips chips--start",part:"suggestions",children:[t.map(i=>r("button",{class:"chip",onClick:()=>e(i),children:i},i)),n]})}function Nn({text:t}){return r(F,{children:fn(t).map((e,n)=>e.t==="ul"?r("ul",{children:e.items.map((i,a)=>r("li",{children:r($n,{parts:i})},a))},n):r("p",{children:r($n,{parts:e.parts})},n))})}function Hn({client:t,config:e,bind:n,onView:i}){let a=t.agent,s=t.features,o=e.showChat&&s.chat,l=e.showCall&&s.call,[p,d]=C(e.open?o?"chat":"call":"closed"),[f,m]=C(!1),[c,g]=C(!1),{messages:x,busy:b}=na(t),{call:_,state:k,captions:w,reset:$}=ia(t),[R,N]=C(""),j=K(null),B=K(null),O=K(null),X=e.subtitle??a.tagline,y=a.name||h("assistant"),[H,Z]=C(null);I(()=>{if(!o)return;let u=!0;return t.opening().then(S=>{u&&(_n(S?.strings),Z(S))}),()=>{u=!1}},[t,o]);let re=e.greeting||H?.teaser||"",Y=e.suggestions.length?e.suggestions:H?.suggestions??[],se=H?.greeting||h("greetingDefault",{name:y}),[E,W]=C("loading"),[J,L]=C(!1),[z,ne]=C(null),[At,qn]=C(""),[Je,Ge]=C(null),[Qe,et]=C(null),te=Te(u=>{d(u),i(u)},[i]),pe=Te(()=>{m(!0),setTimeout(()=>{m(!1),te("closed")},200)},[te]),_e=Te(async()=>{try{let u=await t.chat.load();W(S=>S==="loading"?u.length?u.length:"empty":S)}catch{W(u=>u==="loading"?"empty":u)}},[t]),Q=Te((u=o?"chat":"call")=>{g(!1),Ee(wt,"1"),te(u),u==="chat"&&_e()},[o,te,_e]);I(()=>n({open:Q,close:pe}),[n,Q,pe]),I(()=>t.on("siteEvent",u=>{u.openChat&&Q("chat")}),[t,Q]),I(()=>{e.open&&o&&_e()},[_e,e.open,o]),I(()=>{if(!re||Ee(wt))return;let u=setTimeout(()=>g(!0),e.greetingDelay*1e3);return()=>clearTimeout(u)},[re,e.greetingDelay]),I(()=>{if(p!=="chat"||J||E==="loading")return;let u=setTimeout(()=>L(!0),700);return()=>clearTimeout(u)},[p,J,E]);let[tt,Vn]=C(()=>!Ee(On));I(()=>{if(!tt)return;let u=setTimeout(()=>{Vn(!1),Ee(On,"1")},5e3);return()=>clearTimeout(u)},[tt]),I(()=>{if(p==="closed")return;let u=S=>{S.key==="Escape"&&pe()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[p,pe]),I(()=>{let u=j.current;u&&(u.scrollTop=u.scrollHeight)},[x,p,k?.phase]),I(()=>{p==="chat"&&setTimeout(()=>B.current?.focus({preventScroll:!0}),60)},[p]);let xe=e.face&&!!a.video,[Fe,Kn]=C("loading"),T=k?.phase??"idle";I(()=>{if(!(T!=="ready"||!_)){if(ta(),p==="call"){if(!xe||Fe!=="loading"){_.accept();return}let u=setTimeout(()=>_.accept(),3e3);return()=>clearTimeout(u)}if(typeof document<"u"&&document.hidden){let u=document.title;document.title=`\u25CF ${y} is ready for you`;let S=()=>{document.title=u,document.removeEventListener("visibilitychange",S)};document.addEventListener("visibilitychange",S)}}},[T,_,p,y,xe,Fe]);let Mt=T==="live"||T==="connecting";ra(_,O,Mt&&p==="call");let Ie=aa(k?.startedAt??null,T==="live"),nt=ca(_,k?.position??1),it=()=>{let u=H?.details;if(u&&!z&&o){Ge(u),te("chat"),_e();return}at()},Et=(u,S="")=>{ne(u),qn(S),et(null);let ue=!!Je;Ge(null),ue&&at()},Xn=async u=>{await t.sendDetails(u),Et("sent",u.name.trim().split(/\s+/)[0]??"")},Zn=()=>{t.declineDetails().catch(()=>{}),Et("skipped")},Jn=async()=>{try{await t.chat.reset()}catch{return}W("empty"),L(!1),ne(null),Ge(null),et(null),N(""),Z(await t.opening(!0))},at=async()=>{te("call");try{await t.startCall({autoAccept:!1,...xe?{face:{emotion:()=>kt.current}}:{}})}catch{}},rt=[...x].reverse().find(u=>u.detailsForm||u.askDetails)?.detailsForm??[...x].reverse().find(u=>u.askDetails)?.askDetails??H?.details??null,be=async u=>{let S=u.trim();if(!S||b)return;let ue=rt&&z!=="sent"?An(S):null;ue&&rt&&et({form:rt,values:ue}),N(""),B.current&&(B.current.style.height="");try{await t.chat.send(S)}catch{}},Le=x[x.length-1],Ft=Le?.role==="agent"&&!Le.streaming?Le.askDetails:void 0,q=Je?{form:Je,kind:"call"}:Qe&&z!=="sent"&&!b?{form:Qe.form,kind:"typed",initial:Qe.values}:Ft&&!z?{form:Ft,kind:"invited"}:null;if(p==="closed"){let u=T==="queued"||T==="ready"||T==="live"||T==="connecting";return r("div",{class:`dock dock--${e.display}`,part:"launcher",children:[c?r("div",{class:"greeting",part:"greeting",role:"status",onClick:()=>Q(),children:[re,r("button",{class:"greeting__close","aria-label":h("dismiss"),onClick:S=>{S.stopPropagation(),g(!1),Ee(wt,"1")},children:r(Xe,{size:14})})]}):null,r("button",{class:`presence presence--${e.display} ${u?"presence--live":""}`,part:"presence","aria-label":u?T==="queued"?h("inLineToCall",{position:le(k?.position??1),name:y}):h("backToCallWith",{name:y}):o?h("chatWith",{name:y}):h("callName",{name:y}),onClick:()=>Q(u||!o?"call":"chat"),children:[e.display==="bubble"?r("span",{class:"presence__ring"}):null,r("span",{class:"presence__face",children:r(Me,{agent:a,shot:e.display==="full"?Cn:e.display==="half"?wn:Ke})}),r("span",{class:"presence__dot"}),t.mode==="test"?r("span",{class:"testmode",title:"Test mode: this key only works on development sites",children:"TEST"}):null,T==="queued"?r("span",{class:"presence__badge","aria-hidden":"true",children:k?.position??1}):null,e.launcher==="bubble"&&!c?r("span",{class:"presence__label","aria-hidden":"true",children:u?T==="queued"?h("inLine",{position:le(k?.position??1)}):h("backToCall"):o?h("chatWith",{name:y}):h("callName",{name:y})}):null]}),e.launcher==="bubble"?null:r("div",{class:`acts ${tt?"acts--labelled":""}`,part:"actions",children:[o?r("button",{class:"act","aria-label":h("chatWith",{name:y}),onClick:()=>Q("chat"),children:[r(Ae,{size:20}),r("span",{class:"act__label","aria-hidden":"true",children:h("chat")})]}):null,l?r("button",{class:`act act--call ${u?"act--live":""}`,"aria-label":u?T==="queued"?h("inLineOpen",{position:le(k?.position??1)}):h("backToCall"):h("callName",{name:y}),onClick:()=>u?Q("call"):it(),children:[r(me,{size:20}),r("span",{class:"act__label","aria-hidden":"true",children:u?T==="queued"?h("inLine",{position:le(k?.position??1)}):h("onCall"):h("call")}),T==="queued"?r("span",{class:"act__badge","aria-hidden":"true",children:k?.position??1}):null]}):null]})]})}let Gn=r("div",{class:"head",part:"header",children:[r("div",{class:"head__face",children:r(Me,{agent:a,shot:Ke})}),r("div",{class:"head__who",children:[r("div",{class:"head__name",children:y}),r("div",{class:"head__sub",children:[r("i",{}),b?h("typing"):X||h("online")]})]}),p==="chat"&&x.length>0&&!b?r("button",{class:"icon-btn","aria-label":h("newConversation"),title:h("newConversation"),onClick:()=>{Jn()},children:r(zn,{})}):null,l&&p==="chat"?r("button",{class:"icon-btn icon-btn--accent","aria-label":h("callName",{name:y}),title:h("callName",{name:y}),onClick:()=>_&&T!=="ended"?te("call"):it(),children:r(me,{size:18})}):null,r("button",{class:"icon-btn","aria-label":h("close"),onClick:pe,children:r(Xe,{})})]});if(p==="chat")return r("div",{class:`panel ${f?"is-closing":""}`,part:"panel",role:"dialog","aria-label":h("chatWith",{name:y}),children:[Gn,_&&(T==="queued"||T==="ready")?r("div",{class:"banner",part:"banner",role:"status",children:[r("div",{class:"banner__text",children:T==="queued"?r(F,{children:h("inLineFor",{position:le(k?.position??1),eta:Ve(k?.etaSeconds??null)})}):r(F,{children:[r("b",{children:h("readyForYou",{name:y})})," \xB7 ",h("secondsToJoin",{seconds:k?.holdSeconds??30})]})}),T==="ready"?r("button",{class:"btn btn--accent btn--glow",onClick:()=>{_.accept(),te("call")},children:h("join")}):r("button",{class:"btn",onClick:()=>te("call"),children:h("view")})]}):null,r("div",{class:"log",ref:j,role:"log","aria-live":"polite","aria-relevant":"additions",children:[x.length===0?r(F,{children:[r("div",{class:"empty",children:[r("div",{class:"empty__face",children:r(Me,{agent:a,shot:Ke})}),r("div",{class:"empty__title",children:y}),X?r("div",{class:"empty__body",children:X}):null]}),E==="loading"?null:J?r(F,{children:[r("div",{class:"msg msg--agent",part:"message message-agent",children:r(Nn,{text:se})}),q?null:r(Ct,{items:Y,onPick:u=>{be(u)},children:l?r("button",{class:"chip chip--call",onClick:()=>_&&T!=="ended"?te("call"):it(),children:[r(me,{size:14})," ",h("callName",{name:y})]}):null})]}):r("div",{class:"msg msg--agent typing","aria-label":h("typingName",{name:y}),children:[r("i",{}),r("i",{}),r("i",{})]})]}):null,x.map(u=>u.role==="event"?r("div",{class:"event",part:"event message message-event",children:[r("span",{class:"event__dot","aria-hidden":"true"}),u.text]},u.id):u.role==="agent"&&u.streaming&&!u.text?r("div",{class:"msg msg--agent typing","aria-label":h("typingName",{name:y}),children:[r("i",{}),r("i",{}),r("i",{})]},u.id):r(F,{children:[r("div",{class:`msg msg--${u.role} ${u.failed?"msg--failed":""} ${u.streaming?"caret":""}`,part:`message message-${u.role}`,children:u.role==="agent"?r(Nn,{text:u.text}):u.text}),u===x[x.length-1]&&u.role==="agent"&&!u.streaming&&!b&&!q&&u.suggestions?.length?r(Ct,{items:u.suggestions,onPick:S=>{be(S)}}):null,u.failed&&u.error?r("div",{class:"msg__why",role:"status",children:u.error}):u.failed?r("button",{class:"msg__retry",onClick:()=>{t.chat.retry(u.id).catch(()=>{})},children:[r(Rn,{})," ",h("notSent")]}):null]},u.id)),typeof E=="number"&&x.length===E&&H?.welcomeBack?r(F,{children:[r("div",{class:"msg msg--agent",part:"message message-agent",children:H.welcomeBack}),q?null:r(Ct,{items:Y,onPick:u=>{be(u)}})]}):null,q?r(la,{form:q.form,initial:q.initial,title:q.kind==="call"?h("beforeYouCall",{name:y}):q.kind==="typed"?h("confirmDetails"):h("leaveDetails"),note:q.kind==="call"?h("detailsWhy"):q.kind==="typed"?h("detailsTyped"):null,onSend:Xn,onSkip:Zn,skipLabel:q.kind==="call"?h("skipAndCall"):h("notNow"),hasHistory:x.length>0},q.kind==="invited"?Le?.id:q.kind):z==="sent"?r("div",{class:"notice",role:"status",children:[r(Dn,{})," ",At?h("thanksName",{name:At}):h("thanks")]}):null]}),r("form",{class:"compose",part:"composer",onSubmit:u=>{u.preventDefault(),be(R)},children:r("div",{class:"compose__box",children:[r("textarea",{ref:B,rows:1,value:R,maxLength:2e3,placeholder:e.placeholder===ce.placeholder?h("message"):e.placeholder,"aria-label":h("message"),onInput:u=>{let S=u.currentTarget;N(S.value),S.style.height="auto",S.style.height=`${Math.min(120,S.scrollHeight)}px`},onKeyDown:u=>{u.key==="Enter"&&!u.shiftKey&&!u.isComposing&&(u.preventDefault(),be(R))}}),r("button",{class:"send",type:"submit","aria-label":h("send"),disabled:!R.trim()||b,children:r(In,{})})]})}),e.branding?r("div",{class:"foot",children:h("poweredBy").split("{brand}").map((u,S)=>r(F,{children:[S?r("a",{href:"https://character.xyz",target:"_blank",rel:"noopener noreferrer",children:"Character XYZ"}):null,u]},S))}):null]});let A=k,st=A?.position??1,Qn=nt>1?(nt-st)/(nt-1):0,ot=74,It=2*Math.PI*ot,ve=A?.maxSeconds?A.maxSeconds-Ie:null,ei=A?.agentState??"idle",ti=A?.speaking?h("speaking"):ei==="thinking"?h("thinking"):h("listening"),ni=!A||T==="ended"||T==="idle",lt=xn(A?.endReason??null,y);return r("div",{class:`panel ${f?"is-closing":""}`,part:"panel",role:"dialog","aria-label":h("callWith",{name:y}),children:r("div",{class:`stage ${xe&&Fe==="ready"?"stage--face":""}`,ref:O,children:[r("div",{class:"stage__figure",style:{opacity:T==="queued"?.35:1,transition:"opacity .6s"},children:[r(Me,{agent:a,shot:kn,talking:!!A?.speaking,full:!0}),xe?r("div",{class:`stage__face ${Fe==="ready"?"is-ready":""}`,children:r(Pn,{client:t,call:_,state:A,src:e.faceUrl,onStatus:Kn})}):null]}),Mt?r("div",{class:"voice"}):null,r("div",{class:"stage__veil"}),r("div",{class:"stage__top",children:[T==="live"?r("span",{class:`badge ${ve!=null&&ve<=60?"badge--warn":""}`,role:"timer","aria-label":h("callTime"),children:[r("i",{}),ve!=null&&ve<=60?h("timeLeft",{time:qe(ve)}):qe(Ie)]}):r("span",{}),r("div",{style:{display:"flex",gap:"6px"},children:[o?r("button",{class:"icon-btn","aria-label":h("chat"),title:h("chat"),onClick:()=>Q("chat"),children:r(Ae,{size:18})}):null,r("button",{class:"icon-btn","aria-label":h("minimise"),onClick:pe,children:r(Xe,{})})]})]}),r("div",{class:"stage__bottom","aria-live":"polite",children:[T==="joining"||T==="connecting"?r(F,{children:[r("div",{class:"stage__name",children:y}),r("div",{class:"stage__status",children:[r("span",{class:"spinner"})," ",T==="joining"?h("connecting"):h("joining")]})]}):null,T==="queued"?r(F,{children:[r("div",{class:"line",role:"status","aria-label":h("inLineEta",{position:le(st),eta:Ve(A?.etaSeconds??null)}),children:[r("svg",{width:"168",height:"168",viewBox:"0 0 168 168",children:[r("circle",{class:"line__track",cx:"84",cy:"84",r:ot,fill:"none","stroke-width":"7"}),r("circle",{class:"line__fill",cx:"84",cy:"84",r:ot,fill:"none","stroke-width":"7","stroke-linecap":"round","stroke-dasharray":It,"stroke-dashoffset":It*(1-Math.max(.06,Qn))})]}),r("div",{children:[r("div",{class:"line__num",children:le(st)}),r("div",{class:"line__lbl",children:h("lineLabel")})]})]}),r("div",{class:"title",children:h("onOtherCalls",{name:y})}),r("div",{class:"note",children:h(o?"yourTurnChat":"yourTurn",{eta:Ve(A?.etaSeconds??null)})}),r("div",{class:"btn-row",children:[o?r("button",{class:"btn btn--accent",onClick:()=>Q("chat"),children:[r(Ae,{size:18})," ",h("keepChatting")]}):null,r("button",{class:"btn",onClick:()=>{_?.hangUp()},children:h("leaveLine")})]})]}):null,T==="ready"?r(F,{children:[r("div",{class:"title",children:h("readyForYou",{name:y})}),r("div",{class:"note",children:h("joinWithin",{seconds:A?.holdSeconds??30})}),r("button",{class:"btn btn--accent btn--glow",onClick:()=>_?.accept(),children:[r(me,{size:18})," ",h("joinCall")]})]}):null,T==="live"?r(F,{children:[r("div",{class:"stage__name",children:y}),r("div",{class:"stage__status",children:[A?.speaking?r("span",{class:"wave","aria-hidden":"true",children:[.6,1,.75,1,.55].map((u,S)=>r("i",{style:{"--k":u}},S))}):null,A?.muted?h("muted"):ti]}),r("div",{class:"captions",children:w.slice(-2).map((u,S,ue)=>r("div",{class:`captions__line ${S===ue.length-1?"captions__line--now":""}`,children:u.role==="visitor"?h("you",{text:u.text}):u.text},u.id))}),r("div",{class:"controls",children:[r("div",{class:"ctl",children:[r("button",{class:`round ${A?.muted?"round--on":""}`,"aria-pressed":A?.muted,"aria-label":A?.muted?h("unmute"):h("mute"),onClick:()=>_?.setMuted(!A?.muted),children:A?.muted?r(Fn,{size:22}):r(En,{size:22})}),r("span",{class:"round__label",children:A?.muted?h("unmute"):h("mute")})]}),r("div",{class:"ctl",children:[r("button",{class:"round round--end","aria-label":h("endCall"),onClick:()=>{_?.hangUp()},children:r(Mn,{size:26})}),r("span",{class:"round__label",children:h("end")})]}),A?.speaking?r("div",{class:"ctl",children:[r("button",{class:"round","aria-label":h("interruptName",{name:y}),onClick:()=>_?.interrupt(),children:r(Ln,{size:22})}),r("span",{class:"round__label",children:h("interrupt")})]}):null]})]}):null,ni?r(F,{children:[r("div",{class:"title",children:A?lt.title:h("callName",{name:y})}),r("div",{class:"note",children:A?A.endReason==="hangup"&&Ie?`${qe(Ie)} \xB7 ${lt.body}`:A.error??lt.body:h("talkWith",{name:y})}),r("div",{class:"btn-row",children:[l&&A?.endReason!=="credits"&&A?.endReason!=="unavailable"&&A?.endReason!=="daily_limit"?r("button",{class:"btn btn--accent",onClick:()=>{$(),at()},children:[r(me,{size:18})," ",A?h("callAgain"):h("startCall")]}):null,o?r("button",{class:"btn",onClick:()=>Q("chat"),children:[r(Ae,{size:18})," ",h("chat")]}):null]})]}):null]})]})})}function ca(t,e){let n=K({call:null,start:e});return n.current.call!==t&&(n.current={call:t,start:e}),e>n.current.start&&(n.current.start=e),n.current.start}var Wn=`
39
+ `)){if(!d||d.startsWith(":"))continue;let f=d.indexOf(":"),_=f===-1?d:d.slice(0,f),c=f===-1?"":d.slice(f+1).replace(/^ /,"");_==="event"?s=c:_==="data"&&o.push(c)}if(!o.length)continue;let l=o.join(`
40
+ `),p=l;try{p=JSON.parse(l)}catch{}e({event:s,data:p})}return n}function vi(t){if(t.byteLength<25)return null;let e=new DataView(t);if(e.getUint8(0)!==67||e.getUint8(1)!==88||e.getUint8(2)!==89||e.getUint8(3)!==90||e.getUint8(4)!==1)return null;let n=e.getUint8(5),i=(e.getUint8(6)&1)!==0,a=7,s=e.getUint16(a,!0);if(a+=2,a+s+20>t.byteLength)return null;let o=new TextDecoder().decode(new Uint8Array(t,a,s));a+=s+4+8+4;let l=e.getUint32(a,!0);return a+=4,a+l>t.byteLength?null:{kind:n,final:i,corr:o,payload:new Uint8Array(t,a,l)}}var yi=.09,ki=350,wi=25e3,Ci=()=>({phase:"idle",callId:null,position:null,etaSeconds:null,holdSeconds:null,maxSeconds:null,startedAt:null,endReason:null,muted:!1,speaking:!1,agentState:"idle",error:null}),Si=class extends ht{constructor(t,e,n,i={}){super(),y(this,"apiUrl",t),y(this,"session",e),y(this,"agentId",n),y(this,"opts",i),y(this,"s",Ci()),y(this,"ticket",null),y(this,"eventsAbort",null),y(this,"ws",null),y(this,"mic",null),y(this,"players",new Map),y(this,"sampleRates",new Map),y(this,"cancelled",new Set),y(this,"speakingCorr",null),y(this,"heartbeat",null),y(this,"loudSince",null)}get state(){return this.s}audible(){let t=this.speakingCorr,e=t?this.players.get(t):void 0;return t&&e?{corr:t,ms:e.playedMs()}:null}voiceLevel(){let t=this.speakingCorr?this.players.get(this.speakingCorr):void 0;return t?t.level():0}set(t){this.s={...this.s,...t},this.emit("state",this.s)}async start(){if(this.s.phase==="idle"){this.set({phase:"joining"}),Pt();try{this.mic=await _i({deviceId:this.opts.deviceId,onFrame:(t,e)=>this.onMicFrame(t,e)})}catch{this.finish("mic-denied","Allow the microphone to talk, or chat instead.");return}try{let t=await this.session.token(),e=await X(this.apiUrl,"/sdk/v1/calls",{method:"POST",body:{},token:t});this.set({callId:e.callId,phase:e.state==="ready"?"joining":"queued",position:e.position??null,etaSeconds:e.etaSeconds??null}),this.follow()}catch(t){let e=t instanceof P?t:new P("unknown","Could not start the call."),n=e.code==="rate_limited"?"busy":"unavailable";this.finish(n,e.message),this.emit("error",e)}}}async follow(){let t=0;for(;this.s.callId&&this.s.phase!=="ended"&&this.s.phase!=="idle";){this.eventsAbort=new AbortController;try{let e=await this.session.token(),n=await Ce(this.apiUrl,`/sdk/v1/calls/${encodeURIComponent(this.s.callId)}/events`,{token:e,signal:this.eventsAbort.signal});t=0,await Ut(n,i=>this.onServerEvent(i.event,i.data),this.eventsAbort.signal)}catch(e){if(e?.name==="AbortError")return;if(e instanceof P&&e.code==="not_found"){this.finish("failed","The call ended.");return}if(t+=1,t>5){this.finish("failed","Lost the connection to the call.");return}}if(this.ended())return;await new Promise(e=>setTimeout(e,Math.min(4e3,500*2**t)))}}onServerEvent(t,e){switch(t){case"queued":(this.s.phase==="joining"||this.s.phase==="queued")&&this.set({phase:"queued",position:Number(e.position)||1,etaSeconds:Number(e.etaSeconds)||null});break;case"ready":{typeof e.ticket=="string"&&e.ticket&&(this.ticket=e.ticket);let n=Number(e.holdSeconds)||0;this.s.phase!=="ready"&&this.s.phase!=="connecting"&&this.s.phase!=="live"?(this.set({phase:"ready",holdSeconds:n,position:null,etaSeconds:null}),this.emit("ready",{holdSeconds:n}),this.opts.autoAccept!==!1&&this.accept()):this.s.phase==="ready"&&this.set({holdSeconds:n});break}case"live":this.set({phase:"live",maxSeconds:Number(e.maxSeconds)||null,startedAt:this.s.startedAt??Date.now()-(Number(e.elapsedSeconds)||0)*1e3});break;case"ended":this.finish(String(e.reason||"hangup")||"hangup",null);break}}ended(){return this.s.phase==="ended"}accept(){if(this.s.phase!=="ready"||!this.ticket||this.ws)return;this.set({phase:"connecting"});let t=this.apiUrl.replace(/^http/,"ws")+"/sdk/v1/calls/socket",e=new WebSocket(t,[`cxyz-ticket.${this.ticket}`]);this.ticket=null,e.binaryType="arraybuffer",this.ws=e,e.onopen=()=>{let n=this.opts.face,i=n?.emotion?.()??null;e.send(JSON.stringify({type:"agent_identity",agent_id:this.agentId,skin_index:0,blendshapes:!!n,...n?{blendshape_stream:!0}:{},...n&&i?{face_emotion:i}:{}})),e.send(JSON.stringify({type:"mic_state",silero:"off",denoise:!1})),this.heartbeat=setInterval(()=>this.sendJson({type:"heartbeat"}),wi),this.set({phase:"live",startedAt:this.s.startedAt??Date.now()})},e.onmessage=n=>this.onSocket(n.data),e.onclose=()=>{this.ws=null,setTimeout(()=>{(this.s.phase==="live"||this.s.phase==="connecting")&&this.finish("hangup",null)},1500)}}sendJson(t){this.ws?.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify(t))}onMicFrame(t,e){let n=this.ws;if(!(!n||n.readyState!==WebSocket.OPEN)){if(this.speakingCorr){let i=performance.now();if(e>yi){if(this.loudSince??(this.loudSince=i),i-this.loudSince>=ki){this.loudSince=null,this.interrupt(),n.send(t);return}}else this.loudSince=null;n.send(new ArrayBuffer(t.byteLength));return}n.send(t)}}onSocket(t){if(t instanceof ArrayBuffer){let n=vi(t);if(!n||this.cancelled.has(n.corr))return;if(n.kind===3){this.opts.face&&this.emit("face",{corr:n.corr,payload:n.payload.slice()});return}if(n.kind!==1)return;let i=this.players.get(n.corr);if(!i){for(let[s,o]of this.players)o.stop(),this.players.delete(s);let a=n.corr;i=new fi({sampleRate:this.sampleRates.get(a)??16e3,onStart:()=>{this.speakingCorr=a,this.set({speaking:!0}),this.emit("line",{corr:a,event:"audible"}),this.sendJson({type:"playback_started",correlationId:a,timestampMs:Date.now()})},onEnd:()=>{this.players.delete(a),this.speakingCorr===a&&(this.speakingCorr=null),this.set({speaking:!1}),this.emit("line",{corr:a,event:"end"}),this.sendJson({type:"playback_ended",correlationId:a,timestampMs:Date.now(),reason:"natural"}),this.sendJson({type:"speech_ended"})}}),this.players.set(a,i)}i.enqueue(n.payload),n.final&&i.end();return}if(typeof t!="string")return;let e;try{e=JSON.parse(t)}catch{return}if("AgentSpeechMeta"in e){let n=e.AgentSpeechMeta;n?.correlation_id&&n.sample_rate&&this.sampleRates.set(n.correlation_id,n.sample_rate);return}if("InteractorTranscript"in e){let n=e.InteractorTranscript;n?.text&&this.emit("caption",{id:`v:${n.correlation_id}`,role:"visitor",text:n.text});return}if("AgentReplyTranscript"in e){let n=e.AgentReplyTranscript;n?.text&&!this.cancelled.has(n.correlation_id)&&this.emit("caption",{id:`a:${n.correlation_id}`,role:"agent",text:n.text});return}if(e.type==="turn_cancelled"&&typeof e.correlationId=="string"){let n=e.correlationId;this.cancelled.add(n),this.players.get(n)?.stop(),this.players.delete(n),this.emit("line",{corr:n,event:"end"}),this.speakingCorr===n&&(this.speakingCorr=null,this.set({speaking:!1})),this.emit("captionRemoved",`a:${n}`);return}e.kind==="agent_status"&&typeof e.state=="string"&&this.set({agentState:e.state.toLowerCase()})}interrupt(){let t=this.speakingCorr;if(!t)return;let e=this.players.get(t),n=Math.round(e?.playedMs()??0);e?.stop(),this.players.delete(t),this.cancelled.add(t),this.speakingCorr=null,this.set({speaking:!1}),this.emit("line",{corr:t,event:"end"}),this.sendJson({type:"playback_ended",correlationId:t,timestampMs:Date.now(),reason:"interrupted"}),this.sendJson({type:"interrupt",correlationId:t,heardMs:n,timestampMs:Date.now()})}setMuted(t){this.mic?.setMuted(t),this.set({muted:t})}async hangUp(){let t=this.s.callId,e=this.s.phase;if(this.finish(e==="live"?"hangup":"left",null),!!t)try{let n=await this.session.token();await Ce(this.apiUrl,`/sdk/v1/calls/${encodeURIComponent(t)}`,{method:"DELETE",token:n})}catch{}}finish(t,e){if(this.s.phase==="ended")return;this.eventsAbort?.abort(),this.eventsAbort=null,this.heartbeat&&clearInterval(this.heartbeat),this.heartbeat=null;for(let i of this.players.values())i.stop();this.players.clear(),this.speakingCorr=null,this.mic?.stop(),this.mic=null;let n=this.ws;this.ws=null,n&&n.readyState<=WebSocket.OPEN&&n.close(1e3),this.ticket=null,this.set({phase:"ended",endReason:t,speaking:!1,holdSeconds:null,error:e})}},Ti=0,Dt=t=>`${t}_${Date.now().toString(36)}_${(Ti++).toString(36)}`,Ai=class extends ht{constructor(t,e){super(),y(this,"apiUrl",t),y(this,"session",e),y(this,"list",[]),y(this,"loaded",!1),y(this,"busy",!1),y(this,"abort",null)}get messages(){return this.list}get isBusy(){return this.busy}publish(){this.list=[...this.list],this.emit("messages",this.list)}applySiteEvent(t){let e=!1;t.event&&!this.list.some(n=>n.id===t.event.id)&&(this.list.push(t.event),e=!0),t.message&&!this.list.some(n=>n.id===t.message.id)&&(this.list.push({...t.message,...t.suggestions?.length?{suggestions:t.suggestions}:{},...t.askDetails?{askDetails:t.askDetails}:{}}),e=!0),e&&this.publish()}async load(){if(this.loaded)return this.list;let t=await this.session.token(),e=await X(this.apiUrl,"/sdk/v1/chat/messages?limit=50",{token:t}),n=this.list;return this.list=[...e?.messages??[],...n],this.loaded=!0,this.publish(),this.list}async send(t){let e=t.trim();if(!e)throw new P("invalid","Say something first.");if(this.busy)throw new P("rate_limited","Wait for the reply first.");this.setBusy(!0);let n={id:Dt("local"),role:"visitor",text:e,createdAt:new Date().toISOString()},i={id:Dt("reply"),role:"agent",text:"",createdAt:new Date().toISOString(),streaming:!0};this.list.push(n,i),this.publish(),this.abort=new AbortController;try{let a=await this.session.token(),s=await Ce(this.apiUrl,"/sdk/v1/chat/messages",{method:"POST",body:{text:e},token:a,signal:this.abort.signal}),o=null,l=null;if(await Ut(s,({event:d,data:f})=>{let _=f;if(d==="delta"&&typeof _?.text=="string")i.text+=_.text,this.publish();else if(d==="done"){let c=Array.isArray(_.suggestions)?_.suggestions.filter(g=>typeof g=="string"&&g.trim()!==""):[];o={id:String(_.id),role:"agent",text:String(_.text??i.text),createdAt:String(_.createdAt??i.createdAt),...c.length?{suggestions:c}:{},..._.askDetails&&typeof _.askDetails=="object"?{askDetails:_.askDetails}:{},..._.detailsForm&&typeof _.detailsForm=="object"?{detailsForm:_.detailsForm}:{}}}else d==="error"&&(l=typeof _?.message=="string"?_.message:"Something went wrong.")},this.abort.signal),l||!o)throw new P("unknown",l??"The reply was cut off. Try again.");let p=o;return this.replace(i.id,p),p}catch(a){let s=a instanceof P?a:new P("network","The reply was cut off. Try again.");this.list=this.list.filter(l=>l.id!==i.id);let o=this.list.findIndex(l=>l.id===n.id);throw o!==-1&&(this.list[o]={...n,failed:!0,...s.status===429?{error:s.message}:{}}),this.publish(),a?.name!=="AbortError"&&this.emit("error",s),s}finally{this.abort=null,this.setBusy(!1)}}async reset(){this.stop();let t=await this.session.token();await Ce(this.apiUrl,"/sdk/v1/chat/messages",{method:"DELETE",token:t}),this.list=[],this.loaded=!0,this.publish()}retry(t){let e=this.list.find(n=>n.id===t&&n.failed);if(!e)throw new P("not_found","Nothing to retry.");return this.list=this.list.filter(n=>n.id!==t),this.publish(),this.send(e.text)}stop(){this.abort?.abort()}replace(t,e){let n=this.list.findIndex(i=>i.id===t);n!==-1&&(this.list[n]=e),this.publish()}setBusy(t){this.busy=t,this.emit("busy",t)}},Mi=()=>{let t=new Map;return{get:e=>t.get(e)??null,set:(e,n)=>{t.set(e,n)}}},Ei=()=>({get(t){try{return globalThis.localStorage?.getItem(t)??null}catch{return null}},set(t,e){try{globalThis.localStorage?.setItem(t,e)}catch{}}}),Ii=60,Fi=class{constructor(t){if(y(this,"src",t),y(this,"current",null),y(this,"inflight",null),!t.publishableKey&&!t.getSessionToken)throw new P("invalid","Pass a publishableKey, or getSessionToken for sessions your server mints.")}visitorKey(){return`cxyz:visitor:${(this.src.publishableKey??"server").slice(-12)}`}get info(){return this.current}async token(){let t=Date.now()/1e3;return this.current&&this.current.expiresAt-Ii>t?this.current.token:(await this.refresh()).token}refresh(){return this.inflight??(this.inflight=this.mint().finally(()=>{this.inflight=null})),this.inflight}async mint(){let t;if(this.src.getSessionToken){let e=await this.src.getSessionToken();typeof e=="string"?t=await this.describe(e):t=e}else{let e=this.src.store.get(this.visitorKey())??void 0;t=await X(this.src.apiUrl,"/sdk/v1/sessions",{method:"POST",body:{publishableKey:this.src.publishableKey,agentId:this.src.agentId,visitorId:e}}),this.src.store.set(this.visitorKey(),t.visitorId)}return this.current=t,t}async describe(t){return{...await X(this.src.apiUrl,"/sdk/v1/session",{token:t}),token:t}}},Li="https://api.character.xyz",Ot=class $t extends ht{constructor(e,n,i){super(),y(this,"apiUrl",e),y(this,"session",n),y(this,"info",i),y(this,"chat"),y(this,"currentCall",null),y(this,"destroyed",!1),y(this,"openingP",null),y(this,"actionHandlers",new Map),this.chat=new Ai(e,n)}static async init(e){let n=(e.apiUrl??Li).replace(/\/+$/,"");if(e.publishableKey&&/^cxyz_sk_/.test(e.publishableKey))throw new P("invalid","That is a SECRET key. Never put it in a web page: use a publishable key (cxyz_pk_\u2026). Revoke the secret key now.");let i=e.storage==="memory"?Mi():e.storage&&typeof e.storage=="object"?e.storage:Ei(),a=new Fi({apiUrl:n,agentId:e.agentId,publishableKey:e.publishableKey,getSessionToken:e.getSessionToken,store:i}),s=await a.refresh();return new $t(n,a,s)}get agent(){return(this.session.info??this.info).agent}get features(){return(this.session.info??this.info).features}get appearance(){return(this.session.info??this.info).appearance??{}}get visitorId(){return(this.session.info??this.info).visitorId}get mode(){return(this.session.info??this.info).mode}get call(){return this.currentCall&&this.currentCall.state.phase!=="ended"?this.currentCall:null}async videoAvatar(){let e=await this.session.token();return X(this.apiUrl,"/sdk/v1/agent/video-avatar",{token:e})}opening(e=!1){return e&&(this.openingP=null),this.openingP??(this.openingP=this.session.token().then(n=>{let i=typeof navigator>"u"?"":navigator.language||"",a=i?`/sdk/v1/agent/opening?locale=${encodeURIComponent(i)}`:"/sdk/v1/agent/opening";return X(this.apiUrl,a,{token:n})}).catch(()=>null)),this.openingP}async sendDetails(e){let n=await this.session.token(),i=typeof location<"u"?location.href:void 0;await X(this.apiUrl,"/sdk/v1/lead",{token:n,body:{...e,consent:!0,...i?{page:i}:{}}})}async declineDetails(){let e=await this.session.token();await X(this.apiUrl,"/sdk/v1/lead/decline",{token:e,method:"POST",body:{}})}async identify(e){let n=await this.session.token();await X(this.apiUrl,"/sdk/v1/context",{token:n,method:"POST",body:{visitor:e}})}async setContext(e){let n=await this.session.token();await X(this.apiUrl,"/sdk/v1/context",{token:n,method:"POST",body:{context:e}})}async track(e,n={},i={}){let a=await this.session.token(),s=i.id??Ri(),o=await X(this.apiUrl,"/sdk/v1/track",{token:a,method:"POST",body:{name:e,data:n,id:s},keepalive:!0});this.emit("siteEvent",o),!o.accepted&&o.ignored&&o.ignored!=="duplicate"&&console.warn(`[characterxyz] event "${e}" ignored: ${o.ignored}`);for(let p of o.actions??[])this.runAction(p);let l=0;for(;o.action&&l++<4;){let p=o.action,d=await this.runAction(p);o=await X(this.apiUrl,`/sdk/v1/actions/${encodeURIComponent(p.id)}`,{token:a,method:"POST",body:d}),this.emit("siteEvent",o)}return this.chat.applySiteEvent(o),o}registerAction(e,n){return this.actionHandlers.set(e,n),()=>{this.actionHandlers.get(e)===n&&this.actionHandlers.delete(e)}}async runAction(e){let n=this.actionHandlers.get(e.name);if(!n)return{ok:!1,error:`no handler registered for "${e.name}"`};try{return{ok:!0,result:await n(e.inputs??{},e.name)??null}}catch(i){return{ok:!1,error:String(i?.message??i)}}}async startCall(e={}){if(this.destroyed)throw new P("invalid","This client was destroyed.");if(!this.features.call)throw new P("forbidden","Calls are not available on this site.");if(this.call)return this.call;let n=new Si(this.apiUrl,this.session,this.agent.id,e);return this.currentCall=n,n.on("state",i=>{i.phase==="ended"&&this.currentCall===n&&this.emit("call",null)}),n.on("error",i=>this.emit("error",i)),this.emit("call",n),await n.start(),n}destroy(){this.destroyed=!0,this.currentCall?.hangUp(),this.chat.stop(),this.chat.clear(),this.actionHandlers.clear(),this.clear()}};function Ri(){let t=typeof crypto<"u"?crypto:void 0;return t&&typeof t.randomUUID=="function"?`evt_${t.randomUUID()}`:`evt_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`}var We,I,Yt,zi,le,Nt,qt,jt,ft,Ue,Se,Vt,_t,gt,mt,Di,Ne={},He=[],Pi=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Ye=Array.isArray;function ae(t,e){for(var n in e)t[n]=e[n];return t}function xt(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function Ui(t,e,n){var i,a,s,o={};for(s in e)s=="key"?i=e[s]:s=="ref"?a=e[s]:o[s]=e[s];if(arguments.length>2&&(o.children=arguments.length>3?We.call(arguments,2):n),typeof t=="function"&&t.defaultProps!=null)for(s in t.defaultProps)o[s]===void 0&&(o[s]=t.defaultProps[s]);return Oe(t,o,i,a,null)}function Oe(t,e,n,i,a){var s={type:t,props:e,key:n,ref:i,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:a??++Yt,__i:-1,__u:0};return a==null&&I.vnode!=null&&I.vnode(s),s}function F(t){return t.children}function $e(t,e){this.props=t,this.context=e}function pe(t,e){if(e==null)return t.__?pe(t.__,t.__i+1):null;for(var n;e<t.__k.length;e++)if((n=t.__k[e])!=null&&n.__e!=null)return n.__e;return typeof t.type=="function"?pe(t):null}function Oi(t){if(t.__P&&t.__d){var e=t.__v,n=e.__e,i=[],a=[],s=ae({},e);s.__v=e.__v+1,I.vnode&&I.vnode(s),bt(t.__P,s,e,t.__n,t.__P.namespaceURI,32&e.__u?[n]:null,i,n??pe(e),!!(32&e.__u),a),s.__v=e.__v,s.__.__k[s.__i]=s,Gt(i,s,a),e.__e=e.__=null,s.__e!=n&&Kt(s)}}function Kt(t){if((t=t.__)!=null&&t.__c!=null)return t.__e=t.__c.base=null,t.__k.some(function(e){if(e!=null&&e.__e!=null)return t.__e=t.__c.base=e.__e}),Kt(t)}function Ht(t){(!t.__d&&(t.__d=!0)&&le.push(t)&&!Be.__r++||Nt!=I.debounceRendering)&&((Nt=I.debounceRendering)||qt)(Be)}function Be(){try{for(var t,e=1;le.length;)le.length>e&&le.sort(jt),t=le.shift(),e=le.length,Oi(t)}finally{le.length=Be.__r=0}}function Xt(t,e,n,i,a,s,o,l,p,d,f){var _,c,g,b,x,m,k=i&&i.__k||He,w=e.length;for(p=$i(n,e,k,p,w),_=0;_<w;_++)(g=n.__k[_])!=null&&(c=g.__i!=-1&&k[g.__i]||Ne,g.__i=_,m=bt(t,g,c,a,s,o,l,p,d,f),b=g.__e,g.ref&&c.ref!=g.ref&&(c.ref&&vt(c.ref,null,g),f.push(g.ref,g.__c||b,g)),x==null&&b!=null&&(x=b),4&g.__u?(p=Zt(g,p,t),c.__e&&(c.__e=null)):typeof g.type=="function"&&m!==void 0?p=m:b&&(p=b.nextSibling),g.__u&=-7);return n.__e=x,p}function $i(t,e,n,i,a){var s,o,l,p,d,f=n.length,_=f,c=0;for(t.__k=new Array(a),s=0;s<a;s++)(o=e[s])!=null&&typeof o!="boolean"&&typeof o!="function"?(typeof o=="string"||typeof o=="number"||typeof o=="bigint"||o.constructor==String?o=t.__k[s]=Oe(null,o,null,null,null):Ye(o)?o=t.__k[s]=Oe(F,{children:o},null,null,null):o.constructor===void 0&&o.__b>0?o=t.__k[s]=Oe(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):t.__k[s]=o,p=s+c,o.__=t,o.__b=t.__b+1,l=null,(d=o.__i=Ni(o,n,p,_))!=-1&&(_--,(l=n[d])&&(l.__u|=2)),l==null||l.__v==null?(d==-1&&(a>f?c--:a<f&&c++),typeof o.type!="function"&&(o.__u|=4)):d!=p&&(d==p-1?c--:d==p+1?c++:(d>p?c--:c++,o.__u|=4))):t.__k[s]=null;if(_)for(s=0;s<f;s++)(l=n[s])!=null&&(2&l.__u)==0&&(l.__e==i&&(i=pe(l)),en(l,l));return i}function Zt(t,e,n){var i,a;if(typeof t.type=="function"){for(i=t.__k,a=0;i&&a<i.length;a++)i[a]&&(i[a].__=t,e=Zt(i[a],e,n));return e}t.__e!=e&&(e&&t.type&&!e.parentNode&&(e=pe(t)),e=n.insertBefore(t.__e,e||null));do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function Ni(t,e,n,i){var a,s,o,l=t.key,p=t.type,d=e[n],f=d!=null&&(2&d.__u)==0;if(d===null&&l==null||f&&l==d.key&&p==d.type)return n;if(i>(f?1:0)){for(a=n-1,s=n+1;a>=0||s<e.length;)if((d=e[o=a>=0?a--:s++])!=null&&(2&d.__u)==0&&l==d.key&&p==d.type)return o}return-1}function Bt(t,e,n){e[0]=="-"?t.setProperty(e,n??""):t[e]=n==null?"":typeof n!="number"||Pi.test(e)?n:n+"px"}function Pe(t,e,n,i,a){var s,o;e:if(e=="style")if(typeof n=="string")t.style.cssText=n;else{if(typeof i=="string"&&(t.style.cssText=i=""),i)for(e in i)n&&e in n||Bt(t.style,e,"");if(n)for(e in n)i&&n[e]==i[e]||Bt(t.style,e,n[e])}else if(e[0]=="o"&&e[1]=="n")s=e!=(e=e.replace(Vt,"$1")),o=e.toLowerCase(),e=o in t||e=="onFocusOut"||e=="onFocusIn"?o.slice(2):e.slice(2),t.l||(t.l={}),t.l[e+s]=n,n?i?n[Se]=i[Se]:(n[Se]=_t,t.addEventListener(e,s?mt:gt,s)):t.removeEventListener(e,s?mt:gt,s);else{if(a=="http://www.w3.org/2000/svg")e=e.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(e!="width"&&e!="height"&&e!="href"&&e!="list"&&e!="form"&&e!="tabIndex"&&e!="download"&&e!="rowSpan"&&e!="colSpan"&&e!="role"&&e!="popover"&&e in t)try{t[e]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&e[4]!="-"?t.removeAttribute(e):t.setAttribute(e,e=="popover"&&n==1?"":n))}}function Wt(t){return function(e){if(this.l){var n=this.l[e.type+t];if(e[Ue]==null)e[Ue]=_t++;else if(e[Ue]<n[Se])return;return n(I.event?I.event(e):e)}}}function bt(t,e,n,i,a,s,o,l,p,d){var f,_,c,g,b,x,m,k,w,N,U,O,H,B,W,Z,v=e.type;if(e.constructor!==void 0)return null;128&n.__u&&(p=!!(32&n.__u),s=[l=e.__e=n.__e]),(f=I.__b)&&f(e);e:if(typeof v=="function"){_=o.length;try{if(w=e.props,N=v.prototype&&v.prototype.render,U=(f=v.contextType)&&i[f.__c],O=f?U?U.props.value:f.__:i,n.__c?k=(c=e.__c=n.__c).__=c.__E:(N?e.__c=c=new v(w,O):(e.__c=c=new $e(w,O),c.constructor=v,c.render=Bi),U&&U.sub(c),c.state||(c.state={}),c.__n=i,g=c.__d=!0,c.__h=[],c._sb=[]),N&&c.__s==null&&(c.__s=c.state),N&&v.getDerivedStateFromProps!=null&&(c.__s==c.state&&(c.__s=ae({},c.__s)),ae(c.__s,v.getDerivedStateFromProps(w,c.__s))),b=c.props,x=c.state,c.__v=e,g)N&&v.getDerivedStateFromProps==null&&c.componentWillMount!=null&&c.componentWillMount(),N&&c.componentDidMount!=null&&c.__h.push(c.componentDidMount);else{if(N&&v.getDerivedStateFromProps==null&&w!==b&&c.componentWillReceiveProps!=null&&c.componentWillReceiveProps(w,O),e.__v==n.__v||!c.__e&&c.shouldComponentUpdate!=null&&c.shouldComponentUpdate(w,c.__s,O)===!1){e.__v!=n.__v&&(c.props=w,c.state=c.__s,c.__d=!1),e.__e=n.__e,e.__k=n.__k,e.__k.some(function($){$&&($.__=e)}),He.push.apply(c.__h,c._sb),c._sb=[],c.__h.length&&o.push(c),l=pe(n);break e}c.componentWillUpdate!=null&&c.componentWillUpdate(w,c.__s,O),N&&c.componentDidUpdate!=null&&c.__h.push(function(){c.componentDidUpdate(b,x,m)})}if(c.context=O,c.props=w,c.__P=t,c.__e=!1,H=I.__r,B=0,N)c.state=c.__s,c.__d=!1,H&&H(e),f=c.render(c.props,c.state,c.context),He.push.apply(c.__h,c._sb),c._sb=[];else do c.__d=!1,H&&H(e),f=c.render(c.props,c.state,c.context),c.state=c.__s;while(c.__d&&++B<25);c.state=c.__s,c.getChildContext!=null&&(i=ae(ae({},i),c.getChildContext())),N&&!g&&c.getSnapshotBeforeUpdate!=null&&(m=c.getSnapshotBeforeUpdate(b,x)),W=f!=null&&f.type===F&&f.key==null?Qt(f.props.children):f,l=Xt(t,Ye(W)?W:[W],e,n,i,a,s,o,l,p,d),c.base=e.__e,e.__u&=-161,c.__h.length&&o.push(c),k&&(c.__E=c.__=null)}catch($){if(o.length=_,e.__v=null,p||s!=null){if($.then){for(e.__u|=p?160:128;l&&l.nodeType==8&&l.nextSibling;)l=l.nextSibling;s!=null&&(s[s.indexOf(l)]=null),e.__e=l}else if(s!=null)for(Z=s.length;Z--;)xt(s[Z])}else e.__e=n.__e;e.__k==null&&(e.__k=n.__k||[]),$.then||Jt(e),I.__e($,e,n)}}else s==null&&e.__v==n.__v?(e.__k=n.__k,e.__e=n.__e):l=e.__e=Hi(n.__e,e,n,i,a,s,o,p,d);return(f=I.diffed)&&f(e),128&e.__u?void 0:l}function Jt(t){t&&(t.__c&&(t.__c.__e=!0),t.__k&&t.__k.some(Jt))}function Gt(t,e,n){for(var i=0;i<n.length;i++)vt(n[i],n[++i],n[++i]);I.__c&&I.__c(e,t),t.some(function(a){try{t=a.__h,a.__h=[],t.some(function(s){s.call(a)})}catch(s){I.__e(s,a.__v)}})}function Qt(t){return typeof t!="object"||t==null||t.__b>0?t:Ye(t)?t.map(Qt):t.constructor!==void 0?null:ae({},t)}function Hi(t,e,n,i,a,s,o,l,p){var d,f,_,c,g,b,x,m=n.props||Ne,k=e.props,w=e.type;if(w=="svg"?a="http://www.w3.org/2000/svg":w=="math"?a="http://www.w3.org/1998/Math/MathML":a||(a="http://www.w3.org/1999/xhtml"),s!=null){for(d=0;d<s.length;d++)if((g=s[d])&&"setAttribute"in g==!!w&&(w?g.localName==w:g.nodeType==3)){t=g,s[d]=null;break}}if(t==null){if(w==null)return document.createTextNode(k);t=document.createElementNS(a,w,k.is&&k),l&&(I.__m&&I.__m(e,s),l=!1),s=null}if(w==null)m===k||l&&t.data==k||(t.data=k);else{if(s=w=="textarea"&&k.defaultValue!=null?null:s&&We.call(t.childNodes),!l&&s!=null)for(m={},d=0;d<t.attributes.length;d++)m[(g=t.attributes[d]).name]=g.value;for(d in m)g=m[d],d=="dangerouslySetInnerHTML"?_=g:d=="children"||d in k||d=="value"&&"defaultValue"in k||d=="checked"&&"defaultChecked"in k||Pe(t,d,null,g,a);for(d in k)g=k[d],d=="children"?c=g:d=="dangerouslySetInnerHTML"?f=g:d=="value"?b=g:d=="checked"?x=g:l&&typeof g!="function"||m[d]===g||Pe(t,d,g,m[d],a);if(f)l||_&&(f.__html==_.__html||f.__html==t.innerHTML)||(t.innerHTML=f.__html),e.__k=[];else if(_&&(t.innerHTML=""),Xt(e.type=="template"?t.content:t,Ye(c)?c:[c],e,n,i,w=="foreignObject"?"http://www.w3.org/1999/xhtml":a,s,o,s?s[0]:n.__k&&pe(n,0),l,p),s!=null)for(d=s.length;d--;)xt(s[d]);l&&w!="textarea"||(d="value",w=="progress"&&b==null?t.removeAttribute("value"):b!=null&&(b!==t[d]||w=="progress"&&!b||w=="option"&&b!=m[d])&&Pe(t,d,b,m[d],a),d="checked",x!=null&&x!=t[d]&&Pe(t,d,x,m[d],a))}return t}function vt(t,e,n){try{if(typeof t=="function"){var i=typeof t.__u=="function";i&&t.__u(),i&&e==null||(t.__u=t(e))}else t.current=e}catch(a){I.__e(a,n)}}function en(t,e,n){var i,a;if(I.unmount&&I.unmount(t),(i=t.ref)&&(i.current&&i.current!=t.__e||vt(i,null,e)),(i=t.__c)!=null){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(s){I.__e(s,e)}i.base=i.__P=i.__n=null}if(i=t.__k)for(a=0;a<i.length;a++)i[a]&&en(i[a],e,n||typeof t.type!="function");n||xt(t.__e),t.__c=t.__=t.__e=void 0}function Bi(t,e,n){return this.constructor(t,n)}function yt(t,e,n){var i,a,s,o;e==document&&(e=document.documentElement),I.__&&I.__(t,e),a=(i=typeof n=="function")?null:n&&n.__k||e.__k,s=[],o=[],bt(e,t=(!i&&n||e).__k=Ui(F,null,[t]),a||Ne,Ne,e.namespaceURI,!i&&n?[n]:a?null:e.firstChild?We.call(e.childNodes):null,s,!i&&n?n:a?a.__e:e.firstChild,i,o),Gt(s,t,o),t.props.children=null}We=He.slice,I={__e:function(t,e,n,i){for(var a,s,o;e=e.__;)if((a=e.__c)&&!a.__)try{if((s=a.constructor)&&s.getDerivedStateFromError!=null&&(a.setState(s.getDerivedStateFromError(t)),o=a.__d),a.componentDidCatch!=null&&(a.componentDidCatch(t,i||{}),o=a.__d),o)return a.__E=a}catch(l){t=l}throw t}},Yt=0,zi=function(t){return t!=null&&t.constructor===void 0},$e.prototype.setState=function(t,e){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=ae({},this.state),typeof t=="function"&&(t=t(ae({},n),this.props)),t&&ae(n,t),t!=null&&this.__v&&(e&&this._sb.push(e),Ht(this))},$e.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),Ht(this))},$e.prototype.render=F,le=[],qt=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,jt=function(t,e){return t.__v.__b-e.__v.__b},Be.__r=0,ft=Math.random().toString(8),Ue="__d"+ft,Se="__a"+ft,Vt=/(PointerCapture)$|Capture$/i,_t=0,gt=Wt(!1),mt=Wt(!0),Di=0;var me,R,kt,tn,Te=0,dn=[],z=I,nn=z.__b,an=z.__r,rn=z.diffed,sn=z.__c,on=z.unmount,ln=z.__;function je(t,e){z.__h&&z.__h(R,t,Te||e),Te=0;var n=R.__H||(R.__H={__:[],__h:[]});return t>=n.__.length&&n.__.push({}),n.__[t]}function C(t){return Te=1,Wi(un,t)}function Wi(t,e,n){var i=je(me++,2);if(i.t=t,!i.__c&&(i.__=[n?n(e):un(void 0,e),function(l){var p=i.__N?i.__N[0]:i.__[0],d=i.t(p,l);p!==d&&(i.__N=[d,i.__[1]],i.__c.setState({}))}],i.__c=R,!R.__f)){var a=function(l,p,d){if(!i.__c.__H)return!0;var f=!1,_=i.__c.props!==l;if(i.__c.__H.__.some(function(g){if(g.__N){f=!0;var b=g.__[0];g.__=g.__N,g.__N=void 0,b!==g.__[0]&&(_=!0)}}),s){var c=s.call(this,l,p,d);return f?c||_:c}return!f||_};R.__f=!0;var s=R.shouldComponentUpdate,o=R.componentWillUpdate;R.componentWillUpdate=function(l,p,d){if(this.__e){var f=s;s=void 0,a(l,p,d),s=f}o&&o.call(this,l,p,d)},R.shouldComponentUpdate=a}return i.__N||i.__}function L(t,e){var n=je(me++,3);!z.__s&&Ct(n.__H,e)&&(n.__=t,n.u=e,R.__H.__h.push(n))}function Ve(t,e){var n=je(me++,4);!z.__s&&Ct(n.__H,e)&&(n.__=t,n.u=e,R.__h.push(n))}function V(t){return Te=5,pn(function(){return{current:t}},[])}function pn(t,e){var n=je(me++,7);return Ct(n.__H,e)&&(n.__=t(),n.__H=e,n.__h=t),n.__}function Ae(t,e){return Te=8,pn(function(){return t},e)}function Yi(){for(var t;t=dn.shift();){var e=t.__H;if(t.__P&&e)try{e.__h.some(qe),e.__h.some(wt),e.__h=[]}catch(n){e.__h=[],z.__e(n,t.__v)}}}z.__b=function(t){R=null,nn&&nn(t)},z.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),ln&&ln(t,e)},z.__r=function(t){an&&an(t),me=0;var e=(R=t.__c).__H;e&&(kt===R?(e.__h=[],R.__h=[],e.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(e.__h.some(qe),e.__h.some(wt),e.__h=[],me=0)),kt=R},z.diffed=function(t){rn&&rn(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(dn.push(e)!==1&&tn===z.requestAnimationFrame||((tn=z.requestAnimationFrame)||qi)(Yi)),e.__H.__.some(function(n){n.u&&(n.__H=n.u,n.u=void 0)})),kt=R=null},z.__c=function(t,e){e.some(function(n){try{n.__h.some(qe),n.__h=n.__h.filter(function(i){return!i.__||wt(i)})}catch(i){e.some(function(a){a.__h&&(a.__h=[])}),e=[],z.__e(i,n.__v)}}),sn&&sn(t,e)},z.unmount=function(t){on&&on(t);var e,n=t.__c;n&&n.__H&&(n.__H.__.some(function(i){try{qe(i)}catch(a){e=a}}),n.__H=void 0,e&&z.__e(e,n.__v))};var cn=typeof requestAnimationFrame=="function";function qi(t){var e,n=function(){clearTimeout(i),cn&&cancelAnimationFrame(e),setTimeout(t)},i=setTimeout(n,35);cn&&(e=requestAnimationFrame(n))}function qe(t){var e=R,n=t.__c;typeof n=="function"&&(t.__c=void 0,n()),R=e}function wt(t){var e=R;t.__c=t.__(),R=e}function Ct(t,e){return!t||t.length!==e.length||e.some(function(n,i){return n!==t[i]})}function un(t,e){return typeof e=="function"?e(t):e}function fn(t){let e=t%100;if(e>=11&&e<=13)return`${t}th`;switch(t%10){case 1:return`${t}st`;case 2:return`${t}nd`;case 3:return`${t}rd`;default:return`${t}th`}}function Ke(t){let e=Math.max(0,Math.floor(t)),n=Math.floor(e/3600),i=Math.floor(e%3600/60),a=String(e%60).padStart(2,"0");return n?`${n}:${String(i).padStart(2,"0")}:${a}`:`${i}:${a}`}function hn(t){let e=[],n=/(\*\*[^*]+\*\*|`[^`]+`|\[[^\]]+\]\((https?:\/\/[^)\s]+)\)|https?:\/\/[^\s<>()]+[^\s<>().,;:!?'"]|\*[^*\s][^*]*\*)/g,i=0,a;for(;a=n.exec(t);){a.index>i&&e.push({t:"text",v:t.slice(i,a.index)});let s=a[0];s.startsWith("**")?e.push({t:"b",v:s.slice(2,-2)}):s.startsWith("`")?e.push({t:"code",v:s.slice(1,-1)}):s.startsWith("[")?e.push({t:"link",v:s.slice(1,s.indexOf("]")),href:a[2]}):s.startsWith("http")?e.push({t:"link",v:s,href:s}):e.push({t:"i",v:s.slice(1,-1)}),i=a.index+s.length}return i<t.length&&e.push({t:"text",v:t.slice(i)}),e}function gn(t){let e=[];for(let n of t.split(/\n{2,}/)){let i=n.split(`
41
+ `);i.length&&i.every(a=>/^\s*[-*•]\s+/.test(a))?e.push({t:"ul",items:i.map(a=>hn(a.replace(/^\s*[-*•]\s+/,"")))}):e.push({t:"p",parts:hn(n)})}return e}var ji={assistant:"Assistant",online:"Online",typing:"Typing\u2026",typingName:"{name} is typing",message:"Message",send:"Send",sending:"Sending\u2026",close:"Close",minimise:"Minimise",dismiss:"Dismiss",notNow:"Not now",newConversation:"Start a new conversation",chat:"Chat",chatWith:"Chat with {name}",call:"Call",callName:"Call {name}",callWith:"Call with {name}",startCall:"Start call",callAgain:"Call again",joinCall:"Join call",join:"Join",view:"View",onCall:"On call",backToCall:"Back to your call",backToCallWith:"Back to your call with {name}",callTime:"Call time",timeLeft:"{time} left",endCall:"End call",end:"End",mute:"Mute",unmute:"Unmute",muted:"You are muted",interrupt:"Interrupt",interruptName:"Interrupt {name}",connecting:"Connecting\u2026",joining:"Joining\u2026",speaking:"Speaking",thinking:"Thinking\u2026",listening:"Listening",you:"You: {text}",inLine:"{position} in line",lineLabel:"in line",inLineFor:"You're {position} in line for a call \xB7 {eta}",inLineToCall:"You are {position} in line to call {name}. Open",inLineOpen:"You are {position} in line. Open your call",inLineEta:"You are {position} in line, {eta}",onOtherCalls:"{name} is on other calls",yourTurn:"Your turn in {eta}. We'll chime when it's time.",yourTurnChat:"Your turn in {eta}. We'll chime when it's time, so feel free to keep chatting.",keepChatting:"Keep chatting",leaveLine:"Leave line",readyForYou:"{name} is ready for you",secondsToJoin:"{seconds}s to join",joinWithin:"Join within {seconds} seconds.",talkWith:"Talk with {name} in real time.",etaSoon:"less than a minute",etaMin:"about {n} min",etaHr:"about {n} hr",notSent:"Not sent \xB7 Retry",beforeYouCall:"Before you call {name}",leaveDetails:"Leave your details",confirmDetails:"Confirm your details",detailsWhy:"So the team can follow up, even if the line drops.",detailsTyped:"From what you typed. Check them and send.",reasonField:"Reason",reasonChoose:"Choose a reason",reasonOther:"Something else",reasonPlaceholder:"Tell us in a few words",reasonInferred:"I'll tell the team this is about",reasonFromConversation:"From your conversation",reasonFromPage:"From this page",change:"Change",skipAndCall:"Skip and call",optional:"optional",privacyPolicy:"Privacy policy",thanks:"Thanks. The team will be in touch.",thanksName:"Thanks, {name}. The team will be in touch.",sendFailed:"Could not send. Try again.",nameField:"Name",emailField:"Email",phoneField:"Phone",companyField:"Company",poweredBy:"Powered by {brand}",greetingDefault:"Hi, I'm {name}. How can I help you today?",endedTitle:"Call ended",endedBody:"Thanks for talking with {name}.",leftTitle:"You left the line",leftBody:"You can call again whenever you like.",missedTitle:"You missed your turn",missedBody:"{name} was ready, but the call wasn't joined in time.",stillBusyTitle:"Still busy",stillBusyBody:"Sorry for the wait. {name} is still on other calls. Chat is open meanwhile.",limitTitle:"Time is up",limitBody:"This call reached its time limit.",busyTitle:"All lines are busy",busyBody:"Try again in a few minutes, or keep chatting.",micTitle:"Microphone needed",micBody:"Allow the microphone in your browser to talk, or keep chatting.",silenceBody:"The line was quiet for a minute, so {name} hung up. Call again any time.",restingTitle:"Calls are resting",restingBody:"Calls are done for today. Chat is open.",unavailableTitle:"Calls are unavailable",unavailableBody:"Calls are not available right now. Chat is open.",droppedTitle:"The call dropped",droppedBody:"Something interrupted the call. Try again."},mn={},_n=!0;function xn(t){mn=t??{},_n=!t||!Object.keys(t).length}function h(t,e){let n=mn[t]??ji[t];if(e)for(let i in e)n=n.split(`{${i}}`).join(String(e[i]));return n}function ce(t){return _n?fn(t):String(t)}function Xe(t){if(t==null)return"";if(t<60)return h("etaSoon");let e=Math.round(t/60);return e<60?h("etaMin",{n:e}):h("etaHr",{n:Math.round(e/60)})}function bn(t,e){let n=(i,a)=>({title:h(i),body:h(a,{name:e})});switch(t){case"hangup":return n("endedTitle","endedBody");case"left":return n("leftTitle","leftBody");case"missed":return n("missedTitle","missedBody");case"timeout":return n("stillBusyTitle","stillBusyBody");case"limit":return n("limitTitle","limitBody");case"busy":return n("busyTitle","busyBody");case"mic-denied":return n("micTitle","micBody");case"silence":return n("endedTitle","silenceBody");case"daily_limit":return n("restingTitle","restingBody");case"credits":case"unavailable":return n("unavailableTitle","unavailableBody");default:return n("droppedTitle","droppedBody")}}var vn={cx:.5,cy:.12,span:.06};function kn(t,e,n){let i=t?.face?.eyes,a=t?.face?.chin;if(!i||!a||!e||!n)return vn;let s=(i.left.x+i.right.x)/2,o=(i.left.y+i.right.y)/2,l=(a.y-o)/n;return l>.005&&l<.5?{cx:s/e,cy:(o+a.y)/2/n,span:l}:vn}var Ze={faceFraction:.26,at:{x:.5,y:.5}},wn={faceFraction:.14,at:{x:.5,y:.34},keepCrown:!0},Cn={faceFraction:.16,at:{x:.5,y:.22},keepCrown:!0},Sn={fit:"height"},Vi=1.8,yn=.04;function Tn(t,e,n,i,a){if("fit"in a){let d=i*e;return{width:d,height:i,left:n/2-t.cx*d,top:0}}let s=i*a.faceFraction/t.span,o=s*e,l=i*a.at.y-t.cy*s,p=l+(t.cy-t.span*Vi)*s;return a.keepCrown&&p<i*yn&&(l+=i*yn-p),{width:o,height:s,left:n*a.at.x-t.cx*o,top:l}}var An=/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/,Ki=/\+?\d[\d\s().-]{5,}\d/g,Xi=/\b(?:my name is|i am|i'm|im|this is|name\s*[:-])\s+([A-Za-z][A-Za-z'’-]+(?:\s+[A-Za-z][A-Za-z'’-]+)?)/i,Zi=new Set(["interested","looking","from","with","here","trying","not","a","an","the","just","also","happy","keen","curious","calling","sure","fine","good","okay","ok"]);function Mn(t){let e={},n=t.match(An)?.[0];n&&(e.email=n.replace(/[.,;:]+$/,""));for(let a of t.replace(An," ").matchAll(Ki)){let s=a[0].replace(/\D/g,"");if(s.length>=7&&s.length<=15){e.phone=a[0].trim();break}}if(!e.email&&!e.phone)return null;let i=t.match(Xi)?.[1];if(i){let a=i.split(/\s+/).filter(o=>!Zi.has(o.toLowerCase())),s=[];for(let o of a){if(["and","here","at","from"].includes(o.toLowerCase()))break;s.push(o)}s.length&&s[0].length>1&&(e.name=s.map(o=>o[0].toUpperCase()+o.slice(1)).join(" "))}return e}var Ji=0;function r(t,e,n,i,a,s){e||(e={});var o,l,p=e;if("ref"in p)for(l in p={},e)l=="ref"?o=e[l]:p[l]=e[l];var d={type:t,props:p,key:n,ref:o,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--Ji,__i:-1,__u:0,__source:a,__self:s};if(typeof t=="function"&&(o=t.defaultProps))for(l in o)p[l]===void 0&&(p[l]=o[l]);return I.vnode&&I.vnode(d),d}var ee=(t,e)=>r("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"1.9","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",focusable:"false",children:e}),Me=({size:t=20})=>ee(t,r("path",{d:"M4 5.5A2.5 2.5 0 0 1 6.5 3h11A2.5 2.5 0 0 1 20 5.5v8a2.5 2.5 0 0 1-2.5 2.5H10l-4.2 3.6a.5.5 0 0 1-.8-.4V16h0A2.5 2.5 0 0 1 4 13.5z"})),_e=({size:t=20})=>ee(t,r("path",{d:"M5.2 3.5h3l1.6 4.2-2 1.4a12 12 0 0 0 7.1 7.1l1.4-2 4.2 1.6v3a1.7 1.7 0 0 1-1.8 1.7A16.6 16.6 0 0 1 3.5 5.3 1.7 1.7 0 0 1 5.2 3.5z"})),En=({size:t=22})=>ee(t,r("path",{d:"M3 13.6c5-4.4 13-4.4 18 0l-1.7 2.6-3.6-1.3v-2.6a11 11 0 0 0-7.4 0v2.6l-3.6 1.3z"})),In=({size:t=20})=>ee(t,r(F,{children:[r("rect",{x:"9",y:"3",width:"6",height:"11",rx:"3"}),r("path",{d:"M5.5 11a6.5 6.5 0 0 0 13 0M12 17.5V21"})]})),Fn=({size:t=20})=>ee(t,r(F,{children:[r("path",{d:"M9 9v2a3 3 0 0 0 5.1 2.1M15 9.4V6a3 3 0 0 0-5.7-1.3"}),r("path",{d:"M5.5 11a6.5 6.5 0 0 0 10.6 5M18.4 12.5a6.5 6.5 0 0 0 .1-1.5M12 17.5V21M3 3l18 18"})]})),Je=({size:t=18})=>ee(t,r("path",{d:"M6 6l12 12M18 6L6 18"})),Ln=({size:t=18})=>ee(t,r("path",{d:"M12 19V5M5.5 11.5L12 5l6.5 6.5"})),Rn=({size:t=18})=>ee(t,r("path",{d:"M15 5l-7 7 7 7"}));var zn=({size:t=18})=>ee(t,r("path",{d:"M12 4H6.5A2.5 2.5 0 0 0 4 6.5v11A2.5 2.5 0 0 0 6.5 20h11a2.5 2.5 0 0 0 2.5-2.5V12M17.5 3.5a2.1 2.1 0 0 1 3 3L13 14l-4 1 1-4z"})),Dn=({size:t=14})=>ee(t,r("path",{d:"M5 12.5l4.2 4.2L19 7"})),Pn=({size:t=14})=>ee(t,r("path",{d:"M4 12a8 8 0 1 0 2.3-5.6M4 4v4h4"}));var St={current:null};function Gi(t){return t?t.speaking?"speaking":t.agentState==="thinking"?"reasoning":t.agentState==="listening"||t.phase==="live"?"listening":"idle":"idle"}function Un({client:t,call:e,state:n,src:i,onStatus:a}){let s=V(null),[o,l]=C(!1),p=V(!1),d=(()=>{try{return new URL(i).origin}catch{return null}})(),f=(c,g)=>{let b=s.current?.contentWindow;b&&d&&b.postMessage({cx:"face",...c},d,g??[])};L(()=>{if(!d){a("unavailable");return}let c=!1,g=x=>{if(x.source!==s.current?.contentWindow||x.origin!==d)return;let m=x.data;m?.cx==="face"&&(m.type==="loaded"?(p.current=!0,l(!0),t.videoAvatar().then(k=>{c||(k?f({type:"init",avatar:k}):a("unavailable"))}).catch(()=>!c&&a("unavailable"))):m.type==="ready"?(St.current=typeof m.faceEmotion=="string"?m.faceEmotion:null,a("ready")):m.type==="unavailable"&&a("unavailable"))};window.addEventListener("message",g);let b=setTimeout(()=>!c&&!p.current&&a("unavailable"),15e3);return()=>{c=!0,clearTimeout(b),window.removeEventListener("message",g)}},[t,d]);let _=Gi(n);return L(()=>{o&&f({type:"state",state:_})},[_,o]),L(()=>{if(!e||!o)return;let c=[e.on("face",({corr:x,payload:m})=>f({type:"batch",corr:x,payload:m},[m.buffer])),e.on("line",({corr:x,event:m})=>{f(m==="audible"?{type:"audible",corr:x,ms:e.audible()?.ms??0}:{type:"end",corr:x})})],g=0,b=()=>{let x=e.audible();x&&f({type:"clock",corr:x.corr,ms:x.ms}),g=requestAnimationFrame(b)};return g=requestAnimationFrame(b),()=>{c.forEach(x=>x()),cancelAnimationFrame(g)}},[e,o]),d?r("iframe",{ref:s,class:"face-frame",src:i,title:"","aria-hidden":"true",tabIndex:-1,allow:"autoplay",sandbox:"allow-scripts allow-same-origin",referrerpolicy:"strict-origin"}):null}function Qi(){if(typeof document>"u")return!1;let t=navigator.userAgent;return/Safari\//.test(t)&&!/(Chrome|Chromium|Edg|OPR|Firefox)\//.test(t)?!1:document.createElement("video").canPlayType('video/webm; codecs="vp9"')!==""}var ea=()=>typeof matchMedia<"u"&&matchMedia("(prefers-reduced-motion: reduce)").matches;function Ee({agent:t,shot:e,talking:n=!1,still:i=!1,full:a=!1,class:s}){let o=V(null),[l,p]=C({w:0,h:0}),[d,f]=C(null),[_,c]=C({}),[g,b]=C({}),x=t.video,m=(S,D,ie)=>!a&&S&&!g[ie]?S:D,k=x?.anchor?.alphaUrl??x?.anchor?.url??null,w=m(x?.anchor?.smallUrl,k,"anchor"),N=w!==k,U=!i&&!ea()&&Qi(),O=x?.clips.idle,H=x?.clips.talking??O,B=m(O?.smallUrl,O?.alphaUrl??null,"idle"),W=m(H?.smallUrl,H?.alphaUrl??null,"talk")??B,[Z,v]=C(a);if(L(()=>{n&&v(!0)},[n]),Ve(()=>{let S=o.current;if(!S)return;let D=()=>p({w:S.clientWidth,h:S.clientHeight});if(D(),typeof ResizeObserver>"u")return;let ie=new ResizeObserver(D);return ie.observe(S),()=>ie.disconnect()},[]),!x||!w)return r("div",{ref:o,class:`portrait portrait--initial ${s??""}`,"aria-hidden":"true",children:r("span",{children:(t.name||"?").slice(0,1).toUpperCase()})});let J=(x.anchor?.width&&x.anchor?.height?{w:x.anchor.width,h:x.anchor.height}:null)??(d&&!N?d:null),se=kn(x,J?.w??0,J?.h??0),Y=l.w&&l.h&&J?Tn(se,J.w/J.h,l.w,l.h,e):null,oe=Y?{width:`${Y.width}px`,height:`${Y.height}px`,left:`${Y.left}px`,top:`${Y.top}px`}:{},K=!!Y&&U&&!!B&&!!_.idle,ne=!!Y&&U&&!!W&&W!==B&&!!_.talk&&n,M=!!Y&&(!!d||K);return r("div",{ref:o,class:`portrait ${s??""}`,"aria-hidden":"true",children:[r("img",{class:"portrait__media",src:w,alt:"",draggable:!1,style:{...oe,opacity:Y&&d&&!K?1:0},onLoad:S=>{let D=S.currentTarget;f({w:D.naturalWidth,h:D.naturalHeight})},onError:()=>N&&b(S=>({...S,anchor:!0}))}),U&&B?r(On,{src:B,style:oe,visible:K&&!ne,onReady:()=>c(S=>({...S,idle:!0})),onFail:()=>b(S=>({...S,idle:!0}))}):null,U&&Z&&W&&W!==B?r(On,{src:W,style:oe,visible:ne,onReady:()=>c(S=>({...S,talk:!0})),onFail:()=>b(S=>({...S,talk:!0}))}):null,r("span",{class:`portrait__sparkle${M?" is-done":""}`,children:[r("i",{}),r("i",{}),r("i",{})]})]})}function On({src:t,style:e,visible:n,onReady:i,onFail:a}){let s=V(null);return L(()=>{let o=s.current;o&&(n?o.play().catch(()=>{}):o.pause())},[n]),r("video",{ref:s,class:"portrait__media portrait__clip",src:t,muted:!0,loop:!0,playsInline:!0,preload:"auto",style:{...e,opacity:n?1:0},onLoadedData:i,onError:a})}var Tt="cxyz:greeted",$n="cxyz:introduced";function Ie(t,e){try{return e!==void 0&&localStorage.setItem(t,e),localStorage.getItem(t)}catch{return null}}function ta(){try{let t=window.AudioContext??window.webkitAudioContext,e=new t,n=e.currentTime;[660,880].forEach((i,a)=>{let s=e.createOscillator(),o=e.createGain();s.type="sine",s.frequency.value=i,o.gain.setValueAtTime(0,n+a*.16),o.gain.linearRampToValueAtTime(.18,n+a*.16+.02),o.gain.exponentialRampToValueAtTime(1e-4,n+a*.16+.5),s.connect(o).connect(e.destination),s.start(n+a*.16),s.stop(n+a*.16+.55)}),setTimeout(()=>{e.close()},1200)}catch{}}function na(t){let[e,n]=C(t.chat.messages),[i,a]=C(t.chat.isBusy);return L(()=>{let s=t.chat.on("messages",n),o=t.chat.on("busy",a);return()=>{s(),o()}},[t]),{messages:e,busy:i}}function ia(t){let[e,n]=C(t.call),[i,a]=C(t.call?.state??null),[s,o]=C([]);return L(()=>t.on("call",l=>l&&n(l)),[t]),L(()=>{if(!e)return;a(e.state),o([]);let l=[e.on("state",a),e.on("caption",p=>o(d=>[...d.filter(f=>f.id!==p.id),p].slice(-4))),e.on("captionRemoved",p=>o(d=>d.filter(f=>f.id!==p)))];return()=>l.forEach(p=>p())},[e]),{call:e,state:i,captions:s,reset:()=>n(null)}}function aa(t,e){let[n,i]=C(Date.now());return L(()=>{if(!e)return;let a=setInterval(()=>i(Date.now()),1e3);return()=>clearInterval(a)},[e]),t?Math.max(0,(n-t)/1e3):0}function ra(t,e,n){L(()=>{if(!t||!n)return;let i=0,a=0,s=()=>{let o=t.voiceLevel();a=a*.7+o*.3,e.current?.style.setProperty("--cx-lvl",a.toFixed(3)),i=requestAnimationFrame(s)};return i=requestAnimationFrame(s),()=>cancelAnimationFrame(i)},[t,n,e])}function Nn({parts:t}){return r(F,{children:t.map((e,n)=>e.t==="b"?r("strong",{children:e.v},n):e.t==="i"?r("em",{children:e.v},n):e.t==="code"?r("code",{children:e.v},n):e.t==="link"?r("a",{href:e.href,target:"_blank",rel:"noopener noreferrer nofollow",children:e.v},n):e.v.split(`
42
+ `).map((i,a,s)=>r(F,{children:[i,a<s.length-1?r("br",{}):null]},`${n}.${a}`)))})}var sa={name:{label:"nameField",type:"text",auto:"name"},email:{label:"emailField",type:"email",auto:"email"},phone:{label:"phoneField",type:"tel",auto:"tel"},company:{label:"companyField",type:"text",auto:"organization"},reason:{label:"reasonField",type:"text",auto:"off"}};function oa(){try{let t=new URLSearchParams(location.search).get("reason")??new URLSearchParams(location.search).get("intent");return t&&t.trim()?t.trim().slice(0,120):(document.querySelector("character-xyz")?.getAttribute("data-reason")??"").trim().slice(0,120)}catch{return""}}function la({form:t,title:e,note:n,onSend:i,onSkip:a,skipLabel:s,initial:o,hasHistory:l}){let[p,d]=C(()=>({...o??{}})),f=t.required??["name","email"],_=M=>f.includes(M),c=t.reasonOptions??[],g=t.fields.includes("reason"),b=g&&!l?oa():"",x=t.reasonDefault||b||"",[m,k]=C(x),[w,N]=C(t.reasonDefault?t.reasonSource??"conversation":b?"cta":""),[U,O]=C(g&&!x),[H,B]=C(!1),[W,Z]=C(""),[v,$]=C({}),[J,se]=C(null),[Y,oe]=C(!1),K=V(null),ne=V(null);return L(()=>{setTimeout(()=>K.current?.focus({preventScroll:!0}),80)},[]),Ve(()=>{let M=ne.current?.closest(".log");if(!M)return;let S=M.style.scrollBehavior;M.style.scrollBehavior="auto",M.scrollTop=M.scrollHeight,M.style.scrollBehavior=S},[U,H]),r("form",{class:"card",part:"details",ref:ne,onSubmit:async M=>{M.preventDefault(),oe(!0),$({}),se(null);try{let S=(H?W:m).trim();await i({name:p.name??"",email:p.email??"",...p.phone?{phone:p.phone}:{},...p.company?{company:p.company}:{},...g&&S?{reason:S}:{}})}catch(S){let D=S.fields??{};Object.keys(D).length?$(D):se(S.message||h("sendFailed"))}finally{oe(!1)}},children:[r("div",{class:"card__title",children:e}),n?r("div",{class:"card__note",children:n}):null,t.fields.map((M,S)=>{if(M==="reason")return r("div",{class:"card__field card__field--reason",children:[!U&&m?null:r("span",{class:"card__reason-label",children:t.reasonLabel||h("reasonField")}),!U&&m?r(F,{children:[r("div",{class:"card__reason-line",children:[r("span",{class:"card__reason-said",children:h("reasonInferred")}),r("strong",{children:m}),r("button",{type:"button",class:"card__change",onClick:()=>O(!0),children:h("change")})]}),w?r("span",{class:"card__reason-src",children:w==="cta"?h("reasonFromPage"):w==="conversation"?h("reasonFromConversation"):null}):null]}):r("div",{class:"card__reason-edit",children:[c.length?r("div",{class:"card__chips",role:"group","aria-label":t.reasonLabel||h("reasonField"),children:[c.map(G=>r("button",{type:"button",class:"card__chip","aria-pressed":!H&&m===G,onClick:()=>{k(G),B(!1),N("user"),O(!1)},children:G},G)),r("button",{type:"button",class:"card__chip","aria-pressed":H,onClick:()=>{B(!0),k("")},children:h("reasonOther")})]}):null,H||!c.length?r("input",{type:"text",maxLength:500,placeholder:h("reasonPlaceholder"),value:W,onInput:G=>Z(G.currentTarget.value)}):null]}),v.reason?r("em",{children:v.reason}):null]},M);let D=sa[M],ie=h(D.label);return r("label",{class:"card__field",children:[r("span",{children:[ie,_(M)?null:r("i",{children:[" \xB7 ",h("optional")]})]}),r("input",{ref:S===0?K:void 0,type:D.type,autocomplete:D.auto,required:_(M),maxLength:M==="email"?254:120,value:p[M]??"","aria-invalid":v[M]?"true":void 0,onInput:G=>d(Qe=>({...Qe,[M]:G.currentTarget.value}))}),v[M]?r("em",{children:v[M]}):null]},M)}),r("div",{class:"card__consent",children:[t.consent,t.privacyUrl?r(F,{children:[" ",r("a",{href:t.privacyUrl,target:"_blank",rel:"noopener noreferrer",children:h("privacyPolicy")})]}):null]}),J?r("div",{class:"card__failed",children:J}):null,r("div",{class:"card__actions",children:[r("button",{type:"submit",class:"btn btn--accent btn--sm",disabled:Y,children:Y?h("sending"):h("send")}),r("button",{type:"button",class:"btn btn--ghost btn--sm",onClick:a,disabled:Y,children:s})]})]})}function At({items:t,onPick:e,children:n}){return!t.length&&!n?null:r("div",{class:"chips chips--start",part:"suggestions",children:[t.map(i=>r("button",{class:"chip",onClick:()=>e(i),children:i},i)),n]})}function Hn({text:t}){return r(F,{children:gn(t).map((e,n)=>e.t==="ul"?r("ul",{children:e.items.map((i,a)=>r("li",{children:r(Nn,{parts:i})},a))},n):r("p",{children:r(Nn,{parts:e.parts})},n))})}function Bn({client:t,config:e,bind:n,onView:i}){let a=t.agent,s=t.features,o=e.showChat&&s.chat,l=e.showCall&&s.call,[p,d]=C(e.open?o?"chat":"call":"closed"),[f,_]=C(!1),[c,g]=C(!1),{messages:b,busy:x}=na(t),{call:m,state:k,captions:w,reset:N}=ia(t),[U,O]=C(""),H=V(null),B=V(null),W=V(null),Z=e.subtitle??a.tagline,v=a.name||h("assistant"),[$,J]=C(null);L(()=>{if(!o)return;let u=!0;return t.opening().then(T=>{u&&(xn(T?.strings),J(T))}),()=>{u=!1}},[t,o]);let se=e.greeting||$?.teaser||"",Y=e.suggestions.length?e.suggestions:$?.suggestions??[],oe=$?.greeting||h("greetingDefault",{name:v}),[K,ne]=C("loading"),[M,S]=C(!1),[D,ie]=C(null),[G,Qe]=C(""),[et,tt]=C(null),[nt,it]=C(null),te=Ae(u=>{d(u),i(u)},[i]),ue=Ae(()=>{_(!0),setTimeout(()=>{_(!1),te("closed")},200)},[te]),xe=Ae(async()=>{try{let u=await t.chat.load();ne(T=>T==="loading"?u.length?u.length:"empty":T)}catch{ne(u=>u==="loading"?"empty":u)}},[t]),Q=Ae((u=o?"chat":"call")=>{g(!1),Ie(Tt,"1"),te(u),u==="chat"&&xe()},[o,te,xe]);L(()=>n({open:Q,close:ue}),[n,Q,ue]),L(()=>t.on("siteEvent",u=>{u.openChat&&Q("chat")}),[t,Q]),L(()=>{e.open&&o&&xe()},[xe,e.open,o]),L(()=>{if(!se||Ie(Tt))return;let u=setTimeout(()=>g(!0),e.greetingDelay*1e3);return()=>clearTimeout(u)},[se,e.greetingDelay]),L(()=>{if(p!=="chat"||M||K==="loading")return;let u=setTimeout(()=>S(!0),700);return()=>clearTimeout(u)},[p,M,K]);let[at,Vn]=C(()=>!Ie($n));L(()=>{if(!at)return;let u=setTimeout(()=>{Vn(!1),Ie($n,"1")},5e3);return()=>clearTimeout(u)},[at]),L(()=>{if(p==="closed")return;let u=T=>{T.key==="Escape"&&ue()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[p,ue]),L(()=>{let u=H.current;u&&(u.scrollTop=u.scrollHeight)},[b,p,k?.phase]),L(()=>{p==="chat"&&setTimeout(()=>B.current?.focus({preventScroll:!0}),60)},[p]);let be=e.face&&!!a.video,[Fe,Kn]=C("loading"),A=k?.phase??"idle";L(()=>{if(!(A!=="ready"||!m)){if(ta(),p==="call"){if(!be||Fe!=="loading"){m.accept();return}let u=setTimeout(()=>m.accept(),3e3);return()=>clearTimeout(u)}if(typeof document<"u"&&document.hidden){let u=document.title;document.title=`\u25CF ${v} is ready for you`;let T=()=>{document.title=u,document.removeEventListener("visibilitychange",T)};document.addEventListener("visibilitychange",T)}}},[A,m,p,v,be,Fe]);let It=A==="live"||A==="connecting";ra(m,W,It&&p==="call");let Le=aa(k?.startedAt??null,A==="live"),rt=ca(m,k?.position??1),st=()=>{let u=$?.details;if(u&&!D&&o){tt(u),te("chat"),xe();return}ot()},Ft=(u,T="")=>{ie(u),Qe(T),it(null);let he=!!et;tt(null),he&&ot()},Xn=async u=>{await t.sendDetails(u),Ft("sent",u.name.trim().split(/\s+/)[0]??"")},Zn=()=>{t.declineDetails().catch(()=>{}),Ft("skipped")},Jn=async()=>{try{await t.chat.reset()}catch{return}ne("empty"),S(!1),ie(null),tt(null),it(null),O(""),J(await t.opening(!0))},ot=async()=>{te("call");try{await t.startCall({autoAccept:!1,...be?{face:{emotion:()=>St.current}}:{}})}catch{}},lt=[...b].reverse().find(u=>u.detailsForm||u.askDetails)?.detailsForm??[...b].reverse().find(u=>u.askDetails)?.askDetails??$?.details??null,ve=async u=>{let T=u.trim();if(!T||x)return;let he=lt&&D!=="sent"?Mn(T):null;he&&lt&&it({form:lt,values:he}),O(""),B.current&&(B.current.style.height="");try{await t.chat.send(T)}catch{}},Re=b[b.length-1],Lt=Re?.role==="agent"&&!Re.streaming?Re.askDetails:void 0,q=et?{form:et,kind:"call"}:nt&&D!=="sent"&&!x?{form:nt.form,kind:"typed",initial:nt.values}:Lt&&!D?{form:Lt,kind:"invited"}:null;if(p==="closed"){let u=A==="queued"||A==="ready"||A==="live"||A==="connecting";return r("div",{class:`dock dock--${e.display}`,part:"launcher",children:[c?r("div",{class:"greeting",part:"greeting",role:"status",onClick:()=>Q(),children:[se,r("button",{class:"greeting__close","aria-label":h("dismiss"),onClick:T=>{T.stopPropagation(),g(!1),Ie(Tt,"1")},children:r(Je,{size:14})})]}):null,r("button",{class:`presence presence--${e.display} ${u?"presence--live":""}`,part:"presence","aria-label":u?A==="queued"?h("inLineToCall",{position:ce(k?.position??1),name:v}):h("backToCallWith",{name:v}):o?h("chatWith",{name:v}):h("callName",{name:v}),onClick:()=>Q(u||!o?"call":"chat"),children:[e.display==="bubble"?r("span",{class:"presence__ring"}):null,r("span",{class:"presence__face",children:r(Ee,{agent:a,shot:e.display==="full"?Sn:e.display==="half"?Cn:Ze})}),r("span",{class:"presence__dot"}),t.mode==="test"?r("span",{class:"testmode",title:"Test mode: this key only works on development sites",children:"TEST"}):null,A==="queued"?r("span",{class:"presence__badge","aria-hidden":"true",children:k?.position??1}):null,e.launcher==="bubble"&&!c?r("span",{class:"presence__label","aria-hidden":"true",children:u?A==="queued"?h("inLine",{position:ce(k?.position??1)}):h("backToCall"):o?h("chatWith",{name:v}):h("callName",{name:v})}):null]}),e.launcher==="bubble"?null:r("div",{class:`acts ${at?"acts--labelled":""}`,part:"actions",children:[o?r("button",{class:"act","aria-label":h("chatWith",{name:v}),onClick:()=>Q("chat"),children:[r(Me,{size:20}),r("span",{class:"act__label","aria-hidden":"true",children:h("chat")})]}):null,l?r("button",{class:`act act--call ${u?"act--live":""}`,"aria-label":u?A==="queued"?h("inLineOpen",{position:ce(k?.position??1)}):h("backToCall"):h("callName",{name:v}),onClick:()=>u?Q("call"):st(),children:[r(_e,{size:20}),r("span",{class:"act__label","aria-hidden":"true",children:u?A==="queued"?h("inLine",{position:ce(k?.position??1)}):h("onCall"):h("call")}),A==="queued"?r("span",{class:"act__badge","aria-hidden":"true",children:k?.position??1}):null]}):null]})]})}let Gn=r("div",{class:"head",part:"header",children:[r("div",{class:"head__face",children:r(Ee,{agent:a,shot:Ze})}),r("div",{class:"head__who",children:[r("div",{class:"head__name",children:v}),r("div",{class:"head__sub",children:[r("i",{}),x?h("typing"):Z||h("online")]})]}),p==="chat"&&b.length>0&&!x?r("button",{class:"icon-btn","aria-label":h("newConversation"),title:h("newConversation"),onClick:()=>{Jn()},children:r(zn,{})}):null,l&&p==="chat"?r("button",{class:"icon-btn icon-btn--accent","aria-label":h("callName",{name:v}),title:h("callName",{name:v}),onClick:()=>m&&A!=="ended"?te("call"):st(),children:r(_e,{size:18})}):null,r("button",{class:"icon-btn","aria-label":h("close"),onClick:ue,children:r(Je,{})})]});if(p==="chat")return r("div",{class:`panel ${f?"is-closing":""}`,part:"panel",role:"dialog","aria-label":h("chatWith",{name:v}),children:[Gn,m&&(A==="queued"||A==="ready")?r("div",{class:"banner",part:"banner",role:"status",children:[r("div",{class:"banner__text",children:A==="queued"?r(F,{children:h("inLineFor",{position:ce(k?.position??1),eta:Xe(k?.etaSeconds??null)})}):r(F,{children:[r("b",{children:h("readyForYou",{name:v})})," \xB7 ",h("secondsToJoin",{seconds:k?.holdSeconds??30})]})}),A==="ready"?r("button",{class:"btn btn--accent btn--glow",onClick:()=>{m.accept(),te("call")},children:h("join")}):r("button",{class:"btn",onClick:()=>te("call"),children:h("view")})]}):null,r("div",{class:"log",ref:H,role:"log","aria-live":"polite","aria-relevant":"additions",children:[b.length===0?r(F,{children:[r("div",{class:"empty",children:[r("div",{class:"empty__face",children:r(Ee,{agent:a,shot:Ze})}),r("div",{class:"empty__title",children:v}),Z?r("div",{class:"empty__body",children:Z}):null]}),K==="loading"?null:M?r(F,{children:[r("div",{class:"msg msg--agent",part:"message message-agent",children:r(Hn,{text:oe})}),q?null:r(At,{items:Y,onPick:u=>{ve(u)},children:l?r("button",{class:"chip chip--call",onClick:()=>m&&A!=="ended"?te("call"):st(),children:[r(_e,{size:14})," ",h("callName",{name:v})]}):null})]}):r("div",{class:"msg msg--agent typing","aria-label":h("typingName",{name:v}),children:[r("i",{}),r("i",{}),r("i",{})]})]}):null,b.map(u=>u.role==="event"?r("div",{class:"event",part:"event message message-event",children:[r("span",{class:"event__dot","aria-hidden":"true"}),u.text]},u.id):u.role==="agent"&&u.streaming&&!u.text?r("div",{class:"msg msg--agent typing","aria-label":h("typingName",{name:v}),children:[r("i",{}),r("i",{}),r("i",{})]},u.id):r(F,{children:[r("div",{class:`msg msg--${u.role} ${u.failed?"msg--failed":""} ${u.streaming?"caret":""}`,part:`message message-${u.role}`,children:u.role==="agent"?r(Hn,{text:u.text}):u.text}),u===b[b.length-1]&&u.role==="agent"&&!u.streaming&&!x&&!q&&u.suggestions?.length?r(At,{items:u.suggestions,onPick:T=>{ve(T)}}):null,u.failed&&u.error?r("div",{class:"msg__why",role:"status",children:u.error}):u.failed?r("button",{class:"msg__retry",onClick:()=>{t.chat.retry(u.id).catch(()=>{})},children:[r(Pn,{})," ",h("notSent")]}):null]},u.id)),typeof K=="number"&&b.length===K&&$?.welcomeBack?r(F,{children:[r("div",{class:"msg msg--agent",part:"message message-agent",children:$.welcomeBack}),q?null:r(At,{items:Y,onPick:u=>{ve(u)}})]}):null,q?r(la,{form:q.form,initial:q.initial,title:q.kind==="call"?h("beforeYouCall",{name:v}):q.kind==="typed"?h("confirmDetails"):h("leaveDetails"),note:q.kind==="call"?h("detailsWhy"):q.kind==="typed"?h("detailsTyped"):null,onSend:Xn,onSkip:Zn,skipLabel:q.kind==="call"?h("skipAndCall"):h("notNow"),hasHistory:b.length>0},q.kind==="invited"?Re?.id:q.kind):D==="sent"?r("div",{class:"notice",role:"status",children:[r(Dn,{})," ",G?h("thanksName",{name:G}):h("thanks")]}):null]}),r("form",{class:"compose",part:"composer",onSubmit:u=>{u.preventDefault(),ve(U)},children:r("div",{class:"compose__box",children:[r("textarea",{ref:B,rows:1,value:U,maxLength:2e3,placeholder:e.placeholder===de.placeholder?h("message"):e.placeholder,"aria-label":h("message"),onInput:u=>{let T=u.currentTarget;O(T.value),T.style.height="auto",T.style.height=`${Math.min(120,T.scrollHeight)}px`},onKeyDown:u=>{u.key==="Enter"&&!u.shiftKey&&!u.isComposing&&(u.preventDefault(),ve(U))}}),r("button",{class:"send",type:"submit","aria-label":h("send"),disabled:!U.trim()||x,children:r(Ln,{})})]})}),e.branding?r("div",{class:"foot",children:h("poweredBy").split("{brand}").map((u,T)=>r(F,{children:[T?r("a",{href:"https://character.xyz",target:"_blank",rel:"noopener noreferrer",children:"Character XYZ"}):null,u]},T))}):null]});let E=k,ct=E?.position??1,Qn=rt>1?(rt-ct)/(rt-1):0,dt=74,Rt=2*Math.PI*dt,ye=E?.maxSeconds?E.maxSeconds-Le:null,ei=E?.agentState??"idle",ti=E?.speaking?h("speaking"):ei==="thinking"?h("thinking"):h("listening"),ni=!E||A==="ended"||A==="idle",pt=bn(E?.endReason??null,v);return r("div",{class:`panel ${f?"is-closing":""}`,part:"panel",role:"dialog","aria-label":h("callWith",{name:v}),children:r("div",{class:`stage ${be&&Fe==="ready"?"stage--face":""}`,ref:W,children:[r("div",{class:"stage__figure",style:{opacity:A==="queued"?.35:1,transition:"opacity .6s"},children:[r(Ee,{agent:a,shot:wn,talking:!!E?.speaking,full:!0}),be?r("div",{class:`stage__face ${Fe==="ready"?"is-ready":""}`,children:r(Un,{client:t,call:m,state:E,src:e.faceUrl,onStatus:Kn})}):null]}),It?r("div",{class:"voice"}):null,r("div",{class:"stage__veil"}),r("div",{class:"stage__top",children:[A==="live"?r("span",{class:`badge ${ye!=null&&ye<=60?"badge--warn":""}`,role:"timer","aria-label":h("callTime"),children:[r("i",{}),ye!=null&&ye<=60?h("timeLeft",{time:Ke(ye)}):Ke(Le)]}):r("span",{}),r("div",{style:{display:"flex",gap:"6px"},children:[o?r("button",{class:"icon-btn","aria-label":h("chat"),title:h("chat"),onClick:()=>Q("chat"),children:r(Me,{size:18})}):null,r("button",{class:"icon-btn","aria-label":h("minimise"),onClick:ue,children:r(Je,{})})]})]}),r("div",{class:"stage__bottom","aria-live":"polite",children:[A==="joining"||A==="connecting"?r(F,{children:[r("div",{class:"stage__name",children:v}),r("div",{class:"stage__status",children:[r("span",{class:"spinner"})," ",A==="joining"?h("connecting"):h("joining")]})]}):null,A==="queued"?r(F,{children:[r("div",{class:"line",role:"status","aria-label":h("inLineEta",{position:ce(ct),eta:Xe(E?.etaSeconds??null)}),children:[r("svg",{width:"168",height:"168",viewBox:"0 0 168 168",children:[r("circle",{class:"line__track",cx:"84",cy:"84",r:dt,fill:"none","stroke-width":"7"}),r("circle",{class:"line__fill",cx:"84",cy:"84",r:dt,fill:"none","stroke-width":"7","stroke-linecap":"round","stroke-dasharray":Rt,"stroke-dashoffset":Rt*(1-Math.max(.06,Qn))})]}),r("div",{children:[r("div",{class:"line__num",children:ce(ct)}),r("div",{class:"line__lbl",children:h("lineLabel")})]})]}),r("div",{class:"title",children:h("onOtherCalls",{name:v})}),r("div",{class:"note",children:h(o?"yourTurnChat":"yourTurn",{eta:Xe(E?.etaSeconds??null)})}),r("div",{class:"btn-row",children:[o?r("button",{class:"btn btn--accent",onClick:()=>Q("chat"),children:[r(Me,{size:18})," ",h("keepChatting")]}):null,r("button",{class:"btn",onClick:()=>{m?.hangUp()},children:h("leaveLine")})]})]}):null,A==="ready"?r(F,{children:[r("div",{class:"title",children:h("readyForYou",{name:v})}),r("div",{class:"note",children:h("joinWithin",{seconds:E?.holdSeconds??30})}),r("button",{class:"btn btn--accent btn--glow",onClick:()=>m?.accept(),children:[r(_e,{size:18})," ",h("joinCall")]})]}):null,A==="live"?r(F,{children:[r("div",{class:"stage__name",children:v}),r("div",{class:"stage__status",children:[E?.speaking?r("span",{class:"wave","aria-hidden":"true",children:[.6,1,.75,1,.55].map((u,T)=>r("i",{style:{"--k":u}},T))}):null,E?.muted?h("muted"):ti]}),r("div",{class:"captions",children:w.slice(-2).map((u,T,he)=>r("div",{class:`captions__line ${T===he.length-1?"captions__line--now":""}`,children:u.role==="visitor"?h("you",{text:u.text}):u.text},u.id))}),r("div",{class:"controls",children:[r("div",{class:"ctl",children:[r("button",{class:`round ${E?.muted?"round--on":""}`,"aria-pressed":E?.muted,"aria-label":E?.muted?h("unmute"):h("mute"),onClick:()=>m?.setMuted(!E?.muted),children:E?.muted?r(Fn,{size:22}):r(In,{size:22})}),r("span",{class:"round__label",children:E?.muted?h("unmute"):h("mute")})]}),r("div",{class:"ctl",children:[r("button",{class:"round round--end","aria-label":h("endCall"),onClick:()=>{m?.hangUp()},children:r(En,{size:26})}),r("span",{class:"round__label",children:h("end")})]}),E?.speaking?r("div",{class:"ctl",children:[r("button",{class:"round","aria-label":h("interruptName",{name:v}),onClick:()=>m?.interrupt(),children:r(Rn,{size:22})}),r("span",{class:"round__label",children:h("interrupt")})]}):null]})]}):null,ni?r(F,{children:[r("div",{class:"title",children:E?pt.title:h("callName",{name:v})}),r("div",{class:"note",children:E?E.endReason==="hangup"&&Le?`${Ke(Le)} \xB7 ${pt.body}`:E.error??pt.body:h("talkWith",{name:v})}),r("div",{class:"btn-row",children:[l&&E?.endReason!=="credits"&&E?.endReason!=="unavailable"&&E?.endReason!=="daily_limit"?r("button",{class:"btn btn--accent",onClick:()=>{N(),ot()},children:[r(_e,{size:18})," ",E?h("callAgain"):h("startCall")]}):null,o?r("button",{class:"btn",onClick:()=>Q("chat"),children:[r(Me,{size:18})," ",h("chat")]}):null]})]}):null]})]})})}function ca(t,e){let n=V({call:null,start:e});return n.current.call!==t&&(n.current={call:t,start:e}),e>n.current.start&&(n.current.start=e),n.current.start}var Wn=`
43
43
  :host {
44
44
  --cx-accent: #7c5cff;
45
45
  --cx-accent-ink: #fff;
@@ -401,5 +401,5 @@ button:focus-visible, textarea:focus-visible, a:focus-visible { outline: 2px sol
401
401
  *, *::before, *::after { animation-duration: .01ms !important; animation-iteration-count: 1 !important; transition-duration: .01ms !important; }
402
402
  .presence__ring { animation: none; }
403
403
  }
404
- `;var St="character-xyz";function da(t){let e=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(t.trim());if(!e)return"#ffffff";let n=e[1].length===3?e[1].replace(/./g,l=>l+l):e[1],[i,a,s]=[0,2,4].map(l=>parseInt(n.slice(l,l+2),16)/255).map(l=>l<=.03928?l/12.92:((l+.055)/1.055)**2.4);return .2126*i+.7152*a+.0722*s>.45?"#14121a":"#ffffff"}function pa(t){let e=/rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)(?:[,\s/]+([\d.]+%?))?\s*\)/.exec(t);if(!e||(e[4]===void 0?1:e[4].endsWith("%")?parseFloat(e[4])/100:parseFloat(e[4]))<.5)return null;let[i,a,s]=[e[1],e[2],e[3]].map(o=>Number(o)/255).map(o=>o<=.03928?o/12.92:((o+.055)/1.055)**2.4);return .2126*i+.7152*a+.0722*s}function Bn(t){for(let e of[document.body,document.documentElement]){if(!e)continue;let n=pa(getComputedStyle(e).backgroundColor);if(n!==null)return n<.22}return!!t?.matches}var ua=["publishable-key","agent","api-url","position","mode","accent","greeting","open"],Tt=class extends HTMLElement{constructor(){super(...arguments);V(this,"options",null);V(this,"client",null);V(this,"api",null);V(this,"pendingOpen",null);V(this,"booted",!1);V(this,"mq",null);V(this,"stage",null);V(this,"waiters",[]);V(this,"queuedActions",new Map);V(this,"bootFailed",!1);V(this,"onSchemeChange",()=>requestAnimationFrame(this.onScheme));V(this,"onScheme",()=>{this.dataset.mode==="auto"&&(this.dataset.theme=Bn(this.mq)?"dark":"light")})}static get observedAttributes(){return ua}connectedCallback(){if(this.booted)return;this.booted=!0;let n=this.shadowRoot??this.attachShadow({mode:"open"}),i=document.createElement("style");i.textContent=Wn,this.stage=document.createElement("div"),n.replaceChildren(i,this.stage),this.style.display="none";let a=window.requestIdleCallback;a?a(()=>{this.boot()},{timeout:2e3}):setTimeout(()=>{this.boot()},200)}disconnectedCallback(){this.stage&&xt(null,this.stage),this.settleWaiters(!1),this.client?.destroy(),this.client=null,this.mq?.removeEventListener("change",this.onSchemeChange),this.booted=!1}open(n="chat"){this.api?this.api.open(n):this.pendingOpen=n}close(){this.api?.close()}track(n,i={},a={}){return this.untilClient().then(s=>s.track(n,i,a))}identify(n){return this.untilClient().then(i=>i.identify(n))}setContext(n){return this.untilClient().then(i=>i.setContext(n))}registerAction(n,i){return this.queuedActions.set(n,i),this.client?.registerAction(n,i),()=>{this.queuedActions.delete(n),this.client?.registerAction(n,i)()}}untilClient(){return this.client?Promise.resolve(this.client):this.bootFailed?Promise.reject(new U("unknown","The widget could not start.")):new Promise((n,i)=>{this.waiters.push(a=>a?n(a):i(new U("unknown","The widget could not start.")))})}settleWaiters(n){let i=this.waiters;this.waiters=[];for(let a of i)a(n?this.client:null)}fire(n,i){this.dispatchEvent(new CustomEvent(n,{detail:i,bubbles:!0,composed:!0}))}async boot(){let n={...this.options??{}},i=De(Array.from(this.attributes)),a=n.publishableKey??i.publishableKey;try{this.client=await Pt.init({publishableKey:a,getSessionToken:n.getSessionToken,agentId:n.agentId??i.agent,apiUrl:n.apiUrl??i.apiUrl,storage:n.storage})}catch(l){let p=l instanceof U?l:new U("unknown",String(l?.message??l));console.warn(`[characterxyz] widget not shown: ${p.message}`),this.fire("cx-error",{code:p.code,message:p.message}),this.bootFailed=!0,this.settleWaiters(!1);return}if(!this.isConnected){this.client.destroy();return}let s=this.client;for(let[l,p]of this.queuedActions)s.registerAction(l,p);let o=he(ce,s.appearance);if(o=he(o,i),o=he(o,n),!(o.showChat&&s.features.chat)&&!(o.showCall&&s.features.call)){console.warn("[characterxyz] widget not shown: neither chat nor calls are enabled for this site");return}this.applyTokens(o),s.on("call",l=>{l&&l.on("state",p=>this.fire("cx-call",{phase:p.phase,position:p.position,endReason:p.endReason}))}),s.on("error",l=>this.fire("cx-error",{code:l.code,message:l.message})),this.style.display="",xt(r(Hn,{client:s,config:o,bind:l=>{this.api=l,this.pendingOpen&&this.pendingOpen!=="closed"&&(l.open(this.pendingOpen),this.pendingOpen=null)},onView:l=>{l==="closed"?(this.removeAttribute("data-open"),this.fire("cx-close")):(this.setAttribute("data-open",""),this.fire("cx-open",{view:l}))}}),this.stage),o.open&&this.setAttribute("data-open",""),this.fire("cx-ready",{agent:{id:s.agent.id,name:s.agent.name},features:s.features}),this.settleWaiters(!0)}applyTokens(n){this.dataset.side=n.position==="bottom-left"?"left":"right",this.dataset.mode=n.mode,n.mode==="auto"?(this.mq=matchMedia("(prefers-color-scheme: dark)"),this.mq.addEventListener("change",this.onSchemeChange),this.dataset.theme=Bn(this.mq)?"dark":"light"):this.dataset.theme=n.mode;let i=(a,s)=>this.style.setProperty(a,s);i("--cx-accent",n.accent),i("--cx-accent-ink",da(n.accent)),i("--cx-radius",`${n.radius}px`),n.font&&i("--cx-font",n.font),i("--cx-ox",`${n.offsetX}px`),i("--cx-oy",`${n.offsetY}px`),i("--cx-z",String(n.zIndex))}};function ha(){typeof customElements<"u"&&!customElements.get(St)&&customElements.define(St,Tt)}function Ze(t){ha();let e=document.createElement(St);return e.options=t,(t.container??document.body).appendChild(e),{element:e,open:n=>e.open(n),close:()=>e.close(),track:(n,i,a)=>e.track(n,i,a),identify:n=>e.identify(n),setContext:n=>e.setContext(n),registerAction:(n,i)=>e.registerAction(n,i),destroy:()=>e.remove()}}var Yn=document.currentScript,ae=null;function jn(){if(!Yn)return;let t=De(Array.from(Yn.attributes).filter(o=>o.name.startsWith("data-"))),e=o=>typeof o=="string"&&o.trim()?o.trim():void 0,n=e(t.key)??e(t.publishableKey);if(!n)return;let i=he(ce,t),s={...Object.fromEntries(Object.entries(i).filter(([o,l])=>o in t&&l!==ce[o])),publishableKey:n,agentId:e(t.agent),apiUrl:e(t.apiUrl)};ae=Ze(s)}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",jn,{once:!0}):jn();var fa={mount:t=>ae=Ze(t),open:t=>ae?.open(t),close:()=>ae?.close(),track:(t,e,n)=>ae?.track(t,e,n),identify:t=>ae?.identify(t),setContext:t=>ae?.setContext(t),registerAction:(t,e)=>ae?.registerAction(t,e),get widget(){return ae}};window.CharacterXYZ=fa;return ci(ga);})();
404
+ `;var Mt="character-xyz";function da(t){let e=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(t.trim());if(!e)return"#ffffff";let n=e[1].length===3?e[1].replace(/./g,l=>l+l):e[1],[i,a,s]=[0,2,4].map(l=>parseInt(n.slice(l,l+2),16)/255).map(l=>l<=.03928?l/12.92:((l+.055)/1.055)**2.4);return .2126*i+.7152*a+.0722*s>.45?"#14121a":"#ffffff"}function pa(t){let e=/rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)(?:[,\s/]+([\d.]+%?))?\s*\)/.exec(t);if(!e||(e[4]===void 0?1:e[4].endsWith("%")?parseFloat(e[4])/100:parseFloat(e[4]))<.5)return null;let[i,a,s]=[e[1],e[2],e[3]].map(o=>Number(o)/255).map(o=>o<=.03928?o/12.92:((o+.055)/1.055)**2.4);return .2126*i+.7152*a+.0722*s}function Yn(t){for(let e of[document.body,document.documentElement]){if(!e)continue;let n=pa(getComputedStyle(e).backgroundColor);if(n!==null)return n<.22}return!!t?.matches}var ua=["publishable-key","agent","api-url","position","mode","accent","greeting","open"],Et=class extends HTMLElement{constructor(){super(...arguments);j(this,"options",null);j(this,"client",null);j(this,"api",null);j(this,"pendingOpen",null);j(this,"booted",!1);j(this,"mq",null);j(this,"stage",null);j(this,"waiters",[]);j(this,"queuedActions",new Map);j(this,"bootFailed",!1);j(this,"onSchemeChange",()=>requestAnimationFrame(this.onScheme));j(this,"onScheme",()=>{this.dataset.mode==="auto"&&(this.dataset.theme=Yn(this.mq)?"dark":"light")})}static get observedAttributes(){return ua}connectedCallback(){if(this.booted)return;this.booted=!0;let n=this.shadowRoot??this.attachShadow({mode:"open"}),i=document.createElement("style");i.textContent=Wn,this.stage=document.createElement("div"),n.replaceChildren(i,this.stage),this.style.display="none";let a=window.requestIdleCallback;a?a(()=>{this.boot()},{timeout:2e3}):setTimeout(()=>{this.boot()},200)}disconnectedCallback(){this.stage&&yt(null,this.stage),this.settleWaiters(!1),this.client?.destroy(),this.client=null,this.mq?.removeEventListener("change",this.onSchemeChange),this.booted=!1}open(n="chat"){this.api?this.api.open(n):this.pendingOpen=n}close(){this.api?.close()}track(n,i={},a={}){return this.untilClient().then(s=>s.track(n,i,a))}identify(n){return this.untilClient().then(i=>i.identify(n))}setContext(n){return this.untilClient().then(i=>i.setContext(n))}registerAction(n,i){return this.queuedActions.set(n,i),this.client?.registerAction(n,i),()=>{this.queuedActions.delete(n),this.client?.registerAction(n,i)()}}untilClient(){return this.client?Promise.resolve(this.client):this.bootFailed?Promise.reject(new P("unknown","The widget could not start.")):new Promise((n,i)=>{this.waiters.push(a=>a?n(a):i(new P("unknown","The widget could not start.")))})}settleWaiters(n){let i=this.waiters;this.waiters=[];for(let a of i)a(n?this.client:null)}fire(n,i){this.dispatchEvent(new CustomEvent(n,{detail:i,bubbles:!0,composed:!0}))}async boot(){let n={...this.options??{}},i=De(Array.from(this.attributes)),a=n.publishableKey??i.publishableKey;try{this.client=await Ot.init({publishableKey:a,getSessionToken:n.getSessionToken,agentId:n.agentId??i.agent,apiUrl:n.apiUrl??i.apiUrl,storage:n.storage})}catch(l){let p=l instanceof P?l:new P("unknown",String(l?.message??l));console.warn(`[characterxyz] widget not shown: ${p.message}`),this.fire("cx-error",{code:p.code,message:p.message}),this.bootFailed=!0,this.settleWaiters(!1);return}if(!this.isConnected){this.client.destroy();return}let s=this.client;for(let[l,p]of this.queuedActions)s.registerAction(l,p);let o=fe(de,s.appearance);if(o=fe(o,i),o=fe(o,n),!(o.showChat&&s.features.chat)&&!(o.showCall&&s.features.call)){console.warn("[characterxyz] widget not shown: neither chat nor calls are enabled for this site");return}this.applyTokens(o),s.on("call",l=>{l&&l.on("state",p=>this.fire("cx-call",{phase:p.phase,position:p.position,endReason:p.endReason}))}),s.on("error",l=>this.fire("cx-error",{code:l.code,message:l.message})),this.style.display="",yt(r(Bn,{client:s,config:o,bind:l=>{this.api=l,this.pendingOpen&&this.pendingOpen!=="closed"&&(l.open(this.pendingOpen),this.pendingOpen=null)},onView:l=>{l==="closed"?(this.removeAttribute("data-open"),this.fire("cx-close")):(this.setAttribute("data-open",""),this.fire("cx-open",{view:l}))}}),this.stage),o.open&&this.setAttribute("data-open",""),this.fire("cx-ready",{agent:{id:s.agent.id,name:s.agent.name},features:s.features}),this.settleWaiters(!0)}applyTokens(n){this.dataset.side=n.position==="bottom-left"?"left":"right",this.dataset.mode=n.mode,n.mode==="auto"?(this.mq=matchMedia("(prefers-color-scheme: dark)"),this.mq.addEventListener("change",this.onSchemeChange),this.dataset.theme=Yn(this.mq)?"dark":"light"):this.dataset.theme=n.mode;let i=(a,s)=>this.style.setProperty(a,s);i("--cx-accent",n.accent),i("--cx-accent-ink",da(n.accent)),i("--cx-radius",`${n.radius}px`),n.font&&i("--cx-font",n.font),i("--cx-ox",`${n.offsetX}px`),i("--cx-oy",`${n.offsetY}px`),i("--cx-z",String(n.zIndex))}};function ha(){typeof customElements<"u"&&!customElements.get(Mt)&&customElements.define(Mt,Et)}function Ge(t){ha();let e=document.createElement(Mt);return e.options=t,(t.container??document.body).appendChild(e),{element:e,open:n=>e.open(n),close:()=>e.close(),track:(n,i,a)=>e.track(n,i,a),identify:n=>e.identify(n),setContext:n=>e.setContext(n),registerAction:(n,i)=>e.registerAction(n,i),destroy:()=>e.remove()}}var qn=document.currentScript,re=null;function jn(){if(!qn)return;let t=De(Array.from(qn.attributes).filter(o=>o.name.startsWith("data-"))),e=o=>typeof o=="string"&&o.trim()?o.trim():void 0,n=e(t.key)??e(t.publishableKey);if(!n)return;let i=fe(de,t),s={...Object.fromEntries(Object.entries(i).filter(([o,l])=>o in t&&l!==de[o])),publishableKey:n,agentId:e(t.agent),apiUrl:e(t.apiUrl)};re=Ge(s)}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",jn,{once:!0}):jn();var fa={mount:t=>re=Ge(t),open:t=>re?.open(t),close:()=>re?.close(),track:(t,e,n)=>re?.track(t,e,n),identify:t=>re?.identify(t),setContext:t=>re?.setContext(t),registerAction:(t,e)=>re?.registerAction(t,e),get widget(){return re}};window.CharacterXYZ=fa;return ci(ga);})();
405
405
  //# sourceMappingURL=cx.js.map