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