@sendbird/ai-agent-messenger-react 1.21.0 → 1.21.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +47 -47
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1100 -1093
- package/package.json +4 -4
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var Ks=Object.defineProperty;var js=(e,t,n)=>t in e?Ks(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var C=(e,t,n)=>js(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Z=require("@sendbird/chat"),u=require("react"),w=require("styled-components"),Fe=require("date-fns"),Ys=require("date-fns/locale/en-US"),ee=require("@sendbird/chat/aiAgent"),ke=require("@sendbird/chat/message"),tt=require("@sendbird/chat/groupChannel"),Le=require("@sendbird/uikit-tools"),Xs=require("react-dom"),Zs=require("date-fns/isSameDay"),an=require("@sendbird/react-uikit-message-template-view"),Js=require("@sendbird/uikit-message-template"),Qs=require("dompurify"),eo=require("@emotion/is-prop-valid"),Rt=e=>e&&e.__esModule?e:{default:e};function to(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 no=Rt(Z),o=to(u),h=Rt(w),Dr=Rt(Qs),ro=Rt(eo),Ke="sb-agent",Nr="KEY_IMG_ASPECT_RATIO",ln="*/*",H={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},fe=e=>!!e&&"sender"in e,so=e=>fe(e)?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId),oo=(e,t,n,r=!0)=>{if(!r||!fe(e))return"single";const s=()=>{if(!t||!fe(t))return!1;const c=t.sender.userId===e.sender.userId,d=Fe.isSameMinute(t.createdAt,e.createdAt);return c&&d},a=()=>{if(!n||!fe(n))return!1;const c=n.sender.userId===e.sender.userId,d=Fe.isSameMinute(n.createdAt,e.createdAt);return c&&d},i=s(),l=a();return i&&l?"middle":i?"bottom":l?"top":"single"},rt=(e,t)=>(()=>{var r;return fe(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)},isIncoming:(e,t)=>fe(e)&&e.sender.userId!==t,isOutgoing:(e,t)=>fe(e)&&(e.sender.userId===t||e.sendingStatus===ke.SendingStatus.PENDING)},we=e=>e.startsWith("image/"),Pr=e=>e.startsWith("video/"),vn=(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"},Fr=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},yn=e=>{switch(e){case"top":case"middle":return H.GAP_GROUPED;default:return H.GAP_UNGROUPED}},ao=(e,t)=>{const n=/```(\w+)?\n([\s\S]*?)```/g,r=[];let s=0;return e.replace(n,(a,...i)=>{const[l,c,d]=i;return s<d&&r.push({type:"text",value:e.slice(s,d).trim()}),r.push({type:"code",value:c.trim(),language:l?l.trim():"plaintext"}),s=d+a.length,a}),s<e.length&&r.push({type:"text",value:e.slice(s).trim()}),t?r.map(a=>a.type!=="text"?a:{...a,value:t(a.value)}):r},io=e=>e.replace(/\[([^\]]+)\](?!\()/g,"\\[$1\\]"),lo=e=>e.replace(/([a-zA-Z0-9])_(?=[a-zA-Z0-9])/g,"$1\\_"),co=e=>e.replace(/~~/g,"\\~\\~"),uo=e=>{let t=e;return t=io(t),t=lo(t),t=co(t),t},mo=typeof navigator<"u"&&navigator.product==="ReactNative",Kn=(e,t)=>{const n=r=>!t||t.length===0?!0:fe(r)&&t.includes(r.sendingStatus);return mo?e.find(n):e.findLast(n)};function Ce(){}function ho(){const e=typeof navigator<"u"?navigator.userAgent:"",t=/iPad|iPhone|iPod/.test(e),n=/Android/.test(e);return t||n}function go(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 cn=e=>{try{return JSON.parse(e===""?"{}":e)}catch{return{}}},Me={isStreaming(e){const t=cn(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(rt(e,t)){const r=cn(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)}},Xt=`@${Ke}`,fo=({appId:e,aiAgentId:t,storage:n})=>{const r={templateBase:`${Xt}-template`,template:s=>`${r.templateBase}/templates/${s}`,templateToken:()=>`${r.templateBase}/tokens`,messengerSession:s=>{const a=go(`${e}/${t}/${s}`);return`${Xt}-udata/${a}`},anonUserSession:()=>`${Xt}-session/${e}/${t}`};return{template:{set:(s,a)=>n.set(r.template(s),a),get:s=>n.get(r.template(s)),setCachedToken:s=>n.set(r.templateToken(),s),getCachedToken:()=>n.get(r.templateToken()),clear:()=>{n.getKeys(r.templateBase).forEach(n.delete)}},messenger:{getSettings:s=>{try{const a=n.get(r.messengerSession(s));return a?JSON.parse(a):null}catch{return null}},setSettings:(s,a)=>{try{delete a.auto_created_user;const i=JSON.stringify(a);n.set(r.messengerSession(s),i)}catch{return}},getAnonUser:()=>{try{const s=n.get(r.anonUserSession());return s?JSON.parse(s):null}catch{return null}},setAnonUser:s=>{try{const a=JSON.stringify(s);n.set(r.anonUserSession(),a)}catch{return}},clear:s=>{try{s&&n.delete(r.messengerSession(s)),n.delete(r.anonUserSession())}catch{return}}}}},Br=(e,t,n={})=>{let r=null,s=null,a=null;const{leading:i=!0,trailing:l=!0}=n,c=(...d)=>{const m=Date.now();if(a===null||m-a>=t)i?(e(...d),a=m):(s=d,a=m);else if(s=d,l&&!r){const p=t-(m-a);r=setTimeout(()=>{s&&l&&(e(...s),a=Date.now()),r=null,s=null},p)}};return c.cancel=()=>{r&&(clearTimeout(r),r=null),s=null,a=null},c};class Ur{constructor(t,{filter:n,limit:r=20}){C(this,"filter");C(this,"_sdk");C(this,"_pinnedChannels");C(this,"_channels");C(this,"_isDisposed",!1);C(this,"_handlerId",`handler-id-${Date.now()}`);C(this,"_order",tt.GroupChannelListOrder.LATEST_LAST_MESSAGE);C(this,"_limit");C(this,"_query");C(this,"_token");C(this,"_timestamp");C(this,"_isSyncing");C(this,"_channelHandler");C(this,"_connectionHandler");C(this,"_collectionEventHandler");C(this,"_throttledOnChannelChanged");var s,a,i,l,c,d,m;this.filter=n,this._sdk=t,this._pinnedChannels=[],this._channels=[],this._limit=r,this._query=this._sdk.aiAgent.createMyGroupChannelListQuery({aiAgentChannelFilter:(s=this.filter)==null?void 0:s.aiAgentChannelFilter,aiAgentConversationStatusFilter:(a=this.filter)==null?void 0:a.aiAgentConversationStatusFilter,aiAgentIds:(i=this.filter)==null?void 0:i.aiAgentIds,deskChannelFilter:(l=this.filter)==null?void 0:l.deskChannelFilter,pinnedChannelUrls:(c=this.filter)==null?void 0:c.pinnedChannelUrls,copilotConversationOnly:(d=this.filter)==null?void 0:d.copilotConversationOnly,copilotSupportChannelUrl:(m=this.filter)==null?void 0:m.copilotSupportChannelUrl,limit:this._limit}),this._token="",this._timestamp=Number.MAX_SAFE_INTEGER,this._isSyncing=!1,this._throttledOnChannelChanged=Br(p=>{this._query.belongsTo(p)?this._addChannelsToView([p],!1):this._removeChannelsFromView([p.url])},250,{trailing:!1,leading:!0}),this._channelHandler=new tt.GroupChannelHandler({onChannelChanged:p=>{p.isGroupChannel()&&this._throttledOnChannelChanged(p)},onChannelDeleted:p=>{this._removeChannelsFromView([p])}}),this._connectionHandler=new Z.ConnectionHandler({onReconnectSucceeded:()=>{this._isDefaultChangelogSyncTimestampUpdated&&this._syncChannelChangelogs()}}),this._sdk.addConnectionHandler(this._handlerId,this._connectionHandler),this._sdk.groupChannel.addGroupChannelHandler(this._handlerId,this._channelHandler)}get _isDefaultChangelogSyncTimestampUpdated(){return this._timestamp!==Number.MAX_SAFE_INTEGER}_setDefaultChangelogsSyncTimestamp(t){var a,i;const n=new Set(((a=this.filter)==null?void 0:a.pinnedChannelUrls)??[]),r=t.find(l=>!n.has(l.url));let s;r?s=((i=r.lastMessage)==null?void 0:i.createdAt)??r.createdAt:s=this._query.lastResponseAt,this._timestamp>s&&(this._timestamp=s)}async _syncChannelChangelogs(){if(this._isDisposed)return[];if(this._isSyncing)return[];try{this._isSyncing=!0;let t;for(this._token?t=await this._sdk.aiAgent.getMyGroupChannelChangeLogsByToken(this._token,this.filter):t=await this._sdk.aiAgent.getMyGroupChannelChangeLogsByTimestamp(this._timestamp,this.filter),this._token=t.token,this._addChannelsToView(t.updatedChannels),this._removeChannelsFromView(t.deletedChannelUrls);t.hasMore&&t.token;)t=await this._sdk.aiAgent.getMyGroupChannelChangeLogsByToken(this._token,this.filter),this._token=t.token,this._addChannelsToView(t.updatedChannels),this._removeChannelsFromView(t.deletedChannelUrls)}catch{}finally{this._isSyncing=!1}return[]}_upsertPinnedChannelsToArray(t){var l;const n=((l=this.filter)==null?void 0:l.pinnedChannelUrls)??[],r=new Map(n.map((c,d)=>[c,d])),s=[],a=[],i=[];for(const c of t){if(!this._query.belongsTo(c)){i.push(c.url);continue}const d=r.get(c.url);if(d===void 0)continue;const m=un(this._pinnedChannels,c);m>=0?(this._pinnedChannels.splice(m,1),a.push(c)):s.push(c);const E=this._pinnedChannels.findIndex(x=>(r.get(x.url)??1/0)>d),v=E===-1?this._pinnedChannels.length:E;this._pinnedChannels.splice(v,0,c)}return{addedChannels:s,updatedChannels:a,unmatchedChannelUrls:i}}_upsertRegularChannelsToArray(t,n=!1){const r=[],s=[],a=[];for(const i of t){if(!this._query.belongsTo(i)){r.push(i.url);continue}const l=un(this._channels,i),c=l<0;!c&&this._channels.splice(l,1);const m=po(this._channels,i,this._order).place,p=m===this._channels.length;c?p?(n||!this.hasMore)&&(this._channels.push(i),s.push(i)):(this._channels.splice(m,0,i),s.push(i)):(this._channels.splice(m,0,i),a.push(i))}return{addedChannels:s,updatedChannels:a,unmatchedChannelUrls:r}}_addChannelsToView(t,n=!1){var p,E,v,x,b;const r=new Set(((p=this.filter)==null?void 0:p.pinnedChannelUrls)??[]),s=[],a=[];for(const g of t)r.has(g.url)?s.push(g):a.push(g);const i=this._upsertPinnedChannelsToArray(s),l=this._upsertRegularChannelsToArray(a,n),c=i.addedChannels.concat(l.addedChannels),d=i.updatedChannels.concat(l.updatedChannels),m=i.unmatchedChannelUrls.concat(l.unmatchedChannelUrls);c.length>0&&((v=(E=this._collectionEventHandler)==null?void 0:E.onChannelsAdded)==null||v.call(E,{},c)),d.length>0&&((b=(x=this._collectionEventHandler)==null?void 0:x.onChannelsUpdated)==null||b.call(x,{},d)),m.length>0&&this._removeChannelsFromView(m)}_removeChannelsFromView(t){var s,a,i;const n=new Set(((s=this.filter)==null?void 0:s.pinnedChannelUrls)??[]),r=[];for(const l of t)if(n.has(l)){const c=this._pinnedChannels.findIndex(d=>d.url===l);c>=0&&(r.push(l),this._pinnedChannels.splice(c,1))}else{const c=this._channels.findIndex(d=>d.url===l);c>=0&&(r.push(l),this._channels.splice(c,1))}r.length>0&&((i=(a=this._collectionEventHandler)==null?void 0:a.onChannelsDeleted)==null||i.call(a,{},r))}get channels(){return this._isDisposed?[]:[...this._pinnedChannels,...this._channels]}get hasMore(){return this._isDisposed?!1:this._query.hasNext}async loadMore(){if(this._isDisposed)return[];if(this.hasMore){const t=await this._query.next();return this._setDefaultChangelogsSyncTimestamp(t),this._addChannelsToView(t,!0),t}return[]}setConversationListCollectionHandler(t){this._collectionEventHandler=t}dispose(){this._isDisposed||(this._isDisposed=!0,this._throttledOnChannelChanged.cancel(),this._collectionEventHandler=void 0,this._sdk.removeConnectionHandler(this._handlerId),this._sdk.groupChannel.removeGroupChannelHandler(this._handlerId),this._pinnedChannels.length=0,this._channels.length=0)}}const un=(e,t)=>e.findIndex(n=>n.isIdentical(t)),po=(e,t,n)=>{if(e.length>0){const r=un(e,t);let s=0,a=e.length-1,i=Math.floor((s+a)/2);for(;s<a;){const c=jn(e[i],t,n);if(c>0)a=i,i=Math.floor((s+a)/2);else if(c<0)s=i+1,i=Math.floor((s+a)/2);else return{place:i,oldPosition:r}}return{place:jn(e[i],t,n)>=0?i:i+1,oldPosition:r}}return{place:e.length,oldPosition:-1}},jn=(e,t,n)=>{switch(n){case tt.GroupChannelListOrder.LATEST_LAST_MESSAGE:if(e.lastMessage&&t.lastMessage){const r=t.lastMessage.createdAt-e.lastMessage.createdAt;return r===0?t.createdAt-e.createdAt:r}else return e.lastMessage?-1:t.lastMessage?1:t.createdAt-e.createdAt;default:return 0}};class Hr{constructor(t){C(this,"subscribers",{});this.logger=t}async send(t){const n=Eo(),r=this.subscribers[t.type];if(r){this.logger.debug(`messenger.dispatcher: dispatching command: ${t.type}`,t.payload);const s=r.map(a=>a(t.payload));await Promise.all(s).catch(a=>{this.logger.error(`messenger.dispatcher: error in callback for command: ${t.type}`,a)})}return n.resolve(),n.promise}subscribe(t,n){this.subscribers[t]||(this.subscribers[t]=[]),this.subscribers[t].push(n)}unsubscribe(t,n){const r=this.subscribers[t];r&&(this.subscribers[t]=r.filter(s=>s!==n))}}const Eo=()=>{let e=Ce,t=Ce;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}};var ce=(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))(ce||{});class st{constructor(t={}){C(this,"payload");this.payload=t}toJSON(){return JSON.stringify({type:this.type,payload:this.payload})}}const Be={CloseConversation:e=>new bo(e),MessengerSettingsUpdated:e=>new _o(e),ActiveChannelUpdated:e=>new Co(e),AnonymousSessionTokenExpired:()=>new xo,AuthTokenRefreshed:()=>new vo};class bo extends st{constructor(){super(...arguments);C(this,"type","conv.close")}}class _o extends st{constructor(){super(...arguments);C(this,"type","messenger.settings.updated")}}class Co extends st{constructor(){super(...arguments);C(this,"type","active.channel.updated")}}class xo extends st{constructor(){super(...arguments);C(this,"type","anon.token.expired")}}class vo extends st{constructor(){super(...arguments);C(this,"type","auth.token.refreshed")}}var Sn=(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))(Sn||{});class Vr{constructor(t){C(this,"level");this.level=t}verbose(...t){this.level<=0&&console.log(`[${Ke}/verbose]`,...t)}debug(...t){this.level<=1&&console.log(`[${Ke}/debug]`,...t)}info(...t){this.level<=2&&console.log(`[${Ke}/info]`,...t)}warn(...t){this.level<=3&&console.warn(`[${Ke}/warn]`,...t)}error(...t){this.level<=4&&console.error(`[${Ke}/error]`,...t)}}class zr{constructor({userId:t,authToken:n,sessionHandler:r}){C(this,"userId");C(this,"authToken");C(this,"sessionHandler");this.userId=t,this.authToken=n,this.sessionHandler=r}}class dn{constructor(){C(this,"userId");C(this,"authToken");C(this,"sessionHandler")}}const yo=e=>({onSessionTokenRequired:t=>{t(null),e.send(Be.AnonymousSessionTokenExpired())}}),So="ai_agent:stats",Ao="conversation_initial_render",To=800220;var X=(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))(X||{});class Io{constructor(){C(this,"timers",new Map);C(this,"committed",!1);C(this,"commitCallback",null);C(this,"conversationId",null);C(this,"channelUrl",null);C(this,"errorCode",null);C(this,"errorDescription",null);C(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??To,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(So,t)):!1}}class wo extends Io{constructor(){super(...arguments);C(this,"presentMethod","direct_present")}setPresentMethod(n){return this.presentMethod=n,this}getMetricKey(){return Ao}buildPayload(){const n=this.getDuration(X.AUTH),r=this.getDuration(X.GET_CHANNEL),s=this.getDuration(X.GET_MESSAGES),a=this.getDuration(X.TOTAL_DURATION_FROM_CACHE),i=this.getDuration(X.TOTAL_DURATION),l={...this.extraData,present_method:this.presentMethod,...n!==null&&{auth_duration:n},...r!==null&&{get_channel_duration:r},...s!==null&&{get_messages_duration:s},...a!==null&&{total_duration_from_cache:a}},c={key:this.getMetricKey(),value:i!==null?String(i):"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 ko{constructor(t){C(this,"commitCallback");C(this,"presentMethod","direct_present");C(this,"stats",null);this.commitCallback=t}getOrCreateStats(){return(!this.stats||this.stats.isCommitted())&&(this.stats=new wo().setCommitCallback(this.commitCallback).setPresentMethod(this.presentMethod)),this.stats}onAuthStart(){this.getOrCreateStats().startTimer(X.TOTAL_DURATION).startTimer(X.TOTAL_DURATION_FROM_CACHE).startTimer(X.AUTH)}onAuthComplete(){var t;(t=this.stats)==null||t.stopTimer(X.AUTH)}onAuthError(t){this.stats&&!this.stats.isCommitted()&&this.stats.stopTimer(X.AUTH).setError(t instanceof Z.SendbirdError?t.code:void 0,t.message).stopTimer(X.TOTAL_DURATION).commit()}onGetChannelStart(){var t;(t=this.stats)==null||t.startTimer(X.GET_CHANNEL)}onGetChannelComplete(t){this.stats&&(this.stats.stopTimer(X.GET_CHANNEL),t!==void 0&&this.stats.setConversationId(t),this.stats.startTimer(X.GET_MESSAGES))}onGetChannelError(t){this.stats&&!this.stats.isCommitted()&&this.stats.stopTimer(X.GET_CHANNEL).setError(t instanceof Z.SendbirdError?t.code:void 0,t.message).stopTimer(X.TOTAL_DURATION).commit()}onCacheResult(t){this.stats&&!this.stats.isCommitted()&&(t&&this.stats.setError(t instanceof Z.SendbirdError?t.code:void 0,t.message),this.stats.stopTimer(X.TOTAL_DURATION_FROM_CACHE))}onApiResult(t){this.stats&&!this.stats.isCommitted()&&(t&&this.stats.setError(t instanceof Z.SendbirdError?t.code:void 0,t.message),this.stats.stopTimer(X.TOTAL_DURATION).stopTimer(X.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 Mo(){let e=null,t=0;const n=(r,s)=>{if((e==null?void 0:e.key)===r)return e.promise;const a=++t,l=(e?e.promise.catch(()=>{}).then(()=>s()):s()).finally(()=>{(e==null?void 0:e.id)===a&&(e=null)});return e={key:r,id:a,promise:l},l};return n.isPending=()=>e!==null,n}const Ie={conversation:{isTalkToAgentViewEnabled:!0,scrollMode:"auto",newMessageIndicatorEnabled:!0,senderAvatarEnabled:!0,messageAlertSoundEnabled:!1,header:{avatarEnabled:!0},input:{camera:{photoEnabled:!0},gallery:{photoEnabled:!0},fileEnabled:!0},fileViewer:{downloadEnabled:!0}}},Yn=e=>{var t,n,r,s,a,i,l,c,d,m,p,E,v,x;return e?{...Ie,...e,conversation:{...Ie.conversation,...e==null?void 0:e.conversation,header:{...(t=Ie.conversation)==null?void 0:t.header,...(n=e==null?void 0:e.conversation)==null?void 0:n.header},input:{...(r=Ie.conversation)==null?void 0:r.input,...(s=e==null?void 0:e.conversation)==null?void 0:s.input,camera:{...(i=(a=Ie.conversation)==null?void 0:a.input)==null?void 0:i.camera,...(c=(l=e==null?void 0:e.conversation)==null?void 0:l.input)==null?void 0:c.camera},gallery:{...(m=(d=Ie.conversation)==null?void 0:d.input)==null?void 0:m.gallery,...(E=(p=e==null?void 0:e.conversation)==null?void 0:p.input)==null?void 0:E.gallery}},fileViewer:{...(v=Ie.conversation)==null?void 0:v.fileViewer,...(x=e==null?void 0:e.conversation)==null?void 0:x.fileViewer}}}:Ie},ue=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")},An=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 Ue(e){var n,r,s;return typeof(((n=e==null?void 0:e.conversation)==null?void 0:n.handedOverAt)??((s=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff)==null?void 0:s.timestamp))=="number"}function $o(e){var r;const t=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff;return t?typeof t.requestedAt=="number"&&!Ue(e):!1}function Lo(e){var t;if(((t=e==null?void 0:e.resolution)==null?void 0:t.determinedBy)==="user")return e.resolution.isResolved}function Xn(e){return!!e&&e<Date.now()}function Ro(e){return!e.title}function Oo(e,t){var n;if(e)return Ro(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 Do{constructor(){C(this,"_channelHandlerId",null);C(this,"_connectionHandlerId",null);C(this,"_handleActiveChannelChangedThrottled",null);C(this,"_setupChannelHandler",()=>{const t=Date.now();this._channelHandlerId=`aiagent_channel_${t}`,this._connectionHandlerId=`aiagent_connection_${t}`,this._handleActiveChannelChangedThrottled=Br(s=>{var a,i;(i=this._session)==null||i._updateActiveChannel({url:s.url,status:ue(s)?"closed":"open",conversationStatus:(a=s.conversation)==null?void 0:a.status}),this._logger.debug("AIAgentEventManager: activeChannel updated",s.url)},250,{leading:!0,trailing:!1});const n=new tt.GroupChannelHandler({onChannelChanged:s=>{var a,i;s.isGroupChannel()&&s.url===((a=this._session)==null?void 0:a.activeChannel.url)&&((i=this._handleActiveChannelChangedThrottled)==null||i.call(this,s))}}),r=new Z.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})});C(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")});C(this,"_syncActiveChannelOnReconnect",async()=>{var n,r,s;const t=(n=this._session)==null?void 0:n.activeChannel.url;if(t)try{const i=await(await this._chatClient.chatSDK.groupChannel.getChannel(t)).refresh();i.url===t&&((s=this._session)==null||s._updateActiveChannel({url:i.url,status:ue(i)?"closed":"open",conversationStatus:(r=i.conversation)==null?void 0:r.status}),this._logger.debug("AIAgentEventManager: activeChannel synced on reconnect",i.url))}catch(a){this._logger.error("AIAgentEventManager: failed to sync activeChannel on reconnect",a)}});C(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)}});C(this,"onMessengerSettingsUpdated",t=>(this._dispatcher.subscribe(ce.MessengerSettingsUpdated,t),()=>{this._dispatcher.unsubscribe(ce.MessengerSettingsUpdated,t)}));C(this,"onActiveChannelUpdated",t=>(this._dispatcher.subscribe(ce.ActiveChannelUpdated,t),()=>{this._dispatcher.unsubscribe(ce.ActiveChannelUpdated,t)}));C(this,"onAuthTokenRefreshed",t=>(this._dispatcher.subscribe(ce.AuthTokenRefreshed,t),()=>{this._dispatcher.unsubscribe(ce.AuthTokenRefreshed,t)}))}}class No{constructor(t){C(this,"_sdkUser");C(this,"_userSession");C(this,"_dispatcher");C(this,"_activeChannel");C(this,"_updateActiveChannel",t=>{this._activeChannel=t,this._dispatcher.send(Be.ActiveChannelUpdated({channelUrl:t.url,status:t.status,conversationStatus:t.conversationStatus}))});C(this,"_updateAuthToken",t=>{this._userSession.authToken=t,this._dispatcher.send(Be.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 Gr=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)}},ot=e=>JSON.parse(e),Ot=e=>JSON.parse(e);function Po(e,t){const[n,r]=t.split(",").map(s=>s.trim());return e==="dark"&&r||n}function Fo(e){const t={};function n(r,s=""){for(const[a,i]of Object.entries(r)){const l=s?`${s}.${a}`:a;i&&typeof i=="object"&&!Array.isArray(i)?n(i,l):t[l]=i}}return n(e),t}function Tn({template:e,variables:t,variableKeyPattern:n,variableValueTransformer:r}){return Object.entries(t).reduce((s,[a,i])=>{if(!r&&!["number","boolean","string"].includes(typeof i))throw new Error(`If transformer is not provided, value(${a}:${i}) must be a {string, number, or boolean}`);const l=r?r(i):String(i),c=n(a);return s.replace(c,Gr(l))},e)}async function Bo({template:e,variables:t,variableKeyPattern:n,variableValueTransformer:r}){return(await Promise.all(Object.entries(t).map(async([a,i])=>{const l=await r(i);return{regex:n(a),transformedValue:l}}))).reduce((a,{regex:i,transformedValue:l})=>a.replace(i,Gr(l)),e)}var mn=(e=>(e[e.EXTERNAL_AUTH_TOKEN_EXPIRED=1]="EXTERNAL_AUTH_TOKEN_EXPIRED",e))(mn||{});const qr=e=>typeof e=="object"&&e!==null,Zn=(e,t)=>t in e&&typeof e[t]=="string"&&e[t]!=="",Uo=e=>!qr(e)||!Zn(e,"channel_url")||!Zn(e,"ai_agent_id")?null:{channelUrl:e.channel_url,aiAgentId:e.ai_agent_id},Ho={1:Uo};function Vo(e){if(!qr(e)||!("cat"in e)||typeof e.cat!="number"||!("data"in e))return null;const t=e.cat,n=Ho[t];if(!n)return null;const r=n(e.data);return r?{category:t,data:r}:null}function zo(e,t,n,r){const s=no.default.init({appId:e,modules:[new tt.GroupChannelModule,new ee.AIAgentModule],localCacheEnabled:!0,options:new Z.SendbirdChatOptions({typingIndicatorInvalidateTime:2e4}),...r});return s.addSendbirdExtensions([{version:n,product:Z.SendbirdProduct.AI_AGENT,platform:t.platform}],{platform:t.deviceOSPlatform,version:t.deviceOSVersion},t.customData)||console.warn("Invalid Sendbird Extensions",t),s}function Go(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 qo=[400300,400301,400302,400310];class In{constructor(t,n,r){C(this,"chatSDK");C(this,"_logger");C(this,"_cache");C(this,"connect",async(t,n,r,s)=>{if(this._logger.debug("ChatClient.connect: start",t.userId),n){const a=new Z.SessionHandler({...n,onSessionTokenRequired:this._interceptTokenRefresh(n.onSessionTokenRequired,r,s)});this.chatSDK.setSessionHandler(a),this.chatSDK.aiAgent.addEventHandler(mn.EXTERNAL_AUTH_TOKEN_EXPIRED.toString(),i=>{var c;this._logger.debug("ChatClient.connect: EXTERNAL_AUTH_TOKEN_EXPIRED event received",i);const l=Vo(i);(l==null?void 0:l.category)===mn.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(a){const i=a;if(this.chatSDK.isCacheEnabled){if(this._isCacheRestrictedError(i))this._logger.warn("ChatClient.connect","offline connect restricted",i.message,i.code),this._logger.warn("ChatClient.connect","clear cached-data"),await this.chatSDK.clearCachedData().catch(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",i.message,i.code),i}});C(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")});C(this,"getChannel",async t=>this.chatSDK.groupChannel.getChannel(t));C(this,"patchContext",async(t,n,r)=>this.chatSDK.aiAgent.patchContext(t,n,r));C(this,"updateContext",async(t,n,r)=>this.chatSDK.aiAgent.updateContext(t,n,r));C(this,"requestMessengerSettings",async t=>{var s;if(t.userId===""){const a=new Error("userId cannot be empty string for messenger settings request");throw this._logger.error("ChatClient.requestMessengerSettings: invalid userId",a),a}const n={...t,shouldSendFirstMessage:!1};this._logger.debug("ChatClient.requestMessengerSettings: requesting",n);const r=await this.chatSDK.aiAgent.requestMessengerSettings(n);return this._logger.debug("ChatClient.requestMessengerSettings: received",(s=r.active_channel)==null?void 0:s.channel_url),r});C(this,"_interceptTokenRefresh",(t,n,r)=>{if(t)return async(s,a)=>{new Promise((i,l)=>t==null?void 0:t(i,l)).then(i=>{i?n==null||n(i):r==null||r(),s(i)}).catch(i=>{r==null||r(),a(i)})}});C(this,"_isCacheRestrictedError",t=>qo.some(n=>t.code===n));C(this,"_syncTemplatesIfNeeded",async()=>{var r,s;const t=(s=(r=this.chatSDK.appInfo)==null?void 0:r.aiAgentInfo)==null?void 0:s.templateListToken;if(!t)return;const n=this._cache.template.getCachedToken();if(!(n&&n===t)){this._logger.debug("ChatClient._syncTemplatesIfNeeded: syncing templates");try{const{templates:a,token:i}=await this.chatSDK.aiAgent.getMessageTemplates({limit:20});for(const{template:l}of a){const{key:c}=ot(l);this._cache.template.set(c,l)}this._cache.template.setCachedToken(i),this._logger.debug("ChatClient._syncTemplatesIfNeeded: sync completed")}catch(a){this._logger.error("ChatClient._syncTemplatesIfNeeded: error",a)}}});this.chatSDK=t,this._logger=n,this._cache=r}static init(t){let n;return t.chatSDK?(Go(t.chatSDK),n=t.chatSDK):n=zo(t.appId,t.extensions,t.messengerVersion,t.chatParams),new In(n,t.logger,t.cache)}}const ft=new Map,Wr={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]}}},Wo=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0));class Jn extends Error{constructor(n,r){const s=(r==null?void 0:r.detail)??"";super(s||`Desk API error (${n})`);C(this,"status");C(this,"code");C(this,"detail");this.name="DeskApiError",this.status=n,this.code=(r==null?void 0:r.code)??"",this.detail=s}}var wn=(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))(wn||{}),kn=(e=>(e.URGENT="URGENT",e.HIGH="HIGH",e.MEDIUM="MEDIUM",e.LOW="LOW",e))(kn||{}),Kr=(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))(Kr||{});const Ko=e=>e==="desk401103"||e==="desk401106"||e==="desk401107"||e==="desk401108"||e==="desk401109";class jo{constructor(t){C(this,"_appId");C(this,"_apiHost");C(this,"_logger");C(this,"_credential",null);C(this,"_authRefreshPromise",null);C(this,"_onDeskTokenRefreshRequired",async()=>!1);C(this,"request",async(t,n)=>{const r=n.authRequired??!0,s=`${this._apiHost}${t}`;r&&this._authRefreshPromise&&(this._logger.debug("DeskApiClient: waiting for in-flight recovery..."),await this._authRefreshPromise);const a=await this._fetch(s,n);return r&&a.status===401?this._handleUnauthorized(a,s,n):this._toResult(a)});C(this,"setCredential",(t,n=async()=>!1)=>{this._authRefreshPromise=null,this._onDeskTokenRefreshRequired=n,this._credential=t});C(this,"clearCredential",()=>{this._authRefreshPromise=null,this._credential=null,this._onDeskTokenRefreshRequired=async()=>!1});C(this,"_handleUnauthorized",async(t,n,r)=>{const s=await this._parseErrorCode(t);if(!Ko(s))return this._toResult(t);if(!await this._refresh(s)||this._credential===null)return this._toResult(t);const i=await this._fetch(n,r);return this._toResult(i)});C(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}});C(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))}:{}}));C(this,"_buildParams",t=>new URLSearchParams({sendbirdAppId:this._appId,...t}));C(this,"_buildBody",t=>({sendbirdAppId:this._appId,...t}));C(this,"_buildHeaders",(t,n)=>({"content-type":"application/json",...t&&this._credential?{sendbirdDeskToken:this._credential.deskToken}:{},...n}));C(this,"_toResult",async t=>{if(!t.ok){const r=await t.json().catch(()=>({}));throw new Jn(t.status,r)}const n=await t.text();if(n)try{return JSON.parse(n)}catch{throw new Jn(t.status,{})}});C(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 St{constructor(t,n){C(this,"id");C(this,"title");C(this,"status");C(this,"agent");C(this,"priority");C(this,"group");C(this,"firstResponseTime");C(this,"issuedAt");C(this,"customFields");C(this,"_client");C(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 St({id:t.id,title:t.channelName??null,status:t.status2??wn.INITIALIZED,agent:(()=>{var a;const s=(a=t.recentAssignment)==null?void 0:a.agent;return s?{userId:s.sendbirdId??"",name:s.displayName??"",profileUrl:s.photoThumbnailUrl??""}:null})(),priority:t.priority??kn.MEDIUM,group:t.group??0,firstResponseTime:t.firstResponseTime??-1,issuedAt:t.issuedAt??null,customFields:Object.fromEntries(((r=t.customFields)==null?void 0:r.map(s=>[s.key,s.value]))??[])},n)}}class Mn{constructor(t){C(this,"_logger");C(this,"_apiClient");C(this,"_onDeskTokenRefreshRequired");C(this,"refreshDeskAuthToken",async t=>this._apiClient.credential?this.authenticate({userId:this._apiClient.credential.userId,accessToken:t,onDeskTokenRefreshRequired:this._onDeskTokenRefreshRequired}):!1);C(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}});C(this,"deauthenticate",()=>{this._apiClient.clearCredential(),this._onDeskTokenRefreshRequired=void 0,this._logger.debug("DeskClient.deauthenticate: token cleared")});C(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")});C(this,"getTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request(`/tickets/${encodeURIComponent(t)}/`,{method:"GET"});return St._fromResponse(n,this)});C(this,"createTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request("/tickets/",{method:"POST",body:Wo({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 St._fromResponse(n,this)});this._logger=t.logger,this._apiClient=new jo(t)}static init(t){return new Mn(t)}_assertAuthenticated(t){if(t.credential==null)throw new Error("DeskClient is not authenticated")}}function Yo(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 Xo=1440*60*1e3;function Pe(e){if(!e)throw new Error("Not authenticated. Call authenticate() first.")}function Zo(e,t){return Object.entries(t).every(([n,r])=>e[n]===r)}class At extends Do{constructor(n){super();C(this,"appId");C(this,"aiAgentId");C(this,"_chatClient");C(this,"_deskClient");C(this,"_cache");C(this,"_logger");C(this,"_dispatcher");C(this,"_session",null);C(this,"language");C(this,"countryCode");C(this,"context");C(this,"queryParams");C(this,"_config");C(this,"_networkStateAdapter");C(this,"_forceCreateChannel");C(this,"_agentVersion");C(this,"_statsTrackers");C(this,"_operationQueue",Mo());C(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"))});C(this,"initConversationIfNeeded",n=>this._initConversationIfNeeded(n));C(this,"authenticate",n=>{const r=n&&"userId"in n?`auth:${n.userId}`:"auth:anon";return this._operationQueue(r,async()=>{var i,l,c,d,m;this._logger.debug("AIAgent.authenticate: start"),this._statsTrackers.initialRender.onAuthStart();const s=this._getSessionCandidate(n),a=(i=s.userSessionCandidate)!=null&&i.userId?this._cache.messenger.getSettings(s.userSessionCandidate.userId):null;a!=null&&a.bot&&this._dispatcher.send(Be.MessengerSettingsUpdated({settings:a,source:"cache"}));try{const p=await this._chatClient.requestMessengerSettings({aiAgentId:this.aiAgentId,userId:(l=s.userSessionCandidate)==null?void 0:l.userId,language:this.language,country:this.countryCode,context:this.context,knownActiveChannelUrl:(c=a==null?void 0:a.active_channel)==null?void 0:c.channel_url,forceCreateChannel:this._forceCreateChannel,agentVersion:this._agentVersion});let E;if(p.auto_created_user)if(s.type==="manual")this._logger.warn("Received auto created user info but current session is manual. Ignoring auto created user info."),E={userId:s.userSessionCandidate.userId,authToken:s.userSessionCandidate.authToken};else{const{user_id:b,session_token:g,expire_at:_}=p.auto_created_user;this._cache.messenger.setAnonUser({userId:b,authToken:g,expireAt:_}),E={userId:b,authToken:g},this._logger.debug("AIAgent.authenticate: anonymous user created",b)}else E={userId:((d=s.userSessionCandidate)==null?void 0:d.userId)??"",authToken:((m=s.userSessionCandidate)==null?void 0:m.authToken)??""};this._cache.messenger.setSettings(E.userId,p),this._dispatcher.send(Be.MessengerSettingsUpdated({settings:p,source:"server"}));const v=(()=>{var b;return s.type==="anonymous"?yo(this._dispatcher):(b=s.userSessionCandidate)==null?void 0:b.sessionHandler})(),x=await this._chatClient.connect(E,v,b=>{var g;this._logger.debug("AIAgent: session token refreshed"),(g=this._session)==null||g._updateAuthToken(b),this._deskClient.refreshDeskAuthToken(b)},()=>{this._logger.debug("AIAgent: session token unavailable, deauthenticating desk"),this._deskClient.deauthenticate()});return await this._deskClient.authenticate({userId:E.userId,accessToken:E.authToken,onDeskTokenRefreshRequired:async({reason:b})=>{var g;if(b===Kr.ERR_SESSION_KEY_EXPIRED){await new Promise(y=>setTimeout(y,2e3));const _=(g=this._session)==null?void 0:g.userSession.authToken;return _?await this._deskClient.refreshDeskAuthToken(_):!1}return!1}}),(a==null?void 0:a.language)!==p.language&&this._deskClient.setCustomerLanguage(this.language).catch(()=>{}),this._statsTrackers.initialRender.onAuthComplete(),this._session=new No({sdkUser:x,userSession:E,activeChannel:{url:p.active_channel.channel_url,status:"open"},dispatcher:this._dispatcher}),this._setupChannelHandler(),this._logger.debug("AIAgent.authenticate: end",{userId:E.userId}),p}catch(p){throw this._statsTrackers.initialRender.onAuthError(p),p}})});C(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")}));C(this,"createConversation",async n=>{Pe(this._session),this._logger.debug("AIAgent.createConversation: start",n);const r=await this._chatClient.requestMessengerSettings({...n,userId:this._session.userSession.userId,knownActiveChannelUrl:void 0,agentVersion:this._agentVersion}),s=r.active_channel.channel_url;return this._cache.messenger.setSettings(this._session.userSession.userId,r),this._logger.debug("AIAgent.createConversation: end",s),s});C(this,"searchConversation",async n=>{if(Pe(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}),s=[];for(;r.hasNext;){const a=await r.next();for(const i of a)Zo(i.context??{},n.context)&&s.push(i.channelInfo.url)}return this._logger.debug("AIAgent.searchConversation: end",{count:s.length}),s});C(this,"closeConversation",async n=>{var s;Pe(this._session),this._logger.debug("AIAgent.closeConversation: start",n);const r=await this._chatClient.getChannel(n);((s=r.conversation)==null?void 0:s.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")});C(this,"createConversationListCollection",n=>new Ur(this.chatSDK,n??{}));C(this,"patchContext",async(n,r)=>{Pe(this._session),this._logger.debug("AIAgent.patchContext: start",{channelUrl:n,context:r});const s=await this._chatClient.patchContext(this.aiAgentId,n,r);return this._logger.debug("AIAgent.patchContext: end",s),{...s,context:s.context??{}}});C(this,"updateContext",async(n,r)=>{Pe(this._session),this._logger.debug("AIAgent.updateContext: start",{channelUrl:n,context:r});const s=await this._chatClient.updateContext(this.aiAgentId,n,r);return this._logger.debug("AIAgent.updateContext: end",s),{...s,context:s.context??{}}});C(this,"getContextObject",async n=>{Pe(this._session),this._logger.debug("AIAgent.getContextObject: start",n);const s=await(await this._chatClient.getChannel(n)).getContextObject(this.aiAgentId);return this._logger.debug("AIAgent.getContextObject: end",s),{...s,context:s.context??{}}});C(this,"refreshActiveChannel",async n=>{var i,l;Pe(this._session);const r=(n==null?void 0:n.useKnownActiveChannelUrl)??!0;this._logger.debug("AIAgent.refreshActiveChannel: start",{useKnownActiveChannelUrl:r});const s=await this._chatClient.requestMessengerSettings({aiAgentId:this.aiAgentId,userId:this._session.userSession.userId,language:this.language,country:this.countryCode,context:this.context,knownActiveChannelUrl:r?(l=(i=this._cache.messenger.getSettings(this._session.userSession.userId))==null?void 0:i.active_channel)==null?void 0:l.channel_url:void 0,forceCreateChannel:this._forceCreateChannel,agentVersion:this._agentVersion}),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});C(this,"_getSessionCandidate",n=>n instanceof zr?{type:"manual",userSessionCandidate:this._getManualSessionInfo(n)}:n instanceof dn?{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});C(this,"_getAnonymousSessionInfo",()=>{const n=this._cache.messenger.getAnonUser();return n?n.expireAt-Xo<=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});C(this,"_getManualSessionInfo",n=>{if(!n||n instanceof dn)throw new Error("userSessionInfo must be an instance of ManualSessionInfo");if(typeof n.userId!="string")throw new Error("userSessionInfo.userId must be a string");const r=["userId","authToken","sessionHandler"].filter(s=>!(s in n));return r.length>0&&this._logger.error(`_getManualSessionInfo: missing required keys in userSessionInfo: ${r.join(", ")}`),this._logger.debug("_getManualSessionInfo: manual session info detected"),{userId:n.userId,authToken:n.authToken,sessionHandler:n.sessionHandler}});this.appId=n.appId,this.aiAgentId=n.aiAgentId,this.language=n.language??"en",this.countryCode=n.countryCode,this.context=n.context,this._config=Yn(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 ko((r,s)=>this._chatClient.chatSDK.aiAgent.appendStat(r,s))}}static init(n){var m;const r=Wr.get(n.platform),s=n.logger??new Vr(n.logLevel??Sn.WARN),a=n.dispatcher??new Hr(s),i=n.useMMKVStorage?Yo(n.useMMKVStorage):r.keyValueStorage,l=fo({appId:n.appId,aiAgentId:n.aiAgentId,storage:i}),c=In.init({appId:n.appId,messengerVersion:r.messengerVersion,extensions:{platform:r.platform,deviceOSPlatform:r.deviceOSPlatform,deviceOSVersion:r.deviceOSVersion},chatParams:n.chatParams,chatSDK:n.chatSDK,logger:s,cache:l}),d=Mn.init({appId:n.appId,logger:s,customApiHost:(m=n.deskParams)==null?void 0:m.customApiHost});return s.debug("AIAgent.init: created",{appId:n.appId,aiAgentId:n.aiAgentId}),new At({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:c,deskClient:d,cache:l,logger:s,dispatcher:a})}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=Yn(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 te=(e,t)=>{const n=u.createContext(null),r=({children:i,value:l})=>o.createElement(n.Provider,{value:l},typeof i=="function"?i(l):i),s=({children:i})=>o.createElement(n.Consumer,null,l=>l?typeof i=="function"?i(l):i:null),a=()=>{const i=u.useContext(n);if(!i)throw new Error(`use${e}Context must be used within a ${e}Provider`);return i};return n.displayName=`${e}Context`,r.displayName=`${e}Provider`,s.displayName=`${e}Consumer`,a.displayName=`use${e}Context`,{Context:n,Provider:r,Consumer:s,useContext:a}};function pe(e){const t=u.createContext({Template:e.template,updateTemplate:()=>{},components:e.components,updateComponent:()=>{}});function n({children:a}){const[i,l]=u.useState(()=>e.template),[c,d]=u.useState(e.components),m={Template:i,updateTemplate:p=>l(()=>p),components:c,updateComponent:(p,E)=>d(v=>({...v,[p]:E}))};return o.createElement(t.Provider,{value:m},a)}function r({template:a,children:i}){const{updateTemplate:l}=u.useContext(t);return u.useLayoutEffect(()=>{a&&l(a)},[a]),o.createElement(o.Fragment,null,i)}function s({children:a}){return o.createElement(n,null,a)}return s.defaults=e,s.useContext=()=>u.useContext(t),s.Context=t,s.Template=r,Object.keys(e.components).forEach(a=>{s[a]=function({component:l}){const{updateComponent:c}=u.useContext(t);return u.useLayoutEffect(()=>{l&&c(a,l)},[l]),null}}),s}function Jo(...e){return function({children:n}){return e.reduce((r,s)=>o.createElement(s,null,r),n)}}function Qo(e,t){var r;const n=e.lastMessage;if(n!=null&&n.isUserMessage()||n!=null&&n.isAdminMessage())return n.message||"";if(n!=null&&n.isFileMessage())return n.message||n.name||"FILE";if(n!=null&&n.isMultipleFilesMessage()){if(n.message)return n.message;const s=n.fileInfoList.length;return((r=t==null?void 0:t.formatMultipleFilesCount)==null?void 0:r.call(t,s))??`${s} photos`}return e.name}function ea(e,t,n){var i;const r=new Date,s=new Date(((i=e.lastMessage)==null?void 0:i.createdAt)||e.createdAt),a=Fe.differenceInMinutes(r,s);return a<1?n.justNow:a<60?n.minutesAgo(a):Fe.isToday(s)?n.hoursAgo(Fe.differenceInHours(r,s)):t(s,n.dateShortFormat)}const ta=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},pt=e=>Math.max(0,Math.min(255,e)).toString(16).padStart(2,"0"),Qn=(e,t)=>{const n=pt(Math.round(t*255));if(e.startsWith("#")){const s=e.slice(1);return s.length===3||s.length===4?`#${s[0]}${s[0]}${s[1]}${s[1]}${s[2]}${s[2]}${n}`:`#${s.slice(0,6)}${n}`}const r=ta(e);return r?`#${pt(r[0])}${pt(r[1])}${pt(r[2])}${n}`:e},{Provider:na,useContext:me}=te("AIAgent");function ra(e){const t=sa(e);return o.createElement(na,{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}},e.children)}function sa(e){const t=u.useRef(null),n=u.useRef(null);if(!t.current||!n.current)t.current=At.init(e);else{const s=oa(n.current,e);(s.appId||s.aiAgentId||s.chatSDK)&&(t.current.dispose(),t.current=At.init({...e,chatParams:s.appId?{...e.chatParams,newInstance:!0}:e.chatParams}))}n.current=e,u.useEffect(()=>()=>{var s;(s=t.current)==null||s.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 oa(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 aa=(e,t,n)=>Le.useGroupChannelMessages(e,t,{...n,strictStreamingOrder:!0}),nt={DEFAULT_PRIMARY:"#000000",DEFAULT_BOT_MSG_BG:"#ECECEC",WHITE:"#ffffff",BLACK:"#000000"};function jr(e){return e.length===4?`#${[...e.slice(1)].map(t=>t+t).join("")}`:e}function ia(e){const t=jr(e);return[parseInt(t.slice(1,3),16),parseInt(t.slice(3,5),16),parseInt(t.slice(5,7),16)]}function la(e){return`#${e.map(t=>t.toString(16).padStart(2,"0")).join("")}`}function ca(e,t,n){e/=255,t/=255,n/=255;const r=Math.max(e,t,n),s=Math.min(e,t,n),a=r-s;let i=0,l=0;const c=(r+s)/2;return r!==s&&(l=c>.5?a/(2-r-s):a/(r+s)),r===e?i=(t-n)/a+(t<n?6:0):r===t?i=(n-e)/a+2:r===n&&(i=(e-t)/a+4),i/=6,[i,l,c]}function ua(e,t,n){let r,s,a;if(t===0)r=s=a=n;else{const i=function(m,p,E){return E<0&&(E+=1),E>1&&(E-=1),E<.16666666666666666?m+(p-m)*6*E:E<.5?p:E<.6666666666666666?m+(p-m)*(.6666666666666666-E)*6:m},l=n<.5?n*(1+t):n+t-n*t,c=2*n-l;r=i(c,l,e+1/3),s=i(c,l,e),a=i(c,l,e-1/3)}return[Math.round(r*255),Math.round(s*255),Math.round(a*255)]}function Et(e,t,n){const[r,s,a]=ia(e),[i,l,c]=ca(r,s,a),d=Math.max(0,Math.min(1,c*t)),m=Math.max(0,Math.min(1,l*n)),[p,E,v]=ua(i,m,d);return la([Math.round(p),Math.round(E),Math.round(v)])}function da(e,t="light"){return{extraDark:Et(e,.6,1.2),dark:Et(e,.85,1.1),main:e,light:Et(e,t==="dark"?1.1:1.5,t==="dark"?.95:.9),extraLight:Et(e,t==="dark"?1.2:1.75,t==="dark"?.9:.8)}}function hn(e){const t=jr(e),n=149,r=+`0x${t[1]}${t[2]}`,s=+`0x${t[3]}${t[4]}`,a=+`0x${t[5]}${t[6]}`;return r*.299+s*.587+a*.114>n?nt.BLACK:nt.WHITE}function ma(e,t,n,r,s){return{base:{primary:t,primaryContrastContent:n,background:e.background50,headerBackground:e.background50,modalContentBackground:e.background50},messageInput:{text:e.onlight.textHighEmphasis,placeholderText:e.onlight.textLowEmphasis,background:e.background100},messageIncoming:{text:s,background:r},messageOutgoing:{text:n,background:t},csat:{background:e.background100}}}const ha=(e,t,n,r,s)=>({base:{primary:t,primaryContrastContent:n,background:e.background600,headerBackground:e.background500,modalContentBackground:e.background500},messageInput:{text:e.ondark.textHighEmphasis,placeholderText:e.ondark.textLowEmphasis,background:e.background400},messageIncoming:{text:s,background:r},messageOutgoing:{text:n,background:t},csat:{background:e.background400}}),bt={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, 0.88)",textMidEmphasis:"rgba(0, 0, 0, 0.5)",textLowEmphasis:"rgba(0, 0, 0, 0.38)",textDisabled:"rgba(0, 0, 0, 0.12)"},ondark:{textHighEmphasis:"rgba(255, 255, 255, 0.88)",textMidEmphasis:"rgba(255, 255, 255, 0.5)",textLowEmphasis:"rgba(255, 255, 255, 0.38)",textDisabled:"rgba(255, 255, 255, 0.12)"},overlay:{dark:"rgba(0, 0, 0, 0.55)",light:"rgba(22, 22, 22, 0.32)"}},Zt={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 er(e){const t=ga(e),{colors:n,aiAgentColorVariables:r}=fa(e,t),s=Ea(e);return{selectedTheme:e.selectedTheme,palette:t,colors:n,aiAgentColorVariables:r,typography:s}}function ga({selectedTheme:e,palette:t,primary:n}){const r=t!=null&&t.primary?t.primary:n?n===bt.primary.main?bt.primary:da(n,e):bt.primary;return{...bt,primary:r,...t}}function fa({selectedTheme:e,primaryContrast:t,botMessageBackground:n,botMessageBackgroundContrast:r},s){const a=s.primary.main,i=t??hn(a),l=n??nt.DEFAULT_BOT_MSG_BG,c=r??hn(l);return{colors:(e==="light"?ma:ha)(s,a,i,l,c),aiAgentColorVariables:{primary_color:a,bot_message_bg_color:l,primary_contrast_color:i,bot_message_bg_contrast_color:c}}}function pa(e,t,n){const r={...e};return n.forEach(s=>{const a=t[s];a!=null&&(r[s]=a)}),r}function Ea({typography:e}){if(!e)return Zt;const t={...Zt};return Object.keys(e).forEach(n=>{const r=e[n];if(r&&typeof r=="object"){const s=Zt[n],a=["fontSize","fontWeight","fontFamily","lineHeight"];t[n]=pa(s,r,a)}}),t}const{Provider:ba,useContext:$n}=te("AIAgentTheme");function _a({logger:e,palette:t,typography:n,appearance:r,children:s}){const a=u.useRef(null),[i,l]=u.useState(()=>er({selectedTheme:(r==null?void 0:r.theme)??"light",palette:t,typography:n,primary:r==null?void 0:r.primaryColor,botMessageBackground:r==null?void 0:r.botMessageBackgroundColor})),c=u.useCallback((d,m)=>{m&&(a.current=m);const p=(r==null?void 0:r.theme)??d,E=a.current?a.current.themes[p]:null,v={primary:r==null?void 0:r.primaryColor,primaryContrast:void 0,botMessageBackground:r==null?void 0:r.botMessageBackgroundColor,botMessageBackgroundContrast:void 0};!v.primary&&(E!=null&&E.primary_color)&&(v.primary=E.primary_color,v.primaryContrast=E.primary_contrast_color),!v.botMessageBackground&&(E!=null&&E.bot_message_bg_color)&&(v.botMessageBackground=E.bot_message_bg_color,v.botMessageBackgroundContrast=E.bot_message_bg_contrast_color);const x=er({selectedTheme:p,palette:t,typography:n,...v});l(x),e==null||e.info("theme.update:",p)},[r==null?void 0:r.theme,r==null?void 0:r.primaryColor,r==null?void 0:r.botMessageBackgroundColor,t,n,e]);return u.useEffect(()=>{(r!=null&&r.theme||r!=null&&r.primaryColor||r!=null&&r.botMessageBackgroundColor)&&c(i.selectedTheme)},[r==null?void 0:r.theme,r==null?void 0:r.primaryColor,r==null?void 0:r.botMessageBackgroundColor]),o.createElement(ba,{value:{theme:i,updateTheme:c}},s)}const Jt=25*1024*1024,tr=1,nr=new Set(["image/png","image/jpeg","image/jpg"]),rr=new Set(["application/pdf"]),Ca={off:"off",always:"always",handed_off_only:"handed_off_only"},xa=()=>{const[e,t]=u.useState(()=>({maxAttachmentCount:tr,attachmentMode:"handed_off_only",defaultUploadSizeLimit:Jt,uploadSizeLimitPerType:new Map,supportedImageMimeTypes:nr,supportedFileMimeTypes:rr})),n=u.useCallback(({active_channel:s,upload_restriction:a})=>{t({maxAttachmentCount:(a==null?void 0:a.max_attachment_count)??tr,attachmentMode:Ca[s.attachment_mode]??"handed_off_only",defaultUploadSizeLimit:(a==null?void 0:a.default_upload_size_limit)??Jt,uploadSizeLimitPerType:new Map(Object.entries((a==null?void 0:a.upload_size_limit_per_type)??[])),supportedImageMimeTypes:new Set((a==null?void 0:a.supported_image_mime_types)??nr),supportedFileMimeTypes:new Set((a==null?void 0:a.supported_file_mime_types)??rr)})},[]),r=u.useCallback(s=>{const{channel:a,uploadSizeLimit:i=Jt}=s,l=(d=!0)=>a!=null&&a.isAIAgent?d?Ue(a):!1:!0,c=d=>{if(l())return e.defaultUploadSizeLimit??i;const m=e.defaultUploadSizeLimit??i,p=e.uploadSizeLimitPerType.get(d)??m;return Math.min(m,p)};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 Ue(a);default:return!0}},get supportedMimeTypes(){return l()?[ln]:[...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}},sr=(...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)")},Ze=e=>({...e,context:e.context??{}}),{Provider:va,useContext:at}=te("AIAgentMessengerSession"),ya=u.forwardRef(function({userSessionInfo:e,children:t},n){const{_aiAgentSDK:r,chatSDK:s,aiAgentId:a,logger:i}=me(),{updateTheme:l}=$n(),[c,d]=u.useState(void 0),[m,p]=u.useState(void 0),[E,v]=u.useState(null),[x,b]=u.useState(null),[g,_]=u.useState(null),[y,I]=u.useState(null),{updateBaseAttachmentRules:A,createAttachmentRules:$}=xa();u.useEffect(()=>{const T=r.onMessengerSettingsUpdated(({settings:z})=>{const{appearance:Y,bot:G,launcher:ye}=z;l(Y.selected_theme,Y),_({userId:G.bot_userid,profileUrl:G.bot_profile_url,nickname:G.bot_nickname,replyToFile:G.reply_to_file,specialNotice:G.special_notice,specialNoticeEnabled:G.is_special_notice_enabled,showHandoffButton:G.show_handoff_button??!0,isMultipleActiveConversationsEnabled:G.is_multiple_active_conversations_enabled??!0,isUserFeedbackEnabled:G.is_user_feedback_enabled??!1,isUserFeedbackCommentOptionEnabled:G.is_user_feedback_comment_option_enabled??!1}),I({type:ye.image_type||"default_icon",imageUrl:ye.image_url}),A(z)}),B=r.onActiveChannelUpdated(({channelUrl:z,status:Y,conversationStatus:G})=>{p({url:z,status:Y,conversationStatus:G})}),N=r.onAuthTokenRefreshed(()=>{var Y;const z=(Y=r.session)==null?void 0:Y.userSession.authToken;z&&b(G=>G?{...G,authToken:z}:null)});return()=>{T(),B(),N()}},[r,l,A]);const k=u.useCallback(async()=>{d(void 0);try{const T=await r.authenticate(e),B=r.session;return v(B.sdkUser),b(B.userSession),p(B.activeChannel),T}catch(T){throw d(T),T}},[r,e]),S=u.useCallback(async()=>{await r.deauthenticate(),v(null),p(void 0),b(null),_(null),I(null)},[r]),R=u.useCallback(async()=>{if(!r.session)throw i.error("agentMessengerSession.refreshActiveChannel: userSession is not ready"),new Error("userSession is not ready");return p(void 0),await r.refreshActiveChannel()},[r,i]),P=u.useCallback(async T=>{if(!r.session)throw new Error("Current user is not authenticated. Please authenticate first.");return r.createConversation(T)},[r]),O=u.useCallback(async T=>{if(!r.session)throw new Error("Current user is not authenticated. Please authenticate first.");return r.searchConversation(T)},[r]);return u.useImperativeHandle(n,()=>{const T=async()=>{if(!m)throw new Error("No active conversation. Please start a conversation first.");return await s.groupChannel.getChannel(m.url)};return{activeChannel:m,chatSDK:s,authenticate:k,deauthenticate:S,updateContext:async(...B)=>{const N=sr(...B);if(N.type==="active"){const G=await(await T()).updateContext(a,N.context);return Ze(G)}const z=await s.aiAgent.updateContext(N.aiAgentId,N.channelUrl,N.context);return Ze(z)},patchContext:async(...B)=>{const N=sr(...B);if(N.type==="active"){const G=await(await T()).patchContext(a,N.context);return Ze(G)}const z=await s.aiAgent.patchContext(N.aiAgentId,N.channelUrl,N.context);return Ze(z)},getContextObject:async()=>{const N=await(await T()).getContextObject(a);return Ze(N)}}},[k,S,m,s,a,i]),o.createElement(va,{value:{sdkUser:E,userSessionInfo:e,userSession:x,activeChannel:m,setActiveChannel:p,refreshActiveChannel:R,createConversation:P,searchConversation:O,connectionError:c,aiAgentInfo:g,launcherInfo:y,authenticate:k,deauthenticate:S,createAttachmentRules:$,statsTrackers:r.statsTrackers}},t)}),Ln=(e,t)=>{const n=u.useId(),r=u.useRef(t);u.useLayoutEffect(()=>{r.current=t}),u.useEffect(()=>{const s=new Z.ConnectionHandler({onDisconnected:a=>{var i,l;return(l=(i=r.current).onDisconnected)==null?void 0:l.call(i,a)},onConnected:a=>{var i,l;return(l=(i=r.current).onConnected)==null?void 0:l.call(i,a)},onReconnectStarted:()=>{var a,i;return(i=(a=r.current).onReconnectStarted)==null?void 0:i.call(a)},onReconnectSucceeded:()=>{var a,i;return(i=(a=r.current).onReconnectSucceeded)==null?void 0:i.call(a)},onReconnectFailed:()=>{var a,i;return(i=(a=r.current).onReconnectFailed)==null?void 0:i.call(a)},onConnectionLost:()=>{var a,i;return(i=(a=r.current).onConnectionLost)==null?void 0:i.call(a)},onConnectionDelayed:a=>{var i,l;return(l=(i=r.current).onConnectionDelayed)==null?void 0:l.call(i,a)}});return e.addConnectionHandler(n,s),()=>{e.removeConnectionHandler(n)}},[e,n])};function Sa(e){const{chatSDK:t,logger:n,aiAgentId:r,_aiAgentSDK:s}=me(),{sdkUser:a,statsTrackers:i}=at(),l=Le.useForceUpdate(),[c,d]=u.useState(void 0),[m,p]=u.useState(void 0),[E,v]=u.useState(!1);function x(g){g.isAIAgent&&!g.conversation&&(v(!0),s.initConversationIfNeeded(g).finally(()=>v(!1)))}async function b(){var g,_,y;if(!a){n.debug("useChannel.getChannel: no sdk user, skip fetching channel");return}if(n.debug("useChannel.getChannel: start"),d(void 0),p(void 0),v(!1),e){i.initialRender.onGetChannelStart();try{n.debug("useChannel.getChannel: get channel",e);const I=await t.groupChannel.getChannel(e);x(I),d(I),i.initialRender.onGetChannelComplete((g=I.conversation)==null?void 0:g.id),I.url===((_=s.session)==null?void 0:_.activeChannel.url)&&s.session._updateActiveChannel({url:I.url,status:ue(I)?"closed":"open",conversationStatus:(y=I.conversation)==null?void 0:y.status}),n.debug("useChannel.getChannel: fetched channel",I)}catch(I){i.initialRender.onGetChannelError(I),I instanceof Z.SendbirdError&&p(I),n.error("useChannel.getChannel: error",I)}}}return u.useEffect(()=>{b()},[t,a,e,r]),Ln(t,{async onReconnectSucceeded(){if(!c)return;const g=await c.refresh();x(g),d(g)}}),Le.useGroupChannelHandler(t,{onChannelChanged:g=>{g.isGroupChannel()&&g.url===e&&(n.debug("useChannel.onChannelChanged: channel changed",g.url),d(g),l())}}),{channel:c,channelFetchError:m,getChannel:b,isInitializingConversation:E}}const Aa=e=>{const t=e==null?void 0:e.lastMessage,n=t==null?void 0:t.extendedMessagePayload;return n==null?void 0:n.user_input_disabled_by},Ta=e=>{var i;const t=e==null?void 0:e.lastMessage;if(!t||!e)return!1;const n=t.extendedMessagePayload,r=n==null?void 0:n.form,s=!!r&&!r.submitted_at&&!r.canceled_at,a=e.isAIAgent&&!!((i=e.conversation)!=null&&i.handedOverAt);return s&&!a},Ia=()=>{const{chatSDK:e,networkStateAdapter:t}=me(),[n,r]=u.useState(()=>t?t.isOnline()?"connected":"reconnecting":"connected");return Ln(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(s=>{if(!s){r("reconnecting");return}r(a=>a==="reconnecting"&&e.connectionState===Z.ConnectionState.OPEN?"connected":a)})},[t,e]),n},wa=3e4,ka=({shouldApply:e,lastMessage:t,isBlockedWhileAIResponding:n,currentUserId:r})=>{const[s,a]=u.useState(!1),i=u.useRef(null),l=t&&rt(t,r)?t.createdAt:0;return u.useEffect(()=>{const c=()=>{i.current&&(clearTimeout(i.current),i.current=null),a(!1)},d=E=>{i.current&&clearTimeout(i.current),a(!0),i.current=setTimeout(()=>{a(!1),i.current=null},E)},m=Date.now()-l,p=wa-m;return n||p<=0?c():d(p),()=>{i.current&&clearTimeout(i.current)}},[n,l]),s&&e},Yr=e=>{const{chatSDK:t}=me(),[n,r]=u.useState([]);return Le.useGroupChannelHandler(t,{onTypingStatusUpdated(s){if(s.url===(e==null?void 0:e.url)){const a=s.getTypingUsers();r(a)}}}),n},Ma=({channel:e,lastMessage:t,aiAgentUserId:n,isStreamAnimating:r})=>{const[s,a]=u.useState(!1),i=Yr(e);return u.useEffect(()=>{if(!t)return;const l=i.some(d=>d.userId===n),c=rt(t,n)&&(Me.isStreaming(t)||r);a(c||l)},[i,t,n,r]),s},$a=({channel:e,messages:t,isStreamAnimating:n,isInitializingConversation:r})=>{const{aiAgentInfo:s,userSession:a}=at(),i=Ia(),l=Ma({channel:e,lastMessage:Kn(t,[ke.SendingStatus.SUCCEEDED]),aiAgentUserId:(s==null?void 0:s.userId)??"",isStreamAnimating:n}),c=ka({shouldApply:!!(e!=null&&e.isAIAgent)&&!Ue(e),isBlockedWhileAIResponding:l,lastMessage:Kn(t,[ke.SendingStatus.PENDING,ke.SendingStatus.SUCCEEDED]),currentUserId:(a==null?void 0:a.userId)??""});if(!e||i==="disconnected")return{disabled:!0,disabledBy:"unavailable"};if(i==="reconnecting")return{disabled:!0,disabledBy:"reconnecting"};if(ue(e))return{disabled:!0,disabledBy:"conversation_closed"};if($o(e))return{disabled:!0,disabledBy:"handoff_pending"};if(Ta(e))return{disabled:!0,disabledBy:"form_active"};const d=Aa(e);return d?{disabled:!0,disabledBy:d}:l||c||r?{disabled:!0,disabledBy:"ai_responding"}:{disabled:!1,disabledBy:""}},La=()=>{const[e,t]=u.useState(new Set),n=u.useCallback(s=>{t(a=>{if(a.has(s))return a;const i=new Set(a);return i.add(s),i})},[]),r=u.useCallback(s=>{t(a=>{if(!a.has(s))return a;const i=new Set(a);return i.delete(s),i})},[]);return{isAnimating:e.size>0,start:n,stop:r}},{Provider:Ra}=te("AIAgentConversation");function Oa({children:e,channelUrl:t,onChannelDeleted:n,onMessagesReceived:r,onMessagesUpdated:s,onConversationClosedStatusChanged:a,onConversationClosedViaDispatcher:i,onBeforeSendMessage:l,onAfterSendMessage:c=Ce,shouldMarkAsRead:d=!0,shouldCountNewMessages:m=()=>!1,sortComparator:p}){var O;const E=()=>d&&(g==null?void 0:g.markAsRead()),{chatSDK:v,logger:x,dispatcher:b}=me(),{channel:g,channelFetchError:_,getChannel:y,isInitializingConversation:I}=Sa(t),{statsTrackers:A}=at();u.useEffect(()=>{if(t)return A.initialRender.setChannelUrl(t),()=>{A.initialRender.cleanup()}},[t,A]);const $=aa(v,g,{replyType:ke.ReplyType.ONLY_REPLY_TO_CHANNEL,shouldCountNewMessages:m,onChannelDeleted:n,onMessagesReceived:T=>r==null?void 0:r(T),onMessagesUpdated:T=>s==null?void 0:s(T),onCacheResult:T=>A.initialRender.onCacheResult(T),onApiResult:T=>A.initialRender.onApiResult(T),logger:x,markAsRead:E,sortComparator:p}),k=La(),S=$a({channel:g,messages:$.messages,isStreamAnimating:k.isAnimating,isInitializingConversation:I});u.useEffect(()=>{E()},[d,g]);const R=ue(g);u.useEffect(()=>{a==null||a(R)},[R,a]),u.useEffect(()=>{const T=async B=>{const N=typeof(B==null?void 0:B.channelUrl)=="string";g&&N&&B.channelUrl!==g.url||(x.debug("conversation.dispatcher: try to close conversation",g),g!=null&&g.conversation&&g.conversation.status===ee.ConversationStatus.OPEN&&(await g.closeConversation(),i==null||i()))};return b.subscribe(ce.ConversationClose,T),()=>{b.unsubscribe(ce.ConversationClose,T)}},[b,g,x,(O=g==null?void 0:g.conversation)==null?void 0:O.status,i]);const P={conversation:(g==null?void 0:g.conversation)??void 0,channelSource:{channel:g,error:_,refetch:()=>y(),closeConversation:async()=>{ue(g)||await(g==null?void 0:g.closeConversation())}},messageSource:{messages:$.messages,newMessages:$.newMessages,initialized:$.initialized,loadPrevious:()=>$.loadPrevious(),loadNext:()=>$.loadNext(),deleteMessage:T=>$.deleteMessage(T),resendMessage:T=>$.resendMessage(T),resetNewMessages:()=>$.resetNewMessages(),sendUserMessage:async T=>{var N;if(((N=g==null?void 0:g.conversation)==null?void 0:N.status)===ee.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(T=await l(T));const B=await $.sendUserMessage(T,c);return c==null||c(B),B},sendFileMessage:async T=>{var N;if(((N=g==null?void 0:g.conversation)==null?void 0:N.status)===ee.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(T=await l(T));const B=await $.sendFileMessage(T,c);return c==null||c(B),B},sendMultipleFilesMessage:async T=>{var N;if(((N=g==null?void 0:g.conversation)==null?void 0:N.status)===ee.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(T=await l(T));const B=await $.sendMultipleFilesMessage(T,c);return c==null||c(B),B}},state:{streamAnimation:k,input:S}};return o.createElement(Ra,{value:P},e)}function Da(e,t){var v,x,b,g,_,y,I,A,$,k;const[n,r]=u.useState(!1),[s,a]=u.useState(null),[i,l]=u.useState([]),[c,d]=u.useState(null),m=u.useRef(!1),p=u.useCallback(async()=>{if(!m.current&&e.currentUser){m.current=!0,r(!1),a(null),l([]);try{c==null||c.dispose();const S=new Ur(e,t);S.setConversationListCollectionHandler({onChannelsAdded:()=>{l(S.channels)},onChannelsUpdated:()=>{l(S.channels)},onChannelsDeleted:()=>{l(S.channels)}}),await S.loadMore(),d(S),a(null)}catch(S){d(null),a(S)}finally{r(!0),m.current=!1}}},[e,e.currentUser,(v=t.filter)==null?void 0:v.aiAgentChannelFilter,(b=(x=t.filter)==null?void 0:x.aiAgentConversationStatusFilter)==null?void 0:b.join(),(_=(g=t.filter)==null?void 0:g.aiAgentIds)==null?void 0:_.join(),(y=t.filter)==null?void 0:y.deskChannelFilter,(A=(I=t.filter)==null?void 0:I.pinnedChannelUrls)==null?void 0:A.join(),($=t.filter)==null?void 0:$.copilotConversationOnly,(k=t.filter)==null?void 0:k.copilotSupportChannelUrl,t.limit]),E=u.useCallback(async()=>{if(c)try{await c.loadMore()}catch(S){a(S)}},[c]);return Ln(e,{onConnected:()=>p()}),u.useEffect(()=>{p()},[p]),u.useEffect(()=>()=>{m.current=!1,c==null||c.dispose()},[c]),{initialized:n,error:s,channels:i,loadMore:E}}const{Provider:Na}=te("AIAgentConversationList");function Pa({conversationListLimit:e,conversationListFilter:t,children:n}){var p,E;const{chatSDK:r,aiAgentId:s,queryParams:a}=me(),i={aiAgentIds:[s],aiAgentConversationStatusFilter:[ee.ConversationStatus.CLOSED,ee.ConversationStatus.OPEN]},l=e??((p=a==null?void 0:a.conversationListParams)==null?void 0:p.limit),c={...i,...(E=a==null?void 0:a.conversationListParams)==null?void 0:E.filter,...t},d=Da(r,{limit:l,filter:c}),m={listSource:{initialized:d.initialized,error:d.error??void 0,channels:d.channels,loadMore:()=>d.loadMore()}};return o.createElement(Na,{value:m},n)}function Fa(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:Ba,useContext:Xr}=te("MessageTemplateFetching");function Ua({children:e,internalVariables:t}){const n=u.useRef({}),r=u.useRef({}),[s,a]=u.useState({}),i=u.useCallback((d,m)=>{a(p=>({...p,[d]:{fetching:!1,error:!1,...p[d],...m}}))},[]),l=u.useCallback(async({onRequestTemplate:d,onGetCachedTemplate:m,templateKey:p,suspense:E=!1})=>{const v=m(p);if(v)return v;const x=r.current[p];if(x)return x;E||i(p,{fetching:!0});const b=d(p).catch(g=>{throw E||i(p,{error:!0}),g}).finally(()=>{E||i(p,{fetching:!1}),delete r.current[p]});return r.current[p]=b,b},[i]),c={internalVariables:t,fetchTemplate:l,suspend:(d,m)=>{if(n.current[d])return n.current[d];const p=Fa(m());return n.current[d]=p,p},getIsFetching:d=>{var m;return((m=s[d])==null?void 0:m.fetching)??!1},getHasError:d=>{var m;return((m=s[d])==null?void 0:m.error)??!1}};return o.createElement(Ba,{value:c},e)}const Dt={VARIABLE:e=>new RegExp(`\\{${e}\\}`,"g"),VIEW_VARIABLE:e=>new RegExp(`"{@${e}}"`,"g")};function Re({uiTemplateString:e,variables:t={}}){const n=Fo(t);return Tn({template:e,variables:n,variableKeyPattern:r=>Dt.VARIABLE(r)})}function Oe({theme:e,uiTemplateString:t,colorVariables:n={}}){return Tn({template:t,variables:n,variableKeyPattern:r=>Dt.VARIABLE(r),variableValueTransformer:r=>Po(e,r)})}function Ha({theme:e,uiTemplateString:t,viewVariables:n={},aiAgentColorVariables:r,internalVariables:s,onRequestTemplate:a}){const l=Object.values(n).flat().map(d=>d.key);return[...new Set(l)].some(d=>!a(d))?null:Tn({template:t,variables:n,variableKeyPattern:d=>Dt.VIEW_VARIABLE(d),variableValueTransformer:d=>{const m=d.map(({key:p,variables:E})=>{const v=a(p),{ui_template:x,color_variables:b}=ot(v);let g=JSON.stringify(x);return g=Re({uiTemplateString:g,variables:s}),g=Oe({theme:e,uiTemplateString:g,colorVariables:b}),g=Oe({theme:e,uiTemplateString:g,colorVariables:r}),g=Re({uiTemplateString:g,variables:E}),Ot(g)});return JSON.stringify(m)}})}async function Va({theme:e,uiTemplateString:t,viewVariables:n={},aiAgentColorVariables:r,internalVariables:s,onRequestTemplate:a}){return Bo({template:t,variables:n,variableKeyPattern:i=>Dt.VIEW_VARIABLE(i),variableValueTransformer:async i=>{const l=i.map(async({key:d,variables:m})=>{const p=await a(d),{ui_template:E,color_variables:v}=ot(p);let x=JSON.stringify(E);return x=Re({uiTemplateString:x,variables:s}),x=Oe({theme:e,uiTemplateString:x,colorVariables:v}),x=Oe({theme:e,uiTemplateString:x,colorVariables:r}),x=Re({uiTemplateString:x,variables:m}),Ot(x)}),c=await Promise.all(l);return JSON.stringify(c)}})}const za=({rawTemplate:e,aiAgentColorVariables:t,internalVariables:n,...r})=>{const{ui_template:s,color_variables:a}=ot(e);let i=JSON.stringify(s);if(Object.keys(r.viewVariables??{}).length>0){const c=Ha({...r,uiTemplateString:i,aiAgentColorVariables:t,internalVariables:n});if(c===null)return null;i=c}return i=Re({...r,uiTemplateString:i,variables:n}),i=Oe({...r,uiTemplateString:i,colorVariables:a}),i=Oe({...r,uiTemplateString:i,colorVariables:t}),i=Re({...r,uiTemplateString:i}),Ot(i)},Ga=async({rawTemplate:e,aiAgentColorVariables:t,internalVariables:n,...r})=>{const{ui_template:s,color_variables:a}=ot(e);let i=JSON.stringify(s);return Object.keys(r.viewVariables??{}).length>0&&(i=await Va({...r,uiTemplateString:i,aiAgentColorVariables:t,internalVariables:n})),i=Re({...r,uiTemplateString:i,variables:n}),i=Oe({...r,uiTemplateString:i,colorVariables:a}),i=Oe({...r,uiTemplateString:i,colorVariables:t}),i=Re({...r,uiTemplateString:i}),Ot(i)},qa=e=>{const{aiAgentColorVariables:t={}}=e,{internalVariables:n}=Xr();return u.useState(()=>{const r=e.onGetCachedTemplate(e.templateKey);return r?za({...e,rawTemplate:r,aiAgentColorVariables:t,internalVariables:n,onRequestTemplate:e.onGetCachedTemplate}):null})},Wa=e=>{const[t]=qa(e);if(t)return t;const{aiAgentColorVariables:n={}}=e,{internalVariables:r,fetchTemplate:s,suspend:a}=Xr();return a(e.templateKey,async()=>{const l=await s({...e,suspense:!0});return await Ga({...e,rawTemplate:l,aiAgentColorVariables:n,internalVariables:r})}).value},Ka="remove_powered_by",Rn=(e,t)=>{var s,a;const{chatSDK:n}=me(),{aiAgentInfo:r}=at();if(e==="handoff-button"){const i=!!((s=t==null?void 0:t.conversation)!=null&&s.handoff);return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.showHandoffButton)&&i&&An(t)}if(e==="special-notice")return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.specialNoticeEnabled)&&!!(r!=null&&r.specialNotice);if(e==="powered-by"){const i=(a=n==null?void 0:n.appInfo)==null?void 0:a.applicationAttributes;return u.useMemo(()=>!(Array.isArray(i)&&i.includes(Ka)),[i])}throw new Error("Unsupported feature")},ja={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"},Ya={getValueOrDefault:e=>e.value??e.default_value??null,validate:(e,t,n)=>{const r=t;if(e.required&&(!r||r.trim()===""))return{isValid:!1,error:n.required};if(!r)return{isValid:!0};const{rules:s}=e;if(s){if(s.min_length!==void 0&&r.length<s.min_length)return{isValid:!1,error:typeof n.minLength=="function"?n.minLength(s.min_length):n.minLength};if(s.max_length!==void 0&&r.length>s.max_length)return{isValid:!1,error:typeof n.maxLength=="function"?n.maxLength(s.max_length):n.maxLength};if(s.regex&&!new RegExp(s.regex).test(r))return{isValid:!1,error:n.regex}}return{isValid:!0}}},Xa={getValueOrDefault:e=>e.value??e.default_value??null,validate:(e,t,n)=>{const r=t;if(e.required&&r===null)return{isValid:!1,error:n.required};if(r===null)return{isValid:!0};const{rules:s}=e;if(s){if(s.min!==void 0&&r<s.min)return{isValid:!1,error:typeof n.min=="function"?n.min(s.min):n.min};if(s.max!==void 0&&r>s.max)return{isValid:!1,error:typeof n.max=="function"?n.max(s.max):n.max}}return{isValid:!0}}},Za={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}}},Ja={getValueOrDefault:e=>e.values??e.default_values??null,validate:(e,t,n)=>{const r=t;if(e.required&&(!r||r.length===0))return{isValid:!1,error:n.required};if(!r||r.length===0)return{isValid:!0};if(r.filter(i=>!e.options.includes(i)).length>0)return{isValid:!1,error:n.invalidSelection};const{rules:a}=e;if(a){if(a.min_select!==void 0&&r.length<a.min_select)return{isValid:!1,error:typeof n.minSelect=="function"?n.minSelect(a.min_select):n.minSelect};if(a.max_select!==void 0&&r.length>a.max_select)return{isValid:!1,error:typeof n.maxSelect=="function"?n.maxSelect(a.max_select):n.maxSelect}}return{isValid:!0}}},Qa={text:Ya,number:Xa,"single-select":Za,"multi-select":Ja},ei={getValueOrDefault:()=>null,validate:()=>({isValid:!1})};function Zr(e){return Qa[e.type]||ei}function or(e){return Zr(e).getValueOrDefault(e)}function ti(e,t,n={}){const r={...ja,...n};return Zr(e).validate(e,t,r)}const ni=(e,t={})=>{const{labels:n={},onSubmit:r,onCancel:s}=t,[a,i]=u.useState({}),[l,c]=u.useState(()=>{const b={};return e.fields.forEach(g=>{b[g.key]=or(g)}),b}),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 b={};let g=!1;e.fields.forEach(_=>{const y=or(_);JSON.stringify(l[_.key])!==JSON.stringify(y)&&(g=!0),b[_.key]=y}),g&&c(b)}},[d]);const m=(b,g)=>{c(_=>({..._,[b]:g})),i(_=>({..._,[b]:void 0}))},p=e.fields.map(b=>{var y,I,A;const g=l[b.key]??null,_={key:b.key,label:b.label,error:a[b.key],required:b.required};return b.type==="text"?{..._,type:"text",layout:b.layout,value:g,...b.placeholder&&{placeholder:b.placeholder},...((y=b.rules)==null?void 0:y.max_length)&&{maxLength:b.rules.max_length}}:b.type==="number"?{..._,type:"number",layout:b.layout,value:g,...b.placeholder&&{placeholder:b.placeholder},...((I=b.rules)==null?void 0:I.max)&&{max:b.rules.max}}:b.type==="single-select"?{..._,type:"single-select",layout:b.layout,value:g,options:b.options}:b.type==="multi-select"?{..._,type:"multi-select",layout:b.layout,value:g,options:b.options,...((A=b.rules)==null?void 0:A.max_select)&&{maxSelect:b.rules.max_select}}:{..._,type:"unknown",layout:"default",value:null}});return{state:d,fields:p,getField:b=>p.find(g=>g.key===b),updateFieldValue:m,submit:async()=>{const b={};let g=!1;for(const _ of e.fields){const y=l[_.key]??null,I=ti(_,y,n);I.isValid||(b[_.key]=I.error,g=!0)}if(i(b),!g&&r){const _={};e.fields.forEach(y=>{_[y.key]=l[y.key]??null}),await r(_)}},cancel:async()=>{await(s==null?void 0:s())}}},ri=e=>{if(e==null||typeof e!="object")return;const t="thinking_message"in e?e.thinking_message:void 0;return typeof t=="string"&&t?t:void 0},si=e=>{const{aiAgentInfo:t}=at(),r=Yr(e)[0];if(!r)return null;const s=r.userId===(t==null?void 0:t.userId),a=s?ri(r.metaData):void 0;return{user:s?t:r,isBot:s,thinkingMessage:a}},Jr=({channel:e,userSession:t,aiAgentInfo:n})=>{if(!t||!n||!e)return{fallbackIcon:"delight",url:void 0,title:""};const r=(()=>{const[a]=e.members.filter(i=>i.userId!==t.userId);return a})(),s={ai(a){return{fallbackIcon:a,url:n.profileUrl,title:n.nickname}},human(a){return{fallbackIcon:a,url:r==null?void 0:r.profileUrl,title:(r==null?void 0:r.nickname)||n.nickname}},channel(a){return{fallbackIcon:a,url:e==null?void 0:e.coverUrl,title:(e==null?void 0:e.name)??""}}};return e.isAIAgent?Ue(e)?s.human("agent"):s.ai("delight"):e.isDesk?s.human("agent"):s.channel("user")},ar=e=>u.useReducer((t,n)=>({...t,...n}),e);var he=(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))(he||{});const oi=new Set(["free_text","single_choice"]),ai=({csatPayload:e,type:t,initialCsat:n,initialCsatReason:r,initialIsResolved:s})=>{const[a,i]=ar({csatType:t,csat:n,csatReason:r,isResolved:s}),[l,c]=ar({followUpItem:!1}),d=u.useMemo(()=>{var g;const v=a.csat,x=typeof v=="number",b=(g=e.follow_up)==null?void 0:g.find(_=>x?_.scores.includes(v):_.always_visible??!1);if(oi.has(b==null?void 0:b.response_type))return b},[a.csat,e.follow_up]),m=(()=>{var v;if(typeof n=="number")return"submitted";if((t===he.AI_AGENT_CSAT_5||t===he.HELPDESK_CSAT_5)&&typeof a.csat=="number")return"submittable";if(t===he.AI_AGENT_CSAT_5_WITH_CRE){const x=typeof a.csat=="number",b=!((v=e.cre)!=null&&v.required)||typeof a.isResolved=="boolean";if(x&&b)return"submittable"}return"unsubmittable"})(),p=u.useCallback(()=>typeof a.csat>"u"?!1:d!=null&&d.required&&!a.csatReason?(c({followUpItem:!0}),!1):!0,[a,d,c]);return u.useEffect(()=>{r||(i({csatReason:""}),c({followUpItem:!1}))},[r,d,i,c]),{params:a,setParams:i,error:l,setError:c,followUpItem:d,state:m,validateParams:p,itemProps:{csatPayload:e,state:m,submitted:m==="submitted"}}},Qt=5,ii=250,li=50,ir=e=>Math.max(0,e-li),ci=e=>e<1e3?{speed:Qt*.5,chunkSize:2}:e<2e3?{speed:Qt*.8,chunkSize:2}:{speed:Qt*.6,chunkSize:3},ui=e=>{const{text:t,enabled:n=!1,onAnimationStart:r,onAnimationProgress:s,onAnimationComplete:a}=e,[i,l]=u.useState(()=>ir(t.length)),c=u.useRef(null),d=u.useRef({startTime:0,lastUpdate:0,lastProgressCall:0}).current,m=u.useRef({onStart:r,onProgress:s,onComplete:a}).current,p=u.useRef({startCalled:!1,completeCalled:!1}).current,E=u.useRef({initialEnabled:n,textLength:t.length,enabled:n}).current,v=n,x=i<t.length,b=E.initialEnabled&&(v||x);return u.useLayoutEffect(()=>{m.onStart=r,m.onProgress=s,m.onComplete=a,E.textLength=t.length,E.enabled=n}),u.useLayoutEffect(()=>{var g;E.initialEnabled&&(p.startCalled||(p.startCalled=!0,(g=m.onStart)==null||g.call(m)),l(_=>t.length<_?t.length:_))},[t]),u.useEffect(()=>{if(!E.initialEnabled)return;let g=ir(t.length);d.lastUpdate=0,d.startTime=0,d.lastProgressCall=0;const _=y=>{var O;d.lastUpdate===0&&(d.lastUpdate=y,d.startTime=y,d.lastProgressCall=y);const I=E.textLength,A=y-d.lastUpdate,$=y-d.startTime,{speed:k,chunkSize:S}=ci($),R=k*S;A>=R&&g<I&&(g=Math.min(g+S,I),l(g),d.lastUpdate=y),y-d.lastProgressCall>=ii&&(d.lastProgressCall=y,(O=m.onProgress)==null||O.call(m)),(g<I||E.enabled)&&(c.current=requestAnimationFrame(_))};return c.current=requestAnimationFrame(_),()=>{var y;c.current&&cancelAnimationFrame(c.current),p.startCalled&&!p.completeCalled&&(p.completeCalled=!0,(y=m.onComplete)==null||y.call(m))}},[]),u.useEffect(()=>{var I;const g=E.initialEnabled&&p.startCalled,_=!n,y=i>=t.length&&t.length>0;g&&_&&y&&!p.completeCalled&&(p.completeCalled=!0,(I=m.onComplete)==null||I.call(m))},[n,i,t.length]),{streamText:E.initialEnabled?t.slice(0,i):t,isAnimating:b}},di="1.21.0",le="sb-agent",de={ENTRY:`${le}-entry`,MODAL_ROOT:`${le}-modal-root`,WINDOW:`${le}-window`,LAUNCHER:`${le}-launcher`},_t=2147483647,Ve={MODAL:_t-1,TOOLTIP:_t-2,WINDOW:_t-3,LAUNCHER:_t-4},Qr=36,mi=100,hi=di,On="noopener noreferrer nofollow";function gi(){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 Ct={};function fi(){return{get:e=>{try{return localStorage.getItem(e)}catch{return Ct[e]??null}},set:(e,t)=>{try{localStorage.setItem(e,t)}catch{Ct[e]=t}},delete:e=>{try{localStorage.removeItem(e)}catch{delete Ct[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(Ct).filter(t=>t.startsWith(e))}}}}const pi='@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}',Ei={conversation:{input_placeholder:"Ask a question",input_placeholder_disabled:"Chat is unavailable in this channel",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.",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"},conversation_list:{header_title:"Conversations",ended:"Ended",footer_title:"Start a conversation",multiple_files_count:e=>`${e} ${e===1?"file":"files"}`},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."},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"},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"}},gn={language:"en",strings:Ei,dateLocale:Ys.enUS},es=e=>({MESSAGE_INPUT__PLACE_HOLDER:e.conversation.input_placeholder,MESSAGE_INPUT__PLACE_HOLDER__DISABLED:e.conversation.input_placeholder_disabled,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__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,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,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,SCROLL_TO_NEW_MESSAGES_LABEL:e.conversation.scroll_to_new_messages_label}),bi=e=>{var t;return((t=e.split("-"))==null?void 0:t[0])??Nt},Nt="en",_i=new Set([Nt,"ko","es","pt","fr","hi","it","de","tr","ja"]),Ci=(e,t,n)=>{const r=e[t];return r?typeof r=="function"?r():Promise.resolve(r):new Promise((s,a)=>{(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(a.bind(null,new Error("Unknown variable dynamic import: "+t+(t.split("/").length!==n?". Note that variables only represent file names one level deep.":""))))})},lr=es(gn.strings),xi={...lr,HEADER_BUTTON__AGENT_HANDOFF:"Connect with an agent",MESSAGE_INPUT__PLACE_HOLDER__SUGGESTED_REPLIES:"Select an option to continue",BUTTON__CANCEL:"Cancel",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_UPLOAD_FILES:"Files",FILE_VIEWER__UNSUPPORT:"Unsupported message",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",A11Y_ATTACH_FILE:"Attach file",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:lr.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",BUTTON__OK:"OK",NO_NAME:"(No name)",CHANNEL_FROZEN:"Channel frozen"},Tt={language:gn.language,dateLocale:gn.dateLocale,stringSet:xi},vi=Object.freeze(Object.defineProperty({__proto__:null,default:Tt},Symbol.toStringTag,{value:"Module"})),fn=new Map([[Nt,Tt]]);async function yi(e){const t=fn.get(e);if(t)return t;try{if(_i.has(e)){const{default:n}=await Ci(Object.assign({"./languages/de.ts":()=>Promise.resolve().then(()=>require("./cjs/DbxUqtQc.cjs")),"./languages/en.ts":()=>Promise.resolve().then(()=>vi),"./languages/es.ts":()=>Promise.resolve().then(()=>require("./cjs/DTCJ6-eC.cjs")),"./languages/fr.ts":()=>Promise.resolve().then(()=>require("./cjs/7UVs65zS.cjs")),"./languages/hi.ts":()=>Promise.resolve().then(()=>require("./cjs/DfRVurNO.cjs")),"./languages/it.ts":()=>Promise.resolve().then(()=>require("./cjs/JLk8Bvao.cjs")),"./languages/ja.ts":()=>Promise.resolve().then(()=>require("./cjs/BRnfdIkb.cjs")),"./languages/ko.ts":()=>Promise.resolve().then(()=>require("./cjs/BMS5Zb7W.cjs")),"./languages/pt.ts":()=>Promise.resolve().then(()=>require("./cjs/Dl0262MS.cjs")),"./languages/tr.ts":()=>Promise.resolve().then(()=>require("./cjs/DFmkiYPE.cjs"))}),`./languages/${e}.ts`,3);return fn.set(e,n),n}return Tt}catch{return Tt}}const{Provider:Si,useContext:K}=te("Localization"),Ai=({language:e=navigator.language,logger:t,stringSet:n,children:r})=>{const[s,a]=u.useState(fn.get(Nt));return u.useEffect(()=>{const i=bi(e);s.language!==i&&(t==null||t.debug("localization.useEffect: update language",{from:s.language,to:i}),yi(i).then(a))},[e,t]),o.createElement(Si,{value:{language:s.language,stringSet:{...s.stringSet,...n},dateLocale:s.dateLocale,format:(i,l,c)=>Fe.format(i,l,{locale:s.dateLocale,...c})}},r)},It="data-sb-agent-theme",cr=e=>(t,...n)=>{let r="";return t.forEach((s,a)=>{r+=s+(n[a]??"")}),`[${It}='${e}'] & { ${r} }`},F={light:cr("light"),dark:cr("dark")},Ti=w.css(({theme:e})=>{const{palette:t}=e;return`
|
|
1
|
+
"use strict";var js=Object.defineProperty;var Ys=(e,t,n)=>t in e?js(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var C=(e,t,n)=>Ys(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Z=require("@sendbird/chat"),u=require("react"),w=require("styled-components"),Fe=require("date-fns"),Xs=require("date-fns/locale/en-US"),ee=require("@sendbird/chat/aiAgent"),ke=require("@sendbird/chat/message"),tt=require("@sendbird/chat/groupChannel"),Le=require("@sendbird/uikit-tools"),Zs=require("react-dom"),Js=require("date-fns/isSameDay"),an=require("@sendbird/react-uikit-message-template-view"),Qs=require("@sendbird/uikit-message-template"),eo=require("dompurify"),to=require("@emotion/is-prop-valid"),Rt=e=>e&&e.__esModule?e:{default:e};function no(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 ro=Rt(Z),o=no(u),h=Rt(w),Dr=Rt(eo),so=Rt(to),Ke="sb-agent",Nr="KEY_IMG_ASPECT_RATIO",ln="*/*",H={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},fe=e=>!!e&&"sender"in e,oo=e=>fe(e)?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId),ao=(e,t,n,r=!0)=>{if(!r||!fe(e))return"single";const s=()=>{if(!t||!fe(t))return!1;const c=t.sender.userId===e.sender.userId,d=Fe.isSameMinute(t.createdAt,e.createdAt);return c&&d},a=()=>{if(!n||!fe(n))return!1;const c=n.sender.userId===e.sender.userId,d=Fe.isSameMinute(n.createdAt,e.createdAt);return c&&d},i=s(),l=a();return i&&l?"middle":i?"bottom":l?"top":"single"},rt=(e,t)=>(()=>{var r;return fe(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)},isIncoming:(e,t)=>fe(e)&&e.sender.userId!==t,isOutgoing:(e,t)=>fe(e)&&(e.sender.userId===t||e.sendingStatus===ke.SendingStatus.PENDING)},we=e=>e.startsWith("image/"),Pr=e=>e.startsWith("video/"),vn=(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"},Fr=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},yn=e=>{switch(e){case"top":case"middle":return H.GAP_GROUPED;default:return H.GAP_UNGROUPED}},io=(e,t)=>{const n=/```(\w+)?\n([\s\S]*?)```/g,r=[];let s=0;return e.replace(n,(a,...i)=>{const[l,c,d]=i;return s<d&&r.push({type:"text",value:e.slice(s,d).trim()}),r.push({type:"code",value:c.trim(),language:l?l.trim():"plaintext"}),s=d+a.length,a}),s<e.length&&r.push({type:"text",value:e.slice(s).trim()}),t?r.map(a=>a.type!=="text"?a:{...a,value:t(a.value)}):r},lo=e=>e.replace(/\[([^\]]+)\](?!\()/g,"\\[$1\\]"),co=e=>e.replace(/([a-zA-Z0-9])_(?=[a-zA-Z0-9])/g,"$1\\_"),uo=e=>e.replace(/~~/g,"\\~\\~"),mo=e=>{let t=e;return t=lo(t),t=co(t),t=uo(t),t},ho=typeof navigator<"u"&&navigator.product==="ReactNative",Kn=(e,t)=>{const n=r=>!t||t.length===0?!0:fe(r)&&t.includes(r.sendingStatus);return ho?e.find(n):e.findLast(n)};function Ce(){}function go(){const e=typeof navigator<"u"?navigator.userAgent:"",t=/iPad|iPhone|iPod/.test(e),n=/Android/.test(e);return t||n}function fo(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 cn=e=>{try{return JSON.parse(e===""?"{}":e)}catch{return{}}},Me={isStreaming(e){const t=cn(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(rt(e,t)){const r=cn(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)}},Xt=`@${Ke}`,po=({appId:e,aiAgentId:t,storage:n})=>{const r={templateBase:`${Xt}-template`,template:s=>`${r.templateBase}/templates/${s}`,templateToken:()=>`${r.templateBase}/tokens`,messengerSession:s=>{const a=fo(`${e}/${t}/${s}`);return`${Xt}-udata/${a}`},anonUserSession:()=>`${Xt}-session/${e}/${t}`};return{template:{set:(s,a)=>n.set(r.template(s),a),get:s=>n.get(r.template(s)),setCachedToken:s=>n.set(r.templateToken(),s),getCachedToken:()=>n.get(r.templateToken()),clear:()=>{n.getKeys(r.templateBase).forEach(n.delete)}},messenger:{getSettings:s=>{try{const a=n.get(r.messengerSession(s));return a?JSON.parse(a):null}catch{return null}},setSettings:(s,a)=>{try{delete a.auto_created_user;const i=JSON.stringify(a);n.set(r.messengerSession(s),i)}catch{return}},getAnonUser:()=>{try{const s=n.get(r.anonUserSession());return s?JSON.parse(s):null}catch{return null}},setAnonUser:s=>{try{const a=JSON.stringify(s);n.set(r.anonUserSession(),a)}catch{return}},clear:s=>{try{s&&n.delete(r.messengerSession(s)),n.delete(r.anonUserSession())}catch{return}}}}},Br=(e,t,n={})=>{let r=null,s=null,a=null;const{leading:i=!0,trailing:l=!0}=n,c=(...d)=>{const m=Date.now();if(a===null||m-a>=t)i?(e(...d),a=m):(s=d,a=m);else if(s=d,l&&!r){const p=t-(m-a);r=setTimeout(()=>{s&&l&&(e(...s),a=Date.now()),r=null,s=null},p)}};return c.cancel=()=>{r&&(clearTimeout(r),r=null),s=null,a=null},c};class Ur{constructor(t,{filter:n,limit:r=20}){C(this,"filter");C(this,"_sdk");C(this,"_pinnedChannels");C(this,"_channels");C(this,"_isDisposed",!1);C(this,"_handlerId",`handler-id-${Date.now()}`);C(this,"_order",tt.GroupChannelListOrder.LATEST_LAST_MESSAGE);C(this,"_limit");C(this,"_query");C(this,"_token");C(this,"_timestamp");C(this,"_isSyncing");C(this,"_channelHandler");C(this,"_connectionHandler");C(this,"_collectionEventHandler");C(this,"_throttledOnChannelChanged");var s,a,i,l,c,d,m;this.filter=n,this._sdk=t,this._pinnedChannels=[],this._channels=[],this._limit=r,this._query=this._sdk.aiAgent.createMyGroupChannelListQuery({aiAgentChannelFilter:(s=this.filter)==null?void 0:s.aiAgentChannelFilter,aiAgentConversationStatusFilter:(a=this.filter)==null?void 0:a.aiAgentConversationStatusFilter,aiAgentIds:(i=this.filter)==null?void 0:i.aiAgentIds,deskChannelFilter:(l=this.filter)==null?void 0:l.deskChannelFilter,pinnedChannelUrls:(c=this.filter)==null?void 0:c.pinnedChannelUrls,copilotConversationOnly:(d=this.filter)==null?void 0:d.copilotConversationOnly,copilotSupportChannelUrl:(m=this.filter)==null?void 0:m.copilotSupportChannelUrl,limit:this._limit}),this._token="",this._timestamp=Number.MAX_SAFE_INTEGER,this._isSyncing=!1,this._throttledOnChannelChanged=Br(p=>{this._query.belongsTo(p)?this._addChannelsToView([p],!1):this._removeChannelsFromView([p.url])},250,{trailing:!1,leading:!0}),this._channelHandler=new tt.GroupChannelHandler({onChannelChanged:p=>{p.isGroupChannel()&&this._throttledOnChannelChanged(p)},onChannelDeleted:p=>{this._removeChannelsFromView([p])}}),this._connectionHandler=new Z.ConnectionHandler({onReconnectSucceeded:()=>{this._isDefaultChangelogSyncTimestampUpdated&&this._syncChannelChangelogs()}}),this._sdk.addConnectionHandler(this._handlerId,this._connectionHandler),this._sdk.groupChannel.addGroupChannelHandler(this._handlerId,this._channelHandler)}get _isDefaultChangelogSyncTimestampUpdated(){return this._timestamp!==Number.MAX_SAFE_INTEGER}_setDefaultChangelogsSyncTimestamp(t){var a,i;const n=new Set(((a=this.filter)==null?void 0:a.pinnedChannelUrls)??[]),r=t.find(l=>!n.has(l.url));let s;r?s=((i=r.lastMessage)==null?void 0:i.createdAt)??r.createdAt:s=this._query.lastResponseAt,this._timestamp>s&&(this._timestamp=s)}async _syncChannelChangelogs(){if(this._isDisposed)return[];if(this._isSyncing)return[];try{this._isSyncing=!0;let t;for(this._token?t=await this._sdk.aiAgent.getMyGroupChannelChangeLogsByToken(this._token,this.filter):t=await this._sdk.aiAgent.getMyGroupChannelChangeLogsByTimestamp(this._timestamp,this.filter),this._token=t.token,this._addChannelsToView(t.updatedChannels),this._removeChannelsFromView(t.deletedChannelUrls);t.hasMore&&t.token;)t=await this._sdk.aiAgent.getMyGroupChannelChangeLogsByToken(this._token,this.filter),this._token=t.token,this._addChannelsToView(t.updatedChannels),this._removeChannelsFromView(t.deletedChannelUrls)}catch{}finally{this._isSyncing=!1}return[]}_upsertPinnedChannelsToArray(t){var l;const n=((l=this.filter)==null?void 0:l.pinnedChannelUrls)??[],r=new Map(n.map((c,d)=>[c,d])),s=[],a=[],i=[];for(const c of t){if(!this._query.belongsTo(c)){i.push(c.url);continue}const d=r.get(c.url);if(d===void 0)continue;const m=un(this._pinnedChannels,c);m>=0?(this._pinnedChannels.splice(m,1),a.push(c)):s.push(c);const E=this._pinnedChannels.findIndex(x=>(r.get(x.url)??1/0)>d),v=E===-1?this._pinnedChannels.length:E;this._pinnedChannels.splice(v,0,c)}return{addedChannels:s,updatedChannels:a,unmatchedChannelUrls:i}}_upsertRegularChannelsToArray(t,n=!1){const r=[],s=[],a=[];for(const i of t){if(!this._query.belongsTo(i)){r.push(i.url);continue}const l=un(this._channels,i),c=l<0;!c&&this._channels.splice(l,1);const m=Eo(this._channels,i,this._order).place,p=m===this._channels.length;c?p?(n||!this.hasMore)&&(this._channels.push(i),s.push(i)):(this._channels.splice(m,0,i),s.push(i)):(this._channels.splice(m,0,i),a.push(i))}return{addedChannels:s,updatedChannels:a,unmatchedChannelUrls:r}}_addChannelsToView(t,n=!1){var p,E,v,x,b;const r=new Set(((p=this.filter)==null?void 0:p.pinnedChannelUrls)??[]),s=[],a=[];for(const g of t)r.has(g.url)?s.push(g):a.push(g);const i=this._upsertPinnedChannelsToArray(s),l=this._upsertRegularChannelsToArray(a,n),c=i.addedChannels.concat(l.addedChannels),d=i.updatedChannels.concat(l.updatedChannels),m=i.unmatchedChannelUrls.concat(l.unmatchedChannelUrls);c.length>0&&((v=(E=this._collectionEventHandler)==null?void 0:E.onChannelsAdded)==null||v.call(E,{},c)),d.length>0&&((b=(x=this._collectionEventHandler)==null?void 0:x.onChannelsUpdated)==null||b.call(x,{},d)),m.length>0&&this._removeChannelsFromView(m)}_removeChannelsFromView(t){var s,a,i;const n=new Set(((s=this.filter)==null?void 0:s.pinnedChannelUrls)??[]),r=[];for(const l of t)if(n.has(l)){const c=this._pinnedChannels.findIndex(d=>d.url===l);c>=0&&(r.push(l),this._pinnedChannels.splice(c,1))}else{const c=this._channels.findIndex(d=>d.url===l);c>=0&&(r.push(l),this._channels.splice(c,1))}r.length>0&&((i=(a=this._collectionEventHandler)==null?void 0:a.onChannelsDeleted)==null||i.call(a,{},r))}get channels(){return this._isDisposed?[]:[...this._pinnedChannels,...this._channels]}get hasMore(){return this._isDisposed?!1:this._query.hasNext}async loadMore(){if(this._isDisposed)return[];if(this.hasMore){const t=await this._query.next();return this._setDefaultChangelogsSyncTimestamp(t),this._addChannelsToView(t,!0),t}return[]}setConversationListCollectionHandler(t){this._collectionEventHandler=t}dispose(){this._isDisposed||(this._isDisposed=!0,this._throttledOnChannelChanged.cancel(),this._collectionEventHandler=void 0,this._sdk.removeConnectionHandler(this._handlerId),this._sdk.groupChannel.removeGroupChannelHandler(this._handlerId),this._pinnedChannels.length=0,this._channels.length=0)}}const un=(e,t)=>e.findIndex(n=>n.isIdentical(t)),Eo=(e,t,n)=>{if(e.length>0){const r=un(e,t);let s=0,a=e.length-1,i=Math.floor((s+a)/2);for(;s<a;){const c=jn(e[i],t,n);if(c>0)a=i,i=Math.floor((s+a)/2);else if(c<0)s=i+1,i=Math.floor((s+a)/2);else return{place:i,oldPosition:r}}return{place:jn(e[i],t,n)>=0?i:i+1,oldPosition:r}}return{place:e.length,oldPosition:-1}},jn=(e,t,n)=>{switch(n){case tt.GroupChannelListOrder.LATEST_LAST_MESSAGE:if(e.lastMessage&&t.lastMessage){const r=t.lastMessage.createdAt-e.lastMessage.createdAt;return r===0?t.createdAt-e.createdAt:r}else return e.lastMessage?-1:t.lastMessage?1:t.createdAt-e.createdAt;default:return 0}};class Hr{constructor(t){C(this,"subscribers",{});this.logger=t}async send(t){const n=bo(),r=this.subscribers[t.type];if(r){this.logger.debug(`messenger.dispatcher: dispatching command: ${t.type}`,t.payload);const s=r.map(a=>a(t.payload));await Promise.all(s).catch(a=>{this.logger.error(`messenger.dispatcher: error in callback for command: ${t.type}`,a)})}return n.resolve(),n.promise}subscribe(t,n){this.subscribers[t]||(this.subscribers[t]=[]),this.subscribers[t].push(n)}unsubscribe(t,n){const r=this.subscribers[t];r&&(this.subscribers[t]=r.filter(s=>s!==n))}}const bo=()=>{let e=Ce,t=Ce;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}};var ue=(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))(ue||{});class st{constructor(t={}){C(this,"payload");this.payload=t}toJSON(){return JSON.stringify({type:this.type,payload:this.payload})}}const Be={CloseConversation:e=>new _o(e),MessengerSettingsUpdated:e=>new Co(e),ActiveChannelUpdated:e=>new xo(e),AnonymousSessionTokenExpired:()=>new vo,AuthTokenRefreshed:()=>new yo};class _o extends st{constructor(){super(...arguments);C(this,"type","conv.close")}}class Co extends st{constructor(){super(...arguments);C(this,"type","messenger.settings.updated")}}class xo extends st{constructor(){super(...arguments);C(this,"type","active.channel.updated")}}class vo extends st{constructor(){super(...arguments);C(this,"type","anon.token.expired")}}class yo extends st{constructor(){super(...arguments);C(this,"type","auth.token.refreshed")}}var Sn=(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))(Sn||{});class Vr{constructor(t){C(this,"level");this.level=t}verbose(...t){this.level<=0&&console.log(`[${Ke}/verbose]`,...t)}debug(...t){this.level<=1&&console.log(`[${Ke}/debug]`,...t)}info(...t){this.level<=2&&console.log(`[${Ke}/info]`,...t)}warn(...t){this.level<=3&&console.warn(`[${Ke}/warn]`,...t)}error(...t){this.level<=4&&console.error(`[${Ke}/error]`,...t)}}class zr{constructor({userId:t,authToken:n,sessionHandler:r}){C(this,"userId");C(this,"authToken");C(this,"sessionHandler");this.userId=t,this.authToken=n,this.sessionHandler=r}}class dn{constructor(){C(this,"userId");C(this,"authToken");C(this,"sessionHandler")}}const So=e=>({onSessionTokenRequired:t=>{t(null),e.send(Be.AnonymousSessionTokenExpired())}}),Ao="ai_agent:stats",To="conversation_initial_render",Io=800220;var X=(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))(X||{});class wo{constructor(){C(this,"timers",new Map);C(this,"committed",!1);C(this,"commitCallback",null);C(this,"conversationId",null);C(this,"channelUrl",null);C(this,"errorCode",null);C(this,"errorDescription",null);C(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??Io,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(Ao,t)):!1}}class ko extends wo{constructor(){super(...arguments);C(this,"presentMethod","direct_present")}setPresentMethod(n){return this.presentMethod=n,this}getMetricKey(){return To}buildPayload(){const n=this.getDuration(X.AUTH),r=this.getDuration(X.GET_CHANNEL),s=this.getDuration(X.GET_MESSAGES),a=this.getDuration(X.TOTAL_DURATION_FROM_CACHE),i=this.getDuration(X.TOTAL_DURATION),l={...this.extraData,present_method:this.presentMethod,...n!==null&&{auth_duration:n},...r!==null&&{get_channel_duration:r},...s!==null&&{get_messages_duration:s},...a!==null&&{total_duration_from_cache:a}},c={key:this.getMetricKey(),value:i!==null?String(i):"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 Mo{constructor(t){C(this,"commitCallback");C(this,"presentMethod","direct_present");C(this,"stats",null);this.commitCallback=t}getOrCreateStats(){return(!this.stats||this.stats.isCommitted())&&(this.stats=new ko().setCommitCallback(this.commitCallback).setPresentMethod(this.presentMethod)),this.stats}onAuthStart(){this.getOrCreateStats().startTimer(X.TOTAL_DURATION).startTimer(X.TOTAL_DURATION_FROM_CACHE).startTimer(X.AUTH)}onAuthComplete(){var t;(t=this.stats)==null||t.stopTimer(X.AUTH)}onAuthError(t){this.stats&&!this.stats.isCommitted()&&this.stats.stopTimer(X.AUTH).setError(t instanceof Z.SendbirdError?t.code:void 0,t.message).stopTimer(X.TOTAL_DURATION).commit()}onGetChannelStart(){var t;(t=this.stats)==null||t.startTimer(X.GET_CHANNEL)}onGetChannelComplete(t){this.stats&&(this.stats.stopTimer(X.GET_CHANNEL),t!==void 0&&this.stats.setConversationId(t),this.stats.startTimer(X.GET_MESSAGES))}onGetChannelError(t){this.stats&&!this.stats.isCommitted()&&this.stats.stopTimer(X.GET_CHANNEL).setError(t instanceof Z.SendbirdError?t.code:void 0,t.message).stopTimer(X.TOTAL_DURATION).commit()}onCacheResult(t){this.stats&&!this.stats.isCommitted()&&(t&&this.stats.setError(t instanceof Z.SendbirdError?t.code:void 0,t.message),this.stats.stopTimer(X.TOTAL_DURATION_FROM_CACHE))}onApiResult(t){this.stats&&!this.stats.isCommitted()&&(t&&this.stats.setError(t instanceof Z.SendbirdError?t.code:void 0,t.message),this.stats.stopTimer(X.TOTAL_DURATION).stopTimer(X.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 $o(){let e=null,t=0;const n=(r,s)=>{if((e==null?void 0:e.key)===r)return e.promise;const a=++t,l=(e?e.promise.catch(()=>{}).then(()=>s()):s()).finally(()=>{(e==null?void 0:e.id)===a&&(e=null)});return e={key:r,id:a,promise:l},l};return n.isPending=()=>e!==null,n}const Ie={conversation:{isTalkToAgentViewEnabled:!0,scrollMode:"auto",newMessageIndicatorEnabled:!0,senderAvatarEnabled:!0,messageAlertSoundEnabled:!1,header:{avatarEnabled:!0},input:{camera:{photoEnabled:!0},gallery:{photoEnabled:!0},fileEnabled:!0},fileViewer:{downloadEnabled:!0}}},Yn=e=>{var t,n,r,s,a,i,l,c,d,m,p,E,v,x;return e?{...Ie,...e,conversation:{...Ie.conversation,...e==null?void 0:e.conversation,header:{...(t=Ie.conversation)==null?void 0:t.header,...(n=e==null?void 0:e.conversation)==null?void 0:n.header},input:{...(r=Ie.conversation)==null?void 0:r.input,...(s=e==null?void 0:e.conversation)==null?void 0:s.input,camera:{...(i=(a=Ie.conversation)==null?void 0:a.input)==null?void 0:i.camera,...(c=(l=e==null?void 0:e.conversation)==null?void 0:l.input)==null?void 0:c.camera},gallery:{...(m=(d=Ie.conversation)==null?void 0:d.input)==null?void 0:m.gallery,...(E=(p=e==null?void 0:e.conversation)==null?void 0:p.input)==null?void 0:E.gallery}},fileViewer:{...(v=Ie.conversation)==null?void 0:v.fileViewer,...(x=e==null?void 0:e.conversation)==null?void 0:x.fileViewer}}}:Ie},de=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")},An=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 Ue(e){var n,r,s;return typeof(((n=e==null?void 0:e.conversation)==null?void 0:n.handedOverAt)??((s=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff)==null?void 0:s.timestamp))=="number"}function Lo(e){var r;const t=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff;return t?typeof t.requestedAt=="number"&&!Ue(e):!1}function Ro(e){var t;if(((t=e==null?void 0:e.resolution)==null?void 0:t.determinedBy)==="user")return e.resolution.isResolved}function Xn(e){return!!e&&e<Date.now()}function Oo(e){return!e.title}function Do(e,t){var n;if(e)return Oo(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 No{constructor(){C(this,"_channelHandlerId",null);C(this,"_connectionHandlerId",null);C(this,"_handleActiveChannelChangedThrottled",null);C(this,"_setupChannelHandler",()=>{const t=Date.now();this._channelHandlerId=`aiagent_channel_${t}`,this._connectionHandlerId=`aiagent_connection_${t}`,this._handleActiveChannelChangedThrottled=Br(s=>{var a,i;(i=this._session)==null||i._updateActiveChannel({url:s.url,status:de(s)?"closed":"open",conversationStatus:(a=s.conversation)==null?void 0:a.status}),this._logger.debug("AIAgentEventManager: activeChannel updated",s.url)},250,{leading:!0,trailing:!1});const n=new tt.GroupChannelHandler({onChannelChanged:s=>{var a,i;s.isGroupChannel()&&s.url===((a=this._session)==null?void 0:a.activeChannel.url)&&((i=this._handleActiveChannelChangedThrottled)==null||i.call(this,s))}}),r=new Z.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})});C(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")});C(this,"_syncActiveChannelOnReconnect",async()=>{var n,r,s;const t=(n=this._session)==null?void 0:n.activeChannel.url;if(t)try{const i=await(await this._chatClient.chatSDK.groupChannel.getChannel(t)).refresh();i.url===t&&((s=this._session)==null||s._updateActiveChannel({url:i.url,status:de(i)?"closed":"open",conversationStatus:(r=i.conversation)==null?void 0:r.status}),this._logger.debug("AIAgentEventManager: activeChannel synced on reconnect",i.url))}catch(a){this._logger.error("AIAgentEventManager: failed to sync activeChannel on reconnect",a)}});C(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)}});C(this,"onMessengerSettingsUpdated",t=>(this._dispatcher.subscribe(ue.MessengerSettingsUpdated,t),()=>{this._dispatcher.unsubscribe(ue.MessengerSettingsUpdated,t)}));C(this,"onActiveChannelUpdated",t=>(this._dispatcher.subscribe(ue.ActiveChannelUpdated,t),()=>{this._dispatcher.unsubscribe(ue.ActiveChannelUpdated,t)}));C(this,"onAuthTokenRefreshed",t=>(this._dispatcher.subscribe(ue.AuthTokenRefreshed,t),()=>{this._dispatcher.unsubscribe(ue.AuthTokenRefreshed,t)}))}}class Po{constructor(t){C(this,"_sdkUser");C(this,"_userSession");C(this,"_dispatcher");C(this,"_activeChannel");C(this,"_updateActiveChannel",t=>{this._activeChannel=t,this._dispatcher.send(Be.ActiveChannelUpdated({channelUrl:t.url,status:t.status,conversationStatus:t.conversationStatus}))});C(this,"_updateAuthToken",t=>{this._userSession.authToken=t,this._dispatcher.send(Be.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 Gr=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)}},ot=e=>JSON.parse(e),Ot=e=>JSON.parse(e);function Fo(e,t){const[n,r]=t.split(",").map(s=>s.trim());return e==="dark"&&r||n}function Bo(e){const t={};function n(r,s=""){for(const[a,i]of Object.entries(r)){const l=s?`${s}.${a}`:a;i&&typeof i=="object"&&!Array.isArray(i)?n(i,l):t[l]=i}}return n(e),t}function Tn({template:e,variables:t,variableKeyPattern:n,variableValueTransformer:r}){return Object.entries(t).reduce((s,[a,i])=>{if(!r&&!["number","boolean","string"].includes(typeof i))throw new Error(`If transformer is not provided, value(${a}:${i}) must be a {string, number, or boolean}`);const l=r?r(i):String(i),c=n(a);return s.replace(c,Gr(l))},e)}async function Uo({template:e,variables:t,variableKeyPattern:n,variableValueTransformer:r}){return(await Promise.all(Object.entries(t).map(async([a,i])=>{const l=await r(i);return{regex:n(a),transformedValue:l}}))).reduce((a,{regex:i,transformedValue:l})=>a.replace(i,Gr(l)),e)}var mn=(e=>(e[e.EXTERNAL_AUTH_TOKEN_EXPIRED=1]="EXTERNAL_AUTH_TOKEN_EXPIRED",e))(mn||{});const qr=e=>typeof e=="object"&&e!==null,Zn=(e,t)=>t in e&&typeof e[t]=="string"&&e[t]!=="",Ho=e=>!qr(e)||!Zn(e,"channel_url")||!Zn(e,"ai_agent_id")?null:{channelUrl:e.channel_url,aiAgentId:e.ai_agent_id},Vo={1:Ho};function zo(e){if(!qr(e)||!("cat"in e)||typeof e.cat!="number"||!("data"in e))return null;const t=e.cat,n=Vo[t];if(!n)return null;const r=n(e.data);return r?{category:t,data:r}:null}function Go(e,t,n,r){const s=ro.default.init({appId:e,modules:[new tt.GroupChannelModule,new ee.AIAgentModule],localCacheEnabled:!0,options:new Z.SendbirdChatOptions({typingIndicatorInvalidateTime:2e4}),...r});return s.addSendbirdExtensions([{version:n,product:Z.SendbirdProduct.AI_AGENT,platform:t.platform}],{platform:t.deviceOSPlatform,version:t.deviceOSVersion},t.customData)||console.warn("Invalid Sendbird Extensions",t),s}function qo(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 Wo=[400300,400301,400302,400310];class In{constructor(t,n,r){C(this,"chatSDK");C(this,"_logger");C(this,"_cache");C(this,"connect",async(t,n,r,s)=>{if(this._logger.debug("ChatClient.connect: start",t.userId),n){const a=new Z.SessionHandler({...n,onSessionTokenRequired:this._interceptTokenRefresh(n.onSessionTokenRequired,r,s)});this.chatSDK.setSessionHandler(a),this.chatSDK.aiAgent.addEventHandler(mn.EXTERNAL_AUTH_TOKEN_EXPIRED.toString(),i=>{var c;this._logger.debug("ChatClient.connect: EXTERNAL_AUTH_TOKEN_EXPIRED event received",i);const l=zo(i);(l==null?void 0:l.category)===mn.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(a){const i=a;if(this.chatSDK.isCacheEnabled){if(this._isCacheRestrictedError(i))this._logger.warn("ChatClient.connect","offline connect restricted",i.message,i.code),this._logger.warn("ChatClient.connect","clear cached-data"),await this.chatSDK.clearCachedData().catch(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",i.message,i.code),i}});C(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")});C(this,"getChannel",async t=>this.chatSDK.groupChannel.getChannel(t));C(this,"patchContext",async(t,n,r)=>this.chatSDK.aiAgent.patchContext(t,n,r));C(this,"updateContext",async(t,n,r)=>this.chatSDK.aiAgent.updateContext(t,n,r));C(this,"requestMessengerSettings",async t=>{var s;if(t.userId===""){const a=new Error("userId cannot be empty string for messenger settings request");throw this._logger.error("ChatClient.requestMessengerSettings: invalid userId",a),a}const n={...t,shouldSendFirstMessage:!1};this._logger.debug("ChatClient.requestMessengerSettings: requesting",n);const r=await this.chatSDK.aiAgent.requestMessengerSettings(n);return this._logger.debug("ChatClient.requestMessengerSettings: received",(s=r.active_channel)==null?void 0:s.channel_url),r});C(this,"_interceptTokenRefresh",(t,n,r)=>{if(t)return async(s,a)=>{new Promise((i,l)=>t==null?void 0:t(i,l)).then(i=>{i?n==null||n(i):r==null||r(),s(i)}).catch(i=>{r==null||r(),a(i)})}});C(this,"_isCacheRestrictedError",t=>Wo.some(n=>t.code===n));C(this,"_syncTemplatesIfNeeded",async()=>{var r,s;const t=(s=(r=this.chatSDK.appInfo)==null?void 0:r.aiAgentInfo)==null?void 0:s.templateListToken;if(!t)return;const n=this._cache.template.getCachedToken();if(!(n&&n===t)){this._logger.debug("ChatClient._syncTemplatesIfNeeded: syncing templates");try{const{templates:a,token:i}=await this.chatSDK.aiAgent.getMessageTemplates({limit:20});for(const{template:l}of a){const{key:c}=ot(l);this._cache.template.set(c,l)}this._cache.template.setCachedToken(i),this._logger.debug("ChatClient._syncTemplatesIfNeeded: sync completed")}catch(a){this._logger.error("ChatClient._syncTemplatesIfNeeded: error",a)}}});this.chatSDK=t,this._logger=n,this._cache=r}static init(t){let n;return t.chatSDK?(qo(t.chatSDK),n=t.chatSDK):n=Go(t.appId,t.extensions,t.messengerVersion,t.chatParams),new In(n,t.logger,t.cache)}}const ft=new Map,Wr={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]}}},Ko=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0));class Jn extends Error{constructor(n,r){const s=(r==null?void 0:r.detail)??"";super(s||`Desk API error (${n})`);C(this,"status");C(this,"code");C(this,"detail");this.name="DeskApiError",this.status=n,this.code=(r==null?void 0:r.code)??"",this.detail=s}}var wn=(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))(wn||{}),kn=(e=>(e.URGENT="URGENT",e.HIGH="HIGH",e.MEDIUM="MEDIUM",e.LOW="LOW",e))(kn||{}),Kr=(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))(Kr||{});const jo=e=>e==="desk401103"||e==="desk401106"||e==="desk401107"||e==="desk401108"||e==="desk401109";class Yo{constructor(t){C(this,"_appId");C(this,"_apiHost");C(this,"_logger");C(this,"_credential",null);C(this,"_authRefreshPromise",null);C(this,"_onDeskTokenRefreshRequired",async()=>!1);C(this,"request",async(t,n)=>{const r=n.authRequired??!0,s=`${this._apiHost}${t}`;r&&this._authRefreshPromise&&(this._logger.debug("DeskApiClient: waiting for in-flight recovery..."),await this._authRefreshPromise);const a=await this._fetch(s,n);return r&&a.status===401?this._handleUnauthorized(a,s,n):this._toResult(a)});C(this,"setCredential",(t,n=async()=>!1)=>{this._authRefreshPromise=null,this._onDeskTokenRefreshRequired=n,this._credential=t});C(this,"clearCredential",()=>{this._authRefreshPromise=null,this._credential=null,this._onDeskTokenRefreshRequired=async()=>!1});C(this,"_handleUnauthorized",async(t,n,r)=>{const s=await this._parseErrorCode(t);if(!jo(s))return this._toResult(t);if(!await this._refresh(s)||this._credential===null)return this._toResult(t);const i=await this._fetch(n,r);return this._toResult(i)});C(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}});C(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))}:{}}));C(this,"_buildParams",t=>new URLSearchParams({sendbirdAppId:this._appId,...t}));C(this,"_buildBody",t=>({sendbirdAppId:this._appId,...t}));C(this,"_buildHeaders",(t,n)=>({"content-type":"application/json",...t&&this._credential?{sendbirdDeskToken:this._credential.deskToken}:{},...n}));C(this,"_toResult",async t=>{if(!t.ok){const r=await t.json().catch(()=>({}));throw new Jn(t.status,r)}const n=await t.text();if(n)try{return JSON.parse(n)}catch{throw new Jn(t.status,{})}});C(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 St{constructor(t,n){C(this,"id");C(this,"title");C(this,"status");C(this,"agent");C(this,"priority");C(this,"group");C(this,"firstResponseTime");C(this,"issuedAt");C(this,"customFields");C(this,"_client");C(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 St({id:t.id,title:t.channelName??null,status:t.status2??wn.INITIALIZED,agent:(()=>{var a;const s=(a=t.recentAssignment)==null?void 0:a.agent;return s?{userId:s.sendbirdId??"",name:s.displayName??"",profileUrl:s.photoThumbnailUrl??""}:null})(),priority:t.priority??kn.MEDIUM,group:t.group??0,firstResponseTime:t.firstResponseTime??-1,issuedAt:t.issuedAt??null,customFields:Object.fromEntries(((r=t.customFields)==null?void 0:r.map(s=>[s.key,s.value]))??[])},n)}}class Mn{constructor(t){C(this,"_logger");C(this,"_apiClient");C(this,"_onDeskTokenRefreshRequired");C(this,"refreshDeskAuthToken",async t=>this._apiClient.credential?this.authenticate({userId:this._apiClient.credential.userId,accessToken:t,onDeskTokenRefreshRequired:this._onDeskTokenRefreshRequired}):!1);C(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}});C(this,"deauthenticate",()=>{this._apiClient.clearCredential(),this._onDeskTokenRefreshRequired=void 0,this._logger.debug("DeskClient.deauthenticate: token cleared")});C(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")});C(this,"getTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request(`/tickets/${encodeURIComponent(t)}/`,{method:"GET"});return St._fromResponse(n,this)});C(this,"createTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request("/tickets/",{method:"POST",body:Ko({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 St._fromResponse(n,this)});this._logger=t.logger,this._apiClient=new Yo(t)}static init(t){return new Mn(t)}_assertAuthenticated(t){if(t.credential==null)throw new Error("DeskClient is not authenticated")}}function Xo(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 Zo=1440*60*1e3;function Pe(e){if(!e)throw new Error("Not authenticated. Call authenticate() first.")}function Jo(e,t){return Object.entries(t).every(([n,r])=>e[n]===r)}class At extends No{constructor(n){super();C(this,"appId");C(this,"aiAgentId");C(this,"_chatClient");C(this,"_deskClient");C(this,"_cache");C(this,"_logger");C(this,"_dispatcher");C(this,"_session",null);C(this,"language");C(this,"countryCode");C(this,"context");C(this,"queryParams");C(this,"_config");C(this,"_networkStateAdapter");C(this,"_forceCreateChannel");C(this,"_agentVersion");C(this,"_statsTrackers");C(this,"_operationQueue",$o());C(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"))});C(this,"initConversationIfNeeded",n=>this._initConversationIfNeeded(n));C(this,"authenticate",n=>{const r=n&&"userId"in n?`auth:${n.userId}`:"auth:anon";return this._operationQueue(r,async()=>{var i,l,c,d,m;this._logger.debug("AIAgent.authenticate: start"),this._statsTrackers.initialRender.onAuthStart();const s=this._getSessionCandidate(n),a=(i=s.userSessionCandidate)!=null&&i.userId?this._cache.messenger.getSettings(s.userSessionCandidate.userId):null;a!=null&&a.bot&&this._dispatcher.send(Be.MessengerSettingsUpdated({settings:a,source:"cache"}));try{const p=await this._chatClient.requestMessengerSettings({aiAgentId:this.aiAgentId,userId:(l=s.userSessionCandidate)==null?void 0:l.userId,language:this.language,country:this.countryCode,context:this.context,knownActiveChannelUrl:(c=a==null?void 0:a.active_channel)==null?void 0:c.channel_url,forceCreateChannel:this._forceCreateChannel,agentVersion:this._agentVersion});let E;if(p.auto_created_user)if(s.type==="manual")this._logger.warn("Received auto created user info but current session is manual. Ignoring auto created user info."),E={userId:s.userSessionCandidate.userId,authToken:s.userSessionCandidate.authToken};else{const{user_id:b,session_token:g,expire_at:_}=p.auto_created_user;this._cache.messenger.setAnonUser({userId:b,authToken:g,expireAt:_}),E={userId:b,authToken:g},this._logger.debug("AIAgent.authenticate: anonymous user created",b)}else E={userId:((d=s.userSessionCandidate)==null?void 0:d.userId)??"",authToken:((m=s.userSessionCandidate)==null?void 0:m.authToken)??""};this._cache.messenger.setSettings(E.userId,p),this._dispatcher.send(Be.MessengerSettingsUpdated({settings:p,source:"server"}));const v=(()=>{var b;return s.type==="anonymous"?So(this._dispatcher):(b=s.userSessionCandidate)==null?void 0:b.sessionHandler})(),x=await this._chatClient.connect(E,v,b=>{var g;this._logger.debug("AIAgent: session token refreshed"),(g=this._session)==null||g._updateAuthToken(b),this._deskClient.refreshDeskAuthToken(b)},()=>{this._logger.debug("AIAgent: session token unavailable, deauthenticating desk"),this._deskClient.deauthenticate()});return await this._deskClient.authenticate({userId:E.userId,accessToken:E.authToken,onDeskTokenRefreshRequired:async({reason:b})=>{var g;if(b===Kr.ERR_SESSION_KEY_EXPIRED){await new Promise(y=>setTimeout(y,2e3));const _=(g=this._session)==null?void 0:g.userSession.authToken;return _?await this._deskClient.refreshDeskAuthToken(_):!1}return!1}}),(a==null?void 0:a.language)!==p.language&&this._deskClient.setCustomerLanguage(this.language).catch(()=>{}),this._statsTrackers.initialRender.onAuthComplete(),this._session=new Po({sdkUser:x,userSession:E,activeChannel:{url:p.active_channel.channel_url,status:"open"},dispatcher:this._dispatcher}),this._setupChannelHandler(),this._logger.debug("AIAgent.authenticate: end",{userId:E.userId}),p}catch(p){throw this._statsTrackers.initialRender.onAuthError(p),p}})});C(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")}));C(this,"createConversation",async n=>{Pe(this._session),this._logger.debug("AIAgent.createConversation: start",n);const r=await this._chatClient.requestMessengerSettings({...n,userId:this._session.userSession.userId,knownActiveChannelUrl:void 0,agentVersion:this._agentVersion}),s=r.active_channel.channel_url;return this._cache.messenger.setSettings(this._session.userSession.userId,r),this._logger.debug("AIAgent.createConversation: end",s),s});C(this,"searchConversation",async n=>{if(Pe(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}),s=[];for(;r.hasNext;){const a=await r.next();for(const i of a)Jo(i.context??{},n.context)&&s.push(i.channelInfo.url)}return this._logger.debug("AIAgent.searchConversation: end",{count:s.length}),s});C(this,"closeConversation",async n=>{var s;Pe(this._session),this._logger.debug("AIAgent.closeConversation: start",n);const r=await this._chatClient.getChannel(n);((s=r.conversation)==null?void 0:s.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")});C(this,"createConversationListCollection",n=>new Ur(this.chatSDK,n??{}));C(this,"patchContext",async(n,r)=>{Pe(this._session),this._logger.debug("AIAgent.patchContext: start",{channelUrl:n,context:r});const s=await this._chatClient.patchContext(this.aiAgentId,n,r);return this._logger.debug("AIAgent.patchContext: end",s),{...s,context:s.context??{}}});C(this,"updateContext",async(n,r)=>{Pe(this._session),this._logger.debug("AIAgent.updateContext: start",{channelUrl:n,context:r});const s=await this._chatClient.updateContext(this.aiAgentId,n,r);return this._logger.debug("AIAgent.updateContext: end",s),{...s,context:s.context??{}}});C(this,"getContextObject",async n=>{Pe(this._session),this._logger.debug("AIAgent.getContextObject: start",n);const s=await(await this._chatClient.getChannel(n)).getContextObject(this.aiAgentId);return this._logger.debug("AIAgent.getContextObject: end",s),{...s,context:s.context??{}}});C(this,"refreshActiveChannel",async n=>{var l,c,d;Pe(this._session);const r=this._session,s=(n==null?void 0:n.useKnownActiveChannelUrl)??!0;this._logger.debug("AIAgent.refreshActiveChannel: start",{useKnownActiveChannelUrl:s});const a=await this._chatClient.requestMessengerSettings({aiAgentId:this.aiAgentId,userId:r.userSession.userId,language:this.language,country:this.countryCode,context:this.context,knownActiveChannelUrl:s?(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)??a.active_channel.channel_url;const i=a.active_channel.channel_url;return this._cache.messenger.setSettings(this._session.userSession.userId,a),this._session._updateActiveChannel({url:i,status:"open"}),this._logger.debug("AIAgent.refreshActiveChannel: end",i),i});C(this,"_getSessionCandidate",n=>n instanceof zr?{type:"manual",userSessionCandidate:this._getManualSessionInfo(n)}:n instanceof dn?{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});C(this,"_getAnonymousSessionInfo",()=>{const n=this._cache.messenger.getAnonUser();return n?n.expireAt-Zo<=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});C(this,"_getManualSessionInfo",n=>{if(!n||n instanceof dn)throw new Error("userSessionInfo must be an instance of ManualSessionInfo");if(typeof n.userId!="string")throw new Error("userSessionInfo.userId must be a string");const r=["userId","authToken","sessionHandler"].filter(s=>!(s in n));return r.length>0&&this._logger.error(`_getManualSessionInfo: missing required keys in userSessionInfo: ${r.join(", ")}`),this._logger.debug("_getManualSessionInfo: manual session info detected"),{userId:n.userId,authToken:n.authToken,sessionHandler:n.sessionHandler}});this.appId=n.appId,this.aiAgentId=n.aiAgentId,this.language=n.language??"en",this.countryCode=n.countryCode,this.context=n.context,this._config=Yn(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 Mo((r,s)=>this._chatClient.chatSDK.aiAgent.appendStat(r,s))}}static init(n){var p;const r=Wr.get(n.platform),s=n.logger??new Vr(n.logLevel??Sn.WARN),a=n.dispatcher??new Hr(s),i=n.useMMKVStorage?Xo(n.useMMKVStorage):r.keyValueStorage,l=n.useMMKVStorage?{...n.chatParams,useMMKVStorageStore:n.useMMKVStorage}:n.chatParams,c=po({appId:n.appId,aiAgentId:n.aiAgentId,storage:i}),d=In.init({appId:n.appId,messengerVersion:r.messengerVersion,extensions:{platform:r.platform,deviceOSPlatform:r.deviceOSPlatform,deviceOSVersion:r.deviceOSVersion},chatParams:l,chatSDK:n.chatSDK,logger:s,cache:c}),m=Mn.init({appId:n.appId,logger:s,customApiHost:(p=n.deskParams)==null?void 0:p.customApiHost});return s.debug("AIAgent.init: created",{appId:n.appId,aiAgentId:n.aiAgentId}),new At({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:s,dispatcher:a})}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=Yn(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 te=(e,t)=>{const n=u.createContext(null),r=({children:i,value:l})=>o.createElement(n.Provider,{value:l},typeof i=="function"?i(l):i),s=({children:i})=>o.createElement(n.Consumer,null,l=>l?typeof i=="function"?i(l):i:null),a=()=>{const i=u.useContext(n);if(!i)throw new Error(`use${e}Context must be used within a ${e}Provider`);return i};return n.displayName=`${e}Context`,r.displayName=`${e}Provider`,s.displayName=`${e}Consumer`,a.displayName=`use${e}Context`,{Context:n,Provider:r,Consumer:s,useContext:a}};function pe(e){const t=u.createContext({Template:e.template,updateTemplate:()=>{},components:e.components,updateComponent:()=>{}});function n({children:a}){const[i,l]=u.useState(()=>e.template),[c,d]=u.useState(e.components),m={Template:i,updateTemplate:p=>l(()=>p),components:c,updateComponent:(p,E)=>d(v=>({...v,[p]:E}))};return o.createElement(t.Provider,{value:m},a)}function r({template:a,children:i}){const{updateTemplate:l}=u.useContext(t);return u.useLayoutEffect(()=>{a&&l(a)},[a]),o.createElement(o.Fragment,null,i)}function s({children:a}){return o.createElement(n,null,a)}return s.defaults=e,s.useContext=()=>u.useContext(t),s.Context=t,s.Template=r,Object.keys(e.components).forEach(a=>{s[a]=function({component:l}){const{updateComponent:c}=u.useContext(t);return u.useLayoutEffect(()=>{l&&c(a,l)},[l]),null}}),s}function Qo(...e){return function({children:n}){return e.reduce((r,s)=>o.createElement(s,null,r),n)}}function ea(e,t){var r;const n=e.lastMessage;if(n!=null&&n.isUserMessage()||n!=null&&n.isAdminMessage())return n.message||"";if(n!=null&&n.isFileMessage())return n.message||n.name||"FILE";if(n!=null&&n.isMultipleFilesMessage()){if(n.message)return n.message;const s=n.fileInfoList.length;return((r=t==null?void 0:t.formatMultipleFilesCount)==null?void 0:r.call(t,s))??`${s} photos`}return e.name}function ta(e,t,n){var i;const r=new Date,s=new Date(((i=e.lastMessage)==null?void 0:i.createdAt)||e.createdAt),a=Fe.differenceInMinutes(r,s);return a<1?n.justNow:a<60?n.minutesAgo(a):Fe.isToday(s)?n.hoursAgo(Fe.differenceInHours(r,s)):t(s,n.dateShortFormat)}const na=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},pt=e=>Math.max(0,Math.min(255,e)).toString(16).padStart(2,"0"),Qn=(e,t)=>{const n=pt(Math.round(t*255));if(e.startsWith("#")){const s=e.slice(1);return s.length===3||s.length===4?`#${s[0]}${s[0]}${s[1]}${s[1]}${s[2]}${s[2]}${n}`:`#${s.slice(0,6)}${n}`}const r=na(e);return r?`#${pt(r[0])}${pt(r[1])}${pt(r[2])}${n}`:e},jr=te("AIAgent"),ra=jr.Provider,ce=jr.useContext;function sa(e){const t=oa(e);return o.createElement(ra,{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}},e.children)}function oa(e){const t=u.useRef(null),n=u.useRef(null);if(!t.current||!n.current)t.current=At.init(e);else{const s=aa(n.current,e);(s.appId||s.aiAgentId||s.chatSDK)&&(t.current.dispose(),t.current=At.init({...e,chatParams:s.appId?{...e.chatParams,newInstance:!0}:e.chatParams}))}n.current=e,u.useEffect(()=>()=>{var s;(s=t.current)==null||s.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 aa(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 ia=(e,t,n)=>Le.useGroupChannelMessages(e,t,{...n,strictStreamingOrder:!0}),nt={DEFAULT_PRIMARY:"#000000",DEFAULT_BOT_MSG_BG:"#ECECEC",WHITE:"#ffffff",BLACK:"#000000"};function Yr(e){return e.length===4?`#${[...e.slice(1)].map(t=>t+t).join("")}`:e}function la(e){const t=Yr(e);return[parseInt(t.slice(1,3),16),parseInt(t.slice(3,5),16),parseInt(t.slice(5,7),16)]}function ca(e){return`#${e.map(t=>t.toString(16).padStart(2,"0")).join("")}`}function ua(e,t,n){e/=255,t/=255,n/=255;const r=Math.max(e,t,n),s=Math.min(e,t,n),a=r-s;let i=0,l=0;const c=(r+s)/2;return r!==s&&(l=c>.5?a/(2-r-s):a/(r+s)),r===e?i=(t-n)/a+(t<n?6:0):r===t?i=(n-e)/a+2:r===n&&(i=(e-t)/a+4),i/=6,[i,l,c]}function da(e,t,n){let r,s,a;if(t===0)r=s=a=n;else{const i=function(m,p,E){return E<0&&(E+=1),E>1&&(E-=1),E<.16666666666666666?m+(p-m)*6*E:E<.5?p:E<.6666666666666666?m+(p-m)*(.6666666666666666-E)*6:m},l=n<.5?n*(1+t):n+t-n*t,c=2*n-l;r=i(c,l,e+1/3),s=i(c,l,e),a=i(c,l,e-1/3)}return[Math.round(r*255),Math.round(s*255),Math.round(a*255)]}function Et(e,t,n){const[r,s,a]=la(e),[i,l,c]=ua(r,s,a),d=Math.max(0,Math.min(1,c*t)),m=Math.max(0,Math.min(1,l*n)),[p,E,v]=da(i,m,d);return ca([Math.round(p),Math.round(E),Math.round(v)])}function ma(e,t="light"){return{extraDark:Et(e,.6,1.2),dark:Et(e,.85,1.1),main:e,light:Et(e,t==="dark"?1.1:1.5,t==="dark"?.95:.9),extraLight:Et(e,t==="dark"?1.2:1.75,t==="dark"?.9:.8)}}function hn(e){const t=Yr(e),n=149,r=+`0x${t[1]}${t[2]}`,s=+`0x${t[3]}${t[4]}`,a=+`0x${t[5]}${t[6]}`;return r*.299+s*.587+a*.114>n?nt.BLACK:nt.WHITE}function ha(e,t,n,r,s){return{base:{primary:t,primaryContrastContent:n,background:e.background50,headerBackground:e.background50,modalContentBackground:e.background50},messageInput:{text:e.onlight.textHighEmphasis,placeholderText:e.onlight.textLowEmphasis,background:e.background100},messageIncoming:{text:s,background:r},messageOutgoing:{text:n,background:t},csat:{background:e.background100}}}const ga=(e,t,n,r,s)=>({base:{primary:t,primaryContrastContent:n,background:e.background600,headerBackground:e.background500,modalContentBackground:e.background500},messageInput:{text:e.ondark.textHighEmphasis,placeholderText:e.ondark.textLowEmphasis,background:e.background400},messageIncoming:{text:s,background:r},messageOutgoing:{text:n,background:t},csat:{background:e.background400}}),bt={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, 0.88)",textMidEmphasis:"rgba(0, 0, 0, 0.5)",textLowEmphasis:"rgba(0, 0, 0, 0.38)",textDisabled:"rgba(0, 0, 0, 0.12)"},ondark:{textHighEmphasis:"rgba(255, 255, 255, 0.88)",textMidEmphasis:"rgba(255, 255, 255, 0.5)",textLowEmphasis:"rgba(255, 255, 255, 0.38)",textDisabled:"rgba(255, 255, 255, 0.12)"},overlay:{dark:"rgba(0, 0, 0, 0.55)",light:"rgba(22, 22, 22, 0.32)"}},Zt={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 er(e){const t=fa(e),{colors:n,aiAgentColorVariables:r}=pa(e,t),s=ba(e);return{selectedTheme:e.selectedTheme,palette:t,colors:n,aiAgentColorVariables:r,typography:s}}function fa({selectedTheme:e,palette:t,primary:n}){const r=t!=null&&t.primary?t.primary:n?n===bt.primary.main?bt.primary:ma(n,e):bt.primary;return{...bt,primary:r,...t}}function pa({selectedTheme:e,primaryContrast:t,botMessageBackground:n,botMessageBackgroundContrast:r},s){const a=s.primary.main,i=t??hn(a),l=n??nt.DEFAULT_BOT_MSG_BG,c=r??hn(l);return{colors:(e==="light"?ha:ga)(s,a,i,l,c),aiAgentColorVariables:{primary_color:a,bot_message_bg_color:l,primary_contrast_color:i,bot_message_bg_contrast_color:c}}}function Ea(e,t,n){const r={...e};return n.forEach(s=>{const a=t[s];a!=null&&(r[s]=a)}),r}function ba({typography:e}){if(!e)return Zt;const t={...Zt};return Object.keys(e).forEach(n=>{const r=e[n];if(r&&typeof r=="object"){const s=Zt[n],a=["fontSize","fontWeight","fontFamily","lineHeight"];t[n]=Ea(s,r,a)}}),t}const{Provider:_a,useContext:$n}=te("AIAgentTheme");function Ca({logger:e,palette:t,typography:n,appearance:r,children:s}){const a=u.useRef(null),[i,l]=u.useState(()=>er({selectedTheme:(r==null?void 0:r.theme)??"light",palette:t,typography:n,primary:r==null?void 0:r.primaryColor,botMessageBackground:r==null?void 0:r.botMessageBackgroundColor})),c=u.useCallback((d,m)=>{m&&(a.current=m);const p=(r==null?void 0:r.theme)??d,E=a.current?a.current.themes[p]:null,v={primary:r==null?void 0:r.primaryColor,primaryContrast:void 0,botMessageBackground:r==null?void 0:r.botMessageBackgroundColor,botMessageBackgroundContrast:void 0};!v.primary&&(E!=null&&E.primary_color)&&(v.primary=E.primary_color,v.primaryContrast=E.primary_contrast_color),!v.botMessageBackground&&(E!=null&&E.bot_message_bg_color)&&(v.botMessageBackground=E.bot_message_bg_color,v.botMessageBackgroundContrast=E.bot_message_bg_contrast_color);const x=er({selectedTheme:p,palette:t,typography:n,...v});l(x),e==null||e.info("theme.update:",p)},[r==null?void 0:r.theme,r==null?void 0:r.primaryColor,r==null?void 0:r.botMessageBackgroundColor,t,n,e]);return u.useEffect(()=>{(r!=null&&r.theme||r!=null&&r.primaryColor||r!=null&&r.botMessageBackgroundColor)&&c(i.selectedTheme)},[r==null?void 0:r.theme,r==null?void 0:r.primaryColor,r==null?void 0:r.botMessageBackgroundColor]),o.createElement(_a,{value:{theme:i,updateTheme:c}},s)}const Jt=25*1024*1024,tr=1,nr=new Set(["image/png","image/jpeg","image/jpg"]),rr=new Set(["application/pdf"]),xa={off:"off",always:"always",handed_off_only:"handed_off_only"},va=()=>{const[e,t]=u.useState(()=>({maxAttachmentCount:tr,attachmentMode:"handed_off_only",defaultUploadSizeLimit:Jt,uploadSizeLimitPerType:new Map,supportedImageMimeTypes:nr,supportedFileMimeTypes:rr})),n=u.useCallback(({active_channel:s,upload_restriction:a})=>{t({maxAttachmentCount:(a==null?void 0:a.max_attachment_count)??tr,attachmentMode:xa[s.attachment_mode]??"handed_off_only",defaultUploadSizeLimit:(a==null?void 0:a.default_upload_size_limit)??Jt,uploadSizeLimitPerType:new Map(Object.entries((a==null?void 0:a.upload_size_limit_per_type)??[])),supportedImageMimeTypes:new Set((a==null?void 0:a.supported_image_mime_types)??nr),supportedFileMimeTypes:new Set((a==null?void 0:a.supported_file_mime_types)??rr)})},[]),r=u.useCallback(s=>{const{channel:a,uploadSizeLimit:i=Jt}=s,l=(d=!0)=>a!=null&&a.isAIAgent?d?Ue(a):!1:!0,c=d=>{if(l())return e.defaultUploadSizeLimit??i;const m=e.defaultUploadSizeLimit??i,p=e.uploadSizeLimitPerType.get(d)??m;return Math.min(m,p)};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 Ue(a);default:return!0}},get supportedMimeTypes(){return l()?[ln]:[...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}},sr=(...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)")},Ze=e=>({...e,context:e.context??{}}),{Provider:ya,useContext:at}=te("AIAgentMessengerSession"),Sa=u.forwardRef(function({userSessionInfo:e,children:t},n){const{_aiAgentSDK:r,chatSDK:s,aiAgentId:a,logger:i}=ce(),{updateTheme:l}=$n(),[c,d]=u.useState(void 0),[m,p]=u.useState(void 0),[E,v]=u.useState(null),[x,b]=u.useState(null),[g,_]=u.useState(null),[y,I]=u.useState(null),{updateBaseAttachmentRules:A,createAttachmentRules:$}=va();u.useEffect(()=>{const T=r.onMessengerSettingsUpdated(({settings:z})=>{const{appearance:Y,bot:G,launcher:ye}=z;l(Y.selected_theme,Y),_({userId:G.bot_userid,profileUrl:G.bot_profile_url,nickname:G.bot_nickname,replyToFile:G.reply_to_file,specialNotice:G.special_notice,specialNoticeEnabled:G.is_special_notice_enabled,showHandoffButton:G.show_handoff_button??!0,isMultipleActiveConversationsEnabled:G.is_multiple_active_conversations_enabled??!0,isUserFeedbackEnabled:G.is_user_feedback_enabled??!1,isUserFeedbackCommentOptionEnabled:G.is_user_feedback_comment_option_enabled??!1}),I({type:ye.image_type||"default_icon",imageUrl:ye.image_url}),A(z)}),B=r.onActiveChannelUpdated(({channelUrl:z,status:Y,conversationStatus:G})=>{p({url:z,status:Y,conversationStatus:G})}),N=r.onAuthTokenRefreshed(()=>{var Y;const z=(Y=r.session)==null?void 0:Y.userSession.authToken;z&&b(G=>G?{...G,authToken:z}:null)});return()=>{T(),B(),N()}},[r,l,A]);const k=u.useCallback(async()=>{d(void 0);try{const T=await r.authenticate(e),B=r.session;return v(B.sdkUser),b(B.userSession),p(B.activeChannel),T}catch(T){throw d(T),T}},[r,e]),S=u.useCallback(async()=>{await r.deauthenticate(),v(null),p(void 0),b(null),_(null),I(null)},[r]),R=u.useCallback(async()=>{if(!r.session){if(x)return i.debug("agentMessengerSession.refreshActiveChannel: stale call after deauthenticate, skipping"),"";throw i.error("agentMessengerSession.refreshActiveChannel: userSession is not ready"),new Error("userSession is not ready")}return r.session.userSession.userId!==(x==null?void 0:x.userId)?(i.debug("agentMessengerSession.refreshActiveChannel: stale call from previous session, skipping"),r.session.activeChannel.url):(p(void 0),await r.refreshActiveChannel())},[r,i,x]),P=u.useCallback(async T=>{if(!r.session)throw new Error("Current user is not authenticated. Please authenticate first.");return r.createConversation(T)},[r]),O=u.useCallback(async T=>{if(!r.session)throw new Error("Current user is not authenticated. Please authenticate first.");return r.searchConversation(T)},[r]);return u.useImperativeHandle(n,()=>{const T=async()=>{if(!m)throw new Error("No active conversation. Please start a conversation first.");return await s.groupChannel.getChannel(m.url)};return{activeChannel:m,chatSDK:s,authenticate:k,deauthenticate:S,updateContext:async(...B)=>{const N=sr(...B);if(N.type==="active"){const G=await(await T()).updateContext(a,N.context);return Ze(G)}const z=await s.aiAgent.updateContext(N.aiAgentId,N.channelUrl,N.context);return Ze(z)},patchContext:async(...B)=>{const N=sr(...B);if(N.type==="active"){const G=await(await T()).patchContext(a,N.context);return Ze(G)}const z=await s.aiAgent.patchContext(N.aiAgentId,N.channelUrl,N.context);return Ze(z)},getContextObject:async()=>{const N=await(await T()).getContextObject(a);return Ze(N)}}},[k,S,m,s,a,i]),o.createElement(ya,{value:{sdkUser:E,userSessionInfo:e,userSession:x,activeChannel:m,setActiveChannel:p,refreshActiveChannel:R,createConversation:P,searchConversation:O,connectionError:c,aiAgentInfo:g,launcherInfo:y,authenticate:k,deauthenticate:S,createAttachmentRules:$,statsTrackers:r.statsTrackers}},t)}),Ln=(e,t)=>{const n=u.useId(),r=u.useRef(t);u.useLayoutEffect(()=>{r.current=t}),u.useEffect(()=>{const s=new Z.ConnectionHandler({onDisconnected:a=>{var i,l;return(l=(i=r.current).onDisconnected)==null?void 0:l.call(i,a)},onConnected:a=>{var i,l;return(l=(i=r.current).onConnected)==null?void 0:l.call(i,a)},onReconnectStarted:()=>{var a,i;return(i=(a=r.current).onReconnectStarted)==null?void 0:i.call(a)},onReconnectSucceeded:()=>{var a,i;return(i=(a=r.current).onReconnectSucceeded)==null?void 0:i.call(a)},onReconnectFailed:()=>{var a,i;return(i=(a=r.current).onReconnectFailed)==null?void 0:i.call(a)},onConnectionLost:()=>{var a,i;return(i=(a=r.current).onConnectionLost)==null?void 0:i.call(a)},onConnectionDelayed:a=>{var i,l;return(l=(i=r.current).onConnectionDelayed)==null?void 0:l.call(i,a)}});return e.addConnectionHandler(n,s),()=>{e.removeConnectionHandler(n)}},[e,n])};function Aa(e){const{chatSDK:t,logger:n,aiAgentId:r,_aiAgentSDK:s}=ce(),{sdkUser:a,statsTrackers:i}=at(),l=Le.useForceUpdate(),[c,d]=u.useState(void 0),[m,p]=u.useState(void 0),[E,v]=u.useState(!1);function x(g){g.isAIAgent&&!g.conversation&&(v(!0),s.initConversationIfNeeded(g).finally(()=>v(!1)))}async function b(){var g,_,y;if(!a){n.debug("useChannel.getChannel: no sdk user, skip fetching channel");return}if(n.debug("useChannel.getChannel: start"),d(void 0),p(void 0),v(!1),e){i.initialRender.onGetChannelStart();try{n.debug("useChannel.getChannel: get channel",e);const I=await t.groupChannel.getChannel(e);x(I),d(I),i.initialRender.onGetChannelComplete((g=I.conversation)==null?void 0:g.id),I.url===((_=s.session)==null?void 0:_.activeChannel.url)&&s.session._updateActiveChannel({url:I.url,status:de(I)?"closed":"open",conversationStatus:(y=I.conversation)==null?void 0:y.status}),n.debug("useChannel.getChannel: fetched channel",I)}catch(I){i.initialRender.onGetChannelError(I),I instanceof Z.SendbirdError&&p(I),n.error("useChannel.getChannel: error",I)}}}return u.useEffect(()=>{b()},[t,a,e,r]),Ln(t,{async onReconnectSucceeded(){if(!c)return;const g=await c.refresh();x(g),d(g)}}),Le.useGroupChannelHandler(t,{onChannelChanged:g=>{g.isGroupChannel()&&g.url===e&&(n.debug("useChannel.onChannelChanged: channel changed",g.url),d(g),l())}}),{channel:c,channelFetchError:m,getChannel:b,isInitializingConversation:E}}const Ta=e=>{const t=e==null?void 0:e.lastMessage,n=t==null?void 0:t.extendedMessagePayload;return n==null?void 0:n.user_input_disabled_by},Ia=e=>{var i;const t=e==null?void 0:e.lastMessage;if(!t||!e)return!1;const n=t.extendedMessagePayload,r=n==null?void 0:n.form,s=!!r&&!r.submitted_at&&!r.canceled_at,a=e.isAIAgent&&!!((i=e.conversation)!=null&&i.handedOverAt);return s&&!a},wa=()=>{const{chatSDK:e,networkStateAdapter:t}=ce(),[n,r]=u.useState(()=>t?t.isOnline()?"connected":"reconnecting":"connected");return Ln(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(s=>{if(!s){r("reconnecting");return}r(a=>a==="reconnecting"&&e.connectionState===Z.ConnectionState.OPEN?"connected":a)})},[t,e]),n},ka=3e4,Ma=({shouldApply:e,lastMessage:t,isBlockedWhileAIResponding:n,currentUserId:r})=>{const[s,a]=u.useState(!1),i=u.useRef(null),l=t&&rt(t,r)?t.createdAt:0;return u.useEffect(()=>{const c=()=>{i.current&&(clearTimeout(i.current),i.current=null),a(!1)},d=E=>{i.current&&clearTimeout(i.current),a(!0),i.current=setTimeout(()=>{a(!1),i.current=null},E)},m=Date.now()-l,p=ka-m;return n||p<=0?c():d(p),()=>{i.current&&clearTimeout(i.current)}},[n,l]),s&&e},Xr=e=>{const{chatSDK:t}=ce(),[n,r]=u.useState([]);return Le.useGroupChannelHandler(t,{onTypingStatusUpdated(s){if(s.url===(e==null?void 0:e.url)){const a=s.getTypingUsers();r(a)}}}),n},$a=({channel:e,lastMessage:t,aiAgentUserId:n,isStreamAnimating:r})=>{const[s,a]=u.useState(!1),i=Xr(e);return u.useEffect(()=>{if(!t)return;const l=i.some(d=>d.userId===n),c=rt(t,n)&&(Me.isStreaming(t)||r);a(c||l)},[i,t,n,r]),s},La=({channel:e,messages:t,isStreamAnimating:n,isInitializingConversation:r})=>{const{aiAgentInfo:s,userSession:a}=at(),i=wa(),l=$a({channel:e,lastMessage:Kn(t,[ke.SendingStatus.SUCCEEDED]),aiAgentUserId:(s==null?void 0:s.userId)??"",isStreamAnimating:n}),c=Ma({shouldApply:!!(e!=null&&e.isAIAgent)&&!Ue(e),isBlockedWhileAIResponding:l,lastMessage:Kn(t,[ke.SendingStatus.PENDING,ke.SendingStatus.SUCCEEDED]),currentUserId:(a==null?void 0:a.userId)??""});if(!e||i==="disconnected")return{disabled:!0,disabledBy:"unavailable"};if(i==="reconnecting")return{disabled:!0,disabledBy:"reconnecting"};if(de(e))return{disabled:!0,disabledBy:"conversation_closed"};if(Lo(e))return{disabled:!0,disabledBy:"handoff_pending"};if(Ia(e))return{disabled:!0,disabledBy:"form_active"};const d=Ta(e);return d?{disabled:!0,disabledBy:d}:l||c||r?{disabled:!0,disabledBy:"ai_responding"}:{disabled:!1,disabledBy:""}},Ra=()=>{const[e,t]=u.useState(new Set),n=u.useCallback(s=>{t(a=>{if(a.has(s))return a;const i=new Set(a);return i.add(s),i})},[]),r=u.useCallback(s=>{t(a=>{if(!a.has(s))return a;const i=new Set(a);return i.delete(s),i})},[]);return{isAnimating:e.size>0,start:n,stop:r}},{Provider:Oa}=te("AIAgentConversation");function Da({children:e,channelUrl:t,onChannelDeleted:n,onMessagesReceived:r,onMessagesUpdated:s,onConversationClosedStatusChanged:a,onConversationClosedViaDispatcher:i,onBeforeSendMessage:l,onAfterSendMessage:c=Ce,shouldMarkAsRead:d=!0,shouldCountNewMessages:m=()=>!1,sortComparator:p}){var O;const E=()=>d&&(g==null?void 0:g.markAsRead()),{chatSDK:v,logger:x,dispatcher:b}=ce(),{channel:g,channelFetchError:_,getChannel:y,isInitializingConversation:I}=Aa(t),{statsTrackers:A}=at();u.useEffect(()=>{if(t)return A.initialRender.setChannelUrl(t),()=>{A.initialRender.cleanup()}},[t,A]);const $=ia(v,g,{replyType:ke.ReplyType.ONLY_REPLY_TO_CHANNEL,shouldCountNewMessages:m,onChannelDeleted:n,onMessagesReceived:T=>r==null?void 0:r(T),onMessagesUpdated:T=>s==null?void 0:s(T),onCacheResult:T=>A.initialRender.onCacheResult(T),onApiResult:T=>A.initialRender.onApiResult(T),logger:x,markAsRead:E,sortComparator:p}),k=Ra(),S=La({channel:g,messages:$.messages,isStreamAnimating:k.isAnimating,isInitializingConversation:I});u.useEffect(()=>{E()},[d,g]);const R=de(g);u.useEffect(()=>{a==null||a(R)},[R,a]),u.useEffect(()=>{const T=async B=>{const N=typeof(B==null?void 0:B.channelUrl)=="string";g&&N&&B.channelUrl!==g.url||(x.debug("conversation.dispatcher: try to close conversation",g),g!=null&&g.conversation&&g.conversation.status===ee.ConversationStatus.OPEN&&(await g.closeConversation(),i==null||i()))};return b.subscribe(ue.ConversationClose,T),()=>{b.unsubscribe(ue.ConversationClose,T)}},[b,g,x,(O=g==null?void 0:g.conversation)==null?void 0:O.status,i]);const P={conversation:(g==null?void 0:g.conversation)??void 0,channelSource:{channel:g,error:_,refetch:()=>y(),closeConversation:async()=>{de(g)||await(g==null?void 0:g.closeConversation())}},messageSource:{messages:$.messages,newMessages:$.newMessages,initialized:$.initialized,loadPrevious:()=>$.loadPrevious(),loadNext:()=>$.loadNext(),deleteMessage:T=>$.deleteMessage(T),resendMessage:T=>$.resendMessage(T),resetNewMessages:()=>$.resetNewMessages(),sendUserMessage:async T=>{var N;if(((N=g==null?void 0:g.conversation)==null?void 0:N.status)===ee.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(T=await l(T));const B=await $.sendUserMessage(T,c);return c==null||c(B),B},sendFileMessage:async T=>{var N;if(((N=g==null?void 0:g.conversation)==null?void 0:N.status)===ee.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(T=await l(T));const B=await $.sendFileMessage(T,c);return c==null||c(B),B},sendMultipleFilesMessage:async T=>{var N;if(((N=g==null?void 0:g.conversation)==null?void 0:N.status)===ee.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(T=await l(T));const B=await $.sendMultipleFilesMessage(T,c);return c==null||c(B),B}},state:{streamAnimation:k,input:S}};return o.createElement(Oa,{value:P},e)}function Na(e,t){var v,x,b,g,_,y,I,A,$,k;const[n,r]=u.useState(!1),[s,a]=u.useState(null),[i,l]=u.useState([]),[c,d]=u.useState(null),m=u.useRef(!1),p=u.useCallback(async()=>{if(!m.current&&e.currentUser){m.current=!0,r(!1),a(null),l([]);try{c==null||c.dispose();const S=new Ur(e,t);S.setConversationListCollectionHandler({onChannelsAdded:()=>{l(S.channels)},onChannelsUpdated:()=>{l(S.channels)},onChannelsDeleted:()=>{l(S.channels)}}),await S.loadMore(),d(S),a(null)}catch(S){d(null),a(S)}finally{r(!0),m.current=!1}}},[e,e.currentUser,(v=t.filter)==null?void 0:v.aiAgentChannelFilter,(b=(x=t.filter)==null?void 0:x.aiAgentConversationStatusFilter)==null?void 0:b.join(),(_=(g=t.filter)==null?void 0:g.aiAgentIds)==null?void 0:_.join(),(y=t.filter)==null?void 0:y.deskChannelFilter,(A=(I=t.filter)==null?void 0:I.pinnedChannelUrls)==null?void 0:A.join(),($=t.filter)==null?void 0:$.copilotConversationOnly,(k=t.filter)==null?void 0:k.copilotSupportChannelUrl,t.limit]),E=u.useCallback(async()=>{if(c)try{await c.loadMore()}catch(S){a(S)}},[c]);return Ln(e,{onConnected:()=>p()}),u.useEffect(()=>{p()},[p]),u.useEffect(()=>()=>{m.current=!1,c==null||c.dispose()},[c]),{initialized:n,error:s,channels:i,loadMore:E}}const{Provider:Pa}=te("AIAgentConversationList");function Fa({conversationListLimit:e,conversationListFilter:t,children:n}){var p,E;const{chatSDK:r,aiAgentId:s,queryParams:a}=ce(),i={aiAgentIds:[s],aiAgentConversationStatusFilter:[ee.ConversationStatus.CLOSED,ee.ConversationStatus.OPEN]},l=e??((p=a==null?void 0:a.conversationListParams)==null?void 0:p.limit),c={...i,...(E=a==null?void 0:a.conversationListParams)==null?void 0:E.filter,...t},d=Na(r,{limit:l,filter:c}),m={listSource:{initialized:d.initialized,error:d.error??void 0,channels:d.channels,loadMore:()=>d.loadMore()}};return o.createElement(Pa,{value:m},n)}function Ba(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:Ua,useContext:Zr}=te("MessageTemplateFetching");function Ha({children:e,internalVariables:t}){const n=u.useRef({}),r=u.useRef({}),[s,a]=u.useState({}),i=u.useCallback((d,m)=>{a(p=>({...p,[d]:{fetching:!1,error:!1,...p[d],...m}}))},[]),l=u.useCallback(async({onRequestTemplate:d,onGetCachedTemplate:m,templateKey:p,suspense:E=!1})=>{const v=m(p);if(v)return v;const x=r.current[p];if(x)return x;E||i(p,{fetching:!0});const b=d(p).catch(g=>{throw E||i(p,{error:!0}),g}).finally(()=>{E||i(p,{fetching:!1}),delete r.current[p]});return r.current[p]=b,b},[i]),c={internalVariables:t,fetchTemplate:l,suspend:(d,m)=>{if(n.current[d])return n.current[d];const p=Ba(m());return n.current[d]=p,p},getIsFetching:d=>{var m;return((m=s[d])==null?void 0:m.fetching)??!1},getHasError:d=>{var m;return((m=s[d])==null?void 0:m.error)??!1}};return o.createElement(Ua,{value:c},e)}const Dt={VARIABLE:e=>new RegExp(`\\{${e}\\}`,"g"),VIEW_VARIABLE:e=>new RegExp(`"{@${e}}"`,"g")};function Re({uiTemplateString:e,variables:t={}}){const n=Bo(t);return Tn({template:e,variables:n,variableKeyPattern:r=>Dt.VARIABLE(r)})}function Oe({theme:e,uiTemplateString:t,colorVariables:n={}}){return Tn({template:t,variables:n,variableKeyPattern:r=>Dt.VARIABLE(r),variableValueTransformer:r=>Fo(e,r)})}function Va({theme:e,uiTemplateString:t,viewVariables:n={},aiAgentColorVariables:r,internalVariables:s,onRequestTemplate:a}){const l=Object.values(n).flat().map(d=>d.key);return[...new Set(l)].some(d=>!a(d))?null:Tn({template:t,variables:n,variableKeyPattern:d=>Dt.VIEW_VARIABLE(d),variableValueTransformer:d=>{const m=d.map(({key:p,variables:E})=>{const v=a(p),{ui_template:x,color_variables:b}=ot(v);let g=JSON.stringify(x);return g=Re({uiTemplateString:g,variables:s}),g=Oe({theme:e,uiTemplateString:g,colorVariables:b}),g=Oe({theme:e,uiTemplateString:g,colorVariables:r}),g=Re({uiTemplateString:g,variables:E}),Ot(g)});return JSON.stringify(m)}})}async function za({theme:e,uiTemplateString:t,viewVariables:n={},aiAgentColorVariables:r,internalVariables:s,onRequestTemplate:a}){return Uo({template:t,variables:n,variableKeyPattern:i=>Dt.VIEW_VARIABLE(i),variableValueTransformer:async i=>{const l=i.map(async({key:d,variables:m})=>{const p=await a(d),{ui_template:E,color_variables:v}=ot(p);let x=JSON.stringify(E);return x=Re({uiTemplateString:x,variables:s}),x=Oe({theme:e,uiTemplateString:x,colorVariables:v}),x=Oe({theme:e,uiTemplateString:x,colorVariables:r}),x=Re({uiTemplateString:x,variables:m}),Ot(x)}),c=await Promise.all(l);return JSON.stringify(c)}})}const Ga=({rawTemplate:e,aiAgentColorVariables:t,internalVariables:n,...r})=>{const{ui_template:s,color_variables:a}=ot(e);let i=JSON.stringify(s);if(Object.keys(r.viewVariables??{}).length>0){const c=Va({...r,uiTemplateString:i,aiAgentColorVariables:t,internalVariables:n});if(c===null)return null;i=c}return i=Re({...r,uiTemplateString:i,variables:n}),i=Oe({...r,uiTemplateString:i,colorVariables:a}),i=Oe({...r,uiTemplateString:i,colorVariables:t}),i=Re({...r,uiTemplateString:i}),Ot(i)},qa=async({rawTemplate:e,aiAgentColorVariables:t,internalVariables:n,...r})=>{const{ui_template:s,color_variables:a}=ot(e);let i=JSON.stringify(s);return Object.keys(r.viewVariables??{}).length>0&&(i=await za({...r,uiTemplateString:i,aiAgentColorVariables:t,internalVariables:n})),i=Re({...r,uiTemplateString:i,variables:n}),i=Oe({...r,uiTemplateString:i,colorVariables:a}),i=Oe({...r,uiTemplateString:i,colorVariables:t}),i=Re({...r,uiTemplateString:i}),Ot(i)},Wa=e=>{const{aiAgentColorVariables:t={}}=e,{internalVariables:n}=Zr();return u.useState(()=>{const r=e.onGetCachedTemplate(e.templateKey);return r?Ga({...e,rawTemplate:r,aiAgentColorVariables:t,internalVariables:n,onRequestTemplate:e.onGetCachedTemplate}):null})},Ka=e=>{const[t]=Wa(e);if(t)return t;const{aiAgentColorVariables:n={}}=e,{internalVariables:r,fetchTemplate:s,suspend:a}=Zr();return a(e.templateKey,async()=>{const l=await s({...e,suspense:!0});return await qa({...e,rawTemplate:l,aiAgentColorVariables:n,internalVariables:r})}).value},ja="remove_powered_by",Rn=(e,t)=>{var s,a;const{chatSDK:n}=ce(),{aiAgentInfo:r}=at();if(e==="handoff-button"){const i=!!((s=t==null?void 0:t.conversation)!=null&&s.handoff);return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.showHandoffButton)&&i&&An(t)}if(e==="special-notice")return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.specialNoticeEnabled)&&!!(r!=null&&r.specialNotice);if(e==="powered-by"){const i=(a=n==null?void 0:n.appInfo)==null?void 0:a.applicationAttributes;return u.useMemo(()=>!(Array.isArray(i)&&i.includes(ja)),[i])}throw new Error("Unsupported feature")},Ya={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"},Xa={getValueOrDefault:e=>e.value??e.default_value??null,validate:(e,t,n)=>{const r=t;if(e.required&&(!r||r.trim()===""))return{isValid:!1,error:n.required};if(!r)return{isValid:!0};const{rules:s}=e;if(s){if(s.min_length!==void 0&&r.length<s.min_length)return{isValid:!1,error:typeof n.minLength=="function"?n.minLength(s.min_length):n.minLength};if(s.max_length!==void 0&&r.length>s.max_length)return{isValid:!1,error:typeof n.maxLength=="function"?n.maxLength(s.max_length):n.maxLength};if(s.regex&&!new RegExp(s.regex).test(r))return{isValid:!1,error:n.regex}}return{isValid:!0}}},Za={getValueOrDefault:e=>e.value??e.default_value??null,validate:(e,t,n)=>{const r=t;if(e.required&&r===null)return{isValid:!1,error:n.required};if(r===null)return{isValid:!0};const{rules:s}=e;if(s){if(s.min!==void 0&&r<s.min)return{isValid:!1,error:typeof n.min=="function"?n.min(s.min):n.min};if(s.max!==void 0&&r>s.max)return{isValid:!1,error:typeof n.max=="function"?n.max(s.max):n.max}}return{isValid:!0}}},Ja={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}}},Qa={getValueOrDefault:e=>e.values??e.default_values??null,validate:(e,t,n)=>{const r=t;if(e.required&&(!r||r.length===0))return{isValid:!1,error:n.required};if(!r||r.length===0)return{isValid:!0};if(r.filter(i=>!e.options.includes(i)).length>0)return{isValid:!1,error:n.invalidSelection};const{rules:a}=e;if(a){if(a.min_select!==void 0&&r.length<a.min_select)return{isValid:!1,error:typeof n.minSelect=="function"?n.minSelect(a.min_select):n.minSelect};if(a.max_select!==void 0&&r.length>a.max_select)return{isValid:!1,error:typeof n.maxSelect=="function"?n.maxSelect(a.max_select):n.maxSelect}}return{isValid:!0}}},ei={text:Xa,number:Za,"single-select":Ja,"multi-select":Qa},ti={getValueOrDefault:()=>null,validate:()=>({isValid:!1})};function Jr(e){return ei[e.type]||ti}function or(e){return Jr(e).getValueOrDefault(e)}function ni(e,t,n={}){const r={...Ya,...n};return Jr(e).validate(e,t,r)}const ri=(e,t={})=>{const{labels:n={},onSubmit:r,onCancel:s}=t,[a,i]=u.useState({}),[l,c]=u.useState(()=>{const b={};return e.fields.forEach(g=>{b[g.key]=or(g)}),b}),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 b={};let g=!1;e.fields.forEach(_=>{const y=or(_);JSON.stringify(l[_.key])!==JSON.stringify(y)&&(g=!0),b[_.key]=y}),g&&c(b)}},[d]);const m=(b,g)=>{c(_=>({..._,[b]:g})),i(_=>({..._,[b]:void 0}))},p=e.fields.map(b=>{var y,I,A;const g=l[b.key]??null,_={key:b.key,label:b.label,error:a[b.key],required:b.required};return b.type==="text"?{..._,type:"text",layout:b.layout,value:g,...b.placeholder&&{placeholder:b.placeholder},...((y=b.rules)==null?void 0:y.max_length)&&{maxLength:b.rules.max_length}}:b.type==="number"?{..._,type:"number",layout:b.layout,value:g,...b.placeholder&&{placeholder:b.placeholder},...((I=b.rules)==null?void 0:I.max)&&{max:b.rules.max}}:b.type==="single-select"?{..._,type:"single-select",layout:b.layout,value:g,options:b.options}:b.type==="multi-select"?{..._,type:"multi-select",layout:b.layout,value:g,options:b.options,...((A=b.rules)==null?void 0:A.max_select)&&{maxSelect:b.rules.max_select}}:{..._,type:"unknown",layout:"default",value:null}});return{state:d,fields:p,getField:b=>p.find(g=>g.key===b),updateFieldValue:m,submit:async()=>{const b={};let g=!1;for(const _ of e.fields){const y=l[_.key]??null,I=ni(_,y,n);I.isValid||(b[_.key]=I.error,g=!0)}if(i(b),!g&&r){const _={};e.fields.forEach(y=>{_[y.key]=l[y.key]??null}),await r(_)}},cancel:async()=>{await(s==null?void 0:s())}}},si=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},oi=e=>{const{aiAgentInfo:t}=at(),r=Xr(e)[0];if(!r)return null;const s=r.userId===(t==null?void 0:t.userId),a=s?si(r.metaData):void 0;return{user:s?t:r,isBot:s,thinkingMessage:a}},Qr=({channel:e,userSession:t,aiAgentInfo:n})=>{if(!t||!n||!e)return{fallbackIcon:"delight",url:void 0,title:""};const r=(()=>{const[a]=e.members.filter(i=>i.userId!==t.userId);return a})(),s={ai(a){return{fallbackIcon:a,url:n.profileUrl,title:n.nickname}},human(a){return{fallbackIcon:a,url:r==null?void 0:r.profileUrl,title:(r==null?void 0:r.nickname)||n.nickname}},channel(a){return{fallbackIcon:a,url:e==null?void 0:e.coverUrl,title:(e==null?void 0:e.name)??""}}};return e.isAIAgent?Ue(e)?s.human("agent"):s.ai("delight"):e.isDesk?s.human("agent"):s.channel("user")},ar=e=>u.useReducer((t,n)=>({...t,...n}),e);var he=(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))(he||{});const ai=new Set(["free_text","single_choice"]),ii=({csatPayload:e,type:t,initialCsat:n,initialCsatReason:r,initialIsResolved:s})=>{const[a,i]=ar({csatType:t,csat:n,csatReason:r,isResolved:s}),[l,c]=ar({followUpItem:!1}),d=u.useMemo(()=>{var g;const v=a.csat,x=typeof v=="number",b=(g=e.follow_up)==null?void 0:g.find(_=>x?_.scores.includes(v):_.always_visible??!1);if(ai.has(b==null?void 0:b.response_type))return b},[a.csat,e.follow_up]),m=(()=>{var v;if(typeof n=="number")return"submitted";if((t===he.AI_AGENT_CSAT_5||t===he.HELPDESK_CSAT_5)&&typeof a.csat=="number")return"submittable";if(t===he.AI_AGENT_CSAT_5_WITH_CRE){const x=typeof a.csat=="number",b=!((v=e.cre)!=null&&v.required)||typeof a.isResolved=="boolean";if(x&&b)return"submittable"}return"unsubmittable"})(),p=u.useCallback(()=>typeof a.csat>"u"?!1:d!=null&&d.required&&!a.csatReason?(c({followUpItem:!0}),!1):!0,[a,d,c]);return u.useEffect(()=>{r||(i({csatReason:""}),c({followUpItem:!1}))},[r,d,i,c]),{params:a,setParams:i,error:l,setError:c,followUpItem:d,state:m,validateParams:p,itemProps:{csatPayload:e,state:m,submitted:m==="submitted"}}},Qt=5,li=250,ci=50,ir=e=>Math.max(0,e-ci),ui=e=>e<1e3?{speed:Qt*.5,chunkSize:2}:e<2e3?{speed:Qt*.8,chunkSize:2}:{speed:Qt*.6,chunkSize:3},di=e=>{const{text:t,enabled:n=!1,onAnimationStart:r,onAnimationProgress:s,onAnimationComplete:a}=e,[i,l]=u.useState(()=>ir(t.length)),c=u.useRef(null),d=u.useRef({startTime:0,lastUpdate:0,lastProgressCall:0}).current,m=u.useRef({onStart:r,onProgress:s,onComplete:a}).current,p=u.useRef({startCalled:!1,completeCalled:!1}).current,E=u.useRef({initialEnabled:n,textLength:t.length,enabled:n}).current,v=n,x=i<t.length,b=E.initialEnabled&&(v||x);return u.useLayoutEffect(()=>{m.onStart=r,m.onProgress=s,m.onComplete=a,E.textLength=t.length,E.enabled=n}),u.useLayoutEffect(()=>{var g;E.initialEnabled&&(p.startCalled||(p.startCalled=!0,(g=m.onStart)==null||g.call(m)),l(_=>t.length<_?t.length:_))},[t]),u.useEffect(()=>{if(!E.initialEnabled)return;let g=ir(t.length);d.lastUpdate=0,d.startTime=0,d.lastProgressCall=0;const _=y=>{var O;d.lastUpdate===0&&(d.lastUpdate=y,d.startTime=y,d.lastProgressCall=y);const I=E.textLength,A=y-d.lastUpdate,$=y-d.startTime,{speed:k,chunkSize:S}=ui($),R=k*S;A>=R&&g<I&&(g=Math.min(g+S,I),l(g),d.lastUpdate=y),y-d.lastProgressCall>=li&&(d.lastProgressCall=y,(O=m.onProgress)==null||O.call(m)),(g<I||E.enabled)&&(c.current=requestAnimationFrame(_))};return c.current=requestAnimationFrame(_),()=>{var y;c.current&&cancelAnimationFrame(c.current),p.startCalled&&!p.completeCalled&&(p.completeCalled=!0,(y=m.onComplete)==null||y.call(m))}},[]),u.useEffect(()=>{var I;const g=E.initialEnabled&&p.startCalled,_=!n,y=i>=t.length&&t.length>0;g&&_&&y&&!p.completeCalled&&(p.completeCalled=!0,(I=m.onComplete)==null||I.call(m))},[n,i,t.length]),{streamText:E.initialEnabled?t.slice(0,i):t,isAnimating:b}},mi="1.21.2",le="sb-agent",me={ENTRY:`${le}-entry`,MODAL_ROOT:`${le}-modal-root`,WINDOW:`${le}-window`,LAUNCHER:`${le}-launcher`},_t=2147483647,Ve={MODAL:_t-1,TOOLTIP:_t-2,WINDOW:_t-3,LAUNCHER:_t-4},es=36,hi=100,gi=mi,On="noopener noreferrer nofollow";function fi(){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 Ct={};function pi(){return{get:e=>{try{return localStorage.getItem(e)}catch{return Ct[e]??null}},set:(e,t)=>{try{localStorage.setItem(e,t)}catch{Ct[e]=t}},delete:e=>{try{localStorage.removeItem(e)}catch{delete Ct[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(Ct).filter(t=>t.startsWith(e))}}}}const Ei='@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}',bi={conversation:{input_placeholder:"Ask a question",input_placeholder_disabled:"Chat is unavailable in this channel",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.",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"},conversation_list:{header_title:"Conversations",ended:"Ended",footer_title:"Start a conversation",multiple_files_count:e=>`${e} ${e===1?"file":"files"}`},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."},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"},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"}},gn={language:"en",strings:bi,dateLocale:Xs.enUS},ts=e=>({MESSAGE_INPUT__PLACE_HOLDER:e.conversation.input_placeholder,MESSAGE_INPUT__PLACE_HOLDER__DISABLED:e.conversation.input_placeholder_disabled,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__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,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,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,SCROLL_TO_NEW_MESSAGES_LABEL:e.conversation.scroll_to_new_messages_label}),_i=e=>{var t;return((t=e.split("-"))==null?void 0:t[0])??Nt},Nt="en",Ci=new Set([Nt,"ko","es","pt","fr","hi","it","de","tr","ja"]),xi=(e,t,n)=>{const r=e[t];return r?typeof r=="function"?r():Promise.resolve(r):new Promise((s,a)=>{(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(a.bind(null,new Error("Unknown variable dynamic import: "+t+(t.split("/").length!==n?". Note that variables only represent file names one level deep.":""))))})},lr=ts(gn.strings),vi={...lr,HEADER_BUTTON__AGENT_HANDOFF:"Connect with an agent",MESSAGE_INPUT__PLACE_HOLDER__SUGGESTED_REPLIES:"Select an option to continue",BUTTON__CANCEL:"Cancel",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_UPLOAD_FILES:"Files",FILE_VIEWER__UNSUPPORT:"Unsupported message",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",A11Y_ATTACH_FILE:"Attach file",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:lr.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",BUTTON__OK:"OK",NO_NAME:"(No name)",CHANNEL_FROZEN:"Channel frozen"},Tt={language:gn.language,dateLocale:gn.dateLocale,stringSet:vi},yi=Object.freeze(Object.defineProperty({__proto__:null,default:Tt},Symbol.toStringTag,{value:"Module"})),fn=new Map([[Nt,Tt]]);async function Si(e){const t=fn.get(e);if(t)return t;try{if(Ci.has(e)){const{default:n}=await xi(Object.assign({"./languages/de.ts":()=>Promise.resolve().then(()=>require("./cjs/DbxUqtQc.cjs")),"./languages/en.ts":()=>Promise.resolve().then(()=>yi),"./languages/es.ts":()=>Promise.resolve().then(()=>require("./cjs/DTCJ6-eC.cjs")),"./languages/fr.ts":()=>Promise.resolve().then(()=>require("./cjs/7UVs65zS.cjs")),"./languages/hi.ts":()=>Promise.resolve().then(()=>require("./cjs/DfRVurNO.cjs")),"./languages/it.ts":()=>Promise.resolve().then(()=>require("./cjs/JLk8Bvao.cjs")),"./languages/ja.ts":()=>Promise.resolve().then(()=>require("./cjs/BRnfdIkb.cjs")),"./languages/ko.ts":()=>Promise.resolve().then(()=>require("./cjs/BMS5Zb7W.cjs")),"./languages/pt.ts":()=>Promise.resolve().then(()=>require("./cjs/Dl0262MS.cjs")),"./languages/tr.ts":()=>Promise.resolve().then(()=>require("./cjs/DFmkiYPE.cjs"))}),`./languages/${e}.ts`,3);return fn.set(e,n),n}return Tt}catch{return Tt}}const{Provider:Ai,useContext:K}=te("Localization"),Ti=({language:e=navigator.language,logger:t,stringSet:n,children:r})=>{const[s,a]=u.useState(fn.get(Nt));return u.useEffect(()=>{const i=_i(e);s.language!==i&&(t==null||t.debug("localization.useEffect: update language",{from:s.language,to:i}),Si(i).then(a))},[e,t]),o.createElement(Ai,{value:{language:s.language,stringSet:{...s.stringSet,...n},dateLocale:s.dateLocale,format:(i,l,c)=>Fe.format(i,l,{locale:s.dateLocale,...c})}},r)},It="data-sb-agent-theme",cr=e=>(t,...n)=>{let r="";return t.forEach((s,a)=>{r+=s+(n[a]??"")}),`[${It}='${e}'] & { ${r} }`},F={light:cr("light"),dark:cr("dark")},Ii=w.css(({theme:e})=>{const{palette:t}=e;return`
|
|
2
2
|
:root,
|
|
3
3
|
:host {
|
|
4
4
|
--sendbird-primary-extra-dark: ${t.primary.extraDark};
|
|
@@ -47,15 +47,15 @@
|
|
|
47
47
|
--sendbird-overlay-dark: ${t.overlay.dark};
|
|
48
48
|
--sendbird-overlay-light: ${t.overlay.light};
|
|
49
49
|
}
|
|
50
|
-
`}),
|
|
50
|
+
`}),wi=w.css`[${It}='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-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);}[${It}='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-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);}`,f={color:{primary:{dark:"var(--sendbird-primary-dark)",main:"var(--sendbird-primary-main)"},information:{main:"var(--sendbird-information-main)",light:"var(--sendbird-information-light)"},background700:"var(--sendbird-background-700)",background600:"var(--sendbird-background-600)",background500:"var(--sendbird-background-500)",background400:"var(--sendbird-background-400)",background200:"var(--sendbird-background-200)",background100:"var(--sendbird-background-100)",background50:"var(--sendbird-background-50)",onlight:{textLowEmphasis:"var(--sendbird-onlight-text-low-emphasis)"},ondark:{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_200_400:"var(--sb-bg-200-400)",primary:"var(--sb-primary)",error:"var(--sb-error)",secondary:"var(--sb-secondary)"}},{Provider:ki,useContext:ns}=te("MessengerTheme");function Mi(e){const{theme:t,appearance:n,logger:r}=e;return o.createElement(Ca,{appearance:n,palette:t==null?void 0:t.palette,typography:t==null?void 0:t.typography,logger:r},o.createElement($i,{...e}))}function $i({rootElement:e=document.body,children:t}){const{theme:n,updateTheme:r}=$n();return u.useLayoutEffect(()=>{e.setAttribute(It,n.selectedTheme)},[e,n.selectedTheme]),o.createElement(w.ThemeProvider,{theme:n},o.createElement(ki,{value:{theme:n,updateTheme:r,rootElement:e}},t))}function He(e,t){const n=e.getRootNode({composed:t});return n instanceof ShadowRoot||n instanceof Document?n:document}const Li=(e,t)=>{u.useEffect(()=>{const n=He(t)instanceof ShadowRoot,r=He(t,!0);if(!(n?t:r).querySelector(`link[href*='${e}']`)){const a=r.createElement("link");a.rel="stylesheet",a.href=e,(n?t:r.head).appendChild(a)}},[e,t])},Ri=(e,t=document.body)=>{u.useEffect(()=>{const n=He(t),s=n instanceof ShadowRoot?t:n.head;if(!s)return;const a=`sba-${btoa(e).slice(0,10)}`;let i=s.querySelector(`style#${a}`);i?i.textContent!==e&&(i.textContent=e):(i=s.ownerDocument.createElement("style"),i.id=a,i.textContent=e,s.appendChild(i))},[e,t])},{Provider:Oi,Consumer:rs,useContext:j}=te("Messenger");function Di({children:e,state:t,enableCloseConversationButton:n=!1,enableExpandButton:r=!0,enableAutoDisconnectInLauncher:s=!0,...a}){const[i,l]=u.useState(!1),[c,d]=u.useState(!1),m={opened:(t==null?void 0:t.opened)??i,setOpened:(t==null?void 0:t.setOpened)??l,expanded:(t==null?void 0:t.expanded)??c,setExpanded:(t==null?void 0:t.setExpanded)??d};return o.createElement(sa,{...a},p=>o.createElement(Oi,{value:{...a,...p,state:m,enableCloseConversationButton:n,enableExpandButton:r,enableAutoDisconnectInLauncher:s}},e))}const ss=/iPad|iPhone|iPod/.test(navigator.userAgent),Ni=/Android/.test(navigator.userAgent),it=e=>ss||Ni;let Je=null,en=null;const Pi=(e,t=5e3)=>{Je&&(clearInterval(Je),clearTimeout(en));const n=document.title;Je=setInterval(()=>{document.title=document.title===e?n:e},750),en=setTimeout(()=>{clearInterval(Je),Je=null,en=null,document.title=n},t)},os=()=>{Promise.resolve().then(()=>require("./cjs/B93o4u0P.cjs")).then(e=>{new Audio(e.default).play().catch(()=>{})})},ge=e=>{const t=e;return typeof t=="number"?`${t}px`:t},M=({as:e,variant:t="body1",color:n,maxTextLines:r,className:s,...a})=>o.createElement(Ui,{as:e,$variant:t,className:s,$color:n,$maxTextLines:r,...a}),ur=new WeakMap,Fi=(e,t)=>{let n=ur.get(t);n||(n=new Map,ur.set(t,n));const r=n.get(e);if(r)return r;const s=t[e]??t.body1,a=w.css`font-size:${ge(s.fontSize)};font-weight:${s.fontWeight};${s.fontFamily?`font-family: ${s.fontFamily};`:""}
|
|
51
51
|
${s.lineHeight?`line-height: ${s.lineHeight};`:"line-height: 100%;"}
|
|
52
|
-
`;return n.set(e,a),a},Fi=e=>e?w.css`display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:${e};overflow:hidden;`:"",Bi=h.default.span`font-stretch:normal;letter-spacing:normal;${({$variant:e,theme:t})=>Pi(e,t.typography)}color:${({$color:e})=>e};${({$maxTextLines:e})=>Fi(e)}`,Pt=({style:e,rootElementId:t,visible:n,onClose:r,children:s})=>{if(!n)return null;const{rootElement:a}=ts(),i=He(a),l=He(a,!0);return Xs.createPortal(o.createElement(Ui,{onClick:r,style:e},o.createElement(Hi,{onClick:c=>c.stopPropagation()},s)),i.getElementById(t)??i.getElementById(de.MODAL_ROOT)??l.body)},Ui=h.default.div`position:fixed;top:0;left:0;width:100%;height:100%;background:${f.color.overlay.dark};display:flex;justify-content:center;align-items:center;z-index:${Ve.MODAL};`,Hi=h.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:${Ve.MODAL};`,Dn=({visible:e,title:t,description:n,confirmText:r="OK",onConfirm:s,onClose:a})=>{const i=()=>{s==null||s(),a()};return o.createElement(Pt,{rootElementId:de.WINDOW,visible:e,onClose:a},o.createElement(Vi,null,o.createElement(zi,null,t&&o.createElement(M,{variant:"h1",color:f.themedColor.textHighEmphasis},t),n&&o.createElement(Gi,null,o.createElement(M,{variant:"subtitle2",color:f.themedColor.textHighEmphasis},n))),o.createElement(qi,null,o.createElement(Wi,{onClick:i},o.createElement(M,{variant:"button",color:f.themedColor.primary},r)))))},Vi=h.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};`,zi=h.default.div`margin-bottom:16px;`,Gi=h.default.div`margin-top:8px;`,qi=h.default.div`display:flex;flex-direction:row;justify-content:flex-end;`,Wi=h.default.button`all:unset;display:flex;justify-content:center;align-items:center;border-radius:4px;cursor:pointer;background-color:transparent;padding:10px 16px;`,{Provider:Ki,useContext:oe}=te("MessengerSession"),ji=u.forwardRef(function({children:e,...t},n){return o.createElement(ya,{ref:n,...t},r=>o.createElement(Yi,{...r},e))}),Yi=({children:e,...t})=>{const{chatSDK:n,logger:r,appId:s,aiAgentId:a,agentPreviewConfigs:i,state:l,handlers:c,dispatcher:d,_aiAgentSDK:m}=j(),{userSessionInfo:p,authenticate:E,userSession:v,aiAgentInfo:x,launcherInfo:b}=t,[g,_]=u.useState(!1),y=u.useRef(null);Le.useGroupChannelHandler(n,{async onUserJoined(A,$){var S,R,P,O;A.conversation&&A.conversation.type===ee.ConversationType.PROACTIVE&&$.userId===((S=n.currentUser)==null?void 0:S.userId)&&(r.info("messengerSession.onUserJoined: proactive channel joined",A.url),(P=m.session)==null||P._updateActiveChannel({url:A.url,status:"open",conversationStatus:(R=A.conversation)==null?void 0:R.status}),l.setOpened(!0),Xi({sound:document.hidden||!l.opened}),(O=y.current)==null||O.call(y,{channel:A}))}}),u.useEffect(()=>{E().then(({launcher:A})=>{A.auto_open&&!it()&&setTimeout(()=>l.setOpened(!0),500)}).catch(A=>{var $;r.error("messengerSession: failed to initialize",A),($=c==null?void 0:c.onInitializeFailed)==null||$.call(c,A)})},[n,s,a,p==null?void 0:p.userId]),u.useEffect(()=>{const A=()=>_(!0);return d.subscribe(ce.AnonymousSessionTokenExpired,A),()=>d.unsubscribe(ce.AnonymousSessionTokenExpired,A)},[d]);const I=u.useCallback(()=>{t.deauthenticate().finally(()=>window.location.reload())},[t.deauthenticate]);return!v||!x||!b?null:o.createElement(Ki,{value:{...t,userSession:v,aiAgentInfo:{...x,...i==null?void 0:i.bot},launcherInfo:{...b,...i==null?void 0:i.launcher},registerOnJoinedProactiveConversation:A=>y.current=A}},e,o.createElement(Dn,{visible:g,title:"Session timed out",description:"Start a new conversation.",onConfirm:I,onClose:Ce}))};function Xi({sound:e}){Ni("🔔You have received a new message"),e&&ss()}const Zi=e=>{const{chatSDK:t,handlers:n,logger:r}=j(),{aiAgentInfo:s}=oe(),a=u.useRef(new Set),i=m=>{if(!(n!=null&&n.onCustomEvent))return;fe(m)&&m.sender.userId===s.userId&&!Me.isStreaming(m)&&!a.current.has(m.messageId)&&(r.debug("useCustomEventForMessageReceive: bot-message-received",m),n.onCustomEvent({type:"bot-message-received",data:{message:m}}),a.current.add(m.messageId))},l=m=>{if(n!=null&&n.onCustomEvent&&m.isAdminMessage()&&m.customType==="user_action_required"&&!a.current.has(m.messageId)){const p=cn(m.data);Array.isArray(p.history)&&p.history.length===0&&(r.debug("useCustomEventForMessageReceive: user_action_required",p),n.onCustomEvent({type:"user-action-requested",data:p}),a.current.add(m.messageId))}},c=(m,p)=>{m.url===e&&(i(p),l(p))},d=m=>{l(m)};return Le.useGroupChannelHandler(t,{onMessageUpdated:c,onMessageReceived:c}),{checkForUserActionRequired:d}},wt=`@${le}-focused-channel`,os=`${Date.now()}-${Math.random().toString(36).slice(2)}`,Ji=()=>{try{const e=localStorage.getItem(wt);return e?JSON.parse(e).channelUrl??null:null}catch{return null}},dr=e=>{try{localStorage.setItem(wt,JSON.stringify({channelUrl:e,tabId:os}))}catch{}},mr=()=>{try{const e=localStorage.getItem(wt);if(!e)return;JSON.parse(e).tabId===os&&localStorage.removeItem(wt)}catch{}},Qi=(e,t)=>(u.useEffect(()=>{if(!t||!e)return;const n=()=>dr(e),r=()=>mr();return document.hasFocus()&&dr(e),window.addEventListener("focus",n),window.addEventListener("blur",r),()=>{window.removeEventListener("focus",n),window.removeEventListener("blur",r),mr()}},[t,e]),{isChannelViewedInAnyTab:()=>document.hasFocus()||Ji()===e}),el=e=>{var i;const{config:t,chatSDK:n}=j(),{sdkUser:r}=oe(),s=!!((i=t==null?void 0:t.conversation)!=null&&i.messageAlertSoundEnabled),{isChannelViewedInAnyTab:a}=Qi(e,s);Le.useGroupChannelHandler(n,{onMessageReceived(l,c){if(!s||l.url!==e||a())return;(fe(c)&&c.sender.userId!==(r==null?void 0:r.userId)||c.isAdminMessage()&&!c.silent)&&ss()}})};function tl(e){return new Promise(t=>{const n=new Image;n.onload=function(){const r=String(n.width),s=String(n.height);URL.revokeObjectURL(n.src),t({width:r,height:s})},n.src=URL.createObjectURL(e)})}async function nl(e){if("file"in e&&e.file instanceof File&&e.file.type.startsWith("image/")){const{width:t,height:n}=await tl(e.file);return new ke.MessageMetaArray({key:Nr,value:[t,n]})}}const rl=({onScrollAfterSendMessage:e})=>{const{agentPreviewConfigs:t,handlers:n}=j(),r=u.useRef(t==null?void 0:t.agentAttributes);return r.current=t==null?void 0:t.agentAttributes,{onBeforeSendMessage:async s=>{const a=await nl(s),i={...s,metaArrays:a?[a]:void 0},l=sl(r.current);return l?{...i,data:JSON.stringify(l)}:i},onAfterSendMessage:s=>{var a,i,l;e(),(a=n==null?void 0:n.onMessageSend)==null||a.call(n,s.message),s.sendingStatus===ke.SendingStatus.SUCCEEDED?(i=n==null?void 0:n.onCustomEvent)==null||i.call(n,{type:"message-sent-succeeded",data:{message:s}}):s.sendingStatus===ke.SendingStatus.PENDING&&((l=n==null?void 0:n.onCustomEvent)==null||l.call(n,{type:"message-sent-pending",data:{message:s}}))}}},sl=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};async function Nn(e){let t=e;t&&(!t.startsWith("http://")&&!t.startsWith("https://")&&(t="https://"+t),window.open(t,"_blank","noopener,noreferrer"))}function kt(e){requestAnimationFrame(()=>{requestAnimationFrame(()=>{e()})})}const je=50,tn=je-40,{Provider:ol,useContext:as}=te("ConversationScroll"),hr={viewport:0,contentHeight:0,contentSnapshotHeight:0,shouldRecalc:!1,shouldUpdate:!1},nn=e=>Math.max(0,e.scrollHeight-e.scrollTop-e.clientHeight);function al({scrollMode:e,messageStackDirection:t,children:n}){const r=u.useRef(null),s=u.useRef(null),a=u.useRef(0),i=u.useRef(0),l=u.useRef(!1),c=u.useRef(!1),d=u.useRef(null),m=u.useRef(hr),p=u.useRef(!1),E=u.useRef(null),[v,x]=u.useState(0),[b,g]=u.useState(0),[_,y]=u.useState(!1),[I,A]=u.useState(!1),[$,k]=u.useState(!0),S=D=>{const V=nn(D);return a.current=V,g(V),V},R=()=>{d.current&&(clearTimeout(d.current),d.current=null)},P=u.useMemo(()=>_||t==="bottom"?"auto":e,[_,t,e]),O=()=>{m.current.contentSnapshotHeight=m.current.contentHeight,m.current.shouldUpdate=!0,m.current.shouldRecalc=!0},T=()=>{const D=r.current;!D||!m.current.shouldUpdate||x(V=>{m.current.shouldUpdate=!1;const{contentHeight:W,contentSnapshotHeight:Q,shouldRecalc:ae}=m.current,ie=D.clientHeight;if(Q>W)return V;const qe=B(D,{messageType:"outgoing"});let Ae=0;if(qe){const re=qe.message.offsetTop-tn+ie;Ae=Math.max(0,re-W)}else{const re=W-Q,Te=ie-tn;Ae=Math.max(0,re-Te)}return V===0||Ae!==V||ae?(m.current.shouldRecalc=!1,Ae):V})},B=u.useCallback((D,V)=>{const{messageType:W="all"}=V??{},Q=Array.from(D.querySelectorAll(`#${le}-message-item`));let ae=Q;W==="outgoing"&&(ae=Q.filter(gt=>gt.getAttribute("data-layout-id")==="outgoingmessage"));const ie=ae[ae.length-1];if(!ie)return null;const qe=D.getBoundingClientRect(),Ae=ie.getBoundingClientRect(),re=D.scrollTop+(Ae.top-qe.top),Te=re+ie.offsetHeight;return{message:ie,scrollTop:re,lastMessageBottom:Te}},[]),N=u.useCallback(()=>{const D=r.current;if(!D||P!=="fixed")return;const V=B(D);m.current.contentHeight=(V==null?void 0:V.lastMessageBottom)??D.scrollHeight,!p.current&&m.current.contentSnapshotHeight>0&&O(),c.current?a.current=nn(D):S(D),T()},[P,B]),z=u.useCallback(()=>{s.current&&(s.current.disconnect(),s.current=null),R(),m.current=hr,x(0),g(0),k(!0),a.current=0,l.current=!1,i.current=0,c.current=!1},[]),Y=u.useCallback((D=!0)=>{const V=a.current>je;if(l.current=!1,g(0),!V){kt(()=>{const W=r.current;W&&!l.current&&W.scrollTo({top:W.scrollHeight,behavior:"auto"})});return}c.current||(c.current=!0,k(!1),R()),kt(()=>{const W=r.current;if(!W){c.current=!1,k(!0);return}if(l.current){c.current=!1,S(W),k(!0);return}const Q=()=>{if(r.current!==W){c.current=!1,r.current&&S(r.current),k(!0);return}c.current=!1,S(W),k(!0)};if(D&&!d.current){const ae=setTimeout(Q,500);d.current=ae,W.addEventListener("scrollend",()=>{clearTimeout(ae),d.current=null,Q()},{once:!0})}W.scrollTo({top:W.scrollHeight,behavior:D?"smooth":"auto"}),D||Q()})},[]),G=u.useCallback(D=>{D&&(r.current=D,P==="fixed"&&(z(),m.current.viewport=D.clientHeight,s.current=new MutationObserver(()=>{N()}),s.current.observe(D,{childList:!0,subtree:!0})))},[P,N,z]),ye=u.useCallback(()=>{const D=r.current;if(!D)return;const V=B(D,{messageType:"outgoing"});V&&(D.scrollTo({top:V.message.offsetTop-tn,behavior:"smooth"}),E.current&&clearTimeout(E.current),E.current=setTimeout(()=>{A(!1)},500))},[B]),mt=(D,V,W)=>{const Q=nn(D);if(W&&Q>je){c.current=!1,l.current=!0,R(),S(D),k(!0),i.current=V;return}a.current=Q},L=(D,V,W)=>{const ae=S(D)<=je;V&&!ae&&(l.current=!0,R()),W&&ae&&(l.current=!1)},Ne=D=>{const{scrollTop:V}=D.currentTarget,W=i.current;c.current?mt(D.currentTarget,V,V<W):L(D.currentTarget,V<W,V>W),i.current=V},Ge=u.useCallback(()=>{P==="fixed"&&(A(!0),O())},[P]),Se=u.useCallback(()=>{P==="fixed"?setTimeout(()=>ye(),300):Y()},[P,ye]),qt=u.useCallback(D=>{p.current=D,P==="fixed"?O():l.current||Y()},[P,Y]),Wt=u.useCallback(D=>{y(D),D&&(x(0),s.current&&(s.current.disconnect(),s.current=null))},[]),Kt=u.useCallback(D=>{P==="auto"&&D&&!l.current&&Y()},[P,Y]),jt=!(b<=je)&&!I,Yt=u.useCallback(()=>a.current>je,[]);return o.createElement(ol,{value:{ref:G,state:{bottomSpace:v,isAwayFromBottom:jt,isScrollPositionReconciled:$,shouldCountNewMessages:Yt},props:{onScroll:Ne},actions:{scrollToBottom:Y,onBeforeMessageSend:Ge,onAfterMessageSend:Se,onStreamingUpdate:qt,onConversationClosed:Wt,onTypingIndicatorUpdate:Kt}}},n)}const{Provider:il,Context:ll,useContext:ne}=te("Conversation"),cl=({children:e})=>{var s;const{channelSource:t}=ne(),n=(s=t.channel)==null?void 0:s.url,{checkForUserActionRequired:r}=Zi(n);return u.useEffect(()=>{var i;const a=(i=t.channel)==null?void 0:i.lastMessage;a&&r(a)},[t.channel,r]),o.createElement(o.Fragment,null,e)},ul=({channelUrl:e,onClearChannelUrl:t,onNavigateToConversationList:n,shouldMarkAsRead:r,children:s})=>{const{activeChannel:a,refreshActiveChannel:i}=oe(),l=as(),c=e||(a==null?void 0:a.url);el(c);const{onBeforeSendMessage:d,onAfterSendMessage:m}=rl({onScrollAfterSendMessage:()=>{l.actions.onAfterMessageSend()}}),p=u.useCallback(x=>(l.actions.onBeforeMessageSend(),d(x)),[l.actions,d]),E=u.useCallback(x=>{const b=x.some(g=>Me.isStreaming(g));l.actions.onStreamingUpdate(b)},[l.actions.onStreamingUpdate]),v=u.useCallback(async()=>{await i(),e&&(t==null||t())},[i,e,t]);return o.createElement(Oa,{key:c,channelUrl:c,onBeforeSendMessage:p,onAfterSendMessage:m,onMessagesUpdated:E,onMessagesReceived:E,onChannelDeleted:v,onConversationClosedStatusChanged:l.actions.onConversationClosed,shouldMarkAsRead:r,shouldCountNewMessages:l.state.shouldCountNewMessages},x=>o.createElement(il,{value:{...x,scrollSource:l,goToActiveConversation:v,onNavigateToConversationList:n}},o.createElement(cl,null,s)))},is=({children:e,...t})=>{var i;const{config:n}=me(),{agentPreviewConfigs:r}=j(),s=((i=n==null?void 0:n.conversation)==null?void 0:i.scrollMode)??"auto",a=r==null?void 0:r.messageStackDirection;return o.createElement(al,{scrollMode:s,messageStackDirection:a},o.createElement(ul,{...t},e))},Pn=u.createContext({onDrop:Ce,subscribe:()=>Ce}),pn=({children:e})=>{const t=u.useRef(new Set);return o.createElement(Pn.Provider,{value:{onDrop:n=>{var r;if(n.preventDefault(),(r=n.dataTransfer)!=null&&r.files){const s=Array.from(n.dataTransfer.files);s.length>0&&t.current.forEach(a=>a(s))}},subscribe:n=>(t.current.add(n),()=>t.current.delete(n))}},e)},dl=({onDropFiles:e})=>{const{subscribe:t}=u.useContext(Pn);u.useEffect(()=>t(e),[e])};pn.Consumer=({children:e})=>{const{onDrop:t}=u.useContext(Pn);return e({onDrop:t,onDragOver:s=>s.preventDefault()})};class Mt 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:s}=this.props;return this.state.hasError?n:o.createElement(u.Suspense,{fallback:r},s)}}const ml=e=>o.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",...e},o.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"})),hl=e=>o.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 16 16",...e},o.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"})),gl=e=>o.createElement("svg",{viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg",...e},o.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"})),fl=e=>o.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",fill:"evenodd",...e},o.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"})),pl=e=>o.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",...e},o.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"})),El=new Set(["send","chat","message","chevron-right","good","good-filled","bad","bad-filled"]),bl={close:ml,send:pl,menu:fl,expand:gl,collapse:hl,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"))),info:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/ohTjxqcW.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"))),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"))),delete:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/CKPzhVy2.cjs"))),"close-filled":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/D1kINslt.cjs"))),agent:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/Ce1MzjFq.cjs"))),question:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/JA0x62Fd.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"))),bot:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/PhHbzZB_.cjs"))),"bot-filled":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DlvMdI1f.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"))),"arrow-left":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/CZIjo9nb.cjs"))),add:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DEGDJBmd.cjs"))),document:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DBHlAmeA.cjs")))},U=({type:e,size:t=24,className:n,color:r})=>{const s=bl[e];return o.createElement(Cl,{className:n,$rtlFlip:El.has(e),$size:t,$color:r??f.color.primary.main},o.createElement(Mt,{errorFallback:o.createElement(xl,null)},o.createElement(s,null)))},_l=w.css`[dir='rtl'] &{transform:scaleX(-1);}`,Cl=h.default.div`width:${({$size:e})=>ge(e)};height:${({$size:e})=>ge(e)};display:inline-block;&:focus{outline:none;}svg{display:block;}[class*='fill']{fill:${({$color:e})=>e};}[class*='stroke']{stroke:${({$color:e})=>e};stroke-width:2px;stroke-linejoin:round;}${({$rtlFlip:e})=>e&&_l};`,xl=()=>o.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64"},o.createElement("rect",{x:"8",y:"8",width:"48",height:"48",fill:"none",className:"stroke",rx:"4"}),o.createElement("line",{x1:"20",y1:"20",x2:"44",y2:"44",className:"stroke"}),o.createElement("line",{x1:"44",y1:"20",x2:"20",y2:"44",className:"stroke"})),vl=.75,ls=6,yl=ls*2;let En=null;typeof Intl<"u"&&"Segmenter"in Intl&&(En=new Intl.Segmenter(void 0,{granularity:"grapheme"}));const Sl=e=>En?Array.from(En.segment(e),t=>t.segment):[...e],Al=e=>{const t=Math.floor(e.length*vl),n=Math.max(0,e.length-ls);return Math.max(t,n)},gr=(e,t="")=>{if(e.length<yl)return{start:e+t,end:""};const n=Sl(e),r=Al(n);return{start:n.slice(0,r).join(""),end:n.slice(r).join("")+t}},Tl=e=>{const t=e.normalize("NFC").trim(),n=t.lastIndexOf(".");if(!(n>0&&n<t.length-1))return gr(t);const s=t.slice(0,n),a=t.slice(n);return gr(s,a)},cs=({children:e,...t})=>{const{start:n,end:r}=u.useMemo(()=>Tl(e),[e]);return r?o.createElement(Il,null,o.createElement(wl,{...t},n),o.createElement(kl,{...t},r)):o.createElement(M,{...t},n)},Il=h.default.span`display:flex;width:100%;min-width:0;overflow:hidden;direction:inherit;`,wl=h.default(M)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex-shrink:1;min-width:0;`,kl=h.default(M)`flex-shrink:0;white-space:nowrap;`,Fn=({name:e,type:t="FILE",iconColor:n,iconBackgroundColor:r,onClick:s})=>{const{colors:a}=w.useTheme();return o.createElement(Ml,{onClick:s,$clickable:!!s},o.createElement(Ll,{$bgColor:r??a.base.primary},o.createElement(U,{type:"file-document",size:24,color:n??a.base.primaryContrastContent})),o.createElement(Rl,null,o.createElement(cs,{variant:"button",color:f.themedColor.textHighEmphasis},e),o.createElement(M,{color:f.themedColor.textMidEmphasis,variant:"caption3"},t)))},Ml=h.default.div`border-radius:12px;gap:8px;width:${H.BODY_MAX_WIDTH}px;height:64px;display:flex;align-items:center;padding:12px;box-sizing:border-box;border:1px solid ${f.themedColor.textDisabled};background-color:${f.themedColor.bg_50_600};${({$clickable:e})=>e&&$l}`,$l=w.css`cursor:pointer;&:hover{background-color:${f.themedColor.bg_100_500};}`,Ll=h.default.div`border-radius:8px;width:40px;height:40px;display:flex;align-items:center;justify-content:center;background-color:${({$bgColor:e})=>e};`,Rl=h.default.div`display:flex;flex:1;flex-direction:column;gap:4px;min-width:0;`;function Ol({file:e,children:t,onClickFile:n}){return o.createElement(Dl,null,o.createElement(Fn,{name:e.name,type:vn(e.name,e.type),onClick:n&&(()=>n==null?void 0:n(e))}),t)}const Dl=h.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${H.GAP_GROUPED}px;`,xe=`${le}-incoming-msg`,Nl=`${le}-marked-text`;function Pl({file:e,onClickMedia:t,onClickMediaFiles:n,children:r}){const s=()=>{n?n({files:[{url:e.url,type:e.type,name:e.name}],index:0}):t&&t(e)},a=()=>e.type.startsWith("image")?o.createElement(Ul,{src:e.url,alt:"image-message"}):e.type.startsWith("video")?o.createElement(Hl,{controls:!0},o.createElement("source",{src:e.url}),o.createElement("track",{kind:"captions"})):null;if(a){const i={id:`${xe}-media-body`,onClick:s};return o.createElement(Fl,null,o.createElement(Bl,{...i},a()),r)}return null}const Fl=h.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${H.GAP_GROUPED}px;`,Bl=h.default.div`width:${H.BODY_MAX_WIDTH}px;height:160px;border-radius:12px;overflow:hidden;cursor:pointer;${F.light`
|
|
52
|
+
`;return n.set(e,a),a},Bi=e=>e?w.css`display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:${e};overflow:hidden;`:"",Ui=h.default.span`font-stretch:normal;letter-spacing:normal;${({$variant:e,theme:t})=>Fi(e,t.typography)}color:${({$color:e})=>e};${({$maxTextLines:e})=>Bi(e)}`,Pt=({style:e,rootElementId:t,visible:n,onClose:r,children:s})=>{if(!n)return null;const{rootElement:a}=ns(),i=He(a),l=He(a,!0);return Zs.createPortal(o.createElement(Hi,{onClick:r,style:e},o.createElement(Vi,{onClick:c=>c.stopPropagation()},s)),i.getElementById(t)??i.getElementById(me.MODAL_ROOT)??l.body)},Hi=h.default.div`position:fixed;top:0;left:0;width:100%;height:100%;background:${f.color.overlay.dark};display:flex;justify-content:center;align-items:center;z-index:${Ve.MODAL};`,Vi=h.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:${Ve.MODAL};`,Dn=({visible:e,title:t,description:n,confirmText:r="OK",onConfirm:s,onClose:a})=>{const i=()=>{s==null||s(),a()};return o.createElement(Pt,{rootElementId:me.WINDOW,visible:e,onClose:a},o.createElement(zi,null,o.createElement(Gi,null,t&&o.createElement(M,{variant:"h1",color:f.themedColor.textHighEmphasis},t),n&&o.createElement(qi,null,o.createElement(M,{variant:"subtitle2",color:f.themedColor.textHighEmphasis},n))),o.createElement(Wi,null,o.createElement(Ki,{onClick:i},o.createElement(M,{variant:"button",color:f.themedColor.primary},r)))))},zi=h.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};`,Gi=h.default.div`margin-bottom:16px;`,qi=h.default.div`margin-top:8px;`,Wi=h.default.div`display:flex;flex-direction:row;justify-content:flex-end;`,Ki=h.default.button`all:unset;display:flex;justify-content:center;align-items:center;border-radius:4px;cursor:pointer;background-color:transparent;padding:10px 16px;`,{Provider:ji,useContext:oe}=te("MessengerSession"),Yi=u.forwardRef(function({children:e,...t},n){return o.createElement(Sa,{ref:n,...t},r=>o.createElement(Xi,{...r},e))}),Xi=({children:e,...t})=>{const{chatSDK:n,logger:r,appId:s,aiAgentId:a,agentPreviewConfigs:i,state:l,handlers:c,dispatcher:d,_aiAgentSDK:m}=j(),{userSessionInfo:p,authenticate:E,userSession:v,aiAgentInfo:x,launcherInfo:b}=t,[g,_]=u.useState(!1),y=u.useRef(null);Le.useGroupChannelHandler(n,{async onUserJoined(A,$){var S,R,P,O;A.conversation&&A.conversation.type===ee.ConversationType.PROACTIVE&&$.userId===((S=n.currentUser)==null?void 0:S.userId)&&(r.info("messengerSession.onUserJoined: proactive channel joined",A.url),(P=m.session)==null||P._updateActiveChannel({url:A.url,status:"open",conversationStatus:(R=A.conversation)==null?void 0:R.status}),l.setOpened(!0),Zi({sound:document.hidden||!l.opened}),(O=y.current)==null||O.call(y,{channel:A}))}}),u.useEffect(()=>{E().then(({launcher:A})=>{A.auto_open&&!it()&&setTimeout(()=>l.setOpened(!0),500)}).catch(A=>{var $;r.error("messengerSession: failed to initialize",A),($=c==null?void 0:c.onInitializeFailed)==null||$.call(c,A)})},[n,s,a,p==null?void 0:p.userId]),u.useEffect(()=>{const A=()=>_(!0);return d.subscribe(ue.AnonymousSessionTokenExpired,A),()=>d.unsubscribe(ue.AnonymousSessionTokenExpired,A)},[d]);const I=u.useCallback(()=>{t.deauthenticate().finally(()=>window.location.reload())},[t.deauthenticate]);return!v||!x||!b?null:o.createElement(ji,{value:{...t,userSession:v,aiAgentInfo:{...x,...i==null?void 0:i.bot},launcherInfo:{...b,...i==null?void 0:i.launcher},registerOnJoinedProactiveConversation:A=>y.current=A}},e,o.createElement(Dn,{visible:g,title:"Session timed out",description:"Start a new conversation.",onConfirm:I,onClose:Ce}))};function Zi({sound:e}){Pi("🔔You have received a new message"),e&&os()}const Ji=e=>{const{chatSDK:t,handlers:n,logger:r}=j(),{aiAgentInfo:s}=oe(),a=u.useRef(new Set),i=m=>{if(!(n!=null&&n.onCustomEvent))return;fe(m)&&m.sender.userId===s.userId&&!Me.isStreaming(m)&&!a.current.has(m.messageId)&&(r.debug("useCustomEventForMessageReceive: bot-message-received",m),n.onCustomEvent({type:"bot-message-received",data:{message:m}}),a.current.add(m.messageId))},l=m=>{if(n!=null&&n.onCustomEvent&&m.isAdminMessage()&&m.customType==="user_action_required"&&!a.current.has(m.messageId)){const p=cn(m.data);Array.isArray(p.history)&&p.history.length===0&&(r.debug("useCustomEventForMessageReceive: user_action_required",p),n.onCustomEvent({type:"user-action-requested",data:p}),a.current.add(m.messageId))}},c=(m,p)=>{m.url===e&&(i(p),l(p))},d=m=>{l(m)};return Le.useGroupChannelHandler(t,{onMessageUpdated:c,onMessageReceived:c}),{checkForUserActionRequired:d}},wt=`@${le}-focused-channel`,as=`${Date.now()}-${Math.random().toString(36).slice(2)}`,Qi=()=>{try{const e=localStorage.getItem(wt);return e?JSON.parse(e).channelUrl??null:null}catch{return null}},dr=e=>{try{localStorage.setItem(wt,JSON.stringify({channelUrl:e,tabId:as}))}catch{}},mr=()=>{try{const e=localStorage.getItem(wt);if(!e)return;JSON.parse(e).tabId===as&&localStorage.removeItem(wt)}catch{}},el=(e,t)=>(u.useEffect(()=>{if(!t||!e)return;const n=()=>dr(e),r=()=>mr();return document.hasFocus()&&dr(e),window.addEventListener("focus",n),window.addEventListener("blur",r),()=>{window.removeEventListener("focus",n),window.removeEventListener("blur",r),mr()}},[t,e]),{isChannelViewedInAnyTab:()=>document.hasFocus()||Qi()===e}),tl=e=>{var i;const{config:t,chatSDK:n}=j(),{sdkUser:r}=oe(),s=!!((i=t==null?void 0:t.conversation)!=null&&i.messageAlertSoundEnabled),{isChannelViewedInAnyTab:a}=el(e,s);Le.useGroupChannelHandler(n,{onMessageReceived(l,c){if(!s||l.url!==e||a())return;(fe(c)&&c.sender.userId!==(r==null?void 0:r.userId)||c.isAdminMessage()&&!c.silent)&&os()}})};function nl(e){return new Promise(t=>{const n=new Image;n.onload=function(){const r=String(n.width),s=String(n.height);URL.revokeObjectURL(n.src),t({width:r,height:s})},n.src=URL.createObjectURL(e)})}async function rl(e){if("file"in e&&e.file instanceof File&&e.file.type.startsWith("image/")){const{width:t,height:n}=await nl(e.file);return new ke.MessageMetaArray({key:Nr,value:[t,n]})}}const sl=({onScrollAfterSendMessage:e})=>{const{agentPreviewConfigs:t,handlers:n}=j(),r=u.useRef(t==null?void 0:t.agentAttributes);return r.current=t==null?void 0:t.agentAttributes,{onBeforeSendMessage:async s=>{const a=await rl(s),i={...s,metaArrays:a?[a]:void 0},l=ol(r.current);return l?{...i,data:JSON.stringify(l)}:i},onAfterSendMessage:s=>{var a,i,l;e(),(a=n==null?void 0:n.onMessageSend)==null||a.call(n,s.message),s.sendingStatus===ke.SendingStatus.SUCCEEDED?(i=n==null?void 0:n.onCustomEvent)==null||i.call(n,{type:"message-sent-succeeded",data:{message:s}}):s.sendingStatus===ke.SendingStatus.PENDING&&((l=n==null?void 0:n.onCustomEvent)==null||l.call(n,{type:"message-sent-pending",data:{message:s}}))}}},ol=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};async function Nn(e){let t=e;t&&(!t.startsWith("http://")&&!t.startsWith("https://")&&(t="https://"+t),window.open(t,"_blank","noopener,noreferrer"))}function kt(e){requestAnimationFrame(()=>{requestAnimationFrame(()=>{e()})})}const je=50,tn=je-40,{Provider:al,useContext:is}=te("ConversationScroll"),hr={viewport:0,contentHeight:0,contentSnapshotHeight:0,shouldRecalc:!1,shouldUpdate:!1},nn=e=>Math.max(0,e.scrollHeight-e.scrollTop-e.clientHeight);function il({scrollMode:e,messageStackDirection:t,children:n}){const r=u.useRef(null),s=u.useRef(null),a=u.useRef(0),i=u.useRef(0),l=u.useRef(!1),c=u.useRef(!1),d=u.useRef(null),m=u.useRef(hr),p=u.useRef(!1),E=u.useRef(null),[v,x]=u.useState(0),[b,g]=u.useState(0),[_,y]=u.useState(!1),[I,A]=u.useState(!1),[$,k]=u.useState(!0),S=D=>{const V=nn(D);return a.current=V,g(V),V},R=()=>{d.current&&(clearTimeout(d.current),d.current=null)},P=u.useMemo(()=>_||t==="bottom"?"auto":e,[_,t,e]),O=()=>{m.current.contentSnapshotHeight=m.current.contentHeight,m.current.shouldUpdate=!0,m.current.shouldRecalc=!0},T=()=>{const D=r.current;!D||!m.current.shouldUpdate||x(V=>{m.current.shouldUpdate=!1;const{contentHeight:W,contentSnapshotHeight:Q,shouldRecalc:ae}=m.current,ie=D.clientHeight;if(Q>W)return V;const qe=B(D,{messageType:"outgoing"});let Ae=0;if(qe){const re=qe.message.offsetTop-tn+ie;Ae=Math.max(0,re-W)}else{const re=W-Q,Te=ie-tn;Ae=Math.max(0,re-Te)}return V===0||Ae!==V||ae?(m.current.shouldRecalc=!1,Ae):V})},B=u.useCallback((D,V)=>{const{messageType:W="all"}=V??{},Q=Array.from(D.querySelectorAll(`#${le}-message-item`));let ae=Q;W==="outgoing"&&(ae=Q.filter(gt=>gt.getAttribute("data-layout-id")==="outgoingmessage"));const ie=ae[ae.length-1];if(!ie)return null;const qe=D.getBoundingClientRect(),Ae=ie.getBoundingClientRect(),re=D.scrollTop+(Ae.top-qe.top),Te=re+ie.offsetHeight;return{message:ie,scrollTop:re,lastMessageBottom:Te}},[]),N=u.useCallback(()=>{const D=r.current;if(!D||P!=="fixed")return;const V=B(D);m.current.contentHeight=(V==null?void 0:V.lastMessageBottom)??D.scrollHeight,!p.current&&m.current.contentSnapshotHeight>0&&O(),c.current?a.current=nn(D):S(D),T()},[P,B]),z=u.useCallback(()=>{s.current&&(s.current.disconnect(),s.current=null),R(),m.current=hr,x(0),g(0),k(!0),a.current=0,l.current=!1,i.current=0,c.current=!1},[]),Y=u.useCallback((D=!0)=>{const V=a.current>je;if(l.current=!1,g(0),!V){kt(()=>{const W=r.current;W&&!l.current&&W.scrollTo({top:W.scrollHeight,behavior:"auto"})});return}c.current||(c.current=!0,k(!1),R()),kt(()=>{const W=r.current;if(!W){c.current=!1,k(!0);return}if(l.current){c.current=!1,S(W),k(!0);return}const Q=()=>{if(r.current!==W){c.current=!1,r.current&&S(r.current),k(!0);return}c.current=!1,S(W),k(!0)};if(D&&!d.current){const ae=setTimeout(Q,500);d.current=ae,W.addEventListener("scrollend",()=>{clearTimeout(ae),d.current=null,Q()},{once:!0})}W.scrollTo({top:W.scrollHeight,behavior:D?"smooth":"auto"}),D||Q()})},[]),G=u.useCallback(D=>{D&&(r.current=D,P==="fixed"&&(z(),m.current.viewport=D.clientHeight,s.current=new MutationObserver(()=>{N()}),s.current.observe(D,{childList:!0,subtree:!0})))},[P,N,z]),ye=u.useCallback(()=>{const D=r.current;if(!D)return;const V=B(D,{messageType:"outgoing"});V&&(D.scrollTo({top:V.message.offsetTop-tn,behavior:"smooth"}),E.current&&clearTimeout(E.current),E.current=setTimeout(()=>{A(!1)},500))},[B]),mt=(D,V,W)=>{const Q=nn(D);if(W&&Q>je){c.current=!1,l.current=!0,R(),S(D),k(!0),i.current=V;return}a.current=Q},L=(D,V,W)=>{const ae=S(D)<=je;V&&!ae&&(l.current=!0,R()),W&&ae&&(l.current=!1)},Ne=D=>{const{scrollTop:V}=D.currentTarget,W=i.current;c.current?mt(D.currentTarget,V,V<W):L(D.currentTarget,V<W,V>W),i.current=V},Ge=u.useCallback(()=>{P==="fixed"&&(A(!0),O())},[P]),Se=u.useCallback(()=>{P==="fixed"?setTimeout(()=>ye(),300):Y()},[P,ye]),qt=u.useCallback(D=>{p.current=D,P==="fixed"?O():l.current||Y()},[P,Y]),Wt=u.useCallback(D=>{y(D),D&&(x(0),s.current&&(s.current.disconnect(),s.current=null))},[]),Kt=u.useCallback(D=>{P==="auto"&&D&&!l.current&&Y()},[P,Y]),jt=!(b<=je)&&!I,Yt=u.useCallback(()=>a.current>je,[]);return o.createElement(al,{value:{ref:G,state:{bottomSpace:v,isAwayFromBottom:jt,isScrollPositionReconciled:$,shouldCountNewMessages:Yt},props:{onScroll:Ne},actions:{scrollToBottom:Y,onBeforeMessageSend:Ge,onAfterMessageSend:Se,onStreamingUpdate:qt,onConversationClosed:Wt,onTypingIndicatorUpdate:Kt}}},n)}const{Provider:ll,Context:cl,useContext:ne}=te("Conversation"),ul=({children:e})=>{var s;const{channelSource:t}=ne(),n=(s=t.channel)==null?void 0:s.url,{checkForUserActionRequired:r}=Ji(n);return u.useEffect(()=>{var i;const a=(i=t.channel)==null?void 0:i.lastMessage;a&&r(a)},[t.channel,r]),o.createElement(o.Fragment,null,e)},dl=({channelUrl:e,onClearChannelUrl:t,onNavigateToConversationList:n,shouldMarkAsRead:r,children:s})=>{const{activeChannel:a,refreshActiveChannel:i}=oe(),l=is(),c=e||(a==null?void 0:a.url);tl(c);const{onBeforeSendMessage:d,onAfterSendMessage:m}=sl({onScrollAfterSendMessage:()=>{l.actions.onAfterMessageSend()}}),p=u.useCallback(x=>(l.actions.onBeforeMessageSend(),d(x)),[l.actions,d]),E=u.useCallback(x=>{const b=x.some(g=>Me.isStreaming(g));l.actions.onStreamingUpdate(b)},[l.actions.onStreamingUpdate]),v=u.useCallback(async()=>{await i(),e&&(t==null||t())},[i,e,t]);return o.createElement(Da,{key:c,channelUrl:c,onBeforeSendMessage:p,onAfterSendMessage:m,onMessagesUpdated:E,onMessagesReceived:E,onChannelDeleted:v,onConversationClosedStatusChanged:l.actions.onConversationClosed,shouldMarkAsRead:r,shouldCountNewMessages:l.state.shouldCountNewMessages},x=>o.createElement(ll,{value:{...x,scrollSource:l,goToActiveConversation:v,onNavigateToConversationList:n}},o.createElement(ul,null,s)))},ls=({children:e,...t})=>{var i;const{config:n}=ce(),{agentPreviewConfigs:r}=j(),s=((i=n==null?void 0:n.conversation)==null?void 0:i.scrollMode)??"auto",a=r==null?void 0:r.messageStackDirection;return o.createElement(il,{scrollMode:s,messageStackDirection:a},o.createElement(dl,{...t},e))},Pn=u.createContext({onDrop:Ce,subscribe:()=>Ce}),pn=({children:e})=>{const t=u.useRef(new Set);return o.createElement(Pn.Provider,{value:{onDrop:n=>{var r;if(n.preventDefault(),(r=n.dataTransfer)!=null&&r.files){const s=Array.from(n.dataTransfer.files);s.length>0&&t.current.forEach(a=>a(s))}},subscribe:n=>(t.current.add(n),()=>t.current.delete(n))}},e)},ml=({onDropFiles:e})=>{const{subscribe:t}=u.useContext(Pn);u.useEffect(()=>t(e),[e])};pn.Consumer=({children:e})=>{const{onDrop:t}=u.useContext(Pn);return e({onDrop:t,onDragOver:s=>s.preventDefault()})};class Mt 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:s}=this.props;return this.state.hasError?n:o.createElement(u.Suspense,{fallback:r},s)}}const hl=e=>o.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",...e},o.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"})),gl=e=>o.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 16 16",...e},o.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"})),fl=e=>o.createElement("svg",{viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg",...e},o.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"})),pl=e=>o.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",fill:"evenodd",...e},o.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"})),El=e=>o.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",...e},o.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"})),bl=new Set(["send","chat","message","chevron-right","good","good-filled","bad","bad-filled"]),_l={close:hl,send:El,menu:pl,expand:fl,collapse:gl,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"))),info:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/ohTjxqcW.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"))),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"))),delete:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/CKPzhVy2.cjs"))),"close-filled":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/D1kINslt.cjs"))),agent:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/Ce1MzjFq.cjs"))),question:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/JA0x62Fd.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"))),bot:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/PhHbzZB_.cjs"))),"bot-filled":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DlvMdI1f.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"))),"arrow-left":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/CZIjo9nb.cjs"))),add:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DEGDJBmd.cjs"))),document:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DBHlAmeA.cjs")))},U=({type:e,size:t=24,className:n,color:r})=>{const s=_l[e];return o.createElement(xl,{className:n,$rtlFlip:bl.has(e),$size:t,$color:r??f.color.primary.main},o.createElement(Mt,{errorFallback:o.createElement(vl,null)},o.createElement(s,null)))},Cl=w.css`[dir='rtl'] &{transform:scaleX(-1);}`,xl=h.default.div`width:${({$size:e})=>ge(e)};height:${({$size:e})=>ge(e)};display:inline-block;&:focus{outline:none;}svg{display:block;}[class*='fill']{fill:${({$color:e})=>e};}[class*='stroke']{stroke:${({$color:e})=>e};stroke-width:2px;stroke-linejoin:round;}${({$rtlFlip:e})=>e&&Cl};`,vl=()=>o.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64"},o.createElement("rect",{x:"8",y:"8",width:"48",height:"48",fill:"none",className:"stroke",rx:"4"}),o.createElement("line",{x1:"20",y1:"20",x2:"44",y2:"44",className:"stroke"}),o.createElement("line",{x1:"44",y1:"20",x2:"20",y2:"44",className:"stroke"})),yl=.75,cs=6,Sl=cs*2;let En=null;typeof Intl<"u"&&"Segmenter"in Intl&&(En=new Intl.Segmenter(void 0,{granularity:"grapheme"}));const Al=e=>En?Array.from(En.segment(e),t=>t.segment):[...e],Tl=e=>{const t=Math.floor(e.length*yl),n=Math.max(0,e.length-cs);return Math.max(t,n)},gr=(e,t="")=>{if(e.length<Sl)return{start:e+t,end:""};const n=Al(e),r=Tl(n);return{start:n.slice(0,r).join(""),end:n.slice(r).join("")+t}},Il=e=>{const t=e.normalize("NFC").trim(),n=t.lastIndexOf(".");if(!(n>0&&n<t.length-1))return gr(t);const s=t.slice(0,n),a=t.slice(n);return gr(s,a)},us=({children:e,...t})=>{const{start:n,end:r}=u.useMemo(()=>Il(e),[e]);return r?o.createElement(wl,null,o.createElement(kl,{...t},n),o.createElement(Ml,{...t},r)):o.createElement(M,{...t},n)},wl=h.default.span`display:flex;width:100%;min-width:0;overflow:hidden;direction:inherit;`,kl=h.default(M)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex-shrink:1;min-width:0;`,Ml=h.default(M)`flex-shrink:0;white-space:nowrap;`,Fn=({name:e,type:t="FILE",iconColor:n,iconBackgroundColor:r,onClick:s})=>{const{colors:a}=w.useTheme();return o.createElement($l,{onClick:s,$clickable:!!s},o.createElement(Rl,{$bgColor:r??a.base.primary},o.createElement(U,{type:"file-document",size:24,color:n??a.base.primaryContrastContent})),o.createElement(Ol,null,o.createElement(us,{variant:"button",color:f.themedColor.textHighEmphasis},e),o.createElement(M,{color:f.themedColor.textMidEmphasis,variant:"caption3"},t)))},$l=h.default.div`border-radius:12px;gap:8px;width:${H.BODY_MAX_WIDTH}px;height:64px;display:flex;align-items:center;padding:12px;box-sizing:border-box;border:1px solid ${f.themedColor.textDisabled};background-color:${f.themedColor.bg_50_600};${({$clickable:e})=>e&&Ll}`,Ll=w.css`cursor:pointer;&:hover{background-color:${f.themedColor.bg_100_500};}`,Rl=h.default.div`border-radius:8px;width:40px;height:40px;display:flex;align-items:center;justify-content:center;background-color:${({$bgColor:e})=>e};`,Ol=h.default.div`display:flex;flex:1;flex-direction:column;gap:4px;min-width:0;`;function Dl({file:e,children:t,onClickFile:n}){return o.createElement(Nl,null,o.createElement(Fn,{name:e.name,type:vn(e.name,e.type),onClick:n&&(()=>n==null?void 0:n(e))}),t)}const Nl=h.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${H.GAP_GROUPED}px;`,xe=`${le}-incoming-msg`,Pl=`${le}-marked-text`;function Fl({file:e,onClickMedia:t,onClickMediaFiles:n,children:r}){const s=()=>{n?n({files:[{url:e.url,type:e.type,name:e.name}],index:0}):t&&t(e)},a=()=>e.type.startsWith("image")?o.createElement(Hl,{src:e.url,alt:"image-message"}):e.type.startsWith("video")?o.createElement(Vl,{controls:!0},o.createElement("source",{src:e.url}),o.createElement("track",{kind:"captions"})):null;if(a){const i={id:`${xe}-media-body`,onClick:s};return o.createElement(Bl,null,o.createElement(Ul,{...i},a()),r)}return null}const Bl=h.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${H.GAP_GROUPED}px;`,Ul=h.default.div`width:${H.BODY_MAX_WIDTH}px;height:160px;border-radius:12px;overflow:hidden;cursor:pointer;${F.light`
|
|
53
53
|
background-color: ${f.color.background100};
|
|
54
54
|
`}
|
|
55
55
|
${F.dark`
|
|
56
56
|
background-color: ${f.color.background400};
|
|
57
57
|
`}
|
|
58
|
-
`,
|
|
58
|
+
`,Hl=h.default.img`width:100%;height:100%;object-fit:cover;`,Vl=h.default.video`width:100%;height:100%;object-fit:cover;`,lt=({className:e,children:t,size:n=26})=>o.createElement(zl,{className:e,$size:n},t??o.createElement(U,{type:"spinner",size:n})),zl=h.default.div`display:flex;align-items:center;justify-content:center;width:${({$size:e})=>ge(e)};height:${({$size:e})=>ge(e)};animation:1s infinite linear;animation-name:rotate;@keyframes rotate{from{transform:rotate(0);}to{transform:rotate(360deg);}}`,$t=3,Ft=6,Gl=Ft/$t,ql=$t,Wl=Ft,Kl=e=>{const t=e%$t;return{gridColumns:t>0?Ft:$t,wideBottomCount:t}},ds=({images:e,isPending:t=!1,onClickImage:n})=>{const r=e.length;if(r===0)return null;const{gridColumns:s,wideBottomCount:a=0}=Kl(r);return o.createElement(Yl,{$width:H.BODY_MAX_WIDTH,$columns:s},e.map((i,l)=>{const c=a>0&&l>=r-a;let d=1;return s===Ft&&(c?d=a===1?Wl:ql:d=Gl),o.createElement(Xl,{key:i.url,$clickable:!!n&&!t,$itemSpan:d,$isPending:t,onClick:()=>!t&&(n==null?void 0:n(l))},o.createElement(jl,{src:i.url,alt:i.name||""}),t&&o.createElement(Zl,null))}))},jl=({src:e,alt:t})=>{const[n,r]=u.useState(!1),[s,a]=u.useState(!1);return o.createElement(o.Fragment,null,!n&&!s&&o.createElement(Jl,null,o.createElement(lt,{size:20},o.createElement(U,{type:"spinner",color:"textLowEmphasis",size:20}))),s?o.createElement(Ql,null,o.createElement(U,{type:"photo",color:"textLowEmphasis",size:24})):o.createElement(ec,{src:e,alt:t,$loaded:n,onLoad:()=>r(!0),onError:()=>a(!0)}))},Yl=h.default.div`display:grid;grid-template-columns:repeat(${({$columns:e})=>e},1fr);width:${({$width:e})=>e}px;gap:2px;border-radius:16px;overflow:hidden;`,Xl=h.default.div`position:relative;width:100%;aspect-ratio:1;overflow:hidden;cursor:${e=>e.$clickable?"pointer":"default"};${F.light`
|
|
59
59
|
background-color: ${f.color.background100};
|
|
60
60
|
`}
|
|
61
61
|
${F.dark`
|
|
@@ -73,28 +73,28 @@
|
|
|
73
73
|
}
|
|
74
74
|
`}
|
|
75
75
|
}
|
|
76
|
-
`,
|
|
76
|
+
`,Zl=h.default.div`position:absolute;top:0;left:0;width:100%;height:100%;background-color:${f.color.overlay.dark};pointer-events:none;`,ms=h.default.div`display:flex;align-items:center;justify-content:center;`,Jl=h.default(ms)`position:absolute;inset:0;`,Ql=h.default(ms)`position:absolute;inset:0;${F.light`
|
|
77
77
|
background-color: ${f.color.background200};
|
|
78
78
|
`}
|
|
79
79
|
${F.dark`
|
|
80
80
|
background-color: ${f.color.background500};
|
|
81
81
|
`}
|
|
82
|
-
`,
|
|
82
|
+
`,ec=h.default.img`position:absolute;inset:0;width:100%;height:100%;object-fit:cover;opacity:${({$loaded:e})=>e?1:0};transition:opacity 0.3s ease;`,tc=({files:e,children:t,onClickMedia:n,onClickMediaFiles:r})=>{const s=a=>{const i=e[a];i&&(r?r({files:e,index:a}):n&&n({url:i.url,type:i.type||"image/*"}))};return o.createElement(nc,null,o.createElement(ds,{images:e,onClickImage:s}),t)},nc=h.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${H.GAP_GROUPED}px;`,rc="✱",hs=e=>{const t=new RegExp(`(\`+)([^\`]+?)\\1|(${rc}+)`,"g");return e.replace(t,(n,r,s,a)=>r?n:a?`<span id=${Pl} aria-label="masked-text">${a}</span>`:n)},sc=e=>e.replace(/\*\*(.*?)\*\*/g,"<b>$1</b>"),fr=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)}}},oc=u.lazy(async()=>({default:(await Promise.resolve().then(()=>require("./cjs/D2Opuq0j.cjs"))).MarkdownText})),ac=u.lazy(async()=>({default:(await Promise.resolve().then(()=>require("./cjs/DlvEEpWX.cjs"))).CodeBlock}));function ic(e){var s,a;const t=e.maxBodyWidth??H.BODY_MAX_WIDTH,n=u.useMemo(()=>io(e.message,hs),[e.message]),r={id:`${xe}-text-body`,$maxWidth:t,$color:(s=e.customStyle)==null?void 0:s.bubbleContentColor,$bgColor:(a=e.customStyle)==null?void 0:a.bubbleBackgroundColor};return n.length===0?e.children?o.createElement(pr,{...r},e.children):null:o.createElement(pr,{...r},n.map((i,l)=>i.type==="text"?o.createElement(Er,{key:l,variant:"body3"},o.createElement(Mt,{fallback:i.value},o.createElement(oc,{onClickImage:c=>{var d;return(d=e.onClickMedia)==null?void 0:d.call(e,{url:c,type:"image/*"})}},i.value))):i.type==="code"?o.createElement(Mt,{key:l,fallback:o.createElement(Er,{variant:"body3"},i.value)},o.createElement(ac,{code:i.value,language:i.language})):null),e.children)}const pr=h.default.div`display:flex;flex-direction:column;border-radius:12px;overflow:hidden;min-width:0;max-width:min(${({$maxWidth:e})=>e}px,100%);${({theme:e,$color:t,$bgColor:n})=>w.css`
|
|
83
83
|
color: ${t||e.colors.messageIncoming.text};
|
|
84
84
|
background-color: ${n||e.colors.messageIncoming.background};
|
|
85
85
|
`}
|
|
86
86
|
padding: 12px 0;
|
|
87
87
|
transition: max-width 0.3s;
|
|
88
88
|
overflow-wrap: break-word;
|
|
89
|
-
`,Er=h.default(M)`align-items:flex-start;line-height:140%;white-space:pre-wrap;padding:0 12px;`;function
|
|
89
|
+
`,Er=h.default(M)`align-items:flex-start;line-height:140%;white-space:pre-wrap;padding:0 12px;`;function gs({id:e,src:t,size:n=56,onClick:r,style:s}){return o.createElement(lc,{id:e,tabIndex:0,onClick:r,$size:ge(n),style:s},t?o.createElement(cc,{src:t}):o.createElement(U,{type:"user",size:n}))}const lc=h.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:${f.themedColor.bg_100_500};&:focus{outline:none;}`,cc=h.default.img`object-fit:cover;width:100%;height:100%;position:absolute;`,uc=({sender:e,isBotMessage:t})=>{const n=`${xe}-sender-avatar`;return t&&!e.profileUrl?o.createElement(dc,{id:n},o.createElement(U,{type:"delight",size:"100%"})):o.createElement(gs,{id:n,size:H.AVATAR_SIZE,src:e.profileUrl})},dc=h.default.div`flex-shrink:0;width:${H.AVATAR_SIZE}px;height:${H.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;}}`,mc=({sender:e})=>o.createElement(hc,{id:`${xe}-sender-name`,variant:"caption1",color:f.themedColor.textMidEmphasis},e.nickname),hc=h.default(M)`text-align:start;width:100%;box-sizing:border-box;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding-block:5px;padding-inline:0 7px;`,gc=({createdAt:e})=>{const{stringSet:t,format:n}=K();return e?o.createElement(M,{id:`${xe}-sent-time`,variant:"caption4",color:f.themedColor.textLowEmphasis},n(e,t.DATE_FORMAT__MESSAGE_TIMESTAMP)):null},fc=({thinkingMessage:e,customStyle:t})=>e?o.createElement(bc,null,o.createElement(_c,null,e),o.createElement(Cc,null)):o.createElement(pc,{$bgColor:t==null?void 0:t.bubbleBackgroundColor},[0,1,2].map(n=>o.createElement(Ec,{key:n,$color:t==null?void 0:t.bubbleContentColor}))),pc=h.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};`,Ec=h.default.span`animation: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};@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;}`,bc=h.default.div`position:relative;overflow:hidden;animation:fadeIn 0.4s ease-in-out;@keyframes fadeIn{from{opacity:0;}to{opacity:1;}}`,_c=h.default(M).attrs({variant:"body3"})`
|
|
90
90
|
white-space: pre-wrap;
|
|
91
91
|
word-break: break-word;
|
|
92
92
|
color: ${f.themedColor.textHighEmphasis};
|
|
93
|
-
`,
|
|
94
|
-
`,
|
|
93
|
+
`,Cc=h.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=Qn(e.colors.base.background,.5),n=Qn(e.colors.base.background,0);return`linear-gradient(90deg, ${n} 0%, ${t} 30%, ${t} 60%, ${n} 100%)`}};
|
|
94
|
+
`,xc=({extendedMessagePayload:e,onClickCTA:t=({url:n})=>Nn(n)})=>{const n=e==null?void 0:e.cta_button;return n?o.createElement(vc,{id:`${xe}-ext-cta-button`,role:"button",onClick:()=>t(n)},o.createElement(yc,{variant:"button"},n.label)):null},vc=h.default.div`display:flex;align-items:center;justify-content:center;cursor:pointer;border-radius:6px;padding:8px;color:${f.themedColor.textHighEmphasis};background-color:${f.color.background50};${F.dark`
|
|
95
95
|
background-color: ${f.color.ondark.textDisabled};
|
|
96
96
|
`}
|
|
97
|
-
`,
|
|
97
|
+
`,yc=h.default(M)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,Sc=({extendedMessagePayload:e,onClickCitation:t=n=>Nn(n.link)})=>{const{stringSet:n}=K(),{theme:r}=$n(),s=e==null?void 0:e.citations;return!s||s.length===0?null:o.createElement(Ac,{id:`${xe}-ext-citation`},o.createElement(Tc,{variant:"caption1",color:r.colors.messageIncoming.text},n.CITATION_SOURCE_TITLE),o.createElement(Ic,null,s.map((a,i)=>o.createElement(kc,{key:`${a.embedding_id}-${i}`,role:"button",onClick:()=>t(a)},o.createElement(U,{type:"source",size:16,color:r.colors.messageIncoming.text}),o.createElement(wc,{variant:"body3",color:r.colors.messageIncoming.text},a.title)))))},Ac=h.default.div`display:flex;flex-direction:column;gap:8px;border-radius:8px;padding:8px 12px 6px;`,Tc=h.default(M)`opacity:0.5;`,Ic=h.default.div`display:flex;flex-direction:column;gap:8px;`,wc=h.default(M)`text-decoration:underline;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,kc=h.default.div`display:flex;align-items:center;gap:4px;cursor:pointer;&:hover{opacity:0.5;}`,Mc=e=>o.createElement(o.Fragment,null),$c=({visible:e,onClose:t,children:n})=>o.createElement(Pt,{rootElementId:me.WINDOW,visible:e,onClose:t},o.createElement(Dc,null,n)),Lc=({onClick:e,destructive:t,icon:n,children:r})=>o.createElement(Rc,{onClick:e,$destructive:t},n&&o.createElement(Oc,null,o.createElement(U,{type:n,size:24,color:f.themedColor.primary})),r),$e=Object.assign($c,{ActionItem:Lc}),Rc=h.default.button`all:unset;display:flex;align-items:center;gap:24px;width:100%;padding:12px 24px;cursor:pointer;color:${({$destructive:e})=>e?f.themedColor.error:f.themedColor.textHighEmphasis};`,Oc=h.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,Dc=h.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};`,bn=e=>`${e}-filled`,Nc=e=>e==="good"?ee.AIAgentMessageFeedbackRating.GOOD:ee.AIAgentMessageFeedbackRating.BAD,fs=w.css`&:hover{opacity:0.8;}&:active{opacity:0.6;}`,br={good:f.themedColor.secondary,bad:f.themedColor.error},Pc=({visible:e,onClose:t,isEdit:n,initialRating:r,initialComment:s="",onSubmit:a,isCommentEnabled:i=!1})=>{const{stringSet:l}=K(),[c,d]=u.useState(r),[m,p]=u.useState(s);u.useLayoutEffect(()=>{e?(d(r),p(s)):(d(void 0),p(""))},[e,r,s]);const E=()=>{c&&(a({rating:c,comment:m.trim()||void 0}),t())},v=()=>{t()};return e?o.createElement(Pt,{rootElementId:me.WINDOW,visible:e,onClose:v},o.createElement(Fc,null,o.createElement(Bc,null,o.createElement(M,{variant:"h2",color:f.themedColor.textHighEmphasis},l.FEEDBACK_TITLE)),o.createElement(Uc,null,o.createElement(Hc,null,["good","bad"].map(x=>{const b=c===x,g=x==="good"?l.FEEDBACK_GOOD:l.FEEDBACK_BAD;return o.createElement(Vc,{key:x,$selected:b,$rating:x,onClick:()=>d(x)},o.createElement(U,{type:b?bn(x):x,size:24,color:b?br[x]:f.themedColor.textLowEmphasis}),o.createElement(M,{variant:"caption1",color:b?br[x]:f.themedColor.textLowEmphasis},g))})),i&&o.createElement(zc,null,o.createElement(M,{variant:"caption3",color:f.themedColor.textHighEmphasis},l.FEEDBACK_COMMENT_LABEL),o.createElement(Gc,{placeholder:l.FEEDBACK_COMMENT_PLACEHOLDER,value:m,onChange:x=>p(x.target.value),maxLength:100}))),o.createElement(qc,null,o.createElement(Wc,{onClick:v},o.createElement(M,{variant:"button",color:f.themedColor.textHighEmphasis},l.FEEDBACK_CANCEL)),o.createElement(Kc,{onClick:E,disabled:!c},o.createElement(M,{variant:"button"},n?l.FEEDBACK_SAVE:l.FEEDBACK_SUBMIT))))):null},Fc=h.default.div`width:280px;background-color:${({theme:e})=>e.colors.base.modalContentBackground};border-radius:12px;overflow:hidden;`,Bc=h.default.div`padding:24px;`,Uc=h.default.div`padding-inline:24px;display:flex;flex-direction:column;gap:24px;`,Hc=h.default.div`display:flex;gap:4px;`,Vc=h.default.button`width:114px;height:64px;border-radius:12px;border:1px solid ${f.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;background-color:${({$selected:e})=>e?f.color.background100:"transparent"};${({$selected:e})=>F.dark`
|
|
98
98
|
background-color: ${e?f.color.background600:"transparent"};
|
|
99
99
|
`}
|
|
100
100
|
|
|
@@ -105,16 +105,16 @@
|
|
|
105
105
|
&:active {
|
|
106
106
|
opacity: 0.6;
|
|
107
107
|
}
|
|
108
|
-
`,
|
|
108
|
+
`,zc=h.default.div`display:flex;flex-direction:column;gap:6px;`,Gc=h.default.textarea`font-family:inherit;font-size:12px;line-height:16px;border:1px solid ${f.themedColor.textDisabled};border-radius:4px;padding:6px 12px;color:${f.themedColor.textHighEmphasis};background-color:${f.themedColor.textLowEmphasisInverse};resize:none;field-sizing:content;min-height:28px;max-height:118px;overflow-y:auto;&::placeholder{color:${f.themedColor.textLowEmphasis};}&:focus{outline:none;}`,qc=h.default.div`padding-inline:24px;padding-block:16px;display:flex;justify-content:flex-end;gap:4px;`,ps=h.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;`,Wc=h.default(ps)`${fs}`,Kc=h.default(ps)`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};}`,_r={good:f.themedColor.secondary,bad:f.themedColor.error},jc=({isBotMessage:e,isConversationClosed:t,isStreaming:n,isFeedbackEnabled:r,isFeedbackCommentEnabled:s,extendedMessagePayload:a,onFeedbackUpdate:i})=>{const{stringSet:l}=K(),[c,d]=u.useState(!1),[m,p]=u.useState(!1),[E,v]=u.useState(void 0),[x,b]=u.useState(""),g=a==null?void 0:a.feedback,_=(g==null?void 0:g.rating)??"none";if(_!=="none"?!1:!!(n||!e||!r||(a==null?void 0:a.bot_message_type)!=="generated"||t))return null;const I=S=>{_==="none"?(v(S),b(""),d(!0)):p(!0)},A=()=>{i==null||i(null),p(!1)},$=()=>{p(!1),v(g==null?void 0:g.rating),b((g==null?void 0:g.comment)??""),d(!0)},k=S=>{i==null||i(S)};return t&&_!=="none"?o.createElement(Cr,{$horizontal:!0},o.createElement(Yc,null,o.createElement(U,{type:bn(_),size:12,color:_r[_]})),(g==null?void 0:g.comment)&&o.createElement(xr,{variant:"caption2",style:{lineHeight:"16px"}},g.comment)):o.createElement(o.Fragment,null,o.createElement(Cr,null,o.createElement(Xc,null,["good","bad"].map(S=>{const R=_===S;return o.createElement(Zc,{key:S,$selected:R,$rating:S,onClick:()=>I(S)},o.createElement(U,{type:R?bn(S):S,size:14,color:R?_r[S]:f.themedColor.textMidEmphasis}))})),_!=="none"&&(g==null?void 0:g.comment)&&o.createElement(xr,{variant:"caption2"},g.comment)),o.createElement($e,{visible:m,onClose:()=>p(!1)},o.createElement($e.ActionItem,{onClick:$},l.FEEDBACK_EDIT),o.createElement($e.ActionItem,{onClick:A,destructive:!0},l.FEEDBACK_REMOVE)),o.createElement(Pc,{visible:c,onClose:()=>d(!1),isEdit:_!=="none",initialRating:E,initialComment:x,onSubmit:k,isCommentEnabled:s}))},Cr=h.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:${H.BODY_MAX_WIDTH}px;`,Yc=h.default.div`padding:2px;flex-shrink:0;display:flex;align-items:center;`,Xc=h.default.div`display:flex;gap:2px;`,Zc=h.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;border:1px solid ${f.color.background200};background-color:${({$selected:e})=>e?f.color.background100:"transparent"};${({$selected:e})=>F.dark`
|
|
109
109
|
border: 1px solid ${f.color.background400};
|
|
110
110
|
background-color: ${e?f.color.background500:"transparent"};
|
|
111
111
|
`}
|
|
112
112
|
|
|
113
|
-
${
|
|
113
|
+
${fs}
|
|
114
114
|
`,xr=h.default(M)`color:${f.themedColor.textMidEmphasis};${F.dark`
|
|
115
115
|
color: ${f.themedColor.textHighEmphasis};
|
|
116
116
|
`}
|
|
117
|
-
`,Bn=w.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;&:disabled{cursor:not-allowed;}`,vr=h.default.button`${Bn};background-color:${f.themedColor.primary};color:${f.themedColor.textHighEmphasis};&:hover:not(:disabled){opacity:0.9;}`,
|
|
117
|
+
`,Bn=w.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;&:disabled{cursor:not-allowed;}`,vr=h.default.button`${Bn};background-color:${f.themedColor.primary};color:${f.themedColor.textHighEmphasis};&:hover:not(:disabled){opacity:0.9;}`,Jc=h.default.button`${Bn};color:${f.themedColor.primary};${F.light`
|
|
118
118
|
background-color: ${f.color.background50};
|
|
119
119
|
`};
|
|
120
120
|
${F.dark`
|
|
@@ -124,7 +124,7 @@
|
|
|
124
124
|
&:hover:not(:disabled) {
|
|
125
125
|
opacity: 0.9;
|
|
126
126
|
}
|
|
127
|
-
`,
|
|
127
|
+
`,Qc=h.default.button`${Bn};background-color:transparent;color:${f.themedColor.textHighEmphasis};&:hover:not(:disabled){opacity:0.7;}`,eu=e=>{switch(e){case"primary":return vr;case"secondary":return Jc;case"clear":return Qc;default:return vr}},tu=h.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);}}`,nu=({children:e,onClick:t,variant:n="primary",disabled:r=!1,loading:s=!1,className:a})=>{const i=()=>{switch(n){case"primary":return f.themedColor.textHighEmphasisInverse;case"secondary":return f.themedColor.primary;case"clear":return f.themedColor.textHighEmphasis;default:return f.themedColor.textHighEmphasisInverse}},l=eu(n);return o.createElement(l,{onClick:t,disabled:r||s,className:a},s?o.createElement(tu,null,o.createElement(U,{type:"spinner",size:22,color:i()})):o.createElement(M,{variant:"button",color:i()},e))},ru=({children:e,className:t,style:n})=>o.createElement(M,{variant:"caption4",color:f.themedColor.error,className:t,style:n},e),su=({children:e,className:t,style:n,required:r})=>{const{stringSet:s}=K();return o.createElement(M,{variant:"caption3",color:f.themedColor.textMidEmphasis,className:t,style:n},e,!r&&o.createElement("span",{style:{color:f.themedColor.textLowEmphasis}},` (${s.OPTIONAL})`))},ou=({value:e,onChange:t,placeholder:n,error:r=!1,submitted:s=!1,className:a,disabled:i=!1,max:l})=>{const c=m=>{const E=m.target.value.replace(/[^0-9.-]/g,""),v=E.split("."),b=v.length>1?v[0]+"."+v.slice(1).join("").replace(/\./g,""):E;if(m.target.value=b,b===""||b==="-")t==null||t(null);else{const g=Number(b);if(!isNaN(g)){if(l!==void 0&&g>l)return;t==null||t(g)}}},d=e==null?"":String(e);return o.createElement(uu,{type:"text",value:d,onChange:c,placeholder:n,className:a,disabled:i||s,inputMode:"decimal",$error:r,$submitted:s})},au=w.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;&::placeholder{color:${f.themedColor.textLowEmphasis};}&::-webkit-inner-spin-button,&::-webkit-outer-spin-button{-webkit-appearance:none;margin:0;}`,iu=w.css`color:${f.themedColor.textHighEmphasis};border:1px solid transparent;cursor:not-allowed;${F.light`
|
|
128
128
|
background-color: ${f.color.ondark.textMidEmphasis};
|
|
129
129
|
`}
|
|
130
130
|
${F.dark`
|
|
@@ -134,13 +134,13 @@
|
|
|
134
134
|
&::placeholder {
|
|
135
135
|
color: ${f.themedColor.textLowEmphasis};
|
|
136
136
|
}
|
|
137
|
-
`,
|
|
137
|
+
`,lu=w.css`border:1px solid ${f.themedColor.error};color:${f.themedColor.textHighEmphasis};${F.light`
|
|
138
138
|
background-color: ${f.color.background50};
|
|
139
139
|
`}
|
|
140
140
|
${F.dark`
|
|
141
141
|
background-color: ${f.color.onlight.textLowEmphasis};
|
|
142
142
|
`}
|
|
143
|
-
`,
|
|
143
|
+
`,cu=w.css`border:1px solid ${f.themedColor.textDisabled};color:${f.themedColor.textHighEmphasis};${F.light`
|
|
144
144
|
background-color: ${f.color.background50};
|
|
145
145
|
`}
|
|
146
146
|
${F.dark`
|
|
@@ -150,12 +150,12 @@
|
|
|
150
150
|
&:focus {
|
|
151
151
|
border-color: ${f.themedColor.primary};
|
|
152
152
|
}
|
|
153
|
-
`,
|
|
153
|
+
`,uu=h.default.input`${au}${({$error:e,$submitted:t})=>t?iu:e?lu:cu}`,du=e=>{if(e.multiple){const{value:t=[],onChange:n,maxSelect:r,submitted:s=!1}=e;return{selectedValues:t,handleOptionClick:i=>{if(s)return;if(t.includes(i)){const c=t.filter(d=>d!==i);n==null||n(c)}else{if(r&&t.length>=r)return;const c=[...t,i];n==null||n(c)}}}}else{const{value:t,onChange:n,submitted:r=!1}=e;return{selectedValues:t?[t]:[],handleOptionClick:a=>{if(r)return;const i=t===a?"":a;n==null||n(i)}}}},Es=e=>{const{options:t,submitted:n=!1,error:r=!1,className:s}=e,{selectedValues:a,handleOptionClick:i}=du(e);return o.createElement(hu,{className:s},t.map(l=>{const c=a.includes(l.value);return o.createElement(Cu,{key:l.value,$active:c,$submitted:n,$error:r,onClick:()=>i(l.value)},o.createElement(M,{variant:"caption1",color:mu(c,n)},l.label))}))},mu=(e,t)=>t?e?f.themedColor.textHighEmphasis:f.themedColor.textDisabled:e?f.themedColor.primary:f.themedColor.textMidEmphasis,hu=h.default.div`display:flex;flex-wrap:wrap;gap:4px 2px;`,gu=w.css`display:inline-flex;align-items:center;padding:8px 12px;border-radius:15px;transition:all 0.2s ease;`,fu=w.css`cursor:default;background-color:${f.color.ondark.textMidEmphasis};color:${f.themedColor.textHighEmphasis};${F.dark`
|
|
154
154
|
background-color: transparent;
|
|
155
155
|
border: 1px solid white;
|
|
156
156
|
color: white;
|
|
157
157
|
`}
|
|
158
|
-
`,
|
|
158
|
+
`,pu=w.css`cursor:default;${F.light`
|
|
159
159
|
background-color: ${f.color.ondark.textMidEmphasis};
|
|
160
160
|
color: ${f.themedColor.textDisabled};
|
|
161
161
|
`}
|
|
@@ -164,7 +164,7 @@
|
|
|
164
164
|
border: 1px solid ${f.color.onlight.textLowEmphasis};
|
|
165
165
|
color: ${f.themedColor.textDisabled};
|
|
166
166
|
`}
|
|
167
|
-
`,
|
|
167
|
+
`,Eu=w.css`cursor:pointer;border:1px solid ${f.themedColor.primary};${F.light`
|
|
168
168
|
background-color: ${f.color.background50};
|
|
169
169
|
color: ${f.themedColor.primary};
|
|
170
170
|
`}
|
|
@@ -172,7 +172,7 @@
|
|
|
172
172
|
background-color: ${f.color.onlight.textLowEmphasis};
|
|
173
173
|
color: ${f.themedColor.primary};
|
|
174
174
|
`}
|
|
175
|
-
`,
|
|
175
|
+
`,bu=w.css`cursor:pointer;border:1px solid ${f.themedColor.textDisabled};${F.light`
|
|
176
176
|
background-color: ${f.color.background50};
|
|
177
177
|
color: ${f.themedColor.textMidEmphasis};
|
|
178
178
|
`}
|
|
@@ -180,10 +180,10 @@
|
|
|
180
180
|
background-color: ${f.color.onlight.textLowEmphasis};
|
|
181
181
|
color: ${f.themedColor.textMidEmphasis};
|
|
182
182
|
`}
|
|
183
|
-
`,
|
|
184
|
-
${r} ${
|
|
183
|
+
`,_u=w.css`border-color:${f.themedColor.error}!important;`,Cu=h.default.div`${gu}${({$active:e,$submitted:t,$error:n})=>{if(t)return e?fu:pu;const r=e?Eu:bu;return n?w.css`
|
|
184
|
+
${r} ${_u}
|
|
185
185
|
`:r}}
|
|
186
|
-
`,
|
|
186
|
+
`,xu=e=>o.createElement(Es,{...e,multiple:!1}),vu=e=>o.createElement(Es,{...e,multiple:!0}),yu=h.default.div`width:100%;height:1px;background-color:${f.themedColor.textDisabled};`,Su=({className:e})=>o.createElement(yu,{className:e}),Au=({value:e="",onChange:t,placeholder:n,variant:r="single-line",error:s=!1,submitted:a=!1,className:i,disabled:l=!1,maxLength:c})=>{const m={value:e,onChange:p=>{const E=p.target.value;c&&E.length>c||t==null||t(E)},placeholder:n,className:i,disabled:l||a,maxLength:c,$error:s,$submitted:a};return r==="multi-line"?o.createElement(Iu,{...m}):o.createElement(Tu,{...m})},bs=w.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;&::placeholder{color:${f.themedColor.textLowEmphasis};}`,_s=w.css`color:${f.themedColor.textHighEmphasis};border:1px solid transparent;cursor:not-allowed;${F.light`
|
|
187
187
|
background-color: ${f.color.ondark.textMidEmphasis};
|
|
188
188
|
`}
|
|
189
189
|
${F.dark`
|
|
@@ -193,13 +193,13 @@
|
|
|
193
193
|
&::placeholder {
|
|
194
194
|
color: ${f.themedColor.textLowEmphasis};
|
|
195
195
|
}
|
|
196
|
-
`,
|
|
196
|
+
`,Cs=w.css`border:1px solid ${f.themedColor.error};color:${f.themedColor.textHighEmphasis};${F.light`
|
|
197
197
|
background-color: ${f.color.background50};
|
|
198
198
|
`}
|
|
199
199
|
${F.dark`
|
|
200
200
|
background-color: ${f.color.onlight.textLowEmphasis};
|
|
201
201
|
`}
|
|
202
|
-
`,
|
|
202
|
+
`,xs=w.css`border:1px solid ${f.themedColor.textDisabled};color:${f.themedColor.textHighEmphasis};${F.light`
|
|
203
203
|
background-color: ${f.color.background50};
|
|
204
204
|
`}
|
|
205
205
|
${F.dark`
|
|
@@ -209,54 +209,54 @@
|
|
|
209
209
|
&:focus {
|
|
210
210
|
border-color: ${f.themedColor.primary};
|
|
211
211
|
}
|
|
212
|
-
`,
|
|
212
|
+
`,Tu=h.default.input`${bs};height:36px;${({$error:e,$submitted:t})=>t?_s:e?Cs:xs}`,Iu=h.default.textarea`${bs};height:96px;resize:none;font-family:inherit;${({$error:e,$submitted:t})=>t?_s:e?Cs:xs}`,wu=({children:e,className:t,style:n})=>o.createElement(M,{variant:"button",color:f.themedColor.textHighEmphasis,className:t,style:n},e),J={Title:wu,Label:su,ErrorLabel:ru,Separator:Su,Button:nu,TextInput:Au,NumberInput:ou,SingleSelect:xu,MultiSelect:vu},ku=1,Mu=new Set(["text","number","single-select","multi-select"]),$u=e=>{var g;const t=(g=e.extendedMessagePayload)==null?void 0:g.form;if(!t)throw new Error("Form is not provided");const{stringSet:n}=K(),[r,s]=u.useState({submitting:!1,canceling:!1}),[a,i]=u.useState({visible:!1}),{state:l,fields:c,submit:d,cancel:m,updateFieldValue:p}=ri(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:_=>{var y;return(y=e.onSubmitForm)==null?void 0:y.call(e,{key:t.key,data:_})},onCancel:()=>{var _;return(_=e.onCancelForm)==null?void 0:_.call(e,{key:t.key})}}),E=l==="submitted",v=async()=>{s(_=>({..._,submitting:!0}));try{await d()}catch(_){i({visible:!0,description:_ instanceof Error?_.message:n.TRY_AGAIN})}finally{s(_=>({..._,submitting:!1}))}},x=async()=>{s(_=>({..._,canceling:!0}));try{await m()}catch(_){i({visible:!0,description:_ instanceof Error?_.message:n.TRY_AGAIN})}finally{s(_=>({..._,canceling:!1}))}},b=u.useMemo(()=>{const _=()=>t.version>ku,y=()=>t.fields.some(I=>!Mu.has(I.type));return _()||y()?{visible:!1,cancelable:!0,reason:n.FORM_NOT_SUPPORTED}:l==="draft"&&(e.isHandedOff||e.isConversationClosed)?{visible:!1,cancelable:!1,reason:n.FORM_UNAVAILABLE}:{visible:!0,cancelable:!0,reason:""}},[t.version,t.fields,l,e.isHandedOff,e.isConversationClosed]);return l==="canceled"?null:b.visible?o.createElement(u.Fragment,null,o.createElement(yr,{$maxWidth:e.maxBodyWidth??H.BODY_MAX_WIDTH},o.createElement(J.Title,null,t.title),o.createElement(Lu,null,c.map(_=>o.createElement(Ru,{key:_.key},o.createElement(J.Label,{style:{marginBottom:"6px"},required:_.required},_.label),_.type==="text"&&o.createElement(J.TextInput,{value:_.value||"",placeholder:_.placeholder,onChange:y=>p(_.key,y),disabled:E,error:!!_.error,submitted:E,variant:_.layout==="multiline"?"multi-line":"single-line",maxLength:_.maxLength}),_.type==="number"&&o.createElement(J.NumberInput,{value:_.value||null,placeholder:_.placeholder,onChange:y=>p(_.key,y),disabled:E,error:!!_.error,submitted:E,max:_.max}),_.type==="single-select"&&o.createElement(J.SingleSelect,{options:_.options.map(y=>({label:y,value:y})),value:_.value||"",onChange:y=>p(_.key,y),submitted:E}),_.type==="multi-select"&&o.createElement(J.MultiSelect,{options:_.options.map(y=>({label:y,value:y})),value:_.value||[],onChange:y=>p(_.key,y),submitted:E,maxSelect:_.maxSelect}),_.error&&o.createElement(J.ErrorLabel,{style:{marginTop:"4px"}},_.error)))),o.createElement(J.Separator,null),o.createElement(Ou,null,o.createElement(J.Button,{variant:E?"clear":"primary",onClick:v,disabled:E||r.canceling,loading:r.submitting},E?n.SUBMITTED:n.BUTTON__SUBMIT),l!=="submitted"&&o.createElement(J.Button,{variant:"secondary",onClick:x,disabled:r.submitting,loading:r.canceling},n.BUTTON__CANCEL))),o.createElement(Dn,{...a,onClose:()=>i({visible:!1,title:""})})):o.createElement(yr,{$maxWidth:e.maxBodyWidth??H.BODY_MAX_WIDTH},o.createElement(M,{variant:"body3"},b.reason),b.cancelable&&o.createElement(J.Button,{variant:"primary",onClick:x,loading:r.canceling},n.BUTTON__CANCEL))},yr=h.default.div`display:flex;flex-direction:column;gap:12px;border-radius:12px;overflow:hidden;max-width:${({$maxWidth:e})=>e}px;${({theme:e})=>w.css`
|
|
213
213
|
color: ${e.colors.messageIncoming.text};
|
|
214
214
|
background-color: ${e.colors.messageIncoming.background};
|
|
215
215
|
`}
|
|
216
216
|
padding: 16px 12px;
|
|
217
217
|
transition: max-width 0.3s;
|
|
218
218
|
overflow-wrap: break-word;
|
|
219
|
-
|
|
220
|
-
${e==="vertical"?
|
|
219
|
+
`,Lu=h.default.div`display:flex;flex-direction:column;gap:12px;`,Ru=h.default.div`display:flex;flex-direction:column;`,Ou=h.default.div`display:flex;flex-direction:column;gap:8px;`,Du=e=>o.createElement(o.Fragment,null),Nu=new Set(["default"]),{MessageTemplate:Pu}=Qs.createMessageTemplate({parser:an.parser,renderer:an.renderer,Container:e=>o.createElement("div",{...e})}),Fu=e=>o.createElement(Mt,{errorFallback:e.messageTemplateErrorFallback,loadingFallback:e.messageTemplateLoadingFallback},o.createElement(Bu,{...e})),Bu=({extendedMessagePayload:e,onGetCachedMessageTemplate:t=()=>null,onRequestMessageTemplate:n,onHandleTemplateInternalAction:r=Ce})=>{const s=e==null?void 0:e.message_template;if(!Nu.has((s==null?void 0:s.type)??"default"))throw new Error("Unsupported template type");if(!n)throw new Error("onRequestMessageTemplate is required");const i=s==null?void 0:s.key;if(!i)throw new Error("Template key is missing");const{theme:l}=ns(),c=Ka({onRequestTemplate:n,onGetCachedTemplate:t,theme:l.selectedTheme,templateKey:i,variables:s==null?void 0:s.variables,viewVariables:s==null?void 0:s.view_variables,aiAgentColorVariables:l.aiAgentColorVariables});return o.createElement(Uu,{id:`${xe}-ext-message-template`},o.createElement(an.MessageProvider,{handleInternalAction:(d,m)=>{d.stopPropagation(),r==null||r(m)}},o.createElement(Pu,{templateItems:c.body.items,templateVersion:c.version})))},Uu=h.default.div`box-sizing:border-box;overflow:hidden;width:100%;`,Hu=({extendedMessagePayload:e,onClickSuggestedReply:t,suggestedRepliesDirection:n="vertical"})=>{const[r,s]=u.useState(!1),a=(e==null?void 0:e.suggested_replies)??[];return a.length===0||r?null:o.createElement(Vu,{id:`${xe}-ext-suggested-replies`,$type:n},a.map((i,l)=>o.createElement(zu,{key:l,$type:n,variant:"body3",onClick:()=>{t&&(t==null||t({reply:i}),s(!0))}},i)))},Vu=h.default.div`margin:16px 0;padding:0 ${H.HORIZONTAL_PADDING}px;position:relative;display:flex;align-self:stretch;gap:8px;${({$type:e})=>e==="vertical"?Gu:qu};`,zu=h.default(M)`box-sizing:border-box;padding:8px 12px;display:flex;align-items:center;border-radius:20px / clamp(20px,5%,100px);cursor:pointer;word-break:break-word;color:${f.color.primary.main};border:1px solid ${f.color.primary.main};background-color:${f.themedColor.bg_50_600};&:hover{background-color:${f.themedColor.bg_100_500};}${({$type:e,theme:t})=>w.css`
|
|
220
|
+
${e==="vertical"?Wu:Ku};
|
|
221
221
|
&:active {
|
|
222
222
|
background-color: ${t.colors.base.primary};
|
|
223
223
|
color: ${t.colors.base.primaryContrastContent};
|
|
224
224
|
}
|
|
225
225
|
`}
|
|
226
|
-
`,
|
|
226
|
+
`,Gu=w.css`flex-direction:column;align-items:flex-end;`,qu=w.css`flex-direction:row;overflow-x:scroll;-ms-overflow-style:none;scrollbar-width:none;&::-webkit-scrollbar{display:none;}`,Wu=w.css`max-width:calc(100% - 70px);white-space:pre-wrap;`,Ku=w.css`white-space:nowrap;`,ju=e=>{const{components:t}=De.useContext(),{stringSet:n}=K(),r=Fr(e)?o.createElement(t.TextMessageBody,{...e}):null;if(e.messageType==="user")return r;if(e.messageType==="file"){const s=e.file;return s.type.startsWith("image")||s.type.startsWith("video")?o.createElement(t.MediaMessageBody,{...e},r):o.createElement(t.FileMessageBody,{...e},r)}return e.messageType==="multipleFiles"?o.createElement(t.MultipleFilesMessageBody,{...e},r):o.createElement(t.TextMessageBody,{...e,message:n.UNKNOWN__UNKNOWN_MESSAGE_TYPE})},Yu=e=>o.createElement(vs,{...e,testerMode:!1}),De=pe({template:Yu,components:{SenderName:mc,SenderAvatar:uc,SentTime:gc,MessageBody:ju,TextMessageBody:ic,MediaMessageBody:Fl,FileMessageBody:Dl,MultipleFilesMessageBody:tc,TypingIndicator:fc,SuggestedReplies:Hu,MessageTemplate:Fu,CustomMessageTemplate:Mc,CTAButton:xc,Citation:Sc,Form:$u,Feedback:jc,MessageLogs:Du}}),vs=e=>{var g,_,y,I,A,$,k;const{components:t}=De.useContext(),{streamText:n,isAnimating:r}=di({text:e.message,enabled:e.isStreaming,onAnimationStart:e.onStreamAnimationStart,onAnimationProgress:e.onStreamAnimationProgress,onAnimationComplete:e.onStreamAnimationComplete}),s={...e,message:n,extendedMessagePayload:r?{}:e.extendedMessagePayload},a=!!s.isTyping,i=s.testerMode,l=!!s.isSenderAvatarVisible,c=!!((g=s.extendedMessagePayload)!=null&&g.form)&&!((_=s.extendedMessagePayload)!=null&&_.form.canceled_at),d=!!((y=s.extendedMessagePayload)!=null&&y.message_template),m=!!((I=s.extendedMessagePayload)!=null&&I.cta_button),p=!!((A=s.extendedMessagePayload)!=null&&A.citations)&&s.extendedMessagePayload.citations.length>0,E=!!s.createdAt,v=s.groupType==="top"||s.groupType==="single",x=s.groupType==="bottom"||s.groupType==="single",b=i||!l?0:H.AVATAR_SIZE;return o.createElement(Xu,{$marginBottom:a?0:yn(s.groupType)},v&&o.createElement(Zu,null,!i&&l&&o.createElement(t.SenderAvatar,{...s}),o.createElement(t.SenderName,{...s})),o.createElement(Qu,null,o.createElement(rn,{$extraStartPadding:b},a?o.createElement(t.TypingIndicator,{...s}):o.createElement(t.MessageBody,{...s},m&&o.createElement("div",{style:{marginTop:12,marginInline:12}},o.createElement(t.CTAButton,{...s})),p&&o.createElement(t.Citation,{...s}))),d&&o.createElement(Sr,{$startPadding:0,$endPadding:0},o.createElement(t.MessageTemplate,{...s,messageTemplateErrorFallback:s.messageTemplateErrorFallback??o.createElement(rn,{$extraStartPadding:b},o.createElement(t.MessageBody,{...s,messageType:"user",message:((k=($=s.extendedMessagePayload)==null?void 0:$.message_template)==null?void 0:k.fallback_message)??"Cannot read this template."})),messageTemplateLoadingFallback:s.messageTemplateLoadingFallback??o.createElement(rn,{$extraStartPadding:b},o.createElement(t.TypingIndicator,{...s}))})),o.createElement(t.CustomMessageTemplate,{...s}),c&&o.createElement(Sr,{$extraStartPadding:b},o.createElement(t.Form,{...s}))),x&&E&&o.createElement(Ju,{$extraStartPadding:b+8},o.createElement(t.SentTime,{...s})),o.createElement(u.Fragment,null,!a&&o.createElement(ct,{$extraStartPadding:b+8},o.createElement(t.Feedback,{...s})),s.suggestedRepliesVisible&&o.createElement(t.SuggestedReplies,{...s}),o.createElement(t.MessageLogs,{...s})))},Xu=h.default.div`display:flex;flex-direction:column;align-items:flex-start;margin-bottom:${({$marginBottom:e})=>`${e}px`};
|
|
227
227
|
`,ct=h.default.div`display:flex;align-self:stretch;justify-content:flex-start;${({$startPadding:e=H.HORIZONTAL_PADDING,$endPadding:t=H.HORIZONTAL_PADDING,$extraStartPadding:n=0})=>`
|
|
228
228
|
padding-inline: ${e+n}px ${t}px;
|
|
229
229
|
`}
|
|
230
|
-
`,
|
|
230
|
+
`,Zu=h.default(ct)`display:flex;flex-direction:row;align-items:center;gap:8px;`,rn=h.default(ct)`display:flex;`,Ju=h.default(ct)`margin-top:${H.BODY_TIME_GAP}px;display:flex;align-items:flex-start;justify-content:flex-start;`,Sr=h.default(ct)`display:flex;${({$startPadding:e=H.HORIZONTAL_PADDING,$endPadding:t=H.HORIZONTAL_PADDING,$extraStartPadding:n=0})=>`
|
|
231
231
|
padding-inline: ${e+n}px ${t}px;
|
|
232
232
|
`}
|
|
233
|
-
`,
|
|
233
|
+
`,Qu=h.default.div`display:flex;flex-direction:column;min-width:0;max-width:100%;gap:${H.GAP_GROUPED}px;`;function ed({file:e,children:t,onClickFile:n,sendingStatus:r}){const s=(()=>{if(!(!n||r==="failed"))return()=>n==null?void 0:n(e)})();return o.createElement(td,null,o.createElement(Fn,{name:e.name,type:vn(e.name,e.type),onClick:s}),t)}const td=h.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${H.GAP_GROUPED}px;`;function nd({sendingStatus:e,file:t,metadata:n,onClickMedia:r,onClickMediaFiles:s,children:a}){const{aspectRatio:i,localFile:l}=n,[c]=u.useState(()=>l instanceof Blob?URL.createObjectURL(l):t.url),[d,m]=u.useState(!1),p=(()=>{if(e!=="failed"){if(s)return()=>s({files:[{url:c,type:t.type,name:t.name}],index:0});if(r)return()=>r({...t,url:c})}})(),E={onClick:p,$ratio:i,$clickable:!!p};return o.createElement(rd,null,o.createElement(sd,{...E},!d&&o.createElement(lt,{size:26},o.createElement(U,{type:"spinner",color:"textLowEmphasis",size:26})),o.createElement(od,{$loaded:d,src:c,alt:"image-message",onLoad:()=>m(!0)})),a)}const rd=h.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${H.GAP_GROUPED}px;`,sd=h.default.div`width:${H.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;${F.light`
|
|
234
234
|
background-color: ${f.color.background100};
|
|
235
235
|
`}
|
|
236
236
|
${F.dark`
|
|
237
237
|
background-color: ${f.color.background400};
|
|
238
238
|
`}
|
|
239
|
-
`,
|
|
239
|
+
`,od=h.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;`,ad=({sendingStatus:e,files:t,metadata:n,onClickMedia:r,onClickMediaFiles:s,children:a})=>{const[i]=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 p=i[m];p&&(s?s({files:i,index:m}):r&&r({url:p.url,type:p.type||"image/*"}))};return o.createElement(id,null,o.createElement(ds,{images:i,isPending:l,onClickImage:d}),a)},id=h.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${H.GAP_GROUPED}px;`;function ld(e){var n,r;const t=u.useMemo(()=>{const s=sc(hs(e.message));return Dr.default.sanitize(s)},[e.message]);return o.createElement(cd,{$maxWidth:e.maxBodyWidth??H.BODY_MAX_WIDTH,$color:(n=e.customStyle)==null?void 0:n.bubbleContentColor,$bgColor:(r=e.customStyle)==null?void 0:r.bubbleBackgroundColor},o.createElement(ud,{variant:"body3",dangerouslySetInnerHTML:{__html:t}}))}const cd=h.default.div`display:flex;flex-direction:column;border-radius:12px;overflow:hidden;max-width:${({$maxWidth:e})=>e}px;${({theme:e,$color:t,$bgColor:n})=>w.css`
|
|
240
240
|
color: ${t||e.colors.messageOutgoing.text};
|
|
241
241
|
background-color: ${n||e.colors.messageOutgoing.background};
|
|
242
242
|
`}
|
|
243
243
|
padding: 12px 0;
|
|
244
244
|
transition: max-width 0.3s;
|
|
245
245
|
overflow-wrap: break-word;
|
|
246
|
-
`,
|
|
247
|
-
`,
|
|
248
|
-
`,pd=h.default(vs)``,Ed=h.default(vs)`margin-top:${H.BODY_TIME_GAP}px;`,bd=e=>e.messageType!=="admin"?null:o.createElement(_d,null,o.createElement(M,{variant:"caption2",color:f.themedColor.textMidEmphasis},Cd(Dr.default.sanitize(e.message)))),_d=h.default.div`text-align:center;text-wrap:pretty;word-break:break-word;padding-inline:${H.HORIZONTAL_PADDING}px;a{text-decoration:underline;color:inherit;}`,Cd=e=>{try{const t=[];let n=e,r=0;for(;n;){const s=n.match(/\[([^\]]+)\]\((https?:\/\/[^\s]+)\)/),a=n.match(/\*\*([^*]+)\*\*/),i=[s&&{match:s,type:"link"},a&&{match:a,type:"bold"}].filter(p=>!!p);if(!i.length){t.push(n);break}const l=i.reduce((p,E)=>E.match.index<p.match.index?E:p),{match:c,type:d}=l,m=c.index;m>0&&t.push(n.slice(0,m)),d==="link"?t.push(o.createElement("a",{key:r++,href:c[2],target:"_blank",rel:On},c[1])):d==="bold"&&t.push(o.createElement("strong",{key:r++},c[1])),n=n.slice(m+c[0].length)}return t.filter(s=>s!=="")}catch{return[e]}},ys=({onClick:e,checked:t,label:n,disabled:r,labelVariant:s="caption2"})=>{const a=t?f.themedColor.primary:r?f.themedColor.textDisabled:f.themedColor.textLowEmphasis,i=t?f.themedColor.textHighEmphasis:r?f.themedColor.textLowEmphasis:f.themedColor.textHighEmphasis;return o.createElement(yd,{onClick:e,disabled:r},o.createElement(xd,null,o.createElement(U,{size:20,type:t?"radio-on":"radio-off",color:a})),o.createElement(vd,{variant:s,color:i},n))},xd=h.default.div`width:20px;height:20px;`,vd=h.default(M)`line-height:20px;word-break:break-word;`,yd=h.default.button`all:unset;display:flex;align-items:flex-start;justify-content:flex-start;gap:2px;&:enabled{cursor:pointer;}`,Sd=({csatPayload:e,submitted:t,defaultValue:n,value:r,onChange:s})=>(u.useEffect(()=>{typeof r>"u"&&typeof n=="boolean"&&(s==null||s(n))},[r,n]),e.cre?o.createElement(Ad,null,o.createElement(J.Label,{required:e.cre.required},e.cre.question),o.createElement(Td,null,[{label:e.cre.positive_label,value:!0},{label:e.cre.negative_label,value:!1}].map(a=>o.createElement(ys,{key:a.label,checked:r===a.value,label:a.label,disabled:t,onClick:()=>s==null?void 0:s(a.value)})))):null),Ad=h.default.div`display:flex;flex-direction:column;gap:8px;`,Td=h.default.div`display:flex;flex-direction:column;gap:8px;`,Id=({followUpItem:e,submitted:t,value:n="",onChange:r,hasError:s})=>{const{stringSet:a}=K();return o.createElement(wd,null,o.createElement(J.Label,{required:e.required},e.question),e.response_type==="free_text"&&o.createElement(J.TextInput,{variant:"multi-line",disabled:t,submitted:t,maxLength:100,value:n,onChange:i=>r(i),error:s}),e.response_type==="single_choice"&&o.createElement(kd,null,e.options.map(i=>o.createElement(ys,{key:i,checked:n===i,label:i,disabled:t,onClick:()=>r==null?void 0:r(i),labelVariant:"body3"}))),s&&o.createElement(J.ErrorLabel,null,a.FORM_VALIDATION_REQUIRED))},wd=h.default.div`display:flex;flex-direction:column;gap:8px;`,kd=h.default.div`display:flex;flex-direction:column;gap:8px;`,Md=({value:e,selected:t,label:n})=>o.createElement($d,{$selected:t,"aria-label":n},Ld[e-1]),$d=h.default.div`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,Ld=[o.createElement("svg",{width:"40",height:"40",viewBox:"0 0 40 40",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o.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)"}),o.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"}),o.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"}),o.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"}),o.createElement("defs",null,o.createElement("linearGradient",{id:"paint0_linear_159_173206",x1:"20",y1:"2.08325",x2:"20",y2:"37.9166",gradientUnits:"userSpaceOnUse"},o.createElement("stop",{stopColor:"#FF2D1D"}),o.createElement("stop",{offset:"1",stopColor:"#FFA540"})))),o.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},o.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"}),o.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"}),o.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"}),o.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"})),o.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},o.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"}),o.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"}),o.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"})),o.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},o.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"}),o.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"}),o.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"})),o.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},o.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"}),o.createElement("g",{clipPath:"url(#clip0_159_173224)"},o.createElement("g",{clipPath:"url(#clip1_159_173224)"},o.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"})),o.createElement("mask",{id:"mask0_159_173224",style:{maskType:"alpha"},maskUnits:"userSpaceOnUse",x:"12",y:"22",width:"16",height:"9"},o.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"})),o.createElement("g",{mask:"url(#mask0_159_173224)"},o.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"}))),o.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"}),o.createElement("defs",null,o.createElement("clipPath",{id:"clip0_159_173224"},o.createElement("rect",{width:"15.83",height:"7.915",fill:"white",transform:"translate(12.085 22.709)"})),o.createElement("clipPath",{id:"clip1_159_173224"},o.createElement("rect",{width:"15.83",height:"7.915",fill:"white",transform:"translate(12.085 22.709)"}))))],Rd=({csatPayload:e,submitted:t,value:n,onChange:r})=>{const s=typeof n>"u";return o.createElement(Dd,null,o.createElement(M,{variant:"caption3",color:f.themedColor.textMidEmphasis},e.csat_question),o.createElement(Nd,null,e.csat_scores.map(({label:a,image_url:i},l)=>{const c=l+1,d=n===c;return o.createElement(Pd,{key:l,disabled:t,onClick:()=>r(c)},o.createElement(Od,{value:c,selected:s||d,label:a,src:i}),!!a&&o.createElement(M,{color:d?f.themedColor.textHighEmphasis:f.themedColor.textLowEmphasis,variant:"caption3"},a))})))},Od=({value:e,src:t,label:n,selected:r})=>{const[s,a]=u.useState(!1),i=s?o.createElement(Md,{value:e,selected:r,label:n}):o.createElement(Bd,{$selected:r,"aria-label":n,src:t,onError:()=>a(!0)});return o.createElement(Fd,null,i)},Dd=h.default.div`display:flex;flex-direction:column;gap:8px;`,Nd=h.default.div`display:flex;justify-content:space-between;align-self:center;width:100%;max-width:400px;gap:16px;`,Pd=h.default.button`background-color:transparent;border:none;gap:4px;display:flex;flex-direction:column;align-items:center;justify-content:start;box-sizing:border-box;min-width:48px;max-width:68px;&:hover:not(:disabled) span{color:${f.themedColor.textHighEmphasis};}`,Fd=h.default.div`button:hover:not(:disabled) &{border-radius:4px;cursor:pointer;background-color:${f.color.background200};${F.dark`
|
|
246
|
+
`,ud=h.default(M)`align-items:flex-start;line-height:140%;white-space:pre-wrap;padding:0 12px;`,dd=({sendingStatus:e})=>{const t=w.useTheme();switch(e){case"pending":return o.createElement(md,{size:16},o.createElement(U,{type:"spinner",color:t.colors.messageOutgoing.background,size:16}));case"failed":return o.createElement("div",{style:{marginBottom:2}},o.createElement(U,{type:"error",color:f.themedColor.error,size:16}));case"scheduled":case"canceled":return null;default:return o.createElement("div",{style:{marginBottom:2}},o.createElement(U,{type:"done",color:f.themedColor.secondary,size:16}))}},md=h.default(lt)`margin-bottom:2px;width:16px;height:16px;`,hd=({createdAt:e})=>{const{stringSet:t,format:n}=K();return e?o.createElement(M,{variant:"caption4",color:f.themedColor.textLowEmphasis},n(e,t.DATE_FORMAT__MESSAGE_TIMESTAMP)):null},gd=e=>{const{components:t}=ut.useContext(),{stringSet:n}=K(),r=()=>{const i=Fr(e)?o.createElement(t.TextMessageBody,{...e}):null;return e.messageType==="user"?i:e.messageType==="file"?e.file.type.startsWith("image")?o.createElement(t.MediaMessageBody,{...e},i):o.createElement(t.FileMessageBody,{...e},i):e.messageType==="multipleFiles"?o.createElement(t.MultipleFilesMessageBody,{...e},i):o.createElement(t.TextMessageBody,{...e,message:n.UNKNOWN__UNKNOWN_MESSAGE_TYPE})},s=e.sendingStatus==="failed"&&e.onClickFailedMessage,a=i=>{var l;(i.key==="Enter"||i.key===" ")&&(i.preventDefault(),(l=e.onClickFailedMessage)==null||l.call(e))};return o.createElement("div",{...s&&{onClick:e.onClickFailedMessage,onKeyDown:a,role:"button",tabIndex:0},style:{display:"contents",cursor:s?"pointer":"default"}},r())},fd=e=>{const{components:t}=ut.useContext(),n=e.sendingStatus==="succeeded",r=e.groupType==="bottom"||e.groupType==="single";return o.createElement(pd,{$marginBottom:yn(e.groupType)},o.createElement(Ed,null,o.createElement(t.MessageBody,{...e})),r&&o.createElement(bd,{$extraEndPadding:8},n?o.createElement(t.SentTime,{...e}):o.createElement(t.SendingStatus,{...e})))},ut=pe({template:fd,components:{SendingStatus:dd,SentTime:hd,MessageBody:gd,TextMessageBody:ld,MediaMessageBody:nd,FileMessageBody:ed,MultipleFilesMessageBody:ad}}),pd=h.default.div`display:flex;flex:1;flex-direction:column;align-items:flex-end;margin-bottom:${({$marginBottom:e})=>`${e}px`};
|
|
247
|
+
`,ys=h.default.div`display:flex;align-self:stretch;justify-content:flex-end;${({$startPadding:e=H.HORIZONTAL_PADDING,$endPadding:t=H.HORIZONTAL_PADDING,$extraEndPadding:n=0})=>`padding-inline: ${e}px ${t+n}px;`};
|
|
248
|
+
`,Ed=h.default(ys)``,bd=h.default(ys)`margin-top:${H.BODY_TIME_GAP}px;`,_d=e=>e.messageType!=="admin"?null:o.createElement(Cd,null,o.createElement(M,{variant:"caption2",color:f.themedColor.textMidEmphasis},xd(Dr.default.sanitize(e.message)))),Cd=h.default.div`text-align:center;text-wrap:pretty;word-break:break-word;padding-inline:${H.HORIZONTAL_PADDING}px;a{text-decoration:underline;color:inherit;}`,xd=e=>{try{const t=[];let n=e,r=0;for(;n;){const s=n.match(/\[([^\]]+)\]\((https?:\/\/[^\s]+)\)/),a=n.match(/\*\*([^*]+)\*\*/),i=[s&&{match:s,type:"link"},a&&{match:a,type:"bold"}].filter(p=>!!p);if(!i.length){t.push(n);break}const l=i.reduce((p,E)=>E.match.index<p.match.index?E:p),{match:c,type:d}=l,m=c.index;m>0&&t.push(n.slice(0,m)),d==="link"?t.push(o.createElement("a",{key:r++,href:c[2],target:"_blank",rel:On},c[1])):d==="bold"&&t.push(o.createElement("strong",{key:r++},c[1])),n=n.slice(m+c[0].length)}return t.filter(s=>s!=="")}catch{return[e]}},Ss=({onClick:e,checked:t,label:n,disabled:r,labelVariant:s="caption2"})=>{const a=t?f.themedColor.primary:r?f.themedColor.textDisabled:f.themedColor.textLowEmphasis,i=t?f.themedColor.textHighEmphasis:r?f.themedColor.textLowEmphasis:f.themedColor.textHighEmphasis;return o.createElement(Sd,{onClick:e,disabled:r},o.createElement(vd,null,o.createElement(U,{size:20,type:t?"radio-on":"radio-off",color:a})),o.createElement(yd,{variant:s,color:i},n))},vd=h.default.div`width:20px;height:20px;`,yd=h.default(M)`line-height:20px;word-break:break-word;`,Sd=h.default.button`all:unset;display:flex;align-items:flex-start;justify-content:flex-start;gap:2px;&:enabled{cursor:pointer;}`,Ad=({csatPayload:e,submitted:t,defaultValue:n,value:r,onChange:s})=>(u.useEffect(()=>{typeof r>"u"&&typeof n=="boolean"&&(s==null||s(n))},[r,n]),e.cre?o.createElement(Td,null,o.createElement(J.Label,{required:e.cre.required},e.cre.question),o.createElement(Id,null,[{label:e.cre.positive_label,value:!0},{label:e.cre.negative_label,value:!1}].map(a=>o.createElement(Ss,{key:a.label,checked:r===a.value,label:a.label,disabled:t,onClick:()=>s==null?void 0:s(a.value)})))):null),Td=h.default.div`display:flex;flex-direction:column;gap:8px;`,Id=h.default.div`display:flex;flex-direction:column;gap:8px;`,wd=({followUpItem:e,submitted:t,value:n="",onChange:r,hasError:s})=>{const{stringSet:a}=K();return o.createElement(kd,null,o.createElement(J.Label,{required:e.required},e.question),e.response_type==="free_text"&&o.createElement(J.TextInput,{variant:"multi-line",disabled:t,submitted:t,maxLength:100,value:n,onChange:i=>r(i),error:s}),e.response_type==="single_choice"&&o.createElement(Md,null,e.options.map(i=>o.createElement(Ss,{key:i,checked:n===i,label:i,disabled:t,onClick:()=>r==null?void 0:r(i),labelVariant:"body3"}))),s&&o.createElement(J.ErrorLabel,null,a.FORM_VALIDATION_REQUIRED))},kd=h.default.div`display:flex;flex-direction:column;gap:8px;`,Md=h.default.div`display:flex;flex-direction:column;gap:8px;`,$d=({value:e,selected:t,label:n})=>o.createElement(Ld,{$selected:t,"aria-label":n},Rd[e-1]),Ld=h.default.div`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,Rd=[o.createElement("svg",{width:"40",height:"40",viewBox:"0 0 40 40",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o.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)"}),o.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"}),o.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"}),o.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"}),o.createElement("defs",null,o.createElement("linearGradient",{id:"paint0_linear_159_173206",x1:"20",y1:"2.08325",x2:"20",y2:"37.9166",gradientUnits:"userSpaceOnUse"},o.createElement("stop",{stopColor:"#FF2D1D"}),o.createElement("stop",{offset:"1",stopColor:"#FFA540"})))),o.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},o.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"}),o.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"}),o.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"}),o.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"})),o.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},o.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"}),o.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"}),o.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"})),o.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},o.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"}),o.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"}),o.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"})),o.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},o.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"}),o.createElement("g",{clipPath:"url(#clip0_159_173224)"},o.createElement("g",{clipPath:"url(#clip1_159_173224)"},o.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"})),o.createElement("mask",{id:"mask0_159_173224",style:{maskType:"alpha"},maskUnits:"userSpaceOnUse",x:"12",y:"22",width:"16",height:"9"},o.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"})),o.createElement("g",{mask:"url(#mask0_159_173224)"},o.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"}))),o.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"}),o.createElement("defs",null,o.createElement("clipPath",{id:"clip0_159_173224"},o.createElement("rect",{width:"15.83",height:"7.915",fill:"white",transform:"translate(12.085 22.709)"})),o.createElement("clipPath",{id:"clip1_159_173224"},o.createElement("rect",{width:"15.83",height:"7.915",fill:"white",transform:"translate(12.085 22.709)"}))))],Od=({csatPayload:e,submitted:t,value:n,onChange:r})=>{const s=typeof n>"u";return o.createElement(Nd,null,o.createElement(M,{variant:"caption3",color:f.themedColor.textMidEmphasis},e.csat_question),o.createElement(Pd,null,e.csat_scores.map(({label:a,image_url:i},l)=>{const c=l+1,d=n===c;return o.createElement(Fd,{key:l,disabled:t,onClick:()=>r(c)},o.createElement(Dd,{value:c,selected:s||d,label:a,src:i}),!!a&&o.createElement(M,{color:d?f.themedColor.textHighEmphasis:f.themedColor.textLowEmphasis,variant:"caption3"},a))})))},Dd=({value:e,src:t,label:n,selected:r})=>{const[s,a]=u.useState(!1),i=s?o.createElement($d,{value:e,selected:r,label:n}):o.createElement(Ud,{$selected:r,"aria-label":n,src:t,onError:()=>a(!0)});return o.createElement(Bd,null,i)},Nd=h.default.div`display:flex;flex-direction:column;gap:8px;`,Pd=h.default.div`display:flex;justify-content:space-between;align-self:center;width:100%;max-width:400px;gap:16px;`,Fd=h.default.button`background-color:transparent;border:none;gap:4px;display:flex;flex-direction:column;align-items:center;justify-content:start;box-sizing:border-box;min-width:48px;max-width:68px;&:hover:not(:disabled) span{color:${f.themedColor.textHighEmphasis};}`,Bd=h.default.div`button:hover:not(:disabled) &{border-radius:4px;cursor:pointer;background-color:${f.color.background200};${F.dark`
|
|
249
249
|
background-color: ${f.color.background500};
|
|
250
250
|
`}
|
|
251
251
|
}
|
|
252
|
-
`,
|
|
252
|
+
`,Ud=h.default.img`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,Hd=({csatPayload:e})=>o.createElement(M,{variant:"button",color:f.themedColor.textHighEmphasis},e.title),sn=({csatPayload:e,type:t,renderSubmitButton:n,initialCsat:r,initialCsatReason:s,initialIsResolved:a})=>{const{params:i,setParams:l,error:c,setError:d,followUpItem:m,state:p,validateParams:E,itemProps:v}=ii({csatPayload:e,type:t,initialCsat:r,initialCsatReason:s,initialIsResolved:a});return o.createElement(o.Fragment,null,o.createElement(Vd,null,o.createElement(Hd,{...v}),t===he.AI_AGENT_CSAT_5_WITH_CRE&&o.createElement(Ad,{...v,defaultValue:a,value:i.isResolved,onChange:x=>l({isResolved:x})}),o.createElement(Od,{...v,value:i.csat,onChange:x=>l({csat:x})}),m&&o.createElement(wd,{...v,followUpItem:m,value:i.csatReason,onChange:x=>{l({csatReason:x}),d({followUpItem:!1})},hasError:c.followUpItem})),p!=="unsubmittable"&&o.createElement(o.Fragment,null,o.createElement(J.Separator,null),n({state:p,params:i,validateParams:E})))},Vd=h.default.div`display:flex;flex-direction:column;gap:12px;`,zd=e=>{const{stringSet:t}=K();return Do(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})},Gd=()=>{const{stringSet:e}=K();return o.createElement(M,{variant:"body2",color:f.themedColor.textMidEmphasis,style:{textAlign:"center"}},e.CSAT_SUBMISSION_EXPIRED)},qd=({onMount:e,children:t})=>(u.useEffect(()=>{e&&kt(e)},[]),o.createElement(o.Fragment,null,t)),Wd=e=>{if(e.messageType!=="admin.csat")throw new Error("Invalid message type");const{extendedMessagePayload:t,onSubmitCSAT:n,onScrollToBottom:r}=e,{csat:s,csatReason:a,csatExpireAt:i,isResolvedWhenDeterminedByUser:l}=e,c=Le.useForceUpdate(),d=zd(t==null?void 0:t.csat),m=u.useRef(!1);if(!d||!d.visibility||!he[d.type])return null;const p=d.type===he.AI_AGENT_CSAT_5||d.type===he.AI_AGENT_CSAT_5_WITH_CRE||d.type===he.HELPDESK_CSAT_5?sn:()=>null;return o.createElement(Kd,null,!s&&Xn(i)?o.createElement(Gd,null):o.createElement(p,{csatPayload:d,type:d.type,initialCsat:s,initialCsatReason:a,initialIsResolved:l,renderSubmitButton:({state:E,params:v,validateParams:x})=>o.createElement(qd,{onMount:r},o.createElement(jd,{$state:E,disabled:E==="submitted",onClick:async()=>{m.current||(!Xn(i)&&x()?(m.current=!0,await n(v).finally(()=>{m.current=!1})):c())}},o.createElement(M,{variant:"button"},E==="submitted"?d.csat_submitted_label:d.csat_submit_label)))}))},Kd=h.default.div`display:flex;flex-direction:column;background-color:${({theme:e})=>e.colors.csat.background};border-radius:16px;gap:16px;padding:16px;`,jd=h.default.button`all:unset;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;&:hover{background-color:${f.color.primary.dark};}&:disabled{color:${({$state:e})=>e==="submitted"?f.themedColor.textHighEmphasis:f.color.ondark.textLowEmphasis};background-color:${f.themedColor.textDisabled};cursor:not-allowed;}`,Yd=e=>{const{components:t}=Bt.useContext(),n=e.messageType==="admin"?o.createElement(t.AdminMessage,{...e}):e.messageType==="admin.csat"?o.createElement(t.CSATMessage,{...e}):null;return o.createElement(Xd,{$marginBottom:yn(e.groupType)},n)},Bt=pe({template:Yd,components:{AdminMessage:_d,CSATMessage:Wd}}),Xd=h.default.div`padding-inline:${H.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>e}px;`,Ar={file:"attach",snippet:"snippet",site:"website",sb_sprinklr:"sprinklr",sb_salesforce:"salesforce",sb_confluence:"confluence",sb_zendesk:"zendesk",sb_desk:"snippet"},As=({actionbook:e,functionCalls:t,groundedness:n,agentMessageTemplates:r,onClickActionbook:s,onClickFunctionCall:a,onClickFunctionCallDetail:i,onClickGroundedness:l,onClickAgentMessageTemplate:c,bottomContent:d,renderCustomGroundednessIcon:m=E=>E.default,style:p={}})=>{const{iconColor:E="#000000",textColor:v="#000000",highlightColor:x=nt.DEFAULT_PRIMARY}=p;return o.createElement(Tr,null,e&&o.createElement(Tr,null,o.createElement(Lt,null,o.createElement(vt,null,o.createElement(U,{size:16,type:"actionbook",color:E})),o.createElement(xt,{$clickable:!!s,$highlightColor:x,variant:"body2",color:v,onClick:()=>s==null?void 0:s(e),maxTextLines:1},e.name))),t==null?void 0:t.map(b=>o.createElement(on,{key:b.key},o.createElement(vt,null,o.createElement(U,{size:16,type:"function",color:E})),o.createElement(Lt,null,o.createElement(xt,{$clickable:!!a,$highlightColor:x,variant:"body2",color:v,onClick:()=>a==null?void 0:a(b),maxTextLines:1},b.name),i&&o.createElement(Jd,{role:"button",onClick:()=>i==null?void 0:i(b)},o.createElement(M,{variant:"body2",color:x},"View details"),o.createElement(U,{type:"chevron-right",size:16,color:x}))))),n==null?void 0:n.map(b=>o.createElement(on,{key:b.id},o.createElement(vt,null,m({default:o.createElement(U,{size:16,type:Ar[b.source_type]??Ar.snippet,color:E}),sourceType:b.source_type})),o.createElement(xt,{$clickable:!!l,$highlightColor:x,variant:"body2",color:v,onClick:()=>l==null?void 0:l(b),maxTextLines:1},b.preview_title))),r==null?void 0:r.map(b=>o.createElement(on,{key:b.key},o.createElement(vt,null,o.createElement(U,{size:16,type:"template",color:E})),o.createElement(xt,{$clickable:!!c,$highlightColor:x,variant:"body2",color:v,onClick:()=>c==null?void 0:c(b),maxTextLines:1},b.name))),d)},Zd=h.default(M)`font-weight:400;`,xt=h.default(Zd)`${({$clickable:e,$highlightColor:t})=>e&&w.css`
|
|
253
253
|
cursor: pointer;
|
|
254
254
|
text-decoration: underline;
|
|
255
255
|
&:hover {
|
|
256
256
|
color: ${t};
|
|
257
257
|
}
|
|
258
258
|
`}
|
|
259
|
-
`,vt=h.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,Lt=h.default.div`display:flex;gap:8px;align-items:center;word-break:break-word;`,Zd=h.default(Lt)`cursor:pointer;gap:4px;`,on=h.default(Lt)`flex-direction:row;align-items:center;`,Tr=h.default.div`display:flex;gap:4px;flex-direction:column;align-items:flex-start;`,As=u.createContext(null);function Jd({testerType:e,origin:t,children:n}){return o.createElement(As.Provider,{value:{testerType:e,isActionbookTester:e==="actionbook",origin:t}},e&&o.createElement(Qd,null),n)}const Ye=()=>{const e=u.useContext(As);if(!e)throw new Error("_UNSAFE_INTERNAL_DashboardTesterProvider not found");return e},Qd=()=>{const{isActionbookTester:e}=Ye();return o.createElement(De.Template,{template:e?em:void 0},o.createElement(De.MessageLogs,{component:tm}))},em=e=>o.createElement(xs,{...e,testerMode:!0,maxBodyWidth:H.WIDE_BODY_MAX_WIDTH}),tm=({extendedMessagePayload:e={}})=>{const{handlers:t}=j(),{manual:n,groundedness:r,function_calls:s,agent_message_templates:a,is_thinking:i}=e;return i||!n&&!(r!=null&&r.length)&&!(s!=null&&s.length)&&!(a!=null&&a.length)?o.createElement(o.Fragment,null):o.createElement(nm,null,o.createElement(rm,{width:4}),o.createElement(Ss,{actionbook:n,functionCalls:s,groundedness:r,agentMessageTemplates:a,onClickFunctionCallDetail:t==null?void 0:t.onFunctionCallDetailClick,style:{iconColor:f.themedColor.textHighEmphasis,textColor:f.themedColor.textHighEmphasis,barColor:f.themedColor.textDisabled},bottomContent:o.createElement(sm,{variant:"caption2",color:f.themedColor.textLowEmphasis},"Only visible in the tester")}))},nm=h.default.div`display:flex;gap:16px;margin:16px ${H.HORIZONTAL_PADDING}px 0;align-self:stretch;`,rm=h.default.div`width:${({width:e})=>e}px;background-color:${f.themedColor.textDisabled};border-radius:100px;flex-shrink:0;`,sm=h.default(M)`margin-top:5px;`,om=u.forwardRef(function(t,n){const{messages:r,renderMessage:s,loading:a,LoadingComponent:i,error:l,ErrorComponent:c,empty:d,EmptyComponent:m,messageTopArea:p,messageBottomArea:E,overlayArea:v,onLoadPrev:x,onLoadNext:b,loadThreshold:g=.05,onScroll:_=Ce,depsForResetScrollPositionToBottom:y,stackDirection:I="top",bottomSpacerHeight:A=0,ariaLabel:$}=t,k=u.useRef(null),S=u.useCallback(N=>{k.current=N,n&&(typeof n=="function"?n(N):n.current=N)},[n]),R=u.useRef(!1),P=u.useRef(void 0),O=u.useRef(0),T=u.useRef(0);u.useLayoutEffect(()=>{k.current&&(k.current.scrollTop=k.current.scrollHeight)},y),u.useLayoutEffect(()=>{k.current&&(P.current==="top"&&(k.current.scrollTop=k.current.scrollHeight-T.current),P.current==="bottom"&&(k.current.scrollTop=O.current),P.current=void 0)},[k.current,r.length]);const B=async N=>{if(_==null||_(N),!k.current)return;const z=k.current;if(T.current=z.scrollHeight-z.scrollTop,O.current=z.scrollTop,R.current)return;const Y=z.clientHeight*Math.min(Math.max(0,g),1);z.scrollTop<=Y?(R.current=!0,P.current="top",await x(),R.current=!1):z.scrollHeight-z.scrollTop-z.clientHeight<=Y?(R.current=!0,P.current="bottom",await b(),R.current=!1):P.current=void 0};return l?o.createElement(o.Fragment,null,c):a?o.createElement(o.Fragment,null,i):o.createElement(am,{id:"infinite-list-container"},o.createElement(im,{id:"infinite-list-inner",ref:S,onScroll:B,role:"list","aria-label":$},I==="bottom"&&o.createElement("div",{style:{flexGrow:1}}),p,d?m:r.map((N,z)=>s({message:N,index:z})),E,A>0&&o.createElement("div",{style:{minHeight:A}})),o.createElement(lm,{id:"infinite-list-overlay-container"},o.createElement(cm,{id:"infinite-list-overlay"},v)))}),am=h.default.div`display:flex;position:relative;flex:1;overflow:hidden;`,im=h.default.div`display:flex;flex:1;flex-direction:column;overflow-y:auto;overscroll-behavior:contain;scrollbar-color:${f.themedColor.textLowEmphasis}transparent;&::-webkit-scrollbar-thumb:hover{background-color:transparent;}`,lm=h.default.div`position:absolute;top:0;bottom:0;left:0;right:0;pointer-events:none;`,cm=h.default.div`pointer-events:auto;`,um=e=>we(e)||Pr(e);function dm(e){return e.isAdminMessage()?e.message==="The channel's custom_type was updated.":!1}function mm(e,t){return e.filter(n=>Me.isWelcomeMessage(n,t))}const ve=({as:e,type:t,size:n=16,color:r,disabled:s,...a})=>{const i=s?f.themedColor.textDisabled:f.themedColor.textHighEmphasis;return o.createElement(hm,{as:e,disabled:s,...a},o.createElement(U,{type:t,size:n,color:r??i}))},hm=h.default.button`all:unset;padding:4px;cursor:pointer;display:flex;align-items:center;justify-content:center;&:disabled{cursor:not-allowed;}`,gm=({files:e,initialIndex:t=0,onClose:n,visible:r})=>{var $,k;const[s,a]=u.useState(t),[i,l]=u.useState(!1),{stringSet:c,format:d}=K(),{config:m}=j(),p=e.length,E=e[s],v=((k=($=m==null?void 0:m.conversation)==null?void 0:$.fileViewer)==null?void 0:k.downloadEnabled)!==!1,x=p>1,b=(E==null?void 0:E.type)||"",g=we(b),_=Pr(b),y=!um(b);u.useEffect(()=>{r&&(a(t),l(!1))},[r,t]);const I=u.useCallback(()=>{s>0&&(a(S=>S-1),l(!1))},[s]),A=u.useCallback(()=>{s<p-1&&(a(S=>S+1),l(!1))},[s,p]);return u.useEffect(()=>{if(!r)return;const S=R=>{R.key==="ArrowLeft"?I():R.key==="ArrowRight"?A():R.key==="Escape"&&n()};return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[r,I,A,n]),!r||!E?null:o.createElement(Pt,{onClose:n,visible:r,rootElementId:de.MODAL_ROOT},o.createElement(fm,null,o.createElement(pm,null,o.createElement(Em,null,o.createElement(bm,null,o.createElement(M,{variant:"button",maxTextLines:1,color:f.themedColor.textHighEmphasis},E.name||c.IMAGE_VIEWER__DEFAULT_TITLE),E.timestamp&&o.createElement(M,{variant:"caption2",color:f.themedColor.textMidEmphasis},d(new Date(E.timestamp),"h:mm a")))),o.createElement(_m,{type:"close",size:24,"aria-label":c.A11Y_IMAGE_VIEWER_CLOSE,onClick:n})),o.createElement(Cm,{onClick:S=>S.currentTarget===S.target&&n()},x&&o.createElement(Ir,{$position:"left",type:"chevron-right",size:32,onClick:I,"aria-label":c.A11Y_IMAGE_VIEWER_PREVIOUS,disabled:s===0,$flipped:!0}),o.createElement(xm,null,g&&o.createElement(o.Fragment,null,!i&&o.createElement(vm,null,o.createElement(lt,{size:32},o.createElement(U,{type:"spinner",color:"textLowEmphasis",size:32}))),o.createElement(ym,{src:E.url,alt:E.name||"Image",$loaded:i,onLoad:()=>l(!0)})),_&&o.createElement(Sm,{controls:!0},o.createElement("source",{src:E.url,type:b})),y&&o.createElement(Am,null,o.createElement(M,{variant:"h1",color:f.themedColor.textHighEmphasis},c.FILE_VIEWER__UNSUPPORT))),x&&o.createElement(Ir,{$position:"right",type:"chevron-right",size:32,onClick:A,"aria-label":c.A11Y_IMAGE_VIEWER_NEXT,disabled:s===p-1})),o.createElement(Tm,null,o.createElement(Im,null),x&&o.createElement(M,{variant:"body3",color:f.themedColor.textHighEmphasis},s+1,"/",p),o.createElement(wm,null,v&&!y&&o.createElement(ve,{as:"a",href:E.url,download:E.name||"file",type:"download",size:24,"aria-label":c.A11Y_IMAGE_VIEWER_DOWNLOAD})))))},fm=h.default.div`position:fixed;inset:0;outline:none;display:flex;flex-direction:column;background-color:${f.themedColor.bg_50_600};`,pm=h.default.header`display:flex;align-items:center;justify-content:space-between;padding:12px 16px;min-height:56px;border-bottom:1px solid ${f.themedColor.textDisabled};`,Em=h.default.div`flex:1;min-width:0;padding-right:16px;`,bm=h.default.div`display:flex;flex-direction:column;gap:2px;`,_m=h.default(ve)`flex-shrink:0;width:32px;height:32px;border-radius:50%;&:hover{background-color:${f.themedColor.bg_100_500};}`,Ut=h.default.div`display:flex;align-items:center;justify-content:center;`,Cm=h.default(Ut)`flex:1;min-height:0;position:relative;padding:0 16px;`,xm=h.default(Ut)`position:relative;max-width:100%;max-height:100%;`,vm=h.default(Ut)`position:absolute;inset:0;`,ym=h.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;`,Sm=h.default.video`max-width:100%;max-height:100%;object-fit:contain;`,Am=h.default(Ut)`flex-direction:column;gap:16px;`,Ir=h.default(ve)`position:absolute;${e=>e.$position==="left"?"left: 16px;":"right: 16px;"}top:50%;transform:translateY(-50%) ${e=>e.$flipped?"scaleX(-1)":""};border-radius:50%;&:hover:not(:disabled){background-color:${f.themedColor.bg_200_400};}&:disabled{opacity:0.3;}@media (max-width:480px){width:38px;height:38px;${e=>e.$position==="left"?"left: 8px;":"right: 8px;"}}`,Tm=h.default.footer`display:flex;align-items:center;justify-content:space-between;padding:16px;min-height:56px;border-top:1px solid ${f.themedColor.textDisabled};`,Im=h.default.div`width:40px;`,wm=h.default.div`display:flex;align-items:center;justify-content:flex-end;width:40px;`,km=({className:e,label:t,ariaLabel:n,onClick:r})=>{const{colors:s}=w.useTheme();return o.createElement(Mm,{className:e,onClick:r,"aria-label":n},o.createElement(M,{variant:"button",color:s.base.primaryContrastContent},t),o.createElement(U,{size:16,type:"chevron-down",color:s.base.primaryContrastContent}))},Mm=h.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;}`,Un=({iconSize:e=64,icon:t,className:n,label:r,children:s})=>o.createElement(Lm,{className:n},t&&o.createElement(U,{type:t,size:e,color:f.themedColor.textLowEmphasis}),r&&o.createElement(M,{variant:"body1",color:f.themedColor.textMidEmphasis},r),s),$m=h.default.div`position:relative;display:flex;justify-content:center;align-items:center;width:100%;height:100%;`,Lm=h.default.div`display:flex;flex-direction:column;min-height:104px;align-items:center;gap:20px;text-align:center;`,Rm=({label:e="Something went wrong",icon:t="error",action:n,...r})=>o.createElement(Un,{icon:t,label:e,...r},n&&o.createElement(Om,{onClick:n.onClick,label:n.label??"Retry"})),Om=({label:e,onClick:t})=>o.createElement(Dm,{tabIndex:0,onClick:t},o.createElement(U,{type:"refresh",size:20}),o.createElement(M,{variant:"button",color:f.color.primary.main},e)),Dm=h.default.button`all:unset;display:flex;cursor:pointer;gap:4px;align-items:center;justify-content:center;`,Nm=({iconSize:e=48,className:t})=>o.createElement(lt,{size:e,className:t}),Pm=({label:e="No channels",icon:t="chat",...n})=>o.createElement(Un,{icon:t,label:e,...n}),Fm=({label:e="No messages",icon:t="message",...n})=>o.createElement(Un,{icon:t,label:e,...n}),Bm=e=>{const{components:t}=Ht.useContext(),n=e.type==="loading"?o.createElement(t.Loading,{...e}):e.type==="error"?o.createElement(t.Error,{...e}):e.type==="noChannels"?o.createElement(t.NoChannels,{...e}):e.type==="noMessages"?o.createElement(t.NoMessages,{...e}):null;return n&&o.createElement($m,null,n)},Ht=pe({template:Bm,components:{Loading:Nm,Error:Rm,NoChannels:Pm,NoMessages:Fm}}),et=e=>{const{Template:t}=Ht.useContext();return o.createElement(t,{...e})},Um=[0,150,450];function Hm({enabled:e}){const{state:t,actions:n}=as(),r=u.useRef(0),s=u.useRef(t.isAwayFromBottom);s.current=t.isAwayFromBottom,u.useEffect(()=>{if(!e){r.current+=1;return}const a=r.current+1;r.current=a;const i=Um.map(l=>setTimeout(()=>{kt(()=>{r.current===a&&(s.current||n.scrollToBottom(!1))})},l));return()=>{r.current+=1,i.forEach(l=>clearTimeout(l))}},[n.scrollToBottom,e])}const Vm=({className:e,date:t=Date.now(),style:n})=>{const{format:r,stringSet:s}=K();return o.createElement(zm,{id:`${le}-date-separator`,style:n,className:e},o.createElement(M,{variant:"caption4",color:f.themedColor.textMidEmphasis},r(t,s.DATE_FORMAT__MESSAGE_LIST__DATE_SEPARATOR)))},zm=h.default.div`display:flex;justify-content:center;align-items:center;text-align:center;word-break:break-word;`,Gm=({className:e,style:t,onClick:n,ariaLabel:r})=>o.createElement(qm,{className:e,style:t,onClick:n,tabIndex:0,"aria-label":r},o.createElement(U,{size:24,type:"chevron-down",color:f.color.primary.main})),qm=h.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);${F.light`
|
|
259
|
+
`,vt=h.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,Lt=h.default.div`display:flex;gap:8px;align-items:center;word-break:break-word;`,Jd=h.default(Lt)`cursor:pointer;gap:4px;`,on=h.default(Lt)`flex-direction:row;align-items:center;`,Tr=h.default.div`display:flex;gap:4px;flex-direction:column;align-items:flex-start;`,Ts=u.createContext(null);function Qd({testerType:e,origin:t,children:n}){return o.createElement(Ts.Provider,{value:{testerType:e,isActionbookTester:e==="actionbook",origin:t}},e&&o.createElement(em,null),n)}const Ye=()=>{const e=u.useContext(Ts);if(!e)throw new Error("_UNSAFE_INTERNAL_DashboardTesterProvider not found");return e},em=()=>{const{isActionbookTester:e}=Ye();return o.createElement(De.Template,{template:e?tm:void 0},o.createElement(De.MessageLogs,{component:nm}))},tm=e=>o.createElement(vs,{...e,testerMode:!0,maxBodyWidth:H.WIDE_BODY_MAX_WIDTH}),nm=({extendedMessagePayload:e={}})=>{const{handlers:t}=j(),{manual:n,groundedness:r,function_calls:s,agent_message_templates:a,is_thinking:i}=e;return i||!n&&!(r!=null&&r.length)&&!(s!=null&&s.length)&&!(a!=null&&a.length)?o.createElement(o.Fragment,null):o.createElement(rm,null,o.createElement(sm,{width:4}),o.createElement(As,{actionbook:n,functionCalls:s,groundedness:r,agentMessageTemplates:a,onClickFunctionCallDetail:t==null?void 0:t.onFunctionCallDetailClick,style:{iconColor:f.themedColor.textHighEmphasis,textColor:f.themedColor.textHighEmphasis,barColor:f.themedColor.textDisabled},bottomContent:o.createElement(om,{variant:"caption2",color:f.themedColor.textLowEmphasis},"Only visible in the tester")}))},rm=h.default.div`display:flex;gap:16px;margin:16px ${H.HORIZONTAL_PADDING}px 0;align-self:stretch;`,sm=h.default.div`width:${({width:e})=>e}px;background-color:${f.themedColor.textDisabled};border-radius:100px;flex-shrink:0;`,om=h.default(M)`margin-top:5px;`,am=u.forwardRef(function(t,n){const{messages:r,renderMessage:s,loading:a,LoadingComponent:i,error:l,ErrorComponent:c,empty:d,EmptyComponent:m,messageTopArea:p,messageBottomArea:E,overlayArea:v,onLoadPrev:x,onLoadNext:b,loadThreshold:g=.05,onScroll:_=Ce,depsForResetScrollPositionToBottom:y,stackDirection:I="top",bottomSpacerHeight:A=0,ariaLabel:$}=t,k=u.useRef(null),S=u.useCallback(N=>{k.current=N,n&&(typeof n=="function"?n(N):n.current=N)},[n]),R=u.useRef(!1),P=u.useRef(void 0),O=u.useRef(0),T=u.useRef(0);u.useLayoutEffect(()=>{k.current&&(k.current.scrollTop=k.current.scrollHeight)},y),u.useLayoutEffect(()=>{k.current&&(P.current==="top"&&(k.current.scrollTop=k.current.scrollHeight-T.current),P.current==="bottom"&&(k.current.scrollTop=O.current),P.current=void 0)},[k.current,r.length]);const B=async N=>{if(_==null||_(N),!k.current)return;const z=k.current;if(T.current=z.scrollHeight-z.scrollTop,O.current=z.scrollTop,R.current)return;const Y=z.clientHeight*Math.min(Math.max(0,g),1);z.scrollTop<=Y?(R.current=!0,P.current="top",await x(),R.current=!1):z.scrollHeight-z.scrollTop-z.clientHeight<=Y?(R.current=!0,P.current="bottom",await b(),R.current=!1):P.current=void 0};return l?o.createElement(o.Fragment,null,c):a?o.createElement(o.Fragment,null,i):o.createElement(im,{id:"infinite-list-container"},o.createElement(lm,{id:"infinite-list-inner",ref:S,onScroll:B,role:"list","aria-label":$},I==="bottom"&&o.createElement("div",{style:{flexGrow:1}}),p,d?m:r.map((N,z)=>s({message:N,index:z})),E,A>0&&o.createElement("div",{style:{minHeight:A}})),o.createElement(cm,{id:"infinite-list-overlay-container"},o.createElement(um,{id:"infinite-list-overlay"},v)))}),im=h.default.div`display:flex;position:relative;flex:1;overflow:hidden;`,lm=h.default.div`display:flex;flex:1;flex-direction:column;overflow-y:auto;overscroll-behavior:contain;scrollbar-color:${f.themedColor.textLowEmphasis}transparent;&::-webkit-scrollbar-thumb:hover{background-color:transparent;}`,cm=h.default.div`position:absolute;top:0;bottom:0;left:0;right:0;pointer-events:none;`,um=h.default.div`pointer-events:auto;`,dm=e=>we(e)||Pr(e);function mm(e){return e.isAdminMessage()?e.message==="The channel's custom_type was updated.":!1}function hm(e,t){return e.filter(n=>Me.isWelcomeMessage(n,t))}const ve=({as:e,type:t,size:n=16,color:r,disabled:s,...a})=>{const i=s?f.themedColor.textDisabled:f.themedColor.textHighEmphasis;return o.createElement(gm,{as:e,disabled:s,...a},o.createElement(U,{type:t,size:n,color:r??i}))},gm=h.default.button`all:unset;padding:4px;cursor:pointer;display:flex;align-items:center;justify-content:center;&:disabled{cursor:not-allowed;}`,fm=({files:e,initialIndex:t=0,onClose:n,visible:r})=>{var $,k;const[s,a]=u.useState(t),[i,l]=u.useState(!1),{stringSet:c,format:d}=K(),{config:m}=j(),p=e.length,E=e[s],v=((k=($=m==null?void 0:m.conversation)==null?void 0:$.fileViewer)==null?void 0:k.downloadEnabled)!==!1,x=p>1,b=(E==null?void 0:E.type)||"",g=we(b),_=Pr(b),y=!dm(b);u.useEffect(()=>{r&&(a(t),l(!1))},[r,t]);const I=u.useCallback(()=>{s>0&&(a(S=>S-1),l(!1))},[s]),A=u.useCallback(()=>{s<p-1&&(a(S=>S+1),l(!1))},[s,p]);return u.useEffect(()=>{if(!r)return;const S=R=>{R.key==="ArrowLeft"?I():R.key==="ArrowRight"?A():R.key==="Escape"&&n()};return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[r,I,A,n]),!r||!E?null:o.createElement(Pt,{onClose:n,visible:r,rootElementId:me.MODAL_ROOT},o.createElement(pm,null,o.createElement(Em,null,o.createElement(bm,null,o.createElement(_m,null,o.createElement(M,{variant:"button",maxTextLines:1,color:f.themedColor.textHighEmphasis},E.name||c.IMAGE_VIEWER__DEFAULT_TITLE),E.timestamp&&o.createElement(M,{variant:"caption2",color:f.themedColor.textMidEmphasis},d(new Date(E.timestamp),"h:mm a")))),o.createElement(Cm,{type:"close",size:24,"aria-label":c.A11Y_IMAGE_VIEWER_CLOSE,onClick:n})),o.createElement(xm,{onClick:S=>S.currentTarget===S.target&&n()},x&&o.createElement(Ir,{$position:"left",type:"chevron-right",size:32,onClick:I,"aria-label":c.A11Y_IMAGE_VIEWER_PREVIOUS,disabled:s===0,$flipped:!0}),o.createElement(vm,null,g&&o.createElement(o.Fragment,null,!i&&o.createElement(ym,null,o.createElement(lt,{size:32},o.createElement(U,{type:"spinner",color:"textLowEmphasis",size:32}))),o.createElement(Sm,{src:E.url,alt:E.name||"Image",$loaded:i,onLoad:()=>l(!0)})),_&&o.createElement(Am,{controls:!0},o.createElement("source",{src:E.url,type:b})),y&&o.createElement(Tm,null,o.createElement(M,{variant:"h1",color:f.themedColor.textHighEmphasis},c.FILE_VIEWER__UNSUPPORT))),x&&o.createElement(Ir,{$position:"right",type:"chevron-right",size:32,onClick:A,"aria-label":c.A11Y_IMAGE_VIEWER_NEXT,disabled:s===p-1})),o.createElement(Im,null,o.createElement(wm,null),x&&o.createElement(M,{variant:"body3",color:f.themedColor.textHighEmphasis},s+1,"/",p),o.createElement(km,null,v&&!y&&o.createElement(ve,{as:"a",href:E.url,download:E.name||"file",type:"download",size:24,"aria-label":c.A11Y_IMAGE_VIEWER_DOWNLOAD})))))},pm=h.default.div`position:fixed;inset:0;outline:none;display:flex;flex-direction:column;background-color:${f.themedColor.bg_50_600};`,Em=h.default.header`display:flex;align-items:center;justify-content:space-between;padding:12px 16px;min-height:56px;border-bottom:1px solid ${f.themedColor.textDisabled};`,bm=h.default.div`flex:1;min-width:0;padding-right:16px;`,_m=h.default.div`display:flex;flex-direction:column;gap:2px;`,Cm=h.default(ve)`flex-shrink:0;width:32px;height:32px;border-radius:50%;&:hover{background-color:${f.themedColor.bg_100_500};}`,Ut=h.default.div`display:flex;align-items:center;justify-content:center;`,xm=h.default(Ut)`flex:1;min-height:0;position:relative;padding:0 16px;`,vm=h.default(Ut)`position:relative;max-width:100%;max-height:100%;`,ym=h.default(Ut)`position:absolute;inset:0;`,Sm=h.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;`,Am=h.default.video`max-width:100%;max-height:100%;object-fit:contain;`,Tm=h.default(Ut)`flex-direction:column;gap:16px;`,Ir=h.default(ve)`position:absolute;${e=>e.$position==="left"?"left: 16px;":"right: 16px;"}top:50%;transform:translateY(-50%) ${e=>e.$flipped?"scaleX(-1)":""};border-radius:50%;&:hover:not(:disabled){background-color:${f.themedColor.bg_200_400};}&:disabled{opacity:0.3;}@media (max-width:480px){width:38px;height:38px;${e=>e.$position==="left"?"left: 8px;":"right: 8px;"}}`,Im=h.default.footer`display:flex;align-items:center;justify-content:space-between;padding:16px;min-height:56px;border-top:1px solid ${f.themedColor.textDisabled};`,wm=h.default.div`width:40px;`,km=h.default.div`display:flex;align-items:center;justify-content:flex-end;width:40px;`,Mm=({className:e,label:t,ariaLabel:n,onClick:r})=>{const{colors:s}=w.useTheme();return o.createElement($m,{className:e,onClick:r,"aria-label":n},o.createElement(M,{variant:"button",color:s.base.primaryContrastContent},t),o.createElement(U,{size:16,type:"chevron-down",color:s.base.primaryContrastContent}))},$m=h.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;}`,Un=({iconSize:e=64,icon:t,className:n,label:r,children:s})=>o.createElement(Rm,{className:n},t&&o.createElement(U,{type:t,size:e,color:f.themedColor.textLowEmphasis}),r&&o.createElement(M,{variant:"body1",color:f.themedColor.textMidEmphasis},r),s),Lm=h.default.div`position:relative;display:flex;justify-content:center;align-items:center;width:100%;height:100%;`,Rm=h.default.div`display:flex;flex-direction:column;min-height:104px;align-items:center;gap:20px;text-align:center;`,Om=({label:e="Something went wrong",icon:t="error",action:n,...r})=>o.createElement(Un,{icon:t,label:e,...r},n&&o.createElement(Dm,{onClick:n.onClick,label:n.label??"Retry"})),Dm=({label:e,onClick:t})=>o.createElement(Nm,{tabIndex:0,onClick:t},o.createElement(U,{type:"refresh",size:20}),o.createElement(M,{variant:"button",color:f.color.primary.main},e)),Nm=h.default.button`all:unset;display:flex;cursor:pointer;gap:4px;align-items:center;justify-content:center;`,Pm=({iconSize:e=48,className:t})=>o.createElement(lt,{size:e,className:t}),Fm=({label:e="No channels",icon:t="chat",...n})=>o.createElement(Un,{icon:t,label:e,...n}),Bm=({label:e="No messages",icon:t="message",...n})=>o.createElement(Un,{icon:t,label:e,...n}),Um=e=>{const{components:t}=Ht.useContext(),n=e.type==="loading"?o.createElement(t.Loading,{...e}):e.type==="error"?o.createElement(t.Error,{...e}):e.type==="noChannels"?o.createElement(t.NoChannels,{...e}):e.type==="noMessages"?o.createElement(t.NoMessages,{...e}):null;return n&&o.createElement(Lm,null,n)},Ht=pe({template:Um,components:{Loading:Pm,Error:Om,NoChannels:Fm,NoMessages:Bm}}),et=e=>{const{Template:t}=Ht.useContext();return o.createElement(t,{...e})},Hm=[0,150,450];function Vm({enabled:e}){const{state:t,actions:n}=is(),r=u.useRef(0),s=u.useRef(t.isAwayFromBottom);s.current=t.isAwayFromBottom,u.useEffect(()=>{if(!e){r.current+=1;return}const a=r.current+1;r.current=a;const i=Hm.map(l=>setTimeout(()=>{kt(()=>{r.current===a&&(s.current||n.scrollToBottom(!1))})},l));return()=>{r.current+=1,i.forEach(l=>clearTimeout(l))}},[n.scrollToBottom,e])}const zm=({className:e,date:t=Date.now(),style:n})=>{const{format:r,stringSet:s}=K();return o.createElement(Gm,{id:`${le}-date-separator`,style:n,className:e},o.createElement(M,{variant:"caption4",color:f.themedColor.textMidEmphasis},r(t,s.DATE_FORMAT__MESSAGE_LIST__DATE_SEPARATOR)))},Gm=h.default.div`display:flex;justify-content:center;align-items:center;text-align:center;word-break:break-word;`,qm=({className:e,style:t,onClick:n,ariaLabel:r})=>o.createElement(Wm,{className:e,style:t,onClick:n,tabIndex:0,"aria-label":r},o.createElement(U,{size:24,type:"chevron-down",color:f.color.primary.main})),Wm=h.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);${F.light`
|
|
260
260
|
background-color: ${f.color.background50};
|
|
261
261
|
&:hover {
|
|
262
262
|
background-color: ${f.color.background100};
|
|
@@ -278,11 +278,11 @@
|
|
|
278
278
|
&:focus {
|
|
279
279
|
outline: none;
|
|
280
280
|
}
|
|
281
|
-
`,
|
|
281
|
+
`,Km=()=>null,Vt=pe({template:Km,components:{DateSeparator:zm,ScrollToBottomButton:qm}}),jm=()=>{const{agentPreviewConfigs:e={},aiAgentId:t}=j(),{aiAgentInfo:n}=oe(),{messageSource:r}=ne(),{Template:s}=De.useContext(),{components:a}=Vt.useContext(),i=e.welcomeMessages??[],l=r.messages,c=hm(l,t),d=l[c.length+1],m=c[0]??d;return{filteredMessages:l.filter(p=>mm(p)?!1:i.length>0?!Me.isWelcomeMessage(p,t):!0),shouldShowOriginalDate:p=>p>0||i.length===0?!0:d&&!Fe.isSameDay(d.createdAt,(m==null?void 0:m.createdAt)??0),renderAgentPreviewWelcomeMessages:()=>i.length===0?null:o.createElement(o.Fragment,null,o.createElement(a.DateSeparator,{style:{margin:"16px 0"},date:m==null?void 0:m.createdAt}),i.map((p,E)=>{const v=E===i.length-1,x=c.length!==l.length,b=i.length===1?"single":E===0?"top":v||x?"bottom":"middle";return o.createElement(s,{messageType:"user",message:p.message,sender:n,groupType:b,createdAt:(m==null?void 0:m.createdAt)??Date.now(),extendedMessagePayload:{suggested_replies:p.suggestedReplies},suggestedRepliesDirection:e.suggestedRepliesDirection,suggestedRepliesVisible:v&&!x,isBotMessage:!0,onClickSuggestedReply:async({reply:g})=>{r.sendUserMessage({message:g})}})}))}},Ym=()=>{const{messageSource:e,scrollSource:t}=ne();u.useEffect(()=>{!t.state.isAwayFromBottom&&t.state.isScrollPositionReconciled&&e.resetNewMessages()},[t.state.isAwayFromBottom,t.state.isScrollPositionReconciled])},Xm=e=>h.default(e).withConfig({shouldForwardProp:so.default}),Zm=({style:e})=>{const{stringSet:t}=K(),{isActionbookTester:n}=Ye();return!Rn("powered-by")||n?null:o.createElement(Jm,{variant:"caption2",style:e},t.POWERED_BY+" ",o.createElement(Qm,{variant:"caption2",as:"a",href:"https://delight.ai?utm_medium=product&utm_source=aiagent&utm_campaign=fy26-glbl-ai-agent-poweredby","aria-label":"Learn more about Delight AI Agent",rel:On,target:"_blank"},"Sendbird"))},Jm=h.default(M)`color:${f.themedColor.textLowEmphasis};text-align:center;`,Qm=Xm(M)`
|
|
282
282
|
color: ${f.themedColor.textLowEmphasis};
|
|
283
283
|
cursor: pointer;
|
|
284
284
|
text-decoration: none;
|
|
285
|
-
`,Qm=()=>{var i;const{stringSet:e}=K(),{channelSource:t,goToActiveConversation:n,scrollSource:r}=ne(),s=ue(t.channel),a=u.useRef(s);return u.useEffect(()=>{if(!a.current&&s){const d=setTimeout(()=>{r.actions.scrollToBottom()},100);return()=>clearTimeout(d)}a.current=s},[s,r.actions.scrollToBottom]),!((i=t.channel)!=null&&i.isAIAgent)||!s?null:o.createElement(eh,null,o.createElement(th,{variant:"button",role:"button",color:f.themedColor.textHighEmphasis,onClick:()=>n()},e.TALK_TO_AGENT))},eh=h.default.div`display:flex;justify-content:center;margin-bottom:16px;`,th=h.default(M)`border-radius:6px;box-sizing:border-box;padding:10px 20px;border:1px solid ${f.themedColor.textDisabled};cursor:pointer;user-select:none;`,nh=()=>{var Y,G,ye,mt;const{Template:e}=ut.useContext(),{Template:t}=De.useContext(),{Template:n}=Bt.useContext(),{components:r}=Vt.useContext(),{stringSet:s}=K(),{config:a,cache:i,agentPreviewConfigs:l,chatSDK:c,state:d}=j(),{userSession:m,aiAgentInfo:p,connectionError:E}=oe(),{conversation:v,channelSource:x,messageSource:b,scrollSource:g,state:{input:_,streamAnimation:y}}=ne(),{isActionbookTester:I}=Ye(),{filteredMessages:A,shouldShowOriginalDate:$,renderAgentPreviewWelcomeMessages:k}=Km(),S=si(x.channel),[R,P]=u.useState(null),[O,T]=u.useState(null);u.useEffect(()=>{g.actions.onTypingIndicatorUpdate(!!S)},[!!S,g.actions.onTypingIndicatorUpdate]),jm(),Hm({enabled:b.initialized&&b.messages.length>0});const B=(L,Ne=!1)=>{var Ge;return Ne?p:((Ge=x.channel)==null?void 0:Ge.members.find(Se=>Se.userId===L.sender.userId))??L.sender},N=L=>{if(L.sendingStatus==="failed"&&!_.disabled)return()=>T(L)},z=({message:L,index:Ne})=>{const Ge=so(L),Se=A[Ne-1],qt=A[Ne+1],Wt=A[A.length-1],Kt=L===Wt,ht=rt(L,p.userId),jt=!(p.isUserFeedbackEnabled&&ht&&!Me.isWelcomeMessage(L)),Yt=oo(L,Se,qt,jt),D=!Zs.isSameDay((Se==null?void 0:Se.createdAt)??0,L.createdAt)&&$(Ne)&&!I,V=re=>{P({files:re.files.map(Te=>({...Te,timestamp:L.createdAt})),index:re.index})},W=re=>{V({files:[re],index:0})},Q=()=>{L.isFileMessage()&&Nn(L.url)},ae=D?o.createElement(r.DateSeparator,{style:{margin:"16px 0"},date:L.createdAt}):null,ie={data:L.data,maxBodyWidth:d.expanded?H.WIDE_BODY_MAX_WIDTH:void 0,extendedMessagePayload:L.extendedMessagePayload,createdAt:L.createdAt,groupType:Yt,onClickMedia:W,onClickMediaFiles:V,onClickFile:Q},qe=()=>{if(We.isOutgoing(L,m.userId))return"outgoingmessage";if(We.isIncoming(L,m.userId))return"incomingmessage"},Ae=(()=>{var re,Te,gt;if(We.isAdmin(L))return We.isCSAT(L)?v?o.createElement(n,{...ie,...v,isResolvedWhenDeterminedByUser:Lo(v),messageType:"admin.csat",onSubmitCSAT:async Ee=>{var q;await((q=x.channel)==null?void 0:q.submitCSAT(Ee))},onScrollToBottom:()=>g.actions.scrollToBottom()}):null:o.createElement(n,{...ie,messageType:"admin",message:L.message});if(We.isOutgoing(L,m.userId)){const Ee={...ie,message:L.message,sender:B(L),sendingStatus:L.sendingStatus,onClickFailedMessage:N(L)};if(L.isUserMessage())return o.createElement(e,{messageType:"user",...Ee});if(L.isFileMessage()){const[q,se]=((re=L.metaArrays.find(be=>be.key===Nr))==null?void 0:re.value)??[];return o.createElement(e,{messageType:"file",file:L,metadata:{aspectRatio:q&&se?`${q}/${se}`:"1/1",localFile:(Te=L.messageParams)==null?void 0:Te.file},...Ee})}if(L.isMultipleFilesMessage()){const{files:q,metadata:se}=fr(L);return o.createElement(e,{messageType:"multipleFiles",files:q,metadata:se,...Ee})}}if(We.isIncoming(L,m.userId)){const Ee={...ie,sender:B(L,ht),message:L.message,suggestedRepliesVisible:Kt,suggestedRepliesDirection:l==null?void 0:l.suggestedRepliesDirection,isBotMessage:ht,isStreaming:Me.isStreaming(L),isHandedOff:Ue(x.channel),isConversationClosed:ue(x.channel),isFeedbackEnabled:p.isUserFeedbackEnabled,isFeedbackCommentEnabled:p.isUserFeedbackCommentOptionEnabled,isSenderAvatarVisible:(gt=a==null?void 0:a.conversation)==null?void 0:gt.senderAvatarEnabled,onClickSuggestedReply:async({reply:q})=>{b.sendUserMessage({message:q})},onRequestMessageTemplate:async q=>{const{template:se}=await c.aiAgent.getMessageTemplate(q);return i.template.set(q,se),se},onGetCachedMessageTemplate:q=>i.template.get(q),onHandleTemplateInternalAction:q=>{if(q.type==="internal"&&q.internalData){const{method:se,payload:be}=q.internalData;se==="message.send"&&(be!=null&&be.message)&&b.sendUserMessage({message:be.message})}},onFeedbackUpdate:q=>{const se={messageId:L.messageId,channelUrl:L.channelUrl};if(!q)return c.aiAgent.deleteMessageFeedback(se);const be={...se,rating:Dc(q.rating),comment:q.comment};return Me.hasFeedback(L)?c.aiAgent.updateMessageFeedback(be):c.aiAgent.createMessageFeedback(be)},onSubmitForm:({key:q,data:se})=>c.aiAgent.submitForm({messageId:L.messageId,channelUrl:L.channelUrl,formKey:q,formData:se}),onCancelForm:({key:q})=>c.aiAgent.cancelForm({messageId:L.messageId,channelUrl:L.channelUrl,formKey:q}),onStreamAnimationStart:()=>{y.start(L.messageId)},onStreamAnimationProgress:()=>{g.actions.onStreamingUpdate(!0)},onStreamAnimationComplete:()=>{y.stop(L.messageId),g.actions.onStreamingUpdate(!1)}};if(L.isUserMessage())return o.createElement(t,{messageType:"user",...Ee});if(L.isFileMessage())return o.createElement(t,{messageType:"file",file:L,...Ee});if(L.isMultipleFilesMessage()){const{files:q}=fr(L);return o.createElement(t,{messageType:"multipleFiles",files:q,...Ee})}}})();return o.createElement("div",{key:Ge,id:`${le}-message-item`,role:"listitem","data-layout-id":qe()},ae,Ae)};return o.createElement(rh,{id:`${le}-message-list`},o.createElement(om,{ref:g.ref,onScroll:g.props.onScroll,stackDirection:l==null?void 0:l.messageStackDirection,messages:A,renderMessage:z,onLoadPrev:b.loadPrevious,onLoadNext:b.loadNext,depsForResetScrollPositionToBottom:[b.initialized,b.messages.length!==0],bottomSpacerHeight:g.state.bottomSpace,ariaLabel:s.A11Y_MESSAGE_LIST,loading:!b.initialized||!x.channel,empty:A.length===0&&!S,error:!!(E||x.error),LoadingComponent:o.createElement(et,{type:"loading"}),EmptyComponent:(()=>{const L=k();return L?o.createElement("div",{style:{width:"100%"}},L):o.createElement(et,{type:"noMessages",label:s.PLACE_HOLDER__NO_MESSAGES})})(),ErrorComponent:o.createElement(et,{type:"error",label:(E==null?void 0:E.message)??((Y=x.error)==null?void 0:Y.message),action:x.error?{label:s.RETRY,onClick:()=>x.refetch()}:void 0}),messageTopArea:o.createElement(o.Fragment,null,o.createElement(Xm,{style:{marginTop:16}}),k()),messageBottomArea:o.createElement(o.Fragment,null,S&&o.createElement("div",{id:`${le}-message-item`,role:"listitem",style:{marginTop:A.length===0?8:0}},o.createElement(t,{isTyping:!0,isBotMessage:S.isBot,sender:S.user,thinkingMessage:S.thinkingMessage,messageType:"user",groupType:"single",message:"",isSenderAvatarVisible:(G=a==null?void 0:a.conversation)==null?void 0:G.senderAvatarEnabled})),((ye=a==null?void 0:a.conversation)==null?void 0:ye.isTalkToAgentViewEnabled)&&o.createElement(Qm,null)),overlayArea:o.createElement(o.Fragment,null,((mt=a==null?void 0:a.conversation)==null?void 0:mt.newMessageIndicatorEnabled)&&g.state.isAwayFromBottom&&b.newMessages.length>0&&o.createElement(sh,{label:s.SCROLL_TO_NEW_MESSAGES_LABEL(b.newMessages),ariaLabel:s.A11Y_SCROLL_TO_NEW_MESSAGES,onClick:()=>g.actions.scrollToBottom()}),g.state.isAwayFromBottom&&b.newMessages.length===0&&!S&&o.createElement(r.ScrollToBottomButton,{ariaLabel:s.A11Y_SCROLL_TO_BOTTOM,onClick:()=>g.actions.scrollToBottom(),style:{position:"absolute",bottom:12,insetInlineEnd:16}}))}),R&&o.createElement(gm,{files:R.files,initialIndex:R.index,onClose:()=>P(null),visible:!0}),O&&o.createElement($e,{visible:!0,onClose:()=>T(null)},o.createElement($e.ActionItem,{onClick:()=>{b.resendMessage(O),T(null)}},s.FAILED_MESSAGE_RESEND),o.createElement($e.ActionItem,{destructive:!0,onClick:()=>{b.deleteMessage(O),T(null)}},s.FAILED_MESSAGE_REMOVE)))},rh=h.default.div`overflow-y:hidden;display:flex;flex:1;position:relative;`,sh=h.default(km)`position:absolute;bottom:12px;left:50%;transform:translateX(-50%);`,oh=()=>o.createElement(nh,null),ah=()=>{var s;const{origin:e}=Ye(),{appId:t,aiAgentId:n}=me(),{channelSource:r}=ne();return(s=r.channel)!=null&&s.conversation?o.createElement(ih,null,o.createElement(_n,{style:{gap:4}},o.createElement(U,{color:f.themedColor.textLowEmphasis,size:12,type:"show"}),o.createElement(M,{as:"i",color:f.themedColor.textLowEmphasis,variant:"caption2"},"Only visible in the tester")),o.createElement(_n,{role:"button",style:{gap:4},onClick:()=>{var c,d;const a=e??window.location.origin,i=(d=(c=r.channel)==null?void 0:c.conversation)==null?void 0:d.id,l=`${a}/ai-agent/${t}/${n}/evaluate/conversations/${i}`;navigator.clipboard.writeText(l)}},o.createElement(M,{variant:"body3",color:f.themedColor.textHighEmphasis},"Copy ",o.createElement("span",{style:{color:f.themedColor.primary}},"conversation link")),o.createElement(U,{color:f.themedColor.primary,size:14,type:"copy"}))):null},_n=h.default.div`display:flex;justify-content:center;align-items:center;`,ih=h.default(_n)`flex-direction:column;padding-block:16px;background-color:${f.themedColor.bg_100_500};gap:8px;`,lh=e=>{const t=e[0];if(!t)return e;const n=e.some(s=>we(s.type)),r=e.some(s=>!we(s.type));return n&&r?we(t.type)?e.filter(s=>we(s.type)):[t]:r?[t]:e},ch=(e,t)=>{const n=[],r=[],s=[];for(const a of e){const i=t.isSupportedMimeType(a.type),l=a.size<=t.getUploadSizeLimit(a.type);i&&l?n.push(a):i?r.push(a):s.push(a)}return{passed:n,failedBySize:r,failedByType:s}},Ts=u.createContext(void 0),uh=({children:e})=>{var k;const{chatSDK:t}=j(),{createAttachmentRules:n}=oe(),{stringSet:r}=K(),{channelSource:s}=ne(),[a,i]=u.useState([]),[l,c]=u.useState({visible:!1,title:""}),d=n({channel:s.channel,uploadSizeLimit:(k=t.appInfo)==null?void 0:k.uploadSizeLimit}),m=d.isEnabled(),p=d.maxAttachmentCount,E=S=>{c({visible:!0,title:S})},v=()=>{E(r.FILE_UPLOAD_NOTIFICATION__COUNT_LIMIT.replace("%d",p.toString()))},x=S=>{E(r.FILE_UPLOAD_NOTIFICATION__SIZE_LIMIT.replace("%d",S.toString()))},b=S=>{E(r.FILE_UPLOAD_NOTIFICATION__FILES_EXCLUDED_BY_VALIDATION.replace("%d",S.toString()))},g=S=>S.map(R=>({file:R,preview:{url:URL.createObjectURL(R),type:R.type,name:R.name}})),_=S=>{i(R=>[...R,...g(S)])},y=S=>{i(R=>(R.forEach(P=>URL.revokeObjectURL(P.preview.url)),g(S)))},I=S=>{if(!m||S.length===0)return;if(p-a.length===0){v();return}if(a.length+S.length>p){v();return}const P=lh(S),{passed:O,failedBySize:T,failedByType:B}=ch(P,d),N=T.length+B.length,z=P.length===1?T[0]:void 0;if(z?x(d.getUploadSizeLimitInMB(z.type)):N>0&&b(N),O.length===0)return;a.length>0&&a.every(G=>we(G.file.type))&&O.every(G=>we(G.type))?_(O):y(O)},A=S=>{i(R=>{var O;const P=(O=R[S])==null?void 0:O.preview;return P&&URL.revokeObjectURL(P.url),R.filter((T,B)=>B!==S)})},$=()=>{i(S=>(S.forEach(R=>URL.revokeObjectURL(R.preview.url)),[]))};return o.createElement(Ts.Provider,{value:{files:a,addFiles:I,removeFile:A,clearFiles:$,isFileUploadEnabled:m,acceptableMimeTypes:d.supportedMimeTypes,maxAttachmentCount:d.maxAttachmentCount,showFileUploadAlert:E}},e,o.createElement(Dn,{...l,onClose:()=>c({visible:!1,title:""})}))},Hn=()=>{const e=u.useContext(Ts);if(!e)throw new Error("useFileUpload must be used within FileUploadProvider");return e};function dh({blurred:e,elementRef:t,document:n=window.document}){const r=u.useRef(!1);e&&t.current&&n.activeElement===t.current&&(r.current=!0),u.useLayoutEffect(()=>{var s;!e&&r.current&&((s=t.current)==null||s.focus(),r.current=!1)},[e])}const mh=(e,t)=>{u.useEffect(()=>{t?e==null||e.startTyping():e==null||e.endTyping()},[e,t])},hh=h.default.div`&::-webkit-scrollbar{display:none;}overflow-x:auto;display:flex;flex-direction:row;gap:10px;padding:8px 16px;background-color:transparent;`,gh=h.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;}`,fh=h.default.div`display:flex;align-items:center;justify-content:center;position:absolute;inset-inline-end:-8px;inset-block-start:-8px;cursor:pointer;border-radius:50%;${F.light`
|
|
285
|
+
`,eh=()=>{var i;const{stringSet:e}=K(),{channelSource:t,goToActiveConversation:n,scrollSource:r}=ne(),s=de(t.channel),a=u.useRef(s);return u.useEffect(()=>{if(!a.current&&s){const d=setTimeout(()=>{r.actions.scrollToBottom()},100);return()=>clearTimeout(d)}a.current=s},[s,r.actions.scrollToBottom]),!((i=t.channel)!=null&&i.isAIAgent)||!s?null:o.createElement(th,null,o.createElement(nh,{variant:"button",role:"button",color:f.themedColor.textHighEmphasis,onClick:()=>n()},e.TALK_TO_AGENT))},th=h.default.div`display:flex;justify-content:center;margin-bottom:16px;`,nh=h.default(M)`border-radius:6px;box-sizing:border-box;padding:10px 20px;border:1px solid ${f.themedColor.textDisabled};cursor:pointer;user-select:none;`,rh=()=>{var Y,G,ye,mt;const{Template:e}=ut.useContext(),{Template:t}=De.useContext(),{Template:n}=Bt.useContext(),{components:r}=Vt.useContext(),{stringSet:s}=K(),{config:a,cache:i,agentPreviewConfigs:l,chatSDK:c,state:d}=j(),{userSession:m,aiAgentInfo:p,connectionError:E}=oe(),{conversation:v,channelSource:x,messageSource:b,scrollSource:g,state:{input:_,streamAnimation:y}}=ne(),{isActionbookTester:I}=Ye(),{filteredMessages:A,shouldShowOriginalDate:$,renderAgentPreviewWelcomeMessages:k}=jm(),S=oi(x.channel),[R,P]=u.useState(null),[O,T]=u.useState(null);u.useEffect(()=>{g.actions.onTypingIndicatorUpdate(!!S)},[!!S,g.actions.onTypingIndicatorUpdate]),Ym(),Vm({enabled:b.initialized&&b.messages.length>0});const B=(L,Ne=!1)=>{var Ge;return Ne?p:((Ge=x.channel)==null?void 0:Ge.members.find(Se=>Se.userId===L.sender.userId))??L.sender},N=L=>{if(L.sendingStatus==="failed"&&!_.disabled)return()=>T(L)},z=({message:L,index:Ne})=>{const Ge=oo(L),Se=A[Ne-1],qt=A[Ne+1],Wt=A[A.length-1],Kt=L===Wt,ht=rt(L,p.userId),jt=!(p.isUserFeedbackEnabled&&ht&&!Me.isWelcomeMessage(L)),Yt=ao(L,Se,qt,jt),D=!Js.isSameDay((Se==null?void 0:Se.createdAt)??0,L.createdAt)&&$(Ne)&&!I,V=re=>{P({files:re.files.map(Te=>({...Te,timestamp:L.createdAt})),index:re.index})},W=re=>{V({files:[re],index:0})},Q=()=>{L.isFileMessage()&&Nn(L.url)},ae=D?o.createElement(r.DateSeparator,{style:{margin:"16px 0"},date:L.createdAt}):null,ie={data:L.data,maxBodyWidth:d.expanded?H.WIDE_BODY_MAX_WIDTH:void 0,extendedMessagePayload:L.extendedMessagePayload,createdAt:L.createdAt,groupType:Yt,onClickMedia:W,onClickMediaFiles:V,onClickFile:Q},qe=()=>{if(We.isOutgoing(L,m.userId))return"outgoingmessage";if(We.isIncoming(L,m.userId))return"incomingmessage"},Ae=(()=>{var re,Te,gt;if(We.isAdmin(L))return We.isCSAT(L)?v?o.createElement(n,{...ie,...v,isResolvedWhenDeterminedByUser:Ro(v),messageType:"admin.csat",onSubmitCSAT:async Ee=>{var q;await((q=x.channel)==null?void 0:q.submitCSAT(Ee))},onScrollToBottom:()=>g.actions.scrollToBottom()}):null:o.createElement(n,{...ie,messageType:"admin",message:L.message});if(We.isOutgoing(L,m.userId)){const Ee={...ie,message:L.message,sender:B(L),sendingStatus:L.sendingStatus,onClickFailedMessage:N(L)};if(L.isUserMessage())return o.createElement(e,{messageType:"user",...Ee});if(L.isFileMessage()){const[q,se]=((re=L.metaArrays.find(be=>be.key===Nr))==null?void 0:re.value)??[];return o.createElement(e,{messageType:"file",file:L,metadata:{aspectRatio:q&&se?`${q}/${se}`:"1/1",localFile:(Te=L.messageParams)==null?void 0:Te.file},...Ee})}if(L.isMultipleFilesMessage()){const{files:q,metadata:se}=fr(L);return o.createElement(e,{messageType:"multipleFiles",files:q,metadata:se,...Ee})}}if(We.isIncoming(L,m.userId)){const Ee={...ie,sender:B(L,ht),message:L.message,suggestedRepliesVisible:Kt,suggestedRepliesDirection:l==null?void 0:l.suggestedRepliesDirection,isBotMessage:ht,isStreaming:Me.isStreaming(L),isHandedOff:Ue(x.channel),isConversationClosed:de(x.channel),isFeedbackEnabled:p.isUserFeedbackEnabled,isFeedbackCommentEnabled:p.isUserFeedbackCommentOptionEnabled,isSenderAvatarVisible:(gt=a==null?void 0:a.conversation)==null?void 0:gt.senderAvatarEnabled,onClickSuggestedReply:async({reply:q})=>{b.sendUserMessage({message:q})},onRequestMessageTemplate:async q=>{const{template:se}=await c.aiAgent.getMessageTemplate(q);return i.template.set(q,se),se},onGetCachedMessageTemplate:q=>i.template.get(q),onHandleTemplateInternalAction:q=>{if(q.type==="internal"&&q.internalData){const{method:se,payload:be}=q.internalData;se==="message.send"&&(be!=null&&be.message)&&b.sendUserMessage({message:be.message})}},onFeedbackUpdate:q=>{const se={messageId:L.messageId,channelUrl:L.channelUrl};if(!q)return c.aiAgent.deleteMessageFeedback(se);const be={...se,rating:Nc(q.rating),comment:q.comment};return Me.hasFeedback(L)?c.aiAgent.updateMessageFeedback(be):c.aiAgent.createMessageFeedback(be)},onSubmitForm:({key:q,data:se})=>c.aiAgent.submitForm({messageId:L.messageId,channelUrl:L.channelUrl,formKey:q,formData:se}),onCancelForm:({key:q})=>c.aiAgent.cancelForm({messageId:L.messageId,channelUrl:L.channelUrl,formKey:q}),onStreamAnimationStart:()=>{y.start(L.messageId)},onStreamAnimationProgress:()=>{g.actions.onStreamingUpdate(!0)},onStreamAnimationComplete:()=>{y.stop(L.messageId),g.actions.onStreamingUpdate(!1)}};if(L.isUserMessage())return o.createElement(t,{messageType:"user",...Ee});if(L.isFileMessage())return o.createElement(t,{messageType:"file",file:L,...Ee});if(L.isMultipleFilesMessage()){const{files:q}=fr(L);return o.createElement(t,{messageType:"multipleFiles",files:q,...Ee})}}})();return o.createElement("div",{key:Ge,id:`${le}-message-item`,role:"listitem","data-layout-id":qe()},ae,Ae)};return o.createElement(sh,{id:`${le}-message-list`},o.createElement(am,{ref:g.ref,onScroll:g.props.onScroll,stackDirection:l==null?void 0:l.messageStackDirection,messages:A,renderMessage:z,onLoadPrev:b.loadPrevious,onLoadNext:b.loadNext,depsForResetScrollPositionToBottom:[b.initialized,b.messages.length!==0],bottomSpacerHeight:g.state.bottomSpace,ariaLabel:s.A11Y_MESSAGE_LIST,loading:!b.initialized||!x.channel,empty:A.length===0&&!S,error:!!(E||x.error),LoadingComponent:o.createElement(et,{type:"loading"}),EmptyComponent:(()=>{const L=k();return L?o.createElement("div",{style:{width:"100%"}},L):o.createElement(et,{type:"noMessages",label:s.PLACE_HOLDER__NO_MESSAGES})})(),ErrorComponent:o.createElement(et,{type:"error",label:(E==null?void 0:E.message)??((Y=x.error)==null?void 0:Y.message),action:x.error?{label:s.RETRY,onClick:()=>x.refetch()}:void 0}),messageTopArea:o.createElement(o.Fragment,null,o.createElement(Zm,{style:{marginTop:16}}),k()),messageBottomArea:o.createElement(o.Fragment,null,S&&o.createElement("div",{id:`${le}-message-item`,role:"listitem",style:{marginTop:A.length===0?8:0}},o.createElement(t,{isTyping:!0,isBotMessage:S.isBot,sender:S.user,thinkingMessage:S.thinkingMessage,messageType:"user",groupType:"single",message:"",isSenderAvatarVisible:(G=a==null?void 0:a.conversation)==null?void 0:G.senderAvatarEnabled})),((ye=a==null?void 0:a.conversation)==null?void 0:ye.isTalkToAgentViewEnabled)&&o.createElement(eh,null)),overlayArea:o.createElement(o.Fragment,null,((mt=a==null?void 0:a.conversation)==null?void 0:mt.newMessageIndicatorEnabled)&&g.state.isAwayFromBottom&&b.newMessages.length>0&&o.createElement(oh,{label:s.SCROLL_TO_NEW_MESSAGES_LABEL(b.newMessages),ariaLabel:s.A11Y_SCROLL_TO_NEW_MESSAGES,onClick:()=>g.actions.scrollToBottom()}),g.state.isAwayFromBottom&&b.newMessages.length===0&&!S&&o.createElement(r.ScrollToBottomButton,{ariaLabel:s.A11Y_SCROLL_TO_BOTTOM,onClick:()=>g.actions.scrollToBottom(),style:{position:"absolute",bottom:12,insetInlineEnd:16}}))}),R&&o.createElement(fm,{files:R.files,initialIndex:R.index,onClose:()=>P(null),visible:!0}),O&&o.createElement($e,{visible:!0,onClose:()=>T(null)},o.createElement($e.ActionItem,{onClick:()=>{b.resendMessage(O),T(null)}},s.FAILED_MESSAGE_RESEND),o.createElement($e.ActionItem,{destructive:!0,onClick:()=>{b.deleteMessage(O),T(null)}},s.FAILED_MESSAGE_REMOVE)))},sh=h.default.div`overflow-y:hidden;display:flex;flex:1;position:relative;`,oh=h.default(Mm)`position:absolute;bottom:12px;left:50%;transform:translateX(-50%);`,ah=()=>o.createElement(rh,null),ih=()=>{var s;const{origin:e}=Ye(),{appId:t,aiAgentId:n}=ce(),{channelSource:r}=ne();return(s=r.channel)!=null&&s.conversation?o.createElement(lh,null,o.createElement(_n,{style:{gap:4}},o.createElement(U,{color:f.themedColor.textLowEmphasis,size:12,type:"show"}),o.createElement(M,{as:"i",color:f.themedColor.textLowEmphasis,variant:"caption2"},"Only visible in the tester")),o.createElement(_n,{role:"button",style:{gap:4},onClick:()=>{var c,d;const a=e??window.location.origin,i=(d=(c=r.channel)==null?void 0:c.conversation)==null?void 0:d.id,l=`${a}/ai-agent/${t}/${n}/evaluate/conversations/${i}`;navigator.clipboard.writeText(l)}},o.createElement(M,{variant:"body3",color:f.themedColor.textHighEmphasis},"Copy ",o.createElement("span",{style:{color:f.themedColor.primary}},"conversation link")),o.createElement(U,{color:f.themedColor.primary,size:14,type:"copy"}))):null},_n=h.default.div`display:flex;justify-content:center;align-items:center;`,lh=h.default(_n)`flex-direction:column;padding-block:16px;background-color:${f.themedColor.bg_100_500};gap:8px;`,ch=e=>{const t=e[0];if(!t)return e;const n=e.some(s=>we(s.type)),r=e.some(s=>!we(s.type));return n&&r?we(t.type)?e.filter(s=>we(s.type)):[t]:r?[t]:e},uh=(e,t)=>{const n=[],r=[],s=[];for(const a of e){const i=t.isSupportedMimeType(a.type),l=a.size<=t.getUploadSizeLimit(a.type);i&&l?n.push(a):i?r.push(a):s.push(a)}return{passed:n,failedBySize:r,failedByType:s}},Is=u.createContext(void 0),dh=({children:e})=>{var k;const{chatSDK:t}=j(),{createAttachmentRules:n}=oe(),{stringSet:r}=K(),{channelSource:s}=ne(),[a,i]=u.useState([]),[l,c]=u.useState({visible:!1,title:""}),d=n({channel:s.channel,uploadSizeLimit:(k=t.appInfo)==null?void 0:k.uploadSizeLimit}),m=d.isEnabled(),p=d.maxAttachmentCount,E=S=>{c({visible:!0,title:S})},v=()=>{E(r.FILE_UPLOAD_NOTIFICATION__COUNT_LIMIT.replace("%d",p.toString()))},x=S=>{E(r.FILE_UPLOAD_NOTIFICATION__SIZE_LIMIT.replace("%d",S.toString()))},b=S=>{E(r.FILE_UPLOAD_NOTIFICATION__FILES_EXCLUDED_BY_VALIDATION.replace("%d",S.toString()))},g=S=>S.map(R=>({file:R,preview:{url:URL.createObjectURL(R),type:R.type,name:R.name}})),_=S=>{i(R=>[...R,...g(S)])},y=S=>{i(R=>(R.forEach(P=>URL.revokeObjectURL(P.preview.url)),g(S)))},I=S=>{if(!m||S.length===0)return;if(p-a.length===0){v();return}if(a.length+S.length>p){v();return}const P=ch(S),{passed:O,failedBySize:T,failedByType:B}=uh(P,d),N=T.length+B.length,z=P.length===1?T[0]:void 0;if(z?x(d.getUploadSizeLimitInMB(z.type)):N>0&&b(N),O.length===0)return;a.length>0&&a.every(G=>we(G.file.type))&&O.every(G=>we(G.type))?_(O):y(O)},A=S=>{i(R=>{var O;const P=(O=R[S])==null?void 0:O.preview;return P&&URL.revokeObjectURL(P.url),R.filter((T,B)=>B!==S)})},$=()=>{i(S=>(S.forEach(R=>URL.revokeObjectURL(R.preview.url)),[]))};return o.createElement(Is.Provider,{value:{files:a,addFiles:I,removeFile:A,clearFiles:$,isFileUploadEnabled:m,acceptableMimeTypes:d.supportedMimeTypes,maxAttachmentCount:d.maxAttachmentCount,showFileUploadAlert:E}},e,o.createElement(Dn,{...l,onClose:()=>c({visible:!1,title:""})}))},Hn=()=>{const e=u.useContext(Is);if(!e)throw new Error("useFileUpload must be used within FileUploadProvider");return e};function mh({blurred:e,elementRef:t,document:n=window.document}){const r=u.useRef(!1);e&&t.current&&n.activeElement===t.current&&(r.current=!0),u.useLayoutEffect(()=>{var s;!e&&r.current&&((s=t.current)==null||s.focus(),r.current=!1)},[e])}const hh=(e,t)=>{u.useEffect(()=>{t?e==null||e.startTyping():e==null||e.endTyping()},[e,t])},gh=h.default.div`&::-webkit-scrollbar{display:none;}overflow-x:auto;display:flex;flex-direction:row;gap:10px;padding:8px 16px;background-color:transparent;`,fh=h.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;}`,ph=h.default.div`display:flex;align-items:center;justify-content:center;position:absolute;inset-inline-end:-8px;inset-block-start:-8px;cursor:pointer;border-radius:50%;${F.light`
|
|
286
286
|
background-color: ${f.color.background50};
|
|
287
287
|
`}
|
|
288
288
|
${F.dark`
|
|
@@ -301,17 +301,17 @@
|
|
|
301
301
|
circle {
|
|
302
302
|
stroke: ${f.themedColor.bg_50_600};
|
|
303
303
|
}
|
|
304
|
-
`,
|
|
304
|
+
`,Eh=()=>{const e=it(),[t,n]=u.useState(),{files:r,removeFile:s,isFileUploadEnabled:a}=Hn();return!a||r.length===0?null:o.createElement(gh,null,r.map(({preview:{type:i,name:l,url:c}},d)=>o.createElement(fh,{key:c,onMouseOver:()=>n(d),onMouseLeave:()=>n(void 0)},(e||t===d)&&o.createElement(ph,{title:"Remove file",onClick:()=>s(d)},o.createElement(U,{type:"close-filled",color:f.themedColor.textMidEmphasis})),i.startsWith("image/")?o.createElement("img",{alt:"file-image",src:c}):o.createElement(Fn,{name:l,type:vn(l,i)}))))},bh={textArea:w.css`min-height:40px;height:40px;font-size:16px;line-height:24px;`},ws=h.default.button`all:unset;cursor:pointer;display:flex;align-items:center;justify-content:center;width:32px;height:32px;`,wr=h.default.div`width:100%;position:relative;background-color:${f.themedColor.bg_100_500};border-radius:20px;`,kr=h.default.div`display:flex;flex-direction:row;align-items:flex-end;position:relative;`,Mr=h.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:${f.themedColor.textHighEmphasis};resize:none;width:100%;height:${es}px;overflow-wrap:break-word;white-space:pre-wrap;overflow-x:hidden;${ss&&bh.textArea};&::placeholder{color:${f.themedColor.textLowEmphasis};}&:disabled{cursor:not-allowed;&::placeholder{color:${f.themedColor.textDisabled};}}`,_h=h.default.input`display:none;`;h.default.div`display:flex;align-items:center;gap:24px;`;const Ch=h.default(ws)`flex-shrink:0;border-radius:8px;&:disabled{cursor:not-allowed;}&:not(:disabled){&:hover{background-color:${f.themedColor.bg_100_500};path{fill:${f.themedColor.textHighEmphasis};}}&:active{background-color:${f.themedColor.bg_200_400};}}`,$r=h.default.div`padding:10px 16px 10px 12px;position:relative;display:flex;align-items:center;gap:8px;`,Lr=e=>e.startsWith("image/"),Rr=({disabled:e})=>{var $,k,S,R,P;const{stringSet:t}=K(),{config:n}=j(),r=u.useRef(null),s=u.useRef(null),[a,i]=u.useState(!1),{addFiles:l,isFileUploadEnabled:c,acceptableMimeTypes:d,showFileUploadAlert:m}=Hn(),p=d.includes(ln),E=p?["image/*"]:d.filter(Lr),v=p?[ln]:d.filter(O=>!Lr(O)),x=!!((S=(k=($=n==null?void 0:n.conversation)==null?void 0:$.input)==null?void 0:k.gallery)!=null&&S.photoEnabled),b=!!((P=(R=n==null?void 0:n.conversation)==null?void 0:R.input)!=null&&P.fileEnabled),g=()=>p||E.length>0,_=()=>p||v.length>0,y=O=>{const T=O.currentTarget.files;T&&l(Array.from(T)),O.target.value=""},I=()=>{i(!0)},A=u.useMemo(()=>{const O=[];return x&&O.push({type:"image",icon:"photo",label:t.FILE_UPLOAD_PHOTOS,accept:E.join(","),inputRef:r,onSelect:()=>{if(!g()){m(t.FILE_UPLOAD_NO_SUPPORTED_FILES);return}i(!1),setTimeout(()=>{var T;return(T=r.current)==null?void 0:T.click()},100)}}),b&&O.push({type:"file",icon:"document",label:t.FILE_UPLOAD_FILES,accept:d.join(","),inputRef:s,onSelect:()=>{if(!_()){m(t.FILE_UPLOAD_NO_SUPPORTED_FILES);return}i(!1),setTimeout(()=>{var T;return(T=s.current)==null?void 0:T.click()},100)}}),O},[E,d,t,x,b]);return c?o.createElement(o.Fragment,null,o.createElement(Ch,{disabled:e,onClick:I,"aria-label":t.A11Y_ATTACH_FILE},o.createElement(U,{type:"add",color:e?f.themedColor.textDisabled:f.color.primary.main,size:20})),A.map(O=>o.createElement(_h,{key:O.type,type:"file",ref:O.inputRef,multiple:O.type==="image",onChange:y,accept:O.accept})),o.createElement($e,{visible:a,onClose:()=>i(!1)},A.map(O=>o.createElement($e.ActionItem,{key:O.type,onClick:O.onSelect,icon:O.icon},O.label)))):null},xh=()=>{const e=u.useRef(null),[t,n]=u.useState(""),{stringSet:r}=K(),{rootElement:s}=j(),{channelSource:a,messageSource:i,state:l}=ne(),{files:c,addFiles:d,clearFiles:m}=Hn(),p=l.input.disabled,E=(()=>{if(!p)return r.MESSAGE_INPUT__PLACE_HOLDER;switch(l.input.disabledBy){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"reconnecting":return r.MESSAGE_INPUT__PLACE_HOLDER__RECONNECTING;case"unavailable":case"conversation_closed":default:return r.MESSAGE_INPUT__PLACE_HOLDER__DISABLED}})();ml({onDropFiles:d}),mh({blurred:p,elementRef:e,document:He(s)}),hh(a.channel,t);const v=t.trim().length>0,x=c.length>0,b=!p&&(v||x),g=()=>{e.current&&(e.current.value="",e.current.style.height=""),m(),n("")},_=async()=>{const $=t.trim();if(!$&&!c.length)return;const k=[...c];if(g(),k.length===0){i.sendUserMessage({message:$});return}if(k.length===1)await i.sendFileMessage({message:$,file:k[0].file});else{const S=k.map(({file:R})=>({file:R}));await i.sendMultipleFilesMessage({message:$,fileInfoList:S})}},y=$=>{const k=Array.from($.clipboardData.files);k.length>0&&($.preventDefault(),d(k))},I=$=>{$.key!=="Enter"||$.nativeEvent.isComposing||$.shiftKey||($.preventDefault(),_())},A=$=>{if(e.current){e.current.style.height="";const k=Math.min(hi,e.current.scrollHeight);es<k&&(e.current.style.height=`${k}px`)}n($.target.value)};return p?o.createElement($r,null,o.createElement(Rr,{disabled:!0}),o.createElement(wr,null,o.createElement(kr,null,o.createElement(Mr,{disabled:!0,placeholder:E})))):o.createElement($r,null,o.createElement(Rr,null),o.createElement(wr,null,o.createElement(Eh,null),o.createElement(kr,null,o.createElement(Mr,{ref:e,role:"textbox","aria-label":"Text Input",placeholder:E,maxLength:5e3,onKeyDown:I,onChange:A,onPaste:y}))),b&&o.createElement(ws,{onClick:()=>_()},o.createElement(U,{type:"send",color:f.color.primary.main,size:20})))},vh=h.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:${f.themedColor.textLowEmphasis};&& a{font-weight:700;text-decoration:none;${F.light`
|
|
305
305
|
color: ${f.color.information.light};
|
|
306
306
|
`};
|
|
307
307
|
${F.dark`
|
|
308
308
|
color: ${f.color.information.main};
|
|
309
309
|
`};
|
|
310
310
|
}
|
|
311
|
-
`,vh=u.lazy(()=>Promise.resolve().then(()=>require("./cjs/D2Opuq0j.cjs")).then(e=>({default:e.MarkdownText}))),yh=()=>{const{aiAgentInfo:e,userSession:t}=oe(),{messageSource:n,channelSource:r}=ne(),[s,a]=u.useState(null),i=Rn("special-notice",r.channel),l=u.useCallback(()=>r.channel?i?n.messages.some(c=>rt(c,(t==null?void 0:t.userId)??"")):!0:null,[r.channel,i,n.messages,t==null?void 0:t.userId]);return u.useEffect(()=>{s||a(l())},[l,s]),s||!e.specialNotice?null:o.createElement(xh,null,o.createElement(vh,null,e.specialNotice))},Sh=()=>o.createElement(Ah,null,o.createElement(yh,null),o.createElement(uh,null,o.createElement(Ch,null))),Ah=h.default.div`z-index:0;border:none;width:100%;`,Th=()=>{var s;const{testerType:e}=Ye(),{channelSource:t}=ne(),n=ue(t.channel),r=!!e&&((s=t.channel)==null?void 0:s.isAIAgent);return n&&r?o.createElement(ah,null):o.createElement(Sh,null)},ws=({start:e,title:t,titleAlign:n="start",end:r})=>{const s=u.useRef(null),a=u.useRef(null),[i,l]=u.useState(0),[c,d]=u.useState(0);return u.useLayoutEffect(()=>{s.current&&l(s.current.offsetWidth),a.current&&d(a.current.offsetWidth)},[e,r]),o.createElement(Ih,null,o.createElement(wh,null,n==="center"&&t&&o.createElement(kh,{$sideWidth:Math.max(i,c)},o.createElement(Mh,null,t)),o.createElement($h,null,o.createElement(Lh,{ref:s},e),(n==="start"||n==="end")&&t&&o.createElement(Oh,{$align:n,$hasStart:!!e,$hasEnd:!!r},t),o.createElement(Rh,{ref:a},r))))},Ih=h.default.div`position:relative;width:100%;background-color:${({theme:e})=>e.colors.base.headerBackground};border-bottom:1px solid ${f.themedColor.textDisabled};`,wh=h.default.div`position:relative;height:56px;padding:11px 12px;`,kh=h.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;`,Mh=h.default.div`max-width:100%;overflow:hidden;`,$h=h.default.div`display:flex;flex-direction:row;align-items:center;justify-content:space-between;height:100%;z-index:1;`,Lh=h.default.div`flex-shrink:0;display:flex;align-items:center;`,Rh=h.default.div`flex-shrink:0;display:flex;align-items:center;`,Oh=h.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;`,dt=()=>it()?24:16,Dh=()=>{const{state:e}=j(),t=dt(),n=()=>{e.setOpened(!1)};return o.createElement(ve,{"aria-label":"close messenger",type:"close",size:t,onClick:n})},Nh=()=>{const{enableCloseConversationButton:e,dispatcher:t}=j(),{channelSource:n}=ne(),r=n.channel,s=dt(),a=(r==null?void 0:r.isAIAgent)&&e,i=!An(r);if(!a)return null;const l=async()=>{r&&await t.send(Be.CloseConversation({channelUrl:r.url}))};return o.createElement(ve,{"aria-label":"close conversation",type:"mute",size:s,disabled:i,onClick:l})},Ph=()=>{const{state:e,enableExpandButton:t}=j(),n=dt();return t?o.createElement(ve,{"aria-label":"expand",type:e.expanded?"collapse":"expand",size:n,onClick:()=>e.setExpanded(!e.expanded)}):null},Fh=({label:e,children:t,position:n="top",disabled:r})=>r?t:o.createElement(Cn,null,t,o.createElement(Hh,{$position:n},o.createElement(Vh,{variant:"caption1"},e),o.createElement(Bh,{$position:n}))),Bh=({$position:e})=>o.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"},o.createElement("path",{d:"M6 6L0 0h12L6 6Z",fill:f.themedColor.textHighEmphasis})),Uh={top:w.css`flex-direction:column;top:0;transform:translate(-50%,-100%);`,bottom:w.css`flex-direction:column-reverse;bottom:0;transform:translate(-50%,100%);`},Cn=h.default.div`position:relative;`,Hh=h.default.div`display:flex;align-items:center;position:absolute;left:50%;z-index:${Ve.TOOLTIP};${({$position:e})=>Uh[e]}opacity:0;transition:opacity 0.2s ease-in-out;pointer-events:none;${Cn}:hover &,${Cn}:focus-within &{opacity:1;}`,Vh=h.default(M)`padding:6px 8px;background:${f.themedColor.textHighEmphasis};color:${f.themedColor.textHighEmphasisInverse};border-radius:4px;font-size:12px;white-space:nowrap;`,zh=()=>{const{logger:e}=j(),{stringSet:t}=K(),{channelSource:n}=ne(),r=n.channel,s=dt(),a=Rn("handoff-button",r),i=!An(r)||Ue(r),l=async()=>{try{const c=await(r==null?void 0:r.markConversationAsHandoff());e.info("conversation.handleAgentHandoff: success",c)}catch(c){e.error("conversation.handleAgentHandoff: error",c)}};return a?o.createElement(Fh,{label:t.HEADER_BUTTON__AGENT_HANDOFF,position:"bottom",disabled:i},o.createElement(ve,{"aria-label":"request handoff",type:"agent",size:s,disabled:i,onClick:l})):null},Gh=()=>{const{stringSet:e}=K(),{onNavigateToConversationList:t}=ne();return t?o.createElement(ve,{type:"menu",size:24,onClick:()=>t(),"aria-label":e.A11Y_OPEN_CONVERSATION_LIST}):null},ks=({channel:e,size:t=40})=>{const{userSession:n,aiAgentInfo:r}=oe(),{fallbackIcon:s,url:a}=Jr({channel:e,aiAgentInfo:r,userSession:n}),i=w.useTheme();return a?o.createElement(hs,{src:a,size:t}):o.createElement(qh,{$size:t,$bgColor:i.colors.base.primary},o.createElement(U,{type:s,size:t*.55,color:i.colors.base.primaryContrastContent}))},qh=h.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;`,Wh=()=>{var l,c;const{channelSource:e}=ne(),{aiAgentInfo:t,userSession:n}=oe(),{config:r}=me(),s=e.channel,a=Jr({channel:s,userSession:n,aiAgentInfo:t}),i=(c=(l=r==null?void 0:r.conversation)==null?void 0:l.header)==null?void 0:c.avatarEnabled;return o.createElement(Kh,null,i&&o.createElement(ks,{channel:s,size:34}),o.createElement(jh,{variant:"h2",color:f.themedColor.textHighEmphasis},a.title))},Kh=h.default.div`display:flex;flex-direction:row;align-items:center;gap:6px;overflow:hidden;`,jh=h.default(M)`text-overflow:ellipsis;overflow:hidden;white-space:nowrap;padding:2px 0;`,Yh=e=>{const{components:t}=ze.useContext();return o.createElement(ws,{start:o.createElement(t.StartArea,null),title:o.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:o.createElement(t.EndArea,null)})},Xh=()=>{const{components:e}=ze.useContext();return o.createElement(e.MenuButton,null)},Zh=()=>{const{components:e}=ze.useContext();return o.createElement(e.Title,null)},Jh=()=>{const{components:e}=ze.useContext();return o.createElement(eg,null,o.createElement(e.HandoffButton,null),o.createElement(e.ConversationCloseButton,null),o.createElement(e.ExpandButton,null),o.createElement(e.CloseButton,null))},ze=pe({template:Yh,components:{StartArea:Xh,TitleArea:Zh,EndArea:Jh,MenuButton:Gh,Title:Wh,HandoffButton:zh,ConversationCloseButton:Nh,ExpandButton:Ph,CloseButton:Dh}}),Qh=()=>{const{isActionbookTester:e}=Ye(),{Template:t}=ze.useContext();return e?null:o.createElement(t,{titleAlign:"start"})},eg=h.default.div`display:flex;gap:10px;align-items:center;justify-content:center;`,Ms=({children:e,onNavigateToConversationList:t,channelUrl:n,onClearChannelUrl:r,shouldMarkAsRead:s,style:a,closedChannelUrl:i,onClearClosedChannelUrl:l})=>{const{Template:c}=zt.useContext();return o.createElement(is,{onNavigateToConversationList:t,channelUrl:n??i,onClearChannelUrl:r??l,shouldMarkAsRead:s},o.createElement(pn,null,o.createElement(pn.Consumer,null,d=>o.createElement(o.Fragment,null,o.createElement(ng,{style:a,...d},o.createElement(c,null)),e))))},tg=()=>{const{components:e}=zt.useContext();return o.createElement(o.Fragment,null,o.createElement(e.Header,null),o.createElement(e.Body,null),o.createElement(e.Footer,null))},zt=pe({template:tg,components:{Header:Qh,Body:oh,Footer:Th}}),ng=h.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,{Provider:rg,Context:sg,useContext:Vn}=te("ConversationList");function $s({conversationListLimit:e,conversationListFilter:t,onOpenConversationView:n=Ce,children:r}){return o.createElement(Pa,{conversationListLimit:e,conversationListFilter:t},s=>o.createElement(rg,{value:{...s,onOpenConversationView:n}},r))}const og=({channel:e})=>o.createElement(ks,{channel:e}),xn=99,ag=e=>{var c;const{channel:t,onClick:n}=e,{stringSet:r,format:s}=K(),a=Qo(t,{formatMultipleFilesCount:r.CONVERSATION_LIST__MULTIPLE_FILES_COUNT}),i=ea(t,s,{justNow:r.DATE_FORMAT__JUST_NOW,minutesAgo:r.DATE_FORMAT__MINUTES_AGO,hoursAgo:r.DATE_FORMAT__HOURS_AGO,dateShortFormat:r.DATE_FORMAT__DATE_SHORT}),l=t.unreadMessageCount;return o.createElement(ig,{role:"button",onClick:()=>n==null?void 0:n()},o.createElement(lg,null,o.createElement(og,{...e})),o.createElement(cg,null,o.createElement(ug,null,(c=t.lastMessage)!=null&&c.isFileMessage()&&(!t.lastMessage.message||t.lastMessage.name===t.lastMessage.message)?o.createElement(cs,{variant:"subtitle1",color:f.themedColor.textHighEmphasis},a):o.createElement(M,{variant:"subtitle1",color:f.themedColor.textHighEmphasis,maxTextLines:1},a),o.createElement(dg,null,ue(t)&&o.createElement(o.Fragment,null,o.createElement(M,{variant:"caption1",color:f.themedColor.textMidEmphasis,maxTextLines:1},r.CONVERSATION_LIST__ENDED),o.createElement(mg,null)),o.createElement(M,{variant:"caption2",color:f.themedColor.textLowEmphasis,maxTextLines:1},i))),l>0&&o.createElement(hg,{$count:l},o.createElement(M,{variant:"caption3",color:f.themedColor.textHighEmphasisInverse},l<=xn?l:`${xn}+`))))},zn=pe({template:ag,components:{}}),ig=h.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:pointer;`,lg=h.default.div`display:flex;align-items:center;justify-content:center;padding-inline-start:16px;`,cg=h.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 ${f.themedColor.textDisabled};`,ug=h.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;`,dg=h.default.div`display:flex;align-items:center;gap:6px;`,mg=h.default.div`width:2px;height:2px;border-radius:1px;background-color:${f.themedColor.textLowEmphasis};`,hg=h.default.div`display:flex;align-items:center;justify-content:center;height:20px;padding:4px;border-radius:10px;background-color:${f.themedColor.error};${({$count:e})=>e<=xn&&w.css`
|
|
311
|
+
`,yh=u.lazy(()=>Promise.resolve().then(()=>require("./cjs/D2Opuq0j.cjs")).then(e=>({default:e.MarkdownText}))),Sh=()=>{const{aiAgentInfo:e,userSession:t}=oe(),{messageSource:n,channelSource:r}=ne(),[s,a]=u.useState(null),i=Rn("special-notice",r.channel),l=u.useCallback(()=>r.channel?i?n.messages.some(c=>rt(c,(t==null?void 0:t.userId)??"")):!0:null,[r.channel,i,n.messages,t==null?void 0:t.userId]);return u.useEffect(()=>{s||a(l())},[l,s]),s||!e.specialNotice?null:o.createElement(vh,null,o.createElement(yh,null,e.specialNotice))},Ah=()=>o.createElement(Th,null,o.createElement(Sh,null),o.createElement(dh,null,o.createElement(xh,null))),Th=h.default.div`z-index:0;border:none;width:100%;`,Ih=()=>{var s;const{testerType:e}=Ye(),{channelSource:t}=ne(),n=de(t.channel),r=!!e&&((s=t.channel)==null?void 0:s.isAIAgent);return n&&r?o.createElement(ih,null):o.createElement(Ah,null)},ks=({start:e,title:t,titleAlign:n="start",end:r})=>{const s=u.useRef(null),a=u.useRef(null),[i,l]=u.useState(0),[c,d]=u.useState(0);return u.useLayoutEffect(()=>{s.current&&l(s.current.offsetWidth),a.current&&d(a.current.offsetWidth)},[e,r]),o.createElement(wh,null,o.createElement(kh,null,n==="center"&&t&&o.createElement(Mh,{$sideWidth:Math.max(i,c)},o.createElement($h,null,t)),o.createElement(Lh,null,o.createElement(Rh,{ref:s},e),(n==="start"||n==="end")&&t&&o.createElement(Dh,{$align:n,$hasStart:!!e,$hasEnd:!!r},t),o.createElement(Oh,{ref:a},r))))},wh=h.default.div`position:relative;width:100%;background-color:${({theme:e})=>e.colors.base.headerBackground};border-bottom:1px solid ${f.themedColor.textDisabled};`,kh=h.default.div`position:relative;height:56px;padding:11px 12px;`,Mh=h.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;`,$h=h.default.div`max-width:100%;overflow:hidden;`,Lh=h.default.div`display:flex;flex-direction:row;align-items:center;justify-content:space-between;height:100%;z-index:1;`,Rh=h.default.div`flex-shrink:0;display:flex;align-items:center;`,Oh=h.default.div`flex-shrink:0;display:flex;align-items:center;`,Dh=h.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;`,dt=()=>it()?24:16,Nh=()=>{const{state:e}=j(),t=dt(),n=()=>{e.setOpened(!1)};return o.createElement(ve,{"aria-label":"close messenger",type:"close",size:t,onClick:n})},Ph=()=>{const{enableCloseConversationButton:e,dispatcher:t}=j(),{channelSource:n}=ne(),r=n.channel,s=dt(),a=(r==null?void 0:r.isAIAgent)&&e,i=!An(r);if(!a)return null;const l=async()=>{r&&await t.send(Be.CloseConversation({channelUrl:r.url}))};return o.createElement(ve,{"aria-label":"close conversation",type:"mute",size:s,disabled:i,onClick:l})},Fh=()=>{const{state:e,enableExpandButton:t}=j(),n=dt();return t?o.createElement(ve,{"aria-label":"expand",type:e.expanded?"collapse":"expand",size:n,onClick:()=>e.setExpanded(!e.expanded)}):null},Bh=({label:e,children:t,position:n="top",disabled:r})=>r?t:o.createElement(Cn,null,t,o.createElement(Vh,{$position:n},o.createElement(zh,{variant:"caption1"},e),o.createElement(Uh,{$position:n}))),Uh=({$position:e})=>o.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"},o.createElement("path",{d:"M6 6L0 0h12L6 6Z",fill:f.themedColor.textHighEmphasis})),Hh={top:w.css`flex-direction:column;top:0;transform:translate(-50%,-100%);`,bottom:w.css`flex-direction:column-reverse;bottom:0;transform:translate(-50%,100%);`},Cn=h.default.div`position:relative;`,Vh=h.default.div`display:flex;align-items:center;position:absolute;left:50%;z-index:${Ve.TOOLTIP};${({$position:e})=>Hh[e]}opacity:0;transition:opacity 0.2s ease-in-out;pointer-events:none;${Cn}:hover &,${Cn}:focus-within &{opacity:1;}`,zh=h.default(M)`padding:6px 8px;background:${f.themedColor.textHighEmphasis};color:${f.themedColor.textHighEmphasisInverse};border-radius:4px;font-size:12px;white-space:nowrap;`,Gh=()=>{const{logger:e}=j(),{stringSet:t}=K(),{channelSource:n}=ne(),r=n.channel,s=dt(),a=Rn("handoff-button",r),i=!An(r)||Ue(r),l=async()=>{try{const c=await(r==null?void 0:r.markConversationAsHandoff());e.info("conversation.handleAgentHandoff: success",c)}catch(c){e.error("conversation.handleAgentHandoff: error",c)}};return a?o.createElement(Bh,{label:t.HEADER_BUTTON__AGENT_HANDOFF,position:"bottom",disabled:i},o.createElement(ve,{"aria-label":"request handoff",type:"agent",size:s,disabled:i,onClick:l})):null},qh=()=>{const{stringSet:e}=K(),{onNavigateToConversationList:t}=ne();return t?o.createElement(ve,{type:"menu",size:24,onClick:()=>t(),"aria-label":e.A11Y_OPEN_CONVERSATION_LIST}):null},Ms=({channel:e,size:t=40})=>{const{userSession:n,aiAgentInfo:r}=oe(),{fallbackIcon:s,url:a}=Qr({channel:e,aiAgentInfo:r,userSession:n}),i=w.useTheme();return a?o.createElement(gs,{src:a,size:t}):o.createElement(Wh,{$size:t,$bgColor:i.colors.base.primary},o.createElement(U,{type:s,size:t*.55,color:i.colors.base.primaryContrastContent}))},Wh=h.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;`,Kh=()=>{var l,c;const{channelSource:e}=ne(),{aiAgentInfo:t,userSession:n}=oe(),{config:r}=ce(),s=e.channel,a=Qr({channel:s,userSession:n,aiAgentInfo:t}),i=(c=(l=r==null?void 0:r.conversation)==null?void 0:l.header)==null?void 0:c.avatarEnabled;return o.createElement(jh,null,i&&o.createElement(Ms,{channel:s,size:34}),o.createElement(Yh,{variant:"h2",color:f.themedColor.textHighEmphasis},a.title))},jh=h.default.div`display:flex;flex-direction:row;align-items:center;gap:6px;overflow:hidden;`,Yh=h.default(M)`text-overflow:ellipsis;overflow:hidden;white-space:nowrap;padding:2px 0;`,Xh=e=>{const{components:t}=ze.useContext();return o.createElement(ks,{start:o.createElement(t.StartArea,null),title:o.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:o.createElement(t.EndArea,null)})},Zh=()=>{const{components:e}=ze.useContext();return o.createElement(e.MenuButton,null)},Jh=()=>{const{components:e}=ze.useContext();return o.createElement(e.Title,null)},Qh=()=>{const{components:e}=ze.useContext();return o.createElement(tg,null,o.createElement(e.HandoffButton,null),o.createElement(e.ConversationCloseButton,null),o.createElement(e.ExpandButton,null),o.createElement(e.CloseButton,null))},ze=pe({template:Xh,components:{StartArea:Zh,TitleArea:Jh,EndArea:Qh,MenuButton:qh,Title:Kh,HandoffButton:Gh,ConversationCloseButton:Ph,ExpandButton:Fh,CloseButton:Nh}}),eg=()=>{const{isActionbookTester:e}=Ye(),{Template:t}=ze.useContext();return e?null:o.createElement(t,{titleAlign:"start"})},tg=h.default.div`display:flex;gap:10px;align-items:center;justify-content:center;`,$s=({children:e,onNavigateToConversationList:t,channelUrl:n,onClearChannelUrl:r,shouldMarkAsRead:s,style:a,closedChannelUrl:i,onClearClosedChannelUrl:l})=>{const{Template:c}=zt.useContext();return o.createElement(ls,{onNavigateToConversationList:t,channelUrl:n??i,onClearChannelUrl:r??l,shouldMarkAsRead:s},o.createElement(pn,null,o.createElement(pn.Consumer,null,d=>o.createElement(o.Fragment,null,o.createElement(rg,{style:a,...d},o.createElement(c,null)),e))))},ng=()=>{const{components:e}=zt.useContext();return o.createElement(o.Fragment,null,o.createElement(e.Header,null),o.createElement(e.Body,null),o.createElement(e.Footer,null))},zt=pe({template:ng,components:{Header:eg,Body:ah,Footer:Ih}}),rg=h.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,{Provider:sg,Context:og,useContext:Vn}=te("ConversationList");function Ls({conversationListLimit:e,conversationListFilter:t,onOpenConversationView:n=Ce,children:r}){return o.createElement(Fa,{conversationListLimit:e,conversationListFilter:t},s=>o.createElement(sg,{value:{...s,onOpenConversationView:n}},r))}const ag=({channel:e})=>o.createElement(Ms,{channel:e}),xn=99,ig=e=>{var c;const{channel:t,onClick:n}=e,{stringSet:r,format:s}=K(),a=ea(t,{formatMultipleFilesCount:r.CONVERSATION_LIST__MULTIPLE_FILES_COUNT}),i=ta(t,s,{justNow:r.DATE_FORMAT__JUST_NOW,minutesAgo:r.DATE_FORMAT__MINUTES_AGO,hoursAgo:r.DATE_FORMAT__HOURS_AGO,dateShortFormat:r.DATE_FORMAT__DATE_SHORT}),l=t.unreadMessageCount;return o.createElement(lg,{role:"button",onClick:()=>n==null?void 0:n()},o.createElement(cg,null,o.createElement(ag,{...e})),o.createElement(ug,null,o.createElement(dg,null,(c=t.lastMessage)!=null&&c.isFileMessage()&&(!t.lastMessage.message||t.lastMessage.name===t.lastMessage.message)?o.createElement(us,{variant:"subtitle1",color:f.themedColor.textHighEmphasis},a):o.createElement(M,{variant:"subtitle1",color:f.themedColor.textHighEmphasis,maxTextLines:1},a),o.createElement(mg,null,de(t)&&o.createElement(o.Fragment,null,o.createElement(M,{variant:"caption1",color:f.themedColor.textMidEmphasis,maxTextLines:1},r.CONVERSATION_LIST__ENDED),o.createElement(hg,null)),o.createElement(M,{variant:"caption2",color:f.themedColor.textLowEmphasis,maxTextLines:1},i))),l>0&&o.createElement(gg,{$count:l},o.createElement(M,{variant:"caption3",color:f.themedColor.textHighEmphasisInverse},l<=xn?l:`${xn}+`))))},zn=pe({template:ig,components:{}}),lg=h.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:pointer;`,cg=h.default.div`display:flex;align-items:center;justify-content:center;padding-inline-start:16px;`,ug=h.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 ${f.themedColor.textDisabled};`,dg=h.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;`,mg=h.default.div`display:flex;align-items:center;gap:6px;`,hg=h.default.div`width:2px;height:2px;border-radius:1px;background-color:${f.themedColor.textLowEmphasis};`,gg=h.default.div`display:flex;align-items:center;justify-content:center;height:20px;padding:4px;border-radius:10px;background-color:${f.themedColor.error};${({$count:e})=>e<=xn&&w.css`
|
|
312
312
|
width: 20px;
|
|
313
313
|
`}
|
|
314
|
-
`,
|
|
314
|
+
`,fg=({items:e,renderItem:t,onEndReached:n})=>{const r=s=>{const a=s.target;a.scrollHeight-a.scrollTop===a.clientHeight&&(n==null||n())};return o.createElement(pg,{onScroll:s=>r(s)},e.map((s,a)=>t(s,a)))},pg=h.default.div`width:100%;height:100%;display:flex;flex-direction:column;flex:1;overflow:auto;overscroll-behavior:contain;`,Eg=()=>{const{stringSet:e}=K(),{listSource:t,onOpenConversationView:n}=Vn(),{Template:r}=zn.useContext();return t.initialized?t.channels.length===0?o.createElement(et,{type:"noChannels",label:e.CONVERSATION_LIST__NO_CONVERSATIONS}):o.createElement(fg,{items:t.channels,renderItem:s=>{var a,i,l;return o.createElement(r,{key:s.url,channel:s,onClick:()=>n(s.url,de(s)?"closed":"open"),channelUrl:s.url,title:(i=(a=s.conversation)==null?void 0:a.topics)==null?void 0:i.join(", "),lastMessageTimestamp:(l=s.lastMessage)==null?void 0:l.createdAt})},onEndReached:()=>{t.loadMore()}}):o.createElement(et,{type:"loading"})},bg=()=>{const{stringSet:e}=K(),{_aiAgentSDK:t}=ce(),{language:n,countryCode:r,context:s}=j(),{aiAgentInfo:a,refreshActiveChannel:i,createConversation:l}=oe(),{onOpenConversationView:c}=Vn();return o.createElement(_g,{role:"button",onClick:async()=>{var d;if(a.isMultipleActiveConversationsEnabled){const m=await l({aiAgentId:a.userId,language:n,country:r,context:s});(d=t.session)==null||d._updateActiveChannel({url:m,status:"open"}),c(m,"open")}else{const m=await i();c(m,"open")}}},o.createElement(Cg,{variant:"h1"},e.TALK_TO_AGENT))},_g=h.default.div`background-color:${({theme:e})=>e.colors.base.primary};display:flex;align-items:center;justify-content:center;padding:16px;cursor:pointer;`,Cg=h.default(M)`color:${({theme:e})=>e.colors.base.primaryContrastContent};overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,xg=()=>{const{state:e}=j(),t=dt(),n=()=>{e.setOpened(!1)};return o.createElement(ve,{"aria-label":"close messenger",type:"close",size:t,onClick:n})},vg=()=>{const{stringSet:e}=K();return o.createElement(yg,{variant:"h2",color:f.themedColor.textHighEmphasis},e.CONVERSATION_LIST__HEADER_TITLE)},yg=h.default(M)`padding:0 4px;width:100%;box-sizing:border-box;text-overflow:ellipsis;overflow:hidden;white-space:nowrap;`,Sg=e=>{const{components:t}=Xe.useContext();return o.createElement(ks,{start:o.createElement(t.StartArea,null),title:o.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:o.createElement(t.EndArea,null)})},Ag=()=>null,Tg=()=>{const{components:e}=Xe.useContext();return o.createElement(e.Title,null)},Ig=()=>{const{components:e}=Xe.useContext();return o.createElement(e.CloseButton,null)},Xe=pe({template:Sg,components:{StartArea:Ag,TitleArea:Tg,EndArea:Ig,Title:vg,CloseButton:xg}}),wg=()=>{const{Template:e}=Xe.useContext();return o.createElement(e,{titleAlign:"start"})},Rs=({conversationListLimit:e,conversationListFilter:t,children:n,onOpenConversationView:r,style:s})=>{const{Template:a}=Gt.useContext();return o.createElement(Ls,{conversationListLimit:e,conversationListFilter:t,onOpenConversationView:r},o.createElement(Mg,{style:s},o.createElement(a,null)),n)},kg=()=>{const{components:e}=Gt.useContext();return o.createElement(o.Fragment,null,o.createElement(e.Header,null),o.createElement(e.Body,null),o.createElement(e.Footer,null))},Gt=pe({template:kg,components:{Header:wg,Body:Eg,Footer:bg}}),Mg=h.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,$g=w.css`:where(#${me.ENTRY}) :not(code *){font-family:'Roboto',sans-serif;box-sizing:border-box;}`,Lg=[$g,Ii,wi],Rg=(e,...t)=>w.createGlobalStyle(e,...Lg,...t),Og=Rg``,Dg=Qo(zt,De,ut,Bt,Vt,Gt,ze,zn,Xe,Ht);function Os({appearance:e,rootElement:t,logger:n,language:r,stringSet:s,children:a,messageTemplate:i,theme:l}){return Ri(Ei,t),o.createElement(w.StyleSheetManager,{target:t},o.createElement(Mi,{rootElement:t,logger:n,appearance:e,theme:l},o.createElement(Ha,{internalVariables:i==null?void 0:i.__internalVariables},o.createElement(Ti,{stringSet:s,logger:n,language:r},o.createElement(Dg,null,a,o.createElement(Og,null))))))}const Gn=u.forwardRef(function({rootElement:t=document.body,logLevel:n=Z.LogLevel.WARN,language:r=navigator.language,userSessionInfo:s,children:a,chatParams:i,...l},c){var d,m,p;return Qe.level!==n&&(Qe.level=n),Li("https://fonts.googleapis.com/css2?family=Roboto&display=swap",t),o.createElement("div",{id:me.ENTRY,style:{width:"fit-content",height:"fit-content",...l.entryStyle}},o.createElement(Os,{logger:Qe,rootElement:t,appearance:(d=l.agentPreviewConfigs)==null?void 0:d.appearance,stringSet:l.stringSet,language:r,messageTemplate:l.messageTemplate,theme:l.theme},o.createElement(Di,{rootElement:t,language:r,logger:Qe,dispatcher:Ds,chatParams:{...i,...l.customApiHost&&{customApiHost:l.customApiHost},...l.customWebSocketHost&&{customWebSocketHost:l.customWebSocketHost}},chatSDK:l.customChatSDK,_forceCreateChannel:(m=l.agentPreviewConfigs)==null?void 0:m.forceCreateChannel,_agentVersion:(p=l.agentPreviewConfigs)==null?void 0:p.agentVersion,...l},o.createElement(Yi,{ref:c,userSessionInfo:s},o.createElement(Qd,{...l._UNSAFE_INTERNAL_dashboardTester},a,o.createElement("div",{id:me.MODAL_ROOT,dir:l.dir}))))))}),Qe=new Vr(Z.LogLevel.WARN),Ds=new Hr(Qe),{Provider:Ng,useContext:qn}=te("PageChildren"),Ns=({children:e})=>{const[t,n]=u.useState(null),[r,s]=u.useState(null);return o.createElement(Ng,{value:{conversationChildren:t,setConversationChildren:n,conversationListChildren:r,setConversationListChildren:s}},e)},Ps=({children:e,isOpened:t})=>{const{dir:n,rootElement:r}=j(),s=He(r,!0);return u.useEffect(()=>{const a="sb-agent-block-scroll";return t?s.body.classList.add(a):s.body.classList.remove(a),()=>{s.body.classList.remove(a)}},[s,t]),o.createElement(Pg,{dir:n,$visible:t},e)},Pg=h.default.div`width:100%;height:100%;position:fixed;top:0;left:0;z-index:${Ve.WINDOW};visibility:${({$visible:e})=>e?"visible":"hidden"};`,Fg=48,Bg=2/3;function Fs({className:e,isOpened:t,onClick:n,type:r,imageUrl:s,dir:a,animated:i=!0,backgroundColor:l,size:c=Fg}){const d=hn(l),m=Math.round(c*Bg);return o.createElement(Vg,{dir:a,id:me.LAUNCHER,className:e,"aria-label":"Sendbird AIAgent Launcher",onClick:n,$animated:i,$backgroundColor:l,$size:c},o.createElement(zg,{$isOpened:t,$animated:i,$fillColor:d,$iconSize:m},o.createElement(Or.Open,{url:s,isDefaultIcon:r==="default_icon",size:m})),o.createElement(Gg,{$isOpened:t,$animated:i,$fillColor:d,$iconSize:m},o.createElement(Or.Close,{size:m})))}const Ug=w.css`&:hover{transition:transform 250ms cubic-bezier(0.33,0,0,1);transform:scale(1.1);}&:active{transform:scale(0.8);}`,Hg=w.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===nt.WHITE?"grayscale(100%) brightness(2000%)":"grayscale(100%) invert(100%) saturate(0%) brightness(0%) contrast(1000%)"};}}`,Bs=w.css`svg{width:${({$iconSize:e})=>e}px;height:${({$iconSize:e})=>e}px;${({$fillColor:e})=>w.css`
|
|
315
315
|
ellipse,
|
|
316
316
|
path {
|
|
317
317
|
fill: ${e};
|
|
@@ -321,15 +321,15 @@
|
|
|
321
321
|
}
|
|
322
322
|
`}
|
|
323
323
|
}
|
|
324
|
-
`,
|
|
324
|
+
`,Vg=h.default.button`position:relative;padding:0;width:${({$size:e})=>e}px;height:${({$size:e})=>e}px;background:${({$backgroundColor:e})=>e};border-radius:50%;transition: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&&Ug}`,Us=h.default.span`position:absolute;width:100%;height:100%;border-radius:50%;overflow:hidden;transition:transform 0.16s linear,opacity 0.08s linear,scale 0.16s linear;user-select:none;display:flex;justify-content:center;align-items:center;`,zg=h.default(Us)`opacity:${({$isOpened:e})=>e?0:1};transform:${({$animated:e,$isOpened:t})=>e&&(t?"rotate(-90deg) scale(0)":"rotate(0deg)")};${Hg}${Bs}`,Gg=h.default(Us)`scale:${({$isOpened:e})=>e?1:0};transform:${({$animated:e,$isOpened:t})=>e&&(t?"rotate(0deg)":"rotate(-90deg)")};${Bs}`,Or={Open:e=>e.url?o.createElement("img",{src:e.url,alt:"launcher-img","data-default-icon":e.isDefaultIcon}):o.createElement(U,{size:e.size,type:"delight"}),Close:({size:e})=>o.createElement(U,{size:e,type:"chevron-down"})};function Hs({className:e,size:t}){const{colors:n}=w.useTheme(),{dir:r,state:s}=j(),{launcherInfo:a,statsTrackers:i}=oe();return u.useLayoutEffect(()=>{i.initialRender.setPresentMethod("launcher_toggle")},[i]),Wg(),o.createElement(Fs,{dir:r,className:e,isOpened:s.opened,onClick:()=>s.setOpened(!s.opened),type:a.type,imageUrl:a.imageUrl,backgroundColor:n.base.primary,size:t})}const qg=1e3*60;function Wg(){const{chatSDK:e,state:t,logger:n,enableAutoDisconnectInLauncher:r}=j(),s=u.useRef(null);u.useEffect(()=>{if(!r)return;function a(){s.current&&(clearTimeout(s.current),s.current=null)}function i(){e.connectionState===Z.ConnectionState.CLOSED&&(e.reconnect(),n.debug("useSDKInactivityTimeout: reconnected")),a(),n.debug("useSDKInactivityTimeout: clear disconnect schedule")}function l(){a(),s.current=setTimeout(async()=>{await e.disconnectWebSocket(),n.debug("useSDKInactivityTimeout: disconnected")},qg)}t.opened?i():(l(),n.debug("useSDKInactivityTimeout: schedule disconnect"))},[r,e,t.opened])}const Vs=u.createContext(null);function zs(){const e=u.useContext(Vs);if(!e)throw new Error("useNavigator() must be used within <Navigator />");return e}function Gs({children:e}){const t=zs();return typeof e=="function"?e(t):o.createElement(o.Fragment,null,e)}const Kg=w.keyframes`0%{transform:translateY(40px);opacity:0;}100%{transform:translateY(0px);opacity:1;}`,jg=w.keyframes`0%{transform:translateY(0px);opacity:1;}100%{transform:translateY(40px);opacity:0;}`,Yg=w.css`animation-name:${Kg};animation-duration:0.3s;animation-fill-mode:forwards;`,Xg=w.css``,Zg=w.css`animation-name:${jg};animation-duration:0.3s;animation-fill-mode:forwards;`,Jg=w.css`visibility:hidden;`,Qg=h.default.div`position:absolute;top:0;left:0;width:100%;height:100%;${({$transitionState:e})=>{switch(e){case"entering":return Yg;case"entered":return Xg;case"exiting":return Zg;case"exited":return Jg;default:return""}}}${({$active:e})=>e?w.css`
|
|
325
325
|
z-index: 999;
|
|
326
326
|
`:w.css`z-index:1;pointer-events:none;`}
|
|
327
|
-
`;function yt({initialId:e,children:t}){const[n,r]=u.useState([e]),s=n[n.length-1],a=u.useCallback((g,_)=>{r(y=>[...y,g]),p(y=>({...y,[g]:!0})),_!=null&&_.reset&&b(y=>({...y,[g]:(y[g]||0)+1})),v(y=>({...y,[g]:"entering"})),setTimeout(()=>{v(y=>({...y,[g]:"entered"}))},300)},[]),i=u.useCallback(()=>{r(g=>{if(g.length<=1)return g;const _=g[g.length-1];return v(y=>({...y,[_]:"exiting"})),setTimeout(()=>{v(y=>({...y,[_]:"exited"})),r(y=>y.slice(0,-1))},300),g})},[]),l=u.useMemo(()=>({navigation:{navigate:a,pop:i},activeScreenId:s}),[a,i,s]),c=u.useMemo(()=>u.Children.toArray(t).filter(g=>g.type===
|
|
327
|
+
`;function yt({initialId:e,children:t}){const[n,r]=u.useState([e]),s=n[n.length-1],a=u.useCallback((g,_)=>{r(y=>[...y,g]),p(y=>({...y,[g]:!0})),_!=null&&_.reset&&b(y=>({...y,[g]:(y[g]||0)+1})),v(y=>({...y,[g]:"entering"})),setTimeout(()=>{v(y=>({...y,[g]:"entered"}))},300)},[]),i=u.useCallback(()=>{r(g=>{if(g.length<=1)return g;const _=g[g.length-1];return v(y=>({...y,[_]:"exiting"})),setTimeout(()=>{v(y=>({...y,[_]:"exited"})),r(y=>y.slice(0,-1))},300),g})},[]),l=u.useMemo(()=>({navigation:{navigate:a,pop:i},activeScreenId:s}),[a,i,s]),c=u.useMemo(()=>u.Children.toArray(t).filter(g=>g.type===Gs),[t]),d=u.useMemo(()=>{const g={};return c.forEach(_=>{const{id:y,lazy:I,children:A}=_.props;g[y]={lazy:I,element:typeof A=="function"?A(l):A}}),g},[c,l]),[m,p]=u.useState(()=>{const g={};return Object.entries(d).forEach(([_,{lazy:y}])=>{y===!1&&(g[_]=!0)}),g[e]=!0,g}),[E,v]=u.useState(()=>{const g={};return Object.keys(d).forEach(_=>{_===e?g[_]="entered":g[_]="exited"}),g}),[x,b]=u.useState({});return o.createElement(Vs.Provider,{value:l},o.createElement(ef,null,Object.keys(d).map(g=>{var A;if(!m[g])return null;const _=E[g]||"exited",y=g===s,I=`${g}-${x[g]||0}`;return o.createElement(Qg,{key:I,$transitionState:_,$active:y},(A=d[g])==null?void 0:A.element)})))}const ef=h.default.div`position:relative;width:100%;height:100%;`;yt.Screen=Gs;const _e={conv:"conv",convList:"conv-list"},qs=({isOpened:e,entryPoint:t,selectedChannelUrl:n,setSelectedChannelUrl:r})=>{const{conversationChildren:s,conversationListChildren:a}=qn(),i=(()=>{switch(t){case"Conversation":return _e.conv;case"ConversationList":return _e.convList;default:return _e.conv}})(),l=o.createElement(o.Fragment,null,o.createElement(tf,{onOpenConversationView:r}));return o.createElement(yt,{initialId:i},o.createElement(yt.Screen,{id:_e.conv},({navigation:c,activeScreenId:d})=>o.createElement($s,{key:n,channelUrl:n,onClearChannelUrl:()=>r(void 0),onNavigateToConversationList:()=>c.navigate(_e.convList),shouldMarkAsRead:e&&d===_e.conv},l,s)),o.createElement(yt.Screen,{id:_e.convList,lazy:!0},({navigation:c})=>o.createElement(Rs,{onOpenConversationView:d=>{r(d),c.navigate(_e.conv)}},l,a)))},tf=({onOpenConversationView:e})=>{const{registerOnJoinedProactiveConversation:t}=oe(),{navigation:n}=zs();return t(({channel:r})=>{e(r.url),n.navigate(_e.conv)}),null};function nf({isExpanded:e,isOpened:t,children:n,launcher:r}){const{dir:s}=j();return o.createElement(rf,null,o.createElement(sf,{dir:s,id:me.WINDOW,$isExpanded:e,$isOpened:t},n),r)}const rf=h.default.div`display:flex;flex-direction:column;gap:8px;align-items:flex-end;`,sf=h.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&&af};${({$isExpanded:e})=>e&&of};`,of=w.css`width:743px;height:723px;`,af=w.css`z-index:${Ve.WINDOW};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;`,lf=u.forwardRef(function({children:e,initialChannelUrl:t,...n},r){const s=it(),[a,i]=u.useState(t),l=s?Ps:nf;return o.createElement(Gn,{enableExpandButton:!s,ref:r,...n},o.createElement(rs,null,({state:c})=>o.createElement(Ns,null,o.createElement(l,{isExpanded:c.expanded,isOpened:c.opened,launcher:o.createElement(Hs,null)},o.createElement(qs,{isOpened:c.opened,entryPoint:n.entryPoint,selectedChannelUrl:a,setSelectedChannelUrl:i})),e)))}),{Provider:cf,useContext:Wn}=te("FixedMessengerStyle");function Ws(e,t,n,r=0){const{top:s,bottom:a,start:i,end:l}=n;let c="",d="";switch(e){case"start":d=`inset-inline-start: ${ge(i)}`;break;case"end":d=`inset-inline-end: ${ge(l)}`;break}switch(t){case"top":c=`top: calc(${ge(s)} + ${r}px)`;break;case"bottom":c=`bottom: calc(${ge(a)} + ${r}px)`;break}return w.css`${c};${d};`}function uf(e){const{horizontal:t,vertical:n,margin:r,launcherSize:s}=Wn();return o.createElement(df,{...e,size:s,$horizontal:t,$vertical:n,$margin:r})}const df=h.default(Hs)`position:fixed;z-index:${Ve.LAUNCHER};${({$horizontal:e,$vertical:t,$margin:n})=>Ws(e,t,n)};`;function mf({isExpanded:e,isOpened:t,children:n}){const{dir:r}=j(),{horizontal:s,vertical:a,margin:i,launcherSize:l}=Wn();return o.createElement(hf,{dir:r,id:me.WINDOW,$isExpanded:e,$isOpened:t,$horizontal:s,$vertical:a,$margin:i,$launcherSize:l},n)}const hf=h.default.div`background:${({theme:e})=>e.colors.base.background};display:flex;overscroll-behavior:none;-webkit-overflow-scrolling:auto;position:fixed;${({$horizontal:e,$vertical:t,$margin:n,$launcherSize:r})=>Ws(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;transform:scale(0.15);opacity:0;transform-origin:${({$horizontal:e,$vertical:t})=>`${e==="start"?"left":"right"} ${t}`};
|
|
328
328
|
[dir='rtl'] &:not([dir='ltr']),
|
|
329
329
|
&[dir='rtl'] {
|
|
330
330
|
transform-origin: ${({$horizontal:e,$vertical:t})=>`${e==="start"?"right":"left"} ${t}`};
|
|
331
331
|
}
|
|
332
332
|
|
|
333
|
-
${({$isOpened:e})=>e&&
|
|
334
|
-
${({$isExpanded:e})=>e&&
|
|
335
|
-
`,
|
|
333
|
+
${({$isOpened:e})=>e&&ff};
|
|
334
|
+
${({$isExpanded:e})=>e&&gf};
|
|
335
|
+
`,gf=w.css`width:743px;height:723px;`,ff=w.css`z-index:${Ve.WINDOW};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;`,Ks={top:24,bottom:24,start:24,end:24},pf=u.forwardRef(function({children:e,initialChannelUrl:t,...n},r){const[s,a]=u.useState(t),[i,l]=u.useState("end-bottom"),[c,d]=u.useState(Ks),[m,p]=u.useState(48),E=it(),v=E?Ps:mf,{horizontal:x,vertical:b}=u.useMemo(()=>{const[g,_]=i.split("-");return{horizontal:g==="start"?"start":"end",vertical:_==="top"?"top":"bottom"}},[i]);return o.createElement(Gn,{enableExpandButton:!E,ref:r,...n},o.createElement(rs,null,({state:g})=>o.createElement(cf,{value:{horizontal:x,vertical:b,margin:c,launcherSize:m,setPosition:l,setMargin:d,setLauncherSize:p}},o.createElement(Ns,null,o.createElement(v,{isExpanded:g.expanded,isOpened:g.opened},o.createElement(qs,{isOpened:g.opened,entryPoint:n.entryPoint,selectedChannelUrl:s,setSelectedChannelUrl:a})),o.createElement(uf,null),e))))}),Ef=e=>{var s,a,i,l;const{setPosition:t,setMargin:n,setLauncherSize:r}=Wn();return u.useLayoutEffect(()=>{e.position&&t(e.position),e.margin&&n({...Ks,...e.margin}),e.launcherSize&&r(e.launcherSize)},[e.position,(s=e.margin)==null?void 0:s.top,(a=e.margin)==null?void 0:a.bottom,(i=e.margin)==null?void 0:i.start,(l=e.margin)==null?void 0:l.end,e.launcherSize]),null},bf=({children:e})=>{const{setConversationChildren:t}=qn();return u.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},_f=({children:e})=>{const{setConversationListChildren:t}=qn();return u.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},Cf=Object.assign(pf,{Style:Ef,ConversationChildren:bf,ConversationListChildren:_f}),xf=e=>{const{refreshActiveChannel:t}=oe(),[n,r]=u.useState(!1),s=u.useRef(null),a=u.useRef(null);return u.useEffect(()=>{n&&t().then(()=>{var i;(i=s.current)==null||i.call(s),r(!1)}).catch(i=>{var l;(l=a.current)==null||l.call(a,i),r(!1)})},[n]),u.useCallback(()=>new Promise((i,l)=>{s.current=i,a.current=l,e().then(()=>r(!0)).catch(l)}),[e])};Wr.set(Z.SendbirdPlatform.JS,{deviceOSPlatform:go()?Z.DeviceOsPlatform.MOBILE_WEB:Z.DeviceOsPlatform.WEB,messengerVersion:gi,keyValueStorage:pi(),networkStateAdapter:fi()});exports.ANCHOR_REL=On;exports.AgentProviderContainer=Gn;exports.AgentUIProviderContainer=Os;exports.AnonymousSessionInfo=dn;exports.CSATType=he;exports.Commands=Be;exports.Conversation=$s;exports.ConversationContext=cl;exports.ConversationContextProvider=ls;exports.ConversationHeaderLayout=ze;exports.ConversationLayout=zt;exports.ConversationList=Rs;exports.ConversationListContext=og;exports.ConversationListContextProvider=Ls;exports.ConversationListHeaderLayout=Xe;exports.ConversationListItemLayout=zn;exports.ConversationListLayout=Gt;exports.DefaultMessenger=lf;exports.DeskTicketPriority=kn;exports.DeskTicketStatus=wn;exports.FixedMessenger=Cf;exports.IncomingMessageLayout=De;exports.LauncherBase=Fs;exports.LogLevel=Sn;exports.ManualSessionInfo=zr;exports.MessageListUILayout=Vt;exports.MessageLogs=As;exports.OutgoingMessageLayout=ut;exports.PlaceholderLayout=Ht;exports.SystemMessageLayout=Bt;exports.cssVars=f;exports.escapeMarkdownSyntax=mo;exports.mapCommonStringsToReactFormat=ts;exports.messengerDispatcher=Ds;exports.useAIAgentContext=ce;exports.useConversationContext=ne;exports.useConversationListContext=Vn;exports.useLocalizationContext=K;exports.useMessengerContext=j;exports.useMessengerSessionContext=oe;exports.useRefreshActiveChannel=xf;
|