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