@sendbird/ai-agent-messenger-react 1.35.0 → 1.36.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +177 -177
- package/dist/index.d.ts +1596 -902
- package/dist/index.js +5184 -5014
- package/package.json +5 -5
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(`
|
|
2
|
-
`),n=[];let r=0;for(;r<t.length;){const s=t[r],o=t[r+1],i=
|
|
3
|
-
`)},
|
|
4
|
-
`),r=[];let s=0;for(;s<n.length;){const o=n[s],i=
|
|
5
|
-
`)},
|
|
6
|
-
`;){if(e[c]==="`"&&!
|
|
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`
|
|
1
|
+
"use strict";var nc=Object.defineProperty;var rc=(e,t,n)=>t in e?nc(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var S=(e,t,n)=>rc(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Ce=require("@sendbird/chat"),l=require("react"),H=require("styled-components"),ot=require("date-fns"),sc=require("date-fns/locale/en-US"),De=require("@sendbird/chat/message"),fe=require("@sendbird/chat/aiAgent"),oc=require("react-dom"),We=require("@sendbird/chat/groupChannel"),ic=require("date-fns/isSameDay"),ac=require("dompurify"),Ar=e=>e&&e.__esModule?e:{default:e};function cc(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 lc=Ar(Ce),a=cc(l),E=Ar(H),zo=Ar(ac),Vo=e=>{try{return JSON.parse(e===""?"{}":e)}catch{return{}}},uc=e=>{const t=Vo(e);return typeof t=="object"&&t!==null?t:{}},qo=e=>typeof e=="string"?uc(e):e??{},dc=e=>!!qo(e).stream,ms=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},Ko=e=>{const t=qo(e),n=ms(t.user_message_id)??ms(t.respond_mesg_id);return{isStreaming:!!t.stream,hasResponseMetadata:Object.prototype.hasOwnProperty.call(t,"stream")||n!==void 0,...n!==void 0&&{userMessageId:n}}},Ct="sb-agent",Yo="KEY_IMG_ASPECT_RATIO",ir="*/*",re={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 pn=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(pn||{}),Ft=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(Ft||{});const mc=e=>!!(e!=null&&e.cta_button),hc=e=>{var t;return!!((t=e==null?void 0:e.citations)!=null&&t.length)},Wo=e=>!!(e!=null&&e.form)&&!e.form.canceled_at,fc=e=>{var t;return Wo(e)&&!((t=e==null?void 0:e.form)!=null&&t.submitted_at)},gc=e=>{var t;return!!((t=e==null?void 0:e.suggested_replies)!=null&&t.length)},He=e=>{let t;return{enumerable:!0,get:()=>(t??(t=e()),t)}},In=e=>Object.defineProperties({},{hasMessageTemplate:He(()=>!!(e!=null&&e.message_template)),hasCTAButton:He(()=>mc(e)),hasChallenge:He(()=>!!(e!=null&&e.challenge)),isThinking:He(()=>!!(e!=null&&e.is_thinking)),hasCSAT:He(()=>!!(e!=null&&e.csat)),hasSuggestedReplies:He(()=>gc(e)),hasCustomMessageTemplates:He(()=>{var t;return!!((t=e==null?void 0:e.custom_message_templates)!=null&&t.length)}),hasForm:He(()=>Wo(e)),hasActiveForm:He(()=>fc(e)),hasSteward:He(()=>!!(e!=null&&e.steward)),hasCitations:He(()=>hc(e))}),pc=e=>{const t=In(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)},_c=e=>e===Ft.COMPLETED||e===Ft.CANCELED?e:Ft.IN_PROGRESS,Gn=e=>Xe(e)&&!jo(e),Xe=e=>!!e&&"sender"in e,Ec=e=>Xe(e)?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId),Cc=(e,t,n,r=!0)=>{if(!r||!Gn(e))return"single";const s=()=>{if(!Gn(t))return!1;const u=t.sender.userId===e.sender.userId,d=ot.isSameMinute(t.createdAt,e.createdAt);return u&&d},o=()=>{if(!Gn(n))return!1;const u=n.sender.userId===e.sender.userId,d=ot.isSameMinute(n.createdAt,e.createdAt);return u&&d},i=s(),c=o();return i&&c?"middle":i?"bottom":c?"top":"single"},tt=(e,t)=>(()=>{var r;return Xe(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)=>Xe(e)&&e.sender.userId!==t,isOutgoing:(e,t)=>Xe(e)&&(e.sender.userId===t||e.sendingStatus===De.SendingStatus.PENDING)},Ve=e=>e.startsWith("image/"),zt=e=>e.startsWith("video/"),bc=e=>e.startsWith("audio/"),Xo=({name:e="",mimeType:t=""})=>t==="application/pdf"||/\.pdf$/i.test(e.trim()),Tr=(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"},Zo=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},vc=e=>{if(e.message&&e.message.trim().length>0)return!0;const t=e.extendedMessagePayload;return pc(t)},xn=e=>{switch(e){case"top":case"middle":return re.GAP_GROUPED;default:return re.GAP_UNGROUPED}},Sc=(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},yc=e=>e.replace(/\[([^\]]+)\](?!\()/g,"\\[$1\\]"),Ac=e=>e.replace(/([a-zA-Z0-9])_(?=[a-zA-Z0-9])/g,"$1\\_"),Tc=e=>e.replace(/~~/g,"\\~\\~"),Ic=e=>{let t=e;return t=yc(t),t=Ac(t),t=Tc(t),t},xc=typeof navigator<"u"&&navigator.product==="ReactNative",hs=(e,t)=>{const n=r=>!t||t.length===0?!0:Xe(r)&&t.includes(r.sendingStatus);return xc?e.find(n):e.findLast(n)},Ie=e=>{requestAnimationFrame(()=>{requestAnimationFrame(e)})};function he(){}function Rc(){const e=typeof navigator<"u"?navigator.userAgent:"",t=/iPad|iPhone|iPod/.test(e),n=/Android/.test(e);return t||n}function Mc(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 ke={isStreaming(e){return dc(e.data)},isExplicitWelcomeMessage(e){var t;return((t=e.extendedMessagePayload)==null?void 0:t.bot_message_type)==="welcome"},isWelcomeMessage(e,t){var r;if(ke.isExplicitWelcomeMessage(e))return!0;if(((r=e.extendedMessagePayload)==null?void 0:r.bot_message_type)!==void 0||!tt(e,t))return!1;const n=Ko(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)}},zn=`@${Ct}`,wc=({appId:e,aiAgentId:t,storage:n})=>{const r={templateBase:`${zn}-template`,template:s=>`${r.templateBase}/templates/${s}`,templateToken:()=>`${r.templateBase}/tokens`,messengerSession:s=>{const o=Mc(`${e}/${t}/${s}`);return`${zn}-udata/${o}`},anonUserSession:()=>`${zn}-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}}}}},Jo=(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},kc=()=>{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 Lc{constructor(t){S(this,"_params");this._params={aiAgentChannelFilter:(t==null?void 0:t.aiAgentChannelFilter)??fe.AIAgentChannelFilter.INCLUDE,aiAgentConversationStatusFilter:(t==null?void 0:t.aiAgentConversationStatusFilter)??[fe.ConversationStatus.OPEN,fe.ConversationStatus.CLOSED],aiAgentIds:(t==null?void 0:t.aiAgentIds)??[],deskChannelFilter:(t==null?void 0:t.deskChannelFilter)??fe.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===fe.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!==fe.DeskChannelFilter.EXCLUDE:!1}}class Qo extends We.BaseChannelCollection{constructor(n,r){const s=new Lc(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:p}=s.params,b={aiAgentChannelFilter:h,aiAgentIds:f,deskChannelFilter:g,pinnedChannelUrls:C,copilotConversationOnly:v,copilotSupportChannelUrl:p};return i.getMyGroupChannelChangeLogs(m,b,We.GroupChannelEventSource.SYNC_CHANNEL_CHANGELOGS)}};super(o.aiAgent._iid,{filter:s,order:u,limit:c,syncKeyPrefix:"aiAgent",fetcher:d});S(this,"_params");S(this,"_sdk");S(this,"_throttledOnChannelChanged");S(this,"_key");S(this,"_pendingChannels",[]);this._sdk=n,this._params=r,this._key=`clc-${kc()}`,this._throttledOnChannelChanged=Jo(()=>{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 p=Array.from(v.values()),b=(g=this._sdk.currentUser)==null?void 0:g.userId,y=p.filter(T=>this.filter.match(T,b)),A=p.filter(T=>!this.filter.match(T,b)).map(T=>T.url);y.length>0&&this._base._addChannelsToView(y,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 ei{constructor(t){S(this,"subscribers",{});this.logger=t}async send(t){const n=Oc(),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 Oc=()=>{let e=he,t=he;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}};var ze=(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))(ze||{});class Vt{constructor(t={}){S(this,"payload");this.payload=t}toJSON(){return JSON.stringify({type:this.type,payload:this.payload})}}const it={CloseConversation:e=>new Nc(e),MessengerSettingsUpdated:e=>new Dc(e),ActiveChannelUpdated:e=>new $c(e),AnonymousSessionTokenExpired:()=>new Pc,AuthTokenRefreshed:()=>new Fc};class Nc extends Vt{constructor(){super(...arguments);S(this,"type","conv.close")}}class Dc extends Vt{constructor(){super(...arguments);S(this,"type","messenger.settings.updated")}}class $c extends Vt{constructor(){super(...arguments);S(this,"type","active.channel.updated")}}class Pc extends Vt{constructor(){super(...arguments);S(this,"type","anon.token.expired")}}class Fc extends Vt{constructor(){super(...arguments);S(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){S(this,"category","connection");this.userId=t}get data(){return qt({user_id:this.userId})}}class Uc extends Kt{constructor(){super(...arguments);S(this,"metricKey","connection_connected")}}class Bc extends Kt{constructor(){super(...arguments);S(this,"metricKey","connection_reconnect_started")}}class Hc extends Kt{constructor(){super(...arguments);S(this,"metricKey","connection_reconnect_succeeded")}}class Gc extends Kt{constructor(){super(...arguments);S(this,"metricKey","connection_reconnect_failed")}}class zc extends Kt{constructor(){super(...arguments);S(this,"metricKey","connection_disconnected")}}class Vc{constructor(t){S(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 Uc(n):t==="reconnectStarted"?new Bc(n):t==="reconnectSucceeded"?new Hc(n):t==="reconnectFailed"?new Gc(n):new zc(n);this.dispatch(s)}}shouldEmit(t){return t!==this.lastKey}}class Ir{constructor(t,n){S(this,"category","conversation");this.channelUrl=t,this.conversationId=n}get data(){return qt({channel_url:this.channelUrl,conversation_id:this.conversationId})}}class qc extends Ir{constructor(){super(...arguments);S(this,"metricKey","conversation_initialized")}}class Kc extends Ir{constructor(){super(...arguments);S(this,"metricKey","conversation_open")}}class Yc extends Ir{constructor(){super(...arguments);S(this,"metricKey","conversation_closed")}}class Wc{constructor(t){S(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===fe.ConversationStatus.INITIALIZED?new qc(t.url,n.id):s===fe.ConversationStatus.OPEN?new Kc(t.url,n.id):new Yc(t.url,n.id);this.dispatch(o)}}shouldEmit(t,n){return n===fe.ConversationStatus.INITIALIZED?t===void 0:n===fe.ConversationStatus.OPEN?t===fe.ConversationStatus.INITIALIZED:t===fe.ConversationStatus.OPEN}}const ti=(e,t)=>{if(e)return e.members.filter(n=>n.userId!==t).sort((n,r)=>r.joinedAt-n.joinedAt)[0]},Fe=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===fe.ConversationStatus.CLOSED||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="closed")},xr=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===fe.ConversationStatus.OPEN||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="open")};function et(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 jc(e){var r;const t=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff;return t?typeof t.requestedAt=="number"&&!et(e):!1}function Xc(e){var t;if(((t=e==null?void 0:e.resolution)==null?void 0:t.determinedBy)==="user")return e.resolution.isResolved}function ni(e){return!!e&&e<=Date.now()}function Zc(e){return!e.title}function Jc(e,t){var n;if(e)return Zc(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 Rr{constructor(t,n){S(this,"category","handoff");this.channelUrl=t,this.conversationId=n}get data(){return qt({channel_url:this.channelUrl,conversation_id:this.conversationId})}}class Qc extends Rr{constructor(){super(...arguments);S(this,"metricKey","handoff_started")}}class el extends Rr{constructor(){super(...arguments);S(this,"metricKey","handoff_succeeded")}}class tl extends Rr{constructor(){super(...arguments);S(this,"metricKey","handoff_failed")}}class nl{constructor(t){S(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 Qc(t.url,r.id):o==="succeeded"?new el(t.url,r.id):new tl(t.url,r.id);this.dispatch(i)}}resolveStatus(t,n){if(Fe(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 rl{constructor(t){S(this,"category","message");S(this,"metricKey","incoming_message_received");S(this,"channelUrl");S(this,"messageId");S(this,"senderType");S(this,"createdAt");S(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 sl=(e,t)=>{const n=Xe(e)?e.sender.userId:void 0;return n===void 0?"system":n===t?"ai_agent":"human_agent"};class ol{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 rl({channelUrl:t.url,messageId:n.messageId,senderType:sl(n,r.aiAgentId),createdAt:n.createdAt,conversationId:r.id}))}shouldEmit(t,n){return!tt(t,this.getCurrentUserId())&&n!==null}}class il{constructor(t){S(this,"category","message");S(this,"metricKey");S(this,"channelUrl");S(this,"requestId");S(this,"messageId");S(this,"target");S(this,"sendingStatus");S(this,"createdAt");S(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 al=e=>{switch(e){case De.SendingStatus.PENDING:return"pending";case De.SendingStatus.SUCCEEDED:return"succeeded";case De.SendingStatus.FAILED:return"failed";case De.SendingStatus.SCHEDULED:return"scheduled";default:return}};class cl{constructor(t,n){S(this,"statusByReqId",new Map);this.dispatch=t,this.getCurrentUserId=n}handleEvent({channel:t,message:n}){var o;if(!tt(n,this.getCurrentUserId()))return;const r=al(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 il({channelUrl:t.url,requestId:n.reqId,messageId:r==="succeeded"?n.messageId:void 0,target:et(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 ll{constructor(t){S(this,"id","aiagent_livemetric");S(this,"dispatch");S(this,"emit",({category:t,metricKey:n,data:r})=>{var s;(s=this.dispatch)==null||s.call(this,{category:t,metricKey:n,data:r})});S(this,"emitters");this.chatSDK=t;const n=()=>{var r;return(r=this.chatSDK.currentUser)==null?void 0:r.userId};this.emitters={connection:new Vc(this.emit),conversation:new Wc(this.emit),handoff:new nl(this.emit),incomingMessage:new ol(this.emit,n),outgoingMessage:new cl(this.emit,n)}}start(){const t=new Ce.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 Mr=(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))(Mr||{});class ri{constructor(t){S(this,"level");this.level=t}verbose(...t){this.level<=0&&console.log(`[${Ct}/verbose]`,...t)}debug(...t){this.level<=1&&console.log(`[${Ct}/debug]`,...t)}info(...t){this.level<=2&&console.log(`[${Ct}/info]`,...t)}warn(...t){this.level<=3&&console.warn(`[${Ct}/warn]`,...t)}error(...t){this.level<=4&&console.error(`[${Ct}/error]`,...t)}}class si{constructor({userId:t,authToken:n,sessionHandler:r}){S(this,"userId");S(this,"authToken");S(this,"sessionHandler");this.userId=t,this.authToken=n,this.sessionHandler=r}}class ar{constructor(){S(this,"userId");S(this,"authToken");S(this,"sessionHandler")}}const ul=e=>({onSessionTokenRequired:t=>{t(null),e.send(it.AnonymousSessionTokenExpired())}}),wr=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!=null)),dl="ai_agent:stats",ml="conversation_initial_render",hl="conversation_not_interactive_timeout",fl="recovery_not_interactive_timeout",gl="conversation_list_initial_render",pl="message_pending_stuck",_l="aiev_auth_expired_unhandled",El="user_perceived_response_time",Cl="stream_stalled",bl="ai_typing_indicator_absent_timeout",vl="rendered_content_unusable",Sl=800220;var z=(e=>(e.ACK_TO_FIRST_CHUNK="ack_to_first_chunk_ms",e.AFTER_TPEN_ABSENT="after_tpen_absent_ms",e.AUTH="auth_duration_ms",e.BEFORE_TPST_ABSENT="before_tpst_absent_ms",e.FIRST_CHUNK_TO_RENDER="first_chunk_to_render_ms",e.GET_CHANNEL="get_channel_duration_ms",e.GET_LIST="get_list_duration_ms",e.GET_MESSAGES="get_messages_duration_ms",e.PAGE_RENDER="page_render_duration_ms",e.PAGE_RENDER_FROM_CACHE="total_duration_from_cache_ms",e.SEND_TO_ACK="send_to_ack_ms",e.TIMEOUT="timeout_ms",e))(z||{});const cr=(e,t)=>e.startAt===null||e.endedAt===null||t.startAt===null||t.endedAt===null?0:Math.max(0,Math.min(e.endedAt,t.endedAt)-Math.max(e.startAt,t.startAt)),oi=e=>typeof e=="object"&&e!==null,yl=e=>{if(oi(e))return typeof e.code=="number"?e.code:void 0},Al=e=>e instanceof Error?e.message:typeof e=="string"?e:oi(e)&&typeof e.message=="string"?e.message:"";class Ze{constructor(){S(this,"timers",new Map);S(this,"committed",!1);S(this,"commitCallback",null);S(this,"conversationId",null);S(this,"errorCode",null);S(this,"errorDescription",null);S(this,"extraData",{})}setCommitCallback(t){return this.commitCallback=t,this}setConversationId(t){return t&&(this.conversationId=t),this}setError(t){return t==null?this:(this.errorCode=yl(t)??Sl,this.errorDescription=Al(t),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:performance.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:performance.now()}),this)}getTimer(t){const n=this.timers.get(t);return!n||n.startTime===null?{startAt:null,endedAt:null,duration:null}:{startAt:n.startTime,endedAt:n.endTime,duration:n.endTime===null?null:n.endTime-n.startTime}}createPayload(t,n){const r={key:this.getMetricKey(),value:String(t)},s=(n==null?void 0:n.conversationId)??this.conversationId??void 0;s!==void 0&&(r.conversation_id=s),this.errorCode!==null&&(r.error_code=this.errorCode,r.error_description=this.errorDescription??"");const o=wr({...this.extraData,...n==null?void 0:n.extra});return Object.keys(o).length>0&&(r.extra=o),r}isCommitted(){return this.committed}discard(){this.committed=!0}commit(){if(this.committed||!this.commitCallback)return!1;const t=this.buildPayload();return t?(this.committed=!0,this.commitCallback(dl,t)):!1}}class fs extends Ze{constructor(){super(...arguments);S(this,"reason");S(this,"aiAgentId")}setReason(n){return this.reason=n,this}setAIAgentId(n){return this.aiAgentId=n,this}getMetricKey(){return _l}buildPayload(){return this.reason===void 0||this.aiAgentId===void 0?null:this.createPayload(this.reason,{extra:{agent_id:this.aiAgentId}})}}class Rn{constructor(t){S(this,"commitCallback");this.commitCallback=t}}class It extends Rn{constructor(){super(...arguments);S(this,"records",new Map)}}class ii extends Rn{constructor(){super(...arguments);S(this,"activeSpan",null);S(this,"visible",!0)}setVisible(n){var r;this.visible=n,(r=this.activeSpan)==null||r.onVisibilityChanged(n)}}class ai{constructor(t,n){S(this,"stats");S(this,"visible");S(this,"completedHidden",!1);this.stats=t,this.visible=n}get isRecording(){return this.stats!==null&&!this.stats.isCommitted()}onVisibilityChanged(t){this.stats&&(this.visible=t,t&&this.completedHidden&&(this.stats.commit(),this.stats=null))}commitOrDefer(){if(this.stats){if(!this.visible){this.completedHidden=!0;return}this.stats.commit(),this.stats=null}}cancel(){this.stats=null}}const dt=(e,t)=>!(e&&t&&e!==t),lr=(e,t)=>{for(const n of e)if(n.measure.userMessageId===void 0&&dt(n.measure.channelUrl,t))return!0;return!1},Mn=(e,t)=>{if(e.size<t)return;const n=e.keys().next();n.done||e.delete(n.value)};class Tl extends Rn{onPayloadParseFailed(t){new fs().setReason("payload_parse_failed").setAIAgentId(t.aiAgentId).setCommitCallback(this.commitCallback).commit()}onCallbackNotFound(t){new fs().setReason("callback_not_found").setAIAgentId(t.aiAgentId).setCommitCallback(this.commitCallback).commit()}clear(){}}class Il extends Ze{constructor(){super(...arguments);S(this,"channelUrl",null);S(this,"presentMethod","direct_present")}setChannelUrl(n){return this.channelUrl=n,this}setPresentMethod(n){return this.presentMethod=n,this}resetPageRenderSpan(){return this.timers.delete(z.PAGE_RENDER),this.timers.delete(z.PAGE_RENDER_FROM_CACHE),this.timers.delete(z.GET_CHANNEL),this.timers.delete(z.GET_MESSAGES),this.conversationId=null,this.channelUrl=null,this.errorCode=null,this.errorDescription=null,this}getMetricKey(){return ml}buildPayload(){const n=this.getTimer(z.AUTH),r=this.getTimer(z.PAGE_RENDER),s=this.getTimer(z.PAGE_RENDER_FROM_CACHE);if(r.duration===null&&(this.errorCode===null||n.duration===null))return null;const o=r.duration===null?0:r.duration-cr(n,r),i=s.duration===null?null:s.duration-cr(n,s);return this.createPayload((n.duration??0)+o,{extra:{channel_url:this.channelUrl,present_method:this.presentMethod,[z.AUTH]:n.duration,[z.GET_CHANNEL]:this.getTimer(z.GET_CHANNEL).duration,[z.GET_MESSAGES]:this.getTimer(z.GET_MESSAGES).duration,[z.PAGE_RENDER_FROM_CACHE]:i}})}}class xl extends ai{constructor(n,r,s){var o;super(n,s);S(this,"measure");this.measure={channelUrl:r,pageRenderState:"initialized"},(o=this.stats)==null||o.setChannelUrl(r).startTimer(z.PAGE_RENDER).startTimer(z.PAGE_RENDER_FROM_CACHE)}onGetChannelStart(n){!this.stats||n!==this.measure.channelUrl||this.measure.pageRenderState!=="initialized"||(this.stats.startTimer(z.GET_CHANNEL),this.measure.pageRenderState="channel_fetching")}onGetChannelComplete(n,r){!this.stats||n!==this.measure.channelUrl||this.measure.pageRenderState!=="channel_fetching"||(this.stats.stopTimer(z.GET_CHANNEL).setConversationId(r),this.measure.pageRenderState="channel_fetched")}onGetChannelError(n,r){!this.stats||n!==this.measure.channelUrl||this.measure.pageRenderState!=="channel_fetching"||(this.stats.stopTimer(z.GET_CHANNEL).setError(r).stopTimer(z.PAGE_RENDER),this.measure.pageRenderState="channel_failed",this.tryFinalize())}onGetMessagesStart(){!this.stats||this.measure.pageRenderState!=="channel_fetched"||(this.stats.startTimer(z.GET_MESSAGES),this.measure.pageRenderState="messages_fetching")}onGetMessagesCacheComplete(n,r){!this.stats||n!==this.measure.channelUrl||r||this.measure.pageRenderState!=="messages_fetching"||this.stats.stopTimer(z.PAGE_RENDER_FROM_CACHE)}onGetMessagesComplete(n,r){!this.stats||n!==this.measure.channelUrl||this.measure.pageRenderState!=="messages_fetching"||(this.stats.stopTimer(z.GET_MESSAGES).setError(r),this.measure.pageRenderState="messages_fetching_completed")}onRendered(){!this.stats||this.measure.pageRenderState!=="messages_fetching_completed"||(this.stats.stopTimer(z.PAGE_RENDER),this.tryFinalize())}onRenderDiscarded(){!this.stats||this.measure.pageRenderState!=="messages_fetching_completed"||(this.stats.discard(),this.stats=null)}onAuthSettled(){this.tryFinalize()}tryFinalize(){if(!this.stats||this.stats.getTimer(z.PAGE_RENDER).endedAt===null)return;const n=this.stats.getTimer(z.AUTH);if(!(n.startAt!==null&&n.endedAt===null)){if(this.measure.pageRenderState==="channel_failed"){this.stats.commit(),this.stats=null;return}this.commitOrDefer()}}}class Rl extends ii{constructor(){super(...arguments);S(this,"stats",null);S(this,"authState","idle");S(this,"presentMethod","direct_present")}getOrCreateStats(){var n;return(n=this.stats)!=null&&n.isCommitted()?null:(this.stats||(this.stats=new Il().setCommitCallback(this.commitCallback).setPresentMethod(this.presentMethod)),this.stats)}getActiveStats(){return!this.stats||this.stats.isCommitted()?null:this.stats}setPresentMethod(n){var r;this.presentMethod=n,(r=this.getActiveStats())==null||r.setPresentMethod(n)}onAuthStart(){var n,r;if((n=this.stats)!=null&&n.isCommitted()){if(this.authState!=="failed"||this.activeSpan!==null)return;this.stats=null,this.authState="idle"}this.authState==="idle"&&(this.authState="in_progress",(r=this.getOrCreateStats())==null||r.startTimer(z.AUTH))}onAuthComplete(){var n,r;this.authState==="in_progress"&&(this.authState="completed",(n=this.getActiveStats())==null||n.stopTimer(z.AUTH)),(r=this.activeSpan)==null||r.onAuthSettled()}onAuthError(n){var r,s;this.authState==="in_progress"&&(this.authState="failed",(r=this.getActiveStats())==null||r.stopTimer(z.AUTH).setError(n).commit(),(s=this.activeSpan)==null||s.cancel())}startSpan(n){const r=this.activeSpan;r==null||r.cancel();const s=this.getOrCreateStats();return s&&r&&s.resetPageRenderSpan(),this.activeSpan=new xl(s,n,this.visible),this.activeSpan}clear(){var n;(n=this.activeSpan)==null||n.cancel(),this.activeSpan=null,this.stats=null,this.authState="idle"}}class Ml extends Ze{constructor(){super(...arguments);S(this,"presentMethod","direct_present")}setPresentMethod(n){return this.presentMethod=n,this}resetPageRenderSpan(){return this.timers.delete(z.PAGE_RENDER),this.timers.delete(z.GET_LIST),this.errorCode=null,this.errorDescription=null,this}getMetricKey(){return gl}buildPayload(){const n=this.getTimer(z.AUTH),r=this.getTimer(z.PAGE_RENDER),s=this.getTimer(z.GET_LIST).duration;if(r.duration===null&&(this.errorCode===null||n.duration===null))return null;const o=r.duration===null?0:r.duration-cr(n,r),i=(n.duration??0)+o;return this.createPayload(i,{extra:{present_method:this.presentMethod,[z.AUTH]:n.duration,[z.GET_LIST]:s}})}}class wl extends ai{constructor(n,r){var s;super(n,r);S(this,"measure",{listStarted:!1,listCompleted:!1});(s=this.stats)==null||s.startTimer(z.PAGE_RENDER)}onListRequestStart(){!this.stats||this.measure.listStarted||(this.stats.startTimer(z.PAGE_RENDER),this.stats.startTimer(z.GET_LIST),this.measure.listStarted=!0)}onListRequestComplete(n){if(!(!this.stats||!this.measure.listStarted||this.measure.listCompleted)){if(n){this.stats.resetPageRenderSpan(),this.measure.listStarted=!1;return}this.stats.stopTimer(z.GET_LIST),this.measure.listCompleted=!0}}onRendered(){!this.stats||!this.measure.listCompleted||(this.stats.stopTimer(z.PAGE_RENDER),this.tryFinalize())}onRenderDiscarded(){!this.stats||!this.measure.listCompleted||(this.stats.discard(),this.stats=null)}onAuthSettled(){this.tryFinalize()}tryFinalize(){if(!this.stats||this.stats.getTimer(z.PAGE_RENDER).endedAt===null)return;const n=this.stats.getTimer(z.AUTH);n.startAt!==null&&n.endedAt===null||this.commitOrDefer()}}class kl extends ii{constructor(){super(...arguments);S(this,"stats",null);S(this,"authState","idle");S(this,"presentMethod","direct_present")}getOrCreateStats(){var n;return(n=this.stats)!=null&&n.isCommitted()?null:(this.stats||(this.stats=new Ml().setCommitCallback(this.commitCallback).setPresentMethod(this.presentMethod)),this.stats)}getActiveStats(){return!this.stats||this.stats.isCommitted()?null:this.stats}setPresentMethod(n){var r;this.presentMethod=n,(r=this.getActiveStats())==null||r.setPresentMethod(n)}onAuthStart(){var n;this.authState="in_progress",(n=this.getOrCreateStats())==null||n.startTimer(z.AUTH)}onAuthComplete(){var r,s;const n=this.authState==="in_progress";this.authState="completed",n&&((r=this.getActiveStats())==null||r.stopTimer(z.AUTH)),(s=this.activeSpan)==null||s.onAuthSettled()}onAuthError(n){var o;const r=this.authState==="in_progress";this.authState="failed";const s=this.getActiveStats();if(s){if(!((o=this.activeSpan)!=null&&o.isRecording)){this.stats=null;return}r&&s.stopTimer(z.AUTH),s.setError(n).commit(),this.activeSpan.cancel()}}startSpan(){const n=this.activeSpan;n==null||n.cancel();const r=this.getOrCreateStats();return r&&n&&r.resetPageRenderSpan(),r&&this.authState==="in_progress"&&r.startTimer(z.AUTH),this.activeSpan=new wl(r,this.visible),this.activeSpan}clear(){var n;(n=this.activeSpan)==null||n.cancel(),this.activeSpan=null,this.stats=null,this.authState="idle"}}class Ll extends Ze{constructor(){super(...arguments);S(this,"phaseReached","auth");S(this,"historyLoadResult","pending")}setHistoryLoadResult(n){return this.historyLoadResult=n,this}setPhaseReached(n){return this.phaseReached=n,this}getMetricKey(){return hl}buildPayload(){const n=this.getTimer(z.TIMEOUT).duration;return n===null?null:this.createPayload(n,{extra:{outcome:"timeout",phase_reached:this.phaseReached,history_load_result:this.historyLoadResult}})}}class Ol extends It{start(t){const n=this.getKey(t==null?void 0:t.channelUrl);this.clearKey(n);const r={stats:new Ll().setCommitCallback(this.commitCallback).startTimer(z.TIMEOUT),measure:{channelUrl:t==null?void 0:t.channelUrl,historyLoadResult:"pending",inputEnabled:!1,timer:null}};(t==null?void 0:t.conversationId)!==void 0&&r.stats.setConversationId(t.conversationId),r.measure.timer=setTimeout(()=>this.commitTimeout(n),1e4),this.records.set(n,r)}markChannelJoined(t,n){const r=this.getRecord(n);r&&(r.stats.setPhaseReached("channel_join"),t!==void 0&&r.stats.setConversationId(t))}markHistoryLoaded(t,n){const r=this.getRecord(n);r&&(r.measure.historyLoadResult=t,r.stats.setHistoryLoadResult(t).setPhaseReached("history_load"),this.cancelIfReady(n))}markInputReady(t){const n=this.getRecord(t);n&&(n.measure.inputEnabled=!0,n.stats.setPhaseReached("input_enable"),this.cancelIfReady(t))}markRendered(t){const n=this.getRecord(t);n&&n.stats.setPhaseReached("render")}clear(){this.records.forEach(t=>{t.measure.timer!==null&&clearTimeout(t.measure.timer)}),this.records.clear()}clearChannel(t){t!==void 0&&this.clearKey(this.getKey(t))}clearKey(t){const n=this.records.get(t);n&&(n.measure.timer!==null&&clearTimeout(n.measure.timer),this.records.delete(t))}cancelIfReady(t){const n=this.getRecord(t);!n||!n.measure.inputEnabled||n.measure.historyLoadResult==="pending"||this.clearKey(this.getKey(n.measure.channelUrl))}commitTimeout(t){const n=this.records.get(t);n&&(n.measure.timer=null,this.records.delete(t),n.stats.stopTimer(z.TIMEOUT).commit())}getRecord(t){return t!==void 0?this.records.get(this.getKey(t)):this.records.size===1?this.records.values().next().value:this.records.get(this.getKey())}getKey(t){return t??"__default__"}}class Nl extends Ze{constructor(){super(...arguments);S(this,"requestId");S(this,"messageType");S(this,"stuckReason")}setRequestId(n){return this.requestId=n,this}setMessageType(n){return this.messageType=n,this}setStuckReason(n){return this.stuckReason=n,this}getMetricKey(){return pl}buildPayload(){return this.requestId===void 0||this.messageType===void 0||this.stuckReason===void 0?null:this.createPayload(this.stuckReason,{extra:{message_type:this.messageType,request_id:this.requestId}})}}const Dl=5e3,gs=1e4;class $l extends It{start(t){if(!t.requestId||this.records.has(t.requestId))return;const n=t.messageType!=="text"&&t.tracksUploadProgress===!0,s={stats:new Nl().setRequestId(t.requestId).setMessageType(t.messageType).setStuckReason(n?"upload_no_progress":"pending_too_long").setCommitCallback(this.commitCallback),measure:{channelUrl:t.channelUrl,timer:null,usesUploadProgress:n}},o=n?gs:Dl;s.measure.timer=setTimeout(()=>this.detect(t.requestId),o),this.records.set(t.requestId,s)}resolve(t){this.cancel(t.requestId)}disappear(t){this.cancel(t.requestId)}cancel(t){const n=this.records.get(t);n&&(n.measure.timer!==null&&clearTimeout(n.measure.timer),this.records.delete(t))}markUploadProgress(t){const n=this.records.get(t);n&&n.measure.usesUploadProgress&&(n.measure.timer!==null&&clearTimeout(n.measure.timer),n.measure.timer=setTimeout(()=>this.detect(t),gs))}clear(){this.records.forEach(t=>{t.measure.timer!==null&&clearTimeout(t.measure.timer)}),this.records.clear()}clearChannel(t){t&&this.records.forEach((n,r)=>{n.measure.channelUrl===t&&(n.measure.timer!==null&&clearTimeout(n.measure.timer),this.records.delete(r))})}detect(t){const n=this.records.get(t);n&&(this.records.delete(t),n.stats.commit())}}class Vn extends Ze{constructor(){super(...arguments);S(this,"triggerType")}setTriggerType(n){return this.triggerType=n,this}getMetricKey(){return fl}buildPayload(){const n=this.getTimer(z.TIMEOUT).duration;return n===null||this.triggerType===void 0?null:this.createPayload(n,{extra:{trigger_type:this.triggerType}})}}class Pl extends It{start(t,n){const r=this.getKey(n);let s=this.records.get(r);s!=null&&s.measure.started||s!=null&&s.measure.inputEnabled||(s||(s=this.createRecord(!1)),s.measure.started=!0,s.stats=new Vn().setTriggerType(t).setCommitCallback(this.commitCallback).startTimer(z.TIMEOUT),s.measure.timer=setTimeout(()=>this.commitTimeout(r),1e4),this.records.set(r,s))}setInputEnabled(t,n){const r=this.getKey(n);let s=this.records.get(r);if(!s){if(!t)return;s=this.createRecord(t),this.records.set(r,s);return}s.measure.inputEnabled=t,t?this.cancelRecord(s):s.measure.started||this.records.delete(r)}cancelPending(t){const n=this.getKey(t),r=this.records.get(n);r&&(this.cancelRecord(r),r.measure.inputEnabled||this.records.delete(n))}clear(){this.records.forEach(t=>{t.measure.timer!==null&&clearTimeout(t.measure.timer)}),this.records.clear()}clearChannel(t){t!==void 0&&this.clearKey(this.getKey(t))}clearKey(t){const n=this.records.get(t);n&&(n.measure.timer!==null&&clearTimeout(n.measure.timer),this.records.delete(t))}commitTimeout(t){const n=this.records.get(t);if(!(!n||!n.measure.started)){if(n.measure.inputEnabled){this.cancelRecord(n);return}n.stats.stopTimer(z.TIMEOUT),this.records.delete(t),n.stats.commit()}}cancelRecord(t){t.measure.timer!==null&&clearTimeout(t.measure.timer),t.measure.timer=null,t.measure.started=!1,t.stats=new Vn().setCommitCallback(this.commitCallback)}createRecord(t){return{stats:new Vn().setCommitCallback(this.commitCallback),measure:{inputEnabled:t,started:!1,timer:null}}}getKey(t){return t??"__default__"}}class Fl extends Ze{constructor(){super(...arguments);S(this,"messageId");S(this,"contentKind");S(this,"errorDomain")}setMessageId(n){return this.messageId=n,this}setContentKind(n){return this.contentKind=n,this}setErrorDomain(n){return this.errorDomain=n,this}getMetricKey(){return vl}buildPayload(){return this.messageId===void 0||this.contentKind===void 0||this.errorDomain===void 0?null:this.createPayload(this.errorDomain,{extra:{content_kind:this.contentKind,message_id:String(this.messageId)}})}}const Ul=500;class Bl extends Rn{constructor(){super(...arguments);S(this,"measure",{committed:new Set})}commit(n){const r=`${n.messageId}:${n.contentKind}:${n.errorDomain}`;if(this.measure.committed.has(r))return;Mn(this.measure.committed,Ul),this.measure.committed.add(r),new Fl().setMessageId(n.messageId).setContentKind(n.contentKind).setErrorDomain(n.errorDomain).setError(n.error?{code:n.error.code,message:n.errorDomain}:void 0).setCommitCallback(this.commitCallback).commit()}clear(){this.measure.committed.clear()}}class Hl extends Ze{constructor(){super(...arguments);S(this,"durationMs");S(this,"messageId");S(this,"stallKind")}setMessageId(n){return this.messageId=n,this}setStall(n){return this.durationMs=n.durationMs,this.stallKind=n.stallKind,this}getMetricKey(){return Cl}buildPayload(){return this.durationMs===void 0||this.messageId===void 0||this.stallKind===void 0?null:this.createPayload(this.durationMs,{extra:{message_id:String(this.messageId),stall_kind:this.stallKind}})}}const ps=1e4,Et=5e3,Gl=500;class zl extends It{constructor(){super(...arguments);S(this,"emittedMessageChannels",new Map)}markRawProgress(n){if(!n.aiResponse.isStreaming){this.completeDelivery(n.messageId,n.textLength);return}if(this.emittedMessageChannels.has(n.messageId))return;const r=this.getOrCreate(n.messageId,n.channelUrl),s=r.measure;this.markRawProgressForRecord(r,n.textLength,performance.now())?(s.deliveryTimer!==null&&clearTimeout(s.deliveryTimer),s.deliveryTimer=null,this.scheduleDeliveryStallCheck(n.messageId,r)):this.scheduleDeliveryStallCheck(n.messageId,r),this.isRenderPending(r)&&s.renderTimer===null&&(s.lastRenderAt=performance.now(),this.scheduleRenderStallCheck(n.messageId,r,Et))}markRenderedProgress(n){const r=this.records.get(n.messageId);if(!r)return;const s=r.measure;if(this.markRenderedProgressForRecord(r,n.displayedLength,performance.now())){if(!this.isRenderPending(r)){if(s.deliveryTimer===null){this.clearRecord(n.messageId,r);return}s.renderTimer!==null&&clearTimeout(s.renderTimer),s.renderTimer=null;return}this.scheduleRenderStallCheck(n.messageId,r,Et)}}hasPendingStream(n){return this.records.has(n)}complete(n){const r=this.records.get(n);r&&this.clearRecord(n,r)}completeDelivery(n,r){const s=this.records.get(n);if(!s)return;const o=s.measure;if(r>o.lastRawLength&&(o.lastRawLength=r,o.lastRawAt=performance.now()),o.deliveryTimer!==null&&clearTimeout(o.deliveryTimer),o.deliveryTimer=null,!this.isRenderPending(s)){this.clearRecord(n,s);return}o.renderTimer===null&&(o.lastRenderAt=performance.now(),this.scheduleRenderStallCheck(n,s,Et))}clearMessage(n){const r=this.records.get(n);r&&this.clearRecord(n,r),this.emittedMessageChannels.delete(n)}clear(){this.records.forEach(n=>{n.measure.deliveryTimer!==null&&clearTimeout(n.measure.deliveryTimer),n.measure.renderTimer!==null&&clearTimeout(n.measure.renderTimer)}),this.records.clear(),this.emittedMessageChannels.clear()}clearChannel(n){n&&(this.records.forEach((r,s)=>{r.measure.channelUrl!==n&&r.measure.channelUrl!==void 0||this.clearRecord(s,r)}),this.emittedMessageChannels.forEach((r,s)=>{(r===n||r===void 0)&&this.emittedMessageChannels.delete(s)}))}detectDelivery(n){const r=this.records.get(n);if(!r)return;const s=r.measure;s.deliveryTimer=null,s.renderTimer!==null&&clearTimeout(s.renderTimer),s.renderTimer=null,this.emit(n,r,"delivery")}detectRender(n){const r=this.records.get(n);if(!r)return;const s=r.measure;if(s.renderTimer=null,!this.isRenderPending(r))return;const o=performance.now()-s.lastRenderAt;if(o<Et){this.scheduleRenderStallCheck(n,r,Et-o);return}const i=performance.now()-s.lastRawAt;if(i>=Et&&s.deliveryTimer!==null){const c=ps-i;if(c>0){this.scheduleRenderStallCheck(n,r,c);return}}this.emit(n,r,"render")}scheduleRenderStallCheck(n,r,s){r.measure.renderTimer===null&&(r.measure.renderTimer=setTimeout(()=>this.detectRender(n),s))}scheduleDeliveryStallCheck(n,r){r.measure.deliveryTimer===null&&(r.measure.deliveryTimer=setTimeout(()=>this.detectDelivery(n),ps))}emit(n,r,s){if(this.emittedMessageChannels.has(n))return;const o=performance.now(),i=s==="delivery"?r.measure.lastRawAt:r.measure.lastRenderAt;r.stats.setStall({stallKind:s,durationMs:o-i}).commit(),this.rememberEmitted(n,r.measure.channelUrl),this.clearRecord(n,r)}getOrCreate(n,r){const s=this.records.get(n);if(s)return s;const o=performance.now(),i={stats:new Hl().setMessageId(n).setCommitCallback(this.commitCallback),measure:{channelUrl:r,deliveryTimer:null,lastRawAt:o,lastRawLength:0,lastRenderAt:o,lastRenderedLength:0,renderTimer:null}};return this.records.set(n,i),i}rememberEmitted(n,r){this.emittedMessageChannels.has(n)||Mn(this.emittedMessageChannels,Gl),this.emittedMessageChannels.set(n,r)}clearRecord(n,r){r.measure.deliveryTimer!==null&&clearTimeout(r.measure.deliveryTimer),r.measure.renderTimer!==null&&clearTimeout(r.measure.renderTimer),this.records.delete(n)}isRenderPending(n){return n.measure.lastRenderedLength<n.measure.lastRawLength}markRawProgressForRecord(n,r,s){return r<=n.measure.lastRawLength?!1:(n.measure.lastRawLength=r,n.measure.lastRawAt=s,!0)}markRenderedProgressForRecord(n,r,s){return r<=n.measure.lastRenderedLength?!1:(n.measure.lastRenderedLength=r,n.measure.lastRenderAt=s,!0)}}class Vl extends Ze{constructor(){super(...arguments);S(this,"beforeTpstAbsentMs");S(this,"afterTpenAbsentMs")}setBeforeTpstAbsentMs(n){return this.beforeTpstAbsentMs=n,this}setAfterTpenAbsentMs(n){return this.afterTpenAbsentMs=n,this}getMetricKey(){return bl}buildPayload(){return this.beforeTpstAbsentMs===void 0&&this.afterTpenAbsentMs===void 0?null:this.createPayload((this.beforeTpstAbsentMs??0)+(this.afterTpenAbsentMs??0),{extra:{[z.BEFORE_TPST_ABSENT]:this.beforeTpstAbsentMs,[z.AFTER_TPEN_ABSENT]:this.afterTpenAbsentMs}})}}const _s=3e3,ql=3e4;class Kl extends It{constructor(){super(...arguments);S(this,"pendingAIResponseStartsByUserMessageId",new Map)}startTurn(n){this.cancelTurn(n.requestId);const r={stats:new Vl().setCommitCallback(this.commitCallback),measure:{afterTpenStartedAt:null,beforeTpstStartedAt:performance.now(),channelUrl:n.channelUrl,requestId:n.requestId,timer:null}};r.measure.timer=setTimeout(()=>this.commitTimeout(r.measure.requestId),ql),this.records.set(n.requestId,r)}markUserMessageAck(n){const r=this.records.get(n.requestId);if(!r)return;r.measure.userMessageId=n.messageId;const s=this.pendingAIResponseStartsByUserMessageId.get(n.messageId);s&&(this.pendingAIResponseStartsByUserMessageId.delete(n.messageId),this.applyAIResponseStarted({channelUrl:s.channelUrl,matchesUserMessage:!0,userMessageId:n.messageId},s.startedAt))}replaceTurnRequestId(n,r){if(n===r)return;const s=this.records.get(n);s&&(this.records.delete(n),s.measure.requestId=r,this.records.set(r,s))}cancelTurn(n){this.cleanupTurn(n)}markTypingStarted(n){const r=performance.now();this.records.forEach(s=>{dt(s.measure.channelUrl,n)&&(this.recordAfterTpen(s,r),this.recordBeforeTpst(s,r))})}markTypingEnded(n){const r=performance.now();this.records.forEach(s=>{dt(s.measure.channelUrl,n)&&(this.recordBeforeTpst(s,r),s.measure.afterTpenStartedAt=r)})}markAIResponseStarted(n={}){const r=n.channelUrl,s=n.userMessageId,o=s!==void 0,i=performance.now();this.applyAIResponseStarted({channelUrl:r,matchesUserMessage:o,userMessageId:s},i)||!o||s===void 0||!lr(this.records.values(),r)||this.pendingAIResponseStartsByUserMessageId.has(s)||(Mn(this.pendingAIResponseStartsByUserMessageId,100),this.pendingAIResponseStartsByUserMessageId.set(s,{channelUrl:r,startedAt:i}))}applyAIResponseStarted(n,r){if(!n.matchesUserMessage){const o=this.findSingleTurn(n.channelUrl);return o?(this.completeTurn(o.requestId,o.record,r),!0):!1}let s=!1;return this.records.forEach(o=>{dt(o.measure.channelUrl,n.channelUrl)&&(n.matchesUserMessage&&o.measure.userMessageId!==n.userMessageId||(s=!0,this.completeTurn(o.measure.requestId,o,r)))}),s}findSingleTurn(n){let r,s=0;return this.records.forEach(o=>{dt(o.measure.channelUrl,n)&&(s+=1,!(s>1)&&(r={requestId:o.measure.requestId,record:o}))}),s===1?r:void 0}completeTurn(n,r,s){this.recordBeforeTpst(r,s),this.recordAfterTpen(r,s),this.commitIfAbsent(n,r)}clear(){this.records.forEach(n=>{n.measure.timer!==null&&clearTimeout(n.measure.timer)}),this.records.clear(),this.pendingAIResponseStartsByUserMessageId.clear()}clearChannel(n){n&&(this.records.forEach(r=>{r.measure.channelUrl===n&&this.cleanupTurn(r.measure.requestId)}),this.pendingAIResponseStartsByUserMessageId.forEach((r,s)=>{r.channelUrl===n&&this.pendingAIResponseStartsByUserMessageId.delete(s)}))}commitTimeout(n){const r=this.records.get(n);if(!r)return;const s=performance.now();this.recordBeforeTpst(r,s),this.recordAfterTpen(r,s),this.commitIfAbsent(n,r)}commitIfAbsent(n,r){r.stats.commit(),this.cleanupTurn(n)}cleanupTurn(n){const r=this.records.get(n);r&&(r.measure.timer!==null&&clearTimeout(r.measure.timer),this.records.delete(n))}recordBeforeTpst(n,r){if(n.measure.beforeTpstStartedAt===null)return;const s=r-n.measure.beforeTpstStartedAt;s>=_s&&n.stats.setBeforeTpstAbsentMs(s),n.measure.beforeTpstStartedAt=null}recordAfterTpen(n,r){if(n.measure.afterTpenStartedAt===null)return;const s=r-n.measure.afterTpenStartedAt;s>=_s&&n.stats.setAfterTpenAbsentMs(s),n.measure.afterTpenStartedAt=null}}class Yl extends Ze{constructor(){super(...arguments);S(this,"ackToFirstChunkMs");S(this,"firstChunkToRenderMs");S(this,"isStreaming");S(this,"sendToAckMs");S(this,"totalDurationMs")}setDurations(n){return this.ackToFirstChunkMs=n.ackToFirstChunkMs,this.firstChunkToRenderMs=n.firstChunkToRenderMs,this.isStreaming=n.isStreaming,this.sendToAckMs=n.sendToAckMs,this.totalDurationMs=n.totalDurationMs,this}getMetricKey(){return El}buildPayload(){return this.ackToFirstChunkMs===void 0||this.firstChunkToRenderMs===void 0||this.isStreaming===void 0||this.sendToAckMs===void 0||this.totalDurationMs===void 0?null:this.createPayload(this.totalDurationMs,{extra:{is_streaming:this.isStreaming,[z.ACK_TO_FIRST_CHUNK]:this.ackToFirstChunkMs,[z.FIRST_CHUNK_TO_RENDER]:this.firstChunkToRenderMs,[z.SEND_TO_ACK]:this.sendToAckMs}})}}const Wl=.15,jl=10,Xl=e=>e<=0?!1:e>=1?!0:Math.random()<e;class Zl extends It{constructor(n,r){super(n);S(this,"samplingRate");S(this,"pendingAIResponseByUserMessageId",new Map);S(this,"collectedCount",0);this.samplingRate=(r==null?void 0:r.samplingRate)??Wl}startTurn(n){if(this.collectedCount>=jl||!Xl(this.samplingRate))return;this.collectedCount+=1;const r={stats:new Yl().setCommitCallback(this.commitCallback),measure:{channelUrl:n.channelUrl,requestId:n.requestId,startedAt:performance.now()}};this.records.set(n.requestId,r)}markUserMessageAck(n){const r=this.records.get(n.requestId);if(!r)return;r.measure.ackAt=performance.now(),r.measure.userMessageId=n.messageId;const s=this.pendingAIResponseByUserMessageId.get(n.messageId);s&&(this.pendingAIResponseByUserMessageId.delete(n.messageId),this.applyAIResponseRaw(r,s))}replaceTurnRequestId(n,r){if(n===r)return;const s=this.records.get(n);s&&(this.records.delete(n),s.measure.requestId=r,this.records.set(r,s))}cancelTurn(n){const r=this.records.get(n);r&&(this.deleteRecord(r),this.collectedCount>0&&(this.collectedCount-=1))}markAIResponseRaw(n){const r=performance.now(),s=n.aiResponse.userMessageId;if(s===void 0&&lr(this.records.values(),n.channelUrl))return;const o=this.findPendingRecord(n.channelUrl,s);if(o){this.applyAIResponseRaw(o,{...n,firstChunkAt:r});return}s===void 0||!lr(this.records.values(),n.channelUrl)||this.bufferAIResponseRaw({messageId:n.messageId,...n.channelUrl!==void 0&&{channelUrl:n.channelUrl},aiResponse:n.aiResponse,firstChunkAt:r},s)}markAIResponseVisible(n){const r=this.findRecordByAIMessageId(n);if(!r)return!1;const s=r.measure;if(s.ackAt===void 0||s.firstChunkAt===void 0||s.userMessageId===void 0)return!1;const o=performance.now();return r.stats.setDurations({ackToFirstChunkMs:s.firstChunkAt-s.ackAt,firstChunkToRenderMs:o-s.firstChunkAt,isStreaming:!!s.isStreaming,sendToAckMs:s.ackAt-s.startedAt,totalDurationMs:o-s.startedAt}).commit(),this.deleteRecord(r),!0}hasPendingAIResponse(n){return this.findRecordByAIMessageId(n)!==void 0}clearMessage(n){this.pendingAIResponseByUserMessageId.forEach((s,o)=>{s.messageId===n&&this.pendingAIResponseByUserMessageId.delete(o)});const r=this.findRecordByAIMessageId(n);r&&(this.deleteRecord(r),this.collectedCount>0&&(this.collectedCount-=1))}clearChannel(n){n&&(this.records.forEach(r=>{r.measure.channelUrl===n&&(this.deleteRecord(r),this.collectedCount>0&&(this.collectedCount-=1))}),this.pendingAIResponseByUserMessageId.forEach((r,s)=>{r.channelUrl===n&&this.pendingAIResponseByUserMessageId.delete(s)}))}clear(){this.records.clear(),this.pendingAIResponseByUserMessageId.clear(),this.collectedCount=0}findRecordByAIMessageId(n){for(const r of this.records.values())if(r.measure.aiMessageId===n)return r}findPendingRecord(n,r){if(r!==void 0){for(const o of this.records.values())if(!(o.measure.ackAt===void 0||o.measure.firstChunkAt!==void 0)&&dt(o.measure.channelUrl,n)&&o.measure.userMessageId===r)return o;return}let s;for(const o of this.records.values())if(!(o.measure.ackAt===void 0||o.measure.firstChunkAt!==void 0)&&dt(o.measure.channelUrl,n)){if(s)return;s=o}return s}applyAIResponseRaw(n,r){n.measure.firstChunkAt===void 0&&(n.measure.firstChunkAt=n.measure.ackAt===void 0?r.firstChunkAt:Math.max(r.firstChunkAt,n.measure.ackAt),n.measure.aiMessageId=r.messageId,n.measure.channelUrl=n.measure.channelUrl??r.channelUrl,n.measure.isStreaming=r.aiResponse.isStreaming)}bufferAIResponseRaw(n,r){this.pendingAIResponseByUserMessageId.has(r)||(Mn(this.pendingAIResponseByUserMessageId,100),this.pendingAIResponseByUserMessageId.set(r,n))}deleteRecord(n){this.records.delete(n.measure.requestId),n.measure.userMessageId!==void 0&&this.pendingAIResponseByUserMessageId.delete(n.measure.userMessageId)}}function Jl(){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 Es={isTalkToAgentViewEnabled:!0,scrollMode:"auto",newMessageIndicatorEnabled:!0,senderAvatarEnabled:!0},kr={conversation:{...Es,messageAlertSoundEnabled:!1,list:{...Es,deferredMarkdownElements:[]},header:{avatarEnabled:!0},input:{camera:{photoEnabled:!0},gallery:{photoEnabled:!0},fileEnabled:!0},fileViewer:{downloadEnabled:!0}},launcher:{unreadBadgeEnabled:!1}},Cs=e=>e?{conversation:tu(e.conversation),launcher:Ql(e.launcher)}:kr,Ql=e=>bt(kr.launcher,e),eu=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},tu=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={...bt(t.list,c,n),deferredMarkdownElements:eu(n)};return{...h,messageAlertSoundEnabled:i,list:h,header:bt(t.header,r),input:{camera:bt(t.input.camera,u),gallery:bt(t.input.gallery,d),fileEnabled:m},fileViewer:bt(t.fileViewer,o)}},bt=(e,...t)=>{const n={...e};for(const r of t)r&&Object.assign(n,wr(r));return n},nu=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}),ru=e=>({type:e.image_type||"default_icon",imageUrl:e.image_url}),ur=e=>({enabled:e.enabled,showIndicator:e.show_indicator,toggleAllowed:e.toggle_allowed,deleteOnOff:e.delete_on_off,consentDialog:e.consent_dialog});class su{constructor(){S(this,"_channelHandlerId",null);S(this,"_connectionHandlerId",null);S(this,"_initConversationRequests",new Map);S(this,"_handleActiveChannelChangedThrottled",null);S(this,"_setupChannelHandler",()=>{const t=Date.now();this._channelHandlerId=`aiagent_channel_${t}`,this._connectionHandlerId=`aiagent_connection_${t}`,this._handleActiveChannelChangedThrottled=Jo(s=>{var o,i;(i=this._session)==null||i._updateActiveChannel({url:s.url,status:Fe(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 Ce.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})});S(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")});S(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:Fe(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)}});S(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});S(this,"onMessengerSettingsUpdated",t=>(this._dispatcher.subscribe(ze.MessengerSettingsUpdated,t),()=>{this._dispatcher.unsubscribe(ze.MessengerSettingsUpdated,t)}));S(this,"onActiveChannelUpdated",t=>(this._dispatcher.subscribe(ze.ActiveChannelUpdated,t),()=>{this._dispatcher.unsubscribe(ze.ActiveChannelUpdated,t)}));S(this,"onAuthTokenRefreshed",t=>(this._dispatcher.subscribe(ze.AuthTokenRefreshed,t),()=>{this._dispatcher.unsubscribe(ze.AuthTokenRefreshed,t)}))}}class ou{constructor(t){S(this,"_sdkUser");S(this,"_userSession");S(this,"_dispatcher");S(this,"_activeChannel");S(this,"_updateActiveChannel",t=>{this._activeChannel=t,this._dispatcher.send(it.ActiveChannelUpdated({channelUrl:t.url,status:t.status,conversationStatus:t.conversationStatus}))});S(this,"_updateAuthToken",t=>{this._userSession.authToken=t,this._dispatcher.send(it.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 ci=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)}},li=e=>JSON.parse(e),iu=e=>JSON.parse(e);function au(e,t){const[n,r]=t.split(",").map(s=>s.trim());return e==="dark"&&r||n}function cu(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 lu({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,ci(c))},e)}async function uu({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,ci(c)),e)}var Lr=(e=>(e[e.EXTERNAL_AUTH_TOKEN_EXPIRED=1]="EXTERNAL_AUTH_TOKEN_EXPIRED",e))(Lr||{});const ui=e=>typeof e=="object"&&e!==null,bs=(e,t)=>t in e&&typeof e[t]=="string"&&e[t]!=="",du=e=>!ui(e)||!bs(e,"channel_url")||!bs(e,"ai_agent_id")?null:{channelUrl:e.channel_url,aiAgentId:e.ai_agent_id},mu={1:du};function hu(e){if(!ui(e)||!("cat"in e)||typeof e.cat!="number"||!("data"in e))return null;const t=e.cat,n=mu[t];if(!n)return null;const r=n(e.data);return r?{category:t,data:r}:null}function fu(e,t,n,r){const s=lc.default.init({appId:e,modules:[new We.GroupChannelModule,new fe.AIAgentModule],localCacheEnabled:!0,options:new Ce.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:Ce.SendbirdProduct.AI_AGENT,platform:t.platform}],{platform:t.deviceOSPlatform,version:t.deviceOSVersion},t.customData)||console.warn("Invalid Sendbird Extensions",t),s}function gu(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 pu=[400300,400301,400302,400310],_u=Lr.EXTERNAL_AUTH_TOKEN_EXPIRED.toString(),Eu=e=>`${_u}:${e}`;class Or{constructor(t,n,r,s,o){S(this,"chatSDK");S(this,"_aiAgentId");S(this,"_externalAuthTokenExpiredEventHandlerKey");S(this,"_logger");S(this,"_cache");S(this,"_statsTrackers");S(this,"_sessionHandler");S(this,"_aiEventHandlerRegistered",!1);S(this,"connect",async(t,n,r,s)=>{if(this._logger.debug("ChatClient.connect: start",t.userId),n){this._sessionHandler=n;const o=new Ce.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}});S(this,"_registerAIEventHandler",()=>{this._aiEventHandlerRegistered||(this._aiEventHandlerRegistered=!0,this.chatSDK.aiAgent.addEventHandler(this._externalAuthTokenExpiredEventHandlerKey,this._handleAIEvent))});S(this,"_handleAIEvent",t=>{var o;this._logger.debug("ChatClient.connect: EXTERNAL_AUTH_TOKEN_EXPIRED event received",t);const n=hu(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)});S(this,"dispose",()=>{this._aiEventHandlerRegistered&&(this.chatSDK.aiAgent.removeEventHandler(this._externalAuthTokenExpiredEventHandlerKey),this._aiEventHandlerRegistered=!1),this._sessionHandler=void 0});S(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")});S(this,"getChannel",async t=>this.chatSDK.groupChannel.getChannel(t));S(this,"patchContext",async(t,n,r)=>this.chatSDK.aiAgent.patchContext(t,n,r));S(this,"updateContext",async(t,n,r)=>this.chatSDK.aiAgent.updateContext(t,n,r));S(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});S(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});S(this,"clearUserMemories",async(t={})=>{this._logger.debug("ChatClient.clearUserMemories: requesting",t),await this.chatSDK.aiAgent.clearUserMemories(t),this._logger.debug("ChatClient.clearUserMemories: completed")});S(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)})}});S(this,"_isCacheRestrictedError",t=>pu.some(n=>t.code===n));S(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}=li(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=Eu(n),this._logger=r,this._cache=s,this._statsTrackers=o}static init(t){let n;return t.chatSDK?(gu(t.chatSDK),n=t.chatSDK):n=fu(t.appId,t.extensions,t.messengerVersion,t.chatParams),new Or(n,t.aiAgentId,t.logger,t.cache,t.statsTrackers)}}const Cu=e=>t=>{if(!e||e.getState()==="foregrounded"){t();return}const n=e.subscribe(r=>{r==="foregrounded"&&(n(),t())});return n},bu=e=>()=>{let t=e.getState()==="backgrounded";const n=e.subscribe(r=>{r==="backgrounded"&&(t=!0)});return()=>(n(),t)},en=new Map,di={set:(e,t)=>{en.set(e,t)},get:e=>{if(en.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=en.get(e);if(!n)throw new Error(`AIAgent platform "${e}" is not configured.`);return{platform:e,...n}}const t=en.entries().next().value;return{platform:t[0],...t[1]}}};class vs extends Error{constructor(n,r){const s=(r==null?void 0:r.detail)??"";super(s||`Desk API error (${n})`);S(this,"status");S(this,"code");S(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||{}),mi=(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))(mi||{});const vu=e=>e==="desk401103"||e==="desk401106"||e==="desk401107"||e==="desk401108"||e==="desk401109";class Su{constructor(t){S(this,"_appId");S(this,"_apiHost");S(this,"_logger");S(this,"_credential",null);S(this,"_authRefreshPromise",null);S(this,"_onDeskTokenRefreshRequired",async()=>!1);S(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)});S(this,"setCredential",(t,n=async()=>!1)=>{this._authRefreshPromise=null,this._onDeskTokenRefreshRequired=n,this._credential=t});S(this,"clearCredential",()=>{this._authRefreshPromise=null,this._credential=null,this._onDeskTokenRefreshRequired=async()=>!1});S(this,"_handleUnauthorized",async(t,n,r)=>{const s=await this._parseErrorCode(t);if(!vu(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)});S(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}});S(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))}:{}}));S(this,"_buildParams",t=>new URLSearchParams({sendbirdAppId:this._appId,...t}));S(this,"_buildBody",t=>({sendbirdAppId:this._appId,...t}));S(this,"_buildHeaders",(t,n)=>({"content-type":"application/json",...t&&this._credential?{sendbirdDeskToken:this._credential.deskToken}:{},...n}));S(this,"_toResult",async t=>{if(!t.ok){const r=await t.json().catch(()=>({}));throw new vs(t.status,r)}const n=await t.text();if(n)try{return JSON.parse(n)}catch{throw new vs(t.status,{})}});S(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 _n{constructor(t,n){S(this,"id");S(this,"title");S(this,"status");S(this,"agent");S(this,"priority");S(this,"group");S(this,"firstResponseTime");S(this,"issuedAt");S(this,"customFields");S(this,"_client");S(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 _n({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){S(this,"_logger");S(this,"_apiClient");S(this,"_onDeskTokenRefreshRequired");S(this,"refreshDeskAuthToken",async t=>this._apiClient.credential?this.authenticate({userId:this._apiClient.credential.userId,accessToken:t,onDeskTokenRefreshRequired:this._onDeskTokenRefreshRequired}):!1);S(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}});S(this,"deauthenticate",()=>{this._apiClient.clearCredential(),this._onDeskTokenRefreshRequired=void 0,this._logger.debug("DeskClient.deauthenticate: token cleared")});S(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")});S(this,"getTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request(`/tickets/${encodeURIComponent(t)}/`,{method:"GET"});return _n._fromResponse(n,this)});S(this,"createTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request("/tickets/",{method:"POST",body:wr({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 _n._fromResponse(n,this)});this._logger=t.logger,this._apiClient=new Su(t)}static init(t){return new $r(t)}_assertAuthenticated(t){if(t.credential==null)throw new Error("DeskClient is not authenticated")}}class Pr{constructor(){S(this,"authenticate",async t=>!1);S(this,"deauthenticate",()=>{});S(this,"refreshDeskAuthToken",async()=>!1);S(this,"setCustomerLanguage",async()=>{});S(this,"getTicket",async()=>{throw new Error("DeskClient is disabled via __SBA_USE_DESK_CLIENT__")})}static init(){return new Pr}}function yu(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 Au=1440*60*1e3,Tu=typeof __SBA_USE_DESK_CLIENT__>"u"||__SBA_USE_DESK_CLIENT__;function Qe(e){if(!e)throw new Error("Not authenticated. Call authenticate() first.")}function Iu(e,t){return Object.entries(t).every(([n,r])=>e[n]===r)}const xu=e=>{const t={conversationInitialRender:new Rl(e),conversationNotInteractiveTimeout:new Ol(e),recoveryNotInteractiveTimeout:new Pl(e),conversationListInitialRender:new kl(e),aievAuthExpiredUnhandled:new Tl(e),messagePendingStuck:new $l(e),userPerceivedResponseTime:new Zl(e),streamStalled:new zl(e),typingIndicatorAbsentTimeout:new Kl(e),renderedContentUnusable:new Bl(e)};return{...t,clear:()=>{Object.values(t).forEach(n=>n.clear())}}};class En extends su{constructor(n){super();S(this,"appId");S(this,"aiAgentId");S(this,"_chatClient");S(this,"_deskClient");S(this,"_cache");S(this,"_logger");S(this,"_dispatcher");S(this,"_session",null);S(this,"language");S(this,"countryCode");S(this,"context");S(this,"queryParams");S(this,"_config");S(this,"_networkStateAdapter");S(this,"_scheduleForegroundTask");S(this,"_watchBackgrounded");S(this,"_forceCreateChannel");S(this,"_agentVersion");S(this,"_statsTrackers");S(this,"_liveMetricManager");S(this,"_operationQueue",Jl());S(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"))});S(this,"initConversationIfNeeded",n=>this._initConversationIfNeeded(n));S(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(it.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:p,expire_at:b}=h.auto_created_user;this._cache.messenger.setAnonUser({userId:v,authToken:p,expireAt:b}),f={userId:v,authToken:p},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(it.MessengerSettingsUpdated({settings:h,source:"server"}));const g=(()=>{var v;return s.type==="anonymous"?ul(this._dispatcher):(v=s.userSessionCandidate)==null?void 0:v.sessionHandler})(),C=await this._chatClient.connect(f,g,v=>{var p;this._logger.debug("AIAgent: session token refreshed"),(p=this._session)==null||p._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 p;if(v===mi.ERR_SESSION_KEY_EXPIRED){await new Promise(y=>setTimeout(y,2e3));const b=(p=this._session)==null?void 0:p.userSession.authToken;return b?await this._deskClient.refreshDeskAuthToken(b):!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 ou({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),this._statsTrackers.conversationListInitialRender.onAuthError(h),h}})});S(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")}));S(this,"createConversation",async n=>{Qe(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});S(this,"searchConversation",async n=>{if(Qe(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:fe.ConversationStatus.OPEN,limit:100}),s=[];for(;r.hasNext;){const o=await r.next();for(const i of o)Iu(i.context??{},n.context)&&s.push(i.channelInfo.url)}return this._logger.debug("AIAgent.searchConversation: end",{count:s.length}),s});S(this,"closeConversation",async n=>{var s;Qe(this._session),this._logger.debug("AIAgent.closeConversation: start",n);const r=await this._chatClient.getChannel(n);((s=r.conversation)==null?void 0:s.status)===fe.ConversationStatus.OPEN?(await r.closeConversation(),this._session.activeChannel.url===n&&this._session._updateActiveChannel({url:n,status:"closed",conversationStatus:fe.ConversationStatus.CLOSED}),this._logger.debug("AIAgent.closeConversation: end")):this._logger.debug("AIAgent.closeConversation: already closed or not an AI agent conversation")});S(this,"createConversationListCollection",n=>new Qo(this.chatSDK,n??{}));S(this,"patchContext",async(n,r)=>{Qe(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??{}}});S(this,"updateContext",async(n,r)=>{Qe(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??{}}});S(this,"getContextObject",async n=>{Qe(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??{}}});S(this,"clearUserMemories",async(n={})=>{Qe(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")});S(this,"setUserMemoryState",async n=>{Qe(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"),ur(i);const c=this._cache.messenger.getSettings(o);if(c){const u={...c,memory:i};this._cache.messenger.setSettings(o,u),this._dispatcher.send(it.MessengerSettingsUpdated({settings:u,source:"cache"}))}return this._logger.debug("AIAgent.setUserMemoryState: end",i.enabled),ur(i)});S(this,"refreshActiveChannel",async n=>{var c,u,d;Qe(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});S(this,"_getSessionCandidate",n=>n instanceof si?{type:"manual",userSessionCandidate:this._getManualSessionInfo(n)}:n instanceof ar?{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});S(this,"_getAnonymousSessionInfo",()=>{const n=this._cache.messenger.getAnonUser();return n?n.expireAt-Au<=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});S(this,"_getManualSessionInfo",n=>{if(!n||n instanceof ar)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=Cs(n.config),this.queryParams=n.queryParams,this._networkStateAdapter=n.networkStateAdapter,this._scheduleForegroundTask=Cu(n.foregroundStateAdapter),this._watchBackgrounded=n.foregroundStateAdapter&&bu(n.foregroundStateAdapter),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 ll(this._chatClient.chatSDK),this._liveMetricManager.start()}static init(n){var g;const r=di.get(n.platform),s=n.logger??new ri(n.logLevel??Mr.WARN),o=n.dispatcher??new ei(s),i=n.useMMKVStorage?yu(n.useMMKVStorage):r.keyValueStorage,c=n.useMMKVStorage?{...n.chatParams,useMMKVStorageStore:n.useMMKVStorage}:n.chatParams,u=wc({appId:n.appId,aiAgentId:n.aiAgentId,storage:i});let d;const h=xu((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=Tu?$r.init({appId:n.appId,logger:s,customApiHost:(g=n.deskParams)==null?void 0:g.customApiHost}):Pr.init();return s.debug("AIAgent.init: created",{appId:n.appId,aiAgentId:n.aiAgentId}),new En({appId:n.appId,aiAgentId:n.aiAgentId,language:n.language,countryCode:n.countryCode,context:n.context,config:n.config,queryParams:n.queryParams,networkStateAdapter:r.networkStateAdapter,foregroundStateAdapter:r.foregroundStateAdapter,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=Cs(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}get watchBackgrounded(){return this._watchBackgrounded}}const ve=(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 qe(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 Ru(...e){return function({children:n}){return e.reduce((r,s)=>a.createElement(s,null,r),n)}}function Mu(e,t){const n=e.lastMessage;return n!=null&&n.isAdminMessage()?n.message??"":wu(e,t)}function wu(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 ku(e,t,n){var i;const r=new Date,s=new Date(((i=e.lastMessage)==null?void 0:i.createdAt)||e.createdAt),o=ot.differenceInMinutes(r,s);return o<1?n.justNow:o<60?n.minutesAgo(o):ot.isToday(s)?n.hoursAgo(ot.differenceInHours(r,s)):t(s,n.dateShortFormat)}const Lu=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},tn=e=>Math.max(0,Math.min(255,e)).toString(16).padStart(2,"0"),Ss=(e,t)=>{const n=tn(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=Lu(e);return r?`#${tn(r[0])}${tn(r[1])}${tn(r[2])}${n}`:e},Ou=(e,t)=>{if(!t)return e;const n={...e};for(const[r,s]of Object.entries(t))s&&(n[r]=s);return n},Nu=e=>e.consentDialog?"consent":e.toggleAllowed?e.enabled?"on":"off":"readonly",Du=e=>e.length>0,$u=e=>{const t=e[0];if(!t)return e;const n=e.some(s=>Ve(s.type)),r=e.some(s=>!Ve(s.type));return n&&r?Ve(t.type)?e.filter(s=>Ve(s.type)):[t]:r?[t]:e},ys=e=>e.length===0?"empty":e.every(t=>Ve(t.type))?"images":"non_images",Pu=({currentFiles:e,incomingFiles:t,maxAttachmentCount:n})=>{const r=$u(t),s=ys(e),o=ys(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}},yt=3,hi=6,Fu=e=>e%yt===0?yt:hi,Uu=({index:e,itemCount:t})=>{const n=t%yt,r=n>0,s=r?t-n:t,o=r&&e>=s,i=o?n:yt,c=o?e-s:e%yt,u=!r&&e>=t-yt;return{columnSpan:r?hi/i:1,rowItemCount:i,isLastInRow:c===i-1,isLastRow:o||u}},fi=ve("AIAgent"),Bu=fi.Provider,xe=fi.useContext;function Hu(e){const t=Gu(e);return a.createElement(Bu,{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 Gu(e){var s;const t=l.useRef(null),n=l.useRef(null);if(!t.current||!n.current)t.current=En.init(e);else{const o=zu(n.current,e);(o.appId||o.aiAgentId||o.chatSDK)&&(t.current.dispose(),t.current=En.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 zu(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 le(e){const t=l.useRef(e);return t.current=e,l.useCallback((...n)=>t.current(...n),[t])}const wn=()=>{const[,e]=l.useState(0);return l.useCallback(()=>e(t=>t+1),[])};let Vu=0;function qu(){return l.useState(()=>`${Vu++}`)[0]}const mt=(e,t,n)=>{const r=l.useRef(t),o=qu();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 Ku(e,t){return!e||!t?!0:e.url!==t.url}function Be(e){return e!=null&&"sendingStatus"in e}function Yu(e,t="##__USER_ID_IS_NOT_PROVIDED__##"){var n;return Be(e)?((n=e.sender)==null?void 0:n.userId)===t:!1}function Wu(e,t){return Yu(e,t)||e.isAdminMessage()?!1:e.updatedAt===0}function As(e){return"sendingStatus"in e?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId)}const Cn={collection:{groupChannel:{defaultOrder:We.GroupChannelListOrder.LATEST_LAST_MESSAGE},message:{defaultLimit:{next:25,prev:25},searchLimit:{next:10,prev:10}}}};function Ts(e){return!e||!Array.isArray(e)?!1:e.length!==0}function Is(e,t){return e.reduce((n,r)=>{const s=t(r);return n[s]=r,n},{})}const ju=({...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=Xu(t.value.messages);else{const n={...e.messageMap},r=[],s=[];t.value.messages.forEach(o=>{const i=Be(o)?o.reqId:void 0,c=o.messageId||void 0;[i,c].forEach(u=>{if(!u)return;const d=n[u];Zu(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=>{Be(o)&&delete n[o.reqId],delete n[o.messageId]}),s.forEach(o=>{Be(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=>Wu(s,n));return t.value.clearBeforeAction?e.newMessageMap=Is(r,As):(r.map(o=>o.messageId).forEach(o=>delete e.newMessageMap[o]),e.newMessageMap={...e.newMessageMap,...Is(r,As)}),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&&(Be(s)&&delete e[n][s.reqId],delete e[n][s.messageId])}),t.value.reqIds.forEach(r=>{const s=e[n][r];s&&(Be(s)&&delete e[n][s.reqId],delete e[n][s.messageId])}),e}}},Xu=e=>e.reduce((t,n)=>(Be(n)?(t[n.reqId]=n,n.sendingStatus===De.SendingStatus.SUCCEEDED&&(t[n.messageId]=n)):t[n.messageId]=n,t),{}),Zu=(e,t,n=!1)=>{var r,s;if(!Be(e)||!Be(t))return!0;if(n&&e&&ke.isStreaming(e)&&ke.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===De.SendingStatus.SUCCEEDED?t.sendingStatus===De.SendingStatus.SUCCEEDED:e.sendingStatus!==t.sendingStatus},Ju=(e=Qu)=>{const[{initialized:t,loading:n,refreshing:r,messageMap:s,newMessageMap:o},i]=l.useReducer(ju,{initialized:!1,loading:!0,refreshing:!1,messageMap:{},newMessageMap:{}}),c=(p,b,y,A)=>{i({type:"update_messages",value:{messages:p,clearBeforeAction:b,currentUserId:y,strictStreamingOrder:A}})},u=(p,b)=>{i({type:"delete_messages",value:{messageIds:p,reqIds:b}})},d=(p,b,y)=>{i({type:"update_new_messages",value:{messages:p,clearBeforeAction:b,currentUserId:y}})},m=(p,b)=>{i({type:"delete_new_messages",value:{messageIds:p,reqIds:b}})},h=p=>{i({type:"update_initialized",value:{status:p}})},f=p=>{i({type:"update_loading",value:{status:p}})},g=p=>{i({type:"update_refreshing",value:{status:p}})},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}},xs=Math.floor(Number.MAX_SAFE_INTEGER/10);function Qu(e,t){let n=0,r=0;return Be(e)&&e.sendingStatus!=="succeeded"&&(n=xs),Be(t)&&t.sendingStatus!=="succeeded"&&(r=xs),e.createdAt+n-(t.createdAt+r)}const ed=(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 Rs(e){return e<Date.now()?Cn.collection.message.searchLimit:Cn.collection.message.defaultLimit}const td=(e,t,n={})=>{var Me,$;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=Rs(i),u=r.current.strictStreamingOrder??!1,d=l.useRef({prev:!1,next:!1}),m=wn(),h=l.useRef({initialized:!1,apiInitialized:!1,instance:null}),{initialized:f,loading:g,refreshing:C,messages:v,newMessages:p,updateMessages:b,updateNewMessages:y,deleteNewMessages:A,deleteMessages:T,updateInitialized:R,updateLoading:N,updateRefreshing:k}=Ju(n==null?void 0:n.sortComparator),x=le(I=>{var w,O,G,J;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 Ce.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case Ce.CollectionEventSource.EVENT_MESSAGE_SENT_SUCCESS:case Ce.CollectionEventSource.SYNC_MESSAGE_FILL:case void 0:(G=(O=r.current).markAsRead)==null||G.call(O,[s.current]);break}}catch(se){(J=o==null?void 0:o.warn)==null||J.call(o,"[useGroupChannelMessages/markAsReadBySource]",se)}}),D=le((I,w)=>{var O,G,J,se,Q;if(w.length>0)switch(I){case Ce.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case Ce.CollectionEventSource.SYNC_MESSAGE_FILL:{(G=(O=r.current).shouldCountNewMessages)!=null&&G.call(O)&&y(w,!1,(J=e.currentUser)==null?void 0:J.userId),(Q=(se=r.current).onMessagesReceived)==null||Q.call(se,w);break}}}),F=le(I=>{var w,O;(O=(w=r.current).onCollectionEvent)==null||O.call(w,I)}),U=le(async(I,w,O)=>new Promise((G,J)=>{var Ke,ut,st;h.current.instance&&h.current.instance.dispose(),x(),y([],!0,(Ke=e.currentUser)==null?void 0:Ke.userId);const se=()=>{var ne,ce;const{pendingMessages:de,failedMessages:be}=h.current.instance??{};Ts(de)&&b(de,!1,(ne=e.currentUser)==null?void 0:ne.userId),Ts(be)&&b(be,!1,(ce=e.currentUser)==null?void 0:ce.userId)},Q=ed(I,O,{...r.current,startingPoint:w});h.current={apiInitialized:!1,initialized:!1,instance:Q},Q.setMessageCollectionHandler({onMessagesAdded:(de,be,ne)=>{var ce;x(de.source),D(de.source,ne),b(ne,!1,(ce=e.currentUser)==null?void 0:ce.userId,u),F({kind:"messagesAdded",source:de.source,channelUrl:I.url,messages:ne})},onMessagesUpdated:(de,be,ne)=>{var ce,_e,Ee;x(de.source),D(de.source,ne),b(ne,!1,(ce=e.currentUser)==null?void 0:ce.userId,u),de.source===Ce.CollectionEventSource.EVENT_MESSAGE_UPDATED&&((Ee=(_e=r.current).onMessagesUpdated)==null||Ee.call(_e,ne)),F({kind:"messagesUpdated",source:de.source,channelUrl:I.url,messages:ne})},onMessagesDeleted:(de,be,ne,ce)=>{const _e=ce.map(Ae=>Ae.messageId),Ee=ce.filter(Be).map(Ae=>Ae.reqId);T(_e,Ee),A(_e,Ee),F({kind:"messagesDeleted",source:de.source,channelUrl:I.url,messages:ce})},onChannelDeleted:(de,be)=>{var ne,ce;(ce=(ne=r.current).onChannelDeleted)==null||ce.call(ne,be)},onChannelUpdated:(de,be)=>{var ne,ce;m(),(ce=(ne=r.current).onChannelUpdated)==null||ce.call(ne,be,de)},onHugeGapDetected:()=>{U(I,Number.MAX_SAFE_INTEGER,Cn.collection.message.defaultLimit)}});let pe=!1;(st=(ut=r.current).onCollectionInitializeStart)==null||st.call(ut),Q.initialize(We.MessageCollectionInitPolicy.CACHE_AND_REPLACE_BY_API).onCacheResult((de,be)=>{var ne,ce,_e,Ee,Ae;(ce=(ne=r.current).onCacheResult)==null||ce.call(ne,de,be??[],I.url),de?(e.isCacheEnabled&&((_e=o==null?void 0:o.error)==null||_e.call(o,"[useGroupChannelMessages/onCacheResult]",de)),pe=!0):be&&((Ee=o==null?void 0:o.debug)==null||Ee.call(o,"[useGroupChannelMessages/onCacheResult]","message length:",be.length),b(Q.succeededMessages,!0,(Ae=e.currentUser)==null?void 0:Ae.userId),se(),be.length>0&&(h.current.initialized=!0,G())),F({kind:"initialized",source:"cache",channelUrl:I.url,messages:be??[],error:de})}).onApiResult((de,be)=>{var ne,ce,_e,Ee,Ae,ue,we;(ce=(ne=r.current).onApiResult)==null||ce.call(ne,de,be??[],I.url),h.current.initialized=!0,h.current.apiInitialized=!0,de?((_e=o==null?void 0:o.warn)==null||_e.call(o,"[useGroupChannelMessages/onApiResult]",de),pe?J(de):G()):be&&((Ee=o==null?void 0:o.debug)==null||Ee.call(o,"[useGroupChannelMessages/onApiResult]","message length:",be.length),b(Q.succeededMessages,!0,(Ae=e.currentUser)==null?void 0:Ae.userId),r.current.startingPoint||(we=(ue=r.current).onMessagesReceived)==null||we.call(ue,be),e.isCacheEnabled&&se(),G()),F({kind:"initialized",source:"api",channelUrl:I.url,messages:be??[],error:de})})}));mt(e,{onUserBanned(I,w){var O,G,J;I.isGroupChannel()&&!Ku(I,s.current)&&(w.userId===((O=e.currentUser)==null?void 0:O.userId)?(J=(G=r.current).onCurrentUserBanned)==null||J.call(G):m())}}),l.useLayoutEffect(()=>{const I=setTimeout(async()=>{e.currentUser&&s.current&&(R(!1),N(!0),await U(s.current,i,c),N(!1),R(!0))});return()=>clearTimeout(I)},[e,(Me=e.currentUser)==null?void 0:Me.userId,($=s.current)==null?void 0:$.url,r.current.replyType]),l.useEffect(()=>()=>{h.current.instance&&h.current.instance.dispose()},[]);const q=le(async()=>{e.currentUser&&s.current&&(k(!0),await U(s.current,Number.MAX_SAFE_INTEGER,Cn.collection.message.defaultLimit),k(!1))}),K=le(async()=>{var w;const I=h.current.instance;if(I!=null&&I.hasPrevious&&!d.current.prev)try{d.current.prev=!0;const O=await I.loadPrevious();b(O,!1,(w=e.currentUser)==null?void 0:w.userId)}catch{}finally{d.current.prev=!1}}),L=le(()=>{const{initialized:I,instance:w}=h.current;return I&&w?w.hasPrevious:!1}),V=le(async()=>{var w;const I=h.current.instance;if(I!=null&&I.hasNext&&!d.current.next)try{d.current.next=!0;const O=await I.loadNext();b(O,!1,(w=e.currentUser)==null?void 0:w.userId)}catch{}finally{d.current.next=!1}}),P=le(()=>{const{initialized:I,apiInitialized:w,instance:O}=h.current;return w&&I&&O?O.hasNext:!1}),Y=I=>{var w,O,G,J;!I||I.channelUrl!==((w=s.current)==null?void 0:w.url)||(b([I],!1,(O=e.currentUser)==null?void 0:O.userId),(J=(G=r.current).onOutgoingMessageStatusChanged)==null||J.call(G,I))},ge=le((I,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((G,J)=>{s.current.sendUserMessage(I).onPending(se=>{Y(se),w==null||w(se)}).onSucceeded(se=>{Y(se),G(se)}).onFailed((se,Q)=>{Y(Q),J(se)})})}),j=le((I,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((G,J)=>{s.current.sendFileMessage(I).onPending(se=>{Y(se),w==null||w(se)}).onSucceeded(se=>{Y(se),G(se)}).onFailed((se,Q)=>{Y(Q),J(se)})})}),W=le((I,w,O)=>{var G;if(!s.current||!s.current.url)throw(G=o==null?void 0:o.error)==null||G.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((J,se)=>{s.current.sendMultipleFilesMessage(I).onPending(Q=>{Y(Q),w==null||w(Q)}).onFileUploaded(Q=>{O==null||O(Q),m()}).onSucceeded(Q=>{Y(Q),J(Q)}).onFailed((Q,pe)=>{Y(pe),se(Q)})})}),X=le(async(I,w)=>{var G,J;if(!s.current||!s.current.url)throw(G=o==null?void 0:o.error)==null||G.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");const O=await s.current.updateUserMessage(I,w);return O.channelUrl===s.current.url&&b([O],!1,(J=e.currentUser)==null?void 0:J.userId),O}),M=le(async(I,w)=>{var G,J;if(!s.current||!s.current.url)throw(G=o==null?void 0:o.error)==null||G.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");const O=await s.current.updateFileMessage(I,w);return O.channelUrl===s.current.url&&b([O],!1,(J=e.currentUser)==null?void 0:J.userId),O}),Z=le(async(I,w,O)=>{var G;if(!s.current||!s.current.url)throw(G=o==null?void 0:o.error)==null||G.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((J,se)=>{let Q;I.isUserMessage()&&(Q=s.current.resendMessage(I)),I.isFileMessage()&&(Q=s.current.resendMessage(I)),I.isMultipleFilesMessage()&&(Q=s.current.resendMessage(I)),Q&&("onPending"in Q&&Q.onPending(pe=>{Y(pe),w==null||w(pe)}),"onFileUploaded"in Q&&Q.onFileUploaded(pe=>{O==null||O(pe),m()}),"onSucceeded"in Q&&Q.onSucceeded(pe=>{Y(pe),J(pe)}),"onFailed"in Q&&Q.onFailed((pe,Ke)=>{Y(Ke),se(pe)}))})}),ie=le(async I=>{var w,O,G,J;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((O=h.current.instance)==null?void 0:O.removeFailedMessage(I.reqId))}finally{T([],[I.reqId]),(J=(G=r.current).onLocalMessageDeleted)==null||J.call(G,I)}}),ye=le(()=>{var I;y([],!0,(I=e.currentUser)==null?void 0:I.userId)}),$e=le(async I=>{var w;if(e.currentUser&&s.current){const O=Rs(I);N(!0),b([],!0,(w=e.currentUser)==null?void 0:w.userId),await U(s.current,I,O),N(!1)}});return{initialized:f,loading:g,refreshing:C,messages:v,newMessages:p,resetNewMessages:ye,refresh:q,loadPrevious:K,hasPrevious:L,loadNext:V,hasNext:P,sendUserMessage:ge,sendFileMessage:j,sendMultipleFilesMessage:W,updateUserMessage:X,updateFileMessage:M,resendMessage:Z,deleteMessage:ie,resetWithStartingPoint:$e,_dangerous_reducer_updateMessages:b,_dangerous_reducer_deleteMessages:T}},nd=e=>e.customType==="SENDBIRD_DESK_ADMIN_MESSAGE_CUSTOM_TYPE"?!0:e.isAdminMessage()?e.message==="The channel's custom_type was updated.":!1,rd=(e,t,n)=>{const r=td(e,t,{...n,strictStreamingOrder:!0}),s=l.useMemo(()=>r.messages.filter(o=>!nd(o)),[r.messages]);return{...r,messages:s}},sd=()=>{const e=new Set;return{publish:t=>{e.size!==0&&[...e].forEach(n=>{n(t)})},subscribe:t=>{let n=!0;return e.add(t),()=>{n&&(n=!1,e.delete(t))}}}},gi=sd(),od=({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}},id=({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 pi(e){return e.length===4?`#${[...e.slice(1)].map(t=>t+t).join("")}`:e}function ad(e){const t=pi(e);return[parseInt(t.slice(1,3),16),parseInt(t.slice(3,5),16),parseInt(t.slice(5,7),16)]}function cd(e){return`#${e.map(t=>t.toString(16).padStart(2,"0")).join("")}`}function ld(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 ud(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 nn(e,t,n){const[r,s,o]=ad(e),[i,c,u]=ld(r,s,o),d=Math.max(0,Math.min(1,u*t)),m=Math.max(0,Math.min(1,c*n)),[h,f,g]=ud(i,m,d);return cd([Math.round(h),Math.round(f),Math.round(g)])}function dd(e,t="light"){return{extraDark:nn(e,.6,1.2),dark:nn(e,.85,1.1),main:e,light:nn(e,t==="dark"?1.1:1.5,t==="dark"?.95:.9),extraLight:nn(e,t==="dark"?1.2:1.75,t==="dark"?.9:.8)}}function dr(e){const t=pi(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 md(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 hd=(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"}}),rn={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)"}},qn={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 Ms(e){const t=fd(e),n=gd(e,t),r=_d(n,e.colors,e.selectedTheme),s=Cd(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 fd({selectedTheme:e,palette:t,primary:n}){const r=t!=null&&t.primary?t.primary:n?n===rn.primary.main?rn.primary:dd(n,e):rn.primary;return{...rn,primary:r,...t}}function gd({selectedTheme:e,primaryContrast:t,botMessageBackground:n,botMessageBackgroundContrast:r},s){const o=s.primary.main,i=t??dr(o),c=n??Bt.DEFAULT_BOT_MSG_BG,u=r??dr(c);return(e==="light"?md:hd)(s,o,i,c,u)}function pd(e,t,n){return typeof e=="string"?e:e[t]??n}function _d(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]=pd(m,n,h)}}}return r}function Ed(e,t,n){const r={...e};return n.forEach(s=>{const o=t[s];o!=null&&(r[s]=o)}),r}function Cd({typography:e}){if(!e)return qn;const t={...qn};return Object.keys(e).forEach(n=>{const r=e[n];if(r&&typeof r=="object"){const s=qn[n],o=["fontSize","fontWeight","fontFamily","lineHeight"];t[n]=Ed(s,r,o)}}),t}const{Provider:bd,useContext:Fr}=ve("AIAgentTheme");function vd({logger:e,palette:t,typography:n,colors:r,appearance:s,children:o}){const i=l.useRef(null),[c,u]=l.useState(()=>Ms({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=Ms({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(bd,{value:{theme:c,updateTheme:d}},o)}const Kn=25*1024*1024,ws=1,ks=new Set(["image/png","image/jpeg","image/jpg"]),Ls=new Set(["application/pdf"]),Sd={off:"off",always:"always",handed_off_only:"handed_off_only"},yd=()=>{const[e,t]=l.useState(()=>({maxAttachmentCount:ws,attachmentMode:"handed_off_only",defaultUploadSizeLimit:Kn,uploadSizeLimitPerType:new Map,supportedImageMimeTypes:ks,supportedFileMimeTypes:Ls})),n=l.useCallback(({active_channel:s,upload_restriction:o})=>{t({maxAttachmentCount:(o==null?void 0:o.max_attachment_count)??ws,attachmentMode:Sd[s.attachment_mode]??"handed_off_only",defaultUploadSizeLimit:(o==null?void 0:o.default_upload_size_limit)??Kn,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)??ks),supportedFileMimeTypes:new Set((o==null?void 0:o.supported_file_mime_types)??Ls)})},[]),r=l.useCallback(s=>{const{channel:o,uploadSizeLimit:i=Kn}=s,c=(d=!0)=>o!=null&&o.isAIAgent?d?et(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 et(o);default:return!0}},get supportedMimeTypes(){return c()?[ir]:[...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}},Os=(...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:Ad,useContext:ht}=ve("AIAgentMessengerSession"),Td=l.forwardRef(function({userSessionInfo:e,children:t},n){const{_aiAgentSDK:r,chatSDK:s,aiAgentId:o,logger:i}=xe(),{updateTheme:c}=Fr(),[u,d]=l.useState(void 0),[m,h]=l.useState(void 0),[f,g]=l.useState(null),[C,v]=l.useState(null),[p,b]=l.useState(null),[y,A]=l.useState(null),[T,R]=l.useState(null),{updateBaseAttachmentRules:N,createAttachmentRules:k}=yd();l.useEffect(()=>{const U=r.onMessengerSettingsUpdated(({settings:L})=>{const{appearance:V,bot:P,launcher:Y,memory:ge}=L;c(V.selected_theme,V),b(nu(P)),A(ru(Y)),R(ge?ur(ge):null),N(L)}),q=r.onActiveChannelUpdated(({channelUrl:L,status:V,conversationStatus:P})=>{h({url:L,status:V,conversationStatus:P})}),K=r.onAuthTokenRefreshed(()=>{var V;const L=(V=r.session)==null?void 0:V.userSession.authToken;L&&v(P=>P?{...P,authToken:L}:null)});return()=>{U(),q(),K()}},[r,c,N]);const x=l.useCallback(async()=>{try{const U=await r.authenticate(e),q=r.session;return g(q.sdkUser),v(q.userSession),h(q.activeChannel),d(void 0),U}catch(U){throw g(null),v(null),h(void 0),d(U),U}},[r,e]),D=l.useCallback(async()=>{await r.deauthenticate(),g(null),h(void 0),v(null),b(null),A(null),R(null)},[r]),F=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 U=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:D,updateContext:async(...q)=>{const K=Os(...q);if(K.type==="active"){const P=await(await U()).updateContext(o,K.context);return kt(P)}const L=await s.aiAgent.updateContext(K.aiAgentId,K.channelUrl,K.context);return kt(L)},patchContext:async(...q)=>{const K=Os(...q);if(K.type==="active"){const P=await(await U()).patchContext(o,K.context);return kt(P)}const L=await s.aiAgent.patchContext(K.aiAgentId,K.channelUrl,K.context);return kt(L)},getContextObject:async()=>{const K=await(await U()).getContextObject(o);return kt(K)}}},[x,D,m,s,o,i]),a.createElement(Ad,{value:{sdkUser:f,userSessionInfo:e,userSession:C,activeChannel:m,setActiveChannel:h,refreshActiveChannel:F,createConversation:r.createConversation,searchConversation:r.searchConversation,connectionError:u,aiAgentInfo:p,launcherInfo:y,memoryInfo:T,authenticate:x,deauthenticate:D,createAttachmentRules:k}},t)}),Id={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"},xd=e=>e.disabled?Id[e.disabledBy]==="ready":!0,Rd=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&&Ve(t)?"file_image":t&&zt(t)?"file_video":t&&bc(t)?"file_audio":"file_document"};let Ns=0;const Md=e=>(Ns+=1,`${e??"unknown"}:${Ns}`),vt=(e,t)=>e===void 0||t===e,_i=(e,t)=>{!t.error&&t.messages.length>0&&e.conversationNotInteractiveTimeout.markHistoryLoaded("success",t.channelUrl)},Ei=(e,t)=>{t.error?e.conversationNotInteractiveTimeout.markHistoryLoaded("failed",t.channelUrl):e.conversationNotInteractiveTimeout.markHistoryLoaded(t.messages.length>0?"success":"verified_empty",t.channelUrl)},wd=(e,t)=>{_i(e,t)},kd=(e,t)=>{Ei(e,t)},Ld=(e,t,n)=>{var o;if(!tt(e,n))return;const{hasResponseMetadata:r,...s}=Ko(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}))},Ds=(e,t)=>{t.streamStalled.clearMessage(e.messageId),t.userPerceivedResponseTime.clearMessage(e.messageId);const n=Xe(e)?e.reqId:void 0;n&&(t.messagePendingStuck.disappear({requestId:n}),t.userPerceivedResponseTime.cancelTurn(n),t.typingIndicatorAbsentTimeout.cancelTurn(n))},Yn=(e,t)=>{t&&(e.conversationNotInteractiveTimeout.clearChannel(t),e.recoveryNotInteractiveTimeout.clearChannel(t),e.messagePendingStuck.clearChannel(t),e.userPerceivedResponseTime.clearChannel(t),e.typingIndicatorAbsentTimeout.clearChannel(t),e.streamStalled.clearChannel(t))},Od=({activeChannelUrl:e,statsTrackers:t})=>{const{chatSDK:n}=xe(),{aiAgentInfo:r}=ht(),s=l.useRef(!1),o=r==null?void 0:r.userId;mt(!!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])},Nd=({enabled:e=!0,requestedChannelUrl:t,statsTrackers:n})=>{const r=l.useRef(void 0);l.useLayoutEffect(()=>{const s=r.current;if(!e){s&&(Yn(n,s),r.current=void 0);return}s&&s!==t&&(Yn(n,s),r.current=void 0),t&&s!==t&&(n.conversationNotInteractiveTimeout.start({channelUrl:t}),r.current=t)},[e,t,n]),l.useLayoutEffect(()=>()=>{const s=r.current;s&&(Yn(n,s),r.current=void 0)},[n])},Dd=({aiAgentUserId:e,statsEnabled: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&&vt(n,g.channelUrl),[n]);return l.useEffect(()=>{if(!t)return;const g=s.current;g&&f(g)&&(g.tracked||(_i(r,g),g.tracked=!0));const C=o.current;C&&f(C)&&(C.tracked||(Ei(r,C),C.tracked=!0))},[t,f,r]),l.useMemo(()=>({onCollectionEvent:g=>{if(h(m)&&vt(n,g.channelUrl)){if(g.kind==="messagesDeleted"){g.messages.forEach(C=>Ds(C,r));return}t&&g.messages.forEach(C=>Ld(C,r,e))}},onCacheResult:(g,C,v)=>{if(!h(m)||!vt(n,v))return;const p={error:g,messages:C,channelUrl:v,lifecycleGeneration:u.current,tracked:!1};s.current=p,t&&(wd(r,p),p.tracked=!0)},onApiResult:(g,C,v)=>{if(!h(m)||!vt(n,v))return;const p={error:g,messages:C,channelUrl:v,lifecycleGeneration:u.current,tracked:!1};o.current=p,t&&(kd(r,p),p.tracked=!0)},onLocalMessageDeleted:g=>{h(m)&&vt(n,g.channelUrl)&&Ds(g,r)}}),[e,m,t,h,n,r])},$d=({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.markInputReady(t))},[t,e,r,o]),l.useEffect(()=>{if(!e||!n||i.current)return;const u=c.current,d=setTimeout(()=>{c.current===u&&(o.conversationNotInteractiveTimeout.markRendered(t),i.current=!0)});return()=>clearTimeout(d)},[t,e,n,s,o])},Pd=({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()&&vt(f,v);try{const v=await c(p=>{if(!C(p.channelUrl)){u==null||u(p);return}m=p.reqId,n.messagePendingStuck.start({requestId:p.reqId,channelUrl:p.channelUrl,messageType:Rd(p),tracksUploadProgress:d.tracksUploadProgress??!1}),u==null||u(p)},p=>{!g()||m!==p||n.messagePendingStuck.markUploadProgress(p)});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])},Fd=({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=Md(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])},Ud=({requestedChannelUrl:e,activeChannelUrl:t,statsEnabled:n=!0,statsTrackers:r})=>{const{aiAgentInfo:s}=ht();Od({activeChannelUrl:t,statsTrackers:r}),Nd({enabled:n,requestedChannelUrl:e,statsTrackers:r});const o=Dd({aiAgentUserId:s==null?void 0:s.userId,statsEnabled:n,requestedChannelUrl:e,statsTrackers:r}),i=Pd({channelUrl:t,enabled:n,statsTrackers:r}),c=Fd({channelUrl:t,enabled:n,statsTrackers:r});return l.useMemo(()=>({messageCallbacks:o,runWithPendingStuckStats:i,runWithUserTurnStats:c}),[o,i,c])},xt=()=>xe()._aiAgentSDK.statsTrackers,Bd=({enabled:e=!0,channelUrl:t}={})=>{const{conversationInitialRender:n}=xt(),{watchBackgrounded:r}=xe()._aiAgentSDK,s=l.useRef(null);return l.useLayoutEffect(()=>{n.setVisible(e)},[e,n]),l.useLayoutEffect(()=>{if(!t)return;const o=n.startSpan(t);return s.current=o,()=>{o.cancel(),s.current===o&&(s.current=null)}},[t,n]),l.useMemo(()=>({onGetChannelStart:o=>{var i;(i=s.current)==null||i.onGetChannelStart(o)},onGetChannelComplete:({channelUrl:o,conversationId:i})=>{var c;(c=s.current)==null||c.onGetChannelComplete(o,i)},onGetChannelError:({channelUrl:o,error:i})=>{var c;(c=s.current)==null||c.onGetChannelError(o,i)},onCollectionInitializeStart:()=>{var o;(o=s.current)==null||o.onGetMessagesStart()},onCollectionCacheResult:(o,i)=>{var c;(c=s.current)==null||c.onGetMessagesCacheComplete(i,o)},onCollectionApiResult:(o,i)=>{const c=s.current;if(!c)return;c.onGetMessagesComplete(i,o);const u=r==null?void 0:r();Ie(()=>{u!=null&&u()?c.onRenderDiscarded():c.onRendered()})}}),[r])},Yt=(e,t)=>{const n=l.useId(),r=l.useRef(t);l.useLayoutEffect(()=>{r.current=t}),l.useLayoutEffect(()=>{const s=new Ce.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])},$s=()=>{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 Hd(e,t={}){const{shouldInitializeConversation:n=!0}=t,{chatSDK:r,logger:s,aiAgentId:o,_aiAgentSDK:i}=xe(),{sdkUser:c}=ht(),u=$s(),d=$s(),m=wn(),[h,f]=l.useState(void 0),[g,C]=l.useState(void 0),[v,p]=l.useState(!1),b=le(A=>{if(n&&A.isAIAgent&&!A.conversation){const T=d.next();p(!0),i.initConversationIfNeeded(A).finally(()=>{d.isCurrent(T)&&p(!1)})}});async function y(){var T,R,N,k,x,D;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),C(void 0),d.invalidate(),p(!1),e){(T=t.onFetchStart)==null||T.call(t,e);try{s.debug("useChannel.getChannel: get channel",e);const F=await r.groupChannel.getChannel(e);if(!u.isCurrent(A))return;b(F),f(F),(N=t.onFetchSuccess)==null||N.call(t,{channelUrl:F.url,conversationId:(R=F.conversation)==null?void 0:R.id}),F.url===((k=i.session)==null?void 0:k.activeChannel.url)&&i.session._updateActiveChannel({url:F.url,status:Fe(F)?"closed":"open",conversationStatus:(x=F.conversation)==null?void 0:x.status}),s.debug("useChannel.getChannel: fetched channel",F)}catch(F){if(!u.isCurrent(A))return;(D=t.onFetchError)==null||D.call(t,{channelUrl:e,error:F}),F instanceof Ce.SendbirdError&&C(F),s.error("useChannel.getChannel: error",F)}}}return l.useEffect(()=>(y(),()=>{u.invalidate()}),[r,c,e,o]),l.useEffect(()=>{n&&h&&b(h)},[n]),Yt(r,{async onReconnectSucceeded(){var R;if(!h){g&&await y();return}const A=u.current(),T=await h.refresh();!u.isCurrent(A)||h.url!==e||((R=t.onReconnectSucceeded)==null||R.call(t,h.url),b(T),f(T))}}),mt(r,{onChannelChanged:A=>{A.isGroupChannel()&&A.url===e&&(s.debug("useChannel.onChannelChanged: channel changed",A.url),f(A),m())}}),{channel:h,channelFetchError:g,getChannel:y,isInitializingConversation:v}}const Gd=new Set(["suggested_replies","steward","system"]),zd=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||!Gd.has(r)))return r},Vd=e=>{var o;const t=e==null?void 0:e.lastMessage;if(!t||!e)return!1;const n=t.extendedMessagePayload,r=In(n).hasActiveForm,s=e.isAIAgent&&!!((o=e.conversation)!=null&&o.handedOverAt);return r&&!s},qd=()=>{const{chatSDK:e,networkStateAdapter:t}=xe(),[n,r]=l.useState(()=>t?t.isOnline()?"connected":"reconnecting":"connected");return Yt(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===Ce.ConnectionState.OPEN?"connected":o)})},[t,e]),n},Kd=3e4,Yd=({shouldApply:e,lastMessage:t,isBlockedWhileAIResponding:n,currentUserId:r})=>{const[s,o]=l.useState(!1),i=l.useRef(null),c=t&&tt(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=Kd-m;return n||h<=0?u():d(h),()=>{i.current&&clearTimeout(i.current)}},[n,c]),s&&e},Ci=e=>{const{chatSDK:t}=xe(),[n,r]=l.useState([]);return mt(t,{onTypingStatusUpdated(s){if(s.url===(e==null?void 0:e.url)){const o=s.getTypingUsers();r(o)}}}),n},Wd=({channel:e,lastMessage:t,aiAgentUserId:n,isStreamAnimating:r})=>{const[s,o]=l.useState(!1),i=Ci(e);return l.useEffect(()=>{if(!t)return;const c=i.some(d=>d.userId===n),u=tt(t,n)&&(ke.isStreaming(t)||r);o(u||c)},[i,t,n,r]),s},jd=({channel:e,messages:t,isStreamAnimating:n,isInitializingConversation:r})=>{const{aiAgentInfo:s,userSession:o}=ht(),i=qd(),c=Wd({channel:e,lastMessage:hs(t,[De.SendingStatus.SUCCEEDED]),aiAgentUserId:(s==null?void 0:s.userId)??"",isStreamAnimating:n}),u=Yd({shouldApply:!!(e!=null&&e.isAIAgent)&&!et(e),isBlockedWhileAIResponding:c,lastMessage:hs(t,[De.SendingStatus.PENDING,De.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(Fe(e))return d("conversation_closed");if(jc(e))return d("handoff_pending");if(Vd(e))return d("form_active");const m=zd(e);return d(m||(c||u||r?"ai_responding":""))},Xd=()=>{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:Zd}=ve("AIAgentConversation");function Jd({children:e,channelUrl:t,onChannelDeleted:n,onMessagesReceived:r,onMessagesUpdated:s,onConversationStatusChanged:o,onConversationClosedViaDispatcher:i,onBeforeSendMessage:c,onAfterSendMessage:u=he,shouldMarkAsRead:d=!0,conversationStatsEnabled:m=!0,shouldInitializeConversation:h=!0,shouldCountNewMessages:f=()=>!1,sortComparator:g}){var Me,$;const C=()=>d&&(x==null?void 0:x.markAsRead()),{_aiAgentSDK:v,chatSDK:p,logger:b,dispatcher:y}=xe(),A=xt(),T={channelUrl:t,enabled:m},R=od({...T,statsTracker:A.conversationNotInteractiveTimeout}),N=id({...T,scheduleForegroundTask:v.scheduleForegroundTask,statsTracker:A.recoveryNotInteractiveTimeout}),k=Bd(T),{channel:x,channelFetchError:D,getChannel:F,isInitializingConversation:U}=Hd(t,{shouldInitializeConversation:h,onFetchStart:I=>{R.onFetchStart(I),k.onGetChannelStart(I)},onFetchSuccess:I=>{R.onFetchSuccess(I),k.onGetChannelComplete(I)},onFetchError:I=>{R.onFetchError(I),k.onGetChannelError(I)},onReconnectSucceeded:N.onReconnectSucceeded}),q=x==null?void 0:x.url,K=Ud({requestedChannelUrl:t,activeChannelUrl:q,statsEnabled:m,statsTrackers:A}),L=rd(p,x,{replyType:De.ReplyType.ONLY_REPLY_TO_CHANNEL,shouldCountNewMessages:f,logger:b,markAsRead:C,sortComparator:g,onChannelDeleted:n,onMessagesReceived:I=>r==null?void 0:r(I),onMessagesUpdated:I=>s==null?void 0:s(I),onCollectionInitializeStart:()=>{k.onCollectionInitializeStart()},onApiResult:(I,w,O)=>{k.onCollectionApiResult(I,O),K.messageCallbacks.onApiResult(I,w,O)},onCacheResult:(I,w,O)=>{k.onCollectionCacheResult(I,O),K.messageCallbacks.onCacheResult(I,w,O)},onCollectionEvent:I=>{K.messageCallbacks.onCollectionEvent(I),gi.publish(I)},onLocalMessageDeleted:I=>{K.messageCallbacks.onLocalMessageDeleted(I)},onOutgoingMessageStatusChanged:I=>{x&&v.liveMetricManager.track({type:"outgoingMessage",channel:x,message:I})}}),V=Xd(),P=jd({channel:x,messages:L.messages,isStreamAnimating:V.isAnimating,isInitializingConversation:U});$d({enabled:m,channelUrl:q,initialized:L.initialized,inputReady:xd(P),renderedSignal:L.messages,statsTrackers:A}),l.useEffect(()=>{C()},[d,x]);const Y=(Me=x==null?void 0:x.conversation)==null?void 0:Me.status;l.useEffect(()=>{Y&&(o==null||o(Y))},[Y,o]),l.useEffect(()=>{const I=async w=>{const O=typeof(w==null?void 0:w.channelUrl)=="string";x&&O&&w.channelUrl!==x.url||(b.debug("conversation.dispatcher: try to close conversation",x),x!=null&&x.conversation&&x.conversation.status===fe.ConversationStatus.OPEN&&(await x.closeConversation(),i==null||i()))};return y.subscribe(ze.ConversationClose,I),()=>{y.unsubscribe(ze.ConversationClose,I)}},[y,x,b,($=x==null?void 0:x.conversation)==null?void 0:$.status,i]);const ge=le(()=>L.loadPrevious()),j=le(()=>L.loadNext()),W=le(async I=>{try{await L.deleteMessage(I)}finally{I.sendingStatus!=="succeeded"&&K.messageCallbacks.onLocalMessageDeleted(I)}}),X=le(I=>I.isUserMessage()?K.runWithUserTurnStats(w=>K.runWithPendingStuckStats(O=>L.resendMessage(I,G=>{w(G.reqId),O(G)}),void 0)):K.runWithPendingStuckStats((w,O)=>L.resendMessage(I,w,O),void 0,{tracksUploadProgress:I.isMultipleFilesMessage()})),M=le(()=>L.resetNewMessages()),Z=le(async I=>{var O;if(((O=x==null?void 0:x.conversation)==null?void 0:O.status)===fe.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(I=await c(I));const w=await K.runWithUserTurnStats(G=>K.runWithPendingStuckStats(J=>L.sendUserMessage(I,se=>{G(se.reqId),J(se)}),u));return u==null||u(w),w}),ie=le(async I=>{var O;if(((O=x==null?void 0:x.conversation)==null?void 0:O.status)===fe.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(I=await c(I));const w=await K.runWithPendingStuckStats(G=>L.sendFileMessage(I,G),u);return u==null||u(w),w}),ye=le(async I=>{var O;if(((O=x==null?void 0:x.conversation)==null?void 0:O.status)===fe.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(I=await c(I));const w=await K.runWithPendingStuckStats((G,J)=>L.sendMultipleFilesMessage(I,G,J),u,{tracksUploadProgress:!0});return u==null||u(w),w}),$e={_statsEnabled:m,conversation:(x==null?void 0:x.conversation)??void 0,actions:{setUserMemoryState:v.setUserMemoryState},channelSource:{channel:x,error:D,refetch:()=>F(),closeConversation:async()=>{Fe(x)||await(x==null?void 0:x.closeConversation())}},messageSource:{messages:L.messages,newMessages:L.newMessages,initialized:L.initialized,loadPrevious:ge,loadNext:j,deleteMessage:W,resendMessage:X,resetNewMessages:M,sendUserMessage:Z,sendFileMessage:ie,sendMultipleFilesMessage:ye},state:{streamAnimation:V,input:P}};return a.createElement(Zd,{value:$e},e)}function Qd(e,t,n){var b,y,A,T,R,N,k,x,D,F;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=le(()=>{var U;return(U=n==null?void 0:n.onListRequestStart)==null?void 0:U.call(n)}),g=le(U=>{var q;return(q=n==null?void 0:n.onListRequestComplete)==null?void 0:q.call(n,U)}),C=l.useCallback(async U=>{f();try{await U.loadMore(),g()}catch(q){throw g(q),q}},[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 U=new Qo(e,t);U.setConversationListCollectionHandler({onChannelsAdded:()=>{u(U.channels)},onChannelsUpdated:()=>{u(U.channels)},onChannelsDeleted:()=>{u(U.channels)}}),await C(U),u(U.channels),m(U),i(null)}catch(U){m(null),i(U)}finally{s(!0),h.current=!1}}},[e,e.currentUser,(b=t.filter)==null?void 0:b.aiAgentChannelFilter,(A=(y=t.filter)==null?void 0:y.aiAgentConversationStatusFilter)==null?void 0:A.join(),(R=(T=t.filter)==null?void 0:T.aiAgentIds)==null?void 0:R.join(),(N=t.filter)==null?void 0:N.deskChannelFilter,(x=(k=t.filter)==null?void 0:k.pinnedChannelUrls)==null?void 0:x.join(),(D=t.filter)==null?void 0:D.copilotConversationOnly,(F=t.filter)==null?void 0:F.copilotSupportChannelUrl,t.limit,C]),p=l.useCallback(async()=>{if(d)try{await d.loadMore(),u(d.channels)}catch(U){i(U)}},[d]);return Yt(e,{onConnected:()=>v()}),l.useEffect(()=>{v()},[v]),l.useEffect(()=>()=>{h.current=!1,d==null||d.dispose()},[d]),{initialized:r,error:o,channels:c,loadMore:p}}const bi=e=>{var s;const{aiAgentId:t,queryParams:n}=xe(),r=(s=n==null?void 0:n.conversationListParams)==null?void 0:s.filter;return{aiAgentIds:[t],aiAgentConversationStatusFilter:[fe.ConversationStatus.CLOSED,fe.ConversationStatus.OPEN],...r,...e}},em=({enabled:e=!0}={})=>{const{conversationListInitialRender:t}=xt(),{watchBackgrounded:n}=xe()._aiAgentSDK,r=l.useRef(null);return l.useLayoutEffect(()=>{t.setVisible(e)},[e,t]),l.useLayoutEffect(()=>{const s=t.startSpan();return r.current=s,()=>{s.cancel(),r.current===s&&(r.current=null)}},[t]),l.useMemo(()=>({onListRequestStart:()=>{var s;(s=r.current)==null||s.onListRequestStart()},onListRequestComplete:s=>{const o=r.current;if(!o||(o.onListRequestComplete(s),s))return;const i=n==null?void 0:n();Ie(()=>{i!=null&&i()?o.onRenderDiscarded():o.onRendered()})}}),[n])},{Provider:tm}=ve("AIAgentConversationList");function nm({conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:n=!0,children:r}){var h;const{chatSDK:s,queryParams:o}=xe(),i=e??((h=o==null?void 0:o.conversationListParams)==null?void 0:h.limit),c=bi(t),u=em({enabled:n}),d=Qd(s,{limit:i,filter:c},{onListRequestStart:()=>{u.onListRequestStart()},onListRequestComplete:f=>{u.onListRequestComplete(f)}}),m={listSource:{initialized:d.initialized,error:d.error??void 0,channels:d.channels,loadMore:()=>d.loadMore()}};return a.createElement(tm,{value:m},r)}function rm(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:sm,useContext:om}=ve("MessageTemplateFetching");function im({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(p=>{throw f||i(h,{error:!0}),p}).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=rm(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(sm,{value:u},e)}const am="remove_powered_by",Ur=(e,t)=>{var s,o;const{chatSDK:n}=xe(),{aiAgentInfo:r}=ht();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&&xr(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(am)),[i])}throw new Error("Unsupported feature")},cm={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"},lm={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}}},um={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}}},dm={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}}},mm={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}}},hm={text:lm,number:um,"single-select":dm,"multi-select":mm},fm={getValueOrDefault:()=>null,validate:()=>({isValid:!1})};function vi(e){return hm[e.type]||fm}function Ps(e){return vi(e).getValueOrDefault(e)}function gm(e,t,n={}){const r={...cm,...n};return vi(e).validate(e,t,r)}const pm=(e,t={})=>{const{labels:n={},onSubmit:r,onCancel:s}=t,[o,i]=l.useState({}),[c,u]=l.useState(()=>{const v={};return e.fields.forEach(p=>{v[p.key]=Ps(p)}),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 p=!1;e.fields.forEach(b=>{const y=Ps(b);JSON.stringify(c[b.key])!==JSON.stringify(y)&&(p=!0),v[b.key]=y}),p&&u(v)}},[d]);const m=(v,p)=>{u(b=>({...b,[v]:p})),i(b=>({...b,[v]:void 0}))},h=e.fields.map(v=>{var y,A,T;const p=c[v.key]??null,b={key:v.key,label:v.label,error:o[v.key],required:v.required};return v.type==="text"?{...b,type:"text",layout:v.layout,value:p,...v.placeholder&&{placeholder:v.placeholder},...((y=v.rules)==null?void 0:y.max_length)&&{maxLength:v.rules.max_length}}:v.type==="number"?{...b,type:"number",layout:v.layout,value:p,...v.placeholder&&{placeholder:v.placeholder},...((A=v.rules)==null?void 0:A.max)&&{max:v.rules.max}}:v.type==="single-select"?{...b,type:"single-select",layout:v.layout,value:p,options:v.options}:v.type==="multi-select"?{...b,type:"multi-select",layout:v.layout,value:p,options:v.options,...((T=v.rules)==null?void 0:T.max_select)&&{maxSelect:v.rules.max_select}}:{...b,type:"unknown",layout:"default",value:null}});return{state:d,fields:h,getField:v=>h.find(p=>p.key===v),updateFieldValue:m,submit:async()=>{const v={};let p=!1;for(const b of e.fields){const y=c[b.key]??null,A=gm(b,y,n);A.isValid||(v[b.key]=A.error,p=!0)}if(i(v),!p&&r){const b={};e.fields.forEach(y=>{b[y.key]=c[y.key]??null}),await r(b)}},cancel:async()=>{await(s==null?void 0:s())}}},_m=e=>{const{chatSDK:t,handlers:n,logger:r}=xe(),{aiAgentInfo:s}=ht(),o=l.useRef(new Set),i=l.useRef(new Set),c=(m,h)=>{if(!(n!=null&&n.onCustomEvent)||!(s!=null&&s.userId)||!tt(m,s.userId))return;const f=m.messageId;if(ke.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=Vo(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 mt(t,{onMessageReceived:(m,h)=>d(m,h,"received"),onMessageUpdated:(m,h)=>d(m,h,"updated")}),{checkForUserActionRequired:u}},Em=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},Si=e=>{const{aiAgentInfo:t}=ht(),n=Ci(e);if(Fe(e))return null;const r=n[0];if(!r)return null;const s=r.userId===(t==null?void 0:t.userId),o=s?Em(r.metaData):void 0;return{user:s?t:r,isBot:s,thinkingMessage:o}},Cm=(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},[])},bm=(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()}}},vm=(e,t,n=1e4,r=!0)=>{const s=l.useRef(null),o=l.useRef(null),i=l.useRef(!1);s.current||(s.current=bm(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])},Sm=({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=ti(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?et(e)?s.human("agent"):s.ai("delight"):e.isDesk?s.human("agent"):s.channel("user")},Fs=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 ym=new Set(["free_text","single_choice"]),Am=({csatPayload:e,type:t,initialCsat:n,initialCsatReason:r,initialIsResolved:s})=>{const[o,i]=Fs({csatType:t,csat:n,csatReason:r,isResolved:s}),[c,u]=Fs({followUpItem:!1}),d=l.useMemo(()=>{var p;const g=o.csat,C=typeof g=="number",v=(p=e.follow_up)==null?void 0:p.find(b=>C?b.scores.includes(g):b.always_visible??!1);if(ym.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"}}},Tm=({csat:e,csatExpireAt:t,csatPayload:n,isSubmitInFlight:r=!1})=>{const s=!!n&&n.visibility&&!!je[n.type],o=!r&&typeof e!="number"&&ni(t),i=wn();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}},Wn=5,Nt=250,Im=50,Us=e=>Math.max(0,e-Im),dn=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():0,xm=e=>e<1e3?{speed:Wn*.5,chunkSize:2}:e<2e3?{speed:Wn*.8,chunkSize:2}:{speed:Wn*.6,chunkSize:3},mn=(e,t)=>{let n=0;for(let r=t-1;r>=0&&e[r]==="\\";r--)n++;return n%2===1},Bs=(e,t,n,r)=>{let s=1,o=t;for(;o<e.length&&s>0;){if(mn(e,o)){o++;continue}e[o]===n?s++:e[o]===r&&s--,o++}return s>0?-1:o},yi=(e,{hideImages:t,hideLinks:n})=>{let r="",s=0,o=0;for(;s<e.length;){if(e[s]==="`"&&!mn(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]==="["&&!mn(e,s),c=e[s]==="["&&!mn(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=Bs(e,s+(i?2:1),"[","]");if(d===-1)return r;if(s=d,e[s]!=="("){r+=e.slice(u,s);continue}const m=Bs(e,s+1,"(",")");if(m===-1)return r;s=m,r+=e.slice(u,s)}return r},Rm=({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(y=>{var A;(A=r.current)==null||A.call(r,y)},[]),m=l.useCallback(y=>{const A=e.initialEnabled&&(e.enabled||y<e.textLength),T=A&&e.deferImages,R=A&&e.deferLinks;return!T&&!R?y:yi(e.text.slice(0,y),{hideImages:T,hideLinks:R}).length},[e]),h=l.useCallback((y,A,T=!1)=>{r.current&&(y<=c.lastLength||!T&&A-c.lastReportedAt<Nt||(c.lastLength=y,c.lastReportedAt=A,d(y)))},[d,c]),f=l.useCallback((y,A,T=!1)=>{if(!r.current)return;const R=Math.max(c.lastReportedAt,c.lastCheckedAt);!T&&A-R<Nt||(c.lastCheckedAt=A,h(m(y),A,!0))},[m,h,c]),g=l.useCallback((y,A,T=!1)=>{s.current&&(y<=i.lastLength||!T&&A-i.lastReportedAt<Nt||(i.lastLength=y,i.lastReportedAt=A,s.current(y)))},[i]),C=l.useCallback((y,A,T)=>{const R=y>=A,N=T-i.lastReportedAt>=Nt;if(!R&&!N)return;const k=m(y);g(k,T,R)},[m,i,g]),v=l.useCallback(()=>{c.lastLength=0,c.lastReportedAt=0,c.lastCheckedAt=0,i.lastLength=0,i.lastReportedAt=0},[i,c]),p=l.useCallback(y=>{r.current&&(o.current!==null&&y<=o.current||(o.current=y,d(y)))},[d]),b=l.useCallback(({displayedLength:y,streamTextLength:A})=>{const T=u.current;if(u.current={displayedLength:y,streamTextLength:A},!e.initialEnabled||!T||y>T.displayedLength||A<=T.streamTextLength)return;const R=dn();h(A,R,!0),g(A,R,!0)},[u,g,h,e]);return{resetProgress:v,reportVisibleTextProgress:f,reportRenderedTextProgress:C,reportNonStreamingVisibleTextProgress:p,reportMarkdownRevealProgress:b}},Mm=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(()=>Us(t.length)),C=l.useRef(null),v=l.useRef({startTime:0,lastUpdate:0,lastProgressCall:0}).current,p=l.useRef({startCalled:!1,completeCalled:!1}).current,b=l.useRef({initialEnabled:n,textLength:t.length,enabled:n,text:t,deferImages:m,deferLinks:h,snapOnDisable:r}).current,y=le(()=>o==null?void 0:o()),A=le(()=>i==null?void 0:i()),T=le(()=>c==null?void 0:c()),{resetProgress:R,reportVisibleTextProgress:N,reportRenderedTextProgress:k,reportNonStreamingVisibleTextProgress:x,reportMarkdownRevealProgress:D}=Rm({trackedRef:b,onVisibleTextProgress:u,onRenderedTextProgress:d}),F=n,U=f<t.length,q=b.initialEnabled&&(F||U);l.useLayoutEffect(()=>{b.textLength=t.length,b.enabled=n,b.text=t,b.deferImages=m,b.deferLinks=h,b.snapOnDisable=r}),l.useLayoutEffect(()=>{if(b.initialEnabled){if(p.startCalled||(p.startCalled=!0,y()),!b.enabled&&b.snapOnDisable){g(t.length);const L=dn();N(t.length,L,!0),k(t.length,t.length,L);return}g(L=>t.length<L?t.length:L)}},[y,k,N,t]),l.useEffect(()=>{if(!b.initialEnabled)return;let L=Us(t.length);v.lastUpdate=0,v.startTime=0,v.lastProgressCall=0,R();const V=P=>{v.lastUpdate===0&&(v.lastUpdate=P,v.startTime=P,v.lastProgressCall=P,L>0&&N(L,P,!0));const Y=b.textLength;!b.enabled&&b.snapOnDisable&&L<Y&&(L=Y,g(L),N(L,P,!0),k(L,Y,P));const ge=P-v.lastUpdate,j=P-v.startTime,{speed:W,chunkSize:X}=xm(j),M=W*X;ge>=M&&L<Y&&(L=Math.min(L+X,Y),g(L),N(L,P,L>=Y),k(L,Y,P),v.lastUpdate=P),P-v.lastProgressCall>=Nt&&(v.lastProgressCall=P,A()),(L<Y||b.enabled)&&(C.current=requestAnimationFrame(V))};return C.current=requestAnimationFrame(V),()=>{C.current&&cancelAnimationFrame(C.current),p.startCalled&&!p.completeCalled&&(p.completeCalled=!0,T())}},[T,A,k,N,R]),l.useEffect(()=>{b.initialEnabled&&(n||t.length>0)||(x(t.length),k(t.length,t.length,dn()))},[n,d,u,x,k,t.length,b]),l.useEffect(()=>{const L=b.initialEnabled&&p.startCalled,V=!n,P=f>=t.length;L&&V&&P&&!p.completeCalled&&(p.completeCalled=!0,T())},[n,f,T,t.length]);const K=l.useMemo(()=>{const L=b.initialEnabled?t.slice(0,f):t,V=q&&m,P=q&&h;return!V&&!P?L:yi(L,{hideImages:V,hideLinks:P})},[t,f,m,h,q]);return l.useEffect(()=>{!b.initialEnabled||q||N(f,dn(),!0)},[f,q,N]),l.useEffect(()=>{D({displayedLength:f,streamTextLength:K.length})},[f,D,K.length]),{streamText:K,isAnimating:q}},Hs={visible:!1,remainingTime:0,showDescription:!1,targetTimeMs:null},wm=e=>({visible:!0,remainingTime:e,showDescription:!0,targetTimeMs:Date.now()+e*1e3}),km=(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}},Lm=()=>{const{chatSDK:e}=xe(),[t,n]=l.useState(Hs),r=()=>n(Hs);return Yt(e,{onConnectionDelayed:s=>{s>0?n(wm(s)):r()},onReconnectSucceeded:r,onConnected:r}),l.useEffect(()=>{if(!t.visible||!t.showDescription||t.targetTimeMs==null)return;const s=setTimeout(()=>{n(o=>km(o))},1e3);return()=>clearTimeout(s)},[t.visible,t.showDescription,t.targetTimeMs,t.remainingTime]),{visible:t.visible,remainingTime:t.remainingTime,showDescription:t.showDescription}},Om=e=>{const t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`},Nm=(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)}},Dm=({enabled:e=!0}={})=>{const t=xt();return l.useCallback(({message:n,isBotMessage:r,aiAgentUserId:s})=>{if(!e)return;const o=n.messageId,i=ke.isStreaming(n),c=In(n.extendedMessagePayload),u=c.hasMessageTemplate,d=c.hasForm,m=r&&n.isUserMessage()&&!i&&!vc(n)&&!ke.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=p=>{t.streamStalled.markRenderedProgress({messageId:o,displayedLength:p})}),u&&(v.onMessageTemplateError=p=>{t.renderedContentUnusable.commit({messageId:o,contentKind:"template",errorDomain:"template_error",error:p})}),d&&(v.onFormRenderError=p=>{t.renderedContentUnusable.commit({messageId:o,contentKind:"form",errorDomain:"form_error",error:p})}),v},[e,t])},$m=e=>{const t=l.useRef(!1);l.useEffect(()=>{t.current||e!=null&&e.onVisibleTextProgress&&(t.current=!0,e.onVisibleTextProgress(0))},[e])},jn=5e3,Pm=({channelUrl:e,enabled:t=!0,isInitiallyBackgrounded:n,isForegrounded:r,subscribeToForegroundState:s})=>{const o=xt(),i=l.useRef(t),c=l.useRef(n),u=l.useRef(t&&n()?performance.now()-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(performance.now()-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=performance.now()-jn):u.current=null,s(h=>{if(h==="backgrounded"){u.current??(u.current=performance.now()),d.current=!1,e&&o.recoveryNotInteractiveTimeout.cancelPending(e);return}m(!0)})},[e,t,m,o,s])},Fm=e=>{const{conversationInitialRender:t,conversationListInitialRender:n}=xt();l.useLayoutEffect(()=>{t.setPresentMethod(e),n.setPresentMethod(e)},[t,n,e])},Um=(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===Ce.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]),Yt(e,{onConnected:c,onReconnectSucceeded:c}),s},At=e=>e.replace(/\s+/g," ").trim(),Bm="Code block",Ai=e=>`A11Y_INLINE_CODE_${e}`,Ti=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}},Ii=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}},Hm=e=>{const{blockquotePrefix:t,content:n}=Ti(e),{content:r}=Ii(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}},Gm=(e,t)=>{const{blockquotePrefix:n,content:r}=Ti(e);if(n!==t.blockquotePrefix)return!1;const{content:s,hasListPrefix:o}=Ii(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)},zm=(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},Vm=(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},qm=(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},Km=e=>{let t=0,n="";for(;t<e.length;){const r=zm(e,"[",t);if(r===-1){n+=e.slice(t);break}const s=Vm(e,r+1);if(s===-1){n+=e.slice(t);break}if(r>0&&e[r-1]==="!"&&bn(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]==="!"&&!bn(e,r-1)?r-1:r;n+=e.slice(t,o);const i=e.slice(r+1,s),c=qm(e,s+2);if(c===-1){n+=e.slice(o);break}n+=i,t=c}return n},xi=(e,t,n)=>{if(!/^\d+$/.test(t))return!1;const r=e.slice(-1);return/\d/.test(r)&&/\d/.test(n)},Ym=e=>e.replace(/(^|[^*\\])\*\*([^\s*](?:[\s\S]*?[^\s*])?)\*\*(?!\*)/g,(t,n,r,s,o)=>{const i=o[s+t.length]??"";return xi(n,r,i)?t:`${n}${r}`}),Wm=e=>e.replace(/(^|[^_\\])__([^\s_](?:[\s\S]*?[^\s_])?)__(?!_)/g,"$1$2"),jm=e=>e.replace(/(^|[^~\\])~~([^\s~](?:[\s\S]*?[^\s~])?)~~(?!~)/g,"$1$2"),Xm=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 xi(r,s,c)?n:`${r}${s}`}),t=t.replace(/(^|[\s([{"'])_([^_\s](?:[\s\S]*?[^_\s])?)_(?=$|[\s)\]}"'.,!?:;])/g,"$1$2"),t},Zm=e=>e.replace(/\\([\\`*_[\]()#+.!~|-])/g,"$1"),Jm=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},Gs=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))},zs=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},Qm=e=>{const t=e.split(`
|
|
2
|
+
`),n=[];let r=0;for(;r<t.length;){const s=t[r],o=t[r+1],i=zs(s);if(i.length>0&&o&&Gs(o)){for(n.push(i.join(" ")),r+=2;r<t.length;){const c=t[r],u=zs(c);if(u.length===0||Gs(c))break;n.push(u.join(" ")),r+=1}continue}n.push(s),r+=1}return n.join(`
|
|
3
|
+
`)},eh=e=>e.replace(/^\s{0,3}(?:(?:-\s*){3,}|(?:\*\s*){3,}|(?:_\s*){3,})$/gm,""),th=(e,t)=>{const n=e.split(`
|
|
4
|
+
`),r=[];let s=0;for(;s<n.length;){const o=n[s],i=Hm(o);if(!i){r.push(o),s+=1;continue}let c=-1;for(let u=s+1;u<n.length;u++)if(Gm(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
|
+
`)},bn=(e,t)=>{let n=0,r=t-1;for(;r>=0&&e[r]==="\\";)n+=1,r-=1;return n%2===1},nh=e=>{const t=[];let n=0,r="";for(;n<e.length;){const s=e[n];if(s!=="`"||bn(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
|
+
`;){if(e[c]==="`"&&!bn(e,c)&&e.startsWith(i,c)){const d=e.slice(o,c),m=t.push(d)-1;r+=Ai(m),n=c+i.length,u=!0;break}c+=1}u||(r+=i,n=o)}return{text:r,inlineCodes:t}},Ri=(e,{codeBlockPlaceholder:t=Bm}={})=>{const n=e==null?void 0:e.replace(/\r\n?/g,`
|
|
7
|
+
`);if(!n)return;const r=[];let s=n;s=th(s,t),s=Jm(s);const o=nh(s);s=o.text,r.push(...o.inlineCodes),s=Km(s),s=Ym(s),s=Wm(s),s=jm(s),s=Xm(s),s=Qm(s),s=eh(s),s=Zm(s);for(let c=0;c<r.length;c++)s=s.replaceAll(Ai(c),r[c]);return At(s)||void 0},rh=(e,t)=>{var s;const n=((s=e.name)==null?void 0:s.trim())||"",r=e.mimeType??"";return Ve(r)?t.image:zt(r)?t.video:Xo({name:n,mimeType:r})?t.pdf(n):t.document(n)},vn=e=>(e==null?void 0:e.trim())||"",sh=e=>(e?At(e):void 0)||void 0,Vs=30,oh=e=>e.length>Vs?`${e.slice(0,Vs)}…`:e,ih=({agent:e,status:t,lastMessage:n,time:r,unreadCount:s},o)=>{const i=oh(At(n)),c=[t,i].filter(Boolean).join(", ");return o(At(e),At(c),r,s)},Mi=e=>({text:vn(e),format:"plain"}),ah=e=>({text:vn(e),format:"markdown"}),Xn=({markdownText:e,plainText:t,comparisonText:n})=>{const r=vn(e);return r&&r!==vn(n)?ah(r):Mi(t)},Dt=({sender:e,message:t,messageFormat:n="plain",time:r,codeBlockPlaceholder:s})=>{const o=[],i=n==="markdown"?Ri(t,{codeBlockPlaceholder:s}):sh(t);if(r&&o.push(r),e&&o.push(e),i&&o.push(i),o.length!==0)return o.join(", ")},wi=(e,t)=>Ri(e==null?void 0:e.trim(),t!==void 0?{codeBlockPlaceholder:t}:void 0),ch=(...e)=>At(e.filter(Boolean).join(", "))||void 0,qs=(e,t,n,r)=>{if(!t||t===n)return e;const s=wi(t,r);return s?ch(e,s):e},lh=(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=rh({name:c,mimeType:e.type},t);return qs(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 qs(h,n,d,t.codeBlockPlaceholder)}return wi(n,t.codeBlockPlaceholder)},uh=(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,D,F)=>({text:x,ignoreSuppression:D,queueOrder:f++,dedupeKey:F}),C=()=>{const x=c[0]??null,D=i;return x&&D?D.queueOrder<x.queueOrder?(i=null,D):c.shift()??null:x?c.shift()??null:D!==null?(i=null,D):null},v=()=>{for(;;){const x=C();if(!x)return null;if(!(!x.ignoreSuppression&&(r!=null&&r())))return x}},p=x=>{u=x.text,d=x.dedupeKey??null,h=!0,e(x.text),m=setTimeout(()=>{m=null,h=!1;const D=v();D&&p(D)},n)},b=x=>{u=x.text,d=x.dedupeKey??null,e(x.text)},y=(x,D,F,U)=>D!=null&&U!=null?D===U:D==null&&U==null?x!=null&&x===F:!1,A=(x,D,F)=>{if(!x||!D&&(r!=null&&r()))return;const U=F==null?void 0:F.dedupeKey;if(!(h&&y(x,U,u,d)))if(h){if(((F==null?void 0:F.mode)??"latestOnly")==="ordered"){const K=c[c.length-1];if(K&&y(x,U,K.text,K.dedupeKey))return;c.push(g(x,D,U)),c.length>o&&c.shift();return}i=g(x,D,U)}else i=null,p(g(x,D,U))};return{announce:(x,D)=>{A(x,!1,D)},announceIgnoringSuppression:(x,D)=>{A(x,!0,D)},flush:()=>{const x=[];let D=C();for(;D!==null;)x.push(D),D=C();if(m!==null&&(clearTimeout(m),m=null),h=!1,x.length!==0)for(const F of x)b(F)},destroy:()=>{m!==null&&(clearTimeout(m),m=null),i=null,c.length=0,u=null,d=null,h=!1}}},dh=e=>{switch(e){case"newMessage":case"conversationClosed":case"csatDisplayed":case"csatSubmitted":case"csatExpired":return"ordered";default:return"latestOnly"}},mh=(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(". "),hh=(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}},fh=(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}},gh=(e,t)=>!t||!Xe(e)||e.sender.userId!==t?null:e.reqId||(e.messageId>0?String(e.messageId):null),ph=(e,t)=>Oe.isAdmin(e)?Oe.isCSAT(e):"sender"in e?e.sender.userId!==t:!1,_h=e=>"messageId"in e&&e.messageId>0?String(e.messageId):"reqId"in e&&typeof e.reqId=="string"&&e.reqId.length>0?e.reqId:null,Eh=e=>e===Ce.CollectionEventSource.EVENT_MESSAGE_RECEIVED||e===Ce.CollectionEventSource.EVENT_MESSAGE_UPDATED,Ch=({isOpened:e,opensConversationList:t})=>e?t?"closeConversationList":"closeConversation":t?"openConversationList":"openConversation",bh=(e,t)=>{switch(e){case"closeConversationList":return t.closeConversationList;case"closeConversation":return t.closeConversation;case"openConversationList":return t.openConversationList;case"openConversation":return t.openConversation}},vh=(e,t)=>{switch(e){case"closeConversation":return t.hintCloseConversation;case"openConversationList":return t.hintOpenConversationList;case"openConversation":return t.hintOpenConversation;default:return}},Sh=({intent:e,strings:t})=>({label:bh(e,t),hint:vh(e,t)}),yh="1.36.0",Ue="sb-agent",Se={ENTRY:`${Ue}-entry`,MODAL_ROOT:`${Ue}-modal-root`,WINDOW:`${Ue}-window`,LAUNCHER:`${Ue}-launcher`,WINDOW_TITLE:`${Ue}-window-title`},ki="data-sb-initial-focus",Li="true",Ah=`[${ki}="${Li}"]`,Oi={[ki]:Li},Hr="data-sb-focus-trap-sentinel",Th="true",Ni="data-sb-initial-focus-header",Di="true",Ih=`[${Ni}="${Di}"]`,$i={[Ni]:Di},Pi="data-sb-message-input",Fi="true",xh=`textarea[${Pi}="${Fi}"]:not(:disabled)`,Rh={[Pi]:Fi},Ui=1e3,sn=2147483647,ft={MODAL:sn-1,TOOLTIP:sn-2,WINDOW:sn-3,LAUNCHER:sn-4},Bi=36,Mh=100,wh=yh,Gr="noopener noreferrer nofollow",kh=()=>typeof document>"u"||document.visibilityState==="visible",mr=()=>typeof document<"u"&&document.visibilityState==="hidden",Ks=()=>mr()?"backgrounded":"foregrounded",Lh={getState:Ks,subscribe:e=>{if(typeof document>"u")return()=>{};const t=()=>e(Ks());return document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t)}};function Oh(){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 on={};function Nh(){return{get:e=>{try{return localStorage.getItem(e)}catch{return on[e]??null}},set:(e,t)=>{try{localStorage.setItem(e,t)}catch{on[e]=t}},delete:e=>{try{localStorage.removeItem(e)}catch{delete on[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(on).filter(t=>t.startsWith(e))}}}}const Dh={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}`}},hr={language:"en",strings:Dh,dateLocale:sc.enUS},Hi=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}),Gi=e=>{var t;return((t=e.split("-"))==null?void 0:t[0])??Wt},Wt="en",zi=new Set([Wt,"ko","es","pt","fr","hi","it","de","tr","ja"]),$h='@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:Ph,useContext:zr}=ve("AgentUIElementResolver"),Fh=({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===Se.MODAL_ROOT?c:i.querySelector(`#${d}`);return{resolveElement:u,resolvePortalContainer:d=>u(d)??c}},[e,t,n]);return a.createElement(Ph,{value:s},r)};function ct(e,t){const n=e.getRootNode({composed:t});return n instanceof ShadowRoot||n instanceof Document?n:document}const Ys=()=>{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:Uh,useContext:Vr}=ve("EscapeDismissStack"),Ws=e=>{e.stopPropagation(),e.stopImmediatePropagation()},Bh=({rootElement:e=document.body,boundaryElement:t,children:n})=>{const r=l.useRef(null),s=l.useRef(null);r.current||(r.current=Ys()),s.current||(s.current=Ys());const o=r.current,i=s.current;l.useLayoutEffect(()=>{const u=t??ct(e),d=m=>{if(m.key==="Escape"){if(o.dismissTopmost()){Ws(m);return}i.dismissTopmost()&&Ws(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(Uh,{value:c},n)},Vi=(e,t,n)=>{const r=l.useRef(t);l.useLayoutEffect(()=>{r.current=t},[t]),l.useLayoutEffect(()=>{if(e)return n(()=>r.current())},[e,n])},Hh=(e,t)=>{const{register:n}=Vr();Vi(e,t,n)},Gh=(e,t)=>{const{registerShellDismissHandler:n}=Vr();Vi(e,t,n)},qi=()=>{const{subscribe:e,getOpenCount:t}=Vr();return l.useSyncExternalStore(e,()=>t()>0,()=>!1)},zh=(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=Hi(hr.strings),Vh={...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"},Sn={language:hr.language,dateLocale:hr.dateLocale,stringSet:Vh},qh=Object.freeze(Object.defineProperty({__proto__:null,default:Sn},Symbol.toStringTag,{value:"Module"})),fr=new Map([[Wt,Sn]]);async function Kh(e){const t=fr.get(e);if(t)return t;try{if(zi.has(e)){const{default:n}=await zh(Object.assign({"./languages/de.ts":()=>Promise.resolve().then(()=>require("./cjs/I-l-5Zo-.cjs")),"./languages/en.ts":()=>Promise.resolve().then(()=>qh),"./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 fr.set(e,n),n}return Sn}catch{return Sn}}const{Provider:Yh,useContext:ae}=ve("Localization"),Wh=({language:e=navigator.language,languageCode:t,logger:n,stringSet:r,children:s})=>{const[o,i]=l.useState(fr.get(Wt));return l.useEffect(()=>{const c=t??Gi(e);o.language!==c&&(n==null||n.debug("localization.useEffect: update language",{from:o.language,to:c}),Kh(c).then(i))},[e,t,n]),a.createElement(Yh,{value:{language:o.language,defaultStringSet:o.stringSet,stringSet:{...o.stringSet,...r},dateLocale:o.dateLocale,format:(c,u,d)=>ot.format(c,u,{locale:o.dateLocale,...d})}},s)},yn="data-sb-agent-theme",Xs=e=>(t,...n)=>{let r="";return t.forEach((s,o)=>{r+=s+(n[o]??"")}),`[${yn}='${e}'] & { ${r} }`},te={light:Xs("light"),dark:Xs("dark")},jh=H.css(({theme:e})=>{const{palette:t}=e;return`
|
|
8
8
|
:root,
|
|
9
9
|
:host {
|
|
10
10
|
--sendbird-primary-extra-dark: ${t.primary.extraDark};
|
|
@@ -53,9 +53,9 @@
|
|
|
53
53
|
--sendbird-overlay-dark: ${t.overlay.dark};
|
|
54
54
|
--sendbird-overlay-light: ${t.overlay.light};
|
|
55
55
|
}
|
|
56
|
-
`}),
|
|
57
|
-
width: ${({$size:e})=>
|
|
58
|
-
height: ${({$size:e})=>
|
|
56
|
+
`}),Xh=H.css`[${yn}='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);}[${yn}='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);}`,_={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 Ye=e=>{const t=e;return typeof t=="number"?`${t}px`:t},Zh=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"})),Jh=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"})),Qh=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"})),ef=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"})),tf=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"})),nf=new Set(["send","chat","message","chevron-right","good","good-filled","bad","bad-filled"]),rf={close:Zh,send:tf,menu:ef,expand:Qh,collapse:Jh,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")))},sf=e=>({size:t=24,color:n=_.color.primary.main,flipInRtl:r=!1})=>a.createElement(af,{$size:t,$color:n,$rtlFlip:r},a.createElement(Ht,{errorFallback:a.createElement(cf,null)},a.createElement(e,null))),Ki=Object.fromEntries(Object.entries(rf).map(([e,t])=>[e,sf(t)])),of=H.css`[dir='rtl'] &:not([dir='ltr']),&[dir='rtl']{transform:scaleX(-1);}`,af=E.default.span.attrs({"aria-hidden":"true"})`
|
|
57
|
+
width: ${({$size:e})=>Ye(e)};
|
|
58
|
+
height: ${({$size:e})=>Ye(e)};
|
|
59
59
|
display: inline-block;
|
|
60
60
|
|
|
61
61
|
svg {
|
|
@@ -74,25 +74,25 @@
|
|
|
74
74
|
stroke-linejoin: round;
|
|
75
75
|
}
|
|
76
76
|
|
|
77
|
-
${({$rtlFlip:e})=>e&&
|
|
78
|
-
`,
|
|
77
|
+
${({$rtlFlip:e})=>e&&of};
|
|
78
|
+
`,cf=()=>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:lf,useContext:uf}=ve("MessengerIcon",{icons:Ki}),df=({icons:e,children:t})=>{const n=l.useMemo(()=>({icons:Ou(Ki,e)}),[e]);return a.createElement(lf,{value:n},t)},{Provider:mf,useContext:Yi}=ve("MessengerTheme");function hf(e){const{theme:t,appearance:n,logger:r}=e;return a.createElement(vd,{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(ff,{...e}))}function ff({rootElement:e=document.body,children:t}){const{theme:n,updateTheme:r}=Fr();return l.useLayoutEffect(()=>{e.setAttribute(yn,n.selectedTheme)},[e,n.selectedTheme]),a.createElement(H.ThemeProvider,{theme:n},a.createElement(mf,{value:{theme:n,updateTheme:r,rootElement:e}},t))}const gf=(e,t)=>{l.useEffect(()=>{const n=ct(t)instanceof ShadowRoot,r=ct(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])},pf=(e,t=document.body)=>{l.useEffect(()=>{if(!e)return;const n=ct(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])},_f=80,Ef=()=>{const{stringSet:e}=ae(),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},Wi=ve("AriaLiveRegion",{announce:he,announceScreenEntry:he,announceStatus:he,announceError:he,flush:he,setSuppressionState:he}),Cf=Wi.Provider,qr=Wi.useContext,bf={position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},vf=({children:e})=>{const t=l.useRef(null),n=l.useRef(new Set),r=l.useRef(he),s=Ef(),[o]=l.useState(()=>uh(g=>{r.current(g)},{throttleMs:1e3,isSuppressed:()=>n.current.size>0}));r.current=g=>{const C=t.current;C&&(C.textContent="",requestAnimationFrame(()=>{C.textContent=g}))},l.useEffect(()=>()=>{o.destroy()},[o]);const i=o.announce,c=o.flush,u=l.useCallback(g=>{const C=mh(g,s.current);i(C)},[i]),d=l.useCallback((g,C)=>{const v=hh(g,s.current),p=(C==null?void 0:C.mode)??dh(g.event);i(v,{mode:p,dedupeKey:C==null?void 0:C.dedupeKey})},[i]),m=l.useCallback((g,C)=>{const v=fh(g,s.current);o.announceIgnoringSuppression(v),C&&setTimeout(()=>{C.focus()},_f)},[o]),h=l.useCallback((g,C)=>{if(C){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(Cf,{value:f},e,a.createElement("div",{ref:t,role:"status","aria-live":"polite","aria-atomic":"true",style:bf}))},ji=ve("ConversationAnnouncements",{announcementsEnabled:!0,announce:he,announceScreenEntry:he,announceStatus:he,announceError:he,setIsSuppressed:he,setStatusPauseState:he,flush:he}),Sf=ji.Provider,nt=ji.useContext,yf=({children:e,announcementsEnabled:t=!0})=>{const{announce:n,announceScreenEntry:r,announceStatus:s,announceError:o,flush:i,setSuppressionState:c}=qr(),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]),C=l.useCallback((T,R)=>{if(R){d.current.add(T);return}d.current.delete(T),d.current.size===0&&g()},[g]),v=l.useCallback(T=>{t&&n(T)},[n,t]),p=l.useCallback(T=>{t&&r(T)},[r,t]),b=l.useCallback((T,R)=>{if(t){if(d.current.size>0){u.current.push({params:T,options:R});return}s(T,R)}},[s,t]),y=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:v,announceScreenEntry:p,announceStatus:b,announceError:y,setIsSuppressed:h,setStatusPauseState:C,flush:i}),[t,i,v,y,p,b,h,C]);return a.createElement(Sf,{value:A},e)},kn=["a[href]","button:not(:disabled)","input:not(:disabled)","select:not(:disabled)","textarea:not(:disabled)",'[tabindex]:not([tabindex="-1"])'].join(", "),Xi=`${kn}, [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(Hr)&&Tt(n))return n;return null},Zi=e=>{let t=null,n=null;for(const r of e.querySelectorAll(kn))r.hasAttribute(Hr)||Tt(r)&&(t??(t=r),n=r);return t?{first:t,last:n}:null},Ji=(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,Af=(e,t,n)=>Ji(e,t)||n!=null&&t instanceof HTMLElement&&n.contains(t),Kr=e=>Gt(e,Ah),Qi=e=>Kr(e)??Gt(e,kn),Tf=e=>{const t=Kr(e);if(t)return t;const n=e.querySelector(Ih);return(n?Gt(n,Xi):null)??Gt(e,kn)},B=({as:e,variant:t="body1",color:n,maxTextLines:r,className:s,...o})=>a.createElement(Rf,{as:e,$variant:t,className:s,$color:n,$maxTextLines:r,...o}),Zs=new WeakMap,If=(e,t)=>{let n=Zs.get(t);n||(n=new Map,Zs.set(t,n));const r=n.get(e);if(r)return r;const s=t[e]??t.body1,o=H.css`font-size:${Ye(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},xf=e=>e?H.css`display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:${e};overflow:hidden;`:"",Rf=E.default.span`font-stretch:normal;letter-spacing:normal;${({$variant:e,theme:t})=>If(e,t.typography)}color:${({$color:e})=>e};${({$maxTextLines:e})=>xf(e)}`;async function Yr(e){let t=e;t&&(!t.startsWith("http://")&&!t.startsWith("https://")&&(t="https://"+t),window.open(t,"_blank","noopener,noreferrer"))}const gr='[role="dialog"][aria-modal="true"]',Mf=(e,t)=>{const n=new Set(Array.from(e.ownerDocument.querySelectorAll(gr)).filter(s=>s!==e&&(s.contains(e)||e.contains(s)))),r=t==null?void 0:t.closest(gr);return r&&r!==e&&n.add(r),n},wf=(e,t)=>Array.from(e.ownerDocument.querySelectorAll(gr)).some(n=>n!==e&&!t.has(n)&&!n.contains(e)&&Tt(n)),kf=e=>{const t=Qi(e)??e;t===e&&ea(e),t.focus()},ea=e=>{e.hasAttribute("tabindex")||e.setAttribute("tabindex","-1")},Lf=(e,t)=>{const n=Zi(e);if(!n){ea(e),e.focus();return}n[t].focus()},Js=(e,t)=>{const n=e.ownerDocument.createElement("span");return n.tabIndex=0,n.setAttribute(Hr,Th),n.style.cssText=["position: fixed","width: 1px","height: 1px","opacity: 0","overflow: hidden","pointer-events: none"].join(";"),n.addEventListener("focus",()=>Lf(e,t)),n},Of=(e,t)=>{e.key==="Tab"&&(e.defaultPrevented||e.target===t&&(Zi(t)||(e.preventDefault(),t.focus())))},Ln=(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=Mf(i,u);return()=>{u&&Ie(()=>{if(r.current!==o)return;const m=c.activeElement;i.isConnected&&m instanceof HTMLElement&&m!==i&&!i.contains(m)&&!Ji(c,m)&&m.matches(Xi)&&Tt(m)||wf(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,kf(o)};if(n)return Ie(c),()=>{i=!0};const u=setTimeout(()=>Ie(c),Ui);return()=>{i=!0,clearTimeout(u)}},[e,t,n]),l.useEffect(()=>{if(!e||!t.current)return;const o=t.current,i=Js(o,"last"),c=Js(o,"first"),u=d=>Of(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])},lt=({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}=zr();return Ln(n,d),Hh(n,o?r:he),n?oc.createPortal(a.createElement(Nf,{onClick:o?r:void 0,style:e},a.createElement(Df,{ref:d,role:"dialog","aria-modal":"true","aria-label":i,"aria-labelledby":c,"aria-describedby":u,onClick:h=>h.stopPropagation()},s)),m(t)):null},Nf=E.default.div`position:fixed;top:0;left:0;width:100%;height:100%;background:${_.color.overlay.dark};display:flex;justify-content:center;align-items:center;z-index:${ft.MODAL};`,Df=E.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:${ft.MODAL};`,$f=({id:e,children:t})=>a.createElement(Pf,{id:e},t),Pf=E.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;`,Qs=(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?{}:Oi}:n},Ff=()=>{const e=`${l.useId()}-`;return(t,n)=>{if(!t)return{props:{},node:null};const r=e+n,s=l.createElement($f,{id:r,children:t});return{props:{"aria-describedby":r},node:s}}},eo=({name:e,mimeType:t,selected:n},r)=>{var o;const s=Ve(t??"")?r.A11Y_FILE_IMAGE(e):zt(t??"")?r.A11Y_FILE_VIDEO(e):Xo({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},Uf=e=>t=>{t.repeat||(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())},$t=({onActivate:e})=>({role:"button",tabIndex:0,onClick:e,onKeyDown:Uf(e)}),Bf=({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()},to=(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:Bf({disabled:t,currentIndex:n,totalCount:r,onNavigate:o}),tabIndex:i}},oe=()=>{const{stringSet:e}=ae(),t=Ff(),n=(i,c)=>{let u=e.A11Y_HINT_OPEN_FILE,d="of";Ve(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":eo(i,e)});return{launcher:{button:({isOpened:i,opensConversationList:c})=>{const u=Sh({intent:Ch({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:Qs(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,...Rh},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?eo({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 b;const C=c.trim()||c,v=e.A11Y_HINT_SELECT_RATING,p=t(v,`cs${i}`);return{props:{disabled:d,onClick:()=>g(i),...to(u,d,m,h,f,y=>g(y+1)),...p.props,"aria-label":((b=e.A11Y_CSAT_RATING_LABEL)==null?void 0:b.call(e,i,C))??`${i} / ${h} — ${C}`},descriptionNode:p.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:{...to(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:Qs(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,lastMessage:u,time:d,unreadCount:m,onActivate:h})=>{const f=ih({agent:i,status:c,lastMessage:u,time:d,unreadCount:m},e.A11Y_CONVERSATION_ITEM);if(!h)return{props:{"aria-label":f},descriptionNode:null};const g=e.A11Y_HINT_OPEN_CONVERSATION,C=t(g,"cli");return{props:{...$t({onActivate:h}),...C.props,"aria-label":f},descriptionNode:C.node}}}}},Hf=({title:e,description:t,highlightedText:n})=>{const r=Nm(t,n);return a.createElement(zf,null,a.createElement(Vf,null,a.createElement(B,{as:"div",variant:"h1",color:_.themedColor.textHighEmphasis},e),t&&a.createElement(qf,null,a.createElement(B,{as:"div",variant:"body3",color:_.themedColor.textMidEmphasis},r.beforeText,r.highlightedText?a.createElement(Kf,null,r.highlightedText):null,r.afterText))))},Gf=()=>{const{components:e}=On.useContext(),{stringSet:t}=ae(),{messenger:n}=oe(),r=Lm(),s=r.showDescription?Om(r.remainingTime):"",o=r.showDescription?t.CONNECTION_DELAY__DESCRIPTION(s):"";return a.createElement(lt,{portalContainerId:Se.WINDOW,visible:r.visible,onClose:he,...n.connectionDelayDialog().props},a.createElement(e.Dialog,{title:t.CONNECTION_DELAY__TITLE,description:o,highlightedText:s||void 0}))},On=qe({template:Gf,components:{Dialog:Hf}}),zf=E.default.div`width:280px;padding:24px;margin:0 auto;border-radius:4px;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,Vf=E.default.div`display:flex;flex-direction:column;`,qf=E.default.div`margin-top:16px;`,Kf=E.default.strong`font-weight:700;`,Yf=({url:e})=>Yr(e),{Provider:Wf,Consumer:ta,useContext:me}=ve("Messenger");function jf({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}=zr(),f=l.useCallback(()=>{m.setOpened(!1)},[m.setOpened]);Gh(m.opened,f);const g=l.useRef(m.opened);l.useLayoutEffect(()=>{const p=g.current&&!m.opened;if(g.current=m.opened,!p)return;const b=ct(o.rootElement),y=h(Se.WINDOW);let A=!1;return Ie(()=>{var T;A||Af(b,b.activeElement,y)&&((T=h(Se.LAUNCHER))==null||T.focus())}),()=>{A=!0}},[m.opened,o.rootElement,h]);const{Template:C}=On.useContext(),v=l.useMemo(()=>{var p;return{...o.handlers,onClickLink:((p=o.handlers)==null?void 0:p.onClickLink)??Yf}},[o.handlers]);return a.createElement(Hu,{...o},p=>a.createElement(Wf,{value:{...o,...p,state:m,enableCloseConversationButton:n,enableExpandButton:r,enableAutoDisconnectInLauncher:s,handlers:v}},a.createElement(C,null),e))}const na=/iPad|iPhone|iPod/.test(navigator.userAgent),Xf=/Android/.test(navigator.userAgent),jt=e=>na||Xf;let Lt=null,Zn=null;const Zf=(e,t=5e3)=>{Lt&&(clearInterval(Lt),clearTimeout(Zn));const n=document.title;Lt=setInterval(()=>{document.title=document.title===e?n:e},750),Zn=setTimeout(()=>{clearInterval(Lt),Lt=null,Zn=null,document.title=n},t)},ra=()=>{Promise.resolve().then(()=>require("./cjs/B93o4u0P.cjs")).then(e=>{new Audio(e.default).play().catch(()=>{})})},Re=H.css`&:focus-visible{outline:2px solid ${_.themedColor.primary};outline-offset:2px;}`,no=e=>{if(typeof e=="string"||typeof e=="number")return String(e)},Nn=({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??no(t)??no(n),f=u?void 0:t?d:n?m:void 0,g=t&&n?m:void 0,C=()=>{c(),Ie(()=>o==null?void 0:o())},v=()=>{c(),Ie(()=>i==null?void 0:i())};return a.createElement(lt,{portalContainerId:Se.WINDOW,visible:e,onClose:c,"aria-label":h,"aria-labelledby":f,"aria-describedby":g},a.createElement(Jf,null,a.createElement(Qf,null,t&&a.createElement("div",{id:d},a.createElement(B,{variant:"h1",color:_.themedColor.textHighEmphasis},t)),n&&a.createElement(eg,{id:m},a.createElement(B,{variant:"body3",color:_.themedColor.textMidEmphasis},n))),a.createElement(tg,null,s&&a.createElement(ro,{onClick:v},a.createElement(B,{variant:"button",color:_.themedColor.textHighEmphasis},s)),a.createElement(ro,{onClick:C},a.createElement(B,{variant:"button",color:_.themedColor.primary},r)))))},Jf=E.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};`,Qf=E.default.div`margin-bottom:16px;`,eg=E.default.div`margin-top:16px;`,tg=E.default.div`display:flex;flex-direction:row;justify-content:flex-end;`,ro=E.default.button`all:unset;display:flex;justify-content:center;align-items:center;border-radius:4px;cursor:pointer;background-color:transparent;padding:10px 16px;${Re}`,{Provider:ng,useContext:Ne}=ve("MessengerSession"),rg=l.forwardRef(function({children:e,...t},n){return a.createElement(Td,{ref:n,...t},r=>a.createElement(sg,{...r},e))}),sg=({children:e,...t})=>{const{chatSDK:n,logger:r,appId:s,aiAgentId:o,agentPreviewConfigs:i,state:c,handlers:u,dispatcher:d,_aiAgentSDK:m}=me(),{userSessionInfo:h,authenticate:f,userSession:g,aiAgentInfo:C,launcherInfo:v}=t,[p,b]=l.useState(!1),y=l.useRef(null);mt(n,{async onUserJoined(T,R){var k,x,D,F;T.conversation&&T.conversation.type===fe.ConversationType.PROACTIVE&&R.userId===((k=n.currentUser)==null?void 0:k.userId)&&(r.info("messengerSession.onUserJoined: proactive channel joined",T.url),(D=m.session)==null||D._updateActiveChannel({url:T.url,status:"open",conversationStatus:(x=T.conversation)==null?void 0:x.status}),c.setOpened(!0),og({sound:document.hidden||!c.opened}),(F=y.current)==null||F.call(y,{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=()=>b(!0);return d.subscribe(ze.AnonymousSessionTokenExpired,T),()=>d.unsubscribe(ze.AnonymousSessionTokenExpired,T)},[d]);const A=l.useCallback(()=>{t.deauthenticate().finally(()=>window.location.reload())},[t.deauthenticate]);return!g||!C||!v?null:a.createElement(ng,{value:{...t,userSession:g,aiAgentInfo:{...C,...i==null?void 0:i.bot},launcherInfo:{...v,...i==null?void 0:i.launcher},registerOnJoinedProactiveConversation:T=>y.current=T}},e,a.createElement(Nn,{visible:p,title:"Session timed out",description:"Start a new conversation.",onConfirm:A,onClose:he}))};function og({sound:e}){Zf("🔔You have received a new message"),e&&ra()}const An=`@${Ue}-focused-channel`,sa=`${Date.now()}-${Math.random().toString(36).slice(2)}`,ig=()=>{try{const e=localStorage.getItem(An);return e?JSON.parse(e).channelUrl??null:null}catch{return null}},so=e=>{try{localStorage.setItem(An,JSON.stringify({channelUrl:e,tabId:sa}))}catch{}},oo=()=>{try{const e=localStorage.getItem(An);if(!e)return;JSON.parse(e).tabId===sa&&localStorage.removeItem(An)}catch{}},ag=(e,t)=>(l.useEffect(()=>{if(!t||!e)return;const n=()=>so(e),r=()=>oo();return document.hasFocus()&&so(e),window.addEventListener("focus",n),window.addEventListener("blur",r),()=>{window.removeEventListener("focus",n),window.removeEventListener("blur",r),oo()}},[t,e]),{isChannelViewedInAnyTab:()=>document.hasFocus()||ig()===e}),cg=e=>{const{config:t,chatSDK:n}=me(),{sdkUser:r}=Ne(),s=t.conversation.messageAlertSoundEnabled,{isChannelViewedInAnyTab:o}=ag(e,s);mt(n,{onMessageReceived(i,c){if(!s||i.url!==e||o())return;(Xe(c)&&c.sender.userId!==(r==null?void 0:r.userId)||c.isAdminMessage()&&!c.silent)&&ra()}})};function lg(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 ug(e){if("file"in e&&e.file instanceof File&&e.file.type.startsWith("image/")){const{width:t,height:n}=await lg(e.file);return new De.MessageMetaArray({key:Yo,value:[t,n]})}}const dg=({onScrollAfterSendMessage:e})=>{const{agentPreviewConfigs:t,handlers:n}=me(),r=l.useRef(t==null?void 0:t.agentAttributes);return r.current=t==null?void 0:t.agentAttributes,{onBeforeSendMessage:async s=>{const o=await ug(s),i={...s,metaArrays:o?[o]:void 0},c=mg(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===De.SendingStatus.SUCCEEDED?(i=n==null?void 0:n.onCustomEvent)==null||i.call(n,{type:"message-sent-succeeded",data:{message:s}}):s.sendingStatus===De.SendingStatus.PENDING&&((c=n==null?void 0:n.onCustomEvent)==null||c.call(n,{type:"message-sent-pending",data:{message:s}}))}}},mg=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,Jn=St-40,{Provider:hg,useContext:oa}=ve("ConversationScroll"),io={viewport:0,contentHeight:0,contentSnapshotHeight:0,shouldRecalc:!1,shouldUpdate:!1},Qn=e=>Math.max(0,e.scrollHeight-e.scrollTop-e.clientHeight),ao=e=>Array.from(e.querySelectorAll(`#${Ue}-message-item`));function fg({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(io),[u,d]=l.useState(0),[m,h]=l.useState(0),[f,g]=l.useState(!1),[C,v]=l.useState(!1),[p,b]=l.useState(!0),y=$=>{const I=Qn($);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()},[]),R=l.useMemo(()=>f||t==="bottom"?"auto":e,[f,t,e]),N=()=>{c.current.contentSnapshotHeight=c.current.contentHeight,c.current.shouldUpdate=!0,c.current.shouldRecalc=!0},k=()=>{const $=r.current;!$||!c.current.shouldUpdate||d(I=>{c.current.shouldUpdate=!1;const{contentHeight:w,contentSnapshotHeight:O,shouldRecalc:G}=c.current,J=$.clientHeight;if(O>w)return I;const se=x($,{messageType:"outgoing"});let Q=0;if(se){const pe=se.message.offsetTop-Jn+J;Q=Math.max(0,pe-w)}else{const pe=w-O,Ke=J-Jn;Q=Math.max(0,pe-Ke)}return I===0||Q!==I||G?(c.current.shouldRecalc=!1,Q):I})},x=l.useCallback(($,I)=>{const{messageType:w="all"}=I??{},O=ao($);let G=O;w==="outgoing"&&(G=O.filter(ut=>ut.getAttribute("data-layout-id")==="outgoingmessage"));const J=G[G.length-1];if(!J)return null;const se=$.getBoundingClientRect(),Q=J.getBoundingClientRect(),pe=$.scrollTop+(Q.top-se.top),Ke=pe+J.offsetHeight;return{message:J,scrollTop:pe,lastMessageBottom:Ke}},[]),D=l.useCallback(()=>{const $=r.current;if(!$||R!=="fixed")return;const I=x($);c.current.contentHeight=(I==null?void 0:I.lastMessageBottom)??$.scrollHeight,!i.current.streaming&&c.current.contentSnapshotHeight>0&&N(),i.current.programmatic?o.current.distanceFromBottom=Qn($):y($),k()},[R,x]),F=l.useCallback(()=>{T(),A(),c.current=io,d(0),h(0),b(!0),o.current.distanceFromBottom=0,o.current.prevScrollTop=0,i.current.awayByUser=!1,i.current.programmatic=!1},[T]),U=l.useCallback(($=!0)=>{const I=o.current.distanceFromBottom>St;if(i.current.awayByUser=!1,h(0),!I){Ie(()=>{const w=r.current;w&&!i.current.awayByUser&&w.scrollTo({top:w.scrollHeight,behavior:"auto"})});return}i.current.programmatic||(i.current.programmatic=!0,b(!1),A()),Ie(()=>{const w=r.current;if(!w){i.current.programmatic=!1,b(!0);return}if(i.current.awayByUser){i.current.programmatic=!1,y(w),b(!0);return}const O=()=>{if(r.current!==w){i.current.programmatic=!1,r.current&&y(r.current),b(!0);return}i.current.programmatic=!1,y(w),b(!0)};if($&&!i.current.reconcileTimer){const G=setTimeout(O,500);i.current.reconcileTimer=G,w.addEventListener("scrollend",()=>{clearTimeout(G),i.current.reconcileTimer=null,O()},{once:!0})}w.scrollTo({top:w.scrollHeight,behavior:$?"smooth":"auto"}),$||O()})},[]),q=l.useCallback(()=>{const $=r.current;if($){if(i.current.awayByUser){y($);return}U(!1)}},[U]),K=l.useCallback(()=>{const $=r.current,I=s.current;if(!$||!I.resize)return;const w=new Set(ao($));for(const O of I.resizeTargets)w.has(O)||(I.resize.unobserve(O),I.resizeTargets.delete(O));for(const O of w)I.resizeTargets.has(O)||(I.resize.observe(O),I.resizeTargets.add(O))},[]),L=l.useCallback($=>{T();const I=s.current;typeof ResizeObserver<"u"&&(I.resize=new ResizeObserver(q),K());const w=new MutationObserver(()=>{K(),q()});I.mutation=w,w.observe($,{childList:!0})},[T,q,K]),V=l.useCallback($=>{if(!$){r.current=null,T();return}if(r.current=$,R!=="fixed"){L($);return}F(),c.current.viewport=$.clientHeight;const I=new MutationObserver(()=>{D()});s.current.mutation=I,I.observe($,{childList:!0,subtree:!0})},[T,R,D,F,L]),P=l.useCallback(()=>{const $=r.current;if(!$)return;const I=x($,{messageType:"outgoing"});I&&($.scrollTo({top:I.message.offsetTop-Jn,behavior:"smooth"}),i.current.userMessageTimer&&clearTimeout(i.current.userMessageTimer),i.current.userMessageTimer=setTimeout(()=>{v(!1)},500))},[x]),Y=($,I,w)=>{const O=Qn($);if(w&&O>St){i.current.programmatic=!1,i.current.awayByUser=!0,A(),y($),b(!0),o.current.prevScrollTop=I;return}o.current.distanceFromBottom=O},ge=($,I,w)=>{const G=y($)<=St;I&&!G&&(i.current.awayByUser=!0,A()),w&&G&&(i.current.awayByUser=!1)},j=$=>{const{scrollTop:I}=$.currentTarget,w=o.current.prevScrollTop;i.current.programmatic?Y($.currentTarget,I,I<w):ge($.currentTarget,I<w,I>w),o.current.prevScrollTop=I},W=l.useCallback(()=>{R==="fixed"&&(v(!0),N())},[R]),X=l.useCallback(()=>{R==="fixed"?setTimeout(()=>P(),300):U()},[R,P]),M=l.useCallback($=>{i.current.streaming=$,R==="fixed"?N():i.current.awayByUser||U()},[R,U]),Z=l.useCallback($=>{g($),$&&(d(0),R==="fixed"&&T())},[T,R]),ie=l.useCallback($=>{R==="auto"&&$&&!i.current.awayByUser&&U()},[R,U]),$e=!(m<=St)&&!C,Me=l.useCallback(()=>o.current.distanceFromBottom>St,[]);return a.createElement(hg,{value:{ref:V,state:{bottomSpace:u,isAwayFromBottom:$e,isScrollPositionReconciled:p,shouldCountNewMessages:Me},props:{onScroll:j},actions:{scrollToBottom:U,onBeforeMessageSend:W,onAfterMessageSend:X,onStreamingUpdate:M,onConversationClosed:Z,onTypingIndicatorUpdate:ie}}},n)}const{Provider:gg,Context:pg,useContext:Te}=ve("Conversation"),_g=({children:e})=>{var s;const{channelSource:t}=Te(),n=(s=t.channel)==null?void 0:s.url,{checkForUserActionRequired:r}=_m(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)},Eg=({channelUrl:e,onClearChannelUrl:t,onNavigateToConversationList:n,conversationStatsEnabled:r,shouldMarkAsRead:s,shouldInitializeConversation:o,children:i})=>{const{activeChannel:c,refreshActiveChannel:u}=Ne(),d=oa(),m=e||(c==null?void 0:c.url);cg(m);const{onBeforeSendMessage:h,onAfterSendMessage:f}=dg({onScrollAfterSendMessage:()=>{d.actions.onAfterMessageSend()}}),g=l.useCallback(b=>(d.actions.onBeforeMessageSend(),h(b)),[d.actions,h]),C=l.useCallback(b=>{const y=b.some(A=>ke.isStreaming(A));d.actions.onStreamingUpdate(y)},[d.actions.onStreamingUpdate]),v=l.useCallback(b=>{d.actions.onConversationClosed(b===fe.ConversationStatus.CLOSED)},[d.actions.onConversationClosed]),p=l.useCallback(async()=>{await u(),e&&(t==null||t())},[u,e,t]);return a.createElement(Jd,{key:m,channelUrl:m,onBeforeSendMessage:g,onAfterSendMessage:f,onMessagesUpdated:C,onMessagesReceived:C,onChannelDeleted:p,onConversationStatusChanged:v,conversationStatsEnabled:r,shouldMarkAsRead:s,shouldInitializeConversation:o,shouldCountNewMessages:d.state.shouldCountNewMessages},b=>a.createElement(gg,{value:{...b,scrollSource:d,goToActiveConversation:p,onNavigateToConversationList:n}},a.createElement(_g,null,i)))},ia=({children:e,...t})=>{const{config:n}=xe(),{agentPreviewConfigs:r}=me(),s=n.conversation.list.scrollMode,o=r==null?void 0:r.messageStackDirection;return a.createElement(fg,{scrollMode:s,messageStackDirection:o},a.createElement(Eg,{...t},e))},Wr=l.createContext({onDrop:he,subscribe:()=>he}),pr=({children:e})=>{const t=l.useRef(new Set);return a.createElement(Wr.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)},Cg=({onDropFiles:e})=>{const{subscribe:t}=l.useContext(Wr);l.useEffect(()=>t(e),[e])};pr.Consumer=({children:e})=>{const{onDrop:t}=l.useContext(Wr);return e({onDrop:t,onDragOver:s=>s.preventDefault()})};const aa=ve("WindowTitle",{hasWindowTitleReference:!1,isTitlePending:!1,isWindowNameReady:!0,registerWindowTitleReference:()=>he,registerWindowTitlePending:()=>he}),bg=aa.Provider,ca=aa.useContext,co=()=>{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]},jr=({children:e})=>{const[t,n]=co(),[r,s]=co(),o=!r||t,i=l.useMemo(()=>({hasWindowTitleReference:t,isTitlePending:r,isWindowNameReady:o,registerWindowTitleReference:n,registerWindowTitlePending:s}),[t,r,n,s]);return a.createElement(bg,{value:i},e)},Dn=ca,la=({enabled:e,label:t})=>{const{registerWindowTitleReference:n,registerWindowTitlePending:r}=ca(),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?Se.WINDOW_TITLE:void 0}},vg=(e,t)=>{const r=(t?Gt(e,t):null)??Tf(e)??e;r===e&&!e.hasAttribute("tabindex")&&e.setAttribute("tabindex","-1"),r.focus({focusVisible:!1})},ua=(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=Kr(e.current)!=null;if(!s&&!c&&!n)return;let u=!1;const d=()=>{u||i.current||!e.current||(i.current=!0,vg(e.current,s))};if(r)return Ie(d),()=>{u=!0};const m=setTimeout(()=>Ie(d),Ui);return()=>{u=!0,clearTimeout(m)}},[t,n,r,s,e,o])},Sg=(e,t)=>{const{announcementsEnabled:n}=nt(),{channelSource:r}=Te(),{isWindowNameReady:s}=Dn(),o=qi(),i=r.channel!=null||r.error!=null;ua(e,{enabled:n,ready:i,nameReady:s,targetSelector:t==="messageInput"?xh:void 0,suppressed:o})},yg=()=>{var s;const{_statsEnabled:e,channelSource:t}=Te(),n=(s=t.channel)==null?void 0:s.url,r=l.useCallback(o=>{const i=()=>{o(mr()?"backgrounded":"foregrounded")};return document.addEventListener("visibilitychange",i),()=>document.removeEventListener("visibilitychange",i)},[]);Pm({channelUrl:n,enabled:e,isInitiallyBackgrounded:mr,isForegrounded:kh,subscribeToForegroundState:r})},Ag=e=>Ve(e)||zt(e);function Tg(e,t){return e.filter(n=>ke.isWelcomeMessage(n,t))}const da=(e,{previewWelcomeMessages:t,aiAgentUserId:n})=>e.filter(r=>t.length>0?!ke.isWelcomeMessage(r,n):!0),Ig=[],ma=()=>{var C,v,p,b,y,A;const{agentPreviewConfigs:e={},aiAgentId:t}=me(),{aiAgentInfo:n,userSession:r}=Ne(),{channelSource:s,messageSource:o,state:{input:i,streamAnimation:c}}=Te(),u=e.welcomeMessages??Ig,d=l.useMemo(()=>da(o.messages,{previewWelcomeMessages:u,aiAgentUserId:t}),[t,o.messages,u]),m=et(s.channel),h=(v=(C=ti(s.channel,r.userId))==null?void 0:C.nickname)==null?void 0:v.trim(),f=m?(b=(p=s.channel)==null?void 0:p.name)==null?void 0:b.trim():(y=n==null?void 0:n.nickname)==null?void 0:y.trim(),g=h||f||void 0;return{initialized:o.initialized,channelUrl:(A=s.channel)==null?void 0:A.url,agentName:g,isClosed:Fe(s.channel),isHandedOff:m,messages:d,filteredMessagesCount:d.length,hasWelcomeMessages:u.length>0,inputDisabled:i.disabled,inputDisabledBy:i.disabledBy,isStreamAnimating:c.isAnimating,currentUserId:r.userId}},xg=(e={})=>{const{announceScreenEntry:t,announcementsEnabled:n}=nt(),{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])},Rg=()=>{const e=ma();xg(e)},Mg=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}),lo=(e,t,n=ot.format)=>{const r=lh(e,Mg(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}},wg={senderName:!0,body:!0,time:!0},kg=Object.keys(wg),Lg=(e,t)=>kg.every(n=>e[n]===t[n]),uo=2e3,mo=400,_r=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]},ha=e=>{if(!Oe.isAdmin(e)||!Oe.isCSAT(e))return null;const t=_h(e);return t?`csat:${t}`:null},Og=e=>{const t=new Set;for(const n of e){const r=ha(n);r&&t.add(r)}return t},Ng=(e,t)=>{for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r&&_r(r).some(s=>t.includes(s)))return r}},er=(e,t)=>e.some(n=>t.includes(n)),ho=()=>typeof document>"u"?null:document.activeElement instanceof HTMLElement?document.activeElement:null,tr=e=>new Map(e.map(({key:t,sendingStatus:n})=>[t,n])),Dg=()=>{const{announceStatus:e,announcementsEnabled:t}=nt(),{stringSet:n,format:r}=ae(),{channelUrl:s,messages:o,isClosed:i,isHandedOff:c,agentName:u,initialized:d,inputDisabled:m,inputDisabledBy:h,isStreamAnimating:f,currentUserId:g}=ma(),{outgoingMessageStates:C,outgoingMessageStatusSignature:v}=l.useMemo(()=>{if(!g)return{outgoingMessageStates:[],outgoingMessageStatusSignature:""};const j=o.flatMap(W=>{const X=gh(W,g);return!X||!("sendingStatus"in W)?[]:[{key:X,sendingStatus:W.sendingStatus}]});return{outgoingMessageStates:j,outgoingMessageStatusSignature:j.map(({key:W,sendingStatus:X})=>`${W}:${X}`).join(",")}},[g,o]),p=l.useRef({isClosed:!1,isHandedOff:!1,inputDisabled:m,inputDisabledBy:h,outgoingMessageStatuses:tr(C)}),b=l.useRef({messages:o,currentUserId:g,inputDisabledBy:h,isStreamAnimating:f,stringSet:n,format:r}),y=l.useRef([]),A=l.useRef(null),T=l.useRef([]),R=l.useRef(new Set),N=l.useRef(new Set),k=l.useRef(!1),x=l.useRef(s);b.current={messages:o,currentUserId:g,inputDisabledBy:h,isStreamAnimating:f,stringSet:n,format:r};const D=()=>b.current.isStreamAnimating||b.current.inputDisabledBy==="ai_responding",F=()=>{A.current!=null&&(clearTimeout(A.current),A.current=null)},U=(j,W,X)=>{const M=X==null?void 0:X.replaceableForMs;if(j.length===0||!M)return;const Z=Date.now();T.current=[...T.current.filter(({replaceableUntil:ie})=>ie>Z),{eventKeys:j,parts:W,replaceableUntil:Z+M}]},q=()=>y.current.length>0,K=()=>{y.current=[]},L=()=>{const[j,...W]=y.current;if(!j)return!1;y.current=W;const{eventKeys:X,parts:M,dedupeKey:Z}=j,ie=Me=>{U(X,Me,{replaceableForMs:X.length>0?uo:void 0}),e({event:"newMessage",...Me},Z?{dedupeKey:Z}:void 0)};if(X.length===0)return ie(M),!0;const ye=b.current,$e=Ng(ye.messages,X);if($e){const Me=lo($e,ye.stringSet,ye.format);return ie(Me),!0}return ie(M),!0},V=()=>{for(F();L(););},P=(j=uo)=>{F(),A.current=setTimeout(()=>{if(A.current=null,D())return;const W=ho(),[X]=y.current;if(!X)return;if(X.focusTarget!==W){y.current=[{...X,focusTarget:W},...y.current.slice(1)],P(mo);return}L()&&q()&&P(mo)},j)},Y=(j,W,X)=>{const M={eventKeys:W,parts:j,focusTarget:ho(),dedupeKey:X?X.dedupeKey??void 0:W[0]},Z=W.length===0?-1:y.current.findIndex(({eventKeys:ie})=>er(ie,W));Z>=0?y.current=y.current.map((ie,ye)=>ye===Z?{...M,dedupeKey:X?M.dedupeKey:ie.dedupeKey}:ie):y.current=[...y.current,M],P()},ge=(j,W,X)=>{if(j!=="messagesUpdated"||W.length===0)return!1;const M=Date.now(),Z=T.current.find(ie=>ie.replaceableUntil>M&&er(ie.eventKeys,W));return Z?!Lg(X,Z.parts):!1};l.useEffect(()=>{const j=x.current!==s;(!t||!d||j)&&(k.current=!1,N.current.clear(),K(),T.current=[],R.current.clear(),F(),j&&(x.current=s),!t||!d)||k.current||(k.current=!0,x.current=s,p.current={isClosed:i,isHandedOff:c,inputDisabled:m,inputDisabledBy:h,outgoingMessageStatuses:tr(C)},R.current=new Set(o.flatMap(W=>{if(!ke.isStreaming(W))return[];const X="sender"in W?W.sender:void 0;return(X==null?void 0:X.userId)===b.current.currentUserId?[]:_r(W)})),N.current=Og(o))},[e,t,s,d,m,i,c,v]),l.useEffect(()=>{const j=(W,X)=>{const M=b.current,Z=_r(W),ie=ha(W);if(ie!=null){if(N.current.has(ie))return;N.current.add(ie),e({event:"csatDisplayed"});return}if(ke.isStreaming(W)){Z.forEach(G=>{R.current.add(G)});return}const ye=Z.filter(G=>R.current.has(G)),$e=X==="messagesUpdated"&&ye.length>0;$e&&ye.forEach(G=>{R.current.delete(G)});const Me=X==="messagesUpdated"&&y.current.some(({eventKeys:G})=>er(G,Z)),$=lo(W,M.stringSet,M.format),I=ge(X,Z,$);if(!$e&&X!=="messagesAdded"&&!Me&&!I)return;const w=I?{dedupeKey:null}:void 0;if($e||D()||Me){Y($,[...new Set([...ye,...Z])],w);return}if(I){Y($,Z,w);return}q()&&V();const O=Z[0];e({event:"newMessage",...$},O?{dedupeKey:O}:void 0)};return gi.subscribe(W=>{if(!k.current||W.channelUrl!==s||W.kind==="initialized"||W.kind==="messagesDeleted"||!Eh(W.source))return;const X=b.current.currentUserId;for(const M of W.messages)M&&ph(M,X)&&j(M,W.kind)})},[e,s]),l.useEffect(()=>{k.current&&(D()||q()&&P())},[h,f]),l.useEffect(()=>()=>{F()},[]),l.useEffect(()=>{if(!k.current)return;const j=p.current,W=j.outgoingMessageStatuses;j.outgoingMessageStatuses=tr(C),C.some(({key:M,sendingStatus:Z})=>{const ie=W.get(M);return ie!==void 0&&ie!=="failed"&&Z==="failed"})&&e({event:"sendFailed"})},[e,v]),l.useEffect(()=>{if(!k.current)return;const j=p.current;i&&!j.isClosed&&e({event:"conversationClosed"}),j.isClosed=i},[e,i]),l.useEffect(()=>{if(!k.current)return;const j=p.current;c&&!j.isHandedOff&&e({event:"agentConnected",agentName:u}),j.isHandedOff=c},[u,e,c]),l.useEffect(()=>{if(!k.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])},$g=()=>{const{channelSource:e}=Te(),t=Si(e.channel);return!(t!=null&&t.user.userId)||!t.user.nickname?null:{userId:t.user.userId,nickname:t.user.nickname}},Pg=e=>{const{announceStatus:t,announcementsEnabled:n}=nt();vm(e??null,r=>{t({event:"typing",agentName:r})},1e4,n)},Fg=()=>{const e=$g();Pg(e)},ee=({type:e,size:t=24,className:n,color:r})=>{const{icons:s}=uf(),o=s[e];return a.createElement(Ug,{className:n},a.createElement(o,{size:t,color:r??_.color.primary.main,flipInRtl:nf.has(e)}))},Ug=E.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`
|
|
86
|
-
background-color: ${
|
|
85
|
+
`,Bg=({visible:e,onClose:t,children:n,"aria-label":r})=>a.createElement(lt,{portalContainerId:Se.WINDOW,visible:e,onClose:t,"aria-label":r},a.createElement(Vg,null,n)),Hg=({onClick:e,destructive:t,icon:n,initialFocus:r,children:s})=>a.createElement(Gg,{onClick:e,$destructive:t,"data-sb-initial-focus":r?"true":void 0},n&&a.createElement(zg,null,a.createElement(ee,{type:n,size:24,color:_.themedColor.primary})),s),at=Object.assign(Bg,{ActionItem:Hg}),Gg=E.default.button`all:unset;display:flex;align-items:center;gap:24px;width:100%;padding:12px 24px;cursor:pointer;color:${({$destructive:e})=>e?_.themedColor.error:_.themedColor.textHighEmphasis};${Re}`,zg=E.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,Vg=E.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};`,fo=40,go=.9,qg="[data-message-listitem]",Kg='input, textarea, select, [role="textbox"], [contenteditable="true"]',Yg=({event:e,list:t,isMessageAnchor:n})=>{switch(e.key){case"PageDown":return t.clientHeight*go;case"PageUp":return t.clientHeight*-go;case"ArrowDown":return n?fo:void 0;case"ArrowUp":return n?fo*-1:void 0;default:return}},Wg=({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(qg),i=Yg({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]),jg="[data-message-listitem]",Xg=e=>Math.min(Math.max(0,e),1),Zg=e=>{const n=e.getRootNode().activeElement,r=n==null?void 0:n.closest(jg),s=n===e||n===r;return!n||!e.contains(n)?null:s?e:n},Jg=({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})},Qg=({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 b=t.current;b&&(u.current==="top"&&(b.scrollTop=b.scrollHeight-m.current,Jg({list:b,focusRestoreTarget:h.current}),h.current=null),u.current==="bottom"&&(b.scrollTop=d.current),u.current=void 0)},[t,r]);const C=l.useCallback(async b=>{const y=t.current;if(!y||(i==null||i(b),m.current=y.scrollHeight-y.scrollTop,d.current=y.scrollTop,c.current))return;const A=y.clientHeight*Xg(n);if(y.scrollTop<=A){c.current=!0,u.current="top",h.current=Zg(y),await o(),c.current=!1;return}if(y.scrollHeight-y.scrollTop-y.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(b=>{const y=t.current;if(!y)return;const A=g.current;if(A!=null){if(A===y.scrollTop){g.current=null;return}g.current=null}const T=f.current;if(T!=null&&T===y.scrollTop){f.current=null,g.current=y.scrollTop,C(b);return}f.current=null,C(b)},[C,t]),p=l.useCallback(b=>{const y=t.current;y&&(f.current=b,g.current=null,y.scrollTop=b,y.dispatchEvent(new Event("scroll",{bubbles:!0})))},[t]);return l.useLayoutEffect(()=>()=>{f.current=null,g.current=null},[]),{handleScroll:v,syncScrollPosition:p}},ep=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:p=.05,onScroll:b=he,depsForResetScrollPositionToBottom:y,stackDirection:A="top",bottomSpacerHeight:T=0,"aria-label":R}=t,N=l.useRef(null),k=l.useCallback(U=>{N.current=U,n&&(typeof n=="function"?n(U):n.current=U)},[n]),{handleScroll:x,syncScrollPosition:D}=Qg({depsForResetScrollPositionToBottom:y,listRef:N,loadThreshold:p,messagesLength:r.length,onLoadNext:v,onLoadPrev:C,onScroll:b}),F=Wg({listRef:N,syncScrollPosition:D});return c?a.createElement(a.Fragment,null,u):o?a.createElement(a.Fragment,null,i):a.createElement(tp,{id:"infinite-list-container"},a.createElement(np,{id:"infinite-list-inner",ref:k,onScroll:x,onKeyDown:F,role:"list","aria-label":R,tabIndex:0},A==="bottom"&&a.createElement("div",{style:{flexGrow:1}}),h,d?m:r.map((U,q)=>s({message:U,index:q})),f,T>0&&a.createElement("div",{style:{minHeight:T}})),a.createElement(rp,{id:"infinite-list-overlay-container"},a.createElement(sp,{id:"infinite-list-overlay"},g)))}),tp=E.default.div`display:flex;position:relative;flex:1;overflow:hidden;`,np=E.default.div`display:flex;flex:1;flex-direction:column;overflow-x:hidden;overflow-y:auto;overscroll-behavior:contain;scrollbar-color:${_.themedColor.textLowEmphasis}transparent;&::-webkit-scrollbar-thumb:hover{background-color:transparent;}`,rp=E.default.div`position:absolute;top:0;bottom:0;left:0;right:0;pointer-events:none;`,sp=E.default.div`pointer-events:auto;`,rt=({as:e,type:t,size:n=16,color:r,disabled:s,children:o,...i})=>{const c=s?_.themedColor.textDisabled:_.themedColor.textHighEmphasis;return a.createElement(op,{as:e,disabled:s,...i},a.createElement(ee,{type:t,size:n,color:r??c}),o)},op=E.default.button`all:unset;padding:4px;cursor:pointer;display:flex;align-items:center;justify-content:center;${Re}&:disabled{cursor:not-allowed;}`,gt=({className:e,children:t,size:n=26})=>a.createElement(ip,{className:e,$size:n},t??a.createElement(ee,{type:"spinner",size:n})),ip=E.default.div`display:flex;align-items:center;justify-content:center;width:${({$size:e})=>Ye(e)};height:${({$size:e})=>Ye(e)};animation:1s infinite linear;animation-name:rotate;@keyframes rotate{from{transform:rotate(0);}to{transform:rotate(360deg);}}`,ap=({files:e,initialIndex:t=0,onClose:n,visible:r})=>{const[s,o]=l.useState(t),[i,c]=l.useState(!1),{stringSet:u,format:d}=ae(),{config:m}=me(),h=e.length,f=e[s],g=m.conversation.fileViewer.downloadEnabled,C=h>1,v=(f==null?void 0:f.type)||"",p=Ve(v),b=zt(v),y=!Ag(v);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=N=>{N.key==="ArrowLeft"?A():N.key==="ArrowRight"&&T()};return window.addEventListener("keydown",R),()=>window.removeEventListener("keydown",R)},[r,A,T]),!r||!f?null:a.createElement(lt,{onClose:n,visible:r,portalContainerId:Se.MODAL_ROOT,"aria-label":(f==null?void 0:f.name)||u.IMAGE_VIEWER__DEFAULT_TITLE},a.createElement(cp,null,a.createElement(lp,null,a.createElement(up,null,a.createElement(dp,null,a.createElement(B,{variant:"button",maxTextLines:1,color:_.color.ondark.textHighEmphasis},f.name||u.IMAGE_VIEWER__DEFAULT_TITLE),f.timestamp&&a.createElement(B,{variant:"caption2",color:_.color.ondark.textHighEmphasis},d(new Date(f.timestamp),"h:mm a")))),a.createElement(mp,{type:"close",size:18,color:_.color.ondark.textHighEmphasis,"aria-label":u.A11Y_IMAGE_VIEWER_CLOSE,onClick:n})),a.createElement(hp,null,C&&a.createElement(po,{$position:"left",type:"chevron-right",size:22,color:_.color.ondark.textHighEmphasis,onClick:A,"aria-label":u.A11Y_IMAGE_VIEWER_PREVIOUS,disabled:s===0,$flipped:!0}),a.createElement(fp,{onClick:R=>R.currentTarget===R.target&&n()},p&&a.createElement(a.Fragment,null,!i&&a.createElement(gp,null,a.createElement(gt,{size:32},a.createElement(ee,{type:"spinner",color:"textLowEmphasis",size:32}))),a.createElement(pp,{src:f.url,alt:f.name||"Image",$loaded:i,onLoad:()=>c(!0)})),b&&a.createElement(_p,{controls:!0},a.createElement("source",{src:f.url,type:v})),y&&a.createElement(Ep,null,a.createElement(B,{variant:"h1",color:_.themedColor.textHighEmphasis},u.FILE_VIEWER__UNSUPPORT))),C&&a.createElement(po,{$position:"right",type:"chevron-right",size:22,color:_.color.ondark.textHighEmphasis,onClick:T,"aria-label":u.A11Y_IMAGE_VIEWER_NEXT,disabled:s===h-1})),a.createElement(Cp,null,C&&a.createElement(B,{variant:"body2",color:_.color.ondark.textHighEmphasis},s+1,"/",h),g&&!y&&a.createElement(bp,{forwardedAs:"a",href:f.url,download:f.name||"file",type:"download",size:24,color:_.color.ondark.textHighEmphasis,"aria-label":u.A11Y_IMAGE_VIEWER_DOWNLOAD}))))},cp=E.default.div`position:fixed;top:0;left:0;right:0;bottom:0;height:100dvh;outline:none;display:flex;flex-direction:column;background-color:${_.themedColor.bg_50_600};`,lp=E.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:${_.color.overlay.dark};`,up=E.default.div`flex:1;min-width:0;padding-right:8px;`,dp=E.default.div`display:flex;flex-direction:column;gap:2px;`,mp=E.default(rt)`flex-shrink:0;width:28px;height:28px;border-radius:50%;`,$n=E.default.div`display:flex;align-items:center;justify-content:center;`,hp=E.default($n)`flex:1;min-height:0;position:relative;`,fp=E.default($n)`position:relative;width:100%;height:100%;min-width:0;min-height:0;`,gp=E.default($n)`position:absolute;inset:0;pointer-events:none;`,pp=E.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;`,_p=E.default.video`max-width:100%;max-height:100%;object-fit:contain;`,Ep=E.default($n)`flex-direction:column;gap:16px;`,po=E.default(rt)`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:${_.color.overlay.dark};&:disabled{opacity:0.3;}`,Cp=E.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:${_.color.overlay.dark};`,bp=E.default(rt)`position:absolute;right:16px;top:50%;transform:translateY(-50%);padding:0;width:24px;height:24px;`,vp=.75,fa=6,Sp=fa*2;let Er=null;typeof Intl<"u"&&"Segmenter"in Intl&&(Er=new Intl.Segmenter(void 0,{granularity:"grapheme"}));const yp=e=>Er?Array.from(Er.segment(e),t=>t.segment):[...e],Ap=e=>{const t=Math.floor(e.length*vp),n=Math.max(0,e.length-fa);return Math.max(t,n)},_o=(e,t="")=>{if(e.length<Sp)return{start:e+t,end:""};const n=yp(e),r=Ap(n);return{start:n.slice(0,r).join(""),end:n.slice(r).join("")+t}},Tp=e=>{const t=e.normalize("NFC").trim(),n=t.lastIndexOf(".");if(!(n>0&&n<t.length-1))return _o(t);const s=t.slice(0,n),o=t.slice(n);return _o(s,o)},ga=({children:e,...t})=>{const{start:n,end:r}=l.useMemo(()=>Tp(e),[e]);return r?a.createElement(Ip,null,a.createElement(xp,{...t},n),a.createElement(Rp,{...t},r)):a.createElement(B,{...t},n)},Ip=E.default.span`display:flex;width:100%;min-width:0;overflow:hidden;direction:inherit;`,xp=E.default(B)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex-shrink:1;min-width:0;`,Rp=E.default(B)`flex-shrink:0;white-space:nowrap;`,Xr=({name:e,mimeType:t,type:n="FILE",iconColor:r,iconBackgroundColor:s,onClick:o,selected:i})=>{const{colors:c}=H.useTheme(),{conversation:u}=oe(),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(Mp,{...d.props,$clickable:!!o},a.createElement(kp,{$bgColor:s??c.base.primary},a.createElement(ee,{type:"file-document",size:24,color:r??c.base.primaryContrastContent})),a.createElement(Lp,null,a.createElement(ga,{variant:"button",color:_.themedColor.textHighEmphasis},e),a.createElement(B,{color:_.themedColor.textMidEmphasis,variant:"caption3"},n)),d.descriptionNode)},Mp=E.default.div`border:none;border-radius:12px;gap:8px;width:${re.BODY_MAX_WIDTH}px;height:64px;display:flex;align-items:center;padding:12px;box-sizing:border-box;border:1px solid ${_.themedColor.textDisabled};background-color:${_.themedColor.bg_50_600};${({$clickable:e})=>e&&wp}`,wp=H.css`cursor:pointer;${Re}&:hover{background-color:${_.themedColor.bg_100_500};}`,kp=E.default.div`border-radius:8px;width:40px;height:40px;display:flex;align-items:center;justify-content:center;background-color:${({$bgColor:e})=>e};`,Lp=E.default.div`display:flex;flex:1;flex-direction:column;gap:4px;min-width:0;`;function Op({file:e,children:t,onClickFile:n}){const r=n?()=>n(e):void 0;return a.createElement(Np,null,a.createElement(Xr,{name:e.name,mimeType:e.type,type:Tr(e.name,e.type),onClick:r}),t)}const Np=E.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${re.GAP_GROUPED}px;`,Je=`${Ue}-incoming-msg`,Dp=`${Ue}-marked-text`;function $p({file:e,onClickMedia:t,onClickMediaFiles:n,children:r}){const{conversation:s}=oe(),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(Up,{src:e.url,alt:"image-message"}):e.type.startsWith("video")?a.createElement(Bp,{controls:!0},a.createElement("source",{src:e.url}),a.createElement("track",{kind:"captions"})):null;if(u){const d={id:`${Je}-media-body`,...c.props};return a.createElement(Pp,null,a.createElement(Fp,{...d},u(),c.descriptionNode),r)}return null}const Pp=E.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${re.GAP_GROUPED}px;`,Fp=E.default.div`width:${re.BODY_MAX_WIDTH}px;height:160px;border-radius:12px;overflow:hidden;cursor:pointer;${te.light`
|
|
86
|
+
background-color: ${_.color.background100};
|
|
87
87
|
`}
|
|
88
|
-
${
|
|
89
|
-
background-color: ${
|
|
88
|
+
${te.dark`
|
|
89
|
+
background-color: ${_.color.background400};
|
|
90
90
|
`}
|
|
91
|
-
`,
|
|
92
|
-
background-color: ${
|
|
91
|
+
`,Up=E.default.img`width:100%;height:100%;object-fit:cover;`,Bp=E.default.video`width:100%;height:100%;object-fit:cover;`,pa=({images:e,isPending:t=!1,onClickImage:n})=>{const{conversation:r}=oe(),s=e.length;if(s===0)return null;const o=Fu(s),i=!!n&&!t;return a.createElement(Gp,{$width:re.BODY_MAX_WIDTH,$columns:o},e.map((c,u)=>{const{columnSpan:d}=Uu({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(zp,{key:c.url,$clickable:i,$itemSpan:d,$isPending:t,...g.props},a.createElement(Hp,{src:c.url,alt:c.name||""}),t&&a.createElement(Vp,null),g.descriptionNode)}))},Hp=({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(qp,null,a.createElement(gt,{size:20},a.createElement(ee,{type:"spinner",color:"textLowEmphasis",size:20}))),s&&a.createElement(Kp,null,a.createElement(ee,{type:"photo",color:"textLowEmphasis",size:24})),!s&&a.createElement(Yp,{src:e,alt:t,$loaded:n,onLoad:()=>r(!0),onError:()=>o(!0)}))},Gp=E.default.div`display:grid;grid-template-columns:repeat(${({$columns:e})=>e},1fr);width:${({$width:e})=>e}px;gap:2px;border-radius:16px;overflow:hidden;`,zp=E.default.div`position:relative;width:100%;aspect-ratio:1;overflow:hidden;cursor:${e=>e.$clickable?"pointer":"default"};${te.light`
|
|
92
|
+
background-color: ${_.color.background100};
|
|
93
93
|
`}
|
|
94
|
-
${
|
|
95
|
-
background-color: ${
|
|
94
|
+
${te.dark`
|
|
95
|
+
background-color: ${_.color.background400};
|
|
96
96
|
`}
|
|
97
97
|
${e=>e.$itemSpan&&e.$itemSpan>1&&`
|
|
98
98
|
grid-column: span ${e.$itemSpan};
|
|
@@ -100,7 +100,7 @@
|
|
|
100
100
|
`}
|
|
101
101
|
|
|
102
102
|
&:focus-visible {
|
|
103
|
-
outline: 2px solid ${
|
|
103
|
+
outline: 2px solid ${_.color.primary.main};
|
|
104
104
|
outline-offset: -2px;
|
|
105
105
|
}
|
|
106
106
|
|
|
@@ -111,19 +111,19 @@
|
|
|
111
111
|
}
|
|
112
112
|
`}
|
|
113
113
|
}
|
|
114
|
-
`,
|
|
115
|
-
background-color: ${
|
|
114
|
+
`,Vp=E.default.div`position:absolute;top:0;left:0;width:100%;height:100%;background-color:${_.color.overlay.dark};pointer-events:none;`,_a=E.default.div`display:flex;align-items:center;justify-content:center;`,qp=E.default(_a)`position:absolute;inset:0;`,Kp=E.default(_a)`position:absolute;inset:0;${te.light`
|
|
115
|
+
background-color: ${_.color.background200};
|
|
116
116
|
`}
|
|
117
|
-
${
|
|
118
|
-
background-color: ${
|
|
117
|
+
${te.dark`
|
|
118
|
+
background-color: ${_.color.background500};
|
|
119
119
|
`}
|
|
120
|
-
`,
|
|
120
|
+
`,Yp=E.default.img`position:absolute;inset:0;width:100%;height:100%;object-fit:cover;opacity:${({$loaded:e})=>e?1:0};transition:opacity 0.3s ease;`,Wp=({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(jp,null,a.createElement(pa,{images:e,onClickImage:s}),t)},jp=E.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${re.GAP_GROUPED}px;`,Xp="✱",Ea=e=>{const t=new RegExp(`(\`+)([^\`]+?)\\1|(${Xp}+)`,"g");return e.replace(t,(n,r,s,o)=>r?n:o?`<span id=${Dp} aria-label="masked-text">${o}</span>`:n)},Zp=e=>e.replace(/\*\*(.*?)\*\*/g,"<b>$1</b>"),Eo=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)}}},Jp=l.lazy(async()=>({default:(await Promise.resolve().then(()=>require("./cjs/VvejebHE.cjs"))).MarkdownText})),Co=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 Qp(e){var s,o;const t=e.maxBodyWidth??re.BODY_MAX_WIDTH,n=l.useMemo(()=>Sc(e.message,Ea),[e.message]),r={id:`${Je}-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(bo,{...r},e.children):null:a.createElement(bo,{...r},n.map((i,c)=>i.type==="text"?a.createElement(vo,{key:c,variant:"body3"},a.createElement(Ht,{fallback:i.value},a.createElement(Jp,{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"?Co?a.createElement(Ht,{key:c,fallback:a.createElement(vo,{variant:"body3"},i.value)},a.createElement(Co,{code:i.value,language:i.language})):a.createElement(e_,{key:c},a.createElement("code",null,i.value)):null),e.children)}const bo=E.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})=>H.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
|
-
`,
|
|
126
|
+
`,vo=E.default(B)`align-items:flex-start;line-height:140%;white-space:pre-wrap;padding:0 12px;`,e_=E.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 Ca({id:e,src:t,size:n=56,onClick:r,onImageError:s,style:o,...i}){const[c,u]=l.useState();return a.createElement(t_,{id:e,tabIndex:r?0:void 0,onClick:r,$size:Ye(n),style:o,...i},t&&t!==c?a.createElement(n_,{src:t,alt:"",onError:()=>{u(t),s==null||s(t)}}):a.createElement(ee,{type:"user",size:n}))}const t_=E.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:${_.themedColor.bg_100_500};&:focus{outline:none;}${Re}`,n_=E.default.img`object-fit:cover;width:100%;height:100%;position:absolute;`,r_=({sender:e,isBotMessage:t})=>{const n=`${Je}-sender-avatar`,[r,s]=l.useState();return t&&(!e.profileUrl||e.profileUrl===r)?a.createElement(s_,{id:n},a.createElement(ee,{type:"delight",size:"100%"})):a.createElement(Ca,{id:n,size:re.AVATAR_SIZE,src:e.profileUrl,onImageError:t?s:void 0})},s_=E.default.div`flex-shrink:0;width:${re.AVATAR_SIZE}px;height:${re.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;}}`,o_=({sender:e})=>a.createElement(i_,{id:`${Je}-sender-name`,variant:"caption1",color:_.themedColor.textMidEmphasis},e.nickname),i_=E.default(B)`text-align:start;width:100%;box-sizing:border-box;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding-block:5px;padding-inline:0 7px;`,a_=({createdAt:e})=>{const{stringSet:t,format:n}=ae();return e?a.createElement(B,{id:`${Je}-sent-time`,variant:"caption4",color:_.themedColor.textLowEmphasis},n(e,t.DATE_FORMAT__MESSAGE_TIMESTAMP)):null},ba="(prefers-reduced-motion: reduce)",c_=()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(ba).matches,va=()=>{const[e,t]=l.useState(c_);return l.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const n=window.matchMedia(ba);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},l_=({thinkingMessage:e,customStyle:t})=>{const n=va();return e?a.createElement(m_,{$prefersReducedMotion:n},a.createElement(h_,null,e),!n&&a.createElement(f_,null)):a.createElement(u_,{$bgColor:t==null?void 0:t.bubbleBackgroundColor},[0,1,2].map(r=>a.createElement(d_,{key:r,$color:t==null?void 0:t.bubbleContentColor,$prefersReducedMotion:n})))},u_=E.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};`,d_=E.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;}`,m_=E.default.div.attrs({id:`${Je}-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
|
-
`,
|
|
138
|
+
`,h_=E.default(B).attrs({variant:"body3"})`
|
|
139
139
|
white-space: pre-wrap;
|
|
140
140
|
word-break: break-word;
|
|
141
|
-
color: ${
|
|
142
|
-
`,
|
|
143
|
-
`,
|
|
141
|
+
color: ${_.themedColor.textHighEmphasis};
|
|
142
|
+
`,f_=E.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=Ss(e.colors.base.background,.5),n=Ss(e.colors.base.background,0);return`linear-gradient(90deg, ${n} 0%, ${t} 30%, ${t} 60%, ${n} 100%)`}};
|
|
143
|
+
`,g_=({extendedMessagePayload:e,onClickCTA:t=({url:n})=>Yr(n)})=>{const n=e==null?void 0:e.cta_button;if(!n)return null;const r=()=>t(n);return a.createElement(p_,{id:`${Je}-ext-cta-button`,onClick:r},a.createElement(__,{variant:"button"},n.label))},p_=E.default.button.attrs({type:"button"})`
|
|
144
144
|
all: unset;
|
|
145
145
|
display: flex;
|
|
146
146
|
width: 100%;
|
|
@@ -150,14 +150,14 @@
|
|
|
150
150
|
cursor: pointer;
|
|
151
151
|
border-radius: 6px;
|
|
152
152
|
padding: 8px;
|
|
153
|
-
color: ${
|
|
154
|
-
background-color: ${
|
|
155
|
-
${
|
|
156
|
-
background-color: ${
|
|
153
|
+
color: ${_.themedColor.textHighEmphasis};
|
|
154
|
+
background-color: ${_.color.background50};
|
|
155
|
+
${te.dark`
|
|
156
|
+
background-color: ${_.color.ondark.textDisabled};
|
|
157
157
|
`}
|
|
158
158
|
|
|
159
|
-
${
|
|
160
|
-
`,
|
|
159
|
+
${Re}
|
|
160
|
+
`,__=E.default(B)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,E_=e=>a.createElement(a.Fragment,null),C_=({extendedMessagePayload:e,onClickCitation:t=n=>Yr(n.link)})=>{const{stringSet:n}=ae(),{theme:r}=Fr(),s=e==null?void 0:e.citations;return!s||s.length===0?null:a.createElement(b_,{id:`${Je}-ext-citation`},a.createElement(v_,{variant:"caption1",color:r.colors.messageIncoming.text},n.CITATION_SOURCE_TITLE),a.createElement(S_,null,s.map((o,i)=>a.createElement(A_,{key:`${o.embedding_id}-${i}`,onClick:()=>t(o)},a.createElement(ee,{type:"source",size:16,color:r.colors.messageIncoming.text}),a.createElement(y_,{variant:"body3",color:r.colors.messageIncoming.text},o.title)))))},b_=E.default.div`display:flex;flex-direction:column;gap:8px;border-radius:8px;padding:8px 12px 6px;`,v_=E.default(B)`opacity:0.5;`,S_=E.default.div`display:flex;flex-direction:column;gap:8px;`,y_=E.default(B)`text-decoration:underline;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,A_=E.default.button.attrs({type:"button"})`
|
|
161
161
|
background: none;
|
|
162
162
|
border: none;
|
|
163
163
|
padding: 0;
|
|
@@ -172,127 +172,127 @@
|
|
|
172
172
|
&:hover {
|
|
173
173
|
opacity: 0.5;
|
|
174
174
|
}
|
|
175
|
-
`,
|
|
176
|
-
color: ${
|
|
177
|
-
border-color: ${
|
|
175
|
+
`,T_=e=>a.createElement(a.Fragment,null),Cr=e=>`${e}-filled`,I_=e=>e==="good"?fe.AIAgentMessageFeedbackRating.GOOD:fe.AIAgentMessageFeedbackRating.BAD,Zr=H.css`&:hover{opacity:0.8;}&:active{opacity:0.6;}`,an={good:{onlight:_.color.secondary.dark,ondark:_.color.secondary.light},bad:{onlight:_.color.error.dark,ondark:_.color.error.light}},x_={good:_.themedColor.secondary,bad:_.themedColor.error},Sa=e=>H.css`color:${an[e].onlight};border-color:${an[e].onlight};${te.dark`
|
|
176
|
+
color: ${an[e].ondark};
|
|
177
|
+
border-color: ${an[e].ondark};
|
|
178
178
|
`}
|
|
179
|
-
`,
|
|
180
|
-
outline: 2px solid ${
|
|
179
|
+
`,R_=({visible:e,onClose:t,isEdit:n,initialRating:r,initialComment:s="",onSubmit:o,isCommentEnabled:i=!1})=>{const{stringSet:c}=ae(),{conversation:u}=oe(),{rootElement:d}=Yi(),m=ct(d),[h,f]=l.useState(r),[g,C]=l.useState(s),[v,p]=l.useState(!1),b=l.useRef(!1),y=h??r??"good",A=u.feedback;l.useLayoutEffect(()=>{e?(f(r),C(s)):(f(void 0),C(""))},[e,r,s]),l.useEffect(()=>{if(!e)return;const k=D=>{const F=D;F.metaKey||F.altKey||F.ctrlKey||(b.current=!0)},x=()=>{b.current=!1,p(!1)};return m.addEventListener("keydown",k),m.addEventListener("pointerdown",x),()=>{m.removeEventListener("keydown",k),m.removeEventListener("pointerdown",x)}},[m,e]);const T=()=>{h&&(o({rating:h,comment:g.trim()||void 0}),t())},R=()=>{t()};if(!e)return null;const N={feedback:A.container()};return a.createElement(lt,{portalContainerId:Se.WINDOW,visible:e,onClose:R,"aria-label":c.FEEDBACK_TITLE},a.createElement(M_,null,a.createElement(w_,null,a.createElement(B,{variant:"h2",color:_.themedColor.textHighEmphasis},c.FEEDBACK_TITLE)),a.createElement(k_,null,a.createElement(L_,{...N.feedback.props},["good","bad"].map(k=>{const x=h===k,D=k==="good"?c.FEEDBACK_GOOD:c.FEEDBACK_BAD,F=A.button(k,x);return a.createElement(l.Fragment,{key:k},a.createElement(O_,{type:"button",$selected:x,$rating:k,...F.props,onClick:()=>f(k),"data-sb-initial-focus":k===y?"true":void 0},a.createElement(ee,{type:x?Cr(k):k,size:24,color:"currentColor"}),a.createElement(B,{variant:"caption1",color:"currentColor"},D)),F.descriptionNode)}),N.feedback.descriptionNode),i&&a.createElement(N_,null,a.createElement(B,{variant:"caption3",color:_.themedColor.textHighEmphasis},c.FEEDBACK_COMMENT_LABEL),a.createElement(D_,{placeholder:c.FEEDBACK_COMMENT_PLACEHOLDER,value:g,onChange:k=>C(k.target.value),onFocus:()=>p(b.current),onBlur:()=>p(!1),maxLength:100,$focusVisible:v,"data-focus-visible":v?"true":"false"}))),a.createElement($_,null,a.createElement(P_,{onClick:R},a.createElement(B,{variant:"button",color:_.themedColor.textHighEmphasis},c.FEEDBACK_CANCEL)),a.createElement(F_,{onClick:T,disabled:!h},a.createElement(B,{variant:"button"},n?c.FEEDBACK_SAVE:c.FEEDBACK_SUBMIT)))))},M_=E.default.div`width:280px;background-color:${({theme:e})=>e.colors.base.modalContentBackground};border-radius:12px;overflow:hidden;`,w_=E.default.div`padding:24px;`,k_=E.default.div`padding-inline:24px;display:flex;flex-direction:column;gap:24px;`,L_=E.default.div`display:flex;gap:4px;`,O_=E.default.button`width:114px;height:64px;border-radius:12px;border:1px solid ${_.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:${_.themedColor.textLowEmphasis};background-color:transparent;${({$selected:e,$rating:t})=>e&&Sa(t)}${Zr}`,N_=E.default.label`display:flex;flex-direction:column;gap:6px;`,D_=E.default.textarea`font-family:inherit;font-size:12px;line-height:16px;border:1px solid ${_.themedColor.textDisabled};border-radius:4px;padding:6px 12px;color:${_.themedColor.textHighEmphasis};background-color:${_.themedColor.textLowEmphasisInverse};resize:none;field-sizing:content;min-height:28px;max-height:118px;overflow-y:auto;&::placeholder{color:${_.themedColor.textLowEmphasis};}&:focus{outline:none;}${({$focusVisible:e})=>e&&H.css`
|
|
180
|
+
outline: 2px solid ${_.themedColor.primary};
|
|
181
181
|
outline-offset: 2px;
|
|
182
182
|
`}
|
|
183
|
-
|
|
184
|
-
border: 1px solid ${
|
|
183
|
+
`,$_=E.default.div`padding-inline:24px;padding-block:16px;display:flex;justify-content:flex-end;gap:4px;`,ya=E.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;`,P_=E.default(ya)`background-color:transparent;${Zr}`,F_=E.default(ya)`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};}`,U_=({isBotMessage:e,isConversationClosed:t,isStreaming:n,isFeedbackEnabled:r,isFeedbackCommentEnabled:s,extendedMessagePayload:o,onFeedbackUpdate:i})=>{const{stringSet:c}=ae(),{conversation:u}=oe(),[d,m]=l.useState(!1),[h,f]=l.useState(!1),[g,C]=l.useState(void 0),[v,p]=l.useState(""),b=l.useRef(null),y=l.useRef(null),A=l.useRef(null),T=l.useRef(!1),R=u.feedback,N=o==null?void 0:o.feedback,k=(N==null?void 0:N.rating)??"none";if(k!=="none"?!1:!!(n||!e||!r||(o==null?void 0:o.bot_message_type)!=="generated"||t))return null;const D=P=>{P&&Ie(()=>{const Y=P==="good"?b.current:y.current;Y==null||Y.focus()})},F=({restoreTrigger:P=!0}={})=>{f(!1),P&&D(A.current)},U=P=>{k==="none"?(C(P),p(""),m(!0)):(A.current=P,f(!0))},q=()=>{i==null||i(null),F()},K=()=>{T.current=!0,F({restoreTrigger:!1}),C(N==null?void 0:N.rating),p((N==null?void 0:N.comment)??""),m(!0)},L=P=>{T.current=!1,i==null||i(P),m(!1),D(A.current)},V=()=>{m(!1),T.current&&(T.current=!1,f(!0))};return t&&k!=="none"?a.createElement(So,{role:"presentation",$horizontal:!0},a.createElement(B_,null,a.createElement(ee,{type:Cr(k),size:12,color:x_[k]})),(N==null?void 0:N.comment)&&a.createElement(yo,{variant:"caption2",style:{lineHeight:"16px"}},N.comment)):a.createElement(a.Fragment,null,a.createElement(So,{role:"presentation"},a.createElement(H_,{role:"presentation"},["good","bad"].map(P=>{const Y=k===P,ge=R.button(P,Y);return a.createElement(l.Fragment,{key:P},a.createElement(G_,{$selected:Y,$rating:P,ref:P==="good"?b:y,...ge.props,onClick:()=>U(P)},a.createElement(ee,{type:Y?Cr(P):P,size:14,color:"currentColor"})),ge.descriptionNode)})),k!=="none"&&(N==null?void 0:N.comment)&&a.createElement(yo,{variant:"caption2"},N.comment)),a.createElement(at,{visible:h,onClose:F,...R.optionsBottomSheet().props},a.createElement(at.ActionItem,{onClick:K,initialFocus:!0},c.FEEDBACK_EDIT),a.createElement(at.ActionItem,{onClick:q,destructive:!0},c.FEEDBACK_REMOVE)),a.createElement(R_,{visible:d,onClose:V,isEdit:k!=="none",initialRating:g,initialComment:v,onSubmit:L,isCommentEnabled:s}))},So=E.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:${re.BODY_MAX_WIDTH}px;`,B_=E.default.div`padding:2px;flex-shrink:0;display:flex;align-items:center;`,H_=E.default.div`display:flex;gap:2px;`,G_=E.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:${_.themedColor.textMidEmphasis};border:1px solid ${_.color.background200};background-color:transparent;${te.dark`
|
|
184
|
+
border: 1px solid ${_.color.background400};
|
|
185
185
|
`}
|
|
186
186
|
|
|
187
|
-
${({$selected:e,$rating:t})=>e&&
|
|
187
|
+
${({$selected:e,$rating:t})=>e&&Sa(t)}
|
|
188
188
|
|
|
189
|
-
${
|
|
190
|
-
`,
|
|
191
|
-
color: ${
|
|
189
|
+
${Zr}
|
|
190
|
+
`,yo=E.default(B)`color:${_.themedColor.textMidEmphasis};${te.dark`
|
|
191
|
+
color: ${_.themedColor.textHighEmphasis};
|
|
192
192
|
`}
|
|
193
|
-
`,
|
|
194
|
-
background-color: ${
|
|
193
|
+
`,Jr=H.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;${Re}&:disabled{cursor:not-allowed;}`,Ao=E.default.button`${Jr};background-color:${_.themedColor.primary};color:${_.themedColor.textHighEmphasis};&:hover:not(:disabled){opacity:0.9;}`,z_=E.default.button`${Jr};color:${_.themedColor.primary};${te.light`
|
|
194
|
+
background-color: ${_.color.background50};
|
|
195
195
|
`};
|
|
196
|
-
${
|
|
197
|
-
background-color: ${
|
|
196
|
+
${te.dark`
|
|
197
|
+
background-color: ${_.color.background700};
|
|
198
198
|
`};
|
|
199
199
|
|
|
200
200
|
&:hover:not(:disabled) {
|
|
201
201
|
opacity: 0.9;
|
|
202
202
|
}
|
|
203
|
-
`,
|
|
204
|
-
background-color: ${
|
|
203
|
+
`,V_=E.default.button`${Jr};background-color:transparent;color:${_.themedColor.textHighEmphasis};&:hover:not(:disabled){opacity:0.7;}`,q_=e=>{switch(e){case"primary":return Ao;case"secondary":return z_;case"clear":return V_;default:return Ao}},K_=E.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);}}`,Y_=({children:e,onClick:t,variant:n="primary",disabled:r=!1,loading:s=!1,className:o,...i})=>{const c=()=>{switch(n){case"primary":return _.themedColor.textHighEmphasisInverse;case"secondary":return _.themedColor.primary;case"clear":return _.themedColor.textHighEmphasis;default:return _.themedColor.textHighEmphasisInverse}},u=q_(n);return a.createElement(u,{onClick:t,disabled:r||s,className:o,...i},s?a.createElement(K_,null,a.createElement(ee,{type:"spinner",size:22,color:c()})):a.createElement(B,{variant:"button",color:c()},e))},W_=({children:e,className:t,style:n,id:r,role:s})=>a.createElement(B,{variant:"caption4",color:_.themedColor.error,className:t,style:n,id:r,role:s},e),j_=({id:e,children:t,className:n,style:r,required:s,"aria-hidden":o})=>{const{stringSet:i}=ae();return a.createElement(B,{id:e,variant:"caption3",color:_.themedColor.textMidEmphasis,className:n,style:r,"aria-hidden":o},t,!s&&a.createElement("span",{style:{color:_.themedColor.textLowEmphasis}},` (${i.OPTIONAL})`))},X_=({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,""),C=g.split("."),p=C.length>1?C[0]+"."+C.slice(1).join("").replace(/\./g,""):g;if(h.target.value=p,p===""||p==="-")t==null||t(null);else{const b=Number(p);if(!isNaN(b)){if(c!==void 0&&b>c)return;t==null||t(b)}}},m=e==null?"":String(e);return a.createElement(tE,{type:"text",value:m,onChange:d,placeholder:n,className:o,disabled:i||s,inputMode:"decimal",$error:r,$submitted:s,...u})},Z_=H.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;${Re}&::placeholder{color:${_.themedColor.textLowEmphasis};}&::-webkit-inner-spin-button,&::-webkit-outer-spin-button{-webkit-appearance:none;margin:0;}`,J_=H.css`color:${_.themedColor.textHighEmphasis};border:1px solid transparent;cursor:not-allowed;${te.light`
|
|
204
|
+
background-color: ${_.color.ondark.textMidEmphasis};
|
|
205
205
|
`}
|
|
206
|
-
${
|
|
207
|
-
background-color: ${
|
|
206
|
+
${te.dark`
|
|
207
|
+
background-color: ${_.color.onlight.textLowEmphasis};
|
|
208
208
|
`}
|
|
209
209
|
|
|
210
210
|
&::placeholder {
|
|
211
|
-
color: ${
|
|
211
|
+
color: ${_.themedColor.textLowEmphasis};
|
|
212
212
|
}
|
|
213
|
-
`,
|
|
214
|
-
background-color: ${
|
|
213
|
+
`,Q_=H.css`border:1px solid ${_.themedColor.error};color:${_.themedColor.textHighEmphasis};${te.light`
|
|
214
|
+
background-color: ${_.color.background50};
|
|
215
215
|
`}
|
|
216
|
-
${
|
|
217
|
-
background-color: ${
|
|
216
|
+
${te.dark`
|
|
217
|
+
background-color: ${_.color.onlight.textLowEmphasis};
|
|
218
218
|
`}
|
|
219
|
-
`,
|
|
220
|
-
background-color: ${
|
|
219
|
+
`,eE=H.css`border:1px solid ${_.themedColor.textDisabled};color:${_.themedColor.textHighEmphasis};${te.light`
|
|
220
|
+
background-color: ${_.color.background50};
|
|
221
221
|
`}
|
|
222
|
-
${
|
|
223
|
-
background-color: ${
|
|
222
|
+
${te.dark`
|
|
223
|
+
background-color: ${_.color.onlight.textLowEmphasis};
|
|
224
224
|
`}
|
|
225
225
|
|
|
226
226
|
&:focus {
|
|
227
|
-
border-color: ${
|
|
227
|
+
border-color: ${_.themedColor.primary};
|
|
228
228
|
}
|
|
229
|
-
`,
|
|
229
|
+
`,tE=E.default.input`${Z_}${({$error:e,$submitted:t})=>t?J_:e?Q_:eE}`,nE=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))}}}},Aa=e=>{const{options:t,submitted:n=!1,error:r=!1,className:s,groupLabel:o}=e,{conversation:i}=oe(),c=e.multiple===!0,{selectedValues:u,handleOptionClick:d}=nE(e),m=t.some(h=>u.includes(h.value));return a.createElement(sE,{className:s,...c?void 0:i.form.singleSelectGroup(o).props},t.map((h,f)=>{const g=u.includes(h.value),C=o?`${o}, ${h.label}`:h.label;return a.createElement(dE,{key:h.value,type:"button",$active:g,$submitted:n,$error:r,...(c?i.form.multiSelectOption(C,g,n):i.form.singleSelectOption(C,g,n,f,t.length,m,v=>{const p=t[v];p&&d(p.value)})).props,disabled:n,onClick:()=>d(h.value)},a.createElement(B,{variant:"caption1",color:rE(g,n)},h.label))}))},rE=(e,t)=>t?e?_.themedColor.textHighEmphasis:_.themedColor.textDisabled:e?_.themedColor.primary:_.themedColor.textMidEmphasis,sE=E.default.div`display:flex;flex-wrap:wrap;gap:4px 2px;`,oE=H.css`display:inline-flex;align-items:center;padding:8px 12px;border-radius:15px;transition:all 0.2s ease;`,iE=H.css`cursor:default;background-color:${_.color.ondark.textMidEmphasis};color:${_.themedColor.textHighEmphasis};${te.dark`
|
|
230
230
|
background-color: transparent;
|
|
231
231
|
border: 1px solid white;
|
|
232
232
|
color: white;
|
|
233
233
|
`}
|
|
234
|
-
`,
|
|
235
|
-
background-color: ${
|
|
236
|
-
color: ${
|
|
234
|
+
`,aE=H.css`cursor:default;${te.light`
|
|
235
|
+
background-color: ${_.color.ondark.textMidEmphasis};
|
|
236
|
+
color: ${_.themedColor.textDisabled};
|
|
237
237
|
`}
|
|
238
|
-
${
|
|
239
|
-
background-color: ${
|
|
240
|
-
border: 1px solid ${
|
|
241
|
-
color: ${
|
|
238
|
+
${te.dark`
|
|
239
|
+
background-color: ${_.color.onlight.textLowEmphasis};
|
|
240
|
+
border: 1px solid ${_.color.onlight.textLowEmphasis};
|
|
241
|
+
color: ${_.themedColor.textDisabled};
|
|
242
242
|
`}
|
|
243
|
-
`,
|
|
244
|
-
background-color: ${
|
|
245
|
-
color: ${
|
|
243
|
+
`,cE=H.css`cursor:pointer;border:1px solid ${_.themedColor.primary};${te.light`
|
|
244
|
+
background-color: ${_.color.background50};
|
|
245
|
+
color: ${_.themedColor.primary};
|
|
246
246
|
`}
|
|
247
|
-
${
|
|
248
|
-
background-color: ${
|
|
249
|
-
color: ${
|
|
247
|
+
${te.dark`
|
|
248
|
+
background-color: ${_.color.onlight.textLowEmphasis};
|
|
249
|
+
color: ${_.themedColor.primary};
|
|
250
250
|
`}
|
|
251
|
-
`,
|
|
252
|
-
background-color: ${
|
|
253
|
-
color: ${
|
|
251
|
+
`,lE=H.css`cursor:pointer;border:1px solid ${_.themedColor.textDisabled};${te.light`
|
|
252
|
+
background-color: ${_.color.background50};
|
|
253
|
+
color: ${_.themedColor.textMidEmphasis};
|
|
254
254
|
`}
|
|
255
|
-
${
|
|
256
|
-
background-color: ${
|
|
257
|
-
color: ${
|
|
255
|
+
${te.dark`
|
|
256
|
+
background-color: ${_.color.onlight.textLowEmphasis};
|
|
257
|
+
color: ${_.themedColor.textMidEmphasis};
|
|
258
258
|
`}
|
|
259
|
-
`,
|
|
260
|
-
${r} ${
|
|
259
|
+
`,uE=H.css`border-color:${_.themedColor.error}!important;`,dE=E.default.button`${oE}${({$active:e,$submitted:t,$error:n})=>{if(t)return e?iE:aE;const r=e?cE:lE;return n?H.css`
|
|
260
|
+
${r} ${uE}
|
|
261
261
|
`:r}}
|
|
262
|
-
`,
|
|
263
|
-
background-color: ${
|
|
262
|
+
`,mE=e=>a.createElement(Aa,{...e,multiple:!1}),hE=e=>a.createElement(Aa,{...e,multiple:!0}),fE=E.default.div`width:100%;height:1px;background-color:${_.themedColor.textDisabled};`,gE=({className:e})=>a.createElement(fE,{className:e}),pE=({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 C=g.target.value;d&&C.length>d||n==null||n(C)},placeholder:r,className:c,disabled:u||i,maxLength:d,$error:o,$submitted:i,...m};return s==="multi-line"?a.createElement(EE,{...f}):a.createElement(_E,{...f})},Ta=H.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;${Re}&::placeholder{color:${_.themedColor.textLowEmphasis};}`,Ia=H.css`color:${_.themedColor.textHighEmphasis};border:1px solid transparent;cursor:not-allowed;${te.light`
|
|
263
|
+
background-color: ${_.color.ondark.textMidEmphasis};
|
|
264
264
|
`}
|
|
265
|
-
${
|
|
266
|
-
background-color: ${
|
|
265
|
+
${te.dark`
|
|
266
|
+
background-color: ${_.color.onlight.textLowEmphasis};
|
|
267
267
|
`}
|
|
268
268
|
|
|
269
269
|
&::placeholder {
|
|
270
|
-
color: ${
|
|
270
|
+
color: ${_.themedColor.textLowEmphasis};
|
|
271
271
|
}
|
|
272
|
-
`,
|
|
273
|
-
background-color: ${
|
|
272
|
+
`,xa=H.css`border:1px solid ${_.themedColor.error};color:${_.themedColor.textHighEmphasis};${te.light`
|
|
273
|
+
background-color: ${_.color.background50};
|
|
274
274
|
`}
|
|
275
|
-
${
|
|
276
|
-
background-color: ${
|
|
275
|
+
${te.dark`
|
|
276
|
+
background-color: ${_.color.onlight.textLowEmphasis};
|
|
277
277
|
`}
|
|
278
|
-
`,
|
|
279
|
-
background-color: ${
|
|
278
|
+
`,Ra=H.css`border:1px solid ${_.themedColor.textDisabled};color:${_.themedColor.textHighEmphasis};${te.light`
|
|
279
|
+
background-color: ${_.color.background50};
|
|
280
280
|
`}
|
|
281
|
-
${
|
|
282
|
-
background-color: ${
|
|
281
|
+
${te.dark`
|
|
282
|
+
background-color: ${_.color.onlight.textLowEmphasis};
|
|
283
283
|
`}
|
|
284
284
|
|
|
285
285
|
&:focus {
|
|
286
|
-
border-color: ${
|
|
286
|
+
border-color: ${_.themedColor.primary};
|
|
287
287
|
}
|
|
288
|
-
`,
|
|
288
|
+
`,_E=E.default.input`${Ta};height:36px;${({$error:e,$submitted:t})=>t?Ia:e?xa:Ra}`,EE=E.default.textarea`${Ta};height:96px;resize:none;font-family:inherit;${({$error:e,$submitted:t})=>t?Ia:e?xa:Ra}`,CE=({children:e,className:t,style:n})=>a.createElement(B,{variant:"button",color:_.themedColor.textHighEmphasis,className:t,style:n},e),Le={Title:CE,Label:j_,ErrorLabel:W_,Separator:gE,Button:Y_,TextInput:pE,NumberInput:X_,SingleSelect:mE,MultiSelect:hE},bE=1,vE=new Set(["text","number","single-select","multi-select"]),Ma=typeof __SBA_USE_FORM__>"u"||__SBA_USE_FORM__,SE=({messageForm:e,onError:t})=>{const n=l.useRef(void 0);l.useEffect(()=>{if(Ma||!e||!t)return;const r=e.key??"";n.current!==r&&(t(new Error("Form rendering is disabled")),n.current=r)},[e,t])},yE=e=>{var b,y;const t=(b=e.extendedMessagePayload)==null?void 0:b.form;if(SE({messageForm:t,onError:(y=e.statsCallbacks)==null?void 0:y.onFormRenderError}),!Ma)return null;if(!t)throw new Error("Form is not provided");const{stringSet:n}=ae(),{conversation:r}=oe(),[s,o]=l.useState({submitting:!1,canceling:!1}),[i,c]=l.useState({visible:!1}),{state:u,fields:d,submit:m,cancel:h,updateFieldValue:f}=pm(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",C=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}))}},v=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}))}},p=l.useMemo(()=>{const A=()=>t.version>bE,T=()=>t.fields.some(R=>!vE.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:p.visible?a.createElement(l.Fragment,null,a.createElement(To,{$maxWidth:e.maxBodyWidth??re.BODY_MAX_WIDTH},a.createElement(Le.Title,null,t.title),a.createElement(AE,null,d.map(A=>a.createElement(TE,{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(IE,null,a.createElement(Le.Button,{variant:g?"clear":"primary",...r.form.button(g?n.SUBMITTED:n.BUTTON__SUBMIT).props,onClick:C,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:v,disabled:s.submitting,loading:s.canceling},n.BUTTON__CANCEL))),a.createElement(Nn,{...i,onClose:()=>c({visible:!1,title:""})})):a.createElement(To,{$maxWidth:e.maxBodyWidth??re.BODY_MAX_WIDTH},a.createElement(B,{variant:"body3"},p.reason),p.cancelable&&a.createElement(Le.Button,{variant:"primary",...r.form.button(n.BUTTON__CANCEL).props,onClick:v,loading:s.canceling},n.BUTTON__CANCEL))},To=E.default.div`display:flex;flex-direction:column;gap:12px;border-radius:12px;overflow:hidden;max-width:${({$maxWidth:e})=>e}px;${({theme:e})=>H.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
|
-
`,
|
|
295
|
+
`,AE=E.default.div`display:flex;flex-direction:column;gap:12px;`,TE=E.default.div`display:flex;flex-direction:column;`,IE=E.default.div`display:flex;flex-direction:column;gap:8px;`,xE=e=>a.createElement(a.Fragment,null),br=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,RE=({messageTemplate:e,onError:t})=>{const n=l.useRef(void 0);l.useEffect(()=>{if(br||!e||!t)return;const r=e.key??"";n.current!==r&&(t(new Error("Message template rendering is disabled")),n.current=r)},[e,t])},ME=e=>{var n,r,s;const t=(n=e.extendedMessagePayload)==null?void 0:n.message_template;return RE({messageTemplate:t,onError:(r=e.statsCallbacks)==null?void 0:r.onMessageTemplateError}),br?a.createElement(Ht,{errorFallback:e.messageTemplateErrorFallback,loadingFallback:e.messageTemplateLoadingFallback,onError:(s=e.statsCallbacks)==null?void 0:s.onMessageTemplateError},a.createElement(br,{...e})):null},wE=({extendedMessagePayload:e,onClickSuggestedReply:t,suggestedRepliesDirection:n="vertical"})=>{const{conversation:r}=oe(),[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(kE,{id:`${Je}-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(LE,{$type:n,...h.props,onClick:()=>u(d)},a.createElement(OE,{variant:"body3"},d)),h.descriptionNode)}))},kE=E.default.div`margin:16px 0;padding:0 ${re.HORIZONTAL_PADDING}px;position:relative;display:flex;align-self:stretch;gap:8px;${({$type:e})=>e==="vertical"?NE:DE};`,LE=E.default.button.attrs({type:"button"})`
|
|
296
296
|
all: unset;
|
|
297
297
|
box-sizing: border-box;
|
|
298
298
|
padding: 8px 12px;
|
|
@@ -302,84 +302,84 @@
|
|
|
302
302
|
border-radius: 20px / clamp(20px, 5%, 100px);
|
|
303
303
|
cursor: pointer;
|
|
304
304
|
word-break: break-word;
|
|
305
|
-
color: ${
|
|
306
|
-
border: 1px solid ${
|
|
307
|
-
background-color: ${
|
|
305
|
+
color: ${_.color.primary.main};
|
|
306
|
+
border: 1px solid ${_.color.primary.main};
|
|
307
|
+
background-color: ${_.themedColor.bg_50_600};
|
|
308
308
|
|
|
309
309
|
&:hover {
|
|
310
|
-
background-color: ${
|
|
310
|
+
background-color: ${_.themedColor.bg_100_500};
|
|
311
311
|
}
|
|
312
312
|
|
|
313
|
-
${
|
|
313
|
+
${Re}
|
|
314
314
|
|
|
315
|
-
${({$type:e,theme:t})=>
|
|
316
|
-
`,
|
|
315
|
+
${({$type:e,theme:t})=>H.css`${e==="vertical"?$E:PE};&:active{background-color:${t.colors.base.primary};color:${t.colors.base.primaryContrastContent};}`}
|
|
316
|
+
`,OE=E.default(B)`color:inherit;`,NE=H.css`flex-direction:column;align-items:flex-end;`,DE=H.css`flex-direction:row;overflow-x:scroll;-ms-overflow-style:none;scrollbar-width:none;&::-webkit-scrollbar{display:none;}`,$E=H.css`max-width:calc(100% - 70px);white-space:pre-wrap;`,PE=H.css`white-space:nowrap;`,FE=e=>{const{components:t}=pt.useContext(),{stringSet:n}=ae(),r=Zo(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})},UE=e=>{var A,T,R,N,k;const{components:t}=pt.useContext(),{streamText:n,isAnimating:r}=Mm({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=In(s.extendedMessagePayload),u=c.hasCTAButton,d=c.hasChallenge,m=c.hasCitations,h=c.hasForm,f=c.hasMessageTemplate,g=!!s.createdAt,C=u||m,v=s.groupType==="top"||s.groupType==="single",p=s.groupType==="bottom"||s.groupType==="single",b=i?re.AVATAR_SIZE:0,y=C&&a.createElement(l.Fragment,null,u&&a.createElement(HE,{$marginTop:12,$paddingInline:12},a.createElement(t.CTAButton,{...s})),m&&a.createElement(t.Citation,{...s}));return a.createElement(BE,{$marginBottom:o?0:xn(s.groupType)},v&&a.createElement(GE,null,i&&a.createElement(t.SenderAvatar,{...s}),a.createElement(t.SenderName,{...s})),a.createElement(VE,null,a.createElement(nr,{$extraStartPadding:b},o?a.createElement(t.TypingIndicator,{...s}):a.createElement(t.MessageBody,{...s},y)),f&&a.createElement(Io,{$startPadding:0,$endPadding:0},a.createElement(t.MessageTemplate,{...s,messageTemplateErrorFallback:s.messageTemplateErrorFallback??a.createElement(nr,{$extraStartPadding:b},a.createElement(t.MessageBody,{...s,messageType:"user",message:((k=(N=s.extendedMessagePayload)==null?void 0:N.message_template)==null?void 0:k.fallback_message)??"Cannot read this template."})),messageTemplateLoadingFallback:s.messageTemplateLoadingFallback??a.createElement(nr,{$extraStartPadding:b},a.createElement(t.TypingIndicator,{...s}))})),a.createElement(t.CustomMessageTemplate,{...s}),d&&a.createElement(t.Challenge,{...s}),h&&a.createElement(Io,{$extraStartPadding:b},a.createElement(t.Form,{...s}))),a.createElement(t.MessageLogs,{...s}),p&&g&&a.createElement(zE,{$extraStartPadding:b+8},a.createElement(t.SentTime,{...s})),a.createElement(l.Fragment,null,!o&&a.createElement(Xt,{$extraStartPadding:b+8},a.createElement(t.Feedback,{...s})),s.suggestedRepliesVisible&&a.createElement(t.SuggestedReplies,{...s})))},pt=qe({template:UE,components:{SenderName:o_,SenderAvatar:r_,SentTime:a_,MessageBody:FE,TextMessageBody:Qp,MediaMessageBody:$p,FileMessageBody:Op,MultipleFilesMessageBody:Wp,TypingIndicator:l_,SuggestedReplies:wE,MessageTemplate:ME,CustomMessageTemplate:T_,Challenge:E_,CTAButton:g_,Citation:C_,Form:yE,Feedback:U_,MessageLogs:xE}}),BE=E.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
|
-
`,
|
|
321
|
+
`,Xt=E.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=re.HORIZONTAL_PADDING,$endPadding:t=re.HORIZONTAL_PADDING,$extraStartPadding:n=0})=>`
|
|
326
326
|
padding-inline: ${e+n}px ${t}px;
|
|
327
327
|
`}
|
|
328
|
-
`,
|
|
328
|
+
`,HE=E.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
|
-
`,
|
|
332
|
+
${({$marginTop:e=0,$paddingInline:t=0})=>H.css`margin-top:${e}px;padding-inline:${t}px;`}
|
|
333
|
+
`,GE=E.default(Xt)`display:flex;flex-direction:row;align-items:center;gap:8px;`,nr=E.default(Xt)`display:flex;`,zE=E.default(Xt)`margin-top:${re.BODY_TIME_GAP}px;display:flex;align-items:flex-start;justify-content:flex-start;`,Io=E.default(Xt).attrs({role:"presentation"})`
|
|
334
334
|
display: flex;
|
|
335
|
-
${({$startPadding:e=
|
|
335
|
+
${({$startPadding:e=re.HORIZONTAL_PADDING,$endPadding:t=re.HORIZONTAL_PADDING,$extraStartPadding:n=0})=>`
|
|
336
336
|
padding-inline: ${e+n}px ${t}px;
|
|
337
337
|
`}
|
|
338
|
-
`,
|
|
338
|
+
`,VE=E.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
|
|
345
|
-
background-color: ${
|
|
343
|
+
gap: ${re.GAP_GROUPED}px;
|
|
344
|
+
`;function qE({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(Xr,{name:e.name,mimeType:e.type,type:Tr(e.name,e.type),onClick:s}),t)}const KE=E.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${re.GAP_GROUPED}px;`;function YE({sendingStatus:e,file:t,metadata:n,onClickMedia:r,onClickMediaFiles:s,children:o}){const{conversation:i}=oe(),{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}),C={...g.props,$ratio:c,$clickable:!!f};return a.createElement(WE,null,a.createElement(jE,{...C},!m&&a.createElement(gt,{size:26},a.createElement(ee,{type:"spinner",color:"textLowEmphasis",size:26})),a.createElement(XE,{$loaded:m,src:d,alt:"image-message",onLoad:()=>h(!0)}),g.descriptionNode),o)}const WE=E.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${re.GAP_GROUPED}px;`,jE=E.default.div`width:${re.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;${te.light`
|
|
345
|
+
background-color: ${_.color.background100};
|
|
346
346
|
`}
|
|
347
|
-
${
|
|
348
|
-
background-color: ${
|
|
347
|
+
${te.dark`
|
|
348
|
+
background-color: ${_.color.background400};
|
|
349
349
|
`}
|
|
350
|
-
`,
|
|
350
|
+
`,XE=E.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;`,ZE=({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(JE,null,a.createElement(pa,{images:i,isPending:c,onClickImage:d}),o)},JE=E.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${re.GAP_GROUPED}px;`;function QE(e){var n,r;const t=l.useMemo(()=>{const s=Zp(Ea(e.message));return zo.default.sanitize(s)},[e.message]);return a.createElement(eC,{$maxWidth:e.maxBodyWidth??re.BODY_MAX_WIDTH,$color:(n=e.customStyle)==null?void 0:n.bubbleContentColor,$bgColor:(r=e.customStyle)==null?void 0:r.bubbleBackgroundColor},a.createElement(tC,{variant:"body3",dangerouslySetInnerHTML:{__html:t}}))}const eC=E.default.div`display:flex;flex-direction:column;border-radius:12px;overflow:hidden;max-width:${({$maxWidth:e})=>e}px;${({theme:e,$color:t,$bgColor:n})=>H.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
|
-
`,
|
|
358
|
-
`,
|
|
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`
|
|
360
|
-
background-color: ${
|
|
357
|
+
`,tC=E.default(B)`align-items:flex-start;line-height:140%;white-space:pre-wrap;padding:0 12px;`,nC=({sendingStatus:e})=>{const t=H.useTheme();switch(e){case"pending":return a.createElement(rC,{size:16},a.createElement(ee,{type:"spinner",color:t.colors.messageOutgoing.background,size:16}));case"failed":return a.createElement("div",{style:{marginBottom:2}},a.createElement(ee,{type:"error",color:_.themedColor.error,size:16}));case"scheduled":case"canceled":return null;default:return a.createElement("div",{style:{marginBottom:2}},a.createElement(ee,{type:"done",color:_.themedColor.secondary,size:16}))}},rC=E.default(gt)`margin-bottom:2px;width:16px;height:16px;`,sC=({createdAt:e})=>{const{stringSet:t,format:n}=ae();return e?a.createElement(B,{variant:"caption4",color:_.themedColor.textLowEmphasis},n(e,t.DATE_FORMAT__MESSAGE_TIMESTAMP)):null},oC=e=>{const{components:t}=Rt.useContext(),{stringSet:n}=ae(),r=()=>{const i=Zo(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())},iC=e=>a.createElement(a.Fragment,null),aC=e=>{const{components:t}=Rt.useContext(),n=e.sendingStatus==="succeeded",r=e.groupType==="bottom"||e.groupType==="single";return a.createElement(cC,{$marginBottom:xn(e.groupType)},a.createElement(lC,null,a.createElement(t.MessageBody,{...e})),a.createElement(t.MessageLogs,{...e}),r&&a.createElement(uC,{$extraEndPadding:8},n?a.createElement(t.SentTime,{...e}):a.createElement(t.SendingStatus,{...e})))},Rt=qe({template:aC,components:{SendingStatus:nC,SentTime:sC,MessageBody:oC,TextMessageBody:QE,MediaMessageBody:YE,FileMessageBody:qE,MultipleFilesMessageBody:ZE,MessageLogs:iC}}),cC=E.default.div`display:flex;flex:1;flex-direction:column;align-items:flex-end;margin-bottom:${({$marginBottom:e})=>`${e}px`};
|
|
358
|
+
`,wa=E.default.div`display:flex;align-self:stretch;justify-content:flex-end;${({$startPadding:e=re.HORIZONTAL_PADDING,$endPadding:t=re.HORIZONTAL_PADDING,$extraEndPadding:n=0})=>`padding-inline: ${e}px ${t+n}px;`};
|
|
359
|
+
`,lC=E.default(wa)``,uC=E.default(wa)`margin-top:${re.BODY_TIME_GAP}px;`,dC=e=>e.messageType!=="admin"?null:a.createElement(mC,null,a.createElement(B,{variant:"caption2",color:_.themedColor.textMidEmphasis},hC(zo.default.sanitize(e.message),e.onClickLink))),mC=E.default.div`text-align:center;text-wrap:pretty;word-break:break-word;padding-inline:${re.HORIZONTAL_PADDING}px;a{text-decoration:underline;color:inherit;}`,hC=(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:Gr,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]}},fC=({direction:e,currentIndex:t,totalCount:n})=>n<=0?t:e==="next"?(t+1)%n:(t-1+n)%n,ka=({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(fC({direction:f,currentIndex:h,totalCount:e.length}))}})}},gC=e=>{switch(e.key){case"ArrowDown":case"ArrowRight":return"next";case"ArrowUp":case"ArrowLeft":return"previous";default:return}},pC=({event:e,onClick:t,onArrowNavigate:n})=>{if(_C(e))return;const r=gC(e);if(r){e.preventDefault(),n==null||n(r);return}e.key!=="Enter"&&e.key!==" "||(e.preventDefault(),t==null||t())},_C=e=>e.repeat||e.currentTarget.getAttribute("aria-disabled")==="true",Qr=l.forwardRef(({onClick:e,checked:t,label:n,disabled:r,tabIndex:s=0,labelVariant:o="caption2",describedBy:i,onArrowNavigate:c},u)=>{const d=t?_.themedColor.primary:r?_.themedColor.textDisabled:_.themedColor.textLowEmphasis,m=t?_.themedColor.textHighEmphasis:r?_.themedColor.textLowEmphasis:_.themedColor.textHighEmphasis;return a.createElement(bC,{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=>pC({event:h,onClick:e,onArrowNavigate:c})},a.createElement(EC,{"aria-hidden":"true"},a.createElement(ee,{size:20,type:t?"radio-on":"radio-off",color:d})),a.createElement(CC,{"aria-hidden":"true",variant:o,color:m},n))});Qr.displayName="Radio";const EC=E.default.div`width:20px;height:20px;`,CC=E.default(B)`line-height:20px;word-break:break-word;`,bC=E.default.div`display:flex;align-items:flex-start;justify-content:flex-start;gap:2px;${Re}&[aria-disabled='false']{cursor:pointer;}`,vC=({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=ka({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(SC,null,a.createElement(Le.Label,{required:c.required,"aria-hidden":!0},c.question),a.createElement(yC,{...i.radioGroupProps(c.question)},o.map((m,h)=>a.createElement(Qr,{key:m.label,checked:r===m.value,label:m.label,disabled:t,...i.getRadioProps(h),onClick:()=>s==null?void 0:s(m.value)}))))},SC=E.default.div`display:flex;flex-direction:column;gap:8px;`,yC=E.default.div`display:flex;flex-direction:column;gap:8px;`,AC=({followUpItem:e,submitted:t,value:n="",onChange:r,hasError:s})=>{const{stringSet:o}=ae(),{conversation:i}=oe(),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=ka({options:m,value:n,disabled:t,hasError:s,errorId:c,onChange:r});return a.createElement(TC,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(IC,{...h.radioGroupProps(e.question)},m.map((f,g)=>a.createElement(Qr,{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(xC,{role:"alert",id:c},o.FORM_VALIDATION_REQUIRED))},TC=E.default.div`display:flex;flex-direction:column;gap:8px;`,IC=E.default.div`display:flex;flex-direction:column;gap:8px;`,xC=E.default(Le.ErrorLabel)``,RC=({value:e,selected:t})=>a.createElement(MC,{$selected:t,"aria-hidden":"true"},wC[e-1]),MC=E.default.div`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,wC=[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)"}))))],kC=({csatPayload:e,submitted:t,value:n,onChange:r})=>{const s=typeof n>"u",{conversation:o}=oe(),i=o.csat.scoresContainer(e.csat_question);return a.createElement(OC,null,a.createElement(B,{variant:"caption3",color:_.themedColor.textMidEmphasis,"aria-hidden":"true"},e.csat_question),a.createElement(NC,{...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(DC,{key:d,type:"button",...g.props},a.createElement(LC,{value:m,selected:s||h,src:u}),!!c&&a.createElement(B,{"aria-hidden":"true",color:h?_.themedColor.textHighEmphasis:_.themedColor.textLowEmphasis,variant:"caption3"},c),g.descriptionNode)})))},LC=({value:e,src:t,selected:n})=>{const[r,s]=l.useState(!1),o=r?a.createElement(RC,{value:e,selected:n}):a.createElement(PC,{$selected:n,alt:"","aria-hidden":"true",src:t,onError:()=>s(!0)});return a.createElement($C,null,o)},OC=E.default.div`display:flex;flex-direction:column;gap:8px;`,NC=E.default.div`display:flex;justify-content:space-between;align-self:center;width:100%;max-width:400px;gap:16px;`,DC=E.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;${Re}&:not(:disabled):hover span{color:${_.themedColor.textHighEmphasis};}`,$C=E.default.div`button:not(:disabled):hover &{border-radius:4px;cursor:pointer;background-color:${_.color.background200};${te.dark`
|
|
360
|
+
background-color: ${_.color.background500};
|
|
361
361
|
`}
|
|
362
362
|
}
|
|
363
|
-
`,
|
|
364
|
-
background-color: ${
|
|
363
|
+
`,PC=E.default.img`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,FC=({csatPayload:e})=>a.createElement(B,{variant:"button",color:_.themedColor.textHighEmphasis},e.title),rr=({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}=Am({csatPayload:e,type:t,initialCsat:r,initialCsatReason:s,initialIsResolved:o});return a.createElement(a.Fragment,null,a.createElement(UC,null,a.createElement(FC,{...g}),t===je.AI_AGENT_CSAT_5_WITH_CRE&&a.createElement(vC,{...g,defaultValue:o,value:i.isResolved,onChange:C=>c({isResolved:C})}),a.createElement(kC,{...g,value:i.csat,onChange:C=>c({csat:C})}),m&&a.createElement(AC,{...g,followUpItem:m,value:i.csatReason,onChange:C=>{c({csatReason:C}),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})))},UC=E.default.div`display:flex;flex-direction:column;gap:12px;`,BC=e=>{const{stringSet:t}=ae();return Jc(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})},HC=()=>{const{stringSet:e}=ae();return a.createElement(B,{variant:"body2",color:_.themedColor.textMidEmphasis,style:{textAlign:"center"}},e.CSAT_SUBMISSION_EXPIRED)},GC=({onMount:e,children:t})=>(l.useEffect(()=>{e&&Ie(e)},[]),t),zC=e=>{const{conversation:t}=oe();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=wn(),m=BC(n==null?void 0:n.csat),h=l.useRef(null),f=l.useRef(null),[g,C]=l.useState(!1),v=l.useRef(!1),p=l.useCallback(()=>{Ie(()=>{var R;return(R=f.current)==null?void 0:R.focus()})},[]),{isExpiredNow:b,isRenderableCSAT:y}=Tm({csat:o,csatExpireAt:c,csatPayload:m,isSubmitInFlight:g});if(Sm({csat:o,csatPayload:m,isRenderableCSAT:y,isExpiredNow:b,announceStatus:e.announceStatus,onSubmittedAnnounced:p}),!y||!m)return null;const A=()=>{var N;const R=(N=h.current)==null?void 0:N.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?rr:()=>null;return a.createElement(VC,{ref:h},!o&&b?a.createElement(HC,null):a.createElement(T,{csatPayload:m,type:m.type,initialCsat:o,initialCsatReason:i,initialIsResolved:u,renderSubmitButton:({state:R,params:N,validateParams:k})=>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(B,{variant:"button","aria-hidden":"true"},m.csat_submitted_label)):a.createElement(GC,{onMount:s},a.createElement(qC,{type:"button",...t.csat.submitButton(m.csat_submit_label).props,onClick:async()=>{if(v.current)return;const x=ni(c);if(!x&&k()){v.current=!0,C(!0);try{await r(N)}catch(D){throw v.current=!1,C(!1),D}}else d(),x||Ie(()=>{var D;(D=e.announceError)==null||D.call(e,{type:"csatFormError"},A())})}},a.createElement(B,{variant:"button"},m.csat_submit_label)))}))},VC=E.default.div`display:flex;flex-direction:column;background-color:${({theme:e})=>e.colors.csat.background};border-radius:16px;gap:16px;padding:16px;`,qC=E.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;${Re}&:hover{background-color:${_.color.primary.dark};}`,KC=E.default.div`width:100%;box-sizing:border-box;color:${_.themedColor.textHighEmphasis};background-color:${_.color.background200};border-radius:6px;padding:10px 20px;display:flex;align-items:center;justify-content:center;text-align:center;word-break:break-word;${te.dark`
|
|
364
|
+
background-color: ${_.color.onlight.textDisabled};
|
|
365
365
|
`}
|
|
366
|
-
`,
|
|
367
|
-
`,
|
|
368
|
-
background-color: ${
|
|
366
|
+
`,YC=e=>{const{components:t}=Pn.useContext(),n=e.messageType==="admin"?a.createElement(t.AdminMessage,{...e}):e.messageType==="admin.csat"?a.createElement(t.CSATMessage,{...e}):null;return a.createElement(WC,{$marginBottom:xn(e.groupType)},n)},Pn=qe({template:YC,components:{AdminMessage:dC,CSATMessage:zC}}),WC=E.default.div`padding-inline:${re.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>e}px;`,es=({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(QC,{type:"button",onClick:i,$fullWidth:u!=="horizontal",$background:d==null?void 0:d.negativeBackground,$borderColor:d==null?void 0:d.negativeBorderColor},a.createElement(B,{variant:"button",color:(d==null?void 0:d.negativeText)??_.themedColor.textHighEmphasis},s)):null,g=h?a.createElement(eb,{type:"button",onClick:c,$fullWidth:u!=="horizontal",$background:d==null?void 0:d.positiveBackground,$borderColor:d==null?void 0:d.positiveBorderColor},a.createElement(B,{variant:"button",color:(d==null?void 0:d.positiveText)??_.themedColor.textHighEmphasisInverse},o)):null;return a.createElement(jC,null,a.createElement(XC,null,a.createElement(B,{as:"div",id:t,variant:"h2",color:(d==null?void 0:d.titleColor)??_.themedColor.textHighEmphasis},e)),a.createElement(ZC,null,a.createElement(B,{as:"div",id:r,variant:"body3",color:(d==null?void 0:d.descriptionColor)??_.themedColor.textMidEmphasis},n)),a.createElement(JC,{$buttonLayout:u},u==="horizontal"?a.createElement(a.Fragment,null,f,g):a.createElement(a.Fragment,null,g,f)))},jC=E.default.div`display:flex;flex-direction:column;width:280px;border-radius:16px;overflow:hidden;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,XC=E.default.div`padding:24px 24px 16px;`,ZC=E.default.div`padding-inline:24px;`,JC=E.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;`,QC=E.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;}`,eb=E.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??_.themedColor.textHighEmphasis};white-space:nowrap;overflow:hidden;text-overflow:ellipsis;&:hover{opacity:0.8;}`,cn=16,tb=({status:e})=>e===pn.COMPLETED?a.createElement(ee,{type:"done-circle",size:cn,color:_.themedColor.textHighEmphasis}):e===pn.CANCELED?a.createElement(ee,{type:"stop-circle",size:cn,color:_.themedColor.textLowEmphasis}):a.createElement(gt,{size:cn},a.createElement(ee,{type:"spinner",size:cn,color:_.themedColor.textHighEmphasis})),La=24,nb=8,rb=40,sb=({task:e,isFirst:t,isLast:n})=>a.createElement(ob,{role:"listitem"},a.createElement(ib,null,a.createElement(xo,{$hidden:t}),a.createElement(ab,null,a.createElement(tb,{status:e.status})),a.createElement(xo,{$hidden:n})),a.createElement(cb,null,a.createElement(B,{as:"div",variant:"body3",color:e.status===pn.CANCELED?_.themedColor.textLowEmphasis:_.themedColor.textHighEmphasis},e.user_facing_title))),ob=E.default.div`display:flex;gap:4px;`,ib=E.default.div`display:flex;flex-direction:column;align-items:center;width:${La}px;flex-shrink:0;`,xo=E.default.div`width:1px;flex:1;transform:translateX(-25%);${({$hidden:e})=>e&&"visibility: hidden;"}background-image:repeating-linear-gradient( to bottom,${_.themedColor.textHighEmphasis}0 2px,transparent 2px 4px );`,ab=E.default.div`display:flex;height:${La}px;align-items:center;justify-content:center;`,cb=E.default.div`display:flex;flex:1;align-items:center;box-sizing:border-box;min-width:0;min-height:${rb}px;padding-block:${nb}px;`,lb=({steward:e,onCancelSteward:t})=>{const{logger:n}=me(),[r,s]=l.useState(!1),[o,i]=l.useState(!1),c=!!e.cancellation_option,u=_c(e.status);return a.createElement(ub,{$marginBottom:xn("single")},a.createElement(db,null,a.createElement(mb,null,a.createElement(hb,null,a.createElement(B,{as:"div",variant:"caption1",color:_.themedColor.textHighEmphasis},e.title),!!e.description&&a.createElement(B,{as:"div",variant:"caption4",color:_.themedColor.textLowEmphasis},e.description)),c&&a.createElement(_b,{type:"button","aria-label":"Stop steward",disabled:o,onClick:()=>s(!0)},a.createElement(ee,{type:"stop",size:16,color:o?_.themedColor.textDisabled:_.themedColor.textHighEmphasis}))),a.createElement(fb,null),e.tasks.length===0?u!==Ft.IN_PROGRESS?null:a.createElement(pb,null,a.createElement(gt,{size:16},a.createElement(ee,{type:"spinner",size:16,color:_.themedColor.textHighEmphasis}))):a.createElement(gb,{role:"list"},e.tasks.map((d,m)=>a.createElement(sb,{key:d.id,task:d,isFirst:m===0,isLast:m===e.tasks.length-1})))),r&&e.cancellation_option&&a.createElement(lt,{portalContainerId:Se.WINDOW,visible:r,onClose:()=>s(!1)},a.createElement(es,{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)}}})))},ub=E.default.div`display:flex;flex-direction:column;margin:0 ${re.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>`${e}px`};
|
|
367
|
+
`,db=E.default.div`display:flex;flex-direction:column;border-radius:12px;overflow:hidden;padding:16px;border:1px solid ${_.themedColor.bg_300_500};background-color:${_.themedColor.bg_50_600};box-shadow:0 8px 20px rgba(0,0,0,0.12);`,mb=E.default.div`display:flex;flex-direction:row;align-items:flex-start;gap:8px;`,hb=E.default.div`display:flex;flex-direction:column;gap:4px;flex:1;min-width:0;`,fb=E.default.div`height:1px;margin-block:12px;background-color:${_.themedColor.bg_200_400};`,gb=E.default.div`display:flex;flex-direction:column;`,pb=E.default.div`display:flex;width:100%;height:40px;align-items:center;justify-content:center;`,_b=E.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:${_.themedColor.textHighEmphasis};background-color:${_.themedColor.bg_200_400};&:hover:not(:disabled){opacity:0.8;}&:disabled{cursor:default;}`,Eb=({className:e,label:t,onClick:n})=>{const{colors:r}=H.useTheme(),{conversation:s}=oe(),o={newMessages:s.newMessagesButton()};return a.createElement(Cb,{className:e,onClick:n,...o.newMessages.props},a.createElement(B,{variant:"button",color:r.base.primaryContrastContent},t),a.createElement(ee,{size:16,type:"chevron-down",color:r.base.primaryContrastContent}),o.newMessages.descriptionNode)},Cb=E.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;}${Re}`,ts=({iconSize:e=64,icon:t,className:n,label:r,children:s})=>a.createElement(vb,{className:n},t&&a.createElement(ee,{type:t,size:e,color:_.themedColor.textLowEmphasis}),r&&a.createElement(B,{variant:"body1",color:_.themedColor.textMidEmphasis},r),s),bb=E.default.div`position:relative;display:flex;justify-content:center;align-items:center;width:100%;height:100%;`,vb=E.default.div`display:flex;flex-direction:column;min-height:104px;align-items:center;gap:20px;text-align:center;`,Sb=({label:e="Something went wrong",icon:t="error",action:n,...r})=>a.createElement(ts,{icon:t,label:e,...r},n&&a.createElement(yb,{onClick:n.onClick,label:n.label??"Retry"})),yb=({label:e,onClick:t})=>{const{conversation:n}=oe();return a.createElement(Ab,{tabIndex:0,...n.retryButton(e).props,onClick:t},a.createElement(ee,{type:"refresh",size:20}),a.createElement(B,{variant:"button",color:_.color.primary.main},e))},Ab=E.default.button`all:unset;display:flex;cursor:pointer;gap:4px;align-items:center;justify-content:center;${Re}`,Tb=({iconSize:e=48,className:t})=>a.createElement(gt,{size:e,className:t}),Ib=({label:e="No channels",icon:t="chat",...n})=>a.createElement(ts,{icon:t,label:e,...n}),xb=({label:e="No messages",icon:t="message",...n})=>a.createElement(ts,{icon:t,label:e,...n}),Rb=e=>{const{components:t}=Fn.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(bb,null,n)},Fn=qe({template:Rb,components:{Loading:Tb,Error:Sb,NoChannels:Ib,NoMessages:xb}}),Ut=e=>{const{Template:t}=Fn.useContext();return a.createElement(t,{...e})},Mb=[0,150,450];function wb({enabled:e}){const{state:t,actions:n}=oa(),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=Mb.map(c=>setTimeout(()=>{Ie(()=>{r.current===o&&(s.current||n.scrollToBottom(!1))})},c));return()=>{r.current+=1,i.forEach(c=>clearTimeout(c))}},[n.scrollToBottom,e])}const kb=({className:e,date:t=Date.now(),role:n,style:r})=>{const{format:s,stringSet:o}=ae();return a.createElement(Lb,{id:`${Ue}-date-separator`,role:n,style:r,className:e},a.createElement(B,{variant:"caption4",color:_.themedColor.textMidEmphasis},s(t,o.DATE_FORMAT__MESSAGE_LIST__DATE_SEPARATOR)))},Lb=E.default.div`display:flex;justify-content:center;align-items:center;text-align:center;word-break:break-word;`,Ob=({className:e,style:t,onClick:n})=>{const{conversation:r}=oe(),s={scrollToBottom:r.scrollToBottomButton()};return a.createElement(Nb,{className:e,style:t,onClick:n,tabIndex:0,...s.scrollToBottom.props},a.createElement(ee,{size:24,type:"chevron-down",color:_.color.primary.main}),s.scrollToBottom.descriptionNode??null)},Nb=E.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);${te.light`
|
|
368
|
+
background-color: ${_.color.background50};
|
|
369
369
|
&:hover {
|
|
370
|
-
background-color: ${
|
|
370
|
+
background-color: ${_.color.background100};
|
|
371
371
|
}
|
|
372
372
|
&:active {
|
|
373
|
-
background-color: ${
|
|
373
|
+
background-color: ${_.color.background200};
|
|
374
374
|
}
|
|
375
375
|
`}
|
|
376
|
-
${
|
|
377
|
-
background-color: ${
|
|
376
|
+
${te.dark`
|
|
377
|
+
background-color: ${_.color.background400};
|
|
378
378
|
&:hover {
|
|
379
|
-
background-color: ${
|
|
379
|
+
background-color: ${_.color.background500};
|
|
380
380
|
}
|
|
381
381
|
&:active {
|
|
382
|
-
background-color: ${
|
|
382
|
+
background-color: ${_.color.background700};
|
|
383
383
|
}
|
|
384
384
|
`}
|
|
385
385
|
|
|
@@ -387,45 +387,45 @@
|
|
|
387
387
|
outline: none;
|
|
388
388
|
}
|
|
389
389
|
|
|
390
|
-
${
|
|
391
|
-
`,
|
|
392
|
-
background-color: ${
|
|
393
|
-
border-color: ${
|
|
390
|
+
${Re}
|
|
391
|
+
`,Db=()=>null,Un=qe({template:Db,components:{DateSeparator:kb,ScrollToBottomButton:Ob}}),$b=()=>{const{stringSet:e,format:t}=ae(),{agentPreviewConfigs:n={},aiAgentId:r}=me(),{aiAgentInfo:s}=Ne(),{messageSource:o}=Te(),{Template:i}=pt.useContext(),{components:c}=Un.useContext(),u=n.welcomeMessages??[],d=o.messages,m=Tg(d,r),h=d[m.length+1],f=m[0]??h;return{filteredMessages:da(d,{previewWelcomeMessages:u,aiAgentUserId:r}),shouldShowOriginalDate:g=>g>0||u.length===0?!0:h&&!ot.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,C)=>{const v=C===u.length-1,p=m.length!==d.length,b=u.length===1?"single":C===0?"top":v||p?"bottom":"middle",y=(f==null?void 0:f.createdAt)??Date.now();return a.createElement("div",{key:C,role:"listitem",tabIndex:-1,"aria-label":Dt({sender:(s==null?void 0:s.nickname)||"",message:g.message,messageFormat:"markdown",time:t(y,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:b,createdAt:y,extendedMessagePayload:{suggested_replies:g.suggestedReplies},suggestedRepliesDirection:n.suggestedRepliesDirection,suggestedRepliesVisible:v&&!p,isBotMessage:!0,onClickSuggestedReply:async({reply:A})=>{o.sendUserMessage({message:A})}}))}))}},Pb=()=>{const{messageSource:e,scrollSource:t}=Te();l.useEffect(()=>{!t.state.isAwayFromBottom&&t.state.isScrollPositionReconciled&&e.resetNewMessages()},[t.state.isAwayFromBottom,t.state.isScrollPositionReconciled])},Ro="https://delight.ai?utm_medium=product&utm_source=aiagent&utm_campaign=fy26-glbl-ai-agent-poweredby",Fb=({style:e})=>{const{stringSet:t}=ae(),{handlers:n}=me(),{conversation:r}=oe();return Ur("powered-by")?a.createElement(Ub,{variant:"caption2",style:e},t.POWERED_BY+" ",a.createElement(Bb,{variant:"caption2",forwardedAs:"a",href:Ro,...r.poweredByLink().props,rel:Gr,target:"_blank",onClick:o=>{o.preventDefault(),n.onClickLink({url:Ro})}},"Sendbird")):null},Ub=E.default(B)`color:${_.themedColor.textLowEmphasis};text-align:center;`,Bb=E.default(B)`color:${_.themedColor.textLowEmphasis};cursor:pointer;text-decoration:none;`,Hb=()=>{var c;const{stringSet:e}=ae(),{conversation:t}=oe(),{channelSource:n,goToActiveConversation:r,scrollSource:s}=Te(),o=Fe(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(Gb,null,a.createElement(zb,{variant:"button",color:_.themedColor.textHighEmphasis,...t.startNewConversationButton({onActivate:r}).props},e.TALK_TO_AGENT))},Gb=E.default.div`display:flex;justify-content:center;margin-bottom:16px;`,zb=E.default(B)`border-radius:6px;box-sizing:border-box;padding:10px 20px;cursor:pointer;user-select:none;background-color:${_.color.background50};border:1px solid ${_.color.onlight.textDisabled};${te.dark`
|
|
392
|
+
background-color: ${_.color.background700};
|
|
393
|
+
border-color: ${_.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
|
+
`,Vb=({statsCallbacks:e,...t})=>($m(e),a.createElement(lb,{...t})),qb=(e,t,n)=>t&&ke.isWelcomeMessage(e,n)&&ke.isWelcomeMessage(t,n)?!1:!ic.isSameDay((t==null?void 0:t.createdAt)??0,e.createdAt),Kb=()=>{var X;const{Template:e}=Rt.useContext(),{Template:t}=pt.useContext(),{Template:n}=Pn.useContext(),{components:r}=Un.useContext(),{stringSet:s,format:o}=ae(),{announceError:i,announceStatus:c}=nt(),{file:u}=oe().conversation,{config:d,cache:m,agentPreviewConfigs:h,chatSDK:f,handlers:g,state:C}=me(),{userSession:v,aiAgentInfo:p,connectionError:b}=Ne(),{_statsEnabled:y,conversation:A,channelSource:T,messageSource:R,scrollSource:N,state:{input:k,streamAnimation:x}}=Te(),{filteredMessages:D,shouldShowOriginalDate:F,renderAgentPreviewWelcomeMessages:U}=$b(),q=Si(T.channel),K=Dm({enabled:y}),[L,V]=l.useState(null),[P,Y]=l.useState(null);l.useEffect(()=>{N.actions.onTypingIndicatorUpdate(!!q)},[!!q,N.actions.onTypingIndicatorUpdate]),Pb(),wb({enabled:R.initialized&&R.messages.length>0});const ge=(M,Z=!1)=>{var ie;return Z?p:((ie=T.channel)==null?void 0:ie.members.find(ye=>ye.userId===M.sender.userId))??M.sender},j=M=>{if(M.sendingStatus==="failed"&&!k.disabled)return()=>Y(M)},W=({message:M,index:Z})=>{const ie=Ec(M),ye=D[Z-1],$e=D[Z+1],Me=D[D.length-1],$=M===Me,I=tt(M,p.userId),w=!(p.isUserFeedbackEnabled&&I&&!ke.isWelcomeMessage(M)),O=Cc(M,ye,$e,w),G=qb(M,ye,p.userId)&&F(Z),J=ne=>{V({files:ne.files.map(ce=>({...ce,timestamp:M.createdAt})),index:ne.index})},se=ne=>{J({files:[ne],index:0})},Q=G?a.createElement(r.DateSeparator,{role:"listitem",style:{margin:"16px 0"},date:M.createdAt}):null,pe={data:M.data,maxBodyWidth:C.expanded?re.WIDE_BODY_MAX_WIDTH:void 0,extendedMessagePayload:M.extendedMessagePayload,createdAt:M.createdAt,groupType:O,onClickMedia:se,onClickMediaFiles:J,onClickFile:g.onClickLink,onClickCTA:g.onClickLink,onClickCitation:ne=>g.onClickLink({url:ne.link}),onClickLink:g.onClickLink},Ke=()=>{if(Oe.isOutgoing(M,v.userId))return"outgoingmessage";if(Oe.isIncoming(M,v.userId))return"incomingmessage"},ut=M.createdAt!=null&&M.createdAt!==0?o(M.createdAt,s.DATE_FORMAT__MESSAGE_TIMESTAMP):void 0,st=(()=>{var ce,_e,Ee,Ae,ue,we;const ne=(ce=M.message)==null?void 0:ce.trim();if(M.isFileMessage()){const Pe=((_e=M.name)==null?void 0:_e.trim())||"";return Xn({markdownText:ne,comparisonText:Pe,plainText:u.label(Pe,M.type)})}if(M.isMultipleFilesMessage()){const Pe=((ue=(Ae=(Ee=M.fileInfoList)==null?void 0:Ee[0])==null?void 0:Ae.fileName)==null?void 0:ue.trim())||"",Qt=((we=M.fileInfoList)==null?void 0:we.length)??0;return Xn({markdownText:ne,comparisonText:Pe,plainText:Qt>0?s.CONVERSATION_LIST__MULTIPLE_FILES_COUNT(Qt):""})}return ne?Xn({markdownText:ne}):Mi("")})(),de=(()=>{if(Oe.isAdmin(M))return Dt({message:st.text,messageFormat:st.format,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER});if(Oe.isOutgoing(M,v.userId))return Dt({sender:s.A11Y_MESSAGE_SENDER_YOU,message:st.text,messageFormat:"plain",time:ut,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER});if(Oe.isIncoming(M,v.userId))return Dt({sender:ge(M,I).nickname,message:st.text,messageFormat:st.format,time:ut,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER})})(),be=(()=>{var ne,ce;if(Oe.isAdmin(M))return Oe.isCSAT(M)?A?a.createElement(n,{...pe,...A,isResolvedWhenDeterminedByUser:Xc(A),messageType:"admin.csat",announceError:i,announceStatus:c,onSubmitCSAT:async _e=>{var Ee;await((Ee=T.channel)==null?void 0:Ee.submitCSAT(_e))},onScrollToBottom:()=>N.actions.scrollToBottom()}):null:a.createElement(n,{...pe,messageType:"admin",message:M.message});if(Oe.isSteward(M)){const _e=K({message:M,isBotMessage:I,aiAgentUserId:p.userId});return a.createElement(Vb,{steward:M.extendedMessagePayload.steward,statsCallbacks:_e,onCancelSteward:async()=>{await f.aiAgent.cancelStewardTask({channelUrl:M.channelUrl,messageId:M.messageId})}})}if(Oe.isOutgoing(M,v.userId)){const _e={...pe,message:M.message,sender:ge(M),sendingStatus:M.sendingStatus,onClickFailedMessage:j(M)};if(M.isUserMessage())return a.createElement(e,{messageType:"user",..._e});if(M.isFileMessage()){const[Ee,Ae]=((ne=M.metaArrays.find(ue=>ue.key===Yo))==null?void 0:ne.value)??[];return a.createElement(e,{messageType:"file",file:M,metadata:{aspectRatio:Ee&&Ae?`${Ee}/${Ae}`:"1/1",localFile:(ce=M.messageParams)==null?void 0:ce.file},..._e})}if(M.isMultipleFilesMessage()){const{files:Ee,metadata:Ae}=Eo(M);return a.createElement(e,{messageType:"multipleFiles",files:Ee,metadata:Ae,..._e})}}if(Oe.isIncoming(M,v.userId)){const _e=ke.isStreaming(M),Ee=K({message:M,isBotMessage:I,aiAgentUserId:p.userId}),Ae={...pe,statsCallbacks:Ee,sender:ge(M,I),message:M.message,suggestedRepliesVisible:$,suggestedRepliesDirection:h==null?void 0:h.suggestedRepliesDirection,isBotMessage:I,isStreaming:_e,isHandedOff:et(T.channel),isConversationClosed:Fe(T.channel),isFeedbackEnabled:p.isUserFeedbackEnabled,isFeedbackCommentEnabled:p.isUserFeedbackCommentOptionEnabled,isSenderAvatarVisible:d.conversation.list.senderAvatarEnabled,deferredMarkdownElements:d.conversation.list.deferredMarkdownElements,onClickSuggestedReply:async({reply:ue})=>{R.sendUserMessage({message:ue})},onRequestMessageTemplate:async ue=>{const{template:we}=await f.aiAgent.getMessageTemplate(ue);return m.template.set(ue,we),we},onGetCachedMessageTemplate:ue=>m.template.get(ue),onHandleTemplateInternalAction:ue=>{if(ue.type==="internal"&&ue.internalData){const{method:we,payload:Pe}=ue.internalData;we==="message.send"&&(Pe!=null&&Pe.message)&&R.sendUserMessage({message:Pe.message})}},onFeedbackUpdate:ue=>{const we={messageId:M.messageId,channelUrl:M.channelUrl};if(!ue)return f.aiAgent.deleteMessageFeedback(we);const Pe={...we,rating:I_(ue.rating),comment:ue.comment};return ke.hasFeedback(M)?f.aiAgent.updateMessageFeedback(Pe):f.aiAgent.createMessageFeedback(Pe)},onSubmitForm:({key:ue,data:we})=>f.aiAgent.submitForm({messageId:M.messageId,channelUrl:M.channelUrl,formKey:ue,formData:we}),onCancelForm:({key:ue})=>f.aiAgent.cancelForm({messageId:M.messageId,channelUrl:M.channelUrl,formKey:ue}),onSendChallengeAction:({key:ue,requestId:we,action:Pe,data:Qt})=>f.aiAgent.sendChallengeAction({channelUrl:M.channelUrl,key:ue,requestId:we,action:Pe,data:Qt}),onStreamAnimationStart:()=>{x.start(M.messageId)},onStreamAnimationProgress:()=>{N.actions.onStreamingUpdate(!0)},onStreamAnimationComplete:()=>{x.stop(M.messageId),N.actions.onStreamingUpdate(!1)}};if(M.isUserMessage())return a.createElement(t,{messageType:"user",...Ae});if(M.isFileMessage())return a.createElement(t,{messageType:"file",file:M,...Ae});if(M.isMultipleFilesMessage()){const{files:ue}=Eo(M);return a.createElement(t,{messageType:"multipleFiles",files:ue,...Ae})}}})();return a.createElement(l.Fragment,{key:ie},Q,a.createElement("div",{id:`${Ue}-message-item`,role:"listitem",tabIndex:-1,"aria-label":de,"data-message-listitem":"","data-layout-id":Ke()},be))};return a.createElement(Yb,{id:`${Ue}-message-list`},a.createElement(ep,{ref:N.ref,onScroll:N.props.onScroll,stackDirection:h==null?void 0:h.messageStackDirection,messages:D,renderMessage:W,onLoadPrev:R.loadPrevious,onLoadNext:R.loadNext,depsForResetScrollPositionToBottom:[R.initialized,R.messages.length!==0],bottomSpacerHeight:N.state.bottomSpace,"aria-label":s.A11Y_MESSAGE_LIST,loading:!R.initialized||!T.channel,empty:D.length===0&&!q,error:!!(b||T.error),LoadingComponent:a.createElement(Ut,{type:"loading"}),EmptyComponent:(()=>{const M=U();return M?a.createElement("div",{style:{width:"100%"}},M):a.createElement(Ut,{type:"noMessages",label:s.PLACE_HOLDER__NO_MESSAGES})})(),ErrorComponent:a.createElement(Ut,{type:"error",label:(b==null?void 0:b.message)??((X=T.error)==null?void 0:X.message),action:T.error?{label:s.RETRY,onClick:()=>T.refetch()}:void 0}),messageTopArea:a.createElement(a.Fragment,null,a.createElement(Fb,{style:{marginTop:16}}),U()),messageBottomArea:a.createElement(a.Fragment,null,q&&a.createElement("div",{id:`${Ue}-message-item`,role:"listitem",tabIndex:-1,"aria-label":Dt({sender:q.user.nickname,message:s.A11Y_TYPING_INDICATOR,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER}),"data-message-listitem":"",style:{marginTop:D.length===0?8:0}},a.createElement(t,{isTyping:!0,isBotMessage:q.isBot,sender:q.user,thinkingMessage:q.thinkingMessage,messageType:"user",groupType:"single",message:"",isSenderAvatarVisible:d.conversation.list.senderAvatarEnabled})),d.conversation.list.isTalkToAgentViewEnabled&&a.createElement(Hb,null)),overlayArea:a.createElement(a.Fragment,null,d.conversation.list.newMessageIndicatorEnabled&&N.state.isAwayFromBottom&&R.newMessages.length>0&&a.createElement(Wb,{label:s.SCROLL_TO_NEW_MESSAGES_LABEL(R.newMessages),onClick:()=>N.actions.scrollToBottom()}),N.state.isAwayFromBottom&&R.newMessages.length===0&&!q&&a.createElement(r.ScrollToBottomButton,{onClick:()=>N.actions.scrollToBottom(),style:{position:"absolute",bottom:12,insetInlineEnd:16}}))}),L&&a.createElement(ap,{files:L.files,initialIndex:L.index,onClose:()=>V(null),visible:!0}),P&&a.createElement(at,{visible:!0,onClose:()=>Y(null),"aria-label":s.A11Y_FAILED_MESSAGE_OPTIONS},a.createElement(at.ActionItem,{onClick:()=>{R.resendMessage(P),Y(null)}},s.FAILED_MESSAGE_RESEND),a.createElement(at.ActionItem,{destructive:!0,onClick:()=>{R.deleteMessage(P),Y(null)}},s.FAILED_MESSAGE_REMOVE)))},Yb=E.default.div`overflow-y:hidden;display:flex;flex:1;position:relative;`,Wb=E.default(Eb)`position:absolute;bottom:12px;left:50%;transform:translateX(-50%);`,jb=()=>a.createElement(Kb,null),Mo={file:"attach",snippet:"snippet",site:"website",sb_sprinklr:"sprinklr",sb_salesforce:"salesforce",sb_confluence:"confluence",sb_zendesk:"zendesk",sb_desk:"snippet"},Oa=({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:p=Bt.DEFAULT_PRIMARY}=g;return a.createElement(wo,null,m,e&&a.createElement(wo,null,a.createElement(Tn,null,a.createElement(Ot,null,a.createElement(ee,{size:16,type:"actionbook",color:C})),a.createElement(ln,{$clickable:!!o,$highlightColor:p,variant:"body2",color:v,onClick:()=>o==null?void 0:o(e),maxTextLines:1},e.name))),t==null?void 0:t.map(b=>a.createElement(hn,{key:b.key},a.createElement(Ot,null,a.createElement(ee,{size:16,type:"function",color:C})),a.createElement(Tn,null,a.createElement(ln,{$clickable:!!i,$highlightColor:p,variant:"body2",color:v,onClick:()=>i==null?void 0:i(b),maxTextLines:1},b.name),c&&a.createElement(Xb,{role:"button",onClick:()=>c==null?void 0:c(b)},a.createElement(B,{variant:"body2",color:p},"View details"),a.createElement(ee,{type:"chevron-right",size:16,color:p}))))),n==null?void 0:n.map(b=>a.createElement(hn,{key:b.id},a.createElement(Ot,null,f({default:a.createElement(ee,{size:16,type:Mo[b.source_type]??Mo.snippet,color:C}),sourceType:b.source_type})),a.createElement(ln,{$clickable:!!u,$highlightColor:p,variant:"body2",color:v,onClick:()=>u==null?void 0:u(b),maxTextLines:1},b.preview_title))),r==null?void 0:r.map(b=>a.createElement(hn,{key:b.key},a.createElement(Ot,null,a.createElement(ee,{size:16,type:"template",color:C})),a.createElement(ln,{$clickable:!!d,$highlightColor:p,variant:"body2",color:v,onClick:()=>d==null?void 0:d(b),maxTextLines:1},b.name))),!!(s!=null&&s.length)&&a.createElement(Zb,null,a.createElement(Ot,null,a.createElement(ee,{size:16,type:"activity",color:C})),a.createElement(Jb,{variant:"body2",color:v},s.map(b=>b.replace(/_/g," ")).join(" · "))),h)},Na=E.default(B)`font-weight:400;`,ln=E.default(Na)`${({$clickable:e,$highlightColor:t})=>e&&H.css`
|
|
396
396
|
cursor: pointer;
|
|
397
397
|
text-decoration: underline;
|
|
398
398
|
&:hover {
|
|
399
399
|
color: ${t};
|
|
400
400
|
}
|
|
401
401
|
`}
|
|
402
|
-
`,Ot=
|
|
403
|
-
background-color: ${
|
|
402
|
+
`,Ot=E.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,Tn=E.default.div`display:flex;gap:8px;align-items:center;word-break:break-word;`,Xb=E.default(Tn)`cursor:pointer;gap:4px;`,hn=E.default(Tn)`flex-direction:row;align-items:center;`,Zb=E.default(hn)`align-items:flex-start;max-width:100%;`,Jb=E.default(Na)`min-width:0;`,wo=E.default.div`display:flex;gap:4px;flex-direction:column;align-items:flex-start;`,Da=ve("DashboardTester"),Qb=Da.Provider;function ev({testerType:e,origin:t,children:n}){return a.createElement(Qb,{value:{testerType:e,origin:t}},e&&a.createElement(tv,null),n)}const $a=Da.useContext,tv=()=>a.createElement(a.Fragment,null,a.createElement(pt.MessageLogs,{component:ko}),a.createElement(Rt.MessageLogs,{component:ko})),ko=({extendedMessagePayload:e={}})=>{const{handlers:t}=me(),{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(nv,null,a.createElement(rv,{$width:4}),a.createElement(Oa,{actionbook:n,functionCalls:s,groundedness:r,agentMessageTemplates:o,flaggedTypes:i,onClickFunctionCallDetail:t==null?void 0:t.onFunctionCallDetailClick,style:{iconColor:_.themedColor.textHighEmphasis,textColor:_.themedColor.textHighEmphasis,barColor:_.themedColor.textDisabled},topContent:a.createElement(B,{variant:"caption4",color:_.themedColor.textLowEmphasis},"Only visible in the tester")}))},nv=E.default.div`display:flex;gap:16px;margin:6px ${re.HORIZONTAL_PADDING}px 4px ${re.HORIZONTAL_PADDING+re.AVATAR_SIZE}px;align-self:stretch;`,rv=E.default.div`width:${({$width:e})=>e}px;background-color:${_.themedColor.textDisabled};border-radius:100px;flex-shrink:0;`,sv=()=>{var s;const{origin:e}=$a(),{appId:t,aiAgentId:n}=xe(),{channelSource:r}=Te();return(s=r.channel)!=null&&s.conversation?a.createElement(ov,null,a.createElement(vr,{style:{gap:4}},a.createElement(ee,{color:_.themedColor.textLowEmphasis,size:12,type:"show"}),a.createElement(B,{as:"i",color:_.themedColor.textLowEmphasis,variant:"caption2"},"Only visible in the tester")),a.createElement(vr,{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(B,{variant:"body3",color:_.themedColor.textHighEmphasis},"Copy ",a.createElement("span",{style:{color:_.themedColor.primary}},"conversation link")),a.createElement(ee,{color:_.themedColor.primary,size:14,type:"copy"}))):null},vr=E.default.div`display:flex;justify-content:center;align-items:center;`,ov=E.default(vr)`flex-direction:column;padding-block:16px;background-color:${_.themedColor.bg_100_500};gap:8px;`,iv=(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}},Pa=l.createContext(void 0),av=({children:e})=>{var q,K;const{chatSDK:t}=me(),{createAttachmentRules:n}=Ne(),{stringSet:r}=ae(),{channelSource:s,state:o}=Te(),[i,c]=l.useState([]),{announceError:u}=qr(),[d,m]=l.useState(null),h=n({channel:s.channel,uploadSizeLimit:(q=t.appInfo)==null?void 0:q.uploadSizeLimit}),f=((K=o==null?void 0:o.input)==null?void 0:K.disabled)??!1,g=h.isEnabled(),C=h.maxAttachmentCount,v=()=>m(null),p=L=>m(L),b=()=>{p({title:r.FILE_UPLOAD_NOTIFICATION__COUNT_LIMIT.replace("%d",C.toString())})},y=L=>{p({title:r.FILE_UPLOAD_NOTIFICATION__SIZE_LIMIT.replace("%d",L.toString())}),u({type:"fileSizeExceeded",maxSizeMB:L})},A=L=>{p({title:r.FILE_UPLOAD_NOTIFICATION__FILES_EXCLUDED_BY_VALIDATION.replace("%d",L.toString())})},T=L=>L.map(V=>({file:V,preview:{url:URL.createObjectURL(V),type:V.type,name:V.name}})),R=L=>{c(V=>[...V,...T(L)])},N=L=>{c(V=>(V.forEach(P=>URL.revokeObjectURL(P.preview.url)),T(L)))},k=L=>{const{passed:V,failedBySize:P,failedByType:Y}=iv(L,h),ge=P.length+Y.length,j=L.length===1?P[0]:void 0;return j?y(h.getUploadSizeLimitInMB(j.type)):ge>0&&A(ge),V},x=L=>{const V=k(L.files);V.length!==0&&(L.type==="append"?R(V):N(V))},D=L=>{if(!g||f||!Du(L))return;const V=Pu({currentFiles:i.map(({file:P})=>P),incomingFiles:L,maxAttachmentCount:C});switch(V.type){case"reject":b();return;case"confirm_replace":p({title:r.FILE_UPLOAD_REPLACE_ALERT__TITLE,description:r.FILE_UPLOAD_REPLACE_ALERT__DESCRIPTION,confirmText:r.BUTTON__OK,cancelText:r.BUTTON__CANCEL,onConfirm:()=>x(V.action)});return;case"apply":x(V.action);return}},F=L=>{c(V=>{var Y;const P=(Y=V[L])==null?void 0:Y.preview;return P&&URL.revokeObjectURL(P.url),V.filter((ge,j)=>j!==L)})},U=()=>{c(L=>(L.forEach(V=>URL.revokeObjectURL(V.preview.url)),[]))};return a.createElement(Pa.Provider,{value:{files:i,addFiles:D,removeFile:F,clearFiles:U,isFileUploadEnabled:g,acceptableMimeTypes:h.supportedMimeTypes,maxAttachmentCount:h.maxAttachmentCount,showFileUploadAlert:p}},e,a.createElement(Nn,{visible:!!d,...d??{},onClose:v}))},ns=()=>{const e=l.useContext(Pa);if(!e)throw new Error("useFileUpload must be used within FileUploadProvider");return e};function cv({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 lv({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 uv=()=>{const{announceError:e}=nt();return l.useCallback(t=>{e({type:"sendFailed"},t)},[e])},dv=1e3,mv=(e,t,n)=>{const{announcementsEnabled:r,setIsSuppressed:s}=nt(),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]),Cm(t,u,{enabled:o,idleMs:dv})},hv=({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}}},fv=E.default.div`&::-webkit-scrollbar{display:none;}overflow-x:auto;display:flex;flex-direction:row;gap:10px;padding:8px 16px;background-color:transparent;`,gv=E.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;}`,pv=E.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;${te.light`
|
|
403
|
+
background-color: ${_.color.background50};
|
|
404
404
|
`}
|
|
405
|
-
${
|
|
406
|
-
background-color: ${
|
|
405
|
+
${te.dark`
|
|
406
|
+
background-color: ${_.color.background500};
|
|
407
407
|
`}
|
|
408
408
|
path {
|
|
409
|
-
fill: ${
|
|
409
|
+
fill: ${_.themedColor.textMidEmphasis};
|
|
410
410
|
}
|
|
411
411
|
|
|
412
412
|
&:hover {
|
|
413
413
|
path {
|
|
414
|
-
fill: ${
|
|
414
|
+
fill: ${_.themedColor.textHighEmphasis};
|
|
415
415
|
}
|
|
416
416
|
}
|
|
417
417
|
|
|
418
418
|
&:focus-visible {
|
|
419
419
|
opacity: 1;
|
|
420
|
-
outline: 2px solid ${
|
|
420
|
+
outline: 2px solid ${_.color.primary.main};
|
|
421
421
|
outline-offset: 2px;
|
|
422
422
|
}
|
|
423
423
|
|
|
424
424
|
circle {
|
|
425
|
-
stroke: ${
|
|
425
|
+
stroke: ${_.themedColor.bg_50_600};
|
|
426
426
|
}
|
|
427
|
-
`,
|
|
428
|
-
outline: 2px solid ${
|
|
427
|
+
`,_v=()=>{const e=jt(),{conversation:t}=oe(),{files:n,removeFile:r,isFileUploadEnabled:s}=ns();return s&&n.length>0?a.createElement(fv,null,n.map(({preview:{type:i,name:c,url:u}},d)=>{let m=a.createElement(Xr,{name:c,mimeType:i,type:Tr(c,i),selected:!0});return i.startsWith("image/")&&(m=a.createElement("img",{alt:t.file.label(c,i,!0),src:u})),a.createElement(gv,{key:u},a.createElement(pv,{type:"button",...t.file.removeButton(c).props,$mobile:e,onClick:()=>r(d)},a.createElement(ee,{type:"close-filled",color:_.themedColor.textMidEmphasis})),m)})):null},Ev={textArea:H.css`min-height:40px;height:40px;font-size:16px;line-height:24px;`},Fa=E.default.button`all:unset;cursor:pointer;display:flex;align-items:center;justify-content:center;width:32px;height:32px;${Re}`,Lo=E.default.div`width:100%;position:relative;background-color:${({theme:e})=>e.colors.messageInput.background};border-radius:20px;`,Oo=E.default.div`display:flex;flex-direction:row;align-items:flex-end;position:relative;`,No=E.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:${Bi}px;overflow-wrap:break-word;white-space:pre-wrap;overflow-x:hidden;${na&&Ev.textArea};${({$focusVisible:e})=>e&&H.css`
|
|
428
|
+
outline: 2px solid ${_.themedColor.primary};
|
|
429
429
|
outline-offset: 2px;
|
|
430
430
|
`}
|
|
431
431
|
|
|
@@ -436,22 +436,22 @@
|
|
|
436
436
|
&:disabled {
|
|
437
437
|
cursor: not-allowed;
|
|
438
438
|
&::placeholder {
|
|
439
|
-
color: ${
|
|
439
|
+
color: ${_.themedColor.textDisabled};
|
|
440
440
|
}
|
|
441
441
|
}
|
|
442
442
|
|
|
443
|
-
${({$blocked:e})=>e&&
|
|
444
|
-
`,
|
|
445
|
-
color: ${
|
|
443
|
+
${({$blocked:e})=>e&&H.css`cursor:not-allowed;&::placeholder{color:${_.themedColor.textDisabled};}`}
|
|
444
|
+
`,Cv=E.default.input`display:none;`;E.default.div`display:flex;align-items:center;gap:24px;`;const bv=E.default(Fa)`flex-shrink:0;border-radius:8px;&:disabled{cursor:not-allowed;}&:not(:disabled){&:hover{background-color:${_.themedColor.bg_100_500};path{fill:${_.themedColor.textHighEmphasis};}}&:active{background-color:${_.themedColor.bg_200_400};}}`,Do=E.default.div`padding:10px 16px 10px 12px;position:relative;display:flex;align-items:center;gap:8px;`,$o=e=>e.startsWith("image/"),Po=({disabled:e})=>{const{stringSet:t}=ae(),{conversation:n}=oe(),{config:r}=me(),s=l.useRef(null),o=l.useRef(null),[i,c]=l.useState(!1),{addFiles:u,isFileUploadEnabled:d,acceptableMimeTypes:m,showFileUploadAlert:h}=ns(),f=m.includes(ir),g=f?["image/*"]:m.filter($o),C=f?[ir]:m.filter(k=>!$o(k)),v=r.conversation.input.gallery.photoEnabled,p=r.conversation.input.fileEnabled,b=()=>f||g.length>0,y=()=>f||C.length>0,A=k=>{const x=k.currentTarget.files;x&&u(Array.from(x)),k.target.value=""},T=()=>{c(!0)},R=l.useMemo(()=>{const k=[];return v&&k.push({type:"image",icon:"photo",label:t.FILE_UPLOAD_PHOTOS,accept:g.join(","),inputRef:s,onSelect:()=>{if(!b()){h({title:t.FILE_UPLOAD_NO_SUPPORTED_FILES});return}c(!1),setTimeout(()=>{var x;return(x=s.current)==null?void 0:x.click()},100)}}),p&&k.push({type:"file",icon:"document",label:t.FILE_UPLOAD_FILES,accept:m.join(","),inputRef:o,onSelect:()=>{if(!y()){h({title:t.FILE_UPLOAD_NO_SUPPORTED_FILES});return}c(!1),setTimeout(()=>{var x;return(x=o.current)==null?void 0:x.click()},100)}}),k},[g,m,t,v,p]);if(!d)return null;const N={attach:n.messageInput.attachFileButton()};return a.createElement(a.Fragment,null,a.createElement(bv,{...N.attach.props,disabled:e,onClick:T},a.createElement(ee,{type:"add",color:e?_.themedColor.textDisabled:_.color.primary.main,size:20}),N.attach.descriptionNode),R.map(k=>a.createElement(Cv,{key:k.type,type:"file",ref:k.inputRef,multiple:k.type==="image",onChange:A,accept:k.accept})),a.createElement(at,{visible:i,onClose:()=>c(!1),"aria-label":t.A11Y_FILE_UPLOAD_OPTIONS},R.map(k=>a.createElement(at.ActionItem,{key:k.type,onClick:k.onSelect,icon:k.icon},k.label))))},vv=()=>{const e=l.useRef(null),[t,n]=l.useState(""),{stringSet:r}=ae(),{conversation:s}=oe(),{rootElement:o}=me(),i=ct(o),{focusHandlers:c,isFocusVisible:u,suppressNextFocusVisible:d}=hv({focusRoot:i}),{channelSource:m,messageSource:h,state:f}=Te(),{files:g,addFiles:C,clearFiles:v}=ns(),p=uv(),{focusPolicy:b,disabled:y,disabledBy:A}=f.input,T=b==="preserve",R=b==="release",N=(()=>{if(!y)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}})();Cg({onDropFiles:M=>{C(M)}}),lv({blurred:R,elementRef:e,document:i,onRecoverFocus:()=>{d()}}),mv(m.channel,t,!y);const k=t.trim().length>0,x=g.length>0,D=!y&&(k||x),F={input:s.messageInput.textInput(r.A11Y_MESSAGE_INPUT),send:s.messageInput.sendButton()},U=()=>{e.current&&(e.current.value="",e.current.style.height=""),v(),n("")},q=()=>{var M;d(),(M=e.current)==null||M.focus()},{requestRestore:K,cancelRestore:L}=cv({elementRef:e,ready:T,onRestore:d}),V=M=>{L(),p(M)},P=()=>{L()},Y=async M=>{try{await M(),P()}catch{V(e.current)}},ge=async()=>{if(y)return;const M=t.trim();if(!M&&!g.length)return;const Z=[...g];if(K(),U(),q(),Z.length===0){await Y(()=>h.sendUserMessage({message:M}));return}if(Z.length===1)await Y(()=>h.sendFileMessage({message:M,file:Z[0].file}));else{const ie=Z.map(({file:ye})=>({file:ye}));await Y(()=>h.sendMultipleFilesMessage({message:M,fileInfoList:ie}))}},j=M=>{const Z=Array.from(M.clipboardData.files);Z.length>0&&(M.preventDefault(),C(Z))},W=M=>{M.key!=="Enter"||M.nativeEvent.isComposing||M.shiftKey||(M.preventDefault(),ge())},X=M=>{if(y){e.current&&(e.current.value=t);return}if(e.current){e.current.style.height="";const Z=Math.min(Mh,e.current.scrollHeight);Bi<Z&&(e.current.style.height=`${Z}px`)}n(M.target.value)};return R?a.createElement(Do,null,a.createElement(Po,{disabled:!0}),a.createElement(Lo,null,a.createElement(Oo,null,a.createElement(No,{rows:1,...F.input.props,disabled:!0,placeholder:N,$blocked:!0,$focusVisible:!1,"data-focus-visible":"false"})))):a.createElement(Do,{"data-message-composer":""},a.createElement(Po,{disabled:y}),a.createElement(Lo,null,a.createElement(_v,null),a.createElement(Oo,null,a.createElement(No,{ref:e,rows:1,...F.input.props,readOnly:T,"aria-disabled":T?"true":void 0,placeholder:N,maxLength:5e3,$blocked:y,$focusVisible:u,"data-focus-visible":u?"true":"false",onKeyDown:W,onChange:X,onFocus:c.onFocus,onBlur:c.onBlur,onPaste:j}))),D&&a.createElement(Fa,{...F.send.props,onClick:()=>ge()},a.createElement(ee,{type:"send",color:_.color.primary.main,size:20}),F.send.descriptionNode))},Sv=E.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:${_.themedColor.textLowEmphasis};&& a{font-weight:700;text-decoration:none;${te.light`
|
|
445
|
+
color: ${_.color.information.light};
|
|
446
446
|
`};
|
|
447
|
-
${
|
|
448
|
-
color: ${
|
|
447
|
+
${te.dark`
|
|
448
|
+
color: ${_.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`
|
|
452
|
-
box-shadow: 0 0 0 2px ${
|
|
451
|
+
`,yv=l.lazy(()=>Promise.resolve().then(()=>require("./cjs/VvejebHE.cjs")).then(e=>({default:e.MarkdownText}))),Av=()=>{const{aiAgentInfo:e,userSession:t}=Ne(),{handlers:n}=me(),{messageSource:r,channelSource:s}=Te(),[o,i]=l.useState(null),c=Ur("special-notice",s.channel),u=l.useCallback(()=>s.channel?c?r.messages.some(d=>tt(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(Sv,null,a.createElement(yv,{onClickLink:n.onClickLink},e.specialNotice))},Tv=()=>a.createElement(Iv,null,a.createElement(Av,null),a.createElement(av,null,a.createElement(vv,null))),Iv=E.default.div`z-index:0;border:none;width:100%;`,xv=()=>{var s;const{testerType:e}=$a(),{channelSource:t}=Te(),n=Fe(t.channel),r=!!e&&((s=t.channel)==null?void 0:s.isAIAgent);return n&&r?a.createElement(sv,null):a.createElement(Tv,null)},Ua=({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(Rv,{...s},a.createElement(Mv,null,n==="center"&&t&&a.createElement(wv,{$sideWidth:Math.max(c,d)},a.createElement(kv,null,t)),a.createElement(Lv,null,a.createElement(Ov,{ref:o},e),(n==="start"||n==="end")&&t&&a.createElement(Dv,{$align:n,$hasStart:!!e,$hasEnd:!!r},t),a.createElement(Nv,{ref:i},r))))},Rv=E.default.div`position:relative;width:100%;background-color:${({theme:e})=>e.colors.base.headerBackground};border-bottom:1px solid ${_.themedColor.textDisabled};`,Mv=E.default.div`position:relative;height:56px;padding:11px 12px;`,wv=E.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;`,kv=E.default.div`max-width:100%;overflow:hidden;`,Lv=E.default.div`display:flex;flex-direction:row;align-items:center;justify-content:space-between;height:100%;z-index:1;`,Ov=E.default.div`flex-shrink:0;display:flex;align-items:center;`,Nv=E.default.div`flex-shrink:0;display:flex;align-items:center;`,Dv=E.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;`,Mt=(e=16)=>jt()?e*1.5:e,$v=()=>{const{state:e}=me(),{messenger:t}=oe(),n=Mt(),r=()=>{e.setOpened(!1)};return a.createElement(rt,{...t.closeButton().props,type:"close",size:n,onClick:r})},Pv=()=>{const{enableCloseConversationButton:e,dispatcher:t}=me(),{channelSource:n}=Te(),{conversation:r}=oe(),s=n.channel,o=Mt(),i=(s==null?void 0:s.isAIAgent)&&e,c=!xr(s);if(!i)return null;const u={close:r.header.closeConversationButton()},d=async()=>{s&&await t.send(it.CloseConversation({channelUrl:s.url}))};return a.createElement(a.Fragment,null,a.createElement(rt,{...u.close.props,type:"mute",size:o,disabled:c,onClick:d}),u.close.descriptionNode)},Fv=()=>{const{state:e,enableExpandButton:t}=me(),{messenger:n}=oe(),r=Mt();return t?a.createElement(rt,{...n.expandButton(e.expanded).props,type:e.expanded?"collapse":"expand",size:r,onClick:()=>e.setExpanded(!e.expanded)}):null},Uv=({label:e,children:t,position:n="top",disabled:r})=>r?t:a.createElement(Sr,null,t,a.createElement(Gv,{$position:n},a.createElement(zv,{variant:"caption1"},e),a.createElement(Bv,{$position:n}))),Bv=({$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:_.themedColor.textHighEmphasis})),Hv={top:H.css`flex-direction:column;top:0;transform:translate(-50%,-100%);`,bottom:H.css`flex-direction:column-reverse;bottom:0;transform:translate(-50%,100%);`},Sr=E.default.div`position:relative;`,Gv=E.default.div`display:flex;align-items:center;position:absolute;left:50%;z-index:${ft.TOOLTIP};${({$position:e})=>Hv[e]}opacity:0;transition:opacity 0.2s ease-in-out;pointer-events:none;${Sr}:hover &,${Sr}:focus-within &{opacity:1;}`,zv=E.default(B)`padding:6px 8px;background:${_.themedColor.textHighEmphasis};color:${_.themedColor.textHighEmphasisInverse};border-radius:4px;font-size:12px;white-space:nowrap;`,Vv=2e3,Fo=0,qv=1500,un=Symbol("header-focus-status-pause"),Uo="data-sb-header-focus-protected",Kv="[data-message-composer]",Bo=new WeakMap,sr=e=>{const t=Bo.get(e);if(t)return t;const n={focusedTargetIds:new Set,pendingBlurTimeouts:new Map,maxPauseTimeout:null};return Bo.set(e,n),n},or=(e,t)=>{const n=e.pendingBlurTimeouts.get(t);n&&(clearTimeout(n),e.pendingBlurTimeouts.delete(t))},fn=e=>{e.maxPauseTimeout&&(clearTimeout(e.maxPauseTimeout),e.maxPauseTimeout=null)},Yv=e=>{e.pendingBlurTimeouts.forEach(t=>clearTimeout(t)),e.pendingBlurTimeouts.clear(),e.focusedTargetIds.clear(),fn(e)},Wv=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)})},jv=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),rs=()=>{const{setStatusPauseState:e}=nt(),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()+qv,o();const u=sr(e);or(u,t.current),u.focusedTargetIds.add(t.current),u.focusedTargetIds.size===1&&e(un,!0),fn(u),u.maxPauseTimeout=setTimeout(()=>{Yv(u),e(un,!1)},Vv)},[o,e]),c=l.useCallback(u=>{if(!n.current)return;n.current=!1;const d=u.currentTarget,m=sr(e),h=d instanceof HTMLElement&&Date.now()<=r.current;or(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(Uo);if(g===d||C||!jv(g))return;const v=Wv(d);d.focus({preventScroll:!0}),v()},Fo)),m.pendingBlurTimeouts.set(t.current,setTimeout(()=>{m.pendingBlurTimeouts.delete(t.current),m.focusedTargetIds.delete(t.current),m.focusedTargetIds.size===0&&(fn(m),e(un,!1))},Fo))},[o,e]);return l.useEffect(()=>()=>{const u=sr(e);n.current=!1,o(),or(u,t.current),u.focusedTargetIds.delete(t.current)&&u.focusedTargetIds.size===0&&(fn(u),e(un,!1))},[o,e]),{[Uo]:"true",onFocus:i,onBlur:c}},Xv=()=>{const{logger:e}=me(),{stringSet:t}=ae(),{channelSource:n}=Te(),{conversation:r}=oe(),s=n.channel,o=Mt(),i=Ur("handoff-button",s),c=!xr(s)||et(s),[u,d]=l.useState(!1),m=rs(),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(Uv,{label:t.HEADER_BUTTON__AGENT_HANDOFF,position:"bottom",disabled:c},a.createElement(rt,{...f.handoff.props,type:"agent",size:o,disabled:c,...m,onClick:()=>d(!0)})),f.handoff.descriptionNode),a.createElement(lt,{portalContainerId:Se.WINDOW,visible:u,onClose:()=>d(!1)},a.createElement(es,{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})))},Zv=l.lazy(()=>Promise.resolve().then(()=>require("./cjs/VvejebHE.cjs")).then(e=>({default:e.MarkdownText}))),Jv=()=>{const{logger:e}=me(),{stringSet:t}=ae(),{memoryInfo:n,sdkUser:r}=Ne(),{actions:s}=Te(),{conversation:o}=oe(),i=Mt(20),c=rs(),[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(p){e.error("memoryIndicator.setUserMemoryState: error",p),h(!0)}finally{f.current=!1}}};return a.createElement(a.Fragment,null,n.showIndicator&&a.createElement(a.Fragment,null,a.createElement(nS,{...g.props,as:"button",type:"button",onClick:()=>d({...n}),...c,$size:i},a.createElement(ee,{type:"memory",size:i,color:_.themedColor.textHighEmphasis}),a.createElement(rS,{$enabled:n.enabled})),g.descriptionNode),u&&a.createElement(Qv,{memoryInfo:u,onClose:()=>d(null),onSetEnabled:C}),a.createElement(Nn,{visible:m,title:t.PLACE_HOLDER__WRONG,description:t.MEMORY__ERROR_MESSAGE,onClose:()=>h(!1)}))},Qv=({memoryInfo:e,onClose:t,onSetEnabled:n})=>{var h;const{stringSet:r}=ae(),{colors:s}=H.useTheme(),o=l.useId(),i=l.useId(),c=Nu(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(lt,{visible:!0,portalContainerId:Se.WINDOW,onClose:t,cancelable:!u,"aria-labelledby":o,"aria-describedby":i},a.createElement(es,{title:r.MEMORY__DIALOG_TITLE,titleId:o,description:a.createElement(eS,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}}))},eS=({children:e})=>{const{handlers:t}=me();return a.createElement(sS,null,a.createElement(Ht,{fallback:e},a.createElement(Zv,{onClickLink:t.onClickLink},e)))},tS=H.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;`,nS=E.default.button`${tS};cursor:pointer;${Re}`,rS=E.default.span`position:absolute;top:0;inset-inline-end:0;width:8px;height:8px;border-radius:999px;background-color:${({$enabled:e})=>e?_.themedColor.secondary:_.color.background300};box-shadow:0 0 0 2px ${_.color.background50};${te.dark`
|
|
452
|
+
box-shadow: 0 0 0 2px ${_.color.background500};
|
|
453
453
|
`}
|
|
454
|
-
`,
|
|
454
|
+
`,sS=E.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;}`,oS=()=>{const{conversation:e}=oe(),{onNavigateToConversationList:t}=Te();if(!t)return null;const n={menu:e.header.menuButton()};return a.createElement(a.Fragment,null,a.createElement(rt,{...n.menu.props,...Oi,type:"menu",size:24,onClick:()=>t()}),n.menu.descriptionNode)},Ba=({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=H.useTheme();return o&&o!==i?a.createElement(Ca,{src:o,size:t,"aria-hidden":"true",onImageError:c}):a.createElement(iS,{"aria-hidden":"true",$size:t,$bgColor:u.colors.base.primary},a.createElement(ee,{type:s,size:t*.55,color:u.colors.base.primaryContrastContent}))},iS=E.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;`,aS=()=>{const{channelSource:e}=Te(),{aiAgentInfo:t,userSession:n}=Ne(),{conversation:r}=oe(),{config:s}=xe(),{announcementsEnabled:o}=nt(),i=e.channel,c=Br({channel:i,userSession:n,aiAgentInfo:t}),u=s.conversation.header.avatarEnabled,d=rs(),m=la({enabled:o,label:c.title}),h={title:r.header.title(c.title,{active:m.enabled,titleId:m.id,initialFocus:!1})};return a.createElement(cS,null,u&&a.createElement(Ba,{channel:i,size:34}),a.createElement(lS,{...h.title.props,...d},c.title))},cS=E.default.div`display:flex;flex-direction:row;align-items:center;gap:6px;min-width:0;width:100%;overflow:hidden;`,lS=E.default(B).attrs({variant:"h2",color:_.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
|
-
`,
|
|
466
|
+
`,uS=e=>{const{components:t}=_t.useContext();return a.createElement(Ua,{start:a.createElement(t.StartArea,null),title:a.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:a.createElement(t.EndArea,null),containerProps:$i})},dS=()=>{const{components:e}=_t.useContext();return a.createElement(e.MenuButton,null)},mS=()=>{const{components:e}=_t.useContext();return a.createElement(e.Title,null)},hS=()=>{const{components:e}=_t.useContext();return a.createElement(gS,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))},_t=qe({template:uS,components:{StartArea:dS,TitleArea:mS,EndArea:hS,MenuButton:oS,Title:aS,MemoryIndicator:Jv,HandoffButton:Xv,ConversationCloseButton:Pv,ExpandButton:Fv,CloseButton:$v}}),fS=()=>{const{Template:e}=_t.useContext();return a.createElement(e,{titleAlign:"start"})},gS=E.default.div`display:flex;gap:10px;align-items:center;justify-content:center;`,ss=({children:e,onNavigateToConversationList:t,channelUrl:n,onClearChannelUrl:r,shouldMarkAsRead:s,shouldInitializeConversation:o,announcementsEnabled:i=!0,conversationStatsEnabled:c,initialFocusTarget:u,style:d,closedChannelUrl:m,onClearClosedChannelUrl:h})=>{const{Template:f}=Bn.useContext();return a.createElement(ia,{onNavigateToConversationList:t,channelUrl:n??m,onClearChannelUrl:r??h,conversationStatsEnabled:c,shouldMarkAsRead:s,shouldInitializeConversation:o},a.createElement(pr,null,a.createElement(pr.Consumer,null,g=>a.createElement(yf,{announcementsEnabled:i},a.createElement(pS,null),a.createElement(_S,null),a.createElement(ES,{style:d,dragHandlers:g,initialFocusTarget:u},a.createElement(f,null)),e))))},pS=()=>(yg(),null),_S=()=>(Fg(),Rg(),Dg(),null),ES=({style:e,dragHandlers:t,initialFocusTarget:n,children:r})=>{const s=l.useRef(null);return Sg(s,n),a.createElement(bS,{ref:s,style:e,...t},r)},CS=e=>{const{components:t}=Bn.useContext();return a.createElement(a.Fragment,null,a.createElement(t.Header,null),a.createElement(t.Body,null),a.createElement(t.Footer,null))},Bn=qe({template:CS,components:{Header:fS,Body:jb,Footer:xv}}),bS=E.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,Ha=ve("ConversationListAnnouncements",{announcementsEnabled:!0,announceScreenEntry:he}),vS=Ha.Provider,os=Ha.useContext,SS=({children:e,announcementsEnabled:t=!0})=>{const{announceScreenEntry:n}=qr(),r=l.useCallback(o=>{t&&n(o)},[n,t]),s=l.useMemo(()=>({announcementsEnabled:t,announceScreenEntry:r}),[t,r]);return a.createElement(vS,{value:s},e)},{Provider:yS,Context:AS,useContext:Zt}=ve("ConversationList");function Ga({conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:n,onOpenConversationView:r=he,children:s}){return a.createElement(nm,{conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:n},o=>a.createElement(yS,{value:{...o,onOpenConversationView:r}},s))}const TS=e=>{const{announcementsEnabled:t}=os(),{listSource:n}=Zt(),r=qi();ua(e,{enabled:t,ready:n.initialized,suppressed:r})},IS=()=>{const{announceScreenEntry:e,announcementsEnabled:t}=os(),{listSource:n}=Zt(),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])},xS=({channel:e})=>a.createElement(Ba,{channel:e}),yr=99,RS=e=>{var p,b;const{channel:t,onClick:n}=e,{stringSet:r,format:s}=ae(),{userSession:o,aiAgentInfo:i}=Ne(),{conversationList:c}=oe(),u=Br({channel:t,userSession:o,aiAgentInfo:i}),d=Mu(t,{formatMultipleFilesCount:r.CONVERSATION_LIST__MULTIPLE_FILES_COUNT}),m=ku(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=(p=t.lastMessage)!=null&&p.isAdminMessage()?r.CONVERSATION_LIST__SYSTEM_MESSAGE:u.title,g=Fe(t)?r.CONVERSATION_LIST__ENDED:"",C=n?()=>n():void 0,v=c.item({agent:f,status:g,lastMessage:d,time:m,unreadCount:h,onActivate:C});return a.createElement(MS,{"data-testid":"sb-conversation-list-item",$clickable:!!C,...v.props},a.createElement(wS,null,a.createElement(xS,{...e})),a.createElement(kS,null,a.createElement(LS,null,(b=t.lastMessage)!=null&&b.isFileMessage()&&(!t.lastMessage.message||t.lastMessage.name===t.lastMessage.message)?a.createElement(ga,{variant:"subtitle1",color:_.themedColor.textHighEmphasis},d):a.createElement(B,{variant:"subtitle1",color:_.themedColor.textHighEmphasis,maxTextLines:1},d),a.createElement(OS,null,Fe(t)&&a.createElement(a.Fragment,null,a.createElement(B,{variant:"caption1",color:_.themedColor.textMidEmphasis,maxTextLines:1},r.CONVERSATION_LIST__ENDED),a.createElement(NS,null)),a.createElement(B,{variant:"caption2",color:_.themedColor.textLowEmphasis,maxTextLines:1},m))),h>0&&a.createElement(DS,{$count:h},a.createElement(B,{variant:"caption3",color:_.themedColor.textHighEmphasisInverse},h<=yr?h:`${yr}+`))),v.descriptionNode)},is=qe({template:RS,components:{}}),MS=E.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"};`,wS=E.default.div`display:flex;align-items:center;justify-content:center;padding-inline-start:16px;`,kS=E.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 ${_.themedColor.textDisabled};`,LS=E.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;`,OS=E.default.div`display:flex;align-items:center;gap:6px;`,NS=E.default.div`width:2px;height:2px;border-radius:1px;background-color:${_.themedColor.textLowEmphasis};`,DS=E.default.div`display:flex;align-items:center;justify-content:center;height:20px;padding:4px;border-radius:10px;background-color:${_.themedColor.error};${({$count:e})=>e<=yr&&H.css`
|
|
467
467
|
width: 20px;
|
|
468
468
|
`}
|
|
469
|
-
|
|
469
|
+
`,$S=({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(PS,{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(FS,{key:d,role:"listitem"},u)}))},PS=E.default.div`width:100%;height:100%;display:flex;flex-direction:column;flex:1;overflow:auto;overscroll-behavior:contain;`,FS=E.default.div`flex-shrink:0;`,US=()=>{const{stringSet:e}=ae(),{listSource:t,onOpenConversationView:n}=Zt(),{Template:r}=is.useContext();return t.initialized?t.channels.length===0?a.createElement(Ut,{type:"noChannels",label:e.CONVERSATION_LIST__NO_CONVERSATIONS}):a.createElement($S,{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,Fe(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"})},BS=()=>{const{stringSet:e}=ae(),{_aiAgentSDK:t}=xe(),{language:n,countryCode:r,context:s}=me(),{aiAgentInfo:o,refreshActiveChannel:i,createConversation:c}=Ne(),{onOpenConversationView:u}=Zt(),{conversationList:d}=oe(),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(HS,{...d.footer.button({onActivate:m}).props},a.createElement(GS,{variant:"h1"},e.TALK_TO_AGENT))},HS=E.default.div`background-color:${({theme:e})=>e.colors.base.primary};display:flex;align-items:center;justify-content:center;padding:16px;cursor:pointer;`,GS=E.default(B)`color:${({theme:e})=>e.colors.base.primaryContrastContent};overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,zS=()=>{const{state:e}=me(),{messenger:t}=oe(),n=Mt(),r=()=>{e.setOpened(!1)};return a.createElement(rt,{...t.closeButton().props,type:"close",size:n,onClick:r})},VS=()=>{const{stringSet:e}=ae(),{announcementsEnabled:t}=os(),{conversationList:n}=oe(),r=e.CONVERSATION_LIST__HEADER_TITLE,s=la({enabled:t,label:r}),o={title:n.headerTitle(r,{active:s.enabled,titleId:s.id})};return a.createElement(qS,{forwardedAs:"h2",variant:"h2",color:_.themedColor.textHighEmphasis,...o.title.props},r)},qS=E.default(B)`margin:0;padding:0 4px;min-width:0;width:100%;box-sizing:border-box;text-overflow:ellipsis;overflow:hidden;white-space:nowrap;`,KS=e=>{const{components:t}=wt.useContext();return a.createElement(Ua,{start:a.createElement(t.StartArea,null),title:a.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:a.createElement(t.EndArea,null),containerProps:$i})},YS=()=>null,WS=()=>{const{components:e}=wt.useContext();return a.createElement(e.Title,null)},jS=()=>{const{components:e}=wt.useContext();return a.createElement(e.CloseButton,null)},wt=qe({template:KS,components:{StartArea:YS,TitleArea:WS,EndArea:jS,Title:VS,CloseButton:zS}}),XS=()=>{const{Template:e}=wt.useContext();return a.createElement(e,{titleAlign:"start"})},ZS=()=>(IS(),null),as=({conversationListLimit:e,conversationListFilter:t,children:n,onOpenConversationView:r,announcementsEnabled:s=!0,conversationListStatsEnabled:o,style:i})=>{const{Template:c}=Hn.useContext();return a.createElement(Ga,{conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:o,onOpenConversationView:r},a.createElement(SS,{announcementsEnabled:s},a.createElement(ZS,null),a.createElement(JS,{style:i},a.createElement(c,null)),n))},JS=({style:e,children:t})=>{const n=l.useRef(null);return TS(n),a.createElement(ey,{ref:n,style:e},t)},QS=()=>{const{components:e}=Hn.useContext();return a.createElement(a.Fragment,null,a.createElement(e.Header,null),a.createElement(e.Body,null),a.createElement(e.Footer,null))},Hn=qe({template:QS,components:{Header:XS,Body:US,Footer:BS}}),ey=E.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,ty=H.css`:where(#${Se.ENTRY}) :not(code *){font-family:'Roboto',sans-serif;box-sizing:border-box;}`,ny=[ty,jh,Xh],ry=(e,...t)=>H.createGlobalStyle(e,...ny,...t),sy=ry``,oy=Ru(Bn,pt,Rt,Pn,Un,Hn,_t,is,wt,Fn,On),iy=typeof __SBA_USE_MESSAGE_TEMPLATE__>"u"||__SBA_USE_MESSAGE_TEMPLATE__;function za({appearance:e,rootElement:t,logger:n,language:r,languageCode:s,stringSet:o,children:i,messageTemplate:c,icons:u,theme:d,entryElement:m,modalRootElement:h}){pf(iy?$h:"",t);const[f,g]=l.useState(null),C=l.useCallback(b=>{g(y=>y===b?y:b)},[]),v=m??f,p=a.createElement(H.StyleSheetManager,{target:t},a.createElement(hf,{rootElement:t,logger:n,appearance:e,theme:d},a.createElement(Bh,{rootElement:t,boundaryElement:v},a.createElement(im,{internalVariables:c==null?void 0:c.__internalVariables},a.createElement(Wh,{stringSet:o,logger:n,language:r,languageCode:s},a.createElement(df,{icons:u},a.createElement(oy,null,a.createElement(Fh,{entryElement:v,modalRootElement:h,rootElement:t},i),a.createElement(sy,null))))))));return m?p:a.createElement("div",{ref:C,style:{display:"contents"}},p)}const ay=()=>{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}},cs=l.forwardRef(function({rootElement:t=document.body,logLevel:n=Ce.LogLevel.WARN,language:r=navigator.language,userSessionInfo:s,children:o,chatParams:i,icons:c,...u},d){var p,b,y;Pt.level!==n&&(Pt.level=n);const{entryElement:m,modalRootElement:h,setEntryElement:f,setModalRootElement:g}=ay();gf("https://fonts.googleapis.com/css2?family=Roboto&display=swap",t);const C=Gi(r),v=zi.has(C)?C:Wt;return a.createElement("div",{ref:f,id:Se.ENTRY,lang:v,style:{width:"fit-content",height:"fit-content",...u.entryStyle}},m&&h&&a.createElement(za,{logger:Pt,rootElement:t,appearance:(p=u.agentPreviewConfigs)==null?void 0:p.appearance,stringSet:u.stringSet,language:v,messageTemplate:u.messageTemplate,icons:c,theme:u.theme,entryElement:m,modalRootElement:h},a.createElement(jf,{rootElement:t,language:r,logger:Pt,dispatcher:Va,chatParams:{...i,...u.customApiHost&&{customApiHost:u.customApiHost},...u.customWebSocketHost&&{customWebSocketHost:u.customWebSocketHost}},chatSDK:u.customChatSDK,_forceCreateChannel:(b=u.agentPreviewConfigs)==null?void 0:b.forceCreateChannel,_agentVersion:(y=u.agentPreviewConfigs)==null?void 0:y.agentVersion,...u},a.createElement(rg,{ref:d,userSessionInfo:s},a.createElement(ev,{...u._UNSAFE_INTERNAL_dashboardTester},a.createElement(vf,null,o))))),a.createElement("div",{ref:g,id:Se.MODAL_ROOT,dir:u.dir}))}),Pt=new ri(Ce.LogLevel.WARN),Va=new ei(Pt),{Provider:cy,useContext:Jt}=ve("PageChildren"),qa=({children:e})=>{const[t,n]=l.useState(()=>ss),[r,s]=l.useState(null),[o,i]=l.useState(()=>as),[c,u]=l.useState(null),d=l.useCallback(h=>{n(()=>h)},[]),m=l.useCallback(h=>{i(()=>h)},[]);return a.createElement(cy,{value:{conversationComponent:t,setConversationComponent:d,conversationChildren:r,setConversationChildren:s,conversationListComponent:o,setConversationListComponent:m,conversationListChildren:c,setConversationListChildren:u}},e)},ls=(e,t)=>e?{role:"dialog","aria-modal":"true",...t?{"aria-labelledby":Se.WINDOW_TITLE}:{"aria-label":"Messenger"}}:{"aria-hidden":"true",inert:!0},Ka=({children:e,isOpened:t,zIndex:n=ft.WINDOW})=>a.createElement(jr,null,a.createElement(ly,{isOpened:t,zIndex:n},e)),ly=({children:e,isOpened:t,zIndex:n=ft.WINDOW})=>{const{dir:r,rootElement:s}=me(),o=ct(s,!0),i=l.useRef(null),{hasWindowTitleReference:c,isWindowNameReady:u}=Dn();return Ln(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(uy,{ref:i,id:Se.WINDOW,dir:r,...ls(t,c),$visible:t,$zIndex:n},e)},uy=E.default.div`width:100%;height:100%;position:fixed;top:0;left:0;z-index:${({$zIndex:e})=>e};visibility:${({$visible:e})=>e?"visible":"hidden"};`,dy=48,my=2/3,Ho=12;function Ya({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=dy,hasUnread:f=!1}){const g=va(),C=d&&!g,v=dr(m),p=Math.round(h*my);return a.createElement(gy,{dir:u,id:Se.LAUNCHER,className:e,"aria-label":s,"aria-describedby":o,onClick:r,$animated:C,$backgroundColor:m,$prefersReducedMotion:g,$size:h},a.createElement(py,{$isOpened:n,$animated:C,$fillColor:v,$iconSize:p,$prefersReducedMotion:g},a.createElement(Go.Open,{url:c,isDefaultIcon:i==="default_icon",size:p})),a.createElement(_y,{$isOpened:n,$animated:C,$fillColor:v,$iconSize:p,$prefersReducedMotion:g},a.createElement(Go.Close,{size:p})),f&&a.createElement(Ey,null),t)}const hy=H.css`&:hover{transition:transform 250ms cubic-bezier(0.33,0,0,1);transform:scale(1.1);}&:active{transform:scale(0.8);}`,fy=H.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%)"};}}`,Wa=H.css`svg{width:${({$iconSize:e})=>e}px;height:${({$iconSize:e})=>e}px;${({$fillColor:e})=>H.css`
|
|
470
470
|
ellipse,
|
|
471
471
|
path {
|
|
472
472
|
fill: ${e};
|
|
@@ -476,7 +476,7 @@
|
|
|
476
476
|
}
|
|
477
477
|
`}
|
|
478
478
|
}
|
|
479
|
-
`,
|
|
479
|
+
`,gy=E.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&&hy}`,ja=E.default.span.attrs({"aria-hidden":"true"})`
|
|
480
480
|
position: absolute;
|
|
481
481
|
width: 100%;
|
|
482
482
|
height: 100%;
|
|
@@ -486,23 +486,23 @@
|
|
|
486
486
|
display: flex;
|
|
487
487
|
justify-content: center;
|
|
488
488
|
align-items: center;
|
|
489
|
-
`,
|
|
489
|
+
`,py=E.default(ja)`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)")};${fy}${Wa}`,_y=E.default(ja)`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)")};${Wa}`,Ey=E.default.span.attrs({"aria-hidden":"true"})`
|
|
490
490
|
position: absolute;
|
|
491
491
|
top: 1px;
|
|
492
492
|
inset-inline-end: 1px;
|
|
493
|
-
width: ${
|
|
494
|
-
height: ${
|
|
493
|
+
width: ${Ho}px;
|
|
494
|
+
height: ${Ho}px;
|
|
495
495
|
border-radius: 50%;
|
|
496
|
-
background-color: ${
|
|
497
|
-
`,
|
|
496
|
+
background-color: ${_.themedColor.error};
|
|
497
|
+
`,Go={Open:e=>e.url?a.createElement("img",{src:e.url,alt:"","data-default-icon":e.isDefaultIcon}):a.createElement(ee,{size:e.size,type:"delight"}),Close:({size:e})=>a.createElement(ee,{size:e,type:"chevron-down"})};function Xa({className:e,size:t,entryPoint:n="Conversation",activeRoute:r}){const{colors:s}=H.useTheme(),{chatSDK:o,config:i,dir:c,state:u}=me(),{resolveElement:d}=zr(),{launcher:m}=oe(),{launcherInfo:h}=Ne(),f=i.launcher.unreadBadgeEnabled,g=bi(),C=Um(o,{enabled:f,opened:u.opened,filter:g}),v=(r??n)==="ConversationList",p={launcher:m.button({isOpened:u.opened,opensConversationList:v})};Fm("launcher_toggle"),by();const b=()=>{Ie(()=>{const T=d(Se.WINDOW),R=T?Qi(T):null;R==null||R.focus()})},y=()=>{Ie(()=>{var T;(T=d(Se.LAUNCHER))==null||T.focus()})},A=()=>{const T=!u.opened;u.setOpened(T),T?b():y()};return a.createElement(Ya,{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&&C,...p.launcher.props},p.launcher.descriptionNode)}const Cy=1e3*60;function by(){const{chatSDK:e,state:t,logger:n,enableAutoDisconnectInLauncher:r}=me(),s=l.useRef(null);l.useEffect(()=>{if(!r)return;function o(){s.current&&(clearTimeout(s.current),s.current=null)}function i(){e.connectionState===Ce.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")},Cy)}t.opened?i():(c(),n.debug("useSDKInactivityTimeout: schedule disconnect"))},[r,e,t.opened])}const Za=l.createContext(null);function us(){const e=l.useContext(Za);if(!e)throw new Error("useNavigator() must be used within <Navigator />");return e}function Ja({children:e}){const t=us();return typeof e=="function"?e(t):a.createElement(a.Fragment,null,e)}const vy=H.keyframes`0%{transform:translateY(40px);opacity:0;}100%{transform:translateY(0px);opacity:1;}`,Sy=H.keyframes`0%{transform:translateY(0px);opacity:1;}100%{transform:translateY(40px);opacity:0;}`,yy=H.css`animation-name:${vy};animation-duration:0.3s;animation-fill-mode:forwards;`,Ay=H.css``,Ty=H.css`animation-name:${Sy};animation-duration:0.3s;animation-fill-mode:forwards;`,Iy=H.css`visibility:hidden;`,xy=E.default.div`position:absolute;top:0;left:0;width:100%;height:100%;${({$transitionState:e})=>{switch(e){case"entering":return yy;case"entered":return Ay;case"exiting":return Ty;case"exited":return Iy;default:return""}}}${({$active:e})=>e?H.css`
|
|
498
498
|
z-index: 999;
|
|
499
|
-
`:
|
|
500
|
-
`;function
|
|
499
|
+
`:H.css`z-index:1;pointer-events:none;`}
|
|
500
|
+
`;function gn({initialId:e,children:t}){const[n,r]=l.useState([e]),s=n[n.length-1],o=l.useCallback((p,b)=>{r(y=>[...y,p]),h(y=>({...y,[p]:!0})),b!=null&&b.reset&&v(y=>({...y,[p]:(y[p]||0)+1})),g(y=>({...y,[p]:"entering"})),setTimeout(()=>{g(y=>({...y,[p]:"entered"}))},300)},[]),i=l.useCallback(()=>{r(p=>{if(p.length<=1)return p;const b=p[p.length-1];return g(y=>({...y,[b]:"exiting"})),setTimeout(()=>{g(y=>({...y,[b]:"exited"})),r(y=>y.slice(0,-1))},300),p})},[]),c=l.useMemo(()=>({navigation:{navigate:o,pop:i},activeScreenId:s}),[o,i,s]),u=l.useMemo(()=>l.Children.toArray(t).filter(p=>p.type===Ja),[t]),d=l.useMemo(()=>{const p={};return u.forEach(b=>{const{id:y,lazy:A,children:T}=b.props;p[y]={lazy:A,element:typeof T=="function"?T(c):T}}),p},[u,c]),[m,h]=l.useState(()=>{const p={};return Object.entries(d).forEach(([b,{lazy:y}])=>{y===!1&&(p[b]=!0)}),p[e]=!0,p}),[f,g]=l.useState(()=>{const p={};return Object.keys(d).forEach(b=>{b===e?p[b]="entered":p[b]="exited"}),p}),[C,v]=l.useState({});return a.createElement(Za.Provider,{value:c},a.createElement(Ry,null,Object.keys(d).map(p=>{var T;if(!m[p])return null;const b=f[p]||"exited",y=p===s,A=`${p}-${C[p]||0}`;return a.createElement(xy,{key:A,$transitionState:b,$active:y,"aria-hidden":y?void 0:!0,inert:y?void 0:!0},(T=d[p])==null?void 0:T.element)})))}const Ry=E.default.div`position:relative;width:100%;height:100%;`;gn.Screen=Ja;const Ge={conv:"conv",convList:"conv-list"},My=e=>e===Ge.convList?"ConversationList":"Conversation",Qa=({isOpened:e,entryPoint:t,selectedChannelUrl:n,setSelectedChannelUrl:r,onActiveRouteChange:s})=>{const{conversationComponent:o,conversationChildren:i,conversationListComponent:c,conversationListChildren:u}=Jt(),[d,m]=l.useState(),h=(()=>{switch(t){case"Conversation":return Ge.conv;case"ConversationList":return Ge.convList;default:return Ge.conv}})(),f=a.createElement(a.Fragment,null,a.createElement(wy,{onOpenConversationView:(g,C)=>{r(C),m(void 0),g.navigate(Ge.conv)}}),a.createElement(ky,{onActiveRouteChange:s}));return a.createElement(gn,{initialId:h},a.createElement(gn.Screen,{id:Ge.conv},({navigation:g,activeScreenId:C})=>{const v=C===Ge.conv,p=e&&v;return a.createElement(a.Fragment,null,f,a.createElement(o,{key:n,channelUrl:n,onClearChannelUrl:()=>r(void 0),onNavigateToConversationList:()=>{m(void 0),g.navigate(Ge.convList)},announcementsEnabled:p,conversationStatsEnabled:p,shouldMarkAsRead:p,shouldInitializeConversation:p,initialFocusTarget:d},i))}),a.createElement(gn.Screen,{id:Ge.convList,lazy:!0},({navigation:g,activeScreenId:C})=>{const v=C===Ge.convList,p=e&&v;return a.createElement(a.Fragment,null,f,a.createElement(c,{announcementsEnabled:p,conversationListStatsEnabled:p,onOpenConversationView:(b,y,A)=>{r(b),m(A==null?void 0:A.initialFocusTarget),g.navigate(Ge.conv)}},u))}))},wy=({onOpenConversationView:e})=>{const{registerOnJoinedProactiveConversation:t}=Ne(),{navigation:n}=us();return t(({channel:r})=>{e(n,r.url)}),null},ky=({onActiveRouteChange:e})=>{const{activeScreenId:t}=us();return l.useEffect(()=>{e==null||e(My(t))},[t,e]),null},Ly=({isExpanded:e,isOpened:t,children:n,launcher:r})=>a.createElement(jr,null,a.createElement(Oy,{isExpanded:e,isOpened:t,launcher:r},n)),Oy=({isExpanded:e,isOpened:t,children:n,launcher:r})=>{const{dir:s}=me(),o=l.useRef(null),{hasWindowTitleReference:i,isWindowNameReady:c}=Dn();return Ln(t,o,{nameReady:c}),a.createElement(Ny,null,a.createElement(Dy,{ref:o,dir:s,id:Se.WINDOW,...ls(t,i),$isExpanded:e,$isOpened:t},n),r)},Ny=E.default.div`display:flex;flex-direction:column;gap:8px;align-items:flex-end;`,Dy=E.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&&Py};${({$isExpanded:e})=>e&&$y};`,$y=H.css`width:743px;height:723px;`,Py=H.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;`,Fy=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?Ka:Ly;return a.createElement(cs,{enableExpandButton:!s,ref:r,...n},a.createElement(ta,null,({state:m})=>a.createElement(qa,null,a.createElement(d,{isExpanded:m.expanded,isOpened:m.opened,...s&&{zIndex:"auto"},launcher:a.createElement(Xa,{entryPoint:n.entryPoint,activeRoute:c})},a.createElement(Qa,{isOpened:m.opened,entryPoint:n.entryPoint,selectedChannelUrl:o,setSelectedChannelUrl:i,onActiveRouteChange:u})),e)))}),{Provider:Uy,useContext:ds}=ve("FixedMessengerStyle");function ec(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: ${Ye(i)}`;break;case"end":d=`inset-inline-end: ${Ye(c)}`;break}switch(t){case"top":u=`top: calc(${Ye(s)} + ${r}px)`;break;case"bottom":u=`bottom: calc(${Ye(o)} + ${r}px)`;break}return H.css`${u};${d};`}function By(e){const{horizontal:t,vertical:n,margin:r,launcherSize:s}=ds();return a.createElement(Hy,{...e,size:s,$horizontal:t,$vertical:n,$margin:r})}const Hy=E.default(Xa)`position:fixed;z-index:${ft.LAUNCHER};${({$horizontal:e,$vertical:t,$margin:n})=>ec(e,t,n)};`,Gy=({isExpanded:e,isOpened:t,children:n})=>a.createElement(jr,null,a.createElement(zy,{isExpanded:e,isOpened:t},n)),zy=({isExpanded:e,isOpened:t,children:n})=>{const{dir:r}=me(),{horizontal:s,vertical:o,margin:i,launcherSize:c}=ds(),u=l.useRef(null),{hasWindowTitleReference:d,isWindowNameReady:m}=Dn();return Ln(t,u,{nameReady:m}),a.createElement(Vy,{ref:u,dir:r,id:Se.WINDOW,...ls(t,d),$isExpanded:e,$isOpened:t,$horizontal:s,$vertical:o,$margin:i,$launcherSize:c},n)},Vy=E.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})=>ec(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}`};
|
|
504
504
|
}
|
|
505
505
|
|
|
506
|
-
${({$isOpened:e})=>e&&
|
|
507
|
-
${({$isExpanded:e})=>e&&
|
|
508
|
-
`,
|
|
506
|
+
${({$isOpened:e})=>e&&Ky};
|
|
507
|
+
${({$isExpanded:e})=>e&&qy};
|
|
508
|
+
`,qy=H.css`width:743px;height:723px;`,Ky=H.css`z-index:${ft.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;`,tc={top:24,bottom:24,start:24,end:24},Yy=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(tc),[f,g]=l.useState(48),C=jt(),v=C?Ka:Gy,{horizontal:p,vertical:b}=l.useMemo(()=>{const[y,A]=u.split("-");return{horizontal:y==="start"?"start":"end",vertical:A==="top"?"top":"bottom"}},[u]);return a.createElement(cs,{enableExpandButton:!C,ref:r,...n},a.createElement(ta,null,({state:y})=>a.createElement(Uy,{value:{horizontal:p,vertical:b,margin:m,launcherSize:f,setPosition:d,setMargin:h,setLauncherSize:g}},a.createElement(qa,null,a.createElement(v,{isExpanded:y.expanded,isOpened:y.opened},a.createElement(Qa,{isOpened:y.opened,entryPoint:n.entryPoint,selectedChannelUrl:s,setSelectedChannelUrl:o,onActiveRouteChange:c})),a.createElement(By,{entryPoint:n.entryPoint,activeRoute:i}),e))))}),Wy=e=>{var s,o,i,c;const{setPosition:t,setMargin:n,setLauncherSize:r}=ds();return l.useLayoutEffect(()=>{e.position&&t(e.position),e.margin&&n({...tc,...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},jy=({children:e})=>{const{setConversationChildren:t}=Jt();return l.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},Xy=({component:e})=>{const{setConversationComponent:t}=Jt();return l.useLayoutEffect(()=>(t(e),()=>t(ss)),[e,t]),null},Zy=({children:e})=>{const{setConversationListChildren:t}=Jt();return l.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},Jy=({component:e})=>{const{setConversationListComponent:t}=Jt();return l.useLayoutEffect(()=>(t(e),()=>t(as)),[e,t]),null},Qy=Object.assign(Yy,{Style:Wy,Conversation:Xy,ConversationChildren:jy,ConversationList:Jy,ConversationListChildren:Zy}),eA=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])};di.set(Ce.SendbirdPlatform.JS,{deviceOSPlatform:Rc()?Ce.DeviceOsPlatform.MOBILE_WEB:Ce.DeviceOsPlatform.WEB,messengerVersion:wh,keyValueStorage:Nh(),networkStateAdapter:Oh(),foregroundStateAdapter:Lh});exports.ANCHOR_REL=Gr;exports.AgentProviderContainer=cs;exports.AgentUIProviderContainer=za;exports.AnonymousSessionInfo=ar;exports.CSATType=je;exports.Commands=it;exports.ConnectionDelayLayout=On;exports.Conversation=ss;exports.ConversationContext=pg;exports.ConversationContextProvider=ia;exports.ConversationHeaderLayout=_t;exports.ConversationLayout=Bn;exports.ConversationList=as;exports.ConversationListContext=AS;exports.ConversationListContextProvider=Ga;exports.ConversationListHeaderLayout=wt;exports.ConversationListItemLayout=is;exports.ConversationListLayout=Hn;exports.DefaultMessenger=Fy;exports.DeskTicketPriority=Dr;exports.DeskTicketStatus=Nr;exports.FixedMessenger=Qy;exports.ID_INCOMING=Je;exports.IncomingMessageLayout=pt;exports.LauncherBase=Ya;exports.LogLevel=Mr;exports.ManualSessionInfo=si;exports.MessageListUILayout=Un;exports.MessageLogs=Oa;exports.OutgoingMessageLayout=Rt;exports.PlaceholderLayout=Fn;exports.SystemMessageLayout=Pn;exports.cssVars=_;exports.escapeMarkdownSyntax=Ic;exports.flattenObject=cu;exports.mapCommonStringsToReactFormat=Hi;exports.messengerDispatcher=Va;exports.noop=he;exports.parseToMessageTemplate=li;exports.parseToUITemplate=iu;exports.pickColorByTheme=au;exports.replaceVariablesAsync=uu;exports.replaceVariablesSync=lu;exports.useAIAgentContext=xe;exports.useConversationContext=Te;exports.useConversationListContext=Zt;exports.useLocalizationContext=ae;exports.useMessageTemplateFetchingContext=om;exports.useMessengerContext=me;exports.useMessengerSessionContext=Ne;exports.useMessengerThemeContext=Yi;exports.useRefreshActiveChannel=eA;
|