@sendbird/ai-agent-messenger-react 1.30.0 → 1.31.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/DP95uu-Y.cjs +1 -0
- package/dist/es/ClXsn-JF.js +5 -0
- package/dist/index.cjs +98 -98
- package/dist/index.d.ts +111 -79
- package/dist/index.js +3652 -3630
- package/package.json +6 -6
package/dist/index.cjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
"use strict";var da=Object.defineProperty;var ma=(e,t,n)=>t in e?da(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var A=(e,t,n)=>ma(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const he=require("@sendbird/chat"),u=require("react"),D=require("styled-components"),Xe=require("date-fns"),fa=require("date-fns/locale/en-US"),Ue=require("@sendbird/chat/message"),ga=require("react-dom"),be=require("@sendbird/chat/aiAgent"),ze=require("@sendbird/chat/groupChannel"),ha=require("date-fns/isSameDay"),pa=require("dompurify"),tr=e=>e&&e.__esModule?e:{default:e};function _a(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 Ea=tr(he),i=_a(u),p=tr(D),ls=tr(pa),ct="sb-agent",cs="KEY_IMG_ASPECT_RATIO",Un="*/*",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 Jt=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(Jt||{}),Tt=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(Tt||{});const us=e=>{var t;return!!((t=e==null?void 0:e.extendedMessagePayload)!=null&&t.steward)},ba=e=>e===Tt.COMPLETED||e===Tt.CANCELED?e:Tt.IN_PROGRESS,Sn=e=>Qe(e)&&!us(e),Qe=e=>!!e&&"sender"in e,Ca=e=>Qe(e)?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId),va=(e,t,n,r=!0)=>{if(!r||!Sn(e))return"single";const o=()=>{if(!Sn(t))return!1;const c=t.sender.userId===e.sender.userId,d=Xe.isSameMinute(t.createdAt,e.createdAt);return c&&d},s=()=>{if(!Sn(n))return!1;const c=n.sender.userId===e.sender.userId,d=Xe.isSameMinute(n.createdAt,e.createdAt);return c&&d},a=o(),l=s();return a&&l?"middle":a?"bottom":l?"top":"single"},gt=(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,Ie={isAdmin:e=>e.isAdminMessage(),isCSAT:e=>{var t;return e.isAdminMessage()&&!!((t=e.extendedMessagePayload)!=null&&t.csat)},isSteward:e=>us(e),isIncoming:(e,t)=>Qe(e)&&e.sender.userId!==t,isOutgoing:(e,t)=>Qe(e)&&(e.sender.userId===t||e.sendingStatus===Ue.SendingStatus.PENDING)},He=e=>e.startsWith("image/"),cn=e=>e.startsWith("video/"),ds=({name:e="",mimeType:t=""})=>t==="application/pdf"||/\.pdf$/i.test(e.trim()),nr=(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"},ms=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},un=e=>{switch(e){case"top":case"middle":return ee.GAP_GROUPED;default:return ee.GAP_UNGROUPED}},ya=(e,t)=>{const n=/```(\w+)?\n([\s\S]*?)```/g,r=[];let o=0;return e.replace(n,(s,...a)=>{const[l,c,d]=a;return o<d&&r.push({type:"text",value:e.slice(o,d).trim()}),r.push({type:"code",value:c.trim(),language:l?l.trim():"plaintext"}),o=d+s.length,s}),o<e.length&&r.push({type:"text",value:e.slice(o).trim()}),t?r.map(s=>s.type!=="text"?s:{...s,value:t(s.value)}):r},Sa=e=>e.replace(/\[([^\]]+)\](?!\()/g,"\\[$1\\]"),Aa=e=>e.replace(/([a-zA-Z0-9])_(?=[a-zA-Z0-9])/g,"$1\\_"),xa=e=>e.replace(/~~/g,"\\~\\~"),Ta=e=>{let t=e;return t=Sa(t),t=Aa(t),t=xa(t),t},Ia=typeof navigator<"u"&&navigator.product==="ReactNative",Ur=(e,t)=>{const n=r=>!t||t.length===0?!0:Qe(r)&&t.includes(r.sendingStatus);return Ia?e.find(n):e.findLast(n)};function ge(){}function wa(){const e=typeof navigator<"u"?navigator.userAgent:"",t=/iPad|iPhone|iPod/.test(e),n=/Android/.test(e);return t||n}function Ma(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 Bn=e=>{try{return JSON.parse(e===""?"{}":e)}catch{return{}}},Ve={isStreaming(e){const t=Bn(e.data);return typeof t=="object"&&!!t.stream},isWelcomeMessage(e,t){var n;if(((n=e.extendedMessagePayload)==null?void 0:n.bot_message_type)==="welcome")return!0;if(gt(e,t)){const r=Bn(e.data);return!(r!=null&&r.respond_mesg_id)&&!(r!=null&&r.stream)}return!1},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)}},An=`@${ct}`,ka=({appId:e,aiAgentId:t,storage:n})=>{const r={templateBase:`${An}-template`,template:o=>`${r.templateBase}/templates/${o}`,templateToken:()=>`${r.templateBase}/tokens`,messengerSession:o=>{const s=Ma(`${e}/${t}/${o}`);return`${An}-udata/${s}`},anonUserSession:()=>`${An}-session/${e}/${t}`};return{template:{set:(o,s)=>n.set(r.template(o),s),get:o=>n.get(r.template(o)),setCachedToken:o=>n.set(r.templateToken(),o),getCachedToken:()=>n.get(r.templateToken()),clear:()=>{n.getKeys(r.templateBase).forEach(n.delete)}},messenger:{getSettings:o=>{try{const s=n.get(r.messengerSession(o));return s?JSON.parse(s):null}catch{return null}},setSettings:(o,s)=>{try{delete s.auto_created_user;const a=JSON.stringify(s);n.set(r.messengerSession(o),a)}catch{return}},getAnonUser:()=>{try{const o=n.get(r.anonUserSession());return o?JSON.parse(o):null}catch{return null}},setAnonUser:o=>{try{const s=JSON.stringify(o);n.set(r.anonUserSession(),s)}catch{return}},clear:o=>{try{o&&n.delete(r.messengerSession(o)),n.delete(r.anonUserSession())}catch{return}}}}},fs=(e,t,n={})=>{let r=null,o=null,s=null;const{leading:a=!0,trailing:l=!0}=n,c=(...d)=>{const m=Date.now();if(s===null||m-s>=t)a?(e(...d),s=m):(o=d,s=m);else if(o=d,l&&!r){const f=t-(m-s);r=setTimeout(()=>{o&&l&&(e(...o),s=Date.now()),r=null,o=null},f)}};return c.cancel=()=>{r&&(clearTimeout(r),r=null),o=null,s=null},c},Ra=()=>{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 La{constructor(t){A(this,"_params");this._params={aiAgentChannelFilter:(t==null?void 0:t.aiAgentChannelFilter)??be.AIAgentChannelFilter.INCLUDE,aiAgentConversationStatusFilter:(t==null?void 0:t.aiAgentConversationStatusFilter)??[be.ConversationStatus.OPEN,be.ConversationStatus.CLOSED],aiAgentIds:(t==null?void 0:t.aiAgentIds)??[],deskChannelFilter:(t==null?void 0:t.deskChannelFilter)??be.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:o,aiAgentConversationStatusFilter:s,aiAgentIds:a,deskChannelFilter:l}=this._params;return r!=null&&r.includes(t.url)?!0:t.isAIAgent?!(!t.conversation||o===be.AIAgentChannelFilter.EXCLUDE||a&&a.length>0&&!a.includes(t.conversation.aiAgentId)||s&&s.length>0&&!s.some(d=>{var m;return((m=t.conversation)==null?void 0:m.status)===d})):t.isDesk?l!==be.DeskChannelFilter.EXCLUDE:!1}}class gs extends ze.BaseChannelCollection{constructor(n,r){const o=new La(r.filter),s=n,a=s.aiAgent._manager,l=r.limit??20,c=ze.GroupChannelListOrder.LATEST_LAST_MESSAGE,d={getRemoteChannels:(m,f,g,_)=>a.getMyGroupChannels(m,f.params,_),changeLogSync:m=>{const{aiAgentChannelFilter:f,aiAgentIds:g,deskChannelFilter:_,pinnedChannelUrls:v,copilotConversationOnly:y,copilotSupportChannelUrl:b}=o.params,E={aiAgentChannelFilter:f,aiAgentIds:g,deskChannelFilter:_,pinnedChannelUrls:v,copilotConversationOnly:y,copilotSupportChannelUrl:b};return a.getMyGroupChannelChangeLogs(m,E,ze.GroupChannelEventSource.SYNC_CHANNEL_CHANGELOGS)}};super(s.aiAgent._iid,{filter:o,order:c,limit:l,syncKeyPrefix:"aiAgent",fetcher:d});A(this,"_params");A(this,"_sdk");A(this,"_throttledOnChannelChanged");A(this,"_key");A(this,"_pendingChannels",[]);this._sdk=n,this._params=r,this._key=`clc-${Ra()}`,this._throttledOnChannelChanged=fs(()=>{var _;const m=[...this._pendingChannels];this._pendingChannels=[];const f=new Map;for(const{channel:v,context:y}of m)f.delete(v.url),f.set(v.url,{channel:v,context:y});const g=new Map;for(const{channel:v,context:y}of f.values())g.has(y)||g.set(y,new Map),g.get(y).set(v.url,v);for(const[v,y]of g){const b=Array.from(y.values()),E=(_=this._sdk.currentUser)==null?void 0:_.userId,C=b.filter(x=>this.filter.match(x,E)),S=b.filter(x=>!this.filter.match(x,E)).map(x=>x.url);C.length>0&&this._base._addChannelsToView(C,v,!1),S.length>0&&this._removeChannels(S,v)}},250,{trailing:!0,leading:!0}),this._base._subscribeChannelEvent(this._key,{onUpdate:(m,f)=>{for(const g of m)this._pendingChannels.push({channel:g,context:f});this._throttledOnChannelChanged()},onRemove:(m,f)=>{this._removeChannels(m,f)}})}get _base(){return this}_removeChannels(n,r){const o=new Set(n);this._pendingChannels=this._pendingChannels.filter(({channel:s})=>!o.has(s.url)),this._base._removeChannelsFromView(n,r)}get channels(){var l;const n=((l=this._params.filter)==null?void 0:l.pinnedChannelUrls)??[],r=[],o=new Map(super.channels.map(c=>[c.url,c])),s=new Set;for(const c of n){const d=o.get(c);d&&!s.has(c)&&(r.push(d),s.add(c))}const a=super.channels.filter(c=>!s.has(c.url));return[...r,...a]}setConversationListCollectionHandler(n){super.setGroupChannelCollectionHandler(n)}dispose(){super.dispose(),this._throttledOnChannelChanged.cancel(),this._base._unsubscribeChannelEvent(this._key)}}class hs{constructor(t){A(this,"subscribers",{});this.logger=t}async send(t){const n=Oa(),r=this.subscribers[t.type];if(r){this.logger.debug(`messenger.dispatcher: dispatching command: ${t.type}`,t.payload);const o=r.map(s=>s(t.payload));await Promise.all(o).catch(s=>{this.logger.error(`messenger.dispatcher: error in callback for command: ${t.type}`,s)})}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(o=>o!==n))}}const Oa=()=>{let e=ge,t=ge;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}};var Fe=(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))(Fe||{});class Rt{constructor(t={}){A(this,"payload");this.payload=t}toJSON(){return JSON.stringify({type:this.type,payload:this.payload})}}const Ze={CloseConversation:e=>new Na(e),MessengerSettingsUpdated:e=>new Da(e),ActiveChannelUpdated:e=>new $a(e),AnonymousSessionTokenExpired:()=>new Pa,AuthTokenRefreshed:()=>new Fa};class Na extends Rt{constructor(){super(...arguments);A(this,"type","conv.close")}}class Da extends Rt{constructor(){super(...arguments);A(this,"type","messenger.settings.updated")}}class $a extends Rt{constructor(){super(...arguments);A(this,"type","active.channel.updated")}}class Pa extends Rt{constructor(){super(...arguments);A(this,"type","anon.token.expired")}}class Fa extends Rt{constructor(){super(...arguments);A(this,"type","auth.token.refreshed")}}var rr=(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))(rr||{});class ps{constructor(t){A(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 _s{constructor({userId:t,authToken:n,sessionHandler:r}){A(this,"userId");A(this,"authToken");A(this,"sessionHandler");this.userId=t,this.authToken=n,this.sessionHandler=r}}class Hn{constructor(){A(this,"userId");A(this,"authToken");A(this,"sessionHandler")}}const Ua=e=>({onSessionTokenRequired:t=>{t(null),e.send(Ze.AnonymousSessionTokenExpired())}}),Ba="ai_agent:stats",Ha="conversation_initial_render",Ga=800220;var ve=(e=>(e.AUTH="auth_duration",e.GET_CHANNEL="get_channel_duration",e.GET_MESSAGES="get_messages_duration",e.TOTAL_DURATION="total_duration",e.TOTAL_DURATION_FROM_CACHE="total_duration_from_cache",e))(ve||{});class za{constructor(){A(this,"timers",new Map);A(this,"committed",!1);A(this,"commitCallback",null);A(this,"conversationId",null);A(this,"channelUrl",null);A(this,"errorCode",null);A(this,"errorDescription",null);A(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??Ga,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:Date.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:Date.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(Ba,t)):!1}}class Va extends za{constructor(){super(...arguments);A(this,"presentMethod","direct_present")}setPresentMethod(n){return this.presentMethod=n,this}getMetricKey(){return Ha}buildPayload(){const n=this.getDuration(ve.AUTH),r=this.getDuration(ve.GET_CHANNEL),o=this.getDuration(ve.GET_MESSAGES),s=this.getDuration(ve.TOTAL_DURATION_FROM_CACHE),a=this.getDuration(ve.TOTAL_DURATION),l={...this.extraData,present_method:this.presentMethod,...n!==null&&{auth_duration:n},...r!==null&&{get_channel_duration:r},...o!==null&&{get_messages_duration:o},...s!==null&&{total_duration_from_cache:s}},c={key:this.getMetricKey(),value:a!==null?String(a):"0"};return this.conversationId!==null&&(c.conversation_id=this.conversationId),this.errorCode!==null&&(c.error_code=this.errorCode),this.errorDescription!==null&&(c.error_description=this.errorDescription),Object.keys(l).length>0&&(c.extra=l),c}}class Ya{constructor(t){A(this,"commitCallback");A(this,"presentMethod","direct_present");A(this,"stats",null);this.commitCallback=t}getOrCreateStats(){return(!this.stats||this.stats.isCommitted())&&(this.stats=new Va().setCommitCallback(this.commitCallback).setPresentMethod(this.presentMethod)),this.stats}onAuthStart(){this.getOrCreateStats().startTimer(ve.TOTAL_DURATION).startTimer(ve.TOTAL_DURATION_FROM_CACHE).startTimer(ve.AUTH)}onAuthComplete(){var t;(t=this.stats)==null||t.stopTimer(ve.AUTH)}onAuthError(t){this.stats&&!this.stats.isCommitted()&&this.stats.stopTimer(ve.AUTH).setError(t instanceof he.SendbirdError?t.code:void 0,t.message).stopTimer(ve.TOTAL_DURATION).commit()}onGetChannelStart(){var t;(t=this.stats)==null||t.startTimer(ve.GET_CHANNEL)}onGetChannelComplete(t){this.stats&&(this.stats.stopTimer(ve.GET_CHANNEL),t!==void 0&&this.stats.setConversationId(t),this.stats.startTimer(ve.GET_MESSAGES))}onGetChannelError(t){this.stats&&!this.stats.isCommitted()&&this.stats.stopTimer(ve.GET_CHANNEL).setError(t instanceof he.SendbirdError?t.code:void 0,t.message).stopTimer(ve.TOTAL_DURATION).commit()}onCacheResult(t){this.stats&&!this.stats.isCommitted()&&(t&&this.stats.setError(t instanceof he.SendbirdError?t.code:void 0,t.message),this.stats.stopTimer(ve.TOTAL_DURATION_FROM_CACHE))}onApiResult(t){this.stats&&!this.stats.isCommitted()&&(t&&this.stats.setError(t instanceof he.SendbirdError?t.code:void 0,t.message),this.stats.stopTimer(ve.TOTAL_DURATION).stopTimer(ve.GET_MESSAGES).commit())}setChannelUrl(t){var n;(n=this.stats)==null||n.setChannelUrl(t)}cleanup(){var t;(t=this.stats)==null||t.commit()}setPresentMethod(t){var n;this.presentMethod=t,(n=this.stats)==null||n.setPresentMethod(t)}clear(){this.stats=null}}function Wa(){let e=null,t=0;const n=(r,o)=>{if((e==null?void 0:e.key)===r)return e.promise;const s=++t,l=(e?e.promise.catch(()=>{}).then(()=>o()):o()).finally(()=>{(e==null?void 0:e.id)===s&&(e=null)});return e={key:r,id:s,promise:l},l};return n.isPending=()=>e!==null,n}const Es=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0)),Br={isTalkToAgentViewEnabled:!0,scrollMode:"auto",newMessageIndicatorEnabled:!0,senderAvatarEnabled:!0},or={conversation:{...Br,messageAlertSoundEnabled:!1,list:{...Br,markdownImageRenderMode:"default",markdownLinkRenderMode:"default"},header:{avatarEnabled:!0},input:{camera:{photoEnabled:!0},gallery:{photoEnabled:!0},fileEnabled:!0},fileViewer:{downloadEnabled:!0}},launcher:{unreadBadgeEnabled:!1}},Hr=e=>e?{conversation:Ka(e.conversation),launcher:qa(e.launcher)}:or,qa=e=>ut(or.launcher,e),Ka=e=>{const t=or.conversation;if(!e)return t;const{list:n={},header:r={},input:o,fileViewer:s={},messageAlertSoundEnabled:a=t.messageAlertSoundEnabled,...l}=e,{camera:c={},gallery:d={},fileEnabled:m=t.input.fileEnabled}=o??{},f=ut(t.list,l,n);return{...f,messageAlertSoundEnabled:a,list:f,header:ut(t.header,r),input:{camera:ut(t.input.camera,c),gallery:ut(t.input.gallery,d),fileEnabled:m},fileViewer:ut(t.fileViewer,s)}},ut=(e,...t)=>{const n={...e};for(const r of t)r&&Object.assign(n,Es(r));return n},ja=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}),Xa=e=>({type:e.image_type||"default_icon",imageUrl:e.image_url}),Gn=e=>({enabled:e.enabled,showIndicator:e.show_indicator,toggleAllowed:e.toggle_allowed,deleteOnOff:e.delete_on_off,consentDialog:e.consent_dialog}),bs=(e,t)=>{if(e)return e.members.filter(n=>n.userId!==t).sort((n,r)=>r.joinedAt-n.joinedAt)[0]},Le=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===be.ConversationStatus.CLOSED||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="closed")},sr=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===be.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,o;return typeof(((n=e==null?void 0:e.conversation)==null?void 0:n.handedOverAt)??((o=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff)==null?void 0:o.timestamp))=="number"}function Za(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 Ja(e){var t;if(((t=e==null?void 0:e.resolution)==null?void 0:t.determinedBy)==="user")return e.resolution.isResolved}function Cs(e){return!!e&&e<=Date.now()}function Qa(e){return!e.title}function el(e,t){var n;if(e)return Qa(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 tl{constructor(){A(this,"_channelHandlerId",null);A(this,"_connectionHandlerId",null);A(this,"_handleActiveChannelChangedThrottled",null);A(this,"_setupChannelHandler",()=>{const t=Date.now();this._channelHandlerId=`aiagent_channel_${t}`,this._connectionHandlerId=`aiagent_connection_${t}`,this._handleActiveChannelChangedThrottled=fs(o=>{var s,a;(a=this._session)==null||a._updateActiveChannel({url:o.url,status:Le(o)?"closed":"open",conversationStatus:(s=o.conversation)==null?void 0:s.status}),this._logger.debug("AIAgentEventManager: activeChannel updated",o.url)},250,{leading:!0,trailing:!1});const n=new ze.GroupChannelHandler({onChannelChanged:o=>{var s,a;o.isGroupChannel()&&o.url===((s=this._session)==null?void 0:s.activeChannel.url)&&((a=this._handleActiveChannelChangedThrottled)==null||a.call(this,o))}}),r=new he.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})});A(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")});A(this,"_syncActiveChannelOnReconnect",async()=>{var n,r,o;const t=(n=this._session)==null?void 0:n.activeChannel.url;if(t)try{const a=await(await this._chatClient.chatSDK.groupChannel.getChannel(t)).refresh();a.url===t&&((o=this._session)==null||o._updateActiveChannel({url:a.url,status:Le(a)?"closed":"open",conversationStatus:(r=a.conversation)==null?void 0:r.status}),this._logger.debug("AIAgentEventManager: activeChannel synced on reconnect",a.url))}catch(s){this._logger.error("AIAgentEventManager: failed to sync activeChannel on reconnect",s)}});A(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)}});A(this,"onMessengerSettingsUpdated",t=>(this._dispatcher.subscribe(Fe.MessengerSettingsUpdated,t),()=>{this._dispatcher.unsubscribe(Fe.MessengerSettingsUpdated,t)}));A(this,"onActiveChannelUpdated",t=>(this._dispatcher.subscribe(Fe.ActiveChannelUpdated,t),()=>{this._dispatcher.unsubscribe(Fe.ActiveChannelUpdated,t)}));A(this,"onAuthTokenRefreshed",t=>(this._dispatcher.subscribe(Fe.AuthTokenRefreshed,t),()=>{this._dispatcher.unsubscribe(Fe.AuthTokenRefreshed,t)}))}}class nl{constructor(t){A(this,"_sdkUser");A(this,"_userSession");A(this,"_dispatcher");A(this,"_activeChannel");A(this,"_updateActiveChannel",t=>{this._activeChannel=t,this._dispatcher.send(Ze.ActiveChannelUpdated({channelUrl:t.url,status:t.status,conversationStatus:t.conversationStatus}))});A(this,"_updateAuthToken",t=>{this._userSession.authToken=t,this._dispatcher.send(Ze.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 vs=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)}},ys=e=>JSON.parse(e),rl=e=>JSON.parse(e);function ol(e,t){const[n,r]=t.split(",").map(o=>o.trim());return e==="dark"&&r||n}function sl(e){const t={};function n(r,o=""){for(const[s,a]of Object.entries(r)){const l=o?`${o}.${s}`:s;a&&typeof a=="object"&&!Array.isArray(a)?n(a,l):t[l]=a}}return n(e),t}function il({template:e,variables:t,variableKeyPattern:n,variableValueTransformer:r}){return Object.entries(t).reduce((o,[s,a])=>{if(!r&&!["number","boolean","string"].includes(typeof a))throw new Error(`If transformer is not provided, value(${s}:${a}) must be a {string, number, or boolean}`);const l=r?r(a):String(a),c=n(s);return o.replace(c,vs(l))},e)}async function al({template:e,variables:t,variableKeyPattern:n,variableValueTransformer:r}){return(await Promise.all(Object.entries(t).map(async([s,a])=>{const l=await r(a);return{regex:n(s),transformedValue:l}}))).reduce((s,{regex:a,transformedValue:l})=>s.replace(a,vs(l)),e)}var zn=(e=>(e[e.EXTERNAL_AUTH_TOKEN_EXPIRED=1]="EXTERNAL_AUTH_TOKEN_EXPIRED",e))(zn||{});const Ss=e=>typeof e=="object"&&e!==null,Gr=(e,t)=>t in e&&typeof e[t]=="string"&&e[t]!=="",ll=e=>!Ss(e)||!Gr(e,"channel_url")||!Gr(e,"ai_agent_id")?null:{channelUrl:e.channel_url,aiAgentId:e.ai_agent_id},cl={1:ll};function ul(e){if(!Ss(e)||!("cat"in e)||typeof e.cat!="number"||!("data"in e))return null;const t=e.cat,n=cl[t];if(!n)return null;const r=n(e.data);return r?{category:t,data:r}:null}function dl(e,t,n,r){const o=Ea.default.init({appId:e,modules:[new ze.GroupChannelModule,new be.AIAgentModule],localCacheEnabled:!0,options:new he.SendbirdChatOptions({typingIndicatorInvalidateTime:2e4}),...r});return o.addSendbirdExtensions([{version:n,product:he.SendbirdProduct.AI_AGENT,platform:t.platform}],{platform:t.deviceOSPlatform,version:t.deviceOSVersion},t.customData)||console.warn("Invalid Sendbird Extensions",t),o}function ml(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 fl=[400300,400301,400302,400310];class ir{constructor(t,n,r){A(this,"chatSDK");A(this,"_logger");A(this,"_cache");A(this,"connect",async(t,n,r,o)=>{if(this._logger.debug("ChatClient.connect: start",t.userId),n){const s=new he.SessionHandler({...n,onSessionTokenRequired:this._interceptTokenRefresh(n.onSessionTokenRequired,r,o)});this.chatSDK.setSessionHandler(s),this.chatSDK.aiAgent.addEventHandler(zn.EXTERNAL_AUTH_TOKEN_EXPIRED.toString(),a=>{var c;this._logger.debug("ChatClient.connect: EXTERNAL_AUTH_TOKEN_EXPIRED event received",a);const l=ul(a);(l==null?void 0:l.category)===zn.EXTERNAL_AUTH_TOKEN_EXPIRED&&(this._logger.debug("ChatClient.connect: calling onExternalAuthTokenExpired handler",l.data),(c=n==null?void 0:n.onExternalAuthTokenExpired)==null||c.call(n,l.data))})}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(s){const a=s;if(this.chatSDK.isCacheEnabled){if(this._isCacheRestrictedError(a))this._logger.warn("ChatClient.connect","offline connect restricted",a.message,a.code),this._logger.warn("ChatClient.connect","clear cached-data"),await this.chatSDK.clearCachedData().catch(l=>this._logger.warn("ChatClient.connect","clear cached-data failure",l));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",a.message,a.code),a}});A(this,"disconnect",async()=>{this._logger.debug("ChatClient.disconnect: start"),this.chatSDK.aiAgent.removeAllEventHandlers(),await this.chatSDK.disconnect(),this._cache.template.clear(),this._logger.debug("ChatClient.disconnect: end")});A(this,"getChannel",async t=>this.chatSDK.groupChannel.getChannel(t));A(this,"patchContext",async(t,n,r)=>this.chatSDK.aiAgent.patchContext(t,n,r));A(this,"updateContext",async(t,n,r)=>this.chatSDK.aiAgent.updateContext(t,n,r));A(this,"requestMessengerSettings",async t=>{var o;if(t.userId===""){const s=new Error("userId cannot be empty string for messenger settings request");throw this._logger.error("ChatClient.requestMessengerSettings: invalid userId",s),s}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",(o=r.active_channel)==null?void 0:o.channel_url),r});A(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});A(this,"clearUserMemories",async(t={})=>{this._logger.debug("ChatClient.clearUserMemories: requesting",t),await this.chatSDK.aiAgent.clearUserMemories(t),this._logger.debug("ChatClient.clearUserMemories: completed")});A(this,"_interceptTokenRefresh",(t,n,r)=>{if(t)return async(o,s)=>{new Promise((a,l)=>t==null?void 0:t(a,l)).then(a=>{a?n==null||n(a):r==null||r(),o(a)}).catch(a=>{r==null||r(),s(a)})}});A(this,"_isCacheRestrictedError",t=>fl.some(n=>t.code===n));A(this,"_syncTemplatesIfNeeded",async()=>{var r,o;const t=(o=(r=this.chatSDK.appInfo)==null?void 0:r.aiAgentInfo)==null?void 0:o.templateListToken;if(!t)return;const n=this._cache.template.getCachedToken();if(!(n&&n===t)){this._logger.debug("ChatClient._syncTemplatesIfNeeded: syncing templates");try{const{templates:s,token:a}=await this.chatSDK.aiAgent.getMessageTemplates({limit:20});for(const{template:l}of s){const{key:c}=ys(l);this._cache.template.set(c,l)}this._cache.template.setCachedToken(a),this._logger.debug("ChatClient._syncTemplatesIfNeeded: sync completed")}catch(s){this._logger.error("ChatClient._syncTemplatesIfNeeded: error",s)}}});this.chatSDK=t,this._logger=n,this._cache=r}static init(t){let n;return t.chatSDK?(ml(t.chatSDK),n=t.chatSDK):n=dl(t.appId,t.extensions,t.messengerVersion,t.chatParams),new ir(n,t.logger,t.cache)}}const Ft=new Map,As={set:(e,t)=>{Ft.set(e,t)},get:e=>{if(Ft.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=Ft.get(e);if(!n)throw new Error(`AIAgent platform "${e}" is not configured.`);return{platform:e,...n}}const t=Ft.entries().next().value;return{platform:t[0],...t[1]}}};class zr extends Error{constructor(n,r){const o=(r==null?void 0:r.detail)??"";super(o||`Desk API error (${n})`);A(this,"status");A(this,"code");A(this,"detail");this.name="DeskApiError",this.status=n,this.code=(r==null?void 0:r.code)??"",this.detail=o}}var ar=(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))(ar||{}),lr=(e=>(e.URGENT="URGENT",e.HIGH="HIGH",e.MEDIUM="MEDIUM",e.LOW="LOW",e))(lr||{}),xs=(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))(xs||{});const gl=e=>e==="desk401103"||e==="desk401106"||e==="desk401107"||e==="desk401108"||e==="desk401109";class hl{constructor(t){A(this,"_appId");A(this,"_apiHost");A(this,"_logger");A(this,"_credential",null);A(this,"_authRefreshPromise",null);A(this,"_onDeskTokenRefreshRequired",async()=>!1);A(this,"request",async(t,n)=>{const r=n.authRequired??!0,o=`${this._apiHost}${t}`;r&&this._authRefreshPromise&&(this._logger.debug("DeskApiClient: waiting for in-flight recovery..."),await this._authRefreshPromise);const s=await this._fetch(o,n);return r&&s.status===401?this._handleUnauthorized(s,o,n):this._toResult(s)});A(this,"setCredential",(t,n=async()=>!1)=>{this._authRefreshPromise=null,this._onDeskTokenRefreshRequired=n,this._credential=t});A(this,"clearCredential",()=>{this._authRefreshPromise=null,this._credential=null,this._onDeskTokenRefreshRequired=async()=>!1});A(this,"_handleUnauthorized",async(t,n,r)=>{const o=await this._parseErrorCode(t);if(!gl(o))return this._toResult(t);if(!await this._refresh(o)||this._credential===null)return this._toResult(t);const a=await this._fetch(n,r);return this._toResult(a)});A(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}});A(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))}:{}}));A(this,"_buildParams",t=>new URLSearchParams({sendbirdAppId:this._appId,...t}));A(this,"_buildBody",t=>({sendbirdAppId:this._appId,...t}));A(this,"_buildHeaders",(t,n)=>({"content-type":"application/json",...t&&this._credential?{sendbirdDeskToken:this._credential.deskToken}:{},...n}));A(this,"_toResult",async t=>{if(!t.ok){const r=await t.json().catch(()=>({}));throw new zr(t.status,r)}const n=await t.text();if(n)try{return JSON.parse(n)}catch{throw new zr(t.status,{})}});A(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}.sendbird.com/sapi`,this._logger=t.logger}get credential(){return this._credential}}class Qt{constructor(t,n){A(this,"id");A(this,"title");A(this,"status");A(this,"agent");A(this,"priority");A(this,"group");A(this,"firstResponseTime");A(this,"issuedAt");A(this,"customFields");A(this,"_client");A(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 Qt({id:t.id,title:t.channelName??null,status:t.status2??ar.INITIALIZED,agent:(()=>{var s;const o=(s=t.recentAssignment)==null?void 0:s.agent;return o?{userId:o.sendbirdId??"",name:o.displayName??"",profileUrl:o.photoThumbnailUrl??""}:null})(),priority:t.priority??lr.MEDIUM,group:t.group??0,firstResponseTime:t.firstResponseTime??-1,issuedAt:t.issuedAt??null,customFields:Object.fromEntries(((r=t.customFields)==null?void 0:r.map(o=>[o.key,o.value]))??[])},n)}}class cr{constructor(t){A(this,"_logger");A(this,"_apiClient");A(this,"_onDeskTokenRefreshRequired");A(this,"refreshDeskAuthToken",async t=>this._apiClient.credential?this.authenticate({userId:this._apiClient.credential.userId,accessToken:t,onDeskTokenRefreshRequired:this._onDeskTokenRefreshRequired}):!1);A(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}});A(this,"deauthenticate",()=>{this._apiClient.clearCredential(),this._onDeskTokenRefreshRequired=void 0,this._logger.debug("DeskClient.deauthenticate: token cleared")});A(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")});A(this,"getTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request(`/tickets/${encodeURIComponent(t)}/`,{method:"GET"});return Qt._fromResponse(n,this)});A(this,"createTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request("/tickets/",{method:"POST",body:Es({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 Qt._fromResponse(n,this)});this._logger=t.logger,this._apiClient=new hl(t)}static init(t){return new cr(t)}_assertAuthenticated(t){if(t.credential==null)throw new Error("DeskClient is not authenticated")}}class ur{constructor(){A(this,"authenticate",async t=>!1);A(this,"deauthenticate",()=>{});A(this,"refreshDeskAuthToken",async()=>!1);A(this,"setCustomerLanguage",async()=>{});A(this,"getTicket",async()=>{throw new Error("DeskClient is disabled via __SBA_USE_DESK_CLIENT__")})}static init(){return new ur}}function pl(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 _l=1440*60*1e3,El=typeof __SBA_USE_DESK_CLIENT__>"u"||__SBA_USE_DESK_CLIENT__;function qe(e){if(!e)throw new Error("Not authenticated. Call authenticate() first.")}function bl(e,t){return Object.entries(t).every(([n,r])=>e[n]===r)}class en extends tl{constructor(n){super();A(this,"appId");A(this,"aiAgentId");A(this,"_chatClient");A(this,"_deskClient");A(this,"_cache");A(this,"_logger");A(this,"_dispatcher");A(this,"_session",null);A(this,"language");A(this,"countryCode");A(this,"context");A(this,"queryParams");A(this,"_config");A(this,"_networkStateAdapter");A(this,"_forceCreateChannel");A(this,"_agentVersion");A(this,"_statsTrackers");A(this,"_operationQueue",Wa());A(this,"dispose",()=>{this._operationQueue.isPending()||(this._logger.debug("AIAgent.dispose: start"),this._chatClient.chatSDK.connectionState==="OPEN"&&this._chatClient.chatSDK.disconnectWebSocket(),this._removeChannelHandler(),this._session=null,this._deskClient.deauthenticate(),this._statsTrackers.initialRender.clear(),this._logger.debug("AIAgent.dispose: end"))});A(this,"initConversationIfNeeded",n=>this._initConversationIfNeeded(n));A(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 a,l,c,d,m;this._logger.debug("AIAgent.authenticate: start"),this._statsTrackers.initialRender.onAuthStart();const o=this._getSessionCandidate(n),s=(a=o.userSessionCandidate)!=null&&a.userId?this._cache.messenger.getSettings(o.userSessionCandidate.userId):null;s!=null&&s.bot&&this._dispatcher.send(Ze.MessengerSettingsUpdated({settings:s,source:"cache"}));try{const f=await this._chatClient.requestMessengerSettings({aiAgentId:this.aiAgentId,userId:(l=o.userSessionCandidate)==null?void 0:l.userId,language:this.language,country:this.countryCode,context:this.context,knownActiveChannelUrl:(c=s==null?void 0:s.active_channel)==null?void 0:c.channel_url,forceCreateChannel:this._forceCreateChannel,agentVersion:this._agentVersion});let g;if(f.auto_created_user)if(o.type==="manual")this._logger.warn("Received auto created user info but current session is manual. Ignoring auto created user info."),g={userId:o.userSessionCandidate.userId,authToken:o.userSessionCandidate.authToken};else{const{user_id:y,session_token:b,expire_at:E}=f.auto_created_user;this._cache.messenger.setAnonUser({userId:y,authToken:b,expireAt:E}),g={userId:y,authToken:b},this._logger.debug("AIAgent.authenticate: anonymous user created",y)}else g={userId:((d=o.userSessionCandidate)==null?void 0:d.userId)??"",authToken:((m=o.userSessionCandidate)==null?void 0:m.authToken)??""};this._cache.messenger.setSettings(g.userId,f),this._dispatcher.send(Ze.MessengerSettingsUpdated({settings:f,source:"server"}));const _=(()=>{var y;return o.type==="anonymous"?Ua(this._dispatcher):(y=o.userSessionCandidate)==null?void 0:y.sessionHandler})(),v=await this._chatClient.connect(g,_,y=>{var b;this._logger.debug("AIAgent: session token refreshed"),(b=this._session)==null||b._updateAuthToken(y),this._deskClient.refreshDeskAuthToken(y)},()=>{this._logger.debug("AIAgent: session token unavailable, deauthenticating desk"),this._deskClient.deauthenticate()});return await this._deskClient.authenticate({userId:g.userId,accessToken:g.authToken,onDeskTokenRefreshRequired:async({reason:y})=>{var b;if(y===xs.ERR_SESSION_KEY_EXPIRED){await new Promise(C=>setTimeout(C,2e3));const E=(b=this._session)==null?void 0:b.userSession.authToken;return E?await this._deskClient.refreshDeskAuthToken(E):!1}return!1}}),(s==null?void 0:s.language)!==f.language&&this._deskClient.setCustomerLanguage(this.language).catch(()=>{}),this._statsTrackers.initialRender.onAuthComplete(),this._session=new nl({sdkUser:v,userSession:g,activeChannel:{url:f.active_channel.channel_url,status:"open"},dispatcher:this._dispatcher}),this._setupChannelHandler(),this._logger.debug("AIAgent.authenticate: end",{userId:g.userId}),f}catch(f){throw this._statsTrackers.initialRender.onAuthError(f),f}})});A(this,"deauthenticate",()=>this._operationQueue("deauth",async()=>{var n;this._logger.debug("AIAgent.deauthenticate: start"),await this._chatClient.disconnect(),this._deskClient.deauthenticate(),this._cache.messenger.clear((n=this._session)==null?void 0:n.userSession.userId),this._session=null,this._removeChannelHandler(),this._statsTrackers.initialRender.clear(),this._logger.debug("AIAgent.deauthenticate: end")}));A(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}),o=r.active_channel.channel_url;return this._cache.messenger.setSettings(this._session.userSession.userId,r),this._logger.debug("AIAgent.createConversation: end",o),o});A(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:be.ConversationStatus.OPEN,limit:100}),o=[];for(;r.hasNext;){const s=await r.next();for(const a of s)bl(a.context??{},n.context)&&o.push(a.channelInfo.url)}return this._logger.debug("AIAgent.searchConversation: end",{count:o.length}),o});A(this,"closeConversation",async n=>{var o;qe(this._session),this._logger.debug("AIAgent.closeConversation: start",n);const r=await this._chatClient.getChannel(n);((o=r.conversation)==null?void 0:o.status)===be.ConversationStatus.OPEN?(await r.closeConversation(),this._session.activeChannel.url===n&&this._session._updateActiveChannel({url:n,status:"closed",conversationStatus:be.ConversationStatus.CLOSED}),this._logger.debug("AIAgent.closeConversation: end")):this._logger.debug("AIAgent.closeConversation: already closed or not an AI agent conversation")});A(this,"createConversationListCollection",n=>new gs(this.chatSDK,n??{}));A(this,"patchContext",async(n,r)=>{qe(this._session),this._logger.debug("AIAgent.patchContext: start",{channelUrl:n,context:r});const o=await this._chatClient.patchContext(this.aiAgentId,n,r);return this._logger.debug("AIAgent.patchContext: end",o),{...o,context:o.context??{}}});A(this,"updateContext",async(n,r)=>{qe(this._session),this._logger.debug("AIAgent.updateContext: start",{channelUrl:n,context:r});const o=await this._chatClient.updateContext(this.aiAgentId,n,r);return this._logger.debug("AIAgent.updateContext: end",o),{...o,context:o.context??{}}});A(this,"getContextObject",async n=>{qe(this._session),this._logger.debug("AIAgent.getContextObject: start",n);const o=await(await this._chatClient.getChannel(n)).getContextObject(this.aiAgentId);return this._logger.debug("AIAgent.getContextObject: end",o),{...o,context:o.context??{}}});A(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")});A(this,"setUserMemoryState",async n=>{qe(this._session);const r=this._session;this._logger.debug("AIAgent.setUserMemoryState: start",n.enabled);const o={...n,contextAiAgentId:n.contextAiAgentId??this.aiAgentId},s=r.userSession.userId,a=await this._chatClient.setUserMemoryState(o);if(this._session!==r)return this._logger.debug("AIAgent.setUserMemoryState: session changed during request, discarding stale result"),Gn(a);const l=this._cache.messenger.getSettings(s);if(l){const c={...l,memory:a};this._cache.messenger.setSettings(s,c),this._dispatcher.send(Ze.MessengerSettingsUpdated({settings:c,source:"cache"}))}return this._logger.debug("AIAgent.setUserMemoryState: end",a.enabled),Gn(a)});A(this,"refreshActiveChannel",async n=>{var l,c,d;qe(this._session);const r=this._session,o=(n==null?void 0:n.useKnownActiveChannelUrl)??!0;this._logger.debug("AIAgent.refreshActiveChannel: start",{useKnownActiveChannelUrl:o});const s=await this._chatClient.requestMessengerSettings({aiAgentId:this.aiAgentId,userId:r.userSession.userId,language:this.language,country:this.countryCode,context:this.context,knownActiveChannelUrl:o?(c=(l=this._cache.messenger.getSettings(r.userSession.userId))==null?void 0:l.active_channel)==null?void 0:c.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)??s.active_channel.channel_url;const a=s.active_channel.channel_url;return this._cache.messenger.setSettings(this._session.userSession.userId,s),this._session._updateActiveChannel({url:a,status:"open"}),this._logger.debug("AIAgent.refreshActiveChannel: end",a),a});A(this,"_getSessionCandidate",n=>n instanceof _s?{type:"manual",userSessionCandidate:this._getManualSessionInfo(n)}:n instanceof Hn?{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});A(this,"_getAnonymousSessionInfo",()=>{const n=this._cache.messenger.getAnonUser();return n?n.expireAt-_l<=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});A(this,"_getManualSessionInfo",n=>{if(!n||n instanceof Hn)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(o=>!(o 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=Hr(n.config),this.queryParams=n.queryParams,this._networkStateAdapter=n.networkStateAdapter,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={initialRender:new Ya((r,o)=>this._chatClient.chatSDK.aiAgent.appendStat(r,o))}}static init(n){var f;const r=As.get(n.platform),o=n.logger??new ps(n.logLevel??rr.WARN),s=n.dispatcher??new hs(o),a=n.useMMKVStorage?pl(n.useMMKVStorage):r.keyValueStorage,l=n.useMMKVStorage?{...n.chatParams,useMMKVStorageStore:n.useMMKVStorage}:n.chatParams,c=ka({appId:n.appId,aiAgentId:n.aiAgentId,storage:a}),d=ir.init({appId:n.appId,messengerVersion:r.messengerVersion,extensions:{platform:r.platform,deviceOSPlatform:r.deviceOSPlatform,deviceOSVersion:r.deviceOSVersion},chatParams:l,chatSDK:n.chatSDK,logger:o,cache:c}),m=El?cr.init({appId:n.appId,logger:o,customApiHost:(f=n.deskParams)==null?void 0:f.customApiHost}):ur.init();return o.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,forceCreateChannel:n._forceCreateChannel,agentVersion:n._agentVersion,chatClient:d,deskClient:m,cache:c,logger:o,dispatcher:s})}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=Hr(n)}get agentVersion(){return this._agentVersion}set agentVersion(n){this._agentVersion=n}get networkStateAdapter(){return this._networkStateAdapter}get logger(){return this._logger}get dispatcher(){return this._dispatcher}get cache(){return this._cache}get statsTrackers(){return this._statsTrackers}}const Ee=(e,t)=>{const n=u.createContext(t??null),r=({children:a,value:l})=>i.createElement(n.Provider,{value:l},typeof a=="function"?a(l):a),o=({children:a})=>i.createElement(n.Consumer,null,l=>l?typeof a=="function"?a(l):a:null),s=()=>{const a=u.useContext(n);if(!a)throw new Error(`use${e}Context must be used within a ${e}Provider`);return a};return n.displayName=`${e}Context`,r.displayName=`${e}Provider`,o.displayName=`${e}Consumer`,s.displayName=`use${e}Context`,{Context:n,Provider:r,Consumer:o,useContext:s}};function Be(e){const t=u.createContext({Template:e.template,updateTemplate:()=>{},components:e.components,updateComponent:()=>{}});function n({children:s}){const[a,l]=u.useState(()=>e.template),[c,d]=u.useState(e.components),m={Template:a,updateTemplate:f=>l(()=>f),components:c,updateComponent:(f,g)=>d(_=>({..._,[f]:g}))};return i.createElement(t.Provider,{value:m},s)}function r({template:s,children:a}){const{updateTemplate:l}=u.useContext(t);return u.useLayoutEffect(()=>{s&&l(s)},[s]),i.createElement(i.Fragment,null,a)}function o({children:s}){return i.createElement(n,null,s)}return o.defaults=e,o.useContext=()=>u.useContext(t),o.Context=t,o.Template=r,Object.keys(e.components).forEach(s=>{o[s]=function({component:l}){const{updateComponent:c}=u.useContext(t);return u.useLayoutEffect(()=>{l&&c(s,l)},[l]),null}}),o}function Cl(...e){return function({children:n}){return e.reduce((r,o)=>i.createElement(o,null,r),n)}}function vl(e,t){const n=e.lastMessage;return n!=null&&n.isAdminMessage()?n.message??"":Ts(e,t)}function Ts(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 o=n.fileInfoList.length;return((r=t==null?void 0:t.formatMultipleFilesCount)==null?void 0:r.call(t,o))??`${o} photos`}return e.name}function yl(e,t,n){var a;const r=new Date,o=new Date(((a=e.lastMessage)==null?void 0:a.createdAt)||e.createdAt),s=Xe.differenceInMinutes(r,o);return s<1?n.justNow:s<60?n.minutesAgo(s):Xe.isToday(o)?n.hoursAgo(Xe.differenceInHours(r,o)):t(o,n.dateShortFormat)}const Sl=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},Ut=e=>Math.max(0,Math.min(255,e)).toString(16).padStart(2,"0"),Vr=(e,t)=>{const n=Ut(Math.round(t*255));if(e.startsWith("#")){const o=e.slice(1);return o.length===3||o.length===4?`#${o[0]}${o[0]}${o[1]}${o[1]}${o[2]}${o[2]}${n}`:`#${o.slice(0,6)}${n}`}const r=Sl(e);return r?`#${Ut(r[0])}${Ut(r[1])}${Ut(r[2])}${n}`:e},Al=(e,t)=>{if(!t)return e;const n={...e};for(const[r,o]of Object.entries(t))o&&(n[r]=o);return n},xl=e=>e.consentDialog?"consent":e.toggleAllowed?e.enabled?"on":"off":"readonly",Tl=e=>e.length>0,Il=e=>{const t=e[0];if(!t)return e;const n=e.some(o=>He(o.type)),r=e.some(o=>!He(o.type));return n&&r?He(t.type)?e.filter(o=>He(o.type)):[t]:r?[t]:e},Yr=e=>e.length===0?"empty":e.every(t=>He(t.type))?"images":"non_images",wl=({currentFiles:e,incomingFiles:t,maxAttachmentCount:n})=>{const r=Il(t),o=Yr(e),s=Yr(r),l=o==="images"&&s==="images"?{type:"append",files:r,nextFiles:[...e,...r]}:{type:"replace",files:r,nextFiles:r};return l.nextFiles.length>n?{type:"reject",reason:"count_limit",maxAttachmentCount:n,nextFileCount:l.nextFiles.length}:l.type==="replace"&&o!=="empty"&&o!==s?{type:"confirm_replace",action:l}:{type:"apply",action:l}},mt=3,Is=6,Ml=e=>e%mt===0?mt:Is,kl=({index:e,itemCount:t})=>{const n=t%mt,r=n>0,o=r?t-n:t,s=r&&e>=o,a=s?n:mt,l=s?e-o:e%mt,c=!r&&e>=t-mt;return{columnSpan:r?Is/a:1,rowItemCount:a,isLastInRow:l===a-1,isLastRow:s||c}},ws=Ee("AIAgent"),Rl=ws.Provider,ke=ws.useContext;function Ll(e){const t=Ol(e);return i.createElement(Rl,{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 Ol(e){const t=u.useRef(null),n=u.useRef(null);if(!t.current||!n.current)t.current=en.init(e);else{const o=Nl(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,u.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}function Nl(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}}const Wr=Symbol("conversationMessageEventBridge"),Ct=Symbol("conversationMessageEventPublisher"),Dl=(e,t)=>{const n=e;if(n[Ct]=t,n[Wr])return e;n[Wr]=!0;const r=e.setMessageCollectionHandler.bind(e);e.setMessageCollectionHandler=s=>{r({...s,onMessagesAdded:(a,l,c)=>{var d,m;(d=s.onMessagesAdded)==null||d.call(s,a,l,c),(m=n[Ct])==null||m.call(n,{kind:"messagesAdded",source:a.source,messages:c})},onMessagesUpdated:(a,l,c)=>{var d,m;(d=s.onMessagesUpdated)==null||d.call(s,a,l,c),(m=n[Ct])==null||m.call(n,{kind:"messagesUpdated",source:a.source,messages:c})}})};const o=e.initialize.bind(e);return e.initialize=s=>{const a=o(s),l=a.onCacheResult.bind(a),c=a.onApiResult.bind(a);return a.onCacheResult=d=>l((m,f)=>{var g;d(m,f),(g=n[Ct])==null||g.call(n,{kind:"initialized",source:"cache",messages:f??[]})}),a.onApiResult=d=>c((m,f)=>{var g;d(m,f),(g=n[Ct])==null||g.call(n,{kind:"initialized",source:"api",messages:f??[]})}),a},e},dn=()=>{const[,e]=u.useState(0);return u.useCallback(()=>e(t=>t+1),[])};let $l=0;function Pl(){return u.useState(()=>`${$l++}`)[0]}const ht=(e,t,n)=>{const r=u.useRef(t),s=Pl();r.current=t,u.useEffect(()=>{var l;const a=c=>{const d=c;return Object.keys(d).forEach(f=>{d[f]=(...g)=>{var v;const _=r.current;(v=_[f])==null||v.call(_,...g)}}),d};return(l=e==null?void 0:e.groupChannel)==null||l.addGroupChannelHandler(s,a(new ze.GroupChannelHandler)),()=>{var c;(c=e==null?void 0:e.groupChannel)==null||c.removeGroupChannelHandler(s)}},[e==null?void 0:e.groupChannel,s])};function Fl(e,t){return!e||!t?!0:e.url!==t.url}function De(e){return e!=null&&"sendingStatus"in e}function Ul(e,t="##__USER_ID_IS_NOT_PROVIDED__##"){var n;return De(e)?((n=e.sender)==null?void 0:n.userId)===t:!1}function Bl(e,t){return Ul(e,t)||e.isAdminMessage()?!1:e.updatedAt===0}function qr(e){return"sendingStatus"in e?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId)}const tn={collection:{groupChannel:{defaultOrder:ze.GroupChannelListOrder.LATEST_LAST_MESSAGE},message:{defaultLimit:{next:25,prev:25},searchLimit:{next:10,prev:10}}}};function Kr(e){return!e||!Array.isArray(e)?!1:e.length!==0}function jr(e,t){return e.reduce((n,r)=>{const o=t(r);return n[o]=r,n},{})}const Hl=({...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=Gl(t.value.messages);else{const n={...e.messageMap},r=[],o=[];t.value.messages.forEach(s=>{const a=De(s)?s.reqId:void 0,l=s.messageId||void 0;[a,l].forEach(c=>{if(!c)return;const d=n[c];zl(d,s,t.value.strictStreamingOrder)&&(d&&r.push(d),s.parentMessageId>0&&(d!=null&&d.parentMessage)&&s.applyParentMessage(d.parentMessage),o.push(s))})}),r.forEach(s=>{De(s)&&delete n[s.reqId],delete n[s.messageId]}),o.forEach(s=>{De(s)&&(n[s.reqId]=s),s.messageId!==0&&(n[s.messageId]=s)}),e.messageMap=n}return e}case"update_new_messages":{const n=t.value.currentUserId,r=t.value.messages.filter(o=>Bl(o,n));return t.value.clearBeforeAction?e.newMessageMap=jr(r,qr):(r.map(s=>s.messageId).forEach(s=>delete e.newMessageMap[s]),e.newMessageMap={...e.newMessageMap,...jr(r,qr)}),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 o=e[n][r];o&&(De(o)&&delete e[n][o.reqId],delete e[n][o.messageId])}),t.value.reqIds.forEach(r=>{const o=e[n][r];o&&(De(o)&&delete e[n][o.reqId],delete e[n][o.messageId])}),e}}},Gl=e=>e.reduce((t,n)=>(De(n)?(t[n.reqId]=n,n.sendingStatus===Ue.SendingStatus.SUCCEEDED&&(t[n.messageId]=n)):t[n.messageId]=n,t),{}),zl=(e,t,n=!1)=>{var r,o;if(!De(e)||!De(t))return!0;if(n&&e&&Zr(e)&&Zr(t)){const s=((r=e.message)==null?void 0:r.length)||0,a=((o=t.message)==null?void 0:o.length)||0;if(s>a)return!1}return e.sendingStatus===Ue.SendingStatus.SUCCEEDED?t.sendingStatus===Ue.SendingStatus.SUCCEEDED:e.sendingStatus!==t.sendingStatus},Vl=(e=Yl)=>{const[{initialized:t,loading:n,refreshing:r,messageMap:o,newMessageMap:s},a]=u.useReducer(Hl,{initialized:!1,loading:!0,refreshing:!1,messageMap:{},newMessageMap:{}}),l=(b,E,C,S)=>{a({type:"update_messages",value:{messages:b,clearBeforeAction:E,currentUserId:C,strictStreamingOrder:S}})},c=(b,E)=>{a({type:"delete_messages",value:{messageIds:b,reqIds:E}})},d=(b,E,C)=>{a({type:"update_new_messages",value:{messages:b,clearBeforeAction:E,currentUserId:C}})},m=(b,E)=>{a({type:"delete_new_messages",value:{messageIds:b,reqIds:E}})},f=b=>{a({type:"update_initialized",value:{status:b}})},g=b=>{a({type:"update_loading",value:{status:b}})},_=b=>{a({type:"update_refreshing",value:{status:b}})},v=Object.values(s),y=u.useMemo(()=>Array.from(new Set(Object.values(o))).sort(e),[o]);return{updateInitialized:f,updateLoading:g,updateRefreshing:_,updateMessages:l,deleteMessages:c,initialized:t,loading:n,refreshing:r,messages:y,newMessages:v,updateNewMessages:d,deleteNewMessages:m}},Xr=Math.floor(Number.MAX_SAFE_INTEGER/10);function Yl(e,t){let n=0,r=0;return De(e)&&e.sendingStatus!=="succeeded"&&(n=Xr),De(t)&&t.sendingStatus!=="succeeded"&&(r=Xr),e.createdAt+n-(t.createdAt+r)}function Zr(e){try{const t=JSON.parse(e.data||"{}");return typeof t=="object"&&!!t.stream}catch{return!1}}function ye(e){const t=u.useRef(e);return t.current=e,u.useCallback((...n)=>t.current(...n),[t])}const Wl=(e,t,n)=>{var s;const r={prevResultLimit:t.prev,nextResultLimit:t.next,startingPoint:n==null?void 0:n.startingPoint,replyType:n==null?void 0:n.replyType},o=(s=n==null?void 0:n.collectionCreator)==null?void 0:s.call(n,r);return o||e.createMessageCollection({...r,filter:new ze.MessageFilter(r)})};function Jr(e){return e<Date.now()?tn.collection.message.searchLimit:tn.collection.message.defaultLimit}const ql=(e,t,n={})=>{var Oe,Re;const r=u.useRef(n);r.current=n;const o=u.useRef(t);o.current=t;const s=r.current.logger,a=r.current.startingPoint??Number.MAX_SAFE_INTEGER,l=Jr(a),c=r.current.strictStreamingOrder??!1,d=u.useRef({prev:!1,next:!1}),m=dn(),f=u.useRef({initialized:!1,apiInitialized:!1,instance:null}),{initialized:g,loading:_,refreshing:v,messages:y,newMessages:b,updateMessages:E,updateNewMessages:C,deleteNewMessages:S,deleteMessages:x,updateInitialized:w,updateLoading:k,updateRefreshing:I}=Vl(n==null?void 0:n.sortComparator),M=ye(T=>{var R,N,j,U;if(!o.current||!o.current.url)return(R=s==null?void 0:s.error)==null?void 0:R.call(s,"[useGroupChannelMessages] channel is required");try{switch(T){case he.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case he.CollectionEventSource.EVENT_MESSAGE_SENT_SUCCESS:case he.CollectionEventSource.SYNC_MESSAGE_FILL:case void 0:(j=(N=r.current).markAsRead)==null||j.call(N,[o.current]);break}}catch(G){(U=s==null?void 0:s.warn)==null||U.call(s,"[useGroupChannelMessages/markAsReadBySource]",G)}}),O=ye((T,R)=>{var N,j,U,G,B;if(R.length>0)switch(T){case he.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case he.CollectionEventSource.SYNC_MESSAGE_FILL:{(j=(N=r.current).shouldCountNewMessages)!=null&&j.call(N)&&C(R,!1,(U=e.currentUser)==null?void 0:U.userId),(B=(G=r.current).onMessagesReceived)==null||B.call(G,R);break}}}),F=ye(T=>{var R,N;(N=(R=r.current).onCollectionEvent)==null||N.call(R,T)}),Y=ye(async(T,R,N)=>new Promise((j,U)=>{var $e;f.current.instance&&f.current.instance.dispose(),M(),C([],!0,($e=e.currentUser)==null?void 0:$e.userId);const G=()=>{var ie,re;const{pendingMessages:ae,failedMessages:ne}=f.current.instance??{};Kr(ae)&&E(ae,!1,(ie=e.currentUser)==null?void 0:ie.userId),Kr(ne)&&E(ne,!1,(re=e.currentUser)==null?void 0:re.userId)},B=Wl(T,N,{...r.current,startingPoint:R});f.current={apiInitialized:!1,initialized:!1,instance:B},B.setMessageCollectionHandler({onMessagesAdded:(ae,ne,ie)=>{var re;M(ae.source),O(ae.source,ie),E(ie,!1,(re=e.currentUser)==null?void 0:re.userId,c),F({kind:"messagesAdded",source:ae.source,messages:ie})},onMessagesUpdated:(ae,ne,ie)=>{var re,Z,le;M(ae.source),O(ae.source,ie),E(ie,!1,(re=e.currentUser)==null?void 0:re.userId,c),ae.source===he.CollectionEventSource.EVENT_MESSAGE_UPDATED&&((le=(Z=r.current).onMessagesUpdated)==null||le.call(Z,ie)),F({kind:"messagesUpdated",source:ae.source,messages:ie})},onMessagesDeleted:(ae,ne,ie,re)=>{const Z=re.map(pe=>pe.messageId),le=re.filter(De).map(pe=>pe.reqId);x(Z,le),S(Z,le),F({kind:"messagesDeleted",source:ae.source,messages:re})},onChannelDeleted:(ae,ne)=>{var ie,re;(re=(ie=r.current).onChannelDeleted)==null||re.call(ie,ne)},onChannelUpdated:(ae,ne)=>{var ie,re;m(),(re=(ie=r.current).onChannelUpdated)==null||re.call(ie,ne,ae)},onHugeGapDetected:()=>{Y(T,Number.MAX_SAFE_INTEGER,tn.collection.message.defaultLimit)}});let ue=!1;B.initialize(ze.MessageCollectionInitPolicy.CACHE_AND_REPLACE_BY_API).onCacheResult((ae,ne)=>{var ie,re,Z,le,pe;(re=(ie=r.current).onCacheResult)==null||re.call(ie,ae,ne??[]),ae?(e.isCacheEnabled&&((Z=s==null?void 0:s.error)==null||Z.call(s,"[useGroupChannelMessages/onCacheResult]",ae)),ue=!0):ne&&((le=s==null?void 0:s.debug)==null||le.call(s,"[useGroupChannelMessages/onCacheResult]","message length:",ne.length),E(B.succeededMessages,!0,(pe=e.currentUser)==null?void 0:pe.userId),G(),ne.length>0&&(f.current.initialized=!0,j())),F({kind:"initialized",source:"cache",messages:ne??[]})}).onApiResult((ae,ne)=>{var ie,re,Z,le,pe,rt,ot;(re=(ie=r.current).onApiResult)==null||re.call(ie,ae,ne??[]),f.current.initialized=!0,f.current.apiInitialized=!0,ae?((Z=s==null?void 0:s.warn)==null||Z.call(s,"[useGroupChannelMessages/onApiResult]",ae),ue?U(ae):j()):ne&&((le=s==null?void 0:s.debug)==null||le.call(s,"[useGroupChannelMessages/onApiResult]","message length:",ne.length),E(B.succeededMessages,!0,(pe=e.currentUser)==null?void 0:pe.userId),r.current.startingPoint||(ot=(rt=r.current).onMessagesReceived)==null||ot.call(rt,ne),e.isCacheEnabled&&G(),j()),F({kind:"initialized",source:"api",messages:ne??[]})})}));ht(e,{onUserBanned(T,R){var N,j,U;T.isGroupChannel()&&!Fl(T,o.current)&&(R.userId===((N=e.currentUser)==null?void 0:N.userId)?(U=(j=r.current).onCurrentUserBanned)==null||U.call(j):m())}}),u.useLayoutEffect(()=>{const T=setTimeout(async()=>{e.currentUser&&o.current&&(w(!1),k(!0),await Y(o.current,a,l),k(!1),w(!0))});return()=>clearTimeout(T)},[e,(Oe=e.currentUser)==null?void 0:Oe.userId,(Re=o.current)==null?void 0:Re.url,r.current.replyType]),u.useEffect(()=>()=>{f.current.instance&&f.current.instance.dispose()},[]);const z=ye(async()=>{e.currentUser&&o.current&&(I(!0),await Y(o.current,Number.MAX_SAFE_INTEGER,tn.collection.message.defaultLimit),I(!1))}),V=ye(async()=>{var R;const T=f.current.instance;if(T!=null&&T.hasPrevious&&!d.current.prev)try{d.current.prev=!0;const N=await T.loadPrevious();E(N,!1,(R=e.currentUser)==null?void 0:R.userId)}catch{}finally{d.current.prev=!1}}),H=ye(()=>{const{initialized:T,instance:R}=f.current;return T&&R?R.hasPrevious:!1}),W=ye(async()=>{var R;const T=f.current.instance;if(T!=null&&T.hasNext&&!d.current.next)try{d.current.next=!0;const N=await T.loadNext();E(N,!1,(R=e.currentUser)==null?void 0:R.userId)}catch{}finally{d.current.next=!1}}),q=ye(()=>{const{initialized:T,apiInitialized:R,instance:N}=f.current;return R&&T&&N?N.hasNext:!1}),ce=ye((T,R)=>{var N;if(!o.current||!o.current.url)throw(N=s==null?void 0:s.error)==null||N.call(s,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((j,U)=>{o.current.sendUserMessage(T).onPending(G=>{var B;G.channelUrl===o.current.url&&E([G],!1,(B=e.currentUser)==null?void 0:B.userId),R==null||R(G)}).onSucceeded(G=>{var B;G.channelUrl===o.current.url&&E([G],!1,(B=e.currentUser)==null?void 0:B.userId),j(G)}).onFailed((G,B)=>{var ue;B&&B.channelUrl===o.current.url&&E([B],!1,(ue=e.currentUser)==null?void 0:ue.userId),U(G)})})}),_e=ye((T,R)=>{var N;if(!o.current||!o.current.url)throw(N=s==null?void 0:s.error)==null||N.call(s,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((j,U)=>{o.current.sendFileMessage(T).onPending(G=>{var B;G.channelUrl===o.current.url&&E([G],!1,(B=e.currentUser)==null?void 0:B.userId),R==null||R(G)}).onSucceeded(G=>{var B;G.channelUrl===o.current.url&&E([G],!1,(B=e.currentUser)==null?void 0:B.userId),j(G)}).onFailed((G,B)=>{var ue;B&&B.channelUrl===o.current.url&&E([B],!1,(ue=e.currentUser)==null?void 0:ue.userId),U(G)})})}),L=ye(async(T,R)=>{var N;if(!o.current||!o.current.url)throw(N=s==null?void 0:s.error)==null||N.call(s,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise(j=>{const U=[];o.current.sendFileMessages(T).onPending(G=>{var B;G.channelUrl===o.current.url&&E([G],!1,(B=e.currentUser)==null?void 0:B.userId),R==null||R(G)}).onSucceeded(G=>{var B;G.isFileMessage()&&G.channelUrl===o.current.url&&(E([G],!1,(B=e.currentUser)==null?void 0:B.userId),U.push(G)),U.length===T.length&&j(U)}).onFailed((G,B)=>{var ue;B&&B.channelUrl===o.current.url?(E([B],!1,(ue=e.currentUser)==null?void 0:ue.userId),U.push(B)):U.push(null),U.length===T.length&&j(U)})})}),X=ye((T,R)=>{var N;if(!o.current||!o.current.url)throw(N=s==null?void 0:s.error)==null||N.call(s,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((j,U)=>{o.current.sendMultipleFilesMessage(T).onPending(G=>{var B;G.channelUrl===o.current.url&&E([G],!1,(B=e.currentUser)==null?void 0:B.userId),R==null||R(G)}).onFileUploaded(()=>{m()}).onSucceeded(G=>{var B;G.channelUrl===o.current.url&&E([G],!1,(B=e.currentUser)==null?void 0:B.userId),j(G)}).onFailed((G,B)=>{var ue;B&&B.channelUrl===o.current.url&&E([B],!1,(ue=e.currentUser)==null?void 0:ue.userId),U(G)})})}),K=ye(async(T,R)=>{var j,U;if(!o.current||!o.current.url)throw(j=s==null?void 0:s.error)==null||j.call(s,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");const N=await o.current.updateUserMessage(T,R);return N.channelUrl===o.current.url&&E([N],!1,(U=e.currentUser)==null?void 0:U.userId),N}),P=ye(async(T,R)=>{var j,U;if(!o.current||!o.current.url)throw(j=s==null?void 0:s.error)==null||j.call(s,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");const N=await o.current.updateFileMessage(T,R);return N.channelUrl===o.current.url&&E([N],!1,(U=e.currentUser)==null?void 0:U.userId),N}),te=ye(async T=>{var R;if(!o.current||!o.current.url)throw(R=s==null?void 0:s.error)==null||R.call(s,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((N,j)=>{let U;T.isUserMessage()&&(U=o.current.resendMessage(T)),T.isFileMessage()&&(U=o.current.resendMessage(T)),T.isMultipleFilesMessage()&&(U=o.current.resendMessage(T)),U&&("onPending"in U&&U.onPending(G=>{var B;G.channelUrl===o.current.url&&E([G],!1,(B=e.currentUser)==null?void 0:B.userId)}),"onFileUploaded"in U&&U.onFileUploaded(()=>{m()}),"onSucceeded"in U&&U.onSucceeded(G=>{var B;G.channelUrl===o.current.url&&E([G],!1,(B=e.currentUser)==null?void 0:B.userId),N(G)}),"onFailed"in U&&U.onFailed((G,B)=>{var ue;B&&B.channelUrl===o.current.url&&E([B],!1,(ue=e.currentUser)==null?void 0:ue.userId),j(G)}))})}),de=ye(async T=>{var R,N;if(!o.current||!o.current.url)throw(R=s==null?void 0:s.error)==null||R.call(s,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");if(T.sendingStatus==="succeeded")T.isUserMessage()&&await o.current.deleteMessage(T),T.isFileMessage()&&await o.current.deleteMessage(T),T.isMultipleFilesMessage()&&await o.current.deleteMessage(T);else try{await((N=f.current.instance)==null?void 0:N.removeFailedMessage(T.reqId))}finally{x([],[T.reqId])}}),fe=ye(()=>{var T;C([],!0,(T=e.currentUser)==null?void 0:T.userId)}),xe=ye(async T=>{var R;if(e.currentUser&&o.current){const N=Jr(T);k(!0),E([],!0,(R=e.currentUser)==null?void 0:R.userId),await Y(o.current,T,N),k(!1)}});return{initialized:g,loading:_,refreshing:v,messages:y,newMessages:b,resetNewMessages:fe,refresh:z,loadPrevious:V,hasPrevious:H,loadNext:W,hasNext:q,sendUserMessage:ce,sendFileMessage:_e,sendFileMessages:L,sendMultipleFilesMessage:X,updateUserMessage:K,updateFileMessage:P,resendMessage:te,deleteMessage:de,resetWithStartingPoint:xe,_dangerous_reducer_updateMessages:E,_dangerous_reducer_deleteMessages:x}},Kl=(e,t,n)=>{const r=u.useRef(0),o=u.useRef(new Set),s=u.useCallback(d=>{const m={id:r.current+=1,...d};o.current.forEach(f=>{f(m)})},[]),a=u.useCallback(d=>{var f;const m=((f=n==null?void 0:n.collectionCreator)==null?void 0:f.call(n,d))??(t==null?void 0:t.createMessageCollection({...d??{},filter:new ze.MessageFilter(d)}));if(!m)throw new Error("Group channel is required to create a message collection");return Dl(m,s)},[t,n==null?void 0:n.collectionCreator,s]),l=ql(e,t,{...n,collectionCreator:a,strictStreamingOrder:!0}),c=u.useCallback(d=>(o.current.add(d),()=>{o.current.delete(d)}),[]);return{...l,subscribeMessageEvents:c}},wt={DEFAULT_PRIMARY:"#000000",DEFAULT_BOT_MSG_BG:"#ECECEC",WHITE:"#ffffff",BLACK:"#000000"};function Ms(e){return e.length===4?`#${[...e.slice(1)].map(t=>t+t).join("")}`:e}function jl(e){const t=Ms(e);return[parseInt(t.slice(1,3),16),parseInt(t.slice(3,5),16),parseInt(t.slice(5,7),16)]}function Xl(e){return`#${e.map(t=>t.toString(16).padStart(2,"0")).join("")}`}function Zl(e,t,n){e/=255,t/=255,n/=255;const r=Math.max(e,t,n),o=Math.min(e,t,n),s=r-o;let a=0,l=0;const c=(r+o)/2;return r!==o&&(l=c>.5?s/(2-r-o):s/(r+o)),r===e?a=(t-n)/s+(t<n?6:0):r===t?a=(n-e)/s+2:r===n&&(a=(e-t)/s+4),a/=6,[a,l,c]}function Jl(e,t,n){let r,o,s;if(t===0)r=o=s=n;else{const a=function(m,f,g){return g<0&&(g+=1),g>1&&(g-=1),g<.16666666666666666?m+(f-m)*6*g:g<.5?f:g<.6666666666666666?m+(f-m)*(.6666666666666666-g)*6:m},l=n<.5?n*(1+t):n+t-n*t,c=2*n-l;r=a(c,l,e+1/3),o=a(c,l,e),s=a(c,l,e-1/3)}return[Math.round(r*255),Math.round(o*255),Math.round(s*255)]}function Bt(e,t,n){const[r,o,s]=jl(e),[a,l,c]=Zl(r,o,s),d=Math.max(0,Math.min(1,c*t)),m=Math.max(0,Math.min(1,l*n)),[f,g,_]=Jl(a,m,d);return Xl([Math.round(f),Math.round(g),Math.round(_)])}function Ql(e,t="light"){return{extraDark:Bt(e,.6,1.2),dark:Bt(e,.85,1.1),main:e,light:Bt(e,t==="dark"?1.1:1.5,t==="dark"?.95:.9),extraLight:Bt(e,t==="dark"?1.2:1.75,t==="dark"?.9:.8)}}function Vn(e){const t=Ms(e),n=149,r=+`0x${t[1]}${t[2]}`,o=+`0x${t[3]}${t[4]}`,s=+`0x${t[5]}${t[6]}`;return r*.299+o*.587+s*.114>n?wt.BLACK:wt.WHITE}function ec(e,t,n,r,o){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:o,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 tc=(e,t,n,r,o)=>({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:o,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"}}),Ht={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)"}},xn={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 Qr(e){const t=nc(e),n=rc(e,t),r=sc(n,e.colors,e.selectedTheme),o=ac(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:o}}function nc({selectedTheme:e,palette:t,primary:n}){const r=t!=null&&t.primary?t.primary:n?n===Ht.primary.main?Ht.primary:Ql(n,e):Ht.primary;return{...Ht,primary:r,...t}}function rc({selectedTheme:e,primaryContrast:t,botMessageBackground:n,botMessageBackgroundContrast:r},o){const s=o.primary.main,a=t??Vn(s),l=n??wt.DEFAULT_BOT_MSG_BG,c=r??Vn(l);return(e==="light"?ec:tc)(o,s,a,l,c)}function oc(e,t,n){return typeof e=="string"?e:e[t]??n}function sc(e,t,n){var a;if(!t||Object.keys(t).length===0)return e;const r={...e},o=r,s=e;for(const l of Object.keys(t)){const c=t[l];if(c){o[l]={...o[l]};for(const[d,m]of Object.entries(c))if(m!==void 0){const f=((a=s[l])==null?void 0:a[d])??"";o[l][d]=oc(m,n,f)}}}return r}function ic(e,t,n){const r={...e};return n.forEach(o=>{const s=t[o];s!=null&&(r[o]=s)}),r}function ac({typography:e}){if(!e)return xn;const t={...xn};return Object.keys(e).forEach(n=>{const r=e[n];if(r&&typeof r=="object"){const o=xn[n],s=["fontSize","fontWeight","fontFamily","lineHeight"];t[n]=ic(o,r,s)}}),t}const{Provider:lc,useContext:dr}=Ee("AIAgentTheme");function cc({logger:e,palette:t,typography:n,colors:r,appearance:o,children:s}){const a=u.useRef(null),[l,c]=u.useState(()=>Qr({selectedTheme:(o==null?void 0:o.theme)??"light",palette:t,typography:n,colors:r,primary:o==null?void 0:o.primaryColor,botMessageBackground:o==null?void 0:o.botMessageBackgroundColor})),d=u.useCallback((m,f)=>{f&&(a.current=f);const g=(o==null?void 0:o.theme)??m,_=a.current?a.current.themes[g]:null,v={primary:o==null?void 0:o.primaryColor,primaryContrast:void 0,botMessageBackground:o==null?void 0:o.botMessageBackgroundColor,botMessageBackgroundContrast:void 0};!v.primary&&(_!=null&&_.primary_color)&&(v.primary=_.primary_color,v.primaryContrast=_.primary_contrast_color),!v.botMessageBackground&&(_!=null&&_.bot_message_bg_color)&&(v.botMessageBackground=_.bot_message_bg_color,v.botMessageBackgroundContrast=_.bot_message_bg_contrast_color);const y=Qr({selectedTheme:g,palette:t,typography:n,colors:r,...v});c(y),e==null||e.info("theme.update:",g)},[o==null?void 0:o.theme,o==null?void 0:o.primaryColor,o==null?void 0:o.botMessageBackgroundColor,t,n,r,e]);return u.useEffect(()=>{(o!=null&&o.theme||o!=null&&o.primaryColor||o!=null&&o.botMessageBackgroundColor)&&d(l.selectedTheme)},[o==null?void 0:o.theme,o==null?void 0:o.primaryColor,o==null?void 0:o.botMessageBackgroundColor]),i.createElement(lc,{value:{theme:l,updateTheme:d}},s)}const Tn=25*1024*1024,eo=1,to=new Set(["image/png","image/jpeg","image/jpg"]),no=new Set(["application/pdf"]),uc={off:"off",always:"always",handed_off_only:"handed_off_only"},dc=()=>{const[e,t]=u.useState(()=>({maxAttachmentCount:eo,attachmentMode:"handed_off_only",defaultUploadSizeLimit:Tn,uploadSizeLimitPerType:new Map,supportedImageMimeTypes:to,supportedFileMimeTypes:no})),n=u.useCallback(({active_channel:o,upload_restriction:s})=>{t({maxAttachmentCount:(s==null?void 0:s.max_attachment_count)??eo,attachmentMode:uc[o.attachment_mode]??"handed_off_only",defaultUploadSizeLimit:(s==null?void 0:s.default_upload_size_limit)??Tn,uploadSizeLimitPerType:new Map(Object.entries((s==null?void 0:s.upload_size_limit_per_type)??[])),supportedImageMimeTypes:new Set((s==null?void 0:s.supported_image_mime_types)??to),supportedFileMimeTypes:new Set((s==null?void 0:s.supported_file_mime_types)??no)})},[]),r=u.useCallback(o=>{const{channel:s,uploadSizeLimit:a=Tn}=o,l=(d=!0)=>s!=null&&s.isAIAgent?d?et(s):!1:!0,c=d=>{if(l())return e.defaultUploadSizeLimit??a;const m=e.defaultUploadSizeLimit??a,f=e.uploadSizeLimitPerType.get(d)??m;return Math.min(m,f)};return{maxAttachmentCount:e.maxAttachmentCount,isEnabled:()=>{if(l(!1))return!0;switch(e.attachmentMode){case"off":return!1;case"always":return!0;case"handed_off_only":return et(s);default:return!0}},get supportedMimeTypes(){return l()?[Un]:[...e.supportedImageMimeTypes,...e.supportedFileMimeTypes]},isSupportedMimeType:d=>l()?!0:e.supportedImageMimeTypes.has(d)||e.supportedFileMimeTypes.has(d),getUploadSizeLimit:c,getUploadSizeLimitInMB:d=>c(d)/(1024*1024)}},[e]);return{updateBaseAttachmentRules:n,createAttachmentRules:r}},ro=(...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)")},vt=e=>({...e,context:e.context??{}}),{Provider:mc,useContext:pt}=Ee("AIAgentMessengerSession"),fc=u.forwardRef(function({userSessionInfo:e,children:t},n){const{_aiAgentSDK:r,chatSDK:o,aiAgentId:s,logger:a}=ke(),{updateTheme:l}=dr(),[c,d]=u.useState(void 0),[m,f]=u.useState(void 0),[g,_]=u.useState(null),[v,y]=u.useState(null),[b,E]=u.useState(null),[C,S]=u.useState(null),[x,w]=u.useState(null),{updateBaseAttachmentRules:k,createAttachmentRules:I}=dc();u.useEffect(()=>{const Y=r.onMessengerSettingsUpdated(({settings:H})=>{const{appearance:W,bot:q,launcher:ce,memory:_e}=H;l(W.selected_theme,W),E(ja(q)),S(Xa(ce)),w(_e?Gn(_e):null),k(H)}),z=r.onActiveChannelUpdated(({channelUrl:H,status:W,conversationStatus:q})=>{f({url:H,status:W,conversationStatus:q})}),V=r.onAuthTokenRefreshed(()=>{var W;const H=(W=r.session)==null?void 0:W.userSession.authToken;H&&y(q=>q?{...q,authToken:H}:null)});return()=>{Y(),z(),V()}},[r,l,k]);const M=u.useCallback(async()=>{try{const Y=await r.authenticate(e),z=r.session;return _(z.sdkUser),y(z.userSession),f(z.activeChannel),d(void 0),Y}catch(Y){throw _(null),y(null),f(void 0),d(Y),Y}},[r,e]),O=u.useCallback(async()=>{await r.deauthenticate(),_(null),f(void 0),y(null),E(null),S(null),w(null)},[r]),F=u.useCallback(async()=>{if(!r.session){if(v)return a.debug("agentMessengerSession.refreshActiveChannel: stale call after deauthenticate, skipping"),"";throw a.error("agentMessengerSession.refreshActiveChannel: userSession is not ready"),new Error("userSession is not ready")}return r.session.userSession.userId!==(v==null?void 0:v.userId)?(a.debug("agentMessengerSession.refreshActiveChannel: stale call from previous session, skipping"),r.session.activeChannel.url):(f(void 0),await r.refreshActiveChannel())},[r,a,v]);return u.useImperativeHandle(n,()=>{const Y=async()=>{if(!m)throw new Error("No active conversation. Please start a conversation first.");return await o.groupChannel.getChannel(m.url)};return{activeChannel:m,chatSDK:o,authenticate:M,deauthenticate:O,updateContext:async(...z)=>{const V=ro(...z);if(V.type==="active"){const q=await(await Y()).updateContext(s,V.context);return vt(q)}const H=await o.aiAgent.updateContext(V.aiAgentId,V.channelUrl,V.context);return vt(H)},patchContext:async(...z)=>{const V=ro(...z);if(V.type==="active"){const q=await(await Y()).patchContext(s,V.context);return vt(q)}const H=await o.aiAgent.patchContext(V.aiAgentId,V.channelUrl,V.context);return vt(H)},getContextObject:async()=>{const V=await(await Y()).getContextObject(s);return vt(V)}}},[M,O,m,o,s,a]),i.createElement(mc,{value:{sdkUser:g,userSessionInfo:e,userSession:v,activeChannel:m,setActiveChannel:f,refreshActiveChannel:F,createConversation:r.createConversation,searchConversation:r.searchConversation,connectionError:c,aiAgentInfo:b,launcherInfo:C,memoryInfo:x,authenticate:M,deauthenticate:O,createAttachmentRules:I,statsTrackers:r.statsTrackers}},t)}),Lt=(e,t)=>{const n=u.useId(),r=u.useRef(t);u.useLayoutEffect(()=>{r.current=t}),u.useLayoutEffect(()=>{const o=new he.ConnectionHandler({onDisconnected:s=>{var a,l;return(l=(a=r.current).onDisconnected)==null?void 0:l.call(a,s)},onConnected:s=>{var a,l;return(l=(a=r.current).onConnected)==null?void 0:l.call(a,s)},onReconnectStarted:()=>{var s,a;return(a=(s=r.current).onReconnectStarted)==null?void 0:a.call(s)},onReconnectSucceeded:()=>{var s,a;return(a=(s=r.current).onReconnectSucceeded)==null?void 0:a.call(s)},onReconnectFailed:()=>{var s,a;return(a=(s=r.current).onReconnectFailed)==null?void 0:a.call(s)},onConnectionLost:()=>{var s,a;return(a=(s=r.current).onConnectionLost)==null?void 0:a.call(s)},onConnectionDelayed:s=>{var a,l;return(l=(a=r.current).onConnectionDelayed)==null?void 0:l.call(a,s)}});return e.addConnectionHandler(n,o),()=>{e.removeConnectionHandler(n)}},[e,n])};function gc(e){const{chatSDK:t,logger:n,aiAgentId:r,_aiAgentSDK:o}=ke(),{sdkUser:s,statsTrackers:a}=pt(),l=dn(),[c,d]=u.useState(void 0),[m,f]=u.useState(void 0),[g,_]=u.useState(!1);function v(b){b.isAIAgent&&!b.conversation&&(_(!0),o.initConversationIfNeeded(b).finally(()=>_(!1)))}async function y(){var b,E,C;if(!s){n.debug("useChannel.getChannel: no sdk user, skip fetching channel");return}if(n.debug("useChannel.getChannel: start"),d(void 0),f(void 0),_(!1),e){a.initialRender.onGetChannelStart();try{n.debug("useChannel.getChannel: get channel",e);const S=await t.groupChannel.getChannel(e);v(S),d(S),a.initialRender.onGetChannelComplete((b=S.conversation)==null?void 0:b.id),S.url===((E=o.session)==null?void 0:E.activeChannel.url)&&o.session._updateActiveChannel({url:S.url,status:Le(S)?"closed":"open",conversationStatus:(C=S.conversation)==null?void 0:C.status}),n.debug("useChannel.getChannel: fetched channel",S)}catch(S){a.initialRender.onGetChannelError(S),S instanceof he.SendbirdError&&f(S),n.error("useChannel.getChannel: error",S)}}}return u.useEffect(()=>{y()},[t,s,e,r]),Lt(t,{async onReconnectSucceeded(){if(!c)return;const b=await c.refresh();v(b),d(b)}}),ht(t,{onChannelChanged:b=>{b.isGroupChannel()&&b.url===e&&(n.debug("useChannel.onChannelChanged: channel changed",b.url),d(b),l())}}),{channel:c,channelFetchError:m,getChannel:y,isInitializingConversation:g}}const hc=new Set(["suggested_replies","steward","system"]),pc=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||!hc.has(r)))return r},_c=e=>{var a;const t=e==null?void 0:e.lastMessage;if(!t||!e)return!1;const n=t.extendedMessagePayload,r=n==null?void 0:n.form,o=!!r&&!r.submitted_at&&!r.canceled_at,s=e.isAIAgent&&!!((a=e.conversation)!=null&&a.handedOverAt);return o&&!s},Ec=()=>{const{chatSDK:e,networkStateAdapter:t}=ke(),[n,r]=u.useState(()=>t?t.isOnline()?"connected":"reconnecting":"connected");return Lt(e,{onConnected:()=>r("connected"),onDisconnected:()=>r("disconnected"),onReconnectStarted:()=>r("reconnecting"),onReconnectSucceeded:()=>r("connected"),onReconnectFailed:()=>r("disconnected"),onConnectionLost:()=>r("reconnecting")}),u.useEffect(()=>{if(t)return t.subscribe(o=>{if(!o){r("reconnecting");return}r(s=>s==="reconnecting"&&e.connectionState===he.ConnectionState.OPEN?"connected":s)})},[t,e]),n},bc=3e4,Cc=({shouldApply:e,lastMessage:t,isBlockedWhileAIResponding:n,currentUserId:r})=>{const[o,s]=u.useState(!1),a=u.useRef(null),l=t&>(t,r)?t.createdAt:0;return u.useEffect(()=>{const c=()=>{a.current&&(clearTimeout(a.current),a.current=null),s(!1)},d=g=>{a.current&&clearTimeout(a.current),s(!0),a.current=setTimeout(()=>{s(!1),a.current=null},g)},m=Date.now()-l,f=bc-m;return n||f<=0?c():d(f),()=>{a.current&&clearTimeout(a.current)}},[n,l]),o&&e},ks=e=>{const{chatSDK:t}=ke(),[n,r]=u.useState([]);return ht(t,{onTypingStatusUpdated(o){if(o.url===(e==null?void 0:e.url)){const s=o.getTypingUsers();r(s)}}}),n},vc=({channel:e,lastMessage:t,aiAgentUserId:n,isStreamAnimating:r})=>{const[o,s]=u.useState(!1),a=ks(e);return u.useEffect(()=>{if(!t)return;const l=a.some(d=>d.userId===n),c=gt(t,n)&&(Ve.isStreaming(t)||r);s(c||l)},[a,t,n,r]),o},yc=({channel:e,messages:t,isStreamAnimating:n,isInitializingConversation:r})=>{const{aiAgentInfo:o,userSession:s}=pt(),a=Ec(),l=vc({channel:e,lastMessage:Ur(t,[Ue.SendingStatus.SUCCEEDED]),aiAgentUserId:(o==null?void 0:o.userId)??"",isStreamAnimating:n}),c=Cc({shouldApply:!!(e!=null&&e.isAIAgent)&&!et(e),isBlockedWhileAIResponding:l,lastMessage:Ur(t,[Ue.SendingStatus.PENDING,Ue.SendingStatus.SUCCEEDED]),currentUserId:(s==null?void 0:s.userId)??""}),d=f=>f===""?{disabled:!1,disabledBy:"",focusPolicy:"auto"}:f==="ai_responding"?{disabled:!0,disabledBy:f,focusPolicy:"preserve"}:{disabled:!0,disabledBy:f,focusPolicy:"release"};if(!e||a==="disconnected")return d("unavailable");if(a==="reconnecting")return d("reconnecting");if(Le(e))return d("conversation_closed");if(Za(e))return d("handoff_pending");if(_c(e))return d("form_active");const m=pc(e);return d(m||(l||c||r?"ai_responding":""))},Sc=()=>{const[e,t]=u.useState(new Set),n=u.useCallback(o=>{t(s=>{if(s.has(o))return s;const a=new Set(s);return a.add(o),a})},[]),r=u.useCallback(o=>{t(s=>{if(!s.has(o))return s;const a=new Set(s);return a.delete(o),a})},[]);return{isAnimating:e.size>0,start:n,stop:r}},{Provider:Ac}=Ee("AIAgentConversation");function xc({children:e,channelUrl:t,onChannelDeleted:n,onMessagesReceived:r,onMessagesUpdated:o,onConversationClosedStatusChanged:s,onConversationClosedViaDispatcher:a,onBeforeSendMessage:l,onAfterSendMessage:c=ge,shouldMarkAsRead:d=!0,shouldCountNewMessages:m=()=>!1,sortComparator:f}){var Y;const g=()=>d&&(E==null?void 0:E.markAsRead()),{_aiAgentSDK:_,chatSDK:v,logger:y,dispatcher:b}=ke(),{channel:E,channelFetchError:C,getChannel:S,isInitializingConversation:x}=gc(t),{statsTrackers:w}=pt();u.useEffect(()=>{if(t)return w.initialRender.setChannelUrl(t),()=>{w.initialRender.cleanup()}},[t,w]);const k=Kl(v,E,{replyType:Ue.ReplyType.ONLY_REPLY_TO_CHANNEL,shouldCountNewMessages:m,onChannelDeleted:n,onMessagesReceived:z=>r==null?void 0:r(z),onMessagesUpdated:z=>o==null?void 0:o(z),onCacheResult:z=>w.initialRender.onCacheResult(z),onApiResult:z=>w.initialRender.onApiResult(z),logger:y,markAsRead:g,sortComparator:f}),I=Sc(),M=yc({channel:E,messages:k.messages,isStreamAnimating:I.isAnimating,isInitializingConversation:x});u.useEffect(()=>{g()},[d,E]);const O=Le(E);u.useEffect(()=>{s==null||s(O)},[O,s]),u.useEffect(()=>{const z=async V=>{const H=typeof(V==null?void 0:V.channelUrl)=="string";E&&H&&V.channelUrl!==E.url||(y.debug("conversation.dispatcher: try to close conversation",E),E!=null&&E.conversation&&E.conversation.status===be.ConversationStatus.OPEN&&(await E.closeConversation(),a==null||a()))};return b.subscribe(Fe.ConversationClose,z),()=>{b.unsubscribe(Fe.ConversationClose,z)}},[b,E,y,(Y=E==null?void 0:E.conversation)==null?void 0:Y.status,a]);const F={conversation:(E==null?void 0:E.conversation)??void 0,actions:{setUserMemoryState:_.setUserMemoryState},channelSource:{channel:E,error:C,refetch:()=>S(),closeConversation:async()=>{Le(E)||await(E==null?void 0:E.closeConversation())}},messageSource:{messages:k.messages,newMessages:k.newMessages,initialized:k.initialized,subscribeMessageEvents:k.subscribeMessageEvents,loadPrevious:()=>k.loadPrevious(),loadNext:()=>k.loadNext(),deleteMessage:z=>k.deleteMessage(z),resendMessage:z=>k.resendMessage(z),resetNewMessages:()=>k.resetNewMessages(),sendUserMessage:async z=>{var H;if(((H=E==null?void 0:E.conversation)==null?void 0:H.status)===be.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(z=await l(z));const V=await k.sendUserMessage(z,c);return c==null||c(V),V},sendFileMessage:async z=>{var H;if(((H=E==null?void 0:E.conversation)==null?void 0:H.status)===be.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(z=await l(z));const V=await k.sendFileMessage(z,c);return c==null||c(V),V},sendMultipleFilesMessage:async z=>{var H;if(((H=E==null?void 0:E.conversation)==null?void 0:H.status)===be.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(z=await l(z));const V=await k.sendMultipleFilesMessage(z,c);return c==null||c(V),V}},state:{streamAnimation:I,input:M}};return i.createElement(Ac,{value:F},e)}function Tc(e,t){var _,v,y,b,E,C,S,x,w,k;const[n,r]=u.useState(!1),[o,s]=u.useState(null),[a,l]=u.useState([]),[c,d]=u.useState(null),m=u.useRef(!1),f=u.useCallback(async()=>{if(!m.current&&e.currentUser){m.current=!0,r(!1),s(null),l([]);try{c==null||c.dispose();const I=new gs(e,t);I.setConversationListCollectionHandler({onChannelsAdded:()=>{l(I.channels)},onChannelsUpdated:()=>{l(I.channels)},onChannelsDeleted:()=>{l(I.channels)}}),await I.loadMore(),l(I.channels),d(I),s(null)}catch(I){d(null),s(I)}finally{r(!0),m.current=!1}}},[e,e.currentUser,(_=t.filter)==null?void 0:_.aiAgentChannelFilter,(y=(v=t.filter)==null?void 0:v.aiAgentConversationStatusFilter)==null?void 0:y.join(),(E=(b=t.filter)==null?void 0:b.aiAgentIds)==null?void 0:E.join(),(C=t.filter)==null?void 0:C.deskChannelFilter,(x=(S=t.filter)==null?void 0:S.pinnedChannelUrls)==null?void 0:x.join(),(w=t.filter)==null?void 0:w.copilotConversationOnly,(k=t.filter)==null?void 0:k.copilotSupportChannelUrl,t.limit]),g=u.useCallback(async()=>{if(c)try{await c.loadMore(),l(c.channels)}catch(I){s(I)}},[c]);return Lt(e,{onConnected:()=>f()}),u.useEffect(()=>{f()},[f]),u.useEffect(()=>()=>{m.current=!1,c==null||c.dispose()},[c]),{initialized:n,error:o,channels:a,loadMore:g}}const Rs=e=>{var o;const{aiAgentId:t,queryParams:n}=ke(),r=(o=n==null?void 0:n.conversationListParams)==null?void 0:o.filter;return{aiAgentIds:[t],aiAgentConversationStatusFilter:[be.ConversationStatus.CLOSED,be.ConversationStatus.OPEN],...r,...e}},{Provider:Ic}=Ee("AIAgentConversationList");function wc({conversationListLimit:e,conversationListFilter:t,children:n}){var d;const{chatSDK:r,queryParams:o}=ke(),s=e??((d=o==null?void 0:o.conversationListParams)==null?void 0:d.limit),a=Rs(t),l=Tc(r,{limit:s,filter:a}),c={listSource:{initialized:l.initialized,error:l.error??void 0,channels:l.channels,loadMore:()=>l.loadMore()}};return i.createElement(Ic,{value:c},n)}function Mc(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:kc,useContext:Rc}=Ee("MessageTemplateFetching");function Lc({children:e,internalVariables:t}){const n=u.useRef({}),r=u.useRef({}),[o,s]=u.useState({}),a=u.useCallback((d,m)=>{s(f=>({...f,[d]:{fetching:!1,error:!1,...f[d],...m}}))},[]),l=u.useCallback(async({onRequestTemplate:d,onGetCachedTemplate:m,templateKey:f,suspense:g=!1})=>{const _=m(f);if(_)return _;const v=r.current[f];if(v)return v;g||a(f,{fetching:!0});const y=d(f).catch(b=>{throw g||a(f,{error:!0}),b}).finally(()=>{g||a(f,{fetching:!1}),delete r.current[f]});return r.current[f]=y,y},[a]),c={internalVariables:t,fetchTemplate:l,suspend:(d,m)=>{if(n.current[d])return n.current[d];const f=Mc(m());return n.current[d]=f,f},getIsFetching:d=>{var m;return((m=o[d])==null?void 0:m.fetching)??!1},getHasError:d=>{var m;return((m=o[d])==null?void 0:m.error)??!1}};return i.createElement(kc,{value:c},e)}const Oc="remove_powered_by",mr=(e,t)=>{var o,s;const{chatSDK:n}=ke(),{aiAgentInfo:r}=pt();if(e==="handoff-button"){const a=!!((o=t==null?void 0:t.conversation)!=null&&o.handoff);return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.showHandoffButton)&&a&&sr(t)}if(e==="special-notice")return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.specialNoticeEnabled)&&!!(r!=null&&r.specialNotice);if(e==="powered-by"){const a=(s=n==null?void 0:n.appInfo)==null?void 0:s.applicationAttributes;return u.useMemo(()=>!(Array.isArray(a)&&a.includes(Oc)),[a])}throw new Error("Unsupported feature")},Nc={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"},Dc={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:o}=e;if(o){if(o.min_length!==void 0&&r.length<o.min_length)return{isValid:!1,error:typeof n.minLength=="function"?n.minLength(o.min_length):n.minLength};if(o.max_length!==void 0&&r.length>o.max_length)return{isValid:!1,error:typeof n.maxLength=="function"?n.maxLength(o.max_length):n.maxLength};if(o.regex&&!new RegExp(o.regex).test(r))return{isValid:!1,error:n.regex}}return{isValid:!0}}},$c={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:o}=e;if(o){if(o.min!==void 0&&r<o.min)return{isValid:!1,error:typeof n.min=="function"?n.min(o.min):n.min};if(o.max!==void 0&&r>o.max)return{isValid:!1,error:typeof n.max=="function"?n.max(o.max):n.max}}return{isValid:!0}}},Pc={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}}},Fc={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(a=>!e.options.includes(a)).length>0)return{isValid:!1,error:n.invalidSelection};const{rules:s}=e;if(s){if(s.min_select!==void 0&&r.length<s.min_select)return{isValid:!1,error:typeof n.minSelect=="function"?n.minSelect(s.min_select):n.minSelect};if(s.max_select!==void 0&&r.length>s.max_select)return{isValid:!1,error:typeof n.maxSelect=="function"?n.maxSelect(s.max_select):n.maxSelect}}return{isValid:!0}}},Uc={text:Dc,number:$c,"single-select":Pc,"multi-select":Fc},Bc={getValueOrDefault:()=>null,validate:()=>({isValid:!1})};function Ls(e){return Uc[e.type]||Bc}function oo(e){return Ls(e).getValueOrDefault(e)}function Hc(e,t,n={}){const r={...Nc,...n};return Ls(e).validate(e,t,r)}const Gc=(e,t={})=>{const{labels:n={},onSubmit:r,onCancel:o}=t,[s,a]=u.useState({}),[l,c]=u.useState(()=>{const y={};return e.fields.forEach(b=>{y[b.key]=oo(b)}),y}),d=u.useMemo(()=>e.submitted_at?"submitted":e.canceled_at?"canceled":"draft",[e.submitted_at,e.canceled_at]);u.useEffect(()=>{if(d==="submitted"||d==="canceled"){const y={};let b=!1;e.fields.forEach(E=>{const C=oo(E);JSON.stringify(l[E.key])!==JSON.stringify(C)&&(b=!0),y[E.key]=C}),b&&c(y)}},[d]);const m=(y,b)=>{c(E=>({...E,[y]:b})),a(E=>({...E,[y]:void 0}))},f=e.fields.map(y=>{var C,S,x;const b=l[y.key]??null,E={key:y.key,label:y.label,error:s[y.key],required:y.required};return y.type==="text"?{...E,type:"text",layout:y.layout,value:b,...y.placeholder&&{placeholder:y.placeholder},...((C=y.rules)==null?void 0:C.max_length)&&{maxLength:y.rules.max_length}}:y.type==="number"?{...E,type:"number",layout:y.layout,value:b,...y.placeholder&&{placeholder:y.placeholder},...((S=y.rules)==null?void 0:S.max)&&{max:y.rules.max}}:y.type==="single-select"?{...E,type:"single-select",layout:y.layout,value:b,options:y.options}:y.type==="multi-select"?{...E,type:"multi-select",layout:y.layout,value:b,options:y.options,...((x=y.rules)==null?void 0:x.max_select)&&{maxSelect:y.rules.max_select}}:{...E,type:"unknown",layout:"default",value:null}});return{state:d,fields:f,getField:y=>f.find(b=>b.key===y),updateFieldValue:m,submit:async()=>{const y={};let b=!1;for(const E of e.fields){const C=l[E.key]??null,S=Hc(E,C,n);S.isValid||(y[E.key]=S.error,b=!0)}if(a(y),!b&&r){const E={};e.fields.forEach(C=>{E[C.key]=l[C.key]??null}),await r(E)}},cancel:async()=>{await(o==null?void 0:o())}}},zc=e=>{const{chatSDK:t,handlers:n,logger:r}=ke(),{aiAgentInfo:o}=pt(),s=u.useRef(new Set),a=u.useRef(new Set),l=(m,f)=>{if(!(n!=null&&n.onCustomEvent)||!(o!=null&&o.userId)||!gt(m,o.userId))return;const g=m.messageId;if(Ve.isStreaming(m)){a.current.add(g);return}f==="updated"&&!a.current.has(g)||(r.debug("useCustomEventForMessageReceive: bot-message-received",m),n.onCustomEvent({type:"bot-message-received",data:{message:m}}),a.current.delete(g))},c=u.useCallback(m=>{if(n!=null&&n.onCustomEvent&&m.isAdminMessage()&&m.customType==="user_action_required"&&!s.current.has(m.messageId)){const f=Bn(m.data);Array.isArray(f.history)&&f.history.length===0&&(r.debug("useCustomEventForMessageReceive: user_action_required",f),n.onCustomEvent({type:"user-action-requested",data:f}),s.current.add(m.messageId))}},[n,r]),d=(m,f,g)=>{m.url===e&&(l(f,g),c(f))};return ht(t,{onMessageReceived:(m,f)=>d(m,f,"received"),onMessageUpdated:(m,f)=>d(m,f,"updated")}),{checkForUserActionRequired:c}},Vc=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},Os=e=>{const{aiAgentInfo:t}=pt(),n=ks(e);if(Le(e))return null;const r=n[0];if(!r)return null;const o=r.userId===(t==null?void 0:t.userId),s=o?Vc(r.metaData):void 0;return{user:o?t:r,isBot:o,thinkingMessage:s}},Yc=(e,t,{enabled:n=!0,idleMs:r=1e3}={})=>{const o=u.useRef(null),s=u.useRef(t),a=u.useRef(t),l=u.useRef(!1);s.current=t,u.useEffect(()=>{if(o.current&&(clearTimeout(o.current),o.current=null),!n||!e){(l.current?a.current:s.current)(!1),l.current=!1,a.current=s.current;return}l.current=!0,a.current=s.current,a.current(!0),o.current=setTimeout(()=>{o.current=null,a.current(!1),l.current=!1,a.current=s.current},r)},[n,r,e]),u.useEffect(()=>()=>{o.current&&(clearTimeout(o.current),o.current=null),(l.current?a.current:s.current)(!1),l.current=!1,a.current=s.current},[])},Wc=(e=1e4)=>{const t=new Map;let n=e;return{shouldAnnounce:l=>{const c=Date.now(),d=t.get(l);return d!==void 0&&c-d<n?!1:(t.set(l,c),!0)},setInterval:l=>{n=l},reset:()=>{t.clear()}}},qc=(e,t,n=1e4,r=!0)=>{const o=u.useRef(null),s=u.useRef(null),a=u.useRef(!1);o.current||(o.current=Wc(n));const l=(e==null?void 0:e.nickname.trim())||null,c=(e==null?void 0:e.userId)??l;u.useEffect(()=>{var d;(d=o.current)==null||d.setInterval(n)},[n]),u.useEffect(()=>{var f;if(!r){a.current=!1,s.current=c;return}if(!c||!l){a.current=!1,s.current=null;return}const d=!a.current,m=s.current!==c;a.current=!0,s.current=c,!(!d&&!m)&&(f=o.current)!=null&&f.shouldAnnounce(c)&&t(l)},[c,l,r,t])};var Ye=(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))(Ye||{});const Kc=({csat:e,csatExpireAt:t,csatPayload:n,isSubmitInFlight:r})=>{const o=!!n&&n.visibility&&!!Ye[n.type],s=!r&&typeof e!="number"&&Cs(t),a=dn();return u.useEffect(()=>{if(!o||typeof e=="number"||t==null||s)return;const l=t-Date.now();if(l<=0&&r)return;const c=setTimeout(a,Math.max(0,l));return()=>clearTimeout(c)},[a,e,t,s,o,r]),{isRenderableCSAT:o,isExpiredNow:s}},jc=({csat:e,csatExpireAt:t,csatPayload:n,announceStatus:r,onSubmittedAnnounced:o,isSubmitInFlight:s=!1})=>{const{isRenderableCSAT:a,isExpiredNow:l}=Kc({csat:e,csatExpireAt:t,csatPayload:n,isSubmitInFlight:s}),c=(n==null?void 0:n.csat_submitted_label)??"",d=u.useRef(a&&typeof e=="number"),m=u.useRef(a&&l);return u.useEffect(()=>{a&&c&&(typeof e!="number"||d.current||(d.current=!0,r({event:"csatSubmitted",submittedLabel:c}),o==null||o()))},[r,e,a,o,c]),u.useEffect(()=>{a&&l&&(m.current||(m.current=!0,r({event:"csatExpired"})))},[r,l,a]),{isExpiredNow:l,isRenderableCSAT:a}},fr=({channel:e,userSession:t,aiAgentInfo:n})=>{if(!t||!n||!e)return{fallbackIcon:"delight",url:void 0,title:""};const r=bs(e,t.userId),o={ai(s){return{fallbackIcon:s,url:n.profileUrl,title:n.nickname}},human(s){return{fallbackIcon:s,url:r==null?void 0:r.profileUrl,title:(r==null?void 0:r.nickname)||n.nickname}},channel(s){return{fallbackIcon:s,url:e==null?void 0:e.coverUrl,title:(e==null?void 0:e.name)??""}}};return e.isAIAgent?et(e)?o.human("agent"):o.ai("delight"):e.isDesk?o.human("agent"):o.channel("user")},so=e=>u.useReducer((t,n)=>({...t,...n}),e),Xc=new Set(["free_text","single_choice"]),Zc=({csatPayload:e,type:t,initialCsat:n,initialCsatReason:r,initialIsResolved:o})=>{const[s,a]=so({csatType:t,csat:n,csatReason:r,isResolved:o}),[l,c]=so({followUpItem:!1}),d=u.useMemo(()=>{var b;const _=s.csat,v=typeof _=="number",y=(b=e.follow_up)==null?void 0:b.find(E=>v?E.scores.includes(_):E.always_visible??!1);if(Xc.has(y==null?void 0:y.response_type))return y},[s.csat,e.follow_up]),m=(()=>{var _;if(typeof n=="number")return"submitted";if((t===Ye.AI_AGENT_CSAT_5||t===Ye.HELPDESK_CSAT_5)&&typeof s.csat=="number")return"submittable";if(t===Ye.AI_AGENT_CSAT_5_WITH_CRE){const v=typeof s.csat=="number",y=!((_=e.cre)!=null&&_.required)||typeof s.isResolved=="boolean";if(v&&y)return"submittable"}return"unsubmittable"})(),f=u.useCallback(()=>typeof s.csat>"u"?!1:d!=null&&d.required&&!s.csatReason?(c({followUpItem:!0}),!1):!0,[s,d,c]);return u.useEffect(()=>{r||(a({csatReason:""}),c({followUpItem:!1}))},[r,d,a,c]),{params:s,setParams:a,error:l,setError:c,followUpItem:d,state:m,validateParams:f,itemProps:{csatPayload:e,state:m,submitted:m==="submitted"}}},In=5,Jc=250,Qc=50,io=e=>Math.max(0,e-Qc),eu=e=>e<1e3?{speed:In*.5,chunkSize:2}:e<2e3?{speed:In*.8,chunkSize:2}:{speed:In*.6,chunkSize:3},jt=(e,t)=>{let n=0;for(let r=t-1;r>=0&&e[r]==="\\";r--)n++;return n%2===1},ao=(e,t,n,r)=>{let o=1,s=t;for(;s<e.length&&o>0;){if(jt(e,s)){s++;continue}e[s]===n?o++:e[s]===r&&o--,s++}return o>0?-1:s},tu=(e,{hideImages:t,hideLinks:n})=>{let r="",o=0,s=0;for(;o<e.length;){if(e[o]==="`"&&!jt(e,o)){let f=1;for(;e[o+f]==="`";)f++;s===0?s=f:f===s&&(s=0),r+=e.slice(o,o+f),o+=f;continue}const a=e[o]==="!"&&e[o+1]==="["&&!jt(e,o),l=e[o]==="["&&!jt(e,o);if(s>0||!a&&!l){r+=e[o],o++;continue}if(a?!t:!n){const f=a?"![":"[";r+=f,o+=f.length;continue}const c=o,d=ao(e,o+(a?2:1),"[","]");if(d===-1)return r;if(o=d,e[o]!=="("){r+=e.slice(c,o);continue}const m=ao(e,o+1,"(",")");if(m===-1)return r;o=m,r+=e.slice(c,o)}return r},nu=e=>{const{text:t,enabled:n=!1,markdownImageRenderMode:r="default",markdownLinkRenderMode:o="default",onAnimationStart:s,onAnimationProgress:a,onAnimationComplete:l}=e,[c,d]=u.useState(()=>io(t.length)),m=u.useRef(null),f=u.useRef({startTime:0,lastUpdate:0,lastProgressCall:0}).current,g=u.useRef({onStart:s,onProgress:a,onComplete:l}).current,_=u.useRef({startCalled:!1,completeCalled:!1}).current,v=u.useRef({initialEnabled:n,textLength:t.length,enabled:n}).current,y=n,b=c<t.length,E=v.initialEnabled&&(y||b);return u.useLayoutEffect(()=>{g.onStart=s,g.onProgress=a,g.onComplete=l,v.textLength=t.length,v.enabled=n}),u.useLayoutEffect(()=>{var S;v.initialEnabled&&(_.startCalled||(_.startCalled=!0,(S=g.onStart)==null||S.call(g)),d(x=>t.length<x?t.length:x))},[t]),u.useEffect(()=>{if(!v.initialEnabled)return;let S=io(t.length);f.lastUpdate=0,f.startTime=0,f.lastProgressCall=0;const x=w=>{var V;f.lastUpdate===0&&(f.lastUpdate=w,f.startTime=w,f.lastProgressCall=w);const k=v.textLength,I=w-f.lastUpdate,M=w-f.startTime,{speed:O,chunkSize:F}=eu(M),Y=O*F;I>=Y&&S<k&&(S=Math.min(S+F,k),d(S),f.lastUpdate=w),w-f.lastProgressCall>=Jc&&(f.lastProgressCall=w,(V=g.onProgress)==null||V.call(g)),(S<k||v.enabled)&&(m.current=requestAnimationFrame(x))};return m.current=requestAnimationFrame(x),()=>{var w;m.current&&cancelAnimationFrame(m.current),_.startCalled&&!_.completeCalled&&(_.completeCalled=!0,(w=g.onComplete)==null||w.call(g))}},[]),u.useEffect(()=>{var k;const S=v.initialEnabled&&_.startCalled,x=!n,w=c>=t.length&&t.length>0;S&&x&&w&&!_.completeCalled&&(_.completeCalled=!0,(k=g.onComplete)==null||k.call(g))},[n,c,t.length]),{streamText:u.useMemo(()=>{const S=v.initialEnabled?t.slice(0,c):t,x=E&&r==="complete-only",w=E&&o==="complete-only";return!x&&!w?S:tu(S,{hideImages:x,hideLinks:w})},[t,c,r,o,E]),isAnimating:E}},lo={visible:!1,remainingTime:0,showDescription:!1,targetTimeMs:null},ru=e=>({visible:!0,remainingTime:e,showDescription:!0,targetTimeMs:Date.now()+e*1e3}),ou=(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}},su=()=>{const{chatSDK:e}=ke(),[t,n]=u.useState(lo),r=()=>n(lo);return Lt(e,{onConnectionDelayed:o=>{o>0?n(ru(o)):r()},onReconnectSucceeded:r,onConnected:r}),u.useEffect(()=>{if(!t.visible||!t.showDescription||t.targetTimeMs==null)return;const o=setTimeout(()=>{n(s=>ou(s))},1e3);return()=>clearTimeout(o)},[t.visible,t.showDescription,t.targetTimeMs,t.remainingTime]),{visible:t.visible,remainingTime:t.remainingTime,showDescription:t.showDescription}},iu=e=>{const t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`},au=(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)}},lu=(e,{enabled:t=!0,opened:n=!1,filter:r}={})=>{var c,d,m;const[o,s]=u.useState(!1),a=u.useRef(0),l=()=>{if(!t)return;const f=++a.current;e.aiAgent.getUnreadMessageCount(r).then(g=>{f===a.current&&s(g.total>0)}).catch(()=>{})};return u.useEffect(()=>{if(!t){s(!1),a.current++;return}e.connectionState===he.ConnectionState.OPEN&&l()},[t,e,r==null?void 0:r.aiAgentChannelFilter,(c=r==null?void 0:r.aiAgentConversationStatusFilter)==null?void 0:c.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]),u.useEffect(()=>{n&&(s(!1),a.current++)},[n]),Lt(e,{onConnected:l,onReconnectSucceeded:l}),o},gr=e=>e.replace(/\s+/g," ").trim(),cu="Code block",Ns=e=>`A11Y_INLINE_CODE_${e}`,Ds=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}},$s=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}},uu=e=>{const{blockquotePrefix:t,content:n}=Ds(e),{content:r}=$s(n),o=r.match(/^[ \t]{0,3}([`~]{3,})(.*)$/);if(!o)return;const s=o[1],a=o[2],l=s[0];if(!(l!=="`"&&l!=="~"||!s.split("").every(c=>c===l))&&!(l==="`"&&a.includes("`")))return{char:l,blockquotePrefix:t,length:s.length}},du=(e,t)=>{const{blockquotePrefix:n,content:r}=Ds(e);if(n!==t.blockquotePrefix)return!1;const{content:o,hasListPrefix:s}=$s(r);if(s)return!1;const a=o.match(/^[ \t]{0,3}([`~]{3,})[ \t]*$/);if(!a)return!1;const l=a[1];return l[0]===t.char&&l.length>=t.length&&l.split("").every(c=>c===t.char)},mu=(e,t,n)=>{let r=n;for(;r<e.length;){const o=e[r];if(o==="\\"&&r+1<e.length){r+=2;continue}if(o===t)return r;r+=1}return-1},fu=(e,t)=>{let n=1,r=t;for(;r<e.length;){const o=e[r];if(o==="\\"&&r+1<e.length){r+=2;continue}if(o==="["){n+=1,r+=1;continue}if(o==="]"&&(n-=1,n===0))return r;r+=1}return-1},gu=(e,t)=>{let n=t,r=1,o,s=!1,a=!1;for(;n<e.length&&r>0;){const l=e[n];if(l==="\\"&&n+1<e.length){n+=2;continue}if(o){l===o&&(o=void 0),n+=1;continue}if(r===1&&s&&/\s/.test(l)){a=!0,n+=1;continue}if(r===1&&a&&(l==='"'||l==="'")){o=l,n+=1;continue}if(l==="("){r+=1,s=!0,n+=1;continue}if(l===")"){r-=1,n+=1;continue}/\s/.test(l)||(s=!0),n+=1}return r===0?n:-1},hu=e=>{let t=0,n="";for(;t<e.length;){const r=mu(e,"[",t);if(r===-1){n+=e.slice(t);break}const o=fu(e,r+1);if(o===-1){n+=e.slice(t);break}if(r>0&&e[r-1]==="!"&&nn(e,r-1)){n+=e.slice(t,o+1),t=o+1;continue}if(e[o+1]!=="("){n+=e.slice(t,o+1),t=o+1;continue}const s=r>0&&e[r-1]==="!"&&!nn(e,r-1)?r-1:r;n+=e.slice(t,s);const a=e.slice(r+1,o),l=gu(e,o+2);if(l===-1){n+=e.slice(s);break}n+=a,t=l}return n},Ps=(e,t,n)=>{if(!/^\d+$/.test(t))return!1;const r=e.slice(-1);return/\d/.test(r)&&/\d/.test(n)},pu=e=>e.replace(/(^|[^*\\])\*\*([^\s*](?:[\s\S]*?[^\s*])?)\*\*(?!\*)/g,(t,n,r,o,s)=>{const a=s[o+t.length]??"";return Ps(n,r,a)?t:`${n}${r}`}),_u=e=>e.replace(/(^|[^_\\])__([^\s_](?:[\s\S]*?[^\s_])?)__(?!_)/g,"$1$2"),Eu=e=>e.replace(/(^|[^~\\])~~([^\s~](?:[\s\S]*?[^\s~])?)~~(?!~)/g,"$1$2"),bu=e=>{let t=e;return t=t.replace(/(^|[^*\\])\*([^\s*](?:[\s\S]*?[^\s*])?)\*(?!\*)/g,(n,r,o,s,a)=>{const l=a[s+n.length]??"";return Ps(r,o,l)?n:`${r}${o}`}),t=t.replace(/(^|[\s([{"'])_([^_\s](?:[\s\S]*?[^_\s])?)_(?=$|[\s)\]}"'.,!?:;])/g,"$1$2"),t},Cu=e=>e.replace(/\\([\\`*_[\]()#+.!~|-])/g,"$1"),vu=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},co=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))},uo=e=>{const t=[];let n="",r=!1;for(const s of e.trim()){if(r){n+=s==="|"?"|":`\\${s}`,r=!1;continue}if(s==="\\"){r=!0;continue}if(s==="|"){const a=n.trim();a&&t.push(a),n="";continue}n+=s}r&&(n+="\\");const o=n.trim();return o&&t.push(o),t},yu=e=>{const t=e.split(`
|
|
2
|
-
`),n=[];let r=0;for(;r<t.length;){const o=t[r],s=t[r+1],a=
|
|
3
|
-
`)},
|
|
4
|
-
`),r=[];let o=0;for(;o<n.length;){const s=n[o],a=
|
|
5
|
-
`)},
|
|
6
|
-
`;){if(e[l]==="`"&&!
|
|
7
|
-
`);if(!n)return;const r=[];let o=n;o=Au(o,t),o=vu(o);const s=xu(o);o=s.text,r.push(...s.inlineCodes),o=hu(o),o=pu(o),o=_u(o),o=Eu(o),o=bu(o),o=yu(o),o=Su(o),o=Cu(o);for(let l=0;l<r.length;l++)o=o.replaceAll(Ns(l),r[l]);return gr(o)||void 0},Tu=(e,t)=>{var o;const n=((o=e.name)==null?void 0:o.trim())||"",r=e.mimeType??"";return He(r)?t.image:cn(r)?t.video:ds({name:n,mimeType:r})?t.pdf(n):t.document(n)},rn=e=>(e==null?void 0:e.trim())||"",Iu=e=>(e?gr(e):void 0)||void 0,Us=e=>({text:rn(e),format:"plain"}),wu=e=>({text:rn(e),format:"markdown"}),wn=({markdownText:e,plainText:t,comparisonText:n})=>{const r=rn(e);return r&&r!==rn(n)?wu(r):Us(t)},St=({sender:e,message:t,messageFormat:n="plain",time:r,codeBlockPlaceholder:o})=>{const s=[],a=n==="markdown"?Fs(t,{codeBlockPlaceholder:o}):Iu(t);if(r&&s.push(r),e&&s.push(e),a&&s.push(a),s.length!==0)return s.join(", ")},Bs=(e,t)=>Fs(e==null?void 0:e.trim(),t!==void 0?{codeBlockPlaceholder:t}:void 0),Mu=(...e)=>gr(e.filter(Boolean).join(", "))||void 0,mo=(e,t,n,r)=>{if(!t||t===n)return e;const o=Bs(t,r);return o?Mu(e,o):e},ku=(e,t)=>{var r,o,s,a;const n=(r=e.message)==null?void 0:r.trim();if(e.isFileMessage()){const l=((o=e.name)==null?void 0:o.trim())||"",c=Tu({name:l,mimeType:e.type},t);return mo(c,n,l,t.codeBlockPlaceholder)}if(e.isMultipleFilesMessage()){const l=e.fileInfoList??[],c=l.length;if(c===0)return;const d=((a=(s=l[0])==null?void 0:s.fileName)==null?void 0:a.trim())||"",f=l.every(g=>{var _;return(_=g.mimeType)==null?void 0:_.startsWith("image")})?t.receivedFilesImageCount(c):t.multipleFilesCount(c);return mo(f,n,d,t.codeBlockPlaceholder)}return Bs(n,t.codeBlockPlaceholder)},Ru=(e,t={})=>{const{throttleMs:n=1e3,isSuppressed:r,maxOrderedQueueSize:o=10}=t,s=Math.max(1,o);let a=null;const l=[];let c=null,d=null,m=null,f=!1,g=0;const _=(M,O,F)=>({text:M,ignoreSuppression:O,queueOrder:g++,dedupeKey:F}),v=()=>{const M=l[0]??null,O=a;return M&&O?O.queueOrder<M.queueOrder?(a=null,O):l.shift()??null:M?l.shift()??null:O!==null?(a=null,O):null},y=()=>{for(;;){const M=v();if(!M)return null;if(!(!M.ignoreSuppression&&(r!=null&&r())))return M}},b=M=>{c=M.text,d=M.dedupeKey??null,f=!0,e(M.text),m=setTimeout(()=>{m=null,f=!1;const O=y();O&&b(O)},n)},E=M=>{c=M.text,d=M.dedupeKey??null,e(M.text)},C=(M,O,F,Y)=>O!=null&&Y!=null?O===Y:O==null&&Y==null?M!=null&&M===F:!1,S=(M,O,F)=>{if(!M||!O&&(r!=null&&r()))return;const Y=F==null?void 0:F.dedupeKey;if(!(f&&C(M,Y,c,d)))if(f){if(((F==null?void 0:F.mode)??"latestOnly")==="ordered"){const V=l[l.length-1];if(V&&C(M,Y,V.text,V.dedupeKey))return;l.push(_(M,O,Y)),l.length>s&&l.shift();return}a=_(M,O,Y)}else a=null,b(_(M,O,Y))};return{announce:(M,O)=>{S(M,!1,O)},announceIgnoringSuppression:(M,O)=>{S(M,!0,O)},flush:()=>{const M=[];let O=v();for(;O!==null;)M.push(O),O=v();if(m!==null&&(clearTimeout(m),m=null),f=!1,M.length!==0)for(const F of M)E(F)},destroy:()=>{m!==null&&(clearTimeout(m),m=null),a=null,l.length=0,c=null,d=null,f=!1}}},Lu=e=>{switch(e){case"newMessage":case"conversationClosed":case"csatDisplayed":case"csatSubmitted":case"csatExpired":return"ordered";default:return"latestOnly"}},Ou=(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(". "),Nu=(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}},Du=(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}},$u=(e,t)=>!t||!Qe(e)||e.sender.userId!==t?null:e.reqId||(e.messageId>0?String(e.messageId):null),Pu=(e,t)=>Ie.isAdmin(e)?Ie.isCSAT(e):"sender"in e?e.sender.userId!==t:!1,Fu=e=>"messageId"in e&&e.messageId>0?String(e.messageId):"reqId"in e&&typeof e.reqId=="string"&&e.reqId.length>0?e.reqId:null,Uu=e=>e===he.CollectionEventSource.EVENT_MESSAGE_RECEIVED||e===he.CollectionEventSource.EVENT_MESSAGE_UPDATED,Bu=({isOpened:e,opensConversationList:t})=>e?t?"closeConversationList":"closeConversation":t?"openConversationList":"openConversation",Hu=(e,t)=>{switch(e){case"closeConversationList":return t.closeConversationList;case"closeConversation":return t.closeConversation;case"openConversationList":return t.openConversationList;case"openConversation":return t.openConversation}},Gu=(e,t)=>{switch(e){case"closeConversation":return t.hintCloseConversation;case"openConversationList":return t.hintOpenConversationList;case"openConversation":return t.hintOpenConversation;default:return}},zu=({intent:e,strings:t})=>({label:Hu(e,t),hint:Gu(e,t)}),Vu="1.30.0",Ne="sb-agent",Ce={ENTRY:`${Ne}-entry`,MODAL_ROOT:`${Ne}-modal-root`,WINDOW:`${Ne}-window`,LAUNCHER:`${Ne}-launcher`,WINDOW_TITLE:`${Ne}-window-title`},Hs="data-sb-initial-focus",Gs="true",Yu=`[${Hs}="${Gs}"]`,zs={[Hs]:Gs},hr="data-sb-focus-trap-sentinel",Wu="true",Vs="data-sb-initial-focus-header",Ys="true",qu=`[${Vs}="${Ys}"]`,Ws={[Vs]:Ys},qs="data-sb-message-input",Ks="true",Ku=`textarea[${qs}="${Ks}"]:not(:disabled)`,ju={[qs]:Ks},js=1e3,Gt=2147483647,it={MODAL:Gt-1,TOOLTIP:Gt-2,WINDOW:Gt-3,LAUNCHER:Gt-4},Xs=36,Xu=100,Zu=Vu,pr="noopener noreferrer nofollow";function Ju(){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 zt={};function Qu(){return{get:e=>{try{return localStorage.getItem(e)}catch{return zt[e]??null}},set:(e,t)=>{try{localStorage.setItem(e,t)}catch{zt[e]=t}},delete:e=>{try{localStorage.removeItem(e)}catch{delete zt[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(zt).filter(t=>t.startsWith(e))}}}}const ed={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}`}},Yn={language:"en",strings:ed,dateLocale:fa.enUS},Zs=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}),Js=e=>{var t;return((t=e.split("-"))==null?void 0:t[0])??Ot},Ot="en",Qs=new Set([Ot,"ko","es","pt","fr","hi","it","de","tr","ja"]),td='@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:nd,useContext:_r}=Ee("AgentUIElementResolver"),rd=({entryElement:e,modalRootElement:t,rootElement:n,children:r})=>{const o=u.useMemo(()=>{const s=n??document.body,a=e??s,l=t??s,c=d=>d===Ce.MODAL_ROOT?l:a.querySelector(`#${d}`);return{resolveElement:c,resolvePortalContainer:d=>c(d)??l}},[e,t,n]);return i.createElement(nd,{value:o},r)};function st(e,t){const n=e.getRootNode({composed:t});return n instanceof ShadowRoot||n instanceof Document?n:document}const fo=()=>{const e=[];let t=0;return{register:n=>{const r=++t;return e.push({id:r,handler:n}),()=>{const o=e.findIndex(s=>s.id===r);o>=0&&e.splice(o,1)}},dismissTopmost:()=>{const n=e[e.length-1];return n?(n.handler(),!0):!1}}},{Provider:od,useContext:ei}=Ee("EscapeDismissStack"),go=e=>{e.stopPropagation(),e.stopImmediatePropagation()},sd=({rootElement:e=document.body,boundaryElement:t,children:n})=>{const r=u.useRef(null),o=u.useRef(null);r.current||(r.current=fo()),o.current||(o.current=fo());const s=r.current,a=o.current;u.useLayoutEffect(()=>{const c=t??st(e),d=m=>{if(m.key==="Escape"){if(s.dismissTopmost()){go(m);return}a.dismissTopmost()&&go(m)}};return c.addEventListener("keydown",d),()=>c.removeEventListener("keydown",d)},[t,e,a,s]);const l=u.useMemo(()=>({register:s.register,dismissTopmost:s.dismissTopmost,registerShellDismissHandler:a.register}),[a,s]);return i.createElement(od,{value:l},n)},ti=(e,t,n)=>{const r=u.useRef(t);u.useLayoutEffect(()=>{r.current=t},[t]),u.useLayoutEffect(()=>{if(e)return n(()=>r.current())},[e,n])},id=(e,t)=>{const{register:n}=ei();ti(e,t,n)},ad=(e,t)=>{const{registerShellDismissHandler:n}=ei();ti(e,t,n)},ld=(e,t,n)=>{const r=e[t];return r?typeof r=="function"?r():Promise.resolve(r):new Promise((o,s)=>{(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(s.bind(null,new Error("Unknown variable dynamic import: "+t+(t.split("/").length!==n?". Note that variables only represent file names one level deep.":""))))})},ho=Zs(Yn.strings),cd={...ho,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:ho.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"},on={language:Yn.language,dateLocale:Yn.dateLocale,stringSet:cd},ud=Object.freeze(Object.defineProperty({__proto__:null,default:on},Symbol.toStringTag,{value:"Module"})),Wn=new Map([[Ot,on]]);async function dd(e){const t=Wn.get(e);if(t)return t;try{if(Qs.has(e)){const{default:n}=await ld(Object.assign({"./languages/de.ts":()=>Promise.resolve().then(()=>require("./cjs/I-l-5Zo-.cjs")),"./languages/en.ts":()=>Promise.resolve().then(()=>ud),"./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 Wn.set(e,n),n}return on}catch{return on}}const{Provider:md,useContext:se}=Ee("Localization"),fd=({language:e=navigator.language,languageCode:t,logger:n,stringSet:r,children:o})=>{const[s,a]=u.useState(Wn.get(Ot));return u.useEffect(()=>{const l=t??Js(e);s.language!==l&&(n==null||n.debug("localization.useEffect: update language",{from:s.language,to:l}),dd(l).then(a))},[e,t,n]),i.createElement(md,{value:{language:s.language,defaultStringSet:s.stringSet,stringSet:{...s.stringSet,...r},dateLocale:s.dateLocale,format:(l,c,d)=>Xe.format(l,c,{locale:s.dateLocale,...d})}},o)},sn="data-sb-agent-theme",po=e=>(t,...n)=>{let r="";return t.forEach((o,s)=>{r+=o+(n[s]??"")}),`[${sn}='${e}'] & { ${r} }`},J={light:po("light"),dark:po("dark")},gd=D.css(({theme:e})=>{const{palette:t}=e;return`
|
|
1
|
+
"use strict";var ha=Object.defineProperty;var pa=(e,t,n)=>t in e?ha(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var S=(e,t,n)=>pa(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ue=require("@sendbird/chat"),u=require("react"),D=require("styled-components"),Je=require("date-fns"),_a=require("date-fns/locale/en-US"),He=require("@sendbird/chat/message"),Ea=require("react-dom"),Ee=require("@sendbird/chat/aiAgent"),Ye=require("@sendbird/chat/groupChannel"),ba=require("date-fns/isSameDay"),Ca=require("dompurify"),rr=e=>e&&e.__esModule?e:{default:e};function va(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 ya=rr(ue),i=va(u),p=rr(D),ds=rr(Ca),ct="sb-agent",ms="KEY_IMG_ASPECT_RATIO",Hn="*/*",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 tn=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(tn||{}),It=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(It||{});const fs=e=>{var t;return!!((t=e==null?void 0:e.extendedMessagePayload)!=null&&t.steward)},Sa=e=>e===It.COMPLETED||e===It.CANCELED?e:It.IN_PROGRESS,Tn=e=>tt(e)&&!fs(e),tt=e=>!!e&&"sender"in e,Aa=e=>tt(e)?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId),xa=(e,t,n,r=!0)=>{if(!r||!Tn(e))return"single";const o=()=>{if(!Tn(t))return!1;const c=t.sender.userId===e.sender.userId,d=Je.isSameMinute(t.createdAt,e.createdAt);return c&&d},s=()=>{if(!Tn(n))return!1;const c=n.sender.userId===e.sender.userId,d=Je.isSameMinute(n.createdAt,e.createdAt);return c&&d},a=o(),l=s();return a&&l?"middle":a?"bottom":l?"top":"single"},gt=(e,t)=>(()=>{var r;return tt(e)?e.sender.userId:((r=e==null?void 0:e.sender)==null?void 0:r.userId)??void 0})()===t,we={isAdmin:e=>e.isAdminMessage(),isCSAT:e=>{var t;return e.isAdminMessage()&&!!((t=e.extendedMessagePayload)!=null&&t.csat)},isSteward:e=>fs(e),isIncoming:(e,t)=>tt(e)&&e.sender.userId!==t,isOutgoing:(e,t)=>tt(e)&&(e.sender.userId===t||e.sendingStatus===He.SendingStatus.PENDING)},ze=e=>e.startsWith("image/"),mn=e=>e.startsWith("video/"),gs=({name:e="",mimeType:t=""})=>t==="application/pdf"||/\.pdf$/i.test(e.trim()),or=(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"},hs=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},fn=e=>{switch(e){case"top":case"middle":return ee.GAP_GROUPED;default:return ee.GAP_UNGROUPED}},Ta=(e,t)=>{const n=/```(\w+)?\n([\s\S]*?)```/g,r=[];let o=0;return e.replace(n,(s,...a)=>{const[l,c,d]=a;return o<d&&r.push({type:"text",value:e.slice(o,d).trim()}),r.push({type:"code",value:c.trim(),language:l?l.trim():"plaintext"}),o=d+s.length,s}),o<e.length&&r.push({type:"text",value:e.slice(o).trim()}),t?r.map(s=>s.type!=="text"?s:{...s,value:t(s.value)}):r},Ia=e=>e.replace(/\[([^\]]+)\](?!\()/g,"\\[$1\\]"),wa=e=>e.replace(/([a-zA-Z0-9])_(?=[a-zA-Z0-9])/g,"$1\\_"),Ma=e=>e.replace(/~~/g,"\\~\\~"),ka=e=>{let t=e;return t=Ia(t),t=wa(t),t=Ma(t),t},Ra=typeof navigator<"u"&&navigator.product==="ReactNative",Gr=(e,t)=>{const n=r=>!t||t.length===0?!0:tt(r)&&t.includes(r.sendingStatus);return Ra?e.find(n):e.findLast(n)};function ce(){}function La(){const e=typeof navigator<"u"?navigator.userAgent:"",t=/iPad|iPhone|iPod/.test(e),n=/Android/.test(e);return t||n}function Oa(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 Gn=e=>{try{return JSON.parse(e===""?"{}":e)}catch{return{}}},We={isStreaming(e){const t=Gn(e.data);return typeof t=="object"&&!!t.stream},isWelcomeMessage(e,t){var n;if(((n=e.extendedMessagePayload)==null?void 0:n.bot_message_type)==="welcome")return!0;if(gt(e,t)){const r=Gn(e.data);return!(r!=null&&r.respond_mesg_id)&&!(r!=null&&r.stream)}return!1},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)}},In=`@${ct}`,Na=({appId:e,aiAgentId:t,storage:n})=>{const r={templateBase:`${In}-template`,template:o=>`${r.templateBase}/templates/${o}`,templateToken:()=>`${r.templateBase}/tokens`,messengerSession:o=>{const s=Oa(`${e}/${t}/${o}`);return`${In}-udata/${s}`},anonUserSession:()=>`${In}-session/${e}/${t}`};return{template:{set:(o,s)=>n.set(r.template(o),s),get:o=>n.get(r.template(o)),setCachedToken:o=>n.set(r.templateToken(),o),getCachedToken:()=>n.get(r.templateToken()),clear:()=>{n.getKeys(r.templateBase).forEach(n.delete)}},messenger:{getSettings:o=>{try{const s=n.get(r.messengerSession(o));return s?JSON.parse(s):null}catch{return null}},setSettings:(o,s)=>{try{delete s.auto_created_user;const a=JSON.stringify(s);n.set(r.messengerSession(o),a)}catch{return}},getAnonUser:()=>{try{const o=n.get(r.anonUserSession());return o?JSON.parse(o):null}catch{return null}},setAnonUser:o=>{try{const s=JSON.stringify(o);n.set(r.anonUserSession(),s)}catch{return}},clear:o=>{try{o&&n.delete(r.messengerSession(o)),n.delete(r.anonUserSession())}catch{return}}}}},ps=(e,t,n={})=>{let r=null,o=null,s=null;const{leading:a=!0,trailing:l=!0}=n,c=(...d)=>{const m=Date.now();if(s===null||m-s>=t)a?(e(...d),s=m):(o=d,s=m);else if(o=d,l&&!r){const f=t-(m-s);r=setTimeout(()=>{o&&l&&(e(...o),s=Date.now()),r=null,o=null},f)}};return c.cancel=()=>{r&&(clearTimeout(r),r=null),o=null,s=null},c},Da=()=>{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 $a{constructor(t){S(this,"_params");this._params={aiAgentChannelFilter:(t==null?void 0:t.aiAgentChannelFilter)??Ee.AIAgentChannelFilter.INCLUDE,aiAgentConversationStatusFilter:(t==null?void 0:t.aiAgentConversationStatusFilter)??[Ee.ConversationStatus.OPEN,Ee.ConversationStatus.CLOSED],aiAgentIds:(t==null?void 0:t.aiAgentIds)??[],deskChannelFilter:(t==null?void 0:t.deskChannelFilter)??Ee.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:o,aiAgentConversationStatusFilter:s,aiAgentIds:a,deskChannelFilter:l}=this._params;return r!=null&&r.includes(t.url)?!0:t.isAIAgent?!(!t.conversation||o===Ee.AIAgentChannelFilter.EXCLUDE||a&&a.length>0&&!a.includes(t.conversation.aiAgentId)||s&&s.length>0&&!s.some(d=>{var m;return((m=t.conversation)==null?void 0:m.status)===d})):t.isDesk?l!==Ee.DeskChannelFilter.EXCLUDE:!1}}class _s extends Ye.BaseChannelCollection{constructor(n,r){const o=new $a(r.filter),s=n,a=s.aiAgent._manager,l=r.limit??20,c=Ye.GroupChannelListOrder.LATEST_LAST_MESSAGE,d={getRemoteChannels:(m,f,g,E)=>a.getMyGroupChannels(m,f.params,E),changeLogSync:m=>{const{aiAgentChannelFilter:f,aiAgentIds:g,deskChannelFilter:E,pinnedChannelUrls:y,copilotConversationOnly:v,copilotSupportChannelUrl:b}=o.params,_={aiAgentChannelFilter:f,aiAgentIds:g,deskChannelFilter:E,pinnedChannelUrls:y,copilotConversationOnly:v,copilotSupportChannelUrl:b};return a.getMyGroupChannelChangeLogs(m,_,Ye.GroupChannelEventSource.SYNC_CHANNEL_CHANGELOGS)}};super(s.aiAgent._iid,{filter:o,order:c,limit:l,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-${Da()}`,this._throttledOnChannelChanged=ps(()=>{var E;const m=[...this._pendingChannels];this._pendingChannels=[];const f=new Map;for(const{channel:y,context:v}of m)f.delete(y.url),f.set(y.url,{channel:y,context:v});const g=new Map;for(const{channel:y,context:v}of f.values())g.has(v)||g.set(v,new Map),g.get(v).set(y.url,y);for(const[y,v]of g){const b=Array.from(v.values()),_=(E=this._sdk.currentUser)==null?void 0:E.userId,C=b.filter(A=>this.filter.match(A,_)),x=b.filter(A=>!this.filter.match(A,_)).map(A=>A.url);C.length>0&&this._base._addChannelsToView(C,y,!1),x.length>0&&this._removeChannels(x,y)}},250,{trailing:!0,leading:!0}),this._base._subscribeChannelEvent(this._key,{onUpdate:(m,f)=>{for(const g of m)this._pendingChannels.push({channel:g,context:f});this._throttledOnChannelChanged()},onRemove:(m,f)=>{this._removeChannels(m,f)}})}get _base(){return this}_removeChannels(n,r){const o=new Set(n);this._pendingChannels=this._pendingChannels.filter(({channel:s})=>!o.has(s.url)),this._base._removeChannelsFromView(n,r)}get channels(){var l;const n=((l=this._params.filter)==null?void 0:l.pinnedChannelUrls)??[],r=[],o=new Map(super.channels.map(c=>[c.url,c])),s=new Set;for(const c of n){const d=o.get(c);d&&!s.has(c)&&(r.push(d),s.add(c))}const a=super.channels.filter(c=>!s.has(c.url));return[...r,...a]}setConversationListCollectionHandler(n){super.setGroupChannelCollectionHandler(n)}dispose(){super.dispose(),this._throttledOnChannelChanged.cancel(),this._base._unsubscribeChannelEvent(this._key)}}class Es{constructor(t){S(this,"subscribers",{});this.logger=t}async send(t){const n=Pa(),r=this.subscribers[t.type];if(r){this.logger.debug(`messenger.dispatcher: dispatching command: ${t.type}`,t.payload);const o=r.map(s=>s(t.payload));await Promise.all(o).catch(s=>{this.logger.error(`messenger.dispatcher: error in callback for command: ${t.type}`,s)})}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(o=>o!==n))}}const Pa=()=>{let e=ce,t=ce;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}};var Be=(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))(Be||{});class Lt{constructor(t={}){S(this,"payload");this.payload=t}toJSON(){return JSON.stringify({type:this.type,payload:this.payload})}}const Qe={CloseConversation:e=>new Fa(e),MessengerSettingsUpdated:e=>new Ua(e),ActiveChannelUpdated:e=>new Ba(e),AnonymousSessionTokenExpired:()=>new Ha,AuthTokenRefreshed:()=>new Ga};class Fa extends Lt{constructor(){super(...arguments);S(this,"type","conv.close")}}class Ua extends Lt{constructor(){super(...arguments);S(this,"type","messenger.settings.updated")}}class Ba extends Lt{constructor(){super(...arguments);S(this,"type","active.channel.updated")}}class Ha extends Lt{constructor(){super(...arguments);S(this,"type","anon.token.expired")}}class Ga extends Lt{constructor(){super(...arguments);S(this,"type","auth.token.refreshed")}}var sr=(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))(sr||{});class bs{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 Cs{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 zn{constructor(){S(this,"userId");S(this,"authToken");S(this,"sessionHandler")}}const za=e=>({onSessionTokenRequired:t=>{t(null),e.send(Qe.AnonymousSessionTokenExpired())}}),Va="ai_agent:stats",Ya="conversation_initial_render",Wa=800220;var Ce=(e=>(e.AUTH="auth_duration",e.GET_CHANNEL="get_channel_duration",e.GET_MESSAGES="get_messages_duration",e.TOTAL_DURATION="total_duration",e.TOTAL_DURATION_FROM_CACHE="total_duration_from_cache",e))(Ce||{});class qa{constructor(){S(this,"timers",new Map);S(this,"committed",!1);S(this,"commitCallback",null);S(this,"conversationId",null);S(this,"channelUrl",null);S(this,"errorCode",null);S(this,"errorDescription",null);S(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??Wa,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:Date.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:Date.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(Va,t)):!1}}class Ka extends qa{constructor(){super(...arguments);S(this,"presentMethod","direct_present")}setPresentMethod(n){return this.presentMethod=n,this}getMetricKey(){return Ya}buildPayload(){const n=this.getDuration(Ce.AUTH),r=this.getDuration(Ce.GET_CHANNEL),o=this.getDuration(Ce.GET_MESSAGES),s=this.getDuration(Ce.TOTAL_DURATION_FROM_CACHE),a=this.getDuration(Ce.TOTAL_DURATION),l={...this.extraData,present_method:this.presentMethod,...n!==null&&{auth_duration:n},...r!==null&&{get_channel_duration:r},...o!==null&&{get_messages_duration:o},...s!==null&&{total_duration_from_cache:s}},c={key:this.getMetricKey(),value:a!==null?String(a):"0"};return this.conversationId!==null&&(c.conversation_id=this.conversationId),this.errorCode!==null&&(c.error_code=this.errorCode),this.errorDescription!==null&&(c.error_description=this.errorDescription),Object.keys(l).length>0&&(c.extra=l),c}}class ja{constructor(t){S(this,"commitCallback");S(this,"presentMethod","direct_present");S(this,"stats",null);this.commitCallback=t}getOrCreateStats(){return(!this.stats||this.stats.isCommitted())&&(this.stats=new Ka().setCommitCallback(this.commitCallback).setPresentMethod(this.presentMethod)),this.stats}onAuthStart(){this.getOrCreateStats().startTimer(Ce.TOTAL_DURATION).startTimer(Ce.TOTAL_DURATION_FROM_CACHE).startTimer(Ce.AUTH)}onAuthComplete(){var t;(t=this.stats)==null||t.stopTimer(Ce.AUTH)}onAuthError(t){this.stats&&!this.stats.isCommitted()&&this.stats.stopTimer(Ce.AUTH).setError(t instanceof ue.SendbirdError?t.code:void 0,t.message).stopTimer(Ce.TOTAL_DURATION).commit()}onGetChannelStart(){var t;(t=this.stats)==null||t.startTimer(Ce.GET_CHANNEL)}onGetChannelComplete(t){this.stats&&(this.stats.stopTimer(Ce.GET_CHANNEL),t!==void 0&&this.stats.setConversationId(t),this.stats.startTimer(Ce.GET_MESSAGES))}onGetChannelError(t){this.stats&&!this.stats.isCommitted()&&this.stats.stopTimer(Ce.GET_CHANNEL).setError(t instanceof ue.SendbirdError?t.code:void 0,t.message).stopTimer(Ce.TOTAL_DURATION).commit()}onCacheResult(t){this.stats&&!this.stats.isCommitted()&&(t&&this.stats.setError(t instanceof ue.SendbirdError?t.code:void 0,t.message),this.stats.stopTimer(Ce.TOTAL_DURATION_FROM_CACHE))}onApiResult(t){this.stats&&!this.stats.isCommitted()&&(t&&this.stats.setError(t instanceof ue.SendbirdError?t.code:void 0,t.message),this.stats.stopTimer(Ce.TOTAL_DURATION).stopTimer(Ce.GET_MESSAGES).commit())}setChannelUrl(t){var n;(n=this.stats)==null||n.setChannelUrl(t)}cleanup(){var t;(t=this.stats)==null||t.commit()}setPresentMethod(t){var n;this.presentMethod=t,(n=this.stats)==null||n.setPresentMethod(t)}clear(){this.stats=null}}function Xa(){let e=null,t=0;const n=(r,o)=>{if((e==null?void 0:e.key)===r)return e.promise;const s=++t,l=(e?e.promise.catch(()=>{}).then(()=>o()):o()).finally(()=>{(e==null?void 0:e.id)===s&&(e=null)});return e={key:r,id:s,promise:l},l};return n.isPending=()=>e!==null,n}const vs=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0)),zr={isTalkToAgentViewEnabled:!0,scrollMode:"auto",newMessageIndicatorEnabled:!0,senderAvatarEnabled:!0},ir={conversation:{...zr,messageAlertSoundEnabled:!1,list:{...zr,deferredMarkdownElements:[]},header:{avatarEnabled:!0},input:{camera:{photoEnabled:!0},gallery:{photoEnabled:!0},fileEnabled:!0},fileViewer:{downloadEnabled:!0}},launcher:{unreadBadgeEnabled:!1}},Vr=e=>e?{conversation:Qa(e.conversation),launcher:Za(e.launcher)}:ir,Za=e=>ut(ir.launcher,e),Ja=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},Qa=e=>{const t=ir.conversation;if(!e)return t;const{list:n={},header:r={},input:o,fileViewer:s={},messageAlertSoundEnabled:a=t.messageAlertSoundEnabled,...l}=e,{camera:c={},gallery:d={},fileEnabled:m=t.input.fileEnabled}=o??{},f={...ut(t.list,l,n),deferredMarkdownElements:Ja(n)};return{...f,messageAlertSoundEnabled:a,list:f,header:ut(t.header,r),input:{camera:ut(t.input.camera,c),gallery:ut(t.input.gallery,d),fileEnabled:m},fileViewer:ut(t.fileViewer,s)}},ut=(e,...t)=>{const n={...e};for(const r of t)r&&Object.assign(n,vs(r));return n},el=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}),tl=e=>({type:e.image_type||"default_icon",imageUrl:e.image_url}),Vn=e=>({enabled:e.enabled,showIndicator:e.show_indicator,toggleAllowed:e.toggle_allowed,deleteOnOff:e.delete_on_off,consentDialog:e.consent_dialog}),ys=(e,t)=>{if(e)return e.members.filter(n=>n.userId!==t).sort((n,r)=>r.joinedAt-n.joinedAt)[0]},Ne=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===Ee.ConversationStatus.CLOSED||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="closed")},ar=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===Ee.ConversationStatus.OPEN||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="open")};function nt(e){var n,r,o;return typeof(((n=e==null?void 0:e.conversation)==null?void 0:n.handedOverAt)??((o=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff)==null?void 0:o.timestamp))=="number"}function nl(e){var r;const t=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff;return t?typeof t.requestedAt=="number"&&!nt(e):!1}function rl(e){var t;if(((t=e==null?void 0:e.resolution)==null?void 0:t.determinedBy)==="user")return e.resolution.isResolved}function Ss(e){return!!e&&e<=Date.now()}function ol(e){return!e.title}function sl(e,t){var n;if(e)return ol(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 il{constructor(){S(this,"_channelHandlerId",null);S(this,"_connectionHandlerId",null);S(this,"_handleActiveChannelChangedThrottled",null);S(this,"_setupChannelHandler",()=>{const t=Date.now();this._channelHandlerId=`aiagent_channel_${t}`,this._connectionHandlerId=`aiagent_connection_${t}`,this._handleActiveChannelChangedThrottled=ps(o=>{var s,a;(a=this._session)==null||a._updateActiveChannel({url:o.url,status:Ne(o)?"closed":"open",conversationStatus:(s=o.conversation)==null?void 0:s.status}),this._logger.debug("AIAgentEventManager: activeChannel updated",o.url)},250,{leading:!0,trailing:!1});const n=new Ye.GroupChannelHandler({onChannelChanged:o=>{var s,a;o.isGroupChannel()&&o.url===((s=this._session)==null?void 0:s.activeChannel.url)&&((a=this._handleActiveChannelChangedThrottled)==null||a.call(this,o))}}),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})});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,o;const t=(n=this._session)==null?void 0:n.activeChannel.url;if(t)try{const a=await(await this._chatClient.chatSDK.groupChannel.getChannel(t)).refresh();a.url===t&&((o=this._session)==null||o._updateActiveChannel({url:a.url,status:Ne(a)?"closed":"open",conversationStatus:(r=a.conversation)==null?void 0:r.status}),this._logger.debug("AIAgentEventManager: activeChannel synced on reconnect",a.url))}catch(s){this._logger.error("AIAgentEventManager: failed to sync activeChannel on reconnect",s)}});S(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)}});S(this,"onMessengerSettingsUpdated",t=>(this._dispatcher.subscribe(Be.MessengerSettingsUpdated,t),()=>{this._dispatcher.unsubscribe(Be.MessengerSettingsUpdated,t)}));S(this,"onActiveChannelUpdated",t=>(this._dispatcher.subscribe(Be.ActiveChannelUpdated,t),()=>{this._dispatcher.unsubscribe(Be.ActiveChannelUpdated,t)}));S(this,"onAuthTokenRefreshed",t=>(this._dispatcher.subscribe(Be.AuthTokenRefreshed,t),()=>{this._dispatcher.unsubscribe(Be.AuthTokenRefreshed,t)}))}}class al{constructor(t){S(this,"_sdkUser");S(this,"_userSession");S(this,"_dispatcher");S(this,"_activeChannel");S(this,"_updateActiveChannel",t=>{this._activeChannel=t,this._dispatcher.send(Qe.ActiveChannelUpdated({channelUrl:t.url,status:t.status,conversationStatus:t.conversationStatus}))});S(this,"_updateAuthToken",t=>{this._userSession.authToken=t,this._dispatcher.send(Qe.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 As=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)}},xs=e=>JSON.parse(e),ll=e=>JSON.parse(e);function cl(e,t){const[n,r]=t.split(",").map(o=>o.trim());return e==="dark"&&r||n}function ul(e){const t={};function n(r,o=""){for(const[s,a]of Object.entries(r)){const l=o?`${o}.${s}`:s;a&&typeof a=="object"&&!Array.isArray(a)?n(a,l):t[l]=a}}return n(e),t}function dl({template:e,variables:t,variableKeyPattern:n,variableValueTransformer:r}){return Object.entries(t).reduce((o,[s,a])=>{if(!r&&!["number","boolean","string"].includes(typeof a))throw new Error(`If transformer is not provided, value(${s}:${a}) must be a {string, number, or boolean}`);const l=r?r(a):String(a),c=n(s);return o.replace(c,As(l))},e)}async function ml({template:e,variables:t,variableKeyPattern:n,variableValueTransformer:r}){return(await Promise.all(Object.entries(t).map(async([s,a])=>{const l=await r(a);return{regex:n(s),transformedValue:l}}))).reduce((s,{regex:a,transformedValue:l})=>s.replace(a,As(l)),e)}var Yn=(e=>(e[e.EXTERNAL_AUTH_TOKEN_EXPIRED=1]="EXTERNAL_AUTH_TOKEN_EXPIRED",e))(Yn||{});const Ts=e=>typeof e=="object"&&e!==null,Yr=(e,t)=>t in e&&typeof e[t]=="string"&&e[t]!=="",fl=e=>!Ts(e)||!Yr(e,"channel_url")||!Yr(e,"ai_agent_id")?null:{channelUrl:e.channel_url,aiAgentId:e.ai_agent_id},gl={1:fl};function hl(e){if(!Ts(e)||!("cat"in e)||typeof e.cat!="number"||!("data"in e))return null;const t=e.cat,n=gl[t];if(!n)return null;const r=n(e.data);return r?{category:t,data:r}:null}function pl(e,t,n,r){const o=ya.default.init({appId:e,modules:[new Ye.GroupChannelModule,new Ee.AIAgentModule],localCacheEnabled:!0,options:new ue.SendbirdChatOptions({typingIndicatorInvalidateTime:2e4}),...r});return o.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),o}function _l(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 El=[400300,400301,400302,400310];class lr{constructor(t,n,r){S(this,"chatSDK");S(this,"_logger");S(this,"_cache");S(this,"connect",async(t,n,r,o)=>{if(this._logger.debug("ChatClient.connect: start",t.userId),n){const s=new ue.SessionHandler({...n,onSessionTokenRequired:this._interceptTokenRefresh(n.onSessionTokenRequired,r,o)});this.chatSDK.setSessionHandler(s),this.chatSDK.aiAgent.addEventHandler(Yn.EXTERNAL_AUTH_TOKEN_EXPIRED.toString(),a=>{var c;this._logger.debug("ChatClient.connect: EXTERNAL_AUTH_TOKEN_EXPIRED event received",a);const l=hl(a);(l==null?void 0:l.category)===Yn.EXTERNAL_AUTH_TOKEN_EXPIRED&&(this._logger.debug("ChatClient.connect: calling onExternalAuthTokenExpired handler",l.data),(c=n==null?void 0:n.onExternalAuthTokenExpired)==null||c.call(n,l.data))})}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(s){const a=s;if(this.chatSDK.isCacheEnabled){if(this._isCacheRestrictedError(a))this._logger.warn("ChatClient.connect","offline connect restricted",a.message,a.code),this._logger.warn("ChatClient.connect","clear cached-data"),await this.chatSDK.clearCachedData().catch(l=>this._logger.warn("ChatClient.connect","clear cached-data failure",l));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",a.message,a.code),a}});S(this,"disconnect",async()=>{this._logger.debug("ChatClient.disconnect: start"),this.chatSDK.aiAgent.removeAllEventHandlers(),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 o;if(t.userId===""){const s=new Error("userId cannot be empty string for messenger settings request");throw this._logger.error("ChatClient.requestMessengerSettings: invalid userId",s),s}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",(o=r.active_channel)==null?void 0:o.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(o,s)=>{new Promise((a,l)=>t==null?void 0:t(a,l)).then(a=>{a?n==null||n(a):r==null||r(),o(a)}).catch(a=>{r==null||r(),s(a)})}});S(this,"_isCacheRestrictedError",t=>El.some(n=>t.code===n));S(this,"_syncTemplatesIfNeeded",async()=>{var r,o;const t=(o=(r=this.chatSDK.appInfo)==null?void 0:r.aiAgentInfo)==null?void 0:o.templateListToken;if(!t)return;const n=this._cache.template.getCachedToken();if(!(n&&n===t)){this._logger.debug("ChatClient._syncTemplatesIfNeeded: syncing templates");try{const{templates:s,token:a}=await this.chatSDK.aiAgent.getMessageTemplates({limit:20});for(const{template:l}of s){const{key:c}=xs(l);this._cache.template.set(c,l)}this._cache.template.setCachedToken(a),this._logger.debug("ChatClient._syncTemplatesIfNeeded: sync completed")}catch(s){this._logger.error("ChatClient._syncTemplatesIfNeeded: error",s)}}});this.chatSDK=t,this._logger=n,this._cache=r}static init(t){let n;return t.chatSDK?(_l(t.chatSDK),n=t.chatSDK):n=pl(t.appId,t.extensions,t.messengerVersion,t.chatParams),new lr(n,t.logger,t.cache)}}const Ht=new Map,Is={set:(e,t)=>{Ht.set(e,t)},get:e=>{if(Ht.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=Ht.get(e);if(!n)throw new Error(`AIAgent platform "${e}" is not configured.`);return{platform:e,...n}}const t=Ht.entries().next().value;return{platform:t[0],...t[1]}}};class Wr extends Error{constructor(n,r){const o=(r==null?void 0:r.detail)??"";super(o||`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=o}}var cr=(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))(cr||{}),ur=(e=>(e.URGENT="URGENT",e.HIGH="HIGH",e.MEDIUM="MEDIUM",e.LOW="LOW",e))(ur||{}),ws=(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))(ws||{});const bl=e=>e==="desk401103"||e==="desk401106"||e==="desk401107"||e==="desk401108"||e==="desk401109";class Cl{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,o=`${this._apiHost}${t}`;r&&this._authRefreshPromise&&(this._logger.debug("DeskApiClient: waiting for in-flight recovery..."),await this._authRefreshPromise);const s=await this._fetch(o,n);return r&&s.status===401?this._handleUnauthorized(s,o,n):this._toResult(s)});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 o=await this._parseErrorCode(t);if(!bl(o))return this._toResult(t);if(!await this._refresh(o)||this._credential===null)return this._toResult(t);const a=await this._fetch(n,r);return this._toResult(a)});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 Wr(t.status,r)}const n=await t.text();if(n)try{return JSON.parse(n)}catch{throw new Wr(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}.sendbird.com/sapi`,this._logger=t.logger}get credential(){return this._credential}}class nn{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 nn({id:t.id,title:t.channelName??null,status:t.status2??cr.INITIALIZED,agent:(()=>{var s;const o=(s=t.recentAssignment)==null?void 0:s.agent;return o?{userId:o.sendbirdId??"",name:o.displayName??"",profileUrl:o.photoThumbnailUrl??""}:null})(),priority:t.priority??ur.MEDIUM,group:t.group??0,firstResponseTime:t.firstResponseTime??-1,issuedAt:t.issuedAt??null,customFields:Object.fromEntries(((r=t.customFields)==null?void 0:r.map(o=>[o.key,o.value]))??[])},n)}}class dr{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 nn._fromResponse(n,this)});S(this,"createTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request("/tickets/",{method:"POST",body:vs({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 nn._fromResponse(n,this)});this._logger=t.logger,this._apiClient=new Cl(t)}static init(t){return new dr(t)}_assertAuthenticated(t){if(t.credential==null)throw new Error("DeskClient is not authenticated")}}class mr{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 mr}}function vl(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 yl=1440*60*1e3,Sl=typeof __SBA_USE_DESK_CLIENT__>"u"||__SBA_USE_DESK_CLIENT__;function je(e){if(!e)throw new Error("Not authenticated. Call authenticate() first.")}function Al(e,t){return Object.entries(t).every(([n,r])=>e[n]===r)}class rn extends il{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,"_forceCreateChannel");S(this,"_agentVersion");S(this,"_statsTrackers");S(this,"_operationQueue",Xa());S(this,"dispose",()=>{this._operationQueue.isPending()||(this._logger.debug("AIAgent.dispose: start"),this._chatClient.chatSDK.connectionState==="OPEN"&&this._chatClient.chatSDK.disconnectWebSocket(),this._removeChannelHandler(),this._session=null,this._deskClient.deauthenticate(),this._statsTrackers.initialRender.clear(),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 a,l,c,d,m;this._logger.debug("AIAgent.authenticate: start"),this._statsTrackers.initialRender.onAuthStart();const o=this._getSessionCandidate(n),s=(a=o.userSessionCandidate)!=null&&a.userId?this._cache.messenger.getSettings(o.userSessionCandidate.userId):null;s!=null&&s.bot&&this._dispatcher.send(Qe.MessengerSettingsUpdated({settings:s,source:"cache"}));try{const f=await this._chatClient.requestMessengerSettings({aiAgentId:this.aiAgentId,userId:(l=o.userSessionCandidate)==null?void 0:l.userId,language:this.language,country:this.countryCode,context:this.context,knownActiveChannelUrl:(c=s==null?void 0:s.active_channel)==null?void 0:c.channel_url,forceCreateChannel:this._forceCreateChannel,agentVersion:this._agentVersion});let g;if(f.auto_created_user)if(o.type==="manual")this._logger.warn("Received auto created user info but current session is manual. Ignoring auto created user info."),g={userId:o.userSessionCandidate.userId,authToken:o.userSessionCandidate.authToken};else{const{user_id:v,session_token:b,expire_at:_}=f.auto_created_user;this._cache.messenger.setAnonUser({userId:v,authToken:b,expireAt:_}),g={userId:v,authToken:b},this._logger.debug("AIAgent.authenticate: anonymous user created",v)}else g={userId:((d=o.userSessionCandidate)==null?void 0:d.userId)??"",authToken:((m=o.userSessionCandidate)==null?void 0:m.authToken)??""};this._cache.messenger.setSettings(g.userId,f),this._dispatcher.send(Qe.MessengerSettingsUpdated({settings:f,source:"server"}));const E=(()=>{var v;return o.type==="anonymous"?za(this._dispatcher):(v=o.userSessionCandidate)==null?void 0:v.sessionHandler})(),y=await this._chatClient.connect(g,E,v=>{var b;this._logger.debug("AIAgent: session token refreshed"),(b=this._session)==null||b._updateAuthToken(v),this._deskClient.refreshDeskAuthToken(v)},()=>{this._logger.debug("AIAgent: session token unavailable, deauthenticating desk"),this._deskClient.deauthenticate()});return await this._deskClient.authenticate({userId:g.userId,accessToken:g.authToken,onDeskTokenRefreshRequired:async({reason:v})=>{var b;if(v===ws.ERR_SESSION_KEY_EXPIRED){await new Promise(C=>setTimeout(C,2e3));const _=(b=this._session)==null?void 0:b.userSession.authToken;return _?await this._deskClient.refreshDeskAuthToken(_):!1}return!1}}),(s==null?void 0:s.language)!==f.language&&this._deskClient.setCustomerLanguage(this.language).catch(()=>{}),this._statsTrackers.initialRender.onAuthComplete(),this._session=new al({sdkUser:y,userSession:g,activeChannel:{url:f.active_channel.channel_url,status:"open"},dispatcher:this._dispatcher}),this._setupChannelHandler(),this._logger.debug("AIAgent.authenticate: end",{userId:g.userId}),f}catch(f){throw this._statsTrackers.initialRender.onAuthError(f),f}})});S(this,"deauthenticate",()=>this._operationQueue("deauth",async()=>{var n;this._logger.debug("AIAgent.deauthenticate: start"),await this._chatClient.disconnect(),this._deskClient.deauthenticate(),this._cache.messenger.clear((n=this._session)==null?void 0:n.userSession.userId),this._session=null,this._removeChannelHandler(),this._statsTrackers.initialRender.clear(),this._logger.debug("AIAgent.deauthenticate: end")}));S(this,"createConversation",async n=>{je(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}),o=r.active_channel.channel_url;return this._cache.messenger.setSettings(this._session.userSession.userId,r),this._logger.debug("AIAgent.createConversation: end",o),o});S(this,"searchConversation",async n=>{if(je(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:Ee.ConversationStatus.OPEN,limit:100}),o=[];for(;r.hasNext;){const s=await r.next();for(const a of s)Al(a.context??{},n.context)&&o.push(a.channelInfo.url)}return this._logger.debug("AIAgent.searchConversation: end",{count:o.length}),o});S(this,"closeConversation",async n=>{var o;je(this._session),this._logger.debug("AIAgent.closeConversation: start",n);const r=await this._chatClient.getChannel(n);((o=r.conversation)==null?void 0:o.status)===Ee.ConversationStatus.OPEN?(await r.closeConversation(),this._session.activeChannel.url===n&&this._session._updateActiveChannel({url:n,status:"closed",conversationStatus:Ee.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 _s(this.chatSDK,n??{}));S(this,"patchContext",async(n,r)=>{je(this._session),this._logger.debug("AIAgent.patchContext: start",{channelUrl:n,context:r});const o=await this._chatClient.patchContext(this.aiAgentId,n,r);return this._logger.debug("AIAgent.patchContext: end",o),{...o,context:o.context??{}}});S(this,"updateContext",async(n,r)=>{je(this._session),this._logger.debug("AIAgent.updateContext: start",{channelUrl:n,context:r});const o=await this._chatClient.updateContext(this.aiAgentId,n,r);return this._logger.debug("AIAgent.updateContext: end",o),{...o,context:o.context??{}}});S(this,"getContextObject",async n=>{je(this._session),this._logger.debug("AIAgent.getContextObject: start",n);const o=await(await this._chatClient.getChannel(n)).getContextObject(this.aiAgentId);return this._logger.debug("AIAgent.getContextObject: end",o),{...o,context:o.context??{}}});S(this,"clearUserMemories",async(n={})=>{je(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=>{je(this._session);const r=this._session;this._logger.debug("AIAgent.setUserMemoryState: start",n.enabled);const o={...n,contextAiAgentId:n.contextAiAgentId??this.aiAgentId},s=r.userSession.userId,a=await this._chatClient.setUserMemoryState(o);if(this._session!==r)return this._logger.debug("AIAgent.setUserMemoryState: session changed during request, discarding stale result"),Vn(a);const l=this._cache.messenger.getSettings(s);if(l){const c={...l,memory:a};this._cache.messenger.setSettings(s,c),this._dispatcher.send(Qe.MessengerSettingsUpdated({settings:c,source:"cache"}))}return this._logger.debug("AIAgent.setUserMemoryState: end",a.enabled),Vn(a)});S(this,"refreshActiveChannel",async n=>{var l,c,d;je(this._session);const r=this._session,o=(n==null?void 0:n.useKnownActiveChannelUrl)??!0;this._logger.debug("AIAgent.refreshActiveChannel: start",{useKnownActiveChannelUrl:o});const s=await this._chatClient.requestMessengerSettings({aiAgentId:this.aiAgentId,userId:r.userSession.userId,language:this.language,country:this.countryCode,context:this.context,knownActiveChannelUrl:o?(c=(l=this._cache.messenger.getSettings(r.userSession.userId))==null?void 0:l.active_channel)==null?void 0:c.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)??s.active_channel.channel_url;const a=s.active_channel.channel_url;return this._cache.messenger.setSettings(this._session.userSession.userId,s),this._session._updateActiveChannel({url:a,status:"open"}),this._logger.debug("AIAgent.refreshActiveChannel: end",a),a});S(this,"_getSessionCandidate",n=>n instanceof Cs?{type:"manual",userSessionCandidate:this._getManualSessionInfo(n)}:n instanceof zn?{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-yl<=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 zn)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(o=>!(o 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=Vr(n.config),this.queryParams=n.queryParams,this._networkStateAdapter=n.networkStateAdapter,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={initialRender:new ja((r,o)=>this._chatClient.chatSDK.aiAgent.appendStat(r,o))}}static init(n){var f;const r=Is.get(n.platform),o=n.logger??new bs(n.logLevel??sr.WARN),s=n.dispatcher??new Es(o),a=n.useMMKVStorage?vl(n.useMMKVStorage):r.keyValueStorage,l=n.useMMKVStorage?{...n.chatParams,useMMKVStorageStore:n.useMMKVStorage}:n.chatParams,c=Na({appId:n.appId,aiAgentId:n.aiAgentId,storage:a}),d=lr.init({appId:n.appId,messengerVersion:r.messengerVersion,extensions:{platform:r.platform,deviceOSPlatform:r.deviceOSPlatform,deviceOSVersion:r.deviceOSVersion},chatParams:l,chatSDK:n.chatSDK,logger:o,cache:c}),m=Sl?dr.init({appId:n.appId,logger:o,customApiHost:(f=n.deskParams)==null?void 0:f.customApiHost}):mr.init();return o.debug("AIAgent.init: created",{appId:n.appId,aiAgentId:n.aiAgentId}),new rn({appId:n.appId,aiAgentId:n.aiAgentId,language:n.language,countryCode:n.countryCode,context:n.context,config:n.config,queryParams:n.queryParams,networkStateAdapter:r.networkStateAdapter,forceCreateChannel:n._forceCreateChannel,agentVersion:n._agentVersion,chatClient:d,deskClient:m,cache:c,logger:o,dispatcher:s})}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=Vr(n)}get agentVersion(){return this._agentVersion}set agentVersion(n){this._agentVersion=n}get networkStateAdapter(){return this._networkStateAdapter}get logger(){return this._logger}get dispatcher(){return this._dispatcher}get cache(){return this._cache}get statsTrackers(){return this._statsTrackers}}const pe=(e,t)=>{const n=u.createContext(t??null),r=({children:a,value:l})=>i.createElement(n.Provider,{value:l},typeof a=="function"?a(l):a),o=({children:a})=>i.createElement(n.Consumer,null,l=>l?typeof a=="function"?a(l):a:null),s=()=>{const a=u.useContext(n);if(!a)throw new Error(`use${e}Context must be used within a ${e}Provider`);return a};return n.displayName=`${e}Context`,r.displayName=`${e}Provider`,o.displayName=`${e}Consumer`,s.displayName=`use${e}Context`,{Context:n,Provider:r,Consumer:o,useContext:s}};function Ge(e){const t=u.createContext({Template:e.template,updateTemplate:()=>{},components:e.components,updateComponent:()=>{}});function n({children:s}){const[a,l]=u.useState(()=>e.template),[c,d]=u.useState(e.components),m={Template:a,updateTemplate:f=>l(()=>f),components:c,updateComponent:(f,g)=>d(E=>({...E,[f]:g}))};return i.createElement(t.Provider,{value:m},s)}function r({template:s,children:a}){const{updateTemplate:l}=u.useContext(t);return u.useLayoutEffect(()=>{s&&l(s)},[s]),i.createElement(i.Fragment,null,a)}function o({children:s}){return i.createElement(n,null,s)}return o.defaults=e,o.useContext=()=>u.useContext(t),o.Context=t,o.Template=r,Object.keys(e.components).forEach(s=>{o[s]=function({component:l}){const{updateComponent:c}=u.useContext(t);return u.useLayoutEffect(()=>{l&&c(s,l)},[l]),null}}),o}function xl(...e){return function({children:n}){return e.reduce((r,o)=>i.createElement(o,null,r),n)}}function Tl(e,t){const n=e.lastMessage;return n!=null&&n.isAdminMessage()?n.message??"":Ms(e,t)}function Ms(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 o=n.fileInfoList.length;return((r=t==null?void 0:t.formatMultipleFilesCount)==null?void 0:r.call(t,o))??`${o} photos`}return e.name}function Il(e,t,n){var a;const r=new Date,o=new Date(((a=e.lastMessage)==null?void 0:a.createdAt)||e.createdAt),s=Je.differenceInMinutes(r,o);return s<1?n.justNow:s<60?n.minutesAgo(s):Je.isToday(o)?n.hoursAgo(Je.differenceInHours(r,o)):t(o,n.dateShortFormat)}const wl=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},Gt=e=>Math.max(0,Math.min(255,e)).toString(16).padStart(2,"0"),qr=(e,t)=>{const n=Gt(Math.round(t*255));if(e.startsWith("#")){const o=e.slice(1);return o.length===3||o.length===4?`#${o[0]}${o[0]}${o[1]}${o[1]}${o[2]}${o[2]}${n}`:`#${o.slice(0,6)}${n}`}const r=wl(e);return r?`#${Gt(r[0])}${Gt(r[1])}${Gt(r[2])}${n}`:e},Ml=(e,t)=>{if(!t)return e;const n={...e};for(const[r,o]of Object.entries(t))o&&(n[r]=o);return n},kl=e=>e.consentDialog?"consent":e.toggleAllowed?e.enabled?"on":"off":"readonly",Rl=e=>e.length>0,Ll=e=>{const t=e[0];if(!t)return e;const n=e.some(o=>ze(o.type)),r=e.some(o=>!ze(o.type));return n&&r?ze(t.type)?e.filter(o=>ze(o.type)):[t]:r?[t]:e},Kr=e=>e.length===0?"empty":e.every(t=>ze(t.type))?"images":"non_images",Ol=({currentFiles:e,incomingFiles:t,maxAttachmentCount:n})=>{const r=Ll(t),o=Kr(e),s=Kr(r),l=o==="images"&&s==="images"?{type:"append",files:r,nextFiles:[...e,...r]}:{type:"replace",files:r,nextFiles:r};return l.nextFiles.length>n?{type:"reject",reason:"count_limit",maxAttachmentCount:n,nextFileCount:l.nextFiles.length}:l.type==="replace"&&o!=="empty"&&o!==s?{type:"confirm_replace",action:l}:{type:"apply",action:l}},mt=3,ks=6,Nl=e=>e%mt===0?mt:ks,Dl=({index:e,itemCount:t})=>{const n=t%mt,r=n>0,o=r?t-n:t,s=r&&e>=o,a=s?n:mt,l=s?e-o:e%mt,c=!r&&e>=t-mt;return{columnSpan:r?ks/a:1,rowItemCount:a,isLastInRow:l===a-1,isLastRow:s||c}},Rs=pe("AIAgent"),$l=Rs.Provider,Re=Rs.useContext;function Pl(e){const t=Fl(e);return i.createElement($l,{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 Fl(e){const t=u.useRef(null),n=u.useRef(null);if(!t.current||!n.current)t.current=rn.init(e);else{const o=Ul(n.current,e);(o.appId||o.aiAgentId||o.chatSDK)&&(t.current.dispose(),t.current=rn.init({...e,chatParams:o.appId?{...e.chatParams,newInstance:!0}:e.chatParams}))}n.current=e,u.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}function Ul(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}}const jr=Symbol("conversationMessageEventBridge"),Ct=Symbol("conversationMessageEventPublisher"),Bl=(e,t)=>{const n=e;if(n[Ct]=t,n[jr])return e;n[jr]=!0;const r=e.setMessageCollectionHandler.bind(e);e.setMessageCollectionHandler=s=>{r({...s,onMessagesAdded:(a,l,c)=>{var d,m;(d=s.onMessagesAdded)==null||d.call(s,a,l,c),(m=n[Ct])==null||m.call(n,{kind:"messagesAdded",source:a.source,messages:c})},onMessagesUpdated:(a,l,c)=>{var d,m;(d=s.onMessagesUpdated)==null||d.call(s,a,l,c),(m=n[Ct])==null||m.call(n,{kind:"messagesUpdated",source:a.source,messages:c})}})};const o=e.initialize.bind(e);return e.initialize=s=>{const a=o(s),l=a.onCacheResult.bind(a),c=a.onApiResult.bind(a);return a.onCacheResult=d=>l((m,f)=>{var g;d(m,f),(g=n[Ct])==null||g.call(n,{kind:"initialized",source:"cache",messages:f??[]})}),a.onApiResult=d=>c((m,f)=>{var g;d(m,f),(g=n[Ct])==null||g.call(n,{kind:"initialized",source:"api",messages:f??[]})}),a},e},gn=()=>{const[,e]=u.useState(0);return u.useCallback(()=>e(t=>t+1),[])};let Hl=0;function Gl(){return u.useState(()=>`${Hl++}`)[0]}const ht=(e,t,n)=>{const r=u.useRef(t),s=Gl();r.current=t,u.useEffect(()=>{var l;const a=c=>{const d=c;return Object.keys(d).forEach(f=>{d[f]=(...g)=>{var y;const E=r.current;(y=E[f])==null||y.call(E,...g)}}),d};return(l=e==null?void 0:e.groupChannel)==null||l.addGroupChannelHandler(s,a(new Ye.GroupChannelHandler)),()=>{var c;(c=e==null?void 0:e.groupChannel)==null||c.removeGroupChannelHandler(s)}},[e==null?void 0:e.groupChannel,s])};function zl(e,t){return!e||!t?!0:e.url!==t.url}function Fe(e){return e!=null&&"sendingStatus"in e}function Vl(e,t="##__USER_ID_IS_NOT_PROVIDED__##"){var n;return Fe(e)?((n=e.sender)==null?void 0:n.userId)===t:!1}function Yl(e,t){return Vl(e,t)||e.isAdminMessage()?!1:e.updatedAt===0}function Xr(e){return"sendingStatus"in e?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId)}const on={collection:{groupChannel:{defaultOrder:Ye.GroupChannelListOrder.LATEST_LAST_MESSAGE},message:{defaultLimit:{next:25,prev:25},searchLimit:{next:10,prev:10}}}};function Zr(e){return!e||!Array.isArray(e)?!1:e.length!==0}function Jr(e,t){return e.reduce((n,r)=>{const o=t(r);return n[o]=r,n},{})}const Wl=({...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=ql(t.value.messages);else{const n={...e.messageMap},r=[],o=[];t.value.messages.forEach(s=>{const a=Fe(s)?s.reqId:void 0,l=s.messageId||void 0;[a,l].forEach(c=>{if(!c)return;const d=n[c];Kl(d,s,t.value.strictStreamingOrder)&&(d&&r.push(d),s.parentMessageId>0&&(d!=null&&d.parentMessage)&&s.applyParentMessage(d.parentMessage),o.push(s))})}),r.forEach(s=>{Fe(s)&&delete n[s.reqId],delete n[s.messageId]}),o.forEach(s=>{Fe(s)&&(n[s.reqId]=s),s.messageId!==0&&(n[s.messageId]=s)}),e.messageMap=n}return e}case"update_new_messages":{const n=t.value.currentUserId,r=t.value.messages.filter(o=>Yl(o,n));return t.value.clearBeforeAction?e.newMessageMap=Jr(r,Xr):(r.map(s=>s.messageId).forEach(s=>delete e.newMessageMap[s]),e.newMessageMap={...e.newMessageMap,...Jr(r,Xr)}),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 o=e[n][r];o&&(Fe(o)&&delete e[n][o.reqId],delete e[n][o.messageId])}),t.value.reqIds.forEach(r=>{const o=e[n][r];o&&(Fe(o)&&delete e[n][o.reqId],delete e[n][o.messageId])}),e}}},ql=e=>e.reduce((t,n)=>(Fe(n)?(t[n.reqId]=n,n.sendingStatus===He.SendingStatus.SUCCEEDED&&(t[n.messageId]=n)):t[n.messageId]=n,t),{}),Kl=(e,t,n=!1)=>{var r,o;if(!Fe(e)||!Fe(t))return!0;if(n&&e&&eo(e)&&eo(t)){const s=((r=e.message)==null?void 0:r.length)||0,a=((o=t.message)==null?void 0:o.length)||0;if(s>a)return!1}return e.sendingStatus===He.SendingStatus.SUCCEEDED?t.sendingStatus===He.SendingStatus.SUCCEEDED:e.sendingStatus!==t.sendingStatus},jl=(e=Xl)=>{const[{initialized:t,loading:n,refreshing:r,messageMap:o,newMessageMap:s},a]=u.useReducer(Wl,{initialized:!1,loading:!0,refreshing:!1,messageMap:{},newMessageMap:{}}),l=(b,_,C,x)=>{a({type:"update_messages",value:{messages:b,clearBeforeAction:_,currentUserId:C,strictStreamingOrder:x}})},c=(b,_)=>{a({type:"delete_messages",value:{messageIds:b,reqIds:_}})},d=(b,_,C)=>{a({type:"update_new_messages",value:{messages:b,clearBeforeAction:_,currentUserId:C}})},m=(b,_)=>{a({type:"delete_new_messages",value:{messageIds:b,reqIds:_}})},f=b=>{a({type:"update_initialized",value:{status:b}})},g=b=>{a({type:"update_loading",value:{status:b}})},E=b=>{a({type:"update_refreshing",value:{status:b}})},y=Object.values(s),v=u.useMemo(()=>Array.from(new Set(Object.values(o))).sort(e),[o]);return{updateInitialized:f,updateLoading:g,updateRefreshing:E,updateMessages:l,deleteMessages:c,initialized:t,loading:n,refreshing:r,messages:v,newMessages:y,updateNewMessages:d,deleteNewMessages:m}},Qr=Math.floor(Number.MAX_SAFE_INTEGER/10);function Xl(e,t){let n=0,r=0;return Fe(e)&&e.sendingStatus!=="succeeded"&&(n=Qr),Fe(t)&&t.sendingStatus!=="succeeded"&&(r=Qr),e.createdAt+n-(t.createdAt+r)}function eo(e){try{const t=JSON.parse(e.data||"{}");return typeof t=="object"&&!!t.stream}catch{return!1}}function ye(e){const t=u.useRef(e);return t.current=e,u.useCallback((...n)=>t.current(...n),[t])}const Zl=(e,t,n)=>{var s;const r={prevResultLimit:t.prev,nextResultLimit:t.next,startingPoint:n==null?void 0:n.startingPoint,replyType:n==null?void 0:n.replyType},o=(s=n==null?void 0:n.collectionCreator)==null?void 0:s.call(n,r);return o||e.createMessageCollection({...r,filter:new Ye.MessageFilter(r)})};function to(e){return e<Date.now()?on.collection.message.searchLimit:on.collection.message.defaultLimit}const Jl=(e,t,n={})=>{var De,xe;const r=u.useRef(n);r.current=n;const o=u.useRef(t);o.current=t;const s=r.current.logger,a=r.current.startingPoint??Number.MAX_SAFE_INTEGER,l=to(a),c=r.current.strictStreamingOrder??!1,d=u.useRef({prev:!1,next:!1}),m=gn(),f=u.useRef({initialized:!1,apiInitialized:!1,instance:null}),{initialized:g,loading:E,refreshing:y,messages:v,newMessages:b,updateMessages:_,updateNewMessages:C,deleteNewMessages:x,deleteMessages:A,updateInitialized:w,updateLoading:M,updateRefreshing:k}=jl(n==null?void 0:n.sortComparator),R=ye(I=>{var L,N,K,G;if(!o.current||!o.current.url)return(L=s==null?void 0:s.error)==null?void 0:L.call(s,"[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:(K=(N=r.current).markAsRead)==null||K.call(N,[o.current]);break}}catch(H){(G=s==null?void 0:s.warn)==null||G.call(s,"[useGroupChannelMessages/markAsReadBySource]",H)}}),O=ye((I,L)=>{var N,K,G,H,U;if(L.length>0)switch(I){case ue.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case ue.CollectionEventSource.SYNC_MESSAGE_FILL:{(K=(N=r.current).shouldCountNewMessages)!=null&&K.call(N)&&C(L,!1,(G=e.currentUser)==null?void 0:G.userId),(U=(H=r.current).onMessagesReceived)==null||U.call(H,L);break}}}),z=ye(I=>{var L,N;(N=(L=r.current).onCollectionEvent)==null||N.call(L,I)}),Y=ye(async(I,L,N)=>new Promise((K,G)=>{var Pe;f.current.instance&&f.current.instance.dispose(),R(),C([],!0,(Pe=e.currentUser)==null?void 0:Pe.userId);const H=()=>{var me,te;const{pendingMessages:ne,failedMessages:fe}=f.current.instance??{};Zr(ne)&&_(ne,!1,(me=e.currentUser)==null?void 0:me.userId),Zr(fe)&&_(fe,!1,(te=e.currentUser)==null?void 0:te.userId)},U=Zl(I,N,{...r.current,startingPoint:L});f.current={apiInitialized:!1,initialized:!1,instance:U},U.setMessageCollectionHandler({onMessagesAdded:(ne,fe,me)=>{var te;R(ne.source),O(ne.source,me),_(me,!1,(te=e.currentUser)==null?void 0:te.userId,c),z({kind:"messagesAdded",source:ne.source,messages:me})},onMessagesUpdated:(ne,fe,me)=>{var te,ve,ge;R(ne.source),O(ne.source,me),_(me,!1,(te=e.currentUser)==null?void 0:te.userId,c),ne.source===ue.CollectionEventSource.EVENT_MESSAGE_UPDATED&&((ge=(ve=r.current).onMessagesUpdated)==null||ge.call(ve,me)),z({kind:"messagesUpdated",source:ne.source,messages:me})},onMessagesDeleted:(ne,fe,me,te)=>{const ve=te.map(j=>j.messageId),ge=te.filter(Fe).map(j=>j.reqId);A(ve,ge),x(ve,ge),z({kind:"messagesDeleted",source:ne.source,messages:te})},onChannelDeleted:(ne,fe)=>{var me,te;(te=(me=r.current).onChannelDeleted)==null||te.call(me,fe)},onChannelUpdated:(ne,fe)=>{var me,te;m(),(te=(me=r.current).onChannelUpdated)==null||te.call(me,fe,ne)},onHugeGapDetected:()=>{Y(I,Number.MAX_SAFE_INTEGER,on.collection.message.defaultLimit)}});let de=!1;U.initialize(Ye.MessageCollectionInitPolicy.CACHE_AND_REPLACE_BY_API).onCacheResult((ne,fe)=>{var me,te,ve,ge,j;(te=(me=r.current).onCacheResult)==null||te.call(me,ne,fe??[]),ne?(e.isCacheEnabled&&((ve=s==null?void 0:s.error)==null||ve.call(s,"[useGroupChannelMessages/onCacheResult]",ne)),de=!0):fe&&((ge=s==null?void 0:s.debug)==null||ge.call(s,"[useGroupChannelMessages/onCacheResult]","message length:",fe.length),_(U.succeededMessages,!0,(j=e.currentUser)==null?void 0:j.userId),H(),fe.length>0&&(f.current.initialized=!0,K())),z({kind:"initialized",source:"cache",messages:fe??[]})}).onApiResult((ne,fe)=>{var me,te,ve,ge,j,he,Te;(te=(me=r.current).onApiResult)==null||te.call(me,ne,fe??[]),f.current.initialized=!0,f.current.apiInitialized=!0,ne?((ve=s==null?void 0:s.warn)==null||ve.call(s,"[useGroupChannelMessages/onApiResult]",ne),de?G(ne):K()):fe&&((ge=s==null?void 0:s.debug)==null||ge.call(s,"[useGroupChannelMessages/onApiResult]","message length:",fe.length),_(U.succeededMessages,!0,(j=e.currentUser)==null?void 0:j.userId),r.current.startingPoint||(Te=(he=r.current).onMessagesReceived)==null||Te.call(he,fe),e.isCacheEnabled&&H(),K()),z({kind:"initialized",source:"api",messages:fe??[]})})}));ht(e,{onUserBanned(I,L){var N,K,G;I.isGroupChannel()&&!zl(I,o.current)&&(L.userId===((N=e.currentUser)==null?void 0:N.userId)?(G=(K=r.current).onCurrentUserBanned)==null||G.call(K):m())}}),u.useLayoutEffect(()=>{const I=setTimeout(async()=>{e.currentUser&&o.current&&(w(!1),M(!0),await Y(o.current,a,l),M(!1),w(!0))});return()=>clearTimeout(I)},[e,(De=e.currentUser)==null?void 0:De.userId,(xe=o.current)==null?void 0:xe.url,r.current.replyType]),u.useEffect(()=>()=>{f.current.instance&&f.current.instance.dispose()},[]);const P=ye(async()=>{e.currentUser&&o.current&&(k(!0),await Y(o.current,Number.MAX_SAFE_INTEGER,on.collection.message.defaultLimit),k(!1))}),V=ye(async()=>{var L;const I=f.current.instance;if(I!=null&&I.hasPrevious&&!d.current.prev)try{d.current.prev=!0;const N=await I.loadPrevious();_(N,!1,(L=e.currentUser)==null?void 0:L.userId)}catch{}finally{d.current.prev=!1}}),B=ye(()=>{const{initialized:I,instance:L}=f.current;return I&&L?L.hasPrevious:!1}),W=ye(async()=>{var L;const I=f.current.instance;if(I!=null&&I.hasNext&&!d.current.next)try{d.current.next=!0;const N=await I.loadNext();_(N,!1,(L=e.currentUser)==null?void 0:L.userId)}catch{}finally{d.current.next=!1}}),q=ye(()=>{const{initialized:I,apiInitialized:L,instance:N}=f.current;return L&&I&&N?N.hasNext:!1}),ie=ye((I,L)=>{var N;if(!o.current||!o.current.url)throw(N=s==null?void 0:s.error)==null||N.call(s,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((K,G)=>{o.current.sendUserMessage(I).onPending(H=>{var U;H.channelUrl===o.current.url&&_([H],!1,(U=e.currentUser)==null?void 0:U.userId),L==null||L(H)}).onSucceeded(H=>{var U;H.channelUrl===o.current.url&&_([H],!1,(U=e.currentUser)==null?void 0:U.userId),K(H)}).onFailed((H,U)=>{var de;U&&U.channelUrl===o.current.url&&_([U],!1,(de=e.currentUser)==null?void 0:de.userId),G(H)})})}),_e=ye((I,L)=>{var N;if(!o.current||!o.current.url)throw(N=s==null?void 0:s.error)==null||N.call(s,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((K,G)=>{o.current.sendFileMessage(I).onPending(H=>{var U;H.channelUrl===o.current.url&&_([H],!1,(U=e.currentUser)==null?void 0:U.userId),L==null||L(H)}).onSucceeded(H=>{var U;H.channelUrl===o.current.url&&_([H],!1,(U=e.currentUser)==null?void 0:U.userId),K(H)}).onFailed((H,U)=>{var de;U&&U.channelUrl===o.current.url&&_([U],!1,(de=e.currentUser)==null?void 0:de.userId),G(H)})})}),Le=ye(async(I,L)=>{var N;if(!o.current||!o.current.url)throw(N=s==null?void 0:s.error)==null||N.call(s,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise(K=>{const G=[];o.current.sendFileMessages(I).onPending(H=>{var U;H.channelUrl===o.current.url&&_([H],!1,(U=e.currentUser)==null?void 0:U.userId),L==null||L(H)}).onSucceeded(H=>{var U;H.isFileMessage()&&H.channelUrl===o.current.url&&(_([H],!1,(U=e.currentUser)==null?void 0:U.userId),G.push(H)),G.length===I.length&&K(G)}).onFailed((H,U)=>{var de;U&&U.channelUrl===o.current.url?(_([U],!1,(de=e.currentUser)==null?void 0:de.userId),G.push(U)):G.push(null),G.length===I.length&&K(G)})})}),J=ye((I,L)=>{var N;if(!o.current||!o.current.url)throw(N=s==null?void 0:s.error)==null||N.call(s,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((K,G)=>{o.current.sendMultipleFilesMessage(I).onPending(H=>{var U;H.channelUrl===o.current.url&&_([H],!1,(U=e.currentUser)==null?void 0:U.userId),L==null||L(H)}).onFileUploaded(()=>{m()}).onSucceeded(H=>{var U;H.channelUrl===o.current.url&&_([H],!1,(U=e.currentUser)==null?void 0:U.userId),K(H)}).onFailed((H,U)=>{var de;U&&U.channelUrl===o.current.url&&_([U],!1,(de=e.currentUser)==null?void 0:de.userId),G(H)})})}),T=ye(async(I,L)=>{var K,G;if(!o.current||!o.current.url)throw(K=s==null?void 0:s.error)==null||K.call(s,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");const N=await o.current.updateUserMessage(I,L);return N.channelUrl===o.current.url&&_([N],!1,(G=e.currentUser)==null?void 0:G.userId),N}),F=ye(async(I,L)=>{var K,G;if(!o.current||!o.current.url)throw(K=s==null?void 0:s.error)==null||K.call(s,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");const N=await o.current.updateFileMessage(I,L);return N.channelUrl===o.current.url&&_([N],!1,(G=e.currentUser)==null?void 0:G.userId),N}),Q=ye(async I=>{var L;if(!o.current||!o.current.url)throw(L=s==null?void 0:s.error)==null||L.call(s,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((N,K)=>{let G;I.isUserMessage()&&(G=o.current.resendMessage(I)),I.isFileMessage()&&(G=o.current.resendMessage(I)),I.isMultipleFilesMessage()&&(G=o.current.resendMessage(I)),G&&("onPending"in G&&G.onPending(H=>{var U;H.channelUrl===o.current.url&&_([H],!1,(U=e.currentUser)==null?void 0:U.userId)}),"onFileUploaded"in G&&G.onFileUploaded(()=>{m()}),"onSucceeded"in G&&G.onSucceeded(H=>{var U;H.channelUrl===o.current.url&&_([H],!1,(U=e.currentUser)==null?void 0:U.userId),N(H)}),"onFailed"in G&&G.onFailed((H,U)=>{var de;U&&U.channelUrl===o.current.url&&_([U],!1,(de=e.currentUser)==null?void 0:de.userId),K(H)}))})}),re=ye(async I=>{var L,N;if(!o.current||!o.current.url)throw(L=s==null?void 0:s.error)==null||L.call(s,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");if(I.sendingStatus==="succeeded")I.isUserMessage()&&await o.current.deleteMessage(I),I.isFileMessage()&&await o.current.deleteMessage(I),I.isMultipleFilesMessage()&&await o.current.deleteMessage(I);else try{await((N=f.current.instance)==null?void 0:N.removeFailedMessage(I.reqId))}finally{A([],[I.reqId])}}),le=ye(()=>{var I;C([],!0,(I=e.currentUser)==null?void 0:I.userId)}),Oe=ye(async I=>{var L;if(e.currentUser&&o.current){const N=to(I);M(!0),_([],!0,(L=e.currentUser)==null?void 0:L.userId),await Y(o.current,I,N),M(!1)}});return{initialized:g,loading:E,refreshing:y,messages:v,newMessages:b,resetNewMessages:le,refresh:P,loadPrevious:V,hasPrevious:B,loadNext:W,hasNext:q,sendUserMessage:ie,sendFileMessage:_e,sendFileMessages:Le,sendMultipleFilesMessage:J,updateUserMessage:T,updateFileMessage:F,resendMessage:Q,deleteMessage:re,resetWithStartingPoint:Oe,_dangerous_reducer_updateMessages:_,_dangerous_reducer_deleteMessages:A}},Ql=(e,t,n)=>{const r=u.useRef(0),o=u.useRef(new Set),s=u.useCallback(d=>{const m={id:r.current+=1,...d};o.current.forEach(f=>{f(m)})},[]),a=u.useCallback(d=>{var f;const m=((f=n==null?void 0:n.collectionCreator)==null?void 0:f.call(n,d))??(t==null?void 0:t.createMessageCollection({...d??{},filter:new Ye.MessageFilter(d)}));if(!m)throw new Error("Group channel is required to create a message collection");return Bl(m,s)},[t,n==null?void 0:n.collectionCreator,s]),l=Jl(e,t,{...n,collectionCreator:a,strictStreamingOrder:!0}),c=u.useCallback(d=>(o.current.add(d),()=>{o.current.delete(d)}),[]);return{...l,subscribeMessageEvents:c}},Mt={DEFAULT_PRIMARY:"#000000",DEFAULT_BOT_MSG_BG:"#ECECEC",WHITE:"#ffffff",BLACK:"#000000"};function Ls(e){return e.length===4?`#${[...e.slice(1)].map(t=>t+t).join("")}`:e}function ec(e){const t=Ls(e);return[parseInt(t.slice(1,3),16),parseInt(t.slice(3,5),16),parseInt(t.slice(5,7),16)]}function tc(e){return`#${e.map(t=>t.toString(16).padStart(2,"0")).join("")}`}function nc(e,t,n){e/=255,t/=255,n/=255;const r=Math.max(e,t,n),o=Math.min(e,t,n),s=r-o;let a=0,l=0;const c=(r+o)/2;return r!==o&&(l=c>.5?s/(2-r-o):s/(r+o)),r===e?a=(t-n)/s+(t<n?6:0):r===t?a=(n-e)/s+2:r===n&&(a=(e-t)/s+4),a/=6,[a,l,c]}function rc(e,t,n){let r,o,s;if(t===0)r=o=s=n;else{const a=function(m,f,g){return g<0&&(g+=1),g>1&&(g-=1),g<.16666666666666666?m+(f-m)*6*g:g<.5?f:g<.6666666666666666?m+(f-m)*(.6666666666666666-g)*6:m},l=n<.5?n*(1+t):n+t-n*t,c=2*n-l;r=a(c,l,e+1/3),o=a(c,l,e),s=a(c,l,e-1/3)}return[Math.round(r*255),Math.round(o*255),Math.round(s*255)]}function zt(e,t,n){const[r,o,s]=ec(e),[a,l,c]=nc(r,o,s),d=Math.max(0,Math.min(1,c*t)),m=Math.max(0,Math.min(1,l*n)),[f,g,E]=rc(a,m,d);return tc([Math.round(f),Math.round(g),Math.round(E)])}function oc(e,t="light"){return{extraDark:zt(e,.6,1.2),dark:zt(e,.85,1.1),main:e,light:zt(e,t==="dark"?1.1:1.5,t==="dark"?.95:.9),extraLight:zt(e,t==="dark"?1.2:1.75,t==="dark"?.9:.8)}}function Wn(e){const t=Ls(e),n=149,r=+`0x${t[1]}${t[2]}`,o=+`0x${t[3]}${t[4]}`,s=+`0x${t[5]}${t[6]}`;return r*.299+o*.587+s*.114>n?Mt.BLACK:Mt.WHITE}function sc(e,t,n,r,o){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:o,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 ic=(e,t,n,r,o)=>({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:o,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"}}),Vt={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 no(e){const t=ac(e),n=lc(e,t),r=uc(n,e.colors,e.selectedTheme),o=mc(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:o}}function ac({selectedTheme:e,palette:t,primary:n}){const r=t!=null&&t.primary?t.primary:n?n===Vt.primary.main?Vt.primary:oc(n,e):Vt.primary;return{...Vt,primary:r,...t}}function lc({selectedTheme:e,primaryContrast:t,botMessageBackground:n,botMessageBackgroundContrast:r},o){const s=o.primary.main,a=t??Wn(s),l=n??Mt.DEFAULT_BOT_MSG_BG,c=r??Wn(l);return(e==="light"?sc:ic)(o,s,a,l,c)}function cc(e,t,n){return typeof e=="string"?e:e[t]??n}function uc(e,t,n){var a;if(!t||Object.keys(t).length===0)return e;const r={...e},o=r,s=e;for(const l of Object.keys(t)){const c=t[l];if(c){o[l]={...o[l]};for(const[d,m]of Object.entries(c))if(m!==void 0){const f=((a=s[l])==null?void 0:a[d])??"";o[l][d]=cc(m,n,f)}}}return r}function dc(e,t,n){const r={...e};return n.forEach(o=>{const s=t[o];s!=null&&(r[o]=s)}),r}function mc({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 o=wn[n],s=["fontSize","fontWeight","fontFamily","lineHeight"];t[n]=dc(o,r,s)}}),t}const{Provider:fc,useContext:fr}=pe("AIAgentTheme");function gc({logger:e,palette:t,typography:n,colors:r,appearance:o,children:s}){const a=u.useRef(null),[l,c]=u.useState(()=>no({selectedTheme:(o==null?void 0:o.theme)??"light",palette:t,typography:n,colors:r,primary:o==null?void 0:o.primaryColor,botMessageBackground:o==null?void 0:o.botMessageBackgroundColor})),d=u.useCallback((m,f)=>{f&&(a.current=f);const g=(o==null?void 0:o.theme)??m,E=a.current?a.current.themes[g]:null,y={primary:o==null?void 0:o.primaryColor,primaryContrast:void 0,botMessageBackground:o==null?void 0:o.botMessageBackgroundColor,botMessageBackgroundContrast:void 0};!y.primary&&(E!=null&&E.primary_color)&&(y.primary=E.primary_color,y.primaryContrast=E.primary_contrast_color),!y.botMessageBackground&&(E!=null&&E.bot_message_bg_color)&&(y.botMessageBackground=E.bot_message_bg_color,y.botMessageBackgroundContrast=E.bot_message_bg_contrast_color);const v=no({selectedTheme:g,palette:t,typography:n,colors:r,...y});c(v),e==null||e.info("theme.update:",g)},[o==null?void 0:o.theme,o==null?void 0:o.primaryColor,o==null?void 0:o.botMessageBackgroundColor,t,n,r,e]);return u.useEffect(()=>{(o!=null&&o.theme||o!=null&&o.primaryColor||o!=null&&o.botMessageBackgroundColor)&&d(l.selectedTheme)},[o==null?void 0:o.theme,o==null?void 0:o.primaryColor,o==null?void 0:o.botMessageBackgroundColor]),i.createElement(fc,{value:{theme:l,updateTheme:d}},s)}const Mn=25*1024*1024,ro=1,oo=new Set(["image/png","image/jpeg","image/jpg"]),so=new Set(["application/pdf"]),hc={off:"off",always:"always",handed_off_only:"handed_off_only"},pc=()=>{const[e,t]=u.useState(()=>({maxAttachmentCount:ro,attachmentMode:"handed_off_only",defaultUploadSizeLimit:Mn,uploadSizeLimitPerType:new Map,supportedImageMimeTypes:oo,supportedFileMimeTypes:so})),n=u.useCallback(({active_channel:o,upload_restriction:s})=>{t({maxAttachmentCount:(s==null?void 0:s.max_attachment_count)??ro,attachmentMode:hc[o.attachment_mode]??"handed_off_only",defaultUploadSizeLimit:(s==null?void 0:s.default_upload_size_limit)??Mn,uploadSizeLimitPerType:new Map(Object.entries((s==null?void 0:s.upload_size_limit_per_type)??[])),supportedImageMimeTypes:new Set((s==null?void 0:s.supported_image_mime_types)??oo),supportedFileMimeTypes:new Set((s==null?void 0:s.supported_file_mime_types)??so)})},[]),r=u.useCallback(o=>{const{channel:s,uploadSizeLimit:a=Mn}=o,l=(d=!0)=>s!=null&&s.isAIAgent?d?nt(s):!1:!0,c=d=>{if(l())return e.defaultUploadSizeLimit??a;const m=e.defaultUploadSizeLimit??a,f=e.uploadSizeLimitPerType.get(d)??m;return Math.min(m,f)};return{maxAttachmentCount:e.maxAttachmentCount,isEnabled:()=>{if(l(!1))return!0;switch(e.attachmentMode){case"off":return!1;case"always":return!0;case"handed_off_only":return nt(s);default:return!0}},get supportedMimeTypes(){return l()?[Hn]:[...e.supportedImageMimeTypes,...e.supportedFileMimeTypes]},isSupportedMimeType:d=>l()?!0:e.supportedImageMimeTypes.has(d)||e.supportedFileMimeTypes.has(d),getUploadSizeLimit:c,getUploadSizeLimitInMB:d=>c(d)/(1024*1024)}},[e]);return{updateBaseAttachmentRules:n,createAttachmentRules:r}},io=(...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)")},vt=e=>({...e,context:e.context??{}}),{Provider:_c,useContext:pt}=pe("AIAgentMessengerSession"),Ec=u.forwardRef(function({userSessionInfo:e,children:t},n){const{_aiAgentSDK:r,chatSDK:o,aiAgentId:s,logger:a}=Re(),{updateTheme:l}=fr(),[c,d]=u.useState(void 0),[m,f]=u.useState(void 0),[g,E]=u.useState(null),[y,v]=u.useState(null),[b,_]=u.useState(null),[C,x]=u.useState(null),[A,w]=u.useState(null),{updateBaseAttachmentRules:M,createAttachmentRules:k}=pc();u.useEffect(()=>{const Y=r.onMessengerSettingsUpdated(({settings:B})=>{const{appearance:W,bot:q,launcher:ie,memory:_e}=B;l(W.selected_theme,W),_(el(q)),x(tl(ie)),w(_e?Vn(_e):null),M(B)}),P=r.onActiveChannelUpdated(({channelUrl:B,status:W,conversationStatus:q})=>{f({url:B,status:W,conversationStatus:q})}),V=r.onAuthTokenRefreshed(()=>{var W;const B=(W=r.session)==null?void 0:W.userSession.authToken;B&&v(q=>q?{...q,authToken:B}:null)});return()=>{Y(),P(),V()}},[r,l,M]);const R=u.useCallback(async()=>{try{const Y=await r.authenticate(e),P=r.session;return E(P.sdkUser),v(P.userSession),f(P.activeChannel),d(void 0),Y}catch(Y){throw E(null),v(null),f(void 0),d(Y),Y}},[r,e]),O=u.useCallback(async()=>{await r.deauthenticate(),E(null),f(void 0),v(null),_(null),x(null),w(null)},[r]),z=u.useCallback(async()=>{if(!r.session){if(y)return a.debug("agentMessengerSession.refreshActiveChannel: stale call after deauthenticate, skipping"),"";throw a.error("agentMessengerSession.refreshActiveChannel: userSession is not ready"),new Error("userSession is not ready")}return r.session.userSession.userId!==(y==null?void 0:y.userId)?(a.debug("agentMessengerSession.refreshActiveChannel: stale call from previous session, skipping"),r.session.activeChannel.url):(f(void 0),await r.refreshActiveChannel())},[r,a,y]);return u.useImperativeHandle(n,()=>{const Y=async()=>{if(!m)throw new Error("No active conversation. Please start a conversation first.");return await o.groupChannel.getChannel(m.url)};return{activeChannel:m,chatSDK:o,authenticate:R,deauthenticate:O,updateContext:async(...P)=>{const V=io(...P);if(V.type==="active"){const q=await(await Y()).updateContext(s,V.context);return vt(q)}const B=await o.aiAgent.updateContext(V.aiAgentId,V.channelUrl,V.context);return vt(B)},patchContext:async(...P)=>{const V=io(...P);if(V.type==="active"){const q=await(await Y()).patchContext(s,V.context);return vt(q)}const B=await o.aiAgent.patchContext(V.aiAgentId,V.channelUrl,V.context);return vt(B)},getContextObject:async()=>{const V=await(await Y()).getContextObject(s);return vt(V)}}},[R,O,m,o,s,a]),i.createElement(_c,{value:{sdkUser:g,userSessionInfo:e,userSession:y,activeChannel:m,setActiveChannel:f,refreshActiveChannel:z,createConversation:r.createConversation,searchConversation:r.searchConversation,connectionError:c,aiAgentInfo:b,launcherInfo:C,memoryInfo:A,authenticate:R,deauthenticate:O,createAttachmentRules:k,statsTrackers:r.statsTrackers}},t)}),Ot=(e,t)=>{const n=u.useId(),r=u.useRef(t);u.useLayoutEffect(()=>{r.current=t}),u.useLayoutEffect(()=>{const o=new ue.ConnectionHandler({onDisconnected:s=>{var a,l;return(l=(a=r.current).onDisconnected)==null?void 0:l.call(a,s)},onConnected:s=>{var a,l;return(l=(a=r.current).onConnected)==null?void 0:l.call(a,s)},onReconnectStarted:()=>{var s,a;return(a=(s=r.current).onReconnectStarted)==null?void 0:a.call(s)},onReconnectSucceeded:()=>{var s,a;return(a=(s=r.current).onReconnectSucceeded)==null?void 0:a.call(s)},onReconnectFailed:()=>{var s,a;return(a=(s=r.current).onReconnectFailed)==null?void 0:a.call(s)},onConnectionLost:()=>{var s,a;return(a=(s=r.current).onConnectionLost)==null?void 0:a.call(s)},onConnectionDelayed:s=>{var a,l;return(l=(a=r.current).onConnectionDelayed)==null?void 0:l.call(a,s)}});return e.addConnectionHandler(n,o),()=>{e.removeConnectionHandler(n)}},[e,n])};function bc(e){const{chatSDK:t,logger:n,aiAgentId:r,_aiAgentSDK:o}=Re(),{sdkUser:s,statsTrackers:a}=pt(),l=gn(),[c,d]=u.useState(void 0),[m,f]=u.useState(void 0),[g,E]=u.useState(!1);function y(b){b.isAIAgent&&!b.conversation&&(E(!0),o.initConversationIfNeeded(b).finally(()=>E(!1)))}async function v(){var b,_,C;if(!s){n.debug("useChannel.getChannel: no sdk user, skip fetching channel");return}if(n.debug("useChannel.getChannel: start"),d(void 0),f(void 0),E(!1),e){a.initialRender.onGetChannelStart();try{n.debug("useChannel.getChannel: get channel",e);const x=await t.groupChannel.getChannel(e);y(x),d(x),a.initialRender.onGetChannelComplete((b=x.conversation)==null?void 0:b.id),x.url===((_=o.session)==null?void 0:_.activeChannel.url)&&o.session._updateActiveChannel({url:x.url,status:Ne(x)?"closed":"open",conversationStatus:(C=x.conversation)==null?void 0:C.status}),n.debug("useChannel.getChannel: fetched channel",x)}catch(x){a.initialRender.onGetChannelError(x),x instanceof ue.SendbirdError&&f(x),n.error("useChannel.getChannel: error",x)}}}return u.useEffect(()=>{v()},[t,s,e,r]),Ot(t,{async onReconnectSucceeded(){if(!c)return;const b=await c.refresh();y(b),d(b)}}),ht(t,{onChannelChanged:b=>{b.isGroupChannel()&&b.url===e&&(n.debug("useChannel.onChannelChanged: channel changed",b.url),d(b),l())}}),{channel:c,channelFetchError:m,getChannel:v,isInitializingConversation:g}}const Cc=new Set(["suggested_replies","steward","system"]),vc=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||!Cc.has(r)))return r},yc=e=>{var a;const t=e==null?void 0:e.lastMessage;if(!t||!e)return!1;const n=t.extendedMessagePayload,r=n==null?void 0:n.form,o=!!r&&!r.submitted_at&&!r.canceled_at,s=e.isAIAgent&&!!((a=e.conversation)!=null&&a.handedOverAt);return o&&!s},Sc=()=>{const{chatSDK:e,networkStateAdapter:t}=Re(),[n,r]=u.useState(()=>t?t.isOnline()?"connected":"reconnecting":"connected");return Ot(e,{onConnected:()=>r("connected"),onDisconnected:()=>r("disconnected"),onReconnectStarted:()=>r("reconnecting"),onReconnectSucceeded:()=>r("connected"),onReconnectFailed:()=>r("disconnected"),onConnectionLost:()=>r("reconnecting")}),u.useEffect(()=>{if(t)return t.subscribe(o=>{if(!o){r("reconnecting");return}r(s=>s==="reconnecting"&&e.connectionState===ue.ConnectionState.OPEN?"connected":s)})},[t,e]),n},Ac=3e4,xc=({shouldApply:e,lastMessage:t,isBlockedWhileAIResponding:n,currentUserId:r})=>{const[o,s]=u.useState(!1),a=u.useRef(null),l=t&>(t,r)?t.createdAt:0;return u.useEffect(()=>{const c=()=>{a.current&&(clearTimeout(a.current),a.current=null),s(!1)},d=g=>{a.current&&clearTimeout(a.current),s(!0),a.current=setTimeout(()=>{s(!1),a.current=null},g)},m=Date.now()-l,f=Ac-m;return n||f<=0?c():d(f),()=>{a.current&&clearTimeout(a.current)}},[n,l]),o&&e},Os=e=>{const{chatSDK:t}=Re(),[n,r]=u.useState([]);return ht(t,{onTypingStatusUpdated(o){if(o.url===(e==null?void 0:e.url)){const s=o.getTypingUsers();r(s)}}}),n},Tc=({channel:e,lastMessage:t,aiAgentUserId:n,isStreamAnimating:r})=>{const[o,s]=u.useState(!1),a=Os(e);return u.useEffect(()=>{if(!t)return;const l=a.some(d=>d.userId===n),c=gt(t,n)&&(We.isStreaming(t)||r);s(c||l)},[a,t,n,r]),o},Ic=({channel:e,messages:t,isStreamAnimating:n,isInitializingConversation:r})=>{const{aiAgentInfo:o,userSession:s}=pt(),a=Sc(),l=Tc({channel:e,lastMessage:Gr(t,[He.SendingStatus.SUCCEEDED]),aiAgentUserId:(o==null?void 0:o.userId)??"",isStreamAnimating:n}),c=xc({shouldApply:!!(e!=null&&e.isAIAgent)&&!nt(e),isBlockedWhileAIResponding:l,lastMessage:Gr(t,[He.SendingStatus.PENDING,He.SendingStatus.SUCCEEDED]),currentUserId:(s==null?void 0:s.userId)??""}),d=f=>f===""?{disabled:!1,disabledBy:"",focusPolicy:"auto"}:f==="ai_responding"?{disabled:!0,disabledBy:f,focusPolicy:"preserve"}:{disabled:!0,disabledBy:f,focusPolicy:"release"};if(!e||a==="disconnected")return d("unavailable");if(a==="reconnecting")return d("reconnecting");if(Ne(e))return d("conversation_closed");if(nl(e))return d("handoff_pending");if(yc(e))return d("form_active");const m=vc(e);return d(m||(l||c||r?"ai_responding":""))},wc=()=>{const[e,t]=u.useState(new Set),n=u.useCallback(o=>{t(s=>{if(s.has(o))return s;const a=new Set(s);return a.add(o),a})},[]),r=u.useCallback(o=>{t(s=>{if(!s.has(o))return s;const a=new Set(s);return a.delete(o),a})},[]);return{isAnimating:e.size>0,start:n,stop:r}},{Provider:Mc}=pe("AIAgentConversation");function kc({children:e,channelUrl:t,onChannelDeleted:n,onMessagesReceived:r,onMessagesUpdated:o,onConversationClosedStatusChanged:s,onConversationClosedViaDispatcher:a,onBeforeSendMessage:l,onAfterSendMessage:c=ce,shouldMarkAsRead:d=!0,shouldCountNewMessages:m=()=>!1,sortComparator:f}){var Y;const g=()=>d&&(_==null?void 0:_.markAsRead()),{_aiAgentSDK:E,chatSDK:y,logger:v,dispatcher:b}=Re(),{channel:_,channelFetchError:C,getChannel:x,isInitializingConversation:A}=bc(t),{statsTrackers:w}=pt();u.useEffect(()=>{if(t)return w.initialRender.setChannelUrl(t),()=>{w.initialRender.cleanup()}},[t,w]);const M=Ql(y,_,{replyType:He.ReplyType.ONLY_REPLY_TO_CHANNEL,shouldCountNewMessages:m,onChannelDeleted:n,onMessagesReceived:P=>r==null?void 0:r(P),onMessagesUpdated:P=>o==null?void 0:o(P),onCacheResult:P=>w.initialRender.onCacheResult(P),onApiResult:P=>w.initialRender.onApiResult(P),logger:v,markAsRead:g,sortComparator:f}),k=wc(),R=Ic({channel:_,messages:M.messages,isStreamAnimating:k.isAnimating,isInitializingConversation:A});u.useEffect(()=>{g()},[d,_]);const O=Ne(_);u.useEffect(()=>{s==null||s(O)},[O,s]),u.useEffect(()=>{const P=async V=>{const B=typeof(V==null?void 0:V.channelUrl)=="string";_&&B&&V.channelUrl!==_.url||(v.debug("conversation.dispatcher: try to close conversation",_),_!=null&&_.conversation&&_.conversation.status===Ee.ConversationStatus.OPEN&&(await _.closeConversation(),a==null||a()))};return b.subscribe(Be.ConversationClose,P),()=>{b.unsubscribe(Be.ConversationClose,P)}},[b,_,v,(Y=_==null?void 0:_.conversation)==null?void 0:Y.status,a]);const z={conversation:(_==null?void 0:_.conversation)??void 0,actions:{setUserMemoryState:E.setUserMemoryState},channelSource:{channel:_,error:C,refetch:()=>x(),closeConversation:async()=>{Ne(_)||await(_==null?void 0:_.closeConversation())}},messageSource:{messages:M.messages,newMessages:M.newMessages,initialized:M.initialized,subscribeMessageEvents:M.subscribeMessageEvents,loadPrevious:()=>M.loadPrevious(),loadNext:()=>M.loadNext(),deleteMessage:P=>M.deleteMessage(P),resendMessage:P=>M.resendMessage(P),resetNewMessages:()=>M.resetNewMessages(),sendUserMessage:async P=>{var B;if(((B=_==null?void 0:_.conversation)==null?void 0:B.status)===Ee.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(P=await l(P));const V=await M.sendUserMessage(P,c);return c==null||c(V),V},sendFileMessage:async P=>{var B;if(((B=_==null?void 0:_.conversation)==null?void 0:B.status)===Ee.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(P=await l(P));const V=await M.sendFileMessage(P,c);return c==null||c(V),V},sendMultipleFilesMessage:async P=>{var B;if(((B=_==null?void 0:_.conversation)==null?void 0:B.status)===Ee.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(P=await l(P));const V=await M.sendMultipleFilesMessage(P,c);return c==null||c(V),V}},state:{streamAnimation:k,input:R}};return i.createElement(Mc,{value:z},e)}function Rc(e,t){var E,y,v,b,_,C,x,A,w,M;const[n,r]=u.useState(!1),[o,s]=u.useState(null),[a,l]=u.useState([]),[c,d]=u.useState(null),m=u.useRef(!1),f=u.useCallback(async()=>{if(!m.current&&e.currentUser){m.current=!0,r(!1),s(null),l([]);try{c==null||c.dispose();const k=new _s(e,t);k.setConversationListCollectionHandler({onChannelsAdded:()=>{l(k.channels)},onChannelsUpdated:()=>{l(k.channels)},onChannelsDeleted:()=>{l(k.channels)}}),await k.loadMore(),l(k.channels),d(k),s(null)}catch(k){d(null),s(k)}finally{r(!0),m.current=!1}}},[e,e.currentUser,(E=t.filter)==null?void 0:E.aiAgentChannelFilter,(v=(y=t.filter)==null?void 0:y.aiAgentConversationStatusFilter)==null?void 0:v.join(),(_=(b=t.filter)==null?void 0:b.aiAgentIds)==null?void 0:_.join(),(C=t.filter)==null?void 0:C.deskChannelFilter,(A=(x=t.filter)==null?void 0:x.pinnedChannelUrls)==null?void 0:A.join(),(w=t.filter)==null?void 0:w.copilotConversationOnly,(M=t.filter)==null?void 0:M.copilotSupportChannelUrl,t.limit]),g=u.useCallback(async()=>{if(c)try{await c.loadMore(),l(c.channels)}catch(k){s(k)}},[c]);return Ot(e,{onConnected:()=>f()}),u.useEffect(()=>{f()},[f]),u.useEffect(()=>()=>{m.current=!1,c==null||c.dispose()},[c]),{initialized:n,error:o,channels:a,loadMore:g}}const Ns=e=>{var o;const{aiAgentId:t,queryParams:n}=Re(),r=(o=n==null?void 0:n.conversationListParams)==null?void 0:o.filter;return{aiAgentIds:[t],aiAgentConversationStatusFilter:[Ee.ConversationStatus.CLOSED,Ee.ConversationStatus.OPEN],...r,...e}},{Provider:Lc}=pe("AIAgentConversationList");function Oc({conversationListLimit:e,conversationListFilter:t,children:n}){var d;const{chatSDK:r,queryParams:o}=Re(),s=e??((d=o==null?void 0:o.conversationListParams)==null?void 0:d.limit),a=Ns(t),l=Rc(r,{limit:s,filter:a}),c={listSource:{initialized:l.initialized,error:l.error??void 0,channels:l.channels,loadMore:()=>l.loadMore()}};return i.createElement(Lc,{value:c},n)}function Nc(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:Dc,useContext:$c}=pe("MessageTemplateFetching");function Pc({children:e,internalVariables:t}){const n=u.useRef({}),r=u.useRef({}),[o,s]=u.useState({}),a=u.useCallback((d,m)=>{s(f=>({...f,[d]:{fetching:!1,error:!1,...f[d],...m}}))},[]),l=u.useCallback(async({onRequestTemplate:d,onGetCachedTemplate:m,templateKey:f,suspense:g=!1})=>{const E=m(f);if(E)return E;const y=r.current[f];if(y)return y;g||a(f,{fetching:!0});const v=d(f).catch(b=>{throw g||a(f,{error:!0}),b}).finally(()=>{g||a(f,{fetching:!1}),delete r.current[f]});return r.current[f]=v,v},[a]),c={internalVariables:t,fetchTemplate:l,suspend:(d,m)=>{if(n.current[d])return n.current[d];const f=Nc(m());return n.current[d]=f,f},getIsFetching:d=>{var m;return((m=o[d])==null?void 0:m.fetching)??!1},getHasError:d=>{var m;return((m=o[d])==null?void 0:m.error)??!1}};return i.createElement(Dc,{value:c},e)}const Fc="remove_powered_by",gr=(e,t)=>{var o,s;const{chatSDK:n}=Re(),{aiAgentInfo:r}=pt();if(e==="handoff-button"){const a=!!((o=t==null?void 0:t.conversation)!=null&&o.handoff);return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.showHandoffButton)&&a&&ar(t)}if(e==="special-notice")return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.specialNoticeEnabled)&&!!(r!=null&&r.specialNotice);if(e==="powered-by"){const a=(s=n==null?void 0:n.appInfo)==null?void 0:s.applicationAttributes;return u.useMemo(()=>!(Array.isArray(a)&&a.includes(Fc)),[a])}throw new Error("Unsupported feature")},Uc={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"},Bc={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:o}=e;if(o){if(o.min_length!==void 0&&r.length<o.min_length)return{isValid:!1,error:typeof n.minLength=="function"?n.minLength(o.min_length):n.minLength};if(o.max_length!==void 0&&r.length>o.max_length)return{isValid:!1,error:typeof n.maxLength=="function"?n.maxLength(o.max_length):n.maxLength};if(o.regex&&!new RegExp(o.regex).test(r))return{isValid:!1,error:n.regex}}return{isValid:!0}}},Hc={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:o}=e;if(o){if(o.min!==void 0&&r<o.min)return{isValid:!1,error:typeof n.min=="function"?n.min(o.min):n.min};if(o.max!==void 0&&r>o.max)return{isValid:!1,error:typeof n.max=="function"?n.max(o.max):n.max}}return{isValid:!0}}},Gc={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}}},zc={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(a=>!e.options.includes(a)).length>0)return{isValid:!1,error:n.invalidSelection};const{rules:s}=e;if(s){if(s.min_select!==void 0&&r.length<s.min_select)return{isValid:!1,error:typeof n.minSelect=="function"?n.minSelect(s.min_select):n.minSelect};if(s.max_select!==void 0&&r.length>s.max_select)return{isValid:!1,error:typeof n.maxSelect=="function"?n.maxSelect(s.max_select):n.maxSelect}}return{isValid:!0}}},Vc={text:Bc,number:Hc,"single-select":Gc,"multi-select":zc},Yc={getValueOrDefault:()=>null,validate:()=>({isValid:!1})};function Ds(e){return Vc[e.type]||Yc}function ao(e){return Ds(e).getValueOrDefault(e)}function Wc(e,t,n={}){const r={...Uc,...n};return Ds(e).validate(e,t,r)}const qc=(e,t={})=>{const{labels:n={},onSubmit:r,onCancel:o}=t,[s,a]=u.useState({}),[l,c]=u.useState(()=>{const v={};return e.fields.forEach(b=>{v[b.key]=ao(b)}),v}),d=u.useMemo(()=>e.submitted_at?"submitted":e.canceled_at?"canceled":"draft",[e.submitted_at,e.canceled_at]);u.useEffect(()=>{if(d==="submitted"||d==="canceled"){const v={};let b=!1;e.fields.forEach(_=>{const C=ao(_);JSON.stringify(l[_.key])!==JSON.stringify(C)&&(b=!0),v[_.key]=C}),b&&c(v)}},[d]);const m=(v,b)=>{c(_=>({..._,[v]:b})),a(_=>({..._,[v]:void 0}))},f=e.fields.map(v=>{var C,x,A;const b=l[v.key]??null,_={key:v.key,label:v.label,error:s[v.key],required:v.required};return v.type==="text"?{..._,type:"text",layout:v.layout,value:b,...v.placeholder&&{placeholder:v.placeholder},...((C=v.rules)==null?void 0:C.max_length)&&{maxLength:v.rules.max_length}}:v.type==="number"?{..._,type:"number",layout:v.layout,value:b,...v.placeholder&&{placeholder:v.placeholder},...((x=v.rules)==null?void 0:x.max)&&{max:v.rules.max}}:v.type==="single-select"?{..._,type:"single-select",layout:v.layout,value:b,options:v.options}:v.type==="multi-select"?{..._,type:"multi-select",layout:v.layout,value:b,options:v.options,...((A=v.rules)==null?void 0:A.max_select)&&{maxSelect:v.rules.max_select}}:{..._,type:"unknown",layout:"default",value:null}});return{state:d,fields:f,getField:v=>f.find(b=>b.key===v),updateFieldValue:m,submit:async()=>{const v={};let b=!1;for(const _ of e.fields){const C=l[_.key]??null,x=Wc(_,C,n);x.isValid||(v[_.key]=x.error,b=!0)}if(a(v),!b&&r){const _={};e.fields.forEach(C=>{_[C.key]=l[C.key]??null}),await r(_)}},cancel:async()=>{await(o==null?void 0:o())}}},Kc=e=>{const{chatSDK:t,handlers:n,logger:r}=Re(),{aiAgentInfo:o}=pt(),s=u.useRef(new Set),a=u.useRef(new Set),l=(m,f)=>{if(!(n!=null&&n.onCustomEvent)||!(o!=null&&o.userId)||!gt(m,o.userId))return;const g=m.messageId;if(We.isStreaming(m)){a.current.add(g);return}f==="updated"&&!a.current.has(g)||(r.debug("useCustomEventForMessageReceive: bot-message-received",m),n.onCustomEvent({type:"bot-message-received",data:{message:m}}),a.current.delete(g))},c=u.useCallback(m=>{if(n!=null&&n.onCustomEvent&&m.isAdminMessage()&&m.customType==="user_action_required"&&!s.current.has(m.messageId)){const f=Gn(m.data);Array.isArray(f.history)&&f.history.length===0&&(r.debug("useCustomEventForMessageReceive: user_action_required",f),n.onCustomEvent({type:"user-action-requested",data:f}),s.current.add(m.messageId))}},[n,r]),d=(m,f,g)=>{m.url===e&&(l(f,g),c(f))};return ht(t,{onMessageReceived:(m,f)=>d(m,f,"received"),onMessageUpdated:(m,f)=>d(m,f,"updated")}),{checkForUserActionRequired:c}},jc=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},$s=e=>{const{aiAgentInfo:t}=pt(),n=Os(e);if(Ne(e))return null;const r=n[0];if(!r)return null;const o=r.userId===(t==null?void 0:t.userId),s=o?jc(r.metaData):void 0;return{user:o?t:r,isBot:o,thinkingMessage:s}},Xc=(e,t,{enabled:n=!0,idleMs:r=1e3}={})=>{const o=u.useRef(null),s=u.useRef(t),a=u.useRef(t),l=u.useRef(!1);s.current=t,u.useEffect(()=>{if(o.current&&(clearTimeout(o.current),o.current=null),!n||!e){(l.current?a.current:s.current)(!1),l.current=!1,a.current=s.current;return}l.current=!0,a.current=s.current,a.current(!0),o.current=setTimeout(()=>{o.current=null,a.current(!1),l.current=!1,a.current=s.current},r)},[n,r,e]),u.useEffect(()=>()=>{o.current&&(clearTimeout(o.current),o.current=null),(l.current?a.current:s.current)(!1),l.current=!1,a.current=s.current},[])},Zc=(e=1e4)=>{const t=new Map;let n=e;return{shouldAnnounce:l=>{const c=Date.now(),d=t.get(l);return d!==void 0&&c-d<n?!1:(t.set(l,c),!0)},setInterval:l=>{n=l},reset:()=>{t.clear()}}},Jc=(e,t,n=1e4,r=!0)=>{const o=u.useRef(null),s=u.useRef(null),a=u.useRef(!1);o.current||(o.current=Zc(n));const l=(e==null?void 0:e.nickname.trim())||null,c=(e==null?void 0:e.userId)??l;u.useEffect(()=>{var d;(d=o.current)==null||d.setInterval(n)},[n]),u.useEffect(()=>{var f;if(!r){a.current=!1,s.current=c;return}if(!c||!l){a.current=!1,s.current=null;return}const d=!a.current,m=s.current!==c;a.current=!0,s.current=c,!(!d&&!m)&&(f=o.current)!=null&&f.shouldAnnounce(c)&&t(l)},[c,l,r,t])},Qc=({csat:e,csatPayload:t,isRenderableCSAT:n,isExpiredNow:r,announceStatus:o,onSubmittedAnnounced:s})=>{const a=(t==null?void 0:t.csat_submitted_label)??"",l=u.useRef(n&&typeof e=="number"),c=u.useRef(n&&r);u.useEffect(()=>{n&&a&&(typeof e!="number"||l.current||(l.current=!0,o&&(o({event:"csatSubmitted",submittedLabel:a}),s==null||s())))},[o,e,n,s,a]),u.useEffect(()=>{n&&r&&(c.current||(c.current=!0,o==null||o({event:"csatExpired"})))},[o,r,n])},hr=({channel:e,userSession:t,aiAgentInfo:n})=>{if(!t||!n||!e)return{fallbackIcon:"delight",url:void 0,title:""};const r=ys(e,t.userId),o={ai(s){return{fallbackIcon:s,url:n.profileUrl,title:n.nickname}},human(s){return{fallbackIcon:s,url:r==null?void 0:r.profileUrl,title:(r==null?void 0:r.nickname)||n.nickname}},channel(s){return{fallbackIcon:s,url:e==null?void 0:e.coverUrl,title:(e==null?void 0:e.name)??""}}};return e.isAIAgent?nt(e)?o.human("agent"):o.ai("delight"):e.isDesk?o.human("agent"):o.channel("user")},lo=e=>u.useReducer((t,n)=>({...t,...n}),e);var qe=(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))(qe||{});const eu=new Set(["free_text","single_choice"]),tu=({csatPayload:e,type:t,initialCsat:n,initialCsatReason:r,initialIsResolved:o})=>{const[s,a]=lo({csatType:t,csat:n,csatReason:r,isResolved:o}),[l,c]=lo({followUpItem:!1}),d=u.useMemo(()=>{var b;const E=s.csat,y=typeof E=="number",v=(b=e.follow_up)==null?void 0:b.find(_=>y?_.scores.includes(E):_.always_visible??!1);if(eu.has(v==null?void 0:v.response_type))return v},[s.csat,e.follow_up]),m=(()=>{var E;if(typeof n=="number")return"submitted";if((t===qe.AI_AGENT_CSAT_5||t===qe.HELPDESK_CSAT_5)&&typeof s.csat=="number")return"submittable";if(t===qe.AI_AGENT_CSAT_5_WITH_CRE){const y=typeof s.csat=="number",v=!((E=e.cre)!=null&&E.required)||typeof s.isResolved=="boolean";if(y&&v)return"submittable"}return"unsubmittable"})(),f=u.useCallback(()=>typeof s.csat>"u"?!1:d!=null&&d.required&&!s.csatReason?(c({followUpItem:!0}),!1):!0,[s,d,c]);return u.useEffect(()=>{r||(a({csatReason:""}),c({followUpItem:!1}))},[r,d,a,c]),{params:s,setParams:a,error:l,setError:c,followUpItem:d,state:m,validateParams:f,itemProps:{csatPayload:e,state:m,submitted:m==="submitted"}}},nu=({csat:e,csatExpireAt:t,csatPayload:n,isSubmitInFlight:r=!1})=>{const o=!!n&&n.visibility&&!!qe[n.type],s=!r&&typeof e!="number"&&Ss(t),a=gn();return u.useEffect(()=>{if(!o||typeof e=="number"||t==null||s)return;const l=t-Date.now();if(l<=0&&r)return;const c=setTimeout(a,Math.max(0,l));return()=>clearTimeout(c)},[a,e,t,s,o,r]),{isRenderableCSAT:o,isExpiredNow:s}},kn=5,ru=250,ou=50,co=e=>Math.max(0,e-ou),su=e=>e<1e3?{speed:kn*.5,chunkSize:2}:e<2e3?{speed:kn*.8,chunkSize:2}:{speed:kn*.6,chunkSize:3},Zt=(e,t)=>{let n=0;for(let r=t-1;r>=0&&e[r]==="\\";r--)n++;return n%2===1},uo=(e,t,n,r)=>{let o=1,s=t;for(;s<e.length&&o>0;){if(Zt(e,s)){s++;continue}e[s]===n?o++:e[s]===r&&o--,s++}return o>0?-1:s},iu=(e,{hideImages:t,hideLinks:n})=>{let r="",o=0,s=0;for(;o<e.length;){if(e[o]==="`"&&!Zt(e,o)){let f=1;for(;e[o+f]==="`";)f++;s===0?s=f:f===s&&(s=0),r+=e.slice(o,o+f),o+=f;continue}const a=e[o]==="!"&&e[o+1]==="["&&!Zt(e,o),l=e[o]==="["&&!Zt(e,o);if(s>0||!a&&!l){r+=e[o],o++;continue}if(a?!t:!n){const f=a?"![":"[";r+=f,o+=f.length;continue}const c=o,d=uo(e,o+(a?2:1),"[","]");if(d===-1)return r;if(o=d,e[o]!=="("){r+=e.slice(c,o);continue}const m=uo(e,o+1,"(",")");if(m===-1)return r;o=m,r+=e.slice(c,o)}return r},au=e=>{const{text:t,enabled:n=!1,deferredMarkdownElements:r=[],onAnimationStart:o,onAnimationProgress:s,onAnimationComplete:a}=e,[l,c]=u.useState(()=>co(t.length)),d=u.useRef(null),m=u.useRef({startTime:0,lastUpdate:0,lastProgressCall:0}).current,f=u.useRef({onStart:o,onProgress:s,onComplete:a}).current,g=u.useRef({startCalled:!1,completeCalled:!1}).current,E=u.useRef({initialEnabled:n,textLength:t.length,enabled:n}).current,y=n,v=l<t.length,b=E.initialEnabled&&(y||v);u.useLayoutEffect(()=>{f.onStart=o,f.onProgress=s,f.onComplete=a,E.textLength=t.length,E.enabled=n}),u.useLayoutEffect(()=>{var A;E.initialEnabled&&(g.startCalled||(g.startCalled=!0,(A=f.onStart)==null||A.call(f)),c(w=>t.length<w?t.length:w))},[t]),u.useEffect(()=>{if(!E.initialEnabled)return;let A=co(t.length);m.lastUpdate=0,m.startTime=0,m.lastProgressCall=0;const w=M=>{var B;m.lastUpdate===0&&(m.lastUpdate=M,m.startTime=M,m.lastProgressCall=M);const k=E.textLength,R=M-m.lastUpdate,O=M-m.startTime,{speed:z,chunkSize:Y}=su(O),P=z*Y;R>=P&&A<k&&(A=Math.min(A+Y,k),c(A),m.lastUpdate=M),M-m.lastProgressCall>=ru&&(m.lastProgressCall=M,(B=f.onProgress)==null||B.call(f)),(A<k||E.enabled)&&(d.current=requestAnimationFrame(w))};return d.current=requestAnimationFrame(w),()=>{var M;d.current&&cancelAnimationFrame(d.current),g.startCalled&&!g.completeCalled&&(g.completeCalled=!0,(M=f.onComplete)==null||M.call(f))}},[]),u.useEffect(()=>{var k;const A=E.initialEnabled&&g.startCalled,w=!n,M=l>=t.length&&t.length>0;A&&w&&M&&!g.completeCalled&&(g.completeCalled=!0,(k=f.onComplete)==null||k.call(f))},[n,l,t.length]);const _=r.includes("image"),C=r.includes("link");return{streamText:u.useMemo(()=>{const A=E.initialEnabled?t.slice(0,l):t,w=b&&_,M=b&&C;return!w&&!M?A:iu(A,{hideImages:w,hideLinks:M})},[t,l,_,C,b]),isAnimating:b}},mo={visible:!1,remainingTime:0,showDescription:!1,targetTimeMs:null},lu=e=>({visible:!0,remainingTime:e,showDescription:!0,targetTimeMs:Date.now()+e*1e3}),cu=(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}},uu=()=>{const{chatSDK:e}=Re(),[t,n]=u.useState(mo),r=()=>n(mo);return Ot(e,{onConnectionDelayed:o=>{o>0?n(lu(o)):r()},onReconnectSucceeded:r,onConnected:r}),u.useEffect(()=>{if(!t.visible||!t.showDescription||t.targetTimeMs==null)return;const o=setTimeout(()=>{n(s=>cu(s))},1e3);return()=>clearTimeout(o)},[t.visible,t.showDescription,t.targetTimeMs,t.remainingTime]),{visible:t.visible,remainingTime:t.remainingTime,showDescription:t.showDescription}},du=e=>{const t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`},mu=(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)}},fu=(e,{enabled:t=!0,opened:n=!1,filter:r}={})=>{var c,d,m;const[o,s]=u.useState(!1),a=u.useRef(0),l=()=>{if(!t)return;const f=++a.current;e.aiAgent.getUnreadMessageCount(r).then(g=>{f===a.current&&s(g.total>0)}).catch(()=>{})};return u.useEffect(()=>{if(!t){s(!1),a.current++;return}e.connectionState===ue.ConnectionState.OPEN&&l()},[t,e,r==null?void 0:r.aiAgentChannelFilter,(c=r==null?void 0:r.aiAgentConversationStatusFilter)==null?void 0:c.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]),u.useEffect(()=>{n&&(s(!1),a.current++)},[n]),Ot(e,{onConnected:l,onReconnectSucceeded:l}),o},pr=e=>e.replace(/\s+/g," ").trim(),gu="Code block",Ps=e=>`A11Y_INLINE_CODE_${e}`,Fs=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}},Us=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}},hu=e=>{const{blockquotePrefix:t,content:n}=Fs(e),{content:r}=Us(n),o=r.match(/^[ \t]{0,3}([`~]{3,})(.*)$/);if(!o)return;const s=o[1],a=o[2],l=s[0];if(!(l!=="`"&&l!=="~"||!s.split("").every(c=>c===l))&&!(l==="`"&&a.includes("`")))return{char:l,blockquotePrefix:t,length:s.length}},pu=(e,t)=>{const{blockquotePrefix:n,content:r}=Fs(e);if(n!==t.blockquotePrefix)return!1;const{content:o,hasListPrefix:s}=Us(r);if(s)return!1;const a=o.match(/^[ \t]{0,3}([`~]{3,})[ \t]*$/);if(!a)return!1;const l=a[1];return l[0]===t.char&&l.length>=t.length&&l.split("").every(c=>c===t.char)},_u=(e,t,n)=>{let r=n;for(;r<e.length;){const o=e[r];if(o==="\\"&&r+1<e.length){r+=2;continue}if(o===t)return r;r+=1}return-1},Eu=(e,t)=>{let n=1,r=t;for(;r<e.length;){const o=e[r];if(o==="\\"&&r+1<e.length){r+=2;continue}if(o==="["){n+=1,r+=1;continue}if(o==="]"&&(n-=1,n===0))return r;r+=1}return-1},bu=(e,t)=>{let n=t,r=1,o,s=!1,a=!1;for(;n<e.length&&r>0;){const l=e[n];if(l==="\\"&&n+1<e.length){n+=2;continue}if(o){l===o&&(o=void 0),n+=1;continue}if(r===1&&s&&/\s/.test(l)){a=!0,n+=1;continue}if(r===1&&a&&(l==='"'||l==="'")){o=l,n+=1;continue}if(l==="("){r+=1,s=!0,n+=1;continue}if(l===")"){r-=1,n+=1;continue}/\s/.test(l)||(s=!0),n+=1}return r===0?n:-1},Cu=e=>{let t=0,n="";for(;t<e.length;){const r=_u(e,"[",t);if(r===-1){n+=e.slice(t);break}const o=Eu(e,r+1);if(o===-1){n+=e.slice(t);break}if(r>0&&e[r-1]==="!"&&sn(e,r-1)){n+=e.slice(t,o+1),t=o+1;continue}if(e[o+1]!=="("){n+=e.slice(t,o+1),t=o+1;continue}const s=r>0&&e[r-1]==="!"&&!sn(e,r-1)?r-1:r;n+=e.slice(t,s);const a=e.slice(r+1,o),l=bu(e,o+2);if(l===-1){n+=e.slice(s);break}n+=a,t=l}return n},Bs=(e,t,n)=>{if(!/^\d+$/.test(t))return!1;const r=e.slice(-1);return/\d/.test(r)&&/\d/.test(n)},vu=e=>e.replace(/(^|[^*\\])\*\*([^\s*](?:[\s\S]*?[^\s*])?)\*\*(?!\*)/g,(t,n,r,o,s)=>{const a=s[o+t.length]??"";return Bs(n,r,a)?t:`${n}${r}`}),yu=e=>e.replace(/(^|[^_\\])__([^\s_](?:[\s\S]*?[^\s_])?)__(?!_)/g,"$1$2"),Su=e=>e.replace(/(^|[^~\\])~~([^\s~](?:[\s\S]*?[^\s~])?)~~(?!~)/g,"$1$2"),Au=e=>{let t=e;return t=t.replace(/(^|[^*\\])\*([^\s*](?:[\s\S]*?[^\s*])?)\*(?!\*)/g,(n,r,o,s,a)=>{const l=a[s+n.length]??"";return Bs(r,o,l)?n:`${r}${o}`}),t=t.replace(/(^|[\s([{"'])_([^_\s](?:[\s\S]*?[^_\s])?)_(?=$|[\s)\]}"'.,!?:;])/g,"$1$2"),t},xu=e=>e.replace(/\\([\\`*_[\]()#+.!~|-])/g,"$1"),Tu=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},fo=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))},go=e=>{const t=[];let n="",r=!1;for(const s of e.trim()){if(r){n+=s==="|"?"|":`\\${s}`,r=!1;continue}if(s==="\\"){r=!0;continue}if(s==="|"){const a=n.trim();a&&t.push(a),n="";continue}n+=s}r&&(n+="\\");const o=n.trim();return o&&t.push(o),t},Iu=e=>{const t=e.split(`
|
|
2
|
+
`),n=[];let r=0;for(;r<t.length;){const o=t[r],s=t[r+1],a=go(o);if(a.length>0&&s&&fo(s)){for(n.push(a.join(" ")),r+=2;r<t.length;){const l=t[r],c=go(l);if(c.length===0||fo(l))break;n.push(c.join(" ")),r+=1}continue}n.push(o),r+=1}return n.join(`
|
|
3
|
+
`)},wu=e=>e.replace(/^\s{0,3}(?:(?:-\s*){3,}|(?:\*\s*){3,}|(?:_\s*){3,})$/gm,""),Mu=(e,t)=>{const n=e.split(`
|
|
4
|
+
`),r=[];let o=0;for(;o<n.length;){const s=n[o],a=hu(s);if(!a){r.push(s),o+=1;continue}let l=-1;for(let c=o+1;c<n.length;c++)if(pu(n[c],a)){l=c;break}if(l===-1){r.push(s),o+=1;continue}r.push(` ${t} `),o=l+1}return r.join(`
|
|
5
|
+
`)},sn=(e,t)=>{let n=0,r=t-1;for(;r>=0&&e[r]==="\\";)n+=1,r-=1;return n%2===1},ku=e=>{const t=[];let n=0,r="";for(;n<e.length;){const o=e[n];if(o!=="`"||sn(e,n)){r+=o,n+=1;continue}let s=n;for(;s<e.length&&e[s]==="`";)s+=1;const a=e.slice(n,s);let l=s,c=!1;for(;l<e.length&&e[l]!==`
|
|
6
|
+
`;){if(e[l]==="`"&&!sn(e,l)&&e.startsWith(a,l)){const d=e.slice(s,l),m=t.push(d)-1;r+=Ps(m),n=l+a.length,c=!0;break}l+=1}c||(r+=a,n=s)}return{text:r,inlineCodes:t}},Hs=(e,{codeBlockPlaceholder:t=gu}={})=>{const n=e==null?void 0:e.replace(/\r\n?/g,`
|
|
7
|
+
`);if(!n)return;const r=[];let o=n;o=Mu(o,t),o=Tu(o);const s=ku(o);o=s.text,r.push(...s.inlineCodes),o=Cu(o),o=vu(o),o=yu(o),o=Su(o),o=Au(o),o=Iu(o),o=wu(o),o=xu(o);for(let l=0;l<r.length;l++)o=o.replaceAll(Ps(l),r[l]);return pr(o)||void 0},Ru=(e,t)=>{var o;const n=((o=e.name)==null?void 0:o.trim())||"",r=e.mimeType??"";return ze(r)?t.image:mn(r)?t.video:gs({name:n,mimeType:r})?t.pdf(n):t.document(n)},an=e=>(e==null?void 0:e.trim())||"",Lu=e=>(e?pr(e):void 0)||void 0,Gs=e=>({text:an(e),format:"plain"}),Ou=e=>({text:an(e),format:"markdown"}),Rn=({markdownText:e,plainText:t,comparisonText:n})=>{const r=an(e);return r&&r!==an(n)?Ou(r):Gs(t)},At=({sender:e,message:t,messageFormat:n="plain",time:r,codeBlockPlaceholder:o})=>{const s=[],a=n==="markdown"?Hs(t,{codeBlockPlaceholder:o}):Lu(t);if(r&&s.push(r),e&&s.push(e),a&&s.push(a),s.length!==0)return s.join(", ")},zs=(e,t)=>Hs(e==null?void 0:e.trim(),t!==void 0?{codeBlockPlaceholder:t}:void 0),Nu=(...e)=>pr(e.filter(Boolean).join(", "))||void 0,ho=(e,t,n,r)=>{if(!t||t===n)return e;const o=zs(t,r);return o?Nu(e,o):e},Du=(e,t)=>{var r,o,s,a;const n=(r=e.message)==null?void 0:r.trim();if(e.isFileMessage()){const l=((o=e.name)==null?void 0:o.trim())||"",c=Ru({name:l,mimeType:e.type},t);return ho(c,n,l,t.codeBlockPlaceholder)}if(e.isMultipleFilesMessage()){const l=e.fileInfoList??[],c=l.length;if(c===0)return;const d=((a=(s=l[0])==null?void 0:s.fileName)==null?void 0:a.trim())||"",f=l.every(g=>{var E;return(E=g.mimeType)==null?void 0:E.startsWith("image")})?t.receivedFilesImageCount(c):t.multipleFilesCount(c);return ho(f,n,d,t.codeBlockPlaceholder)}return zs(n,t.codeBlockPlaceholder)},$u=(e,t={})=>{const{throttleMs:n=1e3,isSuppressed:r,maxOrderedQueueSize:o=10}=t,s=Math.max(1,o);let a=null;const l=[];let c=null,d=null,m=null,f=!1,g=0;const E=(R,O,z)=>({text:R,ignoreSuppression:O,queueOrder:g++,dedupeKey:z}),y=()=>{const R=l[0]??null,O=a;return R&&O?O.queueOrder<R.queueOrder?(a=null,O):l.shift()??null:R?l.shift()??null:O!==null?(a=null,O):null},v=()=>{for(;;){const R=y();if(!R)return null;if(!(!R.ignoreSuppression&&(r!=null&&r())))return R}},b=R=>{c=R.text,d=R.dedupeKey??null,f=!0,e(R.text),m=setTimeout(()=>{m=null,f=!1;const O=v();O&&b(O)},n)},_=R=>{c=R.text,d=R.dedupeKey??null,e(R.text)},C=(R,O,z,Y)=>O!=null&&Y!=null?O===Y:O==null&&Y==null?R!=null&&R===z:!1,x=(R,O,z)=>{if(!R||!O&&(r!=null&&r()))return;const Y=z==null?void 0:z.dedupeKey;if(!(f&&C(R,Y,c,d)))if(f){if(((z==null?void 0:z.mode)??"latestOnly")==="ordered"){const V=l[l.length-1];if(V&&C(R,Y,V.text,V.dedupeKey))return;l.push(E(R,O,Y)),l.length>s&&l.shift();return}a=E(R,O,Y)}else a=null,b(E(R,O,Y))};return{announce:(R,O)=>{x(R,!1,O)},announceIgnoringSuppression:(R,O)=>{x(R,!0,O)},flush:()=>{const R=[];let O=y();for(;O!==null;)R.push(O),O=y();if(m!==null&&(clearTimeout(m),m=null),f=!1,R.length!==0)for(const z of R)_(z)},destroy:()=>{m!==null&&(clearTimeout(m),m=null),a=null,l.length=0,c=null,d=null,f=!1}}},Pu=e=>{switch(e){case"newMessage":case"conversationClosed":case"csatDisplayed":case"csatSubmitted":case"csatExpired":return"ordered";default:return"latestOnly"}},Fu=(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(". "),Uu=(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}},Bu=(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}},Hu=(e,t)=>!t||!tt(e)||e.sender.userId!==t?null:e.reqId||(e.messageId>0?String(e.messageId):null),Gu=(e,t)=>we.isAdmin(e)?we.isCSAT(e):"sender"in e?e.sender.userId!==t:!1,zu=e=>"messageId"in e&&e.messageId>0?String(e.messageId):"reqId"in e&&typeof e.reqId=="string"&&e.reqId.length>0?e.reqId:null,Vu=e=>e===ue.CollectionEventSource.EVENT_MESSAGE_RECEIVED||e===ue.CollectionEventSource.EVENT_MESSAGE_UPDATED,Yu=({isOpened:e,opensConversationList:t})=>e?t?"closeConversationList":"closeConversation":t?"openConversationList":"openConversation",Wu=(e,t)=>{switch(e){case"closeConversationList":return t.closeConversationList;case"closeConversation":return t.closeConversation;case"openConversationList":return t.openConversationList;case"openConversation":return t.openConversation}},qu=(e,t)=>{switch(e){case"closeConversation":return t.hintCloseConversation;case"openConversationList":return t.hintOpenConversationList;case"openConversation":return t.hintOpenConversation;default:return}},Ku=({intent:e,strings:t})=>({label:Wu(e,t),hint:qu(e,t)}),ju="1.31.1",$e="sb-agent",be={ENTRY:`${$e}-entry`,MODAL_ROOT:`${$e}-modal-root`,WINDOW:`${$e}-window`,LAUNCHER:`${$e}-launcher`,WINDOW_TITLE:`${$e}-window-title`},Vs="data-sb-initial-focus",Ys="true",Xu=`[${Vs}="${Ys}"]`,Ws={[Vs]:Ys},_r="data-sb-focus-trap-sentinel",Zu="true",qs="data-sb-initial-focus-header",Ks="true",Ju=`[${qs}="${Ks}"]`,js={[qs]:Ks},Xs="data-sb-message-input",Zs="true",Qu=`textarea[${Xs}="${Zs}"]:not(:disabled)`,ed={[Xs]:Zs},Js=1e3,Yt=2147483647,it={MODAL:Yt-1,TOOLTIP:Yt-2,WINDOW:Yt-3,LAUNCHER:Yt-4},Qs=36,td=100,nd=ju,Er="noopener noreferrer nofollow";function rd(){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 Wt={};function od(){return{get:e=>{try{return localStorage.getItem(e)}catch{return Wt[e]??null}},set:(e,t)=>{try{localStorage.setItem(e,t)}catch{Wt[e]=t}},delete:e=>{try{localStorage.removeItem(e)}catch{delete Wt[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(Wt).filter(t=>t.startsWith(e))}}}}const sd={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}`}},qn={language:"en",strings:sd,dateLocale:_a.enUS},ei=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}),ti=e=>{var t;return((t=e.split("-"))==null?void 0:t[0])??Nt},Nt="en",ni=new Set([Nt,"ko","es","pt","fr","hi","it","de","tr","ja"]),id='@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:ad,useContext:br}=pe("AgentUIElementResolver"),ld=({entryElement:e,modalRootElement:t,rootElement:n,children:r})=>{const o=u.useMemo(()=>{const s=n??document.body,a=e??s,l=t??s,c=d=>d===be.MODAL_ROOT?l:a.querySelector(`#${d}`);return{resolveElement:c,resolvePortalContainer:d=>c(d)??l}},[e,t,n]);return i.createElement(ad,{value:o},r)};function st(e,t){const n=e.getRootNode({composed:t});return n instanceof ShadowRoot||n instanceof Document?n:document}const po=()=>{const e=[];let t=0;const n=new Set,r=()=>n.forEach(o=>o());return{register:o=>{const s=++t;return e.push({id:s,handler:o}),r(),()=>{const a=e.findIndex(l=>l.id===s);a>=0&&(e.splice(a,1),r())}},dismissTopmost:()=>{const o=e[e.length-1];return o?(o.handler(),!0):!1},subscribe:o=>(n.add(o),()=>{n.delete(o)}),getOpenCount:()=>e.length}},{Provider:cd,useContext:Cr}=pe("EscapeDismissStack"),_o=e=>{e.stopPropagation(),e.stopImmediatePropagation()},ud=({rootElement:e=document.body,boundaryElement:t,children:n})=>{const r=u.useRef(null),o=u.useRef(null);r.current||(r.current=po()),o.current||(o.current=po());const s=r.current,a=o.current;u.useLayoutEffect(()=>{const c=t??st(e),d=m=>{if(m.key==="Escape"){if(s.dismissTopmost()){_o(m);return}a.dismissTopmost()&&_o(m)}};return c.addEventListener("keydown",d),()=>c.removeEventListener("keydown",d)},[t,e,a,s]);const l=u.useMemo(()=>({register:s.register,dismissTopmost:s.dismissTopmost,registerShellDismissHandler:a.register,subscribe:s.subscribe,getOpenCount:s.getOpenCount}),[a,s]);return i.createElement(cd,{value:l},n)},ri=(e,t,n)=>{const r=u.useRef(t);u.useLayoutEffect(()=>{r.current=t},[t]),u.useLayoutEffect(()=>{if(e)return n(()=>r.current())},[e,n])},dd=(e,t)=>{const{register:n}=Cr();ri(e,t,n)},md=(e,t)=>{const{registerShellDismissHandler:n}=Cr();ri(e,t,n)},oi=()=>{const{subscribe:e,getOpenCount:t}=Cr();return u.useSyncExternalStore(e,()=>t()>0,()=>!1)},fd=(e,t,n)=>{const r=e[t];return r?typeof r=="function"?r():Promise.resolve(r):new Promise((o,s)=>{(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(s.bind(null,new Error("Unknown variable dynamic import: "+t+(t.split("/").length!==n?". Note that variables only represent file names one level deep.":""))))})},Eo=ei(qn.strings),gd={...Eo,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:Eo.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"},ln={language:qn.language,dateLocale:qn.dateLocale,stringSet:gd},hd=Object.freeze(Object.defineProperty({__proto__:null,default:ln},Symbol.toStringTag,{value:"Module"})),Kn=new Map([[Nt,ln]]);async function pd(e){const t=Kn.get(e);if(t)return t;try{if(ni.has(e)){const{default:n}=await fd(Object.assign({"./languages/de.ts":()=>Promise.resolve().then(()=>require("./cjs/I-l-5Zo-.cjs")),"./languages/en.ts":()=>Promise.resolve().then(()=>hd),"./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 Kn.set(e,n),n}return ln}catch{return ln}}const{Provider:_d,useContext:se}=pe("Localization"),Ed=({language:e=navigator.language,languageCode:t,logger:n,stringSet:r,children:o})=>{const[s,a]=u.useState(Kn.get(Nt));return u.useEffect(()=>{const l=t??ti(e);s.language!==l&&(n==null||n.debug("localization.useEffect: update language",{from:s.language,to:l}),pd(l).then(a))},[e,t,n]),i.createElement(_d,{value:{language:s.language,defaultStringSet:s.stringSet,stringSet:{...s.stringSet,...r},dateLocale:s.dateLocale,format:(l,c,d)=>Je.format(l,c,{locale:s.dateLocale,...d})}},o)},cn="data-sb-agent-theme",bo=e=>(t,...n)=>{let r="";return t.forEach((o,s)=>{r+=o+(n[s]??"")}),`[${cn}='${e}'] & { ${r} }`},Z={light:bo("light"),dark:bo("dark")},bd=D.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
|
+
`}),Cd=D.css`[${cn}='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);}[${cn}='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);}`,h={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 kt extends u.PureComponent{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}render(){const{fallback:t=null,errorFallback:n=t,loadingFallback:r=t,children:o}=this.props;return this.state.hasError?n:i.createElement(u.Suspense,{fallback:r},o)}}const Ve=e=>{const t=e;return typeof t=="number"?`${t}px`:t},vd=e=>i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",...e},i.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"})),yd=e=>i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 16 16",...e},i.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"})),Sd=e=>i.createElement("svg",{viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg",...e},i.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"})),Ad=e=>i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",fill:"evenodd",...e},i.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"})),xd=e=>i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",...e},i.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"})),Td=new Set(["send","chat","message","chevron-right","good","good-filled","bad","bad-filled"]),Id={close:vd,send:xd,menu:Ad,expand:Sd,collapse:yd,spinner:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/Cf3-irI8.cjs"))),chat:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/BmdfYY9c.cjs"))),message:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/CmWLVNPR.cjs"))),error:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DNmdC4-j.cjs"))),refresh:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/D00MOxhE.cjs"))),"chevron-down":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/wf-LdaaN.cjs"))),"chevron-right":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/B0k-GApQ.cjs"))),done:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/kp5wcW4s.cjs"))),"done-circle":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/Bwaslfwl.cjs"))),stop:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/w1C9O3WB.cjs"))),"stop-circle":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DGubkk9p.cjs"))),user:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/CtHfgPDp.cjs"))),"file-document":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/_YfLwFkX.cjs"))),download:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/BN09c8-A.cjs"))),attach:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DcDTXo8_.cjs"))),"close-filled":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/D1kINslt.cjs"))),agent:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/Ce1MzjFq.cjs"))),actionbook:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/CXa-CGHE.cjs"))),function:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/zbLY6xl_.cjs"))),"radio-on":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/B9NJk4MI.cjs"))),"radio-off":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/Bb0r6Nhu.cjs"))),confluence:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/c6TZaE94.cjs"))),zendesk:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DqpDy_26.cjs"))),salesforce:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/BsgzT_SF.cjs"))),sprinklr:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/D97ZpKUC.cjs"))),website:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/ygZY2D-5.cjs"))),snippet:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/BCFOnu0u.cjs"))),template:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/eJXfXI1_.cjs"))),source:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/yVmX6iux.cjs"))),copy:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/COgkkyBM.cjs"))),show:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DM-WWpci.cjs"))),mute:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/P_ra76fq.cjs"))),good:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DEgUVAck.cjs"))),bad:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/C0s7eAf7.cjs"))),"good-filled":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/Chg8xHXT.cjs"))),"bad-filled":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/CGkmTaBn.cjs"))),delight:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DCB0iTxd.cjs"))),photo:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/GQlGFYP2.cjs"))),add:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DEGDJBmd.cjs"))),document:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DBHlAmeA.cjs"))),memory:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DB0sLqre.cjs"))),activity:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DP95uu-Y.cjs")))},wd=e=>({size:t=24,color:n=h.color.primary.main,flipInRtl:r=!1})=>i.createElement(kd,{$size:t,$color:n,$rtlFlip:r},i.createElement(kt,{errorFallback:i.createElement(Rd,null)},i.createElement(e,null))),si=Object.fromEntries(Object.entries(Id).map(([e,t])=>[e,wd(t)])),Md=D.css`[dir='rtl'] &:not([dir='ltr']),&[dir='rtl']{transform:scaleX(-1);}`,kd=p.default.span.attrs({"aria-hidden":"true"})`
|
|
57
|
+
width: ${({$size:e})=>Ve(e)};
|
|
58
|
+
height: ${({$size:e})=>Ve(e)};
|
|
59
59
|
display: inline-block;
|
|
60
60
|
|
|
61
61
|
svg {
|
|
@@ -74,24 +74,24 @@
|
|
|
74
74
|
stroke-linejoin: round;
|
|
75
75
|
}
|
|
76
76
|
|
|
77
|
-
${({$rtlFlip:e})=>e&&
|
|
78
|
-
`,
|
|
77
|
+
${({$rtlFlip:e})=>e&&Md};
|
|
78
|
+
`,Rd=()=>i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64"},i.createElement("rect",{x:"8",y:"8",width:"48",height:"48",fill:"none",className:"stroke",rx:"4"}),i.createElement("line",{x1:"20",y1:"20",x2:"44",y2:"44",className:"stroke"}),i.createElement("line",{x1:"44",y1:"20",x2:"20",y2:"44",className:"stroke"})),{Provider:Ld,useContext:Od}=pe("MessengerIcon",{icons:si}),Nd=({icons:e,children:t})=>{const n=u.useMemo(()=>({icons:Ml(si,e)}),[e]);return i.createElement(Ld,{value:n},t)},{Provider:Dd,useContext:ii}=pe("MessengerTheme");function $d(e){const{theme:t,appearance:n,logger:r}=e;return i.createElement(gc,{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},i.createElement(Pd,{...e}))}function Pd({rootElement:e=document.body,children:t}){const{theme:n,updateTheme:r}=fr();return u.useLayoutEffect(()=>{e.setAttribute(cn,n.selectedTheme)},[e,n.selectedTheme]),i.createElement(D.ThemeProvider,{theme:n},i.createElement(Dd,{value:{theme:n,updateTheme:r,rootElement:e}},t))}const Fd=(e,t)=>{u.useEffect(()=>{const n=st(t)instanceof ShadowRoot,r=st(t,!0);if(!(n?t:r).querySelector(`link[href*='${e}']`)){const s=r.createElement("link");s.rel="stylesheet",s.href=e,(n?t:r.head).appendChild(s)}},[e,t])},Ud=(e,t=document.body)=>{u.useEffect(()=>{if(!e)return;const n=st(t),o=n instanceof ShadowRoot?t:n.head;if(!o)return;const s=`sba-${btoa(e).slice(0,10)}`;let a=o.querySelector(`style#${s}`);a?a.textContent!==e&&(a.textContent=e):(a=o.ownerDocument.createElement("style"),a.id=s,a.textContent=e,o.appendChild(a))},[e,t])},Bd=80,Hd=()=>{const{stringSet:e}=se(),t={screenConversation:e.A11Y_SCREEN_CONVERSATION,screenConversationWithAgent:e.A11Y_SCREEN_CONVERSATION_WITH_AGENT,screenConversationListNoCount:e.A11Y_SCREEN_CONVERSATION_LIST_NO_COUNT,screenConversationListWithCount:e.A11Y_SCREEN_CONVERSATION_LIST_WITH_COUNT,newMessage:e.A11Y_NEW_MESSAGES_RECEIVED,newMessageFromSender:e.A11Y_NEW_MESSAGES_RECEIVED_FROM_SENDER,typing:e.A11Y_TYPING_FORMAT,sendFailed:e.A11Y_MESSAGE_FAILED,agentConnected:e.A11Y_AGENT_CONNECTED,conversationClosed:e.A11Y_CONVERSATION_CLOSED,csatDisplayed:e.A11Y_CSAT_DISPLAYED,csatExpired:e.CSAT_SUBMISSION_EXPIRED,emptyState:e.A11Y_EMPTY_CONVERSATION,inputDisabled:e.A11Y_INPUT_DISABLED,fileSizeExceeded:e.A11Y_FILE_SIZE_EXCEEDED,csatFormError:e.A11Y_CSAT_FORM_ERROR},n=u.useRef(t);return n.current=t,n},ai=pe("AriaLiveRegion",{announce:ce,announceScreenEntry:ce,announceStatus:ce,announceError:ce,flush:ce,setSuppressionState:ce}),Gd=ai.Provider,vr=ai.useContext,zd={position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},Vd=({children:e})=>{const t=u.useRef(null),n=u.useRef(new Set),r=u.useRef(ce),o=Hd(),[s]=u.useState(()=>$u(E=>{r.current(E)},{throttleMs:1e3,isSuppressed:()=>n.current.size>0}));r.current=E=>{const y=t.current;y&&(y.textContent="",requestAnimationFrame(()=>{y.textContent=E}))},u.useEffect(()=>()=>{s.destroy()},[s]);const a=s.announce,l=s.flush,c=u.useCallback(E=>{const y=Fu(E,o.current);a(y)},[a]),d=u.useCallback((E,y)=>{const v=Uu(E,o.current),b=(y==null?void 0:y.mode)??Pu(E.event);a(v,{mode:b,dedupeKey:y==null?void 0:y.dedupeKey})},[a]),m=u.useCallback((E,y)=>{const v=Bu(E,o.current);s.announceIgnoringSuppression(v),y&&setTimeout(()=>{y.focus()},Bd)},[s]),f=u.useCallback((E,y)=>{if(y){n.current.add(E);return}n.current.delete(E)},[]),g=u.useMemo(()=>({announce:a,announceScreenEntry:c,announceStatus:d,announceError:m,flush:l,setSuppressionState:f}),[a,m,c,d,l,f]);return i.createElement(Gd,{value:g},e,i.createElement("div",{ref:t,role:"status","aria-live":"polite","aria-atomic":"true",style:zd}))},li=pe("ConversationAnnouncements",{announcementsEnabled:!0,announce:ce,announceScreenEntry:ce,announceStatus:ce,announceError:ce,setIsSuppressed:ce,setStatusPauseState:ce,flush:ce}),Yd=li.Provider,Xe=li.useContext,Wd=({children:e,announcementsEnabled:t=!0})=>{const{announce:n,announceScreenEntry:r,announceStatus:o,announceError:s,flush:a,setSuppressionState:l}=vr(),c=u.useRef([]),d=u.useRef(new Set),m=u.useRef(Symbol("conversation-announcements")),f=u.useCallback(A=>{if(!t||!A){l(m.current,!1);return}l(m.current,!0)},[t,l]),g=u.useCallback(()=>{c.current=[]},[]),E=u.useCallback(()=>{if(c.current.length===0)return;if(!t){g();return}const A=[...c.current];g(),A.forEach(w=>{a(),o(w.params,w.options)})},[o,t,g,a]),y=u.useCallback((A,w)=>{if(w){d.current.add(A);return}d.current.delete(A),d.current.size===0&&E()},[E]),v=u.useCallback(A=>{t&&n(A)},[n,t]),b=u.useCallback(A=>{t&&r(A)},[r,t]),_=u.useCallback((A,w)=>{if(t){if(d.current.size>0){c.current.push({params:A,options:w});return}o(A,w)}},[o,t]),C=u.useCallback((A,w)=>{t&&s(A,w)},[s,t]);u.useLayoutEffect(()=>(t||(g(),l(m.current,!1)),()=>{g(),l(m.current,!1)}),[t,g,l]);const x=u.useMemo(()=>({announcementsEnabled:t,announce:v,announceScreenEntry:b,announceStatus:_,announceError:C,setIsSuppressed:f,setStatusPauseState:y,flush:a}),[t,a,v,C,b,_,f,y]);return i.createElement(Yd,{value:x},e)},$=({as:e,variant:t="body1",color:n,maxTextLines:r,className:o,...s})=>i.createElement(jd,{as:e,$variant:t,className:o,$color:n,$maxTextLines:r,...s}),Co=new WeakMap,qd=(e,t)=>{let n=Co.get(t);n||(n=new Map,Co.set(t,n));const r=n.get(e);if(r)return r;const o=t[e]??t.body1,s=D.css`font-size:${Ve(o.fontSize)};font-weight:${o.fontWeight};${o.fontFamily?`font-family: ${o.fontFamily};`:""}
|
|
79
79
|
${o.lineHeight?`line-height: ${o.lineHeight};`:"line-height: 100%;"}
|
|
80
|
-
`;return n.set(e,s),s},zd=e=>e?D.css`display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:${e};overflow:hidden;`:"",Vd=p.default.span`font-stretch:normal;letter-spacing:normal;${({$variant:e,theme:t})=>Gd(e,t.typography)}color:${({$color:e})=>e};${({$maxTextLines:e})=>zd(e)}`,mn=["a[href]","button:not(:disabled)","input:not(:disabled)","select:not(:disabled)","textarea:not(:disabled)",'[tabindex]:not([tabindex="-1"])'].join(", "),ii=`${mn}, [tabindex="-1"]`,ft=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};async function br(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 kt=(e,t)=>{for(const n of e.querySelectorAll(t))if(!n.hasAttribute(hr)&&ft(n))return n;return null},ai=e=>{let t=null,n=null;for(const r of e.querySelectorAll(mn))r.hasAttribute(hr)||ft(r)&&(t??(t=r),n=r);return t?{first:t,last:n}:null},Cr=e=>kt(e,Yu),li=e=>Cr(e)??kt(e,mn),Yd=e=>{const t=Cr(e);if(t)return t;const n=e.querySelector(qu);return(n?kt(n,ii):null)??kt(e,mn)},qn='[role="dialog"][aria-modal="true"]',Wd=(e,t)=>{const n=new Set(Array.from(e.ownerDocument.querySelectorAll(qn)).filter(o=>o!==e&&(o.contains(e)||e.contains(o)))),r=t==null?void 0:t.closest(qn);return r&&r!==e&&n.add(r),n},qd=(e,t)=>Array.from(e.ownerDocument.querySelectorAll(qn)).some(n=>n!==e&&!t.has(n)&&!n.contains(e)&&ft(n)),Kd=e=>{const t=li(e)??e;t===e&&ci(e),t.focus()},ci=e=>{e.hasAttribute("tabindex")||e.setAttribute("tabindex","-1")},jd=(e,t)=>{const n=ai(e);if(!n){ci(e),e.focus();return}n[t].focus()},Eo=(e,t)=>{const n=e.ownerDocument.createElement("span");return n.tabIndex=0,n.setAttribute(hr,Wu),n.style.cssText=["position: fixed","width: 1px","height: 1px","opacity: 0","overflow: hidden","pointer-events: none"].join(";"),n.addEventListener("focus",()=>jd(e,t)),n},Xd=(e,t)=>{e.key==="Tab"&&(e.defaultPrevented||e.target===t&&(ai(t)||(e.preventDefault(),t.focus())))},Zd=(e,t)=>t instanceof HTMLElement?e instanceof Document?t===e.body||t===e.documentElement:!1:!0,fn=(e,t,{nameReady:n=!0}={})=>{const r=u.useRef(0),o=u.useRef(!1);u.useEffect(()=>{if(!e||!t.current){o.current=!1;return}r.current+=1;const s=r.current,a=t.current,l=a.getRootNode(),c=l.activeElement instanceof HTMLElement?l.activeElement:null,d=Wd(a,c);return()=>{c&&we(()=>{if(r.current!==s)return;const m=l.activeElement;a.isConnected&&m instanceof HTMLElement&&m!==a&&!a.contains(m)&&!Zd(l,m)&&m.matches(ii)&&ft(m)||qd(a,d)||!c.isConnected||!ft(c)||c.focus()})}},[e,t]),u.useEffect(()=>{if(!e||!t.current)return;const s=t.current;let a=!1;const l=()=>{if(a||o.current||!s.isConnected)return;const m=s.getRootNode().activeElement;if(m instanceof HTMLElement&&m!==s&&s.contains(m)&&ft(m)){o.current=!0;return}o.current=!0,Kd(s)};if(n)return we(l),()=>{a=!0};const c=setTimeout(()=>we(l),js);return()=>{a=!0,clearTimeout(c)}},[e,t,n]),u.useEffect(()=>{if(!e||!t.current)return;const s=t.current,a=Eo(s,"last"),l=Eo(s,"first"),c=d=>Xd(d,s);return s.insertBefore(a,s.firstChild),s.appendChild(l),s.addEventListener("keydown",c),()=>{s.removeEventListener("keydown",c),a.remove(),l.remove()}},[e,t])},nt=({style:e,portalContainerId:t,visible:n,onClose:r,children:o,cancelable:s=!0,"aria-label":a,"aria-labelledby":l,"aria-describedby":c})=>{const d=u.useRef(null),{resolvePortalContainer:m}=_r();return fn(n,d),id(n,s?r:ge),n?ga.createPortal(i.createElement(Jd,{onClick:s?r:void 0,style:e},i.createElement(Qd,{ref:d,role:"dialog","aria-modal":"true","aria-label":a,"aria-labelledby":l,"aria-describedby":c,onClick:f=>f.stopPropagation()},o)),m(t)):null},Jd=p.default.div`position:fixed;top:0;left:0;width:100%;height:100%;background:${h.color.overlay.dark};display:flex;justify-content:center;align-items:center;z-index:${it.MODAL};`,Qd=p.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:${it.MODAL};`,em=({id:e,children:t})=>i.createElement(tm,{id:e},t),tm=p.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;`,bo=(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?{}:zs}:n},nm=()=>{const e=`${u.useId()}-`;return(t,n)=>{if(!t)return{props:{},node:null};const r=e+n,o=u.createElement(em,{id:r,children:t});return{props:{"aria-describedby":r},node:o}}},Co=({name:e,mimeType:t,selected:n},r)=>{var s;const o=He(t??"")?r.A11Y_FILE_IMAGE(e):cn(t??"")?r.A11Y_FILE_VIDEO(e):ds({name:e,mimeType:t})?r.A11Y_FILE_PDF(e):r.A11Y_FILE_DOCUMENT(e);return n?((s=r.A11Y_FILE_SELECTED)==null?void 0:s.call(r,o))??`${o}, selected`:o},rm=e=>t=>{t.repeat||(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())},At=({onActivate:e})=>({role:"button",tabIndex:0,onClick:e,onKeyDown:rm(e)}),om=({disabled:e,currentIndex:t,totalCount:n,onNavigate:r})=>o=>{var c;if(e||n<=0)return;let s=null;switch(o.key){case"ArrowRight":case"ArrowDown":s=(t+1)%n;break;case"ArrowLeft":case"ArrowUp":s=(t-1+n)%n;break;default:return}o.preventDefault(),r(s);const a=o.currentTarget.parentElement,l=a==null?void 0:a.querySelectorAll('[role="radio"]');(c=l==null?void 0:l[s])==null||c.focus()},vo=(e,t,n,r,o,s)=>{let a=-1;return(e||!o&&n===0)&&(a=0),{role:"radio","aria-checked":e,"aria-disabled":t,onKeyDown:om({disabled:t,currentIndex:n,totalCount:r,onNavigate:s}),tabIndex:a}},oe=()=>{const{stringSet:e}=se(),t=nm(),n=(a,l)=>{let c=e.A11Y_HINT_OPEN_FILE,d="of";He(a??"")&&(c=e.A11Y_HINT_OPEN_IMAGE,d="oi"),l!==void 0&&(d+=l);const m=t(c,d);return{props:m.props,descriptionNode:m.node}},r=a=>({"aria-label":Co(a,e)});return{launcher:{button:({isOpened:a,opensConversationList:l})=>{const c=zu({intent:Bu({isOpened:a,opensConversationList:l}),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";c.hint===e.A11Y_HINT_OPEN_CONVERSATION&&(d="lo"),c.hint===e.A11Y_HINT_OPEN_CONVERSATIONS&&(d="los");const m=t(c.hint,d);return{props:{"aria-label":c.label,...m.props},descriptionNode:m.node}}},messenger:{closeButton:()=>({props:{"aria-label":e.A11Y_CLOSE_MESSENGER},descriptionNode:null}),expandButton:a=>{let l=e.A11Y_EXPAND_MESSENGER;return a&&(l=e.A11Y_COLLAPSE_MESSENGER),{props:{"aria-label":l},descriptionNode:null}},connectionDelayDialog:()=>({props:{"aria-label":e.CONNECTION_DELAY__TITLE},descriptionNode:null})},conversation:{header:{menuButton:()=>{const a=e.A11Y_HINT_OPEN_MENU,l=t(a,"mb");return{props:{"aria-label":e.A11Y_MENU,...l.props},descriptionNode:l.node}},closeConversationButton:()=>{const a=e.A11Y_HINT_CLOSE_CONVERSATION,l=t(a,"cc");return{props:{"aria-label":e.A11Y_CLOSE_CONVERSATION,...l.props},descriptionNode:l.node}},handoffButton:()=>{const a=e.A11Y_HINT_CONNECT_TO_AGENT,l=t(a,"h");return{props:{"aria-label":e.A11Y_CONNECT_AGENT,...l.props},descriptionNode:l.node}},title:(a,l)=>({props:bo(a,l),descriptionNode:null}),memoryIndicator:a=>{let l=e.A11Y_MEMORY_INDICATOR_OFF,c="mof";a&&(l=e.A11Y_MEMORY_INDICATOR_ON,c="mon");const d=t(l,c);return{props:{"aria-label":e.A11Y_MEMORY_INDICATOR_MANAGE,...d.props},descriptionNode:d.node}}},messageInput:{attachFileButton:()=>{const a=e.A11Y_HINT_ATTACH_FILE,l=t(a,"af");return{props:{"aria-label":e.A11Y_ATTACH_FILE,...l.props},descriptionNode:l.node}},sendButton:()=>{const a=e.A11Y_HINT_SEND_MESSAGE,l=t(a,"sm");return{props:{"aria-label":e.A11Y_SEND_MESSAGE,...l.props},descriptionNode:l.node}},textInput:a=>({props:{role:"textbox","aria-label":a,...ju},descriptionNode:null})},suggestedReplies:{item:(a,l)=>{const c=e.A11Y_HINT_SEND_REPLY,d=t(c,`sr${l}`);return{props:{"aria-label":`${e.A11Y_SUGGESTED_REPLY}, ${a}`,...d.props},descriptionNode:d.node}}},feedback:{container:()=>{const a=e.A11Y_HINT_SELECT_RATING,l=t(a,"fb");return{props:l.props,descriptionNode:l.node}},button:(a,l)=>{const c=e.A11Y_HINT_SELECT_RATING,d=t(c,`f${a}`);let m=e.FEEDBACK_BAD;return a==="good"&&(m=e.FEEDBACK_GOOD),{props:{"aria-label":m,...d.props,"aria-pressed":l},descriptionNode:d.node}},optionsBottomSheet:()=>({props:{"aria-label":e.A11Y_FEEDBACK_OPTIONS},descriptionNode:null})},newMessagesButton:()=>{const a=e.A11Y_HINT_VIEW_NEW_MESSAGES,l=t(a,"nm");return{props:{"aria-label":e.A11Y_SCROLL_TO_NEW_MESSAGES,...l.props},descriptionNode:l.node}},scrollToBottomButton:()=>{const a=e.A11Y_HINT_VIEW_NEW_MESSAGES,l=t(a,"sb");return{props:{"aria-label":e.A11Y_SCROLL_TO_BOTTOM,...l.props},descriptionNode:l.node}},startNewConversationButton:({onActivate:a})=>({props:{...At({onActivate:a}),"aria-label":e.TALK_TO_AGENT},descriptionNode:null}),poweredByLink:()=>({props:{"aria-label":`${e.POWERED_BY} Sendbird`},descriptionNode:null}),retryButton:(a=e.RETRY)=>({props:{"aria-label":a},descriptionNode:null}),file:{label:(a,l,c)=>a?Co({name:a,mimeType:l,selected:c},e):"",preview:a=>({props:r(a),descriptionNode:null}),buttonLikePreview:({onActivate:a,...l},c)=>{const d=n(l.mimeType,c);return{props:{...At({onActivate:a}),...r(l),...d.props},descriptionNode:d.descriptionNode}},removeButton:a=>({props:{"aria-label":e.A11Y_FILE_REMOVE_BUTTON(a)},descriptionNode:null})},csat:{scoresContainer:a=>{const l=e.A11Y_HINT_SELECT_RATING,c=t(l,"cs");return{props:{role:"radiogroup","aria-label":a,...c.props},descriptionNode:c.node}},scoreItem:({score:a,label:l,selected:c,disabled:d,currentIndex:m,totalCount:f,hasSelection:g,onChange:_})=>{var E;const v=l.trim()||l,y=e.A11Y_HINT_SELECT_RATING,b=t(y,`cs${a}`);return{props:{disabled:d,onClick:()=>_(a),...vo(c,d,m,f,g,C=>_(C+1)),...b.props,"aria-label":((E=e.A11Y_CSAT_RATING_LABEL)==null?void 0:E.call(e,a,v))??`${a} / ${f} — ${v}`},descriptionNode:b.node}},submitButton:a=>({props:{"aria-label":a},descriptionNode:null})},form:{button:a=>({props:{"aria-label":a},descriptionNode:null}),textInput:(a,l,c,d)=>({props:{...d!=null&&d.labelId?{"aria-labelledby":d.labelId}:{"aria-label":a},"aria-required":l,"aria-disabled":c},descriptionNode:null}),numberInput:(a,l,c)=>({props:{"aria-label":a,"aria-required":l,"aria-disabled":c},descriptionNode:null}),singleSelectGroup:a=>{const l={role:"radiogroup"};return a&&(l["aria-label"]=a),{props:l,descriptionNode:null}},singleSelectOption:(a,l,c,d,m,f,g)=>({props:{...vo(l,c,d,m,f,g),"aria-label":a},descriptionNode:null}),multiSelectOption:(a,l,c)=>({props:{"aria-label":a,"aria-pressed":l,"aria-disabled":c},descriptionNode:null})}},conversationList:{headerTitle:(a,l)=>({props:bo(a,l),descriptionNode:null}),footer:{button:({onActivate:a})=>({props:{...At({onActivate:a}),"aria-label":e.TALK_TO_AGENT},descriptionNode:null})},item:({agent:a,status:l,time:c,unreadCount:d,onActivate:m})=>{if(!m)return{props:{"aria-label":e.A11Y_CONVERSATION_ITEM(a,l,c,d)},descriptionNode:null};const f=e.A11Y_HINT_OPEN_CONVERSATION,g=t(f,"cli");return{props:{...At({onActivate:m}),...g.props,"aria-label":e.A11Y_CONVERSATION_ITEM(a,l,c,d)},descriptionNode:g.node}}}}},sm=({title:e,description:t,highlightedText:n})=>{const r=au(t,n);return i.createElement(am,null,i.createElement(lm,null,i.createElement($,{as:"div",variant:"h1",color:h.themedColor.textHighEmphasis},e),t&&i.createElement(cm,null,i.createElement($,{as:"div",variant:"body3",color:h.themedColor.textMidEmphasis},r.beforeText,r.highlightedText?i.createElement(um,null,r.highlightedText):null,r.afterText))))},im=()=>{const{components:e}=gn.useContext(),{stringSet:t}=se(),{messenger:n}=oe(),r=su(),o=r.showDescription?iu(r.remainingTime):"",s=r.showDescription?t.CONNECTION_DELAY__DESCRIPTION(o):"";return i.createElement(nt,{portalContainerId:Ce.WINDOW,visible:r.visible,onClose:ge,...n.connectionDelayDialog().props},i.createElement(e.Dialog,{title:t.CONNECTION_DELAY__TITLE,description:s,highlightedText:o||void 0}))},gn=Be({template:im,components:{Dialog:sm}}),am=p.default.div`width:280px;padding:24px;margin:0 auto;border-radius:4px;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,lm=p.default.div`display:flex;flex-direction:column;`,cm=p.default.div`margin-top:16px;`,um=p.default.strong`font-weight:700;`,dm=({url:e})=>br(e),{Provider:mm,Consumer:ui,useContext:me}=Ee("Messenger");function fm({children:e,state:t,enableCloseConversationButton:n=!1,enableExpandButton:r=!0,enableAutoDisconnectInLauncher:o=!0,...s}){const[a,l]=u.useState(!1),[c,d]=u.useState(!1),m={opened:(t==null?void 0:t.opened)??a,setOpened:(t==null?void 0:t.setOpened)??l,expanded:(t==null?void 0:t.expanded)??c,setExpanded:(t==null?void 0:t.setExpanded)??d},{resolveElement:f}=_r(),g=u.useCallback(()=>{var y;m.setOpened(!1),(y=f(Ce.LAUNCHER))==null||y.focus()},[m.setOpened,f]);ad(m.opened,g);const{Template:_}=gn.useContext(),v=u.useMemo(()=>{var y;return{...s.handlers,onClickLink:((y=s.handlers)==null?void 0:y.onClickLink)??dm}},[s.handlers]);return i.createElement(Ll,{...s},y=>i.createElement(mm,{value:{...s,...y,state:m,enableCloseConversationButton:n,enableExpandButton:r,enableAutoDisconnectInLauncher:o,handlers:v}},i.createElement(_,null),e))}const di=/iPad|iPhone|iPod/.test(navigator.userAgent),gm=/Android/.test(navigator.userAgent),Nt=e=>di||gm;let yt=null,Mn=null;const hm=(e,t=5e3)=>{yt&&(clearInterval(yt),clearTimeout(Mn));const n=document.title;yt=setInterval(()=>{document.title=document.title===e?n:e},750),Mn=setTimeout(()=>{clearInterval(yt),yt=null,Mn=null,document.title=n},t)},mi=()=>{Promise.resolve().then(()=>require("./cjs/B93o4u0P.cjs")).then(e=>{new Audio(e.default).play().catch(()=>{})})},Ae=D.css`&:focus-visible{outline:2px solid ${h.themedColor.primary};outline-offset:2px;}`,yo=e=>{if(typeof e=="string"||typeof e=="number")return String(e)},hn=({visible:e,title:t,description:n,confirmText:r="OK",cancelText:o,onConfirm:s,onCancel:a,onClose:l,"aria-label":c})=>{const d=u.useId(),m=u.useId(),f=c??yo(t)??yo(n),g=c?void 0:t?d:n?m:void 0,_=t&&n?m:void 0,v=()=>{l(),we(()=>s==null?void 0:s())},y=()=>{l(),we(()=>a==null?void 0:a())};return i.createElement(nt,{portalContainerId:Ce.WINDOW,visible:e,onClose:l,"aria-label":f,"aria-labelledby":g,"aria-describedby":_},i.createElement(pm,null,i.createElement(_m,null,t&&i.createElement("div",{id:d},i.createElement($,{variant:"h1",color:h.themedColor.textHighEmphasis},t)),n&&i.createElement(Em,{id:m},i.createElement($,{variant:"body3",color:h.themedColor.textMidEmphasis},n))),i.createElement(bm,null,o&&i.createElement(So,{onClick:y},i.createElement($,{variant:"button",color:h.themedColor.textHighEmphasis},o)),i.createElement(So,{onClick:v},i.createElement($,{variant:"button",color:h.themedColor.primary},r)))))},pm=p.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};`,_m=p.default.div`margin-bottom:16px;`,Em=p.default.div`margin-top:16px;`,bm=p.default.div`display:flex;flex-direction:row;justify-content:flex-end;`,So=p.default.button`all:unset;display:flex;justify-content:center;align-items:center;border-radius:4px;cursor:pointer;background-color:transparent;padding:10px 16px;${Ae}`,{Provider:Cm,useContext:Me}=Ee("MessengerSession"),vm=u.forwardRef(function({children:e,...t},n){return i.createElement(fc,{ref:n,...t},r=>i.createElement(ym,{...r},e))}),ym=({children:e,...t})=>{const{chatSDK:n,logger:r,appId:o,aiAgentId:s,agentPreviewConfigs:a,state:l,handlers:c,dispatcher:d,_aiAgentSDK:m}=me(),{userSessionInfo:f,authenticate:g,userSession:_,aiAgentInfo:v,launcherInfo:y}=t,[b,E]=u.useState(!1),C=u.useRef(null);ht(n,{async onUserJoined(x,w){var I,M,O,F;x.conversation&&x.conversation.type===be.ConversationType.PROACTIVE&&w.userId===((I=n.currentUser)==null?void 0:I.userId)&&(r.info("messengerSession.onUserJoined: proactive channel joined",x.url),(O=m.session)==null||O._updateActiveChannel({url:x.url,status:"open",conversationStatus:(M=x.conversation)==null?void 0:M.status}),l.setOpened(!0),Sm({sound:document.hidden||!l.opened}),(F=C.current)==null||F.call(C,{channel:x}))}}),u.useEffect(()=>{g().then(({launcher:x})=>{x.auto_open&&!Nt()&&setTimeout(()=>l.setOpened(!0),500)}).catch(x=>{var w;r.error("messengerSession: failed to initialize",x),(w=c==null?void 0:c.onInitializeFailed)==null||w.call(c,x)})},[n,o,s,f==null?void 0:f.userId]),u.useEffect(()=>{const x=()=>E(!0);return d.subscribe(Fe.AnonymousSessionTokenExpired,x),()=>d.unsubscribe(Fe.AnonymousSessionTokenExpired,x)},[d]);const S=u.useCallback(()=>{t.deauthenticate().finally(()=>window.location.reload())},[t.deauthenticate]);return!_||!v||!y?null:i.createElement(Cm,{value:{...t,userSession:_,aiAgentInfo:{...v,...a==null?void 0:a.bot},launcherInfo:{...y,...a==null?void 0:a.launcher},registerOnJoinedProactiveConversation:x=>C.current=x}},e,i.createElement(hn,{visible:b,title:"Session timed out",description:"Start a new conversation.",onConfirm:S,onClose:ge}))};function Sm({sound:e}){hm("🔔You have received a new message"),e&&mi()}const an=`@${Ne}-focused-channel`,fi=`${Date.now()}-${Math.random().toString(36).slice(2)}`,Am=()=>{try{const e=localStorage.getItem(an);return e?JSON.parse(e).channelUrl??null:null}catch{return null}},Ao=e=>{try{localStorage.setItem(an,JSON.stringify({channelUrl:e,tabId:fi}))}catch{}},xo=()=>{try{const e=localStorage.getItem(an);if(!e)return;JSON.parse(e).tabId===fi&&localStorage.removeItem(an)}catch{}},xm=(e,t)=>(u.useEffect(()=>{if(!t||!e)return;const n=()=>Ao(e),r=()=>xo();return document.hasFocus()&&Ao(e),window.addEventListener("focus",n),window.addEventListener("blur",r),()=>{window.removeEventListener("focus",n),window.removeEventListener("blur",r),xo()}},[t,e]),{isChannelViewedInAnyTab:()=>document.hasFocus()||Am()===e}),Tm=e=>{const{config:t,chatSDK:n}=me(),{sdkUser:r}=Me(),o=t.conversation.messageAlertSoundEnabled,{isChannelViewedInAnyTab:s}=xm(e,o);ht(n,{onMessageReceived(a,l){if(!o||a.url!==e||s())return;(Qe(l)&&l.sender.userId!==(r==null?void 0:r.userId)||l.isAdminMessage()&&!l.silent)&&mi()}})};function Im(e){return new Promise(t=>{const n=new Image;n.onload=function(){const r=String(n.width),o=String(n.height);URL.revokeObjectURL(n.src),t({width:r,height:o})},n.src=URL.createObjectURL(e)})}async function wm(e){if("file"in e&&e.file instanceof File&&e.file.type.startsWith("image/")){const{width:t,height:n}=await Im(e.file);return new Ue.MessageMetaArray({key:cs,value:[t,n]})}}const Mm=({onScrollAfterSendMessage:e})=>{const{agentPreviewConfigs:t,handlers:n}=me(),r=u.useRef(t==null?void 0:t.agentAttributes);return r.current=t==null?void 0:t.agentAttributes,{onBeforeSendMessage:async o=>{const s=await wm(o),a={...o,metaArrays:s?[s]:void 0},l=km(r.current);return l?{...a,data:JSON.stringify(l)}:a},onAfterSendMessage:o=>{var s,a,l;e(),(s=n==null?void 0:n.onMessageSend)==null||s.call(n,o.message),o.sendingStatus===Ue.SendingStatus.SUCCEEDED?(a=n==null?void 0:n.onCustomEvent)==null||a.call(n,{type:"message-sent-succeeded",data:{message:o}}):o.sendingStatus===Ue.SendingStatus.PENDING&&((l=n==null?void 0:n.onCustomEvent)==null||l.call(n,{type:"message-sent-pending",data:{message:o}}))}}},km=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},dt=50,kn=dt-40,{Provider:Rm,useContext:gi}=Ee("ConversationScroll"),To={viewport:0,contentHeight:0,contentSnapshotHeight:0,shouldRecalc:!1,shouldUpdate:!1},Rn=e=>Math.max(0,e.scrollHeight-e.scrollTop-e.clientHeight);function Lm({scrollMode:e,messageStackDirection:t,children:n}){const r=u.useRef(null),o=u.useRef(null),s=u.useRef(0),a=u.useRef(0),l=u.useRef(!1),c=u.useRef(!1),d=u.useRef(null),m=u.useRef(To),f=u.useRef(!1),g=u.useRef(null),[_,v]=u.useState(0),[y,b]=u.useState(0),[E,C]=u.useState(!1),[S,x]=u.useState(!1),[w,k]=u.useState(!0),I=T=>{const R=Rn(T);return s.current=R,b(R),R},M=()=>{d.current&&(clearTimeout(d.current),d.current=null)},O=u.useMemo(()=>E||t==="bottom"?"auto":e,[E,t,e]),F=()=>{m.current.contentSnapshotHeight=m.current.contentHeight,m.current.shouldUpdate=!0,m.current.shouldRecalc=!0},Y=()=>{const T=r.current;!T||!m.current.shouldUpdate||v(R=>{m.current.shouldUpdate=!1;const{contentHeight:N,contentSnapshotHeight:j,shouldRecalc:U}=m.current,G=T.clientHeight;if(j>N)return R;const B=z(T,{messageType:"outgoing"});let ue=0;if(B){const $e=B.message.offsetTop-kn+G;ue=Math.max(0,$e-N)}else{const $e=N-j,ae=G-kn;ue=Math.max(0,$e-ae)}return R===0||ue!==R||U?(m.current.shouldRecalc=!1,ue):R})},z=u.useCallback((T,R)=>{const{messageType:N="all"}=R??{},j=Array.from(T.querySelectorAll(`#${Ne}-message-item`));let U=j;N==="outgoing"&&(U=j.filter(ne=>ne.getAttribute("data-layout-id")==="outgoingmessage"));const G=U[U.length-1];if(!G)return null;const B=T.getBoundingClientRect(),ue=G.getBoundingClientRect(),$e=T.scrollTop+(ue.top-B.top),ae=$e+G.offsetHeight;return{message:G,scrollTop:$e,lastMessageBottom:ae}},[]),V=u.useCallback(()=>{const T=r.current;if(!T||O!=="fixed")return;const R=z(T);m.current.contentHeight=(R==null?void 0:R.lastMessageBottom)??T.scrollHeight,!f.current&&m.current.contentSnapshotHeight>0&&F(),c.current?s.current=Rn(T):I(T),Y()},[O,z]),H=u.useCallback(()=>{o.current&&(o.current.disconnect(),o.current=null),M(),m.current=To,v(0),b(0),k(!0),s.current=0,l.current=!1,a.current=0,c.current=!1},[]),W=u.useCallback((T=!0)=>{const R=s.current>dt;if(l.current=!1,b(0),!R){we(()=>{const N=r.current;N&&!l.current&&N.scrollTo({top:N.scrollHeight,behavior:"auto"})});return}c.current||(c.current=!0,k(!1),M()),we(()=>{const N=r.current;if(!N){c.current=!1,k(!0);return}if(l.current){c.current=!1,I(N),k(!0);return}const j=()=>{if(r.current!==N){c.current=!1,r.current&&I(r.current),k(!0);return}c.current=!1,I(N),k(!0)};if(T&&!d.current){const U=setTimeout(j,500);d.current=U,N.addEventListener("scrollend",()=>{clearTimeout(U),d.current=null,j()},{once:!0})}N.scrollTo({top:N.scrollHeight,behavior:T?"smooth":"auto"}),T||j()})},[]),q=u.useCallback(T=>{T&&(r.current=T,O==="fixed"&&(H(),m.current.viewport=T.clientHeight,o.current=new MutationObserver(()=>{V()}),o.current.observe(T,{childList:!0,subtree:!0})))},[O,V,H]),ce=u.useCallback(()=>{const T=r.current;if(!T)return;const R=z(T,{messageType:"outgoing"});R&&(T.scrollTo({top:R.message.offsetTop-kn,behavior:"smooth"}),g.current&&clearTimeout(g.current),g.current=setTimeout(()=>{x(!1)},500))},[z]),_e=(T,R,N)=>{const j=Rn(T);if(N&&j>dt){c.current=!1,l.current=!0,M(),I(T),k(!0),a.current=R;return}s.current=j},L=(T,R,N)=>{const U=I(T)<=dt;R&&!U&&(l.current=!0,M()),N&&U&&(l.current=!1)},X=T=>{const{scrollTop:R}=T.currentTarget,N=a.current;c.current?_e(T.currentTarget,R,R<N):L(T.currentTarget,R<N,R>N),a.current=R},K=u.useCallback(()=>{O==="fixed"&&(x(!0),F())},[O]),P=u.useCallback(()=>{O==="fixed"?setTimeout(()=>ce(),300):W()},[O,ce]),te=u.useCallback(T=>{f.current=T,O==="fixed"?F():l.current||W()},[O,W]),de=u.useCallback(T=>{C(T),T&&(v(0),o.current&&(o.current.disconnect(),o.current=null))},[]),fe=u.useCallback(T=>{O==="auto"&&T&&!l.current&&W()},[O,W]),Oe=!(y<=dt)&&!S,Re=u.useCallback(()=>s.current>dt,[]);return i.createElement(Rm,{value:{ref:q,state:{bottomSpace:_,isAwayFromBottom:Oe,isScrollPositionReconciled:w,shouldCountNewMessages:Re},props:{onScroll:X},actions:{scrollToBottom:W,onBeforeMessageSend:K,onAfterMessageSend:P,onStreamingUpdate:te,onConversationClosed:de,onTypingIndicatorUpdate:fe}}},n)}const{Provider:Om,Context:Nm,useContext:Se}=Ee("Conversation"),Dm=({children:e})=>{var o;const{channelSource:t}=Se(),n=(o=t.channel)==null?void 0:o.url,{checkForUserActionRequired:r}=zc(n);return u.useEffect(()=>{var a;const s=(a=t.channel)==null?void 0:a.lastMessage;s&&r(s)},[t.channel,r]),i.createElement(i.Fragment,null,e)},$m=({channelUrl:e,onClearChannelUrl:t,onNavigateToConversationList:n,shouldMarkAsRead:r,children:o})=>{const{activeChannel:s,refreshActiveChannel:a}=Me(),l=gi(),c=e||(s==null?void 0:s.url);Tm(c);const{onBeforeSendMessage:d,onAfterSendMessage:m}=Mm({onScrollAfterSendMessage:()=>{l.actions.onAfterMessageSend()}}),f=u.useCallback(v=>(l.actions.onBeforeMessageSend(),d(v)),[l.actions,d]),g=u.useCallback(v=>{const y=v.some(b=>Ve.isStreaming(b));l.actions.onStreamingUpdate(y)},[l.actions.onStreamingUpdate]),_=u.useCallback(async()=>{await a(),e&&(t==null||t())},[a,e,t]);return i.createElement(xc,{key:c,channelUrl:c,onBeforeSendMessage:f,onAfterSendMessage:m,onMessagesUpdated:g,onMessagesReceived:g,onChannelDeleted:_,onConversationClosedStatusChanged:l.actions.onConversationClosed,shouldMarkAsRead:r,shouldCountNewMessages:l.state.shouldCountNewMessages},v=>i.createElement(Om,{value:{...v,scrollSource:l,goToActiveConversation:_,onNavigateToConversationList:n}},i.createElement(Dm,null,o)))},hi=({children:e,...t})=>{const{config:n}=ke(),{agentPreviewConfigs:r}=me(),o=n.conversation.list.scrollMode,s=r==null?void 0:r.messageStackDirection;return i.createElement(Lm,{scrollMode:o,messageStackDirection:s},i.createElement($m,{...t},e))},vr=u.createContext({onDrop:ge,subscribe:()=>ge}),Kn=({children:e})=>{const t=u.useRef(new Set);return i.createElement(vr.Provider,{value:{onDrop:n=>{var r;if(n.preventDefault(),(r=n.dataTransfer)!=null&&r.files){const o=Array.from(n.dataTransfer.files);o.length>0&&t.current.forEach(s=>s(o))}},subscribe:n=>(t.current.add(n),()=>t.current.delete(n))}},e)},Pm=({onDropFiles:e})=>{const{subscribe:t}=u.useContext(vr);u.useEffect(()=>t(e),[e])};Kn.Consumer=({children:e})=>{const{onDrop:t}=u.useContext(vr);return e({onDrop:t,onDragOver:o=>o.preventDefault()})};const pi=Ee("WindowTitle",{hasWindowTitleReference:!1,isTitlePending:!1,isWindowNameReady:!0,registerWindowTitleReference:()=>ge,registerWindowTitlePending:()=>ge}),Fm=pi.Provider,_i=pi.useContext,Io=()=>{const e=u.useRef(0),[t,n]=u.useState(!1),r=u.useCallback(()=>{let o=!0;return e.current+=1,e.current===1&&n(!0),()=>{o&&(o=!1,e.current=Math.max(0,e.current-1),e.current===0&&n(!1))}},[]);return[t,r]},yr=({children:e})=>{const[t,n]=Io(),[r,o]=Io(),s=!r||t,a=u.useMemo(()=>({hasWindowTitleReference:t,isTitlePending:r,isWindowNameReady:s,registerWindowTitleReference:n,registerWindowTitlePending:o}),[t,r,n,o]);return i.createElement(Fm,{value:a},e)},pn=_i,Ei=({enabled:e,label:t})=>{const{registerWindowTitleReference:n,registerWindowTitlePending:r}=_i(),o=e&&t.trim().length>0;return u.useLayoutEffect(()=>{if(e)return r()},[r,e]),u.useLayoutEffect(()=>{if(o)return n()},[n,o]),{enabled:o,id:o?Ce.WINDOW_TITLE:void 0}},Um=(e,t)=>{const r=(t?kt(e,t):null)??Yd(e)??e;r===e&&!e.hasAttribute("tabindex")&&e.setAttribute("tabindex","-1"),r.focus()},bi=(e,{enabled:t,ready:n,nameReady:r=!0,targetSelector:o})=>{const s=u.useRef(!1);u.useEffect(()=>{if(!t){s.current=!1;return}if(s.current||!e.current||o&&!n)return;const a=Cr(e.current)!=null;if(!o&&!a&&!n)return;let l=!1;const c=()=>{l||s.current||!e.current||(s.current=!0,Um(e.current,o))};if(r)return we(c),()=>{l=!0};const d=setTimeout(()=>we(c),js);return()=>{l=!0,clearTimeout(d)}},[t,n,r,o,e])},Bm=(e,t)=>{const{announcementsEnabled:n}=Ke(),{channelSource:r}=Se(),{isWindowNameReady:o}=pn(),s=r.channel!=null||r.error!=null;bi(e,{enabled:n,ready:s,nameReady:o,targetSelector:t==="messageInput"?Ku:void 0})},Hm=e=>He(e)||cn(e);function Gm(e){return e.isAdminMessage()?e.message==="The channel's custom_type was updated.":!1}function zm(e,t){return e.filter(n=>Ve.isWelcomeMessage(n,t))}const Ci=(e,{previewWelcomeMessages:t,aiAgentUserId:n})=>e.filter(r=>Gm(r)?!1:t.length>0?!Ve.isWelcomeMessage(r,n):!0),Vm=[],vi=()=>{var v,y,b,E,C,S;const{agentPreviewConfigs:e={},aiAgentId:t}=me(),{aiAgentInfo:n,userSession:r}=Me(),{channelSource:o,messageSource:s,state:{input:a,streamAnimation:l}}=Se(),c=e.welcomeMessages??Vm,d=u.useMemo(()=>Ci(s.messages,{previewWelcomeMessages:c,aiAgentUserId:t}),[t,s.messages,c]),m=et(o.channel),f=(y=(v=bs(o.channel,r.userId))==null?void 0:v.nickname)==null?void 0:y.trim(),g=m?(E=(b=o.channel)==null?void 0:b.name)==null?void 0:E.trim():(C=n==null?void 0:n.nickname)==null?void 0:C.trim(),_=f||g||void 0;return{initialized:s.initialized,channelUrl:(S=o.channel)==null?void 0:S.url,agentName:_,isClosed:Le(o.channel),isHandedOff:m,messages:d,filteredMessagesCount:d.length,hasWelcomeMessages:c.length>0,inputDisabled:a.disabled,inputDisabledBy:a.disabledBy,isStreamAnimating:l.isAnimating,subscribeMessageEvents:s.subscribeMessageEvents,currentUserId:r.userId}},Ym=(e={})=>{const{announceScreenEntry:t,announcementsEnabled:n}=Ke(),{initialized:r=!1,channelUrl:o,agentName:s,isClosed:a=!1,messages:l=[],hasWelcomeMessages:c=!1}=e,d=u.useRef(null),m=u.useMemo(()=>l.some(g=>Ie.isAdmin(g)&&Ie.isCSAT(g)),[l]),f=l.length===0&&!c;u.useEffect(()=>{if(!n){d.current=null;return}!r||!o||d.current!==o&&(t({screen:"conversation",agentName:s,isClosed:a,hasCSAT:m,...f?{isEmpty:!0}:{}}),d.current=o)},[s,t,n,o,m,r,a,f])},Wm=()=>{const e=vi();Ym(e)},qm=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}),wo=(e,t,n=Xe.format)=>{const r=ku(e,qm(t)),o="sender"in e?e.sender:void 0,s=e.createdAt!=null&&e.createdAt!==0?n(e.createdAt,t.DATE_FORMAT__MESSAGE_TIMESTAMP):void 0;return{senderName:typeof(o==null?void 0:o.nickname)=="string"&&o.nickname.trim()||void 0,body:r||void 0,time:s}},Km={senderName:!0,body:!0,time:!0},jm=Object.keys(Km),Xm=(e,t)=>jm.every(n=>e[n]===t[n]),Mo=2e3,ko=400,jn=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]},yi=e=>{if(!Ie.isAdmin(e)||!Ie.isCSAT(e))return null;const t=Fu(e);return t?`csat:${t}`:null},Zm=e=>{const t=new Set;for(const n of e){const r=yi(n);r&&t.add(r)}return t},Jm=(e,t)=>{for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r&&jn(r).some(o=>t.includes(o)))return r}},Ln=(e,t)=>e.some(n=>t.includes(n)),Ro=()=>typeof document>"u"?null:document.activeElement instanceof HTMLElement?document.activeElement:null,On=e=>new Map(e.map(({key:t,sendingStatus:n})=>[t,n])),Qm=()=>{const{announceStatus:e,announcementsEnabled:t}=Ke(),{stringSet:n,format:r}=se(),{channelUrl:o,messages:s,isClosed:a,isHandedOff:l,agentName:c,initialized:d,inputDisabled:m,inputDisabledBy:f,isStreamAnimating:g,subscribeMessageEvents:_,currentUserId:v}=vi(),{outgoingMessageStates:y,outgoingMessageStatusSignature:b}=u.useMemo(()=>{if(!v)return{outgoingMessageStates:[],outgoingMessageStatusSignature:""};const X=s.flatMap(K=>{const P=$u(K,v);return!P||!("sendingStatus"in K)?[]:[{key:P,sendingStatus:K.sendingStatus}]});return{outgoingMessageStates:X,outgoingMessageStatusSignature:X.map(({key:K,sendingStatus:P})=>`${K}:${P}`).join(",")}},[v,s]),E=u.useRef({isClosed:!1,isHandedOff:!1,inputDisabled:m,inputDisabledBy:f,outgoingMessageStatuses:On(y)}),C=u.useRef({messages:s,currentUserId:v,inputDisabledBy:f,isStreamAnimating:g,stringSet:n,format:r}),S=u.useRef([]),x=u.useRef(null),w=u.useRef([]),k=u.useRef(new Set),I=u.useRef(new Set),M=u.useRef(!1),O=u.useRef(o);C.current={messages:s,currentUserId:v,inputDisabledBy:f,isStreamAnimating:g,stringSet:n,format:r};const F=()=>C.current.isStreamAnimating||C.current.inputDisabledBy==="ai_responding",Y=()=>{x.current!=null&&(clearTimeout(x.current),x.current=null)},z=(X,K,P)=>{const te=P==null?void 0:P.replaceableForMs;if(X.length===0||!te)return;const de=Date.now();w.current=[...w.current.filter(({replaceableUntil:fe})=>fe>de),{eventKeys:X,parts:K,replaceableUntil:de+te}]},V=()=>S.current.length>0,H=()=>{S.current=[]},W=()=>{const[X,...K]=S.current;if(!X)return!1;S.current=K;const{eventKeys:P,parts:te,dedupeKey:de}=X,fe=Re=>{z(P,Re,{replaceableForMs:P.length>0?Mo:void 0}),e({event:"newMessage",...Re},de?{dedupeKey:de}:void 0)};if(P.length===0)return fe(te),!0;const xe=C.current,Oe=Jm(xe.messages,P);if(Oe){const Re=wo(Oe,xe.stringSet,xe.format);return fe(Re),!0}return fe(te),!0},q=()=>{for(Y();W(););},ce=(X=Mo)=>{Y(),x.current=setTimeout(()=>{if(x.current=null,F())return;const K=Ro(),[P]=S.current;if(!P)return;if(P.focusTarget!==K){S.current=[{...P,focusTarget:K},...S.current.slice(1)],ce(ko);return}W()&&V()&&ce(ko)},X)},_e=(X,K,P)=>{const te={eventKeys:K,parts:X,focusTarget:Ro(),dedupeKey:P?P.dedupeKey??void 0:K[0]},de=K.length===0?-1:S.current.findIndex(({eventKeys:fe})=>Ln(fe,K));de>=0?S.current=S.current.map((fe,xe)=>xe===de?{...te,dedupeKey:P?te.dedupeKey:fe.dedupeKey}:fe):S.current=[...S.current,te],ce()},L=(X,K,P)=>{if(X!=="messagesUpdated"||K.length===0)return!1;const te=Date.now(),de=w.current.find(fe=>fe.replaceableUntil>te&&Ln(fe.eventKeys,K));return de?!Xm(P,de.parts):!1};u.useEffect(()=>{const X=O.current!==o;(!t||!d||X)&&(M.current=!1,I.current.clear(),H(),w.current=[],k.current.clear(),Y(),X&&(O.current=o),!t||!d)||M.current||(M.current=!0,O.current=o,E.current={isClosed:a,isHandedOff:l,inputDisabled:m,inputDisabledBy:f,outgoingMessageStatuses:On(y)},k.current=new Set(s.flatMap(K=>{if(!Ve.isStreaming(K))return[];const P="sender"in K?K.sender:void 0;return(P==null?void 0:P.userId)===C.current.currentUserId?[]:jn(K)})),I.current=Zm(s))},[e,t,o,d,m,a,l,b]),u.useEffect(()=>{const X=(K,P)=>{const te=C.current,de=jn(K),fe=yi(K);if(fe!=null){if(I.current.has(fe))return;I.current.add(fe),e({event:"csatDisplayed"});return}if(Ve.isStreaming(K)){de.forEach(U=>{k.current.add(U)});return}const xe=de.filter(U=>k.current.has(U)),Oe=P==="messagesUpdated"&&xe.length>0;Oe&&xe.forEach(U=>{k.current.delete(U)});const Re=P==="messagesUpdated"&&S.current.some(({eventKeys:U})=>Ln(U,de)),T=wo(K,te.stringSet,te.format),R=L(P,de,T);if(!Oe&&P!=="messagesAdded"&&!Re&&!R)return;const N=R?{dedupeKey:null}:void 0;if(Oe||F()||Re){_e(T,[...new Set([...xe,...de])],N);return}if(R){_e(T,de,N);return}V()&&q();const j=de[0];e({event:"newMessage",...T},j?{dedupeKey:j}:void 0)};return _(K=>{if(!M.current||K.kind==="initialized"||!Uu(K.source))return;const P=C.current.currentUserId;for(const te of K.messages)te&&Pu(te,P)&&X(te,K.kind)})},[e,_]),u.useEffect(()=>{M.current&&(F()||V()&&ce())},[f,g]),u.useEffect(()=>()=>{Y()},[]),u.useEffect(()=>{if(!M.current)return;const X=E.current,K=X.outgoingMessageStatuses;X.outgoingMessageStatuses=On(y),y.some(({key:te,sendingStatus:de})=>{const fe=K.get(te);return fe!==void 0&&fe!=="failed"&&de==="failed"})&&e({event:"sendFailed"})},[e,b]),u.useEffect(()=>{if(!M.current)return;const X=E.current;a&&!X.isClosed&&e({event:"conversationClosed"}),X.isClosed=a},[e,a]),u.useEffect(()=>{if(!M.current)return;const X=E.current;l&&!X.isHandedOff&&e({event:"agentConnected",agentName:c}),X.isHandedOff=l},[c,e,l]),u.useEffect(()=>{if(!M.current)return;const X=E.current;m&&f!=="ai_responding"&&(!X.inputDisabled||X.inputDisabledBy==="ai_responding")&&e({event:"inputDisabled"}),X.inputDisabled=m,X.inputDisabledBy=f},[e,m,f])},ef=()=>{const{channelSource:e}=Se(),t=Os(e.channel);return!(t!=null&&t.user.userId)||!t.user.nickname?null:{userId:t.user.userId,nickname:t.user.nickname}},tf=e=>{const{announceStatus:t,announcementsEnabled:n}=Ke();qc(e??null,r=>{t({event:"typing",agentName:r})},1e4,n)},nf=()=>{const e=ef();tf(e)},Q=({type:e,size:t=24,className:n,color:r})=>{const{icons:o}=wd(),s=o[e];return i.createElement(rf,{className:n},i.createElement(s,{size:t,color:r??h.color.primary.main,flipInRtl:vd.has(e)}))},rf=p.default.span.attrs({"aria-hidden":"true"})`
|
|
80
|
+
`;return n.set(e,s),s},Kd=e=>e?D.css`display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:${e};overflow:hidden;`:"",jd=p.default.span`font-stretch:normal;letter-spacing:normal;${({$variant:e,theme:t})=>qd(e,t.typography)}color:${({$color:e})=>e};${({$maxTextLines:e})=>Kd(e)}`,hn=["a[href]","button:not(:disabled)","input:not(:disabled)","select:not(:disabled)","textarea:not(:disabled)",'[tabindex]:not([tabindex="-1"])'].join(", "),ci=`${hn}, [tabindex="-1"]`,ft=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};async function yr(e){let t=e;t&&(!t.startsWith("http://")&&!t.startsWith("https://")&&(t="https://"+t),window.open(t,"_blank","noopener,noreferrer"))}function Me(e){requestAnimationFrame(()=>{requestAnimationFrame(()=>{e()})})}const Rt=(e,t)=>{for(const n of e.querySelectorAll(t))if(!n.hasAttribute(_r)&&ft(n))return n;return null},ui=e=>{let t=null,n=null;for(const r of e.querySelectorAll(hn))r.hasAttribute(_r)||ft(r)&&(t??(t=r),n=r);return t?{first:t,last:n}:null},Sr=e=>Rt(e,Xu),di=e=>Sr(e)??Rt(e,hn),Xd=e=>{const t=Sr(e);if(t)return t;const n=e.querySelector(Ju);return(n?Rt(n,ci):null)??Rt(e,hn)},jn='[role="dialog"][aria-modal="true"]',Zd=(e,t)=>{const n=new Set(Array.from(e.ownerDocument.querySelectorAll(jn)).filter(o=>o!==e&&(o.contains(e)||e.contains(o)))),r=t==null?void 0:t.closest(jn);return r&&r!==e&&n.add(r),n},Jd=(e,t)=>Array.from(e.ownerDocument.querySelectorAll(jn)).some(n=>n!==e&&!t.has(n)&&!n.contains(e)&&ft(n)),Qd=e=>{const t=di(e)??e;t===e&&mi(e),t.focus()},mi=e=>{e.hasAttribute("tabindex")||e.setAttribute("tabindex","-1")},em=(e,t)=>{const n=ui(e);if(!n){mi(e),e.focus();return}n[t].focus()},vo=(e,t)=>{const n=e.ownerDocument.createElement("span");return n.tabIndex=0,n.setAttribute(_r,Zu),n.style.cssText=["position: fixed","width: 1px","height: 1px","opacity: 0","overflow: hidden","pointer-events: none"].join(";"),n.addEventListener("focus",()=>em(e,t)),n},tm=(e,t)=>{e.key==="Tab"&&(e.defaultPrevented||e.target===t&&(ui(t)||(e.preventDefault(),t.focus())))},nm=(e,t)=>t instanceof HTMLElement?e instanceof Document?t===e.body||t===e.documentElement:!1:!0,pn=(e,t,{nameReady:n=!0}={})=>{const r=u.useRef(0),o=u.useRef(!1);u.useEffect(()=>{if(!e||!t.current){o.current=!1;return}r.current+=1;const s=r.current,a=t.current,l=a.getRootNode(),c=l.activeElement instanceof HTMLElement?l.activeElement:null,d=Zd(a,c);return()=>{c&&Me(()=>{if(r.current!==s)return;const m=l.activeElement;a.isConnected&&m instanceof HTMLElement&&m!==a&&!a.contains(m)&&!nm(l,m)&&m.matches(ci)&&ft(m)||Jd(a,d)||!c.isConnected||!ft(c)||c.focus()})}},[e,t]),u.useEffect(()=>{if(!e||!t.current)return;const s=t.current;let a=!1;const l=()=>{if(a||o.current||!s.isConnected)return;const m=s.getRootNode().activeElement;if(m instanceof HTMLElement&&m!==s&&s.contains(m)&&ft(m)){o.current=!0;return}o.current=!0,Qd(s)};if(n)return Me(l),()=>{a=!0};const c=setTimeout(()=>Me(l),Js);return()=>{a=!0,clearTimeout(c)}},[e,t,n]),u.useEffect(()=>{if(!e||!t.current)return;const s=t.current,a=vo(s,"last"),l=vo(s,"first"),c=d=>tm(d,s);return s.insertBefore(a,s.firstChild),s.appendChild(l),s.addEventListener("keydown",c),()=>{s.removeEventListener("keydown",c),a.remove(),l.remove()}},[e,t])},ot=({style:e,portalContainerId:t,visible:n,onClose:r,children:o,cancelable:s=!0,"aria-label":a,"aria-labelledby":l,"aria-describedby":c})=>{const d=u.useRef(null),{resolvePortalContainer:m}=br();return pn(n,d),dd(n,s?r:ce),n?Ea.createPortal(i.createElement(rm,{onClick:s?r:void 0,style:e},i.createElement(om,{ref:d,role:"dialog","aria-modal":"true","aria-label":a,"aria-labelledby":l,"aria-describedby":c,onClick:f=>f.stopPropagation()},o)),m(t)):null},rm=p.default.div`position:fixed;top:0;left:0;width:100%;height:100%;background:${h.color.overlay.dark};display:flex;justify-content:center;align-items:center;z-index:${it.MODAL};`,om=p.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:${it.MODAL};`,sm=({id:e,children:t})=>i.createElement(im,{id:e},t),im=p.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;`,yo=(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?{}:Ws}:n},am=()=>{const e=`${u.useId()}-`;return(t,n)=>{if(!t)return{props:{},node:null};const r=e+n,o=u.createElement(sm,{id:r,children:t});return{props:{"aria-describedby":r},node:o}}},So=({name:e,mimeType:t,selected:n},r)=>{var s;const o=ze(t??"")?r.A11Y_FILE_IMAGE(e):mn(t??"")?r.A11Y_FILE_VIDEO(e):gs({name:e,mimeType:t})?r.A11Y_FILE_PDF(e):r.A11Y_FILE_DOCUMENT(e);return n?((s=r.A11Y_FILE_SELECTED)==null?void 0:s.call(r,o))??`${o}, selected`:o},lm=e=>t=>{t.repeat||(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())},xt=({onActivate:e})=>({role:"button",tabIndex:0,onClick:e,onKeyDown:lm(e)}),cm=({disabled:e,currentIndex:t,totalCount:n,onNavigate:r})=>o=>{var c;if(e||n<=0)return;let s=null;switch(o.key){case"ArrowRight":case"ArrowDown":s=(t+1)%n;break;case"ArrowLeft":case"ArrowUp":s=(t-1+n)%n;break;default:return}o.preventDefault(),r(s);const a=o.currentTarget.parentElement,l=a==null?void 0:a.querySelectorAll('[role="radio"]');(c=l==null?void 0:l[s])==null||c.focus()},Ao=(e,t,n,r,o,s)=>{let a=-1;return(e||!o&&n===0)&&(a=0),{role:"radio","aria-checked":e,"aria-disabled":t,onKeyDown:cm({disabled:t,currentIndex:n,totalCount:r,onNavigate:s}),tabIndex:a}},oe=()=>{const{stringSet:e}=se(),t=am(),n=(a,l)=>{let c=e.A11Y_HINT_OPEN_FILE,d="of";ze(a??"")&&(c=e.A11Y_HINT_OPEN_IMAGE,d="oi"),l!==void 0&&(d+=l);const m=t(c,d);return{props:m.props,descriptionNode:m.node}},r=a=>({"aria-label":So(a,e)});return{launcher:{button:({isOpened:a,opensConversationList:l})=>{const c=Ku({intent:Yu({isOpened:a,opensConversationList:l}),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";c.hint===e.A11Y_HINT_OPEN_CONVERSATION&&(d="lo"),c.hint===e.A11Y_HINT_OPEN_CONVERSATIONS&&(d="los");const m=t(c.hint,d);return{props:{"aria-label":c.label,...m.props},descriptionNode:m.node}}},messenger:{closeButton:()=>({props:{"aria-label":e.A11Y_CLOSE_MESSENGER},descriptionNode:null}),expandButton:a=>{let l=e.A11Y_EXPAND_MESSENGER;return a&&(l=e.A11Y_COLLAPSE_MESSENGER),{props:{"aria-label":l},descriptionNode:null}},connectionDelayDialog:()=>({props:{"aria-label":e.CONNECTION_DELAY__TITLE},descriptionNode:null})},conversation:{header:{menuButton:()=>{const a=e.A11Y_HINT_OPEN_MENU,l=t(a,"mb");return{props:{"aria-label":e.A11Y_MENU,...l.props},descriptionNode:l.node}},closeConversationButton:()=>{const a=e.A11Y_HINT_CLOSE_CONVERSATION,l=t(a,"cc");return{props:{"aria-label":e.A11Y_CLOSE_CONVERSATION,...l.props},descriptionNode:l.node}},handoffButton:()=>{const a=e.A11Y_HINT_CONNECT_TO_AGENT,l=t(a,"h");return{props:{"aria-label":e.A11Y_CONNECT_AGENT,...l.props},descriptionNode:l.node}},title:(a,l)=>({props:yo(a,l),descriptionNode:null}),memoryIndicator:a=>{let l=e.A11Y_MEMORY_INDICATOR_OFF,c="mof";a&&(l=e.A11Y_MEMORY_INDICATOR_ON,c="mon");const d=t(l,c);return{props:{"aria-label":e.A11Y_MEMORY_INDICATOR_MANAGE,...d.props},descriptionNode:d.node}}},messageInput:{attachFileButton:()=>{const a=e.A11Y_HINT_ATTACH_FILE,l=t(a,"af");return{props:{"aria-label":e.A11Y_ATTACH_FILE,...l.props},descriptionNode:l.node}},sendButton:()=>{const a=e.A11Y_HINT_SEND_MESSAGE,l=t(a,"sm");return{props:{"aria-label":e.A11Y_SEND_MESSAGE,...l.props},descriptionNode:l.node}},textInput:a=>({props:{role:"textbox","aria-label":a,...ed},descriptionNode:null})},suggestedReplies:{item:(a,l)=>{const c=e.A11Y_HINT_SEND_REPLY,d=t(c,`sr${l}`);return{props:{"aria-label":`${e.A11Y_SUGGESTED_REPLY}, ${a}`,...d.props},descriptionNode:d.node}}},feedback:{container:()=>{const a=e.A11Y_HINT_SELECT_RATING,l=t(a,"fb");return{props:l.props,descriptionNode:l.node}},button:(a,l)=>{const c=e.A11Y_HINT_SELECT_RATING,d=t(c,`f${a}`);let m=e.FEEDBACK_BAD;return a==="good"&&(m=e.FEEDBACK_GOOD),{props:{"aria-label":m,...d.props,"aria-pressed":l},descriptionNode:d.node}},optionsBottomSheet:()=>({props:{"aria-label":e.A11Y_FEEDBACK_OPTIONS},descriptionNode:null})},newMessagesButton:()=>{const a=e.A11Y_HINT_VIEW_NEW_MESSAGES,l=t(a,"nm");return{props:{"aria-label":e.A11Y_SCROLL_TO_NEW_MESSAGES,...l.props},descriptionNode:l.node}},scrollToBottomButton:()=>{const a=e.A11Y_HINT_VIEW_NEW_MESSAGES,l=t(a,"sb");return{props:{"aria-label":e.A11Y_SCROLL_TO_BOTTOM,...l.props},descriptionNode:l.node}},startNewConversationButton:({onActivate:a})=>({props:{...xt({onActivate:a}),"aria-label":e.TALK_TO_AGENT},descriptionNode:null}),poweredByLink:()=>({props:{"aria-label":`${e.POWERED_BY} Sendbird`},descriptionNode:null}),retryButton:(a=e.RETRY)=>({props:{"aria-label":a},descriptionNode:null}),file:{label:(a,l,c)=>a?So({name:a,mimeType:l,selected:c},e):"",preview:a=>({props:r(a),descriptionNode:null}),buttonLikePreview:({onActivate:a,...l},c)=>{const d=n(l.mimeType,c);return{props:{...xt({onActivate:a}),...r(l),...d.props},descriptionNode:d.descriptionNode}},removeButton:a=>({props:{"aria-label":e.A11Y_FILE_REMOVE_BUTTON(a)},descriptionNode:null})},csat:{scoresContainer:a=>{const l=e.A11Y_HINT_SELECT_RATING,c=t(l,"cs");return{props:{role:"radiogroup","aria-label":a,...c.props},descriptionNode:c.node}},scoreItem:({score:a,label:l,selected:c,disabled:d,currentIndex:m,totalCount:f,hasSelection:g,onChange:E})=>{var _;const y=l.trim()||l,v=e.A11Y_HINT_SELECT_RATING,b=t(v,`cs${a}`);return{props:{disabled:d,onClick:()=>E(a),...Ao(c,d,m,f,g,C=>E(C+1)),...b.props,"aria-label":((_=e.A11Y_CSAT_RATING_LABEL)==null?void 0:_.call(e,a,y))??`${a} / ${f} — ${y}`},descriptionNode:b.node}},submitButton:a=>({props:{"aria-label":a},descriptionNode:null})},form:{button:a=>({props:{"aria-label":a},descriptionNode:null}),textInput:(a,l,c,d)=>({props:{...d!=null&&d.labelId?{"aria-labelledby":d.labelId}:{"aria-label":a},"aria-required":l,"aria-disabled":c},descriptionNode:null}),numberInput:(a,l,c)=>({props:{"aria-label":a,"aria-required":l,"aria-disabled":c},descriptionNode:null}),singleSelectGroup:a=>{const l={role:"radiogroup"};return a&&(l["aria-label"]=a),{props:l,descriptionNode:null}},singleSelectOption:(a,l,c,d,m,f,g)=>({props:{...Ao(l,c,d,m,f,g),"aria-label":a},descriptionNode:null}),multiSelectOption:(a,l,c)=>({props:{"aria-label":a,"aria-pressed":l,"aria-disabled":c},descriptionNode:null})}},conversationList:{headerTitle:(a,l)=>({props:yo(a,l),descriptionNode:null}),footer:{button:({onActivate:a})=>({props:{...xt({onActivate:a}),"aria-label":e.TALK_TO_AGENT},descriptionNode:null})},item:({agent:a,status:l,time:c,unreadCount:d,onActivate:m})=>{if(!m)return{props:{"aria-label":e.A11Y_CONVERSATION_ITEM(a,l,c,d)},descriptionNode:null};const f=e.A11Y_HINT_OPEN_CONVERSATION,g=t(f,"cli");return{props:{...xt({onActivate:m}),...g.props,"aria-label":e.A11Y_CONVERSATION_ITEM(a,l,c,d)},descriptionNode:g.node}}}}},um=({title:e,description:t,highlightedText:n})=>{const r=mu(t,n);return i.createElement(mm,null,i.createElement(fm,null,i.createElement($,{as:"div",variant:"h1",color:h.themedColor.textHighEmphasis},e),t&&i.createElement(gm,null,i.createElement($,{as:"div",variant:"body3",color:h.themedColor.textMidEmphasis},r.beforeText,r.highlightedText?i.createElement(hm,null,r.highlightedText):null,r.afterText))))},dm=()=>{const{components:e}=_n.useContext(),{stringSet:t}=se(),{messenger:n}=oe(),r=uu(),o=r.showDescription?du(r.remainingTime):"",s=r.showDescription?t.CONNECTION_DELAY__DESCRIPTION(o):"";return i.createElement(ot,{portalContainerId:be.WINDOW,visible:r.visible,onClose:ce,...n.connectionDelayDialog().props},i.createElement(e.Dialog,{title:t.CONNECTION_DELAY__TITLE,description:s,highlightedText:o||void 0}))},_n=Ge({template:dm,components:{Dialog:um}}),mm=p.default.div`width:280px;padding:24px;margin:0 auto;border-radius:4px;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,fm=p.default.div`display:flex;flex-direction:column;`,gm=p.default.div`margin-top:16px;`,hm=p.default.strong`font-weight:700;`,pm=({url:e})=>yr(e),{Provider:_m,Consumer:fi,useContext:ae}=pe("Messenger");function Em({children:e,state:t,enableCloseConversationButton:n=!1,enableExpandButton:r=!0,enableAutoDisconnectInLauncher:o=!0,...s}){const[a,l]=u.useState(!1),[c,d]=u.useState(!1),m={opened:(t==null?void 0:t.opened)??a,setOpened:(t==null?void 0:t.setOpened)??l,expanded:(t==null?void 0:t.expanded)??c,setExpanded:(t==null?void 0:t.setExpanded)??d},{resolveElement:f}=br(),g=u.useCallback(()=>{var v;m.setOpened(!1),(v=f(be.LAUNCHER))==null||v.focus()},[m.setOpened,f]);md(m.opened,g);const{Template:E}=_n.useContext(),y=u.useMemo(()=>{var v;return{...s.handlers,onClickLink:((v=s.handlers)==null?void 0:v.onClickLink)??pm}},[s.handlers]);return i.createElement(Pl,{...s},v=>i.createElement(_m,{value:{...s,...v,state:m,enableCloseConversationButton:n,enableExpandButton:r,enableAutoDisconnectInLauncher:o,handlers:y}},i.createElement(E,null),e))}const gi=/iPad|iPhone|iPod/.test(navigator.userAgent),bm=/Android/.test(navigator.userAgent),Dt=e=>gi||bm;let yt=null,Ln=null;const Cm=(e,t=5e3)=>{yt&&(clearInterval(yt),clearTimeout(Ln));const n=document.title;yt=setInterval(()=>{document.title=document.title===e?n:e},750),Ln=setTimeout(()=>{clearInterval(yt),yt=null,Ln=null,document.title=n},t)},hi=()=>{Promise.resolve().then(()=>require("./cjs/B93o4u0P.cjs")).then(e=>{new Audio(e.default).play().catch(()=>{})})},Ae=D.css`&:focus-visible{outline:2px solid ${h.themedColor.primary};outline-offset:2px;}`,xo=e=>{if(typeof e=="string"||typeof e=="number")return String(e)},En=({visible:e,title:t,description:n,confirmText:r="OK",cancelText:o,onConfirm:s,onCancel:a,onClose:l,"aria-label":c})=>{const d=u.useId(),m=u.useId(),f=c??xo(t)??xo(n),g=c?void 0:t?d:n?m:void 0,E=t&&n?m:void 0,y=()=>{l(),Me(()=>s==null?void 0:s())},v=()=>{l(),Me(()=>a==null?void 0:a())};return i.createElement(ot,{portalContainerId:be.WINDOW,visible:e,onClose:l,"aria-label":f,"aria-labelledby":g,"aria-describedby":E},i.createElement(vm,null,i.createElement(ym,null,t&&i.createElement("div",{id:d},i.createElement($,{variant:"h1",color:h.themedColor.textHighEmphasis},t)),n&&i.createElement(Sm,{id:m},i.createElement($,{variant:"body3",color:h.themedColor.textMidEmphasis},n))),i.createElement(Am,null,o&&i.createElement(To,{onClick:v},i.createElement($,{variant:"button",color:h.themedColor.textHighEmphasis},o)),i.createElement(To,{onClick:y},i.createElement($,{variant:"button",color:h.themedColor.primary},r)))))},vm=p.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};`,ym=p.default.div`margin-bottom:16px;`,Sm=p.default.div`margin-top:16px;`,Am=p.default.div`display:flex;flex-direction:row;justify-content:flex-end;`,To=p.default.button`all:unset;display:flex;justify-content:center;align-items:center;border-radius:4px;cursor:pointer;background-color:transparent;padding:10px 16px;${Ae}`,{Provider:xm,useContext:ke}=pe("MessengerSession"),Tm=u.forwardRef(function({children:e,...t},n){return i.createElement(Ec,{ref:n,...t},r=>i.createElement(Im,{...r},e))}),Im=({children:e,...t})=>{const{chatSDK:n,logger:r,appId:o,aiAgentId:s,agentPreviewConfigs:a,state:l,handlers:c,dispatcher:d,_aiAgentSDK:m}=ae(),{userSessionInfo:f,authenticate:g,userSession:E,aiAgentInfo:y,launcherInfo:v}=t,[b,_]=u.useState(!1),C=u.useRef(null);ht(n,{async onUserJoined(A,w){var k,R,O,z;A.conversation&&A.conversation.type===Ee.ConversationType.PROACTIVE&&w.userId===((k=n.currentUser)==null?void 0:k.userId)&&(r.info("messengerSession.onUserJoined: proactive channel joined",A.url),(O=m.session)==null||O._updateActiveChannel({url:A.url,status:"open",conversationStatus:(R=A.conversation)==null?void 0:R.status}),l.setOpened(!0),wm({sound:document.hidden||!l.opened}),(z=C.current)==null||z.call(C,{channel:A}))}}),u.useEffect(()=>{g().then(({launcher:A})=>{A.auto_open&&!Dt()&&setTimeout(()=>l.setOpened(!0),500)}).catch(A=>{var w;r.error("messengerSession: failed to initialize",A),(w=c==null?void 0:c.onInitializeFailed)==null||w.call(c,A)})},[n,o,s,f==null?void 0:f.userId]),u.useEffect(()=>{const A=()=>_(!0);return d.subscribe(Be.AnonymousSessionTokenExpired,A),()=>d.unsubscribe(Be.AnonymousSessionTokenExpired,A)},[d]);const x=u.useCallback(()=>{t.deauthenticate().finally(()=>window.location.reload())},[t.deauthenticate]);return!E||!y||!v?null:i.createElement(xm,{value:{...t,userSession:E,aiAgentInfo:{...y,...a==null?void 0:a.bot},launcherInfo:{...v,...a==null?void 0:a.launcher},registerOnJoinedProactiveConversation:A=>C.current=A}},e,i.createElement(En,{visible:b,title:"Session timed out",description:"Start a new conversation.",onConfirm:x,onClose:ce}))};function wm({sound:e}){Cm("🔔You have received a new message"),e&&hi()}const un=`@${$e}-focused-channel`,pi=`${Date.now()}-${Math.random().toString(36).slice(2)}`,Mm=()=>{try{const e=localStorage.getItem(un);return e?JSON.parse(e).channelUrl??null:null}catch{return null}},Io=e=>{try{localStorage.setItem(un,JSON.stringify({channelUrl:e,tabId:pi}))}catch{}},wo=()=>{try{const e=localStorage.getItem(un);if(!e)return;JSON.parse(e).tabId===pi&&localStorage.removeItem(un)}catch{}},km=(e,t)=>(u.useEffect(()=>{if(!t||!e)return;const n=()=>Io(e),r=()=>wo();return document.hasFocus()&&Io(e),window.addEventListener("focus",n),window.addEventListener("blur",r),()=>{window.removeEventListener("focus",n),window.removeEventListener("blur",r),wo()}},[t,e]),{isChannelViewedInAnyTab:()=>document.hasFocus()||Mm()===e}),Rm=e=>{const{config:t,chatSDK:n}=ae(),{sdkUser:r}=ke(),o=t.conversation.messageAlertSoundEnabled,{isChannelViewedInAnyTab:s}=km(e,o);ht(n,{onMessageReceived(a,l){if(!o||a.url!==e||s())return;(tt(l)&&l.sender.userId!==(r==null?void 0:r.userId)||l.isAdminMessage()&&!l.silent)&&hi()}})};function Lm(e){return new Promise(t=>{const n=new Image;n.onload=function(){const r=String(n.width),o=String(n.height);URL.revokeObjectURL(n.src),t({width:r,height:o})},n.src=URL.createObjectURL(e)})}async function Om(e){if("file"in e&&e.file instanceof File&&e.file.type.startsWith("image/")){const{width:t,height:n}=await Lm(e.file);return new He.MessageMetaArray({key:ms,value:[t,n]})}}const Nm=({onScrollAfterSendMessage:e})=>{const{agentPreviewConfigs:t,handlers:n}=ae(),r=u.useRef(t==null?void 0:t.agentAttributes);return r.current=t==null?void 0:t.agentAttributes,{onBeforeSendMessage:async o=>{const s=await Om(o),a={...o,metaArrays:s?[s]:void 0},l=Dm(r.current);return l?{...a,data:JSON.stringify(l)}:a},onAfterSendMessage:o=>{var s,a,l;e(),(s=n==null?void 0:n.onMessageSend)==null||s.call(n,o.message),o.sendingStatus===He.SendingStatus.SUCCEEDED?(a=n==null?void 0:n.onCustomEvent)==null||a.call(n,{type:"message-sent-succeeded",data:{message:o}}):o.sendingStatus===He.SendingStatus.PENDING&&((l=n==null?void 0:n.onCustomEvent)==null||l.call(n,{type:"message-sent-pending",data:{message:o}}))}}},Dm=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},dt=50,On=dt-40,{Provider:$m,useContext:_i}=pe("ConversationScroll"),Mo={viewport:0,contentHeight:0,contentSnapshotHeight:0,shouldRecalc:!1,shouldUpdate:!1},Nn=e=>Math.max(0,e.scrollHeight-e.scrollTop-e.clientHeight);function Pm({scrollMode:e,messageStackDirection:t,children:n}){const r=u.useRef(null),o=u.useRef(null),s=u.useRef(0),a=u.useRef(0),l=u.useRef(!1),c=u.useRef(!1),d=u.useRef(null),m=u.useRef(Mo),f=u.useRef(!1),g=u.useRef(null),[E,y]=u.useState(0),[v,b]=u.useState(0),[_,C]=u.useState(!1),[x,A]=u.useState(!1),[w,M]=u.useState(!0),k=I=>{const L=Nn(I);return s.current=L,b(L),L},R=()=>{d.current&&(clearTimeout(d.current),d.current=null)},O=u.useMemo(()=>_||t==="bottom"?"auto":e,[_,t,e]),z=()=>{m.current.contentSnapshotHeight=m.current.contentHeight,m.current.shouldUpdate=!0,m.current.shouldRecalc=!0},Y=()=>{const I=r.current;!I||!m.current.shouldUpdate||y(L=>{m.current.shouldUpdate=!1;const{contentHeight:N,contentSnapshotHeight:K,shouldRecalc:G}=m.current,H=I.clientHeight;if(K>N)return L;const U=P(I,{messageType:"outgoing"});let de=0;if(U){const Pe=U.message.offsetTop-On+H;de=Math.max(0,Pe-N)}else{const Pe=N-K,ne=H-On;de=Math.max(0,Pe-ne)}return L===0||de!==L||G?(m.current.shouldRecalc=!1,de):L})},P=u.useCallback((I,L)=>{const{messageType:N="all"}=L??{},K=Array.from(I.querySelectorAll(`#${$e}-message-item`));let G=K;N==="outgoing"&&(G=K.filter(fe=>fe.getAttribute("data-layout-id")==="outgoingmessage"));const H=G[G.length-1];if(!H)return null;const U=I.getBoundingClientRect(),de=H.getBoundingClientRect(),Pe=I.scrollTop+(de.top-U.top),ne=Pe+H.offsetHeight;return{message:H,scrollTop:Pe,lastMessageBottom:ne}},[]),V=u.useCallback(()=>{const I=r.current;if(!I||O!=="fixed")return;const L=P(I);m.current.contentHeight=(L==null?void 0:L.lastMessageBottom)??I.scrollHeight,!f.current&&m.current.contentSnapshotHeight>0&&z(),c.current?s.current=Nn(I):k(I),Y()},[O,P]),B=u.useCallback(()=>{o.current&&(o.current.disconnect(),o.current=null),R(),m.current=Mo,y(0),b(0),M(!0),s.current=0,l.current=!1,a.current=0,c.current=!1},[]),W=u.useCallback((I=!0)=>{const L=s.current>dt;if(l.current=!1,b(0),!L){Me(()=>{const N=r.current;N&&!l.current&&N.scrollTo({top:N.scrollHeight,behavior:"auto"})});return}c.current||(c.current=!0,M(!1),R()),Me(()=>{const N=r.current;if(!N){c.current=!1,M(!0);return}if(l.current){c.current=!1,k(N),M(!0);return}const K=()=>{if(r.current!==N){c.current=!1,r.current&&k(r.current),M(!0);return}c.current=!1,k(N),M(!0)};if(I&&!d.current){const G=setTimeout(K,500);d.current=G,N.addEventListener("scrollend",()=>{clearTimeout(G),d.current=null,K()},{once:!0})}N.scrollTo({top:N.scrollHeight,behavior:I?"smooth":"auto"}),I||K()})},[]),q=u.useCallback(I=>{I&&(r.current=I,O==="fixed"&&(B(),m.current.viewport=I.clientHeight,o.current=new MutationObserver(()=>{V()}),o.current.observe(I,{childList:!0,subtree:!0})))},[O,V,B]),ie=u.useCallback(()=>{const I=r.current;if(!I)return;const L=P(I,{messageType:"outgoing"});L&&(I.scrollTo({top:L.message.offsetTop-On,behavior:"smooth"}),g.current&&clearTimeout(g.current),g.current=setTimeout(()=>{A(!1)},500))},[P]),_e=(I,L,N)=>{const K=Nn(I);if(N&&K>dt){c.current=!1,l.current=!0,R(),k(I),M(!0),a.current=L;return}s.current=K},Le=(I,L,N)=>{const G=k(I)<=dt;L&&!G&&(l.current=!0,R()),N&&G&&(l.current=!1)},J=I=>{const{scrollTop:L}=I.currentTarget,N=a.current;c.current?_e(I.currentTarget,L,L<N):Le(I.currentTarget,L<N,L>N),a.current=L},T=u.useCallback(()=>{O==="fixed"&&(A(!0),z())},[O]),F=u.useCallback(()=>{O==="fixed"?setTimeout(()=>ie(),300):W()},[O,ie]),Q=u.useCallback(I=>{f.current=I,O==="fixed"?z():l.current||W()},[O,W]),re=u.useCallback(I=>{C(I),I&&(y(0),o.current&&(o.current.disconnect(),o.current=null))},[]),le=u.useCallback(I=>{O==="auto"&&I&&!l.current&&W()},[O,W]),De=!(v<=dt)&&!x,xe=u.useCallback(()=>s.current>dt,[]);return i.createElement($m,{value:{ref:q,state:{bottomSpace:E,isAwayFromBottom:De,isScrollPositionReconciled:w,shouldCountNewMessages:xe},props:{onScroll:J},actions:{scrollToBottom:W,onBeforeMessageSend:T,onAfterMessageSend:F,onStreamingUpdate:Q,onConversationClosed:re,onTypingIndicatorUpdate:le}}},n)}const{Provider:Fm,Context:Um,useContext:Se}=pe("Conversation"),Bm=({children:e})=>{var o;const{channelSource:t}=Se(),n=(o=t.channel)==null?void 0:o.url,{checkForUserActionRequired:r}=Kc(n);return u.useEffect(()=>{var a;const s=(a=t.channel)==null?void 0:a.lastMessage;s&&r(s)},[t.channel,r]),i.createElement(i.Fragment,null,e)},Hm=({channelUrl:e,onClearChannelUrl:t,onNavigateToConversationList:n,shouldMarkAsRead:r,children:o})=>{const{activeChannel:s,refreshActiveChannel:a}=ke(),l=_i(),c=e||(s==null?void 0:s.url);Rm(c);const{onBeforeSendMessage:d,onAfterSendMessage:m}=Nm({onScrollAfterSendMessage:()=>{l.actions.onAfterMessageSend()}}),f=u.useCallback(y=>(l.actions.onBeforeMessageSend(),d(y)),[l.actions,d]),g=u.useCallback(y=>{const v=y.some(b=>We.isStreaming(b));l.actions.onStreamingUpdate(v)},[l.actions.onStreamingUpdate]),E=u.useCallback(async()=>{await a(),e&&(t==null||t())},[a,e,t]);return i.createElement(kc,{key:c,channelUrl:c,onBeforeSendMessage:f,onAfterSendMessage:m,onMessagesUpdated:g,onMessagesReceived:g,onChannelDeleted:E,onConversationClosedStatusChanged:l.actions.onConversationClosed,shouldMarkAsRead:r,shouldCountNewMessages:l.state.shouldCountNewMessages},y=>i.createElement(Fm,{value:{...y,scrollSource:l,goToActiveConversation:E,onNavigateToConversationList:n}},i.createElement(Bm,null,o)))},Ei=({children:e,...t})=>{const{config:n}=Re(),{agentPreviewConfigs:r}=ae(),o=n.conversation.list.scrollMode,s=r==null?void 0:r.messageStackDirection;return i.createElement(Pm,{scrollMode:o,messageStackDirection:s},i.createElement(Hm,{...t},e))},Ar=u.createContext({onDrop:ce,subscribe:()=>ce}),Xn=({children:e})=>{const t=u.useRef(new Set);return i.createElement(Ar.Provider,{value:{onDrop:n=>{var r;if(n.preventDefault(),(r=n.dataTransfer)!=null&&r.files){const o=Array.from(n.dataTransfer.files);o.length>0&&t.current.forEach(s=>s(o))}},subscribe:n=>(t.current.add(n),()=>t.current.delete(n))}},e)},Gm=({onDropFiles:e})=>{const{subscribe:t}=u.useContext(Ar);u.useEffect(()=>t(e),[e])};Xn.Consumer=({children:e})=>{const{onDrop:t}=u.useContext(Ar);return e({onDrop:t,onDragOver:o=>o.preventDefault()})};const bi=pe("WindowTitle",{hasWindowTitleReference:!1,isTitlePending:!1,isWindowNameReady:!0,registerWindowTitleReference:()=>ce,registerWindowTitlePending:()=>ce}),zm=bi.Provider,Ci=bi.useContext,ko=()=>{const e=u.useRef(0),[t,n]=u.useState(!1),r=u.useCallback(()=>{let o=!0;return e.current+=1,e.current===1&&n(!0),()=>{o&&(o=!1,e.current=Math.max(0,e.current-1),e.current===0&&n(!1))}},[]);return[t,r]},xr=({children:e})=>{const[t,n]=ko(),[r,o]=ko(),s=!r||t,a=u.useMemo(()=>({hasWindowTitleReference:t,isTitlePending:r,isWindowNameReady:s,registerWindowTitleReference:n,registerWindowTitlePending:o}),[t,r,n,o]);return i.createElement(zm,{value:a},e)},bn=Ci,vi=({enabled:e,label:t})=>{const{registerWindowTitleReference:n,registerWindowTitlePending:r}=Ci(),o=e&&t.trim().length>0;return u.useLayoutEffect(()=>{if(e)return r()},[r,e]),u.useLayoutEffect(()=>{if(o)return n()},[n,o]),{enabled:o,id:o?be.WINDOW_TITLE:void 0}},Vm=(e,t)=>{const r=(t?Rt(e,t):null)??Xd(e)??e;r===e&&!e.hasAttribute("tabindex")&&e.setAttribute("tabindex","-1"),r.focus({focusVisible:!1})},yi=(e,{enabled:t,ready:n,nameReady:r=!0,targetSelector:o,suppressed:s=!1})=>{const a=u.useRef(!1);u.useEffect(()=>{if(!t){a.current=!1;return}if(a.current||!e.current||s||o&&!n)return;const l=Sr(e.current)!=null;if(!o&&!l&&!n)return;let c=!1;const d=()=>{c||a.current||!e.current||(a.current=!0,Vm(e.current,o))};if(r)return Me(d),()=>{c=!0};const m=setTimeout(()=>Me(d),Js);return()=>{c=!0,clearTimeout(m)}},[t,n,r,o,e,s])},Ym=(e,t)=>{const{announcementsEnabled:n}=Xe(),{channelSource:r}=Se(),{isWindowNameReady:o}=bn(),s=oi(),a=r.channel!=null||r.error!=null;yi(e,{enabled:n,ready:a,nameReady:o,targetSelector:t==="messageInput"?Qu:void 0,suppressed:s})},Wm=e=>ze(e)||mn(e);function qm(e){return e.isAdminMessage()?e.message==="The channel's custom_type was updated.":!1}function Km(e,t){return e.filter(n=>We.isWelcomeMessage(n,t))}const Si=(e,{previewWelcomeMessages:t,aiAgentUserId:n})=>e.filter(r=>qm(r)?!1:t.length>0?!We.isWelcomeMessage(r,n):!0),jm=[],Ai=()=>{var y,v,b,_,C,x;const{agentPreviewConfigs:e={},aiAgentId:t}=ae(),{aiAgentInfo:n,userSession:r}=ke(),{channelSource:o,messageSource:s,state:{input:a,streamAnimation:l}}=Se(),c=e.welcomeMessages??jm,d=u.useMemo(()=>Si(s.messages,{previewWelcomeMessages:c,aiAgentUserId:t}),[t,s.messages,c]),m=nt(o.channel),f=(v=(y=ys(o.channel,r.userId))==null?void 0:y.nickname)==null?void 0:v.trim(),g=m?(_=(b=o.channel)==null?void 0:b.name)==null?void 0:_.trim():(C=n==null?void 0:n.nickname)==null?void 0:C.trim(),E=f||g||void 0;return{initialized:s.initialized,channelUrl:(x=o.channel)==null?void 0:x.url,agentName:E,isClosed:Ne(o.channel),isHandedOff:m,messages:d,filteredMessagesCount:d.length,hasWelcomeMessages:c.length>0,inputDisabled:a.disabled,inputDisabledBy:a.disabledBy,isStreamAnimating:l.isAnimating,subscribeMessageEvents:s.subscribeMessageEvents,currentUserId:r.userId}},Xm=(e={})=>{const{announceScreenEntry:t,announcementsEnabled:n}=Xe(),{initialized:r=!1,channelUrl:o,agentName:s,isClosed:a=!1,messages:l=[],hasWelcomeMessages:c=!1}=e,d=u.useRef(null),m=u.useMemo(()=>l.some(g=>we.isAdmin(g)&&we.isCSAT(g)),[l]),f=l.length===0&&!c;u.useEffect(()=>{if(!n){d.current=null;return}!r||!o||d.current!==o&&(t({screen:"conversation",agentName:s,isClosed:a,hasCSAT:m,...f?{isEmpty:!0}:{}}),d.current=o)},[s,t,n,o,m,r,a,f])},Zm=()=>{const e=Ai();Xm(e)},Jm=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}),Ro=(e,t,n=Je.format)=>{const r=Du(e,Jm(t)),o="sender"in e?e.sender:void 0,s=e.createdAt!=null&&e.createdAt!==0?n(e.createdAt,t.DATE_FORMAT__MESSAGE_TIMESTAMP):void 0;return{senderName:typeof(o==null?void 0:o.nickname)=="string"&&o.nickname.trim()||void 0,body:r||void 0,time:s}},Qm={senderName:!0,body:!0,time:!0},ef=Object.keys(Qm),tf=(e,t)=>ef.every(n=>e[n]===t[n]),Lo=2e3,Oo=400,Zn=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]},xi=e=>{if(!we.isAdmin(e)||!we.isCSAT(e))return null;const t=zu(e);return t?`csat:${t}`:null},nf=e=>{const t=new Set;for(const n of e){const r=xi(n);r&&t.add(r)}return t},rf=(e,t)=>{for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r&&Zn(r).some(o=>t.includes(o)))return r}},Dn=(e,t)=>e.some(n=>t.includes(n)),No=()=>typeof document>"u"?null:document.activeElement instanceof HTMLElement?document.activeElement:null,$n=e=>new Map(e.map(({key:t,sendingStatus:n})=>[t,n])),of=()=>{const{announceStatus:e,announcementsEnabled:t}=Xe(),{stringSet:n,format:r}=se(),{channelUrl:o,messages:s,isClosed:a,isHandedOff:l,agentName:c,initialized:d,inputDisabled:m,inputDisabledBy:f,isStreamAnimating:g,subscribeMessageEvents:E,currentUserId:y}=Ai(),{outgoingMessageStates:v,outgoingMessageStatusSignature:b}=u.useMemo(()=>{if(!y)return{outgoingMessageStates:[],outgoingMessageStatusSignature:""};const J=s.flatMap(T=>{const F=Hu(T,y);return!F||!("sendingStatus"in T)?[]:[{key:F,sendingStatus:T.sendingStatus}]});return{outgoingMessageStates:J,outgoingMessageStatusSignature:J.map(({key:T,sendingStatus:F})=>`${T}:${F}`).join(",")}},[y,s]),_=u.useRef({isClosed:!1,isHandedOff:!1,inputDisabled:m,inputDisabledBy:f,outgoingMessageStatuses:$n(v)}),C=u.useRef({messages:s,currentUserId:y,inputDisabledBy:f,isStreamAnimating:g,stringSet:n,format:r}),x=u.useRef([]),A=u.useRef(null),w=u.useRef([]),M=u.useRef(new Set),k=u.useRef(new Set),R=u.useRef(!1),O=u.useRef(o);C.current={messages:s,currentUserId:y,inputDisabledBy:f,isStreamAnimating:g,stringSet:n,format:r};const z=()=>C.current.isStreamAnimating||C.current.inputDisabledBy==="ai_responding",Y=()=>{A.current!=null&&(clearTimeout(A.current),A.current=null)},P=(J,T,F)=>{const Q=F==null?void 0:F.replaceableForMs;if(J.length===0||!Q)return;const re=Date.now();w.current=[...w.current.filter(({replaceableUntil:le})=>le>re),{eventKeys:J,parts:T,replaceableUntil:re+Q}]},V=()=>x.current.length>0,B=()=>{x.current=[]},W=()=>{const[J,...T]=x.current;if(!J)return!1;x.current=T;const{eventKeys:F,parts:Q,dedupeKey:re}=J,le=xe=>{P(F,xe,{replaceableForMs:F.length>0?Lo:void 0}),e({event:"newMessage",...xe},re?{dedupeKey:re}:void 0)};if(F.length===0)return le(Q),!0;const Oe=C.current,De=rf(Oe.messages,F);if(De){const xe=Ro(De,Oe.stringSet,Oe.format);return le(xe),!0}return le(Q),!0},q=()=>{for(Y();W(););},ie=(J=Lo)=>{Y(),A.current=setTimeout(()=>{if(A.current=null,z())return;const T=No(),[F]=x.current;if(!F)return;if(F.focusTarget!==T){x.current=[{...F,focusTarget:T},...x.current.slice(1)],ie(Oo);return}W()&&V()&&ie(Oo)},J)},_e=(J,T,F)=>{const Q={eventKeys:T,parts:J,focusTarget:No(),dedupeKey:F?F.dedupeKey??void 0:T[0]},re=T.length===0?-1:x.current.findIndex(({eventKeys:le})=>Dn(le,T));re>=0?x.current=x.current.map((le,Oe)=>Oe===re?{...Q,dedupeKey:F?Q.dedupeKey:le.dedupeKey}:le):x.current=[...x.current,Q],ie()},Le=(J,T,F)=>{if(J!=="messagesUpdated"||T.length===0)return!1;const Q=Date.now(),re=w.current.find(le=>le.replaceableUntil>Q&&Dn(le.eventKeys,T));return re?!tf(F,re.parts):!1};u.useEffect(()=>{const J=O.current!==o;(!t||!d||J)&&(R.current=!1,k.current.clear(),B(),w.current=[],M.current.clear(),Y(),J&&(O.current=o),!t||!d)||R.current||(R.current=!0,O.current=o,_.current={isClosed:a,isHandedOff:l,inputDisabled:m,inputDisabledBy:f,outgoingMessageStatuses:$n(v)},M.current=new Set(s.flatMap(T=>{if(!We.isStreaming(T))return[];const F="sender"in T?T.sender:void 0;return(F==null?void 0:F.userId)===C.current.currentUserId?[]:Zn(T)})),k.current=nf(s))},[e,t,o,d,m,a,l,b]),u.useEffect(()=>{const J=(T,F)=>{const Q=C.current,re=Zn(T),le=xi(T);if(le!=null){if(k.current.has(le))return;k.current.add(le),e({event:"csatDisplayed"});return}if(We.isStreaming(T)){re.forEach(G=>{M.current.add(G)});return}const Oe=re.filter(G=>M.current.has(G)),De=F==="messagesUpdated"&&Oe.length>0;De&&Oe.forEach(G=>{M.current.delete(G)});const xe=F==="messagesUpdated"&&x.current.some(({eventKeys:G})=>Dn(G,re)),I=Ro(T,Q.stringSet,Q.format),L=Le(F,re,I);if(!De&&F!=="messagesAdded"&&!xe&&!L)return;const N=L?{dedupeKey:null}:void 0;if(De||z()||xe){_e(I,[...new Set([...Oe,...re])],N);return}if(L){_e(I,re,N);return}V()&&q();const K=re[0];e({event:"newMessage",...I},K?{dedupeKey:K}:void 0)};return E(T=>{if(!R.current||T.kind==="initialized"||!Vu(T.source))return;const F=C.current.currentUserId;for(const Q of T.messages)Q&&Gu(Q,F)&&J(Q,T.kind)})},[e,E]),u.useEffect(()=>{R.current&&(z()||V()&&ie())},[f,g]),u.useEffect(()=>()=>{Y()},[]),u.useEffect(()=>{if(!R.current)return;const J=_.current,T=J.outgoingMessageStatuses;J.outgoingMessageStatuses=$n(v),v.some(({key:Q,sendingStatus:re})=>{const le=T.get(Q);return le!==void 0&&le!=="failed"&&re==="failed"})&&e({event:"sendFailed"})},[e,b]),u.useEffect(()=>{if(!R.current)return;const J=_.current;a&&!J.isClosed&&e({event:"conversationClosed"}),J.isClosed=a},[e,a]),u.useEffect(()=>{if(!R.current)return;const J=_.current;l&&!J.isHandedOff&&e({event:"agentConnected",agentName:c}),J.isHandedOff=l},[c,e,l]),u.useEffect(()=>{if(!R.current)return;const J=_.current;m&&f!=="ai_responding"&&(!J.inputDisabled||J.inputDisabledBy==="ai_responding")&&e({event:"inputDisabled"}),J.inputDisabled=m,J.inputDisabledBy=f},[e,m,f])},sf=()=>{const{channelSource:e}=Se(),t=$s(e.channel);return!(t!=null&&t.user.userId)||!t.user.nickname?null:{userId:t.user.userId,nickname:t.user.nickname}},af=e=>{const{announceStatus:t,announcementsEnabled:n}=Xe();Jc(e??null,r=>{t({event:"typing",agentName:r})},1e4,n)},lf=()=>{const e=sf();af(e)},X=({type:e,size:t=24,className:n,color:r})=>{const{icons:o}=Od(),s=o[e];return i.createElement(cf,{className:n},i.createElement(s,{size:t,color:r??h.color.primary.main,flipInRtl:Td.has(e)}))},cf=p.default.span.attrs({"aria-hidden":"true"})`
|
|
81
81
|
display: inline-flex;
|
|
82
82
|
&:focus {
|
|
83
83
|
outline: none;
|
|
84
84
|
}
|
|
85
|
-
`,
|
|
85
|
+
`,uf=.75,Ti=6,df=Ti*2;let Jn=null;typeof Intl<"u"&&"Segmenter"in Intl&&(Jn=new Intl.Segmenter(void 0,{granularity:"grapheme"}));const mf=e=>Jn?Array.from(Jn.segment(e),t=>t.segment):[...e],ff=e=>{const t=Math.floor(e.length*uf),n=Math.max(0,e.length-Ti);return Math.max(t,n)},Do=(e,t="")=>{if(e.length<df)return{start:e+t,end:""};const n=mf(e),r=ff(n);return{start:n.slice(0,r).join(""),end:n.slice(r).join("")+t}},gf=e=>{const t=e.normalize("NFC").trim(),n=t.lastIndexOf(".");if(!(n>0&&n<t.length-1))return Do(t);const o=t.slice(0,n),s=t.slice(n);return Do(o,s)},Ii=({children:e,...t})=>{const{start:n,end:r}=u.useMemo(()=>gf(e),[e]);return r?i.createElement(hf,null,i.createElement(pf,{...t},n),i.createElement(_f,{...t},r)):i.createElement($,{...t},n)},hf=p.default.span`display:flex;width:100%;min-width:0;overflow:hidden;direction:inherit;`,pf=p.default($)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex-shrink:1;min-width:0;`,_f=p.default($)`flex-shrink:0;white-space:nowrap;`,Tr=({name:e,mimeType:t,type:n="FILE",iconColor:r,iconBackgroundColor:o,onClick:s,selected:a})=>{const{colors:l}=D.useTheme(),{conversation:c}=oe(),d=s?c.file.buttonLikePreview({name:e,mimeType:t,selected:a,onActivate:s}):c.file.preview({name:e,mimeType:t,selected:a});return i.createElement(Ef,{...d.props,$clickable:!!s},i.createElement(Cf,{$bgColor:o??l.base.primary},i.createElement(X,{type:"file-document",size:24,color:r??l.base.primaryContrastContent})),i.createElement(vf,null,i.createElement(Ii,{variant:"button",color:h.themedColor.textHighEmphasis},e),i.createElement($,{color:h.themedColor.textMidEmphasis,variant:"caption3"},n)),d.descriptionNode)},Ef=p.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 ${h.themedColor.textDisabled};background-color:${h.themedColor.bg_50_600};${({$clickable:e})=>e&&bf}`,bf=D.css`cursor:pointer;${Ae}&:hover{background-color:${h.themedColor.bg_100_500};}`,Cf=p.default.div`border-radius:8px;width:40px;height:40px;display:flex;align-items:center;justify-content:center;background-color:${({$bgColor:e})=>e};`,vf=p.default.div`display:flex;flex:1;flex-direction:column;gap:4px;min-width:0;`;function yf({file:e,children:t,onClickFile:n}){const r=n?()=>n(e):void 0;return i.createElement(Sf,null,i.createElement(Tr,{name:e.name,mimeType:e.type,type:or(e.name,e.type),onClick:r}),t)}const Sf=p.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${ee.GAP_GROUPED}px;`,Ke=`${$e}-incoming-msg`,Af=`${$e}-marked-text`;function xf({file:e,onClickMedia:t,onClickMediaFiles:n,children:r}){const{conversation:o}=oe(),s=e.type.startsWith("image"),a=(()=>{if(n)return()=>n({files:[{url:e.url,type:e.type,name:e.name}],index:0});if(t)return()=>t(e)})(),l=a?o.file.buttonLikePreview({name:e.name,mimeType:e.type,onActivate:a}):o.file.preview({name:e.name,mimeType:e.type}),c=()=>s?i.createElement(wf,{src:e.url,alt:"image-message"}):e.type.startsWith("video")?i.createElement(Mf,{controls:!0},i.createElement("source",{src:e.url}),i.createElement("track",{kind:"captions"})):null;if(c){const d={id:`${Ke}-media-body`,...l.props};return i.createElement(Tf,null,i.createElement(If,{...d},c(),l.descriptionNode),r)}return null}const Tf=p.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${ee.GAP_GROUPED}px;`,If=p.default.div`width:${ee.BODY_MAX_WIDTH}px;height:160px;border-radius:12px;overflow:hidden;cursor:pointer;${Z.light`
|
|
86
86
|
background-color: ${h.color.background100};
|
|
87
87
|
`}
|
|
88
|
-
${
|
|
88
|
+
${Z.dark`
|
|
89
89
|
background-color: ${h.color.background400};
|
|
90
90
|
`}
|
|
91
|
-
`,
|
|
91
|
+
`,wf=p.default.img`width:100%;height:100%;object-fit:cover;`,Mf=p.default.video`width:100%;height:100%;object-fit:cover;`,at=({className:e,children:t,size:n=26})=>i.createElement(kf,{className:e,$size:n},t??i.createElement(X,{type:"spinner",size:n})),kf=p.default.div`display:flex;align-items:center;justify-content:center;width:${({$size:e})=>Ve(e)};height:${({$size:e})=>Ve(e)};animation:1s infinite linear;animation-name:rotate;@keyframes rotate{from{transform:rotate(0);}to{transform:rotate(360deg);}}`,wi=({images:e,isPending:t=!1,onClickImage:n})=>{const{conversation:r}=oe(),o=e.length;if(o===0)return null;const s=Nl(o),a=!!n&&!t;return i.createElement(Lf,{$width:ee.BODY_MAX_WIDTH,$columns:s},e.map((l,c)=>{const{columnSpan:d}=Dl({index:c,itemCount:o}),m=l.name||"",f=()=>{t||n==null||n(c)},g=l.type??"image/*",E=a?r.file.buttonLikePreview({name:m,mimeType:g,onActivate:f},c):r.file.preview({name:m,mimeType:g});return i.createElement(Of,{key:l.url,$clickable:a,$itemSpan:d,$isPending:t,...E.props},i.createElement(Rf,{src:l.url,alt:l.name||""}),t&&i.createElement(Nf,null),E.descriptionNode)}))},Rf=({src:e,alt:t})=>{const[n,r]=u.useState(!1),[o,s]=u.useState(!1);return i.createElement(i.Fragment,null,!n&&!o&&i.createElement(Df,null,i.createElement(at,{size:20},i.createElement(X,{type:"spinner",color:"textLowEmphasis",size:20}))),o&&i.createElement($f,null,i.createElement(X,{type:"photo",color:"textLowEmphasis",size:24})),!o&&i.createElement(Pf,{src:e,alt:t,$loaded:n,onLoad:()=>r(!0),onError:()=>s(!0)}))},Lf=p.default.div`display:grid;grid-template-columns:repeat(${({$columns:e})=>e},1fr);width:${({$width:e})=>e}px;gap:2px;border-radius:16px;overflow:hidden;`,Of=p.default.div`position:relative;width:100%;aspect-ratio:1;overflow:hidden;cursor:${e=>e.$clickable?"pointer":"default"};${Z.light`
|
|
92
92
|
background-color: ${h.color.background100};
|
|
93
93
|
`}
|
|
94
|
-
${
|
|
94
|
+
${Z.dark`
|
|
95
95
|
background-color: ${h.color.background400};
|
|
96
96
|
`}
|
|
97
97
|
${e=>e.$itemSpan&&e.$itemSpan>1&&`
|
|
@@ -111,19 +111,19 @@
|
|
|
111
111
|
}
|
|
112
112
|
`}
|
|
113
113
|
}
|
|
114
|
-
`,
|
|
114
|
+
`,Nf=p.default.div`position:absolute;top:0;left:0;width:100%;height:100%;background-color:${h.color.overlay.dark};pointer-events:none;`,Mi=p.default.div`display:flex;align-items:center;justify-content:center;`,Df=p.default(Mi)`position:absolute;inset:0;`,$f=p.default(Mi)`position:absolute;inset:0;${Z.light`
|
|
115
115
|
background-color: ${h.color.background200};
|
|
116
116
|
`}
|
|
117
|
-
${
|
|
117
|
+
${Z.dark`
|
|
118
118
|
background-color: ${h.color.background500};
|
|
119
119
|
`}
|
|
120
|
-
`,
|
|
120
|
+
`,Pf=p.default.img`position:absolute;inset:0;width:100%;height:100%;object-fit:cover;opacity:${({$loaded:e})=>e?1:0};transition:opacity 0.3s ease;`,Ff=({files:e,children:t,onClickMedia:n,onClickMediaFiles:r})=>{const o=s=>{const a=e[s];a&&(r?r({files:e,index:s}):n&&n({url:a.url,type:a.type||"image/*"}))};return i.createElement(Uf,null,i.createElement(wi,{images:e,onClickImage:o}),t)},Uf=p.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${ee.GAP_GROUPED}px;`,Bf="✱",ki=e=>{const t=new RegExp(`(\`+)([^\`]+?)\\1|(${Bf}+)`,"g");return e.replace(t,(n,r,o,s)=>r?n:s?`<span id=${Af} aria-label="masked-text">${s}</span>`:n)},Hf=e=>e.replace(/\*\*(.*?)\*\*/g,"<b>$1</b>"),$o=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)}}},Gf=u.lazy(async()=>({default:(await Promise.resolve().then(()=>require("./cjs/VvejebHE.cjs"))).MarkdownText})),Po=typeof __SBA_USE_SYNTAX_HIGHLIGHT__>"u"||__SBA_USE_SYNTAX_HIGHLIGHT__?u.lazy(async()=>({default:(await Promise.resolve().then(()=>require("./cjs/DlvEEpWX.cjs"))).CodeBlock})):null;function zf(e){var o,s;const t=e.maxBodyWidth??ee.BODY_MAX_WIDTH,n=u.useMemo(()=>Ta(e.message,ki),[e.message]),r={id:`${Ke}-text-body`,$maxWidth:t,$color:(o=e.customStyle)==null?void 0:o.bubbleContentColor,$bgColor:(s=e.customStyle)==null?void 0:s.bubbleBackgroundColor,$surface:e.surface??"bubble"};return n.length===0?e.children?i.createElement(Fo,{...r},e.children):null:i.createElement(Fo,{...r},n.map((a,l)=>a.type==="text"?i.createElement(Uo,{key:l,variant:"body3"},i.createElement(kt,{fallback:a.value},i.createElement(Gf,{onClickImage:c=>{var d;return(d=e.onClickMedia)==null?void 0:d.call(e,{url:c,type:"image/*"})},onClickLink:e.onClickLink},a.value))):a.type==="code"?Po?i.createElement(kt,{key:l,fallback:i.createElement(Uo,{variant:"body3"},a.value)},i.createElement(Po,{code:a.value,language:a.language})):i.createElement(Vf,{key:l},i.createElement("code",null,a.value)):null),e.children)}const Fo=p.default.div`display:flex;flex-direction:column;min-width:0;max-width:min(${({$maxWidth:e})=>e}px,100%);${({theme:e,$color:t,$bgColor:n,$surface:r})=>D.css`
|
|
121
121
|
color: ${t||e.colors.messageIncoming.text};
|
|
122
122
|
${r==="bubble"?D.css`background-color:${n||e.colors.messageIncoming.background};border-radius:12px;overflow:hidden;padding:12px 0;`:D.css`background-color:transparent;border-radius:0;overflow:visible;padding:0;`}
|
|
123
123
|
`}
|
|
124
124
|
transition: max-width 0.3s;
|
|
125
125
|
overflow-wrap: break-word;
|
|
126
|
-
|
|
126
|
+
`,Uo=p.default($)`align-items:flex-start;line-height:140%;white-space:pre-wrap;padding:0 12px;`,Vf=p.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 Ri({id:e,src:t,size:n=56,onClick:r,style:o,...s}){return i.createElement(Yf,{id:e,tabIndex:r?0:void 0,onClick:r,$size:Ve(n),style:o,...s},t?i.createElement(Wf,{src:t,alt:""}):i.createElement(X,{type:"user",size:n}))}const Yf=p.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:${h.themedColor.bg_100_500};&:focus{outline:none;}${Ae}`,Wf=p.default.img`object-fit:cover;width:100%;height:100%;position:absolute;`,qf=({sender:e,isBotMessage:t})=>{const n=`${Ke}-sender-avatar`;return t&&!e.profileUrl?i.createElement(Kf,{id:n},i.createElement(X,{type:"delight",size:"100%"})):i.createElement(Ri,{id:n,size:ee.AVATAR_SIZE,src:e.profileUrl})},Kf=p.default.div`flex-shrink:0;width:${ee.AVATAR_SIZE}px;height:${ee.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;}}`,jf=({sender:e})=>i.createElement(Xf,{id:`${Ke}-sender-name`,variant:"caption1",color:h.themedColor.textMidEmphasis},e.nickname),Xf=p.default($)`text-align:start;width:100%;box-sizing:border-box;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding-block:5px;padding-inline:0 7px;`,Zf=({createdAt:e})=>{const{stringSet:t,format:n}=se();return e?i.createElement($,{id:`${Ke}-sent-time`,variant:"caption4",color:h.themedColor.textLowEmphasis},n(e,t.DATE_FORMAT__MESSAGE_TIMESTAMP)):null},Li="(prefers-reduced-motion: reduce)",Jf=()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(Li).matches,Oi=()=>{const[e,t]=u.useState(Jf);return u.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const n=window.matchMedia(Li);t(n.matches);const r=o=>{t(o.matches)};return typeof n.addEventListener=="function"?(n.addEventListener("change",r),()=>{n.removeEventListener("change",r)}):(n.addListener(r),()=>{n.removeListener(r)})},[]),e},Qf=({thinkingMessage:e,customStyle:t})=>{const n=Oi();return e?i.createElement(ng,{$prefersReducedMotion:n},i.createElement(rg,null,e),!n&&i.createElement(og,null)):i.createElement(eg,{$bgColor:t==null?void 0:t.bubbleBackgroundColor},[0,1,2].map(r=>i.createElement(tg,{key:r,$color:t==null?void 0:t.bubbleContentColor,$prefersReducedMotion:n})))},eg=p.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};`,tg=p.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;}`,ng=p.default.div.attrs({id:`${Ke}-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
|
+
`,rg=p.default($).attrs({variant:"body3"})`
|
|
139
139
|
white-space: pre-wrap;
|
|
140
140
|
word-break: break-word;
|
|
141
141
|
color: ${h.themedColor.textHighEmphasis};
|
|
142
|
-
`,
|
|
143
|
-
`,
|
|
142
|
+
`,og=p.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=qr(e.colors.base.background,.5),n=qr(e.colors.base.background,0);return`linear-gradient(90deg, ${n} 0%, ${t} 30%, ${t} 60%, ${n} 100%)`}};
|
|
143
|
+
`,sg=({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 i.createElement(ig,{id:`${Ke}-ext-cta-button`,onClick:r},i.createElement(ag,{variant:"button"},n.label))},ig=p.default.button.attrs({type:"button"})`
|
|
144
144
|
all: unset;
|
|
145
145
|
display: flex;
|
|
146
146
|
width: 100%;
|
|
@@ -152,12 +152,12 @@
|
|
|
152
152
|
padding: 8px;
|
|
153
153
|
color: ${h.themedColor.textHighEmphasis};
|
|
154
154
|
background-color: ${h.color.background50};
|
|
155
|
-
${
|
|
155
|
+
${Z.dark`
|
|
156
156
|
background-color: ${h.color.ondark.textDisabled};
|
|
157
157
|
`}
|
|
158
158
|
|
|
159
159
|
${Ae}
|
|
160
|
-
`,
|
|
160
|
+
`,ag=p.default($)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,lg=e=>i.createElement(i.Fragment,null),cg=({extendedMessagePayload:e,onClickCitation:t=n=>yr(n.link)})=>{const{stringSet:n}=se(),{theme:r}=fr(),o=e==null?void 0:e.citations;return!o||o.length===0?null:i.createElement(ug,{id:`${Ke}-ext-citation`},i.createElement(dg,{variant:"caption1",color:r.colors.messageIncoming.text},n.CITATION_SOURCE_TITLE),i.createElement(mg,null,o.map((s,a)=>i.createElement(gg,{key:`${s.embedding_id}-${a}`,onClick:()=>t(s)},i.createElement(X,{type:"source",size:16,color:r.colors.messageIncoming.text}),i.createElement(fg,{variant:"body3",color:r.colors.messageIncoming.text},s.title)))))},ug=p.default.div`display:flex;flex-direction:column;gap:8px;border-radius:8px;padding:8px 12px 6px;`,dg=p.default($)`opacity:0.5;`,mg=p.default.div`display:flex;flex-direction:column;gap:8px;`,fg=p.default($)`text-decoration:underline;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,gg=p.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
|
+
`,hg=e=>i.createElement(i.Fragment,null),pg=({visible:e,onClose:t,children:n,"aria-label":r})=>i.createElement(ot,{portalContainerId:be.WINDOW,visible:e,onClose:t,"aria-label":r},i.createElement(Cg,null,n)),_g=({onClick:e,destructive:t,icon:n,initialFocus:r,children:o})=>i.createElement(Eg,{onClick:e,$destructive:t,"data-sb-initial-focus":r?"true":void 0},n&&i.createElement(bg,null,i.createElement(X,{type:n,size:24,color:h.themedColor.primary})),o),et=Object.assign(pg,{ActionItem:_g}),Eg=p.default.button`all:unset;display:flex;align-items:center;gap:24px;width:100%;padding:12px 24px;cursor:pointer;color:${({$destructive:e})=>e?h.themedColor.error:h.themedColor.textHighEmphasis};${Ae}`,bg=p.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,Cg=p.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};`,Qn=e=>`${e}-filled`,vg=e=>e==="good"?Ee.AIAgentMessageFeedbackRating.GOOD:Ee.AIAgentMessageFeedbackRating.BAD,Ir=D.css`&:hover{opacity:0.8;}&:active{opacity:0.6;}`,qt={good:{onlight:h.color.secondary.dark,ondark:h.color.secondary.light},bad:{onlight:h.color.error.dark,ondark:h.color.error.light}},yg={good:h.themedColor.secondary,bad:h.themedColor.error},Ni=e=>D.css`color:${qt[e].onlight};border-color:${qt[e].onlight};${Z.dark`
|
|
176
|
+
color: ${qt[e].ondark};
|
|
177
|
+
border-color: ${qt[e].ondark};
|
|
178
178
|
`}
|
|
179
|
-
`,
|
|
179
|
+
`,Sg=({visible:e,onClose:t,isEdit:n,initialRating:r,initialComment:o="",onSubmit:s,isCommentEnabled:a=!1})=>{const{stringSet:l}=se(),{conversation:c}=oe(),{rootElement:d}=ii(),m=st(d),[f,g]=u.useState(r),[E,y]=u.useState(o),[v,b]=u.useState(!1),_=u.useRef(!1),C=f??r??"good",x=c.feedback;u.useLayoutEffect(()=>{e?(g(r),y(o)):(g(void 0),y(""))},[e,r,o]),u.useEffect(()=>{if(!e)return;const k=O=>{const z=O;z.metaKey||z.altKey||z.ctrlKey||(_.current=!0)},R=()=>{_.current=!1,b(!1)};return m.addEventListener("keydown",k),m.addEventListener("pointerdown",R),()=>{m.removeEventListener("keydown",k),m.removeEventListener("pointerdown",R)}},[m,e]);const A=()=>{f&&(s({rating:f,comment:E.trim()||void 0}),t())},w=()=>{t()};if(!e)return null;const M={feedback:x.container()};return i.createElement(ot,{portalContainerId:be.WINDOW,visible:e,onClose:w,"aria-label":l.FEEDBACK_TITLE},i.createElement(Ag,null,i.createElement(xg,null,i.createElement($,{variant:"h2",color:h.themedColor.textHighEmphasis},l.FEEDBACK_TITLE)),i.createElement(Tg,null,i.createElement(Ig,{...M.feedback.props},["good","bad"].map(k=>{const R=f===k,O=k==="good"?l.FEEDBACK_GOOD:l.FEEDBACK_BAD,z=x.button(k,R);return i.createElement(u.Fragment,{key:k},i.createElement(wg,{type:"button",$selected:R,$rating:k,...z.props,onClick:()=>g(k),"data-sb-initial-focus":k===C?"true":void 0},i.createElement(X,{type:R?Qn(k):k,size:24,color:"currentColor"}),i.createElement($,{variant:"caption1",color:"currentColor"},O)),z.descriptionNode)}),M.feedback.descriptionNode),a&&i.createElement(Mg,null,i.createElement($,{variant:"caption3",color:h.themedColor.textHighEmphasis},l.FEEDBACK_COMMENT_LABEL),i.createElement(kg,{placeholder:l.FEEDBACK_COMMENT_PLACEHOLDER,value:E,onChange:k=>y(k.target.value),onFocus:()=>b(_.current),onBlur:()=>b(!1),maxLength:100,$focusVisible:v,"data-focus-visible":v?"true":"false"}))),i.createElement(Rg,null,i.createElement(Lg,{onClick:w},i.createElement($,{variant:"button",color:h.themedColor.textHighEmphasis},l.FEEDBACK_CANCEL)),i.createElement(Og,{onClick:A,disabled:!f},i.createElement($,{variant:"button"},n?l.FEEDBACK_SAVE:l.FEEDBACK_SUBMIT)))))},Ag=p.default.div`width:280px;background-color:${({theme:e})=>e.colors.base.modalContentBackground};border-radius:12px;overflow:hidden;`,xg=p.default.div`padding:24px;`,Tg=p.default.div`padding-inline:24px;display:flex;flex-direction:column;gap:24px;`,Ig=p.default.div`display:flex;gap:4px;`,wg=p.default.button`width:114px;height:64px;border-radius:12px;border:1px solid ${h.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:${h.themedColor.textLowEmphasis};background-color:transparent;${({$selected:e,$rating:t})=>e&&Ni(t)}${Ir}`,Mg=p.default.label`display:flex;flex-direction:column;gap:6px;`,kg=p.default.textarea`font-family:inherit;font-size:12px;line-height:16px;border:1px solid ${h.themedColor.textDisabled};border-radius:4px;padding:6px 12px;color:${h.themedColor.textHighEmphasis};background-color:${h.themedColor.textLowEmphasisInverse};resize:none;field-sizing:content;min-height:28px;max-height:118px;overflow-y:auto;&::placeholder{color:${h.themedColor.textLowEmphasis};}&:focus{outline:none;}${({$focusVisible:e})=>e&&D.css`
|
|
180
180
|
outline: 2px solid ${h.themedColor.primary};
|
|
181
181
|
outline-offset: 2px;
|
|
182
182
|
`}
|
|
183
|
-
`,
|
|
183
|
+
`,Rg=p.default.div`padding-inline:24px;padding-block:16px;display:flex;justify-content:flex-end;gap:4px;`,Di=p.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;`,Lg=p.default(Di)`background-color:transparent;${Ir}`,Og=p.default(Di)`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};}`,Ng=({isBotMessage:e,isConversationClosed:t,isStreaming:n,isFeedbackEnabled:r,isFeedbackCommentEnabled:o,extendedMessagePayload:s,onFeedbackUpdate:a})=>{const{stringSet:l}=se(),{conversation:c}=oe(),[d,m]=u.useState(!1),[f,g]=u.useState(!1),[E,y]=u.useState(void 0),[v,b]=u.useState(""),_=u.useRef(null),C=u.useRef(null),x=u.useRef(null),A=u.useRef(!1),w=c.feedback,M=s==null?void 0:s.feedback,k=(M==null?void 0:M.rating)??"none";if(k!=="none"?!1:!!(n||!e||!r||(s==null?void 0:s.bot_message_type)!=="generated"||t))return null;const O=q=>{q&&Me(()=>{const ie=q==="good"?_.current:C.current;ie==null||ie.focus()})},z=({restoreTrigger:q=!0}={})=>{g(!1),q&&O(x.current)},Y=q=>{k==="none"?(y(q),b(""),m(!0)):(x.current=q,g(!0))},P=()=>{a==null||a(null),z()},V=()=>{A.current=!0,z({restoreTrigger:!1}),y(M==null?void 0:M.rating),b((M==null?void 0:M.comment)??""),m(!0)},B=q=>{A.current=!1,a==null||a(q),m(!1),O(x.current)},W=()=>{m(!1),A.current&&(A.current=!1,g(!0))};return t&&k!=="none"?i.createElement(Bo,{role:"presentation",$horizontal:!0},i.createElement(Dg,null,i.createElement(X,{type:Qn(k),size:12,color:yg[k]})),(M==null?void 0:M.comment)&&i.createElement(Ho,{variant:"caption2",style:{lineHeight:"16px"}},M.comment)):i.createElement(i.Fragment,null,i.createElement(Bo,{role:"presentation"},i.createElement($g,{role:"presentation"},["good","bad"].map(q=>{const ie=k===q,_e=w.button(q,ie);return i.createElement(u.Fragment,{key:q},i.createElement(Pg,{$selected:ie,$rating:q,ref:q==="good"?_:C,..._e.props,onClick:()=>Y(q)},i.createElement(X,{type:ie?Qn(q):q,size:14,color:"currentColor"})),_e.descriptionNode)})),k!=="none"&&(M==null?void 0:M.comment)&&i.createElement(Ho,{variant:"caption2"},M.comment)),i.createElement(et,{visible:f,onClose:z,...w.optionsBottomSheet().props},i.createElement(et.ActionItem,{onClick:V,initialFocus:!0},l.FEEDBACK_EDIT),i.createElement(et.ActionItem,{onClick:P,destructive:!0},l.FEEDBACK_REMOVE)),i.createElement(Sg,{visible:d,onClose:W,isEdit:k!=="none",initialRating:E,initialComment:v,onSubmit:B,isCommentEnabled:o}))},Bo=p.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:${ee.BODY_MAX_WIDTH}px;`,Dg=p.default.div`padding:2px;flex-shrink:0;display:flex;align-items:center;`,$g=p.default.div`display:flex;gap:2px;`,Pg=p.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:${h.themedColor.textMidEmphasis};border:1px solid ${h.color.background200};background-color:transparent;${Z.dark`
|
|
184
184
|
border: 1px solid ${h.color.background400};
|
|
185
185
|
`}
|
|
186
186
|
|
|
187
|
-
${({$selected:e,$rating:t})=>e&&
|
|
187
|
+
${({$selected:e,$rating:t})=>e&&Ni(t)}
|
|
188
188
|
|
|
189
|
-
${
|
|
190
|
-
`,
|
|
189
|
+
${Ir}
|
|
190
|
+
`,Ho=p.default($)`color:${h.themedColor.textMidEmphasis};${Z.dark`
|
|
191
191
|
color: ${h.themedColor.textHighEmphasis};
|
|
192
192
|
`}
|
|
193
|
-
`,
|
|
193
|
+
`,wr=D.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;${Ae}&:disabled{cursor:not-allowed;}`,Go=p.default.button`${wr};background-color:${h.themedColor.primary};color:${h.themedColor.textHighEmphasis};&:hover:not(:disabled){opacity:0.9;}`,Fg=p.default.button`${wr};color:${h.themedColor.primary};${Z.light`
|
|
194
194
|
background-color: ${h.color.background50};
|
|
195
195
|
`};
|
|
196
|
-
${
|
|
196
|
+
${Z.dark`
|
|
197
197
|
background-color: ${h.color.background700};
|
|
198
198
|
`};
|
|
199
199
|
|
|
200
200
|
&:hover:not(:disabled) {
|
|
201
201
|
opacity: 0.9;
|
|
202
202
|
}
|
|
203
|
-
`,
|
|
203
|
+
`,Ug=p.default.button`${wr};background-color:transparent;color:${h.themedColor.textHighEmphasis};&:hover:not(:disabled){opacity:0.7;}`,Bg=e=>{switch(e){case"primary":return Go;case"secondary":return Fg;case"clear":return Ug;default:return Go}},Hg=p.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);}}`,Gg=({children:e,onClick:t,variant:n="primary",disabled:r=!1,loading:o=!1,className:s,...a})=>{const l=()=>{switch(n){case"primary":return h.themedColor.textHighEmphasisInverse;case"secondary":return h.themedColor.primary;case"clear":return h.themedColor.textHighEmphasis;default:return h.themedColor.textHighEmphasisInverse}},c=Bg(n);return i.createElement(c,{onClick:t,disabled:r||o,className:s,...a},o?i.createElement(Hg,null,i.createElement(X,{type:"spinner",size:22,color:l()})):i.createElement($,{variant:"button",color:l()},e))},zg=({children:e,className:t,style:n,id:r,role:o})=>i.createElement($,{variant:"caption4",color:h.themedColor.error,className:t,style:n,id:r,role:o},e),Vg=({id:e,children:t,className:n,style:r,required:o,"aria-hidden":s})=>{const{stringSet:a}=se();return i.createElement($,{id:e,variant:"caption3",color:h.themedColor.textMidEmphasis,className:n,style:r,"aria-hidden":s},t,!o&&i.createElement("span",{style:{color:h.themedColor.textLowEmphasis}},` (${a.OPTIONAL})`))},Yg=({value:e,onChange:t,placeholder:n,error:r=!1,submitted:o=!1,className:s,disabled:a=!1,max:l,...c})=>{const d=f=>{const E=f.target.value.replace(/[^0-9.-]/g,""),y=E.split("."),b=y.length>1?y[0]+"."+y.slice(1).join("").replace(/\./g,""):E;if(f.target.value=b,b===""||b==="-")t==null||t(null);else{const _=Number(b);if(!isNaN(_)){if(l!==void 0&&_>l)return;t==null||t(_)}}},m=e==null?"":String(e);return i.createElement(Xg,{type:"text",value:m,onChange:d,placeholder:n,className:s,disabled:a||o,inputMode:"decimal",$error:r,$submitted:o,...c})},Wg=D.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;${Ae}&::placeholder{color:${h.themedColor.textLowEmphasis};}&::-webkit-inner-spin-button,&::-webkit-outer-spin-button{-webkit-appearance:none;margin:0;}`,qg=D.css`color:${h.themedColor.textHighEmphasis};border:1px solid transparent;cursor:not-allowed;${Z.light`
|
|
204
204
|
background-color: ${h.color.ondark.textMidEmphasis};
|
|
205
205
|
`}
|
|
206
|
-
${
|
|
206
|
+
${Z.dark`
|
|
207
207
|
background-color: ${h.color.onlight.textLowEmphasis};
|
|
208
208
|
`}
|
|
209
209
|
|
|
210
210
|
&::placeholder {
|
|
211
211
|
color: ${h.themedColor.textLowEmphasis};
|
|
212
212
|
}
|
|
213
|
-
`,
|
|
213
|
+
`,Kg=D.css`border:1px solid ${h.themedColor.error};color:${h.themedColor.textHighEmphasis};${Z.light`
|
|
214
214
|
background-color: ${h.color.background50};
|
|
215
215
|
`}
|
|
216
|
-
${
|
|
216
|
+
${Z.dark`
|
|
217
217
|
background-color: ${h.color.onlight.textLowEmphasis};
|
|
218
218
|
`}
|
|
219
|
-
`,
|
|
219
|
+
`,jg=D.css`border:1px solid ${h.themedColor.textDisabled};color:${h.themedColor.textHighEmphasis};${Z.light`
|
|
220
220
|
background-color: ${h.color.background50};
|
|
221
221
|
`}
|
|
222
|
-
${
|
|
222
|
+
${Z.dark`
|
|
223
223
|
background-color: ${h.color.onlight.textLowEmphasis};
|
|
224
224
|
`}
|
|
225
225
|
|
|
226
226
|
&:focus {
|
|
227
227
|
border-color: ${h.themedColor.primary};
|
|
228
228
|
}
|
|
229
|
-
`,
|
|
229
|
+
`,Xg=p.default.input`${Wg}${({$error:e,$submitted:t})=>t?qg:e?Kg:jg}`,Zg=e=>{if(e.multiple){const{value:t=[],onChange:n,maxSelect:r,submitted:o=!1}=e;return{selectedValues:t,handleOptionClick:a=>{if(o)return;if(t.includes(a)){const c=t.filter(d=>d!==a);n==null||n(c)}else{if(r&&t.length>=r)return;const c=[...t,a];n==null||n(c)}}}}else{const{value:t,onChange:n,submitted:r=!1}=e;return{selectedValues:t?[t]:[],handleOptionClick:s=>{r||t!==s&&(n==null||n(s))}}}},$i=e=>{const{options:t,submitted:n=!1,error:r=!1,className:o,groupLabel:s}=e,{conversation:a}=oe(),l=e.multiple===!0,{selectedValues:c,handleOptionClick:d}=Zg(e),m=t.some(f=>c.includes(f.value));return i.createElement(Qg,{className:o,...l?void 0:a.form.singleSelectGroup(s).props},t.map((f,g)=>{const E=c.includes(f.value),y=s?`${s}, ${f.label}`:f.label;return i.createElement(ih,{key:f.value,type:"button",$active:E,$submitted:n,$error:r,...(l?a.form.multiSelectOption(y,E,n):a.form.singleSelectOption(y,E,n,g,t.length,m,v=>{const b=t[v];b&&d(b.value)})).props,disabled:n,onClick:()=>d(f.value)},i.createElement($,{variant:"caption1",color:Jg(E,n)},f.label))}))},Jg=(e,t)=>t?e?h.themedColor.textHighEmphasis:h.themedColor.textDisabled:e?h.themedColor.primary:h.themedColor.textMidEmphasis,Qg=p.default.div`display:flex;flex-wrap:wrap;gap:4px 2px;`,eh=D.css`display:inline-flex;align-items:center;padding:8px 12px;border-radius:15px;transition:all 0.2s ease;`,th=D.css`cursor:default;background-color:${h.color.ondark.textMidEmphasis};color:${h.themedColor.textHighEmphasis};${Z.dark`
|
|
230
230
|
background-color: transparent;
|
|
231
231
|
border: 1px solid white;
|
|
232
232
|
color: white;
|
|
233
233
|
`}
|
|
234
|
-
`,
|
|
234
|
+
`,nh=D.css`cursor:default;${Z.light`
|
|
235
235
|
background-color: ${h.color.ondark.textMidEmphasis};
|
|
236
236
|
color: ${h.themedColor.textDisabled};
|
|
237
237
|
`}
|
|
238
|
-
${
|
|
238
|
+
${Z.dark`
|
|
239
239
|
background-color: ${h.color.onlight.textLowEmphasis};
|
|
240
240
|
border: 1px solid ${h.color.onlight.textLowEmphasis};
|
|
241
241
|
color: ${h.themedColor.textDisabled};
|
|
242
242
|
`}
|
|
243
|
-
`,
|
|
243
|
+
`,rh=D.css`cursor:pointer;border:1px solid ${h.themedColor.primary};${Z.light`
|
|
244
244
|
background-color: ${h.color.background50};
|
|
245
245
|
color: ${h.themedColor.primary};
|
|
246
246
|
`}
|
|
247
|
-
${
|
|
247
|
+
${Z.dark`
|
|
248
248
|
background-color: ${h.color.onlight.textLowEmphasis};
|
|
249
249
|
color: ${h.themedColor.primary};
|
|
250
250
|
`}
|
|
251
|
-
`,
|
|
251
|
+
`,oh=D.css`cursor:pointer;border:1px solid ${h.themedColor.textDisabled};${Z.light`
|
|
252
252
|
background-color: ${h.color.background50};
|
|
253
253
|
color: ${h.themedColor.textMidEmphasis};
|
|
254
254
|
`}
|
|
255
|
-
${
|
|
255
|
+
${Z.dark`
|
|
256
256
|
background-color: ${h.color.onlight.textLowEmphasis};
|
|
257
257
|
color: ${h.themedColor.textMidEmphasis};
|
|
258
258
|
`}
|
|
259
|
-
`,
|
|
260
|
-
${r} ${
|
|
259
|
+
`,sh=D.css`border-color:${h.themedColor.error}!important;`,ih=p.default.button`${eh}${({$active:e,$submitted:t,$error:n})=>{if(t)return e?th:nh;const r=e?rh:oh;return n?D.css`
|
|
260
|
+
${r} ${sh}
|
|
261
261
|
`:r}}
|
|
262
|
-
`,
|
|
262
|
+
`,ah=e=>i.createElement($i,{...e,multiple:!1}),lh=e=>i.createElement($i,{...e,multiple:!0}),ch=p.default.div`width:100%;height:1px;background-color:${h.themedColor.textDisabled};`,uh=({className:e})=>i.createElement(ch,{className:e}),dh=({id:e,value:t="",onChange:n,placeholder:r,variant:o="single-line",error:s=!1,submitted:a=!1,className:l,disabled:c=!1,maxLength:d,...m})=>{const g={id:e,value:t,onChange:E=>{const y=E.target.value;d&&y.length>d||n==null||n(y)},placeholder:r,className:l,disabled:c||a,maxLength:d,$error:s,$submitted:a,...m};return o==="multi-line"?i.createElement(fh,{...g}):i.createElement(mh,{...g})},Pi=D.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;${Ae}&::placeholder{color:${h.themedColor.textLowEmphasis};}`,Fi=D.css`color:${h.themedColor.textHighEmphasis};border:1px solid transparent;cursor:not-allowed;${Z.light`
|
|
263
263
|
background-color: ${h.color.ondark.textMidEmphasis};
|
|
264
264
|
`}
|
|
265
|
-
${
|
|
265
|
+
${Z.dark`
|
|
266
266
|
background-color: ${h.color.onlight.textLowEmphasis};
|
|
267
267
|
`}
|
|
268
268
|
|
|
269
269
|
&::placeholder {
|
|
270
270
|
color: ${h.themedColor.textLowEmphasis};
|
|
271
271
|
}
|
|
272
|
-
|
|
272
|
+
`,Ui=D.css`border:1px solid ${h.themedColor.error};color:${h.themedColor.textHighEmphasis};${Z.light`
|
|
273
273
|
background-color: ${h.color.background50};
|
|
274
274
|
`}
|
|
275
|
-
${
|
|
275
|
+
${Z.dark`
|
|
276
276
|
background-color: ${h.color.onlight.textLowEmphasis};
|
|
277
277
|
`}
|
|
278
|
-
`,
|
|
278
|
+
`,Bi=D.css`border:1px solid ${h.themedColor.textDisabled};color:${h.themedColor.textHighEmphasis};${Z.light`
|
|
279
279
|
background-color: ${h.color.background50};
|
|
280
280
|
`}
|
|
281
|
-
${
|
|
281
|
+
${Z.dark`
|
|
282
282
|
background-color: ${h.color.onlight.textLowEmphasis};
|
|
283
283
|
`}
|
|
284
284
|
|
|
285
285
|
&:focus {
|
|
286
286
|
border-color: ${h.themedColor.primary};
|
|
287
287
|
}
|
|
288
|
-
`,
|
|
288
|
+
`,mh=p.default.input`${Pi};height:36px;${({$error:e,$submitted:t})=>t?Fi:e?Ui:Bi}`,fh=p.default.textarea`${Pi};height:96px;resize:none;font-family:inherit;${({$error:e,$submitted:t})=>t?Fi:e?Ui:Bi}`,gh=({children:e,className:t,style:n})=>i.createElement($,{variant:"button",color:h.themedColor.textHighEmphasis,className:t,style:n},e),Ie={Title:gh,Label:Vg,ErrorLabel:zg,Separator:uh,Button:Gg,TextInput:dh,NumberInput:Yg,SingleSelect:ah,MultiSelect:lh},hh=1,ph=new Set(["text","number","single-select","multi-select"]),_h=typeof __SBA_USE_FORM__>"u"||__SBA_USE_FORM__,Eh=e=>{var _;if(!_h)return null;const t=(_=e.extendedMessagePayload)==null?void 0:_.form;if(!t)throw new Error("Form is not provided");const{stringSet:n}=se(),{conversation:r}=oe(),[o,s]=u.useState({submitting:!1,canceling:!1}),[a,l]=u.useState({visible:!1}),{state:c,fields:d,submit:m,cancel:f,updateFieldValue:g}=qc(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:C=>{var x;return(x=e.onSubmitForm)==null?void 0:x.call(e,{key:t.key,data:C})},onCancel:()=>{var C;return(C=e.onCancelForm)==null?void 0:C.call(e,{key:t.key})}}),E=c==="submitted",y=async()=>{s(C=>({...C,submitting:!0}));try{await m()}catch(C){l({visible:!0,description:C instanceof Error?C.message:n.TRY_AGAIN})}finally{s(C=>({...C,submitting:!1}))}},v=async()=>{s(C=>({...C,canceling:!0}));try{await f()}catch(C){l({visible:!0,description:C instanceof Error?C.message:n.TRY_AGAIN})}finally{s(C=>({...C,canceling:!1}))}},b=u.useMemo(()=>{const C=()=>t.version>hh,x=()=>t.fields.some(A=>!ph.has(A.type));return C()||x()?{visible:!1,cancelable:!0,reason:n.FORM_NOT_SUPPORTED}:c==="draft"&&(e.isHandedOff||e.isConversationClosed)?{visible:!1,cancelable:!1,reason:n.FORM_UNAVAILABLE}:{visible:!0,cancelable:!0,reason:""}},[t.version,t.fields,c,e.isHandedOff,e.isConversationClosed]);return c==="canceled"?null:b.visible?i.createElement(u.Fragment,null,i.createElement(zo,{$maxWidth:e.maxBodyWidth??ee.BODY_MAX_WIDTH},i.createElement(Ie.Title,null,t.title),i.createElement(bh,null,d.map(C=>i.createElement(Ch,{key:C.key},i.createElement(Ie.Label,{style:{marginBottom:"6px"},required:C.required},C.label),C.type==="text"&&i.createElement(Ie.TextInput,{value:C.value||"",placeholder:C.placeholder,onChange:x=>g(C.key,x),disabled:E,error:!!C.error,submitted:E,variant:C.layout==="multiline"?"multi-line":"single-line",maxLength:C.maxLength,...r.form.textInput(C.label,C.required??!1,E).props}),C.type==="number"&&i.createElement(Ie.NumberInput,{value:C.value||null,placeholder:C.placeholder,onChange:x=>g(C.key,x),disabled:E,error:!!C.error,submitted:E,max:C.max,...r.form.numberInput(C.label,C.required??!1,E).props}),C.type==="single-select"&&i.createElement(Ie.SingleSelect,{options:C.options.map(x=>({label:x,value:x})),value:C.value||"",onChange:x=>g(C.key,x),submitted:E,groupLabel:C.label}),C.type==="multi-select"&&i.createElement(Ie.MultiSelect,{options:C.options.map(x=>({label:x,value:x})),value:C.value||[],onChange:x=>g(C.key,x),submitted:E,maxSelect:C.maxSelect,groupLabel:C.label}),C.error&&i.createElement(Ie.ErrorLabel,{style:{marginTop:"4px"}},C.error)))),i.createElement(Ie.Separator,null),i.createElement(vh,null,i.createElement(Ie.Button,{variant:E?"clear":"primary",...r.form.button(E?n.SUBMITTED:n.BUTTON__SUBMIT).props,onClick:y,disabled:E||o.canceling,loading:o.submitting},E?n.SUBMITTED:n.BUTTON__SUBMIT),c!=="submitted"&&i.createElement(Ie.Button,{variant:"secondary",...r.form.button(n.BUTTON__CANCEL).props,onClick:v,disabled:o.submitting,loading:o.canceling},n.BUTTON__CANCEL))),i.createElement(En,{...a,onClose:()=>l({visible:!1,title:""})})):i.createElement(zo,{$maxWidth:e.maxBodyWidth??ee.BODY_MAX_WIDTH},i.createElement($,{variant:"body3"},b.reason),b.cancelable&&i.createElement(Ie.Button,{variant:"primary",...r.form.button(n.BUTTON__CANCEL).props,onClick:v,loading:o.canceling},n.BUTTON__CANCEL))},zo=p.default.div`display:flex;flex-direction:column;gap:12px;border-radius:12px;overflow:hidden;max-width:${({$maxWidth:e})=>e}px;${({theme:e})=>D.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
|
+
`,bh=p.default.div`display:flex;flex-direction:column;gap:12px;`,Ch=p.default.div`display:flex;flex-direction:column;`,vh=p.default.div`display:flex;flex-direction:column;gap:8px;`,yh=e=>i.createElement(i.Fragment,null),Vo=typeof __SBA_USE_MESSAGE_TEMPLATE__>"u"||__SBA_USE_MESSAGE_TEMPLATE__?u.lazy(()=>Promise.resolve().then(()=>require("./cjs/BjKg30ip.cjs")).then(e=>({default:e.MessageTemplateWrapper}))):null,Sh=e=>Vo?i.createElement(kt,{errorFallback:e.messageTemplateErrorFallback,loadingFallback:e.messageTemplateLoadingFallback},i.createElement(Vo,{...e})):null,Ah=({extendedMessagePayload:e,onClickSuggestedReply:t,suggestedRepliesDirection:n="vertical"})=>{const{conversation:r}=oe(),[o,s]=u.useState(!1),{suggestedReplies:a}=r,l=(e==null?void 0:e.suggested_replies)??[];if(l.length===0||o)return null;const c=d=>{t&&(t({reply:d}),s(!0))};return i.createElement(xh,{id:`${Ke}-ext-suggested-replies`,role:"presentation",$type:n},l.map((d,m)=>{const f=a.item(d,m);return i.createElement(u.Fragment,{key:m},i.createElement(Th,{$type:n,...f.props,onClick:()=>c(d)},i.createElement(Ih,{variant:"body3"},d)),f.descriptionNode)}))},xh=p.default.div`margin:16px 0;padding:0 ${ee.HORIZONTAL_PADDING}px;position:relative;display:flex;align-self:stretch;gap:8px;${({$type:e})=>e==="vertical"?wh:Mh};`,Th=p.default.button.attrs({type:"button"})`
|
|
296
296
|
all: unset;
|
|
297
297
|
box-sizing: border-box;
|
|
298
298
|
padding: 8px 12px;
|
|
@@ -312,20 +312,20 @@
|
|
|
312
312
|
|
|
313
313
|
${Ae}
|
|
314
314
|
|
|
315
|
-
${({$type:e,theme:t})=>D.css`${e==="vertical"?
|
|
316
|
-
`,
|
|
315
|
+
${({$type:e,theme:t})=>D.css`${e==="vertical"?kh:Rh};&:active{background-color:${t.colors.base.primary};color:${t.colors.base.primaryContrastContent};}`}
|
|
316
|
+
`,Ih=p.default($)`color:inherit;`,wh=D.css`flex-direction:column;align-items:flex-end;`,Mh=D.css`flex-direction:row;overflow-x:scroll;-ms-overflow-style:none;scrollbar-width:none;&::-webkit-scrollbar{display:none;}`,kh=D.css`max-width:calc(100% - 70px);white-space:pre-wrap;`,Rh=D.css`white-space:nowrap;`,Lh=e=>{const{components:t}=rt.useContext(),{stringSet:n}=se(),r=hs(e)?i.createElement(t.TextMessageBody,{...e}):null;if(e.messageType==="user")return r;if(e.messageType==="file"){const o=e.file;return o.type.startsWith("image")||o.type.startsWith("video")?i.createElement(t.MediaMessageBody,{...e},r):i.createElement(t.FileMessageBody,{...e},r)}return e.messageType==="multipleFiles"?i.createElement(t.MultipleFilesMessageBody,{...e},r):i.createElement(t.TextMessageBody,{...e,message:n.UNKNOWN__UNKNOWN_MESSAGE_TYPE})},Oh=e=>i.createElement(Hi,{...e,testerMode:!1}),rt=Ge({template:Oh,components:{SenderName:jf,SenderAvatar:qf,SentTime:Zf,MessageBody:Lh,TextMessageBody:zf,MediaMessageBody:xf,FileMessageBody:yf,MultipleFilesMessageBody:Ff,TypingIndicator:Qf,SuggestedReplies:Ah,MessageTemplate:Sh,CustomMessageTemplate:hg,Challenge:lg,CTAButton:sg,Citation:cg,Form:Eh,Feedback:Ng,MessageLogs:yh}}),Hi=e=>{var C,x,A,w,M,k,R,O;const{components:t}=rt.useContext(),{streamText:n,isAnimating:r}=au({text:e.message,enabled:e.isStreaming,deferredMarkdownElements:e.deferredMarkdownElements,onAnimationStart:e.onStreamAnimationStart,onAnimationProgress:e.onStreamAnimationProgress,onAnimationComplete:e.onStreamAnimationComplete}),o={...e,message:n,extendedMessagePayload:r?{}:e.extendedMessagePayload},s=!!o.isTyping,a=o.testerMode,l=!!o.isSenderAvatarVisible,c=!!((C=o.extendedMessagePayload)!=null&&C.form)&&!((x=o.extendedMessagePayload)!=null&&x.form.canceled_at),d=!!((A=o.extendedMessagePayload)!=null&&A.message_template),m=!!((w=o.extendedMessagePayload)!=null&&w.challenge),f=!!((M=o.extendedMessagePayload)!=null&&M.cta_button),g=!!((k=o.extendedMessagePayload)!=null&&k.citations)&&o.extendedMessagePayload.citations.length>0,E=!!o.createdAt,y=f||g,v=o.groupType==="top"||o.groupType==="single",b=o.groupType==="bottom"||o.groupType==="single",_=a||!l?0:ee.AVATAR_SIZE;return i.createElement(Nh,{$marginBottom:s?0:fn(o.groupType)},v&&i.createElement(Ph,null,!a&&l&&i.createElement(t.SenderAvatar,{...o}),i.createElement(t.SenderName,{...o})),i.createElement(Uh,null,i.createElement(Pn,{$extraStartPadding:_},s?i.createElement(t.TypingIndicator,{...o}):y?i.createElement(Dh,{$maxWidth:o.maxBodyWidth??ee.BODY_MAX_WIDTH},i.createElement(t.MessageBody,{...o,surface:"plain"}),f&&i.createElement($h,{$marginTop:12,$paddingInline:12},i.createElement(t.CTAButton,{...o})),g&&i.createElement(t.Citation,{...o})):i.createElement(t.MessageBody,{...o})),d&&i.createElement(Yo,{$startPadding:0,$endPadding:0},i.createElement(t.MessageTemplate,{...o,messageTemplateErrorFallback:o.messageTemplateErrorFallback??i.createElement(Pn,{$extraStartPadding:_},i.createElement(t.MessageBody,{...o,messageType:"user",message:((O=(R=o.extendedMessagePayload)==null?void 0:R.message_template)==null?void 0:O.fallback_message)??"Cannot read this template."})),messageTemplateLoadingFallback:o.messageTemplateLoadingFallback??i.createElement(Pn,{$extraStartPadding:_},i.createElement(t.TypingIndicator,{...o}))})),i.createElement(t.CustomMessageTemplate,{...o}),m&&i.createElement(t.Challenge,{...o}),c&&i.createElement(Yo,{$extraStartPadding:_},i.createElement(t.Form,{...o}))),i.createElement(t.MessageLogs,{...o}),b&&E&&i.createElement(Fh,{$extraStartPadding:_+8},i.createElement(t.SentTime,{...o})),i.createElement(u.Fragment,null,!s&&i.createElement($t,{$extraStartPadding:_+8},i.createElement(t.Feedback,{...o})),o.suggestedRepliesVisible&&i.createElement(t.SuggestedReplies,{...o})))},Nh=p.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
|
+
`,$t=p.default.div.attrs({role:"presentation"})`
|
|
322
322
|
display: flex;
|
|
323
323
|
align-self: stretch;
|
|
324
324
|
justify-content: flex-start;
|
|
325
325
|
${({$startPadding:e=ee.HORIZONTAL_PADDING,$endPadding:t=ee.HORIZONTAL_PADDING,$extraStartPadding:n=0})=>`
|
|
326
326
|
padding-inline: ${e+n}px ${t}px;
|
|
327
327
|
`}
|
|
328
|
-
`,
|
|
328
|
+
`,Dh=p.default.div.attrs({role:"presentation"})`
|
|
329
329
|
display: flex;
|
|
330
330
|
flex-direction: column;
|
|
331
331
|
min-width: 0;
|
|
@@ -334,53 +334,53 @@
|
|
|
334
334
|
overflow: hidden;
|
|
335
335
|
padding: 12px 0;
|
|
336
336
|
${({theme:e})=>D.css`color:${e.colors.messageIncoming.text};background-color:${e.colors.messageIncoming.background};`}
|
|
337
|
-
|
|
337
|
+
`,$h=p.default.div.attrs({role:"presentation"})`
|
|
338
338
|
display: flex;
|
|
339
339
|
flex-direction: column;
|
|
340
340
|
min-width: 0;
|
|
341
341
|
${({$marginTop:e=0,$paddingInline:t=0})=>D.css`margin-top:${e}px;padding-inline:${t}px;`}
|
|
342
|
-
`,
|
|
342
|
+
`,Ph=p.default($t)`display:flex;flex-direction:row;align-items:center;gap:8px;`,Pn=p.default($t)`display:flex;`,Fh=p.default($t)`margin-top:${ee.BODY_TIME_GAP}px;display:flex;align-items:flex-start;justify-content:flex-start;`,Yo=p.default($t).attrs({role:"presentation"})`
|
|
343
343
|
display: flex;
|
|
344
344
|
${({$startPadding:e=ee.HORIZONTAL_PADDING,$endPadding:t=ee.HORIZONTAL_PADDING,$extraStartPadding:n=0})=>`
|
|
345
345
|
padding-inline: ${e+n}px ${t}px;
|
|
346
346
|
`}
|
|
347
|
-
`,
|
|
347
|
+
`,Uh=p.default.div.attrs({role:"presentation"})`
|
|
348
348
|
display: flex;
|
|
349
349
|
flex-direction: column;
|
|
350
350
|
min-width: 0;
|
|
351
351
|
max-width: 100%;
|
|
352
352
|
gap: ${ee.GAP_GROUPED}px;
|
|
353
|
-
`;function
|
|
353
|
+
`;function Bh({file:e,children:t,onClickFile:n,sendingStatus:r}){const o=(()=>{if(!(!n||r==="failed"))return()=>n==null?void 0:n(e)})();return i.createElement(Hh,null,i.createElement(Tr,{name:e.name,mimeType:e.type,type:or(e.name,e.type),onClick:o}),t)}const Hh=p.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${ee.GAP_GROUPED}px;`;function Gh({sendingStatus:e,file:t,metadata:n,onClickMedia:r,onClickMediaFiles:o,children:s}){const{conversation:a}=oe(),{aspectRatio:l,localFile:c}=n,[d]=u.useState(()=>c instanceof Blob?URL.createObjectURL(c):t.url),[m,f]=u.useState(!1),g=(()=>{if(e!=="failed"){if(o)return()=>o({files:[{url:d,type:t.type,name:t.name}],index:0});if(r)return()=>r({...t,url:d})}})(),E=g?a.file.buttonLikePreview({name:t.name,mimeType:t.type,onActivate:g}):a.file.preview({name:t.name,mimeType:t.type}),y={...E.props,$ratio:l,$clickable:!!g};return i.createElement(zh,null,i.createElement(Vh,{...y},!m&&i.createElement(at,{size:26},i.createElement(X,{type:"spinner",color:"textLowEmphasis",size:26})),i.createElement(Yh,{$loaded:m,src:d,alt:"image-message",onLoad:()=>f(!0)}),E.descriptionNode),s)}const zh=p.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${ee.GAP_GROUPED}px;`,Vh=p.default.div`width:${ee.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;${Z.light`
|
|
354
354
|
background-color: ${h.color.background100};
|
|
355
355
|
`}
|
|
356
|
-
${
|
|
356
|
+
${Z.dark`
|
|
357
357
|
background-color: ${h.color.background400};
|
|
358
358
|
`}
|
|
359
|
-
`,
|
|
359
|
+
`,Yh=p.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;`,Wh=({sendingStatus:e,files:t,metadata:n,onClickMedia:r,onClickMediaFiles:o,children:s})=>{const[a]=u.useState(()=>n.localFiles?n.localFiles.filter(m=>m instanceof Blob).map(m=>({...m,url:URL.createObjectURL(m)})):t),l=e==="pending",c=e==="failed",d=m=>{if(c||l)return;const f=a[m];f&&(o?o({files:a,index:m}):r&&r({url:f.url,type:f.type||"image/*"}))};return i.createElement(qh,null,i.createElement(wi,{images:a,isPending:l,onClickImage:d}),s)},qh=p.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${ee.GAP_GROUPED}px;`;function Kh(e){var n,r;const t=u.useMemo(()=>{const o=Hf(ki(e.message));return ds.default.sanitize(o)},[e.message]);return i.createElement(jh,{$maxWidth:e.maxBodyWidth??ee.BODY_MAX_WIDTH,$color:(n=e.customStyle)==null?void 0:n.bubbleContentColor,$bgColor:(r=e.customStyle)==null?void 0:r.bubbleBackgroundColor},i.createElement(Xh,{variant:"body3",dangerouslySetInnerHTML:{__html:t}}))}const jh=p.default.div`display:flex;flex-direction:column;border-radius:12px;overflow:hidden;max-width:${({$maxWidth:e})=>e}px;${({theme:e,$color:t,$bgColor:n})=>D.css`
|
|
360
360
|
color: ${t||e.colors.messageOutgoing.text};
|
|
361
361
|
background-color: ${n||e.colors.messageOutgoing.background};
|
|
362
362
|
`}
|
|
363
363
|
padding: 12px 0;
|
|
364
364
|
transition: max-width 0.3s;
|
|
365
365
|
overflow-wrap: break-word;
|
|
366
|
-
`,
|
|
367
|
-
`,
|
|
368
|
-
`,Jh=p.default(Ui)``,Qh=p.default(Ui)`margin-top:${ee.BODY_TIME_GAP}px;`,ep=e=>e.messageType!=="admin"?null:i.createElement(tp,null,i.createElement($,{variant:"caption2",color:h.themedColor.textMidEmphasis},np(ls.default.sanitize(e.message),e.onClickLink))),tp=p.default.div`text-align:center;text-wrap:pretty;word-break:break-word;padding-inline:${ee.HORIZONTAL_PADDING}px;a{text-decoration:underline;color:inherit;}`,np=(e,t)=>{try{const n=[];let r=e,o=0;for(;r;){const s=r.match(/\[([^\]]+)\]\((https?:\/\/[^\s]+)\)/),a=r.match(/\*\*([^*]+)\*\*/),l=[s&&{match:s,type:"link"},a&&{match:a,type:"bold"}].filter(g=>!!g);if(!l.length){n.push(r);break}const c=l.reduce((g,_)=>_.match.index<g.match.index?_:g),{match:d,type:m}=c,f=d.index;f>0&&n.push(r.slice(0,f)),m==="link"?n.push(i.createElement("a",{key:o++,href:d[2],target:"_blank",rel:pr,onClick:g=>{g.preventDefault();const _=d[2];_&&(t==null||t({url:_}))}},d[1])):m==="bold"&&n.push(i.createElement("strong",{key:o++},d[1])),r=r.slice(f+d[0].length)}return n.filter(s=>s!=="")}catch{return[e]}},rp=({direction:e,currentIndex:t,totalCount:n})=>n<=0?t:e==="next"?(t+1)%n:(t-1+n)%n,Bi=({options:e,value:t,disabled:n,hasError:r=!1,errorId:o,onChange:s})=>{const a=u.useRef([]),l=e.findIndex(f=>f.value===t),c=l>=0?l:0,d=f=>{requestAnimationFrame(()=>{var g;(g=a.current[f])==null||g.focus()})},m=f=>{const g=e[f];!g||n||(s==null||s(g.value),d(f))};return{radioGroupProps:f=>({role:"radiogroup","aria-label":f,...r&&o?{"aria-invalid":!0,"aria-errormessage":o}:{}}),getRadioProps:f=>({ref:g=>{a.current[f]=g},tabIndex:n?-1:f===c?0:-1,describedBy:r&&o?o:void 0,onArrowNavigate:g=>{m(rp({direction:g,currentIndex:f,totalCount:e.length}))}})}},op=e=>{switch(e.key){case"ArrowDown":case"ArrowRight":return"next";case"ArrowUp":case"ArrowLeft":return"previous";default:return}},sp=({event:e,onClick:t,onArrowNavigate:n})=>{if(ip(e))return;const r=op(e);if(r){e.preventDefault(),n==null||n(r);return}e.key!=="Enter"&&e.key!==" "||(e.preventDefault(),t==null||t())},ip=e=>e.repeat||e.currentTarget.getAttribute("aria-disabled")==="true",Tr=u.forwardRef(({onClick:e,checked:t,label:n,disabled:r,tabIndex:o=0,labelVariant:s="caption2",describedBy:a,onArrowNavigate:l},c)=>{const d=t?h.themedColor.primary:r?h.themedColor.textDisabled:h.themedColor.textLowEmphasis,m=t?h.themedColor.textHighEmphasis:r?h.themedColor.textLowEmphasis:h.themedColor.textHighEmphasis;return i.createElement(cp,{ref:c,role:"radio",tabIndex:r?-1:o,"aria-checked":t,"aria-disabled":!!r,"aria-label":n,"aria-describedby":a,onClick:r?void 0:e,onKeyDown:f=>sp({event:f,onClick:e,onArrowNavigate:l})},i.createElement(ap,{"aria-hidden":"true"},i.createElement(Q,{size:20,type:t?"radio-on":"radio-off",color:d})),i.createElement(lp,{"aria-hidden":"true",variant:s,color:m},n))});Tr.displayName="Radio";const ap=p.default.div`width:20px;height:20px;`,lp=p.default($)`line-height:20px;word-break:break-word;`,cp=p.default.div`display:flex;align-items:flex-start;justify-content:flex-start;gap:2px;${Ae}&[aria-disabled='false']{cursor:pointer;}`,up=({csatPayload:e,submitted:t,defaultValue:n,value:r,onChange:o})=>{var c,d;const s=[{label:((c=e.cre)==null?void 0:c.positive_label)??"",value:!0},{label:((d=e.cre)==null?void 0:d.negative_label)??"",value:!1}],a=Bi({options:s,value:r,disabled:t,onChange:o});if(u.useEffect(()=>{typeof r>"u"&&typeof n=="boolean"&&(o==null||o(n))},[r,n]),!e.cre)return null;const l=e.cre;return i.createElement(dp,null,i.createElement(Te.Label,{required:l.required,"aria-hidden":!0},l.question),i.createElement(mp,{...a.radioGroupProps(l.question)},s.map((m,f)=>i.createElement(Tr,{key:m.label,checked:r===m.value,label:m.label,disabled:t,...a.getRadioProps(f),onClick:()=>o==null?void 0:o(m.value)}))))},dp=p.default.div`display:flex;flex-direction:column;gap:8px;`,mp=p.default.div`display:flex;flex-direction:column;gap:8px;`,fp=({followUpItem:e,submitted:t,value:n="",onChange:r,hasError:o})=>{const{stringSet:s}=se(),{conversation:a}=oe(),l=u.useId(),c=u.useId(),d=e.response_type!=="free_text",m=e.response_type==="single_choice"?e.options.map(g=>({label:g,value:g})):[],f=Bi({options:m,value:n,disabled:t,hasError:o,errorId:l,onChange:r});return i.createElement(gp,null,i.createElement(Te.Label,{id:c,required:e.required,"aria-hidden":d},e.question),e.response_type==="free_text"&&i.createElement(Te.TextInput,{variant:"multi-line",disabled:t,submitted:t,maxLength:100,value:n,onChange:g=>r(g),error:o,...a.form.textInput(s.A11Y_CSAT_TEXT_INPUT_LABEL,e.required??!1,t,{labelId:c}).props,"aria-invalid":o,"aria-errormessage":o?l:void 0}),e.response_type==="single_choice"&&i.createElement(hp,{...f.radioGroupProps(e.question)},m.map((g,_)=>i.createElement(Tr,{key:g.value,checked:n===g.value,label:g.label,disabled:t,...f.getRadioProps(_),onClick:()=>r==null?void 0:r(g.value),labelVariant:"body3"}))),o&&i.createElement(pp,{role:"alert",id:l},s.FORM_VALIDATION_REQUIRED))},gp=p.default.div`display:flex;flex-direction:column;gap:8px;`,hp=p.default.div`display:flex;flex-direction:column;gap:8px;`,pp=p.default(Te.ErrorLabel)``,_p=({value:e,selected:t})=>i.createElement(Ep,{$selected:t,"aria-hidden":"true"},bp[e-1]),Ep=p.default.div`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,bp=[i.createElement("svg",{width:"40",height:"40",viewBox:"0 0 40 40",fill:"none",xmlns:"http://www.w3.org/2000/svg"},i.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)"}),i.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"}),i.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"}),i.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"}),i.createElement("defs",null,i.createElement("linearGradient",{id:"paint0_linear_159_173206",x1:"20",y1:"2.08325",x2:"20",y2:"37.9166",gradientUnits:"userSpaceOnUse"},i.createElement("stop",{stopColor:"#FF2D1D"}),i.createElement("stop",{offset:"1",stopColor:"#FFA540"})))),i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},i.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"}),i.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"}),i.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"}),i.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"})),i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},i.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"}),i.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"}),i.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"})),i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},i.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"}),i.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"}),i.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"})),i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},i.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"}),i.createElement("g",{clipPath:"url(#clip0_159_173224)"},i.createElement("g",{clipPath:"url(#clip1_159_173224)"},i.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"})),i.createElement("mask",{id:"mask0_159_173224",style:{maskType:"alpha"},maskUnits:"userSpaceOnUse",x:"12",y:"22",width:"16",height:"9"},i.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"})),i.createElement("g",{mask:"url(#mask0_159_173224)"},i.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"}))),i.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"}),i.createElement("defs",null,i.createElement("clipPath",{id:"clip0_159_173224"},i.createElement("rect",{width:"15.83",height:"7.915",fill:"white",transform:"translate(12.085 22.709)"})),i.createElement("clipPath",{id:"clip1_159_173224"},i.createElement("rect",{width:"15.83",height:"7.915",fill:"white",transform:"translate(12.085 22.709)"}))))],Cp=({csatPayload:e,submitted:t,value:n,onChange:r})=>{const o=typeof n>"u",{conversation:s}=oe(),a=s.csat.scoresContainer(e.csat_question);return i.createElement(yp,null,i.createElement($,{variant:"caption3",color:h.themedColor.textMidEmphasis,"aria-hidden":"true"},e.csat_question),i.createElement(Sp,{...a.props},a.descriptionNode,e.csat_scores.map(({label:l,image_url:c},d)=>{const m=d+1,f=n===m,g=e.csat_scores.length,_=s.csat.scoreItem({score:m,label:l,selected:f,disabled:t,currentIndex:d,totalCount:g,hasSelection:!o,onChange:r});return i.createElement(Ap,{key:d,type:"button",..._.props},i.createElement(vp,{value:m,selected:o||f,src:c}),!!l&&i.createElement($,{"aria-hidden":"true",color:f?h.themedColor.textHighEmphasis:h.themedColor.textLowEmphasis,variant:"caption3"},l),_.descriptionNode)})))},vp=({value:e,src:t,selected:n})=>{const[r,o]=u.useState(!1),s=r?i.createElement(_p,{value:e,selected:n}):i.createElement(Tp,{$selected:n,alt:"","aria-hidden":"true",src:t,onError:()=>o(!0)});return i.createElement(xp,null,s)},yp=p.default.div`display:flex;flex-direction:column;gap:8px;`,Sp=p.default.div`display:flex;justify-content:space-between;align-self:center;width:100%;max-width:400px;gap:16px;`,Ap=p.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;${Ae}&:not(:disabled):hover span{color:${h.themedColor.textHighEmphasis};}`,xp=p.default.div`button:not(:disabled):hover &{border-radius:4px;cursor:pointer;background-color:${h.color.background200};${J.dark`
|
|
366
|
+
`,Xh=p.default($)`align-items:flex-start;line-height:140%;white-space:pre-wrap;padding:0 12px;`,Zh=({sendingStatus:e})=>{const t=D.useTheme();switch(e){case"pending":return i.createElement(Jh,{size:16},i.createElement(X,{type:"spinner",color:t.colors.messageOutgoing.background,size:16}));case"failed":return i.createElement("div",{style:{marginBottom:2}},i.createElement(X,{type:"error",color:h.themedColor.error,size:16}));case"scheduled":case"canceled":return null;default:return i.createElement("div",{style:{marginBottom:2}},i.createElement(X,{type:"done",color:h.themedColor.secondary,size:16}))}},Jh=p.default(at)`margin-bottom:2px;width:16px;height:16px;`,Qh=({createdAt:e})=>{const{stringSet:t,format:n}=se();return e?i.createElement($,{variant:"caption4",color:h.themedColor.textLowEmphasis},n(e,t.DATE_FORMAT__MESSAGE_TIMESTAMP)):null},ep=e=>{const{components:t}=Pt.useContext(),{stringSet:n}=se(),r=()=>{const a=hs(e)?i.createElement(t.TextMessageBody,{...e}):null;return e.messageType==="user"?a:e.messageType==="file"?e.file.type.startsWith("image")?i.createElement(t.MediaMessageBody,{...e},a):i.createElement(t.FileMessageBody,{...e},a):e.messageType==="multipleFiles"?i.createElement(t.MultipleFilesMessageBody,{...e},a):i.createElement(t.TextMessageBody,{...e,message:n.UNKNOWN__UNKNOWN_MESSAGE_TYPE})},o=e.sendingStatus==="failed"&&e.onClickFailedMessage,s=o?xt({onActivate:()=>{var a;return(a=e.onClickFailedMessage)==null?void 0:a.call(e)}}):{};return i.createElement("div",{...s,style:{display:"contents",cursor:o?"pointer":"default"}},r())},tp=e=>{const{components:t}=Pt.useContext(),n=e.sendingStatus==="succeeded",r=e.groupType==="bottom"||e.groupType==="single";return i.createElement(np,{$marginBottom:fn(e.groupType)},i.createElement(rp,null,i.createElement(t.MessageBody,{...e})),r&&i.createElement(op,{$extraEndPadding:8},n?i.createElement(t.SentTime,{...e}):i.createElement(t.SendingStatus,{...e})))},Pt=Ge({template:tp,components:{SendingStatus:Zh,SentTime:Qh,MessageBody:ep,TextMessageBody:Kh,MediaMessageBody:Gh,FileMessageBody:Bh,MultipleFilesMessageBody:Wh}}),np=p.default.div`display:flex;flex:1;flex-direction:column;align-items:flex-end;margin-bottom:${({$marginBottom:e})=>`${e}px`};
|
|
367
|
+
`,Gi=p.default.div`display:flex;align-self:stretch;justify-content:flex-end;${({$startPadding:e=ee.HORIZONTAL_PADDING,$endPadding:t=ee.HORIZONTAL_PADDING,$extraEndPadding:n=0})=>`padding-inline: ${e}px ${t+n}px;`};
|
|
368
|
+
`,rp=p.default(Gi)``,op=p.default(Gi)`margin-top:${ee.BODY_TIME_GAP}px;`,sp=e=>e.messageType!=="admin"?null:i.createElement(ip,null,i.createElement($,{variant:"caption2",color:h.themedColor.textMidEmphasis},ap(ds.default.sanitize(e.message),e.onClickLink))),ip=p.default.div`text-align:center;text-wrap:pretty;word-break:break-word;padding-inline:${ee.HORIZONTAL_PADDING}px;a{text-decoration:underline;color:inherit;}`,ap=(e,t)=>{try{const n=[];let r=e,o=0;for(;r;){const s=r.match(/\[([^\]]+)\]\((https?:\/\/[^\s]+)\)/),a=r.match(/\*\*([^*]+)\*\*/),l=[s&&{match:s,type:"link"},a&&{match:a,type:"bold"}].filter(g=>!!g);if(!l.length){n.push(r);break}const c=l.reduce((g,E)=>E.match.index<g.match.index?E:g),{match:d,type:m}=c,f=d.index;f>0&&n.push(r.slice(0,f)),m==="link"?n.push(i.createElement("a",{key:o++,href:d[2],target:"_blank",rel:Er,onClick:g=>{g.preventDefault();const E=d[2];E&&(t==null||t({url:E}))}},d[1])):m==="bold"&&n.push(i.createElement("strong",{key:o++},d[1])),r=r.slice(f+d[0].length)}return n.filter(s=>s!=="")}catch{return[e]}},lp=({direction:e,currentIndex:t,totalCount:n})=>n<=0?t:e==="next"?(t+1)%n:(t-1+n)%n,zi=({options:e,value:t,disabled:n,hasError:r=!1,errorId:o,onChange:s})=>{const a=u.useRef([]),l=e.findIndex(f=>f.value===t),c=l>=0?l:0,d=f=>{requestAnimationFrame(()=>{var g;(g=a.current[f])==null||g.focus()})},m=f=>{const g=e[f];!g||n||(s==null||s(g.value),d(f))};return{radioGroupProps:f=>({role:"radiogroup","aria-label":f,...r&&o?{"aria-invalid":!0,"aria-errormessage":o}:{}}),getRadioProps:f=>({ref:g=>{a.current[f]=g},tabIndex:n?-1:f===c?0:-1,describedBy:r&&o?o:void 0,onArrowNavigate:g=>{m(lp({direction:g,currentIndex:f,totalCount:e.length}))}})}},cp=e=>{switch(e.key){case"ArrowDown":case"ArrowRight":return"next";case"ArrowUp":case"ArrowLeft":return"previous";default:return}},up=({event:e,onClick:t,onArrowNavigate:n})=>{if(dp(e))return;const r=cp(e);if(r){e.preventDefault(),n==null||n(r);return}e.key!=="Enter"&&e.key!==" "||(e.preventDefault(),t==null||t())},dp=e=>e.repeat||e.currentTarget.getAttribute("aria-disabled")==="true",Mr=u.forwardRef(({onClick:e,checked:t,label:n,disabled:r,tabIndex:o=0,labelVariant:s="caption2",describedBy:a,onArrowNavigate:l},c)=>{const d=t?h.themedColor.primary:r?h.themedColor.textDisabled:h.themedColor.textLowEmphasis,m=t?h.themedColor.textHighEmphasis:r?h.themedColor.textLowEmphasis:h.themedColor.textHighEmphasis;return i.createElement(gp,{ref:c,role:"radio",tabIndex:r?-1:o,"aria-checked":t,"aria-disabled":!!r,"aria-label":n,"aria-describedby":a,onClick:r?void 0:e,onKeyDown:f=>up({event:f,onClick:e,onArrowNavigate:l})},i.createElement(mp,{"aria-hidden":"true"},i.createElement(X,{size:20,type:t?"radio-on":"radio-off",color:d})),i.createElement(fp,{"aria-hidden":"true",variant:s,color:m},n))});Mr.displayName="Radio";const mp=p.default.div`width:20px;height:20px;`,fp=p.default($)`line-height:20px;word-break:break-word;`,gp=p.default.div`display:flex;align-items:flex-start;justify-content:flex-start;gap:2px;${Ae}&[aria-disabled='false']{cursor:pointer;}`,hp=({csatPayload:e,submitted:t,defaultValue:n,value:r,onChange:o})=>{var c,d;const s=[{label:((c=e.cre)==null?void 0:c.positive_label)??"",value:!0},{label:((d=e.cre)==null?void 0:d.negative_label)??"",value:!1}],a=zi({options:s,value:r,disabled:t,onChange:o});if(u.useEffect(()=>{typeof r>"u"&&typeof n=="boolean"&&(o==null||o(n))},[r,n]),!e.cre)return null;const l=e.cre;return i.createElement(pp,null,i.createElement(Ie.Label,{required:l.required,"aria-hidden":!0},l.question),i.createElement(_p,{...a.radioGroupProps(l.question)},s.map((m,f)=>i.createElement(Mr,{key:m.label,checked:r===m.value,label:m.label,disabled:t,...a.getRadioProps(f),onClick:()=>o==null?void 0:o(m.value)}))))},pp=p.default.div`display:flex;flex-direction:column;gap:8px;`,_p=p.default.div`display:flex;flex-direction:column;gap:8px;`,Ep=({followUpItem:e,submitted:t,value:n="",onChange:r,hasError:o})=>{const{stringSet:s}=se(),{conversation:a}=oe(),l=u.useId(),c=u.useId(),d=e.response_type!=="free_text",m=e.response_type==="single_choice"?e.options.map(g=>({label:g,value:g})):[],f=zi({options:m,value:n,disabled:t,hasError:o,errorId:l,onChange:r});return i.createElement(bp,null,i.createElement(Ie.Label,{id:c,required:e.required,"aria-hidden":d},e.question),e.response_type==="free_text"&&i.createElement(Ie.TextInput,{variant:"multi-line",disabled:t,submitted:t,maxLength:100,value:n,onChange:g=>r(g),error:o,...a.form.textInput(s.A11Y_CSAT_TEXT_INPUT_LABEL,e.required??!1,t,{labelId:c}).props,"aria-invalid":o,"aria-errormessage":o?l:void 0}),e.response_type==="single_choice"&&i.createElement(Cp,{...f.radioGroupProps(e.question)},m.map((g,E)=>i.createElement(Mr,{key:g.value,checked:n===g.value,label:g.label,disabled:t,...f.getRadioProps(E),onClick:()=>r==null?void 0:r(g.value),labelVariant:"body3"}))),o&&i.createElement(vp,{role:"alert",id:l},s.FORM_VALIDATION_REQUIRED))},bp=p.default.div`display:flex;flex-direction:column;gap:8px;`,Cp=p.default.div`display:flex;flex-direction:column;gap:8px;`,vp=p.default(Ie.ErrorLabel)``,yp=({value:e,selected:t})=>i.createElement(Sp,{$selected:t,"aria-hidden":"true"},Ap[e-1]),Sp=p.default.div`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,Ap=[i.createElement("svg",{width:"40",height:"40",viewBox:"0 0 40 40",fill:"none",xmlns:"http://www.w3.org/2000/svg"},i.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)"}),i.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"}),i.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"}),i.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"}),i.createElement("defs",null,i.createElement("linearGradient",{id:"paint0_linear_159_173206",x1:"20",y1:"2.08325",x2:"20",y2:"37.9166",gradientUnits:"userSpaceOnUse"},i.createElement("stop",{stopColor:"#FF2D1D"}),i.createElement("stop",{offset:"1",stopColor:"#FFA540"})))),i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},i.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"}),i.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"}),i.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"}),i.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"})),i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},i.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"}),i.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"}),i.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"})),i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},i.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"}),i.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"}),i.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"})),i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},i.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"}),i.createElement("g",{clipPath:"url(#clip0_159_173224)"},i.createElement("g",{clipPath:"url(#clip1_159_173224)"},i.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"})),i.createElement("mask",{id:"mask0_159_173224",style:{maskType:"alpha"},maskUnits:"userSpaceOnUse",x:"12",y:"22",width:"16",height:"9"},i.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"})),i.createElement("g",{mask:"url(#mask0_159_173224)"},i.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"}))),i.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"}),i.createElement("defs",null,i.createElement("clipPath",{id:"clip0_159_173224"},i.createElement("rect",{width:"15.83",height:"7.915",fill:"white",transform:"translate(12.085 22.709)"})),i.createElement("clipPath",{id:"clip1_159_173224"},i.createElement("rect",{width:"15.83",height:"7.915",fill:"white",transform:"translate(12.085 22.709)"}))))],xp=({csatPayload:e,submitted:t,value:n,onChange:r})=>{const o=typeof n>"u",{conversation:s}=oe(),a=s.csat.scoresContainer(e.csat_question);return i.createElement(Ip,null,i.createElement($,{variant:"caption3",color:h.themedColor.textMidEmphasis,"aria-hidden":"true"},e.csat_question),i.createElement(wp,{...a.props},a.descriptionNode,e.csat_scores.map(({label:l,image_url:c},d)=>{const m=d+1,f=n===m,g=e.csat_scores.length,E=s.csat.scoreItem({score:m,label:l,selected:f,disabled:t,currentIndex:d,totalCount:g,hasSelection:!o,onChange:r});return i.createElement(Mp,{key:d,type:"button",...E.props},i.createElement(Tp,{value:m,selected:o||f,src:c}),!!l&&i.createElement($,{"aria-hidden":"true",color:f?h.themedColor.textHighEmphasis:h.themedColor.textLowEmphasis,variant:"caption3"},l),E.descriptionNode)})))},Tp=({value:e,src:t,selected:n})=>{const[r,o]=u.useState(!1),s=r?i.createElement(yp,{value:e,selected:n}):i.createElement(Rp,{$selected:n,alt:"","aria-hidden":"true",src:t,onError:()=>o(!0)});return i.createElement(kp,null,s)},Ip=p.default.div`display:flex;flex-direction:column;gap:8px;`,wp=p.default.div`display:flex;justify-content:space-between;align-self:center;width:100%;max-width:400px;gap:16px;`,Mp=p.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;${Ae}&:not(:disabled):hover span{color:${h.themedColor.textHighEmphasis};}`,kp=p.default.div`button:not(:disabled):hover &{border-radius:4px;cursor:pointer;background-color:${h.color.background200};${Z.dark`
|
|
369
369
|
background-color: ${h.color.background500};
|
|
370
370
|
`}
|
|
371
371
|
}
|
|
372
|
-
`,
|
|
372
|
+
`,Rp=p.default.img`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,Lp=({csatPayload:e})=>i.createElement($,{variant:"button",color:h.themedColor.textHighEmphasis},e.title),Fn=({csatPayload:e,type:t,renderSubmitButton:n,initialCsat:r,initialCsatReason:o,initialIsResolved:s})=>{const{params:a,setParams:l,error:c,setError:d,followUpItem:m,state:f,validateParams:g,itemProps:E}=tu({csatPayload:e,type:t,initialCsat:r,initialCsatReason:o,initialIsResolved:s});return i.createElement(i.Fragment,null,i.createElement(Op,null,i.createElement(Lp,{...E}),t===qe.AI_AGENT_CSAT_5_WITH_CRE&&i.createElement(hp,{...E,defaultValue:s,value:a.isResolved,onChange:y=>l({isResolved:y})}),i.createElement(xp,{...E,value:a.csat,onChange:y=>l({csat:y})}),m&&i.createElement(Ep,{...E,followUpItem:m,value:a.csatReason,onChange:y=>{l({csatReason:y}),d({followUpItem:!1})},hasError:c.followUpItem})),f!=="unsubmittable"&&i.createElement(i.Fragment,null,i.createElement(Ie.Separator,null),n({state:f,params:a,validateParams:g})))},Op=p.default.div`display:flex;flex-direction:column;gap:12px;`,Np=e=>{const{stringSet:t}=se();return sl(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})},Dp=()=>{const{stringSet:e}=se();return i.createElement($,{variant:"body2",color:h.themedColor.textMidEmphasis,style:{textAlign:"center"}},e.CSAT_SUBMISSION_EXPIRED)},$p=({onMount:e,children:t})=>(u.useEffect(()=>{e&&Me(e)},[]),t),Pp=e=>{const{conversation:t}=oe();if(e.messageType!=="admin.csat")throw new Error("Invalid message type");const{extendedMessagePayload:n,onSubmitCSAT:r,onScrollToBottom:o}=e,{csat:s,csatReason:a,csatExpireAt:l,isResolvedWhenDeterminedByUser:c}=e,d=gn(),m=Np(n==null?void 0:n.csat),f=u.useRef(null),g=u.useRef(null),[E,y]=u.useState(!1),v=u.useRef(!1),b=u.useCallback(()=>{Me(()=>{var w;return(w=g.current)==null?void 0:w.focus()})},[]),{isExpiredNow:_,isRenderableCSAT:C}=nu({csat:s,csatExpireAt:l,csatPayload:m,isSubmitInFlight:E});if(Qc({csat:s,csatPayload:m,isRenderableCSAT:C,isExpiredNow:_,announceStatus:e.announceStatus,onSubmittedAnnounced:b}),!C||!m)return null;const x=()=>{var M;const w=(M=f.current)==null?void 0:M.querySelector('[aria-invalid="true"]');return w?w.getAttribute("role")==="radiogroup"?w.querySelector('[role="radio"]'):w:null},A=m.type===qe.AI_AGENT_CSAT_5||m.type===qe.AI_AGENT_CSAT_5_WITH_CRE||m.type===qe.HELPDESK_CSAT_5?Fn:()=>null;return i.createElement(Fp,{ref:f},!s&&_?i.createElement(Dp,null):i.createElement(A,{csatPayload:m,type:m.type,initialCsat:s,initialCsatReason:a,initialIsResolved:c,renderSubmitButton:({state:w,params:M,validateParams:k})=>w==="submitted"?i.createElement(Bp,{ref:g,role:"status","aria-live":"polite","aria-atomic":"true","aria-label":m.csat_submitted_label,tabIndex:-1},i.createElement($,{variant:"button","aria-hidden":"true"},m.csat_submitted_label)):i.createElement($p,{onMount:o},i.createElement(Up,{type:"button",...t.csat.submitButton(m.csat_submit_label).props,onClick:async()=>{if(v.current)return;const R=Ss(l);if(!R&&k()){v.current=!0,y(!0);try{await r(M)}catch(O){throw v.current=!1,y(!1),O}}else d(),R||Me(()=>{var O;(O=e.announceError)==null||O.call(e,{type:"csatFormError"},x())})}},i.createElement($,{variant:"button"},m.csat_submit_label)))}))},Fp=p.default.div`display:flex;flex-direction:column;background-color:${({theme:e})=>e.colors.csat.background};border-radius:16px;gap:16px;padding:16px;`,Up=p.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;${Ae}&:hover{background-color:${h.color.primary.dark};}`,Bp=p.default.div`width:100%;box-sizing:border-box;color:${h.themedColor.textHighEmphasis};background-color:${h.color.background200};border-radius:6px;padding:10px 20px;display:flex;align-items:center;justify-content:center;text-align:center;word-break:break-word;${Z.dark`
|
|
373
373
|
background-color: ${h.color.onlight.textDisabled};
|
|
374
374
|
`}
|
|
375
|
-
|
|
375
|
+
`,Hp=e=>{const{components:t}=Cn.useContext(),n=e.messageType==="admin"?i.createElement(t.AdminMessage,{...e}):e.messageType==="admin.csat"?i.createElement(t.CSATMessage,{...e}):null;return i.createElement(Gp,{$marginBottom:fn(e.groupType)},n)},Cn=Ge({template:Hp,components:{AdminMessage:sp,CSATMessage:Pp}}),Gp=p.default.div`padding-inline:${ee.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>e}px;`,Wo={file:"attach",snippet:"snippet",site:"website",sb_sprinklr:"sprinklr",sb_salesforce:"salesforce",sb_confluence:"confluence",sb_zendesk:"zendesk",sb_desk:"snippet"},Vi=({actionbook:e,functionCalls:t,groundedness:n,agentMessageTemplates:r,flaggedTypes:o,onClickActionbook:s,onClickFunctionCall:a,onClickFunctionCallDetail:l,onClickGroundedness:c,onClickAgentMessageTemplate:d,topContent:m,bottomContent:f,renderCustomGroundednessIcon:g=y=>y.default,style:E={}})=>{const{iconColor:y="#000000",textColor:v="#000000",highlightColor:b=Mt.DEFAULT_PRIMARY}=E;return i.createElement(qo,null,m,e&&i.createElement(qo,null,i.createElement(dn,null,i.createElement(St,null,i.createElement(X,{size:16,type:"actionbook",color:y})),i.createElement(Kt,{$clickable:!!s,$highlightColor:b,variant:"body2",color:v,onClick:()=>s==null?void 0:s(e),maxTextLines:1},e.name))),t==null?void 0:t.map(_=>i.createElement(Jt,{key:_.key},i.createElement(St,null,i.createElement(X,{size:16,type:"function",color:y})),i.createElement(dn,null,i.createElement(Kt,{$clickable:!!a,$highlightColor:b,variant:"body2",color:v,onClick:()=>a==null?void 0:a(_),maxTextLines:1},_.name),l&&i.createElement(zp,{role:"button",onClick:()=>l==null?void 0:l(_)},i.createElement($,{variant:"body2",color:b},"View details"),i.createElement(X,{type:"chevron-right",size:16,color:b}))))),n==null?void 0:n.map(_=>i.createElement(Jt,{key:_.id},i.createElement(St,null,g({default:i.createElement(X,{size:16,type:Wo[_.source_type]??Wo.snippet,color:y}),sourceType:_.source_type})),i.createElement(Kt,{$clickable:!!c,$highlightColor:b,variant:"body2",color:v,onClick:()=>c==null?void 0:c(_),maxTextLines:1},_.preview_title))),r==null?void 0:r.map(_=>i.createElement(Jt,{key:_.key},i.createElement(St,null,i.createElement(X,{size:16,type:"template",color:y})),i.createElement(Kt,{$clickable:!!d,$highlightColor:b,variant:"body2",color:v,onClick:()=>d==null?void 0:d(_),maxTextLines:1},_.name))),!!(o!=null&&o.length)&&i.createElement(Vp,null,i.createElement(St,null,i.createElement(X,{size:16,type:"activity",color:y})),i.createElement(Yp,{variant:"body2",color:v},o.map(_=>_.replace(/_/g," ")).join(" · "))),f)},Yi=p.default($)`font-weight:400;`,Kt=p.default(Yi)`${({$clickable:e,$highlightColor:t})=>e&&D.css`
|
|
376
376
|
cursor: pointer;
|
|
377
377
|
text-decoration: underline;
|
|
378
378
|
&:hover {
|
|
379
379
|
color: ${t};
|
|
380
380
|
}
|
|
381
381
|
`}
|
|
382
|
-
`,Wt=p.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,ln=p.default.div`display:flex;gap:8px;align-items:center;word-break:break-word;`,Up=p.default(ln)`cursor:pointer;gap:4px;`,$n=p.default(ln)`flex-direction:row;align-items:center;`,Vo=p.default.div`display:flex;gap:4px;flex-direction:column;align-items:flex-start;`,Gi=u.createContext(null);function Bp({testerType:e,origin:t,children:n}){return i.createElement(Gi.Provider,{value:{testerType:e,isActionbookTester:e==="actionbook",origin:t}},e&&i.createElement(Hp,null),n)}const _t=()=>{const e=u.useContext(Gi);if(!e)throw new Error("_UNSAFE_INTERNAL_DashboardTesterProvider not found");return e},Hp=()=>{const{isActionbookTester:e}=_t();return i.createElement(tt.Template,{template:e?Gp:void 0},i.createElement(tt.MessageLogs,{component:zp}))},Gp=e=>i.createElement(Fi,{...e,testerMode:!0,maxBodyWidth:ee.WIDE_BODY_MAX_WIDTH}),zp=({extendedMessagePayload:e={}})=>{const{handlers:t}=me(),{manual:n,groundedness:r,function_calls:o,agent_message_templates:s,is_thinking:a}=e;return a||!n&&!(r!=null&&r.length)&&!(o!=null&&o.length)&&!(s!=null&&s.length)?i.createElement(i.Fragment,null):i.createElement(Vp,null,i.createElement(Yp,{$width:4}),i.createElement(Hi,{actionbook:n,functionCalls:o,groundedness:r,agentMessageTemplates:s,onClickFunctionCallDetail:t==null?void 0:t.onFunctionCallDetailClick,style:{iconColor:h.themedColor.textHighEmphasis,textColor:h.themedColor.textHighEmphasis,barColor:h.themedColor.textDisabled},topContent:i.createElement($,{variant:"caption4",color:h.themedColor.textLowEmphasis},"Only visible in the tester")}))},Vp=p.default.div`display:flex;gap:16px;margin:6px ${ee.HORIZONTAL_PADDING}px 4px ${ee.HORIZONTAL_PADDING+ee.AVATAR_SIZE}px;align-self:stretch;`,Yp=p.default.div`width:${({$width:e})=>e}px;background-color:${h.themedColor.textDisabled};border-radius:100px;flex-shrink:0;`,Yo=40,Wo=.9,Wp="[data-message-listitem]",qp='input, textarea, select, [role="textbox"], [contenteditable="true"]',Kp=({event:e,list:t,isMessageAnchor:n})=>{switch(e.key){case"PageDown":return t.clientHeight*Wo;case"PageUp":return t.clientHeight*-Wo;case"ArrowDown":return n?Yo:void 0;case"ArrowUp":return n?Yo*-1:void 0;default:return}},jp=({listRef:e,syncScrollPosition:t})=>u.useCallback(n=>{const r=e.current;if(!r||n.defaultPrevented||n.metaKey||n.altKey||n.ctrlKey)return;const o=n.target;if(!o||!r.contains(o)||o.closest(qp))return;const s=o===r||o.matches(Wp),a=Kp({event:n,list:r,isMessageAnchor:s});if(a==null||a===0)return;const l=Math.max(0,r.scrollHeight-r.clientHeight),c=Math.min(l,Math.max(0,r.scrollTop+a));c!==r.scrollTop&&(n.preventDefault(),t(c))},[e,t]),Xp="[data-message-listitem]",Zp=e=>Math.min(Math.max(0,e),1),Jp=e=>{const n=e.getRootNode().activeElement,r=n==null?void 0:n.closest(Xp),o=n===e||n===r;return!n||!e.contains(n)?null:o?e:n},Qp=({list:e,focusRestoreTarget:t})=>{if(!t)return;const r=e.getRootNode().activeElement,o=r===e||e.contains(r),s=t===e||e.contains(t);o&&s&&t.focus({preventScroll:!0})},e_=({depsForResetScrollPositionToBottom:e,listRef:t,loadThreshold:n,messagesLength:r,onLoadNext:o,onLoadPrev:s,onScroll:a})=>{const l=u.useRef(!1),c=u.useRef(void 0),d=u.useRef(0),m=u.useRef(0),f=u.useRef(null),g=u.useRef(null),_=u.useRef(null);u.useLayoutEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight)},e),u.useLayoutEffect(()=>{const E=t.current;E&&(c.current==="top"&&(E.scrollTop=E.scrollHeight-m.current,Qp({list:E,focusRestoreTarget:f.current}),f.current=null),c.current==="bottom"&&(E.scrollTop=d.current),c.current=void 0)},[t,r]);const v=u.useCallback(async E=>{const C=t.current;if(!C||(a==null||a(E),m.current=C.scrollHeight-C.scrollTop,d.current=C.scrollTop,l.current))return;const S=C.clientHeight*Zp(n);if(C.scrollTop<=S){l.current=!0,c.current="top",f.current=Jp(C),await s(),l.current=!1;return}if(C.scrollHeight-C.scrollTop-C.clientHeight<=S){l.current=!0,c.current="bottom",await o(),l.current=!1;return}c.current=void 0},[t,n,o,s,a]),y=u.useCallback(E=>{const C=t.current;if(!C)return;const S=_.current;if(S!=null){if(S===C.scrollTop){_.current=null;return}_.current=null}const x=g.current;if(x!=null&&x===C.scrollTop){g.current=null,_.current=C.scrollTop,v(E);return}g.current=null,v(E)},[v,t]),b=u.useCallback(E=>{const C=t.current;C&&(g.current=E,_.current=null,C.scrollTop=E,C.dispatchEvent(new Event("scroll",{bubbles:!0})))},[t]);return u.useLayoutEffect(()=>()=>{g.current=null,_.current=null},[]),{handleScroll:y,syncScrollPosition:b}},t_=u.forwardRef(function(t,n){const{messages:r,renderMessage:o,loading:s,LoadingComponent:a,error:l,ErrorComponent:c,empty:d,EmptyComponent:m,messageTopArea:f,messageBottomArea:g,overlayArea:_,onLoadPrev:v,onLoadNext:y,loadThreshold:b=.05,onScroll:E=ge,depsForResetScrollPositionToBottom:C,stackDirection:S="top",bottomSpacerHeight:x=0,"aria-label":w}=t,k=u.useRef(null),I=u.useCallback(Y=>{k.current=Y,n&&(typeof n=="function"?n(Y):n.current=Y)},[n]),{handleScroll:M,syncScrollPosition:O}=e_({depsForResetScrollPositionToBottom:C,listRef:k,loadThreshold:b,messagesLength:r.length,onLoadNext:y,onLoadPrev:v,onScroll:E}),F=jp({listRef:k,syncScrollPosition:O});return l?i.createElement(i.Fragment,null,c):s?i.createElement(i.Fragment,null,a):i.createElement(n_,{id:"infinite-list-container"},i.createElement(r_,{id:"infinite-list-inner",ref:I,onScroll:M,onKeyDown:F,role:"list","aria-label":w,tabIndex:0},S==="bottom"&&i.createElement("div",{style:{flexGrow:1}}),f,d?m:r.map((Y,z)=>o({message:Y,index:z})),g,x>0&&i.createElement("div",{style:{minHeight:x}})),i.createElement(o_,{id:"infinite-list-overlay-container"},i.createElement(s_,{id:"infinite-list-overlay"},_)))}),n_=p.default.div`display:flex;position:relative;flex:1;overflow:hidden;`,r_=p.default.div`display:flex;flex:1;flex-direction:column;overflow-x:hidden;overflow-y:auto;overscroll-behavior:contain;scrollbar-color:${h.themedColor.textLowEmphasis}transparent;&::-webkit-scrollbar-thumb:hover{background-color:transparent;}`,o_=p.default.div`position:absolute;top:0;bottom:0;left:0;right:0;pointer-events:none;`,s_=p.default.div`pointer-events:auto;`,je=({as:e,type:t,size:n=16,color:r,disabled:o,children:s,...a})=>{const l=o?h.themedColor.textDisabled:h.themedColor.textHighEmphasis;return i.createElement(i_,{as:e,disabled:o,...a},i.createElement(Q,{type:t,size:n,color:r??l}),s)},i_=p.default.button`all:unset;padding:4px;cursor:pointer;display:flex;align-items:center;justify-content:center;${Ae}&:disabled{cursor:not-allowed;}`,a_=({files:e,initialIndex:t=0,onClose:n,visible:r})=>{const[o,s]=u.useState(t),[a,l]=u.useState(!1),{stringSet:c,format:d}=se(),{config:m}=me(),f=e.length,g=e[o],_=m.conversation.fileViewer.downloadEnabled,v=f>1,y=(g==null?void 0:g.type)||"",b=He(y),E=cn(y),C=!Hm(y);u.useEffect(()=>{r&&(s(t),l(!1))},[r,t]);const S=u.useCallback(()=>{o>0&&(s(w=>w-1),l(!1))},[o]),x=u.useCallback(()=>{o<f-1&&(s(w=>w+1),l(!1))},[o,f]);return u.useEffect(()=>{if(!r)return;const w=k=>{k.key==="ArrowLeft"?S():k.key==="ArrowRight"&&x()};return window.addEventListener("keydown",w),()=>window.removeEventListener("keydown",w)},[r,S,x]),!r||!g?null:i.createElement(nt,{onClose:n,visible:r,portalContainerId:Ce.MODAL_ROOT,"aria-label":(g==null?void 0:g.name)||c.IMAGE_VIEWER__DEFAULT_TITLE},i.createElement(l_,null,i.createElement(c_,null,i.createElement(u_,null,i.createElement(d_,null,i.createElement($,{variant:"button",maxTextLines:1,color:h.color.ondark.textHighEmphasis},g.name||c.IMAGE_VIEWER__DEFAULT_TITLE),g.timestamp&&i.createElement($,{variant:"caption2",color:h.color.ondark.textHighEmphasis},d(new Date(g.timestamp),"h:mm a")))),i.createElement(m_,{type:"close",size:18,color:h.color.ondark.textHighEmphasis,"aria-label":c.A11Y_IMAGE_VIEWER_CLOSE,onClick:n})),i.createElement(f_,{onClick:w=>w.currentTarget===w.target&&n()},v&&i.createElement(qo,{$position:"left",type:"chevron-right",size:22,color:h.color.ondark.textHighEmphasis,onClick:S,"aria-label":c.A11Y_IMAGE_VIEWER_PREVIOUS,disabled:o===0,$flipped:!0}),i.createElement(g_,null,b&&i.createElement(i.Fragment,null,!a&&i.createElement(h_,null,i.createElement(at,{size:32},i.createElement(Q,{type:"spinner",color:"textLowEmphasis",size:32}))),i.createElement(p_,{src:g.url,alt:g.name||"Image",$loaded:a,onLoad:()=>l(!0)})),E&&i.createElement(__,{controls:!0},i.createElement("source",{src:g.url,type:y})),C&&i.createElement(E_,null,i.createElement($,{variant:"h1",color:h.themedColor.textHighEmphasis},c.FILE_VIEWER__UNSUPPORT))),v&&i.createElement(qo,{$position:"right",type:"chevron-right",size:22,color:h.color.ondark.textHighEmphasis,onClick:x,"aria-label":c.A11Y_IMAGE_VIEWER_NEXT,disabled:o===f-1})),i.createElement(b_,null,v&&i.createElement($,{variant:"body2",color:h.color.ondark.textHighEmphasis},o+1,"/",f),_&&!C&&i.createElement(C_,{forwardedAs:"a",href:g.url,download:g.name||"file",type:"download",size:24,color:h.color.ondark.textHighEmphasis,"aria-label":c.A11Y_IMAGE_VIEWER_DOWNLOAD}))))},l_=p.default.div`position:fixed;inset:0;outline:none;display:flex;flex-direction:column;background-color:${h.themedColor.bg_50_600};`,c_=p.default.header`display:flex;align-items:center;justify-content:space-between;padding:12px 12px 12px 16px;min-height:56px;background-color:${h.color.overlay.dark};`,u_=p.default.div`flex:1;min-width:0;padding-right:8px;`,d_=p.default.div`display:flex;flex-direction:column;gap:2px;`,m_=p.default(je)`flex-shrink:0;width:28px;height:28px;border-radius:50%;`,En=p.default.div`display:flex;align-items:center;justify-content:center;`,f_=p.default(En)`flex:1;min-height:0;position:relative;`,g_=p.default(En)`position:relative;max-width:100%;max-height:100%;`,h_=p.default(En)`position:absolute;inset:0;`,p_=p.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.default.video`max-width:100%;max-height:100%;object-fit:contain;`,E_=p.default(En)`flex-direction:column;gap:16px;`,qo=p.default(je)`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:${h.color.overlay.dark};&:disabled{opacity:0.3;}`,b_=p.default.footer`position:relative;display:flex;align-items:center;justify-content:center;padding:16px;min-height:56px;background-color:${h.color.overlay.dark};`,C_=p.default(je)`position:absolute;right:16px;top:50%;transform:translateY(-50%);padding:0;width:24px;height:24px;`,Ir=({title:e,titleId:t,description:n,descriptionId:r,negativeText:o,positiveText:s,onCancel:a,onConfirm:l,buttonLayout:c="horizontal",styles:d})=>{const m=o!==void 0&&a!==void 0,f=s!==void 0&&l!==void 0,g=m?i.createElement(x_,{type:"button",onClick:a,$fullWidth:c!=="horizontal",$background:d==null?void 0:d.negativeBackground,$borderColor:d==null?void 0:d.negativeBorderColor},i.createElement($,{variant:"button",color:(d==null?void 0:d.negativeText)??h.themedColor.textHighEmphasis},o)):null,_=f?i.createElement(T_,{type:"button",onClick:l,$fullWidth:c!=="horizontal",$background:d==null?void 0:d.positiveBackground,$borderColor:d==null?void 0:d.positiveBorderColor},i.createElement($,{variant:"button",color:(d==null?void 0:d.positiveText)??h.themedColor.textHighEmphasisInverse},s)):null;return i.createElement(v_,null,i.createElement(y_,null,i.createElement($,{as:"div",id:t,variant:"h2",color:(d==null?void 0:d.titleColor)??h.themedColor.textHighEmphasis},e)),i.createElement(S_,null,i.createElement($,{as:"div",id:r,variant:"body3",color:(d==null?void 0:d.descriptionColor)??h.themedColor.textMidEmphasis},n)),i.createElement(A_,{$buttonLayout:c},c==="horizontal"?i.createElement(i.Fragment,null,g,_):i.createElement(i.Fragment,null,_,g)))},v_=p.default.div`display:flex;flex-direction:column;width:280px;border-radius:16px;overflow:hidden;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,y_=p.default.div`padding:24px 24px 16px;`,S_=p.default.div`padding-inline:24px;`,A_=p.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;`,x_=p.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;}`,T_=p.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??h.themedColor.textHighEmphasis};white-space:nowrap;overflow:hidden;text-overflow:ellipsis;&:hover{opacity:0.8;}`,qt=16,I_=({status:e})=>e===Jt.COMPLETED?i.createElement(Q,{type:"done-circle",size:qt,color:h.themedColor.textHighEmphasis}):e===Jt.CANCELED?i.createElement(Q,{type:"stop-circle",size:qt,color:h.themedColor.textLowEmphasis}):i.createElement(at,{size:qt},i.createElement(Q,{type:"spinner",size:qt,color:h.themedColor.textHighEmphasis})),zi=24,w_=8,M_=40,k_=({task:e,isFirst:t,isLast:n})=>i.createElement(R_,{role:"listitem"},i.createElement(L_,null,i.createElement(Ko,{$hidden:t}),i.createElement(O_,null,i.createElement(I_,{status:e.status})),i.createElement(Ko,{$hidden:n})),i.createElement(N_,null,i.createElement($,{as:"div",variant:"body3",color:e.status===Jt.CANCELED?h.themedColor.textLowEmphasis:h.themedColor.textHighEmphasis},e.user_facing_title))),R_=p.default.div`display:flex;gap:4px;`,L_=p.default.div`display:flex;flex-direction:column;align-items:center;width:${zi}px;flex-shrink:0;`,Ko=p.default.div`width:1px;flex:1;transform:translateX(-25%);${({$hidden:e})=>e&&"visibility: hidden;"}background-image:repeating-linear-gradient( to bottom,${h.themedColor.textHighEmphasis}0 2px,transparent 2px 4px );`,O_=p.default.div`display:flex;height:${zi}px;align-items:center;justify-content:center;`,N_=p.default.div`display:flex;flex:1;align-items:center;box-sizing:border-box;min-width:0;min-height:${M_}px;padding-block:${w_}px;`,D_=({steward:e,onCancelSteward:t})=>{const{logger:n}=me(),[r,o]=u.useState(!1),[s,a]=u.useState(!1),l=!!e.cancellation_option,c=ba(e.status);return i.createElement($_,{$marginBottom:un("single")},i.createElement(P_,null,i.createElement(F_,null,i.createElement(U_,null,i.createElement($,{as:"div",variant:"caption1",color:h.themedColor.textHighEmphasis},e.title),!!e.description&&i.createElement($,{as:"div",variant:"caption4",color:h.themedColor.textLowEmphasis},e.description)),l&&i.createElement(z_,{type:"button","aria-label":"Stop steward",disabled:s,onClick:()=>o(!0)},i.createElement(Q,{type:"stop",size:16,color:s?h.themedColor.textDisabled:h.themedColor.textHighEmphasis}))),i.createElement(B_,null),e.tasks.length===0?c!==Tt.IN_PROGRESS?null:i.createElement(G_,null,i.createElement(at,{size:16},i.createElement(Q,{type:"spinner",size:16,color:h.themedColor.textHighEmphasis}))):i.createElement(H_,{role:"list"},e.tasks.map((d,m)=>i.createElement(k_,{key:d.id,task:d,isFirst:m===0,isLast:m===e.tasks.length-1})))),r&&e.cancellation_option&&i.createElement(nt,{portalContainerId:Ce.WINDOW,visible:r,onClose:()=>o(!1)},i.createElement(Ir,{title:e.cancellation_option.title,description:e.cancellation_option.description,negativeText:e.cancellation_option.negative_text,positiveText:e.cancellation_option.positive_text,onCancel:()=>o(!1),onConfirm:async()=>{o(!1),a(!0);try{await(t==null?void 0:t())}catch(d){n.warn("steward.cancelSteward: failed",d)}finally{a(!1)}}})))},$_=p.default.div`display:flex;flex-direction:column;margin:0 ${ee.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>`${e}px`};
|
|
383
|
-
`,
|
|
382
|
+
`,St=p.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,dn=p.default.div`display:flex;gap:8px;align-items:center;word-break:break-word;`,zp=p.default(dn)`cursor:pointer;gap:4px;`,Jt=p.default(dn)`flex-direction:row;align-items:center;`,Vp=p.default(Jt)`align-items:flex-start;max-width:100%;`,Yp=p.default(Yi)`min-width:0;`,qo=p.default.div`display:flex;gap:4px;flex-direction:column;align-items:flex-start;`,Wi=u.createContext(null);function Wp({testerType:e,origin:t,children:n}){return i.createElement(Wi.Provider,{value:{testerType:e,isActionbookTester:e==="actionbook",origin:t}},e&&i.createElement(qp,null),n)}const _t=()=>{const e=u.useContext(Wi);if(!e)throw new Error("_UNSAFE_INTERNAL_DashboardTesterProvider not found");return e},qp=()=>{const{isActionbookTester:e}=_t();return i.createElement(rt.Template,{template:e?Kp:void 0},i.createElement(rt.MessageLogs,{component:jp}))},Kp=e=>i.createElement(Hi,{...e,testerMode:!0,maxBodyWidth:ee.WIDE_BODY_MAX_WIDTH}),jp=({extendedMessagePayload:e={}})=>{const{handlers:t}=ae(),{manual:n,groundedness:r,function_calls:o,agent_message_templates:s,flagged_types:a,is_thinking:l}=e;return l||!n&&!(r!=null&&r.length)&&!(o!=null&&o.length)&&!(s!=null&&s.length)&&!(a!=null&&a.length)?i.createElement(i.Fragment,null):i.createElement(Xp,null,i.createElement(Zp,{$width:4}),i.createElement(Vi,{actionbook:n,functionCalls:o,groundedness:r,agentMessageTemplates:s,flaggedTypes:a,onClickFunctionCallDetail:t==null?void 0:t.onFunctionCallDetailClick,style:{iconColor:h.themedColor.textHighEmphasis,textColor:h.themedColor.textHighEmphasis,barColor:h.themedColor.textDisabled},topContent:i.createElement($,{variant:"caption4",color:h.themedColor.textLowEmphasis},"Only visible in the tester")}))},Xp=p.default.div`display:flex;gap:16px;margin:6px ${ee.HORIZONTAL_PADDING}px 4px ${ee.HORIZONTAL_PADDING+ee.AVATAR_SIZE}px;align-self:stretch;`,Zp=p.default.div`width:${({$width:e})=>e}px;background-color:${h.themedColor.textDisabled};border-radius:100px;flex-shrink:0;`,Ko=40,jo=.9,Jp="[data-message-listitem]",Qp='input, textarea, select, [role="textbox"], [contenteditable="true"]',e_=({event:e,list:t,isMessageAnchor:n})=>{switch(e.key){case"PageDown":return t.clientHeight*jo;case"PageUp":return t.clientHeight*-jo;case"ArrowDown":return n?Ko:void 0;case"ArrowUp":return n?Ko*-1:void 0;default:return}},t_=({listRef:e,syncScrollPosition:t})=>u.useCallback(n=>{const r=e.current;if(!r||n.defaultPrevented||n.metaKey||n.altKey||n.ctrlKey)return;const o=n.target;if(!o||!r.contains(o)||o.closest(Qp))return;const s=o===r||o.matches(Jp),a=e_({event:n,list:r,isMessageAnchor:s});if(a==null||a===0)return;const l=Math.max(0,r.scrollHeight-r.clientHeight),c=Math.min(l,Math.max(0,r.scrollTop+a));c!==r.scrollTop&&(n.preventDefault(),t(c))},[e,t]),n_="[data-message-listitem]",r_=e=>Math.min(Math.max(0,e),1),o_=e=>{const n=e.getRootNode().activeElement,r=n==null?void 0:n.closest(n_),o=n===e||n===r;return!n||!e.contains(n)?null:o?e:n},s_=({list:e,focusRestoreTarget:t})=>{if(!t)return;const r=e.getRootNode().activeElement,o=r===e||e.contains(r),s=t===e||e.contains(t);o&&s&&t.focus({preventScroll:!0})},i_=({depsForResetScrollPositionToBottom:e,listRef:t,loadThreshold:n,messagesLength:r,onLoadNext:o,onLoadPrev:s,onScroll:a})=>{const l=u.useRef(!1),c=u.useRef(void 0),d=u.useRef(0),m=u.useRef(0),f=u.useRef(null),g=u.useRef(null),E=u.useRef(null);u.useLayoutEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight)},e),u.useLayoutEffect(()=>{const _=t.current;_&&(c.current==="top"&&(_.scrollTop=_.scrollHeight-m.current,s_({list:_,focusRestoreTarget:f.current}),f.current=null),c.current==="bottom"&&(_.scrollTop=d.current),c.current=void 0)},[t,r]);const y=u.useCallback(async _=>{const C=t.current;if(!C||(a==null||a(_),m.current=C.scrollHeight-C.scrollTop,d.current=C.scrollTop,l.current))return;const x=C.clientHeight*r_(n);if(C.scrollTop<=x){l.current=!0,c.current="top",f.current=o_(C),await s(),l.current=!1;return}if(C.scrollHeight-C.scrollTop-C.clientHeight<=x){l.current=!0,c.current="bottom",await o(),l.current=!1;return}c.current=void 0},[t,n,o,s,a]),v=u.useCallback(_=>{const C=t.current;if(!C)return;const x=E.current;if(x!=null){if(x===C.scrollTop){E.current=null;return}E.current=null}const A=g.current;if(A!=null&&A===C.scrollTop){g.current=null,E.current=C.scrollTop,y(_);return}g.current=null,y(_)},[y,t]),b=u.useCallback(_=>{const C=t.current;C&&(g.current=_,E.current=null,C.scrollTop=_,C.dispatchEvent(new Event("scroll",{bubbles:!0})))},[t]);return u.useLayoutEffect(()=>()=>{g.current=null,E.current=null},[]),{handleScroll:v,syncScrollPosition:b}},a_=u.forwardRef(function(t,n){const{messages:r,renderMessage:o,loading:s,LoadingComponent:a,error:l,ErrorComponent:c,empty:d,EmptyComponent:m,messageTopArea:f,messageBottomArea:g,overlayArea:E,onLoadPrev:y,onLoadNext:v,loadThreshold:b=.05,onScroll:_=ce,depsForResetScrollPositionToBottom:C,stackDirection:x="top",bottomSpacerHeight:A=0,"aria-label":w}=t,M=u.useRef(null),k=u.useCallback(Y=>{M.current=Y,n&&(typeof n=="function"?n(Y):n.current=Y)},[n]),{handleScroll:R,syncScrollPosition:O}=i_({depsForResetScrollPositionToBottom:C,listRef:M,loadThreshold:b,messagesLength:r.length,onLoadNext:v,onLoadPrev:y,onScroll:_}),z=t_({listRef:M,syncScrollPosition:O});return l?i.createElement(i.Fragment,null,c):s?i.createElement(i.Fragment,null,a):i.createElement(l_,{id:"infinite-list-container"},i.createElement(c_,{id:"infinite-list-inner",ref:k,onScroll:R,onKeyDown:z,role:"list","aria-label":w,tabIndex:0},x==="bottom"&&i.createElement("div",{style:{flexGrow:1}}),f,d?m:r.map((Y,P)=>o({message:Y,index:P})),g,A>0&&i.createElement("div",{style:{minHeight:A}})),i.createElement(u_,{id:"infinite-list-overlay-container"},i.createElement(d_,{id:"infinite-list-overlay"},E)))}),l_=p.default.div`display:flex;position:relative;flex:1;overflow:hidden;`,c_=p.default.div`display:flex;flex:1;flex-direction:column;overflow-x:hidden;overflow-y:auto;overscroll-behavior:contain;scrollbar-color:${h.themedColor.textLowEmphasis}transparent;&::-webkit-scrollbar-thumb:hover{background-color:transparent;}`,u_=p.default.div`position:absolute;top:0;bottom:0;left:0;right:0;pointer-events:none;`,d_=p.default.div`pointer-events:auto;`,Ze=({as:e,type:t,size:n=16,color:r,disabled:o,children:s,...a})=>{const l=o?h.themedColor.textDisabled:h.themedColor.textHighEmphasis;return i.createElement(m_,{as:e,disabled:o,...a},i.createElement(X,{type:t,size:n,color:r??l}),s)},m_=p.default.button`all:unset;padding:4px;cursor:pointer;display:flex;align-items:center;justify-content:center;${Ae}&:disabled{cursor:not-allowed;}`,f_=({files:e,initialIndex:t=0,onClose:n,visible:r})=>{const[o,s]=u.useState(t),[a,l]=u.useState(!1),{stringSet:c,format:d}=se(),{config:m}=ae(),f=e.length,g=e[o],E=m.conversation.fileViewer.downloadEnabled,y=f>1,v=(g==null?void 0:g.type)||"",b=ze(v),_=mn(v),C=!Wm(v);u.useEffect(()=>{r&&(s(t),l(!1))},[r,t]);const x=u.useCallback(()=>{o>0&&(s(w=>w-1),l(!1))},[o]),A=u.useCallback(()=>{o<f-1&&(s(w=>w+1),l(!1))},[o,f]);return u.useEffect(()=>{if(!r)return;const w=M=>{M.key==="ArrowLeft"?x():M.key==="ArrowRight"&&A()};return window.addEventListener("keydown",w),()=>window.removeEventListener("keydown",w)},[r,x,A]),!r||!g?null:i.createElement(ot,{onClose:n,visible:r,portalContainerId:be.MODAL_ROOT,"aria-label":(g==null?void 0:g.name)||c.IMAGE_VIEWER__DEFAULT_TITLE},i.createElement(g_,null,i.createElement(h_,null,i.createElement(p_,null,i.createElement(__,null,i.createElement($,{variant:"button",maxTextLines:1,color:h.color.ondark.textHighEmphasis},g.name||c.IMAGE_VIEWER__DEFAULT_TITLE),g.timestamp&&i.createElement($,{variant:"caption2",color:h.color.ondark.textHighEmphasis},d(new Date(g.timestamp),"h:mm a")))),i.createElement(E_,{type:"close",size:18,color:h.color.ondark.textHighEmphasis,"aria-label":c.A11Y_IMAGE_VIEWER_CLOSE,onClick:n})),i.createElement(b_,null,y&&i.createElement(Xo,{$position:"left",type:"chevron-right",size:22,color:h.color.ondark.textHighEmphasis,onClick:x,"aria-label":c.A11Y_IMAGE_VIEWER_PREVIOUS,disabled:o===0,$flipped:!0}),i.createElement(C_,{onClick:w=>w.currentTarget===w.target&&n()},b&&i.createElement(i.Fragment,null,!a&&i.createElement(v_,null,i.createElement(at,{size:32},i.createElement(X,{type:"spinner",color:"textLowEmphasis",size:32}))),i.createElement(y_,{src:g.url,alt:g.name||"Image",$loaded:a,onLoad:()=>l(!0)})),_&&i.createElement(S_,{controls:!0},i.createElement("source",{src:g.url,type:v})),C&&i.createElement(A_,null,i.createElement($,{variant:"h1",color:h.themedColor.textHighEmphasis},c.FILE_VIEWER__UNSUPPORT))),y&&i.createElement(Xo,{$position:"right",type:"chevron-right",size:22,color:h.color.ondark.textHighEmphasis,onClick:A,"aria-label":c.A11Y_IMAGE_VIEWER_NEXT,disabled:o===f-1})),i.createElement(x_,null,y&&i.createElement($,{variant:"body2",color:h.color.ondark.textHighEmphasis},o+1,"/",f),E&&!C&&i.createElement(T_,{forwardedAs:"a",href:g.url,download:g.name||"file",type:"download",size:24,color:h.color.ondark.textHighEmphasis,"aria-label":c.A11Y_IMAGE_VIEWER_DOWNLOAD}))))},g_=p.default.div`position:fixed;top:0;left:0;right:0;bottom:0;height:100dvh;outline:none;display:flex;flex-direction:column;background-color:${h.themedColor.bg_50_600};`,h_=p.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:${h.color.overlay.dark};`,p_=p.default.div`flex:1;min-width:0;padding-right:8px;`,__=p.default.div`display:flex;flex-direction:column;gap:2px;`,E_=p.default(Ze)`flex-shrink:0;width:28px;height:28px;border-radius:50%;`,vn=p.default.div`display:flex;align-items:center;justify-content:center;`,b_=p.default(vn)`flex:1;min-height:0;position:relative;`,C_=p.default(vn)`position:relative;width:100%;height:100%;min-width:0;min-height:0;`,v_=p.default(vn)`position:absolute;inset:0;pointer-events:none;`,y_=p.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;`,S_=p.default.video`max-width:100%;max-height:100%;object-fit:contain;`,A_=p.default(vn)`flex-direction:column;gap:16px;`,Xo=p.default(Ze)`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:${h.color.overlay.dark};&:disabled{opacity:0.3;}`,x_=p.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:${h.color.overlay.dark};`,T_=p.default(Ze)`position:absolute;right:16px;top:50%;transform:translateY(-50%);padding:0;width:24px;height:24px;`,kr=({title:e,titleId:t,description:n,descriptionId:r,negativeText:o,positiveText:s,onCancel:a,onConfirm:l,buttonLayout:c="horizontal",styles:d})=>{const m=o!==void 0&&a!==void 0,f=s!==void 0&&l!==void 0,g=m?i.createElement(R_,{type:"button",onClick:a,$fullWidth:c!=="horizontal",$background:d==null?void 0:d.negativeBackground,$borderColor:d==null?void 0:d.negativeBorderColor},i.createElement($,{variant:"button",color:(d==null?void 0:d.negativeText)??h.themedColor.textHighEmphasis},o)):null,E=f?i.createElement(L_,{type:"button",onClick:l,$fullWidth:c!=="horizontal",$background:d==null?void 0:d.positiveBackground,$borderColor:d==null?void 0:d.positiveBorderColor},i.createElement($,{variant:"button",color:(d==null?void 0:d.positiveText)??h.themedColor.textHighEmphasisInverse},s)):null;return i.createElement(I_,null,i.createElement(w_,null,i.createElement($,{as:"div",id:t,variant:"h2",color:(d==null?void 0:d.titleColor)??h.themedColor.textHighEmphasis},e)),i.createElement(M_,null,i.createElement($,{as:"div",id:r,variant:"body3",color:(d==null?void 0:d.descriptionColor)??h.themedColor.textMidEmphasis},n)),i.createElement(k_,{$buttonLayout:c},c==="horizontal"?i.createElement(i.Fragment,null,g,E):i.createElement(i.Fragment,null,E,g)))},I_=p.default.div`display:flex;flex-direction:column;width:280px;border-radius:16px;overflow:hidden;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,w_=p.default.div`padding:24px 24px 16px;`,M_=p.default.div`padding-inline:24px;`,k_=p.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;`,R_=p.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;}`,L_=p.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??h.themedColor.textHighEmphasis};white-space:nowrap;overflow:hidden;text-overflow:ellipsis;&:hover{opacity:0.8;}`,jt=16,O_=({status:e})=>e===tn.COMPLETED?i.createElement(X,{type:"done-circle",size:jt,color:h.themedColor.textHighEmphasis}):e===tn.CANCELED?i.createElement(X,{type:"stop-circle",size:jt,color:h.themedColor.textLowEmphasis}):i.createElement(at,{size:jt},i.createElement(X,{type:"spinner",size:jt,color:h.themedColor.textHighEmphasis})),qi=24,N_=8,D_=40,$_=({task:e,isFirst:t,isLast:n})=>i.createElement(P_,{role:"listitem"},i.createElement(F_,null,i.createElement(Zo,{$hidden:t}),i.createElement(U_,null,i.createElement(O_,{status:e.status})),i.createElement(Zo,{$hidden:n})),i.createElement(B_,null,i.createElement($,{as:"div",variant:"body3",color:e.status===tn.CANCELED?h.themedColor.textLowEmphasis:h.themedColor.textHighEmphasis},e.user_facing_title))),P_=p.default.div`display:flex;gap:4px;`,F_=p.default.div`display:flex;flex-direction:column;align-items:center;width:${qi}px;flex-shrink:0;`,Zo=p.default.div`width:1px;flex:1;transform:translateX(-25%);${({$hidden:e})=>e&&"visibility: hidden;"}background-image:repeating-linear-gradient( to bottom,${h.themedColor.textHighEmphasis}0 2px,transparent 2px 4px );`,U_=p.default.div`display:flex;height:${qi}px;align-items:center;justify-content:center;`,B_=p.default.div`display:flex;flex:1;align-items:center;box-sizing:border-box;min-width:0;min-height:${D_}px;padding-block:${N_}px;`,H_=({steward:e,onCancelSteward:t})=>{const{logger:n}=ae(),[r,o]=u.useState(!1),[s,a]=u.useState(!1),l=!!e.cancellation_option,c=Sa(e.status);return i.createElement(G_,{$marginBottom:fn("single")},i.createElement(z_,null,i.createElement(V_,null,i.createElement(Y_,null,i.createElement($,{as:"div",variant:"caption1",color:h.themedColor.textHighEmphasis},e.title),!!e.description&&i.createElement($,{as:"div",variant:"caption4",color:h.themedColor.textLowEmphasis},e.description)),l&&i.createElement(j_,{type:"button","aria-label":"Stop steward",disabled:s,onClick:()=>o(!0)},i.createElement(X,{type:"stop",size:16,color:s?h.themedColor.textDisabled:h.themedColor.textHighEmphasis}))),i.createElement(W_,null),e.tasks.length===0?c!==It.IN_PROGRESS?null:i.createElement(K_,null,i.createElement(at,{size:16},i.createElement(X,{type:"spinner",size:16,color:h.themedColor.textHighEmphasis}))):i.createElement(q_,{role:"list"},e.tasks.map((d,m)=>i.createElement($_,{key:d.id,task:d,isFirst:m===0,isLast:m===e.tasks.length-1})))),r&&e.cancellation_option&&i.createElement(ot,{portalContainerId:be.WINDOW,visible:r,onClose:()=>o(!1)},i.createElement(kr,{title:e.cancellation_option.title,description:e.cancellation_option.description,negativeText:e.cancellation_option.negative_text,positiveText:e.cancellation_option.positive_text,onCancel:()=>o(!1),onConfirm:async()=>{o(!1),a(!0);try{await(t==null?void 0:t())}catch(d){n.warn("steward.cancelSteward: failed",d)}finally{a(!1)}}})))},G_=p.default.div`display:flex;flex-direction:column;margin:0 ${ee.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>`${e}px`};
|
|
383
|
+
`,z_=p.default.div`display:flex;flex-direction:column;border-radius:12px;overflow:hidden;padding:16px;border:1px solid ${h.themedColor.bg_300_500};background-color:${h.themedColor.bg_50_600};box-shadow:0 8px 20px rgba(0,0,0,0.12);`,V_=p.default.div`display:flex;flex-direction:row;align-items:flex-start;gap:8px;`,Y_=p.default.div`display:flex;flex-direction:column;gap:4px;flex:1;min-width:0;`,W_=p.default.div`height:1px;margin-block:12px;background-color:${h.themedColor.bg_200_400};`,q_=p.default.div`display:flex;flex-direction:column;`,K_=p.default.div`display:flex;width:100%;height:40px;align-items:center;justify-content:center;`,j_=p.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:${h.themedColor.textHighEmphasis};background-color:${h.themedColor.bg_200_400};&:hover:not(:disabled){opacity:0.8;}&:disabled{cursor:default;}`,X_=({className:e,label:t,onClick:n})=>{const{colors:r}=D.useTheme(),{conversation:o}=oe(),s={newMessages:o.newMessagesButton()};return i.createElement(Z_,{className:e,onClick:n,...s.newMessages.props},i.createElement($,{variant:"button",color:r.base.primaryContrastContent},t),i.createElement(X,{size:16,type:"chevron-down",color:r.base.primaryContrastContent}),s.newMessages.descriptionNode)},Z_=p.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;}${Ae}`,Rr=({iconSize:e=64,icon:t,className:n,label:r,children:o})=>i.createElement(Q_,{className:n},t&&i.createElement(X,{type:t,size:e,color:h.themedColor.textLowEmphasis}),r&&i.createElement($,{variant:"body1",color:h.themedColor.textMidEmphasis},r),o),J_=p.default.div`position:relative;display:flex;justify-content:center;align-items:center;width:100%;height:100%;`,Q_=p.default.div`display:flex;flex-direction:column;min-height:104px;align-items:center;gap:20px;text-align:center;`,eE=({label:e="Something went wrong",icon:t="error",action:n,...r})=>i.createElement(Rr,{icon:t,label:e,...r},n&&i.createElement(tE,{onClick:n.onClick,label:n.label??"Retry"})),tE=({label:e,onClick:t})=>{const{conversation:n}=oe();return i.createElement(nE,{tabIndex:0,...n.retryButton(e).props,onClick:t},i.createElement(X,{type:"refresh",size:20}),i.createElement($,{variant:"button",color:h.color.primary.main},e))},nE=p.default.button`all:unset;display:flex;cursor:pointer;gap:4px;align-items:center;justify-content:center;${Ae}`,rE=({iconSize:e=48,className:t})=>i.createElement(at,{size:e,className:t}),oE=({label:e="No channels",icon:t="chat",...n})=>i.createElement(Rr,{icon:t,label:e,...n}),sE=({label:e="No messages",icon:t="message",...n})=>i.createElement(Rr,{icon:t,label:e,...n}),iE=e=>{const{components:t}=yn.useContext(),n=e.type==="loading"?i.createElement(t.Loading,{...e}):e.type==="error"?i.createElement(t.Error,{...e}):e.type==="noChannels"?i.createElement(t.NoChannels,{...e}):e.type==="noMessages"?i.createElement(t.NoMessages,{...e}):null;return n&&i.createElement(J_,null,n)},yn=Ge({template:iE,components:{Loading:rE,Error:eE,NoChannels:oE,NoMessages:sE}}),wt=e=>{const{Template:t}=yn.useContext();return i.createElement(t,{...e})},aE=[0,150,450];function lE({enabled:e}){const{state:t,actions:n}=_i(),r=u.useRef(0),o=u.useRef(t.isAwayFromBottom);o.current=t.isAwayFromBottom,u.useEffect(()=>{if(!e){r.current+=1;return}const s=r.current+1;r.current=s;const a=aE.map(l=>setTimeout(()=>{Me(()=>{r.current===s&&(o.current||n.scrollToBottom(!1))})},l));return()=>{r.current+=1,a.forEach(l=>clearTimeout(l))}},[n.scrollToBottom,e])}const cE=({className:e,date:t=Date.now(),role:n,style:r})=>{const{format:o,stringSet:s}=se();return i.createElement(uE,{id:`${$e}-date-separator`,role:n,style:r,className:e},i.createElement($,{variant:"caption4",color:h.themedColor.textMidEmphasis},o(t,s.DATE_FORMAT__MESSAGE_LIST__DATE_SEPARATOR)))},uE=p.default.div`display:flex;justify-content:center;align-items:center;text-align:center;word-break:break-word;`,dE=({className:e,style:t,onClick:n})=>{const{conversation:r}=oe(),o={scrollToBottom:r.scrollToBottomButton()};return i.createElement(mE,{className:e,style:t,onClick:n,tabIndex:0,...o.scrollToBottom.props},i.createElement(X,{size:24,type:"chevron-down",color:h.color.primary.main}),o.scrollToBottom.descriptionNode??null)},mE=p.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);${Z.light`
|
|
384
384
|
background-color: ${h.color.background50};
|
|
385
385
|
&:hover {
|
|
386
386
|
background-color: ${h.color.background100};
|
|
@@ -389,7 +389,7 @@
|
|
|
389
389
|
background-color: ${h.color.background200};
|
|
390
390
|
}
|
|
391
391
|
`}
|
|
392
|
-
${
|
|
392
|
+
${Z.dark`
|
|
393
393
|
background-color: ${h.color.background400};
|
|
394
394
|
&:hover {
|
|
395
395
|
background-color: ${h.color.background500};
|
|
@@ -404,14 +404,14 @@
|
|
|
404
404
|
}
|
|
405
405
|
|
|
406
406
|
${Ae}
|
|
407
|
-
`,
|
|
407
|
+
`,fE=()=>null,Sn=Ge({template:fE,components:{DateSeparator:cE,ScrollToBottomButton:dE}}),gE=()=>{const{stringSet:e,format:t}=se(),{agentPreviewConfigs:n={},aiAgentId:r}=ae(),{aiAgentInfo:o}=ke(),{messageSource:s}=Se(),{Template:a}=rt.useContext(),{components:l}=Sn.useContext(),c=n.welcomeMessages??[],d=s.messages,m=Km(d,r),f=d[m.length+1],g=m[0]??f;return{filteredMessages:Si(d,{previewWelcomeMessages:c,aiAgentUserId:r}),shouldShowOriginalDate:E=>E>0||c.length===0?!0:f&&!Je.isSameDay(f.createdAt,(g==null?void 0:g.createdAt)??0),renderAgentPreviewWelcomeMessages:()=>c.length===0?null:i.createElement(i.Fragment,null,i.createElement(l.DateSeparator,{role:"listitem",style:{margin:"16px 0"},date:g==null?void 0:g.createdAt}),c.map((E,y)=>{const v=y===c.length-1,b=m.length!==d.length,_=c.length===1?"single":y===0?"top":v||b?"bottom":"middle",C=(g==null?void 0:g.createdAt)??Date.now();return i.createElement("div",{key:y,role:"listitem",tabIndex:-1,"aria-label":At({sender:(o==null?void 0:o.nickname)||"",message:E.message,messageFormat:"markdown",time:t(C,e.DATE_FORMAT__MESSAGE_TIMESTAMP),codeBlockPlaceholder:e.A11Y_CODE_BLOCK_PLACEHOLDER}),"data-message-listitem":""},i.createElement(a,{messageType:"user",message:E.message,sender:o,groupType:_,createdAt:C,extendedMessagePayload:{suggested_replies:E.suggestedReplies},suggestedRepliesDirection:n.suggestedRepliesDirection,suggestedRepliesVisible:v&&!b,isBotMessage:!0,onClickSuggestedReply:async({reply:x})=>{s.sendUserMessage({message:x})}}))}))}},hE=()=>{const{messageSource:e,scrollSource:t}=Se();u.useEffect(()=>{!t.state.isAwayFromBottom&&t.state.isScrollPositionReconciled&&e.resetNewMessages()},[t.state.isAwayFromBottom,t.state.isScrollPositionReconciled])},Jo="https://delight.ai?utm_medium=product&utm_source=aiagent&utm_campaign=fy26-glbl-ai-agent-poweredby",pE=({style:e})=>{const{stringSet:t}=se(),{handlers:n}=ae(),{conversation:r}=oe(),{isActionbookTester:o}=_t();return!gr("powered-by")||o?null:i.createElement(_E,{variant:"caption2",style:e},t.POWERED_BY+" ",i.createElement(EE,{variant:"caption2",forwardedAs:"a",href:Jo,...r.poweredByLink().props,rel:Er,target:"_blank",onClick:a=>{a.preventDefault(),n.onClickLink({url:Jo})}},"Sendbird"))},_E=p.default($)`color:${h.themedColor.textLowEmphasis};text-align:center;`,EE=p.default($)`color:${h.themedColor.textLowEmphasis};cursor:pointer;text-decoration:none;`,bE=()=>{var l;const{stringSet:e}=se(),{conversation:t}=oe(),{channelSource:n,goToActiveConversation:r,scrollSource:o}=Se(),s=Ne(n.channel),a=u.useRef(s);return u.useEffect(()=>{if(!a.current&&s){const m=setTimeout(()=>{o.actions.scrollToBottom()},100);return()=>clearTimeout(m)}a.current=s},[s,o.actions.scrollToBottom]),!((l=n.channel)!=null&&l.isAIAgent)||!s?null:i.createElement(CE,null,i.createElement(vE,{variant:"button",color:h.themedColor.textHighEmphasis,...t.startNewConversationButton({onActivate:r}).props},e.TALK_TO_AGENT))},CE=p.default.div`display:flex;justify-content:center;margin-bottom:16px;`,vE=p.default($)`border-radius:6px;box-sizing:border-box;padding:10px 20px;cursor:pointer;user-select:none;background-color:${h.color.background50};border:1px solid ${h.color.onlight.textDisabled};${Z.dark`
|
|
408
408
|
background-color: ${h.color.background700};
|
|
409
409
|
border-color: ${h.color.ondark.textLowEmphasis};
|
|
410
410
|
`}
|
|
411
|
-
`,pE=()=>{var _e;const{Template:e}=$t.useContext(),{Template:t}=tt.useContext(),{Template:n}=_n.useContext(),{components:r}=Cn.useContext(),{stringSet:o,format:s}=se(),{file:a}=oe().conversation,{config:l,cache:c,agentPreviewConfigs:d,chatSDK:m,handlers:f,state:g}=me(),{userSession:_,aiAgentInfo:v,connectionError:y}=Me(),{conversation:b,channelSource:E,messageSource:C,scrollSource:S,state:{input:x,streamAnimation:w}}=Se(),{isActionbookTester:k}=_t(),{filteredMessages:I,shouldShowOriginalDate:M,renderAgentPreviewWelcomeMessages:O}=lE(),F=Os(E.channel),[Y,z]=u.useState(null),[V,H]=u.useState(null);u.useEffect(()=>{S.actions.onTypingIndicatorUpdate(!!F)},[!!F,S.actions.onTypingIndicatorUpdate]),cE(),nE({enabled:C.initialized&&C.messages.length>0});const W=(L,X=!1)=>{var K;return X?v:((K=E.channel)==null?void 0:K.members.find(P=>P.userId===L.sender.userId))??L.sender},q=L=>{if(L.sendingStatus==="failed"&&!x.disabled)return()=>H(L)},ce=({message:L,index:X})=>{const K=Ca(L),P=I[X-1],te=I[X+1],de=I[I.length-1],fe=L===de,xe=gt(L,v.userId),Oe=!(v.isUserFeedbackEnabled&&xe&&!Ve.isWelcomeMessage(L)),Re=va(L,P,te,Oe),T=!ha.isSameDay((P==null?void 0:P.createdAt)??0,L.createdAt)&&M(X)&&!k,R=ne=>{z({files:ne.files.map(ie=>({...ie,timestamp:L.createdAt})),index:ne.index})},N=ne=>{R({files:[ne],index:0})},j=T?i.createElement(r.DateSeparator,{role:"listitem",style:{margin:"16px 0"},date:L.createdAt}):null,U={data:L.data,maxBodyWidth:g.expanded?ee.WIDE_BODY_MAX_WIDTH:void 0,extendedMessagePayload:L.extendedMessagePayload,createdAt:L.createdAt,groupType:Re,onClickMedia:N,onClickMediaFiles:R,onClickFile:f.onClickLink,onClickCTA:f.onClickLink,onClickCitation:ne=>f.onClickLink({url:ne.link}),onClickLink:f.onClickLink},G=()=>{if(Ie.isOutgoing(L,_.userId))return"outgoingmessage";if(Ie.isIncoming(L,_.userId))return"incomingmessage"},B=L.createdAt!=null&&L.createdAt!==0?s(L.createdAt,o.DATE_FORMAT__MESSAGE_TIMESTAMP):void 0,ue=(()=>{var ie,re,Z,le,pe,rt;const ne=(ie=L.message)==null?void 0:ie.trim();if(L.isFileMessage()){const ot=((re=L.name)==null?void 0:re.trim())||"";return wn({markdownText:ne,comparisonText:ot,plainText:a.label(ot,L.type)})}if(L.isMultipleFilesMessage()){const ot=((pe=(le=(Z=L.fileInfoList)==null?void 0:Z[0])==null?void 0:le.fileName)==null?void 0:pe.trim())||"",Fr=((rt=L.fileInfoList)==null?void 0:rt.length)??0;return wn({markdownText:ne,comparisonText:ot,plainText:Fr>0?o.CONVERSATION_LIST__MULTIPLE_FILES_COUNT(Fr):""})}return ne?wn({markdownText:ne}):Us("")})(),$e=(()=>{if(Ie.isAdmin(L))return St({message:ue.text,messageFormat:ue.format,codeBlockPlaceholder:o.A11Y_CODE_BLOCK_PLACEHOLDER});if(Ie.isOutgoing(L,_.userId))return St({sender:o.A11Y_MESSAGE_SENDER_YOU,message:ue.text,messageFormat:"plain",time:B,codeBlockPlaceholder:o.A11Y_CODE_BLOCK_PLACEHOLDER});if(Ie.isIncoming(L,_.userId))return St({sender:W(L,xe).nickname,message:ue.text,messageFormat:ue.format,time:B,codeBlockPlaceholder:o.A11Y_CODE_BLOCK_PLACEHOLDER})})(),ae=(()=>{var ne,ie;if(Ie.isAdmin(L))return Ie.isCSAT(L)?b?i.createElement(n,{...U,...b,isResolvedWhenDeterminedByUser:Ja(b),messageType:"admin.csat",onSubmitCSAT:async re=>{var Z;await((Z=E.channel)==null?void 0:Z.submitCSAT(re))},onScrollToBottom:()=>S.actions.scrollToBottom()}):null:i.createElement(n,{...U,messageType:"admin",message:L.message});if(Ie.isSteward(L))return i.createElement(D_,{steward:L.extendedMessagePayload.steward,onCancelSteward:async()=>{await m.aiAgent.cancelStewardTask({channelUrl:L.channelUrl,messageId:L.messageId})}});if(Ie.isOutgoing(L,_.userId)){const re={...U,message:L.message,sender:W(L),sendingStatus:L.sendingStatus,onClickFailedMessage:q(L)};if(L.isUserMessage())return i.createElement(e,{messageType:"user",...re});if(L.isFileMessage()){const[Z,le]=((ne=L.metaArrays.find(pe=>pe.key===cs))==null?void 0:ne.value)??[];return i.createElement(e,{messageType:"file",file:L,metadata:{aspectRatio:Z&&le?`${Z}/${le}`:"1/1",localFile:(ie=L.messageParams)==null?void 0:ie.file},...re})}if(L.isMultipleFilesMessage()){const{files:Z,metadata:le}=Oo(L);return i.createElement(e,{messageType:"multipleFiles",files:Z,metadata:le,...re})}}if(Ie.isIncoming(L,_.userId)){const re={...U,sender:W(L,xe),message:L.message,suggestedRepliesVisible:fe,suggestedRepliesDirection:d==null?void 0:d.suggestedRepliesDirection,isBotMessage:xe,isStreaming:Ve.isStreaming(L),isHandedOff:et(E.channel),isConversationClosed:Le(E.channel),isFeedbackEnabled:v.isUserFeedbackEnabled,isFeedbackCommentEnabled:v.isUserFeedbackCommentOptionEnabled,isSenderAvatarVisible:l.conversation.list.senderAvatarEnabled,markdownImageRenderMode:l.conversation.list.markdownImageRenderMode,markdownLinkRenderMode:l.conversation.list.markdownLinkRenderMode,onClickSuggestedReply:async({reply:Z})=>{C.sendUserMessage({message:Z})},onRequestMessageTemplate:async Z=>{const{template:le}=await m.aiAgent.getMessageTemplate(Z);return c.template.set(Z,le),le},onGetCachedMessageTemplate:Z=>c.template.get(Z),onHandleTemplateInternalAction:Z=>{if(Z.type==="internal"&&Z.internalData){const{method:le,payload:pe}=Z.internalData;le==="message.send"&&(pe!=null&&pe.message)&&C.sendUserMessage({message:pe.message})}},onFeedbackUpdate:Z=>{const le={messageId:L.messageId,channelUrl:L.channelUrl};if(!Z)return m.aiAgent.deleteMessageFeedback(le);const pe={...le,rating:pg(Z.rating),comment:Z.comment};return Ve.hasFeedback(L)?m.aiAgent.updateMessageFeedback(pe):m.aiAgent.createMessageFeedback(pe)},onSubmitForm:({key:Z,data:le})=>m.aiAgent.submitForm({messageId:L.messageId,channelUrl:L.channelUrl,formKey:Z,formData:le}),onCancelForm:({key:Z})=>m.aiAgent.cancelForm({messageId:L.messageId,channelUrl:L.channelUrl,formKey:Z}),onSendChallengeAction:({key:Z,requestId:le,action:pe,data:rt})=>m.aiAgent.sendChallengeAction({channelUrl:L.channelUrl,key:Z,requestId:le,action:pe,data:rt}),onStreamAnimationStart:()=>{w.start(L.messageId)},onStreamAnimationProgress:()=>{S.actions.onStreamingUpdate(!0)},onStreamAnimationComplete:()=>{w.stop(L.messageId),S.actions.onStreamingUpdate(!1)}};if(L.isUserMessage())return i.createElement(t,{messageType:"user",...re});if(L.isFileMessage())return i.createElement(t,{messageType:"file",file:L,...re});if(L.isMultipleFilesMessage()){const{files:Z}=Oo(L);return i.createElement(t,{messageType:"multipleFiles",files:Z,...re})}}})();return i.createElement(u.Fragment,{key:K},j,i.createElement("div",{id:`${Ne}-message-item`,role:"listitem",tabIndex:-1,"aria-label":$e,"data-message-listitem":"","data-layout-id":G()},ae))};return i.createElement(_E,{id:`${Ne}-message-list`},i.createElement(t_,{ref:S.ref,onScroll:S.props.onScroll,stackDirection:d==null?void 0:d.messageStackDirection,messages:I,renderMessage:ce,onLoadPrev:C.loadPrevious,onLoadNext:C.loadNext,depsForResetScrollPositionToBottom:[C.initialized,C.messages.length!==0],bottomSpacerHeight:S.state.bottomSpace,"aria-label":o.A11Y_MESSAGE_LIST,loading:!C.initialized||!E.channel,empty:I.length===0&&!F,error:!!(y||E.error),LoadingComponent:i.createElement(It,{type:"loading"}),EmptyComponent:(()=>{const L=O();return L?i.createElement("div",{style:{width:"100%"}},L):i.createElement(It,{type:"noMessages",label:o.PLACE_HOLDER__NO_MESSAGES})})(),ErrorComponent:i.createElement(It,{type:"error",label:(y==null?void 0:y.message)??((_e=E.error)==null?void 0:_e.message),action:E.error?{label:o.RETRY,onClick:()=>E.refetch()}:void 0}),messageTopArea:i.createElement(i.Fragment,null,i.createElement(uE,{style:{marginTop:16}}),O()),messageBottomArea:i.createElement(i.Fragment,null,F&&i.createElement("div",{id:`${Ne}-message-item`,role:"listitem",tabIndex:-1,"aria-label":St({sender:F.user.nickname,message:o.A11Y_TYPING_INDICATOR,codeBlockPlaceholder:o.A11Y_CODE_BLOCK_PLACEHOLDER}),"data-message-listitem":"",style:{marginTop:I.length===0?8:0}},i.createElement(t,{isTyping:!0,isBotMessage:F.isBot,sender:F.user,thinkingMessage:F.thinkingMessage,messageType:"user",groupType:"single",message:"",isSenderAvatarVisible:l.conversation.list.senderAvatarEnabled})),l.conversation.list.isTalkToAgentViewEnabled&&i.createElement(fE,null)),overlayArea:i.createElement(i.Fragment,null,l.conversation.list.newMessageIndicatorEnabled&&S.state.isAwayFromBottom&&C.newMessages.length>0&&i.createElement(EE,{label:o.SCROLL_TO_NEW_MESSAGES_LABEL(C.newMessages),onClick:()=>S.actions.scrollToBottom()}),S.state.isAwayFromBottom&&C.newMessages.length===0&&!F&&i.createElement(r.ScrollToBottomButton,{onClick:()=>S.actions.scrollToBottom(),style:{position:"absolute",bottom:12,insetInlineEnd:16}}))}),Y&&i.createElement(a_,{files:Y.files,initialIndex:Y.index,onClose:()=>z(null),visible:!0}),V&&i.createElement(Je,{visible:!0,onClose:()=>H(null),"aria-label":o.A11Y_FAILED_MESSAGE_OPTIONS},i.createElement(Je.ActionItem,{onClick:()=>{C.resendMessage(V),H(null)}},o.FAILED_MESSAGE_RESEND),i.createElement(Je.ActionItem,{destructive:!0,onClick:()=>{C.deleteMessage(V),H(null)}},o.FAILED_MESSAGE_REMOVE)))},_E=p.default.div`overflow-y:hidden;display:flex;flex:1;position:relative;`,EE=p.default(V_)`position:absolute;bottom:12px;left:50%;transform:translateX(-50%);`,bE=()=>i.createElement(pE,null),CE=()=>{var o;const{origin:e}=_t(),{appId:t,aiAgentId:n}=ke(),{channelSource:r}=Se();return(o=r.channel)!=null&&o.conversation?i.createElement(vE,null,i.createElement(Jn,{style:{gap:4}},i.createElement(Q,{color:h.themedColor.textLowEmphasis,size:12,type:"show"}),i.createElement($,{as:"i",color:h.themedColor.textLowEmphasis,variant:"caption2"},"Only visible in the tester")),i.createElement(Jn,{role:"button",style:{gap:4},onClick:()=>{var c,d;const s=e??window.location.origin,a=(d=(c=r.channel)==null?void 0:c.conversation)==null?void 0:d.id,l=`${s}/ai-agent/${t}/${n}/evaluate/conversations/${a}`;navigator.clipboard.writeText(l)}},i.createElement($,{variant:"body3",color:h.themedColor.textHighEmphasis},"Copy ",i.createElement("span",{style:{color:h.themedColor.primary}},"conversation link")),i.createElement(Q,{color:h.themedColor.primary,size:14,type:"copy"}))):null},Jn=p.default.div`display:flex;justify-content:center;align-items:center;`,vE=p.default(Jn)`flex-direction:column;padding-block:16px;background-color:${h.themedColor.bg_100_500};gap:8px;`,yE=(e,t)=>{const n=[],r=[],o=[];for(const s of e){const a=t.isSupportedMimeType(s.type),l=s.size<=t.getUploadSizeLimit(s.type);a&&l?n.push(s):a?r.push(s):o.push(s)}return{passed:n,failedBySize:r,failedByType:o}},Vi=u.createContext(void 0),SE=({children:e})=>{var z,V;const{chatSDK:t}=me(),{createAttachmentRules:n}=Me(),{stringSet:r}=se(),{channelSource:o,state:s}=Se(),[a,l]=u.useState([]),{announceError:c}=Er(),[d,m]=u.useState(null),f=n({channel:o.channel,uploadSizeLimit:(z=t.appInfo)==null?void 0:z.uploadSizeLimit}),g=((V=s==null?void 0:s.input)==null?void 0:V.disabled)??!1,_=f.isEnabled(),v=f.maxAttachmentCount,y=()=>m(null),b=H=>m(H),E=()=>{b({title:r.FILE_UPLOAD_NOTIFICATION__COUNT_LIMIT.replace("%d",v.toString())})},C=H=>{b({title:r.FILE_UPLOAD_NOTIFICATION__SIZE_LIMIT.replace("%d",H.toString())}),c({type:"fileSizeExceeded",maxSizeMB:H})},S=H=>{b({title:r.FILE_UPLOAD_NOTIFICATION__FILES_EXCLUDED_BY_VALIDATION.replace("%d",H.toString())})},x=H=>H.map(W=>({file:W,preview:{url:URL.createObjectURL(W),type:W.type,name:W.name}})),w=H=>{l(W=>[...W,...x(H)])},k=H=>{l(W=>(W.forEach(q=>URL.revokeObjectURL(q.preview.url)),x(H)))},I=H=>{const{passed:W,failedBySize:q,failedByType:ce}=yE(H,f),_e=q.length+ce.length,L=H.length===1?q[0]:void 0;return L?C(f.getUploadSizeLimitInMB(L.type)):_e>0&&S(_e),W},M=H=>{const W=I(H.files);W.length!==0&&(H.type==="append"?w(W):k(W))},O=H=>{if(!_||g||!Tl(H))return;const W=wl({currentFiles:a.map(({file:q})=>q),incomingFiles:H,maxAttachmentCount:v});switch(W.type){case"reject":E();return;case"confirm_replace":b({title:r.FILE_UPLOAD_REPLACE_ALERT__TITLE,description:r.FILE_UPLOAD_REPLACE_ALERT__DESCRIPTION,confirmText:r.BUTTON__OK,cancelText:r.BUTTON__CANCEL,onConfirm:()=>M(W.action)});return;case"apply":M(W.action);return}},F=H=>{l(W=>{var ce;const q=(ce=W[H])==null?void 0:ce.preview;return q&&URL.revokeObjectURL(q.url),W.filter((_e,L)=>L!==H)})},Y=()=>{l(H=>(H.forEach(W=>URL.revokeObjectURL(W.preview.url)),[]))};return i.createElement(Vi.Provider,{value:{files:a,addFiles:O,removeFile:F,clearFiles:Y,isFileUploadEnabled:_,acceptableMimeTypes:f.supportedMimeTypes,maxAttachmentCount:f.maxAttachmentCount,showFileUploadAlert:b}},e,i.createElement(hn,{visible:!!d,...d??{},onClose:y}))},Mr=()=>{const e=u.useContext(Vi);if(!e)throw new Error("useFileUpload must be used within FileUploadProvider");return e};function AE({elementRef:e,ready:t,onRestore:n}){const r=u.useRef(!1);u.useEffect(()=>{var a;!t||!r.current||(n==null||n(),(a=e.current)==null||a.focus(),r.current=!1)},[t,n]);const o=u.useCallback(()=>{r.current=!0},[]),s=u.useCallback(()=>{r.current=!1},[]);return{requestRestore:o,cancelRestore:s}}function xE({blurred:e,elementRef:t,document:n=window.document,onRecoverFocus:r}){const o=u.useRef(!1);e&&t.current&&n.activeElement===t.current&&(o.current=!0),u.useLayoutEffect(()=>{var s;!e&&o.current&&(r==null||r(),(s=t.current)==null||s.focus(),o.current=!1)},[e,r])}const TE=()=>{const{announceError:e}=Ke();return u.useCallback(t=>{e({type:"sendFailed"},t)},[e])},IE=1e3,wE=(e,t,n)=>{const{announcementsEnabled:r,setIsSuppressed:o}=Ke(),s=n??!0,a=u.useRef(!1),l=u.useRef(void 0),c=u.useCallback(d=>{var m;d&&s&&(a.current=!0,l.current=e,e==null||e.startTyping()),d||(a.current&&s&&((m=l.current)==null||m.endTyping()),a.current=!1,l.current=void 0),o(d)},[e,o,s]);u.useLayoutEffect(()=>{o(a.current)},[r,o]),Yc(t,c,{enabled:s,idleMs:IE})},ME=({enabled:e=!0,focusRoot:t})=>{const[n,r]=u.useState(!1),o=u.useRef(!1),s=u.useRef(!1);u.useEffect(()=>{if(!e){r(!1);return}const d=f=>{const g=f;g.metaKey||g.altKey||g.ctrlKey||(o.current=!0)},m=()=>{o.current=!1,r(!1)};return t.addEventListener("keydown",d),t.addEventListener("pointerdown",m),()=>{t.removeEventListener("keydown",d),t.removeEventListener("pointerdown",m)}},[e,t]);const a=u.useCallback(()=>{if(s.current){s.current=!1,r(!1);return}r(o.current)},[]),l=u.useCallback(()=>{r(!1)},[]),c=u.useCallback(()=>{s.current=!0,r(!1)},[]);return{isFocusVisible:n,suppressNextFocusVisible:c,focusHandlers:{onFocus:a,onBlur:l}}},kE=p.default.div`&::-webkit-scrollbar{display:none;}overflow-x:auto;display:flex;flex-direction:row;gap:10px;padding:8px 16px;background-color:transparent;`,RE=p.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;}`,LE=p.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;${J.light`
|
|
411
|
+
`,yE=()=>{var J;const{Template:e}=Pt.useContext(),{Template:t}=rt.useContext(),{Template:n}=Cn.useContext(),{components:r}=Sn.useContext(),{stringSet:o,format:s}=se(),{announceError:a,announceStatus:l}=Xe(),{file:c}=oe().conversation,{config:d,cache:m,agentPreviewConfigs:f,chatSDK:g,handlers:E,state:y}=ae(),{userSession:v,aiAgentInfo:b,connectionError:_}=ke(),{conversation:C,channelSource:x,messageSource:A,scrollSource:w,state:{input:M,streamAnimation:k}}=Se(),{isActionbookTester:R}=_t(),{filteredMessages:O,shouldShowOriginalDate:z,renderAgentPreviewWelcomeMessages:Y}=gE(),P=$s(x.channel),[V,B]=u.useState(null),[W,q]=u.useState(null);u.useEffect(()=>{w.actions.onTypingIndicatorUpdate(!!P)},[!!P,w.actions.onTypingIndicatorUpdate]),hE(),lE({enabled:A.initialized&&A.messages.length>0});const ie=(T,F=!1)=>{var Q;return F?b:((Q=x.channel)==null?void 0:Q.members.find(re=>re.userId===T.sender.userId))??T.sender},_e=T=>{if(T.sendingStatus==="failed"&&!M.disabled)return()=>q(T)},Le=({message:T,index:F})=>{const Q=Aa(T),re=O[F-1],le=O[F+1],Oe=O[O.length-1],De=T===Oe,xe=gt(T,b.userId),I=!(b.isUserFeedbackEnabled&&xe&&!We.isWelcomeMessage(T)),L=xa(T,re,le,I),N=!ba.isSameDay((re==null?void 0:re.createdAt)??0,T.createdAt)&&z(F)&&!R,K=te=>{B({files:te.files.map(ve=>({...ve,timestamp:T.createdAt})),index:te.index})},G=te=>{K({files:[te],index:0})},H=N?i.createElement(r.DateSeparator,{role:"listitem",style:{margin:"16px 0"},date:T.createdAt}):null,U={data:T.data,maxBodyWidth:y.expanded?ee.WIDE_BODY_MAX_WIDTH:void 0,extendedMessagePayload:T.extendedMessagePayload,createdAt:T.createdAt,groupType:L,onClickMedia:G,onClickMediaFiles:K,onClickFile:E.onClickLink,onClickCTA:E.onClickLink,onClickCitation:te=>E.onClickLink({url:te.link}),onClickLink:E.onClickLink},de=()=>{if(we.isOutgoing(T,v.userId))return"outgoingmessage";if(we.isIncoming(T,v.userId))return"incomingmessage"},Pe=T.createdAt!=null&&T.createdAt!==0?s(T.createdAt,o.DATE_FORMAT__MESSAGE_TIMESTAMP):void 0,ne=(()=>{var ve,ge,j,he,Te,Ut;const te=(ve=T.message)==null?void 0:ve.trim();if(T.isFileMessage()){const Bt=((ge=T.name)==null?void 0:ge.trim())||"";return Rn({markdownText:te,comparisonText:Bt,plainText:c.label(Bt,T.type)})}if(T.isMultipleFilesMessage()){const Bt=((Te=(he=(j=T.fileInfoList)==null?void 0:j[0])==null?void 0:he.fileName)==null?void 0:Te.trim())||"",Hr=((Ut=T.fileInfoList)==null?void 0:Ut.length)??0;return Rn({markdownText:te,comparisonText:Bt,plainText:Hr>0?o.CONVERSATION_LIST__MULTIPLE_FILES_COUNT(Hr):""})}return te?Rn({markdownText:te}):Gs("")})(),fe=(()=>{if(we.isAdmin(T))return At({message:ne.text,messageFormat:ne.format,codeBlockPlaceholder:o.A11Y_CODE_BLOCK_PLACEHOLDER});if(we.isOutgoing(T,v.userId))return At({sender:o.A11Y_MESSAGE_SENDER_YOU,message:ne.text,messageFormat:"plain",time:Pe,codeBlockPlaceholder:o.A11Y_CODE_BLOCK_PLACEHOLDER});if(we.isIncoming(T,v.userId))return At({sender:ie(T,xe).nickname,message:ne.text,messageFormat:ne.format,time:Pe,codeBlockPlaceholder:o.A11Y_CODE_BLOCK_PLACEHOLDER})})(),me=(()=>{var te,ve;if(we.isAdmin(T))return we.isCSAT(T)?C?i.createElement(n,{...U,...C,isResolvedWhenDeterminedByUser:rl(C),messageType:"admin.csat",announceError:a,announceStatus:l,onSubmitCSAT:async ge=>{var j;await((j=x.channel)==null?void 0:j.submitCSAT(ge))},onScrollToBottom:()=>w.actions.scrollToBottom()}):null:i.createElement(n,{...U,messageType:"admin",message:T.message});if(we.isSteward(T))return i.createElement(H_,{steward:T.extendedMessagePayload.steward,onCancelSteward:async()=>{await g.aiAgent.cancelStewardTask({channelUrl:T.channelUrl,messageId:T.messageId})}});if(we.isOutgoing(T,v.userId)){const ge={...U,message:T.message,sender:ie(T),sendingStatus:T.sendingStatus,onClickFailedMessage:_e(T)};if(T.isUserMessage())return i.createElement(e,{messageType:"user",...ge});if(T.isFileMessage()){const[j,he]=((te=T.metaArrays.find(Te=>Te.key===ms))==null?void 0:te.value)??[];return i.createElement(e,{messageType:"file",file:T,metadata:{aspectRatio:j&&he?`${j}/${he}`:"1/1",localFile:(ve=T.messageParams)==null?void 0:ve.file},...ge})}if(T.isMultipleFilesMessage()){const{files:j,metadata:he}=$o(T);return i.createElement(e,{messageType:"multipleFiles",files:j,metadata:he,...ge})}}if(we.isIncoming(T,v.userId)){const ge={...U,sender:ie(T,xe),message:T.message,suggestedRepliesVisible:De,suggestedRepliesDirection:f==null?void 0:f.suggestedRepliesDirection,isBotMessage:xe,isStreaming:We.isStreaming(T),isHandedOff:nt(x.channel),isConversationClosed:Ne(x.channel),isFeedbackEnabled:b.isUserFeedbackEnabled,isFeedbackCommentEnabled:b.isUserFeedbackCommentOptionEnabled,isSenderAvatarVisible:d.conversation.list.senderAvatarEnabled,deferredMarkdownElements:d.conversation.list.deferredMarkdownElements,onClickSuggestedReply:async({reply:j})=>{A.sendUserMessage({message:j})},onRequestMessageTemplate:async j=>{const{template:he}=await g.aiAgent.getMessageTemplate(j);return m.template.set(j,he),he},onGetCachedMessageTemplate:j=>m.template.get(j),onHandleTemplateInternalAction:j=>{if(j.type==="internal"&&j.internalData){const{method:he,payload:Te}=j.internalData;he==="message.send"&&(Te!=null&&Te.message)&&A.sendUserMessage({message:Te.message})}},onFeedbackUpdate:j=>{const he={messageId:T.messageId,channelUrl:T.channelUrl};if(!j)return g.aiAgent.deleteMessageFeedback(he);const Te={...he,rating:vg(j.rating),comment:j.comment};return We.hasFeedback(T)?g.aiAgent.updateMessageFeedback(Te):g.aiAgent.createMessageFeedback(Te)},onSubmitForm:({key:j,data:he})=>g.aiAgent.submitForm({messageId:T.messageId,channelUrl:T.channelUrl,formKey:j,formData:he}),onCancelForm:({key:j})=>g.aiAgent.cancelForm({messageId:T.messageId,channelUrl:T.channelUrl,formKey:j}),onSendChallengeAction:({key:j,requestId:he,action:Te,data:Ut})=>g.aiAgent.sendChallengeAction({channelUrl:T.channelUrl,key:j,requestId:he,action:Te,data:Ut}),onStreamAnimationStart:()=>{k.start(T.messageId)},onStreamAnimationProgress:()=>{w.actions.onStreamingUpdate(!0)},onStreamAnimationComplete:()=>{k.stop(T.messageId),w.actions.onStreamingUpdate(!1)}};if(T.isUserMessage())return i.createElement(t,{messageType:"user",...ge});if(T.isFileMessage())return i.createElement(t,{messageType:"file",file:T,...ge});if(T.isMultipleFilesMessage()){const{files:j}=$o(T);return i.createElement(t,{messageType:"multipleFiles",files:j,...ge})}}})();return i.createElement(u.Fragment,{key:Q},H,i.createElement("div",{id:`${$e}-message-item`,role:"listitem",tabIndex:-1,"aria-label":fe,"data-message-listitem":"","data-layout-id":de()},me))};return i.createElement(SE,{id:`${$e}-message-list`},i.createElement(a_,{ref:w.ref,onScroll:w.props.onScroll,stackDirection:f==null?void 0:f.messageStackDirection,messages:O,renderMessage:Le,onLoadPrev:A.loadPrevious,onLoadNext:A.loadNext,depsForResetScrollPositionToBottom:[A.initialized,A.messages.length!==0],bottomSpacerHeight:w.state.bottomSpace,"aria-label":o.A11Y_MESSAGE_LIST,loading:!A.initialized||!x.channel,empty:O.length===0&&!P,error:!!(_||x.error),LoadingComponent:i.createElement(wt,{type:"loading"}),EmptyComponent:(()=>{const T=Y();return T?i.createElement("div",{style:{width:"100%"}},T):i.createElement(wt,{type:"noMessages",label:o.PLACE_HOLDER__NO_MESSAGES})})(),ErrorComponent:i.createElement(wt,{type:"error",label:(_==null?void 0:_.message)??((J=x.error)==null?void 0:J.message),action:x.error?{label:o.RETRY,onClick:()=>x.refetch()}:void 0}),messageTopArea:i.createElement(i.Fragment,null,i.createElement(pE,{style:{marginTop:16}}),Y()),messageBottomArea:i.createElement(i.Fragment,null,P&&i.createElement("div",{id:`${$e}-message-item`,role:"listitem",tabIndex:-1,"aria-label":At({sender:P.user.nickname,message:o.A11Y_TYPING_INDICATOR,codeBlockPlaceholder:o.A11Y_CODE_BLOCK_PLACEHOLDER}),"data-message-listitem":"",style:{marginTop:O.length===0?8:0}},i.createElement(t,{isTyping:!0,isBotMessage:P.isBot,sender:P.user,thinkingMessage:P.thinkingMessage,messageType:"user",groupType:"single",message:"",isSenderAvatarVisible:d.conversation.list.senderAvatarEnabled})),d.conversation.list.isTalkToAgentViewEnabled&&i.createElement(bE,null)),overlayArea:i.createElement(i.Fragment,null,d.conversation.list.newMessageIndicatorEnabled&&w.state.isAwayFromBottom&&A.newMessages.length>0&&i.createElement(AE,{label:o.SCROLL_TO_NEW_MESSAGES_LABEL(A.newMessages),onClick:()=>w.actions.scrollToBottom()}),w.state.isAwayFromBottom&&A.newMessages.length===0&&!P&&i.createElement(r.ScrollToBottomButton,{onClick:()=>w.actions.scrollToBottom(),style:{position:"absolute",bottom:12,insetInlineEnd:16}}))}),V&&i.createElement(f_,{files:V.files,initialIndex:V.index,onClose:()=>B(null),visible:!0}),W&&i.createElement(et,{visible:!0,onClose:()=>q(null),"aria-label":o.A11Y_FAILED_MESSAGE_OPTIONS},i.createElement(et.ActionItem,{onClick:()=>{A.resendMessage(W),q(null)}},o.FAILED_MESSAGE_RESEND),i.createElement(et.ActionItem,{destructive:!0,onClick:()=>{A.deleteMessage(W),q(null)}},o.FAILED_MESSAGE_REMOVE)))},SE=p.default.div`overflow-y:hidden;display:flex;flex:1;position:relative;`,AE=p.default(X_)`position:absolute;bottom:12px;left:50%;transform:translateX(-50%);`,xE=()=>i.createElement(yE,null),TE=()=>{var o;const{origin:e}=_t(),{appId:t,aiAgentId:n}=Re(),{channelSource:r}=Se();return(o=r.channel)!=null&&o.conversation?i.createElement(IE,null,i.createElement(er,{style:{gap:4}},i.createElement(X,{color:h.themedColor.textLowEmphasis,size:12,type:"show"}),i.createElement($,{as:"i",color:h.themedColor.textLowEmphasis,variant:"caption2"},"Only visible in the tester")),i.createElement(er,{role:"button",style:{gap:4},onClick:()=>{var c,d;const s=e??window.location.origin,a=(d=(c=r.channel)==null?void 0:c.conversation)==null?void 0:d.id,l=`${s}/ai-agent/${t}/${n}/evaluate/conversations/${a}`;navigator.clipboard.writeText(l)}},i.createElement($,{variant:"body3",color:h.themedColor.textHighEmphasis},"Copy ",i.createElement("span",{style:{color:h.themedColor.primary}},"conversation link")),i.createElement(X,{color:h.themedColor.primary,size:14,type:"copy"}))):null},er=p.default.div`display:flex;justify-content:center;align-items:center;`,IE=p.default(er)`flex-direction:column;padding-block:16px;background-color:${h.themedColor.bg_100_500};gap:8px;`,wE=(e,t)=>{const n=[],r=[],o=[];for(const s of e){const a=t.isSupportedMimeType(s.type),l=s.size<=t.getUploadSizeLimit(s.type);a&&l?n.push(s):a?r.push(s):o.push(s)}return{passed:n,failedBySize:r,failedByType:o}},Ki=u.createContext(void 0),ME=({children:e})=>{var P,V;const{chatSDK:t}=ae(),{createAttachmentRules:n}=ke(),{stringSet:r}=se(),{channelSource:o,state:s}=Se(),[a,l]=u.useState([]),{announceError:c}=vr(),[d,m]=u.useState(null),f=n({channel:o.channel,uploadSizeLimit:(P=t.appInfo)==null?void 0:P.uploadSizeLimit}),g=((V=s==null?void 0:s.input)==null?void 0:V.disabled)??!1,E=f.isEnabled(),y=f.maxAttachmentCount,v=()=>m(null),b=B=>m(B),_=()=>{b({title:r.FILE_UPLOAD_NOTIFICATION__COUNT_LIMIT.replace("%d",y.toString())})},C=B=>{b({title:r.FILE_UPLOAD_NOTIFICATION__SIZE_LIMIT.replace("%d",B.toString())}),c({type:"fileSizeExceeded",maxSizeMB:B})},x=B=>{b({title:r.FILE_UPLOAD_NOTIFICATION__FILES_EXCLUDED_BY_VALIDATION.replace("%d",B.toString())})},A=B=>B.map(W=>({file:W,preview:{url:URL.createObjectURL(W),type:W.type,name:W.name}})),w=B=>{l(W=>[...W,...A(B)])},M=B=>{l(W=>(W.forEach(q=>URL.revokeObjectURL(q.preview.url)),A(B)))},k=B=>{const{passed:W,failedBySize:q,failedByType:ie}=wE(B,f),_e=q.length+ie.length,Le=B.length===1?q[0]:void 0;return Le?C(f.getUploadSizeLimitInMB(Le.type)):_e>0&&x(_e),W},R=B=>{const W=k(B.files);W.length!==0&&(B.type==="append"?w(W):M(W))},O=B=>{if(!E||g||!Rl(B))return;const W=Ol({currentFiles:a.map(({file:q})=>q),incomingFiles:B,maxAttachmentCount:y});switch(W.type){case"reject":_();return;case"confirm_replace":b({title:r.FILE_UPLOAD_REPLACE_ALERT__TITLE,description:r.FILE_UPLOAD_REPLACE_ALERT__DESCRIPTION,confirmText:r.BUTTON__OK,cancelText:r.BUTTON__CANCEL,onConfirm:()=>R(W.action)});return;case"apply":R(W.action);return}},z=B=>{l(W=>{var ie;const q=(ie=W[B])==null?void 0:ie.preview;return q&&URL.revokeObjectURL(q.url),W.filter((_e,Le)=>Le!==B)})},Y=()=>{l(B=>(B.forEach(W=>URL.revokeObjectURL(W.preview.url)),[]))};return i.createElement(Ki.Provider,{value:{files:a,addFiles:O,removeFile:z,clearFiles:Y,isFileUploadEnabled:E,acceptableMimeTypes:f.supportedMimeTypes,maxAttachmentCount:f.maxAttachmentCount,showFileUploadAlert:b}},e,i.createElement(En,{visible:!!d,...d??{},onClose:v}))},Lr=()=>{const e=u.useContext(Ki);if(!e)throw new Error("useFileUpload must be used within FileUploadProvider");return e};function kE({elementRef:e,ready:t,onRestore:n}){const r=u.useRef(!1);u.useEffect(()=>{var a;!t||!r.current||(n==null||n(),(a=e.current)==null||a.focus(),r.current=!1)},[t,n]);const o=u.useCallback(()=>{r.current=!0},[]),s=u.useCallback(()=>{r.current=!1},[]);return{requestRestore:o,cancelRestore:s}}function RE({blurred:e,elementRef:t,document:n=window.document,onRecoverFocus:r}){const o=u.useRef(!1);e&&t.current&&n.activeElement===t.current&&(o.current=!0),u.useLayoutEffect(()=>{var s;!e&&o.current&&(r==null||r(),(s=t.current)==null||s.focus(),o.current=!1)},[e,r])}const LE=()=>{const{announceError:e}=Xe();return u.useCallback(t=>{e({type:"sendFailed"},t)},[e])},OE=1e3,NE=(e,t,n)=>{const{announcementsEnabled:r,setIsSuppressed:o}=Xe(),s=n??!0,a=u.useRef(!1),l=u.useRef(void 0),c=u.useCallback(d=>{var m;d&&s&&(a.current=!0,l.current=e,e==null||e.startTyping()),d||(a.current&&s&&((m=l.current)==null||m.endTyping()),a.current=!1,l.current=void 0),o(d)},[e,o,s]);u.useLayoutEffect(()=>{o(a.current)},[r,o]),Xc(t,c,{enabled:s,idleMs:OE})},DE=({enabled:e=!0,focusRoot:t})=>{const[n,r]=u.useState(!1),o=u.useRef(!1),s=u.useRef(!1);u.useEffect(()=>{if(!e){r(!1);return}const d=f=>{const g=f;g.metaKey||g.altKey||g.ctrlKey||(o.current=!0)},m=()=>{o.current=!1,r(!1)};return t.addEventListener("keydown",d),t.addEventListener("pointerdown",m),()=>{t.removeEventListener("keydown",d),t.removeEventListener("pointerdown",m)}},[e,t]);const a=u.useCallback(()=>{if(s.current){s.current=!1,r(!1);return}r(o.current)},[]),l=u.useCallback(()=>{r(!1)},[]),c=u.useCallback(()=>{s.current=!0,r(!1)},[]);return{isFocusVisible:n,suppressNextFocusVisible:c,focusHandlers:{onFocus:a,onBlur:l}}},$E=p.default.div`&::-webkit-scrollbar{display:none;}overflow-x:auto;display:flex;flex-direction:row;gap:10px;padding:8px 16px;background-color:transparent;`,PE=p.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;}`,FE=p.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;${Z.light`
|
|
412
412
|
background-color: ${h.color.background50};
|
|
413
413
|
`}
|
|
414
|
-
${
|
|
414
|
+
${Z.dark`
|
|
415
415
|
background-color: ${h.color.background500};
|
|
416
416
|
`}
|
|
417
417
|
path {
|
|
@@ -433,7 +433,7 @@
|
|
|
433
433
|
circle {
|
|
434
434
|
stroke: ${h.themedColor.bg_50_600};
|
|
435
435
|
}
|
|
436
|
-
`,
|
|
436
|
+
`,UE=()=>{const e=Dt(),{conversation:t}=oe(),{files:n,removeFile:r,isFileUploadEnabled:o}=Lr();return o&&n.length>0?i.createElement($E,null,n.map(({preview:{type:a,name:l,url:c}},d)=>{let m=i.createElement(Tr,{name:l,mimeType:a,type:or(l,a),selected:!0});return a.startsWith("image/")&&(m=i.createElement("img",{alt:t.file.label(l,a,!0),src:c})),i.createElement(PE,{key:c},i.createElement(FE,{type:"button",...t.file.removeButton(l).props,$mobile:e,onClick:()=>r(d)},i.createElement(X,{type:"close-filled",color:h.themedColor.textMidEmphasis})),m)})):null},BE={textArea:D.css`min-height:40px;height:40px;font-size:16px;line-height:24px;`},ji=p.default.button`all:unset;cursor:pointer;display:flex;align-items:center;justify-content:center;width:32px;height:32px;${Ae}`,Qo=p.default.div`width:100%;position:relative;background-color:${({theme:e})=>e.colors.messageInput.background};border-radius:20px;`,es=p.default.div`display:flex;flex-direction:row;align-items:flex-end;position:relative;`,ts=p.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:${Qs}px;overflow-wrap:break-word;white-space:pre-wrap;overflow-x:hidden;${gi&&BE.textArea};${({$focusVisible:e})=>e&&D.css`
|
|
437
437
|
outline: 2px solid ${h.themedColor.primary};
|
|
438
438
|
outline-offset: 2px;
|
|
439
439
|
`}
|
|
@@ -445,22 +445,22 @@
|
|
|
445
445
|
&:disabled {
|
|
446
446
|
cursor: not-allowed;
|
|
447
447
|
&::placeholder {
|
|
448
|
-
color: ${
|
|
448
|
+
color: ${h.themedColor.textDisabled};
|
|
449
449
|
}
|
|
450
450
|
}
|
|
451
451
|
|
|
452
|
-
${({$blocked:e})=>e&&D.css`cursor:not-allowed;&::placeholder{color:${
|
|
453
|
-
`,
|
|
452
|
+
${({$blocked:e})=>e&&D.css`cursor:not-allowed;&::placeholder{color:${h.themedColor.textDisabled};}`}
|
|
453
|
+
`,HE=p.default.input`display:none;`;p.default.div`display:flex;align-items:center;gap:24px;`;const GE=p.default(ji)`flex-shrink:0;border-radius:8px;&:disabled{cursor:not-allowed;}&:not(:disabled){&:hover{background-color:${h.themedColor.bg_100_500};path{fill:${h.themedColor.textHighEmphasis};}}&:active{background-color:${h.themedColor.bg_200_400};}}`,ns=p.default.div`padding:10px 16px 10px 12px;position:relative;display:flex;align-items:center;gap:8px;`,rs=e=>e.startsWith("image/"),os=({disabled:e})=>{const{stringSet:t}=se(),{conversation:n}=oe(),{config:r}=ae(),o=u.useRef(null),s=u.useRef(null),[a,l]=u.useState(!1),{addFiles:c,isFileUploadEnabled:d,acceptableMimeTypes:m,showFileUploadAlert:f}=Lr(),g=m.includes(Hn),E=g?["image/*"]:m.filter(rs),y=g?[Hn]:m.filter(k=>!rs(k)),v=r.conversation.input.gallery.photoEnabled,b=r.conversation.input.fileEnabled,_=()=>g||E.length>0,C=()=>g||y.length>0,x=k=>{const R=k.currentTarget.files;R&&c(Array.from(R)),k.target.value=""},A=()=>{l(!0)},w=u.useMemo(()=>{const k=[];return v&&k.push({type:"image",icon:"photo",label:t.FILE_UPLOAD_PHOTOS,accept:E.join(","),inputRef:o,onSelect:()=>{if(!_()){f({title:t.FILE_UPLOAD_NO_SUPPORTED_FILES});return}l(!1),setTimeout(()=>{var R;return(R=o.current)==null?void 0:R.click()},100)}}),b&&k.push({type:"file",icon:"document",label:t.FILE_UPLOAD_FILES,accept:m.join(","),inputRef:s,onSelect:()=>{if(!C()){f({title:t.FILE_UPLOAD_NO_SUPPORTED_FILES});return}l(!1),setTimeout(()=>{var R;return(R=s.current)==null?void 0:R.click()},100)}}),k},[E,m,t,v,b]);if(!d)return null;const M={attach:n.messageInput.attachFileButton()};return i.createElement(i.Fragment,null,i.createElement(GE,{...M.attach.props,disabled:e,onClick:A},i.createElement(X,{type:"add",color:e?h.themedColor.textDisabled:h.color.primary.main,size:20}),M.attach.descriptionNode),w.map(k=>i.createElement(HE,{key:k.type,type:"file",ref:k.inputRef,multiple:k.type==="image",onChange:x,accept:k.accept})),i.createElement(et,{visible:a,onClose:()=>l(!1),"aria-label":t.A11Y_FILE_UPLOAD_OPTIONS},w.map(k=>i.createElement(et.ActionItem,{key:k.type,onClick:k.onSelect,icon:k.icon},k.label))))},zE=()=>{const e=u.useRef(null),[t,n]=u.useState(""),{stringSet:r}=se(),{conversation:o}=oe(),{rootElement:s}=ae(),a=st(s),{focusHandlers:l,isFocusVisible:c,suppressNextFocusVisible:d}=DE({focusRoot:a}),{channelSource:m,messageSource:f,state:g}=Se(),{files:E,addFiles:y,clearFiles:v}=Lr(),b=LE(),{focusPolicy:_,disabled:C,disabledBy:x}=g.input,A=_==="preserve",w=_==="release",M=(()=>{if(!C)return r.MESSAGE_INPUT__PLACE_HOLDER;switch(x){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}})();Gm({onDropFiles:F=>{y(F)}}),RE({blurred:w,elementRef:e,document:a,onRecoverFocus:()=>{d()}}),NE(m.channel,t,!C);const k=t.trim().length>0,R=E.length>0,O=!C&&(k||R),z={input:o.messageInput.textInput(r.A11Y_MESSAGE_INPUT),send:o.messageInput.sendButton()},Y=()=>{e.current&&(e.current.value="",e.current.style.height=""),v(),n("")},P=()=>{var F;d(),(F=e.current)==null||F.focus()},{requestRestore:V,cancelRestore:B}=kE({elementRef:e,ready:A,onRestore:d}),W=F=>{B(),b(F)},q=()=>{B()},ie=async F=>{try{await F(),q()}catch{W(e.current)}},_e=async()=>{if(C)return;const F=t.trim();if(!F&&!E.length)return;const Q=[...E];if(V(),Y(),P(),Q.length===0){await ie(()=>f.sendUserMessage({message:F}));return}if(Q.length===1)await ie(()=>f.sendFileMessage({message:F,file:Q[0].file}));else{const re=Q.map(({file:le})=>({file:le}));await ie(()=>f.sendMultipleFilesMessage({message:F,fileInfoList:re}))}},Le=F=>{const Q=Array.from(F.clipboardData.files);Q.length>0&&(F.preventDefault(),y(Q))},J=F=>{F.key!=="Enter"||F.nativeEvent.isComposing||F.shiftKey||(F.preventDefault(),_e())},T=F=>{if(C){e.current&&(e.current.value=t);return}if(e.current){e.current.style.height="";const Q=Math.min(td,e.current.scrollHeight);Qs<Q&&(e.current.style.height=`${Q}px`)}n(F.target.value)};return w?i.createElement(ns,null,i.createElement(os,{disabled:!0}),i.createElement(Qo,null,i.createElement(es,null,i.createElement(ts,{rows:1,...z.input.props,disabled:!0,placeholder:M,$blocked:!0,$focusVisible:!1,"data-focus-visible":"false"})))):i.createElement(ns,{"data-message-composer":""},i.createElement(os,{disabled:C}),i.createElement(Qo,null,i.createElement(UE,null),i.createElement(es,null,i.createElement(ts,{ref:e,rows:1,...z.input.props,readOnly:A,"aria-disabled":A?"true":void 0,placeholder:M,maxLength:5e3,$blocked:C,$focusVisible:c,"data-focus-visible":c?"true":"false",onKeyDown:J,onChange:T,onFocus:l.onFocus,onBlur:l.onBlur,onPaste:Le}))),O&&i.createElement(ji,{...z.send.props,onClick:()=>_e()},i.createElement(X,{type:"send",color:h.color.primary.main,size:20}),z.send.descriptionNode))},VE=p.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:${h.themedColor.textLowEmphasis};&& a{font-weight:700;text-decoration:none;${Z.light`
|
|
454
454
|
color: ${h.color.information.light};
|
|
455
455
|
`};
|
|
456
|
-
${
|
|
456
|
+
${Z.dark`
|
|
457
457
|
color: ${h.color.information.main};
|
|
458
458
|
`};
|
|
459
459
|
}
|
|
460
|
-
`,UE=u.lazy(()=>Promise.resolve().then(()=>require("./cjs/VvejebHE.cjs")).then(e=>({default:e.MarkdownText}))),BE=()=>{const{aiAgentInfo:e,userSession:t}=Me(),{handlers:n}=me(),{messageSource:r,channelSource:o}=Se(),[s,a]=u.useState(null),l=mr("special-notice",o.channel),c=u.useCallback(()=>o.channel?l?r.messages.some(d=>gt(d,(t==null?void 0:t.userId)??"")):!0:null,[o.channel,l,r.messages,t==null?void 0:t.userId]);return u.useEffect(()=>{s||a(c())},[c,s]),s||!e.specialNotice?null:i.createElement(FE,null,i.createElement(UE,{onClickLink:n.onClickLink},e.specialNotice))},HE=()=>i.createElement(GE,null,i.createElement(BE,null),i.createElement(SE,null,i.createElement(PE,null))),GE=p.default.div`z-index:0;border:none;width:100%;`,zE=()=>{var o;const{testerType:e}=_t(),{channelSource:t}=Se(),n=Le(t.channel),r=!!e&&((o=t.channel)==null?void 0:o.isAIAgent);return n&&r?i.createElement(CE,null):i.createElement(HE,null)},Wi=({start:e,title:t,titleAlign:n="start",end:r,containerProps:o})=>{const s=u.useRef(null),a=u.useRef(null),[l,c]=u.useState(0),[d,m]=u.useState(0);return u.useLayoutEffect(()=>{s.current&&c(s.current.offsetWidth),a.current&&m(a.current.offsetWidth)},[e,r]),i.createElement(VE,{...o},i.createElement(YE,null,n==="center"&&t&&i.createElement(WE,{$sideWidth:Math.max(l,d)},i.createElement(qE,null,t)),i.createElement(KE,null,i.createElement(jE,{ref:s},e),(n==="start"||n==="end")&&t&&i.createElement(ZE,{$align:n,$hasStart:!!e,$hasEnd:!!r},t),i.createElement(XE,{ref:a},r))))},VE=p.default.div`position:relative;width:100%;background-color:${({theme:e})=>e.colors.base.headerBackground};border-bottom:1px solid ${h.themedColor.textDisabled};`,YE=p.default.div`position:relative;height:56px;padding:11px 12px;`,WE=p.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;`,qE=p.default.div`max-width:100%;overflow:hidden;`,KE=p.default.div`display:flex;flex-direction:row;align-items:center;justify-content:space-between;height:100%;z-index:1;`,jE=p.default.div`flex-shrink:0;display:flex;align-items:center;`,XE=p.default.div`flex-shrink:0;display:flex;align-items:center;`,ZE=p.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;`,Et=(e=16)=>Nt()?e*1.5:e,JE=()=>{const{state:e}=me(),{messenger:t}=oe(),n=Et(),r=()=>{e.setOpened(!1)};return i.createElement(je,{...t.closeButton().props,type:"close",size:n,onClick:r})},QE=()=>{const{enableCloseConversationButton:e,dispatcher:t}=me(),{channelSource:n}=Se(),{conversation:r}=oe(),o=n.channel,s=Et(),a=(o==null?void 0:o.isAIAgent)&&e,l=!sr(o);if(!a)return null;const c={close:r.header.closeConversationButton()},d=async()=>{o&&await t.send(Ze.CloseConversation({channelUrl:o.url}))};return i.createElement(i.Fragment,null,i.createElement(je,{...c.close.props,type:"mute",size:s,disabled:l,onClick:d}),c.close.descriptionNode)},eb=()=>{const{state:e,enableExpandButton:t}=me(),{messenger:n}=oe(),r=Et();return t?i.createElement(je,{...n.expandButton(e.expanded).props,type:e.expanded?"collapse":"expand",size:r,onClick:()=>e.setExpanded(!e.expanded)}):null},tb=({label:e,children:t,position:n="top",disabled:r})=>r?t:i.createElement(Qn,null,t,i.createElement(ob,{$position:n},i.createElement(sb,{variant:"caption1"},e),i.createElement(nb,{$position:n}))),nb=({$position:e})=>i.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"},i.createElement("path",{d:"M6 6L0 0h12L6 6Z",fill:h.themedColor.textHighEmphasis})),rb={top:D.css`flex-direction:column;top:0;transform:translate(-50%,-100%);`,bottom:D.css`flex-direction:column-reverse;bottom:0;transform:translate(-50%,100%);`},Qn=p.default.div`position:relative;`,ob=p.default.div`display:flex;align-items:center;position:absolute;left:50%;z-index:${it.TOOLTIP};${({$position:e})=>rb[e]}opacity:0;transition:opacity 0.2s ease-in-out;pointer-events:none;${Qn}:hover &,${Qn}:focus-within &{opacity:1;}`,sb=p.default($)`padding:6px 8px;background:${h.themedColor.textHighEmphasis};color:${h.themedColor.textHighEmphasisInverse};border-radius:4px;font-size:12px;white-space:nowrap;`,ib=2e3,ns=0,ab=1500,Kt=Symbol("header-focus-status-pause"),rs="data-sb-header-focus-protected",lb="[data-message-composer]",os=new WeakMap,Pn=e=>{const t=os.get(e);if(t)return t;const n={focusedTargetIds:new Set,pendingBlurTimeouts:new Map,maxPauseTimeout:null};return os.set(e,n),n},Fn=(e,t)=>{const n=e.pendingBlurTimeouts.get(t);n&&(clearTimeout(n),e.pendingBlurTimeouts.delete(t))},Xt=e=>{e.maxPauseTimeout&&(clearTimeout(e.maxPauseTimeout),e.maxPauseTimeout=null)},cb=e=>{e.pendingBlurTimeouts.forEach(t=>clearTimeout(t)),e.pendingBlurTimeouts.clear(),e.focusedTargetIds.clear(),Xt(e)},ub=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)})},db=e=>e instanceof HTMLBodyElement||(e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&e.disabled?!0:(e instanceof HTMLElement&&e.closest(lb),!1),kr=()=>{const{setStatusPauseState:e}=Ke(),t=u.useRef(Symbol("header-focus-target")),n=u.useRef(!1),r=u.useRef(0),o=u.useRef(null),s=u.useCallback(()=>{o.current&&(clearTimeout(o.current),o.current=null)},[]),a=u.useCallback(()=>{if(n.current)return;n.current=!0,r.current=Date.now()+ab,s();const c=Pn(e);Fn(c,t.current),c.focusedTargetIds.add(t.current),c.focusedTargetIds.size===1&&e(Kt,!0),Xt(c),c.maxPauseTimeout=setTimeout(()=>{cb(c),e(Kt,!1)},ib)},[s,e]),l=u.useCallback(c=>{if(!n.current)return;n.current=!1;const d=c.currentTarget,m=Pn(e),f=d instanceof HTMLElement&&Date.now()<=r.current;Fn(m,t.current),f&&(s(),o.current=setTimeout(()=>{if(o.current=null,!(d instanceof HTMLElement)||!d.isConnected)return;const _=d.ownerDocument.activeElement,v=_ instanceof HTMLElement&&_.hasAttribute(rs);if(_===d||v||!db(_))return;const y=ub(d);d.focus({preventScroll:!0}),y()},ns)),m.pendingBlurTimeouts.set(t.current,setTimeout(()=>{m.pendingBlurTimeouts.delete(t.current),m.focusedTargetIds.delete(t.current),m.focusedTargetIds.size===0&&(Xt(m),e(Kt,!1))},ns))},[s,e]);return u.useEffect(()=>()=>{const c=Pn(e);n.current=!1,s(),Fn(c,t.current),c.focusedTargetIds.delete(t.current)&&c.focusedTargetIds.size===0&&(Xt(c),e(Kt,!1))},[s,e]),{[rs]:"true",onFocus:a,onBlur:l}},mb=()=>{const{logger:e}=me(),{stringSet:t}=se(),{channelSource:n}=Se(),{conversation:r}=oe(),o=n.channel,s=Et(),a=mr("handoff-button",o),l=!sr(o)||et(o),[c,d]=u.useState(!1),m=kr(),f=async()=>{d(!1);try{const _=await(o==null?void 0:o.markConversationAsHandoff());e.info("conversation.handleAgentHandoff: success",_)}catch(_){e.error("conversation.handleAgentHandoff: error",_)}};if(!a)return null;const g={handoff:r.header.handoffButton()};return i.createElement(i.Fragment,null,i.createElement(i.Fragment,null,i.createElement(tb,{label:t.HEADER_BUTTON__AGENT_HANDOFF,position:"bottom",disabled:l},i.createElement(je,{...g.handoff.props,type:"agent",size:s,disabled:l,...m,onClick:()=>d(!0)})),g.handoff.descriptionNode),i.createElement(nt,{portalContainerId:Ce.WINDOW,visible:c,onClose:()=>d(!1)},i.createElement(Ir,{title:t.HANDOFF_CONFIRM__TITLE,description:t.HANDOFF_CONFIRM__DESCRIPTION,negativeText:t.HANDOFF_CONFIRM__CANCEL,positiveText:t.HANDOFF_CONFIRM__HANDOFF,onCancel:()=>d(!1),onConfirm:f})))},fb=u.lazy(()=>Promise.resolve().then(()=>require("./cjs/VvejebHE.cjs")).then(e=>({default:e.MarkdownText}))),gb=()=>{const{logger:e}=me(),{stringSet:t}=se(),{memoryInfo:n,sdkUser:r}=Me(),{actions:o}=Se(),{conversation:s}=oe(),a=Et(20),l=kr(),[c,d]=u.useState(null),[m,f]=u.useState(!1),g=u.useRef(!1);if(u.useEffect(()=>{r&&(n!=null&&n.consentDialog)&&d({...n})},[r,n==null?void 0:n.consentDialog]),!r||!n)return null;const _=s.header.memoryIndicator(n.enabled),v=async y=>{if(!g.current){g.current=!0,f(!1);try{await o.setUserMemoryState({enabled:y}),d(null)}catch(b){e.error("memoryIndicator.setUserMemoryState: error",b),f(!0)}finally{g.current=!1}}};return i.createElement(i.Fragment,null,n.showIndicator&&i.createElement(i.Fragment,null,i.createElement(Eb,{..._.props,as:"button",type:"button",onClick:()=>d({...n}),...l,$size:a},i.createElement(Q,{type:"memory",size:a,color:h.themedColor.textHighEmphasis}),i.createElement(bb,{$enabled:n.enabled})),_.descriptionNode),c&&i.createElement(hb,{memoryInfo:c,onClose:()=>d(null),onSetEnabled:v}),i.createElement(hn,{visible:m,title:t.PLACE_HOLDER__WRONG,description:t.MEMORY__ERROR_MESSAGE,onClose:()=>f(!1)}))},hb=({memoryInfo:e,onClose:t,onSetEnabled:n})=>{var f;const{stringSet:r}=se(),{colors:o}=D.useTheme(),s=u.useId(),a=u.useId(),l=xl(e),c=l==="consent",d={consent:{body:((f=e.consentDialog)==null?void 0:f.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}}[l],m=o.memoryDialog;return i.createElement(nt,{visible:!0,portalContainerId:Ce.WINDOW,onClose:t,cancelable:!c,"aria-labelledby":s,"aria-describedby":a},i.createElement(Ir,{title:r.MEMORY__DIALOG_TITLE,titleId:s,description:i.createElement(pb,null,d.body),descriptionId:a,negativeText:d.negativeText,positiveText:d.positiveText,buttonLayout:c?"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}}))},pb=({children:e})=>{const{handlers:t}=me();return i.createElement(Cb,null,i.createElement(Mt,{fallback:e},i.createElement(fb,{onClickLink:t.onClickLink},e)))},_b=D.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;`,Eb=p.default.button`${_b};cursor:pointer;${Ae}`,bb=p.default.span`position:absolute;top:0;inset-inline-end:0;width:8px;height:8px;border-radius:999px;background-color:${({$enabled:e})=>e?h.themedColor.secondary:h.color.background300};box-shadow:0 0 0 2px ${h.color.background50};${J.dark`
|
|
460
|
+
`,YE=u.lazy(()=>Promise.resolve().then(()=>require("./cjs/VvejebHE.cjs")).then(e=>({default:e.MarkdownText}))),WE=()=>{const{aiAgentInfo:e,userSession:t}=ke(),{handlers:n}=ae(),{messageSource:r,channelSource:o}=Se(),[s,a]=u.useState(null),l=gr("special-notice",o.channel),c=u.useCallback(()=>o.channel?l?r.messages.some(d=>gt(d,(t==null?void 0:t.userId)??"")):!0:null,[o.channel,l,r.messages,t==null?void 0:t.userId]);return u.useEffect(()=>{s||a(c())},[c,s]),s||!e.specialNotice?null:i.createElement(VE,null,i.createElement(YE,{onClickLink:n.onClickLink},e.specialNotice))},qE=()=>i.createElement(KE,null,i.createElement(WE,null),i.createElement(ME,null,i.createElement(zE,null))),KE=p.default.div`z-index:0;border:none;width:100%;`,jE=()=>{var o;const{testerType:e}=_t(),{channelSource:t}=Se(),n=Ne(t.channel),r=!!e&&((o=t.channel)==null?void 0:o.isAIAgent);return n&&r?i.createElement(TE,null):i.createElement(qE,null)},Xi=({start:e,title:t,titleAlign:n="start",end:r,containerProps:o})=>{const s=u.useRef(null),a=u.useRef(null),[l,c]=u.useState(0),[d,m]=u.useState(0);return u.useLayoutEffect(()=>{s.current&&c(s.current.offsetWidth),a.current&&m(a.current.offsetWidth)},[e,r]),i.createElement(XE,{...o},i.createElement(ZE,null,n==="center"&&t&&i.createElement(JE,{$sideWidth:Math.max(l,d)},i.createElement(QE,null,t)),i.createElement(eb,null,i.createElement(tb,{ref:s},e),(n==="start"||n==="end")&&t&&i.createElement(rb,{$align:n,$hasStart:!!e,$hasEnd:!!r},t),i.createElement(nb,{ref:a},r))))},XE=p.default.div`position:relative;width:100%;background-color:${({theme:e})=>e.colors.base.headerBackground};border-bottom:1px solid ${h.themedColor.textDisabled};`,ZE=p.default.div`position:relative;height:56px;padding:11px 12px;`,JE=p.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;`,QE=p.default.div`max-width:100%;overflow:hidden;`,eb=p.default.div`display:flex;flex-direction:row;align-items:center;justify-content:space-between;height:100%;z-index:1;`,tb=p.default.div`flex-shrink:0;display:flex;align-items:center;`,nb=p.default.div`flex-shrink:0;display:flex;align-items:center;`,rb=p.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;`,Et=(e=16)=>Dt()?e*1.5:e,ob=()=>{const{state:e}=ae(),{messenger:t}=oe(),n=Et(),r=()=>{e.setOpened(!1)};return i.createElement(Ze,{...t.closeButton().props,type:"close",size:n,onClick:r})},sb=()=>{const{enableCloseConversationButton:e,dispatcher:t}=ae(),{channelSource:n}=Se(),{conversation:r}=oe(),o=n.channel,s=Et(),a=(o==null?void 0:o.isAIAgent)&&e,l=!ar(o);if(!a)return null;const c={close:r.header.closeConversationButton()},d=async()=>{o&&await t.send(Qe.CloseConversation({channelUrl:o.url}))};return i.createElement(i.Fragment,null,i.createElement(Ze,{...c.close.props,type:"mute",size:s,disabled:l,onClick:d}),c.close.descriptionNode)},ib=()=>{const{state:e,enableExpandButton:t}=ae(),{messenger:n}=oe(),r=Et();return t?i.createElement(Ze,{...n.expandButton(e.expanded).props,type:e.expanded?"collapse":"expand",size:r,onClick:()=>e.setExpanded(!e.expanded)}):null},ab=({label:e,children:t,position:n="top",disabled:r})=>r?t:i.createElement(tr,null,t,i.createElement(ub,{$position:n},i.createElement(db,{variant:"caption1"},e),i.createElement(lb,{$position:n}))),lb=({$position:e})=>i.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"},i.createElement("path",{d:"M6 6L0 0h12L6 6Z",fill:h.themedColor.textHighEmphasis})),cb={top:D.css`flex-direction:column;top:0;transform:translate(-50%,-100%);`,bottom:D.css`flex-direction:column-reverse;bottom:0;transform:translate(-50%,100%);`},tr=p.default.div`position:relative;`,ub=p.default.div`display:flex;align-items:center;position:absolute;left:50%;z-index:${it.TOOLTIP};${({$position:e})=>cb[e]}opacity:0;transition:opacity 0.2s ease-in-out;pointer-events:none;${tr}:hover &,${tr}:focus-within &{opacity:1;}`,db=p.default($)`padding:6px 8px;background:${h.themedColor.textHighEmphasis};color:${h.themedColor.textHighEmphasisInverse};border-radius:4px;font-size:12px;white-space:nowrap;`,mb=2e3,ss=0,fb=1500,Xt=Symbol("header-focus-status-pause"),is="data-sb-header-focus-protected",gb="[data-message-composer]",as=new WeakMap,Un=e=>{const t=as.get(e);if(t)return t;const n={focusedTargetIds:new Set,pendingBlurTimeouts:new Map,maxPauseTimeout:null};return as.set(e,n),n},Bn=(e,t)=>{const n=e.pendingBlurTimeouts.get(t);n&&(clearTimeout(n),e.pendingBlurTimeouts.delete(t))},Qt=e=>{e.maxPauseTimeout&&(clearTimeout(e.maxPauseTimeout),e.maxPauseTimeout=null)},hb=e=>{e.pendingBlurTimeouts.forEach(t=>clearTimeout(t)),e.pendingBlurTimeouts.clear(),e.focusedTargetIds.clear(),Qt(e)},pb=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)})},_b=e=>e instanceof HTMLBodyElement||(e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&e.disabled?!0:(e instanceof HTMLElement&&e.closest(gb),!1),Or=()=>{const{setStatusPauseState:e}=Xe(),t=u.useRef(Symbol("header-focus-target")),n=u.useRef(!1),r=u.useRef(0),o=u.useRef(null),s=u.useCallback(()=>{o.current&&(clearTimeout(o.current),o.current=null)},[]),a=u.useCallback(()=>{if(n.current)return;n.current=!0,r.current=Date.now()+fb,s();const c=Un(e);Bn(c,t.current),c.focusedTargetIds.add(t.current),c.focusedTargetIds.size===1&&e(Xt,!0),Qt(c),c.maxPauseTimeout=setTimeout(()=>{hb(c),e(Xt,!1)},mb)},[s,e]),l=u.useCallback(c=>{if(!n.current)return;n.current=!1;const d=c.currentTarget,m=Un(e),f=d instanceof HTMLElement&&Date.now()<=r.current;Bn(m,t.current),f&&(s(),o.current=setTimeout(()=>{if(o.current=null,!(d instanceof HTMLElement)||!d.isConnected)return;const E=d.ownerDocument.activeElement,y=E instanceof HTMLElement&&E.hasAttribute(is);if(E===d||y||!_b(E))return;const v=pb(d);d.focus({preventScroll:!0}),v()},ss)),m.pendingBlurTimeouts.set(t.current,setTimeout(()=>{m.pendingBlurTimeouts.delete(t.current),m.focusedTargetIds.delete(t.current),m.focusedTargetIds.size===0&&(Qt(m),e(Xt,!1))},ss))},[s,e]);return u.useEffect(()=>()=>{const c=Un(e);n.current=!1,s(),Bn(c,t.current),c.focusedTargetIds.delete(t.current)&&c.focusedTargetIds.size===0&&(Qt(c),e(Xt,!1))},[s,e]),{[is]:"true",onFocus:a,onBlur:l}},Eb=()=>{const{logger:e}=ae(),{stringSet:t}=se(),{channelSource:n}=Se(),{conversation:r}=oe(),o=n.channel,s=Et(),a=gr("handoff-button",o),l=!ar(o)||nt(o),[c,d]=u.useState(!1),m=Or(),f=async()=>{d(!1);try{const E=await(o==null?void 0:o.markConversationAsHandoff());e.info("conversation.handleAgentHandoff: success",E)}catch(E){e.error("conversation.handleAgentHandoff: error",E)}};if(!a)return null;const g={handoff:r.header.handoffButton()};return i.createElement(i.Fragment,null,i.createElement(i.Fragment,null,i.createElement(ab,{label:t.HEADER_BUTTON__AGENT_HANDOFF,position:"bottom",disabled:l},i.createElement(Ze,{...g.handoff.props,type:"agent",size:s,disabled:l,...m,onClick:()=>d(!0)})),g.handoff.descriptionNode),i.createElement(ot,{portalContainerId:be.WINDOW,visible:c,onClose:()=>d(!1)},i.createElement(kr,{title:t.HANDOFF_CONFIRM__TITLE,description:t.HANDOFF_CONFIRM__DESCRIPTION,negativeText:t.HANDOFF_CONFIRM__CANCEL,positiveText:t.HANDOFF_CONFIRM__HANDOFF,onCancel:()=>d(!1),onConfirm:f})))},bb=u.lazy(()=>Promise.resolve().then(()=>require("./cjs/VvejebHE.cjs")).then(e=>({default:e.MarkdownText}))),Cb=()=>{const{logger:e}=ae(),{stringSet:t}=se(),{memoryInfo:n,sdkUser:r}=ke(),{actions:o}=Se(),{conversation:s}=oe(),a=Et(20),l=Or(),[c,d]=u.useState(null),[m,f]=u.useState(!1),g=u.useRef(!1);if(u.useEffect(()=>{r&&(n!=null&&n.consentDialog)&&d({...n})},[r,n==null?void 0:n.consentDialog]),!r||!n)return null;const E=s.header.memoryIndicator(n.enabled),y=async v=>{if(!g.current){g.current=!0,f(!1);try{await o.setUserMemoryState({enabled:v}),d(null)}catch(b){e.error("memoryIndicator.setUserMemoryState: error",b),f(!0)}finally{g.current=!1}}};return i.createElement(i.Fragment,null,n.showIndicator&&i.createElement(i.Fragment,null,i.createElement(Ab,{...E.props,as:"button",type:"button",onClick:()=>d({...n}),...l,$size:a},i.createElement(X,{type:"memory",size:a,color:h.themedColor.textHighEmphasis}),i.createElement(xb,{$enabled:n.enabled})),E.descriptionNode),c&&i.createElement(vb,{memoryInfo:c,onClose:()=>d(null),onSetEnabled:y}),i.createElement(En,{visible:m,title:t.PLACE_HOLDER__WRONG,description:t.MEMORY__ERROR_MESSAGE,onClose:()=>f(!1)}))},vb=({memoryInfo:e,onClose:t,onSetEnabled:n})=>{var f;const{stringSet:r}=se(),{colors:o}=D.useTheme(),s=u.useId(),a=u.useId(),l=kl(e),c=l==="consent",d={consent:{body:((f=e.consentDialog)==null?void 0:f.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}}[l],m=o.memoryDialog;return i.createElement(ot,{visible:!0,portalContainerId:be.WINDOW,onClose:t,cancelable:!c,"aria-labelledby":s,"aria-describedby":a},i.createElement(kr,{title:r.MEMORY__DIALOG_TITLE,titleId:s,description:i.createElement(yb,null,d.body),descriptionId:a,negativeText:d.negativeText,positiveText:d.positiveText,buttonLayout:c?"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}}))},yb=({children:e})=>{const{handlers:t}=ae();return i.createElement(Tb,null,i.createElement(kt,{fallback:e},i.createElement(bb,{onClickLink:t.onClickLink},e)))},Sb=D.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;`,Ab=p.default.button`${Sb};cursor:pointer;${Ae}`,xb=p.default.span`position:absolute;top:0;inset-inline-end:0;width:8px;height:8px;border-radius:999px;background-color:${({$enabled:e})=>e?h.themedColor.secondary:h.color.background300};box-shadow:0 0 0 2px ${h.color.background50};${Z.dark`
|
|
461
461
|
box-shadow: 0 0 0 2px ${h.color.background500};
|
|
462
462
|
`}
|
|
463
|
-
`,
|
|
463
|
+
`,Tb=p.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;}`,Ib=()=>{const{conversation:e}=oe(),{onNavigateToConversationList:t}=Se();if(!t)return null;const n={menu:e.header.menuButton()};return i.createElement(i.Fragment,null,i.createElement(Ze,{...n.menu.props,...Ws,type:"menu",size:24,onClick:()=>t()}),n.menu.descriptionNode)},Zi=({channel:e,size:t=40})=>{const{userSession:n,aiAgentInfo:r}=ke(),{fallbackIcon:o,url:s}=hr({channel:e,aiAgentInfo:r,userSession:n}),a=D.useTheme();return s?i.createElement(Ri,{src:s,size:t,"aria-hidden":"true"}):i.createElement(wb,{"aria-hidden":"true",$size:t,$bgColor:a.colors.base.primary},i.createElement(X,{type:o,size:t*.55,color:a.colors.base.primaryContrastContent}))},wb=p.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;`,Mb=()=>{const{channelSource:e}=Se(),{aiAgentInfo:t,userSession:n}=ke(),{conversation:r}=oe(),{config:o}=Re(),{announcementsEnabled:s}=Xe(),a=e.channel,l=hr({channel:a,userSession:n,aiAgentInfo:t}),c=o.conversation.header.avatarEnabled,d=Or(),m=vi({enabled:s,label:l.title}),f={title:r.header.title(l.title,{active:m.enabled,titleId:m.id,initialFocus:!1})};return i.createElement(kb,null,c&&i.createElement(Zi,{channel:a,size:34}),i.createElement(Rb,{...f.title.props,...d},l.title))},kb=p.default.div`display:flex;flex-direction:row;align-items:center;gap:6px;min-width:0;width:100%;overflow:hidden;`,Rb=p.default($).attrs({variant:"h2",color:h.themedColor.textHighEmphasis})`
|
|
464
464
|
margin: 0;
|
|
465
465
|
flex: 1;
|
|
466
466
|
min-width: 0;
|
|
@@ -472,10 +472,10 @@
|
|
|
472
472
|
&:focus {
|
|
473
473
|
outline: none;
|
|
474
474
|
}
|
|
475
|
-
`,
|
|
475
|
+
`,Lb=e=>{const{components:t}=lt.useContext();return i.createElement(Xi,{start:i.createElement(t.StartArea,null),title:i.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:i.createElement(t.EndArea,null),containerProps:js})},Ob=()=>{const{components:e}=lt.useContext();return i.createElement(e.MenuButton,null)},Nb=()=>{const{components:e}=lt.useContext();return i.createElement(e.Title,null)},Db=()=>{const{components:e}=lt.useContext();return i.createElement(Pb,null,i.createElement(e.MemoryIndicator,null),i.createElement(e.HandoffButton,null),i.createElement(e.ConversationCloseButton,null),i.createElement(e.ExpandButton,null),i.createElement(e.CloseButton,null))},lt=Ge({template:Lb,components:{StartArea:Ob,TitleArea:Nb,EndArea:Db,MenuButton:Ib,Title:Mb,MemoryIndicator:Cb,HandoffButton:Eb,ConversationCloseButton:sb,ExpandButton:ib,CloseButton:ob}}),$b=()=>{const{isActionbookTester:e}=_t(),{Template:t}=lt.useContext();return e?null:i.createElement(t,{titleAlign:"start"})},Pb=p.default.div`display:flex;gap:10px;align-items:center;justify-content:center;`,Ji=({children:e,onNavigateToConversationList:t,channelUrl:n,onClearChannelUrl:r,shouldMarkAsRead:o,announcementsEnabled:s,initialFocusTarget:a,style:l,closedChannelUrl:c,onClearClosedChannelUrl:d})=>{const{Template:m}=An.useContext();return i.createElement(Ei,{onNavigateToConversationList:t,channelUrl:n??c,onClearChannelUrl:r??d,shouldMarkAsRead:o},i.createElement(Xn,null,i.createElement(Xn.Consumer,null,f=>i.createElement(Wd,{announcementsEnabled:s},i.createElement(Fb,null),i.createElement(Ub,{style:l,dragHandlers:f,initialFocusTarget:a},i.createElement(m,null)),e))))},Fb=()=>(lf(),Zm(),of(),null),Ub=({style:e,dragHandlers:t,initialFocusTarget:n,children:r})=>{const o=u.useRef(null);return Ym(o,n),i.createElement(Hb,{ref:o,style:e,...t},r)},Bb=e=>{const{components:t}=An.useContext();return i.createElement(i.Fragment,null,i.createElement(t.Header,null),i.createElement(t.Body,null),i.createElement(t.Footer,null))},An=Ge({template:Bb,components:{Header:$b,Body:xE,Footer:jE}}),Hb=p.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,Qi=pe("ConversationListAnnouncements",{announcementsEnabled:!0,announceScreenEntry:ce}),Gb=Qi.Provider,Nr=Qi.useContext,zb=({children:e,announcementsEnabled:t=!0})=>{const{announceScreenEntry:n}=vr(),r=u.useCallback(s=>{t&&n(s)},[n,t]),o=u.useMemo(()=>({announcementsEnabled:t,announceScreenEntry:r}),[t,r]);return i.createElement(Gb,{value:o},e)},{Provider:Vb,Context:Yb,useContext:Ft}=pe("ConversationList");function ea({conversationListLimit:e,conversationListFilter:t,onOpenConversationView:n=ce,children:r}){return i.createElement(Oc,{conversationListLimit:e,conversationListFilter:t},o=>i.createElement(Vb,{value:{...o,onOpenConversationView:n}},r))}const Wb=e=>{const{announcementsEnabled:t}=Nr(),{listSource:n}=Ft(),r=oi();yi(e,{enabled:t,ready:n.initialized,suppressed:r})},qb=()=>{const{announceScreenEntry:e,announcementsEnabled:t}=Nr(),{listSource:n}=Ft(),r=u.useRef(!1);u.useEffect(()=>{if(!t){r.current=!1;return}if(!n.initialized||r.current)return;const o=n.channels.length,s=setTimeout(()=>{e({screen:"conversationList",conversationCount:o}),r.current=!0},0);return()=>clearTimeout(s)},[e,t,n.initialized])},Kb=({channel:e})=>i.createElement(Zi,{channel:e}),nr=99,jb=e=>{var b,_;const{channel:t,onClick:n}=e,{stringSet:r,format:o}=se(),{userSession:s,aiAgentInfo:a}=ke(),{conversationList:l}=oe(),c=hr({channel:t,userSession:s,aiAgentInfo:a}),d=Tl(t,{formatMultipleFilesCount:r.CONVERSATION_LIST__MULTIPLE_FILES_COUNT}),m=Il(t,o,{justNow:r.DATE_FORMAT__JUST_NOW,minutesAgo:r.DATE_FORMAT__MINUTES_AGO,hoursAgo:r.DATE_FORMAT__HOURS_AGO,dateShortFormat:r.DATE_FORMAT__DATE_SHORT}),f=t.unreadMessageCount,g=(b=t.lastMessage)!=null&&b.isAdminMessage()?r.CONVERSATION_LIST__SYSTEM_MESSAGE:c.title,E=Ne(t)?r.CONVERSATION_LIST__ENDED:Ms(t,{formatMultipleFilesCount:r.CONVERSATION_LIST__MULTIPLE_FILES_COUNT}),y=n?()=>n():void 0,v=l.item({agent:g,status:E,time:m,unreadCount:f,onActivate:y});return i.createElement(Xb,{"data-testid":"sb-conversation-list-item",$clickable:!!y,...v.props},i.createElement(Zb,null,i.createElement(Kb,{...e})),i.createElement(Jb,null,i.createElement(Qb,null,(_=t.lastMessage)!=null&&_.isFileMessage()&&(!t.lastMessage.message||t.lastMessage.name===t.lastMessage.message)?i.createElement(Ii,{variant:"subtitle1",color:h.themedColor.textHighEmphasis},d):i.createElement($,{variant:"subtitle1",color:h.themedColor.textHighEmphasis,maxTextLines:1},d),i.createElement(eC,null,Ne(t)&&i.createElement(i.Fragment,null,i.createElement($,{variant:"caption1",color:h.themedColor.textMidEmphasis,maxTextLines:1},r.CONVERSATION_LIST__ENDED),i.createElement(tC,null)),i.createElement($,{variant:"caption2",color:h.themedColor.textLowEmphasis,maxTextLines:1},m))),f>0&&i.createElement(nC,{$count:f},i.createElement($,{variant:"caption3",color:h.themedColor.textHighEmphasisInverse},f<=nr?f:`${nr}+`))),v.descriptionNode)},Dr=Ge({template:jb,components:{}}),Xb=p.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"};`,Zb=p.default.div`display:flex;align-items:center;justify-content:center;padding-inline-start:16px;`,Jb=p.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 ${h.themedColor.textDisabled};`,Qb=p.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;`,eC=p.default.div`display:flex;align-items:center;gap:6px;`,tC=p.default.div`width:2px;height:2px;border-radius:1px;background-color:${h.themedColor.textLowEmphasis};`,nC=p.default.div`display:flex;align-items:center;justify-content:center;height:20px;padding:4px;border-radius:10px;background-color:${h.themedColor.error};${({$count:e})=>e<=nr&&D.css`
|
|
476
476
|
width: 20px;
|
|
477
477
|
`}
|
|
478
|
-
`,
|
|
478
|
+
`,rC=({items:e,renderItem:t,onEndReached:n,role:r,"aria-label":o})=>{const s=a=>{const l=a.target;l.scrollHeight-l.scrollTop-l.clientHeight<=2&&(n==null||n())};return i.createElement(oC,{role:r,"aria-label":o,onScroll:a=>s(a)},e.map((a,l)=>{const c=t(a,l);if(r!=="list")return c;const d=u.isValidElement(c)&&c.key!=null?c.key:l;return i.createElement(sC,{key:d,role:"listitem"},c)}))},oC=p.default.div`width:100%;height:100%;display:flex;flex-direction:column;flex:1;overflow:auto;overscroll-behavior:contain;`,sC=p.default.div`flex-shrink:0;`,iC=()=>{const{stringSet:e}=se(),{listSource:t,onOpenConversationView:n}=Ft(),{Template:r}=Dr.useContext();return t.initialized?t.channels.length===0?i.createElement(wt,{type:"noChannels",label:e.CONVERSATION_LIST__NO_CONVERSATIONS}):i.createElement(rC,{role:"list","aria-label":e.CONVERSATION_LIST__HEADER_TITLE,items:t.channels,renderItem:o=>{var s,a,l;return i.createElement(r,{key:o.url,channel:o,onClick:()=>n(o.url,Ne(o)?"closed":"open"),channelUrl:o.url,title:(a=(s=o.conversation)==null?void 0:s.topics)==null?void 0:a.join(", "),lastMessageTimestamp:(l=o.lastMessage)==null?void 0:l.createdAt})},onEndReached:()=>{t.loadMore()}}):i.createElement(wt,{type:"loading"})},aC=()=>{const{stringSet:e}=se(),{_aiAgentSDK:t}=Re(),{language:n,countryCode:r,context:o}=ae(),{aiAgentInfo:s,refreshActiveChannel:a,createConversation:l}=ke(),{onOpenConversationView:c}=Ft(),{conversationList:d}=oe(),m=async()=>{var f;if(s.isMultipleActiveConversationsEnabled){const g=await l({aiAgentId:s.userId,language:n,country:r,context:o});(f=t.session)==null||f._updateActiveChannel({url:g,status:"open"}),c(g,"open",{initialFocusTarget:"messageInput"})}else{const g=await a();c(g,"open",{initialFocusTarget:"messageInput"})}};return i.createElement(lC,{...d.footer.button({onActivate:m}).props},i.createElement(cC,{variant:"h1"},e.TALK_TO_AGENT))},lC=p.default.div`background-color:${({theme:e})=>e.colors.base.primary};display:flex;align-items:center;justify-content:center;padding:16px;cursor:pointer;`,cC=p.default($)`color:${({theme:e})=>e.colors.base.primaryContrastContent};overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,uC=()=>{const{state:e}=ae(),{messenger:t}=oe(),n=Et(),r=()=>{e.setOpened(!1)};return i.createElement(Ze,{...t.closeButton().props,type:"close",size:n,onClick:r})},dC=()=>{const{stringSet:e}=se(),{announcementsEnabled:t}=Nr(),{conversationList:n}=oe(),r=e.CONVERSATION_LIST__HEADER_TITLE,o=vi({enabled:t,label:r}),s={title:n.headerTitle(r,{active:o.enabled,titleId:o.id})};return i.createElement(mC,{forwardedAs:"h2",variant:"h2",color:h.themedColor.textHighEmphasis,...s.title.props},r)},mC=p.default($)`margin:0;padding:0 4px;min-width:0;width:100%;box-sizing:border-box;text-overflow:ellipsis;overflow:hidden;white-space:nowrap;`,fC=e=>{const{components:t}=bt.useContext();return i.createElement(Xi,{start:i.createElement(t.StartArea,null),title:i.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:i.createElement(t.EndArea,null),containerProps:js})},gC=()=>null,hC=()=>{const{components:e}=bt.useContext();return i.createElement(e.Title,null)},pC=()=>{const{components:e}=bt.useContext();return i.createElement(e.CloseButton,null)},bt=Ge({template:fC,components:{StartArea:gC,TitleArea:hC,EndArea:pC,Title:dC,CloseButton:uC}}),_C=()=>{const{Template:e}=bt.useContext();return i.createElement(e,{titleAlign:"start"})},EC=()=>(qb(),null),ta=({conversationListLimit:e,conversationListFilter:t,children:n,onOpenConversationView:r,announcementsEnabled:o=!0,style:s})=>{const{Template:a}=xn.useContext();return i.createElement(ea,{conversationListLimit:e,conversationListFilter:t,onOpenConversationView:r},i.createElement(zb,{announcementsEnabled:o},i.createElement(EC,null),i.createElement(bC,{style:s},i.createElement(a,null)),n))},bC=({style:e,children:t})=>{const n=u.useRef(null);return Wb(n),i.createElement(vC,{ref:n,style:e},t)},CC=()=>{const{components:e}=xn.useContext();return i.createElement(i.Fragment,null,i.createElement(e.Header,null),i.createElement(e.Body,null),i.createElement(e.Footer,null))},xn=Ge({template:CC,components:{Header:_C,Body:iC,Footer:aC}}),vC=p.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,yC=D.css`:where(#${be.ENTRY}) :not(code *){font-family:'Roboto',sans-serif;box-sizing:border-box;}`,SC=[yC,bd,Cd],AC=(e,...t)=>D.createGlobalStyle(e,...SC,...t),xC=AC``,TC=xl(An,rt,Pt,Cn,Sn,xn,lt,Dr,bt,yn,_n),IC=typeof __SBA_USE_MESSAGE_TEMPLATE__>"u"||__SBA_USE_MESSAGE_TEMPLATE__;function na({appearance:e,rootElement:t,logger:n,language:r,languageCode:o,stringSet:s,children:a,messageTemplate:l,icons:c,theme:d,entryElement:m,modalRootElement:f}){Ud(IC?id:"",t);const[g,E]=u.useState(null),y=u.useCallback(_=>{E(C=>C===_?C:_)},[]),v=m??g,b=i.createElement(D.StyleSheetManager,{target:t},i.createElement($d,{rootElement:t,logger:n,appearance:e,theme:d},i.createElement(ud,{rootElement:t,boundaryElement:v},i.createElement(Pc,{internalVariables:l==null?void 0:l.__internalVariables},i.createElement(Ed,{stringSet:s,logger:n,language:r,languageCode:o},i.createElement(Nd,{icons:c},i.createElement(TC,null,i.createElement(ld,{entryElement:v,modalRootElement:f,rootElement:t},a),i.createElement(xC,null))))))));return m?b:i.createElement("div",{ref:y,style:{display:"contents"}},b)}const wC=()=>{const[e,t]=u.useState(null),[n,r]=u.useState(null),o=u.useCallback(a=>{t(l=>l===a?l:a)},[]),s=u.useCallback(a=>{r(l=>l===a?l:a)},[]);return{entryElement:e,modalRootElement:n,setEntryElement:o,setModalRootElement:s}},$r=u.forwardRef(function({rootElement:t=document.body,logLevel:n=ue.LogLevel.WARN,language:r=navigator.language,userSessionInfo:o,children:s,chatParams:a,icons:l,...c},d){var b,_,C;Tt.level!==n&&(Tt.level=n);const{entryElement:m,modalRootElement:f,setEntryElement:g,setModalRootElement:E}=wC();Fd("https://fonts.googleapis.com/css2?family=Roboto&display=swap",t);const y=ti(r),v=ni.has(y)?y:Nt;return i.createElement("div",{ref:g,id:be.ENTRY,lang:v,style:{width:"fit-content",height:"fit-content",...c.entryStyle}},m&&f&&i.createElement(na,{logger:Tt,rootElement:t,appearance:(b=c.agentPreviewConfigs)==null?void 0:b.appearance,stringSet:c.stringSet,language:v,messageTemplate:c.messageTemplate,icons:l,theme:c.theme,entryElement:m,modalRootElement:f},i.createElement(Em,{rootElement:t,language:r,logger:Tt,dispatcher:ra,chatParams:{...a,...c.customApiHost&&{customApiHost:c.customApiHost},...c.customWebSocketHost&&{customWebSocketHost:c.customWebSocketHost}},chatSDK:c.customChatSDK,_forceCreateChannel:(_=c.agentPreviewConfigs)==null?void 0:_.forceCreateChannel,_agentVersion:(C=c.agentPreviewConfigs)==null?void 0:C.agentVersion,...c},i.createElement(Tm,{ref:d,userSessionInfo:o},i.createElement(Wp,{...c._UNSAFE_INTERNAL_dashboardTester},i.createElement(Vd,null,s))))),i.createElement("div",{ref:E,id:be.MODAL_ROOT,dir:c.dir}))}),Tt=new bs(ue.LogLevel.WARN),ra=new Es(Tt),{Provider:MC,useContext:Pr}=pe("PageChildren"),oa=({children:e})=>{const[t,n]=u.useState(null),[r,o]=u.useState(null);return i.createElement(MC,{value:{conversationChildren:t,setConversationChildren:n,conversationListChildren:r,setConversationListChildren:o}},e)},Fr=(e,t)=>e?{role:"dialog","aria-modal":"true",...t?{"aria-labelledby":be.WINDOW_TITLE}:{"aria-label":"Messenger"}}:{"aria-hidden":"true",inert:!0},sa=({children:e,isOpened:t,zIndex:n=it.WINDOW})=>i.createElement(xr,null,i.createElement(kC,{isOpened:t,zIndex:n},e)),kC=({children:e,isOpened:t,zIndex:n=it.WINDOW})=>{const{dir:r,rootElement:o}=ae(),s=st(o,!0),a=u.useRef(null),{hasWindowTitleReference:l,isWindowNameReady:c}=bn();return pn(t,a,{nameReady:c}),u.useEffect(()=>{const d="sb-agent-block-scroll";return t?s.body.classList.add(d):s.body.classList.remove(d),()=>{s.body.classList.remove(d)}},[s,t]),i.createElement(RC,{ref:a,id:be.WINDOW,dir:r,...Fr(t,l),$visible:t,$zIndex:n},e)},RC=p.default.div`width:100%;height:100%;position:fixed;top:0;left:0;z-index:${({$zIndex:e})=>e};visibility:${({$visible:e})=>e?"visible":"hidden"};`,LC=48,OC=2/3,ls=12;function ia({className:e,children:t,isOpened:n,onClick:r,"aria-label":o,"aria-describedby":s,type:a,imageUrl:l,dir:c,animated:d=!0,backgroundColor:m,size:f=LC,hasUnread:g=!1}){const E=Oi(),y=d&&!E,v=Wn(m),b=Math.round(f*OC);return i.createElement($C,{dir:c,id:be.LAUNCHER,className:e,"aria-label":o,"aria-describedby":s,onClick:r,$animated:y,$backgroundColor:m,$prefersReducedMotion:E,$size:f},i.createElement(PC,{$isOpened:n,$animated:y,$fillColor:v,$iconSize:b,$prefersReducedMotion:E},i.createElement(cs.Open,{url:l,isDefaultIcon:a==="default_icon",size:b})),i.createElement(FC,{$isOpened:n,$animated:y,$fillColor:v,$iconSize:b,$prefersReducedMotion:E},i.createElement(cs.Close,{size:b})),g&&i.createElement(UC,null),t)}const NC=D.css`&:hover{transition:transform 250ms cubic-bezier(0.33,0,0,1);transform:scale(1.1);}&:active{transform:scale(0.8);}`,DC=D.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===Mt.WHITE?"grayscale(100%) brightness(2000%)":"grayscale(100%) invert(100%) saturate(0%) brightness(0%) contrast(1000%)"};}}`,aa=D.css`svg{width:${({$iconSize:e})=>e}px;height:${({$iconSize:e})=>e}px;${({$fillColor:e})=>D.css`
|
|
479
479
|
ellipse,
|
|
480
480
|
path {
|
|
481
481
|
fill: ${e};
|
|
@@ -485,7 +485,7 @@
|
|
|
485
485
|
}
|
|
486
486
|
`}
|
|
487
487
|
}
|
|
488
|
-
|
|
488
|
+
`,$C=p.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&&NC}`,la=p.default.span.attrs({"aria-hidden":"true"})`
|
|
489
489
|
position: absolute;
|
|
490
490
|
width: 100%;
|
|
491
491
|
height: 100%;
|
|
@@ -495,23 +495,23 @@
|
|
|
495
495
|
display: flex;
|
|
496
496
|
justify-content: center;
|
|
497
497
|
align-items: center;
|
|
498
|
-
`,
|
|
498
|
+
`,PC=p.default(la)`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)")};${DC}${aa}`,FC=p.default(la)`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)")};${aa}`,UC=p.default.span.attrs({"aria-hidden":"true"})`
|
|
499
499
|
position: absolute;
|
|
500
500
|
top: 1px;
|
|
501
501
|
inset-inline-end: 1px;
|
|
502
|
-
width: ${
|
|
503
|
-
height: ${
|
|
502
|
+
width: ${ls}px;
|
|
503
|
+
height: ${ls}px;
|
|
504
504
|
border-radius: 50%;
|
|
505
505
|
background-color: ${h.themedColor.error};
|
|
506
|
-
`,
|
|
506
|
+
`,cs={Open:e=>e.url?i.createElement("img",{src:e.url,alt:"","data-default-icon":e.isDefaultIcon}):i.createElement(X,{size:e.size,type:"delight"}),Close:({size:e})=>i.createElement(X,{size:e,type:"chevron-down"})};function ca({className:e,size:t,entryPoint:n="Conversation",activeRoute:r}){const{colors:o}=D.useTheme(),{chatSDK:s,config:a,dir:l,state:c}=ae(),{resolveElement:d}=br(),{launcher:m}=oe(),{launcherInfo:f,statsTrackers:g}=ke(),E=a.launcher.unreadBadgeEnabled,y=Ns(),v=fu(s,{enabled:E,opened:c.opened,filter:y}),b=(r??n)==="ConversationList",_={launcher:m.button({isOpened:c.opened,opensConversationList:b})};u.useLayoutEffect(()=>{g.initialRender.setPresentMethod("launcher_toggle")},[g]),HC();const C=()=>{Me(()=>{const w=d(be.WINDOW),M=w?di(w):null;M==null||M.focus()})},x=()=>{Me(()=>{var w;(w=d(be.LAUNCHER))==null||w.focus()})},A=()=>{const w=!c.opened;c.setOpened(w),w?C():x()};return i.createElement(ia,{dir:l,className:e,isOpened:c.opened,onClick:A,type:f.type,imageUrl:f.imageUrl,backgroundColor:o.base.primary,size:t,hasUnread:E&&!c.opened&&v,..._.launcher.props},_.launcher.descriptionNode)}const BC=1e3*60;function HC(){const{chatSDK:e,state:t,logger:n,enableAutoDisconnectInLauncher:r}=ae(),o=u.useRef(null);u.useEffect(()=>{if(!r)return;function s(){o.current&&(clearTimeout(o.current),o.current=null)}function a(){e.connectionState===ue.ConnectionState.CLOSED&&(e.reconnect(),n.debug("useSDKInactivityTimeout: reconnected")),s(),n.debug("useSDKInactivityTimeout: clear disconnect schedule")}function l(){s(),o.current=setTimeout(async()=>{await e.disconnectWebSocket(),n.debug("useSDKInactivityTimeout: disconnected")},BC)}t.opened?a():(l(),n.debug("useSDKInactivityTimeout: schedule disconnect"))},[r,e,t.opened])}const ua=u.createContext(null);function Ur(){const e=u.useContext(ua);if(!e)throw new Error("useNavigator() must be used within <Navigator />");return e}function da({children:e}){const t=Ur();return typeof e=="function"?e(t):i.createElement(i.Fragment,null,e)}const GC=D.keyframes`0%{transform:translateY(40px);opacity:0;}100%{transform:translateY(0px);opacity:1;}`,zC=D.keyframes`0%{transform:translateY(0px);opacity:1;}100%{transform:translateY(40px);opacity:0;}`,VC=D.css`animation-name:${GC};animation-duration:0.3s;animation-fill-mode:forwards;`,YC=D.css``,WC=D.css`animation-name:${zC};animation-duration:0.3s;animation-fill-mode:forwards;`,qC=D.css`visibility:hidden;`,KC=p.default.div`position:absolute;top:0;left:0;width:100%;height:100%;${({$transitionState:e})=>{switch(e){case"entering":return VC;case"entered":return YC;case"exiting":return WC;case"exited":return qC;default:return""}}}${({$active:e})=>e?D.css`
|
|
507
507
|
z-index: 999;
|
|
508
508
|
`:D.css`z-index:1;pointer-events:none;`}
|
|
509
|
-
`;function
|
|
509
|
+
`;function en({initialId:e,children:t}){const[n,r]=u.useState([e]),o=n[n.length-1],s=u.useCallback((b,_)=>{r(C=>[...C,b]),f(C=>({...C,[b]:!0})),_!=null&&_.reset&&v(C=>({...C,[b]:(C[b]||0)+1})),E(C=>({...C,[b]:"entering"})),setTimeout(()=>{E(C=>({...C,[b]:"entered"}))},300)},[]),a=u.useCallback(()=>{r(b=>{if(b.length<=1)return b;const _=b[b.length-1];return E(C=>({...C,[_]:"exiting"})),setTimeout(()=>{E(C=>({...C,[_]:"exited"})),r(C=>C.slice(0,-1))},300),b})},[]),l=u.useMemo(()=>({navigation:{navigate:s,pop:a},activeScreenId:o}),[s,a,o]),c=u.useMemo(()=>u.Children.toArray(t).filter(b=>b.type===da),[t]),d=u.useMemo(()=>{const b={};return c.forEach(_=>{const{id:C,lazy:x,children:A}=_.props;b[C]={lazy:x,element:typeof A=="function"?A(l):A}}),b},[c,l]),[m,f]=u.useState(()=>{const b={};return Object.entries(d).forEach(([_,{lazy:C}])=>{C===!1&&(b[_]=!0)}),b[e]=!0,b}),[g,E]=u.useState(()=>{const b={};return Object.keys(d).forEach(_=>{_===e?b[_]="entered":b[_]="exited"}),b}),[y,v]=u.useState({});return i.createElement(ua.Provider,{value:l},i.createElement(jC,null,Object.keys(d).map(b=>{var A;if(!m[b])return null;const _=g[b]||"exited",C=b===o,x=`${b}-${y[b]||0}`;return i.createElement(KC,{key:x,$transitionState:_,$active:C,"aria-hidden":C?void 0:!0,inert:C?void 0:!0},(A=d[b])==null?void 0:A.element)})))}const jC=p.default.div`position:relative;width:100%;height:100%;`;en.Screen=da;const Ue={conv:"conv",convList:"conv-list"},XC=e=>e===Ue.convList?"ConversationList":"Conversation",us=({isOpened:e,activeScreenId:t})=>e&&t===Ue.conv,ma=({isOpened:e,entryPoint:t,selectedChannelUrl:n,setSelectedChannelUrl:r,onActiveRouteChange:o})=>{const{conversationChildren:s,conversationListChildren:a}=Pr(),[l,c]=u.useState(),d=(()=>{switch(t){case"Conversation":return Ue.conv;case"ConversationList":return Ue.convList;default:return Ue.conv}})(),m=i.createElement(i.Fragment,null,i.createElement(ZC,{onOpenConversationView:(f,g)=>{r(g),c(void 0),f.navigate(Ue.conv)}}),i.createElement(JC,{onActiveRouteChange:o}));return i.createElement(en,{initialId:d},i.createElement(en.Screen,{id:Ue.conv},({navigation:f,activeScreenId:g})=>i.createElement(Ji,{key:n,channelUrl:n,onClearChannelUrl:()=>r(void 0),onNavigateToConversationList:()=>{c(void 0),f.navigate(Ue.convList)},announcementsEnabled:us({isOpened:e,activeScreenId:g}),shouldMarkAsRead:us({isOpened:e,activeScreenId:g}),initialFocusTarget:l},m,s)),i.createElement(en.Screen,{id:Ue.convList,lazy:!0},({navigation:f,activeScreenId:g})=>{const E=e&&g===Ue.convList;return i.createElement(ta,{announcementsEnabled:E,onOpenConversationView:(y,v,b)=>{r(y),c(b==null?void 0:b.initialFocusTarget),f.navigate(Ue.conv)}},m,a)}))},ZC=({onOpenConversationView:e})=>{const{registerOnJoinedProactiveConversation:t}=ke(),{navigation:n}=Ur();return t(({channel:r})=>{e(n,r.url)}),null},JC=({onActiveRouteChange:e})=>{const{activeScreenId:t}=Ur();return u.useEffect(()=>{e==null||e(XC(t))},[t,e]),null},QC=({isExpanded:e,isOpened:t,children:n,launcher:r})=>i.createElement(xr,null,i.createElement(ev,{isExpanded:e,isOpened:t,launcher:r},n)),ev=({isExpanded:e,isOpened:t,children:n,launcher:r})=>{const{dir:o}=ae(),s=u.useRef(null),{hasWindowTitleReference:a,isWindowNameReady:l}=bn();return pn(t,s,{nameReady:l}),i.createElement(tv,null,i.createElement(nv,{ref:s,dir:o,id:be.WINDOW,...Fr(t,a),$isExpanded:e,$isOpened:t},n),r)},tv=p.default.div`display:flex;flex-direction:column;gap:8px;align-items:flex-end;`,nv=p.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&&ov};${({$isExpanded:e})=>e&&rv};`,rv=D.css`width:743px;height:723px;`,ov=D.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;`,sv=u.forwardRef(function({children:e,initialChannelUrl:t,...n},r){const o=Dt(),[s,a]=u.useState(t),[l,c]=u.useState(n.entryPoint??"Conversation"),d=o?sa:QC;return i.createElement($r,{enableExpandButton:!o,ref:r,...n},i.createElement(fi,null,({state:m})=>i.createElement(oa,null,i.createElement(d,{isExpanded:m.expanded,isOpened:m.opened,...o&&{zIndex:"auto"},launcher:i.createElement(ca,{entryPoint:n.entryPoint,activeRoute:l})},i.createElement(ma,{isOpened:m.opened,entryPoint:n.entryPoint,selectedChannelUrl:s,setSelectedChannelUrl:a,onActiveRouteChange:c})),e)))}),{Provider:iv,useContext:Br}=pe("FixedMessengerStyle");function fa(e,t,n,r=0){const{top:o,bottom:s,start:a,end:l}=n;let c="",d="";switch(e){case"start":d=`inset-inline-start: ${Ve(a)}`;break;case"end":d=`inset-inline-end: ${Ve(l)}`;break}switch(t){case"top":c=`top: calc(${Ve(o)} + ${r}px)`;break;case"bottom":c=`bottom: calc(${Ve(s)} + ${r}px)`;break}return D.css`${c};${d};`}function av(e){const{horizontal:t,vertical:n,margin:r,launcherSize:o}=Br();return i.createElement(lv,{...e,size:o,$horizontal:t,$vertical:n,$margin:r})}const lv=p.default(ca)`position:fixed;z-index:${it.LAUNCHER};${({$horizontal:e,$vertical:t,$margin:n})=>fa(e,t,n)};`,cv=({isExpanded:e,isOpened:t,children:n})=>i.createElement(xr,null,i.createElement(uv,{isExpanded:e,isOpened:t},n)),uv=({isExpanded:e,isOpened:t,children:n})=>{const{dir:r}=ae(),{horizontal:o,vertical:s,margin:a,launcherSize:l}=Br(),c=u.useRef(null),{hasWindowTitleReference:d,isWindowNameReady:m}=bn();return pn(t,c,{nameReady:m}),i.createElement(dv,{ref:c,dir:r,id:be.WINDOW,...Fr(t,d),$isExpanded:e,$isOpened:t,$horizontal:o,$vertical:s,$margin:a,$launcherSize:l},n)},dv=p.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})=>fa(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}`};
|
|
510
510
|
[dir='rtl'] &:not([dir='ltr']),
|
|
511
511
|
&[dir='rtl'] {
|
|
512
512
|
transform-origin: ${({$horizontal:e,$vertical:t})=>`${e==="start"?"right":"left"} ${t}`};
|
|
513
513
|
}
|
|
514
514
|
|
|
515
|
-
${({$isOpened:e})=>e&&
|
|
516
|
-
${({$isExpanded:e})=>e&&
|
|
517
|
-
`,
|
|
515
|
+
${({$isOpened:e})=>e&&fv};
|
|
516
|
+
${({$isExpanded:e})=>e&&mv};
|
|
517
|
+
`,mv=D.css`width:743px;height:723px;`,fv=D.css`z-index:${it.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;`,ga={top:24,bottom:24,start:24,end:24},gv=u.forwardRef(function({children:e,initialChannelUrl:t,...n},r){const[o,s]=u.useState(t),[a,l]=u.useState(n.entryPoint??"Conversation"),[c,d]=u.useState("end-bottom"),[m,f]=u.useState(ga),[g,E]=u.useState(48),y=Dt(),v=y?sa:cv,{horizontal:b,vertical:_}=u.useMemo(()=>{const[C,x]=c.split("-");return{horizontal:C==="start"?"start":"end",vertical:x==="top"?"top":"bottom"}},[c]);return i.createElement($r,{enableExpandButton:!y,ref:r,...n},i.createElement(fi,null,({state:C})=>i.createElement(iv,{value:{horizontal:b,vertical:_,margin:m,launcherSize:g,setPosition:d,setMargin:f,setLauncherSize:E}},i.createElement(oa,null,i.createElement(v,{isExpanded:C.expanded,isOpened:C.opened},i.createElement(ma,{isOpened:C.opened,entryPoint:n.entryPoint,selectedChannelUrl:o,setSelectedChannelUrl:s,onActiveRouteChange:l})),i.createElement(av,{entryPoint:n.entryPoint,activeRoute:a}),e))))}),hv=e=>{var o,s,a,l;const{setPosition:t,setMargin:n,setLauncherSize:r}=Br();return u.useLayoutEffect(()=>{e.position&&t(e.position),e.margin&&n({...ga,...e.margin}),e.launcherSize&&r(e.launcherSize)},[e.position,(o=e.margin)==null?void 0:o.top,(s=e.margin)==null?void 0:s.bottom,(a=e.margin)==null?void 0:a.start,(l=e.margin)==null?void 0:l.end,e.launcherSize]),null},pv=({children:e})=>{const{setConversationChildren:t}=Pr();return u.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},_v=({children:e})=>{const{setConversationListChildren:t}=Pr();return u.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},Ev=Object.assign(gv,{Style:hv,ConversationChildren:pv,ConversationListChildren:_v}),bv=e=>{const{refreshActiveChannel:t}=ke(),[n,r]=u.useState(!1),o=u.useRef(null),s=u.useRef(null);return u.useEffect(()=>{n&&t().then(()=>{var a;(a=o.current)==null||a.call(o),r(!1)}).catch(a=>{var l;(l=s.current)==null||l.call(s,a),r(!1)})},[n]),u.useCallback(()=>new Promise((a,l)=>{o.current=a,s.current=l,e().then(()=>r(!0)).catch(l)}),[e])};Is.set(ue.SendbirdPlatform.JS,{deviceOSPlatform:La()?ue.DeviceOsPlatform.MOBILE_WEB:ue.DeviceOsPlatform.WEB,messengerVersion:nd,keyValueStorage:od(),networkStateAdapter:rd()});exports.ANCHOR_REL=Er;exports.AgentProviderContainer=$r;exports.AgentUIProviderContainer=na;exports.AnonymousSessionInfo=zn;exports.CSATType=qe;exports.Commands=Qe;exports.ConnectionDelayLayout=_n;exports.Conversation=Ji;exports.ConversationContext=Um;exports.ConversationContextProvider=Ei;exports.ConversationHeaderLayout=lt;exports.ConversationLayout=An;exports.ConversationList=ta;exports.ConversationListContext=Yb;exports.ConversationListContextProvider=ea;exports.ConversationListHeaderLayout=bt;exports.ConversationListItemLayout=Dr;exports.ConversationListLayout=xn;exports.DefaultMessenger=sv;exports.DeskTicketPriority=ur;exports.DeskTicketStatus=cr;exports.FixedMessenger=Ev;exports.ID_INCOMING=Ke;exports.IncomingMessageLayout=rt;exports.LauncherBase=ia;exports.LogLevel=sr;exports.ManualSessionInfo=Cs;exports.MessageListUILayout=Sn;exports.MessageLogs=Vi;exports.OutgoingMessageLayout=Pt;exports.PlaceholderLayout=yn;exports.SystemMessageLayout=Cn;exports.cssVars=h;exports.escapeMarkdownSyntax=ka;exports.flattenObject=ul;exports.mapCommonStringsToReactFormat=ei;exports.messengerDispatcher=ra;exports.noop=ce;exports.parseToMessageTemplate=xs;exports.parseToUITemplate=ll;exports.pickColorByTheme=cl;exports.replaceVariablesAsync=ml;exports.replaceVariablesSync=dl;exports.useAIAgentContext=Re;exports.useConversationContext=Se;exports.useConversationListContext=Ft;exports.useLocalizationContext=se;exports.useMessageTemplateFetchingContext=$c;exports.useMessengerContext=ae;exports.useMessengerSessionContext=ke;exports.useMessengerThemeContext=ii;exports.useRefreshActiveChannel=bv;
|