@sendbird/ai-agent-messenger-react 1.21.2 → 1.22.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/A0RFIJy_.cjs +1 -0
- package/dist/cjs/BNjeOTuI.cjs +1 -0
- package/dist/cjs/BV40WZg3.cjs +1 -0
- package/dist/cjs/Bwaslfwl.cjs +1 -0
- package/dist/cjs/C3OHcrBV.cjs +1 -0
- package/dist/cjs/D2fiRjSz.cjs +1 -0
- package/dist/cjs/DGubkk9p.cjs +1 -0
- package/dist/cjs/DVc2qz6N.cjs +1 -0
- package/dist/cjs/jGp6gOJ2.cjs +1 -0
- package/dist/cjs/pDHRH5ez.cjs +1 -0
- package/dist/cjs/rNq_TnmW.cjs +1 -0
- package/dist/cjs/w1C9O3WB.cjs +1 -0
- package/dist/es/{C5TioO5h.js → 89kkkmJB.js} +78 -17
- package/dist/es/{BELIKAJm.js → B1Zl6v7X.js} +75 -14
- package/dist/es/{BdQuAUPe.js → BL89djVk.js} +78 -17
- package/dist/es/{ETHHqHi2.js → BPLO52kK.js} +78 -17
- package/dist/es/{DlJqMPv3.js → BbQiMuUs.js} +78 -17
- package/dist/es/Bi1npOpy.js +5 -0
- package/dist/es/C_Rvvh_g.js +5 -0
- package/dist/es/{DqTYCLQ3.js → Culegmk_.js} +78 -17
- package/dist/es/CvWQvWt9.js +5 -0
- package/dist/es/{D_jawtL2.js → DaiGT8Mr.js} +76 -15
- package/dist/es/{CNnV1uD8.js → Dd81G18F.js} +78 -17
- package/dist/es/{CT9vVq3h.js → gn5TNb_w.js} +78 -17
- package/dist/index.cjs +232 -128
- package/dist/index.d.ts +254 -8
- package/dist/index.js +5635 -3395
- package/package.json +2 -2
- package/dist/cjs/7UVs65zS.cjs +0 -1
- package/dist/cjs/BMS5Zb7W.cjs +0 -1
- package/dist/cjs/BRnfdIkb.cjs +0 -1
- package/dist/cjs/DFmkiYPE.cjs +0 -1
- package/dist/cjs/DTCJ6-eC.cjs +0 -1
- package/dist/cjs/DbxUqtQc.cjs +0 -1
- package/dist/cjs/DfRVurNO.cjs +0 -1
- package/dist/cjs/Dl0262MS.cjs +0 -1
- package/dist/cjs/JLk8Bvao.cjs +0 -1
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,10 @@
|
|
|
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`
|
|
1
|
+
"use strict";var ni=Object.defineProperty;var ri=(e,t,n)=>t in e?ni(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var S=(e,t,n)=>ri(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Q=require("@sendbird/chat"),u=require("react"),D=require("styled-components"),Ze=require("date-fns"),oi=require("date-fns/locale/en-US"),Pe=require("@sendbird/chat/message"),ue=require("@sendbird/chat/aiAgent"),ct=require("@sendbird/chat/groupChannel"),He=require("@sendbird/uikit-tools"),si=require("react-dom"),ii=require("date-fns/isSameDay"),Mn=require("@sendbird/react-uikit-message-template-view"),ai=require("@sendbird/uikit-message-template"),li=require("dompurify"),ci=require("@emotion/is-prop-valid"),nn=e=>e&&e.__esModule?e:{default:e};function ui(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 di=nn(Q),i=ui(u),p=nn(D),bo=nn(li),mi=nn(ci),at="sb-agent",Co="KEY_IMG_ASPECT_RATIO",Ln="*/*",z={BODY_MAX_WIDTH:244,WIDE_BODY_MAX_WIDTH:640,AVATAR_SIZE:26,BODY_TIME_GAP:4,HORIZONTAL_PADDING:12,GAP_GROUPED:2,GAP_UNGROUPED:16};var Wt=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(Wt||{}),Ct=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(Ct||{});const vo=e=>{var t;return!!((t=e==null?void 0:e.extendedMessagePayload)!=null&&t.steward)},hi=e=>e===Ct.COMPLETED||e===Ct.CANCELED?e:Ct.IN_PROGRESS,_n=e=>Ae(e)&&!vo(e),Ae=e=>!!e&&"sender"in e,gi=e=>Ae(e)?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId),Cr=(e,t)=>!e||!t?!1:Ae(e)&&Ae(t)?e.messageId>0&&t.messageId>0?e.messageId===t.messageId:e.reqId.length>0&&e.reqId===t.reqId:e.messageId>0&&e.messageId===t.messageId,fi=(e,t,n,r=!0)=>{if(!r||!_n(e))return"single";const o=()=>{if(!_n(t))return!1;const c=t.sender.userId===e.sender.userId,d=Ze.isSameMinute(t.createdAt,e.createdAt);return c&&d},s=()=>{if(!_n(n))return!1;const c=n.sender.userId===e.sender.userId,d=Ze.isSameMinute(n.createdAt,e.createdAt);return c&&d},a=o(),l=s();return a&&l?"middle":a?"bottom":l?"top":"single"},St=(e,t)=>(()=>{var r;return Ae(e)?e.sender.userId:((r=e==null?void 0:e.sender)==null?void 0:r.userId)??void 0})()===t,te={isAdmin:e=>e.isAdminMessage(),isCSAT:e=>{var t;return e.isAdminMessage()&&!!((t=e.extendedMessagePayload)!=null&&t.csat)},isSteward:e=>vo(e),isIncoming:(e,t)=>Ae(e)&&e.sender.userId!==t,isOutgoing:(e,t)=>Ae(e)&&(e.sender.userId===t||e.sendingStatus===Pe.SendingStatus.PENDING)},De=e=>e.startsWith("image/"),yo=e=>e.startsWith("video/"),Wn=(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"},So=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},rn=e=>{switch(e){case"top":case"middle":return z.GAP_GROUPED;default:return z.GAP_UNGROUPED}},pi=(e,t)=>{const n=/```(\w+)?\n([\s\S]*?)```/g,r=[];let o=0;return e.replace(n,(s,...a)=>{const[l,c,d]=a;return o<d&&r.push({type:"text",value:e.slice(o,d).trim()}),r.push({type:"code",value:c.trim(),language:l?l.trim():"plaintext"}),o=d+s.length,s}),o<e.length&&r.push({type:"text",value:e.slice(o).trim()}),t?r.map(s=>s.type!=="text"?s:{...s,value:t(s.value)}):r},_i=e=>e.replace(/\[([^\]]+)\](?!\()/g,"\\[$1\\]"),Ei=e=>e.replace(/([a-zA-Z0-9])_(?=[a-zA-Z0-9])/g,"$1\\_"),bi=e=>e.replace(/~~/g,"\\~\\~"),Ci=e=>{let t=e;return t=_i(t),t=Ei(t),t=bi(t),t},vi=typeof navigator<"u"&&navigator.product==="ReactNative",vr=(e,t)=>{const n=r=>!t||t.length===0?!0:Ae(r)&&t.includes(r.sendingStatus);return vi?e.find(n):e.findLast(n)};function X(){}function yi(){const e=typeof navigator<"u"?navigator.userAgent:"",t=/iPad|iPhone|iPod/.test(e),n=/Android/.test(e);return t||n}function Si(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 On=e=>{try{return JSON.parse(e===""?"{}":e)}catch{return{}}},Fe={isStreaming(e){const t=On(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(St(e,t)){const r=On(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)}},En=`@${at}`,xi=({appId:e,aiAgentId:t,storage:n})=>{const r={templateBase:`${En}-template`,template:o=>`${r.templateBase}/templates/${o}`,templateToken:()=>`${r.templateBase}/tokens`,messengerSession:o=>{const s=Si(`${e}/${t}/${o}`);return`${En}-udata/${s}`},anonUserSession:()=>`${En}-session/${e}/${t}`};return{template:{set:(o,s)=>n.set(r.template(o),s),get:o=>n.get(r.template(o)),setCachedToken:o=>n.set(r.templateToken(),o),getCachedToken:()=>n.get(r.templateToken()),clear:()=>{n.getKeys(r.templateBase).forEach(n.delete)}},messenger:{getSettings:o=>{try{const s=n.get(r.messengerSession(o));return s?JSON.parse(s):null}catch{return null}},setSettings:(o,s)=>{try{delete s.auto_created_user;const a=JSON.stringify(s);n.set(r.messengerSession(o),a)}catch{return}},getAnonUser:()=>{try{const o=n.get(r.anonUserSession());return o?JSON.parse(o):null}catch{return null}},setAnonUser:o=>{try{const s=JSON.stringify(o);n.set(r.anonUserSession(),s)}catch{return}},clear:o=>{try{o&&n.delete(r.messengerSession(o)),n.delete(r.anonUserSession())}catch{return}}}}},xo=(e,t,n={})=>{let r=null,o=null,s=null;const{leading:a=!0,trailing:l=!0}=n,c=(...d)=>{const m=Date.now();if(s===null||m-s>=t)a?(e(...d),s=m):(o=d,s=m);else if(o=d,l&&!r){const h=t-(m-s);r=setTimeout(()=>{o&&l&&(e(...o),s=Date.now()),r=null,o=null},h)}};return c.cancel=()=>{r&&(clearTimeout(r),r=null),o=null,s=null},c};class Ao{constructor(t,{filter:n,limit:r=20}){S(this,"filter");S(this,"_sdk");S(this,"_pinnedChannels");S(this,"_channels");S(this,"_isDisposed",!1);S(this,"_handlerId",`handler-id-${Date.now()}`);S(this,"_order",ct.GroupChannelListOrder.LATEST_LAST_MESSAGE);S(this,"_limit");S(this,"_query");S(this,"_token");S(this,"_timestamp");S(this,"_isSyncing");S(this,"_channelHandler");S(this,"_connectionHandler");S(this,"_collectionEventHandler");S(this,"_throttledOnChannelChanged");var o,s,a,l,c,d,m;this.filter=n,this._sdk=t,this._pinnedChannels=[],this._channels=[],this._limit=r,this._query=this._sdk.aiAgent.createMyGroupChannelListQuery({aiAgentChannelFilter:(o=this.filter)==null?void 0:o.aiAgentChannelFilter,aiAgentConversationStatusFilter:(s=this.filter)==null?void 0:s.aiAgentConversationStatusFilter,aiAgentIds:(a=this.filter)==null?void 0:a.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=xo(h=>{this._query.belongsTo(h)?this._addChannelsToView([h],!1):this._removeChannelsFromView([h.url])},250,{trailing:!1,leading:!0}),this._channelHandler=new ct.GroupChannelHandler({onChannelChanged:h=>{h.isGroupChannel()&&this._throttledOnChannelChanged(h)},onChannelDeleted:h=>{this._removeChannelsFromView([h])}}),this._connectionHandler=new Q.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 s,a;const n=new Set(((s=this.filter)==null?void 0:s.pinnedChannelUrls)??[]),r=t.find(l=>!n.has(l.url));let o;r?o=((a=r.lastMessage)==null?void 0:a.createdAt)??r.createdAt:o=this._query.lastResponseAt,this._timestamp>o&&(this._timestamp=o)}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])),o=[],s=[],a=[];for(const c of t){if(!this._query.belongsTo(c)){a.push(c.url);continue}const d=r.get(c.url);if(d===void 0)continue;const m=Rn(this._pinnedChannels,c);m>=0?(this._pinnedChannels.splice(m,1),s.push(c)):o.push(c);const f=this._pinnedChannels.findIndex(C=>(r.get(C.url)??1/0)>d),b=f===-1?this._pinnedChannels.length:f;this._pinnedChannels.splice(b,0,c)}return{addedChannels:o,updatedChannels:s,unmatchedChannelUrls:a}}_upsertRegularChannelsToArray(t,n=!1){const r=[],o=[],s=[];for(const a of t){if(!this._query.belongsTo(a)){r.push(a.url);continue}const l=Rn(this._channels,a),c=l<0;!c&&this._channels.splice(l,1);const m=Ai(this._channels,a,this._order).place,h=m===this._channels.length;c?h?(n||!this.hasMore)&&(this._channels.push(a),o.push(a)):(this._channels.splice(m,0,a),o.push(a)):(this._channels.splice(m,0,a),s.push(a))}return{addedChannels:o,updatedChannels:s,unmatchedChannelUrls:r}}_addChannelsToView(t,n=!1){var h,f,b,C,v;const r=new Set(((h=this.filter)==null?void 0:h.pinnedChannelUrls)??[]),o=[],s=[];for(const _ of t)r.has(_.url)?o.push(_):s.push(_);const a=this._upsertPinnedChannelsToArray(o),l=this._upsertRegularChannelsToArray(s,n),c=a.addedChannels.concat(l.addedChannels),d=a.updatedChannels.concat(l.updatedChannels),m=a.unmatchedChannelUrls.concat(l.unmatchedChannelUrls);c.length>0&&((b=(f=this._collectionEventHandler)==null?void 0:f.onChannelsAdded)==null||b.call(f,{},c)),d.length>0&&((v=(C=this._collectionEventHandler)==null?void 0:C.onChannelsUpdated)==null||v.call(C,{},d)),m.length>0&&this._removeChannelsFromView(m)}_removeChannelsFromView(t){var o,s,a;const n=new Set(((o=this.filter)==null?void 0:o.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&&((a=(s=this._collectionEventHandler)==null?void 0:s.onChannelsDeleted)==null||a.call(s,{},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 Rn=(e,t)=>e.findIndex(n=>n.isIdentical(t)),Ai=(e,t,n)=>{if(e.length>0){const r=Rn(e,t);let o=0,s=e.length-1,a=Math.floor((o+s)/2);for(;o<s;){const c=yr(e[a],t,n);if(c>0)s=a,a=Math.floor((o+s)/2);else if(c<0)o=a+1,a=Math.floor((o+s)/2);else return{place:a,oldPosition:r}}return{place:yr(e[a],t,n)>=0?a:a+1,oldPosition:r}}return{place:e.length,oldPosition:-1}},yr=(e,t,n)=>{switch(n){case ct.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 To{constructor(t){S(this,"subscribers",{});this.logger=t}async send(t){const n=Ti(),r=this.subscribers[t.type];if(r){this.logger.debug(`messenger.dispatcher: dispatching command: ${t.type}`,t.payload);const o=r.map(s=>s(t.payload));await Promise.all(o).catch(s=>{this.logger.error(`messenger.dispatcher: error in callback for command: ${t.type}`,s)})}return n.resolve(),n.promise}subscribe(t,n){this.subscribers[t]||(this.subscribers[t]=[]),this.subscribers[t].push(n)}unsubscribe(t,n){const r=this.subscribers[t];r&&(this.subscribers[t]=r.filter(o=>o!==n))}}const Ti=()=>{let e=X,t=X;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}};var xe=(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))(xe||{});class xt{constructor(t={}){S(this,"payload");this.payload=t}toJSON(){return JSON.stringify({type:this.type,payload:this.payload})}}const Je={CloseConversation:e=>new Ii(e),MessengerSettingsUpdated:e=>new wi(e),ActiveChannelUpdated:e=>new ki(e),AnonymousSessionTokenExpired:()=>new Mi,AuthTokenRefreshed:()=>new Li};class Ii extends xt{constructor(){super(...arguments);S(this,"type","conv.close")}}class wi extends xt{constructor(){super(...arguments);S(this,"type","messenger.settings.updated")}}class ki extends xt{constructor(){super(...arguments);S(this,"type","active.channel.updated")}}class Mi extends xt{constructor(){super(...arguments);S(this,"type","anon.token.expired")}}class Li extends xt{constructor(){super(...arguments);S(this,"type","auth.token.refreshed")}}var qn=(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))(qn||{});class Io{constructor(t){S(this,"level");this.level=t}verbose(...t){this.level<=0&&console.log(`[${at}/verbose]`,...t)}debug(...t){this.level<=1&&console.log(`[${at}/debug]`,...t)}info(...t){this.level<=2&&console.log(`[${at}/info]`,...t)}warn(...t){this.level<=3&&console.warn(`[${at}/warn]`,...t)}error(...t){this.level<=4&&console.error(`[${at}/error]`,...t)}}class wo{constructor({userId:t,authToken:n,sessionHandler:r}){S(this,"userId");S(this,"authToken");S(this,"sessionHandler");this.userId=t,this.authToken=n,this.sessionHandler=r}}class Nn{constructor(){S(this,"userId");S(this,"authToken");S(this,"sessionHandler")}}const Oi=e=>({onSessionTokenRequired:t=>{t(null),e.send(Je.AnonymousSessionTokenExpired())}}),Ri="ai_agent:stats",Ni="conversation_initial_render",$i=800220;var ee=(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))(ee||{});class Di{constructor(){S(this,"timers",new Map);S(this,"committed",!1);S(this,"commitCallback",null);S(this,"conversationId",null);S(this,"channelUrl",null);S(this,"errorCode",null);S(this,"errorDescription",null);S(this,"extraData",{})}setCommitCallback(t){return this.commitCallback=t,this}setConversationId(t){return this.conversationId=t,this}setChannelUrl(t){return this.setExtra("channel_url",t),this}setError(t,n){return this.errorCode=t??$i,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(Ri,t)):!1}}class Pi extends Di{constructor(){super(...arguments);S(this,"presentMethod","direct_present")}setPresentMethod(n){return this.presentMethod=n,this}getMetricKey(){return Ni}buildPayload(){const n=this.getDuration(ee.AUTH),r=this.getDuration(ee.GET_CHANNEL),o=this.getDuration(ee.GET_MESSAGES),s=this.getDuration(ee.TOTAL_DURATION_FROM_CACHE),a=this.getDuration(ee.TOTAL_DURATION),l={...this.extraData,present_method:this.presentMethod,...n!==null&&{auth_duration:n},...r!==null&&{get_channel_duration:r},...o!==null&&{get_messages_duration:o},...s!==null&&{total_duration_from_cache:s}},c={key:this.getMetricKey(),value:a!==null?String(a):"0"};return this.conversationId!==null&&(c.conversation_id=this.conversationId),this.errorCode!==null&&(c.error_code=this.errorCode),this.errorDescription!==null&&(c.error_description=this.errorDescription),Object.keys(l).length>0&&(c.extra=l),c}}class Fi{constructor(t){S(this,"commitCallback");S(this,"presentMethod","direct_present");S(this,"stats",null);this.commitCallback=t}getOrCreateStats(){return(!this.stats||this.stats.isCommitted())&&(this.stats=new Pi().setCommitCallback(this.commitCallback).setPresentMethod(this.presentMethod)),this.stats}onAuthStart(){this.getOrCreateStats().startTimer(ee.TOTAL_DURATION).startTimer(ee.TOTAL_DURATION_FROM_CACHE).startTimer(ee.AUTH)}onAuthComplete(){var t;(t=this.stats)==null||t.stopTimer(ee.AUTH)}onAuthError(t){this.stats&&!this.stats.isCommitted()&&this.stats.stopTimer(ee.AUTH).setError(t instanceof Q.SendbirdError?t.code:void 0,t.message).stopTimer(ee.TOTAL_DURATION).commit()}onGetChannelStart(){var t;(t=this.stats)==null||t.startTimer(ee.GET_CHANNEL)}onGetChannelComplete(t){this.stats&&(this.stats.stopTimer(ee.GET_CHANNEL),t!==void 0&&this.stats.setConversationId(t),this.stats.startTimer(ee.GET_MESSAGES))}onGetChannelError(t){this.stats&&!this.stats.isCommitted()&&this.stats.stopTimer(ee.GET_CHANNEL).setError(t instanceof Q.SendbirdError?t.code:void 0,t.message).stopTimer(ee.TOTAL_DURATION).commit()}onCacheResult(t){this.stats&&!this.stats.isCommitted()&&(t&&this.stats.setError(t instanceof Q.SendbirdError?t.code:void 0,t.message),this.stats.stopTimer(ee.TOTAL_DURATION_FROM_CACHE))}onApiResult(t){this.stats&&!this.stats.isCommitted()&&(t&&this.stats.setError(t instanceof Q.SendbirdError?t.code:void 0,t.message),this.stats.stopTimer(ee.TOTAL_DURATION).stopTimer(ee.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 Bi(){let e=null,t=0;const n=(r,o)=>{if((e==null?void 0:e.key)===r)return e.promise;const s=++t,l=(e?e.promise.catch(()=>{}).then(()=>o()):o()).finally(()=>{(e==null?void 0:e.id)===s&&(e=null)});return e={key:r,id:s,promise:l},l};return n.isPending=()=>e!==null,n}const $e={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}}},Sr=e=>{var t,n,r,o,s,a,l,c,d,m,h,f,b,C;return e?{...$e,...e,conversation:{...$e.conversation,...e==null?void 0:e.conversation,header:{...(t=$e.conversation)==null?void 0:t.header,...(n=e==null?void 0:e.conversation)==null?void 0:n.header},input:{...(r=$e.conversation)==null?void 0:r.input,...(o=e==null?void 0:e.conversation)==null?void 0:o.input,camera:{...(a=(s=$e.conversation)==null?void 0:s.input)==null?void 0:a.camera,...(c=(l=e==null?void 0:e.conversation)==null?void 0:l.input)==null?void 0:c.camera},gallery:{...(m=(d=$e.conversation)==null?void 0:d.input)==null?void 0:m.gallery,...(f=(h=e==null?void 0:e.conversation)==null?void 0:h.input)==null?void 0:f.gallery}},fileViewer:{...(b=$e.conversation)==null?void 0:b.fileViewer,...(C=e==null?void 0:e.conversation)==null?void 0:C.fileViewer}}}:$e},ge=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===ue.ConversationStatus.CLOSED||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="closed")},Yn=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===ue.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,o;return typeof(((n=e==null?void 0:e.conversation)==null?void 0:n.handedOverAt)??((o=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff)==null?void 0:o.timestamp))=="number"}function Hi(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 Ui(e){var t;if(((t=e==null?void 0:e.resolution)==null?void 0:t.determinedBy)==="user")return e.resolution.isResolved}function xr(e){return!!e&&e<Date.now()}function Vi(e){return!e.title}function zi(e,t){var n;if(e)return Vi(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 Gi{constructor(){S(this,"_channelHandlerId",null);S(this,"_connectionHandlerId",null);S(this,"_handleActiveChannelChangedThrottled",null);S(this,"_setupChannelHandler",()=>{const t=Date.now();this._channelHandlerId=`aiagent_channel_${t}`,this._connectionHandlerId=`aiagent_connection_${t}`,this._handleActiveChannelChangedThrottled=xo(o=>{var s,a;(a=this._session)==null||a._updateActiveChannel({url:o.url,status:ge(o)?"closed":"open",conversationStatus:(s=o.conversation)==null?void 0:s.status}),this._logger.debug("AIAgentEventManager: activeChannel updated",o.url)},250,{leading:!0,trailing:!1});const n=new ct.GroupChannelHandler({onChannelChanged:o=>{var s,a;o.isGroupChannel()&&o.url===((s=this._session)==null?void 0:s.activeChannel.url)&&((a=this._handleActiveChannelChangedThrottled)==null||a.call(this,o))}}),r=new Q.ConnectionHandler({onReconnectSucceeded:async()=>{await this._syncActiveChannelOnReconnect()}});this._chatClient.chatSDK.groupChannel.addGroupChannelHandler(this._channelHandlerId,n),this._chatClient.chatSDK.addConnectionHandler(this._connectionHandlerId,r),this._logger.debug("AIAgentEventManager: handlers registered",{channelHandlerId:this._channelHandlerId,connectionHandlerId:this._connectionHandlerId})});S(this,"_removeChannelHandler",()=>{this._channelHandlerId&&(this._chatClient.chatSDK.groupChannel.removeGroupChannelHandler(this._channelHandlerId),this._channelHandlerId=null),this._connectionHandlerId&&(this._chatClient.chatSDK.removeConnectionHandler(this._connectionHandlerId),this._connectionHandlerId=null),this._handleActiveChannelChangedThrottled&&(this._handleActiveChannelChangedThrottled.cancel(),this._handleActiveChannelChangedThrottled=null),this._logger.debug("AIAgentEventManager: handlers removed")});S(this,"_syncActiveChannelOnReconnect",async()=>{var n,r,o;const t=(n=this._session)==null?void 0:n.activeChannel.url;if(t)try{const a=await(await this._chatClient.chatSDK.groupChannel.getChannel(t)).refresh();a.url===t&&((o=this._session)==null||o._updateActiveChannel({url:a.url,status:ge(a)?"closed":"open",conversationStatus:(r=a.conversation)==null?void 0:r.status}),this._logger.debug("AIAgentEventManager: activeChannel synced on reconnect",a.url))}catch(s){this._logger.error("AIAgentEventManager: failed to sync activeChannel on reconnect",s)}});S(this,"_initConversationIfNeeded",async t=>{if(t.isAIAgent&&!t.conversation)try{await t.initConversation({aiAgentId:this.aiAgentId})}catch(n){this._logger.warn("AIAgentEventManager: initConversation failed",n)}});S(this,"onMessengerSettingsUpdated",t=>(this._dispatcher.subscribe(xe.MessengerSettingsUpdated,t),()=>{this._dispatcher.unsubscribe(xe.MessengerSettingsUpdated,t)}));S(this,"onActiveChannelUpdated",t=>(this._dispatcher.subscribe(xe.ActiveChannelUpdated,t),()=>{this._dispatcher.unsubscribe(xe.ActiveChannelUpdated,t)}));S(this,"onAuthTokenRefreshed",t=>(this._dispatcher.subscribe(xe.AuthTokenRefreshed,t),()=>{this._dispatcher.unsubscribe(xe.AuthTokenRefreshed,t)}))}}class Wi{constructor(t){S(this,"_sdkUser");S(this,"_userSession");S(this,"_dispatcher");S(this,"_activeChannel");S(this,"_updateActiveChannel",t=>{this._activeChannel=t,this._dispatcher.send(Je.ActiveChannelUpdated({channelUrl:t.url,status:t.status,conversationStatus:t.conversationStatus}))});S(this,"_updateAuthToken",t=>{this._userSession.authToken=t,this._dispatcher.send(Je.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 ko=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)}},At=e=>JSON.parse(e),on=e=>JSON.parse(e);function qi(e,t){const[n,r]=t.split(",").map(o=>o.trim());return e==="dark"&&r||n}function Yi(e){const t={};function n(r,o=""){for(const[s,a]of Object.entries(r)){const l=o?`${o}.${s}`:s;a&&typeof a=="object"&&!Array.isArray(a)?n(a,l):t[l]=a}}return n(e),t}function Kn({template:e,variables:t,variableKeyPattern:n,variableValueTransformer:r}){return Object.entries(t).reduce((o,[s,a])=>{if(!r&&!["number","boolean","string"].includes(typeof a))throw new Error(`If transformer is not provided, value(${s}:${a}) must be a {string, number, or boolean}`);const l=r?r(a):String(a),c=n(s);return o.replace(c,ko(l))},e)}async function Ki({template:e,variables:t,variableKeyPattern:n,variableValueTransformer:r}){return(await Promise.all(Object.entries(t).map(async([s,a])=>{const l=await r(a);return{regex:n(s),transformedValue:l}}))).reduce((s,{regex:a,transformedValue:l})=>s.replace(a,ko(l)),e)}var $n=(e=>(e[e.EXTERNAL_AUTH_TOKEN_EXPIRED=1]="EXTERNAL_AUTH_TOKEN_EXPIRED",e))($n||{});const Mo=e=>typeof e=="object"&&e!==null,Ar=(e,t)=>t in e&&typeof e[t]=="string"&&e[t]!=="",ji=e=>!Mo(e)||!Ar(e,"channel_url")||!Ar(e,"ai_agent_id")?null:{channelUrl:e.channel_url,aiAgentId:e.ai_agent_id},Xi={1:ji};function Zi(e){if(!Mo(e)||!("cat"in e)||typeof e.cat!="number"||!("data"in e))return null;const t=e.cat,n=Xi[t];if(!n)return null;const r=n(e.data);return r?{category:t,data:r}:null}function Ji(e,t,n,r){const o=di.default.init({appId:e,modules:[new ct.GroupChannelModule,new ue.AIAgentModule],localCacheEnabled:!0,options:new Q.SendbirdChatOptions({typingIndicatorInvalidateTime:2e4}),...r});return o.addSendbirdExtensions([{version:n,product:Q.SendbirdProduct.AI_AGENT,platform:t.platform}],{platform:t.deviceOSPlatform,version:t.deviceOSVersion},t.customData)||console.warn("Invalid Sendbird Extensions",t),o}function Qi(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 ea=[400300,400301,400302,400310];class jn{constructor(t,n,r){S(this,"chatSDK");S(this,"_logger");S(this,"_cache");S(this,"connect",async(t,n,r,o)=>{if(this._logger.debug("ChatClient.connect: start",t.userId),n){const s=new Q.SessionHandler({...n,onSessionTokenRequired:this._interceptTokenRefresh(n.onSessionTokenRequired,r,o)});this.chatSDK.setSessionHandler(s),this.chatSDK.aiAgent.addEventHandler($n.EXTERNAL_AUTH_TOKEN_EXPIRED.toString(),a=>{var c;this._logger.debug("ChatClient.connect: EXTERNAL_AUTH_TOKEN_EXPIRED event received",a);const l=Zi(a);(l==null?void 0:l.category)===$n.EXTERNAL_AUTH_TOKEN_EXPIRED&&(this._logger.debug("ChatClient.connect: calling onExternalAuthTokenExpired handler",l.data),(c=n==null?void 0:n.onExternalAuthTokenExpired)==null||c.call(n,l.data))})}try{return await this.chatSDK.connect(t.userId,t.authToken),await this._syncTemplatesIfNeeded(),this._logger.debug("ChatClient.connect: end",this.chatSDK.currentUser),this.chatSDK.currentUser}catch(s){const a=s;if(this.chatSDK.isCacheEnabled){if(this._isCacheRestrictedError(a))this._logger.warn("ChatClient.connect","offline connect restricted",a.message,a.code),this._logger.warn("ChatClient.connect","clear cached-data"),await this.chatSDK.clearCachedData().catch(l=>this._logger.warn("ChatClient.connect","clear cached-data failure",l));else if(this.chatSDK.currentUser)return this._logger.debug("ChatClient.connect: end (offline)",this.chatSDK.currentUser),this.chatSDK.currentUser}throw this._logger.warn("ChatClient.connect","connect failure",a.message,a.code),a}});S(this,"disconnect",async()=>{this._logger.debug("ChatClient.disconnect: start"),this.chatSDK.aiAgent.removeAllEventHandlers(),await this.chatSDK.disconnect(),this._cache.template.clear(),this._logger.debug("ChatClient.disconnect: end")});S(this,"getChannel",async t=>this.chatSDK.groupChannel.getChannel(t));S(this,"patchContext",async(t,n,r)=>this.chatSDK.aiAgent.patchContext(t,n,r));S(this,"updateContext",async(t,n,r)=>this.chatSDK.aiAgent.updateContext(t,n,r));S(this,"requestMessengerSettings",async t=>{var o;if(t.userId===""){const s=new Error("userId cannot be empty string for messenger settings request");throw this._logger.error("ChatClient.requestMessengerSettings: invalid userId",s),s}const n={...t,shouldSendFirstMessage:!1};this._logger.debug("ChatClient.requestMessengerSettings: requesting",n);const r=await this.chatSDK.aiAgent.requestMessengerSettings(n);return this._logger.debug("ChatClient.requestMessengerSettings: received",(o=r.active_channel)==null?void 0:o.channel_url),r});S(this,"_interceptTokenRefresh",(t,n,r)=>{if(t)return async(o,s)=>{new Promise((a,l)=>t==null?void 0:t(a,l)).then(a=>{a?n==null||n(a):r==null||r(),o(a)}).catch(a=>{r==null||r(),s(a)})}});S(this,"_isCacheRestrictedError",t=>ea.some(n=>t.code===n));S(this,"_syncTemplatesIfNeeded",async()=>{var r,o;const t=(o=(r=this.chatSDK.appInfo)==null?void 0:r.aiAgentInfo)==null?void 0:o.templateListToken;if(!t)return;const n=this._cache.template.getCachedToken();if(!(n&&n===t)){this._logger.debug("ChatClient._syncTemplatesIfNeeded: syncing templates");try{const{templates:s,token:a}=await this.chatSDK.aiAgent.getMessageTemplates({limit:20});for(const{template:l}of s){const{key:c}=At(l);this._cache.template.set(c,l)}this._cache.template.setCachedToken(a),this._logger.debug("ChatClient._syncTemplatesIfNeeded: sync completed")}catch(s){this._logger.error("ChatClient._syncTemplatesIfNeeded: error",s)}}});this.chatSDK=t,this._logger=n,this._cache=r}static init(t){let n;return t.chatSDK?(Qi(t.chatSDK),n=t.chatSDK):n=Ji(t.appId,t.extensions,t.messengerVersion,t.chatParams),new jn(n,t.logger,t.cache)}}const Rt=new Map,Lo={set:(e,t)=>{Rt.set(e,t)},get:e=>{if(Rt.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=Rt.get(e);if(!n)throw new Error(`AIAgent platform "${e}" is not configured.`);return{platform:e,...n}}const t=Rt.entries().next().value;return{platform:t[0],...t[1]}}},ta=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0));class Tr extends Error{constructor(n,r){const o=(r==null?void 0:r.detail)??"";super(o||`Desk API error (${n})`);S(this,"status");S(this,"code");S(this,"detail");this.name="DeskApiError",this.status=n,this.code=(r==null?void 0:r.code)??"",this.detail=o}}var Xn=(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))(Xn||{}),Zn=(e=>(e.URGENT="URGENT",e.HIGH="HIGH",e.MEDIUM="MEDIUM",e.LOW="LOW",e))(Zn||{}),Oo=(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))(Oo||{});const na=e=>e==="desk401103"||e==="desk401106"||e==="desk401107"||e==="desk401108"||e==="desk401109";class ra{constructor(t){S(this,"_appId");S(this,"_apiHost");S(this,"_logger");S(this,"_credential",null);S(this,"_authRefreshPromise",null);S(this,"_onDeskTokenRefreshRequired",async()=>!1);S(this,"request",async(t,n)=>{const r=n.authRequired??!0,o=`${this._apiHost}${t}`;r&&this._authRefreshPromise&&(this._logger.debug("DeskApiClient: waiting for in-flight recovery..."),await this._authRefreshPromise);const s=await this._fetch(o,n);return r&&s.status===401?this._handleUnauthorized(s,o,n):this._toResult(s)});S(this,"setCredential",(t,n=async()=>!1)=>{this._authRefreshPromise=null,this._onDeskTokenRefreshRequired=n,this._credential=t});S(this,"clearCredential",()=>{this._authRefreshPromise=null,this._credential=null,this._onDeskTokenRefreshRequired=async()=>!1});S(this,"_handleUnauthorized",async(t,n,r)=>{const o=await this._parseErrorCode(t);if(!na(o))return this._toResult(t);if(!await this._refresh(o)||this._credential===null)return this._toResult(t);const a=await this._fetch(n,r);return this._toResult(a)});S(this,"_refresh",async t=>{if(this._authRefreshPromise)return this._logger.debug("DeskApiClient: refresh already in progress, joining..."),this._authRefreshPromise;try{return this._authRefreshPromise=this._onDeskTokenRefreshRequired({reason:t}).catch(n=>(this._logger.error("DeskApiClient: delegated recovery failed",n),!1)),await this._authRefreshPromise}finally{this._authRefreshPromise=null}});S(this,"_fetch",(t,n)=>fetch(`${t}?${this._buildParams(n.params)}`,{method:n.method,headers:this._buildHeaders(n.authRequired??!0,n.headers),...n.body?{body:JSON.stringify(this._buildBody(n.body))}:{}}));S(this,"_buildParams",t=>new URLSearchParams({sendbirdAppId:this._appId,...t}));S(this,"_buildBody",t=>({sendbirdAppId:this._appId,...t}));S(this,"_buildHeaders",(t,n)=>({"content-type":"application/json",...t&&this._credential?{sendbirdDeskToken:this._credential.deskToken}:{},...n}));S(this,"_toResult",async t=>{if(!t.ok){const r=await t.json().catch(()=>({}));throw new Tr(t.status,r)}const n=await t.text();if(n)try{return JSON.parse(n)}catch{throw new Tr(t.status,{})}});S(this,"_parseErrorCode",async t=>{const n=await t.clone().json().catch(()=>({}));return n==null?void 0:n.code});this._appId=t.appId,this._apiHost=t.customApiHost??`https://desk-api-${t.appId}.sendbird.com/sapi`,this._logger=t.logger}get credential(){return this._credential}}class qt{constructor(t,n){S(this,"id");S(this,"title");S(this,"status");S(this,"agent");S(this,"priority");S(this,"group");S(this,"firstResponseTime");S(this,"issuedAt");S(this,"customFields");S(this,"_client");S(this,"refresh",async()=>this._client.getTicket(this.id));this.id=t.id,this.title=t.title,this.status=t.status,this.agent=t.agent,this.priority=t.priority,this.group=t.group,this.firstResponseTime=t.firstResponseTime,this.issuedAt=t.issuedAt,this.customFields=t.customFields,this._client=n}static _fromResponse(t,n){var r;return new qt({id:t.id,title:t.channelName??null,status:t.status2??Xn.INITIALIZED,agent:(()=>{var s;const o=(s=t.recentAssignment)==null?void 0:s.agent;return o?{userId:o.sendbirdId??"",name:o.displayName??"",profileUrl:o.photoThumbnailUrl??""}:null})(),priority:t.priority??Zn.MEDIUM,group:t.group??0,firstResponseTime:t.firstResponseTime??-1,issuedAt:t.issuedAt??null,customFields:Object.fromEntries(((r=t.customFields)==null?void 0:r.map(o=>[o.key,o.value]))??[])},n)}}class Jn{constructor(t){S(this,"_logger");S(this,"_apiClient");S(this,"_onDeskTokenRefreshRequired");S(this,"refreshDeskAuthToken",async t=>this._apiClient.credential?this.authenticate({userId:this._apiClient.credential.userId,accessToken:t,onDeskTokenRefreshRequired:this._onDeskTokenRefreshRequired}):!1);S(this,"authenticate",async t=>{this._logger.debug("DeskClient.authenticate: start",t.userId);try{const{token:n}=await this._apiClient.request("/customers/auth/",{method:"POST",headers:{sendbirdAccessToken:t.accessToken},body:{sendbirdId:t.userId},authRequired:!1});return t.onDeskTokenRefreshRequired!==void 0&&(this._onDeskTokenRefreshRequired=t.onDeskTokenRefreshRequired),this._apiClient.setCredential({userId:t.userId,deskToken:n,chatToken:t.accessToken},this._onDeskTokenRefreshRequired),this._logger.debug("DeskClient.authenticate: end"),!0}catch(n){return this._apiClient.clearCredential(),this._logger.debug("DeskClient.authenticate: failed",n),!1}});S(this,"deauthenticate",()=>{this._apiClient.clearCredential(),this._onDeskTokenRefreshRequired=void 0,this._logger.debug("DeskClient.deauthenticate: token cleared")});S(this,"setCustomerLanguage",async t=>{this._assertAuthenticated(this._apiClient),this._logger.debug("DeskClient.setCustomerLanguage: start",t),await this._apiClient.request("/customers/language/",{method:"PATCH",body:{language:t}}),this._logger.debug("DeskClient.setCustomerLanguage: end")});S(this,"getTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request(`/tickets/${encodeURIComponent(t)}/`,{method:"GET"});return qt._fromResponse(n,this)});S(this,"createTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request("/tickets/",{method:"POST",body:ta({channelName:t.title,channelType:"SENDBIRD_JAVASCRIPT",customFields:t.customFields?JSON.stringify(t.customFields):void 0,info:JSON.stringify({ticket:{subject:t.title,requester:{name:t.name,email:this._apiClient.credential.userId}}}),priority:t.priority,groupKey:t.groupKey})});return qt._fromResponse(n,this)});this._logger=t.logger,this._apiClient=new ra(t)}static init(t){return new Jn(t)}_assertAuthenticated(t){if(t.credential==null)throw new Error("DeskClient is not authenticated")}}function oa(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 sa=1440*60*1e3;function je(e){if(!e)throw new Error("Not authenticated. Call authenticate() first.")}function ia(e,t){return Object.entries(t).every(([n,r])=>e[n]===r)}class Yt extends Gi{constructor(n){super();S(this,"appId");S(this,"aiAgentId");S(this,"_chatClient");S(this,"_deskClient");S(this,"_cache");S(this,"_logger");S(this,"_dispatcher");S(this,"_session",null);S(this,"language");S(this,"countryCode");S(this,"context");S(this,"queryParams");S(this,"_config");S(this,"_networkStateAdapter");S(this,"_forceCreateChannel");S(this,"_agentVersion");S(this,"_statsTrackers");S(this,"_operationQueue",Bi());S(this,"dispose",()=>{this._operationQueue.isPending()||(this._logger.debug("AIAgent.dispose: start"),this._chatClient.chatSDK.connectionState==="OPEN"&&this._chatClient.chatSDK.disconnectWebSocket(),this._removeChannelHandler(),this._session=null,this._deskClient.deauthenticate(),this._statsTrackers.initialRender.clear(),this._logger.debug("AIAgent.dispose: end"))});S(this,"initConversationIfNeeded",n=>this._initConversationIfNeeded(n));S(this,"authenticate",n=>{const r=n&&"userId"in n?`auth:${n.userId}`:"auth:anon";return this._operationQueue(r,async()=>{var a,l,c,d,m;this._logger.debug("AIAgent.authenticate: start"),this._statsTrackers.initialRender.onAuthStart();const o=this._getSessionCandidate(n),s=(a=o.userSessionCandidate)!=null&&a.userId?this._cache.messenger.getSettings(o.userSessionCandidate.userId):null;s!=null&&s.bot&&this._dispatcher.send(Je.MessengerSettingsUpdated({settings:s,source:"cache"}));try{const h=await this._chatClient.requestMessengerSettings({aiAgentId:this.aiAgentId,userId:(l=o.userSessionCandidate)==null?void 0:l.userId,language:this.language,country:this.countryCode,context:this.context,knownActiveChannelUrl:(c=s==null?void 0:s.active_channel)==null?void 0:c.channel_url,forceCreateChannel:this._forceCreateChannel,agentVersion:this._agentVersion});let f;if(h.auto_created_user)if(o.type==="manual")this._logger.warn("Received auto created user info but current session is manual. Ignoring auto created user info."),f={userId:o.userSessionCandidate.userId,authToken:o.userSessionCandidate.authToken};else{const{user_id:v,session_token:_,expire_at:y}=h.auto_created_user;this._cache.messenger.setAnonUser({userId:v,authToken:_,expireAt:y}),f={userId:v,authToken:_},this._logger.debug("AIAgent.authenticate: anonymous user created",v)}else f={userId:((d=o.userSessionCandidate)==null?void 0:d.userId)??"",authToken:((m=o.userSessionCandidate)==null?void 0:m.authToken)??""};this._cache.messenger.setSettings(f.userId,h),this._dispatcher.send(Je.MessengerSettingsUpdated({settings:h,source:"server"}));const b=(()=>{var v;return o.type==="anonymous"?Oi(this._dispatcher):(v=o.userSessionCandidate)==null?void 0:v.sessionHandler})(),C=await this._chatClient.connect(f,b,v=>{var _;this._logger.debug("AIAgent: session token refreshed"),(_=this._session)==null||_._updateAuthToken(v),this._deskClient.refreshDeskAuthToken(v)},()=>{this._logger.debug("AIAgent: session token unavailable, deauthenticating desk"),this._deskClient.deauthenticate()});return await this._deskClient.authenticate({userId:f.userId,accessToken:f.authToken,onDeskTokenRefreshRequired:async({reason:v})=>{var _;if(v===Oo.ERR_SESSION_KEY_EXPIRED){await new Promise(E=>setTimeout(E,2e3));const y=(_=this._session)==null?void 0:_.userSession.authToken;return y?await this._deskClient.refreshDeskAuthToken(y):!1}return!1}}),(s==null?void 0:s.language)!==h.language&&this._deskClient.setCustomerLanguage(this.language).catch(()=>{}),this._statsTrackers.initialRender.onAuthComplete(),this._session=new Wi({sdkUser:C,userSession:f,activeChannel:{url:h.active_channel.channel_url,status:"open"},dispatcher:this._dispatcher}),this._setupChannelHandler(),this._logger.debug("AIAgent.authenticate: end",{userId:f.userId}),h}catch(h){throw this._statsTrackers.initialRender.onAuthError(h),h}})});S(this,"deauthenticate",()=>this._operationQueue("deauth",async()=>{var n;this._logger.debug("AIAgent.deauthenticate: start"),await this._chatClient.disconnect(),this._deskClient.deauthenticate(),this._cache.messenger.clear((n=this._session)==null?void 0:n.userSession.userId),this._session=null,this._removeChannelHandler(),this._statsTrackers.initialRender.clear(),this._logger.debug("AIAgent.deauthenticate: end")}));S(this,"createConversation",async n=>{je(this._session),this._logger.debug("AIAgent.createConversation: start",n);const r=await this._chatClient.requestMessengerSettings({...n,userId:this._session.userSession.userId,knownActiveChannelUrl:void 0,agentVersion:this._agentVersion}),o=r.active_channel.channel_url;return this._cache.messenger.setSettings(this._session.userSession.userId,r),this._logger.debug("AIAgent.createConversation: end",o),o});S(this,"searchConversation",async n=>{if(je(this._session),this._logger.debug("AIAgent.searchConversation: start",n),Object.entries(n.context).length===0)return this._logger.debug("AIAgent.searchConversation: empty context, returning empty array"),[];const r=this.chatSDK.aiAgent.createConversationListQuery({aiAgentId:n.aiAgentId,status:ue.ConversationStatus.OPEN,limit:100}),o=[];for(;r.hasNext;){const s=await r.next();for(const a of s)ia(a.context??{},n.context)&&o.push(a.channelInfo.url)}return this._logger.debug("AIAgent.searchConversation: end",{count:o.length}),o});S(this,"closeConversation",async n=>{var o;je(this._session),this._logger.debug("AIAgent.closeConversation: start",n);const r=await this._chatClient.getChannel(n);((o=r.conversation)==null?void 0:o.status)===ue.ConversationStatus.OPEN?(await r.closeConversation(),this._session.activeChannel.url===n&&this._session._updateActiveChannel({url:n,status:"closed",conversationStatus:ue.ConversationStatus.CLOSED}),this._logger.debug("AIAgent.closeConversation: end")):this._logger.debug("AIAgent.closeConversation: already closed or not an AI agent conversation")});S(this,"createConversationListCollection",n=>new Ao(this.chatSDK,n??{}));S(this,"patchContext",async(n,r)=>{je(this._session),this._logger.debug("AIAgent.patchContext: start",{channelUrl:n,context:r});const o=await this._chatClient.patchContext(this.aiAgentId,n,r);return this._logger.debug("AIAgent.patchContext: end",o),{...o,context:o.context??{}}});S(this,"updateContext",async(n,r)=>{je(this._session),this._logger.debug("AIAgent.updateContext: start",{channelUrl:n,context:r});const o=await this._chatClient.updateContext(this.aiAgentId,n,r);return this._logger.debug("AIAgent.updateContext: end",o),{...o,context:o.context??{}}});S(this,"getContextObject",async n=>{je(this._session),this._logger.debug("AIAgent.getContextObject: start",n);const o=await(await this._chatClient.getChannel(n)).getContextObject(this.aiAgentId);return this._logger.debug("AIAgent.getContextObject: end",o),{...o,context:o.context??{}}});S(this,"refreshActiveChannel",async n=>{var l,c,d;je(this._session);const r=this._session,o=(n==null?void 0:n.useKnownActiveChannelUrl)??!0;this._logger.debug("AIAgent.refreshActiveChannel: start",{useKnownActiveChannelUrl:o});const s=await this._chatClient.requestMessengerSettings({aiAgentId:this.aiAgentId,userId:r.userSession.userId,language:this.language,country:this.countryCode,context:this.context,knownActiveChannelUrl:o?(c=(l=this._cache.messenger.getSettings(r.userSession.userId))==null?void 0:l.active_channel)==null?void 0:c.channel_url:void 0,forceCreateChannel:this._forceCreateChannel,agentVersion:this._agentVersion});if(this._session!==r)return this._logger.debug("AIAgent.refreshActiveChannel: session changed during refresh, discarding stale result"),((d=this._session)==null?void 0:d.activeChannel.url)??s.active_channel.channel_url;const a=s.active_channel.channel_url;return this._cache.messenger.setSettings(this._session.userSession.userId,s),this._session._updateActiveChannel({url:a,status:"open"}),this._logger.debug("AIAgent.refreshActiveChannel: end",a),a});S(this,"_getSessionCandidate",n=>n instanceof wo?{type:"manual",userSessionCandidate:this._getManualSessionInfo(n)}:n instanceof Nn?{type:"anonymous",userSessionCandidate:this._getAnonymousSessionInfo()}:n&&typeof n=="object"?(this._logger.warn("Please use ManualSessionInfo instead of the old userSessionInfo format."),{type:"manual",userSessionCandidate:this._getManualSessionInfo(n)}):n===void 0?(this._logger.warn("Please use AnonymousSessionInfo instead of undefined userSessionInfo."),{type:"anonymous",userSessionCandidate:this._getAnonymousSessionInfo()}):{type:"anonymous",userSessionCandidate:null});S(this,"_getAnonymousSessionInfo",()=>{const n=this._cache.messenger.getAnonUser();return n?n.expireAt-sa<=Date.now()?(this._logger.debug("_getAnonymousSessionInfo: auto session expired, clear cache"),this._cache.messenger.clear(n.userId),null):(this._logger.debug("_getAnonymousSessionInfo: auto session info detected"),{userId:n.userId,authToken:n.authToken}):null});S(this,"_getManualSessionInfo",n=>{if(!n||n instanceof Nn)throw new Error("userSessionInfo must be an instance of ManualSessionInfo");if(typeof n.userId!="string")throw new Error("userSessionInfo.userId must be a string");const r=["userId","authToken","sessionHandler"].filter(o=>!(o in n));return r.length>0&&this._logger.error(`_getManualSessionInfo: missing required keys in userSessionInfo: ${r.join(", ")}`),this._logger.debug("_getManualSessionInfo: manual session info detected"),{userId:n.userId,authToken:n.authToken,sessionHandler:n.sessionHandler}});this.appId=n.appId,this.aiAgentId=n.aiAgentId,this.language=n.language??"en",this.countryCode=n.countryCode,this.context=n.context,this._config=Sr(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 Fi((r,o)=>this._chatClient.chatSDK.aiAgent.appendStat(r,o))}}static init(n){var h;const r=Lo.get(n.platform),o=n.logger??new Io(n.logLevel??qn.WARN),s=n.dispatcher??new To(o),a=n.useMMKVStorage?oa(n.useMMKVStorage):r.keyValueStorage,l=n.useMMKVStorage?{...n.chatParams,useMMKVStorageStore:n.useMMKVStorage}:n.chatParams,c=xi({appId:n.appId,aiAgentId:n.aiAgentId,storage:a}),d=jn.init({appId:n.appId,messengerVersion:r.messengerVersion,extensions:{platform:r.platform,deviceOSPlatform:r.deviceOSPlatform,deviceOSVersion:r.deviceOSVersion},chatParams:l,chatSDK:n.chatSDK,logger:o,cache:c}),m=Jn.init({appId:n.appId,logger:o,customApiHost:(h=n.deskParams)==null?void 0:h.customApiHost});return o.debug("AIAgent.init: created",{appId:n.appId,aiAgentId:n.aiAgentId}),new Yt({appId:n.appId,aiAgentId:n.aiAgentId,language:n.language,countryCode:n.countryCode,context:n.context,config:n.config,queryParams:n.queryParams,networkStateAdapter:r.networkStateAdapter,forceCreateChannel:n._forceCreateChannel,agentVersion:n._agentVersion,chatClient:d,deskClient:m,cache:c,logger:o,dispatcher:s})}get chatSDK(){return this._chatClient.chatSDK}get deskClient(){return this._deskClient}get session(){return this._session}get config(){return this._config}set config(n){this._config=Sr(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 oe=(e,t)=>{const n=u.createContext(t??null),r=({children:a,value:l})=>i.createElement(n.Provider,{value:l},typeof a=="function"?a(l):a),o=({children:a})=>i.createElement(n.Consumer,null,l=>l?typeof a=="function"?a(l):a:null),s=()=>{const a=u.useContext(n);if(!a)throw new Error(`use${e}Context must be used within a ${e}Provider`);return a};return n.displayName=`${e}Context`,r.displayName=`${e}Provider`,o.displayName=`${e}Consumer`,s.displayName=`use${e}Context`,{Context:n,Provider:r,Consumer:o,useContext:s}};function ke(e){const t=u.createContext({Template:e.template,updateTemplate:()=>{},components:e.components,updateComponent:()=>{}});function n({children:s}){const[a,l]=u.useState(()=>e.template),[c,d]=u.useState(e.components),m={Template:a,updateTemplate:h=>l(()=>h),components:c,updateComponent:(h,f)=>d(b=>({...b,[h]:f}))};return i.createElement(t.Provider,{value:m},s)}function r({template:s,children:a}){const{updateTemplate:l}=u.useContext(t);return u.useLayoutEffect(()=>{s&&l(s)},[s]),i.createElement(i.Fragment,null,a)}function o({children:s}){return i.createElement(n,null,s)}return o.defaults=e,o.useContext=()=>u.useContext(t),o.Context=t,o.Template=r,Object.keys(e.components).forEach(s=>{o[s]=function({component:l}){const{updateComponent:c}=u.useContext(t);return u.useLayoutEffect(()=>{l&&c(s,l)},[l]),null}}),o}function aa(...e){return function({children:n}){return e.reduce((r,o)=>i.createElement(o,null,r),n)}}function la(e,t){const n=e.lastMessage;return n!=null&&n.isAdminMessage()?n.message??"":Ro(e,t)}function Ro(e,t){var r;const n=e.lastMessage;if(n!=null&&n.isUserMessage())return n.message||"";if(n!=null&&n.isAdminMessage())return n.message??"";if(n!=null&&n.isFileMessage())return n.message||n.name||"FILE";if(n!=null&&n.isMultipleFilesMessage()){if(n.message)return n.message;const o=n.fileInfoList.length;return((r=t==null?void 0:t.formatMultipleFilesCount)==null?void 0:r.call(t,o))??`${o} photos`}return e.name}function ca(e,t,n){var a;const r=new Date,o=new Date(((a=e.lastMessage)==null?void 0:a.createdAt)||e.createdAt),s=Ze.differenceInMinutes(r,o);return s<1?n.justNow:s<60?n.minutesAgo(s):Ze.isToday(o)?n.hoursAgo(Ze.differenceInHours(r,o)):t(o,n.dateShortFormat)}const ua=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},Nt=e=>Math.max(0,Math.min(255,e)).toString(16).padStart(2,"0"),Ir=(e,t)=>{const n=Nt(Math.round(t*255));if(e.startsWith("#")){const o=e.slice(1);return o.length===3||o.length===4?`#${o[0]}${o[0]}${o[1]}${o[1]}${o[2]}${o[2]}${n}`:`#${o.slice(0,6)}${n}`}const r=ua(e);return r?`#${Nt(r[0])}${Nt(r[1])}${Nt(r[2])}${n}`:e},No=oe("AIAgent"),da=No.Provider,ve=No.useContext;function ma(e){const t=ha(e);return i.createElement(da,{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 ha(e){const t=u.useRef(null),n=u.useRef(null);if(!t.current||!n.current)t.current=Yt.init(e);else{const o=ga(n.current,e);(o.appId||o.aiAgentId||o.chatSDK)&&(t.current.dispose(),t.current=Yt.init({...e,chatParams:o.appId?{...e.chatParams,newInstance:!0}:e.chatParams}))}n.current=e,u.useEffect(()=>()=>{var o;(o=t.current)==null||o.dispose()},[]);const r=t.current;return r.language=e.language??"en",r.countryCode=e.countryCode,r.context=e.context,r.queryParams=e.queryParams,r.config=e.config,r.agentVersion=e._agentVersion,r}function ga(e,t){const n=t.chatSDK!==void 0&&t.chatSDK!==null;return{appId:!n&&e.appId!==t.appId,aiAgentId:e.aiAgentId!==t.aiAgentId,chatSDK:!!e.chatSDK!==n||n&&t.chatSDK!==e.chatSDK}}const wr=Symbol("conversationMessageEventBridge"),gt=Symbol("conversationMessageEventPublisher"),fa=(e,t)=>{const n=e;if(n[gt]=t,n[wr])return e;n[wr]=!0;const r=e.setMessageCollectionHandler.bind(e);e.setMessageCollectionHandler=s=>{r({...s,onMessagesAdded:(a,l,c)=>{var d,m;(d=s.onMessagesAdded)==null||d.call(s,a,l,c),(m=n[gt])==null||m.call(n,{kind:"messagesAdded",source:a.source,messages:c})},onMessagesUpdated:(a,l,c)=>{var d,m;(d=s.onMessagesUpdated)==null||d.call(s,a,l,c),(m=n[gt])==null||m.call(n,{kind:"messagesUpdated",source:a.source,messages:c})}})};const o=e.initialize.bind(e);return e.initialize=s=>{const a=o(s),l=a.onCacheResult.bind(a),c=a.onApiResult.bind(a);return a.onCacheResult=d=>l((m,h)=>{var f;d(m,h),(f=n[gt])==null||f.call(n,{kind:"initialized",source:"cache",messages:h??[]})}),a.onApiResult=d=>c((m,h)=>{var f;d(m,h),(f=n[gt])==null||f.call(n,{kind:"initialized",source:"api",messages:h??[]})}),a},e},pa=(e,t,n)=>{const r=u.useRef(0),o=u.useRef(new Set),s=u.useCallback(d=>{const m={id:r.current+=1,...d};o.current.forEach(h=>{h(m)})},[]),a=u.useCallback(d=>{var h;const m=((h=n==null?void 0:n.collectionCreator)==null?void 0:h.call(n,d))??(t==null?void 0:t.createMessageCollection({...d??{},filter:new ct.MessageFilter(d)}));if(!m)throw new Error("Group channel is required to create a message collection");return fa(m,s)},[t,n==null?void 0:n.collectionCreator,s]),l=He.useGroupChannelMessages(e,t,{...n,collectionCreator:a,strictStreamingOrder:!0}),c=u.useCallback(d=>(o.current.add(d),()=>{o.current.delete(d)}),[]);return{...l,subscribeMessageEvents:c}},yt={DEFAULT_PRIMARY:"#000000",DEFAULT_BOT_MSG_BG:"#ECECEC",WHITE:"#ffffff",BLACK:"#000000"};function $o(e){return e.length===4?`#${[...e.slice(1)].map(t=>t+t).join("")}`:e}function _a(e){const t=$o(e);return[parseInt(t.slice(1,3),16),parseInt(t.slice(3,5),16),parseInt(t.slice(5,7),16)]}function Ea(e){return`#${e.map(t=>t.toString(16).padStart(2,"0")).join("")}`}function ba(e,t,n){e/=255,t/=255,n/=255;const r=Math.max(e,t,n),o=Math.min(e,t,n),s=r-o;let a=0,l=0;const c=(r+o)/2;return r!==o&&(l=c>.5?s/(2-r-o):s/(r+o)),r===e?a=(t-n)/s+(t<n?6:0):r===t?a=(n-e)/s+2:r===n&&(a=(e-t)/s+4),a/=6,[a,l,c]}function Ca(e,t,n){let r,o,s;if(t===0)r=o=s=n;else{const a=function(m,h,f){return f<0&&(f+=1),f>1&&(f-=1),f<.16666666666666666?m+(h-m)*6*f:f<.5?h:f<.6666666666666666?m+(h-m)*(.6666666666666666-f)*6:m},l=n<.5?n*(1+t):n+t-n*t,c=2*n-l;r=a(c,l,e+1/3),o=a(c,l,e),s=a(c,l,e-1/3)}return[Math.round(r*255),Math.round(o*255),Math.round(s*255)]}function $t(e,t,n){const[r,o,s]=_a(e),[a,l,c]=ba(r,o,s),d=Math.max(0,Math.min(1,c*t)),m=Math.max(0,Math.min(1,l*n)),[h,f,b]=Ca(a,m,d);return Ea([Math.round(h),Math.round(f),Math.round(b)])}function va(e,t="light"){return{extraDark:$t(e,.6,1.2),dark:$t(e,.85,1.1),main:e,light:$t(e,t==="dark"?1.1:1.5,t==="dark"?.95:.9),extraLight:$t(e,t==="dark"?1.2:1.75,t==="dark"?.9:.8)}}function Dn(e){const t=$o(e),n=149,r=+`0x${t[1]}${t[2]}`,o=+`0x${t[3]}${t[4]}`,s=+`0x${t[5]}${t[6]}`;return r*.299+o*.587+s*.114>n?yt.BLACK:yt.WHITE}function ya(e,t,n,r,o){return{base:{primary:t,primaryContrastContent:n,background:e.background50,headerBackground:e.background50,modalContentBackground:e.background50},messageInput:{text:e.onlight.textHighEmphasis,placeholderText:e.onlight.textLowEmphasis,background:e.background100},messageIncoming:{text:o,background:r},messageOutgoing:{text:n,background:t},csat:{background:e.background100}}}const Sa=(e,t,n,r,o)=>({base:{primary:t,primaryContrastContent:n,background:e.background600,headerBackground:e.background500,modalContentBackground:e.background500},messageInput:{text:e.ondark.textHighEmphasis,placeholderText:e.ondark.textLowEmphasis,background:e.background400},messageIncoming:{text:o,background:r},messageOutgoing:{text:n,background:t},csat:{background:e.background400}}),Dt={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)"}},bn={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 kr(e){const t=xa(e),n=Aa(e,t),r=Ia(n,e.colors,e.selectedTheme),o=ka(e);return{selectedTheme:e.selectedTheme,palette:t,colors:r,aiAgentColorVariables:{primary_color:r.base.primary,primary_contrast_color:r.base.primaryContrastContent,bot_message_bg_color:r.messageIncoming.background,bot_message_bg_contrast_color:r.messageIncoming.text},typography:o}}function xa({selectedTheme:e,palette:t,primary:n}){const r=t!=null&&t.primary?t.primary:n?n===Dt.primary.main?Dt.primary:va(n,e):Dt.primary;return{...Dt,primary:r,...t}}function Aa({selectedTheme:e,primaryContrast:t,botMessageBackground:n,botMessageBackgroundContrast:r},o){const s=o.primary.main,a=t??Dn(s),l=n??yt.DEFAULT_BOT_MSG_BG,c=r??Dn(l);return(e==="light"?ya:Sa)(o,s,a,l,c)}function Ta(e,t,n){return typeof e=="string"?e:e[t]??n}function Ia(e,t,n){var a;if(!t||Object.keys(t).length===0)return e;const r={...e},o=r,s=e;for(const l of Object.keys(t)){const c=t[l];if(c){o[l]={...o[l]};for(const[d,m]of Object.entries(c))if(m!==void 0){const h=((a=s[l])==null?void 0:a[d])??"";o[l][d]=Ta(m,n,h)}}}return r}function wa(e,t,n){const r={...e};return n.forEach(o=>{const s=t[o];s!=null&&(r[o]=s)}),r}function ka({typography:e}){if(!e)return bn;const t={...bn};return Object.keys(e).forEach(n=>{const r=e[n];if(r&&typeof r=="object"){const o=bn[n],s=["fontSize","fontWeight","fontFamily","lineHeight"];t[n]=wa(o,r,s)}}),t}const{Provider:Ma,useContext:Qn}=oe("AIAgentTheme");function La({logger:e,palette:t,typography:n,colors:r,appearance:o,children:s}){const a=u.useRef(null),[l,c]=u.useState(()=>kr({selectedTheme:(o==null?void 0:o.theme)??"light",palette:t,typography:n,colors:r,primary:o==null?void 0:o.primaryColor,botMessageBackground:o==null?void 0:o.botMessageBackgroundColor})),d=u.useCallback((m,h)=>{h&&(a.current=h);const f=(o==null?void 0:o.theme)??m,b=a.current?a.current.themes[f]:null,C={primary:o==null?void 0:o.primaryColor,primaryContrast:void 0,botMessageBackground:o==null?void 0:o.botMessageBackgroundColor,botMessageBackgroundContrast:void 0};!C.primary&&(b!=null&&b.primary_color)&&(C.primary=b.primary_color,C.primaryContrast=b.primary_contrast_color),!C.botMessageBackground&&(b!=null&&b.bot_message_bg_color)&&(C.botMessageBackground=b.bot_message_bg_color,C.botMessageBackgroundContrast=b.bot_message_bg_contrast_color);const v=kr({selectedTheme:f,palette:t,typography:n,colors:r,...C});c(v),e==null||e.info("theme.update:",f)},[o==null?void 0:o.theme,o==null?void 0:o.primaryColor,o==null?void 0:o.botMessageBackgroundColor,t,n,r,e]);return u.useEffect(()=>{(o!=null&&o.theme||o!=null&&o.primaryColor||o!=null&&o.botMessageBackgroundColor)&&d(l.selectedTheme)},[o==null?void 0:o.theme,o==null?void 0:o.primaryColor,o==null?void 0:o.botMessageBackgroundColor]),i.createElement(Ma,{value:{theme:l,updateTheme:d}},s)}const Cn=25*1024*1024,Mr=1,Lr=new Set(["image/png","image/jpeg","image/jpg"]),Or=new Set(["application/pdf"]),Oa={off:"off",always:"always",handed_off_only:"handed_off_only"},Ra=()=>{const[e,t]=u.useState(()=>({maxAttachmentCount:Mr,attachmentMode:"handed_off_only",defaultUploadSizeLimit:Cn,uploadSizeLimitPerType:new Map,supportedImageMimeTypes:Lr,supportedFileMimeTypes:Or})),n=u.useCallback(({active_channel:o,upload_restriction:s})=>{t({maxAttachmentCount:(s==null?void 0:s.max_attachment_count)??Mr,attachmentMode:Oa[o.attachment_mode]??"handed_off_only",defaultUploadSizeLimit:(s==null?void 0:s.default_upload_size_limit)??Cn,uploadSizeLimitPerType:new Map(Object.entries((s==null?void 0:s.upload_size_limit_per_type)??[])),supportedImageMimeTypes:new Set((s==null?void 0:s.supported_image_mime_types)??Lr),supportedFileMimeTypes:new Set((s==null?void 0:s.supported_file_mime_types)??Or)})},[]),r=u.useCallback(o=>{const{channel:s,uploadSizeLimit:a=Cn}=o,l=(d=!0)=>s!=null&&s.isAIAgent?d?Ue(s):!1:!0,c=d=>{if(l())return e.defaultUploadSizeLimit??a;const m=e.defaultUploadSizeLimit??a,h=e.uploadSizeLimitPerType.get(d)??m;return Math.min(m,h)};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(s);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}},Rr=(...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)")},ft=e=>({...e,context:e.context??{}}),{Provider:Na,useContext:Tt}=oe("AIAgentMessengerSession"),$a=u.forwardRef(function({userSessionInfo:e,children:t},n){const{_aiAgentSDK:r,chatSDK:o,aiAgentId:s,logger:a}=ve(),{updateTheme:l}=Qn(),[c,d]=u.useState(void 0),[m,h]=u.useState(void 0),[f,b]=u.useState(null),[C,v]=u.useState(null),[_,y]=u.useState(null),[E,A]=u.useState(null),{updateBaseAttachmentRules:T,createAttachmentRules:O}=Ra();u.useEffect(()=>{const I=r.onMessengerSettingsUpdated(({settings:F})=>{const{appearance:B,bot:G,launcher:J}=F;l(B.selected_theme,B),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}),A({type:J.image_type||"default_icon",imageUrl:J.image_url}),T(F)}),x=r.onActiveChannelUpdated(({channelUrl:F,status:B,conversationStatus:G})=>{h({url:F,status:B,conversationStatus:G})}),L=r.onAuthTokenRefreshed(()=>{var B;const F=(B=r.session)==null?void 0:B.userSession.authToken;F&&v(G=>G?{...G,authToken:F}:null)});return()=>{I(),x(),L()}},[r,l,T]);const w=u.useCallback(async()=>{d(void 0);try{const I=await r.authenticate(e),x=r.session;return b(x.sdkUser),v(x.userSession),h(x.activeChannel),I}catch(I){throw d(I),I}},[r,e]),N=u.useCallback(async()=>{await r.deauthenticate(),b(null),h(void 0),v(null),y(null),A(null)},[r]),R=u.useCallback(async()=>{if(!r.session){if(C)return a.debug("agentMessengerSession.refreshActiveChannel: stale call after deauthenticate, skipping"),"";throw a.error("agentMessengerSession.refreshActiveChannel: userSession is not ready"),new Error("userSession is not ready")}return r.session.userSession.userId!==(C==null?void 0:C.userId)?(a.debug("agentMessengerSession.refreshActiveChannel: stale call from previous session, skipping"),r.session.activeChannel.url):(h(void 0),await r.refreshActiveChannel())},[r,a,C]),k=u.useCallback(async I=>{if(!r.session)throw new Error("Current user is not authenticated. Please authenticate first.");return r.createConversation(I)},[r]),P=u.useCallback(async I=>{if(!r.session)throw new Error("Current user is not authenticated. Please authenticate first.");return r.searchConversation(I)},[r]);return u.useImperativeHandle(n,()=>{const I=async()=>{if(!m)throw new Error("No active conversation. Please start a conversation first.");return await o.groupChannel.getChannel(m.url)};return{activeChannel:m,chatSDK:o,authenticate:w,deauthenticate:N,updateContext:async(...x)=>{const L=Rr(...x);if(L.type==="active"){const G=await(await I()).updateContext(s,L.context);return ft(G)}const F=await o.aiAgent.updateContext(L.aiAgentId,L.channelUrl,L.context);return ft(F)},patchContext:async(...x)=>{const L=Rr(...x);if(L.type==="active"){const G=await(await I()).patchContext(s,L.context);return ft(G)}const F=await o.aiAgent.patchContext(L.aiAgentId,L.channelUrl,L.context);return ft(F)},getContextObject:async()=>{const L=await(await I()).getContextObject(s);return ft(L)}}},[w,N,m,o,s,a]),i.createElement(Na,{value:{sdkUser:f,userSessionInfo:e,userSession:C,activeChannel:m,setActiveChannel:h,refreshActiveChannel:R,createConversation:k,searchConversation:P,connectionError:c,aiAgentInfo:_,launcherInfo:E,authenticate:w,deauthenticate:N,createAttachmentRules:O,statsTrackers:r.statsTrackers}},t)}),er=(e,t)=>{const n=u.useId(),r=u.useRef(t);u.useLayoutEffect(()=>{r.current=t}),u.useEffect(()=>{const o=new Q.ConnectionHandler({onDisconnected:s=>{var a,l;return(l=(a=r.current).onDisconnected)==null?void 0:l.call(a,s)},onConnected:s=>{var a,l;return(l=(a=r.current).onConnected)==null?void 0:l.call(a,s)},onReconnectStarted:()=>{var s,a;return(a=(s=r.current).onReconnectStarted)==null?void 0:a.call(s)},onReconnectSucceeded:()=>{var s,a;return(a=(s=r.current).onReconnectSucceeded)==null?void 0:a.call(s)},onReconnectFailed:()=>{var s,a;return(a=(s=r.current).onReconnectFailed)==null?void 0:a.call(s)},onConnectionLost:()=>{var s,a;return(a=(s=r.current).onConnectionLost)==null?void 0:a.call(s)},onConnectionDelayed:s=>{var a,l;return(l=(a=r.current).onConnectionDelayed)==null?void 0:l.call(a,s)}});return e.addConnectionHandler(n,o),()=>{e.removeConnectionHandler(n)}},[e,n])};function Da(e){const{chatSDK:t,logger:n,aiAgentId:r,_aiAgentSDK:o}=ve(),{sdkUser:s,statsTrackers:a}=Tt(),l=He.useForceUpdate(),[c,d]=u.useState(void 0),[m,h]=u.useState(void 0),[f,b]=u.useState(!1);function C(_){_.isAIAgent&&!_.conversation&&(b(!0),o.initConversationIfNeeded(_).finally(()=>b(!1)))}async function v(){var _,y,E;if(!s){n.debug("useChannel.getChannel: no sdk user, skip fetching channel");return}if(n.debug("useChannel.getChannel: start"),d(void 0),h(void 0),b(!1),e){a.initialRender.onGetChannelStart();try{n.debug("useChannel.getChannel: get channel",e);const A=await t.groupChannel.getChannel(e);C(A),d(A),a.initialRender.onGetChannelComplete((_=A.conversation)==null?void 0:_.id),A.url===((y=o.session)==null?void 0:y.activeChannel.url)&&o.session._updateActiveChannel({url:A.url,status:ge(A)?"closed":"open",conversationStatus:(E=A.conversation)==null?void 0:E.status}),n.debug("useChannel.getChannel: fetched channel",A)}catch(A){a.initialRender.onGetChannelError(A),A instanceof Q.SendbirdError&&h(A),n.error("useChannel.getChannel: error",A)}}}return u.useEffect(()=>{v()},[t,s,e,r]),er(t,{async onReconnectSucceeded(){if(!c)return;const _=await c.refresh();C(_),d(_)}}),He.useGroupChannelHandler(t,{onChannelChanged:_=>{_.isGroupChannel()&&_.url===e&&(n.debug("useChannel.onChannelChanged: channel changed",_.url),d(_),l())}}),{channel:c,channelFetchError:m,getChannel:v,isInitializingConversation:f}}const Pa=new Set(["suggested_replies","steward","system"]),Fa=e=>{const t=e==null?void 0:e.lastMessage,n=t==null?void 0:t.extendedMessagePayload,r=n==null?void 0:n.user_input_disabled_by;if(!(!r||!Pa.has(r)))return r},Ba=e=>{var a;const t=e==null?void 0:e.lastMessage;if(!t||!e)return!1;const n=t.extendedMessagePayload,r=n==null?void 0:n.form,o=!!r&&!r.submitted_at&&!r.canceled_at,s=e.isAIAgent&&!!((a=e.conversation)!=null&&a.handedOverAt);return o&&!s},Ha=()=>{const{chatSDK:e,networkStateAdapter:t}=ve(),[n,r]=u.useState(()=>t?t.isOnline()?"connected":"reconnecting":"connected");return er(e,{onConnected:()=>r("connected"),onDisconnected:()=>r("disconnected"),onReconnectStarted:()=>r("reconnecting"),onReconnectSucceeded:()=>r("connected"),onReconnectFailed:()=>r("disconnected"),onConnectionLost:()=>r("reconnecting")}),u.useEffect(()=>{if(t)return t.subscribe(o=>{if(!o){r("reconnecting");return}r(s=>s==="reconnecting"&&e.connectionState===Q.ConnectionState.OPEN?"connected":s)})},[t,e]),n},Ua=3e4,Va=({shouldApply:e,lastMessage:t,isBlockedWhileAIResponding:n,currentUserId:r})=>{const[o,s]=u.useState(!1),a=u.useRef(null),l=t&&St(t,r)?t.createdAt:0;return u.useEffect(()=>{const c=()=>{a.current&&(clearTimeout(a.current),a.current=null),s(!1)},d=f=>{a.current&&clearTimeout(a.current),s(!0),a.current=setTimeout(()=>{s(!1),a.current=null},f)},m=Date.now()-l,h=Ua-m;return n||h<=0?c():d(h),()=>{a.current&&clearTimeout(a.current)}},[n,l]),o&&e},Do=e=>{const{chatSDK:t}=ve(),[n,r]=u.useState([]);return He.useGroupChannelHandler(t,{onTypingStatusUpdated(o){if(o.url===(e==null?void 0:e.url)){const s=o.getTypingUsers();r(s)}}}),n},za=({channel:e,lastMessage:t,aiAgentUserId:n,isStreamAnimating:r})=>{const[o,s]=u.useState(!1),a=Do(e);return u.useEffect(()=>{if(!t)return;const l=a.some(d=>d.userId===n),c=St(t,n)&&(Fe.isStreaming(t)||r);s(c||l)},[a,t,n,r]),o},Ga=({channel:e,messages:t,isStreamAnimating:n,isInitializingConversation:r})=>{const{aiAgentInfo:o,userSession:s}=Tt(),a=Ha(),l=za({channel:e,lastMessage:vr(t,[Pe.SendingStatus.SUCCEEDED]),aiAgentUserId:(o==null?void 0:o.userId)??"",isStreamAnimating:n}),c=Va({shouldApply:!!(e!=null&&e.isAIAgent)&&!Ue(e),isBlockedWhileAIResponding:l,lastMessage:vr(t,[Pe.SendingStatus.PENDING,Pe.SendingStatus.SUCCEEDED]),currentUserId:(s==null?void 0:s.userId)??""});if(!e||a==="disconnected")return{disabled:!0,disabledBy:"unavailable"};if(a==="reconnecting")return{disabled:!0,disabledBy:"reconnecting"};if(ge(e))return{disabled:!0,disabledBy:"conversation_closed"};if(Hi(e))return{disabled:!0,disabledBy:"handoff_pending"};if(Ba(e))return{disabled:!0,disabledBy:"form_active"};const d=Fa(e);return d?{disabled:!0,disabledBy:d}:l||c||r?{disabled:!0,disabledBy:"ai_responding"}:{disabled:!1,disabledBy:""}},Wa=()=>{const[e,t]=u.useState(new Set),n=u.useCallback(o=>{t(s=>{if(s.has(o))return s;const a=new Set(s);return a.add(o),a})},[]),r=u.useCallback(o=>{t(s=>{if(!s.has(o))return s;const a=new Set(s);return a.delete(o),a})},[]);return{isAnimating:e.size>0,start:n,stop:r}},{Provider:qa}=oe("AIAgentConversation");function Ya({children:e,channelUrl:t,onChannelDeleted:n,onMessagesReceived:r,onMessagesUpdated:o,onConversationClosedStatusChanged:s,onConversationClosedViaDispatcher:a,onBeforeSendMessage:l,onAfterSendMessage:c=X,shouldMarkAsRead:d=!0,shouldCountNewMessages:m=()=>!1,sortComparator:h}){var P;const f=()=>d&&(_==null?void 0:_.markAsRead()),{chatSDK:b,logger:C,dispatcher:v}=ve(),{channel:_,channelFetchError:y,getChannel:E,isInitializingConversation:A}=Da(t),{statsTrackers:T}=Tt();u.useEffect(()=>{if(t)return T.initialRender.setChannelUrl(t),()=>{T.initialRender.cleanup()}},[t,T]);const O=pa(b,_,{replyType:Pe.ReplyType.ONLY_REPLY_TO_CHANNEL,shouldCountNewMessages:m,onChannelDeleted:n,onMessagesReceived:I=>r==null?void 0:r(I),onMessagesUpdated:I=>o==null?void 0:o(I),onCacheResult:I=>T.initialRender.onCacheResult(I),onApiResult:I=>T.initialRender.onApiResult(I),logger:C,markAsRead:f,sortComparator:h}),w=Wa(),N=Ga({channel:_,messages:O.messages,isStreamAnimating:w.isAnimating,isInitializingConversation:A});u.useEffect(()=>{f()},[d,_]);const R=ge(_);u.useEffect(()=>{s==null||s(R)},[R,s]),u.useEffect(()=>{const I=async x=>{const L=typeof(x==null?void 0:x.channelUrl)=="string";_&&L&&x.channelUrl!==_.url||(C.debug("conversation.dispatcher: try to close conversation",_),_!=null&&_.conversation&&_.conversation.status===ue.ConversationStatus.OPEN&&(await _.closeConversation(),a==null||a()))};return v.subscribe(xe.ConversationClose,I),()=>{v.unsubscribe(xe.ConversationClose,I)}},[v,_,C,(P=_==null?void 0:_.conversation)==null?void 0:P.status,a]);const k={conversation:(_==null?void 0:_.conversation)??void 0,channelSource:{channel:_,error:y,refetch:()=>E(),closeConversation:async()=>{ge(_)||await(_==null?void 0:_.closeConversation())}},messageSource:{messages:O.messages,newMessages:O.newMessages,initialized:O.initialized,subscribeMessageEvents:O.subscribeMessageEvents,loadPrevious:()=>O.loadPrevious(),loadNext:()=>O.loadNext(),deleteMessage:I=>O.deleteMessage(I),resendMessage:I=>O.resendMessage(I),resetNewMessages:()=>O.resetNewMessages(),sendUserMessage:async I=>{var L;if(((L=_==null?void 0:_.conversation)==null?void 0:L.status)===ue.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(I=await l(I));const x=await O.sendUserMessage(I,c);return c==null||c(x),x},sendFileMessage:async I=>{var L;if(((L=_==null?void 0:_.conversation)==null?void 0:L.status)===ue.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(I=await l(I));const x=await O.sendFileMessage(I,c);return c==null||c(x),x},sendMultipleFilesMessage:async I=>{var L;if(((L=_==null?void 0:_.conversation)==null?void 0:L.status)===ue.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(I=await l(I));const x=await O.sendMultipleFilesMessage(I,c);return c==null||c(x),x}},state:{streamAnimation:w,input:N}};return i.createElement(qa,{value:k},e)}function Ka(e,t){var b,C,v,_,y,E,A,T,O,w;const[n,r]=u.useState(!1),[o,s]=u.useState(null),[a,l]=u.useState([]),[c,d]=u.useState(null),m=u.useRef(!1),h=u.useCallback(async()=>{if(!m.current&&e.currentUser){m.current=!0,r(!1),s(null),l([]);try{c==null||c.dispose();const N=new Ao(e,t);N.setConversationListCollectionHandler({onChannelsAdded:()=>{l(N.channels)},onChannelsUpdated:()=>{l(N.channels)},onChannelsDeleted:()=>{l(N.channels)}}),await N.loadMore(),d(N),s(null)}catch(N){d(null),s(N)}finally{r(!0),m.current=!1}}},[e,e.currentUser,(b=t.filter)==null?void 0:b.aiAgentChannelFilter,(v=(C=t.filter)==null?void 0:C.aiAgentConversationStatusFilter)==null?void 0:v.join(),(y=(_=t.filter)==null?void 0:_.aiAgentIds)==null?void 0:y.join(),(E=t.filter)==null?void 0:E.deskChannelFilter,(T=(A=t.filter)==null?void 0:A.pinnedChannelUrls)==null?void 0:T.join(),(O=t.filter)==null?void 0:O.copilotConversationOnly,(w=t.filter)==null?void 0:w.copilotSupportChannelUrl,t.limit]),f=u.useCallback(async()=>{if(c)try{await c.loadMore()}catch(N){s(N)}},[c]);return er(e,{onConnected:()=>h()}),u.useEffect(()=>{h()},[h]),u.useEffect(()=>()=>{m.current=!1,c==null||c.dispose()},[c]),{initialized:n,error:o,channels:a,loadMore:f}}const{Provider:ja}=oe("AIAgentConversationList");function Xa({conversationListLimit:e,conversationListFilter:t,children:n}){var h,f;const{chatSDK:r,aiAgentId:o,queryParams:s}=ve(),a={aiAgentIds:[o],aiAgentConversationStatusFilter:[ue.ConversationStatus.CLOSED,ue.ConversationStatus.OPEN]},l=e??((h=s==null?void 0:s.conversationListParams)==null?void 0:h.limit),c={...a,...(f=s==null?void 0:s.conversationListParams)==null?void 0:f.filter,...t},d=Ka(r,{limit:l,filter:c}),m={listSource:{initialized:d.initialized,error:d.error??void 0,channels:d.channels,loadMore:()=>d.loadMore()}};return i.createElement(ja,{value:m},n)}function Za(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:Ja,useContext:Po}=oe("MessageTemplateFetching");function Qa({children:e,internalVariables:t}){const n=u.useRef({}),r=u.useRef({}),[o,s]=u.useState({}),a=u.useCallback((d,m)=>{s(h=>({...h,[d]:{fetching:!1,error:!1,...h[d],...m}}))},[]),l=u.useCallback(async({onRequestTemplate:d,onGetCachedTemplate:m,templateKey:h,suspense:f=!1})=>{const b=m(h);if(b)return b;const C=r.current[h];if(C)return C;f||a(h,{fetching:!0});const v=d(h).catch(_=>{throw f||a(h,{error:!0}),_}).finally(()=>{f||a(h,{fetching:!1}),delete r.current[h]});return r.current[h]=v,v},[a]),c={internalVariables:t,fetchTemplate:l,suspend:(d,m)=>{if(n.current[d])return n.current[d];const h=Za(m());return n.current[d]=h,h},getIsFetching:d=>{var m;return((m=o[d])==null?void 0:m.fetching)??!1},getHasError:d=>{var m;return((m=o[d])==null?void 0:m.error)??!1}};return i.createElement(Ja,{value:c},e)}const sn={VARIABLE:e=>new RegExp(`\\{${e}\\}`,"g"),VIEW_VARIABLE:e=>new RegExp(`"{@${e}}"`,"g")};function Ve({uiTemplateString:e,variables:t={}}){const n=Yi(t);return Kn({template:e,variables:n,variableKeyPattern:r=>sn.VARIABLE(r)})}function ze({theme:e,uiTemplateString:t,colorVariables:n={}}){return Kn({template:t,variables:n,variableKeyPattern:r=>sn.VARIABLE(r),variableValueTransformer:r=>qi(e,r)})}function el({theme:e,uiTemplateString:t,viewVariables:n={},aiAgentColorVariables:r,internalVariables:o,onRequestTemplate:s}){const l=Object.values(n).flat().map(d=>d.key);return[...new Set(l)].some(d=>!s(d))?null:Kn({template:t,variables:n,variableKeyPattern:d=>sn.VIEW_VARIABLE(d),variableValueTransformer:d=>{const m=d.map(({key:h,variables:f})=>{const b=s(h),{ui_template:C,color_variables:v}=At(b);let _=JSON.stringify(C);return _=Ve({uiTemplateString:_,variables:o}),_=ze({theme:e,uiTemplateString:_,colorVariables:v}),_=ze({theme:e,uiTemplateString:_,colorVariables:r}),_=Ve({uiTemplateString:_,variables:f}),on(_)});return JSON.stringify(m)}})}async function tl({theme:e,uiTemplateString:t,viewVariables:n={},aiAgentColorVariables:r,internalVariables:o,onRequestTemplate:s}){return Ki({template:t,variables:n,variableKeyPattern:a=>sn.VIEW_VARIABLE(a),variableValueTransformer:async a=>{const l=a.map(async({key:d,variables:m})=>{const h=await s(d),{ui_template:f,color_variables:b}=At(h);let C=JSON.stringify(f);return C=Ve({uiTemplateString:C,variables:o}),C=ze({theme:e,uiTemplateString:C,colorVariables:b}),C=ze({theme:e,uiTemplateString:C,colorVariables:r}),C=Ve({uiTemplateString:C,variables:m}),on(C)}),c=await Promise.all(l);return JSON.stringify(c)}})}const nl=({rawTemplate:e,aiAgentColorVariables:t,internalVariables:n,...r})=>{const{ui_template:o,color_variables:s}=At(e);let a=JSON.stringify(o);if(Object.keys(r.viewVariables??{}).length>0){const c=el({...r,uiTemplateString:a,aiAgentColorVariables:t,internalVariables:n});if(c===null)return null;a=c}return a=Ve({...r,uiTemplateString:a,variables:n}),a=ze({...r,uiTemplateString:a,colorVariables:s}),a=ze({...r,uiTemplateString:a,colorVariables:t}),a=Ve({...r,uiTemplateString:a}),on(a)},rl=async({rawTemplate:e,aiAgentColorVariables:t,internalVariables:n,...r})=>{const{ui_template:o,color_variables:s}=At(e);let a=JSON.stringify(o);return Object.keys(r.viewVariables??{}).length>0&&(a=await tl({...r,uiTemplateString:a,aiAgentColorVariables:t,internalVariables:n})),a=Ve({...r,uiTemplateString:a,variables:n}),a=ze({...r,uiTemplateString:a,colorVariables:s}),a=ze({...r,uiTemplateString:a,colorVariables:t}),a=Ve({...r,uiTemplateString:a}),on(a)},ol=e=>{const{aiAgentColorVariables:t={}}=e,{internalVariables:n}=Po();return u.useState(()=>{const r=e.onGetCachedTemplate(e.templateKey);return r?nl({...e,rawTemplate:r,aiAgentColorVariables:t,internalVariables:n,onRequestTemplate:e.onGetCachedTemplate}):null})},sl=e=>{const[t]=ol(e);if(t)return t;const{aiAgentColorVariables:n={}}=e,{internalVariables:r,fetchTemplate:o,suspend:s}=Po();return s(e.templateKey,async()=>{const l=await o({...e,suspense:!0});return await rl({...e,rawTemplate:l,aiAgentColorVariables:n,internalVariables:r})}).value},il="remove_powered_by",tr=(e,t)=>{var o,s;const{chatSDK:n}=ve(),{aiAgentInfo:r}=Tt();if(e==="handoff-button"){const a=!!((o=t==null?void 0:t.conversation)!=null&&o.handoff);return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.showHandoffButton)&&a&&Yn(t)}if(e==="special-notice")return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.specialNoticeEnabled)&&!!(r!=null&&r.specialNotice);if(e==="powered-by"){const a=(s=n==null?void 0:n.appInfo)==null?void 0:s.applicationAttributes;return u.useMemo(()=>!(Array.isArray(a)&&a.includes(il)),[a])}throw new Error("Unsupported feature")},al={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"},ll={getValueOrDefault:e=>e.value??e.default_value??null,validate:(e,t,n)=>{const r=t;if(e.required&&(!r||r.trim()===""))return{isValid:!1,error:n.required};if(!r)return{isValid:!0};const{rules:o}=e;if(o){if(o.min_length!==void 0&&r.length<o.min_length)return{isValid:!1,error:typeof n.minLength=="function"?n.minLength(o.min_length):n.minLength};if(o.max_length!==void 0&&r.length>o.max_length)return{isValid:!1,error:typeof n.maxLength=="function"?n.maxLength(o.max_length):n.maxLength};if(o.regex&&!new RegExp(o.regex).test(r))return{isValid:!1,error:n.regex}}return{isValid:!0}}},cl={getValueOrDefault:e=>e.value??e.default_value??null,validate:(e,t,n)=>{const r=t;if(e.required&&r===null)return{isValid:!1,error:n.required};if(r===null)return{isValid:!0};const{rules:o}=e;if(o){if(o.min!==void 0&&r<o.min)return{isValid:!1,error:typeof n.min=="function"?n.min(o.min):n.min};if(o.max!==void 0&&r>o.max)return{isValid:!1,error:typeof n.max=="function"?n.max(o.max):n.max}}return{isValid:!0}}},ul={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}}},dl={getValueOrDefault:e=>e.values??e.default_values??null,validate:(e,t,n)=>{const r=t;if(e.required&&(!r||r.length===0))return{isValid:!1,error:n.required};if(!r||r.length===0)return{isValid:!0};if(r.filter(a=>!e.options.includes(a)).length>0)return{isValid:!1,error:n.invalidSelection};const{rules:s}=e;if(s){if(s.min_select!==void 0&&r.length<s.min_select)return{isValid:!1,error:typeof n.minSelect=="function"?n.minSelect(s.min_select):n.minSelect};if(s.max_select!==void 0&&r.length>s.max_select)return{isValid:!1,error:typeof n.maxSelect=="function"?n.maxSelect(s.max_select):n.maxSelect}}return{isValid:!0}}},ml={text:ll,number:cl,"single-select":ul,"multi-select":dl},hl={getValueOrDefault:()=>null,validate:()=>({isValid:!1})};function Fo(e){return ml[e.type]||hl}function Nr(e){return Fo(e).getValueOrDefault(e)}function gl(e,t,n={}){const r={...al,...n};return Fo(e).validate(e,t,r)}const fl=(e,t={})=>{const{labels:n={},onSubmit:r,onCancel:o}=t,[s,a]=u.useState({}),[l,c]=u.useState(()=>{const v={};return e.fields.forEach(_=>{v[_.key]=Nr(_)}),v}),d=u.useMemo(()=>e.submitted_at?"submitted":e.canceled_at?"canceled":"draft",[e.submitted_at,e.canceled_at]);u.useEffect(()=>{if(d==="submitted"||d==="canceled"){const v={};let _=!1;e.fields.forEach(y=>{const E=Nr(y);JSON.stringify(l[y.key])!==JSON.stringify(E)&&(_=!0),v[y.key]=E}),_&&c(v)}},[d]);const m=(v,_)=>{c(y=>({...y,[v]:_})),a(y=>({...y,[v]:void 0}))},h=e.fields.map(v=>{var E,A,T;const _=l[v.key]??null,y={key:v.key,label:v.label,error:s[v.key],required:v.required};return v.type==="text"?{...y,type:"text",layout:v.layout,value:_,...v.placeholder&&{placeholder:v.placeholder},...((E=v.rules)==null?void 0:E.max_length)&&{maxLength:v.rules.max_length}}:v.type==="number"?{...y,type:"number",layout:v.layout,value:_,...v.placeholder&&{placeholder:v.placeholder},...((A=v.rules)==null?void 0:A.max)&&{max:v.rules.max}}:v.type==="single-select"?{...y,type:"single-select",layout:v.layout,value:_,options:v.options}:v.type==="multi-select"?{...y,type:"multi-select",layout:v.layout,value:_,options:v.options,...((T=v.rules)==null?void 0:T.max_select)&&{maxSelect:v.rules.max_select}}:{...y,type:"unknown",layout:"default",value:null}});return{state:d,fields:h,getField:v=>h.find(_=>_.key===v),updateFieldValue:m,submit:async()=>{const v={};let _=!1;for(const y of e.fields){const E=l[y.key]??null,A=gl(y,E,n);A.isValid||(v[y.key]=A.error,_=!0)}if(a(v),!_&&r){const y={};e.fields.forEach(E=>{y[E.key]=l[E.key]??null}),await r(y)}},cancel:async()=>{await(o==null?void 0:o())}}},pl=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},Bo=e=>{const{aiAgentInfo:t}=Tt(),r=Do(e)[0];if(!r)return null;const o=r.userId===(t==null?void 0:t.userId),s=o?pl(r.metaData):void 0;return{user:o?t:r,isBot:o,thinkingMessage:s}},_l=(e,t,{enabled:n=!0,idleMs:r=1e3}={})=>{const o=u.useRef(null),s=u.useRef(t),a=u.useRef(t),l=u.useRef(!1);s.current=t,u.useEffect(()=>{if(o.current&&(clearTimeout(o.current),o.current=null),!n||!e){(l.current?a.current:s.current)(!1),l.current=!1,a.current=s.current;return}l.current=!0,a.current=s.current,a.current(!0),o.current=setTimeout(()=>{o.current=null,a.current(!1),l.current=!1,a.current=s.current},r)},[n,r,e]),u.useEffect(()=>()=>{o.current&&(clearTimeout(o.current),o.current=null),(l.current?a.current:s.current)(!1),l.current=!1,a.current=s.current},[])},El=(e=1e4)=>{const t=new Map;let n=e;return{shouldAnnounce:l=>{const c=Date.now(),d=t.get(l);return d!==void 0&&c-d<n?!1:(t.set(l,c),!0)},setInterval:l=>{n=l},reset:()=>{t.clear()}}},bl=(e,t,n=1e4,r=!0)=>{const o=u.useRef(null),s=u.useRef(null),a=u.useRef(!1);o.current||(o.current=El(n));const l=(e==null?void 0:e.nickname.trim())||null,c=(e==null?void 0:e.userId)??l;u.useEffect(()=>{var d;(d=o.current)==null||d.setInterval(n)},[n]),u.useEffect(()=>{var h;if(!r){a.current=!1,s.current=c;return}if(!c||!l){a.current=!1,s.current=null;return}const d=!a.current,m=s.current!==c;a.current=!0,s.current=c,!(!d&&!m)&&(h=o.current)!=null&&h.shouldAnnounce(c)&&t(l)},[c,l,r,t])},nr=({channel:e,userSession:t,aiAgentInfo:n})=>{if(!t||!n||!e)return{fallbackIcon:"delight",url:void 0,title:""};const r=(()=>{const[s]=e.members.filter(a=>a.userId!==t.userId);return s})(),o={ai(s){return{fallbackIcon:s,url:n.profileUrl,title:n.nickname}},human(s){return{fallbackIcon:s,url:r==null?void 0:r.profileUrl,title:(r==null?void 0:r.nickname)||n.nickname}},channel(s){return{fallbackIcon:s,url:e==null?void 0:e.coverUrl,title:(e==null?void 0:e.name)??""}}};return e.isAIAgent?Ue(e)?o.human("agent"):o.ai("delight"):e.isDesk?o.human("agent"):o.channel("user")},$r=e=>u.useReducer((t,n)=>({...t,...n}),e);var Ie=(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))(Ie||{});const Cl=new Set(["free_text","single_choice"]),vl=({csatPayload:e,type:t,initialCsat:n,initialCsatReason:r,initialIsResolved:o})=>{const[s,a]=$r({csatType:t,csat:n,csatReason:r,isResolved:o}),[l,c]=$r({followUpItem:!1}),d=u.useMemo(()=>{var _;const b=s.csat,C=typeof b=="number",v=(_=e.follow_up)==null?void 0:_.find(y=>C?y.scores.includes(b):y.always_visible??!1);if(Cl.has(v==null?void 0:v.response_type))return v},[s.csat,e.follow_up]),m=(()=>{var b;if(typeof n=="number")return"submitted";if((t===Ie.AI_AGENT_CSAT_5||t===Ie.HELPDESK_CSAT_5)&&typeof s.csat=="number")return"submittable";if(t===Ie.AI_AGENT_CSAT_5_WITH_CRE){const C=typeof s.csat=="number",v=!((b=e.cre)!=null&&b.required)||typeof s.isResolved=="boolean";if(C&&v)return"submittable"}return"unsubmittable"})(),h=u.useCallback(()=>typeof s.csat>"u"?!1:d!=null&&d.required&&!s.csatReason?(c({followUpItem:!0}),!1):!0,[s,d,c]);return u.useEffect(()=>{r||(a({csatReason:""}),c({followUpItem:!1}))},[r,d,a,c]),{params:s,setParams:a,error:l,setError:c,followUpItem:d,state:m,validateParams:h,itemProps:{csatPayload:e,state:m,submitted:m==="submitted"}}},vn=5,yl=250,Sl=50,Dr=e=>Math.max(0,e-Sl),xl=e=>e<1e3?{speed:vn*.5,chunkSize:2}:e<2e3?{speed:vn*.8,chunkSize:2}:{speed:vn*.6,chunkSize:3},Al=e=>{const{text:t,enabled:n=!1,onAnimationStart:r,onAnimationProgress:o,onAnimationComplete:s}=e,[a,l]=u.useState(()=>Dr(t.length)),c=u.useRef(null),d=u.useRef({startTime:0,lastUpdate:0,lastProgressCall:0}).current,m=u.useRef({onStart:r,onProgress:o,onComplete:s}).current,h=u.useRef({startCalled:!1,completeCalled:!1}).current,f=u.useRef({initialEnabled:n,textLength:t.length,enabled:n}).current,b=n,C=a<t.length,v=f.initialEnabled&&(b||C);return u.useLayoutEffect(()=>{m.onStart=r,m.onProgress=o,m.onComplete=s,f.textLength=t.length,f.enabled=n}),u.useLayoutEffect(()=>{var _;f.initialEnabled&&(h.startCalled||(h.startCalled=!0,(_=m.onStart)==null||_.call(m)),l(y=>t.length<y?t.length:y))},[t]),u.useEffect(()=>{if(!f.initialEnabled)return;let _=Dr(t.length);d.lastUpdate=0,d.startTime=0,d.lastProgressCall=0;const y=E=>{var P;d.lastUpdate===0&&(d.lastUpdate=E,d.startTime=E,d.lastProgressCall=E);const A=f.textLength,T=E-d.lastUpdate,O=E-d.startTime,{speed:w,chunkSize:N}=xl(O),R=w*N;T>=R&&_<A&&(_=Math.min(_+N,A),l(_),d.lastUpdate=E),E-d.lastProgressCall>=yl&&(d.lastProgressCall=E,(P=m.onProgress)==null||P.call(m)),(_<A||f.enabled)&&(c.current=requestAnimationFrame(y))};return c.current=requestAnimationFrame(y),()=>{var E;c.current&&cancelAnimationFrame(c.current),h.startCalled&&!h.completeCalled&&(h.completeCalled=!0,(E=m.onComplete)==null||E.call(m))}},[]),u.useEffect(()=>{var A;const _=f.initialEnabled&&h.startCalled,y=!n,E=a>=t.length&&t.length>0;_&&y&&E&&!h.completeCalled&&(h.completeCalled=!0,(A=m.onComplete)==null||A.call(m))},[n,a,t.length]),{streamText:f.initialEnabled?t.slice(0,a):t,isAnimating:v}},Ho=e=>e.replace(/\s+/g," ").trim(),Tl="Code block",Uo=e=>`A11Y_INLINE_CODE_${e}`,Vo=e=>{let t="",n=e;for(;;){const r=n.match(/^([ \t]{0,3}>\s?)(.*)$/);if(r){t+=r[1],n=r[2];continue}break}return{blockquotePrefix:t,content:n}},zo=e=>{const t=e.match(/^([ \t]{0,3}[-+*]\s+)(.*)$/);if(t)return{content:t[2],hasListPrefix:!0};const n=e.match(/^([ \t]{0,3}\d+[.)]\s+)(.*)$/);return n?{content:n[2],hasListPrefix:!0}:{content:e,hasListPrefix:!1}},Il=e=>{const{blockquotePrefix:t,content:n}=Vo(e),{content:r}=zo(n),o=r.match(/^[ \t]{0,3}([`~]{3,})(.*)$/);if(!o)return;const s=o[1],a=o[2],l=s[0];if(!(l!=="`"&&l!=="~"||!s.split("").every(c=>c===l))&&!(l==="`"&&a.includes("`")))return{char:l,blockquotePrefix:t,length:s.length}},wl=(e,t)=>{const{blockquotePrefix:n,content:r}=Vo(e);if(n!==t.blockquotePrefix)return!1;const{content:o,hasListPrefix:s}=zo(r);if(s)return!1;const a=o.match(/^[ \t]{0,3}([`~]{3,})[ \t]*$/);if(!a)return!1;const l=a[1];return l[0]===t.char&&l.length>=t.length&&l.split("").every(c=>c===t.char)},kl=(e,t,n)=>{let r=n;for(;r<e.length;){const o=e[r];if(o==="\\"&&r+1<e.length){r+=2;continue}if(o===t)return r;r+=1}return-1},Ml=(e,t)=>{let n=1,r=t;for(;r<e.length;){const o=e[r];if(o==="\\"&&r+1<e.length){r+=2;continue}if(o==="["){n+=1,r+=1;continue}if(o==="]"&&(n-=1,n===0))return r;r+=1}return-1},Ll=(e,t)=>{let n=t,r=1,o,s=!1,a=!1;for(;n<e.length&&r>0;){const l=e[n];if(l==="\\"&&n+1<e.length){n+=2;continue}if(o){l===o&&(o=void 0),n+=1;continue}if(r===1&&s&&/\s/.test(l)){a=!0,n+=1;continue}if(r===1&&a&&(l==='"'||l==="'")){o=l,n+=1;continue}if(l==="("){r+=1,s=!0,n+=1;continue}if(l===")"){r-=1,n+=1;continue}/\s/.test(l)||(s=!0),n+=1}return r===0?n:-1},Ol=e=>{let t=0,n="";for(;t<e.length;){const r=kl(e,"[",t);if(r===-1){n+=e.slice(t);break}const o=Ml(e,r+1);if(o===-1){n+=e.slice(t);break}if(r>0&&e[r-1]==="!"&&Kt(e,r-1)){n+=e.slice(t,o+1),t=o+1;continue}if(e[o+1]!=="("){n+=e.slice(t,o+1),t=o+1;continue}const s=r>0&&e[r-1]==="!"&&!Kt(e,r-1)?r-1:r;n+=e.slice(t,s);const a=e.slice(r+1,o),l=Ll(e,o+2);if(l===-1){n+=e.slice(s);break}n+=a,t=l}return n},Go=(e,t,n)=>{if(!/^\d+$/.test(t))return!1;const r=e.slice(-1);return/\d/.test(r)&&/\d/.test(n)},Rl=e=>e.replace(/(^|[^*\\])\*\*([^\s*](?:[\s\S]*?[^\s*])?)\*\*(?!\*)/g,(t,n,r,o,s)=>{const a=s[o+t.length]??"";return Go(n,r,a)?t:`${n}${r}`}),Nl=e=>e.replace(/(^|[^_\\])__([^\s_](?:[\s\S]*?[^\s_])?)__(?!_)/g,"$1$2"),$l=e=>e.replace(/(^|[^~\\])~~([^\s~](?:[\s\S]*?[^\s~])?)~~(?!~)/g,"$1$2"),Dl=e=>{let t=e;return t=t.replace(/(^|[^*\\])\*([^\s*](?:[\s\S]*?[^\s*])?)\*(?!\*)/g,(n,r,o,s,a)=>{const l=a[s+n.length]??"";return Go(r,o,l)?n:`${r}${o}`}),t=t.replace(/(^|[\s([{"'])_([^_\s](?:[\s\S]*?[^_\s])?)_(?=$|[\s)\]}"'.,!?:;])/g,"$1$2"),t},Pl=e=>e.replace(/\\([\\`*_[\]()#+.!~|-])/g,"$1"),Fl=e=>{let t=e;return t=t.replace(/^\s{0,3}#{1,6}\s+/gm,""),t=t.replace(/^\s{0,3}>\s?/gm,""),t=t.replace(/^\s{0,3}(?!([-*_])(?:\s*\1){2,}\s*$)[-*+]\s+/gm,""),t=t.replace(/^\s{0,3}\d+[.)]\s+/gm,""),t},Pr=e=>{const t=e.trim();if(!t.includes("|"))return!1;const n=t.split("|").map(r=>r.trim()).filter(Boolean);return n.length===0?!1:n.every(r=>/^:?-{3,}:?$/.test(r))},Fr=e=>{const t=[];let n="",r=!1;for(const s of e.trim()){if(r){n+=s==="|"?"|":`\\${s}`,r=!1;continue}if(s==="\\"){r=!0;continue}if(s==="|"){const a=n.trim();a&&t.push(a),n="";continue}n+=s}r&&(n+="\\");const o=n.trim();return o&&t.push(o),t},Bl=e=>{const t=e.split(`
|
|
2
|
+
`),n=[];let r=0;for(;r<t.length;){const o=t[r],s=t[r+1],a=Fr(o);if(a.length>0&&s&&Pr(s)){for(n.push(a.join(" ")),r+=2;r<t.length;){const l=t[r],c=Fr(l);if(c.length===0||Pr(l))break;n.push(c.join(" ")),r+=1}continue}n.push(o),r+=1}return n.join(`
|
|
3
|
+
`)},Hl=e=>e.replace(/^\s{0,3}(?:(?:-\s*){3,}|(?:\*\s*){3,}|(?:_\s*){3,})$/gm,""),Ul=(e,t)=>{const n=e.split(`
|
|
4
|
+
`),r=[];let o=0;for(;o<n.length;){const s=n[o],a=Il(s);if(!a){r.push(s),o+=1;continue}let l=-1;for(let c=o+1;c<n.length;c++)if(wl(n[c],a)){l=c;break}if(l===-1){r.push(s),o+=1;continue}r.push(` ${t} `),o=l+1}return r.join(`
|
|
5
|
+
`)},Kt=(e,t)=>{let n=0,r=t-1;for(;r>=0&&e[r]==="\\";)n+=1,r-=1;return n%2===1},Vl=e=>{const t=[];let n=0,r="";for(;n<e.length;){const o=e[n];if(o!=="`"||Kt(e,n)){r+=o,n+=1;continue}let s=n;for(;s<e.length&&e[s]==="`";)s+=1;const a=e.slice(n,s);let l=s,c=!1;for(;l<e.length&&e[l]!==`
|
|
6
|
+
`;){if(e[l]==="`"&&!Kt(e,l)&&e.startsWith(a,l)){const d=e.slice(s,l),m=t.push(d)-1;r+=Uo(m),n=l+a.length,c=!0;break}l+=1}c||(r+=a,n=s)}return{text:r,inlineCodes:t}},zl=(e,{codeBlockPlaceholder:t=Tl}={})=>{const n=e==null?void 0:e.replace(/\r\n?/g,`
|
|
7
|
+
`);if(!n)return;const r=[];let o=n;o=Ul(o,t),o=Fl(o);const s=Vl(o);o=s.text,r.push(...s.inlineCodes),o=Ol(o),o=Rl(o),o=Nl(o),o=$l(o),o=Dl(o),o=Bl(o),o=Hl(o),o=Pl(o);for(let l=0;l<r.length;l++)o=o.replaceAll(Uo(l),r[l]);return Ho(o)||void 0},jt=e=>(e==null?void 0:e.trim())||"",Gl=e=>(e?Ho(e):void 0)||void 0,Wo=e=>({text:jt(e),format:"plain"}),Wl=e=>({text:jt(e),format:"markdown"}),yn=({markdownText:e,plainText:t,comparisonText:n})=>{const r=jt(e);return r&&r!==jt(n)?Wl(r):Wo(t)},Et=({sender:e,message:t,messageFormat:n="plain",time:r,codeBlockPlaceholder:o})=>{const s=[],a=n==="markdown"?zl(t,{codeBlockPlaceholder:o}):Gl(t);if(e&&s.push(e),a&&s.push(a),r&&s.push(r),s.length!==0)return s.join(", ")},ql=(e,t={})=>{const{throttleMs:n=1e3,isSuppressed:r}=t;let o=null;const s=[];let a=null,l=null,c=!1,d=0;const m=(T,O)=>({text:T,ignoreSuppression:O,queueOrder:d++}),h=()=>{const T=s[0]??null,O=o;return T&&O?O.queueOrder<T.queueOrder?(o=null,O):s.shift()??null:T?s.shift()??null:O!==null?(o=null,O):null},f=()=>{for(;;){const T=h();if(!T)return null;if(!(!T.ignoreSuppression&&(r!=null&&r())))return T}},b=T=>{a=T,c=!0,e(T),l=setTimeout(()=>{l=null,c=!1;const O=f();O&&b(O.text)},n)},C=T=>{a=T,e(T)},v=(T,O,w)=>{if(T&&!(!O&&(r!=null&&r()))&&!(T===a&&c))if(c){if(((w==null?void 0:w.mode)??"latestOnly")==="ordered"){const R=s[s.length-1];if((R==null?void 0:R.text)===T)return;s.push(m(T,O));return}o=m(T,O)}else o=null,b(T)};return{announce:(T,O)=>{v(T,!1,O)},announceIgnoringSuppression:(T,O)=>{v(T,!0,O)},flush:()=>{const T=[];let O=h();for(;O!==null;)T.push(O),O=h();if(T.length!==0){l!==null&&(clearTimeout(l),l=null),c=!1;for(const w of T)C(w.text)}},destroy:()=>{l!==null&&(clearTimeout(l),l=null),o=null,s.length=0,a=null,c=!1}}},Yl=e=>{switch(e){case"conversationClosed":case"csatDisplayed":return"ordered";default:return"latestOnly"}},Kl=(e,t)=>e.screen==="conversationList"?t.screenConversationListNoCount:[e.agentName?t.screenConversationWithAgent(e.agentName):t.screenConversation,e.isClosed?t.conversationClosed:null,e.isClosed&&e.hasCSAT?t.csatDisplayed:null,e.isEmpty?t.emptyState:null].filter(r=>!!r).join(". "),jl=(e,t)=>{switch(e.event){case"newMessage":return e.senderName?t.newMessageFromSender(e.senderName,1):t.newMessage(1);case"typing":return t.typing(e.agentName??"");case"sendFailed":return t.sendFailed;case"agentConnected":return t.agentConnected(e.agentName??"");case"conversationClosed":return t.conversationClosed;case"csatDisplayed":return t.csatDisplayed;case"emptyState":return t.emptyState;case"inputDisabled":return t.inputDisabled}},Xl=(e,t)=>{switch(e.type){case"fileSizeExceeded":return t.fileSizeExceeded(e.maxSizeMB??25);case"sendFailed":return t.sendFailed;case"csatFormError":return t.csatFormError;case"generic":return e.message}},Zl=(e,t)=>!t||!Ae(e)||e.sender.userId!==t?null:e.reqId||(e.messageId>0?String(e.messageId):null),Br=(e,t)=>te.isAdmin(e)?te.isCSAT(e):"sender"in e?e.sender.userId!==t:!1,qo=e=>"messageId"in e&&e.messageId>0?String(e.messageId):"reqId"in e&&typeof e.reqId=="string"&&e.reqId.length>0?e.reqId:null,Jl=e=>e===Q.CollectionEventSource.EVENT_MESSAGE_RECEIVED||e===Q.CollectionEventSource.EVENT_MESSAGE_UPDATED,Hr=(e,t,n,r)=>{const{newestFirst:o=!1}={};if(o){for(const s of e)if(s&&Br(s,n)&&t.some(a=>Cr(s,a)))return s;return}for(let s=e.length-1;s>=0;s-=1){const a=e[s];if(a&&Br(a,n)&&t.some(l=>Cr(a,l)))return a}},Ql=({isOpened:e,opensConversationList:t})=>e?t?"closeConversationList":"closeConversation":t?"openConversationList":"openConversation",ec=(e,t)=>{switch(e){case"closeConversationList":return t.closeConversationList;case"closeConversation":return t.closeConversation;case"openConversationList":return t.openConversationList;case"openConversation":return t.openConversation}},tc=(e,t)=>{switch(e){case"closeConversation":return t.hintCloseConversation;case"openConversationList":return t.hintOpenConversationList;case"openConversation":return t.hintOpenConversation;default:return}},nc=({intent:e,strings:t})=>({label:ec(e,t),hint:tc(e,t)}),rc="1.22.0",Ce="sb-agent",ne={ENTRY:`${Ce}-entry`,MODAL_ROOT:`${Ce}-modal-root`,WINDOW:`${Ce}-window`,LAUNCHER:`${Ce}-launcher`},Pt=2147483647,et={MODAL:Pt-1,TOOLTIP:Pt-2,WINDOW:Pt-3,LAUNCHER:Pt-4},Yo=36,oc=100,sc=rc,rr="noopener noreferrer nofollow";function ic(){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 Ft={};function ac(){return{get:e=>{try{return localStorage.getItem(e)}catch{return Ft[e]??null}},set:(e,t)=>{try{localStorage.setItem(e,t)}catch{Ft[e]=t}},delete:e=>{try{localStorage.removeItem(e)}catch{delete Ft[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(Ft).filter(t=>t.startsWith(e))}}}}const lc={conversation:{input_placeholder:"Ask a question",input_placeholder_disabled:"Chat is unavailable in this channel",input_placeholder_steward:"Processing your request...",input_placeholder_wait_ai_agent_response:"Waiting for the agent's reply...",input_placeholder_active_form:"Please fill out the form to move forward.",input_placeholder_reconnecting:"Trying to reconnect. Refresh if persists.",unknown_message_type:"(Unknown message type)",powered_by:"Powered by",citation_title:"Source",start_new_conversation_label:"Start a conversation",scroll_to_new_messages_label:()=>"New message",failed_message_resend:"Retry",failed_message_remove:"Remove",file_upload_no_supported_files:"No supported file types available.",a11y_message_list:"Chat messages",a11y_scroll_to_bottom:"Scroll to bottom",a11y_scroll_to_new_messages:"Scroll to new messages",a11y_open_conversation_list:"Open conversation list",a11y_open_conversation:"Open conversation",a11y_open_conversations:"Open conversations",a11y_close_conversation:"Close conversation",a11y_close_conversations:"Close conversations",a11y_menu:"Menu",a11y_message_input:"Message",a11y_send_message:"Send message",a11y_attach_file:"Attach file",a11y_close_messenger:"Close messenger",a11y_expand_messenger:"Expand messenger",a11y_collapse_messenger:"Collapse messenger",a11y_connect_agent:"Connect with an agent",a11y_message_sender_you:"You",a11y_suggested_reply:"Suggested reply",a11y_typing_indicator:"Typing",a11y_code_block_placeholder:"Code block",a11y_typing_format:e=>`${e} is typing`,a11y_message_failed:"Message send failed",a11y_new_messages_received:e=>`${e} new ${e===1?"message":"messages"} received`,a11y_new_messages_received_from_sender:(e,t)=>`${e}: ${t} new ${t===1?"message":"messages"} received`,a11y_agent_connected:e=>"Connected to human agent",a11y_conversation_closed:"Conversation has ended",a11y_file_image:e=>`Image file: ${e}`,a11y_file_video:e=>`Video file: ${e}`,a11y_file_document:e=>`Document file: ${e}`,a11y_screen_conversation:"Conversation",a11y_screen_conversation_with_agent:e=>`Conversation with ${e}`,a11y_screen_conversation_list_no_count:"Conversation list",a11y_csat_displayed:"Satisfaction survey displayed",a11y_empty_conversation:"No messages in this conversation",a11y_input_disabled:"Message input is disabled",a11y_file_size_exceeded:e=>`File exceeds size limit of ${e}MB`,a11y_csat_form_error:"Please complete the required fields",a11y_hint_send_message:"Sends the message",a11y_hint_open_conversation:"Opens the conversation",a11y_hint_open_conversations:"Opens conversations",a11y_hint_close_conversation:"Closes the conversation",a11y_hint_open_menu:"Opens the menu",a11y_hint_connect_to_agent:"Escalates to a human agent",a11y_hint_attach_file:"Opens file attachment options",a11y_hint_view_new_messages:"Scrolls to new messages",a11y_hint_open_file:"Opens the file",a11y_hint_open_image:"Opens the image",a11y_hint_send_reply:"Sends this reply"},conversation_list:{header_title:"Conversations",ended:"Ended",system_message:"System message",footer_title:"Start a conversation",multiple_files_count:e=>`${e} ${e===1?"file":"files"}`,a11y_conversation_item:(e,t,n,r)=>`${e}, ${t}, ${n}, ${r} unread ${r===1?"message":"messages"}`},date_format:{just_now:"Just now",minutes_ago:e=>`${e} minutes ago`,hours_ago:e=>`${e} hours ago`,date_short:"MM/dd/yyyy",date_separator:"MMMM dd, yyyy",message_timestamp:"p"},csat:{title:"Your feedback matters to us",submitted_label:"Successfully submitted!",cre_question:"Was your issue resolved?",cre_positive_label:"Yes, thank you! 👍",cre_negative_label:"No, that didn't help.",reason_placeholder:"Share your feedback",question:"How would you rate your experience?",submit_label:"Submit",submission_expired:"We're sorry, the survey period has ended.",a11y_rating_label:(e,t)=>`${e} out of 5 — ${t}`,a11y_hint_select_rating:"Selects this rating"},form:{optional_label:"optional",validation_required:"This question is required"},common:{placeholder_something_went_wrong:"Something went wrong",placeholder_no_messages:"No messages",placeholder_no_conversations:"No conversations yet",placeholder_something_went_wrong_retry_label:"Retry"},feedback:{title:"Submit feedback",good:"Good",bad:"Bad",comment_label:"Comment (optional)",comment_placeholder:"Leave a comment",cancel:"Cancel",submit:"Submit",save:"Save",edit:"Edit feedback",remove:"Remove feedback"},handoff:{confirm_title:"Request handoff?",confirm_description:"You'll be transferred to a human agent. Your conversation history will be shared.",confirm_cancel:"Cancel",confirm_handoff:"Handoff"}},Pn={language:"en",strings:lc,dateLocale:oi.enUS},Ko=e=>({MESSAGE_INPUT__PLACE_HOLDER:e.conversation.input_placeholder,MESSAGE_INPUT__PLACE_HOLDER__DISABLED:e.conversation.input_placeholder_disabled,MESSAGE_INPUT__PLACE_HOLDER__STEWARD:e.conversation.input_placeholder_steward,MESSAGE_INPUT__PLACE_HOLDER__WAIT_AI_AGENT_RESPONSE:e.conversation.input_placeholder_wait_ai_agent_response,MESSAGE_INPUT__PLACE_HOLDER__RECONNECTING:e.conversation.input_placeholder_reconnecting,UNKNOWN__UNKNOWN_MESSAGE_TYPE:e.conversation.unknown_message_type,POWERED_BY:e.conversation.powered_by,CSAT_TITLE_UNSUBMITTED:e.csat.title,CSAT_TITLE_SUBMITTED:e.csat.submitted_label,CSAT_CRE_TITLE:e.csat.cre_question,CSAT_CRE_SOLVED:e.csat.cre_positive_label,CSAT_CRE_NOT_SOLVED:e.csat.cre_negative_label,CSAT_REASON_PLACEHOLDER:e.csat.reason_placeholder,CSAT_RATING_TITLE:e.csat.question,CSAT_SUBMIT_LABEL:e.csat.submit_label,CSAT_SUBMISSION_EXPIRED:e.csat.submission_expired,DATE_FORMAT__JUST_NOW:e.date_format.just_now,DATE_FORMAT__MINUTES_AGO:e.date_format.minutes_ago,DATE_FORMAT__HOURS_AGO:e.date_format.hours_ago,DATE_FORMAT__DATE_SHORT:e.date_format.date_short,DATE_FORMAT__MESSAGE_LIST__DATE_SEPARATOR:e.date_format.date_separator,DATE_FORMAT__MESSAGE_TIMESTAMP:e.date_format.message_timestamp,CONVERSATION_LIST__HEADER_TITLE:e.conversation_list.header_title,CONVERSATION_LIST__ENDED:e.conversation_list.ended,CONVERSATION_LIST__SYSTEM_MESSAGE:e.conversation_list.system_message,CONVERSATION_LIST__NO_CONVERSATIONS:e.common.placeholder_no_conversations,CONVERSATION_LIST__MULTIPLE_FILES_COUNT:e.conversation_list.multiple_files_count,TALK_TO_AGENT:e.conversation.start_new_conversation_label,CITATION_SOURCE_TITLE:e.conversation.citation_title,FORM_PLACEHOLDER:e.conversation.input_placeholder_active_form,FORM_VALIDATION_REQUIRED:e.form.validation_required,OPTIONAL:e.form.optional_label,PLACE_HOLDER__WRONG:e.common.placeholder_something_went_wrong,PLACE_HOLDER__NO_MESSAGES:e.common.placeholder_no_messages,RETRY:e.common.placeholder_something_went_wrong_retry_label,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,A11Y_OPEN_CONVERSATION:e.conversation.a11y_open_conversation,A11Y_OPEN_CONVERSATIONS:e.conversation.a11y_open_conversations,A11Y_CLOSE_CONVERSATION:e.conversation.a11y_close_conversation,A11Y_CLOSE_CONVERSATIONS:e.conversation.a11y_close_conversations,A11Y_MENU:e.conversation.a11y_menu,A11Y_MESSAGE_INPUT:e.conversation.a11y_message_input,A11Y_SEND_MESSAGE:e.conversation.a11y_send_message,A11Y_ATTACH_FILE:e.conversation.a11y_attach_file,A11Y_CONNECT_AGENT:e.conversation.a11y_connect_agent,A11Y_CLOSE_MESSENGER:e.conversation.a11y_close_messenger,A11Y_EXPAND_MESSENGER:e.conversation.a11y_expand_messenger,A11Y_COLLAPSE_MESSENGER:e.conversation.a11y_collapse_messenger,A11Y_MESSAGE_SENDER_YOU:e.conversation.a11y_message_sender_you,A11Y_SUGGESTED_REPLY:e.conversation.a11y_suggested_reply,A11Y_TYPING_INDICATOR:e.conversation.a11y_typing_indicator,A11Y_CODE_BLOCK_PLACEHOLDER:e.conversation.a11y_code_block_placeholder,A11Y_TYPING_FORMAT:e.conversation.a11y_typing_format,A11Y_MESSAGE_FAILED:e.conversation.a11y_message_failed,A11Y_NEW_MESSAGES_RECEIVED:e.conversation.a11y_new_messages_received,A11Y_NEW_MESSAGES_RECEIVED_FROM_SENDER:e.conversation.a11y_new_messages_received_from_sender,A11Y_AGENT_CONNECTED:e.conversation.a11y_agent_connected,A11Y_CONVERSATION_CLOSED:e.conversation.a11y_conversation_closed,A11Y_FILE_IMAGE:e.conversation.a11y_file_image,A11Y_FILE_VIDEO:e.conversation.a11y_file_video,A11Y_FILE_DOCUMENT:e.conversation.a11y_file_document,A11Y_SCREEN_CONVERSATION:e.conversation.a11y_screen_conversation,A11Y_SCREEN_CONVERSATION_WITH_AGENT:e.conversation.a11y_screen_conversation_with_agent,A11Y_SCREEN_CONVERSATION_LIST_NO_COUNT:e.conversation.a11y_screen_conversation_list_no_count,A11Y_CSAT_DISPLAYED:e.conversation.a11y_csat_displayed,A11Y_EMPTY_CONVERSATION:e.conversation.a11y_empty_conversation,A11Y_INPUT_DISABLED:e.conversation.a11y_input_disabled,A11Y_FILE_SIZE_EXCEEDED:e.conversation.a11y_file_size_exceeded,A11Y_CSAT_FORM_ERROR:e.conversation.a11y_csat_form_error,A11Y_HINT_SEND_MESSAGE:e.conversation.a11y_hint_send_message,A11Y_HINT_OPEN_CONVERSATION:e.conversation.a11y_hint_open_conversation,A11Y_HINT_OPEN_CONVERSATIONS:e.conversation.a11y_hint_open_conversations,A11Y_HINT_CLOSE_CONVERSATION:e.conversation.a11y_hint_close_conversation,A11Y_HINT_OPEN_MENU:e.conversation.a11y_hint_open_menu,A11Y_HINT_CONNECT_TO_AGENT:e.conversation.a11y_hint_connect_to_agent,A11Y_HINT_ATTACH_FILE:e.conversation.a11y_hint_attach_file,A11Y_HINT_VIEW_NEW_MESSAGES:e.conversation.a11y_hint_view_new_messages,A11Y_HINT_OPEN_FILE:e.conversation.a11y_hint_open_file,A11Y_HINT_OPEN_IMAGE:e.conversation.a11y_hint_open_image,A11Y_HINT_SEND_REPLY:e.conversation.a11y_hint_send_reply,A11Y_CONVERSATION_ITEM:e.conversation_list.a11y_conversation_item,A11Y_RATING_LABEL:e.csat.a11y_rating_label,A11Y_HINT_SELECT_RATING:e.csat.a11y_hint_select_rating,SCROLL_TO_NEW_MESSAGES_LABEL:e.conversation.scroll_to_new_messages_label,HANDOFF_CONFIRM__TITLE:e.handoff.confirm_title,HANDOFF_CONFIRM__DESCRIPTION:e.handoff.confirm_description,HANDOFF_CONFIRM__CANCEL:e.handoff.confirm_cancel,HANDOFF_CONFIRM__HANDOFF:e.handoff.confirm_handoff}),jo=e=>{var t;return((t=e.split("-"))==null?void 0:t[0])??It},It="en",Xo=new Set([It,"ko","es","pt","fr","hi","it","de","tr","ja"]),cc='@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}',uc=(e,t,n)=>{const r=e[t];return r?typeof r=="function"?r():Promise.resolve(r):new Promise((o,s)=>{(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(s.bind(null,new Error("Unknown variable dynamic import: "+t+(t.split("/").length!==n?". Note that variables only represent file names one level deep.":""))))})},Ur=Ko(Pn.strings),dc={...Ur,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",A11Y_FILE_SELECTED:e=>`${e}, selected`,A11Y_FILE_REMOVE_BUTTON:e=>`Remove file: ${e}`,A11Y_CSAT_RATING_LABEL:(e,t)=>`${e} out of 5, ${t}`,A11Y_FILE_UPLOAD_OPTIONS:"File upload options",A11Y_FAILED_MESSAGE_OPTIONS:"Failed message options",A11Y_FEEDBACK_OPTIONS:"Feedback options",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:Ur.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"},Xt={language:Pn.language,dateLocale:Pn.dateLocale,stringSet:dc},mc=Object.freeze(Object.defineProperty({__proto__:null,default:Xt},Symbol.toStringTag,{value:"Module"})),Fn=new Map([[It,Xt]]);async function hc(e){const t=Fn.get(e);if(t)return t;try{if(Xo.has(e)){const{default:n}=await uc(Object.assign({"./languages/de.ts":()=>Promise.resolve().then(()=>require("./cjs/rNq_TnmW.cjs")),"./languages/en.ts":()=>Promise.resolve().then(()=>mc),"./languages/es.ts":()=>Promise.resolve().then(()=>require("./cjs/DVc2qz6N.cjs")),"./languages/fr.ts":()=>Promise.resolve().then(()=>require("./cjs/C3OHcrBV.cjs")),"./languages/hi.ts":()=>Promise.resolve().then(()=>require("./cjs/pDHRH5ez.cjs")),"./languages/it.ts":()=>Promise.resolve().then(()=>require("./cjs/D2fiRjSz.cjs")),"./languages/ja.ts":()=>Promise.resolve().then(()=>require("./cjs/jGp6gOJ2.cjs")),"./languages/ko.ts":()=>Promise.resolve().then(()=>require("./cjs/BV40WZg3.cjs")),"./languages/pt.ts":()=>Promise.resolve().then(()=>require("./cjs/A0RFIJy_.cjs")),"./languages/tr.ts":()=>Promise.resolve().then(()=>require("./cjs/BNjeOTuI.cjs"))}),`./languages/${e}.ts`,3);return Fn.set(e,n),n}return Xt}catch{return Xt}}const{Provider:gc,useContext:Y}=oe("Localization"),fc=({language:e=navigator.language,languageCode:t,logger:n,stringSet:r,children:o})=>{const[s,a]=u.useState(Fn.get(It));return u.useEffect(()=>{const l=t??jo(e);s.language!==l&&(n==null||n.debug("localization.useEffect: update language",{from:s.language,to:l}),hc(l).then(a))},[e,t,n]),i.createElement(gc,{value:{language:s.language,defaultStringSet:s.stringSet,stringSet:{...s.stringSet,...r},dateLocale:s.dateLocale,format:(l,c,d)=>Ze.format(l,c,{locale:s.dateLocale,...d})}},o)},Zt="data-sb-agent-theme",Vr=e=>(t,...n)=>{let r="";return t.forEach((o,s)=>{r+=o+(n[s]??"")}),`[${Zt}='${e}'] & { ${r} }`},V={light:Vr("light"),dark:Vr("dark")},pc=D.css(({theme:e})=>{const{palette:t}=e;return`
|
|
2
8
|
:root,
|
|
3
9
|
:host {
|
|
4
10
|
--sendbird-primary-extra-dark: ${t.primary.extraDark};
|
|
@@ -47,25 +53,53 @@
|
|
|
47
53
|
--sendbird-overlay-dark: ${t.overlay.dark};
|
|
48
54
|
--sendbird-overlay-light: ${t.overlay.light};
|
|
49
55
|
}
|
|
50
|
-
`}),
|
|
51
|
-
${
|
|
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
|
-
|
|
56
|
+
`}),_c=D.css`[${Zt}='light'] &{--sb-text-high-emphasis:var(--sendbird-onlight-text-high-emphasis);--sb-text-mid-emphasis:var(--sendbird-onlight-text-mid-emphasis);--sb-text-low-emphasis:var(--sendbird-onlight-text-low-emphasis);--sb-text-disabled:var(--sendbird-onlight-text-disabled);--sb-text-high-emphasis-inverse:var(--sendbird-ondark-text-high-emphasis);--sb-text-mid-emphasis-inverse:var(--sendbird-ondark-text-mid-emphasis);--sb-text-low-emphasis-inverse:var(--sendbird-ondark-text-low-emphasis);--sb-text-disabled-inverse:var(--sendbird-ondark-text-disabled);--sb-bg-50-600:var(--sendbird-background-50);--sb-bg-100-500:var(--sendbird-background-100);--sb-bg-300-500:var(--sendbird-background-300);--sb-bg-200-400:var(--sendbird-background-200);--sb-primary:var(--sendbird-primary-main);--sb-secondary:var(--sendbird-secondary-main);--sb-error:var(--sendbird-error-main);--sb-information:var(--sendbird-information-light);}[${Zt}='dark'] &{--sb-text-high-emphasis:var(--sendbird-ondark-text-high-emphasis);--sb-text-mid-emphasis:var(--sendbird-ondark-text-mid-emphasis);--sb-text-low-emphasis:var(--sendbird-ondark-text-low-emphasis);--sb-text-disabled:var(--sendbird-ondark-text-disabled);--sb-text-high-emphasis-inverse:var(--sendbird-onlight-text-high-emphasis);--sb-text-mid-emphasis-inverse:var(--sendbird-onlight-text-mid-emphasis);--sb-text-low-emphasis-inverse:var(--sendbird-onlight-text-low-emphasis);--sb-text-disabled-inverse:var(--sendbird-onlight-text-disabled);--sb-bg-50-600:var(--sendbird-background-600);--sb-bg-100-500:var(--sendbird-background-500);--sb-bg-300-500:var(--sendbird-background-500);--sb-bg-200-400:var(--sendbird-background-400);--sb-primary:var(--sendbird-primary-light);--sb-secondary:var(--sendbird-secondary-light);--sb-error:var(--sendbird-error-light);--sb-information:var(--sendbird-information-light);}`,g={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_300_500:"var(--sb-bg-300-500)",bg_200_400:"var(--sb-bg-200-400)",primary:"var(--sb-primary)",error:"var(--sb-error)",secondary:"var(--sb-secondary)"}},{Provider:Ec,useContext:or}=oe("MessengerTheme");function bc(e){const{theme:t,appearance:n,logger:r}=e;return i.createElement(La,{appearance:n,palette:t==null?void 0:t.palette,typography:t==null?void 0:t.typography,colors:t==null?void 0:t.colors,logger:r},i.createElement(Cc,{...e}))}function Cc({rootElement:e=document.body,children:t}){const{theme:n,updateTheme:r}=Qn();return u.useLayoutEffect(()=>{e.setAttribute(Zt,n.selectedTheme)},[e,n.selectedTheme]),i.createElement(D.ThemeProvider,{theme:n},i.createElement(Ec,{value:{theme:n,updateTheme:r,rootElement:e}},t))}function Le(e,t){const n=e.getRootNode({composed:t});return n instanceof ShadowRoot||n instanceof Document?n:document}const vc=(e,t)=>{u.useEffect(()=>{const n=Le(t)instanceof ShadowRoot,r=Le(t,!0);if(!(n?t:r).querySelector(`link[href*='${e}']`)){const s=r.createElement("link");s.rel="stylesheet",s.href=e,(n?t:r.head).appendChild(s)}},[e,t])},yc=(e,t=document.body)=>{u.useEffect(()=>{const n=Le(t),o=n instanceof ShadowRoot?t:n.head;if(!o)return;const s=`sba-${btoa(e).slice(0,10)}`;let a=o.querySelector(`style#${s}`);a?a.textContent!==e&&(a.textContent=e):(a=o.ownerDocument.createElement("style"),a.id=s,a.textContent=e,o.appendChild(a))},[e,t])},Sc=80,xc=()=>{const{stringSet:e}=Y(),t={screenConversation:e.A11Y_SCREEN_CONVERSATION,screenConversationWithAgent:e.A11Y_SCREEN_CONVERSATION_WITH_AGENT,screenConversationListNoCount:e.A11Y_SCREEN_CONVERSATION_LIST_NO_COUNT,newMessage:e.A11Y_NEW_MESSAGES_RECEIVED,newMessageFromSender:e.A11Y_NEW_MESSAGES_RECEIVED_FROM_SENDER,typing:e.A11Y_TYPING_FORMAT,sendFailed:e.A11Y_MESSAGE_FAILED,agentConnected:e.A11Y_AGENT_CONNECTED,conversationClosed:e.A11Y_CONVERSATION_CLOSED,csatDisplayed:e.A11Y_CSAT_DISPLAYED,emptyState:e.A11Y_EMPTY_CONVERSATION,inputDisabled:e.A11Y_INPUT_DISABLED,fileSizeExceeded:e.A11Y_FILE_SIZE_EXCEEDED,csatFormError:e.A11Y_CSAT_FORM_ERROR},n=u.useRef(t);return n.current=t,n},Zo=oe("AriaLiveRegion",{announce:X,announceScreenEntry:X,announceStatus:X,announceError:X,flush:X,setSuppressionState:X}),Ac=Zo.Provider,an=Zo.useContext,Tc={position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},Ic=({children:e})=>{const t=u.useRef(null),n=u.useRef(new Set),r=u.useRef(X),o=xc(),[s]=u.useState(()=>ql(b=>{r.current(b)},{throttleMs:1e3,isSuppressed:()=>n.current.size>0}));r.current=b=>{const C=t.current;C&&(C.textContent="",requestAnimationFrame(()=>{C.textContent=b}))},u.useEffect(()=>()=>{s.destroy()},[s]);const a=s.announce,l=s.flush,c=u.useCallback(b=>{const C=Kl(b,o.current);a(C)},[a]),d=u.useCallback(b=>{const C=jl(b,o.current);a(C,{mode:Yl(b.event)})},[a]),m=u.useCallback((b,C)=>{const v=Xl(b,o.current);s.announceIgnoringSuppression(v),C&&setTimeout(()=>{C.focus()},Sc)},[s]),h=u.useCallback((b,C)=>{if(C){n.current.add(b);return}n.current.delete(b)},[]),f=u.useMemo(()=>({announce:a,announceScreenEntry:c,announceStatus:d,announceError:m,flush:l,setSuppressionState:h}),[a,m,c,d,l,h]);return i.createElement(Ac,{value:f},e,i.createElement("div",{ref:t,role:"status","aria-live":"polite","aria-atomic":"true",style:Tc}))},Jo=oe("ConversationAnnouncements",{announcementsActive:!0,announce:X,announceScreenEntry:X,announceStatus:X,announceError:X,setIsSuppressed:X,flush:X}),wc=Jo.Provider,ln=Jo.useContext,kc=({children:e,announcementsActive:t=!0})=>{const{announce:n,announceScreenEntry:r,announceStatus:o,announceError:s,flush:a,setSuppressionState:l}=an(),c=u.useRef(!1),d=u.useCallback(h=>{c.current=h,l(Sn,t?h:!1)},[t,l]);u.useEffect(()=>(l(Sn,t?c.current:!1),()=>{l(Sn,!1)}),[t,l]);const m=u.useMemo(()=>({announcementsActive:t,announce:t?n:X,announceScreenEntry:t?r:X,announceStatus:t?o:X,announceError:t?s:X,setIsSuppressed:d,flush:a}),[n,s,t,r,o,a,d]);return i.createElement(wc,{value:m},e)},Sn=Symbol("conversation-announcements"),{Provider:Mc,Consumer:Qo,useContext:Z}=oe("Messenger");function Lc({children:e,state:t,enableCloseConversationButton:n=!1,enableExpandButton:r=!0,enableAutoDisconnectInLauncher:o=!0,...s}){const[a,l]=u.useState(!1),[c,d]=u.useState(!1),m={opened:(t==null?void 0:t.opened)??a,setOpened:(t==null?void 0:t.setOpened)??l,expanded:(t==null?void 0:t.expanded)??c,setExpanded:(t==null?void 0:t.setExpanded)??d};return i.createElement(ma,{...s},h=>i.createElement(Mc,{value:{...s,...h,state:m,enableCloseConversationButton:n,enableExpandButton:r,enableAutoDisconnectInLauncher:o}},e))}const es=/iPad|iPhone|iPod/.test(navigator.userAgent),Oc=/Android/.test(navigator.userAgent),wt=e=>es||Oc;let pt=null,xn=null;const Rc=(e,t=5e3)=>{pt&&(clearInterval(pt),clearTimeout(xn));const n=document.title;pt=setInterval(()=>{document.title=document.title===e?n:e},750),xn=setTimeout(()=>{clearInterval(pt),pt=null,xn=null,document.title=n},t)},ts=()=>{Promise.resolve().then(()=>require("./cjs/B93o4u0P.cjs")).then(e=>{new Audio(e.default).play().catch(()=>{})})},de=D.css`&:focus-visible{outline:2px solid ${g.themedColor.primary};outline-offset:2px;}`,we=e=>{const t=e;return typeof t=="number"?`${t}px`:t},$=({as:e,variant:t="body1",color:n,maxTextLines:r,className:o,...s})=>i.createElement(Dc,{as:e,$variant:t,className:o,$color:n,$maxTextLines:r,...s}),zr=new WeakMap,Nc=(e,t)=>{let n=zr.get(t);n||(n=new Map,zr.set(t,n));const r=n.get(e);if(r)return r;const o=t[e]??t.body1,s=D.css`font-size:${we(o.fontSize)};font-weight:${o.fontWeight};${o.fontFamily?`font-family: ${o.fontFamily};`:""}
|
|
57
|
+
${o.lineHeight?`line-height: ${o.lineHeight};`:"line-height: 100%;"}
|
|
58
|
+
`;return n.set(e,s),s},$c=e=>e?D.css`display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:${e};overflow:hidden;`:"",Dc=p.default.span`font-stretch:normal;letter-spacing:normal;${({$variant:e,theme:t})=>Nc(e,t.typography)}color:${({$color:e})=>e};${({$maxTextLines:e})=>$c(e)}`,Pc=(e,t=!0,n)=>{const r=n==null?void 0:n.containerRef;u.useEffect(()=>{if(!t||!e)return;const o=a=>{a.key==="Escape"&&e()&&a.stopImmediatePropagation()},s=(r==null?void 0:r.current)??document;return s.addEventListener("keydown",o),()=>s.removeEventListener("keydown",o)},[r,e,t])},ns=["a[href]","button:not(:disabled)","input:not(:disabled)","select:not(:disabled)","textarea:not(:disabled)",'[tabindex]:not([tabindex="-1"])'].join(", "),rs=e=>Array.from(e.querySelectorAll(ns)),Fc=e=>{const t=rs(e),n=t[0]??e;t.length||e.setAttribute("tabindex","-1"),n.focus()},Bc=(e,t,n)=>{const r=rs(t);if(r.length===0){e.preventDefault(),t.focus();return}const o=r[0],s=r[r.length-1],a=n.activeElement;(e.shiftKey?a===o:a===s)&&(e.preventDefault(),(e.shiftKey?s:o).focus())},Hc=(e,t)=>{const n=u.useRef(null);u.useEffect(()=>{if(!e||!t.current)return;const r=t.current.getRootNode();return n.current=r.activeElement,Fc(t.current),()=>{var o;(o=n.current)==null||o.focus(),n.current=null}},[e,t]),u.useEffect(()=>{if(!e||!t.current)return;const r=t.current,o=r.getRootNode(),s=a=>{a.key==="Tab"&&Bc(a,r,o)};return r.addEventListener("keydown",s),()=>r.removeEventListener("keydown",s)},[e,t])},ut=({style:e,rootElementId:t,visible:n,onClose:r,children:o,"aria-label":s,"aria-labelledby":a,"aria-describedby":l})=>{const c=u.useRef(null),{rootElement:d}=or();if(Hc(n,c),Pc(u.useCallback(()=>(r(),!0),[r]),n,{containerRef:c}),!n)return null;const m=Le(d),h=Le(d,!0);return si.createPortal(i.createElement(Uc,{onClick:r,style:e},i.createElement(Vc,{ref:c,role:"dialog","aria-modal":"true","aria-label":s,"aria-labelledby":a,"aria-describedby":l,onClick:f=>f.stopPropagation()},o)),m.getElementById(t)??m.getElementById(ne.MODAL_ROOT)??h.body)},Uc=p.default.div`position:fixed;top:0;left:0;width:100%;height:100%;background:${g.color.overlay.dark};display:flex;justify-content:center;align-items:center;z-index:${et.MODAL};`,Vc=p.default.div`border-radius:4px;overflow:hidden;box-shadow:0 16px 24px 2px rgba(13,13,13,0.12),0 6px 30px 5px rgba(13,13,13,0.08),0 6px 10px -5px rgba(13,13,13,0.04);z-index:${et.MODAL};`,Gr=e=>{if(typeof e=="string"||typeof e=="number")return String(e)},sr=({visible:e,title:t,description:n,confirmText:r="OK",onConfirm:o,onClose:s,"aria-label":a})=>{const l=u.useId(),c=u.useId(),d=()=>{o==null||o(),s()},m=a??Gr(t)??Gr(n),h=a?void 0:t?l:n?c:void 0,f=t&&n?c:void 0;return i.createElement(ut,{rootElementId:ne.WINDOW,visible:e,onClose:s,"aria-label":m,"aria-labelledby":h,"aria-describedby":f},i.createElement(zc,null,i.createElement(Gc,null,t&&i.createElement("div",{id:l},i.createElement($,{variant:"h1",color:g.themedColor.textHighEmphasis},t)),n&&i.createElement(Wc,{id:c},i.createElement($,{variant:"subtitle2",color:g.themedColor.textHighEmphasis},n))),i.createElement(qc,null,i.createElement(Yc,{onClick:d},i.createElement($,{variant:"button",color:g.themedColor.primary},r)))))},zc=p.default.div`width:360px;height:auto;padding-block:24px 12px;padding-inline:24px;margin:0 auto;border-radius:4px;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,Gc=p.default.div`margin-bottom:16px;`,Wc=p.default.div`margin-top:8px;`,qc=p.default.div`display:flex;flex-direction:row;justify-content:flex-end;`,Yc=p.default.button`all:unset;display:flex;justify-content:center;align-items:center;border-radius:4px;cursor:pointer;background-color:transparent;padding:10px 16px;${de}`,{Provider:Kc,useContext:ce}=oe("MessengerSession"),jc=u.forwardRef(function({children:e,...t},n){return i.createElement($a,{ref:n,...t},r=>i.createElement(Xc,{...r},e))}),Xc=({children:e,...t})=>{const{chatSDK:n,logger:r,appId:o,aiAgentId:s,agentPreviewConfigs:a,state:l,handlers:c,dispatcher:d,_aiAgentSDK:m}=Z(),{userSessionInfo:h,authenticate:f,userSession:b,aiAgentInfo:C,launcherInfo:v}=t,[_,y]=u.useState(!1),E=u.useRef(null);He.useGroupChannelHandler(n,{async onUserJoined(T,O){var N,R,k,P;T.conversation&&T.conversation.type===ue.ConversationType.PROACTIVE&&O.userId===((N=n.currentUser)==null?void 0:N.userId)&&(r.info("messengerSession.onUserJoined: proactive channel joined",T.url),(k=m.session)==null||k._updateActiveChannel({url:T.url,status:"open",conversationStatus:(R=T.conversation)==null?void 0:R.status}),l.setOpened(!0),Zc({sound:document.hidden||!l.opened}),(P=E.current)==null||P.call(E,{channel:T}))}}),u.useEffect(()=>{f().then(({launcher:T})=>{T.auto_open&&!wt()&&setTimeout(()=>l.setOpened(!0),500)}).catch(T=>{var O;r.error("messengerSession: failed to initialize",T),(O=c==null?void 0:c.onInitializeFailed)==null||O.call(c,T)})},[n,o,s,h==null?void 0:h.userId]),u.useEffect(()=>{const T=()=>y(!0);return d.subscribe(xe.AnonymousSessionTokenExpired,T),()=>d.unsubscribe(xe.AnonymousSessionTokenExpired,T)},[d]);const A=u.useCallback(()=>{t.deauthenticate().finally(()=>window.location.reload())},[t.deauthenticate]);return!b||!C||!v?null:i.createElement(Kc,{value:{...t,userSession:b,aiAgentInfo:{...C,...a==null?void 0:a.bot},launcherInfo:{...v,...a==null?void 0:a.launcher},registerOnJoinedProactiveConversation:T=>E.current=T}},e,i.createElement(sr,{visible:_,title:"Session timed out",description:"Start a new conversation.",onConfirm:A,onClose:X}))};function Zc({sound:e}){Rc("🔔You have received a new message"),e&&ts()}const Jc=e=>{const{chatSDK:t,handlers:n,logger:r}=Z(),{aiAgentInfo:o}=ce(),s=u.useRef(new Set),a=m=>{if(!(n!=null&&n.onCustomEvent))return;Ae(m)&&m.sender.userId===o.userId&&!Fe.isStreaming(m)&&!s.current.has(m.messageId)&&(r.debug("useCustomEventForMessageReceive: bot-message-received",m),n.onCustomEvent({type:"bot-message-received",data:{message:m}}),s.current.add(m.messageId))},l=m=>{if(n!=null&&n.onCustomEvent&&m.isAdminMessage()&&m.customType==="user_action_required"&&!s.current.has(m.messageId)){const h=On(m.data);Array.isArray(h.history)&&h.history.length===0&&(r.debug("useCustomEventForMessageReceive: user_action_required",h),n.onCustomEvent({type:"user-action-requested",data:h}),s.current.add(m.messageId))}},c=(m,h)=>{m.url===e&&(a(h),l(h))},d=m=>{l(m)};return He.useGroupChannelHandler(t,{onMessageUpdated:c,onMessageReceived:c}),{checkForUserActionRequired:d}},Jt=`@${Ce}-focused-channel`,os=`${Date.now()}-${Math.random().toString(36).slice(2)}`,Qc=()=>{try{const e=localStorage.getItem(Jt);return e?JSON.parse(e).channelUrl??null:null}catch{return null}},Wr=e=>{try{localStorage.setItem(Jt,JSON.stringify({channelUrl:e,tabId:os}))}catch{}},qr=()=>{try{const e=localStorage.getItem(Jt);if(!e)return;JSON.parse(e).tabId===os&&localStorage.removeItem(Jt)}catch{}},eu=(e,t)=>(u.useEffect(()=>{if(!t||!e)return;const n=()=>Wr(e),r=()=>qr();return document.hasFocus()&&Wr(e),window.addEventListener("focus",n),window.addEventListener("blur",r),()=>{window.removeEventListener("focus",n),window.removeEventListener("blur",r),qr()}},[t,e]),{isChannelViewedInAnyTab:()=>document.hasFocus()||Qc()===e}),tu=e=>{var a;const{config:t,chatSDK:n}=Z(),{sdkUser:r}=ce(),o=!!((a=t==null?void 0:t.conversation)!=null&&a.messageAlertSoundEnabled),{isChannelViewedInAnyTab:s}=eu(e,o);He.useGroupChannelHandler(n,{onMessageReceived(l,c){if(!o||l.url!==e||s())return;(Ae(c)&&c.sender.userId!==(r==null?void 0:r.userId)||c.isAdminMessage()&&!c.silent)&&ts()}})};function nu(e){return new Promise(t=>{const n=new Image;n.onload=function(){const r=String(n.width),o=String(n.height);URL.revokeObjectURL(n.src),t({width:r,height:o})},n.src=URL.createObjectURL(e)})}async function ru(e){if("file"in e&&e.file instanceof File&&e.file.type.startsWith("image/")){const{width:t,height:n}=await nu(e.file);return new Pe.MessageMetaArray({key:Co,value:[t,n]})}}const ou=({onScrollAfterSendMessage:e})=>{const{agentPreviewConfigs:t,handlers:n}=Z(),r=u.useRef(t==null?void 0:t.agentAttributes);return r.current=t==null?void 0:t.agentAttributes,{onBeforeSendMessage:async o=>{const s=await ru(o),a={...o,metaArrays:s?[s]:void 0},l=su(r.current);return l?{...a,data:JSON.stringify(l)}:a},onAfterSendMessage:o=>{var s,a,l;e(),(s=n==null?void 0:n.onMessageSend)==null||s.call(n,o.message),o.sendingStatus===Pe.SendingStatus.SUCCEEDED?(a=n==null?void 0:n.onCustomEvent)==null||a.call(n,{type:"message-sent-succeeded",data:{message:o}}):o.sendingStatus===Pe.SendingStatus.PENDING&&((l=n==null?void 0:n.onCustomEvent)==null||l.call(n,{type:"message-sent-pending",data:{message:o}}))}}},su=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 ir(e){let t=e;t&&(!t.startsWith("http://")&&!t.startsWith("https://")&&(t="https://"+t),window.open(t,"_blank","noopener,noreferrer"))}function Qe(e){requestAnimationFrame(()=>{requestAnimationFrame(()=>{e()})})}const lt=50,An=lt-40,{Provider:iu,useContext:ss}=oe("ConversationScroll"),Yr={viewport:0,contentHeight:0,contentSnapshotHeight:0,shouldRecalc:!1,shouldUpdate:!1},Tn=e=>Math.max(0,e.scrollHeight-e.scrollTop-e.clientHeight);function au({scrollMode:e,messageStackDirection:t,children:n}){const r=u.useRef(null),o=u.useRef(null),s=u.useRef(0),a=u.useRef(0),l=u.useRef(!1),c=u.useRef(!1),d=u.useRef(null),m=u.useRef(Yr),h=u.useRef(!1),f=u.useRef(null),[b,C]=u.useState(0),[v,_]=u.useState(0),[y,E]=u.useState(!1),[A,T]=u.useState(!1),[O,w]=u.useState(!0),N=H=>{const W=Tn(H);return s.current=W,_(W),W},R=()=>{d.current&&(clearTimeout(d.current),d.current=null)},k=u.useMemo(()=>y||t==="bottom"?"auto":e,[y,t,e]),P=()=>{m.current.contentSnapshotHeight=m.current.contentHeight,m.current.shouldUpdate=!0,m.current.shouldRecalc=!0},I=()=>{const H=r.current;!H||!m.current.shouldUpdate||C(W=>{m.current.shouldUpdate=!1;const{contentHeight:K,contentSnapshotHeight:ie,shouldRecalc:he}=m.current,Me=H.clientHeight;if(ie>K)return W;const st=x(H,{messageType:"outgoing"});let ye=0;if(st){const Ne=st.message.offsetTop-An+Me;ye=Math.max(0,Ne-K)}else{const Ne=K-ie,it=Me-An;ye=Math.max(0,Ne-it)}return W===0||ye!==W||he?(m.current.shouldRecalc=!1,ye):W})},x=u.useCallback((H,W)=>{const{messageType:K="all"}=W??{},ie=Array.from(H.querySelectorAll(`#${Ce}-message-item`));let he=ie;K==="outgoing"&&(he=ie.filter(Ye=>Ye.getAttribute("data-layout-id")==="outgoingmessage"));const Me=he[he.length-1];if(!Me)return null;const st=H.getBoundingClientRect(),ye=Me.getBoundingClientRect(),Ne=H.scrollTop+(ye.top-st.top),it=Ne+Me.offsetHeight;return{message:Me,scrollTop:Ne,lastMessageBottom:it}},[]),L=u.useCallback(()=>{const H=r.current;if(!H||k!=="fixed")return;const W=x(H);m.current.contentHeight=(W==null?void 0:W.lastMessageBottom)??H.scrollHeight,!h.current&&m.current.contentSnapshotHeight>0&&P(),c.current?s.current=Tn(H):N(H),I()},[k,x]),F=u.useCallback(()=>{o.current&&(o.current.disconnect(),o.current=null),R(),m.current=Yr,C(0),_(0),w(!0),s.current=0,l.current=!1,a.current=0,c.current=!1},[]),B=u.useCallback((H=!0)=>{const W=s.current>lt;if(l.current=!1,_(0),!W){Qe(()=>{const K=r.current;K&&!l.current&&K.scrollTo({top:K.scrollHeight,behavior:"auto"})});return}c.current||(c.current=!0,w(!1),R()),Qe(()=>{const K=r.current;if(!K){c.current=!1,w(!0);return}if(l.current){c.current=!1,N(K),w(!0);return}const ie=()=>{if(r.current!==K){c.current=!1,r.current&&N(r.current),w(!0);return}c.current=!1,N(K),w(!0)};if(H&&!d.current){const he=setTimeout(ie,500);d.current=he,K.addEventListener("scrollend",()=>{clearTimeout(he),d.current=null,ie()},{once:!0})}K.scrollTo({top:K.scrollHeight,behavior:H?"smooth":"auto"}),H||ie()})},[]),G=u.useCallback(H=>{H&&(r.current=H,k==="fixed"&&(F(),m.current.viewport=H.clientHeight,o.current=new MutationObserver(()=>{L()}),o.current.observe(H,{childList:!0,subtree:!0})))},[k,L,F]),J=u.useCallback(()=>{const H=r.current;if(!H)return;const W=x(H,{messageType:"outgoing"});W&&(H.scrollTo({top:W.message.offsetTop-An,behavior:"smooth"}),f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{T(!1)},500))},[x]),me=(H,W,K)=>{const ie=Tn(H);if(K&&ie>lt){c.current=!1,l.current=!0,R(),N(H),w(!0),a.current=W;return}s.current=ie},We=(H,W,K)=>{const he=N(H)<=lt;W&&!he&&(l.current=!0,R()),K&&he&&(l.current=!1)},qe=H=>{const{scrollTop:W}=H.currentTarget,K=a.current;c.current?me(H.currentTarget,W,W<K):We(H.currentTarget,W<K,W>K),a.current=W},M=u.useCallback(()=>{k==="fixed"&&(T(!0),P())},[k]),fe=u.useCallback(()=>{k==="fixed"?setTimeout(()=>J(),300):B()},[k,J]),Te=u.useCallback(H=>{h.current=H,k==="fixed"?P():l.current||B()},[k,B]),pe=u.useCallback(H=>{E(H),H&&(C(0),o.current&&(o.current.disconnect(),o.current=null))},[]),rt=u.useCallback(H=>{k==="auto"&&H&&!l.current&&B()},[k,B]),pn=!(v<=lt)&&!A,ot=u.useCallback(()=>s.current>lt,[]);return i.createElement(iu,{value:{ref:G,state:{bottomSpace:b,isAwayFromBottom:pn,isScrollPositionReconciled:O,shouldCountNewMessages:ot},props:{onScroll:qe},actions:{scrollToBottom:B,onBeforeMessageSend:M,onAfterMessageSend:fe,onStreamingUpdate:Te,onConversationClosed:pe,onTypingIndicatorUpdate:rt}}},n)}const{Provider:lu,Context:cu,useContext:se}=oe("Conversation"),uu=({children:e})=>{var o;const{channelSource:t}=se(),n=(o=t.channel)==null?void 0:o.url,{checkForUserActionRequired:r}=Jc(n);return u.useEffect(()=>{var a;const s=(a=t.channel)==null?void 0:a.lastMessage;s&&r(s)},[t.channel,r]),i.createElement(i.Fragment,null,e)},du=({channelUrl:e,onClearChannelUrl:t,onNavigateToConversationList:n,shouldMarkAsRead:r,children:o})=>{const{activeChannel:s,refreshActiveChannel:a}=ce(),l=ss(),c=e||(s==null?void 0:s.url);tu(c);const{onBeforeSendMessage:d,onAfterSendMessage:m}=ou({onScrollAfterSendMessage:()=>{l.actions.onAfterMessageSend()}}),h=u.useCallback(C=>(l.actions.onBeforeMessageSend(),d(C)),[l.actions,d]),f=u.useCallback(C=>{const v=C.some(_=>Fe.isStreaming(_));l.actions.onStreamingUpdate(v)},[l.actions.onStreamingUpdate]),b=u.useCallback(async()=>{await a(),e&&(t==null||t())},[a,e,t]);return i.createElement(Ya,{key:c,channelUrl:c,onBeforeSendMessage:h,onAfterSendMessage:m,onMessagesUpdated:f,onMessagesReceived:f,onChannelDeleted:b,onConversationClosedStatusChanged:l.actions.onConversationClosed,shouldMarkAsRead:r,shouldCountNewMessages:l.state.shouldCountNewMessages},C=>i.createElement(lu,{value:{...C,scrollSource:l,goToActiveConversation:b,onNavigateToConversationList:n}},i.createElement(uu,null,o)))},is=({children:e,...t})=>{var a;const{config:n}=ve(),{agentPreviewConfigs:r}=Z(),o=((a=n==null?void 0:n.conversation)==null?void 0:a.scrollMode)??"auto",s=r==null?void 0:r.messageStackDirection;return i.createElement(au,{scrollMode:o,messageStackDirection:s},i.createElement(du,{...t},e))},ar=u.createContext({onDrop:X,subscribe:()=>X}),Bn=({children:e})=>{const t=u.useRef(new Set);return i.createElement(ar.Provider,{value:{onDrop:n=>{var r;if(n.preventDefault(),(r=n.dataTransfer)!=null&&r.files){const o=Array.from(n.dataTransfer.files);o.length>0&&t.current.forEach(s=>s(o))}},subscribe:n=>(t.current.add(n),()=>t.current.delete(n))}},e)},mu=({onDropFiles:e})=>{const{subscribe:t}=u.useContext(ar);u.useEffect(()=>t(e),[e])};Bn.Consumer=({children:e})=>{const{onDrop:t}=u.useContext(ar);return e({onDrop:t,onDragOver:o=>o.preventDefault()})};const hu=e=>De(e)||yo(e);function gu(e){return e.isAdminMessage()?e.message==="The channel's custom_type was updated.":!1}function fu(e,t){return e.filter(n=>Fe.isWelcomeMessage(n,t))}const as=(e,{previewWelcomeMessages:t,aiAgentUserId:n})=>e.filter(r=>gu(r)?!1:t.length>0?!Fe.isWelcomeMessage(r,n):!0),pu=[],ls=()=>{var b,C,v,_,y,E,A;const{agentPreviewConfigs:e={},aiAgentId:t}=Z(),{aiAgentInfo:n,userSession:r}=ce(),{channelSource:o,messageSource:s,state:{input:a}}=se(),l=e.welcomeMessages??pu,c=u.useMemo(()=>as(s.messages,{previewWelcomeMessages:l,aiAgentUserId:t}),[t,s.messages,l]),d=Ue(o.channel),m=(v=(C=(b=o.channel)==null?void 0:b.members.find(T=>T.userId!==r.userId))==null?void 0:C.nickname)==null?void 0:v.trim(),h=d?(y=(_=o.channel)==null?void 0:_.name)==null?void 0:y.trim():(E=n==null?void 0:n.nickname)==null?void 0:E.trim(),f=m||h||void 0;return{initialized:s.initialized,channelUrl:(A=o.channel)==null?void 0:A.url,agentName:f,isClosed:ge(o.channel),isHandedOff:d,messages:c,filteredMessagesCount:c.length,hasWelcomeMessages:l.length>0,inputDisabled:a.disabled,subscribeMessageEvents:s.subscribeMessageEvents,currentUserId:r.userId}},_u=(e={})=>{const{announceScreenEntry:t,announcementsActive:n}=ln(),{initialized:r=!1,channelUrl:o,agentName:s,isClosed:a=!1,messages:l=[],hasWelcomeMessages:c=!1}=e,d=u.useRef(null),m=u.useMemo(()=>l.some(f=>te.isAdmin(f)&&te.isCSAT(f)),[l]),h=l.length===0&&!c;u.useEffect(()=>{if(!n){d.current=null;return}!r||!o||d.current!==o&&(t({screen:"conversation",agentName:s,isClosed:a,hasCSAT:m,...h?{isEmpty:!0}:{}}),d.current=o)},[s,t,n,o,m,r,a,h])},Eu=()=>{const e=ls();_u(e)},bu=e=>{const t=new Set;for(const n of e){if(!te.isAdmin(n)||!te.isCSAT(n))continue;const r=qo(n);r&&t.add(`csat:${r}`)}return t},Cu=()=>{const{announceStatus:e,announcementsActive:t}=ln(),{channelUrl:n,messages:r,isClosed:o,isHandedOff:s,agentName:a,initialized:l,inputDisabled:c,subscribeMessageEvents:d,currentUserId:m}=ls(),{outgoingMessageStates:h,outgoingMessageStatusSignature:f}=u.useMemo(()=>{if(!m)return{outgoingMessageStates:[],outgoingMessageStatusSignature:""};const w=r.flatMap(N=>{const R=Zl(N,m);return!R||!("sendingStatus"in N)?[]:[{key:R,sendingStatus:N.sendingStatus}]});return{outgoingMessageStates:w,outgoingMessageStatusSignature:w.map(({key:N,sendingStatus:R})=>`${N}:${R}`).join(",")}},[m,r]),b=u.useRef(new Map(h.map(({key:w,sendingStatus:N})=>[w,N]))),C=u.useRef(!1),v=u.useRef(!1),_=u.useRef(c),y=u.useRef(r),E=u.useRef(m),A=u.useRef(new Set),T=u.useRef(!1),O=u.useRef(n);y.current=r,E.current=m,u.useEffect(()=>{const w=O.current!==n;(!t||!l||w)&&(T.current=!1,A.current.clear(),w&&(O.current=n),!t||!l)||T.current||(T.current=!0,O.current=n,C.current=o,v.current=s,_.current=c,b.current=new Map(h.map(({key:N,sendingStatus:R})=>[N,R])),A.current=bu(r))},[t,n,l,c,o,s,f]),u.useEffect(()=>d(w=>{if(!T.current||w.kind==="initialized"||!Jl(w.source))return;const N=Hr(w.messages,w.messages,E.current)??Hr(y.current,w.messages,E.current);if(!N)return;const R=qo(N);if(te.isAdmin(N)&&te.isCSAT(N)){if(R&&A.current.has(`csat:${R}`))return;R&&A.current.add(`csat:${R}`),e({event:"csatDisplayed"});return}if(w.kind!=="messagesAdded"||!("sender"in N))return;const k=N.sender;k.userId!==E.current&&e({event:"newMessage",senderName:k.nickname??""})}),[e,d]),u.useEffect(()=>{if(!T.current)return;const w=b.current;b.current=new Map(h.map(({key:R,sendingStatus:k})=>[R,k])),h.some(({key:R,sendingStatus:k})=>{const P=w.get(R);return P!==void 0&&P!=="failed"&&k==="failed"})&&e({event:"sendFailed"})},[e,f]),u.useEffect(()=>{T.current&&(o&&!C.current&&e({event:"conversationClosed"}),C.current=o)},[e,o]),u.useEffect(()=>{T.current&&(s&&!v.current&&e({event:"agentConnected",agentName:a}),v.current=s)},[a,e,s]),u.useEffect(()=>{T.current&&(c&&!_.current&&e({event:"inputDisabled"}),_.current=c)},[e,c])},vu=()=>{const{channelSource:e}=se(),t=Bo(e.channel);return!(t!=null&&t.user.userId)||!t.user.nickname?null:{userId:t.user.userId,nickname:t.user.nickname}},yu=e=>{const{announceStatus:t,announcementsActive:n}=ln();bl(e??null,r=>{t({event:"typing",agentName:r})},1e4,n)},Su=()=>{const e=vu();yu(e)};class Qt extends u.PureComponent{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}render(){const{fallback:t=null,errorFallback:n=t,loadingFallback:r=t,children:o}=this.props;return this.state.hasError?n:i.createElement(u.Suspense,{fallback:r},o)}}const xu=e=>i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",...e},i.createElement("path",{className:"fill",d:"M52.552 11.448a2.666 2.666 0 0 1 .222 3.52l-.222.251-16.781 16.78 16.781 16.782a2.665 2.665 0 0 1 0 3.771 2.666 2.666 0 0 1-3.52.222l-.251-.222L32 35.771 15.219 52.552a2.665 2.665 0 0 1-3.771 0 2.666 2.666 0 0 1-.222-3.52l.222-.251L28.228 32l-16.78-16.781a2.665 2.665 0 0 1 0-3.771 2.666 2.666 0 0 1 3.52-.222l.251.222 16.78 16.78 16.782-16.78a2.665 2.665 0 0 1 3.771 0z",fill:"#000",fillRule:"evenodd"})),Au=e=>i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 16 16",...e},i.createElement("path",{className:"fill",d:"M7.33348 7.3335L2.00015 7.3335L2.00015 6.00016H5.05735L1.3335 2.27631L2.27631 1.3335L6.00015 5.05734V2.00016L7.33348 2.00016L7.33348 7.3335ZM8.66683 8.66683H14.0002V10.0002L10.943 10.0002L14.6668 13.724L13.724 14.6668L10.0002 10.943V14.0002H8.66683L8.66683 8.66683Z",fill:"#000",fillRule:"evenodd"})),Tu=e=>i.createElement("svg",{viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg",...e},i.createElement("path",{className:"fill",fillRule:"evenodd",clipRule:"evenodd",d:"M2 2H7.33333V3.33333L4.27613 3.33333L7.99999 7.05719L7.05718 8L3.33333 4.27616L3.33333 7.33333H2V2ZM14 14H8.66667V12.6667H11.7239L8.00001 8.94281L8.94282 8L12.6667 11.7238V8.66667H14V14Z",fill:"#000"})),Iu=e=>i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",fill:"evenodd",...e},i.createElement("path",{className:"fill",fill:"#0D0D0D",d:"M50.667 18.667H13.333v-5.334h37.334zM50.667 34.667H13.333v-5.334h37.334zM13.333 50.667h37.334v-5.334H13.333z"})),wu=e=>i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",...e},i.createElement("path",{fill:"#000",fillRule:"evenodd",d:"M59.795 29.43 7.329 2.979C4.691 1.802 1.76 4.153 2.932 6.798l6.925 18.609a2 2 0 0 0 1.544 1.275l32.273 5.394L11.4 37.47a1.998 1.998 0 0 0-1.544 1.275L2.932 57.353c-.879 2.645 1.76 4.997 4.397 3.527l52.466-26.453c2.051-.882 2.051-3.82 0-4.996z",className:"fill"})),ku=new Set(["send","chat","message","chevron-right","good","good-filled","bad","bad-filled"]),Mu={close:xu,send:wu,menu:Iu,expand:Tu,collapse:Au,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"))),"done-circle":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/Bwaslfwl.cjs"))),stop:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/w1C9O3WB.cjs"))),"stop-circle":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DGubkk9p.cjs"))),user:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/CtHfgPDp.cjs"))),"file-document":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/_YfLwFkX.cjs"))),download:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/BN09c8-A.cjs"))),attach:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DcDTXo8_.cjs"))),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 o=Mu[e];return i.createElement(Ou,{className:n,$rtlFlip:ku.has(e),$size:t,$color:r??g.color.primary.main},i.createElement(Qt,{errorFallback:i.createElement(Ru,null)},i.createElement(o,null)))},Lu=D.css`[dir='rtl'] &{transform:scaleX(-1);}`,Ou=p.default.div.attrs({"aria-hidden":"true"})`
|
|
59
|
+
width: ${({$size:e})=>we(e)};
|
|
60
|
+
height: ${({$size:e})=>we(e)};
|
|
61
|
+
display: inline-block;
|
|
62
|
+
&:focus {
|
|
63
|
+
outline: none;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
svg {
|
|
67
|
+
display: block;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
[class*='fill'] {
|
|
71
|
+
fill: ${({$color:e})=>e};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
[class*='stroke'] {
|
|
75
|
+
stroke: ${({$color:e})=>e};
|
|
76
|
+
stroke-width: 2px;
|
|
77
|
+
stroke-linejoin: round;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
${({$rtlFlip:e})=>e&&Lu};
|
|
81
|
+
`,Ru=()=>i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64"},i.createElement("rect",{x:"8",y:"8",width:"48",height:"48",fill:"none",className:"stroke",rx:"4"}),i.createElement("line",{x1:"20",y1:"20",x2:"44",y2:"44",className:"stroke"}),i.createElement("line",{x1:"44",y1:"20",x2:"20",y2:"44",className:"stroke"})),Nu=.75,cs=6,$u=cs*2;let Hn=null;typeof Intl<"u"&&"Segmenter"in Intl&&(Hn=new Intl.Segmenter(void 0,{granularity:"grapheme"}));const Du=e=>Hn?Array.from(Hn.segment(e),t=>t.segment):[...e],Pu=e=>{const t=Math.floor(e.length*Nu),n=Math.max(0,e.length-cs);return Math.max(t,n)},Kr=(e,t="")=>{if(e.length<$u)return{start:e+t,end:""};const n=Du(e),r=Pu(n);return{start:n.slice(0,r).join(""),end:n.slice(r).join("")+t}},Fu=e=>{const t=e.normalize("NFC").trim(),n=t.lastIndexOf(".");if(!(n>0&&n<t.length-1))return Kr(t);const o=t.slice(0,n),s=t.slice(n);return Kr(o,s)},us=({children:e,...t})=>{const{start:n,end:r}=u.useMemo(()=>Fu(e),[e]);return r?i.createElement(Bu,null,i.createElement(Hu,{...t},n),i.createElement(Uu,{...t},r)):i.createElement($,{...t},n)},Bu=p.default.span`display:flex;width:100%;min-width:0;overflow:hidden;direction:inherit;`,Hu=p.default($)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex-shrink:1;min-width:0;`,Uu=p.default($)`flex-shrink:0;white-space:nowrap;`,Vu=({id:e,children:t})=>i.createElement(zu,{id:e},t),zu=p.default.span`position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0;`,Bt=(e,t)=>e!=null&&e.startsWith("image")?t.A11Y_HINT_OPEN_IMAGE:t.A11Y_HINT_OPEN_FILE,Ht=({name:e,mimeType:t,selected:n},r)=>{var s;const o=t!=null&&t.startsWith("image")?r.A11Y_FILE_IMAGE(e):t!=null&&t.startsWith("video")?r.A11Y_FILE_VIDEO(e):r.A11Y_FILE_DOCUMENT(e);return n?((s=r.A11Y_FILE_SELECTED)==null?void 0:s.call(r,o))??`${o}, selected`:o},ae=(e,t)=>t?{describedByProps:{"aria-describedby":e},descriptionNode:u.createElement(Vu,{id:e,children:t})}:{describedByProps:{},descriptionNode:null},_t=e=>t=>{t.repeat||(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())},j=()=>{const{stringSet:e}=Y(),t=u.useId(),n=u.useId(),r=u.useId(),o=u.useId(),s=u.useId(),a=u.useId(),l=u.useId(),c=u.useId(),d=u.useId(),m=u.useId(),h=u.useId(),f=u.useId(),b=u.useId(),C=u.useId(),v=u.useId(),_=x=>x===e.A11Y_HINT_OPEN_CONVERSATION?ae(t,x):x===e.A11Y_HINT_OPEN_CONVERSATIONS?ae(n,x):(x===e.A11Y_HINT_CLOSE_CONVERSATION,ae(r,x)),y=ae(o,e.A11Y_HINT_OPEN_MENU),E=ae(s,e.A11Y_HINT_CLOSE_CONVERSATION),A=ae(a,e.A11Y_HINT_CONNECT_TO_AGENT),T=ae(l,e.A11Y_HINT_ATTACH_FILE),O=ae(c,e.A11Y_HINT_SEND_MESSAGE),w=ae(d,e.A11Y_HINT_VIEW_NEW_MESSAGES),N=ae(m,e.A11Y_HINT_SEND_REPLY),R=ae(h,e.A11Y_HINT_SELECT_RATING),k=ae(f,e.A11Y_HINT_SELECT_RATING),P=ae(b,e.A11Y_HINT_OPEN_CONVERSATION),I=x=>{const L=Bt(x,e);return x!=null&&x.startsWith("image")?ae(v,L):ae(C,L)};return{launcher:{button:({isOpened:x,opensConversationList:L})=>{const F=nc({intent:Ql({isOpened:x,opensConversationList:L}),strings:{openConversation:e.A11Y_OPEN_CONVERSATION,openConversationList:e.A11Y_OPEN_CONVERSATIONS,closeConversation:e.A11Y_CLOSE_CONVERSATION,closeConversationList:e.A11Y_CLOSE_CONVERSATIONS,hintOpenConversation:e.A11Y_HINT_OPEN_CONVERSATION,hintOpenConversationList:e.A11Y_HINT_OPEN_CONVERSATIONS,hintCloseConversation:e.A11Y_HINT_CLOSE_CONVERSATION}}),B=_(F.hint);return{props:{"aria-label":F.label,...B.describedByProps},hint:F.hint,descriptionNode:B.descriptionNode}}},messenger:{closeButton:{"aria-label":e.A11Y_CLOSE_MESSENGER},expandButton:x=>({"aria-label":x?e.A11Y_COLLAPSE_MESSENGER:e.A11Y_EXPAND_MESSENGER})},conversation:{menuButton:{props:{"aria-label":e.A11Y_MENU,...y.describedByProps},hint:e.A11Y_HINT_OPEN_MENU,descriptionNode:y.descriptionNode},closeConversationButton:{props:{"aria-label":e.A11Y_CLOSE_CONVERSATION,...E.describedByProps},hint:e.A11Y_HINT_CLOSE_CONVERSATION,descriptionNode:E.descriptionNode},handoffButton:{props:{"aria-label":e.A11Y_CONNECT_AGENT,...A.describedByProps},hint:e.A11Y_HINT_CONNECT_TO_AGENT,descriptionNode:A.descriptionNode},messageInput:{attachFileButton:{props:{"aria-label":e.A11Y_ATTACH_FILE,...T.describedByProps},hint:e.A11Y_HINT_ATTACH_FILE,descriptionNode:T.descriptionNode},sendButton:{props:{"aria-label":e.A11Y_SEND_MESSAGE,...O.describedByProps},hint:e.A11Y_HINT_SEND_MESSAGE,descriptionNode:O.descriptionNode},textInput:x=>({role:"textbox","aria-label":x})},suggestedReplies:{hint:e.A11Y_HINT_SEND_REPLY,descriptionNode:N.descriptionNode,item:(x,L)=>({props:{role:"button",tabIndex:0,"aria-label":`${e.A11Y_SUGGESTED_REPLY}, ${x}`,...N.describedByProps,onClick:L,onKeyDown:_t(L)}})},feedback:{hint:e.A11Y_HINT_SELECT_RATING,descriptionNode:R.descriptionNode,button:(x,L)=>({props:{"aria-label":x==="good"?e.FEEDBACK_GOOD:e.FEEDBACK_BAD,...R.describedByProps,"aria-pressed":L}}),optionsBottomSheet:{"aria-label":e.A11Y_FEEDBACK_OPTIONS}},newMessagesButton:{props:{"aria-label":e.A11Y_SCROLL_TO_NEW_MESSAGES,...w.describedByProps},hint:e.A11Y_HINT_VIEW_NEW_MESSAGES,descriptionNode:w.descriptionNode},startNewConversationButton:({onActivate:x})=>({role:"button",tabIndex:0,"aria-label":e.TALK_TO_AGENT,onClick:x,onKeyDown:_t(x)}),poweredByLink:{"aria-label":`${e.POWERED_BY} Sendbird`},retryButton:(x=e.RETRY)=>({"aria-label":x}),file:{label:(x,L)=>x?Ht({name:x,mimeType:L},e):"",preview:x=>({props:{"aria-label":Ht(x,e)}}),interactivePreview:x=>{const L=I(x.mimeType);return{props:{"aria-label":Ht(x,e),...L.describedByProps},hint:Bt(x.mimeType,e),descriptionNode:L.descriptionNode}},openDescription:x=>{const L=I(x);return{props:L.describedByProps,hint:Bt(x,e),descriptionNode:L.descriptionNode}},buttonLikeInteractivePreview:({onActivate:x,...L})=>{const F=I(L.mimeType);return{props:{role:"button",tabIndex:0,"aria-label":Ht(L,e),...F.describedByProps,onClick:x,onKeyDown:_t(x)},hint:Bt(L.mimeType,e),descriptionNode:F.descriptionNode}},removeButton:x=>({"aria-label":e.A11Y_FILE_REMOVE_BUTTON(x)})},csat:{scoresContainer:x=>({props:{role:"radiogroup","aria-label":x},descriptionNode:k.descriptionNode}),scoreButton:(x,L,F)=>{var B;return{props:{role:"radio","aria-checked":F,...k.describedByProps,"aria-label":((B=e.A11Y_CSAT_RATING_LABEL)==null?void 0:B.call(e,x,L))??e.A11Y_RATING_LABEL(x,L)}}},scoreItem:({score:x,label:L,selected:F,disabled:B,currentIndex:G,totalCount:J,hasSelection:me,onChange:We})=>{var qe;return{props:{disabled:B,onClick:()=>We(x),onKeyDown:M=>{var rt;if(B)return;let fe=null;switch(M.key){case"ArrowRight":case"ArrowDown":fe=(G+1)%J;break;case"ArrowLeft":case"ArrowUp":fe=(G-1+J)%J;break;default:return}M.preventDefault(),We(fe+1);const Te=M.currentTarget.parentElement,pe=Te==null?void 0:Te.querySelectorAll('[role="radio"]');(rt=pe==null?void 0:pe[fe])==null||rt.focus()},tabIndex:F||!me&&G===0?0:-1,role:"radio","aria-checked":F,"aria-disabled":B,...k.describedByProps,"aria-label":((qe=e.A11Y_CSAT_RATING_LABEL)==null?void 0:qe.call(e,x,L))??e.A11Y_RATING_LABEL(x,L)}}},submitButton:x=>({"aria-label":x})},form:{button:x=>({"aria-label":x}),textInput:(x,L,F)=>({"aria-label":x,"aria-required":L,"aria-disabled":F}),numberInput:(x,L,F)=>({"aria-label":x,"aria-required":L,"aria-disabled":F}),singleSelectGroup:x=>({role:"radiogroup",...x?{"aria-label":x}:{}}),singleSelectOption:(x,L,F)=>({role:"radio","aria-label":x,"aria-checked":L,"aria-disabled":F}),multiSelectOption:(x,L,F)=>({"aria-label":x,"aria-pressed":L,"aria-disabled":F})}},conversationList:{footer:{button:({onActivate:x})=>({role:"button",tabIndex:0,"aria-label":e.TALK_TO_AGENT,onClick:x,onKeyDown:_t(x)})},item:({agent:x,status:L,time:F,unreadCount:B,onActivate:G})=>{const J=typeof G<"u",me=J?P:{describedByProps:{},descriptionNode:null};return{props:{...J?{role:"button",tabIndex:0,onClick:G,onKeyDown:_t(G)}:{},...me.describedByProps,"aria-label":e.A11Y_CONVERSATION_ITEM(x,L,F,B)},hint:J?e.A11Y_HINT_OPEN_CONVERSATION:void 0,descriptionNode:J?me.descriptionNode:void 0}}}}},lr=({name:e,mimeType:t,type:n="FILE",iconColor:r,iconBackgroundColor:o,onClick:s,ariaLabel:a})=>{const{colors:l}=D.useTheme(),{conversation:c}=j(),d=s?c.file.interactivePreview({name:e,mimeType:t}):c.file.preview({name:e,mimeType:t}),m={...d,props:{...d.props,...a?{"aria-label":a}:{}}};return i.createElement(Gu,{as:s?"button":"div",type:s?"button":void 0,onClick:s,...m.props,$clickable:!!s},i.createElement(qu,{$bgColor:o??l.base.primary},i.createElement(U,{type:"file-document",size:24,color:r??l.base.primaryContrastContent})),i.createElement(Yu,null,i.createElement(us,{variant:"button",color:g.themedColor.textHighEmphasis},e),i.createElement($,{color:g.themedColor.textMidEmphasis,variant:"caption3"},n)),m.descriptionNode)},Gu=p.default.div`border:none;border-radius:12px;gap:8px;width:${z.BODY_MAX_WIDTH}px;height:64px;display:flex;align-items:center;padding:12px;box-sizing:border-box;border:1px solid ${g.themedColor.textDisabled};background-color:${g.themedColor.bg_50_600};${({$clickable:e})=>e&&Wu}`,Wu=D.css`cursor:pointer;&:hover{background-color:${g.themedColor.bg_100_500};}`,qu=p.default.div`border-radius:8px;width:40px;height:40px;display:flex;align-items:center;justify-content:center;background-color:${({$bgColor:e})=>e};`,Yu=p.default.div`display:flex;flex:1;flex-direction:column;gap:4px;min-width:0;`;function Ku({file:e,children:t,onClickFile:n}){const r=n?()=>n(e):void 0;return i.createElement(ju,null,i.createElement(lr,{name:e.name,mimeType:e.type,type:Wn(e.name,e.type),onClick:r}),t)}const ju=p.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${z.GAP_GROUPED}px;`,Oe=`${Ce}-incoming-msg`,Xu=`${Ce}-marked-text`;function Zu({file:e,onClickMedia:t,onClickMediaFiles:n,children:r}){const{conversation:o}=j(),s=e.type.startsWith("image"),a=(()=>{if(n)return()=>n({files:[{url:e.url,type:e.type,name:e.name}],index:0});if(t)return()=>t(e)})(),l=a?o.file.buttonLikeInteractivePreview({name:e.name,mimeType:e.type,onActivate:a}):o.file.preview({name:e.name,mimeType:e.type}),c=()=>s?i.createElement(ed,{src:e.url,alt:"image-message"}):e.type.startsWith("video")?i.createElement(td,{controls:!0},i.createElement("source",{src:e.url}),i.createElement("track",{kind:"captions"})):null;if(c){const d={id:`${Oe}-media-body`,...l.props};return i.createElement(Ju,null,i.createElement(Qu,{...d},c(),l.descriptionNode),r)}return null}const Ju=p.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${z.GAP_GROUPED}px;`,Qu=p.default.div`width:${z.BODY_MAX_WIDTH}px;height:160px;border-radius:12px;overflow:hidden;cursor:pointer;${V.light`
|
|
82
|
+
background-color: ${g.color.background100};
|
|
54
83
|
`}
|
|
55
|
-
${
|
|
56
|
-
background-color: ${
|
|
84
|
+
${V.dark`
|
|
85
|
+
background-color: ${g.color.background400};
|
|
57
86
|
`}
|
|
58
|
-
`,
|
|
59
|
-
background-color: ${
|
|
87
|
+
`,ed=p.default.img`width:100%;height:100%;object-fit:cover;`,td=p.default.video`width:100%;height:100%;object-fit:cover;`,tt=({className:e,children:t,size:n=26})=>i.createElement(nd,{className:e,$size:n},t??i.createElement(U,{type:"spinner",size:n})),nd=p.default.div`display:flex;align-items:center;justify-content:center;width:${({$size:e})=>we(e)};height:${({$size:e})=>we(e)};animation:1s infinite linear;animation-name:rotate;@keyframes rotate{from{transform:rotate(0);}to{transform:rotate(360deg);}}`,en=3,cn=6,rd=cn/en,od=en,sd=cn,id=e=>{const t=e%en;return{gridColumns:t>0?cn:en,wideBottomCount:t}},ds=({images:e,isPending:t=!1,onClickImage:n})=>{const{conversation:r}=j(),o=e.length;if(o===0)return null;const{gridColumns:s,wideBottomCount:a=0}=id(o),l=!!n&&!t,c=e.map(b=>b.type??"image/*"),d=c.find(b=>b.startsWith("image")),m=c.find(b=>!b.startsWith("image")),h=l&&d?r.file.openDescription(d):void 0,f=l&&m?r.file.openDescription(m):void 0;return i.createElement(ld,{$width:z.BODY_MAX_WIDTH,$columns:s},e.map((b,C)=>{const v=a>0&&C>=o-a,_=()=>!t&&(n==null?void 0:n(C)),y=b.type??"image/*",E=l?r.file.buttonLikeInteractivePreview({name:b.name||"",mimeType:y,onActivate:_}):r.file.preview({name:b.name||"",mimeType:y});let A=1;return s===cn&&(v?A=a===1?sd:od:A=rd),i.createElement(cd,{key:b.url,$clickable:l,$itemSpan:A,$isPending:t,...E.props},i.createElement(ad,{src:b.url,alt:b.name||""}),t&&i.createElement(ud,null))}),h==null?void 0:h.descriptionNode,f==null?void 0:f.descriptionNode)},ad=({src:e,alt:t})=>{const[n,r]=u.useState(!1),[o,s]=u.useState(!1);return i.createElement(i.Fragment,null,!n&&!o&&i.createElement(dd,null,i.createElement(tt,{size:20},i.createElement(U,{type:"spinner",color:"textLowEmphasis",size:20}))),o?i.createElement(md,null,i.createElement(U,{type:"photo",color:"textLowEmphasis",size:24})):i.createElement(hd,{src:e,alt:t,$loaded:n,onLoad:()=>r(!0),onError:()=>s(!0)}))},ld=p.default.div`display:grid;grid-template-columns:repeat(${({$columns:e})=>e},1fr);width:${({$width:e})=>e}px;gap:2px;border-radius:16px;overflow:hidden;`,cd=p.default.div`position:relative;width:100%;aspect-ratio:1;overflow:hidden;cursor:${e=>e.$clickable?"pointer":"default"};${V.light`
|
|
88
|
+
background-color: ${g.color.background100};
|
|
60
89
|
`}
|
|
61
|
-
${
|
|
62
|
-
background-color: ${
|
|
90
|
+
${V.dark`
|
|
91
|
+
background-color: ${g.color.background400};
|
|
63
92
|
`}
|
|
64
93
|
${e=>e.$itemSpan&&e.$itemSpan>1&&`
|
|
65
94
|
grid-column: span ${e.$itemSpan};
|
|
66
95
|
aspect-ratio: ${e.$itemSpan/2};
|
|
67
96
|
`}
|
|
68
97
|
|
|
98
|
+
&:focus-visible {
|
|
99
|
+
outline: 2px solid ${g.color.primary.main};
|
|
100
|
+
outline-offset: -2px;
|
|
101
|
+
}
|
|
102
|
+
|
|
69
103
|
&:hover {
|
|
70
104
|
${e=>e.$clickable&&!e.$isPending&&`
|
|
71
105
|
& > img {
|
|
@@ -73,29 +107,58 @@
|
|
|
73
107
|
}
|
|
74
108
|
`}
|
|
75
109
|
}
|
|
76
|
-
`,
|
|
77
|
-
background-color: ${
|
|
110
|
+
`,ud=p.default.div`position:absolute;top:0;left:0;width:100%;height:100%;background-color:${g.color.overlay.dark};pointer-events:none;`,ms=p.default.div`display:flex;align-items:center;justify-content:center;`,dd=p.default(ms)`position:absolute;inset:0;`,md=p.default(ms)`position:absolute;inset:0;${V.light`
|
|
111
|
+
background-color: ${g.color.background200};
|
|
78
112
|
`}
|
|
79
|
-
${
|
|
80
|
-
background-color: ${
|
|
113
|
+
${V.dark`
|
|
114
|
+
background-color: ${g.color.background500};
|
|
81
115
|
`}
|
|
82
|
-
`,
|
|
116
|
+
`,hd=p.default.img`position:absolute;inset:0;width:100%;height:100%;object-fit:cover;opacity:${({$loaded:e})=>e?1:0};transition:opacity 0.3s ease;`,gd=({files:e,children:t,onClickMedia:n,onClickMediaFiles:r})=>{const o=s=>{const a=e[s];a&&(r?r({files:e,index:s}):n&&n({url:a.url,type:a.type||"image/*"}))};return i.createElement(fd,null,i.createElement(ds,{images:e,onClickImage:o}),t)},fd=p.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${z.GAP_GROUPED}px;`,pd="✱",hs=e=>{const t=new RegExp(`(\`+)([^\`]+?)\\1|(${pd}+)`,"g");return e.replace(t,(n,r,o,s)=>r?n:s?`<span id=${Xu} aria-label="masked-text">${s}</span>`:n)},_d=e=>e.replace(/\*\*(.*?)\*\*/g,"<b>$1</b>"),jr=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)}}},Ed=u.lazy(async()=>({default:(await Promise.resolve().then(()=>require("./cjs/D2Opuq0j.cjs"))).MarkdownText})),bd=u.lazy(async()=>({default:(await Promise.resolve().then(()=>require("./cjs/DlvEEpWX.cjs"))).CodeBlock}));function Cd(e){var o,s;const t=e.maxBodyWidth??z.BODY_MAX_WIDTH,n=u.useMemo(()=>pi(e.message,hs),[e.message]),r={id:`${Oe}-text-body`,$maxWidth:t,$color:(o=e.customStyle)==null?void 0:o.bubbleContentColor,$bgColor:(s=e.customStyle)==null?void 0:s.bubbleBackgroundColor};return n.length===0?e.children?i.createElement(Xr,{...r},e.children):null:i.createElement(Xr,{...r},n.map((a,l)=>a.type==="text"?i.createElement(Zr,{key:l,variant:"body3"},i.createElement(Qt,{fallback:a.value},i.createElement(Ed,{onClickImage:c=>{var d;return(d=e.onClickMedia)==null?void 0:d.call(e,{url:c,type:"image/*"})}},a.value))):a.type==="code"?i.createElement(Qt,{key:l,fallback:i.createElement(Zr,{variant:"body3"},a.value)},i.createElement(bd,{code:a.value,language:a.language})):null),e.children)}const Xr=p.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})=>D.css`
|
|
83
117
|
color: ${t||e.colors.messageIncoming.text};
|
|
84
118
|
background-color: ${n||e.colors.messageIncoming.background};
|
|
85
119
|
`}
|
|
86
120
|
padding: 12px 0;
|
|
87
121
|
transition: max-width 0.3s;
|
|
88
122
|
overflow-wrap: break-word;
|
|
89
|
-
`,
|
|
123
|
+
`,Zr=p.default($)`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:o}){return i.createElement(vd,{id:e,tabIndex:0,onClick:r,$size:we(n),style:o},t?i.createElement(yd,{src:t}):i.createElement(U,{type:"user",size:n}))}const vd=p.default.div`border-radius:50%;display:inline-block;overflow:hidden;position:relative;flex-shrink:0;height:${e=>e.$size};width:${e=>e.$size};background-color:${g.themedColor.bg_100_500};&:focus{outline:none;}${de}`,yd=p.default.img`object-fit:cover;width:100%;height:100%;position:absolute;`,Sd=({sender:e,isBotMessage:t})=>{const n=`${Oe}-sender-avatar`;return t&&!e.profileUrl?i.createElement(xd,{id:n},i.createElement(U,{type:"delight",size:"100%"})):i.createElement(gs,{id:n,size:z.AVATAR_SIZE,src:e.profileUrl})},xd=p.default.div`flex-shrink:0;width:${z.AVATAR_SIZE}px;height:${z.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;}}`,Ad=({sender:e})=>i.createElement(Td,{id:`${Oe}-sender-name`,variant:"caption1",color:g.themedColor.textMidEmphasis},e.nickname),Td=p.default($)`text-align:start;width:100%;box-sizing:border-box;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding-block:5px;padding-inline:0 7px;`,Id=({createdAt:e})=>{const{stringSet:t,format:n}=Y();return e?i.createElement($,{id:`${Oe}-sent-time`,variant:"caption4",color:g.themedColor.textLowEmphasis},n(e,t.DATE_FORMAT__MESSAGE_TIMESTAMP)):null},fs="(prefers-reduced-motion: reduce)",wd=()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(fs).matches,ps=()=>{const[e,t]=u.useState(wd);return u.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const n=window.matchMedia(fs);t(n.matches);const r=o=>{t(o.matches)};return typeof n.addEventListener=="function"?(n.addEventListener("change",r),()=>{n.removeEventListener("change",r)}):(n.addListener(r),()=>{n.removeListener(r)})},[]),e},kd=({thinkingMessage:e,customStyle:t})=>{const n=ps();return e?i.createElement(Od,{$prefersReducedMotion:n},i.createElement(Rd,null,e),!n&&i.createElement(Nd,null)):i.createElement(Md,{$bgColor:t==null?void 0:t.bubbleBackgroundColor},[0,1,2].map(r=>i.createElement(Ld,{key:r,$color:t==null?void 0:t.bubbleContentColor,$prefersReducedMotion:n})))},Md=p.default.div`align-items:center;border-radius:16px;display:flex;gap:6px;height:26px;justify-content:center;padding:0 12px;background-color:${({theme:e,$bgColor:t})=>t||e.colors.messageIncoming.background};`,Ld=p.default.span`animation:${({$prefersReducedMotion:e})=>e?"none":"blink 1.4s infinite"};animation-fill-mode:both;border-radius:50%;height:8px;width:8px;background:${({theme:e,$color:t})=>t||e.colors.messageIncoming.text};opacity:${({$prefersReducedMotion:e})=>e?.38:void 0};@keyframes blink{0%{opacity:0.12;transform:scale(1);}21.43%{opacity:0.38;transform:scale(1.2);}42.86%{opacity:0.12;transform:scale(1);}100%{opacity:0.12;transform:scale(1);}}&:nth-child(1){animation-delay:0.4s;}&:nth-child(2){animation-delay:0.6s;}&:nth-child(3){animation-delay:0.8s;}`,Od=p.default.div`position:relative;overflow:hidden;animation:${({$prefersReducedMotion:e})=>e?"none":"fadeIn 0.4s ease-in-out"};@keyframes fadeIn{from{opacity:0;}to{opacity:1;}}`,Rd=p.default($).attrs({variant:"body3"})`
|
|
90
124
|
white-space: pre-wrap;
|
|
91
125
|
word-break: break-word;
|
|
92
|
-
color: ${
|
|
93
|
-
`,
|
|
94
|
-
|
|
95
|
-
|
|
126
|
+
color: ${g.themedColor.textHighEmphasis};
|
|
127
|
+
`,Nd=p.default.div`position:absolute;inset:0;pointer-events:none;background-size:33% 100%;background-repeat:no-repeat;animation:shimmerSweepLtr 1.6s linear infinite;@keyframes shimmerSweepLtr{from{background-position:-33% 0;}to{background-position:133% 0;}}[dir='rtl'] &{animation-name:shimmerSweepRtl;@keyframes shimmerSweepRtl{from{background-position:133% 0;}to{background-position:-33% 0;}}}background-image:${({theme:e})=>{const t=Ir(e.colors.base.background,.5),n=Ir(e.colors.base.background,0);return`linear-gradient(90deg, ${n} 0%, ${t} 30%, ${t} 60%, ${n} 100%)`}};
|
|
128
|
+
`,$d=({extendedMessagePayload:e,onClickCTA:t=({url:n})=>ir(n)})=>{const n=e==null?void 0:e.cta_button;if(!n)return null;const r=()=>t(n);return i.createElement(Dd,{id:`${Oe}-ext-cta-button`,onClick:r},i.createElement(Pd,{variant:"button"},n.label))},Dd=p.default.button.attrs({type:"button"})`
|
|
129
|
+
all: unset;
|
|
130
|
+
display: flex;
|
|
131
|
+
width: 100%;
|
|
132
|
+
box-sizing: border-box;
|
|
133
|
+
align-items: center;
|
|
134
|
+
justify-content: center;
|
|
135
|
+
cursor: pointer;
|
|
136
|
+
border-radius: 6px;
|
|
137
|
+
padding: 8px;
|
|
138
|
+
color: ${g.themedColor.textHighEmphasis};
|
|
139
|
+
background-color: ${g.color.background50};
|
|
140
|
+
${V.dark`
|
|
141
|
+
background-color: ${g.color.ondark.textDisabled};
|
|
96
142
|
`}
|
|
97
|
-
|
|
98
|
-
|
|
143
|
+
|
|
144
|
+
${de}
|
|
145
|
+
`,Pd=p.default($)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,Fd=({extendedMessagePayload:e,onClickCitation:t=n=>ir(n.link)})=>{const{stringSet:n}=Y(),{theme:r}=Qn(),o=e==null?void 0:e.citations;return!o||o.length===0?null:i.createElement(Bd,{id:`${Oe}-ext-citation`},i.createElement(Hd,{variant:"caption1",color:r.colors.messageIncoming.text},n.CITATION_SOURCE_TITLE),i.createElement(Ud,null,o.map((s,a)=>i.createElement(zd,{key:`${s.embedding_id}-${a}`,onClick:()=>t(s)},i.createElement(U,{type:"source",size:16,color:r.colors.messageIncoming.text}),i.createElement(Vd,{variant:"body3",color:r.colors.messageIncoming.text},s.title)))))},Bd=p.default.div`display:flex;flex-direction:column;gap:8px;border-radius:8px;padding:8px 12px 6px;`,Hd=p.default($)`opacity:0.5;`,Ud=p.default.div`display:flex;flex-direction:column;gap:8px;`,Vd=p.default($)`text-decoration:underline;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,zd=p.default.button.attrs({type:"button"})`
|
|
146
|
+
background: none;
|
|
147
|
+
border: none;
|
|
148
|
+
padding: 0;
|
|
149
|
+
font: inherit;
|
|
150
|
+
color: inherit;
|
|
151
|
+
|
|
152
|
+
display: flex;
|
|
153
|
+
align-items: center;
|
|
154
|
+
gap: 4px;
|
|
155
|
+
cursor: pointer;
|
|
156
|
+
|
|
157
|
+
&:hover {
|
|
158
|
+
opacity: 0.5;
|
|
159
|
+
}
|
|
160
|
+
`,Gd=e=>i.createElement(i.Fragment,null),Wd=({visible:e,onClose:t,children:n,"aria-label":r})=>i.createElement(ut,{rootElementId:ne.WINDOW,visible:e,onClose:t,"aria-label":r},i.createElement(jd,null,n)),qd=({onClick:e,destructive:t,icon:n,children:r})=>i.createElement(Yd,{onClick:e,$destructive:t},n&&i.createElement(Kd,null,i.createElement(U,{type:n,size:24,color:g.themedColor.primary})),r),Be=Object.assign(Wd,{ActionItem:qd}),Yd=p.default.button`all:unset;display:flex;align-items:center;gap:24px;width:100%;padding:12px 24px;cursor:pointer;color:${({$destructive:e})=>e?g.themedColor.error:g.themedColor.textHighEmphasis};${de}`,Kd=p.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,jd=p.default.div`position:absolute;left:0;right:0;bottom:0;border-radius:12px 12px 0 0;flex-direction:column;align-items:flex-end;margin:0 auto;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,_s=({enabled:e=!0,focusRoot:t})=>{const[n,r]=u.useState(!1),o=u.useRef(!1),s=u.useRef(!1);u.useEffect(()=>{if(!e){r(!1);return}const d=h=>{const f=h;f.metaKey||f.altKey||f.ctrlKey||(o.current=!0)},m=()=>{o.current=!1,r(!1)};return t.addEventListener("keydown",d),t.addEventListener("pointerdown",m),()=>{t.removeEventListener("keydown",d),t.removeEventListener("pointerdown",m)}},[e,t]);const a=u.useCallback(()=>{if(s.current){s.current=!1,r(!1);return}r(o.current)},[]),l=u.useCallback(()=>{r(!1)},[]),c=u.useCallback(()=>{s.current=!0,r(!1)},[]);return{isFocusVisible:n,suppressNextFocusVisible:c,focusHandlers:{onFocus:a,onBlur:l}}},Un=e=>`${e}-filled`,Xd=e=>e==="good"?ue.AIAgentMessageFeedbackRating.GOOD:ue.AIAgentMessageFeedbackRating.BAD,Es=D.css`&:hover{opacity:0.8;}&:active{opacity:0.6;}`,Jr={good:g.themedColor.secondary,bad:g.themedColor.error},Zd=({visible:e,onClose:t,isEdit:n,initialRating:r,initialComment:o="",onSubmit:s,isCommentEnabled:a=!1})=>{const{stringSet:l}=Y(),{rootElement:c}=or(),d=Le(c),[m,h]=u.useState(r),[f,b]=u.useState(o),{focusHandlers:C,isFocusVisible:v}=_s({focusRoot:d,enabled:e});u.useLayoutEffect(()=>{e?(h(r),b(o)):(h(void 0),b(""))},[e,r,o]);const _=()=>{m&&(s({rating:m,comment:f.trim()||void 0}),t())},y=()=>{t()};return e?i.createElement(ut,{rootElementId:ne.WINDOW,visible:e,onClose:y,"aria-label":l.FEEDBACK_TITLE},i.createElement(Jd,null,i.createElement(Qd,null,i.createElement($,{variant:"h2",color:g.themedColor.textHighEmphasis},l.FEEDBACK_TITLE)),i.createElement(em,null,i.createElement(tm,null,["good","bad"].map(E=>{const A=m===E,T=E==="good"?l.FEEDBACK_GOOD:l.FEEDBACK_BAD;return i.createElement(nm,{key:E,$selected:A,$rating:E,onClick:()=>h(E)},i.createElement(U,{type:A?Un(E):E,size:24,color:A?Jr[E]:g.themedColor.textLowEmphasis}),i.createElement($,{variant:"caption1",color:A?Jr[E]:g.themedColor.textLowEmphasis},T))})),a&&i.createElement(rm,null,i.createElement($,{variant:"caption3",color:g.themedColor.textHighEmphasis},l.FEEDBACK_COMMENT_LABEL),i.createElement(om,{placeholder:l.FEEDBACK_COMMENT_PLACEHOLDER,value:f,onChange:E=>b(E.target.value),onFocus:C.onFocus,onBlur:C.onBlur,maxLength:100,$focusVisible:v,"data-focus-visible":v?"true":"false"}))),i.createElement(sm,null,i.createElement(im,{onClick:y},i.createElement($,{variant:"button",color:g.themedColor.textHighEmphasis},l.FEEDBACK_CANCEL)),i.createElement(am,{onClick:_,disabled:!m},i.createElement($,{variant:"button"},n?l.FEEDBACK_SAVE:l.FEEDBACK_SUBMIT))))):null},Jd=p.default.div`width:280px;background-color:${({theme:e})=>e.colors.base.modalContentBackground};border-radius:12px;overflow:hidden;`,Qd=p.default.div`padding:24px;`,em=p.default.div`padding-inline:24px;display:flex;flex-direction:column;gap:24px;`,tm=p.default.div`display:flex;gap:4px;`,nm=p.default.button`width:114px;height:64px;border-radius:12px;border:1px solid ${g.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?g.color.background100:"transparent"};${({$selected:e})=>V.dark`
|
|
161
|
+
background-color: ${e?g.color.background600:"transparent"};
|
|
99
162
|
`}
|
|
100
163
|
|
|
101
164
|
&:hover {
|
|
@@ -105,213 +168,244 @@
|
|
|
105
168
|
&:active {
|
|
106
169
|
opacity: 0.6;
|
|
107
170
|
}
|
|
108
|
-
`,
|
|
109
|
-
|
|
110
|
-
|
|
171
|
+
`,rm=p.default.div`display:flex;flex-direction:column;gap:6px;`,om=p.default.textarea`font-family:inherit;font-size:12px;line-height:16px;border:1px solid ${g.themedColor.textDisabled};border-radius:4px;padding:6px 12px;color:${g.themedColor.textHighEmphasis};background-color:${g.themedColor.textLowEmphasisInverse};resize:none;field-sizing:content;min-height:28px;max-height:118px;overflow-y:auto;&::placeholder{color:${g.themedColor.textLowEmphasis};}&:focus{outline:none;}${({$focusVisible:e})=>e&&D.css`
|
|
172
|
+
outline: 2px solid ${g.themedColor.primary};
|
|
173
|
+
outline-offset: 2px;
|
|
174
|
+
`}
|
|
175
|
+
`,sm=p.default.div`padding-inline:24px;padding-block:16px;display:flex;justify-content:flex-end;gap:4px;`,bs=p.default.button`width:86px;height:40px;border-radius:20px;border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:opacity 0.2s;`,im=p.default(bs)`${Es}`,am=p.default(bs)`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};}`,Qr={good:g.themedColor.secondary,bad:g.themedColor.error},lm=({isBotMessage:e,isConversationClosed:t,isStreaming:n,isFeedbackEnabled:r,isFeedbackCommentEnabled:o,extendedMessagePayload:s,onFeedbackUpdate:a})=>{const{stringSet:l}=Y(),{conversation:c}=j(),[d,m]=u.useState(!1),[h,f]=u.useState(!1),[b,C]=u.useState(void 0),[v,_]=u.useState(""),y=c.feedback,E=s==null?void 0:s.feedback,A=(E==null?void 0:E.rating)??"none";if(A!=="none"?!1:!!(n||!e||!r||(s==null?void 0:s.bot_message_type)!=="generated"||t))return null;const O=k=>{A==="none"?(C(k),_(""),m(!0)):f(!0)},w=()=>{a==null||a(null),f(!1)},N=()=>{f(!1),C(E==null?void 0:E.rating),_((E==null?void 0:E.comment)??""),m(!0)},R=k=>{a==null||a(k)};return t&&A!=="none"?i.createElement(eo,{$horizontal:!0},i.createElement(cm,null,i.createElement(U,{type:Un(A),size:12,color:Qr[A]})),(E==null?void 0:E.comment)&&i.createElement(to,{variant:"caption2",style:{lineHeight:"16px"}},E.comment)):i.createElement(i.Fragment,null,i.createElement(eo,null,i.createElement(um,null,["good","bad"].map(k=>{const P=A===k,I=y.button(k,P);return i.createElement(dm,{key:k,$selected:P,$rating:k,...I.props,onClick:()=>O(k)},i.createElement(U,{type:P?Un(k):k,size:14,color:P?Qr[k]:g.themedColor.textMidEmphasis}))})),y.descriptionNode,A!=="none"&&(E==null?void 0:E.comment)&&i.createElement(to,{variant:"caption2"},E.comment)),i.createElement(Be,{visible:h,onClose:()=>f(!1),...y.optionsBottomSheet},i.createElement(Be.ActionItem,{onClick:N},l.FEEDBACK_EDIT),i.createElement(Be.ActionItem,{onClick:w,destructive:!0},l.FEEDBACK_REMOVE)),i.createElement(Zd,{visible:d,onClose:()=>m(!1),isEdit:A!=="none",initialRating:b,initialComment:v,onSubmit:R,isCommentEnabled:o}))},eo=p.default.div`display:flex;flex-direction:${({$horizontal:e})=>e?"row":"column"};align-items:${({$horizontal:e})=>e?"flex-start":"stretch"};gap:4px;margin-top:8px;word-break:break-word;max-width:${z.BODY_MAX_WIDTH}px;`,cm=p.default.div`padding:2px;flex-shrink:0;display:flex;align-items:center;`,um=p.default.div`display:flex;gap:2px;`,dm=p.default.button`width:38px;height:20px;border-radius:18px;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0;transition:opacity 0.2s;border:1px solid ${g.color.background200};background-color:${({$selected:e})=>e?g.color.background100:"transparent"};${({$selected:e})=>V.dark`
|
|
176
|
+
border: 1px solid ${g.color.background400};
|
|
177
|
+
background-color: ${e?g.color.background500:"transparent"};
|
|
111
178
|
`}
|
|
112
179
|
|
|
113
|
-
${
|
|
114
|
-
`,
|
|
115
|
-
color: ${
|
|
180
|
+
${Es}
|
|
181
|
+
`,to=p.default($)`color:${g.themedColor.textMidEmphasis};${V.dark`
|
|
182
|
+
color: ${g.themedColor.textHighEmphasis};
|
|
116
183
|
`}
|
|
117
|
-
`,
|
|
118
|
-
background-color: ${
|
|
184
|
+
`,cr=D.css`width:100%;height:36px;border-radius:6px;cursor:pointer;transition:all 0.2s ease;padding:0 12px;border:none;outline:none;display:flex;align-items:center;justify-content:center;${de}&:disabled{cursor:not-allowed;}`,no=p.default.button`${cr};background-color:${g.themedColor.primary};color:${g.themedColor.textHighEmphasis};&:hover:not(:disabled){opacity:0.9;}`,mm=p.default.button`${cr};color:${g.themedColor.primary};${V.light`
|
|
185
|
+
background-color: ${g.color.background50};
|
|
119
186
|
`};
|
|
120
|
-
${
|
|
121
|
-
background-color: ${
|
|
187
|
+
${V.dark`
|
|
188
|
+
background-color: ${g.color.background700};
|
|
122
189
|
`};
|
|
123
190
|
|
|
124
191
|
&:hover:not(:disabled) {
|
|
125
192
|
opacity: 0.9;
|
|
126
193
|
}
|
|
127
|
-
`,
|
|
128
|
-
background-color: ${
|
|
194
|
+
`,hm=p.default.button`${cr};background-color:transparent;color:${g.themedColor.textHighEmphasis};&:hover:not(:disabled){opacity:0.7;}`,gm=e=>{switch(e){case"primary":return no;case"secondary":return mm;case"clear":return hm;default:return no}},fm=p.default.div`animation:1s infinite linear;animation-name:rotate;display:flex;align-items:center;justify-content:center;@keyframes rotate{from{transform:rotate(0);}to{transform:rotate(360deg);}}`,pm=({children:e,onClick:t,variant:n="primary",disabled:r=!1,loading:o=!1,className:s,ariaLabel:a})=>{const l=()=>{switch(n){case"primary":return g.themedColor.textHighEmphasisInverse;case"secondary":return g.themedColor.primary;case"clear":return g.themedColor.textHighEmphasis;default:return g.themedColor.textHighEmphasisInverse}},c=gm(n);return i.createElement(c,{onClick:t,disabled:r||o,className:s,"aria-label":a},o?i.createElement(fm,null,i.createElement(U,{type:"spinner",size:22,color:l()})):i.createElement($,{variant:"button",color:l()},e))},_m=({children:e,className:t,style:n})=>i.createElement($,{variant:"caption4",color:g.themedColor.error,className:t,style:n},e),Em=({children:e,className:t,style:n,required:r})=>{const{stringSet:o}=Y();return i.createElement($,{variant:"caption3",color:g.themedColor.textMidEmphasis,className:t,style:n},e,!r&&i.createElement("span",{style:{color:g.themedColor.textLowEmphasis}},` (${o.OPTIONAL})`))},bm=({value:e,onChange:t,placeholder:n,error:r=!1,submitted:o=!1,className:s,disabled:a=!1,max:l,ariaLabel:c,required:d=!1})=>{const m=f=>{const C=f.target.value.replace(/[^0-9.-]/g,""),v=C.split("."),y=v.length>1?v[0]+"."+v.slice(1).join("").replace(/\./g,""):C;if(f.target.value=y,y===""||y==="-")t==null||t(null);else{const E=Number(y);if(!isNaN(E)){if(l!==void 0&&E>l)return;t==null||t(E)}}},h=e==null?"":String(e);return i.createElement(xm,{type:"text",value:h,onChange:m,placeholder:n,className:s,disabled:a||o,inputMode:"decimal","aria-label":c,"aria-required":d,"aria-disabled":a||o,$error:r,$submitted:o})},Cm=D.css`width:100%;height:36px;padding:8px 12px;border-radius:6px;font-size:14px;font-weight:400;line-height:1.43;outline:none;transition:all 0.2s ease;${de}&::placeholder{color:${g.themedColor.textLowEmphasis};}&::-webkit-inner-spin-button,&::-webkit-outer-spin-button{-webkit-appearance:none;margin:0;}`,vm=D.css`color:${g.themedColor.textHighEmphasis};border:1px solid transparent;cursor:not-allowed;${V.light`
|
|
195
|
+
background-color: ${g.color.ondark.textMidEmphasis};
|
|
129
196
|
`}
|
|
130
|
-
${
|
|
131
|
-
background-color: ${
|
|
197
|
+
${V.dark`
|
|
198
|
+
background-color: ${g.color.onlight.textLowEmphasis};
|
|
132
199
|
`}
|
|
133
200
|
|
|
134
201
|
&::placeholder {
|
|
135
|
-
color: ${
|
|
202
|
+
color: ${g.themedColor.textLowEmphasis};
|
|
136
203
|
}
|
|
137
|
-
`,
|
|
138
|
-
background-color: ${
|
|
204
|
+
`,ym=D.css`border:1px solid ${g.themedColor.error};color:${g.themedColor.textHighEmphasis};${V.light`
|
|
205
|
+
background-color: ${g.color.background50};
|
|
139
206
|
`}
|
|
140
|
-
${
|
|
141
|
-
background-color: ${
|
|
207
|
+
${V.dark`
|
|
208
|
+
background-color: ${g.color.onlight.textLowEmphasis};
|
|
142
209
|
`}
|
|
143
|
-
`,
|
|
144
|
-
background-color: ${
|
|
210
|
+
`,Sm=D.css`border:1px solid ${g.themedColor.textDisabled};color:${g.themedColor.textHighEmphasis};${V.light`
|
|
211
|
+
background-color: ${g.color.background50};
|
|
145
212
|
`}
|
|
146
|
-
${
|
|
147
|
-
background-color: ${
|
|
213
|
+
${V.dark`
|
|
214
|
+
background-color: ${g.color.onlight.textLowEmphasis};
|
|
148
215
|
`}
|
|
149
216
|
|
|
150
217
|
&:focus {
|
|
151
|
-
border-color: ${
|
|
218
|
+
border-color: ${g.themedColor.primary};
|
|
152
219
|
}
|
|
153
|
-
`,
|
|
220
|
+
`,xm=p.default.input`${Cm}${({$error:e,$submitted:t})=>t?vm:e?ym:Sm}`,Am=e=>{if(e.multiple){const{value:t=[],onChange:n,maxSelect:r,submitted:o=!1}=e;return{selectedValues:t,handleOptionClick:a=>{if(o)return;if(t.includes(a)){const c=t.filter(d=>d!==a);n==null||n(c)}else{if(r&&t.length>=r)return;const c=[...t,a];n==null||n(c)}}}}else{const{value:t,onChange:n,submitted:r=!1}=e;return{selectedValues:t?[t]:[],handleOptionClick:s=>{r||t!==s&&(n==null||n(s))}}}},Cs=e=>{const{options:t,submitted:n=!1,error:r=!1,className:o,groupLabel:s}=e,{conversation:a}=j(),l=e.multiple===!0,{selectedValues:c,handleOptionClick:d}=Am(e),m=l?void 0:a.form.singleSelectGroup(s),h=u.useRef([]),f=l?-1:Math.max(t.findIndex(C=>c.includes(C.value)),0),b=(C,v)=>{var E;if(l||n)return;let _=null;switch(C.key){case"ArrowRight":case"ArrowDown":_=(v+1)%t.length;break;case"ArrowLeft":case"ArrowUp":_=(v-1+t.length)%t.length;break;default:return}C.preventDefault();const y=t[_];y&&(d(y.value),(E=h.current[_])==null||E.focus())};return i.createElement(Im,{className:o,...m},t.map((C,v)=>{const _=c.includes(C.value),y=s?`${s}, ${C.label}`:C.label,E=l?a.form.multiSelectOption(y,_,n):a.form.singleSelectOption(y,_,n);return i.createElement(Nm,{key:C.value,ref:A=>{h.current[v]=A},type:"button",$active:_,$submitted:n,$error:r,...E,disabled:n,onClick:()=>d(C.value),onKeyDown:A=>b(A,v),tabIndex:l?void 0:v===f?0:-1},i.createElement($,{variant:"caption1",color:Tm(_,n)},C.label))}))},Tm=(e,t)=>t?e?g.themedColor.textHighEmphasis:g.themedColor.textDisabled:e?g.themedColor.primary:g.themedColor.textMidEmphasis,Im=p.default.div`display:flex;flex-wrap:wrap;gap:4px 2px;`,wm=D.css`display:inline-flex;align-items:center;padding:8px 12px;border-radius:15px;transition:all 0.2s ease;`,km=D.css`cursor:default;background-color:${g.color.ondark.textMidEmphasis};color:${g.themedColor.textHighEmphasis};${V.dark`
|
|
154
221
|
background-color: transparent;
|
|
155
222
|
border: 1px solid white;
|
|
156
223
|
color: white;
|
|
157
224
|
`}
|
|
158
|
-
`,
|
|
159
|
-
background-color: ${
|
|
160
|
-
color: ${
|
|
225
|
+
`,Mm=D.css`cursor:default;${V.light`
|
|
226
|
+
background-color: ${g.color.ondark.textMidEmphasis};
|
|
227
|
+
color: ${g.themedColor.textDisabled};
|
|
161
228
|
`}
|
|
162
|
-
${
|
|
163
|
-
background-color: ${
|
|
164
|
-
border: 1px solid ${
|
|
165
|
-
color: ${
|
|
229
|
+
${V.dark`
|
|
230
|
+
background-color: ${g.color.onlight.textLowEmphasis};
|
|
231
|
+
border: 1px solid ${g.color.onlight.textLowEmphasis};
|
|
232
|
+
color: ${g.themedColor.textDisabled};
|
|
166
233
|
`}
|
|
167
|
-
`,
|
|
168
|
-
background-color: ${
|
|
169
|
-
color: ${
|
|
234
|
+
`,Lm=D.css`cursor:pointer;border:1px solid ${g.themedColor.primary};${V.light`
|
|
235
|
+
background-color: ${g.color.background50};
|
|
236
|
+
color: ${g.themedColor.primary};
|
|
170
237
|
`}
|
|
171
|
-
${
|
|
172
|
-
background-color: ${
|
|
173
|
-
color: ${
|
|
238
|
+
${V.dark`
|
|
239
|
+
background-color: ${g.color.onlight.textLowEmphasis};
|
|
240
|
+
color: ${g.themedColor.primary};
|
|
174
241
|
`}
|
|
175
|
-
`,
|
|
176
|
-
background-color: ${
|
|
177
|
-
color: ${
|
|
242
|
+
`,Om=D.css`cursor:pointer;border:1px solid ${g.themedColor.textDisabled};${V.light`
|
|
243
|
+
background-color: ${g.color.background50};
|
|
244
|
+
color: ${g.themedColor.textMidEmphasis};
|
|
178
245
|
`}
|
|
179
|
-
${
|
|
180
|
-
background-color: ${
|
|
181
|
-
color: ${
|
|
246
|
+
${V.dark`
|
|
247
|
+
background-color: ${g.color.onlight.textLowEmphasis};
|
|
248
|
+
color: ${g.themedColor.textMidEmphasis};
|
|
182
249
|
`}
|
|
183
|
-
`,
|
|
184
|
-
${r} ${
|
|
250
|
+
`,Rm=D.css`border-color:${g.themedColor.error}!important;`,Nm=p.default.button`${wm}${({$active:e,$submitted:t,$error:n})=>{if(t)return e?km:Mm;const r=e?Lm:Om;return n?D.css`
|
|
251
|
+
${r} ${Rm}
|
|
185
252
|
`:r}}
|
|
186
|
-
|
|
187
|
-
background-color: ${
|
|
253
|
+
`,$m=e=>i.createElement(Cs,{...e,multiple:!1}),Dm=e=>i.createElement(Cs,{...e,multiple:!0}),Pm=p.default.div`width:100%;height:1px;background-color:${g.themedColor.textDisabled};`,Fm=({className:e})=>i.createElement(Pm,{className:e}),Bm=({value:e="",onChange:t,placeholder:n,variant:r="single-line",error:o=!1,submitted:s=!1,className:a,disabled:l=!1,maxLength:c,ariaLabel:d,required:m=!1})=>{const f={value:e,onChange:b=>{const C=b.target.value;c&&C.length>c||t==null||t(C)},placeholder:n,className:a,disabled:l||s,maxLength:c,"aria-label":d,"aria-required":m,"aria-disabled":l||s,$error:o,$submitted:s};return r==="multi-line"?i.createElement(Um,{...f}):i.createElement(Hm,{...f})},vs=D.css`width:100%;padding:8px 12px;border-radius:6px;font-size:14px;font-weight:400;line-height:1.43;outline:none;transition:all 0.2s ease;${de}&::placeholder{color:${g.themedColor.textLowEmphasis};}`,ys=D.css`color:${g.themedColor.textHighEmphasis};border:1px solid transparent;cursor:not-allowed;${V.light`
|
|
254
|
+
background-color: ${g.color.ondark.textMidEmphasis};
|
|
188
255
|
`}
|
|
189
|
-
${
|
|
190
|
-
background-color: ${
|
|
256
|
+
${V.dark`
|
|
257
|
+
background-color: ${g.color.onlight.textLowEmphasis};
|
|
191
258
|
`}
|
|
192
259
|
|
|
193
260
|
&::placeholder {
|
|
194
|
-
color: ${
|
|
261
|
+
color: ${g.themedColor.textLowEmphasis};
|
|
195
262
|
}
|
|
196
|
-
`,
|
|
197
|
-
background-color: ${
|
|
263
|
+
`,Ss=D.css`border:1px solid ${g.themedColor.error};color:${g.themedColor.textHighEmphasis};${V.light`
|
|
264
|
+
background-color: ${g.color.background50};
|
|
198
265
|
`}
|
|
199
|
-
${
|
|
200
|
-
background-color: ${
|
|
266
|
+
${V.dark`
|
|
267
|
+
background-color: ${g.color.onlight.textLowEmphasis};
|
|
201
268
|
`}
|
|
202
|
-
`,xs=
|
|
203
|
-
background-color: ${
|
|
269
|
+
`,xs=D.css`border:1px solid ${g.themedColor.textDisabled};color:${g.themedColor.textHighEmphasis};${V.light`
|
|
270
|
+
background-color: ${g.color.background50};
|
|
204
271
|
`}
|
|
205
|
-
${
|
|
206
|
-
background-color: ${
|
|
272
|
+
${V.dark`
|
|
273
|
+
background-color: ${g.color.onlight.textLowEmphasis};
|
|
207
274
|
`}
|
|
208
275
|
|
|
209
276
|
&:focus {
|
|
210
|
-
border-color: ${
|
|
277
|
+
border-color: ${g.themedColor.primary};
|
|
211
278
|
}
|
|
212
|
-
`,
|
|
279
|
+
`,Hm=p.default.input`${vs};height:36px;${({$error:e,$submitted:t})=>t?ys:e?Ss:xs}`,Um=p.default.textarea`${vs};height:96px;resize:none;font-family:inherit;${({$error:e,$submitted:t})=>t?ys:e?Ss:xs}`,Vm=({children:e,className:t,style:n})=>i.createElement($,{variant:"button",color:g.themedColor.textHighEmphasis,className:t,style:n},e),le={Title:Vm,Label:Em,ErrorLabel:_m,Separator:Fm,Button:pm,TextInput:Bm,NumberInput:bm,SingleSelect:$m,MultiSelect:Dm},zm=1,Gm=new Set(["text","number","single-select","multi-select"]),Wm=e=>{var y;const t=(y=e.extendedMessagePayload)==null?void 0:y.form;if(!t)throw new Error("Form is not provided");const{stringSet:n}=Y(),{conversation:r}=j(),[o,s]=u.useState({submitting:!1,canceling:!1}),[a,l]=u.useState({visible:!1}),{state:c,fields:d,submit:m,cancel:h,updateFieldValue:f}=fl(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:E=>{var A;return(A=e.onSubmitForm)==null?void 0:A.call(e,{key:t.key,data:E})},onCancel:()=>{var E;return(E=e.onCancelForm)==null?void 0:E.call(e,{key:t.key})}}),b=c==="submitted",C=async()=>{s(E=>({...E,submitting:!0}));try{await m()}catch(E){l({visible:!0,description:E instanceof Error?E.message:n.TRY_AGAIN})}finally{s(E=>({...E,submitting:!1}))}},v=async()=>{s(E=>({...E,canceling:!0}));try{await h()}catch(E){l({visible:!0,description:E instanceof Error?E.message:n.TRY_AGAIN})}finally{s(E=>({...E,canceling:!1}))}},_=u.useMemo(()=>{const E=()=>t.version>zm,A=()=>t.fields.some(T=>!Gm.has(T.type));return E()||A()?{visible:!1,cancelable:!0,reason:n.FORM_NOT_SUPPORTED}:c==="draft"&&(e.isHandedOff||e.isConversationClosed)?{visible:!1,cancelable:!1,reason:n.FORM_UNAVAILABLE}:{visible:!0,cancelable:!0,reason:""}},[t.version,t.fields,c,e.isHandedOff,e.isConversationClosed]);return c==="canceled"?null:_.visible?i.createElement(u.Fragment,null,i.createElement(ro,{$maxWidth:e.maxBodyWidth??z.BODY_MAX_WIDTH},i.createElement(le.Title,null,t.title),i.createElement(qm,null,d.map(E=>i.createElement(Ym,{key:E.key},i.createElement(le.Label,{style:{marginBottom:"6px"},required:E.required},E.label),E.type==="text"&&i.createElement(le.TextInput,{value:E.value||"",placeholder:E.placeholder,onChange:A=>f(E.key,A),disabled:b,error:!!E.error,submitted:b,variant:E.layout==="multiline"?"multi-line":"single-line",maxLength:E.maxLength,ariaLabel:E.label,required:E.required}),E.type==="number"&&i.createElement(le.NumberInput,{value:E.value||null,placeholder:E.placeholder,onChange:A=>f(E.key,A),disabled:b,error:!!E.error,submitted:b,max:E.max,ariaLabel:E.label,required:E.required}),E.type==="single-select"&&i.createElement(le.SingleSelect,{options:E.options.map(A=>({label:A,value:A})),value:E.value||"",onChange:A=>f(E.key,A),submitted:b,groupLabel:E.label}),E.type==="multi-select"&&i.createElement(le.MultiSelect,{options:E.options.map(A=>({label:A,value:A})),value:E.value||[],onChange:A=>f(E.key,A),submitted:b,maxSelect:E.maxSelect,groupLabel:E.label}),E.error&&i.createElement(le.ErrorLabel,{style:{marginTop:"4px"}},E.error)))),i.createElement(le.Separator,null),i.createElement(Km,null,i.createElement(le.Button,{variant:b?"clear":"primary",ariaLabel:r.form.button(b?n.SUBMITTED:n.BUTTON__SUBMIT)["aria-label"],onClick:C,disabled:b||o.canceling,loading:o.submitting},b?n.SUBMITTED:n.BUTTON__SUBMIT),c!=="submitted"&&i.createElement(le.Button,{variant:"secondary",ariaLabel:r.form.button(n.BUTTON__CANCEL)["aria-label"],onClick:v,disabled:o.submitting,loading:o.canceling},n.BUTTON__CANCEL))),i.createElement(sr,{...a,onClose:()=>l({visible:!1,title:""})})):i.createElement(ro,{$maxWidth:e.maxBodyWidth??z.BODY_MAX_WIDTH},i.createElement($,{variant:"body3"},_.reason),_.cancelable&&i.createElement(le.Button,{variant:"primary",ariaLabel:r.form.button(n.BUTTON__CANCEL)["aria-label"],onClick:v,loading:o.canceling},n.BUTTON__CANCEL))},ro=p.default.div`display:flex;flex-direction:column;gap:12px;border-radius:12px;overflow:hidden;max-width:${({$maxWidth:e})=>e}px;${({theme:e})=>D.css`
|
|
213
280
|
color: ${e.colors.messageIncoming.text};
|
|
214
281
|
background-color: ${e.colors.messageIncoming.background};
|
|
215
282
|
`}
|
|
216
283
|
padding: 16px 12px;
|
|
217
284
|
transition: max-width 0.3s;
|
|
218
285
|
overflow-wrap: break-word;
|
|
219
|
-
`,
|
|
220
|
-
${e==="vertical"?
|
|
286
|
+
`,qm=p.default.div`display:flex;flex-direction:column;gap:12px;`,Ym=p.default.div`display:flex;flex-direction:column;`,Km=p.default.div`display:flex;flex-direction:column;gap:8px;`,jm=e=>i.createElement(i.Fragment,null),Xm=new Set(["default"]),{MessageTemplate:Zm}=ai.createMessageTemplate({parser:Mn.parser,renderer:Mn.renderer,Container:e=>i.createElement("div",{...e})}),Jm=e=>i.createElement(Qt,{errorFallback:e.messageTemplateErrorFallback,loadingFallback:e.messageTemplateLoadingFallback},i.createElement(Qm,{...e})),Qm=({extendedMessagePayload:e,onGetCachedMessageTemplate:t=()=>null,onRequestMessageTemplate:n,onHandleTemplateInternalAction:r=X})=>{const o=e==null?void 0:e.message_template;if(!Xm.has((o==null?void 0:o.type)??"default"))throw new Error("Unsupported template type");if(!n)throw new Error("onRequestMessageTemplate is required");const a=o==null?void 0:o.key;if(!a)throw new Error("Template key is missing");const{theme:l}=or(),c=sl({onRequestTemplate:n,onGetCachedTemplate:t,theme:l.selectedTheme,templateKey:a,variables:o==null?void 0:o.variables,viewVariables:o==null?void 0:o.view_variables,aiAgentColorVariables:l.aiAgentColorVariables});return i.createElement(eh,{id:`${Oe}-ext-message-template`},i.createElement(Mn.MessageProvider,{handleInternalAction:(d,m)=>{d.stopPropagation(),r==null||r(m)}},i.createElement(Zm,{templateItems:c.body.items,templateVersion:c.version})))},eh=p.default.div`box-sizing:border-box;overflow:hidden;width:100%;`,th=({extendedMessagePayload:e,onClickSuggestedReply:t,suggestedRepliesDirection:n="vertical"})=>{const{conversation:r}=j(),[o,s]=u.useState(!1),{suggestedReplies:a}=r,l=(e==null?void 0:e.suggested_replies)??[];if(l.length===0||o)return null;const c=d=>{t&&(t({reply:d}),s(!0))};return i.createElement(nh,{id:`${Oe}-ext-suggested-replies`,$type:n},l.map((d,m)=>{const h=a.item(d,()=>c(d));return i.createElement(rh,{key:m,$type:n,variant:"body3",...h.props},d)}),a.descriptionNode)},nh=p.default.div`margin:16px 0;padding:0 ${z.HORIZONTAL_PADDING}px;position:relative;display:flex;align-self:stretch;gap:8px;${({$type:e})=>e==="vertical"?oh:sh};`,rh=p.default($)`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:${g.color.primary.main};border:1px solid ${g.color.primary.main};background-color:${g.themedColor.bg_50_600};&:hover{background-color:${g.themedColor.bg_100_500};}${de}${({$type:e,theme:t})=>D.css`
|
|
287
|
+
${e==="vertical"?ih:ah};
|
|
221
288
|
&:active {
|
|
222
289
|
background-color: ${t.colors.base.primary};
|
|
223
290
|
color: ${t.colors.base.primaryContrastContent};
|
|
224
291
|
}
|
|
225
292
|
`}
|
|
226
|
-
`,
|
|
227
|
-
`,
|
|
293
|
+
`,oh=D.css`flex-direction:column;align-items:flex-end;`,sh=D.css`flex-direction:row;overflow-x:scroll;-ms-overflow-style:none;scrollbar-width:none;&::-webkit-scrollbar{display:none;}`,ih=D.css`max-width:calc(100% - 70px);white-space:pre-wrap;`,ah=D.css`white-space:nowrap;`,lh=e=>{const{components:t}=Ge.useContext(),{stringSet:n}=Y(),r=So(e)?i.createElement(t.TextMessageBody,{...e}):null;if(e.messageType==="user")return r;if(e.messageType==="file"){const o=e.file;return o.type.startsWith("image")||o.type.startsWith("video")?i.createElement(t.MediaMessageBody,{...e},r):i.createElement(t.FileMessageBody,{...e},r)}return e.messageType==="multipleFiles"?i.createElement(t.MultipleFilesMessageBody,{...e},r):i.createElement(t.TextMessageBody,{...e,message:n.UNKNOWN__UNKNOWN_MESSAGE_TYPE})},ch=e=>i.createElement(As,{...e,testerMode:!1}),Ge=ke({template:ch,components:{SenderName:Ad,SenderAvatar:Sd,SentTime:Id,MessageBody:lh,TextMessageBody:Cd,MediaMessageBody:Zu,FileMessageBody:Ku,MultipleFilesMessageBody:gd,TypingIndicator:kd,SuggestedReplies:th,MessageTemplate:Jm,CustomMessageTemplate:Gd,CTAButton:$d,Citation:Fd,Form:Wm,Feedback:lm,MessageLogs:jm}}),As=e=>{var _,y,E,A,T,O,w;const{components:t}=Ge.useContext(),{streamText:n,isAnimating:r}=Al({text:e.message,enabled:e.isStreaming,onAnimationStart:e.onStreamAnimationStart,onAnimationProgress:e.onStreamAnimationProgress,onAnimationComplete:e.onStreamAnimationComplete}),o={...e,message:n,extendedMessagePayload:r?{}:e.extendedMessagePayload},s=!!o.isTyping,a=o.testerMode,l=!!o.isSenderAvatarVisible,c=!!((_=o.extendedMessagePayload)!=null&&_.form)&&!((y=o.extendedMessagePayload)!=null&&y.form.canceled_at),d=!!((E=o.extendedMessagePayload)!=null&&E.message_template),m=!!((A=o.extendedMessagePayload)!=null&&A.cta_button),h=!!((T=o.extendedMessagePayload)!=null&&T.citations)&&o.extendedMessagePayload.citations.length>0,f=!!o.createdAt,b=o.groupType==="top"||o.groupType==="single",C=o.groupType==="bottom"||o.groupType==="single",v=a||!l?0:z.AVATAR_SIZE;return i.createElement(uh,{$marginBottom:s?0:rn(o.groupType)},b&&i.createElement(dh,{"aria-hidden":"true"},!a&&l&&i.createElement(t.SenderAvatar,{...o}),i.createElement(t.SenderName,{...o})),i.createElement(hh,null,i.createElement(In,{$extraStartPadding:v},s?i.createElement(t.TypingIndicator,{...o}):i.createElement(t.MessageBody,{...o},m&&i.createElement("div",{style:{marginTop:12,marginInline:12}},i.createElement(t.CTAButton,{...o})),h&&i.createElement(t.Citation,{...o}))),d&&i.createElement(oo,{$startPadding:0,$endPadding:0},i.createElement(t.MessageTemplate,{...o,messageTemplateErrorFallback:o.messageTemplateErrorFallback??i.createElement(In,{$extraStartPadding:v},i.createElement(t.MessageBody,{...o,messageType:"user",message:((w=(O=o.extendedMessagePayload)==null?void 0:O.message_template)==null?void 0:w.fallback_message)??"Cannot read this template."})),messageTemplateLoadingFallback:o.messageTemplateLoadingFallback??i.createElement(In,{$extraStartPadding:v},i.createElement(t.TypingIndicator,{...o}))})),i.createElement(t.CustomMessageTemplate,{...o}),c&&i.createElement(oo,{$extraStartPadding:v},i.createElement(t.Form,{...o}))),C&&f&&i.createElement(mh,{$extraStartPadding:v+8,"aria-hidden":"true"},i.createElement(t.SentTime,{...o})),i.createElement(u.Fragment,null,!s&&i.createElement(kt,{$extraStartPadding:v+8},i.createElement(t.Feedback,{...o})),o.suggestedRepliesVisible&&i.createElement(t.SuggestedReplies,{...o}),i.createElement(t.MessageLogs,{...o})))},uh=p.default.div`display:flex;flex-direction:column;align-items:flex-start;margin-bottom:${({$marginBottom:e})=>`${e}px`};
|
|
294
|
+
`,kt=p.default.div`display:flex;align-self:stretch;justify-content:flex-start;${({$startPadding:e=z.HORIZONTAL_PADDING,$endPadding:t=z.HORIZONTAL_PADDING,$extraStartPadding:n=0})=>`
|
|
228
295
|
padding-inline: ${e+n}px ${t}px;
|
|
229
296
|
`}
|
|
230
|
-
`,
|
|
297
|
+
`,dh=p.default(kt)`display:flex;flex-direction:row;align-items:center;gap:8px;`,In=p.default(kt)`display:flex;`,mh=p.default(kt)`margin-top:${z.BODY_TIME_GAP}px;display:flex;align-items:flex-start;justify-content:flex-start;`,oo=p.default(kt)`display:flex;${({$startPadding:e=z.HORIZONTAL_PADDING,$endPadding:t=z.HORIZONTAL_PADDING,$extraStartPadding:n=0})=>`
|
|
231
298
|
padding-inline: ${e+n}px ${t}px;
|
|
232
299
|
`}
|
|
233
|
-
`,
|
|
234
|
-
background-color: ${
|
|
300
|
+
`,hh=p.default.div`display:flex;flex-direction:column;min-width:0;max-width:100%;gap:${z.GAP_GROUPED}px;`;function gh({file:e,children:t,onClickFile:n,sendingStatus:r}){const o=(()=>{if(!(!n||r==="failed"))return()=>n==null?void 0:n(e)})();return i.createElement(fh,null,i.createElement(lr,{name:e.name,mimeType:e.type,type:Wn(e.name,e.type),onClick:o}),t)}const fh=p.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${z.GAP_GROUPED}px;`;function ph({sendingStatus:e,file:t,metadata:n,onClickMedia:r,onClickMediaFiles:o,children:s}){const{conversation:a}=j(),{aspectRatio:l,localFile:c}=n,[d]=u.useState(()=>c instanceof Blob?URL.createObjectURL(c):t.url),[m,h]=u.useState(!1),f=(()=>{if(e!=="failed"){if(o)return()=>o({files:[{url:d,type:t.type,name:t.name}],index:0});if(r)return()=>r({...t,url:d})}})(),b=f?a.file.buttonLikeInteractivePreview({name:t.name,mimeType:t.type,onActivate:f}):a.file.preview({name:t.name,mimeType:t.type}),C={...b.props,$ratio:l,$clickable:!!f};return i.createElement(_h,null,i.createElement(Eh,{...C},!m&&i.createElement(tt,{size:26},i.createElement(U,{type:"spinner",color:"textLowEmphasis",size:26})),i.createElement(bh,{$loaded:m,src:d,alt:"image-message",onLoad:()=>h(!0)}),b.descriptionNode),s)}const _h=p.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${z.GAP_GROUPED}px;`,Eh=p.default.div`width:${z.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;${V.light`
|
|
301
|
+
background-color: ${g.color.background100};
|
|
235
302
|
`}
|
|
236
|
-
${
|
|
237
|
-
background-color: ${
|
|
303
|
+
${V.dark`
|
|
304
|
+
background-color: ${g.color.background400};
|
|
238
305
|
`}
|
|
239
|
-
`,
|
|
306
|
+
`,bh=p.default.img`position:absolute;width:100%;height:100%;inset-block-start:0;inset-inline-start:0;object-fit:cover;opacity:${e=>e.$loaded?1:0};transition:opacity 0.5s ease;`,Ch=({sendingStatus:e,files:t,metadata:n,onClickMedia:r,onClickMediaFiles:o,children:s})=>{const[a]=u.useState(()=>n.localFiles?n.localFiles.filter(m=>m instanceof Blob).map(m=>({...m,url:URL.createObjectURL(m)})):t),l=e==="pending",c=e==="failed",d=m=>{if(c||l)return;const h=a[m];h&&(o?o({files:a,index:m}):r&&r({url:h.url,type:h.type||"image/*"}))};return i.createElement(vh,null,i.createElement(ds,{images:a,isPending:l,onClickImage:d}),s)},vh=p.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${z.GAP_GROUPED}px;`;function yh(e){var n,r;const t=u.useMemo(()=>{const o=_d(hs(e.message));return bo.default.sanitize(o)},[e.message]);return i.createElement(Sh,{$maxWidth:e.maxBodyWidth??z.BODY_MAX_WIDTH,$color:(n=e.customStyle)==null?void 0:n.bubbleContentColor,$bgColor:(r=e.customStyle)==null?void 0:r.bubbleBackgroundColor},i.createElement(xh,{variant:"body3",dangerouslySetInnerHTML:{__html:t}}))}const Sh=p.default.div`display:flex;flex-direction:column;border-radius:12px;overflow:hidden;max-width:${({$maxWidth:e})=>e}px;${({theme:e,$color:t,$bgColor:n})=>D.css`
|
|
240
307
|
color: ${t||e.colors.messageOutgoing.text};
|
|
241
308
|
background-color: ${n||e.colors.messageOutgoing.background};
|
|
242
309
|
`}
|
|
243
310
|
padding: 12px 0;
|
|
244
311
|
transition: max-width 0.3s;
|
|
245
312
|
overflow-wrap: break-word;
|
|
246
|
-
`,
|
|
247
|
-
`,
|
|
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
|
-
background-color: ${
|
|
313
|
+
`,xh=p.default($)`align-items:flex-start;line-height:140%;white-space:pre-wrap;padding:0 12px;`,Ah=({sendingStatus:e})=>{const t=D.useTheme();switch(e){case"pending":return i.createElement(Th,{size:16},i.createElement(U,{type:"spinner",color:t.colors.messageOutgoing.background,size:16}));case"failed":return i.createElement("div",{style:{marginBottom:2}},i.createElement(U,{type:"error",color:g.themedColor.error,size:16}));case"scheduled":case"canceled":return null;default:return i.createElement("div",{style:{marginBottom:2}},i.createElement(U,{type:"done",color:g.themedColor.secondary,size:16}))}},Th=p.default(tt)`margin-bottom:2px;width:16px;height:16px;`,Ih=({createdAt:e})=>{const{stringSet:t,format:n}=Y();return e?i.createElement($,{variant:"caption4",color:g.themedColor.textLowEmphasis},n(e,t.DATE_FORMAT__MESSAGE_TIMESTAMP)):null},wh=e=>{const{components:t}=Mt.useContext(),{stringSet:n}=Y(),r=()=>{const c=So(e)?i.createElement(t.TextMessageBody,{...e}):null;return e.messageType==="user"?c:e.messageType==="file"?e.file.type.startsWith("image")?i.createElement(t.MediaMessageBody,{...e},c):i.createElement(t.FileMessageBody,{...e},c):e.messageType==="multipleFiles"?i.createElement(t.MultipleFilesMessageBody,{...e},c):i.createElement(t.TextMessageBody,{...e,message:n.UNKNOWN__UNKNOWN_MESSAGE_TYPE})},o=e.sendingStatus==="failed"&&e.onClickFailedMessage,s=()=>{var c;return(c=e.onClickFailedMessage)==null?void 0:c.call(e)},l=o?{role:"button",tabIndex:0,onClick:s,onKeyDown:c=>{c.repeat||(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),s())}}:{};return i.createElement("div",{...l,style:{display:"contents",cursor:o?"pointer":"default"}},r())},kh=e=>{const{components:t}=Mt.useContext(),n=e.sendingStatus==="succeeded",r=e.groupType==="bottom"||e.groupType==="single",o=e.messageType==="user"&&e.sendingStatus!=="failed";return i.createElement(Mh,{$marginBottom:rn(e.groupType)},i.createElement(Lh,{"aria-hidden":o?"true":void 0},i.createElement(t.MessageBody,{...e})),r&&i.createElement(Oh,{$extraEndPadding:8,"aria-hidden":n?"true":void 0},n?i.createElement(t.SentTime,{...e}):i.createElement(t.SendingStatus,{...e})))},Mt=ke({template:kh,components:{SendingStatus:Ah,SentTime:Ih,MessageBody:wh,TextMessageBody:yh,MediaMessageBody:ph,FileMessageBody:gh,MultipleFilesMessageBody:Ch}}),Mh=p.default.div`display:flex;flex:1;flex-direction:column;align-items:flex-end;margin-bottom:${({$marginBottom:e})=>`${e}px`};
|
|
314
|
+
`,Ts=p.default.div`display:flex;align-self:stretch;justify-content:flex-end;${({$startPadding:e=z.HORIZONTAL_PADDING,$endPadding:t=z.HORIZONTAL_PADDING,$extraEndPadding:n=0})=>`padding-inline: ${e}px ${t+n}px;`};
|
|
315
|
+
`,Lh=p.default(Ts)``,Oh=p.default(Ts)`margin-top:${z.BODY_TIME_GAP}px;`,Rh=e=>e.messageType!=="admin"?null:i.createElement(Nh,null,i.createElement($,{variant:"caption2",color:g.themedColor.textMidEmphasis},$h(bo.default.sanitize(e.message)))),Nh=p.default.div`text-align:center;text-wrap:pretty;word-break:break-word;padding-inline:${z.HORIZONTAL_PADDING}px;a{text-decoration:underline;color:inherit;}`,$h=e=>{try{const t=[];let n=e,r=0;for(;n;){const o=n.match(/\[([^\]]+)\]\((https?:\/\/[^\s]+)\)/),s=n.match(/\*\*([^*]+)\*\*/),a=[o&&{match:o,type:"link"},s&&{match:s,type:"bold"}].filter(h=>!!h);if(!a.length){t.push(n);break}const l=a.reduce((h,f)=>f.match.index<h.match.index?f:h),{match:c,type:d}=l,m=c.index;m>0&&t.push(n.slice(0,m)),d==="link"?t.push(i.createElement("a",{key:r++,href:c[2],target:"_blank",rel:rr},c[1])):d==="bold"&&t.push(i.createElement("strong",{key:r++},c[1])),n=n.slice(m+c[0].length)}return t.filter(o=>o!=="")}catch{return[e]}},Is=({onClick:e,checked:t,label:n,disabled:r,labelVariant:o="caption2"})=>{const s=t?g.themedColor.primary:r?g.themedColor.textDisabled:g.themedColor.textLowEmphasis,a=t?g.themedColor.textHighEmphasis:r?g.themedColor.textLowEmphasis:g.themedColor.textHighEmphasis;return i.createElement(Fh,{onClick:e,disabled:r},i.createElement(Dh,null,i.createElement(U,{size:20,type:t?"radio-on":"radio-off",color:s})),i.createElement(Ph,{variant:o,color:a},n))},Dh=p.default.div`width:20px;height:20px;`,Ph=p.default($)`line-height:20px;word-break:break-word;`,Fh=p.default.button`all:unset;display:flex;align-items:flex-start;justify-content:flex-start;gap:2px;${de}&:enabled{cursor:pointer;}`,Bh=({csatPayload:e,submitted:t,defaultValue:n,value:r,onChange:o})=>(u.useEffect(()=>{typeof r>"u"&&typeof n=="boolean"&&(o==null||o(n))},[r,n]),e.cre?i.createElement(Hh,null,i.createElement(le.Label,{required:e.cre.required},e.cre.question),i.createElement(Uh,null,[{label:e.cre.positive_label,value:!0},{label:e.cre.negative_label,value:!1}].map(s=>i.createElement(Is,{key:s.label,checked:r===s.value,label:s.label,disabled:t,onClick:()=>o==null?void 0:o(s.value)})))):null),Hh=p.default.div`display:flex;flex-direction:column;gap:8px;`,Uh=p.default.div`display:flex;flex-direction:column;gap:8px;`,Vh=({followUpItem:e,submitted:t,value:n="",onChange:r,hasError:o})=>{const{stringSet:s}=Y();return i.createElement(zh,null,i.createElement(le.Label,{required:e.required},e.question),e.response_type==="free_text"&&i.createElement(le.TextInput,{variant:"multi-line",disabled:t,submitted:t,maxLength:100,value:n,onChange:a=>r(a),error:o}),e.response_type==="single_choice"&&i.createElement(Gh,null,e.options.map(a=>i.createElement(Is,{key:a,checked:n===a,label:a,disabled:t,onClick:()=>r==null?void 0:r(a),labelVariant:"body3"}))),o&&i.createElement(le.ErrorLabel,null,s.FORM_VALIDATION_REQUIRED))},zh=p.default.div`display:flex;flex-direction:column;gap:8px;`,Gh=p.default.div`display:flex;flex-direction:column;gap:8px;`,Wh=({value:e,selected:t})=>i.createElement(qh,{$selected:t,"aria-hidden":"true"},Yh[e-1]),qh=p.default.div`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,Yh=[i.createElement("svg",{width:"40",height:"40",viewBox:"0 0 40 40",fill:"none",xmlns:"http://www.w3.org/2000/svg"},i.createElement("path",{d:"M2.08337 19.9999C2.08337 10.1048 10.1049 2.08325 20 2.08325C29.8952 2.08325 37.9167 10.1048 37.9167 19.9999C37.9167 29.8951 29.8952 37.9166 20 37.9166C10.1049 37.9166 2.08337 29.8951 2.08337 19.9999Z",fill:"url(#paint0_linear_159_173206)"}),i.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M12.5828 29.3328C13.1348 29.7473 13.9184 29.636 14.3329 29.084C15.6272 27.3607 17.6839 26.25 20 26.25C22.3164 26.25 24.373 27.3607 25.6672 29.084C26.0819 29.636 26.8654 29.7473 27.4175 29.3328C27.9695 28.9182 28.0809 28.1347 27.6662 27.5825C25.9202 25.2577 23.136 23.75 20 23.75C16.8642 23.75 14.0801 25.2577 12.334 27.5825C11.9194 28.1347 12.0308 28.9182 12.5828 29.3328Z",fill:"#141B34"}),i.createElement("path",{d:"M28.4454 13.7707C29.1329 13.8328 29.6405 14.4406 29.5785 15.1281C29.5165 15.8153 28.9095 16.3221 28.2224 16.2608C28.2224 16.2608 28.0287 16.2502 27.9272 16.2487C27.7229 16.2457 27.4387 16.2509 27.1229 16.2833C26.7869 16.3177 26.4649 16.3782 26.1804 16.4662L26.3045 16.86C26.7797 18.3675 25.5099 19.5813 24.2062 19.5813C23.5045 19.5813 22.8324 19.2617 22.43 18.6857C22.003 18.0745 21.9422 17.241 22.408 16.5344C22.751 16.0143 23.2449 15.3831 23.8964 14.8657C24.836 14.1195 26.044 13.8809 26.8675 13.7963C27.3029 13.7517 28.0154 13.7319 28.4454 13.7707Z",fill:"#141B34"}),i.createElement("path",{d:"M11.5549 13.7707C10.8674 13.8328 10.3597 14.4406 10.4218 15.1281C10.4838 15.8153 11.0908 16.3221 11.7779 16.2608C11.7779 16.2608 11.9716 16.2502 12.073 16.2487C12.2774 16.2457 12.5616 16.2509 12.8774 16.2833C13.2134 16.3177 13.5353 16.3782 13.8199 16.4662L13.6958 16.86C13.2205 18.3675 14.4904 19.5813 15.794 19.5813C16.4958 19.5813 17.168 19.2617 17.5703 18.6857C17.9971 18.0745 18.0581 17.241 17.5921 16.5344C17.2493 16.0143 16.7553 15.3831 16.1039 14.8657C15.1643 14.1195 13.9562 13.8809 13.1327 13.7963C12.6974 13.7517 11.9849 13.7319 11.5549 13.7707Z",fill:"#141B34"}),i.createElement("defs",null,i.createElement("linearGradient",{id:"paint0_linear_159_173206",x1:"20",y1:"2.08325",x2:"20",y2:"37.9166",gradientUnits:"userSpaceOnUse"},i.createElement("stop",{stopColor:"#FF2D1D"}),i.createElement("stop",{offset:"1",stopColor:"#FFA540"})))),i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},i.createElement("path",{d:"M2.083 20C2.083 10.105 10.105 2.083 20 2.083c9.895 0 17.917 8.021 17.917 17.917 0 9.895-8.022 17.917-17.917 17.917C10.105 37.917 2.083 29.895 2.083 20Z",fill:"#FFD46E"}),i.createElement("path",{d:"M14.249 27.334C15.851 26.13 17.844 25.417 20 25.417c2.156 0 4.149.714 5.751 1.917.553.415.664 1.199.25 1.751-.415.552-1.199.664-1.751.25-1.183-.889-2.652-1.416-4.25-1.416s-3.067.527-4.25 1.416c-.553.414-1.336.302-1.751-.25-.415-.552-.303-1.336.249-1.751Z",fill:"#141B34"}),i.createElement("path",{d:"M23.445 14.596c-.687.062-1.294-.445-1.356-1.132-.062-.687.445-1.295 1.132-1.357.082-.005.342-.02.482-.022.277-.004.662.002 1.097.047.823.085 2.031.323 2.97 1.07.652.518 1.146 1.15 1.489 1.67.466.706.405 1.54-.022 2.15-.402.576-1.074.896-1.775.896-1.304 0-2.573-1.214-2.098-2.722l.125-.394c-.285-.088-.607-.148-.942-.182-.316-.033-.6-.038-.804-.035-.101.002-.242.01-.294.013Z",fill:"#141B34"}),i.createElement("path",{d:"M11.779 14.596c-.687.062-1.294-.445-1.356-1.132-.062-.687.445-1.295 1.132-1.357.082-.005.342-.02.482-.022.277-.004.662.002 1.097.047.823.085 2.031.323 2.97 1.07.652.518 1.146 1.15 1.489 1.67.466.706.405 1.54-.022 2.15-.402.576-1.074.896-1.775.896-1.304 0-2.573-1.214-2.098-2.722l.124-.394c-.284-.088-.606-.148-.941-.182-.316-.033-.6-.038-.804-.035-.101.002-.243.01-.294.013Z",fill:"#141B34"})),i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},i.createElement("path",{d:"M2.083 20C2.083 10.105 10.105 2.083 20 2.083c9.895 0 17.917 8.021 17.917 17.917 0 9.895-8.022 17.917-17.917 17.917C10.105 37.917 2.083 29.895 2.083 20Z",fill:"#FFD46E"}),i.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M11.25 15c0-1.151.933-2.083 2.083-2.083h.015c1.151 0 2.084.933 2.084 2.083 0 1.151-.933 2.083-2.084 2.083h-.015c-1.15 0-2.083-.933-2.083-2.083ZM24.568 15c0-1.151.933-2.083 2.084-2.083h.015c1.151 0 2.083.933 2.083 2.083 0 1.151-.932 2.083-2.083 2.083h-.015c-1.151 0-2.084-.933-2.084-2.083Z",fill:"#141B34"}),i.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M13.75 26.667c0-.691.56-1.25 1.25-1.25h10c.69 0 1.25.559 1.25 1.25 0 .691-.56 1.25-1.25 1.25h-10c-.69 0-1.25-.559-1.25-1.25Z",fill:"#141B34"})),i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},i.createElement("path",{d:"M2.083 20C2.083 10.105 10.105 2.083 20 2.083c9.895 0 17.917 8.021 17.917 17.917 0 9.895-8.022 17.917-17.917 17.917C10.105 37.917 2.083 29.895 2.083 20Z",fill:"#FFD46E"}),i.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M12.583 24.001c.552-.414 1.335-.302 1.75.25 1.294 1.723 3.35 2.834 5.667 2.834s4.373-1.11 5.667-2.834c.415-.552 1.199-.664 1.751-.25.552.415.664 1.199.25 1.751C25.92 28.076 23.136 29.584 20 29.584s-5.92-1.508-7.666-3.832c-.415-.552-.303-1.336.249-1.751Z",fill:"#141B34"}),i.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M11.25 15c0-1.151.933-2.083 2.083-2.083h.015c1.151 0 2.084.933 2.084 2.083 0 1.151-.933 2.083-2.084 2.083h-.015c-1.15 0-2.083-.933-2.083-2.083ZM24.568 15c0-1.151.933-2.083 2.084-2.083h.015c1.151 0 2.083.933 2.083 2.083 0 1.151-.932 2.083-2.083 2.083h-.015c-1.151 0-2.084-.933-2.084-2.083Z",fill:"#141B34"})),i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},i.createElement("path",{d:"M2.083 20C2.083 10.105 10.105 2.083 20 2.083c9.895 0 17.917 8.021 17.917 17.917 0 9.895-8.022 17.917-17.917 17.917C10.105 37.917 2.083 29.895 2.083 20Z",fill:"#FFD46E"}),i.createElement("g",{clipPath:"url(#clip0_159_173224)"},i.createElement("g",{clipPath:"url(#clip1_159_173224)"},i.createElement("path",{d:"M20 30.624c3.752 0 6.904-2.532 7.789-5.956.412-1.593-.185-1.959-1.76-1.959H13.973c-1.575 0-2.173.366-1.761 1.959.885 3.424 4.037 5.956 7.788 5.956Z",fill:"#141B34"})),i.createElement("mask",{id:"mask0_159_173224",style:{maskType:"alpha"},maskUnits:"userSpaceOnUse",x:"12",y:"22",width:"16",height:"9"},i.createElement("path",{d:"M20 30.624c3.752 0 6.904-2.532 7.789-5.956.412-1.593-.185-1.959-1.76-1.959H13.973c-1.575 0-2.173.366-1.761 1.959.885 3.424 4.037 5.956 7.788 5.956Z",fill:"#141B34"})),i.createElement("g",{mask:"url(#mask0_159_173224)"},i.createElement("path",{d:"M20 32.998c3.278 0 5.936-1.594 5.936-3.561 0-1.968-2.658-3.562-5.936-3.562-3.278 0-5.936 1.594-5.936 3.562 0 1.967 2.658 3.561 5.936 3.561Z",fill:"#FF493B"}))),i.createElement("path",{d:"M11.667 15.833c0-1.381 1.12-2.5 2.5-2.5s2.5 1.12 2.5 2.5M23.333 15.833c0-1.381 1.12-2.5 2.5-2.5s2.5 1.12 2.5 2.5",stroke:"#141B34",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"}),i.createElement("defs",null,i.createElement("clipPath",{id:"clip0_159_173224"},i.createElement("rect",{width:"15.83",height:"7.915",fill:"white",transform:"translate(12.085 22.709)"})),i.createElement("clipPath",{id:"clip1_159_173224"},i.createElement("rect",{width:"15.83",height:"7.915",fill:"white",transform:"translate(12.085 22.709)"}))))],Kh=({csatPayload:e,submitted:t,value:n,onChange:r})=>{const o=typeof n>"u",{conversation:s}=j(),a=s.csat.scoresContainer(e.csat_question);return i.createElement(Xh,null,i.createElement($,{variant:"caption3",color:g.themedColor.textMidEmphasis},e.csat_question),i.createElement(Zh,{...a.props},e.csat_scores.map(({label:l,image_url:c},d)=>{const m=d+1,h=n===m,f=e.csat_scores.length,b=s.csat.scoreItem({score:m,label:l,selected:h,disabled:t,currentIndex:d,totalCount:f,hasSelection:!o,onChange:r});return i.createElement(Jh,{key:d,...b.props},i.createElement(jh,{value:m,selected:o||h,label:l,src:c}),!!l&&i.createElement($,{color:h?g.themedColor.textHighEmphasis:g.themedColor.textLowEmphasis,variant:"caption3"},l))})),a.descriptionNode)},jh=({value:e,src:t,label:n,selected:r})=>{const[o,s]=u.useState(!1),a=o?i.createElement(Wh,{value:e,selected:r}):i.createElement(eg,{$selected:r,"aria-label":n,src:t,onError:()=>s(!0)});return i.createElement(Qh,null,a)},Xh=p.default.div`display:flex;flex-direction:column;gap:8px;`,Zh=p.default.div`display:flex;justify-content:space-between;align-self:center;width:100%;max-width:400px;gap:16px;`,Jh=p.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:${g.themedColor.textHighEmphasis};}`,Qh=p.default.div`button:hover:not(:disabled) &{border-radius:4px;cursor:pointer;background-color:${g.color.background200};${V.dark`
|
|
316
|
+
background-color: ${g.color.background500};
|
|
250
317
|
`}
|
|
251
318
|
}
|
|
252
|
-
`,
|
|
319
|
+
`,eg=p.default.img`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,tg=({csatPayload:e})=>i.createElement($,{variant:"button",color:g.themedColor.textHighEmphasis},e.title),wn=({csatPayload:e,type:t,renderSubmitButton:n,initialCsat:r,initialCsatReason:o,initialIsResolved:s})=>{const{params:a,setParams:l,error:c,setError:d,followUpItem:m,state:h,validateParams:f,itemProps:b}=vl({csatPayload:e,type:t,initialCsat:r,initialCsatReason:o,initialIsResolved:s});return i.createElement(i.Fragment,null,i.createElement(ng,null,i.createElement(tg,{...b}),t===Ie.AI_AGENT_CSAT_5_WITH_CRE&&i.createElement(Bh,{...b,defaultValue:s,value:a.isResolved,onChange:C=>l({isResolved:C})}),i.createElement(Kh,{...b,value:a.csat,onChange:C=>l({csat:C})}),m&&i.createElement(Vh,{...b,followUpItem:m,value:a.csatReason,onChange:C=>{l({csatReason:C}),d({followUpItem:!1})},hasError:c.followUpItem})),h!=="unsubmittable"&&i.createElement(i.Fragment,null,i.createElement(le.Separator,null),n({state:h,params:a,validateParams:f})))},ng=p.default.div`display:flex;flex-direction:column;gap:12px;`,rg=e=>{const{stringSet:t}=Y();return zi(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})},og=()=>{const{stringSet:e}=Y();return i.createElement($,{variant:"body2",color:g.themedColor.textMidEmphasis,style:{textAlign:"center"}},e.CSAT_SUBMISSION_EXPIRED)},sg=({onMount:e,children:t})=>(u.useEffect(()=>{e&&Qe(e)},[]),i.createElement(i.Fragment,null,t)),ig=e=>{const{conversation:t}=j(),{announceError:n}=an();if(e.messageType!=="admin.csat")throw new Error("Invalid message type");const{extendedMessagePayload:r,onSubmitCSAT:o,onScrollToBottom:s}=e,{csat:a,csatReason:l,csatExpireAt:c,isResolvedWhenDeterminedByUser:d}=e,m=He.useForceUpdate(),h=rg(r==null?void 0:r.csat),f=u.useRef(!1);if(!h||!h.visibility||!Ie[h.type])return null;const b=h.type===Ie.AI_AGENT_CSAT_5||h.type===Ie.AI_AGENT_CSAT_5_WITH_CRE||h.type===Ie.HELPDESK_CSAT_5?wn:()=>null;return i.createElement(ag,null,!a&&xr(c)?i.createElement(og,null):i.createElement(b,{csatPayload:h,type:h.type,initialCsat:a,initialCsatReason:l,initialIsResolved:d,renderSubmitButton:({state:C,params:v,validateParams:_})=>i.createElement(sg,{onMount:s},i.createElement(lg,{$state:C,disabled:C==="submitted",...t.csat.submitButton(C==="submitted"?h.csat_submitted_label:h.csat_submit_label),onClick:async()=>{if(f.current)return;const y=xr(c);!y&&_()?(f.current=!0,await o(v).finally(()=>{f.current=!1})):(y||n({type:"csatFormError"}),m())}},i.createElement($,{variant:"button"},C==="submitted"?h.csat_submitted_label:h.csat_submit_label)))}))},ag=p.default.div`display:flex;flex-direction:column;background-color:${({theme:e})=>e.colors.csat.background};border-radius:16px;gap:16px;padding:16px;`,lg=p.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;${de}&:hover{background-color:${g.color.primary.dark};}&:disabled{color:${({$state:e})=>e==="submitted"?g.themedColor.textHighEmphasis:g.color.ondark.textLowEmphasis};background-color:${g.themedColor.textDisabled};cursor:not-allowed;}`,cg=e=>{const{components:t}=un.useContext(),n=e.messageType==="admin"?i.createElement(t.AdminMessage,{...e}):e.messageType==="admin.csat"?i.createElement(t.CSATMessage,{...e}):null;return i.createElement(ug,{$marginBottom:rn(e.groupType)},n)},un=ke({template:cg,components:{AdminMessage:Rh,CSATMessage:ig}}),ug=p.default.div`padding-inline:${z.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>e}px;`,so={file:"attach",snippet:"snippet",site:"website",sb_sprinklr:"sprinklr",sb_salesforce:"salesforce",sb_confluence:"confluence",sb_zendesk:"zendesk",sb_desk:"snippet"},ws=({actionbook:e,functionCalls:t,groundedness:n,agentMessageTemplates:r,onClickActionbook:o,onClickFunctionCall:s,onClickFunctionCallDetail:a,onClickGroundedness:l,onClickAgentMessageTemplate:c,bottomContent:d,renderCustomGroundednessIcon:m=f=>f.default,style:h={}})=>{const{iconColor:f="#000000",textColor:b="#000000",highlightColor:C=yt.DEFAULT_PRIMARY}=h;return i.createElement(io,null,e&&i.createElement(io,null,i.createElement(tn,null,i.createElement(Vt,null,i.createElement(U,{size:16,type:"actionbook",color:f})),i.createElement(Ut,{$clickable:!!o,$highlightColor:C,variant:"body2",color:b,onClick:()=>o==null?void 0:o(e),maxTextLines:1},e.name))),t==null?void 0:t.map(v=>i.createElement(kn,{key:v.key},i.createElement(Vt,null,i.createElement(U,{size:16,type:"function",color:f})),i.createElement(tn,null,i.createElement(Ut,{$clickable:!!s,$highlightColor:C,variant:"body2",color:b,onClick:()=>s==null?void 0:s(v),maxTextLines:1},v.name),a&&i.createElement(mg,{role:"button",onClick:()=>a==null?void 0:a(v)},i.createElement($,{variant:"body2",color:C},"View details"),i.createElement(U,{type:"chevron-right",size:16,color:C}))))),n==null?void 0:n.map(v=>i.createElement(kn,{key:v.id},i.createElement(Vt,null,m({default:i.createElement(U,{size:16,type:so[v.source_type]??so.snippet,color:f}),sourceType:v.source_type})),i.createElement(Ut,{$clickable:!!l,$highlightColor:C,variant:"body2",color:b,onClick:()=>l==null?void 0:l(v),maxTextLines:1},v.preview_title))),r==null?void 0:r.map(v=>i.createElement(kn,{key:v.key},i.createElement(Vt,null,i.createElement(U,{size:16,type:"template",color:f})),i.createElement(Ut,{$clickable:!!c,$highlightColor:C,variant:"body2",color:b,onClick:()=>c==null?void 0:c(v),maxTextLines:1},v.name))),d)},dg=p.default($)`font-weight:400;`,Ut=p.default(dg)`${({$clickable:e,$highlightColor:t})=>e&&D.css`
|
|
253
320
|
cursor: pointer;
|
|
254
321
|
text-decoration: underline;
|
|
255
322
|
&:hover {
|
|
256
323
|
color: ${t};
|
|
257
324
|
}
|
|
258
325
|
`}
|
|
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
|
-
background-color: ${
|
|
326
|
+
`,Vt=p.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,tn=p.default.div`display:flex;gap:8px;align-items:center;word-break:break-word;`,mg=p.default(tn)`cursor:pointer;gap:4px;`,kn=p.default(tn)`flex-direction:row;align-items:center;`,io=p.default.div`display:flex;gap:4px;flex-direction:column;align-items:flex-start;`,ks=u.createContext(null);function hg({testerType:e,origin:t,children:n}){return i.createElement(ks.Provider,{value:{testerType:e,isActionbookTester:e==="actionbook",origin:t}},e&&i.createElement(gg,null),n)}const dt=()=>{const e=u.useContext(ks);if(!e)throw new Error("_UNSAFE_INTERNAL_DashboardTesterProvider not found");return e},gg=()=>{const{isActionbookTester:e}=dt();return i.createElement(Ge.Template,{template:e?fg:void 0},i.createElement(Ge.MessageLogs,{component:pg}))},fg=e=>i.createElement(As,{...e,testerMode:!0,maxBodyWidth:z.WIDE_BODY_MAX_WIDTH}),pg=({extendedMessagePayload:e={}})=>{const{handlers:t}=Z(),{manual:n,groundedness:r,function_calls:o,agent_message_templates:s,is_thinking:a}=e;return a||!n&&!(r!=null&&r.length)&&!(o!=null&&o.length)&&!(s!=null&&s.length)?i.createElement(i.Fragment,null):i.createElement(_g,null,i.createElement(Eg,{width:4}),i.createElement(ws,{actionbook:n,functionCalls:o,groundedness:r,agentMessageTemplates:s,onClickFunctionCallDetail:t==null?void 0:t.onFunctionCallDetailClick,style:{iconColor:g.themedColor.textHighEmphasis,textColor:g.themedColor.textHighEmphasis,barColor:g.themedColor.textDisabled},bottomContent:i.createElement(bg,{variant:"caption2",color:g.themedColor.textLowEmphasis},"Only visible in the tester")}))},_g=p.default.div`display:flex;gap:16px;margin:16px ${z.HORIZONTAL_PADDING}px 0;align-self:stretch;`,Eg=p.default.div`width:${({width:e})=>e}px;background-color:${g.themedColor.textDisabled};border-radius:100px;flex-shrink:0;`,bg=p.default($)`margin-top:5px;`,Cg="[data-message-listitem]",vg=u.forwardRef(function(t,n){const{messages:r,renderMessage:o,loading:s,LoadingComponent:a,error:l,ErrorComponent:c,empty:d,EmptyComponent:m,messageTopArea:h,messageBottomArea:f,overlayArea:b,onLoadPrev:C,onLoadNext:v,loadThreshold:_=.05,onScroll:y=X,depsForResetScrollPositionToBottom:E,stackDirection:A="top",bottomSpacerHeight:T=0,ariaLabel:O}=t,w=u.useRef(null),N=u.useCallback(F=>{w.current=F,n&&(typeof n=="function"?n(F):n.current=F)},[n]),R=u.useRef(!1),k=u.useRef(void 0),P=u.useRef(0),I=u.useRef(0),x=u.useRef(null);u.useLayoutEffect(()=>{w.current&&(w.current.scrollTop=w.current.scrollHeight)},E),u.useLayoutEffect(()=>{if(w.current){if(k.current==="top"&&(w.current.scrollTop=w.current.scrollHeight-I.current,x.current)){const F=w.current.getRootNode();w.current.contains(F.activeElement)&&x.current.focus({preventScroll:!0}),x.current=null}k.current==="bottom"&&(w.current.scrollTop=P.current),k.current=void 0}},[w.current,r.length]);const L=async F=>{if(y==null||y(F),!w.current)return;const B=w.current;if(I.current=B.scrollHeight-B.scrollTop,P.current=B.scrollTop,R.current)return;const G=B.clientHeight*Math.min(Math.max(0,_),1);if(B.scrollTop<=G){R.current=!0,k.current="top";const me=B.getRootNode().activeElement;x.current=me==null?void 0:me.closest(Cg),await C(),R.current=!1}else B.scrollHeight-B.scrollTop-B.clientHeight<=G?(R.current=!0,k.current="bottom",await v(),R.current=!1):k.current=void 0};return l?i.createElement(i.Fragment,null,c):s?i.createElement(i.Fragment,null,a):i.createElement(yg,{id:"infinite-list-container"},i.createElement(Sg,{id:"infinite-list-inner",ref:N,onScroll:L,role:"list","aria-label":O},A==="bottom"&&i.createElement("div",{style:{flexGrow:1}}),h,d?m:r.map((F,B)=>o({message:F,index:B})),f,T>0&&i.createElement("div",{style:{minHeight:T}})),i.createElement(xg,{id:"infinite-list-overlay-container"},i.createElement(Ag,{id:"infinite-list-overlay"},b)))}),yg=p.default.div`display:flex;position:relative;flex:1;overflow:hidden;`,Sg=p.default.div`display:flex;flex:1;flex-direction:column;overflow-y:auto;overscroll-behavior:contain;scrollbar-color:${g.themedColor.textLowEmphasis}transparent;&::-webkit-scrollbar-thumb:hover{background-color:transparent;}`,xg=p.default.div`position:absolute;top:0;bottom:0;left:0;right:0;pointer-events:none;`,Ag=p.default.div`pointer-events:auto;`,Re=({as:e,type:t,size:n=16,color:r,disabled:o,children:s,...a})=>{const l=o?g.themedColor.textDisabled:g.themedColor.textHighEmphasis;return i.createElement(Tg,{as:e,disabled:o,...a},i.createElement(U,{type:t,size:n,color:r??l}),s)},Tg=p.default.button`all:unset;padding:4px;cursor:pointer;display:flex;align-items:center;justify-content:center;${de}&:disabled{cursor:not-allowed;}`,Ig=({files:e,initialIndex:t=0,onClose:n,visible:r})=>{var O,w;const[o,s]=u.useState(t),[a,l]=u.useState(!1),{stringSet:c,format:d}=Y(),{config:m}=Z(),h=e.length,f=e[o],b=((w=(O=m==null?void 0:m.conversation)==null?void 0:O.fileViewer)==null?void 0:w.downloadEnabled)!==!1,C=h>1,v=(f==null?void 0:f.type)||"",_=De(v),y=yo(v),E=!hu(v);u.useEffect(()=>{r&&(s(t),l(!1))},[r,t]);const A=u.useCallback(()=>{o>0&&(s(N=>N-1),l(!1))},[o]),T=u.useCallback(()=>{o<h-1&&(s(N=>N+1),l(!1))},[o,h]);return u.useEffect(()=>{if(!r)return;const N=R=>{R.key==="ArrowLeft"?A():R.key==="ArrowRight"&&T()};return window.addEventListener("keydown",N),()=>window.removeEventListener("keydown",N)},[r,A,T]),!r||!f?null:i.createElement(ut,{onClose:n,visible:r,rootElementId:ne.MODAL_ROOT,"aria-label":(f==null?void 0:f.name)||c.IMAGE_VIEWER__DEFAULT_TITLE},i.createElement(wg,null,i.createElement(kg,null,i.createElement(Mg,null,i.createElement(Lg,null,i.createElement($,{variant:"button",maxTextLines:1,color:g.themedColor.textHighEmphasis},f.name||c.IMAGE_VIEWER__DEFAULT_TITLE),f.timestamp&&i.createElement($,{variant:"caption2",color:g.themedColor.textMidEmphasis},d(new Date(f.timestamp),"h:mm a")))),i.createElement(Og,{type:"close",size:24,"aria-label":c.A11Y_IMAGE_VIEWER_CLOSE,onClick:n})),i.createElement(Rg,{onClick:N=>N.currentTarget===N.target&&n()},C&&i.createElement(ao,{$position:"left",type:"chevron-right",size:32,onClick:A,"aria-label":c.A11Y_IMAGE_VIEWER_PREVIOUS,disabled:o===0,$flipped:!0}),i.createElement(Ng,null,_&&i.createElement(i.Fragment,null,!a&&i.createElement($g,null,i.createElement(tt,{size:32},i.createElement(U,{type:"spinner",color:"textLowEmphasis",size:32}))),i.createElement(Dg,{src:f.url,alt:f.name||"Image",$loaded:a,onLoad:()=>l(!0)})),y&&i.createElement(Pg,{controls:!0},i.createElement("source",{src:f.url,type:v})),E&&i.createElement(Fg,null,i.createElement($,{variant:"h1",color:g.themedColor.textHighEmphasis},c.FILE_VIEWER__UNSUPPORT))),C&&i.createElement(ao,{$position:"right",type:"chevron-right",size:32,onClick:T,"aria-label":c.A11Y_IMAGE_VIEWER_NEXT,disabled:o===h-1})),i.createElement(Bg,null,i.createElement(Hg,null),C&&i.createElement($,{variant:"body3",color:g.themedColor.textHighEmphasis},o+1,"/",h),i.createElement(Ug,null,b&&!E&&i.createElement(Re,{as:"a",href:f.url,download:f.name||"file",type:"download",size:24,"aria-label":c.A11Y_IMAGE_VIEWER_DOWNLOAD})))))},wg=p.default.div`position:fixed;inset:0;outline:none;display:flex;flex-direction:column;background-color:${g.themedColor.bg_50_600};`,kg=p.default.header`display:flex;align-items:center;justify-content:space-between;padding:12px 16px;min-height:56px;border-bottom:1px solid ${g.themedColor.textDisabled};`,Mg=p.default.div`flex:1;min-width:0;padding-right:16px;`,Lg=p.default.div`display:flex;flex-direction:column;gap:2px;`,Og=p.default(Re)`flex-shrink:0;width:32px;height:32px;border-radius:50%;&:hover{background-color:${g.themedColor.bg_100_500};}`,dn=p.default.div`display:flex;align-items:center;justify-content:center;`,Rg=p.default(dn)`flex:1;min-height:0;position:relative;padding:0 16px;`,Ng=p.default(dn)`position:relative;max-width:100%;max-height:100%;`,$g=p.default(dn)`position:absolute;inset:0;`,Dg=p.default.img`max-width:100%;max-height:100%;object-fit:contain;user-select:none;-webkit-user-drag:none;opacity:${e=>e.$loaded?1:0};transition:opacity 0.3s ease;`,Pg=p.default.video`max-width:100%;max-height:100%;object-fit:contain;`,Fg=p.default(dn)`flex-direction:column;gap:16px;`,ao=p.default(Re)`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:${g.themedColor.bg_200_400};}&:disabled{opacity:0.3;}@media (max-width:480px){width:38px;height:38px;${e=>e.$position==="left"?"left: 8px;":"right: 8px;"}}`,Bg=p.default.footer`display:flex;align-items:center;justify-content:space-between;padding:16px;min-height:56px;border-top:1px solid ${g.themedColor.textDisabled};`,Hg=p.default.div`width:40px;`,Ug=p.default.div`display:flex;align-items:center;justify-content:flex-end;width:40px;`,Ms=({title:e,description:t,negativeText:n,positiveText:r,onCancel:o,onConfirm:s})=>i.createElement(Vg,null,i.createElement(zg,null,i.createElement($,{as:"div",variant:"h2",color:g.themedColor.textHighEmphasis},e)),i.createElement(Gg,null,i.createElement($,{as:"div",variant:"body3",color:g.themedColor.textMidEmphasis},t)),i.createElement(Wg,null,i.createElement(qg,{type:"button",onClick:o},i.createElement($,{variant:"button",color:g.themedColor.textHighEmphasis},n)),i.createElement(Yg,{type:"button",onClick:s},i.createElement($,{variant:"button",color:g.themedColor.textHighEmphasisInverse},r)))),Vg=p.default.div`display:flex;flex-direction:column;width:280px;border-radius:16px;overflow:hidden;background-color:${g.color.background50};${V.dark`
|
|
327
|
+
background-color: ${g.color.background500};
|
|
328
|
+
`}
|
|
329
|
+
`,zg=p.default.div`padding:24px 24px 16px;`,Gg=p.default.div`padding-inline:24px;`,Wg=p.default.div`display:flex;flex-direction:row;align-items:center;justify-content:flex-end;gap:4px;padding:16px 24px;`,qg=p.default.button`display:flex;align-items:center;justify-content:center;padding:12px 20px;border-radius:0;cursor:pointer;border:none;background:none;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;&:hover{opacity:0.8;}`,Yg=p.default.button`display:flex;align-items:center;justify-content:center;padding:12px 20px;border-radius:20px;cursor:pointer;border:none;background-color:${g.themedColor.textHighEmphasis};white-space:nowrap;overflow:hidden;text-overflow:ellipsis;&:hover{opacity:0.8;}`,zt=16,Kg=({status:e})=>e===Wt.COMPLETED?i.createElement(U,{type:"done-circle",size:zt,color:g.themedColor.textHighEmphasis}):e===Wt.CANCELED?i.createElement(U,{type:"stop-circle",size:zt,color:g.themedColor.textLowEmphasis}):i.createElement(tt,{size:zt},i.createElement(U,{type:"spinner",size:zt,color:g.themedColor.textHighEmphasis})),Ls=24,jg=8,Xg=40,Zg=({task:e,isFirst:t,isLast:n})=>i.createElement(Jg,{role:"listitem"},i.createElement(Qg,null,i.createElement(lo,{$hidden:t}),i.createElement(ef,null,i.createElement(Kg,{status:e.status})),i.createElement(lo,{$hidden:n})),i.createElement(tf,null,i.createElement($,{as:"div",variant:"body3",color:e.status===Wt.CANCELED?g.themedColor.textLowEmphasis:g.themedColor.textHighEmphasis},e.user_facing_title))),Jg=p.default.div`display:flex;gap:4px;`,Qg=p.default.div`display:flex;flex-direction:column;align-items:center;width:${Ls}px;flex-shrink:0;`,lo=p.default.div`width:1px;flex:1;transform:translateX(-25%);${({$hidden:e})=>e&&"visibility: hidden;"}background-image:repeating-linear-gradient( to bottom,${g.themedColor.textHighEmphasis}0 2px,transparent 2px 4px );`,ef=p.default.div`display:flex;height:${Ls}px;align-items:center;justify-content:center;`,tf=p.default.div`display:flex;flex:1;align-items:center;box-sizing:border-box;min-width:0;min-height:${Xg}px;padding-block:${jg}px;`,nf=({steward:e,onCancelSteward:t})=>{const{logger:n}=Z(),[r,o]=u.useState(!1),[s,a]=u.useState(!1),l=!!e.cancellation_option,c=hi(e.status);return i.createElement(rf,{$marginBottom:rn("single")},i.createElement(of,null,i.createElement(sf,null,i.createElement(af,null,i.createElement($,{as:"div",variant:"caption1",color:g.themedColor.textHighEmphasis},e.title),!!e.description&&i.createElement($,{as:"div",variant:"caption4",color:g.themedColor.textLowEmphasis},e.description)),l&&i.createElement(df,{type:"button","aria-label":"Stop steward",disabled:s,onClick:()=>o(!0)},i.createElement(U,{type:"stop",size:16,color:s?g.themedColor.textDisabled:g.themedColor.textHighEmphasis}))),i.createElement(lf,null),e.tasks.length===0?c!==Ct.IN_PROGRESS?null:i.createElement(uf,null,i.createElement(tt,{size:16},i.createElement(U,{type:"spinner",size:16,color:g.themedColor.textHighEmphasis}))):i.createElement(cf,{role:"list"},e.tasks.map((d,m)=>i.createElement(Zg,{key:d.id,task:d,isFirst:m===0,isLast:m===e.tasks.length-1})))),r&&e.cancellation_option&&i.createElement(ut,{rootElementId:ne.WINDOW,visible:r,onClose:()=>o(!1)},i.createElement(Ms,{title:e.cancellation_option.title,description:e.cancellation_option.description,negativeText:e.cancellation_option.negative_text,positiveText:e.cancellation_option.positive_text,onCancel:()=>o(!1),onConfirm:async()=>{o(!1),a(!0);try{await(t==null?void 0:t())}catch(d){n.warn("steward.cancelSteward: failed",d)}finally{a(!1)}}})))},rf=p.default.div`display:flex;flex-direction:column;margin:0 ${z.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>`${e}px`};
|
|
330
|
+
`,of=p.default.div`display:flex;flex-direction:column;border-radius:12px;overflow:hidden;padding:16px;border:1px solid ${g.themedColor.bg_300_500};background-color:${g.themedColor.bg_50_600};box-shadow:0 8px 20px rgba(0,0,0,0.12);`,sf=p.default.div`display:flex;flex-direction:row;align-items:flex-start;gap:8px;`,af=p.default.div`display:flex;flex-direction:column;gap:4px;flex:1;min-width:0;`,lf=p.default.div`height:1px;margin-block:12px;background-color:${g.themedColor.bg_200_400};`,cf=p.default.div`display:flex;flex-direction:column;`,uf=p.default.div`display:flex;width:100%;height:40px;align-items:center;justify-content:center;`,df=p.default.button`width:32px;height:32px;border-radius:50%;display:flex;align-items:center;justify-content:center;flex-shrink:0;border:none;cursor:pointer;color:${g.themedColor.textHighEmphasis};background-color:${g.themedColor.bg_200_400};&:hover:not(:disabled){opacity:0.8;}&:disabled{cursor:default;}`,mf=({className:e,label:t,onClick:n})=>{const{colors:r}=D.useTheme(),{conversation:o}=j(),s=o.newMessagesButton;return i.createElement(hf,{className:e,onClick:n,...s.props},i.createElement($,{variant:"button",color:r.base.primaryContrastContent},t),i.createElement(U,{size:16,type:"chevron-down",color:r.base.primaryContrastContent}),s.descriptionNode)},hf=p.default.button`all:unset;cursor:pointer;display:flex;align-items:center;gap:4px;padding:10px 12px 10px 16px;border-radius:24px;background-color:${({theme:e})=>e.colors.base.primary};box-shadow:0 8px 10px 1px rgba(13,13,13,0.12),0 3px 14px 2px rgba(13,13,13,0.08),0 3px 5px -3px rgba(13,13,13,0.04);&:focus{outline:none;}${de}`,ur=({iconSize:e=64,icon:t,className:n,label:r,children:o})=>i.createElement(ff,{className:n},t&&i.createElement(U,{type:t,size:e,color:g.themedColor.textLowEmphasis}),r&&i.createElement($,{variant:"body1",color:g.themedColor.textMidEmphasis},r),o),gf=p.default.div`position:relative;display:flex;justify-content:center;align-items:center;width:100%;height:100%;`,ff=p.default.div`display:flex;flex-direction:column;min-height:104px;align-items:center;gap:20px;text-align:center;`,pf=({label:e="Something went wrong",icon:t="error",action:n,...r})=>i.createElement(ur,{icon:t,label:e,...r},n&&i.createElement(_f,{onClick:n.onClick,label:n.label??"Retry"})),_f=({label:e,onClick:t})=>{const{conversation:n}=j();return i.createElement(Ef,{tabIndex:0,"aria-label":n.retryButton(e)["aria-label"],onClick:t},i.createElement(U,{type:"refresh",size:20}),i.createElement($,{variant:"button",color:g.color.primary.main},e))},Ef=p.default.button`all:unset;display:flex;cursor:pointer;gap:4px;align-items:center;justify-content:center;${de}`,bf=({iconSize:e=48,className:t})=>i.createElement(tt,{size:e,className:t}),Cf=({label:e="No channels",icon:t="chat",...n})=>i.createElement(ur,{icon:t,label:e,...n}),vf=({label:e="No messages",icon:t="message",...n})=>i.createElement(ur,{icon:t,label:e,...n}),yf=e=>{const{components:t}=mn.useContext(),n=e.type==="loading"?i.createElement(t.Loading,{...e}):e.type==="error"?i.createElement(t.Error,{...e}):e.type==="noChannels"?i.createElement(t.NoChannels,{...e}):e.type==="noMessages"?i.createElement(t.NoMessages,{...e}):null;return n&&i.createElement(gf,null,n)},mn=ke({template:yf,components:{Loading:bf,Error:pf,NoChannels:Cf,NoMessages:vf}}),vt=e=>{const{Template:t}=mn.useContext();return i.createElement(t,{...e})},Sf=[0,150,450];function xf({enabled:e}){const{state:t,actions:n}=ss(),r=u.useRef(0),o=u.useRef(t.isAwayFromBottom);o.current=t.isAwayFromBottom,u.useEffect(()=>{if(!e){r.current+=1;return}const s=r.current+1;r.current=s;const a=Sf.map(l=>setTimeout(()=>{Qe(()=>{r.current===s&&(o.current||n.scrollToBottom(!1))})},l));return()=>{r.current+=1,a.forEach(l=>clearTimeout(l))}},[n.scrollToBottom,e])}const Af=({className:e,date:t=Date.now(),style:n})=>{const{format:r,stringSet:o}=Y();return i.createElement(Tf,{id:`${Ce}-date-separator`,style:n,className:e},i.createElement($,{variant:"caption4",color:g.themedColor.textMidEmphasis},r(t,o.DATE_FORMAT__MESSAGE_LIST__DATE_SEPARATOR)))},Tf=p.default.div`display:flex;justify-content:center;align-items:center;text-align:center;word-break:break-word;`,If=({className:e,style:t,onClick:n,ariaLabel:r})=>i.createElement(wf,{className:e,style:t,onClick:n,tabIndex:0,"aria-label":r},i.createElement(U,{size:24,type:"chevron-down",color:g.color.primary.main})),wf=p.default.button`all:unset;cursor:pointer;display:flex;align-items:center;justify-content:center;width:40px;height:40px;border-radius:24px;box-shadow:0 2px 8px 0 rgba(0,0,0,0.08),0 4px 6px 0 rgba(0,0,0,0.12);${V.light`
|
|
331
|
+
background-color: ${g.color.background50};
|
|
261
332
|
&:hover {
|
|
262
|
-
background-color: ${
|
|
333
|
+
background-color: ${g.color.background100};
|
|
263
334
|
}
|
|
264
335
|
&:active {
|
|
265
|
-
background-color: ${
|
|
336
|
+
background-color: ${g.color.background200};
|
|
266
337
|
}
|
|
267
338
|
`}
|
|
268
|
-
${
|
|
269
|
-
background-color: ${
|
|
339
|
+
${V.dark`
|
|
340
|
+
background-color: ${g.color.background400};
|
|
270
341
|
&:hover {
|
|
271
|
-
background-color: ${
|
|
342
|
+
background-color: ${g.color.background500};
|
|
272
343
|
}
|
|
273
344
|
&:active {
|
|
274
|
-
background-color: ${
|
|
345
|
+
background-color: ${g.color.background700};
|
|
275
346
|
}
|
|
276
347
|
`}
|
|
277
348
|
|
|
278
349
|
&:focus {
|
|
279
350
|
outline: none;
|
|
280
351
|
}
|
|
281
|
-
|
|
282
|
-
|
|
352
|
+
|
|
353
|
+
${de}
|
|
354
|
+
`,kf=()=>null,hn=ke({template:kf,components:{DateSeparator:Af,ScrollToBottomButton:If}}),Mf=()=>{const{stringSet:e,format:t}=Y(),{agentPreviewConfigs:n={},aiAgentId:r}=Z(),{aiAgentInfo:o}=ce(),{messageSource:s}=se(),{Template:a}=Ge.useContext(),{components:l}=hn.useContext(),c=n.welcomeMessages??[],d=s.messages,m=fu(d,r),h=d[m.length+1],f=m[0]??h;return{filteredMessages:as(d,{previewWelcomeMessages:c,aiAgentUserId:r}),shouldShowOriginalDate:b=>b>0||c.length===0?!0:h&&!Ze.isSameDay(h.createdAt,(f==null?void 0:f.createdAt)??0),renderAgentPreviewWelcomeMessages:()=>c.length===0?null:i.createElement(i.Fragment,null,i.createElement(l.DateSeparator,{style:{margin:"16px 0"},date:f==null?void 0:f.createdAt}),c.map((b,C)=>{const v=C===c.length-1,_=m.length!==d.length,y=c.length===1?"single":C===0?"top":v||_?"bottom":"middle",E=(f==null?void 0:f.createdAt)??Date.now();return i.createElement("div",{key:C,role:"listitem",tabIndex:-1,"aria-label":Et({sender:(o==null?void 0:o.nickname)||"",message:b.message,messageFormat:"markdown",time:t(E,e.DATE_FORMAT__MESSAGE_TIMESTAMP),codeBlockPlaceholder:e.A11Y_CODE_BLOCK_PLACEHOLDER}),"data-message-listitem":""},i.createElement(a,{messageType:"user",message:b.message,sender:o,groupType:y,createdAt:E,extendedMessagePayload:{suggested_replies:b.suggestedReplies},suggestedRepliesDirection:n.suggestedRepliesDirection,suggestedRepliesVisible:v&&!_,isBotMessage:!0,onClickSuggestedReply:async({reply:A})=>{s.sendUserMessage({message:A})}}))}))}},Lf=()=>{const{messageSource:e,scrollSource:t}=se();u.useEffect(()=>{!t.state.isAwayFromBottom&&t.state.isScrollPositionReconciled&&e.resetNewMessages()},[t.state.isAwayFromBottom,t.state.isScrollPositionReconciled])},Of=e=>p.default(e).withConfig({shouldForwardProp:mi.default}),Rf=({style:e})=>{const{stringSet:t}=Y(),{conversation:n}=j(),{isActionbookTester:r}=dt();return!tr("powered-by")||r?null:i.createElement(Nf,{variant:"caption2",style:e},t.POWERED_BY+" ",i.createElement($f,{variant:"caption2",as:"a",href:"https://delight.ai?utm_medium=product&utm_source=aiagent&utm_campaign=fy26-glbl-ai-agent-poweredby",...n.poweredByLink,rel:rr,target:"_blank"},"Sendbird"))},Nf=p.default($)`color:${g.themedColor.textLowEmphasis};text-align:center;`,$f=Of($)`
|
|
355
|
+
color: ${g.themedColor.textLowEmphasis};
|
|
283
356
|
cursor: pointer;
|
|
284
357
|
text-decoration: none;
|
|
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
|
-
background-color: ${
|
|
358
|
+
`,Df=()=>{var c;const{stringSet:e}=Y(),{conversation:t}=j(),{channelSource:n,goToActiveConversation:r,scrollSource:o}=se(),s=ge(n.channel),a=u.useRef(s);if(u.useEffect(()=>{if(!a.current&&s){const h=setTimeout(()=>{o.actions.scrollToBottom()},100);return()=>clearTimeout(h)}a.current=s},[s,o.actions.scrollToBottom]),!((c=n.channel)!=null&&c.isAIAgent)||!s)return null;const l=t.startNewConversationButton({onActivate:r});return i.createElement(Pf,null,i.createElement(Ff,{variant:"button",color:g.themedColor.textHighEmphasis,...l},e.TALK_TO_AGENT))},Pf=p.default.div`display:flex;justify-content:center;margin-bottom:16px;`,Ff=p.default($)`border-radius:6px;box-sizing:border-box;padding:10px 20px;border:1px solid ${g.themedColor.textDisabled};cursor:pointer;user-select:none;`,Bf=()=>{var J,me,We,qe;const{Template:e}=Mt.useContext(),{Template:t}=Ge.useContext(),{Template:n}=un.useContext(),{components:r}=hn.useContext(),{stringSet:o,format:s}=Y(),{conversation:a}=j(),{config:l,cache:c,agentPreviewConfigs:d,chatSDK:m,state:h}=Z(),{userSession:f,aiAgentInfo:b,connectionError:C}=ce(),{conversation:v,channelSource:_,messageSource:y,scrollSource:E,state:{input:A,streamAnimation:T}}=se(),{isActionbookTester:O}=dt(),{filteredMessages:w,shouldShowOriginalDate:N,renderAgentPreviewWelcomeMessages:R}=Mf(),k=Bo(_.channel),[P,I]=u.useState(null),[x,L]=u.useState(null);u.useEffect(()=>{E.actions.onTypingIndicatorUpdate(!!k)},[!!k,E.actions.onTypingIndicatorUpdate]),Lf(),xf({enabled:y.initialized&&y.messages.length>0});const F=(M,fe=!1)=>{var Te;return fe?b:((Te=_.channel)==null?void 0:Te.members.find(pe=>pe.userId===M.sender.userId))??M.sender},B=M=>{if(M.sendingStatus==="failed"&&!A.disabled)return()=>L(M)},G=({message:M,index:fe})=>{const Te=gi(M),pe=w[fe-1],rt=w[fe+1],Er=w[w.length-1],pn=M===Er,ot=St(M,b.userId),H=!(b.isUserFeedbackEnabled&&ot&&!Fe.isWelcomeMessage(M)),W=fi(M,pe,rt,H),K=!ii.isSameDay((pe==null?void 0:pe.createdAt)??0,M.createdAt)&&N(fe)&&!O,ie=_e=>{I({files:_e.files.map(Ke=>({...Ke,timestamp:M.createdAt})),index:_e.index})},he=_e=>{ie({files:[_e],index:0})},Me=()=>{M.isFileMessage()&&ir(M.url)},st=K?i.createElement(r.DateSeparator,{style:{margin:"16px 0"},date:M.createdAt}):null,ye={data:M.data,maxBodyWidth:h.expanded?z.WIDE_BODY_MAX_WIDTH:void 0,extendedMessagePayload:M.extendedMessagePayload,createdAt:M.createdAt,groupType:W,onClickMedia:he,onClickMediaFiles:ie,onClickFile:Me},Ne=()=>{if(te.isOutgoing(M,f.userId))return"outgoingmessage";if(te.isIncoming(M,f.userId))return"incomingmessage"},it=M.createdAt!=null&&M.createdAt!==0?s(M.createdAt,o.DATE_FORMAT__MESSAGE_TIMESTAMP):void 0,Ye=(()=>{var Ke,ht,Ee,q,re,be;const _e=(Ke=M.message)==null?void 0:Ke.trim();if(M.isFileMessage()){const Ot=((ht=M.name)==null?void 0:ht.trim())||"";return yn({markdownText:_e,comparisonText:Ot,plainText:a.file.label(Ot,M.type)})}if(M.isMultipleFilesMessage()){const Ot=((re=(q=(Ee=M.fileInfoList)==null?void 0:Ee[0])==null?void 0:q.fileName)==null?void 0:re.trim())||"",br=((be=M.fileInfoList)==null?void 0:be.length)??0;return yn({markdownText:_e,comparisonText:Ot,plainText:br>0?o.CONVERSATION_LIST__MULTIPLE_FILES_COUNT(br):""})}return _e?yn({markdownText:_e}):Wo("")})(),ei=(()=>{if(te.isAdmin(M))return Et({message:Ye.text,messageFormat:Ye.format,codeBlockPlaceholder:o.A11Y_CODE_BLOCK_PLACEHOLDER});if(te.isOutgoing(M,f.userId))return Et({sender:o.A11Y_MESSAGE_SENDER_YOU,message:Ye.text,messageFormat:"plain",time:it,codeBlockPlaceholder:o.A11Y_CODE_BLOCK_PLACEHOLDER});if(te.isIncoming(M,f.userId))return Et({sender:F(M,ot).nickname,message:Ye.text,messageFormat:Ye.format,time:it,codeBlockPlaceholder:o.A11Y_CODE_BLOCK_PLACEHOLDER})})(),ti=(()=>{var _e,Ke,ht;if(te.isAdmin(M))return te.isCSAT(M)?v?i.createElement(n,{...ye,...v,isResolvedWhenDeterminedByUser:Ui(v),messageType:"admin.csat",onSubmitCSAT:async Ee=>{var q;await((q=_.channel)==null?void 0:q.submitCSAT(Ee))},onScrollToBottom:()=>E.actions.scrollToBottom()}):null:i.createElement(n,{...ye,messageType:"admin",message:M.message});if(te.isSteward(M))return i.createElement(nf,{steward:M.extendedMessagePayload.steward,onCancelSteward:async()=>{await m.aiAgent.cancelStewardTask({channelUrl:M.channelUrl,messageId:M.messageId})}});if(te.isOutgoing(M,f.userId)){const Ee={...ye,message:M.message,sender:F(M),sendingStatus:M.sendingStatus,onClickFailedMessage:B(M)};if(M.isUserMessage())return i.createElement(e,{messageType:"user",...Ee});if(M.isFileMessage()){const[q,re]=((_e=M.metaArrays.find(be=>be.key===Co))==null?void 0:_e.value)??[];return i.createElement(e,{messageType:"file",file:M,metadata:{aspectRatio:q&&re?`${q}/${re}`:"1/1",localFile:(Ke=M.messageParams)==null?void 0:Ke.file},...Ee})}if(M.isMultipleFilesMessage()){const{files:q,metadata:re}=jr(M);return i.createElement(e,{messageType:"multipleFiles",files:q,metadata:re,...Ee})}}if(te.isIncoming(M,f.userId)){const Ee={...ye,sender:F(M,ot),message:M.message,suggestedRepliesVisible:pn,suggestedRepliesDirection:d==null?void 0:d.suggestedRepliesDirection,isBotMessage:ot,isStreaming:Fe.isStreaming(M),isHandedOff:Ue(_.channel),isConversationClosed:ge(_.channel),isFeedbackEnabled:b.isUserFeedbackEnabled,isFeedbackCommentEnabled:b.isUserFeedbackCommentOptionEnabled,isSenderAvatarVisible:(ht=l==null?void 0:l.conversation)==null?void 0:ht.senderAvatarEnabled,onClickSuggestedReply:async({reply:q})=>{y.sendUserMessage({message:q})},onRequestMessageTemplate:async q=>{const{template:re}=await m.aiAgent.getMessageTemplate(q);return c.template.set(q,re),re},onGetCachedMessageTemplate:q=>c.template.get(q),onHandleTemplateInternalAction:q=>{if(q.type==="internal"&&q.internalData){const{method:re,payload:be}=q.internalData;re==="message.send"&&(be!=null&&be.message)&&y.sendUserMessage({message:be.message})}},onFeedbackUpdate:q=>{const re={messageId:M.messageId,channelUrl:M.channelUrl};if(!q)return m.aiAgent.deleteMessageFeedback(re);const be={...re,rating:Xd(q.rating),comment:q.comment};return Fe.hasFeedback(M)?m.aiAgent.updateMessageFeedback(be):m.aiAgent.createMessageFeedback(be)},onSubmitForm:({key:q,data:re})=>m.aiAgent.submitForm({messageId:M.messageId,channelUrl:M.channelUrl,formKey:q,formData:re}),onCancelForm:({key:q})=>m.aiAgent.cancelForm({messageId:M.messageId,channelUrl:M.channelUrl,formKey:q}),onStreamAnimationStart:()=>{T.start(M.messageId)},onStreamAnimationProgress:()=>{E.actions.onStreamingUpdate(!0)},onStreamAnimationComplete:()=>{T.stop(M.messageId),E.actions.onStreamingUpdate(!1)}};if(M.isUserMessage())return i.createElement(t,{messageType:"user",...Ee});if(M.isFileMessage())return i.createElement(t,{messageType:"file",file:M,...Ee});if(M.isMultipleFilesMessage()){const{files:q}=jr(M);return i.createElement(t,{messageType:"multipleFiles",files:q,...Ee})}}})();return i.createElement("div",{key:Te,id:`${Ce}-message-item`,role:"listitem",tabIndex:-1,"aria-label":ei,"data-message-listitem":"","data-layout-id":Ne()},st,ti)};return i.createElement(Hf,{id:`${Ce}-message-list`},i.createElement(vg,{ref:E.ref,onScroll:E.props.onScroll,stackDirection:d==null?void 0:d.messageStackDirection,messages:w,renderMessage:G,onLoadPrev:y.loadPrevious,onLoadNext:y.loadNext,depsForResetScrollPositionToBottom:[y.initialized,y.messages.length!==0],bottomSpacerHeight:E.state.bottomSpace,ariaLabel:o.A11Y_MESSAGE_LIST,loading:!y.initialized||!_.channel,empty:w.length===0&&!k,error:!!(C||_.error),LoadingComponent:i.createElement(vt,{type:"loading"}),EmptyComponent:(()=>{const M=R();return M?i.createElement("div",{style:{width:"100%"}},M):i.createElement(vt,{type:"noMessages",label:o.PLACE_HOLDER__NO_MESSAGES})})(),ErrorComponent:i.createElement(vt,{type:"error",label:(C==null?void 0:C.message)??((J=_.error)==null?void 0:J.message),action:_.error?{label:o.RETRY,onClick:()=>_.refetch()}:void 0}),messageTopArea:i.createElement(i.Fragment,null,i.createElement(Rf,{style:{marginTop:16}}),R()),messageBottomArea:i.createElement(i.Fragment,null,k&&i.createElement("div",{id:`${Ce}-message-item`,role:"listitem",tabIndex:-1,"aria-label":Et({sender:k.user.nickname,message:o.A11Y_TYPING_INDICATOR,codeBlockPlaceholder:o.A11Y_CODE_BLOCK_PLACEHOLDER}),"data-message-listitem":"",style:{marginTop:w.length===0?8:0}},i.createElement(t,{isTyping:!0,isBotMessage:k.isBot,sender:k.user,thinkingMessage:k.thinkingMessage,messageType:"user",groupType:"single",message:"",isSenderAvatarVisible:(me=l==null?void 0:l.conversation)==null?void 0:me.senderAvatarEnabled})),((We=l==null?void 0:l.conversation)==null?void 0:We.isTalkToAgentViewEnabled)&&i.createElement(Df,null)),overlayArea:i.createElement(i.Fragment,null,((qe=l==null?void 0:l.conversation)==null?void 0:qe.newMessageIndicatorEnabled)&&E.state.isAwayFromBottom&&y.newMessages.length>0&&i.createElement(Uf,{label:o.SCROLL_TO_NEW_MESSAGES_LABEL(y.newMessages),onClick:()=>E.actions.scrollToBottom()}),E.state.isAwayFromBottom&&y.newMessages.length===0&&!k&&i.createElement(r.ScrollToBottomButton,{ariaLabel:o.A11Y_SCROLL_TO_BOTTOM,onClick:()=>E.actions.scrollToBottom(),style:{position:"absolute",bottom:12,insetInlineEnd:16}}))}),P&&i.createElement(Ig,{files:P.files,initialIndex:P.index,onClose:()=>I(null),visible:!0}),x&&i.createElement(Be,{visible:!0,onClose:()=>L(null),"aria-label":o.A11Y_FAILED_MESSAGE_OPTIONS},i.createElement(Be.ActionItem,{onClick:()=>{y.resendMessage(x),L(null)}},o.FAILED_MESSAGE_RESEND),i.createElement(Be.ActionItem,{destructive:!0,onClick:()=>{y.deleteMessage(x),L(null)}},o.FAILED_MESSAGE_REMOVE)))},Hf=p.default.div`overflow-y:hidden;display:flex;flex:1;position:relative;`,Uf=p.default(mf)`position:absolute;bottom:12px;left:50%;transform:translateX(-50%);`,Vf=()=>i.createElement(Bf,null),zf=()=>{var o;const{origin:e}=dt(),{appId:t,aiAgentId:n}=ve(),{channelSource:r}=se();return(o=r.channel)!=null&&o.conversation?i.createElement(Gf,null,i.createElement(Vn,{style:{gap:4}},i.createElement(U,{color:g.themedColor.textLowEmphasis,size:12,type:"show"}),i.createElement($,{as:"i",color:g.themedColor.textLowEmphasis,variant:"caption2"},"Only visible in the tester")),i.createElement(Vn,{role:"button",style:{gap:4},onClick:()=>{var c,d;const s=e??window.location.origin,a=(d=(c=r.channel)==null?void 0:c.conversation)==null?void 0:d.id,l=`${s}/ai-agent/${t}/${n}/evaluate/conversations/${a}`;navigator.clipboard.writeText(l)}},i.createElement($,{variant:"body3",color:g.themedColor.textHighEmphasis},"Copy ",i.createElement("span",{style:{color:g.themedColor.primary}},"conversation link")),i.createElement(U,{color:g.themedColor.primary,size:14,type:"copy"}))):null},Vn=p.default.div`display:flex;justify-content:center;align-items:center;`,Gf=p.default(Vn)`flex-direction:column;padding-block:16px;background-color:${g.themedColor.bg_100_500};gap:8px;`,Wf=e=>{const t=e[0];if(!t)return e;const n=e.some(o=>De(o.type)),r=e.some(o=>!De(o.type));return n&&r?De(t.type)?e.filter(o=>De(o.type)):[t]:r?[t]:e},qf=(e,t)=>{const n=[],r=[],o=[];for(const s of e){const a=t.isSupportedMimeType(s.type),l=s.size<=t.getUploadSizeLimit(s.type);a&&l?n.push(s):a?r.push(s):o.push(s)}return{passed:n,failedBySize:r,failedByType:o}},Os=u.createContext(void 0),Yf=({children:e})=>{var N;const{chatSDK:t}=Z(),{createAttachmentRules:n}=ce(),{stringSet:r}=Y(),{channelSource:o}=se(),[s,a]=u.useState([]),{announceError:l}=an(),[c,d]=u.useState({visible:!1,title:""}),m=n({channel:o.channel,uploadSizeLimit:(N=t.appInfo)==null?void 0:N.uploadSizeLimit}),h=m.isEnabled(),f=m.maxAttachmentCount,b=R=>{d({visible:!0,title:R})},C=()=>{b(r.FILE_UPLOAD_NOTIFICATION__COUNT_LIMIT.replace("%d",f.toString()))},v=R=>{b(r.FILE_UPLOAD_NOTIFICATION__SIZE_LIMIT.replace("%d",R.toString())),l({type:"fileSizeExceeded",maxSizeMB:R})},_=R=>{b(r.FILE_UPLOAD_NOTIFICATION__FILES_EXCLUDED_BY_VALIDATION.replace("%d",R.toString()))},y=R=>R.map(k=>({file:k,preview:{url:URL.createObjectURL(k),type:k.type,name:k.name}})),E=R=>{a(k=>[...k,...y(R)])},A=R=>{a(k=>(k.forEach(P=>URL.revokeObjectURL(P.preview.url)),y(R)))},T=R=>{if(!h||R.length===0)return;if(f-s.length===0){C();return}if(s.length+R.length>f){C();return}const P=Wf(R),{passed:I,failedBySize:x,failedByType:L}=qf(P,m),F=x.length+L.length,B=P.length===1?x[0]:void 0;if(B?v(m.getUploadSizeLimitInMB(B.type)):F>0&&_(F),I.length===0)return;s.length>0&&s.every(J=>De(J.file.type))&&I.every(J=>De(J.type))?E(I):A(I)},O=R=>{a(k=>{var I;const P=(I=k[R])==null?void 0:I.preview;return P&&URL.revokeObjectURL(P.url),k.filter((x,L)=>L!==R)})},w=()=>{a(R=>(R.forEach(k=>URL.revokeObjectURL(k.preview.url)),[]))};return i.createElement(Os.Provider,{value:{files:s,addFiles:T,removeFile:O,clearFiles:w,isFileUploadEnabled:h,acceptableMimeTypes:m.supportedMimeTypes,maxAttachmentCount:m.maxAttachmentCount,showFileUploadAlert:b}},e,i.createElement(sr,{...c,onClose:()=>d({visible:!1,title:""})}))},dr=()=>{const e=u.useContext(Os);if(!e)throw new Error("useFileUpload must be used within FileUploadProvider");return e};function Kf({blurred:e,elementRef:t,document:n=window.document,onRecoverFocus:r}){const o=u.useRef(!1);e&&t.current&&n.activeElement===t.current&&(o.current=!0),u.useLayoutEffect(()=>{var s;!e&&o.current&&(r==null||r(),(s=t.current)==null||s.focus(),o.current=!1)},[e,r])}const jf=1e3,Xf=(e,t,n)=>{const{setIsSuppressed:r}=ln(),o=n??!0,s=u.useRef(!1),a=u.useRef(void 0),l=u.useCallback(c=>{var d;c&&o&&(s.current=!0,a.current=e,e==null||e.startTyping()),c||(s.current&&o&&((d=a.current)==null||d.endTyping()),s.current=!1,a.current=void 0),r(c)},[e,r,o]);_l(t,l,{enabled:o,idleMs:jf})},Zf=p.default.div`&::-webkit-scrollbar{display:none;}overflow-x:auto;display:flex;flex-direction:row;gap:10px;padding:8px 16px;background-color:transparent;`,Jf=p.default.div`display:flex;flex-shrink:0;position:relative;margin-block-start:8px;border-radius:12px;height:64px;img{border-radius:12px;object-fit:cover;width:64px;-webkit-user-drag:none;}&:hover button,&:focus-within button{opacity:1;}`,Qf=p.default.button`display:flex;align-items:center;justify-content:center;position:absolute;inset-inline-end:-8px;inset-block-start:-8px;cursor:pointer;border-radius:50%;border:none;padding:0;opacity:${({$mobile:e})=>e?1:0};transition:opacity 0.12s ease-in-out;${V.light`
|
|
359
|
+
background-color: ${g.color.background50};
|
|
287
360
|
`}
|
|
288
|
-
${
|
|
289
|
-
background-color: ${
|
|
361
|
+
${V.dark`
|
|
362
|
+
background-color: ${g.color.background500};
|
|
290
363
|
`}
|
|
291
364
|
path {
|
|
292
|
-
fill: ${
|
|
365
|
+
fill: ${g.themedColor.textMidEmphasis};
|
|
293
366
|
}
|
|
294
367
|
|
|
295
368
|
&:hover {
|
|
296
369
|
path {
|
|
297
|
-
fill: ${
|
|
370
|
+
fill: ${g.themedColor.textHighEmphasis};
|
|
298
371
|
}
|
|
299
372
|
}
|
|
300
373
|
|
|
374
|
+
&:focus-visible {
|
|
375
|
+
opacity: 1;
|
|
376
|
+
outline: 2px solid ${g.color.primary.main};
|
|
377
|
+
outline-offset: 2px;
|
|
378
|
+
}
|
|
379
|
+
|
|
301
380
|
circle {
|
|
302
|
-
stroke: ${
|
|
381
|
+
stroke: ${g.themedColor.bg_50_600};
|
|
382
|
+
}
|
|
383
|
+
`,ep=()=>{const e=wt(),{conversation:t}=j(),{files:n,removeFile:r,isFileUploadEnabled:o}=dr();return o&&n.length>0?i.createElement(Zf,null,n.map(({preview:{type:a,name:l,url:c}},d)=>{const m=t.file.removeButton(l),f=t.file.preview({name:l,mimeType:a,selected:!0}).props["aria-label"];return i.createElement(Jf,{key:c},i.createElement(Qf,{type:"button",title:m["aria-label"],"aria-label":m["aria-label"],$mobile:e,onClick:()=>r(d)},i.createElement(U,{type:"close-filled",color:g.themedColor.textMidEmphasis})),a.startsWith("image/")?i.createElement("img",{alt:f,src:c}):i.createElement(lr,{name:l,mimeType:a,type:Wn(l,a),ariaLabel:f}))})):null},tp={textArea:D.css`min-height:40px;height:40px;font-size:16px;line-height:24px;`},Rs=p.default.button`all:unset;cursor:pointer;display:flex;align-items:center;justify-content:center;width:32px;height:32px;${de}`,co=p.default.div`width:100%;position:relative;background-color:${g.themedColor.bg_100_500};border-radius:20px;`,uo=p.default.div`display:flex;flex-direction:row;align-items:flex-end;position:relative;`,mo=p.default.textarea`all:unset;display:block;flex:1;min-width:0;padding-top:8px;padding-bottom:8px;padding-inline-start:16px;padding-inline-end:12px;box-sizing:border-box;font-size:14px;line-height:20px;color:${g.themedColor.textHighEmphasis};resize:none;width:100%;height:${Yo}px;overflow-wrap:break-word;white-space:pre-wrap;overflow-x:hidden;${es&&tp.textArea};${({$focusVisible:e})=>e&&D.css`
|
|
384
|
+
outline: 2px solid ${g.themedColor.primary};
|
|
385
|
+
outline-offset: 2px;
|
|
386
|
+
`}
|
|
387
|
+
|
|
388
|
+
&::placeholder {
|
|
389
|
+
color: ${g.themedColor.textLowEmphasis};
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
&:disabled {
|
|
393
|
+
cursor: not-allowed;
|
|
394
|
+
&::placeholder {
|
|
395
|
+
color: ${g.themedColor.textDisabled};
|
|
396
|
+
}
|
|
303
397
|
}
|
|
304
|
-
`,
|
|
305
|
-
color: ${
|
|
398
|
+
`,np=p.default.input`display:none;`;p.default.div`display:flex;align-items:center;gap:24px;`;const rp=p.default(Rs)`flex-shrink:0;border-radius:8px;&:disabled{cursor:not-allowed;}&:not(:disabled){&:hover{background-color:${g.themedColor.bg_100_500};path{fill:${g.themedColor.textHighEmphasis};}}&:active{background-color:${g.themedColor.bg_200_400};}}`,ho=p.default.div`padding:10px 16px 10px 12px;position:relative;display:flex;align-items:center;gap:8px;`,go=e=>e.startsWith("image/"),fo=({disabled:e})=>{var w,N,R,k,P;const{stringSet:t}=Y(),{conversation:n}=j(),{config:r}=Z(),o=u.useRef(null),s=u.useRef(null),[a,l]=u.useState(!1),{addFiles:c,isFileUploadEnabled:d,acceptableMimeTypes:m,showFileUploadAlert:h}=dr(),f=m.includes(Ln),b=f?["image/*"]:m.filter(go),C=f?[Ln]:m.filter(I=>!go(I)),v=!!((R=(N=(w=r==null?void 0:r.conversation)==null?void 0:w.input)==null?void 0:N.gallery)!=null&&R.photoEnabled),_=!!((P=(k=r==null?void 0:r.conversation)==null?void 0:k.input)!=null&&P.fileEnabled),y=()=>f||b.length>0,E=()=>f||C.length>0,A=I=>{const x=I.currentTarget.files;x&&c(Array.from(x)),I.target.value=""},T=()=>{l(!0)},O=u.useMemo(()=>{const I=[];return v&&I.push({type:"image",icon:"photo",label:t.FILE_UPLOAD_PHOTOS,accept:b.join(","),inputRef:o,onSelect:()=>{if(!y()){h(t.FILE_UPLOAD_NO_SUPPORTED_FILES);return}l(!1),setTimeout(()=>{var x;return(x=o.current)==null?void 0:x.click()},100)}}),_&&I.push({type:"file",icon:"document",label:t.FILE_UPLOAD_FILES,accept:m.join(","),inputRef:s,onSelect:()=>{if(!E()){h(t.FILE_UPLOAD_NO_SUPPORTED_FILES);return}l(!1),setTimeout(()=>{var x;return(x=s.current)==null?void 0:x.click()},100)}}),I},[b,m,t,v,_]);return d?i.createElement(i.Fragment,null,i.createElement(rp,{...n.messageInput.attachFileButton.props,disabled:e,onClick:T},i.createElement(U,{type:"add",color:e?g.themedColor.textDisabled:g.color.primary.main,size:20}),n.messageInput.attachFileButton.descriptionNode),O.map(I=>i.createElement(np,{key:I.type,type:"file",ref:I.inputRef,multiple:I.type==="image",onChange:A,accept:I.accept})),i.createElement(Be,{visible:a,onClose:()=>l(!1),"aria-label":t.A11Y_FILE_UPLOAD_OPTIONS},O.map(I=>i.createElement(Be.ActionItem,{key:I.type,onClick:I.onSelect,icon:I.icon},I.label)))):null},op=()=>{const e=u.useRef(null),[t,n]=u.useState(""),{stringSet:r}=Y(),{conversation:o}=j(),{rootElement:s}=Z(),a=Le(s),{focusHandlers:l,isFocusVisible:c,suppressNextFocusVisible:d}=_s({focusRoot:a}),{channelSource:m,messageSource:h,state:f}=se(),{files:b,addFiles:C,clearFiles:v}=dr(),_=f.input.disabled,y=(()=>{if(!_)return r.MESSAGE_INPUT__PLACE_HOLDER;switch(f.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"steward":return r.MESSAGE_INPUT__PLACE_HOLDER__STEWARD;case"system":return r.MESSAGE_INPUT__PLACE_HOLDER__DISABLED;case"reconnecting":return r.MESSAGE_INPUT__PLACE_HOLDER__RECONNECTING;case"unavailable":case"conversation_closed":default:return r.MESSAGE_INPUT__PLACE_HOLDER__DISABLED}})();mu({onDropFiles:C}),Kf({blurred:_,elementRef:e,document:a,onRecoverFocus:()=>{d()}}),Xf(m.channel,t,!_);const E=t.trim().length>0,A=b.length>0,T=!_&&(E||A),O=()=>{e.current&&(e.current.value="",e.current.style.height=""),v(),n("")},w=async()=>{const P=t.trim();if(!P&&!b.length)return;const I=[...b];if(O(),I.length===0){h.sendUserMessage({message:P});return}if(I.length===1)await h.sendFileMessage({message:P,file:I[0].file});else{const x=I.map(({file:L})=>({file:L}));await h.sendMultipleFilesMessage({message:P,fileInfoList:x})}},N=P=>{const I=Array.from(P.clipboardData.files);I.length>0&&(P.preventDefault(),C(I))},R=P=>{P.key!=="Enter"||P.nativeEvent.isComposing||P.shiftKey||(P.preventDefault(),w())},k=P=>{if(e.current){e.current.style.height="";const I=Math.min(oc,e.current.scrollHeight);Yo<I&&(e.current.style.height=`${I}px`)}n(P.target.value)};return _?i.createElement(ho,null,i.createElement(fo,{disabled:!0}),i.createElement(co,null,i.createElement(uo,null,i.createElement(mo,{rows:1,disabled:!0,placeholder:y,$focusVisible:!1,"data-focus-visible":"false"})))):i.createElement(ho,{"data-message-composer":""},i.createElement(fo,null),i.createElement(co,null,i.createElement(ep,null),i.createElement(uo,null,i.createElement(mo,{ref:e,rows:1,role:"textbox","aria-label":r.A11Y_MESSAGE_INPUT,placeholder:y,maxLength:5e3,$focusVisible:c,"data-focus-visible":c?"true":"false",onKeyDown:R,onChange:k,onFocus:l.onFocus,onBlur:l.onBlur,onPaste:N}))),T&&i.createElement(Rs,{...o.messageInput.sendButton.props,onClick:()=>w()},i.createElement(U,{type:"send",color:g.color.primary.main,size:20}),o.messageInput.sendButton.descriptionNode))},sp=p.default.div`padding:8px 16px;text-align:center;word-break:break-word;white-space:pre-wrap;line-height:1.43;letter-spacing:-0.2px;font-size:14px;font-weight:400;color:${g.themedColor.textLowEmphasis};&& a{font-weight:700;text-decoration:none;${V.light`
|
|
399
|
+
color: ${g.color.information.light};
|
|
306
400
|
`};
|
|
307
|
-
${
|
|
308
|
-
color: ${
|
|
401
|
+
${V.dark`
|
|
402
|
+
color: ${g.color.information.main};
|
|
309
403
|
`};
|
|
310
404
|
}
|
|
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`
|
|
405
|
+
`,ip=u.lazy(()=>Promise.resolve().then(()=>require("./cjs/D2Opuq0j.cjs")).then(e=>({default:e.MarkdownText}))),ap=()=>{const{aiAgentInfo:e,userSession:t}=ce(),{messageSource:n,channelSource:r}=se(),[o,s]=u.useState(null),a=tr("special-notice",r.channel),l=u.useCallback(()=>r.channel?a?n.messages.some(c=>St(c,(t==null?void 0:t.userId)??"")):!0:null,[r.channel,a,n.messages,t==null?void 0:t.userId]);return u.useEffect(()=>{o||s(l())},[l,o]),o||!e.specialNotice?null:i.createElement(sp,null,i.createElement(ip,null,e.specialNotice))},lp=()=>i.createElement(cp,null,i.createElement(ap,null),i.createElement(Yf,null,i.createElement(op,null))),cp=p.default.div`z-index:0;border:none;width:100%;`,up=()=>{var o;const{testerType:e}=dt(),{channelSource:t}=se(),n=ge(t.channel),r=!!e&&((o=t.channel)==null?void 0:o.isAIAgent);return n&&r?i.createElement(zf,null):i.createElement(lp,null)},Ns=({start:e,title:t,titleAlign:n="start",end:r})=>{const o=u.useRef(null),s=u.useRef(null),[a,l]=u.useState(0),[c,d]=u.useState(0);return u.useLayoutEffect(()=>{o.current&&l(o.current.offsetWidth),s.current&&d(s.current.offsetWidth)},[e,r]),i.createElement(dp,null,i.createElement(mp,null,n==="center"&&t&&i.createElement(hp,{$sideWidth:Math.max(a,c)},i.createElement(gp,null,t)),i.createElement(fp,null,i.createElement(pp,{ref:o},e),(n==="start"||n==="end")&&t&&i.createElement(Ep,{$align:n,$hasStart:!!e,$hasEnd:!!r},t),i.createElement(_p,{ref:s},r))))},dp=p.default.div`position:relative;width:100%;background-color:${({theme:e})=>e.colors.base.headerBackground};border-bottom:1px solid ${g.themedColor.textDisabled};`,mp=p.default.div`position:relative;height:56px;padding:11px 12px;`,hp=p.default.div`position:absolute;left:${({$sideWidth:e})=>e}px;right:${({$sideWidth:e})=>e}px;top:0;bottom:0;display:flex;align-items:center;justify-content:center;`,gp=p.default.div`max-width:100%;overflow:hidden;`,fp=p.default.div`display:flex;flex-direction:row;align-items:center;justify-content:space-between;height:100%;z-index:1;`,pp=p.default.div`flex-shrink:0;display:flex;align-items:center;`,_p=p.default.div`flex-shrink:0;display:flex;align-items:center;`,Ep=p.default.div`flex:1;overflow:hidden;display:flex;align-items:${({$align:e})=>e==="start"?"flex-start":"flex-end"};margin-left:${({$hasStart:e})=>e?8:0}px;margin-right:${({$hasEnd:e})=>e?8:0}px;`,Lt=()=>wt()?24:16,bp=()=>{const{state:e}=Z(),{messenger:t}=j(),n=Lt(),r=()=>{e.setOpened(!1)};return i.createElement(Re,{...t.closeButton,type:"close",size:n,onClick:r})},Cp=()=>{const{enableCloseConversationButton:e,dispatcher:t}=Z(),{channelSource:n}=se(),{conversation:r}=j(),o=n.channel,s=Lt(),a=(o==null?void 0:o.isAIAgent)&&e,l=!Yn(o);if(!a)return null;const c=async()=>{o&&await t.send(Je.CloseConversation({channelUrl:o.url}))};return i.createElement(Re,{...r.closeConversationButton.props,type:"mute",size:s,disabled:l,onClick:c},r.closeConversationButton.descriptionNode)},vp=()=>{const{state:e,enableExpandButton:t}=Z(),{messenger:n}=j(),r=Lt();return t?i.createElement(Re,{...n.expandButton(e.expanded),type:e.expanded?"collapse":"expand",size:r,onClick:()=>e.setExpanded(!e.expanded)}):null},yp=({label:e,children:t,position:n="top",disabled:r})=>r?t:i.createElement(zn,null,t,i.createElement(Ap,{$position:n},i.createElement(Tp,{variant:"caption1"},e),i.createElement(Sp,{$position:n}))),Sp=({$position:e})=>i.createElement("svg",{style:{transform:e==="top"?"rotate(0)":"rotate(180deg)"},xmlns:"http://www.w3.org/2000/svg",width:"12",height:"6",viewBox:"0 0 12 6",fill:"none"},i.createElement("path",{d:"M6 6L0 0h12L6 6Z",fill:g.themedColor.textHighEmphasis})),xp={top:D.css`flex-direction:column;top:0;transform:translate(-50%,-100%);`,bottom:D.css`flex-direction:column-reverse;bottom:0;transform:translate(-50%,100%);`},zn=p.default.div`position:relative;`,Ap=p.default.div`display:flex;align-items:center;position:absolute;left:50%;z-index:${et.TOOLTIP};${({$position:e})=>xp[e]}opacity:0;transition:opacity 0.2s ease-in-out;pointer-events:none;${zn}:hover &,${zn}:focus-within &{opacity:1;}`,Tp=p.default($)`padding:6px 8px;background:${g.themedColor.textHighEmphasis};color:${g.themedColor.textHighEmphasisInverse};border-radius:4px;font-size:12px;white-space:nowrap;`,Ip=()=>{const{logger:e}=Z(),{stringSet:t}=Y(),{channelSource:n}=se(),{conversation:r}=j(),o=n.channel,s=Lt(),a=tr("handoff-button",o),l=!Yn(o)||Ue(o),[c,d]=u.useState(!1),m=async()=>{d(!1);try{const h=await(o==null?void 0:o.markConversationAsHandoff());e.info("conversation.handleAgentHandoff: success",h)}catch(h){e.error("conversation.handleAgentHandoff: error",h)}};return a?i.createElement(i.Fragment,null,i.createElement(yp,{label:t.HEADER_BUTTON__AGENT_HANDOFF,position:"bottom",disabled:l},i.createElement(Re,{...r.handoffButton.props,type:"agent",size:s,disabled:l,onClick:()=>d(!0)},r.handoffButton.descriptionNode)),i.createElement(ut,{rootElementId:ne.WINDOW,visible:c,onClose:()=>d(!1)},i.createElement(Ms,{title:t.HANDOFF_CONFIRM__TITLE,description:t.HANDOFF_CONFIRM__DESCRIPTION,negativeText:t.HANDOFF_CONFIRM__CANCEL,positiveText:t.HANDOFF_CONFIRM__HANDOFF,onCancel:()=>d(!1),onConfirm:m}))):null},wp=()=>{const{conversation:e}=j(),{onNavigateToConversationList:t}=se();return t?i.createElement(Re,{...e.menuButton.props,"data-sb-initial-focus":"true",type:"menu",size:24,onClick:()=>t()},e.menuButton.descriptionNode):null},$s=({channel:e,size:t=40})=>{const{userSession:n,aiAgentInfo:r}=ce(),{fallbackIcon:o,url:s}=nr({channel:e,aiAgentInfo:r,userSession:n}),a=D.useTheme();return s?i.createElement(gs,{src:s,size:t}):i.createElement(kp,{$size:t,$bgColor:a.colors.base.primary},i.createElement(U,{type:o,size:t*.55,color:a.colors.base.primaryContrastContent}))},kp=p.default.div`width:${({$size:e})=>e}px;height:${({$size:e})=>e}px;border-radius:50%;background-color:${({$bgColor:e})=>e};display:flex;align-items:center;justify-content:center;flex-shrink:0;`,Mp=()=>{var l,c;const{channelSource:e}=se(),{aiAgentInfo:t,userSession:n}=ce(),{config:r}=ve(),o=e.channel,s=nr({channel:o,userSession:n,aiAgentInfo:t}),a=(c=(l=r==null?void 0:r.conversation)==null?void 0:l.header)==null?void 0:c.avatarEnabled;return i.createElement(Lp,null,a&&i.createElement($s,{channel:o,size:34}),i.createElement(Op,{variant:"h2",color:g.themedColor.textHighEmphasis},s.title))},Lp=p.default.div`display:flex;flex-direction:row;align-items:center;gap:6px;overflow:hidden;`,Op=p.default($)`text-overflow:ellipsis;overflow:hidden;white-space:nowrap;padding:2px 0;`,Rp=e=>{const{components:t}=nt.useContext();return i.createElement(Ns,{start:i.createElement(t.StartArea,null),title:i.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:i.createElement(t.EndArea,null)})},Np=()=>{const{components:e}=nt.useContext();return i.createElement(e.MenuButton,null)},$p=()=>{const{components:e}=nt.useContext();return i.createElement(e.Title,null)},Dp=()=>{const{components:e}=nt.useContext();return i.createElement(Fp,null,i.createElement(e.HandoffButton,null),i.createElement(e.ConversationCloseButton,null),i.createElement(e.ExpandButton,null),i.createElement(e.CloseButton,null))},nt=ke({template:Rp,components:{StartArea:Np,TitleArea:$p,EndArea:Dp,MenuButton:wp,Title:Mp,HandoffButton:Ip,ConversationCloseButton:Cp,ExpandButton:vp,CloseButton:bp}}),Pp=()=>{const{isActionbookTester:e}=dt(),{Template:t}=nt.useContext();return e?null:i.createElement(t,{titleAlign:"start"})},Fp=p.default.div`display:flex;gap:10px;align-items:center;justify-content:center;`,Ds=({children:e,onNavigateToConversationList:t,channelUrl:n,onClearChannelUrl:r,shouldMarkAsRead:o,announcementsEnabled:s,style:a,closedChannelUrl:l,onClearClosedChannelUrl:c})=>{const{Template:d}=gn.useContext();return i.createElement(is,{onNavigateToConversationList:t,channelUrl:n??l,onClearChannelUrl:r??c,shouldMarkAsRead:o},i.createElement(Bn,null,i.createElement(Bn.Consumer,null,m=>i.createElement(kc,{announcementsActive:s},i.createElement(Bp,null),i.createElement(Up,{style:a,...m},i.createElement(d,null)),e))))},Bp=()=>(Su(),Eu(),Cu(),null),Hp=e=>{const{components:t}=gn.useContext();return i.createElement(i.Fragment,null,i.createElement(t.Header,null),i.createElement(t.Body,null),i.createElement(t.Footer,null))},gn=ke({template:Hp,components:{Header:Pp,Body:Vf,Footer:up}}),Up=p.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,{Provider:Vp,Context:zp,useContext:mr}=oe("ConversationList");function Ps({conversationListLimit:e,conversationListFilter:t,onOpenConversationView:n=X,children:r}){return i.createElement(Xa,{conversationListLimit:e,conversationListFilter:t},o=>i.createElement(Vp,{value:{...o,onOpenConversationView:n}},r))}const Gp=({channel:e})=>i.createElement($s,{channel:e}),Gn=99,Wp=e=>{var _,y;const{channel:t,onClick:n}=e,{stringSet:r,format:o}=Y(),{userSession:s,aiAgentInfo:a}=ce(),{conversationList:l}=j(),c=nr({channel:t,userSession:s,aiAgentInfo:a}),d=la(t,{formatMultipleFilesCount:r.CONVERSATION_LIST__MULTIPLE_FILES_COUNT}),m=ca(t,o,{justNow:r.DATE_FORMAT__JUST_NOW,minutesAgo:r.DATE_FORMAT__MINUTES_AGO,hoursAgo:r.DATE_FORMAT__HOURS_AGO,dateShortFormat:r.DATE_FORMAT__DATE_SHORT}),h=t.unreadMessageCount,f=(_=t.lastMessage)!=null&&_.isAdminMessage()?r.CONVERSATION_LIST__SYSTEM_MESSAGE:c.title,b=ge(t)?r.CONVERSATION_LIST__ENDED:Ro(t,{formatMultipleFilesCount:r.CONVERSATION_LIST__MULTIPLE_FILES_COUNT}),C=n?()=>n():void 0,v=l.item({agent:f,status:b,time:m,unreadCount:h,onActivate:C});return i.createElement(qp,{"data-testid":"sb-conversation-list-item",$clickable:!!C,...v.props},i.createElement(Yp,null,i.createElement(Gp,{...e})),i.createElement(Kp,null,i.createElement(jp,null,(y=t.lastMessage)!=null&&y.isFileMessage()&&(!t.lastMessage.message||t.lastMessage.name===t.lastMessage.message)?i.createElement(us,{variant:"subtitle1",color:g.themedColor.textHighEmphasis},d):i.createElement($,{variant:"subtitle1",color:g.themedColor.textHighEmphasis,maxTextLines:1},d),i.createElement(Xp,null,ge(t)&&i.createElement(i.Fragment,null,i.createElement($,{variant:"caption1",color:g.themedColor.textMidEmphasis,maxTextLines:1},r.CONVERSATION_LIST__ENDED),i.createElement(Zp,null)),i.createElement($,{variant:"caption2",color:g.themedColor.textLowEmphasis,maxTextLines:1},m))),h>0&&i.createElement(Jp,{$count:h},i.createElement($,{variant:"caption3",color:g.themedColor.textHighEmphasisInverse},h<=Gn?h:`${Gn}+`))),v.descriptionNode)},hr=ke({template:Wp,components:{}}),qp=p.default.div`display:flex;flex-shrink:0;flex-direction:row;align-items:center;position:relative;width:100%;height:72px;box-sizing:border-box;gap:16px;cursor:${({$clickable:e})=>e?"pointer":"default"};`,Yp=p.default.div`display:flex;align-items:center;justify-content:center;padding-inline-start:16px;`,Kp=p.default.div`display:flex;flex-direction:row;align-items:center;flex:1;min-width:0;padding-inline-end:16px;height:100%;gap:8px;border-bottom:1px solid ${g.themedColor.textDisabled};`,jp=p.default.div`display:flex;flex-direction:column;justify-content:center;flex:1;min-width:0;gap:4px;word-break:break-word;overflow-wrap:break-word;`,Xp=p.default.div`display:flex;align-items:center;gap:6px;`,Zp=p.default.div`width:2px;height:2px;border-radius:1px;background-color:${g.themedColor.textLowEmphasis};`,Jp=p.default.div`display:flex;align-items:center;justify-content:center;height:20px;padding:4px;border-radius:10px;background-color:${g.themedColor.error};${({$count:e})=>e<=Gn&&D.css`
|
|
312
406
|
width: 20px;
|
|
313
407
|
`}
|
|
314
|
-
`,
|
|
408
|
+
`,Qp=({items:e,renderItem:t,onEndReached:n})=>{const r=o=>{const s=o.target;s.scrollHeight-s.scrollTop===s.clientHeight&&(n==null||n())};return i.createElement(e_,{onScroll:o=>r(o)},e.map((o,s)=>t(o,s)))},e_=p.default.div`width:100%;height:100%;display:flex;flex-direction:column;flex:1;overflow:auto;overscroll-behavior:contain;`,t_=()=>{const{stringSet:e}=Y(),{listSource:t,onOpenConversationView:n}=mr(),{Template:r}=hr.useContext();return t.initialized?t.channels.length===0?i.createElement(vt,{type:"noChannels",label:e.CONVERSATION_LIST__NO_CONVERSATIONS}):i.createElement(Qp,{items:t.channels,renderItem:o=>{var s,a,l;return i.createElement(r,{key:o.url,channel:o,onClick:()=>n(o.url,ge(o)?"closed":"open"),channelUrl:o.url,title:(a=(s=o.conversation)==null?void 0:s.topics)==null?void 0:a.join(", "),lastMessageTimestamp:(l=o.lastMessage)==null?void 0:l.createdAt})},onEndReached:()=>{t.loadMore()}}):i.createElement(vt,{type:"loading"})},n_=()=>{const{stringSet:e}=Y(),{_aiAgentSDK:t}=ve(),{language:n,countryCode:r,context:o}=Z(),{aiAgentInfo:s,refreshActiveChannel:a,createConversation:l}=ce(),{onOpenConversationView:c}=mr(),{conversationList:d}=j(),m=async()=>{var h;if(s.isMultipleActiveConversationsEnabled){const f=await l({aiAgentId:s.userId,language:n,country:r,context:o});(h=t.session)==null||h._updateActiveChannel({url:f,status:"open"}),c(f,"open")}else{const f=await a();c(f,"open")}};return i.createElement(r_,{...d.footer.button({onActivate:m})},i.createElement(o_,{variant:"h1"},e.TALK_TO_AGENT))},r_=p.default.div`background-color:${({theme:e})=>e.colors.base.primary};display:flex;align-items:center;justify-content:center;padding:16px;cursor:pointer;`,o_=p.default($)`color:${({theme:e})=>e.colors.base.primaryContrastContent};overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,s_=()=>{const{state:e}=Z(),{messenger:t}=j(),n=Lt(),r=()=>{e.setOpened(!1)};return i.createElement(Re,{...t.closeButton,type:"close",size:n,onClick:r})},i_=()=>{const{stringSet:e}=Y();return i.createElement(a_,{forwardedAs:"h2",variant:"h2",color:g.themedColor.textHighEmphasis},e.CONVERSATION_LIST__HEADER_TITLE)},a_=p.default($)`margin:0;padding:0 4px;width:100%;box-sizing:border-box;text-overflow:ellipsis;overflow:hidden;white-space:nowrap;`,l_=e=>{const{components:t}=mt.useContext();return i.createElement(Ns,{start:i.createElement(t.StartArea,null),title:i.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:i.createElement(t.EndArea,null)})},c_=()=>null,u_=()=>{const{components:e}=mt.useContext();return i.createElement(e.Title,null)},d_=()=>{const{components:e}=mt.useContext();return i.createElement(e.CloseButton,null)},mt=ke({template:l_,components:{StartArea:c_,TitleArea:u_,EndArea:d_,Title:i_,CloseButton:s_}}),m_=()=>{const{Template:e}=mt.useContext();return i.createElement(e,{titleAlign:"start"})},Fs=({conversationListLimit:e,conversationListFilter:t,children:n,onOpenConversationView:r,style:o})=>{const{Template:s}=fn.useContext();return i.createElement(Ps,{conversationListLimit:e,conversationListFilter:t,onOpenConversationView:r},i.createElement(g_,{style:o},i.createElement(s,null)),n)},h_=()=>{const{components:e}=fn.useContext();return i.createElement(i.Fragment,null,i.createElement(e.Header,null),i.createElement(e.Body,null),i.createElement(e.Footer,null))},fn=ke({template:h_,components:{Header:m_,Body:t_,Footer:n_}}),g_=p.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,f_=D.css`:where(#${ne.ENTRY}) :not(code *){font-family:'Roboto',sans-serif;box-sizing:border-box;}`,p_=[f_,pc,_c],__=(e,...t)=>D.createGlobalStyle(e,...p_,...t),E_=__``,b_=aa(gn,Ge,Mt,un,hn,fn,nt,hr,mt,mn);function Bs({appearance:e,rootElement:t,logger:n,language:r,languageCode:o,stringSet:s,children:a,messageTemplate:l,theme:c}){return yc(cc,t),i.createElement(D.StyleSheetManager,{target:t},i.createElement(bc,{rootElement:t,logger:n,appearance:e,theme:c},i.createElement(Qa,{internalVariables:l==null?void 0:l.__internalVariables},i.createElement(fc,{stringSet:s,logger:n,language:r,languageCode:o},i.createElement(b_,null,a,i.createElement(E_,null))))))}const gr=u.forwardRef(function({rootElement:t=document.body,logLevel:n=Q.LogLevel.WARN,language:r=navigator.language,userSessionInfo:o,children:s,chatParams:a,...l},c){var h,f,b;bt.level!==n&&(bt.level=n),vc("https://fonts.googleapis.com/css2?family=Roboto&display=swap",t);const d=jo(r),m=Xo.has(d)?d:It;return i.createElement("div",{id:ne.ENTRY,lang:m,style:{width:"fit-content",height:"fit-content",...l.entryStyle}},i.createElement(Bs,{logger:bt,rootElement:t,appearance:(h=l.agentPreviewConfigs)==null?void 0:h.appearance,stringSet:l.stringSet,language:m,messageTemplate:l.messageTemplate,theme:l.theme},i.createElement(Lc,{rootElement:t,language:r,logger:bt,dispatcher:Hs,chatParams:{...a,...l.customApiHost&&{customApiHost:l.customApiHost},...l.customWebSocketHost&&{customWebSocketHost:l.customWebSocketHost}},chatSDK:l.customChatSDK,_forceCreateChannel:(f=l.agentPreviewConfigs)==null?void 0:f.forceCreateChannel,_agentVersion:(b=l.agentPreviewConfigs)==null?void 0:b.agentVersion,...l},i.createElement(jc,{ref:c,userSessionInfo:o},i.createElement(hg,{...l._UNSAFE_INTERNAL_dashboardTester},i.createElement(Ic,null,s,i.createElement("div",{id:ne.MODAL_ROOT,dir:l.dir})))))))}),bt=new Io(Q.LogLevel.WARN),Hs=new To(bt),{Provider:C_,useContext:fr}=oe("PageChildren"),Us=({children:e})=>{const[t,n]=u.useState(null),[r,o]=u.useState(null);return i.createElement(C_,{value:{conversationChildren:t,setConversationChildren:n,conversationListChildren:r,setConversationListChildren:o}},e)},Vs=({children:e,isOpened:t})=>{const{dir:n,rootElement:r}=Z(),o=Le(r,!0);return u.useEffect(()=>{const s="sb-agent-block-scroll";return t?o.body.classList.add(s):o.body.classList.remove(s),()=>{o.body.classList.remove(s)}},[o,t]),i.createElement(v_,{dir:n,$visible:t},e)},v_=p.default.div`width:100%;height:100%;position:fixed;top:0;left:0;z-index:${et.WINDOW};visibility:${({$visible:e})=>e?"visible":"hidden"};`,y_=48,S_=2/3;function zs({className:e,children:t,isOpened:n,onClick:r,ariaLabel:o,"aria-label":s,"aria-describedby":a,type:l,imageUrl:c,dir:d,animated:m=!0,backgroundColor:h,size:f=y_}){const b=ps(),C=m&&!b,v=Dn(h),_=Math.round(f*S_),y=s??o;return i.createElement(T_,{dir:d,id:ne.LAUNCHER,className:e,"aria-label":y??"Sendbird AIAgent Launcher","aria-describedby":a,onClick:r,$animated:C,$backgroundColor:h,$prefersReducedMotion:b,$size:f},i.createElement(I_,{$isOpened:n,$animated:C,$fillColor:v,$iconSize:_,$prefersReducedMotion:b},i.createElement(po.Open,{url:c,isDefaultIcon:l==="default_icon",size:_})),i.createElement(w_,{$isOpened:n,$animated:C,$fillColor:v,$iconSize:_,$prefersReducedMotion:b},i.createElement(po.Close,{size:_})),t)}const x_=D.css`&:hover{transition:transform 250ms cubic-bezier(0.33,0,0,1);transform:scale(1.1);}&:active{transform:scale(0.8);}`,A_=D.css`img{width:100%;height:100%;object-fit:cover;user-select:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;-webkit-user-drag:none;&[data-default-icon='true']{width:${({$iconSize:e})=>e}px;height:${({$iconSize:e})=>e}px;filter:${({$fillColor:e})=>e===yt.WHITE?"grayscale(100%) brightness(2000%)":"grayscale(100%) invert(100%) saturate(0%) brightness(0%) contrast(1000%)"};}}`,Gs=D.css`svg{width:${({$iconSize:e})=>e}px;height:${({$iconSize:e})=>e}px;${({$fillColor:e})=>D.css`
|
|
315
409
|
ellipse,
|
|
316
410
|
path {
|
|
317
411
|
fill: ${e};
|
|
@@ -321,15 +415,25 @@
|
|
|
321
415
|
}
|
|
322
416
|
`}
|
|
323
417
|
}
|
|
324
|
-
`,
|
|
418
|
+
`,T_=p.default.button`position:relative;padding:0;width:${({$size:e})=>e}px;height:${({$size:e})=>e}px;background:${({$backgroundColor:e})=>e};border-radius:50%;transition:${({$prefersReducedMotion:e})=>e?"none":"all 0.3s cubic-bezier(0.31, -0.105, 0.43, 1.4)"};border:none;display:flex;justify-content:center;align-items:center;box-shadow:0 16px 24px 2px rgba(33,33,33,0.12),0 6px 30px 5px rgba(33,33,33,0.08),0 6px 10px -5px rgba(33,33,33,0.04);${({$animated:e})=>e&&x_}`,Ws=p.default.span.attrs({"aria-hidden":"true"})`
|
|
419
|
+
position: absolute;
|
|
420
|
+
width: 100%;
|
|
421
|
+
height: 100%;
|
|
422
|
+
border-radius: 50%;
|
|
423
|
+
overflow: hidden;
|
|
424
|
+
user-select: none;
|
|
425
|
+
display: flex;
|
|
426
|
+
justify-content: center;
|
|
427
|
+
align-items: center;
|
|
428
|
+
`,I_=p.default(Ws)`transition:${({$prefersReducedMotion:e})=>e?"none":"transform 0.16s linear, opacity 0.08s linear, scale 0.16s linear"};opacity:${({$isOpened:e})=>e?0:1};transform:${({$animated:e,$isOpened:t})=>e&&(t?"rotate(-90deg) scale(0)":"rotate(0deg)")};${A_}${Gs}`,w_=p.default(Ws)`transition:${({$prefersReducedMotion:e})=>e?"none":"transform 0.16s linear, opacity 0.08s linear, scale 0.16s linear"};scale:${({$isOpened:e})=>e?1:0};transform:${({$animated:e,$isOpened:t})=>e&&(t?"rotate(0deg)":"rotate(-90deg)")};${Gs}`,po={Open:e=>e.url?i.createElement("img",{src:e.url,alt:"","data-default-icon":e.isDefaultIcon}):i.createElement(U,{size:e.size,type:"delight"}),Close:({size:e})=>i.createElement(U,{size:e,type:"chevron-down"})},k_='[data-sb-initial-focus="true"]',M_=e=>{if(!e.isConnected||e.hidden)return!1;let t=e;const n=e.ownerDocument.defaultView;for(;t;){if(t.hidden||t.getAttribute("aria-hidden")==="true")return!1;if(n){const r=n.getComputedStyle(t);if(r.display==="none"||r.visibility==="hidden")return!1}t=t.parentElement}return!0},_o=(e,t)=>Array.from(e.querySelectorAll(t)).find(M_)??null,qs=e=>_o(e,k_)??_o(e,ns),L_=e=>{const t=qs(e)??e;t===e&&!t.hasAttribute("tabindex")&&t.setAttribute("tabindex","-1"),t.focus()},O_=(e,t)=>{u.useEffect(()=>{if(!e||!t.current)return;let n=!1;return Qe(()=>{n||!t.current||L_(t.current)}),()=>{n=!0}},[e,t])};function Ys({className:e,size:t,entryPoint:n="Conversation",activeRoute:r}){const{colors:o}=D.useTheme(),{dir:s,rootElement:a,state:l}=Z(),{launcher:c}=j(),{launcherInfo:d,statsTrackers:m}=ce(),h=(r??n)==="ConversationList",f=c.button({isOpened:l.opened,opensConversationList:h}),b=Le(a);u.useLayoutEffect(()=>{m.initialRender.setPresentMethod("launcher_toggle")},[m]),N_();const C=E=>b.querySelector(`#${E}`),v=()=>{Qe(()=>{const E=C(ne.WINDOW),A=E?qs(E):null;A==null||A.focus()})},_=()=>{Qe(()=>{var E;(E=C(ne.LAUNCHER))==null||E.focus()})},y=()=>{const E=!l.opened;l.setOpened(E),E?v():_()};return i.createElement(zs,{dir:s,className:e,isOpened:l.opened,onClick:y,type:d.type,imageUrl:d.imageUrl,backgroundColor:o.base.primary,size:t,...f.props},f.descriptionNode)}const R_=1e3*60;function N_(){const{chatSDK:e,state:t,logger:n,enableAutoDisconnectInLauncher:r}=Z(),o=u.useRef(null);u.useEffect(()=>{if(!r)return;function s(){o.current&&(clearTimeout(o.current),o.current=null)}function a(){e.connectionState===Q.ConnectionState.CLOSED&&(e.reconnect(),n.debug("useSDKInactivityTimeout: reconnected")),s(),n.debug("useSDKInactivityTimeout: clear disconnect schedule")}function l(){s(),o.current=setTimeout(async()=>{await e.disconnectWebSocket(),n.debug("useSDKInactivityTimeout: disconnected")},R_)}t.opened?a():(l(),n.debug("useSDKInactivityTimeout: schedule disconnect"))},[r,e,t.opened])}const Ks=u.createContext(null);function pr(){const e=u.useContext(Ks);if(!e)throw new Error("useNavigator() must be used within <Navigator />");return e}function js({children:e}){const t=pr();return typeof e=="function"?e(t):i.createElement(i.Fragment,null,e)}const $_=D.keyframes`0%{transform:translateY(40px);opacity:0;}100%{transform:translateY(0px);opacity:1;}`,D_=D.keyframes`0%{transform:translateY(0px);opacity:1;}100%{transform:translateY(40px);opacity:0;}`,P_=D.css`animation-name:${$_};animation-duration:0.3s;animation-fill-mode:forwards;`,F_=D.css``,B_=D.css`animation-name:${D_};animation-duration:0.3s;animation-fill-mode:forwards;`,H_=D.css`visibility:hidden;`,U_=p.default.div`position:absolute;top:0;left:0;width:100%;height:100%;${({$transitionState:e})=>{switch(e){case"entering":return P_;case"entered":return F_;case"exiting":return B_;case"exited":return H_;default:return""}}}${({$active:e})=>e?D.css`
|
|
325
429
|
z-index: 999;
|
|
326
|
-
`:
|
|
327
|
-
`;function
|
|
430
|
+
`:D.css`z-index:1;pointer-events:none;`}
|
|
431
|
+
`;function Gt({initialId:e,children:t}){const[n,r]=u.useState([e]),o=n[n.length-1],s=u.useCallback((_,y)=>{r(E=>[...E,_]),h(E=>({...E,[_]:!0})),y!=null&&y.reset&&v(E=>({...E,[_]:(E[_]||0)+1})),b(E=>({...E,[_]:"entering"})),setTimeout(()=>{b(E=>({...E,[_]:"entered"}))},300)},[]),a=u.useCallback(()=>{r(_=>{if(_.length<=1)return _;const y=_[_.length-1];return b(E=>({...E,[y]:"exiting"})),setTimeout(()=>{b(E=>({...E,[y]:"exited"})),r(E=>E.slice(0,-1))},300),_})},[]),l=u.useMemo(()=>({navigation:{navigate:s,pop:a},activeScreenId:o}),[s,a,o]),c=u.useMemo(()=>u.Children.toArray(t).filter(_=>_.type===js),[t]),d=u.useMemo(()=>{const _={};return c.forEach(y=>{const{id:E,lazy:A,children:T}=y.props;_[E]={lazy:A,element:typeof T=="function"?T(l):T}}),_},[c,l]),[m,h]=u.useState(()=>{const _={};return Object.entries(d).forEach(([y,{lazy:E}])=>{E===!1&&(_[y]=!0)}),_[e]=!0,_}),[f,b]=u.useState(()=>{const _={};return Object.keys(d).forEach(y=>{y===e?_[y]="entered":_[y]="exited"}),_}),[C,v]=u.useState({});return i.createElement(Ks.Provider,{value:l},i.createElement(V_,null,Object.keys(d).map(_=>{var T;if(!m[_])return null;const y=f[_]||"exited",E=_===o,A=`${_}-${C[_]||0}`;return i.createElement(U_,{key:A,$transitionState:y,$active:E},(T=d[_])==null?void 0:T.element)})))}const V_=p.default.div`position:relative;width:100%;height:100%;`;Gt.Screen=js;const Se={conv:"conv",convList:"conv-list"},Eo=({isOpened:e,activeScreenId:t})=>e&&t===Se.conv,z_=({screenId:e,conversationKey:t})=>e===Se.conv?`${e}:${t??""}`:e,G_=({initialRoute:e,isOpened:t,selectedChannelUrl:n,setSelectedChannelUrl:r})=>{const{announceScreenEntry:o}=an(),s=u.useRef(null),a=u.useRef(null),l=u.useCallback(h=>{const f=z_(h);s.current!==f&&(s.current=f,a.current=h,h.screenId===Se.convList&&o({screen:"conversationList"}))},[o]),c=u.useCallback((h,f)=>{const b={screenId:Se.conv,conversationKey:f};r(f),h.navigate(Se.conv),a.current=b,t&&l(b)},[l,t,r]),d=u.useCallback(h=>{a.current={screenId:Se.convList},h.navigate(Se.convList)},[]),m=u.useCallback(()=>{l({screenId:Se.convList})},[l]);return u.useEffect(()=>{if(t){const h=a.current?a.current.screenId===Se.conv?{screenId:Se.conv,conversationKey:n??a.current.conversationKey}:a.current:{screenId:e,conversationKey:e===Se.conv?n:void 0};l(h)}else s.current=null},[l,e,t,n]),{announceConversationListScreen:m,navigateToConversationList:d,openConversation:c}},Xe={conv:"conv",convList:"conv-list"},W_=e=>e===Xe.convList?"ConversationList":"Conversation",Xs=({isOpened:e,entryPoint:t,selectedChannelUrl:n,setSelectedChannelUrl:r,onActiveRouteChange:o})=>{const{conversationChildren:s,conversationListChildren:a}=fr(),l=(()=>{switch(t){case"Conversation":return Xe.conv;case"ConversationList":return Xe.convList;default:return Xe.conv}})(),{announceConversationListScreen:c,navigateToConversationList:d,openConversation:m}=G_({initialRoute:l,isOpened:e,selectedChannelUrl:n,setSelectedChannelUrl:r}),h=i.createElement(i.Fragment,null,i.createElement(q_,{onOpenConversationView:(f,b)=>m(f,b)}),i.createElement(K_,{onActiveRouteChange:o}));return i.createElement(Gt,{initialId:l},i.createElement(Gt.Screen,{id:Xe.conv},({navigation:f,activeScreenId:b})=>i.createElement(Ds,{key:n,channelUrl:n,onClearChannelUrl:()=>r(void 0),onNavigateToConversationList:()=>d(f),announcementsEnabled:Eo({isOpened:e,activeScreenId:b}),shouldMarkAsRead:Eo({isOpened:e,activeScreenId:b})},h,s)),i.createElement(Gt.Screen,{id:Xe.convList,lazy:!0},({navigation:f,activeScreenId:b})=>{const C=e&&b===Xe.convList;return i.createElement(Fs,{onOpenConversationView:v=>{m(f,v)}},i.createElement(Y_,{enabled:C,onAnnounce:c}),h,a)}))},q_=({onOpenConversationView:e})=>{const{registerOnJoinedProactiveConversation:t}=ce(),{navigation:n}=pr();return t(({channel:r})=>{e(n,r.url)}),null},Y_=({enabled:e,onAnnounce:t})=>(u.useEffect(()=>{if(!e)return;const n=setTimeout(()=>{t()},0);return()=>{clearTimeout(n)}},[e,t]),null),K_=({onActiveRouteChange:e})=>{const{activeScreenId:t}=pr();return u.useEffect(()=>{e==null||e(W_(t))},[t,e]),null},j_=`#${ne.WINDOW} [role="dialog"][aria-modal="true"], #${ne.MODAL_ROOT} [role="dialog"][aria-modal="true"]`,X_=e=>!!e.querySelector(j_),Zs=(e,t)=>u.useCallback(n=>{var r;if(n.key==="Escape"&&e){const s=n.currentTarget.getRootNode();if(X_(s))return;n.stopPropagation(),t(!1),(r=s.querySelector(`#${ne.LAUNCHER}`))==null||r.focus()}},[e,t]),Z_=({isExpanded:e,isOpened:t,children:n,launcher:r})=>{const{dir:o,state:s}=Z(),a=Zs(t,s.setOpened),l=u.useRef(null);return O_(t,l),i.createElement(J_,null,i.createElement(Q_,{ref:l,dir:o,id:ne.WINDOW,$isExpanded:e,$isOpened:t,onKeyDown:a},n),r)},J_=p.default.div`display:flex;flex-direction:column;gap:8px;align-items:flex-end;`,Q_=p.default.div`background:${({theme:e})=>e.colors.base.background};display:flex;overscroll-behavior:none;-webkit-overflow-scrolling:auto;height:640px;min-height:80px;width:400px;max-width:80vw;max-height:80vh;box-shadow:0px 16px 24px 2px rgba(33,33,33,0.12),0px 6px 30px 5px rgba(33,33,33,0.08),0px 6px 10px -5px rgba(33,33,33,0.04);border-radius:16px;overflow:hidden;transition:width 200ms ease 0s,height 200ms ease 0s,max-height 200ms ease 0s,transform 150ms cubic-bezier(0,1.2,1,1) 0s,opacity 83ms ease-out 0s;transform:scale(0.15);opacity:0;transform-origin:right bottom;[dir='rtl'] &:not([dir='ltr']),&[dir='rtl']{transform-origin:left bottom;}${({$isOpened:e})=>e&&tE};${({$isExpanded:e})=>e&&eE};`,eE=D.css`width:743px;height:723px;`,tE=D.css`z-index:${et.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;`,nE=u.forwardRef(function({children:e,initialChannelUrl:t,...n},r){const o=wt(),[s,a]=u.useState(t),[l,c]=u.useState(n.entryPoint??"Conversation"),d=o?Vs:Z_;return i.createElement(gr,{enableExpandButton:!o,ref:r,...n},i.createElement(Qo,null,({state:m})=>i.createElement(Us,null,i.createElement(d,{isExpanded:m.expanded,isOpened:m.opened,launcher:i.createElement(Ys,{entryPoint:n.entryPoint,activeRoute:l})},i.createElement(Xs,{isOpened:m.opened,entryPoint:n.entryPoint,selectedChannelUrl:s,setSelectedChannelUrl:a,onActiveRouteChange:c})),e)))}),{Provider:rE,useContext:_r}=oe("FixedMessengerStyle");function Js(e,t,n,r=0){const{top:o,bottom:s,start:a,end:l}=n;let c="",d="";switch(e){case"start":d=`inset-inline-start: ${we(a)}`;break;case"end":d=`inset-inline-end: ${we(l)}`;break}switch(t){case"top":c=`top: calc(${we(o)} + ${r}px)`;break;case"bottom":c=`bottom: calc(${we(s)} + ${r}px)`;break}return D.css`${c};${d};`}function oE(e){const{horizontal:t,vertical:n,margin:r,launcherSize:o}=_r();return i.createElement(sE,{...e,size:o,$horizontal:t,$vertical:n,$margin:r})}const sE=p.default(Ys)`position:fixed;z-index:${et.LAUNCHER};${({$horizontal:e,$vertical:t,$margin:n})=>Js(e,t,n)};`,iE=({isExpanded:e,isOpened:t,children:n})=>{const{dir:r,state:o}=Z(),{horizontal:s,vertical:a,margin:l,launcherSize:c}=_r(),d=Zs(t,o.setOpened);return i.createElement(aE,{dir:r,id:ne.WINDOW,$isExpanded:e,$isOpened:t,$horizontal:s,$vertical:a,$margin:l,$launcherSize:c,onKeyDown:d},n)},aE=p.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})=>Js(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
432
|
[dir='rtl'] &:not([dir='ltr']),
|
|
329
433
|
&[dir='rtl'] {
|
|
330
434
|
transform-origin: ${({$horizontal:e,$vertical:t})=>`${e==="start"?"right":"left"} ${t}`};
|
|
331
435
|
}
|
|
332
436
|
|
|
333
|
-
${({$isOpened:e})=>e&&
|
|
334
|
-
${({$isExpanded:e})=>e&&
|
|
335
|
-
`,
|
|
437
|
+
${({$isOpened:e})=>e&&cE};
|
|
438
|
+
${({$isExpanded:e})=>e&&lE};
|
|
439
|
+
`,lE=D.css`width:743px;height:723px;`,cE=D.css`z-index:${et.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;`,Qs={top:24,bottom:24,start:24,end:24},uE=u.forwardRef(function({children:e,initialChannelUrl:t,...n},r){const[o,s]=u.useState(t),[a,l]=u.useState(n.entryPoint??"Conversation"),[c,d]=u.useState("end-bottom"),[m,h]=u.useState(Qs),[f,b]=u.useState(48),C=wt(),v=C?Vs:iE,{horizontal:_,vertical:y}=u.useMemo(()=>{const[E,A]=c.split("-");return{horizontal:E==="start"?"start":"end",vertical:A==="top"?"top":"bottom"}},[c]);return i.createElement(gr,{enableExpandButton:!C,ref:r,...n},i.createElement(Qo,null,({state:E})=>i.createElement(rE,{value:{horizontal:_,vertical:y,margin:m,launcherSize:f,setPosition:d,setMargin:h,setLauncherSize:b}},i.createElement(Us,null,i.createElement(v,{isExpanded:E.expanded,isOpened:E.opened},i.createElement(Xs,{isOpened:E.opened,entryPoint:n.entryPoint,selectedChannelUrl:o,setSelectedChannelUrl:s,onActiveRouteChange:l})),i.createElement(oE,{entryPoint:n.entryPoint,activeRoute:a}),e))))}),dE=e=>{var o,s,a,l;const{setPosition:t,setMargin:n,setLauncherSize:r}=_r();return u.useLayoutEffect(()=>{e.position&&t(e.position),e.margin&&n({...Qs,...e.margin}),e.launcherSize&&r(e.launcherSize)},[e.position,(o=e.margin)==null?void 0:o.top,(s=e.margin)==null?void 0:s.bottom,(a=e.margin)==null?void 0:a.start,(l=e.margin)==null?void 0:l.end,e.launcherSize]),null},mE=({children:e})=>{const{setConversationChildren:t}=fr();return u.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},hE=({children:e})=>{const{setConversationListChildren:t}=fr();return u.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},gE=Object.assign(uE,{Style:dE,ConversationChildren:mE,ConversationListChildren:hE}),fE=e=>{const{refreshActiveChannel:t}=ce(),[n,r]=u.useState(!1),o=u.useRef(null),s=u.useRef(null);return u.useEffect(()=>{n&&t().then(()=>{var a;(a=o.current)==null||a.call(o),r(!1)}).catch(a=>{var l;(l=s.current)==null||l.call(s,a),r(!1)})},[n]),u.useCallback(()=>new Promise((a,l)=>{o.current=a,s.current=l,e().then(()=>r(!0)).catch(l)}),[e])};Lo.set(Q.SendbirdPlatform.JS,{deviceOSPlatform:yi()?Q.DeviceOsPlatform.MOBILE_WEB:Q.DeviceOsPlatform.WEB,messengerVersion:sc,keyValueStorage:ac(),networkStateAdapter:ic()});exports.ANCHOR_REL=rr;exports.AgentProviderContainer=gr;exports.AgentUIProviderContainer=Bs;exports.AnonymousSessionInfo=Nn;exports.CSATType=Ie;exports.Commands=Je;exports.Conversation=Ds;exports.ConversationContext=cu;exports.ConversationContextProvider=is;exports.ConversationHeaderLayout=nt;exports.ConversationLayout=gn;exports.ConversationList=Fs;exports.ConversationListContext=zp;exports.ConversationListContextProvider=Ps;exports.ConversationListHeaderLayout=mt;exports.ConversationListItemLayout=hr;exports.ConversationListLayout=fn;exports.DefaultMessenger=nE;exports.DeskTicketPriority=Zn;exports.DeskTicketStatus=Xn;exports.FixedMessenger=gE;exports.IncomingMessageLayout=Ge;exports.LauncherBase=zs;exports.LogLevel=qn;exports.ManualSessionInfo=wo;exports.MessageListUILayout=hn;exports.MessageLogs=ws;exports.OutgoingMessageLayout=Mt;exports.PlaceholderLayout=mn;exports.SystemMessageLayout=un;exports.cssVars=g;exports.escapeMarkdownSyntax=Ci;exports.mapCommonStringsToReactFormat=Ko;exports.messengerDispatcher=Hs;exports.useAIAgentContext=ve;exports.useConversationContext=se;exports.useConversationListContext=mr;exports.useLocalizationContext=Y;exports.useMessengerContext=Z;exports.useMessengerSessionContext=ce;exports.useRefreshActiveChannel=fE;
|