@sendbird/ai-agent-messenger-react 1.35.0 → 1.35.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +66 -66
- package/dist/index.d.ts +5 -1
- package/dist/index.js +2153 -2139
- package/package.json +4 -4
package/dist/index.cjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
"use strict";var ac=Object.defineProperty;var cc=(e,t,n)=>t in e?ac(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var y=(e,t,n)=>cc(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ue=require("@sendbird/chat"),l=require("react"),B=require("styled-components"),at=require("date-fns"),lc=require("date-fns/locale/en-US"),Fe=require("@sendbird/chat/message"),de=require("@sendbird/chat/aiAgent"),uc=require("react-dom"),We=require("@sendbird/chat/groupChannel"),dc=require("date-fns/isSameDay"),mc=require("dompurify"),Tr=e=>e&&e.__esModule?e:{default:e};function hc(e){if(e&&e.__esModule)return e;const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const fc=Tr(ue),a=hc(l),b=Tr(B),Ko=Tr(mc),Yo=e=>{try{return JSON.parse(e===""?"{}":e)}catch{return{}}},gc=e=>{const t=Yo(e);return typeof t=="object"&&t!==null?t:{}},Wo=e=>typeof e=="string"?gc(e):e??{},pc=e=>!!Wo(e).stream,hs=e=>{if(typeof e=="number"&&Number.isSafeInteger(e)&&e>0)return e;if(typeof e!="string"||e.trim().length===0)return;const t=Number(e);return Number.isSafeInteger(t)&&t>0?t:void 0},jo=e=>{const t=Wo(e),n=hs(t.user_message_id)??hs(t.respond_mesg_id);return{isStreaming:!!t.stream,hasResponseMetadata:Object.prototype.hasOwnProperty.call(t,"stream")||n!==void 0,...n!==void 0&&{userMessageId:n}}},bt="sb-agent",Xo="KEY_IMG_ASPECT_RATIO",lr="*/*",ee={BODY_MAX_WIDTH:244,WIDE_BODY_MAX_WIDTH:640,AVATAR_SIZE:26,BODY_TIME_GAP:4,HORIZONTAL_PADDING:12,GAP_GROUPED:2,GAP_UNGROUPED:16};var bn=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(bn||{}),Pt=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(Pt||{});const _c=e=>!!(e!=null&&e.cta_button),Ec=e=>{var t;return!!((t=e==null?void 0:e.citations)!=null&&t.length)},Zo=e=>!!(e!=null&&e.form)&&!e.form.canceled_at,Cc=e=>{var t;return Zo(e)&&!((t=e==null?void 0:e.form)!=null&&t.submitted_at)},bc=e=>{var t;return!!((t=e==null?void 0:e.suggested_replies)!=null&&t.length)},Ve=e=>{let t;return{enumerable:!0,get:()=>(t??(t=e()),t)}},kn=e=>Object.defineProperties({},{hasMessageTemplate:Ve(()=>!!(e!=null&&e.message_template)),hasCTAButton:Ve(()=>_c(e)),hasChallenge:Ve(()=>!!(e!=null&&e.challenge)),isThinking:Ve(()=>!!(e!=null&&e.is_thinking)),hasCSAT:Ve(()=>!!(e!=null&&e.csat)),hasSuggestedReplies:Ve(()=>bc(e)),hasCustomMessageTemplates:Ve(()=>{var t;return!!((t=e==null?void 0:e.custom_message_templates)!=null&&t.length)}),hasForm:Ve(()=>Zo(e)),hasActiveForm:Ve(()=>Cc(e)),hasSteward:Ve(()=>!!(e!=null&&e.steward)),hasCitations:Ve(()=>Ec(e))}),vc=e=>{const t=kn(e);return t.hasMessageTemplate||t.hasCTAButton||t.hasCSAT||t.hasSuggestedReplies||t.hasForm||t.hasSteward||t.hasCitations},Jo=e=>{var t;return!!((t=e==null?void 0:e.extendedMessagePayload)!=null&&t.steward)},yc=e=>e===Pt.COMPLETED||e===Pt.CANCELED?e:Pt.IN_PROGRESS,Kn=e=>Qe(e)&&!Jo(e),Qe=e=>!!e&&"sender"in e,Sc=e=>Qe(e)?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId),Ac=(e,t,n,r=!0)=>{if(!r||!Kn(e))return"single";const s=()=>{if(!Kn(t))return!1;const u=t.sender.userId===e.sender.userId,d=at.isSameMinute(t.createdAt,e.createdAt);return u&&d},o=()=>{if(!Kn(n))return!1;const u=n.sender.userId===e.sender.userId,d=at.isSameMinute(n.createdAt,e.createdAt);return u&&d},i=s(),c=o();return i&&c?"middle":i?"bottom":c?"top":"single"},st=(e,t)=>(()=>{var r;return Qe(e)?e.sender.userId:((r=e==null?void 0:e.sender)==null?void 0:r.userId)??void 0})()===t,Ne={isAdmin:e=>e.isAdminMessage(),isCSAT:e=>{var t;return e.isAdminMessage()&&!!((t=e.extendedMessagePayload)!=null&&t.csat)},isSteward:e=>Jo(e),isIncoming:(e,t)=>Qe(e)&&e.sender.userId!==t,isOutgoing:(e,t)=>Qe(e)&&(e.sender.userId===t||e.sendingStatus===Fe.SendingStatus.PENDING)},Ye=e=>e.startsWith("image/"),zt=e=>e.startsWith("video/"),Tc=e=>e.startsWith("audio/"),Qo=({name:e="",mimeType:t=""})=>t==="application/pdf"||/\.pdf$/i.test(e.trim()),Ir=(e,t)=>{if(e&&!e.startsWith(".")){const n=e.split(".").pop();if(n&&n!==e)return n.toUpperCase()}if(t){const[,n]=t.split("/");if(n)return n.toUpperCase()}return"FILE"},ei=e=>{var t;return e.messageType==="file"?e.message.length>0&&e.file.name!==e.message:e.messageType==="multipleFiles"?e.message.length>0&&((t=e.files[0])==null?void 0:t.name)!==e.message:e.message.length>0},Ic=e=>{if(e.message&&e.message.trim().length>0)return!0;const t=e.extendedMessagePayload;return vc(t)},Ln=e=>{switch(e){case"top":case"middle":return ee.GAP_GROUPED;default:return ee.GAP_UNGROUPED}},xc=(e,t)=>{const n=/```(\w+)?\n([\s\S]*?)```/g,r=[];let s=0;return e.replace(n,(o,...i)=>{const[c,u,d]=i;return s<d&&r.push({type:"text",value:e.slice(s,d).trim()}),r.push({type:"code",value:u.trim(),language:c?c.trim():"plaintext"}),s=d+o.length,o}),s<e.length&&r.push({type:"text",value:e.slice(s).trim()}),t?r.map(o=>o.type!=="text"?o:{...o,value:t(o.value)}):r},Rc=e=>e.replace(/\[([^\]]+)\](?!\()/g,"\\[$1\\]"),Mc=e=>e.replace(/([a-zA-Z0-9])_(?=[a-zA-Z0-9])/g,"$1\\_"),wc=e=>e.replace(/~~/g,"\\~\\~"),kc=e=>{let t=e;return t=Rc(t),t=Mc(t),t=wc(t),t},Lc=typeof navigator<"u"&&navigator.product==="ReactNative",fs=(e,t)=>{const n=r=>!t||t.length===0?!0:Qe(r)&&t.includes(r.sendingStatus);return Lc?e.find(n):e.findLast(n)};function le(){}function Oc(){const e=typeof navigator<"u"?navigator.userAgent:"",t=/iPad|iPhone|iPod/.test(e),n=/Android/.test(e);return t||n}function Nc(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return t.toString(16)}const Me={isStreaming(e){return pc(e.data)},isExplicitWelcomeMessage(e){var t;return((t=e.extendedMessagePayload)==null?void 0:t.bot_message_type)==="welcome"},isWelcomeMessage(e,t){var r;if(Me.isExplicitWelcomeMessage(e))return!0;if(((r=e.extendedMessagePayload)==null?void 0:r.bot_message_type)!==void 0||!st(e,t))return!1;const n=jo(e.data);return!n.isStreaming&&!n.hasResponseMetadata},isGeneratedMessage(e){var t;return((t=e.extendedMessagePayload)==null?void 0:t.bot_message_type)==="generated"},hasFeedback(e){var t;return!!((t=e.extendedMessagePayload)!=null&&t.feedback)}},Yn=`@${bt}`,Dc=({appId:e,aiAgentId:t,storage:n})=>{const r={templateBase:`${Yn}-template`,template:s=>`${r.templateBase}/templates/${s}`,templateToken:()=>`${r.templateBase}/tokens`,messengerSession:s=>{const o=Nc(`${e}/${t}/${s}`);return`${Yn}-udata/${o}`},anonUserSession:()=>`${Yn}-session/${e}/${t}`};return{template:{set:(s,o)=>n.set(r.template(s),o),get:s=>n.get(r.template(s)),setCachedToken:s=>n.set(r.templateToken(),s),getCachedToken:()=>n.get(r.templateToken()),clear:()=>{n.getKeys(r.templateBase).forEach(n.delete)}},messenger:{getSettings:s=>{try{const o=n.get(r.messengerSession(s));return o?JSON.parse(o):null}catch{return null}},setSettings:(s,o)=>{try{delete o.auto_created_user;const i=JSON.stringify(o);n.set(r.messengerSession(s),i)}catch{return}},getAnonUser:()=>{try{const s=n.get(r.anonUserSession());return s?JSON.parse(s):null}catch{return null}},setAnonUser:s=>{try{const o=JSON.stringify(s);n.set(r.anonUserSession(),o)}catch{return}},clear:s=>{try{s&&n.delete(r.messengerSession(s)),n.delete(r.anonUserSession())}catch{return}}}}},ti=(e,t,n={})=>{let r=null,s=null,o=null;const{leading:i=!0,trailing:c=!0}=n,u=(...d)=>{const m=Date.now();if(o===null||m-o>=t)i?(e(...d),o=m):(s=d,o=m);else if(s=d,c&&!r){const h=t-(m-o);r=setTimeout(()=>{s&&c&&(e(...s),o=Date.now()),r=null,s=null},h)}};return u.cancel=()=>{r&&(clearTimeout(r),r=null),s=null,o=null},u},$c=()=>{let e=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const n=(e+Math.random()*16)%16|0;return e=Math.floor(e/16),(t==="x"?n:n&3|8).toString(16)})};class Fc{constructor(t){y(this,"_params");this._params={aiAgentChannelFilter:(t==null?void 0:t.aiAgentChannelFilter)??de.AIAgentChannelFilter.INCLUDE,aiAgentConversationStatusFilter:(t==null?void 0:t.aiAgentConversationStatusFilter)??[de.ConversationStatus.OPEN,de.ConversationStatus.CLOSED],aiAgentIds:(t==null?void 0:t.aiAgentIds)??[],deskChannelFilter:(t==null?void 0:t.deskChannelFilter)??de.DeskChannelFilter.INCLUDE,pinnedChannelUrls:(t==null?void 0:t.pinnedChannelUrls)??[],copilotConversationOnly:(t==null?void 0:t.copilotConversationOnly)??!1,copilotSupportChannelUrl:t==null?void 0:t.copilotSupportChannelUrl}}get params(){return{...this._params}}match(t,n){const{pinnedChannelUrls:r,aiAgentChannelFilter:s,aiAgentConversationStatusFilter:o,aiAgentIds:i,deskChannelFilter:c}=this._params;return r!=null&&r.includes(t.url)?!0:t.isAIAgent?!(!t.conversation||s===de.AIAgentChannelFilter.EXCLUDE||i&&i.length>0&&!i.includes(t.conversation.aiAgentId)||o&&o.length>0&&!o.some(d=>{var m;return((m=t.conversation)==null?void 0:m.status)===d})):t.isDesk?c!==de.DeskChannelFilter.EXCLUDE:!1}}class ni extends We.BaseChannelCollection{constructor(n,r){const s=new Fc(r.filter),o=n,i=o.aiAgent._manager,c=r.limit??20,u=We.GroupChannelListOrder.LATEST_LAST_MESSAGE,d={getRemoteChannels:(m,h,f,g)=>i.getMyGroupChannels(m,h.params,g),changeLogSync:m=>{const{aiAgentChannelFilter:h,aiAgentIds:f,deskChannelFilter:g,pinnedChannelUrls:C,copilotConversationOnly:v,copilotSupportChannelUrl:_}=s.params,p={aiAgentChannelFilter:h,aiAgentIds:f,deskChannelFilter:g,pinnedChannelUrls:C,copilotConversationOnly:v,copilotSupportChannelUrl:_};return i.getMyGroupChannelChangeLogs(m,p,We.GroupChannelEventSource.SYNC_CHANNEL_CHANGELOGS)}};super(o.aiAgent._iid,{filter:s,order:u,limit:c,syncKeyPrefix:"aiAgent",fetcher:d});y(this,"_params");y(this,"_sdk");y(this,"_throttledOnChannelChanged");y(this,"_key");y(this,"_pendingChannels",[]);this._sdk=n,this._params=r,this._key=`clc-${$c()}`,this._throttledOnChannelChanged=ti(()=>{var g;const m=[...this._pendingChannels];this._pendingChannels=[];const h=new Map;for(const{channel:C,context:v}of m)h.delete(C.url),h.set(C.url,{channel:C,context:v});const f=new Map;for(const{channel:C,context:v}of h.values())f.has(v)||f.set(v,new Map),f.get(v).set(C.url,C);for(const[C,v]of f){const _=Array.from(v.values()),p=(g=this._sdk.currentUser)==null?void 0:g.userId,S=_.filter(T=>this.filter.match(T,p)),A=_.filter(T=>!this.filter.match(T,p)).map(T=>T.url);S.length>0&&this._base._addChannelsToView(S,C,!1),A.length>0&&this._removeChannels(A,C)}},250,{trailing:!0,leading:!0}),this._base._subscribeChannelEvent(this._key,{onUpdate:(m,h)=>{for(const f of m)this._pendingChannels.push({channel:f,context:h});this._throttledOnChannelChanged()},onRemove:(m,h)=>{this._removeChannels(m,h)}})}get _base(){return this}_removeChannels(n,r){const s=new Set(n);this._pendingChannels=this._pendingChannels.filter(({channel:o})=>!s.has(o.url)),this._base._removeChannelsFromView(n,r)}get channels(){var c;const n=((c=this._params.filter)==null?void 0:c.pinnedChannelUrls)??[],r=[],s=new Map(super.channels.map(u=>[u.url,u])),o=new Set;for(const u of n){const d=s.get(u);d&&!o.has(u)&&(r.push(d),o.add(u))}const i=super.channels.filter(u=>!o.has(u.url));return[...r,...i]}setConversationListCollectionHandler(n){super.setGroupChannelCollectionHandler(n)}dispose(){super.dispose(),this._throttledOnChannelChanged.cancel(),this._base._unsubscribeChannelEvent(this._key)}}class ri{constructor(t){y(this,"subscribers",{});this.logger=t}async send(t){const n=Pc(),r=this.subscribers[t.type];if(r){this.logger.debug(`messenger.dispatcher: dispatching command: ${t.type}`,t.payload);const s=r.map(o=>o(t.payload));await Promise.all(s).catch(o=>{this.logger.error(`messenger.dispatcher: error in callback for command: ${t.type}`,o)})}return n.resolve(),n.promise}subscribe(t,n){this.subscribers[t]||(this.subscribers[t]=[]),this.subscribers[t].push(n)}unsubscribe(t,n){const r=this.subscribers[t];r&&(this.subscribers[t]=r.filter(s=>s!==n))}}const Pc=()=>{let e=le,t=le;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}};var Ke=(e=>(e.ConversationClose="conv.close",e.MessengerSettingsUpdated="messenger.settings.updated",e.ActiveChannelUpdated="active.channel.updated",e.AnonymousSessionTokenExpired="anon.token.expired",e.AuthTokenRefreshed="auth.token.refreshed",e))(Ke||{});class Vt{constructor(t={}){y(this,"payload");this.payload=t}toJSON(){return JSON.stringify({type:this.type,payload:this.payload})}}const ct={CloseConversation:e=>new Uc(e),MessengerSettingsUpdated:e=>new Bc(e),ActiveChannelUpdated:e=>new Hc(e),AnonymousSessionTokenExpired:()=>new Gc,AuthTokenRefreshed:()=>new zc};class Uc extends Vt{constructor(){super(...arguments);y(this,"type","conv.close")}}class Bc extends Vt{constructor(){super(...arguments);y(this,"type","messenger.settings.updated")}}class Hc extends Vt{constructor(){super(...arguments);y(this,"type","active.channel.updated")}}class Gc extends Vt{constructor(){super(...arguments);y(this,"type","anon.token.expired")}}class zc extends Vt{constructor(){super(...arguments);y(this,"type","auth.token.refreshed")}}const qt=e=>{const t={};for(const n of Object.keys(e)){const r=e[n];r!==void 0&&(t[n]=String(r))}return t};class Kt{constructor(t){y(this,"category","connection");this.userId=t}get data(){return qt({user_id:this.userId})}}class Vc extends Kt{constructor(){super(...arguments);y(this,"metricKey","connection_connected")}}class qc extends Kt{constructor(){super(...arguments);y(this,"metricKey","connection_reconnect_started")}}class Kc extends Kt{constructor(){super(...arguments);y(this,"metricKey","connection_reconnect_succeeded")}}class Yc extends Kt{constructor(){super(...arguments);y(this,"metricKey","connection_reconnect_failed")}}class Wc extends Kt{constructor(){super(...arguments);y(this,"metricKey","connection_disconnected")}}class jc{constructor(t){y(this,"lastKey",null);this.dispatch=t}handleEvent({detail:t,userId:n}){const r=`${t}:${n}`;if(this.shouldEmit(r)){this.lastKey=r;const s=t==="connected"?new Vc(n):t==="reconnectStarted"?new qc(n):t==="reconnectSucceeded"?new Kc(n):t==="reconnectFailed"?new Yc(n):new Wc(n);this.dispatch(s)}}shouldEmit(t){return t!==this.lastKey}}class xr{constructor(t,n){y(this,"category","conversation");this.channelUrl=t,this.conversationId=n}get data(){return qt({channel_url:this.channelUrl,conversation_id:this.conversationId})}}class Xc extends xr{constructor(){super(...arguments);y(this,"metricKey","conversation_initialized")}}class Zc extends xr{constructor(){super(...arguments);y(this,"metricKey","conversation_open")}}class Jc extends xr{constructor(){super(...arguments);y(this,"metricKey","conversation_closed")}}class Qc{constructor(t){y(this,"statusByChannel",new Map);this.dispatch=t}handleEvent({channel:t}){const{conversation:n}=t;if(!n)return;const r=this.statusByChannel.get(t.url),s=n.status;if(this.statusByChannel.set(t.url,s),this.shouldEmit(r,s)){const o=s===de.ConversationStatus.INITIALIZED?new Xc(t.url,n.id):s===de.ConversationStatus.OPEN?new Zc(t.url,n.id):new Jc(t.url,n.id);this.dispatch(o)}}shouldEmit(t,n){return n===de.ConversationStatus.INITIALIZED?t===void 0:n===de.ConversationStatus.OPEN?t===de.ConversationStatus.INITIALIZED:t===de.ConversationStatus.OPEN}}const si=(e,t)=>{if(e)return e.members.filter(n=>n.userId!==t).sort((n,r)=>r.joinedAt-n.joinedAt)[0]},He=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===de.ConversationStatus.CLOSED||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="closed")},Rr=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===de.ConversationStatus.OPEN||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="open")};function rt(e){var n,r,s;return typeof(((n=e==null?void 0:e.conversation)==null?void 0:n.handedOverAt)??((s=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff)==null?void 0:s.timestamp))=="number"}function el(e){var r;const t=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff;return t?typeof t.requestedAt=="number"&&!rt(e):!1}function tl(e){var t;if(((t=e==null?void 0:e.resolution)==null?void 0:t.determinedBy)==="user")return e.resolution.isResolved}function oi(e){return!!e&&e<=Date.now()}function nl(e){return!e.title}function rl(e,t){var n;if(e)return nl(e)?{...e,title:t.title,csat_question:t.question,csat_scores:[{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/angry-active.png"},{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/suspicious-active.png"},{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/neutral-active.png"},{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/smile-active.png"},{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/happy-active.png"}],cre:{required:((n=e.cre)==null?void 0:n.required)??!0,question:t.cre.question,positive_label:t.cre.positive_label,negative_label:t.cre.negative_label},follow_up:[{response_type:"free_text",scores:[1,2,3,4,5],question:t.followUp.question,always_visible:!1}],csat_submit_label:t.submit_label,csat_submitted_label:t.submitted_label}:e}class Mr{constructor(t,n){y(this,"category","handoff");this.channelUrl=t,this.conversationId=n}get data(){return qt({channel_url:this.channelUrl,conversation_id:this.conversationId})}}class sl extends Mr{constructor(){super(...arguments);y(this,"metricKey","handoff_started")}}class ol extends Mr{constructor(){super(...arguments);y(this,"metricKey","handoff_succeeded")}}class il extends Mr{constructor(){super(...arguments);y(this,"metricKey","handoff_failed")}}class al{constructor(t){y(this,"statusByChannel",new Map);this.dispatch=t}handleEvent({channel:t}){const n=!this.statusByChannel.has(t.url);n&&this.statusByChannel.set(t.url,void 0);const r=t.conversation;if(!r||!r.handoff||n)return;const s=this.statusByChannel.get(t.url),o=this.resolveStatus(t,r);if(o!==void 0&&this.shouldEmit(s,o)){this.statusByChannel.set(t.url,o);const i=o==="started"?new sl(t.url,r.id):o==="succeeded"?new ol(t.url,r.id):new il(t.url,r.id);this.dispatch(i)}}resolveStatus(t,n){if(He(t))return"failed";const{members:r}=t;if(r.length===1)return"started";if(r.length===2&&n.aiAgentId&&!r.some(s=>s.userId===n.aiAgentId))return"succeeded"}shouldEmit(t,n){return n==="started"?t===void 0:t==="started"}}class cl{constructor(t){y(this,"category","message");y(this,"metricKey","incoming_message_received");y(this,"channelUrl");y(this,"messageId");y(this,"senderType");y(this,"createdAt");y(this,"conversationId");this.channelUrl=t.channelUrl,this.messageId=t.messageId,this.senderType=t.senderType,this.createdAt=t.createdAt,this.conversationId=t.conversationId}get data(){return qt({channel_url:this.channelUrl,message_id:this.messageId,sender_type:this.senderType,created_at:this.createdAt,conversation_id:this.conversationId})}}const ll=(e,t)=>{const n=Qe(e)?e.sender.userId:void 0;return n===void 0?"system":n===t?"ai_agent":"human_agent"};class ul{constructor(t,n){this.dispatch=t,this.getCurrentUserId=n}handleEvent({channel:t,message:n}){const{conversation:r}=t;this.shouldEmit(n,r)&&this.dispatch(new cl({channelUrl:t.url,messageId:n.messageId,senderType:ll(n,r.aiAgentId),createdAt:n.createdAt,conversationId:r.id}))}shouldEmit(t,n){return!st(t,this.getCurrentUserId())&&n!==null}}class dl{constructor(t){y(this,"category","message");y(this,"metricKey");y(this,"channelUrl");y(this,"requestId");y(this,"messageId");y(this,"target");y(this,"sendingStatus");y(this,"createdAt");y(this,"conversationId");this.channelUrl=t.channelUrl,this.requestId=t.requestId,this.messageId=t.messageId,this.target=t.target,this.sendingStatus=t.sendingStatus,this.createdAt=t.createdAt,this.conversationId=t.conversationId,this.metricKey=`outgoing_message_${t.sendingStatus}`}get data(){return qt({channel_url:this.channelUrl,request_id:this.requestId,message_id:this.messageId,target:this.target,created_at:this.createdAt,conversation_id:this.conversationId})}}const ml=e=>{switch(e){case Fe.SendingStatus.PENDING:return"pending";case Fe.SendingStatus.SUCCEEDED:return"succeeded";case Fe.SendingStatus.FAILED:return"failed";case Fe.SendingStatus.SCHEDULED:return"scheduled";default:return}};class hl{constructor(t,n){y(this,"statusByReqId",new Map);this.dispatch=t,this.getCurrentUserId=n}handleEvent({channel:t,message:n}){var o;if(!st(n,this.getCurrentUserId()))return;const r=ml(n.sendingStatus);if(r===void 0)return;const s=this.statusByReqId.get(n.reqId);this.statusByReqId.set(n.reqId,r),r!=="scheduled"&&this.shouldEmit(s,r)&&this.dispatch(new dl({channelUrl:t.url,requestId:n.reqId,messageId:r==="succeeded"?n.messageId:void 0,target:rt(t)?"human_agent":"ai_agent",sendingStatus:r,createdAt:n.createdAt,conversationId:(o=t.conversation)==null?void 0:o.id}))}shouldEmit(t,n){return n==="pending"?t!=="pending"&&t!=="succeeded":n==="succeeded"?t==="pending"||t==="scheduled":t!=="failed"}}class fl{constructor(t){y(this,"id","aiagent_livemetric");y(this,"dispatch");y(this,"emit",({category:t,metricKey:n,data:r})=>{var s;(s=this.dispatch)==null||s.call(this,{category:t,metricKey:n,data:r})});y(this,"emitters");this.chatSDK=t;const n=()=>{var r;return(r=this.chatSDK.currentUser)==null?void 0:r.userId};this.emitters={connection:new jc(this.emit),conversation:new Qc(this.emit),handoff:new al(this.emit),incomingMessage:new ul(this.emit,n),outgoingMessage:new hl(this.emit,n)}}start(){const t=new ue.ConnectionHandler({onConnected:r=>this.trackConnection("connected",r),onDisconnected:r=>this.trackConnection("disconnected",r),onReconnectStarted:()=>this.trackConnection("reconnectStarted"),onReconnectSucceeded:()=>this.trackConnection("reconnectSucceeded"),onReconnectFailed:()=>this.trackConnection("reconnectFailed")}),n=new We.GroupChannelHandler({onMessageReceived:(r,s)=>{r.isGroupChannel()&&this.track({type:"incomingMessage",channel:r,message:s})},onChannelChanged:r=>{r.isGroupChannel()&&(this.track({type:"handoff",channel:r}),this.track({type:"conversation",channel:r}))},onUserJoined:r=>this.track({type:"handoff",channel:r}),onUserLeft:r=>this.track({type:"handoff",channel:r})});this.chatSDK.addConnectionHandler(this.id,t),this.chatSDK.groupChannel.addGroupChannelHandler(this.id,n)}track(t){try{this.emitters[t.type].handleEvent(t)}catch{}}dispose(){this.chatSDK.removeConnectionHandler(this.id),this.chatSDK.groupChannel.removeGroupChannelHandler(this.id)}trackConnection(t,n=(r=>(r=this.chatSDK.currentUser)==null?void 0:r.userId)()){n&&this.track({type:"connection",detail:t,userId:n})}}var wr=(e=>(e[e.VERBOSE=0]="VERBOSE",e[e.DEBUG=1]="DEBUG",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.NONE=5]="NONE",e))(wr||{});class ii{constructor(t){y(this,"level");this.level=t}verbose(...t){this.level<=0&&console.log(`[${bt}/verbose]`,...t)}debug(...t){this.level<=1&&console.log(`[${bt}/debug]`,...t)}info(...t){this.level<=2&&console.log(`[${bt}/info]`,...t)}warn(...t){this.level<=3&&console.warn(`[${bt}/warn]`,...t)}error(...t){this.level<=4&&console.error(`[${bt}/error]`,...t)}}class ai{constructor({userId:t,authToken:n,sessionHandler:r}){y(this,"userId");y(this,"authToken");y(this,"sessionHandler");this.userId=t,this.authToken=n,this.sessionHandler=r}}class ur{constructor(){y(this,"userId");y(this,"authToken");y(this,"sessionHandler")}}const gl=e=>({onSessionTokenRequired:t=>{t(null),e.send(ct.AnonymousSessionTokenExpired())}}),ci="ai_agent:stats",pl="conversation_initial_render",gs="conversation_not_interactive_timeout",_l="recovery_not_interactive_timeout",El="conversation_list_initial_render",Cl="message_pending_stuck",ps="aiev_auth_expired_unhandled",bl="user_perceived_response_time",vl="stream_stalled",yl="ai_typing_indicator_absent_timeout",Sl="rendered_content_unusable",li=800220;var ge=(e=>(e.AUTH="auth_duration_ms",e.GET_CHANNEL="get_channel_duration_ms",e.GET_MESSAGES="get_messages_duration_ms",e.TOTAL_DURATION="total_duration_ms",e.TOTAL_DURATION_FROM_CACHE="total_duration_from_cache_ms",e))(ge||{});const vn={now:()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()},ui=(e,t,n)=>{const r={key:e,value:String(t)};return(n==null?void 0:n.conversationId)!==void 0&&(r.conversation_id=n.conversationId),n!=null&&n.error&&(r.error_code=n.error.code??li,r.error_description=n.error.message??""),n!=null&&n.extra&&Object.keys(n.extra).length>0&&(r.extra=n.extra),r},It=e=>(e==null?void 0:e.clock)??vn,Al=((e,t)=>setTimeout(e,t)),Tl=(e=>clearTimeout(e)),Yt=e=>(e==null?void 0:e.setTimeout)??Al,Wt=e=>(e==null?void 0:e.clearTimeout)??Tl,et=(e,t,n,r)=>e(ci,ui(t,n,r)),Se=(e,t)=>{e!==null&&t(e)},On=(e,t)=>{if(e.size<t)return;const n=e.keys().next();n.done||e.delete(n.value)},mt=(e,t)=>!(e.channelUrl&&t&&e.channelUrl!==t),di=(e,t)=>{for(const n of e)if(n.userMessageId===void 0&&mt(n,t))return!0;return!1};class Il{constructor(t){y(this,"callback");this.callback=t}onPayloadParseFailed(t){et(this.callback,ps,"payload_parse_failed",{extra:{agent_id:t.aiAgentId}})}onCallbackNotFound(t){et(this.callback,ps,"callback_not_found",{extra:{agent_id:t.aiAgentId}})}clear(){}}class xl{constructor(){y(this,"timers",new Map);y(this,"committed",!1);y(this,"commitCallback",null);y(this,"conversationId",null);y(this,"channelUrl",null);y(this,"errorCode",null);y(this,"errorDescription",null);y(this,"extraData",{})}setCommitCallback(t){return this.commitCallback=t,this}setConversationId(t){return this.conversationId=t,this}setChannelUrl(t){return this.setExtra("channel_url",t),this}setError(t,n){return this.errorCode=t??li,this.errorDescription=n,this}setExtra(t,n){return n!=null&&(this.extraData[t]=n),this}startTimer(t){if(this.committed)return this;const n=this.timers.get(t);return(n==null?void 0:n.startTime)!==null&&(n==null?void 0:n.startTime)!==void 0?this:(this.timers.set(t,{startTime:vn.now(),endTime:null}),this)}stopTimer(t){if(this.committed)return this;const n=this.timers.get(t);return!n||n.startTime===null||n.endTime!==null?this:(this.timers.set(t,{...n,endTime:vn.now()}),this)}getDuration(t){const n=this.timers.get(t);return!n||n.startTime===null||n.endTime===null?null:n.endTime-n.startTime}isCommitted(){return this.committed}commit(){if(this.committed||!this.commitCallback)return!1;const t=this.buildPayload();return t?(this.committed=!0,this.commitCallback(ci,t)):!1}}class Rl extends xl{constructor(){super(...arguments);y(this,"presentMethod","direct_present")}setPresentMethod(n){return this.presentMethod=n,this}getMetricKey(){return pl}buildPayload(){const n=this.getDuration(ge.AUTH),r=this.getDuration(ge.GET_CHANNEL),s=this.getDuration(ge.GET_MESSAGES),o=this.getDuration(ge.TOTAL_DURATION_FROM_CACHE),i=this.getDuration(ge.TOTAL_DURATION),c={...this.extraData,present_method:this.presentMethod,...n!==null&&{[ge.AUTH]:n},...r!==null&&{[ge.GET_CHANNEL]:r},...s!==null&&{[ge.GET_MESSAGES]:s},...o!==null&&{[ge.TOTAL_DURATION_FROM_CACHE]:o}};return ui(this.getMetricKey(),i??0,{conversationId:this.conversationId??void 0,error:this.errorCode!==null?{code:this.errorCode,message:this.errorDescription??""}:void 0,extra:c})}}class Ml{constructor(t){y(this,"commitCallback");y(this,"apiResultReceived",!1);y(this,"channelUrl");y(this,"consumed",!1);y(this,"consumedByAuthError",!1);y(this,"presentMethod","direct_present");y(this,"renderedAfterApiResult",!1);y(this,"stats",null);this.commitCallback=t}getOrCreateStats(){var t;return this.consumed?null:(t=this.stats)!=null&&t.isCommitted()?(this.consumed=!0,null):(this.stats||(this.stats=new Rl().setCommitCallback(this.commitCallback).setPresentMethod(this.presentMethod),this.apiResultReceived=!1,this.renderedAfterApiResult=!1),this.stats)}getActiveStats(){return this.consumed||!this.stats||this.stats.isCommitted()?null:this.stats}matchesChannelUrl(t){return t===void 0||this.channelUrl===void 0||t===this.channelUrl}pinChannelUrl(t){var n;return t===void 0?!0:this.matchesChannelUrl(t)?(this.channelUrl=t,(n=this.stats)==null||n.setChannelUrl(t),!0):!1}consume(t){return t&&(this.consumed=!0),t}commitIfReady(t){return this.consumed||!this.stats||this.stats.isCommitted()?!0:!this.matchesChannelUrl(t)||!this.apiResultReceived||!this.renderedAfterApiResult?!1:this.consume(this.stats.stopTimer(ge.TOTAL_DURATION).commit())}start(t){const n=this.getOrCreateStats();!n||!this.pinChannelUrl(t)||n.startTimer(ge.TOTAL_DURATION).startTimer(ge.TOTAL_DURATION_FROM_CACHE)}onAuthStart(){var t;this.consumedByAuthError&&this.clear(),(t=this.getOrCreateStats())==null||t.startTimer(ge.AUTH)}onAuthComplete(){var t;(t=this.getActiveStats())==null||t.stopTimer(ge.AUTH)}onAuthError(t){const n=this.getActiveStats();n&&this.consume(n.stopTimer(ge.AUTH).setError(t instanceof ue.SendbirdError?t.code:void 0,t.message).stopTimer(ge.TOTAL_DURATION).commit())&&(this.consumedByAuthError=!0)}onGetChannelStart(t){const n=this.getActiveStats();!n||!this.pinChannelUrl(t)||n.startTimer(ge.GET_CHANNEL)}onGetChannelComplete(t){const n=typeof t=="object"?t.channelUrl:void 0,r=typeof t=="object"?t.conversationId:t,s=this.getActiveStats();!s||!this.pinChannelUrl(n)||(s.stopTimer(ge.GET_CHANNEL),r!==void 0&&s.setConversationId(r),s.startTimer(ge.GET_MESSAGES))}onGetChannelError(t){const n=t instanceof Error?void 0:t.channelUrl,r=t instanceof Error?t:t.error,s=this.getActiveStats();s&&this.pinChannelUrl(n)&&this.consume(s.stopTimer(ge.GET_CHANNEL).setError(r instanceof ue.SendbirdError?r.code:void 0,r.message).stopTimer(ge.TOTAL_DURATION).commit())}onCacheResult(t){const n=this.getActiveStats();n&&(t&&n.setError(t instanceof ue.SendbirdError?t.code:void 0,t.message),n.stopTimer(ge.TOTAL_DURATION_FROM_CACHE))}onApiResult(t){const n=this.getActiveStats();if(n){if(t){this.consume(n.setError(t instanceof ue.SendbirdError?t.code:void 0,t.message).stopTimer(ge.TOTAL_DURATION).stopTimer(ge.GET_MESSAGES).commit());return}this.apiResultReceived=!0,this.renderedAfterApiResult=!1,n.stopTimer(ge.GET_MESSAGES),this.commitIfReady()}}setChannelUrl(t){this.pinChannelUrl(t)}commitPending(){const t=this.getActiveStats();return t?this.consume(t.stopTimer(ge.TOTAL_DURATION).commit()):!0}markRendered(t){return this.matchesChannelUrl(t)?(this.renderedAfterApiResult=!0,this.commitIfReady(t)):!1}setPresentMethod(t){var n;this.presentMethod=t,(n=this.getActiveStats())==null||n.setPresentMethod(t)}clear(){this.stats=null,this.apiResultReceived=!1,this.channelUrl=void 0,this.consumed=!1,this.consumedByAuthError=!1,this.renderedAfterApiResult=!1}}const _s=()=>({initialized:!1,listStarted:!1,listCompleted:!1,rendered:!1});class wl{constructor(t,n){y(this,"callback");y(this,"clock");y(this,"measurement",_s());y(this,"renderedCommitted",!1);y(this,"startedAt",null);y(this,"listStartedAt",null);y(this,"authStartedAt",null);y(this,"authDuration",null);y(this,"listDuration",null);y(this,"presentMethod","direct_present");y(this,"committed",!1);this.callback=t,this.clock=It(n)}onInitializeStart(){this.measurement.rendered||(this.measurement.initialized&&this.clearMeasurementState(),this.renderedCommitted=!1,this.startMeasurement())}onListRequestStart(){this.measurement.listStarted&&!this.measurement.listCompleted&&!this.measurement.rendered&&this.clearMeasurementState(),this.markListRequestStartOnce()}onListRequestComplete(){this.markListRequestCompleteOnce()}onRendered(){this.markRenderedOnce()}setPresentMethod(t){this.presentMethod=t}start(t){this.committed||(this.startedAt=this.clock.now(),t&&(this.presentMethod=t))}onAuthStart(){this.committed&&(this.clearMeasurementState(),this.renderedCommitted=!1),this.authDuration=null,this.authStartedAt=this.clock.now()}onAuthComplete(){if(!(this.committed||this.authDuration!==null)){if(this.authStartedAt===null){this.authDuration=0;return}this.authDuration=this.clock.now()-this.authStartedAt,this.authStartedAt=null}}markListRequestStart(){this.committed||(this.startedAt===null&&this.start(),this.listStartedAt=this.clock.now())}markListRequestComplete(){this.committed||this.listStartedAt===null||(this.listDuration=this.clock.now()-this.listStartedAt)}markRendered(){this.committed||this.startedAt===null||(this.committed=!0,et(this.callback,El,this.clock.now()-this.startedAt,{extra:{...this.authDuration!==null&&{auth_duration_ms:this.authDuration},...this.listDuration!==null&&{get_list_duration_ms:this.listDuration},present_method:this.presentMethod}}))}clear(){this.clearMeasurementState(),this.clearAuthState(),this.renderedCommitted=!1}clearMeasurementState(){this.startedAt=null,this.listStartedAt=null,this.listDuration=null,this.committed=!1,this.measurement=_s()}clearAuthState(){this.authStartedAt=null,this.authDuration=null}startMeasurement(){this.measurement.initialized||(this.clearMeasurementState(),this.start(),this.measurement.initialized=!0)}markListRequestStartOnce(){this.startMeasurement(),!this.measurement.listStarted&&(this.markListRequestStart(),this.measurement.listStarted=!0)}markListRequestCompleteOnce(){this.markListRequestStartOnce(),!this.measurement.listCompleted&&(this.markListRequestComplete(),this.measurement.listCompleted=!0)}markRenderedOnce(){this.renderedCommitted||(this.startMeasurement(),!this.measurement.rendered&&(this.markRendered(),this.measurement.rendered=!0,this.renderedCommitted=!0))}}class kl{constructor(t,n){y(this,"callback");y(this,"clock");y(this,"setTimeoutFn");y(this,"clearTimeoutFn");y(this,"measurements",new Map);this.callback=t,this.clock=It(n),this.setTimeoutFn=Yt(n),this.clearTimeoutFn=Wt(n)}start(t){const n=this.getKey(t==null?void 0:t.channelUrl);this.clearKey(n);const r={startedAt:this.clock.now(),channelUrl:t==null?void 0:t.channelUrl,conversationId:t==null?void 0:t.conversationId,committed:!1,inputEnabled:!1,phaseReached:"auth",historyLoadResult:"pending",timer:null};r.timer=this.setTimeoutFn(()=>this.commitTimeout(n),1e4),this.measurements.set(n,r)}markChannelJoined(t,n){const r=this.getMeasurement(n);!r||r.committed||(r.phaseReached="channel_join",t!==void 0&&(r.conversationId=t))}markHistoryLoaded(t,n){const r=this.getMeasurement(n);!r||r.committed||(r.phaseReached="history_load",r.historyLoadResult=t,this.cancelIfReady(n))}markInputEnabled(t){const n=this.getMeasurement(t);!n||n.committed||(n.phaseReached="input_enable",n.inputEnabled=!0,this.cancelIfReady(t))}markRendered(t){const n=this.getMeasurement(t);!n||n.committed||(n.phaseReached="render")}clear(){this.measurements.forEach(t=>Se(t.timer,this.clearTimeoutFn)),this.measurements.clear()}clearChannel(t){t!==void 0&&this.clearKey(this.getKey(t))}clearKey(t){const n=this.measurements.get(t);n&&(Se(n.timer,this.clearTimeoutFn),this.measurements.delete(t))}cancelIfReady(t){const n=this.getMeasurement(t);!n||!n.inputEnabled||n.historyLoadResult==="pending"||this.clearKey(this.getKey(n.channelUrl))}commitTimeout(t){const n=this.measurements.get(t);!n||n.committed||(n.committed=!0,n.timer=null,et(this.callback,gs,this.clock.now()-n.startedAt,{conversationId:n.conversationId,error:{message:gs},extra:{outcome:"timeout",phase_reached:n.phaseReached,history_load_result:n.historyLoadResult}}),this.measurements.delete(t))}getMeasurement(t){return t!==void 0?this.measurements.get(this.getKey(t)):this.measurements.size===1?Array.from(this.measurements.values())[0]:this.measurements.get(this.getKey())}getKey(t){return t??"__default__"}}const Ll=5e3,Es=1e4;class Ol{constructor(t,n){y(this,"callback");y(this,"setTimeoutFn");y(this,"clearTimeoutFn");y(this,"measurements",new Map);this.callback=t,this.setTimeoutFn=Yt(n),this.clearTimeoutFn=Wt(n)}start(t){if(!t.requestId||this.measurements.has(t.requestId))return;const n=t.messageType!=="text"&&t.tracksUploadProgress===!0,r={channelUrl:t.channelUrl,messageType:t.messageType,stuckReason:n?"upload_no_progress":"pending_too_long",timer:null},s=n?Es:Ll;r.timer=this.setTimeoutFn(()=>this.detect(t.requestId),s),this.measurements.set(t.requestId,r)}resolve(t){const n=this.measurements.get(t.requestId);n&&(Se(n.timer,this.clearTimeoutFn),this.measurements.delete(t.requestId))}disappear(t){const n=this.measurements.get(t.requestId);n&&(Se(n.timer,this.clearTimeoutFn),this.measurements.delete(t.requestId))}markUploadProgress(t){const n=this.measurements.get(t);n&&n.stuckReason==="upload_no_progress"&&(Se(n.timer,this.clearTimeoutFn),n.timer=this.setTimeoutFn(()=>this.detect(t),Es))}clear(){this.measurements.forEach(t=>Se(t.timer,this.clearTimeoutFn)),this.measurements.clear()}clearChannel(t){t&&this.measurements.forEach((n,r)=>{n.channelUrl===t&&(Se(n.timer,this.clearTimeoutFn),this.measurements.delete(r))})}detect(t){const n=this.measurements.get(t);n&&(this.measurements.delete(t),this.commit(t,n))}commit(t,n){et(this.callback,Cl,n.stuckReason,{extra:{message_type:n.messageType,request_id:t}})}}class Nl{constructor(t,n){y(this,"callback");y(this,"clock");y(this,"setTimeoutFn");y(this,"clearTimeoutFn");y(this,"measurements",new Map);this.callback=t,this.clock=It(n),this.setTimeoutFn=Yt(n),this.clearTimeoutFn=Wt(n)}start(t,n){const r=this.getKey(n);let s=this.measurements.get(r);s&&s.startedAt!==null||s!=null&&s.inputEnabled||(s={startedAt:this.clock.now(),triggerType:t,inputEnabled:(s==null?void 0:s.inputEnabled)??!1,timer:this.setTimeoutFn(()=>this.commitTimeout(r),1e4)},this.measurements.set(r,s))}setInputEnabled(t,n){const r=this.getKey(n);let s=this.measurements.get(r);if(!s){if(!t)return;s={startedAt:null,triggerType:null,inputEnabled:t,timer:null},this.measurements.set(r,s)}s.inputEnabled=t,t&&this.cancelMeasurement(s)}cancelPending(t){const n=this.getKey(t),r=this.measurements.get(n);r&&(this.cancelMeasurement(r),r.inputEnabled||this.measurements.delete(n))}clear(){this.measurements.forEach(t=>Se(t.timer,this.clearTimeoutFn)),this.measurements.clear()}clearChannel(t){t!==void 0&&this.clearKey(this.getKey(t))}clearKey(t){const n=this.measurements.get(t);n&&(Se(n.timer,this.clearTimeoutFn),this.measurements.delete(t))}commitTimeout(t){const n=this.measurements.get(t);if(!n||n.startedAt===null||n.triggerType===null)return;if(n.inputEnabled){this.cancelMeasurement(n);return}const r=this.clock.now()-n.startedAt,s=n.triggerType;this.measurements.delete(t),et(this.callback,_l,r,{extra:{trigger_type:s}})}cancelMeasurement(t){Se(t.timer,this.clearTimeoutFn),t.timer=null,t.startedAt=null,t.triggerType=null}getKey(t){return t??"__default__"}}const Dl=500;class $l{constructor(t){y(this,"callback");y(this,"committed",new Set);this.callback=t}commit(t){const n=`${t.messageId}:${t.contentKind}:${t.errorDomain}`;this.committed.has(n)||(On(this.committed,Dl),this.committed.add(n),et(this.callback,Sl,t.errorDomain,{error:t.error?{code:t.error.code,message:t.errorDomain}:void 0,extra:{content_kind:t.contentKind,message_id:String(t.messageId)}}))}clear(){this.committed.clear()}}const Cs=1e4,Ct=5e3,Fl=500;class Pl{constructor(t,n){y(this,"callback");y(this,"clock");y(this,"setTimeoutFn");y(this,"clearTimeoutFn");y(this,"streams",new Map);y(this,"emittedMessageChannels",new Map);this.callback=t,this.clock=It(n),this.setTimeoutFn=Yt(n),this.clearTimeoutFn=Wt(n)}markRawProgress(t){if(!t.aiResponse.isStreaming){this.completeDelivery(t.messageId,t.textLength);return}if(this.emittedMessageChannels.has(t.messageId))return;const n=this.getOrCreate(t.messageId,t.channelUrl);t.textLength>n.lastRawLength?(n.chunksReceived+=1,n.lastRawLength=t.textLength,n.lastRawAt=this.clock.now(),Se(n.deliveryTimer,this.clearTimeoutFn),n.deliveryTimer=null,this.scheduleDeliveryStallCheck(t.messageId,n)):this.scheduleDeliveryStallCheck(t.messageId,n),n.lastRenderedLength<n.lastRawLength&&n.renderTimer===null&&(n.lastRenderAt=this.clock.now(),this.scheduleRenderStallCheck(t.messageId,n,Ct))}markRenderedProgress(t){const n=this.streams.get(t.messageId);if(!(!n||t.displayedLength<=n.lastRenderedLength)){if(n.lastRenderedLength=t.displayedLength,n.lastRenderAt=this.clock.now(),n.lastRenderedLength>=n.lastRawLength){if(n.deliveryTimer===null){this.clearStream(t.messageId,n);return}Se(n.renderTimer,this.clearTimeoutFn),n.renderTimer=null;return}this.scheduleRenderStallCheck(t.messageId,n,Ct)}}hasPendingStream(t){return this.streams.has(t)}complete(t){const n=this.streams.get(t);n&&this.clearStream(t,n)}completeDelivery(t,n){const r=this.streams.get(t);if(r){if(n>r.lastRawLength&&(r.lastRawLength=n,r.lastRawAt=this.clock.now()),Se(r.deliveryTimer,this.clearTimeoutFn),r.deliveryTimer=null,r.lastRenderedLength>=r.lastRawLength){this.clearStream(t,r);return}r.renderTimer===null&&(r.lastRenderAt=this.clock.now(),this.scheduleRenderStallCheck(t,r,Ct))}}clearMessage(t){const n=this.streams.get(t);n&&this.clearStream(t,n),this.emittedMessageChannels.delete(t)}clear(){this.streams.forEach(t=>{Se(t.deliveryTimer,this.clearTimeoutFn),Se(t.renderTimer,this.clearTimeoutFn)}),this.streams.clear(),this.emittedMessageChannels.clear()}clearChannel(t){t&&(this.streams.forEach((n,r)=>{n.channelUrl!==t&&n.channelUrl!==void 0||this.clearStream(r,n)}),this.emittedMessageChannels.forEach((n,r)=>{(n===t||n===void 0)&&this.emittedMessageChannels.delete(r)}))}detectDelivery(t){const n=this.streams.get(t);n&&(n.deliveryTimer=null,Se(n.renderTimer,this.clearTimeoutFn),n.renderTimer=null,this.emit(t,n,"delivery"))}detectRender(t){const n=this.streams.get(t);if(!n||(n.renderTimer=null,n.lastRenderedLength>=n.lastRawLength))return;const r=this.clock.now()-n.lastRenderAt;if(r<Ct){this.scheduleRenderStallCheck(t,n,Ct-r);return}const s=this.clock.now()-n.lastRawAt;if(s>=Ct&&n.deliveryTimer!==null){const o=Cs-s;if(o>0){this.scheduleRenderStallCheck(t,n,o);return}}this.emit(t,n,"render")}scheduleRenderStallCheck(t,n,r){n.renderTimer===null&&(n.renderTimer=this.setTimeoutFn(()=>this.detectRender(t),r))}scheduleDeliveryStallCheck(t,n){n.deliveryTimer===null&&(n.deliveryTimer=this.setTimeoutFn(()=>this.detectDelivery(t),Cs))}emit(t,n,r){if(this.emittedMessageChannels.has(t))return;const s=r==="delivery"?n.lastRawAt:n.lastRenderAt;et(this.callback,vl,this.clock.now()-s,{extra:{message_id:String(t),stall_kind:r}}),this.rememberEmitted(t,n.channelUrl),this.clearStream(t,n)}getOrCreate(t,n){const r=this.streams.get(t);if(r)return r;const s=this.clock.now(),o={channelUrl:n,chunksReceived:0,lastRawAt:s,lastRenderAt:s,lastRawLength:0,lastRenderedLength:0,deliveryTimer:null,renderTimer:null};return this.streams.set(t,o),o}rememberEmitted(t,n){this.emittedMessageChannels.has(t)||On(this.emittedMessageChannels,Fl),this.emittedMessageChannels.set(t,n)}clearStream(t,n){Se(n.deliveryTimer,this.clearTimeoutFn),Se(n.renderTimer,this.clearTimeoutFn),this.streams.delete(t)}}const bs=3e3,Ul=3e4;class Bl{constructor(t,n){y(this,"callback");y(this,"clock");y(this,"setTimeoutFn");y(this,"clearTimeoutFn");y(this,"turns",new Map);y(this,"pendingAIResponseStartsByUserMessageId",new Map);this.callback=t,this.clock=It(n),this.setTimeoutFn=Yt(n),this.clearTimeoutFn=Wt(n)}startTurn(t){this.cancelTurn(t.requestId);const n={requestId:t.requestId,channelUrl:t.channelUrl,beforeTpstStartedAt:this.clock.now(),afterTpenStartedAt:null,timer:null};n.timer=this.setTimeoutFn(()=>this.commitTimeout(n.requestId),Ul),this.turns.set(t.requestId,n)}markUserMessageAck(t){const n=this.turns.get(t.requestId);if(!n)return;n.userMessageId=t.messageId;const r=this.pendingAIResponseStartsByUserMessageId.get(t.messageId);r&&(this.pendingAIResponseStartsByUserMessageId.delete(t.messageId),this.applyAIResponseStarted({channelUrl:r.channelUrl,matchesUserMessage:!0,userMessageId:t.messageId},r.startedAt))}replaceTurnRequestId(t,n){if(t===n)return;const r=this.turns.get(t);r&&(this.turns.delete(t),r.requestId=n,this.turns.set(n,r))}cancelTurn(t){this.cleanupTurn(t)}markTypingStarted(t){const n=this.clock.now();this.turns.forEach(r=>{mt(r,t)&&(this.recordAfterTpen(r,n),this.recordBeforeTpst(r,n))})}markTypingEnded(t){const n=this.clock.now();this.turns.forEach(r=>{mt(r,t)&&(this.recordBeforeTpst(r,n),r.afterTpenStartedAt=n)})}markAIResponseStarted(t={}){const n=t.channelUrl,r=t.userMessageId,s=r!==void 0,o=this.clock.now();this.applyAIResponseStarted({channelUrl:n,matchesUserMessage:s,userMessageId:r},o)||!s||r===void 0||!this.hasUnackedTurn(n)||this.pendingAIResponseStartsByUserMessageId.has(r)||(On(this.pendingAIResponseStartsByUserMessageId,100),this.pendingAIResponseStartsByUserMessageId.set(r,{channelUrl:n,startedAt:o}))}applyAIResponseStarted(t,n){if(!t.matchesUserMessage){const s=this.findSingleTurn(t.channelUrl);return s?(this.completeTurn(s.requestId,s.turn,n),!0):!1}let r=!1;return this.turns.forEach((s,o)=>{mt(s,t.channelUrl)&&(t.matchesUserMessage&&s.userMessageId!==t.userMessageId||(r=!0,this.completeTurn(o,s,n)))}),r}findSingleTurn(t){let n,r=0;return this.turns.forEach((s,o)=>{mt(s,t)&&(r+=1,!(r>1)&&(n={requestId:o,turn:s}))}),r===1?n:void 0}completeTurn(t,n,r){this.recordBeforeTpst(n,r),this.recordAfterTpen(n,r),this.commitIfAbsent(t,n)}hasUnackedTurn(t){return di(this.turns.values(),t)}clear(){this.turns.forEach(t=>{Se(t.timer,this.clearTimeoutFn)}),this.turns.clear(),this.pendingAIResponseStartsByUserMessageId.clear()}clearChannel(t){t&&(this.turns.forEach((n,r)=>{n.channelUrl===t&&this.cleanupTurn(r)}),this.pendingAIResponseStartsByUserMessageId.forEach((n,r)=>{n.channelUrl===t&&this.pendingAIResponseStartsByUserMessageId.delete(r)}))}commitTimeout(t){const n=this.turns.get(t);if(!n)return;const r=this.clock.now();this.recordBeforeTpst(n,r),this.recordAfterTpen(n,r),this.commitIfAbsent(t,n)}recordBeforeTpst(t,n){if(t.beforeTpstStartedAt===null)return;const r=n-t.beforeTpstStartedAt;r>=bs&&(t.beforeTpstAbsentMs=r),t.beforeTpstStartedAt=null}recordAfterTpen(t,n){if(t.afterTpenStartedAt===null)return;const r=n-t.afterTpenStartedAt;r>=bs&&(t.afterTpenAbsentMs=r),t.afterTpenStartedAt=null}commitIfAbsent(t,n){const r=n.beforeTpstAbsentMs,s=n.afterTpenAbsentMs;if(r===void 0&&s===void 0){this.cleanupTurn(t);return}et(this.callback,yl,(r??0)+(s??0),{extra:{...r!==void 0&&{before_tpst_absent_ms:r},...s!==void 0&&{after_tpen_absent_ms:s}}}),this.cleanupTurn(t)}cleanupTurn(t){const n=this.turns.get(t);n&&(Se(n.timer,this.clearTimeoutFn),this.turns.delete(t))}}class Hl{constructor(t,n){y(this,"callback");y(this,"clock");y(this,"random");y(this,"sampledByRequestId",new Map);y(this,"sampledByAIMessageId",new Map);y(this,"pendingAIResponseByUserMessageId",new Map);y(this,"collectedCount",0);this.callback=t,this.clock=It(n),this.random=(n==null?void 0:n.random)??Math.random}startTurn(t){this.collectedCount>=10||this.random()>=.15||(this.collectedCount+=1,this.sampledByRequestId.set(t.requestId,{requestId:t.requestId,channelUrl:t.channelUrl,startedAt:this.clock.now()}))}markUserMessageAck(t){const n=this.sampledByRequestId.get(t.requestId);if(!n)return;n.ackAt=this.clock.now(),n.userMessageId=t.messageId;const r=this.pendingAIResponseByUserMessageId.get(t.messageId);r&&(this.pendingAIResponseByUserMessageId.delete(t.messageId),this.applyAIResponseRaw(n,r))}replaceTurnRequestId(t,n){if(t===n)return;const r=this.sampledByRequestId.get(t);r&&(this.sampledByRequestId.delete(t),r.requestId=n,this.sampledByRequestId.set(n,r))}cancelTurn(t){const n=this.sampledByRequestId.get(t);n&&(this.deleteTurn(n),this.collectedCount>0&&(this.collectedCount-=1))}markAIResponseRaw(t){const n=this.clock.now(),r=t.aiResponse.userMessageId;if(r===void 0&&this.hasUnackedTurn(t.channelUrl))return;const s=this.findPendingTurn(t.channelUrl,r);if(s){this.applyAIResponseRaw(s,{...t,firstChunkAt:n});return}r===void 0||!this.hasUnackedTurn(t.channelUrl)||this.bufferAIResponseRaw({messageId:t.messageId,...t.channelUrl!==void 0&&{channelUrl:t.channelUrl},aiResponse:t.aiResponse,firstChunkAt:n},r)}markAIResponseVisible(t){const n=this.sampledByAIMessageId.get(t);if(!n||n.ackAt===void 0||n.firstChunkAt===void 0||n.userMessageId===void 0)return!1;const r=this.clock.now();return et(this.callback,bl,r-n.startedAt,{extra:{ack_to_first_chunk_ms:n.firstChunkAt-n.ackAt,first_chunk_to_render_ms:r-n.firstChunkAt,is_streaming:!!n.isStreaming,send_to_ack_ms:n.ackAt-n.startedAt}}),this.deleteTurn(n),!0}hasPendingAIResponse(t){return this.sampledByAIMessageId.has(t)}clearMessage(t){this.pendingAIResponseByUserMessageId.forEach((r,s)=>{r.messageId===t&&this.pendingAIResponseByUserMessageId.delete(s)});const n=this.sampledByAIMessageId.get(t);n&&(this.deleteTurn(n),this.collectedCount>0&&(this.collectedCount-=1))}clearChannel(t){t&&(this.sampledByRequestId.forEach(n=>{n.channelUrl===t&&(this.deleteTurn(n),this.collectedCount>0&&(this.collectedCount-=1))}),this.pendingAIResponseByUserMessageId.forEach((n,r)=>{n.channelUrl===t&&this.pendingAIResponseByUserMessageId.delete(r)}))}clear(){this.sampledByRequestId.clear(),this.sampledByAIMessageId.clear(),this.pendingAIResponseByUserMessageId.clear(),this.collectedCount=0}findPendingTurn(t,n){if(n!==void 0){for(const s of this.sampledByRequestId.values())if(!(s.ackAt===void 0||s.firstChunkAt!==void 0)&&mt(s,t)&&s.userMessageId===n)return s;return}let r;for(const s of this.sampledByRequestId.values())if(!(s.ackAt===void 0||s.firstChunkAt!==void 0)&&mt(s,t)){if(r)return;r=s}return r}applyAIResponseRaw(t,n){t.firstChunkAt===void 0&&(t.firstChunkAt=t.ackAt===void 0?n.firstChunkAt:Math.max(n.firstChunkAt,t.ackAt),t.aiMessageId=n.messageId,t.channelUrl=t.channelUrl??n.channelUrl,t.isStreaming=n.aiResponse.isStreaming,this.sampledByAIMessageId.set(n.messageId,t))}bufferAIResponseRaw(t,n){this.pendingAIResponseByUserMessageId.has(n)||(On(this.pendingAIResponseByUserMessageId,100),this.pendingAIResponseByUserMessageId.set(n,t))}hasUnackedTurn(t){return di(this.sampledByRequestId.values(),t)}deleteTurn(t){this.sampledByRequestId.delete(t.requestId),t.aiMessageId!==void 0&&this.sampledByAIMessageId.delete(t.aiMessageId),t.userMessageId!==void 0&&this.pendingAIResponseByUserMessageId.delete(t.userMessageId)}}function Gl(){let e=null,t=0;const n=(r,s)=>{if((e==null?void 0:e.key)===r)return e.promise;const o=++t,c=(e?e.promise.catch(()=>{}).then(()=>s()):s()).finally(()=>{(e==null?void 0:e.id)===o&&(e=null)});return e={key:r,id:o,promise:c},c};return n.isPending=()=>e!==null,n}const mi=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0)),vs={isTalkToAgentViewEnabled:!0,scrollMode:"auto",newMessageIndicatorEnabled:!0,senderAvatarEnabled:!0},kr={conversation:{...vs,messageAlertSoundEnabled:!1,list:{...vs,deferredMarkdownElements:[]},header:{avatarEnabled:!0},input:{camera:{photoEnabled:!0},gallery:{photoEnabled:!0},fileEnabled:!0},fileViewer:{downloadEnabled:!0}},launcher:{unreadBadgeEnabled:!1}},ys=e=>e?{conversation:ql(e.conversation),launcher:zl(e.launcher)}:kr,zl=e=>vt(kr.launcher,e),Vl=e=>{if(e.deferredMarkdownElements)return[...e.deferredMarkdownElements];const t=[];return e.markdownImageRenderMode==="complete-only"&&t.push("image"),e.markdownLinkRenderMode==="complete-only"&&t.push("link"),t},ql=e=>{const t=kr.conversation;if(!e)return t;const{list:n={},header:r={},input:s,fileViewer:o={},messageAlertSoundEnabled:i=t.messageAlertSoundEnabled,...c}=e,{camera:u={},gallery:d={},fileEnabled:m=t.input.fileEnabled}=s??{},h={...vt(t.list,c,n),deferredMarkdownElements:Vl(n)};return{...h,messageAlertSoundEnabled:i,list:h,header:vt(t.header,r),input:{camera:vt(t.input.camera,u),gallery:vt(t.input.gallery,d),fileEnabled:m},fileViewer:vt(t.fileViewer,o)}},vt=(e,...t)=>{const n={...e};for(const r of t)r&&Object.assign(n,mi(r));return n},Kl=e=>({userId:e.bot_userid,profileUrl:e.bot_profile_url,nickname:e.bot_nickname,replyToFile:e.reply_to_file,specialNotice:e.special_notice,specialNoticeEnabled:e.is_special_notice_enabled,showHandoffButton:e.show_handoff_button??!0,isMultipleActiveConversationsEnabled:e.is_multiple_active_conversations_enabled??!0,isUserFeedbackEnabled:e.is_user_feedback_enabled??!1,isUserFeedbackCommentOptionEnabled:e.is_user_feedback_comment_option_enabled??!1}),Yl=e=>({type:e.image_type||"default_icon",imageUrl:e.image_url}),dr=e=>({enabled:e.enabled,showIndicator:e.show_indicator,toggleAllowed:e.toggle_allowed,deleteOnOff:e.delete_on_off,consentDialog:e.consent_dialog});class Wl{constructor(){y(this,"_channelHandlerId",null);y(this,"_connectionHandlerId",null);y(this,"_handleActiveChannelChangedThrottled",null);y(this,"_setupChannelHandler",()=>{const t=Date.now();this._channelHandlerId=`aiagent_channel_${t}`,this._connectionHandlerId=`aiagent_connection_${t}`,this._handleActiveChannelChangedThrottled=ti(s=>{var o,i;(i=this._session)==null||i._updateActiveChannel({url:s.url,status:He(s)?"closed":"open",conversationStatus:(o=s.conversation)==null?void 0:o.status}),this._logger.debug("AIAgentEventManager: activeChannel updated",s.url)},250,{leading:!0,trailing:!1});const n=new We.GroupChannelHandler({onChannelChanged:s=>{var o,i;s.isGroupChannel()&&s.url===((o=this._session)==null?void 0:o.activeChannel.url)&&((i=this._handleActiveChannelChangedThrottled)==null||i.call(this,s))}}),r=new ue.ConnectionHandler({onReconnectSucceeded:async()=>{await this._syncActiveChannelOnReconnect()}});this._chatClient.chatSDK.groupChannel.addGroupChannelHandler(this._channelHandlerId,n),this._chatClient.chatSDK.addConnectionHandler(this._connectionHandlerId,r),this._logger.debug("AIAgentEventManager: handlers registered",{channelHandlerId:this._channelHandlerId,connectionHandlerId:this._connectionHandlerId})});y(this,"_removeChannelHandler",()=>{this._channelHandlerId&&(this._chatClient.chatSDK.groupChannel.removeGroupChannelHandler(this._channelHandlerId),this._channelHandlerId=null),this._connectionHandlerId&&(this._chatClient.chatSDK.removeConnectionHandler(this._connectionHandlerId),this._connectionHandlerId=null),this._handleActiveChannelChangedThrottled&&(this._handleActiveChannelChangedThrottled.cancel(),this._handleActiveChannelChangedThrottled=null),this._logger.debug("AIAgentEventManager: handlers removed")});y(this,"_syncActiveChannelOnReconnect",async()=>{var n,r,s;const t=(n=this._session)==null?void 0:n.activeChannel.url;if(t)try{const i=await(await this._chatClient.chatSDK.groupChannel.getChannel(t)).refresh();i.url===t&&((s=this._session)==null||s._updateActiveChannel({url:i.url,status:He(i)?"closed":"open",conversationStatus:(r=i.conversation)==null?void 0:r.status}),this._logger.debug("AIAgentEventManager: activeChannel synced on reconnect",i.url))}catch(o){this._logger.error("AIAgentEventManager: failed to sync activeChannel on reconnect",o)}});y(this,"_initConversationIfNeeded",async t=>{if(t.isAIAgent&&!t.conversation)try{await t.initConversation({aiAgentId:this.aiAgentId})}catch(n){this._logger.warn("AIAgentEventManager: initConversation failed",n)}});y(this,"onMessengerSettingsUpdated",t=>(this._dispatcher.subscribe(Ke.MessengerSettingsUpdated,t),()=>{this._dispatcher.unsubscribe(Ke.MessengerSettingsUpdated,t)}));y(this,"onActiveChannelUpdated",t=>(this._dispatcher.subscribe(Ke.ActiveChannelUpdated,t),()=>{this._dispatcher.unsubscribe(Ke.ActiveChannelUpdated,t)}));y(this,"onAuthTokenRefreshed",t=>(this._dispatcher.subscribe(Ke.AuthTokenRefreshed,t),()=>{this._dispatcher.unsubscribe(Ke.AuthTokenRefreshed,t)}))}}class jl{constructor(t){y(this,"_sdkUser");y(this,"_userSession");y(this,"_dispatcher");y(this,"_activeChannel");y(this,"_updateActiveChannel",t=>{this._activeChannel=t,this._dispatcher.send(ct.ActiveChannelUpdated({channelUrl:t.url,status:t.status,conversationStatus:t.conversationStatus}))});y(this,"_updateAuthToken",t=>{this._userSession.authToken=t,this._dispatcher.send(ct.AuthTokenRefreshed())});this._sdkUser=t.sdkUser,this._userSession=t.userSession,this._dispatcher=t.dispatcher,this._activeChannel=t.activeChannel}get sdkUser(){return this._sdkUser}get userSession(){return this._userSession}get activeChannel(){return this._activeChannel}}const hi=e=>{try{const t=JSON.parse(e);return typeof t=="string"?JSON.stringify(t).slice(1,-1):e.trim()}catch{return JSON.stringify(e).slice(1,-1)}},fi=e=>JSON.parse(e),Xl=e=>JSON.parse(e);function Zl(e,t){const[n,r]=t.split(",").map(s=>s.trim());return e==="dark"&&r||n}function Jl(e){const t={};function n(r,s=""){for(const[o,i]of Object.entries(r)){const c=s?`${s}.${o}`:o;i&&typeof i=="object"&&!Array.isArray(i)?n(i,c):t[c]=i}}return n(e),t}function Ql({template:e,variables:t,variableKeyPattern:n,variableValueTransformer:r}){return Object.entries(t).reduce((s,[o,i])=>{if(!r&&!["number","boolean","string"].includes(typeof i))throw new Error(`If transformer is not provided, value(${o}:${i}) must be a {string, number, or boolean}`);const c=r?r(i):String(i),u=n(o);return s.replace(u,hi(c))},e)}async function eu({template:e,variables:t,variableKeyPattern:n,variableValueTransformer:r}){return(await Promise.all(Object.entries(t).map(async([o,i])=>{const c=await r(i);return{regex:n(o),transformedValue:c}}))).reduce((o,{regex:i,transformedValue:c})=>o.replace(i,hi(c)),e)}var Lr=(e=>(e[e.EXTERNAL_AUTH_TOKEN_EXPIRED=1]="EXTERNAL_AUTH_TOKEN_EXPIRED",e))(Lr||{});const gi=e=>typeof e=="object"&&e!==null,Ss=(e,t)=>t in e&&typeof e[t]=="string"&&e[t]!=="",tu=e=>!gi(e)||!Ss(e,"channel_url")||!Ss(e,"ai_agent_id")?null:{channelUrl:e.channel_url,aiAgentId:e.ai_agent_id},nu={1:tu};function ru(e){if(!gi(e)||!("cat"in e)||typeof e.cat!="number"||!("data"in e))return null;const t=e.cat,n=nu[t];if(!n)return null;const r=n(e.data);return r?{category:t,data:r}:null}function su(e,t,n,r){const s=fc.default.init({appId:e,modules:[new We.GroupChannelModule,new de.AIAgentModule],localCacheEnabled:!0,options:new ue.SendbirdChatOptions({typingIndicatorInvalidateTime:2e4}),...r,customApiHost:(r==null?void 0:r.customApiHost)??`https://api-${e}.app.delight.ai`,customWebSocketHost:(r==null?void 0:r.customWebSocketHost)??`wss://ws-${e}.app.delight.ai`});return s.addSendbirdExtensions([{version:n,product:ue.SendbirdProduct.AI_AGENT,platform:t.platform}],{platform:t.deviceOSPlatform,version:t.deviceOSVersion},t.customData)||console.warn("Invalid Sendbird Extensions",t),s}function ou(e){const t=n=>{throw new Error(`Please initialize chat sdk with ${n}`)};typeof e.groupChannel!="object"&&t("GroupChannelModule"),typeof e.aiAgent!="object"&&t("AIAgentModule")}const iu=[400300,400301,400302,400310],au=Lr.EXTERNAL_AUTH_TOKEN_EXPIRED.toString(),cu=e=>`${au}:${e}`;class Or{constructor(t,n,r,s,o){y(this,"chatSDK");y(this,"_aiAgentId");y(this,"_externalAuthTokenExpiredEventHandlerKey");y(this,"_logger");y(this,"_cache");y(this,"_statsTrackers");y(this,"_sessionHandler");y(this,"_aiEventHandlerRegistered",!1);y(this,"connect",async(t,n,r,s)=>{if(this._logger.debug("ChatClient.connect: start",t.userId),n){this._sessionHandler=n;const o=new ue.SessionHandler({...n,onSessionTokenRequired:this._interceptTokenRefresh(n.onSessionTokenRequired,r,s)});this.chatSDK.setSessionHandler(o)}this._registerAIEventHandler();try{return await this.chatSDK.connect(t.userId,t.authToken),await this._syncTemplatesIfNeeded(),this._logger.debug("ChatClient.connect: end",this.chatSDK.currentUser),this.chatSDK.currentUser}catch(o){const i=o;if(this.chatSDK.isCacheEnabled){if(this._isCacheRestrictedError(i))this._logger.warn("ChatClient.connect","offline connect restricted",i.message,i.code),this._logger.warn("ChatClient.connect","clear cached-data"),await this.chatSDK.clearCachedData().catch(c=>this._logger.warn("ChatClient.connect","clear cached-data failure",c));else if(this.chatSDK.currentUser)return this._logger.debug("ChatClient.connect: end (offline)",this.chatSDK.currentUser),this.chatSDK.currentUser}throw this._logger.warn("ChatClient.connect","connect failure",i.message,i.code),this.dispose(),i}});y(this,"_registerAIEventHandler",()=>{this._aiEventHandlerRegistered||(this._aiEventHandlerRegistered=!0,this.chatSDK.aiAgent.addEventHandler(this._externalAuthTokenExpiredEventHandlerKey,this._handleAIEvent))});y(this,"_handleAIEvent",t=>{var o;this._logger.debug("ChatClient.connect: EXTERNAL_AUTH_TOKEN_EXPIRED event received",t);const n=ru(t),r=typeof t.cat=="number"?t.cat:void 0;if(r!==void 0&&r!==Lr.EXTERNAL_AUTH_TOKEN_EXPIRED)return;if(!n){this._statsTrackers.aievAuthExpiredUnhandled.onPayloadParseFailed({aiAgentId:this._aiAgentId});return}if(n.data.aiAgentId!==this._aiAgentId){this._logger.debug("ChatClient.connect: ignore EXTERNAL_AUTH_TOKEN_EXPIRED for another agent",n.data);return}const s=(o=this._sessionHandler)==null?void 0:o.onExternalAuthTokenExpired;if(!s){this._statsTrackers.aievAuthExpiredUnhandled.onCallbackNotFound(n.data);return}this._logger.debug("ChatClient.connect: calling onExternalAuthTokenExpired handler",n.data),s(n.data)});y(this,"dispose",()=>{this._aiEventHandlerRegistered&&(this.chatSDK.aiAgent.removeEventHandler(this._externalAuthTokenExpiredEventHandlerKey),this._aiEventHandlerRegistered=!1),this._sessionHandler=void 0});y(this,"disconnect",async()=>{this._logger.debug("ChatClient.disconnect: start"),this.dispose(),await this.chatSDK.disconnect(),this._cache.template.clear(),this._logger.debug("ChatClient.disconnect: end")});y(this,"getChannel",async t=>this.chatSDK.groupChannel.getChannel(t));y(this,"patchContext",async(t,n,r)=>this.chatSDK.aiAgent.patchContext(t,n,r));y(this,"updateContext",async(t,n,r)=>this.chatSDK.aiAgent.updateContext(t,n,r));y(this,"requestMessengerSettings",async t=>{var s;if(t.userId===""){const o=new Error("userId cannot be empty string for messenger settings request");throw this._logger.error("ChatClient.requestMessengerSettings: invalid userId",o),o}const n={...t,shouldSendFirstMessage:!1};this._logger.debug("ChatClient.requestMessengerSettings: requesting",n);const r=await this.chatSDK.aiAgent.requestMessengerSettings(n);return this._logger.debug("ChatClient.requestMessengerSettings: received",(s=r.active_channel)==null?void 0:s.channel_url),r});y(this,"setUserMemoryState",async t=>{this._logger.debug("ChatClient.setUserMemoryState: requesting",t);const n=await this.chatSDK.aiAgent.setUserMemoryState(t);return this._logger.debug("ChatClient.setUserMemoryState: received",n.enabled),n});y(this,"clearUserMemories",async(t={})=>{this._logger.debug("ChatClient.clearUserMemories: requesting",t),await this.chatSDK.aiAgent.clearUserMemories(t),this._logger.debug("ChatClient.clearUserMemories: completed")});y(this,"_interceptTokenRefresh",(t,n,r)=>{if(t)return async(s,o)=>{new Promise((i,c)=>t==null?void 0:t(i,c)).then(i=>{i?n==null||n(i):r==null||r(),s(i)}).catch(i=>{r==null||r(),o(i)})}});y(this,"_isCacheRestrictedError",t=>iu.some(n=>t.code===n));y(this,"_syncTemplatesIfNeeded",async()=>{var r,s;const t=(s=(r=this.chatSDK.appInfo)==null?void 0:r.aiAgentInfo)==null?void 0:s.templateListToken;if(!t)return;const n=this._cache.template.getCachedToken();if(!(n&&n===t)){this._logger.debug("ChatClient._syncTemplatesIfNeeded: syncing templates");try{const{templates:o,token:i}=await this.chatSDK.aiAgent.getMessageTemplates({limit:20});for(const{template:c}of o){const{key:u}=fi(c);this._cache.template.set(u,c)}this._cache.template.setCachedToken(i),this._logger.debug("ChatClient._syncTemplatesIfNeeded: sync completed")}catch(o){this._logger.error("ChatClient._syncTemplatesIfNeeded: error",o)}}});this.chatSDK=t,this._aiAgentId=n,this._externalAuthTokenExpiredEventHandlerKey=cu(n),this._logger=r,this._cache=s,this._statsTrackers=o}static init(t){let n;return t.chatSDK?(ou(t.chatSDK),n=t.chatSDK):n=su(t.appId,t.extensions,t.messengerVersion,t.chatParams),new Or(n,t.aiAgentId,t.logger,t.cache,t.statsTrackers)}}const rn=new Map,pi={set:(e,t)=>{rn.set(e,t)},get:e=>{if(rn.size===0)throw new Error("AIAgent platform not configured. Ensure you are using the correct package (@sendbird/ai-agent-messenger-react or @sendbird/ai-agent-messenger-react-native).");if(e){const n=rn.get(e);if(!n)throw new Error(`AIAgent platform "${e}" is not configured.`);return{platform:e,...n}}const t=rn.entries().next().value;return{platform:t[0],...t[1]}}};class As extends Error{constructor(n,r){const s=(r==null?void 0:r.detail)??"";super(s||`Desk API error (${n})`);y(this,"status");y(this,"code");y(this,"detail");this.name="DeskApiError",this.status=n,this.code=(r==null?void 0:r.code)??"",this.detail=s}}var Nr=(e=>(e.INITIALIZED="INITIALIZED",e.PROACTIVE="PROACTIVE",e.PENDING="PENDING",e.ACTIVE="ACTIVE",e.CLOSED="CLOSED",e.WORK_IN_PROGRESS="WORK_IN_PROGRESS",e.IDLE="IDLE",e))(Nr||{}),Dr=(e=>(e.URGENT="URGENT",e.HIGH="HIGH",e.MEDIUM="MEDIUM",e.LOW="LOW",e))(Dr||{}),_i=(e=>(e.ERR_CREDENTIALS_NOT_PROVIDED="desk401100",e.ERR_NON_AUTHORIZED="desk401103",e.ERR_SESSION_KEY_EXPIRED="desk401106",e.ERR_SESSION_TOKEN_REVOKED="desk401107",e.ERR_USER_DEACTIVATED="desk401108",e.ERR_USER_NOT_EXIST="desk401109",e))(_i||{});const lu=e=>e==="desk401103"||e==="desk401106"||e==="desk401107"||e==="desk401108"||e==="desk401109";class uu{constructor(t){y(this,"_appId");y(this,"_apiHost");y(this,"_logger");y(this,"_credential",null);y(this,"_authRefreshPromise",null);y(this,"_onDeskTokenRefreshRequired",async()=>!1);y(this,"request",async(t,n)=>{const r=n.authRequired??!0,s=`${this._apiHost}${t}`;r&&this._authRefreshPromise&&(this._logger.debug("DeskApiClient: waiting for in-flight recovery..."),await this._authRefreshPromise);const o=await this._fetch(s,n);return r&&o.status===401?this._handleUnauthorized(o,s,n):this._toResult(o)});y(this,"setCredential",(t,n=async()=>!1)=>{this._authRefreshPromise=null,this._onDeskTokenRefreshRequired=n,this._credential=t});y(this,"clearCredential",()=>{this._authRefreshPromise=null,this._credential=null,this._onDeskTokenRefreshRequired=async()=>!1});y(this,"_handleUnauthorized",async(t,n,r)=>{const s=await this._parseErrorCode(t);if(!lu(s))return this._toResult(t);if(!await this._refresh(s)||this._credential===null)return this._toResult(t);const i=await this._fetch(n,r);return this._toResult(i)});y(this,"_refresh",async t=>{if(this._authRefreshPromise)return this._logger.debug("DeskApiClient: refresh already in progress, joining..."),this._authRefreshPromise;try{return this._authRefreshPromise=this._onDeskTokenRefreshRequired({reason:t}).catch(n=>(this._logger.error("DeskApiClient: delegated recovery failed",n),!1)),await this._authRefreshPromise}finally{this._authRefreshPromise=null}});y(this,"_fetch",(t,n)=>fetch(`${t}?${this._buildParams(n.params)}`,{method:n.method,headers:this._buildHeaders(n.authRequired??!0,n.headers),...n.body?{body:JSON.stringify(this._buildBody(n.body))}:{}}));y(this,"_buildParams",t=>new URLSearchParams({sendbirdAppId:this._appId,...t}));y(this,"_buildBody",t=>({sendbirdAppId:this._appId,...t}));y(this,"_buildHeaders",(t,n)=>({"content-type":"application/json",...t&&this._credential?{sendbirdDeskToken:this._credential.deskToken}:{},...n}));y(this,"_toResult",async t=>{if(!t.ok){const r=await t.json().catch(()=>({}));throw new As(t.status,r)}const n=await t.text();if(n)try{return JSON.parse(n)}catch{throw new As(t.status,{})}});y(this,"_parseErrorCode",async t=>{const n=await t.clone().json().catch(()=>({}));return n==null?void 0:n.code});this._appId=t.appId,this._apiHost=t.customApiHost??`https://desk-api-${t.appId}.app.delight.ai/sapi`,this._logger=t.logger}get credential(){return this._credential}}class yn{constructor(t,n){y(this,"id");y(this,"title");y(this,"status");y(this,"agent");y(this,"priority");y(this,"group");y(this,"firstResponseTime");y(this,"issuedAt");y(this,"customFields");y(this,"_client");y(this,"refresh",async()=>this._client.getTicket(this.id));this.id=t.id,this.title=t.title,this.status=t.status,this.agent=t.agent,this.priority=t.priority,this.group=t.group,this.firstResponseTime=t.firstResponseTime,this.issuedAt=t.issuedAt,this.customFields=t.customFields,this._client=n}static _fromResponse(t,n){var r;return new yn({id:t.id,title:t.channelName??null,status:t.status2??Nr.INITIALIZED,agent:(()=>{var o;const s=(o=t.recentAssignment)==null?void 0:o.agent;return s?{userId:s.sendbirdId??"",name:s.displayName??"",profileUrl:s.photoThumbnailUrl??""}:null})(),priority:t.priority??Dr.MEDIUM,group:t.group??0,firstResponseTime:t.firstResponseTime??-1,issuedAt:t.issuedAt??null,customFields:Object.fromEntries(((r=t.customFields)==null?void 0:r.map(s=>[s.key,s.value]))??[])},n)}}class $r{constructor(t){y(this,"_logger");y(this,"_apiClient");y(this,"_onDeskTokenRefreshRequired");y(this,"refreshDeskAuthToken",async t=>this._apiClient.credential?this.authenticate({userId:this._apiClient.credential.userId,accessToken:t,onDeskTokenRefreshRequired:this._onDeskTokenRefreshRequired}):!1);y(this,"authenticate",async t=>{this._logger.debug("DeskClient.authenticate: start",t.userId);try{const{token:n}=await this._apiClient.request("/customers/auth/",{method:"POST",headers:{sendbirdAccessToken:t.accessToken},body:{sendbirdId:t.userId},authRequired:!1});return t.onDeskTokenRefreshRequired!==void 0&&(this._onDeskTokenRefreshRequired=t.onDeskTokenRefreshRequired),this._apiClient.setCredential({userId:t.userId,deskToken:n,chatToken:t.accessToken},this._onDeskTokenRefreshRequired),this._logger.debug("DeskClient.authenticate: end"),!0}catch(n){return this._apiClient.clearCredential(),this._logger.debug("DeskClient.authenticate: failed",n),!1}});y(this,"deauthenticate",()=>{this._apiClient.clearCredential(),this._onDeskTokenRefreshRequired=void 0,this._logger.debug("DeskClient.deauthenticate: token cleared")});y(this,"setCustomerLanguage",async t=>{this._assertAuthenticated(this._apiClient),this._logger.debug("DeskClient.setCustomerLanguage: start",t),await this._apiClient.request("/customers/language/",{method:"PATCH",body:{language:t}}),this._logger.debug("DeskClient.setCustomerLanguage: end")});y(this,"getTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request(`/tickets/${encodeURIComponent(t)}/`,{method:"GET"});return yn._fromResponse(n,this)});y(this,"createTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request("/tickets/",{method:"POST",body:mi({channelName:t.title,channelType:"SENDBIRD_JAVASCRIPT",customFields:t.customFields?JSON.stringify(t.customFields):void 0,info:JSON.stringify({ticket:{subject:t.title,requester:{name:t.name,email:this._apiClient.credential.userId}}}),priority:t.priority,groupKey:t.groupKey})});return yn._fromResponse(n,this)});this._logger=t.logger,this._apiClient=new uu(t)}static init(t){return new $r(t)}_assertAuthenticated(t){if(t.credential==null)throw new Error("DeskClient is not authenticated")}}class Fr{constructor(){y(this,"authenticate",async t=>!1);y(this,"deauthenticate",()=>{});y(this,"refreshDeskAuthToken",async()=>!1);y(this,"setCustomerLanguage",async()=>{});y(this,"getTicket",async()=>{throw new Error("DeskClient is disabled via __SBA_USE_DESK_CLIENT__")})}static init(){return new Fr}}function du(e){return{get:t=>e.getString(t)??null,set:(t,n)=>{e.set(t,n)},delete:t=>{e.delete?e.delete(t):e.remove&&e.remove(t)},getKeys:t=>e.getAllKeys().filter(n=>n.startsWith(t))}}const mu=1440*60*1e3,hu=typeof __SBA_USE_DESK_CLIENT__>"u"||__SBA_USE_DESK_CLIENT__;function nt(e){if(!e)throw new Error("Not authenticated. Call authenticate() first.")}function fu(e,t){return Object.entries(t).every(([n,r])=>e[n]===r)}const gu=e=>{const t={conversationInitialRender:new Ml(e),conversationNotInteractiveTimeout:new kl(e),recoveryNotInteractiveTimeout:new Nl(e),conversationListInitialRender:new wl(e),aievAuthExpiredUnhandled:new Il(e),messagePendingStuck:new Ol(e),userPerceivedResponseTime:new Hl(e),streamStalled:new Pl(e),typingIndicatorAbsentTimeout:new Bl(e),renderedContentUnusable:new $l(e)};return{...t,clear:()=>{Object.values(t).forEach(n=>n.clear())}}};class Sn extends Wl{constructor(n){super();y(this,"appId");y(this,"aiAgentId");y(this,"_chatClient");y(this,"_deskClient");y(this,"_cache");y(this,"_logger");y(this,"_dispatcher");y(this,"_session",null);y(this,"language");y(this,"countryCode");y(this,"context");y(this,"queryParams");y(this,"_config");y(this,"_networkStateAdapter");y(this,"_scheduleForegroundTask");y(this,"_forceCreateChannel");y(this,"_agentVersion");y(this,"_statsTrackers");y(this,"_liveMetricManager");y(this,"_operationQueue",Gl());y(this,"dispose",()=>{this._operationQueue.isPending()||(this._logger.debug("AIAgent.dispose: start"),this._chatClient.dispose(),this._chatClient.chatSDK.connectionState==="OPEN"&&this._chatClient.chatSDK.disconnectWebSocket(),this._removeChannelHandler(),this._session=null,this._deskClient.deauthenticate(),this._statsTrackers.clear(),this._liveMetricManager.dispose(),this._logger.debug("AIAgent.dispose: end"))});y(this,"initConversationIfNeeded",n=>this._initConversationIfNeeded(n));y(this,"authenticate",n=>{if(!this.appId)return Promise.reject(new Error("appId is required"));if(!this.aiAgentId)return Promise.reject(new Error("aiAgentId is required"));const r=n&&"userId"in n?`auth:${n.userId}`:"auth:anon";return this._operationQueue(r,async()=>{var i,c,u,d,m;this._logger.debug("AIAgent.authenticate: start"),this._statsTrackers.conversationInitialRender.onAuthStart(),this._statsTrackers.conversationListInitialRender.onAuthStart();const s=this._getSessionCandidate(n),o=(i=s.userSessionCandidate)!=null&&i.userId?this._cache.messenger.getSettings(s.userSessionCandidate.userId):null;o!=null&&o.bot&&this._dispatcher.send(ct.MessengerSettingsUpdated({settings:o,source:"cache"}));try{const h=await this._chatClient.requestMessengerSettings({aiAgentId:this.aiAgentId,userId:(c=s.userSessionCandidate)==null?void 0:c.userId,language:this.language,country:this.countryCode,context:this.context,knownActiveChannelUrl:(u=o==null?void 0:o.active_channel)==null?void 0:u.channel_url,forceCreateChannel:this._forceCreateChannel,agentVersion:this._agentVersion});let f;if(h.auto_created_user)if(s.type==="manual")this._logger.warn("Received auto created user info but current session is manual. Ignoring auto created user info."),f={userId:s.userSessionCandidate.userId,authToken:s.userSessionCandidate.authToken};else{const{user_id:v,session_token:_,expire_at:p}=h.auto_created_user;this._cache.messenger.setAnonUser({userId:v,authToken:_,expireAt:p}),f={userId:v,authToken:_},this._logger.debug("AIAgent.authenticate: anonymous user created",v)}else f={userId:((d=s.userSessionCandidate)==null?void 0:d.userId)??"",authToken:((m=s.userSessionCandidate)==null?void 0:m.authToken)??""};this._cache.messenger.setSettings(f.userId,h),this._dispatcher.send(ct.MessengerSettingsUpdated({settings:h,source:"server"}));const g=(()=>{var v;return s.type==="anonymous"?gl(this._dispatcher):(v=s.userSessionCandidate)==null?void 0:v.sessionHandler})(),C=await this._chatClient.connect(f,g,v=>{var _;this._logger.debug("AIAgent: session token refreshed"),(_=this._session)==null||_._updateAuthToken(v),this._deskClient.refreshDeskAuthToken(v)},()=>{this._logger.debug("AIAgent: session token unavailable, deauthenticating desk"),this._deskClient.deauthenticate()});return await this._deskClient.authenticate({userId:f.userId,accessToken:f.authToken,onDeskTokenRefreshRequired:async({reason:v})=>{var _;if(v===_i.ERR_SESSION_KEY_EXPIRED){await new Promise(S=>setTimeout(S,2e3));const p=(_=this._session)==null?void 0:_.userSession.authToken;return p?await this._deskClient.refreshDeskAuthToken(p):!1}return!1}}),(o==null?void 0:o.language)!==h.language&&this._deskClient.setCustomerLanguage(this.language).catch(()=>{}),this._statsTrackers.conversationInitialRender.onAuthComplete(),this._statsTrackers.conversationListInitialRender.onAuthComplete(),this._session=new jl({sdkUser:C,userSession:f,activeChannel:{url:h.active_channel.channel_url,status:"open"},dispatcher:this._dispatcher}),this._setupChannelHandler(),this._logger.debug("AIAgent.authenticate: end",{userId:f.userId}),h}catch(h){throw this._statsTrackers.conversationInitialRender.onAuthError(h),h}})});y(this,"deauthenticate",()=>this._operationQueue("deauth",async()=>{var r;this._logger.debug("AIAgent.deauthenticate: start");const n=(r=this._session)==null?void 0:r.userSession.userId;this._statsTrackers.clear();try{await this._chatClient.disconnect()}finally{this._deskClient.deauthenticate(),this._cache.messenger.clear(n),this._session=null,this._removeChannelHandler(),this._statsTrackers.clear()}this._logger.debug("AIAgent.deauthenticate: end")}));y(this,"createConversation",async n=>{nt(this._session),this._logger.debug("AIAgent.createConversation: start",n);const r=await this._chatClient.requestMessengerSettings({...n,userId:this._session.userSession.userId,knownActiveChannelUrl:void 0,agentVersion:this._agentVersion}),s=r.active_channel.channel_url;return this._cache.messenger.setSettings(this._session.userSession.userId,r),this._logger.debug("AIAgent.createConversation: end",s),s});y(this,"searchConversation",async n=>{if(nt(this._session),this._logger.debug("AIAgent.searchConversation: start",n),Object.entries(n.context).length===0)return this._logger.debug("AIAgent.searchConversation: empty context, returning empty array"),[];const r=this.chatSDK.aiAgent.createConversationListQuery({aiAgentId:n.aiAgentId,status:de.ConversationStatus.OPEN,limit:100}),s=[];for(;r.hasNext;){const o=await r.next();for(const i of o)fu(i.context??{},n.context)&&s.push(i.channelInfo.url)}return this._logger.debug("AIAgent.searchConversation: end",{count:s.length}),s});y(this,"closeConversation",async n=>{var s;nt(this._session),this._logger.debug("AIAgent.closeConversation: start",n);const r=await this._chatClient.getChannel(n);((s=r.conversation)==null?void 0:s.status)===de.ConversationStatus.OPEN?(await r.closeConversation(),this._session.activeChannel.url===n&&this._session._updateActiveChannel({url:n,status:"closed",conversationStatus:de.ConversationStatus.CLOSED}),this._logger.debug("AIAgent.closeConversation: end")):this._logger.debug("AIAgent.closeConversation: already closed or not an AI agent conversation")});y(this,"createConversationListCollection",n=>new ni(this.chatSDK,n??{}));y(this,"patchContext",async(n,r)=>{nt(this._session),this._logger.debug("AIAgent.patchContext: start",{channelUrl:n,context:r});const s=await this._chatClient.patchContext(this.aiAgentId,n,r);return this._logger.debug("AIAgent.patchContext: end",s),{...s,context:s.context??{}}});y(this,"updateContext",async(n,r)=>{nt(this._session),this._logger.debug("AIAgent.updateContext: start",{channelUrl:n,context:r});const s=await this._chatClient.updateContext(this.aiAgentId,n,r);return this._logger.debug("AIAgent.updateContext: end",s),{...s,context:s.context??{}}});y(this,"getContextObject",async n=>{nt(this._session),this._logger.debug("AIAgent.getContextObject: start",n);const s=await(await this._chatClient.getChannel(n)).getContextObject(this.aiAgentId);return this._logger.debug("AIAgent.getContextObject: end",s),{...s,context:s.context??{}}});y(this,"clearUserMemories",async(n={})=>{nt(this._session);const r={...n,contextAiAgentId:n.contextAiAgentId??this.aiAgentId};this._logger.debug("AIAgent.clearUserMemories: start",r),await this._chatClient.clearUserMemories(r),this._logger.debug("AIAgent.clearUserMemories: end")});y(this,"setUserMemoryState",async n=>{nt(this._session);const r=this._session;this._logger.debug("AIAgent.setUserMemoryState: start",n.enabled);const s={...n,contextAiAgentId:n.contextAiAgentId??this.aiAgentId},o=r.userSession.userId,i=await this._chatClient.setUserMemoryState(s);if(this._session!==r)return this._logger.debug("AIAgent.setUserMemoryState: session changed during request, discarding stale result"),dr(i);const c=this._cache.messenger.getSettings(o);if(c){const u={...c,memory:i};this._cache.messenger.setSettings(o,u),this._dispatcher.send(ct.MessengerSettingsUpdated({settings:u,source:"cache"}))}return this._logger.debug("AIAgent.setUserMemoryState: end",i.enabled),dr(i)});y(this,"refreshActiveChannel",async n=>{var c,u,d;nt(this._session);const r=this._session,s=(n==null?void 0:n.useKnownActiveChannelUrl)??!0;this._logger.debug("AIAgent.refreshActiveChannel: start",{useKnownActiveChannelUrl:s});const o=await this._chatClient.requestMessengerSettings({aiAgentId:this.aiAgentId,userId:r.userSession.userId,language:this.language,country:this.countryCode,context:this.context,knownActiveChannelUrl:s?(u=(c=this._cache.messenger.getSettings(r.userSession.userId))==null?void 0:c.active_channel)==null?void 0:u.channel_url:void 0,forceCreateChannel:this._forceCreateChannel,agentVersion:this._agentVersion});if(this._session!==r)return this._logger.debug("AIAgent.refreshActiveChannel: session changed during refresh, discarding stale result"),((d=this._session)==null?void 0:d.activeChannel.url)??o.active_channel.channel_url;const i=o.active_channel.channel_url;return this._cache.messenger.setSettings(this._session.userSession.userId,o),this._session._updateActiveChannel({url:i,status:"open"}),this._logger.debug("AIAgent.refreshActiveChannel: end",i),i});y(this,"_getSessionCandidate",n=>n instanceof ai?{type:"manual",userSessionCandidate:this._getManualSessionInfo(n)}:n instanceof ur?{type:"anonymous",userSessionCandidate:this._getAnonymousSessionInfo()}:n&&typeof n=="object"?(this._logger.warn("Please use ManualSessionInfo instead of the old userSessionInfo format."),{type:"manual",userSessionCandidate:this._getManualSessionInfo(n)}):n===void 0?(this._logger.warn("Please use AnonymousSessionInfo instead of undefined userSessionInfo."),{type:"anonymous",userSessionCandidate:this._getAnonymousSessionInfo()}):{type:"anonymous",userSessionCandidate:null});y(this,"_getAnonymousSessionInfo",()=>{const n=this._cache.messenger.getAnonUser();return n?n.expireAt-mu<=Date.now()?(this._logger.debug("_getAnonymousSessionInfo: auto session expired, clear cache"),this._cache.messenger.clear(n.userId),null):(this._logger.debug("_getAnonymousSessionInfo: auto session info detected"),{userId:n.userId,authToken:n.authToken}):null});y(this,"_getManualSessionInfo",n=>{if(!n||n instanceof ur)throw new Error("userSessionInfo must be an instance of ManualSessionInfo");if(typeof n.userId!="string")throw new Error("userSessionInfo.userId must be a string");const r=["userId","authToken","sessionHandler"].filter(s=>!(s in n));return r.length>0&&this._logger.error(`_getManualSessionInfo: missing required keys in userSessionInfo: ${r.join(", ")}`),this._logger.debug("_getManualSessionInfo: manual session info detected"),{userId:n.userId,authToken:n.authToken,sessionHandler:n.sessionHandler}});this.appId=n.appId,this.aiAgentId=n.aiAgentId,this.language=n.language??"en",this.countryCode=n.countryCode,this.context=n.context,this._config=ys(n.config),this.queryParams=n.queryParams,this._networkStateAdapter=n.networkStateAdapter,this._scheduleForegroundTask=n.scheduleForegroundTask,this._forceCreateChannel=n.forceCreateChannel,this._agentVersion=n.agentVersion,this._chatClient=n.chatClient,this._deskClient=n.deskClient,this._cache=n.cache,this._logger=n.logger,this._dispatcher=n.dispatcher,this._statsTrackers=n.statsTrackers,this._liveMetricManager=new fl(this._chatClient.chatSDK),this._liveMetricManager.start()}static init(n){var g;const r=pi.get(n.platform),s=n.logger??new ii(n.logLevel??wr.WARN),o=n.dispatcher??new ri(s),i=n.useMMKVStorage?du(n.useMMKVStorage):r.keyValueStorage,c=n.useMMKVStorage?{...n.chatParams,useMMKVStorageStore:n.useMMKVStorage}:n.chatParams,u=Dc({appId:n.appId,aiAgentId:n.aiAgentId,storage:i});let d;const h=gu((C,v)=>{if(!d)throw new Error("ChatClient is not initialized.");return d.chatSDK.aiAgent.appendStat(C,v)});d=Or.init({appId:n.appId,aiAgentId:n.aiAgentId,messengerVersion:r.messengerVersion,extensions:{platform:r.platform,deviceOSPlatform:r.deviceOSPlatform,deviceOSVersion:r.deviceOSVersion},chatParams:c,chatSDK:n.chatSDK,logger:s,cache:u,statsTrackers:h});const f=hu?$r.init({appId:n.appId,logger:s,customApiHost:(g=n.deskParams)==null?void 0:g.customApiHost}):Fr.init();return s.debug("AIAgent.init: created",{appId:n.appId,aiAgentId:n.aiAgentId}),new Sn({appId:n.appId,aiAgentId:n.aiAgentId,language:n.language,countryCode:n.countryCode,context:n.context,config:n.config,queryParams:n.queryParams,networkStateAdapter:r.networkStateAdapter,scheduleForegroundTask:r.scheduleForegroundTask??(C=>C()),forceCreateChannel:n._forceCreateChannel,agentVersion:n._agentVersion,chatClient:d,deskClient:f,cache:u,logger:s,dispatcher:o,statsTrackers:h})}get chatSDK(){return this._chatClient.chatSDK}get deskClient(){return this._deskClient}get session(){return this._session}get config(){return this._config}set config(n){this._config=ys(n)}get agentVersion(){return this._agentVersion}set agentVersion(n){this._agentVersion=n}get statsTrackers(){return this._statsTrackers}get liveMetricManager(){return this._liveMetricManager}get onLiveMetric(){return this._liveMetricManager.dispatch}set onLiveMetric(n){this._liveMetricManager.dispatch=n}get networkStateAdapter(){return this._networkStateAdapter}get logger(){return this._logger}get dispatcher(){return this._dispatcher}get cache(){return this._cache}get scheduleForegroundTask(){return this._scheduleForegroundTask}}const be=(e,t)=>{const n=l.createContext(t??null),r=({children:i,value:c})=>a.createElement(n.Provider,{value:c},typeof i=="function"?i(c):i),s=({children:i})=>a.createElement(n.Consumer,null,c=>c?typeof i=="function"?i(c):i:null),o=()=>{const i=l.useContext(n);if(!i)throw new Error(`use${e}Context must be used within a ${e}Provider`);return i};return n.displayName=`${e}Context`,r.displayName=`${e}Provider`,s.displayName=`${e}Consumer`,o.displayName=`use${e}Context`,{Context:n,Provider:r,Consumer:s,useContext:o}};function je(e){const t=l.createContext({Template:e.template,updateTemplate:()=>{},components:e.components,updateComponent:()=>{}});function n({children:o}){const[i,c]=l.useState(()=>e.template),[u,d]=l.useState(e.components),m={Template:i,updateTemplate:h=>c(()=>h),components:u,updateComponent:(h,f)=>d(g=>({...g,[h]:f}))};return a.createElement(t.Provider,{value:m},o)}function r({template:o,children:i}){const{updateTemplate:c}=l.useContext(t);return l.useLayoutEffect(()=>{o&&c(o)},[o]),a.createElement(a.Fragment,null,i)}function s({children:o}){return a.createElement(n,null,o)}return s.defaults=e,s.useContext=()=>l.useContext(t),s.Context=t,s.Template=r,Object.keys(e.components).forEach(o=>{s[o]=function({component:c}){const{updateComponent:u}=l.useContext(t);return l.useLayoutEffect(()=>{c&&u(o,c)},[c]),null}}),s}function pu(...e){return function({children:n}){return e.reduce((r,s)=>a.createElement(s,null,r),n)}}function _u(e,t){const n=e.lastMessage;return n!=null&&n.isAdminMessage()?n.message??"":Ei(e,t)}function Ei(e,t){var r;const n=e.lastMessage;if(n!=null&&n.isUserMessage())return n.message||"";if(n!=null&&n.isAdminMessage())return n.message??"";if(n!=null&&n.isFileMessage())return n.message||n.name||"FILE";if(n!=null&&n.isMultipleFilesMessage()){if(n.message)return n.message;const s=n.fileInfoList.length;return((r=t==null?void 0:t.formatMultipleFilesCount)==null?void 0:r.call(t,s))??`${s} photos`}return e.name}function Eu(e,t,n){var i;const r=new Date,s=new Date(((i=e.lastMessage)==null?void 0:i.createdAt)||e.createdAt),o=at.differenceInMinutes(r,s);return o<1?n.justNow:o<60?n.minutesAgo(o):at.isToday(s)?n.hoursAgo(at.differenceInHours(r,s)):t(s,n.dateShortFormat)}const Cu=e=>{const t=e.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null},sn=e=>Math.max(0,Math.min(255,e)).toString(16).padStart(2,"0"),Ts=(e,t)=>{const n=sn(Math.round(t*255));if(e.startsWith("#")){const s=e.slice(1);return s.length===3||s.length===4?`#${s[0]}${s[0]}${s[1]}${s[1]}${s[2]}${s[2]}${n}`:`#${s.slice(0,6)}${n}`}const r=Cu(e);return r?`#${sn(r[0])}${sn(r[1])}${sn(r[2])}${n}`:e},bu=(e,t)=>{if(!t)return e;const n={...e};for(const[r,s]of Object.entries(t))s&&(n[r]=s);return n},vu=e=>e.consentDialog?"consent":e.toggleAllowed?e.enabled?"on":"off":"readonly",yu=e=>e.length>0,Su=e=>{const t=e[0];if(!t)return e;const n=e.some(s=>Ye(s.type)),r=e.some(s=>!Ye(s.type));return n&&r?Ye(t.type)?e.filter(s=>Ye(s.type)):[t]:r?[t]:e},Is=e=>e.length===0?"empty":e.every(t=>Ye(t.type))?"images":"non_images",Au=({currentFiles:e,incomingFiles:t,maxAttachmentCount:n})=>{const r=Su(t),s=Is(e),o=Is(r),c=s==="images"&&o==="images"?{type:"append",files:r,nextFiles:[...e,...r]}:{type:"replace",files:r,nextFiles:r};return c.nextFiles.length>n?{type:"reject",reason:"count_limit",maxAttachmentCount:n,nextFileCount:c.nextFiles.length}:c.type==="replace"&&s!=="empty"&&s!==o?{type:"confirm_replace",action:c}:{type:"apply",action:c}},At=3,Ci=6,Tu=e=>e%At===0?At:Ci,Iu=({index:e,itemCount:t})=>{const n=t%At,r=n>0,s=r?t-n:t,o=r&&e>=s,i=o?n:At,c=o?e-s:e%At,u=!r&&e>=t-At;return{columnSpan:r?Ci/i:1,rowItemCount:i,isLastInRow:c===i-1,isLastRow:o||u}},bi=be("AIAgent"),xu=bi.Provider,ke=bi.useContext;function Ru(e){const t=Mu(e);return a.createElement(xu,{value:{_aiAgentSDK:t,chatSDK:t.chatSDK,deskClient:t.deskClient,appId:t.appId,aiAgentId:t.aiAgentId,language:t.language,countryCode:t.countryCode,context:t.context,logger:t.logger,dispatcher:t.dispatcher,cache:t.cache,networkStateAdapter:t.networkStateAdapter,queryParams:t.queryParams,config:t.config,handlers:e.handlers}},e.children)}function Mu(e){var s;const t=l.useRef(null),n=l.useRef(null);if(!t.current||!n.current)t.current=Sn.init(e);else{const o=wu(n.current,e);(o.appId||o.aiAgentId||o.chatSDK)&&(t.current.dispose(),t.current=Sn.init({...e,chatParams:o.appId?{...e.chatParams,newInstance:!0}:e.chatParams}))}n.current=e,l.useEffect(()=>()=>{var o;(o=t.current)==null||o.dispose()},[]);const r=t.current;return r.language=e.language??"en",r.countryCode=e.countryCode,r.context=e.context,r.queryParams=e.queryParams,r.config=e.config,r.agentVersion=e._agentVersion,r.onLiveMetric=(s=e.handlers)==null?void 0:s.onLiveMetric,r}function wu(e,t){const n=t.chatSDK!==void 0&&t.chatSDK!==null;return{appId:!n&&e.appId!==t.appId,aiAgentId:e.aiAgentId!==t.aiAgentId,chatSDK:!!e.chatSDK!==n||n&&t.chatSDK!==e.chatSDK}}function ie(e){const t=l.useRef(e);return t.current=e,l.useCallback((...n)=>t.current(...n),[t])}const xs=Symbol("conversationMessageEventBridge"),wt=Symbol("conversationMessageEventPublisher"),ku=(e,t)=>{const n=e;if(n[wt]=t,n[xs])return e;n[xs]=!0;const r=e.setMessageCollectionHandler.bind(e);e.setMessageCollectionHandler=o=>{r({...o,onMessagesAdded:(i,c,u)=>{var d,m;(d=o.onMessagesAdded)==null||d.call(o,i,c,u),(m=n[wt])==null||m.call(n,{kind:"messagesAdded",source:i.source,messages:u})},onMessagesUpdated:(i,c,u)=>{var d,m;(d=o.onMessagesUpdated)==null||d.call(o,i,c,u),(m=n[wt])==null||m.call(n,{kind:"messagesUpdated",source:i.source,messages:u})}})};const s=e.initialize.bind(e);return e.initialize=o=>{const i=s(o),c=i.onCacheResult.bind(i),u=i.onApiResult.bind(i);return i.onCacheResult=d=>c((m,h)=>{var f;d(m,h),(f=n[wt])==null||f.call(n,{kind:"initialized",source:"cache",messages:h??[]})}),i.onApiResult=d=>u((m,h)=>{var f;d(m,h),(f=n[wt])==null||f.call(n,{kind:"initialized",source:"api",messages:h??[]})}),i},e},Nn=()=>{const[,e]=l.useState(0);return l.useCallback(()=>e(t=>t+1),[])};let Lu=0;function Ou(){return l.useState(()=>`${Lu++}`)[0]}const ht=(e,t,n)=>{const r=l.useRef(t),o=Ou();r.current=t,l.useEffect(()=>{var c;const i=u=>{const d=u;return Object.keys(d).forEach(h=>{d[h]=(...f)=>{var C;const g=r.current;(C=g[h])==null||C.call(g,...f)}}),d};return(c=e==null?void 0:e.groupChannel)==null||c.addGroupChannelHandler(o,i(new We.GroupChannelHandler)),()=>{var u;(u=e==null?void 0:e.groupChannel)==null||u.removeGroupChannelHandler(o)}},[e==null?void 0:e.groupChannel,o])};function Nu(e,t){return!e||!t?!0:e.url!==t.url}function ze(e){return e!=null&&"sendingStatus"in e}function Du(e,t="##__USER_ID_IS_NOT_PROVIDED__##"){var n;return ze(e)?((n=e.sender)==null?void 0:n.userId)===t:!1}function $u(e,t){return Du(e,t)||e.isAdminMessage()?!1:e.updatedAt===0}function Rs(e){return"sendingStatus"in e?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId)}const An={collection:{groupChannel:{defaultOrder:We.GroupChannelListOrder.LATEST_LAST_MESSAGE},message:{defaultLimit:{next:25,prev:25},searchLimit:{next:10,prev:10}}}};function Ms(e){return!e||!Array.isArray(e)?!1:e.length!==0}function ws(e,t){return e.reduce((n,r)=>{const s=t(r);return n[s]=r,n},{})}const Fu=({...e},t)=>{switch(t.type){case"update_initialized":return e.initialized=t.value.status,e;case"update_refreshing":return e.refreshing=t.value.status,e;case"update_loading":return e.loading=t.value.status,e;case"update_messages":{if(t.value.clearBeforeAction)e.messageMap=Pu(t.value.messages);else{const n={...e.messageMap},r=[],s=[];t.value.messages.forEach(o=>{const i=ze(o)?o.reqId:void 0,c=o.messageId||void 0;[i,c].forEach(u=>{if(!u)return;const d=n[u];Uu(d,o,t.value.strictStreamingOrder)&&(d&&r.push(d),o.parentMessageId>0&&(d!=null&&d.parentMessage)&&o.applyParentMessage(d.parentMessage),s.push(o))})}),r.forEach(o=>{ze(o)&&delete n[o.reqId],delete n[o.messageId]}),s.forEach(o=>{ze(o)&&(n[o.reqId]=o),o.messageId!==0&&(n[o.messageId]=o)}),e.messageMap=n}return e}case"update_new_messages":{const n=t.value.currentUserId,r=t.value.messages.filter(s=>$u(s,n));return t.value.clearBeforeAction?e.newMessageMap=ws(r,Rs):(r.map(o=>o.messageId).forEach(o=>delete e.newMessageMap[o]),e.newMessageMap={...e.newMessageMap,...ws(r,Rs)}),e}case"delete_messages":case"delete_new_messages":{const n=t.type==="delete_messages"?"messageMap":"newMessageMap";return e[n]={...e[n]},t.value.messageIds.forEach(r=>{if(r===0)return;const s=e[n][r];s&&(ze(s)&&delete e[n][s.reqId],delete e[n][s.messageId])}),t.value.reqIds.forEach(r=>{const s=e[n][r];s&&(ze(s)&&delete e[n][s.reqId],delete e[n][s.messageId])}),e}}},Pu=e=>e.reduce((t,n)=>(ze(n)?(t[n.reqId]=n,n.sendingStatus===Fe.SendingStatus.SUCCEEDED&&(t[n.messageId]=n)):t[n.messageId]=n,t),{}),Uu=(e,t,n=!1)=>{var r,s;if(!ze(e)||!ze(t))return!0;if(n&&e&&Me.isStreaming(e)&&Me.isStreaming(t)){const o=((r=e.message)==null?void 0:r.length)||0,i=((s=t.message)==null?void 0:s.length)||0;if(o>i)return!1}return e.sendingStatus===Fe.SendingStatus.SUCCEEDED?t.sendingStatus===Fe.SendingStatus.SUCCEEDED:e.sendingStatus!==t.sendingStatus},Bu=(e=Hu)=>{const[{initialized:t,loading:n,refreshing:r,messageMap:s,newMessageMap:o},i]=l.useReducer(Fu,{initialized:!1,loading:!0,refreshing:!1,messageMap:{},newMessageMap:{}}),c=(_,p,S,A)=>{i({type:"update_messages",value:{messages:_,clearBeforeAction:p,currentUserId:S,strictStreamingOrder:A}})},u=(_,p)=>{i({type:"delete_messages",value:{messageIds:_,reqIds:p}})},d=(_,p,S)=>{i({type:"update_new_messages",value:{messages:_,clearBeforeAction:p,currentUserId:S}})},m=(_,p)=>{i({type:"delete_new_messages",value:{messageIds:_,reqIds:p}})},h=_=>{i({type:"update_initialized",value:{status:_}})},f=_=>{i({type:"update_loading",value:{status:_}})},g=_=>{i({type:"update_refreshing",value:{status:_}})},C=Object.values(o),v=l.useMemo(()=>Array.from(new Set(Object.values(s))).sort(e),[s]);return{updateInitialized:h,updateLoading:f,updateRefreshing:g,updateMessages:c,deleteMessages:u,initialized:t,loading:n,refreshing:r,messages:v,newMessages:C,updateNewMessages:d,deleteNewMessages:m}},ks=Math.floor(Number.MAX_SAFE_INTEGER/10);function Hu(e,t){let n=0,r=0;return ze(e)&&e.sendingStatus!=="succeeded"&&(n=ks),ze(t)&&t.sendingStatus!=="succeeded"&&(r=ks),e.createdAt+n-(t.createdAt+r)}const Gu=(e,t,n)=>{var o;const r={prevResultLimit:t.prev,nextResultLimit:t.next,startingPoint:n==null?void 0:n.startingPoint,replyType:n==null?void 0:n.replyType},s=(o=n==null?void 0:n.collectionCreator)==null?void 0:o.call(n,r);return s||e.createMessageCollection({...r,filter:new We.MessageFilter(r)})};function Ls(e){return e<Date.now()?An.collection.message.searchLimit:An.collection.message.defaultLimit}const zu=(e,t,n={})=>{var Le,$;const r=l.useRef(n);r.current=n;const s=l.useRef(t);s.current=t;const o=r.current.logger,i=r.current.startingPoint??Number.MAX_SAFE_INTEGER,c=Ls(i),u=r.current.strictStreamingOrder??!1,d=l.useRef({prev:!1,next:!1}),m=Nn(),h=l.useRef({initialized:!1,apiInitialized:!1,instance:null}),{initialized:f,loading:g,refreshing:C,messages:v,newMessages:_,updateMessages:p,updateNewMessages:S,deleteNewMessages:A,deleteMessages:T,updateInitialized:M,updateLoading:L,updateRefreshing:D}=Bu(n==null?void 0:n.sortComparator),x=ie(I=>{var w,N,z,Y;if(!s.current||!s.current.url)return(w=o==null?void 0:o.error)==null?void 0:w.call(o,"[useGroupChannelMessages] channel is required");try{switch(I){case ue.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case ue.CollectionEventSource.EVENT_MESSAGE_SENT_SUCCESS:case ue.CollectionEventSource.SYNC_MESSAGE_FILL:case void 0:(z=(N=r.current).markAsRead)==null||z.call(N,[s.current]);break}}catch(te){(Y=o==null?void 0:o.warn)==null||Y.call(o,"[useGroupChannelMessages/markAsReadBySource]",te)}}),O=ie((I,w)=>{var N,z,Y,te,Z;if(w.length>0)switch(I){case ue.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case ue.CollectionEventSource.SYNC_MESSAGE_FILL:{(z=(N=r.current).shouldCountNewMessages)!=null&&z.call(N)&&S(w,!1,(Y=e.currentUser)==null?void 0:Y.userId),(Z=(te=r.current).onMessagesReceived)==null||Z.call(te,w);break}}}),H=ie(I=>{var w,N;(N=(w=r.current).onCollectionEvent)==null||N.call(w,I)}),F=ie(async(I,w,N)=>new Promise((z,Y)=>{var Xe;h.current.instance&&h.current.instance.dispose(),x(),S([],!0,(Xe=e.currentUser)==null?void 0:Xe.userId);const te=()=>{var _e,Ee;const{pendingMessages:ae,failedMessages:he}=h.current.instance??{};Ms(ae)&&p(ae,!1,(_e=e.currentUser)==null?void 0:_e.userId),Ms(he)&&p(he,!1,(Ee=e.currentUser)==null?void 0:Ee.userId)},Z=Gu(I,N,{...r.current,startingPoint:w});h.current={apiInitialized:!1,initialized:!1,instance:Z},Z.setMessageCollectionHandler({onMessagesAdded:(ae,he,_e)=>{var Ee;x(ae.source),O(ae.source,_e),p(_e,!1,(Ee=e.currentUser)==null?void 0:Ee.userId,u),H({kind:"messagesAdded",source:ae.source,channelUrl:I.url,messages:_e})},onMessagesUpdated:(ae,he,_e)=>{var Ee,Ce,Te;x(ae.source),O(ae.source,_e),p(_e,!1,(Ee=e.currentUser)==null?void 0:Ee.userId,u),ae.source===ue.CollectionEventSource.EVENT_MESSAGE_UPDATED&&((Te=(Ce=r.current).onMessagesUpdated)==null||Te.call(Ce,_e)),H({kind:"messagesUpdated",source:ae.source,channelUrl:I.url,messages:_e})},onMessagesDeleted:(ae,he,_e,Ee)=>{const Ce=Ee.map(ve=>ve.messageId),Te=Ee.filter(ze).map(ve=>ve.reqId);T(Ce,Te),A(Ce,Te),H({kind:"messagesDeleted",source:ae.source,channelUrl:I.url,messages:Ee})},onChannelDeleted:(ae,he)=>{var _e,Ee;(Ee=(_e=r.current).onChannelDeleted)==null||Ee.call(_e,he)},onChannelUpdated:(ae,he)=>{var _e,Ee;m(),(Ee=(_e=r.current).onChannelUpdated)==null||Ee.call(_e,he,ae)},onHugeGapDetected:()=>{F(I,Number.MAX_SAFE_INTEGER,An.collection.message.defaultLimit)}});let pe=!1;Z.initialize(We.MessageCollectionInitPolicy.CACHE_AND_REPLACE_BY_API).onCacheResult((ae,he)=>{var _e,Ee,Ce,Te,ve;(Ee=(_e=r.current).onCacheResult)==null||Ee.call(_e,ae,he??[],I.url),ae?(e.isCacheEnabled&&((Ce=o==null?void 0:o.error)==null||Ce.call(o,"[useGroupChannelMessages/onCacheResult]",ae)),pe=!0):he&&((Te=o==null?void 0:o.debug)==null||Te.call(o,"[useGroupChannelMessages/onCacheResult]","message length:",he.length),p(Z.succeededMessages,!0,(ve=e.currentUser)==null?void 0:ve.userId),te(),he.length>0&&(h.current.initialized=!0,z())),H({kind:"initialized",source:"cache",channelUrl:I.url,messages:he??[]})}).onApiResult((ae,he)=>{var _e,Ee,Ce,Te,ve,$e,Pe;(Ee=(_e=r.current).onApiResult)==null||Ee.call(_e,ae,he??[],I.url),h.current.initialized=!0,h.current.apiInitialized=!0,ae?((Ce=o==null?void 0:o.warn)==null||Ce.call(o,"[useGroupChannelMessages/onApiResult]",ae),pe?Y(ae):z()):he&&((Te=o==null?void 0:o.debug)==null||Te.call(o,"[useGroupChannelMessages/onApiResult]","message length:",he.length),p(Z.succeededMessages,!0,(ve=e.currentUser)==null?void 0:ve.userId),r.current.startingPoint||(Pe=($e=r.current).onMessagesReceived)==null||Pe.call($e,he),e.isCacheEnabled&&te(),z()),H({kind:"initialized",source:"api",channelUrl:I.url,messages:he??[]})})}));ht(e,{onUserBanned(I,w){var N,z,Y;I.isGroupChannel()&&!Nu(I,s.current)&&(w.userId===((N=e.currentUser)==null?void 0:N.userId)?(Y=(z=r.current).onCurrentUserBanned)==null||Y.call(z):m())}}),l.useLayoutEffect(()=>{const I=setTimeout(async()=>{e.currentUser&&s.current&&(M(!1),L(!0),await F(s.current,i,c),L(!1),M(!0))});return()=>clearTimeout(I)},[e,(Le=e.currentUser)==null?void 0:Le.userId,($=s.current)==null?void 0:$.url,r.current.replyType]),l.useEffect(()=>()=>{h.current.instance&&h.current.instance.dispose()},[]);const W=ie(async()=>{e.currentUser&&s.current&&(D(!0),await F(s.current,Number.MAX_SAFE_INTEGER,An.collection.message.defaultLimit),D(!1))}),q=ie(async()=>{var w;const I=h.current.instance;if(I!=null&&I.hasPrevious&&!d.current.prev)try{d.current.prev=!0;const N=await I.loadPrevious();p(N,!1,(w=e.currentUser)==null?void 0:w.userId)}catch{}finally{d.current.prev=!1}}),k=ie(()=>{const{initialized:I,instance:w}=h.current;return I&&w?w.hasPrevious:!1}),G=ie(async()=>{var w;const I=h.current.instance;if(I!=null&&I.hasNext&&!d.current.next)try{d.current.next=!0;const N=await I.loadNext();p(N,!1,(w=e.currentUser)==null?void 0:w.userId)}catch{}finally{d.current.next=!1}}),P=ie(()=>{const{initialized:I,apiInitialized:w,instance:N}=h.current;return w&&I&&N?N.hasNext:!1}),V=I=>{var w,N,z,Y;!I||I.channelUrl!==((w=s.current)==null?void 0:w.url)||(p([I],!1,(N=e.currentUser)==null?void 0:N.userId),(Y=(z=r.current).onOutgoingMessageStatusChanged)==null||Y.call(z,I))},me=ie((I,w)=>{var N;if(!s.current||!s.current.url)throw(N=o==null?void 0:o.error)==null||N.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((z,Y)=>{s.current.sendUserMessage(I).onPending(te=>{V(te),w==null||w(te)}).onSucceeded(te=>{V(te),z(te)}).onFailed((te,Z)=>{V(Z),Y(te)})})}),Ie=ie((I,w)=>{var N;if(!s.current||!s.current.url)throw(N=o==null?void 0:o.error)==null||N.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((z,Y)=>{s.current.sendFileMessage(I).onPending(te=>{V(te),w==null||w(te)}).onSucceeded(te=>{V(te),z(te)}).onFailed((te,Z)=>{V(Z),Y(te)})})}),j=ie((I,w,N)=>{var z;if(!s.current||!s.current.url)throw(z=o==null?void 0:o.error)==null||z.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((Y,te)=>{s.current.sendMultipleFilesMessage(I).onPending(Z=>{V(Z),w==null||w(Z)}).onFileUploaded(Z=>{N==null||N(Z),m()}).onSucceeded(Z=>{V(Z),Y(Z)}).onFailed((Z,pe)=>{V(pe),te(Z)})})}),K=ie(async(I,w)=>{var z,Y;if(!s.current||!s.current.url)throw(z=o==null?void 0:o.error)==null||z.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");const N=await s.current.updateUserMessage(I,w);return N.channelUrl===s.current.url&&p([N],!1,(Y=e.currentUser)==null?void 0:Y.userId),N}),R=ie(async(I,w)=>{var z,Y;if(!s.current||!s.current.url)throw(z=o==null?void 0:o.error)==null||z.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");const N=await s.current.updateFileMessage(I,w);return N.channelUrl===s.current.url&&p([N],!1,(Y=e.currentUser)==null?void 0:Y.userId),N}),X=ie(async(I,w,N)=>{var z;if(!s.current||!s.current.url)throw(z=o==null?void 0:o.error)==null||z.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((Y,te)=>{let Z;I.isUserMessage()&&(Z=s.current.resendMessage(I)),I.isFileMessage()&&(Z=s.current.resendMessage(I)),I.isMultipleFilesMessage()&&(Z=s.current.resendMessage(I)),Z&&("onPending"in Z&&Z.onPending(pe=>{V(pe),w==null||w(pe)}),"onFileUploaded"in Z&&Z.onFileUploaded(pe=>{N==null||N(pe),m()}),"onSucceeded"in Z&&Z.onSucceeded(pe=>{V(pe),Y(pe)}),"onFailed"in Z&&Z.onFailed((pe,Xe)=>{V(Xe),te(pe)}))})}),ne=ie(async I=>{var w,N;if(!s.current||!s.current.url)throw(w=o==null?void 0:o.error)==null||w.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");if(I.sendingStatus==="succeeded")I.isUserMessage()&&await s.current.deleteMessage(I),I.isFileMessage()&&await s.current.deleteMessage(I),I.isMultipleFilesMessage()&&await s.current.deleteMessage(I);else try{await((N=h.current.instance)==null?void 0:N.removeFailedMessage(I.reqId))}finally{T([],[I.reqId])}}),oe=ie(()=>{var I;S([],!0,(I=e.currentUser)==null?void 0:I.userId)}),Re=ie(async I=>{var w;if(e.currentUser&&s.current){const N=Ls(I);L(!0),p([],!0,(w=e.currentUser)==null?void 0:w.userId),await F(s.current,I,N),L(!1)}});return{initialized:f,loading:g,refreshing:C,messages:v,newMessages:_,resetNewMessages:oe,refresh:W,loadPrevious:q,hasPrevious:k,loadNext:G,hasNext:P,sendUserMessage:me,sendFileMessage:Ie,sendMultipleFilesMessage:j,updateUserMessage:K,updateFileMessage:R,resendMessage:X,deleteMessage:ne,resetWithStartingPoint:Re,_dangerous_reducer_updateMessages:p,_dangerous_reducer_deleteMessages:T}},Vu=(e,t,n)=>{const r=l.useRef(0),s=l.useRef(new Set),o=l.useCallback(d=>{const m={id:r.current+=1,...d};s.current.forEach(h=>{h(m)})},[]),i=l.useCallback(d=>{var h;const m=((h=n==null?void 0:n.collectionCreator)==null?void 0:h.call(n,d))??(t==null?void 0:t.createMessageCollection({...d??{},filter:new We.MessageFilter(d)}));if(!m)throw new Error("Group channel is required to create a message collection");return ku(m,o)},[t,n==null?void 0:n.collectionCreator,o]),c=zu(e,t,{...n,collectionCreator:i,strictStreamingOrder:!0}),u=l.useCallback(d=>(s.current.add(d),()=>{s.current.delete(d)}),[]);return{...c,subscribeMessageEvents:u}},qu=({channelUrl:e,enabled:t=!0,statsTracker:n})=>{const r=l.useRef(e),s=l.useRef(t),o=l.useRef(!1),i=l.useRef(null),c=l.useRef(null),u=l.useRef(null);s.current=t;const d=l.useCallback(p=>r.current===p,[]),m=l.useCallback(()=>{o.current&&(n.clear(),o.current=!1,i.current=null)},[n]),h=l.useCallback(p=>{if(!s.current)return;const S=!o.current||i.current!==p;n.start(p),S&&n.onGetChannelStart(p),o.current=!0,i.current=p},[n]),f=l.useCallback(p=>{d(p)&&(u.current=p,c.current=null,h(p))},[d,h]),g=l.useCallback(({channelUrl:p,conversationId:S})=>{o.current||h(p),n.onGetChannelComplete({channelUrl:p,conversationId:S})},[h,n]),C=l.useCallback(({channelUrl:p,error:S})=>{o.current||h(p),n.onGetChannelError({channelUrl:p,error:S})},[h,n]),v=l.useCallback(p=>{if(d(p.channelUrl)){if(u.current=null,!s.current){c.current=p;return}c.current=null,g(p)}},[d,g]),_=l.useCallback(p=>{if(d(p.channelUrl)){if(u.current=null,!s.current){c.current=p;return}c.current=null,C(p)}},[d,C]);return l.useEffect(()=>{if(t){const p=c.current;if(p){if(c.current=null,p.channelUrl!==e)return;"error"in p?C(p):g(p);return}const S=u.current;if(S){if(S!==e){u.current=null;return}h(S)}return}m()},[e,m,t,C,g,h]),l.useEffect(()=>(r.current=e,o.current=!1,i.current=null,c.current=null,u.current=null,()=>{m(),o.current=!1,i.current=null,c.current=null,u.current=null}),[e,m]),{onFetchStart:f,onFetchSuccess:v,onFetchError:_}},Ku=({channelUrl:e,enabled:t=!0,statsTracker:n})=>{const r=l.useRef(e),s=l.useRef(t),o=l.useRef(null),i=l.useRef(!1);s.current=t;const c=l.useCallback(C=>r.current===C,[]),u=l.useCallback(()=>{i.current&&(n.clearChannel(r.current),i.current=!1)},[n]),d=l.useCallback(C=>{c(C)&&s.current&&(i.current=!0)},[c]),m=l.useCallback(({channelUrl:C,conversationId:v})=>{i.current=!0,n.markChannelJoined(v,C)},[n]),h=l.useCallback(({channelUrl:C})=>{n.clearChannel(C),i.current=!1},[n]),f=l.useCallback(C=>{if(c(C.channelUrl)){if(!s.current){o.current=C;return}o.current=null,m(C)}},[c,m]),g=l.useCallback(C=>{if(c(C.channelUrl)){if(!s.current){o.current=C;return}o.current=null,h(C)}},[c,h]);return l.useEffect(()=>{if(t){const C=o.current;if(!C||(o.current=null,C.channelUrl!==e))return;"error"in C?h(C):m(C);return}u()},[e,u,t,h,m]),l.useEffect(()=>(r.current=e,o.current=null,i.current=!1,()=>{u(),o.current=null,i.current=!1}),[e,u]),{onFetchStart:d,onFetchSuccess:f,onFetchError:g}},Yu=({channelUrl:e,enabled:t=!0,scheduleForegroundTask:n,statsTracker:r})=>{const s=l.useRef(e),o=l.useRef(null),i=l.useRef(t),c=l.useRef(0),u=l.useRef(null);i.current=t;const d=l.useCallback((h=!0)=>{var g;(g=o.current)==null||g.call(o),o.current=null;const f=u.current;h&&(u.current=null),h&&f&&r.clearChannel(f)},[r]),m=l.useCallback(h=>{if(!i.current){d(),r.clearChannel(h);return}d(!1),u.current=h;const f=c.current,g=()=>{if(!i.current||f!==c.current||s.current!==h){r.clearChannel(h),u.current===h&&(u.current=null);return}r.start("ws_reconnected",h)};o.current=(n==null?void 0:n(g))??null,n||g()},[d,n,r]);return l.useEffect(()=>{t||d()},[d,t]),l.useEffect(()=>(s.current=e,c.current+=1,()=>{c.current+=1,d()}),[e,d]),{onReconnectSucceeded:m}},Bt={DEFAULT_PRIMARY:"#000000",DEFAULT_BOT_MSG_BG:"#ECECEC",WHITE:"#ffffff",BLACK:"#000000"};function vi(e){return e.length===4?`#${[...e.slice(1)].map(t=>t+t).join("")}`:e}function Wu(e){const t=vi(e);return[parseInt(t.slice(1,3),16),parseInt(t.slice(3,5),16),parseInt(t.slice(5,7),16)]}function ju(e){return`#${e.map(t=>t.toString(16).padStart(2,"0")).join("")}`}function Xu(e,t,n){e/=255,t/=255,n/=255;const r=Math.max(e,t,n),s=Math.min(e,t,n),o=r-s;let i=0,c=0;const u=(r+s)/2;return r!==s&&(c=u>.5?o/(2-r-s):o/(r+s)),r===e?i=(t-n)/o+(t<n?6:0):r===t?i=(n-e)/o+2:r===n&&(i=(e-t)/o+4),i/=6,[i,c,u]}function Zu(e,t,n){let r,s,o;if(t===0)r=s=o=n;else{const i=function(m,h,f){return f<0&&(f+=1),f>1&&(f-=1),f<.16666666666666666?m+(h-m)*6*f:f<.5?h:f<.6666666666666666?m+(h-m)*(.6666666666666666-f)*6:m},c=n<.5?n*(1+t):n+t-n*t,u=2*n-c;r=i(u,c,e+1/3),s=i(u,c,e),o=i(u,c,e-1/3)}return[Math.round(r*255),Math.round(s*255),Math.round(o*255)]}function on(e,t,n){const[r,s,o]=Wu(e),[i,c,u]=Xu(r,s,o),d=Math.max(0,Math.min(1,u*t)),m=Math.max(0,Math.min(1,c*n)),[h,f,g]=Zu(i,m,d);return ju([Math.round(h),Math.round(f),Math.round(g)])}function Ju(e,t="light"){return{extraDark:on(e,.6,1.2),dark:on(e,.85,1.1),main:e,light:on(e,t==="dark"?1.1:1.5,t==="dark"?.95:.9),extraLight:on(e,t==="dark"?1.2:1.75,t==="dark"?.9:.8)}}function mr(e){const t=vi(e),n=149,r=+`0x${t[1]}${t[2]}`,s=+`0x${t[3]}${t[4]}`,o=+`0x${t[5]}${t[6]}`;return r*.299+s*.587+o*.114>n?Bt.BLACK:Bt.WHITE}function Qu(e,t,n,r,s){return{base:{primary:t,primaryContrastContent:n,background:e.background50,headerBackground:e.background50,modalContentBackground:e.background50},messageInput:{text:e.onlight.textHighEmphasis,placeholderText:e.onlight.textLowEmphasis,background:e.background100},messageIncoming:{text:s,background:r},messageOutgoing:{text:n,background:t},csat:{background:e.background100},memoryDialog:{titleText:e.onlight.textHighEmphasis,markdownBodyText:e.onlight.textLowEmphasis,markdownLinkText:e.onlight.textHighEmphasis,positiveBackground:e.onlight.textHighEmphasis,positiveText:e.ondark.textHighEmphasis,positiveBorderColor:"transparent",negativeBackground:"transparent",negativeText:e.onlight.textHighEmphasis,negativeBorderColor:"transparent"}}}const ed=(e,t,n,r,s)=>({base:{primary:t,primaryContrastContent:n,background:e.background600,headerBackground:e.background500,modalContentBackground:e.background500},messageInput:{text:e.ondark.textHighEmphasis,placeholderText:e.ondark.textLowEmphasis,background:e.background400},messageIncoming:{text:s,background:r},messageOutgoing:{text:n,background:t},csat:{background:e.background400},memoryDialog:{titleText:e.ondark.textHighEmphasis,markdownBodyText:e.ondark.textLowEmphasis,markdownLinkText:e.ondark.textHighEmphasis,positiveBackground:e.ondark.textHighEmphasis,positiveText:e.onlight.textHighEmphasis,positiveBorderColor:"transparent",negativeBackground:"transparent",negativeText:e.ondark.textHighEmphasis,negativeBorderColor:"transparent"}}),an={primary:{extraDark:"#491389",dark:"#6211c8",main:"#742ddd",light:"#c2a9fa",extraLight:"#dbd1ff"},secondary:{extraDark:"#066858",dark:"#027d69",main:"#259c72",light:"#69c085",extraLight:"#a8e2ab"},error:{extraDark:"#9d091e",dark:"#bf0711",main:"#de360b",light:"#f66161",extraLight:"#fdaaaa"},information:{extraDark:"#241389",dark:"#362ca9",main:"#4a48cd",light:"#a9bbfa",extraLight:"#d1dbff"},background700:"#000000",background600:"#161616",background500:"#2c2c2c",background400:"#393939",background300:"#bdbdbd",background200:"#e0e0e0",background100:"#eeeeee",background50:"#ffffff",onlight:{textHighEmphasis:"rgba(0, 0, 0, 1)",textMidEmphasis:"rgba(0, 0, 0, 0.75)",textLowEmphasis:"rgba(0, 0, 0, 0.55)",textDisabled:"rgba(0, 0, 0, 0.12)"},ondark:{textHighEmphasis:"rgba(255, 255, 255, 1)",textMidEmphasis:"rgba(255, 255, 255, 0.75)",textLowEmphasis:"rgba(255, 255, 255, 0.58)",textDisabled:"rgba(255, 255, 255, 0.12)"},overlay:{dark:"rgba(0, 0, 0, 0.55)",light:"rgba(22, 22, 22, 0.32)"}},Wn={h1:{fontSize:18,fontWeight:700},h2:{fontSize:16,fontWeight:700},subtitle1:{fontSize:16,fontWeight:500},subtitle2:{fontSize:16,fontWeight:400},body1:{fontSize:16,fontWeight:400},body2:{fontSize:14,fontWeight:500},body3:{fontSize:14,fontWeight:400},button:{fontSize:14,fontWeight:700},caption1:{fontSize:12,fontWeight:700},caption2:{fontSize:12,fontWeight:400},caption3:{fontSize:11,fontWeight:700},caption4:{fontSize:11,fontWeight:400}};function Os(e){const t=td(e),n=nd(e,t),r=sd(n,e.colors,e.selectedTheme),s=id(e);return{selectedTheme:e.selectedTheme,palette:t,colors:r,aiAgentColorVariables:{primary_color:r.base.primary,primary_contrast_color:r.base.primaryContrastContent,bot_message_bg_color:r.messageIncoming.background,bot_message_bg_contrast_color:r.messageIncoming.text},typography:s}}function td({selectedTheme:e,palette:t,primary:n}){const r=t!=null&&t.primary?t.primary:n?n===an.primary.main?an.primary:Ju(n,e):an.primary;return{...an,primary:r,...t}}function nd({selectedTheme:e,primaryContrast:t,botMessageBackground:n,botMessageBackgroundContrast:r},s){const o=s.primary.main,i=t??mr(o),c=n??Bt.DEFAULT_BOT_MSG_BG,u=r??mr(c);return(e==="light"?Qu:ed)(s,o,i,c,u)}function rd(e,t,n){return typeof e=="string"?e:e[t]??n}function sd(e,t,n){var i;if(!t||Object.keys(t).length===0)return e;const r={...e},s=r,o=e;for(const c of Object.keys(t)){const u=t[c];if(u){s[c]={...s[c]};for(const[d,m]of Object.entries(u))if(m!==void 0){const h=((i=o[c])==null?void 0:i[d])??"";s[c][d]=rd(m,n,h)}}}return r}function od(e,t,n){const r={...e};return n.forEach(s=>{const o=t[s];o!=null&&(r[s]=o)}),r}function id({typography:e}){if(!e)return Wn;const t={...Wn};return Object.keys(e).forEach(n=>{const r=e[n];if(r&&typeof r=="object"){const s=Wn[n],o=["fontSize","fontWeight","fontFamily","lineHeight"];t[n]=od(s,r,o)}}),t}const{Provider:ad,useContext:Pr}=be("AIAgentTheme");function cd({logger:e,palette:t,typography:n,colors:r,appearance:s,children:o}){const i=l.useRef(null),[c,u]=l.useState(()=>Os({selectedTheme:(s==null?void 0:s.theme)??"light",palette:t,typography:n,colors:r,primary:s==null?void 0:s.primaryColor,botMessageBackground:s==null?void 0:s.botMessageBackgroundColor})),d=l.useCallback((m,h)=>{h&&(i.current=h);const f=(s==null?void 0:s.theme)??m,g=i.current?i.current.themes[f]:null,C={primary:s==null?void 0:s.primaryColor,primaryContrast:void 0,botMessageBackground:s==null?void 0:s.botMessageBackgroundColor,botMessageBackgroundContrast:void 0};!C.primary&&(g!=null&&g.primary_color)&&(C.primary=g.primary_color,C.primaryContrast=g.primary_contrast_color),!C.botMessageBackground&&(g!=null&&g.bot_message_bg_color)&&(C.botMessageBackground=g.bot_message_bg_color,C.botMessageBackgroundContrast=g.bot_message_bg_contrast_color);const v=Os({selectedTheme:f,palette:t,typography:n,colors:r,...C});u(v),e==null||e.info("theme.update:",f)},[s==null?void 0:s.theme,s==null?void 0:s.primaryColor,s==null?void 0:s.botMessageBackgroundColor,t,n,r,e]);return l.useEffect(()=>{(s!=null&&s.theme||s!=null&&s.primaryColor||s!=null&&s.botMessageBackgroundColor)&&d(c.selectedTheme)},[s==null?void 0:s.theme,s==null?void 0:s.primaryColor,s==null?void 0:s.botMessageBackgroundColor]),a.createElement(ad,{value:{theme:c,updateTheme:d}},o)}const jn=25*1024*1024,Ns=1,Ds=new Set(["image/png","image/jpeg","image/jpg"]),$s=new Set(["application/pdf"]),ld={off:"off",always:"always",handed_off_only:"handed_off_only"},ud=()=>{const[e,t]=l.useState(()=>({maxAttachmentCount:Ns,attachmentMode:"handed_off_only",defaultUploadSizeLimit:jn,uploadSizeLimitPerType:new Map,supportedImageMimeTypes:Ds,supportedFileMimeTypes:$s})),n=l.useCallback(({active_channel:s,upload_restriction:o})=>{t({maxAttachmentCount:(o==null?void 0:o.max_attachment_count)??Ns,attachmentMode:ld[s.attachment_mode]??"handed_off_only",defaultUploadSizeLimit:(o==null?void 0:o.default_upload_size_limit)??jn,uploadSizeLimitPerType:new Map(Object.entries((o==null?void 0:o.upload_size_limit_per_type)??[])),supportedImageMimeTypes:new Set((o==null?void 0:o.supported_image_mime_types)??Ds),supportedFileMimeTypes:new Set((o==null?void 0:o.supported_file_mime_types)??$s)})},[]),r=l.useCallback(s=>{const{channel:o,uploadSizeLimit:i=jn}=s,c=(d=!0)=>o!=null&&o.isAIAgent?d?rt(o):!1:!0,u=d=>{if(c())return e.defaultUploadSizeLimit??i;const m=e.defaultUploadSizeLimit??i,h=e.uploadSizeLimitPerType.get(d)??m;return Math.min(m,h)};return{maxAttachmentCount:e.maxAttachmentCount,isEnabled:()=>{if(c(!1))return!0;switch(e.attachmentMode){case"off":return!1;case"always":return!0;case"handed_off_only":return rt(o);default:return!0}},get supportedMimeTypes(){return c()?[lr]:[...e.supportedImageMimeTypes,...e.supportedFileMimeTypes]},isSupportedMimeType:d=>c()?!0:e.supportedImageMimeTypes.has(d)||e.supportedFileMimeTypes.has(d),getUploadSizeLimit:u,getUploadSizeLimitInMB:d=>u(d)/(1024*1024)}},[e]);return{updateBaseAttachmentRules:n,createAttachmentRules:r}},Fs=(...e)=>{const[t,n,r]=e;if(e.length===1&&typeof t=="object"&&t!==null)return{type:"active",context:t};if(e.length===3&&typeof t=="string"&&typeof n=="string"&&typeof r=="object"&&r!==null)return{type:"specific",aiAgentId:t,channelUrl:n,context:r};throw new Error("Invalid arguments: expected (context) or (aiAgentId, channelUrl, context)")},kt=e=>({...e,context:e.context??{}}),{Provider:dd,useContext:ft}=be("AIAgentMessengerSession"),md=l.forwardRef(function({userSessionInfo:e,children:t},n){const{_aiAgentSDK:r,chatSDK:s,aiAgentId:o,logger:i}=ke(),{updateTheme:c}=Pr(),[u,d]=l.useState(void 0),[m,h]=l.useState(void 0),[f,g]=l.useState(null),[C,v]=l.useState(null),[_,p]=l.useState(null),[S,A]=l.useState(null),[T,M]=l.useState(null),{updateBaseAttachmentRules:L,createAttachmentRules:D}=ud();l.useEffect(()=>{const F=r.onMessengerSettingsUpdated(({settings:k})=>{const{appearance:G,bot:P,launcher:V,memory:me}=k;c(G.selected_theme,G),p(Kl(P)),A(Yl(V)),M(me?dr(me):null),L(k)}),W=r.onActiveChannelUpdated(({channelUrl:k,status:G,conversationStatus:P})=>{h({url:k,status:G,conversationStatus:P})}),q=r.onAuthTokenRefreshed(()=>{var G;const k=(G=r.session)==null?void 0:G.userSession.authToken;k&&v(P=>P?{...P,authToken:k}:null)});return()=>{F(),W(),q()}},[r,c,L]);const x=l.useCallback(async()=>{try{const F=await r.authenticate(e),W=r.session;return g(W.sdkUser),v(W.userSession),h(W.activeChannel),d(void 0),F}catch(F){throw g(null),v(null),h(void 0),d(F),F}},[r,e]),O=l.useCallback(async()=>{await r.deauthenticate(),g(null),h(void 0),v(null),p(null),A(null),M(null)},[r]),H=l.useCallback(async()=>{if(!r.session){if(C)return i.debug("agentMessengerSession.refreshActiveChannel: stale call after deauthenticate, skipping"),"";throw i.error("agentMessengerSession.refreshActiveChannel: userSession is not ready"),new Error("userSession is not ready")}return r.session.userSession.userId!==(C==null?void 0:C.userId)?(i.debug("agentMessengerSession.refreshActiveChannel: stale call from previous session, skipping"),r.session.activeChannel.url):(h(void 0),await r.refreshActiveChannel())},[r,i,C]);return l.useImperativeHandle(n,()=>{const F=async()=>{if(!m)throw new Error("No active conversation. Please start a conversation first.");return await s.groupChannel.getChannel(m.url)};return{activeChannel:m,chatSDK:s,authenticate:x,deauthenticate:O,updateContext:async(...W)=>{const q=Fs(...W);if(q.type==="active"){const P=await(await F()).updateContext(o,q.context);return kt(P)}const k=await s.aiAgent.updateContext(q.aiAgentId,q.channelUrl,q.context);return kt(k)},patchContext:async(...W)=>{const q=Fs(...W);if(q.type==="active"){const P=await(await F()).patchContext(o,q.context);return kt(P)}const k=await s.aiAgent.patchContext(q.aiAgentId,q.channelUrl,q.context);return kt(k)},getContextObject:async()=>{const q=await(await F()).getContextObject(o);return kt(q)}}},[x,O,m,s,o,i]),a.createElement(dd,{value:{sdkUser:f,userSessionInfo:e,userSession:C,activeChannel:m,setActiveChannel:h,refreshActiveChannel:H,createConversation:r.createConversation,searchConversation:r.searchConversation,connectionError:u,aiAgentInfo:_,launcherInfo:S,memoryInfo:T,authenticate:x,deauthenticate:O,createAttachmentRules:D}},t)}),hd={ai_responding:"not_ready",conversation_closed:"ready",form_active:"ready",handoff_pending:"ready",reconnecting:"not_ready",steward:"ready",suggested_replies:"ready",system:"ready",unavailable:"not_ready"},fd=e=>e.disabled?hd[e.disabledBy]==="ready":!0,gd=e=>{var n,r,s,o,i;if(e.isUserMessage())return"text";const t=e.isFileMessage()?e.type:((r=(n=e.fileInfoList)==null?void 0:n[0])==null?void 0:r.mimeType)??((i=(o=(s=e.messageParams)==null?void 0:s.fileInfoList)==null?void 0:o[0])==null?void 0:i.mimeType);return t&&Ye(t)?"file_image":t&&zt(t)?"file_video":t&&Tc(t)?"file_audio":"file_document"};let Ps=0;const pd=e=>(Ps+=1,`${e??"unknown"}:${Ps}`),yt=(e,t)=>e===void 0||t===e,yi=(e,t)=>{!t.error&&t.messages.length>0&&e.conversationNotInteractiveTimeout.markHistoryLoaded("success",t.channelUrl)},Si=(e,t)=>{t.error?e.conversationNotInteractiveTimeout.markHistoryLoaded("failed",t.channelUrl):e.conversationNotInteractiveTimeout.markHistoryLoaded(t.messages.length>0?"success":"verified_empty",t.channelUrl)},_d=(e,t)=>{e.conversationInitialRender.onCacheResult(t.error),yi(e,t)},Ed=(e,t)=>{e.conversationInitialRender.onApiResult(t.error),Si(e,t)},Cd=(e,t,n)=>{var o;if(!st(e,n))return;const{hasResponseMetadata:r,...s}=jo(e.data);r&&(t.typingIndicatorAbsentTimeout.markAIResponseStarted({channelUrl:e.channelUrl,userMessageId:s.userMessageId}),t.userPerceivedResponseTime.markAIResponseRaw({messageId:e.messageId,channelUrl:e.channelUrl,aiResponse:s}),t.streamStalled.markRawProgress({messageId:e.messageId,channelUrl:e.channelUrl,textLength:((o=e.message)==null?void 0:o.length)??0,aiResponse:s}))},Us=(e,t)=>{t.streamStalled.clearMessage(e.messageId),t.userPerceivedResponseTime.clearMessage(e.messageId);const n=Qe(e)?e.reqId:void 0;n&&(t.messagePendingStuck.disappear({requestId:n}),t.userPerceivedResponseTime.cancelTurn(n),t.typingIndicatorAbsentTimeout.cancelTurn(n))},Xn=(e,t)=>{t&&(e.conversationInitialRender.clear(),e.conversationNotInteractiveTimeout.clearChannel(t),e.recoveryNotInteractiveTimeout.clearChannel(t),e.messagePendingStuck.clearChannel(t),e.userPerceivedResponseTime.clearChannel(t),e.typingIndicatorAbsentTimeout.clearChannel(t),e.streamStalled.clearChannel(t))},bd=({activeChannelUrl:e,statsTrackers:t})=>{const{chatSDK:n}=ke(),{aiAgentInfo:r}=ft(),s=l.useRef(!1),o=r==null?void 0:r.userId;ht(!!e&&!!o?n:void 0,{onTypingStatusUpdated(c){if(c.url!==e)return;const u=c.getTypingUsers().some(m=>m.userId===o),d=s.current;u&&!d?t.typingIndicatorAbsentTimeout.markTypingStarted(c.url):!u&&d&&t.typingIndicatorAbsentTimeout.markTypingEnded(c.url),s.current=u}}),l.useEffect(()=>{s.current=!1},[e,o])},vd=({enabled:e=!0,requestedChannelUrl:t,statsTrackers:n})=>{const r=l.useRef(void 0),s=l.useRef(e);l.useLayoutEffect(()=>{const o=r.current,i=s.current;if(s.current=e,!e){o&&(Xn(n,o),r.current=void 0);return}o&&o!==t&&(Xn(n,o),r.current=void 0),t&&o!==t&&(i||n.conversationInitialRender.start(),n.conversationInitialRender.setChannelUrl(t),n.conversationNotInteractiveTimeout.start({channelUrl:t}),r.current=t)},[e,t,n]),l.useLayoutEffect(()=>()=>{const o=r.current;o&&(Xn(n,o),r.current=void 0)},[n])},yd=({aiAgentUserId:e,conversationStatsEnabled:t=!0,requestedChannelUrl:n,statsTrackers:r})=>{const s=l.useRef(null),o=l.useRef(null),i=l.useRef(!1),c=l.useRef(0),u=l.useRef(0),d=l.useRef(t),m=l.useMemo(()=>c.current+1,[n]);l.useLayoutEffect(()=>(i.current=!0,c.current=m,()=>{i.current=!1,c.current+=1}),[m]);const h=l.useCallback(g=>i.current&&c.current===g,[]);l.useLayoutEffect(()=>{u.current+=1,s.current=null,o.current=null},[n]),l.useLayoutEffect(()=>{const g=d.current;d.current=t,!(g||!t)&&(s.current&&(s.current.tracked=!1),o.current&&(o.current.tracked=!1))},[t]);const f=l.useCallback(g=>g.lifecycleGeneration===u.current&&yt(n,g.channelUrl),[n]);return l.useEffect(()=>{if(!t)return;const g=s.current;g&&f(g)&&(g.tracked||(r.conversationInitialRender.onCacheResult(g.error),g.tracked=!0),yi(r,g));const C=o.current;C&&f(C)&&(C.tracked||(r.conversationInitialRender.onApiResult(C.error),C.tracked=!0),Si(r,C))},[t,f,r]),l.useMemo(()=>({onCollectionEvent:g=>{if(h(m)&&yt(n,g.channelUrl)){if(g.kind==="messagesDeleted"){g.messages.forEach(C=>Us(C,r));return}t&&g.messages.forEach(C=>Cd(C,r,e))}},onCacheResult:(g,C,v)=>{if(!h(m)||!yt(n,v))return;const _={error:g,messages:C,channelUrl:v,lifecycleGeneration:u.current,tracked:!1};s.current=_,t&&(_d(r,_),_.tracked=!0)},onApiResult:(g,C,v)=>{if(!h(m)||!yt(n,v))return;const _={error:g,messages:C,channelUrl:v,lifecycleGeneration:u.current,tracked:!1};o.current=_,t&&(Ed(r,_),_.tracked=!0)},onLocalMessageDeleted:g=>{h(m)&&yt(n,g.channelUrl)&&Us(g,r)}}),[e,m,t,h,n,r])},Sd=({enabled:e=!0,channelUrl:t,initialized:n,inputReady:r,renderedSignal:s,statsTrackers:o})=>{const i=l.useRef(!1),c=l.useRef(0);l.useEffect(()=>{c.current+=1,i.current=!1},[t,e]),l.useEffect(()=>{e&&(o.recoveryNotInteractiveTimeout.setInputEnabled(r,t),r&&o.conversationNotInteractiveTimeout.markInputEnabled(t))},[t,e,r,o]),l.useEffect(()=>{if(!e||!n||i.current)return;const u=c.current,d=setTimeout(()=>{c.current===u&&(o.conversationInitialRender.markRendered(t)&&(i.current=!0),o.conversationNotInteractiveTimeout.markRendered(t))});return()=>clearTimeout(d)},[t,e,n,s,o])},Ad=({channelUrl:e,enabled:t=!0,statsTrackers:n})=>{const r=l.useRef(!1),s=l.useRef(e),o=l.useRef(t),i=l.useRef(0);return l.useLayoutEffect(()=>(r.current=!0,s.current=e,o.current=t,i.current+=1,()=>{r.current=!1,i.current+=1}),[e,t]),l.useCallback(async(c,u,d={})=>{if(!r.current||!o.current)return c(v=>u==null?void 0:u(v),()=>{});let m;const h=i.current,f=s.current,g=()=>r.current&&o.current&&i.current===h&&s.current===f,C=v=>g()&&yt(f,v);try{const v=await c(_=>{if(!C(_.channelUrl)){u==null||u(_);return}m=_.reqId,n.messagePendingStuck.start({requestId:_.reqId,channelUrl:_.channelUrl,messageType:gd(_),tracksUploadProgress:d.tracksUploadProgress??!1}),u==null||u(_)},_=>{!g()||m!==_||n.messagePendingStuck.markUploadProgress(_)});return m&&(g()?n.messagePendingStuck.resolve({requestId:m}):n.messagePendingStuck.disappear({requestId:m})),v}catch(v){throw m&&(g()?n.messagePendingStuck.resolve({requestId:m}):n.messagePendingStuck.disappear({requestId:m})),v}},[n])},Td=({channelUrl:e,enabled:t=!0,statsTrackers:n})=>{const r=l.useRef(!1),s=l.useRef(e),o=l.useRef(t),i=l.useRef(0);return l.useLayoutEffect(()=>(r.current=!0,s.current=e,o.current=t,i.current+=1,()=>{r.current=!1,i.current+=1}),[e,t]),l.useCallback(async c=>{if(!r.current||!o.current)return c(()=>{});const u=i.current,d=s.current,m=()=>r.current&&o.current&&i.current===u&&s.current===d;let h=pd(d);n.userPerceivedResponseTime.startTurn({requestId:h,channelUrl:d}),n.typingIndicatorAbsentTimeout.startTurn({requestId:h,channelUrl:d});try{const f=await c(g=>{m()&&(n.userPerceivedResponseTime.replaceTurnRequestId(h,g),n.typingIndicatorAbsentTimeout.replaceTurnRequestId(h,g),h=g)});return m()?(n.userPerceivedResponseTime.markUserMessageAck({requestId:h,messageId:f.messageId}),n.typingIndicatorAbsentTimeout.markUserMessageAck({requestId:h,messageId:f.messageId})):(n.userPerceivedResponseTime.cancelTurn(h),n.typingIndicatorAbsentTimeout.cancelTurn(h)),f}catch(f){throw n.userPerceivedResponseTime.cancelTurn(h),n.typingIndicatorAbsentTimeout.cancelTurn(h),f}},[e,n])},Id=({requestedChannelUrl:e,activeChannelUrl:t,conversationStatsEnabled:n=!0,statsTrackers:r})=>{const{aiAgentInfo:s}=ft();bd({activeChannelUrl:t,statsTrackers:r}),vd({enabled:n,requestedChannelUrl:e,statsTrackers:r});const o=yd({aiAgentUserId:s==null?void 0:s.userId,conversationStatsEnabled:n,requestedChannelUrl:e,statsTrackers:r}),i=Ad({channelUrl:t,enabled:n,statsTrackers:r}),c=Td({channelUrl:t,enabled:n,statsTrackers:r});return l.useMemo(()=>({messageCallbacks:o,runWithPendingStuckStats:i,runWithUserTurnStats:c}),[o,i,c])},jt=()=>ke()._aiAgentSDK.statsTrackers,Xt=(e,t)=>{const n=l.useId(),r=l.useRef(t);l.useLayoutEffect(()=>{r.current=t}),l.useLayoutEffect(()=>{const s=new ue.ConnectionHandler({onDisconnected:o=>{var i,c;return(c=(i=r.current).onDisconnected)==null?void 0:c.call(i,o)},onConnected:o=>{var i,c;return(c=(i=r.current).onConnected)==null?void 0:c.call(i,o)},onReconnectStarted:()=>{var o,i;return(i=(o=r.current).onReconnectStarted)==null?void 0:i.call(o)},onReconnectSucceeded:()=>{var o,i;return(i=(o=r.current).onReconnectSucceeded)==null?void 0:i.call(o)},onReconnectFailed:()=>{var o,i;return(i=(o=r.current).onReconnectFailed)==null?void 0:i.call(o)},onConnectionLost:()=>{var o,i;return(i=(o=r.current).onConnectionLost)==null?void 0:i.call(o)},onConnectionDelayed:o=>{var i,c;return(c=(i=r.current).onConnectionDelayed)==null?void 0:c.call(i,o)}});return e.addConnectionHandler(n,s),()=>{e.removeConnectionHandler(n)}},[e,n])},Bs=()=>{const e=l.useRef(0);return{next:()=>(e.current+=1,e.current),current:()=>e.current,invalidate:()=>{e.current+=1},isCurrent:t=>t===e.current}};function xd(e,t={}){const{chatSDK:n,logger:r,aiAgentId:s,_aiAgentSDK:o}=ke(),{sdkUser:i}=ft(),c=Bs(),u=Bs(),d=Nn(),[m,h]=l.useState(void 0),[f,g]=l.useState(void 0),[C,v]=l.useState(!1);function _(S){if(S.isAIAgent&&!S.conversation){const A=u.next();v(!0),o.initConversationIfNeeded(S).finally(()=>{u.isCurrent(A)&&v(!1)})}}async function p(){var A,T,M,L,D,x;const S=c.next();if(!i){r.debug("useChannel.getChannel: no sdk user, skip fetching channel");return}if(r.debug("useChannel.getChannel: start"),h(void 0),g(void 0),u.invalidate(),v(!1),e){(A=t.onFetchStart)==null||A.call(t,e);try{r.debug("useChannel.getChannel: get channel",e);const O=await n.groupChannel.getChannel(e);if(!c.isCurrent(S))return;_(O),h(O),(M=t.onFetchSuccess)==null||M.call(t,{channelUrl:O.url,conversationId:(T=O.conversation)==null?void 0:T.id}),O.url===((L=o.session)==null?void 0:L.activeChannel.url)&&o.session._updateActiveChannel({url:O.url,status:He(O)?"closed":"open",conversationStatus:(D=O.conversation)==null?void 0:D.status}),r.debug("useChannel.getChannel: fetched channel",O)}catch(O){if(!c.isCurrent(S))return;(x=t.onFetchError)==null||x.call(t,{channelUrl:e,error:O}),O instanceof ue.SendbirdError&&g(O),r.error("useChannel.getChannel: error",O)}}}return l.useEffect(()=>(p(),()=>{c.invalidate()}),[n,i,e,s]),Xt(n,{async onReconnectSucceeded(){var T;if(!m){f&&await p();return}const S=c.current(),A=await m.refresh();!c.isCurrent(S)||m.url!==e||((T=t.onReconnectSucceeded)==null||T.call(t,m.url),_(A),h(A))}}),ht(n,{onChannelChanged:S=>{S.isGroupChannel()&&S.url===e&&(r.debug("useChannel.onChannelChanged: channel changed",S.url),h(S),d())}}),{channel:m,channelFetchError:f,getChannel:p,isInitializingConversation:C}}const Rd=new Set(["suggested_replies","steward","system"]),Md=e=>{const t=e==null?void 0:e.lastMessage,n=t==null?void 0:t.extendedMessagePayload,r=n==null?void 0:n.user_input_disabled_by;if(!(!r||!Rd.has(r)))return r},wd=e=>{var o;const t=e==null?void 0:e.lastMessage;if(!t||!e)return!1;const n=t.extendedMessagePayload,r=kn(n).hasActiveForm,s=e.isAIAgent&&!!((o=e.conversation)!=null&&o.handedOverAt);return r&&!s},kd=()=>{const{chatSDK:e,networkStateAdapter:t}=ke(),[n,r]=l.useState(()=>t?t.isOnline()?"connected":"reconnecting":"connected");return Xt(e,{onConnected:()=>r("connected"),onDisconnected:()=>r("disconnected"),onReconnectStarted:()=>r("reconnecting"),onReconnectSucceeded:()=>r("connected"),onReconnectFailed:()=>r("disconnected"),onConnectionLost:()=>r("reconnecting")}),l.useEffect(()=>{if(t)return t.subscribe(s=>{if(!s){r("reconnecting");return}r(o=>o==="reconnecting"&&e.connectionState===ue.ConnectionState.OPEN?"connected":o)})},[t,e]),n},Ld=3e4,Od=({shouldApply:e,lastMessage:t,isBlockedWhileAIResponding:n,currentUserId:r})=>{const[s,o]=l.useState(!1),i=l.useRef(null),c=t&&st(t,r)?t.createdAt:0;return l.useEffect(()=>{const u=()=>{i.current&&(clearTimeout(i.current),i.current=null),o(!1)},d=f=>{i.current&&clearTimeout(i.current),o(!0),i.current=setTimeout(()=>{o(!1),i.current=null},f)},m=Date.now()-c,h=Ld-m;return n||h<=0?u():d(h),()=>{i.current&&clearTimeout(i.current)}},[n,c]),s&&e},Ai=e=>{const{chatSDK:t}=ke(),[n,r]=l.useState([]);return ht(t,{onTypingStatusUpdated(s){if(s.url===(e==null?void 0:e.url)){const o=s.getTypingUsers();r(o)}}}),n},Nd=({channel:e,lastMessage:t,aiAgentUserId:n,isStreamAnimating:r})=>{const[s,o]=l.useState(!1),i=Ai(e);return l.useEffect(()=>{if(!t)return;const c=i.some(d=>d.userId===n),u=st(t,n)&&(Me.isStreaming(t)||r);o(u||c)},[i,t,n,r]),s},Dd=({channel:e,messages:t,isStreamAnimating:n,isInitializingConversation:r})=>{const{aiAgentInfo:s,userSession:o}=ft(),i=kd(),c=Nd({channel:e,lastMessage:fs(t,[Fe.SendingStatus.SUCCEEDED]),aiAgentUserId:(s==null?void 0:s.userId)??"",isStreamAnimating:n}),u=Od({shouldApply:!!(e!=null&&e.isAIAgent)&&!rt(e),isBlockedWhileAIResponding:c,lastMessage:fs(t,[Fe.SendingStatus.PENDING,Fe.SendingStatus.SUCCEEDED]),currentUserId:(o==null?void 0:o.userId)??""}),d=h=>h===""?{disabled:!1,disabledBy:"",focusPolicy:"auto"}:h==="ai_responding"?{disabled:!0,disabledBy:h,focusPolicy:"preserve"}:{disabled:!0,disabledBy:h,focusPolicy:"release"};if(!e||i==="disconnected")return d("unavailable");if(i==="reconnecting")return d("reconnecting");if(He(e))return d("conversation_closed");if(el(e))return d("handoff_pending");if(wd(e))return d("form_active");const m=Md(e);return d(m||(c||u||r?"ai_responding":""))},$d=()=>{const[e,t]=l.useState(new Set),n=l.useCallback(s=>{t(o=>{if(o.has(s))return o;const i=new Set(o);return i.add(s),i})},[]),r=l.useCallback(s=>{t(o=>{if(!o.has(s))return o;const i=new Set(o);return i.delete(s),i})},[]);return{isAnimating:e.size>0,start:n,stop:r}},{Provider:Fd}=be("AIAgentConversation"),Pd=({initialRenderStats:e,notInteractiveStats:t,recoveryStats:n})=>({onFetchStart:r=>{e.onFetchStart(r),t.onFetchStart(r)},onFetchSuccess:r=>{e.onFetchSuccess(r),t.onFetchSuccess(r)},onFetchError:r=>{e.onFetchError(r),t.onFetchError(r)},onReconnectSucceeded:n.onReconnectSucceeded});function Ud({children:e,channelUrl:t,onChannelDeleted:n,onMessagesReceived:r,onMessagesUpdated:s,onConversationStatusChanged:o,onConversationClosedViaDispatcher:i,onBeforeSendMessage:c,onAfterSendMessage:u=le,shouldMarkAsRead:d=!0,conversationStatsEnabled:m=!0,shouldCountNewMessages:h=()=>!1,sortComparator:f}){var Le,$;const g=()=>d&&(x==null?void 0:x.markAsRead()),{_aiAgentSDK:C,chatSDK:v,logger:_,dispatcher:p}=ke(),S=jt(),A={channelUrl:t,enabled:m},T=qu({...A,statsTracker:S.conversationInitialRender}),M=Ku({...A,statsTracker:S.conversationNotInteractiveTimeout}),L=Yu({...A,scheduleForegroundTask:C.scheduleForegroundTask,statsTracker:S.recoveryNotInteractiveTimeout}),D=Pd({initialRenderStats:T,notInteractiveStats:M,recoveryStats:L}),{channel:x,channelFetchError:O,getChannel:H,isInitializingConversation:F}=xd(t,D),W=x==null?void 0:x.url,q=Id({requestedChannelUrl:t,activeChannelUrl:W,conversationStatsEnabled:m,statsTrackers:S}),k=Vu(v,x,{replyType:Fe.ReplyType.ONLY_REPLY_TO_CHANNEL,shouldCountNewMessages:h,onChannelDeleted:n,onMessagesReceived:I=>r==null?void 0:r(I),onMessagesUpdated:I=>s==null?void 0:s(I),...q.messageCallbacks,onOutgoingMessageStatusChanged:I=>{x&&C.liveMetricManager.track({type:"outgoingMessage",channel:x,message:I})},logger:_,markAsRead:g,sortComparator:f}),G=$d(),P=Dd({channel:x,messages:k.messages,isStreamAnimating:G.isAnimating,isInitializingConversation:F});Sd({enabled:m,channelUrl:W,initialized:k.initialized,inputReady:fd(P),renderedSignal:k.messages,statsTrackers:S}),l.useEffect(()=>{g()},[d,x]);const V=(Le=x==null?void 0:x.conversation)==null?void 0:Le.status;l.useEffect(()=>{V&&(o==null||o(V))},[V,o]),l.useEffect(()=>{const I=async w=>{const N=typeof(w==null?void 0:w.channelUrl)=="string";x&&N&&w.channelUrl!==x.url||(_.debug("conversation.dispatcher: try to close conversation",x),x!=null&&x.conversation&&x.conversation.status===de.ConversationStatus.OPEN&&(await x.closeConversation(),i==null||i()))};return p.subscribe(Ke.ConversationClose,I),()=>{p.unsubscribe(Ke.ConversationClose,I)}},[p,x,_,($=x==null?void 0:x.conversation)==null?void 0:$.status,i]);const me=ie(()=>k.loadPrevious()),Ie=ie(()=>k.loadNext()),j=ie(async I=>{try{await k.deleteMessage(I)}finally{I.sendingStatus!=="succeeded"&&q.messageCallbacks.onLocalMessageDeleted(I)}}),K=ie(I=>I.isUserMessage()?q.runWithUserTurnStats(w=>q.runWithPendingStuckStats(N=>k.resendMessage(I,z=>{w(z.reqId),N(z)}),void 0)):q.runWithPendingStuckStats((w,N)=>k.resendMessage(I,w,N),void 0,{tracksUploadProgress:I.isMultipleFilesMessage()})),R=ie(()=>k.resetNewMessages()),X=ie(async I=>{var N;if(((N=x==null?void 0:x.conversation)==null?void 0:N.status)===de.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(I=await c(I));const w=await q.runWithUserTurnStats(z=>q.runWithPendingStuckStats(Y=>k.sendUserMessage(I,te=>{z(te.reqId),Y(te)}),u));return u==null||u(w),w}),ne=ie(async I=>{var N;if(((N=x==null?void 0:x.conversation)==null?void 0:N.status)===de.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(I=await c(I));const w=await q.runWithPendingStuckStats(z=>k.sendFileMessage(I,z),u);return u==null||u(w),w}),oe=ie(async I=>{var N;if(((N=x==null?void 0:x.conversation)==null?void 0:N.status)===de.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(I=await c(I));const w=await q.runWithPendingStuckStats((z,Y)=>k.sendMultipleFilesMessage(I,z,Y),u,{tracksUploadProgress:!0});return u==null||u(w),w}),Re={conversation:(x==null?void 0:x.conversation)??void 0,actions:{setUserMemoryState:C.setUserMemoryState},channelSource:{channel:x,error:O,refetch:()=>H(),closeConversation:async()=>{He(x)||await(x==null?void 0:x.closeConversation())}},messageSource:{messages:k.messages,newMessages:k.newMessages,initialized:k.initialized,subscribeMessageEvents:k.subscribeMessageEvents,loadPrevious:me,loadNext:Ie,deleteMessage:j,resendMessage:K,resetNewMessages:R,sendUserMessage:X,sendFileMessage:ne,sendMultipleFilesMessage:oe},state:{streamAnimation:G,input:P}};return a.createElement(Fd,{value:Re},e)}function Bd(e,t,n){var p,S,A,T,M,L,D,x,O,H;const[r,s]=l.useState(!1),[o,i]=l.useState(null),[c,u]=l.useState([]),[d,m]=l.useState(null),h=l.useRef(!1),f=ie(()=>{var F;return(F=n==null?void 0:n.onListRequestStart)==null?void 0:F.call(n)}),g=ie(()=>{var F;return(F=n==null?void 0:n.onListRequestComplete)==null?void 0:F.call(n)}),C=l.useCallback(async F=>{f(),await F.loadMore(),g()},[f,g]),v=l.useCallback(async()=>{if(!h.current&&e.currentUser){h.current=!0,s(!1),i(null),u([]);try{d==null||d.dispose();const F=new ni(e,t);F.setConversationListCollectionHandler({onChannelsAdded:()=>{u(F.channels)},onChannelsUpdated:()=>{u(F.channels)},onChannelsDeleted:()=>{u(F.channels)}}),await C(F),u(F.channels),m(F),i(null)}catch(F){m(null),i(F)}finally{s(!0),h.current=!1}}},[e,e.currentUser,(p=t.filter)==null?void 0:p.aiAgentChannelFilter,(A=(S=t.filter)==null?void 0:S.aiAgentConversationStatusFilter)==null?void 0:A.join(),(M=(T=t.filter)==null?void 0:T.aiAgentIds)==null?void 0:M.join(),(L=t.filter)==null?void 0:L.deskChannelFilter,(x=(D=t.filter)==null?void 0:D.pinnedChannelUrls)==null?void 0:x.join(),(O=t.filter)==null?void 0:O.copilotConversationOnly,(H=t.filter)==null?void 0:H.copilotSupportChannelUrl,t.limit,C]),_=l.useCallback(async()=>{if(d)try{await d.loadMore(),u(d.channels)}catch(F){i(F)}},[d]);return Xt(e,{onConnected:()=>v()}),l.useEffect(()=>{v()},[v]),l.useEffect(()=>()=>{h.current=!1,d==null||d.dispose()},[d]),{initialized:r,error:o,channels:c,loadMore:_}}const Ti=e=>{var s;const{aiAgentId:t,queryParams:n}=ke(),r=(s=n==null?void 0:n.conversationListParams)==null?void 0:s.filter;return{aiAgentIds:[t],aiAgentConversationStatusFilter:[de.ConversationStatus.CLOSED,de.ConversationStatus.OPEN],...r,...e}},Hd=({enabled:e=!0}={})=>{const n=jt().conversationListInitialRender,r=l.useRef(e),s=l.useRef(!1),o=l.useRef(!1),i=l.useRef(!1);r.current=e,l.useEffect(()=>{if(!e){o.current&&(s.current=!0);return}if(o.current&&!s.current)return;const m=s.current&&i.current;n.onInitializeStart(),o.current=!0,s.current=!1,m&&n.onListRequestStart()},[e,n]),l.useEffect(()=>()=>{n.clear(),o.current=!1,s.current=!1,i.current=!1},[n]);const c=l.useCallback(()=>r.current&&o.current&&!s.current,[]),u=l.useMemo(()=>({onListRequestStart:()=>{i.current=!0,c()&&n.onListRequestStart()},onListRequestComplete:()=>{i.current=!1,c()&&n.onListRequestComplete()}}),[c,n]),d=l.useCallback(()=>{c()&&n.onRendered()},[c,n]);return l.useMemo(()=>({collectionCallbacks:u,onRendered:d}),[u,d])},{Provider:Gd}=be("AIAgentConversationList");function zd({conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:n=!0,children:r}){var h;const{chatSDK:s,queryParams:o}=ke(),i=Hd({enabled:n}),c=e??((h=o==null?void 0:o.conversationListParams)==null?void 0:h.limit),u=Ti(t),d=Bd(s,{limit:c,filter:u},i.collectionCallbacks);l.useEffect(()=>{n&&d.initialized&&(d.error||i.onRendered())},[n,d.error,d.initialized,i]);const m={listSource:{initialized:d.initialized,error:d.error??void 0,channels:d.channels,loadMore:()=>d.loadMore()}};return a.createElement(Gd,{value:m},r)}function Vd(e){let t="pending",n=e.then(r=>{t="resolved",n=r}).catch(r=>{t="rejected",n=r});return{get value(){if(t==="resolved")return n;throw n}}}const{Provider:qd,useContext:Kd}=be("MessageTemplateFetching");function Yd({children:e,internalVariables:t}){const n=l.useRef({}),r=l.useRef({}),[s,o]=l.useState({}),i=l.useCallback((d,m)=>{o(h=>({...h,[d]:{fetching:!1,error:!1,...h[d],...m}}))},[]),c=l.useCallback(async({onRequestTemplate:d,onGetCachedTemplate:m,templateKey:h,suspense:f=!1})=>{const g=m(h);if(g)return g;const C=r.current[h];if(C)return C;f||i(h,{fetching:!0});const v=d(h).catch(_=>{throw f||i(h,{error:!0}),_}).finally(()=>{f||i(h,{fetching:!1}),delete r.current[h]});return r.current[h]=v,v},[i]),u={internalVariables:t,fetchTemplate:c,suspend:(d,m)=>{if(n.current[d])return n.current[d];const h=Vd(m());return n.current[d]=h,h},getIsFetching:d=>{var m;return((m=s[d])==null?void 0:m.fetching)??!1},getHasError:d=>{var m;return((m=s[d])==null?void 0:m.error)??!1}};return a.createElement(qd,{value:u},e)}const Wd="remove_powered_by",Ur=(e,t)=>{var s,o;const{chatSDK:n}=ke(),{aiAgentInfo:r}=ft();if(e==="handoff-button"){const i=!!((s=t==null?void 0:t.conversation)!=null&&s.handoff);return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.showHandoffButton)&&i&&Rr(t)}if(e==="special-notice")return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.specialNoticeEnabled)&&!!(r!=null&&r.specialNotice);if(e==="powered-by"){const i=(o=n==null?void 0:n.appInfo)==null?void 0:o.applicationAttributes;return l.useMemo(()=>!(Array.isArray(i)&&i.includes(Wd)),[i])}throw new Error("Unsupported feature")},jd={required:"This question is required",minLength:e=>`Minimum ${e} characters required`,maxLength:e=>`Maximum ${e} characters allowed`,min:e=>`Minimum value is ${e}`,max:e=>`Maximum value is ${e}`,minSelect:e=>`Select at least ${e} options`,maxSelect:e=>`Select at most ${e} options`,regex:"Invalid format",invalidSelection:"Invalid selection"},Xd={getValueOrDefault:e=>e.value??e.default_value??null,validate:(e,t,n)=>{const r=t;if(e.required&&(!r||r.trim()===""))return{isValid:!1,error:n.required};if(!r)return{isValid:!0};const{rules:s}=e;if(s){if(s.min_length!==void 0&&r.length<s.min_length)return{isValid:!1,error:typeof n.minLength=="function"?n.minLength(s.min_length):n.minLength};if(s.max_length!==void 0&&r.length>s.max_length)return{isValid:!1,error:typeof n.maxLength=="function"?n.maxLength(s.max_length):n.maxLength};if(s.regex&&!new RegExp(s.regex).test(r))return{isValid:!1,error:n.regex}}return{isValid:!0}}},Zd={getValueOrDefault:e=>e.value??e.default_value??null,validate:(e,t,n)=>{const r=t;if(e.required&&r===null)return{isValid:!1,error:n.required};if(r===null)return{isValid:!0};const{rules:s}=e;if(s){if(s.min!==void 0&&r<s.min)return{isValid:!1,error:typeof n.min=="function"?n.min(s.min):n.min};if(s.max!==void 0&&r>s.max)return{isValid:!1,error:typeof n.max=="function"?n.max(s.max):n.max}}return{isValid:!0}}},Jd={getValueOrDefault:e=>e.value??e.default_value??null,validate:(e,t,n)=>{const r=t;return e.required&&!r?{isValid:!1,error:n.required}:r&&!e.options.includes(r)?{isValid:!1,error:n.invalidSelection}:{isValid:!0}}},Qd={getValueOrDefault:e=>e.values??e.default_values??null,validate:(e,t,n)=>{const r=t;if(e.required&&(!r||r.length===0))return{isValid:!1,error:n.required};if(!r||r.length===0)return{isValid:!0};if(r.filter(i=>!e.options.includes(i)).length>0)return{isValid:!1,error:n.invalidSelection};const{rules:o}=e;if(o){if(o.min_select!==void 0&&r.length<o.min_select)return{isValid:!1,error:typeof n.minSelect=="function"?n.minSelect(o.min_select):n.minSelect};if(o.max_select!==void 0&&r.length>o.max_select)return{isValid:!1,error:typeof n.maxSelect=="function"?n.maxSelect(o.max_select):n.maxSelect}}return{isValid:!0}}},em={text:Xd,number:Zd,"single-select":Jd,"multi-select":Qd},tm={getValueOrDefault:()=>null,validate:()=>({isValid:!1})};function Ii(e){return em[e.type]||tm}function Hs(e){return Ii(e).getValueOrDefault(e)}function nm(e,t,n={}){const r={...jd,...n};return Ii(e).validate(e,t,r)}const rm=(e,t={})=>{const{labels:n={},onSubmit:r,onCancel:s}=t,[o,i]=l.useState({}),[c,u]=l.useState(()=>{const v={};return e.fields.forEach(_=>{v[_.key]=Hs(_)}),v}),d=l.useMemo(()=>e.submitted_at?"submitted":e.canceled_at?"canceled":"draft",[e.submitted_at,e.canceled_at]);l.useEffect(()=>{if(d==="submitted"||d==="canceled"){const v={};let _=!1;e.fields.forEach(p=>{const S=Hs(p);JSON.stringify(c[p.key])!==JSON.stringify(S)&&(_=!0),v[p.key]=S}),_&&u(v)}},[d]);const m=(v,_)=>{u(p=>({...p,[v]:_})),i(p=>({...p,[v]:void 0}))},h=e.fields.map(v=>{var S,A,T;const _=c[v.key]??null,p={key:v.key,label:v.label,error:o[v.key],required:v.required};return v.type==="text"?{...p,type:"text",layout:v.layout,value:_,...v.placeholder&&{placeholder:v.placeholder},...((S=v.rules)==null?void 0:S.max_length)&&{maxLength:v.rules.max_length}}:v.type==="number"?{...p,type:"number",layout:v.layout,value:_,...v.placeholder&&{placeholder:v.placeholder},...((A=v.rules)==null?void 0:A.max)&&{max:v.rules.max}}:v.type==="single-select"?{...p,type:"single-select",layout:v.layout,value:_,options:v.options}:v.type==="multi-select"?{...p,type:"multi-select",layout:v.layout,value:_,options:v.options,...((T=v.rules)==null?void 0:T.max_select)&&{maxSelect:v.rules.max_select}}:{...p,type:"unknown",layout:"default",value:null}});return{state:d,fields:h,getField:v=>h.find(_=>_.key===v),updateFieldValue:m,submit:async()=>{const v={};let _=!1;for(const p of e.fields){const S=c[p.key]??null,A=nm(p,S,n);A.isValid||(v[p.key]=A.error,_=!0)}if(i(v),!_&&r){const p={};e.fields.forEach(S=>{p[S.key]=c[S.key]??null}),await r(p)}},cancel:async()=>{await(s==null?void 0:s())}}},sm=e=>{const{chatSDK:t,handlers:n,logger:r}=ke(),{aiAgentInfo:s}=ft(),o=l.useRef(new Set),i=l.useRef(new Set),c=(m,h)=>{if(!(n!=null&&n.onCustomEvent)||!(s!=null&&s.userId)||!st(m,s.userId))return;const f=m.messageId;if(Me.isStreaming(m)){i.current.add(f);return}h==="updated"&&!i.current.has(f)||(r.debug("useCustomEventForMessageReceive: bot-message-received",m),n.onCustomEvent({type:"bot-message-received",data:{message:m}}),i.current.delete(f))},u=l.useCallback(m=>{if(n!=null&&n.onCustomEvent&&m.isAdminMessage()&&m.customType==="user_action_required"&&!o.current.has(m.messageId)){const h=Yo(m.data);Array.isArray(h.history)&&h.history.length===0&&(r.debug("useCustomEventForMessageReceive: user_action_required",h),n.onCustomEvent({type:"user-action-requested",data:h}),o.current.add(m.messageId))}},[n,r]),d=(m,h,f)=>{m.url===e&&(c(h,f),u(h))};return ht(t,{onMessageReceived:(m,h)=>d(m,h,"received"),onMessageUpdated:(m,h)=>d(m,h,"updated")}),{checkForUserActionRequired:u}},om=e=>{if(e==null||typeof e!="object")return;const t="thinking_message"in e?e.thinking_message:void 0;return typeof t=="string"&&t?t:void 0},xi=e=>{const{aiAgentInfo:t}=ft(),n=Ai(e);if(He(e))return null;const r=n[0];if(!r)return null;const s=r.userId===(t==null?void 0:t.userId),o=s?om(r.metaData):void 0;return{user:s?t:r,isBot:s,thinkingMessage:o}},im=(e,t,{enabled:n=!0,idleMs:r=1e3}={})=>{const s=l.useRef(null),o=l.useRef(t),i=l.useRef(t),c=l.useRef(!1);o.current=t,l.useEffect(()=>{if(s.current&&(clearTimeout(s.current),s.current=null),!n||!e){(c.current?i.current:o.current)(!1),c.current=!1,i.current=o.current;return}c.current=!0,i.current=o.current,i.current(!0),s.current=setTimeout(()=>{s.current=null,i.current(!1),c.current=!1,i.current=o.current},r)},[n,r,e]),l.useEffect(()=>()=>{s.current&&(clearTimeout(s.current),s.current=null),(c.current?i.current:o.current)(!1),c.current=!1,i.current=o.current},[])},am=(e=1e4)=>{const t=new Map;let n=e;return{shouldAnnounce:c=>{const u=Date.now(),d=t.get(c);return d!==void 0&&u-d<n?!1:(t.set(c,u),!0)},setInterval:c=>{n=c},reset:()=>{t.clear()}}},cm=(e,t,n=1e4,r=!0)=>{const s=l.useRef(null),o=l.useRef(null),i=l.useRef(!1);s.current||(s.current=am(n));const c=(e==null?void 0:e.nickname.trim())||null,u=(e==null?void 0:e.userId)??c;l.useEffect(()=>{var d;(d=s.current)==null||d.setInterval(n)},[n]),l.useEffect(()=>{var h;if(!r){i.current=!1,o.current=u;return}if(!u||!c){i.current=!1,o.current=null;return}const d=!i.current,m=o.current!==u;i.current=!0,o.current=u,!(!d&&!m)&&(h=s.current)!=null&&h.shouldAnnounce(u)&&t(c)},[u,c,r,t])},lm=({csat:e,csatPayload:t,isRenderableCSAT:n,isExpiredNow:r,announceStatus:s,onSubmittedAnnounced:o})=>{const i=(t==null?void 0:t.csat_submitted_label)??"",c=l.useRef(n&&typeof e=="number"),u=l.useRef(n&&r);l.useEffect(()=>{n&&i&&(typeof e!="number"||c.current||(c.current=!0,s&&(s({event:"csatSubmitted",submittedLabel:i}),o==null||o())))},[s,e,n,o,i]),l.useEffect(()=>{n&&r&&(u.current||(u.current=!0,s==null||s({event:"csatExpired"})))},[s,r,n])},Br=({channel:e,userSession:t,aiAgentInfo:n})=>{if(!t||!n||!e)return{fallbackIcon:"delight",url:void 0,title:""};const r=si(e,t.userId),s={ai(o){return{fallbackIcon:o,url:n.profileUrl,title:n.nickname}},human(o){return{fallbackIcon:o,url:r==null?void 0:r.profileUrl,title:(r==null?void 0:r.nickname)||n.nickname}},channel(o){return{fallbackIcon:o,url:e==null?void 0:e.coverUrl,title:(e==null?void 0:e.name)??""}}};return e.isAIAgent?rt(e)?s.human("agent"):s.ai("delight"):e.isDesk?s.human("agent"):s.channel("user")},Gs=e=>l.useReducer((t,n)=>({...t,...n}),e);var Je=(e=>(e.AI_AGENT_CSAT_5="AI_AGENT_CSAT_5",e.AI_AGENT_CSAT_5_WITH_CRE="AI_AGENT_CSAT_5_WITH_CRE",e.HELPDESK_CSAT_5="HELPDESK_CSAT_5",e))(Je||{});const um=new Set(["free_text","single_choice"]),dm=({csatPayload:e,type:t,initialCsat:n,initialCsatReason:r,initialIsResolved:s})=>{const[o,i]=Gs({csatType:t,csat:n,csatReason:r,isResolved:s}),[c,u]=Gs({followUpItem:!1}),d=l.useMemo(()=>{var _;const g=o.csat,C=typeof g=="number",v=(_=e.follow_up)==null?void 0:_.find(p=>C?p.scores.includes(g):p.always_visible??!1);if(um.has(v==null?void 0:v.response_type))return v},[o.csat,e.follow_up]),m=(()=>{var g;if(typeof n=="number")return"submitted";if((t===Je.AI_AGENT_CSAT_5||t===Je.HELPDESK_CSAT_5)&&typeof o.csat=="number")return"submittable";if(t===Je.AI_AGENT_CSAT_5_WITH_CRE){const C=typeof o.csat=="number",v=!((g=e.cre)!=null&&g.required)||typeof o.isResolved=="boolean";if(C&&v)return"submittable"}return"unsubmittable"})(),h=l.useCallback(()=>typeof o.csat>"u"?!1:d!=null&&d.required&&!o.csatReason?(u({followUpItem:!0}),!1):!0,[o,d,u]);return l.useEffect(()=>{r||(i({csatReason:""}),u({followUpItem:!1}))},[r,d,i,u]),{params:o,setParams:i,error:c,setError:u,followUpItem:d,state:m,validateParams:h,itemProps:{csatPayload:e,state:m,submitted:m==="submitted"}}},mm=({csat:e,csatExpireAt:t,csatPayload:n,isSubmitInFlight:r=!1})=>{const s=!!n&&n.visibility&&!!Je[n.type],o=!r&&typeof e!="number"&&oi(t),i=Nn();return l.useEffect(()=>{if(!s||typeof e=="number"||t==null||o)return;const c=t-Date.now();if(c<=0&&r)return;const u=setTimeout(i,Math.max(0,c));return()=>clearTimeout(u)},[i,e,t,o,s,r]),{isRenderableCSAT:s,isExpiredNow:o}},Zn=5,Nt=250,hm=50,zs=e=>Math.max(0,e-hm),gn=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():0,fm=e=>e<1e3?{speed:Zn*.5,chunkSize:2}:e<2e3?{speed:Zn*.8,chunkSize:2}:{speed:Zn*.6,chunkSize:3},pn=(e,t)=>{let n=0;for(let r=t-1;r>=0&&e[r]==="\\";r--)n++;return n%2===1},Vs=(e,t,n,r)=>{let s=1,o=t;for(;o<e.length&&s>0;){if(pn(e,o)){o++;continue}e[o]===n?s++:e[o]===r&&s--,o++}return s>0?-1:o},Ri=(e,{hideImages:t,hideLinks:n})=>{let r="",s=0,o=0;for(;s<e.length;){if(e[s]==="`"&&!pn(e,s)){let h=1;for(;e[s+h]==="`";)h++;o===0?o=h:h===o&&(o=0),r+=e.slice(s,s+h),s+=h;continue}const i=e[s]==="!"&&e[s+1]==="["&&!pn(e,s),c=e[s]==="["&&!pn(e,s);if(o>0||!i&&!c){r+=e[s],s++;continue}if(i?!t:!n){const h=i?"![":"[";r+=h,s+=h.length;continue}const u=s,d=Vs(e,s+(i?2:1),"[","]");if(d===-1)return r;if(s=d,e[s]!=="("){r+=e.slice(u,s);continue}const m=Vs(e,s+1,"(",")");if(m===-1)return r;s=m,r+=e.slice(u,s)}return r},gm=({trackedRef:e,onVisibleTextProgress:t,onRenderedTextProgress:n})=>{const r=l.useRef(t),s=l.useRef(n),o=l.useRef(null),i=l.useRef({lastLength:0,lastReportedAt:0}).current,c=l.useRef({lastLength:0,lastReportedAt:0,lastCheckedAt:0}).current,u=l.useRef(null);l.useLayoutEffect(()=>{r.current=t,s.current=n});const d=l.useCallback(S=>{var A;(A=r.current)==null||A.call(r,S)},[]),m=l.useCallback(S=>{const A=e.initialEnabled&&(e.enabled||S<e.textLength),T=A&&e.deferImages,M=A&&e.deferLinks;return!T&&!M?S:Ri(e.text.slice(0,S),{hideImages:T,hideLinks:M}).length},[e]),h=l.useCallback((S,A,T=!1)=>{r.current&&(S<=c.lastLength||!T&&A-c.lastReportedAt<Nt||(c.lastLength=S,c.lastReportedAt=A,d(S)))},[d,c]),f=l.useCallback((S,A,T=!1)=>{if(!r.current)return;const M=Math.max(c.lastReportedAt,c.lastCheckedAt);!T&&A-M<Nt||(c.lastCheckedAt=A,h(m(S),A,!0))},[m,h,c]),g=l.useCallback((S,A,T=!1)=>{s.current&&(S<=i.lastLength||!T&&A-i.lastReportedAt<Nt||(i.lastLength=S,i.lastReportedAt=A,s.current(S)))},[i]),C=l.useCallback((S,A,T)=>{const M=S>=A,L=T-i.lastReportedAt>=Nt;if(!M&&!L)return;const D=m(S);g(D,T,M)},[m,i,g]),v=l.useCallback(()=>{c.lastLength=0,c.lastReportedAt=0,c.lastCheckedAt=0,i.lastLength=0,i.lastReportedAt=0},[i,c]),_=l.useCallback(S=>{r.current&&(o.current!==null&&S<=o.current||(o.current=S,d(S)))},[d]),p=l.useCallback(({displayedLength:S,streamTextLength:A})=>{const T=u.current;if(u.current={displayedLength:S,streamTextLength:A},!e.initialEnabled||!T||S>T.displayedLength||A<=T.streamTextLength)return;const M=gn();h(A,M,!0),g(A,M,!0)},[u,g,h,e]);return{resetProgress:v,reportVisibleTextProgress:f,reportRenderedTextProgress:C,reportNonStreamingVisibleTextProgress:_,reportMarkdownRevealProgress:p}},pm=e=>{const{text:t,enabled:n=!1,snapOnDisable:r=!1,deferredMarkdownElements:s=[],onAnimationStart:o,onAnimationProgress:i,onAnimationComplete:c,onVisibleTextProgress:u,onRenderedTextProgress:d}=e,m=s.includes("image"),h=s.includes("link"),[f,g]=l.useState(()=>zs(t.length)),C=l.useRef(null),v=l.useRef({startTime:0,lastUpdate:0,lastProgressCall:0}).current,_=l.useRef({startCalled:!1,completeCalled:!1}).current,p=l.useRef({initialEnabled:n,textLength:t.length,enabled:n,text:t,deferImages:m,deferLinks:h,snapOnDisable:r}).current,S=ie(()=>o==null?void 0:o()),A=ie(()=>i==null?void 0:i()),T=ie(()=>c==null?void 0:c()),{resetProgress:M,reportVisibleTextProgress:L,reportRenderedTextProgress:D,reportNonStreamingVisibleTextProgress:x,reportMarkdownRevealProgress:O}=gm({trackedRef:p,onVisibleTextProgress:u,onRenderedTextProgress:d}),H=n,F=f<t.length,W=p.initialEnabled&&(H||F);l.useLayoutEffect(()=>{p.textLength=t.length,p.enabled=n,p.text=t,p.deferImages=m,p.deferLinks=h,p.snapOnDisable=r}),l.useLayoutEffect(()=>{if(p.initialEnabled){if(_.startCalled||(_.startCalled=!0,S()),!p.enabled&&p.snapOnDisable){g(t.length);const k=gn();L(t.length,k,!0),D(t.length,t.length,k);return}g(k=>t.length<k?t.length:k)}},[S,D,L,t]),l.useEffect(()=>{if(!p.initialEnabled)return;let k=zs(t.length);v.lastUpdate=0,v.startTime=0,v.lastProgressCall=0,M();const G=P=>{v.lastUpdate===0&&(v.lastUpdate=P,v.startTime=P,v.lastProgressCall=P,k>0&&L(k,P,!0));const V=p.textLength;!p.enabled&&p.snapOnDisable&&k<V&&(k=V,g(k),L(k,P,!0),D(k,V,P));const me=P-v.lastUpdate,Ie=P-v.startTime,{speed:j,chunkSize:K}=fm(Ie),R=j*K;me>=R&&k<V&&(k=Math.min(k+K,V),g(k),L(k,P,k>=V),D(k,V,P),v.lastUpdate=P),P-v.lastProgressCall>=Nt&&(v.lastProgressCall=P,A()),(k<V||p.enabled)&&(C.current=requestAnimationFrame(G))};return C.current=requestAnimationFrame(G),()=>{C.current&&cancelAnimationFrame(C.current),_.startCalled&&!_.completeCalled&&(_.completeCalled=!0,T())}},[T,A,D,L,M]),l.useEffect(()=>{p.initialEnabled&&(n||t.length>0)||(x(t.length),D(t.length,t.length,gn()))},[n,d,u,x,D,t.length,p]),l.useEffect(()=>{const k=p.initialEnabled&&_.startCalled,G=!n,P=f>=t.length;k&&G&&P&&!_.completeCalled&&(_.completeCalled=!0,T())},[n,f,T,t.length]);const q=l.useMemo(()=>{const k=p.initialEnabled?t.slice(0,f):t,G=W&&m,P=W&&h;return!G&&!P?k:Ri(k,{hideImages:G,hideLinks:P})},[t,f,m,h,W]);return l.useEffect(()=>{!p.initialEnabled||W||L(f,gn(),!0)},[f,W,L]),l.useEffect(()=>{O({displayedLength:f,streamTextLength:q.length})},[f,O,q.length]),{streamText:q,isAnimating:W}},qs={visible:!1,remainingTime:0,showDescription:!1,targetTimeMs:null},_m=e=>({visible:!0,remainingTime:e,showDescription:!0,targetTimeMs:Date.now()+e*1e3}),Em=(e,t=Date.now())=>{if(!e.visible||e.targetTimeMs==null)return e;const n=Math.max(Math.ceil((e.targetTimeMs-t)/1e3),0);return n<=0?{...e,remainingTime:0,showDescription:!1,targetTimeMs:null}:e.remainingTime===n&&e.showDescription?e:{...e,remainingTime:n,showDescription:!0}},Cm=()=>{const{chatSDK:e}=ke(),[t,n]=l.useState(qs),r=()=>n(qs);return Xt(e,{onConnectionDelayed:s=>{s>0?n(_m(s)):r()},onReconnectSucceeded:r,onConnected:r}),l.useEffect(()=>{if(!t.visible||!t.showDescription||t.targetTimeMs==null)return;const s=setTimeout(()=>{n(o=>Em(o))},1e3);return()=>clearTimeout(s)},[t.visible,t.showDescription,t.targetTimeMs,t.remainingTime]),{visible:t.visible,remainingTime:t.remainingTime,showDescription:t.showDescription}},bm=e=>{const t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`},vm=(e,t)=>{if(!t)return{beforeText:e,highlightedText:"",afterText:""};const n=e.indexOf(t);return n<0?{beforeText:e,highlightedText:"",afterText:""}:{beforeText:e.slice(0,n),highlightedText:t,afterText:e.slice(n+t.length)}},ym=({enabled:e=!0}={})=>{const t=jt();return l.useCallback(({message:n,isBotMessage:r,aiAgentUserId:s})=>{if(!e)return;const o=n.messageId,i=Me.isStreaming(n),c=kn(n.extendedMessagePayload),u=c.hasMessageTemplate,d=c.hasForm,m=r&&n.isUserMessage()&&!i&&!Ic(n)&&!Me.isWelcomeMessage(n,s),h=i||t.streamStalled.hasPendingStream(o),f=t.userPerceivedResponseTime.hasPendingAIResponse(o);if(!h&&!f&&!m&&!u&&!d)return;let g=!1,C=!1;const v={};return(f||m)&&(v.onVisibleTextProgress=()=>{f&&!g&&(g=t.userPerceivedResponseTime.markAIResponseVisible(o)),m&&!C&&(C=!0,t.renderedContentUnusable.commit({messageId:o,contentKind:"text",errorDomain:"empty_render"}))}),h&&(v.onRenderedTextProgress=_=>{t.streamStalled.markRenderedProgress({messageId:o,displayedLength:_})}),u&&(v.onMessageTemplateError=_=>{t.renderedContentUnusable.commit({messageId:o,contentKind:"template",errorDomain:"template_error",error:_})}),d&&(v.onFormRenderError=_=>{t.renderedContentUnusable.commit({messageId:o,contentKind:"form",errorDomain:"form_error",error:_})}),v},[e,t])},Sm=e=>{const t=l.useRef(!1);l.useEffect(()=>{t.current||e!=null&&e.onVisibleTextProgress&&(t.current=!0,e.onVisibleTextProgress(0))},[e])},Jn=5e3,cn=()=>vn.now(),Am=({channelUrl:e,enabled:t=!0,isInitiallyBackgrounded:n,isForegrounded:r,subscribeToForegroundState:s})=>{const o=jt(),i=l.useRef(t),c=l.useRef(n),u=l.useRef(t&&n()?cn()-Jn:null),d=l.useRef(!1);i.current=t,c.current=n;const m=l.useCallback((h=r())=>{if(!i.current){d.current=!1;return}if(!h){d.current=!1;return}if(u.current===null){d.current=!1;return}if(cn()-u.current<Jn){u.current=null,d.current=!1;return}if(!e){d.current=!0;return}u.current=null,d.current=!1,o.recoveryNotInteractiveTimeout.start("foreground_resume",e)},[e,r,o]);l.useEffect(()=>{t||(u.current=null,d.current=!1,e&&o.recoveryNotInteractiveTimeout.cancelPending(e))},[e,t,o]),l.useEffect(()=>{if(!t)return;d.current&&!!e&&r()&&m()},[e,t,r,m]),l.useEffect(()=>{if(t)return c.current()?u.current??(u.current=cn()-Jn):u.current=null,s(h=>{if(h==="backgrounded"){u.current??(u.current=cn()),d.current=!1,e&&o.recoveryNotInteractiveTimeout.cancelPending(e);return}m(!0)})},[e,t,m,o,s])},Tm=e=>{const{conversationInitialRender:t,conversationListInitialRender:n}=jt();l.useLayoutEffect(()=>{t.setPresentMethod(e),n.setPresentMethod(e)},[t,n,e])},Im=(e,{enabled:t=!0,opened:n=!1,filter:r}={})=>{var u,d,m;const[s,o]=l.useState(!1),i=l.useRef(0),c=()=>{if(!t)return;const h=++i.current;e.aiAgent.getUnreadMessageCount(r).then(f=>{h===i.current&&o(f.total>0)}).catch(()=>{})};return l.useEffect(()=>{if(!t){o(!1),i.current++;return}e.connectionState===ue.ConnectionState.OPEN&&c()},[t,e,r==null?void 0:r.aiAgentChannelFilter,(u=r==null?void 0:r.aiAgentConversationStatusFilter)==null?void 0:u.join(),(d=r==null?void 0:r.aiAgentIds)==null?void 0:d.join(),r==null?void 0:r.deskChannelFilter,(m=r==null?void 0:r.pinnedChannelUrls)==null?void 0:m.join(),r==null?void 0:r.copilotConversationOnly,r==null?void 0:r.copilotSupportChannelUrl]),l.useEffect(()=>{n&&(o(!1),i.current++)},[n]),Xt(e,{onConnected:c,onReconnectSucceeded:c}),s},Hr=e=>e.replace(/\s+/g," ").trim(),xm="Code block",Mi=e=>`A11Y_INLINE_CODE_${e}`,wi=e=>{let t="",n=e;for(;;){const r=n.match(/^([ \t]{0,3}>\s?)(.*)$/);if(r){t+=r[1],n=r[2];continue}break}return{blockquotePrefix:t,content:n}},ki=e=>{const t=e.match(/^([ \t]{0,3}[-+*]\s+)(.*)$/);if(t)return{content:t[2],hasListPrefix:!0};const n=e.match(/^([ \t]{0,3}\d+[.)]\s+)(.*)$/);return n?{content:n[2],hasListPrefix:!0}:{content:e,hasListPrefix:!1}},Rm=e=>{const{blockquotePrefix:t,content:n}=wi(e),{content:r}=ki(n),s=r.match(/^[ \t]{0,3}([`~]{3,})(.*)$/);if(!s)return;const o=s[1],i=s[2],c=o[0];if(!(c!=="`"&&c!=="~"||!o.split("").every(u=>u===c))&&!(c==="`"&&i.includes("`")))return{char:c,blockquotePrefix:t,length:o.length}},Mm=(e,t)=>{const{blockquotePrefix:n,content:r}=wi(e);if(n!==t.blockquotePrefix)return!1;const{content:s,hasListPrefix:o}=ki(r);if(o)return!1;const i=s.match(/^[ \t]{0,3}([`~]{3,})[ \t]*$/);if(!i)return!1;const c=i[1];return c[0]===t.char&&c.length>=t.length&&c.split("").every(u=>u===t.char)},wm=(e,t,n)=>{let r=n;for(;r<e.length;){const s=e[r];if(s==="\\"&&r+1<e.length){r+=2;continue}if(s===t)return r;r+=1}return-1},km=(e,t)=>{let n=1,r=t;for(;r<e.length;){const s=e[r];if(s==="\\"&&r+1<e.length){r+=2;continue}if(s==="["){n+=1,r+=1;continue}if(s==="]"&&(n-=1,n===0))return r;r+=1}return-1},Lm=(e,t)=>{let n=t,r=1,s,o=!1,i=!1;for(;n<e.length&&r>0;){const c=e[n];if(c==="\\"&&n+1<e.length){n+=2;continue}if(s){c===s&&(s=void 0),n+=1;continue}if(r===1&&o&&/\s/.test(c)){i=!0,n+=1;continue}if(r===1&&i&&(c==='"'||c==="'")){s=c,n+=1;continue}if(c==="("){r+=1,o=!0,n+=1;continue}if(c===")"){r-=1,n+=1;continue}/\s/.test(c)||(o=!0),n+=1}return r===0?n:-1},Om=e=>{let t=0,n="";for(;t<e.length;){const r=wm(e,"[",t);if(r===-1){n+=e.slice(t);break}const s=km(e,r+1);if(s===-1){n+=e.slice(t);break}if(r>0&&e[r-1]==="!"&&Tn(e,r-1)){n+=e.slice(t,s+1),t=s+1;continue}if(e[s+1]!=="("){n+=e.slice(t,s+1),t=s+1;continue}const o=r>0&&e[r-1]==="!"&&!Tn(e,r-1)?r-1:r;n+=e.slice(t,o);const i=e.slice(r+1,s),c=Lm(e,s+2);if(c===-1){n+=e.slice(o);break}n+=i,t=c}return n},Li=(e,t,n)=>{if(!/^\d+$/.test(t))return!1;const r=e.slice(-1);return/\d/.test(r)&&/\d/.test(n)},Nm=e=>e.replace(/(^|[^*\\])\*\*([^\s*](?:[\s\S]*?[^\s*])?)\*\*(?!\*)/g,(t,n,r,s,o)=>{const i=o[s+t.length]??"";return Li(n,r,i)?t:`${n}${r}`}),Dm=e=>e.replace(/(^|[^_\\])__([^\s_](?:[\s\S]*?[^\s_])?)__(?!_)/g,"$1$2"),$m=e=>e.replace(/(^|[^~\\])~~([^\s~](?:[\s\S]*?[^\s~])?)~~(?!~)/g,"$1$2"),Fm=e=>{let t=e;return t=t.replace(/(^|[^*\\])\*([^\s*](?:[\s\S]*?[^\s*])?)\*(?!\*)/g,(n,r,s,o,i)=>{const c=i[o+n.length]??"";return Li(r,s,c)?n:`${r}${s}`}),t=t.replace(/(^|[\s([{"'])_([^_\s](?:[\s\S]*?[^_\s])?)_(?=$|[\s)\]}"'.,!?:;])/g,"$1$2"),t},Pm=e=>e.replace(/\\([\\`*_[\]()#+.!~|-])/g,"$1"),Um=e=>{let t=e;return t=t.replace(/^\s{0,3}#{1,6}\s+/gm,""),t=t.replace(/^\s{0,3}>\s?/gm,""),t=t.replace(/^\s{0,3}(?!([-*_])(?:\s*\1){2,}\s*$)[-*+]\s+/gm,""),t=t.replace(/^\s{0,3}\d+[.)]\s+/gm,""),t},Ks=e=>{const t=e.trim();if(!t.includes("|"))return!1;const n=t.split("|").map(r=>r.trim()).filter(Boolean);return n.length===0?!1:n.every(r=>/^:?-{3,}:?$/.test(r))},Ys=e=>{const t=[];let n="",r=!1;for(const o of e.trim()){if(r){n+=o==="|"?"|":`\\${o}`,r=!1;continue}if(o==="\\"){r=!0;continue}if(o==="|"){const i=n.trim();i&&t.push(i),n="";continue}n+=o}r&&(n+="\\");const s=n.trim();return s&&t.push(s),t},Bm=e=>{const t=e.split(`
|
|
1
|
+
"use strict";var ac=Object.defineProperty;var cc=(e,t,n)=>t in e?ac(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var v=(e,t,n)=>cc(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const de=require("@sendbird/chat"),l=require("react"),G=require("styled-components"),at=require("date-fns"),lc=require("date-fns/locale/en-US"),Fe=require("@sendbird/chat/message"),me=require("@sendbird/chat/aiAgent"),uc=require("react-dom"),We=require("@sendbird/chat/groupChannel"),dc=require("date-fns/isSameDay"),mc=require("dompurify"),Tr=e=>e&&e.__esModule?e:{default:e};function hc(e){if(e&&e.__esModule)return e;const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const fc=Tr(de),a=hc(l),C=Tr(G),Ko=Tr(mc),Yo=e=>{try{return JSON.parse(e===""?"{}":e)}catch{return{}}},gc=e=>{const t=Yo(e);return typeof t=="object"&&t!==null?t:{}},Wo=e=>typeof e=="string"?gc(e):e??{},pc=e=>!!Wo(e).stream,hs=e=>{if(typeof e=="number"&&Number.isSafeInteger(e)&&e>0)return e;if(typeof e!="string"||e.trim().length===0)return;const t=Number(e);return Number.isSafeInteger(t)&&t>0?t:void 0},jo=e=>{const t=Wo(e),n=hs(t.user_message_id)??hs(t.respond_mesg_id);return{isStreaming:!!t.stream,hasResponseMetadata:Object.prototype.hasOwnProperty.call(t,"stream")||n!==void 0,...n!==void 0&&{userMessageId:n}}},bt="sb-agent",Xo="KEY_IMG_ASPECT_RATIO",lr="*/*",te={BODY_MAX_WIDTH:244,WIDE_BODY_MAX_WIDTH:640,AVATAR_SIZE:26,BODY_TIME_GAP:4,HORIZONTAL_PADDING:12,GAP_GROUPED:2,GAP_UNGROUPED:16};var bn=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(bn||{}),Pt=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(Pt||{});const _c=e=>!!(e!=null&&e.cta_button),Ec=e=>{var t;return!!((t=e==null?void 0:e.citations)!=null&&t.length)},Zo=e=>!!(e!=null&&e.form)&&!e.form.canceled_at,Cc=e=>{var t;return Zo(e)&&!((t=e==null?void 0:e.form)!=null&&t.submitted_at)},bc=e=>{var t;return!!((t=e==null?void 0:e.suggested_replies)!=null&&t.length)},Ve=e=>{let t;return{enumerable:!0,get:()=>(t??(t=e()),t)}},kn=e=>Object.defineProperties({},{hasMessageTemplate:Ve(()=>!!(e!=null&&e.message_template)),hasCTAButton:Ve(()=>_c(e)),hasChallenge:Ve(()=>!!(e!=null&&e.challenge)),isThinking:Ve(()=>!!(e!=null&&e.is_thinking)),hasCSAT:Ve(()=>!!(e!=null&&e.csat)),hasSuggestedReplies:Ve(()=>bc(e)),hasCustomMessageTemplates:Ve(()=>{var t;return!!((t=e==null?void 0:e.custom_message_templates)!=null&&t.length)}),hasForm:Ve(()=>Zo(e)),hasActiveForm:Ve(()=>Cc(e)),hasSteward:Ve(()=>!!(e!=null&&e.steward)),hasCitations:Ve(()=>Ec(e))}),vc=e=>{const t=kn(e);return t.hasMessageTemplate||t.hasCTAButton||t.hasCSAT||t.hasSuggestedReplies||t.hasForm||t.hasSteward||t.hasCitations},Jo=e=>{var t;return!!((t=e==null?void 0:e.extendedMessagePayload)!=null&&t.steward)},yc=e=>e===Pt.COMPLETED||e===Pt.CANCELED?e:Pt.IN_PROGRESS,Kn=e=>Qe(e)&&!Jo(e),Qe=e=>!!e&&"sender"in e,Sc=e=>Qe(e)?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId),Ac=(e,t,n,r=!0)=>{if(!r||!Kn(e))return"single";const s=()=>{if(!Kn(t))return!1;const u=t.sender.userId===e.sender.userId,d=at.isSameMinute(t.createdAt,e.createdAt);return u&&d},o=()=>{if(!Kn(n))return!1;const u=n.sender.userId===e.sender.userId,d=at.isSameMinute(n.createdAt,e.createdAt);return u&&d},i=s(),c=o();return i&&c?"middle":i?"bottom":c?"top":"single"},st=(e,t)=>(()=>{var r;return Qe(e)?e.sender.userId:((r=e==null?void 0:e.sender)==null?void 0:r.userId)??void 0})()===t,Oe={isAdmin:e=>e.isAdminMessage(),isCSAT:e=>{var t;return e.isAdminMessage()&&!!((t=e.extendedMessagePayload)!=null&&t.csat)},isSteward:e=>Jo(e),isIncoming:(e,t)=>Qe(e)&&e.sender.userId!==t,isOutgoing:(e,t)=>Qe(e)&&(e.sender.userId===t||e.sendingStatus===Fe.SendingStatus.PENDING)},Ye=e=>e.startsWith("image/"),zt=e=>e.startsWith("video/"),Tc=e=>e.startsWith("audio/"),Qo=({name:e="",mimeType:t=""})=>t==="application/pdf"||/\.pdf$/i.test(e.trim()),Ir=(e,t)=>{if(e&&!e.startsWith(".")){const n=e.split(".").pop();if(n&&n!==e)return n.toUpperCase()}if(t){const[,n]=t.split("/");if(n)return n.toUpperCase()}return"FILE"},ei=e=>{var t;return e.messageType==="file"?e.message.length>0&&e.file.name!==e.message:e.messageType==="multipleFiles"?e.message.length>0&&((t=e.files[0])==null?void 0:t.name)!==e.message:e.message.length>0},Ic=e=>{if(e.message&&e.message.trim().length>0)return!0;const t=e.extendedMessagePayload;return vc(t)},Ln=e=>{switch(e){case"top":case"middle":return te.GAP_GROUPED;default:return te.GAP_UNGROUPED}},xc=(e,t)=>{const n=/```(\w+)?\n([\s\S]*?)```/g,r=[];let s=0;return e.replace(n,(o,...i)=>{const[c,u,d]=i;return s<d&&r.push({type:"text",value:e.slice(s,d).trim()}),r.push({type:"code",value:u.trim(),language:c?c.trim():"plaintext"}),s=d+o.length,o}),s<e.length&&r.push({type:"text",value:e.slice(s).trim()}),t?r.map(o=>o.type!=="text"?o:{...o,value:t(o.value)}):r},Rc=e=>e.replace(/\[([^\]]+)\](?!\()/g,"\\[$1\\]"),Mc=e=>e.replace(/([a-zA-Z0-9])_(?=[a-zA-Z0-9])/g,"$1\\_"),wc=e=>e.replace(/~~/g,"\\~\\~"),kc=e=>{let t=e;return t=Rc(t),t=Mc(t),t=wc(t),t},Lc=typeof navigator<"u"&&navigator.product==="ReactNative",fs=(e,t)=>{const n=r=>!t||t.length===0?!0:Qe(r)&&t.includes(r.sendingStatus);return Lc?e.find(n):e.findLast(n)};function ue(){}function Oc(){const e=typeof navigator<"u"?navigator.userAgent:"",t=/iPad|iPhone|iPod/.test(e),n=/Android/.test(e);return t||n}function Nc(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return t.toString(16)}const Me={isStreaming(e){return pc(e.data)},isExplicitWelcomeMessage(e){var t;return((t=e.extendedMessagePayload)==null?void 0:t.bot_message_type)==="welcome"},isWelcomeMessage(e,t){var r;if(Me.isExplicitWelcomeMessage(e))return!0;if(((r=e.extendedMessagePayload)==null?void 0:r.bot_message_type)!==void 0||!st(e,t))return!1;const n=jo(e.data);return!n.isStreaming&&!n.hasResponseMetadata},isGeneratedMessage(e){var t;return((t=e.extendedMessagePayload)==null?void 0:t.bot_message_type)==="generated"},hasFeedback(e){var t;return!!((t=e.extendedMessagePayload)!=null&&t.feedback)}},Yn=`@${bt}`,Dc=({appId:e,aiAgentId:t,storage:n})=>{const r={templateBase:`${Yn}-template`,template:s=>`${r.templateBase}/templates/${s}`,templateToken:()=>`${r.templateBase}/tokens`,messengerSession:s=>{const o=Nc(`${e}/${t}/${s}`);return`${Yn}-udata/${o}`},anonUserSession:()=>`${Yn}-session/${e}/${t}`};return{template:{set:(s,o)=>n.set(r.template(s),o),get:s=>n.get(r.template(s)),setCachedToken:s=>n.set(r.templateToken(),s),getCachedToken:()=>n.get(r.templateToken()),clear:()=>{n.getKeys(r.templateBase).forEach(n.delete)}},messenger:{getSettings:s=>{try{const o=n.get(r.messengerSession(s));return o?JSON.parse(o):null}catch{return null}},setSettings:(s,o)=>{try{delete o.auto_created_user;const i=JSON.stringify(o);n.set(r.messengerSession(s),i)}catch{return}},getAnonUser:()=>{try{const s=n.get(r.anonUserSession());return s?JSON.parse(s):null}catch{return null}},setAnonUser:s=>{try{const o=JSON.stringify(s);n.set(r.anonUserSession(),o)}catch{return}},clear:s=>{try{s&&n.delete(r.messengerSession(s)),n.delete(r.anonUserSession())}catch{return}}}}},ti=(e,t,n={})=>{let r=null,s=null,o=null;const{leading:i=!0,trailing:c=!0}=n,u=(...d)=>{const m=Date.now();if(o===null||m-o>=t)i?(e(...d),o=m):(s=d,o=m);else if(s=d,c&&!r){const h=t-(m-o);r=setTimeout(()=>{s&&c&&(e(...s),o=Date.now()),r=null,s=null},h)}};return u.cancel=()=>{r&&(clearTimeout(r),r=null),s=null,o=null},u},$c=()=>{let e=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const n=(e+Math.random()*16)%16|0;return e=Math.floor(e/16),(t==="x"?n:n&3|8).toString(16)})};class Fc{constructor(t){v(this,"_params");this._params={aiAgentChannelFilter:(t==null?void 0:t.aiAgentChannelFilter)??me.AIAgentChannelFilter.INCLUDE,aiAgentConversationStatusFilter:(t==null?void 0:t.aiAgentConversationStatusFilter)??[me.ConversationStatus.OPEN,me.ConversationStatus.CLOSED],aiAgentIds:(t==null?void 0:t.aiAgentIds)??[],deskChannelFilter:(t==null?void 0:t.deskChannelFilter)??me.DeskChannelFilter.INCLUDE,pinnedChannelUrls:(t==null?void 0:t.pinnedChannelUrls)??[],copilotConversationOnly:(t==null?void 0:t.copilotConversationOnly)??!1,copilotSupportChannelUrl:t==null?void 0:t.copilotSupportChannelUrl}}get params(){return{...this._params}}match(t,n){const{pinnedChannelUrls:r,aiAgentChannelFilter:s,aiAgentConversationStatusFilter:o,aiAgentIds:i,deskChannelFilter:c}=this._params;return r!=null&&r.includes(t.url)?!0:t.isAIAgent?!(!t.conversation||s===me.AIAgentChannelFilter.EXCLUDE||i&&i.length>0&&!i.includes(t.conversation.aiAgentId)||o&&o.length>0&&!o.some(d=>{var m;return((m=t.conversation)==null?void 0:m.status)===d})):t.isDesk?c!==me.DeskChannelFilter.EXCLUDE:!1}}class ni extends We.BaseChannelCollection{constructor(n,r){const s=new Fc(r.filter),o=n,i=o.aiAgent._manager,c=r.limit??20,u=We.GroupChannelListOrder.LATEST_LAST_MESSAGE,d={getRemoteChannels:(m,h,f,g)=>i.getMyGroupChannels(m,h.params,g),changeLogSync:m=>{const{aiAgentChannelFilter:h,aiAgentIds:f,deskChannelFilter:g,pinnedChannelUrls:_,copilotConversationOnly:y,copilotSupportChannelUrl:b}=s.params,p={aiAgentChannelFilter:h,aiAgentIds:f,deskChannelFilter:g,pinnedChannelUrls:_,copilotConversationOnly:y,copilotSupportChannelUrl:b};return i.getMyGroupChannelChangeLogs(m,p,We.GroupChannelEventSource.SYNC_CHANNEL_CHANGELOGS)}};super(o.aiAgent._iid,{filter:s,order:u,limit:c,syncKeyPrefix:"aiAgent",fetcher:d});v(this,"_params");v(this,"_sdk");v(this,"_throttledOnChannelChanged");v(this,"_key");v(this,"_pendingChannels",[]);this._sdk=n,this._params=r,this._key=`clc-${$c()}`,this._throttledOnChannelChanged=ti(()=>{var g;const m=[...this._pendingChannels];this._pendingChannels=[];const h=new Map;for(const{channel:_,context:y}of m)h.delete(_.url),h.set(_.url,{channel:_,context:y});const f=new Map;for(const{channel:_,context:y}of h.values())f.has(y)||f.set(y,new Map),f.get(y).set(_.url,_);for(const[_,y]of f){const b=Array.from(y.values()),p=(g=this._sdk.currentUser)==null?void 0:g.userId,S=b.filter(T=>this.filter.match(T,p)),A=b.filter(T=>!this.filter.match(T,p)).map(T=>T.url);S.length>0&&this._base._addChannelsToView(S,_,!1),A.length>0&&this._removeChannels(A,_)}},250,{trailing:!0,leading:!0}),this._base._subscribeChannelEvent(this._key,{onUpdate:(m,h)=>{for(const f of m)this._pendingChannels.push({channel:f,context:h});this._throttledOnChannelChanged()},onRemove:(m,h)=>{this._removeChannels(m,h)}})}get _base(){return this}_removeChannels(n,r){const s=new Set(n);this._pendingChannels=this._pendingChannels.filter(({channel:o})=>!s.has(o.url)),this._base._removeChannelsFromView(n,r)}get channels(){var c;const n=((c=this._params.filter)==null?void 0:c.pinnedChannelUrls)??[],r=[],s=new Map(super.channels.map(u=>[u.url,u])),o=new Set;for(const u of n){const d=s.get(u);d&&!o.has(u)&&(r.push(d),o.add(u))}const i=super.channels.filter(u=>!o.has(u.url));return[...r,...i]}setConversationListCollectionHandler(n){super.setGroupChannelCollectionHandler(n)}dispose(){super.dispose(),this._throttledOnChannelChanged.cancel(),this._base._unsubscribeChannelEvent(this._key)}}class ri{constructor(t){v(this,"subscribers",{});this.logger=t}async send(t){const n=Pc(),r=this.subscribers[t.type];if(r){this.logger.debug(`messenger.dispatcher: dispatching command: ${t.type}`,t.payload);const s=r.map(o=>o(t.payload));await Promise.all(s).catch(o=>{this.logger.error(`messenger.dispatcher: error in callback for command: ${t.type}`,o)})}return n.resolve(),n.promise}subscribe(t,n){this.subscribers[t]||(this.subscribers[t]=[]),this.subscribers[t].push(n)}unsubscribe(t,n){const r=this.subscribers[t];r&&(this.subscribers[t]=r.filter(s=>s!==n))}}const Pc=()=>{let e=ue,t=ue;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}};var Ke=(e=>(e.ConversationClose="conv.close",e.MessengerSettingsUpdated="messenger.settings.updated",e.ActiveChannelUpdated="active.channel.updated",e.AnonymousSessionTokenExpired="anon.token.expired",e.AuthTokenRefreshed="auth.token.refreshed",e))(Ke||{});class Vt{constructor(t={}){v(this,"payload");this.payload=t}toJSON(){return JSON.stringify({type:this.type,payload:this.payload})}}const ct={CloseConversation:e=>new Uc(e),MessengerSettingsUpdated:e=>new Bc(e),ActiveChannelUpdated:e=>new Hc(e),AnonymousSessionTokenExpired:()=>new Gc,AuthTokenRefreshed:()=>new zc};class Uc extends Vt{constructor(){super(...arguments);v(this,"type","conv.close")}}class Bc extends Vt{constructor(){super(...arguments);v(this,"type","messenger.settings.updated")}}class Hc extends Vt{constructor(){super(...arguments);v(this,"type","active.channel.updated")}}class Gc extends Vt{constructor(){super(...arguments);v(this,"type","anon.token.expired")}}class zc extends Vt{constructor(){super(...arguments);v(this,"type","auth.token.refreshed")}}const qt=e=>{const t={};for(const n of Object.keys(e)){const r=e[n];r!==void 0&&(t[n]=String(r))}return t};class Kt{constructor(t){v(this,"category","connection");this.userId=t}get data(){return qt({user_id:this.userId})}}class Vc extends Kt{constructor(){super(...arguments);v(this,"metricKey","connection_connected")}}class qc extends Kt{constructor(){super(...arguments);v(this,"metricKey","connection_reconnect_started")}}class Kc extends Kt{constructor(){super(...arguments);v(this,"metricKey","connection_reconnect_succeeded")}}class Yc extends Kt{constructor(){super(...arguments);v(this,"metricKey","connection_reconnect_failed")}}class Wc extends Kt{constructor(){super(...arguments);v(this,"metricKey","connection_disconnected")}}class jc{constructor(t){v(this,"lastKey",null);this.dispatch=t}handleEvent({detail:t,userId:n}){const r=`${t}:${n}`;if(this.shouldEmit(r)){this.lastKey=r;const s=t==="connected"?new Vc(n):t==="reconnectStarted"?new qc(n):t==="reconnectSucceeded"?new Kc(n):t==="reconnectFailed"?new Yc(n):new Wc(n);this.dispatch(s)}}shouldEmit(t){return t!==this.lastKey}}class xr{constructor(t,n){v(this,"category","conversation");this.channelUrl=t,this.conversationId=n}get data(){return qt({channel_url:this.channelUrl,conversation_id:this.conversationId})}}class Xc extends xr{constructor(){super(...arguments);v(this,"metricKey","conversation_initialized")}}class Zc extends xr{constructor(){super(...arguments);v(this,"metricKey","conversation_open")}}class Jc extends xr{constructor(){super(...arguments);v(this,"metricKey","conversation_closed")}}class Qc{constructor(t){v(this,"statusByChannel",new Map);this.dispatch=t}handleEvent({channel:t}){const{conversation:n}=t;if(!n)return;const r=this.statusByChannel.get(t.url),s=n.status;if(this.statusByChannel.set(t.url,s),this.shouldEmit(r,s)){const o=s===me.ConversationStatus.INITIALIZED?new Xc(t.url,n.id):s===me.ConversationStatus.OPEN?new Zc(t.url,n.id):new Jc(t.url,n.id);this.dispatch(o)}}shouldEmit(t,n){return n===me.ConversationStatus.INITIALIZED?t===void 0:n===me.ConversationStatus.OPEN?t===me.ConversationStatus.INITIALIZED:t===me.ConversationStatus.OPEN}}const si=(e,t)=>{if(e)return e.members.filter(n=>n.userId!==t).sort((n,r)=>r.joinedAt-n.joinedAt)[0]},He=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===me.ConversationStatus.CLOSED||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="closed")},Rr=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===me.ConversationStatus.OPEN||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="open")};function rt(e){var n,r,s;return typeof(((n=e==null?void 0:e.conversation)==null?void 0:n.handedOverAt)??((s=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff)==null?void 0:s.timestamp))=="number"}function el(e){var r;const t=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff;return t?typeof t.requestedAt=="number"&&!rt(e):!1}function tl(e){var t;if(((t=e==null?void 0:e.resolution)==null?void 0:t.determinedBy)==="user")return e.resolution.isResolved}function oi(e){return!!e&&e<=Date.now()}function nl(e){return!e.title}function rl(e,t){var n;if(e)return nl(e)?{...e,title:t.title,csat_question:t.question,csat_scores:[{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/angry-active.png"},{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/suspicious-active.png"},{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/neutral-active.png"},{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/smile-active.png"},{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/happy-active.png"}],cre:{required:((n=e.cre)==null?void 0:n.required)??!0,question:t.cre.question,positive_label:t.cre.positive_label,negative_label:t.cre.negative_label},follow_up:[{response_type:"free_text",scores:[1,2,3,4,5],question:t.followUp.question,always_visible:!1}],csat_submit_label:t.submit_label,csat_submitted_label:t.submitted_label}:e}class Mr{constructor(t,n){v(this,"category","handoff");this.channelUrl=t,this.conversationId=n}get data(){return qt({channel_url:this.channelUrl,conversation_id:this.conversationId})}}class sl extends Mr{constructor(){super(...arguments);v(this,"metricKey","handoff_started")}}class ol extends Mr{constructor(){super(...arguments);v(this,"metricKey","handoff_succeeded")}}class il extends Mr{constructor(){super(...arguments);v(this,"metricKey","handoff_failed")}}class al{constructor(t){v(this,"statusByChannel",new Map);this.dispatch=t}handleEvent({channel:t}){const n=!this.statusByChannel.has(t.url);n&&this.statusByChannel.set(t.url,void 0);const r=t.conversation;if(!r||!r.handoff||n)return;const s=this.statusByChannel.get(t.url),o=this.resolveStatus(t,r);if(o!==void 0&&this.shouldEmit(s,o)){this.statusByChannel.set(t.url,o);const i=o==="started"?new sl(t.url,r.id):o==="succeeded"?new ol(t.url,r.id):new il(t.url,r.id);this.dispatch(i)}}resolveStatus(t,n){if(He(t))return"failed";const{members:r}=t;if(r.length===1)return"started";if(r.length===2&&n.aiAgentId&&!r.some(s=>s.userId===n.aiAgentId))return"succeeded"}shouldEmit(t,n){return n==="started"?t===void 0:t==="started"}}class cl{constructor(t){v(this,"category","message");v(this,"metricKey","incoming_message_received");v(this,"channelUrl");v(this,"messageId");v(this,"senderType");v(this,"createdAt");v(this,"conversationId");this.channelUrl=t.channelUrl,this.messageId=t.messageId,this.senderType=t.senderType,this.createdAt=t.createdAt,this.conversationId=t.conversationId}get data(){return qt({channel_url:this.channelUrl,message_id:this.messageId,sender_type:this.senderType,created_at:this.createdAt,conversation_id:this.conversationId})}}const ll=(e,t)=>{const n=Qe(e)?e.sender.userId:void 0;return n===void 0?"system":n===t?"ai_agent":"human_agent"};class ul{constructor(t,n){this.dispatch=t,this.getCurrentUserId=n}handleEvent({channel:t,message:n}){const{conversation:r}=t;this.shouldEmit(n,r)&&this.dispatch(new cl({channelUrl:t.url,messageId:n.messageId,senderType:ll(n,r.aiAgentId),createdAt:n.createdAt,conversationId:r.id}))}shouldEmit(t,n){return!st(t,this.getCurrentUserId())&&n!==null}}class dl{constructor(t){v(this,"category","message");v(this,"metricKey");v(this,"channelUrl");v(this,"requestId");v(this,"messageId");v(this,"target");v(this,"sendingStatus");v(this,"createdAt");v(this,"conversationId");this.channelUrl=t.channelUrl,this.requestId=t.requestId,this.messageId=t.messageId,this.target=t.target,this.sendingStatus=t.sendingStatus,this.createdAt=t.createdAt,this.conversationId=t.conversationId,this.metricKey=`outgoing_message_${t.sendingStatus}`}get data(){return qt({channel_url:this.channelUrl,request_id:this.requestId,message_id:this.messageId,target:this.target,created_at:this.createdAt,conversation_id:this.conversationId})}}const ml=e=>{switch(e){case Fe.SendingStatus.PENDING:return"pending";case Fe.SendingStatus.SUCCEEDED:return"succeeded";case Fe.SendingStatus.FAILED:return"failed";case Fe.SendingStatus.SCHEDULED:return"scheduled";default:return}};class hl{constructor(t,n){v(this,"statusByReqId",new Map);this.dispatch=t,this.getCurrentUserId=n}handleEvent({channel:t,message:n}){var o;if(!st(n,this.getCurrentUserId()))return;const r=ml(n.sendingStatus);if(r===void 0)return;const s=this.statusByReqId.get(n.reqId);this.statusByReqId.set(n.reqId,r),r!=="scheduled"&&this.shouldEmit(s,r)&&this.dispatch(new dl({channelUrl:t.url,requestId:n.reqId,messageId:r==="succeeded"?n.messageId:void 0,target:rt(t)?"human_agent":"ai_agent",sendingStatus:r,createdAt:n.createdAt,conversationId:(o=t.conversation)==null?void 0:o.id}))}shouldEmit(t,n){return n==="pending"?t!=="pending"&&t!=="succeeded":n==="succeeded"?t==="pending"||t==="scheduled":t!=="failed"}}class fl{constructor(t){v(this,"id","aiagent_livemetric");v(this,"dispatch");v(this,"emit",({category:t,metricKey:n,data:r})=>{var s;(s=this.dispatch)==null||s.call(this,{category:t,metricKey:n,data:r})});v(this,"emitters");this.chatSDK=t;const n=()=>{var r;return(r=this.chatSDK.currentUser)==null?void 0:r.userId};this.emitters={connection:new jc(this.emit),conversation:new Qc(this.emit),handoff:new al(this.emit),incomingMessage:new ul(this.emit,n),outgoingMessage:new hl(this.emit,n)}}start(){const t=new de.ConnectionHandler({onConnected:r=>this.trackConnection("connected",r),onDisconnected:r=>this.trackConnection("disconnected",r),onReconnectStarted:()=>this.trackConnection("reconnectStarted"),onReconnectSucceeded:()=>this.trackConnection("reconnectSucceeded"),onReconnectFailed:()=>this.trackConnection("reconnectFailed")}),n=new We.GroupChannelHandler({onMessageReceived:(r,s)=>{r.isGroupChannel()&&this.track({type:"incomingMessage",channel:r,message:s})},onChannelChanged:r=>{r.isGroupChannel()&&(this.track({type:"handoff",channel:r}),this.track({type:"conversation",channel:r}))},onUserJoined:r=>this.track({type:"handoff",channel:r}),onUserLeft:r=>this.track({type:"handoff",channel:r})});this.chatSDK.addConnectionHandler(this.id,t),this.chatSDK.groupChannel.addGroupChannelHandler(this.id,n)}track(t){try{this.emitters[t.type].handleEvent(t)}catch{}}dispose(){this.chatSDK.removeConnectionHandler(this.id),this.chatSDK.groupChannel.removeGroupChannelHandler(this.id)}trackConnection(t,n=(r=>(r=this.chatSDK.currentUser)==null?void 0:r.userId)()){n&&this.track({type:"connection",detail:t,userId:n})}}var wr=(e=>(e[e.VERBOSE=0]="VERBOSE",e[e.DEBUG=1]="DEBUG",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.NONE=5]="NONE",e))(wr||{});class ii{constructor(t){v(this,"level");this.level=t}verbose(...t){this.level<=0&&console.log(`[${bt}/verbose]`,...t)}debug(...t){this.level<=1&&console.log(`[${bt}/debug]`,...t)}info(...t){this.level<=2&&console.log(`[${bt}/info]`,...t)}warn(...t){this.level<=3&&console.warn(`[${bt}/warn]`,...t)}error(...t){this.level<=4&&console.error(`[${bt}/error]`,...t)}}class ai{constructor({userId:t,authToken:n,sessionHandler:r}){v(this,"userId");v(this,"authToken");v(this,"sessionHandler");this.userId=t,this.authToken=n,this.sessionHandler=r}}class ur{constructor(){v(this,"userId");v(this,"authToken");v(this,"sessionHandler")}}const gl=e=>({onSessionTokenRequired:t=>{t(null),e.send(ct.AnonymousSessionTokenExpired())}}),ci="ai_agent:stats",pl="conversation_initial_render",gs="conversation_not_interactive_timeout",_l="recovery_not_interactive_timeout",El="conversation_list_initial_render",Cl="message_pending_stuck",ps="aiev_auth_expired_unhandled",bl="user_perceived_response_time",vl="stream_stalled",yl="ai_typing_indicator_absent_timeout",Sl="rendered_content_unusable",li=800220;var ge=(e=>(e.AUTH="auth_duration_ms",e.GET_CHANNEL="get_channel_duration_ms",e.GET_MESSAGES="get_messages_duration_ms",e.TOTAL_DURATION="total_duration_ms",e.TOTAL_DURATION_FROM_CACHE="total_duration_from_cache_ms",e))(ge||{});const vn={now:()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()},ui=(e,t,n)=>{const r={key:e,value:String(t)};return(n==null?void 0:n.conversationId)!==void 0&&(r.conversation_id=n.conversationId),n!=null&&n.error&&(r.error_code=n.error.code??li,r.error_description=n.error.message??""),n!=null&&n.extra&&Object.keys(n.extra).length>0&&(r.extra=n.extra),r},It=e=>(e==null?void 0:e.clock)??vn,Al=((e,t)=>setTimeout(e,t)),Tl=(e=>clearTimeout(e)),Yt=e=>(e==null?void 0:e.setTimeout)??Al,Wt=e=>(e==null?void 0:e.clearTimeout)??Tl,et=(e,t,n,r)=>e(ci,ui(t,n,r)),Se=(e,t)=>{e!==null&&t(e)},On=(e,t)=>{if(e.size<t)return;const n=e.keys().next();n.done||e.delete(n.value)},mt=(e,t)=>!(e.channelUrl&&t&&e.channelUrl!==t),di=(e,t)=>{for(const n of e)if(n.userMessageId===void 0&&mt(n,t))return!0;return!1};class Il{constructor(t){v(this,"callback");this.callback=t}onPayloadParseFailed(t){et(this.callback,ps,"payload_parse_failed",{extra:{agent_id:t.aiAgentId}})}onCallbackNotFound(t){et(this.callback,ps,"callback_not_found",{extra:{agent_id:t.aiAgentId}})}clear(){}}class xl{constructor(){v(this,"timers",new Map);v(this,"committed",!1);v(this,"commitCallback",null);v(this,"conversationId",null);v(this,"channelUrl",null);v(this,"errorCode",null);v(this,"errorDescription",null);v(this,"extraData",{})}setCommitCallback(t){return this.commitCallback=t,this}setConversationId(t){return this.conversationId=t,this}setChannelUrl(t){return this.setExtra("channel_url",t),this}setError(t,n){return this.errorCode=t??li,this.errorDescription=n,this}setExtra(t,n){return n!=null&&(this.extraData[t]=n),this}startTimer(t){if(this.committed)return this;const n=this.timers.get(t);return(n==null?void 0:n.startTime)!==null&&(n==null?void 0:n.startTime)!==void 0?this:(this.timers.set(t,{startTime:vn.now(),endTime:null}),this)}stopTimer(t){if(this.committed)return this;const n=this.timers.get(t);return!n||n.startTime===null||n.endTime!==null?this:(this.timers.set(t,{...n,endTime:vn.now()}),this)}getDuration(t){const n=this.timers.get(t);return!n||n.startTime===null||n.endTime===null?null:n.endTime-n.startTime}isCommitted(){return this.committed}commit(){if(this.committed||!this.commitCallback)return!1;const t=this.buildPayload();return t?(this.committed=!0,this.commitCallback(ci,t)):!1}}class Rl extends xl{constructor(){super(...arguments);v(this,"presentMethod","direct_present")}setPresentMethod(n){return this.presentMethod=n,this}getMetricKey(){return pl}buildPayload(){const n=this.getDuration(ge.AUTH),r=this.getDuration(ge.GET_CHANNEL),s=this.getDuration(ge.GET_MESSAGES),o=this.getDuration(ge.TOTAL_DURATION_FROM_CACHE),i=this.getDuration(ge.TOTAL_DURATION),c={...this.extraData,present_method:this.presentMethod,...n!==null&&{[ge.AUTH]:n},...r!==null&&{[ge.GET_CHANNEL]:r},...s!==null&&{[ge.GET_MESSAGES]:s},...o!==null&&{[ge.TOTAL_DURATION_FROM_CACHE]:o}};return ui(this.getMetricKey(),i??0,{conversationId:this.conversationId??void 0,error:this.errorCode!==null?{code:this.errorCode,message:this.errorDescription??""}:void 0,extra:c})}}class Ml{constructor(t){v(this,"commitCallback");v(this,"apiResultReceived",!1);v(this,"channelUrl");v(this,"consumed",!1);v(this,"consumedByAuthError",!1);v(this,"presentMethod","direct_present");v(this,"renderedAfterApiResult",!1);v(this,"stats",null);this.commitCallback=t}getOrCreateStats(){var t;return this.consumed?null:(t=this.stats)!=null&&t.isCommitted()?(this.consumed=!0,null):(this.stats||(this.stats=new Rl().setCommitCallback(this.commitCallback).setPresentMethod(this.presentMethod),this.apiResultReceived=!1,this.renderedAfterApiResult=!1),this.stats)}getActiveStats(){return this.consumed||!this.stats||this.stats.isCommitted()?null:this.stats}matchesChannelUrl(t){return t===void 0||this.channelUrl===void 0||t===this.channelUrl}pinChannelUrl(t){var n;return t===void 0?!0:this.matchesChannelUrl(t)?(this.channelUrl=t,(n=this.stats)==null||n.setChannelUrl(t),!0):!1}consume(t){return t&&(this.consumed=!0),t}commitIfReady(t){return this.consumed||!this.stats||this.stats.isCommitted()?!0:!this.matchesChannelUrl(t)||!this.apiResultReceived||!this.renderedAfterApiResult?!1:this.consume(this.stats.stopTimer(ge.TOTAL_DURATION).commit())}start(t){const n=this.getOrCreateStats();!n||!this.pinChannelUrl(t)||n.startTimer(ge.TOTAL_DURATION).startTimer(ge.TOTAL_DURATION_FROM_CACHE)}onAuthStart(){var t;this.consumedByAuthError&&this.clear(),(t=this.getOrCreateStats())==null||t.startTimer(ge.AUTH)}onAuthComplete(){var t;(t=this.getActiveStats())==null||t.stopTimer(ge.AUTH)}onAuthError(t){const n=this.getActiveStats();n&&this.consume(n.stopTimer(ge.AUTH).setError(t instanceof de.SendbirdError?t.code:void 0,t.message).stopTimer(ge.TOTAL_DURATION).commit())&&(this.consumedByAuthError=!0)}onGetChannelStart(t){const n=this.getActiveStats();!n||!this.pinChannelUrl(t)||n.startTimer(ge.GET_CHANNEL)}onGetChannelComplete(t){const n=typeof t=="object"?t.channelUrl:void 0,r=typeof t=="object"?t.conversationId:t,s=this.getActiveStats();!s||!this.pinChannelUrl(n)||(s.stopTimer(ge.GET_CHANNEL),r!==void 0&&s.setConversationId(r),s.startTimer(ge.GET_MESSAGES))}onGetChannelError(t){const n=t instanceof Error?void 0:t.channelUrl,r=t instanceof Error?t:t.error,s=this.getActiveStats();s&&this.pinChannelUrl(n)&&this.consume(s.stopTimer(ge.GET_CHANNEL).setError(r instanceof de.SendbirdError?r.code:void 0,r.message).stopTimer(ge.TOTAL_DURATION).commit())}onCacheResult(t){const n=this.getActiveStats();n&&(t&&n.setError(t instanceof de.SendbirdError?t.code:void 0,t.message),n.stopTimer(ge.TOTAL_DURATION_FROM_CACHE))}onApiResult(t){const n=this.getActiveStats();if(n){if(t){this.consume(n.setError(t instanceof de.SendbirdError?t.code:void 0,t.message).stopTimer(ge.TOTAL_DURATION).stopTimer(ge.GET_MESSAGES).commit());return}this.apiResultReceived=!0,this.renderedAfterApiResult=!1,n.stopTimer(ge.GET_MESSAGES),this.commitIfReady()}}setChannelUrl(t){this.pinChannelUrl(t)}commitPending(){const t=this.getActiveStats();return t?this.consume(t.stopTimer(ge.TOTAL_DURATION).commit()):!0}markRendered(t){return this.matchesChannelUrl(t)?(this.renderedAfterApiResult=!0,this.commitIfReady(t)):!1}setPresentMethod(t){var n;this.presentMethod=t,(n=this.getActiveStats())==null||n.setPresentMethod(t)}clear(){this.stats=null,this.apiResultReceived=!1,this.channelUrl=void 0,this.consumed=!1,this.consumedByAuthError=!1,this.renderedAfterApiResult=!1}}const _s=()=>({initialized:!1,listStarted:!1,listCompleted:!1,rendered:!1});class wl{constructor(t,n){v(this,"callback");v(this,"clock");v(this,"measurement",_s());v(this,"renderedCommitted",!1);v(this,"startedAt",null);v(this,"listStartedAt",null);v(this,"authStartedAt",null);v(this,"authDuration",null);v(this,"listDuration",null);v(this,"presentMethod","direct_present");v(this,"committed",!1);this.callback=t,this.clock=It(n)}onInitializeStart(){this.measurement.rendered||(this.measurement.initialized&&this.clearMeasurementState(),this.renderedCommitted=!1,this.startMeasurement())}onListRequestStart(){this.measurement.listStarted&&!this.measurement.listCompleted&&!this.measurement.rendered&&this.clearMeasurementState(),this.markListRequestStartOnce()}onListRequestComplete(){this.markListRequestCompleteOnce()}onRendered(){this.markRenderedOnce()}setPresentMethod(t){this.presentMethod=t}start(t){this.committed||(this.startedAt=this.clock.now(),t&&(this.presentMethod=t))}onAuthStart(){this.committed&&(this.clearMeasurementState(),this.renderedCommitted=!1),this.authDuration=null,this.authStartedAt=this.clock.now()}onAuthComplete(){if(!(this.committed||this.authDuration!==null)){if(this.authStartedAt===null){this.authDuration=0;return}this.authDuration=this.clock.now()-this.authStartedAt,this.authStartedAt=null}}markListRequestStart(){this.committed||(this.startedAt===null&&this.start(),this.listStartedAt=this.clock.now())}markListRequestComplete(){this.committed||this.listStartedAt===null||(this.listDuration=this.clock.now()-this.listStartedAt)}markRendered(){this.committed||this.startedAt===null||(this.committed=!0,et(this.callback,El,this.clock.now()-this.startedAt,{extra:{...this.authDuration!==null&&{auth_duration_ms:this.authDuration},...this.listDuration!==null&&{get_list_duration_ms:this.listDuration},present_method:this.presentMethod}}))}clear(){this.clearMeasurementState(),this.clearAuthState(),this.renderedCommitted=!1}clearMeasurementState(){this.startedAt=null,this.listStartedAt=null,this.listDuration=null,this.committed=!1,this.measurement=_s()}clearAuthState(){this.authStartedAt=null,this.authDuration=null}startMeasurement(){this.measurement.initialized||(this.clearMeasurementState(),this.start(),this.measurement.initialized=!0)}markListRequestStartOnce(){this.startMeasurement(),!this.measurement.listStarted&&(this.markListRequestStart(),this.measurement.listStarted=!0)}markListRequestCompleteOnce(){this.markListRequestStartOnce(),!this.measurement.listCompleted&&(this.markListRequestComplete(),this.measurement.listCompleted=!0)}markRenderedOnce(){this.renderedCommitted||(this.startMeasurement(),!this.measurement.rendered&&(this.markRendered(),this.measurement.rendered=!0,this.renderedCommitted=!0))}}class kl{constructor(t,n){v(this,"callback");v(this,"clock");v(this,"setTimeoutFn");v(this,"clearTimeoutFn");v(this,"measurements",new Map);this.callback=t,this.clock=It(n),this.setTimeoutFn=Yt(n),this.clearTimeoutFn=Wt(n)}start(t){const n=this.getKey(t==null?void 0:t.channelUrl);this.clearKey(n);const r={startedAt:this.clock.now(),channelUrl:t==null?void 0:t.channelUrl,conversationId:t==null?void 0:t.conversationId,committed:!1,inputEnabled:!1,phaseReached:"auth",historyLoadResult:"pending",timer:null};r.timer=this.setTimeoutFn(()=>this.commitTimeout(n),1e4),this.measurements.set(n,r)}markChannelJoined(t,n){const r=this.getMeasurement(n);!r||r.committed||(r.phaseReached="channel_join",t!==void 0&&(r.conversationId=t))}markHistoryLoaded(t,n){const r=this.getMeasurement(n);!r||r.committed||(r.phaseReached="history_load",r.historyLoadResult=t,this.cancelIfReady(n))}markInputEnabled(t){const n=this.getMeasurement(t);!n||n.committed||(n.phaseReached="input_enable",n.inputEnabled=!0,this.cancelIfReady(t))}markRendered(t){const n=this.getMeasurement(t);!n||n.committed||(n.phaseReached="render")}clear(){this.measurements.forEach(t=>Se(t.timer,this.clearTimeoutFn)),this.measurements.clear()}clearChannel(t){t!==void 0&&this.clearKey(this.getKey(t))}clearKey(t){const n=this.measurements.get(t);n&&(Se(n.timer,this.clearTimeoutFn),this.measurements.delete(t))}cancelIfReady(t){const n=this.getMeasurement(t);!n||!n.inputEnabled||n.historyLoadResult==="pending"||this.clearKey(this.getKey(n.channelUrl))}commitTimeout(t){const n=this.measurements.get(t);!n||n.committed||(n.committed=!0,n.timer=null,et(this.callback,gs,this.clock.now()-n.startedAt,{conversationId:n.conversationId,error:{message:gs},extra:{outcome:"timeout",phase_reached:n.phaseReached,history_load_result:n.historyLoadResult}}),this.measurements.delete(t))}getMeasurement(t){return t!==void 0?this.measurements.get(this.getKey(t)):this.measurements.size===1?Array.from(this.measurements.values())[0]:this.measurements.get(this.getKey())}getKey(t){return t??"__default__"}}const Ll=5e3,Es=1e4;class Ol{constructor(t,n){v(this,"callback");v(this,"setTimeoutFn");v(this,"clearTimeoutFn");v(this,"measurements",new Map);this.callback=t,this.setTimeoutFn=Yt(n),this.clearTimeoutFn=Wt(n)}start(t){if(!t.requestId||this.measurements.has(t.requestId))return;const n=t.messageType!=="text"&&t.tracksUploadProgress===!0,r={channelUrl:t.channelUrl,messageType:t.messageType,stuckReason:n?"upload_no_progress":"pending_too_long",timer:null},s=n?Es:Ll;r.timer=this.setTimeoutFn(()=>this.detect(t.requestId),s),this.measurements.set(t.requestId,r)}resolve(t){const n=this.measurements.get(t.requestId);n&&(Se(n.timer,this.clearTimeoutFn),this.measurements.delete(t.requestId))}disappear(t){const n=this.measurements.get(t.requestId);n&&(Se(n.timer,this.clearTimeoutFn),this.measurements.delete(t.requestId))}markUploadProgress(t){const n=this.measurements.get(t);n&&n.stuckReason==="upload_no_progress"&&(Se(n.timer,this.clearTimeoutFn),n.timer=this.setTimeoutFn(()=>this.detect(t),Es))}clear(){this.measurements.forEach(t=>Se(t.timer,this.clearTimeoutFn)),this.measurements.clear()}clearChannel(t){t&&this.measurements.forEach((n,r)=>{n.channelUrl===t&&(Se(n.timer,this.clearTimeoutFn),this.measurements.delete(r))})}detect(t){const n=this.measurements.get(t);n&&(this.measurements.delete(t),this.commit(t,n))}commit(t,n){et(this.callback,Cl,n.stuckReason,{extra:{message_type:n.messageType,request_id:t}})}}class Nl{constructor(t,n){v(this,"callback");v(this,"clock");v(this,"setTimeoutFn");v(this,"clearTimeoutFn");v(this,"measurements",new Map);this.callback=t,this.clock=It(n),this.setTimeoutFn=Yt(n),this.clearTimeoutFn=Wt(n)}start(t,n){const r=this.getKey(n);let s=this.measurements.get(r);s&&s.startedAt!==null||s!=null&&s.inputEnabled||(s={startedAt:this.clock.now(),triggerType:t,inputEnabled:(s==null?void 0:s.inputEnabled)??!1,timer:this.setTimeoutFn(()=>this.commitTimeout(r),1e4)},this.measurements.set(r,s))}setInputEnabled(t,n){const r=this.getKey(n);let s=this.measurements.get(r);if(!s){if(!t)return;s={startedAt:null,triggerType:null,inputEnabled:t,timer:null},this.measurements.set(r,s)}s.inputEnabled=t,t&&this.cancelMeasurement(s)}cancelPending(t){const n=this.getKey(t),r=this.measurements.get(n);r&&(this.cancelMeasurement(r),r.inputEnabled||this.measurements.delete(n))}clear(){this.measurements.forEach(t=>Se(t.timer,this.clearTimeoutFn)),this.measurements.clear()}clearChannel(t){t!==void 0&&this.clearKey(this.getKey(t))}clearKey(t){const n=this.measurements.get(t);n&&(Se(n.timer,this.clearTimeoutFn),this.measurements.delete(t))}commitTimeout(t){const n=this.measurements.get(t);if(!n||n.startedAt===null||n.triggerType===null)return;if(n.inputEnabled){this.cancelMeasurement(n);return}const r=this.clock.now()-n.startedAt,s=n.triggerType;this.measurements.delete(t),et(this.callback,_l,r,{extra:{trigger_type:s}})}cancelMeasurement(t){Se(t.timer,this.clearTimeoutFn),t.timer=null,t.startedAt=null,t.triggerType=null}getKey(t){return t??"__default__"}}const Dl=500;class $l{constructor(t){v(this,"callback");v(this,"committed",new Set);this.callback=t}commit(t){const n=`${t.messageId}:${t.contentKind}:${t.errorDomain}`;this.committed.has(n)||(On(this.committed,Dl),this.committed.add(n),et(this.callback,Sl,t.errorDomain,{error:t.error?{code:t.error.code,message:t.errorDomain}:void 0,extra:{content_kind:t.contentKind,message_id:String(t.messageId)}}))}clear(){this.committed.clear()}}const Cs=1e4,Ct=5e3,Fl=500;class Pl{constructor(t,n){v(this,"callback");v(this,"clock");v(this,"setTimeoutFn");v(this,"clearTimeoutFn");v(this,"streams",new Map);v(this,"emittedMessageChannels",new Map);this.callback=t,this.clock=It(n),this.setTimeoutFn=Yt(n),this.clearTimeoutFn=Wt(n)}markRawProgress(t){if(!t.aiResponse.isStreaming){this.completeDelivery(t.messageId,t.textLength);return}if(this.emittedMessageChannels.has(t.messageId))return;const n=this.getOrCreate(t.messageId,t.channelUrl);t.textLength>n.lastRawLength?(n.chunksReceived+=1,n.lastRawLength=t.textLength,n.lastRawAt=this.clock.now(),Se(n.deliveryTimer,this.clearTimeoutFn),n.deliveryTimer=null,this.scheduleDeliveryStallCheck(t.messageId,n)):this.scheduleDeliveryStallCheck(t.messageId,n),n.lastRenderedLength<n.lastRawLength&&n.renderTimer===null&&(n.lastRenderAt=this.clock.now(),this.scheduleRenderStallCheck(t.messageId,n,Ct))}markRenderedProgress(t){const n=this.streams.get(t.messageId);if(!(!n||t.displayedLength<=n.lastRenderedLength)){if(n.lastRenderedLength=t.displayedLength,n.lastRenderAt=this.clock.now(),n.lastRenderedLength>=n.lastRawLength){if(n.deliveryTimer===null){this.clearStream(t.messageId,n);return}Se(n.renderTimer,this.clearTimeoutFn),n.renderTimer=null;return}this.scheduleRenderStallCheck(t.messageId,n,Ct)}}hasPendingStream(t){return this.streams.has(t)}complete(t){const n=this.streams.get(t);n&&this.clearStream(t,n)}completeDelivery(t,n){const r=this.streams.get(t);if(r){if(n>r.lastRawLength&&(r.lastRawLength=n,r.lastRawAt=this.clock.now()),Se(r.deliveryTimer,this.clearTimeoutFn),r.deliveryTimer=null,r.lastRenderedLength>=r.lastRawLength){this.clearStream(t,r);return}r.renderTimer===null&&(r.lastRenderAt=this.clock.now(),this.scheduleRenderStallCheck(t,r,Ct))}}clearMessage(t){const n=this.streams.get(t);n&&this.clearStream(t,n),this.emittedMessageChannels.delete(t)}clear(){this.streams.forEach(t=>{Se(t.deliveryTimer,this.clearTimeoutFn),Se(t.renderTimer,this.clearTimeoutFn)}),this.streams.clear(),this.emittedMessageChannels.clear()}clearChannel(t){t&&(this.streams.forEach((n,r)=>{n.channelUrl!==t&&n.channelUrl!==void 0||this.clearStream(r,n)}),this.emittedMessageChannels.forEach((n,r)=>{(n===t||n===void 0)&&this.emittedMessageChannels.delete(r)}))}detectDelivery(t){const n=this.streams.get(t);n&&(n.deliveryTimer=null,Se(n.renderTimer,this.clearTimeoutFn),n.renderTimer=null,this.emit(t,n,"delivery"))}detectRender(t){const n=this.streams.get(t);if(!n||(n.renderTimer=null,n.lastRenderedLength>=n.lastRawLength))return;const r=this.clock.now()-n.lastRenderAt;if(r<Ct){this.scheduleRenderStallCheck(t,n,Ct-r);return}const s=this.clock.now()-n.lastRawAt;if(s>=Ct&&n.deliveryTimer!==null){const o=Cs-s;if(o>0){this.scheduleRenderStallCheck(t,n,o);return}}this.emit(t,n,"render")}scheduleRenderStallCheck(t,n,r){n.renderTimer===null&&(n.renderTimer=this.setTimeoutFn(()=>this.detectRender(t),r))}scheduleDeliveryStallCheck(t,n){n.deliveryTimer===null&&(n.deliveryTimer=this.setTimeoutFn(()=>this.detectDelivery(t),Cs))}emit(t,n,r){if(this.emittedMessageChannels.has(t))return;const s=r==="delivery"?n.lastRawAt:n.lastRenderAt;et(this.callback,vl,this.clock.now()-s,{extra:{message_id:String(t),stall_kind:r}}),this.rememberEmitted(t,n.channelUrl),this.clearStream(t,n)}getOrCreate(t,n){const r=this.streams.get(t);if(r)return r;const s=this.clock.now(),o={channelUrl:n,chunksReceived:0,lastRawAt:s,lastRenderAt:s,lastRawLength:0,lastRenderedLength:0,deliveryTimer:null,renderTimer:null};return this.streams.set(t,o),o}rememberEmitted(t,n){this.emittedMessageChannels.has(t)||On(this.emittedMessageChannels,Fl),this.emittedMessageChannels.set(t,n)}clearStream(t,n){Se(n.deliveryTimer,this.clearTimeoutFn),Se(n.renderTimer,this.clearTimeoutFn),this.streams.delete(t)}}const bs=3e3,Ul=3e4;class Bl{constructor(t,n){v(this,"callback");v(this,"clock");v(this,"setTimeoutFn");v(this,"clearTimeoutFn");v(this,"turns",new Map);v(this,"pendingAIResponseStartsByUserMessageId",new Map);this.callback=t,this.clock=It(n),this.setTimeoutFn=Yt(n),this.clearTimeoutFn=Wt(n)}startTurn(t){this.cancelTurn(t.requestId);const n={requestId:t.requestId,channelUrl:t.channelUrl,beforeTpstStartedAt:this.clock.now(),afterTpenStartedAt:null,timer:null};n.timer=this.setTimeoutFn(()=>this.commitTimeout(n.requestId),Ul),this.turns.set(t.requestId,n)}markUserMessageAck(t){const n=this.turns.get(t.requestId);if(!n)return;n.userMessageId=t.messageId;const r=this.pendingAIResponseStartsByUserMessageId.get(t.messageId);r&&(this.pendingAIResponseStartsByUserMessageId.delete(t.messageId),this.applyAIResponseStarted({channelUrl:r.channelUrl,matchesUserMessage:!0,userMessageId:t.messageId},r.startedAt))}replaceTurnRequestId(t,n){if(t===n)return;const r=this.turns.get(t);r&&(this.turns.delete(t),r.requestId=n,this.turns.set(n,r))}cancelTurn(t){this.cleanupTurn(t)}markTypingStarted(t){const n=this.clock.now();this.turns.forEach(r=>{mt(r,t)&&(this.recordAfterTpen(r,n),this.recordBeforeTpst(r,n))})}markTypingEnded(t){const n=this.clock.now();this.turns.forEach(r=>{mt(r,t)&&(this.recordBeforeTpst(r,n),r.afterTpenStartedAt=n)})}markAIResponseStarted(t={}){const n=t.channelUrl,r=t.userMessageId,s=r!==void 0,o=this.clock.now();this.applyAIResponseStarted({channelUrl:n,matchesUserMessage:s,userMessageId:r},o)||!s||r===void 0||!this.hasUnackedTurn(n)||this.pendingAIResponseStartsByUserMessageId.has(r)||(On(this.pendingAIResponseStartsByUserMessageId,100),this.pendingAIResponseStartsByUserMessageId.set(r,{channelUrl:n,startedAt:o}))}applyAIResponseStarted(t,n){if(!t.matchesUserMessage){const s=this.findSingleTurn(t.channelUrl);return s?(this.completeTurn(s.requestId,s.turn,n),!0):!1}let r=!1;return this.turns.forEach((s,o)=>{mt(s,t.channelUrl)&&(t.matchesUserMessage&&s.userMessageId!==t.userMessageId||(r=!0,this.completeTurn(o,s,n)))}),r}findSingleTurn(t){let n,r=0;return this.turns.forEach((s,o)=>{mt(s,t)&&(r+=1,!(r>1)&&(n={requestId:o,turn:s}))}),r===1?n:void 0}completeTurn(t,n,r){this.recordBeforeTpst(n,r),this.recordAfterTpen(n,r),this.commitIfAbsent(t,n)}hasUnackedTurn(t){return di(this.turns.values(),t)}clear(){this.turns.forEach(t=>{Se(t.timer,this.clearTimeoutFn)}),this.turns.clear(),this.pendingAIResponseStartsByUserMessageId.clear()}clearChannel(t){t&&(this.turns.forEach((n,r)=>{n.channelUrl===t&&this.cleanupTurn(r)}),this.pendingAIResponseStartsByUserMessageId.forEach((n,r)=>{n.channelUrl===t&&this.pendingAIResponseStartsByUserMessageId.delete(r)}))}commitTimeout(t){const n=this.turns.get(t);if(!n)return;const r=this.clock.now();this.recordBeforeTpst(n,r),this.recordAfterTpen(n,r),this.commitIfAbsent(t,n)}recordBeforeTpst(t,n){if(t.beforeTpstStartedAt===null)return;const r=n-t.beforeTpstStartedAt;r>=bs&&(t.beforeTpstAbsentMs=r),t.beforeTpstStartedAt=null}recordAfterTpen(t,n){if(t.afterTpenStartedAt===null)return;const r=n-t.afterTpenStartedAt;r>=bs&&(t.afterTpenAbsentMs=r),t.afterTpenStartedAt=null}commitIfAbsent(t,n){const r=n.beforeTpstAbsentMs,s=n.afterTpenAbsentMs;if(r===void 0&&s===void 0){this.cleanupTurn(t);return}et(this.callback,yl,(r??0)+(s??0),{extra:{...r!==void 0&&{before_tpst_absent_ms:r},...s!==void 0&&{after_tpen_absent_ms:s}}}),this.cleanupTurn(t)}cleanupTurn(t){const n=this.turns.get(t);n&&(Se(n.timer,this.clearTimeoutFn),this.turns.delete(t))}}class Hl{constructor(t,n){v(this,"callback");v(this,"clock");v(this,"random");v(this,"sampledByRequestId",new Map);v(this,"sampledByAIMessageId",new Map);v(this,"pendingAIResponseByUserMessageId",new Map);v(this,"collectedCount",0);this.callback=t,this.clock=It(n),this.random=(n==null?void 0:n.random)??Math.random}startTurn(t){this.collectedCount>=10||this.random()>=.15||(this.collectedCount+=1,this.sampledByRequestId.set(t.requestId,{requestId:t.requestId,channelUrl:t.channelUrl,startedAt:this.clock.now()}))}markUserMessageAck(t){const n=this.sampledByRequestId.get(t.requestId);if(!n)return;n.ackAt=this.clock.now(),n.userMessageId=t.messageId;const r=this.pendingAIResponseByUserMessageId.get(t.messageId);r&&(this.pendingAIResponseByUserMessageId.delete(t.messageId),this.applyAIResponseRaw(n,r))}replaceTurnRequestId(t,n){if(t===n)return;const r=this.sampledByRequestId.get(t);r&&(this.sampledByRequestId.delete(t),r.requestId=n,this.sampledByRequestId.set(n,r))}cancelTurn(t){const n=this.sampledByRequestId.get(t);n&&(this.deleteTurn(n),this.collectedCount>0&&(this.collectedCount-=1))}markAIResponseRaw(t){const n=this.clock.now(),r=t.aiResponse.userMessageId;if(r===void 0&&this.hasUnackedTurn(t.channelUrl))return;const s=this.findPendingTurn(t.channelUrl,r);if(s){this.applyAIResponseRaw(s,{...t,firstChunkAt:n});return}r===void 0||!this.hasUnackedTurn(t.channelUrl)||this.bufferAIResponseRaw({messageId:t.messageId,...t.channelUrl!==void 0&&{channelUrl:t.channelUrl},aiResponse:t.aiResponse,firstChunkAt:n},r)}markAIResponseVisible(t){const n=this.sampledByAIMessageId.get(t);if(!n||n.ackAt===void 0||n.firstChunkAt===void 0||n.userMessageId===void 0)return!1;const r=this.clock.now();return et(this.callback,bl,r-n.startedAt,{extra:{ack_to_first_chunk_ms:n.firstChunkAt-n.ackAt,first_chunk_to_render_ms:r-n.firstChunkAt,is_streaming:!!n.isStreaming,send_to_ack_ms:n.ackAt-n.startedAt}}),this.deleteTurn(n),!0}hasPendingAIResponse(t){return this.sampledByAIMessageId.has(t)}clearMessage(t){this.pendingAIResponseByUserMessageId.forEach((r,s)=>{r.messageId===t&&this.pendingAIResponseByUserMessageId.delete(s)});const n=this.sampledByAIMessageId.get(t);n&&(this.deleteTurn(n),this.collectedCount>0&&(this.collectedCount-=1))}clearChannel(t){t&&(this.sampledByRequestId.forEach(n=>{n.channelUrl===t&&(this.deleteTurn(n),this.collectedCount>0&&(this.collectedCount-=1))}),this.pendingAIResponseByUserMessageId.forEach((n,r)=>{n.channelUrl===t&&this.pendingAIResponseByUserMessageId.delete(r)}))}clear(){this.sampledByRequestId.clear(),this.sampledByAIMessageId.clear(),this.pendingAIResponseByUserMessageId.clear(),this.collectedCount=0}findPendingTurn(t,n){if(n!==void 0){for(const s of this.sampledByRequestId.values())if(!(s.ackAt===void 0||s.firstChunkAt!==void 0)&&mt(s,t)&&s.userMessageId===n)return s;return}let r;for(const s of this.sampledByRequestId.values())if(!(s.ackAt===void 0||s.firstChunkAt!==void 0)&&mt(s,t)){if(r)return;r=s}return r}applyAIResponseRaw(t,n){t.firstChunkAt===void 0&&(t.firstChunkAt=t.ackAt===void 0?n.firstChunkAt:Math.max(n.firstChunkAt,t.ackAt),t.aiMessageId=n.messageId,t.channelUrl=t.channelUrl??n.channelUrl,t.isStreaming=n.aiResponse.isStreaming,this.sampledByAIMessageId.set(n.messageId,t))}bufferAIResponseRaw(t,n){this.pendingAIResponseByUserMessageId.has(n)||(On(this.pendingAIResponseByUserMessageId,100),this.pendingAIResponseByUserMessageId.set(n,t))}hasUnackedTurn(t){return di(this.sampledByRequestId.values(),t)}deleteTurn(t){this.sampledByRequestId.delete(t.requestId),t.aiMessageId!==void 0&&this.sampledByAIMessageId.delete(t.aiMessageId),t.userMessageId!==void 0&&this.pendingAIResponseByUserMessageId.delete(t.userMessageId)}}function Gl(){let e=null,t=0;const n=(r,s)=>{if((e==null?void 0:e.key)===r)return e.promise;const o=++t,c=(e?e.promise.catch(()=>{}).then(()=>s()):s()).finally(()=>{(e==null?void 0:e.id)===o&&(e=null)});return e={key:r,id:o,promise:c},c};return n.isPending=()=>e!==null,n}const mi=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0)),vs={isTalkToAgentViewEnabled:!0,scrollMode:"auto",newMessageIndicatorEnabled:!0,senderAvatarEnabled:!0},kr={conversation:{...vs,messageAlertSoundEnabled:!1,list:{...vs,deferredMarkdownElements:[]},header:{avatarEnabled:!0},input:{camera:{photoEnabled:!0},gallery:{photoEnabled:!0},fileEnabled:!0},fileViewer:{downloadEnabled:!0}},launcher:{unreadBadgeEnabled:!1}},ys=e=>e?{conversation:ql(e.conversation),launcher:zl(e.launcher)}:kr,zl=e=>vt(kr.launcher,e),Vl=e=>{if(e.deferredMarkdownElements)return[...e.deferredMarkdownElements];const t=[];return e.markdownImageRenderMode==="complete-only"&&t.push("image"),e.markdownLinkRenderMode==="complete-only"&&t.push("link"),t},ql=e=>{const t=kr.conversation;if(!e)return t;const{list:n={},header:r={},input:s,fileViewer:o={},messageAlertSoundEnabled:i=t.messageAlertSoundEnabled,...c}=e,{camera:u={},gallery:d={},fileEnabled:m=t.input.fileEnabled}=s??{},h={...vt(t.list,c,n),deferredMarkdownElements:Vl(n)};return{...h,messageAlertSoundEnabled:i,list:h,header:vt(t.header,r),input:{camera:vt(t.input.camera,u),gallery:vt(t.input.gallery,d),fileEnabled:m},fileViewer:vt(t.fileViewer,o)}},vt=(e,...t)=>{const n={...e};for(const r of t)r&&Object.assign(n,mi(r));return n},Kl=e=>({userId:e.bot_userid,profileUrl:e.bot_profile_url,nickname:e.bot_nickname,replyToFile:e.reply_to_file,specialNotice:e.special_notice,specialNoticeEnabled:e.is_special_notice_enabled,showHandoffButton:e.show_handoff_button??!0,isMultipleActiveConversationsEnabled:e.is_multiple_active_conversations_enabled??!0,isUserFeedbackEnabled:e.is_user_feedback_enabled??!1,isUserFeedbackCommentOptionEnabled:e.is_user_feedback_comment_option_enabled??!1}),Yl=e=>({type:e.image_type||"default_icon",imageUrl:e.image_url}),dr=e=>({enabled:e.enabled,showIndicator:e.show_indicator,toggleAllowed:e.toggle_allowed,deleteOnOff:e.delete_on_off,consentDialog:e.consent_dialog});class Wl{constructor(){v(this,"_channelHandlerId",null);v(this,"_connectionHandlerId",null);v(this,"_initConversationRequests",new Map);v(this,"_handleActiveChannelChangedThrottled",null);v(this,"_setupChannelHandler",()=>{const t=Date.now();this._channelHandlerId=`aiagent_channel_${t}`,this._connectionHandlerId=`aiagent_connection_${t}`,this._handleActiveChannelChangedThrottled=ti(s=>{var o,i;(i=this._session)==null||i._updateActiveChannel({url:s.url,status:He(s)?"closed":"open",conversationStatus:(o=s.conversation)==null?void 0:o.status}),this._logger.debug("AIAgentEventManager: activeChannel updated",s.url)},250,{leading:!0,trailing:!1});const n=new We.GroupChannelHandler({onChannelChanged:s=>{var o,i;s.isGroupChannel()&&s.url===((o=this._session)==null?void 0:o.activeChannel.url)&&((i=this._handleActiveChannelChangedThrottled)==null||i.call(this,s))}}),r=new de.ConnectionHandler({onReconnectSucceeded:async()=>{await this._syncActiveChannelOnReconnect()}});this._chatClient.chatSDK.groupChannel.addGroupChannelHandler(this._channelHandlerId,n),this._chatClient.chatSDK.addConnectionHandler(this._connectionHandlerId,r),this._logger.debug("AIAgentEventManager: handlers registered",{channelHandlerId:this._channelHandlerId,connectionHandlerId:this._connectionHandlerId})});v(this,"_removeChannelHandler",()=>{this._channelHandlerId&&(this._chatClient.chatSDK.groupChannel.removeGroupChannelHandler(this._channelHandlerId),this._channelHandlerId=null),this._connectionHandlerId&&(this._chatClient.chatSDK.removeConnectionHandler(this._connectionHandlerId),this._connectionHandlerId=null),this._handleActiveChannelChangedThrottled&&(this._handleActiveChannelChangedThrottled.cancel(),this._handleActiveChannelChangedThrottled=null),this._logger.debug("AIAgentEventManager: handlers removed")});v(this,"_syncActiveChannelOnReconnect",async()=>{var n,r,s;const t=(n=this._session)==null?void 0:n.activeChannel.url;if(t)try{const i=await(await this._chatClient.chatSDK.groupChannel.getChannel(t)).refresh();i.url===t&&((s=this._session)==null||s._updateActiveChannel({url:i.url,status:He(i)?"closed":"open",conversationStatus:(r=i.conversation)==null?void 0:r.status}),this._logger.debug("AIAgentEventManager: activeChannel synced on reconnect",i.url))}catch(o){this._logger.error("AIAgentEventManager: failed to sync activeChannel on reconnect",o)}});v(this,"_initConversationIfNeeded",t=>{if(!t.isAIAgent||t.conversation)return Promise.resolve();const n=this._initConversationRequests.get(t.url);if(n)return n;const r=t.initConversation({aiAgentId:this.aiAgentId}).then(()=>{}).catch(s=>{this._logger.warn("AIAgentEventManager: initConversation failed",s)}).finally(()=>{this._initConversationRequests.delete(t.url)});return this._initConversationRequests.set(t.url,r),r});v(this,"onMessengerSettingsUpdated",t=>(this._dispatcher.subscribe(Ke.MessengerSettingsUpdated,t),()=>{this._dispatcher.unsubscribe(Ke.MessengerSettingsUpdated,t)}));v(this,"onActiveChannelUpdated",t=>(this._dispatcher.subscribe(Ke.ActiveChannelUpdated,t),()=>{this._dispatcher.unsubscribe(Ke.ActiveChannelUpdated,t)}));v(this,"onAuthTokenRefreshed",t=>(this._dispatcher.subscribe(Ke.AuthTokenRefreshed,t),()=>{this._dispatcher.unsubscribe(Ke.AuthTokenRefreshed,t)}))}}class jl{constructor(t){v(this,"_sdkUser");v(this,"_userSession");v(this,"_dispatcher");v(this,"_activeChannel");v(this,"_updateActiveChannel",t=>{this._activeChannel=t,this._dispatcher.send(ct.ActiveChannelUpdated({channelUrl:t.url,status:t.status,conversationStatus:t.conversationStatus}))});v(this,"_updateAuthToken",t=>{this._userSession.authToken=t,this._dispatcher.send(ct.AuthTokenRefreshed())});this._sdkUser=t.sdkUser,this._userSession=t.userSession,this._dispatcher=t.dispatcher,this._activeChannel=t.activeChannel}get sdkUser(){return this._sdkUser}get userSession(){return this._userSession}get activeChannel(){return this._activeChannel}}const hi=e=>{try{const t=JSON.parse(e);return typeof t=="string"?JSON.stringify(t).slice(1,-1):e.trim()}catch{return JSON.stringify(e).slice(1,-1)}},fi=e=>JSON.parse(e),Xl=e=>JSON.parse(e);function Zl(e,t){const[n,r]=t.split(",").map(s=>s.trim());return e==="dark"&&r||n}function Jl(e){const t={};function n(r,s=""){for(const[o,i]of Object.entries(r)){const c=s?`${s}.${o}`:o;i&&typeof i=="object"&&!Array.isArray(i)?n(i,c):t[c]=i}}return n(e),t}function Ql({template:e,variables:t,variableKeyPattern:n,variableValueTransformer:r}){return Object.entries(t).reduce((s,[o,i])=>{if(!r&&!["number","boolean","string"].includes(typeof i))throw new Error(`If transformer is not provided, value(${o}:${i}) must be a {string, number, or boolean}`);const c=r?r(i):String(i),u=n(o);return s.replace(u,hi(c))},e)}async function eu({template:e,variables:t,variableKeyPattern:n,variableValueTransformer:r}){return(await Promise.all(Object.entries(t).map(async([o,i])=>{const c=await r(i);return{regex:n(o),transformedValue:c}}))).reduce((o,{regex:i,transformedValue:c})=>o.replace(i,hi(c)),e)}var Lr=(e=>(e[e.EXTERNAL_AUTH_TOKEN_EXPIRED=1]="EXTERNAL_AUTH_TOKEN_EXPIRED",e))(Lr||{});const gi=e=>typeof e=="object"&&e!==null,Ss=(e,t)=>t in e&&typeof e[t]=="string"&&e[t]!=="",tu=e=>!gi(e)||!Ss(e,"channel_url")||!Ss(e,"ai_agent_id")?null:{channelUrl:e.channel_url,aiAgentId:e.ai_agent_id},nu={1:tu};function ru(e){if(!gi(e)||!("cat"in e)||typeof e.cat!="number"||!("data"in e))return null;const t=e.cat,n=nu[t];if(!n)return null;const r=n(e.data);return r?{category:t,data:r}:null}function su(e,t,n,r){const s=fc.default.init({appId:e,modules:[new We.GroupChannelModule,new me.AIAgentModule],localCacheEnabled:!0,options:new de.SendbirdChatOptions({typingIndicatorInvalidateTime:2e4}),...r,customApiHost:(r==null?void 0:r.customApiHost)??`https://api-${e}.app.delight.ai`,customWebSocketHost:(r==null?void 0:r.customWebSocketHost)??`wss://ws-${e}.app.delight.ai`});return s.addSendbirdExtensions([{version:n,product:de.SendbirdProduct.AI_AGENT,platform:t.platform}],{platform:t.deviceOSPlatform,version:t.deviceOSVersion},t.customData)||console.warn("Invalid Sendbird Extensions",t),s}function ou(e){const t=n=>{throw new Error(`Please initialize chat sdk with ${n}`)};typeof e.groupChannel!="object"&&t("GroupChannelModule"),typeof e.aiAgent!="object"&&t("AIAgentModule")}const iu=[400300,400301,400302,400310],au=Lr.EXTERNAL_AUTH_TOKEN_EXPIRED.toString(),cu=e=>`${au}:${e}`;class Or{constructor(t,n,r,s,o){v(this,"chatSDK");v(this,"_aiAgentId");v(this,"_externalAuthTokenExpiredEventHandlerKey");v(this,"_logger");v(this,"_cache");v(this,"_statsTrackers");v(this,"_sessionHandler");v(this,"_aiEventHandlerRegistered",!1);v(this,"connect",async(t,n,r,s)=>{if(this._logger.debug("ChatClient.connect: start",t.userId),n){this._sessionHandler=n;const o=new de.SessionHandler({...n,onSessionTokenRequired:this._interceptTokenRefresh(n.onSessionTokenRequired,r,s)});this.chatSDK.setSessionHandler(o)}this._registerAIEventHandler();try{return await this.chatSDK.connect(t.userId,t.authToken),await this._syncTemplatesIfNeeded(),this._logger.debug("ChatClient.connect: end",this.chatSDK.currentUser),this.chatSDK.currentUser}catch(o){const i=o;if(this.chatSDK.isCacheEnabled){if(this._isCacheRestrictedError(i))this._logger.warn("ChatClient.connect","offline connect restricted",i.message,i.code),this._logger.warn("ChatClient.connect","clear cached-data"),await this.chatSDK.clearCachedData().catch(c=>this._logger.warn("ChatClient.connect","clear cached-data failure",c));else if(this.chatSDK.currentUser)return this._logger.debug("ChatClient.connect: end (offline)",this.chatSDK.currentUser),this.chatSDK.currentUser}throw this._logger.warn("ChatClient.connect","connect failure",i.message,i.code),this.dispose(),i}});v(this,"_registerAIEventHandler",()=>{this._aiEventHandlerRegistered||(this._aiEventHandlerRegistered=!0,this.chatSDK.aiAgent.addEventHandler(this._externalAuthTokenExpiredEventHandlerKey,this._handleAIEvent))});v(this,"_handleAIEvent",t=>{var o;this._logger.debug("ChatClient.connect: EXTERNAL_AUTH_TOKEN_EXPIRED event received",t);const n=ru(t),r=typeof t.cat=="number"?t.cat:void 0;if(r!==void 0&&r!==Lr.EXTERNAL_AUTH_TOKEN_EXPIRED)return;if(!n){this._statsTrackers.aievAuthExpiredUnhandled.onPayloadParseFailed({aiAgentId:this._aiAgentId});return}if(n.data.aiAgentId!==this._aiAgentId){this._logger.debug("ChatClient.connect: ignore EXTERNAL_AUTH_TOKEN_EXPIRED for another agent",n.data);return}const s=(o=this._sessionHandler)==null?void 0:o.onExternalAuthTokenExpired;if(!s){this._statsTrackers.aievAuthExpiredUnhandled.onCallbackNotFound(n.data);return}this._logger.debug("ChatClient.connect: calling onExternalAuthTokenExpired handler",n.data),s(n.data)});v(this,"dispose",()=>{this._aiEventHandlerRegistered&&(this.chatSDK.aiAgent.removeEventHandler(this._externalAuthTokenExpiredEventHandlerKey),this._aiEventHandlerRegistered=!1),this._sessionHandler=void 0});v(this,"disconnect",async()=>{this._logger.debug("ChatClient.disconnect: start"),this.dispose(),await this.chatSDK.disconnect(),this._cache.template.clear(),this._logger.debug("ChatClient.disconnect: end")});v(this,"getChannel",async t=>this.chatSDK.groupChannel.getChannel(t));v(this,"patchContext",async(t,n,r)=>this.chatSDK.aiAgent.patchContext(t,n,r));v(this,"updateContext",async(t,n,r)=>this.chatSDK.aiAgent.updateContext(t,n,r));v(this,"requestMessengerSettings",async t=>{var s;if(t.userId===""){const o=new Error("userId cannot be empty string for messenger settings request");throw this._logger.error("ChatClient.requestMessengerSettings: invalid userId",o),o}const n={...t,shouldSendFirstMessage:!1};this._logger.debug("ChatClient.requestMessengerSettings: requesting",n);const r=await this.chatSDK.aiAgent.requestMessengerSettings(n);return this._logger.debug("ChatClient.requestMessengerSettings: received",(s=r.active_channel)==null?void 0:s.channel_url),r});v(this,"setUserMemoryState",async t=>{this._logger.debug("ChatClient.setUserMemoryState: requesting",t);const n=await this.chatSDK.aiAgent.setUserMemoryState(t);return this._logger.debug("ChatClient.setUserMemoryState: received",n.enabled),n});v(this,"clearUserMemories",async(t={})=>{this._logger.debug("ChatClient.clearUserMemories: requesting",t),await this.chatSDK.aiAgent.clearUserMemories(t),this._logger.debug("ChatClient.clearUserMemories: completed")});v(this,"_interceptTokenRefresh",(t,n,r)=>{if(t)return async(s,o)=>{new Promise((i,c)=>t==null?void 0:t(i,c)).then(i=>{i?n==null||n(i):r==null||r(),s(i)}).catch(i=>{r==null||r(),o(i)})}});v(this,"_isCacheRestrictedError",t=>iu.some(n=>t.code===n));v(this,"_syncTemplatesIfNeeded",async()=>{var r,s;const t=(s=(r=this.chatSDK.appInfo)==null?void 0:r.aiAgentInfo)==null?void 0:s.templateListToken;if(!t)return;const n=this._cache.template.getCachedToken();if(!(n&&n===t)){this._logger.debug("ChatClient._syncTemplatesIfNeeded: syncing templates");try{const{templates:o,token:i}=await this.chatSDK.aiAgent.getMessageTemplates({limit:20});for(const{template:c}of o){const{key:u}=fi(c);this._cache.template.set(u,c)}this._cache.template.setCachedToken(i),this._logger.debug("ChatClient._syncTemplatesIfNeeded: sync completed")}catch(o){this._logger.error("ChatClient._syncTemplatesIfNeeded: error",o)}}});this.chatSDK=t,this._aiAgentId=n,this._externalAuthTokenExpiredEventHandlerKey=cu(n),this._logger=r,this._cache=s,this._statsTrackers=o}static init(t){let n;return t.chatSDK?(ou(t.chatSDK),n=t.chatSDK):n=su(t.appId,t.extensions,t.messengerVersion,t.chatParams),new Or(n,t.aiAgentId,t.logger,t.cache,t.statsTrackers)}}const rn=new Map,pi={set:(e,t)=>{rn.set(e,t)},get:e=>{if(rn.size===0)throw new Error("AIAgent platform not configured. Ensure you are using the correct package (@sendbird/ai-agent-messenger-react or @sendbird/ai-agent-messenger-react-native).");if(e){const n=rn.get(e);if(!n)throw new Error(`AIAgent platform "${e}" is not configured.`);return{platform:e,...n}}const t=rn.entries().next().value;return{platform:t[0],...t[1]}}};class As extends Error{constructor(n,r){const s=(r==null?void 0:r.detail)??"";super(s||`Desk API error (${n})`);v(this,"status");v(this,"code");v(this,"detail");this.name="DeskApiError",this.status=n,this.code=(r==null?void 0:r.code)??"",this.detail=s}}var Nr=(e=>(e.INITIALIZED="INITIALIZED",e.PROACTIVE="PROACTIVE",e.PENDING="PENDING",e.ACTIVE="ACTIVE",e.CLOSED="CLOSED",e.WORK_IN_PROGRESS="WORK_IN_PROGRESS",e.IDLE="IDLE",e))(Nr||{}),Dr=(e=>(e.URGENT="URGENT",e.HIGH="HIGH",e.MEDIUM="MEDIUM",e.LOW="LOW",e))(Dr||{}),_i=(e=>(e.ERR_CREDENTIALS_NOT_PROVIDED="desk401100",e.ERR_NON_AUTHORIZED="desk401103",e.ERR_SESSION_KEY_EXPIRED="desk401106",e.ERR_SESSION_TOKEN_REVOKED="desk401107",e.ERR_USER_DEACTIVATED="desk401108",e.ERR_USER_NOT_EXIST="desk401109",e))(_i||{});const lu=e=>e==="desk401103"||e==="desk401106"||e==="desk401107"||e==="desk401108"||e==="desk401109";class uu{constructor(t){v(this,"_appId");v(this,"_apiHost");v(this,"_logger");v(this,"_credential",null);v(this,"_authRefreshPromise",null);v(this,"_onDeskTokenRefreshRequired",async()=>!1);v(this,"request",async(t,n)=>{const r=n.authRequired??!0,s=`${this._apiHost}${t}`;r&&this._authRefreshPromise&&(this._logger.debug("DeskApiClient: waiting for in-flight recovery..."),await this._authRefreshPromise);const o=await this._fetch(s,n);return r&&o.status===401?this._handleUnauthorized(o,s,n):this._toResult(o)});v(this,"setCredential",(t,n=async()=>!1)=>{this._authRefreshPromise=null,this._onDeskTokenRefreshRequired=n,this._credential=t});v(this,"clearCredential",()=>{this._authRefreshPromise=null,this._credential=null,this._onDeskTokenRefreshRequired=async()=>!1});v(this,"_handleUnauthorized",async(t,n,r)=>{const s=await this._parseErrorCode(t);if(!lu(s))return this._toResult(t);if(!await this._refresh(s)||this._credential===null)return this._toResult(t);const i=await this._fetch(n,r);return this._toResult(i)});v(this,"_refresh",async t=>{if(this._authRefreshPromise)return this._logger.debug("DeskApiClient: refresh already in progress, joining..."),this._authRefreshPromise;try{return this._authRefreshPromise=this._onDeskTokenRefreshRequired({reason:t}).catch(n=>(this._logger.error("DeskApiClient: delegated recovery failed",n),!1)),await this._authRefreshPromise}finally{this._authRefreshPromise=null}});v(this,"_fetch",(t,n)=>fetch(`${t}?${this._buildParams(n.params)}`,{method:n.method,headers:this._buildHeaders(n.authRequired??!0,n.headers),...n.body?{body:JSON.stringify(this._buildBody(n.body))}:{}}));v(this,"_buildParams",t=>new URLSearchParams({sendbirdAppId:this._appId,...t}));v(this,"_buildBody",t=>({sendbirdAppId:this._appId,...t}));v(this,"_buildHeaders",(t,n)=>({"content-type":"application/json",...t&&this._credential?{sendbirdDeskToken:this._credential.deskToken}:{},...n}));v(this,"_toResult",async t=>{if(!t.ok){const r=await t.json().catch(()=>({}));throw new As(t.status,r)}const n=await t.text();if(n)try{return JSON.parse(n)}catch{throw new As(t.status,{})}});v(this,"_parseErrorCode",async t=>{const n=await t.clone().json().catch(()=>({}));return n==null?void 0:n.code});this._appId=t.appId,this._apiHost=t.customApiHost??`https://desk-api-${t.appId}.app.delight.ai/sapi`,this._logger=t.logger}get credential(){return this._credential}}class yn{constructor(t,n){v(this,"id");v(this,"title");v(this,"status");v(this,"agent");v(this,"priority");v(this,"group");v(this,"firstResponseTime");v(this,"issuedAt");v(this,"customFields");v(this,"_client");v(this,"refresh",async()=>this._client.getTicket(this.id));this.id=t.id,this.title=t.title,this.status=t.status,this.agent=t.agent,this.priority=t.priority,this.group=t.group,this.firstResponseTime=t.firstResponseTime,this.issuedAt=t.issuedAt,this.customFields=t.customFields,this._client=n}static _fromResponse(t,n){var r;return new yn({id:t.id,title:t.channelName??null,status:t.status2??Nr.INITIALIZED,agent:(()=>{var o;const s=(o=t.recentAssignment)==null?void 0:o.agent;return s?{userId:s.sendbirdId??"",name:s.displayName??"",profileUrl:s.photoThumbnailUrl??""}:null})(),priority:t.priority??Dr.MEDIUM,group:t.group??0,firstResponseTime:t.firstResponseTime??-1,issuedAt:t.issuedAt??null,customFields:Object.fromEntries(((r=t.customFields)==null?void 0:r.map(s=>[s.key,s.value]))??[])},n)}}class $r{constructor(t){v(this,"_logger");v(this,"_apiClient");v(this,"_onDeskTokenRefreshRequired");v(this,"refreshDeskAuthToken",async t=>this._apiClient.credential?this.authenticate({userId:this._apiClient.credential.userId,accessToken:t,onDeskTokenRefreshRequired:this._onDeskTokenRefreshRequired}):!1);v(this,"authenticate",async t=>{this._logger.debug("DeskClient.authenticate: start",t.userId);try{const{token:n}=await this._apiClient.request("/customers/auth/",{method:"POST",headers:{sendbirdAccessToken:t.accessToken},body:{sendbirdId:t.userId},authRequired:!1});return t.onDeskTokenRefreshRequired!==void 0&&(this._onDeskTokenRefreshRequired=t.onDeskTokenRefreshRequired),this._apiClient.setCredential({userId:t.userId,deskToken:n,chatToken:t.accessToken},this._onDeskTokenRefreshRequired),this._logger.debug("DeskClient.authenticate: end"),!0}catch(n){return this._apiClient.clearCredential(),this._logger.debug("DeskClient.authenticate: failed",n),!1}});v(this,"deauthenticate",()=>{this._apiClient.clearCredential(),this._onDeskTokenRefreshRequired=void 0,this._logger.debug("DeskClient.deauthenticate: token cleared")});v(this,"setCustomerLanguage",async t=>{this._assertAuthenticated(this._apiClient),this._logger.debug("DeskClient.setCustomerLanguage: start",t),await this._apiClient.request("/customers/language/",{method:"PATCH",body:{language:t}}),this._logger.debug("DeskClient.setCustomerLanguage: end")});v(this,"getTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request(`/tickets/${encodeURIComponent(t)}/`,{method:"GET"});return yn._fromResponse(n,this)});v(this,"createTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request("/tickets/",{method:"POST",body:mi({channelName:t.title,channelType:"SENDBIRD_JAVASCRIPT",customFields:t.customFields?JSON.stringify(t.customFields):void 0,info:JSON.stringify({ticket:{subject:t.title,requester:{name:t.name,email:this._apiClient.credential.userId}}}),priority:t.priority,groupKey:t.groupKey})});return yn._fromResponse(n,this)});this._logger=t.logger,this._apiClient=new uu(t)}static init(t){return new $r(t)}_assertAuthenticated(t){if(t.credential==null)throw new Error("DeskClient is not authenticated")}}class Fr{constructor(){v(this,"authenticate",async t=>!1);v(this,"deauthenticate",()=>{});v(this,"refreshDeskAuthToken",async()=>!1);v(this,"setCustomerLanguage",async()=>{});v(this,"getTicket",async()=>{throw new Error("DeskClient is disabled via __SBA_USE_DESK_CLIENT__")})}static init(){return new Fr}}function du(e){return{get:t=>e.getString(t)??null,set:(t,n)=>{e.set(t,n)},delete:t=>{e.delete?e.delete(t):e.remove&&e.remove(t)},getKeys:t=>e.getAllKeys().filter(n=>n.startsWith(t))}}const mu=1440*60*1e3,hu=typeof __SBA_USE_DESK_CLIENT__>"u"||__SBA_USE_DESK_CLIENT__;function nt(e){if(!e)throw new Error("Not authenticated. Call authenticate() first.")}function fu(e,t){return Object.entries(t).every(([n,r])=>e[n]===r)}const gu=e=>{const t={conversationInitialRender:new Ml(e),conversationNotInteractiveTimeout:new kl(e),recoveryNotInteractiveTimeout:new Nl(e),conversationListInitialRender:new wl(e),aievAuthExpiredUnhandled:new Il(e),messagePendingStuck:new Ol(e),userPerceivedResponseTime:new Hl(e),streamStalled:new Pl(e),typingIndicatorAbsentTimeout:new Bl(e),renderedContentUnusable:new $l(e)};return{...t,clear:()=>{Object.values(t).forEach(n=>n.clear())}}};class Sn extends Wl{constructor(n){super();v(this,"appId");v(this,"aiAgentId");v(this,"_chatClient");v(this,"_deskClient");v(this,"_cache");v(this,"_logger");v(this,"_dispatcher");v(this,"_session",null);v(this,"language");v(this,"countryCode");v(this,"context");v(this,"queryParams");v(this,"_config");v(this,"_networkStateAdapter");v(this,"_scheduleForegroundTask");v(this,"_forceCreateChannel");v(this,"_agentVersion");v(this,"_statsTrackers");v(this,"_liveMetricManager");v(this,"_operationQueue",Gl());v(this,"dispose",()=>{this._operationQueue.isPending()||(this._logger.debug("AIAgent.dispose: start"),this._chatClient.dispose(),this._chatClient.chatSDK.connectionState==="OPEN"&&this._chatClient.chatSDK.disconnectWebSocket(),this._removeChannelHandler(),this._session=null,this._deskClient.deauthenticate(),this._statsTrackers.clear(),this._liveMetricManager.dispose(),this._logger.debug("AIAgent.dispose: end"))});v(this,"initConversationIfNeeded",n=>this._initConversationIfNeeded(n));v(this,"authenticate",n=>{if(!this.appId)return Promise.reject(new Error("appId is required"));if(!this.aiAgentId)return Promise.reject(new Error("aiAgentId is required"));const r=n&&"userId"in n?`auth:${n.userId}`:"auth:anon";return this._operationQueue(r,async()=>{var i,c,u,d,m;this._logger.debug("AIAgent.authenticate: start"),this._statsTrackers.conversationInitialRender.onAuthStart(),this._statsTrackers.conversationListInitialRender.onAuthStart();const s=this._getSessionCandidate(n),o=(i=s.userSessionCandidate)!=null&&i.userId?this._cache.messenger.getSettings(s.userSessionCandidate.userId):null;o!=null&&o.bot&&this._dispatcher.send(ct.MessengerSettingsUpdated({settings:o,source:"cache"}));try{const h=await this._chatClient.requestMessengerSettings({aiAgentId:this.aiAgentId,userId:(c=s.userSessionCandidate)==null?void 0:c.userId,language:this.language,country:this.countryCode,context:this.context,knownActiveChannelUrl:(u=o==null?void 0:o.active_channel)==null?void 0:u.channel_url,forceCreateChannel:this._forceCreateChannel,agentVersion:this._agentVersion});let f;if(h.auto_created_user)if(s.type==="manual")this._logger.warn("Received auto created user info but current session is manual. Ignoring auto created user info."),f={userId:s.userSessionCandidate.userId,authToken:s.userSessionCandidate.authToken};else{const{user_id:y,session_token:b,expire_at:p}=h.auto_created_user;this._cache.messenger.setAnonUser({userId:y,authToken:b,expireAt:p}),f={userId:y,authToken:b},this._logger.debug("AIAgent.authenticate: anonymous user created",y)}else f={userId:((d=s.userSessionCandidate)==null?void 0:d.userId)??"",authToken:((m=s.userSessionCandidate)==null?void 0:m.authToken)??""};this._cache.messenger.setSettings(f.userId,h),this._dispatcher.send(ct.MessengerSettingsUpdated({settings:h,source:"server"}));const g=(()=>{var y;return s.type==="anonymous"?gl(this._dispatcher):(y=s.userSessionCandidate)==null?void 0:y.sessionHandler})(),_=await this._chatClient.connect(f,g,y=>{var b;this._logger.debug("AIAgent: session token refreshed"),(b=this._session)==null||b._updateAuthToken(y),this._deskClient.refreshDeskAuthToken(y)},()=>{this._logger.debug("AIAgent: session token unavailable, deauthenticating desk"),this._deskClient.deauthenticate()});return await this._deskClient.authenticate({userId:f.userId,accessToken:f.authToken,onDeskTokenRefreshRequired:async({reason:y})=>{var b;if(y===_i.ERR_SESSION_KEY_EXPIRED){await new Promise(S=>setTimeout(S,2e3));const p=(b=this._session)==null?void 0:b.userSession.authToken;return p?await this._deskClient.refreshDeskAuthToken(p):!1}return!1}}),(o==null?void 0:o.language)!==h.language&&this._deskClient.setCustomerLanguage(this.language).catch(()=>{}),this._statsTrackers.conversationInitialRender.onAuthComplete(),this._statsTrackers.conversationListInitialRender.onAuthComplete(),this._session=new jl({sdkUser:_,userSession:f,activeChannel:{url:h.active_channel.channel_url,status:"open"},dispatcher:this._dispatcher}),this._setupChannelHandler(),this._logger.debug("AIAgent.authenticate: end",{userId:f.userId}),h}catch(h){throw this._statsTrackers.conversationInitialRender.onAuthError(h),h}})});v(this,"deauthenticate",()=>this._operationQueue("deauth",async()=>{var r;this._logger.debug("AIAgent.deauthenticate: start");const n=(r=this._session)==null?void 0:r.userSession.userId;this._statsTrackers.clear();try{await this._chatClient.disconnect()}finally{this._deskClient.deauthenticate(),this._cache.messenger.clear(n),this._session=null,this._removeChannelHandler(),this._statsTrackers.clear()}this._logger.debug("AIAgent.deauthenticate: end")}));v(this,"createConversation",async n=>{nt(this._session),this._logger.debug("AIAgent.createConversation: start",n);const r=await this._chatClient.requestMessengerSettings({...n,userId:this._session.userSession.userId,knownActiveChannelUrl:void 0,agentVersion:this._agentVersion}),s=r.active_channel.channel_url;return this._cache.messenger.setSettings(this._session.userSession.userId,r),this._logger.debug("AIAgent.createConversation: end",s),s});v(this,"searchConversation",async n=>{if(nt(this._session),this._logger.debug("AIAgent.searchConversation: start",n),Object.entries(n.context).length===0)return this._logger.debug("AIAgent.searchConversation: empty context, returning empty array"),[];const r=this.chatSDK.aiAgent.createConversationListQuery({aiAgentId:n.aiAgentId,status:me.ConversationStatus.OPEN,limit:100}),s=[];for(;r.hasNext;){const o=await r.next();for(const i of o)fu(i.context??{},n.context)&&s.push(i.channelInfo.url)}return this._logger.debug("AIAgent.searchConversation: end",{count:s.length}),s});v(this,"closeConversation",async n=>{var s;nt(this._session),this._logger.debug("AIAgent.closeConversation: start",n);const r=await this._chatClient.getChannel(n);((s=r.conversation)==null?void 0:s.status)===me.ConversationStatus.OPEN?(await r.closeConversation(),this._session.activeChannel.url===n&&this._session._updateActiveChannel({url:n,status:"closed",conversationStatus:me.ConversationStatus.CLOSED}),this._logger.debug("AIAgent.closeConversation: end")):this._logger.debug("AIAgent.closeConversation: already closed or not an AI agent conversation")});v(this,"createConversationListCollection",n=>new ni(this.chatSDK,n??{}));v(this,"patchContext",async(n,r)=>{nt(this._session),this._logger.debug("AIAgent.patchContext: start",{channelUrl:n,context:r});const s=await this._chatClient.patchContext(this.aiAgentId,n,r);return this._logger.debug("AIAgent.patchContext: end",s),{...s,context:s.context??{}}});v(this,"updateContext",async(n,r)=>{nt(this._session),this._logger.debug("AIAgent.updateContext: start",{channelUrl:n,context:r});const s=await this._chatClient.updateContext(this.aiAgentId,n,r);return this._logger.debug("AIAgent.updateContext: end",s),{...s,context:s.context??{}}});v(this,"getContextObject",async n=>{nt(this._session),this._logger.debug("AIAgent.getContextObject: start",n);const s=await(await this._chatClient.getChannel(n)).getContextObject(this.aiAgentId);return this._logger.debug("AIAgent.getContextObject: end",s),{...s,context:s.context??{}}});v(this,"clearUserMemories",async(n={})=>{nt(this._session);const r={...n,contextAiAgentId:n.contextAiAgentId??this.aiAgentId};this._logger.debug("AIAgent.clearUserMemories: start",r),await this._chatClient.clearUserMemories(r),this._logger.debug("AIAgent.clearUserMemories: end")});v(this,"setUserMemoryState",async n=>{nt(this._session);const r=this._session;this._logger.debug("AIAgent.setUserMemoryState: start",n.enabled);const s={...n,contextAiAgentId:n.contextAiAgentId??this.aiAgentId},o=r.userSession.userId,i=await this._chatClient.setUserMemoryState(s);if(this._session!==r)return this._logger.debug("AIAgent.setUserMemoryState: session changed during request, discarding stale result"),dr(i);const c=this._cache.messenger.getSettings(o);if(c){const u={...c,memory:i};this._cache.messenger.setSettings(o,u),this._dispatcher.send(ct.MessengerSettingsUpdated({settings:u,source:"cache"}))}return this._logger.debug("AIAgent.setUserMemoryState: end",i.enabled),dr(i)});v(this,"refreshActiveChannel",async n=>{var c,u,d;nt(this._session);const r=this._session,s=(n==null?void 0:n.useKnownActiveChannelUrl)??!0;this._logger.debug("AIAgent.refreshActiveChannel: start",{useKnownActiveChannelUrl:s});const o=await this._chatClient.requestMessengerSettings({aiAgentId:this.aiAgentId,userId:r.userSession.userId,language:this.language,country:this.countryCode,context:this.context,knownActiveChannelUrl:s?(u=(c=this._cache.messenger.getSettings(r.userSession.userId))==null?void 0:c.active_channel)==null?void 0:u.channel_url:void 0,forceCreateChannel:this._forceCreateChannel,agentVersion:this._agentVersion});if(this._session!==r)return this._logger.debug("AIAgent.refreshActiveChannel: session changed during refresh, discarding stale result"),((d=this._session)==null?void 0:d.activeChannel.url)??o.active_channel.channel_url;const i=o.active_channel.channel_url;return this._cache.messenger.setSettings(this._session.userSession.userId,o),this._session._updateActiveChannel({url:i,status:"open"}),this._logger.debug("AIAgent.refreshActiveChannel: end",i),i});v(this,"_getSessionCandidate",n=>n instanceof ai?{type:"manual",userSessionCandidate:this._getManualSessionInfo(n)}:n instanceof ur?{type:"anonymous",userSessionCandidate:this._getAnonymousSessionInfo()}:n&&typeof n=="object"?(this._logger.warn("Please use ManualSessionInfo instead of the old userSessionInfo format."),{type:"manual",userSessionCandidate:this._getManualSessionInfo(n)}):n===void 0?(this._logger.warn("Please use AnonymousSessionInfo instead of undefined userSessionInfo."),{type:"anonymous",userSessionCandidate:this._getAnonymousSessionInfo()}):{type:"anonymous",userSessionCandidate:null});v(this,"_getAnonymousSessionInfo",()=>{const n=this._cache.messenger.getAnonUser();return n?n.expireAt-mu<=Date.now()?(this._logger.debug("_getAnonymousSessionInfo: auto session expired, clear cache"),this._cache.messenger.clear(n.userId),null):(this._logger.debug("_getAnonymousSessionInfo: auto session info detected"),{userId:n.userId,authToken:n.authToken}):null});v(this,"_getManualSessionInfo",n=>{if(!n||n instanceof ur)throw new Error("userSessionInfo must be an instance of ManualSessionInfo");if(typeof n.userId!="string")throw new Error("userSessionInfo.userId must be a string");const r=["userId","authToken","sessionHandler"].filter(s=>!(s in n));return r.length>0&&this._logger.error(`_getManualSessionInfo: missing required keys in userSessionInfo: ${r.join(", ")}`),this._logger.debug("_getManualSessionInfo: manual session info detected"),{userId:n.userId,authToken:n.authToken,sessionHandler:n.sessionHandler}});this.appId=n.appId,this.aiAgentId=n.aiAgentId,this.language=n.language??"en",this.countryCode=n.countryCode,this.context=n.context,this._config=ys(n.config),this.queryParams=n.queryParams,this._networkStateAdapter=n.networkStateAdapter,this._scheduleForegroundTask=n.scheduleForegroundTask,this._forceCreateChannel=n.forceCreateChannel,this._agentVersion=n.agentVersion,this._chatClient=n.chatClient,this._deskClient=n.deskClient,this._cache=n.cache,this._logger=n.logger,this._dispatcher=n.dispatcher,this._statsTrackers=n.statsTrackers,this._liveMetricManager=new fl(this._chatClient.chatSDK),this._liveMetricManager.start()}static init(n){var g;const r=pi.get(n.platform),s=n.logger??new ii(n.logLevel??wr.WARN),o=n.dispatcher??new ri(s),i=n.useMMKVStorage?du(n.useMMKVStorage):r.keyValueStorage,c=n.useMMKVStorage?{...n.chatParams,useMMKVStorageStore:n.useMMKVStorage}:n.chatParams,u=Dc({appId:n.appId,aiAgentId:n.aiAgentId,storage:i});let d;const h=gu((_,y)=>{if(!d)throw new Error("ChatClient is not initialized.");return d.chatSDK.aiAgent.appendStat(_,y)});d=Or.init({appId:n.appId,aiAgentId:n.aiAgentId,messengerVersion:r.messengerVersion,extensions:{platform:r.platform,deviceOSPlatform:r.deviceOSPlatform,deviceOSVersion:r.deviceOSVersion},chatParams:c,chatSDK:n.chatSDK,logger:s,cache:u,statsTrackers:h});const f=hu?$r.init({appId:n.appId,logger:s,customApiHost:(g=n.deskParams)==null?void 0:g.customApiHost}):Fr.init();return s.debug("AIAgent.init: created",{appId:n.appId,aiAgentId:n.aiAgentId}),new Sn({appId:n.appId,aiAgentId:n.aiAgentId,language:n.language,countryCode:n.countryCode,context:n.context,config:n.config,queryParams:n.queryParams,networkStateAdapter:r.networkStateAdapter,scheduleForegroundTask:r.scheduleForegroundTask??(_=>_()),forceCreateChannel:n._forceCreateChannel,agentVersion:n._agentVersion,chatClient:d,deskClient:f,cache:u,logger:s,dispatcher:o,statsTrackers:h})}get chatSDK(){return this._chatClient.chatSDK}get deskClient(){return this._deskClient}get session(){return this._session}get config(){return this._config}set config(n){this._config=ys(n)}get agentVersion(){return this._agentVersion}set agentVersion(n){this._agentVersion=n}get statsTrackers(){return this._statsTrackers}get liveMetricManager(){return this._liveMetricManager}get onLiveMetric(){return this._liveMetricManager.dispatch}set onLiveMetric(n){this._liveMetricManager.dispatch=n}get networkStateAdapter(){return this._networkStateAdapter}get logger(){return this._logger}get dispatcher(){return this._dispatcher}get cache(){return this._cache}get scheduleForegroundTask(){return this._scheduleForegroundTask}}const be=(e,t)=>{const n=l.createContext(t??null),r=({children:i,value:c})=>a.createElement(n.Provider,{value:c},typeof i=="function"?i(c):i),s=({children:i})=>a.createElement(n.Consumer,null,c=>c?typeof i=="function"?i(c):i:null),o=()=>{const i=l.useContext(n);if(!i)throw new Error(`use${e}Context must be used within a ${e}Provider`);return i};return n.displayName=`${e}Context`,r.displayName=`${e}Provider`,s.displayName=`${e}Consumer`,o.displayName=`use${e}Context`,{Context:n,Provider:r,Consumer:s,useContext:o}};function je(e){const t=l.createContext({Template:e.template,updateTemplate:()=>{},components:e.components,updateComponent:()=>{}});function n({children:o}){const[i,c]=l.useState(()=>e.template),[u,d]=l.useState(e.components),m={Template:i,updateTemplate:h=>c(()=>h),components:u,updateComponent:(h,f)=>d(g=>({...g,[h]:f}))};return a.createElement(t.Provider,{value:m},o)}function r({template:o,children:i}){const{updateTemplate:c}=l.useContext(t);return l.useLayoutEffect(()=>{o&&c(o)},[o]),a.createElement(a.Fragment,null,i)}function s({children:o}){return a.createElement(n,null,o)}return s.defaults=e,s.useContext=()=>l.useContext(t),s.Context=t,s.Template=r,Object.keys(e.components).forEach(o=>{s[o]=function({component:c}){const{updateComponent:u}=l.useContext(t);return l.useLayoutEffect(()=>{c&&u(o,c)},[c]),null}}),s}function pu(...e){return function({children:n}){return e.reduce((r,s)=>a.createElement(s,null,r),n)}}function _u(e,t){const n=e.lastMessage;return n!=null&&n.isAdminMessage()?n.message??"":Ei(e,t)}function Ei(e,t){var r;const n=e.lastMessage;if(n!=null&&n.isUserMessage())return n.message||"";if(n!=null&&n.isAdminMessage())return n.message??"";if(n!=null&&n.isFileMessage())return n.message||n.name||"FILE";if(n!=null&&n.isMultipleFilesMessage()){if(n.message)return n.message;const s=n.fileInfoList.length;return((r=t==null?void 0:t.formatMultipleFilesCount)==null?void 0:r.call(t,s))??`${s} photos`}return e.name}function Eu(e,t,n){var i;const r=new Date,s=new Date(((i=e.lastMessage)==null?void 0:i.createdAt)||e.createdAt),o=at.differenceInMinutes(r,s);return o<1?n.justNow:o<60?n.minutesAgo(o):at.isToday(s)?n.hoursAgo(at.differenceInHours(r,s)):t(s,n.dateShortFormat)}const Cu=e=>{const t=e.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null},sn=e=>Math.max(0,Math.min(255,e)).toString(16).padStart(2,"0"),Ts=(e,t)=>{const n=sn(Math.round(t*255));if(e.startsWith("#")){const s=e.slice(1);return s.length===3||s.length===4?`#${s[0]}${s[0]}${s[1]}${s[1]}${s[2]}${s[2]}${n}`:`#${s.slice(0,6)}${n}`}const r=Cu(e);return r?`#${sn(r[0])}${sn(r[1])}${sn(r[2])}${n}`:e},bu=(e,t)=>{if(!t)return e;const n={...e};for(const[r,s]of Object.entries(t))s&&(n[r]=s);return n},vu=e=>e.consentDialog?"consent":e.toggleAllowed?e.enabled?"on":"off":"readonly",yu=e=>e.length>0,Su=e=>{const t=e[0];if(!t)return e;const n=e.some(s=>Ye(s.type)),r=e.some(s=>!Ye(s.type));return n&&r?Ye(t.type)?e.filter(s=>Ye(s.type)):[t]:r?[t]:e},Is=e=>e.length===0?"empty":e.every(t=>Ye(t.type))?"images":"non_images",Au=({currentFiles:e,incomingFiles:t,maxAttachmentCount:n})=>{const r=Su(t),s=Is(e),o=Is(r),c=s==="images"&&o==="images"?{type:"append",files:r,nextFiles:[...e,...r]}:{type:"replace",files:r,nextFiles:r};return c.nextFiles.length>n?{type:"reject",reason:"count_limit",maxAttachmentCount:n,nextFileCount:c.nextFiles.length}:c.type==="replace"&&s!=="empty"&&s!==o?{type:"confirm_replace",action:c}:{type:"apply",action:c}},At=3,Ci=6,Tu=e=>e%At===0?At:Ci,Iu=({index:e,itemCount:t})=>{const n=t%At,r=n>0,s=r?t-n:t,o=r&&e>=s,i=o?n:At,c=o?e-s:e%At,u=!r&&e>=t-At;return{columnSpan:r?Ci/i:1,rowItemCount:i,isLastInRow:c===i-1,isLastRow:o||u}},bi=be("AIAgent"),xu=bi.Provider,ke=bi.useContext;function Ru(e){const t=Mu(e);return a.createElement(xu,{value:{_aiAgentSDK:t,chatSDK:t.chatSDK,deskClient:t.deskClient,appId:t.appId,aiAgentId:t.aiAgentId,language:t.language,countryCode:t.countryCode,context:t.context,logger:t.logger,dispatcher:t.dispatcher,cache:t.cache,networkStateAdapter:t.networkStateAdapter,queryParams:t.queryParams,config:t.config,handlers:e.handlers}},e.children)}function Mu(e){var s;const t=l.useRef(null),n=l.useRef(null);if(!t.current||!n.current)t.current=Sn.init(e);else{const o=wu(n.current,e);(o.appId||o.aiAgentId||o.chatSDK)&&(t.current.dispose(),t.current=Sn.init({...e,chatParams:o.appId?{...e.chatParams,newInstance:!0}:e.chatParams}))}n.current=e,l.useEffect(()=>()=>{var o;(o=t.current)==null||o.dispose()},[]);const r=t.current;return r.language=e.language??"en",r.countryCode=e.countryCode,r.context=e.context,r.queryParams=e.queryParams,r.config=e.config,r.agentVersion=e._agentVersion,r.onLiveMetric=(s=e.handlers)==null?void 0:s.onLiveMetric,r}function wu(e,t){const n=t.chatSDK!==void 0&&t.chatSDK!==null;return{appId:!n&&e.appId!==t.appId,aiAgentId:e.aiAgentId!==t.aiAgentId,chatSDK:!!e.chatSDK!==n||n&&t.chatSDK!==e.chatSDK}}function ie(e){const t=l.useRef(e);return t.current=e,l.useCallback((...n)=>t.current(...n),[t])}const xs=Symbol("conversationMessageEventBridge"),wt=Symbol("conversationMessageEventPublisher"),ku=(e,t)=>{const n=e;if(n[wt]=t,n[xs])return e;n[xs]=!0;const r=e.setMessageCollectionHandler.bind(e);e.setMessageCollectionHandler=o=>{r({...o,onMessagesAdded:(i,c,u)=>{var d,m;(d=o.onMessagesAdded)==null||d.call(o,i,c,u),(m=n[wt])==null||m.call(n,{kind:"messagesAdded",source:i.source,messages:u})},onMessagesUpdated:(i,c,u)=>{var d,m;(d=o.onMessagesUpdated)==null||d.call(o,i,c,u),(m=n[wt])==null||m.call(n,{kind:"messagesUpdated",source:i.source,messages:u})}})};const s=e.initialize.bind(e);return e.initialize=o=>{const i=s(o),c=i.onCacheResult.bind(i),u=i.onApiResult.bind(i);return i.onCacheResult=d=>c((m,h)=>{var f;d(m,h),(f=n[wt])==null||f.call(n,{kind:"initialized",source:"cache",messages:h??[]})}),i.onApiResult=d=>u((m,h)=>{var f;d(m,h),(f=n[wt])==null||f.call(n,{kind:"initialized",source:"api",messages:h??[]})}),i},e},Nn=()=>{const[,e]=l.useState(0);return l.useCallback(()=>e(t=>t+1),[])};let Lu=0;function Ou(){return l.useState(()=>`${Lu++}`)[0]}const ht=(e,t,n)=>{const r=l.useRef(t),o=Ou();r.current=t,l.useEffect(()=>{var c;const i=u=>{const d=u;return Object.keys(d).forEach(h=>{d[h]=(...f)=>{var _;const g=r.current;(_=g[h])==null||_.call(g,...f)}}),d};return(c=e==null?void 0:e.groupChannel)==null||c.addGroupChannelHandler(o,i(new We.GroupChannelHandler)),()=>{var u;(u=e==null?void 0:e.groupChannel)==null||u.removeGroupChannelHandler(o)}},[e==null?void 0:e.groupChannel,o])};function Nu(e,t){return!e||!t?!0:e.url!==t.url}function ze(e){return e!=null&&"sendingStatus"in e}function Du(e,t="##__USER_ID_IS_NOT_PROVIDED__##"){var n;return ze(e)?((n=e.sender)==null?void 0:n.userId)===t:!1}function $u(e,t){return Du(e,t)||e.isAdminMessage()?!1:e.updatedAt===0}function Rs(e){return"sendingStatus"in e?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId)}const An={collection:{groupChannel:{defaultOrder:We.GroupChannelListOrder.LATEST_LAST_MESSAGE},message:{defaultLimit:{next:25,prev:25},searchLimit:{next:10,prev:10}}}};function Ms(e){return!e||!Array.isArray(e)?!1:e.length!==0}function ws(e,t){return e.reduce((n,r)=>{const s=t(r);return n[s]=r,n},{})}const Fu=({...e},t)=>{switch(t.type){case"update_initialized":return e.initialized=t.value.status,e;case"update_refreshing":return e.refreshing=t.value.status,e;case"update_loading":return e.loading=t.value.status,e;case"update_messages":{if(t.value.clearBeforeAction)e.messageMap=Pu(t.value.messages);else{const n={...e.messageMap},r=[],s=[];t.value.messages.forEach(o=>{const i=ze(o)?o.reqId:void 0,c=o.messageId||void 0;[i,c].forEach(u=>{if(!u)return;const d=n[u];Uu(d,o,t.value.strictStreamingOrder)&&(d&&r.push(d),o.parentMessageId>0&&(d!=null&&d.parentMessage)&&o.applyParentMessage(d.parentMessage),s.push(o))})}),r.forEach(o=>{ze(o)&&delete n[o.reqId],delete n[o.messageId]}),s.forEach(o=>{ze(o)&&(n[o.reqId]=o),o.messageId!==0&&(n[o.messageId]=o)}),e.messageMap=n}return e}case"update_new_messages":{const n=t.value.currentUserId,r=t.value.messages.filter(s=>$u(s,n));return t.value.clearBeforeAction?e.newMessageMap=ws(r,Rs):(r.map(o=>o.messageId).forEach(o=>delete e.newMessageMap[o]),e.newMessageMap={...e.newMessageMap,...ws(r,Rs)}),e}case"delete_messages":case"delete_new_messages":{const n=t.type==="delete_messages"?"messageMap":"newMessageMap";return e[n]={...e[n]},t.value.messageIds.forEach(r=>{if(r===0)return;const s=e[n][r];s&&(ze(s)&&delete e[n][s.reqId],delete e[n][s.messageId])}),t.value.reqIds.forEach(r=>{const s=e[n][r];s&&(ze(s)&&delete e[n][s.reqId],delete e[n][s.messageId])}),e}}},Pu=e=>e.reduce((t,n)=>(ze(n)?(t[n.reqId]=n,n.sendingStatus===Fe.SendingStatus.SUCCEEDED&&(t[n.messageId]=n)):t[n.messageId]=n,t),{}),Uu=(e,t,n=!1)=>{var r,s;if(!ze(e)||!ze(t))return!0;if(n&&e&&Me.isStreaming(e)&&Me.isStreaming(t)){const o=((r=e.message)==null?void 0:r.length)||0,i=((s=t.message)==null?void 0:s.length)||0;if(o>i)return!1}return e.sendingStatus===Fe.SendingStatus.SUCCEEDED?t.sendingStatus===Fe.SendingStatus.SUCCEEDED:e.sendingStatus!==t.sendingStatus},Bu=(e=Hu)=>{const[{initialized:t,loading:n,refreshing:r,messageMap:s,newMessageMap:o},i]=l.useReducer(Fu,{initialized:!1,loading:!0,refreshing:!1,messageMap:{},newMessageMap:{}}),c=(b,p,S,A)=>{i({type:"update_messages",value:{messages:b,clearBeforeAction:p,currentUserId:S,strictStreamingOrder:A}})},u=(b,p)=>{i({type:"delete_messages",value:{messageIds:b,reqIds:p}})},d=(b,p,S)=>{i({type:"update_new_messages",value:{messages:b,clearBeforeAction:p,currentUserId:S}})},m=(b,p)=>{i({type:"delete_new_messages",value:{messageIds:b,reqIds:p}})},h=b=>{i({type:"update_initialized",value:{status:b}})},f=b=>{i({type:"update_loading",value:{status:b}})},g=b=>{i({type:"update_refreshing",value:{status:b}})},_=Object.values(o),y=l.useMemo(()=>Array.from(new Set(Object.values(s))).sort(e),[s]);return{updateInitialized:h,updateLoading:f,updateRefreshing:g,updateMessages:c,deleteMessages:u,initialized:t,loading:n,refreshing:r,messages:y,newMessages:_,updateNewMessages:d,deleteNewMessages:m}},ks=Math.floor(Number.MAX_SAFE_INTEGER/10);function Hu(e,t){let n=0,r=0;return ze(e)&&e.sendingStatus!=="succeeded"&&(n=ks),ze(t)&&t.sendingStatus!=="succeeded"&&(r=ks),e.createdAt+n-(t.createdAt+r)}const Gu=(e,t,n)=>{var o;const r={prevResultLimit:t.prev,nextResultLimit:t.next,startingPoint:n==null?void 0:n.startingPoint,replyType:n==null?void 0:n.replyType},s=(o=n==null?void 0:n.collectionCreator)==null?void 0:o.call(n,r);return s||e.createMessageCollection({...r,filter:new We.MessageFilter(r)})};function Ls(e){return e<Date.now()?An.collection.message.searchLimit:An.collection.message.defaultLimit}const zu=(e,t,n={})=>{var De,$;const r=l.useRef(n);r.current=n;const s=l.useRef(t);s.current=t;const o=r.current.logger,i=r.current.startingPoint??Number.MAX_SAFE_INTEGER,c=Ls(i),u=r.current.strictStreamingOrder??!1,d=l.useRef({prev:!1,next:!1}),m=Nn(),h=l.useRef({initialized:!1,apiInitialized:!1,instance:null}),{initialized:f,loading:g,refreshing:_,messages:y,newMessages:b,updateMessages:p,updateNewMessages:S,deleteNewMessages:A,deleteMessages:T,updateInitialized:R,updateLoading:L,updateRefreshing:D}=Bu(n==null?void 0:n.sortComparator),k=ie(x=>{var w,O,z,q;if(!s.current||!s.current.url)return(w=o==null?void 0:o.error)==null?void 0:w.call(o,"[useGroupChannelMessages] channel is required");try{switch(x){case de.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case de.CollectionEventSource.EVENT_MESSAGE_SENT_SUCCESS:case de.CollectionEventSource.SYNC_MESSAGE_FILL:case void 0:(z=(O=r.current).markAsRead)==null||z.call(O,[s.current]);break}}catch(ee){(q=o==null?void 0:o.warn)==null||q.call(o,"[useGroupChannelMessages/markAsReadBySource]",ee)}}),M=ie((x,w)=>{var O,z,q,ee,W;if(w.length>0)switch(x){case de.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case de.CollectionEventSource.SYNC_MESSAGE_FILL:{(z=(O=r.current).shouldCountNewMessages)!=null&&z.call(O)&&S(w,!1,(q=e.currentUser)==null?void 0:q.userId),(W=(ee=r.current).onMessagesReceived)==null||W.call(ee,w);break}}}),P=ie(x=>{var w,O;(O=(w=r.current).onCollectionEvent)==null||O.call(w,x)}),F=ie(async(x,w,O)=>new Promise((z,q)=>{var Xe;h.current.instance&&h.current.instance.dispose(),k(),S([],!0,(Xe=e.currentUser)==null?void 0:Xe.userId);const ee=()=>{var _e,Ee;const{pendingMessages:ae,failedMessages:he}=h.current.instance??{};Ms(ae)&&p(ae,!1,(_e=e.currentUser)==null?void 0:_e.userId),Ms(he)&&p(he,!1,(Ee=e.currentUser)==null?void 0:Ee.userId)},W=Gu(x,O,{...r.current,startingPoint:w});h.current={apiInitialized:!1,initialized:!1,instance:W},W.setMessageCollectionHandler({onMessagesAdded:(ae,he,_e)=>{var Ee;k(ae.source),M(ae.source,_e),p(_e,!1,(Ee=e.currentUser)==null?void 0:Ee.userId,u),P({kind:"messagesAdded",source:ae.source,channelUrl:x.url,messages:_e})},onMessagesUpdated:(ae,he,_e)=>{var Ee,Ce,Te;k(ae.source),M(ae.source,_e),p(_e,!1,(Ee=e.currentUser)==null?void 0:Ee.userId,u),ae.source===de.CollectionEventSource.EVENT_MESSAGE_UPDATED&&((Te=(Ce=r.current).onMessagesUpdated)==null||Te.call(Ce,_e)),P({kind:"messagesUpdated",source:ae.source,channelUrl:x.url,messages:_e})},onMessagesDeleted:(ae,he,_e,Ee)=>{const Ce=Ee.map(ve=>ve.messageId),Te=Ee.filter(ze).map(ve=>ve.reqId);T(Ce,Te),A(Ce,Te),P({kind:"messagesDeleted",source:ae.source,channelUrl:x.url,messages:Ee})},onChannelDeleted:(ae,he)=>{var _e,Ee;(Ee=(_e=r.current).onChannelDeleted)==null||Ee.call(_e,he)},onChannelUpdated:(ae,he)=>{var _e,Ee;m(),(Ee=(_e=r.current).onChannelUpdated)==null||Ee.call(_e,he,ae)},onHugeGapDetected:()=>{F(x,Number.MAX_SAFE_INTEGER,An.collection.message.defaultLimit)}});let pe=!1;W.initialize(We.MessageCollectionInitPolicy.CACHE_AND_REPLACE_BY_API).onCacheResult((ae,he)=>{var _e,Ee,Ce,Te,ve;(Ee=(_e=r.current).onCacheResult)==null||Ee.call(_e,ae,he??[],x.url),ae?(e.isCacheEnabled&&((Ce=o==null?void 0:o.error)==null||Ce.call(o,"[useGroupChannelMessages/onCacheResult]",ae)),pe=!0):he&&((Te=o==null?void 0:o.debug)==null||Te.call(o,"[useGroupChannelMessages/onCacheResult]","message length:",he.length),p(W.succeededMessages,!0,(ve=e.currentUser)==null?void 0:ve.userId),ee(),he.length>0&&(h.current.initialized=!0,z())),P({kind:"initialized",source:"cache",channelUrl:x.url,messages:he??[]})}).onApiResult((ae,he)=>{var _e,Ee,Ce,Te,ve,$e,Pe;(Ee=(_e=r.current).onApiResult)==null||Ee.call(_e,ae,he??[],x.url),h.current.initialized=!0,h.current.apiInitialized=!0,ae?((Ce=o==null?void 0:o.warn)==null||Ce.call(o,"[useGroupChannelMessages/onApiResult]",ae),pe?q(ae):z()):he&&((Te=o==null?void 0:o.debug)==null||Te.call(o,"[useGroupChannelMessages/onApiResult]","message length:",he.length),p(W.succeededMessages,!0,(ve=e.currentUser)==null?void 0:ve.userId),r.current.startingPoint||(Pe=($e=r.current).onMessagesReceived)==null||Pe.call($e,he),e.isCacheEnabled&&ee(),z()),P({kind:"initialized",source:"api",channelUrl:x.url,messages:he??[]})})}));ht(e,{onUserBanned(x,w){var O,z,q;x.isGroupChannel()&&!Nu(x,s.current)&&(w.userId===((O=e.currentUser)==null?void 0:O.userId)?(q=(z=r.current).onCurrentUserBanned)==null||q.call(z):m())}}),l.useLayoutEffect(()=>{const x=setTimeout(async()=>{e.currentUser&&s.current&&(R(!1),L(!0),await F(s.current,i,c),L(!1),R(!0))});return()=>clearTimeout(x)},[e,(De=e.currentUser)==null?void 0:De.userId,($=s.current)==null?void 0:$.url,r.current.replyType]),l.useEffect(()=>()=>{h.current.instance&&h.current.instance.dispose()},[]);const Y=ie(async()=>{e.currentUser&&s.current&&(D(!0),await F(s.current,Number.MAX_SAFE_INTEGER,An.collection.message.defaultLimit),D(!1))}),j=ie(async()=>{var w;const x=h.current.instance;if(x!=null&&x.hasPrevious&&!d.current.prev)try{d.current.prev=!0;const O=await x.loadPrevious();p(O,!1,(w=e.currentUser)==null?void 0:w.userId)}catch{}finally{d.current.prev=!1}}),N=ie(()=>{const{initialized:x,instance:w}=h.current;return x&&w?w.hasPrevious:!1}),B=ie(async()=>{var w;const x=h.current.instance;if(x!=null&&x.hasNext&&!d.current.next)try{d.current.next=!0;const O=await x.loadNext();p(O,!1,(w=e.currentUser)==null?void 0:w.userId)}catch{}finally{d.current.next=!1}}),U=ie(()=>{const{initialized:x,apiInitialized:w,instance:O}=h.current;return w&&x&&O?O.hasNext:!1}),V=x=>{var w,O,z,q;!x||x.channelUrl!==((w=s.current)==null?void 0:w.url)||(p([x],!1,(O=e.currentUser)==null?void 0:O.userId),(q=(z=r.current).onOutgoingMessageStatusChanged)==null||q.call(z,x))},ce=ie((x,w)=>{var O;if(!s.current||!s.current.url)throw(O=o==null?void 0:o.error)==null||O.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((z,q)=>{s.current.sendUserMessage(x).onPending(ee=>{V(ee),w==null||w(ee)}).onSucceeded(ee=>{V(ee),z(ee)}).onFailed((ee,W)=>{V(W),q(ee)})})}),Ie=ie((x,w)=>{var O;if(!s.current||!s.current.url)throw(O=o==null?void 0:o.error)==null||O.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((z,q)=>{s.current.sendFileMessage(x).onPending(ee=>{V(ee),w==null||w(ee)}).onSucceeded(ee=>{V(ee),z(ee)}).onFailed((ee,W)=>{V(W),q(ee)})})}),X=ie((x,w,O)=>{var z;if(!s.current||!s.current.url)throw(z=o==null?void 0:o.error)==null||z.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((q,ee)=>{s.current.sendMultipleFilesMessage(x).onPending(W=>{V(W),w==null||w(W)}).onFileUploaded(W=>{O==null||O(W),m()}).onSucceeded(W=>{V(W),q(W)}).onFailed((W,pe)=>{V(pe),ee(W)})})}),K=ie(async(x,w)=>{var z,q;if(!s.current||!s.current.url)throw(z=o==null?void 0:o.error)==null||z.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");const O=await s.current.updateUserMessage(x,w);return O.channelUrl===s.current.url&&p([O],!1,(q=e.currentUser)==null?void 0:q.userId),O}),I=ie(async(x,w)=>{var z,q;if(!s.current||!s.current.url)throw(z=o==null?void 0:o.error)==null||z.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");const O=await s.current.updateFileMessage(x,w);return O.channelUrl===s.current.url&&p([O],!1,(q=e.currentUser)==null?void 0:q.userId),O}),Z=ie(async(x,w,O)=>{var z;if(!s.current||!s.current.url)throw(z=o==null?void 0:o.error)==null||z.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((q,ee)=>{let W;x.isUserMessage()&&(W=s.current.resendMessage(x)),x.isFileMessage()&&(W=s.current.resendMessage(x)),x.isMultipleFilesMessage()&&(W=s.current.resendMessage(x)),W&&("onPending"in W&&W.onPending(pe=>{V(pe),w==null||w(pe)}),"onFileUploaded"in W&&W.onFileUploaded(pe=>{O==null||O(pe),m()}),"onSucceeded"in W&&W.onSucceeded(pe=>{V(pe),q(pe)}),"onFailed"in W&&W.onFailed((pe,Xe)=>{V(Xe),ee(pe)}))})}),ne=ie(async x=>{var w,O;if(!s.current||!s.current.url)throw(w=o==null?void 0:o.error)==null||w.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");if(x.sendingStatus==="succeeded")x.isUserMessage()&&await s.current.deleteMessage(x),x.isFileMessage()&&await s.current.deleteMessage(x),x.isMultipleFilesMessage()&&await s.current.deleteMessage(x);else try{await((O=h.current.instance)==null?void 0:O.removeFailedMessage(x.reqId))}finally{T([],[x.reqId])}}),oe=ie(()=>{var x;S([],!0,(x=e.currentUser)==null?void 0:x.userId)}),Re=ie(async x=>{var w;if(e.currentUser&&s.current){const O=Ls(x);L(!0),p([],!0,(w=e.currentUser)==null?void 0:w.userId),await F(s.current,x,O),L(!1)}});return{initialized:f,loading:g,refreshing:_,messages:y,newMessages:b,resetNewMessages:oe,refresh:Y,loadPrevious:j,hasPrevious:N,loadNext:B,hasNext:U,sendUserMessage:ce,sendFileMessage:Ie,sendMultipleFilesMessage:X,updateUserMessage:K,updateFileMessage:I,resendMessage:Z,deleteMessage:ne,resetWithStartingPoint:Re,_dangerous_reducer_updateMessages:p,_dangerous_reducer_deleteMessages:T}},Vu=(e,t,n)=>{const r=l.useRef(0),s=l.useRef(new Set),o=l.useCallback(d=>{const m={id:r.current+=1,...d};s.current.forEach(h=>{h(m)})},[]),i=l.useCallback(d=>{var h;const m=((h=n==null?void 0:n.collectionCreator)==null?void 0:h.call(n,d))??(t==null?void 0:t.createMessageCollection({...d??{},filter:new We.MessageFilter(d)}));if(!m)throw new Error("Group channel is required to create a message collection");return ku(m,o)},[t,n==null?void 0:n.collectionCreator,o]),c=zu(e,t,{...n,collectionCreator:i,strictStreamingOrder:!0}),u=l.useCallback(d=>(s.current.add(d),()=>{s.current.delete(d)}),[]);return{...c,subscribeMessageEvents:u}},qu=({channelUrl:e,enabled:t=!0,statsTracker:n})=>{const r=l.useRef(e),s=l.useRef(t),o=l.useRef(!1),i=l.useRef(null),c=l.useRef(null),u=l.useRef(null);s.current=t;const d=l.useCallback(p=>r.current===p,[]),m=l.useCallback(()=>{o.current&&(n.clear(),o.current=!1,i.current=null)},[n]),h=l.useCallback(p=>{if(!s.current)return;const S=!o.current||i.current!==p;n.start(p),S&&n.onGetChannelStart(p),o.current=!0,i.current=p},[n]),f=l.useCallback(p=>{d(p)&&(u.current=p,c.current=null,h(p))},[d,h]),g=l.useCallback(({channelUrl:p,conversationId:S})=>{o.current||h(p),n.onGetChannelComplete({channelUrl:p,conversationId:S})},[h,n]),_=l.useCallback(({channelUrl:p,error:S})=>{o.current||h(p),n.onGetChannelError({channelUrl:p,error:S})},[h,n]),y=l.useCallback(p=>{if(d(p.channelUrl)){if(u.current=null,!s.current){c.current=p;return}c.current=null,g(p)}},[d,g]),b=l.useCallback(p=>{if(d(p.channelUrl)){if(u.current=null,!s.current){c.current=p;return}c.current=null,_(p)}},[d,_]);return l.useEffect(()=>{if(t){const p=c.current;if(p){if(c.current=null,p.channelUrl!==e)return;"error"in p?_(p):g(p);return}const S=u.current;if(S){if(S!==e){u.current=null;return}h(S)}return}m()},[e,m,t,_,g,h]),l.useEffect(()=>(r.current=e,o.current=!1,i.current=null,c.current=null,u.current=null,()=>{m(),o.current=!1,i.current=null,c.current=null,u.current=null}),[e,m]),{onFetchStart:f,onFetchSuccess:y,onFetchError:b}},Ku=({channelUrl:e,enabled:t=!0,statsTracker:n})=>{const r=l.useRef(e),s=l.useRef(t),o=l.useRef(null),i=l.useRef(!1);s.current=t;const c=l.useCallback(_=>r.current===_,[]),u=l.useCallback(()=>{i.current&&(n.clearChannel(r.current),i.current=!1)},[n]),d=l.useCallback(_=>{c(_)&&s.current&&(i.current=!0)},[c]),m=l.useCallback(({channelUrl:_,conversationId:y})=>{i.current=!0,n.markChannelJoined(y,_)},[n]),h=l.useCallback(({channelUrl:_})=>{n.clearChannel(_),i.current=!1},[n]),f=l.useCallback(_=>{if(c(_.channelUrl)){if(!s.current){o.current=_;return}o.current=null,m(_)}},[c,m]),g=l.useCallback(_=>{if(c(_.channelUrl)){if(!s.current){o.current=_;return}o.current=null,h(_)}},[c,h]);return l.useEffect(()=>{if(t){const _=o.current;if(!_||(o.current=null,_.channelUrl!==e))return;"error"in _?h(_):m(_);return}u()},[e,u,t,h,m]),l.useEffect(()=>(r.current=e,o.current=null,i.current=!1,()=>{u(),o.current=null,i.current=!1}),[e,u]),{onFetchStart:d,onFetchSuccess:f,onFetchError:g}},Yu=({channelUrl:e,enabled:t=!0,scheduleForegroundTask:n,statsTracker:r})=>{const s=l.useRef(e),o=l.useRef(null),i=l.useRef(t),c=l.useRef(0),u=l.useRef(null);i.current=t;const d=l.useCallback((h=!0)=>{var g;(g=o.current)==null||g.call(o),o.current=null;const f=u.current;h&&(u.current=null),h&&f&&r.clearChannel(f)},[r]),m=l.useCallback(h=>{if(!i.current){d(),r.clearChannel(h);return}d(!1),u.current=h;const f=c.current,g=()=>{if(!i.current||f!==c.current||s.current!==h){r.clearChannel(h),u.current===h&&(u.current=null);return}r.start("ws_reconnected",h)};o.current=(n==null?void 0:n(g))??null,n||g()},[d,n,r]);return l.useEffect(()=>{t||d()},[d,t]),l.useEffect(()=>(s.current=e,c.current+=1,()=>{c.current+=1,d()}),[e,d]),{onReconnectSucceeded:m}},Bt={DEFAULT_PRIMARY:"#000000",DEFAULT_BOT_MSG_BG:"#ECECEC",WHITE:"#ffffff",BLACK:"#000000"};function vi(e){return e.length===4?`#${[...e.slice(1)].map(t=>t+t).join("")}`:e}function Wu(e){const t=vi(e);return[parseInt(t.slice(1,3),16),parseInt(t.slice(3,5),16),parseInt(t.slice(5,7),16)]}function ju(e){return`#${e.map(t=>t.toString(16).padStart(2,"0")).join("")}`}function Xu(e,t,n){e/=255,t/=255,n/=255;const r=Math.max(e,t,n),s=Math.min(e,t,n),o=r-s;let i=0,c=0;const u=(r+s)/2;return r!==s&&(c=u>.5?o/(2-r-s):o/(r+s)),r===e?i=(t-n)/o+(t<n?6:0):r===t?i=(n-e)/o+2:r===n&&(i=(e-t)/o+4),i/=6,[i,c,u]}function Zu(e,t,n){let r,s,o;if(t===0)r=s=o=n;else{const i=function(m,h,f){return f<0&&(f+=1),f>1&&(f-=1),f<.16666666666666666?m+(h-m)*6*f:f<.5?h:f<.6666666666666666?m+(h-m)*(.6666666666666666-f)*6:m},c=n<.5?n*(1+t):n+t-n*t,u=2*n-c;r=i(u,c,e+1/3),s=i(u,c,e),o=i(u,c,e-1/3)}return[Math.round(r*255),Math.round(s*255),Math.round(o*255)]}function on(e,t,n){const[r,s,o]=Wu(e),[i,c,u]=Xu(r,s,o),d=Math.max(0,Math.min(1,u*t)),m=Math.max(0,Math.min(1,c*n)),[h,f,g]=Zu(i,m,d);return ju([Math.round(h),Math.round(f),Math.round(g)])}function Ju(e,t="light"){return{extraDark:on(e,.6,1.2),dark:on(e,.85,1.1),main:e,light:on(e,t==="dark"?1.1:1.5,t==="dark"?.95:.9),extraLight:on(e,t==="dark"?1.2:1.75,t==="dark"?.9:.8)}}function mr(e){const t=vi(e),n=149,r=+`0x${t[1]}${t[2]}`,s=+`0x${t[3]}${t[4]}`,o=+`0x${t[5]}${t[6]}`;return r*.299+s*.587+o*.114>n?Bt.BLACK:Bt.WHITE}function Qu(e,t,n,r,s){return{base:{primary:t,primaryContrastContent:n,background:e.background50,headerBackground:e.background50,modalContentBackground:e.background50},messageInput:{text:e.onlight.textHighEmphasis,placeholderText:e.onlight.textLowEmphasis,background:e.background100},messageIncoming:{text:s,background:r},messageOutgoing:{text:n,background:t},csat:{background:e.background100},memoryDialog:{titleText:e.onlight.textHighEmphasis,markdownBodyText:e.onlight.textLowEmphasis,markdownLinkText:e.onlight.textHighEmphasis,positiveBackground:e.onlight.textHighEmphasis,positiveText:e.ondark.textHighEmphasis,positiveBorderColor:"transparent",negativeBackground:"transparent",negativeText:e.onlight.textHighEmphasis,negativeBorderColor:"transparent"}}}const ed=(e,t,n,r,s)=>({base:{primary:t,primaryContrastContent:n,background:e.background600,headerBackground:e.background500,modalContentBackground:e.background500},messageInput:{text:e.ondark.textHighEmphasis,placeholderText:e.ondark.textLowEmphasis,background:e.background400},messageIncoming:{text:s,background:r},messageOutgoing:{text:n,background:t},csat:{background:e.background400},memoryDialog:{titleText:e.ondark.textHighEmphasis,markdownBodyText:e.ondark.textLowEmphasis,markdownLinkText:e.ondark.textHighEmphasis,positiveBackground:e.ondark.textHighEmphasis,positiveText:e.onlight.textHighEmphasis,positiveBorderColor:"transparent",negativeBackground:"transparent",negativeText:e.ondark.textHighEmphasis,negativeBorderColor:"transparent"}}),an={primary:{extraDark:"#491389",dark:"#6211c8",main:"#742ddd",light:"#c2a9fa",extraLight:"#dbd1ff"},secondary:{extraDark:"#066858",dark:"#027d69",main:"#259c72",light:"#69c085",extraLight:"#a8e2ab"},error:{extraDark:"#9d091e",dark:"#bf0711",main:"#de360b",light:"#f66161",extraLight:"#fdaaaa"},information:{extraDark:"#241389",dark:"#362ca9",main:"#4a48cd",light:"#a9bbfa",extraLight:"#d1dbff"},background700:"#000000",background600:"#161616",background500:"#2c2c2c",background400:"#393939",background300:"#bdbdbd",background200:"#e0e0e0",background100:"#eeeeee",background50:"#ffffff",onlight:{textHighEmphasis:"rgba(0, 0, 0, 1)",textMidEmphasis:"rgba(0, 0, 0, 0.75)",textLowEmphasis:"rgba(0, 0, 0, 0.55)",textDisabled:"rgba(0, 0, 0, 0.12)"},ondark:{textHighEmphasis:"rgba(255, 255, 255, 1)",textMidEmphasis:"rgba(255, 255, 255, 0.75)",textLowEmphasis:"rgba(255, 255, 255, 0.58)",textDisabled:"rgba(255, 255, 255, 0.12)"},overlay:{dark:"rgba(0, 0, 0, 0.55)",light:"rgba(22, 22, 22, 0.32)"}},Wn={h1:{fontSize:18,fontWeight:700},h2:{fontSize:16,fontWeight:700},subtitle1:{fontSize:16,fontWeight:500},subtitle2:{fontSize:16,fontWeight:400},body1:{fontSize:16,fontWeight:400},body2:{fontSize:14,fontWeight:500},body3:{fontSize:14,fontWeight:400},button:{fontSize:14,fontWeight:700},caption1:{fontSize:12,fontWeight:700},caption2:{fontSize:12,fontWeight:400},caption3:{fontSize:11,fontWeight:700},caption4:{fontSize:11,fontWeight:400}};function Os(e){const t=td(e),n=nd(e,t),r=sd(n,e.colors,e.selectedTheme),s=id(e);return{selectedTheme:e.selectedTheme,palette:t,colors:r,aiAgentColorVariables:{primary_color:r.base.primary,primary_contrast_color:r.base.primaryContrastContent,bot_message_bg_color:r.messageIncoming.background,bot_message_bg_contrast_color:r.messageIncoming.text},typography:s}}function td({selectedTheme:e,palette:t,primary:n}){const r=t!=null&&t.primary?t.primary:n?n===an.primary.main?an.primary:Ju(n,e):an.primary;return{...an,primary:r,...t}}function nd({selectedTheme:e,primaryContrast:t,botMessageBackground:n,botMessageBackgroundContrast:r},s){const o=s.primary.main,i=t??mr(o),c=n??Bt.DEFAULT_BOT_MSG_BG,u=r??mr(c);return(e==="light"?Qu:ed)(s,o,i,c,u)}function rd(e,t,n){return typeof e=="string"?e:e[t]??n}function sd(e,t,n){var i;if(!t||Object.keys(t).length===0)return e;const r={...e},s=r,o=e;for(const c of Object.keys(t)){const u=t[c];if(u){s[c]={...s[c]};for(const[d,m]of Object.entries(u))if(m!==void 0){const h=((i=o[c])==null?void 0:i[d])??"";s[c][d]=rd(m,n,h)}}}return r}function od(e,t,n){const r={...e};return n.forEach(s=>{const o=t[s];o!=null&&(r[s]=o)}),r}function id({typography:e}){if(!e)return Wn;const t={...Wn};return Object.keys(e).forEach(n=>{const r=e[n];if(r&&typeof r=="object"){const s=Wn[n],o=["fontSize","fontWeight","fontFamily","lineHeight"];t[n]=od(s,r,o)}}),t}const{Provider:ad,useContext:Pr}=be("AIAgentTheme");function cd({logger:e,palette:t,typography:n,colors:r,appearance:s,children:o}){const i=l.useRef(null),[c,u]=l.useState(()=>Os({selectedTheme:(s==null?void 0:s.theme)??"light",palette:t,typography:n,colors:r,primary:s==null?void 0:s.primaryColor,botMessageBackground:s==null?void 0:s.botMessageBackgroundColor})),d=l.useCallback((m,h)=>{h&&(i.current=h);const f=(s==null?void 0:s.theme)??m,g=i.current?i.current.themes[f]:null,_={primary:s==null?void 0:s.primaryColor,primaryContrast:void 0,botMessageBackground:s==null?void 0:s.botMessageBackgroundColor,botMessageBackgroundContrast:void 0};!_.primary&&(g!=null&&g.primary_color)&&(_.primary=g.primary_color,_.primaryContrast=g.primary_contrast_color),!_.botMessageBackground&&(g!=null&&g.bot_message_bg_color)&&(_.botMessageBackground=g.bot_message_bg_color,_.botMessageBackgroundContrast=g.bot_message_bg_contrast_color);const y=Os({selectedTheme:f,palette:t,typography:n,colors:r,..._});u(y),e==null||e.info("theme.update:",f)},[s==null?void 0:s.theme,s==null?void 0:s.primaryColor,s==null?void 0:s.botMessageBackgroundColor,t,n,r,e]);return l.useEffect(()=>{(s!=null&&s.theme||s!=null&&s.primaryColor||s!=null&&s.botMessageBackgroundColor)&&d(c.selectedTheme)},[s==null?void 0:s.theme,s==null?void 0:s.primaryColor,s==null?void 0:s.botMessageBackgroundColor]),a.createElement(ad,{value:{theme:c,updateTheme:d}},o)}const jn=25*1024*1024,Ns=1,Ds=new Set(["image/png","image/jpeg","image/jpg"]),$s=new Set(["application/pdf"]),ld={off:"off",always:"always",handed_off_only:"handed_off_only"},ud=()=>{const[e,t]=l.useState(()=>({maxAttachmentCount:Ns,attachmentMode:"handed_off_only",defaultUploadSizeLimit:jn,uploadSizeLimitPerType:new Map,supportedImageMimeTypes:Ds,supportedFileMimeTypes:$s})),n=l.useCallback(({active_channel:s,upload_restriction:o})=>{t({maxAttachmentCount:(o==null?void 0:o.max_attachment_count)??Ns,attachmentMode:ld[s.attachment_mode]??"handed_off_only",defaultUploadSizeLimit:(o==null?void 0:o.default_upload_size_limit)??jn,uploadSizeLimitPerType:new Map(Object.entries((o==null?void 0:o.upload_size_limit_per_type)??[])),supportedImageMimeTypes:new Set((o==null?void 0:o.supported_image_mime_types)??Ds),supportedFileMimeTypes:new Set((o==null?void 0:o.supported_file_mime_types)??$s)})},[]),r=l.useCallback(s=>{const{channel:o,uploadSizeLimit:i=jn}=s,c=(d=!0)=>o!=null&&o.isAIAgent?d?rt(o):!1:!0,u=d=>{if(c())return e.defaultUploadSizeLimit??i;const m=e.defaultUploadSizeLimit??i,h=e.uploadSizeLimitPerType.get(d)??m;return Math.min(m,h)};return{maxAttachmentCount:e.maxAttachmentCount,isEnabled:()=>{if(c(!1))return!0;switch(e.attachmentMode){case"off":return!1;case"always":return!0;case"handed_off_only":return rt(o);default:return!0}},get supportedMimeTypes(){return c()?[lr]:[...e.supportedImageMimeTypes,...e.supportedFileMimeTypes]},isSupportedMimeType:d=>c()?!0:e.supportedImageMimeTypes.has(d)||e.supportedFileMimeTypes.has(d),getUploadSizeLimit:u,getUploadSizeLimitInMB:d=>u(d)/(1024*1024)}},[e]);return{updateBaseAttachmentRules:n,createAttachmentRules:r}},Fs=(...e)=>{const[t,n,r]=e;if(e.length===1&&typeof t=="object"&&t!==null)return{type:"active",context:t};if(e.length===3&&typeof t=="string"&&typeof n=="string"&&typeof r=="object"&&r!==null)return{type:"specific",aiAgentId:t,channelUrl:n,context:r};throw new Error("Invalid arguments: expected (context) or (aiAgentId, channelUrl, context)")},kt=e=>({...e,context:e.context??{}}),{Provider:dd,useContext:ft}=be("AIAgentMessengerSession"),md=l.forwardRef(function({userSessionInfo:e,children:t},n){const{_aiAgentSDK:r,chatSDK:s,aiAgentId:o,logger:i}=ke(),{updateTheme:c}=Pr(),[u,d]=l.useState(void 0),[m,h]=l.useState(void 0),[f,g]=l.useState(null),[_,y]=l.useState(null),[b,p]=l.useState(null),[S,A]=l.useState(null),[T,R]=l.useState(null),{updateBaseAttachmentRules:L,createAttachmentRules:D}=ud();l.useEffect(()=>{const F=r.onMessengerSettingsUpdated(({settings:N})=>{const{appearance:B,bot:U,launcher:V,memory:ce}=N;c(B.selected_theme,B),p(Kl(U)),A(Yl(V)),R(ce?dr(ce):null),L(N)}),Y=r.onActiveChannelUpdated(({channelUrl:N,status:B,conversationStatus:U})=>{h({url:N,status:B,conversationStatus:U})}),j=r.onAuthTokenRefreshed(()=>{var B;const N=(B=r.session)==null?void 0:B.userSession.authToken;N&&y(U=>U?{...U,authToken:N}:null)});return()=>{F(),Y(),j()}},[r,c,L]);const k=l.useCallback(async()=>{try{const F=await r.authenticate(e),Y=r.session;return g(Y.sdkUser),y(Y.userSession),h(Y.activeChannel),d(void 0),F}catch(F){throw g(null),y(null),h(void 0),d(F),F}},[r,e]),M=l.useCallback(async()=>{await r.deauthenticate(),g(null),h(void 0),y(null),p(null),A(null),R(null)},[r]),P=l.useCallback(async()=>{if(!r.session){if(_)return i.debug("agentMessengerSession.refreshActiveChannel: stale call after deauthenticate, skipping"),"";throw i.error("agentMessengerSession.refreshActiveChannel: userSession is not ready"),new Error("userSession is not ready")}return r.session.userSession.userId!==(_==null?void 0:_.userId)?(i.debug("agentMessengerSession.refreshActiveChannel: stale call from previous session, skipping"),r.session.activeChannel.url):(h(void 0),await r.refreshActiveChannel())},[r,i,_]);return l.useImperativeHandle(n,()=>{const F=async()=>{if(!m)throw new Error("No active conversation. Please start a conversation first.");return await s.groupChannel.getChannel(m.url)};return{activeChannel:m,chatSDK:s,authenticate:k,deauthenticate:M,updateContext:async(...Y)=>{const j=Fs(...Y);if(j.type==="active"){const U=await(await F()).updateContext(o,j.context);return kt(U)}const N=await s.aiAgent.updateContext(j.aiAgentId,j.channelUrl,j.context);return kt(N)},patchContext:async(...Y)=>{const j=Fs(...Y);if(j.type==="active"){const U=await(await F()).patchContext(o,j.context);return kt(U)}const N=await s.aiAgent.patchContext(j.aiAgentId,j.channelUrl,j.context);return kt(N)},getContextObject:async()=>{const j=await(await F()).getContextObject(o);return kt(j)}}},[k,M,m,s,o,i]),a.createElement(dd,{value:{sdkUser:f,userSessionInfo:e,userSession:_,activeChannel:m,setActiveChannel:h,refreshActiveChannel:P,createConversation:r.createConversation,searchConversation:r.searchConversation,connectionError:u,aiAgentInfo:b,launcherInfo:S,memoryInfo:T,authenticate:k,deauthenticate:M,createAttachmentRules:D}},t)}),hd={ai_responding:"not_ready",conversation_closed:"ready",form_active:"ready",handoff_pending:"ready",reconnecting:"not_ready",steward:"ready",suggested_replies:"ready",system:"ready",unavailable:"not_ready"},fd=e=>e.disabled?hd[e.disabledBy]==="ready":!0,gd=e=>{var n,r,s,o,i;if(e.isUserMessage())return"text";const t=e.isFileMessage()?e.type:((r=(n=e.fileInfoList)==null?void 0:n[0])==null?void 0:r.mimeType)??((i=(o=(s=e.messageParams)==null?void 0:s.fileInfoList)==null?void 0:o[0])==null?void 0:i.mimeType);return t&&Ye(t)?"file_image":t&&zt(t)?"file_video":t&&Tc(t)?"file_audio":"file_document"};let Ps=0;const pd=e=>(Ps+=1,`${e??"unknown"}:${Ps}`),yt=(e,t)=>e===void 0||t===e,yi=(e,t)=>{!t.error&&t.messages.length>0&&e.conversationNotInteractiveTimeout.markHistoryLoaded("success",t.channelUrl)},Si=(e,t)=>{t.error?e.conversationNotInteractiveTimeout.markHistoryLoaded("failed",t.channelUrl):e.conversationNotInteractiveTimeout.markHistoryLoaded(t.messages.length>0?"success":"verified_empty",t.channelUrl)},_d=(e,t)=>{e.conversationInitialRender.onCacheResult(t.error),yi(e,t)},Ed=(e,t)=>{e.conversationInitialRender.onApiResult(t.error),Si(e,t)},Cd=(e,t,n)=>{var o;if(!st(e,n))return;const{hasResponseMetadata:r,...s}=jo(e.data);r&&(t.typingIndicatorAbsentTimeout.markAIResponseStarted({channelUrl:e.channelUrl,userMessageId:s.userMessageId}),t.userPerceivedResponseTime.markAIResponseRaw({messageId:e.messageId,channelUrl:e.channelUrl,aiResponse:s}),t.streamStalled.markRawProgress({messageId:e.messageId,channelUrl:e.channelUrl,textLength:((o=e.message)==null?void 0:o.length)??0,aiResponse:s}))},Us=(e,t)=>{t.streamStalled.clearMessage(e.messageId),t.userPerceivedResponseTime.clearMessage(e.messageId);const n=Qe(e)?e.reqId:void 0;n&&(t.messagePendingStuck.disappear({requestId:n}),t.userPerceivedResponseTime.cancelTurn(n),t.typingIndicatorAbsentTimeout.cancelTurn(n))},Xn=(e,t)=>{t&&(e.conversationInitialRender.clear(),e.conversationNotInteractiveTimeout.clearChannel(t),e.recoveryNotInteractiveTimeout.clearChannel(t),e.messagePendingStuck.clearChannel(t),e.userPerceivedResponseTime.clearChannel(t),e.typingIndicatorAbsentTimeout.clearChannel(t),e.streamStalled.clearChannel(t))},bd=({activeChannelUrl:e,statsTrackers:t})=>{const{chatSDK:n}=ke(),{aiAgentInfo:r}=ft(),s=l.useRef(!1),o=r==null?void 0:r.userId;ht(!!e&&!!o?n:void 0,{onTypingStatusUpdated(c){if(c.url!==e)return;const u=c.getTypingUsers().some(m=>m.userId===o),d=s.current;u&&!d?t.typingIndicatorAbsentTimeout.markTypingStarted(c.url):!u&&d&&t.typingIndicatorAbsentTimeout.markTypingEnded(c.url),s.current=u}}),l.useEffect(()=>{s.current=!1},[e,o])},vd=({enabled:e=!0,requestedChannelUrl:t,statsTrackers:n})=>{const r=l.useRef(void 0),s=l.useRef(e);l.useLayoutEffect(()=>{const o=r.current,i=s.current;if(s.current=e,!e){o&&(Xn(n,o),r.current=void 0);return}o&&o!==t&&(Xn(n,o),r.current=void 0),t&&o!==t&&(i||n.conversationInitialRender.start(),n.conversationInitialRender.setChannelUrl(t),n.conversationNotInteractiveTimeout.start({channelUrl:t}),r.current=t)},[e,t,n]),l.useLayoutEffect(()=>()=>{const o=r.current;o&&(Xn(n,o),r.current=void 0)},[n])},yd=({aiAgentUserId:e,conversationStatsEnabled:t=!0,requestedChannelUrl:n,statsTrackers:r})=>{const s=l.useRef(null),o=l.useRef(null),i=l.useRef(!1),c=l.useRef(0),u=l.useRef(0),d=l.useRef(t),m=l.useMemo(()=>c.current+1,[n]);l.useLayoutEffect(()=>(i.current=!0,c.current=m,()=>{i.current=!1,c.current+=1}),[m]);const h=l.useCallback(g=>i.current&&c.current===g,[]);l.useLayoutEffect(()=>{u.current+=1,s.current=null,o.current=null},[n]),l.useLayoutEffect(()=>{const g=d.current;d.current=t,!(g||!t)&&(s.current&&(s.current.tracked=!1),o.current&&(o.current.tracked=!1))},[t]);const f=l.useCallback(g=>g.lifecycleGeneration===u.current&&yt(n,g.channelUrl),[n]);return l.useEffect(()=>{if(!t)return;const g=s.current;g&&f(g)&&(g.tracked||(r.conversationInitialRender.onCacheResult(g.error),g.tracked=!0),yi(r,g));const _=o.current;_&&f(_)&&(_.tracked||(r.conversationInitialRender.onApiResult(_.error),_.tracked=!0),Si(r,_))},[t,f,r]),l.useMemo(()=>({onCollectionEvent:g=>{if(h(m)&&yt(n,g.channelUrl)){if(g.kind==="messagesDeleted"){g.messages.forEach(_=>Us(_,r));return}t&&g.messages.forEach(_=>Cd(_,r,e))}},onCacheResult:(g,_,y)=>{if(!h(m)||!yt(n,y))return;const b={error:g,messages:_,channelUrl:y,lifecycleGeneration:u.current,tracked:!1};s.current=b,t&&(_d(r,b),b.tracked=!0)},onApiResult:(g,_,y)=>{if(!h(m)||!yt(n,y))return;const b={error:g,messages:_,channelUrl:y,lifecycleGeneration:u.current,tracked:!1};o.current=b,t&&(Ed(r,b),b.tracked=!0)},onLocalMessageDeleted:g=>{h(m)&&yt(n,g.channelUrl)&&Us(g,r)}}),[e,m,t,h,n,r])},Sd=({enabled:e=!0,channelUrl:t,initialized:n,inputReady:r,renderedSignal:s,statsTrackers:o})=>{const i=l.useRef(!1),c=l.useRef(0);l.useEffect(()=>{c.current+=1,i.current=!1},[t,e]),l.useEffect(()=>{e&&(o.recoveryNotInteractiveTimeout.setInputEnabled(r,t),r&&o.conversationNotInteractiveTimeout.markInputEnabled(t))},[t,e,r,o]),l.useEffect(()=>{if(!e||!n||i.current)return;const u=c.current,d=setTimeout(()=>{c.current===u&&(o.conversationInitialRender.markRendered(t)&&(i.current=!0),o.conversationNotInteractiveTimeout.markRendered(t))});return()=>clearTimeout(d)},[t,e,n,s,o])},Ad=({channelUrl:e,enabled:t=!0,statsTrackers:n})=>{const r=l.useRef(!1),s=l.useRef(e),o=l.useRef(t),i=l.useRef(0);return l.useLayoutEffect(()=>(r.current=!0,s.current=e,o.current=t,i.current+=1,()=>{r.current=!1,i.current+=1}),[e,t]),l.useCallback(async(c,u,d={})=>{if(!r.current||!o.current)return c(y=>u==null?void 0:u(y),()=>{});let m;const h=i.current,f=s.current,g=()=>r.current&&o.current&&i.current===h&&s.current===f,_=y=>g()&&yt(f,y);try{const y=await c(b=>{if(!_(b.channelUrl)){u==null||u(b);return}m=b.reqId,n.messagePendingStuck.start({requestId:b.reqId,channelUrl:b.channelUrl,messageType:gd(b),tracksUploadProgress:d.tracksUploadProgress??!1}),u==null||u(b)},b=>{!g()||m!==b||n.messagePendingStuck.markUploadProgress(b)});return m&&(g()?n.messagePendingStuck.resolve({requestId:m}):n.messagePendingStuck.disappear({requestId:m})),y}catch(y){throw m&&(g()?n.messagePendingStuck.resolve({requestId:m}):n.messagePendingStuck.disappear({requestId:m})),y}},[n])},Td=({channelUrl:e,enabled:t=!0,statsTrackers:n})=>{const r=l.useRef(!1),s=l.useRef(e),o=l.useRef(t),i=l.useRef(0);return l.useLayoutEffect(()=>(r.current=!0,s.current=e,o.current=t,i.current+=1,()=>{r.current=!1,i.current+=1}),[e,t]),l.useCallback(async c=>{if(!r.current||!o.current)return c(()=>{});const u=i.current,d=s.current,m=()=>r.current&&o.current&&i.current===u&&s.current===d;let h=pd(d);n.userPerceivedResponseTime.startTurn({requestId:h,channelUrl:d}),n.typingIndicatorAbsentTimeout.startTurn({requestId:h,channelUrl:d});try{const f=await c(g=>{m()&&(n.userPerceivedResponseTime.replaceTurnRequestId(h,g),n.typingIndicatorAbsentTimeout.replaceTurnRequestId(h,g),h=g)});return m()?(n.userPerceivedResponseTime.markUserMessageAck({requestId:h,messageId:f.messageId}),n.typingIndicatorAbsentTimeout.markUserMessageAck({requestId:h,messageId:f.messageId})):(n.userPerceivedResponseTime.cancelTurn(h),n.typingIndicatorAbsentTimeout.cancelTurn(h)),f}catch(f){throw n.userPerceivedResponseTime.cancelTurn(h),n.typingIndicatorAbsentTimeout.cancelTurn(h),f}},[e,n])},Id=({requestedChannelUrl:e,activeChannelUrl:t,conversationStatsEnabled:n=!0,statsTrackers:r})=>{const{aiAgentInfo:s}=ft();bd({activeChannelUrl:t,statsTrackers:r}),vd({enabled:n,requestedChannelUrl:e,statsTrackers:r});const o=yd({aiAgentUserId:s==null?void 0:s.userId,conversationStatsEnabled:n,requestedChannelUrl:e,statsTrackers:r}),i=Ad({channelUrl:t,enabled:n,statsTrackers:r}),c=Td({channelUrl:t,enabled:n,statsTrackers:r});return l.useMemo(()=>({messageCallbacks:o,runWithPendingStuckStats:i,runWithUserTurnStats:c}),[o,i,c])},jt=()=>ke()._aiAgentSDK.statsTrackers,Xt=(e,t)=>{const n=l.useId(),r=l.useRef(t);l.useLayoutEffect(()=>{r.current=t}),l.useLayoutEffect(()=>{const s=new de.ConnectionHandler({onDisconnected:o=>{var i,c;return(c=(i=r.current).onDisconnected)==null?void 0:c.call(i,o)},onConnected:o=>{var i,c;return(c=(i=r.current).onConnected)==null?void 0:c.call(i,o)},onReconnectStarted:()=>{var o,i;return(i=(o=r.current).onReconnectStarted)==null?void 0:i.call(o)},onReconnectSucceeded:()=>{var o,i;return(i=(o=r.current).onReconnectSucceeded)==null?void 0:i.call(o)},onReconnectFailed:()=>{var o,i;return(i=(o=r.current).onReconnectFailed)==null?void 0:i.call(o)},onConnectionLost:()=>{var o,i;return(i=(o=r.current).onConnectionLost)==null?void 0:i.call(o)},onConnectionDelayed:o=>{var i,c;return(c=(i=r.current).onConnectionDelayed)==null?void 0:c.call(i,o)}});return e.addConnectionHandler(n,s),()=>{e.removeConnectionHandler(n)}},[e,n])},Bs=()=>{const e=l.useRef(0);return{next:()=>(e.current+=1,e.current),current:()=>e.current,invalidate:()=>{e.current+=1},isCurrent:t=>t===e.current}};function xd(e,t={},{shouldInitializeConversation:n=!0}={}){const{chatSDK:r,logger:s,aiAgentId:o,_aiAgentSDK:i}=ke(),{sdkUser:c}=ft(),u=Bs(),d=Bs(),m=Nn(),[h,f]=l.useState(void 0),[g,_]=l.useState(void 0),[y,b]=l.useState(!1),p=ie(A=>{if(n&&A.isAIAgent&&!A.conversation){const T=d.next();b(!0),i.initConversationIfNeeded(A).finally(()=>{d.isCurrent(T)&&b(!1)})}});async function S(){var T,R,L,D,k,M;const A=u.next();if(!c){s.debug("useChannel.getChannel: no sdk user, skip fetching channel");return}if(s.debug("useChannel.getChannel: start"),f(void 0),_(void 0),d.invalidate(),b(!1),e){(T=t.onFetchStart)==null||T.call(t,e);try{s.debug("useChannel.getChannel: get channel",e);const P=await r.groupChannel.getChannel(e);if(!u.isCurrent(A))return;p(P),f(P),(L=t.onFetchSuccess)==null||L.call(t,{channelUrl:P.url,conversationId:(R=P.conversation)==null?void 0:R.id}),P.url===((D=i.session)==null?void 0:D.activeChannel.url)&&i.session._updateActiveChannel({url:P.url,status:He(P)?"closed":"open",conversationStatus:(k=P.conversation)==null?void 0:k.status}),s.debug("useChannel.getChannel: fetched channel",P)}catch(P){if(!u.isCurrent(A))return;(M=t.onFetchError)==null||M.call(t,{channelUrl:e,error:P}),P instanceof de.SendbirdError&&_(P),s.error("useChannel.getChannel: error",P)}}}return l.useEffect(()=>(S(),()=>{u.invalidate()}),[r,c,e,o]),l.useEffect(()=>{n&&h&&p(h)},[n]),Xt(r,{async onReconnectSucceeded(){var R;if(!h){g&&await S();return}const A=u.current(),T=await h.refresh();!u.isCurrent(A)||h.url!==e||((R=t.onReconnectSucceeded)==null||R.call(t,h.url),p(T),f(T))}}),ht(r,{onChannelChanged:A=>{A.isGroupChannel()&&A.url===e&&(s.debug("useChannel.onChannelChanged: channel changed",A.url),f(A),m())}}),{channel:h,channelFetchError:g,getChannel:S,isInitializingConversation:y}}const Rd=new Set(["suggested_replies","steward","system"]),Md=e=>{const t=e==null?void 0:e.lastMessage,n=t==null?void 0:t.extendedMessagePayload,r=n==null?void 0:n.user_input_disabled_by;if(!(!r||!Rd.has(r)))return r},wd=e=>{var o;const t=e==null?void 0:e.lastMessage;if(!t||!e)return!1;const n=t.extendedMessagePayload,r=kn(n).hasActiveForm,s=e.isAIAgent&&!!((o=e.conversation)!=null&&o.handedOverAt);return r&&!s},kd=()=>{const{chatSDK:e,networkStateAdapter:t}=ke(),[n,r]=l.useState(()=>t?t.isOnline()?"connected":"reconnecting":"connected");return Xt(e,{onConnected:()=>r("connected"),onDisconnected:()=>r("disconnected"),onReconnectStarted:()=>r("reconnecting"),onReconnectSucceeded:()=>r("connected"),onReconnectFailed:()=>r("disconnected"),onConnectionLost:()=>r("reconnecting")}),l.useEffect(()=>{if(t)return t.subscribe(s=>{if(!s){r("reconnecting");return}r(o=>o==="reconnecting"&&e.connectionState===de.ConnectionState.OPEN?"connected":o)})},[t,e]),n},Ld=3e4,Od=({shouldApply:e,lastMessage:t,isBlockedWhileAIResponding:n,currentUserId:r})=>{const[s,o]=l.useState(!1),i=l.useRef(null),c=t&&st(t,r)?t.createdAt:0;return l.useEffect(()=>{const u=()=>{i.current&&(clearTimeout(i.current),i.current=null),o(!1)},d=f=>{i.current&&clearTimeout(i.current),o(!0),i.current=setTimeout(()=>{o(!1),i.current=null},f)},m=Date.now()-c,h=Ld-m;return n||h<=0?u():d(h),()=>{i.current&&clearTimeout(i.current)}},[n,c]),s&&e},Ai=e=>{const{chatSDK:t}=ke(),[n,r]=l.useState([]);return ht(t,{onTypingStatusUpdated(s){if(s.url===(e==null?void 0:e.url)){const o=s.getTypingUsers();r(o)}}}),n},Nd=({channel:e,lastMessage:t,aiAgentUserId:n,isStreamAnimating:r})=>{const[s,o]=l.useState(!1),i=Ai(e);return l.useEffect(()=>{if(!t)return;const c=i.some(d=>d.userId===n),u=st(t,n)&&(Me.isStreaming(t)||r);o(u||c)},[i,t,n,r]),s},Dd=({channel:e,messages:t,isStreamAnimating:n,isInitializingConversation:r})=>{const{aiAgentInfo:s,userSession:o}=ft(),i=kd(),c=Nd({channel:e,lastMessage:fs(t,[Fe.SendingStatus.SUCCEEDED]),aiAgentUserId:(s==null?void 0:s.userId)??"",isStreamAnimating:n}),u=Od({shouldApply:!!(e!=null&&e.isAIAgent)&&!rt(e),isBlockedWhileAIResponding:c,lastMessage:fs(t,[Fe.SendingStatus.PENDING,Fe.SendingStatus.SUCCEEDED]),currentUserId:(o==null?void 0:o.userId)??""}),d=h=>h===""?{disabled:!1,disabledBy:"",focusPolicy:"auto"}:h==="ai_responding"?{disabled:!0,disabledBy:h,focusPolicy:"preserve"}:{disabled:!0,disabledBy:h,focusPolicy:"release"};if(!e||i==="disconnected")return d("unavailable");if(i==="reconnecting")return d("reconnecting");if(He(e))return d("conversation_closed");if(el(e))return d("handoff_pending");if(wd(e))return d("form_active");const m=Md(e);return d(m||(c||u||r?"ai_responding":""))},$d=()=>{const[e,t]=l.useState(new Set),n=l.useCallback(s=>{t(o=>{if(o.has(s))return o;const i=new Set(o);return i.add(s),i})},[]),r=l.useCallback(s=>{t(o=>{if(!o.has(s))return o;const i=new Set(o);return i.delete(s),i})},[]);return{isAnimating:e.size>0,start:n,stop:r}},{Provider:Fd}=be("AIAgentConversation"),Pd=({initialRenderStats:e,notInteractiveStats:t,recoveryStats:n})=>({onFetchStart:r=>{e.onFetchStart(r),t.onFetchStart(r)},onFetchSuccess:r=>{e.onFetchSuccess(r),t.onFetchSuccess(r)},onFetchError:r=>{e.onFetchError(r),t.onFetchError(r)},onReconnectSucceeded:n.onReconnectSucceeded});function Ud({children:e,channelUrl:t,onChannelDeleted:n,onMessagesReceived:r,onMessagesUpdated:s,onConversationStatusChanged:o,onConversationClosedViaDispatcher:i,onBeforeSendMessage:c,onAfterSendMessage:u=ue,shouldMarkAsRead:d=!0,conversationStatsEnabled:m=!0,shouldInitializeConversation:h=!0,shouldCountNewMessages:f=()=>!1,sortComparator:g}){var $,x;const _=()=>d&&(M==null?void 0:M.markAsRead()),{_aiAgentSDK:y,chatSDK:b,logger:p,dispatcher:S}=ke(),A=jt(),T={channelUrl:t,enabled:m},R=qu({...T,statsTracker:A.conversationInitialRender}),L=Ku({...T,statsTracker:A.conversationNotInteractiveTimeout}),D=Yu({...T,scheduleForegroundTask:y.scheduleForegroundTask,statsTracker:A.recoveryNotInteractiveTimeout}),k=Pd({initialRenderStats:R,notInteractiveStats:L,recoveryStats:D}),{channel:M,channelFetchError:P,getChannel:F,isInitializingConversation:Y}=xd(t,k,{shouldInitializeConversation:h}),j=M==null?void 0:M.url,N=Id({requestedChannelUrl:t,activeChannelUrl:j,conversationStatsEnabled:m,statsTrackers:A}),B=Vu(b,M,{replyType:Fe.ReplyType.ONLY_REPLY_TO_CHANNEL,shouldCountNewMessages:f,onChannelDeleted:n,onMessagesReceived:w=>r==null?void 0:r(w),onMessagesUpdated:w=>s==null?void 0:s(w),...N.messageCallbacks,onOutgoingMessageStatusChanged:w=>{M&&y.liveMetricManager.track({type:"outgoingMessage",channel:M,message:w})},logger:p,markAsRead:_,sortComparator:g}),U=$d(),V=Dd({channel:M,messages:B.messages,isStreamAnimating:U.isAnimating,isInitializingConversation:Y});Sd({enabled:m,channelUrl:j,initialized:B.initialized,inputReady:fd(V),renderedSignal:B.messages,statsTrackers:A}),l.useEffect(()=>{_()},[d,M]);const ce=($=M==null?void 0:M.conversation)==null?void 0:$.status;l.useEffect(()=>{ce&&(o==null||o(ce))},[ce,o]),l.useEffect(()=>{const w=async O=>{const z=typeof(O==null?void 0:O.channelUrl)=="string";M&&z&&O.channelUrl!==M.url||(p.debug("conversation.dispatcher: try to close conversation",M),M!=null&&M.conversation&&M.conversation.status===me.ConversationStatus.OPEN&&(await M.closeConversation(),i==null||i()))};return S.subscribe(Ke.ConversationClose,w),()=>{S.unsubscribe(Ke.ConversationClose,w)}},[S,M,p,(x=M==null?void 0:M.conversation)==null?void 0:x.status,i]);const Ie=ie(()=>B.loadPrevious()),X=ie(()=>B.loadNext()),K=ie(async w=>{try{await B.deleteMessage(w)}finally{w.sendingStatus!=="succeeded"&&N.messageCallbacks.onLocalMessageDeleted(w)}}),I=ie(w=>w.isUserMessage()?N.runWithUserTurnStats(O=>N.runWithPendingStuckStats(z=>B.resendMessage(w,q=>{O(q.reqId),z(q)}),void 0)):N.runWithPendingStuckStats((O,z)=>B.resendMessage(w,O,z),void 0,{tracksUploadProgress:w.isMultipleFilesMessage()})),Z=ie(()=>B.resetNewMessages()),ne=ie(async w=>{var z;if(((z=M==null?void 0:M.conversation)==null?void 0:z.status)===me.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(w=await c(w));const O=await N.runWithUserTurnStats(q=>N.runWithPendingStuckStats(ee=>B.sendUserMessage(w,W=>{q(W.reqId),ee(W)}),u));return u==null||u(O),O}),oe=ie(async w=>{var z;if(((z=M==null?void 0:M.conversation)==null?void 0:z.status)===me.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(w=await c(w));const O=await N.runWithPendingStuckStats(q=>B.sendFileMessage(w,q),u);return u==null||u(O),O}),Re=ie(async w=>{var z;if(((z=M==null?void 0:M.conversation)==null?void 0:z.status)===me.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(w=await c(w));const O=await N.runWithPendingStuckStats((q,ee)=>B.sendMultipleFilesMessage(w,q,ee),u,{tracksUploadProgress:!0});return u==null||u(O),O}),De={conversation:(M==null?void 0:M.conversation)??void 0,actions:{setUserMemoryState:y.setUserMemoryState},channelSource:{channel:M,error:P,refetch:()=>F(),closeConversation:async()=>{He(M)||await(M==null?void 0:M.closeConversation())}},messageSource:{messages:B.messages,newMessages:B.newMessages,initialized:B.initialized,subscribeMessageEvents:B.subscribeMessageEvents,loadPrevious:Ie,loadNext:X,deleteMessage:K,resendMessage:I,resetNewMessages:Z,sendUserMessage:ne,sendFileMessage:oe,sendMultipleFilesMessage:Re},state:{streamAnimation:U,input:V}};return a.createElement(Fd,{value:De},e)}function Bd(e,t,n){var p,S,A,T,R,L,D,k,M,P;const[r,s]=l.useState(!1),[o,i]=l.useState(null),[c,u]=l.useState([]),[d,m]=l.useState(null),h=l.useRef(!1),f=ie(()=>{var F;return(F=n==null?void 0:n.onListRequestStart)==null?void 0:F.call(n)}),g=ie(()=>{var F;return(F=n==null?void 0:n.onListRequestComplete)==null?void 0:F.call(n)}),_=l.useCallback(async F=>{f(),await F.loadMore(),g()},[f,g]),y=l.useCallback(async()=>{if(!h.current&&e.currentUser){h.current=!0,s(!1),i(null),u([]);try{d==null||d.dispose();const F=new ni(e,t);F.setConversationListCollectionHandler({onChannelsAdded:()=>{u(F.channels)},onChannelsUpdated:()=>{u(F.channels)},onChannelsDeleted:()=>{u(F.channels)}}),await _(F),u(F.channels),m(F),i(null)}catch(F){m(null),i(F)}finally{s(!0),h.current=!1}}},[e,e.currentUser,(p=t.filter)==null?void 0:p.aiAgentChannelFilter,(A=(S=t.filter)==null?void 0:S.aiAgentConversationStatusFilter)==null?void 0:A.join(),(R=(T=t.filter)==null?void 0:T.aiAgentIds)==null?void 0:R.join(),(L=t.filter)==null?void 0:L.deskChannelFilter,(k=(D=t.filter)==null?void 0:D.pinnedChannelUrls)==null?void 0:k.join(),(M=t.filter)==null?void 0:M.copilotConversationOnly,(P=t.filter)==null?void 0:P.copilotSupportChannelUrl,t.limit,_]),b=l.useCallback(async()=>{if(d)try{await d.loadMore(),u(d.channels)}catch(F){i(F)}},[d]);return Xt(e,{onConnected:()=>y()}),l.useEffect(()=>{y()},[y]),l.useEffect(()=>()=>{h.current=!1,d==null||d.dispose()},[d]),{initialized:r,error:o,channels:c,loadMore:b}}const Ti=e=>{var s;const{aiAgentId:t,queryParams:n}=ke(),r=(s=n==null?void 0:n.conversationListParams)==null?void 0:s.filter;return{aiAgentIds:[t],aiAgentConversationStatusFilter:[me.ConversationStatus.CLOSED,me.ConversationStatus.OPEN],...r,...e}},Hd=({enabled:e=!0}={})=>{const n=jt().conversationListInitialRender,r=l.useRef(e),s=l.useRef(!1),o=l.useRef(!1),i=l.useRef(!1);r.current=e,l.useEffect(()=>{if(!e){o.current&&(s.current=!0);return}if(o.current&&!s.current)return;const m=s.current&&i.current;n.onInitializeStart(),o.current=!0,s.current=!1,m&&n.onListRequestStart()},[e,n]),l.useEffect(()=>()=>{n.clear(),o.current=!1,s.current=!1,i.current=!1},[n]);const c=l.useCallback(()=>r.current&&o.current&&!s.current,[]),u=l.useMemo(()=>({onListRequestStart:()=>{i.current=!0,c()&&n.onListRequestStart()},onListRequestComplete:()=>{i.current=!1,c()&&n.onListRequestComplete()}}),[c,n]),d=l.useCallback(()=>{c()&&n.onRendered()},[c,n]);return l.useMemo(()=>({collectionCallbacks:u,onRendered:d}),[u,d])},{Provider:Gd}=be("AIAgentConversationList");function zd({conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:n=!0,children:r}){var h;const{chatSDK:s,queryParams:o}=ke(),i=Hd({enabled:n}),c=e??((h=o==null?void 0:o.conversationListParams)==null?void 0:h.limit),u=Ti(t),d=Bd(s,{limit:c,filter:u},i.collectionCallbacks);l.useEffect(()=>{n&&d.initialized&&(d.error||i.onRendered())},[n,d.error,d.initialized,i]);const m={listSource:{initialized:d.initialized,error:d.error??void 0,channels:d.channels,loadMore:()=>d.loadMore()}};return a.createElement(Gd,{value:m},r)}function Vd(e){let t="pending",n=e.then(r=>{t="resolved",n=r}).catch(r=>{t="rejected",n=r});return{get value(){if(t==="resolved")return n;throw n}}}const{Provider:qd,useContext:Kd}=be("MessageTemplateFetching");function Yd({children:e,internalVariables:t}){const n=l.useRef({}),r=l.useRef({}),[s,o]=l.useState({}),i=l.useCallback((d,m)=>{o(h=>({...h,[d]:{fetching:!1,error:!1,...h[d],...m}}))},[]),c=l.useCallback(async({onRequestTemplate:d,onGetCachedTemplate:m,templateKey:h,suspense:f=!1})=>{const g=m(h);if(g)return g;const _=r.current[h];if(_)return _;f||i(h,{fetching:!0});const y=d(h).catch(b=>{throw f||i(h,{error:!0}),b}).finally(()=>{f||i(h,{fetching:!1}),delete r.current[h]});return r.current[h]=y,y},[i]),u={internalVariables:t,fetchTemplate:c,suspend:(d,m)=>{if(n.current[d])return n.current[d];const h=Vd(m());return n.current[d]=h,h},getIsFetching:d=>{var m;return((m=s[d])==null?void 0:m.fetching)??!1},getHasError:d=>{var m;return((m=s[d])==null?void 0:m.error)??!1}};return a.createElement(qd,{value:u},e)}const Wd="remove_powered_by",Ur=(e,t)=>{var s,o;const{chatSDK:n}=ke(),{aiAgentInfo:r}=ft();if(e==="handoff-button"){const i=!!((s=t==null?void 0:t.conversation)!=null&&s.handoff);return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.showHandoffButton)&&i&&Rr(t)}if(e==="special-notice")return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.specialNoticeEnabled)&&!!(r!=null&&r.specialNotice);if(e==="powered-by"){const i=(o=n==null?void 0:n.appInfo)==null?void 0:o.applicationAttributes;return l.useMemo(()=>!(Array.isArray(i)&&i.includes(Wd)),[i])}throw new Error("Unsupported feature")},jd={required:"This question is required",minLength:e=>`Minimum ${e} characters required`,maxLength:e=>`Maximum ${e} characters allowed`,min:e=>`Minimum value is ${e}`,max:e=>`Maximum value is ${e}`,minSelect:e=>`Select at least ${e} options`,maxSelect:e=>`Select at most ${e} options`,regex:"Invalid format",invalidSelection:"Invalid selection"},Xd={getValueOrDefault:e=>e.value??e.default_value??null,validate:(e,t,n)=>{const r=t;if(e.required&&(!r||r.trim()===""))return{isValid:!1,error:n.required};if(!r)return{isValid:!0};const{rules:s}=e;if(s){if(s.min_length!==void 0&&r.length<s.min_length)return{isValid:!1,error:typeof n.minLength=="function"?n.minLength(s.min_length):n.minLength};if(s.max_length!==void 0&&r.length>s.max_length)return{isValid:!1,error:typeof n.maxLength=="function"?n.maxLength(s.max_length):n.maxLength};if(s.regex&&!new RegExp(s.regex).test(r))return{isValid:!1,error:n.regex}}return{isValid:!0}}},Zd={getValueOrDefault:e=>e.value??e.default_value??null,validate:(e,t,n)=>{const r=t;if(e.required&&r===null)return{isValid:!1,error:n.required};if(r===null)return{isValid:!0};const{rules:s}=e;if(s){if(s.min!==void 0&&r<s.min)return{isValid:!1,error:typeof n.min=="function"?n.min(s.min):n.min};if(s.max!==void 0&&r>s.max)return{isValid:!1,error:typeof n.max=="function"?n.max(s.max):n.max}}return{isValid:!0}}},Jd={getValueOrDefault:e=>e.value??e.default_value??null,validate:(e,t,n)=>{const r=t;return e.required&&!r?{isValid:!1,error:n.required}:r&&!e.options.includes(r)?{isValid:!1,error:n.invalidSelection}:{isValid:!0}}},Qd={getValueOrDefault:e=>e.values??e.default_values??null,validate:(e,t,n)=>{const r=t;if(e.required&&(!r||r.length===0))return{isValid:!1,error:n.required};if(!r||r.length===0)return{isValid:!0};if(r.filter(i=>!e.options.includes(i)).length>0)return{isValid:!1,error:n.invalidSelection};const{rules:o}=e;if(o){if(o.min_select!==void 0&&r.length<o.min_select)return{isValid:!1,error:typeof n.minSelect=="function"?n.minSelect(o.min_select):n.minSelect};if(o.max_select!==void 0&&r.length>o.max_select)return{isValid:!1,error:typeof n.maxSelect=="function"?n.maxSelect(o.max_select):n.maxSelect}}return{isValid:!0}}},em={text:Xd,number:Zd,"single-select":Jd,"multi-select":Qd},tm={getValueOrDefault:()=>null,validate:()=>({isValid:!1})};function Ii(e){return em[e.type]||tm}function Hs(e){return Ii(e).getValueOrDefault(e)}function nm(e,t,n={}){const r={...jd,...n};return Ii(e).validate(e,t,r)}const rm=(e,t={})=>{const{labels:n={},onSubmit:r,onCancel:s}=t,[o,i]=l.useState({}),[c,u]=l.useState(()=>{const y={};return e.fields.forEach(b=>{y[b.key]=Hs(b)}),y}),d=l.useMemo(()=>e.submitted_at?"submitted":e.canceled_at?"canceled":"draft",[e.submitted_at,e.canceled_at]);l.useEffect(()=>{if(d==="submitted"||d==="canceled"){const y={};let b=!1;e.fields.forEach(p=>{const S=Hs(p);JSON.stringify(c[p.key])!==JSON.stringify(S)&&(b=!0),y[p.key]=S}),b&&u(y)}},[d]);const m=(y,b)=>{u(p=>({...p,[y]:b})),i(p=>({...p,[y]:void 0}))},h=e.fields.map(y=>{var S,A,T;const b=c[y.key]??null,p={key:y.key,label:y.label,error:o[y.key],required:y.required};return y.type==="text"?{...p,type:"text",layout:y.layout,value:b,...y.placeholder&&{placeholder:y.placeholder},...((S=y.rules)==null?void 0:S.max_length)&&{maxLength:y.rules.max_length}}:y.type==="number"?{...p,type:"number",layout:y.layout,value:b,...y.placeholder&&{placeholder:y.placeholder},...((A=y.rules)==null?void 0:A.max)&&{max:y.rules.max}}:y.type==="single-select"?{...p,type:"single-select",layout:y.layout,value:b,options:y.options}:y.type==="multi-select"?{...p,type:"multi-select",layout:y.layout,value:b,options:y.options,...((T=y.rules)==null?void 0:T.max_select)&&{maxSelect:y.rules.max_select}}:{...p,type:"unknown",layout:"default",value:null}});return{state:d,fields:h,getField:y=>h.find(b=>b.key===y),updateFieldValue:m,submit:async()=>{const y={};let b=!1;for(const p of e.fields){const S=c[p.key]??null,A=nm(p,S,n);A.isValid||(y[p.key]=A.error,b=!0)}if(i(y),!b&&r){const p={};e.fields.forEach(S=>{p[S.key]=c[S.key]??null}),await r(p)}},cancel:async()=>{await(s==null?void 0:s())}}},sm=e=>{const{chatSDK:t,handlers:n,logger:r}=ke(),{aiAgentInfo:s}=ft(),o=l.useRef(new Set),i=l.useRef(new Set),c=(m,h)=>{if(!(n!=null&&n.onCustomEvent)||!(s!=null&&s.userId)||!st(m,s.userId))return;const f=m.messageId;if(Me.isStreaming(m)){i.current.add(f);return}h==="updated"&&!i.current.has(f)||(r.debug("useCustomEventForMessageReceive: bot-message-received",m),n.onCustomEvent({type:"bot-message-received",data:{message:m}}),i.current.delete(f))},u=l.useCallback(m=>{if(n!=null&&n.onCustomEvent&&m.isAdminMessage()&&m.customType==="user_action_required"&&!o.current.has(m.messageId)){const h=Yo(m.data);Array.isArray(h.history)&&h.history.length===0&&(r.debug("useCustomEventForMessageReceive: user_action_required",h),n.onCustomEvent({type:"user-action-requested",data:h}),o.current.add(m.messageId))}},[n,r]),d=(m,h,f)=>{m.url===e&&(c(h,f),u(h))};return ht(t,{onMessageReceived:(m,h)=>d(m,h,"received"),onMessageUpdated:(m,h)=>d(m,h,"updated")}),{checkForUserActionRequired:u}},om=e=>{if(e==null||typeof e!="object")return;const t="thinking_message"in e?e.thinking_message:void 0;return typeof t=="string"&&t?t:void 0},xi=e=>{const{aiAgentInfo:t}=ft(),n=Ai(e);if(He(e))return null;const r=n[0];if(!r)return null;const s=r.userId===(t==null?void 0:t.userId),o=s?om(r.metaData):void 0;return{user:s?t:r,isBot:s,thinkingMessage:o}},im=(e,t,{enabled:n=!0,idleMs:r=1e3}={})=>{const s=l.useRef(null),o=l.useRef(t),i=l.useRef(t),c=l.useRef(!1);o.current=t,l.useEffect(()=>{if(s.current&&(clearTimeout(s.current),s.current=null),!n||!e){(c.current?i.current:o.current)(!1),c.current=!1,i.current=o.current;return}c.current=!0,i.current=o.current,i.current(!0),s.current=setTimeout(()=>{s.current=null,i.current(!1),c.current=!1,i.current=o.current},r)},[n,r,e]),l.useEffect(()=>()=>{s.current&&(clearTimeout(s.current),s.current=null),(c.current?i.current:o.current)(!1),c.current=!1,i.current=o.current},[])},am=(e=1e4)=>{const t=new Map;let n=e;return{shouldAnnounce:c=>{const u=Date.now(),d=t.get(c);return d!==void 0&&u-d<n?!1:(t.set(c,u),!0)},setInterval:c=>{n=c},reset:()=>{t.clear()}}},cm=(e,t,n=1e4,r=!0)=>{const s=l.useRef(null),o=l.useRef(null),i=l.useRef(!1);s.current||(s.current=am(n));const c=(e==null?void 0:e.nickname.trim())||null,u=(e==null?void 0:e.userId)??c;l.useEffect(()=>{var d;(d=s.current)==null||d.setInterval(n)},[n]),l.useEffect(()=>{var h;if(!r){i.current=!1,o.current=u;return}if(!u||!c){i.current=!1,o.current=null;return}const d=!i.current,m=o.current!==u;i.current=!0,o.current=u,!(!d&&!m)&&(h=s.current)!=null&&h.shouldAnnounce(u)&&t(c)},[u,c,r,t])},lm=({csat:e,csatPayload:t,isRenderableCSAT:n,isExpiredNow:r,announceStatus:s,onSubmittedAnnounced:o})=>{const i=(t==null?void 0:t.csat_submitted_label)??"",c=l.useRef(n&&typeof e=="number"),u=l.useRef(n&&r);l.useEffect(()=>{n&&i&&(typeof e!="number"||c.current||(c.current=!0,s&&(s({event:"csatSubmitted",submittedLabel:i}),o==null||o())))},[s,e,n,o,i]),l.useEffect(()=>{n&&r&&(u.current||(u.current=!0,s==null||s({event:"csatExpired"})))},[s,r,n])},Br=({channel:e,userSession:t,aiAgentInfo:n})=>{if(!t||!n||!e)return{fallbackIcon:"delight",url:void 0,title:""};const r=si(e,t.userId),s={ai(o){return{fallbackIcon:o,url:n.profileUrl,title:n.nickname}},human(o){return{fallbackIcon:o,url:r==null?void 0:r.profileUrl,title:(r==null?void 0:r.nickname)||n.nickname}},channel(o){return{fallbackIcon:o,url:e==null?void 0:e.coverUrl,title:(e==null?void 0:e.name)??""}}};return e.isAIAgent?rt(e)?s.human("agent"):s.ai("delight"):e.isDesk?s.human("agent"):s.channel("user")},Gs=e=>l.useReducer((t,n)=>({...t,...n}),e);var Je=(e=>(e.AI_AGENT_CSAT_5="AI_AGENT_CSAT_5",e.AI_AGENT_CSAT_5_WITH_CRE="AI_AGENT_CSAT_5_WITH_CRE",e.HELPDESK_CSAT_5="HELPDESK_CSAT_5",e))(Je||{});const um=new Set(["free_text","single_choice"]),dm=({csatPayload:e,type:t,initialCsat:n,initialCsatReason:r,initialIsResolved:s})=>{const[o,i]=Gs({csatType:t,csat:n,csatReason:r,isResolved:s}),[c,u]=Gs({followUpItem:!1}),d=l.useMemo(()=>{var b;const g=o.csat,_=typeof g=="number",y=(b=e.follow_up)==null?void 0:b.find(p=>_?p.scores.includes(g):p.always_visible??!1);if(um.has(y==null?void 0:y.response_type))return y},[o.csat,e.follow_up]),m=(()=>{var g;if(typeof n=="number")return"submitted";if((t===Je.AI_AGENT_CSAT_5||t===Je.HELPDESK_CSAT_5)&&typeof o.csat=="number")return"submittable";if(t===Je.AI_AGENT_CSAT_5_WITH_CRE){const _=typeof o.csat=="number",y=!((g=e.cre)!=null&&g.required)||typeof o.isResolved=="boolean";if(_&&y)return"submittable"}return"unsubmittable"})(),h=l.useCallback(()=>typeof o.csat>"u"?!1:d!=null&&d.required&&!o.csatReason?(u({followUpItem:!0}),!1):!0,[o,d,u]);return l.useEffect(()=>{r||(i({csatReason:""}),u({followUpItem:!1}))},[r,d,i,u]),{params:o,setParams:i,error:c,setError:u,followUpItem:d,state:m,validateParams:h,itemProps:{csatPayload:e,state:m,submitted:m==="submitted"}}},mm=({csat:e,csatExpireAt:t,csatPayload:n,isSubmitInFlight:r=!1})=>{const s=!!n&&n.visibility&&!!Je[n.type],o=!r&&typeof e!="number"&&oi(t),i=Nn();return l.useEffect(()=>{if(!s||typeof e=="number"||t==null||o)return;const c=t-Date.now();if(c<=0&&r)return;const u=setTimeout(i,Math.max(0,c));return()=>clearTimeout(u)},[i,e,t,o,s,r]),{isRenderableCSAT:s,isExpiredNow:o}},Zn=5,Nt=250,hm=50,zs=e=>Math.max(0,e-hm),gn=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():0,fm=e=>e<1e3?{speed:Zn*.5,chunkSize:2}:e<2e3?{speed:Zn*.8,chunkSize:2}:{speed:Zn*.6,chunkSize:3},pn=(e,t)=>{let n=0;for(let r=t-1;r>=0&&e[r]==="\\";r--)n++;return n%2===1},Vs=(e,t,n,r)=>{let s=1,o=t;for(;o<e.length&&s>0;){if(pn(e,o)){o++;continue}e[o]===n?s++:e[o]===r&&s--,o++}return s>0?-1:o},Ri=(e,{hideImages:t,hideLinks:n})=>{let r="",s=0,o=0;for(;s<e.length;){if(e[s]==="`"&&!pn(e,s)){let h=1;for(;e[s+h]==="`";)h++;o===0?o=h:h===o&&(o=0),r+=e.slice(s,s+h),s+=h;continue}const i=e[s]==="!"&&e[s+1]==="["&&!pn(e,s),c=e[s]==="["&&!pn(e,s);if(o>0||!i&&!c){r+=e[s],s++;continue}if(i?!t:!n){const h=i?"![":"[";r+=h,s+=h.length;continue}const u=s,d=Vs(e,s+(i?2:1),"[","]");if(d===-1)return r;if(s=d,e[s]!=="("){r+=e.slice(u,s);continue}const m=Vs(e,s+1,"(",")");if(m===-1)return r;s=m,r+=e.slice(u,s)}return r},gm=({trackedRef:e,onVisibleTextProgress:t,onRenderedTextProgress:n})=>{const r=l.useRef(t),s=l.useRef(n),o=l.useRef(null),i=l.useRef({lastLength:0,lastReportedAt:0}).current,c=l.useRef({lastLength:0,lastReportedAt:0,lastCheckedAt:0}).current,u=l.useRef(null);l.useLayoutEffect(()=>{r.current=t,s.current=n});const d=l.useCallback(S=>{var A;(A=r.current)==null||A.call(r,S)},[]),m=l.useCallback(S=>{const A=e.initialEnabled&&(e.enabled||S<e.textLength),T=A&&e.deferImages,R=A&&e.deferLinks;return!T&&!R?S:Ri(e.text.slice(0,S),{hideImages:T,hideLinks:R}).length},[e]),h=l.useCallback((S,A,T=!1)=>{r.current&&(S<=c.lastLength||!T&&A-c.lastReportedAt<Nt||(c.lastLength=S,c.lastReportedAt=A,d(S)))},[d,c]),f=l.useCallback((S,A,T=!1)=>{if(!r.current)return;const R=Math.max(c.lastReportedAt,c.lastCheckedAt);!T&&A-R<Nt||(c.lastCheckedAt=A,h(m(S),A,!0))},[m,h,c]),g=l.useCallback((S,A,T=!1)=>{s.current&&(S<=i.lastLength||!T&&A-i.lastReportedAt<Nt||(i.lastLength=S,i.lastReportedAt=A,s.current(S)))},[i]),_=l.useCallback((S,A,T)=>{const R=S>=A,L=T-i.lastReportedAt>=Nt;if(!R&&!L)return;const D=m(S);g(D,T,R)},[m,i,g]),y=l.useCallback(()=>{c.lastLength=0,c.lastReportedAt=0,c.lastCheckedAt=0,i.lastLength=0,i.lastReportedAt=0},[i,c]),b=l.useCallback(S=>{r.current&&(o.current!==null&&S<=o.current||(o.current=S,d(S)))},[d]),p=l.useCallback(({displayedLength:S,streamTextLength:A})=>{const T=u.current;if(u.current={displayedLength:S,streamTextLength:A},!e.initialEnabled||!T||S>T.displayedLength||A<=T.streamTextLength)return;const R=gn();h(A,R,!0),g(A,R,!0)},[u,g,h,e]);return{resetProgress:y,reportVisibleTextProgress:f,reportRenderedTextProgress:_,reportNonStreamingVisibleTextProgress:b,reportMarkdownRevealProgress:p}},pm=e=>{const{text:t,enabled:n=!1,snapOnDisable:r=!1,deferredMarkdownElements:s=[],onAnimationStart:o,onAnimationProgress:i,onAnimationComplete:c,onVisibleTextProgress:u,onRenderedTextProgress:d}=e,m=s.includes("image"),h=s.includes("link"),[f,g]=l.useState(()=>zs(t.length)),_=l.useRef(null),y=l.useRef({startTime:0,lastUpdate:0,lastProgressCall:0}).current,b=l.useRef({startCalled:!1,completeCalled:!1}).current,p=l.useRef({initialEnabled:n,textLength:t.length,enabled:n,text:t,deferImages:m,deferLinks:h,snapOnDisable:r}).current,S=ie(()=>o==null?void 0:o()),A=ie(()=>i==null?void 0:i()),T=ie(()=>c==null?void 0:c()),{resetProgress:R,reportVisibleTextProgress:L,reportRenderedTextProgress:D,reportNonStreamingVisibleTextProgress:k,reportMarkdownRevealProgress:M}=gm({trackedRef:p,onVisibleTextProgress:u,onRenderedTextProgress:d}),P=n,F=f<t.length,Y=p.initialEnabled&&(P||F);l.useLayoutEffect(()=>{p.textLength=t.length,p.enabled=n,p.text=t,p.deferImages=m,p.deferLinks=h,p.snapOnDisable=r}),l.useLayoutEffect(()=>{if(p.initialEnabled){if(b.startCalled||(b.startCalled=!0,S()),!p.enabled&&p.snapOnDisable){g(t.length);const N=gn();L(t.length,N,!0),D(t.length,t.length,N);return}g(N=>t.length<N?t.length:N)}},[S,D,L,t]),l.useEffect(()=>{if(!p.initialEnabled)return;let N=zs(t.length);y.lastUpdate=0,y.startTime=0,y.lastProgressCall=0,R();const B=U=>{y.lastUpdate===0&&(y.lastUpdate=U,y.startTime=U,y.lastProgressCall=U,N>0&&L(N,U,!0));const V=p.textLength;!p.enabled&&p.snapOnDisable&&N<V&&(N=V,g(N),L(N,U,!0),D(N,V,U));const ce=U-y.lastUpdate,Ie=U-y.startTime,{speed:X,chunkSize:K}=fm(Ie),I=X*K;ce>=I&&N<V&&(N=Math.min(N+K,V),g(N),L(N,U,N>=V),D(N,V,U),y.lastUpdate=U),U-y.lastProgressCall>=Nt&&(y.lastProgressCall=U,A()),(N<V||p.enabled)&&(_.current=requestAnimationFrame(B))};return _.current=requestAnimationFrame(B),()=>{_.current&&cancelAnimationFrame(_.current),b.startCalled&&!b.completeCalled&&(b.completeCalled=!0,T())}},[T,A,D,L,R]),l.useEffect(()=>{p.initialEnabled&&(n||t.length>0)||(k(t.length),D(t.length,t.length,gn()))},[n,d,u,k,D,t.length,p]),l.useEffect(()=>{const N=p.initialEnabled&&b.startCalled,B=!n,U=f>=t.length;N&&B&&U&&!b.completeCalled&&(b.completeCalled=!0,T())},[n,f,T,t.length]);const j=l.useMemo(()=>{const N=p.initialEnabled?t.slice(0,f):t,B=Y&&m,U=Y&&h;return!B&&!U?N:Ri(N,{hideImages:B,hideLinks:U})},[t,f,m,h,Y]);return l.useEffect(()=>{!p.initialEnabled||Y||L(f,gn(),!0)},[f,Y,L]),l.useEffect(()=>{M({displayedLength:f,streamTextLength:j.length})},[f,M,j.length]),{streamText:j,isAnimating:Y}},qs={visible:!1,remainingTime:0,showDescription:!1,targetTimeMs:null},_m=e=>({visible:!0,remainingTime:e,showDescription:!0,targetTimeMs:Date.now()+e*1e3}),Em=(e,t=Date.now())=>{if(!e.visible||e.targetTimeMs==null)return e;const n=Math.max(Math.ceil((e.targetTimeMs-t)/1e3),0);return n<=0?{...e,remainingTime:0,showDescription:!1,targetTimeMs:null}:e.remainingTime===n&&e.showDescription?e:{...e,remainingTime:n,showDescription:!0}},Cm=()=>{const{chatSDK:e}=ke(),[t,n]=l.useState(qs),r=()=>n(qs);return Xt(e,{onConnectionDelayed:s=>{s>0?n(_m(s)):r()},onReconnectSucceeded:r,onConnected:r}),l.useEffect(()=>{if(!t.visible||!t.showDescription||t.targetTimeMs==null)return;const s=setTimeout(()=>{n(o=>Em(o))},1e3);return()=>clearTimeout(s)},[t.visible,t.showDescription,t.targetTimeMs,t.remainingTime]),{visible:t.visible,remainingTime:t.remainingTime,showDescription:t.showDescription}},bm=e=>{const t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`},vm=(e,t)=>{if(!t)return{beforeText:e,highlightedText:"",afterText:""};const n=e.indexOf(t);return n<0?{beforeText:e,highlightedText:"",afterText:""}:{beforeText:e.slice(0,n),highlightedText:t,afterText:e.slice(n+t.length)}},ym=({enabled:e=!0}={})=>{const t=jt();return l.useCallback(({message:n,isBotMessage:r,aiAgentUserId:s})=>{if(!e)return;const o=n.messageId,i=Me.isStreaming(n),c=kn(n.extendedMessagePayload),u=c.hasMessageTemplate,d=c.hasForm,m=r&&n.isUserMessage()&&!i&&!Ic(n)&&!Me.isWelcomeMessage(n,s),h=i||t.streamStalled.hasPendingStream(o),f=t.userPerceivedResponseTime.hasPendingAIResponse(o);if(!h&&!f&&!m&&!u&&!d)return;let g=!1,_=!1;const y={};return(f||m)&&(y.onVisibleTextProgress=()=>{f&&!g&&(g=t.userPerceivedResponseTime.markAIResponseVisible(o)),m&&!_&&(_=!0,t.renderedContentUnusable.commit({messageId:o,contentKind:"text",errorDomain:"empty_render"}))}),h&&(y.onRenderedTextProgress=b=>{t.streamStalled.markRenderedProgress({messageId:o,displayedLength:b})}),u&&(y.onMessageTemplateError=b=>{t.renderedContentUnusable.commit({messageId:o,contentKind:"template",errorDomain:"template_error",error:b})}),d&&(y.onFormRenderError=b=>{t.renderedContentUnusable.commit({messageId:o,contentKind:"form",errorDomain:"form_error",error:b})}),y},[e,t])},Sm=e=>{const t=l.useRef(!1);l.useEffect(()=>{t.current||e!=null&&e.onVisibleTextProgress&&(t.current=!0,e.onVisibleTextProgress(0))},[e])},Jn=5e3,cn=()=>vn.now(),Am=({channelUrl:e,enabled:t=!0,isInitiallyBackgrounded:n,isForegrounded:r,subscribeToForegroundState:s})=>{const o=jt(),i=l.useRef(t),c=l.useRef(n),u=l.useRef(t&&n()?cn()-Jn:null),d=l.useRef(!1);i.current=t,c.current=n;const m=l.useCallback((h=r())=>{if(!i.current){d.current=!1;return}if(!h){d.current=!1;return}if(u.current===null){d.current=!1;return}if(cn()-u.current<Jn){u.current=null,d.current=!1;return}if(!e){d.current=!0;return}u.current=null,d.current=!1,o.recoveryNotInteractiveTimeout.start("foreground_resume",e)},[e,r,o]);l.useEffect(()=>{t||(u.current=null,d.current=!1,e&&o.recoveryNotInteractiveTimeout.cancelPending(e))},[e,t,o]),l.useEffect(()=>{if(!t)return;d.current&&!!e&&r()&&m()},[e,t,r,m]),l.useEffect(()=>{if(t)return c.current()?u.current??(u.current=cn()-Jn):u.current=null,s(h=>{if(h==="backgrounded"){u.current??(u.current=cn()),d.current=!1,e&&o.recoveryNotInteractiveTimeout.cancelPending(e);return}m(!0)})},[e,t,m,o,s])},Tm=e=>{const{conversationInitialRender:t,conversationListInitialRender:n}=jt();l.useLayoutEffect(()=>{t.setPresentMethod(e),n.setPresentMethod(e)},[t,n,e])},Im=(e,{enabled:t=!0,opened:n=!1,filter:r}={})=>{var u,d,m;const[s,o]=l.useState(!1),i=l.useRef(0),c=()=>{if(!t)return;const h=++i.current;e.aiAgent.getUnreadMessageCount(r).then(f=>{h===i.current&&o(f.total>0)}).catch(()=>{})};return l.useEffect(()=>{if(!t){o(!1),i.current++;return}e.connectionState===de.ConnectionState.OPEN&&c()},[t,e,r==null?void 0:r.aiAgentChannelFilter,(u=r==null?void 0:r.aiAgentConversationStatusFilter)==null?void 0:u.join(),(d=r==null?void 0:r.aiAgentIds)==null?void 0:d.join(),r==null?void 0:r.deskChannelFilter,(m=r==null?void 0:r.pinnedChannelUrls)==null?void 0:m.join(),r==null?void 0:r.copilotConversationOnly,r==null?void 0:r.copilotSupportChannelUrl]),l.useEffect(()=>{n&&(o(!1),i.current++)},[n]),Xt(e,{onConnected:c,onReconnectSucceeded:c}),s},Hr=e=>e.replace(/\s+/g," ").trim(),xm="Code block",Mi=e=>`A11Y_INLINE_CODE_${e}`,wi=e=>{let t="",n=e;for(;;){const r=n.match(/^([ \t]{0,3}>\s?)(.*)$/);if(r){t+=r[1],n=r[2];continue}break}return{blockquotePrefix:t,content:n}},ki=e=>{const t=e.match(/^([ \t]{0,3}[-+*]\s+)(.*)$/);if(t)return{content:t[2],hasListPrefix:!0};const n=e.match(/^([ \t]{0,3}\d+[.)]\s+)(.*)$/);return n?{content:n[2],hasListPrefix:!0}:{content:e,hasListPrefix:!1}},Rm=e=>{const{blockquotePrefix:t,content:n}=wi(e),{content:r}=ki(n),s=r.match(/^[ \t]{0,3}([`~]{3,})(.*)$/);if(!s)return;const o=s[1],i=s[2],c=o[0];if(!(c!=="`"&&c!=="~"||!o.split("").every(u=>u===c))&&!(c==="`"&&i.includes("`")))return{char:c,blockquotePrefix:t,length:o.length}},Mm=(e,t)=>{const{blockquotePrefix:n,content:r}=wi(e);if(n!==t.blockquotePrefix)return!1;const{content:s,hasListPrefix:o}=ki(r);if(o)return!1;const i=s.match(/^[ \t]{0,3}([`~]{3,})[ \t]*$/);if(!i)return!1;const c=i[1];return c[0]===t.char&&c.length>=t.length&&c.split("").every(u=>u===t.char)},wm=(e,t,n)=>{let r=n;for(;r<e.length;){const s=e[r];if(s==="\\"&&r+1<e.length){r+=2;continue}if(s===t)return r;r+=1}return-1},km=(e,t)=>{let n=1,r=t;for(;r<e.length;){const s=e[r];if(s==="\\"&&r+1<e.length){r+=2;continue}if(s==="["){n+=1,r+=1;continue}if(s==="]"&&(n-=1,n===0))return r;r+=1}return-1},Lm=(e,t)=>{let n=t,r=1,s,o=!1,i=!1;for(;n<e.length&&r>0;){const c=e[n];if(c==="\\"&&n+1<e.length){n+=2;continue}if(s){c===s&&(s=void 0),n+=1;continue}if(r===1&&o&&/\s/.test(c)){i=!0,n+=1;continue}if(r===1&&i&&(c==='"'||c==="'")){s=c,n+=1;continue}if(c==="("){r+=1,o=!0,n+=1;continue}if(c===")"){r-=1,n+=1;continue}/\s/.test(c)||(o=!0),n+=1}return r===0?n:-1},Om=e=>{let t=0,n="";for(;t<e.length;){const r=wm(e,"[",t);if(r===-1){n+=e.slice(t);break}const s=km(e,r+1);if(s===-1){n+=e.slice(t);break}if(r>0&&e[r-1]==="!"&&Tn(e,r-1)){n+=e.slice(t,s+1),t=s+1;continue}if(e[s+1]!=="("){n+=e.slice(t,s+1),t=s+1;continue}const o=r>0&&e[r-1]==="!"&&!Tn(e,r-1)?r-1:r;n+=e.slice(t,o);const i=e.slice(r+1,s),c=Lm(e,s+2);if(c===-1){n+=e.slice(o);break}n+=i,t=c}return n},Li=(e,t,n)=>{if(!/^\d+$/.test(t))return!1;const r=e.slice(-1);return/\d/.test(r)&&/\d/.test(n)},Nm=e=>e.replace(/(^|[^*\\])\*\*([^\s*](?:[\s\S]*?[^\s*])?)\*\*(?!\*)/g,(t,n,r,s,o)=>{const i=o[s+t.length]??"";return Li(n,r,i)?t:`${n}${r}`}),Dm=e=>e.replace(/(^|[^_\\])__([^\s_](?:[\s\S]*?[^\s_])?)__(?!_)/g,"$1$2"),$m=e=>e.replace(/(^|[^~\\])~~([^\s~](?:[\s\S]*?[^\s~])?)~~(?!~)/g,"$1$2"),Fm=e=>{let t=e;return t=t.replace(/(^|[^*\\])\*([^\s*](?:[\s\S]*?[^\s*])?)\*(?!\*)/g,(n,r,s,o,i)=>{const c=i[o+n.length]??"";return Li(r,s,c)?n:`${r}${s}`}),t=t.replace(/(^|[\s([{"'])_([^_\s](?:[\s\S]*?[^_\s])?)_(?=$|[\s)\]}"'.,!?:;])/g,"$1$2"),t},Pm=e=>e.replace(/\\([\\`*_[\]()#+.!~|-])/g,"$1"),Um=e=>{let t=e;return t=t.replace(/^\s{0,3}#{1,6}\s+/gm,""),t=t.replace(/^\s{0,3}>\s?/gm,""),t=t.replace(/^\s{0,3}(?!([-*_])(?:\s*\1){2,}\s*$)[-*+]\s+/gm,""),t=t.replace(/^\s{0,3}\d+[.)]\s+/gm,""),t},Ks=e=>{const t=e.trim();if(!t.includes("|"))return!1;const n=t.split("|").map(r=>r.trim()).filter(Boolean);return n.length===0?!1:n.every(r=>/^:?-{3,}:?$/.test(r))},Ys=e=>{const t=[];let n="",r=!1;for(const o of e.trim()){if(r){n+=o==="|"?"|":`\\${o}`,r=!1;continue}if(o==="\\"){r=!0;continue}if(o==="|"){const i=n.trim();i&&t.push(i),n="";continue}n+=o}r&&(n+="\\");const s=n.trim();return s&&t.push(s),t},Bm=e=>{const t=e.split(`
|
|
2
2
|
`),n=[];let r=0;for(;r<t.length;){const s=t[r],o=t[r+1],i=Ys(s);if(i.length>0&&o&&Ks(o)){for(n.push(i.join(" ")),r+=2;r<t.length;){const c=t[r],u=Ys(c);if(u.length===0||Ks(c))break;n.push(u.join(" ")),r+=1}continue}n.push(s),r+=1}return n.join(`
|
|
3
3
|
`)},Hm=e=>e.replace(/^\s{0,3}(?:(?:-\s*){3,}|(?:\*\s*){3,}|(?:_\s*){3,})$/gm,""),Gm=(e,t)=>{const n=e.split(`
|
|
4
4
|
`),r=[];let s=0;for(;s<n.length;){const o=n[s],i=Rm(o);if(!i){r.push(o),s+=1;continue}let c=-1;for(let u=s+1;u<n.length;u++)if(Mm(n[u],i)){c=u;break}if(c===-1){r.push(o),s+=1;continue}r.push(` ${t} `),s=c+1}return r.join(`
|
|
5
5
|
`)},Tn=(e,t)=>{let n=0,r=t-1;for(;r>=0&&e[r]==="\\";)n+=1,r-=1;return n%2===1},zm=e=>{const t=[];let n=0,r="";for(;n<e.length;){const s=e[n];if(s!=="`"||Tn(e,n)){r+=s,n+=1;continue}let o=n;for(;o<e.length&&e[o]==="`";)o+=1;const i=e.slice(n,o);let c=o,u=!1;for(;c<e.length&&e[c]!==`
|
|
6
6
|
`;){if(e[c]==="`"&&!Tn(e,c)&&e.startsWith(i,c)){const d=e.slice(o,c),m=t.push(d)-1;r+=Mi(m),n=c+i.length,u=!0;break}c+=1}u||(r+=i,n=o)}return{text:r,inlineCodes:t}},Oi=(e,{codeBlockPlaceholder:t=xm}={})=>{const n=e==null?void 0:e.replace(/\r\n?/g,`
|
|
7
|
-
`);if(!n)return;const r=[];let s=n;s=Gm(s,t),s=Um(s);const o=zm(s);s=o.text,r.push(...o.inlineCodes),s=Om(s),s=Nm(s),s=Dm(s),s=$m(s),s=Fm(s),s=Bm(s),s=Hm(s),s=Pm(s);for(let c=0;c<r.length;c++)s=s.replaceAll(Mi(c),r[c]);return Hr(s)||void 0},Vm=(e,t)=>{var s;const n=((s=e.name)==null?void 0:s.trim())||"",r=e.mimeType??"";return Ye(r)?t.image:zt(r)?t.video:Qo({name:n,mimeType:r})?t.pdf(n):t.document(n)},In=e=>(e==null?void 0:e.trim())||"",qm=e=>(e?Hr(e):void 0)||void 0,Ni=e=>({text:In(e),format:"plain"}),Km=e=>({text:In(e),format:"markdown"}),Qn=({markdownText:e,plainText:t,comparisonText:n})=>{const r=In(e);return r&&r!==In(n)?Km(r):Ni(t)},Dt=({sender:e,message:t,messageFormat:n="plain",time:r,codeBlockPlaceholder:s})=>{const o=[],i=n==="markdown"?Oi(t,{codeBlockPlaceholder:s}):qm(t);if(r&&o.push(r),e&&o.push(e),i&&o.push(i),o.length!==0)return o.join(", ")},Di=(e,t)=>Oi(e==null?void 0:e.trim(),t!==void 0?{codeBlockPlaceholder:t}:void 0),Ym=(...e)=>Hr(e.filter(Boolean).join(", "))||void 0,Ws=(e,t,n,r)=>{if(!t||t===n)return e;const s=Di(t,r);return s?Ym(e,s):e},Wm=(e,t)=>{var r,s,o,i;const n=(r=e.message)==null?void 0:r.trim();if(e.isFileMessage()){const c=((s=e.name)==null?void 0:s.trim())||"",u=Vm({name:c,mimeType:e.type},t);return Ws(u,n,c,t.codeBlockPlaceholder)}if(e.isMultipleFilesMessage()){const c=e.fileInfoList??[],u=c.length;if(u===0)return;const d=((i=(o=c[0])==null?void 0:o.fileName)==null?void 0:i.trim())||"",h=c.every(f=>{var g;return(g=f.mimeType)==null?void 0:g.startsWith("image")})?t.receivedFilesImageCount(u):t.multipleFilesCount(u);return Ws(h,n,d,t.codeBlockPlaceholder)}return Di(n,t.codeBlockPlaceholder)},jm=(e,t={})=>{const{throttleMs:n=1e3,isSuppressed:r,maxOrderedQueueSize:s=10}=t,o=Math.max(1,s);let i=null;const c=[];let u=null,d=null,m=null,h=!1,f=0;const g=(x,O,H)=>({text:x,ignoreSuppression:O,queueOrder:f++,dedupeKey:H}),C=()=>{const x=c[0]??null,O=i;return x&&O?O.queueOrder<x.queueOrder?(i=null,O):c.shift()??null:x?c.shift()??null:O!==null?(i=null,O):null},v=()=>{for(;;){const x=C();if(!x)return null;if(!(!x.ignoreSuppression&&(r!=null&&r())))return x}},_=x=>{u=x.text,d=x.dedupeKey??null,h=!0,e(x.text),m=setTimeout(()=>{m=null,h=!1;const O=v();O&&_(O)},n)},p=x=>{u=x.text,d=x.dedupeKey??null,e(x.text)},S=(x,O,H,F)=>O!=null&&F!=null?O===F:O==null&&F==null?x!=null&&x===H:!1,A=(x,O,H)=>{if(!x||!O&&(r!=null&&r()))return;const F=H==null?void 0:H.dedupeKey;if(!(h&&S(x,F,u,d)))if(h){if(((H==null?void 0:H.mode)??"latestOnly")==="ordered"){const q=c[c.length-1];if(q&&S(x,F,q.text,q.dedupeKey))return;c.push(g(x,O,F)),c.length>o&&c.shift();return}i=g(x,O,F)}else i=null,_(g(x,O,F))};return{announce:(x,O)=>{A(x,!1,O)},announceIgnoringSuppression:(x,O)=>{A(x,!0,O)},flush:()=>{const x=[];let O=C();for(;O!==null;)x.push(O),O=C();if(m!==null&&(clearTimeout(m),m=null),h=!1,x.length!==0)for(const H of x)p(H)},destroy:()=>{m!==null&&(clearTimeout(m),m=null),i=null,c.length=0,u=null,d=null,h=!1}}},Xm=e=>{switch(e){case"newMessage":case"conversationClosed":case"csatDisplayed":case"csatSubmitted":case"csatExpired":return"ordered";default:return"latestOnly"}},Zm=(e,t)=>e.screen==="conversationList"?typeof e.conversationCount=="number"?t.screenConversationListWithCount(e.conversationCount):t.screenConversationListNoCount:[e.agentName?t.screenConversationWithAgent(e.agentName):t.screenConversation,e.isClosed?t.conversationClosed:null,e.isClosed&&e.hasCSAT?t.csatDisplayed:null,e.isEmpty?t.emptyState:null].filter(r=>!!r).join(". "),Jm=(e,t)=>{switch(e.event){case"newMessage":return e.body!==void 0||e.time!==void 0?[t.newMessage(1),e.time,e.senderName,e.body].filter(r=>!!r).join(", "):e.senderName?t.newMessageFromSender(e.senderName,1):t.newMessage(1);case"typing":return t.typing(e.agentName??"");case"sendFailed":return t.sendFailed;case"agentConnected":return t.agentConnected(e.agentName??"");case"conversationClosed":return t.conversationClosed;case"csatDisplayed":return t.csatDisplayed;case"csatSubmitted":return e.submittedLabel;case"csatExpired":return t.csatExpired;case"emptyState":return t.emptyState;case"inputDisabled":return t.inputDisabled}},Qm=(e,t)=>{switch(e.type){case"fileSizeExceeded":return t.fileSizeExceeded(e.maxSizeMB??25);case"sendFailed":return t.sendFailed;case"csatFormError":return t.csatFormError;case"generic":return e.message}},eh=(e,t)=>!t||!Qe(e)||e.sender.userId!==t?null:e.reqId||(e.messageId>0?String(e.messageId):null),th=(e,t)=>Ne.isAdmin(e)?Ne.isCSAT(e):"sender"in e?e.sender.userId!==t:!1,nh=e=>"messageId"in e&&e.messageId>0?String(e.messageId):"reqId"in e&&typeof e.reqId=="string"&&e.reqId.length>0?e.reqId:null,rh=e=>e===ue.CollectionEventSource.EVENT_MESSAGE_RECEIVED||e===ue.CollectionEventSource.EVENT_MESSAGE_UPDATED,sh=({isOpened:e,opensConversationList:t})=>e?t?"closeConversationList":"closeConversation":t?"openConversationList":"openConversation",oh=(e,t)=>{switch(e){case"closeConversationList":return t.closeConversationList;case"closeConversation":return t.closeConversation;case"openConversationList":return t.openConversationList;case"openConversation":return t.openConversation}},ih=(e,t)=>{switch(e){case"closeConversation":return t.hintCloseConversation;case"openConversationList":return t.hintOpenConversationList;case"openConversation":return t.hintOpenConversation;default:return}},ah=({intent:e,strings:t})=>({label:oh(e,t),hint:ih(e,t)}),ch="1.35.0",Ge="sb-agent",ye={ENTRY:`${Ge}-entry`,MODAL_ROOT:`${Ge}-modal-root`,WINDOW:`${Ge}-window`,LAUNCHER:`${Ge}-launcher`,WINDOW_TITLE:`${Ge}-window-title`},$i="data-sb-initial-focus",Fi="true",lh=`[${$i}="${Fi}"]`,Pi={[$i]:Fi},Gr="data-sb-focus-trap-sentinel",uh="true",Ui="data-sb-initial-focus-header",Bi="true",dh=`[${Ui}="${Bi}"]`,Hi={[Ui]:Bi},Gi="data-sb-message-input",zi="true",mh=`textarea[${Gi}="${zi}"]:not(:disabled)`,hh={[Gi]:zi},Vi=1e3,ln=2147483647,gt={MODAL:ln-1,TOOLTIP:ln-2,WINDOW:ln-3,LAUNCHER:ln-4},qi=36,fh=100,gh=ch,zr="noopener noreferrer nofollow",hr=()=>typeof document>"u"||document.visibilityState==="visible",js=()=>typeof document<"u"&&document.visibilityState==="hidden",ph=e=>{if(hr()){e();return}if(typeof document>"u")return;const t=()=>{hr()&&(document.removeEventListener("visibilitychange",t),e())};return document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t)};function _h(){return{isOnline:()=>navigator.onLine,subscribe:e=>{const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t),window.addEventListener("offline",n),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}const un={};function Eh(){return{get:e=>{try{return localStorage.getItem(e)}catch{return un[e]??null}},set:(e,t)=>{try{localStorage.setItem(e,t)}catch{un[e]=t}},delete:e=>{try{localStorage.removeItem(e)}catch{delete un[e]}},getKeys:e=>{try{const t=[];for(let n=0;n<localStorage.length;n++){const r=localStorage.key(n);r&&r.startsWith(e)&&t.push(r)}return t}catch{return Object.keys(un).filter(t=>t.startsWith(e))}}}}const Ch={conversation:{input_placeholder:"Ask a question",input_placeholder_disabled:"Chat is unavailable in this channel",input_placeholder_steward:"Processing your request...",input_placeholder_wait_ai_agent_response:"Waiting for the agent's reply...",input_placeholder_active_form:"Please fill out the form to move forward.",input_placeholder_reconnecting:"Trying to reconnect. Refresh if persists.",unknown_message_type:"(Unknown message type)",powered_by:"Powered by",citation_title:"Source",start_new_conversation_label:"Start a conversation",scroll_to_new_messages_label:()=>"New message",failed_message_resend:"Retry",failed_message_remove:"Remove",file_upload_no_supported_files:"No supported file types available.",file_upload_replace_alert_title:"Replace attachment?",file_upload_replace_alert_description:"Uploading a different file type will replace the current one.",a11y_message_list:"Chat messages",a11y_scroll_to_bottom:"Scroll to bottom",a11y_scroll_to_new_messages:"Scroll to new messages",a11y_open_conversation_list:"Open conversation list",a11y_open_conversation:"Open conversation with Support",a11y_open_conversations:"Open conversations",a11y_close_conversation:"Close conversation",a11y_close_conversations:"Close conversations",a11y_menu:"Menu",a11y_message_input:"Message",a11y_send_message:"Send message",a11y_attach_file:"Attach file",a11y_close_messenger:"Close messenger",a11y_expand_messenger:"Expand messenger",a11y_collapse_messenger:"Collapse messenger",a11y_connect_agent:"Talk to human agent",a11y_message_sender_you:"You",a11y_suggested_reply:"Suggested reply",a11y_typing_indicator:"Typing",a11y_code_block_placeholder:"Code block",a11y_typing_format:e=>`${e} is typing`,a11y_message_failed:"Message send failed",a11y_new_messages_received:e=>`${e} new ${e===1?"message":"messages"} received`,a11y_new_messages_received_from_sender:(e,t)=>`${e}: ${t} new ${t===1?"message":"messages"} received`,a11y_agent_connected:e=>"Connected to human agent",a11y_conversation_closed:"Conversation has ended",a11y_file_image:e=>`Image file: ${e}`,a11y_file_video:e=>`Video file: ${e}`,a11y_file_pdf:e=>`PDF file: ${e}`,a11y_file_document:e=>`Document file: ${e}`,a11y_received_file_image:"Image file",a11y_received_file_video:"Video file",a11y_received_file_pdf:e=>`PDF file: ${e}`,a11y_received_files_image_count:e=>`${e} ${e===1?"image":"images"}`,a11y_screen_conversation:"Conversation",a11y_screen_conversation_with_agent:e=>`Conversation with ${e}`,a11y_screen_conversation_list_no_count:"Conversation list",a11y_screen_conversation_list_with_count:e=>`Conversations, ${e} total`,a11y_csat_displayed:"Satisfaction survey displayed",a11y_empty_conversation:"No messages in this conversation",a11y_input_disabled:"Message input is disabled",a11y_file_size_exceeded:e=>`File exceeds size limit of ${e}MB`,a11y_csat_form_error:"Please complete the required fields",a11y_hint_send_message:"Sends the message",a11y_hint_open_conversation:"Opens the conversation",a11y_hint_open_conversations:"Opens conversations",a11y_hint_close_conversation:"Closes the conversation",a11y_hint_close_messenger:"Closes the messenger",a11y_hint_open_menu:"Opens the menu",a11y_hint_connect_to_agent:"Escalates to a human agent",a11y_hint_attach_file:"Opens file attachment options",a11y_hint_view_new_messages:"Scrolls to new messages",a11y_hint_open_file:"Opens the file",a11y_hint_open_image:"Opens the image",a11y_hint_send_reply:"Sends this reply",image_viewer_default_title:"Image",a11y_image_viewer_close:"Close image viewer",a11y_image_viewer_previous:"Previous image",a11y_image_viewer_next:"Next image",a11y_image_viewer_download:"Download image",attachment_document:"Files"},conversation_list:{header_title:"Conversations",ended:"Ended",system_message:"System message",footer_title:"Start a conversation",multiple_files_count:e=>`${e} ${e===1?"file":"files"}`,a11y_conversation_item:(e,t,n,r)=>`${e}, ${t}, ${n}${r>0?`, ${r} unread ${r===1?"message":"messages"}`:""}`},date_format:{just_now:"Just now",minutes_ago:e=>`${e} minutes ago`,hours_ago:e=>`${e} hours ago`,date_short:"MM/dd/yyyy",date_separator:"MMMM dd, yyyy",message_timestamp:"p"},csat:{title:"Your feedback matters to us",submitted_label:"Successfully submitted!",cre_question:"Was your issue resolved?",cre_positive_label:"Yes, thank you! 👍",cre_negative_label:"No, that didn't help.",reason_placeholder:"Share your feedback",question:"How would you rate your experience?",submit_label:"Submit",submission_expired:"We're sorry, the survey period has ended.",a11y_csat_rating_label:(e,t)=>`${e} out of 5 — ${t}`,a11y_hint_select_rating:"Selects this rating"},form:{optional_label:"optional",validation_required:"This question is required"},common:{placeholder_something_went_wrong:"Something went wrong",placeholder_no_messages:"No messages",placeholder_no_conversations:"No conversations yet",placeholder_something_went_wrong_retry_label:"Retry",button_ok:"OK",button_cancel:"Cancel"},feedback:{title:"Submit feedback",good:"Good",bad:"Bad",comment_label:"Comment (optional)",comment_placeholder:"Leave a comment",cancel:"Cancel",submit:"Submit",save:"Save",edit:"Edit feedback",remove:"Remove feedback"},handoff:{confirm_title:"Request handoff?",confirm_description:"You'll be transferred to a human agent. Your conversation history will be shared.",confirm_cancel:"Cancel",confirm_handoff:"Handoff"},memory:{dialog_title:"Memory",desc_on:"Memory is **turned on**. It remembers your conversation history to provide personalized responses tailored to your previous questions and preferences.",desc_off:"Memory is **turned off**. If turned on, it will remember your conversation history to provide personalized responses tailored to your previous questions and preferences.",button_use:"Use",button_dont_use:"Don't use",button_keep_using:"Keep using",button_disable:"Disable",button_disable_and_delete:"Disable & Delete memory",button_keep_off:"Keep off",button_enable:"Enable memory",button_cancel:"Cancel",error_message:"Failed to update memory state. Please try again.",a11y_indicator_manage:"Manage memory",a11y_indicator_on:"Memory is on",a11y_indicator_off:"Memory is off"},connection_delay:{title:"Something went wrong. You'll be reconnected shortly.",description:e=>`Estimated waiting time: ${e}`}},fr={language:"en",strings:Ch,dateLocale:lc.enUS},Ki=e=>({MESSAGE_INPUT__PLACE_HOLDER:e.conversation.input_placeholder,MESSAGE_INPUT__PLACE_HOLDER__DISABLED:e.conversation.input_placeholder_disabled,MESSAGE_INPUT__PLACE_HOLDER__STEWARD:e.conversation.input_placeholder_steward,MESSAGE_INPUT__PLACE_HOLDER__WAIT_AI_AGENT_RESPONSE:e.conversation.input_placeholder_wait_ai_agent_response,MESSAGE_INPUT__PLACE_HOLDER__RECONNECTING:e.conversation.input_placeholder_reconnecting,UNKNOWN__UNKNOWN_MESSAGE_TYPE:e.conversation.unknown_message_type,POWERED_BY:e.conversation.powered_by,CSAT_TITLE_UNSUBMITTED:e.csat.title,CSAT_TITLE_SUBMITTED:e.csat.submitted_label,CSAT_CRE_TITLE:e.csat.cre_question,CSAT_CRE_SOLVED:e.csat.cre_positive_label,CSAT_CRE_NOT_SOLVED:e.csat.cre_negative_label,CSAT_REASON_PLACEHOLDER:e.csat.reason_placeholder,CSAT_RATING_TITLE:e.csat.question,CSAT_SUBMIT_LABEL:e.csat.submit_label,CSAT_SUBMISSION_EXPIRED:e.csat.submission_expired,DATE_FORMAT__JUST_NOW:e.date_format.just_now,DATE_FORMAT__MINUTES_AGO:e.date_format.minutes_ago,DATE_FORMAT__HOURS_AGO:e.date_format.hours_ago,DATE_FORMAT__DATE_SHORT:e.date_format.date_short,DATE_FORMAT__MESSAGE_LIST__DATE_SEPARATOR:e.date_format.date_separator,DATE_FORMAT__MESSAGE_TIMESTAMP:e.date_format.message_timestamp,CONVERSATION_LIST__HEADER_TITLE:e.conversation_list.header_title,CONVERSATION_LIST__ENDED:e.conversation_list.ended,CONVERSATION_LIST__SYSTEM_MESSAGE:e.conversation_list.system_message,CONVERSATION_LIST__NO_CONVERSATIONS:e.common.placeholder_no_conversations,CONVERSATION_LIST__MULTIPLE_FILES_COUNT:e.conversation_list.multiple_files_count,TALK_TO_AGENT:e.conversation.start_new_conversation_label,CITATION_SOURCE_TITLE:e.conversation.citation_title,FORM_PLACEHOLDER:e.conversation.input_placeholder_active_form,FORM_VALIDATION_REQUIRED:e.form.validation_required,OPTIONAL:e.form.optional_label,PLACE_HOLDER__WRONG:e.common.placeholder_something_went_wrong,PLACE_HOLDER__NO_MESSAGES:e.common.placeholder_no_messages,RETRY:e.common.placeholder_something_went_wrong_retry_label,BUTTON__OK:e.common.button_ok,BUTTON__CANCEL:e.common.button_cancel,FAILED_MESSAGE_RESEND:e.conversation.failed_message_resend,FAILED_MESSAGE_REMOVE:e.conversation.failed_message_remove,FILE_UPLOAD_NO_SUPPORTED_FILES:e.conversation.file_upload_no_supported_files,FILE_UPLOAD_REPLACE_ALERT__TITLE:e.conversation.file_upload_replace_alert_title,FILE_UPLOAD_REPLACE_ALERT__DESCRIPTION:e.conversation.file_upload_replace_alert_description,FILE_UPLOAD_FILES:e.conversation.attachment_document,FEEDBACK_TITLE:e.feedback.title,FEEDBACK_GOOD:e.feedback.good,FEEDBACK_BAD:e.feedback.bad,FEEDBACK_COMMENT_LABEL:e.feedback.comment_label,FEEDBACK_COMMENT_PLACEHOLDER:e.feedback.comment_placeholder,FEEDBACK_CANCEL:e.feedback.cancel,FEEDBACK_SUBMIT:e.feedback.submit,FEEDBACK_SAVE:e.feedback.save,FEEDBACK_EDIT:e.feedback.edit,FEEDBACK_REMOVE:e.feedback.remove,A11Y_MESSAGE_LIST:e.conversation.a11y_message_list,A11Y_SCROLL_TO_BOTTOM:e.conversation.a11y_scroll_to_bottom,A11Y_SCROLL_TO_NEW_MESSAGES:e.conversation.a11y_scroll_to_new_messages,A11Y_OPEN_CONVERSATION_LIST:e.conversation.a11y_open_conversation_list,A11Y_OPEN_CONVERSATION:e.conversation.a11y_open_conversation,A11Y_OPEN_CONVERSATIONS:e.conversation.a11y_open_conversations,A11Y_CLOSE_CONVERSATION:e.conversation.a11y_close_conversation,A11Y_CLOSE_CONVERSATIONS:e.conversation.a11y_close_conversations,A11Y_MENU:e.conversation.a11y_menu,A11Y_MESSAGE_INPUT:e.conversation.a11y_message_input,A11Y_SEND_MESSAGE:e.conversation.a11y_send_message,A11Y_ATTACH_FILE:e.conversation.a11y_attach_file,A11Y_CONNECT_AGENT:e.conversation.a11y_connect_agent,A11Y_CLOSE_MESSENGER:e.conversation.a11y_close_messenger,A11Y_EXPAND_MESSENGER:e.conversation.a11y_expand_messenger,A11Y_COLLAPSE_MESSENGER:e.conversation.a11y_collapse_messenger,A11Y_MESSAGE_SENDER_YOU:e.conversation.a11y_message_sender_you,A11Y_SUGGESTED_REPLY:e.conversation.a11y_suggested_reply,A11Y_TYPING_INDICATOR:e.conversation.a11y_typing_indicator,A11Y_CODE_BLOCK_PLACEHOLDER:e.conversation.a11y_code_block_placeholder,A11Y_TYPING_FORMAT:e.conversation.a11y_typing_format,A11Y_MESSAGE_FAILED:e.conversation.a11y_message_failed,A11Y_NEW_MESSAGES_RECEIVED:e.conversation.a11y_new_messages_received,A11Y_NEW_MESSAGES_RECEIVED_FROM_SENDER:e.conversation.a11y_new_messages_received_from_sender,A11Y_AGENT_CONNECTED:e.conversation.a11y_agent_connected,A11Y_CONVERSATION_CLOSED:e.conversation.a11y_conversation_closed,A11Y_FILE_IMAGE:e.conversation.a11y_file_image,A11Y_FILE_VIDEO:e.conversation.a11y_file_video,A11Y_FILE_PDF:e.conversation.a11y_file_pdf,A11Y_FILE_DOCUMENT:e.conversation.a11y_file_document,A11Y_RECEIVED_FILE_IMAGE:e.conversation.a11y_received_file_image,A11Y_RECEIVED_FILE_VIDEO:e.conversation.a11y_received_file_video,A11Y_RECEIVED_FILE_PDF:e.conversation.a11y_received_file_pdf,A11Y_RECEIVED_FILES_IMAGE_COUNT:e.conversation.a11y_received_files_image_count,A11Y_SCREEN_CONVERSATION:e.conversation.a11y_screen_conversation,A11Y_SCREEN_CONVERSATION_WITH_AGENT:e.conversation.a11y_screen_conversation_with_agent,A11Y_SCREEN_CONVERSATION_LIST_NO_COUNT:e.conversation.a11y_screen_conversation_list_no_count,A11Y_SCREEN_CONVERSATION_LIST_WITH_COUNT:e.conversation.a11y_screen_conversation_list_with_count,A11Y_CSAT_DISPLAYED:e.conversation.a11y_csat_displayed,A11Y_EMPTY_CONVERSATION:e.conversation.a11y_empty_conversation,A11Y_INPUT_DISABLED:e.conversation.a11y_input_disabled,A11Y_FILE_SIZE_EXCEEDED:e.conversation.a11y_file_size_exceeded,A11Y_CSAT_FORM_ERROR:e.conversation.a11y_csat_form_error,A11Y_HINT_SEND_MESSAGE:e.conversation.a11y_hint_send_message,A11Y_HINT_OPEN_CONVERSATION:e.conversation.a11y_hint_open_conversation,A11Y_HINT_OPEN_CONVERSATIONS:e.conversation.a11y_hint_open_conversations,A11Y_HINT_CLOSE_CONVERSATION:e.conversation.a11y_hint_close_conversation,A11Y_HINT_OPEN_MENU:e.conversation.a11y_hint_open_menu,A11Y_HINT_CONNECT_TO_AGENT:e.conversation.a11y_hint_connect_to_agent,A11Y_HINT_ATTACH_FILE:e.conversation.a11y_hint_attach_file,A11Y_HINT_VIEW_NEW_MESSAGES:e.conversation.a11y_hint_view_new_messages,A11Y_HINT_OPEN_FILE:e.conversation.a11y_hint_open_file,A11Y_HINT_OPEN_IMAGE:e.conversation.a11y_hint_open_image,A11Y_HINT_SEND_REPLY:e.conversation.a11y_hint_send_reply,A11Y_CONVERSATION_ITEM:e.conversation_list.a11y_conversation_item,A11Y_CSAT_RATING_LABEL:e.csat.a11y_csat_rating_label,A11Y_HINT_SELECT_RATING:e.csat.a11y_hint_select_rating,IMAGE_VIEWER__DEFAULT_TITLE:e.conversation.image_viewer_default_title,A11Y_IMAGE_VIEWER_CLOSE:e.conversation.a11y_image_viewer_close,A11Y_IMAGE_VIEWER_PREVIOUS:e.conversation.a11y_image_viewer_previous,A11Y_IMAGE_VIEWER_NEXT:e.conversation.a11y_image_viewer_next,A11Y_IMAGE_VIEWER_DOWNLOAD:e.conversation.a11y_image_viewer_download,SCROLL_TO_NEW_MESSAGES_LABEL:e.conversation.scroll_to_new_messages_label,HANDOFF_CONFIRM__TITLE:e.handoff.confirm_title,HANDOFF_CONFIRM__DESCRIPTION:e.handoff.confirm_description,HANDOFF_CONFIRM__CANCEL:e.handoff.confirm_cancel,HANDOFF_CONFIRM__HANDOFF:e.handoff.confirm_handoff,MEMORY__DIALOG_TITLE:e.memory.dialog_title,MEMORY__DESC_ON:e.memory.desc_on,MEMORY__DESC_OFF:e.memory.desc_off,MEMORY__BUTTON_USE:e.memory.button_use,MEMORY__BUTTON_DONT_USE:e.memory.button_dont_use,MEMORY__BUTTON_KEEP_USING:e.memory.button_keep_using,MEMORY__BUTTON_DISABLE:e.memory.button_disable,MEMORY__BUTTON_DISABLE_AND_DELETE:e.memory.button_disable_and_delete,MEMORY__BUTTON_KEEP_OFF:e.memory.button_keep_off,MEMORY__BUTTON_ENABLE:e.memory.button_enable,MEMORY__BUTTON_CANCEL:e.memory.button_cancel,MEMORY__ERROR_MESSAGE:e.memory.error_message,A11Y_MEMORY_INDICATOR_MANAGE:e.memory.a11y_indicator_manage,A11Y_MEMORY_INDICATOR_ON:e.memory.a11y_indicator_on,A11Y_MEMORY_INDICATOR_OFF:e.memory.a11y_indicator_off,CONNECTION_DELAY__TITLE:e.connection_delay.title,CONNECTION_DELAY__DESCRIPTION:e.connection_delay.description}),Yi=e=>{var t;return((t=e.split("-"))==null?void 0:t[0])??Zt},Zt="en",Wi=new Set([Zt,"ko","es","pt","fr","hi","it","de","tr","ja"]),bh='@import"https://fonts.googleapis.com/css?family=Roboto:400,500,600,700&display=swap";.sb-message-template__border{position:relative}.sb-message-template__border:after{content:"";position:absolute;top:0;right:0;bottom:0;left:0;z-index:1;box-shadow:inset 0 0 0 var(--border-width) var(--border-color);border-radius:var(--border-radius);pointer-events:none}.sb-message-template__action{cursor:pointer}.sb-message-template__parent{font-family:Roboto,serif}.sb-message-template__text{font-family:inherit;font-size:14px;font-weight:400;font-stretch:normal;font-style:normal;letter-spacing:normal;text-align:left}.sb-message-template__text-button{font-family:inherit;background-color:#e0e0e0;text-align:center;padding:10px;border-radius:6px;font-size:14px;font-weight:600;font-stretch:normal;font-style:normal;letter-spacing:normal}.sendbird-theme--light .sb-message-template__text-button{color:#742ddd}.sendbird-theme--dark .sb-message-template__text-button{color:#c2a9fa}.sb-message-template__text-button:hover{opacity:1;box-shadow:#0000001a 0 1px 3px,#0000000f 0 1px 2px}.sb-message-template__text-button,.sb-message-template__image-button{cursor:pointer;border-style:none}.sb-message-template__parent{border-radius:unset;background-color:transparent;overflow:hidden}.sb-message-template__parent *{box-sizing:border-box;line-height:1.3}.sb-message-template__carousel{display:flex;width:100%;box-sizing:border-box;touch-action:pan-y}',{Provider:vh,useContext:Vr}=be("AgentUIElementResolver"),yh=({entryElement:e,modalRootElement:t,rootElement:n,children:r})=>{const s=l.useMemo(()=>{const o=n??document.body,i=e??o,c=t??o,u=d=>d===ye.MODAL_ROOT?c:i.querySelector(`#${d}`);return{resolveElement:u,resolvePortalContainer:d=>u(d)??c}},[e,t,n]);return a.createElement(vh,{value:s},r)};function ut(e,t){const n=e.getRootNode({composed:t});return n instanceof ShadowRoot||n instanceof Document?n:document}const Xs=()=>{const e=[];let t=0;const n=new Set,r=()=>n.forEach(s=>s());return{register:s=>{const o=++t;return e.push({id:o,handler:s}),r(),()=>{const i=e.findIndex(c=>c.id===o);i>=0&&(e.splice(i,1),r())}},dismissTopmost:()=>{const s=e[e.length-1];return s?(s.handler(),!0):!1},subscribe:s=>(n.add(s),()=>{n.delete(s)}),getOpenCount:()=>e.length}},{Provider:Sh,useContext:qr}=be("EscapeDismissStack"),Zs=e=>{e.stopPropagation(),e.stopImmediatePropagation()},Ah=({rootElement:e=document.body,boundaryElement:t,children:n})=>{const r=l.useRef(null),s=l.useRef(null);r.current||(r.current=Xs()),s.current||(s.current=Xs());const o=r.current,i=s.current;l.useLayoutEffect(()=>{const u=t??ut(e),d=m=>{if(m.key==="Escape"){if(o.dismissTopmost()){Zs(m);return}i.dismissTopmost()&&Zs(m)}};return u.addEventListener("keydown",d),()=>u.removeEventListener("keydown",d)},[t,e,i,o]);const c=l.useMemo(()=>({register:o.register,dismissTopmost:o.dismissTopmost,registerShellDismissHandler:i.register,subscribe:o.subscribe,getOpenCount:o.getOpenCount}),[i,o]);return a.createElement(Sh,{value:c},n)},ji=(e,t,n)=>{const r=l.useRef(t);l.useLayoutEffect(()=>{r.current=t},[t]),l.useLayoutEffect(()=>{if(e)return n(()=>r.current())},[e,n])},Th=(e,t)=>{const{register:n}=qr();ji(e,t,n)},Ih=(e,t)=>{const{registerShellDismissHandler:n}=qr();ji(e,t,n)},Xi=()=>{const{subscribe:e,getOpenCount:t}=qr();return l.useSyncExternalStore(e,()=>t()>0,()=>!1)},xh=(e,t,n)=>{const r=e[t];return r?typeof r=="function"?r():Promise.resolve(r):new Promise((s,o)=>{(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(o.bind(null,new Error("Unknown variable dynamic import: "+t+(t.split("/").length!==n?". Note that variables only represent file names one level deep.":""))))})},Js=Ki(fr.strings),Rh={...Js,HEADER_BUTTON__AGENT_HANDOFF:"Talk to human agent",MESSAGE_INPUT__PLACE_HOLDER__SUGGESTED_REPLIES:"Select an option to continue",BUTTON__SUBMIT:"Submit",SUBMITTED:"Submitted",TRY_AGAIN:"Please try again.",FILE_UPLOAD_NOTIFICATION__COUNT_LIMIT:"Up to %d files can be attached.",FILE_UPLOAD_NOTIFICATION__SIZE_LIMIT:"The maximum size per file is %d MB.",FILE_UPLOAD_NOTIFICATION__FILES_EXCLUDED_BY_VALIDATION:"%d files were excluded due to limits. Please select files individually.",FILE_UPLOAD_PHOTOS:"Photos",FILE_VIEWER__UNSUPPORT:"Unsupported message",A11Y_FILE_SELECTED:e=>`${e}, selected`,A11Y_FILE_REMOVE_BUTTON:e=>`Remove file: ${e}`,A11Y_FILE_UPLOAD_OPTIONS:"File upload options",A11Y_FAILED_MESSAGE_OPTIONS:"Failed message options",A11Y_FEEDBACK_OPTIONS:"Feedback options",A11Y_CSAT_TEXT_INPUT_LABEL:"Enter answer",FORM_UNAVAILABLE:"Form is no longer available.",FORM_NOT_SUPPORTED:"This form is not supported in the current version.",FORM_VALIDATION_MIN_LENGTH:e=>`Minimum ${e} characters required`,FORM_VALIDATION_MAX_LENGTH:e=>`Maximum ${e} characters allowed`,FORM_VALIDATION_MIN:e=>`Minimum value is ${e}`,FORM_VALIDATION_MAX:e=>`Maximum value is ${e}`,FORM_VALIDATION_MIN_SELECT:e=>`Select at least ${e} options`,FORM_VALIDATION_MAX_SELECT:e=>`Select at most ${e} options`,FORM_VALIDATION_REGEX_FAILED:"Invalid format",DATE_FORMAT__CONVERSATION_LIST__LIST_ITEM_TITLE:Js.DATE_FORMAT__DATE_SHORT,DATE_FORMAT__CONVERSATION_LIST__LIST_ITEM_TITLE_CAPTION:"h:mma",CONVERSATION_LIST__TOPICS_FALLBACK:"No category",CONVERSATION_CLOSED_FOOTER_LABEL:"Your conversation has ended",START_NEW_CONVERSATION:"💬 Start a new conversation",RETURN_TO_CONVERSATION:"💬 Return to conversation",BUTTON__SAVE:"Save",NO_NAME:"(No name)",CHANNEL_FROZEN:"Channel frozen"},xn={language:fr.language,dateLocale:fr.dateLocale,stringSet:Rh},Mh=Object.freeze(Object.defineProperty({__proto__:null,default:xn},Symbol.toStringTag,{value:"Module"})),gr=new Map([[Zt,xn]]);async function wh(e){const t=gr.get(e);if(t)return t;try{if(Wi.has(e)){const{default:n}=await xh(Object.assign({"./languages/de.ts":()=>Promise.resolve().then(()=>require("./cjs/I-l-5Zo-.cjs")),"./languages/en.ts":()=>Promise.resolve().then(()=>Mh),"./languages/es.ts":()=>Promise.resolve().then(()=>require("./cjs/D_km8dcd.cjs")),"./languages/fr.ts":()=>Promise.resolve().then(()=>require("./cjs/CLIpC7kY.cjs")),"./languages/hi.ts":()=>Promise.resolve().then(()=>require("./cjs/ChrM6HN1.cjs")),"./languages/it.ts":()=>Promise.resolve().then(()=>require("./cjs/CPZf2TWM.cjs")),"./languages/ja.ts":()=>Promise.resolve().then(()=>require("./cjs/D7UQ9OK7.cjs")),"./languages/ko.ts":()=>Promise.resolve().then(()=>require("./cjs/BMDJStMQ.cjs")),"./languages/pt.ts":()=>Promise.resolve().then(()=>require("./cjs/etCQgYrr.cjs")),"./languages/tr.ts":()=>Promise.resolve().then(()=>require("./cjs/DKQwAy8C.cjs"))}),`./languages/${e}.ts`,3);return gr.set(e,n),n}return xn}catch{return xn}}const{Provider:kh,useContext:se}=be("Localization"),Lh=({language:e=navigator.language,languageCode:t,logger:n,stringSet:r,children:s})=>{const[o,i]=l.useState(gr.get(Zt));return l.useEffect(()=>{const c=t??Yi(e);o.language!==c&&(n==null||n.debug("localization.useEffect: update language",{from:o.language,to:c}),wh(c).then(i))},[e,t,n]),a.createElement(kh,{value:{language:o.language,defaultStringSet:o.stringSet,stringSet:{...o.stringSet,...r},dateLocale:o.dateLocale,format:(c,u,d)=>at.format(c,u,{locale:o.dateLocale,...d})}},s)},Rn="data-sb-agent-theme",Qs=e=>(t,...n)=>{let r="";return t.forEach((s,o)=>{r+=s+(n[o]??"")}),`[${Rn}='${e}'] & { ${r} }`},Q={light:Qs("light"),dark:Qs("dark")},Oh=B.css(({theme:e})=>{const{palette:t}=e;return`
|
|
7
|
+
`);if(!n)return;const r=[];let s=n;s=Gm(s,t),s=Um(s);const o=zm(s);s=o.text,r.push(...o.inlineCodes),s=Om(s),s=Nm(s),s=Dm(s),s=$m(s),s=Fm(s),s=Bm(s),s=Hm(s),s=Pm(s);for(let c=0;c<r.length;c++)s=s.replaceAll(Mi(c),r[c]);return Hr(s)||void 0},Vm=(e,t)=>{var s;const n=((s=e.name)==null?void 0:s.trim())||"",r=e.mimeType??"";return Ye(r)?t.image:zt(r)?t.video:Qo({name:n,mimeType:r})?t.pdf(n):t.document(n)},In=e=>(e==null?void 0:e.trim())||"",qm=e=>(e?Hr(e):void 0)||void 0,Ni=e=>({text:In(e),format:"plain"}),Km=e=>({text:In(e),format:"markdown"}),Qn=({markdownText:e,plainText:t,comparisonText:n})=>{const r=In(e);return r&&r!==In(n)?Km(r):Ni(t)},Dt=({sender:e,message:t,messageFormat:n="plain",time:r,codeBlockPlaceholder:s})=>{const o=[],i=n==="markdown"?Oi(t,{codeBlockPlaceholder:s}):qm(t);if(r&&o.push(r),e&&o.push(e),i&&o.push(i),o.length!==0)return o.join(", ")},Di=(e,t)=>Oi(e==null?void 0:e.trim(),t!==void 0?{codeBlockPlaceholder:t}:void 0),Ym=(...e)=>Hr(e.filter(Boolean).join(", "))||void 0,Ws=(e,t,n,r)=>{if(!t||t===n)return e;const s=Di(t,r);return s?Ym(e,s):e},Wm=(e,t)=>{var r,s,o,i;const n=(r=e.message)==null?void 0:r.trim();if(e.isFileMessage()){const c=((s=e.name)==null?void 0:s.trim())||"",u=Vm({name:c,mimeType:e.type},t);return Ws(u,n,c,t.codeBlockPlaceholder)}if(e.isMultipleFilesMessage()){const c=e.fileInfoList??[],u=c.length;if(u===0)return;const d=((i=(o=c[0])==null?void 0:o.fileName)==null?void 0:i.trim())||"",h=c.every(f=>{var g;return(g=f.mimeType)==null?void 0:g.startsWith("image")})?t.receivedFilesImageCount(u):t.multipleFilesCount(u);return Ws(h,n,d,t.codeBlockPlaceholder)}return Di(n,t.codeBlockPlaceholder)},jm=(e,t={})=>{const{throttleMs:n=1e3,isSuppressed:r,maxOrderedQueueSize:s=10}=t,o=Math.max(1,s);let i=null;const c=[];let u=null,d=null,m=null,h=!1,f=0;const g=(k,M,P)=>({text:k,ignoreSuppression:M,queueOrder:f++,dedupeKey:P}),_=()=>{const k=c[0]??null,M=i;return k&&M?M.queueOrder<k.queueOrder?(i=null,M):c.shift()??null:k?c.shift()??null:M!==null?(i=null,M):null},y=()=>{for(;;){const k=_();if(!k)return null;if(!(!k.ignoreSuppression&&(r!=null&&r())))return k}},b=k=>{u=k.text,d=k.dedupeKey??null,h=!0,e(k.text),m=setTimeout(()=>{m=null,h=!1;const M=y();M&&b(M)},n)},p=k=>{u=k.text,d=k.dedupeKey??null,e(k.text)},S=(k,M,P,F)=>M!=null&&F!=null?M===F:M==null&&F==null?k!=null&&k===P:!1,A=(k,M,P)=>{if(!k||!M&&(r!=null&&r()))return;const F=P==null?void 0:P.dedupeKey;if(!(h&&S(k,F,u,d)))if(h){if(((P==null?void 0:P.mode)??"latestOnly")==="ordered"){const j=c[c.length-1];if(j&&S(k,F,j.text,j.dedupeKey))return;c.push(g(k,M,F)),c.length>o&&c.shift();return}i=g(k,M,F)}else i=null,b(g(k,M,F))};return{announce:(k,M)=>{A(k,!1,M)},announceIgnoringSuppression:(k,M)=>{A(k,!0,M)},flush:()=>{const k=[];let M=_();for(;M!==null;)k.push(M),M=_();if(m!==null&&(clearTimeout(m),m=null),h=!1,k.length!==0)for(const P of k)p(P)},destroy:()=>{m!==null&&(clearTimeout(m),m=null),i=null,c.length=0,u=null,d=null,h=!1}}},Xm=e=>{switch(e){case"newMessage":case"conversationClosed":case"csatDisplayed":case"csatSubmitted":case"csatExpired":return"ordered";default:return"latestOnly"}},Zm=(e,t)=>e.screen==="conversationList"?typeof e.conversationCount=="number"?t.screenConversationListWithCount(e.conversationCount):t.screenConversationListNoCount:[e.agentName?t.screenConversationWithAgent(e.agentName):t.screenConversation,e.isClosed?t.conversationClosed:null,e.isClosed&&e.hasCSAT?t.csatDisplayed:null,e.isEmpty?t.emptyState:null].filter(r=>!!r).join(". "),Jm=(e,t)=>{switch(e.event){case"newMessage":return e.body!==void 0||e.time!==void 0?[t.newMessage(1),e.time,e.senderName,e.body].filter(r=>!!r).join(", "):e.senderName?t.newMessageFromSender(e.senderName,1):t.newMessage(1);case"typing":return t.typing(e.agentName??"");case"sendFailed":return t.sendFailed;case"agentConnected":return t.agentConnected(e.agentName??"");case"conversationClosed":return t.conversationClosed;case"csatDisplayed":return t.csatDisplayed;case"csatSubmitted":return e.submittedLabel;case"csatExpired":return t.csatExpired;case"emptyState":return t.emptyState;case"inputDisabled":return t.inputDisabled}},Qm=(e,t)=>{switch(e.type){case"fileSizeExceeded":return t.fileSizeExceeded(e.maxSizeMB??25);case"sendFailed":return t.sendFailed;case"csatFormError":return t.csatFormError;case"generic":return e.message}},eh=(e,t)=>!t||!Qe(e)||e.sender.userId!==t?null:e.reqId||(e.messageId>0?String(e.messageId):null),th=(e,t)=>Oe.isAdmin(e)?Oe.isCSAT(e):"sender"in e?e.sender.userId!==t:!1,nh=e=>"messageId"in e&&e.messageId>0?String(e.messageId):"reqId"in e&&typeof e.reqId=="string"&&e.reqId.length>0?e.reqId:null,rh=e=>e===de.CollectionEventSource.EVENT_MESSAGE_RECEIVED||e===de.CollectionEventSource.EVENT_MESSAGE_UPDATED,sh=({isOpened:e,opensConversationList:t})=>e?t?"closeConversationList":"closeConversation":t?"openConversationList":"openConversation",oh=(e,t)=>{switch(e){case"closeConversationList":return t.closeConversationList;case"closeConversation":return t.closeConversation;case"openConversationList":return t.openConversationList;case"openConversation":return t.openConversation}},ih=(e,t)=>{switch(e){case"closeConversation":return t.hintCloseConversation;case"openConversationList":return t.hintOpenConversationList;case"openConversation":return t.hintOpenConversation;default:return}},ah=({intent:e,strings:t})=>({label:oh(e,t),hint:ih(e,t)}),ch="1.35.1",Ge="sb-agent",ye={ENTRY:`${Ge}-entry`,MODAL_ROOT:`${Ge}-modal-root`,WINDOW:`${Ge}-window`,LAUNCHER:`${Ge}-launcher`,WINDOW_TITLE:`${Ge}-window-title`},$i="data-sb-initial-focus",Fi="true",lh=`[${$i}="${Fi}"]`,Pi={[$i]:Fi},Gr="data-sb-focus-trap-sentinel",uh="true",Ui="data-sb-initial-focus-header",Bi="true",dh=`[${Ui}="${Bi}"]`,Hi={[Ui]:Bi},Gi="data-sb-message-input",zi="true",mh=`textarea[${Gi}="${zi}"]:not(:disabled)`,hh={[Gi]:zi},Vi=1e3,ln=2147483647,gt={MODAL:ln-1,TOOLTIP:ln-2,WINDOW:ln-3,LAUNCHER:ln-4},qi=36,fh=100,gh=ch,zr="noopener noreferrer nofollow",hr=()=>typeof document>"u"||document.visibilityState==="visible",js=()=>typeof document<"u"&&document.visibilityState==="hidden",ph=e=>{if(hr()){e();return}if(typeof document>"u")return;const t=()=>{hr()&&(document.removeEventListener("visibilitychange",t),e())};return document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t)};function _h(){return{isOnline:()=>navigator.onLine,subscribe:e=>{const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t),window.addEventListener("offline",n),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}const un={};function Eh(){return{get:e=>{try{return localStorage.getItem(e)}catch{return un[e]??null}},set:(e,t)=>{try{localStorage.setItem(e,t)}catch{un[e]=t}},delete:e=>{try{localStorage.removeItem(e)}catch{delete un[e]}},getKeys:e=>{try{const t=[];for(let n=0;n<localStorage.length;n++){const r=localStorage.key(n);r&&r.startsWith(e)&&t.push(r)}return t}catch{return Object.keys(un).filter(t=>t.startsWith(e))}}}}const Ch={conversation:{input_placeholder:"Ask a question",input_placeholder_disabled:"Chat is unavailable in this channel",input_placeholder_steward:"Processing your request...",input_placeholder_wait_ai_agent_response:"Waiting for the agent's reply...",input_placeholder_active_form:"Please fill out the form to move forward.",input_placeholder_reconnecting:"Trying to reconnect. Refresh if persists.",unknown_message_type:"(Unknown message type)",powered_by:"Powered by",citation_title:"Source",start_new_conversation_label:"Start a conversation",scroll_to_new_messages_label:()=>"New message",failed_message_resend:"Retry",failed_message_remove:"Remove",file_upload_no_supported_files:"No supported file types available.",file_upload_replace_alert_title:"Replace attachment?",file_upload_replace_alert_description:"Uploading a different file type will replace the current one.",a11y_message_list:"Chat messages",a11y_scroll_to_bottom:"Scroll to bottom",a11y_scroll_to_new_messages:"Scroll to new messages",a11y_open_conversation_list:"Open conversation list",a11y_open_conversation:"Open conversation with Support",a11y_open_conversations:"Open conversations",a11y_close_conversation:"Close conversation",a11y_close_conversations:"Close conversations",a11y_menu:"Menu",a11y_message_input:"Message",a11y_send_message:"Send message",a11y_attach_file:"Attach file",a11y_close_messenger:"Close messenger",a11y_expand_messenger:"Expand messenger",a11y_collapse_messenger:"Collapse messenger",a11y_connect_agent:"Talk to human agent",a11y_message_sender_you:"You",a11y_suggested_reply:"Suggested reply",a11y_typing_indicator:"Typing",a11y_code_block_placeholder:"Code block",a11y_typing_format:e=>`${e} is typing`,a11y_message_failed:"Message send failed",a11y_new_messages_received:e=>`${e} new ${e===1?"message":"messages"} received`,a11y_new_messages_received_from_sender:(e,t)=>`${e}: ${t} new ${t===1?"message":"messages"} received`,a11y_agent_connected:e=>"Connected to human agent",a11y_conversation_closed:"Conversation has ended",a11y_file_image:e=>`Image file: ${e}`,a11y_file_video:e=>`Video file: ${e}`,a11y_file_pdf:e=>`PDF file: ${e}`,a11y_file_document:e=>`Document file: ${e}`,a11y_received_file_image:"Image file",a11y_received_file_video:"Video file",a11y_received_file_pdf:e=>`PDF file: ${e}`,a11y_received_files_image_count:e=>`${e} ${e===1?"image":"images"}`,a11y_screen_conversation:"Conversation",a11y_screen_conversation_with_agent:e=>`Conversation with ${e}`,a11y_screen_conversation_list_no_count:"Conversation list",a11y_screen_conversation_list_with_count:e=>`Conversations, ${e} total`,a11y_csat_displayed:"Satisfaction survey displayed",a11y_empty_conversation:"No messages in this conversation",a11y_input_disabled:"Message input is disabled",a11y_file_size_exceeded:e=>`File exceeds size limit of ${e}MB`,a11y_csat_form_error:"Please complete the required fields",a11y_hint_send_message:"Sends the message",a11y_hint_open_conversation:"Opens the conversation",a11y_hint_open_conversations:"Opens conversations",a11y_hint_close_conversation:"Closes the conversation",a11y_hint_close_messenger:"Closes the messenger",a11y_hint_open_menu:"Opens the menu",a11y_hint_connect_to_agent:"Escalates to a human agent",a11y_hint_attach_file:"Opens file attachment options",a11y_hint_view_new_messages:"Scrolls to new messages",a11y_hint_open_file:"Opens the file",a11y_hint_open_image:"Opens the image",a11y_hint_send_reply:"Sends this reply",image_viewer_default_title:"Image",a11y_image_viewer_close:"Close image viewer",a11y_image_viewer_previous:"Previous image",a11y_image_viewer_next:"Next image",a11y_image_viewer_download:"Download image",attachment_document:"Files"},conversation_list:{header_title:"Conversations",ended:"Ended",system_message:"System message",footer_title:"Start a conversation",multiple_files_count:e=>`${e} ${e===1?"file":"files"}`,a11y_conversation_item:(e,t,n,r)=>`${e}, ${t}, ${n}${r>0?`, ${r} unread ${r===1?"message":"messages"}`:""}`},date_format:{just_now:"Just now",minutes_ago:e=>`${e} minutes ago`,hours_ago:e=>`${e} hours ago`,date_short:"MM/dd/yyyy",date_separator:"MMMM dd, yyyy",message_timestamp:"p"},csat:{title:"Your feedback matters to us",submitted_label:"Successfully submitted!",cre_question:"Was your issue resolved?",cre_positive_label:"Yes, thank you! 👍",cre_negative_label:"No, that didn't help.",reason_placeholder:"Share your feedback",question:"How would you rate your experience?",submit_label:"Submit",submission_expired:"We're sorry, the survey period has ended.",a11y_csat_rating_label:(e,t)=>`${e} out of 5 — ${t}`,a11y_hint_select_rating:"Selects this rating"},form:{optional_label:"optional",validation_required:"This question is required"},common:{placeholder_something_went_wrong:"Something went wrong",placeholder_no_messages:"No messages",placeholder_no_conversations:"No conversations yet",placeholder_something_went_wrong_retry_label:"Retry",button_ok:"OK",button_cancel:"Cancel"},feedback:{title:"Submit feedback",good:"Good",bad:"Bad",comment_label:"Comment (optional)",comment_placeholder:"Leave a comment",cancel:"Cancel",submit:"Submit",save:"Save",edit:"Edit feedback",remove:"Remove feedback"},handoff:{confirm_title:"Request handoff?",confirm_description:"You'll be transferred to a human agent. Your conversation history will be shared.",confirm_cancel:"Cancel",confirm_handoff:"Handoff"},memory:{dialog_title:"Memory",desc_on:"Memory is **turned on**. It remembers your conversation history to provide personalized responses tailored to your previous questions and preferences.",desc_off:"Memory is **turned off**. If turned on, it will remember your conversation history to provide personalized responses tailored to your previous questions and preferences.",button_use:"Use",button_dont_use:"Don't use",button_keep_using:"Keep using",button_disable:"Disable",button_disable_and_delete:"Disable & Delete memory",button_keep_off:"Keep off",button_enable:"Enable memory",button_cancel:"Cancel",error_message:"Failed to update memory state. Please try again.",a11y_indicator_manage:"Manage memory",a11y_indicator_on:"Memory is on",a11y_indicator_off:"Memory is off"},connection_delay:{title:"Something went wrong. You'll be reconnected shortly.",description:e=>`Estimated waiting time: ${e}`}},fr={language:"en",strings:Ch,dateLocale:lc.enUS},Ki=e=>({MESSAGE_INPUT__PLACE_HOLDER:e.conversation.input_placeholder,MESSAGE_INPUT__PLACE_HOLDER__DISABLED:e.conversation.input_placeholder_disabled,MESSAGE_INPUT__PLACE_HOLDER__STEWARD:e.conversation.input_placeholder_steward,MESSAGE_INPUT__PLACE_HOLDER__WAIT_AI_AGENT_RESPONSE:e.conversation.input_placeholder_wait_ai_agent_response,MESSAGE_INPUT__PLACE_HOLDER__RECONNECTING:e.conversation.input_placeholder_reconnecting,UNKNOWN__UNKNOWN_MESSAGE_TYPE:e.conversation.unknown_message_type,POWERED_BY:e.conversation.powered_by,CSAT_TITLE_UNSUBMITTED:e.csat.title,CSAT_TITLE_SUBMITTED:e.csat.submitted_label,CSAT_CRE_TITLE:e.csat.cre_question,CSAT_CRE_SOLVED:e.csat.cre_positive_label,CSAT_CRE_NOT_SOLVED:e.csat.cre_negative_label,CSAT_REASON_PLACEHOLDER:e.csat.reason_placeholder,CSAT_RATING_TITLE:e.csat.question,CSAT_SUBMIT_LABEL:e.csat.submit_label,CSAT_SUBMISSION_EXPIRED:e.csat.submission_expired,DATE_FORMAT__JUST_NOW:e.date_format.just_now,DATE_FORMAT__MINUTES_AGO:e.date_format.minutes_ago,DATE_FORMAT__HOURS_AGO:e.date_format.hours_ago,DATE_FORMAT__DATE_SHORT:e.date_format.date_short,DATE_FORMAT__MESSAGE_LIST__DATE_SEPARATOR:e.date_format.date_separator,DATE_FORMAT__MESSAGE_TIMESTAMP:e.date_format.message_timestamp,CONVERSATION_LIST__HEADER_TITLE:e.conversation_list.header_title,CONVERSATION_LIST__ENDED:e.conversation_list.ended,CONVERSATION_LIST__SYSTEM_MESSAGE:e.conversation_list.system_message,CONVERSATION_LIST__NO_CONVERSATIONS:e.common.placeholder_no_conversations,CONVERSATION_LIST__MULTIPLE_FILES_COUNT:e.conversation_list.multiple_files_count,TALK_TO_AGENT:e.conversation.start_new_conversation_label,CITATION_SOURCE_TITLE:e.conversation.citation_title,FORM_PLACEHOLDER:e.conversation.input_placeholder_active_form,FORM_VALIDATION_REQUIRED:e.form.validation_required,OPTIONAL:e.form.optional_label,PLACE_HOLDER__WRONG:e.common.placeholder_something_went_wrong,PLACE_HOLDER__NO_MESSAGES:e.common.placeholder_no_messages,RETRY:e.common.placeholder_something_went_wrong_retry_label,BUTTON__OK:e.common.button_ok,BUTTON__CANCEL:e.common.button_cancel,FAILED_MESSAGE_RESEND:e.conversation.failed_message_resend,FAILED_MESSAGE_REMOVE:e.conversation.failed_message_remove,FILE_UPLOAD_NO_SUPPORTED_FILES:e.conversation.file_upload_no_supported_files,FILE_UPLOAD_REPLACE_ALERT__TITLE:e.conversation.file_upload_replace_alert_title,FILE_UPLOAD_REPLACE_ALERT__DESCRIPTION:e.conversation.file_upload_replace_alert_description,FILE_UPLOAD_FILES:e.conversation.attachment_document,FEEDBACK_TITLE:e.feedback.title,FEEDBACK_GOOD:e.feedback.good,FEEDBACK_BAD:e.feedback.bad,FEEDBACK_COMMENT_LABEL:e.feedback.comment_label,FEEDBACK_COMMENT_PLACEHOLDER:e.feedback.comment_placeholder,FEEDBACK_CANCEL:e.feedback.cancel,FEEDBACK_SUBMIT:e.feedback.submit,FEEDBACK_SAVE:e.feedback.save,FEEDBACK_EDIT:e.feedback.edit,FEEDBACK_REMOVE:e.feedback.remove,A11Y_MESSAGE_LIST:e.conversation.a11y_message_list,A11Y_SCROLL_TO_BOTTOM:e.conversation.a11y_scroll_to_bottom,A11Y_SCROLL_TO_NEW_MESSAGES:e.conversation.a11y_scroll_to_new_messages,A11Y_OPEN_CONVERSATION_LIST:e.conversation.a11y_open_conversation_list,A11Y_OPEN_CONVERSATION:e.conversation.a11y_open_conversation,A11Y_OPEN_CONVERSATIONS:e.conversation.a11y_open_conversations,A11Y_CLOSE_CONVERSATION:e.conversation.a11y_close_conversation,A11Y_CLOSE_CONVERSATIONS:e.conversation.a11y_close_conversations,A11Y_MENU:e.conversation.a11y_menu,A11Y_MESSAGE_INPUT:e.conversation.a11y_message_input,A11Y_SEND_MESSAGE:e.conversation.a11y_send_message,A11Y_ATTACH_FILE:e.conversation.a11y_attach_file,A11Y_CONNECT_AGENT:e.conversation.a11y_connect_agent,A11Y_CLOSE_MESSENGER:e.conversation.a11y_close_messenger,A11Y_EXPAND_MESSENGER:e.conversation.a11y_expand_messenger,A11Y_COLLAPSE_MESSENGER:e.conversation.a11y_collapse_messenger,A11Y_MESSAGE_SENDER_YOU:e.conversation.a11y_message_sender_you,A11Y_SUGGESTED_REPLY:e.conversation.a11y_suggested_reply,A11Y_TYPING_INDICATOR:e.conversation.a11y_typing_indicator,A11Y_CODE_BLOCK_PLACEHOLDER:e.conversation.a11y_code_block_placeholder,A11Y_TYPING_FORMAT:e.conversation.a11y_typing_format,A11Y_MESSAGE_FAILED:e.conversation.a11y_message_failed,A11Y_NEW_MESSAGES_RECEIVED:e.conversation.a11y_new_messages_received,A11Y_NEW_MESSAGES_RECEIVED_FROM_SENDER:e.conversation.a11y_new_messages_received_from_sender,A11Y_AGENT_CONNECTED:e.conversation.a11y_agent_connected,A11Y_CONVERSATION_CLOSED:e.conversation.a11y_conversation_closed,A11Y_FILE_IMAGE:e.conversation.a11y_file_image,A11Y_FILE_VIDEO:e.conversation.a11y_file_video,A11Y_FILE_PDF:e.conversation.a11y_file_pdf,A11Y_FILE_DOCUMENT:e.conversation.a11y_file_document,A11Y_RECEIVED_FILE_IMAGE:e.conversation.a11y_received_file_image,A11Y_RECEIVED_FILE_VIDEO:e.conversation.a11y_received_file_video,A11Y_RECEIVED_FILE_PDF:e.conversation.a11y_received_file_pdf,A11Y_RECEIVED_FILES_IMAGE_COUNT:e.conversation.a11y_received_files_image_count,A11Y_SCREEN_CONVERSATION:e.conversation.a11y_screen_conversation,A11Y_SCREEN_CONVERSATION_WITH_AGENT:e.conversation.a11y_screen_conversation_with_agent,A11Y_SCREEN_CONVERSATION_LIST_NO_COUNT:e.conversation.a11y_screen_conversation_list_no_count,A11Y_SCREEN_CONVERSATION_LIST_WITH_COUNT:e.conversation.a11y_screen_conversation_list_with_count,A11Y_CSAT_DISPLAYED:e.conversation.a11y_csat_displayed,A11Y_EMPTY_CONVERSATION:e.conversation.a11y_empty_conversation,A11Y_INPUT_DISABLED:e.conversation.a11y_input_disabled,A11Y_FILE_SIZE_EXCEEDED:e.conversation.a11y_file_size_exceeded,A11Y_CSAT_FORM_ERROR:e.conversation.a11y_csat_form_error,A11Y_HINT_SEND_MESSAGE:e.conversation.a11y_hint_send_message,A11Y_HINT_OPEN_CONVERSATION:e.conversation.a11y_hint_open_conversation,A11Y_HINT_OPEN_CONVERSATIONS:e.conversation.a11y_hint_open_conversations,A11Y_HINT_CLOSE_CONVERSATION:e.conversation.a11y_hint_close_conversation,A11Y_HINT_OPEN_MENU:e.conversation.a11y_hint_open_menu,A11Y_HINT_CONNECT_TO_AGENT:e.conversation.a11y_hint_connect_to_agent,A11Y_HINT_ATTACH_FILE:e.conversation.a11y_hint_attach_file,A11Y_HINT_VIEW_NEW_MESSAGES:e.conversation.a11y_hint_view_new_messages,A11Y_HINT_OPEN_FILE:e.conversation.a11y_hint_open_file,A11Y_HINT_OPEN_IMAGE:e.conversation.a11y_hint_open_image,A11Y_HINT_SEND_REPLY:e.conversation.a11y_hint_send_reply,A11Y_CONVERSATION_ITEM:e.conversation_list.a11y_conversation_item,A11Y_CSAT_RATING_LABEL:e.csat.a11y_csat_rating_label,A11Y_HINT_SELECT_RATING:e.csat.a11y_hint_select_rating,IMAGE_VIEWER__DEFAULT_TITLE:e.conversation.image_viewer_default_title,A11Y_IMAGE_VIEWER_CLOSE:e.conversation.a11y_image_viewer_close,A11Y_IMAGE_VIEWER_PREVIOUS:e.conversation.a11y_image_viewer_previous,A11Y_IMAGE_VIEWER_NEXT:e.conversation.a11y_image_viewer_next,A11Y_IMAGE_VIEWER_DOWNLOAD:e.conversation.a11y_image_viewer_download,SCROLL_TO_NEW_MESSAGES_LABEL:e.conversation.scroll_to_new_messages_label,HANDOFF_CONFIRM__TITLE:e.handoff.confirm_title,HANDOFF_CONFIRM__DESCRIPTION:e.handoff.confirm_description,HANDOFF_CONFIRM__CANCEL:e.handoff.confirm_cancel,HANDOFF_CONFIRM__HANDOFF:e.handoff.confirm_handoff,MEMORY__DIALOG_TITLE:e.memory.dialog_title,MEMORY__DESC_ON:e.memory.desc_on,MEMORY__DESC_OFF:e.memory.desc_off,MEMORY__BUTTON_USE:e.memory.button_use,MEMORY__BUTTON_DONT_USE:e.memory.button_dont_use,MEMORY__BUTTON_KEEP_USING:e.memory.button_keep_using,MEMORY__BUTTON_DISABLE:e.memory.button_disable,MEMORY__BUTTON_DISABLE_AND_DELETE:e.memory.button_disable_and_delete,MEMORY__BUTTON_KEEP_OFF:e.memory.button_keep_off,MEMORY__BUTTON_ENABLE:e.memory.button_enable,MEMORY__BUTTON_CANCEL:e.memory.button_cancel,MEMORY__ERROR_MESSAGE:e.memory.error_message,A11Y_MEMORY_INDICATOR_MANAGE:e.memory.a11y_indicator_manage,A11Y_MEMORY_INDICATOR_ON:e.memory.a11y_indicator_on,A11Y_MEMORY_INDICATOR_OFF:e.memory.a11y_indicator_off,CONNECTION_DELAY__TITLE:e.connection_delay.title,CONNECTION_DELAY__DESCRIPTION:e.connection_delay.description}),Yi=e=>{var t;return((t=e.split("-"))==null?void 0:t[0])??Zt},Zt="en",Wi=new Set([Zt,"ko","es","pt","fr","hi","it","de","tr","ja"]),bh='@import"https://fonts.googleapis.com/css?family=Roboto:400,500,600,700&display=swap";.sb-message-template__border{position:relative}.sb-message-template__border:after{content:"";position:absolute;top:0;right:0;bottom:0;left:0;z-index:1;box-shadow:inset 0 0 0 var(--border-width) var(--border-color);border-radius:var(--border-radius);pointer-events:none}.sb-message-template__action{cursor:pointer}.sb-message-template__parent{font-family:Roboto,serif}.sb-message-template__text{font-family:inherit;font-size:14px;font-weight:400;font-stretch:normal;font-style:normal;letter-spacing:normal;text-align:left}.sb-message-template__text-button{font-family:inherit;background-color:#e0e0e0;text-align:center;padding:10px;border-radius:6px;font-size:14px;font-weight:600;font-stretch:normal;font-style:normal;letter-spacing:normal}.sendbird-theme--light .sb-message-template__text-button{color:#742ddd}.sendbird-theme--dark .sb-message-template__text-button{color:#c2a9fa}.sb-message-template__text-button:hover{opacity:1;box-shadow:#0000001a 0 1px 3px,#0000000f 0 1px 2px}.sb-message-template__text-button,.sb-message-template__image-button{cursor:pointer;border-style:none}.sb-message-template__parent{border-radius:unset;background-color:transparent;overflow:hidden}.sb-message-template__parent *{box-sizing:border-box;line-height:1.3}.sb-message-template__carousel{display:flex;width:100%;box-sizing:border-box;touch-action:pan-y}',{Provider:vh,useContext:Vr}=be("AgentUIElementResolver"),yh=({entryElement:e,modalRootElement:t,rootElement:n,children:r})=>{const s=l.useMemo(()=>{const o=n??document.body,i=e??o,c=t??o,u=d=>d===ye.MODAL_ROOT?c:i.querySelector(`#${d}`);return{resolveElement:u,resolvePortalContainer:d=>u(d)??c}},[e,t,n]);return a.createElement(vh,{value:s},r)};function ut(e,t){const n=e.getRootNode({composed:t});return n instanceof ShadowRoot||n instanceof Document?n:document}const Xs=()=>{const e=[];let t=0;const n=new Set,r=()=>n.forEach(s=>s());return{register:s=>{const o=++t;return e.push({id:o,handler:s}),r(),()=>{const i=e.findIndex(c=>c.id===o);i>=0&&(e.splice(i,1),r())}},dismissTopmost:()=>{const s=e[e.length-1];return s?(s.handler(),!0):!1},subscribe:s=>(n.add(s),()=>{n.delete(s)}),getOpenCount:()=>e.length}},{Provider:Sh,useContext:qr}=be("EscapeDismissStack"),Zs=e=>{e.stopPropagation(),e.stopImmediatePropagation()},Ah=({rootElement:e=document.body,boundaryElement:t,children:n})=>{const r=l.useRef(null),s=l.useRef(null);r.current||(r.current=Xs()),s.current||(s.current=Xs());const o=r.current,i=s.current;l.useLayoutEffect(()=>{const u=t??ut(e),d=m=>{if(m.key==="Escape"){if(o.dismissTopmost()){Zs(m);return}i.dismissTopmost()&&Zs(m)}};return u.addEventListener("keydown",d),()=>u.removeEventListener("keydown",d)},[t,e,i,o]);const c=l.useMemo(()=>({register:o.register,dismissTopmost:o.dismissTopmost,registerShellDismissHandler:i.register,subscribe:o.subscribe,getOpenCount:o.getOpenCount}),[i,o]);return a.createElement(Sh,{value:c},n)},ji=(e,t,n)=>{const r=l.useRef(t);l.useLayoutEffect(()=>{r.current=t},[t]),l.useLayoutEffect(()=>{if(e)return n(()=>r.current())},[e,n])},Th=(e,t)=>{const{register:n}=qr();ji(e,t,n)},Ih=(e,t)=>{const{registerShellDismissHandler:n}=qr();ji(e,t,n)},Xi=()=>{const{subscribe:e,getOpenCount:t}=qr();return l.useSyncExternalStore(e,()=>t()>0,()=>!1)},xh=(e,t,n)=>{const r=e[t];return r?typeof r=="function"?r():Promise.resolve(r):new Promise((s,o)=>{(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(o.bind(null,new Error("Unknown variable dynamic import: "+t+(t.split("/").length!==n?". Note that variables only represent file names one level deep.":""))))})},Js=Ki(fr.strings),Rh={...Js,HEADER_BUTTON__AGENT_HANDOFF:"Talk to human agent",MESSAGE_INPUT__PLACE_HOLDER__SUGGESTED_REPLIES:"Select an option to continue",BUTTON__SUBMIT:"Submit",SUBMITTED:"Submitted",TRY_AGAIN:"Please try again.",FILE_UPLOAD_NOTIFICATION__COUNT_LIMIT:"Up to %d files can be attached.",FILE_UPLOAD_NOTIFICATION__SIZE_LIMIT:"The maximum size per file is %d MB.",FILE_UPLOAD_NOTIFICATION__FILES_EXCLUDED_BY_VALIDATION:"%d files were excluded due to limits. Please select files individually.",FILE_UPLOAD_PHOTOS:"Photos",FILE_VIEWER__UNSUPPORT:"Unsupported message",A11Y_FILE_SELECTED:e=>`${e}, selected`,A11Y_FILE_REMOVE_BUTTON:e=>`Remove file: ${e}`,A11Y_FILE_UPLOAD_OPTIONS:"File upload options",A11Y_FAILED_MESSAGE_OPTIONS:"Failed message options",A11Y_FEEDBACK_OPTIONS:"Feedback options",A11Y_CSAT_TEXT_INPUT_LABEL:"Enter answer",FORM_UNAVAILABLE:"Form is no longer available.",FORM_NOT_SUPPORTED:"This form is not supported in the current version.",FORM_VALIDATION_MIN_LENGTH:e=>`Minimum ${e} characters required`,FORM_VALIDATION_MAX_LENGTH:e=>`Maximum ${e} characters allowed`,FORM_VALIDATION_MIN:e=>`Minimum value is ${e}`,FORM_VALIDATION_MAX:e=>`Maximum value is ${e}`,FORM_VALIDATION_MIN_SELECT:e=>`Select at least ${e} options`,FORM_VALIDATION_MAX_SELECT:e=>`Select at most ${e} options`,FORM_VALIDATION_REGEX_FAILED:"Invalid format",DATE_FORMAT__CONVERSATION_LIST__LIST_ITEM_TITLE:Js.DATE_FORMAT__DATE_SHORT,DATE_FORMAT__CONVERSATION_LIST__LIST_ITEM_TITLE_CAPTION:"h:mma",CONVERSATION_LIST__TOPICS_FALLBACK:"No category",CONVERSATION_CLOSED_FOOTER_LABEL:"Your conversation has ended",START_NEW_CONVERSATION:"💬 Start a new conversation",RETURN_TO_CONVERSATION:"💬 Return to conversation",BUTTON__SAVE:"Save",NO_NAME:"(No name)",CHANNEL_FROZEN:"Channel frozen"},xn={language:fr.language,dateLocale:fr.dateLocale,stringSet:Rh},Mh=Object.freeze(Object.defineProperty({__proto__:null,default:xn},Symbol.toStringTag,{value:"Module"})),gr=new Map([[Zt,xn]]);async function wh(e){const t=gr.get(e);if(t)return t;try{if(Wi.has(e)){const{default:n}=await xh(Object.assign({"./languages/de.ts":()=>Promise.resolve().then(()=>require("./cjs/I-l-5Zo-.cjs")),"./languages/en.ts":()=>Promise.resolve().then(()=>Mh),"./languages/es.ts":()=>Promise.resolve().then(()=>require("./cjs/D_km8dcd.cjs")),"./languages/fr.ts":()=>Promise.resolve().then(()=>require("./cjs/CLIpC7kY.cjs")),"./languages/hi.ts":()=>Promise.resolve().then(()=>require("./cjs/ChrM6HN1.cjs")),"./languages/it.ts":()=>Promise.resolve().then(()=>require("./cjs/CPZf2TWM.cjs")),"./languages/ja.ts":()=>Promise.resolve().then(()=>require("./cjs/D7UQ9OK7.cjs")),"./languages/ko.ts":()=>Promise.resolve().then(()=>require("./cjs/BMDJStMQ.cjs")),"./languages/pt.ts":()=>Promise.resolve().then(()=>require("./cjs/etCQgYrr.cjs")),"./languages/tr.ts":()=>Promise.resolve().then(()=>require("./cjs/DKQwAy8C.cjs"))}),`./languages/${e}.ts`,3);return gr.set(e,n),n}return xn}catch{return xn}}const{Provider:kh,useContext:se}=be("Localization"),Lh=({language:e=navigator.language,languageCode:t,logger:n,stringSet:r,children:s})=>{const[o,i]=l.useState(gr.get(Zt));return l.useEffect(()=>{const c=t??Yi(e);o.language!==c&&(n==null||n.debug("localization.useEffect: update language",{from:o.language,to:c}),wh(c).then(i))},[e,t,n]),a.createElement(kh,{value:{language:o.language,defaultStringSet:o.stringSet,stringSet:{...o.stringSet,...r},dateLocale:o.dateLocale,format:(c,u,d)=>at.format(c,u,{locale:o.dateLocale,...d})}},s)},Rn="data-sb-agent-theme",Qs=e=>(t,...n)=>{let r="";return t.forEach((s,o)=>{r+=s+(n[o]??"")}),`[${Rn}='${e}'] & { ${r} }`},Q={light:Qs("light"),dark:Qs("dark")},Oh=G.css(({theme:e})=>{const{palette:t}=e;return`
|
|
8
8
|
:root,
|
|
9
9
|
:host {
|
|
10
10
|
--sendbird-primary-extra-dark: ${t.primary.extraDark};
|
|
@@ -53,7 +53,7 @@
|
|
|
53
53
|
--sendbird-overlay-dark: ${t.overlay.dark};
|
|
54
54
|
--sendbird-overlay-light: ${t.overlay.light};
|
|
55
55
|
}
|
|
56
|
-
`}),Nh=
|
|
56
|
+
`}),Nh=G.css`[${Rn}='light'] &{--sb-text-high-emphasis:var(--sendbird-onlight-text-high-emphasis);--sb-text-mid-emphasis:var(--sendbird-onlight-text-mid-emphasis);--sb-text-low-emphasis:var(--sendbird-onlight-text-low-emphasis);--sb-text-disabled:var(--sendbird-onlight-text-disabled);--sb-text-high-emphasis-inverse:var(--sendbird-ondark-text-high-emphasis);--sb-text-mid-emphasis-inverse:var(--sendbird-ondark-text-mid-emphasis);--sb-text-low-emphasis-inverse:var(--sendbird-ondark-text-low-emphasis);--sb-text-disabled-inverse:var(--sendbird-ondark-text-disabled);--sb-bg-50-600:var(--sendbird-background-50);--sb-bg-100-500:var(--sendbird-background-100);--sb-bg-300-500:var(--sendbird-background-300);--sb-bg-200-400:var(--sendbird-background-200);--sb-primary:var(--sendbird-primary-main);--sb-secondary:var(--sendbird-secondary-main);--sb-error:var(--sendbird-error-main);--sb-information:var(--sendbird-information-light);}[${Rn}='dark'] &{--sb-text-high-emphasis:var(--sendbird-ondark-text-high-emphasis);--sb-text-mid-emphasis:var(--sendbird-ondark-text-mid-emphasis);--sb-text-low-emphasis:var(--sendbird-ondark-text-low-emphasis);--sb-text-disabled:var(--sendbird-ondark-text-disabled);--sb-text-high-emphasis-inverse:var(--sendbird-onlight-text-high-emphasis);--sb-text-mid-emphasis-inverse:var(--sendbird-onlight-text-mid-emphasis);--sb-text-low-emphasis-inverse:var(--sendbird-onlight-text-low-emphasis);--sb-text-disabled-inverse:var(--sendbird-onlight-text-disabled);--sb-bg-50-600:var(--sendbird-background-600);--sb-bg-100-500:var(--sendbird-background-500);--sb-bg-300-500:var(--sendbird-background-500);--sb-bg-200-400:var(--sendbird-background-400);--sb-primary:var(--sendbird-primary-light);--sb-secondary:var(--sendbird-secondary-light);--sb-error:var(--sendbird-error-light);--sb-information:var(--sendbird-information-light);}`,E={color:{primary:{dark:"var(--sendbird-primary-dark)",main:"var(--sendbird-primary-main)"},secondary:{dark:"var(--sendbird-secondary-dark)",light:"var(--sendbird-secondary-light)"},error:{dark:"var(--sendbird-error-dark)",light:"var(--sendbird-error-light)"},information:{main:"var(--sendbird-information-main)",light:"var(--sendbird-information-light)"},background700:"var(--sendbird-background-700)",background500:"var(--sendbird-background-500)",background400:"var(--sendbird-background-400)",background300:"var(--sendbird-background-300)",background200:"var(--sendbird-background-200)",background100:"var(--sendbird-background-100)",background50:"var(--sendbird-background-50)",onlight:{textLowEmphasis:"var(--sendbird-onlight-text-low-emphasis)",textDisabled:"var(--sendbird-onlight-text-disabled)"},ondark:{textHighEmphasis:"var(--sendbird-ondark-text-high-emphasis)",textMidEmphasis:"var(--sendbird-ondark-text-mid-emphasis)",textLowEmphasis:"var(--sendbird-ondark-text-low-emphasis)",textDisabled:"var(--sendbird-ondark-text-disabled)"},overlay:{dark:"var(--sendbird-overlay-dark)"}},themedColor:{textHighEmphasis:"var(--sb-text-high-emphasis)",textMidEmphasis:"var(--sb-text-mid-emphasis)",textLowEmphasis:"var(--sb-text-low-emphasis)",textDisabled:"var(--sb-text-disabled)",textHighEmphasisInverse:"var(--sb-text-high-emphasis-inverse)",textLowEmphasisInverse:"var(--sb-text-low-emphasis-inverse)",bg_50_600:"var(--sb-bg-50-600)",bg_100_500:"var(--sb-bg-100-500)",bg_300_500:"var(--sb-bg-300-500)",bg_200_400:"var(--sb-bg-200-400)",primary:"var(--sb-primary)",error:"var(--sb-error)",secondary:"var(--sb-secondary)"}};class Ht extends l.PureComponent{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(t){var n,r;(r=(n=this.props).onError)==null||r.call(n,t)}render(){const{fallback:t=null,errorFallback:n=t,loadingFallback:r=t,children:s}=this.props;return this.state.hasError?n:a.createElement(l.Suspense,{fallback:r},s)}}const Ze=e=>{const t=e;return typeof t=="number"?`${t}px`:t},Dh=e=>a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",...e},a.createElement("path",{className:"fill",d:"M52.552 11.448a2.666 2.666 0 0 1 .222 3.52l-.222.251-16.781 16.78 16.781 16.782a2.665 2.665 0 0 1 0 3.771 2.666 2.666 0 0 1-3.52.222l-.251-.222L32 35.771 15.219 52.552a2.665 2.665 0 0 1-3.771 0 2.666 2.666 0 0 1-.222-3.52l.222-.251L28.228 32l-16.78-16.781a2.665 2.665 0 0 1 0-3.771 2.666 2.666 0 0 1 3.52-.222l.251.222 16.78 16.78 16.782-16.78a2.665 2.665 0 0 1 3.771 0z",fill:"#000",fillRule:"evenodd"})),$h=e=>a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 16 16",...e},a.createElement("path",{className:"fill",d:"M7.33348 7.3335L2.00015 7.3335L2.00015 6.00016H5.05735L1.3335 2.27631L2.27631 1.3335L6.00015 5.05734V2.00016L7.33348 2.00016L7.33348 7.3335ZM8.66683 8.66683H14.0002V10.0002L10.943 10.0002L14.6668 13.724L13.724 14.6668L10.0002 10.943V14.0002H8.66683L8.66683 8.66683Z",fill:"#000",fillRule:"evenodd"})),Fh=e=>a.createElement("svg",{viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg",...e},a.createElement("path",{className:"fill",fillRule:"evenodd",clipRule:"evenodd",d:"M2 2H7.33333V3.33333L4.27613 3.33333L7.99999 7.05719L7.05718 8L3.33333 4.27616L3.33333 7.33333H2V2ZM14 14H8.66667V12.6667H11.7239L8.00001 8.94281L8.94282 8L12.6667 11.7238V8.66667H14V14Z",fill:"#000"})),Ph=e=>a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",fill:"evenodd",...e},a.createElement("path",{className:"fill",fill:"#0D0D0D",d:"M50.667 18.667H13.333v-5.334h37.334zM50.667 34.667H13.333v-5.334h37.334zM13.333 50.667h37.334v-5.334H13.333z"})),Uh=e=>a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",...e},a.createElement("path",{fill:"#000",fillRule:"evenodd",d:"M59.795 29.43 7.329 2.979C4.691 1.802 1.76 4.153 2.932 6.798l6.925 18.609a2 2 0 0 0 1.544 1.275l32.273 5.394L11.4 37.47a1.998 1.998 0 0 0-1.544 1.275L2.932 57.353c-.879 2.645 1.76 4.997 4.397 3.527l52.466-26.453c2.051-.882 2.051-3.82 0-4.996z",className:"fill"})),Bh=new Set(["send","chat","message","chevron-right","good","good-filled","bad","bad-filled"]),Hh={close:Dh,send:Uh,menu:Ph,expand:Fh,collapse:$h,spinner:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/Cf3-irI8.cjs"))),chat:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/BmdfYY9c.cjs"))),message:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/CmWLVNPR.cjs"))),error:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DNmdC4-j.cjs"))),refresh:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/D00MOxhE.cjs"))),"chevron-down":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/wf-LdaaN.cjs"))),"chevron-right":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/B0k-GApQ.cjs"))),done:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/kp5wcW4s.cjs"))),"done-circle":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/Bwaslfwl.cjs"))),stop:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/w1C9O3WB.cjs"))),"stop-circle":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DGubkk9p.cjs"))),user:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/CtHfgPDp.cjs"))),"file-document":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/_YfLwFkX.cjs"))),download:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/BN09c8-A.cjs"))),attach:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DcDTXo8_.cjs"))),"close-filled":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/D1kINslt.cjs"))),agent:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/Ce1MzjFq.cjs"))),actionbook:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/CXa-CGHE.cjs"))),function:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/zbLY6xl_.cjs"))),"radio-on":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/B9NJk4MI.cjs"))),"radio-off":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/Bb0r6Nhu.cjs"))),confluence:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/c6TZaE94.cjs"))),zendesk:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DqpDy_26.cjs"))),salesforce:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/BsgzT_SF.cjs"))),sprinklr:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/D97ZpKUC.cjs"))),website:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/ygZY2D-5.cjs"))),snippet:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/BCFOnu0u.cjs"))),template:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/eJXfXI1_.cjs"))),source:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/yVmX6iux.cjs"))),copy:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/COgkkyBM.cjs"))),show:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DM-WWpci.cjs"))),mute:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/P_ra76fq.cjs"))),good:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DEgUVAck.cjs"))),bad:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/C0s7eAf7.cjs"))),"good-filled":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/Chg8xHXT.cjs"))),"bad-filled":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/CGkmTaBn.cjs"))),delight:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DCB0iTxd.cjs"))),photo:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/GQlGFYP2.cjs"))),add:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DEGDJBmd.cjs"))),document:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DBHlAmeA.cjs"))),memory:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DB0sLqre.cjs"))),activity:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DP95uu-Y.cjs")))},Gh=e=>({size:t=24,color:n=E.color.primary.main,flipInRtl:r=!1})=>a.createElement(Vh,{$size:t,$color:n,$rtlFlip:r},a.createElement(Ht,{errorFallback:a.createElement(qh,null)},a.createElement(e,null))),Zi=Object.fromEntries(Object.entries(Hh).map(([e,t])=>[e,Gh(t)])),zh=G.css`[dir='rtl'] &:not([dir='ltr']),&[dir='rtl']{transform:scaleX(-1);}`,Vh=C.default.span.attrs({"aria-hidden":"true"})`
|
|
57
57
|
width: ${({$size:e})=>Ze(e)};
|
|
58
58
|
height: ${({$size:e})=>Ze(e)};
|
|
59
59
|
display: inline-block;
|
|
@@ -75,20 +75,20 @@
|
|
|
75
75
|
}
|
|
76
76
|
|
|
77
77
|
${({$rtlFlip:e})=>e&&zh};
|
|
78
|
-
`,qh=()=>a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64"},a.createElement("rect",{x:"8",y:"8",width:"48",height:"48",fill:"none",className:"stroke",rx:"4"}),a.createElement("line",{x1:"20",y1:"20",x2:"44",y2:"44",className:"stroke"}),a.createElement("line",{x1:"44",y1:"20",x2:"20",y2:"44",className:"stroke"})),{Provider:Kh,useContext:Yh}=be("MessengerIcon",{icons:Zi}),Wh=({icons:e,children:t})=>{const n=l.useMemo(()=>({icons:bu(Zi,e)}),[e]);return a.createElement(Kh,{value:n},t)},{Provider:jh,useContext:Ji}=be("MessengerTheme");function Xh(e){const{theme:t,appearance:n,logger:r}=e;return a.createElement(cd,{appearance:n,palette:t==null?void 0:t.palette,typography:t==null?void 0:t.typography,colors:t==null?void 0:t.colors,logger:r},a.createElement(Zh,{...e}))}function Zh({rootElement:e=document.body,children:t}){const{theme:n,updateTheme:r}=Pr();return l.useLayoutEffect(()=>{e.setAttribute(Rn,n.selectedTheme)},[e,n.selectedTheme]),a.createElement(
|
|
78
|
+
`,qh=()=>a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64"},a.createElement("rect",{x:"8",y:"8",width:"48",height:"48",fill:"none",className:"stroke",rx:"4"}),a.createElement("line",{x1:"20",y1:"20",x2:"44",y2:"44",className:"stroke"}),a.createElement("line",{x1:"44",y1:"20",x2:"20",y2:"44",className:"stroke"})),{Provider:Kh,useContext:Yh}=be("MessengerIcon",{icons:Zi}),Wh=({icons:e,children:t})=>{const n=l.useMemo(()=>({icons:bu(Zi,e)}),[e]);return a.createElement(Kh,{value:n},t)},{Provider:jh,useContext:Ji}=be("MessengerTheme");function Xh(e){const{theme:t,appearance:n,logger:r}=e;return a.createElement(cd,{appearance:n,palette:t==null?void 0:t.palette,typography:t==null?void 0:t.typography,colors:t==null?void 0:t.colors,logger:r},a.createElement(Zh,{...e}))}function Zh({rootElement:e=document.body,children:t}){const{theme:n,updateTheme:r}=Pr();return l.useLayoutEffect(()=>{e.setAttribute(Rn,n.selectedTheme)},[e,n.selectedTheme]),a.createElement(G.ThemeProvider,{theme:n},a.createElement(jh,{value:{theme:n,updateTheme:r,rootElement:e}},t))}const Jh=(e,t)=>{l.useEffect(()=>{const n=ut(t)instanceof ShadowRoot,r=ut(t,!0);if(!(n?t:r).querySelector(`link[href*='${e}']`)){const o=r.createElement("link");o.rel="stylesheet",o.href=e,(n?t:r.head).appendChild(o)}},[e,t])},Qh=(e,t=document.body)=>{l.useEffect(()=>{if(!e)return;const n=ut(t),s=n instanceof ShadowRoot?t:n.head;if(!s)return;const o=`sba-${btoa(e).slice(0,10)}`;let i=s.querySelector(`style#${o}`);i?i.textContent!==e&&(i.textContent=e):(i=s.ownerDocument.createElement("style"),i.id=o,i.textContent=e,s.appendChild(i))},[e,t])},ef=80,tf=()=>{const{stringSet:e}=se(),t={screenConversation:e.A11Y_SCREEN_CONVERSATION,screenConversationWithAgent:e.A11Y_SCREEN_CONVERSATION_WITH_AGENT,screenConversationListNoCount:e.A11Y_SCREEN_CONVERSATION_LIST_NO_COUNT,screenConversationListWithCount:e.A11Y_SCREEN_CONVERSATION_LIST_WITH_COUNT,newMessage:e.A11Y_NEW_MESSAGES_RECEIVED,newMessageFromSender:e.A11Y_NEW_MESSAGES_RECEIVED_FROM_SENDER,typing:e.A11Y_TYPING_FORMAT,sendFailed:e.A11Y_MESSAGE_FAILED,agentConnected:e.A11Y_AGENT_CONNECTED,conversationClosed:e.A11Y_CONVERSATION_CLOSED,csatDisplayed:e.A11Y_CSAT_DISPLAYED,csatExpired:e.CSAT_SUBMISSION_EXPIRED,emptyState:e.A11Y_EMPTY_CONVERSATION,inputDisabled:e.A11Y_INPUT_DISABLED,fileSizeExceeded:e.A11Y_FILE_SIZE_EXCEEDED,csatFormError:e.A11Y_CSAT_FORM_ERROR},n=l.useRef(t);return n.current=t,n},Qi=be("AriaLiveRegion",{announce:ue,announceScreenEntry:ue,announceStatus:ue,announceError:ue,flush:ue,setSuppressionState:ue}),nf=Qi.Provider,Kr=Qi.useContext,rf={position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},sf=({children:e})=>{const t=l.useRef(null),n=l.useRef(new Set),r=l.useRef(ue),s=tf(),[o]=l.useState(()=>jm(g=>{r.current(g)},{throttleMs:1e3,isSuppressed:()=>n.current.size>0}));r.current=g=>{const _=t.current;_&&(_.textContent="",requestAnimationFrame(()=>{_.textContent=g}))},l.useEffect(()=>()=>{o.destroy()},[o]);const i=o.announce,c=o.flush,u=l.useCallback(g=>{const _=Zm(g,s.current);i(_)},[i]),d=l.useCallback((g,_)=>{const y=Jm(g,s.current),b=(_==null?void 0:_.mode)??Xm(g.event);i(y,{mode:b,dedupeKey:_==null?void 0:_.dedupeKey})},[i]),m=l.useCallback((g,_)=>{const y=Qm(g,s.current);o.announceIgnoringSuppression(y),_&&setTimeout(()=>{_.focus()},ef)},[o]),h=l.useCallback((g,_)=>{if(_){n.current.add(g);return}n.current.delete(g)},[]),f=l.useMemo(()=>({announce:i,announceScreenEntry:u,announceStatus:d,announceError:m,flush:c,setSuppressionState:h}),[i,m,u,d,c,h]);return a.createElement(nf,{value:f},e,a.createElement("div",{ref:t,role:"status","aria-live":"polite","aria-atomic":"true",style:rf}))},ea=be("ConversationAnnouncements",{announcementsEnabled:!0,announce:ue,announceScreenEntry:ue,announceStatus:ue,announceError:ue,setIsSuppressed:ue,setStatusPauseState:ue,flush:ue}),of=ea.Provider,ot=ea.useContext,af=({children:e,announcementsEnabled:t=!0})=>{const{announce:n,announceScreenEntry:r,announceStatus:s,announceError:o,flush:i,setSuppressionState:c}=Kr(),u=l.useRef([]),d=l.useRef(new Set),m=l.useRef(Symbol("conversation-announcements")),h=l.useCallback(T=>{if(!t||!T){c(m.current,!1);return}c(m.current,!0)},[t,c]),f=l.useCallback(()=>{u.current=[]},[]),g=l.useCallback(()=>{if(u.current.length===0)return;if(!t){f();return}const T=[...u.current];f(),T.forEach(R=>{i(),s(R.params,R.options)})},[s,t,f,i]),_=l.useCallback((T,R)=>{if(R){d.current.add(T);return}d.current.delete(T),d.current.size===0&&g()},[g]),y=l.useCallback(T=>{t&&n(T)},[n,t]),b=l.useCallback(T=>{t&&r(T)},[r,t]),p=l.useCallback((T,R)=>{if(t){if(d.current.size>0){u.current.push({params:T,options:R});return}s(T,R)}},[s,t]),S=l.useCallback((T,R)=>{t&&o(T,R)},[o,t]);l.useLayoutEffect(()=>(t||(f(),c(m.current,!1)),()=>{f(),c(m.current,!1)}),[t,f,c]);const A=l.useMemo(()=>({announcementsEnabled:t,announce:y,announceScreenEntry:b,announceStatus:p,announceError:S,setIsSuppressed:h,setStatusPauseState:_,flush:i}),[t,i,y,S,b,p,h,_]);return a.createElement(of,{value:A},e)},Dn=["a[href]","button:not(:disabled)","input:not(:disabled)","select:not(:disabled)","textarea:not(:disabled)",'[tabindex]:not([tabindex="-1"])'].join(", "),ta=`${Dn}, [tabindex="-1"]`,Tt=e=>{if(!e.isConnected||e.hidden)return!1;let t=e;const n=e.ownerDocument.defaultView;for(;t;){if(t.hidden||t.getAttribute("aria-hidden")==="true")return!1;if(n){const r=n.getComputedStyle(t);if(r.display==="none"||r.visibility==="hidden")return!1}t=t.parentElement}return!0},Gt=(e,t)=>{for(const n of e.querySelectorAll(t))if(!n.hasAttribute(Gr)&&Tt(n))return n;return null},na=e=>{let t=null,n=null;for(const r of e.querySelectorAll(Dn))r.hasAttribute(Gr)||Tt(r)&&(t??(t=r),n=r);return t?{first:t,last:n}:null},ra=(e,t)=>e instanceof ShadowRoot&&!(t instanceof HTMLElement)?e.host.ownerDocument.activeElement===e.host:t instanceof HTMLElement?e instanceof Document?t===e.body||t===e.documentElement:!1:!0,cf=(e,t,n)=>ra(e,t)||n!=null&&t instanceof HTMLElement&&n.contains(t),Yr=e=>Gt(e,lh),sa=e=>Yr(e)??Gt(e,Dn),lf=e=>{const t=Yr(e);if(t)return t;const n=e.querySelector(dh);return(n?Gt(n,ta):null)??Gt(e,Dn)},H=({as:e,variant:t="body1",color:n,maxTextLines:r,className:s,...o})=>a.createElement(mf,{as:e,$variant:t,className:s,$color:n,$maxTextLines:r,...o}),eo=new WeakMap,uf=(e,t)=>{let n=eo.get(t);n||(n=new Map,eo.set(t,n));const r=n.get(e);if(r)return r;const s=t[e]??t.body1,o=G.css`font-size:${Ze(s.fontSize)};font-weight:${s.fontWeight};${s.fontFamily?`font-family: ${s.fontFamily};`:""}
|
|
79
79
|
${s.lineHeight?`line-height: ${s.lineHeight};`:"line-height: 100%;"}
|
|
80
|
-
`;return n.set(e,o),o},df=e=>e?B.css`display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:${e};overflow:hidden;`:"",mf=b.default.span`font-stretch:normal;letter-spacing:normal;${({$variant:e,theme:t})=>uf(e,t.typography)}color:${({$color:e})=>e};${({$maxTextLines:e})=>df(e)}`;async function Wr(e){let t=e;t&&(!t.startsWith("http://")&&!t.startsWith("https://")&&(t="https://"+t),window.open(t,"_blank","noopener,noreferrer"))}function we(e){requestAnimationFrame(()=>{requestAnimationFrame(()=>{e()})})}const pr='[role="dialog"][aria-modal="true"]',hf=(e,t)=>{const n=new Set(Array.from(e.ownerDocument.querySelectorAll(pr)).filter(s=>s!==e&&(s.contains(e)||e.contains(s)))),r=t==null?void 0:t.closest(pr);return r&&r!==e&&n.add(r),n},ff=(e,t)=>Array.from(e.ownerDocument.querySelectorAll(pr)).some(n=>n!==e&&!t.has(n)&&!n.contains(e)&&Tt(n)),gf=e=>{const t=sa(e)??e;t===e&&oa(e),t.focus()},oa=e=>{e.hasAttribute("tabindex")||e.setAttribute("tabindex","-1")},pf=(e,t)=>{const n=na(e);if(!n){oa(e),e.focus();return}n[t].focus()},to=(e,t)=>{const n=e.ownerDocument.createElement("span");return n.tabIndex=0,n.setAttribute(Gr,uh),n.style.cssText=["position: fixed","width: 1px","height: 1px","opacity: 0","overflow: hidden","pointer-events: none"].join(";"),n.addEventListener("focus",()=>pf(e,t)),n},_f=(e,t)=>{e.key==="Tab"&&(e.defaultPrevented||e.target===t&&(na(t)||(e.preventDefault(),t.focus())))},$n=(e,t,{nameReady:n=!0}={})=>{const r=l.useRef(0),s=l.useRef(!1);l.useEffect(()=>{if(!e||!t.current){s.current=!1;return}r.current+=1;const o=r.current,i=t.current,c=i.getRootNode(),u=c.activeElement instanceof HTMLElement?c.activeElement:null,d=hf(i,u);return()=>{u&&we(()=>{if(r.current!==o)return;const m=c.activeElement;i.isConnected&&m instanceof HTMLElement&&m!==i&&!i.contains(m)&&!ra(c,m)&&m.matches(ta)&&Tt(m)||ff(i,d)||!u.isConnected||!Tt(u)||u.focus()})}},[e,t]),l.useEffect(()=>{if(!e||!t.current)return;const o=t.current;let i=!1;const c=()=>{if(i||s.current||!o.isConnected)return;const m=o.getRootNode().activeElement;if(m instanceof HTMLElement&&m!==o&&o.contains(m)&&Tt(m)){s.current=!0;return}s.current=!0,gf(o)};if(n)return we(c),()=>{i=!0};const u=setTimeout(()=>we(c),Vi);return()=>{i=!0,clearTimeout(u)}},[e,t,n]),l.useEffect(()=>{if(!e||!t.current)return;const o=t.current,i=to(o,"last"),c=to(o,"first"),u=d=>_f(d,o);return o.insertBefore(i,o.firstChild),o.appendChild(c),o.addEventListener("keydown",u),()=>{o.removeEventListener("keydown",u),i.remove(),c.remove()}},[e,t])},dt=({style:e,portalContainerId:t,visible:n,onClose:r,children:s,cancelable:o=!0,"aria-label":i,"aria-labelledby":c,"aria-describedby":u})=>{const d=l.useRef(null),{resolvePortalContainer:m}=Vr();return $n(n,d),Th(n,o?r:le),n?uc.createPortal(a.createElement(Ef,{onClick:o?r:void 0,style:e},a.createElement(Cf,{ref:d,role:"dialog","aria-modal":"true","aria-label":i,"aria-labelledby":c,"aria-describedby":u,onClick:h=>h.stopPropagation()},s)),m(t)):null},Ef=b.default.div`position:fixed;top:0;left:0;width:100%;height:100%;background:${E.color.overlay.dark};display:flex;justify-content:center;align-items:center;z-index:${gt.MODAL};`,Cf=b.default.div`border-radius:4px;overflow:hidden;box-shadow:0 16px 24px 2px rgba(13,13,13,0.12),0 6px 30px 5px rgba(13,13,13,0.08),0 6px 10px -5px rgba(13,13,13,0.04);z-index:${gt.MODAL};`,bf=({id:e,children:t})=>a.createElement(vf,{id:e},t),vf=b.default.span`position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0;`,no=(e,t)=>{const n={role:"heading","aria-level":2,"aria-label":e};return t!=null&&t.active&&t.titleId?{...n,id:t.titleId,tabIndex:-1,...t.initialFocus===!1?{}:Pi}:n},yf=()=>{const e=`${l.useId()}-`;return(t,n)=>{if(!t)return{props:{},node:null};const r=e+n,s=l.createElement(bf,{id:r,children:t});return{props:{"aria-describedby":r},node:s}}},ro=({name:e,mimeType:t,selected:n},r)=>{var o;const s=Ye(t??"")?r.A11Y_FILE_IMAGE(e):zt(t??"")?r.A11Y_FILE_VIDEO(e):Qo({name:e,mimeType:t})?r.A11Y_FILE_PDF(e):r.A11Y_FILE_DOCUMENT(e);return n?((o=r.A11Y_FILE_SELECTED)==null?void 0:o.call(r,s))??`${s}, selected`:s},Sf=e=>t=>{t.repeat||(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())},$t=({onActivate:e})=>({role:"button",tabIndex:0,onClick:e,onKeyDown:Sf(e)}),Af=({disabled:e,currentIndex:t,totalCount:n,onNavigate:r})=>s=>{var u;if(e||n<=0)return;let o=null;switch(s.key){case"ArrowRight":case"ArrowDown":o=(t+1)%n;break;case"ArrowLeft":case"ArrowUp":o=(t-1+n)%n;break;default:return}s.preventDefault(),r(o);const i=s.currentTarget.parentElement,c=i==null?void 0:i.querySelectorAll('[role="radio"]');(u=c==null?void 0:c[o])==null||u.focus()},so=(e,t,n,r,s,o)=>{let i=-1;return(e||!s&&n===0)&&(i=0),{role:"radio","aria-checked":e,"aria-disabled":t,onKeyDown:Af({disabled:t,currentIndex:n,totalCount:r,onNavigate:o}),tabIndex:i}},re=()=>{const{stringSet:e}=se(),t=yf(),n=(i,c)=>{let u=e.A11Y_HINT_OPEN_FILE,d="of";Ye(i??"")&&(u=e.A11Y_HINT_OPEN_IMAGE,d="oi"),c!==void 0&&(d+=c);const m=t(u,d);return{props:m.props,descriptionNode:m.node}},r=i=>({"aria-label":ro(i,e)});return{launcher:{button:({isOpened:i,opensConversationList:c})=>{const u=ah({intent:sh({isOpened:i,opensConversationList:c}),strings:{openConversation:e.A11Y_OPEN_CONVERSATION,openConversationList:e.A11Y_OPEN_CONVERSATIONS,closeConversation:e.A11Y_CLOSE_CONVERSATION,closeConversationList:e.A11Y_CLOSE_CONVERSATIONS,hintOpenConversation:e.A11Y_HINT_OPEN_CONVERSATION,hintOpenConversationList:e.A11Y_HINT_OPEN_CONVERSATIONS,hintCloseConversation:e.A11Y_HINT_CLOSE_CONVERSATION}});let d="lc";u.hint===e.A11Y_HINT_OPEN_CONVERSATION&&(d="lo"),u.hint===e.A11Y_HINT_OPEN_CONVERSATIONS&&(d="los");const m=t(u.hint,d);return{props:{"aria-label":u.label,...m.props},descriptionNode:m.node}}},messenger:{closeButton:()=>({props:{"aria-label":e.A11Y_CLOSE_MESSENGER},descriptionNode:null}),expandButton:i=>{let c=e.A11Y_EXPAND_MESSENGER;return i&&(c=e.A11Y_COLLAPSE_MESSENGER),{props:{"aria-label":c},descriptionNode:null}},connectionDelayDialog:()=>({props:{"aria-label":e.CONNECTION_DELAY__TITLE},descriptionNode:null})},conversation:{header:{menuButton:()=>{const i=e.A11Y_HINT_OPEN_MENU,c=t(i,"mb");return{props:{"aria-label":e.A11Y_MENU,...c.props},descriptionNode:c.node}},closeConversationButton:()=>{const i=e.A11Y_HINT_CLOSE_CONVERSATION,c=t(i,"cc");return{props:{"aria-label":e.A11Y_CLOSE_CONVERSATION,...c.props},descriptionNode:c.node}},handoffButton:()=>{const i=e.A11Y_HINT_CONNECT_TO_AGENT,c=t(i,"h");return{props:{"aria-label":e.A11Y_CONNECT_AGENT,...c.props},descriptionNode:c.node}},title:(i,c)=>({props:no(i,c),descriptionNode:null}),memoryIndicator:i=>{let c=e.A11Y_MEMORY_INDICATOR_OFF,u="mof";i&&(c=e.A11Y_MEMORY_INDICATOR_ON,u="mon");const d=t(c,u);return{props:{"aria-label":e.A11Y_MEMORY_INDICATOR_MANAGE,...d.props},descriptionNode:d.node}}},messageInput:{attachFileButton:()=>{const i=e.A11Y_HINT_ATTACH_FILE,c=t(i,"af");return{props:{"aria-label":e.A11Y_ATTACH_FILE,...c.props},descriptionNode:c.node}},sendButton:()=>{const i=e.A11Y_HINT_SEND_MESSAGE,c=t(i,"sm");return{props:{"aria-label":e.A11Y_SEND_MESSAGE,...c.props},descriptionNode:c.node}},textInput:i=>({props:{role:"textbox","aria-label":i,...hh},descriptionNode:null})},suggestedReplies:{item:(i,c)=>{const u=e.A11Y_HINT_SEND_REPLY,d=t(u,`sr${c}`);return{props:{"aria-label":`${e.A11Y_SUGGESTED_REPLY}, ${i}`,...d.props},descriptionNode:d.node}}},feedback:{container:()=>{const i=e.A11Y_HINT_SELECT_RATING,c=t(i,"fb");return{props:c.props,descriptionNode:c.node}},button:(i,c)=>{const u=e.A11Y_HINT_SELECT_RATING,d=t(u,`f${i}`);let m=e.FEEDBACK_BAD;return i==="good"&&(m=e.FEEDBACK_GOOD),{props:{"aria-label":m,...d.props,"aria-pressed":c},descriptionNode:d.node}},optionsBottomSheet:()=>({props:{"aria-label":e.A11Y_FEEDBACK_OPTIONS},descriptionNode:null})},newMessagesButton:()=>{const i=e.A11Y_HINT_VIEW_NEW_MESSAGES,c=t(i,"nm");return{props:{"aria-label":e.A11Y_SCROLL_TO_NEW_MESSAGES,...c.props},descriptionNode:c.node}},scrollToBottomButton:()=>{const i=e.A11Y_HINT_VIEW_NEW_MESSAGES,c=t(i,"sb");return{props:{"aria-label":e.A11Y_SCROLL_TO_BOTTOM,...c.props},descriptionNode:c.node}},startNewConversationButton:({onActivate:i})=>({props:{...$t({onActivate:i}),"aria-label":e.TALK_TO_AGENT},descriptionNode:null}),poweredByLink:()=>({props:{"aria-label":`${e.POWERED_BY} Sendbird`},descriptionNode:null}),retryButton:(i=e.RETRY)=>({props:{"aria-label":i},descriptionNode:null}),file:{label:(i,c,u)=>i?ro({name:i,mimeType:c,selected:u},e):"",preview:i=>({props:r(i),descriptionNode:null}),buttonLikePreview:({onActivate:i,...c},u)=>{const d=n(c.mimeType,u);return{props:{...$t({onActivate:i}),...r(c),...d.props},descriptionNode:d.descriptionNode}},removeButton:i=>({props:{"aria-label":e.A11Y_FILE_REMOVE_BUTTON(i)},descriptionNode:null})},csat:{scoresContainer:i=>{const c=e.A11Y_HINT_SELECT_RATING,u=t(c,"cs");return{props:{role:"radiogroup","aria-label":i,...u.props},descriptionNode:u.node}},scoreItem:({score:i,label:c,selected:u,disabled:d,currentIndex:m,totalCount:h,hasSelection:f,onChange:g})=>{var p;const C=c.trim()||c,v=e.A11Y_HINT_SELECT_RATING,_=t(v,`cs${i}`);return{props:{disabled:d,onClick:()=>g(i),...so(u,d,m,h,f,S=>g(S+1)),..._.props,"aria-label":((p=e.A11Y_CSAT_RATING_LABEL)==null?void 0:p.call(e,i,C))??`${i} / ${h} — ${C}`},descriptionNode:_.node}},submitButton:i=>({props:{"aria-label":i},descriptionNode:null})},form:{button:i=>({props:{"aria-label":i},descriptionNode:null}),textInput:(i,c,u,d)=>({props:{...d!=null&&d.labelId?{"aria-labelledby":d.labelId}:{"aria-label":i},"aria-required":c,"aria-disabled":u},descriptionNode:null}),numberInput:(i,c,u)=>({props:{"aria-label":i,"aria-required":c,"aria-disabled":u},descriptionNode:null}),singleSelectGroup:i=>{const c={role:"radiogroup"};return i&&(c["aria-label"]=i),{props:c,descriptionNode:null}},singleSelectOption:(i,c,u,d,m,h,f)=>({props:{...so(c,u,d,m,h,f),"aria-label":i},descriptionNode:null}),multiSelectOption:(i,c,u)=>({props:{"aria-label":i,"aria-pressed":c,"aria-disabled":u},descriptionNode:null})}},conversationList:{headerTitle:(i,c)=>({props:no(i,c),descriptionNode:null}),footer:{button:({onActivate:i})=>({props:{...$t({onActivate:i}),"aria-label":e.TALK_TO_AGENT},descriptionNode:null})},item:({agent:i,status:c,time:u,unreadCount:d,onActivate:m})=>{if(!m)return{props:{"aria-label":e.A11Y_CONVERSATION_ITEM(i,c,u,d)},descriptionNode:null};const h=e.A11Y_HINT_OPEN_CONVERSATION,f=t(h,"cli");return{props:{...$t({onActivate:m}),...f.props,"aria-label":e.A11Y_CONVERSATION_ITEM(i,c,u,d)},descriptionNode:f.node}}}}},Tf=({title:e,description:t,highlightedText:n})=>{const r=vm(t,n);return a.createElement(xf,null,a.createElement(Rf,null,a.createElement(U,{as:"div",variant:"h1",color:E.themedColor.textHighEmphasis},e),t&&a.createElement(Mf,null,a.createElement(U,{as:"div",variant:"body3",color:E.themedColor.textMidEmphasis},r.beforeText,r.highlightedText?a.createElement(wf,null,r.highlightedText):null,r.afterText))))},If=()=>{const{components:e}=Fn.useContext(),{stringSet:t}=se(),{messenger:n}=re(),r=Cm(),s=r.showDescription?bm(r.remainingTime):"",o=r.showDescription?t.CONNECTION_DELAY__DESCRIPTION(s):"";return a.createElement(dt,{portalContainerId:ye.WINDOW,visible:r.visible,onClose:le,...n.connectionDelayDialog().props},a.createElement(e.Dialog,{title:t.CONNECTION_DELAY__TITLE,description:o,highlightedText:s||void 0}))},Fn=je({template:If,components:{Dialog:Tf}}),xf=b.default.div`width:280px;padding:24px;margin:0 auto;border-radius:4px;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,Rf=b.default.div`display:flex;flex-direction:column;`,Mf=b.default.div`margin-top:16px;`,wf=b.default.strong`font-weight:700;`,kf=({url:e})=>Wr(e),{Provider:Lf,Consumer:ia,useContext:ce}=be("Messenger");function Of({children:e,state:t,enableCloseConversationButton:n=!1,enableExpandButton:r=!0,enableAutoDisconnectInLauncher:s=!0,...o}){const[i,c]=l.useState(!1),[u,d]=l.useState(!1),m={opened:(t==null?void 0:t.opened)??i,setOpened:(t==null?void 0:t.setOpened)??c,expanded:(t==null?void 0:t.expanded)??u,setExpanded:(t==null?void 0:t.setExpanded)??d},{resolveElement:h}=Vr(),f=l.useCallback(()=>{m.setOpened(!1)},[m.setOpened]);Ih(m.opened,f);const g=l.useRef(m.opened);l.useLayoutEffect(()=>{const _=g.current&&!m.opened;if(g.current=m.opened,!_)return;const p=ut(o.rootElement),S=h(ye.WINDOW);let A=!1;return we(()=>{var T;A||cf(p,p.activeElement,S)&&((T=h(ye.LAUNCHER))==null||T.focus())}),()=>{A=!0}},[m.opened,o.rootElement,h]);const{Template:C}=Fn.useContext(),v=l.useMemo(()=>{var _;return{...o.handlers,onClickLink:((_=o.handlers)==null?void 0:_.onClickLink)??kf}},[o.handlers]);return a.createElement(Ru,{...o},_=>a.createElement(Lf,{value:{...o,..._,state:m,enableCloseConversationButton:n,enableExpandButton:r,enableAutoDisconnectInLauncher:s,handlers:v}},a.createElement(C,null),e))}const aa=/iPad|iPhone|iPod/.test(navigator.userAgent),Nf=/Android/.test(navigator.userAgent),Jt=e=>aa||Nf;let Lt=null,er=null;const Df=(e,t=5e3)=>{Lt&&(clearInterval(Lt),clearTimeout(er));const n=document.title;Lt=setInterval(()=>{document.title=document.title===e?n:e},750),er=setTimeout(()=>{clearInterval(Lt),Lt=null,er=null,document.title=n},t)},ca=()=>{Promise.resolve().then(()=>require("./cjs/B93o4u0P.cjs")).then(e=>{new Audio(e.default).play().catch(()=>{})})},xe=B.css`&:focus-visible{outline:2px solid ${E.themedColor.primary};outline-offset:2px;}`,oo=e=>{if(typeof e=="string"||typeof e=="number")return String(e)},Pn=({visible:e,title:t,description:n,confirmText:r="OK",cancelText:s,onConfirm:o,onCancel:i,onClose:c,"aria-label":u})=>{const d=l.useId(),m=l.useId(),h=u??oo(t)??oo(n),f=u?void 0:t?d:n?m:void 0,g=t&&n?m:void 0,C=()=>{c(),we(()=>o==null?void 0:o())},v=()=>{c(),we(()=>i==null?void 0:i())};return a.createElement(dt,{portalContainerId:ye.WINDOW,visible:e,onClose:c,"aria-label":h,"aria-labelledby":f,"aria-describedby":g},a.createElement($f,null,a.createElement(Ff,null,t&&a.createElement("div",{id:d},a.createElement(U,{variant:"h1",color:E.themedColor.textHighEmphasis},t)),n&&a.createElement(Pf,{id:m},a.createElement(U,{variant:"body3",color:E.themedColor.textMidEmphasis},n))),a.createElement(Uf,null,s&&a.createElement(io,{onClick:v},a.createElement(U,{variant:"button",color:E.themedColor.textHighEmphasis},s)),a.createElement(io,{onClick:C},a.createElement(U,{variant:"button",color:E.themedColor.primary},r)))))},$f=b.default.div`width:360px;height:auto;padding-block:24px 12px;padding-inline:24px;margin:0 auto;border-radius:4px;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,Ff=b.default.div`margin-bottom:16px;`,Pf=b.default.div`margin-top:16px;`,Uf=b.default.div`display:flex;flex-direction:row;justify-content:flex-end;`,io=b.default.button`all:unset;display:flex;justify-content:center;align-items:center;border-radius:4px;cursor:pointer;background-color:transparent;padding:10px 16px;${xe}`,{Provider:Bf,useContext:De}=be("MessengerSession"),Hf=l.forwardRef(function({children:e,...t},n){return a.createElement(md,{ref:n,...t},r=>a.createElement(Gf,{...r},e))}),Gf=({children:e,...t})=>{const{chatSDK:n,logger:r,appId:s,aiAgentId:o,agentPreviewConfigs:i,state:c,handlers:u,dispatcher:d,_aiAgentSDK:m}=ce(),{userSessionInfo:h,authenticate:f,userSession:g,aiAgentInfo:C,launcherInfo:v}=t,[_,p]=l.useState(!1),S=l.useRef(null);ht(n,{async onUserJoined(T,M){var D,x,O,H;T.conversation&&T.conversation.type===de.ConversationType.PROACTIVE&&M.userId===((D=n.currentUser)==null?void 0:D.userId)&&(r.info("messengerSession.onUserJoined: proactive channel joined",T.url),(O=m.session)==null||O._updateActiveChannel({url:T.url,status:"open",conversationStatus:(x=T.conversation)==null?void 0:x.status}),c.setOpened(!0),zf({sound:document.hidden||!c.opened}),(H=S.current)==null||H.call(S,{channel:T}))}}),l.useEffect(()=>{f().then(({launcher:T})=>{T.auto_open&&!Jt()&&setTimeout(()=>c.setOpened(!0),500)}).catch(T=>{var M;r.error("messengerSession: failed to initialize",T),(M=u==null?void 0:u.onInitializeFailed)==null||M.call(u,T)})},[n,s,o,h==null?void 0:h.userId]),l.useEffect(()=>{const T=()=>p(!0);return d.subscribe(Ke.AnonymousSessionTokenExpired,T),()=>d.unsubscribe(Ke.AnonymousSessionTokenExpired,T)},[d]);const A=l.useCallback(()=>{t.deauthenticate().finally(()=>window.location.reload())},[t.deauthenticate]);return!g||!C||!v?null:a.createElement(Bf,{value:{...t,userSession:g,aiAgentInfo:{...C,...i==null?void 0:i.bot},launcherInfo:{...v,...i==null?void 0:i.launcher},registerOnJoinedProactiveConversation:T=>S.current=T}},e,a.createElement(Pn,{visible:_,title:"Session timed out",description:"Start a new conversation.",onConfirm:A,onClose:le}))};function zf({sound:e}){Df("🔔You have received a new message"),e&&ca()}const Mn=`@${Ge}-focused-channel`,la=`${Date.now()}-${Math.random().toString(36).slice(2)}`,Vf=()=>{try{const e=localStorage.getItem(Mn);return e?JSON.parse(e).channelUrl??null:null}catch{return null}},ao=e=>{try{localStorage.setItem(Mn,JSON.stringify({channelUrl:e,tabId:la}))}catch{}},co=()=>{try{const e=localStorage.getItem(Mn);if(!e)return;JSON.parse(e).tabId===la&&localStorage.removeItem(Mn)}catch{}},qf=(e,t)=>(l.useEffect(()=>{if(!t||!e)return;const n=()=>ao(e),r=()=>co();return document.hasFocus()&&ao(e),window.addEventListener("focus",n),window.addEventListener("blur",r),()=>{window.removeEventListener("focus",n),window.removeEventListener("blur",r),co()}},[t,e]),{isChannelViewedInAnyTab:()=>document.hasFocus()||Vf()===e}),Kf=e=>{const{config:t,chatSDK:n}=ce(),{sdkUser:r}=De(),s=t.conversation.messageAlertSoundEnabled,{isChannelViewedInAnyTab:o}=qf(e,s);ht(n,{onMessageReceived(i,c){if(!s||i.url!==e||o())return;(Qe(c)&&c.sender.userId!==(r==null?void 0:r.userId)||c.isAdminMessage()&&!c.silent)&&ca()}})};function Yf(e){return new Promise(t=>{const n=new Image;n.onload=function(){const r=String(n.width),s=String(n.height);URL.revokeObjectURL(n.src),t({width:r,height:s})},n.src=URL.createObjectURL(e)})}async function Wf(e){if("file"in e&&e.file instanceof File&&e.file.type.startsWith("image/")){const{width:t,height:n}=await Yf(e.file);return new Fe.MessageMetaArray({key:Xo,value:[t,n]})}}const jf=({onScrollAfterSendMessage:e})=>{const{agentPreviewConfigs:t,handlers:n}=ce(),r=l.useRef(t==null?void 0:t.agentAttributes);return r.current=t==null?void 0:t.agentAttributes,{onBeforeSendMessage:async s=>{const o=await Wf(s),i={...s,metaArrays:o?[o]:void 0},c=Xf(r.current);return c?{...i,data:JSON.stringify(c)}:i},onAfterSendMessage:s=>{var o,i,c;e(),(o=n==null?void 0:n.onMessageSend)==null||o.call(n,s.message),s.sendingStatus===Fe.SendingStatus.SUCCEEDED?(i=n==null?void 0:n.onCustomEvent)==null||i.call(n,{type:"message-sent-succeeded",data:{message:s}}):s.sendingStatus===Fe.SendingStatus.PENDING&&((c=n==null?void 0:n.onCustomEvent)==null||c.call(n,{type:"message-sent-pending",data:{message:s}}))}}},Xf=e=>{if(!e)return null;const t={};return e.ai&&Object.keys(e.ai).length>0&&(t.ai_attrs=e.ai),e.safeguard&&Object.keys(e.safeguard).length>0&&(t.safeguard_attrs=e.safeguard),typeof e.use_prompt_cache=="boolean"&&(t.use_prompt_cache=e.use_prompt_cache),Object.keys(t).length>0?t:null},St=50,tr=St-40,{Provider:Zf,useContext:ua}=be("ConversationScroll"),lo={viewport:0,contentHeight:0,contentSnapshotHeight:0,shouldRecalc:!1,shouldUpdate:!1},nr=e=>Math.max(0,e.scrollHeight-e.scrollTop-e.clientHeight),uo=e=>Array.from(e.querySelectorAll(`#${Ge}-message-item`));function Jf({scrollMode:e,messageStackDirection:t,children:n}){const r=l.useRef(null),s=l.useRef({mutation:null,resize:null,resizeTargets:new Set}),o=l.useRef({distanceFromBottom:0,prevScrollTop:0}),i=l.useRef({awayByUser:!1,programmatic:!1,streaming:!1,reconcileTimer:null,userMessageTimer:null}),c=l.useRef(lo),[u,d]=l.useState(0),[m,h]=l.useState(0),[f,g]=l.useState(!1),[C,v]=l.useState(!1),[_,p]=l.useState(!0),S=$=>{const I=nr($);return o.current.distanceFromBottom=I,h(I),I},A=()=>{const $=i.current;$.reconcileTimer&&(clearTimeout($.reconcileTimer),$.reconcileTimer=null)},T=l.useCallback(()=>{const $=s.current;$.mutation&&($.mutation.disconnect(),$.mutation=null),$.resize&&($.resize.disconnect(),$.resize=null),$.resizeTargets.clear()},[]),M=l.useMemo(()=>f||t==="bottom"?"auto":e,[f,t,e]),L=()=>{c.current.contentSnapshotHeight=c.current.contentHeight,c.current.shouldUpdate=!0,c.current.shouldRecalc=!0},D=()=>{const $=r.current;!$||!c.current.shouldUpdate||d(I=>{c.current.shouldUpdate=!1;const{contentHeight:w,contentSnapshotHeight:N,shouldRecalc:z}=c.current,Y=$.clientHeight;if(N>w)return I;const te=x($,{messageType:"outgoing"});let Z=0;if(te){const pe=te.message.offsetTop-tr+Y;Z=Math.max(0,pe-w)}else{const pe=w-N,Xe=Y-tr;Z=Math.max(0,pe-Xe)}return I===0||Z!==I||z?(c.current.shouldRecalc=!1,Z):I})},x=l.useCallback(($,I)=>{const{messageType:w="all"}=I??{},N=uo($);let z=N;w==="outgoing"&&(z=N.filter(ae=>ae.getAttribute("data-layout-id")==="outgoingmessage"));const Y=z[z.length-1];if(!Y)return null;const te=$.getBoundingClientRect(),Z=Y.getBoundingClientRect(),pe=$.scrollTop+(Z.top-te.top),Xe=pe+Y.offsetHeight;return{message:Y,scrollTop:pe,lastMessageBottom:Xe}},[]),O=l.useCallback(()=>{const $=r.current;if(!$||M!=="fixed")return;const I=x($);c.current.contentHeight=(I==null?void 0:I.lastMessageBottom)??$.scrollHeight,!i.current.streaming&&c.current.contentSnapshotHeight>0&&L(),i.current.programmatic?o.current.distanceFromBottom=nr($):S($),D()},[M,x]),H=l.useCallback(()=>{T(),A(),c.current=lo,d(0),h(0),p(!0),o.current.distanceFromBottom=0,o.current.prevScrollTop=0,i.current.awayByUser=!1,i.current.programmatic=!1},[T]),F=l.useCallback(($=!0)=>{const I=o.current.distanceFromBottom>St;if(i.current.awayByUser=!1,h(0),!I){we(()=>{const w=r.current;w&&!i.current.awayByUser&&w.scrollTo({top:w.scrollHeight,behavior:"auto"})});return}i.current.programmatic||(i.current.programmatic=!0,p(!1),A()),we(()=>{const w=r.current;if(!w){i.current.programmatic=!1,p(!0);return}if(i.current.awayByUser){i.current.programmatic=!1,S(w),p(!0);return}const N=()=>{if(r.current!==w){i.current.programmatic=!1,r.current&&S(r.current),p(!0);return}i.current.programmatic=!1,S(w),p(!0)};if($&&!i.current.reconcileTimer){const z=setTimeout(N,500);i.current.reconcileTimer=z,w.addEventListener("scrollend",()=>{clearTimeout(z),i.current.reconcileTimer=null,N()},{once:!0})}w.scrollTo({top:w.scrollHeight,behavior:$?"smooth":"auto"}),$||N()})},[]),W=l.useCallback(()=>{const $=r.current;if($){if(i.current.awayByUser){S($);return}F(!1)}},[F]),q=l.useCallback(()=>{const $=r.current,I=s.current;if(!$||!I.resize)return;const w=new Set(uo($));for(const N of I.resizeTargets)w.has(N)||(I.resize.unobserve(N),I.resizeTargets.delete(N));for(const N of w)I.resizeTargets.has(N)||(I.resize.observe(N),I.resizeTargets.add(N))},[]),k=l.useCallback($=>{T();const I=s.current;typeof ResizeObserver<"u"&&(I.resize=new ResizeObserver(W),q());const w=new MutationObserver(()=>{q(),W()});I.mutation=w,w.observe($,{childList:!0})},[T,W,q]),G=l.useCallback($=>{if(!$){r.current=null,T();return}if(r.current=$,M!=="fixed"){k($);return}H(),c.current.viewport=$.clientHeight;const I=new MutationObserver(()=>{O()});s.current.mutation=I,I.observe($,{childList:!0,subtree:!0})},[T,M,O,H,k]),P=l.useCallback(()=>{const $=r.current;if(!$)return;const I=x($,{messageType:"outgoing"});I&&($.scrollTo({top:I.message.offsetTop-tr,behavior:"smooth"}),i.current.userMessageTimer&&clearTimeout(i.current.userMessageTimer),i.current.userMessageTimer=setTimeout(()=>{v(!1)},500))},[x]),V=($,I,w)=>{const N=nr($);if(w&&N>St){i.current.programmatic=!1,i.current.awayByUser=!0,A(),S($),p(!0),o.current.prevScrollTop=I;return}o.current.distanceFromBottom=N},me=($,I,w)=>{const z=S($)<=St;I&&!z&&(i.current.awayByUser=!0,A()),w&&z&&(i.current.awayByUser=!1)},Ie=$=>{const{scrollTop:I}=$.currentTarget,w=o.current.prevScrollTop;i.current.programmatic?V($.currentTarget,I,I<w):me($.currentTarget,I<w,I>w),o.current.prevScrollTop=I},j=l.useCallback(()=>{M==="fixed"&&(v(!0),L())},[M]),K=l.useCallback(()=>{M==="fixed"?setTimeout(()=>P(),300):F()},[M,P]),R=l.useCallback($=>{i.current.streaming=$,M==="fixed"?L():i.current.awayByUser||F()},[M,F]),X=l.useCallback($=>{g($),$&&(d(0),M==="fixed"&&T())},[T,M]),ne=l.useCallback($=>{M==="auto"&&$&&!i.current.awayByUser&&F()},[M,F]),Re=!(m<=St)&&!C,Le=l.useCallback(()=>o.current.distanceFromBottom>St,[]);return a.createElement(Zf,{value:{ref:G,state:{bottomSpace:u,isAwayFromBottom:Re,isScrollPositionReconciled:_,shouldCountNewMessages:Le},props:{onScroll:Ie},actions:{scrollToBottom:F,onBeforeMessageSend:j,onAfterMessageSend:K,onStreamingUpdate:R,onConversationClosed:X,onTypingIndicatorUpdate:ne}}},n)}const{Provider:Qf,Context:eg,useContext:Ae}=be("Conversation"),tg=({children:e})=>{var s;const{channelSource:t}=Ae(),n=(s=t.channel)==null?void 0:s.url,{checkForUserActionRequired:r}=sm(n);return l.useEffect(()=>{var i;const o=(i=t.channel)==null?void 0:i.lastMessage;o&&r(o)},[t.channel,r]),a.createElement(a.Fragment,null,e)},ng=({channelUrl:e,onClearChannelUrl:t,onNavigateToConversationList:n,conversationStatsEnabled:r,shouldMarkAsRead:s,children:o})=>{const{activeChannel:i,refreshActiveChannel:c}=De(),u=ua(),d=e||(i==null?void 0:i.url);Kf(d);const{onBeforeSendMessage:m,onAfterSendMessage:h}=jf({onScrollAfterSendMessage:()=>{u.actions.onAfterMessageSend()}}),f=l.useCallback(_=>(u.actions.onBeforeMessageSend(),m(_)),[u.actions,m]),g=l.useCallback(_=>{const p=_.some(S=>Me.isStreaming(S));u.actions.onStreamingUpdate(p)},[u.actions.onStreamingUpdate]),C=l.useCallback(_=>{u.actions.onConversationClosed(_===de.ConversationStatus.CLOSED)},[u.actions.onConversationClosed]),v=l.useCallback(async()=>{await c(),e&&(t==null||t())},[c,e,t]);return a.createElement(Ud,{key:d,channelUrl:d,onBeforeSendMessage:f,onAfterSendMessage:h,onMessagesUpdated:g,onMessagesReceived:g,onChannelDeleted:v,onConversationStatusChanged:C,conversationStatsEnabled:r,shouldMarkAsRead:s,shouldCountNewMessages:u.state.shouldCountNewMessages},_=>a.createElement(Qf,{value:{..._,conversationStatsEnabled:r??!0,scrollSource:u,goToActiveConversation:v,onNavigateToConversationList:n}},a.createElement(tg,null,o)))},da=({children:e,...t})=>{const{config:n}=ke(),{agentPreviewConfigs:r}=ce(),s=n.conversation.list.scrollMode,o=r==null?void 0:r.messageStackDirection;return a.createElement(Jf,{scrollMode:s,messageStackDirection:o},a.createElement(ng,{...t},e))},jr=l.createContext({onDrop:le,subscribe:()=>le}),_r=({children:e})=>{const t=l.useRef(new Set);return a.createElement(jr.Provider,{value:{onDrop:n=>{var r;if(n.preventDefault(),(r=n.dataTransfer)!=null&&r.files){const s=Array.from(n.dataTransfer.files);s.length>0&&t.current.forEach(o=>o(s))}},subscribe:n=>(t.current.add(n),()=>t.current.delete(n))}},e)},rg=({onDropFiles:e})=>{const{subscribe:t}=l.useContext(jr);l.useEffect(()=>t(e),[e])};_r.Consumer=({children:e})=>{const{onDrop:t}=l.useContext(jr);return e({onDrop:t,onDragOver:s=>s.preventDefault()})};const ma=be("WindowTitle",{hasWindowTitleReference:!1,isTitlePending:!1,isWindowNameReady:!0,registerWindowTitleReference:()=>le,registerWindowTitlePending:()=>le}),sg=ma.Provider,ha=ma.useContext,mo=()=>{const e=l.useRef(0),[t,n]=l.useState(!1),r=l.useCallback(()=>{let s=!0;return e.current+=1,e.current===1&&n(!0),()=>{s&&(s=!1,e.current=Math.max(0,e.current-1),e.current===0&&n(!1))}},[]);return[t,r]},Xr=({children:e})=>{const[t,n]=mo(),[r,s]=mo(),o=!r||t,i=l.useMemo(()=>({hasWindowTitleReference:t,isTitlePending:r,isWindowNameReady:o,registerWindowTitleReference:n,registerWindowTitlePending:s}),[t,r,n,s]);return a.createElement(sg,{value:i},e)},Un=ha,fa=({enabled:e,label:t})=>{const{registerWindowTitleReference:n,registerWindowTitlePending:r}=ha(),s=e&&t.trim().length>0;return l.useLayoutEffect(()=>{if(e)return r()},[r,e]),l.useLayoutEffect(()=>{if(s)return n()},[n,s]),{enabled:s,id:s?ye.WINDOW_TITLE:void 0}},og=(e,t)=>{const r=(t?Gt(e,t):null)??lf(e)??e;r===e&&!e.hasAttribute("tabindex")&&e.setAttribute("tabindex","-1"),r.focus({focusVisible:!1})},ga=(e,{enabled:t,ready:n,nameReady:r=!0,targetSelector:s,suppressed:o=!1})=>{const i=l.useRef(!1);l.useEffect(()=>{if(!t){i.current=!1;return}if(i.current||!e.current||o||s&&!n)return;const c=Yr(e.current)!=null;if(!s&&!c&&!n)return;let u=!1;const d=()=>{u||i.current||!e.current||(i.current=!0,og(e.current,s))};if(r)return we(d),()=>{u=!0};const m=setTimeout(()=>we(d),Vi);return()=>{u=!0,clearTimeout(m)}},[t,n,r,s,e,o])},ig=(e,t)=>{const{announcementsEnabled:n}=ot(),{channelSource:r}=Ae(),{isWindowNameReady:s}=Un(),o=Xi(),i=r.channel!=null||r.error!=null;ga(e,{enabled:n,ready:i,nameReady:s,targetSelector:t==="messageInput"?mh:void 0,suppressed:o})},ag=({enabled:e=!0}={})=>{var s;const{channelSource:t}=Ae(),n=(s=t.channel)==null?void 0:s.url,r=l.useCallback(o=>{const i=()=>{o(js()?"backgrounded":"foregrounded")};return document.addEventListener("visibilitychange",i),()=>document.removeEventListener("visibilitychange",i)},[]);Am({channelUrl:n,enabled:e,isInitiallyBackgrounded:js,isForegrounded:hr,subscribeToForegroundState:r})},cg=e=>Ye(e)||zt(e);function lg(e){return e.isAdminMessage()?e.message==="The channel's custom_type was updated.":!1}function ug(e,t){return e.filter(n=>Me.isWelcomeMessage(n,t))}const pa=(e,{previewWelcomeMessages:t,aiAgentUserId:n})=>e.filter(r=>lg(r)?!1:t.length>0?!Me.isWelcomeMessage(r,n):!0),dg=[],_a=()=>{var C,v,_,p,S,A;const{agentPreviewConfigs:e={},aiAgentId:t}=ce(),{aiAgentInfo:n,userSession:r}=De(),{channelSource:s,messageSource:o,state:{input:i,streamAnimation:c}}=Ae(),u=e.welcomeMessages??dg,d=l.useMemo(()=>pa(o.messages,{previewWelcomeMessages:u,aiAgentUserId:t}),[t,o.messages,u]),m=rt(s.channel),h=(v=(C=si(s.channel,r.userId))==null?void 0:C.nickname)==null?void 0:v.trim(),f=m?(p=(_=s.channel)==null?void 0:_.name)==null?void 0:p.trim():(S=n==null?void 0:n.nickname)==null?void 0:S.trim(),g=h||f||void 0;return{initialized:o.initialized,channelUrl:(A=s.channel)==null?void 0:A.url,agentName:g,isClosed:He(s.channel),isHandedOff:m,messages:d,filteredMessagesCount:d.length,hasWelcomeMessages:u.length>0,inputDisabled:i.disabled,inputDisabledBy:i.disabledBy,isStreamAnimating:c.isAnimating,subscribeMessageEvents:o.subscribeMessageEvents,currentUserId:r.userId}},mg=(e={})=>{const{announceScreenEntry:t,announcementsEnabled:n}=ot(),{initialized:r=!1,channelUrl:s,agentName:o,isClosed:i=!1,messages:c=[],hasWelcomeMessages:u=!1}=e,d=l.useRef(null),m=l.useMemo(()=>c.some(f=>Ne.isAdmin(f)&&Ne.isCSAT(f)),[c]),h=c.length===0&&!u;l.useEffect(()=>{if(!n){d.current=null;return}!r||!s||d.current!==s&&(t({screen:"conversation",agentName:o,isClosed:i,hasCSAT:m,...h?{isEmpty:!0}:{}}),d.current=s)},[o,t,n,s,m,r,i,h])},hg=()=>{const e=_a();mg(e)},fg=e=>({image:e.A11Y_RECEIVED_FILE_IMAGE,video:e.A11Y_RECEIVED_FILE_VIDEO,pdf:e.A11Y_RECEIVED_FILE_PDF,document:e.A11Y_FILE_DOCUMENT,receivedFilesImageCount:e.A11Y_RECEIVED_FILES_IMAGE_COUNT,multipleFilesCount:e.CONVERSATION_LIST__MULTIPLE_FILES_COUNT,codeBlockPlaceholder:e.A11Y_CODE_BLOCK_PLACEHOLDER}),ho=(e,t,n=at.format)=>{const r=Wm(e,fg(t)),s="sender"in e?e.sender:void 0,o=e.createdAt!=null&&e.createdAt!==0?n(e.createdAt,t.DATE_FORMAT__MESSAGE_TIMESTAMP):void 0;return{senderName:typeof(s==null?void 0:s.nickname)=="string"&&s.nickname.trim()||void 0,body:r||void 0,time:o}},gg={senderName:!0,body:!0,time:!0},pg=Object.keys(gg),_g=(e,t)=>pg.every(n=>e[n]===t[n]),fo=2e3,go=400,Er=e=>{const t=new Set;return"reqId"in e&&typeof e.reqId=="string"&&e.reqId.length>0&&t.add(`req:${e.reqId}`),"messageId"in e&&e.messageId>0&&t.add(`message:${String(e.messageId)}`),[...t]},Ea=e=>{if(!Ne.isAdmin(e)||!Ne.isCSAT(e))return null;const t=nh(e);return t?`csat:${t}`:null},Eg=e=>{const t=new Set;for(const n of e){const r=Ea(n);r&&t.add(r)}return t},Cg=(e,t)=>{for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r&&Er(r).some(s=>t.includes(s)))return r}},rr=(e,t)=>e.some(n=>t.includes(n)),po=()=>typeof document>"u"?null:document.activeElement instanceof HTMLElement?document.activeElement:null,sr=e=>new Map(e.map(({key:t,sendingStatus:n})=>[t,n])),bg=()=>{const{announceStatus:e,announcementsEnabled:t}=ot(),{stringSet:n,format:r}=se(),{channelUrl:s,messages:o,isClosed:i,isHandedOff:c,agentName:u,initialized:d,inputDisabled:m,inputDisabledBy:h,isStreamAnimating:f,subscribeMessageEvents:g,currentUserId:C}=_a(),{outgoingMessageStates:v,outgoingMessageStatusSignature:_}=l.useMemo(()=>{if(!C)return{outgoingMessageStates:[],outgoingMessageStatusSignature:""};const j=o.flatMap(K=>{const R=eh(K,C);return!R||!("sendingStatus"in K)?[]:[{key:R,sendingStatus:K.sendingStatus}]});return{outgoingMessageStates:j,outgoingMessageStatusSignature:j.map(({key:K,sendingStatus:R})=>`${K}:${R}`).join(",")}},[C,o]),p=l.useRef({isClosed:!1,isHandedOff:!1,inputDisabled:m,inputDisabledBy:h,outgoingMessageStatuses:sr(v)}),S=l.useRef({messages:o,currentUserId:C,inputDisabledBy:h,isStreamAnimating:f,stringSet:n,format:r}),A=l.useRef([]),T=l.useRef(null),M=l.useRef([]),L=l.useRef(new Set),D=l.useRef(new Set),x=l.useRef(!1),O=l.useRef(s);S.current={messages:o,currentUserId:C,inputDisabledBy:h,isStreamAnimating:f,stringSet:n,format:r};const H=()=>S.current.isStreamAnimating||S.current.inputDisabledBy==="ai_responding",F=()=>{T.current!=null&&(clearTimeout(T.current),T.current=null)},W=(j,K,R)=>{const X=R==null?void 0:R.replaceableForMs;if(j.length===0||!X)return;const ne=Date.now();M.current=[...M.current.filter(({replaceableUntil:oe})=>oe>ne),{eventKeys:j,parts:K,replaceableUntil:ne+X}]},q=()=>A.current.length>0,k=()=>{A.current=[]},G=()=>{const[j,...K]=A.current;if(!j)return!1;A.current=K;const{eventKeys:R,parts:X,dedupeKey:ne}=j,oe=$=>{W(R,$,{replaceableForMs:R.length>0?fo:void 0}),e({event:"newMessage",...$},ne?{dedupeKey:ne}:void 0)};if(R.length===0)return oe(X),!0;const Re=S.current,Le=Cg(Re.messages,R);if(Le){const $=ho(Le,Re.stringSet,Re.format);return oe($),!0}return oe(X),!0},P=()=>{for(F();G(););},V=(j=fo)=>{F(),T.current=setTimeout(()=>{if(T.current=null,H())return;const K=po(),[R]=A.current;if(!R)return;if(R.focusTarget!==K){A.current=[{...R,focusTarget:K},...A.current.slice(1)],V(go);return}G()&&q()&&V(go)},j)},me=(j,K,R)=>{const X={eventKeys:K,parts:j,focusTarget:po(),dedupeKey:R?R.dedupeKey??void 0:K[0]},ne=K.length===0?-1:A.current.findIndex(({eventKeys:oe})=>rr(oe,K));ne>=0?A.current=A.current.map((oe,Re)=>Re===ne?{...X,dedupeKey:R?X.dedupeKey:oe.dedupeKey}:oe):A.current=[...A.current,X],V()},Ie=(j,K,R)=>{if(j!=="messagesUpdated"||K.length===0)return!1;const X=Date.now(),ne=M.current.find(oe=>oe.replaceableUntil>X&&rr(oe.eventKeys,K));return ne?!_g(R,ne.parts):!1};l.useEffect(()=>{const j=O.current!==s;(!t||!d||j)&&(x.current=!1,D.current.clear(),k(),M.current=[],L.current.clear(),F(),j&&(O.current=s),!t||!d)||x.current||(x.current=!0,O.current=s,p.current={isClosed:i,isHandedOff:c,inputDisabled:m,inputDisabledBy:h,outgoingMessageStatuses:sr(v)},L.current=new Set(o.flatMap(K=>{if(!Me.isStreaming(K))return[];const R="sender"in K?K.sender:void 0;return(R==null?void 0:R.userId)===S.current.currentUserId?[]:Er(K)})),D.current=Eg(o))},[e,t,s,d,m,i,c,_]),l.useEffect(()=>{const j=(K,R)=>{const X=S.current,ne=Er(K),oe=Ea(K);if(oe!=null){if(D.current.has(oe))return;D.current.add(oe),e({event:"csatDisplayed"});return}if(Me.isStreaming(K)){ne.forEach(Y=>{L.current.add(Y)});return}const Re=ne.filter(Y=>L.current.has(Y)),Le=R==="messagesUpdated"&&Re.length>0;Le&&Re.forEach(Y=>{L.current.delete(Y)});const $=R==="messagesUpdated"&&A.current.some(({eventKeys:Y})=>rr(Y,ne)),I=ho(K,X.stringSet,X.format),w=Ie(R,ne,I);if(!Le&&R!=="messagesAdded"&&!$&&!w)return;const N=w?{dedupeKey:null}:void 0;if(Le||H()||$){me(I,[...new Set([...Re,...ne])],N);return}if(w){me(I,ne,N);return}q()&&P();const z=ne[0];e({event:"newMessage",...I},z?{dedupeKey:z}:void 0)};return g(K=>{if(!x.current||K.kind==="initialized"||!rh(K.source))return;const R=S.current.currentUserId;for(const X of K.messages)X&&th(X,R)&&j(X,K.kind)})},[e,g]),l.useEffect(()=>{x.current&&(H()||q()&&V())},[h,f]),l.useEffect(()=>()=>{F()},[]),l.useEffect(()=>{if(!x.current)return;const j=p.current,K=j.outgoingMessageStatuses;j.outgoingMessageStatuses=sr(v),v.some(({key:X,sendingStatus:ne})=>{const oe=K.get(X);return oe!==void 0&&oe!=="failed"&&ne==="failed"})&&e({event:"sendFailed"})},[e,_]),l.useEffect(()=>{if(!x.current)return;const j=p.current;i&&!j.isClosed&&e({event:"conversationClosed"}),j.isClosed=i},[e,i]),l.useEffect(()=>{if(!x.current)return;const j=p.current;c&&!j.isHandedOff&&e({event:"agentConnected",agentName:u}),j.isHandedOff=c},[u,e,c]),l.useEffect(()=>{if(!x.current)return;const j=p.current;m&&h!=="ai_responding"&&(!j.inputDisabled||j.inputDisabledBy==="ai_responding")&&e({event:"inputDisabled"}),j.inputDisabled=m,j.inputDisabledBy=h},[e,m,h])},vg=()=>{const{channelSource:e}=Ae(),t=xi(e.channel);return!(t!=null&&t.user.userId)||!t.user.nickname?null:{userId:t.user.userId,nickname:t.user.nickname}},yg=e=>{const{announceStatus:t,announcementsEnabled:n}=ot();cm(e??null,r=>{t({event:"typing",agentName:r})},1e4,n)},Sg=()=>{const e=vg();yg(e)},J=({type:e,size:t=24,className:n,color:r})=>{const{icons:s}=Yh(),o=s[e];return a.createElement(Ag,{className:n},a.createElement(o,{size:t,color:r??E.color.primary.main,flipInRtl:Bh.has(e)}))},Ag=b.default.span.attrs({"aria-hidden":"true"})`
|
|
80
|
+
`;return n.set(e,o),o},df=e=>e?G.css`display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:${e};overflow:hidden;`:"",mf=C.default.span`font-stretch:normal;letter-spacing:normal;${({$variant:e,theme:t})=>uf(e,t.typography)}color:${({$color:e})=>e};${({$maxTextLines:e})=>df(e)}`;async function Wr(e){let t=e;t&&(!t.startsWith("http://")&&!t.startsWith("https://")&&(t="https://"+t),window.open(t,"_blank","noopener,noreferrer"))}function we(e){requestAnimationFrame(()=>{requestAnimationFrame(()=>{e()})})}const pr='[role="dialog"][aria-modal="true"]',hf=(e,t)=>{const n=new Set(Array.from(e.ownerDocument.querySelectorAll(pr)).filter(s=>s!==e&&(s.contains(e)||e.contains(s)))),r=t==null?void 0:t.closest(pr);return r&&r!==e&&n.add(r),n},ff=(e,t)=>Array.from(e.ownerDocument.querySelectorAll(pr)).some(n=>n!==e&&!t.has(n)&&!n.contains(e)&&Tt(n)),gf=e=>{const t=sa(e)??e;t===e&&oa(e),t.focus()},oa=e=>{e.hasAttribute("tabindex")||e.setAttribute("tabindex","-1")},pf=(e,t)=>{const n=na(e);if(!n){oa(e),e.focus();return}n[t].focus()},to=(e,t)=>{const n=e.ownerDocument.createElement("span");return n.tabIndex=0,n.setAttribute(Gr,uh),n.style.cssText=["position: fixed","width: 1px","height: 1px","opacity: 0","overflow: hidden","pointer-events: none"].join(";"),n.addEventListener("focus",()=>pf(e,t)),n},_f=(e,t)=>{e.key==="Tab"&&(e.defaultPrevented||e.target===t&&(na(t)||(e.preventDefault(),t.focus())))},$n=(e,t,{nameReady:n=!0}={})=>{const r=l.useRef(0),s=l.useRef(!1);l.useEffect(()=>{if(!e||!t.current){s.current=!1;return}r.current+=1;const o=r.current,i=t.current,c=i.getRootNode(),u=c.activeElement instanceof HTMLElement?c.activeElement:null,d=hf(i,u);return()=>{u&&we(()=>{if(r.current!==o)return;const m=c.activeElement;i.isConnected&&m instanceof HTMLElement&&m!==i&&!i.contains(m)&&!ra(c,m)&&m.matches(ta)&&Tt(m)||ff(i,d)||!u.isConnected||!Tt(u)||u.focus()})}},[e,t]),l.useEffect(()=>{if(!e||!t.current)return;const o=t.current;let i=!1;const c=()=>{if(i||s.current||!o.isConnected)return;const m=o.getRootNode().activeElement;if(m instanceof HTMLElement&&m!==o&&o.contains(m)&&Tt(m)){s.current=!0;return}s.current=!0,gf(o)};if(n)return we(c),()=>{i=!0};const u=setTimeout(()=>we(c),Vi);return()=>{i=!0,clearTimeout(u)}},[e,t,n]),l.useEffect(()=>{if(!e||!t.current)return;const o=t.current,i=to(o,"last"),c=to(o,"first"),u=d=>_f(d,o);return o.insertBefore(i,o.firstChild),o.appendChild(c),o.addEventListener("keydown",u),()=>{o.removeEventListener("keydown",u),i.remove(),c.remove()}},[e,t])},dt=({style:e,portalContainerId:t,visible:n,onClose:r,children:s,cancelable:o=!0,"aria-label":i,"aria-labelledby":c,"aria-describedby":u})=>{const d=l.useRef(null),{resolvePortalContainer:m}=Vr();return $n(n,d),Th(n,o?r:ue),n?uc.createPortal(a.createElement(Ef,{onClick:o?r:void 0,style:e},a.createElement(Cf,{ref:d,role:"dialog","aria-modal":"true","aria-label":i,"aria-labelledby":c,"aria-describedby":u,onClick:h=>h.stopPropagation()},s)),m(t)):null},Ef=C.default.div`position:fixed;top:0;left:0;width:100%;height:100%;background:${E.color.overlay.dark};display:flex;justify-content:center;align-items:center;z-index:${gt.MODAL};`,Cf=C.default.div`border-radius:4px;overflow:hidden;box-shadow:0 16px 24px 2px rgba(13,13,13,0.12),0 6px 30px 5px rgba(13,13,13,0.08),0 6px 10px -5px rgba(13,13,13,0.04);z-index:${gt.MODAL};`,bf=({id:e,children:t})=>a.createElement(vf,{id:e},t),vf=C.default.span`position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0;`,no=(e,t)=>{const n={role:"heading","aria-level":2,"aria-label":e};return t!=null&&t.active&&t.titleId?{...n,id:t.titleId,tabIndex:-1,...t.initialFocus===!1?{}:Pi}:n},yf=()=>{const e=`${l.useId()}-`;return(t,n)=>{if(!t)return{props:{},node:null};const r=e+n,s=l.createElement(bf,{id:r,children:t});return{props:{"aria-describedby":r},node:s}}},ro=({name:e,mimeType:t,selected:n},r)=>{var o;const s=Ye(t??"")?r.A11Y_FILE_IMAGE(e):zt(t??"")?r.A11Y_FILE_VIDEO(e):Qo({name:e,mimeType:t})?r.A11Y_FILE_PDF(e):r.A11Y_FILE_DOCUMENT(e);return n?((o=r.A11Y_FILE_SELECTED)==null?void 0:o.call(r,s))??`${s}, selected`:s},Sf=e=>t=>{t.repeat||(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())},$t=({onActivate:e})=>({role:"button",tabIndex:0,onClick:e,onKeyDown:Sf(e)}),Af=({disabled:e,currentIndex:t,totalCount:n,onNavigate:r})=>s=>{var u;if(e||n<=0)return;let o=null;switch(s.key){case"ArrowRight":case"ArrowDown":o=(t+1)%n;break;case"ArrowLeft":case"ArrowUp":o=(t-1+n)%n;break;default:return}s.preventDefault(),r(o);const i=s.currentTarget.parentElement,c=i==null?void 0:i.querySelectorAll('[role="radio"]');(u=c==null?void 0:c[o])==null||u.focus()},so=(e,t,n,r,s,o)=>{let i=-1;return(e||!s&&n===0)&&(i=0),{role:"radio","aria-checked":e,"aria-disabled":t,onKeyDown:Af({disabled:t,currentIndex:n,totalCount:r,onNavigate:o}),tabIndex:i}},re=()=>{const{stringSet:e}=se(),t=yf(),n=(i,c)=>{let u=e.A11Y_HINT_OPEN_FILE,d="of";Ye(i??"")&&(u=e.A11Y_HINT_OPEN_IMAGE,d="oi"),c!==void 0&&(d+=c);const m=t(u,d);return{props:m.props,descriptionNode:m.node}},r=i=>({"aria-label":ro(i,e)});return{launcher:{button:({isOpened:i,opensConversationList:c})=>{const u=ah({intent:sh({isOpened:i,opensConversationList:c}),strings:{openConversation:e.A11Y_OPEN_CONVERSATION,openConversationList:e.A11Y_OPEN_CONVERSATIONS,closeConversation:e.A11Y_CLOSE_CONVERSATION,closeConversationList:e.A11Y_CLOSE_CONVERSATIONS,hintOpenConversation:e.A11Y_HINT_OPEN_CONVERSATION,hintOpenConversationList:e.A11Y_HINT_OPEN_CONVERSATIONS,hintCloseConversation:e.A11Y_HINT_CLOSE_CONVERSATION}});let d="lc";u.hint===e.A11Y_HINT_OPEN_CONVERSATION&&(d="lo"),u.hint===e.A11Y_HINT_OPEN_CONVERSATIONS&&(d="los");const m=t(u.hint,d);return{props:{"aria-label":u.label,...m.props},descriptionNode:m.node}}},messenger:{closeButton:()=>({props:{"aria-label":e.A11Y_CLOSE_MESSENGER},descriptionNode:null}),expandButton:i=>{let c=e.A11Y_EXPAND_MESSENGER;return i&&(c=e.A11Y_COLLAPSE_MESSENGER),{props:{"aria-label":c},descriptionNode:null}},connectionDelayDialog:()=>({props:{"aria-label":e.CONNECTION_DELAY__TITLE},descriptionNode:null})},conversation:{header:{menuButton:()=>{const i=e.A11Y_HINT_OPEN_MENU,c=t(i,"mb");return{props:{"aria-label":e.A11Y_MENU,...c.props},descriptionNode:c.node}},closeConversationButton:()=>{const i=e.A11Y_HINT_CLOSE_CONVERSATION,c=t(i,"cc");return{props:{"aria-label":e.A11Y_CLOSE_CONVERSATION,...c.props},descriptionNode:c.node}},handoffButton:()=>{const i=e.A11Y_HINT_CONNECT_TO_AGENT,c=t(i,"h");return{props:{"aria-label":e.A11Y_CONNECT_AGENT,...c.props},descriptionNode:c.node}},title:(i,c)=>({props:no(i,c),descriptionNode:null}),memoryIndicator:i=>{let c=e.A11Y_MEMORY_INDICATOR_OFF,u="mof";i&&(c=e.A11Y_MEMORY_INDICATOR_ON,u="mon");const d=t(c,u);return{props:{"aria-label":e.A11Y_MEMORY_INDICATOR_MANAGE,...d.props},descriptionNode:d.node}}},messageInput:{attachFileButton:()=>{const i=e.A11Y_HINT_ATTACH_FILE,c=t(i,"af");return{props:{"aria-label":e.A11Y_ATTACH_FILE,...c.props},descriptionNode:c.node}},sendButton:()=>{const i=e.A11Y_HINT_SEND_MESSAGE,c=t(i,"sm");return{props:{"aria-label":e.A11Y_SEND_MESSAGE,...c.props},descriptionNode:c.node}},textInput:i=>({props:{role:"textbox","aria-label":i,...hh},descriptionNode:null})},suggestedReplies:{item:(i,c)=>{const u=e.A11Y_HINT_SEND_REPLY,d=t(u,`sr${c}`);return{props:{"aria-label":`${e.A11Y_SUGGESTED_REPLY}, ${i}`,...d.props},descriptionNode:d.node}}},feedback:{container:()=>{const i=e.A11Y_HINT_SELECT_RATING,c=t(i,"fb");return{props:c.props,descriptionNode:c.node}},button:(i,c)=>{const u=e.A11Y_HINT_SELECT_RATING,d=t(u,`f${i}`);let m=e.FEEDBACK_BAD;return i==="good"&&(m=e.FEEDBACK_GOOD),{props:{"aria-label":m,...d.props,"aria-pressed":c},descriptionNode:d.node}},optionsBottomSheet:()=>({props:{"aria-label":e.A11Y_FEEDBACK_OPTIONS},descriptionNode:null})},newMessagesButton:()=>{const i=e.A11Y_HINT_VIEW_NEW_MESSAGES,c=t(i,"nm");return{props:{"aria-label":e.A11Y_SCROLL_TO_NEW_MESSAGES,...c.props},descriptionNode:c.node}},scrollToBottomButton:()=>{const i=e.A11Y_HINT_VIEW_NEW_MESSAGES,c=t(i,"sb");return{props:{"aria-label":e.A11Y_SCROLL_TO_BOTTOM,...c.props},descriptionNode:c.node}},startNewConversationButton:({onActivate:i})=>({props:{...$t({onActivate:i}),"aria-label":e.TALK_TO_AGENT},descriptionNode:null}),poweredByLink:()=>({props:{"aria-label":`${e.POWERED_BY} Sendbird`},descriptionNode:null}),retryButton:(i=e.RETRY)=>({props:{"aria-label":i},descriptionNode:null}),file:{label:(i,c,u)=>i?ro({name:i,mimeType:c,selected:u},e):"",preview:i=>({props:r(i),descriptionNode:null}),buttonLikePreview:({onActivate:i,...c},u)=>{const d=n(c.mimeType,u);return{props:{...$t({onActivate:i}),...r(c),...d.props},descriptionNode:d.descriptionNode}},removeButton:i=>({props:{"aria-label":e.A11Y_FILE_REMOVE_BUTTON(i)},descriptionNode:null})},csat:{scoresContainer:i=>{const c=e.A11Y_HINT_SELECT_RATING,u=t(c,"cs");return{props:{role:"radiogroup","aria-label":i,...u.props},descriptionNode:u.node}},scoreItem:({score:i,label:c,selected:u,disabled:d,currentIndex:m,totalCount:h,hasSelection:f,onChange:g})=>{var p;const _=c.trim()||c,y=e.A11Y_HINT_SELECT_RATING,b=t(y,`cs${i}`);return{props:{disabled:d,onClick:()=>g(i),...so(u,d,m,h,f,S=>g(S+1)),...b.props,"aria-label":((p=e.A11Y_CSAT_RATING_LABEL)==null?void 0:p.call(e,i,_))??`${i} / ${h} — ${_}`},descriptionNode:b.node}},submitButton:i=>({props:{"aria-label":i},descriptionNode:null})},form:{button:i=>({props:{"aria-label":i},descriptionNode:null}),textInput:(i,c,u,d)=>({props:{...d!=null&&d.labelId?{"aria-labelledby":d.labelId}:{"aria-label":i},"aria-required":c,"aria-disabled":u},descriptionNode:null}),numberInput:(i,c,u)=>({props:{"aria-label":i,"aria-required":c,"aria-disabled":u},descriptionNode:null}),singleSelectGroup:i=>{const c={role:"radiogroup"};return i&&(c["aria-label"]=i),{props:c,descriptionNode:null}},singleSelectOption:(i,c,u,d,m,h,f)=>({props:{...so(c,u,d,m,h,f),"aria-label":i},descriptionNode:null}),multiSelectOption:(i,c,u)=>({props:{"aria-label":i,"aria-pressed":c,"aria-disabled":u},descriptionNode:null})}},conversationList:{headerTitle:(i,c)=>({props:no(i,c),descriptionNode:null}),footer:{button:({onActivate:i})=>({props:{...$t({onActivate:i}),"aria-label":e.TALK_TO_AGENT},descriptionNode:null})},item:({agent:i,status:c,time:u,unreadCount:d,onActivate:m})=>{if(!m)return{props:{"aria-label":e.A11Y_CONVERSATION_ITEM(i,c,u,d)},descriptionNode:null};const h=e.A11Y_HINT_OPEN_CONVERSATION,f=t(h,"cli");return{props:{...$t({onActivate:m}),...f.props,"aria-label":e.A11Y_CONVERSATION_ITEM(i,c,u,d)},descriptionNode:f.node}}}}},Tf=({title:e,description:t,highlightedText:n})=>{const r=vm(t,n);return a.createElement(xf,null,a.createElement(Rf,null,a.createElement(H,{as:"div",variant:"h1",color:E.themedColor.textHighEmphasis},e),t&&a.createElement(Mf,null,a.createElement(H,{as:"div",variant:"body3",color:E.themedColor.textMidEmphasis},r.beforeText,r.highlightedText?a.createElement(wf,null,r.highlightedText):null,r.afterText))))},If=()=>{const{components:e}=Fn.useContext(),{stringSet:t}=se(),{messenger:n}=re(),r=Cm(),s=r.showDescription?bm(r.remainingTime):"",o=r.showDescription?t.CONNECTION_DELAY__DESCRIPTION(s):"";return a.createElement(dt,{portalContainerId:ye.WINDOW,visible:r.visible,onClose:ue,...n.connectionDelayDialog().props},a.createElement(e.Dialog,{title:t.CONNECTION_DELAY__TITLE,description:o,highlightedText:s||void 0}))},Fn=je({template:If,components:{Dialog:Tf}}),xf=C.default.div`width:280px;padding:24px;margin:0 auto;border-radius:4px;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,Rf=C.default.div`display:flex;flex-direction:column;`,Mf=C.default.div`margin-top:16px;`,wf=C.default.strong`font-weight:700;`,kf=({url:e})=>Wr(e),{Provider:Lf,Consumer:ia,useContext:le}=be("Messenger");function Of({children:e,state:t,enableCloseConversationButton:n=!1,enableExpandButton:r=!0,enableAutoDisconnectInLauncher:s=!0,...o}){const[i,c]=l.useState(!1),[u,d]=l.useState(!1),m={opened:(t==null?void 0:t.opened)??i,setOpened:(t==null?void 0:t.setOpened)??c,expanded:(t==null?void 0:t.expanded)??u,setExpanded:(t==null?void 0:t.setExpanded)??d},{resolveElement:h}=Vr(),f=l.useCallback(()=>{m.setOpened(!1)},[m.setOpened]);Ih(m.opened,f);const g=l.useRef(m.opened);l.useLayoutEffect(()=>{const b=g.current&&!m.opened;if(g.current=m.opened,!b)return;const p=ut(o.rootElement),S=h(ye.WINDOW);let A=!1;return we(()=>{var T;A||cf(p,p.activeElement,S)&&((T=h(ye.LAUNCHER))==null||T.focus())}),()=>{A=!0}},[m.opened,o.rootElement,h]);const{Template:_}=Fn.useContext(),y=l.useMemo(()=>{var b;return{...o.handlers,onClickLink:((b=o.handlers)==null?void 0:b.onClickLink)??kf}},[o.handlers]);return a.createElement(Ru,{...o},b=>a.createElement(Lf,{value:{...o,...b,state:m,enableCloseConversationButton:n,enableExpandButton:r,enableAutoDisconnectInLauncher:s,handlers:y}},a.createElement(_,null),e))}const aa=/iPad|iPhone|iPod/.test(navigator.userAgent),Nf=/Android/.test(navigator.userAgent),Jt=e=>aa||Nf;let Lt=null,er=null;const Df=(e,t=5e3)=>{Lt&&(clearInterval(Lt),clearTimeout(er));const n=document.title;Lt=setInterval(()=>{document.title=document.title===e?n:e},750),er=setTimeout(()=>{clearInterval(Lt),Lt=null,er=null,document.title=n},t)},ca=()=>{Promise.resolve().then(()=>require("./cjs/B93o4u0P.cjs")).then(e=>{new Audio(e.default).play().catch(()=>{})})},xe=G.css`&:focus-visible{outline:2px solid ${E.themedColor.primary};outline-offset:2px;}`,oo=e=>{if(typeof e=="string"||typeof e=="number")return String(e)},Pn=({visible:e,title:t,description:n,confirmText:r="OK",cancelText:s,onConfirm:o,onCancel:i,onClose:c,"aria-label":u})=>{const d=l.useId(),m=l.useId(),h=u??oo(t)??oo(n),f=u?void 0:t?d:n?m:void 0,g=t&&n?m:void 0,_=()=>{c(),we(()=>o==null?void 0:o())},y=()=>{c(),we(()=>i==null?void 0:i())};return a.createElement(dt,{portalContainerId:ye.WINDOW,visible:e,onClose:c,"aria-label":h,"aria-labelledby":f,"aria-describedby":g},a.createElement($f,null,a.createElement(Ff,null,t&&a.createElement("div",{id:d},a.createElement(H,{variant:"h1",color:E.themedColor.textHighEmphasis},t)),n&&a.createElement(Pf,{id:m},a.createElement(H,{variant:"body3",color:E.themedColor.textMidEmphasis},n))),a.createElement(Uf,null,s&&a.createElement(io,{onClick:y},a.createElement(H,{variant:"button",color:E.themedColor.textHighEmphasis},s)),a.createElement(io,{onClick:_},a.createElement(H,{variant:"button",color:E.themedColor.primary},r)))))},$f=C.default.div`width:360px;height:auto;padding-block:24px 12px;padding-inline:24px;margin:0 auto;border-radius:4px;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,Ff=C.default.div`margin-bottom:16px;`,Pf=C.default.div`margin-top:16px;`,Uf=C.default.div`display:flex;flex-direction:row;justify-content:flex-end;`,io=C.default.button`all:unset;display:flex;justify-content:center;align-items:center;border-radius:4px;cursor:pointer;background-color:transparent;padding:10px 16px;${xe}`,{Provider:Bf,useContext:Ne}=be("MessengerSession"),Hf=l.forwardRef(function({children:e,...t},n){return a.createElement(md,{ref:n,...t},r=>a.createElement(Gf,{...r},e))}),Gf=({children:e,...t})=>{const{chatSDK:n,logger:r,appId:s,aiAgentId:o,agentPreviewConfigs:i,state:c,handlers:u,dispatcher:d,_aiAgentSDK:m}=le(),{userSessionInfo:h,authenticate:f,userSession:g,aiAgentInfo:_,launcherInfo:y}=t,[b,p]=l.useState(!1),S=l.useRef(null);ht(n,{async onUserJoined(T,R){var D,k,M,P;T.conversation&&T.conversation.type===me.ConversationType.PROACTIVE&&R.userId===((D=n.currentUser)==null?void 0:D.userId)&&(r.info("messengerSession.onUserJoined: proactive channel joined",T.url),(M=m.session)==null||M._updateActiveChannel({url:T.url,status:"open",conversationStatus:(k=T.conversation)==null?void 0:k.status}),c.setOpened(!0),zf({sound:document.hidden||!c.opened}),(P=S.current)==null||P.call(S,{channel:T}))}}),l.useEffect(()=>{f().then(({launcher:T})=>{T.auto_open&&!Jt()&&setTimeout(()=>c.setOpened(!0),500)}).catch(T=>{var R;r.error("messengerSession: failed to initialize",T),(R=u==null?void 0:u.onInitializeFailed)==null||R.call(u,T)})},[n,s,o,h==null?void 0:h.userId]),l.useEffect(()=>{const T=()=>p(!0);return d.subscribe(Ke.AnonymousSessionTokenExpired,T),()=>d.unsubscribe(Ke.AnonymousSessionTokenExpired,T)},[d]);const A=l.useCallback(()=>{t.deauthenticate().finally(()=>window.location.reload())},[t.deauthenticate]);return!g||!_||!y?null:a.createElement(Bf,{value:{...t,userSession:g,aiAgentInfo:{..._,...i==null?void 0:i.bot},launcherInfo:{...y,...i==null?void 0:i.launcher},registerOnJoinedProactiveConversation:T=>S.current=T}},e,a.createElement(Pn,{visible:b,title:"Session timed out",description:"Start a new conversation.",onConfirm:A,onClose:ue}))};function zf({sound:e}){Df("🔔You have received a new message"),e&&ca()}const Mn=`@${Ge}-focused-channel`,la=`${Date.now()}-${Math.random().toString(36).slice(2)}`,Vf=()=>{try{const e=localStorage.getItem(Mn);return e?JSON.parse(e).channelUrl??null:null}catch{return null}},ao=e=>{try{localStorage.setItem(Mn,JSON.stringify({channelUrl:e,tabId:la}))}catch{}},co=()=>{try{const e=localStorage.getItem(Mn);if(!e)return;JSON.parse(e).tabId===la&&localStorage.removeItem(Mn)}catch{}},qf=(e,t)=>(l.useEffect(()=>{if(!t||!e)return;const n=()=>ao(e),r=()=>co();return document.hasFocus()&&ao(e),window.addEventListener("focus",n),window.addEventListener("blur",r),()=>{window.removeEventListener("focus",n),window.removeEventListener("blur",r),co()}},[t,e]),{isChannelViewedInAnyTab:()=>document.hasFocus()||Vf()===e}),Kf=e=>{const{config:t,chatSDK:n}=le(),{sdkUser:r}=Ne(),s=t.conversation.messageAlertSoundEnabled,{isChannelViewedInAnyTab:o}=qf(e,s);ht(n,{onMessageReceived(i,c){if(!s||i.url!==e||o())return;(Qe(c)&&c.sender.userId!==(r==null?void 0:r.userId)||c.isAdminMessage()&&!c.silent)&&ca()}})};function Yf(e){return new Promise(t=>{const n=new Image;n.onload=function(){const r=String(n.width),s=String(n.height);URL.revokeObjectURL(n.src),t({width:r,height:s})},n.src=URL.createObjectURL(e)})}async function Wf(e){if("file"in e&&e.file instanceof File&&e.file.type.startsWith("image/")){const{width:t,height:n}=await Yf(e.file);return new Fe.MessageMetaArray({key:Xo,value:[t,n]})}}const jf=({onScrollAfterSendMessage:e})=>{const{agentPreviewConfigs:t,handlers:n}=le(),r=l.useRef(t==null?void 0:t.agentAttributes);return r.current=t==null?void 0:t.agentAttributes,{onBeforeSendMessage:async s=>{const o=await Wf(s),i={...s,metaArrays:o?[o]:void 0},c=Xf(r.current);return c?{...i,data:JSON.stringify(c)}:i},onAfterSendMessage:s=>{var o,i,c;e(),(o=n==null?void 0:n.onMessageSend)==null||o.call(n,s.message),s.sendingStatus===Fe.SendingStatus.SUCCEEDED?(i=n==null?void 0:n.onCustomEvent)==null||i.call(n,{type:"message-sent-succeeded",data:{message:s}}):s.sendingStatus===Fe.SendingStatus.PENDING&&((c=n==null?void 0:n.onCustomEvent)==null||c.call(n,{type:"message-sent-pending",data:{message:s}}))}}},Xf=e=>{if(!e)return null;const t={};return e.ai&&Object.keys(e.ai).length>0&&(t.ai_attrs=e.ai),e.safeguard&&Object.keys(e.safeguard).length>0&&(t.safeguard_attrs=e.safeguard),typeof e.use_prompt_cache=="boolean"&&(t.use_prompt_cache=e.use_prompt_cache),Object.keys(t).length>0?t:null},St=50,tr=St-40,{Provider:Zf,useContext:ua}=be("ConversationScroll"),lo={viewport:0,contentHeight:0,contentSnapshotHeight:0,shouldRecalc:!1,shouldUpdate:!1},nr=e=>Math.max(0,e.scrollHeight-e.scrollTop-e.clientHeight),uo=e=>Array.from(e.querySelectorAll(`#${Ge}-message-item`));function Jf({scrollMode:e,messageStackDirection:t,children:n}){const r=l.useRef(null),s=l.useRef({mutation:null,resize:null,resizeTargets:new Set}),o=l.useRef({distanceFromBottom:0,prevScrollTop:0}),i=l.useRef({awayByUser:!1,programmatic:!1,streaming:!1,reconcileTimer:null,userMessageTimer:null}),c=l.useRef(lo),[u,d]=l.useState(0),[m,h]=l.useState(0),[f,g]=l.useState(!1),[_,y]=l.useState(!1),[b,p]=l.useState(!0),S=$=>{const x=nr($);return o.current.distanceFromBottom=x,h(x),x},A=()=>{const $=i.current;$.reconcileTimer&&(clearTimeout($.reconcileTimer),$.reconcileTimer=null)},T=l.useCallback(()=>{const $=s.current;$.mutation&&($.mutation.disconnect(),$.mutation=null),$.resize&&($.resize.disconnect(),$.resize=null),$.resizeTargets.clear()},[]),R=l.useMemo(()=>f||t==="bottom"?"auto":e,[f,t,e]),L=()=>{c.current.contentSnapshotHeight=c.current.contentHeight,c.current.shouldUpdate=!0,c.current.shouldRecalc=!0},D=()=>{const $=r.current;!$||!c.current.shouldUpdate||d(x=>{c.current.shouldUpdate=!1;const{contentHeight:w,contentSnapshotHeight:O,shouldRecalc:z}=c.current,q=$.clientHeight;if(O>w)return x;const ee=k($,{messageType:"outgoing"});let W=0;if(ee){const pe=ee.message.offsetTop-tr+q;W=Math.max(0,pe-w)}else{const pe=w-O,Xe=q-tr;W=Math.max(0,pe-Xe)}return x===0||W!==x||z?(c.current.shouldRecalc=!1,W):x})},k=l.useCallback(($,x)=>{const{messageType:w="all"}=x??{},O=uo($);let z=O;w==="outgoing"&&(z=O.filter(ae=>ae.getAttribute("data-layout-id")==="outgoingmessage"));const q=z[z.length-1];if(!q)return null;const ee=$.getBoundingClientRect(),W=q.getBoundingClientRect(),pe=$.scrollTop+(W.top-ee.top),Xe=pe+q.offsetHeight;return{message:q,scrollTop:pe,lastMessageBottom:Xe}},[]),M=l.useCallback(()=>{const $=r.current;if(!$||R!=="fixed")return;const x=k($);c.current.contentHeight=(x==null?void 0:x.lastMessageBottom)??$.scrollHeight,!i.current.streaming&&c.current.contentSnapshotHeight>0&&L(),i.current.programmatic?o.current.distanceFromBottom=nr($):S($),D()},[R,k]),P=l.useCallback(()=>{T(),A(),c.current=lo,d(0),h(0),p(!0),o.current.distanceFromBottom=0,o.current.prevScrollTop=0,i.current.awayByUser=!1,i.current.programmatic=!1},[T]),F=l.useCallback(($=!0)=>{const x=o.current.distanceFromBottom>St;if(i.current.awayByUser=!1,h(0),!x){we(()=>{const w=r.current;w&&!i.current.awayByUser&&w.scrollTo({top:w.scrollHeight,behavior:"auto"})});return}i.current.programmatic||(i.current.programmatic=!0,p(!1),A()),we(()=>{const w=r.current;if(!w){i.current.programmatic=!1,p(!0);return}if(i.current.awayByUser){i.current.programmatic=!1,S(w),p(!0);return}const O=()=>{if(r.current!==w){i.current.programmatic=!1,r.current&&S(r.current),p(!0);return}i.current.programmatic=!1,S(w),p(!0)};if($&&!i.current.reconcileTimer){const z=setTimeout(O,500);i.current.reconcileTimer=z,w.addEventListener("scrollend",()=>{clearTimeout(z),i.current.reconcileTimer=null,O()},{once:!0})}w.scrollTo({top:w.scrollHeight,behavior:$?"smooth":"auto"}),$||O()})},[]),Y=l.useCallback(()=>{const $=r.current;if($){if(i.current.awayByUser){S($);return}F(!1)}},[F]),j=l.useCallback(()=>{const $=r.current,x=s.current;if(!$||!x.resize)return;const w=new Set(uo($));for(const O of x.resizeTargets)w.has(O)||(x.resize.unobserve(O),x.resizeTargets.delete(O));for(const O of w)x.resizeTargets.has(O)||(x.resize.observe(O),x.resizeTargets.add(O))},[]),N=l.useCallback($=>{T();const x=s.current;typeof ResizeObserver<"u"&&(x.resize=new ResizeObserver(Y),j());const w=new MutationObserver(()=>{j(),Y()});x.mutation=w,w.observe($,{childList:!0})},[T,Y,j]),B=l.useCallback($=>{if(!$){r.current=null,T();return}if(r.current=$,R!=="fixed"){N($);return}P(),c.current.viewport=$.clientHeight;const x=new MutationObserver(()=>{M()});s.current.mutation=x,x.observe($,{childList:!0,subtree:!0})},[T,R,M,P,N]),U=l.useCallback(()=>{const $=r.current;if(!$)return;const x=k($,{messageType:"outgoing"});x&&($.scrollTo({top:x.message.offsetTop-tr,behavior:"smooth"}),i.current.userMessageTimer&&clearTimeout(i.current.userMessageTimer),i.current.userMessageTimer=setTimeout(()=>{y(!1)},500))},[k]),V=($,x,w)=>{const O=nr($);if(w&&O>St){i.current.programmatic=!1,i.current.awayByUser=!0,A(),S($),p(!0),o.current.prevScrollTop=x;return}o.current.distanceFromBottom=O},ce=($,x,w)=>{const z=S($)<=St;x&&!z&&(i.current.awayByUser=!0,A()),w&&z&&(i.current.awayByUser=!1)},Ie=$=>{const{scrollTop:x}=$.currentTarget,w=o.current.prevScrollTop;i.current.programmatic?V($.currentTarget,x,x<w):ce($.currentTarget,x<w,x>w),o.current.prevScrollTop=x},X=l.useCallback(()=>{R==="fixed"&&(y(!0),L())},[R]),K=l.useCallback(()=>{R==="fixed"?setTimeout(()=>U(),300):F()},[R,U]),I=l.useCallback($=>{i.current.streaming=$,R==="fixed"?L():i.current.awayByUser||F()},[R,F]),Z=l.useCallback($=>{g($),$&&(d(0),R==="fixed"&&T())},[T,R]),ne=l.useCallback($=>{R==="auto"&&$&&!i.current.awayByUser&&F()},[R,F]),Re=!(m<=St)&&!_,De=l.useCallback(()=>o.current.distanceFromBottom>St,[]);return a.createElement(Zf,{value:{ref:B,state:{bottomSpace:u,isAwayFromBottom:Re,isScrollPositionReconciled:b,shouldCountNewMessages:De},props:{onScroll:Ie},actions:{scrollToBottom:F,onBeforeMessageSend:X,onAfterMessageSend:K,onStreamingUpdate:I,onConversationClosed:Z,onTypingIndicatorUpdate:ne}}},n)}const{Provider:Qf,Context:eg,useContext:Ae}=be("Conversation"),tg=({children:e})=>{var s;const{channelSource:t}=Ae(),n=(s=t.channel)==null?void 0:s.url,{checkForUserActionRequired:r}=sm(n);return l.useEffect(()=>{var i;const o=(i=t.channel)==null?void 0:i.lastMessage;o&&r(o)},[t.channel,r]),a.createElement(a.Fragment,null,e)},ng=({channelUrl:e,onClearChannelUrl:t,onNavigateToConversationList:n,conversationStatsEnabled:r,shouldMarkAsRead:s,shouldInitializeConversation:o,children:i})=>{const{activeChannel:c,refreshActiveChannel:u}=Ne(),d=ua(),m=e||(c==null?void 0:c.url);Kf(m);const{onBeforeSendMessage:h,onAfterSendMessage:f}=jf({onScrollAfterSendMessage:()=>{d.actions.onAfterMessageSend()}}),g=l.useCallback(p=>(d.actions.onBeforeMessageSend(),h(p)),[d.actions,h]),_=l.useCallback(p=>{const S=p.some(A=>Me.isStreaming(A));d.actions.onStreamingUpdate(S)},[d.actions.onStreamingUpdate]),y=l.useCallback(p=>{d.actions.onConversationClosed(p===me.ConversationStatus.CLOSED)},[d.actions.onConversationClosed]),b=l.useCallback(async()=>{await u(),e&&(t==null||t())},[u,e,t]);return a.createElement(Ud,{key:m,channelUrl:m,onBeforeSendMessage:g,onAfterSendMessage:f,onMessagesUpdated:_,onMessagesReceived:_,onChannelDeleted:b,onConversationStatusChanged:y,conversationStatsEnabled:r,shouldMarkAsRead:s,shouldInitializeConversation:o,shouldCountNewMessages:d.state.shouldCountNewMessages},p=>a.createElement(Qf,{value:{...p,conversationStatsEnabled:r??!0,scrollSource:d,goToActiveConversation:b,onNavigateToConversationList:n}},a.createElement(tg,null,i)))},da=({children:e,...t})=>{const{config:n}=ke(),{agentPreviewConfigs:r}=le(),s=n.conversation.list.scrollMode,o=r==null?void 0:r.messageStackDirection;return a.createElement(Jf,{scrollMode:s,messageStackDirection:o},a.createElement(ng,{...t},e))},jr=l.createContext({onDrop:ue,subscribe:()=>ue}),_r=({children:e})=>{const t=l.useRef(new Set);return a.createElement(jr.Provider,{value:{onDrop:n=>{var r;if(n.preventDefault(),(r=n.dataTransfer)!=null&&r.files){const s=Array.from(n.dataTransfer.files);s.length>0&&t.current.forEach(o=>o(s))}},subscribe:n=>(t.current.add(n),()=>t.current.delete(n))}},e)},rg=({onDropFiles:e})=>{const{subscribe:t}=l.useContext(jr);l.useEffect(()=>t(e),[e])};_r.Consumer=({children:e})=>{const{onDrop:t}=l.useContext(jr);return e({onDrop:t,onDragOver:s=>s.preventDefault()})};const ma=be("WindowTitle",{hasWindowTitleReference:!1,isTitlePending:!1,isWindowNameReady:!0,registerWindowTitleReference:()=>ue,registerWindowTitlePending:()=>ue}),sg=ma.Provider,ha=ma.useContext,mo=()=>{const e=l.useRef(0),[t,n]=l.useState(!1),r=l.useCallback(()=>{let s=!0;return e.current+=1,e.current===1&&n(!0),()=>{s&&(s=!1,e.current=Math.max(0,e.current-1),e.current===0&&n(!1))}},[]);return[t,r]},Xr=({children:e})=>{const[t,n]=mo(),[r,s]=mo(),o=!r||t,i=l.useMemo(()=>({hasWindowTitleReference:t,isTitlePending:r,isWindowNameReady:o,registerWindowTitleReference:n,registerWindowTitlePending:s}),[t,r,n,s]);return a.createElement(sg,{value:i},e)},Un=ha,fa=({enabled:e,label:t})=>{const{registerWindowTitleReference:n,registerWindowTitlePending:r}=ha(),s=e&&t.trim().length>0;return l.useLayoutEffect(()=>{if(e)return r()},[r,e]),l.useLayoutEffect(()=>{if(s)return n()},[n,s]),{enabled:s,id:s?ye.WINDOW_TITLE:void 0}},og=(e,t)=>{const r=(t?Gt(e,t):null)??lf(e)??e;r===e&&!e.hasAttribute("tabindex")&&e.setAttribute("tabindex","-1"),r.focus({focusVisible:!1})},ga=(e,{enabled:t,ready:n,nameReady:r=!0,targetSelector:s,suppressed:o=!1})=>{const i=l.useRef(!1);l.useEffect(()=>{if(!t){i.current=!1;return}if(i.current||!e.current||o||s&&!n)return;const c=Yr(e.current)!=null;if(!s&&!c&&!n)return;let u=!1;const d=()=>{u||i.current||!e.current||(i.current=!0,og(e.current,s))};if(r)return we(d),()=>{u=!0};const m=setTimeout(()=>we(d),Vi);return()=>{u=!0,clearTimeout(m)}},[t,n,r,s,e,o])},ig=(e,t)=>{const{announcementsEnabled:n}=ot(),{channelSource:r}=Ae(),{isWindowNameReady:s}=Un(),o=Xi(),i=r.channel!=null||r.error!=null;ga(e,{enabled:n,ready:i,nameReady:s,targetSelector:t==="messageInput"?mh:void 0,suppressed:o})},ag=({enabled:e=!0}={})=>{var s;const{channelSource:t}=Ae(),n=(s=t.channel)==null?void 0:s.url,r=l.useCallback(o=>{const i=()=>{o(js()?"backgrounded":"foregrounded")};return document.addEventListener("visibilitychange",i),()=>document.removeEventListener("visibilitychange",i)},[]);Am({channelUrl:n,enabled:e,isInitiallyBackgrounded:js,isForegrounded:hr,subscribeToForegroundState:r})},cg=e=>Ye(e)||zt(e);function lg(e){return e.isAdminMessage()?e.message==="The channel's custom_type was updated.":!1}function ug(e,t){return e.filter(n=>Me.isWelcomeMessage(n,t))}const pa=(e,{previewWelcomeMessages:t,aiAgentUserId:n})=>e.filter(r=>lg(r)?!1:t.length>0?!Me.isWelcomeMessage(r,n):!0),dg=[],_a=()=>{var _,y,b,p,S,A;const{agentPreviewConfigs:e={},aiAgentId:t}=le(),{aiAgentInfo:n,userSession:r}=Ne(),{channelSource:s,messageSource:o,state:{input:i,streamAnimation:c}}=Ae(),u=e.welcomeMessages??dg,d=l.useMemo(()=>pa(o.messages,{previewWelcomeMessages:u,aiAgentUserId:t}),[t,o.messages,u]),m=rt(s.channel),h=(y=(_=si(s.channel,r.userId))==null?void 0:_.nickname)==null?void 0:y.trim(),f=m?(p=(b=s.channel)==null?void 0:b.name)==null?void 0:p.trim():(S=n==null?void 0:n.nickname)==null?void 0:S.trim(),g=h||f||void 0;return{initialized:o.initialized,channelUrl:(A=s.channel)==null?void 0:A.url,agentName:g,isClosed:He(s.channel),isHandedOff:m,messages:d,filteredMessagesCount:d.length,hasWelcomeMessages:u.length>0,inputDisabled:i.disabled,inputDisabledBy:i.disabledBy,isStreamAnimating:c.isAnimating,subscribeMessageEvents:o.subscribeMessageEvents,currentUserId:r.userId}},mg=(e={})=>{const{announceScreenEntry:t,announcementsEnabled:n}=ot(),{initialized:r=!1,channelUrl:s,agentName:o,isClosed:i=!1,messages:c=[],hasWelcomeMessages:u=!1}=e,d=l.useRef(null),m=l.useMemo(()=>c.some(f=>Oe.isAdmin(f)&&Oe.isCSAT(f)),[c]),h=c.length===0&&!u;l.useEffect(()=>{if(!n){d.current=null;return}!r||!s||d.current!==s&&(t({screen:"conversation",agentName:o,isClosed:i,hasCSAT:m,...h?{isEmpty:!0}:{}}),d.current=s)},[o,t,n,s,m,r,i,h])},hg=()=>{const e=_a();mg(e)},fg=e=>({image:e.A11Y_RECEIVED_FILE_IMAGE,video:e.A11Y_RECEIVED_FILE_VIDEO,pdf:e.A11Y_RECEIVED_FILE_PDF,document:e.A11Y_FILE_DOCUMENT,receivedFilesImageCount:e.A11Y_RECEIVED_FILES_IMAGE_COUNT,multipleFilesCount:e.CONVERSATION_LIST__MULTIPLE_FILES_COUNT,codeBlockPlaceholder:e.A11Y_CODE_BLOCK_PLACEHOLDER}),ho=(e,t,n=at.format)=>{const r=Wm(e,fg(t)),s="sender"in e?e.sender:void 0,o=e.createdAt!=null&&e.createdAt!==0?n(e.createdAt,t.DATE_FORMAT__MESSAGE_TIMESTAMP):void 0;return{senderName:typeof(s==null?void 0:s.nickname)=="string"&&s.nickname.trim()||void 0,body:r||void 0,time:o}},gg={senderName:!0,body:!0,time:!0},pg=Object.keys(gg),_g=(e,t)=>pg.every(n=>e[n]===t[n]),fo=2e3,go=400,Er=e=>{const t=new Set;return"reqId"in e&&typeof e.reqId=="string"&&e.reqId.length>0&&t.add(`req:${e.reqId}`),"messageId"in e&&e.messageId>0&&t.add(`message:${String(e.messageId)}`),[...t]},Ea=e=>{if(!Oe.isAdmin(e)||!Oe.isCSAT(e))return null;const t=nh(e);return t?`csat:${t}`:null},Eg=e=>{const t=new Set;for(const n of e){const r=Ea(n);r&&t.add(r)}return t},Cg=(e,t)=>{for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r&&Er(r).some(s=>t.includes(s)))return r}},rr=(e,t)=>e.some(n=>t.includes(n)),po=()=>typeof document>"u"?null:document.activeElement instanceof HTMLElement?document.activeElement:null,sr=e=>new Map(e.map(({key:t,sendingStatus:n})=>[t,n])),bg=()=>{const{announceStatus:e,announcementsEnabled:t}=ot(),{stringSet:n,format:r}=se(),{channelUrl:s,messages:o,isClosed:i,isHandedOff:c,agentName:u,initialized:d,inputDisabled:m,inputDisabledBy:h,isStreamAnimating:f,subscribeMessageEvents:g,currentUserId:_}=_a(),{outgoingMessageStates:y,outgoingMessageStatusSignature:b}=l.useMemo(()=>{if(!_)return{outgoingMessageStates:[],outgoingMessageStatusSignature:""};const X=o.flatMap(K=>{const I=eh(K,_);return!I||!("sendingStatus"in K)?[]:[{key:I,sendingStatus:K.sendingStatus}]});return{outgoingMessageStates:X,outgoingMessageStatusSignature:X.map(({key:K,sendingStatus:I})=>`${K}:${I}`).join(",")}},[_,o]),p=l.useRef({isClosed:!1,isHandedOff:!1,inputDisabled:m,inputDisabledBy:h,outgoingMessageStatuses:sr(y)}),S=l.useRef({messages:o,currentUserId:_,inputDisabledBy:h,isStreamAnimating:f,stringSet:n,format:r}),A=l.useRef([]),T=l.useRef(null),R=l.useRef([]),L=l.useRef(new Set),D=l.useRef(new Set),k=l.useRef(!1),M=l.useRef(s);S.current={messages:o,currentUserId:_,inputDisabledBy:h,isStreamAnimating:f,stringSet:n,format:r};const P=()=>S.current.isStreamAnimating||S.current.inputDisabledBy==="ai_responding",F=()=>{T.current!=null&&(clearTimeout(T.current),T.current=null)},Y=(X,K,I)=>{const Z=I==null?void 0:I.replaceableForMs;if(X.length===0||!Z)return;const ne=Date.now();R.current=[...R.current.filter(({replaceableUntil:oe})=>oe>ne),{eventKeys:X,parts:K,replaceableUntil:ne+Z}]},j=()=>A.current.length>0,N=()=>{A.current=[]},B=()=>{const[X,...K]=A.current;if(!X)return!1;A.current=K;const{eventKeys:I,parts:Z,dedupeKey:ne}=X,oe=$=>{Y(I,$,{replaceableForMs:I.length>0?fo:void 0}),e({event:"newMessage",...$},ne?{dedupeKey:ne}:void 0)};if(I.length===0)return oe(Z),!0;const Re=S.current,De=Cg(Re.messages,I);if(De){const $=ho(De,Re.stringSet,Re.format);return oe($),!0}return oe(Z),!0},U=()=>{for(F();B(););},V=(X=fo)=>{F(),T.current=setTimeout(()=>{if(T.current=null,P())return;const K=po(),[I]=A.current;if(!I)return;if(I.focusTarget!==K){A.current=[{...I,focusTarget:K},...A.current.slice(1)],V(go);return}B()&&j()&&V(go)},X)},ce=(X,K,I)=>{const Z={eventKeys:K,parts:X,focusTarget:po(),dedupeKey:I?I.dedupeKey??void 0:K[0]},ne=K.length===0?-1:A.current.findIndex(({eventKeys:oe})=>rr(oe,K));ne>=0?A.current=A.current.map((oe,Re)=>Re===ne?{...Z,dedupeKey:I?Z.dedupeKey:oe.dedupeKey}:oe):A.current=[...A.current,Z],V()},Ie=(X,K,I)=>{if(X!=="messagesUpdated"||K.length===0)return!1;const Z=Date.now(),ne=R.current.find(oe=>oe.replaceableUntil>Z&&rr(oe.eventKeys,K));return ne?!_g(I,ne.parts):!1};l.useEffect(()=>{const X=M.current!==s;(!t||!d||X)&&(k.current=!1,D.current.clear(),N(),R.current=[],L.current.clear(),F(),X&&(M.current=s),!t||!d)||k.current||(k.current=!0,M.current=s,p.current={isClosed:i,isHandedOff:c,inputDisabled:m,inputDisabledBy:h,outgoingMessageStatuses:sr(y)},L.current=new Set(o.flatMap(K=>{if(!Me.isStreaming(K))return[];const I="sender"in K?K.sender:void 0;return(I==null?void 0:I.userId)===S.current.currentUserId?[]:Er(K)})),D.current=Eg(o))},[e,t,s,d,m,i,c,b]),l.useEffect(()=>{const X=(K,I)=>{const Z=S.current,ne=Er(K),oe=Ea(K);if(oe!=null){if(D.current.has(oe))return;D.current.add(oe),e({event:"csatDisplayed"});return}if(Me.isStreaming(K)){ne.forEach(q=>{L.current.add(q)});return}const Re=ne.filter(q=>L.current.has(q)),De=I==="messagesUpdated"&&Re.length>0;De&&Re.forEach(q=>{L.current.delete(q)});const $=I==="messagesUpdated"&&A.current.some(({eventKeys:q})=>rr(q,ne)),x=ho(K,Z.stringSet,Z.format),w=Ie(I,ne,x);if(!De&&I!=="messagesAdded"&&!$&&!w)return;const O=w?{dedupeKey:null}:void 0;if(De||P()||$){ce(x,[...new Set([...Re,...ne])],O);return}if(w){ce(x,ne,O);return}j()&&U();const z=ne[0];e({event:"newMessage",...x},z?{dedupeKey:z}:void 0)};return g(K=>{if(!k.current||K.kind==="initialized"||!rh(K.source))return;const I=S.current.currentUserId;for(const Z of K.messages)Z&&th(Z,I)&&X(Z,K.kind)})},[e,g]),l.useEffect(()=>{k.current&&(P()||j()&&V())},[h,f]),l.useEffect(()=>()=>{F()},[]),l.useEffect(()=>{if(!k.current)return;const X=p.current,K=X.outgoingMessageStatuses;X.outgoingMessageStatuses=sr(y),y.some(({key:Z,sendingStatus:ne})=>{const oe=K.get(Z);return oe!==void 0&&oe!=="failed"&&ne==="failed"})&&e({event:"sendFailed"})},[e,b]),l.useEffect(()=>{if(!k.current)return;const X=p.current;i&&!X.isClosed&&e({event:"conversationClosed"}),X.isClosed=i},[e,i]),l.useEffect(()=>{if(!k.current)return;const X=p.current;c&&!X.isHandedOff&&e({event:"agentConnected",agentName:u}),X.isHandedOff=c},[u,e,c]),l.useEffect(()=>{if(!k.current)return;const X=p.current;m&&h!=="ai_responding"&&(!X.inputDisabled||X.inputDisabledBy==="ai_responding")&&e({event:"inputDisabled"}),X.inputDisabled=m,X.inputDisabledBy=h},[e,m,h])},vg=()=>{const{channelSource:e}=Ae(),t=xi(e.channel);return!(t!=null&&t.user.userId)||!t.user.nickname?null:{userId:t.user.userId,nickname:t.user.nickname}},yg=e=>{const{announceStatus:t,announcementsEnabled:n}=ot();cm(e??null,r=>{t({event:"typing",agentName:r})},1e4,n)},Sg=()=>{const e=vg();yg(e)},J=({type:e,size:t=24,className:n,color:r})=>{const{icons:s}=Yh(),o=s[e];return a.createElement(Ag,{className:n},a.createElement(o,{size:t,color:r??E.color.primary.main,flipInRtl:Bh.has(e)}))},Ag=C.default.span.attrs({"aria-hidden":"true"})`
|
|
81
81
|
display: inline-flex;
|
|
82
82
|
&:focus {
|
|
83
83
|
outline: none;
|
|
84
84
|
}
|
|
85
|
-
`,Tg=({visible:e,onClose:t,children:n,"aria-label":r})=>a.createElement(dt,{portalContainerId:ye.WINDOW,visible:e,onClose:t,"aria-label":r},a.createElement(Mg,null,n)),Ig=({onClick:e,destructive:t,icon:n,initialFocus:r,children:s})=>a.createElement(xg,{onClick:e,$destructive:t,"data-sb-initial-focus":r?"true":void 0},n&&a.createElement(Rg,null,a.createElement(J,{type:n,size:24,color:E.themedColor.primary})),s),lt=Object.assign(Tg,{ActionItem:Ig}),xg=b.default.button`all:unset;display:flex;align-items:center;gap:24px;width:100%;padding:12px 24px;cursor:pointer;color:${({$destructive:e})=>e?E.themedColor.error:E.themedColor.textHighEmphasis};${xe}`,Rg=b.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,Mg=b.default.div`position:absolute;left:0;right:0;bottom:0;border-radius:12px 12px 0 0;flex-direction:column;align-items:flex-end;margin:0 auto;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,_o=40,Eo=.9,wg="[data-message-listitem]",kg='input, textarea, select, [role="textbox"], [contenteditable="true"]',Lg=({event:e,list:t,isMessageAnchor:n})=>{switch(e.key){case"PageDown":return t.clientHeight*Eo;case"PageUp":return t.clientHeight*-Eo;case"ArrowDown":return n?_o:void 0;case"ArrowUp":return n?_o*-1:void 0;default:return}},Og=({listRef:e,syncScrollPosition:t})=>l.useCallback(n=>{const r=e.current;if(!r||n.defaultPrevented||n.metaKey||n.altKey||n.ctrlKey)return;const s=n.target;if(!s||!r.contains(s)||s.closest(kg))return;const o=s===r||s.matches(wg),i=Lg({event:n,list:r,isMessageAnchor:o});if(i==null||i===0)return;const c=Math.max(0,r.scrollHeight-r.clientHeight),u=Math.min(c,Math.max(0,r.scrollTop+i));u!==r.scrollTop&&(n.preventDefault(),t(u))},[e,t]),Ng="[data-message-listitem]",Dg=e=>Math.min(Math.max(0,e),1),$g=e=>{const n=e.getRootNode().activeElement,r=n==null?void 0:n.closest(Ng),s=n===e||n===r;return!n||!e.contains(n)?null:s?e:n},Fg=({list:e,focusRestoreTarget:t})=>{if(!t)return;const r=e.getRootNode().activeElement,s=r===e||e.contains(r),o=t===e||e.contains(t);s&&o&&t.focus({preventScroll:!0})},Pg=({depsForResetScrollPositionToBottom:e,listRef:t,loadThreshold:n,messagesLength:r,onLoadNext:s,onLoadPrev:o,onScroll:i})=>{const c=l.useRef(!1),u=l.useRef(void 0),d=l.useRef(0),m=l.useRef(0),h=l.useRef(null),f=l.useRef(null),g=l.useRef(null);l.useLayoutEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight)},e),l.useLayoutEffect(()=>{const p=t.current;p&&(u.current==="top"&&(p.scrollTop=p.scrollHeight-m.current,Fg({list:p,focusRestoreTarget:h.current}),h.current=null),u.current==="bottom"&&(p.scrollTop=d.current),u.current=void 0)},[t,r]);const C=l.useCallback(async p=>{const S=t.current;if(!S||(i==null||i(p),m.current=S.scrollHeight-S.scrollTop,d.current=S.scrollTop,c.current))return;const A=S.clientHeight*Dg(n);if(S.scrollTop<=A){c.current=!0,u.current="top",h.current=$g(S),await o(),c.current=!1;return}if(S.scrollHeight-S.scrollTop-S.clientHeight<=A){c.current=!0,u.current="bottom",await s(),c.current=!1;return}u.current=void 0},[t,n,s,o,i]),v=l.useCallback(p=>{const S=t.current;if(!S)return;const A=g.current;if(A!=null){if(A===S.scrollTop){g.current=null;return}g.current=null}const T=f.current;if(T!=null&&T===S.scrollTop){f.current=null,g.current=S.scrollTop,C(p);return}f.current=null,C(p)},[C,t]),_=l.useCallback(p=>{const S=t.current;S&&(f.current=p,g.current=null,S.scrollTop=p,S.dispatchEvent(new Event("scroll",{bubbles:!0})))},[t]);return l.useLayoutEffect(()=>()=>{f.current=null,g.current=null},[]),{handleScroll:v,syncScrollPosition:_}},Ug=l.forwardRef(function(t,n){const{messages:r,renderMessage:s,loading:o,LoadingComponent:i,error:c,ErrorComponent:u,empty:d,EmptyComponent:m,messageTopArea:h,messageBottomArea:f,overlayArea:g,onLoadPrev:C,onLoadNext:v,loadThreshold:_=.05,onScroll:p=le,depsForResetScrollPositionToBottom:S,stackDirection:A="top",bottomSpacerHeight:T=0,"aria-label":M}=t,L=l.useRef(null),D=l.useCallback(F=>{L.current=F,n&&(typeof n=="function"?n(F):n.current=F)},[n]),{handleScroll:x,syncScrollPosition:O}=Pg({depsForResetScrollPositionToBottom:S,listRef:L,loadThreshold:_,messagesLength:r.length,onLoadNext:v,onLoadPrev:C,onScroll:p}),H=Og({listRef:L,syncScrollPosition:O});return c?a.createElement(a.Fragment,null,u):o?a.createElement(a.Fragment,null,i):a.createElement(Bg,{id:"infinite-list-container"},a.createElement(Hg,{id:"infinite-list-inner",ref:D,onScroll:x,onKeyDown:H,role:"list","aria-label":M,tabIndex:0},A==="bottom"&&a.createElement("div",{style:{flexGrow:1}}),h,d?m:r.map((F,W)=>s({message:F,index:W})),f,T>0&&a.createElement("div",{style:{minHeight:T}})),a.createElement(Gg,{id:"infinite-list-overlay-container"},a.createElement(zg,{id:"infinite-list-overlay"},g)))}),Bg=b.default.div`display:flex;position:relative;flex:1;overflow:hidden;`,Hg=b.default.div`display:flex;flex:1;flex-direction:column;overflow-x:hidden;overflow-y:auto;overscroll-behavior:contain;scrollbar-color:${E.themedColor.textLowEmphasis}transparent;&::-webkit-scrollbar-thumb:hover{background-color:transparent;}`,Gg=b.default.div`position:absolute;top:0;bottom:0;left:0;right:0;pointer-events:none;`,zg=b.default.div`pointer-events:auto;`,it=({as:e,type:t,size:n=16,color:r,disabled:s,children:o,...i})=>{const c=s?E.themedColor.textDisabled:E.themedColor.textHighEmphasis;return a.createElement(Vg,{as:e,disabled:s,...i},a.createElement(J,{type:t,size:n,color:r??c}),o)},Vg=b.default.button`all:unset;padding:4px;cursor:pointer;display:flex;align-items:center;justify-content:center;${xe}&:disabled{cursor:not-allowed;}`,pt=({className:e,children:t,size:n=26})=>a.createElement(qg,{className:e,$size:n},t??a.createElement(J,{type:"spinner",size:n})),qg=b.default.div`display:flex;align-items:center;justify-content:center;width:${({$size:e})=>Ze(e)};height:${({$size:e})=>Ze(e)};animation:1s infinite linear;animation-name:rotate;@keyframes rotate{from{transform:rotate(0);}to{transform:rotate(360deg);}}`,Kg=({files:e,initialIndex:t=0,onClose:n,visible:r})=>{const[s,o]=l.useState(t),[i,c]=l.useState(!1),{stringSet:u,format:d}=se(),{config:m}=ce(),h=e.length,f=e[s],g=m.conversation.fileViewer.downloadEnabled,C=h>1,v=(f==null?void 0:f.type)||"",_=Ye(v),p=zt(v),S=!cg(v);l.useEffect(()=>{r&&(o(t),c(!1))},[r,t]);const A=l.useCallback(()=>{s>0&&(o(M=>M-1),c(!1))},[s]),T=l.useCallback(()=>{s<h-1&&(o(M=>M+1),c(!1))},[s,h]);return l.useEffect(()=>{if(!r)return;const M=L=>{L.key==="ArrowLeft"?A():L.key==="ArrowRight"&&T()};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[r,A,T]),!r||!f?null:a.createElement(dt,{onClose:n,visible:r,portalContainerId:ye.MODAL_ROOT,"aria-label":(f==null?void 0:f.name)||u.IMAGE_VIEWER__DEFAULT_TITLE},a.createElement(Yg,null,a.createElement(Wg,null,a.createElement(jg,null,a.createElement(Xg,null,a.createElement(U,{variant:"button",maxTextLines:1,color:E.color.ondark.textHighEmphasis},f.name||u.IMAGE_VIEWER__DEFAULT_TITLE),f.timestamp&&a.createElement(U,{variant:"caption2",color:E.color.ondark.textHighEmphasis},d(new Date(f.timestamp),"h:mm a")))),a.createElement(Zg,{type:"close",size:18,color:E.color.ondark.textHighEmphasis,"aria-label":u.A11Y_IMAGE_VIEWER_CLOSE,onClick:n})),a.createElement(Jg,null,C&&a.createElement(Co,{$position:"left",type:"chevron-right",size:22,color:E.color.ondark.textHighEmphasis,onClick:A,"aria-label":u.A11Y_IMAGE_VIEWER_PREVIOUS,disabled:s===0,$flipped:!0}),a.createElement(Qg,{onClick:M=>M.currentTarget===M.target&&n()},_&&a.createElement(a.Fragment,null,!i&&a.createElement(ep,null,a.createElement(pt,{size:32},a.createElement(J,{type:"spinner",color:"textLowEmphasis",size:32}))),a.createElement(tp,{src:f.url,alt:f.name||"Image",$loaded:i,onLoad:()=>c(!0)})),p&&a.createElement(np,{controls:!0},a.createElement("source",{src:f.url,type:v})),S&&a.createElement(rp,null,a.createElement(U,{variant:"h1",color:E.themedColor.textHighEmphasis},u.FILE_VIEWER__UNSUPPORT))),C&&a.createElement(Co,{$position:"right",type:"chevron-right",size:22,color:E.color.ondark.textHighEmphasis,onClick:T,"aria-label":u.A11Y_IMAGE_VIEWER_NEXT,disabled:s===h-1})),a.createElement(sp,null,C&&a.createElement(U,{variant:"body2",color:E.color.ondark.textHighEmphasis},s+1,"/",h),g&&!S&&a.createElement(op,{forwardedAs:"a",href:f.url,download:f.name||"file",type:"download",size:24,color:E.color.ondark.textHighEmphasis,"aria-label":u.A11Y_IMAGE_VIEWER_DOWNLOAD}))))},Yg=b.default.div`position:fixed;top:0;left:0;right:0;bottom:0;height:100dvh;outline:none;display:flex;flex-direction:column;background-color:${E.themedColor.bg_50_600};`,Wg=b.default.header`display:flex;align-items:center;justify-content:space-between;padding-top:calc(12px + env(safe-area-inset-top));padding-right:12px;padding-bottom:12px;padding-left:16px;min-height:56px;background-color:${E.color.overlay.dark};`,jg=b.default.div`flex:1;min-width:0;padding-right:8px;`,Xg=b.default.div`display:flex;flex-direction:column;gap:2px;`,Zg=b.default(it)`flex-shrink:0;width:28px;height:28px;border-radius:50%;`,Bn=b.default.div`display:flex;align-items:center;justify-content:center;`,Jg=b.default(Bn)`flex:1;min-height:0;position:relative;`,Qg=b.default(Bn)`position:relative;width:100%;height:100%;min-width:0;min-height:0;`,ep=b.default(Bn)`position:absolute;inset:0;pointer-events:none;`,tp=b.default.img`max-width:100%;max-height:100%;object-fit:contain;user-select:none;-webkit-user-drag:none;opacity:${e=>e.$loaded?1:0};transition:opacity 0.3s ease;`,np=b.default.video`max-width:100%;max-height:100%;object-fit:contain;`,rp=b.default(Bn)`flex-direction:column;gap:16px;`,Co=b.default(it)`position:absolute;${e=>e.$position==="left"?"left: 12px;":"right: 12px;"}top:50%;z-index:1;width:38px;height:38px;transform:translateY(-50%) ${e=>e.$flipped?"scaleX(-1)":""};border-radius:50%;background-color:${E.color.overlay.dark};&:disabled{opacity:0.3;}`,sp=b.default.footer`position:relative;display:flex;align-items:center;justify-content:center;padding-top:16px;padding-right:16px;padding-bottom:calc(16px + env(safe-area-inset-bottom));padding-left:16px;min-height:56px;background-color:${E.color.overlay.dark};`,op=b.default(it)`position:absolute;right:16px;top:50%;transform:translateY(-50%);padding:0;width:24px;height:24px;`,ip=.75,Ca=6,ap=Ca*2;let Cr=null;typeof Intl<"u"&&"Segmenter"in Intl&&(Cr=new Intl.Segmenter(void 0,{granularity:"grapheme"}));const cp=e=>Cr?Array.from(Cr.segment(e),t=>t.segment):[...e],lp=e=>{const t=Math.floor(e.length*ip),n=Math.max(0,e.length-Ca);return Math.max(t,n)},bo=(e,t="")=>{if(e.length<ap)return{start:e+t,end:""};const n=cp(e),r=lp(n);return{start:n.slice(0,r).join(""),end:n.slice(r).join("")+t}},up=e=>{const t=e.normalize("NFC").trim(),n=t.lastIndexOf(".");if(!(n>0&&n<t.length-1))return bo(t);const s=t.slice(0,n),o=t.slice(n);return bo(s,o)},ba=({children:e,...t})=>{const{start:n,end:r}=l.useMemo(()=>up(e),[e]);return r?a.createElement(dp,null,a.createElement(mp,{...t},n),a.createElement(hp,{...t},r)):a.createElement(U,{...t},n)},dp=b.default.span`display:flex;width:100%;min-width:0;overflow:hidden;direction:inherit;`,mp=b.default(U)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex-shrink:1;min-width:0;`,hp=b.default(U)`flex-shrink:0;white-space:nowrap;`,Zr=({name:e,mimeType:t,type:n="FILE",iconColor:r,iconBackgroundColor:s,onClick:o,selected:i})=>{const{colors:c}=B.useTheme(),{conversation:u}=re(),d=o?u.file.buttonLikePreview({name:e,mimeType:t,selected:i,onActivate:o}):u.file.preview({name:e,mimeType:t,selected:i});return a.createElement(fp,{...d.props,$clickable:!!o},a.createElement(pp,{$bgColor:s??c.base.primary},a.createElement(J,{type:"file-document",size:24,color:r??c.base.primaryContrastContent})),a.createElement(_p,null,a.createElement(ba,{variant:"button",color:E.themedColor.textHighEmphasis},e),a.createElement(U,{color:E.themedColor.textMidEmphasis,variant:"caption3"},n)),d.descriptionNode)},fp=b.default.div`border:none;border-radius:12px;gap:8px;width:${ee.BODY_MAX_WIDTH}px;height:64px;display:flex;align-items:center;padding:12px;box-sizing:border-box;border:1px solid ${E.themedColor.textDisabled};background-color:${E.themedColor.bg_50_600};${({$clickable:e})=>e&&gp}`,gp=B.css`cursor:pointer;${xe}&:hover{background-color:${E.themedColor.bg_100_500};}`,pp=b.default.div`border-radius:8px;width:40px;height:40px;display:flex;align-items:center;justify-content:center;background-color:${({$bgColor:e})=>e};`,_p=b.default.div`display:flex;flex:1;flex-direction:column;gap:4px;min-width:0;`;function Ep({file:e,children:t,onClickFile:n}){const r=n?()=>n(e):void 0;return a.createElement(Cp,null,a.createElement(Zr,{name:e.name,mimeType:e.type,type:Ir(e.name,e.type),onClick:r}),t)}const Cp=b.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${ee.GAP_GROUPED}px;`,tt=`${Ge}-incoming-msg`,bp=`${Ge}-marked-text`;function vp({file:e,onClickMedia:t,onClickMediaFiles:n,children:r}){const{conversation:s}=re(),o=e.type.startsWith("image"),i=(()=>{if(n)return()=>n({files:[{url:e.url,type:e.type,name:e.name}],index:0});if(t)return()=>t(e)})(),c=i?s.file.buttonLikePreview({name:e.name,mimeType:e.type,onActivate:i}):s.file.preview({name:e.name,mimeType:e.type}),u=()=>o?a.createElement(Ap,{src:e.url,alt:"image-message"}):e.type.startsWith("video")?a.createElement(Tp,{controls:!0},a.createElement("source",{src:e.url}),a.createElement("track",{kind:"captions"})):null;if(u){const d={id:`${tt}-media-body`,...c.props};return a.createElement(yp,null,a.createElement(Sp,{...d},u(),c.descriptionNode),r)}return null}const yp=b.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${ee.GAP_GROUPED}px;`,Sp=b.default.div`width:${ee.BODY_MAX_WIDTH}px;height:160px;border-radius:12px;overflow:hidden;cursor:pointer;${Q.light`
|
|
85
|
+
`,Tg=({visible:e,onClose:t,children:n,"aria-label":r})=>a.createElement(dt,{portalContainerId:ye.WINDOW,visible:e,onClose:t,"aria-label":r},a.createElement(Mg,null,n)),Ig=({onClick:e,destructive:t,icon:n,initialFocus:r,children:s})=>a.createElement(xg,{onClick:e,$destructive:t,"data-sb-initial-focus":r?"true":void 0},n&&a.createElement(Rg,null,a.createElement(J,{type:n,size:24,color:E.themedColor.primary})),s),lt=Object.assign(Tg,{ActionItem:Ig}),xg=C.default.button`all:unset;display:flex;align-items:center;gap:24px;width:100%;padding:12px 24px;cursor:pointer;color:${({$destructive:e})=>e?E.themedColor.error:E.themedColor.textHighEmphasis};${xe}`,Rg=C.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,Mg=C.default.div`position:absolute;left:0;right:0;bottom:0;border-radius:12px 12px 0 0;flex-direction:column;align-items:flex-end;margin:0 auto;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,_o=40,Eo=.9,wg="[data-message-listitem]",kg='input, textarea, select, [role="textbox"], [contenteditable="true"]',Lg=({event:e,list:t,isMessageAnchor:n})=>{switch(e.key){case"PageDown":return t.clientHeight*Eo;case"PageUp":return t.clientHeight*-Eo;case"ArrowDown":return n?_o:void 0;case"ArrowUp":return n?_o*-1:void 0;default:return}},Og=({listRef:e,syncScrollPosition:t})=>l.useCallback(n=>{const r=e.current;if(!r||n.defaultPrevented||n.metaKey||n.altKey||n.ctrlKey)return;const s=n.target;if(!s||!r.contains(s)||s.closest(kg))return;const o=s===r||s.matches(wg),i=Lg({event:n,list:r,isMessageAnchor:o});if(i==null||i===0)return;const c=Math.max(0,r.scrollHeight-r.clientHeight),u=Math.min(c,Math.max(0,r.scrollTop+i));u!==r.scrollTop&&(n.preventDefault(),t(u))},[e,t]),Ng="[data-message-listitem]",Dg=e=>Math.min(Math.max(0,e),1),$g=e=>{const n=e.getRootNode().activeElement,r=n==null?void 0:n.closest(Ng),s=n===e||n===r;return!n||!e.contains(n)?null:s?e:n},Fg=({list:e,focusRestoreTarget:t})=>{if(!t)return;const r=e.getRootNode().activeElement,s=r===e||e.contains(r),o=t===e||e.contains(t);s&&o&&t.focus({preventScroll:!0})},Pg=({depsForResetScrollPositionToBottom:e,listRef:t,loadThreshold:n,messagesLength:r,onLoadNext:s,onLoadPrev:o,onScroll:i})=>{const c=l.useRef(!1),u=l.useRef(void 0),d=l.useRef(0),m=l.useRef(0),h=l.useRef(null),f=l.useRef(null),g=l.useRef(null);l.useLayoutEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight)},e),l.useLayoutEffect(()=>{const p=t.current;p&&(u.current==="top"&&(p.scrollTop=p.scrollHeight-m.current,Fg({list:p,focusRestoreTarget:h.current}),h.current=null),u.current==="bottom"&&(p.scrollTop=d.current),u.current=void 0)},[t,r]);const _=l.useCallback(async p=>{const S=t.current;if(!S||(i==null||i(p),m.current=S.scrollHeight-S.scrollTop,d.current=S.scrollTop,c.current))return;const A=S.clientHeight*Dg(n);if(S.scrollTop<=A){c.current=!0,u.current="top",h.current=$g(S),await o(),c.current=!1;return}if(S.scrollHeight-S.scrollTop-S.clientHeight<=A){c.current=!0,u.current="bottom",await s(),c.current=!1;return}u.current=void 0},[t,n,s,o,i]),y=l.useCallback(p=>{const S=t.current;if(!S)return;const A=g.current;if(A!=null){if(A===S.scrollTop){g.current=null;return}g.current=null}const T=f.current;if(T!=null&&T===S.scrollTop){f.current=null,g.current=S.scrollTop,_(p);return}f.current=null,_(p)},[_,t]),b=l.useCallback(p=>{const S=t.current;S&&(f.current=p,g.current=null,S.scrollTop=p,S.dispatchEvent(new Event("scroll",{bubbles:!0})))},[t]);return l.useLayoutEffect(()=>()=>{f.current=null,g.current=null},[]),{handleScroll:y,syncScrollPosition:b}},Ug=l.forwardRef(function(t,n){const{messages:r,renderMessage:s,loading:o,LoadingComponent:i,error:c,ErrorComponent:u,empty:d,EmptyComponent:m,messageTopArea:h,messageBottomArea:f,overlayArea:g,onLoadPrev:_,onLoadNext:y,loadThreshold:b=.05,onScroll:p=ue,depsForResetScrollPositionToBottom:S,stackDirection:A="top",bottomSpacerHeight:T=0,"aria-label":R}=t,L=l.useRef(null),D=l.useCallback(F=>{L.current=F,n&&(typeof n=="function"?n(F):n.current=F)},[n]),{handleScroll:k,syncScrollPosition:M}=Pg({depsForResetScrollPositionToBottom:S,listRef:L,loadThreshold:b,messagesLength:r.length,onLoadNext:y,onLoadPrev:_,onScroll:p}),P=Og({listRef:L,syncScrollPosition:M});return c?a.createElement(a.Fragment,null,u):o?a.createElement(a.Fragment,null,i):a.createElement(Bg,{id:"infinite-list-container"},a.createElement(Hg,{id:"infinite-list-inner",ref:D,onScroll:k,onKeyDown:P,role:"list","aria-label":R,tabIndex:0},A==="bottom"&&a.createElement("div",{style:{flexGrow:1}}),h,d?m:r.map((F,Y)=>s({message:F,index:Y})),f,T>0&&a.createElement("div",{style:{minHeight:T}})),a.createElement(Gg,{id:"infinite-list-overlay-container"},a.createElement(zg,{id:"infinite-list-overlay"},g)))}),Bg=C.default.div`display:flex;position:relative;flex:1;overflow:hidden;`,Hg=C.default.div`display:flex;flex:1;flex-direction:column;overflow-x:hidden;overflow-y:auto;overscroll-behavior:contain;scrollbar-color:${E.themedColor.textLowEmphasis}transparent;&::-webkit-scrollbar-thumb:hover{background-color:transparent;}`,Gg=C.default.div`position:absolute;top:0;bottom:0;left:0;right:0;pointer-events:none;`,zg=C.default.div`pointer-events:auto;`,it=({as:e,type:t,size:n=16,color:r,disabled:s,children:o,...i})=>{const c=s?E.themedColor.textDisabled:E.themedColor.textHighEmphasis;return a.createElement(Vg,{as:e,disabled:s,...i},a.createElement(J,{type:t,size:n,color:r??c}),o)},Vg=C.default.button`all:unset;padding:4px;cursor:pointer;display:flex;align-items:center;justify-content:center;${xe}&:disabled{cursor:not-allowed;}`,pt=({className:e,children:t,size:n=26})=>a.createElement(qg,{className:e,$size:n},t??a.createElement(J,{type:"spinner",size:n})),qg=C.default.div`display:flex;align-items:center;justify-content:center;width:${({$size:e})=>Ze(e)};height:${({$size:e})=>Ze(e)};animation:1s infinite linear;animation-name:rotate;@keyframes rotate{from{transform:rotate(0);}to{transform:rotate(360deg);}}`,Kg=({files:e,initialIndex:t=0,onClose:n,visible:r})=>{const[s,o]=l.useState(t),[i,c]=l.useState(!1),{stringSet:u,format:d}=se(),{config:m}=le(),h=e.length,f=e[s],g=m.conversation.fileViewer.downloadEnabled,_=h>1,y=(f==null?void 0:f.type)||"",b=Ye(y),p=zt(y),S=!cg(y);l.useEffect(()=>{r&&(o(t),c(!1))},[r,t]);const A=l.useCallback(()=>{s>0&&(o(R=>R-1),c(!1))},[s]),T=l.useCallback(()=>{s<h-1&&(o(R=>R+1),c(!1))},[s,h]);return l.useEffect(()=>{if(!r)return;const R=L=>{L.key==="ArrowLeft"?A():L.key==="ArrowRight"&&T()};return window.addEventListener("keydown",R),()=>window.removeEventListener("keydown",R)},[r,A,T]),!r||!f?null:a.createElement(dt,{onClose:n,visible:r,portalContainerId:ye.MODAL_ROOT,"aria-label":(f==null?void 0:f.name)||u.IMAGE_VIEWER__DEFAULT_TITLE},a.createElement(Yg,null,a.createElement(Wg,null,a.createElement(jg,null,a.createElement(Xg,null,a.createElement(H,{variant:"button",maxTextLines:1,color:E.color.ondark.textHighEmphasis},f.name||u.IMAGE_VIEWER__DEFAULT_TITLE),f.timestamp&&a.createElement(H,{variant:"caption2",color:E.color.ondark.textHighEmphasis},d(new Date(f.timestamp),"h:mm a")))),a.createElement(Zg,{type:"close",size:18,color:E.color.ondark.textHighEmphasis,"aria-label":u.A11Y_IMAGE_VIEWER_CLOSE,onClick:n})),a.createElement(Jg,null,_&&a.createElement(Co,{$position:"left",type:"chevron-right",size:22,color:E.color.ondark.textHighEmphasis,onClick:A,"aria-label":u.A11Y_IMAGE_VIEWER_PREVIOUS,disabled:s===0,$flipped:!0}),a.createElement(Qg,{onClick:R=>R.currentTarget===R.target&&n()},b&&a.createElement(a.Fragment,null,!i&&a.createElement(ep,null,a.createElement(pt,{size:32},a.createElement(J,{type:"spinner",color:"textLowEmphasis",size:32}))),a.createElement(tp,{src:f.url,alt:f.name||"Image",$loaded:i,onLoad:()=>c(!0)})),p&&a.createElement(np,{controls:!0},a.createElement("source",{src:f.url,type:y})),S&&a.createElement(rp,null,a.createElement(H,{variant:"h1",color:E.themedColor.textHighEmphasis},u.FILE_VIEWER__UNSUPPORT))),_&&a.createElement(Co,{$position:"right",type:"chevron-right",size:22,color:E.color.ondark.textHighEmphasis,onClick:T,"aria-label":u.A11Y_IMAGE_VIEWER_NEXT,disabled:s===h-1})),a.createElement(sp,null,_&&a.createElement(H,{variant:"body2",color:E.color.ondark.textHighEmphasis},s+1,"/",h),g&&!S&&a.createElement(op,{forwardedAs:"a",href:f.url,download:f.name||"file",type:"download",size:24,color:E.color.ondark.textHighEmphasis,"aria-label":u.A11Y_IMAGE_VIEWER_DOWNLOAD}))))},Yg=C.default.div`position:fixed;top:0;left:0;right:0;bottom:0;height:100dvh;outline:none;display:flex;flex-direction:column;background-color:${E.themedColor.bg_50_600};`,Wg=C.default.header`display:flex;align-items:center;justify-content:space-between;padding-top:calc(12px + env(safe-area-inset-top));padding-right:12px;padding-bottom:12px;padding-left:16px;min-height:56px;background-color:${E.color.overlay.dark};`,jg=C.default.div`flex:1;min-width:0;padding-right:8px;`,Xg=C.default.div`display:flex;flex-direction:column;gap:2px;`,Zg=C.default(it)`flex-shrink:0;width:28px;height:28px;border-radius:50%;`,Bn=C.default.div`display:flex;align-items:center;justify-content:center;`,Jg=C.default(Bn)`flex:1;min-height:0;position:relative;`,Qg=C.default(Bn)`position:relative;width:100%;height:100%;min-width:0;min-height:0;`,ep=C.default(Bn)`position:absolute;inset:0;pointer-events:none;`,tp=C.default.img`max-width:100%;max-height:100%;object-fit:contain;user-select:none;-webkit-user-drag:none;opacity:${e=>e.$loaded?1:0};transition:opacity 0.3s ease;`,np=C.default.video`max-width:100%;max-height:100%;object-fit:contain;`,rp=C.default(Bn)`flex-direction:column;gap:16px;`,Co=C.default(it)`position:absolute;${e=>e.$position==="left"?"left: 12px;":"right: 12px;"}top:50%;z-index:1;width:38px;height:38px;transform:translateY(-50%) ${e=>e.$flipped?"scaleX(-1)":""};border-radius:50%;background-color:${E.color.overlay.dark};&:disabled{opacity:0.3;}`,sp=C.default.footer`position:relative;display:flex;align-items:center;justify-content:center;padding-top:16px;padding-right:16px;padding-bottom:calc(16px + env(safe-area-inset-bottom));padding-left:16px;min-height:56px;background-color:${E.color.overlay.dark};`,op=C.default(it)`position:absolute;right:16px;top:50%;transform:translateY(-50%);padding:0;width:24px;height:24px;`,ip=.75,Ca=6,ap=Ca*2;let Cr=null;typeof Intl<"u"&&"Segmenter"in Intl&&(Cr=new Intl.Segmenter(void 0,{granularity:"grapheme"}));const cp=e=>Cr?Array.from(Cr.segment(e),t=>t.segment):[...e],lp=e=>{const t=Math.floor(e.length*ip),n=Math.max(0,e.length-Ca);return Math.max(t,n)},bo=(e,t="")=>{if(e.length<ap)return{start:e+t,end:""};const n=cp(e),r=lp(n);return{start:n.slice(0,r).join(""),end:n.slice(r).join("")+t}},up=e=>{const t=e.normalize("NFC").trim(),n=t.lastIndexOf(".");if(!(n>0&&n<t.length-1))return bo(t);const s=t.slice(0,n),o=t.slice(n);return bo(s,o)},ba=({children:e,...t})=>{const{start:n,end:r}=l.useMemo(()=>up(e),[e]);return r?a.createElement(dp,null,a.createElement(mp,{...t},n),a.createElement(hp,{...t},r)):a.createElement(H,{...t},n)},dp=C.default.span`display:flex;width:100%;min-width:0;overflow:hidden;direction:inherit;`,mp=C.default(H)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex-shrink:1;min-width:0;`,hp=C.default(H)`flex-shrink:0;white-space:nowrap;`,Zr=({name:e,mimeType:t,type:n="FILE",iconColor:r,iconBackgroundColor:s,onClick:o,selected:i})=>{const{colors:c}=G.useTheme(),{conversation:u}=re(),d=o?u.file.buttonLikePreview({name:e,mimeType:t,selected:i,onActivate:o}):u.file.preview({name:e,mimeType:t,selected:i});return a.createElement(fp,{...d.props,$clickable:!!o},a.createElement(pp,{$bgColor:s??c.base.primary},a.createElement(J,{type:"file-document",size:24,color:r??c.base.primaryContrastContent})),a.createElement(_p,null,a.createElement(ba,{variant:"button",color:E.themedColor.textHighEmphasis},e),a.createElement(H,{color:E.themedColor.textMidEmphasis,variant:"caption3"},n)),d.descriptionNode)},fp=C.default.div`border:none;border-radius:12px;gap:8px;width:${te.BODY_MAX_WIDTH}px;height:64px;display:flex;align-items:center;padding:12px;box-sizing:border-box;border:1px solid ${E.themedColor.textDisabled};background-color:${E.themedColor.bg_50_600};${({$clickable:e})=>e&&gp}`,gp=G.css`cursor:pointer;${xe}&:hover{background-color:${E.themedColor.bg_100_500};}`,pp=C.default.div`border-radius:8px;width:40px;height:40px;display:flex;align-items:center;justify-content:center;background-color:${({$bgColor:e})=>e};`,_p=C.default.div`display:flex;flex:1;flex-direction:column;gap:4px;min-width:0;`;function Ep({file:e,children:t,onClickFile:n}){const r=n?()=>n(e):void 0;return a.createElement(Cp,null,a.createElement(Zr,{name:e.name,mimeType:e.type,type:Ir(e.name,e.type),onClick:r}),t)}const Cp=C.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${te.GAP_GROUPED}px;`,tt=`${Ge}-incoming-msg`,bp=`${Ge}-marked-text`;function vp({file:e,onClickMedia:t,onClickMediaFiles:n,children:r}){const{conversation:s}=re(),o=e.type.startsWith("image"),i=(()=>{if(n)return()=>n({files:[{url:e.url,type:e.type,name:e.name}],index:0});if(t)return()=>t(e)})(),c=i?s.file.buttonLikePreview({name:e.name,mimeType:e.type,onActivate:i}):s.file.preview({name:e.name,mimeType:e.type}),u=()=>o?a.createElement(Ap,{src:e.url,alt:"image-message"}):e.type.startsWith("video")?a.createElement(Tp,{controls:!0},a.createElement("source",{src:e.url}),a.createElement("track",{kind:"captions"})):null;if(u){const d={id:`${tt}-media-body`,...c.props};return a.createElement(yp,null,a.createElement(Sp,{...d},u(),c.descriptionNode),r)}return null}const yp=C.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${te.GAP_GROUPED}px;`,Sp=C.default.div`width:${te.BODY_MAX_WIDTH}px;height:160px;border-radius:12px;overflow:hidden;cursor:pointer;${Q.light`
|
|
86
86
|
background-color: ${E.color.background100};
|
|
87
87
|
`}
|
|
88
88
|
${Q.dark`
|
|
89
89
|
background-color: ${E.color.background400};
|
|
90
90
|
`}
|
|
91
|
-
`,Ap=
|
|
91
|
+
`,Ap=C.default.img`width:100%;height:100%;object-fit:cover;`,Tp=C.default.video`width:100%;height:100%;object-fit:cover;`,va=({images:e,isPending:t=!1,onClickImage:n})=>{const{conversation:r}=re(),s=e.length;if(s===0)return null;const o=Tu(s),i=!!n&&!t;return a.createElement(xp,{$width:te.BODY_MAX_WIDTH,$columns:o},e.map((c,u)=>{const{columnSpan:d}=Iu({index:u,itemCount:s}),m=c.name||"",h=()=>{t||n==null||n(u)},f=c.type??"image/*",g=i?r.file.buttonLikePreview({name:m,mimeType:f,onActivate:h},u):r.file.preview({name:m,mimeType:f});return a.createElement(Rp,{key:c.url,$clickable:i,$itemSpan:d,$isPending:t,...g.props},a.createElement(Ip,{src:c.url,alt:c.name||""}),t&&a.createElement(Mp,null),g.descriptionNode)}))},Ip=({src:e,alt:t})=>{const[n,r]=l.useState(!1),[s,o]=l.useState(!1);return a.createElement(a.Fragment,null,!n&&!s&&a.createElement(wp,null,a.createElement(pt,{size:20},a.createElement(J,{type:"spinner",color:"textLowEmphasis",size:20}))),s&&a.createElement(kp,null,a.createElement(J,{type:"photo",color:"textLowEmphasis",size:24})),!s&&a.createElement(Lp,{src:e,alt:t,$loaded:n,onLoad:()=>r(!0),onError:()=>o(!0)}))},xp=C.default.div`display:grid;grid-template-columns:repeat(${({$columns:e})=>e},1fr);width:${({$width:e})=>e}px;gap:2px;border-radius:16px;overflow:hidden;`,Rp=C.default.div`position:relative;width:100%;aspect-ratio:1;overflow:hidden;cursor:${e=>e.$clickable?"pointer":"default"};${Q.light`
|
|
92
92
|
background-color: ${E.color.background100};
|
|
93
93
|
`}
|
|
94
94
|
${Q.dark`
|
|
@@ -111,19 +111,19 @@
|
|
|
111
111
|
}
|
|
112
112
|
`}
|
|
113
113
|
}
|
|
114
|
-
`,Mp=
|
|
114
|
+
`,Mp=C.default.div`position:absolute;top:0;left:0;width:100%;height:100%;background-color:${E.color.overlay.dark};pointer-events:none;`,ya=C.default.div`display:flex;align-items:center;justify-content:center;`,wp=C.default(ya)`position:absolute;inset:0;`,kp=C.default(ya)`position:absolute;inset:0;${Q.light`
|
|
115
115
|
background-color: ${E.color.background200};
|
|
116
116
|
`}
|
|
117
117
|
${Q.dark`
|
|
118
118
|
background-color: ${E.color.background500};
|
|
119
119
|
`}
|
|
120
|
-
`,Lp=
|
|
120
|
+
`,Lp=C.default.img`position:absolute;inset:0;width:100%;height:100%;object-fit:cover;opacity:${({$loaded:e})=>e?1:0};transition:opacity 0.3s ease;`,Op=({files:e,children:t,onClickMedia:n,onClickMediaFiles:r})=>{const s=o=>{const i=e[o];i&&(r?r({files:e,index:o}):n&&n({url:i.url,type:i.type||"image/*"}))};return a.createElement(Np,null,a.createElement(va,{images:e,onClickImage:s}),t)},Np=C.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${te.GAP_GROUPED}px;`,Dp="✱",Sa=e=>{const t=new RegExp(`(\`+)([^\`]+?)\\1|(${Dp}+)`,"g");return e.replace(t,(n,r,s,o)=>r?n:o?`<span id=${bp} aria-label="masked-text">${o}</span>`:n)},$p=e=>e.replace(/\*\*(.*?)\*\*/g,"<b>$1</b>"),vo=e=>{var t;return{files:e.fileInfoList.map(n=>({url:n.url,type:n.mimeType??"",name:n.fileName??""})),metadata:{localFiles:(t=e.messageParams)==null?void 0:t.fileInfoList.map(n=>n.file)}}},Fp=l.lazy(async()=>({default:(await Promise.resolve().then(()=>require("./cjs/VvejebHE.cjs"))).MarkdownText})),yo=typeof __SBA_USE_SYNTAX_HIGHLIGHT__>"u"||__SBA_USE_SYNTAX_HIGHLIGHT__?l.lazy(async()=>({default:(await Promise.resolve().then(()=>require("./cjs/DlvEEpWX.cjs"))).CodeBlock})):null;function Pp(e){var s,o;const t=e.maxBodyWidth??te.BODY_MAX_WIDTH,n=l.useMemo(()=>xc(e.message,Sa),[e.message]),r={id:`${tt}-text-body`,$maxWidth:t,$color:(s=e.customStyle)==null?void 0:s.bubbleContentColor,$bgColor:(o=e.customStyle)==null?void 0:o.bubbleBackgroundColor};return n.length===0?e.children?a.createElement(So,{...r},e.children):null:a.createElement(So,{...r},n.map((i,c)=>i.type==="text"?a.createElement(Ao,{key:c,variant:"body3"},a.createElement(Ht,{fallback:i.value},a.createElement(Fp,{onClickImage:u=>{var d;return(d=e.onClickMedia)==null?void 0:d.call(e,{url:u,type:"image/*"})},onClickLink:e.onClickLink},i.value))):i.type==="code"?yo?a.createElement(Ht,{key:c,fallback:a.createElement(Ao,{variant:"body3"},i.value)},a.createElement(yo,{code:i.value,language:i.language})):a.createElement(Up,{key:c},a.createElement("code",null,i.value)):null),e.children)}const So=C.default.div`display:flex;flex-direction:column;min-width:0;max-width:min(${({$maxWidth:e})=>e}px,100%);border-radius:12px;overflow:hidden;padding:12px 0;${({theme:e,$color:t,$bgColor:n})=>G.css`
|
|
121
121
|
color: ${t||e.colors.messageIncoming.text};
|
|
122
122
|
background-color: ${n||e.colors.messageIncoming.background};
|
|
123
123
|
`}
|
|
124
124
|
transition: max-width 0.3s;
|
|
125
125
|
overflow-wrap: break-word;
|
|
126
|
-
`,Ao=
|
|
126
|
+
`,Ao=C.default(H)`align-items:flex-start;line-height:140%;white-space:pre-wrap;padding:0 12px;`,Up=C.default.pre`margin:0;padding:1em;overflow-x:auto;white-space:pre;font-family:monospace;font-size:13px;line-height:1.5;color:#d4d4d4;background:#1e1e1e;border-radius:4px;`;function Aa({id:e,src:t,size:n=56,onClick:r,onImageError:s,style:o,...i}){const[c,u]=l.useState();return a.createElement(Bp,{id:e,tabIndex:r?0:void 0,onClick:r,$size:Ze(n),style:o,...i},t&&t!==c?a.createElement(Hp,{src:t,alt:"",onError:()=>{u(t),s==null||s(t)}}):a.createElement(J,{type:"user",size:n}))}const Bp=C.default.div`border-radius:50%;display:inline-block;overflow:hidden;position:relative;flex-shrink:0;height:${e=>e.$size};width:${e=>e.$size};background-color:${E.themedColor.bg_100_500};&:focus{outline:none;}${xe}`,Hp=C.default.img`object-fit:cover;width:100%;height:100%;position:absolute;`,Gp=({sender:e,isBotMessage:t})=>{const n=`${tt}-sender-avatar`,[r,s]=l.useState();return t&&(!e.profileUrl||e.profileUrl===r)?a.createElement(zp,{id:n},a.createElement(J,{type:"delight",size:"100%"})):a.createElement(Aa,{id:n,size:te.AVATAR_SIZE,src:e.profileUrl,onImageError:t?s:void 0})},zp=C.default.div`flex-shrink:0;width:${te.AVATAR_SIZE}px;height:${te.AVATAR_SIZE}px;box-sizing:border-box;padding:4px;border-radius:50%;display:flex;justify-content:center;align-items:center;background-color:${({theme:e})=>e.colors.base.primary}!important;ellipse,path{fill:${({theme:e})=>e.colors.base.primaryContrastContent}!important;}}`,Vp=({sender:e})=>a.createElement(qp,{id:`${tt}-sender-name`,variant:"caption1",color:E.themedColor.textMidEmphasis},e.nickname),qp=C.default(H)`text-align:start;width:100%;box-sizing:border-box;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding-block:5px;padding-inline:0 7px;`,Kp=({createdAt:e})=>{const{stringSet:t,format:n}=se();return e?a.createElement(H,{id:`${tt}-sent-time`,variant:"caption4",color:E.themedColor.textLowEmphasis},n(e,t.DATE_FORMAT__MESSAGE_TIMESTAMP)):null},Ta="(prefers-reduced-motion: reduce)",Yp=()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(Ta).matches,Ia=()=>{const[e,t]=l.useState(Yp);return l.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const n=window.matchMedia(Ta);t(n.matches);const r=s=>{t(s.matches)};return typeof n.addEventListener=="function"?(n.addEventListener("change",r),()=>{n.removeEventListener("change",r)}):(n.addListener(r),()=>{n.removeListener(r)})},[]),e},Wp=({thinkingMessage:e,customStyle:t})=>{const n=Ia();return e?a.createElement(Zp,{$prefersReducedMotion:n},a.createElement(Jp,null,e),!n&&a.createElement(Qp,null)):a.createElement(jp,{$bgColor:t==null?void 0:t.bubbleBackgroundColor},[0,1,2].map(r=>a.createElement(Xp,{key:r,$color:t==null?void 0:t.bubbleContentColor,$prefersReducedMotion:n})))},jp=C.default.div`align-items:center;border-radius:16px;display:flex;gap:6px;height:26px;justify-content:center;padding:0 12px;background-color:${({theme:e,$bgColor:t})=>t||e.colors.messageIncoming.background};`,Xp=C.default.span`animation:${({$prefersReducedMotion:e})=>e?"none":"blink 1.4s infinite"};animation-fill-mode:both;border-radius:50%;height:8px;width:8px;background:${({theme:e,$color:t})=>t||e.colors.messageIncoming.text};opacity:${({$prefersReducedMotion:e})=>e?.38:void 0};@keyframes blink{0%{opacity:0.12;transform:scale(1);}21.43%{opacity:0.38;transform:scale(1.2);}42.86%{opacity:0.12;transform:scale(1);}100%{opacity:0.12;transform:scale(1);}}&:nth-child(1){animation-delay:0.4s;}&:nth-child(2){animation-delay:0.6s;}&:nth-child(3){animation-delay:0.8s;}`,Zp=C.default.div.attrs({id:`${tt}-typing-indicator`})`
|
|
127
127
|
position: relative;
|
|
128
128
|
overflow: hidden;
|
|
129
129
|
animation: ${({$prefersReducedMotion:e})=>e?"none":"fadeIn 0.4s ease-in-out"};
|
|
@@ -135,12 +135,12 @@
|
|
|
135
135
|
opacity: 1;
|
|
136
136
|
}
|
|
137
137
|
}
|
|
138
|
-
`,Jp=
|
|
138
|
+
`,Jp=C.default(H).attrs({variant:"body3"})`
|
|
139
139
|
white-space: pre-wrap;
|
|
140
140
|
word-break: break-word;
|
|
141
141
|
color: ${E.themedColor.textHighEmphasis};
|
|
142
|
-
`,Qp=
|
|
143
|
-
`,e_=({extendedMessagePayload:e,onClickCTA:t=({url:n})=>Wr(n)})=>{const n=e==null?void 0:e.cta_button;if(!n)return null;const r=()=>t(n);return a.createElement(t_,{id:`${tt}-ext-cta-button`,onClick:r},a.createElement(n_,{variant:"button"},n.label))},t_=
|
|
142
|
+
`,Qp=C.default.div`position:absolute;inset:0;pointer-events:none;background-size:33% 100%;background-repeat:no-repeat;animation:shimmerSweepLtr 1.6s linear infinite;@keyframes shimmerSweepLtr{from{background-position:-33% 0;}to{background-position:133% 0;}}[dir='rtl'] &{animation-name:shimmerSweepRtl;@keyframes shimmerSweepRtl{from{background-position:133% 0;}to{background-position:-33% 0;}}}background-image:${({theme:e})=>{const t=Ts(e.colors.base.background,.5),n=Ts(e.colors.base.background,0);return`linear-gradient(90deg, ${n} 0%, ${t} 30%, ${t} 60%, ${n} 100%)`}};
|
|
143
|
+
`,e_=({extendedMessagePayload:e,onClickCTA:t=({url:n})=>Wr(n)})=>{const n=e==null?void 0:e.cta_button;if(!n)return null;const r=()=>t(n);return a.createElement(t_,{id:`${tt}-ext-cta-button`,onClick:r},a.createElement(n_,{variant:"button"},n.label))},t_=C.default.button.attrs({type:"button"})`
|
|
144
144
|
all: unset;
|
|
145
145
|
display: flex;
|
|
146
146
|
width: 100%;
|
|
@@ -157,7 +157,7 @@
|
|
|
157
157
|
`}
|
|
158
158
|
|
|
159
159
|
${xe}
|
|
160
|
-
`,n_=
|
|
160
|
+
`,n_=C.default(H)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,r_=e=>a.createElement(a.Fragment,null),s_=({extendedMessagePayload:e,onClickCitation:t=n=>Wr(n.link)})=>{const{stringSet:n}=se(),{theme:r}=Pr(),s=e==null?void 0:e.citations;return!s||s.length===0?null:a.createElement(o_,{id:`${tt}-ext-citation`},a.createElement(i_,{variant:"caption1",color:r.colors.messageIncoming.text},n.CITATION_SOURCE_TITLE),a.createElement(a_,null,s.map((o,i)=>a.createElement(l_,{key:`${o.embedding_id}-${i}`,onClick:()=>t(o)},a.createElement(J,{type:"source",size:16,color:r.colors.messageIncoming.text}),a.createElement(c_,{variant:"body3",color:r.colors.messageIncoming.text},o.title)))))},o_=C.default.div`display:flex;flex-direction:column;gap:8px;border-radius:8px;padding:8px 12px 6px;`,i_=C.default(H)`opacity:0.5;`,a_=C.default.div`display:flex;flex-direction:column;gap:8px;`,c_=C.default(H)`text-decoration:underline;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,l_=C.default.button.attrs({type:"button"})`
|
|
161
161
|
background: none;
|
|
162
162
|
border: none;
|
|
163
163
|
padding: 0;
|
|
@@ -172,25 +172,25 @@
|
|
|
172
172
|
&:hover {
|
|
173
173
|
opacity: 0.5;
|
|
174
174
|
}
|
|
175
|
-
`,u_=e=>a.createElement(a.Fragment,null),br=e=>`${e}-filled`,d_=e=>e==="good"?
|
|
175
|
+
`,u_=e=>a.createElement(a.Fragment,null),br=e=>`${e}-filled`,d_=e=>e==="good"?me.AIAgentMessageFeedbackRating.GOOD:me.AIAgentMessageFeedbackRating.BAD,Jr=G.css`&:hover{opacity:0.8;}&:active{opacity:0.6;}`,dn={good:{onlight:E.color.secondary.dark,ondark:E.color.secondary.light},bad:{onlight:E.color.error.dark,ondark:E.color.error.light}},m_={good:E.themedColor.secondary,bad:E.themedColor.error},xa=e=>G.css`color:${dn[e].onlight};border-color:${dn[e].onlight};${Q.dark`
|
|
176
176
|
color: ${dn[e].ondark};
|
|
177
177
|
border-color: ${dn[e].ondark};
|
|
178
178
|
`}
|
|
179
|
-
`,h_=({visible:e,onClose:t,isEdit:n,initialRating:r,initialComment:s="",onSubmit:o,isCommentEnabled:i=!1})=>{const{stringSet:c}=se(),{conversation:u}=re(),{rootElement:d}=Ji(),m=ut(d),[h,f]=l.useState(r),[g,
|
|
179
|
+
`,h_=({visible:e,onClose:t,isEdit:n,initialRating:r,initialComment:s="",onSubmit:o,isCommentEnabled:i=!1})=>{const{stringSet:c}=se(),{conversation:u}=re(),{rootElement:d}=Ji(),m=ut(d),[h,f]=l.useState(r),[g,_]=l.useState(s),[y,b]=l.useState(!1),p=l.useRef(!1),S=h??r??"good",A=u.feedback;l.useLayoutEffect(()=>{e?(f(r),_(s)):(f(void 0),_(""))},[e,r,s]),l.useEffect(()=>{if(!e)return;const D=M=>{const P=M;P.metaKey||P.altKey||P.ctrlKey||(p.current=!0)},k=()=>{p.current=!1,b(!1)};return m.addEventListener("keydown",D),m.addEventListener("pointerdown",k),()=>{m.removeEventListener("keydown",D),m.removeEventListener("pointerdown",k)}},[m,e]);const T=()=>{h&&(o({rating:h,comment:g.trim()||void 0}),t())},R=()=>{t()};if(!e)return null;const L={feedback:A.container()};return a.createElement(dt,{portalContainerId:ye.WINDOW,visible:e,onClose:R,"aria-label":c.FEEDBACK_TITLE},a.createElement(f_,null,a.createElement(g_,null,a.createElement(H,{variant:"h2",color:E.themedColor.textHighEmphasis},c.FEEDBACK_TITLE)),a.createElement(p_,null,a.createElement(__,{...L.feedback.props},["good","bad"].map(D=>{const k=h===D,M=D==="good"?c.FEEDBACK_GOOD:c.FEEDBACK_BAD,P=A.button(D,k);return a.createElement(l.Fragment,{key:D},a.createElement(E_,{type:"button",$selected:k,$rating:D,...P.props,onClick:()=>f(D),"data-sb-initial-focus":D===S?"true":void 0},a.createElement(J,{type:k?br(D):D,size:24,color:"currentColor"}),a.createElement(H,{variant:"caption1",color:"currentColor"},M)),P.descriptionNode)}),L.feedback.descriptionNode),i&&a.createElement(C_,null,a.createElement(H,{variant:"caption3",color:E.themedColor.textHighEmphasis},c.FEEDBACK_COMMENT_LABEL),a.createElement(b_,{placeholder:c.FEEDBACK_COMMENT_PLACEHOLDER,value:g,onChange:D=>_(D.target.value),onFocus:()=>b(p.current),onBlur:()=>b(!1),maxLength:100,$focusVisible:y,"data-focus-visible":y?"true":"false"}))),a.createElement(v_,null,a.createElement(y_,{onClick:R},a.createElement(H,{variant:"button",color:E.themedColor.textHighEmphasis},c.FEEDBACK_CANCEL)),a.createElement(S_,{onClick:T,disabled:!h},a.createElement(H,{variant:"button"},n?c.FEEDBACK_SAVE:c.FEEDBACK_SUBMIT)))))},f_=C.default.div`width:280px;background-color:${({theme:e})=>e.colors.base.modalContentBackground};border-radius:12px;overflow:hidden;`,g_=C.default.div`padding:24px;`,p_=C.default.div`padding-inline:24px;display:flex;flex-direction:column;gap:24px;`,__=C.default.div`display:flex;gap:4px;`,E_=C.default.button`width:114px;height:64px;border-radius:12px;border:1px solid ${E.themedColor.textDisabled};box-sizing:border-box;cursor:pointer;display:flex;flex-direction:column;align-items:center;justify-content:center;padding:0;gap:0;transition:background-color 0.2s;color:${E.themedColor.textLowEmphasis};background-color:transparent;${({$selected:e,$rating:t})=>e&&xa(t)}${Jr}`,C_=C.default.label`display:flex;flex-direction:column;gap:6px;`,b_=C.default.textarea`font-family:inherit;font-size:12px;line-height:16px;border:1px solid ${E.themedColor.textDisabled};border-radius:4px;padding:6px 12px;color:${E.themedColor.textHighEmphasis};background-color:${E.themedColor.textLowEmphasisInverse};resize:none;field-sizing:content;min-height:28px;max-height:118px;overflow-y:auto;&::placeholder{color:${E.themedColor.textLowEmphasis};}&:focus{outline:none;}${({$focusVisible:e})=>e&&G.css`
|
|
180
180
|
outline: 2px solid ${E.themedColor.primary};
|
|
181
181
|
outline-offset: 2px;
|
|
182
182
|
`}
|
|
183
|
-
`,v_=
|
|
183
|
+
`,v_=C.default.div`padding-inline:24px;padding-block:16px;display:flex;justify-content:flex-end;gap:4px;`,Ra=C.default.button`width:86px;height:40px;border-radius:20px;border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:opacity 0.2s;`,y_=C.default(Ra)`background-color:transparent;${Jr}`,S_=C.default(Ra)`cursor:${({disabled:e})=>e?"not-allowed":"pointer"};opacity:${({disabled:e})=>e?.4:1};&:hover:not(:disabled){opacity:0.8;}&:active:not(:disabled){opacity:0.6;}background-color:${({theme:e})=>e.colors.base.primary};span{color:${({theme:e})=>e.colors.base.primaryContrastContent};}`,A_=({isBotMessage:e,isConversationClosed:t,isStreaming:n,isFeedbackEnabled:r,isFeedbackCommentEnabled:s,extendedMessagePayload:o,onFeedbackUpdate:i})=>{const{stringSet:c}=se(),{conversation:u}=re(),[d,m]=l.useState(!1),[h,f]=l.useState(!1),[g,_]=l.useState(void 0),[y,b]=l.useState(""),p=l.useRef(null),S=l.useRef(null),A=l.useRef(null),T=l.useRef(!1),R=u.feedback,L=o==null?void 0:o.feedback,D=(L==null?void 0:L.rating)??"none";if(D!=="none"?!1:!!(n||!e||!r||(o==null?void 0:o.bot_message_type)!=="generated"||t))return null;const M=U=>{U&&we(()=>{const V=U==="good"?p.current:S.current;V==null||V.focus()})},P=({restoreTrigger:U=!0}={})=>{f(!1),U&&M(A.current)},F=U=>{D==="none"?(_(U),b(""),m(!0)):(A.current=U,f(!0))},Y=()=>{i==null||i(null),P()},j=()=>{T.current=!0,P({restoreTrigger:!1}),_(L==null?void 0:L.rating),b((L==null?void 0:L.comment)??""),m(!0)},N=U=>{T.current=!1,i==null||i(U),m(!1),M(A.current)},B=()=>{m(!1),T.current&&(T.current=!1,f(!0))};return t&&D!=="none"?a.createElement(To,{role:"presentation",$horizontal:!0},a.createElement(T_,null,a.createElement(J,{type:br(D),size:12,color:m_[D]})),(L==null?void 0:L.comment)&&a.createElement(Io,{variant:"caption2",style:{lineHeight:"16px"}},L.comment)):a.createElement(a.Fragment,null,a.createElement(To,{role:"presentation"},a.createElement(I_,{role:"presentation"},["good","bad"].map(U=>{const V=D===U,ce=R.button(U,V);return a.createElement(l.Fragment,{key:U},a.createElement(x_,{$selected:V,$rating:U,ref:U==="good"?p:S,...ce.props,onClick:()=>F(U)},a.createElement(J,{type:V?br(U):U,size:14,color:"currentColor"})),ce.descriptionNode)})),D!=="none"&&(L==null?void 0:L.comment)&&a.createElement(Io,{variant:"caption2"},L.comment)),a.createElement(lt,{visible:h,onClose:P,...R.optionsBottomSheet().props},a.createElement(lt.ActionItem,{onClick:j,initialFocus:!0},c.FEEDBACK_EDIT),a.createElement(lt.ActionItem,{onClick:Y,destructive:!0},c.FEEDBACK_REMOVE)),a.createElement(h_,{visible:d,onClose:B,isEdit:D!=="none",initialRating:g,initialComment:y,onSubmit:N,isCommentEnabled:s}))},To=C.default.div`display:flex;flex-direction:${({$horizontal:e})=>e?"row":"column"};align-items:${({$horizontal:e})=>e?"flex-start":"stretch"};gap:4px;margin-top:8px;word-break:break-word;max-width:${te.BODY_MAX_WIDTH}px;`,T_=C.default.div`padding:2px;flex-shrink:0;display:flex;align-items:center;`,I_=C.default.div`display:flex;gap:2px;`,x_=C.default.button`width:38px;height:20px;border-radius:18px;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0;transition:opacity 0.2s;box-sizing:border-box;color:${E.themedColor.textMidEmphasis};border:1px solid ${E.color.background200};background-color:transparent;${Q.dark`
|
|
184
184
|
border: 1px solid ${E.color.background400};
|
|
185
185
|
`}
|
|
186
186
|
|
|
187
187
|
${({$selected:e,$rating:t})=>e&&xa(t)}
|
|
188
188
|
|
|
189
189
|
${Jr}
|
|
190
|
-
`,Io=
|
|
190
|
+
`,Io=C.default(H)`color:${E.themedColor.textMidEmphasis};${Q.dark`
|
|
191
191
|
color: ${E.themedColor.textHighEmphasis};
|
|
192
192
|
`}
|
|
193
|
-
`,Qr=
|
|
193
|
+
`,Qr=G.css`width:100%;height:36px;border-radius:6px;cursor:pointer;transition:all 0.2s ease;padding:0 12px;border:none;outline:none;display:flex;align-items:center;justify-content:center;${xe}&:disabled{cursor:not-allowed;}`,xo=C.default.button`${Qr};background-color:${E.themedColor.primary};color:${E.themedColor.textHighEmphasis};&:hover:not(:disabled){opacity:0.9;}`,R_=C.default.button`${Qr};color:${E.themedColor.primary};${Q.light`
|
|
194
194
|
background-color: ${E.color.background50};
|
|
195
195
|
`};
|
|
196
196
|
${Q.dark`
|
|
@@ -200,7 +200,7 @@
|
|
|
200
200
|
&:hover:not(:disabled) {
|
|
201
201
|
opacity: 0.9;
|
|
202
202
|
}
|
|
203
|
-
`,M_=
|
|
203
|
+
`,M_=C.default.button`${Qr};background-color:transparent;color:${E.themedColor.textHighEmphasis};&:hover:not(:disabled){opacity:0.7;}`,w_=e=>{switch(e){case"primary":return xo;case"secondary":return R_;case"clear":return M_;default:return xo}},k_=C.default.div`animation:1s infinite linear;animation-name:rotate;display:flex;align-items:center;justify-content:center;@keyframes rotate{from{transform:rotate(0);}to{transform:rotate(360deg);}}`,L_=({children:e,onClick:t,variant:n="primary",disabled:r=!1,loading:s=!1,className:o,...i})=>{const c=()=>{switch(n){case"primary":return E.themedColor.textHighEmphasisInverse;case"secondary":return E.themedColor.primary;case"clear":return E.themedColor.textHighEmphasis;default:return E.themedColor.textHighEmphasisInverse}},u=w_(n);return a.createElement(u,{onClick:t,disabled:r||s,className:o,...i},s?a.createElement(k_,null,a.createElement(J,{type:"spinner",size:22,color:c()})):a.createElement(H,{variant:"button",color:c()},e))},O_=({children:e,className:t,style:n,id:r,role:s})=>a.createElement(H,{variant:"caption4",color:E.themedColor.error,className:t,style:n,id:r,role:s},e),N_=({id:e,children:t,className:n,style:r,required:s,"aria-hidden":o})=>{const{stringSet:i}=se();return a.createElement(H,{id:e,variant:"caption3",color:E.themedColor.textMidEmphasis,className:n,style:r,"aria-hidden":o},t,!s&&a.createElement("span",{style:{color:E.themedColor.textLowEmphasis}},` (${i.OPTIONAL})`))},D_=({value:e,onChange:t,placeholder:n,error:r=!1,submitted:s=!1,className:o,disabled:i=!1,max:c,...u})=>{const d=h=>{const g=h.target.value.replace(/[^0-9.-]/g,""),_=g.split("."),b=_.length>1?_[0]+"."+_.slice(1).join("").replace(/\./g,""):g;if(h.target.value=b,b===""||b==="-")t==null||t(null);else{const p=Number(b);if(!isNaN(p)){if(c!==void 0&&p>c)return;t==null||t(p)}}},m=e==null?"":String(e);return a.createElement(B_,{type:"text",value:m,onChange:d,placeholder:n,className:o,disabled:i||s,inputMode:"decimal",$error:r,$submitted:s,...u})},$_=G.css`width:100%;height:36px;padding:8px 12px;border-radius:6px;font-size:14px;font-weight:400;line-height:1.43;outline:none;transition:all 0.2s ease;${xe}&::placeholder{color:${E.themedColor.textLowEmphasis};}&::-webkit-inner-spin-button,&::-webkit-outer-spin-button{-webkit-appearance:none;margin:0;}`,F_=G.css`color:${E.themedColor.textHighEmphasis};border:1px solid transparent;cursor:not-allowed;${Q.light`
|
|
204
204
|
background-color: ${E.color.ondark.textMidEmphasis};
|
|
205
205
|
`}
|
|
206
206
|
${Q.dark`
|
|
@@ -210,13 +210,13 @@
|
|
|
210
210
|
&::placeholder {
|
|
211
211
|
color: ${E.themedColor.textLowEmphasis};
|
|
212
212
|
}
|
|
213
|
-
`,P_=
|
|
213
|
+
`,P_=G.css`border:1px solid ${E.themedColor.error};color:${E.themedColor.textHighEmphasis};${Q.light`
|
|
214
214
|
background-color: ${E.color.background50};
|
|
215
215
|
`}
|
|
216
216
|
${Q.dark`
|
|
217
217
|
background-color: ${E.color.onlight.textLowEmphasis};
|
|
218
218
|
`}
|
|
219
|
-
`,U_=
|
|
219
|
+
`,U_=G.css`border:1px solid ${E.themedColor.textDisabled};color:${E.themedColor.textHighEmphasis};${Q.light`
|
|
220
220
|
background-color: ${E.color.background50};
|
|
221
221
|
`}
|
|
222
222
|
${Q.dark`
|
|
@@ -226,12 +226,12 @@
|
|
|
226
226
|
&:focus {
|
|
227
227
|
border-color: ${E.themedColor.primary};
|
|
228
228
|
}
|
|
229
|
-
`,B_=
|
|
229
|
+
`,B_=C.default.input`${$_}${({$error:e,$submitted:t})=>t?F_:e?P_:U_}`,H_=e=>{if(e.multiple){const{value:t=[],onChange:n,maxSelect:r,submitted:s=!1}=e;return{selectedValues:t,handleOptionClick:i=>{if(s)return;if(t.includes(i)){const u=t.filter(d=>d!==i);n==null||n(u)}else{if(r&&t.length>=r)return;const u=[...t,i];n==null||n(u)}}}}else{const{value:t,onChange:n,submitted:r=!1}=e;return{selectedValues:t?[t]:[],handleOptionClick:o=>{r||t!==o&&(n==null||n(o))}}}},Ma=e=>{const{options:t,submitted:n=!1,error:r=!1,className:s,groupLabel:o}=e,{conversation:i}=re(),c=e.multiple===!0,{selectedValues:u,handleOptionClick:d}=H_(e),m=t.some(h=>u.includes(h.value));return a.createElement(z_,{className:s,...c?void 0:i.form.singleSelectGroup(o).props},t.map((h,f)=>{const g=u.includes(h.value),_=o?`${o}, ${h.label}`:h.label;return a.createElement(X_,{key:h.value,type:"button",$active:g,$submitted:n,$error:r,...(c?i.form.multiSelectOption(_,g,n):i.form.singleSelectOption(_,g,n,f,t.length,m,y=>{const b=t[y];b&&d(b.value)})).props,disabled:n,onClick:()=>d(h.value)},a.createElement(H,{variant:"caption1",color:G_(g,n)},h.label))}))},G_=(e,t)=>t?e?E.themedColor.textHighEmphasis:E.themedColor.textDisabled:e?E.themedColor.primary:E.themedColor.textMidEmphasis,z_=C.default.div`display:flex;flex-wrap:wrap;gap:4px 2px;`,V_=G.css`display:inline-flex;align-items:center;padding:8px 12px;border-radius:15px;transition:all 0.2s ease;`,q_=G.css`cursor:default;background-color:${E.color.ondark.textMidEmphasis};color:${E.themedColor.textHighEmphasis};${Q.dark`
|
|
230
230
|
background-color: transparent;
|
|
231
231
|
border: 1px solid white;
|
|
232
232
|
color: white;
|
|
233
233
|
`}
|
|
234
|
-
`,K_=
|
|
234
|
+
`,K_=G.css`cursor:default;${Q.light`
|
|
235
235
|
background-color: ${E.color.ondark.textMidEmphasis};
|
|
236
236
|
color: ${E.themedColor.textDisabled};
|
|
237
237
|
`}
|
|
@@ -240,7 +240,7 @@
|
|
|
240
240
|
border: 1px solid ${E.color.onlight.textLowEmphasis};
|
|
241
241
|
color: ${E.themedColor.textDisabled};
|
|
242
242
|
`}
|
|
243
|
-
`,Y_=
|
|
243
|
+
`,Y_=G.css`cursor:pointer;border:1px solid ${E.themedColor.primary};${Q.light`
|
|
244
244
|
background-color: ${E.color.background50};
|
|
245
245
|
color: ${E.themedColor.primary};
|
|
246
246
|
`}
|
|
@@ -248,7 +248,7 @@
|
|
|
248
248
|
background-color: ${E.color.onlight.textLowEmphasis};
|
|
249
249
|
color: ${E.themedColor.primary};
|
|
250
250
|
`}
|
|
251
|
-
`,W_=
|
|
251
|
+
`,W_=G.css`cursor:pointer;border:1px solid ${E.themedColor.textDisabled};${Q.light`
|
|
252
252
|
background-color: ${E.color.background50};
|
|
253
253
|
color: ${E.themedColor.textMidEmphasis};
|
|
254
254
|
`}
|
|
@@ -256,10 +256,10 @@
|
|
|
256
256
|
background-color: ${E.color.onlight.textLowEmphasis};
|
|
257
257
|
color: ${E.themedColor.textMidEmphasis};
|
|
258
258
|
`}
|
|
259
|
-
`,j_=
|
|
259
|
+
`,j_=G.css`border-color:${E.themedColor.error}!important;`,X_=C.default.button`${V_}${({$active:e,$submitted:t,$error:n})=>{if(t)return e?q_:K_;const r=e?Y_:W_;return n?G.css`
|
|
260
260
|
${r} ${j_}
|
|
261
261
|
`:r}}
|
|
262
|
-
`,Z_=e=>a.createElement(Ma,{...e,multiple:!1}),J_=e=>a.createElement(Ma,{...e,multiple:!0}),Q_=
|
|
262
|
+
`,Z_=e=>a.createElement(Ma,{...e,multiple:!1}),J_=e=>a.createElement(Ma,{...e,multiple:!0}),Q_=C.default.div`width:100%;height:1px;background-color:${E.themedColor.textDisabled};`,eE=({className:e})=>a.createElement(Q_,{className:e}),tE=({id:e,value:t="",onChange:n,placeholder:r,variant:s="single-line",error:o=!1,submitted:i=!1,className:c,disabled:u=!1,maxLength:d,...m})=>{const f={id:e,value:t,onChange:g=>{const _=g.target.value;d&&_.length>d||n==null||n(_)},placeholder:r,className:c,disabled:u||i,maxLength:d,$error:o,$submitted:i,...m};return s==="multi-line"?a.createElement(rE,{...f}):a.createElement(nE,{...f})},wa=G.css`width:100%;padding:8px 12px;border-radius:6px;font-size:14px;font-weight:400;line-height:1.43;outline:none;transition:all 0.2s ease;${xe}&::placeholder{color:${E.themedColor.textLowEmphasis};}`,ka=G.css`color:${E.themedColor.textHighEmphasis};border:1px solid transparent;cursor:not-allowed;${Q.light`
|
|
263
263
|
background-color: ${E.color.ondark.textMidEmphasis};
|
|
264
264
|
`}
|
|
265
265
|
${Q.dark`
|
|
@@ -269,13 +269,13 @@
|
|
|
269
269
|
&::placeholder {
|
|
270
270
|
color: ${E.themedColor.textLowEmphasis};
|
|
271
271
|
}
|
|
272
|
-
`,La=
|
|
272
|
+
`,La=G.css`border:1px solid ${E.themedColor.error};color:${E.themedColor.textHighEmphasis};${Q.light`
|
|
273
273
|
background-color: ${E.color.background50};
|
|
274
274
|
`}
|
|
275
275
|
${Q.dark`
|
|
276
276
|
background-color: ${E.color.onlight.textLowEmphasis};
|
|
277
277
|
`}
|
|
278
|
-
`,Oa=
|
|
278
|
+
`,Oa=G.css`border:1px solid ${E.themedColor.textDisabled};color:${E.themedColor.textHighEmphasis};${Q.light`
|
|
279
279
|
background-color: ${E.color.background50};
|
|
280
280
|
`}
|
|
281
281
|
${Q.dark`
|
|
@@ -285,14 +285,14 @@
|
|
|
285
285
|
&:focus {
|
|
286
286
|
border-color: ${E.themedColor.primary};
|
|
287
287
|
}
|
|
288
|
-
`,nE=
|
|
288
|
+
`,nE=C.default.input`${wa};height:36px;${({$error:e,$submitted:t})=>t?ka:e?La:Oa}`,rE=C.default.textarea`${wa};height:96px;resize:none;font-family:inherit;${({$error:e,$submitted:t})=>t?ka:e?La:Oa}`,sE=({children:e,className:t,style:n})=>a.createElement(H,{variant:"button",color:E.themedColor.textHighEmphasis,className:t,style:n},e),Le={Title:sE,Label:N_,ErrorLabel:O_,Separator:eE,Button:L_,TextInput:tE,NumberInput:D_,SingleSelect:Z_,MultiSelect:J_},oE=1,iE=new Set(["text","number","single-select","multi-select"]),Na=typeof __SBA_USE_FORM__>"u"||__SBA_USE_FORM__,aE=({messageForm:e,onError:t})=>{const n=l.useRef(void 0);l.useEffect(()=>{if(Na||!e||!t)return;const r=e.key??"";n.current!==r&&(t(new Error("Form rendering is disabled")),n.current=r)},[e,t])},cE=e=>{var p,S;const t=(p=e.extendedMessagePayload)==null?void 0:p.form;if(aE({messageForm:t,onError:(S=e.statsCallbacks)==null?void 0:S.onFormRenderError}),!Na)return null;if(!t)throw new Error("Form is not provided");const{stringSet:n}=se(),{conversation:r}=re(),[s,o]=l.useState({submitting:!1,canceling:!1}),[i,c]=l.useState({visible:!1}),{state:u,fields:d,submit:m,cancel:h,updateFieldValue:f}=rm(t,{labels:{required:n.FORM_VALIDATION_REQUIRED,regex:n.FORM_VALIDATION_REGEX_FAILED,minLength:n.FORM_VALIDATION_MIN_LENGTH,maxLength:n.FORM_VALIDATION_MAX_LENGTH,min:n.FORM_VALIDATION_MIN,max:n.FORM_VALIDATION_MAX,minSelect:n.FORM_VALIDATION_MIN_SELECT,maxSelect:n.FORM_VALIDATION_MAX_SELECT},onSubmit:A=>{var T;return(T=e.onSubmitForm)==null?void 0:T.call(e,{key:t.key,data:A})},onCancel:()=>{var A;return(A=e.onCancelForm)==null?void 0:A.call(e,{key:t.key})}}),g=u==="submitted",_=async()=>{o(A=>({...A,submitting:!0}));try{await m()}catch(A){c({visible:!0,description:A instanceof Error?A.message:n.TRY_AGAIN})}finally{o(A=>({...A,submitting:!1}))}},y=async()=>{o(A=>({...A,canceling:!0}));try{await h()}catch(A){c({visible:!0,description:A instanceof Error?A.message:n.TRY_AGAIN})}finally{o(A=>({...A,canceling:!1}))}},b=l.useMemo(()=>{const A=()=>t.version>oE,T=()=>t.fields.some(R=>!iE.has(R.type));return A()||T()?{visible:!1,cancelable:!0,reason:n.FORM_NOT_SUPPORTED}:u==="draft"&&(e.isHandedOff||e.isConversationClosed)?{visible:!1,cancelable:!1,reason:n.FORM_UNAVAILABLE}:{visible:!0,cancelable:!0,reason:""}},[t.version,t.fields,u,e.isHandedOff,e.isConversationClosed]);return u==="canceled"?null:b.visible?a.createElement(l.Fragment,null,a.createElement(Ro,{$maxWidth:e.maxBodyWidth??te.BODY_MAX_WIDTH},a.createElement(Le.Title,null,t.title),a.createElement(lE,null,d.map(A=>a.createElement(uE,{key:A.key},a.createElement(Le.Label,{style:{marginBottom:"6px"},required:A.required},A.label),A.type==="text"&&a.createElement(Le.TextInput,{value:A.value||"",placeholder:A.placeholder,onChange:T=>f(A.key,T),disabled:g,error:!!A.error,submitted:g,variant:A.layout==="multiline"?"multi-line":"single-line",maxLength:A.maxLength,...r.form.textInput(A.label,A.required??!1,g).props}),A.type==="number"&&a.createElement(Le.NumberInput,{value:A.value||null,placeholder:A.placeholder,onChange:T=>f(A.key,T),disabled:g,error:!!A.error,submitted:g,max:A.max,...r.form.numberInput(A.label,A.required??!1,g).props}),A.type==="single-select"&&a.createElement(Le.SingleSelect,{options:A.options.map(T=>({label:T,value:T})),value:A.value||"",onChange:T=>f(A.key,T),submitted:g,groupLabel:A.label}),A.type==="multi-select"&&a.createElement(Le.MultiSelect,{options:A.options.map(T=>({label:T,value:T})),value:A.value||[],onChange:T=>f(A.key,T),submitted:g,maxSelect:A.maxSelect,groupLabel:A.label}),A.error&&a.createElement(Le.ErrorLabel,{style:{marginTop:"4px"}},A.error)))),a.createElement(Le.Separator,null),a.createElement(dE,null,a.createElement(Le.Button,{variant:g?"clear":"primary",...r.form.button(g?n.SUBMITTED:n.BUTTON__SUBMIT).props,onClick:_,disabled:g||s.canceling,loading:s.submitting},g?n.SUBMITTED:n.BUTTON__SUBMIT),u!=="submitted"&&a.createElement(Le.Button,{variant:"secondary",...r.form.button(n.BUTTON__CANCEL).props,onClick:y,disabled:s.submitting,loading:s.canceling},n.BUTTON__CANCEL))),a.createElement(Pn,{...i,onClose:()=>c({visible:!1,title:""})})):a.createElement(Ro,{$maxWidth:e.maxBodyWidth??te.BODY_MAX_WIDTH},a.createElement(H,{variant:"body3"},b.reason),b.cancelable&&a.createElement(Le.Button,{variant:"primary",...r.form.button(n.BUTTON__CANCEL).props,onClick:y,loading:s.canceling},n.BUTTON__CANCEL))},Ro=C.default.div`display:flex;flex-direction:column;gap:12px;border-radius:12px;overflow:hidden;max-width:${({$maxWidth:e})=>e}px;${({theme:e})=>G.css`
|
|
289
289
|
color: ${e.colors.messageIncoming.text};
|
|
290
290
|
background-color: ${e.colors.messageIncoming.background};
|
|
291
291
|
`}
|
|
292
292
|
padding: 16px 12px;
|
|
293
293
|
transition: max-width 0.3s;
|
|
294
294
|
overflow-wrap: break-word;
|
|
295
|
-
`,lE=
|
|
295
|
+
`,lE=C.default.div`display:flex;flex-direction:column;gap:12px;`,uE=C.default.div`display:flex;flex-direction:column;`,dE=C.default.div`display:flex;flex-direction:column;gap:8px;`,mE=e=>a.createElement(a.Fragment,null),vr=typeof __SBA_USE_MESSAGE_TEMPLATE__>"u"||__SBA_USE_MESSAGE_TEMPLATE__?l.lazy(()=>Promise.resolve().then(()=>require("./cjs/ZOM6SoNd.cjs")).then(e=>({default:e.MessageTemplateWrapper}))):null,hE=({messageTemplate:e,onError:t})=>{const n=l.useRef(void 0);l.useEffect(()=>{if(vr||!e||!t)return;const r=e.key??"";n.current!==r&&(t(new Error("Message template rendering is disabled")),n.current=r)},[e,t])},fE=e=>{var n,r,s;const t=(n=e.extendedMessagePayload)==null?void 0:n.message_template;return hE({messageTemplate:t,onError:(r=e.statsCallbacks)==null?void 0:r.onMessageTemplateError}),vr?a.createElement(Ht,{errorFallback:e.messageTemplateErrorFallback,loadingFallback:e.messageTemplateLoadingFallback,onError:(s=e.statsCallbacks)==null?void 0:s.onMessageTemplateError},a.createElement(vr,{...e})):null},gE=({extendedMessagePayload:e,onClickSuggestedReply:t,suggestedRepliesDirection:n="vertical"})=>{const{conversation:r}=re(),[s,o]=l.useState(!1),{suggestedReplies:i}=r,c=(e==null?void 0:e.suggested_replies)??[];if(c.length===0||s)return null;const u=d=>{t&&(t({reply:d}),o(!0))};return a.createElement(pE,{id:`${tt}-ext-suggested-replies`,role:"presentation",$type:n},c.map((d,m)=>{const h=i.item(d,m);return a.createElement(l.Fragment,{key:m},a.createElement(_E,{$type:n,...h.props,onClick:()=>u(d)},a.createElement(EE,{variant:"body3"},d)),h.descriptionNode)}))},pE=C.default.div`margin:16px 0;padding:0 ${te.HORIZONTAL_PADDING}px;position:relative;display:flex;align-self:stretch;gap:8px;${({$type:e})=>e==="vertical"?CE:bE};`,_E=C.default.button.attrs({type:"button"})`
|
|
296
296
|
all: unset;
|
|
297
297
|
box-sizing: border-box;
|
|
298
298
|
padding: 8px 12px;
|
|
@@ -312,59 +312,59 @@
|
|
|
312
312
|
|
|
313
313
|
${xe}
|
|
314
314
|
|
|
315
|
-
${({$type:e,theme:t})=>
|
|
316
|
-
`,EE=
|
|
315
|
+
${({$type:e,theme:t})=>G.css`${e==="vertical"?vE:yE};&:active{background-color:${t.colors.base.primary};color:${t.colors.base.primaryContrastContent};}`}
|
|
316
|
+
`,EE=C.default(H)`color:inherit;`,CE=G.css`flex-direction:column;align-items:flex-end;`,bE=G.css`flex-direction:row;overflow-x:scroll;-ms-overflow-style:none;scrollbar-width:none;&::-webkit-scrollbar{display:none;}`,vE=G.css`max-width:calc(100% - 70px);white-space:pre-wrap;`,yE=G.css`white-space:nowrap;`,SE=e=>{const{components:t}=_t.useContext(),{stringSet:n}=se(),r=ei(e)?a.createElement(t.TextMessageBody,{...e}):null;if(e.messageType==="user")return r;if(e.messageType==="file"){const s=e.file;return s.type.startsWith("image")||s.type.startsWith("video")?a.createElement(t.MediaMessageBody,{...e},r):a.createElement(t.FileMessageBody,{...e},r)}return e.messageType==="multipleFiles"?a.createElement(t.MultipleFilesMessageBody,{...e},r):a.createElement(t.TextMessageBody,{...e,message:n.UNKNOWN__UNKNOWN_MESSAGE_TYPE})},AE=e=>{var A,T,R,L,D;const{components:t}=_t.useContext(),{streamText:n,isAnimating:r}=pm({text:e.message,enabled:e.isStreaming,snapOnDisable:((A=e.extendedMessagePayload)==null?void 0:A.is_last_in_turn)!==!0,deferredMarkdownElements:e.deferredMarkdownElements,onAnimationStart:e.onStreamAnimationStart,onAnimationProgress:e.onStreamAnimationProgress,onAnimationComplete:e.onStreamAnimationComplete,onVisibleTextProgress:(T=e.statsCallbacks)==null?void 0:T.onVisibleTextProgress,onRenderedTextProgress:(R=e.statsCallbacks)==null?void 0:R.onRenderedTextProgress}),s={...e,message:n,extendedMessagePayload:r?{}:e.extendedMessagePayload},o=!!s.isTyping,i=!!s.isSenderAvatarVisible,c=kn(s.extendedMessagePayload),u=c.hasCTAButton,d=c.hasChallenge,m=c.hasCitations,h=c.hasForm,f=c.hasMessageTemplate,g=!!s.createdAt,_=u||m,y=s.groupType==="top"||s.groupType==="single",b=s.groupType==="bottom"||s.groupType==="single",p=i?te.AVATAR_SIZE:0,S=_&&a.createElement(l.Fragment,null,u&&a.createElement(IE,{$marginTop:12,$paddingInline:12},a.createElement(t.CTAButton,{...s})),m&&a.createElement(t.Citation,{...s}));return a.createElement(TE,{$marginBottom:o?0:Ln(s.groupType)},y&&a.createElement(xE,null,i&&a.createElement(t.SenderAvatar,{...s}),a.createElement(t.SenderName,{...s})),a.createElement(ME,null,a.createElement(or,{$extraStartPadding:p},o?a.createElement(t.TypingIndicator,{...s}):a.createElement(t.MessageBody,{...s},S)),f&&a.createElement(Mo,{$startPadding:0,$endPadding:0},a.createElement(t.MessageTemplate,{...s,messageTemplateErrorFallback:s.messageTemplateErrorFallback??a.createElement(or,{$extraStartPadding:p},a.createElement(t.MessageBody,{...s,messageType:"user",message:((D=(L=s.extendedMessagePayload)==null?void 0:L.message_template)==null?void 0:D.fallback_message)??"Cannot read this template."})),messageTemplateLoadingFallback:s.messageTemplateLoadingFallback??a.createElement(or,{$extraStartPadding:p},a.createElement(t.TypingIndicator,{...s}))})),a.createElement(t.CustomMessageTemplate,{...s}),d&&a.createElement(t.Challenge,{...s}),h&&a.createElement(Mo,{$extraStartPadding:p},a.createElement(t.Form,{...s}))),a.createElement(t.MessageLogs,{...s}),b&&g&&a.createElement(RE,{$extraStartPadding:p+8},a.createElement(t.SentTime,{...s})),a.createElement(l.Fragment,null,!o&&a.createElement(Qt,{$extraStartPadding:p+8},a.createElement(t.Feedback,{...s})),s.suggestedRepliesVisible&&a.createElement(t.SuggestedReplies,{...s})))},_t=je({template:AE,components:{SenderName:Vp,SenderAvatar:Gp,SentTime:Kp,MessageBody:SE,TextMessageBody:Pp,MediaMessageBody:vp,FileMessageBody:Ep,MultipleFilesMessageBody:Op,TypingIndicator:Wp,SuggestedReplies:gE,MessageTemplate:fE,CustomMessageTemplate:u_,Challenge:r_,CTAButton:e_,Citation:s_,Form:cE,Feedback:A_,MessageLogs:mE}}),TE=C.default.div.attrs({role:"presentation"})`
|
|
317
317
|
display: flex;
|
|
318
318
|
flex-direction: column;
|
|
319
319
|
align-items: flex-start;
|
|
320
320
|
margin-bottom: ${({$marginBottom:e})=>`${e}px`};
|
|
321
|
-
`,Qt=
|
|
321
|
+
`,Qt=C.default.div.attrs({role:"presentation"})`
|
|
322
322
|
display: flex;
|
|
323
323
|
align-self: stretch;
|
|
324
324
|
justify-content: flex-start;
|
|
325
|
-
${({$startPadding:e=
|
|
325
|
+
${({$startPadding:e=te.HORIZONTAL_PADDING,$endPadding:t=te.HORIZONTAL_PADDING,$extraStartPadding:n=0})=>`
|
|
326
326
|
padding-inline: ${e+n}px ${t}px;
|
|
327
327
|
`}
|
|
328
|
-
`,IE=
|
|
328
|
+
`,IE=C.default.div.attrs({role:"presentation"})`
|
|
329
329
|
display: flex;
|
|
330
330
|
flex-direction: column;
|
|
331
331
|
min-width: 0;
|
|
332
|
-
${({$marginTop:e=0,$paddingInline:t=0})=>
|
|
333
|
-
`,xE=
|
|
332
|
+
${({$marginTop:e=0,$paddingInline:t=0})=>G.css`margin-top:${e}px;padding-inline:${t}px;`}
|
|
333
|
+
`,xE=C.default(Qt)`display:flex;flex-direction:row;align-items:center;gap:8px;`,or=C.default(Qt)`display:flex;`,RE=C.default(Qt)`margin-top:${te.BODY_TIME_GAP}px;display:flex;align-items:flex-start;justify-content:flex-start;`,Mo=C.default(Qt).attrs({role:"presentation"})`
|
|
334
334
|
display: flex;
|
|
335
|
-
${({$startPadding:e=
|
|
335
|
+
${({$startPadding:e=te.HORIZONTAL_PADDING,$endPadding:t=te.HORIZONTAL_PADDING,$extraStartPadding:n=0})=>`
|
|
336
336
|
padding-inline: ${e+n}px ${t}px;
|
|
337
337
|
`}
|
|
338
|
-
`,ME=
|
|
338
|
+
`,ME=C.default.div.attrs({role:"presentation"})`
|
|
339
339
|
display: flex;
|
|
340
340
|
flex-direction: column;
|
|
341
341
|
min-width: 0;
|
|
342
342
|
max-width: 100%;
|
|
343
|
-
gap: ${
|
|
344
|
-
`;function wE({file:e,children:t,onClickFile:n,sendingStatus:r}){const s=(()=>{if(!(!n||r==="failed"))return()=>n==null?void 0:n(e)})();return a.createElement(kE,null,a.createElement(Zr,{name:e.name,mimeType:e.type,type:Ir(e.name,e.type),onClick:s}),t)}const kE=
|
|
343
|
+
gap: ${te.GAP_GROUPED}px;
|
|
344
|
+
`;function wE({file:e,children:t,onClickFile:n,sendingStatus:r}){const s=(()=>{if(!(!n||r==="failed"))return()=>n==null?void 0:n(e)})();return a.createElement(kE,null,a.createElement(Zr,{name:e.name,mimeType:e.type,type:Ir(e.name,e.type),onClick:s}),t)}const kE=C.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${te.GAP_GROUPED}px;`;function LE({sendingStatus:e,file:t,metadata:n,onClickMedia:r,onClickMediaFiles:s,children:o}){const{conversation:i}=re(),{aspectRatio:c,localFile:u}=n,[d]=l.useState(()=>u instanceof Blob?URL.createObjectURL(u):t.url),[m,h]=l.useState(!1),f=(()=>{if(e!=="failed"){if(s)return()=>s({files:[{url:d,type:t.type,name:t.name}],index:0});if(r)return()=>r({...t,url:d})}})(),g=f?i.file.buttonLikePreview({name:t.name,mimeType:t.type,onActivate:f}):i.file.preview({name:t.name,mimeType:t.type}),_={...g.props,$ratio:c,$clickable:!!f};return a.createElement(OE,null,a.createElement(NE,{..._},!m&&a.createElement(pt,{size:26},a.createElement(J,{type:"spinner",color:"textLowEmphasis",size:26})),a.createElement(DE,{$loaded:m,src:d,alt:"image-message",onLoad:()=>h(!0)}),g.descriptionNode),o)}const OE=C.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${te.GAP_GROUPED}px;`,NE=C.default.div`width:${te.BODY_MAX_WIDTH}px;border-radius:12px;overflow:hidden;cursor:${e=>e.$clickable?"pointer":"default"};height:auto;aspect-ratio:${e=>e.$ratio};position:relative;display:flex;align-items:center;justify-content:center;${Q.light`
|
|
345
345
|
background-color: ${E.color.background100};
|
|
346
346
|
`}
|
|
347
347
|
${Q.dark`
|
|
348
348
|
background-color: ${E.color.background400};
|
|
349
349
|
`}
|
|
350
|
-
`,DE=
|
|
350
|
+
`,DE=C.default.img`position:absolute;width:100%;height:100%;inset-block-start:0;inset-inline-start:0;object-fit:cover;opacity:${e=>e.$loaded?1:0};transition:opacity 0.5s ease;`,$E=({sendingStatus:e,files:t,metadata:n,onClickMedia:r,onClickMediaFiles:s,children:o})=>{const[i]=l.useState(()=>n.localFiles?n.localFiles.filter(m=>m instanceof Blob).map(m=>({...m,url:URL.createObjectURL(m)})):t),c=e==="pending",u=e==="failed",d=m=>{if(u||c)return;const h=i[m];h&&(s?s({files:i,index:m}):r&&r({url:h.url,type:h.type||"image/*"}))};return a.createElement(FE,null,a.createElement(va,{images:i,isPending:c,onClickImage:d}),o)},FE=C.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${te.GAP_GROUPED}px;`;function PE(e){var n,r;const t=l.useMemo(()=>{const s=$p(Sa(e.message));return Ko.default.sanitize(s)},[e.message]);return a.createElement(UE,{$maxWidth:e.maxBodyWidth??te.BODY_MAX_WIDTH,$color:(n=e.customStyle)==null?void 0:n.bubbleContentColor,$bgColor:(r=e.customStyle)==null?void 0:r.bubbleBackgroundColor},a.createElement(BE,{variant:"body3",dangerouslySetInnerHTML:{__html:t}}))}const UE=C.default.div`display:flex;flex-direction:column;border-radius:12px;overflow:hidden;max-width:${({$maxWidth:e})=>e}px;${({theme:e,$color:t,$bgColor:n})=>G.css`
|
|
351
351
|
color: ${t||e.colors.messageOutgoing.text};
|
|
352
352
|
background-color: ${n||e.colors.messageOutgoing.background};
|
|
353
353
|
`}
|
|
354
354
|
padding: 12px 0;
|
|
355
355
|
transition: max-width 0.3s;
|
|
356
356
|
overflow-wrap: break-word;
|
|
357
|
-
`,BE=
|
|
358
|
-
`,Da=
|
|
359
|
-
`,WE=b.default(Da)``,jE=b.default(Da)`margin-top:${ee.BODY_TIME_GAP}px;`,XE=e=>e.messageType!=="admin"?null:a.createElement(ZE,null,a.createElement(U,{variant:"caption2",color:E.themedColor.textMidEmphasis},JE(Ko.default.sanitize(e.message),e.onClickLink))),ZE=b.default.div`text-align:center;text-wrap:pretty;word-break:break-word;padding-inline:${ee.HORIZONTAL_PADDING}px;a{text-decoration:underline;color:inherit;}`,JE=(e,t)=>{try{const n=[];let r=e,s=0;for(;r;){const o=r.match(/\[([^\]]+)\]\((https?:\/\/[^\s]+)\)/),i=r.match(/\*\*([^*]+)\*\*/),c=[o&&{match:o,type:"link"},i&&{match:i,type:"bold"}].filter(f=>!!f);if(!c.length){n.push(r);break}const u=c.reduce((f,g)=>g.match.index<f.match.index?g:f),{match:d,type:m}=u,h=d.index;h>0&&n.push(r.slice(0,h)),m==="link"?n.push(a.createElement("a",{key:s++,href:d[2],target:"_blank",rel:zr,onClick:f=>{f.preventDefault();const g=d[2];g&&(t==null||t({url:g}))}},d[1])):m==="bold"&&n.push(a.createElement("strong",{key:s++},d[1])),r=r.slice(h+d[0].length)}return n.filter(o=>o!=="")}catch{return[e]}},QE=({direction:e,currentIndex:t,totalCount:n})=>n<=0?t:e==="next"?(t+1)%n:(t-1+n)%n,$a=({options:e,value:t,disabled:n,hasError:r=!1,errorId:s,onChange:o})=>{const i=l.useRef([]),c=e.findIndex(h=>h.value===t),u=c>=0?c:0,d=h=>{requestAnimationFrame(()=>{var f;(f=i.current[h])==null||f.focus()})},m=h=>{const f=e[h];!f||n||(o==null||o(f.value),d(h))};return{radioGroupProps:h=>({role:"radiogroup","aria-label":h,...r&&s?{"aria-invalid":!0,"aria-errormessage":s}:{}}),getRadioProps:h=>({ref:f=>{i.current[h]=f},tabIndex:n?-1:h===u?0:-1,describedBy:r&&s?s:void 0,onArrowNavigate:f=>{m(QE({direction:f,currentIndex:h,totalCount:e.length}))}})}},eC=e=>{switch(e.key){case"ArrowDown":case"ArrowRight":return"next";case"ArrowUp":case"ArrowLeft":return"previous";default:return}},tC=({event:e,onClick:t,onArrowNavigate:n})=>{if(nC(e))return;const r=eC(e);if(r){e.preventDefault(),n==null||n(r);return}e.key!=="Enter"&&e.key!==" "||(e.preventDefault(),t==null||t())},nC=e=>e.repeat||e.currentTarget.getAttribute("aria-disabled")==="true",es=l.forwardRef(({onClick:e,checked:t,label:n,disabled:r,tabIndex:s=0,labelVariant:o="caption2",describedBy:i,onArrowNavigate:c},u)=>{const d=t?E.themedColor.primary:r?E.themedColor.textDisabled:E.themedColor.textLowEmphasis,m=t?E.themedColor.textHighEmphasis:r?E.themedColor.textLowEmphasis:E.themedColor.textHighEmphasis;return a.createElement(oC,{ref:u,role:"radio",tabIndex:r?-1:s,"aria-checked":t,"aria-disabled":!!r,"aria-label":n,"aria-describedby":i,onClick:r?void 0:e,onKeyDown:h=>tC({event:h,onClick:e,onArrowNavigate:c})},a.createElement(rC,{"aria-hidden":"true"},a.createElement(J,{size:20,type:t?"radio-on":"radio-off",color:d})),a.createElement(sC,{"aria-hidden":"true",variant:o,color:m},n))});es.displayName="Radio";const rC=b.default.div`width:20px;height:20px;`,sC=b.default(U)`line-height:20px;word-break:break-word;`,oC=b.default.div`display:flex;align-items:flex-start;justify-content:flex-start;gap:2px;${xe}&[aria-disabled='false']{cursor:pointer;}`,iC=({csatPayload:e,submitted:t,defaultValue:n,value:r,onChange:s})=>{var u,d;const o=[{label:((u=e.cre)==null?void 0:u.positive_label)??"",value:!0},{label:((d=e.cre)==null?void 0:d.negative_label)??"",value:!1}],i=$a({options:o,value:r,disabled:t,onChange:s});if(l.useEffect(()=>{typeof r>"u"&&typeof n=="boolean"&&(s==null||s(n))},[r,n]),!e.cre)return null;const c=e.cre;return a.createElement(aC,null,a.createElement(Oe.Label,{required:c.required,"aria-hidden":!0},c.question),a.createElement(cC,{...i.radioGroupProps(c.question)},o.map((m,h)=>a.createElement(es,{key:m.label,checked:r===m.value,label:m.label,disabled:t,...i.getRadioProps(h),onClick:()=>s==null?void 0:s(m.value)}))))},aC=b.default.div`display:flex;flex-direction:column;gap:8px;`,cC=b.default.div`display:flex;flex-direction:column;gap:8px;`,lC=({followUpItem:e,submitted:t,value:n="",onChange:r,hasError:s})=>{const{stringSet:o}=se(),{conversation:i}=re(),c=l.useId(),u=l.useId(),d=e.response_type!=="free_text",m=e.response_type==="single_choice"?e.options.map(f=>({label:f,value:f})):[],h=$a({options:m,value:n,disabled:t,hasError:s,errorId:c,onChange:r});return a.createElement(uC,null,a.createElement(Oe.Label,{id:u,required:e.required,"aria-hidden":d},e.question),e.response_type==="free_text"&&a.createElement(Oe.TextInput,{variant:"multi-line",disabled:t,submitted:t,maxLength:100,value:n,onChange:f=>r(f),error:s,...i.form.textInput(o.A11Y_CSAT_TEXT_INPUT_LABEL,e.required??!1,t,{labelId:u}).props,"aria-invalid":s,"aria-errormessage":s?c:void 0}),e.response_type==="single_choice"&&a.createElement(dC,{...h.radioGroupProps(e.question)},m.map((f,g)=>a.createElement(es,{key:f.value,checked:n===f.value,label:f.label,disabled:t,...h.getRadioProps(g),onClick:()=>r==null?void 0:r(f.value),labelVariant:"body3"}))),s&&a.createElement(mC,{role:"alert",id:c},o.FORM_VALIDATION_REQUIRED))},uC=b.default.div`display:flex;flex-direction:column;gap:8px;`,dC=b.default.div`display:flex;flex-direction:column;gap:8px;`,mC=b.default(Oe.ErrorLabel)``,hC=({value:e,selected:t})=>a.createElement(fC,{$selected:t,"aria-hidden":"true"},gC[e-1]),fC=b.default.div`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,gC=[a.createElement("svg",{width:"40",height:"40",viewBox:"0 0 40 40",fill:"none",xmlns:"http://www.w3.org/2000/svg"},a.createElement("path",{d:"M2.08337 19.9999C2.08337 10.1048 10.1049 2.08325 20 2.08325C29.8952 2.08325 37.9167 10.1048 37.9167 19.9999C37.9167 29.8951 29.8952 37.9166 20 37.9166C10.1049 37.9166 2.08337 29.8951 2.08337 19.9999Z",fill:"url(#paint0_linear_159_173206)"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M12.5828 29.3328C13.1348 29.7473 13.9184 29.636 14.3329 29.084C15.6272 27.3607 17.6839 26.25 20 26.25C22.3164 26.25 24.373 27.3607 25.6672 29.084C26.0819 29.636 26.8654 29.7473 27.4175 29.3328C27.9695 28.9182 28.0809 28.1347 27.6662 27.5825C25.9202 25.2577 23.136 23.75 20 23.75C16.8642 23.75 14.0801 25.2577 12.334 27.5825C11.9194 28.1347 12.0308 28.9182 12.5828 29.3328Z",fill:"#141B34"}),a.createElement("path",{d:"M28.4454 13.7707C29.1329 13.8328 29.6405 14.4406 29.5785 15.1281C29.5165 15.8153 28.9095 16.3221 28.2224 16.2608C28.2224 16.2608 28.0287 16.2502 27.9272 16.2487C27.7229 16.2457 27.4387 16.2509 27.1229 16.2833C26.7869 16.3177 26.4649 16.3782 26.1804 16.4662L26.3045 16.86C26.7797 18.3675 25.5099 19.5813 24.2062 19.5813C23.5045 19.5813 22.8324 19.2617 22.43 18.6857C22.003 18.0745 21.9422 17.241 22.408 16.5344C22.751 16.0143 23.2449 15.3831 23.8964 14.8657C24.836 14.1195 26.044 13.8809 26.8675 13.7963C27.3029 13.7517 28.0154 13.7319 28.4454 13.7707Z",fill:"#141B34"}),a.createElement("path",{d:"M11.5549 13.7707C10.8674 13.8328 10.3597 14.4406 10.4218 15.1281C10.4838 15.8153 11.0908 16.3221 11.7779 16.2608C11.7779 16.2608 11.9716 16.2502 12.073 16.2487C12.2774 16.2457 12.5616 16.2509 12.8774 16.2833C13.2134 16.3177 13.5353 16.3782 13.8199 16.4662L13.6958 16.86C13.2205 18.3675 14.4904 19.5813 15.794 19.5813C16.4958 19.5813 17.168 19.2617 17.5703 18.6857C17.9971 18.0745 18.0581 17.241 17.5921 16.5344C17.2493 16.0143 16.7553 15.3831 16.1039 14.8657C15.1643 14.1195 13.9562 13.8809 13.1327 13.7963C12.6974 13.7517 11.9849 13.7319 11.5549 13.7707Z",fill:"#141B34"}),a.createElement("defs",null,a.createElement("linearGradient",{id:"paint0_linear_159_173206",x1:"20",y1:"2.08325",x2:"20",y2:"37.9166",gradientUnits:"userSpaceOnUse"},a.createElement("stop",{stopColor:"#FF2D1D"}),a.createElement("stop",{offset:"1",stopColor:"#FFA540"})))),a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},a.createElement("path",{d:"M2.083 20C2.083 10.105 10.105 2.083 20 2.083c9.895 0 17.917 8.021 17.917 17.917 0 9.895-8.022 17.917-17.917 17.917C10.105 37.917 2.083 29.895 2.083 20Z",fill:"#FFD46E"}),a.createElement("path",{d:"M14.249 27.334C15.851 26.13 17.844 25.417 20 25.417c2.156 0 4.149.714 5.751 1.917.553.415.664 1.199.25 1.751-.415.552-1.199.664-1.751.25-1.183-.889-2.652-1.416-4.25-1.416s-3.067.527-4.25 1.416c-.553.414-1.336.302-1.751-.25-.415-.552-.303-1.336.249-1.751Z",fill:"#141B34"}),a.createElement("path",{d:"M23.445 14.596c-.687.062-1.294-.445-1.356-1.132-.062-.687.445-1.295 1.132-1.357.082-.005.342-.02.482-.022.277-.004.662.002 1.097.047.823.085 2.031.323 2.97 1.07.652.518 1.146 1.15 1.489 1.67.466.706.405 1.54-.022 2.15-.402.576-1.074.896-1.775.896-1.304 0-2.573-1.214-2.098-2.722l.125-.394c-.285-.088-.607-.148-.942-.182-.316-.033-.6-.038-.804-.035-.101.002-.242.01-.294.013Z",fill:"#141B34"}),a.createElement("path",{d:"M11.779 14.596c-.687.062-1.294-.445-1.356-1.132-.062-.687.445-1.295 1.132-1.357.082-.005.342-.02.482-.022.277-.004.662.002 1.097.047.823.085 2.031.323 2.97 1.07.652.518 1.146 1.15 1.489 1.67.466.706.405 1.54-.022 2.15-.402.576-1.074.896-1.775.896-1.304 0-2.573-1.214-2.098-2.722l.124-.394c-.284-.088-.606-.148-.941-.182-.316-.033-.6-.038-.804-.035-.101.002-.243.01-.294.013Z",fill:"#141B34"})),a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},a.createElement("path",{d:"M2.083 20C2.083 10.105 10.105 2.083 20 2.083c9.895 0 17.917 8.021 17.917 17.917 0 9.895-8.022 17.917-17.917 17.917C10.105 37.917 2.083 29.895 2.083 20Z",fill:"#FFD46E"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M11.25 15c0-1.151.933-2.083 2.083-2.083h.015c1.151 0 2.084.933 2.084 2.083 0 1.151-.933 2.083-2.084 2.083h-.015c-1.15 0-2.083-.933-2.083-2.083ZM24.568 15c0-1.151.933-2.083 2.084-2.083h.015c1.151 0 2.083.933 2.083 2.083 0 1.151-.932 2.083-2.083 2.083h-.015c-1.151 0-2.084-.933-2.084-2.083Z",fill:"#141B34"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M13.75 26.667c0-.691.56-1.25 1.25-1.25h10c.69 0 1.25.559 1.25 1.25 0 .691-.56 1.25-1.25 1.25h-10c-.69 0-1.25-.559-1.25-1.25Z",fill:"#141B34"})),a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},a.createElement("path",{d:"M2.083 20C2.083 10.105 10.105 2.083 20 2.083c9.895 0 17.917 8.021 17.917 17.917 0 9.895-8.022 17.917-17.917 17.917C10.105 37.917 2.083 29.895 2.083 20Z",fill:"#FFD46E"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M12.583 24.001c.552-.414 1.335-.302 1.75.25 1.294 1.723 3.35 2.834 5.667 2.834s4.373-1.11 5.667-2.834c.415-.552 1.199-.664 1.751-.25.552.415.664 1.199.25 1.751C25.92 28.076 23.136 29.584 20 29.584s-5.92-1.508-7.666-3.832c-.415-.552-.303-1.336.249-1.751Z",fill:"#141B34"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M11.25 15c0-1.151.933-2.083 2.083-2.083h.015c1.151 0 2.084.933 2.084 2.083 0 1.151-.933 2.083-2.084 2.083h-.015c-1.15 0-2.083-.933-2.083-2.083ZM24.568 15c0-1.151.933-2.083 2.084-2.083h.015c1.151 0 2.083.933 2.083 2.083 0 1.151-.932 2.083-2.083 2.083h-.015c-1.151 0-2.084-.933-2.084-2.083Z",fill:"#141B34"})),a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},a.createElement("path",{d:"M2.083 20C2.083 10.105 10.105 2.083 20 2.083c9.895 0 17.917 8.021 17.917 17.917 0 9.895-8.022 17.917-17.917 17.917C10.105 37.917 2.083 29.895 2.083 20Z",fill:"#FFD46E"}),a.createElement("g",{clipPath:"url(#clip0_159_173224)"},a.createElement("g",{clipPath:"url(#clip1_159_173224)"},a.createElement("path",{d:"M20 30.624c3.752 0 6.904-2.532 7.789-5.956.412-1.593-.185-1.959-1.76-1.959H13.973c-1.575 0-2.173.366-1.761 1.959.885 3.424 4.037 5.956 7.788 5.956Z",fill:"#141B34"})),a.createElement("mask",{id:"mask0_159_173224",style:{maskType:"alpha"},maskUnits:"userSpaceOnUse",x:"12",y:"22",width:"16",height:"9"},a.createElement("path",{d:"M20 30.624c3.752 0 6.904-2.532 7.789-5.956.412-1.593-.185-1.959-1.76-1.959H13.973c-1.575 0-2.173.366-1.761 1.959.885 3.424 4.037 5.956 7.788 5.956Z",fill:"#141B34"})),a.createElement("g",{mask:"url(#mask0_159_173224)"},a.createElement("path",{d:"M20 32.998c3.278 0 5.936-1.594 5.936-3.561 0-1.968-2.658-3.562-5.936-3.562-3.278 0-5.936 1.594-5.936 3.562 0 1.967 2.658 3.561 5.936 3.561Z",fill:"#FF493B"}))),a.createElement("path",{d:"M11.667 15.833c0-1.381 1.12-2.5 2.5-2.5s2.5 1.12 2.5 2.5M23.333 15.833c0-1.381 1.12-2.5 2.5-2.5s2.5 1.12 2.5 2.5",stroke:"#141B34",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"}),a.createElement("defs",null,a.createElement("clipPath",{id:"clip0_159_173224"},a.createElement("rect",{width:"15.83",height:"7.915",fill:"white",transform:"translate(12.085 22.709)"})),a.createElement("clipPath",{id:"clip1_159_173224"},a.createElement("rect",{width:"15.83",height:"7.915",fill:"white",transform:"translate(12.085 22.709)"}))))],pC=({csatPayload:e,submitted:t,value:n,onChange:r})=>{const s=typeof n>"u",{conversation:o}=re(),i=o.csat.scoresContainer(e.csat_question);return a.createElement(EC,null,a.createElement(U,{variant:"caption3",color:E.themedColor.textMidEmphasis,"aria-hidden":"true"},e.csat_question),a.createElement(CC,{...i.props},i.descriptionNode,e.csat_scores.map(({label:c,image_url:u},d)=>{const m=d+1,h=n===m,f=e.csat_scores.length,g=o.csat.scoreItem({score:m,label:c,selected:h,disabled:t,currentIndex:d,totalCount:f,hasSelection:!s,onChange:r});return a.createElement(bC,{key:d,type:"button",...g.props},a.createElement(_C,{value:m,selected:s||h,src:u}),!!c&&a.createElement(U,{"aria-hidden":"true",color:h?E.themedColor.textHighEmphasis:E.themedColor.textLowEmphasis,variant:"caption3"},c),g.descriptionNode)})))},_C=({value:e,src:t,selected:n})=>{const[r,s]=l.useState(!1),o=r?a.createElement(hC,{value:e,selected:n}):a.createElement(yC,{$selected:n,alt:"","aria-hidden":"true",src:t,onError:()=>s(!0)});return a.createElement(vC,null,o)},EC=b.default.div`display:flex;flex-direction:column;gap:8px;`,CC=b.default.div`display:flex;justify-content:space-between;align-self:center;width:100%;max-width:400px;gap:16px;`,bC=b.default.button`appearance:none;-webkit-appearance:none;background-color:transparent;border:none;padding:0;text-align:center;gap:4px;display:flex;flex-direction:column;align-items:center;justify-content:start;box-sizing:border-box;min-width:48px;max-width:68px;${xe}&:not(:disabled):hover span{color:${E.themedColor.textHighEmphasis};}`,vC=b.default.div`button:not(:disabled):hover &{border-radius:4px;cursor:pointer;background-color:${E.color.background200};${Q.dark`
|
|
357
|
+
`,BE=C.default(H)`align-items:flex-start;line-height:140%;white-space:pre-wrap;padding:0 12px;`,HE=({sendingStatus:e})=>{const t=G.useTheme();switch(e){case"pending":return a.createElement(GE,{size:16},a.createElement(J,{type:"spinner",color:t.colors.messageOutgoing.background,size:16}));case"failed":return a.createElement("div",{style:{marginBottom:2}},a.createElement(J,{type:"error",color:E.themedColor.error,size:16}));case"scheduled":case"canceled":return null;default:return a.createElement("div",{style:{marginBottom:2}},a.createElement(J,{type:"done",color:E.themedColor.secondary,size:16}))}},GE=C.default(pt)`margin-bottom:2px;width:16px;height:16px;`,zE=({createdAt:e})=>{const{stringSet:t,format:n}=se();return e?a.createElement(H,{variant:"caption4",color:E.themedColor.textLowEmphasis},n(e,t.DATE_FORMAT__MESSAGE_TIMESTAMP)):null},VE=e=>{const{components:t}=xt.useContext(),{stringSet:n}=se(),r=()=>{const i=ei(e)?a.createElement(t.TextMessageBody,{...e}):null;return e.messageType==="user"?i:e.messageType==="file"?e.file.type.startsWith("image")?a.createElement(t.MediaMessageBody,{...e},i):a.createElement(t.FileMessageBody,{...e},i):e.messageType==="multipleFiles"?a.createElement(t.MultipleFilesMessageBody,{...e},i):a.createElement(t.TextMessageBody,{...e,message:n.UNKNOWN__UNKNOWN_MESSAGE_TYPE})},s=e.sendingStatus==="failed"&&e.onClickFailedMessage,o=s?$t({onActivate:()=>{var i;return(i=e.onClickFailedMessage)==null?void 0:i.call(e)}}):{};return a.createElement("div",{...o,style:{display:"contents",cursor:s?"pointer":"default"}},r())},qE=e=>a.createElement(a.Fragment,null),KE=e=>{const{components:t}=xt.useContext(),n=e.sendingStatus==="succeeded",r=e.groupType==="bottom"||e.groupType==="single";return a.createElement(YE,{$marginBottom:Ln(e.groupType)},a.createElement(WE,null,a.createElement(t.MessageBody,{...e})),a.createElement(t.MessageLogs,{...e}),r&&a.createElement(jE,{$extraEndPadding:8},n?a.createElement(t.SentTime,{...e}):a.createElement(t.SendingStatus,{...e})))},xt=je({template:KE,components:{SendingStatus:HE,SentTime:zE,MessageBody:VE,TextMessageBody:PE,MediaMessageBody:LE,FileMessageBody:wE,MultipleFilesMessageBody:$E,MessageLogs:qE}}),YE=C.default.div`display:flex;flex:1;flex-direction:column;align-items:flex-end;margin-bottom:${({$marginBottom:e})=>`${e}px`};
|
|
358
|
+
`,Da=C.default.div`display:flex;align-self:stretch;justify-content:flex-end;${({$startPadding:e=te.HORIZONTAL_PADDING,$endPadding:t=te.HORIZONTAL_PADDING,$extraEndPadding:n=0})=>`padding-inline: ${e}px ${t+n}px;`};
|
|
359
|
+
`,WE=C.default(Da)``,jE=C.default(Da)`margin-top:${te.BODY_TIME_GAP}px;`,XE=e=>e.messageType!=="admin"?null:a.createElement(ZE,null,a.createElement(H,{variant:"caption2",color:E.themedColor.textMidEmphasis},JE(Ko.default.sanitize(e.message),e.onClickLink))),ZE=C.default.div`text-align:center;text-wrap:pretty;word-break:break-word;padding-inline:${te.HORIZONTAL_PADDING}px;a{text-decoration:underline;color:inherit;}`,JE=(e,t)=>{try{const n=[];let r=e,s=0;for(;r;){const o=r.match(/\[([^\]]+)\]\((https?:\/\/[^\s]+)\)/),i=r.match(/\*\*([^*]+)\*\*/),c=[o&&{match:o,type:"link"},i&&{match:i,type:"bold"}].filter(f=>!!f);if(!c.length){n.push(r);break}const u=c.reduce((f,g)=>g.match.index<f.match.index?g:f),{match:d,type:m}=u,h=d.index;h>0&&n.push(r.slice(0,h)),m==="link"?n.push(a.createElement("a",{key:s++,href:d[2],target:"_blank",rel:zr,onClick:f=>{f.preventDefault();const g=d[2];g&&(t==null||t({url:g}))}},d[1])):m==="bold"&&n.push(a.createElement("strong",{key:s++},d[1])),r=r.slice(h+d[0].length)}return n.filter(o=>o!=="")}catch{return[e]}},QE=({direction:e,currentIndex:t,totalCount:n})=>n<=0?t:e==="next"?(t+1)%n:(t-1+n)%n,$a=({options:e,value:t,disabled:n,hasError:r=!1,errorId:s,onChange:o})=>{const i=l.useRef([]),c=e.findIndex(h=>h.value===t),u=c>=0?c:0,d=h=>{requestAnimationFrame(()=>{var f;(f=i.current[h])==null||f.focus()})},m=h=>{const f=e[h];!f||n||(o==null||o(f.value),d(h))};return{radioGroupProps:h=>({role:"radiogroup","aria-label":h,...r&&s?{"aria-invalid":!0,"aria-errormessage":s}:{}}),getRadioProps:h=>({ref:f=>{i.current[h]=f},tabIndex:n?-1:h===u?0:-1,describedBy:r&&s?s:void 0,onArrowNavigate:f=>{m(QE({direction:f,currentIndex:h,totalCount:e.length}))}})}},eC=e=>{switch(e.key){case"ArrowDown":case"ArrowRight":return"next";case"ArrowUp":case"ArrowLeft":return"previous";default:return}},tC=({event:e,onClick:t,onArrowNavigate:n})=>{if(nC(e))return;const r=eC(e);if(r){e.preventDefault(),n==null||n(r);return}e.key!=="Enter"&&e.key!==" "||(e.preventDefault(),t==null||t())},nC=e=>e.repeat||e.currentTarget.getAttribute("aria-disabled")==="true",es=l.forwardRef(({onClick:e,checked:t,label:n,disabled:r,tabIndex:s=0,labelVariant:o="caption2",describedBy:i,onArrowNavigate:c},u)=>{const d=t?E.themedColor.primary:r?E.themedColor.textDisabled:E.themedColor.textLowEmphasis,m=t?E.themedColor.textHighEmphasis:r?E.themedColor.textLowEmphasis:E.themedColor.textHighEmphasis;return a.createElement(oC,{ref:u,role:"radio",tabIndex:r?-1:s,"aria-checked":t,"aria-disabled":!!r,"aria-label":n,"aria-describedby":i,onClick:r?void 0:e,onKeyDown:h=>tC({event:h,onClick:e,onArrowNavigate:c})},a.createElement(rC,{"aria-hidden":"true"},a.createElement(J,{size:20,type:t?"radio-on":"radio-off",color:d})),a.createElement(sC,{"aria-hidden":"true",variant:o,color:m},n))});es.displayName="Radio";const rC=C.default.div`width:20px;height:20px;`,sC=C.default(H)`line-height:20px;word-break:break-word;`,oC=C.default.div`display:flex;align-items:flex-start;justify-content:flex-start;gap:2px;${xe}&[aria-disabled='false']{cursor:pointer;}`,iC=({csatPayload:e,submitted:t,defaultValue:n,value:r,onChange:s})=>{var u,d;const o=[{label:((u=e.cre)==null?void 0:u.positive_label)??"",value:!0},{label:((d=e.cre)==null?void 0:d.negative_label)??"",value:!1}],i=$a({options:o,value:r,disabled:t,onChange:s});if(l.useEffect(()=>{typeof r>"u"&&typeof n=="boolean"&&(s==null||s(n))},[r,n]),!e.cre)return null;const c=e.cre;return a.createElement(aC,null,a.createElement(Le.Label,{required:c.required,"aria-hidden":!0},c.question),a.createElement(cC,{...i.radioGroupProps(c.question)},o.map((m,h)=>a.createElement(es,{key:m.label,checked:r===m.value,label:m.label,disabled:t,...i.getRadioProps(h),onClick:()=>s==null?void 0:s(m.value)}))))},aC=C.default.div`display:flex;flex-direction:column;gap:8px;`,cC=C.default.div`display:flex;flex-direction:column;gap:8px;`,lC=({followUpItem:e,submitted:t,value:n="",onChange:r,hasError:s})=>{const{stringSet:o}=se(),{conversation:i}=re(),c=l.useId(),u=l.useId(),d=e.response_type!=="free_text",m=e.response_type==="single_choice"?e.options.map(f=>({label:f,value:f})):[],h=$a({options:m,value:n,disabled:t,hasError:s,errorId:c,onChange:r});return a.createElement(uC,null,a.createElement(Le.Label,{id:u,required:e.required,"aria-hidden":d},e.question),e.response_type==="free_text"&&a.createElement(Le.TextInput,{variant:"multi-line",disabled:t,submitted:t,maxLength:100,value:n,onChange:f=>r(f),error:s,...i.form.textInput(o.A11Y_CSAT_TEXT_INPUT_LABEL,e.required??!1,t,{labelId:u}).props,"aria-invalid":s,"aria-errormessage":s?c:void 0}),e.response_type==="single_choice"&&a.createElement(dC,{...h.radioGroupProps(e.question)},m.map((f,g)=>a.createElement(es,{key:f.value,checked:n===f.value,label:f.label,disabled:t,...h.getRadioProps(g),onClick:()=>r==null?void 0:r(f.value),labelVariant:"body3"}))),s&&a.createElement(mC,{role:"alert",id:c},o.FORM_VALIDATION_REQUIRED))},uC=C.default.div`display:flex;flex-direction:column;gap:8px;`,dC=C.default.div`display:flex;flex-direction:column;gap:8px;`,mC=C.default(Le.ErrorLabel)``,hC=({value:e,selected:t})=>a.createElement(fC,{$selected:t,"aria-hidden":"true"},gC[e-1]),fC=C.default.div`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,gC=[a.createElement("svg",{width:"40",height:"40",viewBox:"0 0 40 40",fill:"none",xmlns:"http://www.w3.org/2000/svg"},a.createElement("path",{d:"M2.08337 19.9999C2.08337 10.1048 10.1049 2.08325 20 2.08325C29.8952 2.08325 37.9167 10.1048 37.9167 19.9999C37.9167 29.8951 29.8952 37.9166 20 37.9166C10.1049 37.9166 2.08337 29.8951 2.08337 19.9999Z",fill:"url(#paint0_linear_159_173206)"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M12.5828 29.3328C13.1348 29.7473 13.9184 29.636 14.3329 29.084C15.6272 27.3607 17.6839 26.25 20 26.25C22.3164 26.25 24.373 27.3607 25.6672 29.084C26.0819 29.636 26.8654 29.7473 27.4175 29.3328C27.9695 28.9182 28.0809 28.1347 27.6662 27.5825C25.9202 25.2577 23.136 23.75 20 23.75C16.8642 23.75 14.0801 25.2577 12.334 27.5825C11.9194 28.1347 12.0308 28.9182 12.5828 29.3328Z",fill:"#141B34"}),a.createElement("path",{d:"M28.4454 13.7707C29.1329 13.8328 29.6405 14.4406 29.5785 15.1281C29.5165 15.8153 28.9095 16.3221 28.2224 16.2608C28.2224 16.2608 28.0287 16.2502 27.9272 16.2487C27.7229 16.2457 27.4387 16.2509 27.1229 16.2833C26.7869 16.3177 26.4649 16.3782 26.1804 16.4662L26.3045 16.86C26.7797 18.3675 25.5099 19.5813 24.2062 19.5813C23.5045 19.5813 22.8324 19.2617 22.43 18.6857C22.003 18.0745 21.9422 17.241 22.408 16.5344C22.751 16.0143 23.2449 15.3831 23.8964 14.8657C24.836 14.1195 26.044 13.8809 26.8675 13.7963C27.3029 13.7517 28.0154 13.7319 28.4454 13.7707Z",fill:"#141B34"}),a.createElement("path",{d:"M11.5549 13.7707C10.8674 13.8328 10.3597 14.4406 10.4218 15.1281C10.4838 15.8153 11.0908 16.3221 11.7779 16.2608C11.7779 16.2608 11.9716 16.2502 12.073 16.2487C12.2774 16.2457 12.5616 16.2509 12.8774 16.2833C13.2134 16.3177 13.5353 16.3782 13.8199 16.4662L13.6958 16.86C13.2205 18.3675 14.4904 19.5813 15.794 19.5813C16.4958 19.5813 17.168 19.2617 17.5703 18.6857C17.9971 18.0745 18.0581 17.241 17.5921 16.5344C17.2493 16.0143 16.7553 15.3831 16.1039 14.8657C15.1643 14.1195 13.9562 13.8809 13.1327 13.7963C12.6974 13.7517 11.9849 13.7319 11.5549 13.7707Z",fill:"#141B34"}),a.createElement("defs",null,a.createElement("linearGradient",{id:"paint0_linear_159_173206",x1:"20",y1:"2.08325",x2:"20",y2:"37.9166",gradientUnits:"userSpaceOnUse"},a.createElement("stop",{stopColor:"#FF2D1D"}),a.createElement("stop",{offset:"1",stopColor:"#FFA540"})))),a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},a.createElement("path",{d:"M2.083 20C2.083 10.105 10.105 2.083 20 2.083c9.895 0 17.917 8.021 17.917 17.917 0 9.895-8.022 17.917-17.917 17.917C10.105 37.917 2.083 29.895 2.083 20Z",fill:"#FFD46E"}),a.createElement("path",{d:"M14.249 27.334C15.851 26.13 17.844 25.417 20 25.417c2.156 0 4.149.714 5.751 1.917.553.415.664 1.199.25 1.751-.415.552-1.199.664-1.751.25-1.183-.889-2.652-1.416-4.25-1.416s-3.067.527-4.25 1.416c-.553.414-1.336.302-1.751-.25-.415-.552-.303-1.336.249-1.751Z",fill:"#141B34"}),a.createElement("path",{d:"M23.445 14.596c-.687.062-1.294-.445-1.356-1.132-.062-.687.445-1.295 1.132-1.357.082-.005.342-.02.482-.022.277-.004.662.002 1.097.047.823.085 2.031.323 2.97 1.07.652.518 1.146 1.15 1.489 1.67.466.706.405 1.54-.022 2.15-.402.576-1.074.896-1.775.896-1.304 0-2.573-1.214-2.098-2.722l.125-.394c-.285-.088-.607-.148-.942-.182-.316-.033-.6-.038-.804-.035-.101.002-.242.01-.294.013Z",fill:"#141B34"}),a.createElement("path",{d:"M11.779 14.596c-.687.062-1.294-.445-1.356-1.132-.062-.687.445-1.295 1.132-1.357.082-.005.342-.02.482-.022.277-.004.662.002 1.097.047.823.085 2.031.323 2.97 1.07.652.518 1.146 1.15 1.489 1.67.466.706.405 1.54-.022 2.15-.402.576-1.074.896-1.775.896-1.304 0-2.573-1.214-2.098-2.722l.124-.394c-.284-.088-.606-.148-.941-.182-.316-.033-.6-.038-.804-.035-.101.002-.243.01-.294.013Z",fill:"#141B34"})),a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},a.createElement("path",{d:"M2.083 20C2.083 10.105 10.105 2.083 20 2.083c9.895 0 17.917 8.021 17.917 17.917 0 9.895-8.022 17.917-17.917 17.917C10.105 37.917 2.083 29.895 2.083 20Z",fill:"#FFD46E"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M11.25 15c0-1.151.933-2.083 2.083-2.083h.015c1.151 0 2.084.933 2.084 2.083 0 1.151-.933 2.083-2.084 2.083h-.015c-1.15 0-2.083-.933-2.083-2.083ZM24.568 15c0-1.151.933-2.083 2.084-2.083h.015c1.151 0 2.083.933 2.083 2.083 0 1.151-.932 2.083-2.083 2.083h-.015c-1.151 0-2.084-.933-2.084-2.083Z",fill:"#141B34"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M13.75 26.667c0-.691.56-1.25 1.25-1.25h10c.69 0 1.25.559 1.25 1.25 0 .691-.56 1.25-1.25 1.25h-10c-.69 0-1.25-.559-1.25-1.25Z",fill:"#141B34"})),a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},a.createElement("path",{d:"M2.083 20C2.083 10.105 10.105 2.083 20 2.083c9.895 0 17.917 8.021 17.917 17.917 0 9.895-8.022 17.917-17.917 17.917C10.105 37.917 2.083 29.895 2.083 20Z",fill:"#FFD46E"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M12.583 24.001c.552-.414 1.335-.302 1.75.25 1.294 1.723 3.35 2.834 5.667 2.834s4.373-1.11 5.667-2.834c.415-.552 1.199-.664 1.751-.25.552.415.664 1.199.25 1.751C25.92 28.076 23.136 29.584 20 29.584s-5.92-1.508-7.666-3.832c-.415-.552-.303-1.336.249-1.751Z",fill:"#141B34"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M11.25 15c0-1.151.933-2.083 2.083-2.083h.015c1.151 0 2.084.933 2.084 2.083 0 1.151-.933 2.083-2.084 2.083h-.015c-1.15 0-2.083-.933-2.083-2.083ZM24.568 15c0-1.151.933-2.083 2.084-2.083h.015c1.151 0 2.083.933 2.083 2.083 0 1.151-.932 2.083-2.083 2.083h-.015c-1.151 0-2.084-.933-2.084-2.083Z",fill:"#141B34"})),a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},a.createElement("path",{d:"M2.083 20C2.083 10.105 10.105 2.083 20 2.083c9.895 0 17.917 8.021 17.917 17.917 0 9.895-8.022 17.917-17.917 17.917C10.105 37.917 2.083 29.895 2.083 20Z",fill:"#FFD46E"}),a.createElement("g",{clipPath:"url(#clip0_159_173224)"},a.createElement("g",{clipPath:"url(#clip1_159_173224)"},a.createElement("path",{d:"M20 30.624c3.752 0 6.904-2.532 7.789-5.956.412-1.593-.185-1.959-1.76-1.959H13.973c-1.575 0-2.173.366-1.761 1.959.885 3.424 4.037 5.956 7.788 5.956Z",fill:"#141B34"})),a.createElement("mask",{id:"mask0_159_173224",style:{maskType:"alpha"},maskUnits:"userSpaceOnUse",x:"12",y:"22",width:"16",height:"9"},a.createElement("path",{d:"M20 30.624c3.752 0 6.904-2.532 7.789-5.956.412-1.593-.185-1.959-1.76-1.959H13.973c-1.575 0-2.173.366-1.761 1.959.885 3.424 4.037 5.956 7.788 5.956Z",fill:"#141B34"})),a.createElement("g",{mask:"url(#mask0_159_173224)"},a.createElement("path",{d:"M20 32.998c3.278 0 5.936-1.594 5.936-3.561 0-1.968-2.658-3.562-5.936-3.562-3.278 0-5.936 1.594-5.936 3.562 0 1.967 2.658 3.561 5.936 3.561Z",fill:"#FF493B"}))),a.createElement("path",{d:"M11.667 15.833c0-1.381 1.12-2.5 2.5-2.5s2.5 1.12 2.5 2.5M23.333 15.833c0-1.381 1.12-2.5 2.5-2.5s2.5 1.12 2.5 2.5",stroke:"#141B34",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"}),a.createElement("defs",null,a.createElement("clipPath",{id:"clip0_159_173224"},a.createElement("rect",{width:"15.83",height:"7.915",fill:"white",transform:"translate(12.085 22.709)"})),a.createElement("clipPath",{id:"clip1_159_173224"},a.createElement("rect",{width:"15.83",height:"7.915",fill:"white",transform:"translate(12.085 22.709)"}))))],pC=({csatPayload:e,submitted:t,value:n,onChange:r})=>{const s=typeof n>"u",{conversation:o}=re(),i=o.csat.scoresContainer(e.csat_question);return a.createElement(EC,null,a.createElement(H,{variant:"caption3",color:E.themedColor.textMidEmphasis,"aria-hidden":"true"},e.csat_question),a.createElement(CC,{...i.props},i.descriptionNode,e.csat_scores.map(({label:c,image_url:u},d)=>{const m=d+1,h=n===m,f=e.csat_scores.length,g=o.csat.scoreItem({score:m,label:c,selected:h,disabled:t,currentIndex:d,totalCount:f,hasSelection:!s,onChange:r});return a.createElement(bC,{key:d,type:"button",...g.props},a.createElement(_C,{value:m,selected:s||h,src:u}),!!c&&a.createElement(H,{"aria-hidden":"true",color:h?E.themedColor.textHighEmphasis:E.themedColor.textLowEmphasis,variant:"caption3"},c),g.descriptionNode)})))},_C=({value:e,src:t,selected:n})=>{const[r,s]=l.useState(!1),o=r?a.createElement(hC,{value:e,selected:n}):a.createElement(yC,{$selected:n,alt:"","aria-hidden":"true",src:t,onError:()=>s(!0)});return a.createElement(vC,null,o)},EC=C.default.div`display:flex;flex-direction:column;gap:8px;`,CC=C.default.div`display:flex;justify-content:space-between;align-self:center;width:100%;max-width:400px;gap:16px;`,bC=C.default.button`appearance:none;-webkit-appearance:none;background-color:transparent;border:none;padding:0;text-align:center;gap:4px;display:flex;flex-direction:column;align-items:center;justify-content:start;box-sizing:border-box;min-width:48px;max-width:68px;${xe}&:not(:disabled):hover span{color:${E.themedColor.textHighEmphasis};}`,vC=C.default.div`button:not(:disabled):hover &{border-radius:4px;cursor:pointer;background-color:${E.color.background200};${Q.dark`
|
|
360
360
|
background-color: ${E.color.background500};
|
|
361
361
|
`}
|
|
362
362
|
}
|
|
363
|
-
`,yC=
|
|
363
|
+
`,yC=C.default.img`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,SC=({csatPayload:e})=>a.createElement(H,{variant:"button",color:E.themedColor.textHighEmphasis},e.title),ir=({csatPayload:e,type:t,renderSubmitButton:n,initialCsat:r,initialCsatReason:s,initialIsResolved:o})=>{const{params:i,setParams:c,error:u,setError:d,followUpItem:m,state:h,validateParams:f,itemProps:g}=dm({csatPayload:e,type:t,initialCsat:r,initialCsatReason:s,initialIsResolved:o});return a.createElement(a.Fragment,null,a.createElement(AC,null,a.createElement(SC,{...g}),t===Je.AI_AGENT_CSAT_5_WITH_CRE&&a.createElement(iC,{...g,defaultValue:o,value:i.isResolved,onChange:_=>c({isResolved:_})}),a.createElement(pC,{...g,value:i.csat,onChange:_=>c({csat:_})}),m&&a.createElement(lC,{...g,followUpItem:m,value:i.csatReason,onChange:_=>{c({csatReason:_}),d({followUpItem:!1})},hasError:u.followUpItem})),h!=="unsubmittable"&&a.createElement(a.Fragment,null,a.createElement(Le.Separator,null),n({state:h,params:i,validateParams:f})))},AC=C.default.div`display:flex;flex-direction:column;gap:12px;`,TC=e=>{const{stringSet:t}=se();return rl(e,{title:t.CSAT_TITLE_UNSUBMITTED,question:t.CSAT_RATING_TITLE,cre:{question:t.CSAT_CRE_TITLE,positive_label:t.CSAT_CRE_SOLVED,negative_label:t.CSAT_CRE_NOT_SOLVED},followUp:{question:t.CSAT_REASON_PLACEHOLDER},submit_label:t.CSAT_SUBMIT_LABEL,submitted_label:t.CSAT_TITLE_SUBMITTED})},IC=()=>{const{stringSet:e}=se();return a.createElement(H,{variant:"body2",color:E.themedColor.textMidEmphasis,style:{textAlign:"center"}},e.CSAT_SUBMISSION_EXPIRED)},xC=({onMount:e,children:t})=>(l.useEffect(()=>{e&&we(e)},[]),t),RC=e=>{const{conversation:t}=re();if(e.messageType!=="admin.csat")throw new Error("Invalid message type");const{extendedMessagePayload:n,onSubmitCSAT:r,onScrollToBottom:s}=e,{csat:o,csatReason:i,csatExpireAt:c,isResolvedWhenDeterminedByUser:u}=e,d=Nn(),m=TC(n==null?void 0:n.csat),h=l.useRef(null),f=l.useRef(null),[g,_]=l.useState(!1),y=l.useRef(!1),b=l.useCallback(()=>{we(()=>{var R;return(R=f.current)==null?void 0:R.focus()})},[]),{isExpiredNow:p,isRenderableCSAT:S}=mm({csat:o,csatExpireAt:c,csatPayload:m,isSubmitInFlight:g});if(lm({csat:o,csatPayload:m,isRenderableCSAT:S,isExpiredNow:p,announceStatus:e.announceStatus,onSubmittedAnnounced:b}),!S||!m)return null;const A=()=>{var L;const R=(L=h.current)==null?void 0:L.querySelector('[aria-invalid="true"]');return R?R.getAttribute("role")==="radiogroup"?R.querySelector('[role="radio"]'):R:null},T=m.type===Je.AI_AGENT_CSAT_5||m.type===Je.AI_AGENT_CSAT_5_WITH_CRE||m.type===Je.HELPDESK_CSAT_5?ir:()=>null;return a.createElement(MC,{ref:h},!o&&p?a.createElement(IC,null):a.createElement(T,{csatPayload:m,type:m.type,initialCsat:o,initialCsatReason:i,initialIsResolved:u,renderSubmitButton:({state:R,params:L,validateParams:D})=>R==="submitted"?a.createElement(kC,{ref:f,role:"status","aria-live":"polite","aria-atomic":"true","aria-label":m.csat_submitted_label,tabIndex:-1},a.createElement(H,{variant:"button","aria-hidden":"true"},m.csat_submitted_label)):a.createElement(xC,{onMount:s},a.createElement(wC,{type:"button",...t.csat.submitButton(m.csat_submit_label).props,onClick:async()=>{if(y.current)return;const k=oi(c);if(!k&&D()){y.current=!0,_(!0);try{await r(L)}catch(M){throw y.current=!1,_(!1),M}}else d(),k||we(()=>{var M;(M=e.announceError)==null||M.call(e,{type:"csatFormError"},A())})}},a.createElement(H,{variant:"button"},m.csat_submit_label)))}))},MC=C.default.div`display:flex;flex-direction:column;background-color:${({theme:e})=>e.colors.csat.background};border-radius:16px;gap:16px;padding:16px;`,wC=C.default.button`all:unset;width:100%;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.primary};color:${({theme:e})=>e.colors.base.primaryContrastContent};border-radius:6px;padding:10px 20px;display:flex;align-items:center;justify-content:center;cursor:pointer;text-align:center;word-break:break-word;${xe}&:hover{background-color:${E.color.primary.dark};}`,kC=C.default.div`width:100%;box-sizing:border-box;color:${E.themedColor.textHighEmphasis};background-color:${E.color.background200};border-radius:6px;padding:10px 20px;display:flex;align-items:center;justify-content:center;text-align:center;word-break:break-word;${Q.dark`
|
|
364
364
|
background-color: ${E.color.onlight.textDisabled};
|
|
365
365
|
`}
|
|
366
|
-
`,LC=e=>{const{components:t}=Hn.useContext(),n=e.messageType==="admin"?a.createElement(t.AdminMessage,{...e}):e.messageType==="admin.csat"?a.createElement(t.CSATMessage,{...e}):null;return a.createElement(OC,{$marginBottom:Ln(e.groupType)},n)},Hn=je({template:LC,components:{AdminMessage:XE,CSATMessage:RC}}),OC=
|
|
367
|
-
`,XC=
|
|
366
|
+
`,LC=e=>{const{components:t}=Hn.useContext(),n=e.messageType==="admin"?a.createElement(t.AdminMessage,{...e}):e.messageType==="admin.csat"?a.createElement(t.CSATMessage,{...e}):null;return a.createElement(OC,{$marginBottom:Ln(e.groupType)},n)},Hn=je({template:LC,components:{AdminMessage:XE,CSATMessage:RC}}),OC=C.default.div`padding-inline:${te.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>e}px;`,ts=({title:e,titleId:t,description:n,descriptionId:r,negativeText:s,positiveText:o,onCancel:i,onConfirm:c,buttonLayout:u="horizontal",styles:d})=>{const m=s!==void 0&&i!==void 0,h=o!==void 0&&c!==void 0,f=m?a.createElement(PC,{type:"button",onClick:i,$fullWidth:u!=="horizontal",$background:d==null?void 0:d.negativeBackground,$borderColor:d==null?void 0:d.negativeBorderColor},a.createElement(H,{variant:"button",color:(d==null?void 0:d.negativeText)??E.themedColor.textHighEmphasis},s)):null,g=h?a.createElement(UC,{type:"button",onClick:c,$fullWidth:u!=="horizontal",$background:d==null?void 0:d.positiveBackground,$borderColor:d==null?void 0:d.positiveBorderColor},a.createElement(H,{variant:"button",color:(d==null?void 0:d.positiveText)??E.themedColor.textHighEmphasisInverse},o)):null;return a.createElement(NC,null,a.createElement(DC,null,a.createElement(H,{as:"div",id:t,variant:"h2",color:(d==null?void 0:d.titleColor)??E.themedColor.textHighEmphasis},e)),a.createElement($C,null,a.createElement(H,{as:"div",id:r,variant:"body3",color:(d==null?void 0:d.descriptionColor)??E.themedColor.textMidEmphasis},n)),a.createElement(FC,{$buttonLayout:u},u==="horizontal"?a.createElement(a.Fragment,null,f,g):a.createElement(a.Fragment,null,g,f)))},NC=C.default.div`display:flex;flex-direction:column;width:280px;border-radius:16px;overflow:hidden;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,DC=C.default.div`padding:24px 24px 16px;`,$C=C.default.div`padding-inline:24px;`,FC=C.default.div`display:flex;flex-direction:${({$buttonLayout:e})=>e==="vertical-full-width"?"column":"row"};align-items:center;justify-content:flex-end;gap:4px;padding:16px 24px;`,PC=C.default.button`display:flex;align-items:center;justify-content:center;box-sizing:border-box;width:${({$fullWidth:e})=>e?"100%":"auto"};padding:12px 20px;border-radius:20px;cursor:pointer;border:1px solid ${({$borderColor:e})=>e??"transparent"};background:${({$background:e})=>e??"none"};white-space:nowrap;overflow:hidden;text-overflow:ellipsis;&:hover{opacity:0.8;}`,UC=C.default.button`display:flex;align-items:center;justify-content:center;box-sizing:border-box;width:${({$fullWidth:e})=>e?"100%":"auto"};padding:12px 20px;border-radius:20px;cursor:pointer;border:1px solid ${({$borderColor:e})=>e??"transparent"};background-color:${({$background:e})=>e??E.themedColor.textHighEmphasis};white-space:nowrap;overflow:hidden;text-overflow:ellipsis;&:hover{opacity:0.8;}`,mn=16,BC=({status:e})=>e===bn.COMPLETED?a.createElement(J,{type:"done-circle",size:mn,color:E.themedColor.textHighEmphasis}):e===bn.CANCELED?a.createElement(J,{type:"stop-circle",size:mn,color:E.themedColor.textLowEmphasis}):a.createElement(pt,{size:mn},a.createElement(J,{type:"spinner",size:mn,color:E.themedColor.textHighEmphasis})),Fa=24,HC=8,GC=40,zC=({task:e,isFirst:t,isLast:n})=>a.createElement(VC,{role:"listitem"},a.createElement(qC,null,a.createElement(wo,{$hidden:t}),a.createElement(KC,null,a.createElement(BC,{status:e.status})),a.createElement(wo,{$hidden:n})),a.createElement(YC,null,a.createElement(H,{as:"div",variant:"body3",color:e.status===bn.CANCELED?E.themedColor.textLowEmphasis:E.themedColor.textHighEmphasis},e.user_facing_title))),VC=C.default.div`display:flex;gap:4px;`,qC=C.default.div`display:flex;flex-direction:column;align-items:center;width:${Fa}px;flex-shrink:0;`,wo=C.default.div`width:1px;flex:1;transform:translateX(-25%);${({$hidden:e})=>e&&"visibility: hidden;"}background-image:repeating-linear-gradient( to bottom,${E.themedColor.textHighEmphasis}0 2px,transparent 2px 4px );`,KC=C.default.div`display:flex;height:${Fa}px;align-items:center;justify-content:center;`,YC=C.default.div`display:flex;flex:1;align-items:center;box-sizing:border-box;min-width:0;min-height:${GC}px;padding-block:${HC}px;`,WC=({steward:e,onCancelSteward:t})=>{const{logger:n}=le(),[r,s]=l.useState(!1),[o,i]=l.useState(!1),c=!!e.cancellation_option,u=yc(e.status);return a.createElement(jC,{$marginBottom:Ln("single")},a.createElement(XC,null,a.createElement(ZC,null,a.createElement(JC,null,a.createElement(H,{as:"div",variant:"caption1",color:E.themedColor.textHighEmphasis},e.title),!!e.description&&a.createElement(H,{as:"div",variant:"caption4",color:E.themedColor.textLowEmphasis},e.description)),c&&a.createElement(nb,{type:"button","aria-label":"Stop steward",disabled:o,onClick:()=>s(!0)},a.createElement(J,{type:"stop",size:16,color:o?E.themedColor.textDisabled:E.themedColor.textHighEmphasis}))),a.createElement(QC,null),e.tasks.length===0?u!==Pt.IN_PROGRESS?null:a.createElement(tb,null,a.createElement(pt,{size:16},a.createElement(J,{type:"spinner",size:16,color:E.themedColor.textHighEmphasis}))):a.createElement(eb,{role:"list"},e.tasks.map((d,m)=>a.createElement(zC,{key:d.id,task:d,isFirst:m===0,isLast:m===e.tasks.length-1})))),r&&e.cancellation_option&&a.createElement(dt,{portalContainerId:ye.WINDOW,visible:r,onClose:()=>s(!1)},a.createElement(ts,{title:e.cancellation_option.title,description:e.cancellation_option.description,negativeText:e.cancellation_option.negative_text,positiveText:e.cancellation_option.positive_text,onCancel:()=>s(!1),onConfirm:async()=>{s(!1),i(!0);try{await(t==null?void 0:t())}catch(d){n.warn("steward.cancelSteward: failed",d)}finally{i(!1)}}})))},jC=C.default.div`display:flex;flex-direction:column;margin:0 ${te.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>`${e}px`};
|
|
367
|
+
`,XC=C.default.div`display:flex;flex-direction:column;border-radius:12px;overflow:hidden;padding:16px;border:1px solid ${E.themedColor.bg_300_500};background-color:${E.themedColor.bg_50_600};box-shadow:0 8px 20px rgba(0,0,0,0.12);`,ZC=C.default.div`display:flex;flex-direction:row;align-items:flex-start;gap:8px;`,JC=C.default.div`display:flex;flex-direction:column;gap:4px;flex:1;min-width:0;`,QC=C.default.div`height:1px;margin-block:12px;background-color:${E.themedColor.bg_200_400};`,eb=C.default.div`display:flex;flex-direction:column;`,tb=C.default.div`display:flex;width:100%;height:40px;align-items:center;justify-content:center;`,nb=C.default.button`width:32px;height:32px;border-radius:50%;display:flex;align-items:center;justify-content:center;flex-shrink:0;border:none;cursor:pointer;color:${E.themedColor.textHighEmphasis};background-color:${E.themedColor.bg_200_400};&:hover:not(:disabled){opacity:0.8;}&:disabled{cursor:default;}`,rb=({className:e,label:t,onClick:n})=>{const{colors:r}=G.useTheme(),{conversation:s}=re(),o={newMessages:s.newMessagesButton()};return a.createElement(sb,{className:e,onClick:n,...o.newMessages.props},a.createElement(H,{variant:"button",color:r.base.primaryContrastContent},t),a.createElement(J,{size:16,type:"chevron-down",color:r.base.primaryContrastContent}),o.newMessages.descriptionNode)},sb=C.default.button`all:unset;cursor:pointer;display:flex;align-items:center;gap:4px;padding:10px 12px 10px 16px;border-radius:24px;background-color:${({theme:e})=>e.colors.base.primary};box-shadow:0 8px 10px 1px rgba(13,13,13,0.12),0 3px 14px 2px rgba(13,13,13,0.08),0 3px 5px -3px rgba(13,13,13,0.04);&:focus{outline:none;}${xe}`,ns=({iconSize:e=64,icon:t,className:n,label:r,children:s})=>a.createElement(ib,{className:n},t&&a.createElement(J,{type:t,size:e,color:E.themedColor.textLowEmphasis}),r&&a.createElement(H,{variant:"body1",color:E.themedColor.textMidEmphasis},r),s),ob=C.default.div`position:relative;display:flex;justify-content:center;align-items:center;width:100%;height:100%;`,ib=C.default.div`display:flex;flex-direction:column;min-height:104px;align-items:center;gap:20px;text-align:center;`,ab=({label:e="Something went wrong",icon:t="error",action:n,...r})=>a.createElement(ns,{icon:t,label:e,...r},n&&a.createElement(cb,{onClick:n.onClick,label:n.label??"Retry"})),cb=({label:e,onClick:t})=>{const{conversation:n}=re();return a.createElement(lb,{tabIndex:0,...n.retryButton(e).props,onClick:t},a.createElement(J,{type:"refresh",size:20}),a.createElement(H,{variant:"button",color:E.color.primary.main},e))},lb=C.default.button`all:unset;display:flex;cursor:pointer;gap:4px;align-items:center;justify-content:center;${xe}`,ub=({iconSize:e=48,className:t})=>a.createElement(pt,{size:e,className:t}),db=({label:e="No channels",icon:t="chat",...n})=>a.createElement(ns,{icon:t,label:e,...n}),mb=({label:e="No messages",icon:t="message",...n})=>a.createElement(ns,{icon:t,label:e,...n}),hb=e=>{const{components:t}=Gn.useContext(),n=e.type==="loading"?a.createElement(t.Loading,{...e}):e.type==="error"?a.createElement(t.Error,{...e}):e.type==="noChannels"?a.createElement(t.NoChannels,{...e}):e.type==="noMessages"?a.createElement(t.NoMessages,{...e}):null;return n&&a.createElement(ob,null,n)},Gn=je({template:hb,components:{Loading:ub,Error:ab,NoChannels:db,NoMessages:mb}}),Ut=e=>{const{Template:t}=Gn.useContext();return a.createElement(t,{...e})},fb=[0,150,450];function gb({enabled:e}){const{state:t,actions:n}=ua(),r=l.useRef(0),s=l.useRef(t.isAwayFromBottom);s.current=t.isAwayFromBottom,l.useEffect(()=>{if(!e){r.current+=1;return}const o=r.current+1;r.current=o;const i=fb.map(c=>setTimeout(()=>{we(()=>{r.current===o&&(s.current||n.scrollToBottom(!1))})},c));return()=>{r.current+=1,i.forEach(c=>clearTimeout(c))}},[n.scrollToBottom,e])}const pb=({className:e,date:t=Date.now(),role:n,style:r})=>{const{format:s,stringSet:o}=se();return a.createElement(_b,{id:`${Ge}-date-separator`,role:n,style:r,className:e},a.createElement(H,{variant:"caption4",color:E.themedColor.textMidEmphasis},s(t,o.DATE_FORMAT__MESSAGE_LIST__DATE_SEPARATOR)))},_b=C.default.div`display:flex;justify-content:center;align-items:center;text-align:center;word-break:break-word;`,Eb=({className:e,style:t,onClick:n})=>{const{conversation:r}=re(),s={scrollToBottom:r.scrollToBottomButton()};return a.createElement(Cb,{className:e,style:t,onClick:n,tabIndex:0,...s.scrollToBottom.props},a.createElement(J,{size:24,type:"chevron-down",color:E.color.primary.main}),s.scrollToBottom.descriptionNode??null)},Cb=C.default.button`all:unset;cursor:pointer;display:flex;align-items:center;justify-content:center;width:40px;height:40px;border-radius:24px;box-shadow:0 2px 8px 0 rgba(0,0,0,0.08),0 4px 6px 0 rgba(0,0,0,0.12);${Q.light`
|
|
368
368
|
background-color: ${E.color.background50};
|
|
369
369
|
&:hover {
|
|
370
370
|
background-color: ${E.color.background100};
|
|
@@ -388,18 +388,18 @@
|
|
|
388
388
|
}
|
|
389
389
|
|
|
390
390
|
${xe}
|
|
391
|
-
`,bb=()=>null,zn=je({template:bb,components:{DateSeparator:pb,ScrollToBottomButton:Eb}}),vb=()=>{const{stringSet:e,format:t}=se(),{agentPreviewConfigs:n={},aiAgentId:r}=
|
|
391
|
+
`,bb=()=>null,zn=je({template:bb,components:{DateSeparator:pb,ScrollToBottomButton:Eb}}),vb=()=>{const{stringSet:e,format:t}=se(),{agentPreviewConfigs:n={},aiAgentId:r}=le(),{aiAgentInfo:s}=Ne(),{messageSource:o}=Ae(),{Template:i}=_t.useContext(),{components:c}=zn.useContext(),u=n.welcomeMessages??[],d=o.messages,m=ug(d,r),h=d[m.length+1],f=m[0]??h;return{filteredMessages:pa(d,{previewWelcomeMessages:u,aiAgentUserId:r}),shouldShowOriginalDate:g=>g>0||u.length===0?!0:h&&!at.isSameDay(h.createdAt,(f==null?void 0:f.createdAt)??0),renderAgentPreviewWelcomeMessages:()=>u.length===0?null:a.createElement(a.Fragment,null,a.createElement(c.DateSeparator,{role:"listitem",style:{margin:"16px 0"},date:f==null?void 0:f.createdAt}),u.map((g,_)=>{const y=_===u.length-1,b=m.length!==d.length,p=u.length===1?"single":_===0?"top":y||b?"bottom":"middle",S=(f==null?void 0:f.createdAt)??Date.now();return a.createElement("div",{key:_,role:"listitem",tabIndex:-1,"aria-label":Dt({sender:(s==null?void 0:s.nickname)||"",message:g.message,messageFormat:"markdown",time:t(S,e.DATE_FORMAT__MESSAGE_TIMESTAMP),codeBlockPlaceholder:e.A11Y_CODE_BLOCK_PLACEHOLDER}),"data-message-listitem":""},a.createElement(i,{messageType:"user",message:g.message,sender:s,groupType:p,createdAt:S,extendedMessagePayload:{suggested_replies:g.suggestedReplies},suggestedRepliesDirection:n.suggestedRepliesDirection,suggestedRepliesVisible:y&&!b,isBotMessage:!0,onClickSuggestedReply:async({reply:A})=>{o.sendUserMessage({message:A})}}))}))}},yb=()=>{const{messageSource:e,scrollSource:t}=Ae();l.useEffect(()=>{!t.state.isAwayFromBottom&&t.state.isScrollPositionReconciled&&e.resetNewMessages()},[t.state.isAwayFromBottom,t.state.isScrollPositionReconciled])},ko="https://delight.ai?utm_medium=product&utm_source=aiagent&utm_campaign=fy26-glbl-ai-agent-poweredby",Sb=({style:e})=>{const{stringSet:t}=se(),{handlers:n}=le(),{conversation:r}=re();return Ur("powered-by")?a.createElement(Ab,{variant:"caption2",style:e},t.POWERED_BY+" ",a.createElement(Tb,{variant:"caption2",forwardedAs:"a",href:ko,...r.poweredByLink().props,rel:zr,target:"_blank",onClick:o=>{o.preventDefault(),n.onClickLink({url:ko})}},"Sendbird")):null},Ab=C.default(H)`color:${E.themedColor.textLowEmphasis};text-align:center;`,Tb=C.default(H)`color:${E.themedColor.textLowEmphasis};cursor:pointer;text-decoration:none;`,Ib=()=>{var c;const{stringSet:e}=se(),{conversation:t}=re(),{channelSource:n,goToActiveConversation:r,scrollSource:s}=Ae(),o=He(n.channel),i=l.useRef(o);return l.useEffect(()=>{if(!i.current&&o){const m=setTimeout(()=>{s.actions.scrollToBottom()},100);return()=>clearTimeout(m)}i.current=o},[o,s.actions.scrollToBottom]),!((c=n.channel)!=null&&c.isAIAgent)||!o?null:a.createElement(xb,null,a.createElement(Rb,{variant:"button",color:E.themedColor.textHighEmphasis,...t.startNewConversationButton({onActivate:r}).props},e.TALK_TO_AGENT))},xb=C.default.div`display:flex;justify-content:center;margin-bottom:16px;`,Rb=C.default(H)`border-radius:6px;box-sizing:border-box;padding:10px 20px;cursor:pointer;user-select:none;background-color:${E.color.background50};border:1px solid ${E.color.onlight.textDisabled};${Q.dark`
|
|
392
392
|
background-color: ${E.color.background700};
|
|
393
393
|
border-color: ${E.color.ondark.textLowEmphasis};
|
|
394
394
|
`}
|
|
395
|
-
`,Mb=({statsCallbacks:e,...t})=>(Sm(e),a.createElement(WC,{...t})),wb=(e,t,n)=>t&&Me.isWelcomeMessage(e,n)&&Me.isWelcomeMessage(t,n)?!1:!dc.isSameDay((t==null?void 0:t.createdAt)??0,e.createdAt),kb=()=>{var K;const{Template:e}=xt.useContext(),{Template:t}=_t.useContext(),{Template:n}=Hn.useContext(),{components:r}=zn.useContext(),{stringSet:s,format:o}=se(),{announceError:i,announceStatus:c}=ot(),{file:u}=re().conversation,{config:d,cache:m,agentPreviewConfigs:h,chatSDK:f,handlers:g,state:C}=ce(),{userSession:v,aiAgentInfo:_,connectionError:p}=De(),{conversationStatsEnabled:S=!0,conversation:A,channelSource:T,messageSource:M,scrollSource:L,state:{input:D,streamAnimation:x}}=Ae(),{filteredMessages:O,shouldShowOriginalDate:H,renderAgentPreviewWelcomeMessages:F}=vb(),W=xi(T.channel),q=ym({enabled:S}),[k,G]=l.useState(null),[P,V]=l.useState(null);l.useEffect(()=>{L.actions.onTypingIndicatorUpdate(!!W)},[!!W,L.actions.onTypingIndicatorUpdate]),yb(),gb({enabled:M.initialized&&M.messages.length>0});const me=(R,X=!1)=>{var ne;return X?_:((ne=T.channel)==null?void 0:ne.members.find(oe=>oe.userId===R.sender.userId))??R.sender},Ie=R=>{if(R.sendingStatus==="failed"&&!D.disabled)return()=>V(R)},j=({message:R,index:X})=>{const ne=Sc(R),oe=O[X-1],Re=O[X+1],Le=O[O.length-1],$=R===Le,I=st(R,_.userId),w=!(_.isUserFeedbackEnabled&&I&&!Me.isWelcomeMessage(R)),N=Ac(R,oe,Re,w),z=wb(R,oe,_.userId)&&H(X),Y=Ce=>{G({files:Ce.files.map(Te=>({...Te,timestamp:R.createdAt})),index:Ce.index})},te=Ce=>{Y({files:[Ce],index:0})},Z=z?a.createElement(r.DateSeparator,{role:"listitem",style:{margin:"16px 0"},date:R.createdAt}):null,pe={data:R.data,maxBodyWidth:C.expanded?ee.WIDE_BODY_MAX_WIDTH:void 0,extendedMessagePayload:R.extendedMessagePayload,createdAt:R.createdAt,groupType:N,onClickMedia:te,onClickMediaFiles:Y,onClickFile:g.onClickLink,onClickCTA:g.onClickLink,onClickCitation:Ce=>g.onClickLink({url:Ce.link}),onClickLink:g.onClickLink},Xe=()=>{if(Ne.isOutgoing(R,v.userId))return"outgoingmessage";if(Ne.isIncoming(R,v.userId))return"incomingmessage"},ae=R.createdAt!=null&&R.createdAt!==0?o(R.createdAt,s.DATE_FORMAT__MESSAGE_TIMESTAMP):void 0,he=(()=>{var Te,ve,$e,Pe,fe,Ue;const Ce=(Te=R.message)==null?void 0:Te.trim();if(R.isFileMessage()){const Be=((ve=R.name)==null?void 0:ve.trim())||"";return Qn({markdownText:Ce,comparisonText:Be,plainText:u.label(Be,R.type)})}if(R.isMultipleFilesMessage()){const Be=((fe=(Pe=($e=R.fileInfoList)==null?void 0:$e[0])==null?void 0:Pe.fileName)==null?void 0:fe.trim())||"",nn=((Ue=R.fileInfoList)==null?void 0:Ue.length)??0;return Qn({markdownText:Ce,comparisonText:Be,plainText:nn>0?s.CONVERSATION_LIST__MULTIPLE_FILES_COUNT(nn):""})}return Ce?Qn({markdownText:Ce}):Ni("")})(),_e=(()=>{if(Ne.isAdmin(R))return Dt({message:he.text,messageFormat:he.format,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER});if(Ne.isOutgoing(R,v.userId))return Dt({sender:s.A11Y_MESSAGE_SENDER_YOU,message:he.text,messageFormat:"plain",time:ae,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER});if(Ne.isIncoming(R,v.userId))return Dt({sender:me(R,I).nickname,message:he.text,messageFormat:he.format,time:ae,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER})})(),Ee=(()=>{var Ce,Te;if(Ne.isAdmin(R))return Ne.isCSAT(R)?A?a.createElement(n,{...pe,...A,isResolvedWhenDeterminedByUser:tl(A),messageType:"admin.csat",announceError:i,announceStatus:c,onSubmitCSAT:async ve=>{var $e;await(($e=T.channel)==null?void 0:$e.submitCSAT(ve))},onScrollToBottom:()=>L.actions.scrollToBottom()}):null:a.createElement(n,{...pe,messageType:"admin",message:R.message});if(Ne.isSteward(R)){const ve=q({message:R,isBotMessage:I,aiAgentUserId:_.userId});return a.createElement(Mb,{steward:R.extendedMessagePayload.steward,statsCallbacks:ve,onCancelSteward:async()=>{await f.aiAgent.cancelStewardTask({channelUrl:R.channelUrl,messageId:R.messageId})}})}if(Ne.isOutgoing(R,v.userId)){const ve={...pe,message:R.message,sender:me(R),sendingStatus:R.sendingStatus,onClickFailedMessage:Ie(R)};if(R.isUserMessage())return a.createElement(e,{messageType:"user",...ve});if(R.isFileMessage()){const[$e,Pe]=((Ce=R.metaArrays.find(fe=>fe.key===Xo))==null?void 0:Ce.value)??[];return a.createElement(e,{messageType:"file",file:R,metadata:{aspectRatio:$e&&Pe?`${$e}/${Pe}`:"1/1",localFile:(Te=R.messageParams)==null?void 0:Te.file},...ve})}if(R.isMultipleFilesMessage()){const{files:$e,metadata:Pe}=vo(R);return a.createElement(e,{messageType:"multipleFiles",files:$e,metadata:Pe,...ve})}}if(Ne.isIncoming(R,v.userId)){const ve=Me.isStreaming(R),$e=q({message:R,isBotMessage:I,aiAgentUserId:_.userId}),Pe={...pe,statsCallbacks:$e,sender:me(R,I),message:R.message,suggestedRepliesVisible:$,suggestedRepliesDirection:h==null?void 0:h.suggestedRepliesDirection,isBotMessage:I,isStreaming:ve,isHandedOff:rt(T.channel),isConversationClosed:He(T.channel),isFeedbackEnabled:_.isUserFeedbackEnabled,isFeedbackCommentEnabled:_.isUserFeedbackCommentOptionEnabled,isSenderAvatarVisible:d.conversation.list.senderAvatarEnabled,deferredMarkdownElements:d.conversation.list.deferredMarkdownElements,onClickSuggestedReply:async({reply:fe})=>{M.sendUserMessage({message:fe})},onRequestMessageTemplate:async fe=>{const{template:Ue}=await f.aiAgent.getMessageTemplate(fe);return m.template.set(fe,Ue),Ue},onGetCachedMessageTemplate:fe=>m.template.get(fe),onHandleTemplateInternalAction:fe=>{if(fe.type==="internal"&&fe.internalData){const{method:Ue,payload:Be}=fe.internalData;Ue==="message.send"&&(Be!=null&&Be.message)&&M.sendUserMessage({message:Be.message})}},onFeedbackUpdate:fe=>{const Ue={messageId:R.messageId,channelUrl:R.channelUrl};if(!fe)return f.aiAgent.deleteMessageFeedback(Ue);const Be={...Ue,rating:d_(fe.rating),comment:fe.comment};return Me.hasFeedback(R)?f.aiAgent.updateMessageFeedback(Be):f.aiAgent.createMessageFeedback(Be)},onSubmitForm:({key:fe,data:Ue})=>f.aiAgent.submitForm({messageId:R.messageId,channelUrl:R.channelUrl,formKey:fe,formData:Ue}),onCancelForm:({key:fe})=>f.aiAgent.cancelForm({messageId:R.messageId,channelUrl:R.channelUrl,formKey:fe}),onSendChallengeAction:({key:fe,requestId:Ue,action:Be,data:nn})=>f.aiAgent.sendChallengeAction({channelUrl:R.channelUrl,key:fe,requestId:Ue,action:Be,data:nn}),onStreamAnimationStart:()=>{x.start(R.messageId)},onStreamAnimationProgress:()=>{L.actions.onStreamingUpdate(!0)},onStreamAnimationComplete:()=>{x.stop(R.messageId),L.actions.onStreamingUpdate(!1)}};if(R.isUserMessage())return a.createElement(t,{messageType:"user",...Pe});if(R.isFileMessage())return a.createElement(t,{messageType:"file",file:R,...Pe});if(R.isMultipleFilesMessage()){const{files:fe}=vo(R);return a.createElement(t,{messageType:"multipleFiles",files:fe,...Pe})}}})();return a.createElement(l.Fragment,{key:ne},Z,a.createElement("div",{id:`${Ge}-message-item`,role:"listitem",tabIndex:-1,"aria-label":_e,"data-message-listitem":"","data-layout-id":Xe()},Ee))};return a.createElement(Lb,{id:`${Ge}-message-list`},a.createElement(Ug,{ref:L.ref,onScroll:L.props.onScroll,stackDirection:h==null?void 0:h.messageStackDirection,messages:O,renderMessage:j,onLoadPrev:M.loadPrevious,onLoadNext:M.loadNext,depsForResetScrollPositionToBottom:[M.initialized,M.messages.length!==0],bottomSpacerHeight:L.state.bottomSpace,"aria-label":s.A11Y_MESSAGE_LIST,loading:!M.initialized||!T.channel,empty:O.length===0&&!W,error:!!(p||T.error),LoadingComponent:a.createElement(Ut,{type:"loading"}),EmptyComponent:(()=>{const R=F();return R?a.createElement("div",{style:{width:"100%"}},R):a.createElement(Ut,{type:"noMessages",label:s.PLACE_HOLDER__NO_MESSAGES})})(),ErrorComponent:a.createElement(Ut,{type:"error",label:(p==null?void 0:p.message)??((K=T.error)==null?void 0:K.message),action:T.error?{label:s.RETRY,onClick:()=>T.refetch()}:void 0}),messageTopArea:a.createElement(a.Fragment,null,a.createElement(Sb,{style:{marginTop:16}}),F()),messageBottomArea:a.createElement(a.Fragment,null,W&&a.createElement("div",{id:`${Ge}-message-item`,role:"listitem",tabIndex:-1,"aria-label":Dt({sender:W.user.nickname,message:s.A11Y_TYPING_INDICATOR,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER}),"data-message-listitem":"",style:{marginTop:O.length===0?8:0}},a.createElement(t,{isTyping:!0,isBotMessage:W.isBot,sender:W.user,thinkingMessage:W.thinkingMessage,messageType:"user",groupType:"single",message:"",isSenderAvatarVisible:d.conversation.list.senderAvatarEnabled})),d.conversation.list.isTalkToAgentViewEnabled&&a.createElement(Ib,null)),overlayArea:a.createElement(a.Fragment,null,d.conversation.list.newMessageIndicatorEnabled&&L.state.isAwayFromBottom&&M.newMessages.length>0&&a.createElement(Ob,{label:s.SCROLL_TO_NEW_MESSAGES_LABEL(M.newMessages),onClick:()=>L.actions.scrollToBottom()}),L.state.isAwayFromBottom&&M.newMessages.length===0&&!W&&a.createElement(r.ScrollToBottomButton,{onClick:()=>L.actions.scrollToBottom(),style:{position:"absolute",bottom:12,insetInlineEnd:16}}))}),k&&a.createElement(Kg,{files:k.files,initialIndex:k.index,onClose:()=>G(null),visible:!0}),P&&a.createElement(lt,{visible:!0,onClose:()=>V(null),"aria-label":s.A11Y_FAILED_MESSAGE_OPTIONS},a.createElement(lt.ActionItem,{onClick:()=>{M.resendMessage(P),V(null)}},s.FAILED_MESSAGE_RESEND),a.createElement(lt.ActionItem,{destructive:!0,onClick:()=>{M.deleteMessage(P),V(null)}},s.FAILED_MESSAGE_REMOVE)))},Lb=b.default.div`overflow-y:hidden;display:flex;flex:1;position:relative;`,Ob=b.default(rb)`position:absolute;bottom:12px;left:50%;transform:translateX(-50%);`,Nb=()=>a.createElement(kb,null),Lo={file:"attach",snippet:"snippet",site:"website",sb_sprinklr:"sprinklr",sb_salesforce:"salesforce",sb_confluence:"confluence",sb_zendesk:"zendesk",sb_desk:"snippet"},Pa=({actionbook:e,functionCalls:t,groundedness:n,agentMessageTemplates:r,flaggedTypes:s,onClickActionbook:o,onClickFunctionCall:i,onClickFunctionCallDetail:c,onClickGroundedness:u,onClickAgentMessageTemplate:d,topContent:m,bottomContent:h,renderCustomGroundednessIcon:f=C=>C.default,style:g={}})=>{const{iconColor:C="#000000",textColor:v="#000000",highlightColor:_=Bt.DEFAULT_PRIMARY}=g;return a.createElement(Oo,null,m,e&&a.createElement(Oo,null,a.createElement(wn,null,a.createElement(Ot,null,a.createElement(J,{size:16,type:"actionbook",color:C})),a.createElement(hn,{$clickable:!!o,$highlightColor:_,variant:"body2",color:v,onClick:()=>o==null?void 0:o(e),maxTextLines:1},e.name))),t==null?void 0:t.map(p=>a.createElement(_n,{key:p.key},a.createElement(Ot,null,a.createElement(J,{size:16,type:"function",color:C})),a.createElement(wn,null,a.createElement(hn,{$clickable:!!i,$highlightColor:_,variant:"body2",color:v,onClick:()=>i==null?void 0:i(p),maxTextLines:1},p.name),c&&a.createElement(Db,{role:"button",onClick:()=>c==null?void 0:c(p)},a.createElement(U,{variant:"body2",color:_},"View details"),a.createElement(J,{type:"chevron-right",size:16,color:_}))))),n==null?void 0:n.map(p=>a.createElement(_n,{key:p.id},a.createElement(Ot,null,f({default:a.createElement(J,{size:16,type:Lo[p.source_type]??Lo.snippet,color:C}),sourceType:p.source_type})),a.createElement(hn,{$clickable:!!u,$highlightColor:_,variant:"body2",color:v,onClick:()=>u==null?void 0:u(p),maxTextLines:1},p.preview_title))),r==null?void 0:r.map(p=>a.createElement(_n,{key:p.key},a.createElement(Ot,null,a.createElement(J,{size:16,type:"template",color:C})),a.createElement(hn,{$clickable:!!d,$highlightColor:_,variant:"body2",color:v,onClick:()=>d==null?void 0:d(p),maxTextLines:1},p.name))),!!(s!=null&&s.length)&&a.createElement($b,null,a.createElement(Ot,null,a.createElement(J,{size:16,type:"activity",color:C})),a.createElement(Fb,{variant:"body2",color:v},s.map(p=>p.replace(/_/g," ")).join(" · "))),h)},Ua=b.default(U)`font-weight:400;`,hn=b.default(Ua)`${({$clickable:e,$highlightColor:t})=>e&&B.css`
|
|
395
|
+
`,Mb=({statsCallbacks:e,...t})=>(Sm(e),a.createElement(WC,{...t})),wb=(e,t,n)=>t&&Me.isWelcomeMessage(e,n)&&Me.isWelcomeMessage(t,n)?!1:!dc.isSameDay((t==null?void 0:t.createdAt)??0,e.createdAt),kb=()=>{var K;const{Template:e}=xt.useContext(),{Template:t}=_t.useContext(),{Template:n}=Hn.useContext(),{components:r}=zn.useContext(),{stringSet:s,format:o}=se(),{announceError:i,announceStatus:c}=ot(),{file:u}=re().conversation,{config:d,cache:m,agentPreviewConfigs:h,chatSDK:f,handlers:g,state:_}=le(),{userSession:y,aiAgentInfo:b,connectionError:p}=Ne(),{conversationStatsEnabled:S=!0,conversation:A,channelSource:T,messageSource:R,scrollSource:L,state:{input:D,streamAnimation:k}}=Ae(),{filteredMessages:M,shouldShowOriginalDate:P,renderAgentPreviewWelcomeMessages:F}=vb(),Y=xi(T.channel),j=ym({enabled:S}),[N,B]=l.useState(null),[U,V]=l.useState(null);l.useEffect(()=>{L.actions.onTypingIndicatorUpdate(!!Y)},[!!Y,L.actions.onTypingIndicatorUpdate]),yb(),gb({enabled:R.initialized&&R.messages.length>0});const ce=(I,Z=!1)=>{var ne;return Z?b:((ne=T.channel)==null?void 0:ne.members.find(oe=>oe.userId===I.sender.userId))??I.sender},Ie=I=>{if(I.sendingStatus==="failed"&&!D.disabled)return()=>V(I)},X=({message:I,index:Z})=>{const ne=Sc(I),oe=M[Z-1],Re=M[Z+1],De=M[M.length-1],$=I===De,x=st(I,b.userId),w=!(b.isUserFeedbackEnabled&&x&&!Me.isWelcomeMessage(I)),O=Ac(I,oe,Re,w),z=wb(I,oe,b.userId)&&P(Z),q=Ce=>{B({files:Ce.files.map(Te=>({...Te,timestamp:I.createdAt})),index:Ce.index})},ee=Ce=>{q({files:[Ce],index:0})},W=z?a.createElement(r.DateSeparator,{role:"listitem",style:{margin:"16px 0"},date:I.createdAt}):null,pe={data:I.data,maxBodyWidth:_.expanded?te.WIDE_BODY_MAX_WIDTH:void 0,extendedMessagePayload:I.extendedMessagePayload,createdAt:I.createdAt,groupType:O,onClickMedia:ee,onClickMediaFiles:q,onClickFile:g.onClickLink,onClickCTA:g.onClickLink,onClickCitation:Ce=>g.onClickLink({url:Ce.link}),onClickLink:g.onClickLink},Xe=()=>{if(Oe.isOutgoing(I,y.userId))return"outgoingmessage";if(Oe.isIncoming(I,y.userId))return"incomingmessage"},ae=I.createdAt!=null&&I.createdAt!==0?o(I.createdAt,s.DATE_FORMAT__MESSAGE_TIMESTAMP):void 0,he=(()=>{var Te,ve,$e,Pe,fe,Ue;const Ce=(Te=I.message)==null?void 0:Te.trim();if(I.isFileMessage()){const Be=((ve=I.name)==null?void 0:ve.trim())||"";return Qn({markdownText:Ce,comparisonText:Be,plainText:u.label(Be,I.type)})}if(I.isMultipleFilesMessage()){const Be=((fe=(Pe=($e=I.fileInfoList)==null?void 0:$e[0])==null?void 0:Pe.fileName)==null?void 0:fe.trim())||"",nn=((Ue=I.fileInfoList)==null?void 0:Ue.length)??0;return Qn({markdownText:Ce,comparisonText:Be,plainText:nn>0?s.CONVERSATION_LIST__MULTIPLE_FILES_COUNT(nn):""})}return Ce?Qn({markdownText:Ce}):Ni("")})(),_e=(()=>{if(Oe.isAdmin(I))return Dt({message:he.text,messageFormat:he.format,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER});if(Oe.isOutgoing(I,y.userId))return Dt({sender:s.A11Y_MESSAGE_SENDER_YOU,message:he.text,messageFormat:"plain",time:ae,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER});if(Oe.isIncoming(I,y.userId))return Dt({sender:ce(I,x).nickname,message:he.text,messageFormat:he.format,time:ae,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER})})(),Ee=(()=>{var Ce,Te;if(Oe.isAdmin(I))return Oe.isCSAT(I)?A?a.createElement(n,{...pe,...A,isResolvedWhenDeterminedByUser:tl(A),messageType:"admin.csat",announceError:i,announceStatus:c,onSubmitCSAT:async ve=>{var $e;await(($e=T.channel)==null?void 0:$e.submitCSAT(ve))},onScrollToBottom:()=>L.actions.scrollToBottom()}):null:a.createElement(n,{...pe,messageType:"admin",message:I.message});if(Oe.isSteward(I)){const ve=j({message:I,isBotMessage:x,aiAgentUserId:b.userId});return a.createElement(Mb,{steward:I.extendedMessagePayload.steward,statsCallbacks:ve,onCancelSteward:async()=>{await f.aiAgent.cancelStewardTask({channelUrl:I.channelUrl,messageId:I.messageId})}})}if(Oe.isOutgoing(I,y.userId)){const ve={...pe,message:I.message,sender:ce(I),sendingStatus:I.sendingStatus,onClickFailedMessage:Ie(I)};if(I.isUserMessage())return a.createElement(e,{messageType:"user",...ve});if(I.isFileMessage()){const[$e,Pe]=((Ce=I.metaArrays.find(fe=>fe.key===Xo))==null?void 0:Ce.value)??[];return a.createElement(e,{messageType:"file",file:I,metadata:{aspectRatio:$e&&Pe?`${$e}/${Pe}`:"1/1",localFile:(Te=I.messageParams)==null?void 0:Te.file},...ve})}if(I.isMultipleFilesMessage()){const{files:$e,metadata:Pe}=vo(I);return a.createElement(e,{messageType:"multipleFiles",files:$e,metadata:Pe,...ve})}}if(Oe.isIncoming(I,y.userId)){const ve=Me.isStreaming(I),$e=j({message:I,isBotMessage:x,aiAgentUserId:b.userId}),Pe={...pe,statsCallbacks:$e,sender:ce(I,x),message:I.message,suggestedRepliesVisible:$,suggestedRepliesDirection:h==null?void 0:h.suggestedRepliesDirection,isBotMessage:x,isStreaming:ve,isHandedOff:rt(T.channel),isConversationClosed:He(T.channel),isFeedbackEnabled:b.isUserFeedbackEnabled,isFeedbackCommentEnabled:b.isUserFeedbackCommentOptionEnabled,isSenderAvatarVisible:d.conversation.list.senderAvatarEnabled,deferredMarkdownElements:d.conversation.list.deferredMarkdownElements,onClickSuggestedReply:async({reply:fe})=>{R.sendUserMessage({message:fe})},onRequestMessageTemplate:async fe=>{const{template:Ue}=await f.aiAgent.getMessageTemplate(fe);return m.template.set(fe,Ue),Ue},onGetCachedMessageTemplate:fe=>m.template.get(fe),onHandleTemplateInternalAction:fe=>{if(fe.type==="internal"&&fe.internalData){const{method:Ue,payload:Be}=fe.internalData;Ue==="message.send"&&(Be!=null&&Be.message)&&R.sendUserMessage({message:Be.message})}},onFeedbackUpdate:fe=>{const Ue={messageId:I.messageId,channelUrl:I.channelUrl};if(!fe)return f.aiAgent.deleteMessageFeedback(Ue);const Be={...Ue,rating:d_(fe.rating),comment:fe.comment};return Me.hasFeedback(I)?f.aiAgent.updateMessageFeedback(Be):f.aiAgent.createMessageFeedback(Be)},onSubmitForm:({key:fe,data:Ue})=>f.aiAgent.submitForm({messageId:I.messageId,channelUrl:I.channelUrl,formKey:fe,formData:Ue}),onCancelForm:({key:fe})=>f.aiAgent.cancelForm({messageId:I.messageId,channelUrl:I.channelUrl,formKey:fe}),onSendChallengeAction:({key:fe,requestId:Ue,action:Be,data:nn})=>f.aiAgent.sendChallengeAction({channelUrl:I.channelUrl,key:fe,requestId:Ue,action:Be,data:nn}),onStreamAnimationStart:()=>{k.start(I.messageId)},onStreamAnimationProgress:()=>{L.actions.onStreamingUpdate(!0)},onStreamAnimationComplete:()=>{k.stop(I.messageId),L.actions.onStreamingUpdate(!1)}};if(I.isUserMessage())return a.createElement(t,{messageType:"user",...Pe});if(I.isFileMessage())return a.createElement(t,{messageType:"file",file:I,...Pe});if(I.isMultipleFilesMessage()){const{files:fe}=vo(I);return a.createElement(t,{messageType:"multipleFiles",files:fe,...Pe})}}})();return a.createElement(l.Fragment,{key:ne},W,a.createElement("div",{id:`${Ge}-message-item`,role:"listitem",tabIndex:-1,"aria-label":_e,"data-message-listitem":"","data-layout-id":Xe()},Ee))};return a.createElement(Lb,{id:`${Ge}-message-list`},a.createElement(Ug,{ref:L.ref,onScroll:L.props.onScroll,stackDirection:h==null?void 0:h.messageStackDirection,messages:M,renderMessage:X,onLoadPrev:R.loadPrevious,onLoadNext:R.loadNext,depsForResetScrollPositionToBottom:[R.initialized,R.messages.length!==0],bottomSpacerHeight:L.state.bottomSpace,"aria-label":s.A11Y_MESSAGE_LIST,loading:!R.initialized||!T.channel,empty:M.length===0&&!Y,error:!!(p||T.error),LoadingComponent:a.createElement(Ut,{type:"loading"}),EmptyComponent:(()=>{const I=F();return I?a.createElement("div",{style:{width:"100%"}},I):a.createElement(Ut,{type:"noMessages",label:s.PLACE_HOLDER__NO_MESSAGES})})(),ErrorComponent:a.createElement(Ut,{type:"error",label:(p==null?void 0:p.message)??((K=T.error)==null?void 0:K.message),action:T.error?{label:s.RETRY,onClick:()=>T.refetch()}:void 0}),messageTopArea:a.createElement(a.Fragment,null,a.createElement(Sb,{style:{marginTop:16}}),F()),messageBottomArea:a.createElement(a.Fragment,null,Y&&a.createElement("div",{id:`${Ge}-message-item`,role:"listitem",tabIndex:-1,"aria-label":Dt({sender:Y.user.nickname,message:s.A11Y_TYPING_INDICATOR,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER}),"data-message-listitem":"",style:{marginTop:M.length===0?8:0}},a.createElement(t,{isTyping:!0,isBotMessage:Y.isBot,sender:Y.user,thinkingMessage:Y.thinkingMessage,messageType:"user",groupType:"single",message:"",isSenderAvatarVisible:d.conversation.list.senderAvatarEnabled})),d.conversation.list.isTalkToAgentViewEnabled&&a.createElement(Ib,null)),overlayArea:a.createElement(a.Fragment,null,d.conversation.list.newMessageIndicatorEnabled&&L.state.isAwayFromBottom&&R.newMessages.length>0&&a.createElement(Ob,{label:s.SCROLL_TO_NEW_MESSAGES_LABEL(R.newMessages),onClick:()=>L.actions.scrollToBottom()}),L.state.isAwayFromBottom&&R.newMessages.length===0&&!Y&&a.createElement(r.ScrollToBottomButton,{onClick:()=>L.actions.scrollToBottom(),style:{position:"absolute",bottom:12,insetInlineEnd:16}}))}),N&&a.createElement(Kg,{files:N.files,initialIndex:N.index,onClose:()=>B(null),visible:!0}),U&&a.createElement(lt,{visible:!0,onClose:()=>V(null),"aria-label":s.A11Y_FAILED_MESSAGE_OPTIONS},a.createElement(lt.ActionItem,{onClick:()=>{R.resendMessage(U),V(null)}},s.FAILED_MESSAGE_RESEND),a.createElement(lt.ActionItem,{destructive:!0,onClick:()=>{R.deleteMessage(U),V(null)}},s.FAILED_MESSAGE_REMOVE)))},Lb=C.default.div`overflow-y:hidden;display:flex;flex:1;position:relative;`,Ob=C.default(rb)`position:absolute;bottom:12px;left:50%;transform:translateX(-50%);`,Nb=()=>a.createElement(kb,null),Lo={file:"attach",snippet:"snippet",site:"website",sb_sprinklr:"sprinklr",sb_salesforce:"salesforce",sb_confluence:"confluence",sb_zendesk:"zendesk",sb_desk:"snippet"},Pa=({actionbook:e,functionCalls:t,groundedness:n,agentMessageTemplates:r,flaggedTypes:s,onClickActionbook:o,onClickFunctionCall:i,onClickFunctionCallDetail:c,onClickGroundedness:u,onClickAgentMessageTemplate:d,topContent:m,bottomContent:h,renderCustomGroundednessIcon:f=_=>_.default,style:g={}})=>{const{iconColor:_="#000000",textColor:y="#000000",highlightColor:b=Bt.DEFAULT_PRIMARY}=g;return a.createElement(Oo,null,m,e&&a.createElement(Oo,null,a.createElement(wn,null,a.createElement(Ot,null,a.createElement(J,{size:16,type:"actionbook",color:_})),a.createElement(hn,{$clickable:!!o,$highlightColor:b,variant:"body2",color:y,onClick:()=>o==null?void 0:o(e),maxTextLines:1},e.name))),t==null?void 0:t.map(p=>a.createElement(_n,{key:p.key},a.createElement(Ot,null,a.createElement(J,{size:16,type:"function",color:_})),a.createElement(wn,null,a.createElement(hn,{$clickable:!!i,$highlightColor:b,variant:"body2",color:y,onClick:()=>i==null?void 0:i(p),maxTextLines:1},p.name),c&&a.createElement(Db,{role:"button",onClick:()=>c==null?void 0:c(p)},a.createElement(H,{variant:"body2",color:b},"View details"),a.createElement(J,{type:"chevron-right",size:16,color:b}))))),n==null?void 0:n.map(p=>a.createElement(_n,{key:p.id},a.createElement(Ot,null,f({default:a.createElement(J,{size:16,type:Lo[p.source_type]??Lo.snippet,color:_}),sourceType:p.source_type})),a.createElement(hn,{$clickable:!!u,$highlightColor:b,variant:"body2",color:y,onClick:()=>u==null?void 0:u(p),maxTextLines:1},p.preview_title))),r==null?void 0:r.map(p=>a.createElement(_n,{key:p.key},a.createElement(Ot,null,a.createElement(J,{size:16,type:"template",color:_})),a.createElement(hn,{$clickable:!!d,$highlightColor:b,variant:"body2",color:y,onClick:()=>d==null?void 0:d(p),maxTextLines:1},p.name))),!!(s!=null&&s.length)&&a.createElement($b,null,a.createElement(Ot,null,a.createElement(J,{size:16,type:"activity",color:_})),a.createElement(Fb,{variant:"body2",color:y},s.map(p=>p.replace(/_/g," ")).join(" · "))),h)},Ua=C.default(H)`font-weight:400;`,hn=C.default(Ua)`${({$clickable:e,$highlightColor:t})=>e&&G.css`
|
|
396
396
|
cursor: pointer;
|
|
397
397
|
text-decoration: underline;
|
|
398
398
|
&:hover {
|
|
399
399
|
color: ${t};
|
|
400
400
|
}
|
|
401
401
|
`}
|
|
402
|
-
`,Ot=
|
|
402
|
+
`,Ot=C.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,wn=C.default.div`display:flex;gap:8px;align-items:center;word-break:break-word;`,Db=C.default(wn)`cursor:pointer;gap:4px;`,_n=C.default(wn)`flex-direction:row;align-items:center;`,$b=C.default(_n)`align-items:flex-start;max-width:100%;`,Fb=C.default(Ua)`min-width:0;`,Oo=C.default.div`display:flex;gap:4px;flex-direction:column;align-items:flex-start;`,Ba=be("DashboardTester"),Pb=Ba.Provider;function Ub({testerType:e,origin:t,children:n}){return a.createElement(Pb,{value:{testerType:e,origin:t}},e&&a.createElement(Bb,null),n)}const Ha=Ba.useContext,Bb=()=>a.createElement(a.Fragment,null,a.createElement(_t.MessageLogs,{component:No}),a.createElement(xt.MessageLogs,{component:No})),No=({extendedMessagePayload:e={}})=>{const{handlers:t}=le(),{manual:n,groundedness:r,function_calls:s,agent_message_templates:o,flagged_types:i,is_thinking:c}=e,u=!!n||[r,s,o,i].some(d=>d==null?void 0:d.length);return c||!u?a.createElement(a.Fragment,null):a.createElement(Hb,null,a.createElement(Gb,{$width:4}),a.createElement(Pa,{actionbook:n,functionCalls:s,groundedness:r,agentMessageTemplates:o,flaggedTypes:i,onClickFunctionCallDetail:t==null?void 0:t.onFunctionCallDetailClick,style:{iconColor:E.themedColor.textHighEmphasis,textColor:E.themedColor.textHighEmphasis,barColor:E.themedColor.textDisabled},topContent:a.createElement(H,{variant:"caption4",color:E.themedColor.textLowEmphasis},"Only visible in the tester")}))},Hb=C.default.div`display:flex;gap:16px;margin:6px ${te.HORIZONTAL_PADDING}px 4px ${te.HORIZONTAL_PADDING+te.AVATAR_SIZE}px;align-self:stretch;`,Gb=C.default.div`width:${({$width:e})=>e}px;background-color:${E.themedColor.textDisabled};border-radius:100px;flex-shrink:0;`,zb=()=>{var s;const{origin:e}=Ha(),{appId:t,aiAgentId:n}=ke(),{channelSource:r}=Ae();return(s=r.channel)!=null&&s.conversation?a.createElement(Vb,null,a.createElement(yr,{style:{gap:4}},a.createElement(J,{color:E.themedColor.textLowEmphasis,size:12,type:"show"}),a.createElement(H,{as:"i",color:E.themedColor.textLowEmphasis,variant:"caption2"},"Only visible in the tester")),a.createElement(yr,{role:"button",style:{gap:4},onClick:()=>{var u,d;const o=e??window.location.origin,i=(d=(u=r.channel)==null?void 0:u.conversation)==null?void 0:d.id,c=`${o}/ai-agent/${t}/${n}/evaluate/conversations/${i}`;navigator.clipboard.writeText(c)}},a.createElement(H,{variant:"body3",color:E.themedColor.textHighEmphasis},"Copy ",a.createElement("span",{style:{color:E.themedColor.primary}},"conversation link")),a.createElement(J,{color:E.themedColor.primary,size:14,type:"copy"}))):null},yr=C.default.div`display:flex;justify-content:center;align-items:center;`,Vb=C.default(yr)`flex-direction:column;padding-block:16px;background-color:${E.themedColor.bg_100_500};gap:8px;`,qb=(e,t)=>{const n=[],r=[],s=[];for(const o of e){const i=t.isSupportedMimeType(o.type),c=o.size<=t.getUploadSizeLimit(o.type);i&&c?n.push(o):i?r.push(o):s.push(o)}return{passed:n,failedBySize:r,failedByType:s}},Ga=l.createContext(void 0),Kb=({children:e})=>{var Y,j;const{chatSDK:t}=le(),{createAttachmentRules:n}=Ne(),{stringSet:r}=se(),{channelSource:s,state:o}=Ae(),[i,c]=l.useState([]),{announceError:u}=Kr(),[d,m]=l.useState(null),h=n({channel:s.channel,uploadSizeLimit:(Y=t.appInfo)==null?void 0:Y.uploadSizeLimit}),f=((j=o==null?void 0:o.input)==null?void 0:j.disabled)??!1,g=h.isEnabled(),_=h.maxAttachmentCount,y=()=>m(null),b=N=>m(N),p=()=>{b({title:r.FILE_UPLOAD_NOTIFICATION__COUNT_LIMIT.replace("%d",_.toString())})},S=N=>{b({title:r.FILE_UPLOAD_NOTIFICATION__SIZE_LIMIT.replace("%d",N.toString())}),u({type:"fileSizeExceeded",maxSizeMB:N})},A=N=>{b({title:r.FILE_UPLOAD_NOTIFICATION__FILES_EXCLUDED_BY_VALIDATION.replace("%d",N.toString())})},T=N=>N.map(B=>({file:B,preview:{url:URL.createObjectURL(B),type:B.type,name:B.name}})),R=N=>{c(B=>[...B,...T(N)])},L=N=>{c(B=>(B.forEach(U=>URL.revokeObjectURL(U.preview.url)),T(N)))},D=N=>{const{passed:B,failedBySize:U,failedByType:V}=qb(N,h),ce=U.length+V.length,Ie=N.length===1?U[0]:void 0;return Ie?S(h.getUploadSizeLimitInMB(Ie.type)):ce>0&&A(ce),B},k=N=>{const B=D(N.files);B.length!==0&&(N.type==="append"?R(B):L(B))},M=N=>{if(!g||f||!yu(N))return;const B=Au({currentFiles:i.map(({file:U})=>U),incomingFiles:N,maxAttachmentCount:_});switch(B.type){case"reject":p();return;case"confirm_replace":b({title:r.FILE_UPLOAD_REPLACE_ALERT__TITLE,description:r.FILE_UPLOAD_REPLACE_ALERT__DESCRIPTION,confirmText:r.BUTTON__OK,cancelText:r.BUTTON__CANCEL,onConfirm:()=>k(B.action)});return;case"apply":k(B.action);return}},P=N=>{c(B=>{var V;const U=(V=B[N])==null?void 0:V.preview;return U&&URL.revokeObjectURL(U.url),B.filter((ce,Ie)=>Ie!==N)})},F=()=>{c(N=>(N.forEach(B=>URL.revokeObjectURL(B.preview.url)),[]))};return a.createElement(Ga.Provider,{value:{files:i,addFiles:M,removeFile:P,clearFiles:F,isFileUploadEnabled:g,acceptableMimeTypes:h.supportedMimeTypes,maxAttachmentCount:h.maxAttachmentCount,showFileUploadAlert:b}},e,a.createElement(Pn,{visible:!!d,...d??{},onClose:y}))},rs=()=>{const e=l.useContext(Ga);if(!e)throw new Error("useFileUpload must be used within FileUploadProvider");return e};function Yb({elementRef:e,ready:t,onRestore:n}){const r=l.useRef(!1);l.useEffect(()=>{var i;!t||!r.current||(n==null||n(),(i=e.current)==null||i.focus(),r.current=!1)},[t,n]);const s=l.useCallback(()=>{r.current=!0},[]),o=l.useCallback(()=>{r.current=!1},[]);return{requestRestore:s,cancelRestore:o}}function Wb({blurred:e,elementRef:t,document:n=window.document,onRecoverFocus:r}){const s=l.useRef(!1);e&&t.current&&n.activeElement===t.current&&(s.current=!0),l.useLayoutEffect(()=>{var o;!e&&s.current&&(r==null||r(),(o=t.current)==null||o.focus(),s.current=!1)},[e,r])}const jb=()=>{const{announceError:e}=ot();return l.useCallback(t=>{e({type:"sendFailed"},t)},[e])},Xb=1e3,Zb=(e,t,n)=>{const{announcementsEnabled:r,setIsSuppressed:s}=ot(),o=n??!0,i=l.useRef(!1),c=l.useRef(void 0),u=l.useCallback(d=>{var m;d&&o&&(i.current=!0,c.current=e,e==null||e.startTyping()),d||(i.current&&o&&((m=c.current)==null||m.endTyping()),i.current=!1,c.current=void 0),s(d)},[e,s,o]);l.useLayoutEffect(()=>{s(i.current)},[r,s]),im(t,u,{enabled:o,idleMs:Xb})},Jb=({enabled:e=!0,focusRoot:t})=>{const[n,r]=l.useState(!1),s=l.useRef(!1),o=l.useRef(!1);l.useEffect(()=>{if(!e){r(!1);return}const d=h=>{const f=h;f.metaKey||f.altKey||f.ctrlKey||(s.current=!0)},m=()=>{s.current=!1,r(!1)};return t.addEventListener("keydown",d),t.addEventListener("pointerdown",m),()=>{t.removeEventListener("keydown",d),t.removeEventListener("pointerdown",m)}},[e,t]);const i=l.useCallback(()=>{if(o.current){o.current=!1,r(!1);return}r(s.current)},[]),c=l.useCallback(()=>{r(!1)},[]),u=l.useCallback(()=>{o.current=!0,r(!1)},[]);return{isFocusVisible:n,suppressNextFocusVisible:u,focusHandlers:{onFocus:i,onBlur:c}}},Qb=C.default.div`&::-webkit-scrollbar{display:none;}overflow-x:auto;display:flex;flex-direction:row;gap:10px;padding:8px 16px;background-color:transparent;`,ev=C.default.div`display:flex;flex-shrink:0;position:relative;margin-block-start:8px;border-radius:12px;height:64px;img{border-radius:12px;object-fit:cover;width:64px;-webkit-user-drag:none;}&:hover button,&:focus-within button{opacity:1;}`,tv=C.default.button`display:flex;align-items:center;justify-content:center;position:absolute;inset-inline-end:-8px;inset-block-start:-8px;cursor:pointer;border-radius:50%;border:none;padding:0;opacity:${({$mobile:e})=>e?1:0};transition:opacity 0.12s ease-in-out;${Q.light`
|
|
403
403
|
background-color: ${E.color.background50};
|
|
404
404
|
`}
|
|
405
405
|
${Q.dark`
|
|
@@ -424,7 +424,7 @@
|
|
|
424
424
|
circle {
|
|
425
425
|
stroke: ${E.themedColor.bg_50_600};
|
|
426
426
|
}
|
|
427
|
-
`,nv=()=>{const e=Jt(),{conversation:t}=re(),{files:n,removeFile:r,isFileUploadEnabled:s}=rs();return s&&n.length>0?a.createElement(Qb,null,n.map(({preview:{type:i,name:c,url:u}},d)=>{let m=a.createElement(Zr,{name:c,mimeType:i,type:Ir(c,i),selected:!0});return i.startsWith("image/")&&(m=a.createElement("img",{alt:t.file.label(c,i,!0),src:u})),a.createElement(ev,{key:u},a.createElement(tv,{type:"button",...t.file.removeButton(c).props,$mobile:e,onClick:()=>r(d)},a.createElement(J,{type:"close-filled",color:E.themedColor.textMidEmphasis})),m)})):null},rv={textArea:
|
|
427
|
+
`,nv=()=>{const e=Jt(),{conversation:t}=re(),{files:n,removeFile:r,isFileUploadEnabled:s}=rs();return s&&n.length>0?a.createElement(Qb,null,n.map(({preview:{type:i,name:c,url:u}},d)=>{let m=a.createElement(Zr,{name:c,mimeType:i,type:Ir(c,i),selected:!0});return i.startsWith("image/")&&(m=a.createElement("img",{alt:t.file.label(c,i,!0),src:u})),a.createElement(ev,{key:u},a.createElement(tv,{type:"button",...t.file.removeButton(c).props,$mobile:e,onClick:()=>r(d)},a.createElement(J,{type:"close-filled",color:E.themedColor.textMidEmphasis})),m)})):null},rv={textArea:G.css`min-height:40px;height:40px;font-size:16px;line-height:24px;`},za=C.default.button`all:unset;cursor:pointer;display:flex;align-items:center;justify-content:center;width:32px;height:32px;${xe}`,Do=C.default.div`width:100%;position:relative;background-color:${({theme:e})=>e.colors.messageInput.background};border-radius:20px;`,$o=C.default.div`display:flex;flex-direction:row;align-items:flex-end;position:relative;`,Fo=C.default.textarea`all:unset;display:block;flex:1;min-width:0;padding-top:8px;padding-bottom:8px;padding-inline-start:16px;padding-inline-end:12px;box-sizing:border-box;font-size:14px;line-height:20px;color:${({theme:e})=>e.colors.messageInput.text};resize:none;width:100%;height:${qi}px;overflow-wrap:break-word;white-space:pre-wrap;overflow-x:hidden;${aa&&rv.textArea};${({$focusVisible:e})=>e&&G.css`
|
|
428
428
|
outline: 2px solid ${E.themedColor.primary};
|
|
429
429
|
outline-offset: 2px;
|
|
430
430
|
`}
|
|
@@ -440,18 +440,18 @@
|
|
|
440
440
|
}
|
|
441
441
|
}
|
|
442
442
|
|
|
443
|
-
${({$blocked:e})=>e&&
|
|
444
|
-
`,sv=
|
|
443
|
+
${({$blocked:e})=>e&&G.css`cursor:not-allowed;&::placeholder{color:${E.themedColor.textDisabled};}`}
|
|
444
|
+
`,sv=C.default.input`display:none;`;C.default.div`display:flex;align-items:center;gap:24px;`;const ov=C.default(za)`flex-shrink:0;border-radius:8px;&:disabled{cursor:not-allowed;}&:not(:disabled){&:hover{background-color:${E.themedColor.bg_100_500};path{fill:${E.themedColor.textHighEmphasis};}}&:active{background-color:${E.themedColor.bg_200_400};}}`,Po=C.default.div`padding:10px 16px 10px 12px;position:relative;display:flex;align-items:center;gap:8px;`,Uo=e=>e.startsWith("image/"),Bo=({disabled:e})=>{const{stringSet:t}=se(),{conversation:n}=re(),{config:r}=le(),s=l.useRef(null),o=l.useRef(null),[i,c]=l.useState(!1),{addFiles:u,isFileUploadEnabled:d,acceptableMimeTypes:m,showFileUploadAlert:h}=rs(),f=m.includes(lr),g=f?["image/*"]:m.filter(Uo),_=f?[lr]:m.filter(D=>!Uo(D)),y=r.conversation.input.gallery.photoEnabled,b=r.conversation.input.fileEnabled,p=()=>f||g.length>0,S=()=>f||_.length>0,A=D=>{const k=D.currentTarget.files;k&&u(Array.from(k)),D.target.value=""},T=()=>{c(!0)},R=l.useMemo(()=>{const D=[];return y&&D.push({type:"image",icon:"photo",label:t.FILE_UPLOAD_PHOTOS,accept:g.join(","),inputRef:s,onSelect:()=>{if(!p()){h({title:t.FILE_UPLOAD_NO_SUPPORTED_FILES});return}c(!1),setTimeout(()=>{var k;return(k=s.current)==null?void 0:k.click()},100)}}),b&&D.push({type:"file",icon:"document",label:t.FILE_UPLOAD_FILES,accept:m.join(","),inputRef:o,onSelect:()=>{if(!S()){h({title:t.FILE_UPLOAD_NO_SUPPORTED_FILES});return}c(!1),setTimeout(()=>{var k;return(k=o.current)==null?void 0:k.click()},100)}}),D},[g,m,t,y,b]);if(!d)return null;const L={attach:n.messageInput.attachFileButton()};return a.createElement(a.Fragment,null,a.createElement(ov,{...L.attach.props,disabled:e,onClick:T},a.createElement(J,{type:"add",color:e?E.themedColor.textDisabled:E.color.primary.main,size:20}),L.attach.descriptionNode),R.map(D=>a.createElement(sv,{key:D.type,type:"file",ref:D.inputRef,multiple:D.type==="image",onChange:A,accept:D.accept})),a.createElement(lt,{visible:i,onClose:()=>c(!1),"aria-label":t.A11Y_FILE_UPLOAD_OPTIONS},R.map(D=>a.createElement(lt.ActionItem,{key:D.type,onClick:D.onSelect,icon:D.icon},D.label))))},iv=()=>{const e=l.useRef(null),[t,n]=l.useState(""),{stringSet:r}=se(),{conversation:s}=re(),{rootElement:o}=le(),i=ut(o),{focusHandlers:c,isFocusVisible:u,suppressNextFocusVisible:d}=Jb({focusRoot:i}),{channelSource:m,messageSource:h,state:f}=Ae(),{files:g,addFiles:_,clearFiles:y}=rs(),b=jb(),{focusPolicy:p,disabled:S,disabledBy:A}=f.input,T=p==="preserve",R=p==="release",L=(()=>{if(!S)return r.MESSAGE_INPUT__PLACE_HOLDER;switch(A){case"form_active":return r.FORM_PLACEHOLDER;case"ai_responding":return r.MESSAGE_INPUT__PLACE_HOLDER__WAIT_AI_AGENT_RESPONSE;case"suggested_replies":return r.MESSAGE_INPUT__PLACE_HOLDER__SUGGESTED_REPLIES;case"steward":return r.MESSAGE_INPUT__PLACE_HOLDER__STEWARD;case"system":return r.MESSAGE_INPUT__PLACE_HOLDER__DISABLED;case"reconnecting":return r.MESSAGE_INPUT__PLACE_HOLDER__RECONNECTING;case"unavailable":case"conversation_closed":default:return r.MESSAGE_INPUT__PLACE_HOLDER__DISABLED}})();rg({onDropFiles:I=>{_(I)}}),Wb({blurred:R,elementRef:e,document:i,onRecoverFocus:()=>{d()}}),Zb(m.channel,t,!S);const D=t.trim().length>0,k=g.length>0,M=!S&&(D||k),P={input:s.messageInput.textInput(r.A11Y_MESSAGE_INPUT),send:s.messageInput.sendButton()},F=()=>{e.current&&(e.current.value="",e.current.style.height=""),y(),n("")},Y=()=>{var I;d(),(I=e.current)==null||I.focus()},{requestRestore:j,cancelRestore:N}=Yb({elementRef:e,ready:T,onRestore:d}),B=I=>{N(),b(I)},U=()=>{N()},V=async I=>{try{await I(),U()}catch{B(e.current)}},ce=async()=>{if(S)return;const I=t.trim();if(!I&&!g.length)return;const Z=[...g];if(j(),F(),Y(),Z.length===0){await V(()=>h.sendUserMessage({message:I}));return}if(Z.length===1)await V(()=>h.sendFileMessage({message:I,file:Z[0].file}));else{const ne=Z.map(({file:oe})=>({file:oe}));await V(()=>h.sendMultipleFilesMessage({message:I,fileInfoList:ne}))}},Ie=I=>{const Z=Array.from(I.clipboardData.files);Z.length>0&&(I.preventDefault(),_(Z))},X=I=>{I.key!=="Enter"||I.nativeEvent.isComposing||I.shiftKey||(I.preventDefault(),ce())},K=I=>{if(S){e.current&&(e.current.value=t);return}if(e.current){e.current.style.height="";const Z=Math.min(fh,e.current.scrollHeight);qi<Z&&(e.current.style.height=`${Z}px`)}n(I.target.value)};return R?a.createElement(Po,null,a.createElement(Bo,{disabled:!0}),a.createElement(Do,null,a.createElement($o,null,a.createElement(Fo,{rows:1,...P.input.props,disabled:!0,placeholder:L,$blocked:!0,$focusVisible:!1,"data-focus-visible":"false"})))):a.createElement(Po,{"data-message-composer":""},a.createElement(Bo,{disabled:S}),a.createElement(Do,null,a.createElement(nv,null),a.createElement($o,null,a.createElement(Fo,{ref:e,rows:1,...P.input.props,readOnly:T,"aria-disabled":T?"true":void 0,placeholder:L,maxLength:5e3,$blocked:S,$focusVisible:u,"data-focus-visible":u?"true":"false",onKeyDown:X,onChange:K,onFocus:c.onFocus,onBlur:c.onBlur,onPaste:Ie}))),M&&a.createElement(za,{...P.send.props,onClick:()=>ce()},a.createElement(J,{type:"send",color:E.color.primary.main,size:20}),P.send.descriptionNode))},av=C.default.div`padding:8px 16px;text-align:center;word-break:break-word;white-space:pre-wrap;line-height:1.43;letter-spacing:-0.2px;font-size:14px;font-weight:400;color:${E.themedColor.textLowEmphasis};&& a{font-weight:700;text-decoration:none;${Q.light`
|
|
445
445
|
color: ${E.color.information.light};
|
|
446
446
|
`};
|
|
447
447
|
${Q.dark`
|
|
448
448
|
color: ${E.color.information.main};
|
|
449
449
|
`};
|
|
450
450
|
}
|
|
451
|
-
`,cv=l.lazy(()=>Promise.resolve().then(()=>require("./cjs/VvejebHE.cjs")).then(e=>({default:e.MarkdownText}))),lv=()=>{const{aiAgentInfo:e,userSession:t}=De(),{handlers:n}=ce(),{messageSource:r,channelSource:s}=Ae(),[o,i]=l.useState(null),c=Ur("special-notice",s.channel),u=l.useCallback(()=>s.channel?c?r.messages.some(d=>st(d,(t==null?void 0:t.userId)??"")):!0:null,[s.channel,c,r.messages,t==null?void 0:t.userId]);return l.useEffect(()=>{o||i(u())},[u,o]),o||!e.specialNotice?null:a.createElement(av,null,a.createElement(cv,{onClickLink:n.onClickLink},e.specialNotice))},uv=()=>a.createElement(dv,null,a.createElement(lv,null),a.createElement(Kb,null,a.createElement(iv,null))),dv=b.default.div`z-index:0;border:none;width:100%;`,mv=()=>{var s;const{testerType:e}=Ha(),{channelSource:t}=Ae(),n=He(t.channel),r=!!e&&((s=t.channel)==null?void 0:s.isAIAgent);return n&&r?a.createElement(zb,null):a.createElement(uv,null)},Va=({start:e,title:t,titleAlign:n="start",end:r,containerProps:s})=>{const o=l.useRef(null),i=l.useRef(null),[c,u]=l.useState(0),[d,m]=l.useState(0);return l.useLayoutEffect(()=>{o.current&&u(o.current.offsetWidth),i.current&&m(i.current.offsetWidth)},[e,r]),a.createElement(hv,{...s},a.createElement(fv,null,n==="center"&&t&&a.createElement(gv,{$sideWidth:Math.max(c,d)},a.createElement(pv,null,t)),a.createElement(_v,null,a.createElement(Ev,{ref:o},e),(n==="start"||n==="end")&&t&&a.createElement(bv,{$align:n,$hasStart:!!e,$hasEnd:!!r},t),a.createElement(Cv,{ref:i},r))))},hv=b.default.div`position:relative;width:100%;background-color:${({theme:e})=>e.colors.base.headerBackground};border-bottom:1px solid ${E.themedColor.textDisabled};`,fv=b.default.div`position:relative;height:56px;padding:11px 12px;`,gv=b.default.div`position:absolute;left:${({$sideWidth:e})=>e}px;right:${({$sideWidth:e})=>e}px;top:0;bottom:0;display:flex;align-items:center;justify-content:center;`,pv=b.default.div`max-width:100%;overflow:hidden;`,_v=b.default.div`display:flex;flex-direction:row;align-items:center;justify-content:space-between;height:100%;z-index:1;`,Ev=b.default.div`flex-shrink:0;display:flex;align-items:center;`,Cv=b.default.div`flex-shrink:0;display:flex;align-items:center;`,bv=b.default.div`flex:1;overflow:hidden;display:flex;align-items:${({$align:e})=>e==="start"?"flex-start":"flex-end"};margin-left:${({$hasStart:e})=>e?8:0}px;margin-right:${({$hasEnd:e})=>e?8:0}px;`,Rt=(e=16)=>Jt()?e*1.5:e,vv=()=>{const{state:e}=ce(),{messenger:t}=re(),n=Rt(),r=()=>{e.setOpened(!1)};return a.createElement(it,{...t.closeButton().props,type:"close",size:n,onClick:r})},yv=()=>{const{enableCloseConversationButton:e,dispatcher:t}=ce(),{channelSource:n}=Ae(),{conversation:r}=re(),s=n.channel,o=Rt(),i=(s==null?void 0:s.isAIAgent)&&e,c=!Rr(s);if(!i)return null;const u={close:r.header.closeConversationButton()},d=async()=>{s&&await t.send(ct.CloseConversation({channelUrl:s.url}))};return a.createElement(a.Fragment,null,a.createElement(it,{...u.close.props,type:"mute",size:o,disabled:c,onClick:d}),u.close.descriptionNode)},Sv=()=>{const{state:e,enableExpandButton:t}=ce(),{messenger:n}=re(),r=Rt();return t?a.createElement(it,{...n.expandButton(e.expanded).props,type:e.expanded?"collapse":"expand",size:r,onClick:()=>e.setExpanded(!e.expanded)}):null},Av=({label:e,children:t,position:n="top",disabled:r})=>r?t:a.createElement(Sr,null,t,a.createElement(xv,{$position:n},a.createElement(Rv,{variant:"caption1"},e),a.createElement(Tv,{$position:n}))),Tv=({$position:e})=>a.createElement("svg",{style:{transform:e==="top"?"rotate(0)":"rotate(180deg)"},xmlns:"http://www.w3.org/2000/svg",width:"12",height:"6",viewBox:"0 0 12 6",fill:"none"},a.createElement("path",{d:"M6 6L0 0h12L6 6Z",fill:E.themedColor.textHighEmphasis})),Iv={top:B.css`flex-direction:column;top:0;transform:translate(-50%,-100%);`,bottom:B.css`flex-direction:column-reverse;bottom:0;transform:translate(-50%,100%);`},Sr=b.default.div`position:relative;`,xv=b.default.div`display:flex;align-items:center;position:absolute;left:50%;z-index:${gt.TOOLTIP};${({$position:e})=>Iv[e]}opacity:0;transition:opacity 0.2s ease-in-out;pointer-events:none;${Sr}:hover &,${Sr}:focus-within &{opacity:1;}`,Rv=b.default(U)`padding:6px 8px;background:${E.themedColor.textHighEmphasis};color:${E.themedColor.textHighEmphasisInverse};border-radius:4px;font-size:12px;white-space:nowrap;`,Mv=2e3,Ho=0,wv=1500,fn=Symbol("header-focus-status-pause"),Go="data-sb-header-focus-protected",kv="[data-message-composer]",zo=new WeakMap,ar=e=>{const t=zo.get(e);if(t)return t;const n={focusedTargetIds:new Set,pendingBlurTimeouts:new Map,maxPauseTimeout:null};return zo.set(e,n),n},cr=(e,t)=>{const n=e.pendingBlurTimeouts.get(t);n&&(clearTimeout(n),e.pendingBlurTimeouts.delete(t))},En=e=>{e.maxPauseTimeout&&(clearTimeout(e.maxPauseTimeout),e.maxPauseTimeout=null)},Lv=e=>{e.pendingBlurTimeouts.forEach(t=>clearTimeout(t)),e.pendingBlurTimeouts.clear(),e.focusedTargetIds.clear(),En(e)},Ov=e=>{const t=e.hasAttribute("tabindex"),n=e.getAttribute("tabindex");return t||e.tabIndex>=0?()=>{}:(e.setAttribute("tabindex","-1"),()=>{if(n===null){e.removeAttribute("tabindex");return}e.setAttribute("tabindex",n)})},Nv=e=>e instanceof HTMLBodyElement||(e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&e.disabled?!0:(e instanceof HTMLElement&&e.closest(kv),!1),ss=()=>{const{setStatusPauseState:e}=ot(),t=l.useRef(Symbol("header-focus-target")),n=l.useRef(!1),r=l.useRef(0),s=l.useRef(null),o=l.useCallback(()=>{s.current&&(clearTimeout(s.current),s.current=null)},[]),i=l.useCallback(()=>{if(n.current)return;n.current=!0,r.current=Date.now()+wv,o();const u=ar(e);cr(u,t.current),u.focusedTargetIds.add(t.current),u.focusedTargetIds.size===1&&e(fn,!0),En(u),u.maxPauseTimeout=setTimeout(()=>{Lv(u),e(fn,!1)},Mv)},[o,e]),c=l.useCallback(u=>{if(!n.current)return;n.current=!1;const d=u.currentTarget,m=ar(e),h=d instanceof HTMLElement&&Date.now()<=r.current;cr(m,t.current),h&&(o(),s.current=setTimeout(()=>{if(s.current=null,!(d instanceof HTMLElement)||!d.isConnected)return;const g=d.ownerDocument.activeElement,C=g instanceof HTMLElement&&g.hasAttribute(Go);if(g===d||C||!Nv(g))return;const v=Ov(d);d.focus({preventScroll:!0}),v()},Ho)),m.pendingBlurTimeouts.set(t.current,setTimeout(()=>{m.pendingBlurTimeouts.delete(t.current),m.focusedTargetIds.delete(t.current),m.focusedTargetIds.size===0&&(En(m),e(fn,!1))},Ho))},[o,e]);return l.useEffect(()=>()=>{const u=ar(e);n.current=!1,o(),cr(u,t.current),u.focusedTargetIds.delete(t.current)&&u.focusedTargetIds.size===0&&(En(u),e(fn,!1))},[o,e]),{[Go]:"true",onFocus:i,onBlur:c}},Dv=()=>{const{logger:e}=ce(),{stringSet:t}=se(),{channelSource:n}=Ae(),{conversation:r}=re(),s=n.channel,o=Rt(),i=Ur("handoff-button",s),c=!Rr(s)||rt(s),[u,d]=l.useState(!1),m=ss(),h=async()=>{d(!1);try{const g=await(s==null?void 0:s.markConversationAsHandoff());e.info("conversation.handleAgentHandoff: success",g)}catch(g){e.error("conversation.handleAgentHandoff: error",g)}};if(!i)return null;const f={handoff:r.header.handoffButton()};return a.createElement(a.Fragment,null,a.createElement(a.Fragment,null,a.createElement(Av,{label:t.HEADER_BUTTON__AGENT_HANDOFF,position:"bottom",disabled:c},a.createElement(it,{...f.handoff.props,type:"agent",size:o,disabled:c,...m,onClick:()=>d(!0)})),f.handoff.descriptionNode),a.createElement(dt,{portalContainerId:ye.WINDOW,visible:u,onClose:()=>d(!1)},a.createElement(ts,{title:t.HANDOFF_CONFIRM__TITLE,description:t.HANDOFF_CONFIRM__DESCRIPTION,negativeText:t.HANDOFF_CONFIRM__CANCEL,positiveText:t.HANDOFF_CONFIRM__HANDOFF,onCancel:()=>d(!1),onConfirm:h})))},$v=l.lazy(()=>Promise.resolve().then(()=>require("./cjs/VvejebHE.cjs")).then(e=>({default:e.MarkdownText}))),Fv=()=>{const{logger:e}=ce(),{stringSet:t}=se(),{memoryInfo:n,sdkUser:r}=De(),{actions:s}=Ae(),{conversation:o}=re(),i=Rt(20),c=ss(),[u,d]=l.useState(null),[m,h]=l.useState(!1),f=l.useRef(!1);if(l.useEffect(()=>{r&&(n!=null&&n.consentDialog)&&d({...n})},[r,n==null?void 0:n.consentDialog]),!r||!n)return null;const g=o.header.memoryIndicator(n.enabled),C=async v=>{if(!f.current){f.current=!0,h(!1);try{await s.setUserMemoryState({enabled:v}),d(null)}catch(_){e.error("memoryIndicator.setUserMemoryState: error",_),h(!0)}finally{f.current=!1}}};return a.createElement(a.Fragment,null,n.showIndicator&&a.createElement(a.Fragment,null,a.createElement(Hv,{...g.props,as:"button",type:"button",onClick:()=>d({...n}),...c,$size:i},a.createElement(J,{type:"memory",size:i,color:E.themedColor.textHighEmphasis}),a.createElement(Gv,{$enabled:n.enabled})),g.descriptionNode),u&&a.createElement(Pv,{memoryInfo:u,onClose:()=>d(null),onSetEnabled:C}),a.createElement(Pn,{visible:m,title:t.PLACE_HOLDER__WRONG,description:t.MEMORY__ERROR_MESSAGE,onClose:()=>h(!1)}))},Pv=({memoryInfo:e,onClose:t,onSetEnabled:n})=>{var h;const{stringSet:r}=se(),{colors:s}=B.useTheme(),o=l.useId(),i=l.useId(),c=vu(e),u=c==="consent",d={consent:{body:((h=e.consentDialog)==null?void 0:h.body)??"",negativeText:r.MEMORY__BUTTON_DONT_USE,positiveText:r.MEMORY__BUTTON_USE,onCancel:()=>n(!1),onConfirm:()=>n(!0)},on:{body:r.MEMORY__DESC_ON,negativeText:e.deleteOnOff?r.MEMORY__BUTTON_DISABLE_AND_DELETE:r.MEMORY__BUTTON_DISABLE,positiveText:r.MEMORY__BUTTON_KEEP_USING,onCancel:()=>n(!1),onConfirm:t},off:{body:r.MEMORY__DESC_OFF,negativeText:r.MEMORY__BUTTON_ENABLE,positiveText:r.MEMORY__BUTTON_KEEP_OFF,onCancel:()=>n(!0),onConfirm:t},readonly:{body:e.enabled?r.MEMORY__DESC_ON:r.MEMORY__DESC_OFF,negativeText:void 0,positiveText:r.MEMORY__BUTTON_CANCEL,onCancel:void 0,onConfirm:t}}[c],m=s.memoryDialog;return a.createElement(dt,{visible:!0,portalContainerId:ye.WINDOW,onClose:t,cancelable:!u,"aria-labelledby":o,"aria-describedby":i},a.createElement(ts,{title:r.MEMORY__DIALOG_TITLE,titleId:o,description:a.createElement(Uv,null,d.body),descriptionId:i,negativeText:d.negativeText,positiveText:d.positiveText,buttonLayout:u?"horizontal":"vertical-full-width",onCancel:d.onCancel,onConfirm:d.onConfirm,styles:{titleColor:m.titleText,positiveBackground:m.positiveBackground,positiveText:m.positiveText,positiveBorderColor:m.positiveBorderColor,negativeBackground:m.negativeBackground,negativeText:m.negativeText,negativeBorderColor:m.negativeBorderColor}}))},Uv=({children:e})=>{const{handlers:t}=ce();return a.createElement(zv,null,a.createElement(Ht,{fallback:e},a.createElement($v,{onClickLink:t.onClickLink},e)))},Bv=B.css`all:unset;box-sizing:border-box;width:${({$size:e})=>e}px;height:${({$size:e})=>e}px;display:flex;align-items:center;justify-content:center;position:relative;`,Hv=b.default.button`${Bv};cursor:pointer;${xe}`,Gv=b.default.span`position:absolute;top:0;inset-inline-end:0;width:8px;height:8px;border-radius:999px;background-color:${({$enabled:e})=>e?E.themedColor.secondary:E.color.background300};box-shadow:0 0 0 2px ${E.color.background50};${Q.dark`
|
|
451
|
+
`,cv=l.lazy(()=>Promise.resolve().then(()=>require("./cjs/VvejebHE.cjs")).then(e=>({default:e.MarkdownText}))),lv=()=>{const{aiAgentInfo:e,userSession:t}=Ne(),{handlers:n}=le(),{messageSource:r,channelSource:s}=Ae(),[o,i]=l.useState(null),c=Ur("special-notice",s.channel),u=l.useCallback(()=>s.channel?c?r.messages.some(d=>st(d,(t==null?void 0:t.userId)??"")):!0:null,[s.channel,c,r.messages,t==null?void 0:t.userId]);return l.useEffect(()=>{o||i(u())},[u,o]),o||!e.specialNotice?null:a.createElement(av,null,a.createElement(cv,{onClickLink:n.onClickLink},e.specialNotice))},uv=()=>a.createElement(dv,null,a.createElement(lv,null),a.createElement(Kb,null,a.createElement(iv,null))),dv=C.default.div`z-index:0;border:none;width:100%;`,mv=()=>{var s;const{testerType:e}=Ha(),{channelSource:t}=Ae(),n=He(t.channel),r=!!e&&((s=t.channel)==null?void 0:s.isAIAgent);return n&&r?a.createElement(zb,null):a.createElement(uv,null)},Va=({start:e,title:t,titleAlign:n="start",end:r,containerProps:s})=>{const o=l.useRef(null),i=l.useRef(null),[c,u]=l.useState(0),[d,m]=l.useState(0);return l.useLayoutEffect(()=>{o.current&&u(o.current.offsetWidth),i.current&&m(i.current.offsetWidth)},[e,r]),a.createElement(hv,{...s},a.createElement(fv,null,n==="center"&&t&&a.createElement(gv,{$sideWidth:Math.max(c,d)},a.createElement(pv,null,t)),a.createElement(_v,null,a.createElement(Ev,{ref:o},e),(n==="start"||n==="end")&&t&&a.createElement(bv,{$align:n,$hasStart:!!e,$hasEnd:!!r},t),a.createElement(Cv,{ref:i},r))))},hv=C.default.div`position:relative;width:100%;background-color:${({theme:e})=>e.colors.base.headerBackground};border-bottom:1px solid ${E.themedColor.textDisabled};`,fv=C.default.div`position:relative;height:56px;padding:11px 12px;`,gv=C.default.div`position:absolute;left:${({$sideWidth:e})=>e}px;right:${({$sideWidth:e})=>e}px;top:0;bottom:0;display:flex;align-items:center;justify-content:center;`,pv=C.default.div`max-width:100%;overflow:hidden;`,_v=C.default.div`display:flex;flex-direction:row;align-items:center;justify-content:space-between;height:100%;z-index:1;`,Ev=C.default.div`flex-shrink:0;display:flex;align-items:center;`,Cv=C.default.div`flex-shrink:0;display:flex;align-items:center;`,bv=C.default.div`flex:1;overflow:hidden;display:flex;align-items:${({$align:e})=>e==="start"?"flex-start":"flex-end"};margin-left:${({$hasStart:e})=>e?8:0}px;margin-right:${({$hasEnd:e})=>e?8:0}px;`,Rt=(e=16)=>Jt()?e*1.5:e,vv=()=>{const{state:e}=le(),{messenger:t}=re(),n=Rt(),r=()=>{e.setOpened(!1)};return a.createElement(it,{...t.closeButton().props,type:"close",size:n,onClick:r})},yv=()=>{const{enableCloseConversationButton:e,dispatcher:t}=le(),{channelSource:n}=Ae(),{conversation:r}=re(),s=n.channel,o=Rt(),i=(s==null?void 0:s.isAIAgent)&&e,c=!Rr(s);if(!i)return null;const u={close:r.header.closeConversationButton()},d=async()=>{s&&await t.send(ct.CloseConversation({channelUrl:s.url}))};return a.createElement(a.Fragment,null,a.createElement(it,{...u.close.props,type:"mute",size:o,disabled:c,onClick:d}),u.close.descriptionNode)},Sv=()=>{const{state:e,enableExpandButton:t}=le(),{messenger:n}=re(),r=Rt();return t?a.createElement(it,{...n.expandButton(e.expanded).props,type:e.expanded?"collapse":"expand",size:r,onClick:()=>e.setExpanded(!e.expanded)}):null},Av=({label:e,children:t,position:n="top",disabled:r})=>r?t:a.createElement(Sr,null,t,a.createElement(xv,{$position:n},a.createElement(Rv,{variant:"caption1"},e),a.createElement(Tv,{$position:n}))),Tv=({$position:e})=>a.createElement("svg",{style:{transform:e==="top"?"rotate(0)":"rotate(180deg)"},xmlns:"http://www.w3.org/2000/svg",width:"12",height:"6",viewBox:"0 0 12 6",fill:"none"},a.createElement("path",{d:"M6 6L0 0h12L6 6Z",fill:E.themedColor.textHighEmphasis})),Iv={top:G.css`flex-direction:column;top:0;transform:translate(-50%,-100%);`,bottom:G.css`flex-direction:column-reverse;bottom:0;transform:translate(-50%,100%);`},Sr=C.default.div`position:relative;`,xv=C.default.div`display:flex;align-items:center;position:absolute;left:50%;z-index:${gt.TOOLTIP};${({$position:e})=>Iv[e]}opacity:0;transition:opacity 0.2s ease-in-out;pointer-events:none;${Sr}:hover &,${Sr}:focus-within &{opacity:1;}`,Rv=C.default(H)`padding:6px 8px;background:${E.themedColor.textHighEmphasis};color:${E.themedColor.textHighEmphasisInverse};border-radius:4px;font-size:12px;white-space:nowrap;`,Mv=2e3,Ho=0,wv=1500,fn=Symbol("header-focus-status-pause"),Go="data-sb-header-focus-protected",kv="[data-message-composer]",zo=new WeakMap,ar=e=>{const t=zo.get(e);if(t)return t;const n={focusedTargetIds:new Set,pendingBlurTimeouts:new Map,maxPauseTimeout:null};return zo.set(e,n),n},cr=(e,t)=>{const n=e.pendingBlurTimeouts.get(t);n&&(clearTimeout(n),e.pendingBlurTimeouts.delete(t))},En=e=>{e.maxPauseTimeout&&(clearTimeout(e.maxPauseTimeout),e.maxPauseTimeout=null)},Lv=e=>{e.pendingBlurTimeouts.forEach(t=>clearTimeout(t)),e.pendingBlurTimeouts.clear(),e.focusedTargetIds.clear(),En(e)},Ov=e=>{const t=e.hasAttribute("tabindex"),n=e.getAttribute("tabindex");return t||e.tabIndex>=0?()=>{}:(e.setAttribute("tabindex","-1"),()=>{if(n===null){e.removeAttribute("tabindex");return}e.setAttribute("tabindex",n)})},Nv=e=>e instanceof HTMLBodyElement||(e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&e.disabled?!0:(e instanceof HTMLElement&&e.closest(kv),!1),ss=()=>{const{setStatusPauseState:e}=ot(),t=l.useRef(Symbol("header-focus-target")),n=l.useRef(!1),r=l.useRef(0),s=l.useRef(null),o=l.useCallback(()=>{s.current&&(clearTimeout(s.current),s.current=null)},[]),i=l.useCallback(()=>{if(n.current)return;n.current=!0,r.current=Date.now()+wv,o();const u=ar(e);cr(u,t.current),u.focusedTargetIds.add(t.current),u.focusedTargetIds.size===1&&e(fn,!0),En(u),u.maxPauseTimeout=setTimeout(()=>{Lv(u),e(fn,!1)},Mv)},[o,e]),c=l.useCallback(u=>{if(!n.current)return;n.current=!1;const d=u.currentTarget,m=ar(e),h=d instanceof HTMLElement&&Date.now()<=r.current;cr(m,t.current),h&&(o(),s.current=setTimeout(()=>{if(s.current=null,!(d instanceof HTMLElement)||!d.isConnected)return;const g=d.ownerDocument.activeElement,_=g instanceof HTMLElement&&g.hasAttribute(Go);if(g===d||_||!Nv(g))return;const y=Ov(d);d.focus({preventScroll:!0}),y()},Ho)),m.pendingBlurTimeouts.set(t.current,setTimeout(()=>{m.pendingBlurTimeouts.delete(t.current),m.focusedTargetIds.delete(t.current),m.focusedTargetIds.size===0&&(En(m),e(fn,!1))},Ho))},[o,e]);return l.useEffect(()=>()=>{const u=ar(e);n.current=!1,o(),cr(u,t.current),u.focusedTargetIds.delete(t.current)&&u.focusedTargetIds.size===0&&(En(u),e(fn,!1))},[o,e]),{[Go]:"true",onFocus:i,onBlur:c}},Dv=()=>{const{logger:e}=le(),{stringSet:t}=se(),{channelSource:n}=Ae(),{conversation:r}=re(),s=n.channel,o=Rt(),i=Ur("handoff-button",s),c=!Rr(s)||rt(s),[u,d]=l.useState(!1),m=ss(),h=async()=>{d(!1);try{const g=await(s==null?void 0:s.markConversationAsHandoff());e.info("conversation.handleAgentHandoff: success",g)}catch(g){e.error("conversation.handleAgentHandoff: error",g)}};if(!i)return null;const f={handoff:r.header.handoffButton()};return a.createElement(a.Fragment,null,a.createElement(a.Fragment,null,a.createElement(Av,{label:t.HEADER_BUTTON__AGENT_HANDOFF,position:"bottom",disabled:c},a.createElement(it,{...f.handoff.props,type:"agent",size:o,disabled:c,...m,onClick:()=>d(!0)})),f.handoff.descriptionNode),a.createElement(dt,{portalContainerId:ye.WINDOW,visible:u,onClose:()=>d(!1)},a.createElement(ts,{title:t.HANDOFF_CONFIRM__TITLE,description:t.HANDOFF_CONFIRM__DESCRIPTION,negativeText:t.HANDOFF_CONFIRM__CANCEL,positiveText:t.HANDOFF_CONFIRM__HANDOFF,onCancel:()=>d(!1),onConfirm:h})))},$v=l.lazy(()=>Promise.resolve().then(()=>require("./cjs/VvejebHE.cjs")).then(e=>({default:e.MarkdownText}))),Fv=()=>{const{logger:e}=le(),{stringSet:t}=se(),{memoryInfo:n,sdkUser:r}=Ne(),{actions:s}=Ae(),{conversation:o}=re(),i=Rt(20),c=ss(),[u,d]=l.useState(null),[m,h]=l.useState(!1),f=l.useRef(!1);if(l.useEffect(()=>{r&&(n!=null&&n.consentDialog)&&d({...n})},[r,n==null?void 0:n.consentDialog]),!r||!n)return null;const g=o.header.memoryIndicator(n.enabled),_=async y=>{if(!f.current){f.current=!0,h(!1);try{await s.setUserMemoryState({enabled:y}),d(null)}catch(b){e.error("memoryIndicator.setUserMemoryState: error",b),h(!0)}finally{f.current=!1}}};return a.createElement(a.Fragment,null,n.showIndicator&&a.createElement(a.Fragment,null,a.createElement(Hv,{...g.props,as:"button",type:"button",onClick:()=>d({...n}),...c,$size:i},a.createElement(J,{type:"memory",size:i,color:E.themedColor.textHighEmphasis}),a.createElement(Gv,{$enabled:n.enabled})),g.descriptionNode),u&&a.createElement(Pv,{memoryInfo:u,onClose:()=>d(null),onSetEnabled:_}),a.createElement(Pn,{visible:m,title:t.PLACE_HOLDER__WRONG,description:t.MEMORY__ERROR_MESSAGE,onClose:()=>h(!1)}))},Pv=({memoryInfo:e,onClose:t,onSetEnabled:n})=>{var h;const{stringSet:r}=se(),{colors:s}=G.useTheme(),o=l.useId(),i=l.useId(),c=vu(e),u=c==="consent",d={consent:{body:((h=e.consentDialog)==null?void 0:h.body)??"",negativeText:r.MEMORY__BUTTON_DONT_USE,positiveText:r.MEMORY__BUTTON_USE,onCancel:()=>n(!1),onConfirm:()=>n(!0)},on:{body:r.MEMORY__DESC_ON,negativeText:e.deleteOnOff?r.MEMORY__BUTTON_DISABLE_AND_DELETE:r.MEMORY__BUTTON_DISABLE,positiveText:r.MEMORY__BUTTON_KEEP_USING,onCancel:()=>n(!1),onConfirm:t},off:{body:r.MEMORY__DESC_OFF,negativeText:r.MEMORY__BUTTON_ENABLE,positiveText:r.MEMORY__BUTTON_KEEP_OFF,onCancel:()=>n(!0),onConfirm:t},readonly:{body:e.enabled?r.MEMORY__DESC_ON:r.MEMORY__DESC_OFF,negativeText:void 0,positiveText:r.MEMORY__BUTTON_CANCEL,onCancel:void 0,onConfirm:t}}[c],m=s.memoryDialog;return a.createElement(dt,{visible:!0,portalContainerId:ye.WINDOW,onClose:t,cancelable:!u,"aria-labelledby":o,"aria-describedby":i},a.createElement(ts,{title:r.MEMORY__DIALOG_TITLE,titleId:o,description:a.createElement(Uv,null,d.body),descriptionId:i,negativeText:d.negativeText,positiveText:d.positiveText,buttonLayout:u?"horizontal":"vertical-full-width",onCancel:d.onCancel,onConfirm:d.onConfirm,styles:{titleColor:m.titleText,positiveBackground:m.positiveBackground,positiveText:m.positiveText,positiveBorderColor:m.positiveBorderColor,negativeBackground:m.negativeBackground,negativeText:m.negativeText,negativeBorderColor:m.negativeBorderColor}}))},Uv=({children:e})=>{const{handlers:t}=le();return a.createElement(zv,null,a.createElement(Ht,{fallback:e},a.createElement($v,{onClickLink:t.onClickLink},e)))},Bv=G.css`all:unset;box-sizing:border-box;width:${({$size:e})=>e}px;height:${({$size:e})=>e}px;display:flex;align-items:center;justify-content:center;position:relative;`,Hv=C.default.button`${Bv};cursor:pointer;${xe}`,Gv=C.default.span`position:absolute;top:0;inset-inline-end:0;width:8px;height:8px;border-radius:999px;background-color:${({$enabled:e})=>e?E.themedColor.secondary:E.color.background300};box-shadow:0 0 0 2px ${E.color.background50};${Q.dark`
|
|
452
452
|
box-shadow: 0 0 0 2px ${E.color.background500};
|
|
453
453
|
`}
|
|
454
|
-
`,zv=
|
|
454
|
+
`,zv=C.default.div`color:${({theme:e})=>e.colors.memoryDialog.markdownBodyText};line-height:20px;word-break:break-word;&& a{color:${({theme:e})=>e.colors.memoryDialog.markdownLinkText};font-weight:inherit;text-decoration:underline;}`,Vv=()=>{const{conversation:e}=re(),{onNavigateToConversationList:t}=Ae();if(!t)return null;const n={menu:e.header.menuButton()};return a.createElement(a.Fragment,null,a.createElement(it,{...n.menu.props,...Pi,type:"menu",size:24,onClick:()=>t()}),n.menu.descriptionNode)},qa=({channel:e,size:t=40})=>{const{userSession:n,aiAgentInfo:r}=Ne(),{fallbackIcon:s,url:o}=Br({channel:e,aiAgentInfo:r,userSession:n}),[i,c]=l.useState(),u=G.useTheme();return o&&o!==i?a.createElement(Aa,{src:o,size:t,"aria-hidden":"true",onImageError:c}):a.createElement(qv,{"aria-hidden":"true",$size:t,$bgColor:u.colors.base.primary},a.createElement(J,{type:s,size:t*.55,color:u.colors.base.primaryContrastContent}))},qv=C.default.div`width:${({$size:e})=>e}px;height:${({$size:e})=>e}px;border-radius:50%;background-color:${({$bgColor:e})=>e};display:flex;align-items:center;justify-content:center;flex-shrink:0;`,Kv=()=>{const{channelSource:e}=Ae(),{aiAgentInfo:t,userSession:n}=Ne(),{conversation:r}=re(),{config:s}=ke(),{announcementsEnabled:o}=ot(),i=e.channel,c=Br({channel:i,userSession:n,aiAgentInfo:t}),u=s.conversation.header.avatarEnabled,d=ss(),m=fa({enabled:o,label:c.title}),h={title:r.header.title(c.title,{active:m.enabled,titleId:m.id,initialFocus:!1})};return a.createElement(Yv,null,u&&a.createElement(qa,{channel:i,size:34}),a.createElement(Wv,{...h.title.props,...d},c.title))},Yv=C.default.div`display:flex;flex-direction:row;align-items:center;gap:6px;min-width:0;width:100%;overflow:hidden;`,Wv=C.default(H).attrs({variant:"h2",color:E.themedColor.textHighEmphasis})`
|
|
455
455
|
margin: 0;
|
|
456
456
|
flex: 1;
|
|
457
457
|
min-width: 0;
|
|
@@ -463,10 +463,10 @@
|
|
|
463
463
|
&:focus {
|
|
464
464
|
outline: none;
|
|
465
465
|
}
|
|
466
|
-
`,jv=e=>{const{components:t}=Et.useContext();return a.createElement(Va,{start:a.createElement(t.StartArea,null),title:a.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:a.createElement(t.EndArea,null),containerProps:Hi})},Xv=()=>{const{components:e}=Et.useContext();return a.createElement(e.MenuButton,null)},Zv=()=>{const{components:e}=Et.useContext();return a.createElement(e.Title,null)},Jv=()=>{const{components:e}=Et.useContext();return a.createElement(ey,null,a.createElement(e.MemoryIndicator,null),a.createElement(e.HandoffButton,null),a.createElement(e.ConversationCloseButton,null),a.createElement(e.ExpandButton,null),a.createElement(e.CloseButton,null))},Et=je({template:jv,components:{StartArea:Xv,TitleArea:Zv,EndArea:Jv,MenuButton:Vv,Title:Kv,MemoryIndicator:Fv,HandoffButton:Dv,ConversationCloseButton:yv,ExpandButton:Sv,CloseButton:vv}}),Qv=()=>{const{Template:e}=Et.useContext();return a.createElement(e,{titleAlign:"start"})},ey=
|
|
466
|
+
`,jv=e=>{const{components:t}=Et.useContext();return a.createElement(Va,{start:a.createElement(t.StartArea,null),title:a.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:a.createElement(t.EndArea,null),containerProps:Hi})},Xv=()=>{const{components:e}=Et.useContext();return a.createElement(e.MenuButton,null)},Zv=()=>{const{components:e}=Et.useContext();return a.createElement(e.Title,null)},Jv=()=>{const{components:e}=Et.useContext();return a.createElement(ey,null,a.createElement(e.MemoryIndicator,null),a.createElement(e.HandoffButton,null),a.createElement(e.ConversationCloseButton,null),a.createElement(e.ExpandButton,null),a.createElement(e.CloseButton,null))},Et=je({template:jv,components:{StartArea:Xv,TitleArea:Zv,EndArea:Jv,MenuButton:Vv,Title:Kv,MemoryIndicator:Fv,HandoffButton:Dv,ConversationCloseButton:yv,ExpandButton:Sv,CloseButton:vv}}),Qv=()=>{const{Template:e}=Et.useContext();return a.createElement(e,{titleAlign:"start"})},ey=C.default.div`display:flex;gap:10px;align-items:center;justify-content:center;`,os=({children:e,onNavigateToConversationList:t,channelUrl:n,onClearChannelUrl:r,shouldMarkAsRead:s,shouldInitializeConversation:o,announcementsEnabled:i=!0,conversationStatsEnabled:c=!0,initialFocusTarget:u,style:d,closedChannelUrl:m,onClearClosedChannelUrl:h})=>{const{Template:f}=Vn.useContext();return a.createElement(da,{onNavigateToConversationList:t,channelUrl:n??m,onClearChannelUrl:r??h,conversationStatsEnabled:c,shouldMarkAsRead:s,shouldInitializeConversation:o},a.createElement(_r,null,a.createElement(_r.Consumer,null,g=>a.createElement(af,{announcementsEnabled:i},a.createElement(ty,{enabled:c}),a.createElement(ny,null),a.createElement(ry,{style:d,dragHandlers:g,initialFocusTarget:u},a.createElement(f,null)),e))))},ty=({enabled:e})=>(ag({enabled:e}),null),ny=()=>(Sg(),hg(),bg(),null),ry=({style:e,dragHandlers:t,initialFocusTarget:n,children:r})=>{const s=l.useRef(null);return ig(s,n),a.createElement(oy,{ref:s,style:e,...t},r)},sy=e=>{const{components:t}=Vn.useContext();return a.createElement(a.Fragment,null,a.createElement(t.Header,null),a.createElement(t.Body,null),a.createElement(t.Footer,null))},Vn=je({template:sy,components:{Header:Qv,Body:Nb,Footer:mv}}),oy=C.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,Ka=be("ConversationListAnnouncements",{announcementsEnabled:!0,announceScreenEntry:ue}),iy=Ka.Provider,is=Ka.useContext,ay=({children:e,announcementsEnabled:t=!0})=>{const{announceScreenEntry:n}=Kr(),r=l.useCallback(o=>{t&&n(o)},[n,t]),s=l.useMemo(()=>({announcementsEnabled:t,announceScreenEntry:r}),[t,r]);return a.createElement(iy,{value:s},e)},{Provider:cy,Context:ly,useContext:en}=be("ConversationList");function Ya({conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:n,onOpenConversationView:r=ue,children:s}){return a.createElement(zd,{conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:n},o=>a.createElement(cy,{value:{...o,onOpenConversationView:r}},s))}const uy=e=>{const{announcementsEnabled:t}=is(),{listSource:n}=en(),r=Xi();ga(e,{enabled:t,ready:n.initialized,suppressed:r})},dy=()=>{const{announceScreenEntry:e,announcementsEnabled:t}=is(),{listSource:n}=en(),r=l.useRef(!1);l.useEffect(()=>{if(!t){r.current=!1;return}if(!n.initialized||r.current)return;const s=n.channels.length,o=setTimeout(()=>{e({screen:"conversationList",conversationCount:s}),r.current=!0},0);return()=>clearTimeout(o)},[e,t,n.initialized])},my=({channel:e})=>a.createElement(qa,{channel:e}),Ar=99,hy=e=>{var b,p;const{channel:t,onClick:n}=e,{stringSet:r,format:s}=se(),{userSession:o,aiAgentInfo:i}=Ne(),{conversationList:c}=re(),u=Br({channel:t,userSession:o,aiAgentInfo:i}),d=_u(t,{formatMultipleFilesCount:r.CONVERSATION_LIST__MULTIPLE_FILES_COUNT}),m=Eu(t,s,{justNow:r.DATE_FORMAT__JUST_NOW,minutesAgo:r.DATE_FORMAT__MINUTES_AGO,hoursAgo:r.DATE_FORMAT__HOURS_AGO,dateShortFormat:r.DATE_FORMAT__DATE_SHORT}),h=t.unreadMessageCount,f=(b=t.lastMessage)!=null&&b.isAdminMessage()?r.CONVERSATION_LIST__SYSTEM_MESSAGE:u.title,g=He(t)?r.CONVERSATION_LIST__ENDED:Ei(t,{formatMultipleFilesCount:r.CONVERSATION_LIST__MULTIPLE_FILES_COUNT}),_=n?()=>n():void 0,y=c.item({agent:f,status:g,time:m,unreadCount:h,onActivate:_});return a.createElement(fy,{"data-testid":"sb-conversation-list-item",$clickable:!!_,...y.props},a.createElement(gy,null,a.createElement(my,{...e})),a.createElement(py,null,a.createElement(_y,null,(p=t.lastMessage)!=null&&p.isFileMessage()&&(!t.lastMessage.message||t.lastMessage.name===t.lastMessage.message)?a.createElement(ba,{variant:"subtitle1",color:E.themedColor.textHighEmphasis},d):a.createElement(H,{variant:"subtitle1",color:E.themedColor.textHighEmphasis,maxTextLines:1},d),a.createElement(Ey,null,He(t)&&a.createElement(a.Fragment,null,a.createElement(H,{variant:"caption1",color:E.themedColor.textMidEmphasis,maxTextLines:1},r.CONVERSATION_LIST__ENDED),a.createElement(Cy,null)),a.createElement(H,{variant:"caption2",color:E.themedColor.textLowEmphasis,maxTextLines:1},m))),h>0&&a.createElement(by,{$count:h},a.createElement(H,{variant:"caption3",color:E.themedColor.textHighEmphasisInverse},h<=Ar?h:`${Ar}+`))),y.descriptionNode)},as=je({template:hy,components:{}}),fy=C.default.div`display:flex;flex-shrink:0;flex-direction:row;align-items:center;position:relative;width:100%;height:72px;box-sizing:border-box;gap:16px;cursor:${({$clickable:e})=>e?"pointer":"default"};`,gy=C.default.div`display:flex;align-items:center;justify-content:center;padding-inline-start:16px;`,py=C.default.div`display:flex;flex-direction:row;align-items:center;flex:1;min-width:0;padding-inline-end:16px;height:100%;gap:8px;border-bottom:1px solid ${E.themedColor.textDisabled};`,_y=C.default.div`display:flex;flex-direction:column;justify-content:center;flex:1;min-width:0;gap:4px;word-break:break-word;overflow-wrap:break-word;`,Ey=C.default.div`display:flex;align-items:center;gap:6px;`,Cy=C.default.div`width:2px;height:2px;border-radius:1px;background-color:${E.themedColor.textLowEmphasis};`,by=C.default.div`display:flex;align-items:center;justify-content:center;height:20px;padding:4px;border-radius:10px;background-color:${E.themedColor.error};${({$count:e})=>e<=Ar&&G.css`
|
|
467
467
|
width: 20px;
|
|
468
468
|
`}
|
|
469
|
-
`,vy=({items:e,renderItem:t,onEndReached:n,role:r,"aria-label":s})=>{const o=i=>{const c=i.target;c.scrollHeight-c.scrollTop-c.clientHeight<=2&&(n==null||n())};return a.createElement(yy,{role:r,"aria-label":s,onScroll:i=>o(i)},e.map((i,c)=>{const u=t(i,c);if(r!=="list")return u;const d=l.isValidElement(u)&&u.key!=null?u.key:c;return a.createElement(Sy,{key:d,role:"listitem"},u)}))},yy=
|
|
469
|
+
`,vy=({items:e,renderItem:t,onEndReached:n,role:r,"aria-label":s})=>{const o=i=>{const c=i.target;c.scrollHeight-c.scrollTop-c.clientHeight<=2&&(n==null||n())};return a.createElement(yy,{role:r,"aria-label":s,onScroll:i=>o(i)},e.map((i,c)=>{const u=t(i,c);if(r!=="list")return u;const d=l.isValidElement(u)&&u.key!=null?u.key:c;return a.createElement(Sy,{key:d,role:"listitem"},u)}))},yy=C.default.div`width:100%;height:100%;display:flex;flex-direction:column;flex:1;overflow:auto;overscroll-behavior:contain;`,Sy=C.default.div`flex-shrink:0;`,Ay=()=>{const{stringSet:e}=se(),{listSource:t,onOpenConversationView:n}=en(),{Template:r}=as.useContext();return t.initialized?t.channels.length===0?a.createElement(Ut,{type:"noChannels",label:e.CONVERSATION_LIST__NO_CONVERSATIONS}):a.createElement(vy,{role:"list","aria-label":e.CONVERSATION_LIST__HEADER_TITLE,items:t.channels,renderItem:s=>{var o,i,c;return a.createElement(r,{key:s.url,channel:s,onClick:()=>n(s.url,He(s)?"closed":"open"),channelUrl:s.url,title:(i=(o=s.conversation)==null?void 0:o.topics)==null?void 0:i.join(", "),lastMessageTimestamp:(c=s.lastMessage)==null?void 0:c.createdAt})},onEndReached:()=>{t.loadMore()}}):a.createElement(Ut,{type:"loading"})},Ty=()=>{const{stringSet:e}=se(),{_aiAgentSDK:t}=ke(),{language:n,countryCode:r,context:s}=le(),{aiAgentInfo:o,refreshActiveChannel:i,createConversation:c}=Ne(),{onOpenConversationView:u}=en(),{conversationList:d}=re(),m=async()=>{var h;if(o.isMultipleActiveConversationsEnabled){const f=await c({aiAgentId:o.userId,language:n,country:r,context:s});(h=t.session)==null||h._updateActiveChannel({url:f,status:"open"}),u(f,"open",{initialFocusTarget:"messageInput"})}else{const f=await i();u(f,"open",{initialFocusTarget:"messageInput"})}};return a.createElement(Iy,{...d.footer.button({onActivate:m}).props},a.createElement(xy,{variant:"h1"},e.TALK_TO_AGENT))},Iy=C.default.div`background-color:${({theme:e})=>e.colors.base.primary};display:flex;align-items:center;justify-content:center;padding:16px;cursor:pointer;`,xy=C.default(H)`color:${({theme:e})=>e.colors.base.primaryContrastContent};overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,Ry=()=>{const{state:e}=le(),{messenger:t}=re(),n=Rt(),r=()=>{e.setOpened(!1)};return a.createElement(it,{...t.closeButton().props,type:"close",size:n,onClick:r})},My=()=>{const{stringSet:e}=se(),{announcementsEnabled:t}=is(),{conversationList:n}=re(),r=e.CONVERSATION_LIST__HEADER_TITLE,s=fa({enabled:t,label:r}),o={title:n.headerTitle(r,{active:s.enabled,titleId:s.id})};return a.createElement(wy,{forwardedAs:"h2",variant:"h2",color:E.themedColor.textHighEmphasis,...o.title.props},r)},wy=C.default(H)`margin:0;padding:0 4px;min-width:0;width:100%;box-sizing:border-box;text-overflow:ellipsis;overflow:hidden;white-space:nowrap;`,ky=e=>{const{components:t}=Mt.useContext();return a.createElement(Va,{start:a.createElement(t.StartArea,null),title:a.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:a.createElement(t.EndArea,null),containerProps:Hi})},Ly=()=>null,Oy=()=>{const{components:e}=Mt.useContext();return a.createElement(e.Title,null)},Ny=()=>{const{components:e}=Mt.useContext();return a.createElement(e.CloseButton,null)},Mt=je({template:ky,components:{StartArea:Ly,TitleArea:Oy,EndArea:Ny,Title:My,CloseButton:Ry}}),Dy=()=>{const{Template:e}=Mt.useContext();return a.createElement(e,{titleAlign:"start"})},$y=()=>(dy(),null),cs=({conversationListLimit:e,conversationListFilter:t,children:n,onOpenConversationView:r,announcementsEnabled:s=!0,conversationListStatsEnabled:o=!0,style:i})=>{const{Template:c}=qn.useContext();return a.createElement(Ya,{conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:o,onOpenConversationView:r},a.createElement(ay,{announcementsEnabled:s},a.createElement($y,null),a.createElement(Fy,{style:i},a.createElement(c,null)),n))},Fy=({style:e,children:t})=>{const n=l.useRef(null);return uy(n),a.createElement(Uy,{ref:n,style:e},t)},Py=()=>{const{components:e}=qn.useContext();return a.createElement(a.Fragment,null,a.createElement(e.Header,null),a.createElement(e.Body,null),a.createElement(e.Footer,null))},qn=je({template:Py,components:{Header:Dy,Body:Ay,Footer:Ty}}),Uy=C.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,By=G.css`:where(#${ye.ENTRY}) :not(code *){font-family:'Roboto',sans-serif;box-sizing:border-box;}`,Hy=[By,Oh,Nh],Gy=(e,...t)=>G.createGlobalStyle(e,...Hy,...t),zy=Gy``,Vy=pu(Vn,_t,xt,Hn,zn,qn,Et,as,Mt,Gn,Fn),qy=typeof __SBA_USE_MESSAGE_TEMPLATE__>"u"||__SBA_USE_MESSAGE_TEMPLATE__;function Wa({appearance:e,rootElement:t,logger:n,language:r,languageCode:s,stringSet:o,children:i,messageTemplate:c,icons:u,theme:d,entryElement:m,modalRootElement:h}){Qh(qy?bh:"",t);const[f,g]=l.useState(null),_=l.useCallback(p=>{g(S=>S===p?S:p)},[]),y=m??f,b=a.createElement(G.StyleSheetManager,{target:t},a.createElement(Xh,{rootElement:t,logger:n,appearance:e,theme:d},a.createElement(Ah,{rootElement:t,boundaryElement:y},a.createElement(Yd,{internalVariables:c==null?void 0:c.__internalVariables},a.createElement(Lh,{stringSet:o,logger:n,language:r,languageCode:s},a.createElement(Wh,{icons:u},a.createElement(Vy,null,a.createElement(yh,{entryElement:y,modalRootElement:h,rootElement:t},i),a.createElement(zy,null))))))));return m?b:a.createElement("div",{ref:_,style:{display:"contents"}},b)}const Ky=()=>{const[e,t]=l.useState(null),[n,r]=l.useState(null),s=l.useCallback(i=>{t(c=>c===i?c:i)},[]),o=l.useCallback(i=>{r(c=>c===i?c:i)},[]);return{entryElement:e,modalRootElement:n,setEntryElement:s,setModalRootElement:o}},ls=l.forwardRef(function({rootElement:t=document.body,logLevel:n=de.LogLevel.WARN,language:r=navigator.language,userSessionInfo:s,children:o,chatParams:i,icons:c,...u},d){var b,p,S;Ft.level!==n&&(Ft.level=n);const{entryElement:m,modalRootElement:h,setEntryElement:f,setModalRootElement:g}=Ky();Jh("https://fonts.googleapis.com/css2?family=Roboto&display=swap",t);const _=Yi(r),y=Wi.has(_)?_:Zt;return a.createElement("div",{ref:f,id:ye.ENTRY,lang:y,style:{width:"fit-content",height:"fit-content",...u.entryStyle}},m&&h&&a.createElement(Wa,{logger:Ft,rootElement:t,appearance:(b=u.agentPreviewConfigs)==null?void 0:b.appearance,stringSet:u.stringSet,language:y,messageTemplate:u.messageTemplate,icons:c,theme:u.theme,entryElement:m,modalRootElement:h},a.createElement(Of,{rootElement:t,language:r,logger:Ft,dispatcher:ja,chatParams:{...i,...u.customApiHost&&{customApiHost:u.customApiHost},...u.customWebSocketHost&&{customWebSocketHost:u.customWebSocketHost}},chatSDK:u.customChatSDK,_forceCreateChannel:(p=u.agentPreviewConfigs)==null?void 0:p.forceCreateChannel,_agentVersion:(S=u.agentPreviewConfigs)==null?void 0:S.agentVersion,...u},a.createElement(Hf,{ref:d,userSessionInfo:s},a.createElement(Ub,{...u._UNSAFE_INTERNAL_dashboardTester},a.createElement(sf,null,o))))),a.createElement("div",{ref:g,id:ye.MODAL_ROOT,dir:u.dir}))}),Ft=new ii(de.LogLevel.WARN),ja=new ri(Ft),{Provider:Yy,useContext:tn}=be("PageChildren"),Xa=({children:e})=>{const[t,n]=l.useState(()=>os),[r,s]=l.useState(null),[o,i]=l.useState(()=>cs),[c,u]=l.useState(null),d=l.useCallback(h=>{n(()=>h)},[]),m=l.useCallback(h=>{i(()=>h)},[]);return a.createElement(Yy,{value:{conversationComponent:t,setConversationComponent:d,conversationChildren:r,setConversationChildren:s,conversationListComponent:o,setConversationListComponent:m,conversationListChildren:c,setConversationListChildren:u}},e)},us=(e,t)=>e?{role:"dialog","aria-modal":"true",...t?{"aria-labelledby":ye.WINDOW_TITLE}:{"aria-label":"Messenger"}}:{"aria-hidden":"true",inert:!0},Za=({children:e,isOpened:t,zIndex:n=gt.WINDOW})=>a.createElement(Xr,null,a.createElement(Wy,{isOpened:t,zIndex:n},e)),Wy=({children:e,isOpened:t,zIndex:n=gt.WINDOW})=>{const{dir:r,rootElement:s}=le(),o=ut(s,!0),i=l.useRef(null),{hasWindowTitleReference:c,isWindowNameReady:u}=Un();return $n(t,i,{nameReady:u}),l.useEffect(()=>{const d="sb-agent-block-scroll";return t?o.body.classList.add(d):o.body.classList.remove(d),()=>{o.body.classList.remove(d)}},[o,t]),a.createElement(jy,{ref:i,id:ye.WINDOW,dir:r,...us(t,c),$visible:t,$zIndex:n},e)},jy=C.default.div`width:100%;height:100%;position:fixed;top:0;left:0;z-index:${({$zIndex:e})=>e};visibility:${({$visible:e})=>e?"visible":"hidden"};`,Xy=48,Zy=2/3,Vo=12;function Ja({className:e,children:t,isOpened:n,onClick:r,"aria-label":s,"aria-describedby":o,type:i,imageUrl:c,dir:u,animated:d=!0,backgroundColor:m,size:h=Xy,hasUnread:f=!1}){const g=Ia(),_=d&&!g,y=mr(m),b=Math.round(h*Zy);return a.createElement(eS,{dir:u,id:ye.LAUNCHER,className:e,"aria-label":s,"aria-describedby":o,onClick:r,$animated:_,$backgroundColor:m,$prefersReducedMotion:g,$size:h},a.createElement(tS,{$isOpened:n,$animated:_,$fillColor:y,$iconSize:b,$prefersReducedMotion:g},a.createElement(qo.Open,{url:c,isDefaultIcon:i==="default_icon",size:b})),a.createElement(nS,{$isOpened:n,$animated:_,$fillColor:y,$iconSize:b,$prefersReducedMotion:g},a.createElement(qo.Close,{size:b})),f&&a.createElement(rS,null),t)}const Jy=G.css`&:hover{transition:transform 250ms cubic-bezier(0.33,0,0,1);transform:scale(1.1);}&:active{transform:scale(0.8);}`,Qy=G.css`img{width:100%;height:100%;object-fit:cover;user-select:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;-webkit-user-drag:none;&[data-default-icon='true']{width:${({$iconSize:e})=>e}px;height:${({$iconSize:e})=>e}px;filter:${({$fillColor:e})=>e===Bt.WHITE?"grayscale(100%) brightness(2000%)":"grayscale(100%) invert(100%) saturate(0%) brightness(0%) contrast(1000%)"};}}`,Qa=G.css`svg{width:${({$iconSize:e})=>e}px;height:${({$iconSize:e})=>e}px;${({$fillColor:e})=>G.css`
|
|
470
470
|
ellipse,
|
|
471
471
|
path {
|
|
472
472
|
fill: ${e};
|
|
@@ -476,7 +476,7 @@
|
|
|
476
476
|
}
|
|
477
477
|
`}
|
|
478
478
|
}
|
|
479
|
-
`,eS=
|
|
479
|
+
`,eS=C.default.button`position:relative;padding:0;width:${({$size:e})=>e}px;height:${({$size:e})=>e}px;background:${({$backgroundColor:e})=>e};border-radius:50%;transition:${({$prefersReducedMotion:e})=>e?"none":"all 0.3s cubic-bezier(0.31, -0.105, 0.43, 1.4)"};border:none;display:flex;justify-content:center;align-items:center;box-shadow:0 16px 24px 2px rgba(33,33,33,0.12),0 6px 30px 5px rgba(33,33,33,0.08),0 6px 10px -5px rgba(33,33,33,0.04);${({$animated:e})=>e&&Jy}`,ec=C.default.span.attrs({"aria-hidden":"true"})`
|
|
480
480
|
position: absolute;
|
|
481
481
|
width: 100%;
|
|
482
482
|
height: 100%;
|
|
@@ -486,7 +486,7 @@
|
|
|
486
486
|
display: flex;
|
|
487
487
|
justify-content: center;
|
|
488
488
|
align-items: center;
|
|
489
|
-
`,tS=
|
|
489
|
+
`,tS=C.default(ec)`transition:${({$prefersReducedMotion:e})=>e?"none":"transform 0.16s linear, opacity 0.08s linear, scale 0.16s linear"};opacity:${({$isOpened:e})=>e?0:1};transform:${({$animated:e,$isOpened:t})=>e&&(t?"rotate(-90deg) scale(0)":"rotate(0deg)")};${Qy}${Qa}`,nS=C.default(ec)`transition:${({$prefersReducedMotion:e})=>e?"none":"transform 0.16s linear, opacity 0.08s linear, scale 0.16s linear"};scale:${({$isOpened:e})=>e?1:0};transform:${({$animated:e,$isOpened:t})=>e&&(t?"rotate(0deg)":"rotate(-90deg)")};${Qa}`,rS=C.default.span.attrs({"aria-hidden":"true"})`
|
|
490
490
|
position: absolute;
|
|
491
491
|
top: 1px;
|
|
492
492
|
inset-inline-end: 1px;
|
|
@@ -494,10 +494,10 @@
|
|
|
494
494
|
height: ${Vo}px;
|
|
495
495
|
border-radius: 50%;
|
|
496
496
|
background-color: ${E.themedColor.error};
|
|
497
|
-
`,qo={Open:e=>e.url?a.createElement("img",{src:e.url,alt:"","data-default-icon":e.isDefaultIcon}):a.createElement(J,{size:e.size,type:"delight"}),Close:({size:e})=>a.createElement(J,{size:e,type:"chevron-down"})};function tc({className:e,size:t,entryPoint:n="Conversation",activeRoute:r}){const{colors:s}=
|
|
497
|
+
`,qo={Open:e=>e.url?a.createElement("img",{src:e.url,alt:"","data-default-icon":e.isDefaultIcon}):a.createElement(J,{size:e.size,type:"delight"}),Close:({size:e})=>a.createElement(J,{size:e,type:"chevron-down"})};function tc({className:e,size:t,entryPoint:n="Conversation",activeRoute:r}){const{colors:s}=G.useTheme(),{chatSDK:o,config:i,dir:c,state:u}=le(),{resolveElement:d}=Vr(),{launcher:m}=re(),{launcherInfo:h}=Ne(),f=i.launcher.unreadBadgeEnabled,g=Ti(),_=Im(o,{enabled:f,opened:u.opened,filter:g}),y=(r??n)==="ConversationList",b={launcher:m.button({isOpened:u.opened,opensConversationList:y})};Tm("launcher_toggle"),oS();const p=()=>{we(()=>{const T=d(ye.WINDOW),R=T?sa(T):null;R==null||R.focus()})},S=()=>{we(()=>{var T;(T=d(ye.LAUNCHER))==null||T.focus()})},A=()=>{const T=!u.opened;u.setOpened(T),T?p():S()};return a.createElement(Ja,{dir:c,className:e,isOpened:u.opened,onClick:A,type:h.type,imageUrl:h.imageUrl,backgroundColor:s.base.primary,size:t,hasUnread:f&&!u.opened&&_,...b.launcher.props},b.launcher.descriptionNode)}const sS=1e3*60;function oS(){const{chatSDK:e,state:t,logger:n,enableAutoDisconnectInLauncher:r}=le(),s=l.useRef(null);l.useEffect(()=>{if(!r)return;function o(){s.current&&(clearTimeout(s.current),s.current=null)}function i(){e.connectionState===de.ConnectionState.CLOSED&&(e.reconnect(),n.debug("useSDKInactivityTimeout: reconnected")),o(),n.debug("useSDKInactivityTimeout: clear disconnect schedule")}function c(){o(),s.current=setTimeout(async()=>{await e.disconnectWebSocket(),n.debug("useSDKInactivityTimeout: disconnected")},sS)}t.opened?i():(c(),n.debug("useSDKInactivityTimeout: schedule disconnect"))},[r,e,t.opened])}const nc=l.createContext(null);function ds(){const e=l.useContext(nc);if(!e)throw new Error("useNavigator() must be used within <Navigator />");return e}function rc({children:e}){const t=ds();return typeof e=="function"?e(t):a.createElement(a.Fragment,null,e)}const iS=G.keyframes`0%{transform:translateY(40px);opacity:0;}100%{transform:translateY(0px);opacity:1;}`,aS=G.keyframes`0%{transform:translateY(0px);opacity:1;}100%{transform:translateY(40px);opacity:0;}`,cS=G.css`animation-name:${iS};animation-duration:0.3s;animation-fill-mode:forwards;`,lS=G.css``,uS=G.css`animation-name:${aS};animation-duration:0.3s;animation-fill-mode:forwards;`,dS=G.css`visibility:hidden;`,mS=C.default.div`position:absolute;top:0;left:0;width:100%;height:100%;${({$transitionState:e})=>{switch(e){case"entering":return cS;case"entered":return lS;case"exiting":return uS;case"exited":return dS;default:return""}}}${({$active:e})=>e?G.css`
|
|
498
498
|
z-index: 999;
|
|
499
|
-
`:
|
|
500
|
-
`;function Cn({initialId:e,children:t}){const[n,r]=l.useState([e]),s=n[n.length-1],o=l.useCallback((
|
|
499
|
+
`:G.css`z-index:1;pointer-events:none;`}
|
|
500
|
+
`;function Cn({initialId:e,children:t}){const[n,r]=l.useState([e]),s=n[n.length-1],o=l.useCallback((b,p)=>{r(S=>[...S,b]),h(S=>({...S,[b]:!0})),p!=null&&p.reset&&y(S=>({...S,[b]:(S[b]||0)+1})),g(S=>({...S,[b]:"entering"})),setTimeout(()=>{g(S=>({...S,[b]:"entered"}))},300)},[]),i=l.useCallback(()=>{r(b=>{if(b.length<=1)return b;const p=b[b.length-1];return g(S=>({...S,[p]:"exiting"})),setTimeout(()=>{g(S=>({...S,[p]:"exited"})),r(S=>S.slice(0,-1))},300),b})},[]),c=l.useMemo(()=>({navigation:{navigate:o,pop:i},activeScreenId:s}),[o,i,s]),u=l.useMemo(()=>l.Children.toArray(t).filter(b=>b.type===rc),[t]),d=l.useMemo(()=>{const b={};return u.forEach(p=>{const{id:S,lazy:A,children:T}=p.props;b[S]={lazy:A,element:typeof T=="function"?T(c):T}}),b},[u,c]),[m,h]=l.useState(()=>{const b={};return Object.entries(d).forEach(([p,{lazy:S}])=>{S===!1&&(b[p]=!0)}),b[e]=!0,b}),[f,g]=l.useState(()=>{const b={};return Object.keys(d).forEach(p=>{p===e?b[p]="entered":b[p]="exited"}),b}),[_,y]=l.useState({});return a.createElement(nc.Provider,{value:c},a.createElement(hS,null,Object.keys(d).map(b=>{var T;if(!m[b])return null;const p=f[b]||"exited",S=b===s,A=`${b}-${_[b]||0}`;return a.createElement(mS,{key:A,$transitionState:p,$active:S,"aria-hidden":S?void 0:!0,inert:S?void 0:!0},(T=d[b])==null?void 0:T.element)})))}const hS=C.default.div`position:relative;width:100%;height:100%;`;Cn.Screen=rc;const qe={conv:"conv",convList:"conv-list"},fS=e=>e===qe.convList?"ConversationList":"Conversation",gS=({isOpened:e,activeScreenId:t})=>e&&t===qe.conv,sc=({isOpened:e,entryPoint:t,selectedChannelUrl:n,setSelectedChannelUrl:r,onActiveRouteChange:s})=>{const{conversationComponent:o,conversationChildren:i,conversationListComponent:c,conversationListChildren:u}=tn(),[d,m]=l.useState(),h=(()=>{switch(t){case"Conversation":return qe.conv;case"ConversationList":return qe.convList;default:return qe.conv}})(),f=a.createElement(a.Fragment,null,a.createElement(pS,{onOpenConversationView:(g,_)=>{r(_),m(void 0),g.navigate(qe.conv)}}),a.createElement(_S,{onActiveRouteChange:s}));return a.createElement(Cn,{initialId:h},a.createElement(Cn.Screen,{id:qe.conv},({navigation:g,activeScreenId:_})=>{const y=gS({isOpened:e,activeScreenId:_});return a.createElement(a.Fragment,null,f,a.createElement(o,{key:n,channelUrl:n,onClearChannelUrl:()=>r(void 0),onNavigateToConversationList:()=>{m(void 0),g.navigate(qe.convList)},announcementsEnabled:y,conversationStatsEnabled:y,shouldMarkAsRead:y,shouldInitializeConversation:y,initialFocusTarget:d},i))}),a.createElement(Cn.Screen,{id:qe.convList,lazy:!0},({navigation:g,activeScreenId:_})=>{const y=e&&_===qe.convList;return a.createElement(a.Fragment,null,f,a.createElement(c,{announcementsEnabled:y,conversationListStatsEnabled:y,onOpenConversationView:(b,p,S)=>{r(b),m(S==null?void 0:S.initialFocusTarget),g.navigate(qe.conv)}},u))}))},pS=({onOpenConversationView:e})=>{const{registerOnJoinedProactiveConversation:t}=Ne(),{navigation:n}=ds();return t(({channel:r})=>{e(n,r.url)}),null},_S=({onActiveRouteChange:e})=>{const{activeScreenId:t}=ds();return l.useEffect(()=>{e==null||e(fS(t))},[t,e]),null},ES=({isExpanded:e,isOpened:t,children:n,launcher:r})=>a.createElement(Xr,null,a.createElement(CS,{isExpanded:e,isOpened:t,launcher:r},n)),CS=({isExpanded:e,isOpened:t,children:n,launcher:r})=>{const{dir:s}=le(),o=l.useRef(null),{hasWindowTitleReference:i,isWindowNameReady:c}=Un();return $n(t,o,{nameReady:c}),a.createElement(bS,null,a.createElement(vS,{ref:o,dir:s,id:ye.WINDOW,...us(t,i),$isExpanded:e,$isOpened:t},n),r)},bS=C.default.div`display:flex;flex-direction:column;gap:8px;align-items:flex-end;`,vS=C.default.div`background:${({theme:e})=>e.colors.base.background};display:flex;overscroll-behavior:none;-webkit-overflow-scrolling:auto;height:640px;min-height:80px;width:400px;max-width:80vw;max-height:80vh;box-shadow:0px 16px 24px 2px rgba(33,33,33,0.12),0px 6px 30px 5px rgba(33,33,33,0.08),0px 6px 10px -5px rgba(33,33,33,0.04);border-radius:16px;overflow:hidden;transition:width 200ms ease 0s,height 200ms ease 0s,max-height 200ms ease 0s,transform 150ms cubic-bezier(0,1.2,1,1) 0s,opacity 83ms ease-out 0s;transform:scale(0.15);opacity:0;transform-origin:right bottom;[dir='rtl'] &:not([dir='ltr']),&[dir='rtl']{transform-origin:left bottom;}${({$isOpened:e})=>e&&SS};${({$isExpanded:e})=>e&&yS};`,yS=G.css`width:743px;height:723px;`,SS=G.css`pointer-events:all;transform:scale(1);opacity:1;transition:width 200ms ease 0s,height 200ms ease 0s,max-height 200ms ease 0s,transform 300ms cubic-bezier(0,1.2,1,1) 0s,opacity 83ms ease-out 0s;`,AS=l.forwardRef(function({children:e,initialChannelUrl:t,...n},r){const s=Jt(),[o,i]=l.useState(t),[c,u]=l.useState(n.entryPoint??"Conversation"),d=s?Za:ES;return a.createElement(ls,{enableExpandButton:!s,ref:r,...n},a.createElement(ia,null,({state:m})=>a.createElement(Xa,null,a.createElement(d,{isExpanded:m.expanded,isOpened:m.opened,...s&&{zIndex:"auto"},launcher:a.createElement(tc,{entryPoint:n.entryPoint,activeRoute:c})},a.createElement(sc,{isOpened:m.opened,entryPoint:n.entryPoint,selectedChannelUrl:o,setSelectedChannelUrl:i,onActiveRouteChange:u})),e)))}),{Provider:TS,useContext:ms}=be("FixedMessengerStyle");function oc(e,t,n,r=0){const{top:s,bottom:o,start:i,end:c}=n;let u="",d="";switch(e){case"start":d=`inset-inline-start: ${Ze(i)}`;break;case"end":d=`inset-inline-end: ${Ze(c)}`;break}switch(t){case"top":u=`top: calc(${Ze(s)} + ${r}px)`;break;case"bottom":u=`bottom: calc(${Ze(o)} + ${r}px)`;break}return G.css`${u};${d};`}function IS(e){const{horizontal:t,vertical:n,margin:r,launcherSize:s}=ms();return a.createElement(xS,{...e,size:s,$horizontal:t,$vertical:n,$margin:r})}const xS=C.default(tc)`position:fixed;z-index:${gt.LAUNCHER};${({$horizontal:e,$vertical:t,$margin:n})=>oc(e,t,n)};`,RS=({isExpanded:e,isOpened:t,children:n})=>a.createElement(Xr,null,a.createElement(MS,{isExpanded:e,isOpened:t},n)),MS=({isExpanded:e,isOpened:t,children:n})=>{const{dir:r}=le(),{horizontal:s,vertical:o,margin:i,launcherSize:c}=ms(),u=l.useRef(null),{hasWindowTitleReference:d,isWindowNameReady:m}=Un();return $n(t,u,{nameReady:m}),a.createElement(wS,{ref:u,dir:r,id:ye.WINDOW,...us(t,d),$isExpanded:e,$isOpened:t,$horizontal:s,$vertical:o,$margin:i,$launcherSize:c},n)},wS=C.default.div`background:${({theme:e})=>e.colors.base.background};display:flex;overscroll-behavior:none;-webkit-overflow-scrolling:auto;position:fixed;pointer-events:none;visibility:hidden;${({$horizontal:e,$vertical:t,$margin:n,$launcherSize:r})=>oc(e,t,n,r+12)};height:640px;min-height:80px;width:400px;max-width:80vw;max-height:80vh;box-shadow:0px 16px 24px 2px rgba(33,33,33,0.12),0px 6px 30px 5px rgba(33,33,33,0.08),0px 6px 10px -5px rgba(33,33,33,0.04);border-radius:16px;overflow:hidden;transition:width 200ms ease 0s,height 200ms ease 0s,max-height 200ms ease 0s,transform 150ms cubic-bezier(0,1.2,1,1) 0s,opacity 83ms ease-out 0s,visibility 0s linear 150ms;transform:scale(0.15);opacity:0;transform-origin:${({$horizontal:e,$vertical:t})=>`${e==="start"?"left":"right"} ${t}`};
|
|
501
501
|
[dir='rtl'] &:not([dir='ltr']),
|
|
502
502
|
&[dir='rtl'] {
|
|
503
503
|
transform-origin: ${({$horizontal:e,$vertical:t})=>`${e==="start"?"right":"left"} ${t}`};
|
|
@@ -505,4 +505,4 @@
|
|
|
505
505
|
|
|
506
506
|
${({$isOpened:e})=>e&&LS};
|
|
507
507
|
${({$isExpanded:e})=>e&&kS};
|
|
508
|
-
`,kS=
|
|
508
|
+
`,kS=G.css`width:743px;height:723px;`,LS=G.css`z-index:${gt.WINDOW};pointer-events:all;visibility:visible;transform:scale(1);opacity:1;transition:width 200ms ease 0s,height 200ms ease 0s,max-height 200ms ease 0s,transform 300ms cubic-bezier(0,1.2,1,1) 0s,opacity 83ms ease-out 0s,visibility 0s linear 0s;`,ic={top:24,bottom:24,start:24,end:24},OS=l.forwardRef(function({children:e,initialChannelUrl:t,...n},r){const[s,o]=l.useState(t),[i,c]=l.useState(n.entryPoint??"Conversation"),[u,d]=l.useState("end-bottom"),[m,h]=l.useState(ic),[f,g]=l.useState(48),_=Jt(),y=_?Za:RS,{horizontal:b,vertical:p}=l.useMemo(()=>{const[S,A]=u.split("-");return{horizontal:S==="start"?"start":"end",vertical:A==="top"?"top":"bottom"}},[u]);return a.createElement(ls,{enableExpandButton:!_,ref:r,...n},a.createElement(ia,null,({state:S})=>a.createElement(TS,{value:{horizontal:b,vertical:p,margin:m,launcherSize:f,setPosition:d,setMargin:h,setLauncherSize:g}},a.createElement(Xa,null,a.createElement(y,{isExpanded:S.expanded,isOpened:S.opened},a.createElement(sc,{isOpened:S.opened,entryPoint:n.entryPoint,selectedChannelUrl:s,setSelectedChannelUrl:o,onActiveRouteChange:c})),a.createElement(IS,{entryPoint:n.entryPoint,activeRoute:i}),e))))}),NS=e=>{var s,o,i,c;const{setPosition:t,setMargin:n,setLauncherSize:r}=ms();return l.useLayoutEffect(()=>{e.position&&t(e.position),e.margin&&n({...ic,...e.margin}),e.launcherSize&&r(e.launcherSize)},[e.position,(s=e.margin)==null?void 0:s.top,(o=e.margin)==null?void 0:o.bottom,(i=e.margin)==null?void 0:i.start,(c=e.margin)==null?void 0:c.end,e.launcherSize]),null},DS=({children:e})=>{const{setConversationChildren:t}=tn();return l.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},$S=({component:e})=>{const{setConversationComponent:t}=tn();return l.useLayoutEffect(()=>(t(e),()=>t(os)),[e,t]),null},FS=({children:e})=>{const{setConversationListChildren:t}=tn();return l.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},PS=({component:e})=>{const{setConversationListComponent:t}=tn();return l.useLayoutEffect(()=>(t(e),()=>t(cs)),[e,t]),null},US=Object.assign(OS,{Style:NS,Conversation:$S,ConversationChildren:DS,ConversationList:PS,ConversationListChildren:FS}),BS=e=>{const{refreshActiveChannel:t}=Ne(),[n,r]=l.useState(!1),s=l.useRef(null),o=l.useRef(null);return l.useEffect(()=>{n&&t().then(()=>{var i;(i=s.current)==null||i.call(s),r(!1)}).catch(i=>{var c;(c=o.current)==null||c.call(o,i),r(!1)})},[n]),l.useCallback(()=>new Promise((i,c)=>{s.current=i,o.current=c,e().then(()=>r(!0)).catch(c)}),[e])};pi.set(de.SendbirdPlatform.JS,{deviceOSPlatform:Oc()?de.DeviceOsPlatform.MOBILE_WEB:de.DeviceOsPlatform.WEB,messengerVersion:gh,keyValueStorage:Eh(),networkStateAdapter:_h(),scheduleForegroundTask:ph});exports.ANCHOR_REL=zr;exports.AgentProviderContainer=ls;exports.AgentUIProviderContainer=Wa;exports.AnonymousSessionInfo=ur;exports.CSATType=Je;exports.Commands=ct;exports.ConnectionDelayLayout=Fn;exports.Conversation=os;exports.ConversationContext=eg;exports.ConversationContextProvider=da;exports.ConversationHeaderLayout=Et;exports.ConversationLayout=Vn;exports.ConversationList=cs;exports.ConversationListContext=ly;exports.ConversationListContextProvider=Ya;exports.ConversationListHeaderLayout=Mt;exports.ConversationListItemLayout=as;exports.ConversationListLayout=qn;exports.DefaultMessenger=AS;exports.DeskTicketPriority=Dr;exports.DeskTicketStatus=Nr;exports.FixedMessenger=US;exports.ID_INCOMING=tt;exports.IncomingMessageLayout=_t;exports.LauncherBase=Ja;exports.LogLevel=wr;exports.ManualSessionInfo=ai;exports.MessageListUILayout=zn;exports.MessageLogs=Pa;exports.OutgoingMessageLayout=xt;exports.PlaceholderLayout=Gn;exports.SystemMessageLayout=Hn;exports.cssVars=E;exports.escapeMarkdownSyntax=kc;exports.flattenObject=Jl;exports.mapCommonStringsToReactFormat=Ki;exports.messengerDispatcher=ja;exports.noop=ue;exports.parseToMessageTemplate=fi;exports.parseToUITemplate=Xl;exports.pickColorByTheme=Zl;exports.replaceVariablesAsync=eu;exports.replaceVariablesSync=Ql;exports.useAIAgentContext=ke;exports.useConversationContext=Ae;exports.useConversationListContext=en;exports.useLocalizationContext=se;exports.useMessageTemplateFetchingContext=Kd;exports.useMessengerContext=le;exports.useMessengerSessionContext=Ne;exports.useMessengerThemeContext=Ji;exports.useRefreshActiveChannel=BS;
|