@sendbird/ai-agent-messenger-react 1.40.0 → 1.41.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +164 -164
- package/dist/index.d.ts +902 -26
- package/dist/index.js +5326 -4707
- package/package.json +11 -7
package/dist/index.cjs
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`)?i.index+1:i.index;r(e.slice(o,c)),n("fence",e.slice(c,i.index+i[0].length)),o=i.index+i[0].length}return r(e.slice(o)),t},
|
|
1
|
+
"use strict";var Bc=Object.defineProperty;var Hc=(e,t,n)=>t in e?Bc(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var S=(e,t,n)=>Hc(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const _e=require("@sendbird/chat"),l=require("react"),F=require("styled-components"),gt=require("date-fns"),Gc=require("date-fns/locale/en-US"),we=require("@sendbird/chat/message"),Ce=require("@sendbird/chat/aiAgent"),zc=require("react-dom"),rt=require("@sendbird/chat/groupChannel"),Vc=require("date-fns/isSameDay"),fi=e=>e&&e.__esModule?e:{default:e};function Kc(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 qc=fi(_e),a=Kc(l),b=fi(F),gi=e=>{try{return JSON.parse(e===""?"{}":e)}catch{return{}}},pi=e=>{const t=gi(e);return typeof t=="object"&&t!==null?t:{}},Ei=e=>typeof e=="string"?pi(e):e??{},Wc=e=>!!Ei(e).stream,Ns=e=>{if(typeof e=="number"&&Number.isSafeInteger(e)&&e>0)return e;if(typeof e!="string"||e.trim().length===0)return;const t=Number(e);return Number.isSafeInteger(t)&&t>0?t:void 0},Kr=e=>{const t=Ei(e),n=Ns(t.user_message_id)??Ns(t.respond_mesg_id);return{isStreaming:!!t.stream,hasResponseMetadata:Object.prototype.hasOwnProperty.call(t,"stream")||n!==void 0,...n!==void 0&&{userMessageId:n}}},kt="sb-agent",_i="KEY_IMG_ASPECT_RATIO",vr="*/*",re={BODY_MAX_WIDTH:244,WIDE_BODY_MAX_WIDTH:640,AVATAR_SIZE:26,BODY_TIME_GAP:4,HORIZONTAL_PADDING:12,GAP_GROUPED:2,GAP_UNGROUPED:16};var Mn=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(Mn||{}),Xt=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(Xt||{});const Yc=e=>!!(e!=null&&e.cta_button),jc=e=>{var t;return!!((t=e==null?void 0:e.citations)!=null&&t.length)},Ci=e=>!!(e!=null&&e.form)&&!e.form.canceled_at,Xc=e=>{var t;return Ci(e)&&!((t=e==null?void 0:e.form)!=null&&t.submitted_at)},Zc=e=>{var t;return!!((t=e==null?void 0:e.suggested_replies)!=null&&t.length)},Je=e=>{let t;return{enumerable:!0,get:()=>(t??(t=e()),t)}},tn=e=>Object.defineProperties({},{hasMessageTemplate:Je(()=>!!(e!=null&&e.message_template)),hasCTAButton:Je(()=>Yc(e)),hasChallenge:Je(()=>!!(e!=null&&e.challenge)),isThinking:Je(()=>!!(e!=null&&e.is_thinking)),hasCSAT:Je(()=>!!(e!=null&&e.csat)),hasSuggestedReplies:Je(()=>Zc(e)),hasCustomMessageTemplates:Je(()=>{var t;return!!((t=e==null?void 0:e.custom_message_templates)!=null&&t.length)}),hasForm:Je(()=>Ci(e)),hasActiveForm:Je(()=>Xc(e)),hasSteward:Je(()=>!!(e!=null&&e.steward)),hasCitations:Je(()=>jc(e))}),Jc=e=>{const t=tn(e);return t.hasMessageTemplate||t.hasCTAButton||t.hasCSAT||t.hasSuggestedReplies||t.hasForm||t.hasSteward||t.hasCitations},Si=e=>{var t;return!!((t=e==null?void 0:e.extendedMessagePayload)!=null&&t.steward)},Qc=e=>e===Xt.COMPLETED||e===Xt.CANCELED?e:Xt.IN_PROGRESS,nr=e=>Xe(e)&&!Si(e),Xe=e=>!!e&&"sender"in e,el=(e,{aiAgentInfo:t,members:n})=>t&&Fe(e,t.userId)?t:(n==null?void 0:n.find(r=>r.userId===e.sender.userId))??e.sender,tl=e=>Xe(e)&&e.reqId?e.reqId:String(e.messageId),nl=(e,t,n,r=!0)=>{if(!r||!nr(e))return"single";const s=()=>{if(!nr(t))return!1;const u=t.sender.userId===e.sender.userId,d=gt.isSameMinute(t.createdAt,e.createdAt);return u&&d},o=()=>{if(!nr(n))return!1;const u=n.sender.userId===e.sender.userId,d=gt.isSameMinute(n.createdAt,e.createdAt);return u&&d},i=s(),c=o();return i&&c?"middle":i?"bottom":c?"top":"single"},Fe=(e,t)=>(()=>{var r;return Xe(e)?e.sender.userId:((r=e==null?void 0:e.sender)==null?void 0:r.userId)??void 0})()===t,Le={isAdmin:e=>e.isAdminMessage(),isCSAT:e=>{var t;return e.isAdminMessage()&&!!((t=e.extendedMessagePayload)!=null&&t.csat)},isSteward:e=>Si(e),isIncoming:(e,t)=>Xe(e)&&e.sender.userId!==t,isOutgoing:(e,t)=>Xe(e)&&(e.sender.userId===t||e.sendingStatus===we.SendingStatus.PENDING)},Ve=e=>e.startsWith("image/"),nn=e=>e.startsWith("video/"),rl=e=>e.startsWith("audio/"),bi=({name:e="",mimeType:t=""})=>t==="application/pdf"||/\.pdf$/i.test(e.trim()),qr=(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"},vi=(e,t)=>t.map(r=>r.trim()).filter(Boolean).sort((r,s)=>s.length-r.length).reduce((r,s)=>r.replace(s,""),e.trim()).replace(/[\s,]/g,"").length===0,yi=e=>{if(e.message.length===0)return!1;if(e.messageType==="file"||e.messageType==="multipleFiles"){const t=e.messageType==="file"?[e.file.name]:e.files.map(n=>n.name);return!vi(e.message,t)}return!0},sl=e=>{if(e.message&&e.message.trim().length>0)return!0;const t=e.extendedMessagePayload;return Jc(t)},Bn=e=>{switch(e){case"top":case"middle":return re.GAP_GROUPED;default:return re.GAP_UNGROUPED}},ol=e=>{const t=/```(\w+)?\n([\s\S]*?)```/g,n=[];let r=0;return e.replace(t,(s,...o)=>{const[i,c,u]=o;return r<u&&n.push({type:"text",value:e.slice(r,u).trim()}),n.push({type:"code",value:c.trim(),language:i?i.trim():"plaintext"}),r=u+s.length,s}),r<e.length&&n.push({type:"text",value:e.slice(r).trim()}),n},Wr=e=>{const t=[],n=(c,u)=>{u&&t.push({kind:c,value:u})},r=c=>{var f;const u=[],d=/`+/g;let m;for(;(m=d.exec(c))!==null;)u.push({start:m.index,end:m.index+m[0].length,length:m[0].length});let h=0;for(let g=0;g<u.length;g++){const p=u[g];if(!p)continue;let C=0;for(;c[p.start-1-C]==="\\";)C+=1;if(C%2===1)continue;let E=g+1;for(;E<u.length&&((f=u[E])==null?void 0:f.length)!==p.length;)E+=1;const _=u[E];_&&(n("text",c.slice(h,p.start)),n("span",c.slice(p.start,_.end)),h=_.end,g=E)}n("text",c.slice(h))},s=/(?:^|\n)[ \t]{0,3}((`|~)\2{2,})[\s\S]*?(?:\n[ \t]{0,3}\1\2*[ \t]*(?=\n|$)|$)/g;let o=0,i;for(;(i=s.exec(e))!==null;){const c=i[0].startsWith(`
|
|
2
|
+
`)?i.index+1:i.index;r(e.slice(o,c)),n("fence",e.slice(c,i.index+i[0].length)),o=i.index+i[0].length}return r(e.slice(o)),t},Ds=(e,{anchorsLineEnd:t=!1}={})=>(n,{atLineStart:r,atLineEnd:s}={atLineStart:!0,atLineEnd:!0})=>{const o=n.indexOf(`
|
|
3
3
|
`),i=r?0:o===-1?n.length:o+1,c=!t||s?n.length:n.lastIndexOf(`
|
|
4
|
-
`)+1;return i>=c?n:n.slice(0,i)+e(n.slice(i,c))+n.slice(c)},
|
|
4
|
+
`)+1;return i>=c?n:n.slice(0,i)+e(n.slice(i,c))+n.slice(c)},il=e=>t=>{const n=Wr(t);return n.map((r,s)=>r.kind==="text"?e(r.value,{atLineStart:s===0,atLineEnd:s===n.length-1}):r.kind==="span"?r.value.replace(/\n/g," "):r.value).join("")},al=e=>e.replace(/\[([^\]]+)\](?!\(\s*[^\s)])/g,"\\[$1\\]"),cl=e=>e.replace(/^([ \t]*(?:[-*+]|\d+[.)])[ \t]+)\[( |x|X)\]/gm,"$1\\[$2\\]"),ll=/[\p{P}$+<=>^`|~]/u,hn=e=>e===void 0||/\s/.test(e),Mt=e=>e!==void 0&&ll.test(e),ul=e=>{const t=[];let n=0;for(const E of Wr(e))E.kind!=="text"&&t.push([n,n+E.value.length]),n+=E.value.length;const r=[],s=/^[ \t]{0,3}(?:_[ \t]*){3,}$/gm;let o;for(;(o=s.exec(e))!==null;)r.push([o.index,o.index+o[0].length]);const i=(E,_,A)=>{for(;_.index<E.length&&E[_.index][1]<=A;)_.index+=1;return _.index<E.length&&A>=E[_.index][0]},c={index:0},u={index:0},d=[],m=/_+/g;let h;for(;(h=m.exec(e))!==null;){const E=h.index,_=E+h[0].length;if(i(t,c,E)||i(r,u,E))continue;let A=0;for(;e[E-1-A]==="\\";)A+=1;if(A%2===1)continue;const y=e[E-1],T=e[_],M=!hn(T)&&(!Mt(T)||hn(y)||Mt(y)),O=!hn(y)&&(!Mt(y)||hn(T)||Mt(T));d.push({start:E,end:_,canOpen:M&&(!O||Mt(y)),canClose:O&&(!M||Mt(T)),paired:!1})}const f=[];let g=0;for(const E of d){/\n[ \t]*\n/.test(e.slice(g,E.start))&&(f.length=0),g=E.end;const _=E.canClose?f.pop():void 0;_?(_.paired=!0,E.paired=!0):E.canOpen&&f.push(E)}let p="",C=0;for(const E of d)E.paired||(p+=e.slice(C,E.start)+"\\_".repeat(E.end-E.start),C=E.end);return p+e.slice(C)},dl=e=>e.replace(/(^|\n)([ \t]{0,3}(?:\*[ \t]*){3,})(?=\n|$)/g,`$1
|
|
5
5
|
$2
|
|
6
6
|
`).replace(/(^|\n)([ \t]{0,3}(?:_[ \t]*){3,})(?=\n|$)/g,`$1
|
|
7
7
|
$2
|
|
8
|
-
`),
|
|
8
|
+
`),ml=e=>e.replace(/~~/g,"\\~\\~"),hl=e=>{const t=e.replace(/\r\n?/g,`
|
|
9
9
|
`),n=s=>s.replace(/(\S[ \t]*)\n(?![ \t]*\n)/g,`$1
|
|
10
|
-
`),r=
|
|
11
|
-
`)}).join("")},Er=(...e)=>(t,n)=>e.reduce((r,s)=>s(r,n),t),xs=Er(jc(Er(Is(el,{anchorsLineEnd:!0}),Xc,Is(Zc),tl)),Qc),rl=({convertSoftBreaks:e=!1}={})=>e?Er(nl,xs):xs,sl=typeof navigator<"u"&&navigator.product==="ReactNative",Cr=(e,t)=>{const n=r=>!t||t.length===0?!0:Qe(r)&&t.includes(r.sendingStatus);return sl?e.find(n):e.findLast(n)},ol=(e,t)=>{const n=Cr(e,[Le.SendingStatus.SUCCEEDED]);return n&&Me.isIncoming(n,t)?n:void 0},Ie=e=>{requestAnimationFrame(()=>{requestAnimationFrame(e)})};function me(){}function il(){const e=typeof navigator<"u"?navigator.userAgent:"",t=/iPad|iPhone|iPod/.test(e),n=/Android/.test(e);return t||n}function al(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 we={isStreaming(e){return $c(e.data)},isExplicitWelcomeMessage(e){var t;return((t=e.extendedMessagePayload)==null?void 0:t.bot_message_type)==="welcome"},isWelcomeMessage(e,t){var r;if(we.isExplicitWelcomeMessage(e))return!0;if(((r=e.extendedMessagePayload)==null?void 0:r.bot_message_type)!==void 0||!et(e,t))return!1;const n=ii(e.data);return!n.isStreaming&&!n.hasResponseMetadata},isGeneratedMessage(e){var t;return((t=e.extendedMessagePayload)==null?void 0:t.bot_message_type)==="generated"},hasFeedback(e){var t;return!!((t=e.extendedMessagePayload)!=null&&t.feedback)}},Jn=`@${yt}`,cl=({appId:e,aiAgentId:t,storage:n})=>{const r={templateBase:`${Jn}-template`,template:s=>`${r.templateBase}/templates/${s}`,templateToken:()=>`${r.templateBase}/tokens`,messengerSession:s=>{const o=al(`${e}/${t}/${s}`);return`${Jn}-udata/${o}`},anonUserSession:()=>`${Jn}-session/${e}/${t}`};return{template:{set:(s,o)=>n.set(r.template(s),o),get:s=>n.get(r.template(s)),setCachedToken:s=>n.set(r.templateToken(),s),getCachedToken:()=>n.get(r.templateToken()),clear:()=>{n.getKeys(r.templateBase).forEach(n.delete)}},messenger:{getSettings:s=>{try{const o=n.get(r.messengerSession(s));return o?JSON.parse(o):null}catch{return null}},setSettings:(s,o)=>{try{delete o.auto_created_user;const i=JSON.stringify(o);n.set(r.messengerSession(s),i)}catch{return}},getAnonUser:()=>{try{const s=n.get(r.anonUserSession());return s?JSON.parse(s):null}catch{return null}},setAnonUser:s=>{try{const o=JSON.stringify(s);n.set(r.anonUserSession(),o)}catch{return}},clear:s=>{try{s&&n.delete(r.messengerSession(s)),n.delete(r.anonUserSession())}catch{return}}}}},hi=(e,t,n={})=>{let r=null,s=null,o=null;const{leading:i=!0,trailing:c=!0}=n,u=(...d)=>{const m=Date.now();if(o===null||m-o>=t)i?(e(...d),o=m):(s=d,o=m);else if(s=d,c&&!r){const h=t-(m-o);r=setTimeout(()=>{s&&c&&(e(...s),o=Date.now()),r=null,s=null},h)}};return u.cancel=()=>{r&&(clearTimeout(r),r=null),s=null,o=null},u},ll=()=>{let e=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const n=(e+Math.random()*16)%16|0;return e=Math.floor(e/16),(t==="x"?n:n&3|8).toString(16)})};class ul{constructor(t){S(this,"_params");this._params={aiAgentChannelFilter:(t==null?void 0:t.aiAgentChannelFilter)??he.AIAgentChannelFilter.INCLUDE,aiAgentConversationStatusFilter:(t==null?void 0:t.aiAgentConversationStatusFilter)??[he.ConversationStatus.OPEN,he.ConversationStatus.CLOSED],aiAgentIds:(t==null?void 0:t.aiAgentIds)??[],deskChannelFilter:(t==null?void 0:t.deskChannelFilter)??he.DeskChannelFilter.INCLUDE,pinnedChannelUrls:(t==null?void 0:t.pinnedChannelUrls)??[],copilotConversationOnly:(t==null?void 0:t.copilotConversationOnly)??!1,copilotSupportChannelUrl:t==null?void 0:t.copilotSupportChannelUrl}}get params(){return{...this._params}}match(t,n){const{pinnedChannelUrls:r,aiAgentChannelFilter:s,aiAgentConversationStatusFilter:o,aiAgentIds:i,deskChannelFilter:c}=this._params;return r!=null&&r.includes(t.url)?!0:t.isAIAgent?!(!t.conversation||s===he.AIAgentChannelFilter.EXCLUDE||i&&i.length>0&&!i.includes(t.conversation.aiAgentId)||o&&o.length>0&&!o.some(d=>{var m;return((m=t.conversation)==null?void 0:m.status)===d})):t.isDesk?c!==he.DeskChannelFilter.EXCLUDE:!1}}class fi extends Ze.BaseChannelCollection{constructor(n,r){const s=new ul(r.filter),o=n,i=o.aiAgent._manager,c=r.limit??20,u=Ze.GroupChannelListOrder.LATEST_LAST_MESSAGE,d={getRemoteChannels:(m,h,f,g)=>i.getMyGroupChannels(m,h.params,g),changeLogSync:m=>{const{aiAgentChannelFilter:h,aiAgentIds:f,deskChannelFilter:g,pinnedChannelUrls:p,copilotConversationOnly:v,copilotSupportChannelUrl:E}=s.params,_={aiAgentChannelFilter:h,aiAgentIds:f,deskChannelFilter:g,pinnedChannelUrls:p,copilotConversationOnly:v,copilotSupportChannelUrl:E};return i.getMyGroupChannelChangeLogs(m,_,Ze.GroupChannelEventSource.SYNC_CHANNEL_CHANGELOGS)}};super(o.aiAgent._iid,{filter:s,order:u,limit:c,syncKeyPrefix:"aiAgent",fetcher:d});S(this,"_params");S(this,"_sdk");S(this,"_throttledOnChannelChanged");S(this,"_key");S(this,"_pendingChannels",[]);this._sdk=n,this._params=r,this._key=`clc-${ll()}`,this._throttledOnChannelChanged=hi(()=>{var g;const m=[...this._pendingChannels];this._pendingChannels=[];const h=new Map;for(const{channel:p,context:v}of m)h.delete(p.url),h.set(p.url,{channel:p,context:v});const f=new Map;for(const{channel:p,context:v}of h.values())f.has(v)||f.set(v,new Map),f.get(v).set(p.url,p);for(const[p,v]of f){const E=Array.from(v.values()),_=(g=this._sdk.currentUser)==null?void 0:g.userId,A=E.filter(T=>this.filter.match(T,_)),y=E.filter(T=>!this.filter.match(T,_)).map(T=>T.url);A.length>0&&this._base._addChannelsToView(A,p,!1),y.length>0&&this._removeChannels(y,p)}},250,{trailing:!0,leading:!0}),this._base._subscribeChannelEvent(this._key,{onUpdate:(m,h)=>{for(const f of m)this._pendingChannels.push({channel:f,context:h});this._throttledOnChannelChanged()},onRemove:(m,h)=>{this._removeChannels(m,h)}})}get _base(){return this}_removeChannels(n,r){const s=new Set(n);this._pendingChannels=this._pendingChannels.filter(({channel:o})=>!s.has(o.url)),this._base._removeChannelsFromView(n,r)}get channels(){var c;const n=((c=this._params.filter)==null?void 0:c.pinnedChannelUrls)??[],r=[],s=new Map(super.channels.map(u=>[u.url,u])),o=new Set;for(const u of n){const d=s.get(u);d&&!o.has(u)&&(r.push(d),o.add(u))}const i=super.channels.filter(u=>!o.has(u.url));return[...r,...i]}setConversationListCollectionHandler(n){super.setGroupChannelCollectionHandler(n)}dispose(){super.dispose(),this._throttledOnChannelChanged.cancel(),this._base._unsubscribeChannelEvent(this._key)}}class gi{constructor(t){S(this,"subscribers",{});this.logger=t}async send(t){const n=dl(),r=this.subscribers[t.type];if(r){this.logger.debug(`messenger.dispatcher: dispatching command: ${t.type}`,t.payload);const s=r.map(o=>o(t.payload));await Promise.all(s).catch(o=>{this.logger.error(`messenger.dispatcher: error in callback for command: ${t.type}`,o)})}return n.resolve(),n.promise}subscribe(t,n){this.subscribers[t]||(this.subscribers[t]=[]),this.subscribers[t].push(n)}unsubscribe(t,n){const r=this.subscribers[t];r&&(this.subscribers[t]=r.filter(s=>s!==n))}}const dl=()=>{let e=me,t=me;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}};var Fe=(e=>(e.ConversationClose="conv.close",e.MessengerSettingsUpdated="messenger.settings.updated",e.ActiveChannelUpdated="active.channel.updated",e.AnonymousSessionTokenExpired="anon.token.expired",e.AuthTokenRefreshed="auth.token.refreshed",e.NudgeMessageReceived="nudge.message.received",e))(Fe||{});class kt{constructor(t={}){S(this,"payload");this.payload=t}toJSON(){return JSON.stringify({type:this.type,payload:this.payload})}}const it={CloseConversation:e=>new ml(e),MessengerSettingsUpdated:e=>new hl(e),ActiveChannelUpdated:e=>new fl(e),AnonymousSessionTokenExpired:()=>new gl,AuthTokenRefreshed:()=>new pl,NudgeMessageReceived:e=>new _l(e)};class ml extends kt{constructor(){super(...arguments);S(this,"type","conv.close")}}class hl extends kt{constructor(){super(...arguments);S(this,"type","messenger.settings.updated")}}class fl extends kt{constructor(){super(...arguments);S(this,"type","active.channel.updated")}}class gl extends kt{constructor(){super(...arguments);S(this,"type","anon.token.expired")}}class pl extends kt{constructor(){super(...arguments);S(this,"type","auth.token.refreshed")}}class _l extends kt{constructor(){super(...arguments);S(this,"type","nudge.message.received")}}const Lt=e=>{const t={};for(const n of Object.keys(e)){const r=e[n];r!==void 0&&(t[n]=String(r))}return t};class Jt{constructor(t){S(this,"category","connection");this.userId=t}get data(){return Lt({user_id:this.userId})}}class El extends Jt{constructor(){super(...arguments);S(this,"metricKey","connection_connected")}}class Cl extends Jt{constructor(){super(...arguments);S(this,"metricKey","connection_reconnect_started")}}class bl extends Jt{constructor(){super(...arguments);S(this,"metricKey","connection_reconnect_succeeded")}}class vl extends Jt{constructor(){super(...arguments);S(this,"metricKey","connection_reconnect_failed")}}class Sl extends Jt{constructor(){super(...arguments);S(this,"metricKey","connection_disconnected")}}class yl{constructor(t){S(this,"lastKey",null);this.dispatch=t}handleEvent({detail:t,userId:n}){const r=`${t}:${n}`;if(this.shouldEmit(r)){this.lastKey=r;const s=t==="connected"?new El(n):t==="reconnectStarted"?new Cl(n):t==="reconnectSucceeded"?new bl(n):t==="reconnectFailed"?new vl(n):new Sl(n);this.dispatch(s)}}shouldEmit(t){return t!==this.lastKey}}class Hr{constructor(t,n){S(this,"category","conversation");this.channelUrl=t,this.conversationId=n}get data(){return Lt({channel_url:this.channelUrl,conversation_id:this.conversationId})}}class Al extends Hr{constructor(){super(...arguments);S(this,"metricKey","conversation_initialized")}}class Tl extends Hr{constructor(){super(...arguments);S(this,"metricKey","conversation_open")}}class Il extends Hr{constructor(){super(...arguments);S(this,"metricKey","conversation_closed")}}class xl{constructor(t){S(this,"statusByChannel",new Map);this.dispatch=t}handleEvent({channel:t}){const{conversation:n}=t;if(!n)return;const r=this.statusByChannel.get(t.url),s=n.status;if(this.statusByChannel.set(t.url,s),this.shouldEmit(r,s)){const o=s===he.ConversationStatus.INITIALIZED?new Al(t.url,n.id):s===he.ConversationStatus.OPEN?new Tl(t.url,n.id):new Il(t.url,n.id);this.dispatch(o)}}shouldEmit(t,n){return n===he.ConversationStatus.INITIALIZED?t===void 0:n===he.ConversationStatus.OPEN?t===he.ConversationStatus.INITIALIZED:t===he.ConversationStatus.OPEN}}const pi=(e,t)=>{if(e)return e.members.filter(n=>n.userId!==t).sort((n,r)=>r.joinedAt-n.joinedAt)[0]},Ne=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===he.ConversationStatus.CLOSED||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="closed")},Gr=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===he.ConversationStatus.OPEN||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="open")};function at(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 Rl(e){var r;const t=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff;return t?typeof t.requestedAt=="number"&&!at(e):!1}function Ml(e){var t;if(((t=e==null?void 0:e.resolution)==null?void 0:t.determinedBy)==="user")return e.resolution.isResolved}function _i(e){return!!e&&e<=Date.now()}function wl(e){return!e.title}function kl(e,t){var n;if(e)return wl(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 zr{constructor(t,n){S(this,"category","handoff");this.channelUrl=t,this.conversationId=n}get data(){return Lt({channel_url:this.channelUrl,conversation_id:this.conversationId})}}class Ll extends zr{constructor(){super(...arguments);S(this,"metricKey","handoff_started")}}class Ol extends zr{constructor(){super(...arguments);S(this,"metricKey","handoff_succeeded")}}class Nl extends zr{constructor(){super(...arguments);S(this,"metricKey","handoff_failed")}}class Dl{constructor(t){S(this,"statusByChannel",new Map);this.dispatch=t}handleEvent({channel:t}){const n=!this.statusByChannel.has(t.url);n&&this.statusByChannel.set(t.url,void 0);const r=t.conversation;if(!r||!r.handoff||n)return;const s=this.statusByChannel.get(t.url),o=this.resolveStatus(t,r);if(o!==void 0&&this.shouldEmit(s,o)){this.statusByChannel.set(t.url,o);const i=o==="started"?new Ll(t.url,r.id):o==="succeeded"?new Ol(t.url,r.id):new Nl(t.url,r.id);this.dispatch(i)}}resolveStatus(t,n){if(Ne(t))return"failed";const{members:r}=t;if(r.length===1)return"started";if(r.length===2&&n.aiAgentId&&!r.some(s=>s.userId===n.aiAgentId))return"succeeded"}shouldEmit(t,n){return n==="started"?t===void 0:t==="started"}}class $l{constructor(t){S(this,"category","message");S(this,"metricKey","incoming_message_received");S(this,"channelUrl");S(this,"messageId");S(this,"senderType");S(this,"createdAt");S(this,"conversationId");this.channelUrl=t.channelUrl,this.messageId=t.messageId,this.senderType=t.senderType,this.createdAt=t.createdAt,this.conversationId=t.conversationId}get data(){return Lt({channel_url:this.channelUrl,message_id:this.messageId,sender_type:this.senderType,created_at:this.createdAt,conversation_id:this.conversationId})}}const Pl=(e,t)=>{const n=Qe(e)?e.sender.userId:void 0;return n===void 0?"system":n===t?"ai_agent":"human_agent"};class Fl{constructor(t,n){this.dispatch=t,this.getCurrentUserId=n}handleEvent({channel:t,message:n}){const{conversation:r}=t;this.shouldEmit(n,r)&&this.dispatch(new $l({channelUrl:t.url,messageId:n.messageId,senderType:Pl(n,r.aiAgentId),createdAt:n.createdAt,conversationId:r.id}))}shouldEmit(t,n){return!et(t,this.getCurrentUserId())&&n!==null}}class Vr{constructor(t){S(this,"category","memory");S(this,"action");S(this,"deleteOnOff");S(this,"userId");this.action=t.action,this.deleteOnOff=t.deleteOnOff,this.userId=t.userId}get data(){return Lt({action:this.action,delete_on_off:this.deleteOnOff,user_id:this.userId})}}class Ul extends Vr{constructor(){super(...arguments);S(this,"metricKey","memory_consent")}}class Bl extends Vr{constructor(){super(...arguments);S(this,"metricKey","memory_on")}}class Hl extends Vr{constructor(){super(...arguments);S(this,"metricKey","memory_off")}}const Gl={consent:{Metric:Ul,actions:{shown:"shown",confirm:"enable",cancel:"disable"}},on:{Metric:Bl,actions:{shown:"shown",confirm:"keep",cancel:"disable",dismiss:"dismiss"}},off:{Metric:Hl,actions:{shown:"shown",confirm:"keep",cancel:"enable",dismiss:"dismiss"}}};class zl{constructor(t,n){this.dispatch=t,this.getCurrentUserId=n}handleEvent({variant:t,action:n,deleteOnOff:r}){if(t==="readonly")return;const{Metric:s,actions:o}=Gl[t],i=o[n];i&&this.dispatch(new s({action:i,deleteOnOff:t==="on"?r:void 0,userId:this.getCurrentUserId()}))}}class Vl{constructor(t){S(this,"category","message");S(this,"metricKey");S(this,"channelUrl");S(this,"requestId");S(this,"messageId");S(this,"target");S(this,"sendingStatus");S(this,"createdAt");S(this,"conversationId");this.channelUrl=t.channelUrl,this.requestId=t.requestId,this.messageId=t.messageId,this.target=t.target,this.sendingStatus=t.sendingStatus,this.createdAt=t.createdAt,this.conversationId=t.conversationId,this.metricKey=`outgoing_message_${t.sendingStatus}`}get data(){return Lt({channel_url:this.channelUrl,request_id:this.requestId,message_id:this.messageId,target:this.target,created_at:this.createdAt,conversation_id:this.conversationId})}}const Kl=e=>{switch(e){case Le.SendingStatus.PENDING:return"pending";case Le.SendingStatus.SUCCEEDED:return"succeeded";case Le.SendingStatus.FAILED:return"failed";case Le.SendingStatus.SCHEDULED:return"scheduled";default:return}};class ql{constructor(t,n){S(this,"statusByReqId",new Map);this.dispatch=t,this.getCurrentUserId=n}handleEvent({channel:t,message:n}){var o;if(!et(n,this.getCurrentUserId()))return;const r=Kl(n.sendingStatus);if(r===void 0)return;const s=this.statusByReqId.get(n.reqId);this.statusByReqId.set(n.reqId,r),r!=="scheduled"&&this.shouldEmit(s,r)&&this.dispatch(new Vl({channelUrl:t.url,requestId:n.reqId,messageId:r==="succeeded"?n.messageId:void 0,target:at(t)?"human_agent":"ai_agent",sendingStatus:r,createdAt:n.createdAt,conversationId:(o=t.conversation)==null?void 0:o.id}))}shouldEmit(t,n){return n==="pending"?t!=="pending"&&t!=="succeeded":n==="succeeded"?t==="pending"||t==="scheduled":t!=="failed"}}class Wl{constructor(t){S(this,"id","aiagent_livemetric");S(this,"dispatch");S(this,"emit",({category:t,metricKey:n,data:r})=>{var s;(s=this.dispatch)==null||s.call(this,{category:t,metricKey:n,data:r})});S(this,"emitters");this.chatSDK=t;const n=()=>{var r;return(r=this.chatSDK.currentUser)==null?void 0:r.userId};this.emitters={connection:new yl(this.emit),conversation:new xl(this.emit),handoff:new Dl(this.emit),incomingMessage:new Fl(this.emit,n),outgoingMessage:new ql(this.emit,n),memory:new zl(this.emit,n)}}start(){const t=new Ee.ConnectionHandler({onConnected:r=>this.trackConnection("connected",r),onDisconnected:r=>this.trackConnection("disconnected",r),onReconnectStarted:()=>this.trackConnection("reconnectStarted"),onReconnectSucceeded:()=>this.trackConnection("reconnectSucceeded"),onReconnectFailed:()=>this.trackConnection("reconnectFailed")}),n=new Ze.GroupChannelHandler({onMessageReceived:(r,s)=>{r.isGroupChannel()&&this.track({type:"incomingMessage",channel:r,message:s})},onChannelChanged:r=>{r.isGroupChannel()&&(this.track({type:"handoff",channel:r}),this.track({type:"conversation",channel:r}))},onUserJoined:r=>this.track({type:"handoff",channel:r}),onUserLeft:r=>this.track({type:"handoff",channel:r})});this.chatSDK.addConnectionHandler(this.id,t),this.chatSDK.groupChannel.addGroupChannelHandler(this.id,n)}track(t){try{this.emitters[t.type].handleEvent(t)}catch{}}dispose(){this.chatSDK.removeConnectionHandler(this.id),this.chatSDK.groupChannel.removeGroupChannelHandler(this.id)}trackConnection(t,n=(r=>(r=this.chatSDK.currentUser)==null?void 0:r.userId)()){n&&this.track({type:"connection",detail:t,userId:n})}}var Kr=(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))(Kr||{});class Ei{constructor(t){S(this,"level");this.level=t}verbose(...t){this.level<=0&&console.log(`[${yt}/verbose]`,...t)}debug(...t){this.level<=1&&console.log(`[${yt}/debug]`,...t)}info(...t){this.level<=2&&console.log(`[${yt}/info]`,...t)}warn(...t){this.level<=3&&console.warn(`[${yt}/warn]`,...t)}error(...t){this.level<=4&&console.error(`[${yt}/error]`,...t)}}class Ci{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 br{constructor(){S(this,"userId");S(this,"authToken");S(this,"sessionHandler")}}const Yl=e=>({onSessionTokenRequired:t=>{t(null),e.send(it.AnonymousSessionTokenExpired())}}),qr=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!=null)),jl="ai_agent:stats",Xl="conversation_initial_render",Zl="conversation_not_interactive_timeout",Jl="recovery_not_interactive_timeout",Ql="conversation_list_initial_render",eu="message_pending_stuck",tu="aiev_auth_expired_unhandled",nu="user_perceived_response_time",ru="stream_stalled",su="ai_typing_indicator_absent_timeout",ou="rendered_content_unusable",iu=800220;var j=(e=>(e.ACK_TO_FIRST_CHUNK="ack_to_first_chunk_ms",e.AFTER_TPEN_ABSENT="after_tpen_absent_ms",e.AUTH="auth_duration_ms",e.BEFORE_TPST_ABSENT="before_tpst_absent_ms",e.FIRST_CHUNK_TO_RENDER="first_chunk_to_render_ms",e.GET_CHANNEL="get_channel_duration_ms",e.GET_LIST="get_list_duration_ms",e.GET_MESSAGES="get_messages_duration_ms",e.PAGE_RENDER="page_render_duration_ms",e.PAGE_RENDER_FROM_CACHE="total_duration_from_cache_ms",e.SEND_TO_ACK="send_to_ack_ms",e.TIMEOUT="timeout_ms",e))(j||{});const vr=(e,t)=>e.startAt===null||e.endedAt===null||t.startAt===null||t.endedAt===null?0:Math.max(0,Math.min(e.endedAt,t.endedAt)-Math.max(e.startAt,t.startAt)),bi=e=>typeof e=="object"&&e!==null,au=e=>{if(bi(e))return typeof e.code=="number"?e.code:void 0},cu=e=>e instanceof Error?e.message:typeof e=="string"?e:bi(e)&&typeof e.message=="string"?e.message:"";class tt{constructor(){S(this,"timers",new Map);S(this,"committed",!1);S(this,"commitCallback",null);S(this,"conversationId",null);S(this,"errorCode",null);S(this,"errorDescription",null);S(this,"extraData",{})}setCommitCallback(t){return this.commitCallback=t,this}setConversationId(t){return t&&(this.conversationId=t),this}setError(t){return t==null?this:(this.errorCode=au(t)??iu,this.errorDescription=cu(t),this)}setExtra(t,n){return n!=null&&(this.extraData[t]=n),this}startTimer(t){if(this.committed)return this;const n=this.timers.get(t);return(n==null?void 0:n.startTime)!==null&&(n==null?void 0:n.startTime)!==void 0?this:(this.timers.set(t,{startTime:performance.now(),endTime:null}),this)}stopTimer(t){if(this.committed)return this;const n=this.timers.get(t);return!n||n.startTime===null||n.endTime!==null?this:(this.timers.set(t,{...n,endTime:performance.now()}),this)}getTimer(t){const n=this.timers.get(t);return!n||n.startTime===null?{startAt:null,endedAt:null,duration:null}:{startAt:n.startTime,endedAt:n.endTime,duration:n.endTime===null?null:n.endTime-n.startTime}}createPayload(t,n){const r={key:this.getMetricKey(),value:String(t)},s=(n==null?void 0:n.conversationId)??this.conversationId??void 0;s!==void 0&&(r.conversation_id=s),this.errorCode!==null&&(r.error_code=this.errorCode,r.error_description=this.errorDescription??"");const o=qr({...this.extraData,...n==null?void 0:n.extra});return Object.keys(o).length>0&&(r.extra=o),r}isCommitted(){return this.committed}discard(){this.committed=!0}commit(){if(this.committed||!this.commitCallback)return!1;const t=this.buildPayload();return t?(this.committed=!0,this.commitCallback(jl,t)):!1}}class Rs extends tt{constructor(){super(...arguments);S(this,"reason");S(this,"aiAgentId")}setReason(n){return this.reason=n,this}setAIAgentId(n){return this.aiAgentId=n,this}getMetricKey(){return tu}buildPayload(){return this.reason===void 0||this.aiAgentId===void 0?null:this.createPayload(this.reason,{extra:{agent_id:this.aiAgentId}})}}class Dn{constructor(t){S(this,"commitCallback");this.commitCallback=t}}class Ot extends Dn{constructor(){super(...arguments);S(this,"records",new Map)}}class vi extends Dn{constructor(){super(...arguments);S(this,"activeSpan",null);S(this,"visible",!0)}setVisible(n){var r;this.visible=n,(r=this.activeSpan)==null||r.onVisibilityChanged(n)}}class Si{constructor(t,n){S(this,"stats");S(this,"visible");S(this,"completedHidden",!1);this.stats=t,this.visible=n}get isRecording(){return this.stats!==null&&!this.stats.isCommitted()}onVisibilityChanged(t){this.stats&&(this.visible=t,t&&this.completedHidden&&(this.stats.commit(),this.stats=null))}commitOrDefer(){if(this.stats){if(!this.visible){this.completedHidden=!0;return}this.stats.commit(),this.stats=null}}cancel(){this.stats=null}}const pt=(e,t)=>!(e&&t&&e!==t),Sr=(e,t)=>{for(const n of e)if(n.measure.userMessageId===void 0&&pt(n.measure.channelUrl,t))return!0;return!1},$n=(e,t)=>{if(e.size<t)return;const n=e.keys().next();n.done||e.delete(n.value)};class lu extends Dn{onPayloadParseFailed(t){new Rs().setReason("payload_parse_failed").setAIAgentId(t.aiAgentId).setCommitCallback(this.commitCallback).commit()}onCallbackNotFound(t){new Rs().setReason("callback_not_found").setAIAgentId(t.aiAgentId).setCommitCallback(this.commitCallback).commit()}clear(){}}class uu extends tt{constructor(){super(...arguments);S(this,"channelUrl",null);S(this,"presentMethod","direct_present")}setChannelUrl(n){return this.channelUrl=n,this}setPresentMethod(n){return this.presentMethod=n,this}resetPageRenderSpan(){return this.timers.delete(j.PAGE_RENDER),this.timers.delete(j.PAGE_RENDER_FROM_CACHE),this.timers.delete(j.GET_CHANNEL),this.timers.delete(j.GET_MESSAGES),this.conversationId=null,this.channelUrl=null,this.errorCode=null,this.errorDescription=null,this}getMetricKey(){return Xl}buildPayload(){const n=this.getTimer(j.AUTH),r=this.getTimer(j.PAGE_RENDER),s=this.getTimer(j.PAGE_RENDER_FROM_CACHE);if(r.duration===null&&(this.errorCode===null||n.duration===null))return null;const o=r.duration===null?0:r.duration-vr(n,r),i=s.duration===null?null:s.duration-vr(n,s);return this.createPayload((n.duration??0)+o,{extra:{channel_url:this.channelUrl,present_method:this.presentMethod,[j.AUTH]:n.duration,[j.GET_CHANNEL]:this.getTimer(j.GET_CHANNEL).duration,[j.GET_MESSAGES]:this.getTimer(j.GET_MESSAGES).duration,[j.PAGE_RENDER_FROM_CACHE]:i}})}}class du extends Si{constructor(n,r,s){var o;super(n,s);S(this,"measure");this.measure={channelUrl:r,pageRenderState:"initialized"},(o=this.stats)==null||o.setChannelUrl(r).startTimer(j.PAGE_RENDER).startTimer(j.PAGE_RENDER_FROM_CACHE)}onGetChannelStart(n){!this.stats||n!==this.measure.channelUrl||this.measure.pageRenderState!=="initialized"||(this.stats.startTimer(j.GET_CHANNEL),this.measure.pageRenderState="channel_fetching")}onGetChannelComplete(n,r){!this.stats||n!==this.measure.channelUrl||this.measure.pageRenderState!=="channel_fetching"||(this.stats.stopTimer(j.GET_CHANNEL).setConversationId(r),this.measure.pageRenderState="channel_fetched")}onGetChannelError(n,r){!this.stats||n!==this.measure.channelUrl||this.measure.pageRenderState!=="channel_fetching"||(this.stats.stopTimer(j.GET_CHANNEL).setError(r).stopTimer(j.PAGE_RENDER),this.measure.pageRenderState="channel_failed",this.tryFinalize())}onGetMessagesStart(){!this.stats||this.measure.pageRenderState!=="channel_fetched"||(this.stats.startTimer(j.GET_MESSAGES),this.measure.pageRenderState="messages_fetching")}onGetMessagesCacheComplete(n,r){!this.stats||n!==this.measure.channelUrl||r||this.measure.pageRenderState!=="messages_fetching"||this.stats.stopTimer(j.PAGE_RENDER_FROM_CACHE)}onGetMessagesComplete(n,r){!this.stats||n!==this.measure.channelUrl||this.measure.pageRenderState!=="messages_fetching"||(this.stats.stopTimer(j.GET_MESSAGES).setError(r),this.measure.pageRenderState="messages_fetching_completed")}onRendered(){!this.stats||this.measure.pageRenderState!=="messages_fetching_completed"||(this.stats.stopTimer(j.PAGE_RENDER),this.tryFinalize())}onRenderDiscarded(){!this.stats||this.measure.pageRenderState!=="messages_fetching_completed"||(this.stats.discard(),this.stats=null)}onAuthSettled(){this.tryFinalize()}tryFinalize(){if(!this.stats||this.stats.getTimer(j.PAGE_RENDER).endedAt===null)return;const n=this.stats.getTimer(j.AUTH);if(!(n.startAt!==null&&n.endedAt===null)){if(this.measure.pageRenderState==="channel_failed"){this.stats.commit(),this.stats=null;return}this.commitOrDefer()}}}class mu extends vi{constructor(){super(...arguments);S(this,"stats",null);S(this,"authState","idle");S(this,"presentMethod","direct_present")}getOrCreateStats(){var n;return(n=this.stats)!=null&&n.isCommitted()?null:(this.stats||(this.stats=new uu().setCommitCallback(this.commitCallback).setPresentMethod(this.presentMethod)),this.stats)}getActiveStats(){return!this.stats||this.stats.isCommitted()?null:this.stats}setPresentMethod(n){var r;this.presentMethod=n,(r=this.getActiveStats())==null||r.setPresentMethod(n)}onAuthStart(){var n,r;if((n=this.stats)!=null&&n.isCommitted()){if(this.authState!=="failed"||this.activeSpan!==null)return;this.stats=null,this.authState="idle"}this.authState==="idle"&&(this.authState="in_progress",(r=this.getOrCreateStats())==null||r.startTimer(j.AUTH))}onAuthComplete(){var n,r;this.authState==="in_progress"&&(this.authState="completed",(n=this.getActiveStats())==null||n.stopTimer(j.AUTH)),(r=this.activeSpan)==null||r.onAuthSettled()}onAuthError(n){var r,s;this.authState==="in_progress"&&(this.authState="failed",(r=this.getActiveStats())==null||r.stopTimer(j.AUTH).setError(n).commit(),(s=this.activeSpan)==null||s.cancel())}startSpan(n){const r=this.activeSpan;r==null||r.cancel();const s=this.getOrCreateStats();return s&&r&&s.resetPageRenderSpan(),this.activeSpan=new du(s,n,this.visible),this.activeSpan}clear(){var n;(n=this.activeSpan)==null||n.cancel(),this.activeSpan=null,this.stats=null,this.authState="idle"}}class hu extends tt{constructor(){super(...arguments);S(this,"presentMethod","direct_present")}setPresentMethod(n){return this.presentMethod=n,this}resetPageRenderSpan(){return this.timers.delete(j.PAGE_RENDER),this.timers.delete(j.GET_LIST),this.errorCode=null,this.errorDescription=null,this}getMetricKey(){return Ql}buildPayload(){const n=this.getTimer(j.AUTH),r=this.getTimer(j.PAGE_RENDER),s=this.getTimer(j.GET_LIST).duration;if(r.duration===null&&(this.errorCode===null||n.duration===null))return null;const o=r.duration===null?0:r.duration-vr(n,r),i=(n.duration??0)+o;return this.createPayload(i,{extra:{present_method:this.presentMethod,[j.AUTH]:n.duration,[j.GET_LIST]:s}})}}class fu extends Si{constructor(n,r){var s;super(n,r);S(this,"measure",{listStarted:!1,listCompleted:!1});(s=this.stats)==null||s.startTimer(j.PAGE_RENDER)}onListRequestStart(){!this.stats||this.measure.listStarted||(this.stats.startTimer(j.PAGE_RENDER),this.stats.startTimer(j.GET_LIST),this.measure.listStarted=!0)}onListRequestComplete(n){if(!(!this.stats||!this.measure.listStarted||this.measure.listCompleted)){if(n){this.stats.resetPageRenderSpan(),this.measure.listStarted=!1;return}this.stats.stopTimer(j.GET_LIST),this.measure.listCompleted=!0}}onRendered(){!this.stats||!this.measure.listCompleted||(this.stats.stopTimer(j.PAGE_RENDER),this.tryFinalize())}onRenderDiscarded(){!this.stats||!this.measure.listCompleted||(this.stats.discard(),this.stats=null)}onAuthSettled(){this.tryFinalize()}tryFinalize(){if(!this.stats||this.stats.getTimer(j.PAGE_RENDER).endedAt===null)return;const n=this.stats.getTimer(j.AUTH);n.startAt!==null&&n.endedAt===null||this.commitOrDefer()}}class gu extends vi{constructor(){super(...arguments);S(this,"stats",null);S(this,"authState","idle");S(this,"presentMethod","direct_present")}getOrCreateStats(){var n;return(n=this.stats)!=null&&n.isCommitted()?null:(this.stats||(this.stats=new hu().setCommitCallback(this.commitCallback).setPresentMethod(this.presentMethod)),this.stats)}getActiveStats(){return!this.stats||this.stats.isCommitted()?null:this.stats}setPresentMethod(n){var r;this.presentMethod=n,(r=this.getActiveStats())==null||r.setPresentMethod(n)}onAuthStart(){var n;this.authState="in_progress",(n=this.getOrCreateStats())==null||n.startTimer(j.AUTH)}onAuthComplete(){var r,s;const n=this.authState==="in_progress";this.authState="completed",n&&((r=this.getActiveStats())==null||r.stopTimer(j.AUTH)),(s=this.activeSpan)==null||s.onAuthSettled()}onAuthError(n){var o;const r=this.authState==="in_progress";this.authState="failed";const s=this.getActiveStats();if(s){if(!((o=this.activeSpan)!=null&&o.isRecording)){this.stats=null;return}r&&s.stopTimer(j.AUTH),s.setError(n).commit(),this.activeSpan.cancel()}}startSpan(){const n=this.activeSpan;n==null||n.cancel();const r=this.getOrCreateStats();return r&&n&&r.resetPageRenderSpan(),r&&this.authState==="in_progress"&&r.startTimer(j.AUTH),this.activeSpan=new fu(r,this.visible),this.activeSpan}clear(){var n;(n=this.activeSpan)==null||n.cancel(),this.activeSpan=null,this.stats=null,this.authState="idle"}}class pu extends tt{constructor(){super(...arguments);S(this,"phaseReached","auth");S(this,"historyLoadResult","pending")}setHistoryLoadResult(n){return this.historyLoadResult=n,this}setPhaseReached(n){return this.phaseReached=n,this}getMetricKey(){return Zl}buildPayload(){const n=this.getTimer(j.TIMEOUT).duration;return n===null?null:this.createPayload(n,{extra:{outcome:"timeout",phase_reached:this.phaseReached,history_load_result:this.historyLoadResult}})}}class _u extends Ot{start(t){const n=this.getKey(t==null?void 0:t.channelUrl);this.clearKey(n);const r={stats:new pu().setCommitCallback(this.commitCallback).startTimer(j.TIMEOUT),measure:{channelUrl:t==null?void 0:t.channelUrl,historyLoadResult:"pending",inputEnabled:!1,timer:null}};(t==null?void 0:t.conversationId)!==void 0&&r.stats.setConversationId(t.conversationId),r.measure.timer=setTimeout(()=>this.commitTimeout(n),1e4),this.records.set(n,r)}markChannelJoined(t,n){const r=this.getRecord(n);r&&(r.stats.setPhaseReached("channel_join"),t!==void 0&&r.stats.setConversationId(t))}markHistoryLoaded(t,n){const r=this.getRecord(n);r&&(r.measure.historyLoadResult=t,r.stats.setHistoryLoadResult(t).setPhaseReached("history_load"),this.cancelIfReady(n))}markInputReady(t){const n=this.getRecord(t);n&&(n.measure.inputEnabled=!0,n.stats.setPhaseReached("input_enable"),this.cancelIfReady(t))}markRendered(t){const n=this.getRecord(t);n&&n.stats.setPhaseReached("render")}clear(){this.records.forEach(t=>{t.measure.timer!==null&&clearTimeout(t.measure.timer)}),this.records.clear()}clearChannel(t){t!==void 0&&this.clearKey(this.getKey(t))}clearKey(t){const n=this.records.get(t);n&&(n.measure.timer!==null&&clearTimeout(n.measure.timer),this.records.delete(t))}cancelIfReady(t){const n=this.getRecord(t);!n||!n.measure.inputEnabled||n.measure.historyLoadResult==="pending"||this.clearKey(this.getKey(n.measure.channelUrl))}commitTimeout(t){const n=this.records.get(t);n&&(n.measure.timer=null,this.records.delete(t),n.stats.stopTimer(j.TIMEOUT).commit())}getRecord(t){return t!==void 0?this.records.get(this.getKey(t)):this.records.size===1?this.records.values().next().value:this.records.get(this.getKey())}getKey(t){return t??"__default__"}}class Eu extends tt{constructor(){super(...arguments);S(this,"requestId");S(this,"messageType");S(this,"stuckReason")}setRequestId(n){return this.requestId=n,this}setMessageType(n){return this.messageType=n,this}setStuckReason(n){return this.stuckReason=n,this}getMetricKey(){return eu}buildPayload(){return this.requestId===void 0||this.messageType===void 0||this.stuckReason===void 0?null:this.createPayload(this.stuckReason,{extra:{message_type:this.messageType,request_id:this.requestId}})}}const Cu=5e3,Ms=1e4;class bu extends Ot{start(t){if(!t.requestId||this.records.has(t.requestId))return;const n=t.messageType!=="text"&&t.tracksUploadProgress===!0,s={stats:new Eu().setRequestId(t.requestId).setMessageType(t.messageType).setStuckReason(n?"upload_no_progress":"pending_too_long").setCommitCallback(this.commitCallback),measure:{channelUrl:t.channelUrl,timer:null,usesUploadProgress:n}},o=n?Ms:Cu;s.measure.timer=setTimeout(()=>this.detect(t.requestId),o),this.records.set(t.requestId,s)}resolve(t){this.cancel(t.requestId)}disappear(t){this.cancel(t.requestId)}cancel(t){const n=this.records.get(t);n&&(n.measure.timer!==null&&clearTimeout(n.measure.timer),this.records.delete(t))}markUploadProgress(t){const n=this.records.get(t);n&&n.measure.usesUploadProgress&&(n.measure.timer!==null&&clearTimeout(n.measure.timer),n.measure.timer=setTimeout(()=>this.detect(t),Ms))}clear(){this.records.forEach(t=>{t.measure.timer!==null&&clearTimeout(t.measure.timer)}),this.records.clear()}clearChannel(t){t&&this.records.forEach((n,r)=>{n.measure.channelUrl===t&&(n.measure.timer!==null&&clearTimeout(n.measure.timer),this.records.delete(r))})}detect(t){const n=this.records.get(t);n&&(this.records.delete(t),n.stats.commit())}}class Qn extends tt{constructor(){super(...arguments);S(this,"triggerType")}setTriggerType(n){return this.triggerType=n,this}getMetricKey(){return Jl}buildPayload(){const n=this.getTimer(j.TIMEOUT).duration;return n===null||this.triggerType===void 0?null:this.createPayload(n,{extra:{trigger_type:this.triggerType}})}}class vu extends Ot{start(t,n){const r=this.getKey(n);let s=this.records.get(r);s!=null&&s.measure.started||s!=null&&s.measure.inputEnabled||(s||(s=this.createRecord(!1)),s.measure.started=!0,s.stats=new Qn().setTriggerType(t).setCommitCallback(this.commitCallback).startTimer(j.TIMEOUT),s.measure.timer=setTimeout(()=>this.commitTimeout(r),1e4),this.records.set(r,s))}setInputEnabled(t,n){const r=this.getKey(n);let s=this.records.get(r);if(!s){if(!t)return;s=this.createRecord(t),this.records.set(r,s);return}s.measure.inputEnabled=t,t?this.cancelRecord(s):s.measure.started||this.records.delete(r)}cancelPending(t){const n=this.getKey(t),r=this.records.get(n);r&&(this.cancelRecord(r),r.measure.inputEnabled||this.records.delete(n))}clear(){this.records.forEach(t=>{t.measure.timer!==null&&clearTimeout(t.measure.timer)}),this.records.clear()}clearChannel(t){t!==void 0&&this.clearKey(this.getKey(t))}clearKey(t){const n=this.records.get(t);n&&(n.measure.timer!==null&&clearTimeout(n.measure.timer),this.records.delete(t))}commitTimeout(t){const n=this.records.get(t);if(!(!n||!n.measure.started)){if(n.measure.inputEnabled){this.cancelRecord(n);return}n.stats.stopTimer(j.TIMEOUT),this.records.delete(t),n.stats.commit()}}cancelRecord(t){t.measure.timer!==null&&clearTimeout(t.measure.timer),t.measure.timer=null,t.measure.started=!1,t.stats=new Qn().setCommitCallback(this.commitCallback)}createRecord(t){return{stats:new Qn().setCommitCallback(this.commitCallback),measure:{inputEnabled:t,started:!1,timer:null}}}getKey(t){return t??"__default__"}}class Su extends tt{constructor(){super(...arguments);S(this,"messageId");S(this,"contentKind");S(this,"errorDomain")}setMessageId(n){return this.messageId=n,this}setContentKind(n){return this.contentKind=n,this}setErrorDomain(n){return this.errorDomain=n,this}getMetricKey(){return ou}buildPayload(){return this.messageId===void 0||this.contentKind===void 0||this.errorDomain===void 0?null:this.createPayload(this.errorDomain,{extra:{content_kind:this.contentKind,message_id:String(this.messageId)}})}}const yu=500;class Au extends Dn{constructor(){super(...arguments);S(this,"measure",{committed:new Set})}commit(n){const r=`${n.messageId}:${n.contentKind}:${n.errorDomain}`;if(this.measure.committed.has(r))return;$n(this.measure.committed,yu),this.measure.committed.add(r),new Su().setMessageId(n.messageId).setContentKind(n.contentKind).setErrorDomain(n.errorDomain).setError(n.error?{code:n.error.code,message:n.errorDomain}:void 0).setCommitCallback(this.commitCallback).commit()}clear(){this.measure.committed.clear()}}class Tu extends tt{constructor(){super(...arguments);S(this,"durationMs");S(this,"messageId");S(this,"stallKind")}setMessageId(n){return this.messageId=n,this}setStall(n){return this.durationMs=n.durationMs,this.stallKind=n.stallKind,this}getMetricKey(){return ru}buildPayload(){return this.durationMs===void 0||this.messageId===void 0||this.stallKind===void 0?null:this.createPayload(this.durationMs,{extra:{message_id:String(this.messageId),stall_kind:this.stallKind}})}}const ws=1e4,St=5e3,Iu=500;class xu extends Ot{constructor(){super(...arguments);S(this,"emittedMessageChannels",new Map)}markRawProgress(n){if(!n.aiResponse.isStreaming){this.completeDelivery(n.messageId,n.textLength);return}if(this.emittedMessageChannels.has(n.messageId))return;const r=this.getOrCreate(n.messageId,n.channelUrl),s=r.measure;this.markRawProgressForRecord(r,n.textLength,performance.now())?(s.deliveryTimer!==null&&clearTimeout(s.deliveryTimer),s.deliveryTimer=null,this.scheduleDeliveryStallCheck(n.messageId,r)):this.scheduleDeliveryStallCheck(n.messageId,r),this.isRenderPending(r)&&s.renderTimer===null&&(s.lastRenderAt=performance.now(),this.scheduleRenderStallCheck(n.messageId,r,St))}markRenderedProgress(n){const r=this.records.get(n.messageId);if(!r)return;const s=r.measure;if(this.markRenderedProgressForRecord(r,n.displayedLength,performance.now())){if(!this.isRenderPending(r)){if(s.deliveryTimer===null){this.clearRecord(n.messageId,r);return}s.renderTimer!==null&&clearTimeout(s.renderTimer),s.renderTimer=null;return}this.scheduleRenderStallCheck(n.messageId,r,St)}}hasPendingStream(n){return this.records.has(n)}complete(n){const r=this.records.get(n);r&&this.clearRecord(n,r)}completeDelivery(n,r){const s=this.records.get(n);if(!s)return;const o=s.measure;if(r>o.lastRawLength&&(o.lastRawLength=r,o.lastRawAt=performance.now()),o.deliveryTimer!==null&&clearTimeout(o.deliveryTimer),o.deliveryTimer=null,!this.isRenderPending(s)){this.clearRecord(n,s);return}o.renderTimer===null&&(o.lastRenderAt=performance.now(),this.scheduleRenderStallCheck(n,s,St))}clearMessage(n){const r=this.records.get(n);r&&this.clearRecord(n,r),this.emittedMessageChannels.delete(n)}clear(){this.records.forEach(n=>{n.measure.deliveryTimer!==null&&clearTimeout(n.measure.deliveryTimer),n.measure.renderTimer!==null&&clearTimeout(n.measure.renderTimer)}),this.records.clear(),this.emittedMessageChannels.clear()}clearChannel(n){n&&(this.records.forEach((r,s)=>{r.measure.channelUrl!==n&&r.measure.channelUrl!==void 0||this.clearRecord(s,r)}),this.emittedMessageChannels.forEach((r,s)=>{(r===n||r===void 0)&&this.emittedMessageChannels.delete(s)}))}detectDelivery(n){const r=this.records.get(n);if(!r)return;const s=r.measure;s.deliveryTimer=null,s.renderTimer!==null&&clearTimeout(s.renderTimer),s.renderTimer=null,this.emit(n,r,"delivery")}detectRender(n){const r=this.records.get(n);if(!r)return;const s=r.measure;if(s.renderTimer=null,!this.isRenderPending(r))return;const o=performance.now()-s.lastRenderAt;if(o<St){this.scheduleRenderStallCheck(n,r,St-o);return}const i=performance.now()-s.lastRawAt;if(i>=St&&s.deliveryTimer!==null){const c=ws-i;if(c>0){this.scheduleRenderStallCheck(n,r,c);return}}this.emit(n,r,"render")}scheduleRenderStallCheck(n,r,s){r.measure.renderTimer===null&&(r.measure.renderTimer=setTimeout(()=>this.detectRender(n),s))}scheduleDeliveryStallCheck(n,r){r.measure.deliveryTimer===null&&(r.measure.deliveryTimer=setTimeout(()=>this.detectDelivery(n),ws))}emit(n,r,s){if(this.emittedMessageChannels.has(n))return;const o=performance.now(),i=s==="delivery"?r.measure.lastRawAt:r.measure.lastRenderAt;r.stats.setStall({stallKind:s,durationMs:o-i}).commit(),this.rememberEmitted(n,r.measure.channelUrl),this.clearRecord(n,r)}getOrCreate(n,r){const s=this.records.get(n);if(s)return s;const o=performance.now(),i={stats:new Tu().setMessageId(n).setCommitCallback(this.commitCallback),measure:{channelUrl:r,deliveryTimer:null,lastRawAt:o,lastRawLength:0,lastRenderAt:o,lastRenderedLength:0,renderTimer:null}};return this.records.set(n,i),i}rememberEmitted(n,r){this.emittedMessageChannels.has(n)||$n(this.emittedMessageChannels,Iu),this.emittedMessageChannels.set(n,r)}clearRecord(n,r){r.measure.deliveryTimer!==null&&clearTimeout(r.measure.deliveryTimer),r.measure.renderTimer!==null&&clearTimeout(r.measure.renderTimer),this.records.delete(n)}isRenderPending(n){return n.measure.lastRenderedLength<n.measure.lastRawLength}markRawProgressForRecord(n,r,s){return r<=n.measure.lastRawLength?!1:(n.measure.lastRawLength=r,n.measure.lastRawAt=s,!0)}markRenderedProgressForRecord(n,r,s){return r<=n.measure.lastRenderedLength?!1:(n.measure.lastRenderedLength=r,n.measure.lastRenderAt=s,!0)}}class Ru extends tt{constructor(){super(...arguments);S(this,"beforeTpstAbsentMs");S(this,"afterTpenAbsentMs")}setBeforeTpstAbsentMs(n){return this.beforeTpstAbsentMs=n,this}setAfterTpenAbsentMs(n){return this.afterTpenAbsentMs=n,this}getMetricKey(){return su}buildPayload(){return this.beforeTpstAbsentMs===void 0&&this.afterTpenAbsentMs===void 0?null:this.createPayload((this.beforeTpstAbsentMs??0)+(this.afterTpenAbsentMs??0),{extra:{[j.BEFORE_TPST_ABSENT]:this.beforeTpstAbsentMs,[j.AFTER_TPEN_ABSENT]:this.afterTpenAbsentMs}})}}const ks=3e3,Mu=3e4;class wu extends Ot{constructor(){super(...arguments);S(this,"pendingAIResponseStartsByUserMessageId",new Map)}startTurn(n){this.cancelTurn(n.requestId);const r={stats:new Ru().setCommitCallback(this.commitCallback),measure:{afterTpenStartedAt:null,beforeTpstStartedAt:performance.now(),channelUrl:n.channelUrl,requestId:n.requestId,timer:null}};r.measure.timer=setTimeout(()=>this.commitTimeout(r.measure.requestId),Mu),this.records.set(n.requestId,r)}markUserMessageAck(n){const r=this.records.get(n.requestId);if(!r)return;r.measure.userMessageId=n.messageId;const s=this.pendingAIResponseStartsByUserMessageId.get(n.messageId);s&&(this.pendingAIResponseStartsByUserMessageId.delete(n.messageId),this.applyAIResponseStarted({channelUrl:s.channelUrl,matchesUserMessage:!0,userMessageId:n.messageId},s.startedAt))}replaceTurnRequestId(n,r){if(n===r)return;const s=this.records.get(n);s&&(this.records.delete(n),s.measure.requestId=r,this.records.set(r,s))}cancelTurn(n){this.cleanupTurn(n)}markTypingStarted(n){const r=performance.now();this.records.forEach(s=>{pt(s.measure.channelUrl,n)&&(this.recordAfterTpen(s,r),this.recordBeforeTpst(s,r))})}markTypingEnded(n){const r=performance.now();this.records.forEach(s=>{pt(s.measure.channelUrl,n)&&(this.recordBeforeTpst(s,r),s.measure.afterTpenStartedAt=r)})}markAIResponseStarted(n={}){const r=n.channelUrl,s=n.userMessageId,o=s!==void 0,i=performance.now();this.applyAIResponseStarted({channelUrl:r,matchesUserMessage:o,userMessageId:s},i)||!o||s===void 0||!Sr(this.records.values(),r)||this.pendingAIResponseStartsByUserMessageId.has(s)||($n(this.pendingAIResponseStartsByUserMessageId,100),this.pendingAIResponseStartsByUserMessageId.set(s,{channelUrl:r,startedAt:i}))}applyAIResponseStarted(n,r){if(!n.matchesUserMessage){const o=this.findSingleTurn(n.channelUrl);return o?(this.completeTurn(o.requestId,o.record,r),!0):!1}let s=!1;return this.records.forEach(o=>{pt(o.measure.channelUrl,n.channelUrl)&&(n.matchesUserMessage&&o.measure.userMessageId!==n.userMessageId||(s=!0,this.completeTurn(o.measure.requestId,o,r)))}),s}findSingleTurn(n){let r,s=0;return this.records.forEach(o=>{pt(o.measure.channelUrl,n)&&(s+=1,!(s>1)&&(r={requestId:o.measure.requestId,record:o}))}),s===1?r:void 0}completeTurn(n,r,s){this.recordBeforeTpst(r,s),this.recordAfterTpen(r,s),this.commitIfAbsent(n,r)}clear(){this.records.forEach(n=>{n.measure.timer!==null&&clearTimeout(n.measure.timer)}),this.records.clear(),this.pendingAIResponseStartsByUserMessageId.clear()}clearChannel(n){n&&(this.records.forEach(r=>{r.measure.channelUrl===n&&this.cleanupTurn(r.measure.requestId)}),this.pendingAIResponseStartsByUserMessageId.forEach((r,s)=>{r.channelUrl===n&&this.pendingAIResponseStartsByUserMessageId.delete(s)}))}commitTimeout(n){const r=this.records.get(n);if(!r)return;const s=performance.now();this.recordBeforeTpst(r,s),this.recordAfterTpen(r,s),this.commitIfAbsent(n,r)}commitIfAbsent(n,r){r.stats.commit(),this.cleanupTurn(n)}cleanupTurn(n){const r=this.records.get(n);r&&(r.measure.timer!==null&&clearTimeout(r.measure.timer),this.records.delete(n))}recordBeforeTpst(n,r){if(n.measure.beforeTpstStartedAt===null)return;const s=r-n.measure.beforeTpstStartedAt;s>=ks&&n.stats.setBeforeTpstAbsentMs(s),n.measure.beforeTpstStartedAt=null}recordAfterTpen(n,r){if(n.measure.afterTpenStartedAt===null)return;const s=r-n.measure.afterTpenStartedAt;s>=ks&&n.stats.setAfterTpenAbsentMs(s),n.measure.afterTpenStartedAt=null}}class ku extends tt{constructor(){super(...arguments);S(this,"ackToFirstChunkMs");S(this,"firstChunkToRenderMs");S(this,"isStreaming");S(this,"sendToAckMs");S(this,"totalDurationMs")}setDurations(n){return this.ackToFirstChunkMs=n.ackToFirstChunkMs,this.firstChunkToRenderMs=n.firstChunkToRenderMs,this.isStreaming=n.isStreaming,this.sendToAckMs=n.sendToAckMs,this.totalDurationMs=n.totalDurationMs,this}getMetricKey(){return nu}buildPayload(){return this.ackToFirstChunkMs===void 0||this.firstChunkToRenderMs===void 0||this.isStreaming===void 0||this.sendToAckMs===void 0||this.totalDurationMs===void 0?null:this.createPayload(this.totalDurationMs,{extra:{is_streaming:this.isStreaming,[j.ACK_TO_FIRST_CHUNK]:this.ackToFirstChunkMs,[j.FIRST_CHUNK_TO_RENDER]:this.firstChunkToRenderMs,[j.SEND_TO_ACK]:this.sendToAckMs}})}}const Lu=.15,Ou=10,Nu=e=>e<=0?!1:e>=1?!0:Math.random()<e;class Du extends Ot{constructor(n,r){super(n);S(this,"samplingRate");S(this,"pendingAIResponseByUserMessageId",new Map);S(this,"collectedCount",0);this.samplingRate=(r==null?void 0:r.samplingRate)??Lu}startTurn(n){if(this.collectedCount>=Ou||!Nu(this.samplingRate))return;this.collectedCount+=1;const r={stats:new ku().setCommitCallback(this.commitCallback),measure:{channelUrl:n.channelUrl,requestId:n.requestId,startedAt:performance.now()}};this.records.set(n.requestId,r)}markUserMessageAck(n){const r=this.records.get(n.requestId);if(!r)return;r.measure.ackAt=performance.now(),r.measure.userMessageId=n.messageId;const s=this.pendingAIResponseByUserMessageId.get(n.messageId);s&&(this.pendingAIResponseByUserMessageId.delete(n.messageId),this.applyAIResponseRaw(r,s))}replaceTurnRequestId(n,r){if(n===r)return;const s=this.records.get(n);s&&(this.records.delete(n),s.measure.requestId=r,this.records.set(r,s))}cancelTurn(n){const r=this.records.get(n);r&&(this.deleteRecord(r),this.collectedCount>0&&(this.collectedCount-=1))}markAIResponseRaw(n){const r=performance.now(),s=n.aiResponse.userMessageId;if(s===void 0&&Sr(this.records.values(),n.channelUrl))return;const o=this.findPendingRecord(n.channelUrl,s);if(o){this.applyAIResponseRaw(o,{...n,firstChunkAt:r});return}s===void 0||!Sr(this.records.values(),n.channelUrl)||this.bufferAIResponseRaw({messageId:n.messageId,...n.channelUrl!==void 0&&{channelUrl:n.channelUrl},aiResponse:n.aiResponse,firstChunkAt:r},s)}markAIResponseVisible(n){const r=this.findRecordByAIMessageId(n);if(!r)return!1;const s=r.measure;if(s.ackAt===void 0||s.firstChunkAt===void 0||s.userMessageId===void 0)return!1;const o=performance.now();return r.stats.setDurations({ackToFirstChunkMs:s.firstChunkAt-s.ackAt,firstChunkToRenderMs:o-s.firstChunkAt,isStreaming:!!s.isStreaming,sendToAckMs:s.ackAt-s.startedAt,totalDurationMs:o-s.startedAt}).commit(),this.deleteRecord(r),!0}hasPendingAIResponse(n){return this.findRecordByAIMessageId(n)!==void 0}clearMessage(n){this.pendingAIResponseByUserMessageId.forEach((s,o)=>{s.messageId===n&&this.pendingAIResponseByUserMessageId.delete(o)});const r=this.findRecordByAIMessageId(n);r&&(this.deleteRecord(r),this.collectedCount>0&&(this.collectedCount-=1))}clearChannel(n){n&&(this.records.forEach(r=>{r.measure.channelUrl===n&&(this.deleteRecord(r),this.collectedCount>0&&(this.collectedCount-=1))}),this.pendingAIResponseByUserMessageId.forEach((r,s)=>{r.channelUrl===n&&this.pendingAIResponseByUserMessageId.delete(s)}))}clear(){this.records.clear(),this.pendingAIResponseByUserMessageId.clear(),this.collectedCount=0}findRecordByAIMessageId(n){for(const r of this.records.values())if(r.measure.aiMessageId===n)return r}findPendingRecord(n,r){if(r!==void 0){for(const o of this.records.values())if(!(o.measure.ackAt===void 0||o.measure.firstChunkAt!==void 0)&&pt(o.measure.channelUrl,n)&&o.measure.userMessageId===r)return o;return}let s;for(const o of this.records.values())if(!(o.measure.ackAt===void 0||o.measure.firstChunkAt!==void 0)&&pt(o.measure.channelUrl,n)){if(s)return;s=o}return s}applyAIResponseRaw(n,r){n.measure.firstChunkAt===void 0&&(n.measure.firstChunkAt=n.measure.ackAt===void 0?r.firstChunkAt:Math.max(r.firstChunkAt,n.measure.ackAt),n.measure.aiMessageId=r.messageId,n.measure.channelUrl=n.measure.channelUrl??r.channelUrl,n.measure.isStreaming=r.aiResponse.isStreaming)}bufferAIResponseRaw(n,r){this.pendingAIResponseByUserMessageId.has(r)||($n(this.pendingAIResponseByUserMessageId,100),this.pendingAIResponseByUserMessageId.set(r,n))}deleteRecord(n){this.records.delete(n.measure.requestId),n.measure.userMessageId!==void 0&&this.pendingAIResponseByUserMessageId.delete(n.measure.userMessageId)}}function $u(){let e=null,t=0;const n=(r,s)=>{if((e==null?void 0:e.key)===r)return e.promise;const o=++t,c=(e?e.promise.catch(()=>{}).then(()=>s()):s()).finally(()=>{(e==null?void 0:e.id)===o&&(e=null)});return e={key:r,id:o,promise:c},c};return n.isPending=()=>e!==null,n}const Ls={isTalkToAgentViewEnabled:!0,scrollMode:"auto",newMessageIndicatorEnabled:!0,senderAvatarEnabled:!0},Wr={conversation:{...Ls,messageAlertSoundEnabled:!1,list:{...Ls,deferredMarkdownElements:[]},header:{avatarEnabled:!0},input:{camera:{photoEnabled:!0},gallery:{photoEnabled:!0},fileEnabled:!0},fileViewer:{downloadEnabled:!0}},launcher:{unreadBadgeEnabled:!1}},Os=e=>e?{conversation:Uu(e.conversation),launcher:Pu(e.launcher)}:Wr,Pu=e=>At(Wr.launcher,e),Fu=e=>{if(e.deferredMarkdownElements)return[...e.deferredMarkdownElements];const t=[];return e.markdownImageRenderMode==="complete-only"&&t.push("image"),e.markdownLinkRenderMode==="complete-only"&&t.push("link"),t},Uu=e=>{const t=Wr.conversation;if(!e)return t;const{list:n={},header:r={},input:s,fileViewer:o={},messageAlertSoundEnabled:i=t.messageAlertSoundEnabled,...c}=e,{camera:u={},gallery:d={},fileEnabled:m=t.input.fileEnabled}=s??{},h={...At(t.list,c,n),deferredMarkdownElements:Fu(n)};return{...h,messageAlertSoundEnabled:i,list:h,header:At(t.header,r),input:{camera:At(t.input.camera,u),gallery:At(t.input.gallery,d),fileEnabled:m},fileViewer:At(t.fileViewer,o)}},At=(e,...t)=>{const n={...e};for(const r of t)r&&Object.assign(n,qr(r));return n},Bu=e=>({userId:e.bot_userid,profileUrl:e.bot_profile_url,nickname:e.bot_nickname,replyToFile:e.reply_to_file,specialNotice:e.special_notice,specialNoticeEnabled:e.is_special_notice_enabled,showHandoffButton:e.show_handoff_button??!0,isMultipleActiveConversationsEnabled:e.is_multiple_active_conversations_enabled??!0,isUserFeedbackEnabled:e.is_user_feedback_enabled??!1,isUserFeedbackCommentOptionEnabled:e.is_user_feedback_comment_option_enabled??!1}),Hu=e=>({type:e.image_type||"default_icon",imageUrl:e.image_url}),yr=e=>({enabled:e.enabled,showIndicator:e.show_indicator,toggleAllowed:e.toggle_allowed,deleteOnOff:e.delete_on_off,consentDialog:e.consent_dialog});class Gu{constructor(){S(this,"_channelHandlerId",null);S(this,"_connectionHandlerId",null);S(this,"_initConversationRequests",new Map);S(this,"_handleActiveChannelChangedThrottled",null);S(this,"_setupChannelHandler",()=>{const t=Date.now();this._channelHandlerId=`aiagent_channel_${t}`,this._connectionHandlerId=`aiagent_connection_${t}`,this._handleActiveChannelChangedThrottled=hi(s=>{var o,i;(i=this._session)==null||i._updateActiveChannel({url:s.url,status:Ne(s)?"closed":"open",conversationStatus:(o=s.conversation)==null?void 0:o.status}),this._logger.debug("AIAgentEventManager: activeChannel updated",s.url)},250,{leading:!0,trailing:!1});const n=new Ze.GroupChannelHandler({onChannelChanged:s=>{var o,i;s.isGroupChannel()&&s.url===((o=this._session)==null?void 0:o.activeChannel.url)&&((i=this._handleActiveChannelChangedThrottled)==null||i.call(this,s))}}),r=new Ee.ConnectionHandler({onReconnectSucceeded:async()=>{await this._syncActiveChannelOnReconnect()}});this._chatClient.chatSDK.groupChannel.addGroupChannelHandler(this._channelHandlerId,n),this._chatClient.chatSDK.addConnectionHandler(this._connectionHandlerId,r),this._logger.debug("AIAgentEventManager: handlers registered",{channelHandlerId:this._channelHandlerId,connectionHandlerId:this._connectionHandlerId})});S(this,"_removeChannelHandler",()=>{this._channelHandlerId&&(this._chatClient.chatSDK.groupChannel.removeGroupChannelHandler(this._channelHandlerId),this._channelHandlerId=null),this._connectionHandlerId&&(this._chatClient.chatSDK.removeConnectionHandler(this._connectionHandlerId),this._connectionHandlerId=null),this._handleActiveChannelChangedThrottled&&(this._handleActiveChannelChangedThrottled.cancel(),this._handleActiveChannelChangedThrottled=null),this._logger.debug("AIAgentEventManager: handlers removed")});S(this,"_syncActiveChannelOnReconnect",async()=>{var n,r,s;const t=(n=this._session)==null?void 0:n.activeChannel.url;if(t)try{const i=await(await this._chatClient.chatSDK.groupChannel.getChannel(t)).refresh();i.url===t&&((s=this._session)==null||s._updateActiveChannel({url:i.url,status:Ne(i)?"closed":"open",conversationStatus:(r=i.conversation)==null?void 0:r.status}),this._logger.debug("AIAgentEventManager: activeChannel synced on reconnect",i.url))}catch(o){this._logger.error("AIAgentEventManager: failed to sync activeChannel on reconnect",o)}});S(this,"_initConversationIfNeeded",(t,n)=>{if(!t.isAIAgent||t.conversation)return Promise.resolve();const r=this._initConversationRequests.get(t.url);if(r)return r;const s=t.initConversation({aiAgentId:this.aiAgentId,initialUserMessage:n==null?void 0:n.initialUserMessage}).then(()=>{}).catch(o=>{this._logger.warn("AIAgentEventManager: initConversation failed",o)}).finally(()=>{this._initConversationRequests.delete(t.url)});return this._initConversationRequests.set(t.url,s),s});S(this,"onMessengerSettingsUpdated",t=>(this._dispatcher.subscribe(Fe.MessengerSettingsUpdated,t),()=>{this._dispatcher.unsubscribe(Fe.MessengerSettingsUpdated,t)}));S(this,"onActiveChannelUpdated",t=>(this._dispatcher.subscribe(Fe.ActiveChannelUpdated,t),()=>{this._dispatcher.unsubscribe(Fe.ActiveChannelUpdated,t)}));S(this,"onAuthTokenRefreshed",t=>(this._dispatcher.subscribe(Fe.AuthTokenRefreshed,t),()=>{this._dispatcher.unsubscribe(Fe.AuthTokenRefreshed,t)}));S(this,"onNudgeMessageReceived",t=>(this._dispatcher.subscribe(Fe.NudgeMessageReceived,t),()=>{this._dispatcher.unsubscribe(Fe.NudgeMessageReceived,t)}))}}class zu{constructor(t){S(this,"_sdkUser");S(this,"_userSession");S(this,"_dispatcher");S(this,"_activeChannel");S(this,"_updateActiveChannel",t=>{this._activeChannel=t,this._dispatcher.send(it.ActiveChannelUpdated({channelUrl:t.url,status:t.status,conversationStatus:t.conversationStatus}))});S(this,"_updateAuthToken",t=>{this._userSession.authToken=t,this._dispatcher.send(it.AuthTokenRefreshed())});this._sdkUser=t.sdkUser,this._userSession=t.userSession,this._dispatcher=t.dispatcher,this._activeChannel=t.activeChannel}get sdkUser(){return this._sdkUser}get userSession(){return this._userSession}get activeChannel(){return this._activeChannel}}const yi=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)}},Ai=e=>JSON.parse(e),Vu=e=>JSON.parse(e);function Ku(e,t){const[n,r]=t.split(",").map(s=>s.trim());return e==="dark"&&r||n}function qu(e){const t={};function n(r,s=""){for(const[o,i]of Object.entries(r)){const c=s?`${s}.${o}`:o;i&&typeof i=="object"&&!Array.isArray(i)?n(i,c):t[c]=i}}return n(e),t}function Wu({template:e,variables:t,variableKeyPattern:n,variableValueTransformer:r}){return Object.entries(t).reduce((s,[o,i])=>{if(!r&&!["number","boolean","string"].includes(typeof i))throw new Error(`If transformer is not provided, value(${o}:${i}) must be a {string, number, or boolean}`);const c=r?r(i):String(i),u=n(o);return s.replace(u,yi(c))},e)}async function Yu({template:e,variables:t,variableKeyPattern:n,variableValueTransformer:r}){return(await Promise.all(Object.entries(t).map(async([o,i])=>{const c=await r(i);return{regex:n(o),transformedValue:c}}))).reduce((o,{regex:i,transformedValue:c})=>o.replace(i,yi(c)),e)}var Yr=(e=>(e[e.EXTERNAL_AUTH_TOKEN_EXPIRED=1]="EXTERNAL_AUTH_TOKEN_EXPIRED",e))(Yr||{});const Ti=e=>typeof e=="object"&&e!==null,er=(e,t)=>t in e&&typeof e[t]=="string"&&e[t]!=="",ju=e=>!Ti(e)||!er(e,"channel_url")||!er(e,"ai_agent_id")||!er(e,"cpa_key")?null:{channelUrl:e.channel_url,aiAgentId:e.ai_agent_id,cpaKey:e.cpa_key},Xu={1:ju};function Zu(e){if(!Ti(e)||!("cat"in e)||typeof e.cat!="number"||!("data"in e))return null;const t=e.cat,n=Xu[t];if(!n)return null;const r=n(e.data);return r?{category:t,data:r}:null}function Ju(e,t,n,r){const s=Nc.default.init({appId:e,modules:[new Ze.GroupChannelModule,new he.AIAgentModule],localCacheEnabled:!0,options:new Ee.SendbirdChatOptions({typingIndicatorInvalidateTime:2e4}),...r,customApiHost:(r==null?void 0:r.customApiHost)??`https://api-${e}.app.delight.ai`,customWebSocketHost:(r==null?void 0:r.customWebSocketHost)??`wss://ws-${e}.app.delight.ai`});return s.addSendbirdExtensions([{version:n,product:Ee.SendbirdProduct.AI_AGENT,platform:t.platform}],{platform:t.deviceOSPlatform,version:t.deviceOSVersion},t.customData)||console.warn("Invalid Sendbird Extensions",t),s}function Qu(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 ed=[400300,400301,400302,400310],td=Yr.EXTERNAL_AUTH_TOKEN_EXPIRED.toString(),nd=e=>`${td}:${e}`;class jr{constructor(t,n,r,s,o){S(this,"chatSDK");S(this,"_aiAgentId");S(this,"_externalAuthTokenExpiredEventHandlerKey");S(this,"_logger");S(this,"_cache");S(this,"_statsTrackers");S(this,"_sessionHandler");S(this,"_aiEventHandlerRegistered",!1);S(this,"connect",async(t,n,r,s,o)=>{if(this._logger.debug("ChatClient.connect: start",t.userId),n){this._sessionHandler=n;const i=new Ee.SessionHandler({...n,onSessionTokenRequired:this._interceptTokenRefresh(n.onSessionTokenRequired,r,s)});this.chatSDK.setSessionHandler(i)}this._registerAIEventHandler();try{await this.chatSDK.connect(t.userId,t.authToken);const[,i]=await Promise.allSettled([this._syncTemplatesIfNeeded(),o?this.submitCPAAuthorizationCodes(o):Promise.resolve()]);return o&&(i.status==="fulfilled"?this._logger.debug("ChatClient.connect: CPA authorization codes submitted",i.value):this._logger.error("ChatClient.connect: CPA authorization code submission failed",i.reason)),this._logger.debug("ChatClient.connect: end",this.chatSDK.currentUser),this.chatSDK.currentUser}catch(i){const c=i;if(this.chatSDK.isCacheEnabled){if(this._isCacheRestrictedError(c))this._logger.warn("ChatClient.connect","offline connect restricted",c.message,c.code),this._logger.warn("ChatClient.connect","clear cached-data"),await this.chatSDK.clearCachedData().catch(u=>this._logger.warn("ChatClient.connect","clear cached-data failure",u));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",c.message,c.code),this.dispose(),c}});S(this,"_registerAIEventHandler",()=>{this._aiEventHandlerRegistered||(this._aiEventHandlerRegistered=!0,this.chatSDK.aiAgent.addEventHandler(this._externalAuthTokenExpiredEventHandlerKey,this._handleAIEvent))});S(this,"_handleAIEvent",t=>{var o;this._logger.debug("ChatClient.connect: EXTERNAL_AUTH_TOKEN_EXPIRED event received",t);const n=Zu(t),r=typeof t.cat=="number"?t.cat:void 0;if(r!==void 0&&r!==Yr.EXTERNAL_AUTH_TOKEN_EXPIRED)return;if(!n){this._statsTrackers.aievAuthExpiredUnhandled.onPayloadParseFailed({aiAgentId:this._aiAgentId});return}if(n.data.aiAgentId!==this._aiAgentId){this._logger.debug("ChatClient.connect: ignore EXTERNAL_AUTH_TOKEN_EXPIRED for another agent",n.data);return}const s=(o=this._sessionHandler)==null?void 0:o.onExternalAuthTokenExpired;if(!s){this._statsTrackers.aievAuthExpiredUnhandled.onCallbackNotFound(n.data);return}this._logger.debug("ChatClient.connect: calling onExternalAuthTokenExpired handler",n.data),s(n.data)});S(this,"dispose",()=>{this._aiEventHandlerRegistered&&(this.chatSDK.aiAgent.removeEventHandler(this._externalAuthTokenExpiredEventHandlerKey),this._aiEventHandlerRegistered=!1),this._sessionHandler=void 0});S(this,"disconnect",async()=>{this._logger.debug("ChatClient.disconnect: start"),this.dispose(),await this.chatSDK.disconnect(),this._cache.template.clear(),this._logger.debug("ChatClient.disconnect: end")});S(this,"getChannel",async t=>this.chatSDK.groupChannel.getChannel(t));S(this,"patchContext",async(t,n,r)=>this.chatSDK.aiAgent.patchContext(t,n,r));S(this,"updateContext",async(t,n,r)=>this.chatSDK.aiAgent.updateContext(t,n,r));S(this,"requestNudgeMessage",async t=>this.chatSDK.aiAgent.requestNudgeMessage(t));S(this,"submitCPAAuthorizationCodes",async({aiAgentId:t,authCodes:n})=>this.chatSDK.aiAgent.submitCustomerProvidedAuthCodes({aiAgentId:t,authorizationCodes:n}));S(this,"requestMessengerSettings",async t=>{var s;if(t.userId===""){const o=new Error("userId cannot be empty string for messenger settings request");throw this._logger.error("ChatClient.requestMessengerSettings: invalid userId",o),o}const n={...t,shouldSendFirstMessage:!1};this._logger.debug("ChatClient.requestMessengerSettings: requesting",n);const r=await this.chatSDK.aiAgent.requestMessengerSettings(n);return this._logger.debug("ChatClient.requestMessengerSettings: received",(s=r.active_channel)==null?void 0:s.channel_url),r});S(this,"setUserMemoryState",async t=>{this._logger.debug("ChatClient.setUserMemoryState: requesting",t);const n=await this.chatSDK.aiAgent.setUserMemoryState(t);return this._logger.debug("ChatClient.setUserMemoryState: received",n.enabled),n});S(this,"clearUserMemories",async(t={})=>{this._logger.debug("ChatClient.clearUserMemories: requesting",t),await this.chatSDK.aiAgent.clearUserMemories(t),this._logger.debug("ChatClient.clearUserMemories: completed")});S(this,"_interceptTokenRefresh",(t,n,r)=>{if(t)return async(s,o)=>{new Promise((i,c)=>t==null?void 0:t(i,c)).then(i=>{i?n==null||n(i):r==null||r(),s(i)}).catch(i=>{r==null||r(),o(i)})}});S(this,"_isCacheRestrictedError",t=>ed.some(n=>t.code===n));S(this,"_syncTemplatesIfNeeded",async()=>{var r,s;const t=(s=(r=this.chatSDK.appInfo)==null?void 0:r.aiAgentInfo)==null?void 0:s.templateListToken;if(!t)return;const n=this._cache.template.getCachedToken();if(!(n&&n===t)){this._logger.debug("ChatClient._syncTemplatesIfNeeded: syncing templates");try{const{templates:o,token:i}=await this.chatSDK.aiAgent.getMessageTemplates({limit:20});for(const{template:c}of o){const{key:u}=Ai(c);this._cache.template.set(u,c)}this._cache.template.setCachedToken(i),this._logger.debug("ChatClient._syncTemplatesIfNeeded: sync completed")}catch(o){this._logger.error("ChatClient._syncTemplatesIfNeeded: error",o)}}});this.chatSDK=t,this._aiAgentId=n,this._externalAuthTokenExpiredEventHandlerKey=nd(n),this._logger=r,this._cache=s,this._statsTrackers=o}static init(t){let n;return t.chatSDK?(Qu(t.chatSDK),n=t.chatSDK):n=Ju(t.appId,t.extensions,t.messengerVersion,t.chatParams),new jr(n,t.aiAgentId,t.logger,t.cache,t.statsTrackers)}}const rd=e=>t=>{if(!e||e.getState()==="foregrounded"){t();return}const n=e.subscribe(r=>{r==="foregrounded"&&(n(),t())});return n},sd=e=>()=>{let t=e.getState()==="backgrounded";const n=e.subscribe(r=>{r==="backgrounded"&&(t=!0)});return()=>(n(),t)},ln=new Map,Ii={set:(e,t)=>{ln.set(e,t)},get:e=>{if(ln.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=ln.get(e);if(!n)throw new Error(`AIAgent platform "${e}" is not configured.`);return{platform:e,...n}}const t=ln.entries().next().value;return{platform:t[0],...t[1]}}},xi="SENDBIRD_DESK_INQUIRE_TICKET_CLOSURE";var An=(e=>(e.WAITING="WAITING",e.CONFIRMED="CONFIRMED",e.DECLINED="DECLINED",e))(An||{});const od=e=>{if(!e)return null;const t=si(e);if(t.type!==xi)return null;const{state:n,ticketId:r}=t.body??{};return n==null||r==null?null:{state:n,ticketId:r}};class Ns extends Error{constructor(n,r){const s=(r==null?void 0:r.detail)??"";super(s||`Desk API error (${n})`);S(this,"status");S(this,"code");S(this,"detail");this.name="DeskApiError",this.status=n,this.code=(r==null?void 0:r.code)??"",this.detail=s}}var Xr=(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))(Xr||{}),Zr=(e=>(e.URGENT="URGENT",e.HIGH="HIGH",e.MEDIUM="MEDIUM",e.LOW="LOW",e))(Zr||{}),Ri=(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))(Ri||{});const id=e=>e==="desk401103"||e==="desk401106"||e==="desk401107"||e==="desk401108"||e==="desk401109";class ad{constructor(t){S(this,"_appId");S(this,"_apiHost");S(this,"_logger");S(this,"_credential",null);S(this,"_authRefreshPromise",null);S(this,"_onDeskTokenRefreshRequired",async()=>!1);S(this,"request",async(t,n)=>{const r=n.authRequired??!0,s=`${this._apiHost}${t}`;r&&this._authRefreshPromise&&(this._logger.debug("DeskApiClient: waiting for in-flight recovery..."),await this._authRefreshPromise);const o=await this._fetch(s,n);return r&&o.status===401?this._handleUnauthorized(o,s,n):this._toResult(o)});S(this,"setCredential",(t,n=async()=>!1)=>{this._authRefreshPromise=null,this._onDeskTokenRefreshRequired=n,this._credential=t});S(this,"clearCredential",()=>{this._authRefreshPromise=null,this._credential=null,this._onDeskTokenRefreshRequired=async()=>!1});S(this,"_handleUnauthorized",async(t,n,r)=>{const s=await this._parseErrorCode(t);if(!id(s))return this._toResult(t);if(!await this._refresh(s)||this._credential===null)return this._toResult(t);const i=await this._fetch(n,r);return this._toResult(i)});S(this,"_refresh",async t=>{if(this._authRefreshPromise)return this._logger.debug("DeskApiClient: refresh already in progress, joining..."),this._authRefreshPromise;try{return this._authRefreshPromise=this._onDeskTokenRefreshRequired({reason:t}).catch(n=>(this._logger.error("DeskApiClient: delegated recovery failed",n),!1)),await this._authRefreshPromise}finally{this._authRefreshPromise=null}});S(this,"_fetch",(t,n)=>fetch(`${t}?${this._buildParams(n.params)}`,{method:n.method,headers:this._buildHeaders(n.authRequired??!0,n.headers),...n.body?{body:JSON.stringify(this._buildBody(n.body))}:{}}));S(this,"_buildParams",t=>new URLSearchParams({sendbirdAppId:this._appId,...t}));S(this,"_buildBody",t=>({sendbirdAppId:this._appId,...t}));S(this,"_buildHeaders",(t,n)=>({"content-type":"application/json",...t&&this._credential?{sendbirdDeskToken:this._credential.deskToken}:{},...n}));S(this,"_toResult",async t=>{if(!t.ok){const r=await t.json().catch(()=>({}));throw new Ns(t.status,r)}const n=await t.text();if(n)try{return JSON.parse(n)}catch{throw new Ns(t.status,{})}});S(this,"_parseErrorCode",async t=>{const n=await t.clone().json().catch(()=>({}));return n==null?void 0:n.code});this._appId=t.appId,this._apiHost=t.customApiHost??`https://desk-api-${t.appId}.app.delight.ai/sapi`,this._logger=t.logger}get credential(){return this._credential}}class Tn{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 Tn({id:t.id,title:t.channelName??null,status:t.status2??Xr.INITIALIZED,agent:(()=>{var o;const s=(o=t.recentAssignment)==null?void 0:o.agent;return s?{userId:s.sendbirdId??"",name:s.displayName??"",profileUrl:s.photoThumbnailUrl??""}:null})(),priority:t.priority??Zr.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 Jr{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 Tn._fromResponse(n,this)});S(this,"createTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request("/tickets/",{method:"POST",body:qr({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 Tn._fromResponse(n,this)});S(this,"confirmEndOfChat",async({messageId:t,ticketId:n,confirmed:r})=>{this._assertAuthenticated(this._apiClient),await this._apiClient.request(`/tickets/${encodeURIComponent(n)}/edit_message/`,{method:"PATCH",body:{messageId:t,messageData:JSON.stringify({type:xi,body:{state:r?An.CONFIRMED:An.DECLINED,ticketId:n}})}})});this._logger=t.logger,this._apiClient=new ad(t)}static init(t){return new Jr(t)}_assertAuthenticated(t){if(t.credential==null)throw new Error("DeskClient is not authenticated")}}class Qr{constructor(){S(this,"authenticate",async t=>!1);S(this,"deauthenticate",()=>{});S(this,"refreshDeskAuthToken",async()=>!1);S(this,"setCustomerLanguage",async()=>{});S(this,"getTicket",async()=>{throw new Error("DeskClient is disabled via __SBA_USE_DESK_CLIENT__")});S(this,"confirmEndOfChat",async()=>{throw new Error("DeskClient is disabled via __SBA_USE_DESK_CLIENT__")})}static init(){return new Qr}}function cd(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 ld=1440*60*1e3,ud=typeof __SBA_USE_DESK_CLIENT__>"u"||__SBA_USE_DESK_CLIENT__;function He(e){if(!e)throw new Error("Not authenticated. Call authenticate() first.")}function dd(e,t){return Object.entries(t).every(([n,r])=>e[n]===r)}const md=e=>{const t={conversationInitialRender:new mu(e),conversationNotInteractiveTimeout:new _u(e),recoveryNotInteractiveTimeout:new vu(e),conversationListInitialRender:new gu(e),aievAuthExpiredUnhandled:new lu(e),messagePendingStuck:new bu(e),userPerceivedResponseTime:new Du(e),streamStalled:new xu(e),typingIndicatorAbsentTimeout:new wu(e),renderedContentUnusable:new Au(e)};return{...t,clear:()=>{Object.values(t).forEach(n=>n.clear())}}};class In extends Gu{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,"cpaAuthorizationCodes");S(this,"queryParams");S(this,"_config");S(this,"_networkStateAdapter");S(this,"_scheduleForegroundTask");S(this,"_watchBackgrounded");S(this,"_forceCreateChannel");S(this,"_agentVersion");S(this,"_statsTrackers");S(this,"_liveMetricManager");S(this,"_operationQueue",$u());S(this,"dispose",()=>{this._operationQueue.isPending()||(this._logger.debug("AIAgent.dispose: start"),this._chatClient.dispose(),this._chatClient.chatSDK.connectionState==="OPEN"&&this._chatClient.chatSDK.disconnectWebSocket(),this._removeChannelHandler(),this._session=null,this._deskClient.deauthenticate(),this._statsTrackers.clear(),this._liveMetricManager.dispose(),this._logger.debug("AIAgent.dispose: end"))});S(this,"initConversationIfNeeded",(n,r)=>this._initConversationIfNeeded(n,r));S(this,"authenticate",n=>{if(!this.appId)return Promise.reject(new Error("appId is required"));if(!this.aiAgentId)return Promise.reject(new Error("aiAgentId is required"));const r=n&&"userId"in n?`auth:${n.userId}`:"auth:anon";return this._operationQueue(r,async()=>{var i,c,u,d,m;this._logger.debug("AIAgent.authenticate: start"),this._statsTrackers.conversationInitialRender.onAuthStart(),this._statsTrackers.conversationListInitialRender.onAuthStart();const s=this._getSessionCandidate(n),o=(i=s.userSessionCandidate)!=null&&i.userId?this._cache.messenger.getSettings(s.userSessionCandidate.userId):null;o!=null&&o.bot&&this._dispatcher.send(it.MessengerSettingsUpdated({settings:o,source:"cache"}));try{const h=await this._chatClient.requestMessengerSettings({aiAgentId:this.aiAgentId,userId:(c=s.userSessionCandidate)==null?void 0:c.userId,language:this.language,country:this.countryCode,context:this.context,knownActiveChannelUrl:(u=o==null?void 0:o.active_channel)==null?void 0:u.channel_url,forceCreateChannel:this._forceCreateChannel,agentVersion:this._agentVersion});let f;if(h.auto_created_user)if(s.type==="manual")this._logger.warn("Received auto created user info but current session is manual. Ignoring auto created user info."),f={userId:s.userSessionCandidate.userId,authToken:s.userSessionCandidate.authToken};else{const{user_id:v,session_token:E,expire_at:_}=h.auto_created_user;this._cache.messenger.setAnonUser({userId:v,authToken:E,expireAt:_}),f={userId:v,authToken:E},this._logger.debug("AIAgent.authenticate: anonymous user created",v)}else f={userId:((d=s.userSessionCandidate)==null?void 0:d.userId)??"",authToken:((m=s.userSessionCandidate)==null?void 0:m.authToken)??""};this._cache.messenger.setSettings(f.userId,h),this._dispatcher.send(it.MessengerSettingsUpdated({settings:h,source:"server"}));const g=(()=>{var v;return s.type==="anonymous"?Yl(this._dispatcher):(v=s.userSessionCandidate)==null?void 0:v.sessionHandler})(),p=await this._chatClient.connect(f,g,v=>{var E;this._logger.debug("AIAgent: session token refreshed"),(E=this._session)==null||E._updateAuthToken(v),this._deskClient.refreshDeskAuthToken(v)},()=>{this._logger.debug("AIAgent: session token unavailable, deauthenticating desk"),this._deskClient.deauthenticate()},this.cpaAuthorizationCodes?{aiAgentId:this.aiAgentId,authCodes:this.cpaAuthorizationCodes}:void 0);return await this._deskClient.authenticate({userId:f.userId,accessToken:f.authToken,onDeskTokenRefreshRequired:async({reason:v})=>{var E;if(v===Ri.ERR_SESSION_KEY_EXPIRED){await new Promise(A=>setTimeout(A,2e3));const _=(E=this._session)==null?void 0:E.userSession.authToken;return _?await this._deskClient.refreshDeskAuthToken(_):!1}return!1}}),(o==null?void 0:o.language)!==h.language&&this._deskClient.setCustomerLanguage(this.language).catch(()=>{}),this._statsTrackers.conversationInitialRender.onAuthComplete(),this._statsTrackers.conversationListInitialRender.onAuthComplete(),this._session=new zu({sdkUser:p,userSession:f,activeChannel:{url:h.active_channel.channel_url,status:"open"},dispatcher:this._dispatcher}),this._setupChannelHandler(),this._logger.debug("AIAgent.authenticate: end",{userId:f.userId}),h}catch(h){throw this._statsTrackers.conversationInitialRender.onAuthError(h),this._statsTrackers.conversationListInitialRender.onAuthError(h),h}})});S(this,"submitCPAAuthorizationCodes",async n=>{He(this._session),this._logger.debug("AIAgent.submitCPAAuthorizationCodes: start");const r=await this._chatClient.submitCPAAuthorizationCodes({aiAgentId:this.aiAgentId,authCodes:n});return this._logger.debug("AIAgent.submitCPAAuthorizationCodes: end",r),r});S(this,"deauthenticate",()=>this._operationQueue("deauth",async()=>{var r;this._logger.debug("AIAgent.deauthenticate: start");const n=(r=this._session)==null?void 0:r.userSession.userId;this._statsTrackers.clear();try{await this._chatClient.disconnect()}finally{this._deskClient.deauthenticate(),this._cache.messenger.clear(n),this._session=null,this._removeChannelHandler(),this._statsTrackers.clear()}this._logger.debug("AIAgent.deauthenticate: end")}));S(this,"createConversation",async n=>{He(this._session),this._logger.debug("AIAgent.createConversation: start",n);const r=await this._chatClient.requestMessengerSettings({...n,userId:this._session.userSession.userId,knownActiveChannelUrl:void 0,agentVersion:this._agentVersion}),s=r.active_channel.channel_url;return this._cache.messenger.setSettings(this._session.userSession.userId,r),this._logger.debug("AIAgent.createConversation: end",s),s});S(this,"searchConversation",async n=>{if(He(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:he.ConversationStatus.OPEN,limit:100}),s=[];for(;r.hasNext;){const o=await r.next();for(const i of o)dd(i.context??{},n.context)&&s.push(i.channelInfo.url)}return this._logger.debug("AIAgent.searchConversation: end",{count:s.length}),s});S(this,"closeConversation",async n=>{var s;He(this._session),this._logger.debug("AIAgent.closeConversation: start",n);const r=await this._chatClient.getChannel(n);((s=r.conversation)==null?void 0:s.status)===he.ConversationStatus.OPEN?(await r.closeConversation(),this._session.activeChannel.url===n&&this._session._updateActiveChannel({url:n,status:"closed",conversationStatus:he.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 fi(this.chatSDK,n??{}));S(this,"patchContext",async(n,r)=>{He(this._session),this._logger.debug("AIAgent.patchContext: start",{channelUrl:n,context:r});const s=await this._chatClient.patchContext(this.aiAgentId,n,r);return this._logger.debug("AIAgent.patchContext: end",s),{...s,context:s.context??{}}});S(this,"updateContext",async(n,r)=>{He(this._session),this._logger.debug("AIAgent.updateContext: start",{channelUrl:n,context:r});const s=await this._chatClient.updateContext(this.aiAgentId,n,r);return this._logger.debug("AIAgent.updateContext: end",s),{...s,context:s.context??{}}});S(this,"getContextObject",async n=>{He(this._session),this._logger.debug("AIAgent.getContextObject: start",n);const s=await(await this._chatClient.getChannel(n)).getContextObject(this.aiAgentId);return this._logger.debug("AIAgent.getContextObject: end",s),{...s,context:s.context??{}}});S(this,"requestNudgeMessage",async n=>{He(this._session);const r=this._session;this._logger.debug("AIAgent.requestNudgeMessage: start",n);const s=await this._chatClient.requestNudgeMessage({aiAgentId:this.aiAgentId,key:n.key,context:n.context,language:this.language});if(this._logger.debug("AIAgent.requestNudgeMessage: end",s),this._session!==r){this._logger.debug("AIAgent.requestNudgeMessage: session changed during request, discarding stale nudge");return}s.status!=="ok"||!s.payload.message||this._dispatcher.send(it.NudgeMessageReceived({message:s.payload.message,callbackUserMessage:s.payload.callback_user_message??void 0}))});S(this,"clearUserMemories",async(n={})=>{He(this._session);const r={...n,contextAiAgentId:n.contextAiAgentId??this.aiAgentId};this._logger.debug("AIAgent.clearUserMemories: start",r),await this._chatClient.clearUserMemories(r),this._logger.debug("AIAgent.clearUserMemories: end")});S(this,"confirmEndOfChat",async n=>{He(this._session),this._logger.debug("AIAgent.confirmEndOfChat: start",n),await this._deskClient.confirmEndOfChat(n),this._logger.debug("AIAgent.confirmEndOfChat: end")});S(this,"setUserMemoryState",async n=>{He(this._session);const r=this._session;this._logger.debug("AIAgent.setUserMemoryState: start",n.enabled);const s={...n,contextAiAgentId:n.contextAiAgentId??this.aiAgentId},o=r.userSession.userId,i=await this._chatClient.setUserMemoryState(s);if(this._session!==r)return this._logger.debug("AIAgent.setUserMemoryState: session changed during request, discarding stale result"),yr(i);const c=this._cache.messenger.getSettings(o);if(c){const u={...c,memory:i};this._cache.messenger.setSettings(o,u),this._dispatcher.send(it.MessengerSettingsUpdated({settings:u,source:"cache"}))}return this._logger.debug("AIAgent.setUserMemoryState: end",i.enabled),yr(i)});S(this,"refreshActiveChannel",async n=>{var c,u,d;He(this._session);const r=this._session,s=(n==null?void 0:n.useKnownActiveChannelUrl)??!0;this._logger.debug("AIAgent.refreshActiveChannel: start",{useKnownActiveChannelUrl:s});const o=await this._chatClient.requestMessengerSettings({aiAgentId:this.aiAgentId,userId:r.userSession.userId,language:this.language,country:this.countryCode,context:this.context,knownActiveChannelUrl:s?(u=(c=this._cache.messenger.getSettings(r.userSession.userId))==null?void 0:c.active_channel)==null?void 0:u.channel_url:void 0,forceCreateChannel:this._forceCreateChannel,agentVersion:this._agentVersion});if(this._session!==r)return this._logger.debug("AIAgent.refreshActiveChannel: session changed during refresh, discarding stale result"),((d=this._session)==null?void 0:d.activeChannel.url)??o.active_channel.channel_url;const i=o.active_channel.channel_url;return this._cache.messenger.setSettings(this._session.userSession.userId,o),this._session._updateActiveChannel({url:i,status:"open"}),this._logger.debug("AIAgent.refreshActiveChannel: end",i),i});S(this,"_getSessionCandidate",n=>n instanceof Ci?{type:"manual",userSessionCandidate:this._getManualSessionInfo(n)}:n instanceof br?{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-ld<=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 br)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.cpaAuthorizationCodes=n.cpaAuthorizationCodes,this._config=Os(n.config),this.queryParams=n.queryParams,this._networkStateAdapter=n.networkStateAdapter,this._scheduleForegroundTask=rd(n.foregroundStateAdapter),this._watchBackgrounded=n.foregroundStateAdapter&&sd(n.foregroundStateAdapter),this._forceCreateChannel=n.forceCreateChannel,this._agentVersion=n.agentVersion,this._chatClient=n.chatClient,this._deskClient=n.deskClient,this._cache=n.cache,this._logger=n.logger,this._dispatcher=n.dispatcher,this._statsTrackers=n.statsTrackers,this._liveMetricManager=new Wl(this._chatClient.chatSDK),this._liveMetricManager.start()}static init(n){var g;const r=Ii.get(n.platform),s=n.logger??new Ei(n.logLevel??Kr.WARN),o=n.dispatcher??new gi(s),i=n.useMMKVStorage?cd(n.useMMKVStorage):r.keyValueStorage,c=n.useMMKVStorage?{...n.chatParams,useMMKVStorageStore:n.useMMKVStorage}:n.chatParams,u=cl({appId:n.appId,aiAgentId:n.aiAgentId,storage:i});let d;const h=md((p,v)=>{if(!d)throw new Error("ChatClient is not initialized.");return d.chatSDK.aiAgent.appendStat(p,v)});d=jr.init({appId:n.appId,aiAgentId:n.aiAgentId,messengerVersion:r.messengerVersion,extensions:{platform:r.platform,deviceOSPlatform:r.deviceOSPlatform,deviceOSVersion:r.deviceOSVersion,customData:n._sourceService?{source_service:n._sourceService}:void 0},chatParams:c,chatSDK:n.chatSDK,logger:s,cache:u,statsTrackers:h});const f=ud?Jr.init({appId:n.appId,logger:s,customApiHost:(g=n.deskParams)==null?void 0:g.customApiHost}):Qr.init();return s.debug("AIAgent.init: created",{appId:n.appId,aiAgentId:n.aiAgentId}),new In({appId:n.appId,aiAgentId:n.aiAgentId,language:n.language,countryCode:n.countryCode,context:n.context,cpaAuthorizationCodes:n.cpaAuthorizationCodes,config:n.config,queryParams:n.queryParams,networkStateAdapter:r.networkStateAdapter,foregroundStateAdapter:r.foregroundStateAdapter,forceCreateChannel:n._forceCreateChannel,agentVersion:n._agentVersion,chatClient:d,deskClient:f,cache:u,logger:s,dispatcher:o,statsTrackers:h})}get chatSDK(){return this._chatClient.chatSDK}get deskClient(){return this._deskClient}get session(){return this._session}get config(){return this._config}set config(n){this._config=Os(n)}get agentVersion(){return this._agentVersion}set agentVersion(n){this._agentVersion=n}get statsTrackers(){return this._statsTrackers}get liveMetricManager(){return this._liveMetricManager}get onLiveMetric(){return this._liveMetricManager.dispatch}set onLiveMetric(n){this._liveMetricManager.dispatch=n}get networkStateAdapter(){return this._networkStateAdapter}get logger(){return this._logger}get dispatcher(){return this._dispatcher}get cache(){return this._cache}get scheduleForegroundTask(){return this._scheduleForegroundTask}get watchBackgrounded(){return this._watchBackgrounded}}const be=(e,t)=>{const n=l.createContext(t??null),r=({children:i,value:c})=>a.createElement(n.Provider,{value:c},typeof i=="function"?i(c):i),s=({children:i})=>a.createElement(n.Consumer,null,c=>c?typeof i=="function"?i(c):i:null),o=()=>{const i=l.useContext(n);if(!i)throw new Error(`use${e}Context must be used within a ${e}Provider`);return i};return n.displayName=`${e}Context`,r.displayName=`${e}Provider`,s.displayName=`${e}Consumer`,o.displayName=`use${e}Context`,{Context:n,Provider:r,Consumer:s,useContext:o}};function qe(e){const t=l.createContext({Template:e.template,updateTemplate:()=>{},components:e.components,updateComponent:()=>{}});function n({children:o}){const[i,c]=l.useState(()=>e.template),[u,d]=l.useState(e.components),m={Template:i,updateTemplate:h=>c(()=>h),components:u,updateComponent:(h,f)=>d(g=>({...g,[h]:f}))};return a.createElement(t.Provider,{value:m},o)}function r({template:o,children:i}){const{updateTemplate:c}=l.useContext(t);return l.useLayoutEffect(()=>{o&&c(o)},[o]),a.createElement(a.Fragment,null,i)}function s({children:o}){return a.createElement(n,null,o)}return s.defaults=e,s.useContext=()=>l.useContext(t),s.Context=t,s.Template=r,Object.keys(e.components).forEach(o=>{s[o]=function({component:c}){const{updateComponent:u}=l.useContext(t);return l.useLayoutEffect(()=>{c&&u(o,c)},[c]),null}}),s}function hd(...e){return function({children:n}){return e.reduce((r,s)=>a.createElement(s,null,r),n)}}function fd(e,t){const n=e.lastMessage;return n!=null&&n.isAdminMessage()?n.message??"":gd(e,t)}function gd(e,t){var r;const n=e.lastMessage;if(n!=null&&n.isUserMessage())return n.message||"";if(n!=null&&n.isAdminMessage())return n.message??"";if(n!=null&&n.isFileMessage())return n.message||n.name||"FILE";if(n!=null&&n.isMultipleFilesMessage()){if(n.message)return n.message;const s=n.fileInfoList.length;return((r=t==null?void 0:t.formatMultipleFilesCount)==null?void 0:r.call(t,s))??`${s} photos`}return e.name}function pd(e,t,n){var i;const r=new Date,s=new Date(((i=e.lastMessage)==null?void 0:i.createdAt)||e.createdAt),o=ut.differenceInMinutes(r,s);return o<1?n.justNow:o<60?n.minutesAgo(o):ut.isToday(s)?n.hoursAgo(ut.differenceInHours(r,s)):t(s,n.dateShortFormat)}const _d=typeof __SBA_USE_DESK_CLIENT__>"u"||__SBA_USE_DESK_CLIENT__,Ed=({data:e,extendedMessagePayload:t,ticketClosureLabels:n})=>{if(_d){const r=od(e);if(r)return r.state!==An.WAITING?[]:[{action:"confirmTicketClosure",label:n.confirm,confirmed:!0,ticketId:r.ticketId},{action:"confirmTicketClosure",label:n.decline,confirmed:!1,ticketId:r.ticketId}]}return((t==null?void 0:t.suggested_replies)??[]).map(r=>({action:"sendMessage",label:r}))},Cd=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},un=e=>Math.max(0,Math.min(255,e)).toString(16).padStart(2,"0"),Ds=(e,t)=>{const n=un(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=Cd(e);return r?`#${un(r[0])}${un(r[1])}${un(r[2])}${n}`:e},bd=(e,t)=>{if(!t)return e;const n={...e};for(const[r,s]of Object.entries(t))s&&(n[r]=s);return n},vd=e=>e.consentDialog?"consent":e.toggleAllowed?e.enabled?"on":"off":"readonly",Sd=e=>e.length>0,yd=e=>{const t=e[0];if(!t)return e;const n=e.some(s=>Ke(s.type)),r=e.some(s=>!Ke(s.type));return n&&r?Ke(t.type)?e.filter(s=>Ke(s.type)):[t]:r?[t]:e},$s=e=>e.length===0?"empty":e.every(t=>Ke(t.type))?"images":"non_images",Ad=({currentFiles:e,incomingFiles:t,maxAttachmentCount:n})=>{const r=yd(t),s=$s(e),o=$s(r),c=s==="images"&&o==="images"?{type:"append",files:r,nextFiles:[...e,...r]}:{type:"replace",files:r,nextFiles:r};return c.nextFiles.length>n?{type:"reject",reason:"count_limit",maxAttachmentCount:n,nextFileCount:c.nextFiles.length}:c.type==="replace"&&s!=="empty"&&s!==o?{type:"confirm_replace",action:c}:{type:"apply",action:c}},xt=3,Mi=6,Td=e=>e%xt===0?xt:Mi,Id=({index:e,itemCount:t})=>{const n=t%xt,r=n>0,s=r?t-n:t,o=r&&e>=s,i=o?n:xt,c=o?e-s:e%xt,u=!r&&e>=t-xt;return{columnSpan:r?Mi/i:1,rowItemCount:i,isLastInRow:c===i-1,isLastRow:o||u}},wi=be("AIAgent"),xd=wi.Provider,ye=wi.useContext;function Rd(e){const t=Md(e);return a.createElement(xd,{value:{_aiAgentSDK:t,chatSDK:t.chatSDK,deskClient:t.deskClient,appId:t.appId,aiAgentId:t.aiAgentId,language:t.language,countryCode:t.countryCode,context:t.context,cpaAuthorizationCodes:t.cpaAuthorizationCodes,logger:t.logger,dispatcher:t.dispatcher,cache:t.cache,networkStateAdapter:t.networkStateAdapter,queryParams:t.queryParams,config:t.config,handlers:e.handlers}},e.children)}function Md(e){var s;const t=l.useRef(null),n=l.useRef(null);if(!t.current||!n.current)t.current=In.init(e);else{const o=wd(n.current,e);(o.appId||o.aiAgentId||o.chatSDK)&&(t.current.dispose(),t.current=In.init({...e,chatParams:o.appId?{...e.chatParams,newInstance:!0}:e.chatParams}))}n.current=e,l.useEffect(()=>()=>{var o;(o=t.current)==null||o.dispose()},[]);const r=t.current;return r.language=e.language??"en",r.countryCode=e.countryCode,r.context=e.context,r.cpaAuthorizationCodes=e.cpaAuthorizationCodes,r.queryParams=e.queryParams,r.config=e.config,r.agentVersion=e._agentVersion,r.onLiveMetric=(s=e.handlers)==null?void 0:s.onLiveMetric,r}function wd(e,t){const n=t.chatSDK!==void 0&&t.chatSDK!==null;return{appId:!n&&e.appId!==t.appId,aiAgentId:e.aiAgentId!==t.aiAgentId,chatSDK:!!e.chatSDK!==n||n&&t.chatSDK!==e.chatSDK}}function ce(e){const t=l.useRef(e);return t.current=e,l.useCallback((...n)=>t.current(...n),[t])}const Pn=()=>{const[,e]=l.useState(0);return l.useCallback(()=>e(t=>t+1),[])};let kd=0;function Ld(){return l.useState(()=>`${kd++}`)[0]}const _t=(e,t,n)=>{const r=l.useRef(t),o=Ld();r.current=t,l.useEffect(()=>{var c;const i=u=>{const d=u;return Object.keys(d).forEach(h=>{d[h]=(...f)=>{var p;const g=r.current;(p=g[h])==null||p.call(g,...f)}}),d};return(c=e==null?void 0:e.groupChannel)==null||c.addGroupChannelHandler(o,i(new Ze.GroupChannelHandler)),()=>{var u;(u=e==null?void 0:e.groupChannel)==null||u.removeGroupChannelHandler(o)}},[e==null?void 0:e.groupChannel,o])};function Od(e,t){return!e||!t?!0:e.url!==t.url}function ze(e){return e!=null&&"sendingStatus"in e}function Nd(e,t="##__USER_ID_IS_NOT_PROVIDED__##"){var n;return ze(e)?((n=e.sender)==null?void 0:n.userId)===t:!1}function Dd(e,t){return Nd(e,t)||e.isAdminMessage()?!1:e.updatedAt===0}function Ps(e){return"sendingStatus"in e?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId)}const xn={collection:{groupChannel:{defaultOrder:Ze.GroupChannelListOrder.LATEST_LAST_MESSAGE},message:{defaultLimit:{next:25,prev:25},searchLimit:{next:10,prev:10}}}};function Fs(e){return!e||!Array.isArray(e)?!1:e.length!==0}function Us(e,t){return e.reduce((n,r)=>{const s=t(r);return n[s]=r,n},{})}const $d=({...e},t)=>{switch(t.type){case"update_initialized":return e.initialized=t.value.status,e;case"update_refreshing":return e.refreshing=t.value.status,e;case"update_loading":return e.loading=t.value.status,e;case"update_messages":{if(t.value.clearBeforeAction)e.messageMap=Pd(t.value.messages);else{const n={...e.messageMap},r=[],s=[];t.value.messages.forEach(o=>{const i=ze(o)?o.reqId:void 0,c=o.messageId||void 0;[i,c].forEach(u=>{if(!u)return;const d=n[u];Fd(d,o,t.value.strictStreamingOrder)&&(d&&r.push(d),o.parentMessageId>0&&(d!=null&&d.parentMessage)&&o.applyParentMessage(d.parentMessage),s.push(o))})}),r.forEach(o=>{ze(o)&&delete n[o.reqId],delete n[o.messageId]}),s.forEach(o=>{ze(o)&&(n[o.reqId]=o),o.messageId!==0&&(n[o.messageId]=o)}),e.messageMap=n}return e}case"update_new_messages":{const n=t.value.currentUserId,r=t.value.messages.filter(s=>Dd(s,n));return t.value.clearBeforeAction?e.newMessageMap=Us(r,Ps):(r.map(o=>o.messageId).forEach(o=>delete e.newMessageMap[o]),e.newMessageMap={...e.newMessageMap,...Us(r,Ps)}),e}case"delete_messages":case"delete_new_messages":{const n=t.type==="delete_messages"?"messageMap":"newMessageMap";return e[n]={...e[n]},t.value.messageIds.forEach(r=>{if(r===0)return;const s=e[n][r];s&&(ze(s)&&delete e[n][s.reqId],delete e[n][s.messageId])}),t.value.reqIds.forEach(r=>{const s=e[n][r];s&&(ze(s)&&delete e[n][s.reqId],delete e[n][s.messageId])}),e}}},Pd=e=>e.reduce((t,n)=>(ze(n)?(t[n.reqId]=n,n.sendingStatus===Le.SendingStatus.SUCCEEDED&&(t[n.messageId]=n)):t[n.messageId]=n,t),{}),Fd=(e,t,n=!1)=>{var r,s;if(!ze(e)||!ze(t))return!0;if(n&&e&&we.isStreaming(e)&&we.isStreaming(t)){const o=((r=e.message)==null?void 0:r.length)||0,i=((s=t.message)==null?void 0:s.length)||0;if(o>i)return!1}return e.sendingStatus===Le.SendingStatus.SUCCEEDED?t.sendingStatus===Le.SendingStatus.SUCCEEDED:e.sendingStatus!==t.sendingStatus},Ud=(e=Bd)=>{const[{initialized:t,loading:n,refreshing:r,messageMap:s,newMessageMap:o},i]=l.useReducer($d,{initialized:!1,loading:!0,refreshing:!1,messageMap:{},newMessageMap:{}}),c=(E,_,A,y)=>{i({type:"update_messages",value:{messages:E,clearBeforeAction:_,currentUserId:A,strictStreamingOrder:y}})},u=(E,_)=>{i({type:"delete_messages",value:{messageIds:E,reqIds:_}})},d=(E,_,A)=>{i({type:"update_new_messages",value:{messages:E,clearBeforeAction:_,currentUserId:A}})},m=(E,_)=>{i({type:"delete_new_messages",value:{messageIds:E,reqIds:_}})},h=E=>{i({type:"update_initialized",value:{status:E}})},f=E=>{i({type:"update_loading",value:{status:E}})},g=E=>{i({type:"update_refreshing",value:{status:E}})},p=Object.values(o),v=l.useMemo(()=>Array.from(new Set(Object.values(s))).sort(e),[s]);return{updateInitialized:h,updateLoading:f,updateRefreshing:g,updateMessages:c,deleteMessages:u,initialized:t,loading:n,refreshing:r,messages:v,newMessages:p,updateNewMessages:d,deleteNewMessages:m}},Bs=Math.floor(Number.MAX_SAFE_INTEGER/10);function Bd(e,t){let n=0,r=0;return ze(e)&&e.sendingStatus!=="succeeded"&&(n=Bs),ze(t)&&t.sendingStatus!=="succeeded"&&(r=Bs),e.createdAt+n-(t.createdAt+r)}const Hd=(e,t,n)=>{var o;const r={prevResultLimit:t.prev,nextResultLimit:t.next,startingPoint:n==null?void 0:n.startingPoint,replyType:n==null?void 0:n.replyType},s=(o=n==null?void 0:n.collectionCreator)==null?void 0:o.call(n,r);return s||e.createMessageCollection({...r,filter:new Ze.MessageFilter(r)})};function Hs(e){return e<Date.now()?xn.collection.message.searchLimit:xn.collection.message.defaultLimit}const Gd=(e,t,n={})=>{var Te,$;const r=l.useRef(n);r.current=n;const s=l.useRef(t);s.current=t;const o=r.current.logger,i=r.current.startingPoint??Number.MAX_SAFE_INTEGER,c=Hs(i),u=r.current.strictStreamingOrder??!1,d=l.useRef({prev:!1,next:!1}),m=Pn(),h=l.useRef({initialized:!1,apiInitialized:!1,instance:null}),{initialized:f,loading:g,refreshing:p,messages:v,newMessages:E,updateMessages:_,updateNewMessages:A,deleteNewMessages:y,deleteMessages:T,updateInitialized:I,updateLoading:N,updateRefreshing:O}=Ud(n==null?void 0:n.sortComparator),k=ce(M=>{var x,L,P,X;if(!s.current||!s.current.url)return(x=o==null?void 0:o.error)==null?void 0:x.call(o,"[useGroupChannelMessages] channel is required");try{switch(M){case Ee.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case Ee.CollectionEventSource.EVENT_MESSAGE_SENT_SUCCESS:case Ee.CollectionEventSource.SYNC_MESSAGE_FILL:case void 0:(P=(L=r.current).markAsRead)==null||P.call(L,[s.current]);break}}catch(oe){(X=o==null?void 0:o.warn)==null||X.call(o,"[useGroupChannelMessages/markAsReadBySource]",oe)}}),R=ce((M,x)=>{var L,P,X,oe,Z;if(x.length>0)switch(M){case Ee.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case Ee.CollectionEventSource.SYNC_MESSAGE_FILL:{(P=(L=r.current).shouldCountNewMessages)!=null&&P.call(L)&&A(x,!1,(X=e.currentUser)==null?void 0:X.userId),(Z=(oe=r.current).onMessagesReceived)==null||Z.call(oe,x);break}}}),F=ce(M=>{var x,L;(L=(x=r.current).onCollectionEvent)==null||L.call(x,M)}),D=ce(async(M,x,L)=>new Promise((P,X)=>{var Ye,rt,an;h.current.instance&&h.current.instance.dispose(),k(),A([],!0,(Ye=e.currentUser)==null?void 0:Ye.userId);const oe=()=>{var ge,pe;const{pendingMessages:le,failedMessages:fe}=h.current.instance??{};Fs(le)&&_(le,!1,(ge=e.currentUser)==null?void 0:ge.userId),Fs(fe)&&_(fe,!1,(pe=e.currentUser)==null?void 0:pe.userId)},Z=Hd(M,L,{...r.current,startingPoint:x});h.current={apiInitialized:!1,initialized:!1,instance:Z},Z.setMessageCollectionHandler({onMessagesAdded:(le,fe,ge)=>{var pe;k(le.source),R(le.source,ge),_(ge,!1,(pe=e.currentUser)==null?void 0:pe.userId,u),F({kind:"messagesAdded",source:le.source,channelUrl:M.url,messages:ge})},onMessagesUpdated:(le,fe,ge)=>{var pe,De,$e;k(le.source),R(le.source,ge),_(ge,!1,(pe=e.currentUser)==null?void 0:pe.userId,u),le.source===Ee.CollectionEventSource.EVENT_MESSAGE_UPDATED&&(($e=(De=r.current).onMessagesUpdated)==null||$e.call(De,ge)),F({kind:"messagesUpdated",source:le.source,channelUrl:M.url,messages:ge})},onMessagesDeleted:(le,fe,ge,pe)=>{const De=pe.map(ve=>ve.messageId),$e=pe.filter(ze).map(ve=>ve.reqId);T(De,$e),y(De,$e),F({kind:"messagesDeleted",source:le.source,channelUrl:M.url,messages:pe})},onChannelDeleted:(le,fe)=>{var ge,pe;(pe=(ge=r.current).onChannelDeleted)==null||pe.call(ge,fe)},onChannelUpdated:(le,fe)=>{var ge,pe;m(),(pe=(ge=r.current).onChannelUpdated)==null||pe.call(ge,fe,le)},onHugeGapDetected:()=>{D(M,Number.MAX_SAFE_INTEGER,xn.collection.message.defaultLimit)}});let Ce=!1;(an=(rt=r.current).onCollectionInitializeStart)==null||an.call(rt),Z.initialize(Ze.MessageCollectionInitPolicy.CACHE_AND_REPLACE_BY_API).onCacheResult((le,fe)=>{var ge,pe,De,$e,ve;(pe=(ge=r.current).onCacheResult)==null||pe.call(ge,le,fe??[],M.url),le?(e.isCacheEnabled&&((De=o==null?void 0:o.error)==null||De.call(o,"[useGroupChannelMessages/onCacheResult]",le)),Ce=!0):fe&&(($e=o==null?void 0:o.debug)==null||$e.call(o,"[useGroupChannelMessages/onCacheResult]","message length:",fe.length),_(Z.succeededMessages,!0,(ve=e.currentUser)==null?void 0:ve.userId),oe(),fe.length>0&&(h.current.initialized=!0,P())),F({kind:"initialized",source:"cache",channelUrl:M.url,messages:fe??[],error:le})}).onApiResult((le,fe)=>{var ge,pe,De,$e,ve,je,Be;(pe=(ge=r.current).onApiResult)==null||pe.call(ge,le,fe??[],M.url),h.current.initialized=!0,h.current.apiInitialized=!0,le?((De=o==null?void 0:o.warn)==null||De.call(o,"[useGroupChannelMessages/onApiResult]",le),Ce?X(le):P()):fe&&(($e=o==null?void 0:o.debug)==null||$e.call(o,"[useGroupChannelMessages/onApiResult]","message length:",fe.length),_(Z.succeededMessages,!0,(ve=e.currentUser)==null?void 0:ve.userId),r.current.startingPoint||(Be=(je=r.current).onMessagesReceived)==null||Be.call(je,fe),e.isCacheEnabled&&oe(),P()),F({kind:"initialized",source:"api",channelUrl:M.url,messages:fe??[],error:le})})}));_t(e,{onUserBanned(M,x){var L,P,X;M.isGroupChannel()&&!Od(M,s.current)&&(x.userId===((L=e.currentUser)==null?void 0:L.userId)?(X=(P=r.current).onCurrentUserBanned)==null||X.call(P):m())}}),l.useLayoutEffect(()=>{const M=setTimeout(async()=>{e.currentUser&&s.current&&(I(!1),N(!0),await D(s.current,i,c),N(!1),I(!0))});return()=>clearTimeout(M)},[e,(Te=e.currentUser)==null?void 0:Te.userId,($=s.current)==null?void 0:$.url,r.current.replyType]),l.useEffect(()=>()=>{h.current.instance&&h.current.instance.dispose()},[]);const Q=ce(async()=>{e.currentUser&&s.current&&(O(!0),await D(s.current,Number.MAX_SAFE_INTEGER,xn.collection.message.defaultLimit),O(!1))}),re=ce(async()=>{var x;const M=h.current.instance;if(M!=null&&M.hasPrevious&&!d.current.prev)try{d.current.prev=!0;const L=await M.loadPrevious();_(L,!1,(x=e.currentUser)==null?void 0:x.userId)}catch{}finally{d.current.prev=!1}}),G=ce(()=>{const{initialized:M,instance:x}=h.current;return M&&x?x.hasPrevious:!1}),H=ce(async()=>{var x;const M=h.current.instance;if(M!=null&&M.hasNext&&!d.current.next)try{d.current.next=!0;const L=await M.loadNext();_(L,!1,(x=e.currentUser)==null?void 0:x.userId)}catch{}finally{d.current.next=!1}}),K=ce(()=>{const{initialized:M,apiInitialized:x,instance:L}=h.current;return x&&M&&L?L.hasNext:!1}),J=M=>{var x,L,P,X;!M||M.channelUrl!==((x=s.current)==null?void 0:x.url)||(_([M],!1,(L=e.currentUser)==null?void 0:L.userId),(X=(P=r.current).onOutgoingMessageStatusChanged)==null||X.call(P,M))},q=ce((M,x)=>{var L;if(!s.current||!s.current.url)throw(L=o==null?void 0:o.error)==null||L.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((P,X)=>{s.current.sendUserMessage(M).onPending(oe=>{J(oe),x==null||x(oe)}).onSucceeded(oe=>{J(oe),P(oe)}).onFailed((oe,Z)=>{J(Z),X(oe)})})}),z=ce((M,x)=>{var L;if(!s.current||!s.current.url)throw(L=o==null?void 0:o.error)==null||L.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((P,X)=>{s.current.sendFileMessage(M).onPending(oe=>{J(oe),x==null||x(oe)}).onSucceeded(oe=>{J(oe),P(oe)}).onFailed((oe,Z)=>{J(Z),X(oe)})})}),W=ce((M,x,L)=>{var P;if(!s.current||!s.current.url)throw(P=o==null?void 0:o.error)==null||P.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((X,oe)=>{s.current.sendMultipleFilesMessage(M).onPending(Z=>{J(Z),x==null||x(Z)}).onFileUploaded(Z=>{L==null||L(Z),m()}).onSucceeded(Z=>{J(Z),X(Z)}).onFailed((Z,Ce)=>{J(Ce),oe(Z)})})}),Y=ce(async(M,x)=>{var P,X;if(!s.current||!s.current.url)throw(P=o==null?void 0:o.error)==null||P.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");const L=await s.current.updateUserMessage(M,x);return L.channelUrl===s.current.url&&_([L],!1,(X=e.currentUser)==null?void 0:X.userId),L}),V=ce(async(M,x)=>{var P,X;if(!s.current||!s.current.url)throw(P=o==null?void 0:o.error)==null||P.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");const L=await s.current.updateFileMessage(M,x);return L.channelUrl===s.current.url&&_([L],!1,(X=e.currentUser)==null?void 0:X.userId),L}),te=ce(async(M,x,L)=>{var P;if(!s.current||!s.current.url)throw(P=o==null?void 0:o.error)==null||P.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((X,oe)=>{let Z;M.isUserMessage()&&(Z=s.current.resendMessage(M)),M.isFileMessage()&&(Z=s.current.resendMessage(M)),M.isMultipleFilesMessage()&&(Z=s.current.resendMessage(M)),Z&&("onPending"in Z&&Z.onPending(Ce=>{J(Ce),x==null||x(Ce)}),"onFileUploaded"in Z&&Z.onFileUploaded(Ce=>{L==null||L(Ce),m()}),"onSucceeded"in Z&&Z.onSucceeded(Ce=>{J(Ce),X(Ce)}),"onFailed"in Z&&Z.onFailed((Ce,Ye)=>{J(Ye),oe(Ce)}))})}),w=ce(async M=>{var x,L,P,X;if(!s.current||!s.current.url)throw(x=o==null?void 0:o.error)==null||x.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");if(M.sendingStatus==="succeeded")M.isUserMessage()&&await s.current.deleteMessage(M),M.isFileMessage()&&await s.current.deleteMessage(M),M.isMultipleFilesMessage()&&await s.current.deleteMessage(M);else try{await((L=h.current.instance)==null?void 0:L.removeFailedMessage(M.reqId))}finally{T([],[M.reqId]),(X=(P=r.current).onLocalMessageDeleted)==null||X.call(P,M)}}),_e=ce(()=>{var M;A([],!0,(M=e.currentUser)==null?void 0:M.userId)}),Re=ce(async M=>{var x;if(e.currentUser&&s.current){const L=Hs(M);N(!0),_([],!0,(x=e.currentUser)==null?void 0:x.userId),await D(s.current,M,L),N(!1)}});return{initialized:f,loading:g,refreshing:p,messages:v,newMessages:E,resetNewMessages:_e,refresh:Q,loadPrevious:re,hasPrevious:G,loadNext:H,hasNext:K,sendUserMessage:q,sendFileMessage:z,sendMultipleFilesMessage:W,updateUserMessage:Y,updateFileMessage:V,resendMessage:te,deleteMessage:w,resetWithStartingPoint:Re,_dangerous_reducer_updateMessages:_,_dangerous_reducer_deleteMessages:T}},zd=e=>e.customType==="SENDBIRD_DESK_ADMIN_MESSAGE_CUSTOM_TYPE"?!0:e.isAdminMessage()?e.message==="The channel's custom_type was updated.":!1,Vd=(e,t,n)=>{const r=Gd(e,t,{...n,strictStreamingOrder:!0}),s=l.useMemo(()=>r.messages.filter(o=>!zd(o)),[r.messages]);return{...r,messages:s}},Kd=()=>{const e=new Set;return{publish:t=>{e.size!==0&&[...e].forEach(n=>{n(t)})},subscribe:t=>{let n=!0;return e.add(t),()=>{n&&(n=!1,e.delete(t))}}}},ki=Kd(),qd=({channelUrl:e,enabled:t=!0,statsTracker:n})=>{const r=l.useRef(e),s=l.useRef(t),o=l.useRef(null),i=l.useRef(!1);s.current=t;const c=l.useCallback(p=>r.current===p,[]),u=l.useCallback(()=>{i.current&&(n.clearChannel(r.current),i.current=!1)},[n]),d=l.useCallback(p=>{c(p)&&s.current&&(i.current=!0)},[c]),m=l.useCallback(({channelUrl:p,conversationId:v})=>{i.current=!0,n.markChannelJoined(v,p)},[n]),h=l.useCallback(({channelUrl:p})=>{n.clearChannel(p),i.current=!1},[n]),f=l.useCallback(p=>{if(c(p.channelUrl)){if(!s.current){o.current=p;return}o.current=null,m(p)}},[c,m]),g=l.useCallback(p=>{if(c(p.channelUrl)){if(!s.current){o.current=p;return}o.current=null,h(p)}},[c,h]);return l.useEffect(()=>{if(t){const p=o.current;if(!p||(o.current=null,p.channelUrl!==e))return;"error"in p?h(p):m(p);return}u()},[e,u,t,h,m]),l.useEffect(()=>(r.current=e,o.current=null,i.current=!1,()=>{u(),o.current=null,i.current=!1}),[e,u]),{onFetchStart:d,onFetchSuccess:f,onFetchError:g}},Wd=({channelUrl:e,enabled:t=!0,scheduleForegroundTask:n,statsTracker:r})=>{const s=l.useRef(e),o=l.useRef(null),i=l.useRef(t),c=l.useRef(0),u=l.useRef(null);i.current=t;const d=l.useCallback((h=!0)=>{var g;(g=o.current)==null||g.call(o),o.current=null;const f=u.current;h&&(u.current=null),h&&f&&r.clearChannel(f)},[r]),m=l.useCallback(h=>{if(!i.current){d(),r.clearChannel(h);return}d(!1),u.current=h;const f=c.current,g=()=>{if(!i.current||f!==c.current||s.current!==h){r.clearChannel(h),u.current===h&&(u.current=null);return}r.start("ws_reconnected",h)};o.current=(n==null?void 0:n(g))??null,n||g()},[d,n,r]);return l.useEffect(()=>{t||d()},[d,t]),l.useEffect(()=>(s.current=e,c.current+=1,()=>{c.current+=1,d()}),[e,d]),{onReconnectSucceeded:m}},Wt={DEFAULT_PRIMARY:"#000000",DEFAULT_BOT_MSG_BG:"#ECECEC",WHITE:"#ffffff",BLACK:"#000000"};function Li(e){return e.length===4?`#${[...e.slice(1)].map(t=>t+t).join("")}`:e}function Yd(e){const t=Li(e);return[parseInt(t.slice(1,3),16),parseInt(t.slice(3,5),16),parseInt(t.slice(5,7),16)]}function jd(e){return`#${e.map(t=>t.toString(16).padStart(2,"0")).join("")}`}function Xd(e,t,n){e/=255,t/=255,n/=255;const r=Math.max(e,t,n),s=Math.min(e,t,n),o=r-s;let i=0,c=0;const u=(r+s)/2;return r!==s&&(c=u>.5?o/(2-r-s):o/(r+s)),r===e?i=(t-n)/o+(t<n?6:0):r===t?i=(n-e)/o+2:r===n&&(i=(e-t)/o+4),i/=6,[i,c,u]}function Zd(e,t,n){let r,s,o;if(t===0)r=s=o=n;else{const i=function(m,h,f){return f<0&&(f+=1),f>1&&(f-=1),f<.16666666666666666?m+(h-m)*6*f:f<.5?h:f<.6666666666666666?m+(h-m)*(.6666666666666666-f)*6:m},c=n<.5?n*(1+t):n+t-n*t,u=2*n-c;r=i(u,c,e+1/3),s=i(u,c,e),o=i(u,c,e-1/3)}return[Math.round(r*255),Math.round(s*255),Math.round(o*255)]}function dn(e,t,n){const[r,s,o]=Yd(e),[i,c,u]=Xd(r,s,o),d=Math.max(0,Math.min(1,u*t)),m=Math.max(0,Math.min(1,c*n)),[h,f,g]=Zd(i,m,d);return jd([Math.round(h),Math.round(f),Math.round(g)])}function Jd(e,t="light"){return{extraDark:dn(e,.6,1.2),dark:dn(e,.85,1.1),main:e,light:dn(e,t==="dark"?1.1:1.5,t==="dark"?.95:.9),extraLight:dn(e,t==="dark"?1.2:1.75,t==="dark"?.9:.8)}}function Ar(e){const t=Li(e),n=149,r=+`0x${t[1]}${t[2]}`,s=+`0x${t[3]}${t[4]}`,o=+`0x${t[5]}${t[6]}`;return r*.299+s*.587+o*.114>n?Wt.BLACK:Wt.WHITE}function Qd(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},conversation:{headerProfileSkeleton:e.background100},memoryDialog:{titleText:e.onlight.textHighEmphasis,markdownBodyText:e.onlight.textLowEmphasis,markdownLinkText:e.onlight.textHighEmphasis,positiveBackground:e.onlight.textHighEmphasis,positiveText:e.ondark.textHighEmphasis,positiveBorderColor:"transparent",negativeBackground:"transparent",negativeText:e.onlight.textHighEmphasis,negativeBorderColor:"transparent"}}}const em=(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},conversation:{headerProfileSkeleton:e.background400},memoryDialog:{titleText:e.ondark.textHighEmphasis,markdownBodyText:e.ondark.textLowEmphasis,markdownLinkText:e.ondark.textHighEmphasis,positiveBackground:e.ondark.textHighEmphasis,positiveText:e.onlight.textHighEmphasis,positiveBorderColor:"transparent",negativeBackground:"transparent",negativeText:e.ondark.textHighEmphasis,negativeBorderColor:"transparent"}}),mn={primary:{extraDark:"#491389",dark:"#6211c8",main:"#742ddd",light:"#c2a9fa",extraLight:"#dbd1ff"},secondary:{extraDark:"#066858",dark:"#027d69",main:"#259c72",light:"#69c085",extraLight:"#a8e2ab"},error:{extraDark:"#9d091e",dark:"#bf0711",main:"#de360b",light:"#f66161",extraLight:"#fdaaaa"},information:{extraDark:"#241389",dark:"#362ca9",main:"#4a48cd",light:"#a9bbfa",extraLight:"#d1dbff"},background700:"#000000",background600:"#161616",background500:"#2c2c2c",background400:"#393939",background300:"#bdbdbd",background200:"#e0e0e0",background100:"#eeeeee",background50:"#ffffff",onlight:{textHighEmphasis:"rgba(0, 0, 0, 1)",textMidEmphasis:"rgba(0, 0, 0, 0.75)",textLowEmphasis:"rgba(0, 0, 0, 0.55)",textDisabled:"rgba(0, 0, 0, 0.12)"},ondark:{textHighEmphasis:"rgba(255, 255, 255, 1)",textMidEmphasis:"rgba(255, 255, 255, 0.75)",textLowEmphasis:"rgba(255, 255, 255, 0.58)",textDisabled:"rgba(255, 255, 255, 0.12)"},overlay:{dark:"rgba(0, 0, 0, 0.55)",light:"rgba(22, 22, 22, 0.32)"}},tr={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 Gs(e){const t=tm(e),n=nm(e,t),r=sm(n,e.colors,e.selectedTheme),s=im(e);return{selectedTheme:e.selectedTheme,palette:t,colors:r,aiAgentColorVariables:{primary_color:r.base.primary,primary_contrast_color:r.base.primaryContrastContent,bot_message_bg_color:r.messageIncoming.background,bot_message_bg_contrast_color:r.messageIncoming.text},typography:s}}function tm({selectedTheme:e,palette:t,primary:n}){const r=t!=null&&t.primary?t.primary:n?n===mn.primary.main?mn.primary:Jd(n,e):mn.primary;return{...mn,primary:r,...t}}function nm({selectedTheme:e,primaryContrast:t,botMessageBackground:n,botMessageBackgroundContrast:r},s){const o=s.primary.main,i=t??Ar(o),c=n??Wt.DEFAULT_BOT_MSG_BG,u=r??Ar(c);return(e==="light"?Qd:em)(s,o,i,c,u)}function rm(e,t,n){return typeof e=="string"?e:e[t]??n}function sm(e,t,n){var i;if(!t||Object.keys(t).length===0)return e;const r={...e},s=r,o=e;for(const c of Object.keys(t)){const u=t[c];if(u){s[c]={...s[c]};for(const[d,m]of Object.entries(u))if(m!==void 0){const h=((i=o[c])==null?void 0:i[d])??"";s[c][d]=rm(m,n,h)}}}return r}function om(e,t,n){const r={...e};return n.forEach(s=>{const o=t[s];o!=null&&(r[s]=o)}),r}function im({typography:e}){if(!e)return tr;const t={...tr};return Object.keys(e).forEach(n=>{const r=e[n];if(r&&typeof r=="object"){const s=tr[n],o=["fontSize","fontWeight","fontFamily","lineHeight"];t[n]=om(s,r,o)}}),t}const{Provider:am,useContext:Fn}=be("AIAgentTheme");function cm({logger:e,palette:t,typography:n,colors:r,appearance:s,children:o}){const i=l.useRef(null),[c,u]=l.useState(()=>Gs({selectedTheme:(s==null?void 0:s.theme)??"light",palette:t,typography:n,colors:r,primary:s==null?void 0:s.primaryColor,botMessageBackground:s==null?void 0:s.botMessageBackgroundColor})),d=l.useCallback((m,h)=>{h&&(i.current=h);const f=(s==null?void 0:s.theme)??m,g=i.current?i.current.themes[f]:null,p={primary:s==null?void 0:s.primaryColor,primaryContrast:void 0,botMessageBackground:s==null?void 0:s.botMessageBackgroundColor,botMessageBackgroundContrast:void 0};!p.primary&&(g!=null&&g.primary_color)&&(p.primary=g.primary_color,p.primaryContrast=g.primary_contrast_color),!p.botMessageBackground&&(g!=null&&g.bot_message_bg_color)&&(p.botMessageBackground=g.bot_message_bg_color,p.botMessageBackgroundContrast=g.bot_message_bg_contrast_color);const v=Gs({selectedTheme:f,palette:t,typography:n,colors:r,...p});u(v),e==null||e.info("theme.update:",f)},[s==null?void 0:s.theme,s==null?void 0:s.primaryColor,s==null?void 0:s.botMessageBackgroundColor,t,n,r,e]);return l.useEffect(()=>{(s!=null&&s.theme||s!=null&&s.primaryColor||s!=null&&s.botMessageBackgroundColor)&&d(c.selectedTheme)},[s==null?void 0:s.theme,s==null?void 0:s.primaryColor,s==null?void 0:s.botMessageBackgroundColor]),a.createElement(am,{value:{theme:c,updateTheme:d}},o)}const nr=25*1024*1024,zs=1,Vs=new Set(["image/png","image/jpeg","image/jpg"]),Ks=new Set(["application/pdf"]),lm={off:"off",always:"always",handed_off_only:"handed_off_only"},um=()=>{const[e,t]=l.useState(()=>({maxAttachmentCount:zs,attachmentMode:"handed_off_only",defaultUploadSizeLimit:nr,uploadSizeLimitPerType:new Map,supportedImageMimeTypes:Vs,supportedFileMimeTypes:Ks})),n=l.useCallback(({active_channel:s,upload_restriction:o})=>{t({maxAttachmentCount:(o==null?void 0:o.max_attachment_count)??zs,attachmentMode:lm[s.attachment_mode]??"handed_off_only",defaultUploadSizeLimit:(o==null?void 0:o.default_upload_size_limit)??nr,uploadSizeLimitPerType:new Map(Object.entries((o==null?void 0:o.upload_size_limit_per_type)??[])),supportedImageMimeTypes:new Set((o==null?void 0:o.supported_image_mime_types)??Vs),supportedFileMimeTypes:new Set((o==null?void 0:o.supported_file_mime_types)??Ks)})},[]),r=l.useCallback(s=>{const{channel:o,uploadSizeLimit:i=nr}=s,c=(d=!0)=>o!=null&&o.isAIAgent?d?at(o):!1:!0,u=d=>{if(c())return e.defaultUploadSizeLimit??i;const m=e.defaultUploadSizeLimit??i,h=e.uploadSizeLimitPerType.get(d)??m;return Math.min(m,h)};return{maxAttachmentCount:e.maxAttachmentCount,isEnabled:()=>{if(c(!1))return!0;switch(e.attachmentMode){case"off":return!1;case"always":return!0;case"handed_off_only":return at(o);default:return!0}},get supportedMimeTypes(){return c()?[_r]:[...e.supportedImageMimeTypes,...e.supportedFileMimeTypes]},isSupportedMimeType:d=>c()?!0:e.supportedImageMimeTypes.has(d)||e.supportedFileMimeTypes.has(d),getUploadSizeLimit:u,getUploadSizeLimitInMB:d=>u(d)/(1024*1024)}},[e]);return{updateBaseAttachmentRules:n,createAttachmentRules:r}},qs=(...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:dm,useContext:ft}=be("AIAgentMessengerSession"),mm=l.forwardRef(function({userSessionInfo:e,children:t},n){const{_aiAgentSDK:r,chatSDK:s,aiAgentId:o,logger:i}=ye(),{updateTheme:c}=Fn(),[u,d]=l.useState(void 0),[m,h]=l.useState(void 0),[f,g]=l.useState(null),[p,v]=l.useState(null),[E,_]=l.useState(null),[A,y]=l.useState(null),[T,I]=l.useState(null),{updateBaseAttachmentRules:N,createAttachmentRules:O}=um();l.useEffect(()=>{const D=r.onMessengerSettingsUpdated(({settings:G})=>{const{appearance:H,bot:K,launcher:J,memory:q}=G;c(H.selected_theme,H),_(Bu(K)),y(Hu(J)),I(q?yr(q):null),N(G)}),Q=r.onActiveChannelUpdated(({channelUrl:G,status:H,conversationStatus:K})=>{h({url:G,status:H,conversationStatus:K})}),re=r.onAuthTokenRefreshed(()=>{var H;const G=(H=r.session)==null?void 0:H.userSession.authToken;G&&v(K=>K?{...K,authToken:G}:null)});return()=>{D(),Q(),re()}},[r,c,N]);const k=l.useCallback(async()=>{try{const D=await r.authenticate(e),Q=r.session;return g(Q.sdkUser),v(Q.userSession),h(Q.activeChannel),d(void 0),D}catch(D){throw g(null),v(null),h(void 0),d(D),D}},[r,e]),R=l.useCallback(async()=>{await r.deauthenticate(),g(null),h(void 0),v(null),_(null),y(null),I(null)},[r]),F=l.useCallback(async()=>{if(!r.session){if(p)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!==(p==null?void 0:p.userId)?(i.debug("agentMessengerSession.refreshActiveChannel: stale call from previous session, skipping"),r.session.activeChannel.url):(h(void 0),await r.refreshActiveChannel())},[r,i,p]);return l.useImperativeHandle(n,()=>{const D=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:R,submitCPAAuthorizationCodes:r.submitCPAAuthorizationCodes,updateContext:async(...Q)=>{const re=qs(...Q);if(re.type==="active"){const K=await(await D()).updateContext(o,re.context);return Ft(K)}const G=await s.aiAgent.updateContext(re.aiAgentId,re.channelUrl,re.context);return Ft(G)},patchContext:async(...Q)=>{const re=qs(...Q);if(re.type==="active"){const K=await(await D()).patchContext(o,re.context);return Ft(K)}const G=await s.aiAgent.patchContext(re.aiAgentId,re.channelUrl,re.context);return Ft(G)},getContextObject:async()=>{const re=await(await D()).getContextObject(o);return Ft(re)},requestNudgeMessage:Q=>r.requestNudgeMessage(Q)}},[k,R,m,s,o,i,r]),a.createElement(dm,{value:{sdkUser:f,userSessionInfo:e,userSession:p,activeChannel:m,setActiveChannel:h,refreshActiveChannel:F,createConversation:r.createConversation,searchConversation:r.searchConversation,submitCPAAuthorizationCodes:r.submitCPAAuthorizationCodes,connectionError:u,aiAgentInfo:E,launcherInfo:A,memoryInfo:T,authenticate:k,deauthenticate:R,createAttachmentRules:O}},t)}),hm={ai_responding:"not_ready",conversation_closed:"ready",form_active:"ready",handoff_pending:"ready",reconnecting:"not_ready",steward:"ready",suggested_replies:"ready",system:"ready",unavailable:"not_ready"},fm=e=>e.disabled?hm[e.disabledBy]==="ready":!0,gm=e=>{var n,r,s,o,i;if(e.isUserMessage())return"text";const t=e.isFileMessage()?e.type:((r=(n=e.fileInfoList)==null?void 0:n[0])==null?void 0:r.mimeType)??((i=(o=(s=e.messageParams)==null?void 0:s.fileInfoList)==null?void 0:o[0])==null?void 0:i.mimeType);return t&&Ke(t)?"file_image":t&&Zt(t)?"file_video":t&&qc(t)?"file_audio":"file_document"};let Ws=0;const pm=e=>(Ws+=1,`${e??"unknown"}:${Ws}`),Tt=(e,t)=>e===void 0||t===e,Oi=(e,t)=>{!t.error&&t.messages.length>0&&e.conversationNotInteractiveTimeout.markHistoryLoaded("success",t.channelUrl)},Ni=(e,t)=>{t.error?e.conversationNotInteractiveTimeout.markHistoryLoaded("failed",t.channelUrl):e.conversationNotInteractiveTimeout.markHistoryLoaded(t.messages.length>0?"success":"verified_empty",t.channelUrl)},_m=(e,t)=>{Oi(e,t)},Em=(e,t)=>{Ni(e,t)},Cm=(e,t,n)=>{var o;if(!et(e,n))return;const{hasResponseMetadata:r,...s}=ii(e.data);r&&(t.typingIndicatorAbsentTimeout.markAIResponseStarted({channelUrl:e.channelUrl,userMessageId:s.userMessageId}),t.userPerceivedResponseTime.markAIResponseRaw({messageId:e.messageId,channelUrl:e.channelUrl,aiResponse:s}),t.streamStalled.markRawProgress({messageId:e.messageId,channelUrl:e.channelUrl,textLength:((o=e.message)==null?void 0:o.length)??0,aiResponse:s}))},Ys=(e,t)=>{t.streamStalled.clearMessage(e.messageId),t.userPerceivedResponseTime.clearMessage(e.messageId);const n=Qe(e)?e.reqId:void 0;n&&(t.messagePendingStuck.disappear({requestId:n}),t.userPerceivedResponseTime.cancelTurn(n),t.typingIndicatorAbsentTimeout.cancelTurn(n))},rr=(e,t)=>{t&&(e.conversationNotInteractiveTimeout.clearChannel(t),e.recoveryNotInteractiveTimeout.clearChannel(t),e.messagePendingStuck.clearChannel(t),e.userPerceivedResponseTime.clearChannel(t),e.typingIndicatorAbsentTimeout.clearChannel(t),e.streamStalled.clearChannel(t))},bm=({activeChannelUrl:e,statsTrackers:t})=>{const{chatSDK:n}=ye(),{aiAgentInfo:r}=ft(),s=l.useRef(!1),o=r==null?void 0:r.userId;_t(!!e&&!!o?n:void 0,{onTypingStatusUpdated(c){if(c.url!==e)return;const u=c.getTypingUsers().some(m=>m.userId===o),d=s.current;u&&!d?t.typingIndicatorAbsentTimeout.markTypingStarted(c.url):!u&&d&&t.typingIndicatorAbsentTimeout.markTypingEnded(c.url),s.current=u}}),l.useEffect(()=>{s.current=!1},[e,o])},vm=({enabled:e=!0,requestedChannelUrl:t,statsTrackers:n})=>{const r=l.useRef(void 0);l.useLayoutEffect(()=>{const s=r.current;if(!e){s&&(rr(n,s),r.current=void 0);return}s&&s!==t&&(rr(n,s),r.current=void 0),t&&s!==t&&(n.conversationNotInteractiveTimeout.start({channelUrl:t}),r.current=t)},[e,t,n]),l.useLayoutEffect(()=>()=>{const s=r.current;s&&(rr(n,s),r.current=void 0)},[n])},Sm=({aiAgentUserId:e,statsEnabled:t=!0,requestedChannelUrl:n,statsTrackers:r})=>{const s=l.useRef(null),o=l.useRef(null),i=l.useRef(!1),c=l.useRef(0),u=l.useRef(0),d=l.useRef(t),m=l.useMemo(()=>c.current+1,[n]);l.useLayoutEffect(()=>(i.current=!0,c.current=m,()=>{i.current=!1,c.current+=1}),[m]);const h=l.useCallback(g=>i.current&&c.current===g,[]);l.useLayoutEffect(()=>{u.current+=1,s.current=null,o.current=null},[n]),l.useLayoutEffect(()=>{const g=d.current;d.current=t,!(g||!t)&&(s.current&&(s.current.tracked=!1),o.current&&(o.current.tracked=!1))},[t]);const f=l.useCallback(g=>g.lifecycleGeneration===u.current&&Tt(n,g.channelUrl),[n]);return l.useEffect(()=>{if(!t)return;const g=s.current;g&&f(g)&&(g.tracked||(Oi(r,g),g.tracked=!0));const p=o.current;p&&f(p)&&(p.tracked||(Ni(r,p),p.tracked=!0))},[t,f,r]),l.useMemo(()=>({onCollectionEvent:g=>{if(h(m)&&Tt(n,g.channelUrl)){if(g.kind==="messagesDeleted"){g.messages.forEach(p=>Ys(p,r));return}t&&g.messages.forEach(p=>Cm(p,r,e))}},onCacheResult:(g,p,v)=>{if(!h(m)||!Tt(n,v))return;const E={error:g,messages:p,channelUrl:v,lifecycleGeneration:u.current,tracked:!1};s.current=E,t&&(_m(r,E),E.tracked=!0)},onApiResult:(g,p,v)=>{if(!h(m)||!Tt(n,v))return;const E={error:g,messages:p,channelUrl:v,lifecycleGeneration:u.current,tracked:!1};o.current=E,t&&(Em(r,E),E.tracked=!0)},onLocalMessageDeleted:g=>{h(m)&&Tt(n,g.channelUrl)&&Ys(g,r)}}),[e,m,t,h,n,r])},ym=({enabled:e=!0,channelUrl:t,initialized:n,inputReady:r,renderedSignal:s,statsTrackers:o})=>{const i=l.useRef(!1),c=l.useRef(0);l.useEffect(()=>{c.current+=1,i.current=!1},[t,e]),l.useEffect(()=>{e&&(o.recoveryNotInteractiveTimeout.setInputEnabled(r,t),r&&o.conversationNotInteractiveTimeout.markInputReady(t))},[t,e,r,o]),l.useEffect(()=>{if(!e||!n||i.current)return;const u=c.current,d=setTimeout(()=>{c.current===u&&(o.conversationNotInteractiveTimeout.markRendered(t),i.current=!0)});return()=>clearTimeout(d)},[t,e,n,s,o])},Am=({channelUrl:e,enabled:t=!0,statsTrackers:n})=>{const r=l.useRef(!1),s=l.useRef(e),o=l.useRef(t),i=l.useRef(0);return l.useLayoutEffect(()=>(r.current=!0,s.current=e,o.current=t,i.current+=1,()=>{r.current=!1,i.current+=1}),[e,t]),l.useCallback(async(c,u,d={})=>{if(!r.current||!o.current)return c(v=>u==null?void 0:u(v),()=>{});let m;const h=i.current,f=s.current,g=()=>r.current&&o.current&&i.current===h&&s.current===f,p=v=>g()&&Tt(f,v);try{const v=await c(E=>{if(!p(E.channelUrl)){u==null||u(E);return}m=E.reqId,n.messagePendingStuck.start({requestId:E.reqId,channelUrl:E.channelUrl,messageType:gm(E),tracksUploadProgress:d.tracksUploadProgress??!1}),u==null||u(E)},E=>{!g()||m!==E||n.messagePendingStuck.markUploadProgress(E)});return m&&(g()?n.messagePendingStuck.resolve({requestId:m}):n.messagePendingStuck.disappear({requestId:m})),v}catch(v){throw m&&(g()?n.messagePendingStuck.resolve({requestId:m}):n.messagePendingStuck.disappear({requestId:m})),v}},[n])},Tm=({channelUrl:e,enabled:t=!0,statsTrackers:n})=>{const r=l.useRef(!1),s=l.useRef(e),o=l.useRef(t),i=l.useRef(0);return l.useLayoutEffect(()=>(r.current=!0,s.current=e,o.current=t,i.current+=1,()=>{r.current=!1,i.current+=1}),[e,t]),l.useCallback(async c=>{if(!r.current||!o.current)return c(()=>{});const u=i.current,d=s.current,m=()=>r.current&&o.current&&i.current===u&&s.current===d;let h=pm(d);n.userPerceivedResponseTime.startTurn({requestId:h,channelUrl:d}),n.typingIndicatorAbsentTimeout.startTurn({requestId:h,channelUrl:d});try{const f=await c(g=>{m()&&(n.userPerceivedResponseTime.replaceTurnRequestId(h,g),n.typingIndicatorAbsentTimeout.replaceTurnRequestId(h,g),h=g)});return m()?(n.userPerceivedResponseTime.markUserMessageAck({requestId:h,messageId:f.messageId}),n.typingIndicatorAbsentTimeout.markUserMessageAck({requestId:h,messageId:f.messageId})):(n.userPerceivedResponseTime.cancelTurn(h),n.typingIndicatorAbsentTimeout.cancelTurn(h)),f}catch(f){throw n.userPerceivedResponseTime.cancelTurn(h),n.typingIndicatorAbsentTimeout.cancelTurn(h),f}},[e,n])},Im=({requestedChannelUrl:e,activeChannelUrl:t,statsEnabled:n=!0,statsTrackers:r})=>{const{aiAgentInfo:s}=ft();bm({activeChannelUrl:t,statsTrackers:r}),vm({enabled:n,requestedChannelUrl:e,statsTrackers:r});const o=Sm({aiAgentUserId:s==null?void 0:s.userId,statsEnabled:n,requestedChannelUrl:e,statsTrackers:r}),i=Am({channelUrl:t,enabled:n,statsTrackers:r}),c=Tm({channelUrl:t,enabled:n,statsTrackers:r});return l.useMemo(()=>({messageCallbacks:o,runWithPendingStuckStats:i,runWithUserTurnStats:c}),[o,i,c])},Nt=()=>ye()._aiAgentSDK.statsTrackers,xm=({enabled:e=!0,channelUrl:t}={})=>{const{conversationInitialRender:n}=Nt(),{watchBackgrounded:r}=ye()._aiAgentSDK,s=l.useRef(null);return l.useLayoutEffect(()=>{n.setVisible(e)},[e,n]),l.useLayoutEffect(()=>{if(!t)return;const o=n.startSpan(t);return s.current=o,()=>{o.cancel(),s.current===o&&(s.current=null)}},[t,n]),l.useMemo(()=>({onGetChannelStart:o=>{var i;(i=s.current)==null||i.onGetChannelStart(o)},onGetChannelComplete:({channelUrl:o,conversationId:i})=>{var c;(c=s.current)==null||c.onGetChannelComplete(o,i)},onGetChannelError:({channelUrl:o,error:i})=>{var c;(c=s.current)==null||c.onGetChannelError(o,i)},onCollectionInitializeStart:()=>{var o;(o=s.current)==null||o.onGetMessagesStart()},onCollectionCacheResult:(o,i)=>{var c;(c=s.current)==null||c.onGetMessagesCacheComplete(i,o)},onCollectionApiResult:(o,i)=>{const c=s.current;if(!c)return;c.onGetMessagesComplete(i,o);const u=r==null?void 0:r();Ie(()=>{u!=null&&u()?c.onRenderDiscarded():c.onRendered()})}}),[r])},Qt=(e,t)=>{const n=l.useId(),r=l.useRef(t);l.useLayoutEffect(()=>{r.current=t}),l.useLayoutEffect(()=>{const s=new Ee.ConnectionHandler({onDisconnected:o=>{var i,c;return(c=(i=r.current).onDisconnected)==null?void 0:c.call(i,o)},onConnected:o=>{var i,c;return(c=(i=r.current).onConnected)==null?void 0:c.call(i,o)},onReconnectStarted:()=>{var o,i;return(i=(o=r.current).onReconnectStarted)==null?void 0:i.call(o)},onReconnectSucceeded:()=>{var o,i;return(i=(o=r.current).onReconnectSucceeded)==null?void 0:i.call(o)},onReconnectFailed:()=>{var o,i;return(i=(o=r.current).onReconnectFailed)==null?void 0:i.call(o)},onConnectionLost:()=>{var o,i;return(i=(o=r.current).onConnectionLost)==null?void 0:i.call(o)},onConnectionDelayed:o=>{var i,c;return(c=(i=r.current).onConnectionDelayed)==null?void 0:c.call(i,o)}});return e.addConnectionHandler(n,s),()=>{e.removeConnectionHandler(n)}},[e,n])},js=()=>{const e=l.useRef(0);return{next:()=>(e.current+=1,e.current),current:()=>e.current,invalidate:()=>{e.current+=1},isCurrent:t=>t===e.current}};function Rm(e,t={}){const{shouldInitializeConversation:n=!0,initialUserMessage:r}=t,{chatSDK:s,logger:o,aiAgentId:i,_aiAgentSDK:c}=ye(),{sdkUser:u}=ft(),d=js(),m=js(),h=Pn(),[f,g]=l.useState(void 0),[p,v]=l.useState(void 0),[E,_]=l.useState(!1),A=ce(T=>{if(n&&T.isAIAgent&&!T.conversation){const I=m.next();_(!0),c.initConversationIfNeeded(T,{initialUserMessage:r}).finally(()=>{m.isCurrent(I)&&_(!1)})}});async function y(){var I,N,O,k,R,F;const T=d.next();if(!u){o.debug("useChannel.getChannel: no sdk user, skip fetching channel");return}if(o.debug("useChannel.getChannel: start"),g(void 0),v(void 0),m.invalidate(),_(!1),e){(I=t.onFetchStart)==null||I.call(t,e);try{o.debug("useChannel.getChannel: get channel",e);const D=await s.groupChannel.getChannel(e);if(!d.isCurrent(T))return;A(D),g(D),(O=t.onFetchSuccess)==null||O.call(t,{channelUrl:D.url,conversationId:(N=D.conversation)==null?void 0:N.id}),D.url===((k=c.session)==null?void 0:k.activeChannel.url)&&c.session._updateActiveChannel({url:D.url,status:Ne(D)?"closed":"open",conversationStatus:(R=D.conversation)==null?void 0:R.status}),o.debug("useChannel.getChannel: fetched channel",D)}catch(D){if(!d.isCurrent(T))return;(F=t.onFetchError)==null||F.call(t,{channelUrl:e,error:D}),D instanceof Ee.SendbirdError&&v(D),o.error("useChannel.getChannel: error",D)}}}return l.useEffect(()=>(y(),()=>{d.invalidate()}),[s,u,e,i]),l.useEffect(()=>{n&&f&&A(f)},[n]),Qt(s,{async onReconnectSucceeded(){var N;if(!f){p&&await y();return}const T=d.current(),I=await f.refresh();!d.isCurrent(T)||f.url!==e||((N=t.onReconnectSucceeded)==null||N.call(t,f.url),A(I),g(I))}}),_t(s,{onChannelChanged:T=>{T.isGroupChannel()&&T.url===e&&(o.debug("useChannel.onChannelChanged: channel changed",T.url),g(T),h())}}),{channel:f,channelFetchError:p,getChannel:y,isInitializingConversation:E}}const Mm=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)return;const s=Xt(n);switch(r){case"suggested_replies":return s.hasSuggestedReplies?r:void 0;case"steward":return s.hasSteward?r:void 0;case"system":return r;default:return}},wm=e=>{var o;const t=e==null?void 0:e.lastMessage;if(!t||!e)return!1;const n=t.extendedMessagePayload,r=Xt(n).hasActiveForm,s=e.isAIAgent&&!!((o=e.conversation)!=null&&o.handedOverAt);return r&&!s},km=()=>{const{chatSDK:e,networkStateAdapter:t}=ye(),[n,r]=l.useState(()=>t?t.isOnline()?"connected":"reconnecting":"connected");return Qt(e,{onConnected:()=>r("connected"),onDisconnected:()=>r("disconnected"),onReconnectStarted:()=>r("reconnecting"),onReconnectSucceeded:()=>r("connected"),onReconnectFailed:()=>r("disconnected"),onConnectionLost:()=>r("reconnecting")}),l.useEffect(()=>{if(t)return t.subscribe(s=>{if(!s){r("reconnecting");return}r(o=>o==="reconnecting"&&e.connectionState===Ee.ConnectionState.OPEN?"connected":o)})},[t,e]),n},Lm=3e4,Om=({shouldApply:e,lastMessage:t,isBlockedWhileAIResponding:n,currentUserId:r})=>{const[s,o]=l.useState(!1),i=l.useRef(null),c=t&&et(t,r)?t.createdAt:0;return l.useEffect(()=>{const u=()=>{i.current&&(clearTimeout(i.current),i.current=null),o(!1)},d=f=>{i.current&&clearTimeout(i.current),o(!0),i.current=setTimeout(()=>{o(!1),i.current=null},f)},m=Date.now()-c,h=Lm-m;return n||h<=0?u():d(h),()=>{i.current&&clearTimeout(i.current)}},[n,c]),s&&e},Di=e=>{const{chatSDK:t}=ye(),[n,r]=l.useState([]);return _t(t,{onTypingStatusUpdated(s){if(s.url===(e==null?void 0:e.url)){const o=s.getTypingUsers();r(o)}}}),n},Nm=({channel:e,lastMessage:t,aiAgentUserId:n,isStreamAnimating:r})=>{const[s,o]=l.useState(!1),i=Di(e);return l.useEffect(()=>{if(!t)return;const c=i.some(d=>d.userId===n),u=et(t,n)&&(we.isStreaming(t)||r);o(u||c)},[i,t,n,r]),s},Dm=({channel:e,messages:t,isStreamAnimating:n,isInitializingConversation:r})=>{const{aiAgentInfo:s,userSession:o}=ft(),i=km(),c=Nm({channel:e,lastMessage:Cr(t,[Le.SendingStatus.SUCCEEDED]),aiAgentUserId:(s==null?void 0:s.userId)??"",isStreamAnimating:n}),u=Om({shouldApply:!!(e!=null&&e.isAIAgent)&&!at(e),isBlockedWhileAIResponding:c,lastMessage:Cr(t,[Le.SendingStatus.PENDING,Le.SendingStatus.SUCCEEDED]),currentUserId:(o==null?void 0:o.userId)??""}),d=h=>h===""?{disabled:!1,disabledBy:"",focusPolicy:"auto"}:h==="ai_responding"?{disabled:!0,disabledBy:h,focusPolicy:"preserve"}:{disabled:!0,disabledBy:h,focusPolicy:"release"};if(!e||i==="disconnected")return d("unavailable");if(i==="reconnecting")return d("reconnecting");if(Ne(e))return d("conversation_closed");if(Rl(e))return d("handoff_pending");if(wm(e))return d("form_active");const m=Mm(e);return d(m||(c||u||r?"ai_responding":""))},$m=()=>{const[e,t]=l.useState(new Set),[n,r]=l.useState(new Map),s=l.useCallback(m=>{t(h=>{if(h.has(m))return h;const f=new Set(h);return f.add(m),f})},[]),o=l.useCallback(m=>{t(h=>{if(!h.has(m))return h;const f=new Set(h);return f.delete(m),f})},[]),i=l.useCallback((m,h)=>{r(f=>{const g=new Map(f);return g.set(m,h),g})},[]),c=l.useCallback(m=>{r(h=>{if(!h.has(m))return h;const f=new Map(h);return f.delete(m),f})},[]),u=l.useCallback(m=>n.has(m),[n]),d=n.values().next().value;return{isAnimating:e.size>0,start:s,stop:o,isHolding:u,heldTypingInfo:d,holdStart:i,holdStop:c}},{Provider:Pm}=be("AIAgentConversation");function Fm({children:e,channelUrl:t,onChannelDeleted:n,onMessagesReceived:r,onMessagesUpdated:s,onConversationStatusChanged:o,onConversationClosedViaDispatcher:i,onBeforeSendMessage:c,onAfterSendMessage:u=me,shouldMarkAsRead:d=!0,conversationStatsEnabled:m=!0,shouldInitializeConversation:h=!0,initialUserMessage:f,shouldCountNewMessages:g=()=>!1,sortComparator:p}){var $,M;const v=()=>d&&(R==null?void 0:R.markAsRead()),{_aiAgentSDK:E,chatSDK:_,logger:A,dispatcher:y}=ye(),T=Nt(),I={channelUrl:t,enabled:m},N=qd({...I,statsTracker:T.conversationNotInteractiveTimeout}),O=Wd({...I,scheduleForegroundTask:E.scheduleForegroundTask,statsTracker:T.recoveryNotInteractiveTimeout}),k=xm(I),{channel:R,channelFetchError:F,getChannel:D,isInitializingConversation:Q}=Rm(t,{shouldInitializeConversation:h,initialUserMessage:f,onFetchStart:x=>{N.onFetchStart(x),k.onGetChannelStart(x)},onFetchSuccess:x=>{N.onFetchSuccess(x),k.onGetChannelComplete(x)},onFetchError:x=>{N.onFetchError(x),k.onGetChannelError(x)},onReconnectSucceeded:O.onReconnectSucceeded}),re=R==null?void 0:R.url,G=Im({requestedChannelUrl:t,activeChannelUrl:re,statsEnabled:m,statsTrackers:T}),H=Vd(_,R,{replyType:Le.ReplyType.ONLY_REPLY_TO_CHANNEL,shouldCountNewMessages:g,logger:A,markAsRead:v,sortComparator:p,onChannelDeleted:n,onMessagesReceived:x=>r==null?void 0:r(x),onMessagesUpdated:x=>s==null?void 0:s(x),onCollectionInitializeStart:()=>{k.onCollectionInitializeStart()},onApiResult:(x,L,P)=>{k.onCollectionApiResult(x,P),G.messageCallbacks.onApiResult(x,L,P)},onCacheResult:(x,L,P)=>{k.onCollectionCacheResult(x,P),G.messageCallbacks.onCacheResult(x,L,P)},onCollectionEvent:x=>{G.messageCallbacks.onCollectionEvent(x),ki.publish(x)},onLocalMessageDeleted:x=>{G.messageCallbacks.onLocalMessageDeleted(x)},onOutgoingMessageStatusChanged:x=>{R&&E.liveMetricManager.track({type:"outgoingMessage",channel:R,message:x})}}),K=$m(),J=Dm({channel:R,messages:H.messages,isStreamAnimating:K.isAnimating,isInitializingConversation:Q});ym({enabled:m,channelUrl:re,initialized:H.initialized,inputReady:fm(J),renderedSignal:H.messages,statsTrackers:T}),l.useEffect(()=>{v()},[d,R]);const q=($=R==null?void 0:R.conversation)==null?void 0:$.status;l.useEffect(()=>{q&&(o==null||o(q))},[q,o]),l.useEffect(()=>{const x=async L=>{const P=typeof(L==null?void 0:L.channelUrl)=="string";R&&P&&L.channelUrl!==R.url||(A.debug("conversation.dispatcher: try to close conversation",R),R!=null&&R.conversation&&R.conversation.status===he.ConversationStatus.OPEN&&(await R.closeConversation(),i==null||i()))};return y.subscribe(Fe.ConversationClose,x),()=>{y.unsubscribe(Fe.ConversationClose,x)}},[y,R,A,(M=R==null?void 0:R.conversation)==null?void 0:M.status,i]);const z=ce(()=>H.loadPrevious()),W=ce(()=>H.loadNext()),Y=ce(async x=>{try{await H.deleteMessage(x)}finally{x.sendingStatus!=="succeeded"&&G.messageCallbacks.onLocalMessageDeleted(x)}}),V=ce(x=>x.isUserMessage()?G.runWithUserTurnStats(L=>G.runWithPendingStuckStats(P=>H.resendMessage(x,X=>{L(X.reqId),P(X)}),void 0)):G.runWithPendingStuckStats((L,P)=>H.resendMessage(x,L,P),void 0,{tracksUploadProgress:x.isMultipleFilesMessage()})),te=ce(()=>H.resetNewMessages()),w=ce(async x=>{var P;if(((P=R==null?void 0:R.conversation)==null?void 0:P.status)===he.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(x=await c(x));const L=await G.runWithUserTurnStats(X=>G.runWithPendingStuckStats(oe=>H.sendUserMessage(x,Z=>{X(Z.reqId),oe(Z)}),u));return u==null||u(L),L}),_e=ce(async x=>{var P;if(((P=R==null?void 0:R.conversation)==null?void 0:P.status)===he.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(x=await c(x));const L=await G.runWithPendingStuckStats(X=>H.sendFileMessage(x,X),u);return u==null||u(L),L}),Re=ce(async x=>{var P;if(((P=R==null?void 0:R.conversation)==null?void 0:P.status)===he.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(x=await c(x));const L=await G.runWithPendingStuckStats((X,oe)=>H.sendMultipleFilesMessage(x,X,oe),u,{tracksUploadProgress:!0});return u==null||u(L),L}),Te={_statsEnabled:m,conversation:(R==null?void 0:R.conversation)??void 0,actions:{setUserMemoryState:E.setUserMemoryState},channelSource:{channel:R,error:F,refetch:()=>D(),closeConversation:async()=>{Ne(R)||await(R==null?void 0:R.closeConversation())}},messageSource:{messages:H.messages,newMessages:H.newMessages,initialized:H.initialized,loadPrevious:z,loadNext:W,deleteMessage:Y,resendMessage:V,resetNewMessages:te,sendUserMessage:w,sendFileMessage:_e,sendMultipleFilesMessage:Re},state:{streamAnimation:K,input:J}};return a.createElement(Pm,{value:Te},e)}function Um(e,t,n){var _,A,y,T,I,N,O,k,R,F;const[r,s]=l.useState(!1),[o,i]=l.useState(null),[c,u]=l.useState([]),[d,m]=l.useState(null),h=l.useRef(!1),f=ce(()=>{var D;return(D=n==null?void 0:n.onListRequestStart)==null?void 0:D.call(n)}),g=ce(D=>{var Q;return(Q=n==null?void 0:n.onListRequestComplete)==null?void 0:Q.call(n,D)}),p=l.useCallback(async D=>{f();try{await D.loadMore(),g()}catch(Q){throw g(Q),Q}},[f,g]),v=l.useCallback(async()=>{if(!h.current&&e.currentUser){h.current=!0,s(!1),i(null),u([]);try{d==null||d.dispose();const D=new fi(e,t);D.setConversationListCollectionHandler({onChannelsAdded:()=>{u(D.channels)},onChannelsUpdated:()=>{u(D.channels)},onChannelsDeleted:()=>{u(D.channels)}}),await p(D),u(D.channels),m(D),i(null)}catch(D){m(null),i(D)}finally{s(!0),h.current=!1}}},[e,e.currentUser,(_=t.filter)==null?void 0:_.aiAgentChannelFilter,(y=(A=t.filter)==null?void 0:A.aiAgentConversationStatusFilter)==null?void 0:y.join(),(I=(T=t.filter)==null?void 0:T.aiAgentIds)==null?void 0:I.join(),(N=t.filter)==null?void 0:N.deskChannelFilter,(k=(O=t.filter)==null?void 0:O.pinnedChannelUrls)==null?void 0:k.join(),(R=t.filter)==null?void 0:R.copilotConversationOnly,(F=t.filter)==null?void 0:F.copilotSupportChannelUrl,t.limit,p]),E=l.useCallback(async()=>{if(d)try{await d.loadMore(),u(d.channels)}catch(D){i(D)}},[d]);return Qt(e,{onConnected:()=>v()}),l.useEffect(()=>{v()},[v]),l.useEffect(()=>()=>{h.current=!1,d==null||d.dispose()},[d]),{initialized:r,error:o,channels:c,loadMore:E}}const $i=e=>{var s;const{aiAgentId:t,queryParams:n}=ye(),r=(s=n==null?void 0:n.conversationListParams)==null?void 0:s.filter;return{aiAgentIds:[t],aiAgentConversationStatusFilter:[he.ConversationStatus.CLOSED,he.ConversationStatus.OPEN],...r,...e}},Bm=({enabled:e=!0}={})=>{const{conversationListInitialRender:t}=Nt(),{watchBackgrounded:n}=ye()._aiAgentSDK,r=l.useRef(null);return l.useLayoutEffect(()=>{t.setVisible(e)},[e,t]),l.useLayoutEffect(()=>{const s=t.startSpan();return r.current=s,()=>{s.cancel(),r.current===s&&(r.current=null)}},[t]),l.useMemo(()=>({onListRequestStart:()=>{var s;(s=r.current)==null||s.onListRequestStart()},onListRequestComplete:s=>{const o=r.current;if(!o||(o.onListRequestComplete(s),s))return;const i=n==null?void 0:n();Ie(()=>{i!=null&&i()?o.onRenderDiscarded():o.onRendered()})}}),[n])},{Provider:Hm}=be("AIAgentConversationList");function Gm({conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:n=!0,children:r}){var h;const{chatSDK:s,queryParams:o}=ye(),i=e??((h=o==null?void 0:o.conversationListParams)==null?void 0:h.limit),c=$i(t),u=Bm({enabled:n}),d=Um(s,{limit:i,filter:c},{onListRequestStart:()=>{u.onListRequestStart()},onListRequestComplete:f=>{u.onListRequestComplete(f)}}),m={listSource:{initialized:d.initialized,error:d.error??void 0,channels:d.channels,loadMore:()=>d.loadMore()}};return a.createElement(Hm,{value:m},r)}function zm(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:Vm,useContext:Km}=be("MessageTemplateFetching");function qm({children:e,internalVariables:t}){const n=l.useRef({}),r=l.useRef({}),[s,o]=l.useState({}),i=l.useCallback((d,m)=>{o(h=>({...h,[d]:{fetching:!1,error:!1,...h[d],...m}}))},[]),c=l.useCallback(async({onRequestTemplate:d,onGetCachedTemplate:m,templateKey:h,suspense:f=!1})=>{const g=m(h);if(g)return g;const p=r.current[h];if(p)return p;f||i(h,{fetching:!0});const v=d(h).catch(E=>{throw f||i(h,{error:!0}),E}).finally(()=>{f||i(h,{fetching:!1}),delete r.current[h]});return r.current[h]=v,v},[i]),u={internalVariables:t,fetchTemplate:c,suspend:(d,m)=>{if(n.current[d])return n.current[d];const h=zm(m());return n.current[d]=h,h},getIsFetching:d=>{var m;return((m=s[d])==null?void 0:m.fetching)??!1},getHasError:d=>{var m;return((m=s[d])==null?void 0:m.error)??!1}};return a.createElement(Vm,{value:u},e)}const Wm="remove_powered_by",es=(e,t)=>{var s,o;const{chatSDK:n}=ye(),{aiAgentInfo:r}=ft();if(e==="handoff-button"){const i=!!((s=t==null?void 0:t.conversation)!=null&&s.handoff);return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.showHandoffButton)&&i&&Gr(t)}if(e==="special-notice")return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.specialNoticeEnabled)&&!!(r!=null&&r.specialNotice);if(e==="powered-by"){const i=(o=n==null?void 0:n.appInfo)==null?void 0:o.applicationAttributes;return l.useMemo(()=>!(Array.isArray(i)&&i.includes(Wm)),[i])}throw new Error("Unsupported feature")},Ym={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"},jm={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}}},Xm={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}}},Zm={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}}},Jm={getValueOrDefault:e=>e.values??e.default_values??null,validate:(e,t,n)=>{const r=t;if(e.required&&(!r||r.length===0))return{isValid:!1,error:n.required};if(!r||r.length===0)return{isValid:!0};if(r.filter(i=>!e.options.includes(i)).length>0)return{isValid:!1,error:n.invalidSelection};const{rules:o}=e;if(o){if(o.min_select!==void 0&&r.length<o.min_select)return{isValid:!1,error:typeof n.minSelect=="function"?n.minSelect(o.min_select):n.minSelect};if(o.max_select!==void 0&&r.length>o.max_select)return{isValid:!1,error:typeof n.maxSelect=="function"?n.maxSelect(o.max_select):n.maxSelect}}return{isValid:!0}}},Qm={text:jm,number:Xm,"single-select":Zm,"multi-select":Jm},eh={getValueOrDefault:()=>null,validate:()=>({isValid:!1})};function Pi(e){return Qm[e.type]||eh}function Xs(e){return Pi(e).getValueOrDefault(e)}function th(e,t,n={}){const r={...Ym,...n};return Pi(e).validate(e,t,r)}const nh=(e,t={})=>{const{labels:n={},onSubmit:r,onCancel:s}=t,[o,i]=l.useState({}),[c,u]=l.useState(()=>{const v={};return e.fields.forEach(E=>{v[E.key]=Xs(E)}),v}),d=l.useMemo(()=>e.submitted_at?"submitted":e.canceled_at?"canceled":"draft",[e.submitted_at,e.canceled_at]);l.useEffect(()=>{if(d==="submitted"||d==="canceled"){const v={};let E=!1;e.fields.forEach(_=>{const A=Xs(_);JSON.stringify(c[_.key])!==JSON.stringify(A)&&(E=!0),v[_.key]=A}),E&&u(v)}},[d]);const m=(v,E)=>{u(_=>({..._,[v]:E})),i(_=>({..._,[v]:void 0}))},h=e.fields.map(v=>{var A,y,T;const E=c[v.key]??null,_={key:v.key,label:v.label,error:o[v.key],required:v.required};return v.type==="text"?{..._,type:"text",layout:v.layout,value:E,...v.placeholder&&{placeholder:v.placeholder},...((A=v.rules)==null?void 0:A.max_length)&&{maxLength:v.rules.max_length}}:v.type==="number"?{..._,type:"number",layout:v.layout,value:E,...v.placeholder&&{placeholder:v.placeholder},...((y=v.rules)==null?void 0:y.max)&&{max:v.rules.max}}:v.type==="single-select"?{..._,type:"single-select",layout:v.layout,value:E,options:v.options}:v.type==="multi-select"?{..._,type:"multi-select",layout:v.layout,value:E,options:v.options,...((T=v.rules)==null?void 0:T.max_select)&&{maxSelect:v.rules.max_select}}:{..._,type:"unknown",layout:"default",value:null}});return{state:d,fields:h,getField:v=>h.find(E=>E.key===v),updateFieldValue:m,submit:async()=>{const v={};let E=!1;for(const _ of e.fields){const A=c[_.key]??null,y=th(_,A,n);y.isValid||(v[_.key]=y.error,E=!0)}if(i(v),!E&&r){const _={};e.fields.forEach(A=>{_[A.key]=c[A.key]??null}),await r(_)}},cancel:async()=>{await(s==null?void 0:s())}}},rh=({isMessengerOpened:e,onConversationStarted:t})=>{const{_aiAgentSDK:n,aiAgentId:r,language:s,countryCode:o,context:i}=ye(),{createConversation:c,userSession:u}=ft(),[d,m]=l.useState(null),h=u==null?void 0:u.userId;l.useEffect(()=>{if(m(null),!(e||!h))return n.onNudgeMessageReceived(v=>m(E=>({seq:((E==null?void 0:E.seq)??0)+1,response:v})))},[n,e,h]);const f=()=>m(null),g=l.useRef(!1),p=async()=>{var E;if(!d||g.current)return;g.current=!0,m(null);const v=n.session;try{const _=await c({aiAgentId:r,language:s,country:o,context:i});if(n.session!==v)return;(E=n.session)==null||E._updateActiveChannel({url:_,status:"open"}),t({channelUrl:_,initialUserMessage:d.response.callbackUserMessage})}finally{g.current=!1}};return{nudgeMessage:e?null:(d==null?void 0:d.response)??null,nudgeMessageKey:(d==null?void 0:d.seq)??0,dismissNudgeMessage:f,startNudgeConversation:p}},sh=e=>{const{chatSDK:t,handlers:n,logger:r}=ye(),{aiAgentInfo:s}=ft(),o=l.useRef(new Set),i=l.useRef(new Set),c=(m,h)=>{if(!(n!=null&&n.onCustomEvent)||!(s!=null&&s.userId)||!et(m,s.userId))return;const f=m.messageId;if(we.isStreaming(m)){i.current.add(f);return}h==="updated"&&!i.current.has(f)||(r.debug("useCustomEventForMessageReceive: bot-message-received",m),n.onCustomEvent({type:"bot-message-received",data:{message:m}}),i.current.delete(f))},u=l.useCallback(m=>{if(n!=null&&n.onCustomEvent&&m.isAdminMessage()&&m.customType==="user_action_required"&&!o.current.has(m.messageId)){const h=ri(m.data);Array.isArray(h.history)&&h.history.length===0&&(r.debug("useCustomEventForMessageReceive: user_action_required",h),n.onCustomEvent({type:"user-action-requested",data:h}),o.current.add(m.messageId))}},[n,r]),d=(m,h,f)=>{m.url===e&&(c(h,f),u(h))};return _t(t,{onMessageReceived:(m,h)=>d(m,h,"received"),onMessageUpdated:(m,h)=>d(m,h,"updated")}),{checkForUserActionRequired:u}},oh=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},Fi=e=>{const{aiAgentInfo:t}=ft(),n=Di(e);if(Ne(e))return null;const r=n[0];if(!r)return null;const s=r.userId===(t==null?void 0:t.userId),o=s?oh(r.metaData):void 0;return{user:s?t:r,isBot:s,thinkingMessage:o}},ih=250,ah=(e,t)=>{var i;const[n,r]=l.useState(!1),s=l.useRef(e),o=l.useRef(void 0);return e!==null?(s.current=e,n||(o.current=t==null?void 0:t.messageId,r(!0))):n&&t!==void 0&&t.sender.userId===((i=s.current)==null?void 0:i.user.userId)&&t.messageId!==o.current&&r(!1),l.useEffect(()=>{if(!n||e!==null)return;const c=setTimeout(()=>r(!1),ih);return()=>clearTimeout(c)},[n,e!==null]),e??(n?s.current:null)},ch=(e,t,{enabled:n=!0,idleMs:r=1e3}={})=>{const s=l.useRef(null),o=l.useRef(t),i=l.useRef(t),c=l.useRef(!1);o.current=t,l.useEffect(()=>{if(s.current&&(clearTimeout(s.current),s.current=null),!n||!e){(c.current?i.current:o.current)(!1),c.current=!1,i.current=o.current;return}c.current=!0,i.current=o.current,i.current(!0),s.current=setTimeout(()=>{s.current=null,i.current(!1),c.current=!1,i.current=o.current},r)},[n,r,e]),l.useEffect(()=>()=>{s.current&&(clearTimeout(s.current),s.current=null),(c.current?i.current:o.current)(!1),c.current=!1,i.current=o.current},[])},lh=(e=1e4)=>{const t=new Map;let n=e;return{shouldAnnounce:c=>{const u=Date.now(),d=t.get(c);return d!==void 0&&u-d<n?!1:(t.set(c,u),!0)},setInterval:c=>{n=c},reset:()=>{t.clear()}}},uh=(e,t,n=1e4,r=!0)=>{const s=l.useRef(null),o=l.useRef(null),i=l.useRef(!1);s.current||(s.current=lh(n));const c=(e==null?void 0:e.nickname.trim())||null,u=(e==null?void 0:e.userId)??c;l.useEffect(()=>{var d;(d=s.current)==null||d.setInterval(n)},[n]),l.useEffect(()=>{var h;if(!r){i.current=!1,o.current=u;return}if(!u||!c){i.current=!1,o.current=null;return}const d=!i.current,m=o.current!==u;i.current=!0,o.current=u,!(!d&&!m)&&(h=s.current)!=null&&h.shouldAnnounce(u)&&t(c)},[u,c,r,t])},dh=({csat:e,csatPayload:t,isRenderableCSAT:n,isExpiredNow:r,announceStatus:s,onSubmittedAnnounced:o})=>{const i=(t==null?void 0:t.csat_submitted_label)??"",c=l.useRef(n&&typeof e=="number"),u=l.useRef(n&&r);l.useEffect(()=>{n&&i&&(typeof e!="number"||c.current||(c.current=!0,s&&(s({event:"csatSubmitted",submittedLabel:i}),o==null||o())))},[s,e,n,o,i]),l.useEffect(()=>{n&&r&&(u.current||(u.current=!0,s==null||s({event:"csatExpired"})))},[s,r,n])},ts=({channel:e,userSession:t,aiAgentInfo:n})=>{if(!t||!n||!e)return{fallbackIcon:void 0,url:void 0,title:""};const r=pi(e,t.userId),s={ai(o){return{fallbackIcon:o,url:n.profileUrl,title:n.nickname}},human(o){return{fallbackIcon:o,url:r==null?void 0:r.profileUrl,title:(r==null?void 0:r.nickname)||n.nickname}},channel(o){return{fallbackIcon:o,url:e==null?void 0:e.coverUrl,title:(e==null?void 0:e.name)??""}}};return e.isAIAgent?at(e)?s.human("agent"):s.ai("delight"):e.isDesk?s.human("agent"):s.channel("user")},Zs=e=>l.useReducer((t,n)=>({...t,...n}),e);var Je=(e=>(e.AI_AGENT_CSAT_5="AI_AGENT_CSAT_5",e.AI_AGENT_CSAT_5_WITH_CRE="AI_AGENT_CSAT_5_WITH_CRE",e.HELPDESK_CSAT_5="HELPDESK_CSAT_5",e))(Je||{});const mh=new Set(["free_text","single_choice"]),hh=({csatPayload:e,type:t,initialCsat:n,initialCsatReason:r,initialIsResolved:s})=>{const[o,i]=Zs({csatType:t,csat:n,csatReason:r,isResolved:s}),[c,u]=Zs({followUpItem:!1}),d=l.useMemo(()=>{var E;const g=o.csat,p=typeof g=="number",v=(E=e.follow_up)==null?void 0:E.find(_=>p?_.scores.includes(g):_.always_visible??!1);if(mh.has(v==null?void 0:v.response_type))return v},[o.csat,e.follow_up]),m=(()=>{var g;if(typeof n=="number")return"submitted";if((t===Je.AI_AGENT_CSAT_5||t===Je.HELPDESK_CSAT_5)&&typeof o.csat=="number")return"submittable";if(t===Je.AI_AGENT_CSAT_5_WITH_CRE){const p=typeof o.csat=="number",v=!((g=e.cre)!=null&&g.required)||typeof o.isResolved=="boolean";if(p&&v)return"submittable"}return"unsubmittable"})(),h=l.useCallback(()=>typeof o.csat>"u"?!1:d!=null&&d.required&&!o.csatReason?(u({followUpItem:!0}),!1):!0,[o,d,u]);return l.useEffect(()=>{r||(i({csatReason:""}),u({followUpItem:!1}))},[r,d,i,u]),{params:o,setParams:i,error:c,setError:u,followUpItem:d,state:m,validateParams:h,itemProps:{csatPayload:e,state:m,submitted:m==="submitted"}}},fh=({csat:e,csatExpireAt:t,csatPayload:n,isSubmitInFlight:r=!1})=>{const s=!!n&&n.visibility&&!!Je[n.type],o=!r&&typeof e!="number"&&_i(t),i=Pn();return l.useEffect(()=>{if(!s||typeof e=="number"||t==null||o)return;const c=t-Date.now();if(c<=0&&r)return;const u=setTimeout(i,Math.max(0,c));return()=>clearTimeout(u)},[i,e,t,o,s,r]),{isRenderableCSAT:s,isExpiredNow:o}},sr=5,Ht=250,Ui=50,gh=1500,or=e=>Math.max(0,e-Ui),Cn=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():0,ph=(e,t)=>{const n=e&&t.length<=Ui,r=l.useRef(n&&t.length>0?t:null),[s,o]=l.useState(()=>!n),i=r.current!==null&&t!==r.current,c=!n||i;return l.useEffect(()=>{if(s)return;const u=()=>{r.current=null,o(!0)};if(c){u();return}if(r.current===null&&t.length>0&&(r.current=t),r.current===null)return;const d=setTimeout(u,gh);return()=>clearTimeout(d)},[s,c,t]),!s&&!c},_h=e=>e<1e3?{speed:sr*.5,chunkSize:2}:e<2e3?{speed:sr*.8,chunkSize:2}:{speed:sr*.6,chunkSize:3},bn=(e,t)=>{let n=0;for(let r=t-1;r>=0&&e[r]==="\\";r--)n++;return n%2===1},Js=(e,t,n,r)=>{let s=1,o=t;for(;o<e.length&&s>0;){if(bn(e,o)){o++;continue}e[o]===n?s++:e[o]===r&&s--,o++}return s>0?-1:o},Bi=(e,{hideImages:t,hideLinks:n})=>{let r="",s=0,o=0;for(;s<e.length;){if(e[s]==="`"&&!bn(e,s)){let h=1;for(;e[s+h]==="`";)h++;o===0?o=h:h===o&&(o=0),r+=e.slice(s,s+h),s+=h;continue}const i=e[s]==="!"&&e[s+1]==="["&&!bn(e,s),c=e[s]==="["&&!bn(e,s);if(o>0||!i&&!c){r+=e[s],s++;continue}if(i?!t:!n){const h=i?"![":"[";r+=h,s+=h.length;continue}const u=s,d=Js(e,s+(i?2:1),"[","]");if(d===-1)return r;if(s=d,e[s]!=="("){r+=e.slice(u,s);continue}const m=Js(e,s+1,"(",")");if(m===-1)return r;s=m,r+=e.slice(u,s)}return r},Eh=({trackedRef:e,onVisibleTextProgress:t,onRenderedTextProgress:n})=>{const r=l.useRef(t),s=l.useRef(n),o=l.useRef(null),i=l.useRef({lastLength:0,lastReportedAt:0}).current,c=l.useRef({lastLength:0,lastReportedAt:0,lastCheckedAt:0}).current,u=l.useRef(null);l.useLayoutEffect(()=>{r.current=t,s.current=n});const d=l.useCallback(A=>{var y;(y=r.current)==null||y.call(r,A)},[]),m=l.useCallback(A=>{const y=e.initialEnabled&&(e.enabled||A<e.textLength),T=y&&e.deferImages,I=y&&e.deferLinks;return!T&&!I?A:Bi(e.text.slice(0,A),{hideImages:T,hideLinks:I}).length},[e]),h=l.useCallback((A,y,T=!1)=>{r.current&&(A<=c.lastLength||!T&&y-c.lastReportedAt<Ht||(c.lastLength=A,c.lastReportedAt=y,d(A)))},[d,c]),f=l.useCallback((A,y,T=!1)=>{if(!r.current)return;const I=Math.max(c.lastReportedAt,c.lastCheckedAt);!T&&y-I<Ht||(c.lastCheckedAt=y,h(m(A),y,!0))},[m,h,c]),g=l.useCallback((A,y,T=!1)=>{s.current&&(A<=i.lastLength||!T&&y-i.lastReportedAt<Ht||(i.lastLength=A,i.lastReportedAt=y,s.current(A)))},[i]),p=l.useCallback((A,y,T)=>{const I=A>=y,N=T-i.lastReportedAt>=Ht;if(!I&&!N)return;const O=m(A);g(O,T,I)},[m,i,g]),v=l.useCallback(()=>{c.lastLength=0,c.lastReportedAt=0,c.lastCheckedAt=0,i.lastLength=0,i.lastReportedAt=0},[i,c]),E=l.useCallback(A=>{r.current&&(o.current!==null&&A<=o.current||(o.current=A,d(A)))},[d]),_=l.useCallback(({displayedLength:A,streamTextLength:y})=>{const T=u.current;if(u.current={displayedLength:A,streamTextLength:y},!e.initialEnabled||!T||A>T.displayedLength||y<=T.streamTextLength)return;const I=Cn();h(y,I,!0),g(y,I,!0)},[u,g,h,e]);return{resetProgress:v,reportVisibleTextProgress:f,reportRenderedTextProgress:p,reportNonStreamingVisibleTextProgress:E,reportMarkdownRevealProgress:_}},Ch=e=>{const{text:t,enabled:n=!1,snapOnDisable:r=!1,deferredMarkdownElements:s=[],onAnimationStart:o,onAnimationProgress:i,onAnimationComplete:c,onAnimationHoldChange:u,onVisibleTextProgress:d,onRenderedTextProgress:m}=e,h=ph(n,t),f=s.includes("image"),g=s.includes("link"),[p,v]=l.useState(()=>n?h?0:or(t.length):t.length),E=l.useRef(null),_=l.useRef({startTime:0,lastUpdate:0,lastProgressCall:0}).current,A=l.useRef({startCalled:!1,completeCalled:!1}).current,y=l.useRef({initialEnabled:n,textLength:t.length,enabled:n,text:t,deferImages:f,deferLinks:g,snapOnDisable:r,isGatingStreamingStart:h}).current,T=ce(()=>o==null?void 0:o()),I=ce(()=>i==null?void 0:i()),N=ce(()=>c==null?void 0:c()),O=ce(q=>u==null?void 0:u(q)),{resetProgress:k,reportVisibleTextProgress:R,reportRenderedTextProgress:F,reportNonStreamingVisibleTextProgress:D,reportMarkdownRevealProgress:Q}=Eh({trackedRef:y,onVisibleTextProgress:d,onRenderedTextProgress:m}),re=n,G=p<t.length,H=y.initialEnabled&&(re||G);l.useLayoutEffect(()=>{y.textLength=t.length,y.enabled=n,y.text=t,y.deferImages=f,y.deferLinks=g,y.snapOnDisable=r,y.isGatingStreamingStart=h}),l.useLayoutEffect(()=>{if(y.initialEnabled){if(A.startCalled||(A.startCalled=!0,T()),!y.enabled&&y.snapOnDisable){v(t.length);const q=Cn();R(t.length,q,!0),F(t.length,t.length,q);return}v(q=>t.length<q?t.length:q)}},[T,F,R,t]),l.useEffect(()=>{if(!y.initialEnabled)return;let q=h?0:or(t.length),z=h;_.lastUpdate=0,_.startTime=0,_.lastProgressCall=0,k();const W=Y=>{_.lastUpdate===0&&(_.lastUpdate=Y,_.startTime=Y,_.lastProgressCall=Y,q>0&&R(q,Y,!0));const V=y.textLength;z&&!y.isGatingStreamingStart&&(q=or(V),v(q),q>0&&R(q,Y,!0),_.lastUpdate=Y,z=!1),!y.enabled&&y.snapOnDisable&&q<V&&(q=V,v(q),R(q,Y,!0),F(q,V,Y));const te=Y-_.lastUpdate,w=Y-_.startTime,{speed:_e,chunkSize:Re}=_h(w),Te=_e*Re;!y.isGatingStreamingStart&&te>=Te&&q<V&&(q=Math.min(q+Re,V),v(q),R(q,Y,q>=V),F(q,V,Y),_.lastUpdate=Y),Y-_.lastProgressCall>=Ht&&(_.lastProgressCall=Y,I()),(q<V||y.enabled)&&(E.current=requestAnimationFrame(W))};return E.current=requestAnimationFrame(W),()=>{E.current&&cancelAnimationFrame(E.current),A.startCalled&&!A.completeCalled&&(A.completeCalled=!0,N())}},[N,I,F,R,k]),l.useEffect(()=>{y.initialEnabled&&(n||t.length>0)||(D(t.length),F(t.length,t.length,Cn()))},[n,m,d,D,F,t.length,y]),l.useEffect(()=>{const q=y.initialEnabled&&A.startCalled,z=!n,W=p>=t.length;q&&z&&W&&!A.completeCalled&&(A.completeCalled=!0,N())},[n,p,N,t.length]);const K=l.useMemo(()=>{let q=t;y.initialEnabled&&(q=h?"":t.slice(0,p));const z=H&&f,W=H&&g;return!z&&!W?q:Bi(q,{hideImages:z,hideLinks:W})},[t,p,f,g,H,h]);l.useEffect(()=>{!y.initialEnabled||H||R(p,Cn(),!0)},[p,H,R]),l.useEffect(()=>{Q({displayedLength:p,streamTextLength:K.length})},[p,Q,K.length]);const J=K.length===0&&H;return l.useLayoutEffect(()=>(O(J),()=>O(!1)),[O,J]),{streamText:K,isAnimating:H,isHolding:J}},Qs={visible:!1,remainingTime:0,showDescription:!1,targetTimeMs:null},bh=e=>({visible:!0,remainingTime:e,showDescription:!0,targetTimeMs:Date.now()+e*1e3}),vh=(e,t=Date.now())=>{if(!e.visible||e.targetTimeMs==null)return e;const n=Math.max(Math.ceil((e.targetTimeMs-t)/1e3),0);return n<=0?{...e,remainingTime:0,showDescription:!1,targetTimeMs:null}:e.remainingTime===n&&e.showDescription?e:{...e,remainingTime:n,showDescription:!0}},Sh=()=>{const{chatSDK:e}=ye(),[t,n]=l.useState(Qs),r=()=>n(Qs);return Qt(e,{onConnectionDelayed:s=>{s>0?n(bh(s)):r()},onReconnectSucceeded:r,onConnected:r}),l.useEffect(()=>{if(!t.visible||!t.showDescription||t.targetTimeMs==null)return;const s=setTimeout(()=>{n(o=>vh(o))},1e3);return()=>clearTimeout(s)},[t.visible,t.showDescription,t.targetTimeMs,t.remainingTime]),{visible:t.visible,remainingTime:t.remainingTime,showDescription:t.showDescription}},yh=e=>{const t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`},Ah=(e,t)=>{if(!t)return{beforeText:e,highlightedText:"",afterText:""};const n=e.indexOf(t);return n<0?{beforeText:e,highlightedText:"",afterText:""}:{beforeText:e.slice(0,n),highlightedText:t,afterText:e.slice(n+t.length)}},Th=({enabled:e=!0}={})=>{const t=Nt();return l.useCallback(({message:n,isBotMessage:r,aiAgentUserId:s})=>{if(!e)return;const o=n.messageId,i=we.isStreaming(n),c=Xt(n.extendedMessagePayload),u=c.hasMessageTemplate,d=c.hasForm,m=r&&n.isUserMessage()&&!i&&!Wc(n)&&!we.isWelcomeMessage(n,s),h=i||t.streamStalled.hasPendingStream(o),f=t.userPerceivedResponseTime.hasPendingAIResponse(o);if(!h&&!f&&!m&&!u&&!d)return;let g=!1,p=!1;const v={};return(f||m)&&(v.onVisibleTextProgress=()=>{f&&!g&&(g=t.userPerceivedResponseTime.markAIResponseVisible(o)),m&&!p&&(p=!0,t.renderedContentUnusable.commit({messageId:o,contentKind:"text",errorDomain:"empty_render"}))}),h&&(v.onRenderedTextProgress=E=>{t.streamStalled.markRenderedProgress({messageId:o,displayedLength:E})}),u&&(v.onMessageTemplateError=E=>{t.renderedContentUnusable.commit({messageId:o,contentKind:"template",errorDomain:"template_error",error:E})}),d&&(v.onFormRenderError=E=>{t.renderedContentUnusable.commit({messageId:o,contentKind:"form",errorDomain:"form_error",error:E})}),v},[e,t])},Ih=e=>{const t=l.useRef(!1);l.useEffect(()=>{t.current||e!=null&&e.onVisibleTextProgress&&(t.current=!0,e.onVisibleTextProgress(0))},[e])},ir=5e3,xh=({channelUrl:e,enabled:t=!0,isInitiallyBackgrounded:n,isForegrounded:r,subscribeToForegroundState:s})=>{const o=Nt(),i=l.useRef(t),c=l.useRef(n),u=l.useRef(t&&n()?performance.now()-ir:null),d=l.useRef(!1);i.current=t,c.current=n;const m=l.useCallback((h=r())=>{if(!i.current){d.current=!1;return}if(!h){d.current=!1;return}if(u.current===null){d.current=!1;return}if(performance.now()-u.current<ir){u.current=null,d.current=!1;return}if(!e){d.current=!0;return}u.current=null,d.current=!1,o.recoveryNotInteractiveTimeout.start("foreground_resume",e)},[e,r,o]);l.useEffect(()=>{t||(u.current=null,d.current=!1,e&&o.recoveryNotInteractiveTimeout.cancelPending(e))},[e,t,o]),l.useEffect(()=>{if(!t)return;d.current&&!!e&&r()&&m()},[e,t,r,m]),l.useEffect(()=>{if(t)return c.current()?u.current??(u.current=performance.now()-ir):u.current=null,s(h=>{if(h==="backgrounded"){u.current??(u.current=performance.now()),d.current=!1,e&&o.recoveryNotInteractiveTimeout.cancelPending(e);return}m(!0)})},[e,t,m,o,s])},Rh=e=>{const{conversationInitialRender:t,conversationListInitialRender:n}=Nt();l.useLayoutEffect(()=>{t.setPresentMethod(e),n.setPresentMethod(e)},[t,n,e])},Mh=(e,{enabled:t=!0,opened:n=!1,filter:r}={})=>{var u,d,m;const[s,o]=l.useState(!1),i=l.useRef(0),c=()=>{if(!t)return;const h=++i.current;e.aiAgent.getUnreadMessageCount(r).then(f=>{h===i.current&&o(f.total>0)}).catch(()=>{})};return l.useEffect(()=>{if(!t){o(!1),i.current++;return}e.connectionState===Ee.ConnectionState.OPEN&&c()},[t,e,r==null?void 0:r.aiAgentChannelFilter,(u=r==null?void 0:r.aiAgentConversationStatusFilter)==null?void 0:u.join(),(d=r==null?void 0:r.aiAgentIds)==null?void 0:d.join(),r==null?void 0:r.deskChannelFilter,(m=r==null?void 0:r.pinnedChannelUrls)==null?void 0:m.join(),r==null?void 0:r.copilotConversationOnly,r==null?void 0:r.copilotSupportChannelUrl]),l.useEffect(()=>{n&&(o(!1),i.current++)},[n]),Qt(e,{onConnected:c,onReconnectSucceeded:c}),s},Mt=e=>e.replace(/\s+/g," ").trim(),wh="Code block",Hi=e=>`A11Y_INLINE_CODE_${e}`,Gi=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}},zi=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}},kh=e=>{const{blockquotePrefix:t,content:n}=Gi(e),{content:r}=zi(n),s=r.match(/^[ \t]{0,3}([`~]{3,})(.*)$/);if(!s)return;const o=s[1],i=s[2],c=o[0];if(!(c!=="`"&&c!=="~"||!o.split("").every(u=>u===c))&&!(c==="`"&&i.includes("`")))return{char:c,blockquotePrefix:t,length:o.length}},Lh=(e,t)=>{const{blockquotePrefix:n,content:r}=Gi(e);if(n!==t.blockquotePrefix)return!1;const{content:s,hasListPrefix:o}=zi(r);if(o)return!1;const i=s.match(/^[ \t]{0,3}([`~]{3,})[ \t]*$/);if(!i)return!1;const c=i[1];return c[0]===t.char&&c.length>=t.length&&c.split("").every(u=>u===t.char)},Oh=(e,t,n)=>{let r=n;for(;r<e.length;){const s=e[r];if(s==="\\"&&r+1<e.length){r+=2;continue}if(s===t)return r;r+=1}return-1},Nh=(e,t)=>{let n=1,r=t;for(;r<e.length;){const s=e[r];if(s==="\\"&&r+1<e.length){r+=2;continue}if(s==="["){n+=1,r+=1;continue}if(s==="]"&&(n-=1,n===0))return r;r+=1}return-1},Dh=(e,t)=>{let n=t,r=1,s,o=!1,i=!1;for(;n<e.length&&r>0;){const c=e[n];if(c==="\\"&&n+1<e.length){n+=2;continue}if(s){c===s&&(s=void 0),n+=1;continue}if(r===1&&o&&/\s/.test(c)){i=!0,n+=1;continue}if(r===1&&i&&(c==='"'||c==="'")){s=c,n+=1;continue}if(c==="("){r+=1,o=!0,n+=1;continue}if(c===")"){r-=1,n+=1;continue}/\s/.test(c)||(o=!0),n+=1}return r===0?n:-1},$h=e=>{let t=0,n="";for(;t<e.length;){const r=Oh(e,"[",t);if(r===-1){n+=e.slice(t);break}const s=Nh(e,r+1);if(s===-1){n+=e.slice(t);break}if(r>0&&e[r-1]==="!"&&Rn(e,r-1)){n+=e.slice(t,s+1),t=s+1;continue}if(e[s+1]!=="("){n+=e.slice(t,s+1),t=s+1;continue}const o=r>0&&e[r-1]==="!"&&!Rn(e,r-1)?r-1:r;n+=e.slice(t,o);const i=e.slice(r+1,s),c=Dh(e,s+2);if(c===-1){n+=e.slice(o);break}n+=i,t=c}return n},Vi=(e,t,n)=>{if(!/^\d+$/.test(t))return!1;const r=e.slice(-1);return/\d/.test(r)&&/\d/.test(n)},Ph=e=>e.replace(/(^|[^*\\])\*\*([^\s*](?:[\s\S]*?[^\s*])?)\*\*(?!\*)/g,(t,n,r,s,o)=>{const i=o[s+t.length]??"";return Vi(n,r,i)?t:`${n}${r}`}),Fh=e=>e.replace(/(^|[^_\\])__([^\s_](?:[\s\S]*?[^\s_])?)__(?!_)/g,"$1$2"),Uh=e=>e.replace(/(^|[^~\\])~~([^\s~](?:[\s\S]*?[^\s~])?)~~(?!~)/g,"$1$2"),Bh=e=>{let t=e;return t=t.replace(/(^|[^*\\])\*([^\s*](?:[\s\S]*?[^\s*])?)\*(?!\*)/g,(n,r,s,o,i)=>{const c=i[o+n.length]??"";return Vi(r,s,c)?n:`${r}${s}`}),t=t.replace(/(^|[\s([{"'])_([^_\s](?:[\s\S]*?[^_\s])?)_(?=$|[\s)\]}"'.,!?:;])/g,"$1$2"),t},Hh=e=>e.replace(/\\([\\`*_[\]()#+.!~|-])/g,"$1"),Gh=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},eo=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))},to=e=>{const t=[];let n="",r=!1;for(const o of e.trim()){if(r){n+=o==="|"?"|":`\\${o}`,r=!1;continue}if(o==="\\"){r=!0;continue}if(o==="|"){const i=n.trim();i&&t.push(i),n="";continue}n+=o}r&&(n+="\\");const s=n.trim();return s&&t.push(s),t},zh=e=>{const t=e.split(`
|
|
12
|
-
`),n=[];let r=0;for(;r<t.length;){const s=t[r],o=t[r+1],i=
|
|
13
|
-
`)},
|
|
14
|
-
`),r=[];let s=0;for(;s<n.length;){const o=n[s],i=
|
|
15
|
-
`)},
|
|
16
|
-
`;){if(e[c]==="`"&&!
|
|
17
|
-
`);if(!n)return;const r=[];let s=n;s=Kh(s,t),s=Gh(s);const o=qh(s);s=o.text,r.push(...o.inlineCodes),s=$h(s),s=Ph(s),s=Fh(s),s=Uh(s),s=Bh(s),s=zh(s),s=Vh(s),s=Hh(s);for(let c=0;c<r.length;c++)s=s.replaceAll(Hi(c),r[c]);return Mt(s)||void 0},Wh=(e,t)=>{var s;const n=((s=e.name)==null?void 0:s.trim())||"",r=e.mimeType??"";return Ke(r)?t.image:Zt(r)?t.video:ui({name:n,mimeType:r})?t.pdf(n):t.document(n)},Mn=e=>(e==null?void 0:e.trim())||"",Yh=e=>(e?Mt(e):void 0)||void 0,no=30,jh=e=>e.length>no?`${e.slice(0,no)}…`:e,Xh=({agent:e,status:t,lastMessage:n,time:r,unreadCount:s},o)=>{const i=jh(Mt(n)),c=[t,i].filter(Boolean).join(", ");return o(Mt(e),Mt(c),r,s)},Tr=e=>({text:Mn(e),format:"plain"}),Zh=e=>({text:Mn(e),format:"markdown"}),Jh=({markdownText:e,plainText:t,comparisonText:n})=>{const r=Mn(e);return r&&r!==Mn(n)?Zh(r):Tr(t)},Kt=({sender:e,message:t,messageFormat:n="plain",time:r,codeBlockPlaceholder:s})=>{const o=[],i=n==="markdown"?Ki(t,{codeBlockPlaceholder:s}):Yh(t);if(r&&o.push(r),e&&o.push(e),i&&o.push(i),o.length!==0)return o.join(", ")},qi=(e,t)=>Ki(e==null?void 0:e.trim(),t!==void 0?{codeBlockPlaceholder:t}:void 0),Qh=(...e)=>Mt(e.filter(Boolean).join(", "))||void 0,ro=(e,t,n,r)=>{if(!t||di(t,n))return e;const s=qi(t,r);return s?Qh(e,s):e},Wi=(e,t)=>{var r,s;const n=(r=e.message)==null?void 0:r.trim();if(e.isFileMessage()){const o=((s=e.name)==null?void 0:s.trim())||"",i=Wh({name:o,mimeType:e.type},t);return ro(i,n,[o],t.codeBlockPlaceholder)}if(e.isMultipleFilesMessage()){const o=e.fileInfoList??[],i=o.length;if(i===0)return;const c=o.map(m=>{var h;return((h=m.fileName)==null?void 0:h.trim())||""}),d=o.every(m=>{var h;return(h=m.mimeType)==null?void 0:h.startsWith("image")})?t.receivedFilesImageCount(i):t.multipleFilesCount(i);return ro(d,n,c,t.codeBlockPlaceholder)}return qi(n,t.codeBlockPlaceholder)},ef=(e,t={})=>{const{throttleMs:n=1e3,isSuppressed:r,maxOrderedQueueSize:s=10}=t,o=Math.max(1,s);let i=null;const c=[];let u=null,d=null,m=null,h=!1,f=0;const g=(k,R,F)=>({text:k,ignoreSuppression:R,queueOrder:f++,dedupeKey:F}),p=()=>{const k=c[0]??null,R=i;return k&&R?R.queueOrder<k.queueOrder?(i=null,R):c.shift()??null:k?c.shift()??null:R!==null?(i=null,R):null},v=()=>{for(;;){const k=p();if(!k)return null;if(!(!k.ignoreSuppression&&(r!=null&&r())))return k}},E=k=>{u=k.text,d=k.dedupeKey??null,h=!0,e(k.text),m=setTimeout(()=>{m=null,h=!1;const R=v();R&&E(R)},n)},_=k=>{u=k.text,d=k.dedupeKey??null,e(k.text)},A=(k,R,F,D)=>R!=null&&D!=null?R===D:R==null&&D==null?k!=null&&k===F:!1,y=(k,R,F)=>{if(!k||!R&&(r!=null&&r()))return;const D=F==null?void 0:F.dedupeKey;if(!(h&&A(k,D,u,d)))if(h){if(((F==null?void 0:F.mode)??"latestOnly")==="ordered"){const re=c[c.length-1];if(re&&A(k,D,re.text,re.dedupeKey))return;c.push(g(k,R,D)),c.length>o&&c.shift();return}i=g(k,R,D)}else i=null,E(g(k,R,D))};return{announce:(k,R)=>{y(k,!1,R)},announceIgnoringSuppression:(k,R)=>{y(k,!0,R)},flush:()=>{const k=[];let R=p();for(;R!==null;)k.push(R),R=p();if(m!==null&&(clearTimeout(m),m=null),h=!1,k.length!==0)for(const F of k)_(F)},destroy:()=>{m!==null&&(clearTimeout(m),m=null),i=null,c.length=0,u=null,d=null,h=!1}}},tf=e=>{switch(e){case"newMessage":case"conversationClosed":case"csatDisplayed":case"csatSubmitted":case"csatExpired":return"ordered";default:return"latestOnly"}},nf=(e,t)=>e.screen==="conversationList"?typeof e.conversationCount=="number"?t.screenConversationListWithCount(e.conversationCount):t.screenConversationListNoCount:[e.agentName?t.screenConversationWithAgent(e.agentName):t.screenConversation,e.isClosed?t.conversationClosed:null,e.isClosed&&e.hasCSAT?t.csatDisplayed:null,e.isEmpty?t.emptyState:null].filter(r=>!!r).join(". "),rf=(e,t)=>{switch(e.event){case"newMessage":return e.body!==void 0||e.time!==void 0?[t.newMessage(1),e.time,e.senderName,e.body].filter(r=>!!r).join(", "):e.senderName?t.newMessageFromSender(e.senderName,1):t.newMessage(1);case"typing":return t.typing(e.agentName??"");case"sendFailed":return t.sendFailed;case"agentConnected":return t.agentConnected(e.agentName??"");case"conversationClosed":return t.conversationClosed;case"csatDisplayed":return t.csatDisplayed;case"csatSubmitted":return e.submittedLabel;case"csatExpired":return t.csatExpired;case"emptyState":return t.emptyState;case"inputDisabled":return t.inputDisabled}},sf=(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}},of=(e,t)=>!t||!Qe(e)||e.sender.userId!==t?null:e.reqId||(e.messageId>0?String(e.messageId):null),af=(e,t)=>Me.isAdmin(e)?Me.isCSAT(e):"sender"in e?e.sender.userId!==t:!1,cf=e=>"messageId"in e&&e.messageId>0?String(e.messageId):"reqId"in e&&typeof e.reqId=="string"&&e.reqId.length>0?e.reqId:null,lf=e=>e===Ee.CollectionEventSource.EVENT_MESSAGE_RECEIVED||e===Ee.CollectionEventSource.EVENT_MESSAGE_UPDATED,uf=({isOpened:e,opensConversationList:t})=>e?t?"closeConversationList":"closeConversation":t?"openConversationList":"openConversation",df=(e,t)=>{switch(e){case"closeConversationList":return t.closeConversationList;case"closeConversation":return t.closeConversation;case"openConversationList":return t.openConversationList;case"openConversation":return t.openConversation}},mf=(e,t)=>{switch(e){case"closeConversation":return t.hintCloseConversation;case"openConversationList":return t.hintOpenConversationList;case"openConversation":return t.hintOpenConversation;default:return}},hf=({intent:e,strings:t})=>({label:df(e,t),hint:mf(e,t)}),ff="1.40.0",Ue="sb-agent",Se={ENTRY:`${Ue}-entry`,MODAL_ROOT:`${Ue}-modal-root`,WINDOW:`${Ue}-window`,LAUNCHER:`${Ue}-launcher`,WINDOW_TITLE:`${Ue}-window-title`},Yi="data-sb-initial-focus",ji="true",gf=`[${Yi}="${ji}"]`,Xi={[Yi]:ji},ns="data-sb-focus-trap-sentinel",pf="true",Zi="data-sb-initial-focus-header",Ji="true",_f=`[${Zi}="${Ji}"]`,Qi={[Zi]:Ji},ea="data-sb-message-input",ta="true",Ef=`textarea[${ea}="${ta}"]:not(:disabled)`,Cf={[ea]:ta},na=1e3,hn=2147483647,Et={MODAL:hn-1,TOOLTIP:hn-2,WINDOW:hn-3,LAUNCHER:hn-4},ra=36,bf=100,vf=ff,rs="noopener noreferrer nofollow",Sf=()=>typeof document>"u"||document.visibilityState==="visible",Ir=()=>typeof document<"u"&&document.visibilityState==="hidden",so=()=>Ir()?"backgrounded":"foregrounded",yf={getState:so,subscribe:e=>{if(typeof document>"u")return()=>{};const t=()=>e(so());return document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t)}};function Af(){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 fn={};function Tf(){return{get:e=>{try{return localStorage.getItem(e)}catch{return fn[e]??null}},set:(e,t)=>{try{localStorage.setItem(e,t)}catch{fn[e]=t}},delete:e=>{try{localStorage.removeItem(e)}catch{delete fn[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(fn).filter(t=>t.startsWith(e))}}}}const If={conversation:{input_placeholder:"Ask a question",input_placeholder_disabled:"Chat is unavailable in this channel",input_placeholder_steward:"Processing your request...",input_placeholder_wait_ai_agent_response:"Waiting for the agent's reply...",input_placeholder_active_form:"Please fill out the form to move forward.",input_placeholder_reconnecting:"Trying to reconnect. Refresh if persists.",unknown_message_type:"(Unknown message type)",powered_by:"Powered by",citation_title:"Source",start_new_conversation_label:"Start a conversation",scroll_to_new_messages_label:()=>"New message",failed_message_resend:"Retry",failed_message_remove:"Remove",file_upload_no_supported_files:"No supported file types available.",file_upload_replace_alert_title:"Replace attachment?",file_upload_replace_alert_description:"Uploading a different file type will replace the current one.",a11y_message_list:"Chat messages",a11y_scroll_to_bottom:"Scroll to bottom",a11y_scroll_to_new_messages:"Scroll to new messages",a11y_open_conversation_list:"Open conversation list",a11y_open_conversation:"Open conversation with Support",a11y_open_conversations:"Open conversations",a11y_close_conversation:"Close conversation",a11y_close_conversations:"Close conversations",a11y_menu:"Menu",a11y_message_input:"Message",a11y_send_message:"Send message",a11y_attach_file:"Attach file",a11y_close_messenger:"Close messenger",a11y_dismiss_nudge_message:"Dismiss message",a11y_expand_messenger:"Expand messenger",a11y_collapse_messenger:"Collapse messenger",a11y_connect_agent:"Talk to human agent",a11y_message_sender_you:"You",a11y_suggested_reply:"Suggested reply",a11y_typing_indicator:"Typing",a11y_code_block_placeholder:"Code block",a11y_typing_format:e=>`${e} is typing`,a11y_message_failed:"Message send failed",a11y_new_messages_received:e=>`${e} new ${e===1?"message":"messages"} received`,a11y_new_messages_received_from_sender:(e,t)=>`${e}: ${t} new ${t===1?"message":"messages"} received`,a11y_agent_connected:e=>"Connected to human agent",a11y_conversation_closed:"Conversation has ended",a11y_file_image:e=>`Image file: ${e}`,a11y_file_video:e=>`Video file: ${e}`,a11y_file_pdf:e=>`PDF file: ${e}`,a11y_file_document:e=>`Document file: ${e}`,a11y_received_file_image:"Image file",a11y_received_file_video:"Video file",a11y_received_file_pdf:e=>`PDF file: ${e}`,a11y_received_files_image_count:e=>`${e} ${e===1?"image":"images"}`,a11y_screen_conversation:"Conversation",a11y_screen_conversation_with_agent:e=>`Conversation with ${e}`,a11y_screen_conversation_list_no_count:"Conversation list",a11y_screen_conversation_list_with_count:e=>`Conversations, ${e} total`,a11y_csat_displayed:"Satisfaction survey displayed",a11y_empty_conversation:"No messages in this conversation",a11y_input_disabled:"Message input is disabled",a11y_file_size_exceeded:e=>`File exceeds size limit of ${e}MB`,a11y_csat_form_error:"Please complete the required fields",a11y_hint_send_message:"Sends the message",a11y_hint_open_conversation:"Opens the conversation",a11y_hint_open_conversations:"Opens conversations",a11y_hint_close_conversation:"Closes the conversation",a11y_hint_close_messenger:"Closes the messenger",a11y_hint_open_menu:"Opens the menu",a11y_hint_connect_to_agent:"Escalates to a human agent",a11y_hint_attach_file:"Opens file attachment options",a11y_hint_view_new_messages:"Scrolls to new messages",a11y_hint_open_file:"Opens the file",a11y_hint_open_image:"Opens the image",a11y_hint_send_reply:"Sends this reply",image_viewer_default_title:"Image",a11y_image_viewer_close:"Close image viewer",a11y_image_viewer_previous:"Previous image",a11y_image_viewer_next:"Next image",a11y_image_viewer_download:"Download image",attachment_document:"Files"},conversation_list:{header_title:"Conversations",ended:"Ended",system_message:"System message",footer_title:"Start a conversation",multiple_files_count:e=>`${e} ${e===1?"file":"files"}`,a11y_conversation_item:(e,t,n,r)=>`${e}, ${t}, ${n}${r>0?`, ${r} unread ${r===1?"message":"messages"}`:""}`},date_format:{just_now:"Just now",minutes_ago:e=>`${e} minutes ago`,hours_ago:e=>`${e} hours ago`,date_short:"MM/dd/yyyy",date_separator:"MMMM dd, yyyy",message_timestamp:"p"},csat:{title:"Your feedback matters to us",submitted_label:"Successfully submitted!",cre_question:"Was your issue resolved?",cre_positive_label:"Yes, thank you! 👍",cre_negative_label:"No, that didn't help.",reason_placeholder:"Share your feedback",question:"How would you rate your experience?",submit_label:"Submit",submission_expired:"We're sorry, the survey period has ended.",a11y_csat_rating_label:(e,t)=>`${e} out of 5 — ${t}`,a11y_hint_select_rating:"Selects this rating"},form:{optional_label:"optional",validation_required:"This question is required"},common:{placeholder_something_went_wrong:"Something went wrong",placeholder_no_messages:"No messages",placeholder_no_conversations:"No conversations yet",placeholder_something_went_wrong_retry_label:"Retry",button_ok:"OK",button_cancel:"Cancel"},feedback:{title:"Submit feedback",good:"Good",bad:"Bad",comment_label:"Comment (optional)",comment_placeholder:"Leave a comment",cancel:"Cancel",submit:"Submit",save:"Save",edit:"Edit feedback",remove:"Remove feedback"},handoff:{confirm_title:"Request handoff?",confirm_description:"You'll be transferred to a human agent. Your conversation history will be shared.",confirm_cancel:"Cancel",confirm_handoff:"Handoff"},memory:{dialog_title:"Memory",desc_on:"Memory is **turned on**. It remembers your conversation history to provide personalized responses tailored to your previous questions and preferences.",desc_off:"Memory is **turned off**. If turned on, it will remember your conversation history to provide personalized responses tailored to your previous questions and preferences.",button_use:"Use",button_dont_use:"Don't use",button_keep_using:"Keep using",button_disable:"Disable",button_disable_and_delete:"Disable & Delete memory",button_keep_off:"Keep off",button_enable:"Enable memory",button_cancel:"Cancel",error_message:"Failed to update memory state. Please try again.",a11y_indicator_manage:"Manage memory",a11y_indicator_on:"Memory is on",a11y_indicator_off:"Memory is off"},connection_delay:{title:"Something went wrong. You'll be reconnected shortly.",description:e=>`Estimated waiting time: ${e}`},desk:{ticket_closure_confirm:"Yes, it's resolved",ticket_closure_decline:"No, I still need help",ticket_closure_error_message:"Failed to update the resolution status. Please try again."}},xr={language:"en",strings:If,dateLocale:Mc.enUS},sa=e=>({MESSAGE_INPUT__PLACE_HOLDER:e.conversation.input_placeholder,MESSAGE_INPUT__PLACE_HOLDER__DISABLED:e.conversation.input_placeholder_disabled,MESSAGE_INPUT__PLACE_HOLDER__STEWARD:e.conversation.input_placeholder_steward,MESSAGE_INPUT__PLACE_HOLDER__WAIT_AI_AGENT_RESPONSE:e.conversation.input_placeholder_wait_ai_agent_response,MESSAGE_INPUT__PLACE_HOLDER__RECONNECTING:e.conversation.input_placeholder_reconnecting,UNKNOWN__UNKNOWN_MESSAGE_TYPE:e.conversation.unknown_message_type,POWERED_BY:e.conversation.powered_by,CSAT_TITLE_UNSUBMITTED:e.csat.title,CSAT_TITLE_SUBMITTED:e.csat.submitted_label,CSAT_CRE_TITLE:e.csat.cre_question,CSAT_CRE_SOLVED:e.csat.cre_positive_label,CSAT_CRE_NOT_SOLVED:e.csat.cre_negative_label,CSAT_REASON_PLACEHOLDER:e.csat.reason_placeholder,CSAT_RATING_TITLE:e.csat.question,CSAT_SUBMIT_LABEL:e.csat.submit_label,CSAT_SUBMISSION_EXPIRED:e.csat.submission_expired,DATE_FORMAT__JUST_NOW:e.date_format.just_now,DATE_FORMAT__MINUTES_AGO:e.date_format.minutes_ago,DATE_FORMAT__HOURS_AGO:e.date_format.hours_ago,DATE_FORMAT__DATE_SHORT:e.date_format.date_short,DATE_FORMAT__MESSAGE_LIST__DATE_SEPARATOR:e.date_format.date_separator,DATE_FORMAT__MESSAGE_TIMESTAMP:e.date_format.message_timestamp,CONVERSATION_LIST__HEADER_TITLE:e.conversation_list.header_title,CONVERSATION_LIST__ENDED:e.conversation_list.ended,CONVERSATION_LIST__SYSTEM_MESSAGE:e.conversation_list.system_message,CONVERSATION_LIST__NO_CONVERSATIONS:e.common.placeholder_no_conversations,CONVERSATION_LIST__MULTIPLE_FILES_COUNT:e.conversation_list.multiple_files_count,TALK_TO_AGENT:e.conversation.start_new_conversation_label,CITATION_SOURCE_TITLE:e.conversation.citation_title,FORM_PLACEHOLDER:e.conversation.input_placeholder_active_form,FORM_VALIDATION_REQUIRED:e.form.validation_required,OPTIONAL:e.form.optional_label,PLACE_HOLDER__WRONG:e.common.placeholder_something_went_wrong,PLACE_HOLDER__NO_MESSAGES:e.common.placeholder_no_messages,RETRY:e.common.placeholder_something_went_wrong_retry_label,BUTTON__OK:e.common.button_ok,BUTTON__CANCEL:e.common.button_cancel,FAILED_MESSAGE_RESEND:e.conversation.failed_message_resend,FAILED_MESSAGE_REMOVE:e.conversation.failed_message_remove,DESK__TICKET_CLOSURE_CONFIRM:e.desk.ticket_closure_confirm,DESK__TICKET_CLOSURE_DECLINE:e.desk.ticket_closure_decline,DESK__TICKET_CLOSURE_ERROR_MESSAGE:e.desk.ticket_closure_error_message,FILE_UPLOAD_NO_SUPPORTED_FILES:e.conversation.file_upload_no_supported_files,FILE_UPLOAD_REPLACE_ALERT__TITLE:e.conversation.file_upload_replace_alert_title,FILE_UPLOAD_REPLACE_ALERT__DESCRIPTION:e.conversation.file_upload_replace_alert_description,FILE_UPLOAD_FILES:e.conversation.attachment_document,FEEDBACK_TITLE:e.feedback.title,FEEDBACK_GOOD:e.feedback.good,FEEDBACK_BAD:e.feedback.bad,FEEDBACK_COMMENT_LABEL:e.feedback.comment_label,FEEDBACK_COMMENT_PLACEHOLDER:e.feedback.comment_placeholder,FEEDBACK_CANCEL:e.feedback.cancel,FEEDBACK_SUBMIT:e.feedback.submit,FEEDBACK_SAVE:e.feedback.save,FEEDBACK_EDIT:e.feedback.edit,FEEDBACK_REMOVE:e.feedback.remove,A11Y_MESSAGE_LIST:e.conversation.a11y_message_list,A11Y_SCROLL_TO_BOTTOM:e.conversation.a11y_scroll_to_bottom,A11Y_SCROLL_TO_NEW_MESSAGES:e.conversation.a11y_scroll_to_new_messages,A11Y_OPEN_CONVERSATION_LIST:e.conversation.a11y_open_conversation_list,A11Y_OPEN_CONVERSATION:e.conversation.a11y_open_conversation,A11Y_OPEN_CONVERSATIONS:e.conversation.a11y_open_conversations,A11Y_CLOSE_CONVERSATION:e.conversation.a11y_close_conversation,A11Y_CLOSE_CONVERSATIONS:e.conversation.a11y_close_conversations,A11Y_MENU:e.conversation.a11y_menu,A11Y_MESSAGE_INPUT:e.conversation.a11y_message_input,A11Y_SEND_MESSAGE:e.conversation.a11y_send_message,A11Y_ATTACH_FILE:e.conversation.a11y_attach_file,A11Y_CONNECT_AGENT:e.conversation.a11y_connect_agent,A11Y_CLOSE_MESSENGER:e.conversation.a11y_close_messenger,A11Y_DISMISS_NUDGE_MESSAGE:e.conversation.a11y_dismiss_nudge_message,A11Y_EXPAND_MESSENGER:e.conversation.a11y_expand_messenger,A11Y_COLLAPSE_MESSENGER:e.conversation.a11y_collapse_messenger,A11Y_MESSAGE_SENDER_YOU:e.conversation.a11y_message_sender_you,A11Y_SUGGESTED_REPLY:e.conversation.a11y_suggested_reply,A11Y_TYPING_INDICATOR:e.conversation.a11y_typing_indicator,A11Y_CODE_BLOCK_PLACEHOLDER:e.conversation.a11y_code_block_placeholder,A11Y_TYPING_FORMAT:e.conversation.a11y_typing_format,A11Y_MESSAGE_FAILED:e.conversation.a11y_message_failed,A11Y_NEW_MESSAGES_RECEIVED:e.conversation.a11y_new_messages_received,A11Y_NEW_MESSAGES_RECEIVED_FROM_SENDER:e.conversation.a11y_new_messages_received_from_sender,A11Y_AGENT_CONNECTED:e.conversation.a11y_agent_connected,A11Y_CONVERSATION_CLOSED:e.conversation.a11y_conversation_closed,A11Y_FILE_IMAGE:e.conversation.a11y_file_image,A11Y_FILE_VIDEO:e.conversation.a11y_file_video,A11Y_FILE_PDF:e.conversation.a11y_file_pdf,A11Y_FILE_DOCUMENT:e.conversation.a11y_file_document,A11Y_RECEIVED_FILE_IMAGE:e.conversation.a11y_received_file_image,A11Y_RECEIVED_FILE_VIDEO:e.conversation.a11y_received_file_video,A11Y_RECEIVED_FILE_PDF:e.conversation.a11y_received_file_pdf,A11Y_RECEIVED_FILES_IMAGE_COUNT:e.conversation.a11y_received_files_image_count,A11Y_SCREEN_CONVERSATION:e.conversation.a11y_screen_conversation,A11Y_SCREEN_CONVERSATION_WITH_AGENT:e.conversation.a11y_screen_conversation_with_agent,A11Y_SCREEN_CONVERSATION_LIST_NO_COUNT:e.conversation.a11y_screen_conversation_list_no_count,A11Y_SCREEN_CONVERSATION_LIST_WITH_COUNT:e.conversation.a11y_screen_conversation_list_with_count,A11Y_CSAT_DISPLAYED:e.conversation.a11y_csat_displayed,A11Y_EMPTY_CONVERSATION:e.conversation.a11y_empty_conversation,A11Y_INPUT_DISABLED:e.conversation.a11y_input_disabled,A11Y_FILE_SIZE_EXCEEDED:e.conversation.a11y_file_size_exceeded,A11Y_CSAT_FORM_ERROR:e.conversation.a11y_csat_form_error,A11Y_HINT_SEND_MESSAGE:e.conversation.a11y_hint_send_message,A11Y_HINT_OPEN_CONVERSATION:e.conversation.a11y_hint_open_conversation,A11Y_HINT_OPEN_CONVERSATIONS:e.conversation.a11y_hint_open_conversations,A11Y_HINT_CLOSE_CONVERSATION:e.conversation.a11y_hint_close_conversation,A11Y_HINT_OPEN_MENU:e.conversation.a11y_hint_open_menu,A11Y_HINT_CONNECT_TO_AGENT:e.conversation.a11y_hint_connect_to_agent,A11Y_HINT_ATTACH_FILE:e.conversation.a11y_hint_attach_file,A11Y_HINT_VIEW_NEW_MESSAGES:e.conversation.a11y_hint_view_new_messages,A11Y_HINT_OPEN_FILE:e.conversation.a11y_hint_open_file,A11Y_HINT_OPEN_IMAGE:e.conversation.a11y_hint_open_image,A11Y_HINT_SEND_REPLY:e.conversation.a11y_hint_send_reply,A11Y_CONVERSATION_ITEM:e.conversation_list.a11y_conversation_item,A11Y_CSAT_RATING_LABEL:e.csat.a11y_csat_rating_label,A11Y_HINT_SELECT_RATING:e.csat.a11y_hint_select_rating,IMAGE_VIEWER__DEFAULT_TITLE:e.conversation.image_viewer_default_title,A11Y_IMAGE_VIEWER_CLOSE:e.conversation.a11y_image_viewer_close,A11Y_IMAGE_VIEWER_PREVIOUS:e.conversation.a11y_image_viewer_previous,A11Y_IMAGE_VIEWER_NEXT:e.conversation.a11y_image_viewer_next,A11Y_IMAGE_VIEWER_DOWNLOAD:e.conversation.a11y_image_viewer_download,SCROLL_TO_NEW_MESSAGES_LABEL:e.conversation.scroll_to_new_messages_label,HANDOFF_CONFIRM__TITLE:e.handoff.confirm_title,HANDOFF_CONFIRM__DESCRIPTION:e.handoff.confirm_description,HANDOFF_CONFIRM__CANCEL:e.handoff.confirm_cancel,HANDOFF_CONFIRM__HANDOFF:e.handoff.confirm_handoff,MEMORY__DIALOG_TITLE:e.memory.dialog_title,MEMORY__DESC_ON:e.memory.desc_on,MEMORY__DESC_OFF:e.memory.desc_off,MEMORY__BUTTON_USE:e.memory.button_use,MEMORY__BUTTON_DONT_USE:e.memory.button_dont_use,MEMORY__BUTTON_KEEP_USING:e.memory.button_keep_using,MEMORY__BUTTON_DISABLE:e.memory.button_disable,MEMORY__BUTTON_DISABLE_AND_DELETE:e.memory.button_disable_and_delete,MEMORY__BUTTON_KEEP_OFF:e.memory.button_keep_off,MEMORY__BUTTON_ENABLE:e.memory.button_enable,MEMORY__BUTTON_CANCEL:e.memory.button_cancel,MEMORY__ERROR_MESSAGE:e.memory.error_message,A11Y_MEMORY_INDICATOR_MANAGE:e.memory.a11y_indicator_manage,A11Y_MEMORY_INDICATOR_ON:e.memory.a11y_indicator_on,A11Y_MEMORY_INDICATOR_OFF:e.memory.a11y_indicator_off,CONNECTION_DELAY__TITLE:e.connection_delay.title,CONNECTION_DELAY__DESCRIPTION:e.connection_delay.description}),oa=e=>{var t;return((t=e.split("-"))==null?void 0:t[0])??en},en="en",ia=new Set([en,"ko","es","pt","fr","hi","it","de","tr","ja"]),xf='@import"https://fonts.googleapis.com/css?family=Roboto:400,500,600,700&display=swap";.sb-message-template__border{position:relative}.sb-message-template__border:after{content:"";position:absolute;top:0;right:0;bottom:0;left:0;z-index:1;box-shadow:inset 0 0 0 var(--border-width) var(--border-color);border-radius:var(--border-radius);pointer-events:none}.sb-message-template__action{cursor:pointer}.sb-message-template__parent{font-family:Roboto,serif}.sb-message-template__text{font-family:inherit;font-size:14px;font-weight:400;font-stretch:normal;font-style:normal;letter-spacing:normal;text-align:left}.sb-message-template__text-button{font-family:inherit;background-color:#e0e0e0;text-align:center;padding:10px;border-radius:6px;font-size:14px;font-weight:600;font-stretch:normal;font-style:normal;letter-spacing:normal}.sendbird-theme--light .sb-message-template__text-button{color:#742ddd}.sendbird-theme--dark .sb-message-template__text-button{color:#c2a9fa}.sb-message-template__text-button:hover{opacity:1;box-shadow:#0000001a 0 1px 3px,#0000000f 0 1px 2px}.sb-message-template__text-button,.sb-message-template__image-button{cursor:pointer;border-style:none}.sb-message-template__parent{border-radius:unset;background-color:transparent;overflow:hidden}.sb-message-template__parent *{box-sizing:border-box;line-height:1.3}.sb-message-template__carousel{display:flex;width:100%;box-sizing:border-box;touch-action:pan-y}',{Provider:Rf,useContext:ss}=be("AgentUIElementResolver"),Mf=({entryElement:e,modalRootElement:t,rootElement:n,children:r})=>{const s=l.useMemo(()=>{const o=n??document.body,i=e??o,c=t??o,u=d=>d===Se.MODAL_ROOT?c:i.querySelector(`#${d}`);return{resolveElement:u,resolvePortalContainer:d=>u(d)??c}},[e,t,n]);return a.createElement(Rf,{value:s},r)};function mt(e,t){const n=e.getRootNode({composed:t});return n instanceof ShadowRoot||n instanceof Document?n:document}const oo=()=>{const e=[];let t=0;const n=new Set,r=()=>n.forEach(s=>s());return{register:s=>{const o=++t;return e.push({id:o,handler:s}),r(),()=>{const i=e.findIndex(c=>c.id===o);i>=0&&(e.splice(i,1),r())}},dismissTopmost:()=>{const s=e[e.length-1];return s?(s.handler(),!0):!1},subscribe:s=>(n.add(s),()=>{n.delete(s)}),getOpenCount:()=>e.length}},{Provider:wf,useContext:os}=be("EscapeDismissStack"),io=e=>{e.stopPropagation(),e.stopImmediatePropagation()},kf=({rootElement:e=document.body,boundaryElement:t,children:n})=>{const r=l.useRef(null),s=l.useRef(null);r.current||(r.current=oo()),s.current||(s.current=oo());const o=r.current,i=s.current;l.useLayoutEffect(()=>{const u=t??mt(e),d=m=>{if(m.key==="Escape"){if(o.dismissTopmost()){io(m);return}i.dismissTopmost()&&io(m)}};return u.addEventListener("keydown",d),()=>u.removeEventListener("keydown",d)},[t,e,i,o]);const c=l.useMemo(()=>({register:o.register,dismissTopmost:o.dismissTopmost,registerShellDismissHandler:i.register,subscribe:o.subscribe,getOpenCount:o.getOpenCount}),[i,o]);return a.createElement(wf,{value:c},n)},aa=(e,t,n)=>{const r=l.useRef(t);l.useLayoutEffect(()=>{r.current=t},[t]),l.useLayoutEffect(()=>{if(e)return n(()=>r.current())},[e,n])},Lf=(e,t)=>{const{register:n}=os();aa(e,t,n)},Of=(e,t)=>{const{registerShellDismissHandler:n}=os();aa(e,t,n)},ca=()=>{const{subscribe:e,getOpenCount:t}=os();return l.useSyncExternalStore(e,()=>t()>0,()=>!1)},Nf=(e,t,n)=>{const r=e[t];return r?typeof r=="function"?r():Promise.resolve(r):new Promise((s,o)=>{(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(o.bind(null,new Error("Unknown variable dynamic import: "+t+(t.split("/").length!==n?". Note that variables only represent file names one level deep.":""))))})},ao=sa(xr.strings),Df={...ao,HEADER_BUTTON__AGENT_HANDOFF:"Talk to human agent",MESSAGE_INPUT__PLACE_HOLDER__SUGGESTED_REPLIES:"Select an option to continue",BUTTON__SUBMIT:"Submit",SUBMITTED:"Submitted",TRY_AGAIN:"Please try again.",FILE_UPLOAD_NOTIFICATION__COUNT_LIMIT:"Up to %d files can be attached.",FILE_UPLOAD_NOTIFICATION__SIZE_LIMIT:"The maximum size per file is %d MB.",FILE_UPLOAD_NOTIFICATION__FILES_EXCLUDED_BY_VALIDATION:"%d files were excluded due to limits. Please select files individually.",FILE_UPLOAD_PHOTOS:"Photos",FILE_VIEWER__UNSUPPORT:"Unsupported message",A11Y_FILE_SELECTED:e=>`${e}, selected`,A11Y_FILE_REMOVE_BUTTON:e=>`Remove file: ${e}`,A11Y_FILE_UPLOAD_OPTIONS:"File upload options",A11Y_FAILED_MESSAGE_OPTIONS:"Failed message options",A11Y_FEEDBACK_OPTIONS:"Feedback options",A11Y_CSAT_TEXT_INPUT_LABEL:"Enter answer",FORM_UNAVAILABLE:"Form is no longer available.",FORM_NOT_SUPPORTED:"This form is not supported in the current version.",FORM_VALIDATION_MIN_LENGTH:e=>`Minimum ${e} characters required`,FORM_VALIDATION_MAX_LENGTH:e=>`Maximum ${e} characters allowed`,FORM_VALIDATION_MIN:e=>`Minimum value is ${e}`,FORM_VALIDATION_MAX:e=>`Maximum value is ${e}`,FORM_VALIDATION_MIN_SELECT:e=>`Select at least ${e} options`,FORM_VALIDATION_MAX_SELECT:e=>`Select at most ${e} options`,FORM_VALIDATION_REGEX_FAILED:"Invalid format",DATE_FORMAT__CONVERSATION_LIST__LIST_ITEM_TITLE:ao.DATE_FORMAT__DATE_SHORT,DATE_FORMAT__CONVERSATION_LIST__LIST_ITEM_TITLE_CAPTION:"h:mma",CONVERSATION_LIST__TOPICS_FALLBACK:"No category",CONVERSATION_CLOSED_FOOTER_LABEL:"Your conversation has ended",START_NEW_CONVERSATION:"💬 Start a new conversation",RETURN_TO_CONVERSATION:"💬 Return to conversation",BUTTON__SAVE:"Save",NO_NAME:"(No name)",CHANNEL_FROZEN:"Channel frozen"},wn={language:xr.language,dateLocale:xr.dateLocale,stringSet:Df},$f=Object.freeze(Object.defineProperty({__proto__:null,default:wn},Symbol.toStringTag,{value:"Module"})),Rr=new Map([[en,wn]]);async function Pf(e){const t=Rr.get(e);if(t)return t;try{if(ia.has(e)){const{default:n}=await Nf(Object.assign({"./languages/de.ts":()=>Promise.resolve().then(()=>require("./cjs/qr4Ghr48.cjs")),"./languages/en.ts":()=>Promise.resolve().then(()=>$f),"./languages/es.ts":()=>Promise.resolve().then(()=>require("./cjs/fdHbDI5i.cjs")),"./languages/fr.ts":()=>Promise.resolve().then(()=>require("./cjs/DsrX4pE_.cjs")),"./languages/hi.ts":()=>Promise.resolve().then(()=>require("./cjs/BoXkkKL_.cjs")),"./languages/it.ts":()=>Promise.resolve().then(()=>require("./cjs/De9EY1XB.cjs")),"./languages/ja.ts":()=>Promise.resolve().then(()=>require("./cjs/DoR1M7Tp.cjs")),"./languages/ko.ts":()=>Promise.resolve().then(()=>require("./cjs/s8NcCXAz.cjs")),"./languages/pt.ts":()=>Promise.resolve().then(()=>require("./cjs/D3Aoub0b.cjs")),"./languages/tr.ts":()=>Promise.resolve().then(()=>require("./cjs/D-lytti9.cjs"))}),`./languages/${e}.ts`,3);return Rr.set(e,n),n}return wn}catch{return wn}}const{Provider:Ff,useContext:ie}=be("Localization"),Uf=({language:e=navigator.language,languageCode:t,logger:n,stringSet:r,children:s})=>{const[o,i]=l.useState(Rr.get(en));return l.useEffect(()=>{const c=t??oa(e);o.language!==c&&(n==null||n.debug("localization.useEffect: update language",{from:o.language,to:c}),Pf(c).then(i))},[e,t,n]),a.createElement(Ff,{value:{language:o.language,defaultStringSet:o.stringSet,stringSet:{...o.stringSet,...r},dateLocale:o.dateLocale,format:(c,u,d)=>ut.format(c,u,{locale:o.dateLocale,...d})}},s)},kn="data-sb-agent-theme",co=e=>(t,...n)=>{let r="";return t.forEach((s,o)=>{r+=s+(n[o]??"")}),`[${kn}='${e}'] & { ${r} }`},ne={light:co("light"),dark:co("dark")},Bf=U.css(({theme:e})=>{const{palette:t}=e;return`
|
|
10
|
+
`),r=Wr(t);return r.map((s,o)=>{var c;if(s.kind!=="text")return s.value;const i=n(s.value);return((c=r[o-1])==null?void 0:c.kind)!=="span"?i:i.replace(/^([ \t]*)\n(?![ \t]*\n)/,`$1
|
|
11
|
+
`)}).join("")},yr=(...e)=>(t,n)=>e.reduce((r,s)=>s(r,n),t),Ps=yr(il(yr(Ds(dl,{anchorsLineEnd:!0}),al,Ds(cl),ml)),ul),fl=({convertSoftBreaks:e=!1}={})=>e?yr(hl,Ps):Ps,Ai=typeof navigator<"u"&&navigator.product==="ReactNative",gl=(e,t)=>{for(let n=0;n<e.length;n++){const r=Ai?n:e.length-1-n,s=e[r];if(s&&t(s)==="stop")return}},Ar=(e,t)=>{const n=r=>!t||t.length===0?!0:Xe(r)&&t.includes(r.sendingStatus);return Ai?e.find(n):e.findLast(n)},pl=(e,t)=>{const n=Ar(e,[we.SendingStatus.SUCCEEDED]);return n&&Le.isIncoming(n,t)?n:void 0},Re=e=>{requestAnimationFrame(()=>{requestAnimationFrame(e)})};function Ee(){}function El(){const e=typeof navigator<"u"?navigator.userAgent:"",t=/iPad|iPhone|iPod/.test(e),n=/Android/.test(e);return t||n}function _l(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 Ae={isStreaming(e){return Wc(e.data)},isExplicitWelcomeMessage(e){var t;return((t=e.extendedMessagePayload)==null?void 0:t.bot_message_type)==="welcome"},isWelcomeMessage(e,t){var r;if(Ae.isExplicitWelcomeMessage(e))return!0;if(((r=e.extendedMessagePayload)==null?void 0:r.bot_message_type)!==void 0||!Fe(e,t))return!1;const n=Kr(e.data);return!n.isStreaming&&!n.hasResponseMetadata},isGeneratedMessage(e){var t;return((t=e.extendedMessagePayload)==null?void 0:t.bot_message_type)==="generated"},hasFeedback(e){var t;return!!((t=e.extendedMessagePayload)!=null&&t.feedback)}},rr=`@${kt}`,Cl=({appId:e,aiAgentId:t,storage:n})=>{const r={templateBase:`${rr}-template`,template:s=>`${r.templateBase}/templates/${s}`,templateToken:()=>`${r.templateBase}/tokens`,messengerSession:s=>{const o=_l(`${e}/${t}/${s}`);return`${rr}-udata/${o}`},anonUserSession:()=>`${rr}-session/${e}/${t}`};return{template:{set:(s,o)=>n.set(r.template(s),o),get:s=>n.get(r.template(s)),setCachedToken:s=>n.set(r.templateToken(),s),getCachedToken:()=>n.get(r.templateToken()),clear:()=>{n.getKeys(r.templateBase).forEach(n.delete)}},messenger:{getSettings:s=>{try{const o=n.get(r.messengerSession(s));return o?JSON.parse(o):null}catch{return null}},setSettings:(s,o)=>{try{delete o.auto_created_user;const i=JSON.stringify(o);n.set(r.messengerSession(s),i)}catch{return}},getAnonUser:()=>{try{const s=n.get(r.anonUserSession());return s?JSON.parse(s):null}catch{return null}},setAnonUser:s=>{try{const o=JSON.stringify(s);n.set(r.anonUserSession(),o)}catch{return}},clear:s=>{try{s&&n.delete(r.messengerSession(s)),n.delete(r.anonUserSession())}catch{return}}}}},Ti=(e,t,n={})=>{let r=null,s=null,o=null;const{leading:i=!0,trailing:c=!0}=n,u=(...d)=>{const m=Date.now();if(o===null||m-o>=t)i?(e(...d),o=m):(s=d,o=m);else if(s=d,c&&!r){const h=t-(m-o);r=setTimeout(()=>{s&&c&&(e(...s),o=Date.now()),r=null,s=null},h)}};return u.cancel=()=>{r&&(clearTimeout(r),r=null),s=null,o=null},u},Sl=()=>{let e=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const n=(e+Math.random()*16)%16|0;return e=Math.floor(e/16),(t==="x"?n:n&3|8).toString(16)})};class bl{constructor(t){S(this,"_params");this._params={aiAgentChannelFilter:(t==null?void 0:t.aiAgentChannelFilter)??Ce.AIAgentChannelFilter.INCLUDE,aiAgentConversationStatusFilter:(t==null?void 0:t.aiAgentConversationStatusFilter)??[Ce.ConversationStatus.OPEN,Ce.ConversationStatus.CLOSED],aiAgentIds:(t==null?void 0:t.aiAgentIds)??[],deskChannelFilter:(t==null?void 0:t.deskChannelFilter)??Ce.DeskChannelFilter.INCLUDE,pinnedChannelUrls:(t==null?void 0:t.pinnedChannelUrls)??[],copilotConversationOnly:(t==null?void 0:t.copilotConversationOnly)??!1,copilotSupportChannelUrl:t==null?void 0:t.copilotSupportChannelUrl}}get params(){return{...this._params}}match(t,n){const{pinnedChannelUrls:r,aiAgentChannelFilter:s,aiAgentConversationStatusFilter:o,aiAgentIds:i,deskChannelFilter:c}=this._params;return r!=null&&r.includes(t.url)?!0:t.isAIAgent?!(!t.conversation||s===Ce.AIAgentChannelFilter.EXCLUDE||i&&i.length>0&&!i.includes(t.conversation.aiAgentId)||o&&o.length>0&&!o.some(d=>{var m;return((m=t.conversation)==null?void 0:m.status)===d})):t.isDesk?c!==Ce.DeskChannelFilter.EXCLUDE:!1}}class Ii extends rt.BaseChannelCollection{constructor(n,r){const s=new bl(r.filter),o=n,i=o.aiAgent._manager,c=r.limit??20,u=rt.GroupChannelListOrder.LATEST_LAST_MESSAGE,d={getRemoteChannels:(m,h,f,g)=>i.getMyGroupChannels(m,h.params,g),changeLogSync:m=>{const{aiAgentChannelFilter:h,aiAgentIds:f,deskChannelFilter:g,pinnedChannelUrls:p,copilotConversationOnly:C,copilotSupportChannelUrl:E}=s.params,_={aiAgentChannelFilter:h,aiAgentIds:f,deskChannelFilter:g,pinnedChannelUrls:p,copilotConversationOnly:C,copilotSupportChannelUrl:E};return i.getMyGroupChannelChangeLogs(m,_,rt.GroupChannelEventSource.SYNC_CHANNEL_CHANGELOGS)}};super(o.aiAgent._iid,{filter:s,order:u,limit:c,syncKeyPrefix:"aiAgent",fetcher:d});S(this,"_params");S(this,"_sdk");S(this,"_throttledOnChannelChanged");S(this,"_key");S(this,"_pendingChannels",[]);this._sdk=n,this._params=r,this._key=`clc-${Sl()}`,this._throttledOnChannelChanged=Ti(()=>{var g;const m=[...this._pendingChannels];this._pendingChannels=[];const h=new Map;for(const{channel:p,context:C}of m)h.delete(p.url),h.set(p.url,{channel:p,context:C});const f=new Map;for(const{channel:p,context:C}of h.values())f.has(C)||f.set(C,new Map),f.get(C).set(p.url,p);for(const[p,C]of f){const E=Array.from(C.values()),_=(g=this._sdk.currentUser)==null?void 0:g.userId,A=E.filter(T=>this.filter.match(T,_)),y=E.filter(T=>!this.filter.match(T,_)).map(T=>T.url);A.length>0&&this._base._addChannelsToView(A,p,!1),y.length>0&&this._removeChannels(y,p)}},250,{trailing:!0,leading:!0}),this._base._subscribeChannelEvent(this._key,{onUpdate:(m,h)=>{for(const f of m)this._pendingChannels.push({channel:f,context:h});this._throttledOnChannelChanged()},onRemove:(m,h)=>{this._removeChannels(m,h)}})}get _base(){return this}_removeChannels(n,r){const s=new Set(n);this._pendingChannels=this._pendingChannels.filter(({channel:o})=>!s.has(o.url)),this._base._removeChannelsFromView(n,r)}get channels(){var c;const n=((c=this._params.filter)==null?void 0:c.pinnedChannelUrls)??[],r=[],s=new Map(super.channels.map(u=>[u.url,u])),o=new Set;for(const u of n){const d=s.get(u);d&&!o.has(u)&&(r.push(d),o.add(u))}const i=super.channels.filter(u=>!o.has(u.url));return[...r,...i]}setConversationListCollectionHandler(n){super.setGroupChannelCollectionHandler(n)}dispose(){super.dispose(),this._throttledOnChannelChanged.cancel(),this._base._unsubscribeChannelEvent(this._key)}}class xi{constructor(t){S(this,"subscribers",{});this.logger=t}async send(t){const n=vl(),r=this.subscribers[t.type];if(r){this.logger.debug(`messenger.dispatcher: dispatching command: ${t.type}`,t.payload);const s=r.map(o=>o(t.payload));await Promise.all(s).catch(o=>{this.logger.error(`messenger.dispatcher: error in callback for command: ${t.type}`,o)})}return n.resolve(),n.promise}subscribe(t,n){this.subscribers[t]||(this.subscribers[t]=[]),this.subscribers[t].push(n)}unsubscribe(t,n){const r=this.subscribers[t];r&&(this.subscribers[t]=r.filter(s=>s!==n))}}const vl=()=>{let e=Ee,t=Ee;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}};var Ge=(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.NudgeMessageReceived="nudge.message.received",e))(Ge||{});class Ft{constructor(t={}){S(this,"payload");this.payload=t}toJSON(){return JSON.stringify({type:this.type,payload:this.payload})}}const ut={CloseConversation:e=>new yl(e),MessengerSettingsUpdated:e=>new Al(e),ActiveChannelUpdated:e=>new Tl(e),AnonymousSessionTokenExpired:()=>new Il,AuthTokenRefreshed:()=>new xl,NudgeMessageReceived:e=>new Ml(e)};class yl extends Ft{constructor(){super(...arguments);S(this,"type","conv.close")}}class Al extends Ft{constructor(){super(...arguments);S(this,"type","messenger.settings.updated")}}class Tl extends Ft{constructor(){super(...arguments);S(this,"type","active.channel.updated")}}class Il extends Ft{constructor(){super(...arguments);S(this,"type","anon.token.expired")}}class xl extends Ft{constructor(){super(...arguments);S(this,"type","auth.token.refreshed")}}class Ml extends Ft{constructor(){super(...arguments);S(this,"type","nudge.message.received")}}const Ut=e=>{const t={};for(const n of Object.keys(e)){const r=e[n];r!==void 0&&(t[n]=String(r))}return t};class rn{constructor(t){S(this,"category","connection");this.userId=t}get data(){return Ut({user_id:this.userId})}}class Rl extends rn{constructor(){super(...arguments);S(this,"metricKey","connection_connected")}}class kl extends rn{constructor(){super(...arguments);S(this,"metricKey","connection_reconnect_started")}}class wl extends rn{constructor(){super(...arguments);S(this,"metricKey","connection_reconnect_succeeded")}}class Ll extends rn{constructor(){super(...arguments);S(this,"metricKey","connection_reconnect_failed")}}class Ol extends rn{constructor(){super(...arguments);S(this,"metricKey","connection_disconnected")}}class Nl{constructor(t){S(this,"lastKey",null);this.dispatch=t}handleEvent({detail:t,userId:n}){const r=`${t}:${n}`;if(this.shouldEmit(r)){this.lastKey=r;const s=t==="connected"?new Rl(n):t==="reconnectStarted"?new kl(n):t==="reconnectSucceeded"?new wl(n):t==="reconnectFailed"?new Ll(n):new Ol(n);this.dispatch(s)}}shouldEmit(t){return t!==this.lastKey}}class Yr{constructor(t,n){S(this,"category","conversation");this.channelUrl=t,this.conversationId=n}get data(){return Ut({channel_url:this.channelUrl,conversation_id:this.conversationId})}}class Dl extends Yr{constructor(){super(...arguments);S(this,"metricKey","conversation_initialized")}}class Pl extends Yr{constructor(){super(...arguments);S(this,"metricKey","conversation_open")}}class $l extends Yr{constructor(){super(...arguments);S(this,"metricKey","conversation_closed")}}class Fl{constructor(t){S(this,"statusByChannel",new Map);this.dispatch=t}handleEvent({channel:t}){const{conversation:n}=t;if(!n)return;const r=this.statusByChannel.get(t.url),s=n.status;if(this.statusByChannel.set(t.url,s),this.shouldEmit(r,s)){const o=s===Ce.ConversationStatus.INITIALIZED?new Dl(t.url,n.id):s===Ce.ConversationStatus.OPEN?new Pl(t.url,n.id):new $l(t.url,n.id);this.dispatch(o)}}shouldEmit(t,n){return n===Ce.ConversationStatus.INITIALIZED?t===void 0:n===Ce.ConversationStatus.OPEN?t===Ce.ConversationStatus.INITIALIZED:t===Ce.ConversationStatus.OPEN}}const Mi=(e,t)=>{if(e)return e.members.filter(n=>n.userId!==t).sort((n,r)=>r.joinedAt-n.joinedAt)[0]},$e=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===Ce.ConversationStatus.CLOSED||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="closed")},jr=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===Ce.ConversationStatus.OPEN||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="open")};function dt(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 Ul(e){var r;const t=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff;return t?typeof t.requestedAt=="number"&&!dt(e):!1}function Bl(e){var t;if(((t=e==null?void 0:e.resolution)==null?void 0:t.determinedBy)==="user")return e.resolution.isResolved}function Ri(e){return!!e&&e<=Date.now()}function Hl(e){return!e.title}function Gl(e,t){var n;if(e)return Hl(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 Xr{constructor(t,n){S(this,"category","handoff");this.channelUrl=t,this.conversationId=n}get data(){return Ut({channel_url:this.channelUrl,conversation_id:this.conversationId})}}class zl extends Xr{constructor(){super(...arguments);S(this,"metricKey","handoff_started")}}class Vl extends Xr{constructor(){super(...arguments);S(this,"metricKey","handoff_succeeded")}}class Kl extends Xr{constructor(){super(...arguments);S(this,"metricKey","handoff_failed")}}class ql{constructor(t){S(this,"statusByChannel",new Map);this.dispatch=t}handleEvent({channel:t}){const n=!this.statusByChannel.has(t.url);n&&this.statusByChannel.set(t.url,void 0);const r=t.conversation;if(!r||!r.handoff||n)return;const s=this.statusByChannel.get(t.url),o=this.resolveStatus(t,r);if(o!==void 0&&this.shouldEmit(s,o)){this.statusByChannel.set(t.url,o);const i=o==="started"?new zl(t.url,r.id):o==="succeeded"?new Vl(t.url,r.id):new Kl(t.url,r.id);this.dispatch(i)}}resolveStatus(t,n){if($e(t))return"failed";const{members:r}=t;if(r.length===1)return"started";if(r.length===2&&n.aiAgentId&&!r.some(s=>s.userId===n.aiAgentId))return"succeeded"}shouldEmit(t,n){return n==="started"?t===void 0:t==="started"}}class Wl{constructor(t){S(this,"category","message");S(this,"metricKey","incoming_message_received");S(this,"channelUrl");S(this,"messageId");S(this,"senderType");S(this,"createdAt");S(this,"conversationId");this.channelUrl=t.channelUrl,this.messageId=t.messageId,this.senderType=t.senderType,this.createdAt=t.createdAt,this.conversationId=t.conversationId}get data(){return Ut({channel_url:this.channelUrl,message_id:this.messageId,sender_type:this.senderType,created_at:this.createdAt,conversation_id:this.conversationId})}}const Yl=(e,t)=>{const n=Xe(e)?e.sender.userId:void 0;return n===void 0?"system":n===t?"ai_agent":"human_agent"};class jl{constructor(t,n){this.dispatch=t,this.getCurrentUserId=n}handleEvent({channel:t,message:n}){const{conversation:r}=t;this.shouldEmit(n,r)&&this.dispatch(new Wl({channelUrl:t.url,messageId:n.messageId,senderType:Yl(n,r.aiAgentId),createdAt:n.createdAt,conversationId:r.id}))}shouldEmit(t,n){return!Fe(t,this.getCurrentUserId())&&n!==null}}class Zr{constructor(t){S(this,"category","memory");S(this,"action");S(this,"deleteOnOff");S(this,"userId");this.action=t.action,this.deleteOnOff=t.deleteOnOff,this.userId=t.userId}get data(){return Ut({action:this.action,delete_on_off:this.deleteOnOff,user_id:this.userId})}}class Xl extends Zr{constructor(){super(...arguments);S(this,"metricKey","memory_consent")}}class Zl extends Zr{constructor(){super(...arguments);S(this,"metricKey","memory_on")}}class Jl extends Zr{constructor(){super(...arguments);S(this,"metricKey","memory_off")}}const Ql={consent:{Metric:Xl,actions:{shown:"shown",confirm:"enable",cancel:"disable"}},on:{Metric:Zl,actions:{shown:"shown",confirm:"keep",cancel:"disable",dismiss:"dismiss"}},off:{Metric:Jl,actions:{shown:"shown",confirm:"keep",cancel:"enable",dismiss:"dismiss"}}};class eu{constructor(t,n){this.dispatch=t,this.getCurrentUserId=n}handleEvent({variant:t,action:n,deleteOnOff:r}){if(t==="readonly")return;const{Metric:s,actions:o}=Ql[t],i=o[n];i&&this.dispatch(new s({action:i,deleteOnOff:t==="on"?r:void 0,userId:this.getCurrentUserId()}))}}class tu{constructor(t){S(this,"category","message");S(this,"metricKey");S(this,"channelUrl");S(this,"requestId");S(this,"messageId");S(this,"target");S(this,"sendingStatus");S(this,"createdAt");S(this,"conversationId");this.channelUrl=t.channelUrl,this.requestId=t.requestId,this.messageId=t.messageId,this.target=t.target,this.sendingStatus=t.sendingStatus,this.createdAt=t.createdAt,this.conversationId=t.conversationId,this.metricKey=`outgoing_message_${t.sendingStatus}`}get data(){return Ut({channel_url:this.channelUrl,request_id:this.requestId,message_id:this.messageId,target:this.target,created_at:this.createdAt,conversation_id:this.conversationId})}}const nu=e=>{switch(e){case we.SendingStatus.PENDING:return"pending";case we.SendingStatus.SUCCEEDED:return"succeeded";case we.SendingStatus.FAILED:return"failed";case we.SendingStatus.SCHEDULED:return"scheduled";default:return}};class ru{constructor(t,n){S(this,"statusByReqId",new Map);this.dispatch=t,this.getCurrentUserId=n}handleEvent({channel:t,message:n}){var o;if(!Fe(n,this.getCurrentUserId()))return;const r=nu(n.sendingStatus);if(r===void 0)return;const s=this.statusByReqId.get(n.reqId);this.statusByReqId.set(n.reqId,r),r!=="scheduled"&&this.shouldEmit(s,r)&&this.dispatch(new tu({channelUrl:t.url,requestId:n.reqId,messageId:r==="succeeded"?n.messageId:void 0,target:dt(t)?"human_agent":"ai_agent",sendingStatus:r,createdAt:n.createdAt,conversationId:(o=t.conversation)==null?void 0:o.id}))}shouldEmit(t,n){return n==="pending"?t!=="pending"&&t!=="succeeded":n==="succeeded"?t==="pending"||t==="scheduled":t!=="failed"}}class su{constructor(t){S(this,"id","aiagent_livemetric");S(this,"dispatch");S(this,"emit",({category:t,metricKey:n,data:r})=>{var s;(s=this.dispatch)==null||s.call(this,{category:t,metricKey:n,data:r})});S(this,"emitters");this.chatSDK=t;const n=()=>{var r;return(r=this.chatSDK.currentUser)==null?void 0:r.userId};this.emitters={connection:new Nl(this.emit),conversation:new Fl(this.emit),handoff:new ql(this.emit),incomingMessage:new jl(this.emit,n),outgoingMessage:new ru(this.emit,n),memory:new eu(this.emit,n)}}start(){const t=new _e.ConnectionHandler({onConnected:r=>this.trackConnection("connected",r),onDisconnected:r=>this.trackConnection("disconnected",r),onReconnectStarted:()=>this.trackConnection("reconnectStarted"),onReconnectSucceeded:()=>this.trackConnection("reconnectSucceeded"),onReconnectFailed:()=>this.trackConnection("reconnectFailed")}),n=new rt.GroupChannelHandler({onMessageReceived:(r,s)=>{r.isGroupChannel()&&this.track({type:"incomingMessage",channel:r,message:s})},onChannelChanged:r=>{r.isGroupChannel()&&(this.track({type:"handoff",channel:r}),this.track({type:"conversation",channel:r}))},onUserJoined:r=>this.track({type:"handoff",channel:r}),onUserLeft:r=>this.track({type:"handoff",channel:r})});this.chatSDK.addConnectionHandler(this.id,t),this.chatSDK.groupChannel.addGroupChannelHandler(this.id,n)}track(t){try{this.emitters[t.type].handleEvent(t)}catch{}}dispose(){this.chatSDK.removeConnectionHandler(this.id),this.chatSDK.groupChannel.removeGroupChannelHandler(this.id)}trackConnection(t,n=(r=>(r=this.chatSDK.currentUser)==null?void 0:r.userId)()){n&&this.track({type:"connection",detail:t,userId:n})}}var Jr=(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))(Jr||{});class ki{constructor(t){S(this,"level");this.level=t}verbose(...t){this.level<=0&&console.log(`[${kt}/verbose]`,...t)}debug(...t){this.level<=1&&console.log(`[${kt}/debug]`,...t)}info(...t){this.level<=2&&console.log(`[${kt}/info]`,...t)}warn(...t){this.level<=3&&console.warn(`[${kt}/warn]`,...t)}error(...t){this.level<=4&&console.error(`[${kt}/error]`,...t)}}class wi{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 Tr{constructor(){S(this,"userId");S(this,"authToken");S(this,"sessionHandler")}}const ou=e=>({onSessionTokenRequired:t=>{t(null),e.send(ut.AnonymousSessionTokenExpired())}}),Qr=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!=null)),iu="ai_agent:stats",es="ai_agent:assertion",au="conversation_initial_render",cu="conversation_not_interactive_timeout",lu="recovery_not_interactive_timeout",uu="conversation_list_initial_render",du="message_pending_stuck",mu="aiev_auth_expired_unhandled",hu="user_perceived_response_time",fu="stream_stalled",gu="ai_typing_indicator_absent_timeout",pu="rendered_content_unusable",Eu="streaming_message_validation",_u="duplicate_message_response",Cu="message_lifecycle_event",Su=800220;var X=(e=>(e.ACK_TO_FIRST_CHUNK="ack_to_first_chunk_ms",e.AFTER_TPEN_ABSENT="after_tpen_absent_ms",e.AUTH="auth_duration_ms",e.BEFORE_TPST_ABSENT="before_tpst_absent_ms",e.FIRST_CHUNK_TO_RENDER="first_chunk_to_render_ms",e.GET_CHANNEL="get_channel_duration_ms",e.GET_LIST="get_list_duration_ms",e.GET_MESSAGES="get_messages_duration_ms",e.PAGE_RENDER="page_render_duration_ms",e.PAGE_RENDER_FROM_CACHE="total_duration_from_cache_ms",e.SEND_TO_ACK="send_to_ack_ms",e.TIMEOUT="timeout_ms",e))(X||{});const Ir=(e,t)=>e.startAt===null||e.endedAt===null||t.startAt===null||t.endedAt===null?0:Math.max(0,Math.min(e.endedAt,t.endedAt)-Math.max(e.startAt,t.startAt)),Li=e=>typeof e=="object"&&e!==null,bu=e=>{if(Li(e))return typeof e.code=="number"?e.code:void 0},vu=e=>e instanceof Error?e.message:typeof e=="string"?e:Li(e)&&typeof e.message=="string"?e.message:"";class qe{constructor(){S(this,"timers",new Map);S(this,"committed",!1);S(this,"commitCallback",null);S(this,"conversationId",null);S(this,"errorCode",null);S(this,"errorDescription",null);S(this,"extraData",{})}getStatType(){return iu}setCommitCallback(t){return this.commitCallback=t,this}setConversationId(t){return t&&(this.conversationId=t),this}setError(t){return t==null?this:(this.errorCode=bu(t)??Su,this.errorDescription=vu(t),this)}setExtra(t,n){return n!=null&&(this.extraData[t]=n),this}startTimer(t){if(this.committed)return this;const n=this.timers.get(t);return(n==null?void 0:n.startTime)!==null&&(n==null?void 0:n.startTime)!==void 0?this:(this.timers.set(t,{startTime:performance.now(),endTime:null}),this)}stopTimer(t){if(this.committed)return this;const n=this.timers.get(t);return!n||n.startTime===null||n.endTime!==null?this:(this.timers.set(t,{...n,endTime:performance.now()}),this)}getTimer(t){const n=this.timers.get(t);return!n||n.startTime===null?{startAt:null,endedAt:null,duration:null}:{startAt:n.startTime,endedAt:n.endTime,duration:n.endTime===null?null:n.endTime-n.startTime}}createPayload(t,n){const r={key:this.getMetricKey(),value:String(t)},s=(n==null?void 0:n.conversationId)??this.conversationId??void 0;s!==void 0&&(r.conversation_id=s),this.errorCode!==null&&(r.error_code=this.errorCode,r.error_description=this.errorDescription??"");const o=Qr({...this.extraData,...n==null?void 0:n.extra});return Object.keys(o).length>0&&(r.extra=o),r}isCommitted(){return this.committed}discard(){this.committed=!0}commit(){if(this.committed||!this.commitCallback)return!1;const t=this.buildPayload();return t?(this.committed=!0,this.commitCallback(this.getStatType(),t)):!1}}class $s extends qe{constructor(){super(...arguments);S(this,"reason");S(this,"aiAgentId")}setReason(n){return this.reason=n,this}setAIAgentId(n){return this.aiAgentId=n,this}getMetricKey(){return mu}buildPayload(){return this.reason===void 0||this.aiAgentId===void 0?null:this.createPayload(this.reason,{extra:{agent_id:this.aiAgentId}})}}class Bt{constructor(t){S(this,"commitCallback");this.commitCallback=t}}class At extends Bt{constructor(){super(...arguments);S(this,"records",new Map)}}class Oi extends Bt{constructor(){super(...arguments);S(this,"activeSpan",null);S(this,"visible",!0)}setVisible(n){var r;this.visible=n,(r=this.activeSpan)==null||r.onVisibilityChanged(n)}}class ts{constructor(t,n){S(this,"stats");S(this,"visible");S(this,"completedHidden",!1);this.stats=t,this.visible=n}get isRecording(){return this.stats!==null&&!this.stats.isCommitted()}onVisibilityChanged(t){this.stats&&(this.visible=t,t&&this.completedHidden&&(this.stats.commit(),this.stats=null))}commitOrDefer(){if(this.stats){if(!this.visible){this.completedHidden=!0;return}this.stats.commit(),this.stats=null}}cancel(){this.stats=null}}const vt=(e,t)=>!(e&&t&&e!==t),xr=(e,t)=>{for(const n of e)if(n.measure.userMessageId===void 0&&vt(n.measure.channelUrl,t))return!0;return!1},sn=(e,t)=>{if(e.size<t)return;const n=e.keys().next();n.done||e.delete(n.value)};class yu extends Bt{onPayloadParseFailed(t){new $s().setReason("payload_parse_failed").setAIAgentId(t.aiAgentId).setCommitCallback(this.commitCallback).commit()}onCallbackNotFound(t){new $s().setReason("callback_not_found").setAIAgentId(t.aiAgentId).setCommitCallback(this.commitCallback).commit()}clear(){}}class Au extends qe{constructor(){super(...arguments);S(this,"channelUrl",null);S(this,"presentMethod","direct_present")}setChannelUrl(n){return this.channelUrl=n,this}setPresentMethod(n){return this.presentMethod=n,this}resetPageRenderSpan(){return this.timers.delete(X.PAGE_RENDER),this.timers.delete(X.PAGE_RENDER_FROM_CACHE),this.timers.delete(X.GET_CHANNEL),this.timers.delete(X.GET_MESSAGES),this.conversationId=null,this.channelUrl=null,this.errorCode=null,this.errorDescription=null,this}getMetricKey(){return au}buildPayload(){const n=this.getTimer(X.AUTH),r=this.getTimer(X.PAGE_RENDER),s=this.getTimer(X.PAGE_RENDER_FROM_CACHE);if(r.duration===null&&(this.errorCode===null||n.duration===null))return null;const o=r.duration===null?0:r.duration-Ir(n,r),i=s.duration===null?null:s.duration-Ir(n,s);return this.createPayload((n.duration??0)+o,{extra:{channel_url:this.channelUrl,present_method:this.presentMethod,[X.AUTH]:n.duration,[X.GET_CHANNEL]:this.getTimer(X.GET_CHANNEL).duration,[X.GET_MESSAGES]:this.getTimer(X.GET_MESSAGES).duration,[X.PAGE_RENDER_FROM_CACHE]:i}})}}class Tu extends ts{constructor(n,r,s){var o;super(n,s);S(this,"measure");this.measure={channelUrl:r,pageRenderState:"initialized"},(o=this.stats)==null||o.setChannelUrl(r).startTimer(X.PAGE_RENDER).startTimer(X.PAGE_RENDER_FROM_CACHE)}onGetChannelStart(n){!this.stats||n!==this.measure.channelUrl||this.measure.pageRenderState!=="initialized"||(this.stats.startTimer(X.GET_CHANNEL),this.measure.pageRenderState="channel_fetching")}onGetChannelComplete(n,r){!this.stats||n!==this.measure.channelUrl||this.measure.pageRenderState!=="channel_fetching"||(this.stats.stopTimer(X.GET_CHANNEL).setConversationId(r),this.measure.pageRenderState="channel_fetched")}onGetChannelError(n,r){!this.stats||n!==this.measure.channelUrl||this.measure.pageRenderState!=="channel_fetching"||(this.stats.stopTimer(X.GET_CHANNEL).setError(r).stopTimer(X.PAGE_RENDER),this.measure.pageRenderState="channel_failed",this.tryFinalize())}onGetMessagesStart(){!this.stats||this.measure.pageRenderState!=="channel_fetched"||(this.stats.startTimer(X.GET_MESSAGES),this.measure.pageRenderState="messages_fetching")}onGetMessagesCacheComplete(n,r){!this.stats||n!==this.measure.channelUrl||r||this.measure.pageRenderState!=="messages_fetching"||this.stats.stopTimer(X.PAGE_RENDER_FROM_CACHE)}onGetMessagesComplete(n,r){!this.stats||n!==this.measure.channelUrl||this.measure.pageRenderState!=="messages_fetching"||(this.stats.stopTimer(X.GET_MESSAGES).setError(r),this.measure.pageRenderState="messages_fetching_completed")}onRendered(){!this.stats||this.measure.pageRenderState!=="messages_fetching_completed"||(this.stats.stopTimer(X.PAGE_RENDER),this.tryFinalize())}onRenderDiscarded(){!this.stats||this.measure.pageRenderState!=="messages_fetching_completed"||(this.stats.discard(),this.stats=null)}onAuthSettled(){this.tryFinalize()}tryFinalize(){if(!this.stats||this.stats.getTimer(X.PAGE_RENDER).endedAt===null)return;const n=this.stats.getTimer(X.AUTH);if(!(n.startAt!==null&&n.endedAt===null)){if(this.measure.pageRenderState==="channel_failed"){this.stats.commit(),this.stats=null;return}this.commitOrDefer()}}}class Iu extends Oi{constructor(){super(...arguments);S(this,"stats",null);S(this,"authState","idle");S(this,"presentMethod","direct_present")}getOrCreateStats(){var n;return(n=this.stats)!=null&&n.isCommitted()?null:(this.stats||(this.stats=new Au().setCommitCallback(this.commitCallback).setPresentMethod(this.presentMethod)),this.stats)}getActiveStats(){return!this.stats||this.stats.isCommitted()?null:this.stats}setPresentMethod(n){var r;this.presentMethod=n,(r=this.getActiveStats())==null||r.setPresentMethod(n)}onAuthStart(){var n,r;if((n=this.stats)!=null&&n.isCommitted()){if(this.authState!=="failed"||this.activeSpan!==null)return;this.stats=null,this.authState="idle"}this.authState==="idle"&&(this.authState="in_progress",(r=this.getOrCreateStats())==null||r.startTimer(X.AUTH))}onAuthComplete(){var n,r;this.authState==="in_progress"&&(this.authState="completed",(n=this.getActiveStats())==null||n.stopTimer(X.AUTH)),(r=this.activeSpan)==null||r.onAuthSettled()}onAuthError(n){var r,s;this.authState==="in_progress"&&(this.authState="failed",(r=this.getActiveStats())==null||r.stopTimer(X.AUTH).setError(n).commit(),(s=this.activeSpan)==null||s.cancel())}startSpan(n){const r=this.activeSpan;r==null||r.cancel();const s=this.getOrCreateStats();return s&&r&&s.resetPageRenderSpan(),this.activeSpan=new Tu(s,n,this.visible),this.activeSpan}clear(){var n;(n=this.activeSpan)==null||n.cancel(),this.activeSpan=null,this.stats=null,this.authState="idle"}}class xu extends qe{constructor(){super(...arguments);S(this,"presentMethod","direct_present")}setPresentMethod(n){return this.presentMethod=n,this}resetPageRenderSpan(){return this.timers.delete(X.PAGE_RENDER),this.timers.delete(X.GET_LIST),this.errorCode=null,this.errorDescription=null,this}getMetricKey(){return uu}buildPayload(){const n=this.getTimer(X.AUTH),r=this.getTimer(X.PAGE_RENDER),s=this.getTimer(X.GET_LIST).duration;if(r.duration===null&&(this.errorCode===null||n.duration===null))return null;const o=r.duration===null?0:r.duration-Ir(n,r),i=(n.duration??0)+o;return this.createPayload(i,{extra:{present_method:this.presentMethod,[X.AUTH]:n.duration,[X.GET_LIST]:s}})}}class Mu extends ts{constructor(n,r){var s;super(n,r);S(this,"measure",{listStarted:!1,listCompleted:!1});(s=this.stats)==null||s.startTimer(X.PAGE_RENDER)}onListRequestStart(){!this.stats||this.measure.listStarted||(this.stats.startTimer(X.PAGE_RENDER),this.stats.startTimer(X.GET_LIST),this.measure.listStarted=!0)}onListRequestComplete(n){if(!(!this.stats||!this.measure.listStarted||this.measure.listCompleted)){if(n){this.stats.resetPageRenderSpan(),this.measure.listStarted=!1;return}this.stats.stopTimer(X.GET_LIST),this.measure.listCompleted=!0}}onRendered(){!this.stats||!this.measure.listCompleted||(this.stats.stopTimer(X.PAGE_RENDER),this.tryFinalize())}onRenderDiscarded(){!this.stats||!this.measure.listCompleted||(this.stats.discard(),this.stats=null)}onAuthSettled(){this.tryFinalize()}tryFinalize(){if(!this.stats||this.stats.getTimer(X.PAGE_RENDER).endedAt===null)return;const n=this.stats.getTimer(X.AUTH);n.startAt!==null&&n.endedAt===null||this.commitOrDefer()}}class Ru extends Oi{constructor(){super(...arguments);S(this,"stats",null);S(this,"authState","idle");S(this,"presentMethod","direct_present")}getOrCreateStats(){var n;return(n=this.stats)!=null&&n.isCommitted()?null:(this.stats||(this.stats=new xu().setCommitCallback(this.commitCallback).setPresentMethod(this.presentMethod)),this.stats)}getActiveStats(){return!this.stats||this.stats.isCommitted()?null:this.stats}setPresentMethod(n){var r;this.presentMethod=n,(r=this.getActiveStats())==null||r.setPresentMethod(n)}onAuthStart(){var n;this.authState="in_progress",(n=this.getOrCreateStats())==null||n.startTimer(X.AUTH)}onAuthComplete(){var r,s;const n=this.authState==="in_progress";this.authState="completed",n&&((r=this.getActiveStats())==null||r.stopTimer(X.AUTH)),(s=this.activeSpan)==null||s.onAuthSettled()}onAuthError(n){var o;const r=this.authState==="in_progress";this.authState="failed";const s=this.getActiveStats();if(s){if(!((o=this.activeSpan)!=null&&o.isRecording)){this.stats=null;return}r&&s.stopTimer(X.AUTH),s.setError(n).commit(),this.activeSpan.cancel()}}startSpan(){const n=this.activeSpan;n==null||n.cancel();const r=this.getOrCreateStats();return r&&n&&r.resetPageRenderSpan(),r&&this.authState==="in_progress"&&r.startTimer(X.AUTH),this.activeSpan=new Mu(r,this.visible),this.activeSpan}clear(){var n;(n=this.activeSpan)==null||n.cancel(),this.activeSpan=null,this.stats=null,this.authState="idle"}}class ku extends qe{constructor(){super(...arguments);S(this,"phaseReached","auth");S(this,"historyLoadResult","pending")}setHistoryLoadResult(n){return this.historyLoadResult=n,this}setPhaseReached(n){return this.phaseReached=n,this}getMetricKey(){return cu}buildPayload(){const n=this.getTimer(X.TIMEOUT).duration;return n===null?null:this.createPayload(n,{extra:{outcome:"timeout",phase_reached:this.phaseReached,history_load_result:this.historyLoadResult}})}}class wu extends At{start(t){const n=this.getKey(t==null?void 0:t.channelUrl);this.clearKey(n);const r={stats:new ku().setCommitCallback(this.commitCallback).startTimer(X.TIMEOUT),measure:{channelUrl:t==null?void 0:t.channelUrl,historyLoadResult:"pending",inputEnabled:!1,timer:null}};(t==null?void 0:t.conversationId)!==void 0&&r.stats.setConversationId(t.conversationId),r.measure.timer=setTimeout(()=>this.commitTimeout(n),1e4),this.records.set(n,r)}markChannelJoined(t,n){const r=this.getRecord(n);r&&(r.stats.setPhaseReached("channel_join"),t!==void 0&&r.stats.setConversationId(t))}markHistoryLoaded(t,n){const r=this.getRecord(n);r&&(r.measure.historyLoadResult=t,r.stats.setHistoryLoadResult(t).setPhaseReached("history_load"),this.cancelIfReady(n))}markInputReady(t){const n=this.getRecord(t);n&&(n.measure.inputEnabled=!0,n.stats.setPhaseReached("input_enable"),this.cancelIfReady(t))}markRendered(t){const n=this.getRecord(t);n&&n.stats.setPhaseReached("render")}clear(){this.records.forEach(t=>{t.measure.timer!==null&&clearTimeout(t.measure.timer)}),this.records.clear()}clearChannel(t){t!==void 0&&this.clearKey(this.getKey(t))}clearKey(t){const n=this.records.get(t);n&&(n.measure.timer!==null&&clearTimeout(n.measure.timer),this.records.delete(t))}cancelIfReady(t){const n=this.getRecord(t);!n||!n.measure.inputEnabled||n.measure.historyLoadResult==="pending"||this.clearKey(this.getKey(n.measure.channelUrl))}commitTimeout(t){const n=this.records.get(t);n&&(n.measure.timer=null,this.records.delete(t),n.stats.stopTimer(X.TIMEOUT).commit())}getRecord(t){return t!==void 0?this.records.get(this.getKey(t)):this.records.size===1?this.records.values().next().value:this.records.get(this.getKey())}getKey(t){return t??"__default__"}}class Lu extends qe{constructor(){super(...arguments);S(this,"previousMessageId");S(this,"nextMessageId")}setDuplicatePair(n){return this.previousMessageId=n.previousMessageId,this.nextMessageId=n.nextMessageId,this}getStatType(){return es}getMetricKey(){return _u}buildPayload(){return this.previousMessageId===void 0||this.nextMessageId===void 0?null:this.createPayload("",{extra:{prev_message_id:String(this.previousMessageId),next_message_id:String(this.nextMessageId)}})}}const Ou=500,Nu=(e,t)=>Fe(e,t)&&!Ae.isStreaming(e)&&!!e.message;class Du extends Bt{constructor(){super(...arguments);S(this,"emittedMessageChannels",new Map)}onMessagesChanged(n){const r=this.findLastTwoReplies(n.messages,n.aiAgentUserId);r&&r.previous.message===r.latest.message&&(this.emittedMessageChannels.has(r.latest.messageId)||this.emit(r.latest,r.previous,n))}clear(){this.emittedMessageChannels.clear()}findLastTwoReplies(n,r){let s=null,o=null;return gl(n,i=>{if(!(Xe(i)&&i.sendingStatus!==we.SendingStatus.SUCCEEDED)&&Fe(i,r)){if(!Nu(i,r))return"stop";if(!s)s=i;else return o=i,"stop"}}),s&&o?{latest:s,previous:o}:null}emit(n,r,s){sn(this.emittedMessageChannels,Ou),this.emittedMessageChannels.set(n.messageId,s.channelUrl),new Lu().setDuplicatePair({previousMessageId:r.messageId,nextMessageId:n.messageId}).setConversationId(s.conversationId).setCommitCallback(this.commitCallback).commit()}}const Pu=-1;class $u extends qe{constructor(){super(...arguments);S(this,"timestamps")}setTimestamps(n){return this.timestamps=n,this}setFailure(n){return this.setError(n),this}getStatType(){return es}getMetricKey(){return Cu}buildPayload(){const n=this.timestamps;if(!n)return null;const r=n.messageSentAt??n.streamStartAt,s=n.animationEndAt,o=s===void 0||r===void 0?Pu:s-r;return this.createPayload(o,{extra:{message_id:n.messageId===void 0?void 0:String(n.messageId),message_sent_at:n.messageSentAt,typing_start_at:n.typingStartAt,typing_end_at:n.typingEndAt,stream_start_at:n.streamStartAt,stream_failed_at:n.streamFailedAt,last_stream_at:n.lastStreamAt,stream_end_at:n.streamEndAt,animation_start_at:n.animationStartAt,animation_end_at:n.animationEndAt}})}}const Fu=3e4,Uu=1e4,Bu=e=>{var t;return((t=e.extendedMessagePayload)==null?void 0:t.is_last_in_turn)===!0};class Hu extends ts{constructor(n,r){super(n,!0);S(this,"measure");this.measure={messageSentAt:r.messageSentAt,startTimeoutTimer:null,stallTimer:null,stopBackgroundWatch:r.stopBackgroundWatch}}armStartTimeout(){this.measure.startTimeoutTimer=setTimeout(()=>this.failWith("sent_timeout"),Fu)}setConversationId(n){var r;(r=this.stats)==null||r.setConversationId(n)}onTypingChanged(n){if(this.stats){if(n){this.measure.typingStartAt===void 0&&(this.measure.typingStartAt=Date.now());return}this.measure.typingStartAt!==void 0&&this.measure.typingEndAt===void 0&&(this.measure.typingEndAt=Date.now())}}onStreamStart(n){this.stats&&(this.measure.streamMessageId=n.messageId,this.measure.streamStartAt=Date.now(),this.clearStartTimeout(),this.armStall())}onStreamFrame(n,r){if(!this.stats)return;const s=Date.now();if(r&&(this.measure.lastStreamAt=s),Ae.isStreaming(n))return this.armStall();this.measure.streamEndAt=s,this.clearStall(),this.measure.animationStartAt===void 0&&this.failWith("animation_not_started")}onAnimationStart(){this.stats&&this.measure.animationStartAt===void 0&&(this.measure.animationStartAt=Date.now())}onAnimationComplete(n){if(this.stats){if(!n)return this.cancel();this.settle({animationEndAt:Date.now()})}}cancel(){var n,r;this.clearTimers(),(r=(n=this.measure).stopBackgroundWatch)==null||r.call(n),super.cancel()}failWith(n){if(this.stats){if(this.stats.setFailure(n),n!=="stream_failed")return this.settle({});this.settle(this.measure.lastStreamAt===void 0?{streamFailedAt:Date.now(),streamStartAt:void 0}:{streamFailedAt:Date.now(),lastStreamAt:this.measure.lastStreamAt})}}settle(n){var r,s;if(this.stats){if(this.clearTimers(),(s=(r=this.measure).stopBackgroundWatch)!=null&&s.call(r))return super.cancel();this.stats.setTimestamps({messageId:this.measure.streamMessageId,messageSentAt:this.measure.messageSentAt,typingStartAt:this.measure.typingStartAt,typingEndAt:this.measure.typingEndAt,streamStartAt:this.measure.streamStartAt,streamEndAt:this.measure.streamEndAt,animationStartAt:this.measure.animationStartAt,...n}),this.commitOrDefer()}}armStall(){this.clearStall(),this.measure.stallTimer=setTimeout(()=>this.failWith("stream_failed"),Uu)}clearTimers(){this.clearStartTimeout(),this.clearStall()}clearStartTimeout(){this.measure.startTimeoutTimer!==null&&clearTimeout(this.measure.startTimeoutTimer),this.measure.startTimeoutTimer=null}clearStall(){this.measure.stallTimer!==null&&clearTimeout(this.measure.stallTimer),this.measure.stallTimer=null}}class Gu extends Bt{constructor(){super(...arguments);S(this,"block",null);S(this,"watchBackgrounded")}setBackgroundedWatcher(n){this.watchBackgrounded=n}onUserMessageSent(n){this.discardBlock();const r=this.createSpan(n.conversationId,{messageSentAt:Date.now()});r.armStartTimeout(),this.block={channelUrl:n.channelUrl,userMessageId:n.messageId,conversationId:n.conversationId,first:r,firstAnnounced:!1,spans:new Map,closed:!1}}onConversationIdResolved(n){const r=this.blockFor(n.channelUrl);r&&(r.conversationId??(r.conversationId=n.conversationId),r.first.setConversationId(n.conversationId),r.spans.forEach(s=>s.setConversationId(n.conversationId)))}onTypingChanged(n){var r;(r=this.blockFor(n.channelUrl))==null||r.first.onTypingChanged(n.isAgentTyping)}onCollectionEvent(n){const r=this.blockFor(n.channelUrl),s=n.event;if(!r||s.channelUrl!==n.channelUrl)return;if(s.kind==="messagesDeleted"){s.messages.forEach(i=>{var c;return(c=r.spans.get(i.messageId))==null?void 0:c.cancel()});return}if(s.kind==="initialized")return;const o=s.source===_e.CollectionEventSource.EVENT_MESSAGE_UPDATED;s.messages.forEach(i=>{Fe(i,n.aiAgentUserId)&&Kr(i.data).userMessageId===r.userMessageId&&this.observeReply(r,i,o)})}onAnimationStart(n){var r,s;(s=(r=this.block)==null?void 0:r.spans.get(n.messageId))==null||s.onAnimationStart()}onAnimationComplete(n){var r,s;(s=(r=this.block)==null?void 0:r.spans.get(n.messageId))==null||s.onAnimationComplete(n.completed)}clearChannel(n){!n||!this.blockFor(n)||this.discardBlock()}clear(){this.discardBlock()}observeReply(n,r,s){const o=Ae.isStreaming(r);Bu(r)&&(n.lastMessageId=r.messageId);const i=n.lastMessageId===r.messageId&&!o,c=n.spans.get(r.messageId);if(c){c.onStreamFrame(r,s),i&&(n.closed=!0);return}if(n.closed)return;if(!o){n.firstAnnounced||n.first.cancel(),n.firstAnnounced=!0,i&&(n.closed=!0);return}const u=n.firstAnnounced?this.createSpan(n.conversationId,{}):n.first;n.firstAnnounced=!0,u.onStreamStart(r),n.spans.set(r.messageId,u)}createSpan(n,r){var o;const s=new $u().setConversationId(n).setCommitCallback(this.commitCallback);return new Hu(s,{messageSentAt:r.messageSentAt,stopBackgroundWatch:((o=this.watchBackgrounded)==null?void 0:o.call(this))??null})}discardBlock(){const n=this.block;n&&(n.first.cancel(),n.spans.forEach(r=>r.cancel()),this.block=null)}blockFor(n){const r=this.block;if(!(!r||r.channelUrl!==n))return r}}class zu extends qe{constructor(){super(...arguments);S(this,"requestId");S(this,"messageType");S(this,"stuckReason")}setRequestId(n){return this.requestId=n,this}setMessageType(n){return this.messageType=n,this}setStuckReason(n){return this.stuckReason=n,this}getMetricKey(){return du}buildPayload(){return this.requestId===void 0||this.messageType===void 0||this.stuckReason===void 0?null:this.createPayload(this.stuckReason,{extra:{message_type:this.messageType,request_id:this.requestId}})}}const Vu=5e3,Fs=1e4;class Ku extends At{start(t){if(!t.requestId||this.records.has(t.requestId))return;const n=t.messageType!=="text"&&t.tracksUploadProgress===!0,s={stats:new zu().setRequestId(t.requestId).setMessageType(t.messageType).setStuckReason(n?"upload_no_progress":"pending_too_long").setCommitCallback(this.commitCallback),measure:{channelUrl:t.channelUrl,timer:null,usesUploadProgress:n}},o=n?Fs:Vu;s.measure.timer=setTimeout(()=>this.detect(t.requestId),o),this.records.set(t.requestId,s)}resolve(t){this.cancel(t.requestId)}disappear(t){this.cancel(t.requestId)}cancel(t){const n=this.records.get(t);n&&(n.measure.timer!==null&&clearTimeout(n.measure.timer),this.records.delete(t))}markUploadProgress(t){const n=this.records.get(t);n&&n.measure.usesUploadProgress&&(n.measure.timer!==null&&clearTimeout(n.measure.timer),n.measure.timer=setTimeout(()=>this.detect(t),Fs))}clear(){this.records.forEach(t=>{t.measure.timer!==null&&clearTimeout(t.measure.timer)}),this.records.clear()}clearChannel(t){t&&this.records.forEach((n,r)=>{n.measure.channelUrl===t&&(n.measure.timer!==null&&clearTimeout(n.measure.timer),this.records.delete(r))})}detect(t){const n=this.records.get(t);n&&(this.records.delete(t),n.stats.commit())}}class sr extends qe{constructor(){super(...arguments);S(this,"triggerType")}setTriggerType(n){return this.triggerType=n,this}getMetricKey(){return lu}buildPayload(){const n=this.getTimer(X.TIMEOUT).duration;return n===null||this.triggerType===void 0?null:this.createPayload(n,{extra:{trigger_type:this.triggerType}})}}class qu extends At{start(t,n){const r=this.getKey(n);let s=this.records.get(r);s!=null&&s.measure.started||s!=null&&s.measure.inputEnabled||(s||(s=this.createRecord(!1)),s.measure.started=!0,s.stats=new sr().setTriggerType(t).setCommitCallback(this.commitCallback).startTimer(X.TIMEOUT),s.measure.timer=setTimeout(()=>this.commitTimeout(r),1e4),this.records.set(r,s))}setInputEnabled(t,n){const r=this.getKey(n);let s=this.records.get(r);if(!s){if(!t)return;s=this.createRecord(t),this.records.set(r,s);return}s.measure.inputEnabled=t,t?this.cancelRecord(s):s.measure.started||this.records.delete(r)}cancelPending(t){const n=this.getKey(t),r=this.records.get(n);r&&(this.cancelRecord(r),r.measure.inputEnabled||this.records.delete(n))}clear(){this.records.forEach(t=>{t.measure.timer!==null&&clearTimeout(t.measure.timer)}),this.records.clear()}clearChannel(t){t!==void 0&&this.clearKey(this.getKey(t))}clearKey(t){const n=this.records.get(t);n&&(n.measure.timer!==null&&clearTimeout(n.measure.timer),this.records.delete(t))}commitTimeout(t){const n=this.records.get(t);if(!(!n||!n.measure.started)){if(n.measure.inputEnabled){this.cancelRecord(n);return}n.stats.stopTimer(X.TIMEOUT),this.records.delete(t),n.stats.commit()}}cancelRecord(t){t.measure.timer!==null&&clearTimeout(t.measure.timer),t.measure.timer=null,t.measure.started=!1,t.stats=new sr().setCommitCallback(this.commitCallback)}createRecord(t){return{stats:new sr().setCommitCallback(this.commitCallback),measure:{inputEnabled:t,started:!1,timer:null}}}getKey(t){return t??"__default__"}}class Wu extends qe{constructor(){super(...arguments);S(this,"messageId");S(this,"contentKind");S(this,"errorDomain")}setMessageId(n){return this.messageId=n,this}setContentKind(n){return this.contentKind=n,this}setErrorDomain(n){return this.errorDomain=n,this}getMetricKey(){return pu}buildPayload(){return this.messageId===void 0||this.contentKind===void 0||this.errorDomain===void 0?null:this.createPayload(this.errorDomain,{extra:{content_kind:this.contentKind,message_id:String(this.messageId)}})}}const Yu=500;class ju extends Bt{constructor(){super(...arguments);S(this,"measure",{committed:new Set})}commit(n){const r=`${n.messageId}:${n.contentKind}:${n.errorDomain}`;if(this.measure.committed.has(r))return;sn(this.measure.committed,Yu),this.measure.committed.add(r),new Wu().setMessageId(n.messageId).setContentKind(n.contentKind).setErrorDomain(n.errorDomain).setError(n.error?{code:n.error.code,message:n.errorDomain}:void 0).setCommitCallback(this.commitCallback).commit()}clear(){this.measure.committed.clear()}}class Xu extends qe{constructor(){super(...arguments);S(this,"durationMs");S(this,"messageId");S(this,"stallKind")}setMessageId(n){return this.messageId=n,this}setStall(n){return this.durationMs=n.durationMs,this.stallKind=n.stallKind,this}getMetricKey(){return fu}buildPayload(){return this.durationMs===void 0||this.messageId===void 0||this.stallKind===void 0?null:this.createPayload(this.durationMs,{extra:{message_id:String(this.messageId),stall_kind:this.stallKind}})}}const Us=1e4,Rt=5e3,Zu=500;class Ju extends At{constructor(){super(...arguments);S(this,"emittedMessageChannels",new Map)}markRawProgress(n){if(!n.aiResponse.isStreaming){this.completeDelivery(n.messageId,n.textLength);return}if(this.emittedMessageChannels.has(n.messageId))return;const r=this.getOrCreate(n.messageId,n.channelUrl),s=r.measure;this.markRawProgressForRecord(r,n.textLength,performance.now())?(s.deliveryTimer!==null&&clearTimeout(s.deliveryTimer),s.deliveryTimer=null,this.scheduleDeliveryStallCheck(n.messageId,r)):this.scheduleDeliveryStallCheck(n.messageId,r),this.isRenderPending(r)&&s.renderTimer===null&&(s.lastRenderAt=performance.now(),this.scheduleRenderStallCheck(n.messageId,r,Rt))}markRenderedProgress(n){const r=this.records.get(n.messageId);if(!r)return;const s=r.measure;if(this.markRenderedProgressForRecord(r,n.displayedLength,performance.now())){if(!this.isRenderPending(r)){if(s.deliveryTimer===null){this.clearRecord(n.messageId,r);return}s.renderTimer!==null&&clearTimeout(s.renderTimer),s.renderTimer=null;return}this.scheduleRenderStallCheck(n.messageId,r,Rt)}}hasPendingStream(n){return this.records.has(n)}complete(n){const r=this.records.get(n);r&&this.clearRecord(n,r)}completeDelivery(n,r){const s=this.records.get(n);if(!s)return;const o=s.measure;if(r>o.lastRawLength&&(o.lastRawLength=r,o.lastRawAt=performance.now()),o.deliveryTimer!==null&&clearTimeout(o.deliveryTimer),o.deliveryTimer=null,!this.isRenderPending(s)){this.clearRecord(n,s);return}o.renderTimer===null&&(o.lastRenderAt=performance.now(),this.scheduleRenderStallCheck(n,s,Rt))}clearMessage(n){const r=this.records.get(n);r&&this.clearRecord(n,r),this.emittedMessageChannels.delete(n)}clear(){this.records.forEach(n=>{n.measure.deliveryTimer!==null&&clearTimeout(n.measure.deliveryTimer),n.measure.renderTimer!==null&&clearTimeout(n.measure.renderTimer)}),this.records.clear(),this.emittedMessageChannels.clear()}clearChannel(n){n&&(this.records.forEach((r,s)=>{r.measure.channelUrl!==n&&r.measure.channelUrl!==void 0||this.clearRecord(s,r)}),this.emittedMessageChannels.forEach((r,s)=>{(r===n||r===void 0)&&this.emittedMessageChannels.delete(s)}))}detectDelivery(n){const r=this.records.get(n);if(!r)return;const s=r.measure;s.deliveryTimer=null,s.renderTimer!==null&&clearTimeout(s.renderTimer),s.renderTimer=null,this.emit(n,r,"delivery")}detectRender(n){const r=this.records.get(n);if(!r)return;const s=r.measure;if(s.renderTimer=null,!this.isRenderPending(r))return;const o=performance.now()-s.lastRenderAt;if(o<Rt){this.scheduleRenderStallCheck(n,r,Rt-o);return}const i=performance.now()-s.lastRawAt;if(i>=Rt&&s.deliveryTimer!==null){const c=Us-i;if(c>0){this.scheduleRenderStallCheck(n,r,c);return}}this.emit(n,r,"render")}scheduleRenderStallCheck(n,r,s){r.measure.renderTimer===null&&(r.measure.renderTimer=setTimeout(()=>this.detectRender(n),s))}scheduleDeliveryStallCheck(n,r){r.measure.deliveryTimer===null&&(r.measure.deliveryTimer=setTimeout(()=>this.detectDelivery(n),Us))}emit(n,r,s){if(this.emittedMessageChannels.has(n))return;const o=performance.now(),i=s==="delivery"?r.measure.lastRawAt:r.measure.lastRenderAt;r.stats.setStall({stallKind:s,durationMs:o-i}).commit(),this.rememberEmitted(n,r.measure.channelUrl),this.clearRecord(n,r)}getOrCreate(n,r){const s=this.records.get(n);if(s)return s;const o=performance.now(),i={stats:new Xu().setMessageId(n).setCommitCallback(this.commitCallback),measure:{channelUrl:r,deliveryTimer:null,lastRawAt:o,lastRawLength:0,lastRenderAt:o,lastRenderedLength:0,renderTimer:null}};return this.records.set(n,i),i}rememberEmitted(n,r){this.emittedMessageChannels.has(n)||sn(this.emittedMessageChannels,Zu),this.emittedMessageChannels.set(n,r)}clearRecord(n,r){r.measure.deliveryTimer!==null&&clearTimeout(r.measure.deliveryTimer),r.measure.renderTimer!==null&&clearTimeout(r.measure.renderTimer),this.records.delete(n)}isRenderPending(n){return n.measure.lastRenderedLength<n.measure.lastRawLength}markRawProgressForRecord(n,r,s){return r<=n.measure.lastRawLength?!1:(n.measure.lastRawLength=r,n.measure.lastRawAt=s,!0)}markRenderedProgressForRecord(n,r,s){return r<=n.measure.lastRenderedLength?!1:(n.measure.lastRenderedLength=r,n.measure.lastRenderAt=s,!0)}}class Qu extends qe{constructor(){super(...arguments);S(this,"durationMs");S(this,"messageId");S(this,"chunkIntervalsMs",[]);S(this,"regenerated",!1)}setMessageId(n){return this.messageId=n,this}setStream(n){return this.durationMs=n.durationMs,this.chunkIntervalsMs=n.chunkIntervalsMs,this.regenerated=n.regenerated,this}getStatType(){return es}getMetricKey(){return Eu}buildPayload(){return this.durationMs===void 0||this.messageId===void 0?null:this.createPayload(this.durationMs,{extra:{message_id:String(this.messageId),chunk_intervals_ms:this.chunkIntervalsMs,regenerated:this.regenerated}})}}const ed=-1,td=e=>e===_e.CollectionEventSource.EVENT_MESSAGE_RECEIVED||e===_e.CollectionEventSource.EVENT_MESSAGE_UPDATED;class nd extends At{constructor(){super(...arguments);S(this,"watchBackgrounded")}setBackgroundedWatcher(n){this.watchBackgrounded=n}onCollectionEvent(n){const r=n.event;if(r.channelUrl!==n.channelUrl)return;if(r.kind==="messagesDeleted"){r.messages.forEach(o=>{const i=this.records.get(o.messageId);i&&this.drop(o.messageId,i)});return}if(r.kind==="initialized"||!td(r.source))return;const s=r.source===_e.CollectionEventSource.EVENT_MESSAGE_RECEIVED;r.messages.forEach(o=>{const i=this.records.get(o.messageId);if(!i){s&&Fe(o,n.aiAgentUserId)&&Ae.isStreaming(o)&&this.start(o,n.channelUrl,n.conversationId);return}i.measure.channelUrl===n.channelUrl&&(i.stats.setConversationId(n.conversationId),this.advance(i,o),Ae.isStreaming(o)||this.finish(o.messageId,i))})}clearChannel(n){n&&this.records.forEach((r,s)=>{r.measure.channelUrl===n&&this.drop(s,r)})}clear(){this.records.forEach((n,r)=>this.drop(r,n))}start(n,r,s){var i;this.clearChannel(r);const o=performance.now();this.records.set(n.messageId,{stats:new Qu().setMessageId(n.messageId).setConversationId(s).setCommitCallback(this.commitCallback),measure:{channelUrl:r,startedAt:o,lastAt:o,lastText:n.message,chunkIntervalsMs:[],regenerated:!1,stopBackgroundWatch:((i=this.watchBackgrounded)==null?void 0:i.call(this))??null}})}advance(n,r){const s=n.measure,o=r.message;if(o===s.lastText)return;o.startsWith(s.lastText)||(s.regenerated=!0,s.chunkIntervalsMs.push(ed));const i=performance.now();s.chunkIntervalsMs.push(Math.round(i-s.lastAt)),s.lastText=o,s.lastAt=i}finish(n,r){var o;const s=r.measure;this.records.delete(n),!((o=s.stopBackgroundWatch)!=null&&o.call(s))&&r.stats.setStream({durationMs:Math.round(performance.now()-s.startedAt),chunkIntervalsMs:s.chunkIntervalsMs,regenerated:s.regenerated}).commit()}drop(n,r){var s,o;(o=(s=r.measure).stopBackgroundWatch)==null||o.call(s),this.records.delete(n)}}class rd extends qe{constructor(){super(...arguments);S(this,"beforeTpstAbsentMs");S(this,"afterTpenAbsentMs")}setBeforeTpstAbsentMs(n){return this.beforeTpstAbsentMs=n,this}setAfterTpenAbsentMs(n){return this.afterTpenAbsentMs=n,this}getMetricKey(){return gu}buildPayload(){return this.beforeTpstAbsentMs===void 0&&this.afterTpenAbsentMs===void 0?null:this.createPayload((this.beforeTpstAbsentMs??0)+(this.afterTpenAbsentMs??0),{extra:{[X.BEFORE_TPST_ABSENT]:this.beforeTpstAbsentMs,[X.AFTER_TPEN_ABSENT]:this.afterTpenAbsentMs}})}}const Bs=3e3,sd=3e4;class od extends At{constructor(){super(...arguments);S(this,"pendingAIResponseStartsByUserMessageId",new Map)}startTurn(n){this.cancelTurn(n.requestId);const r={stats:new rd().setCommitCallback(this.commitCallback),measure:{afterTpenStartedAt:null,beforeTpstStartedAt:performance.now(),channelUrl:n.channelUrl,requestId:n.requestId,timer:null}};r.measure.timer=setTimeout(()=>this.commitTimeout(r.measure.requestId),sd),this.records.set(n.requestId,r)}markUserMessageAck(n){const r=this.records.get(n.requestId);if(!r)return;r.measure.userMessageId=n.messageId;const s=this.pendingAIResponseStartsByUserMessageId.get(n.messageId);s&&(this.pendingAIResponseStartsByUserMessageId.delete(n.messageId),this.applyAIResponseStarted({channelUrl:s.channelUrl,matchesUserMessage:!0,userMessageId:n.messageId},s.startedAt))}replaceTurnRequestId(n,r){if(n===r)return;const s=this.records.get(n);s&&(this.records.delete(n),s.measure.requestId=r,this.records.set(r,s))}cancelTurn(n){this.cleanupTurn(n)}markTypingStarted(n){const r=performance.now();this.records.forEach(s=>{vt(s.measure.channelUrl,n)&&(this.recordAfterTpen(s,r),this.recordBeforeTpst(s,r))})}markTypingEnded(n){const r=performance.now();this.records.forEach(s=>{vt(s.measure.channelUrl,n)&&(this.recordBeforeTpst(s,r),s.measure.afterTpenStartedAt=r)})}markAIResponseStarted(n={}){const r=n.channelUrl,s=n.userMessageId,o=s!==void 0,i=performance.now();this.applyAIResponseStarted({channelUrl:r,matchesUserMessage:o,userMessageId:s},i)||!o||s===void 0||!xr(this.records.values(),r)||this.pendingAIResponseStartsByUserMessageId.has(s)||(sn(this.pendingAIResponseStartsByUserMessageId,100),this.pendingAIResponseStartsByUserMessageId.set(s,{channelUrl:r,startedAt:i}))}applyAIResponseStarted(n,r){if(!n.matchesUserMessage){const o=this.findSingleTurn(n.channelUrl);return o?(this.completeTurn(o.requestId,o.record,r),!0):!1}let s=!1;return this.records.forEach(o=>{vt(o.measure.channelUrl,n.channelUrl)&&(n.matchesUserMessage&&o.measure.userMessageId!==n.userMessageId||(s=!0,this.completeTurn(o.measure.requestId,o,r)))}),s}findSingleTurn(n){let r,s=0;return this.records.forEach(o=>{vt(o.measure.channelUrl,n)&&(s+=1,!(s>1)&&(r={requestId:o.measure.requestId,record:o}))}),s===1?r:void 0}completeTurn(n,r,s){this.recordBeforeTpst(r,s),this.recordAfterTpen(r,s),this.commitIfAbsent(n,r)}clear(){this.records.forEach(n=>{n.measure.timer!==null&&clearTimeout(n.measure.timer)}),this.records.clear(),this.pendingAIResponseStartsByUserMessageId.clear()}clearChannel(n){n&&(this.records.forEach(r=>{r.measure.channelUrl===n&&this.cleanupTurn(r.measure.requestId)}),this.pendingAIResponseStartsByUserMessageId.forEach((r,s)=>{r.channelUrl===n&&this.pendingAIResponseStartsByUserMessageId.delete(s)}))}commitTimeout(n){const r=this.records.get(n);if(!r)return;const s=performance.now();this.recordBeforeTpst(r,s),this.recordAfterTpen(r,s),this.commitIfAbsent(n,r)}commitIfAbsent(n,r){r.stats.commit(),this.cleanupTurn(n)}cleanupTurn(n){const r=this.records.get(n);r&&(r.measure.timer!==null&&clearTimeout(r.measure.timer),this.records.delete(n))}recordBeforeTpst(n,r){if(n.measure.beforeTpstStartedAt===null)return;const s=r-n.measure.beforeTpstStartedAt;s>=Bs&&n.stats.setBeforeTpstAbsentMs(s),n.measure.beforeTpstStartedAt=null}recordAfterTpen(n,r){if(n.measure.afterTpenStartedAt===null)return;const s=r-n.measure.afterTpenStartedAt;s>=Bs&&n.stats.setAfterTpenAbsentMs(s),n.measure.afterTpenStartedAt=null}}class id extends qe{constructor(){super(...arguments);S(this,"ackToFirstChunkMs");S(this,"firstChunkToRenderMs");S(this,"isStreaming");S(this,"sendToAckMs");S(this,"totalDurationMs")}setDurations(n){return this.ackToFirstChunkMs=n.ackToFirstChunkMs,this.firstChunkToRenderMs=n.firstChunkToRenderMs,this.isStreaming=n.isStreaming,this.sendToAckMs=n.sendToAckMs,this.totalDurationMs=n.totalDurationMs,this}getMetricKey(){return hu}buildPayload(){return this.ackToFirstChunkMs===void 0||this.firstChunkToRenderMs===void 0||this.isStreaming===void 0||this.sendToAckMs===void 0||this.totalDurationMs===void 0?null:this.createPayload(this.totalDurationMs,{extra:{is_streaming:this.isStreaming,[X.ACK_TO_FIRST_CHUNK]:this.ackToFirstChunkMs,[X.FIRST_CHUNK_TO_RENDER]:this.firstChunkToRenderMs,[X.SEND_TO_ACK]:this.sendToAckMs}})}}const ad=.15,cd=10,ld=e=>e<=0?!1:e>=1?!0:Math.random()<e;class ud extends At{constructor(n,r){super(n);S(this,"samplingRate");S(this,"pendingAIResponseByUserMessageId",new Map);S(this,"collectedCount",0);this.samplingRate=(r==null?void 0:r.samplingRate)??ad}startTurn(n){if(this.collectedCount>=cd||!ld(this.samplingRate))return;this.collectedCount+=1;const r={stats:new id().setCommitCallback(this.commitCallback),measure:{channelUrl:n.channelUrl,requestId:n.requestId,startedAt:performance.now()}};this.records.set(n.requestId,r)}markUserMessageAck(n){const r=this.records.get(n.requestId);if(!r)return;r.measure.ackAt=performance.now(),r.measure.userMessageId=n.messageId;const s=this.pendingAIResponseByUserMessageId.get(n.messageId);s&&(this.pendingAIResponseByUserMessageId.delete(n.messageId),this.applyAIResponseRaw(r,s))}replaceTurnRequestId(n,r){if(n===r)return;const s=this.records.get(n);s&&(this.records.delete(n),s.measure.requestId=r,this.records.set(r,s))}cancelTurn(n){const r=this.records.get(n);r&&(this.deleteRecord(r),this.collectedCount>0&&(this.collectedCount-=1))}markAIResponseRaw(n){const r=performance.now(),s=n.aiResponse.userMessageId;if(s===void 0&&xr(this.records.values(),n.channelUrl))return;const o=this.findPendingRecord(n.channelUrl,s);if(o){this.applyAIResponseRaw(o,{...n,firstChunkAt:r});return}s===void 0||!xr(this.records.values(),n.channelUrl)||this.bufferAIResponseRaw({messageId:n.messageId,...n.channelUrl!==void 0&&{channelUrl:n.channelUrl},aiResponse:n.aiResponse,firstChunkAt:r},s)}markAIResponseVisible(n){const r=this.findRecordByAIMessageId(n);if(!r)return!1;const s=r.measure;if(s.ackAt===void 0||s.firstChunkAt===void 0||s.userMessageId===void 0)return!1;const o=performance.now();return r.stats.setDurations({ackToFirstChunkMs:s.firstChunkAt-s.ackAt,firstChunkToRenderMs:o-s.firstChunkAt,isStreaming:!!s.isStreaming,sendToAckMs:s.ackAt-s.startedAt,totalDurationMs:o-s.startedAt}).commit(),this.deleteRecord(r),!0}hasPendingAIResponse(n){return this.findRecordByAIMessageId(n)!==void 0}clearMessage(n){this.pendingAIResponseByUserMessageId.forEach((s,o)=>{s.messageId===n&&this.pendingAIResponseByUserMessageId.delete(o)});const r=this.findRecordByAIMessageId(n);r&&(this.deleteRecord(r),this.collectedCount>0&&(this.collectedCount-=1))}clearChannel(n){n&&(this.records.forEach(r=>{r.measure.channelUrl===n&&(this.deleteRecord(r),this.collectedCount>0&&(this.collectedCount-=1))}),this.pendingAIResponseByUserMessageId.forEach((r,s)=>{r.channelUrl===n&&this.pendingAIResponseByUserMessageId.delete(s)}))}clear(){this.records.clear(),this.pendingAIResponseByUserMessageId.clear(),this.collectedCount=0}findRecordByAIMessageId(n){for(const r of this.records.values())if(r.measure.aiMessageId===n)return r}findPendingRecord(n,r){if(r!==void 0){for(const o of this.records.values())if(!(o.measure.ackAt===void 0||o.measure.firstChunkAt!==void 0)&&vt(o.measure.channelUrl,n)&&o.measure.userMessageId===r)return o;return}let s;for(const o of this.records.values())if(!(o.measure.ackAt===void 0||o.measure.firstChunkAt!==void 0)&&vt(o.measure.channelUrl,n)){if(s)return;s=o}return s}applyAIResponseRaw(n,r){n.measure.firstChunkAt===void 0&&(n.measure.firstChunkAt=n.measure.ackAt===void 0?r.firstChunkAt:Math.max(r.firstChunkAt,n.measure.ackAt),n.measure.aiMessageId=r.messageId,n.measure.channelUrl=n.measure.channelUrl??r.channelUrl,n.measure.isStreaming=r.aiResponse.isStreaming)}bufferAIResponseRaw(n,r){this.pendingAIResponseByUserMessageId.has(r)||(sn(this.pendingAIResponseByUserMessageId,100),this.pendingAIResponseByUserMessageId.set(r,n))}deleteRecord(n){this.records.delete(n.measure.requestId),n.measure.userMessageId!==void 0&&this.pendingAIResponseByUserMessageId.delete(n.measure.userMessageId)}}function dd(){let e=null,t=0;const n=(r,s)=>{if((e==null?void 0:e.key)===r)return e.promise;const o=++t,c=(e?e.promise.catch(()=>{}).then(()=>s()):s()).finally(()=>{(e==null?void 0:e.id)===o&&(e=null)});return e={key:r,id:o,promise:c},c};return n.isPending=()=>e!==null,n}const Hs={isTalkToAgentViewEnabled:!0,scrollMode:"auto",newMessageIndicatorEnabled:!0,senderAvatarEnabled:!0},ns={conversation:{...Hs,messageAlertSoundEnabled:!1,list:{...Hs,deferredMarkdownElements:[]},header:{avatarEnabled:!0},input:{camera:{photoEnabled:!0},gallery:{photoEnabled:!0},fileEnabled:!0},fileViewer:{downloadEnabled:!0}},launcher:{unreadBadgeEnabled:!1}},Gs=e=>e?{conversation:fd(e.conversation),launcher:md(e.launcher)}:ns,md=e=>wt(ns.launcher,e),hd=e=>{if(e.deferredMarkdownElements)return[...e.deferredMarkdownElements];const t=[];return e.markdownImageRenderMode==="complete-only"&&t.push("image"),e.markdownLinkRenderMode==="complete-only"&&t.push("link"),t},fd=e=>{const t=ns.conversation;if(!e)return t;const{list:n={},header:r={},input:s,fileViewer:o={},messageAlertSoundEnabled:i=t.messageAlertSoundEnabled,...c}=e,{camera:u={},gallery:d={},fileEnabled:m=t.input.fileEnabled}=s??{},h={...wt(t.list,c,n),deferredMarkdownElements:hd(n)};return{...h,messageAlertSoundEnabled:i,list:h,header:wt(t.header,r),input:{camera:wt(t.input.camera,u),gallery:wt(t.input.gallery,d),fileEnabled:m},fileViewer:wt(t.fileViewer,o)}},wt=(e,...t)=>{const n={...e};for(const r of t)r&&Object.assign(n,Qr(r));return n},gd=(e,t)=>Mr(e,t),Mr=(e,t)=>{if(Object.is(e,t))return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((r,s)=>Mr(r,t[s]));if(!zs(e)||!zs(t))return!1;const n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(r=>Mr(e[r],t[r]))},zs=e=>typeof e=="object"&&e!==null,pd=e=>({userId:e.bot_userid,profileUrl:e.bot_profile_url,nickname:e.bot_nickname,replyToFile:e.reply_to_file,specialNotice:e.special_notice,specialNoticeEnabled:e.is_special_notice_enabled,showHandoffButton:e.show_handoff_button??!0,isMultipleActiveConversationsEnabled:e.is_multiple_active_conversations_enabled??!0,isUserFeedbackEnabled:e.is_user_feedback_enabled??!1,isUserFeedbackCommentOptionEnabled:e.is_user_feedback_comment_option_enabled??!1}),Ed=e=>({type:e.image_type||"default_icon",imageUrl:e.image_url}),Rr=e=>({enabled:e.enabled,showIndicator:e.show_indicator,toggleAllowed:e.toggle_allowed,deleteOnOff:e.delete_on_off,consentDialog:e.consent_dialog});class _d{constructor(){S(this,"_channelHandlerId",null);S(this,"_connectionHandlerId",null);S(this,"_initConversationRequests",new Map);S(this,"_handleActiveChannelChangedThrottled",null);S(this,"_setupChannelHandler",()=>{const t=Date.now();this._channelHandlerId=`aiagent_channel_${t}`,this._connectionHandlerId=`aiagent_connection_${t}`,this._handleActiveChannelChangedThrottled=Ti(s=>{var o,i;(i=this._session)==null||i._updateActiveChannel({url:s.url,status:$e(s)?"closed":"open",conversationStatus:(o=s.conversation)==null?void 0:o.status}),this._logger.debug("AIAgentEventManager: activeChannel updated",s.url)},250,{leading:!0,trailing:!1});const n=new rt.GroupChannelHandler({onChannelChanged:s=>{var o,i;s.isGroupChannel()&&s.url===((o=this._session)==null?void 0:o.activeChannel.url)&&((i=this._handleActiveChannelChangedThrottled)==null||i.call(this,s))}}),r=new _e.ConnectionHandler({onReconnectSucceeded:async()=>{await this._syncActiveChannelOnReconnect()}});this._chatClient.chatSDK.groupChannel.addGroupChannelHandler(this._channelHandlerId,n),this._chatClient.chatSDK.addConnectionHandler(this._connectionHandlerId,r),this._logger.debug("AIAgentEventManager: handlers registered",{channelHandlerId:this._channelHandlerId,connectionHandlerId:this._connectionHandlerId})});S(this,"_removeChannelHandler",()=>{this._channelHandlerId&&(this._chatClient.chatSDK.groupChannel.removeGroupChannelHandler(this._channelHandlerId),this._channelHandlerId=null),this._connectionHandlerId&&(this._chatClient.chatSDK.removeConnectionHandler(this._connectionHandlerId),this._connectionHandlerId=null),this._handleActiveChannelChangedThrottled&&(this._handleActiveChannelChangedThrottled.cancel(),this._handleActiveChannelChangedThrottled=null),this._logger.debug("AIAgentEventManager: handlers removed")});S(this,"_syncActiveChannelOnReconnect",async()=>{var n,r,s;const t=(n=this._session)==null?void 0:n.activeChannel.url;if(t)try{const i=await(await this._chatClient.chatSDK.groupChannel.getChannel(t)).refresh();i.url===t&&((s=this._session)==null||s._updateActiveChannel({url:i.url,status:$e(i)?"closed":"open",conversationStatus:(r=i.conversation)==null?void 0:r.status}),this._logger.debug("AIAgentEventManager: activeChannel synced on reconnect",i.url))}catch(o){this._logger.error("AIAgentEventManager: failed to sync activeChannel on reconnect",o)}});S(this,"_initConversationIfNeeded",(t,n)=>{if(!t.isAIAgent||t.conversation)return Promise.resolve();const r=this._initConversationRequests.get(t.url);if(r)return r;const s=t.initConversation({aiAgentId:this.aiAgentId,initialUserMessage:n==null?void 0:n.initialUserMessage}).then(()=>{}).catch(o=>{this._logger.warn("AIAgentEventManager: initConversation failed",o)}).finally(()=>{this._initConversationRequests.delete(t.url)});return this._initConversationRequests.set(t.url,s),s});S(this,"onMessengerSettingsUpdated",t=>(this._dispatcher.subscribe(Ge.MessengerSettingsUpdated,t),()=>{this._dispatcher.unsubscribe(Ge.MessengerSettingsUpdated,t)}));S(this,"onActiveChannelUpdated",t=>(this._dispatcher.subscribe(Ge.ActiveChannelUpdated,t),()=>{this._dispatcher.unsubscribe(Ge.ActiveChannelUpdated,t)}));S(this,"onAuthTokenRefreshed",t=>(this._dispatcher.subscribe(Ge.AuthTokenRefreshed,t),()=>{this._dispatcher.unsubscribe(Ge.AuthTokenRefreshed,t)}));S(this,"onNudgeMessageReceived",t=>(this._dispatcher.subscribe(Ge.NudgeMessageReceived,t),()=>{this._dispatcher.unsubscribe(Ge.NudgeMessageReceived,t)}))}}class Cd{constructor(t){S(this,"_sdkUser");S(this,"_userSession");S(this,"_dispatcher");S(this,"_activeChannel");S(this,"_updateActiveChannel",t=>{this._activeChannel=t,this._dispatcher.send(ut.ActiveChannelUpdated({channelUrl:t.url,status:t.status,conversationStatus:t.conversationStatus}))});S(this,"_updateAuthToken",t=>{this._userSession.authToken=t,this._dispatcher.send(ut.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 Ni=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)}},Di=e=>JSON.parse(e),Sd=e=>JSON.parse(e);function bd(e,t){const[n,r]=t.split(",").map(s=>s.trim());return e==="dark"&&r||n}function vd(e){const t={};function n(r,s=""){for(const[o,i]of Object.entries(r)){const c=s?`${s}.${o}`:o;i&&typeof i=="object"&&!Array.isArray(i)?n(i,c):t[c]=i}}return n(e),t}function yd({template:e,variables:t,variableKeyPattern:n,variableValueTransformer:r}){return Object.entries(t).reduce((s,[o,i])=>{if(!r&&!["number","boolean","string"].includes(typeof i))throw new Error(`If transformer is not provided, value(${o}:${i}) must be a {string, number, or boolean}`);const c=r?r(i):String(i),u=n(o);return s.replace(u,Ni(c))},e)}async function Ad({template:e,variables:t,variableKeyPattern:n,variableValueTransformer:r}){return(await Promise.all(Object.entries(t).map(async([o,i])=>{const c=await r(i);return{regex:n(o),transformedValue:c}}))).reduce((o,{regex:i,transformedValue:c})=>o.replace(i,Ni(c)),e)}var rs=(e=>(e[e.EXTERNAL_AUTH_TOKEN_EXPIRED=1]="EXTERNAL_AUTH_TOKEN_EXPIRED",e))(rs||{});const Pi=e=>typeof e=="object"&&e!==null,or=(e,t)=>t in e&&typeof e[t]=="string"&&e[t]!=="",Td=e=>!Pi(e)||!or(e,"channel_url")||!or(e,"ai_agent_id")||!or(e,"cpa_key")?null:{channelUrl:e.channel_url,aiAgentId:e.ai_agent_id,cpaKey:e.cpa_key},Id={1:Td};function xd(e){if(!Pi(e)||!("cat"in e)||typeof e.cat!="number"||!("data"in e))return null;const t=e.cat,n=Id[t];if(!n)return null;const r=n(e.data);return r?{category:t,data:r}:null}function Md(e,t,n,r){const s=qc.default.init({appId:e,modules:[new rt.GroupChannelModule,new Ce.AIAgentModule],localCacheEnabled:!0,options:new _e.SendbirdChatOptions({typingIndicatorInvalidateTime:2e4}),...r,customApiHost:(r==null?void 0:r.customApiHost)??`https://api-${e}.app.delight.ai`,customWebSocketHost:(r==null?void 0:r.customWebSocketHost)??`wss://ws-${e}.app.delight.ai`});return s.addSendbirdExtensions([{version:n,product:_e.SendbirdProduct.AI_AGENT,platform:t.platform}],{platform:t.deviceOSPlatform,version:t.deviceOSVersion},t.customData)||console.warn("Invalid Sendbird Extensions",t),s}function Rd(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 kd=[400300,400301,400302,400310],wd=rs.EXTERNAL_AUTH_TOKEN_EXPIRED.toString(),Ld=e=>`${wd}:${e}`;class ss{constructor(t,n,r,s,o){S(this,"chatSDK");S(this,"_aiAgentId");S(this,"_externalAuthTokenExpiredEventHandlerKey");S(this,"_logger");S(this,"_cache");S(this,"_statsTrackers");S(this,"_sessionHandler");S(this,"_aiEventHandlerRegistered",!1);S(this,"connect",async(t,n,r,s,o)=>{if(this._logger.debug("ChatClient.connect: start",t.userId),n){this._sessionHandler=n;const i=new _e.SessionHandler({...n,onSessionTokenRequired:this._interceptTokenRefresh(n.onSessionTokenRequired,r,s)});this.chatSDK.setSessionHandler(i)}this._registerAIEventHandler();try{await this.chatSDK.connect(t.userId,t.authToken);const[,i]=await Promise.allSettled([this._syncTemplatesIfNeeded(),o?this.submitCPAAuthorizationCodes(o):Promise.resolve()]);return o&&(i.status==="fulfilled"?this._logger.debug("ChatClient.connect: CPA authorization codes submitted",i.value):this._logger.error("ChatClient.connect: CPA authorization code submission failed",i.reason)),this._logger.debug("ChatClient.connect: end",this.chatSDK.currentUser),this.chatSDK.currentUser}catch(i){const c=i;if(this.chatSDK.isCacheEnabled){if(this._isCacheRestrictedError(c))this._logger.warn("ChatClient.connect","offline connect restricted",c.message,c.code),this._logger.warn("ChatClient.connect","clear cached-data"),await this.chatSDK.clearCachedData().catch(u=>this._logger.warn("ChatClient.connect","clear cached-data failure",u));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",c.message,c.code),this.dispose(),c}});S(this,"_registerAIEventHandler",()=>{this._aiEventHandlerRegistered||(this._aiEventHandlerRegistered=!0,this.chatSDK.aiAgent.addEventHandler(this._externalAuthTokenExpiredEventHandlerKey,this._handleAIEvent))});S(this,"_handleAIEvent",t=>{var o;this._logger.debug("ChatClient.connect: EXTERNAL_AUTH_TOKEN_EXPIRED event received",t);const n=xd(t),r=typeof t.cat=="number"?t.cat:void 0;if(r!==void 0&&r!==rs.EXTERNAL_AUTH_TOKEN_EXPIRED)return;if(!n){this._statsTrackers.aievAuthExpiredUnhandled.onPayloadParseFailed({aiAgentId:this._aiAgentId});return}if(n.data.aiAgentId!==this._aiAgentId){this._logger.debug("ChatClient.connect: ignore EXTERNAL_AUTH_TOKEN_EXPIRED for another agent",n.data);return}const s=(o=this._sessionHandler)==null?void 0:o.onExternalAuthTokenExpired;if(!s){this._statsTrackers.aievAuthExpiredUnhandled.onCallbackNotFound(n.data);return}this._logger.debug("ChatClient.connect: calling onExternalAuthTokenExpired handler",n.data),s(n.data)});S(this,"dispose",()=>{this._aiEventHandlerRegistered&&(this.chatSDK.aiAgent.removeEventHandler(this._externalAuthTokenExpiredEventHandlerKey),this._aiEventHandlerRegistered=!1),this._sessionHandler=void 0});S(this,"disconnect",async()=>{this._logger.debug("ChatClient.disconnect: start"),this.dispose(),await this.chatSDK.disconnect(),this._cache.template.clear(),this._logger.debug("ChatClient.disconnect: end")});S(this,"getChannel",async t=>this.chatSDK.groupChannel.getChannel(t));S(this,"patchContext",async(t,n,r)=>this.chatSDK.aiAgent.patchContext(t,n,r));S(this,"updateContext",async(t,n,r)=>this.chatSDK.aiAgent.updateContext(t,n,r));S(this,"requestNudgeMessage",async t=>this.chatSDK.aiAgent.requestNudgeMessage(t));S(this,"submitCPAAuthorizationCodes",async({aiAgentId:t,authCodes:n})=>this.chatSDK.aiAgent.submitCustomerProvidedAuthCodes({aiAgentId:t,authorizationCodes:n}));S(this,"requestMessengerSettings",async t=>{var s;if(t.userId===""){const o=new Error("userId cannot be empty string for messenger settings request");throw this._logger.error("ChatClient.requestMessengerSettings: invalid userId",o),o}const n={...t,shouldSendFirstMessage:!1};this._logger.debug("ChatClient.requestMessengerSettings: requesting",n);const r=await this.chatSDK.aiAgent.requestMessengerSettings(n);return this._logger.debug("ChatClient.requestMessengerSettings: received",(s=r.active_channel)==null?void 0:s.channel_url),r});S(this,"setUserMemoryState",async t=>{this._logger.debug("ChatClient.setUserMemoryState: requesting",t);const n=await this.chatSDK.aiAgent.setUserMemoryState(t);return this._logger.debug("ChatClient.setUserMemoryState: received",n.enabled),n});S(this,"clearUserMemories",async(t={})=>{this._logger.debug("ChatClient.clearUserMemories: requesting",t),await this.chatSDK.aiAgent.clearUserMemories(t),this._logger.debug("ChatClient.clearUserMemories: completed")});S(this,"_interceptTokenRefresh",(t,n,r)=>{if(t)return async(s,o)=>{new Promise((i,c)=>t==null?void 0:t(i,c)).then(i=>{i?n==null||n(i):r==null||r(),s(i)}).catch(i=>{r==null||r(),o(i)})}});S(this,"_isCacheRestrictedError",t=>kd.some(n=>t.code===n));S(this,"_syncTemplatesIfNeeded",async()=>{var r,s;const t=(s=(r=this.chatSDK.appInfo)==null?void 0:r.aiAgentInfo)==null?void 0:s.templateListToken;if(!t)return;const n=this._cache.template.getCachedToken();if(!(n&&n===t)){this._logger.debug("ChatClient._syncTemplatesIfNeeded: syncing templates");try{const{templates:o,token:i}=await this.chatSDK.aiAgent.getMessageTemplates({limit:20});for(const{template:c}of o){const{key:u}=Di(c);this._cache.template.set(u,c)}this._cache.template.setCachedToken(i),this._logger.debug("ChatClient._syncTemplatesIfNeeded: sync completed")}catch(o){this._logger.error("ChatClient._syncTemplatesIfNeeded: error",o)}}});this.chatSDK=t,this._aiAgentId=n,this._externalAuthTokenExpiredEventHandlerKey=Ld(n),this._logger=r,this._cache=s,this._statsTrackers=o}static init(t){let n;return t.chatSDK?(Rd(t.chatSDK),n=t.chatSDK):n=Md(t.appId,t.extensions,t.messengerVersion,t.chatParams),new ss(n,t.aiAgentId,t.logger,t.cache,t.statsTrackers)}}const Od=e=>t=>{if(!e||e.getState()==="foregrounded"){t();return}const n=e.subscribe(r=>{r==="foregrounded"&&(n(),t())});return n},Nd=e=>()=>{let t=e.getState()==="backgrounded";const n=e.subscribe(r=>{r==="backgrounded"&&(t=!0)});return()=>(n(),t)},fn=new Map,$i={set:(e,t)=>{fn.set(e,t)},get:e=>{if(fn.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=fn.get(e);if(!n)throw new Error(`AIAgent platform "${e}" is not configured.`);return{platform:e,...n}}const t=fn.entries().next().value;return{platform:t[0],...t[1]}}},Fi="SENDBIRD_DESK_INQUIRE_TICKET_CLOSURE";var Rn=(e=>(e.WAITING="WAITING",e.CONFIRMED="CONFIRMED",e.DECLINED="DECLINED",e))(Rn||{});const Dd=e=>{if(!e)return null;const t=pi(e);if(t.type!==Fi)return null;const{state:n,ticketId:r}=t.body??{};return n==null||r==null?null:{state:n,ticketId:r}};class Vs extends Error{constructor(n,r){const s=(r==null?void 0:r.detail)??"";super(s||`Desk API error (${n})`);S(this,"status");S(this,"code");S(this,"detail");this.name="DeskApiError",this.status=n,this.code=(r==null?void 0:r.code)??"",this.detail=s}}var os=(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))(os||{}),is=(e=>(e.URGENT="URGENT",e.HIGH="HIGH",e.MEDIUM="MEDIUM",e.LOW="LOW",e))(is||{}),Ui=(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))(Ui||{});const Pd=e=>e==="desk401103"||e==="desk401106"||e==="desk401107"||e==="desk401108"||e==="desk401109";class $d{constructor(t){S(this,"_appId");S(this,"_apiHost");S(this,"_logger");S(this,"_credential",null);S(this,"_authRefreshPromise",null);S(this,"_onDeskTokenRefreshRequired",async()=>!1);S(this,"request",async(t,n)=>{const r=n.authRequired??!0,s=`${this._apiHost}${t}`;r&&this._authRefreshPromise&&(this._logger.debug("DeskApiClient: waiting for in-flight recovery..."),await this._authRefreshPromise);const o=await this._fetch(s,n);return r&&o.status===401?this._handleUnauthorized(o,s,n):this._toResult(o)});S(this,"setCredential",(t,n=async()=>!1)=>{this._authRefreshPromise=null,this._onDeskTokenRefreshRequired=n,this._credential=t});S(this,"clearCredential",()=>{this._authRefreshPromise=null,this._credential=null,this._onDeskTokenRefreshRequired=async()=>!1});S(this,"_handleUnauthorized",async(t,n,r)=>{const s=await this._parseErrorCode(t);if(!Pd(s))return this._toResult(t);if(!await this._refresh(s)||this._credential===null)return this._toResult(t);const i=await this._fetch(n,r);return this._toResult(i)});S(this,"_refresh",async t=>{if(this._authRefreshPromise)return this._logger.debug("DeskApiClient: refresh already in progress, joining..."),this._authRefreshPromise;try{return this._authRefreshPromise=this._onDeskTokenRefreshRequired({reason:t}).catch(n=>(this._logger.error("DeskApiClient: delegated recovery failed",n),!1)),await this._authRefreshPromise}finally{this._authRefreshPromise=null}});S(this,"_fetch",(t,n)=>fetch(`${t}?${this._buildParams(n.params)}`,{method:n.method,headers:this._buildHeaders(n.authRequired??!0,n.headers),...n.body?{body:JSON.stringify(this._buildBody(n.body))}:{}}));S(this,"_buildParams",t=>new URLSearchParams({sendbirdAppId:this._appId,...t}));S(this,"_buildBody",t=>({sendbirdAppId:this._appId,...t}));S(this,"_buildHeaders",(t,n)=>({"content-type":"application/json",...t&&this._credential?{sendbirdDeskToken:this._credential.deskToken}:{},...n}));S(this,"_toResult",async t=>{if(!t.ok){const r=await t.json().catch(()=>({}));throw new Vs(t.status,r)}const n=await t.text();if(n)try{return JSON.parse(n)}catch{throw new Vs(t.status,{})}});S(this,"_parseErrorCode",async t=>{const n=await t.clone().json().catch(()=>({}));return n==null?void 0:n.code});this._appId=t.appId,this._apiHost=t.customApiHost??`https://desk-api-${t.appId}.app.delight.ai/sapi`,this._logger=t.logger}get credential(){return this._credential}}class kn{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 kn({id:t.id,title:t.channelName??null,status:t.status2??os.INITIALIZED,agent:(()=>{var o;const s=(o=t.recentAssignment)==null?void 0:o.agent;return s?{userId:s.sendbirdId??"",name:s.displayName??"",profileUrl:s.photoThumbnailUrl??""}:null})(),priority:t.priority??is.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 as{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 kn._fromResponse(n,this)});S(this,"createTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request("/tickets/",{method:"POST",body:Qr({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 kn._fromResponse(n,this)});S(this,"confirmEndOfChat",async({messageId:t,ticketId:n,confirmed:r})=>{this._assertAuthenticated(this._apiClient),await this._apiClient.request(`/tickets/${encodeURIComponent(n)}/edit_message/`,{method:"PATCH",body:{messageId:t,messageData:JSON.stringify({type:Fi,body:{state:r?Rn.CONFIRMED:Rn.DECLINED,ticketId:n}})}})});this._logger=t.logger,this._apiClient=new $d(t)}static init(t){return new as(t)}_assertAuthenticated(t){if(t.credential==null)throw new Error("DeskClient is not authenticated")}}class cs{constructor(){S(this,"authenticate",async t=>!1);S(this,"deauthenticate",()=>{});S(this,"refreshDeskAuthToken",async()=>!1);S(this,"setCustomerLanguage",async()=>{});S(this,"getTicket",async()=>{throw new Error("DeskClient is disabled via __SBA_USE_DESK_CLIENT__")});S(this,"confirmEndOfChat",async()=>{throw new Error("DeskClient is disabled via __SBA_USE_DESK_CLIENT__")})}static init(){return new cs}}function Fd(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 Ud=1440*60*1e3,Bd=typeof __SBA_USE_DESK_CLIENT__>"u"||__SBA_USE_DESK_CLIENT__;function We(e){if(!e)throw new Error("Not authenticated. Call authenticate() first.")}function Hd(e,t){return Object.entries(t).every(([n,r])=>e[n]===r)}const Gd=e=>{const t={conversationInitialRender:new Iu(e),conversationNotInteractiveTimeout:new wu(e),recoveryNotInteractiveTimeout:new qu(e),conversationListInitialRender:new Ru(e),aievAuthExpiredUnhandled:new yu(e),messagePendingStuck:new Ku(e),userPerceivedResponseTime:new ud(e),streamStalled:new Ju(e),typingIndicatorAbsentTimeout:new od(e),renderedContentUnusable:new ju(e),streamingMessageValidation:new nd(e),duplicateMessageResponse:new Du(e),messageLifecycleEvent:new Gu(e)};return{...t,clear:()=>{Object.values(t).forEach(n=>n.clear())}}};class wn extends _d{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,"cpaAuthorizationCodes");S(this,"queryParams");S(this,"_config",Gs());S(this,"_networkStateAdapter");S(this,"_scheduleForegroundTask");S(this,"_watchBackgrounded");S(this,"_forceCreateChannel");S(this,"_agentVersion");S(this,"_statsTrackers");S(this,"_liveMetricManager");S(this,"_operationQueue",dd());S(this,"dispose",()=>{this._operationQueue.isPending()||(this._logger.debug("AIAgent.dispose: start"),this._chatClient.dispose(),this._chatClient.chatSDK.connectionState==="OPEN"&&this._chatClient.chatSDK.disconnectWebSocket(),this._removeChannelHandler(),this._session=null,this._deskClient.deauthenticate(),this._statsTrackers.clear(),this._liveMetricManager.dispose(),this._logger.debug("AIAgent.dispose: end"))});S(this,"initConversationIfNeeded",(n,r)=>this._initConversationIfNeeded(n,r));S(this,"authenticate",n=>{if(!this.appId)return Promise.reject(new Error("appId is required"));if(!this.aiAgentId)return Promise.reject(new Error("aiAgentId is required"));const r=n&&"userId"in n?`auth:${n.userId}`:"auth:anon";return this._operationQueue(r,async()=>{var i,c,u,d,m;this._logger.debug("AIAgent.authenticate: start"),this._statsTrackers.conversationInitialRender.onAuthStart(),this._statsTrackers.conversationListInitialRender.onAuthStart();const s=this._getSessionCandidate(n),o=(i=s.userSessionCandidate)!=null&&i.userId?this._cache.messenger.getSettings(s.userSessionCandidate.userId):null;o!=null&&o.bot&&this._dispatcher.send(ut.MessengerSettingsUpdated({settings:o,source:"cache"}));try{const h=await this._chatClient.requestMessengerSettings({aiAgentId:this.aiAgentId,userId:(c=s.userSessionCandidate)==null?void 0:c.userId,language:this.language,country:this.countryCode,context:this.context,knownActiveChannelUrl:(u=o==null?void 0:o.active_channel)==null?void 0:u.channel_url,forceCreateChannel:this._forceCreateChannel,agentVersion:this._agentVersion});let f;if(h.auto_created_user)if(s.type==="manual")this._logger.warn("Received auto created user info but current session is manual. Ignoring auto created user info."),f={userId:s.userSessionCandidate.userId,authToken:s.userSessionCandidate.authToken};else{const{user_id:C,session_token:E,expire_at:_}=h.auto_created_user;this._cache.messenger.setAnonUser({userId:C,authToken:E,expireAt:_}),f={userId:C,authToken:E},this._logger.debug("AIAgent.authenticate: anonymous user created",C)}else f={userId:((d=s.userSessionCandidate)==null?void 0:d.userId)??"",authToken:((m=s.userSessionCandidate)==null?void 0:m.authToken)??""};this._cache.messenger.setSettings(f.userId,h),this._dispatcher.send(ut.MessengerSettingsUpdated({settings:h,source:"server"}));const g=(()=>{var C;return s.type==="anonymous"?ou(this._dispatcher):(C=s.userSessionCandidate)==null?void 0:C.sessionHandler})(),p=await this._chatClient.connect(f,g,C=>{var E;this._logger.debug("AIAgent: session token refreshed"),(E=this._session)==null||E._updateAuthToken(C),this._deskClient.refreshDeskAuthToken(C)},()=>{this._logger.debug("AIAgent: session token unavailable, deauthenticating desk"),this._deskClient.deauthenticate()},this.cpaAuthorizationCodes?{aiAgentId:this.aiAgentId,authCodes:this.cpaAuthorizationCodes}:void 0);return await this._deskClient.authenticate({userId:f.userId,accessToken:f.authToken,onDeskTokenRefreshRequired:async({reason:C})=>{var E;if(C===Ui.ERR_SESSION_KEY_EXPIRED){await new Promise(A=>setTimeout(A,2e3));const _=(E=this._session)==null?void 0:E.userSession.authToken;return _?await this._deskClient.refreshDeskAuthToken(_):!1}return!1}}),(o==null?void 0:o.language)!==h.language&&this._deskClient.setCustomerLanguage(this.language).catch(()=>{}),this._statsTrackers.conversationInitialRender.onAuthComplete(),this._statsTrackers.conversationListInitialRender.onAuthComplete(),this._session=new Cd({sdkUser:p,userSession:f,activeChannel:{url:h.active_channel.channel_url,status:"open"},dispatcher:this._dispatcher}),this._setupChannelHandler(),this._logger.debug("AIAgent.authenticate: end",{userId:f.userId}),h}catch(h){throw this._statsTrackers.conversationInitialRender.onAuthError(h),this._statsTrackers.conversationListInitialRender.onAuthError(h),h}})});S(this,"submitCPAAuthorizationCodes",async n=>{We(this._session),this._logger.debug("AIAgent.submitCPAAuthorizationCodes: start");const r=await this._chatClient.submitCPAAuthorizationCodes({aiAgentId:this.aiAgentId,authCodes:n});return this._logger.debug("AIAgent.submitCPAAuthorizationCodes: end",r),r});S(this,"deauthenticate",()=>this._operationQueue("deauth",async()=>{var r;this._logger.debug("AIAgent.deauthenticate: start");const n=(r=this._session)==null?void 0:r.userSession.userId;this._statsTrackers.clear();try{await this._chatClient.disconnect()}finally{this._deskClient.deauthenticate(),this._cache.messenger.clear(n),this._session=null,this._removeChannelHandler(),this._statsTrackers.clear()}this._logger.debug("AIAgent.deauthenticate: end")}));S(this,"createConversation",async n=>{We(this._session),this._logger.debug("AIAgent.createConversation: start",n);const r=await this._chatClient.requestMessengerSettings({...n,userId:this._session.userSession.userId,knownActiveChannelUrl:void 0,agentVersion:this._agentVersion}),s=r.active_channel.channel_url;return this._cache.messenger.setSettings(this._session.userSession.userId,r),this._logger.debug("AIAgent.createConversation: end",s),s});S(this,"searchConversation",async n=>{if(We(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:Ce.ConversationStatus.OPEN,limit:100}),s=[];for(;r.hasNext;){const o=await r.next();for(const i of o)Hd(i.context??{},n.context)&&s.push(i.channelInfo.url)}return this._logger.debug("AIAgent.searchConversation: end",{count:s.length}),s});S(this,"closeConversation",async n=>{var s;We(this._session),this._logger.debug("AIAgent.closeConversation: start",n);const r=await this._chatClient.getChannel(n);((s=r.conversation)==null?void 0:s.status)===Ce.ConversationStatus.OPEN?(await r.closeConversation(),this._session.activeChannel.url===n&&this._session._updateActiveChannel({url:n,status:"closed",conversationStatus:Ce.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 Ii(this.chatSDK,n??{}));S(this,"patchContext",async(n,r)=>{We(this._session),this._logger.debug("AIAgent.patchContext: start",{channelUrl:n,context:r});const s=await this._chatClient.patchContext(this.aiAgentId,n,r);return this._logger.debug("AIAgent.patchContext: end",s),{...s,context:s.context??{}}});S(this,"updateContext",async(n,r)=>{We(this._session),this._logger.debug("AIAgent.updateContext: start",{channelUrl:n,context:r});const s=await this._chatClient.updateContext(this.aiAgentId,n,r);return this._logger.debug("AIAgent.updateContext: end",s),{...s,context:s.context??{}}});S(this,"getContextObject",async n=>{We(this._session),this._logger.debug("AIAgent.getContextObject: start",n);const s=await(await this._chatClient.getChannel(n)).getContextObject(this.aiAgentId);return this._logger.debug("AIAgent.getContextObject: end",s),{...s,context:s.context??{}}});S(this,"requestNudgeMessage",async n=>{We(this._session);const r=this._session;this._logger.debug("AIAgent.requestNudgeMessage: start",n);const s=await this._chatClient.requestNudgeMessage({aiAgentId:this.aiAgentId,key:n.key,context:n.context,language:this.language});if(this._logger.debug("AIAgent.requestNudgeMessage: end",s),this._session!==r){this._logger.debug("AIAgent.requestNudgeMessage: session changed during request, discarding stale nudge");return}s.status!=="ok"||!s.payload.message||this._dispatcher.send(ut.NudgeMessageReceived({message:s.payload.message,callbackUserMessage:s.payload.callback_user_message??void 0}))});S(this,"clearUserMemories",async(n={})=>{We(this._session);const r={...n,contextAiAgentId:n.contextAiAgentId??this.aiAgentId};this._logger.debug("AIAgent.clearUserMemories: start",r),await this._chatClient.clearUserMemories(r),this._logger.debug("AIAgent.clearUserMemories: end")});S(this,"confirmEndOfChat",async n=>{We(this._session),this._logger.debug("AIAgent.confirmEndOfChat: start",n),await this._deskClient.confirmEndOfChat(n),this._logger.debug("AIAgent.confirmEndOfChat: end")});S(this,"setUserMemoryState",async n=>{We(this._session);const r=this._session;this._logger.debug("AIAgent.setUserMemoryState: start",n.enabled);const s={...n,contextAiAgentId:n.contextAiAgentId??this.aiAgentId},o=r.userSession.userId,i=await this._chatClient.setUserMemoryState(s);if(this._session!==r)return this._logger.debug("AIAgent.setUserMemoryState: session changed during request, discarding stale result"),Rr(i);const c=this._cache.messenger.getSettings(o);if(c){const u={...c,memory:i};this._cache.messenger.setSettings(o,u),this._dispatcher.send(ut.MessengerSettingsUpdated({settings:u,source:"cache"}))}return this._logger.debug("AIAgent.setUserMemoryState: end",i.enabled),Rr(i)});S(this,"refreshActiveChannel",async n=>{var c,u,d;We(this._session);const r=this._session,s=(n==null?void 0:n.useKnownActiveChannelUrl)??!0;this._logger.debug("AIAgent.refreshActiveChannel: start",{useKnownActiveChannelUrl:s});const o=await this._chatClient.requestMessengerSettings({aiAgentId:this.aiAgentId,userId:r.userSession.userId,language:this.language,country:this.countryCode,context:this.context,knownActiveChannelUrl:s?(u=(c=this._cache.messenger.getSettings(r.userSession.userId))==null?void 0:c.active_channel)==null?void 0:u.channel_url:void 0,forceCreateChannel:this._forceCreateChannel,agentVersion:this._agentVersion});if(this._session!==r)return this._logger.debug("AIAgent.refreshActiveChannel: session changed during refresh, discarding stale result"),((d=this._session)==null?void 0:d.activeChannel.url)??o.active_channel.channel_url;const i=o.active_channel.channel_url;return this._cache.messenger.setSettings(this._session.userSession.userId,o),this._session._updateActiveChannel({url:i,status:"open"}),this._logger.debug("AIAgent.refreshActiveChannel: end",i),i});S(this,"_getSessionCandidate",n=>n instanceof wi?{type:"manual",userSessionCandidate:this._getManualSessionInfo(n)}:n instanceof Tr?{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-Ud<=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 Tr)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.cpaAuthorizationCodes=n.cpaAuthorizationCodes,this.config=n.config,this.queryParams=n.queryParams,this._networkStateAdapter=n.networkStateAdapter,this._scheduleForegroundTask=Od(n.foregroundStateAdapter),this._watchBackgrounded=n.foregroundStateAdapter&&Nd(n.foregroundStateAdapter),this._forceCreateChannel=n.forceCreateChannel,this._agentVersion=n.agentVersion,this._chatClient=n.chatClient,this._deskClient=n.deskClient,this._cache=n.cache,this._logger=n.logger,this._dispatcher=n.dispatcher,this._statsTrackers=n.statsTrackers,this._liveMetricManager=new su(this._chatClient.chatSDK),this._liveMetricManager.start()}static init(n){var g;const r=$i.get(n.platform),s=n.logger??new ki(n.logLevel??Jr.WARN),o=n.dispatcher??new xi(s),i=n.useMMKVStorage?Fd(n.useMMKVStorage):r.keyValueStorage,c=n.useMMKVStorage?{...n.chatParams,useMMKVStorageStore:n.useMMKVStorage}:n.chatParams,u=Cl({appId:n.appId,aiAgentId:n.aiAgentId,storage:i});let d;const h=Gd((p,C)=>{if(!d)throw new Error("ChatClient is not initialized.");return d.chatSDK.aiAgent.appendStat(p,C)});d=ss.init({appId:n.appId,aiAgentId:n.aiAgentId,messengerVersion:r.messengerVersion,extensions:{platform:r.platform,deviceOSPlatform:r.deviceOSPlatform,deviceOSVersion:r.deviceOSVersion,customData:n._sourceService?{source_service:n._sourceService}:void 0},chatParams:c,chatSDK:n.chatSDK,logger:s,cache:u,statsTrackers:h});const f=Bd?as.init({appId:n.appId,logger:s,customApiHost:(g=n.deskParams)==null?void 0:g.customApiHost}):cs.init();return s.debug("AIAgent.init: created",{appId:n.appId,aiAgentId:n.aiAgentId}),new wn({appId:n.appId,aiAgentId:n.aiAgentId,language:n.language,countryCode:n.countryCode,context:n.context,cpaAuthorizationCodes:n.cpaAuthorizationCodes,config:n.config,queryParams:n.queryParams,networkStateAdapter:r.networkStateAdapter,foregroundStateAdapter:r.foregroundStateAdapter,forceCreateChannel:n._forceCreateChannel,agentVersion:n._agentVersion,chatClient:d,deskClient:f,cache:u,logger:s,dispatcher:o,statsTrackers:h})}get chatSDK(){return this._chatClient.chatSDK}get deskClient(){return this._deskClient}get session(){return this._session}get config(){return this._config}set config(n){const r=Gs(n);gd(r,this._config)||(this._config=r)}get agentVersion(){return this._agentVersion}set agentVersion(n){this._agentVersion=n}get statsTrackers(){return this._statsTrackers}get liveMetricManager(){return this._liveMetricManager}get onLiveMetric(){return this._liveMetricManager.dispatch}set onLiveMetric(n){this._liveMetricManager.dispatch=n}get networkStateAdapter(){return this._networkStateAdapter}get logger(){return this._logger}get dispatcher(){return this._dispatcher}get cache(){return this._cache}get scheduleForegroundTask(){return this._scheduleForegroundTask}get watchBackgrounded(){return this._watchBackgrounded}}const ye=(e,t)=>{const n=l.createContext(t??null),r=({children:i,value:c})=>a.createElement(n.Provider,{value:c},typeof i=="function"?i(c):i),s=({children:i})=>a.createElement(n.Consumer,null,c=>c?typeof i=="function"?i(c):i:null),o=()=>{const i=l.useContext(n);if(!i)throw new Error(`use${e}Context must be used within a ${e}Provider`);return i};return n.displayName=`${e}Context`,r.displayName=`${e}Provider`,s.displayName=`${e}Consumer`,o.displayName=`use${e}Context`,{Context:n,Provider:r,Consumer:s,useContext:o}};function Qe(e){const t=l.createContext({Template:e.template,updateTemplate:()=>{},components:e.components,updateComponent:()=>{}});function n({children:o}){const[i,c]=l.useState(()=>e.template),[u,d]=l.useState(e.components),m=l.useCallback(g=>c(()=>g),[]),h=l.useCallback((g,p)=>d(C=>C[g]===p?C:{...C,[g]:p}),[]),f=l.useMemo(()=>({Template:i,updateTemplate:m,components:u,updateComponent:h}),[i,u,m,h]);return a.createElement(t.Provider,{value:f},o)}function r({template:o,children:i}){const{updateTemplate:c}=l.useContext(t);return l.useLayoutEffect(()=>{o&&c(o)},[o]),a.createElement(a.Fragment,null,i)}function s({children:o}){return a.createElement(n,null,o)}return s.defaults=e,s.useContext=()=>l.useContext(t),s.Context=t,s.Template=r,Object.keys(e.components).forEach(o=>{s[o]=function({component:c}){const{updateComponent:u}=l.useContext(t);return l.useLayoutEffect(()=>{c&&u(o,c)},[c]),null}}),s}function zd(...e){return function({children:n}){return e.reduce((r,s)=>a.createElement(s,null,r),n)}}function Vd(e,t){const n=e.lastMessage;return n!=null&&n.isAdminMessage()?n.message??"":Kd(e,t)}function Kd(e,t){var r;const n=e.lastMessage;if(n!=null&&n.isUserMessage())return n.message||"";if(n!=null&&n.isAdminMessage())return n.message??"";if(n!=null&&n.isFileMessage())return n.message||n.name||"FILE";if(n!=null&&n.isMultipleFilesMessage()){if(n.message)return n.message;const s=n.fileInfoList.length;return((r=t==null?void 0:t.formatMultipleFilesCount)==null?void 0:r.call(t,s))??`${s} photos`}return e.name}function qd(e,t,n){var i;const r=new Date,s=new Date(((i=e.lastMessage)==null?void 0:i.createdAt)||e.createdAt),o=gt.differenceInMinutes(r,s);return o<1?n.justNow:o<60?n.minutesAgo(o):gt.isToday(s)?n.hoursAgo(gt.differenceInHours(r,s)):t(s,n.dateShortFormat)}const Wd=typeof __SBA_USE_DESK_CLIENT__>"u"||__SBA_USE_DESK_CLIENT__,Yd=({data:e,extendedMessagePayload:t,ticketClosureLabels:n})=>{if(Wd){const r=Dd(e);if(r)return r.state!==Rn.WAITING?[]:[{action:"confirmTicketClosure",label:n.confirm,confirmed:!0,ticketId:r.ticketId},{action:"confirmTicketClosure",label:n.decline,confirmed:!1,ticketId:r.ticketId}]}return((t==null?void 0:t.suggested_replies)??[]).map(r=>({action:"sendMessage",label:r}))},jd=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},gn=e=>Math.max(0,Math.min(255,e)).toString(16).padStart(2,"0"),Ks=(e,t)=>{const n=gn(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=jd(e);return r?`#${gn(r[0])}${gn(r[1])}${gn(r[2])}${n}`:e},Xd=(e,t)=>{if(!t)return e;const n={...e};for(const[r,s]of Object.entries(t))s&&(n[r]=s);return n},Zd=e=>e.consentDialog?"consent":e.toggleAllowed?e.enabled?"on":"off":"readonly",Jd=e=>e.length>0,Qd=e=>{const t=e[0];if(!t)return e;const n=e.some(s=>Ve(s.type)),r=e.some(s=>!Ve(s.type));return n&&r?Ve(t.type)?e.filter(s=>Ve(s.type)):[t]:r?[t]:e},qs=e=>e.length===0?"empty":e.every(t=>Ve(t.type))?"images":"non_images",em=({currentFiles:e,incomingFiles:t,maxAttachmentCount:n})=>{const r=Qd(t),s=qs(e),o=qs(r),c=s==="images"&&o==="images"?{type:"append",files:r,nextFiles:[...e,...r]}:{type:"replace",files:r,nextFiles:r};return c.nextFiles.length>n?{type:"reject",reason:"count_limit",maxAttachmentCount:n,nextFileCount:c.nextFiles.length}:c.type==="replace"&&s!=="empty"&&s!==o?{type:"confirm_replace",action:c}:{type:"apply",action:c}},Nt=3,Bi=6,tm=e=>e%Nt===0?Nt:Bi,nm=({index:e,itemCount:t})=>{const n=t%Nt,r=n>0,s=r?t-n:t,o=r&&e>=s,i=o?n:Nt,c=o?e-s:e%Nt,u=!r&&e>=t-Nt;return{columnSpan:r?Bi/i:1,rowItemCount:i,isLastInRow:c===i-1,isLastRow:o||u}},Hi=ye("AIAgent"),rm=Hi.Provider,Ie=Hi.useContext;function sm(e){const t=om(e),n=l.useMemo(()=>({_aiAgentSDK:t,chatSDK:t.chatSDK,deskClient:t.deskClient,appId:t.appId,aiAgentId:t.aiAgentId,language:t.language,countryCode:t.countryCode,context:t.context,cpaAuthorizationCodes:t.cpaAuthorizationCodes,logger:t.logger,dispatcher:t.dispatcher,cache:t.cache,networkStateAdapter:t.networkStateAdapter,queryParams:t.queryParams,config:t.config,handlers:e.handlers}),[t,t.chatSDK,t.deskClient,t.appId,t.aiAgentId,t.language,t.countryCode,t.context,t.cpaAuthorizationCodes,t.logger,t.dispatcher,t.cache,t.networkStateAdapter,t.queryParams,t.config,e.handlers]);return a.createElement(rm,{value:n},e.children)}function om(e){var s;const t=l.useRef(null),n=l.useRef(null);if(!t.current||!n.current)t.current=wn.init(e);else{const o=im(n.current,e);(o.appId||o.aiAgentId||o.chatSDK)&&(t.current.dispose(),t.current=wn.init({...e,chatParams:o.appId?{...e.chatParams,newInstance:!0}:e.chatParams}))}n.current=e,l.useEffect(()=>()=>{var o;(o=t.current)==null||o.dispose()},[]);const r=t.current;return r.language=e.language??"en",r.countryCode=e.countryCode,r.context=e.context,r.cpaAuthorizationCodes=e.cpaAuthorizationCodes,r.queryParams=e.queryParams,r.config=e.config,r.agentVersion=e._agentVersion,r.onLiveMetric=(s=e.handlers)==null?void 0:s.onLiveMetric,r}function im(e,t){const n=t.chatSDK!==void 0&&t.chatSDK!==null;return{appId:!n&&e.appId!==t.appId,aiAgentId:e.aiAgentId!==t.aiAgentId,chatSDK:!!e.chatSDK!==n||n&&t.chatSDK!==e.chatSDK}}function ce(e){const t=l.useRef(e);return t.current=e,l.useCallback((...n)=>t.current(...n),[t])}const Hn=()=>{const[e,t]=l.useState(0),n=l.useCallback(()=>t(r=>r+1),[]);return n.revision=e,n};let am=0;function cm(){return l.useState(()=>`${am++}`)[0]}const Ct=(e,t,n)=>{const r=l.useRef(t),o=cm();r.current=t,l.useEffect(()=>{var c;const i=u=>{const d=u;return Object.keys(d).forEach(h=>{d[h]=(...f)=>{var p;const g=r.current;(p=g[h])==null||p.call(g,...f)}}),d};return(c=e==null?void 0:e.groupChannel)==null||c.addGroupChannelHandler(o,i(new rt.GroupChannelHandler)),()=>{var u;(u=e==null?void 0:e.groupChannel)==null||u.removeGroupChannelHandler(o)}},[e==null?void 0:e.groupChannel,o])};function lm(e,t){return!e||!t?!0:e.url!==t.url}function je(e){return e!=null&&"sendingStatus"in e}function um(e,t="##__USER_ID_IS_NOT_PROVIDED__##"){var n;return je(e)?((n=e.sender)==null?void 0:n.userId)===t:!1}function dm(e,t){return um(e,t)||e.isAdminMessage()?!1:e.updatedAt===0}function Ws(e){return"sendingStatus"in e?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId)}const Ln={collection:{groupChannel:{defaultOrder:rt.GroupChannelListOrder.LATEST_LAST_MESSAGE},message:{defaultLimit:{next:25,prev:25},searchLimit:{next:10,prev:10}}}};function Ys(e){return!e||!Array.isArray(e)?!1:e.length!==0}function js(e,t){return e.reduce((n,r)=>{const s=t(r);return n[s]=r,n},{})}const mm=({...e},t)=>{switch(t.type){case"update_initialized":return e.initialized=t.value.status,e;case"update_refreshing":return e.refreshing=t.value.status,e;case"update_loading":return e.loading=t.value.status,e;case"update_messages":{if(t.value.clearBeforeAction)e.messageMap=hm(t.value.messages);else{const n={...e.messageMap},r=[],s=[];t.value.messages.forEach(o=>{const i=je(o)?o.reqId:void 0,c=o.messageId||void 0;[i,c].forEach(u=>{if(!u)return;const d=n[u];fm(d,o,t.value.strictStreamingOrder)&&(d&&r.push(d),o.parentMessageId>0&&(d!=null&&d.parentMessage)&&o.applyParentMessage(d.parentMessage),s.push(o))})}),r.forEach(o=>{je(o)&&delete n[o.reqId],delete n[o.messageId]}),s.forEach(o=>{je(o)&&(n[o.reqId]=o),o.messageId!==0&&(n[o.messageId]=o)}),e.messageMap=n}return e}case"update_new_messages":{const n=t.value.currentUserId,r=t.value.messages.filter(s=>dm(s,n));return t.value.clearBeforeAction?e.newMessageMap=js(r,Ws):(r.map(o=>o.messageId).forEach(o=>delete e.newMessageMap[o]),e.newMessageMap={...e.newMessageMap,...js(r,Ws)}),e}case"delete_messages":case"delete_new_messages":{const n=t.type==="delete_messages"?"messageMap":"newMessageMap";return e[n]={...e[n]},t.value.messageIds.forEach(r=>{if(r===0)return;const s=e[n][r];s&&(je(s)&&delete e[n][s.reqId],delete e[n][s.messageId])}),t.value.reqIds.forEach(r=>{const s=e[n][r];s&&(je(s)&&delete e[n][s.reqId],delete e[n][s.messageId])}),e}}},hm=e=>e.reduce((t,n)=>(je(n)?(t[n.reqId]=n,n.sendingStatus===we.SendingStatus.SUCCEEDED&&(t[n.messageId]=n)):t[n.messageId]=n,t),{}),fm=(e,t,n=!1)=>{var r,s;if(!je(e)||!je(t))return!0;if(n&&e&&Ae.isStreaming(e)&&Ae.isStreaming(t)){const o=((r=e.message)==null?void 0:r.length)||0,i=((s=t.message)==null?void 0:s.length)||0;if(o>i)return!1}return e.sendingStatus===we.SendingStatus.SUCCEEDED?t.sendingStatus===we.SendingStatus.SUCCEEDED:e.sendingStatus!==t.sendingStatus},gm=(e=pm)=>{const[{initialized:t,loading:n,refreshing:r,messageMap:s,newMessageMap:o},i]=l.useReducer(mm,{initialized:!1,loading:!0,refreshing:!1,messageMap:{},newMessageMap:{}}),c=(E,_,A,y)=>{i({type:"update_messages",value:{messages:E,clearBeforeAction:_,currentUserId:A,strictStreamingOrder:y}})},u=(E,_)=>{i({type:"delete_messages",value:{messageIds:E,reqIds:_}})},d=(E,_,A)=>{i({type:"update_new_messages",value:{messages:E,clearBeforeAction:_,currentUserId:A}})},m=(E,_)=>{i({type:"delete_new_messages",value:{messageIds:E,reqIds:_}})},h=E=>{i({type:"update_initialized",value:{status:E}})},f=E=>{i({type:"update_loading",value:{status:E}})},g=E=>{i({type:"update_refreshing",value:{status:E}})},p=l.useMemo(()=>Object.values(o),[o]),C=l.useMemo(()=>Array.from(new Set(Object.values(s))).sort(e),[s]);return{updateInitialized:h,updateLoading:f,updateRefreshing:g,updateMessages:c,deleteMessages:u,initialized:t,loading:n,refreshing:r,messages:C,newMessages:p,updateNewMessages:d,deleteNewMessages:m}},Xs=Math.floor(Number.MAX_SAFE_INTEGER/10);function pm(e,t){let n=0,r=0;return je(e)&&e.sendingStatus!=="succeeded"&&(n=Xs),je(t)&&t.sendingStatus!=="succeeded"&&(r=Xs),e.createdAt+n-(t.createdAt+r)}const Em=(e,t,n)=>{var o;const r={prevResultLimit:t.prev,nextResultLimit:t.next,startingPoint:n==null?void 0:n.startingPoint,replyType:n==null?void 0:n.replyType},s=(o=n==null?void 0:n.collectionCreator)==null?void 0:o.call(n,r);return s||e.createMessageCollection({...r,filter:new rt.MessageFilter(r)})};function Zs(e){return e<Date.now()?Ln.collection.message.searchLimit:Ln.collection.message.defaultLimit}const _m=(e,t,n={})=>{var xe,Oe;const r=l.useRef(n);r.current=n;const s=l.useRef(t);s.current=t;const o=r.current.logger,i=r.current.startingPoint??Number.MAX_SAFE_INTEGER,c=Zs(i),u=r.current.strictStreamingOrder??!1,d=l.useRef({prev:!1,next:!1}),m=Hn(),h=l.useRef({initialized:!1,apiInitialized:!1,instance:null}),{initialized:f,loading:g,refreshing:p,messages:C,newMessages:E,updateMessages:_,updateNewMessages:A,deleteNewMessages:y,deleteMessages:T,updateInitialized:M,updateLoading:O,updateRefreshing:w}=gm(n==null?void 0:n.sortComparator),R=ce(I=>{var k,D,U,Z;if(!s.current||!s.current.url)return(k=o==null?void 0:o.error)==null?void 0:k.call(o,"[useGroupChannelMessages] channel is required");try{switch(I){case _e.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case _e.CollectionEventSource.EVENT_MESSAGE_SENT_SUCCESS:case _e.CollectionEventSource.SYNC_MESSAGE_FILL:case void 0:(U=(D=r.current).markAsRead)==null||U.call(D,[s.current]);break}}catch(oe){(Z=o==null?void 0:o.warn)==null||Z.call(o,"[useGroupChannelMessages/markAsReadBySource]",oe)}}),x=ce((I,k)=>{var D,U,Z,oe,Q;if(k.length>0)switch(I){case _e.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case _e.CollectionEventSource.SYNC_MESSAGE_FILL:{(U=(D=r.current).shouldCountNewMessages)!=null&&U.call(D)&&A(k,!1,(Z=e.currentUser)==null?void 0:Z.userId),(Q=(oe=r.current).onMessagesReceived)==null||Q.call(oe,k);break}}}),$=ce(I=>{var k,D;(D=(k=r.current).onCollectionEvent)==null||D.call(k,I)}),N=ce(async(I,k,D)=>new Promise((U,Z)=>{var K,me,he;h.current.instance&&h.current.instance.dispose(),R(),A([],!0,(K=e.currentUser)==null?void 0:K.userId);const oe=()=>{var de,be;const{pendingMessages:ie,failedMessages:pe}=h.current.instance??{};Ys(ie)&&_(ie,!1,(de=e.currentUser)==null?void 0:de.userId),Ys(pe)&&_(pe,!1,(be=e.currentUser)==null?void 0:be.userId)},Q=Em(I,D,{...r.current,startingPoint:k});h.current={apiInitialized:!1,initialized:!1,instance:Q},Q.setMessageCollectionHandler({onMessagesAdded:(ie,pe,de)=>{var be;R(ie.source),x(ie.source,de),_(de,!1,(be=e.currentUser)==null?void 0:be.userId,u),$({kind:"messagesAdded",source:ie.source,channelUrl:I.url,messages:de})},onMessagesUpdated:(ie,pe,de)=>{var be,Ue,Be;R(ie.source),x(ie.source,de),_(de,!1,(be=e.currentUser)==null?void 0:be.userId,u),ie.source===_e.CollectionEventSource.EVENT_MESSAGE_UPDATED&&((Be=(Ue=r.current).onMessagesUpdated)==null||Be.call(Ue,de)),$({kind:"messagesUpdated",source:ie.source,channelUrl:I.url,messages:de})},onMessagesDeleted:(ie,pe,de,be)=>{const Ue=be.map(Ze=>Ze.messageId),Be=be.filter(je).map(Ze=>Ze.reqId);T(Ue,Be),y(Ue,Be),$({kind:"messagesDeleted",source:ie.source,channelUrl:I.url,messages:be})},onChannelDeleted:(ie,pe)=>{var de,be;(be=(de=r.current).onChannelDeleted)==null||be.call(de,pe)},onChannelUpdated:(ie,pe)=>{var de,be;m(),(be=(de=r.current).onChannelUpdated)==null||be.call(de,pe,ie)},onHugeGapDetected:()=>{N(I,Number.MAX_SAFE_INTEGER,Ln.collection.message.defaultLimit)}});let Se=!1;(he=(me=r.current).onCollectionInitializeStart)==null||he.call(me),Q.initialize(rt.MessageCollectionInitPolicy.CACHE_AND_REPLACE_BY_API).onCacheResult((ie,pe)=>{var de,be,Ue,Be,Ze;(be=(de=r.current).onCacheResult)==null||be.call(de,ie,pe??[],I.url),ie?(e.isCacheEnabled&&((Ue=o==null?void 0:o.error)==null||Ue.call(o,"[useGroupChannelMessages/onCacheResult]",ie)),Se=!0):pe&&((Be=o==null?void 0:o.debug)==null||Be.call(o,"[useGroupChannelMessages/onCacheResult]","message length:",pe.length),_(Q.succeededMessages,!0,(Ze=e.currentUser)==null?void 0:Ze.userId),oe(),pe.length>0&&(h.current.initialized=!0,U())),$({kind:"initialized",source:"cache",channelUrl:I.url,messages:pe??[],error:ie})}).onApiResult((ie,pe)=>{var de,be,Ue,Be,Ze,Pe,tt;(be=(de=r.current).onApiResult)==null||be.call(de,ie,pe??[],I.url),h.current.initialized=!0,h.current.apiInitialized=!0,ie?((Ue=o==null?void 0:o.warn)==null||Ue.call(o,"[useGroupChannelMessages/onApiResult]",ie),Se?Z(ie):U()):pe&&((Be=o==null?void 0:o.debug)==null||Be.call(o,"[useGroupChannelMessages/onApiResult]","message length:",pe.length),_(Q.succeededMessages,!0,(Ze=e.currentUser)==null?void 0:Ze.userId),r.current.startingPoint||(tt=(Pe=r.current).onMessagesReceived)==null||tt.call(Pe,pe),e.isCacheEnabled&&oe(),U()),$({kind:"initialized",source:"api",channelUrl:I.url,messages:pe??[],error:ie})})}));Ct(e,{onUserBanned(I,k){var D,U,Z;I.isGroupChannel()&&!lm(I,s.current)&&(k.userId===((D=e.currentUser)==null?void 0:D.userId)?(Z=(U=r.current).onCurrentUserBanned)==null||Z.call(U):m())}}),l.useLayoutEffect(()=>{const I=setTimeout(async()=>{e.currentUser&&s.current&&(M(!1),O(!0),await N(s.current,i,c),O(!1),M(!0))});return()=>clearTimeout(I)},[e,(xe=e.currentUser)==null?void 0:xe.userId,(Oe=s.current)==null?void 0:Oe.url,r.current.replyType]),l.useEffect(()=>()=>{h.current.instance&&h.current.instance.dispose()},[]);const J=ce(async()=>{e.currentUser&&s.current&&(w(!0),await N(s.current,Number.MAX_SAFE_INTEGER,Ln.collection.message.defaultLimit),w(!1))}),se=ce(async()=>{var k;const I=h.current.instance;if(I!=null&&I.hasPrevious&&!d.current.prev)try{d.current.prev=!0;const D=await I.loadPrevious();_(D,!1,(k=e.currentUser)==null?void 0:k.userId)}catch{}finally{d.current.prev=!1}}),Y=ce(()=>{const{initialized:I,instance:k}=h.current;return I&&k?k.hasPrevious:!1}),j=ce(async()=>{var k;const I=h.current.instance;if(I!=null&&I.hasNext&&!d.current.next)try{d.current.next=!0;const D=await I.loadNext();_(D,!1,(k=e.currentUser)==null?void 0:k.userId)}catch{}finally{d.current.next=!1}}),P=ce(()=>{const{initialized:I,apiInitialized:k,instance:D}=h.current;return k&&I&&D?D.hasNext:!1}),V=I=>{var k,D,U,Z;!I||I.channelUrl!==((k=s.current)==null?void 0:k.url)||(_([I],!1,(D=e.currentUser)==null?void 0:D.userId),(Z=(U=r.current).onOutgoingMessageStatusChanged)==null||Z.call(U,I))},q=ce((I,k)=>{var D;if(!s.current||!s.current.url)throw(D=o==null?void 0:o.error)==null||D.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((U,Z)=>{s.current.sendUserMessage(I).onPending(oe=>{V(oe),k==null||k(oe)}).onSucceeded(oe=>{V(oe),U(oe)}).onFailed((oe,Q)=>{V(Q),Z(oe)})})}),W=ce((I,k)=>{var D;if(!s.current||!s.current.url)throw(D=o==null?void 0:o.error)==null||D.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((U,Z)=>{s.current.sendFileMessage(I).onPending(oe=>{V(oe),k==null||k(oe)}).onSucceeded(oe=>{V(oe),U(oe)}).onFailed((oe,Q)=>{V(Q),Z(oe)})})}),H=ce((I,k,D)=>{var U;if(!s.current||!s.current.url)throw(U=o==null?void 0:o.error)==null||U.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((Z,oe)=>{s.current.sendMultipleFilesMessage(I).onPending(Q=>{V(Q),k==null||k(Q)}).onFileUploaded(Q=>{D==null||D(Q),m()}).onSucceeded(Q=>{V(Q),Z(Q)}).onFailed((Q,Se)=>{V(Se),oe(Q)})})}),G=ce(async(I,k)=>{var U,Z;if(!s.current||!s.current.url)throw(U=o==null?void 0:o.error)==null||U.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");const D=await s.current.updateUserMessage(I,k);return D.channelUrl===s.current.url&&_([D],!1,(Z=e.currentUser)==null?void 0:Z.userId),D}),z=ce(async(I,k)=>{var U,Z;if(!s.current||!s.current.url)throw(U=o==null?void 0:o.error)==null||U.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");const D=await s.current.updateFileMessage(I,k);return D.channelUrl===s.current.url&&_([D],!1,(Z=e.currentUser)==null?void 0:Z.userId),D}),ee=ce(async(I,k,D)=>{var U;if(!s.current||!s.current.url)throw(U=o==null?void 0:o.error)==null||U.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((Z,oe)=>{let Q;I.isUserMessage()&&(Q=s.current.resendMessage(I)),I.isFileMessage()&&(Q=s.current.resendMessage(I)),I.isMultipleFilesMessage()&&(Q=s.current.resendMessage(I)),Q&&("onPending"in Q&&Q.onPending(Se=>{V(Se),k==null||k(Se)}),"onFileUploaded"in Q&&Q.onFileUploaded(Se=>{D==null||D(Se),m()}),"onSucceeded"in Q&&Q.onSucceeded(Se=>{V(Se),Z(Se)}),"onFailed"in Q&&Q.onFailed((Se,K)=>{V(K),oe(Se)}))})}),ae=ce(async I=>{var k,D,U,Z;if(!s.current||!s.current.url)throw(k=o==null?void 0:o.error)==null||k.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");if(I.sendingStatus==="succeeded")I.isUserMessage()&&await s.current.deleteMessage(I),I.isFileMessage()&&await s.current.deleteMessage(I),I.isMultipleFilesMessage()&&await s.current.deleteMessage(I);else try{await((D=h.current.instance)==null?void 0:D.removeFailedMessage(I.reqId))}finally{T([],[I.reqId]),(Z=(U=r.current).onLocalMessageDeleted)==null||Z.call(U,I)}}),L=ce(()=>{var I;A([],!0,(I=e.currentUser)==null?void 0:I.userId)}),ve=ce(async I=>{var k;if(e.currentUser&&s.current){const D=Zs(I);O(!0),_([],!0,(k=e.currentUser)==null?void 0:k.userId),await N(s.current,I,D),O(!1)}});return{initialized:f,loading:g,refreshing:p,collectionRevision:m.revision,messages:C,newMessages:E,resetNewMessages:L,refresh:J,loadPrevious:se,hasPrevious:Y,loadNext:j,hasNext:P,sendUserMessage:q,sendFileMessage:W,sendMultipleFilesMessage:H,updateUserMessage:G,updateFileMessage:z,resendMessage:ee,deleteMessage:ae,resetWithStartingPoint:ve,_dangerous_reducer_updateMessages:_,_dangerous_reducer_deleteMessages:T}},Cm=e=>e.customType==="SENDBIRD_DESK_ADMIN_MESSAGE_CUSTOM_TYPE"?!0:e.isAdminMessage()?e.message==="The channel's custom_type was updated.":!1,Sm=(e,t,n)=>{const r=_m(e,t,{...n,strictStreamingOrder:!0}),s=l.useMemo(()=>r.messages.filter(o=>!Cm(o)),[r.messages]);return{...r,messages:s}},bm=()=>{const e=new Set;return{publish:t=>{e.size!==0&&[...e].forEach(n=>{try{n(t)}catch{}})},subscribe:t=>{let n=!0;return e.add(t),()=>{n&&(n=!1,e.delete(t))}}}},Gn=bm(),vm=({channelUrl:e,enabled:t=!0,statsTracker:n})=>{const r=l.useRef(e),s=l.useRef(t),o=l.useRef(null),i=l.useRef(!1);s.current=t;const c=l.useCallback(p=>r.current===p,[]),u=l.useCallback(()=>{i.current&&(n.clearChannel(r.current),i.current=!1)},[n]),d=l.useCallback(p=>{c(p)&&s.current&&(i.current=!0)},[c]),m=l.useCallback(({channelUrl:p,conversationId:C})=>{i.current=!0,n.markChannelJoined(C,p)},[n]),h=l.useCallback(({channelUrl:p})=>{n.clearChannel(p),i.current=!1},[n]),f=l.useCallback(p=>{if(c(p.channelUrl)){if(!s.current){o.current=p;return}o.current=null,m(p)}},[c,m]),g=l.useCallback(p=>{if(c(p.channelUrl)){if(!s.current){o.current=p;return}o.current=null,h(p)}},[c,h]);return l.useEffect(()=>{if(t){const p=o.current;if(!p||(o.current=null,p.channelUrl!==e))return;"error"in p?h(p):m(p);return}u()},[e,u,t,h,m]),l.useEffect(()=>(r.current=e,o.current=null,i.current=!1,()=>{u(),o.current=null,i.current=!1}),[e,u]),{onFetchStart:d,onFetchSuccess:f,onFetchError:g}},ym=({channelUrl:e,enabled:t=!0,scheduleForegroundTask:n,statsTracker:r})=>{const s=l.useRef(e),o=l.useRef(null),i=l.useRef(t),c=l.useRef(0),u=l.useRef(null);i.current=t;const d=l.useCallback((h=!0)=>{var g;(g=o.current)==null||g.call(o),o.current=null;const f=u.current;h&&(u.current=null),h&&f&&r.clearChannel(f)},[r]),m=l.useCallback(h=>{if(!i.current){d(),r.clearChannel(h);return}d(!1),u.current=h;const f=c.current,g=()=>{if(!i.current||f!==c.current||s.current!==h){r.clearChannel(h),u.current===h&&(u.current=null);return}r.start("ws_reconnected",h)};o.current=(n==null?void 0:n(g))??null,n||g()},[d,n,r]);return l.useEffect(()=>{t||d()},[d,t]),l.useEffect(()=>(s.current=e,c.current+=1,()=>{c.current+=1,d()}),[e,d]),{onReconnectSucceeded:m}},Qt={DEFAULT_PRIMARY:"#000000",DEFAULT_BOT_MSG_BG:"#ECECEC",WHITE:"#ffffff",BLACK:"#000000"};function Gi(e){return e.length===4?`#${[...e.slice(1)].map(t=>t+t).join("")}`:e}function Am(e){const t=Gi(e);return[parseInt(t.slice(1,3),16),parseInt(t.slice(3,5),16),parseInt(t.slice(5,7),16)]}function Tm(e){return`#${e.map(t=>t.toString(16).padStart(2,"0")).join("")}`}function Im(e,t,n){e/=255,t/=255,n/=255;const r=Math.max(e,t,n),s=Math.min(e,t,n),o=r-s;let i=0,c=0;const u=(r+s)/2;return r!==s&&(c=u>.5?o/(2-r-s):o/(r+s)),r===e?i=(t-n)/o+(t<n?6:0):r===t?i=(n-e)/o+2:r===n&&(i=(e-t)/o+4),i/=6,[i,c,u]}function xm(e,t,n){let r,s,o;if(t===0)r=s=o=n;else{const i=function(m,h,f){return f<0&&(f+=1),f>1&&(f-=1),f<.16666666666666666?m+(h-m)*6*f:f<.5?h:f<.6666666666666666?m+(h-m)*(.6666666666666666-f)*6:m},c=n<.5?n*(1+t):n+t-n*t,u=2*n-c;r=i(u,c,e+1/3),s=i(u,c,e),o=i(u,c,e-1/3)}return[Math.round(r*255),Math.round(s*255),Math.round(o*255)]}function pn(e,t,n){const[r,s,o]=Am(e),[i,c,u]=Im(r,s,o),d=Math.max(0,Math.min(1,u*t)),m=Math.max(0,Math.min(1,c*n)),[h,f,g]=xm(i,m,d);return Tm([Math.round(h),Math.round(f),Math.round(g)])}function Mm(e,t="light"){return{extraDark:pn(e,.6,1.2),dark:pn(e,.85,1.1),main:e,light:pn(e,t==="dark"?1.1:1.5,t==="dark"?.95:.9),extraLight:pn(e,t==="dark"?1.2:1.75,t==="dark"?.9:.8)}}function kr(e){const t=Gi(e),n=149,r=+`0x${t[1]}${t[2]}`,s=+`0x${t[3]}${t[4]}`,o=+`0x${t[5]}${t[6]}`;return r*.299+s*.587+o*.114>n?Qt.BLACK:Qt.WHITE}function Rm(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},conversation:{headerProfileSkeleton:e.background100},memoryDialog:{titleText:e.onlight.textHighEmphasis,markdownBodyText:e.onlight.textLowEmphasis,markdownLinkText:e.onlight.textHighEmphasis,positiveBackground:e.onlight.textHighEmphasis,positiveText:e.ondark.textHighEmphasis,positiveBorderColor:"transparent",negativeBackground:"transparent",negativeText:e.onlight.textHighEmphasis,negativeBorderColor:"transparent"}}}const km=(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},conversation:{headerProfileSkeleton:e.background400},memoryDialog:{titleText:e.ondark.textHighEmphasis,markdownBodyText:e.ondark.textLowEmphasis,markdownLinkText:e.ondark.textHighEmphasis,positiveBackground:e.ondark.textHighEmphasis,positiveText:e.onlight.textHighEmphasis,positiveBorderColor:"transparent",negativeBackground:"transparent",negativeText:e.ondark.textHighEmphasis,negativeBorderColor:"transparent"}}),En={primary:{extraDark:"#491389",dark:"#6211c8",main:"#742ddd",light:"#c2a9fa",extraLight:"#dbd1ff"},secondary:{extraDark:"#066858",dark:"#027d69",main:"#259c72",light:"#69c085",extraLight:"#a8e2ab"},error:{extraDark:"#9d091e",dark:"#bf0711",main:"#de360b",light:"#f66161",extraLight:"#fdaaaa"},information:{extraDark:"#241389",dark:"#362ca9",main:"#4a48cd",light:"#a9bbfa",extraLight:"#d1dbff"},background700:"#000000",background600:"#161616",background500:"#2c2c2c",background400:"#393939",background300:"#bdbdbd",background200:"#e0e0e0",background100:"#eeeeee",background50:"#ffffff",onlight:{textHighEmphasis:"rgba(0, 0, 0, 1)",textMidEmphasis:"rgba(0, 0, 0, 0.75)",textLowEmphasis:"rgba(0, 0, 0, 0.55)",textDisabled:"rgba(0, 0, 0, 0.12)"},ondark:{textHighEmphasis:"rgba(255, 255, 255, 1)",textMidEmphasis:"rgba(255, 255, 255, 0.75)",textLowEmphasis:"rgba(255, 255, 255, 0.58)",textDisabled:"rgba(255, 255, 255, 0.12)"},overlay:{dark:"rgba(0, 0, 0, 0.55)",light:"rgba(22, 22, 22, 0.32)"}},ir={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 Js(e){const t=wm(e),n=Lm(e,t),r=Nm(n,e.colors,e.selectedTheme),s=Pm(e);return{selectedTheme:e.selectedTheme,palette:t,colors:r,aiAgentColorVariables:{primary_color:r.base.primary,primary_contrast_color:r.base.primaryContrastContent,bot_message_bg_color:r.messageIncoming.background,bot_message_bg_contrast_color:r.messageIncoming.text},typography:s}}function wm({selectedTheme:e,palette:t,primary:n}){const r=t!=null&&t.primary?t.primary:n?n===En.primary.main?En.primary:Mm(n,e):En.primary;return{...En,primary:r,...t}}function Lm({selectedTheme:e,primaryContrast:t,botMessageBackground:n,botMessageBackgroundContrast:r},s){const o=s.primary.main,i=t??kr(o),c=n??Qt.DEFAULT_BOT_MSG_BG,u=r??kr(c);return(e==="light"?Rm:km)(s,o,i,c,u)}function Om(e,t,n){return typeof e=="string"?e:e[t]??n}function Nm(e,t,n){var i;if(!t||Object.keys(t).length===0)return e;const r={...e},s=r,o=e;for(const c of Object.keys(t)){const u=t[c];if(u){s[c]={...s[c]};for(const[d,m]of Object.entries(u))if(m!==void 0){const h=((i=o[c])==null?void 0:i[d])??"";s[c][d]=Om(m,n,h)}}}return r}function Dm(e,t,n){const r={...e};return n.forEach(s=>{const o=t[s];o!=null&&(r[s]=o)}),r}function Pm({typography:e}){if(!e)return ir;const t={...ir};return Object.keys(e).forEach(n=>{const r=e[n];if(r&&typeof r=="object"){const s=ir[n],o=["fontSize","fontWeight","fontFamily","lineHeight"];t[n]=Dm(s,r,o)}}),t}const{Provider:$m,useContext:zn}=ye("AIAgentTheme");function Fm({logger:e,palette:t,typography:n,colors:r,appearance:s,children:o}){const i=l.useRef(null),[c,u]=l.useState(()=>Js({selectedTheme:(s==null?void 0:s.theme)??"light",palette:t,typography:n,colors:r,primary:s==null?void 0:s.primaryColor,botMessageBackground:s==null?void 0:s.botMessageBackgroundColor})),d=l.useCallback((h,f)=>{f&&(i.current=f);const g=(s==null?void 0:s.theme)??h,p=i.current?i.current.themes[g]:null,C={primary:s==null?void 0:s.primaryColor,primaryContrast:void 0,botMessageBackground:s==null?void 0:s.botMessageBackgroundColor,botMessageBackgroundContrast:void 0};!C.primary&&(p!=null&&p.primary_color)&&(C.primary=p.primary_color,C.primaryContrast=p.primary_contrast_color),!C.botMessageBackground&&(p!=null&&p.bot_message_bg_color)&&(C.botMessageBackground=p.bot_message_bg_color,C.botMessageBackgroundContrast=p.bot_message_bg_contrast_color);const E=Js({selectedTheme:g,palette:t,typography:n,colors:r,...C});u(E),e==null||e.info("theme.update:",g)},[s==null?void 0:s.theme,s==null?void 0:s.primaryColor,s==null?void 0:s.botMessageBackgroundColor,t,n,r,e]);l.useEffect(()=>{(s!=null&&s.theme||s!=null&&s.primaryColor||s!=null&&s.botMessageBackgroundColor)&&d(c.selectedTheme)},[s==null?void 0:s.theme,s==null?void 0:s.primaryColor,s==null?void 0:s.botMessageBackgroundColor]);const m=l.useMemo(()=>({theme:c,updateTheme:d}),[c,d]);return a.createElement($m,{value:m},o)}const ar=25*1024*1024,Qs=1,eo=new Set(["image/png","image/jpeg","image/jpg"]),to=new Set(["application/pdf"]),Um={off:"off",always:"always",handed_off_only:"handed_off_only"},Bm=()=>{const[e,t]=l.useState(()=>({maxAttachmentCount:Qs,attachmentMode:"handed_off_only",defaultUploadSizeLimit:ar,uploadSizeLimitPerType:new Map,supportedImageMimeTypes:eo,supportedFileMimeTypes:to})),n=l.useCallback(({active_channel:s,upload_restriction:o})=>{t({maxAttachmentCount:(o==null?void 0:o.max_attachment_count)??Qs,attachmentMode:Um[s.attachment_mode]??"handed_off_only",defaultUploadSizeLimit:(o==null?void 0:o.default_upload_size_limit)??ar,uploadSizeLimitPerType:new Map(Object.entries((o==null?void 0:o.upload_size_limit_per_type)??[])),supportedImageMimeTypes:new Set((o==null?void 0:o.supported_image_mime_types)??eo),supportedFileMimeTypes:new Set((o==null?void 0:o.supported_file_mime_types)??to)})},[]),r=l.useCallback(s=>{const{channel:o,uploadSizeLimit:i=ar}=s,c=(d=!0)=>o!=null&&o.isAIAgent?d?dt(o):!1:!0,u=d=>{if(c())return e.defaultUploadSizeLimit??i;const m=e.defaultUploadSizeLimit??i,h=e.uploadSizeLimitPerType.get(d)??m;return Math.min(m,h)};return{maxAttachmentCount:e.maxAttachmentCount,isEnabled:()=>{if(c(!1))return!0;switch(e.attachmentMode){case"off":return!1;case"always":return!0;case"handed_off_only":return dt(o);default:return!0}},get supportedMimeTypes(){return c()?[vr]:[...e.supportedImageMimeTypes,...e.supportedFileMimeTypes]},isSupportedMimeType:d=>c()?!0:e.supportedImageMimeTypes.has(d)||e.supportedFileMimeTypes.has(d),getUploadSizeLimit:u,getUploadSizeLimitInMB:d=>u(d)/(1024*1024)}},[e]);return{updateBaseAttachmentRules:n,createAttachmentRules:r}},no=(...e)=>{const[t,n,r]=e;if(e.length===1&&typeof t=="object"&&t!==null)return{type:"active",context:t};if(e.length===3&&typeof t=="string"&&typeof n=="string"&&typeof r=="object"&&r!==null)return{type:"specific",aiAgentId:t,channelUrl:n,context:r};throw new Error("Invalid arguments: expected (context) or (aiAgentId, channelUrl, context)")},Vt=e=>({...e,context:e.context??{}}),{Provider:Hm,useContext:et}=ye("AIAgentMessengerSession"),Gm=l.forwardRef(function({userSessionInfo:e,children:t},n){const{_aiAgentSDK:r,chatSDK:s,aiAgentId:o,logger:i}=Ie(),{updateTheme:c}=zn(),[u,d]=l.useState(void 0),[m,h]=l.useState(void 0),[f,g]=l.useState(null),[p,C]=l.useState(null),[E,_]=l.useState(null),[A,y]=l.useState(null),[T,M]=l.useState(null),{updateBaseAttachmentRules:O,createAttachmentRules:w}=Bm();l.useEffect(()=>{const N=r.onMessengerSettingsUpdated(({settings:Y})=>{const{appearance:j,bot:P,launcher:V,memory:q}=Y;c(j.selected_theme,j),_(pd(P)),y(Ed(V)),M(q?Rr(q):null),O(Y)}),J=r.onActiveChannelUpdated(({channelUrl:Y,status:j,conversationStatus:P})=>{h({url:Y,status:j,conversationStatus:P})}),se=r.onAuthTokenRefreshed(()=>{var j;const Y=(j=r.session)==null?void 0:j.userSession.authToken;Y&&C(P=>P?{...P,authToken:Y}:null)});return()=>{N(),J(),se()}},[r,c,O]);const R=l.useCallback(async()=>{try{const N=await r.authenticate(e),J=r.session;return g(J.sdkUser),C(J.userSession),h(J.activeChannel),d(void 0),N}catch(N){throw g(null),C(null),h(void 0),d(N),N}},[r,e]),x=l.useCallback(async()=>{await r.deauthenticate(),g(null),h(void 0),C(null),_(null),y(null),M(null)},[r]),$=l.useCallback(async()=>{if(!r.session){if(p)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!==(p==null?void 0:p.userId)?(i.debug("agentMessengerSession.refreshActiveChannel: stale call from previous session, skipping"),r.session.activeChannel.url):(h(void 0),await r.refreshActiveChannel())},[r,i,p]);return l.useImperativeHandle(n,()=>{const N=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:R,deauthenticate:x,submitCPAAuthorizationCodes:r.submitCPAAuthorizationCodes,updateContext:async(...J)=>{const se=no(...J);if(se.type==="active"){const P=await(await N()).updateContext(o,se.context);return Vt(P)}const Y=await s.aiAgent.updateContext(se.aiAgentId,se.channelUrl,se.context);return Vt(Y)},patchContext:async(...J)=>{const se=no(...J);if(se.type==="active"){const P=await(await N()).patchContext(o,se.context);return Vt(P)}const Y=await s.aiAgent.patchContext(se.aiAgentId,se.channelUrl,se.context);return Vt(Y)},getContextObject:async()=>{const se=await(await N()).getContextObject(o);return Vt(se)},requestNudgeMessage:J=>r.requestNudgeMessage(J)}},[R,x,m,s,o,i,r]),a.createElement(Hm,{value:{sdkUser:f,userSessionInfo:e,userSession:p,activeChannel:m,setActiveChannel:h,refreshActiveChannel:$,createConversation:r.createConversation,searchConversation:r.searchConversation,submitCPAAuthorizationCodes:r.submitCPAAuthorizationCodes,connectionError:u,aiAgentInfo:E,launcherInfo:A,memoryInfo:T,authenticate:R,deauthenticate:x,createAttachmentRules:w}},t)}),zm={ai_responding:"not_ready",conversation_closed:"ready",form_active:"ready",handoff_pending:"ready",reconnecting:"not_ready",steward:"ready",suggested_replies:"ready",system:"ready",unavailable:"not_ready"},Vm=e=>e.disabled?zm[e.disabledBy]==="ready":!0,Km=e=>{var n,r,s,o,i;if(e.isUserMessage())return"text";const t=e.isFileMessage()?e.type:((r=(n=e.fileInfoList)==null?void 0:n[0])==null?void 0:r.mimeType)??((i=(o=(s=e.messageParams)==null?void 0:s.fileInfoList)==null?void 0:o[0])==null?void 0:i.mimeType);return t&&Ve(t)?"file_image":t&&nn(t)?"file_video":t&&rl(t)?"file_audio":"file_document"};let ro=0;const qm=e=>(ro+=1,`${e??"unknown"}:${ro}`),Lt=(e,t)=>e===void 0||t===e,zi=(e,t)=>{!t.error&&t.messages.length>0&&e.conversationNotInteractiveTimeout.markHistoryLoaded("success",t.channelUrl)},Vi=(e,t)=>{t.error?e.conversationNotInteractiveTimeout.markHistoryLoaded("failed",t.channelUrl):e.conversationNotInteractiveTimeout.markHistoryLoaded(t.messages.length>0?"success":"verified_empty",t.channelUrl)},Wm=(e,t)=>{zi(e,t)},Ym=(e,t)=>{Vi(e,t)},jm=(e,t,n)=>{var o;if(!Fe(e,n))return;const{hasResponseMetadata:r,...s}=Kr(e.data);r&&(t.typingIndicatorAbsentTimeout.markAIResponseStarted({channelUrl:e.channelUrl,userMessageId:s.userMessageId}),t.userPerceivedResponseTime.markAIResponseRaw({messageId:e.messageId,channelUrl:e.channelUrl,aiResponse:s}),t.streamStalled.markRawProgress({messageId:e.messageId,channelUrl:e.channelUrl,textLength:((o=e.message)==null?void 0:o.length)??0,aiResponse:s}))},so=(e,t)=>{t.streamStalled.clearMessage(e.messageId),t.userPerceivedResponseTime.clearMessage(e.messageId);const n=Xe(e)?e.reqId:void 0;n&&(t.messagePendingStuck.disappear({requestId:n}),t.userPerceivedResponseTime.cancelTurn(n),t.typingIndicatorAbsentTimeout.cancelTurn(n))},cr=(e,t)=>{t&&(e.conversationNotInteractiveTimeout.clearChannel(t),e.recoveryNotInteractiveTimeout.clearChannel(t),e.messagePendingStuck.clearChannel(t),e.userPerceivedResponseTime.clearChannel(t),e.typingIndicatorAbsentTimeout.clearChannel(t),e.streamStalled.clearChannel(t))},Xm=({activeChannelUrl:e,statsTrackers:t})=>{const{chatSDK:n}=Ie(),{aiAgentInfo:r}=et(),s=l.useRef(!1),o=r==null?void 0:r.userId;Ct(!!e&&!!o?n:void 0,{onTypingStatusUpdated(c){if(c.url!==e)return;const u=c.getTypingUsers().some(m=>m.userId===o),d=s.current;u&&!d?t.typingIndicatorAbsentTimeout.markTypingStarted(c.url):!u&&d&&t.typingIndicatorAbsentTimeout.markTypingEnded(c.url),s.current=u}}),l.useEffect(()=>{s.current=!1},[e,o])},Zm=({enabled:e=!0,requestedChannelUrl:t,statsTrackers:n})=>{const r=l.useRef(void 0);l.useLayoutEffect(()=>{const s=r.current;if(!e){s&&(cr(n,s),r.current=void 0);return}s&&s!==t&&(cr(n,s),r.current=void 0),t&&s!==t&&(n.conversationNotInteractiveTimeout.start({channelUrl:t}),r.current=t)},[e,t,n]),l.useLayoutEffect(()=>()=>{const s=r.current;s&&(cr(n,s),r.current=void 0)},[n])},Jm=({aiAgentUserId:e,statsEnabled:t=!0,requestedChannelUrl:n,statsTrackers:r})=>{const s=l.useRef(null),o=l.useRef(null),i=l.useRef(!1),c=l.useRef(0),u=l.useRef(0),d=l.useRef(t),m=l.useMemo(()=>c.current+1,[n]);l.useLayoutEffect(()=>(i.current=!0,c.current=m,()=>{i.current=!1,c.current+=1}),[m]);const h=l.useCallback(g=>i.current&&c.current===g,[]);l.useLayoutEffect(()=>{u.current+=1,s.current=null,o.current=null},[n]),l.useLayoutEffect(()=>{const g=d.current;d.current=t,!(g||!t)&&(s.current&&(s.current.tracked=!1),o.current&&(o.current.tracked=!1))},[t]);const f=l.useCallback(g=>g.lifecycleGeneration===u.current&&Lt(n,g.channelUrl),[n]);return l.useEffect(()=>{if(!t)return;const g=s.current;g&&f(g)&&(g.tracked||(zi(r,g),g.tracked=!0));const p=o.current;p&&f(p)&&(p.tracked||(Vi(r,p),p.tracked=!0))},[t,f,r]),l.useMemo(()=>({onCollectionEvent:g=>{if(h(m)&&Lt(n,g.channelUrl)){if(g.kind==="messagesDeleted"){g.messages.forEach(p=>so(p,r));return}t&&g.messages.forEach(p=>jm(p,r,e))}},onCacheResult:(g,p,C)=>{if(!h(m)||!Lt(n,C))return;const E={error:g,messages:p,channelUrl:C,lifecycleGeneration:u.current,tracked:!1};s.current=E,t&&(Wm(r,E),E.tracked=!0)},onApiResult:(g,p,C)=>{if(!h(m)||!Lt(n,C))return;const E={error:g,messages:p,channelUrl:C,lifecycleGeneration:u.current,tracked:!1};o.current=E,t&&(Ym(r,E),E.tracked=!0)},onLocalMessageDeleted:g=>{h(m)&&Lt(n,g.channelUrl)&&so(g,r)}}),[e,m,t,h,n,r])},Qm=({enabled:e=!0,channelUrl:t,initialized:n,inputReady:r,renderedSignal:s,statsTrackers:o})=>{const i=l.useRef(!1),c=l.useRef(0);l.useEffect(()=>{c.current+=1,i.current=!1},[t,e]),l.useEffect(()=>{e&&(o.recoveryNotInteractiveTimeout.setInputEnabled(r,t),r&&o.conversationNotInteractiveTimeout.markInputReady(t))},[t,e,r,o]),l.useEffect(()=>{if(!e||!n||i.current)return;const u=c.current,d=setTimeout(()=>{c.current===u&&(o.conversationNotInteractiveTimeout.markRendered(t),i.current=!0)});return()=>clearTimeout(d)},[t,e,n,s,o])},eh=({channelUrl:e,enabled:t=!0,statsTrackers:n})=>{const r=l.useRef(!1),s=l.useRef(e),o=l.useRef(t),i=l.useRef(0);return l.useLayoutEffect(()=>(r.current=!0,s.current=e,o.current=t,i.current+=1,()=>{r.current=!1,i.current+=1}),[e,t]),l.useCallback(async(c,u,d={})=>{if(!r.current||!o.current)return c(C=>u==null?void 0:u(C),()=>{});let m;const h=i.current,f=s.current,g=()=>r.current&&o.current&&i.current===h&&s.current===f,p=C=>g()&&Lt(f,C);try{const C=await c(E=>{if(!p(E.channelUrl)){u==null||u(E);return}m=E.reqId,n.messagePendingStuck.start({requestId:E.reqId,channelUrl:E.channelUrl,messageType:Km(E),tracksUploadProgress:d.tracksUploadProgress??!1}),u==null||u(E)},E=>{!g()||m!==E||n.messagePendingStuck.markUploadProgress(E)});return m&&(g()?n.messagePendingStuck.resolve({requestId:m}):n.messagePendingStuck.disappear({requestId:m})),C}catch(C){throw m&&(g()?n.messagePendingStuck.resolve({requestId:m}):n.messagePendingStuck.disappear({requestId:m})),C}},[n])},th=({channelUrl:e,enabled:t=!0,statsTrackers:n})=>{const r=l.useRef(!1),s=l.useRef(e),o=l.useRef(t),i=l.useRef(0);return l.useLayoutEffect(()=>(r.current=!0,s.current=e,o.current=t,i.current+=1,()=>{r.current=!1,i.current+=1}),[e,t]),l.useCallback(async c=>{if(!r.current||!o.current)return c(()=>{});const u=i.current,d=s.current,m=()=>r.current&&o.current&&i.current===u&&s.current===d;let h=qm(d);n.userPerceivedResponseTime.startTurn({requestId:h,channelUrl:d}),n.typingIndicatorAbsentTimeout.startTurn({requestId:h,channelUrl:d});try{const f=await c(g=>{m()&&(n.userPerceivedResponseTime.replaceTurnRequestId(h,g),n.typingIndicatorAbsentTimeout.replaceTurnRequestId(h,g),h=g)});return m()?(n.userPerceivedResponseTime.markUserMessageAck({requestId:h,messageId:f.messageId}),n.typingIndicatorAbsentTimeout.markUserMessageAck({requestId:h,messageId:f.messageId})):(n.userPerceivedResponseTime.cancelTurn(h),n.typingIndicatorAbsentTimeout.cancelTurn(h)),f}catch(f){throw n.userPerceivedResponseTime.cancelTurn(h),n.typingIndicatorAbsentTimeout.cancelTurn(h),f}},[e,n])},nh=({requestedChannelUrl:e,activeChannelUrl:t,statsEnabled:n=!0,statsTrackers:r})=>{const{aiAgentInfo:s}=et();Xm({activeChannelUrl:t,statsTrackers:r}),Zm({enabled:n,requestedChannelUrl:e,statsTrackers:r});const o=Jm({aiAgentUserId:s==null?void 0:s.userId,statsEnabled:n,requestedChannelUrl:e,statsTrackers:r}),i=eh({channelUrl:t,enabled:n,statsTrackers:r}),c=th({channelUrl:t,enabled:n,statsTrackers:r});return l.useMemo(()=>({messageCallbacks:o,runWithPendingStuckStats:i,runWithUserTurnStats:c}),[o,i,c])},mt=()=>Ie()._aiAgentSDK.statsTrackers,rh=({enabled:e=!0,channelUrl:t}={})=>{const{conversationInitialRender:n}=mt(),{watchBackgrounded:r}=Ie()._aiAgentSDK,s=l.useRef(null);return l.useLayoutEffect(()=>{n.setVisible(e)},[e,n]),l.useLayoutEffect(()=>{if(!t)return;const o=n.startSpan(t);return s.current=o,()=>{o.cancel(),s.current===o&&(s.current=null)}},[t,n]),l.useMemo(()=>({onGetChannelStart:o=>{var i;(i=s.current)==null||i.onGetChannelStart(o)},onGetChannelComplete:({channelUrl:o,conversationId:i})=>{var c;(c=s.current)==null||c.onGetChannelComplete(o,i)},onGetChannelError:({channelUrl:o,error:i})=>{var c;(c=s.current)==null||c.onGetChannelError(o,i)},onCollectionInitializeStart:()=>{var o;(o=s.current)==null||o.onGetMessagesStart()},onCollectionCacheResult:(o,i)=>{var c;(c=s.current)==null||c.onGetMessagesCacheComplete(i,o)},onCollectionApiResult:(o,i)=>{const c=s.current;if(!c)return;c.onGetMessagesComplete(i,o);const u=r==null?void 0:r();Re(()=>{u!=null&&u()?c.onRenderDiscarded():c.onRendered()})}}),[r])},sh=({enabled:e=!0,channelUrl:t,conversationId:n,messages:r})=>{const{duplicateMessageResponse:s}=mt(),{aiAgentInfo:o}=et(),i=o==null?void 0:o.userId;l.useEffect(()=>{!e||!t||!i||s.onMessagesChanged({channelUrl:t,conversationId:n,aiAgentUserId:i,messages:r})},[i,t,n,e,r,s])},oh=({enabled:e=!0,channelUrl:t,conversationId:n}={})=>{const{messageLifecycleEvent:r}=mt(),{chatSDK:s,_aiAgentSDK:o}=Ie(),{watchBackgrounded:i}=o,{aiAgentInfo:c}=et(),u=c==null?void 0:c.userId,d=e&&!!t&&!!u;l.useEffect(()=>{r.setBackgroundedWatcher(i)},[r,i]),Ct(d?s:void 0,{onTypingStatusUpdated(g){g.url===t&&r.onTypingChanged({channelUrl:g.url,isAgentTyping:g.getTypingUsers().some(p=>p.userId===u)})}}),l.useEffect(()=>{if(!d||!t||!u)return;const g=Gn.subscribe(p=>{r.onCollectionEvent({event:p,channelUrl:t,aiAgentUserId:u})});return()=>{g(),r.clearChannel(t)}},[u,t,d,r]),l.useEffect(()=>{!d||!t||r.onConversationIdResolved({channelUrl:t,conversationId:n})},[t,n,d,r]);const m=l.useCallback(g=>{!d||!t||!Xe(g)||g.sendingStatus!==we.SendingStatus.SUCCEEDED||r.onUserMessageSent({channelUrl:t,conversationId:n,messageId:g.messageId})},[t,n,d,r]),h=l.useCallback(g=>{d&&r.onAnimationStart({messageId:g})},[d,r]),f=l.useCallback((g,p)=>{d&&r.onAnimationComplete({messageId:g,completed:p})},[d,r]);return{onOutgoingMessageStatusChanged:m,onAnimationStart:h,onAnimationComplete:f}},ih=({enabled:e=!0,channelUrl:t,conversationId:n}={})=>{const{streamingMessageValidation:r}=mt(),{watchBackgrounded:s}=Ie()._aiAgentSDK,{aiAgentInfo:o}=et(),i=o==null?void 0:o.userId,c=l.useRef(n);c.current=n,l.useEffect(()=>{r.setBackgroundedWatcher(s)},[r,s]),l.useEffect(()=>{if(!e||!t||!i)return;const u=Gn.subscribe(d=>{r.onCollectionEvent({event:d,channelUrl:t,conversationId:c.current,aiAgentUserId:i})});return()=>{u(),r.clearChannel(t)}},[i,t,e,r])},on=(e,t)=>{const n=l.useId(),r=l.useRef(t);l.useLayoutEffect(()=>{r.current=t}),l.useLayoutEffect(()=>{const s=new _e.ConnectionHandler({onDisconnected:o=>{var i,c;return(c=(i=r.current).onDisconnected)==null?void 0:c.call(i,o)},onConnected:o=>{var i,c;return(c=(i=r.current).onConnected)==null?void 0:c.call(i,o)},onReconnectStarted:()=>{var o,i;return(i=(o=r.current).onReconnectStarted)==null?void 0:i.call(o)},onReconnectSucceeded:()=>{var o,i;return(i=(o=r.current).onReconnectSucceeded)==null?void 0:i.call(o)},onReconnectFailed:()=>{var o,i;return(i=(o=r.current).onReconnectFailed)==null?void 0:i.call(o)},onConnectionLost:()=>{var o,i;return(i=(o=r.current).onConnectionLost)==null?void 0:i.call(o)},onConnectionDelayed:o=>{var i,c;return(c=(i=r.current).onConnectionDelayed)==null?void 0:c.call(i,o)}});return e.addConnectionHandler(n,s),()=>{e.removeConnectionHandler(n)}},[e,n])},oo=()=>{const e=l.useRef(0);return{next:()=>(e.current+=1,e.current),current:()=>e.current,invalidate:()=>{e.current+=1},isCurrent:t=>t===e.current}};function ah(e,t={}){const{shouldInitializeConversation:n=!0,initialUserMessage:r}=t,{chatSDK:s,logger:o,aiAgentId:i,_aiAgentSDK:c}=Ie(),{sdkUser:u}=et(),d=oo(),m=oo(),[h,f]=l.useState(void 0),g=Hn(),[p,C]=l.useState(void 0),[E,_]=l.useState(!1),A=ce(T=>{if(n&&T.isAIAgent&&!T.conversation){const M=m.next();_(!0),c.initConversationIfNeeded(T,{initialUserMessage:r}).finally(()=>{m.isCurrent(M)&&_(!1)})}});async function y(){var M,O,w,R,x,$;const T=d.next();if(!u){o.debug("useChannel.getChannel: no sdk user, skip fetching channel");return}if(o.debug("useChannel.getChannel: start"),f(void 0),C(void 0),m.invalidate(),_(!1),e){(M=t.onFetchStart)==null||M.call(t,e);try{o.debug("useChannel.getChannel: get channel",e);const N=await s.groupChannel.getChannel(e);if(!d.isCurrent(T))return;A(N),f(N),(w=t.onFetchSuccess)==null||w.call(t,{channelUrl:N.url,conversationId:(O=N.conversation)==null?void 0:O.id}),N.url===((R=c.session)==null?void 0:R.activeChannel.url)&&c.session._updateActiveChannel({url:N.url,status:$e(N)?"closed":"open",conversationStatus:(x=N.conversation)==null?void 0:x.status}),o.debug("useChannel.getChannel: fetched channel",N)}catch(N){if(!d.isCurrent(T))return;($=t.onFetchError)==null||$.call(t,{channelUrl:e,error:N}),N instanceof _e.SendbirdError&&C(N),o.error("useChannel.getChannel: error",N)}}}return l.useEffect(()=>(y(),()=>{d.invalidate()}),[s,u,e,i]),l.useEffect(()=>{n&&h&&A(h)},[n]),on(s,{async onReconnectSucceeded(){var O;if(!h){p&&await y();return}const T=d.current(),M=await h.refresh();!d.isCurrent(T)||h.url!==e||((O=t.onReconnectSucceeded)==null||O.call(t,h.url),A(M),f(M))}}),Ct(s,{onChannelChanged:T=>{T.isGroupChannel()&&T.url===e&&(o.debug("useChannel.onChannelChanged: channel changed",T.url),f(T),g())}}),{channel:h,channelRevision:g.revision,channelFetchError:p,getChannel:y,isInitializingConversation:E}}const ch=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)return;const s=tn(n);switch(r){case"suggested_replies":return s.hasSuggestedReplies?r:void 0;case"steward":return s.hasSteward?r:void 0;case"system":return r;default:return}},lh=e=>{var o;const t=e==null?void 0:e.lastMessage;if(!t||!e)return!1;const n=t.extendedMessagePayload,r=tn(n).hasActiveForm,s=e.isAIAgent&&!!((o=e.conversation)!=null&&o.handedOverAt);return r&&!s},uh=()=>{const{chatSDK:e,networkStateAdapter:t}=Ie(),[n,r]=l.useState(()=>t?t.isOnline()?"connected":"reconnecting":"connected");return on(e,{onConnected:()=>r("connected"),onDisconnected:()=>r("disconnected"),onReconnectStarted:()=>r("reconnecting"),onReconnectSucceeded:()=>r("connected"),onReconnectFailed:()=>r("disconnected"),onConnectionLost:()=>r("reconnecting")}),l.useEffect(()=>{if(t)return t.subscribe(s=>{if(!s){r("reconnecting");return}r(o=>o==="reconnecting"&&e.connectionState===_e.ConnectionState.OPEN?"connected":o)})},[t,e]),n},dh=3e4,mh=({shouldApply:e,lastMessage:t,isBlockedWhileAIResponding:n,currentUserId:r})=>{const[s,o]=l.useState(!1),i=l.useRef(null),c=t&&Fe(t,r)?t.createdAt:0;return l.useEffect(()=>{const u=()=>{i.current&&(clearTimeout(i.current),i.current=null),o(!1)},d=f=>{i.current&&clearTimeout(i.current),o(!0),i.current=setTimeout(()=>{o(!1),i.current=null},f)},m=Date.now()-c,h=dh-m;return n||h<=0?u():d(h),()=>{i.current&&clearTimeout(i.current)}},[n,c]),s&&e},Ki=e=>{const{chatSDK:t}=Ie(),[n,r]=l.useState([]);return Ct(t,{onTypingStatusUpdated(s){if(s.url===(e==null?void 0:e.url)){const o=s.getTypingUsers();r(o)}}}),n},hh=({channel:e,lastMessage:t,aiAgentUserId:n,isStreamAnimating:r})=>{const[s,o]=l.useState(!1),i=Ki(e);return l.useEffect(()=>{if(!t)return;const c=i.some(d=>d.userId===n),u=Fe(t,n)&&(Ae.isStreaming(t)||r);o(u||c)},[i,t,n,r]),s},fh=({channel:e,messages:t,isStreamAnimating:n,isInitializingConversation:r})=>{const{aiAgentInfo:s,userSession:o}=et(),i=uh(),c=hh({channel:e,lastMessage:Ar(t,[we.SendingStatus.SUCCEEDED]),aiAgentUserId:(s==null?void 0:s.userId)??"",isStreamAnimating:n}),u=mh({shouldApply:!!(e!=null&&e.isAIAgent)&&!dt(e),isBlockedWhileAIResponding:c,lastMessage:Ar(t,[we.SendingStatus.PENDING,we.SendingStatus.SUCCEEDED]),currentUserId:(o==null?void 0:o.userId)??""});if(!e||i==="disconnected")return bt.unavailable;if(i==="reconnecting")return bt.reconnecting;if($e(e))return bt.conversation_closed;if(Ul(e))return bt.handoff_pending;if(lh(e))return bt.form_active;const d=ch(e);return d?bt[d]:c||u||r?bt.ai_responding:gh},lt=e=>Object.freeze(e==="ai_responding"?{disabled:!0,disabledBy:e,focusPolicy:"preserve"}:{disabled:!0,disabledBy:e,focusPolicy:"release"}),gh=Object.freeze({disabled:!1,disabledBy:"",focusPolicy:"auto"}),bt=Object.freeze({ai_responding:lt("ai_responding"),unavailable:lt("unavailable"),form_active:lt("form_active"),conversation_closed:lt("conversation_closed"),suggested_replies:lt("suggested_replies"),steward:lt("steward"),system:lt("system"),reconnecting:lt("reconnecting"),handoff_pending:lt("handoff_pending")}),ph=()=>{const[e,t]=l.useState(new Set),[n,r]=l.useState(new Map),s=l.useCallback(h=>{t(f=>{if(f.has(h))return f;const g=new Set(f);return g.add(h),g})},[]),o=l.useCallback(h=>{t(f=>{if(!f.has(h))return f;const g=new Set(f);return g.delete(h),g})},[]),i=l.useCallback((h,f)=>{r(g=>{const p=new Map(g);return p.set(h,f),p})},[]),c=l.useCallback(h=>{r(f=>{if(!f.has(h))return f;const g=new Map(f);return g.delete(h),g})},[]),u=l.useCallback(h=>n.has(h),[n]),d=n.values().next().value,m=e.size>0;return l.useMemo(()=>({isAnimating:m,start:s,stop:o,isHolding:u,heldTypingInfo:d,holdStart:i,holdStop:c}),[m,s,o,u,d,i,c])},{Provider:Eh}=ye("AIAgentConversation");function _h({children:e,channelUrl:t,onChannelDeleted:n,onMessagesReceived:r,onMessagesUpdated:s,onConversationStatusChanged:o,onConversationClosedViaDispatcher:i,onBeforeSendMessage:c,onAfterSendMessage:u=Ee,shouldMarkAsRead:d=!0,conversationStatsEnabled:m=!0,shouldInitializeConversation:h=!0,initialUserMessage:f,shouldCountNewMessages:g=()=>!1,sortComparator:p}){var U,Z,oe,Q,Se;const C=()=>d&&(x==null?void 0:x.markAsRead()),{_aiAgentSDK:E,chatSDK:_,logger:A,dispatcher:y}=Ie(),T=mt(),M={channelUrl:t,enabled:m},O=vm({...M,statsTracker:T.conversationNotInteractiveTimeout}),w=ym({...M,scheduleForegroundTask:E.scheduleForegroundTask,statsTracker:T.recoveryNotInteractiveTimeout}),R=rh(M),{channel:x,channelRevision:$,channelFetchError:N,getChannel:J,isInitializingConversation:se}=ah(t,{shouldInitializeConversation:h,initialUserMessage:f,onFetchStart:K=>{O.onFetchStart(K),R.onGetChannelStart(K)},onFetchSuccess:K=>{O.onFetchSuccess(K),R.onGetChannelComplete(K)},onFetchError:K=>{O.onFetchError(K),R.onGetChannelError(K)},onReconnectSucceeded:w.onReconnectSucceeded}),Y=x==null?void 0:x.url,j=oh({enabled:m&&!!(x!=null&&x.isAIAgent)&&x.hasAiBot,channelUrl:Y,conversationId:(U=x==null?void 0:x.conversation)==null?void 0:U.id}),P=nh({requestedChannelUrl:t,activeChannelUrl:Y,statsEnabled:m,statsTrackers:T}),V=Sm(_,x,{replyType:we.ReplyType.ONLY_REPLY_TO_CHANNEL,shouldCountNewMessages:g,logger:A,markAsRead:C,sortComparator:p,onChannelDeleted:n,onMessagesReceived:K=>r==null?void 0:r(K),onMessagesUpdated:K=>s==null?void 0:s(K),onCollectionInitializeStart:()=>{R.onCollectionInitializeStart()},onApiResult:(K,me,he)=>{R.onCollectionApiResult(K,he),P.messageCallbacks.onApiResult(K,me,he)},onCacheResult:(K,me,he)=>{R.onCollectionCacheResult(K,he),P.messageCallbacks.onCacheResult(K,me,he)},onCollectionEvent:K=>{P.messageCallbacks.onCollectionEvent(K),Gn.publish(K)},onLocalMessageDeleted:K=>{P.messageCallbacks.onLocalMessageDeleted(K)},onOutgoingMessageStatusChanged:K=>{j.onOutgoingMessageStatusChanged(K),x&&E.liveMetricManager.track({type:"outgoingMessage",channel:x,message:K})}}),q=ph(),W=fh({channel:x,messages:V.messages,isStreamAnimating:q.isAnimating,isInitializingConversation:se});ih({enabled:m,channelUrl:Y,conversationId:(Z=x==null?void 0:x.conversation)==null?void 0:Z.id}),sh({enabled:m,channelUrl:Y,conversationId:(oe=x==null?void 0:x.conversation)==null?void 0:oe.id,messages:V.messages}),Qm({enabled:m,channelUrl:Y,initialized:V.initialized,inputReady:Vm(W),renderedSignal:V.messages,statsTrackers:T}),l.useEffect(()=>{C()},[d,x]);const H=(Q=x==null?void 0:x.conversation)==null?void 0:Q.status;l.useEffect(()=>{H&&(o==null||o(H))},[H,o]),l.useEffect(()=>{const K=async me=>{const he=typeof(me==null?void 0:me.channelUrl)=="string";x&&he&&me.channelUrl!==x.url||(A.debug("conversation.dispatcher: try to close conversation",x),x!=null&&x.conversation&&x.conversation.status===Ce.ConversationStatus.OPEN&&(await x.closeConversation(),i==null||i()))};return y.subscribe(Ge.ConversationClose,K),()=>{y.unsubscribe(Ge.ConversationClose,K)}},[y,x,A,(Se=x==null?void 0:x.conversation)==null?void 0:Se.status,i]);const G=ce(()=>V.loadPrevious()),z=ce(()=>V.loadNext()),ee=ce(async K=>{try{await V.deleteMessage(K)}finally{K.sendingStatus!=="succeeded"&&P.messageCallbacks.onLocalMessageDeleted(K)}}),ae=ce(K=>K.isUserMessage()?P.runWithUserTurnStats(me=>P.runWithPendingStuckStats(he=>V.resendMessage(K,ie=>{me(ie.reqId),he(ie)}),void 0)):P.runWithPendingStuckStats((me,he)=>V.resendMessage(K,me,he),void 0,{tracksUploadProgress:K.isMultipleFilesMessage()})),L=ce(()=>V.resetNewMessages()),ve=ce(async K=>{var he;if(((he=x==null?void 0:x.conversation)==null?void 0:he.status)===Ce.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(K=await c(K));const me=await P.runWithUserTurnStats(ie=>P.runWithPendingStuckStats(pe=>V.sendUserMessage(K,de=>{ie(de.reqId),pe(de)}),u));return u==null||u(me),me}),xe=ce(async K=>{var he;if(((he=x==null?void 0:x.conversation)==null?void 0:he.status)===Ce.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(K=await c(K));const me=await P.runWithPendingStuckStats(ie=>V.sendFileMessage(K,ie),u);return u==null||u(me),me}),Oe=ce(async K=>{var he;if(((he=x==null?void 0:x.conversation)==null?void 0:he.status)===Ce.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(K=await c(K));const me=await P.runWithPendingStuckStats((ie,pe)=>V.sendMultipleFilesMessage(K,ie,pe),u,{tracksUploadProgress:!0});return u==null||u(me),me}),I=ce(J),k=ce(async()=>{$e(x)||await(x==null?void 0:x.closeConversation())}),D=l.useMemo(()=>({_statsEnabled:m,_stats:{onMessageLifecycleAnimationStart:j.onAnimationStart,onMessageLifecycleAnimationComplete:j.onAnimationComplete},conversation:(x==null?void 0:x.conversation)??void 0,actions:{setUserMemoryState:E.setUserMemoryState},channelSource:{channel:x,error:N,refetch:I,closeConversation:k},messageSource:{messages:V.messages,newMessages:V.newMessages,initialized:V.initialized,loadPrevious:G,loadNext:z,deleteMessage:ee,resendMessage:ae,resetNewMessages:L,sendUserMessage:ve,sendFileMessage:xe,sendMultipleFilesMessage:Oe},state:{streamAnimation:q,input:W}}),[m,j.onAnimationStart,j.onAnimationComplete,x,$,E,N,I,k,V.messages,V.newMessages,V.initialized,V.collectionRevision,G,z,ee,ae,L,ve,xe,Oe,q,W]);return a.createElement(Eh,{value:D},e)}function Ch(e,t,n){var _,A,y,T,M,O,w,R,x,$;const[r,s]=l.useState(!1),[o,i]=l.useState(null),[c,u]=l.useState([]),[d,m]=l.useState(null),h=l.useRef(!1),f=ce(()=>{var N;return(N=n==null?void 0:n.onListRequestStart)==null?void 0:N.call(n)}),g=ce(N=>{var J;return(J=n==null?void 0:n.onListRequestComplete)==null?void 0:J.call(n,N)}),p=l.useCallback(async N=>{f();try{await N.loadMore(),g()}catch(J){throw g(J),J}},[f,g]),C=l.useCallback(async()=>{if(!h.current&&e.currentUser){h.current=!0,s(!1),i(null),u([]);try{d==null||d.dispose();const N=new Ii(e,t);N.setConversationListCollectionHandler({onChannelsAdded:()=>{u(N.channels)},onChannelsUpdated:()=>{u(N.channels)},onChannelsDeleted:()=>{u(N.channels)}}),await p(N),u(N.channels),m(N),i(null)}catch(N){m(null),i(N)}finally{s(!0),h.current=!1}}},[e,e.currentUser,(_=t.filter)==null?void 0:_.aiAgentChannelFilter,(y=(A=t.filter)==null?void 0:A.aiAgentConversationStatusFilter)==null?void 0:y.join(),(M=(T=t.filter)==null?void 0:T.aiAgentIds)==null?void 0:M.join(),(O=t.filter)==null?void 0:O.deskChannelFilter,(R=(w=t.filter)==null?void 0:w.pinnedChannelUrls)==null?void 0:R.join(),(x=t.filter)==null?void 0:x.copilotConversationOnly,($=t.filter)==null?void 0:$.copilotSupportChannelUrl,t.limit,p]),E=l.useCallback(async()=>{if(d)try{await d.loadMore(),u(d.channels)}catch(N){i(N)}},[d]);return on(e,{onConnected:()=>C()}),l.useEffect(()=>{C()},[C]),l.useEffect(()=>()=>{h.current=!1,d==null||d.dispose()},[d]),{initialized:r,error:o,channels:c,loadMore:E}}const qi=e=>{var s;const{aiAgentId:t,queryParams:n}=Ie(),r=(s=n==null?void 0:n.conversationListParams)==null?void 0:s.filter;return{aiAgentIds:[t],aiAgentConversationStatusFilter:[Ce.ConversationStatus.CLOSED,Ce.ConversationStatus.OPEN],...r,...e}},Sh=({enabled:e=!0}={})=>{const{conversationListInitialRender:t}=mt(),{watchBackgrounded:n}=Ie()._aiAgentSDK,r=l.useRef(null);return l.useLayoutEffect(()=>{t.setVisible(e)},[e,t]),l.useLayoutEffect(()=>{const s=t.startSpan();return r.current=s,()=>{s.cancel(),r.current===s&&(r.current=null)}},[t]),l.useMemo(()=>({onListRequestStart:()=>{var s;(s=r.current)==null||s.onListRequestStart()},onListRequestComplete:s=>{const o=r.current;if(!o||(o.onListRequestComplete(s),s))return;const i=n==null?void 0:n();Re(()=>{i!=null&&i()?o.onRenderDiscarded():o.onRendered()})}}),[n])},{Provider:bh}=ye("AIAgentConversationList");function vh({conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:n=!0,children:r}){var h;const{chatSDK:s,queryParams:o}=Ie(),i=e??((h=o==null?void 0:o.conversationListParams)==null?void 0:h.limit),c=qi(t),u=Sh({enabled:n}),d=Ch(s,{limit:i,filter:c},{onListRequestStart:()=>{u.onListRequestStart()},onListRequestComplete:f=>{u.onListRequestComplete(f)}}),m={listSource:{initialized:d.initialized,error:d.error??void 0,channels:d.channels,loadMore:()=>d.loadMore()}};return a.createElement(bh,{value:m},r)}function yh(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:Ah,useContext:Th}=ye("MessageTemplateFetching");function Ih({children:e,internalVariables:t}){const n=l.useRef({}),r=l.useRef({}),[s,o]=l.useState({}),i=l.useCallback((d,m)=>{o(h=>({...h,[d]:{fetching:!1,error:!1,...h[d],...m}}))},[]),c=l.useCallback(async({onRequestTemplate:d,onGetCachedTemplate:m,templateKey:h,suspense:f=!1})=>{const g=m(h);if(g)return g;const p=r.current[h];if(p)return p;f||i(h,{fetching:!0});const C=d(h).catch(E=>{throw f||i(h,{error:!0}),E}).finally(()=>{f||i(h,{fetching:!1}),delete r.current[h]});return r.current[h]=C,C},[i]),u={internalVariables:t,fetchTemplate:c,suspend:(d,m)=>{if(n.current[d])return n.current[d];const h=yh(m());return n.current[d]=h,h},getIsFetching:d=>{var m;return((m=s[d])==null?void 0:m.fetching)??!1},getHasError:d=>{var m;return((m=s[d])==null?void 0:m.error)??!1}};return a.createElement(Ah,{value:u},e)}const xh="remove_powered_by",ls=(e,t)=>{var s,o;const{chatSDK:n}=Ie(),{aiAgentInfo:r}=et();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&&jr(t)}if(e==="special-notice")return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.specialNoticeEnabled)&&!!(r!=null&&r.specialNotice);if(e==="powered-by"){const i=(o=n==null?void 0:n.appInfo)==null?void 0:o.applicationAttributes;return l.useMemo(()=>!(Array.isArray(i)&&i.includes(xh)),[i])}throw new Error("Unsupported feature")},Mh={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"},Rh={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}}},kh={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}}},wh={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}}},Lh={getValueOrDefault:e=>e.values??e.default_values??null,validate:(e,t,n)=>{const r=t;if(e.required&&(!r||r.length===0))return{isValid:!1,error:n.required};if(!r||r.length===0)return{isValid:!0};if(r.filter(i=>!e.options.includes(i)).length>0)return{isValid:!1,error:n.invalidSelection};const{rules:o}=e;if(o){if(o.min_select!==void 0&&r.length<o.min_select)return{isValid:!1,error:typeof n.minSelect=="function"?n.minSelect(o.min_select):n.minSelect};if(o.max_select!==void 0&&r.length>o.max_select)return{isValid:!1,error:typeof n.maxSelect=="function"?n.maxSelect(o.max_select):n.maxSelect}}return{isValid:!0}}},Oh={text:Rh,number:kh,"single-select":wh,"multi-select":Lh},Nh={getValueOrDefault:()=>null,validate:()=>({isValid:!1})};function Wi(e){return Oh[e.type]||Nh}function io(e){return Wi(e).getValueOrDefault(e)}function Dh(e,t,n={}){const r={...Mh,...n};return Wi(e).validate(e,t,r)}const Ph=(e,t={})=>{const{labels:n={},onSubmit:r,onCancel:s}=t,[o,i]=l.useState({}),[c,u]=l.useState(()=>{const C={};return e.fields.forEach(E=>{C[E.key]=io(E)}),C}),d=l.useMemo(()=>e.submitted_at?"submitted":e.canceled_at?"canceled":"draft",[e.submitted_at,e.canceled_at]);l.useEffect(()=>{if(d==="submitted"||d==="canceled"){const C={};let E=!1;e.fields.forEach(_=>{const A=io(_);JSON.stringify(c[_.key])!==JSON.stringify(A)&&(E=!0),C[_.key]=A}),E&&u(C)}},[d]);const m=(C,E)=>{u(_=>({..._,[C]:E})),i(_=>({..._,[C]:void 0}))},h=e.fields.map(C=>{var A,y,T;const E=c[C.key]??null,_={key:C.key,label:C.label,error:o[C.key],required:C.required};return C.type==="text"?{..._,type:"text",layout:C.layout,value:E,...C.placeholder&&{placeholder:C.placeholder},...((A=C.rules)==null?void 0:A.max_length)&&{maxLength:C.rules.max_length}}:C.type==="number"?{..._,type:"number",layout:C.layout,value:E,...C.placeholder&&{placeholder:C.placeholder},...((y=C.rules)==null?void 0:y.max)&&{max:C.rules.max}}:C.type==="single-select"?{..._,type:"single-select",layout:C.layout,value:E,options:C.options}:C.type==="multi-select"?{..._,type:"multi-select",layout:C.layout,value:E,options:C.options,...((T=C.rules)==null?void 0:T.max_select)&&{maxSelect:C.rules.max_select}}:{..._,type:"unknown",layout:"default",value:null}});return{state:d,fields:h,getField:C=>h.find(E=>E.key===C),updateFieldValue:m,submit:async()=>{const C={};let E=!1;for(const _ of e.fields){const A=c[_.key]??null,y=Dh(_,A,n);y.isValid||(C[_.key]=y.error,E=!0)}if(i(C),!E&&r){const _={};e.fields.forEach(A=>{_[A.key]=c[A.key]??null}),await r(_)}},cancel:async()=>{await(s==null?void 0:s())}}},$h=({isMessengerOpened:e,onConversationStarted:t})=>{const{_aiAgentSDK:n,aiAgentId:r,language:s,countryCode:o,context:i}=Ie(),{createConversation:c,userSession:u}=et(),[d,m]=l.useState(null),h=u==null?void 0:u.userId;l.useEffect(()=>{if(m(null),!(e||!h))return n.onNudgeMessageReceived(C=>m(E=>({seq:((E==null?void 0:E.seq)??0)+1,response:C})))},[n,e,h]);const f=()=>m(null),g=l.useRef(!1),p=async()=>{var E;if(!d||g.current)return;g.current=!0,m(null);const C=n.session;try{const _=await c({aiAgentId:r,language:s,country:o,context:i});if(n.session!==C)return;(E=n.session)==null||E._updateActiveChannel({url:_,status:"open"}),t({channelUrl:_,initialUserMessage:d.response.callbackUserMessage})}finally{g.current=!1}};return{nudgeMessage:e?null:(d==null?void 0:d.response)??null,nudgeMessageKey:(d==null?void 0:d.seq)??0,dismissNudgeMessage:f,startNudgeConversation:p}},Fh=e=>{const{chatSDK:t,handlers:n,logger:r}=Ie(),{aiAgentInfo:s}=et(),o=l.useRef(new Set),i=l.useRef(new Set),c=(m,h)=>{if(!(n!=null&&n.onCustomEvent)||!(s!=null&&s.userId)||!Fe(m,s.userId))return;const f=m.messageId;if(Ae.isStreaming(m)){i.current.add(f);return}h==="updated"&&!i.current.has(f)||(r.debug("useCustomEventForMessageReceive: bot-message-received",m),n.onCustomEvent({type:"bot-message-received",data:{message:m}}),i.current.delete(f))},u=l.useCallback(m=>{if(n!=null&&n.onCustomEvent&&m.isAdminMessage()&&m.customType==="user_action_required"&&!o.current.has(m.messageId)){const h=gi(m.data);Array.isArray(h.history)&&h.history.length===0&&(r.debug("useCustomEventForMessageReceive: user_action_required",h),n.onCustomEvent({type:"user-action-requested",data:h}),o.current.add(m.messageId))}},[n,r]),d=(m,h,f)=>{m.url===e&&(c(h,f),u(h))};return Ct(t,{onMessageReceived:(m,h)=>d(m,h,"received"),onMessageUpdated:(m,h)=>d(m,h,"updated")}),{checkForUserActionRequired:u}},Uh=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},Yi=e=>{const{aiAgentInfo:t}=et(),n=Ki(e);if($e(e))return null;const r=n[0];if(!r)return null;const s=r.userId===(t==null?void 0:t.userId),o=s?Uh(r.metaData):void 0;return{user:s?t:r,isBot:s,thinkingMessage:o}},Bh=250,Hh=(e,t)=>{var i;const[n,r]=l.useState(!1),s=l.useRef(e),o=l.useRef(void 0);return e!==null?(s.current=e,n||(o.current=t==null?void 0:t.messageId,r(!0))):n&&t!==void 0&&t.sender.userId===((i=s.current)==null?void 0:i.user.userId)&&t.messageId!==o.current&&r(!1),l.useEffect(()=>{if(!n||e!==null)return;const c=setTimeout(()=>r(!1),Bh);return()=>clearTimeout(c)},[n,e!==null]),e??(n?s.current:null)},Gh=(e,t,{enabled:n=!0,idleMs:r=1e3}={})=>{const s=l.useRef(null),o=l.useRef(t),i=l.useRef(t),c=l.useRef(!1);o.current=t,l.useEffect(()=>{if(s.current&&(clearTimeout(s.current),s.current=null),!n||!e){(c.current?i.current:o.current)(!1),c.current=!1,i.current=o.current;return}c.current=!0,i.current=o.current,i.current(!0),s.current=setTimeout(()=>{s.current=null,i.current(!1),c.current=!1,i.current=o.current},r)},[n,r,e]),l.useEffect(()=>()=>{s.current&&(clearTimeout(s.current),s.current=null),(c.current?i.current:o.current)(!1),c.current=!1,i.current=o.current},[])},zh=(e=1e4)=>{const t=new Map;let n=e;return{shouldAnnounce:c=>{const u=Date.now(),d=t.get(c);return d!==void 0&&u-d<n?!1:(t.set(c,u),!0)},setInterval:c=>{n=c},reset:()=>{t.clear()}}},Vh=(e,t,n=1e4,r=!0)=>{const s=l.useRef(null),o=l.useRef(null),i=l.useRef(!1);s.current||(s.current=zh(n));const c=(e==null?void 0:e.nickname.trim())||null,u=(e==null?void 0:e.userId)??c;l.useEffect(()=>{var d;(d=s.current)==null||d.setInterval(n)},[n]),l.useEffect(()=>{var h;if(!r){i.current=!1,o.current=u;return}if(!u||!c){i.current=!1,o.current=null;return}const d=!i.current,m=o.current!==u;i.current=!0,o.current=u,!(!d&&!m)&&(h=s.current)!=null&&h.shouldAnnounce(u)&&t(c)},[u,c,r,t])},Kh=({csat:e,csatPayload:t,isRenderableCSAT:n,isExpiredNow:r,announceStatus:s,onSubmittedAnnounced:o})=>{const i=(t==null?void 0:t.csat_submitted_label)??"",c=l.useRef(n&&typeof e=="number"),u=l.useRef(n&&r);l.useEffect(()=>{n&&i&&(typeof e!="number"||c.current||(c.current=!0,s&&(s({event:"csatSubmitted",submittedLabel:i}),o==null||o())))},[s,e,n,o,i]),l.useEffect(()=>{n&&r&&(u.current||(u.current=!0,s==null||s({event:"csatExpired"})))},[s,r,n])},us=({channel:e,userSession:t,aiAgentInfo:n})=>{if(!t||!n||!e)return{fallbackIcon:void 0,url:void 0,title:""};const r=Mi(e,t.userId),s={ai(o){return{fallbackIcon:o,url:n.profileUrl,title:n.nickname}},human(o){return{fallbackIcon:o,url:r==null?void 0:r.profileUrl,title:(r==null?void 0:r.nickname)||n.nickname}},channel(o){return{fallbackIcon:o,url:e==null?void 0:e.coverUrl,title:(e==null?void 0:e.name)??""}}};return e.isAIAgent?dt(e)?s.human("agent"):s.ai("delight"):e.isDesk?s.human("agent"):s.channel("user")},ao=e=>l.useReducer((t,n)=>({...t,...n}),e);var st=(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))(st||{});const qh=new Set(["free_text","single_choice"]),Wh=({csatPayload:e,type:t,initialCsat:n,initialCsatReason:r,initialIsResolved:s})=>{const[o,i]=ao({csatType:t,csat:n,csatReason:r,isResolved:s}),[c,u]=ao({followUpItem:!1}),d=l.useMemo(()=>{var E;const g=o.csat,p=typeof g=="number",C=(E=e.follow_up)==null?void 0:E.find(_=>p?_.scores.includes(g):_.always_visible??!1);if(qh.has(C==null?void 0:C.response_type))return C},[o.csat,e.follow_up]),m=(()=>{var g;if(typeof n=="number")return"submitted";if((t===st.AI_AGENT_CSAT_5||t===st.HELPDESK_CSAT_5)&&typeof o.csat=="number")return"submittable";if(t===st.AI_AGENT_CSAT_5_WITH_CRE){const p=typeof o.csat=="number",C=!((g=e.cre)!=null&&g.required)||typeof o.isResolved=="boolean";if(p&&C)return"submittable"}return"unsubmittable"})(),h=l.useCallback(()=>typeof o.csat>"u"?!1:d!=null&&d.required&&!o.csatReason?(u({followUpItem:!0}),!1):!0,[o,d,u]);return l.useEffect(()=>{r||(i({csatReason:""}),u({followUpItem:!1}))},[r,d,i,u]),{params:o,setParams:i,error:c,setError:u,followUpItem:d,state:m,validateParams:h,itemProps:{csatPayload:e,state:m,submitted:m==="submitted"}}},Yh=({csat:e,csatExpireAt:t,csatPayload:n,isSubmitInFlight:r=!1})=>{const s=!!n&&n.visibility&&!!st[n.type],o=!r&&typeof e!="number"&&Ri(t),i=Hn();return l.useEffect(()=>{if(!s||typeof e=="number"||t==null||o)return;const c=t-Date.now();if(c<=0&&r)return;const u=setTimeout(i,Math.max(0,c));return()=>clearTimeout(u)},[i,e,t,o,s,r]),{isRenderableCSAT:s,isExpiredNow:o}},lr=5,Wt=250,ji=50,jh=1500,ur=e=>Math.max(0,e-ji),An=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():0,Xh=(e,t)=>{const n=e&&t.length<=ji,r=l.useRef(n&&t.length>0?t:null),[s,o]=l.useState(()=>!n),i=r.current!==null&&t!==r.current,c=!n||i;return l.useEffect(()=>{if(s)return;const u=()=>{r.current=null,o(!0)};if(c){u();return}if(r.current===null&&t.length>0&&(r.current=t),r.current===null)return;const d=setTimeout(u,jh);return()=>clearTimeout(d)},[s,c,t]),!s&&!c},Zh=e=>e<1e3?{speed:lr*.5,chunkSize:2}:e<2e3?{speed:lr*.8,chunkSize:2}:{speed:lr*.6,chunkSize:3},Tn=(e,t)=>{let n=0;for(let r=t-1;r>=0&&e[r]==="\\";r--)n++;return n%2===1},co=(e,t,n,r)=>{let s=1,o=t;for(;o<e.length&&s>0;){if(Tn(e,o)){o++;continue}e[o]===n?s++:e[o]===r&&s--,o++}return s>0?-1:o},Xi=(e,{hideImages:t,hideLinks:n})=>{let r="",s=0,o=0;for(;s<e.length;){if(e[s]==="`"&&!Tn(e,s)){let h=1;for(;e[s+h]==="`";)h++;o===0?o=h:h===o&&(o=0),r+=e.slice(s,s+h),s+=h;continue}const i=e[s]==="!"&&e[s+1]==="["&&!Tn(e,s),c=e[s]==="["&&!Tn(e,s);if(o>0||!i&&!c){r+=e[s],s++;continue}if(i?!t:!n){const h=i?"![":"[";r+=h,s+=h.length;continue}const u=s,d=co(e,s+(i?2:1),"[","]");if(d===-1)return r;if(s=d,e[s]!=="("){r+=e.slice(u,s);continue}const m=co(e,s+1,"(",")");if(m===-1)return r;s=m,r+=e.slice(u,s)}return r},Jh=({trackedRef:e,onVisibleTextProgress:t,onRenderedTextProgress:n})=>{const r=l.useRef(t),s=l.useRef(n),o=l.useRef(null),i=l.useRef({lastLength:0,lastReportedAt:0}).current,c=l.useRef({lastLength:0,lastReportedAt:0,lastCheckedAt:0}).current,u=l.useRef(null);l.useLayoutEffect(()=>{r.current=t,s.current=n});const d=l.useCallback(A=>{var y;(y=r.current)==null||y.call(r,A)},[]),m=l.useCallback(A=>{const y=e.initialEnabled&&(e.enabled||A<e.textLength),T=y&&e.deferImages,M=y&&e.deferLinks;return!T&&!M?A:Xi(e.text.slice(0,A),{hideImages:T,hideLinks:M}).length},[e]),h=l.useCallback((A,y,T=!1)=>{r.current&&(A<=c.lastLength||!T&&y-c.lastReportedAt<Wt||(c.lastLength=A,c.lastReportedAt=y,d(A)))},[d,c]),f=l.useCallback((A,y,T=!1)=>{if(!r.current)return;const M=Math.max(c.lastReportedAt,c.lastCheckedAt);!T&&y-M<Wt||(c.lastCheckedAt=y,h(m(A),y,!0))},[m,h,c]),g=l.useCallback((A,y,T=!1)=>{s.current&&(A<=i.lastLength||!T&&y-i.lastReportedAt<Wt||(i.lastLength=A,i.lastReportedAt=y,s.current(A)))},[i]),p=l.useCallback((A,y,T)=>{const M=A>=y,O=T-i.lastReportedAt>=Wt;if(!M&&!O)return;const w=m(A);g(w,T,M)},[m,i,g]),C=l.useCallback(()=>{c.lastLength=0,c.lastReportedAt=0,c.lastCheckedAt=0,i.lastLength=0,i.lastReportedAt=0},[i,c]),E=l.useCallback(A=>{r.current&&(o.current!==null&&A<=o.current||(o.current=A,d(A)))},[d]),_=l.useCallback(({displayedLength:A,streamTextLength:y})=>{const T=u.current;if(u.current={displayedLength:A,streamTextLength:y},!e.initialEnabled||!T||A>T.displayedLength||y<=T.streamTextLength)return;const M=An();h(y,M,!0),g(y,M,!0)},[u,g,h,e]);return{resetProgress:C,reportVisibleTextProgress:f,reportRenderedTextProgress:p,reportNonStreamingVisibleTextProgress:E,reportMarkdownRevealProgress:_}},Qh=e=>{const{text:t,enabled:n=!1,snapOnDisable:r=!1,deferredMarkdownElements:s=[],onAnimationStart:o,onAnimationProgress:i,onAnimationComplete:c,onAnimationHoldChange:u,onVisibleTextProgress:d,onRenderedTextProgress:m}=e,h=Xh(n,t),f=s.includes("image"),g=s.includes("link"),[p,C]=l.useState(()=>n?h?0:ur(t.length):t.length),E=l.useRef(null),_=l.useRef({startTime:0,lastUpdate:0,lastProgressCall:0}).current,A=l.useRef({startCalled:!1,completeCalled:!1}).current,y=l.useRef({initialEnabled:n,textLength:t.length,enabled:n,text:t,deferImages:f,deferLinks:g,snapOnDisable:r,isGatingStreamingStart:h}).current,T=ce(()=>o==null?void 0:o()),M=ce(()=>i==null?void 0:i()),O=ce(q=>c==null?void 0:c(q)),w=ce(q=>u==null?void 0:u(q)),{resetProgress:R,reportVisibleTextProgress:x,reportRenderedTextProgress:$,reportNonStreamingVisibleTextProgress:N,reportMarkdownRevealProgress:J}=Jh({trackedRef:y,onVisibleTextProgress:d,onRenderedTextProgress:m}),se=n,Y=p<t.length,j=y.initialEnabled&&(se||Y);l.useLayoutEffect(()=>{y.textLength=t.length,y.enabled=n,y.text=t,y.deferImages=f,y.deferLinks=g,y.snapOnDisable=r,y.isGatingStreamingStart=h}),l.useLayoutEffect(()=>{if(y.initialEnabled){if(A.startCalled||(A.startCalled=!0,T()),!y.enabled&&y.snapOnDisable){C(t.length);const q=An();x(t.length,q,!0),$(t.length,t.length,q);return}C(q=>t.length<q?t.length:q)}},[T,$,x,t]),l.useEffect(()=>{if(!y.initialEnabled)return;let q=h?0:ur(t.length),W=h;_.lastUpdate=0,_.startTime=0,_.lastProgressCall=0,R();const H=G=>{_.lastUpdate===0&&(_.lastUpdate=G,_.startTime=G,_.lastProgressCall=G,q>0&&x(q,G,!0));const z=y.textLength;W&&!y.isGatingStreamingStart&&(q=ur(z),C(q),q>0&&x(q,G,!0),_.lastUpdate=G,W=!1),!y.enabled&&y.snapOnDisable&&q<z&&(q=z,C(q),x(q,G,!0),$(q,z,G));const ee=G-_.lastUpdate,ae=G-_.startTime,{speed:L,chunkSize:ve}=Zh(ae),xe=L*ve;!y.isGatingStreamingStart&&ee>=xe&&q<z&&(q=Math.min(q+ve,z),C(q),x(q,G,q>=z),$(q,z,G),_.lastUpdate=G),G-_.lastProgressCall>=Wt&&(_.lastProgressCall=G,M()),(q<z||y.enabled)&&(E.current=requestAnimationFrame(H))};return E.current=requestAnimationFrame(H),()=>{E.current&&cancelAnimationFrame(E.current),A.startCalled&&!A.completeCalled&&(A.completeCalled=!0,O({completed:!1}))}},[O,M,$,x,R]),l.useEffect(()=>{y.initialEnabled&&(n||t.length>0)||(N(t.length),$(t.length,t.length,An()))},[n,m,d,N,$,t.length,y]),l.useEffect(()=>{const q=y.initialEnabled&&A.startCalled,W=!n,H=p>=t.length;q&&W&&H&&!A.completeCalled&&(A.completeCalled=!0,O({completed:!0}))},[n,p,O,t.length]);const P=l.useMemo(()=>{let q=t;y.initialEnabled&&(q=h?"":t.slice(0,p));const W=j&&f,H=j&&g;return!W&&!H?q:Xi(q,{hideImages:W,hideLinks:H})},[t,p,f,g,j,h]);l.useEffect(()=>{!y.initialEnabled||j||x(p,An(),!0)},[p,j,x]),l.useEffect(()=>{J({displayedLength:p,streamTextLength:P.length})},[p,J,P.length]);const V=P.length===0&&j;return l.useLayoutEffect(()=>(w(V),()=>w(!1)),[w,V]),{streamText:P,isAnimating:j,isHolding:V}},lo={visible:!1,remainingTime:0,showDescription:!1,targetTimeMs:null},ef=e=>({visible:!0,remainingTime:e,showDescription:!0,targetTimeMs:Date.now()+e*1e3}),tf=(e,t=Date.now())=>{if(!e.visible||e.targetTimeMs==null)return e;const n=Math.max(Math.ceil((e.targetTimeMs-t)/1e3),0);return n<=0?{...e,remainingTime:0,showDescription:!1,targetTimeMs:null}:e.remainingTime===n&&e.showDescription?e:{...e,remainingTime:n,showDescription:!0}},nf=()=>{const{chatSDK:e}=Ie(),[t,n]=l.useState(lo),r=()=>n(lo);return on(e,{onConnectionDelayed:s=>{s>0?n(ef(s)):r()},onReconnectSucceeded:r,onConnected:r}),l.useEffect(()=>{if(!t.visible||!t.showDescription||t.targetTimeMs==null)return;const s=setTimeout(()=>{n(o=>tf(o))},1e3);return()=>clearTimeout(s)},[t.visible,t.showDescription,t.targetTimeMs,t.remainingTime]),{visible:t.visible,remainingTime:t.remainingTime,showDescription:t.showDescription}},rf=e=>{const t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`},sf=(e,t)=>{if(!t)return{beforeText:e,highlightedText:"",afterText:""};const n=e.indexOf(t);return n<0?{beforeText:e,highlightedText:"",afterText:""}:{beforeText:e.slice(0,n),highlightedText:t,afterText:e.slice(n+t.length)}},of=({enabled:e=!0}={})=>{const t=mt();return l.useCallback(({message:n,isBotMessage:r,aiAgentUserId:s})=>{if(!e)return;const o=n.messageId,i=Ae.isStreaming(n),c=tn(n.extendedMessagePayload),u=c.hasMessageTemplate,d=c.hasForm,m=r&&n.isUserMessage()&&!i&&!sl(n)&&!Ae.isWelcomeMessage(n,s),h=i||t.streamStalled.hasPendingStream(o),f=t.userPerceivedResponseTime.hasPendingAIResponse(o);if(!h&&!f&&!m&&!u&&!d)return;let g=!1,p=!1;const C={};return(f||m)&&(C.onVisibleTextProgress=()=>{f&&!g&&(g=t.userPerceivedResponseTime.markAIResponseVisible(o)),m&&!p&&(p=!0,t.renderedContentUnusable.commit({messageId:o,contentKind:"text",errorDomain:"empty_render"}))}),h&&(C.onRenderedTextProgress=E=>{t.streamStalled.markRenderedProgress({messageId:o,displayedLength:E})}),u&&(C.onMessageTemplateError=E=>{t.renderedContentUnusable.commit({messageId:o,contentKind:"template",errorDomain:"template_error",error:E})}),d&&(C.onFormRenderError=E=>{t.renderedContentUnusable.commit({messageId:o,contentKind:"form",errorDomain:"form_error",error:E})}),C},[e,t])},af=e=>{const t=l.useRef(!1);l.useEffect(()=>{t.current||e!=null&&e.onVisibleTextProgress&&(t.current=!0,e.onVisibleTextProgress(0))},[e])},dr=5e3,cf=({channelUrl:e,enabled:t=!0,isInitiallyBackgrounded:n,isForegrounded:r,subscribeToForegroundState:s})=>{const o=mt(),i=l.useRef(t),c=l.useRef(n),u=l.useRef(t&&n()?performance.now()-dr:null),d=l.useRef(!1);i.current=t,c.current=n;const m=l.useCallback((h=r())=>{if(!i.current){d.current=!1;return}if(!h){d.current=!1;return}if(u.current===null){d.current=!1;return}if(performance.now()-u.current<dr){u.current=null,d.current=!1;return}if(!e){d.current=!0;return}u.current=null,d.current=!1,o.recoveryNotInteractiveTimeout.start("foreground_resume",e)},[e,r,o]);l.useEffect(()=>{t||(u.current=null,d.current=!1,e&&o.recoveryNotInteractiveTimeout.cancelPending(e))},[e,t,o]),l.useEffect(()=>{if(!t)return;d.current&&!!e&&r()&&m()},[e,t,r,m]),l.useEffect(()=>{if(t)return c.current()?u.current??(u.current=performance.now()-dr):u.current=null,s(h=>{if(h==="backgrounded"){u.current??(u.current=performance.now()),d.current=!1,e&&o.recoveryNotInteractiveTimeout.cancelPending(e);return}m(!0)})},[e,t,m,o,s])},lf=e=>{const{conversationInitialRender:t,conversationListInitialRender:n}=mt();l.useLayoutEffect(()=>{t.setPresentMethod(e),n.setPresentMethod(e)},[t,n,e])},uf=(e,{enabled:t=!0,opened:n=!1,filter:r}={})=>{var u,d,m;const[s,o]=l.useState(!1),i=l.useRef(0),c=()=>{if(!t)return;const h=++i.current;e.aiAgent.getUnreadMessageCount(r).then(f=>{h===i.current&&o(f.total>0)}).catch(()=>{})};return l.useEffect(()=>{if(!t){o(!1),i.current++;return}e.connectionState===_e.ConnectionState.OPEN&&c()},[t,e,r==null?void 0:r.aiAgentChannelFilter,(u=r==null?void 0:r.aiAgentConversationStatusFilter)==null?void 0:u.join(),(d=r==null?void 0:r.aiAgentIds)==null?void 0:d.join(),r==null?void 0:r.deskChannelFilter,(m=r==null?void 0:r.pinnedChannelUrls)==null?void 0:m.join(),r==null?void 0:r.copilotConversationOnly,r==null?void 0:r.copilotSupportChannelUrl]),l.useEffect(()=>{n&&(o(!1),i.current++)},[n]),on(e,{onConnected:c,onReconnectSucceeded:c}),s},Pt=e=>e.replace(/\s+/g," ").trim(),df="Code block",Zi=e=>`A11Y_INLINE_CODE_${e}`,Ji=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}},Qi=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}},mf=e=>{const{blockquotePrefix:t,content:n}=Ji(e),{content:r}=Qi(n),s=r.match(/^[ \t]{0,3}([`~]{3,})(.*)$/);if(!s)return;const o=s[1],i=s[2],c=o[0];if(!(c!=="`"&&c!=="~"||!o.split("").every(u=>u===c))&&!(c==="`"&&i.includes("`")))return{char:c,blockquotePrefix:t,length:o.length}},hf=(e,t)=>{const{blockquotePrefix:n,content:r}=Ji(e);if(n!==t.blockquotePrefix)return!1;const{content:s,hasListPrefix:o}=Qi(r);if(o)return!1;const i=s.match(/^[ \t]{0,3}([`~]{3,})[ \t]*$/);if(!i)return!1;const c=i[1];return c[0]===t.char&&c.length>=t.length&&c.split("").every(u=>u===t.char)},ff=(e,t,n)=>{let r=n;for(;r<e.length;){const s=e[r];if(s==="\\"&&r+1<e.length){r+=2;continue}if(s===t)return r;r+=1}return-1},gf=(e,t)=>{let n=1,r=t;for(;r<e.length;){const s=e[r];if(s==="\\"&&r+1<e.length){r+=2;continue}if(s==="["){n+=1,r+=1;continue}if(s==="]"&&(n-=1,n===0))return r;r+=1}return-1},pf=(e,t)=>{let n=t,r=1,s,o=!1,i=!1;for(;n<e.length&&r>0;){const c=e[n];if(c==="\\"&&n+1<e.length){n+=2;continue}if(s){c===s&&(s=void 0),n+=1;continue}if(r===1&&o&&/\s/.test(c)){i=!0,n+=1;continue}if(r===1&&i&&(c==='"'||c==="'")){s=c,n+=1;continue}if(c==="("){r+=1,o=!0,n+=1;continue}if(c===")"){r-=1,n+=1;continue}/\s/.test(c)||(o=!0),n+=1}return r===0?n:-1},Ef=e=>{let t=0,n="";for(;t<e.length;){const r=ff(e,"[",t);if(r===-1){n+=e.slice(t);break}const s=gf(e,r+1);if(s===-1){n+=e.slice(t);break}if(r>0&&e[r-1]==="!"&&On(e,r-1)){n+=e.slice(t,s+1),t=s+1;continue}if(e[s+1]!=="("){n+=e.slice(t,s+1),t=s+1;continue}const o=r>0&&e[r-1]==="!"&&!On(e,r-1)?r-1:r;n+=e.slice(t,o);const i=e.slice(r+1,s),c=pf(e,s+2);if(c===-1){n+=e.slice(o);break}n+=i,t=c}return n},ea=(e,t,n)=>{if(!/^\d+$/.test(t))return!1;const r=e.slice(-1);return/\d/.test(r)&&/\d/.test(n)},_f=e=>e.replace(/(^|[^*\\])\*\*([^\s*](?:[\s\S]*?[^\s*])?)\*\*(?!\*)/g,(t,n,r,s,o)=>{const i=o[s+t.length]??"";return ea(n,r,i)?t:`${n}${r}`}),Cf=e=>e.replace(/(^|[^_\\])__([^\s_](?:[\s\S]*?[^\s_])?)__(?!_)/g,"$1$2"),Sf=e=>e.replace(/(^|[^~\\])~~([^\s~](?:[\s\S]*?[^\s~])?)~~(?!~)/g,"$1$2"),bf=e=>{let t=e;return t=t.replace(/(^|[^*\\])\*([^\s*](?:[\s\S]*?[^\s*])?)\*(?!\*)/g,(n,r,s,o,i)=>{const c=i[o+n.length]??"";return ea(r,s,c)?n:`${r}${s}`}),t=t.replace(/(^|[\s([{"'])_([^_\s](?:[\s\S]*?[^_\s])?)_(?=$|[\s)\]}"'.,!?:;])/g,"$1$2"),t},vf=e=>e.replace(/\\([\\`*_[\]()#+.!~|-])/g,"$1"),yf=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},uo=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))},mo=e=>{const t=[];let n="",r=!1;for(const o of e.trim()){if(r){n+=o==="|"?"|":`\\${o}`,r=!1;continue}if(o==="\\"){r=!0;continue}if(o==="|"){const i=n.trim();i&&t.push(i),n="";continue}n+=o}r&&(n+="\\");const s=n.trim();return s&&t.push(s),t},Af=e=>{const t=e.split(`
|
|
12
|
+
`),n=[];let r=0;for(;r<t.length;){const s=t[r],o=t[r+1],i=mo(s);if(i.length>0&&o&&uo(o)){for(n.push(i.join(" ")),r+=2;r<t.length;){const c=t[r],u=mo(c);if(u.length===0||uo(c))break;n.push(u.join(" ")),r+=1}continue}n.push(s),r+=1}return n.join(`
|
|
13
|
+
`)},Tf=e=>e.replace(/^\s{0,3}(?:(?:-\s*){3,}|(?:\*\s*){3,}|(?:_\s*){3,})$/gm,""),If=(e,t)=>{const n=e.split(`
|
|
14
|
+
`),r=[];let s=0;for(;s<n.length;){const o=n[s],i=mf(o);if(!i){r.push(o),s+=1;continue}let c=-1;for(let u=s+1;u<n.length;u++)if(hf(n[u],i)){c=u;break}if(c===-1){r.push(o),s+=1;continue}r.push(` ${t} `),s=c+1}return r.join(`
|
|
15
|
+
`)},On=(e,t)=>{let n=0,r=t-1;for(;r>=0&&e[r]==="\\";)n+=1,r-=1;return n%2===1},xf=e=>{const t=[];let n=0,r="";for(;n<e.length;){const s=e[n];if(s!=="`"||On(e,n)){r+=s,n+=1;continue}let o=n;for(;o<e.length&&e[o]==="`";)o+=1;const i=e.slice(n,o);let c=o,u=!1;for(;c<e.length&&e[c]!==`
|
|
16
|
+
`;){if(e[c]==="`"&&!On(e,c)&&e.startsWith(i,c)){const d=e.slice(o,c),m=t.push(d)-1;r+=Zi(m),n=c+i.length,u=!0;break}c+=1}u||(r+=i,n=o)}return{text:r,inlineCodes:t}},ta=(e,{codeBlockPlaceholder:t=df}={})=>{const n=e==null?void 0:e.replace(/\r\n?/g,`
|
|
17
|
+
`);if(!n)return;const r=[];let s=n;s=If(s,t),s=yf(s);const o=xf(s);s=o.text,r.push(...o.inlineCodes),s=Ef(s),s=_f(s),s=Cf(s),s=Sf(s),s=bf(s),s=Af(s),s=Tf(s),s=vf(s);for(let c=0;c<r.length;c++)s=s.replaceAll(Zi(c),r[c]);return Pt(s)||void 0},Mf=(e,t)=>{var s;const n=((s=e.name)==null?void 0:s.trim())||"",r=e.mimeType??"";return Ve(r)?t.image:nn(r)?t.video:bi({name:n,mimeType:r})?t.pdf(n):t.document(n)},Nn=e=>(e==null?void 0:e.trim())||"",Rf=e=>(e?Pt(e):void 0)||void 0,ho=30,kf=e=>e.length>ho?`${e.slice(0,ho)}…`:e,wf=({agent:e,status:t,lastMessage:n,time:r,unreadCount:s},o)=>{const i=kf(Pt(n)),c=[t,i].filter(Boolean).join(", ");return o(Pt(e),Pt(c),r,s)},wr=e=>({text:Nn(e),format:"plain"}),Lf=e=>({text:Nn(e),format:"markdown"}),Of=({markdownText:e,plainText:t,comparisonText:n})=>{const r=Nn(e);return r&&r!==Nn(n)?Lf(r):wr(t)},Zt=({sender:e,message:t,messageFormat:n="plain",time:r,codeBlockPlaceholder:s})=>{const o=[],i=n==="markdown"?ta(t,{codeBlockPlaceholder:s}):Rf(t);if(r&&o.push(r),e&&o.push(e),i&&o.push(i),o.length!==0)return o.join(", ")},na=(e,t)=>ta(e==null?void 0:e.trim(),t!==void 0?{codeBlockPlaceholder:t}:void 0),Nf=(...e)=>Pt(e.filter(Boolean).join(", "))||void 0,fo=(e,t,n,r)=>{if(!t||vi(t,n))return e;const s=na(t,r);return s?Nf(e,s):e},ra=(e,t)=>{var r,s;const n=(r=e.message)==null?void 0:r.trim();if(e.isFileMessage()){const o=((s=e.name)==null?void 0:s.trim())||"",i=Mf({name:o,mimeType:e.type},t);return fo(i,n,[o],t.codeBlockPlaceholder)}if(e.isMultipleFilesMessage()){const o=e.fileInfoList??[],i=o.length;if(i===0)return;const c=o.map(m=>{var h;return((h=m.fileName)==null?void 0:h.trim())||""}),d=o.every(m=>{var h;return(h=m.mimeType)==null?void 0:h.startsWith("image")})?t.receivedFilesImageCount(i):t.multipleFilesCount(i);return fo(d,n,c,t.codeBlockPlaceholder)}return na(n,t.codeBlockPlaceholder)},Df=(e,t={})=>{const{throttleMs:n=1e3,isSuppressed:r,maxOrderedQueueSize:s=10}=t,o=Math.max(1,s);let i=null;const c=[];let u=null,d=null,m=null,h=!1,f=0;const g=(R,x,$)=>({text:R,ignoreSuppression:x,queueOrder:f++,dedupeKey:$}),p=()=>{const R=c[0]??null,x=i;return R&&x?x.queueOrder<R.queueOrder?(i=null,x):c.shift()??null:R?c.shift()??null:x!==null?(i=null,x):null},C=()=>{for(;;){const R=p();if(!R)return null;if(!(!R.ignoreSuppression&&(r!=null&&r())))return R}},E=R=>{u=R.text,d=R.dedupeKey??null,h=!0,e(R.text),m=setTimeout(()=>{m=null,h=!1;const x=C();x&&E(x)},n)},_=R=>{u=R.text,d=R.dedupeKey??null,e(R.text)},A=(R,x,$,N)=>x!=null&&N!=null?x===N:x==null&&N==null?R!=null&&R===$:!1,y=(R,x,$)=>{if(!R||!x&&(r!=null&&r()))return;const N=$==null?void 0:$.dedupeKey;if(!(h&&A(R,N,u,d)))if(h){if((($==null?void 0:$.mode)??"latestOnly")==="ordered"){const se=c[c.length-1];if(se&&A(R,N,se.text,se.dedupeKey))return;c.push(g(R,x,N)),c.length>o&&c.shift();return}i=g(R,x,N)}else i=null,E(g(R,x,N))};return{announce:(R,x)=>{y(R,!1,x)},announceIgnoringSuppression:(R,x)=>{y(R,!0,x)},flush:()=>{const R=[];let x=p();for(;x!==null;)R.push(x),x=p();if(m!==null&&(clearTimeout(m),m=null),h=!1,R.length!==0)for(const $ of R)_($)},destroy:()=>{m!==null&&(clearTimeout(m),m=null),i=null,c.length=0,u=null,d=null,h=!1}}},Pf=e=>{switch(e){case"newMessage":case"conversationClosed":case"csatDisplayed":case"csatSubmitted":case"csatExpired":return"ordered";default:return"latestOnly"}},$f=(e,t)=>e.screen==="conversationList"?typeof e.conversationCount=="number"?t.screenConversationListWithCount(e.conversationCount):t.screenConversationListNoCount:[e.agentName?t.screenConversationWithAgent(e.agentName):t.screenConversation,e.isClosed?t.conversationClosed:null,e.isClosed&&e.hasCSAT?t.csatDisplayed:null,e.isEmpty?t.emptyState:null].filter(r=>!!r).join(". "),Ff=(e,t)=>{switch(e.event){case"newMessage":return e.body!==void 0||e.time!==void 0?[t.newMessage(1),e.time,e.senderName,e.body].filter(r=>!!r).join(", "):e.senderName?t.newMessageFromSender(e.senderName,1):t.newMessage(1);case"typing":return t.typing(e.agentName??"");case"sendFailed":return t.sendFailed;case"agentConnected":return t.agentConnected(e.agentName??"");case"conversationClosed":return t.conversationClosed;case"csatDisplayed":return t.csatDisplayed;case"csatSubmitted":return e.submittedLabel;case"csatExpired":return t.csatExpired;case"emptyState":return t.emptyState;case"inputDisabled":return t.inputDisabled}},Uf=(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}},Bf=(e,t)=>!t||!Xe(e)||e.sender.userId!==t?null:e.reqId||(e.messageId>0?String(e.messageId):null),Hf=(e,t)=>Le.isAdmin(e)?Le.isCSAT(e):"sender"in e?e.sender.userId!==t:!1,Gf=e=>"messageId"in e&&e.messageId>0?String(e.messageId):"reqId"in e&&typeof e.reqId=="string"&&e.reqId.length>0?e.reqId:null,zf=e=>e===_e.CollectionEventSource.EVENT_MESSAGE_RECEIVED||e===_e.CollectionEventSource.EVENT_MESSAGE_UPDATED,Vf=({isOpened:e,opensConversationList:t})=>e?t?"closeConversationList":"closeConversation":t?"openConversationList":"openConversation",Kf=(e,t)=>{switch(e){case"closeConversationList":return t.closeConversationList;case"closeConversation":return t.closeConversation;case"openConversationList":return t.openConversationList;case"openConversation":return t.openConversation}},qf=(e,t)=>{switch(e){case"closeConversation":return t.hintCloseConversation;case"openConversationList":return t.hintOpenConversationList;case"openConversation":return t.hintOpenConversation;default:return}},Wf=({intent:e,strings:t})=>({label:Kf(e,t),hint:qf(e,t)}),Yf="1.41.0",ze="sb-agent",Te={ENTRY:`${ze}-entry`,MODAL_ROOT:`${ze}-modal-root`,WINDOW:`${ze}-window`,LAUNCHER:`${ze}-launcher`,WINDOW_TITLE:`${ze}-window-title`},sa="data-sb-initial-focus",oa="true",jf=`[${sa}="${oa}"]`,ia={[sa]:oa},ds="data-sb-focus-trap-sentinel",Xf="true",aa="data-sb-initial-focus-header",ca="true",Zf=`[${aa}="${ca}"]`,la={[aa]:ca},ua="data-sb-message-input",da="true",Jf=`textarea[${ua}="${da}"]:not(:disabled)`,Qf={[ua]:da},ma=1e3,_n=2147483647,Tt={MODAL:_n-1,TOOLTIP:_n-2,WINDOW:_n-3,LAUNCHER:_n-4},ha=36,eg=100,tg=Yf,fa="noopener noreferrer nofollow",ng=()=>typeof document>"u"||document.visibilityState==="visible",Lr=()=>typeof document<"u"&&document.visibilityState==="hidden",go=()=>Lr()?"backgrounded":"foregrounded",rg={getState:go,subscribe:e=>{if(typeof document>"u")return()=>{};const t=()=>e(go());return document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t)}};function sg(){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 Cn={};function og(){return{get:e=>{try{return localStorage.getItem(e)}catch{return Cn[e]??null}},set:(e,t)=>{try{localStorage.setItem(e,t)}catch{Cn[e]=t}},delete:e=>{try{localStorage.removeItem(e)}catch{delete Cn[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(Cn).filter(t=>t.startsWith(e))}}}}const ig={conversation:{input_placeholder:"Ask a question",input_placeholder_disabled:"Chat is unavailable in this channel",input_placeholder_steward:"Processing your request...",input_placeholder_wait_ai_agent_response:"Waiting for the agent's reply...",input_placeholder_active_form:"Please fill out the form to move forward.",input_placeholder_reconnecting:"Trying to reconnect. Refresh if persists.",unknown_message_type:"(Unknown message type)",powered_by:"Powered by",citation_title:"Source",start_new_conversation_label:"Start a conversation",scroll_to_new_messages_label:()=>"New message",failed_message_resend:"Retry",failed_message_remove:"Remove",file_upload_no_supported_files:"No supported file types available.",file_upload_replace_alert_title:"Replace attachment?",file_upload_replace_alert_description:"Uploading a different file type will replace the current one.",a11y_message_list:"Chat messages",a11y_scroll_to_bottom:"Scroll to bottom",a11y_scroll_to_new_messages:"Scroll to new messages",a11y_open_conversation_list:"Open conversation list",a11y_open_conversation:"Open conversation with Support",a11y_open_conversations:"Open conversations",a11y_close_conversation:"Close conversation",a11y_close_conversations:"Close conversations",a11y_menu:"Menu",a11y_message_input:"Message",a11y_send_message:"Send message",a11y_attach_file:"Attach file",a11y_close_messenger:"Close messenger",a11y_dismiss_nudge_message:"Dismiss message",a11y_expand_messenger:"Expand messenger",a11y_collapse_messenger:"Collapse messenger",a11y_connect_agent:"Talk to human agent",a11y_message_sender_you:"You",a11y_suggested_reply:"Suggested reply",a11y_typing_indicator:"Typing",a11y_code_block_placeholder:"Code block",a11y_typing_format:e=>`${e} is typing`,a11y_message_failed:"Message send failed",a11y_new_messages_received:e=>`${e} new ${e===1?"message":"messages"} received`,a11y_new_messages_received_from_sender:(e,t)=>`${e}: ${t} new ${t===1?"message":"messages"} received`,a11y_agent_connected:e=>"Connected to human agent",a11y_conversation_closed:"Conversation has ended",a11y_file_image:e=>`Image file: ${e}`,a11y_file_video:e=>`Video file: ${e}`,a11y_file_pdf:e=>`PDF file: ${e}`,a11y_file_document:e=>`Document file: ${e}`,a11y_received_file_image:"Image file",a11y_received_file_video:"Video file",a11y_received_file_pdf:e=>`PDF file: ${e}`,a11y_received_files_image_count:e=>`${e} ${e===1?"image":"images"}`,a11y_screen_conversation:"Conversation",a11y_screen_conversation_with_agent:e=>`Conversation with ${e}`,a11y_screen_conversation_list_no_count:"Conversation list",a11y_screen_conversation_list_with_count:e=>`Conversations, ${e} total`,a11y_csat_displayed:"Satisfaction survey displayed",a11y_empty_conversation:"No messages in this conversation",a11y_input_disabled:"Message input is disabled",a11y_file_size_exceeded:e=>`File exceeds size limit of ${e}MB`,a11y_csat_form_error:"Please complete the required fields",a11y_hint_send_message:"Sends the message",a11y_hint_open_conversation:"Opens the conversation",a11y_hint_open_conversations:"Opens conversations",a11y_hint_close_conversation:"Closes the conversation",a11y_hint_close_messenger:"Closes the messenger",a11y_hint_open_menu:"Opens the menu",a11y_hint_connect_to_agent:"Escalates to a human agent",a11y_hint_attach_file:"Opens file attachment options",a11y_hint_view_new_messages:"Scrolls to new messages",a11y_hint_open_file:"Opens the file",a11y_hint_open_image:"Opens the image",a11y_hint_send_reply:"Sends this reply",image_viewer_default_title:"Image",a11y_image_viewer_close:"Close image viewer",a11y_image_viewer_previous:"Previous image",a11y_image_viewer_next:"Next image",a11y_image_viewer_download:"Download image",attachment_document:"Files"},conversation_list:{header_title:"Conversations",ended:"Ended",system_message:"System message",footer_title:"Start a conversation",multiple_files_count:e=>`${e} ${e===1?"file":"files"}`,a11y_conversation_item:(e,t,n,r)=>`${e}, ${t}, ${n}${r>0?`, ${r} unread ${r===1?"message":"messages"}`:""}`},date_format:{just_now:"Just now",minutes_ago:e=>`${e} minutes ago`,hours_ago:e=>`${e} hours ago`,date_short:"MM/dd/yyyy",date_separator:"MMMM dd, yyyy",message_timestamp:"p"},csat:{title:"Your feedback matters to us",submitted_label:"Successfully submitted!",cre_question:"Was your issue resolved?",cre_positive_label:"Yes, thank you! 👍",cre_negative_label:"No, that didn't help.",reason_placeholder:"Share your feedback",question:"How would you rate your experience?",submit_label:"Submit",submission_expired:"We're sorry, the survey period has ended.",a11y_csat_rating_label:(e,t)=>`${e} out of 5 — ${t}`,a11y_hint_select_rating:"Selects this rating"},form:{optional_label:"optional",validation_required:"This question is required"},common:{placeholder_something_went_wrong:"Something went wrong",placeholder_no_messages:"No messages",placeholder_no_conversations:"No conversations yet",placeholder_something_went_wrong_retry_label:"Retry",button_ok:"OK",button_cancel:"Cancel"},feedback:{title:"Submit feedback",good:"Good",bad:"Bad",comment_label:"Comment (optional)",comment_placeholder:"Leave a comment",cancel:"Cancel",submit:"Submit",save:"Save",edit:"Edit feedback",remove:"Remove feedback"},handoff:{confirm_title:"Request handoff?",confirm_description:"You'll be transferred to a human agent. Your conversation history will be shared.",confirm_cancel:"Cancel",confirm_handoff:"Handoff"},memory:{dialog_title:"Memory",desc_on:"Memory is **turned on**. It remembers your conversation history to provide personalized responses tailored to your previous questions and preferences.",desc_off:"Memory is **turned off**. If turned on, it will remember your conversation history to provide personalized responses tailored to your previous questions and preferences.",button_use:"Use",button_dont_use:"Don't use",button_keep_using:"Keep using",button_disable:"Disable",button_disable_and_delete:"Disable & Delete memory",button_keep_off:"Keep off",button_enable:"Enable memory",button_cancel:"Cancel",error_message:"Failed to update memory state. Please try again.",a11y_indicator_manage:"Manage memory",a11y_indicator_on:"Memory is on",a11y_indicator_off:"Memory is off"},connection_delay:{title:"Something went wrong. You'll be reconnected shortly.",description:e=>`Estimated waiting time: ${e}`},desk:{ticket_closure_confirm:"Yes, it's resolved",ticket_closure_decline:"No, I still need help",ticket_closure_error_message:"Failed to update the resolution status. Please try again."}},Or={language:"en",strings:ig,dateLocale:Gc.enUS},ga=e=>({MESSAGE_INPUT__PLACE_HOLDER:e.conversation.input_placeholder,MESSAGE_INPUT__PLACE_HOLDER__DISABLED:e.conversation.input_placeholder_disabled,MESSAGE_INPUT__PLACE_HOLDER__STEWARD:e.conversation.input_placeholder_steward,MESSAGE_INPUT__PLACE_HOLDER__WAIT_AI_AGENT_RESPONSE:e.conversation.input_placeholder_wait_ai_agent_response,MESSAGE_INPUT__PLACE_HOLDER__RECONNECTING:e.conversation.input_placeholder_reconnecting,UNKNOWN__UNKNOWN_MESSAGE_TYPE:e.conversation.unknown_message_type,POWERED_BY:e.conversation.powered_by,CSAT_TITLE_UNSUBMITTED:e.csat.title,CSAT_TITLE_SUBMITTED:e.csat.submitted_label,CSAT_CRE_TITLE:e.csat.cre_question,CSAT_CRE_SOLVED:e.csat.cre_positive_label,CSAT_CRE_NOT_SOLVED:e.csat.cre_negative_label,CSAT_REASON_PLACEHOLDER:e.csat.reason_placeholder,CSAT_RATING_TITLE:e.csat.question,CSAT_SUBMIT_LABEL:e.csat.submit_label,CSAT_SUBMISSION_EXPIRED:e.csat.submission_expired,DATE_FORMAT__JUST_NOW:e.date_format.just_now,DATE_FORMAT__MINUTES_AGO:e.date_format.minutes_ago,DATE_FORMAT__HOURS_AGO:e.date_format.hours_ago,DATE_FORMAT__DATE_SHORT:e.date_format.date_short,DATE_FORMAT__MESSAGE_LIST__DATE_SEPARATOR:e.date_format.date_separator,DATE_FORMAT__MESSAGE_TIMESTAMP:e.date_format.message_timestamp,CONVERSATION_LIST__HEADER_TITLE:e.conversation_list.header_title,CONVERSATION_LIST__ENDED:e.conversation_list.ended,CONVERSATION_LIST__SYSTEM_MESSAGE:e.conversation_list.system_message,CONVERSATION_LIST__NO_CONVERSATIONS:e.common.placeholder_no_conversations,CONVERSATION_LIST__MULTIPLE_FILES_COUNT:e.conversation_list.multiple_files_count,TALK_TO_AGENT:e.conversation.start_new_conversation_label,CITATION_SOURCE_TITLE:e.conversation.citation_title,FORM_PLACEHOLDER:e.conversation.input_placeholder_active_form,FORM_VALIDATION_REQUIRED:e.form.validation_required,OPTIONAL:e.form.optional_label,PLACE_HOLDER__WRONG:e.common.placeholder_something_went_wrong,PLACE_HOLDER__NO_MESSAGES:e.common.placeholder_no_messages,RETRY:e.common.placeholder_something_went_wrong_retry_label,BUTTON__OK:e.common.button_ok,BUTTON__CANCEL:e.common.button_cancel,FAILED_MESSAGE_RESEND:e.conversation.failed_message_resend,FAILED_MESSAGE_REMOVE:e.conversation.failed_message_remove,DESK__TICKET_CLOSURE_CONFIRM:e.desk.ticket_closure_confirm,DESK__TICKET_CLOSURE_DECLINE:e.desk.ticket_closure_decline,DESK__TICKET_CLOSURE_ERROR_MESSAGE:e.desk.ticket_closure_error_message,FILE_UPLOAD_NO_SUPPORTED_FILES:e.conversation.file_upload_no_supported_files,FILE_UPLOAD_REPLACE_ALERT__TITLE:e.conversation.file_upload_replace_alert_title,FILE_UPLOAD_REPLACE_ALERT__DESCRIPTION:e.conversation.file_upload_replace_alert_description,FILE_UPLOAD_FILES:e.conversation.attachment_document,FEEDBACK_TITLE:e.feedback.title,FEEDBACK_GOOD:e.feedback.good,FEEDBACK_BAD:e.feedback.bad,FEEDBACK_COMMENT_LABEL:e.feedback.comment_label,FEEDBACK_COMMENT_PLACEHOLDER:e.feedback.comment_placeholder,FEEDBACK_CANCEL:e.feedback.cancel,FEEDBACK_SUBMIT:e.feedback.submit,FEEDBACK_SAVE:e.feedback.save,FEEDBACK_EDIT:e.feedback.edit,FEEDBACK_REMOVE:e.feedback.remove,A11Y_MESSAGE_LIST:e.conversation.a11y_message_list,A11Y_SCROLL_TO_BOTTOM:e.conversation.a11y_scroll_to_bottom,A11Y_SCROLL_TO_NEW_MESSAGES:e.conversation.a11y_scroll_to_new_messages,A11Y_OPEN_CONVERSATION_LIST:e.conversation.a11y_open_conversation_list,A11Y_OPEN_CONVERSATION:e.conversation.a11y_open_conversation,A11Y_OPEN_CONVERSATIONS:e.conversation.a11y_open_conversations,A11Y_CLOSE_CONVERSATION:e.conversation.a11y_close_conversation,A11Y_CLOSE_CONVERSATIONS:e.conversation.a11y_close_conversations,A11Y_MENU:e.conversation.a11y_menu,A11Y_MESSAGE_INPUT:e.conversation.a11y_message_input,A11Y_SEND_MESSAGE:e.conversation.a11y_send_message,A11Y_ATTACH_FILE:e.conversation.a11y_attach_file,A11Y_CONNECT_AGENT:e.conversation.a11y_connect_agent,A11Y_CLOSE_MESSENGER:e.conversation.a11y_close_messenger,A11Y_DISMISS_NUDGE_MESSAGE:e.conversation.a11y_dismiss_nudge_message,A11Y_EXPAND_MESSENGER:e.conversation.a11y_expand_messenger,A11Y_COLLAPSE_MESSENGER:e.conversation.a11y_collapse_messenger,A11Y_MESSAGE_SENDER_YOU:e.conversation.a11y_message_sender_you,A11Y_SUGGESTED_REPLY:e.conversation.a11y_suggested_reply,A11Y_TYPING_INDICATOR:e.conversation.a11y_typing_indicator,A11Y_CODE_BLOCK_PLACEHOLDER:e.conversation.a11y_code_block_placeholder,A11Y_TYPING_FORMAT:e.conversation.a11y_typing_format,A11Y_MESSAGE_FAILED:e.conversation.a11y_message_failed,A11Y_NEW_MESSAGES_RECEIVED:e.conversation.a11y_new_messages_received,A11Y_NEW_MESSAGES_RECEIVED_FROM_SENDER:e.conversation.a11y_new_messages_received_from_sender,A11Y_AGENT_CONNECTED:e.conversation.a11y_agent_connected,A11Y_CONVERSATION_CLOSED:e.conversation.a11y_conversation_closed,A11Y_FILE_IMAGE:e.conversation.a11y_file_image,A11Y_FILE_VIDEO:e.conversation.a11y_file_video,A11Y_FILE_PDF:e.conversation.a11y_file_pdf,A11Y_FILE_DOCUMENT:e.conversation.a11y_file_document,A11Y_RECEIVED_FILE_IMAGE:e.conversation.a11y_received_file_image,A11Y_RECEIVED_FILE_VIDEO:e.conversation.a11y_received_file_video,A11Y_RECEIVED_FILE_PDF:e.conversation.a11y_received_file_pdf,A11Y_RECEIVED_FILES_IMAGE_COUNT:e.conversation.a11y_received_files_image_count,A11Y_SCREEN_CONVERSATION:e.conversation.a11y_screen_conversation,A11Y_SCREEN_CONVERSATION_WITH_AGENT:e.conversation.a11y_screen_conversation_with_agent,A11Y_SCREEN_CONVERSATION_LIST_NO_COUNT:e.conversation.a11y_screen_conversation_list_no_count,A11Y_SCREEN_CONVERSATION_LIST_WITH_COUNT:e.conversation.a11y_screen_conversation_list_with_count,A11Y_CSAT_DISPLAYED:e.conversation.a11y_csat_displayed,A11Y_EMPTY_CONVERSATION:e.conversation.a11y_empty_conversation,A11Y_INPUT_DISABLED:e.conversation.a11y_input_disabled,A11Y_FILE_SIZE_EXCEEDED:e.conversation.a11y_file_size_exceeded,A11Y_CSAT_FORM_ERROR:e.conversation.a11y_csat_form_error,A11Y_HINT_SEND_MESSAGE:e.conversation.a11y_hint_send_message,A11Y_HINT_OPEN_CONVERSATION:e.conversation.a11y_hint_open_conversation,A11Y_HINT_OPEN_CONVERSATIONS:e.conversation.a11y_hint_open_conversations,A11Y_HINT_CLOSE_CONVERSATION:e.conversation.a11y_hint_close_conversation,A11Y_HINT_OPEN_MENU:e.conversation.a11y_hint_open_menu,A11Y_HINT_CONNECT_TO_AGENT:e.conversation.a11y_hint_connect_to_agent,A11Y_HINT_ATTACH_FILE:e.conversation.a11y_hint_attach_file,A11Y_HINT_VIEW_NEW_MESSAGES:e.conversation.a11y_hint_view_new_messages,A11Y_HINT_OPEN_FILE:e.conversation.a11y_hint_open_file,A11Y_HINT_OPEN_IMAGE:e.conversation.a11y_hint_open_image,A11Y_HINT_SEND_REPLY:e.conversation.a11y_hint_send_reply,A11Y_CONVERSATION_ITEM:e.conversation_list.a11y_conversation_item,A11Y_CSAT_RATING_LABEL:e.csat.a11y_csat_rating_label,A11Y_HINT_SELECT_RATING:e.csat.a11y_hint_select_rating,IMAGE_VIEWER__DEFAULT_TITLE:e.conversation.image_viewer_default_title,A11Y_IMAGE_VIEWER_CLOSE:e.conversation.a11y_image_viewer_close,A11Y_IMAGE_VIEWER_PREVIOUS:e.conversation.a11y_image_viewer_previous,A11Y_IMAGE_VIEWER_NEXT:e.conversation.a11y_image_viewer_next,A11Y_IMAGE_VIEWER_DOWNLOAD:e.conversation.a11y_image_viewer_download,SCROLL_TO_NEW_MESSAGES_LABEL:e.conversation.scroll_to_new_messages_label,HANDOFF_CONFIRM__TITLE:e.handoff.confirm_title,HANDOFF_CONFIRM__DESCRIPTION:e.handoff.confirm_description,HANDOFF_CONFIRM__CANCEL:e.handoff.confirm_cancel,HANDOFF_CONFIRM__HANDOFF:e.handoff.confirm_handoff,MEMORY__DIALOG_TITLE:e.memory.dialog_title,MEMORY__DESC_ON:e.memory.desc_on,MEMORY__DESC_OFF:e.memory.desc_off,MEMORY__BUTTON_USE:e.memory.button_use,MEMORY__BUTTON_DONT_USE:e.memory.button_dont_use,MEMORY__BUTTON_KEEP_USING:e.memory.button_keep_using,MEMORY__BUTTON_DISABLE:e.memory.button_disable,MEMORY__BUTTON_DISABLE_AND_DELETE:e.memory.button_disable_and_delete,MEMORY__BUTTON_KEEP_OFF:e.memory.button_keep_off,MEMORY__BUTTON_ENABLE:e.memory.button_enable,MEMORY__BUTTON_CANCEL:e.memory.button_cancel,MEMORY__ERROR_MESSAGE:e.memory.error_message,A11Y_MEMORY_INDICATOR_MANAGE:e.memory.a11y_indicator_manage,A11Y_MEMORY_INDICATOR_ON:e.memory.a11y_indicator_on,A11Y_MEMORY_INDICATOR_OFF:e.memory.a11y_indicator_off,CONNECTION_DELAY__TITLE:e.connection_delay.title,CONNECTION_DELAY__DESCRIPTION:e.connection_delay.description}),pa=e=>{var t;return((t=e.split("-"))==null?void 0:t[0])??an},an="en",Ea=new Set([an,"ko","es","pt","fr","hi","it","de","tr","ja"]),ag='@import"https://fonts.googleapis.com/css?family=Roboto:400,500,600,700&display=swap";.sb-message-template__border{position:relative}.sb-message-template__border:after{content:"";position:absolute;top:0;right:0;bottom:0;left:0;z-index:1;box-shadow:inset 0 0 0 var(--border-width) var(--border-color);border-radius:var(--border-radius);pointer-events:none}.sb-message-template__action{cursor:pointer}.sb-message-template__parent{font-family:Roboto,serif}.sb-message-template__text{font-family:inherit;font-size:14px;font-weight:400;font-stretch:normal;font-style:normal;letter-spacing:normal;text-align:left}.sb-message-template__text-button{font-family:inherit;background-color:#e0e0e0;text-align:center;padding:10px;border-radius:6px;font-size:14px;font-weight:600;font-stretch:normal;font-style:normal;letter-spacing:normal}.sendbird-theme--light .sb-message-template__text-button{color:#742ddd}.sendbird-theme--dark .sb-message-template__text-button{color:#c2a9fa}.sb-message-template__text-button:hover{opacity:1;box-shadow:#0000001a 0 1px 3px,#0000000f 0 1px 2px}.sb-message-template__text-button,.sb-message-template__image-button{cursor:pointer;border-style:none}.sb-message-template__parent{border-radius:unset;background-color:transparent;overflow:hidden}.sb-message-template__parent *{box-sizing:border-box;line-height:1.3}.sb-message-template__carousel{display:flex;width:100%;box-sizing:border-box;touch-action:pan-y}',{Provider:cg,useContext:ms}=ye("AgentUIElementResolver"),lg=({entryElement:e,modalRootElement:t,rootElement:n,children:r})=>{const s=l.useMemo(()=>{const o=n??document.body,i=e??o,c=t??o,u=d=>d===Te.MODAL_ROOT?c:i.querySelector(`#${d}`);return{resolveElement:u,resolvePortalContainer:d=>u(d)??c}},[e,t,n]);return a.createElement(cg,{value:s},r)};function Et(e,t){const n=e.getRootNode({composed:t});return n instanceof ShadowRoot||n instanceof Document?n:document}const po=()=>{const e=[];let t=0;const n=new Set,r=()=>n.forEach(s=>s());return{register:s=>{const o=++t;return e.push({id:o,handler:s}),r(),()=>{const i=e.findIndex(c=>c.id===o);i>=0&&(e.splice(i,1),r())}},dismissTopmost:()=>{const s=e[e.length-1];return s?(s.handler(),!0):!1},subscribe:s=>(n.add(s),()=>{n.delete(s)}),getOpenCount:()=>e.length}},{Provider:ug,useContext:hs}=ye("EscapeDismissStack"),Eo=e=>{e.stopPropagation(),e.stopImmediatePropagation()},dg=({rootElement:e=document.body,boundaryElement:t,children:n})=>{const r=l.useRef(null),s=l.useRef(null);r.current||(r.current=po()),s.current||(s.current=po());const o=r.current,i=s.current;l.useLayoutEffect(()=>{const u=t??Et(e),d=m=>{if(m.key==="Escape"){if(o.dismissTopmost()){Eo(m);return}i.dismissTopmost()&&Eo(m)}};return u.addEventListener("keydown",d),()=>u.removeEventListener("keydown",d)},[t,e,i,o]);const c=l.useMemo(()=>({register:o.register,dismissTopmost:o.dismissTopmost,registerShellDismissHandler:i.register,subscribe:o.subscribe,getOpenCount:o.getOpenCount}),[i,o]);return a.createElement(ug,{value:c},n)},_a=(e,t,n)=>{const r=l.useRef(t);l.useLayoutEffect(()=>{r.current=t},[t]),l.useLayoutEffect(()=>{if(e)return n(()=>r.current())},[e,n])},mg=(e,t)=>{const{register:n}=hs();_a(e,t,n)},hg=(e,t)=>{const{registerShellDismissHandler:n}=hs();_a(e,t,n)},Ca=()=>{const{subscribe:e,getOpenCount:t}=hs();return l.useSyncExternalStore(e,()=>t()>0,()=>!1)},fg=(e,t,n)=>{const r=e[t];return r?typeof r=="function"?r():Promise.resolve(r):new Promise((s,o)=>{(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(o.bind(null,new Error("Unknown variable dynamic import: "+t+(t.split("/").length!==n?". Note that variables only represent file names one level deep.":""))))})},_o=ga(Or.strings),gg={..._o,HEADER_BUTTON__AGENT_HANDOFF:"Talk to human agent",MESSAGE_INPUT__PLACE_HOLDER__SUGGESTED_REPLIES:"Select an option to continue",BUTTON__SUBMIT:"Submit",SUBMITTED:"Submitted",TRY_AGAIN:"Please try again.",FILE_UPLOAD_NOTIFICATION__COUNT_LIMIT:"Up to %d files can be attached.",FILE_UPLOAD_NOTIFICATION__SIZE_LIMIT:"The maximum size per file is %d MB.",FILE_UPLOAD_NOTIFICATION__FILES_EXCLUDED_BY_VALIDATION:"%d files were excluded due to limits. Please select files individually.",FILE_UPLOAD_PHOTOS:"Photos",FILE_VIEWER__UNSUPPORT:"Unsupported message",A11Y_FILE_SELECTED:e=>`${e}, selected`,A11Y_FILE_REMOVE_BUTTON:e=>`Remove file: ${e}`,A11Y_FILE_UPLOAD_OPTIONS:"File upload options",A11Y_FAILED_MESSAGE_OPTIONS:"Failed message options",A11Y_FEEDBACK_OPTIONS:"Feedback options",A11Y_CSAT_TEXT_INPUT_LABEL:"Enter answer",FORM_UNAVAILABLE:"Form is no longer available.",FORM_NOT_SUPPORTED:"This form is not supported in the current version.",FORM_VALIDATION_MIN_LENGTH:e=>`Minimum ${e} characters required`,FORM_VALIDATION_MAX_LENGTH:e=>`Maximum ${e} characters allowed`,FORM_VALIDATION_MIN:e=>`Minimum value is ${e}`,FORM_VALIDATION_MAX:e=>`Maximum value is ${e}`,FORM_VALIDATION_MIN_SELECT:e=>`Select at least ${e} options`,FORM_VALIDATION_MAX_SELECT:e=>`Select at most ${e} options`,FORM_VALIDATION_REGEX_FAILED:"Invalid format",DATE_FORMAT__CONVERSATION_LIST__LIST_ITEM_TITLE:_o.DATE_FORMAT__DATE_SHORT,DATE_FORMAT__CONVERSATION_LIST__LIST_ITEM_TITLE_CAPTION:"h:mma",CONVERSATION_LIST__TOPICS_FALLBACK:"No category",CONVERSATION_CLOSED_FOOTER_LABEL:"Your conversation has ended",START_NEW_CONVERSATION:"💬 Start a new conversation",RETURN_TO_CONVERSATION:"💬 Return to conversation",BUTTON__SAVE:"Save",NO_NAME:"(No name)",CHANNEL_FROZEN:"Channel frozen"},Dn={language:Or.language,dateLocale:Or.dateLocale,stringSet:gg},pg=Object.freeze(Object.defineProperty({__proto__:null,default:Dn},Symbol.toStringTag,{value:"Module"})),Nr=new Map([[an,Dn]]);async function Eg(e){const t=Nr.get(e);if(t)return t;try{if(Ea.has(e)){const{default:n}=await fg(Object.assign({"./languages/de.ts":()=>Promise.resolve().then(()=>require("./cjs/qr4Ghr48.cjs")),"./languages/en.ts":()=>Promise.resolve().then(()=>pg),"./languages/es.ts":()=>Promise.resolve().then(()=>require("./cjs/fdHbDI5i.cjs")),"./languages/fr.ts":()=>Promise.resolve().then(()=>require("./cjs/DsrX4pE_.cjs")),"./languages/hi.ts":()=>Promise.resolve().then(()=>require("./cjs/BoXkkKL_.cjs")),"./languages/it.ts":()=>Promise.resolve().then(()=>require("./cjs/De9EY1XB.cjs")),"./languages/ja.ts":()=>Promise.resolve().then(()=>require("./cjs/DoR1M7Tp.cjs")),"./languages/ko.ts":()=>Promise.resolve().then(()=>require("./cjs/s8NcCXAz.cjs")),"./languages/pt.ts":()=>Promise.resolve().then(()=>require("./cjs/D3Aoub0b.cjs")),"./languages/tr.ts":()=>Promise.resolve().then(()=>require("./cjs/D-lytti9.cjs"))}),`./languages/${e}.ts`,3);return Nr.set(e,n),n}return Dn}catch{return Dn}}const{Provider:_g,useContext:le}=ye("Localization"),Cg=({language:e=navigator.language,languageCode:t,logger:n,stringSet:r,children:s})=>{const[o,i]=l.useState(Nr.get(an));return l.useEffect(()=>{const c=t??pa(e);o.language!==c&&(n==null||n.debug("localization.useEffect: update language",{from:o.language,to:c}),Eg(c).then(i))},[e,t,n]),a.createElement(_g,{value:{language:o.language,defaultStringSet:o.stringSet,stringSet:{...o.stringSet,...r},dateLocale:o.dateLocale,format:(c,u,d)=>gt.format(c,u,{locale:o.dateLocale,...d})}},s)},Pn="data-sb-agent-theme",Co=e=>(t,...n)=>{let r="";return t.forEach((s,o)=>{r+=s+(n[o]??"")}),`[${Pn}='${e}'] & { ${r} }`},ne={light:Co("light"),dark:Co("dark")},Sg=F.css(({theme:e})=>{const{palette:t}=e;return`
|
|
18
18
|
:root,
|
|
19
19
|
:host {
|
|
20
20
|
--sendbird-primary-extra-dark: ${t.primary.extraDark};
|
|
@@ -63,9 +63,9 @@ $2
|
|
|
63
63
|
--sendbird-overlay-dark: ${t.overlay.dark};
|
|
64
64
|
--sendbird-overlay-light: ${t.overlay.light};
|
|
65
65
|
}
|
|
66
|
-
`}),
|
|
67
|
-
width: ${({$size:e})=>
|
|
68
|
-
height: ${({$size:e})=>
|
|
66
|
+
`}),bg=F.css`[${Pn}='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);}[${Pn}='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);}`,v={color:{primary:{dark:"var(--sendbird-primary-dark)",main:"var(--sendbird-primary-main)"},secondary:{dark:"var(--sendbird-secondary-dark)",light:"var(--sendbird-secondary-light)"},error:{dark:"var(--sendbird-error-dark)",light:"var(--sendbird-error-light)"},information:{main:"var(--sendbird-information-main)",light:"var(--sendbird-information-light)"},background700:"var(--sendbird-background-700)",background500:"var(--sendbird-background-500)",background400:"var(--sendbird-background-400)",background300:"var(--sendbird-background-300)",background200:"var(--sendbird-background-200)",background100:"var(--sendbird-background-100)",background50:"var(--sendbird-background-50)",onlight:{textLowEmphasis:"var(--sendbird-onlight-text-low-emphasis)",textDisabled:"var(--sendbird-onlight-text-disabled)"},ondark:{textHighEmphasis:"var(--sendbird-ondark-text-high-emphasis)",textMidEmphasis:"var(--sendbird-ondark-text-mid-emphasis)",textLowEmphasis:"var(--sendbird-ondark-text-low-emphasis)",textDisabled:"var(--sendbird-ondark-text-disabled)"},overlay:{dark:"var(--sendbird-overlay-dark)"}},themedColor:{textHighEmphasis:"var(--sb-text-high-emphasis)",textMidEmphasis:"var(--sb-text-mid-emphasis)",textLowEmphasis:"var(--sb-text-low-emphasis)",textDisabled:"var(--sb-text-disabled)",textHighEmphasisInverse:"var(--sb-text-high-emphasis-inverse)",textLowEmphasisInverse:"var(--sb-text-low-emphasis-inverse)",bg_50_600:"var(--sb-bg-50-600)",bg_100_500:"var(--sb-bg-100-500)",bg_300_500:"var(--sb-bg-300-500)",bg_200_400:"var(--sb-bg-200-400)",primary:"var(--sb-primary)",error:"var(--sb-error)",secondary:"var(--sb-secondary)"}};class yt extends l.PureComponent{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(t){var n,r;(r=(n=this.props).onError)==null||r.call(n,t)}render(){const{fallback:t=null,errorFallback:n=t,loadingFallback:r=t,children:s}=this.props;return this.state.hasError?n:a.createElement(l.Suspense,{fallback:r},s)}}const nt=e=>{const t=e;return typeof t=="number"?`${t}px`:t},vg=e=>a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",...e},a.createElement("path",{className:"fill",d:"M52.552 11.448a2.666 2.666 0 0 1 .222 3.52l-.222.251-16.781 16.78 16.781 16.782a2.665 2.665 0 0 1 0 3.771 2.666 2.666 0 0 1-3.52.222l-.251-.222L32 35.771 15.219 52.552a2.665 2.665 0 0 1-3.771 0 2.666 2.666 0 0 1-.222-3.52l.222-.251L28.228 32l-16.78-16.781a2.665 2.665 0 0 1 0-3.771 2.666 2.666 0 0 1 3.52-.222l.251.222 16.78 16.78 16.782-16.78a2.665 2.665 0 0 1 3.771 0z",fill:"#000",fillRule:"evenodd"})),yg=e=>a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 16 16",...e},a.createElement("path",{className:"fill",d:"M7.33348 7.3335L2.00015 7.3335L2.00015 6.00016H5.05735L1.3335 2.27631L2.27631 1.3335L6.00015 5.05734V2.00016L7.33348 2.00016L7.33348 7.3335ZM8.66683 8.66683H14.0002V10.0002L10.943 10.0002L14.6668 13.724L13.724 14.6668L10.0002 10.943V14.0002H8.66683L8.66683 8.66683Z",fill:"#000",fillRule:"evenodd"})),Ag=e=>a.createElement("svg",{viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg",...e},a.createElement("path",{className:"fill",fillRule:"evenodd",clipRule:"evenodd",d:"M2 2H7.33333V3.33333L4.27613 3.33333L7.99999 7.05719L7.05718 8L3.33333 4.27616L3.33333 7.33333H2V2ZM14 14H8.66667V12.6667H11.7239L8.00001 8.94281L8.94282 8L12.6667 11.7238V8.66667H14V14Z",fill:"#000"})),Tg=e=>a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",fill:"evenodd",...e},a.createElement("path",{className:"fill",fill:"#0D0D0D",d:"M50.667 18.667H13.333v-5.334h37.334zM50.667 34.667H13.333v-5.334h37.334zM13.333 50.667h37.334v-5.334H13.333z"})),Ig=e=>a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",...e},a.createElement("path",{fill:"#000",fillRule:"evenodd",d:"M59.795 29.43 7.329 2.979C4.691 1.802 1.76 4.153 2.932 6.798l6.925 18.609a2 2 0 0 0 1.544 1.275l32.273 5.394L11.4 37.47a1.998 1.998 0 0 0-1.544 1.275L2.932 57.353c-.879 2.645 1.76 4.997 4.397 3.527l52.466-26.453c2.051-.882 2.051-3.82 0-4.996z",className:"fill"})),xg=new Set(["send","chat","message","chevron-right","good","good-filled","bad","bad-filled"]),Mg={close:vg,send:Ig,menu:Tg,expand:Ag,collapse:yg,spinner:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/Cf3-irI8.cjs"))),chat:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/BmdfYY9c.cjs"))),message:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/CmWLVNPR.cjs"))),error:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DNmdC4-j.cjs"))),refresh:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/D00MOxhE.cjs"))),"chevron-down":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/wf-LdaaN.cjs"))),"chevron-right":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/B0k-GApQ.cjs"))),done:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/kp5wcW4s.cjs"))),"done-circle":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/Bwaslfwl.cjs"))),stop:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/w1C9O3WB.cjs"))),"stop-circle":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DGubkk9p.cjs"))),user:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/CtHfgPDp.cjs"))),"file-document":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/_YfLwFkX.cjs"))),download:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/BN09c8-A.cjs"))),attach:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DcDTXo8_.cjs"))),"close-filled":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/D1kINslt.cjs"))),agent:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/Ce1MzjFq.cjs"))),actionbook:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/CXa-CGHE.cjs"))),function:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/zbLY6xl_.cjs"))),"radio-on":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/B9NJk4MI.cjs"))),"radio-off":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/Bb0r6Nhu.cjs"))),confluence:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/c6TZaE94.cjs"))),zendesk:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DqpDy_26.cjs"))),salesforce:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/BsgzT_SF.cjs"))),sprinklr:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/D97ZpKUC.cjs"))),website:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/ygZY2D-5.cjs"))),snippet:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/BCFOnu0u.cjs"))),template:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/eJXfXI1_.cjs"))),source:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/yVmX6iux.cjs"))),copy:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/COgkkyBM.cjs"))),show:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DM-WWpci.cjs"))),mute:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/P_ra76fq.cjs"))),good:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DEgUVAck.cjs"))),bad:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/C0s7eAf7.cjs"))),"good-filled":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/Chg8xHXT.cjs"))),"bad-filled":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/CGkmTaBn.cjs"))),delight:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DCB0iTxd.cjs"))),photo:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/GQlGFYP2.cjs"))),add:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DEGDJBmd.cjs"))),document:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DBHlAmeA.cjs"))),memory:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DB0sLqre.cjs"))),activity:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DP95uu-Y.cjs")))},Rg=e=>({size:t=24,color:n=v.color.primary.main,flipInRtl:r=!1})=>a.createElement(wg,{$size:t,$color:n,$rtlFlip:r},a.createElement(yt,{errorFallback:a.createElement(Lg,null)},a.createElement(e,null))),Sa=Object.fromEntries(Object.entries(Mg).map(([e,t])=>[e,Rg(t)])),kg=F.css`[dir='rtl'] &:not([dir='ltr']),&[dir='rtl']{transform:scaleX(-1);}`,wg=b.default.span.attrs({"aria-hidden":"true"})`
|
|
67
|
+
width: ${({$size:e})=>nt(e)};
|
|
68
|
+
height: ${({$size:e})=>nt(e)};
|
|
69
69
|
display: inline-block;
|
|
70
70
|
|
|
71
71
|
svg {
|
|
@@ -84,25 +84,25 @@ $2
|
|
|
84
84
|
stroke-linejoin: round;
|
|
85
85
|
}
|
|
86
86
|
|
|
87
|
-
${({$rtlFlip:e})=>e&&
|
|
88
|
-
`,
|
|
87
|
+
${({$rtlFlip:e})=>e&&kg};
|
|
88
|
+
`,Lg=()=>a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64"},a.createElement("rect",{x:"8",y:"8",width:"48",height:"48",fill:"none",className:"stroke",rx:"4"}),a.createElement("line",{x1:"20",y1:"20",x2:"44",y2:"44",className:"stroke"}),a.createElement("line",{x1:"44",y1:"20",x2:"20",y2:"44",className:"stroke"})),{Provider:Og,useContext:Ng}=ye("MessengerIcon",{icons:Sa}),Dg=({icons:e,children:t})=>{const n=l.useMemo(()=>({icons:Xd(Sa,e)}),[e]);return a.createElement(Og,{value:n},t)},{Provider:Pg,useContext:ba}=ye("MessengerTheme");function $g(e){const{theme:t,appearance:n,logger:r}=e;return a.createElement(Fm,{appearance:n,palette:t==null?void 0:t.palette,typography:t==null?void 0:t.typography,colors:t==null?void 0:t.colors,logger:r},a.createElement(Fg,{...e}))}function Fg({rootElement:e=document.body,children:t}){const{theme:n,updateTheme:r}=zn();return l.useLayoutEffect(()=>{e.setAttribute(Pn,n.selectedTheme)},[e,n.selectedTheme]),a.createElement(F.ThemeProvider,{theme:n},a.createElement(Pg,{value:{theme:n,updateTheme:r,rootElement:e}},t))}const Ug=(e,t)=>{l.useEffect(()=>{const n=Et(t)instanceof ShadowRoot,r=Et(t,!0);if(!(n?t:r).querySelector(`link[href*='${e}']`)){const o=r.createElement("link");o.rel="stylesheet",o.href=e,(n?t:r.head).appendChild(o)}},[e,t])},Bg=(e,t=document.body)=>{l.useEffect(()=>{if(!e)return;const n=Et(t),s=n instanceof ShadowRoot?t:n.head;if(!s)return;const o=`sba-${btoa(e).slice(0,10)}`;let i=s.querySelector(`style#${o}`);i?i.textContent!==e&&(i.textContent=e):(i=s.ownerDocument.createElement("style"),i.id=o,i.textContent=e,s.appendChild(i))},[e,t])},Hg=80,Gg=()=>{const{stringSet:e}=le(),t={screenConversation:e.A11Y_SCREEN_CONVERSATION,screenConversationWithAgent:e.A11Y_SCREEN_CONVERSATION_WITH_AGENT,screenConversationListNoCount:e.A11Y_SCREEN_CONVERSATION_LIST_NO_COUNT,screenConversationListWithCount:e.A11Y_SCREEN_CONVERSATION_LIST_WITH_COUNT,newMessage:e.A11Y_NEW_MESSAGES_RECEIVED,newMessageFromSender:e.A11Y_NEW_MESSAGES_RECEIVED_FROM_SENDER,typing:e.A11Y_TYPING_FORMAT,sendFailed:e.A11Y_MESSAGE_FAILED,agentConnected:e.A11Y_AGENT_CONNECTED,conversationClosed:e.A11Y_CONVERSATION_CLOSED,csatDisplayed:e.A11Y_CSAT_DISPLAYED,csatExpired:e.CSAT_SUBMISSION_EXPIRED,emptyState:e.A11Y_EMPTY_CONVERSATION,inputDisabled:e.A11Y_INPUT_DISABLED,fileSizeExceeded:e.A11Y_FILE_SIZE_EXCEEDED,csatFormError:e.A11Y_CSAT_FORM_ERROR},n=l.useRef(t);return n.current=t,n},va=ye("AriaLiveRegion",{announce:Ee,announceScreenEntry:Ee,announceStatus:Ee,announceError:Ee,flush:Ee,setSuppressionState:Ee}),zg=va.Provider,fs=va.useContext,Vg={position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},Kg=({children:e})=>{const t=l.useRef(null),n=l.useRef(new Set),r=l.useRef(Ee),s=Gg(),[o]=l.useState(()=>Df(g=>{r.current(g)},{throttleMs:1e3,isSuppressed:()=>n.current.size>0}));r.current=g=>{const p=t.current;p&&(p.textContent="",requestAnimationFrame(()=>{p.textContent=g}))},l.useEffect(()=>()=>{o.destroy()},[o]);const i=o.announce,c=o.flush,u=l.useCallback(g=>{const p=$f(g,s.current);i(p)},[i]),d=l.useCallback((g,p)=>{const C=Ff(g,s.current),E=(p==null?void 0:p.mode)??Pf(g.event);i(C,{mode:E,dedupeKey:p==null?void 0:p.dedupeKey})},[i]),m=l.useCallback((g,p)=>{const C=Uf(g,s.current);o.announceIgnoringSuppression(C),p&&setTimeout(()=>{p.focus()},Hg)},[o]),h=l.useCallback((g,p)=>{if(p){n.current.add(g);return}n.current.delete(g)},[]),f=l.useMemo(()=>({announce:i,announceScreenEntry:u,announceStatus:d,announceError:m,flush:c,setSuppressionState:h}),[i,m,u,d,c,h]);return a.createElement(zg,{value:f},e,a.createElement("div",{ref:t,role:"status","aria-live":"polite","aria-atomic":"true",style:Vg}))},ya=ye("ConversationAnnouncements",{announcementsEnabled:!0,announce:Ee,announceScreenEntry:Ee,announceStatus:Ee,announceError:Ee,setIsSuppressed:Ee,setStatusPauseState:Ee,flush:Ee}),qg=ya.Provider,ht=ya.useContext,Wg=({children:e,announcementsEnabled:t=!0})=>{const{announce:n,announceScreenEntry:r,announceStatus:s,announceError:o,flush:i,setSuppressionState:c}=fs(),u=l.useRef([]),d=l.useRef(new Set),m=l.useRef(Symbol("conversation-announcements")),h=l.useCallback(T=>{if(!t||!T){c(m.current,!1);return}c(m.current,!0)},[t,c]),f=l.useCallback(()=>{u.current=[]},[]),g=l.useCallback(()=>{if(u.current.length===0)return;if(!t){f();return}const T=[...u.current];f(),T.forEach(M=>{i(),s(M.params,M.options)})},[s,t,f,i]),p=l.useCallback((T,M)=>{if(M){d.current.add(T);return}d.current.delete(T),d.current.size===0&&g()},[g]),C=l.useCallback(T=>{t&&n(T)},[n,t]),E=l.useCallback(T=>{t&&r(T)},[r,t]),_=l.useCallback((T,M)=>{if(t){if(d.current.size>0){u.current.push({params:T,options:M});return}s(T,M)}},[s,t]),A=l.useCallback((T,M)=>{t&&o(T,M)},[o,t]);l.useLayoutEffect(()=>(t||(f(),c(m.current,!1)),()=>{f(),c(m.current,!1)}),[t,f,c]);const y=l.useMemo(()=>({announcementsEnabled:t,announce:C,announceScreenEntry:E,announceStatus:_,announceError:A,setIsSuppressed:h,setStatusPauseState:p,flush:i}),[t,i,C,A,E,_,h,p]);return a.createElement(qg,{value:y},e)},Vn=["a[href]","button:not(:disabled)","input:not(:disabled)","select:not(:disabled)","textarea:not(:disabled)",'[tabindex]:not([tabindex="-1"])'].join(", "),Aa=`${Vn}, [tabindex="-1"]`,$t=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},en=(e,t)=>{for(const n of e.querySelectorAll(t))if(!n.hasAttribute(ds)&&$t(n))return n;return null},Ta=e=>{let t=null,n=null;for(const r of e.querySelectorAll(Vn))r.hasAttribute(ds)||$t(r)&&(t??(t=r),n=r);return t?{first:t,last:n}:null},Ia=(e,t)=>e instanceof ShadowRoot&&!(t instanceof HTMLElement)?e.host.ownerDocument.activeElement===e.host:t instanceof HTMLElement?e instanceof Document?t===e.body||t===e.documentElement:!1:!0,Yg=(e,t,n)=>Ia(e,t)||n!=null&&t instanceof HTMLElement&&n.contains(t),gs=e=>en(e,jf),xa=e=>gs(e)??en(e,Vn),jg=e=>{const t=gs(e);if(t)return t;const n=e.querySelector(Zf);return(n?en(n,Aa):null)??en(e,Vn)},B=({as:e,variant:t="body1",color:n,maxTextLines:r,className:s,...o})=>a.createElement(Jg,{as:e,$variant:t,className:s,$color:n,$maxTextLines:r,...o}),So=new WeakMap,Xg=(e,t)=>{let n=So.get(t);n||(n=new Map,So.set(t,n));const r=n.get(e);if(r)return r;const s=t[e]??t.body1,o=F.css`font-size:${nt(s.fontSize)};font-weight:${s.fontWeight};${s.fontFamily?`font-family: ${s.fontFamily};`:""}
|
|
89
89
|
${s.lineHeight?`line-height: ${s.lineHeight};`:"line-height: 100%;"}
|
|
90
|
-
`;return n.set(e,o),o},_g=e=>e?U.css`display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:${e};overflow:hidden;`:"",Eg=C.default.span`font-stretch:normal;letter-spacing:normal;${({$variant:e,theme:t})=>pg(e,t.typography)}color:${({$color:e})=>e};${({$maxTextLines:e})=>_g(e)}`;async function cs(e){let t=e;t&&(!t.startsWith("http://")&&!t.startsWith("https://")&&(t="https://"+t),window.open(t,"_blank","noopener,noreferrer"))}const Mr='[role="dialog"][aria-modal="true"]',Cg=(e,t)=>{const n=new Set(Array.from(e.ownerDocument.querySelectorAll(Mr)).filter(s=>s!==e&&(s.contains(e)||e.contains(s)))),r=t==null?void 0:t.closest(Mr);return r&&r!==e&&n.add(r),n},bg=(e,t)=>Array.from(e.ownerDocument.querySelectorAll(Mr)).some(n=>n!==e&&!t.has(n)&&!n.contains(e)&&wt(n)),vg=e=>{const t=pa(e)??e;t===e&&_a(e),t.focus()},_a=e=>{e.hasAttribute("tabindex")||e.setAttribute("tabindex","-1")},Sg=(e,t)=>{const n=fa(e);if(!n){_a(e),e.focus();return}n[t].focus()},uo=(e,t)=>{const n=e.ownerDocument.createElement("span");return n.tabIndex=0,n.setAttribute(ns,pf),n.style.cssText=["position: fixed","width: 1px","height: 1px","opacity: 0","overflow: hidden","pointer-events: none"].join(";"),n.addEventListener("focus",()=>Sg(e,t)),n},yg=(e,t)=>{e.key==="Tab"&&(e.defaultPrevented||e.target===t&&(fa(t)||(e.preventDefault(),t.focus())))},Bn=(e,t,{nameReady:n=!0}={})=>{const r=l.useRef(0),s=l.useRef(!1);l.useEffect(()=>{if(!e||!t.current){s.current=!1;return}r.current+=1;const o=r.current,i=t.current,c=i.getRootNode(),u=c.activeElement instanceof HTMLElement?c.activeElement:null,d=Cg(i,u);return()=>{u&&Ie(()=>{if(r.current!==o)return;const m=c.activeElement;i.isConnected&&m instanceof HTMLElement&&m!==i&&!i.contains(m)&&!ga(c,m)&&m.matches(ha)&&wt(m)||bg(i,d)||!u.isConnected||!wt(u)||u.focus()})}},[e,t]),l.useEffect(()=>{if(!e||!t.current)return;const o=t.current;let i=!1;const c=()=>{if(i||s.current||!o.isConnected)return;const m=o.getRootNode().activeElement;if(m instanceof HTMLElement&&m!==o&&o.contains(m)&&wt(m)){s.current=!0;return}s.current=!0,vg(o)};if(n)return Ie(c),()=>{i=!0};const u=setTimeout(()=>Ie(c),na);return()=>{i=!0,clearTimeout(u)}},[e,t,n]),l.useEffect(()=>{if(!e||!t.current)return;const o=t.current,i=uo(o,"last"),c=uo(o,"first"),u=d=>yg(d,o);return o.insertBefore(i,o.firstChild),o.appendChild(c),o.addEventListener("keydown",u),()=>{o.removeEventListener("keydown",u),i.remove(),c.remove()}},[e,t])},gt=({style:e,portalContainerId:t,visible:n,onClose:r,children:s,cancelable:o=!0,"aria-label":i,"aria-labelledby":c,"aria-describedby":u})=>{const d=l.useRef(null),{resolvePortalContainer:m}=ss();return Bn(n,d),Lf(n,o?r:me),n?wc.createPortal(a.createElement(Ag,{onClick:o?r:void 0,style:e},a.createElement(Tg,{ref:d,role:"dialog","aria-modal":"true","aria-label":i,"aria-labelledby":c,"aria-describedby":u,onClick:h=>h.stopPropagation()},s)),m(t)):null},Ag=C.default.div`position:fixed;top:0;left:0;width:100%;height:100%;background:${b.color.overlay.dark};display:flex;justify-content:center;align-items:center;z-index:${Et.MODAL};`,Tg=C.default.div`border-radius:4px;overflow:hidden;box-shadow:0 16px 24px 2px rgba(13,13,13,0.12),0 6px 30px 5px rgba(13,13,13,0.08),0 6px 10px -5px rgba(13,13,13,0.04);z-index:${Et.MODAL};`,Ig=({id:e,children:t})=>a.createElement(xg,{id:e},t),xg=C.default.span`position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0;`,mo=(e,t)=>{const n={role:"heading","aria-level":2,"aria-label":e};return t!=null&&t.active&&t.titleId?{...n,id:t.titleId,tabIndex:-1,...t.initialFocus===!1?{}:Xi}:n},Rg=()=>{const e=`${l.useId()}-`;return(t,n)=>{if(!t)return{props:{},node:null};const r=e+n,s=l.createElement(Ig,{id:r,children:t});return{props:{"aria-describedby":r},node:s}}},ho=({name:e,mimeType:t,selected:n},r)=>{var o;const s=Ke(t??"")?r.A11Y_FILE_IMAGE(e):Zt(t??"")?r.A11Y_FILE_VIDEO(e):ui({name:e,mimeType:t})?r.A11Y_FILE_PDF(e):r.A11Y_FILE_DOCUMENT(e);return n?((o=r.A11Y_FILE_SELECTED)==null?void 0:o.call(r,s))??`${s}, selected`:s},Mg=e=>t=>{t.repeat||(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())},Gt=({onActivate:e})=>({role:"button",tabIndex:0,onClick:e,onKeyDown:Mg(e)}),wg=({disabled:e,currentIndex:t,totalCount:n,onNavigate:r})=>s=>{var u;if(e||n<=0)return;let o=null;switch(s.key){case"ArrowRight":case"ArrowDown":o=(t+1)%n;break;case"ArrowLeft":case"ArrowUp":o=(t-1+n)%n;break;default:return}s.preventDefault(),r(o);const i=s.currentTarget.parentElement,c=i==null?void 0:i.querySelectorAll('[role="radio"]');(u=c==null?void 0:c[o])==null||u.focus()},fo=(e,t,n,r,s,o)=>{let i=-1;return(e||!s&&n===0)&&(i=0),{role:"radio","aria-checked":e,"aria-disabled":t,onKeyDown:wg({disabled:t,currentIndex:n,totalCount:r,onNavigate:o}),tabIndex:i}},ae=()=>{const{stringSet:e}=ie(),t=Rg(),n=(i,c)=>{let u=e.A11Y_HINT_OPEN_FILE,d="of";Ke(i??"")&&(u=e.A11Y_HINT_OPEN_IMAGE,d="oi"),c!==void 0&&(d+=c);const m=t(u,d);return{props:m.props,descriptionNode:m.node}},r=i=>({"aria-label":ho(i,e)});return{launcher:{button:({isOpened:i,opensConversationList:c})=>{const u=hf({intent:uf({isOpened:i,opensConversationList:c}),strings:{openConversation:e.A11Y_OPEN_CONVERSATION,openConversationList:e.A11Y_OPEN_CONVERSATIONS,closeConversation:e.A11Y_CLOSE_CONVERSATION,closeConversationList:e.A11Y_CLOSE_CONVERSATIONS,hintOpenConversation:e.A11Y_HINT_OPEN_CONVERSATION,hintOpenConversationList:e.A11Y_HINT_OPEN_CONVERSATIONS,hintCloseConversation:e.A11Y_HINT_CLOSE_CONVERSATION}});let d="lc";u.hint===e.A11Y_HINT_OPEN_CONVERSATION&&(d="lo"),u.hint===e.A11Y_HINT_OPEN_CONVERSATIONS&&(d="los");const m=t(u.hint,d);return{props:{"aria-label":u.label,...m.props},descriptionNode:m.node}}},messenger:{closeButton:()=>({props:{"aria-label":e.A11Y_CLOSE_MESSENGER},descriptionNode:null}),expandButton:i=>{let c=e.A11Y_EXPAND_MESSENGER;return i&&(c=e.A11Y_COLLAPSE_MESSENGER),{props:{"aria-label":c},descriptionNode:null}},connectionDelayDialog:()=>({props:{"aria-label":e.CONNECTION_DELAY__TITLE},descriptionNode:null})},conversation:{header:{menuButton:()=>{const i=e.A11Y_HINT_OPEN_MENU,c=t(i,"mb");return{props:{"aria-label":e.A11Y_MENU,...c.props},descriptionNode:c.node}},closeConversationButton:()=>{const i=e.A11Y_HINT_CLOSE_CONVERSATION,c=t(i,"cc");return{props:{"aria-label":e.A11Y_CLOSE_CONVERSATION,...c.props},descriptionNode:c.node}},handoffButton:()=>{const i=e.A11Y_HINT_CONNECT_TO_AGENT,c=t(i,"h");return{props:{"aria-label":e.A11Y_CONNECT_AGENT,...c.props},descriptionNode:c.node}},title:(i,c)=>({props:mo(i,c),descriptionNode:null}),memoryIndicator:i=>{let c=e.A11Y_MEMORY_INDICATOR_OFF,u="mof";i&&(c=e.A11Y_MEMORY_INDICATOR_ON,u="mon");const d=t(c,u);return{props:{"aria-label":e.A11Y_MEMORY_INDICATOR_MANAGE,...d.props},descriptionNode:d.node}}},messageInput:{attachFileButton:()=>{const i=e.A11Y_HINT_ATTACH_FILE,c=t(i,"af");return{props:{"aria-label":e.A11Y_ATTACH_FILE,...c.props},descriptionNode:c.node}},sendButton:()=>{const i=e.A11Y_HINT_SEND_MESSAGE,c=t(i,"sm");return{props:{"aria-label":e.A11Y_SEND_MESSAGE,...c.props},descriptionNode:c.node}},textInput:i=>({props:{role:"textbox","aria-label":i,...Cf},descriptionNode:null})},suggestedReplies:{item:(i,c)=>{const u=e.A11Y_HINT_SEND_REPLY,d=t(u,`sr${c}`);return{props:{"aria-label":`${e.A11Y_SUGGESTED_REPLY}, ${i}`,...d.props},descriptionNode:d.node}}},feedback:{container:()=>{const i=e.A11Y_HINT_SELECT_RATING,c=t(i,"fb");return{props:c.props,descriptionNode:c.node}},button:(i,c)=>{const u=e.A11Y_HINT_SELECT_RATING,d=t(u,`f${i}`);let m=e.FEEDBACK_BAD;return i==="good"&&(m=e.FEEDBACK_GOOD),{props:{"aria-label":m,...d.props,"aria-pressed":c},descriptionNode:d.node}},optionsBottomSheet:()=>({props:{"aria-label":e.A11Y_FEEDBACK_OPTIONS},descriptionNode:null})},messageList:{item:({label:i,holding:c})=>c?{props:{"aria-hidden":!0},descriptionNode:null}:{props:{role:"listitem",tabIndex:-1,"aria-label":i},descriptionNode:null},typingItem:i=>({props:{role:"listitem",tabIndex:-1,"aria-label":Kt({sender:i,message:e.A11Y_TYPING_INDICATOR,codeBlockPlaceholder:e.A11Y_CODE_BLOCK_PLACEHOLDER})},descriptionNode:null})},newMessagesButton:()=>{const i=e.A11Y_HINT_VIEW_NEW_MESSAGES,c=t(i,"nm");return{props:{"aria-label":e.A11Y_SCROLL_TO_NEW_MESSAGES,...c.props},descriptionNode:c.node}},scrollToBottomButton:()=>{const i=e.A11Y_HINT_VIEW_NEW_MESSAGES,c=t(i,"sb");return{props:{"aria-label":e.A11Y_SCROLL_TO_BOTTOM,...c.props},descriptionNode:c.node}},startNewConversationButton:({onActivate:i})=>({props:{...Gt({onActivate:i}),"aria-label":e.TALK_TO_AGENT},descriptionNode:null}),poweredByLink:()=>({props:{"aria-label":`${e.POWERED_BY} Sendbird`},descriptionNode:null}),retryButton:(i=e.RETRY)=>({props:{"aria-label":i},descriptionNode:null}),file:{label:(i,c,u)=>i?ho({name:i,mimeType:c,selected:u},e):"",preview:i=>({props:r(i),descriptionNode:null}),buttonLikePreview:({onActivate:i,...c},u)=>{const d=n(c.mimeType,u);return{props:{...Gt({onActivate:i}),...r(c),...d.props},descriptionNode:d.descriptionNode}},removeButton:i=>({props:{"aria-label":e.A11Y_FILE_REMOVE_BUTTON(i)},descriptionNode:null})},csat:{scoresContainer:i=>{const c=e.A11Y_HINT_SELECT_RATING,u=t(c,"cs");return{props:{role:"radiogroup","aria-label":i,...u.props},descriptionNode:u.node}},scoreItem:({score:i,label:c,selected:u,disabled:d,currentIndex:m,totalCount:h,hasSelection:f,onChange:g})=>{var _;const p=c.trim()||c,v=e.A11Y_HINT_SELECT_RATING,E=t(v,`cs${i}`);return{props:{disabled:d,onClick:()=>g(i),...fo(u,d,m,h,f,A=>g(A+1)),...E.props,"aria-label":((_=e.A11Y_CSAT_RATING_LABEL)==null?void 0:_.call(e,i,p))??`${i} / ${h} — ${p}`},descriptionNode:E.node}},submitButton:i=>({props:{"aria-label":i},descriptionNode:null})},form:{button:i=>({props:{"aria-label":i},descriptionNode:null}),textInput:(i,c,u,d)=>({props:{...d!=null&&d.labelId?{"aria-labelledby":d.labelId}:{"aria-label":i},"aria-required":c,"aria-disabled":u},descriptionNode:null}),numberInput:(i,c,u)=>({props:{"aria-label":i,"aria-required":c,"aria-disabled":u},descriptionNode:null}),singleSelectGroup:i=>{const c={role:"radiogroup"};return i&&(c["aria-label"]=i),{props:c,descriptionNode:null}},singleSelectOption:(i,c,u,d,m,h,f)=>({props:{...fo(c,u,d,m,h,f),"aria-label":i},descriptionNode:null}),multiSelectOption:(i,c,u)=>({props:{"aria-label":i,"aria-pressed":c,"aria-disabled":u},descriptionNode:null})}},conversationList:{headerTitle:(i,c)=>({props:mo(i,c),descriptionNode:null}),footer:{button:({onActivate:i})=>({props:{...Gt({onActivate:i}),"aria-label":e.TALK_TO_AGENT},descriptionNode:null})},item:({agent:i,status:c,lastMessage:u,time:d,unreadCount:m,onActivate:h})=>{const f=Xh({agent:i,status:c,lastMessage:u,time:d,unreadCount:m},e.A11Y_CONVERSATION_ITEM);if(!h)return{props:{"aria-label":f},descriptionNode:null};const g=e.A11Y_HINT_OPEN_CONVERSATION,p=t(g,"cli");return{props:{...Gt({onActivate:h}),...p.props,"aria-label":f},descriptionNode:p.node}}}}},kg=({title:e,description:t,highlightedText:n})=>{const r=Ah(t,n);return a.createElement(Og,null,a.createElement(Ng,null,a.createElement(B,{as:"div",variant:"h1",color:b.themedColor.textHighEmphasis},e),t&&a.createElement(Dg,null,a.createElement(B,{as:"div",variant:"body3",color:b.themedColor.textMidEmphasis},r.beforeText,r.highlightedText?a.createElement($g,null,r.highlightedText):null,r.afterText))))},Lg=()=>{const{components:e}=Hn.useContext(),{stringSet:t}=ie(),{messenger:n}=ae(),r=Sh(),s=r.showDescription?yh(r.remainingTime):"",o=r.showDescription?t.CONNECTION_DELAY__DESCRIPTION(s):"";return a.createElement(gt,{portalContainerId:Se.WINDOW,visible:r.visible,onClose:me,...n.connectionDelayDialog().props},a.createElement(e.Dialog,{title:t.CONNECTION_DELAY__TITLE,description:o,highlightedText:s||void 0}))},Hn=qe({template:Lg,components:{Dialog:kg}}),Og=C.default.div`width:280px;padding:24px;margin:0 auto;border-radius:4px;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,Ng=C.default.div`display:flex;flex-direction:column;`,Dg=C.default.div`margin-top:16px;`,$g=C.default.strong`font-weight:700;`,Pg=({url:e})=>cs(e),{Provider:Fg,Consumer:Ea,useContext:ue}=be("Messenger");function Ug({children:e,state:t,enableCloseConversationButton:n=!1,enableExpandButton:r=!0,enableAutoDisconnectInLauncher:s=!0,...o}){const[i,c]=l.useState(!1),[u,d]=l.useState(!1),m={opened:(t==null?void 0:t.opened)??i,setOpened:(t==null?void 0:t.setOpened)??c,expanded:(t==null?void 0:t.expanded)??u,setExpanded:(t==null?void 0:t.setExpanded)??d},{resolveElement:h}=ss(),f=l.useCallback(()=>{m.setOpened(!1)},[m.setOpened]);Of(m.opened,f);const g=l.useRef(m.opened);l.useLayoutEffect(()=>{const E=g.current&&!m.opened;if(g.current=m.opened,!E)return;const _=mt(o.rootElement),A=h(Se.WINDOW);let y=!1;return Ie(()=>{var T;y||fg(_,_.activeElement,A)&&((T=h(Se.LAUNCHER))==null||T.focus())}),()=>{y=!0}},[m.opened,o.rootElement,h]);const{Template:p}=Hn.useContext(),v=l.useMemo(()=>{var E;return{...o.handlers,onClickLink:((E=o.handlers)==null?void 0:E.onClickLink)??Pg}},[o.handlers]);return a.createElement(Rd,{...o},E=>a.createElement(Fg,{value:{...o,...E,state:m,enableCloseConversationButton:n,enableExpandButton:r,enableAutoDisconnectInLauncher:s,handlers:v}},a.createElement(p,null),e))}const Ca=/iPad|iPhone|iPod/.test(navigator.userAgent),Bg=/Android/.test(navigator.userAgent),tn=e=>Ca||Bg;let Ut=null,ar=null;const Hg=(e,t=5e3)=>{Ut&&(clearInterval(Ut),clearTimeout(ar));const n=document.title;Ut=setInterval(()=>{document.title=document.title===e?n:e},750),ar=setTimeout(()=>{clearInterval(Ut),Ut=null,ar=null,document.title=n},t)},ba=()=>{Promise.resolve().then(()=>require("./cjs/B93o4u0P.cjs")).then(e=>{new Audio(e.default).play().catch(()=>{})})},va="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)",xe=U.css`&:focus-visible{outline:2px solid ${b.themedColor.primary};outline-offset:2px;}`,go=e=>{if(typeof e=="string"||typeof e=="number")return String(e)},nn=({visible:e,title:t,description:n,confirmText:r="OK",cancelText:s,onConfirm:o,onCancel:i,onClose:c,"aria-label":u})=>{const d=l.useId(),m=l.useId(),h=u??go(t)??go(n),f=u?void 0:t?d:n?m:void 0,g=t&&n?m:void 0,p=()=>{c(),Ie(()=>o==null?void 0:o())},v=()=>{c(),Ie(()=>i==null?void 0:i())};return a.createElement(gt,{portalContainerId:Se.WINDOW,visible:e,onClose:c,"aria-label":h,"aria-labelledby":f,"aria-describedby":g},a.createElement(Gg,null,a.createElement(zg,null,t&&a.createElement("div",{id:d},a.createElement(B,{variant:"h1",color:b.themedColor.textHighEmphasis},t)),n&&a.createElement(Vg,{id:m},a.createElement(B,{variant:"body3",color:b.themedColor.textMidEmphasis},n))),a.createElement(Kg,null,s&&a.createElement(po,{onClick:v},a.createElement(B,{variant:"button",color:b.themedColor.textHighEmphasis},s)),a.createElement(po,{onClick:p},a.createElement(B,{variant:"button",color:b.themedColor.primary},r)))))},Gg=C.default.div`width:360px;height:auto;padding-block:24px 12px;padding-inline:24px;margin:0 auto;border-radius:4px;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,zg=C.default.div`margin-bottom:16px;`,Vg=C.default.div`margin-top:16px;`,Kg=C.default.div`display:flex;flex-direction:row;justify-content:flex-end;`,po=C.default.button`all:unset;display:flex;justify-content:center;align-items:center;border-radius:4px;cursor:pointer;background-color:transparent;padding:10px 16px;${xe}`,{Provider:qg,useContext:Oe}=be("MessengerSession"),Wg=l.forwardRef(function({children:e,...t},n){return a.createElement(mm,{ref:n,...t},r=>a.createElement(Yg,{...r},e))}),Yg=({children:e,...t})=>{const{chatSDK:n,logger:r,appId:s,aiAgentId:o,agentPreviewConfigs:i,state:c,handlers:u,dispatcher:d,_aiAgentSDK:m}=ue(),{userSessionInfo:h,authenticate:f,userSession:g,aiAgentInfo:p,launcherInfo:v}=t,[E,_]=l.useState(!1),A=l.useRef(null);_t(n,{async onUserJoined(T,I){var O,k,R,F;T.conversation&&T.conversation.type===he.ConversationType.PROACTIVE&&I.userId===((O=n.currentUser)==null?void 0:O.userId)&&(r.info("messengerSession.onUserJoined: proactive channel joined",T.url),(R=m.session)==null||R._updateActiveChannel({url:T.url,status:"open",conversationStatus:(k=T.conversation)==null?void 0:k.status}),c.setOpened(!0),jg({sound:document.hidden||!c.opened}),(F=A.current)==null||F.call(A,{channel:T}))}}),l.useEffect(()=>{f().then(({launcher:T})=>{T.auto_open&&!tn()&&setTimeout(()=>c.setOpened(!0),500)}).catch(T=>{var I;r.error("messengerSession: failed to initialize",T),(I=u==null?void 0:u.onInitializeFailed)==null||I.call(u,T)})},[n,s,o,h==null?void 0:h.userId]),l.useEffect(()=>{const T=()=>_(!0);return d.subscribe(Fe.AnonymousSessionTokenExpired,T),()=>d.unsubscribe(Fe.AnonymousSessionTokenExpired,T)},[d]);const y=l.useCallback(()=>{t.deauthenticate().finally(()=>window.location.reload())},[t.deauthenticate]);return!g||!p||!v?null:a.createElement(qg,{value:{...t,userSession:g,aiAgentInfo:{...p,...i==null?void 0:i.bot},launcherInfo:{...v,...i==null?void 0:i.launcher},registerOnJoinedProactiveConversation:T=>A.current=T}},e,a.createElement(nn,{visible:E,title:"Session timed out",description:"Start a new conversation.",onConfirm:y,onClose:me}))};function jg({sound:e}){Hg("🔔You have received a new message"),e&&ba()}const Ln=`@${Ue}-focused-channel`,Sa=`${Date.now()}-${Math.random().toString(36).slice(2)}`,Xg=()=>{try{const e=localStorage.getItem(Ln);return e?JSON.parse(e).channelUrl??null:null}catch{return null}},_o=e=>{try{localStorage.setItem(Ln,JSON.stringify({channelUrl:e,tabId:Sa}))}catch{}},Eo=()=>{try{const e=localStorage.getItem(Ln);if(!e)return;JSON.parse(e).tabId===Sa&&localStorage.removeItem(Ln)}catch{}},Zg=(e,t)=>(l.useEffect(()=>{if(!t||!e)return;const n=()=>_o(e),r=()=>Eo();return document.hasFocus()&&_o(e),window.addEventListener("focus",n),window.addEventListener("blur",r),()=>{window.removeEventListener("focus",n),window.removeEventListener("blur",r),Eo()}},[t,e]),{isChannelViewedInAnyTab:()=>document.hasFocus()||Xg()===e}),Jg=e=>{const{config:t,chatSDK:n}=ue(),{sdkUser:r}=Oe(),s=t.conversation.messageAlertSoundEnabled,{isChannelViewedInAnyTab:o}=Zg(e,s);_t(n,{onMessageReceived(i,c){if(!s||i.url!==e||o())return;(Qe(c)&&c.sender.userId!==(r==null?void 0:r.userId)||c.isAdminMessage()&&!c.silent)&&ba()}})};function Qg(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 ep(e){if("file"in e&&e.file instanceof File&&e.file.type.startsWith("image/")){const{width:t,height:n}=await Qg(e.file);return new Le.MessageMetaArray({key:ai,value:[t,n]})}}const tp=({onScrollAfterSendMessage:e})=>{const{agentPreviewConfigs:t,handlers:n}=ue(),r=l.useRef(t==null?void 0:t.agentAttributes);return r.current=t==null?void 0:t.agentAttributes,{onBeforeSendMessage:async s=>{const o=await ep(s),i={...s,metaArrays:o?[o]:void 0},c=np(r.current);return c?{...i,data:JSON.stringify(c)}:i},onAfterSendMessage:s=>{var o,i,c;e(),(o=n==null?void 0:n.onMessageSend)==null||o.call(n,s.message),s.sendingStatus===Le.SendingStatus.SUCCEEDED?(i=n==null?void 0:n.onCustomEvent)==null||i.call(n,{type:"message-sent-succeeded",data:{message:s}}):s.sendingStatus===Le.SendingStatus.PENDING&&((c=n==null?void 0:n.onCustomEvent)==null||c.call(n,{type:"message-sent-pending",data:{message:s}}))}}},np=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},It=50,cr=It-40,{Provider:rp,useContext:ya}=be("ConversationScroll"),Co={viewport:0,contentHeight:0,contentSnapshotHeight:0,shouldRecalc:!1,shouldUpdate:!1},lr=e=>Math.max(0,e.scrollHeight-e.scrollTop-e.clientHeight),bo=e=>Array.from(e.querySelectorAll(`#${Ue}-message-item`));function sp({scrollMode:e,messageStackDirection:t,children:n}){const r=l.useRef(null),s=l.useRef({mutation:null,resize:null,resizeTargets:new Set}),o=l.useRef({distanceFromBottom:0,prevScrollTop:0}),i=l.useRef({awayByUser:!1,programmatic:!1,streaming:!1,reconcileTimer:null,userMessageTimer:null}),c=l.useRef(Co),[u,d]=l.useState(0),[m,h]=l.useState(0),[f,g]=l.useState(!1),[p,v]=l.useState(!1),[E,_]=l.useState(!0),A=$=>{const M=lr($);return o.current.distanceFromBottom=M,h(M),M},y=()=>{const $=i.current;$.reconcileTimer&&(clearTimeout($.reconcileTimer),$.reconcileTimer=null)},T=l.useCallback(()=>{const $=s.current;$.mutation&&($.mutation.disconnect(),$.mutation=null),$.resize&&($.resize.disconnect(),$.resize=null),$.resizeTargets.clear()},[]),I=l.useMemo(()=>f||t==="bottom"?"auto":e,[f,t,e]),N=()=>{c.current.contentSnapshotHeight=c.current.contentHeight,c.current.shouldUpdate=!0,c.current.shouldRecalc=!0},O=()=>{const $=r.current;!$||!c.current.shouldUpdate||d(M=>{c.current.shouldUpdate=!1;const{contentHeight:x,contentSnapshotHeight:L,shouldRecalc:P}=c.current,X=$.clientHeight;if(L>x)return M;const oe=k($,{messageType:"outgoing"});let Z=0;if(oe){const Ce=oe.message.offsetTop-cr+X;Z=Math.max(0,Ce-x)}else{const Ce=x-L,Ye=X-cr;Z=Math.max(0,Ce-Ye)}return M===0||Z!==M||P?(c.current.shouldRecalc=!1,Z):M})},k=l.useCallback(($,M)=>{const{messageType:x="all"}=M??{},L=bo($);let P=L;x==="outgoing"&&(P=L.filter(rt=>rt.getAttribute("data-layout-id")==="outgoingmessage"));const X=P[P.length-1];if(!X)return null;const oe=$.getBoundingClientRect(),Z=X.getBoundingClientRect(),Ce=$.scrollTop+(Z.top-oe.top),Ye=Ce+X.offsetHeight;return{message:X,scrollTop:Ce,lastMessageBottom:Ye}},[]),R=l.useCallback(()=>{const $=r.current;if(!$||I!=="fixed")return;const M=k($);c.current.contentHeight=(M==null?void 0:M.lastMessageBottom)??$.scrollHeight,!i.current.streaming&&c.current.contentSnapshotHeight>0&&N(),i.current.programmatic?o.current.distanceFromBottom=lr($):A($),O()},[I,k]),F=l.useCallback(()=>{T(),y(),c.current=Co,d(0),h(0),_(!0),o.current.distanceFromBottom=0,o.current.prevScrollTop=0,i.current.awayByUser=!1,i.current.programmatic=!1},[T]),D=l.useCallback(($=!0)=>{const M=o.current.distanceFromBottom>It;if(i.current.awayByUser=!1,h(0),!M){Ie(()=>{const x=r.current;x&&!i.current.awayByUser&&x.scrollTo({top:x.scrollHeight,behavior:"auto"})});return}i.current.programmatic||(i.current.programmatic=!0,_(!1),y()),Ie(()=>{const x=r.current;if(!x){i.current.programmatic=!1,_(!0);return}if(i.current.awayByUser){i.current.programmatic=!1,A(x),_(!0);return}const L=()=>{if(r.current!==x){i.current.programmatic=!1,r.current&&A(r.current),_(!0);return}i.current.programmatic=!1,A(x),_(!0)};if($&&!i.current.reconcileTimer){const P=setTimeout(L,500);i.current.reconcileTimer=P,x.addEventListener("scrollend",()=>{clearTimeout(P),i.current.reconcileTimer=null,L()},{once:!0})}x.scrollTo({top:x.scrollHeight,behavior:$?"smooth":"auto"}),$||L()})},[]),Q=l.useCallback(()=>{const $=r.current;if($){if(i.current.awayByUser){A($);return}D(!1)}},[D]),re=l.useCallback(()=>{const $=r.current,M=s.current;if(!$||!M.resize)return;const x=new Set(bo($));for(const L of M.resizeTargets)x.has(L)||(M.resize.unobserve(L),M.resizeTargets.delete(L));for(const L of x)M.resizeTargets.has(L)||(M.resize.observe(L),M.resizeTargets.add(L))},[]),G=l.useCallback($=>{T();const M=s.current;typeof ResizeObserver<"u"&&(M.resize=new ResizeObserver(Q),re());const x=new MutationObserver(()=>{re(),Q()});M.mutation=x,x.observe($,{childList:!0})},[T,Q,re]),H=l.useCallback($=>{if(!$){r.current=null,T();return}if(r.current=$,I!=="fixed"){G($);return}F(),c.current.viewport=$.clientHeight;const M=new MutationObserver(()=>{R()});s.current.mutation=M,M.observe($,{childList:!0,subtree:!0})},[T,I,R,F,G]),K=l.useCallback(()=>{const $=r.current;if(!$)return;const M=k($,{messageType:"outgoing"});M&&($.scrollTo({top:M.message.offsetTop-cr,behavior:"smooth"}),i.current.userMessageTimer&&clearTimeout(i.current.userMessageTimer),i.current.userMessageTimer=setTimeout(()=>{v(!1)},500))},[k]),J=($,M,x)=>{const L=lr($);if(x&&L>It){i.current.programmatic=!1,i.current.awayByUser=!0,y(),A($),_(!0),o.current.prevScrollTop=M;return}o.current.distanceFromBottom=L},q=($,M,x)=>{const P=A($)<=It;M&&!P&&(i.current.awayByUser=!0,y()),x&&P&&(i.current.awayByUser=!1)},z=$=>{const{scrollTop:M}=$.currentTarget,x=o.current.prevScrollTop;i.current.programmatic?J($.currentTarget,M,M<x):q($.currentTarget,M<x,M>x),o.current.prevScrollTop=M},W=l.useCallback(()=>{I==="fixed"&&(v(!0),N())},[I]),Y=l.useCallback(()=>{I==="fixed"?setTimeout(()=>K(),300):D()},[I,K]),V=l.useCallback($=>{i.current.streaming=$,I==="fixed"?N():i.current.awayByUser||D()},[I,D]),te=l.useCallback($=>{g($),$&&(d(0),I==="fixed"&&T())},[T,I]),w=l.useCallback($=>{I==="auto"&&$&&!i.current.awayByUser&&D()},[I,D]),Re=!(m<=It)&&!p,Te=l.useCallback(()=>o.current.distanceFromBottom>It,[]);return a.createElement(rp,{value:{ref:H,state:{bottomSpace:u,isAwayFromBottom:Re,isScrollPositionReconciled:E,shouldCountNewMessages:Te},props:{onScroll:z},actions:{scrollToBottom:D,onBeforeMessageSend:W,onAfterMessageSend:Y,onStreamingUpdate:V,onConversationClosed:te,onTypingIndicatorUpdate:w}}},n)}const{Provider:op,Context:ip,useContext:Ae}=be("Conversation"),ap=({children:e})=>{var s;const{channelSource:t}=Ae(),n=(s=t.channel)==null?void 0:s.url,{checkForUserActionRequired:r}=sh(n);return l.useEffect(()=>{var i;const o=(i=t.channel)==null?void 0:i.lastMessage;o&&r(o)},[t.channel,r]),a.createElement(a.Fragment,null,e)},cp=({channelUrl:e,onClearChannelUrl:t,onNavigateToConversationList:n,conversationStatsEnabled:r,shouldMarkAsRead:s,shouldInitializeConversation:o,initialUserMessage:i,children:c})=>{const{activeChannel:u,refreshActiveChannel:d}=Oe(),m=ya(),h=e||(u==null?void 0:u.url);Jg(h);const{onBeforeSendMessage:f,onAfterSendMessage:g}=tp({onScrollAfterSendMessage:()=>{m.actions.onAfterMessageSend()}}),p=l.useCallback(A=>(m.actions.onBeforeMessageSend(),f(A)),[m.actions,f]),v=l.useCallback(A=>{const y=A.some(T=>we.isStreaming(T));m.actions.onStreamingUpdate(y)},[m.actions.onStreamingUpdate]),E=l.useCallback(A=>{m.actions.onConversationClosed(A===he.ConversationStatus.CLOSED)},[m.actions.onConversationClosed]),_=l.useCallback(async()=>{await d(),e&&(t==null||t())},[d,e,t]);return a.createElement(Fm,{key:h,channelUrl:h,onBeforeSendMessage:p,onAfterSendMessage:g,onMessagesUpdated:v,onMessagesReceived:v,onChannelDeleted:_,onConversationStatusChanged:E,conversationStatsEnabled:r,shouldMarkAsRead:s,shouldInitializeConversation:o,initialUserMessage:i,shouldCountNewMessages:m.state.shouldCountNewMessages},A=>a.createElement(op,{value:{...A,scrollSource:m,goToActiveConversation:_,onNavigateToConversationList:n}},a.createElement(ap,null,c)))},Aa=({children:e,...t})=>{const{config:n}=ye(),{agentPreviewConfigs:r}=ue(),s=n.conversation.list.scrollMode,o=r==null?void 0:r.messageStackDirection;return a.createElement(sp,{scrollMode:s,messageStackDirection:o},a.createElement(cp,{...t},e))},ls=l.createContext({onDrop:me,subscribe:()=>me}),wr=({children:e})=>{const t=l.useRef(new Set);return a.createElement(ls.Provider,{value:{onDrop:n=>{var r;if(n.preventDefault(),(r=n.dataTransfer)!=null&&r.files){const s=Array.from(n.dataTransfer.files);s.length>0&&t.current.forEach(o=>o(s))}},subscribe:n=>(t.current.add(n),()=>t.current.delete(n))}},e)},lp=({onDropFiles:e})=>{const{subscribe:t}=l.useContext(ls);l.useEffect(()=>t(e),[e])};wr.Consumer=({children:e})=>{const{onDrop:t}=l.useContext(ls);return e({onDrop:t,onDragOver:s=>s.preventDefault()})};const Ta=be("WindowTitle",{hasWindowTitleReference:!1,isTitlePending:!1,isWindowNameReady:!0,registerWindowTitleReference:()=>me,registerWindowTitlePending:()=>me}),up=Ta.Provider,Ia=Ta.useContext,vo=()=>{const e=l.useRef(0),[t,n]=l.useState(!1),r=l.useCallback(()=>{let s=!0;return e.current+=1,e.current===1&&n(!0),()=>{s&&(s=!1,e.current=Math.max(0,e.current-1),e.current===0&&n(!1))}},[]);return[t,r]},us=({children:e})=>{const[t,n]=vo(),[r,s]=vo(),o=!r||t,i=l.useMemo(()=>({hasWindowTitleReference:t,isTitlePending:r,isWindowNameReady:o,registerWindowTitleReference:n,registerWindowTitlePending:s}),[t,r,n,s]);return a.createElement(up,{value:i},e)},Gn=Ia,xa=({enabled:e,label:t})=>{const{registerWindowTitleReference:n,registerWindowTitlePending:r}=Ia(),s=e&&t.trim().length>0;return l.useLayoutEffect(()=>{if(e)return r()},[r,e]),l.useLayoutEffect(()=>{if(s)return n()},[n,s]),{enabled:s,id:s?Se.WINDOW_TITLE:void 0}},dp=(e,t)=>{const r=(t?jt(e,t):null)??gg(e)??e;r===e&&!e.hasAttribute("tabindex")&&e.setAttribute("tabindex","-1"),r.focus({focusVisible:!1})},Ra=(e,{enabled:t,ready:n,nameReady:r=!0,targetSelector:s,suppressed:o=!1})=>{const i=l.useRef(!1);l.useEffect(()=>{if(!t){i.current=!1;return}if(i.current||!e.current||o||s&&!n)return;const c=as(e.current)!=null;if(!s&&!c&&!n)return;let u=!1;const d=()=>{u||i.current||!e.current||(i.current=!0,dp(e.current,s))};if(r)return Ie(d),()=>{u=!0};const m=setTimeout(()=>Ie(d),na);return()=>{u=!0,clearTimeout(m)}},[t,n,r,s,e,o])},mp=(e,t)=>{const{announcementsEnabled:n}=ct(),{channelSource:r}=Ae(),{isWindowNameReady:s}=Gn(),o=ca(),i=r.channel!=null||r.error!=null;Ra(e,{enabled:n,ready:i,nameReady:s,targetSelector:t==="messageInput"?Ef:void 0,suppressed:o})},hp=()=>{var s;const{_statsEnabled:e,channelSource:t}=Ae(),n=(s=t.channel)==null?void 0:s.url,r=l.useCallback(o=>{const i=()=>{o(Ir()?"backgrounded":"foregrounded")};return document.addEventListener("visibilitychange",i),()=>document.removeEventListener("visibilitychange",i)},[]);xh({channelUrl:n,enabled:e,isInitiallyBackgrounded:Ir,isForegrounded:Sf,subscribeToForegroundState:r})},fp=e=>Ke(e)||Zt(e);function gp(e,t){return e.filter(n=>we.isWelcomeMessage(n,t))}const Ma=(e,{previewWelcomeMessages:t,aiAgentUserId:n})=>e.filter(r=>t.length>0?!we.isWelcomeMessage(r,n):!0),pp=[],wa=()=>{var p,v,E,_,A,y;const{agentPreviewConfigs:e={},aiAgentId:t}=ue(),{aiAgentInfo:n,userSession:r}=Oe(),{channelSource:s,messageSource:o,state:{input:i,streamAnimation:c}}=Ae(),u=e.welcomeMessages??pp,d=l.useMemo(()=>Ma(o.messages,{previewWelcomeMessages:u,aiAgentUserId:t}),[t,o.messages,u]),m=at(s.channel),h=(v=(p=pi(s.channel,r.userId))==null?void 0:p.nickname)==null?void 0:v.trim(),f=m?(_=(E=s.channel)==null?void 0:E.name)==null?void 0:_.trim():(A=n==null?void 0:n.nickname)==null?void 0:A.trim(),g=h||f||void 0;return{initialized:o.initialized,channelUrl:(y=s.channel)==null?void 0:y.url,agentName:g,isClosed:Ne(s.channel),isHandedOff:m,messages:d,filteredMessagesCount:d.length,hasWelcomeMessages:u.length>0,inputDisabled:i.disabled,inputDisabledBy:i.disabledBy,isStreamAnimating:c.isAnimating,currentUserId:r.userId}},_p=(e={})=>{const{announceScreenEntry:t,announcementsEnabled:n}=ct(),{initialized:r=!1,channelUrl:s,agentName:o,isClosed:i=!1,messages:c=[],hasWelcomeMessages:u=!1}=e,d=l.useRef(null),m=l.useMemo(()=>c.some(f=>Me.isAdmin(f)&&Me.isCSAT(f)),[c]),h=c.length===0&&!u;l.useEffect(()=>{if(!n){d.current=null;return}!r||!s||d.current!==s&&(t({screen:"conversation",agentName:o,isClosed:i,hasCSAT:m,...h?{isEmpty:!0}:{}}),d.current=s)},[o,t,n,s,m,r,i,h])},Ep=()=>{const e=wa();_p(e)},ka=e=>({image:e.A11Y_RECEIVED_FILE_IMAGE,video:e.A11Y_RECEIVED_FILE_VIDEO,pdf:e.A11Y_RECEIVED_FILE_PDF,document:e.A11Y_FILE_DOCUMENT,receivedFilesImageCount:e.A11Y_RECEIVED_FILES_IMAGE_COUNT,multipleFilesCount:e.CONVERSATION_LIST__MULTIPLE_FILES_COUNT,codeBlockPlaceholder:e.A11Y_CODE_BLOCK_PLACEHOLDER}),So=(e,t,n=ut.format)=>{const r=Wi(e,ka(t)),s="sender"in e?e.sender:void 0,o=e.createdAt!=null&&e.createdAt!==0?n(e.createdAt,t.DATE_FORMAT__MESSAGE_TIMESTAMP):void 0;return{senderName:typeof(s==null?void 0:s.nickname)=="string"&&s.nickname.trim()||void 0,body:r||void 0,time:o}},Cp={senderName:!0,body:!0,time:!0},bp=Object.keys(Cp),vp=(e,t)=>bp.every(n=>e[n]===t[n]),yo=2e3,Ao=400,kr=e=>{const t=new Set;return"reqId"in e&&typeof e.reqId=="string"&&e.reqId.length>0&&t.add(`req:${e.reqId}`),"messageId"in e&&e.messageId>0&&t.add(`message:${String(e.messageId)}`),[...t]},La=e=>{if(!Me.isAdmin(e)||!Me.isCSAT(e))return null;const t=cf(e);return t?`csat:${t}`:null},Sp=e=>{const t=new Set;for(const n of e){const r=La(n);r&&t.add(r)}return t},yp=(e,t)=>{for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r&&kr(r).some(s=>t.includes(s)))return r}},ur=(e,t)=>e.some(n=>t.includes(n)),To=()=>typeof document>"u"?null:document.activeElement instanceof HTMLElement?document.activeElement:null,dr=e=>new Map(e.map(({key:t,sendingStatus:n})=>[t,n])),Ap=()=>{const{announceStatus:e,announcementsEnabled:t}=ct(),{stringSet:n,format:r}=ie(),{channelUrl:s,messages:o,isClosed:i,isHandedOff:c,agentName:u,initialized:d,inputDisabled:m,inputDisabledBy:h,isStreamAnimating:f,currentUserId:g}=wa(),{outgoingMessageStates:p,outgoingMessageStatusSignature:v}=l.useMemo(()=>{if(!g)return{outgoingMessageStates:[],outgoingMessageStatusSignature:""};const z=o.flatMap(W=>{const Y=of(W,g);return!Y||!("sendingStatus"in W)?[]:[{key:Y,sendingStatus:W.sendingStatus}]});return{outgoingMessageStates:z,outgoingMessageStatusSignature:z.map(({key:W,sendingStatus:Y})=>`${W}:${Y}`).join(",")}},[g,o]),E=l.useRef({isClosed:!1,isHandedOff:!1,inputDisabled:m,inputDisabledBy:h,outgoingMessageStatuses:dr(p)}),_=l.useRef({messages:o,currentUserId:g,inputDisabledBy:h,isStreamAnimating:f,stringSet:n,format:r}),A=l.useRef([]),y=l.useRef(null),T=l.useRef([]),I=l.useRef(new Set),N=l.useRef(new Set),O=l.useRef(!1),k=l.useRef(s);_.current={messages:o,currentUserId:g,inputDisabledBy:h,isStreamAnimating:f,stringSet:n,format:r};const R=()=>_.current.isStreamAnimating||_.current.inputDisabledBy==="ai_responding",F=()=>{y.current!=null&&(clearTimeout(y.current),y.current=null)},D=(z,W,Y)=>{const V=Y==null?void 0:Y.replaceableForMs;if(z.length===0||!V)return;const te=Date.now();T.current=[...T.current.filter(({replaceableUntil:w})=>w>te),{eventKeys:z,parts:W,replaceableUntil:te+V}]},Q=()=>A.current.length>0,re=()=>{A.current=[]},G=()=>{const[z,...W]=A.current;if(!z)return!1;A.current=W;const{eventKeys:Y,parts:V,dedupeKey:te}=z,w=Te=>{D(Y,Te,{replaceableForMs:Y.length>0?yo:void 0}),e({event:"newMessage",...Te},te?{dedupeKey:te}:void 0)};if(Y.length===0)return w(V),!0;const _e=_.current,Re=yp(_e.messages,Y);if(Re){const Te=So(Re,_e.stringSet,_e.format);return w(Te),!0}return w(V),!0},H=()=>{for(F();G(););},K=(z=yo)=>{F(),y.current=setTimeout(()=>{if(y.current=null,R())return;const W=To(),[Y]=A.current;if(!Y)return;if(Y.focusTarget!==W){A.current=[{...Y,focusTarget:W},...A.current.slice(1)],K(Ao);return}G()&&Q()&&K(Ao)},z)},J=(z,W,Y)=>{const V={eventKeys:W,parts:z,focusTarget:To(),dedupeKey:Y?Y.dedupeKey??void 0:W[0]},te=W.length===0?-1:A.current.findIndex(({eventKeys:w})=>ur(w,W));te>=0?A.current=A.current.map((w,_e)=>_e===te?{...V,dedupeKey:Y?V.dedupeKey:w.dedupeKey}:w):A.current=[...A.current,V],K()},q=(z,W,Y)=>{if(z!=="messagesUpdated"||W.length===0)return!1;const V=Date.now(),te=T.current.find(w=>w.replaceableUntil>V&&ur(w.eventKeys,W));return te?!vp(Y,te.parts):!1};l.useEffect(()=>{const z=k.current!==s;(!t||!d||z)&&(O.current=!1,N.current.clear(),re(),T.current=[],I.current.clear(),F(),z&&(k.current=s),!t||!d)||O.current||(O.current=!0,k.current=s,E.current={isClosed:i,isHandedOff:c,inputDisabled:m,inputDisabledBy:h,outgoingMessageStatuses:dr(p)},I.current=new Set(o.flatMap(W=>{if(!we.isStreaming(W))return[];const Y="sender"in W?W.sender:void 0;return(Y==null?void 0:Y.userId)===_.current.currentUserId?[]:kr(W)})),N.current=Sp(o))},[e,t,s,d,m,i,c,v]),l.useEffect(()=>{const z=(W,Y)=>{const V=_.current,te=kr(W),w=La(W);if(w!=null){if(N.current.has(w))return;N.current.add(w),e({event:"csatDisplayed"});return}if(we.isStreaming(W)){te.forEach(P=>{I.current.add(P)});return}const _e=te.filter(P=>I.current.has(P)),Re=Y==="messagesUpdated"&&_e.length>0;Re&&_e.forEach(P=>{I.current.delete(P)});const Te=Y==="messagesUpdated"&&A.current.some(({eventKeys:P})=>ur(P,te)),$=So(W,V.stringSet,V.format),M=q(Y,te,$);if(!Re&&Y!=="messagesAdded"&&!Te&&!M)return;const x=M?{dedupeKey:null}:void 0;if(Re||R()||Te){J($,[...new Set([..._e,...te])],x);return}if(M){J($,te,x);return}Q()&&H();const L=te[0];e({event:"newMessage",...$},L?{dedupeKey:L}:void 0)};return ki.subscribe(W=>{if(!O.current||W.channelUrl!==s||W.kind==="initialized"||W.kind==="messagesDeleted"||!lf(W.source))return;const Y=_.current.currentUserId;for(const V of W.messages)V&&af(V,Y)&&z(V,W.kind)})},[e,s]),l.useEffect(()=>{O.current&&(R()||Q()&&K())},[h,f]),l.useEffect(()=>()=>{F()},[]),l.useEffect(()=>{if(!O.current)return;const z=E.current,W=z.outgoingMessageStatuses;z.outgoingMessageStatuses=dr(p),p.some(({key:V,sendingStatus:te})=>{const w=W.get(V);return w!==void 0&&w!=="failed"&&te==="failed"})&&e({event:"sendFailed"})},[e,v]),l.useEffect(()=>{if(!O.current)return;const z=E.current;i&&!z.isClosed&&e({event:"conversationClosed"}),z.isClosed=i},[e,i]),l.useEffect(()=>{if(!O.current)return;const z=E.current;c&&!z.isHandedOff&&e({event:"agentConnected",agentName:u}),z.isHandedOff=c},[u,e,c]),l.useEffect(()=>{if(!O.current)return;const z=E.current;m&&h!=="ai_responding"&&(!z.inputDisabled||z.inputDisabledBy==="ai_responding")&&e({event:"inputDisabled"}),z.inputDisabled=m,z.inputDisabledBy=h},[e,m,h])},Tp=()=>{const{channelSource:e}=Ae(),t=Fi(e.channel);return!(t!=null&&t.user.userId)||!t.user.nickname?null:{userId:t.user.userId,nickname:t.user.nickname}},Ip=e=>{const{announceStatus:t,announcementsEnabled:n}=ct();uh(e??null,r=>{t({event:"typing",agentName:r})},1e4,n)},xp=()=>{const e=Tp();Ip(e)},ee=({type:e,size:t=24,className:n,color:r})=>{const{icons:s}=eg(),o=s[e];return a.createElement(Rp,{className:n},a.createElement(o,{size:t,color:r??b.color.primary.main,flipInRtl:Wf.has(e)}))},Rp=C.default.span.attrs({"aria-hidden":"true"})`
|
|
90
|
+
`;return n.set(e,o),o},Zg=e=>e?F.css`display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:${e};overflow:hidden;`:"",Jg=b.default.span`font-stretch:normal;letter-spacing:normal;${({$variant:e,theme:t})=>Xg(e,t.typography)}color:${({$color:e})=>e};${({$maxTextLines:e})=>Zg(e)}`;async function ps(e){let t=e;t&&(!t.startsWith("http://")&&!t.startsWith("https://")&&(t="https://"+t),window.open(t,"_blank","noopener,noreferrer"))}const Dr='[role="dialog"][aria-modal="true"]',Qg=(e,t)=>{const n=new Set(Array.from(e.ownerDocument.querySelectorAll(Dr)).filter(s=>s!==e&&(s.contains(e)||e.contains(s)))),r=t==null?void 0:t.closest(Dr);return r&&r!==e&&n.add(r),n},ep=(e,t)=>Array.from(e.ownerDocument.querySelectorAll(Dr)).some(n=>n!==e&&!t.has(n)&&!n.contains(e)&&$t(n)),tp=e=>{const t=xa(e)??e;t===e&&Ma(e),t.focus()},Ma=e=>{e.hasAttribute("tabindex")||e.setAttribute("tabindex","-1")},np=(e,t)=>{const n=Ta(e);if(!n){Ma(e),e.focus();return}n[t].focus()},bo=(e,t)=>{const n=e.ownerDocument.createElement("span");return n.tabIndex=0,n.setAttribute(ds,Xf),n.style.cssText=["position: fixed","width: 1px","height: 1px","opacity: 0","overflow: hidden","pointer-events: none"].join(";"),n.addEventListener("focus",()=>np(e,t)),n},rp=(e,t)=>{e.key==="Tab"&&(e.defaultPrevented||e.target===t&&(Ta(t)||(e.preventDefault(),t.focus())))},Kn=(e,t,{nameReady:n=!0}={})=>{const r=l.useRef(0),s=l.useRef(!1);l.useEffect(()=>{if(!e||!t.current){s.current=!1;return}r.current+=1;const o=r.current,i=t.current,c=i.getRootNode(),u=c.activeElement instanceof HTMLElement?c.activeElement:null,d=Qg(i,u);return()=>{u&&Re(()=>{if(r.current!==o)return;const m=c.activeElement;i.isConnected&&m instanceof HTMLElement&&m!==i&&!i.contains(m)&&!Ia(c,m)&&m.matches(Aa)&&$t(m)||ep(i,d)||!u.isConnected||!$t(u)||u.focus()})}},[e,t]),l.useEffect(()=>{if(!e||!t.current)return;const o=t.current;let i=!1;const c=()=>{if(i||s.current||!o.isConnected)return;const m=o.getRootNode().activeElement;if(m instanceof HTMLElement&&m!==o&&o.contains(m)&&$t(m)){s.current=!0;return}s.current=!0,tp(o)};if(n)return Re(c),()=>{i=!0};const u=setTimeout(()=>Re(c),ma);return()=>{i=!0,clearTimeout(u)}},[e,t,n]),l.useEffect(()=>{if(!e||!t.current)return;const o=t.current,i=bo(o,"last"),c=bo(o,"first"),u=d=>rp(d,o);return o.insertBefore(i,o.firstChild),o.appendChild(c),o.addEventListener("keydown",u),()=>{o.removeEventListener("keydown",u),i.remove(),c.remove()}},[e,t])},St=({style:e,portalContainerId:t,visible:n,onClose:r,children:s,cancelable:o=!0,"aria-label":i,"aria-labelledby":c,"aria-describedby":u})=>{const d=l.useRef(null),{resolvePortalContainer:m}=ms();return Kn(n,d),mg(n,o?r:Ee),n?zc.createPortal(a.createElement(sp,{onClick:o?r:void 0,style:e},a.createElement(op,{ref:d,role:"dialog","aria-modal":"true","aria-label":i,"aria-labelledby":c,"aria-describedby":u,onClick:h=>h.stopPropagation()},s)),m(t)):null},sp=b.default.div`position:fixed;top:0;left:0;width:100%;height:100%;background:${v.color.overlay.dark};display:flex;justify-content:center;align-items:center;z-index:${Tt.MODAL};`,op=b.default.div`border-radius:4px;overflow:hidden;box-shadow:0 16px 24px 2px rgba(13,13,13,0.12),0 6px 30px 5px rgba(13,13,13,0.08),0 6px 10px -5px rgba(13,13,13,0.04);z-index:${Tt.MODAL};`,ip=({id:e,children:t})=>a.createElement(ap,{id:e},t),ap=b.default.span`position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0;`,vo=(e,t)=>{const n={role:"heading","aria-level":2,"aria-label":e};return t!=null&&t.active&&t.titleId?{...n,id:t.titleId,tabIndex:-1,...t.initialFocus===!1?{}:ia}:n},cp=()=>{const e=`${l.useId()}-`;return(t,n)=>{if(!t)return{props:{},node:null};const r=e+n,s=l.createElement(ip,{id:r,children:t});return{props:{"aria-describedby":r},node:s}}},yo=({name:e,mimeType:t,selected:n},r)=>{var o;const s=Ve(t??"")?r.A11Y_FILE_IMAGE(e):nn(t??"")?r.A11Y_FILE_VIDEO(e):bi({name:e,mimeType:t})?r.A11Y_FILE_PDF(e):r.A11Y_FILE_DOCUMENT(e);return n?((o=r.A11Y_FILE_SELECTED)==null?void 0:o.call(r,s))??`${s}, selected`:s},lp=e=>t=>{t.repeat||(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())},Yt=({onActivate:e})=>({role:"button",tabIndex:0,onClick:e,onKeyDown:lp(e)}),up=({disabled:e,currentIndex:t,totalCount:n,onNavigate:r})=>s=>{var u;if(e||n<=0)return;let o=null;switch(s.key){case"ArrowRight":case"ArrowDown":o=(t+1)%n;break;case"ArrowLeft":case"ArrowUp":o=(t-1+n)%n;break;default:return}s.preventDefault(),r(o);const i=s.currentTarget.parentElement,c=i==null?void 0:i.querySelectorAll('[role="radio"]');(u=c==null?void 0:c[o])==null||u.focus()},Ao=(e,t,n,r,s,o)=>{let i=-1;return(e||!s&&n===0)&&(i=0),{role:"radio","aria-checked":e,"aria-disabled":t,onKeyDown:up({disabled:t,currentIndex:n,totalCount:r,onNavigate:o}),tabIndex:i}},ue=()=>{const{stringSet:e}=le(),t=cp(),n=(i,c)=>{let u=e.A11Y_HINT_OPEN_FILE,d="of";Ve(i??"")&&(u=e.A11Y_HINT_OPEN_IMAGE,d="oi"),c!==void 0&&(d+=c);const m=t(u,d);return{props:m.props,descriptionNode:m.node}},r=i=>({"aria-label":yo(i,e)});return{launcher:{button:({isOpened:i,opensConversationList:c})=>{const u=Wf({intent:Vf({isOpened:i,opensConversationList:c}),strings:{openConversation:e.A11Y_OPEN_CONVERSATION,openConversationList:e.A11Y_OPEN_CONVERSATIONS,closeConversation:e.A11Y_CLOSE_CONVERSATION,closeConversationList:e.A11Y_CLOSE_CONVERSATIONS,hintOpenConversation:e.A11Y_HINT_OPEN_CONVERSATION,hintOpenConversationList:e.A11Y_HINT_OPEN_CONVERSATIONS,hintCloseConversation:e.A11Y_HINT_CLOSE_CONVERSATION}});let d="lc";u.hint===e.A11Y_HINT_OPEN_CONVERSATION&&(d="lo"),u.hint===e.A11Y_HINT_OPEN_CONVERSATIONS&&(d="los");const m=t(u.hint,d);return{props:{"aria-label":u.label,...m.props},descriptionNode:m.node}}},messenger:{closeButton:()=>({props:{"aria-label":e.A11Y_CLOSE_MESSENGER},descriptionNode:null}),expandButton:i=>{let c=e.A11Y_EXPAND_MESSENGER;return i&&(c=e.A11Y_COLLAPSE_MESSENGER),{props:{"aria-label":c},descriptionNode:null}},connectionDelayDialog:()=>({props:{"aria-label":e.CONNECTION_DELAY__TITLE},descriptionNode:null})},conversation:{header:{menuButton:()=>{const i=e.A11Y_HINT_OPEN_MENU,c=t(i,"mb");return{props:{"aria-label":e.A11Y_MENU,...c.props},descriptionNode:c.node}},closeConversationButton:()=>{const i=e.A11Y_HINT_CLOSE_CONVERSATION,c=t(i,"cc");return{props:{"aria-label":e.A11Y_CLOSE_CONVERSATION,...c.props},descriptionNode:c.node}},handoffButton:()=>{const i=e.A11Y_HINT_CONNECT_TO_AGENT,c=t(i,"h");return{props:{"aria-label":e.A11Y_CONNECT_AGENT,...c.props},descriptionNode:c.node}},title:(i,c)=>({props:vo(i,c),descriptionNode:null}),memoryIndicator:i=>{let c=e.A11Y_MEMORY_INDICATOR_OFF,u="mof";i&&(c=e.A11Y_MEMORY_INDICATOR_ON,u="mon");const d=t(c,u);return{props:{"aria-label":e.A11Y_MEMORY_INDICATOR_MANAGE,...d.props},descriptionNode:d.node}}},messageInput:{attachFileButton:()=>{const i=e.A11Y_HINT_ATTACH_FILE,c=t(i,"af");return{props:{"aria-label":e.A11Y_ATTACH_FILE,...c.props},descriptionNode:c.node}},sendButton:()=>{const i=e.A11Y_HINT_SEND_MESSAGE,c=t(i,"sm");return{props:{"aria-label":e.A11Y_SEND_MESSAGE,...c.props},descriptionNode:c.node}},textInput:i=>({props:{role:"textbox","aria-label":i,...Qf},descriptionNode:null})},suggestedReplies:{item:(i,c)=>{const u=e.A11Y_HINT_SEND_REPLY,d=t(u,`sr${c}`);return{props:{"aria-label":`${e.A11Y_SUGGESTED_REPLY}, ${i}`,...d.props},descriptionNode:d.node}}},feedback:{container:()=>{const i=e.A11Y_HINT_SELECT_RATING,c=t(i,"fb");return{props:c.props,descriptionNode:c.node}},button:(i,c)=>{const u=e.A11Y_HINT_SELECT_RATING,d=t(u,`f${i}`);let m=e.FEEDBACK_BAD;return i==="good"&&(m=e.FEEDBACK_GOOD),{props:{"aria-label":m,...d.props,"aria-pressed":c},descriptionNode:d.node}},optionsBottomSheet:()=>({props:{"aria-label":e.A11Y_FEEDBACK_OPTIONS},descriptionNode:null})},messageList:{item:({label:i,holding:c})=>c?{props:{"aria-hidden":!0},descriptionNode:null}:{props:{role:"listitem",tabIndex:-1,"aria-label":i},descriptionNode:null},typingItem:i=>({props:{role:"listitem",tabIndex:-1,"aria-label":Zt({sender:i,message:e.A11Y_TYPING_INDICATOR,codeBlockPlaceholder:e.A11Y_CODE_BLOCK_PLACEHOLDER})},descriptionNode:null})},newMessagesButton:()=>{const i=e.A11Y_HINT_VIEW_NEW_MESSAGES,c=t(i,"nm");return{props:{"aria-label":e.A11Y_SCROLL_TO_NEW_MESSAGES,...c.props},descriptionNode:c.node}},scrollToBottomButton:()=>{const i=e.A11Y_HINT_VIEW_NEW_MESSAGES,c=t(i,"sb");return{props:{"aria-label":e.A11Y_SCROLL_TO_BOTTOM,...c.props},descriptionNode:c.node}},startNewConversationButton:({onActivate:i})=>({props:{...Yt({onActivate:i}),"aria-label":e.TALK_TO_AGENT},descriptionNode:null}),poweredByLink:()=>({props:{"aria-label":`${e.POWERED_BY} Sendbird`},descriptionNode:null}),retryButton:(i=e.RETRY)=>({props:{"aria-label":i},descriptionNode:null}),file:{label:(i,c,u)=>i?yo({name:i,mimeType:c,selected:u},e):"",preview:i=>({props:r(i),descriptionNode:null}),buttonLikePreview:({onActivate:i,...c},u)=>{const d=n(c.mimeType,u);return{props:{...Yt({onActivate:i}),...r(c),...d.props},descriptionNode:d.descriptionNode}},removeButton:i=>({props:{"aria-label":e.A11Y_FILE_REMOVE_BUTTON(i)},descriptionNode:null})},csat:{scoresContainer:i=>{const c=e.A11Y_HINT_SELECT_RATING,u=t(c,"cs");return{props:{role:"radiogroup","aria-label":i,...u.props},descriptionNode:u.node}},scoreItem:({score:i,label:c,selected:u,disabled:d,currentIndex:m,totalCount:h,hasSelection:f,onChange:g})=>{var _;const p=c.trim()||c,C=e.A11Y_HINT_SELECT_RATING,E=t(C,`cs${i}`);return{props:{disabled:d,onClick:()=>g(i),...Ao(u,d,m,h,f,A=>g(A+1)),...E.props,"aria-label":((_=e.A11Y_CSAT_RATING_LABEL)==null?void 0:_.call(e,i,p))??`${i} / ${h} — ${p}`},descriptionNode:E.node}},submitButton:i=>({props:{"aria-label":i},descriptionNode:null})},form:{button:i=>({props:{"aria-label":i},descriptionNode:null}),textInput:(i,c,u,d)=>({props:{...d!=null&&d.labelId?{"aria-labelledby":d.labelId}:{"aria-label":i},"aria-required":c,"aria-disabled":u},descriptionNode:null}),numberInput:(i,c,u)=>({props:{"aria-label":i,"aria-required":c,"aria-disabled":u},descriptionNode:null}),singleSelectGroup:i=>{const c={role:"radiogroup"};return i&&(c["aria-label"]=i),{props:c,descriptionNode:null}},singleSelectOption:(i,c,u,d,m,h,f)=>({props:{...Ao(c,u,d,m,h,f),"aria-label":i},descriptionNode:null}),multiSelectOption:(i,c,u)=>({props:{"aria-label":i,"aria-pressed":c,"aria-disabled":u},descriptionNode:null})}},conversationList:{headerTitle:(i,c)=>({props:vo(i,c),descriptionNode:null}),footer:{button:({onActivate:i})=>({props:{...Yt({onActivate:i}),"aria-label":e.TALK_TO_AGENT},descriptionNode:null})},item:({agent:i,status:c,lastMessage:u,time:d,unreadCount:m,onActivate:h})=>{const f=wf({agent:i,status:c,lastMessage:u,time:d,unreadCount:m},e.A11Y_CONVERSATION_ITEM);if(!h)return{props:{"aria-label":f},descriptionNode:null};const g=e.A11Y_HINT_OPEN_CONVERSATION,p=t(g,"cli");return{props:{...Yt({onActivate:h}),...p.props,"aria-label":f},descriptionNode:p.node}}}}},dp=({title:e,description:t,highlightedText:n})=>{const r=sf(t,n);return a.createElement(hp,null,a.createElement(fp,null,a.createElement(B,{as:"div",variant:"h1",color:v.themedColor.textHighEmphasis},e),t&&a.createElement(gp,null,a.createElement(B,{as:"div",variant:"body3",color:v.themedColor.textMidEmphasis},r.beforeText,r.highlightedText?a.createElement(pp,null,r.highlightedText):null,r.afterText))))},mp=()=>{const{components:e}=qn.useContext(),{stringSet:t}=le(),{messenger:n}=ue(),r=nf(),s=r.showDescription?rf(r.remainingTime):"",o=r.showDescription?t.CONNECTION_DELAY__DESCRIPTION(s):"";return a.createElement(St,{portalContainerId:Te.WINDOW,visible:r.visible,onClose:Ee,...n.connectionDelayDialog().props},a.createElement(e.Dialog,{title:t.CONNECTION_DELAY__TITLE,description:o,highlightedText:s||void 0}))},qn=Qe({template:mp,components:{Dialog:dp}}),hp=b.default.div`width:280px;padding:24px;margin:0 auto;border-radius:4px;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,fp=b.default.div`display:flex;flex-direction:column;`,gp=b.default.div`margin-top:16px;`,pp=b.default.strong`font-weight:700;`,Ep=({url:e})=>ps(e),{Provider:_p,Consumer:Ra,useContext:ge}=ye("Messenger");function Cp({children:e,state:t,enableCloseConversationButton:n=!1,enableExpandButton:r=!0,enableAutoDisconnectInLauncher:s=!0,...o}){const[i,c]=l.useState(!1),[u,d]=l.useState(!1),m={opened:(t==null?void 0:t.opened)??i,setOpened:(t==null?void 0:t.setOpened)??c,expanded:(t==null?void 0:t.expanded)??u,setExpanded:(t==null?void 0:t.setExpanded)??d},{resolveElement:h}=ms(),f=l.useCallback(()=>{m.setOpened(!1)},[m.setOpened]);hg(m.opened,f);const g=l.useRef(m.opened);l.useLayoutEffect(()=>{const E=g.current&&!m.opened;if(g.current=m.opened,!E)return;const _=Et(o.rootElement),A=h(Te.WINDOW);let y=!1;return Re(()=>{var T;y||Yg(_,_.activeElement,A)&&((T=h(Te.LAUNCHER))==null||T.focus())}),()=>{y=!0}},[m.opened,o.rootElement,h]);const{Template:p}=qn.useContext(),C=l.useMemo(()=>{var E;return{...o.handlers,onClickLink:((E=o.handlers)==null?void 0:E.onClickLink)??Ep}},[o.handlers]);return a.createElement(sm,{...o},E=>a.createElement(_p,{value:{...o,...E,state:m,enableCloseConversationButton:n,enableExpandButton:r,enableAutoDisconnectInLauncher:s,handlers:C}},a.createElement(p,null),e))}const ka=/iPad|iPhone|iPod/.test(navigator.userAgent),Sp=/Android/.test(navigator.userAgent),cn=e=>ka||Sp;let Kt=null,mr=null;const bp=(e,t=5e3)=>{Kt&&(clearInterval(Kt),clearTimeout(mr));const n=document.title;Kt=setInterval(()=>{document.title=document.title===e?n:e},750),mr=setTimeout(()=>{clearInterval(Kt),Kt=null,mr=null,document.title=n},t)},wa=()=>{Promise.resolve().then(()=>require("./cjs/B93o4u0P.cjs")).then(e=>{new Audio(e.default).play().catch(()=>{})})},La="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)",ke=F.css`&:focus-visible{outline:2px solid ${v.themedColor.primary};outline-offset:2px;}`,To=e=>{if(typeof e=="string"||typeof e=="number")return String(e)},ln=({visible:e,title:t,description:n,confirmText:r="OK",cancelText:s,onConfirm:o,onCancel:i,onClose:c,"aria-label":u})=>{const d=l.useId(),m=l.useId(),h=u??To(t)??To(n),f=u?void 0:t?d:n?m:void 0,g=t&&n?m:void 0,p=()=>{c(),Re(()=>o==null?void 0:o())},C=()=>{c(),Re(()=>i==null?void 0:i())};return a.createElement(St,{portalContainerId:Te.WINDOW,visible:e,onClose:c,"aria-label":h,"aria-labelledby":f,"aria-describedby":g},a.createElement(vp,null,a.createElement(yp,null,t&&a.createElement("div",{id:d},a.createElement(B,{variant:"h1",color:v.themedColor.textHighEmphasis},t)),n&&a.createElement(Ap,{id:m},a.createElement(B,{variant:"body3",color:v.themedColor.textMidEmphasis},n))),a.createElement(Tp,null,s&&a.createElement(Io,{onClick:C},a.createElement(B,{variant:"button",color:v.themedColor.textHighEmphasis},s)),a.createElement(Io,{onClick:p},a.createElement(B,{variant:"button",color:v.themedColor.primary},r)))))},vp=b.default.div`width:360px;height:auto;padding-block:24px 12px;padding-inline:24px;margin:0 auto;border-radius:4px;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,yp=b.default.div`margin-bottom:16px;`,Ap=b.default.div`margin-top:16px;`,Tp=b.default.div`display:flex;flex-direction:row;justify-content:flex-end;`,Io=b.default.button`all:unset;display:flex;justify-content:center;align-items:center;border-radius:4px;cursor:pointer;background-color:transparent;padding:10px 16px;${ke}`,{Provider:Ip,useContext:De}=ye("MessengerSession"),xp=l.forwardRef(function({children:e,...t},n){return a.createElement(Gm,{ref:n,...t},r=>a.createElement(Mp,{...r},e))}),Mp=({children:e,...t})=>{const{chatSDK:n,logger:r,appId:s,aiAgentId:o,agentPreviewConfigs:i,state:c,handlers:u,dispatcher:d,_aiAgentSDK:m}=ge(),{userSessionInfo:h,authenticate:f,userSession:g,aiAgentInfo:p,launcherInfo:C}=t,[E,_]=l.useState(!1),A=l.useRef(null);Ct(n,{async onUserJoined(T,M){var w,R,x,$;T.conversation&&T.conversation.type===Ce.ConversationType.PROACTIVE&&M.userId===((w=n.currentUser)==null?void 0:w.userId)&&(r.info("messengerSession.onUserJoined: proactive channel joined",T.url),(x=m.session)==null||x._updateActiveChannel({url:T.url,status:"open",conversationStatus:(R=T.conversation)==null?void 0:R.status}),c.setOpened(!0),Rp({sound:document.hidden||!c.opened}),($=A.current)==null||$.call(A,{channel:T}))}}),l.useEffect(()=>{f().then(({launcher:T})=>{T.auto_open&&!cn()&&setTimeout(()=>c.setOpened(!0),500)}).catch(T=>{var M;r.error("messengerSession: failed to initialize",T),(M=u==null?void 0:u.onInitializeFailed)==null||M.call(u,T)})},[n,s,o,h==null?void 0:h.userId]),l.useEffect(()=>{const T=()=>_(!0);return d.subscribe(Ge.AnonymousSessionTokenExpired,T),()=>d.unsubscribe(Ge.AnonymousSessionTokenExpired,T)},[d]);const y=l.useCallback(()=>{t.deauthenticate().finally(()=>window.location.reload())},[t.deauthenticate]);return!g||!p||!C?null:a.createElement(Ip,{value:{...t,userSession:g,aiAgentInfo:{...p,...i==null?void 0:i.bot},launcherInfo:{...C,...i==null?void 0:i.launcher},registerOnJoinedProactiveConversation:T=>A.current=T}},e,a.createElement(ln,{visible:E,title:"Session timed out",description:"Start a new conversation.",onConfirm:y,onClose:Ee}))};function Rp({sound:e}){bp("🔔You have received a new message"),e&&wa()}const $n=`@${ze}-focused-channel`,Oa=`${Date.now()}-${Math.random().toString(36).slice(2)}`,kp=()=>{try{const e=localStorage.getItem($n);return e?JSON.parse(e).channelUrl??null:null}catch{return null}},xo=e=>{try{localStorage.setItem($n,JSON.stringify({channelUrl:e,tabId:Oa}))}catch{}},Mo=()=>{try{const e=localStorage.getItem($n);if(!e)return;JSON.parse(e).tabId===Oa&&localStorage.removeItem($n)}catch{}},wp=(e,t)=>(l.useEffect(()=>{if(!t||!e)return;const n=()=>xo(e),r=()=>Mo();return document.hasFocus()&&xo(e),window.addEventListener("focus",n),window.addEventListener("blur",r),()=>{window.removeEventListener("focus",n),window.removeEventListener("blur",r),Mo()}},[t,e]),{isChannelViewedInAnyTab:()=>document.hasFocus()||kp()===e}),Lp=e=>{const{config:t,chatSDK:n}=ge(),{sdkUser:r}=De(),s=t.conversation.messageAlertSoundEnabled,{isChannelViewedInAnyTab:o}=wp(e,s);Ct(n,{onMessageReceived(i,c){if(!s||i.url!==e||o())return;(Xe(c)&&c.sender.userId!==(r==null?void 0:r.userId)||c.isAdminMessage()&&!c.silent)&&wa()}})},Pr=new WeakMap;function Op(e,t){Ve(e.type)&&!Pr.has(e)&&Pr.set(e,Na(t))}async function Np(e){const t=URL.createObjectURL(e),n=await Na(t);return URL.revokeObjectURL(t),n}function Na(e){return new Promise(t=>{const n=new Image;n.onload=function(){t({width:String(n.width),height:String(n.height)})},n.onerror=function(){t(void 0)},n.src=e})}async function Dp(e){if("file"in e&&e.file instanceof File&&Ve(e.file.type)){const t=await(Pr.get(e.file)??Np(e.file));return t?new we.MessageMetaArray({key:_i,value:[t.width,t.height]}):void 0}}const Pp=({onScrollAfterSendMessage:e})=>{const{agentPreviewConfigs:t,handlers:n}=ge(),r=l.useRef(t==null?void 0:t.agentAttributes);return r.current=t==null?void 0:t.agentAttributes,{onBeforeSendMessage:async s=>{const o=await Dp(s),i={...s,metaArrays:o?[o]:void 0},c=$p(r.current);return c?{...i,data:JSON.stringify(c)}:i},onAfterSendMessage:s=>{var o,i,c;e(),(o=n==null?void 0:n.onMessageSend)==null||o.call(n,s.message),s.sendingStatus===we.SendingStatus.SUCCEEDED?(i=n==null?void 0:n.onCustomEvent)==null||i.call(n,{type:"message-sent-succeeded",data:{message:s}}):s.sendingStatus===we.SendingStatus.PENDING&&((c=n==null?void 0:n.onCustomEvent)==null||c.call(n,{type:"message-sent-pending",data:{message:s}}))}}},$p=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},Ot=50,hr=Ot-40,{Provider:Fp,useContext:Da}=ye("ConversationScroll"),Ro={viewport:0,contentHeight:0,contentSnapshotHeight:0,shouldRecalc:!1,shouldUpdate:!1},fr=e=>Math.max(0,e.scrollHeight-e.scrollTop-e.clientHeight),ko=e=>Array.from(e.querySelectorAll(`#${ze}-message-item`));function Up({scrollMode:e,messageStackDirection:t,children:n}){const r=l.useRef(null),s=l.useRef({mutation:null,resize:null,resizeTargets:new Set}),o=l.useRef({distanceFromBottom:0,prevScrollTop:0}),i=l.useRef({awayByUser:!1,programmatic:!1,streaming:!1,reconcileTimer:null,userMessageTimer:null}),c=l.useRef(Ro),[u,d]=l.useState(0),[m,h]=l.useState(0),[f,g]=l.useState(!1),[p,C]=l.useState(!1),[E,_]=l.useState(!0),A=I=>{const k=fr(I);return o.current.distanceFromBottom=k,h(k),k},y=()=>{const I=i.current;I.reconcileTimer&&(clearTimeout(I.reconcileTimer),I.reconcileTimer=null)},T=l.useCallback(()=>{const I=s.current;I.mutation&&(I.mutation.disconnect(),I.mutation=null),I.resize&&(I.resize.disconnect(),I.resize=null),I.resizeTargets.clear()},[]),M=l.useMemo(()=>f||t==="bottom"?"auto":e,[f,t,e]),O=()=>{c.current.contentSnapshotHeight=c.current.contentHeight,c.current.shouldUpdate=!0,c.current.shouldRecalc=!0},w=()=>{const I=r.current;!I||!c.current.shouldUpdate||d(k=>{c.current.shouldUpdate=!1;const{contentHeight:D,contentSnapshotHeight:U,shouldRecalc:Z}=c.current,oe=I.clientHeight;if(U>D)return k;const Q=R(I,{messageType:"outgoing"});let Se=0;if(Q){const K=Q.message.offsetTop-hr+oe;Se=Math.max(0,K-D)}else{const K=D-U,me=oe-hr;Se=Math.max(0,K-me)}return k===0||Se!==k||Z?(c.current.shouldRecalc=!1,Se):k})},R=l.useCallback((I,k)=>{const{messageType:D="all"}=k??{},U=ko(I);let Z=U;D==="outgoing"&&(Z=U.filter(he=>he.getAttribute("data-layout-id")==="outgoingmessage"));const oe=Z[Z.length-1];if(!oe)return null;const Q=I.getBoundingClientRect(),Se=oe.getBoundingClientRect(),K=I.scrollTop+(Se.top-Q.top),me=K+oe.offsetHeight;return{message:oe,scrollTop:K,lastMessageBottom:me}},[]),x=l.useCallback(()=>{const I=r.current;if(!I||M!=="fixed")return;const k=R(I);c.current.contentHeight=(k==null?void 0:k.lastMessageBottom)??I.scrollHeight,!i.current.streaming&&c.current.contentSnapshotHeight>0&&O(),i.current.programmatic?o.current.distanceFromBottom=fr(I):A(I),w()},[M,R]),$=l.useCallback(()=>{T(),y(),c.current=Ro,d(0),h(0),_(!0),o.current.distanceFromBottom=0,o.current.prevScrollTop=0,i.current.awayByUser=!1,i.current.programmatic=!1},[T]),N=l.useCallback((I=!0)=>{const k=o.current.distanceFromBottom>Ot;if(i.current.awayByUser=!1,h(0),!k){Re(()=>{const D=r.current;D&&!i.current.awayByUser&&D.scrollTo({top:D.scrollHeight,behavior:"auto"})});return}i.current.programmatic||(i.current.programmatic=!0,_(!1),y()),Re(()=>{const D=r.current;if(!D){i.current.programmatic=!1,_(!0);return}if(i.current.awayByUser){i.current.programmatic=!1,A(D),_(!0);return}const U=()=>{if(r.current!==D){i.current.programmatic=!1,r.current&&A(r.current),_(!0);return}i.current.programmatic=!1,A(D),_(!0)};if(I&&!i.current.reconcileTimer){const Z=setTimeout(U,500);i.current.reconcileTimer=Z,D.addEventListener("scrollend",()=>{clearTimeout(Z),i.current.reconcileTimer=null,U()},{once:!0})}D.scrollTo({top:D.scrollHeight,behavior:I?"smooth":"auto"}),I||U()})},[]),J=l.useCallback(()=>{const I=r.current;if(I){if(i.current.awayByUser){A(I);return}N(!1)}},[N]),se=l.useCallback(()=>{const I=r.current,k=s.current;if(!I||!k.resize)return;const D=new Set(ko(I));for(const U of k.resizeTargets)D.has(U)||(k.resize.unobserve(U),k.resizeTargets.delete(U));for(const U of D)k.resizeTargets.has(U)||(k.resize.observe(U),k.resizeTargets.add(U))},[]),Y=l.useCallback(I=>{T();const k=s.current;typeof ResizeObserver<"u"&&(k.resize=new ResizeObserver(J),se());const D=new MutationObserver(()=>{se(),J()});k.mutation=D,D.observe(I,{childList:!0})},[T,J,se]),j=l.useCallback(I=>{if(!I){r.current=null,T();return}if(r.current=I,M!=="fixed"){Y(I);return}$(),c.current.viewport=I.clientHeight;const k=new MutationObserver(()=>{x()});s.current.mutation=k,k.observe(I,{childList:!0,subtree:!0})},[T,M,x,$,Y]),P=l.useCallback(()=>{const I=r.current;if(!I)return;const k=R(I,{messageType:"outgoing"});k&&(I.scrollTo({top:k.message.offsetTop-hr,behavior:"smooth"}),i.current.userMessageTimer&&clearTimeout(i.current.userMessageTimer),i.current.userMessageTimer=setTimeout(()=>{C(!1)},500))},[R]),V=(I,k,D)=>{const U=fr(I);if(D&&U>Ot){i.current.programmatic=!1,i.current.awayByUser=!0,y(),A(I),_(!0),o.current.prevScrollTop=k;return}o.current.distanceFromBottom=U},q=(I,k,D)=>{const Z=A(I)<=Ot;k&&!Z&&(i.current.awayByUser=!0,y()),D&&Z&&(i.current.awayByUser=!1)},W=l.useCallback(I=>{const{scrollTop:k}=I.currentTarget,D=o.current.prevScrollTop;i.current.programmatic?V(I.currentTarget,k,k<D):q(I.currentTarget,k<D,k>D),o.current.prevScrollTop=k},[]),H=l.useCallback(()=>{M==="fixed"&&(C(!0),O())},[M]),G=l.useCallback(()=>{M==="fixed"?setTimeout(()=>P(),300):N()},[M,P]),z=l.useCallback(I=>{i.current.streaming=I,M==="fixed"?O():i.current.awayByUser||N()},[M,N]),ee=l.useCallback(I=>{g(I),I&&(d(0),M==="fixed"&&T())},[T,M]),ae=l.useCallback(I=>{M==="auto"&&I&&!i.current.awayByUser&&N()},[M,N]),ve=!(m<=Ot)&&!p,xe=l.useCallback(()=>o.current.distanceFromBottom>Ot,[]),Oe=l.useMemo(()=>({ref:j,state:{bottomSpace:u,isAwayFromBottom:ve,isScrollPositionReconciled:E,shouldCountNewMessages:xe},props:{onScroll:W},actions:{scrollToBottom:N,onBeforeMessageSend:H,onAfterMessageSend:G,onStreamingUpdate:z,onConversationClosed:ee,onTypingIndicatorUpdate:ae}}),[j,u,ve,E,xe,W,N,H,G,z,ee,ae]);return a.createElement(Fp,{value:Oe},n)}const{Provider:Bp,Context:Hp,useContext:Me}=ye("Conversation"),Gp=({children:e})=>{var s;const{channelSource:t}=Me(),n=(s=t.channel)==null?void 0:s.url,{checkForUserActionRequired:r}=Fh(n);return l.useEffect(()=>{var i;const o=(i=t.channel)==null?void 0:i.lastMessage;o&&r(o)},[t.channel,r]),a.createElement(a.Fragment,null,e)},zp=({context:e,scrollSource:t,goToActiveConversation:n,onNavigateToConversationList:r,children:s})=>{const o=l.useMemo(()=>({...e,scrollSource:t,goToActiveConversation:n,onNavigateToConversationList:r}),[e,t,n,r]);return a.createElement(Bp,{value:o},s)},Vp=({channelUrl:e,onClearChannelUrl:t,onNavigateToConversationList:n,conversationStatsEnabled:r,shouldMarkAsRead:s,shouldInitializeConversation:o,initialUserMessage:i,children:c})=>{const{activeChannel:u,refreshActiveChannel:d}=De(),m=Da(),h=e||(u==null?void 0:u.url);Lp(h);const{onBeforeSendMessage:f,onAfterSendMessage:g}=Pp({onScrollAfterSendMessage:()=>{m.actions.onAfterMessageSend()}}),p=l.useCallback(A=>(m.actions.onBeforeMessageSend(),f(A)),[m.actions,f]),C=l.useCallback(A=>{const y=A.some(T=>Ae.isStreaming(T));m.actions.onStreamingUpdate(y)},[m.actions.onStreamingUpdate]),E=l.useCallback(A=>{m.actions.onConversationClosed(A===Ce.ConversationStatus.CLOSED)},[m.actions.onConversationClosed]),_=l.useCallback(async()=>{await d(),e&&(t==null||t())},[d,e,t]);return a.createElement(_h,{key:h,channelUrl:h,onBeforeSendMessage:p,onAfterSendMessage:g,onMessagesUpdated:C,onMessagesReceived:C,onChannelDeleted:_,onConversationStatusChanged:E,conversationStatsEnabled:r,shouldMarkAsRead:s,shouldInitializeConversation:o,initialUserMessage:i,shouldCountNewMessages:m.state.shouldCountNewMessages},A=>a.createElement(zp,{context:A,scrollSource:m,goToActiveConversation:_,onNavigateToConversationList:n},a.createElement(Gp,null,c)))},Pa=({children:e,...t})=>{const{config:n}=Ie(),{agentPreviewConfigs:r}=ge(),s=n.conversation.list.scrollMode,o=r==null?void 0:r.messageStackDirection;return a.createElement(Up,{scrollMode:s,messageStackDirection:o},a.createElement(Vp,{...t},e))},Es=l.createContext({onDrop:Ee,subscribe:()=>Ee}),$r=({children:e})=>{const t=l.useRef(new Set);return a.createElement(Es.Provider,{value:{onDrop:n=>{var r;if(n.preventDefault(),(r=n.dataTransfer)!=null&&r.files){const s=Array.from(n.dataTransfer.files);s.length>0&&t.current.forEach(o=>o(s))}},subscribe:n=>(t.current.add(n),()=>t.current.delete(n))}},e)},Kp=({onDropFiles:e})=>{const{subscribe:t}=l.useContext(Es);l.useEffect(()=>t(e),[e])};$r.Consumer=({children:e})=>{const{onDrop:t}=l.useContext(Es);return e({onDrop:t,onDragOver:s=>s.preventDefault()})};const $a=ye("WindowTitle",{hasWindowTitleReference:!1,isTitlePending:!1,isWindowNameReady:!0,registerWindowTitleReference:()=>Ee,registerWindowTitlePending:()=>Ee}),qp=$a.Provider,Fa=$a.useContext,wo=()=>{const e=l.useRef(0),[t,n]=l.useState(!1),r=l.useCallback(()=>{let s=!0;return e.current+=1,e.current===1&&n(!0),()=>{s&&(s=!1,e.current=Math.max(0,e.current-1),e.current===0&&n(!1))}},[]);return[t,r]},_s=({children:e})=>{const[t,n]=wo(),[r,s]=wo(),o=!r||t,i=l.useMemo(()=>({hasWindowTitleReference:t,isTitlePending:r,isWindowNameReady:o,registerWindowTitleReference:n,registerWindowTitlePending:s}),[t,r,n,s]);return a.createElement(qp,{value:i},e)},Wn=Fa,Ua=({enabled:e,label:t})=>{const{registerWindowTitleReference:n,registerWindowTitlePending:r}=Fa(),s=e&&t.trim().length>0;return l.useLayoutEffect(()=>{if(e)return r()},[r,e]),l.useLayoutEffect(()=>{if(s)return n()},[n,s]),{enabled:s,id:s?Te.WINDOW_TITLE:void 0}},Wp=(e,t)=>{const r=(t?en(e,t):null)??jg(e)??e;r===e&&!e.hasAttribute("tabindex")&&e.setAttribute("tabindex","-1"),r.focus({focusVisible:!1})},Ba=(e,{enabled:t,ready:n,nameReady:r=!0,targetSelector:s,suppressed:o=!1})=>{const i=l.useRef(!1);l.useEffect(()=>{if(!t){i.current=!1;return}if(i.current||!e.current||o||s&&!n)return;const c=gs(e.current)!=null;if(!s&&!c&&!n)return;let u=!1;const d=()=>{u||i.current||!e.current||(i.current=!0,Wp(e.current,s))};if(r)return Re(d),()=>{u=!0};const m=setTimeout(()=>Re(d),ma);return()=>{u=!0,clearTimeout(m)}},[t,n,r,s,e,o])},Yp=(e,t)=>{const{announcementsEnabled:n}=ht(),{channelSource:r}=Me(),{isWindowNameReady:s}=Wn(),o=Ca(),i=r.channel!=null||r.error!=null;Ba(e,{enabled:n,ready:i,nameReady:s,targetSelector:t==="messageInput"?Jf:void 0,suppressed:o})},jp=()=>{var s;const{_statsEnabled:e,channelSource:t}=Me(),n=(s=t.channel)==null?void 0:s.url,r=l.useCallback(o=>{const i=()=>{o(Lr()?"backgrounded":"foregrounded")};return document.addEventListener("visibilitychange",i),()=>document.removeEventListener("visibilitychange",i)},[]);cf({channelUrl:n,enabled:e,isInitiallyBackgrounded:Lr,isForegrounded:ng,subscribeToForegroundState:r})},Xp=e=>Ve(e)||nn(e);function Zp(e,t){return e.filter(n=>Ae.isWelcomeMessage(n,t))}const Ha=(e,{previewWelcomeMessages:t,aiAgentUserId:n})=>e.filter(r=>t.length>0?!Ae.isWelcomeMessage(r,n):!0),Jp=[],Ga=()=>{var p,C,E,_,A,y;const{agentPreviewConfigs:e={},aiAgentId:t}=ge(),{aiAgentInfo:n,userSession:r}=De(),{channelSource:s,messageSource:o,state:{input:i,streamAnimation:c}}=Me(),u=e.welcomeMessages??Jp,d=l.useMemo(()=>Ha(o.messages,{previewWelcomeMessages:u,aiAgentUserId:t}),[t,o.messages,u]),m=dt(s.channel),h=(C=(p=Mi(s.channel,r.userId))==null?void 0:p.nickname)==null?void 0:C.trim(),f=m?(_=(E=s.channel)==null?void 0:E.name)==null?void 0:_.trim():(A=n==null?void 0:n.nickname)==null?void 0:A.trim(),g=h||f||void 0;return{initialized:o.initialized,channelUrl:(y=s.channel)==null?void 0:y.url,agentName:g,isClosed:$e(s.channel),isHandedOff:m,messages:d,filteredMessagesCount:d.length,hasWelcomeMessages:u.length>0,inputDisabled:i.disabled,inputDisabledBy:i.disabledBy,isStreamAnimating:c.isAnimating,currentUserId:r.userId}},Qp=(e={})=>{const{announceScreenEntry:t,announcementsEnabled:n}=ht(),{initialized:r=!1,channelUrl:s,agentName:o,isClosed:i=!1,messages:c=[],hasWelcomeMessages:u=!1}=e,d=l.useRef(null),m=l.useMemo(()=>c.some(f=>Le.isAdmin(f)&&Le.isCSAT(f)),[c]),h=c.length===0&&!u;l.useEffect(()=>{if(!n){d.current=null;return}!r||!s||d.current!==s&&(t({screen:"conversation",agentName:o,isClosed:i,hasCSAT:m,...h?{isEmpty:!0}:{}}),d.current=s)},[o,t,n,s,m,r,i,h])},eE=()=>{const e=Ga();Qp(e)},za=e=>({image:e.A11Y_RECEIVED_FILE_IMAGE,video:e.A11Y_RECEIVED_FILE_VIDEO,pdf:e.A11Y_RECEIVED_FILE_PDF,document:e.A11Y_FILE_DOCUMENT,receivedFilesImageCount:e.A11Y_RECEIVED_FILES_IMAGE_COUNT,multipleFilesCount:e.CONVERSATION_LIST__MULTIPLE_FILES_COUNT,codeBlockPlaceholder:e.A11Y_CODE_BLOCK_PLACEHOLDER}),Lo=(e,t,n=gt.format)=>{const r=ra(e,za(t)),s="sender"in e?e.sender:void 0,o=e.createdAt!=null&&e.createdAt!==0?n(e.createdAt,t.DATE_FORMAT__MESSAGE_TIMESTAMP):void 0;return{senderName:typeof(s==null?void 0:s.nickname)=="string"&&s.nickname.trim()||void 0,body:r||void 0,time:o}},tE={senderName:!0,body:!0,time:!0},nE=Object.keys(tE),rE=(e,t)=>nE.every(n=>e[n]===t[n]),Oo=2e3,No=400,Fr=e=>{const t=new Set;return"reqId"in e&&typeof e.reqId=="string"&&e.reqId.length>0&&t.add(`req:${e.reqId}`),"messageId"in e&&e.messageId>0&&t.add(`message:${String(e.messageId)}`),[...t]},Va=e=>{if(!Le.isAdmin(e)||!Le.isCSAT(e))return null;const t=Gf(e);return t?`csat:${t}`:null},sE=e=>{const t=new Set;for(const n of e){const r=Va(n);r&&t.add(r)}return t},oE=(e,t)=>{for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r&&Fr(r).some(s=>t.includes(s)))return r}},gr=(e,t)=>e.some(n=>t.includes(n)),Do=()=>typeof document>"u"?null:document.activeElement instanceof HTMLElement?document.activeElement:null,pr=e=>new Map(e.map(({key:t,sendingStatus:n})=>[t,n])),iE=()=>{const{announceStatus:e,announcementsEnabled:t}=ht(),{stringSet:n,format:r}=le(),{channelUrl:s,messages:o,isClosed:i,isHandedOff:c,agentName:u,initialized:d,inputDisabled:m,inputDisabledBy:h,isStreamAnimating:f,currentUserId:g}=Ga(),{outgoingMessageStates:p,outgoingMessageStatusSignature:C}=l.useMemo(()=>{if(!g)return{outgoingMessageStates:[],outgoingMessageStatusSignature:""};const W=o.flatMap(H=>{const G=Bf(H,g);return!G||!("sendingStatus"in H)?[]:[{key:G,sendingStatus:H.sendingStatus}]});return{outgoingMessageStates:W,outgoingMessageStatusSignature:W.map(({key:H,sendingStatus:G})=>`${H}:${G}`).join(",")}},[g,o]),E=l.useRef({isClosed:!1,isHandedOff:!1,inputDisabled:m,inputDisabledBy:h,outgoingMessageStatuses:pr(p)}),_=l.useRef({messages:o,currentUserId:g,inputDisabledBy:h,isStreamAnimating:f,stringSet:n,format:r}),A=l.useRef([]),y=l.useRef(null),T=l.useRef([]),M=l.useRef(new Set),O=l.useRef(new Set),w=l.useRef(!1),R=l.useRef(s);_.current={messages:o,currentUserId:g,inputDisabledBy:h,isStreamAnimating:f,stringSet:n,format:r};const x=()=>_.current.isStreamAnimating||_.current.inputDisabledBy==="ai_responding",$=()=>{y.current!=null&&(clearTimeout(y.current),y.current=null)},N=(W,H,G)=>{const z=G==null?void 0:G.replaceableForMs;if(W.length===0||!z)return;const ee=Date.now();T.current=[...T.current.filter(({replaceableUntil:ae})=>ae>ee),{eventKeys:W,parts:H,replaceableUntil:ee+z}]},J=()=>A.current.length>0,se=()=>{A.current=[]},Y=()=>{const[W,...H]=A.current;if(!W)return!1;A.current=H;const{eventKeys:G,parts:z,dedupeKey:ee}=W,ae=xe=>{N(G,xe,{replaceableForMs:G.length>0?Oo:void 0}),e({event:"newMessage",...xe},ee?{dedupeKey:ee}:void 0)};if(G.length===0)return ae(z),!0;const L=_.current,ve=oE(L.messages,G);if(ve){const xe=Lo(ve,L.stringSet,L.format);return ae(xe),!0}return ae(z),!0},j=()=>{for($();Y(););},P=(W=Oo)=>{$(),y.current=setTimeout(()=>{if(y.current=null,x())return;const H=Do(),[G]=A.current;if(!G)return;if(G.focusTarget!==H){A.current=[{...G,focusTarget:H},...A.current.slice(1)],P(No);return}Y()&&J()&&P(No)},W)},V=(W,H,G)=>{const z={eventKeys:H,parts:W,focusTarget:Do(),dedupeKey:G?G.dedupeKey??void 0:H[0]},ee=H.length===0?-1:A.current.findIndex(({eventKeys:ae})=>gr(ae,H));ee>=0?A.current=A.current.map((ae,L)=>L===ee?{...z,dedupeKey:G?z.dedupeKey:ae.dedupeKey}:ae):A.current=[...A.current,z],P()},q=(W,H,G)=>{if(W!=="messagesUpdated"||H.length===0)return!1;const z=Date.now(),ee=T.current.find(ae=>ae.replaceableUntil>z&&gr(ae.eventKeys,H));return ee?!rE(G,ee.parts):!1};l.useEffect(()=>{const W=R.current!==s;(!t||!d||W)&&(w.current=!1,O.current.clear(),se(),T.current=[],M.current.clear(),$(),W&&(R.current=s),!t||!d)||w.current||(w.current=!0,R.current=s,E.current={isClosed:i,isHandedOff:c,inputDisabled:m,inputDisabledBy:h,outgoingMessageStatuses:pr(p)},M.current=new Set(o.flatMap(H=>{if(!Ae.isStreaming(H))return[];const G="sender"in H?H.sender:void 0;return(G==null?void 0:G.userId)===_.current.currentUserId?[]:Fr(H)})),O.current=sE(o))},[e,t,s,d,m,i,c,C]),l.useEffect(()=>{const W=(H,G)=>{const z=_.current,ee=Fr(H),ae=Va(H);if(ae!=null){if(O.current.has(ae))return;O.current.add(ae),e({event:"csatDisplayed"});return}if(Ae.isStreaming(H)){ee.forEach(U=>{M.current.add(U)});return}const L=ee.filter(U=>M.current.has(U)),ve=G==="messagesUpdated"&&L.length>0;ve&&L.forEach(U=>{M.current.delete(U)});const xe=G==="messagesUpdated"&&A.current.some(({eventKeys:U})=>gr(U,ee)),Oe=Lo(H,z.stringSet,z.format),I=q(G,ee,Oe);if(!ve&&G!=="messagesAdded"&&!xe&&!I)return;const k=I?{dedupeKey:null}:void 0;if(ve||x()||xe){V(Oe,[...new Set([...L,...ee])],k);return}if(I){V(Oe,ee,k);return}J()&&j();const D=ee[0];e({event:"newMessage",...Oe},D?{dedupeKey:D}:void 0)};return Gn.subscribe(H=>{if(!w.current||H.channelUrl!==s||H.kind==="initialized"||H.kind==="messagesDeleted"||!zf(H.source))return;const G=_.current.currentUserId;for(const z of H.messages)z&&Hf(z,G)&&W(z,H.kind)})},[e,s]),l.useEffect(()=>{w.current&&(x()||J()&&P())},[h,f]),l.useEffect(()=>()=>{$()},[]),l.useEffect(()=>{if(!w.current)return;const W=E.current,H=W.outgoingMessageStatuses;W.outgoingMessageStatuses=pr(p),p.some(({key:z,sendingStatus:ee})=>{const ae=H.get(z);return ae!==void 0&&ae!=="failed"&&ee==="failed"})&&e({event:"sendFailed"})},[e,C]),l.useEffect(()=>{if(!w.current)return;const W=E.current;i&&!W.isClosed&&e({event:"conversationClosed"}),W.isClosed=i},[e,i]),l.useEffect(()=>{if(!w.current)return;const W=E.current;c&&!W.isHandedOff&&e({event:"agentConnected",agentName:u}),W.isHandedOff=c},[u,e,c]),l.useEffect(()=>{if(!w.current)return;const W=E.current;m&&h!=="ai_responding"&&(!W.inputDisabled||W.inputDisabledBy==="ai_responding")&&e({event:"inputDisabled"}),W.inputDisabled=m,W.inputDisabledBy=h},[e,m,h])},aE=()=>{const{channelSource:e}=Me(),t=Yi(e.channel);return!(t!=null&&t.user.userId)||!t.user.nickname?null:{userId:t.user.userId,nickname:t.user.nickname}},cE=e=>{const{announceStatus:t,announcementsEnabled:n}=ht();Vh(e??null,r=>{t({event:"typing",agentName:r})},1e4,n)},lE=()=>{const e=aE();cE(e)},te=({type:e,size:t=24,className:n,color:r})=>{const{icons:s}=Ng(),o=s[e];return a.createElement(uE,{className:n},a.createElement(o,{size:t,color:r??v.color.primary.main,flipInRtl:xg.has(e)}))},uE=b.default.span.attrs({"aria-hidden":"true"})`
|
|
91
91
|
display: inline-flex;
|
|
92
92
|
&:focus {
|
|
93
93
|
outline: none;
|
|
94
94
|
}
|
|
95
|
-
`,Mp=({visible:e,onClose:t,children:n,"aria-label":r})=>a.createElement(gt,{portalContainerId:Se.WINDOW,visible:e,onClose:t,"aria-label":r},a.createElement(Op,null,n)),wp=({onClick:e,destructive:t,icon:n,initialFocus:r,children:s})=>a.createElement(kp,{onClick:e,$destructive:t,"data-sb-initial-focus":r?"true":void 0},n&&a.createElement(Lp,null,a.createElement(ee,{type:n,size:24,color:b.themedColor.primary})),s),dt=Object.assign(Mp,{ActionItem:wp}),kp=C.default.button`all:unset;display:flex;align-items:center;gap:24px;width:100%;padding:12px 24px;cursor:pointer;color:${({$destructive:e})=>e?b.themedColor.error:b.themedColor.textHighEmphasis};${xe}`,Lp=C.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,Op=C.default.div`position:absolute;left:0;right:0;bottom:0;border-radius:12px 12px 0 0;flex-direction:column;align-items:flex-end;margin:0 auto;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,Io=40,xo=.9,Np="[data-message-listitem]",Dp='input, textarea, select, [role="textbox"], [contenteditable="true"]',$p=({event:e,list:t,isMessageAnchor:n})=>{switch(e.key){case"PageDown":return t.clientHeight*xo;case"PageUp":return t.clientHeight*-xo;case"ArrowDown":return n?Io:void 0;case"ArrowUp":return n?Io*-1:void 0;default:return}},Pp=({listRef:e,syncScrollPosition:t})=>l.useCallback(n=>{const r=e.current;if(!r||n.defaultPrevented||n.metaKey||n.altKey||n.ctrlKey)return;const s=n.target;if(!s||!r.contains(s)||s.closest(Dp))return;const o=s===r||s.matches(Np),i=$p({event:n,list:r,isMessageAnchor:o});if(i==null||i===0)return;const c=Math.max(0,r.scrollHeight-r.clientHeight),u=Math.min(c,Math.max(0,r.scrollTop+i));u!==r.scrollTop&&(n.preventDefault(),t(u))},[e,t]),Fp="[data-message-listitem]",Up=e=>Math.min(Math.max(0,e),1),Bp=e=>{const n=e.getRootNode().activeElement,r=n==null?void 0:n.closest(Fp),s=n===e||n===r;return!n||!e.contains(n)?null:s?e:n},Hp=({list:e,focusRestoreTarget:t})=>{if(!t)return;const r=e.getRootNode().activeElement,s=r===e||e.contains(r),o=t===e||e.contains(t);s&&o&&t.focus({preventScroll:!0})},Gp=({depsForResetScrollPositionToBottom:e,listRef:t,loadThreshold:n,messagesLength:r,onLoadNext:s,onLoadPrev:o,onScroll:i})=>{const c=l.useRef(!1),u=l.useRef(void 0),d=l.useRef(0),m=l.useRef(0),h=l.useRef(null),f=l.useRef(null),g=l.useRef(null);l.useLayoutEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight)},e),l.useLayoutEffect(()=>{const _=t.current;_&&(u.current==="top"&&(_.scrollTop=_.scrollHeight-m.current,Hp({list:_,focusRestoreTarget:h.current}),h.current=null),u.current==="bottom"&&(_.scrollTop=d.current),u.current=void 0)},[t,r]);const p=l.useCallback(async _=>{const A=t.current;if(!A||(i==null||i(_),m.current=A.scrollHeight-A.scrollTop,d.current=A.scrollTop,c.current))return;const y=A.clientHeight*Up(n);if(A.scrollTop<=y){c.current=!0,u.current="top",h.current=Bp(A),await o(),c.current=!1;return}if(A.scrollHeight-A.scrollTop-A.clientHeight<=y){c.current=!0,u.current="bottom",await s(),c.current=!1;return}u.current=void 0},[t,n,s,o,i]),v=l.useCallback(_=>{const A=t.current;if(!A)return;const y=g.current;if(y!=null){if(y===A.scrollTop){g.current=null;return}g.current=null}const T=f.current;if(T!=null&&T===A.scrollTop){f.current=null,g.current=A.scrollTop,p(_);return}f.current=null,p(_)},[p,t]),E=l.useCallback(_=>{const A=t.current;A&&(f.current=_,g.current=null,A.scrollTop=_,A.dispatchEvent(new Event("scroll",{bubbles:!0})))},[t]);return l.useLayoutEffect(()=>()=>{f.current=null,g.current=null},[]),{handleScroll:v,syncScrollPosition:E}},zp=l.forwardRef(function(t,n){const{messages:r,renderMessage:s,loading:o,LoadingComponent:i,error:c,ErrorComponent:u,empty:d,EmptyComponent:m,messageTopArea:h,messageBottomArea:f,overlayArea:g,onLoadPrev:p,onLoadNext:v,loadThreshold:E=.05,onScroll:_=me,depsForResetScrollPositionToBottom:A,stackDirection:y="top",bottomSpacerHeight:T=0,"aria-label":I}=t,N=l.useRef(null),O=l.useCallback(D=>{N.current=D,n&&(typeof n=="function"?n(D):n.current=D)},[n]),{handleScroll:k,syncScrollPosition:R}=Gp({depsForResetScrollPositionToBottom:A,listRef:N,loadThreshold:E,messagesLength:r.length,onLoadNext:v,onLoadPrev:p,onScroll:_}),F=Pp({listRef:N,syncScrollPosition:R});return c?a.createElement(a.Fragment,null,u):o?a.createElement(a.Fragment,null,i):a.createElement(Vp,{id:"infinite-list-container"},a.createElement(Kp,{id:"infinite-list-inner",ref:O,onScroll:k,onKeyDown:F,role:"list","aria-label":I,tabIndex:0},y==="bottom"&&a.createElement("div",{style:{flexGrow:1}}),h,d?m:r.map((D,Q)=>s({message:D,index:Q})),f,T>0&&a.createElement("div",{style:{minHeight:T}})),a.createElement(qp,{id:"infinite-list-overlay-container"},a.createElement(Wp,{id:"infinite-list-overlay"},g)))}),Vp=C.default.div`display:flex;position:relative;flex:1;overflow:hidden;`,Kp=C.default.div`display:flex;flex:1;flex-direction:column;overflow-x:hidden;overflow-y:auto;overscroll-behavior:contain;scrollbar-color:${b.themedColor.textLowEmphasis}transparent;&::-webkit-scrollbar-thumb:hover{background-color:transparent;}`,qp=C.default.div`position:absolute;top:0;bottom:0;left:0;right:0;pointer-events:none;`,Wp=C.default.div`pointer-events:auto;`,nt=({as:e,type:t,size:n=16,color:r,disabled:s,children:o,...i})=>{const c=s?b.themedColor.textDisabled:b.themedColor.textHighEmphasis;return a.createElement(Yp,{as:e,disabled:s,...i},a.createElement(ee,{type:t,size:n,color:r??c}),o)},Yp=C.default.button`all:unset;padding:4px;cursor:pointer;display:flex;align-items:center;justify-content:center;${xe}&:disabled{cursor:not-allowed;}`,Ct=({className:e,children:t,size:n=26})=>a.createElement(jp,{className:e,$size:n},t??a.createElement(ee,{type:"spinner",size:n})),jp=C.default.div`display:flex;align-items:center;justify-content:center;width:${({$size:e})=>Xe(e)};height:${({$size:e})=>Xe(e)};animation:1s infinite linear;animation-name:rotate;@keyframes rotate{from{transform:rotate(0);}to{transform:rotate(360deg);}}`,Xp=({files:e,initialIndex:t=0,onClose:n,visible:r})=>{const[s,o]=l.useState(t),[i,c]=l.useState(!1),{stringSet:u,format:d}=ie(),{config:m}=ue(),h=e.length,f=e[s],g=m.conversation.fileViewer.downloadEnabled,p=h>1,v=(f==null?void 0:f.type)||"",E=Ke(v),_=Zt(v),A=!fp(v);l.useEffect(()=>{r&&(o(t),c(!1))},[r,t]);const y=l.useCallback(()=>{s>0&&(o(I=>I-1),c(!1))},[s]),T=l.useCallback(()=>{s<h-1&&(o(I=>I+1),c(!1))},[s,h]);return l.useEffect(()=>{if(!r)return;const I=N=>{N.key==="ArrowLeft"?y():N.key==="ArrowRight"&&T()};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[r,y,T]),!r||!f?null:a.createElement(gt,{onClose:n,visible:r,portalContainerId:Se.MODAL_ROOT,"aria-label":(f==null?void 0:f.name)||u.IMAGE_VIEWER__DEFAULT_TITLE},a.createElement(Zp,null,a.createElement(Jp,null,a.createElement(Qp,null,a.createElement(e_,null,a.createElement(B,{variant:"button",maxTextLines:1,color:b.color.ondark.textHighEmphasis},f.name||u.IMAGE_VIEWER__DEFAULT_TITLE),f.timestamp&&a.createElement(B,{variant:"caption2",color:b.color.ondark.textHighEmphasis},d(new Date(f.timestamp),"h:mm a")))),a.createElement(t_,{type:"close",size:18,color:b.color.ondark.textHighEmphasis,"aria-label":u.A11Y_IMAGE_VIEWER_CLOSE,onClick:n})),a.createElement(n_,null,p&&a.createElement(Ro,{$position:"left",type:"chevron-right",size:22,color:b.color.ondark.textHighEmphasis,onClick:y,"aria-label":u.A11Y_IMAGE_VIEWER_PREVIOUS,disabled:s===0,$flipped:!0}),a.createElement(r_,{onClick:I=>I.currentTarget===I.target&&n()},E&&a.createElement(a.Fragment,null,!i&&a.createElement(s_,null,a.createElement(Ct,{size:32},a.createElement(ee,{type:"spinner",color:"textLowEmphasis",size:32}))),a.createElement(o_,{src:f.url,alt:f.name||"Image",$loaded:i,onLoad:()=>c(!0)})),_&&a.createElement(i_,{controls:!0},a.createElement("source",{src:f.url,type:v})),A&&a.createElement(a_,null,a.createElement(B,{variant:"h1",color:b.themedColor.textHighEmphasis},u.FILE_VIEWER__UNSUPPORT))),p&&a.createElement(Ro,{$position:"right",type:"chevron-right",size:22,color:b.color.ondark.textHighEmphasis,onClick:T,"aria-label":u.A11Y_IMAGE_VIEWER_NEXT,disabled:s===h-1})),a.createElement(c_,null,p&&a.createElement(B,{variant:"body2",color:b.color.ondark.textHighEmphasis},s+1,"/",h),g&&!A&&a.createElement(l_,{forwardedAs:"a",href:f.url,download:f.name||"file",type:"download",size:24,color:b.color.ondark.textHighEmphasis,"aria-label":u.A11Y_IMAGE_VIEWER_DOWNLOAD}))))},Zp=C.default.div`position:fixed;top:0;left:0;right:0;bottom:0;height:100dvh;outline:none;display:flex;flex-direction:column;background-color:${b.themedColor.bg_50_600};`,Jp=C.default.header`display:flex;align-items:center;justify-content:space-between;padding-top:calc(12px + env(safe-area-inset-top));padding-right:12px;padding-bottom:12px;padding-left:16px;min-height:56px;background-color:${b.color.overlay.dark};`,Qp=C.default.div`flex:1;min-width:0;padding-right:8px;`,e_=C.default.div`display:flex;flex-direction:column;gap:2px;`,t_=C.default(nt)`flex-shrink:0;width:28px;height:28px;border-radius:50%;`,zn=C.default.div`display:flex;align-items:center;justify-content:center;`,n_=C.default(zn)`flex:1;min-height:0;position:relative;`,r_=C.default(zn)`position:relative;width:100%;height:100%;min-width:0;min-height:0;`,s_=C.default(zn)`position:absolute;inset:0;pointer-events:none;`,o_=C.default.img`max-width:100%;max-height:100%;object-fit:contain;user-select:none;-webkit-user-drag:none;opacity:${e=>e.$loaded?1:0};transition:opacity 0.3s ease;`,i_=C.default.video`max-width:100%;max-height:100%;object-fit:contain;`,a_=C.default(zn)`flex-direction:column;gap:16px;`,Ro=C.default(nt)`position:absolute;${e=>e.$position==="left"?"left: 12px;":"right: 12px;"}top:50%;z-index:1;width:38px;height:38px;transform:translateY(-50%) ${e=>e.$flipped?"scaleX(-1)":""};border-radius:50%;background-color:${b.color.overlay.dark};&:disabled{opacity:0.3;}`,c_=C.default.footer`position:relative;display:flex;align-items:center;justify-content:center;padding-top:16px;padding-right:16px;padding-bottom:calc(16px + env(safe-area-inset-bottom));padding-left:16px;min-height:56px;background-color:${b.color.overlay.dark};`,l_=C.default(nt)`position:absolute;right:16px;top:50%;transform:translateY(-50%);padding:0;width:24px;height:24px;`,u_=.75,Oa=6,d_=Oa*2;let Lr=null;typeof Intl<"u"&&"Segmenter"in Intl&&(Lr=new Intl.Segmenter(void 0,{granularity:"grapheme"}));const m_=e=>Lr?Array.from(Lr.segment(e),t=>t.segment):[...e],h_=e=>{const t=Math.floor(e.length*u_),n=Math.max(0,e.length-Oa);return Math.max(t,n)},Mo=(e,t="")=>{if(e.length<d_)return{start:e+t,end:""};const n=m_(e),r=h_(n);return{start:n.slice(0,r).join(""),end:n.slice(r).join("")+t}},f_=e=>{const t=e.normalize("NFC").trim(),n=t.lastIndexOf(".");if(!(n>0&&n<t.length-1))return Mo(t);const s=t.slice(0,n),o=t.slice(n);return Mo(s,o)},Na=({children:e,...t})=>{const{start:n,end:r}=l.useMemo(()=>f_(e),[e]);return r?a.createElement(g_,null,a.createElement(p_,{...t},n),a.createElement(__,{...t},r)):a.createElement(B,{...t},n)},g_=C.default.span`display:flex;width:100%;min-width:0;overflow:hidden;direction:inherit;`,p_=C.default(B)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex-shrink:1;min-width:0;`,__=C.default(B)`flex-shrink:0;white-space:nowrap;`,ds=({name:e,mimeType:t,type:n="FILE",iconColor:r,iconBackgroundColor:s,onClick:o,selected:i})=>{const{colors:c}=U.useTheme(),{conversation:u}=ae(),d=o?u.file.buttonLikePreview({name:e,mimeType:t,selected:i,onActivate:o}):u.file.preview({name:e,mimeType:t,selected:i});return a.createElement(E_,{...d.props,$clickable:!!o},a.createElement(b_,{$bgColor:s??c.base.primary},a.createElement(ee,{type:"file-document",size:24,color:r??c.base.primaryContrastContent})),a.createElement(v_,null,a.createElement(Na,{variant:"button",color:b.themedColor.textHighEmphasis},e),a.createElement(B,{color:b.themedColor.textMidEmphasis,variant:"caption3"},n)),d.descriptionNode)},E_=C.default.div`border:none;border-radius:12px;gap:8px;width:${se.BODY_MAX_WIDTH}px;height:64px;display:flex;align-items:center;padding:12px;box-sizing:border-box;border:1px solid ${b.themedColor.textDisabled};background-color:${b.themedColor.bg_50_600};${({$clickable:e})=>e&&C_}`,C_=U.css`cursor:pointer;${xe}&:hover{background-color:${b.themedColor.bg_100_500};}`,b_=C.default.div`border-radius:8px;width:40px;height:40px;display:flex;align-items:center;justify-content:center;background-color:${({$bgColor:e})=>e};`,v_=C.default.div`display:flex;flex:1;flex-direction:column;gap:4px;min-width:0;`;function S_({file:e,children:t,onClickFile:n}){const r=n?()=>n(e):void 0;return a.createElement(y_,null,a.createElement(ds,{name:e.name,mimeType:e.type,type:Ur(e.name,e.type),onClick:r}),t)}const y_=C.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${se.GAP_GROUPED}px;`,We=`${Ue}-incoming-msg`,wo=`${Ue}-marked-text`,A_="masked-text";function T_({file:e,onClickMedia:t,onClickMediaFiles:n,children:r}){const{conversation:s}=ae(),o=e.type.startsWith("image"),i=(()=>{if(n)return()=>n({files:[{url:e.url,type:e.type,name:e.name}],index:0});if(t)return()=>t(e)})(),c=i?s.file.buttonLikePreview({name:e.name,mimeType:e.type,onActivate:i}):s.file.preview({name:e.name,mimeType:e.type}),u=()=>o?a.createElement(R_,{src:e.url,alt:"image-message"}):e.type.startsWith("video")?a.createElement(M_,{controls:!0},a.createElement("source",{src:e.url}),a.createElement("track",{kind:"captions"})):null;if(u){const d={id:`${We}-media-body`,...c.props};return a.createElement(I_,null,a.createElement(x_,{...d},u(),c.descriptionNode),r)}return null}const I_=C.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${se.GAP_GROUPED}px;`,x_=C.default.div`width:${se.BODY_MAX_WIDTH}px;height:160px;border-radius:12px;overflow:hidden;cursor:pointer;${ne.light`
|
|
96
|
-
background-color: ${
|
|
95
|
+
`,dE=({visible:e,onClose:t,children:n,"aria-label":r})=>a.createElement(St,{portalContainerId:Te.WINDOW,visible:e,onClose:t,"aria-label":r},a.createElement(gE,null,n)),mE=({onClick:e,destructive:t,icon:n,initialFocus:r,children:s})=>a.createElement(hE,{onClick:e,$destructive:t,"data-sb-initial-focus":r?"true":void 0},n&&a.createElement(fE,null,a.createElement(te,{type:n,size:24,color:v.themedColor.primary})),s),pt=Object.assign(dE,{ActionItem:mE}),hE=b.default.button`all:unset;display:flex;align-items:center;gap:24px;width:100%;padding:12px 24px;cursor:pointer;color:${({$destructive:e})=>e?v.themedColor.error:v.themedColor.textHighEmphasis};${ke}`,fE=b.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,gE=b.default.div`position:absolute;left:0;right:0;bottom:0;border-radius:12px 12px 0 0;flex-direction:column;align-items:flex-end;margin:0 auto;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,Po=40,$o=.9,pE="[data-message-listitem]",EE='input, textarea, select, [role="textbox"], [contenteditable="true"]',_E=({event:e,list:t,isMessageAnchor:n})=>{switch(e.key){case"PageDown":return t.clientHeight*$o;case"PageUp":return t.clientHeight*-$o;case"ArrowDown":return n?Po:void 0;case"ArrowUp":return n?Po*-1:void 0;default:return}},CE=({listRef:e,syncScrollPosition:t})=>l.useCallback(n=>{const r=e.current;if(!r||n.defaultPrevented||n.metaKey||n.altKey||n.ctrlKey)return;const s=n.target;if(!s||!r.contains(s)||s.closest(EE))return;const o=s===r||s.matches(pE),i=_E({event:n,list:r,isMessageAnchor:o});if(i==null||i===0)return;const c=Math.max(0,r.scrollHeight-r.clientHeight),u=Math.min(c,Math.max(0,r.scrollTop+i));u!==r.scrollTop&&(n.preventDefault(),t(u))},[e,t]),SE="[data-message-listitem]",bE=e=>Math.min(Math.max(0,e),1),vE=e=>{const n=e.getRootNode().activeElement,r=n==null?void 0:n.closest(SE),s=n===e||n===r;return!n||!e.contains(n)?null:s?e:n},yE=({list:e,focusRestoreTarget:t})=>{if(!t)return;const r=e.getRootNode().activeElement,s=r===e||e.contains(r),o=t===e||e.contains(t);s&&o&&t.focus({preventScroll:!0})},AE=({depsForResetScrollPositionToBottom:e,listRef:t,loadThreshold:n,messagesLength:r,onLoadNext:s,onLoadPrev:o,onScroll:i})=>{const c=l.useRef(!1),u=l.useRef(void 0),d=l.useRef(0),m=l.useRef(0),h=l.useRef(null),f=l.useRef(null),g=l.useRef(null);l.useLayoutEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight)},e),l.useLayoutEffect(()=>{const _=t.current;_&&(u.current==="top"&&(_.scrollTop=_.scrollHeight-m.current,yE({list:_,focusRestoreTarget:h.current}),h.current=null),u.current==="bottom"&&(_.scrollTop=d.current),u.current=void 0)},[t,r]);const p=l.useCallback(async _=>{const A=t.current;if(!A||(i==null||i(_),m.current=A.scrollHeight-A.scrollTop,d.current=A.scrollTop,c.current))return;const y=A.clientHeight*bE(n);if(A.scrollTop<=y){c.current=!0,u.current="top",h.current=vE(A),await o(),c.current=!1;return}if(A.scrollHeight-A.scrollTop-A.clientHeight<=y){c.current=!0,u.current="bottom",await s(),c.current=!1;return}u.current=void 0},[t,n,s,o,i]),C=l.useCallback(_=>{const A=t.current;if(!A)return;const y=g.current;if(y!=null){if(y===A.scrollTop){g.current=null;return}g.current=null}const T=f.current;if(T!=null&&T===A.scrollTop){f.current=null,g.current=A.scrollTop,p(_);return}f.current=null,p(_)},[p,t]),E=l.useCallback(_=>{const A=t.current;A&&(f.current=_,g.current=null,A.scrollTop=_,A.dispatchEvent(new Event("scroll",{bubbles:!0})))},[t]);return l.useLayoutEffect(()=>()=>{f.current=null,g.current=null},[]),{handleScroll:C,syncScrollPosition:E}},TE=l.forwardRef(function(t,n){const{messages:r,renderMessage:s,loading:o,LoadingComponent:i,error:c,ErrorComponent:u,empty:d,EmptyComponent:m,messageTopArea:h,messageBottomArea:f,overlayArea:g,onLoadPrev:p,onLoadNext:C,loadThreshold:E=.05,onScroll:_=Ee,depsForResetScrollPositionToBottom:A,stackDirection:y="top",bottomSpacerHeight:T=0,"aria-label":M}=t,O=l.useRef(null),w=l.useCallback(N=>{O.current=N,n&&(typeof n=="function"?n(N):n.current=N)},[n]),{handleScroll:R,syncScrollPosition:x}=AE({depsForResetScrollPositionToBottom:A,listRef:O,loadThreshold:E,messagesLength:r.length,onLoadNext:C,onLoadPrev:p,onScroll:_}),$=CE({listRef:O,syncScrollPosition:x});return c?a.createElement(a.Fragment,null,u):o?a.createElement(a.Fragment,null,i):a.createElement(IE,{id:"infinite-list-container"},a.createElement(xE,{id:"infinite-list-inner",ref:w,onScroll:R,onKeyDown:$,role:"list","aria-label":M,tabIndex:0},y==="bottom"&&a.createElement("div",{style:{flexGrow:1}}),h,d?m:r.map((N,J)=>s({message:N,index:J})),f,T>0&&a.createElement("div",{style:{minHeight:T}})),a.createElement(ME,{id:"infinite-list-overlay-container"},a.createElement(RE,{id:"infinite-list-overlay"},g)))}),IE=b.default.div`display:flex;position:relative;flex:1;overflow:hidden;`,xE=b.default.div`display:flex;flex:1;flex-direction:column;overflow-x:hidden;overflow-y:auto;overscroll-behavior:contain;scrollbar-color:${v.themedColor.textLowEmphasis}transparent;&::-webkit-scrollbar-thumb:hover{background-color:transparent;}`,ME=b.default.div`position:absolute;top:0;bottom:0;left:0;right:0;pointer-events:none;`,RE=b.default.div`pointer-events:auto;`,ot=({as:e,type:t,size:n=16,color:r,disabled:s,children:o,...i})=>{const c=s?v.themedColor.textDisabled:v.themedColor.textHighEmphasis;return a.createElement(kE,{as:e,disabled:s,...i},a.createElement(te,{type:t,size:n,color:r??c}),o)},kE=b.default.button`all:unset;padding:4px;cursor:pointer;display:flex;align-items:center;justify-content:center;${ke}&:disabled{cursor:not-allowed;}`,It=({className:e,children:t,size:n=26})=>a.createElement(wE,{className:e,$size:n},t??a.createElement(te,{type:"spinner",size:n})),wE=b.default.div`display:flex;align-items:center;justify-content:center;width:${({$size:e})=>nt(e)};height:${({$size:e})=>nt(e)};animation:1s infinite linear;animation-name:rotate;@keyframes rotate{from{transform:rotate(0);}to{transform:rotate(360deg);}}`,LE=({files:e,initialIndex:t=0,onClose:n,visible:r})=>{const[s,o]=l.useState(t),[i,c]=l.useState(!1),{stringSet:u,format:d}=le(),{config:m}=ge(),h=e.length,f=e[s],g=m.conversation.fileViewer.downloadEnabled,p=h>1,C=(f==null?void 0:f.type)||"",E=Ve(C),_=nn(C),A=!Xp(C);l.useEffect(()=>{r&&(o(t),c(!1))},[r,t]);const y=l.useCallback(()=>{s>0&&(o(M=>M-1),c(!1))},[s]),T=l.useCallback(()=>{s<h-1&&(o(M=>M+1),c(!1))},[s,h]);return l.useEffect(()=>{if(!r)return;const M=O=>{O.key==="ArrowLeft"?y():O.key==="ArrowRight"&&T()};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[r,y,T]),!r||!f?null:a.createElement(St,{onClose:n,visible:r,portalContainerId:Te.MODAL_ROOT,"aria-label":(f==null?void 0:f.name)||u.IMAGE_VIEWER__DEFAULT_TITLE},a.createElement(OE,null,a.createElement(NE,null,a.createElement(DE,null,a.createElement(PE,null,a.createElement(B,{variant:"button",maxTextLines:1,color:v.color.ondark.textHighEmphasis},f.name||u.IMAGE_VIEWER__DEFAULT_TITLE),f.timestamp&&a.createElement(B,{variant:"caption2",color:v.color.ondark.textHighEmphasis},d(new Date(f.timestamp),"h:mm a")))),a.createElement($E,{type:"close",size:18,color:v.color.ondark.textHighEmphasis,"aria-label":u.A11Y_IMAGE_VIEWER_CLOSE,onClick:n})),a.createElement(FE,null,p&&a.createElement(Fo,{$position:"left",type:"chevron-right",size:22,color:v.color.ondark.textHighEmphasis,onClick:y,"aria-label":u.A11Y_IMAGE_VIEWER_PREVIOUS,disabled:s===0,$flipped:!0}),a.createElement(UE,{onClick:M=>M.currentTarget===M.target&&n()},E&&a.createElement(a.Fragment,null,!i&&a.createElement(BE,null,a.createElement(It,{size:32},a.createElement(te,{type:"spinner",color:"textLowEmphasis",size:32}))),a.createElement(HE,{src:f.url,alt:f.name||"Image",$loaded:i,onLoad:()=>c(!0)})),_&&a.createElement(GE,{controls:!0},a.createElement("source",{src:f.url,type:C})),A&&a.createElement(zE,null,a.createElement(B,{variant:"h1",color:v.themedColor.textHighEmphasis},u.FILE_VIEWER__UNSUPPORT))),p&&a.createElement(Fo,{$position:"right",type:"chevron-right",size:22,color:v.color.ondark.textHighEmphasis,onClick:T,"aria-label":u.A11Y_IMAGE_VIEWER_NEXT,disabled:s===h-1})),a.createElement(VE,null,p&&a.createElement(B,{variant:"body2",color:v.color.ondark.textHighEmphasis},s+1,"/",h),g&&!A&&a.createElement(KE,{forwardedAs:"a",href:f.url,download:f.name||"file",type:"download",size:24,color:v.color.ondark.textHighEmphasis,"aria-label":u.A11Y_IMAGE_VIEWER_DOWNLOAD}))))},OE=b.default.div`position:fixed;top:0;left:0;right:0;bottom:0;height:100dvh;outline:none;display:flex;flex-direction:column;background-color:${v.themedColor.bg_50_600};`,NE=b.default.header`display:flex;align-items:center;justify-content:space-between;padding-top:calc(12px + env(safe-area-inset-top));padding-right:12px;padding-bottom:12px;padding-left:16px;min-height:56px;background-color:${v.color.overlay.dark};`,DE=b.default.div`flex:1;min-width:0;padding-right:8px;`,PE=b.default.div`display:flex;flex-direction:column;gap:2px;`,$E=b.default(ot)`flex-shrink:0;width:28px;height:28px;border-radius:50%;`,Yn=b.default.div`display:flex;align-items:center;justify-content:center;`,FE=b.default(Yn)`flex:1;min-height:0;position:relative;`,UE=b.default(Yn)`position:relative;width:100%;height:100%;min-width:0;min-height:0;`,BE=b.default(Yn)`position:absolute;inset:0;pointer-events:none;`,HE=b.default.img`max-width:100%;max-height:100%;object-fit:contain;user-select:none;-webkit-user-drag:none;opacity:${e=>e.$loaded?1:0};transition:opacity 0.3s ease;`,GE=b.default.video`max-width:100%;max-height:100%;object-fit:contain;`,zE=b.default(Yn)`flex-direction:column;gap:16px;`,Fo=b.default(ot)`position:absolute;${e=>e.$position==="left"?"left: 12px;":"right: 12px;"}top:50%;z-index:1;width:38px;height:38px;transform:translateY(-50%) ${e=>e.$flipped?"scaleX(-1)":""};border-radius:50%;background-color:${v.color.overlay.dark};&:disabled{opacity:0.3;}`,VE=b.default.footer`position:relative;display:flex;align-items:center;justify-content:center;padding-top:16px;padding-right:16px;padding-bottom:calc(16px + env(safe-area-inset-bottom));padding-left:16px;min-height:56px;background-color:${v.color.overlay.dark};`,KE=b.default(ot)`position:absolute;right:16px;top:50%;transform:translateY(-50%);padding:0;width:24px;height:24px;`,qE=.75,Ka=6,WE=Ka*2;let Ur=null;typeof Intl<"u"&&"Segmenter"in Intl&&(Ur=new Intl.Segmenter(void 0,{granularity:"grapheme"}));const YE=e=>Ur?Array.from(Ur.segment(e),t=>t.segment):[...e],jE=e=>{const t=Math.floor(e.length*qE),n=Math.max(0,e.length-Ka);return Math.max(t,n)},Uo=(e,t="")=>{if(e.length<WE)return{start:e+t,end:""};const n=YE(e),r=jE(n);return{start:n.slice(0,r).join(""),end:n.slice(r).join("")+t}},XE=e=>{const t=e.normalize("NFC").trim(),n=t.lastIndexOf(".");if(!(n>0&&n<t.length-1))return Uo(t);const s=t.slice(0,n),o=t.slice(n);return Uo(s,o)},qa=({children:e,...t})=>{const{start:n,end:r}=l.useMemo(()=>XE(e),[e]);return r?a.createElement(ZE,null,a.createElement(JE,{...t},n),a.createElement(QE,{...t},r)):a.createElement(B,{...t},n)},ZE=b.default.span`display:flex;width:100%;min-width:0;overflow:hidden;direction:inherit;`,JE=b.default(B)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex-shrink:1;min-width:0;`,QE=b.default(B)`flex-shrink:0;white-space:nowrap;`,Cs=({name:e,mimeType:t,type:n="FILE",iconColor:r,iconBackgroundColor:s,onClick:o,selected:i})=>{const{colors:c}=F.useTheme(),{conversation:u}=ue(),d=o?u.file.buttonLikePreview({name:e,mimeType:t,selected:i,onActivate:o}):u.file.preview({name:e,mimeType:t,selected:i});return a.createElement(e_,{...d.props,$clickable:!!o},a.createElement(n_,{$bgColor:s??c.base.primary},a.createElement(te,{type:"file-document",size:24,color:r??c.base.primaryContrastContent})),a.createElement(r_,null,a.createElement(qa,{variant:"button",color:v.themedColor.textHighEmphasis},e),a.createElement(B,{color:v.themedColor.textMidEmphasis,variant:"caption3"},n)),d.descriptionNode)},e_=b.default.div`border:none;border-radius:12px;gap:8px;width:${re.BODY_MAX_WIDTH}px;height:64px;display:flex;align-items:center;padding:12px;box-sizing:border-box;border:1px solid ${v.themedColor.textDisabled};background-color:${v.themedColor.bg_50_600};${({$clickable:e})=>e&&t_}`,t_=F.css`cursor:pointer;${ke}&:hover{background-color:${v.themedColor.bg_100_500};}`,n_=b.default.div`border-radius:8px;width:40px;height:40px;display:flex;align-items:center;justify-content:center;background-color:${({$bgColor:e})=>e};`,r_=b.default.div`display:flex;flex:1;flex-direction:column;gap:4px;min-width:0;`;function s_({file:e,children:t,onClickFile:n}){const r=n?()=>n(e):void 0;return a.createElement(o_,null,a.createElement(Cs,{name:e.name,mimeType:e.type,type:qr(e.name,e.type),onClick:r}),t)}const o_=b.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${re.GAP_GROUPED}px;`,Ke=`${ze}-incoming-msg`,Bo=`${ze}-marked-text`,i_="masked-text";function a_({file:e,onClickMedia:t,onClickMediaFiles:n,children:r}){const{conversation:s}=ue(),o=e.type.startsWith("image"),i=(()=>{if(n)return()=>n({files:[{url:e.url,type:e.type,name:e.name}],index:0});if(t)return()=>t(e)})(),c=i?s.file.buttonLikePreview({name:e.name,mimeType:e.type,onActivate:i}):s.file.preview({name:e.name,mimeType:e.type}),u=()=>o?a.createElement(u_,{src:e.url,alt:"image-message"}):e.type.startsWith("video")?a.createElement(d_,{controls:!0},a.createElement("source",{src:e.url}),a.createElement("track",{kind:"captions"})):null;if(u){const d={id:`${Ke}-media-body`,...c.props};return a.createElement(c_,null,a.createElement(l_,{...d},u(),c.descriptionNode),r)}return null}const c_=b.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${re.GAP_GROUPED}px;`,l_=b.default.div`width:${re.BODY_MAX_WIDTH}px;height:160px;border-radius:12px;overflow:hidden;cursor:pointer;${ne.light`
|
|
96
|
+
background-color: ${v.color.background100};
|
|
97
97
|
`}
|
|
98
98
|
${ne.dark`
|
|
99
|
-
background-color: ${
|
|
99
|
+
background-color: ${v.color.background400};
|
|
100
100
|
`}
|
|
101
|
-
`,
|
|
102
|
-
background-color: ${
|
|
101
|
+
`,u_=b.default.img`width:100%;height:100%;object-fit:cover;`,d_=b.default.video`width:100%;height:100%;object-fit:cover;`,m_=e=>e.startsWith("blob:"),Wa=({images:e,isPending:t=!1,onClickImage:n})=>{const{conversation:r}=ue(),s=e.length;if(s===0)return null;const o=tm(s),i=!!n&&!t;return a.createElement(f_,{$width:re.BODY_MAX_WIDTH,$columns:o},e.map((c,u)=>{const{columnSpan:d}=nm({index:u,itemCount:s}),m=c.name||"",h=()=>{t||n==null||n(u)},f=c.type??"image/*",g=i?r.file.buttonLikePreview({name:m,mimeType:f,onActivate:h},u):r.file.preview({name:m,mimeType:f});return a.createElement(g_,{key:c.url,$clickable:i,$itemSpan:d,$isPending:t,...g.props},a.createElement(h_,{src:c.url,alt:c.name||""}),t&&a.createElement(p_,null),g.descriptionNode)}))},h_=({src:e,alt:t})=>{const[n,r]=l.useState(()=>m_(e)),[s,o]=l.useState(!1);return a.createElement(a.Fragment,null,!n&&!s&&a.createElement(E_,null,a.createElement(It,{size:20},a.createElement(te,{type:"spinner",color:"textLowEmphasis",size:20}))),s&&a.createElement(__,null,a.createElement(te,{type:"photo",color:"textLowEmphasis",size:24})),!s&&a.createElement(C_,{src:e,alt:t,$loaded:n,onLoad:()=>r(!0),onError:()=>o(!0)}))},f_=b.default.div`display:grid;grid-template-columns:repeat(${({$columns:e})=>e},1fr);width:${({$width:e})=>e}px;gap:2px;border-radius:16px;overflow:hidden;`,g_=b.default.div`position:relative;width:100%;aspect-ratio:1;overflow:hidden;cursor:${e=>e.$clickable?"pointer":"default"};${ne.light`
|
|
102
|
+
background-color: ${v.color.background100};
|
|
103
103
|
`}
|
|
104
104
|
${ne.dark`
|
|
105
|
-
background-color: ${
|
|
105
|
+
background-color: ${v.color.background400};
|
|
106
106
|
`}
|
|
107
107
|
${e=>e.$itemSpan&&e.$itemSpan>1&&`
|
|
108
108
|
grid-column: span ${e.$itemSpan};
|
|
@@ -110,7 +110,7 @@ $2
|
|
|
110
110
|
`}
|
|
111
111
|
|
|
112
112
|
&:focus-visible {
|
|
113
|
-
outline: 2px solid ${
|
|
113
|
+
outline: 2px solid ${v.color.primary.main};
|
|
114
114
|
outline-offset: -2px;
|
|
115
115
|
}
|
|
116
116
|
|
|
@@ -121,19 +121,19 @@ $2
|
|
|
121
121
|
}
|
|
122
122
|
`}
|
|
123
123
|
}
|
|
124
|
-
`,
|
|
125
|
-
background-color: ${
|
|
124
|
+
`,p_=b.default.div`position:absolute;top:0;left:0;width:100%;height:100%;background-color:${v.color.overlay.dark};pointer-events:none;`,Ya=b.default.div`display:flex;align-items:center;justify-content:center;`,E_=b.default(Ya)`position:absolute;inset:0;`,__=b.default(Ya)`position:absolute;inset:0;${ne.light`
|
|
125
|
+
background-color: ${v.color.background200};
|
|
126
126
|
`}
|
|
127
127
|
${ne.dark`
|
|
128
|
-
background-color: ${
|
|
128
|
+
background-color: ${v.color.background500};
|
|
129
129
|
`}
|
|
130
|
-
|
|
130
|
+
`,C_=b.default.img`position:absolute;inset:0;width:100%;height:100%;object-fit:cover;opacity:${({$loaded:e})=>e?1:0};transition:opacity 0.3s ease;`,S_=({files:e,children:t,onClickMedia:n,onClickMediaFiles:r})=>{const s=o=>{const i=e[o];i&&(r?r({files:e,index:o}):n&&n({url:i.url,type:i.type||"image/*"}))};return a.createElement(b_,null,a.createElement(Wa,{images:e,onClickImage:s}),t)},b_=b.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${re.GAP_GROUPED}px;`,v_=l.lazy(async()=>({default:(await Promise.resolve().then(()=>require("./cjs/TEfZbcKQ.cjs"))).MarkdownText})),Ho=typeof __SBA_USE_SYNTAX_HIGHLIGHT__>"u"||__SBA_USE_SYNTAX_HIGHLIGHT__?l.lazy(async()=>({default:(await Promise.resolve().then(()=>require("./cjs/DlvEEpWX.cjs"))).CodeBlock})):null;function y_(e){var s,o;const t=e.maxBodyWidth??re.BODY_MAX_WIDTH,n=l.useMemo(()=>ol(e.message),[e.message]),r={id:`${Ke}-text-body`,$maxWidth:t,$color:(s=e.customStyle)==null?void 0:s.bubbleContentColor,$bgColor:(o=e.customStyle)==null?void 0:o.bubbleBackgroundColor};return n.length===0?e.children?a.createElement(Go,{...r},e.children):null:a.createElement(Go,{...r},n.map((i,c)=>i.type==="text"?a.createElement(zo,{key:c,variant:"body3"},a.createElement(yt,{fallback:i.value},a.createElement(v_,{onClickImage:u=>{var m;const d={url:u,type:"image/*"};e.onClickMediaFiles?e.onClickMediaFiles({files:[d],index:0}):(m=e.onClickMedia)==null||m.call(e,d)},onClickLink:e.onClickLink},i.value))):i.type==="code"?Ho?a.createElement(yt,{key:c,fallback:a.createElement(zo,{variant:"body3"},i.value)},a.createElement(Ho,{code:i.value,language:i.language})):a.createElement(A_,{key:c},a.createElement("code",null,i.value)):null),e.children)}const Go=b.default.div`display:flex;flex-direction:column;min-width:0;max-width:min(${({$maxWidth:e})=>e}px,100%);border-radius:12px;overflow:hidden;padding:12px 0;${({theme:e,$color:t,$bgColor:n})=>F.css`
|
|
131
131
|
color: ${t||e.colors.messageIncoming.text};
|
|
132
132
|
background-color: ${n||e.colors.messageIncoming.background};
|
|
133
133
|
`}
|
|
134
134
|
transition: max-width 0.3s;
|
|
135
135
|
overflow-wrap: break-word;
|
|
136
|
-
`,
|
|
136
|
+
`,zo=b.default(B)`align-items:flex-start;line-height:140%;white-space:pre-wrap;padding:0 12px;`,A_=b.default.pre`margin:0;padding:1em;overflow-x:auto;white-space:pre;font-family:monospace;font-size:13px;line-height:1.5;color:#d4d4d4;background:#1e1e1e;border-radius:4px;`;function ja({id:e,src:t,size:n=56,onClick:r,onImageError:s,onImageLoad:o,style:i,backgroundColor:c,...u}){const[d,m]=l.useState();return a.createElement(T_,{id:e,tabIndex:r?0:void 0,onClick:r,$size:nt(n),$backgroundColor:c,style:i,...u},t&&t!==d?a.createElement(I_,{src:t,alt:"",onLoad:()=>o==null?void 0:o(t),onError:()=>{m(t),s==null||s(t)}}):a.createElement(te,{type:"user",size:n}))}const T_=b.default.div`border-radius:50%;display:inline-block;overflow:hidden;position:relative;flex-shrink:0;height:${e=>e.$size};width:${e=>e.$size};background-color:${e=>e.$backgroundColor??v.themedColor.bg_100_500};&:focus{outline:none;}${ke}`,I_=b.default.img`object-fit:cover;width:100%;height:100%;position:absolute;`,x_=({sender:e,isBotMessage:t})=>{const n=`${Ke}-sender-avatar`,[r,s]=l.useState();return t&&(!e.profileUrl||e.profileUrl===r)?a.createElement(M_,{id:n},a.createElement(te,{type:"delight",size:"100%"})):a.createElement(ja,{id:n,size:re.AVATAR_SIZE,src:e.profileUrl,onImageError:t?s:void 0})},M_=b.default.div`flex-shrink:0;width:${re.AVATAR_SIZE}px;height:${re.AVATAR_SIZE}px;box-sizing:border-box;padding:4px;border-radius:50%;display:flex;justify-content:center;align-items:center;background-color:${({theme:e})=>e.colors.base.primary}!important;ellipse,path{fill:${({theme:e})=>e.colors.base.primaryContrastContent}!important;}}`,R_=({sender:e})=>a.createElement(k_,{id:`${Ke}-sender-name`,variant:"caption1",color:v.themedColor.textMidEmphasis},e.nickname),k_=b.default(B)`text-align:start;width:100%;box-sizing:border-box;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding-block:5px;padding-inline:0 7px;`,w_=({createdAt:e})=>{const{stringSet:t,format:n}=le();return e?a.createElement(B,{id:`${Ke}-sent-time`,variant:"caption4",color:v.themedColor.textLowEmphasis},n(e,t.DATE_FORMAT__MESSAGE_TIMESTAMP)):null},Xa="(prefers-reduced-motion: reduce)",L_=()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(Xa).matches,Za=()=>{const[e,t]=l.useState(L_);return l.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const n=window.matchMedia(Xa);t(n.matches);const r=s=>{t(s.matches)};return typeof n.addEventListener=="function"?(n.addEventListener("change",r),()=>{n.removeEventListener("change",r)}):(n.addListener(r),()=>{n.removeListener(r)})},[]),e},O_=({thinkingMessage:e,customStyle:t})=>{const n=Za();return e?a.createElement(P_,{$prefersReducedMotion:n},a.createElement($_,null,e),!n&&a.createElement(F_,null)):a.createElement(N_,{$bgColor:t==null?void 0:t.bubbleBackgroundColor},[0,1,2].map(r=>a.createElement(D_,{key:r,$color:t==null?void 0:t.bubbleContentColor,$prefersReducedMotion:n})))},N_=b.default.div`align-items:center;border-radius:16px;display:flex;gap:6px;height:26px;justify-content:center;padding:0 12px;background-color:${({theme:e,$bgColor:t})=>t||e.colors.messageIncoming.background};`,D_=b.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;}`,P_=b.default.div.attrs({id:`${Ke}-typing-indicator`})`
|
|
137
137
|
position: relative;
|
|
138
138
|
overflow: hidden;
|
|
139
139
|
animation: ${({$prefersReducedMotion:e})=>e?"none":"fadeIn 0.4s ease-in-out"};
|
|
@@ -145,12 +145,12 @@ $2
|
|
|
145
145
|
opacity: 1;
|
|
146
146
|
}
|
|
147
147
|
}
|
|
148
|
-
|
|
148
|
+
`,$_=b.default(B).attrs({variant:"body3"})`
|
|
149
149
|
white-space: pre-wrap;
|
|
150
150
|
word-break: break-word;
|
|
151
|
-
color: ${
|
|
152
|
-
`,
|
|
153
|
-
`,
|
|
151
|
+
color: ${v.themedColor.textHighEmphasis};
|
|
152
|
+
`,F_=b.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=Ks(e.colors.base.background,.5),n=Ks(e.colors.base.background,0);return`linear-gradient(90deg, ${n} 0%, ${t} 30%, ${t} 60%, ${n} 100%)`}};
|
|
153
|
+
`,U_=({extendedMessagePayload:e,onClickCTA:t=({url:n})=>ps(n)})=>{const n=e==null?void 0:e.cta_button;if(!n)return null;const r=()=>t(n);return a.createElement(B_,{id:`${Ke}-ext-cta-button`,onClick:r},a.createElement(H_,{variant:"button"},n.label))},B_=b.default.button.attrs({type:"button"})`
|
|
154
154
|
all: unset;
|
|
155
155
|
display: flex;
|
|
156
156
|
width: 100%;
|
|
@@ -160,14 +160,14 @@ $2
|
|
|
160
160
|
cursor: pointer;
|
|
161
161
|
border-radius: 6px;
|
|
162
162
|
padding: 8px;
|
|
163
|
-
color: ${
|
|
164
|
-
background-color: ${
|
|
163
|
+
color: ${v.themedColor.textHighEmphasis};
|
|
164
|
+
background-color: ${v.color.background50};
|
|
165
165
|
${ne.dark`
|
|
166
|
-
background-color: ${
|
|
166
|
+
background-color: ${v.color.ondark.textDisabled};
|
|
167
167
|
`}
|
|
168
168
|
|
|
169
|
-
${
|
|
170
|
-
`,
|
|
169
|
+
${ke}
|
|
170
|
+
`,H_=b.default(B)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,G_=e=>a.createElement(a.Fragment,null),z_=({extendedMessagePayload:e,onClickCitation:t=n=>ps(n.link)})=>{const{stringSet:n}=le(),{theme:r}=zn(),s=e==null?void 0:e.citations;return!s||s.length===0?null:a.createElement(V_,{id:`${Ke}-ext-citation`},a.createElement(K_,{variant:"caption1",color:r.colors.messageIncoming.text},n.CITATION_SOURCE_TITLE),a.createElement(q_,null,s.map((o,i)=>a.createElement(Y_,{key:`${o.embedding_id}-${i}`,onClick:()=>t(o)},a.createElement(te,{type:"source",size:16,color:r.colors.messageIncoming.text}),a.createElement(W_,{variant:"body3",color:r.colors.messageIncoming.text},o.title)))))},V_=b.default.div`display:flex;flex-direction:column;gap:8px;border-radius:8px;padding:8px 12px 6px;`,K_=b.default(B)`opacity:0.5;`,q_=b.default.div`display:flex;flex-direction:column;gap:8px;`,W_=b.default(B)`text-decoration:underline;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,Y_=b.default.button.attrs({type:"button"})`
|
|
171
171
|
background: none;
|
|
172
172
|
border: none;
|
|
173
173
|
padding: 0;
|
|
@@ -182,127 +182,127 @@ $2
|
|
|
182
182
|
&:hover {
|
|
183
183
|
opacity: 0.5;
|
|
184
184
|
}
|
|
185
|
-
`,
|
|
186
|
-
color: ${
|
|
187
|
-
border-color: ${
|
|
185
|
+
`,j_=e=>a.createElement(a.Fragment,null),Br=e=>`${e}-filled`,X_=e=>e==="good"?Ce.AIAgentMessageFeedbackRating.GOOD:Ce.AIAgentMessageFeedbackRating.BAD,Ss=F.css`&:hover{opacity:0.8;}&:active{opacity:0.6;}`,Sn={good:{onlight:v.color.secondary.dark,ondark:v.color.secondary.light},bad:{onlight:v.color.error.dark,ondark:v.color.error.light}},Z_={good:v.themedColor.secondary,bad:v.themedColor.error},Ja=e=>F.css`color:${Sn[e].onlight};border-color:${Sn[e].onlight};${ne.dark`
|
|
186
|
+
color: ${Sn[e].ondark};
|
|
187
|
+
border-color: ${Sn[e].ondark};
|
|
188
188
|
`}
|
|
189
|
-
`,
|
|
190
|
-
outline: 2px solid ${
|
|
189
|
+
`,J_=({visible:e,onClose:t,isEdit:n,initialRating:r,initialComment:s="",onSubmit:o,isCommentEnabled:i=!1})=>{const{stringSet:c}=le(),{conversation:u}=ue(),{rootElement:d}=ba(),m=Et(d),[h,f]=l.useState(r),[g,p]=l.useState(s),[C,E]=l.useState(!1),_=l.useRef(!1),A=h??r??"good",y=u.feedback;l.useLayoutEffect(()=>{e?(f(r),p(s)):(f(void 0),p(""))},[e,r,s]),l.useEffect(()=>{if(!e)return;const w=x=>{const $=x;$.metaKey||$.altKey||$.ctrlKey||(_.current=!0)},R=()=>{_.current=!1,E(!1)};return m.addEventListener("keydown",w),m.addEventListener("pointerdown",R),()=>{m.removeEventListener("keydown",w),m.removeEventListener("pointerdown",R)}},[m,e]);const T=()=>{h&&(o({rating:h,comment:g.trim()||void 0}),t())},M=()=>{t()};if(!e)return null;const O={feedback:y.container()};return a.createElement(St,{portalContainerId:Te.WINDOW,visible:e,onClose:M,"aria-label":c.FEEDBACK_TITLE},a.createElement(Q_,null,a.createElement(eC,null,a.createElement(B,{variant:"h2",color:v.themedColor.textHighEmphasis},c.FEEDBACK_TITLE)),a.createElement(tC,null,a.createElement(nC,{...O.feedback.props},["good","bad"].map(w=>{const R=h===w,x=w==="good"?c.FEEDBACK_GOOD:c.FEEDBACK_BAD,$=y.button(w,R);return a.createElement(l.Fragment,{key:w},a.createElement(rC,{type:"button",$selected:R,$rating:w,...$.props,onClick:()=>f(w),"data-sb-initial-focus":w===A?"true":void 0},a.createElement(te,{type:R?Br(w):w,size:24,color:"currentColor"}),a.createElement(B,{variant:"caption1",color:"currentColor"},x)),$.descriptionNode)}),O.feedback.descriptionNode),i&&a.createElement(sC,null,a.createElement(B,{variant:"caption3",color:v.themedColor.textHighEmphasis},c.FEEDBACK_COMMENT_LABEL),a.createElement(oC,{placeholder:c.FEEDBACK_COMMENT_PLACEHOLDER,value:g,onChange:w=>p(w.target.value),onFocus:()=>E(_.current),onBlur:()=>E(!1),maxLength:100,$focusVisible:C,"data-focus-visible":C?"true":"false"}))),a.createElement(iC,null,a.createElement(aC,{onClick:M},a.createElement(B,{variant:"button",color:v.themedColor.textHighEmphasis},c.FEEDBACK_CANCEL)),a.createElement(cC,{onClick:T,disabled:!h},a.createElement(B,{variant:"button"},n?c.FEEDBACK_SAVE:c.FEEDBACK_SUBMIT)))))},Q_=b.default.div`width:280px;background-color:${({theme:e})=>e.colors.base.modalContentBackground};border-radius:12px;overflow:hidden;`,eC=b.default.div`padding:24px;`,tC=b.default.div`padding-inline:24px;display:flex;flex-direction:column;gap:24px;`,nC=b.default.div`display:flex;gap:4px;`,rC=b.default.button`width:114px;height:64px;border-radius:12px;border:1px solid ${v.themedColor.textDisabled};box-sizing:border-box;cursor:pointer;display:flex;flex-direction:column;align-items:center;justify-content:center;padding:0;gap:0;transition:background-color 0.2s;color:${v.themedColor.textLowEmphasis};background-color:transparent;${({$selected:e,$rating:t})=>e&&Ja(t)}${Ss}`,sC=b.default.label`display:flex;flex-direction:column;gap:6px;`,oC=b.default.textarea`font-family:inherit;font-size:12px;line-height:16px;border:1px solid ${v.themedColor.textDisabled};border-radius:4px;padding:6px 12px;color:${v.themedColor.textHighEmphasis};background-color:${v.themedColor.textLowEmphasisInverse};resize:none;field-sizing:content;min-height:28px;max-height:118px;overflow-y:auto;&::placeholder{color:${v.themedColor.textLowEmphasis};}&:focus{outline:none;}${({$focusVisible:e})=>e&&F.css`
|
|
190
|
+
outline: 2px solid ${v.themedColor.primary};
|
|
191
191
|
outline-offset: 2px;
|
|
192
192
|
`}
|
|
193
|
-
`,
|
|
194
|
-
border: 1px solid ${
|
|
193
|
+
`,iC=b.default.div`padding-inline:24px;padding-block:16px;display:flex;justify-content:flex-end;gap:4px;`,Qa=b.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;`,aC=b.default(Qa)`background-color:transparent;${Ss}`,cC=b.default(Qa)`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};}`,lC=({isBotMessage:e,isConversationClosed:t,isStreaming:n,isFeedbackEnabled:r,isFeedbackCommentEnabled:s,extendedMessagePayload:o,onFeedbackUpdate:i})=>{const{stringSet:c}=le(),{conversation:u}=ue(),[d,m]=l.useState(!1),[h,f]=l.useState(!1),[g,p]=l.useState(void 0),[C,E]=l.useState(""),_=l.useRef(null),A=l.useRef(null),y=l.useRef(null),T=l.useRef(!1),M=u.feedback,O=o==null?void 0:o.feedback,w=(O==null?void 0:O.rating)??"none";if(w!=="none"?!1:!!(n||!e||!r||(o==null?void 0:o.bot_message_type)!=="generated"||t))return null;const x=P=>{P&&Re(()=>{const V=P==="good"?_.current:A.current;V==null||V.focus()})},$=({restoreTrigger:P=!0}={})=>{f(!1),P&&x(y.current)},N=P=>{w==="none"?(p(P),E(""),m(!0)):(y.current=P,f(!0))},J=()=>{i==null||i(null),$()},se=()=>{T.current=!0,$({restoreTrigger:!1}),p(O==null?void 0:O.rating),E((O==null?void 0:O.comment)??""),m(!0)},Y=P=>{T.current=!1,i==null||i(P),m(!1),x(y.current)},j=()=>{m(!1),T.current&&(T.current=!1,f(!0))};return t&&w!=="none"?a.createElement(Vo,{role:"presentation",$horizontal:!0},a.createElement(uC,null,a.createElement(te,{type:Br(w),size:12,color:Z_[w]})),(O==null?void 0:O.comment)&&a.createElement(Ko,{variant:"caption2",style:{lineHeight:"16px"}},O.comment)):a.createElement(a.Fragment,null,a.createElement(Vo,{role:"presentation"},a.createElement(dC,{role:"presentation"},["good","bad"].map(P=>{const V=w===P,q=M.button(P,V);return a.createElement(l.Fragment,{key:P},a.createElement(mC,{$selected:V,$rating:P,ref:P==="good"?_:A,...q.props,onClick:()=>N(P)},a.createElement(te,{type:V?Br(P):P,size:14,color:"currentColor"})),q.descriptionNode)})),w!=="none"&&(O==null?void 0:O.comment)&&a.createElement(Ko,{variant:"caption2"},O.comment)),a.createElement(pt,{visible:h,onClose:$,...M.optionsBottomSheet().props},a.createElement(pt.ActionItem,{onClick:se,initialFocus:!0},c.FEEDBACK_EDIT),a.createElement(pt.ActionItem,{onClick:J,destructive:!0},c.FEEDBACK_REMOVE)),a.createElement(J_,{visible:d,onClose:j,isEdit:w!=="none",initialRating:g,initialComment:C,onSubmit:Y,isCommentEnabled:s}))},Vo=b.default.div`display:flex;flex-direction:${({$horizontal:e})=>e?"row":"column"};align-items:${({$horizontal:e})=>e?"flex-start":"stretch"};gap:4px;margin-top:8px;word-break:break-word;max-width:${re.BODY_MAX_WIDTH}px;`,uC=b.default.div`padding:2px;flex-shrink:0;display:flex;align-items:center;`,dC=b.default.div`display:flex;gap:2px;`,mC=b.default.button`width:38px;height:20px;border-radius:18px;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0;transition:opacity 0.2s;box-sizing:border-box;color:${v.themedColor.textMidEmphasis};border:1px solid ${v.color.background200};background-color:transparent;${ne.dark`
|
|
194
|
+
border: 1px solid ${v.color.background400};
|
|
195
195
|
`}
|
|
196
196
|
|
|
197
|
-
${({$selected:e,$rating:t})=>e&&
|
|
197
|
+
${({$selected:e,$rating:t})=>e&&Ja(t)}
|
|
198
198
|
|
|
199
|
-
${
|
|
200
|
-
`,
|
|
201
|
-
color: ${
|
|
199
|
+
${Ss}
|
|
200
|
+
`,Ko=b.default(B)`color:${v.themedColor.textMidEmphasis};${ne.dark`
|
|
201
|
+
color: ${v.themedColor.textHighEmphasis};
|
|
202
202
|
`}
|
|
203
|
-
`,
|
|
204
|
-
background-color: ${
|
|
203
|
+
`,bs=F.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;${ke}&:disabled{cursor:not-allowed;}`,qo=b.default.button`${bs};background-color:${v.themedColor.primary};color:${v.themedColor.textHighEmphasis};&:hover:not(:disabled){opacity:0.9;}`,hC=b.default.button`${bs};color:${v.themedColor.primary};${ne.light`
|
|
204
|
+
background-color: ${v.color.background50};
|
|
205
205
|
`};
|
|
206
206
|
${ne.dark`
|
|
207
|
-
background-color: ${
|
|
207
|
+
background-color: ${v.color.background700};
|
|
208
208
|
`};
|
|
209
209
|
|
|
210
210
|
&:hover:not(:disabled) {
|
|
211
211
|
opacity: 0.9;
|
|
212
212
|
}
|
|
213
|
-
`,
|
|
214
|
-
background-color: ${
|
|
213
|
+
`,fC=b.default.button`${bs};background-color:transparent;color:${v.themedColor.textHighEmphasis};&:hover:not(:disabled){opacity:0.7;}`,gC=e=>{switch(e){case"primary":return qo;case"secondary":return hC;case"clear":return fC;default:return qo}},pC=b.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);}}`,EC=({children:e,onClick:t,variant:n="primary",disabled:r=!1,loading:s=!1,className:o,...i})=>{const c=()=>{switch(n){case"primary":return v.themedColor.textHighEmphasisInverse;case"secondary":return v.themedColor.primary;case"clear":return v.themedColor.textHighEmphasis;default:return v.themedColor.textHighEmphasisInverse}},u=gC(n);return a.createElement(u,{onClick:t,disabled:r||s,className:o,...i},s?a.createElement(pC,null,a.createElement(te,{type:"spinner",size:22,color:c()})):a.createElement(B,{variant:"button",color:c()},e))},_C=({children:e,className:t,style:n,id:r,role:s})=>a.createElement(B,{variant:"caption4",color:v.themedColor.error,className:t,style:n,id:r,role:s},e),CC=({id:e,children:t,className:n,style:r,required:s,"aria-hidden":o})=>{const{stringSet:i}=le();return a.createElement(B,{id:e,variant:"caption3",color:v.themedColor.textMidEmphasis,className:n,style:r,"aria-hidden":o},t,!s&&a.createElement("span",{style:{color:v.themedColor.textLowEmphasis}},` (${i.OPTIONAL})`))},SC=({value:e,onChange:t,placeholder:n,error:r=!1,submitted:s=!1,className:o,disabled:i=!1,max:c,...u})=>{const d=h=>{const g=h.target.value.replace(/[^0-9.-]/g,""),p=g.split("."),E=p.length>1?p[0]+"."+p.slice(1).join("").replace(/\./g,""):g;if(h.target.value=E,E===""||E==="-")t==null||t(null);else{const _=Number(E);if(!isNaN(_)){if(c!==void 0&&_>c)return;t==null||t(_)}}},m=e==null?"":String(e);return a.createElement(TC,{type:"text",value:m,onChange:d,placeholder:n,className:o,disabled:i||s,inputMode:"decimal",$error:r,$submitted:s,...u})},bC=F.css`width:100%;box-sizing:border-box;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;${ke}&::placeholder{color:${v.themedColor.textLowEmphasis};}&::-webkit-inner-spin-button,&::-webkit-outer-spin-button{-webkit-appearance:none;margin:0;}`,vC=F.css`color:${v.themedColor.textHighEmphasis};border:1px solid transparent;cursor:not-allowed;${ne.light`
|
|
214
|
+
background-color: ${v.color.ondark.textMidEmphasis};
|
|
215
215
|
`}
|
|
216
216
|
${ne.dark`
|
|
217
|
-
background-color: ${
|
|
217
|
+
background-color: ${v.color.onlight.textLowEmphasis};
|
|
218
218
|
`}
|
|
219
219
|
|
|
220
220
|
&::placeholder {
|
|
221
|
-
color: ${
|
|
221
|
+
color: ${v.themedColor.textLowEmphasis};
|
|
222
222
|
}
|
|
223
|
-
`,
|
|
224
|
-
background-color: ${
|
|
223
|
+
`,yC=F.css`border:1px solid ${v.themedColor.error};color:${v.themedColor.textHighEmphasis};${ne.light`
|
|
224
|
+
background-color: ${v.color.background50};
|
|
225
225
|
`}
|
|
226
226
|
${ne.dark`
|
|
227
|
-
background-color: ${
|
|
227
|
+
background-color: ${v.color.onlight.textLowEmphasis};
|
|
228
228
|
`}
|
|
229
|
-
`,
|
|
230
|
-
background-color: ${
|
|
229
|
+
`,AC=F.css`border:1px solid ${v.themedColor.textDisabled};color:${v.themedColor.textHighEmphasis};${ne.light`
|
|
230
|
+
background-color: ${v.color.background50};
|
|
231
231
|
`}
|
|
232
232
|
${ne.dark`
|
|
233
|
-
background-color: ${
|
|
233
|
+
background-color: ${v.color.onlight.textLowEmphasis};
|
|
234
234
|
`}
|
|
235
235
|
|
|
236
236
|
&:focus {
|
|
237
|
-
border-color: ${
|
|
237
|
+
border-color: ${v.themedColor.primary};
|
|
238
238
|
}
|
|
239
|
-
`,
|
|
239
|
+
`,TC=b.default.input`${bC}${({$error:e,$submitted:t})=>t?vC:e?yC:AC}`,IC=e=>{if(e.multiple){const{value:t=[],onChange:n,maxSelect:r,submitted:s=!1}=e;return{selectedValues:t,handleOptionClick:i=>{if(s)return;if(t.includes(i)){const u=t.filter(d=>d!==i);n==null||n(u)}else{if(r&&t.length>=r)return;const u=[...t,i];n==null||n(u)}}}}else{const{value:t,onChange:n,submitted:r=!1}=e;return{selectedValues:t?[t]:[],handleOptionClick:o=>{r||t!==o&&(n==null||n(o))}}}},ec=e=>{const{options:t,submitted:n=!1,error:r=!1,className:s,groupLabel:o}=e,{conversation:i}=ue(),c=e.multiple===!0,{selectedValues:u,handleOptionClick:d}=IC(e),m=t.some(h=>u.includes(h.value));return a.createElement(MC,{className:s,...c?void 0:i.form.singleSelectGroup(o).props},t.map((h,f)=>{const g=u.includes(h.value),p=o?`${o}, ${h.label}`:h.label;return a.createElement(DC,{key:h.value,type:"button",$active:g,$submitted:n,$error:r,...(c?i.form.multiSelectOption(p,g,n):i.form.singleSelectOption(p,g,n,f,t.length,m,C=>{const E=t[C];E&&d(E.value)})).props,disabled:n,onClick:()=>d(h.value)},a.createElement(B,{variant:"caption1",color:xC(g,n)},h.label))}))},xC=(e,t)=>t?e?v.themedColor.textHighEmphasis:v.themedColor.textDisabled:e?v.themedColor.primary:v.themedColor.textMidEmphasis,MC=b.default.div`display:flex;flex-wrap:wrap;gap:4px 2px;`,RC=F.css`display:inline-flex;align-items:center;padding:8px 12px;border-radius:15px;transition:all 0.2s ease;`,kC=F.css`cursor:default;background-color:${v.color.ondark.textMidEmphasis};color:${v.themedColor.textHighEmphasis};${ne.dark`
|
|
240
240
|
background-color: transparent;
|
|
241
241
|
border: 1px solid white;
|
|
242
242
|
color: white;
|
|
243
243
|
`}
|
|
244
|
-
`,
|
|
245
|
-
background-color: ${
|
|
246
|
-
color: ${
|
|
244
|
+
`,wC=F.css`cursor:default;${ne.light`
|
|
245
|
+
background-color: ${v.color.ondark.textMidEmphasis};
|
|
246
|
+
color: ${v.themedColor.textDisabled};
|
|
247
247
|
`}
|
|
248
248
|
${ne.dark`
|
|
249
|
-
background-color: ${
|
|
250
|
-
border: 1px solid ${
|
|
251
|
-
color: ${
|
|
249
|
+
background-color: ${v.color.onlight.textLowEmphasis};
|
|
250
|
+
border: 1px solid ${v.color.onlight.textLowEmphasis};
|
|
251
|
+
color: ${v.themedColor.textDisabled};
|
|
252
252
|
`}
|
|
253
|
-
`,
|
|
254
|
-
background-color: ${
|
|
255
|
-
color: ${
|
|
253
|
+
`,LC=F.css`cursor:pointer;border:1px solid ${v.themedColor.primary};${ne.light`
|
|
254
|
+
background-color: ${v.color.background50};
|
|
255
|
+
color: ${v.themedColor.primary};
|
|
256
256
|
`}
|
|
257
257
|
${ne.dark`
|
|
258
|
-
background-color: ${
|
|
259
|
-
color: ${
|
|
258
|
+
background-color: ${v.color.onlight.textLowEmphasis};
|
|
259
|
+
color: ${v.themedColor.primary};
|
|
260
260
|
`}
|
|
261
|
-
`,
|
|
262
|
-
background-color: ${
|
|
263
|
-
color: ${
|
|
261
|
+
`,OC=F.css`cursor:pointer;border:1px solid ${v.themedColor.textDisabled};${ne.light`
|
|
262
|
+
background-color: ${v.color.background50};
|
|
263
|
+
color: ${v.themedColor.textMidEmphasis};
|
|
264
264
|
`}
|
|
265
265
|
${ne.dark`
|
|
266
|
-
background-color: ${
|
|
267
|
-
color: ${
|
|
266
|
+
background-color: ${v.color.onlight.textLowEmphasis};
|
|
267
|
+
color: ${v.themedColor.textMidEmphasis};
|
|
268
268
|
`}
|
|
269
|
-
`,
|
|
270
|
-
${r} ${
|
|
269
|
+
`,NC=F.css`border-color:${v.themedColor.error}!important;`,DC=b.default.button`${RC}${({$active:e,$submitted:t,$error:n})=>{if(t)return e?kC:wC;const r=e?LC:OC;return n?F.css`
|
|
270
|
+
${r} ${NC}
|
|
271
271
|
`:r}}
|
|
272
|
-
`,
|
|
273
|
-
background-color: ${
|
|
272
|
+
`,PC=e=>a.createElement(ec,{...e,multiple:!1}),$C=e=>a.createElement(ec,{...e,multiple:!0}),FC=b.default.div`width:100%;height:1px;background-color:${v.themedColor.textDisabled};`,UC=({className:e})=>a.createElement(FC,{className:e}),BC=({id:e,value:t="",onChange:n,placeholder:r,variant:s="single-line",error:o=!1,submitted:i=!1,className:c,disabled:u=!1,maxLength:d,...m})=>{const f={id:e,value:t,onChange:g=>{const p=g.target.value;d&&p.length>d||n==null||n(p)},placeholder:r,className:c,disabled:u||i,maxLength:d,$error:o,$submitted:i,...m};return s==="multi-line"?a.createElement(GC,{...f}):a.createElement(HC,{...f})},tc=F.css`width:100%;box-sizing:border-box;padding:8px 12px;border-radius:6px;font-size:14px;font-weight:400;line-height:1.43;outline:none;transition:all 0.2s ease;${ke}&::placeholder{color:${v.themedColor.textLowEmphasis};}`,nc=F.css`color:${v.themedColor.textHighEmphasis};border:1px solid transparent;cursor:not-allowed;${ne.light`
|
|
273
|
+
background-color: ${v.color.ondark.textMidEmphasis};
|
|
274
274
|
`}
|
|
275
275
|
${ne.dark`
|
|
276
|
-
background-color: ${
|
|
276
|
+
background-color: ${v.color.onlight.textLowEmphasis};
|
|
277
277
|
`}
|
|
278
278
|
|
|
279
279
|
&::placeholder {
|
|
280
|
-
color: ${
|
|
280
|
+
color: ${v.themedColor.textLowEmphasis};
|
|
281
281
|
}
|
|
282
|
-
`,
|
|
283
|
-
background-color: ${
|
|
282
|
+
`,rc=F.css`border:1px solid ${v.themedColor.error};color:${v.themedColor.textHighEmphasis};${ne.light`
|
|
283
|
+
background-color: ${v.color.background50};
|
|
284
284
|
`}
|
|
285
285
|
${ne.dark`
|
|
286
|
-
background-color: ${
|
|
286
|
+
background-color: ${v.color.onlight.textLowEmphasis};
|
|
287
287
|
`}
|
|
288
|
-
`,
|
|
289
|
-
background-color: ${
|
|
288
|
+
`,sc=F.css`border:1px solid ${v.themedColor.textDisabled};color:${v.themedColor.textHighEmphasis};${ne.light`
|
|
289
|
+
background-color: ${v.color.background50};
|
|
290
290
|
`}
|
|
291
291
|
${ne.dark`
|
|
292
|
-
background-color: ${
|
|
292
|
+
background-color: ${v.color.onlight.textLowEmphasis};
|
|
293
293
|
`}
|
|
294
294
|
|
|
295
295
|
&:focus {
|
|
296
|
-
border-color: ${
|
|
296
|
+
border-color: ${v.themedColor.primary};
|
|
297
297
|
}
|
|
298
|
-
`,
|
|
298
|
+
`,HC=b.default.input`${tc};height:36px;${({$error:e,$submitted:t})=>t?nc:e?rc:sc}`,GC=b.default.textarea`${tc};height:96px;resize:none;font-family:inherit;${({$error:e,$submitted:t})=>t?nc:e?rc:sc}`,zC=({children:e,className:t,style:n})=>a.createElement(B,{variant:"button",color:v.themedColor.textHighEmphasis,className:t,style:n},e),Ne={Title:zC,Label:CC,ErrorLabel:_C,Separator:UC,Button:EC,TextInput:BC,NumberInput:SC,SingleSelect:PC,MultiSelect:$C},VC=1,KC=new Set(["text","number","single-select","multi-select"]),oc=typeof __SBA_USE_FORM__>"u"||__SBA_USE_FORM__,qC=({messageForm:e,onError:t})=>{const n=l.useRef(void 0);l.useEffect(()=>{if(oc||!e||!t)return;const r=e.key??"";n.current!==r&&(t(new Error("Form rendering is disabled")),n.current=r)},[e,t])},WC=e=>{var _,A;const t=(_=e.extendedMessagePayload)==null?void 0:_.form;if(qC({messageForm:t,onError:(A=e.statsCallbacks)==null?void 0:A.onFormRenderError}),!oc)return null;if(!t)throw new Error("Form is not provided");const{stringSet:n}=le(),{conversation:r}=ue(),[s,o]=l.useState({submitting:!1,canceling:!1}),[i,c]=l.useState({visible:!1}),{state:u,fields:d,submit:m,cancel:h,updateFieldValue:f}=Ph(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:y=>{var T;return(T=e.onSubmitForm)==null?void 0:T.call(e,{key:t.key,data:y})},onCancel:()=>{var y;return(y=e.onCancelForm)==null?void 0:y.call(e,{key:t.key})}}),g=u==="submitted",p=async()=>{o(y=>({...y,submitting:!0}));try{await m()}catch(y){c({visible:!0,description:y instanceof Error?y.message:n.TRY_AGAIN})}finally{o(y=>({...y,submitting:!1}))}},C=async()=>{o(y=>({...y,canceling:!0}));try{await h()}catch(y){c({visible:!0,description:y instanceof Error?y.message:n.TRY_AGAIN})}finally{o(y=>({...y,canceling:!1}))}},E=l.useMemo(()=>{const y=()=>t.version>VC,T=()=>t.fields.some(M=>!KC.has(M.type));return y()||T()?{visible:!1,cancelable:!0,reason:n.FORM_NOT_SUPPORTED}:u==="draft"&&(e.isHandedOff||e.isConversationClosed)?{visible:!1,cancelable:!1,reason:n.FORM_UNAVAILABLE}:{visible:!0,cancelable:!0,reason:""}},[t.version,t.fields,u,e.isHandedOff,e.isConversationClosed]);return u==="canceled"?null:E.visible?a.createElement(l.Fragment,null,a.createElement(Wo,{id:`${Ke}-ext-form`,$maxWidth:e.maxBodyWidth??re.BODY_MAX_WIDTH},a.createElement(Ne.Title,null,t.title),a.createElement(YC,null,d.map(y=>a.createElement(jC,{key:y.key},a.createElement(Ne.Label,{style:{marginBottom:"6px"},required:y.required},y.label),y.type==="text"&&a.createElement(Ne.TextInput,{value:y.value||"",placeholder:y.placeholder,onChange:T=>f(y.key,T),disabled:g,error:!!y.error,submitted:g,variant:y.layout==="multiline"?"multi-line":"single-line",maxLength:y.maxLength,...r.form.textInput(y.label,y.required??!1,g).props}),y.type==="number"&&a.createElement(Ne.NumberInput,{value:y.value||null,placeholder:y.placeholder,onChange:T=>f(y.key,T),disabled:g,error:!!y.error,submitted:g,max:y.max,...r.form.numberInput(y.label,y.required??!1,g).props}),y.type==="single-select"&&a.createElement(Ne.SingleSelect,{options:y.options.map(T=>({label:T,value:T})),value:y.value||"",onChange:T=>f(y.key,T),submitted:g,groupLabel:y.label}),y.type==="multi-select"&&a.createElement(Ne.MultiSelect,{options:y.options.map(T=>({label:T,value:T})),value:y.value||[],onChange:T=>f(y.key,T),submitted:g,maxSelect:y.maxSelect,groupLabel:y.label}),y.error&&a.createElement(Ne.ErrorLabel,{style:{marginTop:"4px"}},y.error)))),a.createElement(Ne.Separator,null),a.createElement(XC,null,a.createElement(Ne.Button,{variant:g?"clear":"primary",...r.form.button(g?n.SUBMITTED:n.BUTTON__SUBMIT).props,onClick:p,disabled:g||s.canceling,loading:s.submitting},g?n.SUBMITTED:n.BUTTON__SUBMIT),u!=="submitted"&&a.createElement(Ne.Button,{variant:"secondary",...r.form.button(n.BUTTON__CANCEL).props,onClick:C,disabled:s.submitting,loading:s.canceling},n.BUTTON__CANCEL))),a.createElement(ln,{...i,onClose:()=>c({visible:!1,title:""})})):a.createElement(Wo,{id:`${Ke}-ext-form`,$maxWidth:e.maxBodyWidth??re.BODY_MAX_WIDTH},a.createElement(B,{variant:"body3"},E.reason),E.cancelable&&a.createElement(Ne.Button,{variant:"primary",...r.form.button(n.BUTTON__CANCEL).props,onClick:C,loading:s.canceling},n.BUTTON__CANCEL))},Wo=b.default.div`display:flex;flex-direction:column;gap:12px;border-radius:12px;overflow:hidden;width:100%;box-sizing:border-box;max-width:${({$maxWidth:e})=>e}px;${({theme:e})=>F.css`
|
|
299
299
|
color: ${e.colors.messageIncoming.text};
|
|
300
300
|
background-color: ${e.colors.messageIncoming.background};
|
|
301
301
|
`}
|
|
302
302
|
padding: 16px 12px;
|
|
303
303
|
transition: max-width 0.3s;
|
|
304
304
|
overflow-wrap: break-word;
|
|
305
|
-
`,
|
|
305
|
+
`,YC=b.default.div`display:flex;flex-direction:column;gap:12px;`,jC=b.default.div`display:flex;flex-direction:column;`,XC=b.default.div`display:flex;flex-direction:column;gap:8px;`,ZC=e=>a.createElement(a.Fragment,null),Hr=typeof __SBA_USE_MESSAGE_TEMPLATE__>"u"||__SBA_USE_MESSAGE_TEMPLATE__?l.lazy(()=>Promise.resolve().then(()=>require("./cjs/ZOM6SoNd.cjs")).then(e=>({default:e.MessageTemplateWrapper}))):null,JC=({messageTemplate:e,onError:t})=>{const n=l.useRef(void 0);l.useEffect(()=>{if(Hr||!e||!t)return;const r=e.key??"";n.current!==r&&(t(new Error("Message template rendering is disabled")),n.current=r)},[e,t])},QC=e=>{var n,r,s;const t=(n=e.extendedMessagePayload)==null?void 0:n.message_template;return JC({messageTemplate:t,onError:(r=e.statsCallbacks)==null?void 0:r.onMessageTemplateError}),Hr?a.createElement(yt,{errorFallback:e.messageTemplateErrorFallback,loadingFallback:e.messageTemplateLoadingFallback,onError:(s=e.statsCallbacks)==null?void 0:s.onMessageTemplateError},a.createElement(Hr,{...e})):null},eS=e=>a.createElement(a.Fragment,null),tS=({data:e,extendedMessagePayload:t,onClickSuggestedReply:n,onConfirmTicketClosure:r,suggestedRepliesDirection:s="vertical"})=>{const{conversation:o}=ue(),{stringSet:i}=le(),[c,u]=l.useState(!1),[d,m]=l.useState(!1),h=l.useRef(!1),{suggestedReplies:f}=o,g=Yd({data:e,extendedMessagePayload:t,ticketClosureLabels:{confirm:i.DESK__TICKET_CLOSURE_CONFIRM,decline:i.DESK__TICKET_CLOSURE_DECLINE}});if(g.length===0||c)return null;const p=C=>{if(C.action==="confirmTicketClosure"){if(h.current||!r)return;h.current=!0,r({ticketId:C.ticketId,confirmed:C.confirmed}).catch(()=>{h.current=!1,m(!0)});return}n&&(n({reply:C.label}),u(!0))};return a.createElement(a.Fragment,null,a.createElement(nS,{id:`${Ke}-ext-suggested-replies`,role:"presentation",$type:s},g.map((C,E)=>{const _=f.item(C.label,E);return a.createElement(l.Fragment,{key:E},a.createElement(rS,{$type:s,..._.props,onClick:()=>p(C)},a.createElement(sS,{variant:"body3"},C.label)),_.descriptionNode)})),a.createElement(ln,{visible:d,title:i.PLACE_HOLDER__WRONG,description:i.DESK__TICKET_CLOSURE_ERROR_MESSAGE,onClose:()=>m(!1)}))},nS=b.default.div`margin:16px 0;padding:0 ${re.HORIZONTAL_PADDING}px;position:relative;display:flex;align-self:stretch;gap:8px;${({$type:e})=>e==="vertical"?oS:iS};`,rS=b.default.button.attrs({type:"button"})`
|
|
306
306
|
all: unset;
|
|
307
307
|
box-sizing: border-box;
|
|
308
308
|
padding: 8px 12px;
|
|
@@ -312,85 +312,85 @@ $2
|
|
|
312
312
|
border-radius: 20px / clamp(20px, 5%, 100px);
|
|
313
313
|
cursor: pointer;
|
|
314
314
|
word-break: break-word;
|
|
315
|
-
color: ${
|
|
316
|
-
border: 1px solid ${
|
|
317
|
-
background-color: ${
|
|
315
|
+
color: ${v.color.primary.main};
|
|
316
|
+
border: 1px solid ${v.color.primary.main};
|
|
317
|
+
background-color: ${v.themedColor.bg_50_600};
|
|
318
318
|
|
|
319
319
|
&:hover {
|
|
320
|
-
background-color: ${
|
|
320
|
+
background-color: ${v.themedColor.bg_100_500};
|
|
321
321
|
}
|
|
322
322
|
|
|
323
|
-
${
|
|
323
|
+
${ke}
|
|
324
324
|
|
|
325
|
-
${({$type:e,theme:t})=>
|
|
326
|
-
`,
|
|
325
|
+
${({$type:e,theme:t})=>F.css`${e==="vertical"?aS:cS};&:active{background-color:${t.colors.base.primary};color:${t.colors.base.primaryContrastContent};}`}
|
|
326
|
+
`,sS=b.default(B)`color:inherit;`,oS=F.css`flex-direction:column;align-items:flex-end;`,iS=F.css`flex-direction:row;overflow-x:scroll;-ms-overflow-style:none;scrollbar-width:none;&::-webkit-scrollbar{display:none;}`,aS=F.css`max-width:calc(100% - 70px);white-space:pre-wrap;`,cS=F.css`white-space:nowrap;`,lS=e=>{const{components:t}=_t.useContext(),{stringSet:n}=le(),r=yi(e)?a.createElement(t.TextMessageBody,{...e}):null;if(e.messageType==="user")return r;if(e.messageType==="file"){const s=e.file;return s.type.startsWith("image")||s.type.startsWith("video")?a.createElement(t.MediaMessageBody,{...e},r):a.createElement(t.FileMessageBody,{...e},r)}return e.messageType==="multipleFiles"?a.createElement(t.MultipleFilesMessageBody,{...e},r):a.createElement(t.TextMessageBody,{...e,message:n.UNKNOWN__UNKNOWN_MESSAGE_TYPE})},uS=Object.freeze({}),dS=e=>{var T,M,O,w,R;const{components:t}=_t.useContext(),{streamText:n,isAnimating:r,isHolding:s}=Qh({text:e.message,enabled:e.isStreaming,snapOnDisable:((T=e.extendedMessagePayload)==null?void 0:T.is_last_in_turn)!==!0,deferredMarkdownElements:e.deferredMarkdownElements,onAnimationStart:e.onStreamAnimationStart,onAnimationProgress:e.onStreamAnimationProgress,onAnimationComplete:e.onStreamAnimationComplete,onAnimationHoldChange:e.onStreamAnimationHoldChange,onVisibleTextProgress:(M=e.statsCallbacks)==null?void 0:M.onVisibleTextProgress,onRenderedTextProgress:(O=e.statsCallbacks)==null?void 0:O.onRenderedTextProgress});if(s)return null;const o={...e,message:n,extendedMessagePayload:r?uS:e.extendedMessagePayload},i=!!o.isTyping,c=!!o.isSenderAvatarVisible,u=tn(o.extendedMessagePayload),d=u.hasCTAButton,m=u.hasChallenge,h=u.hasCitations,f=u.hasForm,g=u.hasMessageTemplate,p=!!o.createdAt,C=d||h,E=o.groupType==="top"||o.groupType==="single",_=o.groupType==="bottom"||o.groupType==="single",A=c?re.AVATAR_SIZE:0,y=C&&a.createElement(l.Fragment,null,d&&a.createElement(hS,{$marginTop:12,$paddingInline:12},a.createElement(t.CTAButton,{...o})),h&&a.createElement(t.Citation,{...o}));return a.createElement(mS,{$marginBottom:i?0:Bn(o.groupType)},E&&a.createElement(fS,null,c&&a.createElement(t.SenderAvatar,{...o}),a.createElement(t.SenderName,{...o})),a.createElement(t.Prechecks,{...o}),a.createElement(pS,null,a.createElement(Er,{$extraStartPadding:A},i?a.createElement(t.TypingIndicator,{...o}):a.createElement(t.MessageBody,{...o},y)),g&&a.createElement(Yo,{$startPadding:0,$endPadding:0},a.createElement(t.MessageTemplate,{...o,messageTemplateErrorFallback:o.messageTemplateErrorFallback??a.createElement(Er,{$extraStartPadding:A},a.createElement(t.MessageBody,{...o,messageType:"user",message:((R=(w=o.extendedMessagePayload)==null?void 0:w.message_template)==null?void 0:R.fallback_message)??"Cannot read this template."})),messageTemplateLoadingFallback:o.messageTemplateLoadingFallback??a.createElement(Er,{$extraStartPadding:A},a.createElement(t.TypingIndicator,{...o}))})),a.createElement(t.CustomMessageTemplate,{...o}),m&&a.createElement(t.Challenge,{...o}),f&&a.createElement(Yo,{$extraStartPadding:A},a.createElement(t.Form,{...o}))),a.createElement(t.MessageLogs,{...o}),_&&p&&a.createElement(gS,{$extraStartPadding:A+8},a.createElement(t.SentTime,{...o})),a.createElement(l.Fragment,null,!i&&a.createElement(un,{$extraStartPadding:A+8},a.createElement(t.Feedback,{...o})),o.suggestedRepliesVisible&&a.createElement(t.SuggestedReplies,{...o})))},_t=Qe({template:dS,components:{SenderName:R_,SenderAvatar:x_,SentTime:w_,MessageBody:lS,TextMessageBody:y_,MediaMessageBody:a_,FileMessageBody:s_,MultipleFilesMessageBody:S_,TypingIndicator:O_,SuggestedReplies:tS,MessageTemplate:QC,CustomMessageTemplate:j_,Challenge:G_,CTAButton:U_,Citation:z_,Form:WC,Feedback:lC,MessageLogs:ZC,Prechecks:eS}}),mS=b.default.div.attrs({role:"presentation"})`
|
|
327
327
|
display: flex;
|
|
328
328
|
flex-direction: column;
|
|
329
329
|
align-items: flex-start;
|
|
330
330
|
margin-bottom: ${({$marginBottom:e})=>`${e}px`};
|
|
331
|
-
`,
|
|
331
|
+
`,un=b.default.div.attrs({role:"presentation"})`
|
|
332
332
|
display: flex;
|
|
333
333
|
align-self: stretch;
|
|
334
334
|
justify-content: flex-start;
|
|
335
|
-
${({$startPadding:e=
|
|
335
|
+
${({$startPadding:e=re.HORIZONTAL_PADDING,$endPadding:t=re.HORIZONTAL_PADDING,$extraStartPadding:n=0})=>`
|
|
336
336
|
padding-inline: ${e+n}px ${t}px;
|
|
337
337
|
`}
|
|
338
|
-
`,
|
|
338
|
+
`,hS=b.default.div.attrs({role:"presentation"})`
|
|
339
339
|
display: flex;
|
|
340
340
|
flex-direction: column;
|
|
341
341
|
min-width: 0;
|
|
342
|
-
${({$marginTop:e=0,$paddingInline:t=0})=>
|
|
343
|
-
`,
|
|
342
|
+
${({$marginTop:e=0,$paddingInline:t=0})=>F.css`margin-top:${e}px;padding-inline:${t}px;`}
|
|
343
|
+
`,fS=b.default(un)`display:flex;flex-direction:row;align-items:center;gap:8px;`,Er=b.default(un)`display:flex;`,gS=b.default(un)`margin-top:${re.BODY_TIME_GAP}px;display:flex;align-items:flex-start;justify-content:flex-start;`,Yo=b.default(un).attrs({role:"presentation"})`
|
|
344
344
|
display: flex;
|
|
345
|
-
${({$startPadding:e=
|
|
345
|
+
${({$startPadding:e=re.HORIZONTAL_PADDING,$endPadding:t=re.HORIZONTAL_PADDING,$extraStartPadding:n=0})=>`
|
|
346
346
|
padding-inline: ${e+n}px ${t}px;
|
|
347
347
|
`}
|
|
348
|
-
`,
|
|
348
|
+
`,pS=b.default.div.attrs({role:"presentation"})`
|
|
349
349
|
display: flex;
|
|
350
350
|
flex-direction: column;
|
|
351
351
|
align-self: stretch;
|
|
352
352
|
min-width: 0;
|
|
353
353
|
max-width: 100%;
|
|
354
|
-
gap: ${
|
|
355
|
-
`;function
|
|
356
|
-
background-color: ${
|
|
354
|
+
gap: ${re.GAP_GROUPED}px;
|
|
355
|
+
`;function ES({file:e,children:t,onClickFile:n,sendingStatus:r}){const s=(()=>{if(!(!n||r==="failed"))return()=>n==null?void 0:n(e)})();return a.createElement(_S,null,a.createElement(Cs,{name:e.name,mimeType:e.type,type:qr(e.name,e.type),onClick:s}),t)}const _S=b.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${re.GAP_GROUPED}px;`,Fn=new WeakMap;function vs(e){const t=Fn.get(e);if(t)return t;const n=URL.createObjectURL(e);return Fn.set(e,n),n}function jo(e){const t=Fn.get(e);t&&(URL.revokeObjectURL(t),Fn.delete(e))}function CS({sendingStatus:e,file:t,metadata:n,onClickMedia:r,onClickMediaFiles:s,children:o}){const{conversation:i}=ue(),{aspectRatio:c,localFile:u}=n,[d]=l.useState(()=>u instanceof Blob?vs(u):void 0),m=d??t.url,[h,f]=l.useState(()=>u instanceof Blob),g=(()=>{if(e==="failed")return;const E=e==="succeeded"?t.url:m;if(s)return()=>s({files:[{url:E,type:t.type,name:t.name}],index:0});if(r)return()=>r({...t,url:E})})(),p=g?i.file.buttonLikePreview({name:t.name,mimeType:t.type,onActivate:g}):i.file.preview({name:t.name,mimeType:t.type}),C={...p.props,$ratio:c,$clickable:!!g};return a.createElement(SS,null,a.createElement(bS,{...C},!h&&a.createElement(It,{size:26},a.createElement(te,{type:"spinner",color:"textLowEmphasis",size:26})),m?a.createElement(vS,{$loaded:h,src:m,alt:"image-message",onLoad:()=>f(!0)}):null,p.descriptionNode),o)}const SS=b.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${re.GAP_GROUPED}px;`,bS=b.default.div`width:${re.BODY_MAX_WIDTH}px;border-radius:12px;overflow:hidden;cursor:${e=>e.$clickable?"pointer":"default"};height:auto;aspect-ratio:${e=>e.$ratio};position:relative;display:flex;align-items:center;justify-content:center;${ne.light`
|
|
356
|
+
background-color: ${v.color.background100};
|
|
357
357
|
`}
|
|
358
358
|
${ne.dark`
|
|
359
|
-
background-color: ${
|
|
359
|
+
background-color: ${v.color.background400};
|
|
360
360
|
`}
|
|
361
|
-
`,
|
|
361
|
+
`,vS=b.default.img`position:absolute;width:100%;height:100%;inset-block-start:0;inset-inline-start:0;object-fit:cover;border-radius:inherit;opacity:${e=>e.$loaded?1:0};transition:opacity 0.5s ease;`;function yS(e){return typeof e=="object"&&e!==null&&"url"in e}const AS=({sendingStatus:e,files:t,metadata:n,onClickMedia:r,onClickMediaFiles:s,children:o})=>{const[i]=l.useState(()=>{if(!n.localFiles)return null;const h=n.localFiles.flatMap(f=>f instanceof Blob?{url:vs(f),type:f.type,name:f instanceof File?f.name:""}:yS(f)?f:[]);return h.length>0?h:null}),c=i??t,u=e==="pending",d=e==="succeeded",m=h=>{if(!d)return;const f=t[h];f&&(s?s({files:t,index:h}):r&&r({url:f.url,type:f.type||"image/*"}))};return a.createElement(TS,null,a.createElement(Wa,{images:c,isPending:u,onClickImage:d?m:void 0}),o)},TS=b.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${re.GAP_GROUPED}px;`,ic=({children:e})=>a.createElement("span",{id:Bo,className:Bo,"aria-label":i_},e),ac="✱",Xo=e=>{var t,n;return{files:e.fileInfoList.map(r=>({url:r.url,type:r.mimeType??"",name:r.fileName??""})),metadata:{localFiles:(n=(t=e.messageParams)==null?void 0:t.fileInfoList)==null?void 0:n.map(r=>{if(r.file)return r.file;if(r.fileUrl)return{url:r.fileUrl,name:r.fileName??"",type:r.mimeType??""}})}}},IS=e=>{const t=new RegExp(`(\`+)[^\`]+?\\1|(${ac}+)`,"g"),n=[];let r;for(;(r=t.exec(e))!==null;)r[2]&&n.push({start:r.index,end:r.index+r[0].length,text:r[2]});return n},_r=(e,t,n,r)=>{const s=[];let o=t;for(const i of r)i.start<o||i.end>n||(i.start>o&&s.push(e.slice(o,i.start)),s.push(a.createElement(ic,{key:i.start},i.text)),o=i.end);return o<n&&s.push(e.slice(o,n)),s},xS=e=>{const t=IS(e),n=/\*\*.*?\*\*/g,r=[];let s=0,o;for(;(o=n.exec(e))!==null;){const i=o.index+o[0].length;r.push(..._r(e,s,o.index,t)),r.push(a.createElement("b",{key:o.index},_r(e,o.index+2,i-2,t))),s=i}return r.push(..._r(e,s,e.length,t)),r};function MS(e){var n,r;const t=l.useMemo(()=>xS(e.message),[e.message]);return a.createElement(RS,{$maxWidth:e.maxBodyWidth??re.BODY_MAX_WIDTH,$color:(n=e.customStyle)==null?void 0:n.bubbleContentColor,$bgColor:(r=e.customStyle)==null?void 0:r.bubbleBackgroundColor},a.createElement(kS,{variant:"body3"},t))}const RS=b.default.div`display:flex;flex-direction:column;border-radius:12px;overflow:hidden;max-width:${({$maxWidth:e})=>e}px;${({theme:e,$color:t,$bgColor:n})=>F.css`
|
|
362
362
|
color: ${t||e.colors.messageOutgoing.text};
|
|
363
363
|
background-color: ${n||e.colors.messageOutgoing.background};
|
|
364
364
|
`}
|
|
365
365
|
padding: 12px 0;
|
|
366
366
|
transition: max-width 0.3s;
|
|
367
367
|
overflow-wrap: break-word;
|
|
368
|
-
`,
|
|
369
|
-
`,
|
|
370
|
-
`,QC=C.default(Xa)``,eb=C.default(Xa)`margin-top:${se.BODY_TIME_GAP}px;`,tb=e=>e.messageType!=="admin"?null:a.createElement(nb,null,a.createElement(B,{variant:"caption2",color:b.themedColor.textMidEmphasis},rb(Dc.default.sanitize(e.message),e.onClickLink))),nb=C.default.div`text-align:center;text-wrap:pretty;word-break:break-word;padding-inline:${se.HORIZONTAL_PADDING}px;a{text-decoration:underline;color:inherit;}`,rb=(e,t)=>{try{const n=[];let r=e,s=0;for(;r;){const o=r.match(/\[([^\]]+)\]\((https?:\/\/[^\s]+)\)/),i=r.match(/\*\*([^*]+)\*\*/),c=[o&&{match:o,type:"link"},i&&{match:i,type:"bold"}].filter(f=>!!f);if(!c.length){n.push(r);break}const u=c.reduce((f,g)=>g.match.index<f.match.index?g:f),{match:d,type:m}=u,h=d.index;h>0&&n.push(r.slice(0,h)),m==="link"?n.push(a.createElement("a",{key:s++,href:d[2],target:"_blank",rel:rs,onClick:f=>{f.preventDefault();const g=d[2];g&&(t==null||t({url:g}))}},d[1])):m==="bold"&&n.push(a.createElement("strong",{key:s++},d[1])),r=r.slice(h+d[0].length)}return n.filter(o=>o!=="")}catch{return[e]}},sb=({direction:e,currentIndex:t,totalCount:n})=>n<=0?t:e==="next"?(t+1)%n:(t-1+n)%n,Za=({options:e,value:t,disabled:n,hasError:r=!1,errorId:s,onChange:o})=>{const i=l.useRef([]),c=e.findIndex(h=>h.value===t),u=c>=0?c:0,d=h=>{requestAnimationFrame(()=>{var f;(f=i.current[h])==null||f.focus()})},m=h=>{const f=e[h];!f||n||(o==null||o(f.value),d(h))};return{radioGroupProps:h=>({role:"radiogroup","aria-label":h,...r&&s?{"aria-invalid":!0,"aria-errormessage":s}:{}}),getRadioProps:h=>({ref:f=>{i.current[h]=f},tabIndex:n?-1:h===u?0:-1,describedBy:r&&s?s:void 0,onArrowNavigate:f=>{m(sb({direction:f,currentIndex:h,totalCount:e.length}))}})}},ob=e=>{switch(e.key){case"ArrowDown":case"ArrowRight":return"next";case"ArrowUp":case"ArrowLeft":return"previous";default:return}},ib=({event:e,onClick:t,onArrowNavigate:n})=>{if(ab(e))return;const r=ob(e);if(r){e.preventDefault(),n==null||n(r);return}e.key!=="Enter"&&e.key!==" "||(e.preventDefault(),t==null||t())},ab=e=>e.repeat||e.currentTarget.getAttribute("aria-disabled")==="true",fs=l.forwardRef(({onClick:e,checked:t,label:n,disabled:r,tabIndex:s=0,labelVariant:o="caption2",describedBy:i,onArrowNavigate:c},u)=>{const d=t?b.themedColor.primary:r?b.themedColor.textDisabled:b.themedColor.textLowEmphasis,m=t?b.themedColor.textHighEmphasis:r?b.themedColor.textLowEmphasis:b.themedColor.textHighEmphasis;return a.createElement(ub,{ref:u,role:"radio",tabIndex:r?-1:s,"aria-checked":t,"aria-disabled":!!r,"aria-label":n,"aria-describedby":i,onClick:r?void 0:e,onKeyDown:h=>ib({event:h,onClick:e,onArrowNavigate:c})},a.createElement(cb,{"aria-hidden":"true"},a.createElement(ee,{size:20,type:t?"radio-on":"radio-off",color:d})),a.createElement(lb,{"aria-hidden":"true",variant:o,color:m},n))});fs.displayName="Radio";const cb=C.default.div`width:20px;height:20px;`,lb=C.default(B)`line-height:20px;word-break:break-word;`,ub=C.default.div`display:flex;align-items:flex-start;justify-content:flex-start;gap:2px;${xe}&[aria-disabled='false']{cursor:pointer;}`,db=({csatPayload:e,submitted:t,defaultValue:n,value:r,onChange:s})=>{var u,d;const o=[{label:((u=e.cre)==null?void 0:u.positive_label)??"",value:!0},{label:((d=e.cre)==null?void 0:d.negative_label)??"",value:!1}],i=Za({options:o,value:r,disabled:t,onChange:s});if(l.useEffect(()=>{typeof r>"u"&&typeof n=="boolean"&&(s==null||s(n))},[r,n]),!e.cre)return null;const c=e.cre;return a.createElement(mb,null,a.createElement(ke.Label,{required:c.required,"aria-hidden":!0},c.question),a.createElement(hb,{...i.radioGroupProps(c.question)},o.map((m,h)=>a.createElement(fs,{key:m.label,checked:r===m.value,label:m.label,disabled:t,...i.getRadioProps(h),onClick:()=>s==null?void 0:s(m.value)}))))},mb=C.default.div`display:flex;flex-direction:column;gap:8px;`,hb=C.default.div`display:flex;flex-direction:column;gap:8px;`,fb=({followUpItem:e,submitted:t,value:n="",onChange:r,hasError:s})=>{const{stringSet:o}=ie(),{conversation:i}=ae(),c=l.useId(),u=l.useId(),d=e.response_type!=="free_text",m=e.response_type==="single_choice"?e.options.map(f=>({label:f,value:f})):[],h=Za({options:m,value:n,disabled:t,hasError:s,errorId:c,onChange:r});return a.createElement(gb,null,a.createElement(ke.Label,{id:u,required:e.required,"aria-hidden":d},e.question),e.response_type==="free_text"&&a.createElement(ke.TextInput,{variant:"multi-line",disabled:t,submitted:t,maxLength:100,value:n,onChange:f=>r(f),error:s,...i.form.textInput(o.A11Y_CSAT_TEXT_INPUT_LABEL,e.required??!1,t,{labelId:u}).props,"aria-invalid":s,"aria-errormessage":s?c:void 0}),e.response_type==="single_choice"&&a.createElement(pb,{...h.radioGroupProps(e.question)},m.map((f,g)=>a.createElement(fs,{key:f.value,checked:n===f.value,label:f.label,disabled:t,...h.getRadioProps(g),onClick:()=>r==null?void 0:r(f.value),labelVariant:"body3"}))),s&&a.createElement(_b,{role:"alert",id:c},o.FORM_VALIDATION_REQUIRED))},gb=C.default.div`display:flex;flex-direction:column;gap:8px;`,pb=C.default.div`display:flex;flex-direction:column;gap:8px;`,_b=C.default(ke.ErrorLabel)``,Eb=({value:e,selected:t})=>a.createElement(Cb,{$selected:t,"aria-hidden":"true"},bb[e-1]),Cb=C.default.div`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,bb=[a.createElement("svg",{width:"40",height:"40",viewBox:"0 0 40 40",fill:"none",xmlns:"http://www.w3.org/2000/svg"},a.createElement("path",{d:"M2.08337 19.9999C2.08337 10.1048 10.1049 2.08325 20 2.08325C29.8952 2.08325 37.9167 10.1048 37.9167 19.9999C37.9167 29.8951 29.8952 37.9166 20 37.9166C10.1049 37.9166 2.08337 29.8951 2.08337 19.9999Z",fill:"url(#paint0_linear_159_173206)"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M12.5828 29.3328C13.1348 29.7473 13.9184 29.636 14.3329 29.084C15.6272 27.3607 17.6839 26.25 20 26.25C22.3164 26.25 24.373 27.3607 25.6672 29.084C26.0819 29.636 26.8654 29.7473 27.4175 29.3328C27.9695 28.9182 28.0809 28.1347 27.6662 27.5825C25.9202 25.2577 23.136 23.75 20 23.75C16.8642 23.75 14.0801 25.2577 12.334 27.5825C11.9194 28.1347 12.0308 28.9182 12.5828 29.3328Z",fill:"#141B34"}),a.createElement("path",{d:"M28.4454 13.7707C29.1329 13.8328 29.6405 14.4406 29.5785 15.1281C29.5165 15.8153 28.9095 16.3221 28.2224 16.2608C28.2224 16.2608 28.0287 16.2502 27.9272 16.2487C27.7229 16.2457 27.4387 16.2509 27.1229 16.2833C26.7869 16.3177 26.4649 16.3782 26.1804 16.4662L26.3045 16.86C26.7797 18.3675 25.5099 19.5813 24.2062 19.5813C23.5045 19.5813 22.8324 19.2617 22.43 18.6857C22.003 18.0745 21.9422 17.241 22.408 16.5344C22.751 16.0143 23.2449 15.3831 23.8964 14.8657C24.836 14.1195 26.044 13.8809 26.8675 13.7963C27.3029 13.7517 28.0154 13.7319 28.4454 13.7707Z",fill:"#141B34"}),a.createElement("path",{d:"M11.5549 13.7707C10.8674 13.8328 10.3597 14.4406 10.4218 15.1281C10.4838 15.8153 11.0908 16.3221 11.7779 16.2608C11.7779 16.2608 11.9716 16.2502 12.073 16.2487C12.2774 16.2457 12.5616 16.2509 12.8774 16.2833C13.2134 16.3177 13.5353 16.3782 13.8199 16.4662L13.6958 16.86C13.2205 18.3675 14.4904 19.5813 15.794 19.5813C16.4958 19.5813 17.168 19.2617 17.5703 18.6857C17.9971 18.0745 18.0581 17.241 17.5921 16.5344C17.2493 16.0143 16.7553 15.3831 16.1039 14.8657C15.1643 14.1195 13.9562 13.8809 13.1327 13.7963C12.6974 13.7517 11.9849 13.7319 11.5549 13.7707Z",fill:"#141B34"}),a.createElement("defs",null,a.createElement("linearGradient",{id:"paint0_linear_159_173206",x1:"20",y1:"2.08325",x2:"20",y2:"37.9166",gradientUnits:"userSpaceOnUse"},a.createElement("stop",{stopColor:"#FF2D1D"}),a.createElement("stop",{offset:"1",stopColor:"#FFA540"})))),a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},a.createElement("path",{d:"M2.083 20C2.083 10.105 10.105 2.083 20 2.083c9.895 0 17.917 8.021 17.917 17.917 0 9.895-8.022 17.917-17.917 17.917C10.105 37.917 2.083 29.895 2.083 20Z",fill:"#FFD46E"}),a.createElement("path",{d:"M14.249 27.334C15.851 26.13 17.844 25.417 20 25.417c2.156 0 4.149.714 5.751 1.917.553.415.664 1.199.25 1.751-.415.552-1.199.664-1.751.25-1.183-.889-2.652-1.416-4.25-1.416s-3.067.527-4.25 1.416c-.553.414-1.336.302-1.751-.25-.415-.552-.303-1.336.249-1.751Z",fill:"#141B34"}),a.createElement("path",{d:"M23.445 14.596c-.687.062-1.294-.445-1.356-1.132-.062-.687.445-1.295 1.132-1.357.082-.005.342-.02.482-.022.277-.004.662.002 1.097.047.823.085 2.031.323 2.97 1.07.652.518 1.146 1.15 1.489 1.67.466.706.405 1.54-.022 2.15-.402.576-1.074.896-1.775.896-1.304 0-2.573-1.214-2.098-2.722l.125-.394c-.285-.088-.607-.148-.942-.182-.316-.033-.6-.038-.804-.035-.101.002-.242.01-.294.013Z",fill:"#141B34"}),a.createElement("path",{d:"M11.779 14.596c-.687.062-1.294-.445-1.356-1.132-.062-.687.445-1.295 1.132-1.357.082-.005.342-.02.482-.022.277-.004.662.002 1.097.047.823.085 2.031.323 2.97 1.07.652.518 1.146 1.15 1.489 1.67.466.706.405 1.54-.022 2.15-.402.576-1.074.896-1.775.896-1.304 0-2.573-1.214-2.098-2.722l.124-.394c-.284-.088-.606-.148-.941-.182-.316-.033-.6-.038-.804-.035-.101.002-.243.01-.294.013Z",fill:"#141B34"})),a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},a.createElement("path",{d:"M2.083 20C2.083 10.105 10.105 2.083 20 2.083c9.895 0 17.917 8.021 17.917 17.917 0 9.895-8.022 17.917-17.917 17.917C10.105 37.917 2.083 29.895 2.083 20Z",fill:"#FFD46E"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M11.25 15c0-1.151.933-2.083 2.083-2.083h.015c1.151 0 2.084.933 2.084 2.083 0 1.151-.933 2.083-2.084 2.083h-.015c-1.15 0-2.083-.933-2.083-2.083ZM24.568 15c0-1.151.933-2.083 2.084-2.083h.015c1.151 0 2.083.933 2.083 2.083 0 1.151-.932 2.083-2.083 2.083h-.015c-1.151 0-2.084-.933-2.084-2.083Z",fill:"#141B34"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M13.75 26.667c0-.691.56-1.25 1.25-1.25h10c.69 0 1.25.559 1.25 1.25 0 .691-.56 1.25-1.25 1.25h-10c-.69 0-1.25-.559-1.25-1.25Z",fill:"#141B34"})),a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},a.createElement("path",{d:"M2.083 20C2.083 10.105 10.105 2.083 20 2.083c9.895 0 17.917 8.021 17.917 17.917 0 9.895-8.022 17.917-17.917 17.917C10.105 37.917 2.083 29.895 2.083 20Z",fill:"#FFD46E"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M12.583 24.001c.552-.414 1.335-.302 1.75.25 1.294 1.723 3.35 2.834 5.667 2.834s4.373-1.11 5.667-2.834c.415-.552 1.199-.664 1.751-.25.552.415.664 1.199.25 1.751C25.92 28.076 23.136 29.584 20 29.584s-5.92-1.508-7.666-3.832c-.415-.552-.303-1.336.249-1.751Z",fill:"#141B34"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M11.25 15c0-1.151.933-2.083 2.083-2.083h.015c1.151 0 2.084.933 2.084 2.083 0 1.151-.933 2.083-2.084 2.083h-.015c-1.15 0-2.083-.933-2.083-2.083ZM24.568 15c0-1.151.933-2.083 2.084-2.083h.015c1.151 0 2.083.933 2.083 2.083 0 1.151-.932 2.083-2.083 2.083h-.015c-1.151 0-2.084-.933-2.084-2.083Z",fill:"#141B34"})),a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},a.createElement("path",{d:"M2.083 20C2.083 10.105 10.105 2.083 20 2.083c9.895 0 17.917 8.021 17.917 17.917 0 9.895-8.022 17.917-17.917 17.917C10.105 37.917 2.083 29.895 2.083 20Z",fill:"#FFD46E"}),a.createElement("g",{clipPath:"url(#clip0_159_173224)"},a.createElement("g",{clipPath:"url(#clip1_159_173224)"},a.createElement("path",{d:"M20 30.624c3.752 0 6.904-2.532 7.789-5.956.412-1.593-.185-1.959-1.76-1.959H13.973c-1.575 0-2.173.366-1.761 1.959.885 3.424 4.037 5.956 7.788 5.956Z",fill:"#141B34"})),a.createElement("mask",{id:"mask0_159_173224",style:{maskType:"alpha"},maskUnits:"userSpaceOnUse",x:"12",y:"22",width:"16",height:"9"},a.createElement("path",{d:"M20 30.624c3.752 0 6.904-2.532 7.789-5.956.412-1.593-.185-1.959-1.76-1.959H13.973c-1.575 0-2.173.366-1.761 1.959.885 3.424 4.037 5.956 7.788 5.956Z",fill:"#141B34"})),a.createElement("g",{mask:"url(#mask0_159_173224)"},a.createElement("path",{d:"M20 32.998c3.278 0 5.936-1.594 5.936-3.561 0-1.968-2.658-3.562-5.936-3.562-3.278 0-5.936 1.594-5.936 3.562 0 1.967 2.658 3.561 5.936 3.561Z",fill:"#FF493B"}))),a.createElement("path",{d:"M11.667 15.833c0-1.381 1.12-2.5 2.5-2.5s2.5 1.12 2.5 2.5M23.333 15.833c0-1.381 1.12-2.5 2.5-2.5s2.5 1.12 2.5 2.5",stroke:"#141B34",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"}),a.createElement("defs",null,a.createElement("clipPath",{id:"clip0_159_173224"},a.createElement("rect",{width:"15.83",height:"7.915",fill:"white",transform:"translate(12.085 22.709)"})),a.createElement("clipPath",{id:"clip1_159_173224"},a.createElement("rect",{width:"15.83",height:"7.915",fill:"white",transform:"translate(12.085 22.709)"}))))],vb=({csatPayload:e,submitted:t,value:n,onChange:r})=>{const s=typeof n>"u",{conversation:o}=ae(),i=o.csat.scoresContainer(e.csat_question);return a.createElement(yb,null,a.createElement(B,{variant:"caption3",color:b.themedColor.textMidEmphasis,"aria-hidden":"true"},e.csat_question),a.createElement(Ab,{...i.props},i.descriptionNode,e.csat_scores.map(({label:c,image_url:u},d)=>{const m=d+1,h=n===m,f=e.csat_scores.length,g=o.csat.scoreItem({score:m,label:c,selected:h,disabled:t,currentIndex:d,totalCount:f,hasSelection:!s,onChange:r});return a.createElement(Tb,{key:d,type:"button",...g.props},a.createElement(Sb,{value:m,selected:s||h,src:u}),!!c&&a.createElement(B,{"aria-hidden":"true",color:h?b.themedColor.textHighEmphasis:b.themedColor.textLowEmphasis,variant:"caption3"},c),g.descriptionNode)})))},Sb=({value:e,src:t,selected:n})=>{const[r,s]=l.useState(!1),o=r?a.createElement(Eb,{value:e,selected:n}):a.createElement(xb,{$selected:n,alt:"","aria-hidden":"true",src:t,onError:()=>s(!0)});return a.createElement(Ib,null,o)},yb=C.default.div`display:flex;flex-direction:column;gap:8px;`,Ab=C.default.div`display:flex;justify-content:space-between;align-self:center;width:100%;max-width:400px;gap:16px;`,Tb=C.default.button`appearance:none;-webkit-appearance:none;background-color:transparent;border:none;padding:0;text-align:center;gap:4px;display:flex;flex-direction:column;align-items:center;justify-content:start;box-sizing:border-box;min-width:48px;max-width:68px;${xe}&:not(:disabled):hover span{color:${b.themedColor.textHighEmphasis};}`,Ib=C.default.div`button:not(:disabled):hover &{border-radius:4px;cursor:pointer;background-color:${b.color.background200};${ne.dark`
|
|
371
|
-
background-color: ${
|
|
368
|
+
`,kS=b.default(B)`align-items:flex-start;line-height:140%;white-space:pre-wrap;padding:0 12px;`,wS=({sendingStatus:e})=>{const t=F.useTheme();switch(e){case"pending":return a.createElement(LS,{size:16},a.createElement(te,{type:"spinner",color:t.colors.messageOutgoing.background,size:16}));case"failed":return a.createElement("div",{style:{marginBottom:2}},a.createElement(te,{type:"error",color:v.themedColor.error,size:16}));case"scheduled":case"canceled":return null;default:return a.createElement("div",{style:{marginBottom:2}},a.createElement(te,{type:"done",color:v.themedColor.secondary,size:16}))}},LS=b.default(It)`margin-bottom:2px;width:16px;height:16px;`,OS=({createdAt:e})=>{const{stringSet:t,format:n}=le();return e?a.createElement(B,{variant:"caption4",color:v.themedColor.textLowEmphasis},n(e,t.DATE_FORMAT__MESSAGE_TIMESTAMP)):null},NS=e=>{const{components:t}=Ht.useContext(),{stringSet:n}=le(),r=()=>{const i=yi(e)?a.createElement(t.TextMessageBody,{...e}):null;return e.messageType==="user"?i:e.messageType==="file"?e.file.type.startsWith("image")?a.createElement(t.MediaMessageBody,{...e},i):a.createElement(t.FileMessageBody,{...e},i):e.messageType==="multipleFiles"?a.createElement(t.MultipleFilesMessageBody,{...e},i):a.createElement(t.TextMessageBody,{...e,message:n.UNKNOWN__UNKNOWN_MESSAGE_TYPE})},s=e.sendingStatus==="failed"&&e.onClickFailedMessage,o=s?Yt({onActivate:()=>{var i;return(i=e.onClickFailedMessage)==null?void 0:i.call(e)}}):{};return a.createElement("div",{...o,style:{display:"contents",cursor:s?"pointer":"default"}},r())},DS=e=>a.createElement(a.Fragment,null),PS=e=>{const{components:t}=Ht.useContext(),n=e.sendingStatus==="succeeded",r=e.groupType==="bottom"||e.groupType==="single";return a.createElement($S,{$marginBottom:Bn(e.groupType)},a.createElement(FS,null,a.createElement(t.MessageBody,{...e})),a.createElement(t.MessageLogs,{...e}),r&&a.createElement(US,{$extraEndPadding:8},n?a.createElement(t.SentTime,{...e}):a.createElement(t.SendingStatus,{...e})))},Ht=Qe({template:PS,components:{SendingStatus:wS,SentTime:OS,MessageBody:NS,TextMessageBody:MS,MediaMessageBody:CS,FileMessageBody:ES,MultipleFilesMessageBody:AS,MessageLogs:DS}}),$S=b.default.div`display:flex;flex:1;flex-direction:column;align-items:flex-end;margin-bottom:${({$marginBottom:e})=>`${e}px`};
|
|
369
|
+
`,cc=b.default.div`display:flex;align-self:stretch;justify-content:flex-end;${({$startPadding:e=re.HORIZONTAL_PADDING,$endPadding:t=re.HORIZONTAL_PADDING,$extraEndPadding:n=0})=>`padding-inline: ${e}px ${t+n}px;`};
|
|
370
|
+
`,FS=b.default(cc)``,US=b.default(cc)`margin-top:${re.BODY_TIME_GAP}px;`,BS=l.lazy(()=>Promise.resolve().then(()=>require("./cjs/TEfZbcKQ.cjs")).then(e=>({default:e.MarkdownText}))),HS=e=>e.messageType!=="admin"?null:a.createElement(VS,null,a.createElement(GS,{forwardedAs:"div",variant:"caption2",color:v.themedColor.textMidEmphasis},a.createElement(yt,{fallback:e.message},a.createElement(zS,{onClickLink:e.onClickLink},e.message)))),GS=b.default(B)`&&{line-height:${4/3};}`,zS=b.default(BS)`&& p{font-size:inherit;line-height:inherit;}&& a{font-weight:inherit;}`,VS=b.default.div`text-align:center;text-wrap:pretty;word-break:break-word;padding-inline:${re.HORIZONTAL_PADDING}px;a{text-decoration:underline;color:inherit;}`,KS=({direction:e,currentIndex:t,totalCount:n})=>n<=0?t:e==="next"?(t+1)%n:(t-1+n)%n,lc=({options:e,value:t,disabled:n,hasError:r=!1,errorId:s,onChange:o})=>{const i=l.useRef([]),c=e.findIndex(h=>h.value===t),u=c>=0?c:0,d=h=>{requestAnimationFrame(()=>{var f;(f=i.current[h])==null||f.focus()})},m=h=>{const f=e[h];!f||n||(o==null||o(f.value),d(h))};return{radioGroupProps:h=>({role:"radiogroup","aria-label":h,...r&&s?{"aria-invalid":!0,"aria-errormessage":s}:{}}),getRadioProps:h=>({ref:f=>{i.current[h]=f},tabIndex:n?-1:h===u?0:-1,describedBy:r&&s?s:void 0,onArrowNavigate:f=>{m(KS({direction:f,currentIndex:h,totalCount:e.length}))}})}},qS=e=>{switch(e.key){case"ArrowDown":case"ArrowRight":return"next";case"ArrowUp":case"ArrowLeft":return"previous";default:return}},WS=({event:e,onClick:t,onArrowNavigate:n})=>{if(YS(e))return;const r=qS(e);if(r){e.preventDefault(),n==null||n(r);return}e.key!=="Enter"&&e.key!==" "||(e.preventDefault(),t==null||t())},YS=e=>e.repeat||e.currentTarget.getAttribute("aria-disabled")==="true",ys=l.forwardRef(({onClick:e,checked:t,label:n,disabled:r,tabIndex:s=0,labelVariant:o="caption2",describedBy:i,onArrowNavigate:c},u)=>{const d=t?v.themedColor.primary:r?v.themedColor.textDisabled:v.themedColor.textLowEmphasis,m=t?v.themedColor.textHighEmphasis:r?v.themedColor.textLowEmphasis:v.themedColor.textHighEmphasis;return a.createElement(ZS,{ref:u,role:"radio",tabIndex:r?-1:s,"aria-checked":t,"aria-disabled":!!r,"aria-label":n,"aria-describedby":i,onClick:r?void 0:e,onKeyDown:h=>WS({event:h,onClick:e,onArrowNavigate:c})},a.createElement(jS,{"aria-hidden":"true"},a.createElement(te,{size:20,type:t?"radio-on":"radio-off",color:d})),a.createElement(XS,{"aria-hidden":"true",variant:o,color:m},n))});ys.displayName="Radio";const jS=b.default.div`width:20px;height:20px;`,XS=b.default(B)`line-height:20px;word-break:break-word;`,ZS=b.default.div`display:flex;align-items:flex-start;justify-content:flex-start;gap:2px;${ke}&[aria-disabled='false']{cursor:pointer;}`,JS=({csatPayload:e,submitted:t,defaultValue:n,value:r,onChange:s})=>{var u,d;const o=[{label:((u=e.cre)==null?void 0:u.positive_label)??"",value:!0},{label:((d=e.cre)==null?void 0:d.negative_label)??"",value:!1}],i=lc({options:o,value:r,disabled:t,onChange:s});if(l.useEffect(()=>{typeof r>"u"&&typeof n=="boolean"&&(s==null||s(n))},[r,n]),!e.cre)return null;const c=e.cre;return a.createElement(QS,null,a.createElement(Ne.Label,{required:c.required,"aria-hidden":!0},c.question),a.createElement(eb,{...i.radioGroupProps(c.question)},o.map((m,h)=>a.createElement(ys,{key:m.label,checked:r===m.value,label:m.label,disabled:t,...i.getRadioProps(h),onClick:()=>s==null?void 0:s(m.value)}))))},QS=b.default.div`display:flex;flex-direction:column;gap:8px;`,eb=b.default.div`display:flex;flex-direction:column;gap:8px;`,tb=({followUpItem:e,submitted:t,value:n="",onChange:r,hasError:s})=>{const{stringSet:o}=le(),{conversation:i}=ue(),c=l.useId(),u=l.useId(),d=e.response_type!=="free_text",m=e.response_type==="single_choice"?e.options.map(f=>({label:f,value:f})):[],h=lc({options:m,value:n,disabled:t,hasError:s,errorId:c,onChange:r});return a.createElement(nb,null,a.createElement(Ne.Label,{id:u,required:e.required,"aria-hidden":d},e.question),e.response_type==="free_text"&&a.createElement(Ne.TextInput,{variant:"multi-line",disabled:t,submitted:t,maxLength:100,value:n,onChange:f=>r(f),error:s,...i.form.textInput(o.A11Y_CSAT_TEXT_INPUT_LABEL,e.required??!1,t,{labelId:u}).props,"aria-invalid":s,"aria-errormessage":s?c:void 0}),e.response_type==="single_choice"&&a.createElement(rb,{...h.radioGroupProps(e.question)},m.map((f,g)=>a.createElement(ys,{key:f.value,checked:n===f.value,label:f.label,disabled:t,...h.getRadioProps(g),onClick:()=>r==null?void 0:r(f.value),labelVariant:"body3"}))),s&&a.createElement(sb,{role:"alert",id:c},o.FORM_VALIDATION_REQUIRED))},nb=b.default.div`display:flex;flex-direction:column;gap:8px;`,rb=b.default.div`display:flex;flex-direction:column;gap:8px;`,sb=b.default(Ne.ErrorLabel)``,ob=({value:e,selected:t})=>a.createElement(ib,{$selected:t,"aria-hidden":"true"},ab[e-1]),ib=b.default.div`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,ab=[a.createElement("svg",{width:"40",height:"40",viewBox:"0 0 40 40",fill:"none",xmlns:"http://www.w3.org/2000/svg"},a.createElement("path",{d:"M2.08337 19.9999C2.08337 10.1048 10.1049 2.08325 20 2.08325C29.8952 2.08325 37.9167 10.1048 37.9167 19.9999C37.9167 29.8951 29.8952 37.9166 20 37.9166C10.1049 37.9166 2.08337 29.8951 2.08337 19.9999Z",fill:"url(#paint0_linear_159_173206)"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M12.5828 29.3328C13.1348 29.7473 13.9184 29.636 14.3329 29.084C15.6272 27.3607 17.6839 26.25 20 26.25C22.3164 26.25 24.373 27.3607 25.6672 29.084C26.0819 29.636 26.8654 29.7473 27.4175 29.3328C27.9695 28.9182 28.0809 28.1347 27.6662 27.5825C25.9202 25.2577 23.136 23.75 20 23.75C16.8642 23.75 14.0801 25.2577 12.334 27.5825C11.9194 28.1347 12.0308 28.9182 12.5828 29.3328Z",fill:"#141B34"}),a.createElement("path",{d:"M28.4454 13.7707C29.1329 13.8328 29.6405 14.4406 29.5785 15.1281C29.5165 15.8153 28.9095 16.3221 28.2224 16.2608C28.2224 16.2608 28.0287 16.2502 27.9272 16.2487C27.7229 16.2457 27.4387 16.2509 27.1229 16.2833C26.7869 16.3177 26.4649 16.3782 26.1804 16.4662L26.3045 16.86C26.7797 18.3675 25.5099 19.5813 24.2062 19.5813C23.5045 19.5813 22.8324 19.2617 22.43 18.6857C22.003 18.0745 21.9422 17.241 22.408 16.5344C22.751 16.0143 23.2449 15.3831 23.8964 14.8657C24.836 14.1195 26.044 13.8809 26.8675 13.7963C27.3029 13.7517 28.0154 13.7319 28.4454 13.7707Z",fill:"#141B34"}),a.createElement("path",{d:"M11.5549 13.7707C10.8674 13.8328 10.3597 14.4406 10.4218 15.1281C10.4838 15.8153 11.0908 16.3221 11.7779 16.2608C11.7779 16.2608 11.9716 16.2502 12.073 16.2487C12.2774 16.2457 12.5616 16.2509 12.8774 16.2833C13.2134 16.3177 13.5353 16.3782 13.8199 16.4662L13.6958 16.86C13.2205 18.3675 14.4904 19.5813 15.794 19.5813C16.4958 19.5813 17.168 19.2617 17.5703 18.6857C17.9971 18.0745 18.0581 17.241 17.5921 16.5344C17.2493 16.0143 16.7553 15.3831 16.1039 14.8657C15.1643 14.1195 13.9562 13.8809 13.1327 13.7963C12.6974 13.7517 11.9849 13.7319 11.5549 13.7707Z",fill:"#141B34"}),a.createElement("defs",null,a.createElement("linearGradient",{id:"paint0_linear_159_173206",x1:"20",y1:"2.08325",x2:"20",y2:"37.9166",gradientUnits:"userSpaceOnUse"},a.createElement("stop",{stopColor:"#FF2D1D"}),a.createElement("stop",{offset:"1",stopColor:"#FFA540"})))),a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},a.createElement("path",{d:"M2.083 20C2.083 10.105 10.105 2.083 20 2.083c9.895 0 17.917 8.021 17.917 17.917 0 9.895-8.022 17.917-17.917 17.917C10.105 37.917 2.083 29.895 2.083 20Z",fill:"#FFD46E"}),a.createElement("path",{d:"M14.249 27.334C15.851 26.13 17.844 25.417 20 25.417c2.156 0 4.149.714 5.751 1.917.553.415.664 1.199.25 1.751-.415.552-1.199.664-1.751.25-1.183-.889-2.652-1.416-4.25-1.416s-3.067.527-4.25 1.416c-.553.414-1.336.302-1.751-.25-.415-.552-.303-1.336.249-1.751Z",fill:"#141B34"}),a.createElement("path",{d:"M23.445 14.596c-.687.062-1.294-.445-1.356-1.132-.062-.687.445-1.295 1.132-1.357.082-.005.342-.02.482-.022.277-.004.662.002 1.097.047.823.085 2.031.323 2.97 1.07.652.518 1.146 1.15 1.489 1.67.466.706.405 1.54-.022 2.15-.402.576-1.074.896-1.775.896-1.304 0-2.573-1.214-2.098-2.722l.125-.394c-.285-.088-.607-.148-.942-.182-.316-.033-.6-.038-.804-.035-.101.002-.242.01-.294.013Z",fill:"#141B34"}),a.createElement("path",{d:"M11.779 14.596c-.687.062-1.294-.445-1.356-1.132-.062-.687.445-1.295 1.132-1.357.082-.005.342-.02.482-.022.277-.004.662.002 1.097.047.823.085 2.031.323 2.97 1.07.652.518 1.146 1.15 1.489 1.67.466.706.405 1.54-.022 2.15-.402.576-1.074.896-1.775.896-1.304 0-2.573-1.214-2.098-2.722l.124-.394c-.284-.088-.606-.148-.941-.182-.316-.033-.6-.038-.804-.035-.101.002-.243.01-.294.013Z",fill:"#141B34"})),a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},a.createElement("path",{d:"M2.083 20C2.083 10.105 10.105 2.083 20 2.083c9.895 0 17.917 8.021 17.917 17.917 0 9.895-8.022 17.917-17.917 17.917C10.105 37.917 2.083 29.895 2.083 20Z",fill:"#FFD46E"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M11.25 15c0-1.151.933-2.083 2.083-2.083h.015c1.151 0 2.084.933 2.084 2.083 0 1.151-.933 2.083-2.084 2.083h-.015c-1.15 0-2.083-.933-2.083-2.083ZM24.568 15c0-1.151.933-2.083 2.084-2.083h.015c1.151 0 2.083.933 2.083 2.083 0 1.151-.932 2.083-2.083 2.083h-.015c-1.151 0-2.084-.933-2.084-2.083Z",fill:"#141B34"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M13.75 26.667c0-.691.56-1.25 1.25-1.25h10c.69 0 1.25.559 1.25 1.25 0 .691-.56 1.25-1.25 1.25h-10c-.69 0-1.25-.559-1.25-1.25Z",fill:"#141B34"})),a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},a.createElement("path",{d:"M2.083 20C2.083 10.105 10.105 2.083 20 2.083c9.895 0 17.917 8.021 17.917 17.917 0 9.895-8.022 17.917-17.917 17.917C10.105 37.917 2.083 29.895 2.083 20Z",fill:"#FFD46E"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M12.583 24.001c.552-.414 1.335-.302 1.75.25 1.294 1.723 3.35 2.834 5.667 2.834s4.373-1.11 5.667-2.834c.415-.552 1.199-.664 1.751-.25.552.415.664 1.199.25 1.751C25.92 28.076 23.136 29.584 20 29.584s-5.92-1.508-7.666-3.832c-.415-.552-.303-1.336.249-1.751Z",fill:"#141B34"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M11.25 15c0-1.151.933-2.083 2.083-2.083h.015c1.151 0 2.084.933 2.084 2.083 0 1.151-.933 2.083-2.084 2.083h-.015c-1.15 0-2.083-.933-2.083-2.083ZM24.568 15c0-1.151.933-2.083 2.084-2.083h.015c1.151 0 2.083.933 2.083 2.083 0 1.151-.932 2.083-2.083 2.083h-.015c-1.151 0-2.084-.933-2.084-2.083Z",fill:"#141B34"})),a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},a.createElement("path",{d:"M2.083 20C2.083 10.105 10.105 2.083 20 2.083c9.895 0 17.917 8.021 17.917 17.917 0 9.895-8.022 17.917-17.917 17.917C10.105 37.917 2.083 29.895 2.083 20Z",fill:"#FFD46E"}),a.createElement("g",{clipPath:"url(#clip0_159_173224)"},a.createElement("g",{clipPath:"url(#clip1_159_173224)"},a.createElement("path",{d:"M20 30.624c3.752 0 6.904-2.532 7.789-5.956.412-1.593-.185-1.959-1.76-1.959H13.973c-1.575 0-2.173.366-1.761 1.959.885 3.424 4.037 5.956 7.788 5.956Z",fill:"#141B34"})),a.createElement("mask",{id:"mask0_159_173224",style:{maskType:"alpha"},maskUnits:"userSpaceOnUse",x:"12",y:"22",width:"16",height:"9"},a.createElement("path",{d:"M20 30.624c3.752 0 6.904-2.532 7.789-5.956.412-1.593-.185-1.959-1.76-1.959H13.973c-1.575 0-2.173.366-1.761 1.959.885 3.424 4.037 5.956 7.788 5.956Z",fill:"#141B34"})),a.createElement("g",{mask:"url(#mask0_159_173224)"},a.createElement("path",{d:"M20 32.998c3.278 0 5.936-1.594 5.936-3.561 0-1.968-2.658-3.562-5.936-3.562-3.278 0-5.936 1.594-5.936 3.562 0 1.967 2.658 3.561 5.936 3.561Z",fill:"#FF493B"}))),a.createElement("path",{d:"M11.667 15.833c0-1.381 1.12-2.5 2.5-2.5s2.5 1.12 2.5 2.5M23.333 15.833c0-1.381 1.12-2.5 2.5-2.5s2.5 1.12 2.5 2.5",stroke:"#141B34",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"}),a.createElement("defs",null,a.createElement("clipPath",{id:"clip0_159_173224"},a.createElement("rect",{width:"15.83",height:"7.915",fill:"white",transform:"translate(12.085 22.709)"})),a.createElement("clipPath",{id:"clip1_159_173224"},a.createElement("rect",{width:"15.83",height:"7.915",fill:"white",transform:"translate(12.085 22.709)"}))))],cb=({csatPayload:e,submitted:t,value:n,onChange:r})=>{const s=typeof n>"u",{conversation:o}=ue(),i=o.csat.scoresContainer(e.csat_question);return a.createElement(ub,null,a.createElement(B,{variant:"caption3",color:v.themedColor.textMidEmphasis,"aria-hidden":"true"},e.csat_question),a.createElement(db,{...i.props},i.descriptionNode,e.csat_scores.map(({label:c,image_url:u},d)=>{const m=d+1,h=n===m,f=e.csat_scores.length,g=o.csat.scoreItem({score:m,label:c,selected:h,disabled:t,currentIndex:d,totalCount:f,hasSelection:!s,onChange:r});return a.createElement(mb,{key:d,type:"button",...g.props},a.createElement(lb,{value:m,selected:s||h,src:u}),!!c&&a.createElement(B,{"aria-hidden":"true",color:h?v.themedColor.textHighEmphasis:v.themedColor.textLowEmphasis,variant:"caption3"},c),g.descriptionNode)})))},lb=({value:e,src:t,selected:n})=>{const[r,s]=l.useState(!1),o=r?a.createElement(ob,{value:e,selected:n}):a.createElement(fb,{$selected:n,alt:"","aria-hidden":"true",src:t,onError:()=>s(!0)});return a.createElement(hb,null,o)},ub=b.default.div`display:flex;flex-direction:column;gap:8px;`,db=b.default.div`display:flex;justify-content:space-between;align-self:center;width:100%;max-width:400px;gap:16px;`,mb=b.default.button`appearance:none;-webkit-appearance:none;background-color:transparent;border:none;padding:0;text-align:center;gap:4px;display:flex;flex-direction:column;align-items:center;justify-content:start;box-sizing:border-box;min-width:48px;max-width:68px;${ke}&:not(:disabled):hover span{color:${v.themedColor.textHighEmphasis};}`,hb=b.default.div`button:not(:disabled):hover &{border-radius:4px;cursor:pointer;background-color:${v.color.background200};${ne.dark`
|
|
371
|
+
background-color: ${v.color.background500};
|
|
372
372
|
`}
|
|
373
373
|
}
|
|
374
|
-
`,
|
|
375
|
-
background-color: ${
|
|
374
|
+
`,fb=b.default.img`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,gb=({csatPayload:e})=>a.createElement(B,{variant:"button",color:v.themedColor.textHighEmphasis},e.title),Cr=({csatPayload:e,type:t,renderSubmitButton:n,initialCsat:r,initialCsatReason:s,initialIsResolved:o})=>{const{params:i,setParams:c,error:u,setError:d,followUpItem:m,state:h,validateParams:f,itemProps:g}=Wh({csatPayload:e,type:t,initialCsat:r,initialCsatReason:s,initialIsResolved:o});return a.createElement(a.Fragment,null,a.createElement(pb,null,a.createElement(gb,{...g}),t===st.AI_AGENT_CSAT_5_WITH_CRE&&a.createElement(JS,{...g,defaultValue:o,value:i.isResolved,onChange:p=>c({isResolved:p})}),a.createElement(cb,{...g,value:i.csat,onChange:p=>c({csat:p})}),m&&a.createElement(tb,{...g,followUpItem:m,value:i.csatReason,onChange:p=>{c({csatReason:p}),d({followUpItem:!1})},hasError:u.followUpItem})),h!=="unsubmittable"&&a.createElement(a.Fragment,null,a.createElement(Ne.Separator,null),n({state:h,params:i,validateParams:f})))},pb=b.default.div`display:flex;flex-direction:column;gap:12px;`,Eb=e=>{const{stringSet:t}=le();return Gl(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})},_b=()=>{const{stringSet:e}=le();return a.createElement(B,{variant:"body2",color:v.themedColor.textMidEmphasis,style:{textAlign:"center"}},e.CSAT_SUBMISSION_EXPIRED)},Cb=({onMount:e,children:t})=>(l.useEffect(()=>{e&&Re(e)},[]),t),Sb=e=>{const{conversation:t}=ue();if(e.messageType!=="admin.csat")throw new Error("Invalid message type");const{extendedMessagePayload:n,onSubmitCSAT:r,onScrollToBottom:s}=e,{csat:o,csatReason:i,csatExpireAt:c,isResolvedWhenDeterminedByUser:u}=e,d=Hn(),m=Eb(n==null?void 0:n.csat),h=l.useRef(null),f=l.useRef(null),[g,p]=l.useState(!1),C=l.useRef(!1),E=l.useCallback(()=>{Re(()=>{var M;return(M=f.current)==null?void 0:M.focus()})},[]),{isExpiredNow:_,isRenderableCSAT:A}=Yh({csat:o,csatExpireAt:c,csatPayload:m,isSubmitInFlight:g});if(Kh({csat:o,csatPayload:m,isRenderableCSAT:A,isExpiredNow:_,announceStatus:e.announceStatus,onSubmittedAnnounced:E}),!A||!m)return null;const y=()=>{var O;const M=(O=h.current)==null?void 0:O.querySelector('[aria-invalid="true"]');return M?M.getAttribute("role")==="radiogroup"?M.querySelector('[role="radio"]'):M:null},T=m.type===st.AI_AGENT_CSAT_5||m.type===st.AI_AGENT_CSAT_5_WITH_CRE||m.type===st.HELPDESK_CSAT_5?Cr:()=>null;return a.createElement(bb,{ref:h},!o&&_?a.createElement(_b,null):a.createElement(T,{csatPayload:m,type:m.type,initialCsat:o,initialCsatReason:i,initialIsResolved:u,renderSubmitButton:({state:M,params:O,validateParams:w})=>M==="submitted"?a.createElement(yb,{ref:f,role:"status","aria-live":"polite","aria-atomic":"true","aria-label":m.csat_submitted_label,tabIndex:-1},a.createElement(B,{variant:"button","aria-hidden":"true"},m.csat_submitted_label)):a.createElement(Cb,{onMount:s},a.createElement(vb,{type:"button",...t.csat.submitButton(m.csat_submit_label).props,onClick:async()=>{if(C.current)return;const R=Ri(c);if(!R&&w()){C.current=!0,p(!0);try{await r(O)}catch(x){throw C.current=!1,p(!1),x}}else d(),R||Re(()=>{var x;(x=e.announceError)==null||x.call(e,{type:"csatFormError"},y())})}},a.createElement(B,{variant:"button"},m.csat_submit_label)))}))},bb=b.default.div`display:flex;flex-direction:column;background-color:${({theme:e})=>e.colors.csat.background};border-radius:16px;gap:16px;padding:16px;`,vb=b.default.button`all:unset;width:100%;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.primary};color:${({theme:e})=>e.colors.base.primaryContrastContent};border-radius:6px;padding:10px 20px;display:flex;align-items:center;justify-content:center;cursor:pointer;text-align:center;word-break:break-word;${ke}&:hover{background-color:${v.color.primary.dark};}`,yb=b.default.div`width:100%;box-sizing:border-box;color:${v.themedColor.textHighEmphasis};background-color:${v.color.background200};border-radius:6px;padding:10px 20px;display:flex;align-items:center;justify-content:center;text-align:center;word-break:break-word;${ne.dark`
|
|
375
|
+
background-color: ${v.color.onlight.textDisabled};
|
|
376
376
|
`}
|
|
377
|
-
`,
|
|
378
|
-
`,
|
|
379
|
-
background-color: ${
|
|
377
|
+
`,Ab=e=>{const{components:t}=jn.useContext(),n=e.messageType==="admin"?a.createElement(t.AdminMessage,{...e}):e.messageType==="admin.csat"?a.createElement(t.CSATMessage,{...e}):null;return a.createElement(Tb,{$marginBottom:Bn(e.groupType)},n)},jn=Qe({template:Ab,components:{AdminMessage:HS,CSATMessage:Sb}}),Tb=b.default.div`padding-inline:${re.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>e}px;`,As=({title:e,titleId:t,description:n,descriptionId:r,negativeText:s,positiveText:o,onCancel:i,onConfirm:c,buttonLayout:u="horizontal",styles:d})=>{const m=s!==void 0&&i!==void 0,h=o!==void 0&&c!==void 0,f=m?a.createElement(kb,{type:"button",onClick:i,$fullWidth:u!=="horizontal",$background:d==null?void 0:d.negativeBackground,$borderColor:d==null?void 0:d.negativeBorderColor},a.createElement(B,{variant:"button",color:(d==null?void 0:d.negativeText)??v.themedColor.textHighEmphasis},s)):null,g=h?a.createElement(wb,{type:"button",onClick:c,$fullWidth:u!=="horizontal",$background:d==null?void 0:d.positiveBackground,$borderColor:d==null?void 0:d.positiveBorderColor},a.createElement(B,{variant:"button",color:(d==null?void 0:d.positiveText)??v.themedColor.textHighEmphasisInverse},o)):null;return a.createElement(Ib,null,a.createElement(xb,null,a.createElement(B,{as:"div",id:t,variant:"h2",color:(d==null?void 0:d.titleColor)??v.themedColor.textHighEmphasis},e)),a.createElement(Mb,null,a.createElement(B,{as:"div",id:r,variant:"body3",color:(d==null?void 0:d.descriptionColor)??v.themedColor.textMidEmphasis},n)),a.createElement(Rb,{$buttonLayout:u},u==="horizontal"?a.createElement(a.Fragment,null,f,g):a.createElement(a.Fragment,null,g,f)))},Ib=b.default.div`display:flex;flex-direction:column;width:280px;border-radius:16px;overflow:hidden;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,xb=b.default.div`padding:24px 24px 16px;`,Mb=b.default.div`padding-inline:24px;`,Rb=b.default.div`display:flex;flex-direction:${({$buttonLayout:e})=>e==="vertical-full-width"?"column":"row"};align-items:center;justify-content:flex-end;gap:4px;padding:16px 24px;`,kb=b.default.button`display:flex;align-items:center;justify-content:center;box-sizing:border-box;width:${({$fullWidth:e})=>e?"100%":"auto"};padding:12px 20px;border-radius:20px;cursor:pointer;border:1px solid ${({$borderColor:e})=>e??"transparent"};background:${({$background:e})=>e??"none"};white-space:nowrap;overflow:hidden;text-overflow:ellipsis;&:hover{opacity:0.8;}`,wb=b.default.button`display:flex;align-items:center;justify-content:center;box-sizing:border-box;width:${({$fullWidth:e})=>e?"100%":"auto"};padding:12px 20px;border-radius:20px;cursor:pointer;border:1px solid ${({$borderColor:e})=>e??"transparent"};background-color:${({$background:e})=>e??v.themedColor.textHighEmphasis};white-space:nowrap;overflow:hidden;text-overflow:ellipsis;&:hover{opacity:0.8;}`,bn=16,Lb=({status:e})=>e===Mn.COMPLETED?a.createElement(te,{type:"done-circle",size:bn,color:v.themedColor.textHighEmphasis}):e===Mn.CANCELED?a.createElement(te,{type:"stop-circle",size:bn,color:v.themedColor.textLowEmphasis}):a.createElement(It,{size:bn},a.createElement(te,{type:"spinner",size:bn,color:v.themedColor.textHighEmphasis})),uc=24,Ob=8,Nb=40,Db=({task:e,isFirst:t,isLast:n})=>a.createElement(Pb,{role:"listitem"},a.createElement($b,null,a.createElement(Zo,{$hidden:t}),a.createElement(Fb,null,a.createElement(Lb,{status:e.status})),a.createElement(Zo,{$hidden:n})),a.createElement(Ub,null,a.createElement(B,{as:"div",variant:"body3",color:e.status===Mn.CANCELED?v.themedColor.textLowEmphasis:v.themedColor.textHighEmphasis},e.user_facing_title))),Pb=b.default.div`display:flex;gap:4px;`,$b=b.default.div`display:flex;flex-direction:column;align-items:center;width:${uc}px;flex-shrink:0;`,Zo=b.default.div`width:1px;flex:1;transform:translateX(-25%);${({$hidden:e})=>e&&"visibility: hidden;"}background-image:repeating-linear-gradient( to bottom,${v.themedColor.textHighEmphasis}0 2px,transparent 2px 4px );`,Fb=b.default.div`display:flex;height:${uc}px;align-items:center;justify-content:center;`,Ub=b.default.div`display:flex;flex:1;align-items:center;box-sizing:border-box;min-width:0;min-height:${Nb}px;padding-block:${Ob}px;`,Bb=({steward:e,onCancelSteward:t})=>{const{logger:n}=ge(),[r,s]=l.useState(!1),[o,i]=l.useState(!1),c=!!e.cancellation_option,u=Qc(e.status);return a.createElement(Hb,{$marginBottom:Bn("single")},a.createElement(Gb,null,a.createElement(zb,null,a.createElement(Vb,null,a.createElement(B,{as:"div",variant:"caption1",color:v.themedColor.textHighEmphasis},e.title),!!e.description&&a.createElement(B,{as:"div",variant:"caption4",color:v.themedColor.textLowEmphasis},e.description)),c&&a.createElement(Yb,{type:"button","aria-label":"Stop steward",disabled:o,onClick:()=>s(!0)},a.createElement(te,{type:"stop",size:16,color:o?v.themedColor.textDisabled:v.themedColor.textHighEmphasis}))),a.createElement(Kb,null),e.tasks.length===0?u!==Xt.IN_PROGRESS?null:a.createElement(Wb,null,a.createElement(It,{size:16},a.createElement(te,{type:"spinner",size:16,color:v.themedColor.textHighEmphasis}))):a.createElement(qb,{role:"list"},e.tasks.map((d,m)=>a.createElement(Db,{key:d.id,task:d,isFirst:m===0,isLast:m===e.tasks.length-1})))),r&&e.cancellation_option&&a.createElement(St,{portalContainerId:Te.WINDOW,visible:r,onClose:()=>s(!1)},a.createElement(As,{title:e.cancellation_option.title,description:e.cancellation_option.description,negativeText:e.cancellation_option.negative_text,positiveText:e.cancellation_option.positive_text,onCancel:()=>s(!1),onConfirm:async()=>{s(!1),i(!0);try{await(t==null?void 0:t())}catch(d){n.warn("steward.cancelSteward: failed",d)}finally{i(!1)}}})))},Hb=b.default.div`display:flex;flex-direction:column;margin:0 ${re.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>`${e}px`};
|
|
378
|
+
`,Gb=b.default.div`display:flex;flex-direction:column;border-radius:12px;overflow:hidden;padding:16px;border:1px solid ${v.themedColor.bg_300_500};background-color:${v.themedColor.bg_50_600};box-shadow:0 8px 20px rgba(0,0,0,0.12);`,zb=b.default.div`display:flex;flex-direction:row;align-items:flex-start;gap:8px;`,Vb=b.default.div`display:flex;flex-direction:column;gap:4px;flex:1;min-width:0;`,Kb=b.default.div`height:1px;margin-block:12px;background-color:${v.themedColor.bg_200_400};`,qb=b.default.div`display:flex;flex-direction:column;`,Wb=b.default.div`display:flex;width:100%;height:40px;align-items:center;justify-content:center;`,Yb=b.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:${v.themedColor.textHighEmphasis};background-color:${v.themedColor.bg_200_400};&:hover:not(:disabled){opacity:0.8;}&:disabled{cursor:default;}`,jb=({className:e,label:t,onClick:n})=>{const{colors:r}=F.useTheme(),{conversation:s}=ue(),o={newMessages:s.newMessagesButton()};return a.createElement(Xb,{className:e,onClick:n,...o.newMessages.props},a.createElement(B,{variant:"button",color:r.base.primaryContrastContent},t),a.createElement(te,{size:16,type:"chevron-down",color:r.base.primaryContrastContent}),o.newMessages.descriptionNode)},Xb=b.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;}${ke}`,Ts=({iconSize:e=64,icon:t,className:n,label:r,children:s})=>a.createElement(Jb,{className:n},t&&a.createElement(te,{type:t,size:e,color:v.themedColor.textLowEmphasis}),r&&a.createElement(B,{variant:"body1",color:v.themedColor.textMidEmphasis},r),s),Zb=b.default.div`position:relative;display:flex;justify-content:center;align-items:center;width:100%;height:100%;`,Jb=b.default.div`display:flex;flex-direction:column;min-height:104px;align-items:center;gap:20px;text-align:center;`,Qb=({label:e="Something went wrong",icon:t="error",action:n,...r})=>a.createElement(Ts,{icon:t,label:e,...r},n&&a.createElement(ev,{onClick:n.onClick,label:n.label??"Retry"})),ev=({label:e,onClick:t})=>{const{conversation:n}=ue();return a.createElement(tv,{tabIndex:0,...n.retryButton(e).props,onClick:t},a.createElement(te,{type:"refresh",size:20}),a.createElement(B,{variant:"button",color:v.color.primary.main},e))},tv=b.default.button`all:unset;display:flex;cursor:pointer;gap:4px;align-items:center;justify-content:center;${ke}`,nv=({iconSize:e=48,className:t})=>a.createElement(It,{size:e,className:t}),rv=({label:e="No channels",icon:t="chat",...n})=>a.createElement(Ts,{icon:t,label:e,...n}),sv=({label:e="No messages",icon:t="message",...n})=>a.createElement(Ts,{icon:t,label:e,...n}),ov=e=>{const{components:t}=Xn.useContext(),n=e.type==="loading"?a.createElement(t.Loading,{...e}):e.type==="error"?a.createElement(t.Error,{...e}):e.type==="noChannels"?a.createElement(t.NoChannels,{...e}):e.type==="noMessages"?a.createElement(t.NoMessages,{...e}):null;return n&&a.createElement(Zb,null,n)},Xn=Qe({template:ov,components:{Loading:nv,Error:Qb,NoChannels:rv,NoMessages:sv}}),Jt=e=>{const{Template:t}=Xn.useContext();return a.createElement(t,{...e})},iv=[0,150,450];function av({enabled:e}){const{state:t,actions:n}=Da(),r=l.useRef(0),s=l.useRef(t.isAwayFromBottom);s.current=t.isAwayFromBottom,l.useEffect(()=>{if(!e){r.current+=1;return}const o=r.current+1;r.current=o;const i=iv.map(c=>setTimeout(()=>{Re(()=>{r.current===o&&(s.current||n.scrollToBottom(!1))})},c));return()=>{r.current+=1,i.forEach(c=>clearTimeout(c))}},[n.scrollToBottom,e])}const cv=({className:e,date:t=Date.now(),role:n,style:r})=>{const{format:s,stringSet:o}=le();return a.createElement(lv,{id:`${ze}-date-separator`,role:n,style:r,className:e},a.createElement(B,{variant:"caption4",color:v.themedColor.textMidEmphasis},s(t,o.DATE_FORMAT__MESSAGE_LIST__DATE_SEPARATOR)))},lv=b.default.div`display:flex;justify-content:center;align-items:center;text-align:center;word-break:break-word;`,uv=({className:e,style:t,onClick:n})=>{const{conversation:r}=ue(),s={scrollToBottom:r.scrollToBottomButton()};return a.createElement(dv,{className:e,style:t,onClick:n,tabIndex:0,...s.scrollToBottom.props},a.createElement(te,{size:24,type:"chevron-down",color:v.color.primary.main}),s.scrollToBottom.descriptionNode??null)},dv=b.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);${ne.light`
|
|
379
|
+
background-color: ${v.color.background50};
|
|
380
380
|
&:hover {
|
|
381
|
-
background-color: ${
|
|
381
|
+
background-color: ${v.color.background100};
|
|
382
382
|
}
|
|
383
383
|
&:active {
|
|
384
|
-
background-color: ${
|
|
384
|
+
background-color: ${v.color.background200};
|
|
385
385
|
}
|
|
386
386
|
`}
|
|
387
387
|
${ne.dark`
|
|
388
|
-
background-color: ${
|
|
388
|
+
background-color: ${v.color.background400};
|
|
389
389
|
&:hover {
|
|
390
|
-
background-color: ${
|
|
390
|
+
background-color: ${v.color.background500};
|
|
391
391
|
}
|
|
392
392
|
&:active {
|
|
393
|
-
background-color: ${
|
|
393
|
+
background-color: ${v.color.background700};
|
|
394
394
|
}
|
|
395
395
|
`}
|
|
396
396
|
|
|
@@ -398,45 +398,45 @@ $2
|
|
|
398
398
|
outline: none;
|
|
399
399
|
}
|
|
400
400
|
|
|
401
|
-
${
|
|
402
|
-
`,
|
|
403
|
-
background-color: ${
|
|
404
|
-
border-color: ${
|
|
401
|
+
${ke}
|
|
402
|
+
`,mv=()=>null,Zn=Qe({template:mv,components:{DateSeparator:cv,ScrollToBottomButton:uv}}),hv=()=>{const{stringSet:e,format:t}=le(),{agentPreviewConfigs:n={},aiAgentId:r}=ge(),{aiAgentInfo:s}=De(),{messageSource:o}=Me(),{Template:i}=_t.useContext(),{components:c}=Zn.useContext(),u=n.welcomeMessages??[],d=o.messages,m=Zp(d,r),h=d[m.length+1],f=m[0]??h;return{filteredMessages:Ha(d,{previewWelcomeMessages:u,aiAgentUserId:r}),shouldShowOriginalDate:g=>g>0||u.length===0?!0:h&&!gt.isSameDay(h.createdAt,(f==null?void 0:f.createdAt)??0),renderAgentPreviewWelcomeMessages:()=>u.length===0?null:a.createElement(a.Fragment,null,a.createElement(c.DateSeparator,{role:"listitem",style:{margin:"16px 0"},date:f==null?void 0:f.createdAt}),u.map((g,p)=>{const C=p===u.length-1,E=m.length!==d.length,_=u.length===1?"single":p===0?"top":C||E?"bottom":"middle",A=(f==null?void 0:f.createdAt)??Date.now();return a.createElement("div",{key:p,role:"listitem",tabIndex:-1,"aria-label":Zt({sender:(s==null?void 0:s.nickname)||"",message:g.message,messageFormat:"markdown",time:t(A,e.DATE_FORMAT__MESSAGE_TIMESTAMP),codeBlockPlaceholder:e.A11Y_CODE_BLOCK_PLACEHOLDER}),"data-message-listitem":""},a.createElement(i,{messageType:"user",message:g.message,sender:s,groupType:_,createdAt:A,extendedMessagePayload:{suggested_replies:g.suggestedReplies},suggestedRepliesDirection:n.suggestedRepliesDirection,suggestedRepliesVisible:C&&!E,isBotMessage:!0,onClickSuggestedReply:async({reply:y})=>{o.sendUserMessage({message:y})}}))}))}},fv=()=>{const{messageSource:e,scrollSource:t}=Me();l.useEffect(()=>{!t.state.isAwayFromBottom&&t.state.isScrollPositionReconciled&&e.resetNewMessages()},[t.state.isAwayFromBottom,t.state.isScrollPositionReconciled])},Jo="https://delight.ai?utm_medium=product&utm_source=aiagent&utm_campaign=fy26-glbl-ai-agent-poweredby",gv=({style:e})=>{const{stringSet:t}=le(),{handlers:n}=ge(),{conversation:r}=ue();return ls("powered-by")?a.createElement(pv,{variant:"caption2",style:e},t.POWERED_BY+" ",a.createElement(Ev,{variant:"caption2",forwardedAs:"a",href:Jo,...r.poweredByLink().props,rel:fa,target:"_blank",onClick:o=>{o.preventDefault(),n.onClickLink({url:Jo})}},"Sendbird")):null},pv=b.default(B)`color:${v.themedColor.textLowEmphasis};text-align:center;`,Ev=b.default(B)`color:${v.themedColor.textLowEmphasis};cursor:pointer;text-decoration:none;`,_v=()=>{var c;const{stringSet:e}=le(),{conversation:t}=ue(),{channelSource:n,goToActiveConversation:r,scrollSource:s}=Me(),o=$e(n.channel),i=l.useRef(o);return l.useEffect(()=>{if(!i.current&&o){const m=setTimeout(()=>{s.actions.scrollToBottom()},100);return()=>clearTimeout(m)}i.current=o},[o,s.actions.scrollToBottom]),!((c=n.channel)!=null&&c.isAIAgent)||!o?null:a.createElement(Cv,null,a.createElement(Sv,{variant:"button",color:v.themedColor.textHighEmphasis,...t.startNewConversationButton({onActivate:r}).props},e.TALK_TO_AGENT))},Cv=b.default.div`display:flex;justify-content:center;margin-bottom:16px;`,Sv=b.default(B)`border-radius:6px;box-sizing:border-box;padding:10px 20px;cursor:pointer;user-select:none;background-color:${v.color.background50};border:1px solid ${v.color.onlight.textDisabled};${ne.dark`
|
|
403
|
+
background-color: ${v.color.background700};
|
|
404
|
+
border-color: ${v.color.ondark.textLowEmphasis};
|
|
405
405
|
`}
|
|
406
|
-
`,Nv=({statsCallbacks:e,...t})=>(Ih(e),a.createElement(Qb,{...t})),Dv=(e,t,n)=>t&&we.isWelcomeMessage(e,n)&&we.isWelcomeMessage(t,n)?!1:!kc.isSameDay((t==null?void 0:t.createdAt)??0,e.createdAt),$v=()=>{var te;const{Template:e}=Dt.useContext(),{Template:t}=ht.useContext(),{Template:n}=Vn.useContext(),{components:r}=qn.useContext(),{stringSet:s,format:o}=ie(),{announceError:i,announceStatus:c}=ct(),{messageList:u}=ae().conversation,{config:d,cache:m,agentPreviewConfigs:h,chatSDK:f,handlers:g,state:p,_aiAgentSDK:v}=ue(),{userSession:E,aiAgentInfo:_,connectionError:A}=Oe(),{_statsEnabled:y,conversation:T,channelSource:I,messageSource:N,scrollSource:O,state:{input:k,streamAnimation:R}}=Ae(),{filteredMessages:F,shouldShowOriginalDate:D,renderAgentPreviewWelcomeMessages:Q}=Iv(),re=Th({enabled:y}),G=ah(Fi(I.channel),ol(F,E.userId)),[H,K]=l.useState(null),[J,q]=l.useState(null),z=Ne(I.channel)?void 0:G??R.heldTypingInfo;l.useEffect(()=>{O.actions.onTypingIndicatorUpdate(!!z)},[!!z,O.actions.onTypingIndicatorUpdate]),xv(),bv({enabled:N.initialized&&N.messages.length>0});const W=w=>{var _e;return zc(w,{aiAgentInfo:_,members:(_e=I.channel)==null?void 0:_e.members})},Y=w=>{if(w.sendingStatus==="failed"&&!k.disabled)return()=>q(w)},V=({message:w,index:_e})=>{const Re=Vc(w),Te=F[_e-1],$=F[_e+1],M=F[F.length-1],x=w===M,L=et(w,_.userId),P=!(_.isUserFeedbackEnabled&&L&&!we.isWelcomeMessage(w)),X=Kc(w,Te,$,P),oe=Dv(w,Te,_.userId)&&D(_e),Z=ve=>{K({files:ve.files.map(je=>({...je,timestamp:w.createdAt})),index:ve.index})},Ce=ve=>{Z({files:[ve],index:0})},Ye=oe?a.createElement(r.DateSeparator,{role:"listitem",style:{margin:"16px 0"},date:w.createdAt}):null,rt={data:w.data,maxBodyWidth:p.expanded?se.WIDE_BODY_MAX_WIDTH:void 0,extendedMessagePayload:w.extendedMessagePayload,createdAt:w.createdAt,groupType:X,onClickMedia:Ce,onClickMediaFiles:Z,onClickFile:g.onClickLink,onClickCTA:g.onClickLink,onClickCitation:ve=>g.onClickLink({url:ve.link}),onClickLink:g.onClickLink},an=()=>{if(Me.isOutgoing(w,E.userId))return"outgoingmessage";if(Me.isIncoming(w,E.userId))return"incomingmessage"},le=w.createdAt!=null&&w.createdAt!==0?o(w.createdAt,s.DATE_FORMAT__MESSAGE_TIMESTAMP):void 0,fe=(()=>{var je;const ve=(je=w.message)==null?void 0:je.trim();return w.isFileMessage()||w.isMultipleFilesMessage()?Tr(Wi(w,ka(s))):ve?Jh({markdownText:ve}):Tr("")})(),ge=(()=>{if(Me.isAdmin(w))return Kt({message:fe.text,messageFormat:fe.format,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER});if(Me.isOutgoing(w,E.userId))return Kt({sender:s.A11Y_MESSAGE_SENDER_YOU,message:fe.text,messageFormat:"plain",time:le,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER});if(Me.isIncoming(w,E.userId))return Kt({sender:W(w).nickname,message:fe.text,messageFormat:fe.format,time:le,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER})})(),pe=(()=>{var ve,je;if(Me.isAdmin(w))return Me.isCSAT(w)?T?a.createElement(n,{...rt,...T,isResolvedWhenDeterminedByUser:Ml(T),messageType:"admin.csat",announceError:i,announceStatus:c,onSubmitCSAT:async Be=>{var st;await((st=I.channel)==null?void 0:st.submitCSAT(Be))},onScrollToBottom:()=>O.actions.scrollToBottom()}):null:a.createElement(n,{...rt,messageType:"admin",message:w.message});if(Me.isSteward(w)){const Be=re({message:w,isBotMessage:L,aiAgentUserId:_.userId});return a.createElement(Nv,{steward:w.extendedMessagePayload.steward,statsCallbacks:Be,onCancelSteward:async()=>{await f.aiAgent.cancelStewardTask({channelUrl:w.channelUrl,messageId:w.messageId})}})}if(Me.isOutgoing(w,E.userId)){const Be={...rt,message:w.message,sender:W(w),sendingStatus:w.sendingStatus,onClickFailedMessage:Y(w)};if(w.isUserMessage())return a.createElement(e,{messageType:"user",...Be});if(w.isFileMessage()){const[st,lt]=((ve=w.metaArrays.find(de=>de.key===ai))==null?void 0:ve.value)??[];return a.createElement(e,{messageType:"file",file:w,metadata:{aspectRatio:st&<?`${st}/${lt}`:"1/1",localFile:(je=w.messageParams)==null?void 0:je.file},...Be})}if(w.isMultipleFilesMessage()){const{files:st,metadata:lt}=Uo(w);return a.createElement(e,{messageType:"multipleFiles",files:st,metadata:lt,...Be})}}if(Me.isIncoming(w,E.userId)){const Be=we.isStreaming(w),st=re({message:w,isBotMessage:L,aiAgentUserId:_.userId}),lt={...rt,statsCallbacks:st,sender:W(w),message:w.message,suggestedRepliesVisible:x,suggestedRepliesDirection:h==null?void 0:h.suggestedRepliesDirection,isBotMessage:L,isStreaming:Be,isHandedOff:at(I.channel),isConversationClosed:Ne(I.channel),isFeedbackEnabled:_.isUserFeedbackEnabled,isFeedbackCommentEnabled:_.isUserFeedbackCommentOptionEnabled,isSenderAvatarVisible:d.conversation.list.senderAvatarEnabled,deferredMarkdownElements:d.conversation.list.deferredMarkdownElements,onClickSuggestedReply:async({reply:de})=>{N.sendUserMessage({message:de})},onConfirmTicketClosure:async({ticketId:de,confirmed:Pe})=>{await v.confirmEndOfChat({messageId:w.messageId,ticketId:de,confirmed:Pe})},onRequestMessageTemplate:async de=>{const{template:Pe}=await f.aiAgent.getMessageTemplate(de);return m.template.set(de,Pe),Pe},onGetCachedMessageTemplate:de=>m.template.get(de),onHandleTemplateInternalAction:de=>{if(de.type==="internal"&&de.internalData){const{method:Pe,payload:ot}=de.internalData;Pe==="message.send"&&(ot!=null&&ot.message)&&N.sendUserMessage({message:ot.message})}},onFeedbackUpdate:de=>{const Pe={messageId:w.messageId,channelUrl:w.channelUrl};if(!de)return f.aiAgent.deleteMessageFeedback(Pe);const ot={...Pe,rating:hE(de.rating),comment:de.comment};return we.hasFeedback(w)?f.aiAgent.updateMessageFeedback(ot):f.aiAgent.createMessageFeedback(ot)},onSubmitForm:({key:de,data:Pe})=>f.aiAgent.submitForm({messageId:w.messageId,channelUrl:w.channelUrl,formKey:de,formData:Pe}),onCancelForm:({key:de})=>f.aiAgent.cancelForm({messageId:w.messageId,channelUrl:w.channelUrl,formKey:de}),onSendChallengeAction:({key:de,requestId:Pe,action:ot,data:Ic})=>f.aiAgent.sendChallengeAction({channelUrl:w.channelUrl,key:de,requestId:Pe,action:ot,data:Ic}),onStreamAnimationStart:()=>{R.start(w.messageId)},onStreamAnimationProgress:()=>{O.actions.onStreamingUpdate(!0)},onStreamAnimationComplete:()=>{R.stop(w.messageId),O.actions.onStreamingUpdate(!1)},onStreamAnimationHoldChange:de=>{de?R.holdStart(w.messageId,{user:W(w),isBot:L}):R.holdStop(w.messageId)}};if(w.isUserMessage())return a.createElement(t,{messageType:"user",...lt});if(w.isFileMessage())return a.createElement(t,{messageType:"file",file:w,...lt});if(w.isMultipleFilesMessage()){const{files:de}=Uo(w);return a.createElement(t,{messageType:"multipleFiles",files:de,...lt})}}})(),De=R.isHolding(w.messageId),$e=u.item({label:ge,holding:De});return a.createElement(l.Fragment,{key:Re},Ye,a.createElement("div",{id:`${Ue}-message-item`,...$e.props,"data-message-listitem":"","data-layout-id":an()},pe))};return a.createElement(Pv,{id:`${Ue}-message-list`},a.createElement(zp,{ref:O.ref,onScroll:O.props.onScroll,stackDirection:h==null?void 0:h.messageStackDirection,messages:F,renderMessage:V,onLoadPrev:N.loadPrevious,onLoadNext:N.loadNext,depsForResetScrollPositionToBottom:[N.initialized,N.messages.length!==0],bottomSpacerHeight:O.state.bottomSpace,"aria-label":s.A11Y_MESSAGE_LIST,loading:!N.initialized||!I.channel,empty:F.length===0&&!z,error:!!(A||I.error),LoadingComponent:a.createElement(qt,{type:"loading"}),EmptyComponent:(()=>{const w=Q();return w?a.createElement("div",{style:{width:"100%"}},w):a.createElement(qt,{type:"noMessages",label:s.PLACE_HOLDER__NO_MESSAGES})})(),ErrorComponent:a.createElement(qt,{type:"error",label:(A==null?void 0:A.message)??((te=I.error)==null?void 0:te.message),action:I.error?{label:s.RETRY,onClick:()=>I.refetch()}:void 0}),messageTopArea:a.createElement(a.Fragment,null,a.createElement(Rv,{style:{marginTop:16}}),Q()),messageBottomArea:a.createElement(a.Fragment,null,z&&a.createElement("div",{id:`${Ue}-message-item`,...u.typingItem(z.user.nickname).props,"data-message-listitem":"",style:{marginTop:F.length===0?8:0}},a.createElement(t,{isTyping:!0,isBotMessage:z.isBot,sender:z.user,thinkingMessage:z.thinkingMessage,messageType:"user",groupType:"single",message:"",isSenderAvatarVisible:d.conversation.list.senderAvatarEnabled})),d.conversation.list.isTalkToAgentViewEnabled&&a.createElement(kv,null)),overlayArea:a.createElement(a.Fragment,null,d.conversation.list.newMessageIndicatorEnabled&&O.state.isAwayFromBottom&&N.newMessages.length>0&&a.createElement(Fv,{label:s.SCROLL_TO_NEW_MESSAGES_LABEL(N.newMessages),onClick:()=>O.actions.scrollToBottom()}),O.state.isAwayFromBottom&&N.newMessages.length===0&&!z&&a.createElement(r.ScrollToBottomButton,{onClick:()=>O.actions.scrollToBottom(),style:{position:"absolute",bottom:12,insetInlineEnd:16}}))}),H&&a.createElement(Xp,{files:H.files,initialIndex:H.index,onClose:()=>K(null),visible:!0}),J&&a.createElement(dt,{visible:!0,onClose:()=>q(null),"aria-label":s.A11Y_FAILED_MESSAGE_OPTIONS},a.createElement(dt.ActionItem,{onClick:()=>{N.resendMessage(J),q(null)}},s.FAILED_MESSAGE_RESEND),a.createElement(dt.ActionItem,{destructive:!0,onClick:()=>{N.deleteMessage(J),q(null)}},s.FAILED_MESSAGE_REMOVE)))},Pv=C.default.div`overflow-y:hidden;display:flex;flex:1;position:relative;`,Fv=C.default(cv)`position:absolute;bottom:12px;left:50%;transform:translateX(-50%);`,Uv=()=>a.createElement($v,null),Go={file:"attach",snippet:"snippet",site:"website",sb_sprinklr:"sprinklr",sb_salesforce:"salesforce",sb_confluence:"confluence",sb_zendesk:"zendesk",sb_desk:"snippet"},Qa=({actionbook:e,functionCalls:t,groundedness:n,agentMessageTemplates:r,flaggedTypes:s,onClickActionbook:o,onClickFunctionCall:i,onClickFunctionCallDetail:c,onClickGroundedness:u,onClickAgentMessageTemplate:d,topContent:m,bottomContent:h,renderCustomGroundednessIcon:f=p=>p.default,style:g={}})=>{const{iconColor:p="#000000",textColor:v="#000000",highlightColor:E=Wt.DEFAULT_PRIMARY}=g;return a.createElement(zo,null,m,e&&a.createElement(zo,null,a.createElement(On,null,a.createElement(Bt,null,a.createElement(ee,{size:16,type:"actionbook",color:p})),a.createElement(_n,{$clickable:!!o,$highlightColor:E,variant:"body2",color:v,onClick:()=>o==null?void 0:o(e),maxTextLines:1},e.name))),t==null?void 0:t.map(_=>a.createElement(vn,{key:_.key},a.createElement(Bt,null,a.createElement(ee,{size:16,type:"function",color:p})),a.createElement(On,null,a.createElement(_n,{$clickable:!!i,$highlightColor:E,variant:"body2",color:v,onClick:()=>i==null?void 0:i(_),maxTextLines:1},_.name),c&&a.createElement(Bv,{role:"button",onClick:()=>c==null?void 0:c(_)},a.createElement(B,{variant:"body2",color:E},"View details"),a.createElement(ee,{type:"chevron-right",size:16,color:E}))))),n==null?void 0:n.map(_=>a.createElement(vn,{key:_.id},a.createElement(Bt,null,f({default:a.createElement(ee,{size:16,type:Go[_.source_type]??Go.snippet,color:p}),sourceType:_.source_type})),a.createElement(_n,{$clickable:!!u,$highlightColor:E,variant:"body2",color:v,onClick:()=>u==null?void 0:u(_),maxTextLines:1},_.preview_title))),r==null?void 0:r.map(_=>a.createElement(vn,{key:_.key},a.createElement(Bt,null,a.createElement(ee,{size:16,type:"template",color:p})),a.createElement(_n,{$clickable:!!d,$highlightColor:E,variant:"body2",color:v,onClick:()=>d==null?void 0:d(_),maxTextLines:1},_.name))),!!(s!=null&&s.length)&&a.createElement(Hv,null,a.createElement(Bt,null,a.createElement(ee,{size:16,type:"activity",color:p})),a.createElement(Gv,{variant:"body2",color:v},s.map(_=>_.replace(/_/g," ")).join(" · "))),h)},ec=C.default(B)`font-weight:400;`,_n=C.default(ec)`${({$clickable:e,$highlightColor:t})=>e&&U.css`
|
|
406
|
+
`,bv=({statsCallbacks:e,...t})=>(af(e),a.createElement(Bb,{...t})),vv=(e,t,n)=>t&&Ae.isWelcomeMessage(e,n)&&Ae.isWelcomeMessage(t,n)?!1:!Vc.isSameDay((t==null?void 0:t.createdAt)??0,e.createdAt),yv=()=>{var ae;const{Template:e}=Ht.useContext(),{Template:t}=_t.useContext(),{Template:n}=jn.useContext(),{components:r}=Zn.useContext(),{stringSet:s,format:o}=le(),{announceError:i,announceStatus:c}=ht(),{messageList:u}=ue().conversation,{config:d,cache:m,agentPreviewConfigs:h,chatSDK:f,handlers:g,state:p,_aiAgentSDK:C}=ge(),{userSession:E,aiAgentInfo:_,connectionError:A}=De(),{_statsEnabled:y,_stats:T,conversation:M,channelSource:O,messageSource:w,scrollSource:R,state:{input:x,streamAnimation:$}}=Me(),{filteredMessages:N,shouldShowOriginalDate:J,renderAgentPreviewWelcomeMessages:se}=hv(),Y=of({enabled:y}),j=Hh(Yi(O.channel),pl(N,E.userId)),[P,V]=l.useState(null),[q,W]=l.useState(null),H=$e(O.channel)?void 0:j??$.heldTypingInfo;l.useEffect(()=>{R.actions.onTypingIndicatorUpdate(!!H)},[!!H,R.actions.onTypingIndicatorUpdate]),fv(),av({enabled:w.initialized&&w.messages.length>0});const G=L=>{var ve;return el(L,{aiAgentInfo:_,members:(ve=O.channel)==null?void 0:ve.members})},z=L=>{if(L.sendingStatus==="failed"&&!x.disabled)return()=>W(L)},ee=({message:L,index:ve})=>{const xe=tl(L),Oe=N[ve-1],I=N[ve+1],k=N[N.length-1],D=L===k,U=Fe(L,_.userId),Z=!(_.isUserFeedbackEnabled&&U&&!Ae.isWelcomeMessage(L)),oe=nl(L,Oe,I,Z),Q=vv(L,Oe,_.userId)&&J(ve),Se=Pe=>{V({files:Pe.files.map(tt=>({...tt,timestamp:L.createdAt})),index:Pe.index})},K=Pe=>{Se({files:[Pe],index:0})},me=Q?a.createElement(r.DateSeparator,{role:"listitem",style:{margin:"16px 0"},date:L.createdAt}):null,he={data:L.data,maxBodyWidth:p.expanded?re.WIDE_BODY_MAX_WIDTH:void 0,extendedMessagePayload:L.extendedMessagePayload,createdAt:L.createdAt,groupType:oe,onClickMedia:K,onClickMediaFiles:Se,onClickFile:g.onClickLink,onClickCTA:g.onClickLink,onClickCitation:Pe=>g.onClickLink({url:Pe.link}),onClickLink:g.onClickLink},ie=()=>{if(Le.isOutgoing(L,E.userId))return"outgoingmessage";if(Le.isIncoming(L,E.userId))return"incomingmessage"},pe=L.createdAt!=null&&L.createdAt!==0?o(L.createdAt,s.DATE_FORMAT__MESSAGE_TIMESTAMP):void 0,de=(()=>{var tt;const Pe=(tt=L.message)==null?void 0:tt.trim();return L.isFileMessage()||L.isMultipleFilesMessage()?wr(ra(L,za(s))):Pe?Of({markdownText:Pe}):wr("")})(),be=(()=>{if(Le.isAdmin(L))return Zt({message:de.text,messageFormat:de.format,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER});if(Le.isOutgoing(L,E.userId))return Zt({sender:s.A11Y_MESSAGE_SENDER_YOU,message:de.text,messageFormat:"plain",time:pe,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER});if(Le.isIncoming(L,E.userId))return Zt({sender:G(L).nickname,message:de.text,messageFormat:de.format,time:pe,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER})})(),Ue=(()=>{var Pe,tt;if(Le.isAdmin(L))return Le.isCSAT(L)?M?a.createElement(n,{...he,...M,isResolvedWhenDeterminedByUser:Bl(M),messageType:"admin.csat",announceError:i,announceStatus:c,onSubmitCSAT:async it=>{var at;await((at=O.channel)==null?void 0:at.submitCSAT(it))},onScrollToBottom:()=>R.actions.scrollToBottom()}):null:a.createElement(n,{...he,messageType:"admin",message:L.message});if(Le.isSteward(L)){const it=Y({message:L,isBotMessage:U,aiAgentUserId:_.userId});return a.createElement(bv,{steward:L.extendedMessagePayload.steward,statsCallbacks:it,onCancelSteward:async()=>{await f.aiAgent.cancelStewardTask({channelUrl:L.channelUrl,messageId:L.messageId})}})}if(Le.isOutgoing(L,E.userId)){const it={...he,message:L.message,sender:G(L),sendingStatus:L.sendingStatus,onClickFailedMessage:z(L)};if(L.isUserMessage())return a.createElement(e,{messageType:"user",...it});if(L.isFileMessage()){const[at,ft]=((Pe=L.metaArrays.find(fe=>fe.key===_i))==null?void 0:Pe.value)??[];return a.createElement(e,{messageType:"file",file:L,metadata:{aspectRatio:at&&ft?`${at}/${ft}`:"1/1",localFile:(tt=L.messageParams)==null?void 0:tt.file},...it})}if(L.isMultipleFilesMessage()){const{files:at,metadata:ft}=Xo(L);return a.createElement(e,{messageType:"multipleFiles",files:at,metadata:ft,...it})}}if(Le.isIncoming(L,E.userId)){const it=Ae.isStreaming(L),at=Y({message:L,isBotMessage:U,aiAgentUserId:_.userId}),ft={...he,statsCallbacks:at,sender:G(L),message:L.message,suggestedRepliesVisible:D,suggestedRepliesDirection:h==null?void 0:h.suggestedRepliesDirection,isBotMessage:U,isStreaming:it,isHandedOff:dt(O.channel),isConversationClosed:$e(O.channel),isFeedbackEnabled:_.isUserFeedbackEnabled,isFeedbackCommentEnabled:_.isUserFeedbackCommentOptionEnabled,isSenderAvatarVisible:d.conversation.list.senderAvatarEnabled,deferredMarkdownElements:d.conversation.list.deferredMarkdownElements,onClickSuggestedReply:async({reply:fe})=>{w.sendUserMessage({message:fe})},onConfirmTicketClosure:async({ticketId:fe,confirmed:He})=>{await C.confirmEndOfChat({messageId:L.messageId,ticketId:fe,confirmed:He})},onRequestMessageTemplate:async fe=>{const{template:He}=await f.aiAgent.getMessageTemplate(fe);return m.template.set(fe,He),He},onGetCachedMessageTemplate:fe=>m.template.get(fe),onHandleTemplateInternalAction:fe=>{if(fe.type==="internal"&&fe.internalData){const{method:He,payload:ct}=fe.internalData;He==="message.send"&&(ct!=null&&ct.message)&&w.sendUserMessage({message:ct.message})}},onFeedbackUpdate:fe=>{const He={messageId:L.messageId,channelUrl:L.channelUrl};if(!fe)return f.aiAgent.deleteMessageFeedback(He);const ct={...He,rating:X_(fe.rating),comment:fe.comment};return Ae.hasFeedback(L)?f.aiAgent.updateMessageFeedback(ct):f.aiAgent.createMessageFeedback(ct)},onSubmitForm:({key:fe,data:He})=>f.aiAgent.submitForm({messageId:L.messageId,channelUrl:L.channelUrl,formKey:fe,formData:He}),onCancelForm:({key:fe})=>f.aiAgent.cancelForm({messageId:L.messageId,channelUrl:L.channelUrl,formKey:fe}),onSendChallengeAction:({key:fe,requestId:He,action:ct,data:Uc})=>f.aiAgent.sendChallengeAction({channelUrl:L.channelUrl,key:fe,requestId:He,action:ct,data:Uc}),onStreamAnimationStart:()=>{$.start(L.messageId),T.onMessageLifecycleAnimationStart(L.messageId)},onStreamAnimationProgress:()=>{R.actions.onStreamingUpdate(!0)},onStreamAnimationComplete:({completed:fe})=>{$.stop(L.messageId),R.actions.onStreamingUpdate(!1),T.onMessageLifecycleAnimationComplete(L.messageId,fe)},onStreamAnimationHoldChange:fe=>{fe?$.holdStart(L.messageId,{user:G(L),isBot:U}):$.holdStop(L.messageId)}};if(L.isUserMessage())return a.createElement(t,{messageType:"user",...ft});if(L.isFileMessage())return a.createElement(t,{messageType:"file",file:L,...ft});if(L.isMultipleFilesMessage()){const{files:fe}=Xo(L);return a.createElement(t,{messageType:"multipleFiles",files:fe,...ft})}}})(),Be=$.isHolding(L.messageId),Ze=u.item({label:be,holding:Be});return a.createElement(l.Fragment,{key:xe},me,a.createElement("div",{id:`${ze}-message-item`,...Ze.props,"data-message-listitem":"","data-layout-id":ie()},Ue))};return a.createElement(Av,{id:`${ze}-message-list`},a.createElement(TE,{ref:R.ref,onScroll:R.props.onScroll,stackDirection:h==null?void 0:h.messageStackDirection,messages:N,renderMessage:ee,onLoadPrev:w.loadPrevious,onLoadNext:w.loadNext,depsForResetScrollPositionToBottom:[w.initialized,w.messages.length!==0],bottomSpacerHeight:R.state.bottomSpace,"aria-label":s.A11Y_MESSAGE_LIST,loading:!w.initialized||!O.channel,empty:N.length===0&&!H,error:!!(A||O.error),LoadingComponent:a.createElement(Jt,{type:"loading"}),EmptyComponent:(()=>{const L=se();return L?a.createElement("div",{style:{width:"100%"}},L):a.createElement(Jt,{type:"noMessages",label:s.PLACE_HOLDER__NO_MESSAGES})})(),ErrorComponent:a.createElement(Jt,{type:"error",label:(A==null?void 0:A.message)??((ae=O.error)==null?void 0:ae.message),action:O.error?{label:s.RETRY,onClick:()=>O.refetch()}:void 0}),messageTopArea:a.createElement(a.Fragment,null,a.createElement(gv,{style:{marginTop:16}}),se()),messageBottomArea:a.createElement(a.Fragment,null,H&&a.createElement("div",{id:`${ze}-message-item`,...u.typingItem(H.user.nickname).props,"data-message-listitem":"",style:{marginTop:N.length===0?8:0}},a.createElement(t,{isTyping:!0,isBotMessage:H.isBot,sender:H.user,thinkingMessage:H.thinkingMessage,messageType:"user",groupType:"single",message:"",isSenderAvatarVisible:d.conversation.list.senderAvatarEnabled})),d.conversation.list.isTalkToAgentViewEnabled&&a.createElement(_v,null)),overlayArea:a.createElement(a.Fragment,null,d.conversation.list.newMessageIndicatorEnabled&&R.state.isAwayFromBottom&&w.newMessages.length>0&&a.createElement(Tv,{label:s.SCROLL_TO_NEW_MESSAGES_LABEL(w.newMessages),onClick:()=>R.actions.scrollToBottom()}),R.state.isAwayFromBottom&&w.newMessages.length===0&&!H&&a.createElement(r.ScrollToBottomButton,{onClick:()=>R.actions.scrollToBottom(),style:{position:"absolute",bottom:12,insetInlineEnd:16}}))}),P&&a.createElement(LE,{files:P.files,initialIndex:P.index,onClose:()=>V(null),visible:!0}),q&&a.createElement(pt,{visible:!0,onClose:()=>W(null),"aria-label":s.A11Y_FAILED_MESSAGE_OPTIONS},a.createElement(pt.ActionItem,{onClick:()=>{w.resendMessage(q),W(null)}},s.FAILED_MESSAGE_RESEND),a.createElement(pt.ActionItem,{destructive:!0,onClick:()=>{w.deleteMessage(q),W(null)}},s.FAILED_MESSAGE_REMOVE)))},Av=b.default.div`overflow-y:hidden;display:flex;flex:1;position:relative;`,Tv=b.default(jb)`position:absolute;bottom:12px;left:50%;transform:translateX(-50%);`,Iv=()=>a.createElement(yv,null),Qo={file:"attach",snippet:"snippet",site:"website",sb_sprinklr:"sprinklr",sb_salesforce:"salesforce",sb_confluence:"confluence",sb_zendesk:"zendesk",sb_desk:"snippet"},dc=({actionbook:e,functionCalls:t,groundedness:n,agentMessageTemplates:r,flaggedTypes:s,onClickActionbook:o,onClickFunctionCall:i,onClickFunctionCallDetail:c,onClickGroundedness:u,onClickAgentMessageTemplate:d,topContent:m,bottomContent:h,renderCustomGroundednessIcon:f=p=>p.default,style:g={}})=>{const{iconColor:p="#000000",textColor:C="#000000",highlightColor:E=Qt.DEFAULT_PRIMARY}=g;return a.createElement(ei,null,m,e&&a.createElement(ei,null,a.createElement(Un,null,a.createElement(qt,null,a.createElement(te,{size:16,type:"actionbook",color:p})),a.createElement(vn,{$clickable:!!o,$highlightColor:E,variant:"body2",color:C,onClick:()=>o==null?void 0:o(e),maxTextLines:1},e.name))),t==null?void 0:t.map(_=>a.createElement(In,{key:_.key},a.createElement(qt,null,a.createElement(te,{size:16,type:"function",color:p})),a.createElement(Un,null,a.createElement(vn,{$clickable:!!i,$highlightColor:E,variant:"body2",color:C,onClick:()=>i==null?void 0:i(_),maxTextLines:1},_.name),c&&a.createElement(xv,{role:"button",onClick:()=>c==null?void 0:c(_)},a.createElement(B,{variant:"body2",color:E},"View details"),a.createElement(te,{type:"chevron-right",size:16,color:E}))))),n==null?void 0:n.map(_=>a.createElement(In,{key:_.id},a.createElement(qt,null,f({default:a.createElement(te,{size:16,type:Qo[_.source_type]??Qo.snippet,color:p}),sourceType:_.source_type})),a.createElement(vn,{$clickable:!!u,$highlightColor:E,variant:"body2",color:C,onClick:()=>u==null?void 0:u(_),maxTextLines:1},_.preview_title))),r==null?void 0:r.map(_=>a.createElement(In,{key:_.key},a.createElement(qt,null,a.createElement(te,{size:16,type:"template",color:p})),a.createElement(vn,{$clickable:!!d,$highlightColor:E,variant:"body2",color:C,onClick:()=>d==null?void 0:d(_),maxTextLines:1},_.name))),!!(s!=null&&s.length)&&a.createElement(Mv,null,a.createElement(qt,null,a.createElement(te,{size:16,type:"activity",color:p})),a.createElement(Rv,{variant:"body2",color:C},s.map(_=>_.replace(/_/g," ")).join(" · "))),h)},mc=b.default(B)`font-weight:400;`,vn=b.default(mc)`${({$clickable:e,$highlightColor:t})=>e&&F.css`
|
|
407
407
|
cursor: pointer;
|
|
408
408
|
text-decoration: underline;
|
|
409
409
|
&:hover {
|
|
410
410
|
color: ${t};
|
|
411
411
|
}
|
|
412
412
|
`}
|
|
413
|
-
`,
|
|
414
|
-
background-color: ${
|
|
413
|
+
`,qt=b.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,Un=b.default.div`display:flex;gap:8px;align-items:center;word-break:break-word;`,xv=b.default(Un)`cursor:pointer;gap:4px;`,In=b.default(Un)`flex-direction:row;align-items:center;`,Mv=b.default(In)`align-items:flex-start;max-width:100%;`,Rv=b.default(mc)`min-width:0;`,ei=b.default.div`display:flex;gap:4px;flex-direction:column;align-items:flex-start;`,kv=e=>{const t=e.replace(/[_-]+/g," ").trim().toLowerCase();return t?t.charAt(0).toUpperCase()+t.slice(1):""},hc=({prechecks:e,maxBodyWidth:t})=>{const{theme:n}=zn();return e.length===0?null:a.createElement(wv,{id:`${Ke}-ext-prechecks`},a.createElement(Lv,{$maxWidth:t??re.BODY_MAX_WIDTH},e.map(r=>a.createElement(Ov,{key:r.key},a.createElement(Nv,{type:"done-circle",size:16,color:v.themedColor.secondary}),a.createElement(B,{variant:"caption2",color:n.colors.messageIncoming.text},kv(r.key))))))},wv=b.default.div`align-self:stretch;padding-block-end:8px;padding-inline-start:${re.HORIZONTAL_PADDING+re.AVATAR_SIZE}px;padding-inline-end:${re.HORIZONTAL_PADDING}px;`,Lv=b.default.div`display:flex;flex-wrap:wrap;gap:4px 14px;width:fit-content;max-width:min(${({$maxWidth:e})=>e}px,100%);padding:8px 12px;border-radius:8px;background-color:${({theme:e})=>e.colors.messageIncoming.background};`,Ov=b.default.div`display:flex;align-items:center;gap:6px;min-width:0;overflow-wrap:anywhere;`,Nv=b.default(te)`flex-shrink:0;`,fc=ye("DashboardTester"),Dv=fc.Provider;function Pv({testerType:e,origin:t,children:n}){return a.createElement(Dv,{value:{testerType:e,origin:t}},e&&a.createElement($v,null),n)}const gc=fc.useContext,$v=()=>a.createElement(a.Fragment,null,a.createElement(_t.Prechecks,{component:Fv}),a.createElement(_t.MessageLogs,{component:ti}),a.createElement(Ht.MessageLogs,{component:ti})),Fv=({extendedMessagePayload:e={},maxBodyWidth:t})=>a.createElement(hc,{prechecks:e.prechecks??[],maxBodyWidth:t}),ti=({extendedMessagePayload:e={}})=>{const{handlers:t}=ge(),{manual:n,groundedness:r,function_calls:s,agent_message_templates:o,flagged_types:i,is_thinking:c}=e,u=!!n||[r,s,o,i].some(d=>d==null?void 0:d.length);return c||!u?a.createElement(a.Fragment,null):a.createElement(Uv,null,a.createElement(Bv,{$width:4}),a.createElement(dc,{actionbook:n,functionCalls:s,groundedness:r,agentMessageTemplates:o,flaggedTypes:i,onClickFunctionCallDetail:t==null?void 0:t.onFunctionCallDetailClick,style:{iconColor:v.themedColor.textHighEmphasis,textColor:v.themedColor.textHighEmphasis,barColor:v.themedColor.textDisabled},topContent:a.createElement(B,{variant:"caption4",color:v.themedColor.textLowEmphasis},"Only visible in the tester")}))},Uv=b.default.div`display:flex;gap:16px;margin:6px ${re.HORIZONTAL_PADDING}px 4px ${re.HORIZONTAL_PADDING+re.AVATAR_SIZE}px;align-self:stretch;`,Bv=b.default.div`width:${({$width:e})=>e}px;background-color:${v.themedColor.textDisabled};border-radius:100px;flex-shrink:0;`,Hv=()=>{var s;const{origin:e}=gc(),{appId:t,aiAgentId:n}=Ie(),{channelSource:r}=Me();return(s=r.channel)!=null&&s.conversation?a.createElement(Gv,null,a.createElement(Gr,{style:{gap:4}},a.createElement(te,{color:v.themedColor.textLowEmphasis,size:12,type:"show"}),a.createElement(B,{as:"i",color:v.themedColor.textLowEmphasis,variant:"caption2"},"Only visible in the tester")),a.createElement(Gr,{role:"button",style:{gap:4},onClick:()=>{var u,d;const o=e??window.location.origin,i=(d=(u=r.channel)==null?void 0:u.conversation)==null?void 0:d.id,c=`${o}/ai-agent/${t}/${n}/evaluate/conversations/${i}`;navigator.clipboard.writeText(c)}},a.createElement(B,{variant:"body3",color:v.themedColor.textHighEmphasis},"Copy ",a.createElement("span",{style:{color:v.themedColor.primary}},"conversation link")),a.createElement(te,{color:v.themedColor.primary,size:14,type:"copy"}))):null},Gr=b.default.div`display:flex;justify-content:center;align-items:center;`,Gv=b.default(Gr)`flex-direction:column;padding-block:16px;background-color:${v.themedColor.bg_100_500};gap:8px;`,zv=(e,t)=>{const n=[],r=[],s=[];for(const o of e){const i=t.isSupportedMimeType(o.type),c=o.size<=t.getUploadSizeLimit(o.type);i&&c?n.push(o):i?r.push(o):s.push(o)}return{passed:n,failedBySize:r,failedByType:s}},pc=l.createContext(void 0),Vv=({children:e})=>{var J,se;const{chatSDK:t}=ge(),{createAttachmentRules:n}=De(),{stringSet:r}=le(),{channelSource:s,state:o}=Me(),[i,c]=l.useState([]),{announceError:u}=fs(),[d,m]=l.useState(null),h=n({channel:s.channel,uploadSizeLimit:(J=t.appInfo)==null?void 0:J.uploadSizeLimit}),f=((se=o==null?void 0:o.input)==null?void 0:se.disabled)??!1,g=h.isEnabled(),p=h.maxAttachmentCount,C=()=>m(null),E=Y=>m(Y),_=()=>{E({title:r.FILE_UPLOAD_NOTIFICATION__COUNT_LIMIT.replace("%d",p.toString())})},A=Y=>{E({title:r.FILE_UPLOAD_NOTIFICATION__SIZE_LIMIT.replace("%d",Y.toString())}),u({type:"fileSizeExceeded",maxSizeMB:Y})},y=Y=>{E({title:r.FILE_UPLOAD_NOTIFICATION__FILES_EXCLUDED_BY_VALIDATION.replace("%d",Y.toString())})},T=Y=>Y.map(j=>{const P=vs(j);return Op(j,P),{file:j,preview:{url:P,type:j.type,name:j.name}}}),M=Y=>{c(j=>[...j,...Y])},O=Y=>{c(j=>(j.forEach(P=>jo(P.file)),Y))},w=Y=>{const{passed:j,failedBySize:P,failedByType:V}=zv(Y,h),q=P.length+V.length,W=Y.length===1?P[0]:void 0;return W?A(h.getUploadSizeLimitInMB(W.type)):q>0&&y(q),j},R=Y=>{const j=w(Y.files);if(j.length===0)return;const P=T(j);Y.type==="append"?M(P):O(P)},x=Y=>{if(!g||f||!Jd(Y))return;const j=em({currentFiles:i.map(({file:P})=>P),incomingFiles:Y,maxAttachmentCount:p});switch(j.type){case"reject":_();return;case"confirm_replace":E({title:r.FILE_UPLOAD_REPLACE_ALERT__TITLE,description:r.FILE_UPLOAD_REPLACE_ALERT__DESCRIPTION,confirmText:r.BUTTON__OK,cancelText:r.BUTTON__CANCEL,onConfirm:()=>R(j.action)});return;case"apply":R(j.action);return}},$=Y=>{c(j=>{var V;const P=(V=j[Y])==null?void 0:V.file;return P&&jo(P),j.filter((q,W)=>W!==Y)})},N=()=>{c([])};return a.createElement(pc.Provider,{value:{files:i,addFiles:x,removeFile:$,clearFiles:N,isFileUploadEnabled:g,acceptableMimeTypes:h.supportedMimeTypes,maxAttachmentCount:h.maxAttachmentCount,showFileUploadAlert:E}},e,a.createElement(ln,{visible:!!d,...d??{},onClose:C}))},Is=()=>{const e=l.useContext(pc);if(!e)throw new Error("useFileUpload must be used within FileUploadProvider");return e};function Kv({elementRef:e,ready:t,onRestore:n}){const r=l.useRef(!1);l.useEffect(()=>{var i;!t||!r.current||(n==null||n(),(i=e.current)==null||i.focus(),r.current=!1)},[t,n]);const s=l.useCallback(()=>{r.current=!0},[]),o=l.useCallback(()=>{r.current=!1},[]);return{requestRestore:s,cancelRestore:o}}function qv({blurred:e,elementRef:t,document:n=window.document,onRecoverFocus:r}){const s=l.useRef(!1);e&&t.current&&n.activeElement===t.current&&(s.current=!0),l.useLayoutEffect(()=>{var o;!e&&s.current&&(r==null||r(),(o=t.current)==null||o.focus(),s.current=!1)},[e,r])}const Wv=()=>{const{announceError:e}=ht();return l.useCallback(t=>{e({type:"sendFailed"},t)},[e])},Yv=1e3,jv=(e,t,n)=>{const{announcementsEnabled:r,setIsSuppressed:s}=ht(),o=n??!0,i=l.useRef(!1),c=l.useRef(void 0),u=l.useCallback(d=>{var m;d&&o&&(i.current=!0,c.current=e,e==null||e.startTyping()),d||(i.current&&o&&((m=c.current)==null||m.endTyping()),i.current=!1,c.current=void 0),s(d)},[e,s,o]);l.useLayoutEffect(()=>{s(i.current)},[r,s]),Gh(t,u,{enabled:o,idleMs:Yv})},Xv=({enabled:e=!0,focusRoot:t})=>{const[n,r]=l.useState(!1),s=l.useRef(!1),o=l.useRef(!1);l.useEffect(()=>{if(!e){r(!1);return}const d=h=>{const f=h;f.metaKey||f.altKey||f.ctrlKey||(s.current=!0)},m=()=>{s.current=!1,r(!1)};return t.addEventListener("keydown",d),t.addEventListener("pointerdown",m),()=>{t.removeEventListener("keydown",d),t.removeEventListener("pointerdown",m)}},[e,t]);const i=l.useCallback(()=>{if(o.current){o.current=!1,r(!1);return}r(s.current)},[]),c=l.useCallback(()=>{r(!1)},[]),u=l.useCallback(()=>{o.current=!0,r(!1)},[]);return{isFocusVisible:n,suppressNextFocusVisible:u,focusHandlers:{onFocus:i,onBlur:c}}},Zv=b.default.div`&::-webkit-scrollbar{display:none;}overflow-x:auto;display:flex;flex-direction:row;gap:10px;padding:8px 16px;background-color:transparent;`,Jv=b.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;}`,Qv=b.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;${ne.light`
|
|
414
|
+
background-color: ${v.color.background50};
|
|
415
415
|
`}
|
|
416
416
|
${ne.dark`
|
|
417
|
-
background-color: ${
|
|
417
|
+
background-color: ${v.color.background500};
|
|
418
418
|
`}
|
|
419
419
|
path {
|
|
420
|
-
fill: ${
|
|
420
|
+
fill: ${v.themedColor.textMidEmphasis};
|
|
421
421
|
}
|
|
422
422
|
|
|
423
423
|
&:hover {
|
|
424
424
|
path {
|
|
425
|
-
fill: ${
|
|
425
|
+
fill: ${v.themedColor.textHighEmphasis};
|
|
426
426
|
}
|
|
427
427
|
}
|
|
428
428
|
|
|
429
429
|
&:focus-visible {
|
|
430
430
|
opacity: 1;
|
|
431
|
-
outline: 2px solid ${
|
|
431
|
+
outline: 2px solid ${v.color.primary.main};
|
|
432
432
|
outline-offset: 2px;
|
|
433
433
|
}
|
|
434
434
|
|
|
435
435
|
circle {
|
|
436
|
-
stroke: ${
|
|
436
|
+
stroke: ${v.themedColor.bg_50_600};
|
|
437
437
|
}
|
|
438
|
-
`,
|
|
439
|
-
outline: 2px solid ${
|
|
438
|
+
`,ey=()=>{const e=cn(),{conversation:t}=ue(),{files:n,removeFile:r,isFileUploadEnabled:s}=Is();return s&&n.length>0?a.createElement(Zv,null,n.map(({preview:{type:i,name:c,url:u}},d)=>{let m=a.createElement(Cs,{name:c,mimeType:i,type:qr(c,i),selected:!0});return i.startsWith("image/")&&(m=a.createElement("img",{alt:t.file.label(c,i,!0),src:u})),a.createElement(Jv,{key:u},a.createElement(Qv,{type:"button",...t.file.removeButton(c).props,$mobile:e,onClick:()=>r(d)},a.createElement(te,{type:"close-filled",color:v.themedColor.textMidEmphasis})),m)})):null},ty={textArea:F.css`min-height:40px;height:40px;font-size:16px;line-height:24px;`},Ec=b.default.button`all:unset;cursor:pointer;display:flex;align-items:center;justify-content:center;width:32px;height:32px;${ke}`,ni=b.default.div`width:100%;position:relative;background-color:${({theme:e})=>e.colors.messageInput.background};border-radius:20px;`,ri=b.default.div`display:flex;flex-direction:row;align-items:flex-end;position:relative;`,si=b.default.textarea`all:unset;display:block;flex:1;min-width:0;padding-top:8px;padding-bottom:8px;padding-inline-start:16px;padding-inline-end:12px;box-sizing:border-box;font-size:14px;line-height:20px;color:${({theme:e})=>e.colors.messageInput.text};resize:none;width:100%;height:${ha}px;overflow-wrap:break-word;white-space:pre-wrap;overflow-x:hidden;${ka&&ty.textArea};${({$focusVisible:e})=>e&&F.css`
|
|
439
|
+
outline: 2px solid ${v.themedColor.primary};
|
|
440
440
|
outline-offset: 2px;
|
|
441
441
|
`}
|
|
442
442
|
|
|
@@ -447,22 +447,22 @@ $2
|
|
|
447
447
|
&:disabled {
|
|
448
448
|
cursor: not-allowed;
|
|
449
449
|
&::placeholder {
|
|
450
|
-
color: ${
|
|
450
|
+
color: ${v.themedColor.textDisabled};
|
|
451
451
|
}
|
|
452
452
|
}
|
|
453
453
|
|
|
454
|
-
${({$blocked:e})=>e&&
|
|
455
|
-
`,
|
|
456
|
-
color: ${
|
|
454
|
+
${({$blocked:e})=>e&&F.css`cursor:not-allowed;&::placeholder{color:${v.themedColor.textDisabled};}`}
|
|
455
|
+
`,ny=b.default.input`display:none;`;b.default.div`display:flex;align-items:center;gap:24px;`;const ry=b.default(Ec)`flex-shrink:0;border-radius:8px;&:disabled{cursor:not-allowed;}&:not(:disabled){&:hover{background-color:${v.themedColor.bg_100_500};path{fill:${v.themedColor.textHighEmphasis};}}&:active{background-color:${v.themedColor.bg_200_400};}}`,oi=b.default.div`padding:10px 16px 10px 12px;position:relative;display:flex;align-items:center;gap:8px;`,ii=e=>e.startsWith("image/"),ai=({disabled:e})=>{const{stringSet:t}=le(),{conversation:n}=ue(),{config:r}=ge(),s=l.useRef(null),o=l.useRef(null),[i,c]=l.useState(!1),{addFiles:u,isFileUploadEnabled:d,acceptableMimeTypes:m,showFileUploadAlert:h}=Is(),f=m.includes(vr),g=f?["image/*"]:m.filter(ii),p=f?[vr]:m.filter(w=>!ii(w)),C=r.conversation.input.gallery.photoEnabled,E=r.conversation.input.fileEnabled,_=()=>f||g.length>0,A=()=>f||p.length>0,y=w=>{const R=w.currentTarget.files;R&&u(Array.from(R)),w.target.value=""},T=()=>{c(!0)},M=l.useMemo(()=>{const w=[];return C&&w.push({type:"image",icon:"photo",label:t.FILE_UPLOAD_PHOTOS,accept:g.join(","),inputRef:s,onSelect:()=>{if(!_()){h({title:t.FILE_UPLOAD_NO_SUPPORTED_FILES});return}c(!1),setTimeout(()=>{var R;return(R=s.current)==null?void 0:R.click()},100)}}),E&&w.push({type:"file",icon:"document",label:t.FILE_UPLOAD_FILES,accept:m.join(","),inputRef:o,onSelect:()=>{if(!A()){h({title:t.FILE_UPLOAD_NO_SUPPORTED_FILES});return}c(!1),setTimeout(()=>{var R;return(R=o.current)==null?void 0:R.click()},100)}}),w},[g,m,t,C,E]);if(!d)return null;const O={attach:n.messageInput.attachFileButton()};return a.createElement(a.Fragment,null,a.createElement(ry,{...O.attach.props,disabled:e,onClick:T},a.createElement(te,{type:"add",color:e?v.themedColor.textDisabled:v.color.primary.main,size:20}),O.attach.descriptionNode),M.map(w=>a.createElement(ny,{key:w.type,type:"file",ref:w.inputRef,multiple:w.type==="image",onChange:y,accept:w.accept})),a.createElement(pt,{visible:i,onClose:()=>c(!1),"aria-label":t.A11Y_FILE_UPLOAD_OPTIONS},M.map(w=>a.createElement(pt.ActionItem,{key:w.type,onClick:w.onSelect,icon:w.icon},w.label))))},sy=()=>{const e=l.useRef(null),[t,n]=l.useState(""),{stringSet:r}=le(),{conversation:s}=ue(),{rootElement:o}=ge(),i=Et(o),{focusHandlers:c,isFocusVisible:u,suppressNextFocusVisible:d}=Xv({focusRoot:i}),{channelSource:m,messageSource:h,state:f}=Me(),{files:g,addFiles:p,clearFiles:C}=Is(),E=Wv(),{focusPolicy:_,disabled:A,disabledBy:y}=f.input,T=_==="preserve",M=_==="release",O=(()=>{if(!A)return r.MESSAGE_INPUT__PLACE_HOLDER;switch(y){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}})();Kp({onDropFiles:z=>{p(z)}}),qv({blurred:M,elementRef:e,document:i,onRecoverFocus:()=>{d()}}),jv(m.channel,t,!A);const w=t.trim().length>0,R=g.length>0,x=!A&&(w||R),$={input:s.messageInput.textInput(r.A11Y_MESSAGE_INPUT),send:s.messageInput.sendButton()},N=()=>{e.current&&(e.current.value="",e.current.style.height=""),C(),n("")},J=()=>{var z;d(),(z=e.current)==null||z.focus()},{requestRestore:se,cancelRestore:Y}=Kv({elementRef:e,ready:T,onRestore:d}),j=z=>{Y(),E(z)},P=()=>{Y()},V=async z=>{try{await z(),P()}catch{j(e.current)}},q=async()=>{if(A)return;const z=t.trim();if(!z&&!g.length)return;const ee=[...g];if(se(),N(),J(),ee.length===0){await V(()=>h.sendUserMessage({message:z}));return}if(ee.length===1)await V(()=>h.sendFileMessage({message:z,file:ee[0].file}));else{const ae=ee.map(({file:L})=>({file:L}));await V(()=>h.sendMultipleFilesMessage({message:z,fileInfoList:ae}))}},W=z=>{const ee=Array.from(z.clipboardData.files);ee.length>0&&(z.preventDefault(),p(ee))},H=z=>{z.key!=="Enter"||z.nativeEvent.isComposing||z.shiftKey||(z.preventDefault(),q())},G=z=>{if(A){e.current&&(e.current.value=t);return}if(e.current){e.current.style.height="";const ee=Math.min(eg,e.current.scrollHeight);ha<ee&&(e.current.style.height=`${ee}px`)}n(z.target.value)};return M?a.createElement(oi,null,a.createElement(ai,{disabled:!0}),a.createElement(ni,null,a.createElement(ri,null,a.createElement(si,{rows:1,...$.input.props,disabled:!0,placeholder:O,$blocked:!0,$focusVisible:!1,"data-focus-visible":"false"})))):a.createElement(oi,{"data-message-composer":""},a.createElement(ai,{disabled:A}),a.createElement(ni,null,a.createElement(ey,null),a.createElement(ri,null,a.createElement(si,{ref:e,rows:1,...$.input.props,readOnly:T,"aria-disabled":T?"true":void 0,placeholder:O,maxLength:5e3,$blocked:A,$focusVisible:u,"data-focus-visible":u?"true":"false",onKeyDown:H,onChange:G,onFocus:c.onFocus,onBlur:c.onBlur,onPaste:W}))),x&&a.createElement(Ec,{...$.send.props,onClick:()=>q()},a.createElement(te,{type:"send",color:v.color.primary.main,size:20}),$.send.descriptionNode))},oy=b.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:${v.themedColor.textLowEmphasis};&& a{font-weight:700;text-decoration:none;${ne.light`
|
|
456
|
+
color: ${v.color.information.light};
|
|
457
457
|
`};
|
|
458
458
|
${ne.dark`
|
|
459
|
-
color: ${
|
|
459
|
+
color: ${v.color.information.main};
|
|
460
460
|
`};
|
|
461
461
|
}
|
|
462
|
-
`,bS=l.lazy(()=>Promise.resolve().then(()=>require("./cjs/TEfZbcKQ.cjs")).then(e=>({default:e.MarkdownText}))),vS=()=>{const{aiAgentInfo:e,userSession:t}=Oe(),{handlers:n}=ue(),{messageSource:r,channelSource:s}=Ae(),[o,i]=l.useState(null),c=es("special-notice",s.channel),u=l.useCallback(()=>s.channel?c?r.messages.some(d=>et(d,(t==null?void 0:t.userId)??"")):!0:null,[s.channel,c,r.messages,t==null?void 0:t.userId]);return l.useEffect(()=>{o||i(u())},[u,o]),o||!e.specialNotice?null:a.createElement(CS,null,a.createElement(bS,{onClickLink:n.onClickLink},e.specialNotice))},SS=()=>a.createElement(yS,null,a.createElement(vS,null),a.createElement(sS,null,a.createElement(ES,null))),yS=C.default.div`z-index:0;border:none;width:100%;`,AS=()=>{var s;const{testerType:e}=nc(),{channelSource:t}=Ae(),n=Ne(t.channel),r=!!e&&((s=t.channel)==null?void 0:s.isAIAgent);return n&&r?a.createElement(tS,null):a.createElement(SS,null)},oc=({start:e,title:t,titleAlign:n="start",end:r,containerProps:s})=>{const o=l.useRef(null),i=l.useRef(null),[c,u]=l.useState(0),[d,m]=l.useState(0);return l.useLayoutEffect(()=>{o.current&&u(o.current.offsetWidth),i.current&&m(i.current.offsetWidth)},[e,r]),a.createElement(TS,{...s},a.createElement(IS,null,n==="center"&&t&&a.createElement(xS,{$sideWidth:Math.max(c,d)},a.createElement(RS,null,t)),a.createElement(MS,null,a.createElement(wS,{ref:o},e),(n==="start"||n==="end")&&t&&a.createElement(LS,{$align:n,$hasStart:!!e,$hasEnd:!!r},t),a.createElement(kS,{ref:i},r))))},TS=C.default.div`position:relative;width:100%;background-color:${({theme:e})=>e.colors.base.headerBackground};border-bottom:1px solid ${b.themedColor.textDisabled};`,IS=C.default.div`position:relative;height:56px;padding:11px 12px;`,xS=C.default.div`position:absolute;left:${({$sideWidth:e})=>e}px;right:${({$sideWidth:e})=>e}px;top:0;bottom:0;display:flex;align-items:center;justify-content:center;`,RS=C.default.div`max-width:100%;overflow:hidden;`,MS=C.default.div`display:flex;flex-direction:row;align-items:center;justify-content:space-between;height:100%;z-index:1;`,wS=C.default.div`flex-shrink:0;display:flex;align-items:center;`,kS=C.default.div`flex-shrink:0;display:flex;align-items:center;`,LS=C.default.div`flex:1;overflow:hidden;display:flex;align-items:${({$align:e})=>e==="start"?"flex-start":"flex-end"};margin-left:${({$hasStart:e})=>e?8:0}px;margin-right:${({$hasEnd:e})=>e?8:0}px;`,$t=(e=16)=>tn()?e*1.5:e,OS=()=>{const{state:e}=ue(),{messenger:t}=ae(),n=$t(),r=()=>{e.setOpened(!1)};return a.createElement(nt,{...t.closeButton().props,type:"close",size:n,onClick:r})},NS=()=>{const{enableCloseConversationButton:e,dispatcher:t}=ue(),{channelSource:n}=Ae(),{conversation:r}=ae(),s=n.channel,o=$t(),i=(s==null?void 0:s.isAIAgent)&&e,c=!Gr(s);if(!i)return null;const u={close:r.header.closeConversationButton()},d=async()=>{s&&await t.send(it.CloseConversation({channelUrl:s.url}))};return a.createElement(a.Fragment,null,a.createElement(nt,{...u.close.props,type:"mute",size:o,disabled:c,onClick:d}),u.close.descriptionNode)},DS=()=>{const{state:e,enableExpandButton:t}=ue(),{messenger:n}=ae(),r=$t();return t?a.createElement(nt,{...n.expandButton(e.expanded).props,type:e.expanded?"collapse":"expand",size:r,onClick:()=>e.setExpanded(!e.expanded)}):null},$S=({label:e,children:t,position:n="top",disabled:r})=>r?t:a.createElement($r,null,t,a.createElement(US,{$position:n},a.createElement(BS,{variant:"caption1"},e),a.createElement(PS,{$position:n}))),PS=({$position:e})=>a.createElement("svg",{style:{transform:e==="top"?"rotate(0)":"rotate(180deg)"},xmlns:"http://www.w3.org/2000/svg",width:"12",height:"6",viewBox:"0 0 12 6",fill:"none"},a.createElement("path",{d:"M6 6L0 0h12L6 6Z",fill:b.themedColor.textHighEmphasis})),FS={top:U.css`flex-direction:column;top:0;transform:translate(-50%,-100%);`,bottom:U.css`flex-direction:column-reverse;bottom:0;transform:translate(-50%,100%);`},$r=C.default.div`position:relative;`,US=C.default.div`display:flex;align-items:center;position:absolute;left:50%;z-index:${Et.TOOLTIP};${({$position:e})=>FS[e]}opacity:0;transition:opacity 0.2s ease-in-out;pointer-events:none;${$r}:hover &,${$r}:focus-within &{opacity:1;}`,BS=C.default(B)`padding:6px 8px;background:${b.themedColor.textHighEmphasis};color:${b.themedColor.textHighEmphasisInverse};border-radius:4px;font-size:12px;white-space:nowrap;`,HS=2e3,Zo=0,GS=1500,En=Symbol("header-focus-status-pause"),Jo="data-sb-header-focus-protected",zS="[data-message-composer]",Qo=new WeakMap,gr=e=>{const t=Qo.get(e);if(t)return t;const n={focusedTargetIds:new Set,pendingBlurTimeouts:new Map,maxPauseTimeout:null};return Qo.set(e,n),n},pr=(e,t)=>{const n=e.pendingBlurTimeouts.get(t);n&&(clearTimeout(n),e.pendingBlurTimeouts.delete(t))},Sn=e=>{e.maxPauseTimeout&&(clearTimeout(e.maxPauseTimeout),e.maxPauseTimeout=null)},VS=e=>{e.pendingBlurTimeouts.forEach(t=>clearTimeout(t)),e.pendingBlurTimeouts.clear(),e.focusedTargetIds.clear(),Sn(e)},KS=e=>{const t=e.hasAttribute("tabindex"),n=e.getAttribute("tabindex");return t||e.tabIndex>=0?()=>{}:(e.setAttribute("tabindex","-1"),()=>{if(n===null){e.removeAttribute("tabindex");return}e.setAttribute("tabindex",n)})},qS=e=>e instanceof HTMLBodyElement||(e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&e.disabled?!0:(e instanceof HTMLElement&&e.closest(zS),!1),Es=()=>{const{setStatusPauseState:e}=ct(),t=l.useRef(Symbol("header-focus-target")),n=l.useRef(!1),r=l.useRef(0),s=l.useRef(null),o=l.useCallback(()=>{s.current&&(clearTimeout(s.current),s.current=null)},[]),i=l.useCallback(()=>{if(n.current)return;n.current=!0,r.current=Date.now()+GS,o();const u=gr(e);pr(u,t.current),u.focusedTargetIds.add(t.current),u.focusedTargetIds.size===1&&e(En,!0),Sn(u),u.maxPauseTimeout=setTimeout(()=>{VS(u),e(En,!1)},HS)},[o,e]),c=l.useCallback(u=>{if(!n.current)return;n.current=!1;const d=u.currentTarget,m=gr(e),h=d instanceof HTMLElement&&Date.now()<=r.current;pr(m,t.current),h&&(o(),s.current=setTimeout(()=>{if(s.current=null,!(d instanceof HTMLElement)||!d.isConnected)return;const g=d.ownerDocument.activeElement,p=g instanceof HTMLElement&&g.hasAttribute(Jo);if(g===d||p||!qS(g))return;const v=KS(d);d.focus({preventScroll:!0}),v()},Zo)),m.pendingBlurTimeouts.set(t.current,setTimeout(()=>{m.pendingBlurTimeouts.delete(t.current),m.focusedTargetIds.delete(t.current),m.focusedTargetIds.size===0&&(Sn(m),e(En,!1))},Zo))},[o,e]);return l.useEffect(()=>()=>{const u=gr(e);n.current=!1,o(),pr(u,t.current),u.focusedTargetIds.delete(t.current)&&u.focusedTargetIds.size===0&&(Sn(u),e(En,!1))},[o,e]),{[Jo]:"true",onFocus:i,onBlur:c}},WS=()=>{const{logger:e}=ue(),{stringSet:t}=ie(),{channelSource:n}=Ae(),{conversation:r}=ae(),s=n.channel,o=$t(),i=es("handoff-button",s),c=!Gr(s)||at(s),[u,d]=l.useState(!1),m=Es(),h=async()=>{d(!1);try{const g=await(s==null?void 0:s.markConversationAsHandoff());e.info("conversation.handleAgentHandoff: success",g)}catch(g){e.error("conversation.handleAgentHandoff: error",g)}};if(!i)return null;const f={handoff:r.header.handoffButton()};return a.createElement(a.Fragment,null,a.createElement(a.Fragment,null,a.createElement($S,{label:t.HEADER_BUTTON__AGENT_HANDOFF,position:"bottom",disabled:c},a.createElement(nt,{...f.handoff.props,type:"agent",size:o,disabled:c,...m,onClick:()=>d(!0)})),f.handoff.descriptionNode),a.createElement(gt,{portalContainerId:Se.WINDOW,visible:u,onClose:()=>d(!1)},a.createElement(gs,{title:t.HANDOFF_CONFIRM__TITLE,description:t.HANDOFF_CONFIRM__DESCRIPTION,negativeText:t.HANDOFF_CONFIRM__CANCEL,positiveText:t.HANDOFF_CONFIRM__HANDOFF,onCancel:()=>d(!1),onConfirm:h})))},YS=l.lazy(()=>Promise.resolve().then(()=>require("./cjs/TEfZbcKQ.cjs")).then(e=>({default:e.MarkdownText}))),jS=()=>{const{logger:e,_aiAgentSDK:t}=ue(),{stringSet:n}=ie(),{memoryInfo:r,sdkUser:s}=Oe(),{actions:o}=Ae(),{conversation:i}=ae(),c=$t(20),u=Es(),[d,m]=l.useState(null),[h,f]=l.useState(!1),g=l.useRef(!1);if(l.useEffect(()=>{s&&(r!=null&&r.consentDialog)&&m({...r})},[s,r==null?void 0:r.consentDialog]),!s||!r)return null;const p=i.header.memoryIndicator(r.enabled),v=(A,y,T)=>{t.liveMetricManager.track({type:"memory",variant:A,action:y,deleteOnOff:T})},E=()=>m(null),_=async A=>{if(!g.current){g.current=!0,f(!1);try{await o.setUserMemoryState({enabled:A}),E()}catch(y){e.error("memoryIndicator.setUserMemoryState: error",y),f(!0)}finally{g.current=!1}}};return a.createElement(a.Fragment,null,r.showIndicator&&a.createElement(a.Fragment,null,a.createElement(QS,{...p.props,as:"button",type:"button",onClick:()=>m({...r}),...u,$size:c},a.createElement(ee,{type:"memory",size:c,color:b.themedColor.textHighEmphasis}),a.createElement(ey,{$enabled:r.enabled})),p.descriptionNode),d&&a.createElement(XS,{memoryInfo:d,onClose:E,onSetEnabled:_,trackMemory:v}),a.createElement(nn,{visible:h,title:n.PLACE_HOLDER__WRONG,description:n.MEMORY__ERROR_MESSAGE,onClose:()=>f(!1)}))},XS=({memoryInfo:e,onClose:t,onSetEnabled:n,trackMemory:r})=>{var _;const{stringSet:s}=ie(),{colors:o}=U.useTheme(),i=l.useId(),c=l.useId(),u=vd(e),d=u==="consent",m=l.useRef(!1),h=l.useRef(!1),f=A=>{A!=="shown"&&(h.current=!0),r(u,A,e.deleteOnOff)};l.useEffect(()=>{m.current||(m.current=!0,f("shown"))},[]);const g=()=>{h.current||f("dismiss"),t()},p={consent:{body:((_=e.consentDialog)==null?void 0:_.body)??"",negativeText:s.MEMORY__BUTTON_DONT_USE,positiveText:s.MEMORY__BUTTON_USE,onCancel:()=>n(!1),onConfirm:()=>n(!0)},on:{body:s.MEMORY__DESC_ON,negativeText:e.deleteOnOff?s.MEMORY__BUTTON_DISABLE_AND_DELETE:s.MEMORY__BUTTON_DISABLE,positiveText:s.MEMORY__BUTTON_KEEP_USING,onCancel:()=>n(!1),onConfirm:t},off:{body:s.MEMORY__DESC_OFF,negativeText:s.MEMORY__BUTTON_ENABLE,positiveText:s.MEMORY__BUTTON_KEEP_OFF,onCancel:()=>n(!0),onConfirm:t},readonly:{body:e.enabled?s.MEMORY__DESC_ON:s.MEMORY__DESC_OFF,negativeText:void 0,positiveText:s.MEMORY__BUTTON_CANCEL,onCancel:void 0,onConfirm:t}}[u],{onCancel:v}=p,E=o.memoryDialog;return a.createElement(gt,{visible:!0,portalContainerId:Se.WINDOW,onClose:g,cancelable:!d,"aria-labelledby":i,"aria-describedby":c},a.createElement(gs,{title:s.MEMORY__DIALOG_TITLE,titleId:i,description:a.createElement(ZS,null,p.body),descriptionId:c,negativeText:p.negativeText,positiveText:p.positiveText,buttonLayout:d?"horizontal":"vertical-full-width",onCancel:v&&(()=>{f("cancel"),v()}),onConfirm:()=>{f("confirm"),p.onConfirm()},styles:{titleColor:E.titleText,positiveBackground:E.positiveBackground,positiveText:E.positiveText,positiveBorderColor:E.positiveBorderColor,negativeBackground:E.negativeBackground,negativeText:E.negativeText,negativeBorderColor:E.negativeBorderColor}}))},ZS=({children:e})=>{const{handlers:t}=ue();return a.createElement(ty,null,a.createElement(Yt,{fallback:e},a.createElement(YS,{onClickLink:t.onClickLink},e)))},JS=U.css`all:unset;box-sizing:border-box;width:${({$size:e})=>e}px;height:${({$size:e})=>e}px;display:flex;align-items:center;justify-content:center;position:relative;`,QS=C.default.button`${JS};cursor:pointer;${xe}`,ey=C.default.span`position:absolute;top:0;inset-inline-end:0;width:8px;height:8px;border-radius:999px;background-color:${({$enabled:e})=>e?b.themedColor.secondary:b.color.background300};box-shadow:0 0 0 2px ${b.color.background50};${ne.dark`
|
|
463
|
-
box-shadow: 0 0 0 2px ${
|
|
462
|
+
`,iy=l.lazy(()=>Promise.resolve().then(()=>require("./cjs/TEfZbcKQ.cjs")).then(e=>({default:e.MarkdownText}))),ay=()=>{const{aiAgentInfo:e,userSession:t}=De(),{handlers:n}=ge(),{messageSource:r,channelSource:s}=Me(),[o,i]=l.useState(null),c=ls("special-notice",s.channel),u=l.useCallback(()=>s.channel?c?r.messages.some(d=>Fe(d,(t==null?void 0:t.userId)??"")):!0:null,[s.channel,c,r.messages,t==null?void 0:t.userId]);return l.useEffect(()=>{o||i(u())},[u,o]),o||!e.specialNotice?null:a.createElement(oy,null,a.createElement(yt,{fallback:e.specialNotice},a.createElement(iy,{onClickLink:n.onClickLink},e.specialNotice)))},cy=()=>a.createElement(ly,null,a.createElement(ay,null),a.createElement(Vv,null,a.createElement(sy,null))),ly=b.default.div`z-index:0;border:none;width:100%;`,uy=()=>{var s;const{testerType:e}=gc(),{channelSource:t}=Me(),n=$e(t.channel),r=!!e&&((s=t.channel)==null?void 0:s.isAIAgent);return n&&r?a.createElement(Hv,null):a.createElement(cy,null)},_c=({start:e,title:t,titleAlign:n="start",end:r,containerProps:s})=>{const o=l.useRef(null),i=l.useRef(null),[c,u]=l.useState(0),[d,m]=l.useState(0);return l.useLayoutEffect(()=>{o.current&&u(o.current.offsetWidth),i.current&&m(i.current.offsetWidth)},[e,r]),a.createElement(dy,{...s},a.createElement(my,null,n==="center"&&t&&a.createElement(hy,{$sideWidth:Math.max(c,d)},a.createElement(fy,null,t)),a.createElement(gy,null,a.createElement(py,{ref:o},e),(n==="start"||n==="end")&&t&&a.createElement(_y,{$align:n,$hasStart:!!e,$hasEnd:!!r},t),a.createElement(Ey,{ref:i},r))))},dy=b.default.div`position:relative;width:100%;background-color:${({theme:e})=>e.colors.base.headerBackground};border-bottom:1px solid ${v.themedColor.textDisabled};`,my=b.default.div`position:relative;height:56px;padding:11px 12px;`,hy=b.default.div`position:absolute;left:${({$sideWidth:e})=>e}px;right:${({$sideWidth:e})=>e}px;top:0;bottom:0;display:flex;align-items:center;justify-content:center;`,fy=b.default.div`max-width:100%;overflow:hidden;`,gy=b.default.div`display:flex;flex-direction:row;align-items:center;justify-content:space-between;height:100%;z-index:1;`,py=b.default.div`flex-shrink:0;display:flex;align-items:center;`,Ey=b.default.div`flex-shrink:0;display:flex;align-items:center;`,_y=b.default.div`flex:1;overflow:hidden;display:flex;align-items:${({$align:e})=>e==="start"?"flex-start":"flex-end"};margin-left:${({$hasStart:e})=>e?8:0}px;margin-right:${({$hasEnd:e})=>e?8:0}px;`,Gt=(e=16)=>cn()?e*1.5:e,Cy=()=>{const{state:e}=ge(),{messenger:t}=ue(),n=Gt(),r=()=>{e.setOpened(!1)};return a.createElement(ot,{...t.closeButton().props,type:"close",size:n,onClick:r})},Sy=()=>{const{enableCloseConversationButton:e,dispatcher:t}=ge(),{channelSource:n}=Me(),{conversation:r}=ue(),s=n.channel,o=Gt(),i=(s==null?void 0:s.isAIAgent)&&e,c=!jr(s);if(!i)return null;const u={close:r.header.closeConversationButton()},d=async()=>{s&&await t.send(ut.CloseConversation({channelUrl:s.url}))};return a.createElement(a.Fragment,null,a.createElement(ot,{...u.close.props,type:"mute",size:o,disabled:c,onClick:d}),u.close.descriptionNode)},by=()=>{const{state:e,enableExpandButton:t}=ge(),{messenger:n}=ue(),r=Gt();return t?a.createElement(ot,{...n.expandButton(e.expanded).props,type:e.expanded?"collapse":"expand",size:r,onClick:()=>e.setExpanded(!e.expanded)}):null},vy=({label:e,children:t,position:n="top",disabled:r})=>r?t:a.createElement(zr,null,t,a.createElement(Ty,{$position:n},a.createElement(Iy,{variant:"caption1"},e),a.createElement(yy,{$position:n}))),yy=({$position:e})=>a.createElement("svg",{style:{transform:e==="top"?"rotate(0)":"rotate(180deg)"},xmlns:"http://www.w3.org/2000/svg",width:"12",height:"6",viewBox:"0 0 12 6",fill:"none"},a.createElement("path",{d:"M6 6L0 0h12L6 6Z",fill:v.themedColor.textHighEmphasis})),Ay={top:F.css`flex-direction:column;top:0;transform:translate(-50%,-100%);`,bottom:F.css`flex-direction:column-reverse;bottom:0;transform:translate(-50%,100%);`},zr=b.default.div`position:relative;`,Ty=b.default.div`display:flex;align-items:center;position:absolute;left:50%;z-index:${Tt.TOOLTIP};${({$position:e})=>Ay[e]}opacity:0;transition:opacity 0.2s ease-in-out;pointer-events:none;${zr}:hover &,${zr}:focus-within &{opacity:1;}`,Iy=b.default(B)`padding:6px 8px;background:${v.themedColor.textHighEmphasis};color:${v.themedColor.textHighEmphasisInverse};border-radius:4px;font-size:12px;white-space:nowrap;`,xy=2e3,ci=0,My=1500,yn=Symbol("header-focus-status-pause"),li="data-sb-header-focus-protected",Ry="[data-message-composer]",ui=new WeakMap,Sr=e=>{const t=ui.get(e);if(t)return t;const n={focusedTargetIds:new Set,pendingBlurTimeouts:new Map,maxPauseTimeout:null};return ui.set(e,n),n},br=(e,t)=>{const n=e.pendingBlurTimeouts.get(t);n&&(clearTimeout(n),e.pendingBlurTimeouts.delete(t))},xn=e=>{e.maxPauseTimeout&&(clearTimeout(e.maxPauseTimeout),e.maxPauseTimeout=null)},ky=e=>{e.pendingBlurTimeouts.forEach(t=>clearTimeout(t)),e.pendingBlurTimeouts.clear(),e.focusedTargetIds.clear(),xn(e)},wy=e=>{const t=e.hasAttribute("tabindex"),n=e.getAttribute("tabindex");return t||e.tabIndex>=0?()=>{}:(e.setAttribute("tabindex","-1"),()=>{if(n===null){e.removeAttribute("tabindex");return}e.setAttribute("tabindex",n)})},Ly=e=>e instanceof HTMLBodyElement||(e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&e.disabled?!0:(e instanceof HTMLElement&&e.closest(Ry),!1),xs=()=>{const{setStatusPauseState:e}=ht(),t=l.useRef(Symbol("header-focus-target")),n=l.useRef(!1),r=l.useRef(0),s=l.useRef(null),o=l.useCallback(()=>{s.current&&(clearTimeout(s.current),s.current=null)},[]),i=l.useCallback(()=>{if(n.current)return;n.current=!0,r.current=Date.now()+My,o();const u=Sr(e);br(u,t.current),u.focusedTargetIds.add(t.current),u.focusedTargetIds.size===1&&e(yn,!0),xn(u),u.maxPauseTimeout=setTimeout(()=>{ky(u),e(yn,!1)},xy)},[o,e]),c=l.useCallback(u=>{if(!n.current)return;n.current=!1;const d=u.currentTarget,m=Sr(e),h=d instanceof HTMLElement&&Date.now()<=r.current;br(m,t.current),h&&(o(),s.current=setTimeout(()=>{if(s.current=null,!(d instanceof HTMLElement)||!d.isConnected)return;const g=d.ownerDocument.activeElement,p=g instanceof HTMLElement&&g.hasAttribute(li);if(g===d||p||!Ly(g))return;const C=wy(d);d.focus({preventScroll:!0}),C()},ci)),m.pendingBlurTimeouts.set(t.current,setTimeout(()=>{m.pendingBlurTimeouts.delete(t.current),m.focusedTargetIds.delete(t.current),m.focusedTargetIds.size===0&&(xn(m),e(yn,!1))},ci))},[o,e]);return l.useEffect(()=>()=>{const u=Sr(e);n.current=!1,o(),br(u,t.current),u.focusedTargetIds.delete(t.current)&&u.focusedTargetIds.size===0&&(xn(u),e(yn,!1))},[o,e]),{[li]:"true",onFocus:i,onBlur:c}},Oy=()=>{const{logger:e}=ge(),{stringSet:t}=le(),{channelSource:n}=Me(),{conversation:r}=ue(),s=n.channel,o=Gt(),i=ls("handoff-button",s),c=!jr(s)||dt(s),[u,d]=l.useState(!1),m=xs(),h=async()=>{d(!1);try{const g=await(s==null?void 0:s.markConversationAsHandoff());e.info("conversation.handleAgentHandoff: success",g)}catch(g){e.error("conversation.handleAgentHandoff: error",g)}};if(!i)return null;const f={handoff:r.header.handoffButton()};return a.createElement(a.Fragment,null,a.createElement(a.Fragment,null,a.createElement(vy,{label:t.HEADER_BUTTON__AGENT_HANDOFF,position:"bottom",disabled:c},a.createElement(ot,{...f.handoff.props,type:"agent",size:o,disabled:c,...m,onClick:()=>d(!0)})),f.handoff.descriptionNode),a.createElement(St,{portalContainerId:Te.WINDOW,visible:u,onClose:()=>d(!1)},a.createElement(As,{title:t.HANDOFF_CONFIRM__TITLE,description:t.HANDOFF_CONFIRM__DESCRIPTION,negativeText:t.HANDOFF_CONFIRM__CANCEL,positiveText:t.HANDOFF_CONFIRM__HANDOFF,onCancel:()=>d(!1),onConfirm:h})))},Ny=l.lazy(()=>Promise.resolve().then(()=>require("./cjs/TEfZbcKQ.cjs")).then(e=>({default:e.MarkdownText}))),Dy=()=>{const{logger:e,_aiAgentSDK:t}=ge(),{stringSet:n}=le(),{memoryInfo:r,sdkUser:s}=De(),{actions:o}=Me(),{conversation:i}=ue(),c=Gt(20),u=xs(),[d,m]=l.useState(null),[h,f]=l.useState(!1),g=l.useRef(!1);if(l.useEffect(()=>{s&&(r!=null&&r.consentDialog)&&m({...r})},[s,r==null?void 0:r.consentDialog]),!s||!r)return null;const p=i.header.memoryIndicator(r.enabled),C=(A,y,T)=>{t.liveMetricManager.track({type:"memory",variant:A,action:y,deleteOnOff:T})},E=()=>m(null),_=async A=>{if(!g.current){g.current=!0,f(!1);try{await o.setUserMemoryState({enabled:A}),E()}catch(y){e.error("memoryIndicator.setUserMemoryState: error",y),f(!0)}finally{g.current=!1}}};return a.createElement(a.Fragment,null,r.showIndicator&&a.createElement(a.Fragment,null,a.createElement(Uy,{...p.props,as:"button",type:"button",onClick:()=>m({...r}),...u,$size:c},a.createElement(te,{type:"memory",size:c,color:v.themedColor.textHighEmphasis}),a.createElement(By,{$enabled:r.enabled})),p.descriptionNode),d&&a.createElement(Py,{memoryInfo:d,onClose:E,onSetEnabled:_,trackMemory:C}),a.createElement(ln,{visible:h,title:n.PLACE_HOLDER__WRONG,description:n.MEMORY__ERROR_MESSAGE,onClose:()=>f(!1)}))},Py=({memoryInfo:e,onClose:t,onSetEnabled:n,trackMemory:r})=>{var _;const{stringSet:s}=le(),{colors:o}=F.useTheme(),i=l.useId(),c=l.useId(),u=Zd(e),d=u==="consent",m=l.useRef(!1),h=l.useRef(!1),f=A=>{A!=="shown"&&(h.current=!0),r(u,A,e.deleteOnOff)};l.useEffect(()=>{m.current||(m.current=!0,f("shown"))},[]);const g=()=>{h.current||f("dismiss"),t()},p={consent:{body:((_=e.consentDialog)==null?void 0:_.body)??"",negativeText:s.MEMORY__BUTTON_DONT_USE,positiveText:s.MEMORY__BUTTON_USE,onCancel:()=>n(!1),onConfirm:()=>n(!0)},on:{body:s.MEMORY__DESC_ON,negativeText:e.deleteOnOff?s.MEMORY__BUTTON_DISABLE_AND_DELETE:s.MEMORY__BUTTON_DISABLE,positiveText:s.MEMORY__BUTTON_KEEP_USING,onCancel:()=>n(!1),onConfirm:t},off:{body:s.MEMORY__DESC_OFF,negativeText:s.MEMORY__BUTTON_ENABLE,positiveText:s.MEMORY__BUTTON_KEEP_OFF,onCancel:()=>n(!0),onConfirm:t},readonly:{body:e.enabled?s.MEMORY__DESC_ON:s.MEMORY__DESC_OFF,negativeText:void 0,positiveText:s.MEMORY__BUTTON_CANCEL,onCancel:void 0,onConfirm:t}}[u],{onCancel:C}=p,E=o.memoryDialog;return a.createElement(St,{visible:!0,portalContainerId:Te.WINDOW,onClose:g,cancelable:!d,"aria-labelledby":i,"aria-describedby":c},a.createElement(As,{title:s.MEMORY__DIALOG_TITLE,titleId:i,description:a.createElement($y,null,p.body),descriptionId:c,negativeText:p.negativeText,positiveText:p.positiveText,buttonLayout:d?"horizontal":"vertical-full-width",onCancel:C&&(()=>{f("cancel"),C()}),onConfirm:()=>{f("confirm"),p.onConfirm()},styles:{titleColor:E.titleText,positiveBackground:E.positiveBackground,positiveText:E.positiveText,positiveBorderColor:E.positiveBorderColor,negativeBackground:E.negativeBackground,negativeText:E.negativeText,negativeBorderColor:E.negativeBorderColor}}))},$y=({children:e})=>{const{handlers:t}=ge();return a.createElement(Hy,null,a.createElement(yt,{fallback:e},a.createElement(Ny,{onClickLink:t.onClickLink},e)))},Fy=F.css`all:unset;box-sizing:border-box;width:${({$size:e})=>e}px;height:${({$size:e})=>e}px;display:flex;align-items:center;justify-content:center;position:relative;`,Uy=b.default.button`${Fy};cursor:pointer;${ke}`,By=b.default.span`position:absolute;top:0;inset-inline-end:0;width:8px;height:8px;border-radius:999px;background-color:${({$enabled:e})=>e?v.themedColor.secondary:v.color.background300};box-shadow:0 0 0 2px ${v.color.background50};${ne.dark`
|
|
463
|
+
box-shadow: 0 0 0 2px ${v.color.background500};
|
|
464
464
|
`}
|
|
465
|
-
`,
|
|
465
|
+
`,Hy=b.default.div`color:${({theme:e})=>e.colors.memoryDialog.markdownBodyText};line-height:20px;word-break:break-word;&& a{color:${({theme:e})=>e.colors.memoryDialog.markdownLinkText};font-weight:inherit;text-decoration:underline;}`,Gy=()=>{const{conversation:e}=ue(),{onNavigateToConversationList:t}=Me();if(!t)return null;const n={menu:e.header.menuButton()};return a.createElement(a.Fragment,null,a.createElement(ot,{...n.menu.props,...ia,type:"menu",size:24,onClick:()=>t()}),n.menu.descriptionNode)},Cc=({channel:e,size:t=40,skeletonColor:n=v.themedColor.bg_100_500})=>{const{userSession:r,aiAgentInfo:s}=De(),{fallbackIcon:o,url:i}=us({channel:e,aiAgentInfo:s,userSession:r}),[c,u]=l.useState();c&&c.url!==i&&u(void 0);const d=F.useTheme(),{primary:m,primaryContrastContent:h}=d.colors.base;if(!o)return a.createElement(di,{"aria-hidden":"true",$size:t,$bgColor:n});if(i&&(c==null?void 0:c.status)!=="failed"){const f=(c==null?void 0:c.status)==="loaded"?m:n;return a.createElement(ja,{src:i,size:t,"aria-hidden":"true",onImageError:g=>u({url:g,status:"failed"}),onImageLoad:g=>u({url:g,status:"loaded"}),backgroundColor:f})}return a.createElement(di,{"aria-hidden":"true",$size:t,$bgColor:m},a.createElement(te,{type:o,size:t*.55,color:h}))},di=b.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;`,zy=e=>{const{channelSource:t}=Me(),{aiAgentInfo:n,userSession:r}=De(),{conversation:s}=ue(),{config:o}=Ie(),{announcementsEnabled:i}=ht(),c=F.useTheme(),u=t.channel,d=us({channel:u,userSession:r,aiAgentInfo:n}),m=e.title??d.title,h=o.conversation.header.avatarEnabled,f=xs(),g=Ua({enabled:i,label:m}),p={title:s.header.title(m,{active:g.enabled,titleId:g.id,initialFocus:!1})};return a.createElement(Vy,null,h&&a.createElement(Cc,{channel:u,size:34,skeletonColor:c.colors.conversation.headerProfileSkeleton}),a.createElement(Ky,{...p.title.props,...f},m))},Vy=b.default.div`display:flex;flex-direction:row;align-items:center;gap:6px;min-width:0;width:100%;overflow:hidden;`,Ky=b.default(B).attrs({variant:"h2",color:v.themedColor.textHighEmphasis})`
|
|
466
466
|
margin: 0;
|
|
467
467
|
flex: 1;
|
|
468
468
|
min-width: 0;
|
|
@@ -474,10 +474,10 @@ $2
|
|
|
474
474
|
&:focus {
|
|
475
475
|
outline: none;
|
|
476
476
|
}
|
|
477
|
-
`,
|
|
477
|
+
`,qy=e=>{const{components:t}=xt.useContext();return a.createElement(_c,{start:a.createElement(t.StartArea,null),title:a.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:a.createElement(t.EndArea,null),containerProps:la})},Wy=()=>{const{components:e}=xt.useContext();return a.createElement(e.MenuButton,null)},Yy=()=>{const{components:e}=xt.useContext();return a.createElement(e.Title,null)},jy=()=>{const{components:e}=xt.useContext();return a.createElement(Zy,null,a.createElement(e.MemoryIndicator,null),a.createElement(e.HandoffButton,null),a.createElement(e.ConversationCloseButton,null),a.createElement(e.ExpandButton,null),a.createElement(e.CloseButton,null))},xt=Qe({template:qy,components:{StartArea:Wy,TitleArea:Yy,EndArea:jy,MenuButton:Gy,Title:zy,MemoryIndicator:Dy,HandoffButton:Oy,ConversationCloseButton:Sy,ExpandButton:by,CloseButton:Cy}}),Xy=()=>{const{Template:e}=xt.useContext();return a.createElement(e,{titleAlign:"start"})},Zy=b.default.div`display:flex;gap:10px;align-items:center;justify-content:center;`,Ms=({children:e,onNavigateToConversationList:t,channelUrl:n,onClearChannelUrl:r,shouldMarkAsRead:s,shouldInitializeConversation:o,initialUserMessage:i,announcementsEnabled:c=!0,conversationStatsEnabled:u,initialFocusTarget:d,style:m,closedChannelUrl:h,onClearClosedChannelUrl:f})=>{const{Template:g}=Jn.useContext();return a.createElement(Pa,{onNavigateToConversationList:t,channelUrl:n??h,onClearChannelUrl:r??f,conversationStatsEnabled:u,shouldMarkAsRead:s,shouldInitializeConversation:o,initialUserMessage:i},a.createElement($r,null,a.createElement($r.Consumer,null,p=>a.createElement(Wg,{announcementsEnabled:c},a.createElement(Jy,null),a.createElement(Qy,null),a.createElement(eA,{style:m,dragHandlers:p,initialFocusTarget:d},a.createElement(g,null)),e))))},Jy=()=>(jp(),null),Qy=()=>(lE(),eE(),iE(),null),eA=({style:e,dragHandlers:t,initialFocusTarget:n,children:r})=>{const s=l.useRef(null);return Yp(s,n),a.createElement(nA,{ref:s,style:e,...t},r)},tA=e=>{const{components:t}=Jn.useContext();return a.createElement(a.Fragment,null,a.createElement(t.Header,null),a.createElement(t.Body,null),a.createElement(t.Footer,null))},Jn=Qe({template:tA,components:{Header:Xy,Body:Iv,Footer:uy}}),nA=b.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,Sc=ye("ConversationListAnnouncements",{announcementsEnabled:!0,announceScreenEntry:Ee}),rA=Sc.Provider,Rs=Sc.useContext,sA=({children:e,announcementsEnabled:t=!0})=>{const{announceScreenEntry:n}=fs(),r=l.useCallback(o=>{t&&n(o)},[n,t]),s=l.useMemo(()=>({announcementsEnabled:t,announceScreenEntry:r}),[t,r]);return a.createElement(rA,{value:s},e)},{Provider:oA,Context:iA,useContext:dn}=ye("ConversationList");function bc({conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:n,onOpenConversationView:r=Ee,children:s}){return a.createElement(vh,{conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:n},o=>a.createElement(oA,{value:{...o,onOpenConversationView:r}},s))}const aA=e=>{const{announcementsEnabled:t}=Rs(),{listSource:n}=dn(),r=Ca();Ba(e,{enabled:t,ready:n.initialized,suppressed:r})},cA=()=>{const{announceScreenEntry:e,announcementsEnabled:t}=Rs(),{listSource:n}=dn(),r=l.useRef(!1);l.useEffect(()=>{if(!t){r.current=!1;return}if(!n.initialized||r.current)return;const s=n.channels.length,o=setTimeout(()=>{e({screen:"conversationList",conversationCount:s}),r.current=!0},0);return()=>clearTimeout(o)},[e,t,n.initialized])},lA=({channel:e})=>a.createElement(Cc,{channel:e}),Vr=99,uA=e=>{var E,_;const{channel:t,onClick:n}=e,{stringSet:r,format:s}=le(),{userSession:o,aiAgentInfo:i}=De(),{conversationList:c}=ue(),u=us({channel:t,userSession:o,aiAgentInfo:i}),d=Vd(t,{formatMultipleFilesCount:r.CONVERSATION_LIST__MULTIPLE_FILES_COUNT}),m=qd(t,s,{justNow:r.DATE_FORMAT__JUST_NOW,minutesAgo:r.DATE_FORMAT__MINUTES_AGO,hoursAgo:r.DATE_FORMAT__HOURS_AGO,dateShortFormat:r.DATE_FORMAT__DATE_SHORT}),h=t.unreadMessageCount,f=(E=t.lastMessage)!=null&&E.isAdminMessage()?r.CONVERSATION_LIST__SYSTEM_MESSAGE:u.title,g=$e(t)?r.CONVERSATION_LIST__ENDED:"",p=n?()=>n():void 0,C=c.item({agent:f,status:g,lastMessage:d,time:m,unreadCount:h,onActivate:p});return a.createElement(dA,{"data-testid":"sb-conversation-list-item",$clickable:!!p,...C.props},a.createElement(mA,null,a.createElement(lA,{...e})),a.createElement(hA,null,a.createElement(fA,null,(_=t.lastMessage)!=null&&_.isFileMessage()&&(!t.lastMessage.message||t.lastMessage.name===t.lastMessage.message)?a.createElement(qa,{variant:"subtitle1",color:v.themedColor.textHighEmphasis},d):a.createElement(B,{variant:"subtitle1",color:v.themedColor.textHighEmphasis,maxTextLines:1},d),a.createElement(gA,null,$e(t)&&a.createElement(a.Fragment,null,a.createElement(B,{variant:"caption1",color:v.themedColor.textMidEmphasis,maxTextLines:1},r.CONVERSATION_LIST__ENDED),a.createElement(pA,null)),a.createElement(B,{variant:"caption2",color:v.themedColor.textLowEmphasis,maxTextLines:1},m))),h>0&&a.createElement(EA,{$count:h},a.createElement(B,{variant:"caption3",color:v.themedColor.textHighEmphasisInverse},h<=Vr?h:`${Vr}+`))),C.descriptionNode)},ks=Qe({template:uA,components:{}}),dA=b.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"};`,mA=b.default.div`display:flex;align-items:center;justify-content:center;padding-inline-start:16px;`,hA=b.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 ${v.themedColor.textDisabled};`,fA=b.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;`,gA=b.default.div`display:flex;align-items:center;gap:6px;`,pA=b.default.div`width:2px;height:2px;border-radius:1px;background-color:${v.themedColor.textLowEmphasis};`,EA=b.default.div`display:flex;align-items:center;justify-content:center;height:20px;padding:4px;border-radius:10px;background-color:${v.themedColor.error};${({$count:e})=>e<=Vr&&F.css`
|
|
478
478
|
width: 20px;
|
|
479
479
|
`}
|
|
480
|
-
`,
|
|
480
|
+
`,_A=({items:e,renderItem:t,onEndReached:n,role:r,"aria-label":s})=>{const o=i=>{const c=i.target;c.scrollHeight-c.scrollTop-c.clientHeight<=2&&(n==null||n())};return a.createElement(CA,{role:r,"aria-label":s,onScroll:i=>o(i)},e.map((i,c)=>{const u=t(i,c);if(r!=="list")return u;const d=l.isValidElement(u)&&u.key!=null?u.key:c;return a.createElement(SA,{key:d,role:"listitem"},u)}))},CA=b.default.div`width:100%;height:100%;display:flex;flex-direction:column;flex:1;overflow:auto;overscroll-behavior:contain;`,SA=b.default.div`flex-shrink:0;`,bA=()=>{const{stringSet:e}=le(),{listSource:t,onOpenConversationView:n}=dn(),{Template:r}=ks.useContext();return t.initialized?t.channels.length===0?a.createElement(Jt,{type:"noChannels",label:e.CONVERSATION_LIST__NO_CONVERSATIONS}):a.createElement(_A,{role:"list","aria-label":e.CONVERSATION_LIST__HEADER_TITLE,items:t.channels,renderItem:s=>{var o,i,c;return a.createElement(r,{key:s.url,channel:s,onClick:()=>n(s.url,$e(s)?"closed":"open"),channelUrl:s.url,title:(i=(o=s.conversation)==null?void 0:o.topics)==null?void 0:i.join(", "),lastMessageTimestamp:(c=s.lastMessage)==null?void 0:c.createdAt})},onEndReached:()=>{t.loadMore()}}):a.createElement(Jt,{type:"loading"})},vA=()=>{const{stringSet:e}=le(),{_aiAgentSDK:t}=Ie(),{language:n,countryCode:r,context:s}=ge(),{aiAgentInfo:o,refreshActiveChannel:i,createConversation:c}=De(),{onOpenConversationView:u}=dn(),{conversationList:d}=ue(),m=async()=>{var h;if(o.isMultipleActiveConversationsEnabled){const f=await c({aiAgentId:o.userId,language:n,country:r,context:s});(h=t.session)==null||h._updateActiveChannel({url:f,status:"open"}),u(f,"open",{initialFocusTarget:"messageInput"})}else{const f=await i();u(f,"open",{initialFocusTarget:"messageInput"})}};return a.createElement(yA,{...d.footer.button({onActivate:m}).props},a.createElement(AA,{variant:"h1"},e.TALK_TO_AGENT))},yA=b.default.div`background-color:${({theme:e})=>e.colors.base.primary};display:flex;align-items:center;justify-content:center;padding:16px;cursor:pointer;`,AA=b.default(B)`color:${({theme:e})=>e.colors.base.primaryContrastContent};overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,TA=()=>{const{state:e}=ge(),{messenger:t}=ue(),n=Gt(),r=()=>{e.setOpened(!1)};return a.createElement(ot,{...t.closeButton().props,type:"close",size:n,onClick:r})},IA=()=>{const{stringSet:e}=le(),{announcementsEnabled:t}=Rs(),{conversationList:n}=ue(),r=e.CONVERSATION_LIST__HEADER_TITLE,s=Ua({enabled:t,label:r}),o={title:n.headerTitle(r,{active:s.enabled,titleId:s.id})};return a.createElement(xA,{forwardedAs:"h2",variant:"h2",color:v.themedColor.textHighEmphasis,...o.title.props},r)},xA=b.default(B)`margin:0;padding:0 4px;min-width:0;width:100%;box-sizing:border-box;text-overflow:ellipsis;overflow:hidden;white-space:nowrap;`,MA=e=>{const{components:t}=zt.useContext();return a.createElement(_c,{start:a.createElement(t.StartArea,null),title:a.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:a.createElement(t.EndArea,null),containerProps:la})},RA=()=>null,kA=()=>{const{components:e}=zt.useContext();return a.createElement(e.Title,null)},wA=()=>{const{components:e}=zt.useContext();return a.createElement(e.CloseButton,null)},zt=Qe({template:MA,components:{StartArea:RA,TitleArea:kA,EndArea:wA,Title:IA,CloseButton:TA}}),LA=()=>{const{Template:e}=zt.useContext();return a.createElement(e,{titleAlign:"start"})},OA=()=>(cA(),null),ws=({conversationListLimit:e,conversationListFilter:t,children:n,onOpenConversationView:r,announcementsEnabled:s=!0,conversationListStatsEnabled:o,style:i})=>{const{Template:c}=Qn.useContext();return a.createElement(bc,{conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:o,onOpenConversationView:r},a.createElement(sA,{announcementsEnabled:s},a.createElement(OA,null),a.createElement(NA,{style:i},a.createElement(c,null)),n))},NA=({style:e,children:t})=>{const n=l.useRef(null);return aA(n),a.createElement(PA,{ref:n,style:e},t)},DA=()=>{const{components:e}=Qn.useContext();return a.createElement(a.Fragment,null,a.createElement(e.Header,null),a.createElement(e.Body,null),a.createElement(e.Footer,null))},Qn=Qe({template:DA,components:{Header:LA,Body:bA,Footer:vA}}),PA=b.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,$A=F.css`:where(#${Te.ENTRY}) :not(code *){font-family:'Roboto',sans-serif;box-sizing:border-box;}`,FA=[$A,Sg,bg],UA=(e,...t)=>F.createGlobalStyle(e,...FA,...t),BA=UA``,HA=zd(Jn,_t,Ht,jn,Zn,Qn,xt,ks,zt,Xn,qn),GA=typeof __SBA_USE_MESSAGE_TEMPLATE__>"u"||__SBA_USE_MESSAGE_TEMPLATE__;function vc({appearance:e,rootElement:t,logger:n,language:r,languageCode:s,stringSet:o,children:i,messageTemplate:c,icons:u,theme:d,entryElement:m,modalRootElement:h}){Bg(GA?ag:"",t);const[f,g]=l.useState(null),p=l.useCallback(_=>{g(A=>A===_?A:_)},[]),C=m??f,E=a.createElement(F.StyleSheetManager,{target:t},a.createElement($g,{rootElement:t,logger:n,appearance:e,theme:d},a.createElement(dg,{rootElement:t,boundaryElement:C},a.createElement(Ih,{internalVariables:c==null?void 0:c.__internalVariables},a.createElement(Cg,{stringSet:o,logger:n,language:r,languageCode:s},a.createElement(Dg,{icons:u},a.createElement(HA,null,a.createElement(lg,{entryElement:C,modalRootElement:h,rootElement:t},i),a.createElement(BA,null))))))));return m?E:a.createElement("div",{ref:p,style:{display:"contents"}},E)}const zA=()=>{const[e,t]=l.useState(null),[n,r]=l.useState(null),s=l.useCallback(i=>{t(c=>c===i?c:i)},[]),o=l.useCallback(i=>{r(c=>c===i?c:i)},[]);return{entryElement:e,modalRootElement:n,setEntryElement:s,setModalRootElement:o}},Ls=l.forwardRef(function({rootElement:t=document.body,logLevel:n=_e.LogLevel.WARN,language:r=navigator.language,userSessionInfo:s,children:o,chatParams:i,icons:c,...u},d){var E,_,A;jt.level!==n&&(jt.level=n);const{entryElement:m,modalRootElement:h,setEntryElement:f,setModalRootElement:g}=zA();Ug("https://fonts.googleapis.com/css2?family=Roboto&display=swap",t);const p=pa(r),C=Ea.has(p)?p:an;return a.createElement("div",{ref:f,id:Te.ENTRY,lang:C,style:{width:"fit-content",height:"fit-content",...u.entryStyle}},m&&h&&a.createElement(vc,{logger:jt,rootElement:t,appearance:(E=u.agentPreviewConfigs)==null?void 0:E.appearance,stringSet:u.stringSet,language:C,messageTemplate:u.messageTemplate,icons:c,theme:u.theme,entryElement:m,modalRootElement:h},a.createElement(Cp,{rootElement:t,language:r,logger:jt,dispatcher:yc,chatParams:{...i,...u.customApiHost&&{customApiHost:u.customApiHost},...u.customWebSocketHost&&{customWebSocketHost:u.customWebSocketHost}},chatSDK:u.customChatSDK,_forceCreateChannel:(_=u.agentPreviewConfigs)==null?void 0:_.forceCreateChannel,_agentVersion:(A=u.agentPreviewConfigs)==null?void 0:A.agentVersion,...u},a.createElement(xp,{ref:d,userSessionInfo:s},a.createElement(Pv,{...u._UNSAFE_INTERNAL_dashboardTester},a.createElement(Kg,null,o))))),a.createElement("div",{ref:g,id:Te.MODAL_ROOT,dir:u.dir}))}),jt=new ki(_e.LogLevel.WARN),yc=new xi(jt),{Provider:VA,useContext:mn}=ye("PageChildren"),Ac=({children:e})=>{const[t,n]=l.useState(()=>Ms),[r,s]=l.useState(null),[o,i]=l.useState(()=>ws),[c,u]=l.useState(null),d=l.useCallback(h=>{n(()=>h)},[]),m=l.useCallback(h=>{i(()=>h)},[]);return a.createElement(VA,{value:{conversationComponent:t,setConversationComponent:d,conversationChildren:r,setConversationChildren:s,conversationListComponent:o,setConversationListComponent:m,conversationListChildren:c,setConversationListChildren:u}},e)},Os=(e,t)=>e?{role:"dialog","aria-modal":"true",...t?{"aria-labelledby":Te.WINDOW_TITLE}:{"aria-label":"Messenger"}}:{"aria-hidden":"true",inert:!0},Tc=({children:e,isOpened:t,zIndex:n=Tt.WINDOW})=>a.createElement(_s,null,a.createElement(KA,{isOpened:t,zIndex:n},e)),KA=({children:e,isOpened:t,zIndex:n=Tt.WINDOW})=>{const{dir:r,rootElement:s}=ge(),o=Et(s,!0),i=l.useRef(null),{hasWindowTitleReference:c,isWindowNameReady:u}=Wn();return Kn(t,i,{nameReady:u}),l.useEffect(()=>{const d="sb-agent-block-scroll";return t?o.body.classList.add(d):o.body.classList.remove(d),()=>{o.body.classList.remove(d)}},[o,t]),a.createElement(qA,{ref:i,id:Te.WINDOW,dir:r,...Os(t,c),$visible:t,$zIndex:n},e)},qA=b.default.div`width:100%;height:100%;position:fixed;top:0;left:0;z-index:${({$zIndex:e})=>e};visibility:${({$visible:e})=>e?"visible":"hidden"};`,WA=48,YA=2/3,mi=12;function Ic({className:e,children:t,isOpened:n,onClick:r,"aria-label":s,"aria-describedby":o,type:i,imageUrl:c,dir:u,animated:d=!0,backgroundColor:m,size:h=WA,hasUnread:f=!1}){const g=Za(),p=d&&!g,C=kr(m),E=Math.round(h*YA);return a.createElement(ZA,{dir:u,id:Te.LAUNCHER,className:e,"aria-label":s,"aria-describedby":o,onClick:r,$animated:p,$backgroundColor:m,$prefersReducedMotion:g,$size:h},a.createElement(JA,{$isOpened:n,$animated:p,$fillColor:C,$iconSize:E,$prefersReducedMotion:g},a.createElement(hi.Open,{url:c,isDefaultIcon:i==="default_icon",size:E})),a.createElement(QA,{$isOpened:n,$animated:p,$fillColor:C,$iconSize:E,$prefersReducedMotion:g},a.createElement(hi.Close,{size:E})),f&&a.createElement(eT,null),t)}const jA=F.css`&:hover{transition:transform 250ms cubic-bezier(0.33,0,0,1);transform:scale(1.1);}&:active{transform:scale(0.8);}`,XA=F.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===Qt.WHITE?"grayscale(100%) brightness(2000%)":"grayscale(100%) invert(100%) saturate(0%) brightness(0%) contrast(1000%)"};}}`,xc=F.css`svg{width:${({$iconSize:e})=>e}px;height:${({$iconSize:e})=>e}px;${({$fillColor:e})=>F.css`
|
|
481
481
|
ellipse,
|
|
482
482
|
path {
|
|
483
483
|
fill: ${e};
|
|
@@ -487,7 +487,7 @@ $2
|
|
|
487
487
|
}
|
|
488
488
|
`}
|
|
489
489
|
}
|
|
490
|
-
`,
|
|
490
|
+
`,ZA=b.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:${La};${({$animated:e})=>e&&jA}`,Mc=b.default.span.attrs({"aria-hidden":"true"})`
|
|
491
491
|
position: absolute;
|
|
492
492
|
width: 100%;
|
|
493
493
|
height: 100%;
|
|
@@ -497,23 +497,23 @@ $2
|
|
|
497
497
|
display: flex;
|
|
498
498
|
justify-content: center;
|
|
499
499
|
align-items: center;
|
|
500
|
-
`,
|
|
500
|
+
`,JA=b.default(Mc)`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)")};${XA}${xc}`,QA=b.default(Mc)`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)")};${xc}`,eT=b.default.span.attrs({"aria-hidden":"true"})`
|
|
501
501
|
position: absolute;
|
|
502
502
|
top: 1px;
|
|
503
503
|
inset-inline-end: 1px;
|
|
504
|
-
width: ${
|
|
505
|
-
height: ${
|
|
504
|
+
width: ${mi}px;
|
|
505
|
+
height: ${mi}px;
|
|
506
506
|
border-radius: 50%;
|
|
507
|
-
background-color: ${
|
|
508
|
-
`,
|
|
507
|
+
background-color: ${v.themedColor.error};
|
|
508
|
+
`,hi={Open:e=>e.url?a.createElement("img",{src:e.url,alt:"","data-default-icon":e.isDefaultIcon}):a.createElement(te,{size:e.size,type:"delight"}),Close:({size:e})=>a.createElement(te,{size:e,type:"chevron-down"})};function Rc({className:e,size:t,entryPoint:n="Conversation",activeRoute:r}){const{colors:s}=F.useTheme(),{chatSDK:o,config:i,dir:c,state:u}=ge(),{resolveElement:d}=ms(),{launcher:m}=ue(),{launcherInfo:h}=De(),f=i.launcher.unreadBadgeEnabled,g=qi(),p=uf(o,{enabled:f,opened:u.opened,filter:g}),C=(r??n)==="ConversationList",E={launcher:m.button({isOpened:u.opened,opensConversationList:C})};lf("launcher_toggle"),nT();const _=()=>{Re(()=>{const T=d(Te.WINDOW),M=T?xa(T):null;M==null||M.focus()})},A=()=>{Re(()=>{var T;(T=d(Te.LAUNCHER))==null||T.focus()})},y=()=>{const T=!u.opened;u.setOpened(T),T?_():A()};return a.createElement(Ic,{dir:c,className:e,isOpened:u.opened,onClick:y,type:h.type,imageUrl:h.imageUrl,backgroundColor:s.base.primary,size:t,hasUnread:f&&!u.opened&&p,...E.launcher.props},E.launcher.descriptionNode)}const tT=1e3*60;function nT(){const{chatSDK:e,state:t,logger:n,enableAutoDisconnectInLauncher:r}=ge(),s=l.useRef(null);l.useEffect(()=>{if(!r)return;function o(){s.current&&(clearTimeout(s.current),s.current=null)}function i(){e.connectionState===_e.ConnectionState.CLOSED&&(e.reconnect(),n.debug("useSDKInactivityTimeout: reconnected")),o(),n.debug("useSDKInactivityTimeout: clear disconnect schedule")}function c(){o(),s.current=setTimeout(async()=>{await e.disconnectWebSocket(),n.debug("useSDKInactivityTimeout: disconnected")},tT)}t.opened?i():(c(),n.debug("useSDKInactivityTimeout: schedule disconnect"))},[r,e,t.opened])}const kc=l.createContext(null);function er(){const e=l.useContext(kc);if(!e)throw new Error("useNavigator() must be used within <Navigator />");return e}function wc({children:e}){const t=er();return typeof e=="function"?e(t):a.createElement(a.Fragment,null,e)}function Lc({children:e}){return a.createElement(a.Fragment,null,e)}const rT=F.keyframes`0%{transform:translateY(40px);opacity:0;}100%{transform:translateY(0px);opacity:1;}`,sT=F.keyframes`0%{transform:translateY(0px);opacity:1;}100%{transform:translateY(40px);opacity:0;}`,oT=F.css`animation-name:${rT};animation-duration:0.3s;animation-fill-mode:forwards;`,iT=F.css``,aT=F.css`animation-name:${sT};animation-duration:0.3s;animation-fill-mode:forwards;`,cT=F.css`visibility:hidden;`,lT=b.default.div`position:absolute;top:0;left:0;width:100%;height:100%;${({$transitionState:e})=>{switch(e){case"entering":return oT;case"entered":return iT;case"exiting":return aT;case"exited":return cT;default:return""}}}${({$active:e})=>e?F.css`
|
|
509
509
|
z-index: 999;
|
|
510
|
-
`:
|
|
511
|
-
`;function
|
|
510
|
+
`:F.css`z-index:1;pointer-events:none;`}
|
|
511
|
+
`;function Dt({initialId:e,children:t}){const[n,r]=l.useState([e]),s=n[n.length-1],o=l.useCallback((_,A)=>{r(y=>[...y,_]),f(y=>({...y,[_]:!0})),A!=null&&A.reset&&E(y=>({...y,[_]:(y[_]||0)+1})),p(y=>({...y,[_]:"entering"})),setTimeout(()=>{p(y=>({...y,[_]:"entered"}))},300)},[]),i=l.useCallback(()=>{r(_=>{if(_.length<=1)return _;const A=_[_.length-1];return p(y=>({...y,[A]:"exiting"})),setTimeout(()=>{p(y=>({...y,[A]:"exited"})),r(y=>y.slice(0,-1))},300),_})},[]),c=l.useMemo(()=>({navigation:{navigate:o,pop:i},activeScreenId:s}),[o,i,s]),u=l.useMemo(()=>l.Children.toArray(t).filter(_=>_.type===wc),[t]),d=l.useMemo(()=>l.Children.toArray(t).filter(_=>_.type===Lc),[t]),m=l.useMemo(()=>{const _={};return u.forEach(A=>{const{id:y,lazy:T,children:M}=A.props;_[y]={lazy:T,element:typeof M=="function"?M(c):M}}),_},[u,c]),[h,f]=l.useState(()=>{const _={};return Object.entries(m).forEach(([A,{lazy:y}])=>{y===!1&&(_[A]=!0)}),_[e]=!0,_}),[g,p]=l.useState(()=>{const _={};return Object.keys(m).forEach(A=>{A===e?_[A]="entered":_[A]="exited"}),_}),[C,E]=l.useState({});return a.createElement(kc.Provider,{value:c},d,a.createElement(uT,null,Object.keys(m).map(_=>{var M;if(!h[_])return null;const A=g[_]||"exited",y=_===s,T=`${_}-${C[_]||0}`;return a.createElement(lT,{key:T,$transitionState:A,$active:y,"aria-hidden":y?void 0:!0,inert:y?void 0:!0},(M=m[_])==null?void 0:M.element)})))}const uT=b.default.div`position:relative;width:100%;height:100%;`;Dt.Screen=wc;Dt.Effect=Lc;const Ye={conv:"conv",convList:"conv-list"},dT=e=>e===Ye.convList?"ConversationList":"Conversation",Oc=({isOpened:e,entryPoint:t,selectedChannelUrl:n,setSelectedChannelUrl:r,nudgeConversation:s,onActiveRouteChange:o})=>{const{conversationComponent:i,conversationChildren:c,conversationListComponent:u,conversationListChildren:d}=mn(),[m,h]=l.useState(),f=(()=>{switch(t){case"Conversation":return Ye.conv;case"ConversationList":return Ye.convList;default:return Ye.conv}})(),g=a.createElement(a.Fragment,null,a.createElement(mT,{onOpenConversationView:(p,C)=>{r(C),h(void 0),p.navigate(Ye.conv)}}),a.createElement(fT,{onActiveRouteChange:o}));return a.createElement(Dt,{initialId:f},a.createElement(Dt.Effect,null,a.createElement(hT,{nudgeConversation:s,onNavigate:p=>{h("messageInput"),p.navigate(Ye.conv)}})),a.createElement(Dt.Screen,{id:Ye.conv},({navigation:p,activeScreenId:C})=>{const E=C===Ye.conv,_=e&&E;return a.createElement(a.Fragment,null,g,a.createElement(i,{key:n,channelUrl:n,onClearChannelUrl:()=>r(void 0),onNavigateToConversationList:()=>{h(void 0),p.navigate(Ye.convList)},announcementsEnabled:_,conversationStatsEnabled:_,shouldMarkAsRead:_,shouldInitializeConversation:_,initialUserMessage:s&&s.channelUrl===n?s.initialUserMessage:void 0,initialFocusTarget:m},c))}),a.createElement(Dt.Screen,{id:Ye.convList,lazy:!0},({navigation:p,activeScreenId:C})=>{const E=C===Ye.convList,_=e&&E;return a.createElement(a.Fragment,null,g,a.createElement(u,{announcementsEnabled:_,conversationListStatsEnabled:_,onOpenConversationView:(A,y,T)=>{r(A),h(T==null?void 0:T.initialFocusTarget),p.navigate(Ye.conv)}},d))}))},mT=({onOpenConversationView:e})=>{const{registerOnJoinedProactiveConversation:t}=De(),{navigation:n}=er();return t(({channel:r})=>{e(n,r.url)}),null},hT=({nudgeConversation:e,onNavigate:t})=>{const{navigation:n}=er();return l.useEffect(()=>{e&&t(n)},[e]),null},fT=({onActiveRouteChange:e})=>{const{activeScreenId:t}=er();return l.useEffect(()=>{e==null||e(dT(t))},[t,e]),null},gT=({isExpanded:e,isOpened:t,children:n,launcher:r})=>a.createElement(_s,null,a.createElement(pT,{isExpanded:e,isOpened:t,launcher:r},n)),pT=({isExpanded:e,isOpened:t,children:n,launcher:r})=>{const{dir:s}=ge(),o=l.useRef(null),{hasWindowTitleReference:i,isWindowNameReady:c}=Wn();return Kn(t,o,{nameReady:c}),a.createElement(ET,null,a.createElement(_T,{ref:o,dir:s,id:Te.WINDOW,...Os(t,i),$isExpanded:e,$isOpened:t},n),r)},ET=b.default.div`display:flex;flex-direction:column;gap:8px;align-items:flex-end;`,_T=b.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&&ST};${({$isExpanded:e})=>e&&CT};`,CT=F.css`width:743px;height:723px;`,ST=F.css`pointer-events:all;transform:scale(1);opacity:1;transition:width 200ms ease 0s,height 200ms ease 0s,max-height 200ms ease 0s,transform 300ms cubic-bezier(0,1.2,1,1) 0s,opacity 83ms ease-out 0s;`,Nc=({isMessengerOpened:e,onConversationStarted:t,className:n})=>{const{stringSet:r}=le(),{dir:s}=ge(),{nudgeMessage:o,nudgeMessageKey:i,dismissNudgeMessage:c,startNudgeConversation:u}=$h({isMessengerOpened:e,onConversationStarted:t});return o?a.createElement(vT,{key:i,className:n,dir:s},a.createElement(yT,{onClick:u},a.createElement(AT,{variant:"body3",color:v.themedColor.textHighEmphasis,maxTextLines:2},o.message)),a.createElement(TT,{type:"close",size:16,"aria-label":r.A11Y_DISMISS_NUDGE_MESSAGE,onClick:c})):null},Dc=12,bT=F.keyframes`from{opacity:0;transform:scale(0.8);}`,vT=b.default.div`position:relative;display:flex;align-items:flex-start;gap:8px;padding:16px;min-width:120px;max-width:320px;box-sizing:border-box;border-radius:${Dc}px;background-color:${v.themedColor.bg_50_600};box-shadow:${La};animation-name:${bT};animation-duration:0.3s;animation-timing-function:cubic-bezier(0.31,-0.105,0.43,1.4);@media (prefers-reduced-motion:reduce){animation-name:none;}`,yT=b.default.button`all:unset;flex:1;min-width:0;cursor:pointer;text-align:start;${ke}&::after{content:'';position:absolute;inset:0;border-radius:${Dc}px;}`,AT=b.default(B)`line-height:20px;overflow-wrap:anywhere;white-space:pre-line;`,TT=b.default(ot)`position:relative;margin:-4px;`,IT=l.forwardRef(function({children:e,initialChannelUrl:t,...n},r){const s=cn(),[o,i]=l.useState(t),[c,u]=l.useState(),[d,m]=l.useState(n.entryPoint??"Conversation"),h=s?Tc:gT;return a.createElement(Ls,{enableExpandButton:!s,ref:r,...n},a.createElement(Ra,null,({state:f})=>a.createElement(Ac,null,a.createElement(h,{isExpanded:f.expanded,isOpened:f.opened,...s&&{zIndex:"auto"},launcher:a.createElement(a.Fragment,null,a.createElement(Nc,{isMessengerOpened:f.opened,onConversationStarted:g=>{i(g.channelUrl),u(g),f.setOpened(!0)}}),a.createElement(Rc,{entryPoint:n.entryPoint,activeRoute:d}))},a.createElement(Oc,{isOpened:f.opened,entryPoint:n.entryPoint,selectedChannelUrl:o,setSelectedChannelUrl:i,nudgeConversation:c,onActiveRouteChange:m})),e)))}),{Provider:xT,useContext:tr}=ye("FixedMessengerStyle");function Pc(e,t,n,r=0){return F.css`&&{position:fixed;z-index:${Tt.LAUNCHER};${$c(e,t,n,r)};}`}function $c(e,t,n,r=0){const{top:s,bottom:o,start:i,end:c}=n;let u="",d="";switch(e){case"start":d=`inset-inline-start: ${nt(i)}`;break;case"end":d=`inset-inline-end: ${nt(c)}`;break}switch(t){case"top":u=`top: calc(${nt(s)} + ${r}px)`;break;case"bottom":u=`bottom: calc(${nt(o)} + ${r}px)`;break}return F.css`${u};${d};`}function MT(e){const{horizontal:t,vertical:n,margin:r,launcherSize:s}=tr();return a.createElement(RT,{...e,size:s,$horizontal:t,$vertical:n,$margin:r})}const RT=b.default(Rc)`${({$horizontal:e,$vertical:t,$margin:n})=>Pc(e,t,n)};`,kT=({isExpanded:e,isOpened:t,children:n})=>a.createElement(_s,null,a.createElement(wT,{isExpanded:e,isOpened:t},n)),wT=({isExpanded:e,isOpened:t,children:n})=>{const{dir:r}=ge(),{horizontal:s,vertical:o,margin:i,launcherSize:c}=tr(),u=l.useRef(null),{hasWindowTitleReference:d,isWindowNameReady:m}=Wn();return Kn(t,u,{nameReady:m}),a.createElement(LT,{ref:u,dir:r,id:Te.WINDOW,...Os(t,d),$isExpanded:e,$isOpened:t,$horizontal:s,$vertical:o,$margin:i,$launcherSize:c},n)},LT=b.default.div`background:${({theme:e})=>e.colors.base.background};display:flex;overscroll-behavior:none;-webkit-overflow-scrolling:auto;position:fixed;pointer-events:none;visibility:hidden;${({$horizontal:e,$vertical:t,$margin:n,$launcherSize:r})=>$c(e,t,n,r+12)};height:640px;min-height:80px;width:400px;max-width:80vw;max-height:80vh;box-shadow:0px 16px 24px 2px rgba(33,33,33,0.12),0px 6px 30px 5px rgba(33,33,33,0.08),0px 6px 10px -5px rgba(33,33,33,0.04);border-radius:16px;overflow:hidden;transition:width 200ms ease 0s,height 200ms ease 0s,max-height 200ms ease 0s,transform 150ms cubic-bezier(0,1.2,1,1) 0s,opacity 83ms ease-out 0s,visibility 0s linear 150ms;transform:scale(0.15);opacity:0;transform-origin:${({$horizontal:e,$vertical:t})=>`${e==="start"?"left":"right"} ${t}`};
|
|
512
512
|
[dir='rtl'] &:not([dir='ltr']),
|
|
513
513
|
&[dir='rtl'] {
|
|
514
514
|
transform-origin: ${({$horizontal:e,$vertical:t})=>`${e==="start"?"right":"left"} ${t}`};
|
|
515
515
|
}
|
|
516
516
|
|
|
517
|
-
${({$isOpened:e})=>e&&
|
|
518
|
-
${({$isExpanded:e})=>e&&
|
|
519
|
-
`,
|
|
517
|
+
${({$isOpened:e})=>e&&NT};
|
|
518
|
+
${({$isExpanded:e})=>e&&OT};
|
|
519
|
+
`,OT=F.css`width:743px;height:723px;`,NT=F.css`z-index:${Tt.WINDOW};pointer-events:all;visibility:visible;transform:scale(1);opacity:1;transition:width 200ms ease 0s,height 200ms ease 0s,max-height 200ms ease 0s,transform 300ms cubic-bezier(0,1.2,1,1) 0s,opacity 83ms ease-out 0s,visibility 0s linear 0s;`,DT=8,PT=e=>{const{horizontal:t,vertical:n,margin:r,launcherSize:s}=tr();return a.createElement($T,{...e,$horizontal:t,$vertical:n,$margin:r,$launcherSize:s})},$T=b.default(Nc)`${({$horizontal:e,$vertical:t,$margin:n,$launcherSize:r})=>Pc(e,t,n,r+DT)};`,Fc={top:24,bottom:24,start:24,end:24},FT=l.forwardRef(function({children:e,initialChannelUrl:t,...n},r){const[s,o]=l.useState(t),[i,c]=l.useState(),[u,d]=l.useState(n.entryPoint??"Conversation"),[m,h]=l.useState("end-bottom"),[f,g]=l.useState(Fc),[p,C]=l.useState(48),E=cn(),_=E?Tc:kT,{horizontal:A,vertical:y}=l.useMemo(()=>{const[T,M]=m.split("-");return{horizontal:T==="start"?"start":"end",vertical:M==="top"?"top":"bottom"}},[m]);return a.createElement(Ls,{enableExpandButton:!E,ref:r,...n},a.createElement(Ra,null,({state:T})=>a.createElement(xT,{value:{horizontal:A,vertical:y,margin:f,launcherSize:p,setPosition:h,setMargin:g,setLauncherSize:C}},a.createElement(Ac,null,a.createElement(_,{isExpanded:T.expanded,isOpened:T.opened},a.createElement(Oc,{isOpened:T.opened,entryPoint:n.entryPoint,selectedChannelUrl:s,setSelectedChannelUrl:o,nudgeConversation:i,onActiveRouteChange:d})),a.createElement(MT,{entryPoint:n.entryPoint,activeRoute:u}),a.createElement(PT,{isMessengerOpened:T.opened,onConversationStarted:M=>{o(M.channelUrl),c(M),T.setOpened(!0)}}),e))))}),UT=e=>{var s,o,i,c;const{setPosition:t,setMargin:n,setLauncherSize:r}=tr();return l.useLayoutEffect(()=>{e.position&&t(e.position),e.margin&&n({...Fc,...e.margin}),e.launcherSize&&r(e.launcherSize)},[e.position,(s=e.margin)==null?void 0:s.top,(o=e.margin)==null?void 0:o.bottom,(i=e.margin)==null?void 0:i.start,(c=e.margin)==null?void 0:c.end,e.launcherSize]),null},BT=({children:e})=>{const{setConversationChildren:t}=mn();return l.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},HT=({component:e})=>{const{setConversationComponent:t}=mn();return l.useLayoutEffect(()=>(t(e),()=>t(Ms)),[e,t]),null},GT=({children:e})=>{const{setConversationListChildren:t}=mn();return l.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},zT=({component:e})=>{const{setConversationListComponent:t}=mn();return l.useLayoutEffect(()=>(t(e),()=>t(ws)),[e,t]),null},VT=Object.assign(FT,{Style:UT,Conversation:HT,ConversationChildren:BT,ConversationList:zT,ConversationListChildren:GT}),KT=e=>{const{refreshActiveChannel:t}=De(),[n,r]=l.useState(!1),s=l.useRef(null),o=l.useRef(null);return l.useEffect(()=>{n&&t().then(()=>{var i;(i=s.current)==null||i.call(s),r(!1)}).catch(i=>{var c;(c=o.current)==null||c.call(o,i),r(!1)})},[n]),l.useCallback(()=>new Promise((i,c)=>{s.current=i,o.current=c,e().then(()=>r(!0)).catch(c)}),[e])};$i.set(_e.SendbirdPlatform.JS,{deviceOSPlatform:El()?_e.DeviceOsPlatform.MOBILE_WEB:_e.DeviceOsPlatform.WEB,messengerVersion:tg,keyValueStorage:og(),networkStateAdapter:sg(),foregroundStateAdapter:rg});exports.ANCHOR_REL=fa;exports.AgentProviderContainer=Ls;exports.AgentUIProviderContainer=vc;exports.AnonymousSessionInfo=Tr;exports.CSATType=st;exports.Commands=ut;exports.ConnectionDelayLayout=qn;exports.Conversation=Ms;exports.ConversationContext=Hp;exports.ConversationContextProvider=Pa;exports.ConversationHeaderLayout=xt;exports.ConversationLayout=Jn;exports.ConversationList=ws;exports.ConversationListContext=iA;exports.ConversationListContextProvider=bc;exports.ConversationListHeaderLayout=zt;exports.ConversationListItemLayout=ks;exports.ConversationListLayout=Qn;exports.DefaultMessenger=IT;exports.DeskTicketPriority=is;exports.DeskTicketStatus=os;exports.FixedMessenger=VT;exports.ID_INCOMING=Ke;exports.IncomingMessageLayout=_t;exports.LauncherBase=Ic;exports.LogLevel=Jr;exports.MARK_CHAR=ac;exports.ManualSessionInfo=wi;exports.MaskedText=ic;exports.MessageListUILayout=Zn;exports.MessageLogs=dc;exports.OutgoingMessageLayout=Ht;exports.PlaceholderLayout=Xn;exports.Prechecks=hc;exports.SystemMessageLayout=jn;exports.createMarkdownPreprocessor=fl;exports.cssVars=v;exports.flattenObject=vd;exports.mapCommonStringsToReactFormat=ga;exports.messengerDispatcher=yc;exports.noop=Ee;exports.parseToMessageTemplate=Di;exports.parseToUITemplate=Sd;exports.pickColorByTheme=bd;exports.replaceVariablesAsync=Ad;exports.replaceVariablesSync=yd;exports.useAIAgentContext=Ie;exports.useConversationContext=Me;exports.useConversationListContext=dn;exports.useLocalizationContext=le;exports.useMessageTemplateFetchingContext=Th;exports.useMessengerContext=ge;exports.useMessengerSessionContext=De;exports.useMessengerThemeContext=ba;exports.useRefreshActiveChannel=KT;
|