@characterxyz/widget 0.4.0 → 0.6.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/index.js CHANGED
@@ -1,4 +1,4 @@
1
- var ei=Object.defineProperty;var ti=(t,e,n)=>e in t?ei(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var q=(t,e,n)=>ti(t,typeof e!="symbol"?e+"":e,n);var ni=Object.defineProperty,ii=(t,e,n)=>e in t?ni(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,v=(t,e,n)=>ii(t,typeof e!="symbol"?e+"":e,n),te=null;function Ft(){return(!te||te.state==="closed")&&(te=new AudioContext({latencyHint:"interactive"})),te.state==="suspended"&&te.resume().catch(()=>{}),te}var ai=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=Ft(),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 r=this.ctx.createBufferSource();r.buffer=i,r.connect(this.gain);let o=this.ctx.currentTime;if(this.nextAt<o&&(this.nextAt=o+(this.started?.02:.12)),r.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(r),r.onended=()=>{this.sources.delete(r),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?.())}},si=`
1
+ var ti=Object.defineProperty;var ni=(t,e,n)=>e in t?ti(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var X=(t,e,n)=>ni(t,typeof e!="symbol"?e+"":e,n);var ii=Object.defineProperty,ai=(t,e,n)=>e in t?ii(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,v=(t,e,n)=>ai(t,typeof e!="symbol"?e+"":e,n),le=null;function Lt(){return(!le||le.state==="closed")&&(le=new AudioContext({latencyHint:"interactive"})),le.state==="suspended"&&le.resume().catch(()=>{}),le}var ri=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=Lt(),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?.())}},si=`
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 ri(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 oi(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,r=d=>{if(a){t.onFrame(new ArrayBuffer(d.byteLength),0);return}t.onFrame(d,ri(d))},o,l;try{let d=URL.createObjectURL(new Blob([si],{type:"application/javascript"}));try{await n.audioWorklet.addModule(d)}finally{URL.revokeObjectURL(d)}let f=new AudioWorkletNode(n,"cxyz-mic");f.port.onmessage=_=>r(_.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 y=Math.max(-1,Math.min(1,x[m]));c[g++]=y<0?y*32768:y*32767,g===480&&(r(c.buffer),c=new Int16Array(480),g=0)}},o=d,l=()=>{d.onaudioprocess=null}}i.connect(o);let h=n.createGain();return h.gain.value=0,o.connect(h).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 it=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={}}},D=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 li(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 ci(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 D(li(t.status),e||`Request failed (${t.status})`,t.status,n)}async function de(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,credentials:"omit",cache:"no-store"})}catch(r){throw r?.name==="AbortError"?r:new D("network","Could not reach Character XYZ. Check your connection.")}if(!a.ok)throw await ci(a);return a}async function X(t,e,n={}){return(await(await de(t,e,n)).json()).data}async function Lt(t,e,n){let i=t.body;if(!i)return;let a=i.getReader(),r=new TextDecoder,o="",l=()=>{a.cancel().catch(()=>{})};n?.addEventListener("abort",l);try{for(;;){let{value:h,done:d}=await a.read();if(d)break;o+=r.decode(h,{stream:!0}),o=Et(o,e)}o+=r.decode(),Et(o+`
33
+ `;function oi(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 li(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,oi(d))},o,l;try{let d=URL.createObjectURL(new Blob([si],{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=y=>{let b=y.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 h=n.createGain();return h.gain.value=0,o.connect(h).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 lt=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={}}},O=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 ci(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 di(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 O(ci(t.status),e||`Request failed (${t.status})`,t.status,n)}async function xe(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,credentials:"omit",cache:"no-store"})}catch(s){throw s?.name==="AbortError"?s:new O("network","Could not reach Character XYZ. Check your connection.")}if(!a.ok)throw await di(a);return a}async function ee(t,e,n={}){return(await(await xe(t,e,n)).json()).data}async function zt(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:h,done:d}=await a.read();if(d)break;o+=s.decode(h,{stream:!0}),o=It(o,e)}o+=s.decode(),It(o+`
34
34
 
35
- `,e)}finally{n?.removeEventListener("abort",l)}}function Et(t,e){let n=t.replace(/\r\n/g,`
35
+ `,e)}finally{n?.removeEventListener("abort",l)}}function It(t,e){let n=t.replace(/\r\n/g,`
36
36
  `),i;for(;(i=n.indexOf(`
37
37
 
38
- `))!==-1;){let a=n.slice(0,i);n=n.slice(i+2);let r="message",o=[];for(let d of a.split(`
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"?r=c:_==="data"&&o.push(c)}if(!o.length)continue;let l=o.join(`
40
- `),h=l;try{h=JSON.parse(l)}catch{}e({event:r,data:h})}return n}function di(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,r=e.getUint16(a,!0);if(a+=2,a+r+20>t.byteLength)return null;let o=new TextDecoder().decode(new Uint8Array(t,a,r));a+=r+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 pi=.09,ui=350,hi=25e3,fi=()=>({phase:"idle",callId:null,position:null,etaSeconds:null,holdSeconds:null,maxSeconds:null,startedAt:null,endReason:null,muted:!1,speaking:!1,agentState:"idle",error:null}),gi=class extends it{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",fi()),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"}),Ft();try{this.mic=await oi({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 D?t:new D("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 de(this.apiUrl,`/sdk/v1/calls/${encodeURIComponent(this.s.callId)}/events`,{token:e,signal:this.eventsAbort.signal});t=0,await Lt(n,i=>this.onServerEvent(i.event,i.data),this.eventsAbort.signal)}catch(e){if(e?.name==="AbortError")return;if(e instanceof D&&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"}),hi),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>pi){if(this.loudSince??(this.loudSince=i),i-this.loudSince>=ui){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=di(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[r,o]of this.players)o.stop(),this.players.delete(r);let a=n.corr;i=new ai({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 de(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})}},mi=0,It=t=>`${t}_${Date.now().toString(36)}_${(mi++).toString(36)}`,_i=class extends it{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)}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 D("invalid","Say something first.");if(this.busy)throw new D("rate_limited","Wait for the reply first.");this.setBusy(!0);let n={id:It("local"),role:"visitor",text:e,createdAt:new Date().toISOString()},i={id:It("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(),r=await de(this.apiUrl,"/sdk/v1/chat/messages",{method:"POST",body:{text:e},token:a,signal:this.abort.signal}),o=null,l=null;if(await Lt(r,({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 D("unknown",l??"The reply was cut off. Try again.");let h=o;return this.replace(i.id,h),h}catch(a){let r=a instanceof D?a:new D("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,...r.status===429?{error:r.message}:{}}),this.publish(),a?.name!=="AbortError"&&this.emit("error",r),r}finally{this.abort=null,this.setBusy(!1)}}async reset(){this.stop();let t=await this.session.token();await de(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 D("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)}},bi=()=>{let t=new Map;return{get:e=>t.get(e)??null,set:(e,n)=>{t.set(e,n)}}},xi=()=>({get(t){try{return globalThis.localStorage?.getItem(t)??null}catch{return null}},set(t,e){try{globalThis.localStorage?.setItem(t,e)}catch{}}}),yi=60,vi=class{constructor(t){if(v(this,"src",t),v(this,"current",null),v(this,"inflight",null),!t.publishableKey&&!t.getSessionToken)throw new D("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-yi>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}}},ki="https://api.character.xyz",at=class zt extends it{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),this.chat=new _i(e,n)}static async init(e){let n=(e.apiUrl??ki).replace(/\/+$/,"");if(e.publishableKey&&/^cxyz_sk_/.test(e.publishableKey))throw new D("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"?bi():e.storage&&typeof e.storage=="object"?e.storage:xi(),a=new vi({apiUrl:n,agentId:e.agentId,publishableKey:e.publishableKey,getSessionToken:e.getSessionToken,store:i}),r=await a.refresh();return new zt(n,a,r)}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 startCall(e={}){if(this.destroyed)throw new D("invalid","This client was destroyed.");if(!this.features.call)throw new D("forbidden","Calls are not available on this site.");if(this.call)return this.call;let n=new gi(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.clear()}};var Fe,M,Nt,wi,Z,Dt,Ot,$t,st,Se,pe,Bt,lt,rt,ot,Ci,Me={},Ee=[],Si=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Le=Array.isArray;function K(t,e){for(var n in e)t[n]=e[n];return t}function ct(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function Ti(t,e,n){var i,a,r,o={};for(r in e)r=="key"?i=e[r]:r=="ref"?a=e[r]:o[r]=e[r];if(arguments.length>2&&(o.children=arguments.length>3?Fe.call(arguments,2):n),typeof t=="function"&&t.defaultProps!=null)for(r in t.defaultProps)o[r]===void 0&&(o[r]=t.defaultProps[r]);return Te(t,o,i,a,null)}function Te(t,e,n,i,a){var r={type:t,props:e,key:n,ref:i,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:a??++Nt,__i:-1,__u:0};return a==null&&M.vnode!=null&&M.vnode(r),r}function E(t){return t.children}function Ae(t,e){this.props=t,this.context=e}function G(t,e){if(e==null)return t.__?G(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"?G(t):null}function Ai(t){if(t.__P&&t.__d){var e=t.__v,n=e.__e,i=[],a=[],r=K({},e);r.__v=e.__v+1,M.vnode&&M.vnode(r),dt(t.__P,r,e,t.__n,t.__P.namespaceURI,32&e.__u?[n]:null,i,n??G(e),!!(32&e.__u),a),r.__v=e.__v,r.__.__k[r.__i]=r,qt(i,r,a),e.__e=e.__=null,r.__e!=n&&Wt(r)}}function Wt(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}),Wt(t)}function Ut(t){(!t.__d&&(t.__d=!0)&&Z.push(t)&&!Ie.__r++||Dt!=M.debounceRendering)&&((Dt=M.debounceRendering)||Ot)(Ie)}function Ie(){try{for(var t,e=1;Z.length;)Z.length>e&&Z.sort($t),t=Z.shift(),e=Z.length,Ai(t)}finally{Z.length=Ie.__r=0}}function Ht(t,e,n,i,a,r,o,l,h,d,f){var _,c,g,b,x,m,y=i&&i.__k||Ee,w=e.length;for(h=Mi(n,e,y,h,w),_=0;_<w;_++)(g=n.__k[_])!=null&&(c=g.__i!=-1&&y[g.__i]||Me,g.__i=_,m=dt(t,g,c,a,r,o,l,h,d,f),b=g.__e,g.ref&&c.ref!=g.ref&&(c.ref&&pt(c.ref,null,g),f.push(g.ref,g.__c||b,g)),x==null&&b!=null&&(x=b),4&g.__u?(h=Yt(g,h,t),c.__e&&(c.__e=null)):typeof g.type=="function"&&m!==void 0?h=m:b&&(h=b.nextSibling),g.__u&=-7);return n.__e=x,h}function Mi(t,e,n,i,a){var r,o,l,h,d,f=n.length,_=f,c=0;for(t.__k=new Array(a),r=0;r<a;r++)(o=e[r])!=null&&typeof o!="boolean"&&typeof o!="function"?(typeof o=="string"||typeof o=="number"||typeof o=="bigint"||o.constructor==String?o=t.__k[r]=Te(null,o,null,null,null):Le(o)?o=t.__k[r]=Te(E,{children:o},null,null,null):o.constructor===void 0&&o.__b>0?o=t.__k[r]=Te(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):t.__k[r]=o,h=r+c,o.__=t,o.__b=t.__b+1,l=null,(d=o.__i=Ei(o,n,h,_))!=-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!=h&&(d==h-1?c--:d==h+1?c++:(d>h?c--:c++,o.__u|=4))):t.__k[r]=null;if(_)for(r=0;r<f;r++)(l=n[r])!=null&&(2&l.__u)==0&&(l.__e==i&&(i=G(l)),Kt(l,l));return i}function Yt(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=Yt(i[a],e,n));return e}t.__e!=e&&(e&&t.type&&!e.parentNode&&(e=G(t)),e=n.insertBefore(t.__e,e||null));do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function Ei(t,e,n,i){var a,r,o,l=t.key,h=t.type,d=e[n],f=d!=null&&(2&d.__u)==0;if(d===null&&l==null||f&&l==d.key&&h==d.type)return n;if(i>(f?1:0)){for(a=n-1,r=n+1;a>=0||r<e.length;)if((d=e[o=a>=0?a--:r++])!=null&&(2&d.__u)==0&&l==d.key&&h==d.type)return o}return-1}function Pt(t,e,n){e[0]=="-"?t.setProperty(e,n??""):t[e]=n==null?"":typeof n!="number"||Si.test(e)?n:n+"px"}function Ce(t,e,n,i,a){var r,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||Pt(t.style,e,"");if(n)for(e in n)i&&n[e]==i[e]||Pt(t.style,e,n[e])}else if(e[0]=="o"&&e[1]=="n")r=e!=(e=e.replace(Bt,"$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+r]=n,n?i?n[pe]=i[pe]:(n[pe]=lt,t.addEventListener(e,r?ot:rt,r)):t.removeEventListener(e,r?ot:rt,r);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 Rt(t){return function(e){if(this.l){var n=this.l[e.type+t];if(e[Se]==null)e[Se]=lt++;else if(e[Se]<n[pe])return;return n(M.event?M.event(e):e)}}}function dt(t,e,n,i,a,r,o,l,h,d){var f,_,c,g,b,x,m,y,w,L,P,R,W,U,O,Y,k=e.type;if(e.constructor!==void 0)return null;128&n.__u&&(h=!!(32&n.__u),r=[l=e.__e=n.__e]),(f=M.__b)&&f(e);e:if(typeof k=="function"){_=o.length;try{if(w=e.props,L=k.prototype&&k.prototype.render,P=(f=k.contextType)&&i[f.__c],R=f?P?P.props.value:f.__:i,n.__c?y=(c=e.__c=n.__c).__=c.__E:(L?e.__c=c=new k(w,R):(e.__c=c=new Ae(w,R),c.constructor=k,c.render=Fi),P&&P.sub(c),c.state||(c.state={}),c.__n=i,g=c.__d=!0,c.__h=[],c._sb=[]),L&&c.__s==null&&(c.__s=c.state),L&&k.getDerivedStateFromProps!=null&&(c.__s==c.state&&(c.__s=K({},c.__s)),K(c.__s,k.getDerivedStateFromProps(w,c.__s))),b=c.props,x=c.state,c.__v=e,g)L&&k.getDerivedStateFromProps==null&&c.componentWillMount!=null&&c.componentWillMount(),L&&c.componentDidMount!=null&&c.__h.push(c.componentDidMount);else{if(L&&k.getDerivedStateFromProps==null&&w!==b&&c.componentWillReceiveProps!=null&&c.componentWillReceiveProps(w,R),e.__v==n.__v||!c.__e&&c.shouldComponentUpdate!=null&&c.shouldComponentUpdate(w,c.__s,R)===!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(N){N&&(N.__=e)}),Ee.push.apply(c.__h,c._sb),c._sb=[],c.__h.length&&o.push(c),l=G(n);break e}c.componentWillUpdate!=null&&c.componentWillUpdate(w,c.__s,R),L&&c.componentDidUpdate!=null&&c.__h.push(function(){c.componentDidUpdate(b,x,m)})}if(c.context=R,c.props=w,c.__P=t,c.__e=!1,W=M.__r,U=0,L)c.state=c.__s,c.__d=!1,W&&W(e),f=c.render(c.props,c.state,c.context),Ee.push.apply(c.__h,c._sb),c._sb=[];else do c.__d=!1,W&&W(e),f=c.render(c.props,c.state,c.context),c.state=c.__s;while(c.__d&&++U<25);c.state=c.__s,c.getChildContext!=null&&(i=K(K({},i),c.getChildContext())),L&&!g&&c.getSnapshotBeforeUpdate!=null&&(m=c.getSnapshotBeforeUpdate(b,x)),O=f!=null&&f.type===E&&f.key==null?Vt(f.props.children):f,l=Ht(t,Le(O)?O:[O],e,n,i,a,r,o,l,h,d),c.base=e.__e,e.__u&=-161,c.__h.length&&o.push(c),y&&(c.__E=c.__=null)}catch(N){if(o.length=_,e.__v=null,h||r!=null){if(N.then){for(e.__u|=h?160:128;l&&l.nodeType==8&&l.nextSibling;)l=l.nextSibling;r!=null&&(r[r.indexOf(l)]=null),e.__e=l}else if(r!=null)for(Y=r.length;Y--;)ct(r[Y])}else e.__e=n.__e;e.__k==null&&(e.__k=n.__k||[]),N.then||jt(e),M.__e(N,e,n)}}else r==null&&e.__v==n.__v?(e.__k=n.__k,e.__e=n.__e):l=e.__e=Ii(n.__e,e,n,i,a,r,o,h,d);return(f=M.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 qt(t,e,n){for(var i=0;i<n.length;i++)pt(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(r){r.call(a)})}catch(r){M.__e(r,a.__v)}})}function Vt(t){return typeof t!="object"||t==null||t.__b>0?t:Le(t)?t.map(Vt):t.constructor!==void 0?null:K({},t)}function Ii(t,e,n,i,a,r,o,l,h){var d,f,_,c,g,b,x,m=n.props||Me,y=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"),r!=null){for(d=0;d<r.length;d++)if((g=r[d])&&"setAttribute"in g==!!w&&(w?g.localName==w:g.nodeType==3)){t=g,r[d]=null;break}}if(t==null){if(w==null)return document.createTextNode(y);t=document.createElementNS(a,w,y.is&&y),l&&(M.__m&&M.__m(e,r),l=!1),r=null}if(w==null)m===y||l&&t.data==y||(t.data=y);else{if(r=w=="textarea"&&y.defaultValue!=null?null:r&&Fe.call(t.childNodes),!l&&r!=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 y||d=="value"&&"defaultValue"in y||d=="checked"&&"defaultChecked"in y||Ce(t,d,null,g,a);for(d in y)g=y[d],d=="children"?c=g:d=="dangerouslySetInnerHTML"?f=g:d=="value"?b=g:d=="checked"?x=g:l&&typeof g!="function"||m[d]===g||Ce(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=""),Ht(e.type=="template"?t.content:t,Le(c)?c:[c],e,n,i,w=="foreignObject"?"http://www.w3.org/1999/xhtml":a,r,o,r?r[0]:n.__k&&G(n,0),l,h),r!=null)for(d=r.length;d--;)ct(r[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])&&Ce(t,d,b,m[d],a),d="checked",x!=null&&x!=t[d]&&Ce(t,d,x,m[d],a))}return t}function pt(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 Kt(t,e,n){var i,a;if(M.unmount&&M.unmount(t),(i=t.ref)&&(i.current&&i.current!=t.__e||pt(i,null,e)),(i=t.__c)!=null){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(r){M.__e(r,e)}i.base=i.__P=i.__n=null}if(i=t.__k)for(a=0;a<i.length;a++)i[a]&&Kt(i[a],e,n||typeof t.type!="function");n||ct(t.__e),t.__c=t.__=t.__e=void 0}function Fi(t,e,n){return this.constructor(t,n)}function ut(t,e,n){var i,a,r,o;e==document&&(e=document.documentElement),M.__&&M.__(t,e),a=(i=typeof n=="function")?null:n&&n.__k||e.__k,r=[],o=[],dt(e,t=(!i&&n||e).__k=Ti(E,null,[t]),a||Me,Me,e.namespaceURI,!i&&n?[n]:a?null:e.firstChild?Fe.call(e.childNodes):null,r,!i&&n?n:a?a.__e:e.firstChild,i,o),qt(r,t,o),t.props.children=null}Fe=Ee.slice,M={__e:function(t,e,n,i){for(var a,r,o;e=e.__;)if((a=e.__c)&&!a.__)try{if((r=a.constructor)&&r.getDerivedStateFromError!=null&&(a.setState(r.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}},Nt=0,wi=function(t){return t!=null&&t.constructor===void 0},Ae.prototype.setState=function(t,e){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=K({},this.state),typeof t=="function"&&(t=t(K({},n),this.props)),t&&K(n,t),t!=null&&this.__v&&(e&&this._sb.push(e),Ut(this))},Ae.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),Ut(this))},Ae.prototype.render=E,Z=[],Ot=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,$t=function(t,e){return t.__v.__b-e.__v.__b},Ie.__r=0,st=Math.random().toString(8),Se="__d"+st,pe="__a"+st,Bt=/(PointerCapture)$|Capture$/i,lt=0,rt=Rt(!1),ot=Rt(!0),Ci=0;var ne,F,ht,Xt,ue=0,an=[],z=M,Zt=z.__b,Jt=z.__r,Gt=z.diffed,Qt=z.__c,en=z.unmount,tn=z.__;function De(t,e){z.__h&&z.__h(F,t,ue||e),ue=0;var n=F.__H||(F.__H={__:[],__h:[]});return t>=n.__.length&&n.__.push({}),n.__[t]}function T(t){return ue=1,Li(on,t)}function Li(t,e,n){var i=De(ne++,2);if(i.t=t,!i.__c&&(i.__=[n?n(e):on(void 0,e),function(l){var h=i.__N?i.__N[0]:i.__[0],d=i.t(h,l);h!==d&&(i.__N=[d,i.__[1]],i.__c.setState({}))}],i.__c=F,!F.__f)){var a=function(l,h,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)}}),r){var c=r.call(this,l,h,d);return f?c||_:c}return!f||_};F.__f=!0;var r=F.shouldComponentUpdate,o=F.componentWillUpdate;F.componentWillUpdate=function(l,h,d){if(this.__e){var f=r;r=void 0,a(l,h,d),r=f}o&&o.call(this,l,h,d)},F.shouldComponentUpdate=a}return i.__N||i.__}function I(t,e){var n=De(ne++,3);!z.__s&&gt(n.__H,e)&&(n.__=t,n.u=e,F.__H.__h.push(n))}function sn(t,e){var n=De(ne++,4);!z.__s&&gt(n.__H,e)&&(n.__=t,n.u=e,F.__h.push(n))}function B(t){return ue=5,rn(function(){return{current:t}},[])}function rn(t,e){var n=De(ne++,7);return gt(n.__H,e)&&(n.__=t(),n.__H=e,n.__h=t),n.__}function he(t,e){return ue=8,rn(function(){return t},e)}function zi(){for(var t;t=an.shift();){var e=t.__H;if(t.__P&&e)try{e.__h.some(ze),e.__h.some(ft),e.__h=[]}catch(n){e.__h=[],z.__e(n,t.__v)}}}z.__b=function(t){F=null,Zt&&Zt(t)},z.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),tn&&tn(t,e)},z.__r=function(t){Jt&&Jt(t),ne=0;var e=(F=t.__c).__H;e&&(ht===F?(e.__h=[],F.__h=[],e.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(e.__h.some(ze),e.__h.some(ft),e.__h=[],ne=0)),ht=F},z.diffed=function(t){Gt&&Gt(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(an.push(e)!==1&&Xt===z.requestAnimationFrame||((Xt=z.requestAnimationFrame)||Di)(zi)),e.__H.__.some(function(n){n.u&&(n.__H=n.u,n.u=void 0)})),ht=F=null},z.__c=function(t,e){e.some(function(n){try{n.__h.some(ze),n.__h=n.__h.filter(function(i){return!i.__||ft(i)})}catch(i){e.some(function(a){a.__h&&(a.__h=[])}),e=[],z.__e(i,n.__v)}}),Qt&&Qt(t,e)},z.unmount=function(t){en&&en(t);var e,n=t.__c;n&&n.__H&&(n.__H.__.some(function(i){try{ze(i)}catch(a){e=a}}),n.__H=void 0,e&&z.__e(e,n.__v))};var nn=typeof requestAnimationFrame=="function";function Di(t){var e,n=function(){clearTimeout(i),nn&&cancelAnimationFrame(e),setTimeout(t)},i=setTimeout(n,35);nn&&(e=requestAnimationFrame(n))}function ze(t){var e=F,n=t.__c;typeof n=="function"&&(t.__c=void 0,n()),F=e}function ft(t){var e=F;t.__c=t.__(),F=e}function gt(t,e){return!t||t.length!==e.length||e.some(function(n,i){return n!==t[i]})}function on(t,e){return typeof e=="function"?e(t):e}var me={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"},fe=(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},ge=t=>{if(typeof t=="boolean")return t;if(t==="true"||t===""||t==="1")return!0;if(t==="false"||t==="0")return!1},mt=(t,e=200)=>typeof t=="string"?t.slice(0,e):void 0;function Ui(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 _e(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=Ui(e.accent)??n.accent,n.radius=fe(e.radius,0,40)??n.radius,n.font=Pi(e.font)??n.font,e.subtitle===null?n.subtitle=null:n.subtitle=mt(e.subtitle,80)??n.subtitle,n.greeting=mt(e.greeting,160)??n.greeting,n.greetingDelay=fe(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=mt(e.placeholder,60)??n.placeholder,n.showChat=ge(e.showChat)??n.showChat,n.showCall=ge(e.showCall)??n.showCall,n.branding=ge(e.branding)??n.branding,n.offsetX=fe(e.offsetX,0,200)??n.offsetX,n.offsetY=fe(e.offsetY,0,200)??n.offsetY,n.zIndex=fe(e.zIndex,0,2147483647)??n.zIndex,n.open=ge(e.open)??n.open,n.face=ge(e.face)??n.face,typeof e.faceUrl=="string"&&/^https?:\/\/[^\s"'<>]+$/.test(e.faceUrl.trim())&&(n.faceUrl=e.faceUrl.trim()),n}function ln(t){let e={};for(let{name:n,value:i}of t){let a=n.replace(/^data-/,"").replace(/-([a-z])/g,(r,o)=>o.toUpperCase());e[a]=i}return e}function dn(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 Ue(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 cn(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 r=a[0];r.startsWith("**")?e.push({t:"b",v:r.slice(2,-2)}):r.startsWith("`")?e.push({t:"code",v:r.slice(1,-1)}):r.startsWith("[")?e.push({t:"link",v:r.slice(1,r.indexOf("]")),href:a[2]}):r.startsWith("http")?e.push({t:"link",v:r,href:r}):e.push({t:"i",v:r.slice(1,-1)}),i=a.index+r.length}return i<t.length&&e.push({t:"text",v:t.slice(i)}),e}function pn(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=>cn(a.replace(/^\s*[-*•]\s+/,"")))}):e.push({t:"p",parts:cn(n)})}return e}var Ri={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.",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."},un={},hn=!0;function fn(t){un=t??{},hn=!t||!Object.keys(t).length}function u(t,e){let n=un[t]??Ri[t];if(e)for(let i in e)n=n.split(`{${i}}`).join(String(e[i]));return n}function J(t){return hn?dn(t):String(t)}function Pe(t){if(t==null)return"";if(t<60)return u("etaSoon");let e=Math.round(t/60);return e<60?u("etaMin",{n:e}):u("etaHr",{n:Math.round(e/60)})}function gn(t,e){let n=(i,a)=>({title:u(i),body:u(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 mn={cx:.5,cy:.12,span:.06};function _n(t,e,n){let i=t?.face?.eyes,a=t?.face?.chin;if(!i||!a||!e||!n)return mn;let r=(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:r/e,cy:(o+a.y)/2/n,span:l}:mn}var Re={faceFraction:.26,at:{x:.5,y:.5}},bn={faceFraction:.14,at:{x:.5,y:.34}},xn={faceFraction:.16,at:{x:.5,y:.22}},yn={fit:"height"};function vn(t,e,n,i,a){if("fit"in a){let l=i*e;return{width:l,height:i,left:n/2-t.cx*l,top:0}}let r=i*a.faceFraction/t.span,o=r*e;return{width:o,height:r,left:n*a.at.x-t.cx*o,top:i*a.at.y-t.cy*r}}var kn=/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/,Ni=/\+?\d[\d\s().-]{5,}\d/g,Oi=/\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,$i=new Set(["interested","looking","from","with","here","trying","not","a","an","the","just","also","happy","keen","curious","calling","sure","fine","good","okay","ok"]);function wn(t){let e={},n=t.match(kn)?.[0];n&&(e.email=n.replace(/[.,;:]+$/,""));for(let a of t.replace(kn," ").matchAll(Ni)){let r=a[0].replace(/\D/g,"");if(r.length>=7&&r.length<=15){e.phone=a[0].trim();break}}if(!e.email&&!e.phone)return null;let i=t.match(Oi)?.[1];if(i){let a=i.split(/\s+/).filter(o=>!$i.has(o.toLowerCase())),r=[];for(let o of a){if(["and","here","at","from"].includes(o.toLowerCase()))break;r.push(o)}r.length&&r[0].length>1&&(e.name=r.map(o=>o[0].toUpperCase()+o.slice(1)).join(" "))}return e}var Bi=0;function s(t,e,n,i,a,r){e||(e={});var o,l,h=e;if("ref"in h)for(l in h={},e)l=="ref"?o=e[l]:h[l]=e[l];var d={type:t,props:h,key:n,ref:o,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--Bi,__i:-1,__u:0,__source:a,__self:r};if(typeof t=="function"&&(o=t.defaultProps))for(l in o)h[l]===void 0&&(h[l]=o[l]);return M.vnode&&M.vnode(d),d}var H=(t,e)=>s("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}),be=({size:t=20})=>H(t,s("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"})),ie=({size:t=20})=>H(t,s("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"})),Cn=({size:t=22})=>H(t,s("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"})),Sn=({size:t=20})=>H(t,s(E,{children:[s("rect",{x:"9",y:"3",width:"6",height:"11",rx:"3"}),s("path",{d:"M5.5 11a6.5 6.5 0 0 0 13 0M12 17.5V21"})]})),Tn=({size:t=20})=>H(t,s(E,{children:[s("path",{d:"M9 9v2a3 3 0 0 0 5.1 2.1M15 9.4V6a3 3 0 0 0-5.7-1.3"}),s("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"})]})),Ne=({size:t=18})=>H(t,s("path",{d:"M6 6l12 12M18 6L6 18"})),An=({size:t=18})=>H(t,s("path",{d:"M12 19V5M5.5 11.5L12 5l6.5 6.5"})),Mn=({size:t=18})=>H(t,s("path",{d:"M15 5l-7 7 7 7"}));var En=({size:t=18})=>H(t,s("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"})),In=({size:t=14})=>H(t,s("path",{d:"M5 12.5l4.2 4.2L19 7"})),Fn=({size:t=14})=>H(t,s("path",{d:"M4 12a8 8 0 1 0 2.3-5.6M4 4v4h4"}));var _t={current:null};function Wi(t){return t?t.speaking?"speaking":t.agentState==="thinking"?"reasoning":t.agentState==="listening"||t.phase==="live"?"listening":"idle":"idle"}function Ln({client:t,call:e,state:n,src:i,onStatus:a}){let r=B(null),[o,l]=T(!1),h=B(!1),d=(()=>{try{return new URL(i).origin}catch{return null}})(),f=(c,g)=>{let b=r.current?.contentWindow;b&&d&&b.postMessage({cx:"face",...c},d,g??[])};I(()=>{if(!d){a("unavailable");return}let c=!1,g=x=>{if(x.source!==r.current?.contentWindow||x.origin!==d)return;let m=x.data;m?.cx==="face"&&(m.type==="loaded"?(h.current=!0,l(!0),t.videoAvatar().then(y=>{c||(y?f({type:"init",avatar:y}):a("unavailable"))}).catch(()=>!c&&a("unavailable"))):m.type==="ready"?(_t.current=typeof m.faceEmotion=="string"?m.faceEmotion:null,a("ready")):m.type==="unavailable"&&a("unavailable"))};window.addEventListener("message",g);let b=setTimeout(()=>!c&&!h.current&&a("unavailable"),15e3);return()=>{c=!0,clearTimeout(b),window.removeEventListener("message",g)}},[t,d]);let _=Wi(n);return I(()=>{o&&f({type:"state",state:_})},[_,o]),I(()=>{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?s("iframe",{ref:r,class:"face-frame",src:i,title:"","aria-hidden":"true",tabIndex:-1,allow:"autoplay",sandbox:"allow-scripts allow-same-origin",referrerpolicy:"strict-origin"}):null}function Hi(){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 Yi=()=>typeof matchMedia<"u"&&matchMedia("(prefers-reduced-motion: reduce)").matches;function xe({agent:t,shot:e,talking:n=!1,still:i=!1,class:a}){let r=B(null),[o,l]=T({w:0,h:0}),[h,d]=T(null),[f,_]=T({}),c=t.video,g=c?.anchor?.alphaUrl??c?.anchor?.url??null,b=!i&&!Yi()&&Hi(),x=c?.clips.idle?.alphaUrl??null,m=c?.clips.talking?.alphaUrl??x;if(sn(()=>{let U=r.current;if(!U)return;let O=()=>l({w:U.clientWidth,h:U.clientHeight});if(O(),typeof ResizeObserver>"u")return;let Y=new ResizeObserver(O);return Y.observe(U),()=>Y.disconnect()},[]),!c||!g)return s("div",{ref:r,class:`portrait portrait--initial ${a??""}`,"aria-hidden":"true",children:s("span",{children:(t.name||"?").slice(0,1).toUpperCase()})});let y=h?h.w/h.h:.75,w=_n(c,h?.w??0,h?.h??0),L=o.w&&o.h?vn(w,y,o.w,o.h,e):null,P=L?{width:`${L.width}px`,height:`${L.height}px`,left:`${L.left}px`,top:`${L.top}px`}:{opacity:0},R=b&&!!x&&!!f.idle,W=b&&!!m&&m!==x&&!!f.talk&&n;return s("div",{ref:r,class:`portrait ${a??""}`,"aria-hidden":"true",children:[s("img",{class:"portrait__media",src:g,alt:"",draggable:!1,style:{...P,opacity:L?R?0:1:0},onLoad:U=>{let O=U.currentTarget;d({w:O.naturalWidth,h:O.naturalHeight})}}),b&&x?s(zn,{src:x,style:P,visible:R&&!W,onReady:()=>_(U=>({...U,idle:!0}))}):null,b&&m&&m!==x?s(zn,{src:m,style:P,visible:W,onReady:()=>_(U=>({...U,talk:!0}))}):null]})}function zn({src:t,style:e,visible:n,onReady:i}){let a=B(null);return I(()=>{let r=a.current;r&&(n?r.play().catch(()=>{}):r.pause())},[n]),s("video",{ref:a,class:"portrait__media portrait__clip",src:t,muted:!0,loop:!0,playsInline:!0,preload:"auto",style:{...e,opacity:n?1:0},onLoadedData:i})}var bt="cxyz:greeted",Dn="cxyz:introduced";function ye(t,e){try{return e!==void 0&&localStorage.setItem(t,e),localStorage.getItem(t)}catch{return null}}function ji(){try{let t=window.AudioContext??window.webkitAudioContext,e=new t,n=e.currentTime;[660,880].forEach((i,a)=>{let r=e.createOscillator(),o=e.createGain();r.type="sine",r.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),r.connect(o).connect(e.destination),r.start(n+a*.16),r.stop(n+a*.16+.55)}),setTimeout(()=>{e.close()},1200)}catch{}}function qi(t){let[e,n]=T(t.chat.messages),[i,a]=T(t.chat.isBusy);return I(()=>{let r=t.chat.on("messages",n),o=t.chat.on("busy",a);return()=>{r(),o()}},[t]),{messages:e,busy:i}}function Vi(t){let[e,n]=T(t.call),[i,a]=T(t.call?.state??null),[r,o]=T([]);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",h=>o(d=>[...d.filter(f=>f.id!==h.id),h].slice(-4))),e.on("captionRemoved",h=>o(d=>d.filter(f=>f.id!==h)))];return()=>l.forEach(h=>h())},[e]),{call:e,state:i,captions:r,reset:()=>n(null)}}function Ki(t,e){let[n,i]=T(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 Xi(t,e,n){I(()=>{if(!t||!n)return;let i=0,a=0,r=()=>{let o=t.voiceLevel();a=a*.7+o*.3,e.current?.style.setProperty("--cx-lvl",a.toFixed(3)),i=requestAnimationFrame(r)};return i=requestAnimationFrame(r),()=>cancelAnimationFrame(i)},[t,n,e])}function Un({parts:t}){return s(E,{children:t.map((e,n)=>e.t==="b"?s("strong",{children:e.v},n):e.t==="i"?s("em",{children:e.v},n):e.t==="code"?s("code",{children:e.v},n):e.t==="link"?s("a",{href:e.href,target:"_blank",rel:"noopener noreferrer nofollow",children:e.v},n):e.v.split(`
42
- `).map((i,a,r)=>s(E,{children:[i,a<r.length-1?s("br",{}):null]},`${n}.${a}`)))})}var Zi={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"}};function Ji({form:t,title:e,note:n,onSend:i,onSkip:a,skipLabel:r,initial:o}){let[l,h]=T(()=>({...o??{}})),[d,f]=T({}),[_,c]=T(null),[g,b]=T(!1),x=B(null);return I(()=>{setTimeout(()=>x.current?.focus({preventScroll:!0}),80)},[]),s("form",{class:"card",part:"details",onSubmit:async m=>{m.preventDefault(),b(!0),f({}),c(null);try{await i({name:l.name??"",email:l.email??"",...l.phone?{phone:l.phone}:{},...l.company?{company:l.company}:{}})}catch(y){let w=y.fields??{};Object.keys(w).length?f(w):c(y.message||u("sendFailed"))}finally{b(!1)}},children:[s("div",{class:"card__title",children:e}),n?s("div",{class:"card__note",children:n}):null,t.fields.map((m,y)=>{let w=Zi[m];return s("label",{class:"card__field",children:[s("span",{children:[u(w.label),m==="phone"||m==="company"?s("i",{children:[" \xB7 ",u("optional")]}):null]}),s("input",{ref:y===0?x:void 0,type:w.type,autocomplete:w.auto,required:m==="name"||m==="email",maxLength:m==="email"?254:120,value:l[m]??"","aria-invalid":d[m]?"true":void 0,onInput:L=>h(P=>({...P,[m]:L.currentTarget.value}))}),d[m]?s("em",{children:d[m]}):null]},m)}),s("div",{class:"card__consent",children:[t.consent,t.privacyUrl?s(E,{children:[" ",s("a",{href:t.privacyUrl,target:"_blank",rel:"noopener noreferrer",children:u("privacyPolicy")})]}):null]}),_?s("div",{class:"card__failed",children:_}):null,s("div",{class:"card__actions",children:[s("button",{type:"submit",class:"btn btn--accent btn--sm",disabled:g,children:g?u("sending"):u("send")}),s("button",{type:"button",class:"btn btn--ghost btn--sm",onClick:a,disabled:g,children:r})]})]})}function xt({items:t,onPick:e,children:n}){return!t.length&&!n?null:s("div",{class:"chips chips--start",part:"suggestions",children:[t.map(i=>s("button",{class:"chip",onClick:()=>e(i),children:i},i)),n]})}function Pn({text:t}){return s(E,{children:pn(t).map((e,n)=>e.t==="ul"?s("ul",{children:e.items.map((i,a)=>s("li",{children:s(Un,{parts:i})},a))},n):s("p",{children:s(Un,{parts:e.parts})},n))})}function Rn({client:t,config:e,bind:n,onView:i}){let a=t.agent,r=t.features,o=e.showChat&&r.chat,l=e.showCall&&r.call,[h,d]=T(e.open?o?"chat":"call":"closed"),[f,_]=T(!1),[c,g]=T(!1),{messages:b,busy:x}=qi(t),{call:m,state:y,captions:w,reset:L}=Vi(t),[P,R]=T(""),W=B(null),U=B(null),O=B(null),Y=e.subtitle??a.tagline,k=a.name||u("assistant"),[N,yt]=T(null);I(()=>{if(!o)return;let p=!0;return t.opening().then(C=>{p&&(fn(C?.strings),yt(C))}),()=>{p=!1}},[t,o]);let We=e.greeting||N?.teaser||"",vt=e.suggestions.length?e.suggestions:N?.suggestions??[],Bn=N?.greeting||u("greetingDefault",{name:k}),[ae,He]=T("loading"),[Ye,kt]=T(!1),[se,wt]=T(null),[Ct,Wn]=T(""),[je,qe]=T(null),[Ve,Ke]=T(null),j=he(p=>{d(p),i(p)},[i]),Q=he(()=>{_(!0),setTimeout(()=>{_(!1),j("closed")},200)},[j]),re=he(async()=>{try{let p=await t.chat.load();He(C=>C==="loading"?p.length?p.length:"empty":C)}catch{He(p=>p==="loading"?"empty":p)}},[t]),V=he((p=o?"chat":"call")=>{g(!1),ye(bt,"1"),j(p),p==="chat"&&re()},[o,j,re]);I(()=>n({open:V,close:Q}),[n,V,Q]),I(()=>{e.open&&o&&re()},[re,e.open,o]),I(()=>{if(!We||ye(bt))return;let p=setTimeout(()=>g(!0),e.greetingDelay*1e3);return()=>clearTimeout(p)},[We,e.greetingDelay]),I(()=>{if(h!=="chat"||Ye||ae==="loading")return;let p=setTimeout(()=>kt(!0),700);return()=>clearTimeout(p)},[h,Ye,ae]);let[Xe,Hn]=T(()=>!ye(Dn));I(()=>{if(!Xe)return;let p=setTimeout(()=>{Hn(!1),ye(Dn,"1")},5e3);return()=>clearTimeout(p)},[Xe]),I(()=>{if(h==="closed")return;let p=C=>{C.key==="Escape"&&Q()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[h,Q]),I(()=>{let p=W.current;p&&(p.scrollTop=p.scrollHeight)},[b,h,y?.phase]),I(()=>{h==="chat"&&setTimeout(()=>U.current?.focus({preventScroll:!0}),60)},[h]);let oe=e.face&&!!a.video,[ve,Yn]=T("loading"),S=y?.phase??"idle";I(()=>{if(!(S!=="ready"||!m)){if(ji(),h==="call"){if(!oe||ve!=="loading"){m.accept();return}let p=setTimeout(()=>m.accept(),3e3);return()=>clearTimeout(p)}if(typeof document<"u"&&document.hidden){let p=document.title;document.title=`\u25CF ${k} is ready for you`;let C=()=>{document.title=p,document.removeEventListener("visibilitychange",C)};document.addEventListener("visibilitychange",C)}}},[S,m,h,k,oe,ve]);let St=S==="live"||S==="connecting";Xi(m,O,St&&h==="call");let ke=Ki(y?.startedAt??null,S==="live"),Ze=Gi(m,y?.position??1),Je=()=>{let p=N?.details;if(p&&!se&&o){qe(p),j("chat"),re();return}Ge()},Tt=(p,C="")=>{wt(p),Wn(C),Ke(null);let ee=!!je;qe(null),ee&&Ge()},jn=async p=>{await t.sendDetails(p),Tt("sent",p.name.trim().split(/\s+/)[0]??"")},qn=()=>{t.declineDetails().catch(()=>{}),Tt("skipped")},Vn=async()=>{try{await t.chat.reset()}catch{return}He("empty"),kt(!1),wt(null),qe(null),Ke(null),R(""),yt(await t.opening(!0))},Ge=async()=>{j("call");try{await t.startCall({autoAccept:!1,...oe?{face:{emotion:()=>_t.current}}:{}})}catch{}},Qe=[...b].reverse().find(p=>p.detailsForm||p.askDetails)?.detailsForm??[...b].reverse().find(p=>p.askDetails)?.askDetails??N?.details??null,le=async p=>{let C=p.trim();if(!C||x)return;let ee=Qe&&se!=="sent"?wn(C):null;ee&&Qe&&Ke({form:Qe,values:ee}),R(""),U.current&&(U.current.style.height="");try{await t.chat.send(C)}catch{}},Kn=b.length>0&&b[b.length-1].role==="agent"&&b[b.length-1].streaming,we=b[b.length-1],At=we?.role==="agent"&&!we.streaming?we.askDetails:void 0,$=je?{form:je,kind:"call"}:Ve&&se!=="sent"&&!x?{form:Ve.form,kind:"typed",initial:Ve.values}:At&&!se?{form:At,kind:"invited"}:null;if(h==="closed"){let p=S==="queued"||S==="ready"||S==="live"||S==="connecting";return s("div",{class:`dock dock--${e.display}`,part:"launcher",children:[c?s("div",{class:"greeting",part:"greeting",role:"status",onClick:()=>V(),children:[We,s("button",{class:"greeting__close","aria-label":u("dismiss"),onClick:C=>{C.stopPropagation(),g(!1),ye(bt,"1")},children:s(Ne,{size:14})})]}):null,s("button",{class:`presence presence--${e.display} ${p?"presence--live":""}`,part:"presence","aria-label":p?S==="queued"?u("inLineToCall",{position:J(y?.position??1),name:k}):u("backToCallWith",{name:k}):o?u("chatWith",{name:k}):u("callName",{name:k}),onClick:()=>V(p||!o?"call":"chat"),children:[e.display==="bubble"?s("span",{class:"presence__ring"}):null,s("span",{class:"presence__face",children:s(xe,{agent:a,shot:e.display==="full"?yn:e.display==="half"?xn:Re})}),s("span",{class:"presence__dot"}),t.mode==="test"?s("span",{class:"testmode",title:"Test mode: this key only works on development sites",children:"TEST"}):null,S==="queued"?s("span",{class:"presence__badge","aria-hidden":"true",children:y?.position??1}):null,e.launcher==="bubble"&&!c?s("span",{class:"presence__label","aria-hidden":"true",children:p?S==="queued"?u("inLine",{position:J(y?.position??1)}):u("backToCall"):o?u("chatWith",{name:k}):u("callName",{name:k})}):null]}),e.launcher==="bubble"?null:s("div",{class:`acts ${Xe?"acts--labelled":""}`,part:"actions",children:[o?s("button",{class:"act","aria-label":u("chatWith",{name:k}),onClick:()=>V("chat"),children:[s(be,{size:20}),s("span",{class:"act__label","aria-hidden":"true",children:u("chat")})]}):null,l?s("button",{class:`act act--call ${p?"act--live":""}`,"aria-label":p?S==="queued"?u("inLineOpen",{position:J(y?.position??1)}):u("backToCall"):u("callName",{name:k}),onClick:()=>p?V("call"):Je(),children:[s(ie,{size:20}),s("span",{class:"act__label","aria-hidden":"true",children:p?S==="queued"?u("inLine",{position:J(y?.position??1)}):u("onCall"):u("call")}),S==="queued"?s("span",{class:"act__badge","aria-hidden":"true",children:y?.position??1}):null]}):null]})]})}let Xn=s("div",{class:"head",part:"header",children:[s("div",{class:"head__face",children:s(xe,{agent:a,shot:Re,talking:!!Kn})}),s("div",{class:"head__who",children:[s("div",{class:"head__name",children:k}),s("div",{class:"head__sub",children:[s("i",{}),x?u("typing"):Y||u("online")]})]}),h==="chat"&&b.length>0&&!x?s("button",{class:"icon-btn","aria-label":u("newConversation"),title:u("newConversation"),onClick:()=>{Vn()},children:s(En,{})}):null,l&&h==="chat"?s("button",{class:"icon-btn icon-btn--accent","aria-label":u("callName",{name:k}),title:u("callName",{name:k}),onClick:()=>m&&S!=="ended"?j("call"):Je(),children:s(ie,{size:18})}):null,s("button",{class:"icon-btn","aria-label":u("close"),onClick:Q,children:s(Ne,{})})]});if(h==="chat")return s("div",{class:`panel ${f?"is-closing":""}`,part:"panel",role:"dialog","aria-label":u("chatWith",{name:k}),children:[Xn,m&&(S==="queued"||S==="ready")?s("div",{class:"banner",part:"banner",role:"status",children:[s("div",{class:"banner__text",children:S==="queued"?s(E,{children:u("inLineFor",{position:J(y?.position??1),eta:Pe(y?.etaSeconds??null)})}):s(E,{children:[s("b",{children:u("readyForYou",{name:k})})," \xB7 ",u("secondsToJoin",{seconds:y?.holdSeconds??30})]})}),S==="ready"?s("button",{class:"btn btn--accent btn--glow",onClick:()=>{m.accept(),j("call")},children:u("join")}):s("button",{class:"btn",onClick:()=>j("call"),children:u("view")})]}):null,s("div",{class:"log",ref:W,role:"log","aria-live":"polite","aria-relevant":"additions",children:[b.length===0?s(E,{children:[s("div",{class:"empty",children:[s("div",{class:"empty__face",children:s(xe,{agent:a,shot:Re})}),s("div",{class:"empty__title",children:k}),Y?s("div",{class:"empty__body",children:Y}):null]}),ae==="loading"?null:Ye?s(E,{children:[s("div",{class:"msg msg--agent",part:"message message-agent",children:s(Pn,{text:Bn})}),$?null:s(xt,{items:vt,onPick:p=>{le(p)},children:l?s("button",{class:"chip chip--call",onClick:()=>m&&S!=="ended"?j("call"):Je(),children:[s(ie,{size:14})," ",u("callName",{name:k})]}):null})]}):s("div",{class:"msg msg--agent typing","aria-label":u("typingName",{name:k}),children:[s("i",{}),s("i",{}),s("i",{})]})]}):null,b.map(p=>p.role==="agent"&&p.streaming&&!p.text?s("div",{class:"msg msg--agent typing","aria-label":u("typingName",{name:k}),children:[s("i",{}),s("i",{}),s("i",{})]},p.id):s(E,{children:[s("div",{class:`msg msg--${p.role} ${p.failed?"msg--failed":""} ${p.streaming?"caret":""}`,part:`message message-${p.role}`,children:p.role==="agent"?s(Pn,{text:p.text}):p.text}),p===b[b.length-1]&&p.role==="agent"&&!p.streaming&&!x&&!$&&p.suggestions?.length?s(xt,{items:p.suggestions,onPick:C=>{le(C)}}):null,p.failed&&p.error?s("div",{class:"msg__why",role:"status",children:p.error}):p.failed?s("button",{class:"msg__retry",onClick:()=>{t.chat.retry(p.id).catch(()=>{})},children:[s(Fn,{})," ",u("notSent")]}):null]},p.id)),typeof ae=="number"&&b.length===ae&&N?.welcomeBack?s(E,{children:[s("div",{class:"msg msg--agent",part:"message message-agent",children:N.welcomeBack}),$?null:s(xt,{items:vt,onPick:p=>{le(p)}})]}):null,$?s(Ji,{form:$.form,initial:$.initial,title:$.kind==="call"?u("beforeYouCall",{name:k}):$.kind==="typed"?u("confirmDetails"):u("leaveDetails"),note:$.kind==="call"?u("detailsWhy"):$.kind==="typed"?u("detailsTyped"):null,onSend:jn,onSkip:qn,skipLabel:$.kind==="call"?u("skipAndCall"):u("notNow")},$.kind==="invited"?we?.id:$.kind):se==="sent"?s("div",{class:"notice",role:"status",children:[s(In,{})," ",Ct?u("thanksName",{name:Ct}):u("thanks")]}):null]}),s("form",{class:"compose",part:"composer",onSubmit:p=>{p.preventDefault(),le(P)},children:s("div",{class:"compose__box",children:[s("textarea",{ref:U,rows:1,value:P,maxLength:2e3,placeholder:e.placeholder===me.placeholder?u("message"):e.placeholder,"aria-label":u("message"),onInput:p=>{let C=p.currentTarget;R(C.value),C.style.height="auto",C.style.height=`${Math.min(120,C.scrollHeight)}px`},onKeyDown:p=>{p.key==="Enter"&&!p.shiftKey&&!p.isComposing&&(p.preventDefault(),le(P))}}),s("button",{class:"send",type:"submit","aria-label":u("send"),disabled:!P.trim()||x,children:s(An,{})})]})}),e.branding?s("div",{class:"foot",children:u("poweredBy").split("{brand}").map((p,C)=>s(E,{children:[C?s("a",{href:"https://character.xyz",target:"_blank",rel:"noopener noreferrer",children:"Character XYZ"}):null,p]},C))}):null]});let A=y,et=A?.position??1,Zn=Ze>1?(Ze-et)/(Ze-1):0,tt=74,Mt=2*Math.PI*tt,ce=A?.maxSeconds?A.maxSeconds-ke:null,Jn=A?.agentState??"idle",Gn=A?.speaking?u("speaking"):Jn==="thinking"?u("thinking"):u("listening"),Qn=!A||S==="ended"||S==="idle",nt=gn(A?.endReason??null,k);return s("div",{class:`panel ${f?"is-closing":""}`,part:"panel",role:"dialog","aria-label":u("callWith",{name:k}),children:s("div",{class:`stage ${oe&&ve==="ready"?"stage--face":""}`,ref:O,children:[s("div",{class:"stage__figure",style:{opacity:S==="queued"?.35:1,transition:"opacity .6s"},children:[s(xe,{agent:a,shot:bn,talking:!!A?.speaking}),oe?s("div",{class:`stage__face ${ve==="ready"?"is-ready":""}`,children:s(Ln,{client:t,call:m,state:A,src:e.faceUrl,onStatus:Yn})}):null]}),St?s("div",{class:"voice"}):null,s("div",{class:"stage__veil"}),s("div",{class:"stage__top",children:[S==="live"?s("span",{class:`badge ${ce!=null&&ce<=60?"badge--warn":""}`,role:"timer","aria-label":u("callTime"),children:[s("i",{}),ce!=null&&ce<=60?u("timeLeft",{time:Ue(ce)}):Ue(ke)]}):s("span",{}),s("div",{style:{display:"flex",gap:"6px"},children:[o?s("button",{class:"icon-btn","aria-label":u("chat"),title:u("chat"),onClick:()=>V("chat"),children:s(be,{size:18})}):null,s("button",{class:"icon-btn","aria-label":u("minimise"),onClick:Q,children:s(Ne,{})})]})]}),s("div",{class:"stage__bottom","aria-live":"polite",children:[S==="joining"||S==="connecting"?s(E,{children:[s("div",{class:"stage__name",children:k}),s("div",{class:"stage__status",children:[s("span",{class:"spinner"})," ",S==="joining"?u("connecting"):u("joining")]})]}):null,S==="queued"?s(E,{children:[s("div",{class:"line",role:"status","aria-label":u("inLineEta",{position:J(et),eta:Pe(A?.etaSeconds??null)}),children:[s("svg",{width:"168",height:"168",viewBox:"0 0 168 168",children:[s("circle",{class:"line__track",cx:"84",cy:"84",r:tt,fill:"none","stroke-width":"7"}),s("circle",{class:"line__fill",cx:"84",cy:"84",r:tt,fill:"none","stroke-width":"7","stroke-linecap":"round","stroke-dasharray":Mt,"stroke-dashoffset":Mt*(1-Math.max(.06,Zn))})]}),s("div",{children:[s("div",{class:"line__num",children:J(et)}),s("div",{class:"line__lbl",children:u("lineLabel")})]})]}),s("div",{class:"title",children:u("onOtherCalls",{name:k})}),s("div",{class:"note",children:u(o?"yourTurnChat":"yourTurn",{eta:Pe(A?.etaSeconds??null)})}),s("div",{class:"btn-row",children:[o?s("button",{class:"btn btn--accent",onClick:()=>V("chat"),children:[s(be,{size:18})," ",u("keepChatting")]}):null,s("button",{class:"btn",onClick:()=>{m?.hangUp()},children:u("leaveLine")})]})]}):null,S==="ready"?s(E,{children:[s("div",{class:"title",children:u("readyForYou",{name:k})}),s("div",{class:"note",children:u("joinWithin",{seconds:A?.holdSeconds??30})}),s("button",{class:"btn btn--accent btn--glow",onClick:()=>m?.accept(),children:[s(ie,{size:18})," ",u("joinCall")]})]}):null,S==="live"?s(E,{children:[s("div",{class:"stage__name",children:k}),s("div",{class:"stage__status",children:[A?.speaking?s("span",{class:"wave","aria-hidden":"true",children:[.6,1,.75,1,.55].map((p,C)=>s("i",{style:{"--k":p}},C))}):null,A?.muted?u("muted"):Gn]}),s("div",{class:"captions",children:w.slice(-2).map((p,C,ee)=>s("div",{class:`captions__line ${C===ee.length-1?"captions__line--now":""}`,children:p.role==="visitor"?u("you",{text:p.text}):p.text},p.id))}),s("div",{class:"controls",children:[s("div",{class:"ctl",children:[s("button",{class:`round ${A?.muted?"round--on":""}`,"aria-pressed":A?.muted,"aria-label":A?.muted?u("unmute"):u("mute"),onClick:()=>m?.setMuted(!A?.muted),children:A?.muted?s(Tn,{size:22}):s(Sn,{size:22})}),s("span",{class:"round__label",children:A?.muted?u("unmute"):u("mute")})]}),s("div",{class:"ctl",children:[s("button",{class:"round round--end","aria-label":u("endCall"),onClick:()=>{m?.hangUp()},children:s(Cn,{size:26})}),s("span",{class:"round__label",children:u("end")})]}),A?.speaking?s("div",{class:"ctl",children:[s("button",{class:"round","aria-label":u("interruptName",{name:k}),onClick:()=>m?.interrupt(),children:s(Mn,{size:22})}),s("span",{class:"round__label",children:u("interrupt")})]}):null]})]}):null,Qn?s(E,{children:[s("div",{class:"title",children:A?nt.title:u("callName",{name:k})}),s("div",{class:"note",children:A?A.endReason==="hangup"&&ke?`${Ue(ke)} \xB7 ${nt.body}`:A.error??nt.body:u("talkWith",{name:k})}),s("div",{class:"btn-row",children:[l&&A?.endReason!=="credits"&&A?.endReason!=="unavailable"&&A?.endReason!=="daily_limit"?s("button",{class:"btn btn--accent",onClick:()=>{L(),Ge()},children:[s(ie,{size:18})," ",A?u("callAgain"):u("startCall")]}):null,o?s("button",{class:"btn",onClick:()=>V("chat"),children:[s(be,{size:18})," ",u("chat")]}):null]})]}):null]})]})})}function Gi(t,e){let n=B({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 Nn=`
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
+ `),h=l;try{h=JSON.parse(l)}catch{}e({event:s,data:h})}return n}function pi(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 ui=.09,hi=350,fi=25e3,gi=()=>({phase:"idle",callId:null,position:null,etaSeconds:null,holdSeconds:null,maxSeconds:null,startedAt:null,endReason:null,muted:!1,speaking:!1,agentState:"idle",error:null}),mi=class extends lt{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",gi()),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"}),Lt();try{this.mic=await li({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 ee(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 O?t:new O("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 xe(this.apiUrl,`/sdk/v1/calls/${encodeURIComponent(this.s.callId)}/events`,{token:e,signal:this.eventsAbort.signal});t=0,await zt(n,i=>this.onServerEvent(i.event,i.data),this.eventsAbort.signal)}catch(e){if(e?.name==="AbortError")return;if(e instanceof O&&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"}),fi),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>ui){if(this.loudSince??(this.loudSince=i),i-this.loudSince>=hi){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=pi(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 ri({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 xe(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})}},_i=0,Ft=t=>`${t}_${Date.now().toString(36)}_${(_i++).toString(36)}`,xi=class extends lt{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)}async load(){if(this.loaded)return this.list;let t=await this.session.token(),e=await ee(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 O("invalid","Say something first.");if(this.busy)throw new O("rate_limited","Wait for the reply first.");this.setBusy(!0);let n={id:Ft("local"),role:"visitor",text:e,createdAt:new Date().toISOString()},i={id:Ft("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 xe(this.apiUrl,"/sdk/v1/chat/messages",{method:"POST",body:{text:e},token:a,signal:this.abort.signal}),o=null,l=null;if(await zt(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 O("unknown",l??"The reply was cut off. Try again.");let h=o;return this.replace(i.id,h),h}catch(a){let s=a instanceof O?a:new O("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 xe(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 O("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)}},bi=()=>{let t=new Map;return{get:e=>t.get(e)??null,set:(e,n)=>{t.set(e,n)}}},yi=()=>({get(t){try{return globalThis.localStorage?.getItem(t)??null}catch{return null}},set(t,e){try{globalThis.localStorage?.setItem(t,e)}catch{}}}),vi=60,ki=class{constructor(t){if(v(this,"src",t),v(this,"current",null),v(this,"inflight",null),!t.publishableKey&&!t.getSessionToken)throw new O("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-vi>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 ee(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 ee(this.src.apiUrl,"/sdk/v1/session",{token:t}),token:t}}},wi="https://api.character.xyz",ct=class Dt extends lt{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),this.chat=new xi(e,n)}static async init(e){let n=(e.apiUrl??wi).replace(/\/+$/,"");if(e.publishableKey&&/^cxyz_sk_/.test(e.publishableKey))throw new O("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"?bi():e.storage&&typeof e.storage=="object"?e.storage:yi(),a=new ki({apiUrl:n,agentId:e.agentId,publishableKey:e.publishableKey,getSessionToken:e.getSessionToken,store:i}),s=await a.refresh();return new Dt(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 ee(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 ee(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 ee(this.apiUrl,"/sdk/v1/lead",{token:n,body:{...e,consent:!0,...i?{page:i}:{}}})}async declineDetails(){let e=await this.session.token();await ee(this.apiUrl,"/sdk/v1/lead/decline",{token:e,method:"POST",body:{}})}async startCall(e={}){if(this.destroyed)throw new O("invalid","This client was destroyed.");if(!this.features.call)throw new O("forbidden","Calls are not available on this site.");if(this.call)return this.call;let n=new mi(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.clear()}};var Ne,E,Nt,Ci,te,Ut,$t,Bt,dt,ze,be,Wt,ht,pt,ut,Si,Re={},Pe=[],Ti=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,$e=Array.isArray;function G(t,e){for(var n in e)t[n]=e[n];return t}function ft(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function Ai(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?Ne.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 De(t,o,i,a,null)}function De(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??++Nt,__i:-1,__u:0};return a==null&&E.vnode!=null&&E.vnode(s),s}function I(t){return t.children}function Ue(t,e){this.props=t,this.context=e}function ae(t,e){if(e==null)return t.__?ae(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"?ae(t):null}function Mi(t){if(t.__P&&t.__d){var e=t.__v,n=e.__e,i=[],a=[],s=G({},e);s.__v=e.__v+1,E.vnode&&E.vnode(s),gt(t.__P,s,e,t.__n,t.__P.namespaceURI,32&e.__u?[n]:null,i,n??ae(e),!!(32&e.__u),a),s.__v=e.__v,s.__.__k[s.__i]=s,Vt(i,s,a),e.__e=e.__=null,s.__e!=n&&Ht(s)}}function Ht(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}),Ht(t)}function Rt(t){(!t.__d&&(t.__d=!0)&&te.push(t)&&!Oe.__r++||Ut!=E.debounceRendering)&&((Ut=E.debounceRendering)||$t)(Oe)}function Oe(){try{for(var t,e=1;te.length;)te.length>e&&te.sort(Bt),t=te.shift(),e=te.length,Mi(t)}finally{te.length=Oe.__r=0}}function Yt(t,e,n,i,a,s,o,l,h,d,f){var m,c,g,y,b,_,k=i&&i.__k||Pe,w=e.length;for(h=Ei(n,e,k,h,w),m=0;m<w;m++)(g=n.__k[m])!=null&&(c=g.__i!=-1&&k[g.__i]||Re,g.__i=m,_=gt(t,g,c,a,s,o,l,h,d,f),y=g.__e,g.ref&&c.ref!=g.ref&&(c.ref&&mt(c.ref,null,g),f.push(g.ref,g.__c||y,g)),b==null&&y!=null&&(b=y),4&g.__u?(h=jt(g,h,t),c.__e&&(c.__e=null)):typeof g.type=="function"&&_!==void 0?h=_:y&&(h=y.nextSibling),g.__u&=-7);return n.__e=b,h}function Ei(t,e,n,i,a){var s,o,l,h,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]=De(null,o,null,null,null):$e(o)?o=t.__k[s]=De(I,{children:o},null,null,null):o.constructor===void 0&&o.__b>0?o=t.__k[s]=De(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):t.__k[s]=o,h=s+c,o.__=t,o.__b=t.__b+1,l=null,(d=o.__i=Ii(o,n,h,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!=h&&(d==h-1?c--:d==h+1?c++:(d>h?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=ae(l)),Xt(l,l));return i}function jt(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=jt(i[a],e,n));return e}t.__e!=e&&(e&&t.type&&!e.parentNode&&(e=ae(t)),e=n.insertBefore(t.__e,e||null));do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function Ii(t,e,n,i){var a,s,o,l=t.key,h=t.type,d=e[n],f=d!=null&&(2&d.__u)==0;if(d===null&&l==null||f&&l==d.key&&h==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&&h==d.type)return o}return-1}function Pt(t,e,n){e[0]=="-"?t.setProperty(e,n??""):t[e]=n==null?"":typeof n!="number"||Ti.test(e)?n:n+"px"}function Le(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||Pt(t.style,e,"");if(n)for(e in n)i&&n[e]==i[e]||Pt(t.style,e,n[e])}else if(e[0]=="o"&&e[1]=="n")s=e!=(e=e.replace(Wt,"$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[be]=i[be]:(n[be]=ht,t.addEventListener(e,s?ut:pt,s)):t.removeEventListener(e,s?ut:pt,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 Ot(t){return function(e){if(this.l){var n=this.l[e.type+t];if(e[ze]==null)e[ze]=ht++;else if(e[ze]<n[be])return;return n(E.event?E.event(e):e)}}}function gt(t,e,n,i,a,s,o,l,h,d){var f,m,c,g,y,b,_,k,w,P,N,$,C,L,R,q,x=e.type;if(e.constructor!==void 0)return null;128&n.__u&&(h=!!(32&n.__u),s=[l=e.__e=n.__e]),(f=E.__b)&&f(e);e:if(typeof x=="function"){m=o.length;try{if(w=e.props,P=x.prototype&&x.prototype.render,N=(f=x.contextType)&&i[f.__c],$=f?N?N.props.value:f.__:i,n.__c?k=(c=e.__c=n.__c).__=c.__E:(P?e.__c=c=new x(w,$):(e.__c=c=new Ue(w,$),c.constructor=x,c.render=Li),N&&N.sub(c),c.state||(c.state={}),c.__n=i,g=c.__d=!0,c.__h=[],c._sb=[]),P&&c.__s==null&&(c.__s=c.state),P&&x.getDerivedStateFromProps!=null&&(c.__s==c.state&&(c.__s=G({},c.__s)),G(c.__s,x.getDerivedStateFromProps(w,c.__s))),y=c.props,b=c.state,c.__v=e,g)P&&x.getDerivedStateFromProps==null&&c.componentWillMount!=null&&c.componentWillMount(),P&&c.componentDidMount!=null&&c.__h.push(c.componentDidMount);else{if(P&&x.getDerivedStateFromProps==null&&w!==y&&c.componentWillReceiveProps!=null&&c.componentWillReceiveProps(w,$),e.__v==n.__v||!c.__e&&c.shouldComponentUpdate!=null&&c.shouldComponentUpdate(w,c.__s,$)===!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(B){B&&(B.__=e)}),Pe.push.apply(c.__h,c._sb),c._sb=[],c.__h.length&&o.push(c),l=ae(n);break e}c.componentWillUpdate!=null&&c.componentWillUpdate(w,c.__s,$),P&&c.componentDidUpdate!=null&&c.__h.push(function(){c.componentDidUpdate(y,b,_)})}if(c.context=$,c.props=w,c.__P=t,c.__e=!1,C=E.__r,L=0,P)c.state=c.__s,c.__d=!1,C&&C(e),f=c.render(c.props,c.state,c.context),Pe.push.apply(c.__h,c._sb),c._sb=[];else do c.__d=!1,C&&C(e),f=c.render(c.props,c.state,c.context),c.state=c.__s;while(c.__d&&++L<25);c.state=c.__s,c.getChildContext!=null&&(i=G(G({},i),c.getChildContext())),P&&!g&&c.getSnapshotBeforeUpdate!=null&&(_=c.getSnapshotBeforeUpdate(y,b)),R=f!=null&&f.type===I&&f.key==null?Kt(f.props.children):f,l=Yt(t,$e(R)?R:[R],e,n,i,a,s,o,l,h,d),c.base=e.__e,e.__u&=-161,c.__h.length&&o.push(c),k&&(c.__E=c.__=null)}catch(B){if(o.length=m,e.__v=null,h||s!=null){if(B.then){for(e.__u|=h?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(q=s.length;q--;)ft(s[q])}else e.__e=n.__e;e.__k==null&&(e.__k=n.__k||[]),B.then||qt(e),E.__e(B,e,n)}}else s==null&&e.__v==n.__v?(e.__k=n.__k,e.__e=n.__e):l=e.__e=Fi(n.__e,e,n,i,a,s,o,h,d);return(f=E.diffed)&&f(e),128&e.__u?void 0:l}function qt(t){t&&(t.__c&&(t.__c.__e=!0),t.__k&&t.__k.some(qt))}function Vt(t,e,n){for(var i=0;i<n.length;i++)mt(n[i],n[++i],n[++i]);E.__c&&E.__c(e,t),t.some(function(a){try{t=a.__h,a.__h=[],t.some(function(s){s.call(a)})}catch(s){E.__e(s,a.__v)}})}function Kt(t){return typeof t!="object"||t==null||t.__b>0?t:$e(t)?t.map(Kt):t.constructor!==void 0?null:G({},t)}function Fi(t,e,n,i,a,s,o,l,h){var d,f,m,c,g,y,b,_=n.props||Re,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&&(E.__m&&E.__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&&Ne.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||Le(t,d,null,g,a);for(d in k)g=k[d],d=="children"?c=g:d=="dangerouslySetInnerHTML"?f=g:d=="value"?y=g:d=="checked"?b=g:l&&typeof g!="function"||_[d]===g||Le(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=""),Yt(e.type=="template"?t.content:t,$e(c)?c:[c],e,n,i,w=="foreignObject"?"http://www.w3.org/1999/xhtml":a,s,o,s?s[0]:n.__k&&ae(n,0),l,h),s!=null)for(d=s.length;d--;)ft(s[d]);l&&w!="textarea"||(d="value",w=="progress"&&y==null?t.removeAttribute("value"):y!=null&&(y!==t[d]||w=="progress"&&!y||w=="option"&&y!=_[d])&&Le(t,d,y,_[d],a),d="checked",b!=null&&b!=t[d]&&Le(t,d,b,_[d],a))}return t}function mt(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){E.__e(a,n)}}function Xt(t,e,n){var i,a;if(E.unmount&&E.unmount(t),(i=t.ref)&&(i.current&&i.current!=t.__e||mt(i,null,e)),(i=t.__c)!=null){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(s){E.__e(s,e)}i.base=i.__P=i.__n=null}if(i=t.__k)for(a=0;a<i.length;a++)i[a]&&Xt(i[a],e,n||typeof t.type!="function");n||ft(t.__e),t.__c=t.__=t.__e=void 0}function Li(t,e,n){return this.constructor(t,n)}function _t(t,e,n){var i,a,s,o;e==document&&(e=document.documentElement),E.__&&E.__(t,e),a=(i=typeof n=="function")?null:n&&n.__k||e.__k,s=[],o=[],gt(e,t=(!i&&n||e).__k=Ai(I,null,[t]),a||Re,Re,e.namespaceURI,!i&&n?[n]:a?null:e.firstChild?Ne.call(e.childNodes):null,s,!i&&n?n:a?a.__e:e.firstChild,i,o),Vt(s,t,o),t.props.children=null}Ne=Pe.slice,E={__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}},Nt=0,Ci=function(t){return t!=null&&t.constructor===void 0},Ue.prototype.setState=function(t,e){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=G({},this.state),typeof t=="function"&&(t=t(G({},n),this.props)),t&&G(n,t),t!=null&&this.__v&&(e&&this._sb.push(e),Rt(this))},Ue.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),Rt(this))},Ue.prototype.render=I,te=[],$t=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Bt=function(t,e){return t.__v.__b-e.__v.__b},Oe.__r=0,dt=Math.random().toString(8),ze="__d"+dt,be="__a"+dt,Wt=/(PointerCapture)$|Capture$/i,ht=0,pt=Ot(!1),ut=Ot(!0),Si=0;var ce,D,xt,Zt,ye=0,rn=[],U=E,Jt=U.__b,Gt=U.__r,Qt=U.diffed,en=U.__c,tn=U.unmount,nn=U.__;function We(t,e){U.__h&&U.__h(D,t,ye||e),ye=0;var n=D.__H||(D.__H={__:[],__h:[]});return t>=n.__.length&&n.__.push({}),n.__[t]}function S(t){return ye=1,zi(ln,t)}function zi(t,e,n){var i=We(ce++,2);if(i.t=t,!i.__c&&(i.__=[n?n(e):ln(void 0,e),function(l){var h=i.__N?i.__N[0]:i.__[0],d=i.t(h,l);h!==d&&(i.__N=[d,i.__[1]],i.__c.setState({}))}],i.__c=D,!D.__f)){var a=function(l,h,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 y=g.__[0];g.__=g.__N,g.__N=void 0,y!==g.__[0]&&(m=!0)}}),s){var c=s.call(this,l,h,d);return f?c||m:c}return!f||m};D.__f=!0;var s=D.shouldComponentUpdate,o=D.componentWillUpdate;D.componentWillUpdate=function(l,h,d){if(this.__e){var f=s;s=void 0,a(l,h,d),s=f}o&&o.call(this,l,h,d)},D.shouldComponentUpdate=a}return i.__N||i.__}function F(t,e){var n=We(ce++,3);!U.__s&&yt(n.__H,e)&&(n.__=t,n.u=e,D.__H.__h.push(n))}function sn(t,e){var n=We(ce++,4);!U.__s&&yt(n.__H,e)&&(n.__=t,n.u=e,D.__h.push(n))}function j(t){return ye=5,on(function(){return{current:t}},[])}function on(t,e){var n=We(ce++,7);return yt(n.__H,e)&&(n.__=t(),n.__H=e,n.__h=t),n.__}function ve(t,e){return ye=8,on(function(){return t},e)}function Di(){for(var t;t=rn.shift();){var e=t.__H;if(t.__P&&e)try{e.__h.some(Be),e.__h.some(bt),e.__h=[]}catch(n){e.__h=[],U.__e(n,t.__v)}}}U.__b=function(t){D=null,Jt&&Jt(t)},U.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),nn&&nn(t,e)},U.__r=function(t){Gt&&Gt(t),ce=0;var e=(D=t.__c).__H;e&&(xt===D?(e.__h=[],D.__h=[],e.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(e.__h.some(Be),e.__h.some(bt),e.__h=[],ce=0)),xt=D},U.diffed=function(t){Qt&&Qt(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(rn.push(e)!==1&&Zt===U.requestAnimationFrame||((Zt=U.requestAnimationFrame)||Ui)(Di)),e.__H.__.some(function(n){n.u&&(n.__H=n.u,n.u=void 0)})),xt=D=null},U.__c=function(t,e){e.some(function(n){try{n.__h.some(Be),n.__h=n.__h.filter(function(i){return!i.__||bt(i)})}catch(i){e.some(function(a){a.__h&&(a.__h=[])}),e=[],U.__e(i,n.__v)}}),en&&en(t,e)},U.unmount=function(t){tn&&tn(t);var e,n=t.__c;n&&n.__H&&(n.__H.__.some(function(i){try{Be(i)}catch(a){e=a}}),n.__H=void 0,e&&U.__e(e,n.__v))};var an=typeof requestAnimationFrame=="function";function Ui(t){var e,n=function(){clearTimeout(i),an&&cancelAnimationFrame(e),setTimeout(t)},i=setTimeout(n,35);an&&(e=requestAnimationFrame(n))}function Be(t){var e=D,n=t.__c;typeof n=="function"&&(t.__c=void 0,n()),D=e}function bt(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 ln(t,e){return typeof e=="function"?e(t):e}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"},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},vt=(t,e=200)=>typeof t=="string"?t.slice(0,e):void 0;function Ri(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 Se(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=Ri(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=vt(e.subtitle,80)??n.subtitle,n.greeting=vt(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=vt(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 cn(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}function pn(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 He(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 dn(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 un(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=>dn(a.replace(/^\s*[-*•]\s+/,"")))}):e.push({t:"p",parts:dn(n)})}return e}var Oi={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",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."},hn={},fn=!0;function gn(t){hn=t??{},fn=!t||!Object.keys(t).length}function p(t,e){let n=hn[t]??Oi[t];if(e)for(let i in e)n=n.split(`{${i}}`).join(String(e[i]));return n}function ne(t){return fn?pn(t):String(t)}function Ye(t){if(t==null)return"";if(t<60)return p("etaSoon");let e=Math.round(t/60);return e<60?p("etaMin",{n:e}):p("etaHr",{n:Math.round(e/60)})}function mn(t,e){let n=(i,a)=>({title:p(i),body:p(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 _n={cx:.5,cy:.12,span:.06};function bn(t,e,n){let i=t?.face?.eyes,a=t?.face?.chin;if(!i||!a||!e||!n)return _n;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}:_n}var je={faceFraction:.26,at:{x:.5,y:.5}},yn={faceFraction:.14,at:{x:.5,y:.34},keepCrown:!0},vn={faceFraction:.16,at:{x:.5,y:.22},keepCrown:!0},kn={fit:"height"},Ni=1.8,xn=.04;function wn(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,h=l+(t.cy-t.span*Ni)*s;return a.keepCrown&&h<i*xn&&(l+=i*xn-h),{width:o,height:s,left:n*a.at.x-t.cx*o,top:l}}var Cn=/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/,$i=/\+?\d[\d\s().-]{5,}\d/g,Bi=/\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,Wi=new Set(["interested","looking","from","with","here","trying","not","a","an","the","just","also","happy","keen","curious","calling","sure","fine","good","okay","ok"]);function Sn(t){let e={},n=t.match(Cn)?.[0];n&&(e.email=n.replace(/[.,;:]+$/,""));for(let a of t.replace(Cn," ").matchAll($i)){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(Bi)?.[1];if(i){let a=i.split(/\s+/).filter(o=>!Wi.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 Hi=0;function r(t,e,n,i,a,s){e||(e={});var o,l,h=e;if("ref"in h)for(l in h={},e)l=="ref"?o=e[l]:h[l]=e[l];var d={type:t,props:h,key:n,ref:o,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--Hi,__i:-1,__u:0,__source:a,__self:s};if(typeof t=="function"&&(o=t.defaultProps))for(l in o)h[l]===void 0&&(h[l]=o[l]);return E.vnode&&E.vnode(d),d}var V=(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}),Te=({size:t=20})=>V(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"})),de=({size:t=20})=>V(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"})),Tn=({size:t=22})=>V(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"})),An=({size:t=20})=>V(t,r(I,{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"})]})),Mn=({size:t=20})=>V(t,r(I,{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"})]})),qe=({size:t=18})=>V(t,r("path",{d:"M6 6l12 12M18 6L6 18"})),En=({size:t=18})=>V(t,r("path",{d:"M12 19V5M5.5 11.5L12 5l6.5 6.5"})),In=({size:t=18})=>V(t,r("path",{d:"M15 5l-7 7 7 7"}));var Fn=({size:t=18})=>V(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"})),Ln=({size:t=14})=>V(t,r("path",{d:"M5 12.5l4.2 4.2L19 7"})),zn=({size:t=14})=>V(t,r("path",{d:"M4 12a8 8 0 1 0 2.3-5.6M4 4v4h4"}));var kt={current:null};function Yi(t){return t?t.speaking?"speaking":t.agentState==="thinking"?"reasoning":t.agentState==="listening"||t.phase==="live"?"listening":"idle":"idle"}function Dn({client:t,call:e,state:n,src:i,onStatus:a}){let s=j(null),[o,l]=S(!1),h=j(!1),d=(()=>{try{return new URL(i).origin}catch{return null}})(),f=(c,g)=>{let y=s.current?.contentWindow;y&&d&&y.postMessage({cx:"face",...c},d,g??[])};F(()=>{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"?(h.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 y=setTimeout(()=>!c&&!h.current&&a("unavailable"),15e3);return()=>{c=!0,clearTimeout(y),window.removeEventListener("message",g)}},[t,d]);let m=Yi(n);return F(()=>{o&&f({type:"state",state:m})},[m,o]),F(()=>{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,y=()=>{let b=e.audible();b&&f({type:"clock",corr:b.corr,ms:b.ms}),g=requestAnimationFrame(y)};return g=requestAnimationFrame(y),()=>{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 ji(){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 qi=()=>typeof matchMedia<"u"&&matchMedia("(prefers-reduced-motion: reduce)").matches;function Ae({agent:t,shot:e,talking:n=!1,still:i=!1,full:a=!1,class:s}){let o=j(null),[l,h]=S({w:0,h:0}),[d,f]=S(null),[m,c]=S({}),[g,y]=S({}),b=t.video,_=(z,W,ie)=>!a&&z&&!g[ie]?z:W,k=b?.anchor?.alphaUrl??b?.anchor?.url??null,w=_(b?.anchor?.smallUrl,k,"anchor"),P=w!==k,N=!i&&!qi()&&ji(),$=b?.clips.idle,C=b?.clips.talking??$,L=_($?.smallUrl,$?.alphaUrl??null,"idle"),R=_(C?.smallUrl,C?.alphaUrl??null,"talk")??L,[q,x]=S(a);if(F(()=>{n&&x(!0)},[n]),sn(()=>{let z=o.current;if(!z)return;let W=()=>h({w:z.clientWidth,h:z.clientHeight});if(W(),typeof ResizeObserver>"u")return;let ie=new ResizeObserver(W);return ie.observe(z),()=>ie.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 Q=(b.anchor?.width&&b.anchor?.height?{w:b.anchor.width,h:b.anchor.height}:null)??(d&&!P?d:null),pe=bn(b,Q?.w??0,Q?.h??0),Y=l.w&&l.h&&Q?wn(pe,Q.w/Q.h,l.w,l.h,e):null,ue=Y?{width:`${Y.width}px`,height:`${Y.height}px`,left:`${Y.left}px`,top:`${Y.top}px`}:{},Z=!!Y&&N&&!!L&&!!m.idle,re=!!Y&&N&&!!R&&R!==L&&!!m.talk&&n,he=!!Y&&(!!d||Z);return r("div",{ref:o,class:`portrait ${s??""}`,"aria-hidden":"true",children:[r("img",{class:"portrait__media",src:w,alt:"",draggable:!1,style:{...ue,opacity:Y&&d&&!Z?1:0},onLoad:z=>{let W=z.currentTarget;f({w:W.naturalWidth,h:W.naturalHeight})},onError:()=>P&&y(z=>({...z,anchor:!0}))}),N&&L?r(Un,{src:L,style:ue,visible:Z&&!re,onReady:()=>c(z=>({...z,idle:!0})),onFail:()=>y(z=>({...z,idle:!0}))}):null,N&&q&&R&&R!==L?r(Un,{src:R,style:ue,visible:re,onReady:()=>c(z=>({...z,talk:!0})),onFail:()=>y(z=>({...z,talk:!0}))}):null,r("span",{class:`portrait__sparkle${he?" is-done":""}`,children:[r("i",{}),r("i",{}),r("i",{})]})]})}function Un({src:t,style:e,visible:n,onReady:i,onFail:a}){let s=j(null);return F(()=>{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",Rn="cxyz:introduced";function Me(t,e){try{return e!==void 0&&localStorage.setItem(t,e),localStorage.getItem(t)}catch{return null}}function Vi(){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 Ki(t){let[e,n]=S(t.chat.messages),[i,a]=S(t.chat.isBusy);return F(()=>{let s=t.chat.on("messages",n),o=t.chat.on("busy",a);return()=>{s(),o()}},[t]),{messages:e,busy:i}}function Xi(t){let[e,n]=S(t.call),[i,a]=S(t.call?.state??null),[s,o]=S([]);return F(()=>t.on("call",l=>l&&n(l)),[t]),F(()=>{if(!e)return;a(e.state),o([]);let l=[e.on("state",a),e.on("caption",h=>o(d=>[...d.filter(f=>f.id!==h.id),h].slice(-4))),e.on("captionRemoved",h=>o(d=>d.filter(f=>f.id!==h)))];return()=>l.forEach(h=>h())},[e]),{call:e,state:i,captions:s,reset:()=>n(null)}}function Zi(t,e){let[n,i]=S(Date.now());return F(()=>{if(!e)return;let a=setInterval(()=>i(Date.now()),1e3);return()=>clearInterval(a)},[e]),t?Math.max(0,(n-t)/1e3):0}function Ji(t,e,n){F(()=>{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 Pn({parts:t}){return r(I,{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(I,{children:[i,a<s.length-1?r("br",{}):null]},`${n}.${a}`)))})}var Gi={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 On(){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 Qi({form:t,title:e,note:n,onSend:i,onSkip:a,skipLabel:s,initial:o}){let[l,h]=S(()=>({...o??{}})),d=t.reasonOptions??[],f=t.fields.includes("reason"),[m,c]=S(()=>{if(!f)return"";let C=On();return C?d.includes(C)?C:"__other":""}),[g,y]=S(()=>{if(!f)return"";let C=On();return C&&!d.includes(C)?C:""}),[b,_]=S({}),[k,w]=S(null),[P,N]=S(!1),$=j(null);return F(()=>{setTimeout(()=>$.current?.focus({preventScroll:!0}),80)},[]),r("form",{class:"card",part:"details",onSubmit:async C=>{C.preventDefault(),N(!0),_({}),w(null);try{let L=(m==="__other"?g:m).trim();await i({name:l.name??"",email:l.email??"",...l.phone?{phone:l.phone}:{},...l.company?{company:l.company}:{},...f&&L?{reason:L}:{}})}catch(L){let R=L.fields??{};Object.keys(R).length?_(R):w(L.message||p("sendFailed"))}finally{N(!1)}},children:[r("div",{class:"card__title",children:e}),n?r("div",{class:"card__note",children:n}):null,t.fields.map((C,L)=>{let R=Gi[C],q=C==="reason"?t.reasonLabel||p("reasonField"):p(R.label);return r("label",{class:"card__field",children:[r("span",{children:[q,C==="phone"||C==="company"||C==="reason"?r("i",{children:[" \xB7 ",p("optional")]}):null]}),C==="reason"?d.length?r(I,{children:[r("select",{value:m,onChange:x=>c(x.currentTarget.value),children:[r("option",{value:"",children:p("reasonChoose")}),d.map(x=>r("option",{value:x,children:x},x)),r("option",{value:"__other",children:p("reasonOther")})]}),m==="__other"?r("input",{type:"text",maxLength:500,placeholder:p("reasonPlaceholder"),value:g,onInput:x=>y(x.currentTarget.value)}):null]}):r("textarea",{rows:2,maxLength:500,placeholder:p("reasonPlaceholder"),value:g,onInput:x=>y(x.currentTarget.value)}):r("input",{ref:L===0?$:void 0,type:R.type,autocomplete:R.auto,required:C==="name"||C==="email",maxLength:C==="email"?254:120,value:l[C]??"","aria-invalid":b[C]?"true":void 0,onInput:x=>h(B=>({...B,[C]:x.currentTarget.value}))}),b[C]?r("em",{children:b[C]}):null]},C)}),r("div",{class:"card__consent",children:[t.consent,t.privacyUrl?r(I,{children:[" ",r("a",{href:t.privacyUrl,target:"_blank",rel:"noopener noreferrer",children:p("privacyPolicy")})]}):null]}),k?r("div",{class:"card__failed",children:k}):null,r("div",{class:"card__actions",children:[r("button",{type:"submit",class:"btn btn--accent btn--sm",disabled:P,children:P?p("sending"):p("send")}),r("button",{type:"button",class:"btn btn--ghost btn--sm",onClick:a,disabled:P,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(I,{children:un(t).map((e,n)=>e.t==="ul"?r("ul",{children:e.items.map((i,a)=>r("li",{children:r(Pn,{parts:i})},a))},n):r("p",{children:r(Pn,{parts:e.parts})},n))})}function $n({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,[h,d]=S(e.open?o?"chat":"call":"closed"),[f,m]=S(!1),[c,g]=S(!1),{messages:y,busy:b}=Ki(t),{call:_,state:k,captions:w,reset:P}=Xi(t),[N,$]=S(""),C=j(null),L=j(null),R=j(null),q=e.subtitle??a.tagline,x=a.name||p("assistant"),[B,Q]=S(null);F(()=>{if(!o)return;let u=!0;return t.opening().then(T=>{u&&(gn(T?.strings),Q(T))}),()=>{u=!1}},[t,o]);let pe=e.greeting||B?.teaser||"",Y=e.suggestions.length?e.suggestions:B?.suggestions??[],ue=B?.greeting||p("greetingDefault",{name:x}),[Z,re]=S("loading"),[he,z]=S(!1),[W,ie]=S(null),[St,Yn]=S(""),[Ze,Je]=S(null),[Ge,Qe]=S(null),K=ve(u=>{d(u),i(u)},[i]),se=ve(()=>{m(!0),setTimeout(()=>{m(!1),K("closed")},200)},[K]),fe=ve(async()=>{try{let u=await t.chat.load();re(T=>T==="loading"?u.length?u.length:"empty":T)}catch{re(u=>u==="loading"?"empty":u)}},[t]),J=ve((u=o?"chat":"call")=>{g(!1),Me(wt,"1"),K(u),u==="chat"&&fe()},[o,K,fe]);F(()=>n({open:J,close:se}),[n,J,se]),F(()=>{e.open&&o&&fe()},[fe,e.open,o]),F(()=>{if(!pe||Me(wt))return;let u=setTimeout(()=>g(!0),e.greetingDelay*1e3);return()=>clearTimeout(u)},[pe,e.greetingDelay]),F(()=>{if(h!=="chat"||he||Z==="loading")return;let u=setTimeout(()=>z(!0),700);return()=>clearTimeout(u)},[h,he,Z]);let[et,jn]=S(()=>!Me(Rn));F(()=>{if(!et)return;let u=setTimeout(()=>{jn(!1),Me(Rn,"1")},5e3);return()=>clearTimeout(u)},[et]),F(()=>{if(h==="closed")return;let u=T=>{T.key==="Escape"&&se()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[h,se]),F(()=>{let u=C.current;u&&(u.scrollTop=u.scrollHeight)},[y,h,k?.phase]),F(()=>{h==="chat"&&setTimeout(()=>L.current?.focus({preventScroll:!0}),60)},[h]);let ge=e.face&&!!a.video,[Ee,qn]=S("loading"),A=k?.phase??"idle";F(()=>{if(!(A!=="ready"||!_)){if(Vi(),h==="call"){if(!ge||Ee!=="loading"){_.accept();return}let u=setTimeout(()=>_.accept(),3e3);return()=>clearTimeout(u)}if(typeof document<"u"&&document.hidden){let u=document.title;document.title=`\u25CF ${x} is ready for you`;let T=()=>{document.title=u,document.removeEventListener("visibilitychange",T)};document.addEventListener("visibilitychange",T)}}},[A,_,h,x,ge,Ee]);let Tt=A==="live"||A==="connecting";Ji(_,R,Tt&&h==="call");let Ie=Zi(k?.startedAt??null,A==="live"),tt=ea(_,k?.position??1),nt=()=>{let u=B?.details;if(u&&!W&&o){Je(u),K("chat"),fe();return}it()},At=(u,T="")=>{ie(u),Yn(T),Qe(null);let oe=!!Ze;Je(null),oe&&it()},Vn=async u=>{await t.sendDetails(u),At("sent",u.name.trim().split(/\s+/)[0]??"")},Kn=()=>{t.declineDetails().catch(()=>{}),At("skipped")},Xn=async()=>{try{await t.chat.reset()}catch{return}re("empty"),z(!1),ie(null),Je(null),Qe(null),$(""),Q(await t.opening(!0))},it=async()=>{K("call");try{await t.startCall({autoAccept:!1,...ge?{face:{emotion:()=>kt.current}}:{}})}catch{}},at=[...y].reverse().find(u=>u.detailsForm||u.askDetails)?.detailsForm??[...y].reverse().find(u=>u.askDetails)?.askDetails??B?.details??null,me=async u=>{let T=u.trim();if(!T||b)return;let oe=at&&W!=="sent"?Sn(T):null;oe&&at&&Qe({form:at,values:oe}),$(""),L.current&&(L.current.style.height="");try{await t.chat.send(T)}catch{}},Fe=y[y.length-1],Mt=Fe?.role==="agent"&&!Fe.streaming?Fe.askDetails:void 0,H=Ze?{form:Ze,kind:"call"}:Ge&&W!=="sent"&&!b?{form:Ge.form,kind:"typed",initial:Ge.values}:Mt&&!W?{form:Mt,kind:"invited"}:null;if(h==="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:()=>J(),children:[pe,r("button",{class:"greeting__close","aria-label":p("dismiss"),onClick:T=>{T.stopPropagation(),g(!1),Me(wt,"1")},children:r(qe,{size:14})})]}):null,r("button",{class:`presence presence--${e.display} ${u?"presence--live":""}`,part:"presence","aria-label":u?A==="queued"?p("inLineToCall",{position:ne(k?.position??1),name:x}):p("backToCallWith",{name:x}):o?p("chatWith",{name:x}):p("callName",{name:x}),onClick:()=>J(u||!o?"call":"chat"),children:[e.display==="bubble"?r("span",{class:"presence__ring"}):null,r("span",{class:"presence__face",children:r(Ae,{agent:a,shot:e.display==="full"?kn:e.display==="half"?vn:je})}),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"?p("inLine",{position:ne(k?.position??1)}):p("backToCall"):o?p("chatWith",{name:x}):p("callName",{name:x})}):null]}),e.launcher==="bubble"?null:r("div",{class:`acts ${et?"acts--labelled":""}`,part:"actions",children:[o?r("button",{class:"act","aria-label":p("chatWith",{name:x}),onClick:()=>J("chat"),children:[r(Te,{size:20}),r("span",{class:"act__label","aria-hidden":"true",children:p("chat")})]}):null,l?r("button",{class:`act act--call ${u?"act--live":""}`,"aria-label":u?A==="queued"?p("inLineOpen",{position:ne(k?.position??1)}):p("backToCall"):p("callName",{name:x}),onClick:()=>u?J("call"):nt(),children:[r(de,{size:20}),r("span",{class:"act__label","aria-hidden":"true",children:u?A==="queued"?p("inLine",{position:ne(k?.position??1)}):p("onCall"):p("call")}),A==="queued"?r("span",{class:"act__badge","aria-hidden":"true",children:k?.position??1}):null]}):null]})]})}let Zn=r("div",{class:"head",part:"header",children:[r("div",{class:"head__face",children:r(Ae,{agent:a,shot:je})}),r("div",{class:"head__who",children:[r("div",{class:"head__name",children:x}),r("div",{class:"head__sub",children:[r("i",{}),b?p("typing"):q||p("online")]})]}),h==="chat"&&y.length>0&&!b?r("button",{class:"icon-btn","aria-label":p("newConversation"),title:p("newConversation"),onClick:()=>{Xn()},children:r(Fn,{})}):null,l&&h==="chat"?r("button",{class:"icon-btn icon-btn--accent","aria-label":p("callName",{name:x}),title:p("callName",{name:x}),onClick:()=>_&&A!=="ended"?K("call"):nt(),children:r(de,{size:18})}):null,r("button",{class:"icon-btn","aria-label":p("close"),onClick:se,children:r(qe,{})})]});if(h==="chat")return r("div",{class:`panel ${f?"is-closing":""}`,part:"panel",role:"dialog","aria-label":p("chatWith",{name:x}),children:[Zn,_&&(A==="queued"||A==="ready")?r("div",{class:"banner",part:"banner",role:"status",children:[r("div",{class:"banner__text",children:A==="queued"?r(I,{children:p("inLineFor",{position:ne(k?.position??1),eta:Ye(k?.etaSeconds??null)})}):r(I,{children:[r("b",{children:p("readyForYou",{name:x})})," \xB7 ",p("secondsToJoin",{seconds:k?.holdSeconds??30})]})}),A==="ready"?r("button",{class:"btn btn--accent btn--glow",onClick:()=>{_.accept(),K("call")},children:p("join")}):r("button",{class:"btn",onClick:()=>K("call"),children:p("view")})]}):null,r("div",{class:"log",ref:C,role:"log","aria-live":"polite","aria-relevant":"additions",children:[y.length===0?r(I,{children:[r("div",{class:"empty",children:[r("div",{class:"empty__face",children:r(Ae,{agent:a,shot:je})}),r("div",{class:"empty__title",children:x}),q?r("div",{class:"empty__body",children:q}):null]}),Z==="loading"?null:he?r(I,{children:[r("div",{class:"msg msg--agent",part:"message message-agent",children:r(Nn,{text:ue})}),H?null:r(Ct,{items:Y,onPick:u=>{me(u)},children:l?r("button",{class:"chip chip--call",onClick:()=>_&&A!=="ended"?K("call"):nt(),children:[r(de,{size:14})," ",p("callName",{name:x})]}):null})]}):r("div",{class:"msg msg--agent typing","aria-label":p("typingName",{name:x}),children:[r("i",{}),r("i",{}),r("i",{})]})]}):null,y.map(u=>u.role==="agent"&&u.streaming&&!u.text?r("div",{class:"msg msg--agent typing","aria-label":p("typingName",{name:x}),children:[r("i",{}),r("i",{}),r("i",{})]},u.id):r(I,{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===y[y.length-1]&&u.role==="agent"&&!u.streaming&&!b&&!H&&u.suggestions?.length?r(Ct,{items:u.suggestions,onPick:T=>{me(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(zn,{})," ",p("notSent")]}):null]},u.id)),typeof Z=="number"&&y.length===Z&&B?.welcomeBack?r(I,{children:[r("div",{class:"msg msg--agent",part:"message message-agent",children:B.welcomeBack}),H?null:r(Ct,{items:Y,onPick:u=>{me(u)}})]}):null,H?r(Qi,{form:H.form,initial:H.initial,title:H.kind==="call"?p("beforeYouCall",{name:x}):H.kind==="typed"?p("confirmDetails"):p("leaveDetails"),note:H.kind==="call"?p("detailsWhy"):H.kind==="typed"?p("detailsTyped"):null,onSend:Vn,onSkip:Kn,skipLabel:H.kind==="call"?p("skipAndCall"):p("notNow")},H.kind==="invited"?Fe?.id:H.kind):W==="sent"?r("div",{class:"notice",role:"status",children:[r(Ln,{})," ",St?p("thanksName",{name:St}):p("thanks")]}):null]}),r("form",{class:"compose",part:"composer",onSubmit:u=>{u.preventDefault(),me(N)},children:r("div",{class:"compose__box",children:[r("textarea",{ref:L,rows:1,value:N,maxLength:2e3,placeholder:e.placeholder===Ce.placeholder?p("message"):e.placeholder,"aria-label":p("message"),onInput:u=>{let T=u.currentTarget;$(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(),me(N))}}),r("button",{class:"send",type:"submit","aria-label":p("send"),disabled:!N.trim()||b,children:r(En,{})})]})}),e.branding?r("div",{class:"foot",children:p("poweredBy").split("{brand}").map((u,T)=>r(I,{children:[T?r("a",{href:"https://character.xyz",target:"_blank",rel:"noopener noreferrer",children:"Character XYZ"}):null,u]},T))}):null]});let M=k,rt=M?.position??1,Jn=tt>1?(tt-rt)/(tt-1):0,st=74,Et=2*Math.PI*st,_e=M?.maxSeconds?M.maxSeconds-Ie:null,Gn=M?.agentState??"idle",Qn=M?.speaking?p("speaking"):Gn==="thinking"?p("thinking"):p("listening"),ei=!M||A==="ended"||A==="idle",ot=mn(M?.endReason??null,x);return r("div",{class:`panel ${f?"is-closing":""}`,part:"panel",role:"dialog","aria-label":p("callWith",{name:x}),children:r("div",{class:`stage ${ge&&Ee==="ready"?"stage--face":""}`,ref:R,children:[r("div",{class:"stage__figure",style:{opacity:A==="queued"?.35:1,transition:"opacity .6s"},children:[r(Ae,{agent:a,shot:yn,talking:!!M?.speaking,full:!0}),ge?r("div",{class:`stage__face ${Ee==="ready"?"is-ready":""}`,children:r(Dn,{client:t,call:_,state:M,src:e.faceUrl,onStatus:qn})}):null]}),Tt?r("div",{class:"voice"}):null,r("div",{class:"stage__veil"}),r("div",{class:"stage__top",children:[A==="live"?r("span",{class:`badge ${_e!=null&&_e<=60?"badge--warn":""}`,role:"timer","aria-label":p("callTime"),children:[r("i",{}),_e!=null&&_e<=60?p("timeLeft",{time:He(_e)}):He(Ie)]}):r("span",{}),r("div",{style:{display:"flex",gap:"6px"},children:[o?r("button",{class:"icon-btn","aria-label":p("chat"),title:p("chat"),onClick:()=>J("chat"),children:r(Te,{size:18})}):null,r("button",{class:"icon-btn","aria-label":p("minimise"),onClick:se,children:r(qe,{})})]})]}),r("div",{class:"stage__bottom","aria-live":"polite",children:[A==="joining"||A==="connecting"?r(I,{children:[r("div",{class:"stage__name",children:x}),r("div",{class:"stage__status",children:[r("span",{class:"spinner"})," ",A==="joining"?p("connecting"):p("joining")]})]}):null,A==="queued"?r(I,{children:[r("div",{class:"line",role:"status","aria-label":p("inLineEta",{position:ne(rt),eta:Ye(M?.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:st,fill:"none","stroke-width":"7"}),r("circle",{class:"line__fill",cx:"84",cy:"84",r:st,fill:"none","stroke-width":"7","stroke-linecap":"round","stroke-dasharray":Et,"stroke-dashoffset":Et*(1-Math.max(.06,Jn))})]}),r("div",{children:[r("div",{class:"line__num",children:ne(rt)}),r("div",{class:"line__lbl",children:p("lineLabel")})]})]}),r("div",{class:"title",children:p("onOtherCalls",{name:x})}),r("div",{class:"note",children:p(o?"yourTurnChat":"yourTurn",{eta:Ye(M?.etaSeconds??null)})}),r("div",{class:"btn-row",children:[o?r("button",{class:"btn btn--accent",onClick:()=>J("chat"),children:[r(Te,{size:18})," ",p("keepChatting")]}):null,r("button",{class:"btn",onClick:()=>{_?.hangUp()},children:p("leaveLine")})]})]}):null,A==="ready"?r(I,{children:[r("div",{class:"title",children:p("readyForYou",{name:x})}),r("div",{class:"note",children:p("joinWithin",{seconds:M?.holdSeconds??30})}),r("button",{class:"btn btn--accent btn--glow",onClick:()=>_?.accept(),children:[r(de,{size:18})," ",p("joinCall")]})]}):null,A==="live"?r(I,{children:[r("div",{class:"stage__name",children:x}),r("div",{class:"stage__status",children:[M?.speaking?r("span",{class:"wave","aria-hidden":"true",children:[.6,1,.75,1,.55].map((u,T)=>r("i",{style:{"--k":u}},T))}):null,M?.muted?p("muted"):Qn]}),r("div",{class:"captions",children:w.slice(-2).map((u,T,oe)=>r("div",{class:`captions__line ${T===oe.length-1?"captions__line--now":""}`,children:u.role==="visitor"?p("you",{text:u.text}):u.text},u.id))}),r("div",{class:"controls",children:[r("div",{class:"ctl",children:[r("button",{class:`round ${M?.muted?"round--on":""}`,"aria-pressed":M?.muted,"aria-label":M?.muted?p("unmute"):p("mute"),onClick:()=>_?.setMuted(!M?.muted),children:M?.muted?r(Mn,{size:22}):r(An,{size:22})}),r("span",{class:"round__label",children:M?.muted?p("unmute"):p("mute")})]}),r("div",{class:"ctl",children:[r("button",{class:"round round--end","aria-label":p("endCall"),onClick:()=>{_?.hangUp()},children:r(Tn,{size:26})}),r("span",{class:"round__label",children:p("end")})]}),M?.speaking?r("div",{class:"ctl",children:[r("button",{class:"round","aria-label":p("interruptName",{name:x}),onClick:()=>_?.interrupt(),children:r(In,{size:22})}),r("span",{class:"round__label",children:p("interrupt")})]}):null]})]}):null,ei?r(I,{children:[r("div",{class:"title",children:M?ot.title:p("callName",{name:x})}),r("div",{class:"note",children:M?M.endReason==="hangup"&&Ie?`${He(Ie)} \xB7 ${ot.body}`:M.error??ot.body:p("talkWith",{name:x})}),r("div",{class:"btn-row",children:[l&&M?.endReason!=="credits"&&M?.endReason!=="unavailable"&&M?.endReason!=="daily_limit"?r("button",{class:"btn btn--accent",onClick:()=>{P(),it()},children:[r(de,{size:18})," ",M?p("callAgain"):p("startCall")]}):null,o?r("button",{class:"btn",onClick:()=>J("chat"),children:[r(Te,{size:18})," ",p("chat")]}):null]})]}):null]})]})})}function ea(t,e){let n=j({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 Bn=`
43
43
  :host {
44
44
  --cx-accent: #7c5cff;
45
45
  --cx-accent-ink: #fff;
@@ -249,7 +249,10 @@ button:focus-visible, textarea:focus-visible, a:focus-visible { outline: 2px sol
249
249
  .card__field { display: flex; flex-direction: column; gap: 5px; font-size: 12px; font-weight: 600; color: var(--cx-ink-2); }
250
250
  .card__field i { font-style: normal; font-weight: 400; color: var(--cx-ink-3); }
251
251
  .card__field input { height: 40px; padding: 0 12px; border-radius: 10px; border: 1px solid var(--cx-line); background: var(--cx-bubble); color: var(--cx-ink); font: inherit; font-size: 14px; font-weight: 400; outline: none; transition: border-color .2s; }
252
- .card__field input:focus { border-color: var(--cx-accent); }
252
+ .card__field select, .card__field textarea { padding: 0 12px; border-radius: 10px; border: 1px solid var(--cx-line); background: var(--cx-bubble); color: var(--cx-ink); font: inherit; font-size: 14px; font-weight: 400; outline: none; transition: border-color .2s; }
253
+ .card__field select { height: 40px; }
254
+ .card__field textarea { padding: 10px 12px; min-height: 64px; resize: vertical; }
255
+ .card__field input:focus, .card__field select:focus, .card__field textarea:focus { border-color: var(--cx-accent); }
253
256
  .card__field input[aria-invalid="true"] { border-color: #e5484d; }
254
257
  .card__field em { font-style: normal; font-weight: 400; color: #e5484d; }
255
258
  .card__consent { font-size: 11.5px; line-height: 1.45; color: var(--cx-ink-3); }
@@ -339,6 +342,15 @@ button:focus-visible, textarea:focus-visible, a:focus-visible { outline: 2px sol
339
342
  /* ------------------------------------------------------------ portrait */
340
343
  .portrait { position: relative; width: 100%; height: 100%; overflow: hidden; }
341
344
  .portrait__media { position: absolute; max-width: none; transition: opacity .35s ease; user-select: none; -webkit-user-drag: none; }
345
+ .portrait__sparkle { position: absolute; inset: 0; pointer-events: none; transition: opacity .45s ease; }
346
+ .portrait__sparkle.is-done { opacity: 0; }
347
+ .portrait__sparkle i { position: absolute; width: 10px; height: 10px; background: var(--cx-accent); opacity: 0; transform: scale(.4);
348
+ clip-path: polygon(50% 0,61% 39%,100% 50%,61% 61%,50% 100%,39% 61%,0 50%,39% 39%); animation: cx-tw 1.6s ease-in-out infinite; }
349
+ .portrait__sparkle i:nth-child(1) { left: 36%; top: 28% }
350
+ .portrait__sparkle i:nth-child(2) { left: 58%; top: 44%; animation-delay: .5s }
351
+ .portrait__sparkle i:nth-child(3) { left: 44%; top: 60%; animation-delay: 1s }
352
+ @keyframes cx-tw { 50% { opacity: .8; transform: scale(1) } }
353
+ @media (prefers-reduced-motion: reduce) { .portrait__sparkle i { animation: none; opacity: .45; } }
342
354
  .portrait--initial { display: grid; place-items: center; font-size: 26px; font-weight: 700; color: var(--cx-accent); }
343
355
 
344
356
  /* ------------------------------------------------------------ test-mode ribbon */
@@ -375,5 +387,5 @@ button:focus-visible, textarea:focus-visible, a:focus-visible { outline: 2px sol
375
387
  *, *::before, *::after { animation-duration: .01ms !important; animation-iteration-count: 1 !important; transition-duration: .01ms !important; }
376
388
  .presence__ring { animation: none; }
377
389
  }
378
- `;var Oe="character-xyz";function $n(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,r]=[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*r>.45?"#14121a":"#ffffff"}function Qi(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,r]=[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*r}function On(t){for(let e of[document.body,document.documentElement]){if(!e)continue;let n=Qi(getComputedStyle(e).backgroundColor);if(n!==null)return n<.22}return!!t?.matches}var ea=["publishable-key","agent","api-url","position","mode","accent","greeting","open"],$e=class extends HTMLElement{constructor(){super(...arguments);q(this,"options",null);q(this,"client",null);q(this,"api",null);q(this,"pendingOpen",null);q(this,"booted",!1);q(this,"mq",null);q(this,"stage",null);q(this,"onSchemeChange",()=>requestAnimationFrame(this.onScheme));q(this,"onScheme",()=>{this.dataset.mode==="auto"&&(this.dataset.theme=On(this.mq)?"dark":"light")})}static get observedAttributes(){return ea}connectedCallback(){if(this.booted)return;this.booted=!0;let n=this.shadowRoot??this.attachShadow({mode:"open"}),i=document.createElement("style");i.textContent=Nn,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&&ut(null,this.stage),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()}fire(n,i){this.dispatchEvent(new CustomEvent(n,{detail:i,bubbles:!0,composed:!0}))}async boot(){let n={...this.options??{}},i=ln(Array.from(this.attributes)),a=n.publishableKey??i.publishableKey;try{this.client=await at.init({publishableKey:a,getSessionToken:n.getSessionToken,agentId:n.agentId??i.agent,apiUrl:n.apiUrl??i.apiUrl,storage:n.storage})}catch(l){let h=l instanceof D?l:new D("unknown",String(l?.message??l));console.warn(`[characterxyz] widget not shown: ${h.message}`),this.fire("cx-error",{code:h.code,message:h.message});return}if(!this.isConnected){this.client.destroy();return}let r=this.client,o=_e(me,r.appearance);if(o=_e(o,i),o=_e(o,n),!(o.showChat&&r.features.chat)&&!(o.showCall&&r.features.call)){console.warn("[characterxyz] widget not shown: neither chat nor calls are enabled for this site");return}this.applyTokens(o),r.on("call",l=>{l&&l.on("state",h=>this.fire("cx-call",{phase:h.phase,position:h.position,endReason:h.endReason}))}),r.on("error",l=>this.fire("cx-error",{code:l.code,message:l.message})),this.style.display="",ut(s(Rn,{client:r,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:r.agent.id,name:r.agent.name},features:r.features})}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=On(this.mq)?"dark":"light"):this.dataset.theme=n.mode;let i=(a,r)=>this.style.setProperty(a,r);i("--cx-accent",n.accent),i("--cx-accent-ink",$n(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 Be(){typeof customElements<"u"&&!customElements.get(Oe)&&customElements.define(Oe,$e)}function ta(t){Be();let e=document.createElement(Oe);return e.options=t,(t.container??document.body).appendChild(e),{element:e,open:n=>e.open(n),close:()=>e.close(),destroy:()=>e.remove()}}Be();export{at as CharacterXYZ,$e as CharacterXYZElement,D as CxError,me as DEFAULTS,Oe as TAG,_e as applyLayer,Be as define,$n as inkFor,ta as mount};
390
+ `;var Ve="character-xyz";function Hn(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 ta(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 Wn(t){for(let e of[document.body,document.documentElement]){if(!e)continue;let n=ta(getComputedStyle(e).backgroundColor);if(n!==null)return n<.22}return!!t?.matches}var na=["publishable-key","agent","api-url","position","mode","accent","greeting","open"],Ke=class extends HTMLElement{constructor(){super(...arguments);X(this,"options",null);X(this,"client",null);X(this,"api",null);X(this,"pendingOpen",null);X(this,"booted",!1);X(this,"mq",null);X(this,"stage",null);X(this,"onSchemeChange",()=>requestAnimationFrame(this.onScheme));X(this,"onScheme",()=>{this.dataset.mode==="auto"&&(this.dataset.theme=Wn(this.mq)?"dark":"light")})}static get observedAttributes(){return na}connectedCallback(){if(this.booted)return;this.booted=!0;let n=this.shadowRoot??this.attachShadow({mode:"open"}),i=document.createElement("style");i.textContent=Bn,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&&_t(null,this.stage),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()}fire(n,i){this.dispatchEvent(new CustomEvent(n,{detail:i,bubbles:!0,composed:!0}))}async boot(){let n={...this.options??{}},i=cn(Array.from(this.attributes)),a=n.publishableKey??i.publishableKey;try{this.client=await ct.init({publishableKey:a,getSessionToken:n.getSessionToken,agentId:n.agentId??i.agent,apiUrl:n.apiUrl??i.apiUrl,storage:n.storage})}catch(l){let h=l instanceof O?l:new O("unknown",String(l?.message??l));console.warn(`[characterxyz] widget not shown: ${h.message}`),this.fire("cx-error",{code:h.code,message:h.message});return}if(!this.isConnected){this.client.destroy();return}let s=this.client,o=Se(Ce,s.appearance);if(o=Se(o,i),o=Se(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",h=>this.fire("cx-call",{phase:h.phase,position:h.position,endReason:h.endReason}))}),s.on("error",l=>this.fire("cx-error",{code:l.code,message:l.message})),this.style.display="",_t(r($n,{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})}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=Wn(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",Hn(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 Xe(){typeof customElements<"u"&&!customElements.get(Ve)&&customElements.define(Ve,Ke)}function ia(t){Xe();let e=document.createElement(Ve);return e.options=t,(t.container??document.body).appendChild(e),{element:e,open:n=>e.open(n),close:()=>e.close(),destroy:()=>e.remove()}}Xe();export{ct as CharacterXYZ,Ke as CharacterXYZElement,O as CxError,Ce as DEFAULTS,Ve as TAG,Se as applyLayer,Xe as define,Hn as inkFor,ia as mount};
379
391
  //# sourceMappingURL=index.js.map