@sendbird/ai-agent-messenger-react 1.39.1 → 1.40.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/{Cr2LxvlJ.cjs → BoXkkKL_.cjs} +1 -1
- package/dist/cjs/{C116E0pr.cjs → D-lytti9.cjs} +1 -1
- package/dist/cjs/{C3VEshQr.cjs → D3Aoub0b.cjs} +1 -1
- package/dist/cjs/{C2Oi-KA4.cjs → De9EY1XB.cjs} +1 -1
- package/dist/cjs/{LFX2h7v2.cjs → DoR1M7Tp.cjs} +1 -1
- package/dist/cjs/{BQ8EaWkc.cjs → DsrX4pE_.cjs} +1 -1
- package/dist/cjs/TEfZbcKQ.cjs +1 -0
- package/dist/cjs/{B9JzuCyz.cjs → fdHbDI5i.cjs} +1 -1
- package/dist/cjs/{CIjjIGUs.cjs → qr4Ghr48.cjs} +1 -1
- package/dist/cjs/{CKr98WbE.cjs → s8NcCXAz.cjs} +1 -1
- package/dist/es/{DQJT1L-o.js → B6fq85PL.js} +5 -0
- package/dist/es/{yYj8P0Nc.js → BCT2_b4u.js} +5 -0
- package/dist/es/{DYWGE-YD.js → BTcqRd3n.js} +5 -0
- package/dist/es/{CPxk5f9K.js → Ba8iwsKH.js} +5 -0
- package/dist/es/{CrgvxcG1.js → CVbHhqBy.js} +5 -0
- package/dist/es/{Bz42IMvh.js → CooR-8ca.js} +7 -2
- package/dist/es/{0pQ1gLAM.js → Cwr5uDNr.js} +7 -2
- package/dist/es/{2cuzbJp5.js → D0_7HpM9.js} +11 -6
- package/dist/es/{C6lvBtlQ.js → DdfNQl2B.js} +5 -0
- package/dist/es/{DeJTwD_w.js → SygobY-d.js} +1 -1
- package/dist/es/{BQuWAZUg.js → aAk2M2E3.js} +5 -7
- package/dist/index.cjs +107 -106
- package/dist/index.d.ts +148 -8
- package/dist/index.js +3533 -3408
- package/package.json +4 -4
- package/dist/cjs/6HoSeQJQ.cjs +0 -1
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 Rc=Object.defineProperty;var Mc=(e,t,n)=>t in e?Rc(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var S=(e,t,n)=>Mc(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Ee=require("@sendbird/chat"),l=require("react"),U=require("styled-components"),ut=require("date-fns"),wc=require("date-fns/locale/en-US"),Le=require("@sendbird/chat/message"),he=require("@sendbird/chat/aiAgent"),kc=require("react-dom"),Ze=require("@sendbird/chat/groupChannel"),Lc=require("date-fns/isSameDay"),Oc=require("dompurify"),Fr=e=>e&&e.__esModule?e:{default:e};function Nc(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 Dc=Fr(Ee),a=Nc(l),C=Fr(U),$c=Fr(Oc),ri=e=>{try{return JSON.parse(e===""?"{}":e)}catch{return{}}},si=e=>{const t=ri(e);return typeof t=="object"&&t!==null?t:{}},oi=e=>typeof e=="string"?si(e):e??{},Pc=e=>!!oi(e).stream,Ts=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},ii=e=>{const t=oi(e),n=Ts(t.user_message_id)??Ts(t.respond_mesg_id);return{isStreaming:!!t.stream,hasResponseMetadata:Object.prototype.hasOwnProperty.call(t,"stream")||n!==void 0,...n!==void 0&&{userMessageId:n}}},yt="sb-agent",ai="KEY_IMG_ASPECT_RATIO",_r="*/*",se={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 yn=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(yn||{}),Vt=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(Vt||{});const Fc=e=>!!(e!=null&&e.cta_button),Uc=e=>{var t;return!!((t=e==null?void 0:e.citations)!=null&&t.length)},ci=e=>!!(e!=null&&e.form)&&!e.form.canceled_at,Bc=e=>{var t;return ci(e)&&!((t=e==null?void 0:e.form)!=null&&t.submitted_at)},Hc=e=>{var t;return!!((t=e==null?void 0:e.suggested_replies)!=null&&t.length)},Ve=e=>{let t;return{enumerable:!0,get:()=>(t??(t=e()),t)}},Xt=e=>Object.defineProperties({},{hasMessageTemplate:Ve(()=>!!(e!=null&&e.message_template)),hasCTAButton:Ve(()=>Fc(e)),hasChallenge:Ve(()=>!!(e!=null&&e.challenge)),isThinking:Ve(()=>!!(e!=null&&e.is_thinking)),hasCSAT:Ve(()=>!!(e!=null&&e.csat)),hasSuggestedReplies:Ve(()=>Hc(e)),hasCustomMessageTemplates:Ve(()=>{var t;return!!((t=e==null?void 0:e.custom_message_templates)!=null&&t.length)}),hasForm:Ve(()=>ci(e)),hasActiveForm:Ve(()=>Bc(e)),hasSteward:Ve(()=>!!(e!=null&&e.steward)),hasCitations:Ve(()=>Uc(e))}),Gc=e=>{const t=Xt(e);return t.hasMessageTemplate||t.hasCTAButton||t.hasCSAT||t.hasSuggestedReplies||t.hasForm||t.hasSteward||t.hasCitations},li=e=>{var t;return!!((t=e==null?void 0:e.extendedMessagePayload)!=null&&t.steward)},zc=e=>e===Vt.COMPLETED||e===Vt.CANCELED?e:Vt.IN_PROGRESS,Zn=e=>Qe(e)&&!li(e),Qe=e=>!!e&&"sender"in e,Vc=(e,{aiAgentInfo:t,members:n})=>t&&et(e,t.userId)?t:(n==null?void 0:n.find(r=>r.userId===e.sender.userId))??e.sender,Kc=e=>Qe(e)?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId),qc=(e,t,n,r=!0)=>{if(!r||!Zn(e))return"single";const s=()=>{if(!Zn(t))return!1;const u=t.sender.userId===e.sender.userId,d=ut.isSameMinute(t.createdAt,e.createdAt);return u&&d},o=()=>{if(!Zn(n))return!1;const u=n.sender.userId===e.sender.userId,d=ut.isSameMinute(n.createdAt,e.createdAt);return u&&d},i=s(),c=o();return i&&c?"middle":i?"bottom":c?"top":"single"},et=(e,t)=>(()=>{var r;return Qe(e)?e.sender.userId:((r=e==null?void 0:e.sender)==null?void 0:r.userId)??void 0})()===t,Me={isAdmin:e=>e.isAdminMessage(),isCSAT:e=>{var t;return e.isAdminMessage()&&!!((t=e.extendedMessagePayload)!=null&&t.csat)},isSteward:e=>li(e),isIncoming:(e,t)=>Qe(e)&&e.sender.userId!==t,isOutgoing:(e,t)=>Qe(e)&&(e.sender.userId===t||e.sendingStatus===Le.SendingStatus.PENDING)},Ke=e=>e.startsWith("image/"),Zt=e=>e.startsWith("video/"),Wc=e=>e.startsWith("audio/"),ui=({name:e="",mimeType:t=""})=>t==="application/pdf"||/\.pdf$/i.test(e.trim()),Ur=(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"},di=(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,mi=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!di(e.message,t)}return!0},Yc=e=>{if(e.message&&e.message.trim().length>0)return!0;const t=e.extendedMessagePayload;return Gc(t)},Nn=e=>{switch(e){case"top":case"middle":return se.GAP_GROUPED;default:return se.GAP_UNGROUPED}},jc=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},Br=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 v=0;for(;c[p.start-1-v]==="\\";)v+=1;if(v%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},Is=(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)},Xc=e=>t=>{const n=Br(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("")},Zc=e=>e.replace(/\[([^\]]+)\](?!\(\s*[^\s)])/g,"\\[$1\\]"),Jc=e=>e.replace(/^([ \t]*(?:[-*+]|\d+[.)])[ \t]+)\[( |x|X)\]/gm,"$1\\[$2\\]"),Qc=/[\p{P}$+<=>^`|~]/u,cn=e=>e===void 0||/\s/.test(e),vt=e=>e!==void 0&&Qc.test(e),el=e=>{const t=[];let n=0;for(const E of Br(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[_],I=!cn(T)&&(!vt(T)||cn(y)||vt(y)),N=!cn(y)&&(!vt(y)||cn(T)||vt(T));d.push({start:E,end:_,canOpen:I&&(!N||vt(y)),canClose:N&&(!I||vt(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="",v=0;for(const E of d)E.paired||(p+=e.slice(v,E.start)+"\\_".repeat(E.end-E.start),v=E.end);return p+e.slice(v)},tl=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
|
+
`),nl=e=>e.replace(/~~/g,"\\~\\~"),rl=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("")},fr=(...e)=>(t,n)=>e.reduce((r,s)=>s(r,n),t),As=fr(Vc(fr(ys(jc,{anchorsLineEnd:!0}),qc,ys(Kc),Xc)),Wc),Jc=({convertSoftBreaks:e=!1}={})=>e?fr(Zc,As):As,Qc=typeof navigator<"u"&&navigator.product==="ReactNative",gr=(e,t)=>{const n=r=>!t||t.length===0?!0:Je(r)&&t.includes(r.sendingStatus);return Qc?e.find(n):e.findLast(n)},el=(e,t)=>{const n=gr(e,[Oe.SendingStatus.SUCCEEDED]);return n&&we.isIncoming(n,t)?n:void 0},Te=e=>{requestAnimationFrame(()=>{requestAnimationFrame(e)})};function de(){}function tl(){const e=typeof navigator<"u"?navigator.userAgent:"",t=/iPad|iPhone|iPod/.test(e),n=/Android/.test(e);return t||n}function nl(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return t.toString(16)}const ke={isStreaming(e){return kc(e.data)},isExplicitWelcomeMessage(e){var t;return((t=e.extendedMessagePayload)==null?void 0:t.bot_message_type)==="welcome"},isWelcomeMessage(e,t){var r;if(ke.isExplicitWelcomeMessage(e))return!0;if(((r=e.extendedMessagePayload)==null?void 0:r.bot_message_type)!==void 0||!Qe(e,t))return!1;const n=ni(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=`@${St}`,rl=({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=nl(`${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}}}}},li=(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 ol{constructor(t){S(this,"_params");this._params={aiAgentChannelFilter:(t==null?void 0:t.aiAgentChannelFilter)??me.AIAgentChannelFilter.INCLUDE,aiAgentConversationStatusFilter:(t==null?void 0:t.aiAgentConversationStatusFilter)??[me.ConversationStatus.OPEN,me.ConversationStatus.CLOSED],aiAgentIds:(t==null?void 0:t.aiAgentIds)??[],deskChannelFilter:(t==null?void 0:t.deskChannelFilter)??me.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===me.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!==me.DeskChannelFilter.EXCLUDE:!1}}class ui extends Xe.BaseChannelCollection{constructor(n,r){const s=new ol(r.filter),o=n,i=o.aiAgent._manager,c=r.limit??20,u=Xe.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,_,Xe.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=li(()=>{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 di{constructor(t){S(this,"subscribers",{});this.logger=t}async send(t){const n=il(),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 il=()=>{let e=de,t=de;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 wt{constructor(t={}){S(this,"payload");this.payload=t}toJSON(){return JSON.stringify({type:this.type,payload:this.payload})}}const st={CloseConversation:e=>new al(e),MessengerSettingsUpdated:e=>new cl(e),ActiveChannelUpdated:e=>new ll(e),AnonymousSessionTokenExpired:()=>new ul,AuthTokenRefreshed:()=>new dl,NudgeMessageReceived:e=>new ml(e)};class al extends wt{constructor(){super(...arguments);S(this,"type","conv.close")}}class cl extends wt{constructor(){super(...arguments);S(this,"type","messenger.settings.updated")}}class ll extends wt{constructor(){super(...arguments);S(this,"type","active.channel.updated")}}class ul extends wt{constructor(){super(...arguments);S(this,"type","anon.token.expired")}}class dl extends wt{constructor(){super(...arguments);S(this,"type","auth.token.refreshed")}}class ml extends wt{constructor(){super(...arguments);S(this,"type","nudge.message.received")}}const kt=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 kt({user_id:this.userId})}}class hl extends Jt{constructor(){super(...arguments);S(this,"metricKey","connection_connected")}}class fl extends Jt{constructor(){super(...arguments);S(this,"metricKey","connection_reconnect_started")}}class gl extends Jt{constructor(){super(...arguments);S(this,"metricKey","connection_reconnect_succeeded")}}class pl extends Jt{constructor(){super(...arguments);S(this,"metricKey","connection_reconnect_failed")}}class _l extends Jt{constructor(){super(...arguments);S(this,"metricKey","connection_disconnected")}}class El{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 hl(n):t==="reconnectStarted"?new fl(n):t==="reconnectSucceeded"?new gl(n):t==="reconnectFailed"?new pl(n):new _l(n);this.dispatch(s)}}shouldEmit(t){return t!==this.lastKey}}class Pr{constructor(t,n){S(this,"category","conversation");this.channelUrl=t,this.conversationId=n}get data(){return kt({channel_url:this.channelUrl,conversation_id:this.conversationId})}}class Cl extends Pr{constructor(){super(...arguments);S(this,"metricKey","conversation_initialized")}}class bl extends Pr{constructor(){super(...arguments);S(this,"metricKey","conversation_open")}}class vl extends Pr{constructor(){super(...arguments);S(this,"metricKey","conversation_closed")}}class Sl{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===me.ConversationStatus.INITIALIZED?new Cl(t.url,n.id):s===me.ConversationStatus.OPEN?new bl(t.url,n.id):new vl(t.url,n.id);this.dispatch(o)}}shouldEmit(t,n){return n===me.ConversationStatus.INITIALIZED?t===void 0:n===me.ConversationStatus.OPEN?t===me.ConversationStatus.INITIALIZED:t===me.ConversationStatus.OPEN}}const mi=(e,t)=>{if(e)return e.members.filter(n=>n.userId!==t).sort((n,r)=>r.joinedAt-n.joinedAt)[0]},De=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===me.ConversationStatus.CLOSED||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="closed")},Fr=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===me.ConversationStatus.OPEN||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="open")};function ot(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 yl(e){var r;const t=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff;return t?typeof t.requestedAt=="number"&&!ot(e):!1}function Al(e){var t;if(((t=e==null?void 0:e.resolution)==null?void 0:t.determinedBy)==="user")return e.resolution.isResolved}function hi(e){return!!e&&e<=Date.now()}function Tl(e){return!e.title}function Il(e,t){var n;if(e)return Tl(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 Ur{constructor(t,n){S(this,"category","handoff");this.channelUrl=t,this.conversationId=n}get data(){return kt({channel_url:this.channelUrl,conversation_id:this.conversationId})}}class xl extends Ur{constructor(){super(...arguments);S(this,"metricKey","handoff_started")}}class Rl extends Ur{constructor(){super(...arguments);S(this,"metricKey","handoff_succeeded")}}class Ml extends Ur{constructor(){super(...arguments);S(this,"metricKey","handoff_failed")}}class wl{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 xl(t.url,r.id):o==="succeeded"?new Rl(t.url,r.id):new Ml(t.url,r.id);this.dispatch(i)}}resolveStatus(t,n){if(De(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 kl{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 kt({channel_url:this.channelUrl,message_id:this.messageId,sender_type:this.senderType,created_at:this.createdAt,conversation_id:this.conversationId})}}const Ll=(e,t)=>{const n=Je(e)?e.sender.userId:void 0;return n===void 0?"system":n===t?"ai_agent":"human_agent"};class Ol{constructor(t,n){this.dispatch=t,this.getCurrentUserId=n}handleEvent({channel:t,message:n}){const{conversation:r}=t;this.shouldEmit(n,r)&&this.dispatch(new kl({channelUrl:t.url,messageId:n.messageId,senderType:Ll(n,r.aiAgentId),createdAt:n.createdAt,conversationId:r.id}))}shouldEmit(t,n){return!Qe(t,this.getCurrentUserId())&&n!==null}}class Br{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 kt({action:this.action,delete_on_off:this.deleteOnOff,user_id:this.userId})}}class Nl extends Br{constructor(){super(...arguments);S(this,"metricKey","memory_consent")}}class Dl extends Br{constructor(){super(...arguments);S(this,"metricKey","memory_on")}}class $l extends Br{constructor(){super(...arguments);S(this,"metricKey","memory_off")}}const Pl={consent:{Metric:Nl,actions:{shown:"shown",confirm:"enable",cancel:"disable"}},on:{Metric:Dl,actions:{shown:"shown",confirm:"keep",cancel:"disable",dismiss:"dismiss"}},off:{Metric:$l,actions:{shown:"shown",confirm:"keep",cancel:"enable",dismiss:"dismiss"}}};class Fl{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}=Pl[t],i=o[n];i&&this.dispatch(new s({action:i,deleteOnOff:t==="on"?r:void 0,userId:this.getCurrentUserId()}))}}class Ul{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 kt({channel_url:this.channelUrl,request_id:this.requestId,message_id:this.messageId,target:this.target,created_at:this.createdAt,conversation_id:this.conversationId})}}const Bl=e=>{switch(e){case Oe.SendingStatus.PENDING:return"pending";case Oe.SendingStatus.SUCCEEDED:return"succeeded";case Oe.SendingStatus.FAILED:return"failed";case Oe.SendingStatus.SCHEDULED:return"scheduled";default:return}};class Hl{constructor(t,n){S(this,"statusByReqId",new Map);this.dispatch=t,this.getCurrentUserId=n}handleEvent({channel:t,message:n}){var o;if(!Qe(n,this.getCurrentUserId()))return;const r=Bl(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 Ul({channelUrl:t.url,requestId:n.reqId,messageId:r==="succeeded"?n.messageId:void 0,target:ot(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 Gl{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 El(this.emit),conversation:new Sl(this.emit),handoff:new wl(this.emit),incomingMessage:new Ol(this.emit,n),outgoingMessage:new Hl(this.emit,n),memory:new Fl(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 Xe.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 Hr=(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))(Hr||{});class fi{constructor(t){S(this,"level");this.level=t}verbose(...t){this.level<=0&&console.log(`[${St}/verbose]`,...t)}debug(...t){this.level<=1&&console.log(`[${St}/debug]`,...t)}info(...t){this.level<=2&&console.log(`[${St}/info]`,...t)}warn(...t){this.level<=3&&console.warn(`[${St}/warn]`,...t)}error(...t){this.level<=4&&console.error(`[${St}/error]`,...t)}}class gi{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 pr{constructor(){S(this,"userId");S(this,"authToken");S(this,"sessionHandler")}}const zl=e=>({onSessionTokenRequired:t=>{t(null),e.send(st.AnonymousSessionTokenExpired())}}),Gr=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!=null)),Vl="ai_agent:stats",ql="conversation_initial_render",Kl="conversation_not_interactive_timeout",Yl="recovery_not_interactive_timeout",Wl="conversation_list_initial_render",jl="message_pending_stuck",Xl="aiev_auth_expired_unhandled",Zl="user_perceived_response_time",Jl="stream_stalled",Ql="ai_typing_indicator_absent_timeout",eu="rendered_content_unusable",tu=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 _r=(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)),pi=e=>typeof e=="object"&&e!==null,nu=e=>{if(pi(e))return typeof e.code=="number"?e.code:void 0},ru=e=>e instanceof Error?e.message:typeof e=="string"?e:pi(e)&&typeof e.message=="string"?e.message:"";class et{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=nu(t)??tu,this.errorDescription=ru(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=Gr({...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(Vl,t)):!1}}class Ts extends et{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 Xl}buildPayload(){return this.reason===void 0||this.aiAgentId===void 0?null:this.createPayload(this.reason,{extra:{agent_id:this.aiAgentId}})}}class Ln{constructor(t){S(this,"commitCallback");this.commitCallback=t}}class Lt extends Ln{constructor(){super(...arguments);S(this,"records",new Map)}}class _i extends Ln{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 Ei{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 ht=(e,t)=>!(e&&t&&e!==t),Er=(e,t)=>{for(const n of e)if(n.measure.userMessageId===void 0&&ht(n.measure.channelUrl,t))return!0;return!1},On=(e,t)=>{if(e.size<t)return;const n=e.keys().next();n.done||e.delete(n.value)};class su extends Ln{onPayloadParseFailed(t){new Ts().setReason("payload_parse_failed").setAIAgentId(t.aiAgentId).setCommitCallback(this.commitCallback).commit()}onCallbackNotFound(t){new Ts().setReason("callback_not_found").setAIAgentId(t.aiAgentId).setCommitCallback(this.commitCallback).commit()}clear(){}}class ou extends et{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 ql}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-_r(n,r),i=s.duration===null?null:s.duration-_r(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 iu extends Ei{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 au extends _i{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 ou().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 iu(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 cu extends et{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 Wl}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-_r(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 lu extends Ei{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 uu extends _i{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 cu().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 lu(r,this.visible),this.activeSpan}clear(){var n;(n=this.activeSpan)==null||n.cancel(),this.activeSpan=null,this.stats=null,this.authState="idle"}}class du extends et{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 Kl}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 mu extends Lt{start(t){const n=this.getKey(t==null?void 0:t.channelUrl);this.clearKey(n);const r={stats:new du().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 hu extends et{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 jl}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 fu=5e3,Is=1e4;class gu extends Lt{start(t){if(!t.requestId||this.records.has(t.requestId))return;const n=t.messageType!=="text"&&t.tracksUploadProgress===!0,s={stats:new hu().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?Is:fu;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),Is))}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 Xn extends et{constructor(){super(...arguments);S(this,"triggerType")}setTriggerType(n){return this.triggerType=n,this}getMetricKey(){return Yl}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 pu extends Lt{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 Xn().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 Xn().setCommitCallback(this.commitCallback)}createRecord(t){return{stats:new Xn().setCommitCallback(this.commitCallback),measure:{inputEnabled:t,started:!1,timer:null}}}getKey(t){return t??"__default__"}}class _u extends et{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 eu}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 Eu=500;class Cu extends Ln{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;On(this.measure.committed,Eu),this.measure.committed.add(r),new _u().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 bu extends et{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 Jl}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 xs=1e4,vt=5e3,vu=500;class Su extends Lt{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,vt))}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,vt)}}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,vt))}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<vt){this.scheduleRenderStallCheck(n,r,vt-o);return}const i=performance.now()-s.lastRawAt;if(i>=vt&&s.deliveryTimer!==null){const c=xs-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),xs))}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 bu().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)||On(this.emittedMessageChannels,vu),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 yu extends et{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 Ql}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 Rs=3e3,Au=3e4;class Tu extends Lt{constructor(){super(...arguments);S(this,"pendingAIResponseStartsByUserMessageId",new Map)}startTurn(n){this.cancelTurn(n.requestId);const r={stats:new yu().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),Au),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=>{ht(s.measure.channelUrl,n)&&(this.recordAfterTpen(s,r),this.recordBeforeTpst(s,r))})}markTypingEnded(n){const r=performance.now();this.records.forEach(s=>{ht(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||!Er(this.records.values(),r)||this.pendingAIResponseStartsByUserMessageId.has(s)||(On(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=>{ht(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=>{ht(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>=Rs&&n.stats.setBeforeTpstAbsentMs(s),n.measure.beforeTpstStartedAt=null}recordAfterTpen(n,r){if(n.measure.afterTpenStartedAt===null)return;const s=r-n.measure.afterTpenStartedAt;s>=Rs&&n.stats.setAfterTpenAbsentMs(s),n.measure.afterTpenStartedAt=null}}class Iu extends et{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 Zl}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 xu=.15,Ru=10,Mu=e=>e<=0?!1:e>=1?!0:Math.random()<e;class wu extends Lt{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)??xu}startTurn(n){if(this.collectedCount>=Ru||!Mu(this.samplingRate))return;this.collectedCount+=1;const r={stats:new Iu().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&&Er(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||!Er(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)&&ht(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)&&ht(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)||(On(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 ku(){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 Ms={isTalkToAgentViewEnabled:!0,scrollMode:"auto",newMessageIndicatorEnabled:!0,senderAvatarEnabled:!0},zr={conversation:{...Ms,messageAlertSoundEnabled:!1,list:{...Ms,deferredMarkdownElements:[]},header:{avatarEnabled:!0},input:{camera:{photoEnabled:!0},gallery:{photoEnabled:!0},fileEnabled:!0},fileViewer:{downloadEnabled:!0}},launcher:{unreadBadgeEnabled:!1}},ws=e=>e?{conversation:Nu(e.conversation),launcher:Lu(e.launcher)}:zr,Lu=e=>yt(zr.launcher,e),Ou=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},Nu=e=>{const t=zr.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={...yt(t.list,c,n),deferredMarkdownElements:Ou(n)};return{...h,messageAlertSoundEnabled:i,list:h,header:yt(t.header,r),input:{camera:yt(t.input.camera,u),gallery:yt(t.input.gallery,d),fileEnabled:m},fileViewer:yt(t.fileViewer,o)}},yt=(e,...t)=>{const n={...e};for(const r of t)r&&Object.assign(n,Gr(r));return n},Du=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}),$u=e=>({type:e.image_type||"default_icon",imageUrl:e.image_url}),Cr=e=>({enabled:e.enabled,showIndicator:e.show_indicator,toggleAllowed:e.toggle_allowed,deleteOnOff:e.delete_on_off,consentDialog:e.consent_dialog});class Pu{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=li(s=>{var o,i;(i=this._session)==null||i._updateActiveChannel({url:s.url,status:De(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 Xe.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:De(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 Fu{constructor(t){S(this,"_sdkUser");S(this,"_userSession");S(this,"_dispatcher");S(this,"_activeChannel");S(this,"_updateActiveChannel",t=>{this._activeChannel=t,this._dispatcher.send(st.ActiveChannelUpdated({channelUrl:t.url,status:t.status,conversationStatus:t.conversationStatus}))});S(this,"_updateAuthToken",t=>{this._userSession.authToken=t,this._dispatcher.send(st.AuthTokenRefreshed())});this._sdkUser=t.sdkUser,this._userSession=t.userSession,this._dispatcher=t.dispatcher,this._activeChannel=t.activeChannel}get sdkUser(){return this._sdkUser}get userSession(){return this._userSession}get activeChannel(){return this._activeChannel}}const Ci=e=>{try{const t=JSON.parse(e);return typeof t=="string"?JSON.stringify(t).slice(1,-1):e.trim()}catch{return JSON.stringify(e).slice(1,-1)}},bi=e=>JSON.parse(e),Uu=e=>JSON.parse(e);function Bu(e,t){const[n,r]=t.split(",").map(s=>s.trim());return e==="dark"&&r||n}function Hu(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 Gu({template:e,variables:t,variableKeyPattern:n,variableValueTransformer:r}){return Object.entries(t).reduce((s,[o,i])=>{if(!r&&!["number","boolean","string"].includes(typeof i))throw new Error(`If transformer is not provided, value(${o}:${i}) must be a {string, number, or boolean}`);const c=r?r(i):String(i),u=n(o);return s.replace(u,Ci(c))},e)}async function zu({template:e,variables:t,variableKeyPattern:n,variableValueTransformer:r}){return(await Promise.all(Object.entries(t).map(async([o,i])=>{const c=await r(i);return{regex:n(o),transformedValue:c}}))).reduce((o,{regex:i,transformedValue:c})=>o.replace(i,Ci(c)),e)}var Vr=(e=>(e[e.EXTERNAL_AUTH_TOKEN_EXPIRED=1]="EXTERNAL_AUTH_TOKEN_EXPIRED",e))(Vr||{});const vi=e=>typeof e=="object"&&e!==null,Zn=(e,t)=>t in e&&typeof e[t]=="string"&&e[t]!=="",Vu=e=>!vi(e)||!Zn(e,"channel_url")||!Zn(e,"ai_agent_id")||!Zn(e,"cpa_key")?null:{channelUrl:e.channel_url,aiAgentId:e.ai_agent_id,cpaKey:e.cpa_key},qu={1:Vu};function Ku(e){if(!vi(e)||!("cat"in e)||typeof e.cat!="number"||!("data"in e))return null;const t=e.cat,n=qu[t];if(!n)return null;const r=n(e.data);return r?{category:t,data:r}:null}function Yu(e,t,n,r){const s=Mc.default.init({appId:e,modules:[new Xe.GroupChannelModule,new me.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 Wu(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 ju=[400300,400301,400302,400310],Xu=Vr.EXTERNAL_AUTH_TOKEN_EXPIRED.toString(),Zu=e=>`${Xu}:${e}`;class qr{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=Ku(t),r=typeof t.cat=="number"?t.cat:void 0;if(r!==void 0&&r!==Vr.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=>ju.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}=bi(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=Zu(n),this._logger=r,this._cache=s,this._statsTrackers=o}static init(t){let n;return t.chatSDK?(Wu(t.chatSDK),n=t.chatSDK):n=Yu(t.appId,t.extensions,t.messengerVersion,t.chatParams),new qr(n,t.aiAgentId,t.logger,t.cache,t.statsTrackers)}}const Ju=e=>t=>{if(!e||e.getState()==="foregrounded"){t();return}const n=e.subscribe(r=>{r==="foregrounded"&&(n(),t())});return n},Qu=e=>()=>{let t=e.getState()==="backgrounded";const n=e.subscribe(r=>{r==="backgrounded"&&(t=!0)});return()=>(n(),t)},an=new Map,Si={set:(e,t)=>{an.set(e,t)},get:e=>{if(an.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=an.get(e);if(!n)throw new Error(`AIAgent platform "${e}" is not configured.`);return{platform:e,...n}}const t=an.entries().next().value;return{platform:t[0],...t[1]}}};class ks 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 Kr=(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))(Kr||{}),Yr=(e=>(e.URGENT="URGENT",e.HIGH="HIGH",e.MEDIUM="MEDIUM",e.LOW="LOW",e))(Yr||{}),yi=(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))(yi||{});const ed=e=>e==="desk401103"||e==="desk401106"||e==="desk401107"||e==="desk401108"||e==="desk401109";class td{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(!ed(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 ks(t.status,r)}const n=await t.text();if(n)try{return JSON.parse(n)}catch{throw new ks(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 Sn{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 Sn({id:t.id,title:t.channelName??null,status:t.status2??Kr.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??Yr.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 Wr{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 Sn._fromResponse(n,this)});S(this,"createTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request("/tickets/",{method:"POST",body:Gr({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 Sn._fromResponse(n,this)});this._logger=t.logger,this._apiClient=new td(t)}static init(t){return new Wr(t)}_assertAuthenticated(t){if(t.credential==null)throw new Error("DeskClient is not authenticated")}}class jr{constructor(){S(this,"authenticate",async t=>!1);S(this,"deauthenticate",()=>{});S(this,"refreshDeskAuthToken",async()=>!1);S(this,"setCustomerLanguage",async()=>{});S(this,"getTicket",async()=>{throw new Error("DeskClient is disabled via __SBA_USE_DESK_CLIENT__")})}static init(){return new jr}}function nd(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 rd=1440*60*1e3,sd=typeof __SBA_USE_DESK_CLIENT__>"u"||__SBA_USE_DESK_CLIENT__;function Ke(e){if(!e)throw new Error("Not authenticated. Call authenticate() first.")}function od(e,t){return Object.entries(t).every(([n,r])=>e[n]===r)}const id=e=>{const t={conversationInitialRender:new au(e),conversationNotInteractiveTimeout:new mu(e),recoveryNotInteractiveTimeout:new pu(e),conversationListInitialRender:new uu(e),aievAuthExpiredUnhandled:new su(e),messagePendingStuck:new gu(e),userPerceivedResponseTime:new wu(e),streamStalled:new Su(e),typingIndicatorAbsentTimeout:new Tu(e),renderedContentUnusable:new Cu(e)};return{...t,clear:()=>{Object.values(t).forEach(n=>n.clear())}}};class yn extends Pu{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",ku());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(st.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(st.MessengerSettingsUpdated({settings:h,source:"server"}));const g=(()=>{var v;return s.type==="anonymous"?zl(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===yi.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 Fu({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=>{Ke(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=>{Ke(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(Ke(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:me.ConversationStatus.OPEN,limit:100}),s=[];for(;r.hasNext;){const o=await r.next();for(const i of o)od(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;Ke(this._session),this._logger.debug("AIAgent.closeConversation: start",n);const r=await this._chatClient.getChannel(n);((s=r.conversation)==null?void 0:s.status)===me.ConversationStatus.OPEN?(await r.closeConversation(),this._session.activeChannel.url===n&&this._session._updateActiveChannel({url:n,status:"closed",conversationStatus:me.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 ui(this.chatSDK,n??{}));S(this,"patchContext",async(n,r)=>{Ke(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)=>{Ke(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=>{Ke(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=>{Ke(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(st.NudgeMessageReceived({message:s.payload.message,callbackUserMessage:s.payload.callback_user_message??void 0}))});S(this,"clearUserMemories",async(n={})=>{Ke(this._session);const r={...n,contextAiAgentId:n.contextAiAgentId??this.aiAgentId};this._logger.debug("AIAgent.clearUserMemories: start",r),await this._chatClient.clearUserMemories(r),this._logger.debug("AIAgent.clearUserMemories: end")});S(this,"setUserMemoryState",async n=>{Ke(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"),Cr(i);const c=this._cache.messenger.getSettings(o);if(c){const u={...c,memory:i};this._cache.messenger.setSettings(o,u),this._dispatcher.send(st.MessengerSettingsUpdated({settings:u,source:"cache"}))}return this._logger.debug("AIAgent.setUserMemoryState: end",i.enabled),Cr(i)});S(this,"refreshActiveChannel",async n=>{var c,u,d;Ke(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 gi?{type:"manual",userSessionCandidate:this._getManualSessionInfo(n)}:n instanceof pr?{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-rd<=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 pr)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=ws(n.config),this.queryParams=n.queryParams,this._networkStateAdapter=n.networkStateAdapter,this._scheduleForegroundTask=Ju(n.foregroundStateAdapter),this._watchBackgrounded=n.foregroundStateAdapter&&Qu(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 Gl(this._chatClient.chatSDK),this._liveMetricManager.start()}static init(n){var g;const r=Si.get(n.platform),s=n.logger??new fi(n.logLevel??Hr.WARN),o=n.dispatcher??new di(s),i=n.useMMKVStorage?nd(n.useMMKVStorage):r.keyValueStorage,c=n.useMMKVStorage?{...n.chatParams,useMMKVStorageStore:n.useMMKVStorage}:n.chatParams,u=rl({appId:n.appId,aiAgentId:n.aiAgentId,storage:i});let d;const h=id((p,v)=>{if(!d)throw new Error("ChatClient is not initialized.");return d.chatSDK.aiAgent.appendStat(p,v)});d=qr.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=sd?Wr.init({appId:n.appId,logger:s,customApiHost:(g=n.deskParams)==null?void 0:g.customApiHost}):jr.init();return s.debug("AIAgent.init: created",{appId:n.appId,aiAgentId:n.aiAgentId}),new yn({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=ws(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 We(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 ad(...e){return function({children:n}){return e.reduce((r,s)=>a.createElement(s,null,r),n)}}function cd(e,t){const n=e.lastMessage;return n!=null&&n.isAdminMessage()?n.message??"":ld(e,t)}function ld(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 ud(e,t,n){var i;const r=new Date,s=new Date(((i=e.lastMessage)==null?void 0:i.createdAt)||e.createdAt),o=ct.differenceInMinutes(r,s);return o<1?n.justNow:o<60?n.minutesAgo(o):ct.isToday(s)?n.hoursAgo(ct.differenceInHours(r,s)):t(s,n.dateShortFormat)}const dd=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},cn=e=>Math.max(0,Math.min(255,e)).toString(16).padStart(2,"0"),Ls=(e,t)=>{const n=cn(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=dd(e);return r?`#${cn(r[0])}${cn(r[1])}${cn(r[2])}${n}`:e},md=(e,t)=>{if(!t)return e;const n={...e};for(const[r,s]of Object.entries(t))s&&(n[r]=s);return n},hd=e=>e.consentDialog?"consent":e.toggleAllowed?e.enabled?"on":"off":"readonly",fd=e=>e.length>0,gd=e=>{const t=e[0];if(!t)return e;const n=e.some(s=>Ye(s.type)),r=e.some(s=>!Ye(s.type));return n&&r?Ye(t.type)?e.filter(s=>Ye(s.type)):[t]:r?[t]:e},Os=e=>e.length===0?"empty":e.every(t=>Ye(t.type))?"images":"non_images",pd=({currentFiles:e,incomingFiles:t,maxAttachmentCount:n})=>{const r=gd(t),s=Os(e),o=Os(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}},It=3,Ai=6,_d=e=>e%It===0?It:Ai,Ed=({index:e,itemCount:t})=>{const n=t%It,r=n>0,s=r?t-n:t,o=r&&e>=s,i=o?n:It,c=o?e-s:e%It,u=!r&&e>=t-It;return{columnSpan:r?Ai/i:1,rowItemCount:i,isLastInRow:c===i-1,isLastRow:o||u}},Ti=be("AIAgent"),Cd=Ti.Provider,ye=Ti.useContext;function bd(e){const t=vd(e);return a.createElement(Cd,{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 vd(e){var s;const t=l.useRef(null),n=l.useRef(null);if(!t.current||!n.current)t.current=yn.init(e);else{const o=Sd(n.current,e);(o.appId||o.aiAgentId||o.chatSDK)&&(t.current.dispose(),t.current=yn.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 Sd(e,t){const n=t.chatSDK!==void 0&&t.chatSDK!==null;return{appId:!n&&e.appId!==t.appId,aiAgentId:e.aiAgentId!==t.aiAgentId,chatSDK:!!e.chatSDK!==n||n&&t.chatSDK!==e.chatSDK}}function le(e){const t=l.useRef(e);return t.current=e,l.useCallback((...n)=>t.current(...n),[t])}const Nn=()=>{const[,e]=l.useState(0);return l.useCallback(()=>e(t=>t+1),[])};let yd=0;function Ad(){return l.useState(()=>`${yd++}`)[0]}const ft=(e,t,n)=>{const r=l.useRef(t),o=Ad();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 Xe.GroupChannelHandler)),()=>{var u;(u=e==null?void 0:e.groupChannel)==null||u.removeGroupChannelHandler(o)}},[e==null?void 0:e.groupChannel,o])};function Td(e,t){return!e||!t?!0:e.url!==t.url}function ze(e){return e!=null&&"sendingStatus"in e}function Id(e,t="##__USER_ID_IS_NOT_PROVIDED__##"){var n;return ze(e)?((n=e.sender)==null?void 0:n.userId)===t:!1}function xd(e,t){return Id(e,t)||e.isAdminMessage()?!1:e.updatedAt===0}function Ns(e){return"sendingStatus"in e?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId)}const An={collection:{groupChannel:{defaultOrder:Xe.GroupChannelListOrder.LATEST_LAST_MESSAGE},message:{defaultLimit:{next:25,prev:25},searchLimit:{next:10,prev:10}}}};function Ds(e){return!e||!Array.isArray(e)?!1:e.length!==0}function $s(e,t){return e.reduce((n,r)=>{const s=t(r);return n[s]=r,n},{})}const Rd=({...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=Md(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];wd(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=>xd(s,n));return t.value.clearBeforeAction?e.newMessageMap=$s(r,Ns):(r.map(o=>o.messageId).forEach(o=>delete e.newMessageMap[o]),e.newMessageMap={...e.newMessageMap,...$s(r,Ns)}),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}}},Md=e=>e.reduce((t,n)=>(ze(n)?(t[n.reqId]=n,n.sendingStatus===Oe.SendingStatus.SUCCEEDED&&(t[n.messageId]=n)):t[n.messageId]=n,t),{}),wd=(e,t,n=!1)=>{var r,s;if(!ze(e)||!ze(t))return!0;if(n&&e&&ke.isStreaming(e)&&ke.isStreaming(t)){const o=((r=e.message)==null?void 0:r.length)||0,i=((s=t.message)==null?void 0:s.length)||0;if(o>i)return!1}return e.sendingStatus===Oe.SendingStatus.SUCCEEDED?t.sendingStatus===Oe.SendingStatus.SUCCEEDED:e.sendingStatus!==t.sendingStatus},kd=(e=Ld)=>{const[{initialized:t,loading:n,refreshing:r,messageMap:s,newMessageMap:o},i]=l.useReducer(Rd,{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}},Ps=Math.floor(Number.MAX_SAFE_INTEGER/10);function Ld(e,t){let n=0,r=0;return ze(e)&&e.sendingStatus!=="succeeded"&&(n=Ps),ze(t)&&t.sendingStatus!=="succeeded"&&(r=Ps),e.createdAt+n-(t.createdAt+r)}const Od=(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 Xe.MessageFilter(r)})};function Fs(e){return e<Date.now()?An.collection.message.searchLimit:An.collection.message.defaultLimit}const Nd=(e,t,n={})=>{var Re,$;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=Fs(i),u=r.current.strictStreamingOrder??!1,d=l.useRef({prev:!1,next:!1}),m=Nn(),h=l.useRef({initialized:!1,apiInitialized:!1,instance:null}),{initialized:f,loading:g,refreshing:p,messages:v,newMessages:E,updateMessages:_,updateNewMessages:A,deleteNewMessages:y,deleteMessages:T,updateInitialized:I,updateLoading:L,updateRefreshing:N}=kd(n==null?void 0:n.sortComparator),k=le(M=>{var x,O,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 _e.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case _e.CollectionEventSource.EVENT_MESSAGE_SENT_SUCCESS:case _e.CollectionEventSource.SYNC_MESSAGE_FILL:case void 0:(P=(O=r.current).markAsRead)==null||P.call(O,[s.current]);break}}catch(re){(X=o==null?void 0:o.warn)==null||X.call(o,"[useGroupChannelMessages/markAsReadBySource]",re)}}),R=le((M,x)=>{var O,P,X,re,J;if(x.length>0)switch(M){case _e.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case _e.CollectionEventSource.SYNC_MESSAGE_FILL:{(P=(O=r.current).shouldCountNewMessages)!=null&&P.call(O)&&A(x,!1,(X=e.currentUser)==null?void 0:X.userId),(J=(re=r.current).onMessagesReceived)==null||J.call(re,x);break}}}),G=le(M=>{var x,O;(O=(x=r.current).onCollectionEvent)==null||O.call(x,M)}),D=le(async(M,x,O)=>new Promise((P,X)=>{var $e,Ct,Pt;h.current.instance&&h.current.instance.dispose(),k(),A([],!0,($e=e.currentUser)==null?void 0:$e.userId);const re=()=>{var he,fe;const{pendingMessages:ce,failedMessages:Ce}=h.current.instance??{};Ds(ce)&&_(ce,!1,(he=e.currentUser)==null?void 0:he.userId),Ds(Ce)&&_(Ce,!1,(fe=e.currentUser)==null?void 0:fe.userId)},J=Od(M,O,{...r.current,startingPoint:x});h.current={apiInitialized:!1,initialized:!1,instance:J},J.setMessageCollectionHandler({onMessagesAdded:(ce,Ce,he)=>{var fe;k(ce.source),R(ce.source,he),_(he,!1,(fe=e.currentUser)==null?void 0:fe.userId,u),G({kind:"messagesAdded",source:ce.source,channelUrl:M.url,messages:he})},onMessagesUpdated:(ce,Ce,he)=>{var fe,Pe,pe;k(ce.source),R(ce.source,he),_(he,!1,(fe=e.currentUser)==null?void 0:fe.userId,u),ce.source===_e.CollectionEventSource.EVENT_MESSAGE_UPDATED&&((pe=(Pe=r.current).onMessagesUpdated)==null||pe.call(Pe,he)),G({kind:"messagesUpdated",source:ce.source,channelUrl:M.url,messages:he})},onMessagesDeleted:(ce,Ce,he,fe)=>{const Pe=fe.map(Me=>Me.messageId),pe=fe.filter(ze).map(Me=>Me.reqId);T(Pe,pe),y(Pe,pe),G({kind:"messagesDeleted",source:ce.source,channelUrl:M.url,messages:fe})},onChannelDeleted:(ce,Ce)=>{var he,fe;(fe=(he=r.current).onChannelDeleted)==null||fe.call(he,Ce)},onChannelUpdated:(ce,Ce)=>{var he,fe;m(),(fe=(he=r.current).onChannelUpdated)==null||fe.call(he,Ce,ce)},onHugeGapDetected:()=>{D(M,Number.MAX_SAFE_INTEGER,An.collection.message.defaultLimit)}});let Ee=!1;(Pt=(Ct=r.current).onCollectionInitializeStart)==null||Pt.call(Ct),J.initialize(Xe.MessageCollectionInitPolicy.CACHE_AND_REPLACE_BY_API).onCacheResult((ce,Ce)=>{var he,fe,Pe,pe,Me;(fe=(he=r.current).onCacheResult)==null||fe.call(he,ce,Ce??[],M.url),ce?(e.isCacheEnabled&&((Pe=o==null?void 0:o.error)==null||Pe.call(o,"[useGroupChannelMessages/onCacheResult]",ce)),Ee=!0):Ce&&((pe=o==null?void 0:o.debug)==null||pe.call(o,"[useGroupChannelMessages/onCacheResult]","message length:",Ce.length),_(J.succeededMessages,!0,(Me=e.currentUser)==null?void 0:Me.userId),re(),Ce.length>0&&(h.current.initialized=!0,P())),G({kind:"initialized",source:"cache",channelUrl:M.url,messages:Ce??[],error:ce})}).onApiResult((ce,Ce)=>{var he,fe,Pe,pe,Me,Be,He;(fe=(he=r.current).onApiResult)==null||fe.call(he,ce,Ce??[],M.url),h.current.initialized=!0,h.current.apiInitialized=!0,ce?((Pe=o==null?void 0:o.warn)==null||Pe.call(o,"[useGroupChannelMessages/onApiResult]",ce),Ee?X(ce):P()):Ce&&((pe=o==null?void 0:o.debug)==null||pe.call(o,"[useGroupChannelMessages/onApiResult]","message length:",Ce.length),_(J.succeededMessages,!0,(Me=e.currentUser)==null?void 0:Me.userId),r.current.startingPoint||(He=(Be=r.current).onMessagesReceived)==null||He.call(Be,Ce),e.isCacheEnabled&&re(),P()),G({kind:"initialized",source:"api",channelUrl:M.url,messages:Ce??[],error:ce})})}));ft(e,{onUserBanned(M,x){var O,P,X;M.isGroupChannel()&&!Td(M,s.current)&&(x.userId===((O=e.currentUser)==null?void 0:O.userId)?(X=(P=r.current).onCurrentUserBanned)==null||X.call(P):m())}}),l.useLayoutEffect(()=>{const M=setTimeout(async()=>{e.currentUser&&s.current&&(I(!1),L(!0),await D(s.current,i,c),L(!1),I(!0))});return()=>clearTimeout(M)},[e,(Re=e.currentUser)==null?void 0:Re.userId,($=s.current)==null?void 0:$.url,r.current.replyType]),l.useEffect(()=>()=>{h.current.instance&&h.current.instance.dispose()},[]);const Q=le(async()=>{e.currentUser&&s.current&&(N(!0),await D(s.current,Number.MAX_SAFE_INTEGER,An.collection.message.defaultLimit),N(!1))}),ne=le(async()=>{var x;const M=h.current.instance;if(M!=null&&M.hasPrevious&&!d.current.prev)try{d.current.prev=!0;const O=await M.loadPrevious();_(O,!1,(x=e.currentUser)==null?void 0:x.userId)}catch{}finally{d.current.prev=!1}}),B=le(()=>{const{initialized:M,instance:x}=h.current;return M&&x?x.hasPrevious:!1}),H=le(async()=>{var x;const M=h.current.instance;if(M!=null&&M.hasNext&&!d.current.next)try{d.current.next=!0;const O=await M.loadNext();_(O,!1,(x=e.currentUser)==null?void 0:x.userId)}catch{}finally{d.current.next=!1}}),q=le(()=>{const{initialized:M,apiInitialized:x,instance:O}=h.current;return x&&M&&O?O.hasNext:!1}),Z=M=>{var x,O,P,X;!M||M.channelUrl!==((x=s.current)==null?void 0:x.url)||(_([M],!1,(O=e.currentUser)==null?void 0:O.userId),(X=(P=r.current).onOutgoingMessageStatusChanged)==null||X.call(P,M))},z=le((M,x)=>{var O;if(!s.current||!s.current.url)throw(O=o==null?void 0:o.error)==null||O.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((P,X)=>{s.current.sendUserMessage(M).onPending(re=>{Z(re),x==null||x(re)}).onSucceeded(re=>{Z(re),P(re)}).onFailed((re,J)=>{Z(J),X(re)})})}),Y=le((M,x)=>{var O;if(!s.current||!s.current.url)throw(O=o==null?void 0:o.error)==null||O.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((P,X)=>{s.current.sendFileMessage(M).onPending(re=>{Z(re),x==null||x(re)}).onSucceeded(re=>{Z(re),P(re)}).onFailed((re,J)=>{Z(J),X(re)})})}),W=le((M,x,O)=>{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,re)=>{s.current.sendMultipleFilesMessage(M).onPending(J=>{Z(J),x==null||x(J)}).onFileUploaded(J=>{O==null||O(J),m()}).onSucceeded(J=>{Z(J),X(J)}).onFailed((J,Ee)=>{Z(Ee),re(J)})})}),K=le(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 O=await s.current.updateUserMessage(M,x);return O.channelUrl===s.current.url&&_([O],!1,(X=e.currentUser)==null?void 0:X.userId),O}),V=le(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 O=await s.current.updateFileMessage(M,x);return O.channelUrl===s.current.url&&_([O],!1,(X=e.currentUser)==null?void 0:X.userId),O}),w=le(async(M,x,O)=>{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,re)=>{let J;M.isUserMessage()&&(J=s.current.resendMessage(M)),M.isFileMessage()&&(J=s.current.resendMessage(M)),M.isMultipleFilesMessage()&&(J=s.current.resendMessage(M)),J&&("onPending"in J&&J.onPending(Ee=>{Z(Ee),x==null||x(Ee)}),"onFileUploaded"in J&&J.onFileUploaded(Ee=>{O==null||O(Ee),m()}),"onSucceeded"in J&&J.onSucceeded(Ee=>{Z(Ee),X(Ee)}),"onFailed"in J&&J.onFailed((Ee,$e)=>{Z($e),re(Ee)}))})}),oe=le(async M=>{var x,O,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((O=h.current.instance)==null?void 0:O.removeFailedMessage(M.reqId))}finally{T([],[M.reqId]),(X=(P=r.current).onLocalMessageDeleted)==null||X.call(P,M)}}),Se=le(()=>{var M;A([],!0,(M=e.currentUser)==null?void 0:M.userId)}),xe=le(async M=>{var x;if(e.currentUser&&s.current){const O=Fs(M);L(!0),_([],!0,(x=e.currentUser)==null?void 0:x.userId),await D(s.current,M,O),L(!1)}});return{initialized:f,loading:g,refreshing:p,messages:v,newMessages:E,resetNewMessages:Se,refresh:Q,loadPrevious:ne,hasPrevious:B,loadNext:H,hasNext:q,sendUserMessage:z,sendFileMessage:Y,sendMultipleFilesMessage:W,updateUserMessage:K,updateFileMessage:V,resendMessage:w,deleteMessage:oe,resetWithStartingPoint:xe,_dangerous_reducer_updateMessages:_,_dangerous_reducer_deleteMessages:T}},Dd=e=>e.customType==="SENDBIRD_DESK_ADMIN_MESSAGE_CUSTOM_TYPE"?!0:e.isAdminMessage()?e.message==="The channel's custom_type was updated.":!1,$d=(e,t,n)=>{const r=Nd(e,t,{...n,strictStreamingOrder:!0}),s=l.useMemo(()=>r.messages.filter(o=>!Dd(o)),[r.messages]);return{...r,messages:s}},Pd=()=>{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))}}}},Ii=Pd(),Fd=({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}},Ud=({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}},Yt={DEFAULT_PRIMARY:"#000000",DEFAULT_BOT_MSG_BG:"#ECECEC",WHITE:"#ffffff",BLACK:"#000000"};function xi(e){return e.length===4?`#${[...e.slice(1)].map(t=>t+t).join("")}`:e}function Bd(e){const t=xi(e);return[parseInt(t.slice(1,3),16),parseInt(t.slice(3,5),16),parseInt(t.slice(5,7),16)]}function Hd(e){return`#${e.map(t=>t.toString(16).padStart(2,"0")).join("")}`}function Gd(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 ln(e,t,n){const[r,s,o]=Bd(e),[i,c,u]=Gd(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 Hd([Math.round(h),Math.round(f),Math.round(g)])}function Vd(e,t="light"){return{extraDark:ln(e,.6,1.2),dark:ln(e,.85,1.1),main:e,light:ln(e,t==="dark"?1.1:1.5,t==="dark"?.95:.9),extraLight:ln(e,t==="dark"?1.2:1.75,t==="dark"?.9:.8)}}function br(e){const t=xi(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?Yt.BLACK:Yt.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 Kd=(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"}}),un={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)"}},Jn={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 Us(e){const t=Yd(e),n=Wd(e,t),r=Xd(n,e.colors,e.selectedTheme),s=Jd(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 Yd({selectedTheme:e,palette:t,primary:n}){const r=t!=null&&t.primary?t.primary:n?n===un.primary.main?un.primary:Vd(n,e):un.primary;return{...un,primary:r,...t}}function Wd({selectedTheme:e,primaryContrast:t,botMessageBackground:n,botMessageBackgroundContrast:r},s){const o=s.primary.main,i=t??br(o),c=n??Yt.DEFAULT_BOT_MSG_BG,u=r??br(c);return(e==="light"?qd:Kd)(s,o,i,c,u)}function jd(e,t,n){return typeof e=="string"?e:e[t]??n}function Xd(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]=jd(m,n,h)}}}return r}function Zd(e,t,n){const r={...e};return n.forEach(s=>{const o=t[s];o!=null&&(r[s]=o)}),r}function Jd({typography:e}){if(!e)return Jn;const t={...Jn};return Object.keys(e).forEach(n=>{const r=e[n];if(r&&typeof r=="object"){const s=Jn[n],o=["fontSize","fontWeight","fontFamily","lineHeight"];t[n]=Zd(s,r,o)}}),t}const{Provider:Qd,useContext:Xr}=be("AIAgentTheme");function em({logger:e,palette:t,typography:n,colors:r,appearance:s,children:o}){const i=l.useRef(null),[c,u]=l.useState(()=>Us({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=Us({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(Qd,{value:{theme:c,updateTheme:d}},o)}const Qn=25*1024*1024,Bs=1,Hs=new Set(["image/png","image/jpeg","image/jpg"]),Gs=new Set(["application/pdf"]),tm={off:"off",always:"always",handed_off_only:"handed_off_only"},nm=()=>{const[e,t]=l.useState(()=>({maxAttachmentCount:Bs,attachmentMode:"handed_off_only",defaultUploadSizeLimit:Qn,uploadSizeLimitPerType:new Map,supportedImageMimeTypes:Hs,supportedFileMimeTypes:Gs})),n=l.useCallback(({active_channel:s,upload_restriction:o})=>{t({maxAttachmentCount:(o==null?void 0:o.max_attachment_count)??Bs,attachmentMode:tm[s.attachment_mode]??"handed_off_only",defaultUploadSizeLimit:(o==null?void 0:o.default_upload_size_limit)??Qn,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)??Hs),supportedFileMimeTypes:new Set((o==null?void 0:o.supported_file_mime_types)??Gs)})},[]),r=l.useCallback(s=>{const{channel:o,uploadSizeLimit:i=Qn}=s,c=(d=!0)=>o!=null&&o.isAIAgent?d?ot(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 ot(o);default:return!0}},get supportedMimeTypes(){return c()?[hr]:[...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}},zs=(...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:rm,useContext:dt}=be("AIAgentMessengerSession"),sm=l.forwardRef(function({userSessionInfo:e,children:t},n){const{_aiAgentSDK:r,chatSDK:s,aiAgentId:o,logger:i}=ye(),{updateTheme:c}=Xr(),[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:L,createAttachmentRules:N}=nm();l.useEffect(()=>{const D=r.onMessengerSettingsUpdated(({settings:B})=>{const{appearance:H,bot:q,launcher:Z,memory:z}=B;c(H.selected_theme,H),_(Du(q)),y($u(Z)),I(z?Cr(z):null),L(B)}),Q=r.onActiveChannelUpdated(({channelUrl:B,status:H,conversationStatus:q})=>{h({url:B,status:H,conversationStatus:q})}),ne=r.onAuthTokenRefreshed(()=>{var H;const B=(H=r.session)==null?void 0:H.userSession.authToken;B&&v(q=>q?{...q,authToken:B}:null)});return()=>{D(),Q(),ne()}},[r,c,L]);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]),G=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 ne=zs(...Q);if(ne.type==="active"){const q=await(await D()).updateContext(o,ne.context);return Ft(q)}const B=await s.aiAgent.updateContext(ne.aiAgentId,ne.channelUrl,ne.context);return Ft(B)},patchContext:async(...Q)=>{const ne=zs(...Q);if(ne.type==="active"){const q=await(await D()).patchContext(o,ne.context);return Ft(q)}const B=await s.aiAgent.patchContext(ne.aiAgentId,ne.channelUrl,ne.context);return Ft(B)},getContextObject:async()=>{const ne=await(await D()).getContextObject(o);return Ft(ne)},requestNudgeMessage:Q=>r.requestNudgeMessage(Q)}},[k,R,m,s,o,i,r]),a.createElement(rm,{value:{sdkUser:f,userSessionInfo:e,userSession:p,activeChannel:m,setActiveChannel:h,refreshActiveChannel:G,createConversation:r.createConversation,searchConversation:r.searchConversation,submitCPAAuthorizationCodes:r.submitCPAAuthorizationCodes,connectionError:u,aiAgentInfo:E,launcherInfo:A,memoryInfo:T,authenticate:k,deauthenticate:R,createAttachmentRules:N}},t)}),om={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"},im=e=>e.disabled?om[e.disabledBy]==="ready":!0,am=e=>{var n,r,s,o,i;if(e.isUserMessage())return"text";const t=e.isFileMessage()?e.type:((r=(n=e.fileInfoList)==null?void 0:n[0])==null?void 0:r.mimeType)??((i=(o=(s=e.messageParams)==null?void 0:s.fileInfoList)==null?void 0:o[0])==null?void 0:i.mimeType);return t&&Ye(t)?"file_image":t&&Zt(t)?"file_video":t&&Hc(t)?"file_audio":"file_document"};let Vs=0;const cm=e=>(Vs+=1,`${e??"unknown"}:${Vs}`),At=(e,t)=>e===void 0||t===e,Ri=(e,t)=>{!t.error&&t.messages.length>0&&e.conversationNotInteractiveTimeout.markHistoryLoaded("success",t.channelUrl)},Mi=(e,t)=>{t.error?e.conversationNotInteractiveTimeout.markHistoryLoaded("failed",t.channelUrl):e.conversationNotInteractiveTimeout.markHistoryLoaded(t.messages.length>0?"success":"verified_empty",t.channelUrl)},lm=(e,t)=>{Ri(e,t)},um=(e,t)=>{Mi(e,t)},dm=(e,t,n)=>{var o;if(!Qe(e,n))return;const{hasResponseMetadata:r,...s}=ni(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}))},qs=(e,t)=>{t.streamStalled.clearMessage(e.messageId),t.userPerceivedResponseTime.clearMessage(e.messageId);const n=Je(e)?e.reqId:void 0;n&&(t.messagePendingStuck.disappear({requestId:n}),t.userPerceivedResponseTime.cancelTurn(n),t.typingIndicatorAbsentTimeout.cancelTurn(n))},er=(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))},mm=({activeChannelUrl:e,statsTrackers:t})=>{const{chatSDK:n}=ye(),{aiAgentInfo:r}=dt(),s=l.useRef(!1),o=r==null?void 0:r.userId;ft(!!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])},hm=({enabled:e=!0,requestedChannelUrl:t,statsTrackers:n})=>{const r=l.useRef(void 0);l.useLayoutEffect(()=>{const s=r.current;if(!e){s&&(er(n,s),r.current=void 0);return}s&&s!==t&&(er(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&&(er(n,s),r.current=void 0)},[n])},fm=({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&&At(n,g.channelUrl),[n]);return l.useEffect(()=>{if(!t)return;const g=s.current;g&&f(g)&&(g.tracked||(Ri(r,g),g.tracked=!0));const p=o.current;p&&f(p)&&(p.tracked||(Mi(r,p),p.tracked=!0))},[t,f,r]),l.useMemo(()=>({onCollectionEvent:g=>{if(h(m)&&At(n,g.channelUrl)){if(g.kind==="messagesDeleted"){g.messages.forEach(p=>qs(p,r));return}t&&g.messages.forEach(p=>dm(p,r,e))}},onCacheResult:(g,p,v)=>{if(!h(m)||!At(n,v))return;const E={error:g,messages:p,channelUrl:v,lifecycleGeneration:u.current,tracked:!1};s.current=E,t&&(lm(r,E),E.tracked=!0)},onApiResult:(g,p,v)=>{if(!h(m)||!At(n,v))return;const E={error:g,messages:p,channelUrl:v,lifecycleGeneration:u.current,tracked:!1};o.current=E,t&&(um(r,E),E.tracked=!0)},onLocalMessageDeleted:g=>{h(m)&&At(n,g.channelUrl)&&qs(g,r)}}),[e,m,t,h,n,r])},gm=({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])},pm=({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()&&At(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:am(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])},_m=({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=cm(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])},Em=({requestedChannelUrl:e,activeChannelUrl:t,statsEnabled:n=!0,statsTrackers:r})=>{const{aiAgentInfo:s}=dt();mm({activeChannelUrl:t,statsTrackers:r}),hm({enabled:n,requestedChannelUrl:e,statsTrackers:r});const o=fm({aiAgentUserId:s==null?void 0:s.userId,statsEnabled:n,requestedChannelUrl:e,statsTrackers:r}),i=pm({channelUrl:t,enabled:n,statsTrackers:r}),c=_m({channelUrl:t,enabled:n,statsTrackers:r});return l.useMemo(()=>({messageCallbacks:o,runWithPendingStuckStats:i,runWithUserTurnStats:c}),[o,i,c])},Ot=()=>ye()._aiAgentSDK.statsTrackers,Cm=({enabled:e=!0,channelUrl:t}={})=>{const{conversationInitialRender:n}=Ot(),{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();Te(()=>{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 _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])},Ks=()=>{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 bm(e,t={}){const{shouldInitializeConversation:n=!0,initialUserMessage:r}=t,{chatSDK:s,logger:o,aiAgentId:i,_aiAgentSDK:c}=ye(),{sdkUser:u}=dt(),d=Ks(),m=Ks(),h=Nn(),[f,g]=l.useState(void 0),[p,v]=l.useState(void 0),[E,_]=l.useState(!1),A=le(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,L,N,k,R,G;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),(N=t.onFetchSuccess)==null||N.call(t,{channelUrl:D.url,conversationId:(L=D.conversation)==null?void 0:L.id}),D.url===((k=c.session)==null?void 0:k.activeChannel.url)&&c.session._updateActiveChannel({url:D.url,status:De(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;(G=t.onFetchError)==null||G.call(t,{channelUrl:e,error:D}),D instanceof _e.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 L;if(!f){p&&await y();return}const T=d.current(),I=await f.refresh();!d.isCurrent(T)||f.url!==e||((L=t.onReconnectSucceeded)==null||L.call(t,f.url),A(I),g(I))}}),ft(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 vm=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}},Sm=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},ym=()=>{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===_e.ConnectionState.OPEN?"connected":o)})},[t,e]),n},Am=3e4,Tm=({shouldApply:e,lastMessage:t,isBlockedWhileAIResponding:n,currentUserId:r})=>{const[s,o]=l.useState(!1),i=l.useRef(null),c=t&&Qe(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=Am-m;return n||h<=0?u():d(h),()=>{i.current&&clearTimeout(i.current)}},[n,c]),s&&e},wi=e=>{const{chatSDK:t}=ye(),[n,r]=l.useState([]);return ft(t,{onTypingStatusUpdated(s){if(s.url===(e==null?void 0:e.url)){const o=s.getTypingUsers();r(o)}}}),n},Im=({channel:e,lastMessage:t,aiAgentUserId:n,isStreamAnimating:r})=>{const[s,o]=l.useState(!1),i=wi(e);return l.useEffect(()=>{if(!t)return;const c=i.some(d=>d.userId===n),u=Qe(t,n)&&(ke.isStreaming(t)||r);o(u||c)},[i,t,n,r]),s},xm=({channel:e,messages:t,isStreamAnimating:n,isInitializingConversation:r})=>{const{aiAgentInfo:s,userSession:o}=dt(),i=ym(),c=Im({channel:e,lastMessage:gr(t,[Oe.SendingStatus.SUCCEEDED]),aiAgentUserId:(s==null?void 0:s.userId)??"",isStreamAnimating:n}),u=Tm({shouldApply:!!(e!=null&&e.isAIAgent)&&!ot(e),isBlockedWhileAIResponding:c,lastMessage:gr(t,[Oe.SendingStatus.PENDING,Oe.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(De(e))return d("conversation_closed");if(yl(e))return d("handoff_pending");if(Sm(e))return d("form_active");const m=vm(e);return d(m||(c||u||r?"ai_responding":""))},Rm=()=>{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:Mm}=be("AIAgentConversation");function wm({children:e,channelUrl:t,onChannelDeleted:n,onMessagesReceived:r,onMessagesUpdated:s,onConversationStatusChanged:o,onConversationClosedViaDispatcher:i,onBeforeSendMessage:c,onAfterSendMessage:u=de,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=Ot(),I={channelUrl:t,enabled:m},L=Fd({...I,statsTracker:T.conversationNotInteractiveTimeout}),N=Ud({...I,scheduleForegroundTask:E.scheduleForegroundTask,statsTracker:T.recoveryNotInteractiveTimeout}),k=Cm(I),{channel:R,channelFetchError:G,getChannel:D,isInitializingConversation:Q}=bm(t,{shouldInitializeConversation:h,initialUserMessage:f,onFetchStart:x=>{L.onFetchStart(x),k.onGetChannelStart(x)},onFetchSuccess:x=>{L.onFetchSuccess(x),k.onGetChannelComplete(x)},onFetchError:x=>{L.onFetchError(x),k.onGetChannelError(x)},onReconnectSucceeded:N.onReconnectSucceeded}),ne=R==null?void 0:R.url,B=Em({requestedChannelUrl:t,activeChannelUrl:ne,statsEnabled:m,statsTrackers:T}),H=$d(_,R,{replyType:Oe.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,O,P)=>{k.onCollectionApiResult(x,P),B.messageCallbacks.onApiResult(x,O,P)},onCacheResult:(x,O,P)=>{k.onCollectionCacheResult(x,P),B.messageCallbacks.onCacheResult(x,O,P)},onCollectionEvent:x=>{B.messageCallbacks.onCollectionEvent(x),Ii.publish(x)},onLocalMessageDeleted:x=>{B.messageCallbacks.onLocalMessageDeleted(x)},onOutgoingMessageStatusChanged:x=>{R&&E.liveMetricManager.track({type:"outgoingMessage",channel:R,message:x})}}),q=Rm(),Z=xm({channel:R,messages:H.messages,isStreamAnimating:q.isAnimating,isInitializingConversation:Q});gm({enabled:m,channelUrl:ne,initialized:H.initialized,inputReady:im(Z),renderedSignal:H.messages,statsTrackers:T}),l.useEffect(()=>{v()},[d,R]);const z=($=R==null?void 0:R.conversation)==null?void 0:$.status;l.useEffect(()=>{z&&(o==null||o(z))},[z,o]),l.useEffect(()=>{const x=async O=>{const P=typeof(O==null?void 0:O.channelUrl)=="string";R&&P&&O.channelUrl!==R.url||(A.debug("conversation.dispatcher: try to close conversation",R),R!=null&&R.conversation&&R.conversation.status===me.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 Y=le(()=>H.loadPrevious()),W=le(()=>H.loadNext()),K=le(async x=>{try{await H.deleteMessage(x)}finally{x.sendingStatus!=="succeeded"&&B.messageCallbacks.onLocalMessageDeleted(x)}}),V=le(x=>x.isUserMessage()?B.runWithUserTurnStats(O=>B.runWithPendingStuckStats(P=>H.resendMessage(x,X=>{O(X.reqId),P(X)}),void 0)):B.runWithPendingStuckStats((O,P)=>H.resendMessage(x,O,P),void 0,{tracksUploadProgress:x.isMultipleFilesMessage()})),w=le(()=>H.resetNewMessages()),oe=le(async x=>{var P;if(((P=R==null?void 0:R.conversation)==null?void 0:P.status)===me.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(x=await c(x));const O=await B.runWithUserTurnStats(X=>B.runWithPendingStuckStats(re=>H.sendUserMessage(x,J=>{X(J.reqId),re(J)}),u));return u==null||u(O),O}),Se=le(async x=>{var P;if(((P=R==null?void 0:R.conversation)==null?void 0:P.status)===me.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(x=await c(x));const O=await B.runWithPendingStuckStats(X=>H.sendFileMessage(x,X),u);return u==null||u(O),O}),xe=le(async x=>{var P;if(((P=R==null?void 0:R.conversation)==null?void 0:P.status)===me.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(x=await c(x));const O=await B.runWithPendingStuckStats((X,re)=>H.sendMultipleFilesMessage(x,X,re),u,{tracksUploadProgress:!0});return u==null||u(O),O}),Re={_statsEnabled:m,conversation:(R==null?void 0:R.conversation)??void 0,actions:{setUserMemoryState:E.setUserMemoryState},channelSource:{channel:R,error:G,refetch:()=>D(),closeConversation:async()=>{De(R)||await(R==null?void 0:R.closeConversation())}},messageSource:{messages:H.messages,newMessages:H.newMessages,initialized:H.initialized,loadPrevious:Y,loadNext:W,deleteMessage:K,resendMessage:V,resetNewMessages:w,sendUserMessage:oe,sendFileMessage:Se,sendMultipleFilesMessage:xe},state:{streamAnimation:q,input:Z}};return a.createElement(Mm,{value:Re},e)}function km(e,t,n){var _,A,y,T,I,L,N,k,R,G;const[r,s]=l.useState(!1),[o,i]=l.useState(null),[c,u]=l.useState([]),[d,m]=l.useState(null),h=l.useRef(!1),f=le(()=>{var D;return(D=n==null?void 0:n.onListRequestStart)==null?void 0:D.call(n)}),g=le(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 ui(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(),(L=t.filter)==null?void 0:L.deskChannelFilter,(k=(N=t.filter)==null?void 0:N.pinnedChannelUrls)==null?void 0:k.join(),(R=t.filter)==null?void 0:R.copilotConversationOnly,(G=t.filter)==null?void 0:G.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 ki=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:[me.ConversationStatus.CLOSED,me.ConversationStatus.OPEN],...r,...e}},Lm=({enabled:e=!0}={})=>{const{conversationListInitialRender:t}=Ot(),{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();Te(()=>{i!=null&&i()?o.onRenderDiscarded():o.onRendered()})}}),[n])},{Provider:Om}=be("AIAgentConversationList");function Nm({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=ki(t),u=Lm({enabled:n}),d=km(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(Om,{value:m},r)}function Dm(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:$m,useContext:Pm}=be("MessageTemplateFetching");function Fm({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=Dm(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($m,{value:u},e)}const Um="remove_powered_by",Zr=(e,t)=>{var s,o;const{chatSDK:n}=ye(),{aiAgentInfo:r}=dt();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&&Fr(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(Um)),[i])}throw new Error("Unsupported feature")},Bm={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"},Hm={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}}},Gm={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}}},Vm={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:Hm,number:Gm,"single-select":zm,"multi-select":Vm},Km={getValueOrDefault:()=>null,validate:()=>({isValid:!1})};function Li(e){return qm[e.type]||Km}function Ys(e){return Li(e).getValueOrDefault(e)}function Ym(e,t,n={}){const r={...Bm,...n};return Li(e).validate(e,t,r)}const Wm=(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]=Ys(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=Ys(_);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=Ym(_,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())}}},jm=({isMessengerOpened:e,onConversationStarted:t})=>{const{_aiAgentSDK:n,aiAgentId:r,language:s,countryCode:o,context:i}=ye(),{createConversation:c,userSession:u}=dt(),[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}},Xm=e=>{const{chatSDK:t,handlers:n,logger:r}=ye(),{aiAgentInfo:s}=dt(),o=l.useRef(new Set),i=l.useRef(new Set),c=(m,h)=>{if(!(n!=null&&n.onCustomEvent)||!(s!=null&&s.userId)||!Qe(m,s.userId))return;const f=m.messageId;if(ke.isStreaming(m)){i.current.add(f);return}h==="updated"&&!i.current.has(f)||(r.debug("useCustomEventForMessageReceive: bot-message-received",m),n.onCustomEvent({type:"bot-message-received",data:{message:m}}),i.current.delete(f))},u=l.useCallback(m=>{if(n!=null&&n.onCustomEvent&&m.isAdminMessage()&&m.customType==="user_action_required"&&!o.current.has(m.messageId)){const h=ei(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 ft(t,{onMessageReceived:(m,h)=>d(m,h,"received"),onMessageUpdated:(m,h)=>d(m,h,"updated")}),{checkForUserActionRequired:u}},Zm=e=>{if(e==null||typeof e!="object")return;const t="thinking_message"in e?e.thinking_message:void 0;return typeof t=="string"&&t?t:void 0},Oi=e=>{const{aiAgentInfo:t}=dt(),n=wi(e);if(De(e))return null;const r=n[0];if(!r)return null;const s=r.userId===(t==null?void 0:t.userId),o=s?Zm(r.metaData):void 0;return{user:s?t:r,isBot:s,thinkingMessage:o}},Jm=250,Qm=(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),Jm);return()=>clearTimeout(c)},[n,e!==null]),e??(n?s.current:null)},eh=(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},[])},th=(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()}}},nh=(e,t,n=1e4,r=!0)=>{const s=l.useRef(null),o=l.useRef(null),i=l.useRef(!1);s.current||(s.current=th(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])},rh=({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])},Jr=({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?ot(e)?s.human("agent"):s.ai("delight"):e.isDesk?s.human("agent"):s.channel("user")},Ws=e=>l.useReducer((t,n)=>({...t,...n}),e);var Ze=(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))(Ze||{});const sh=new Set(["free_text","single_choice"]),oh=({csatPayload:e,type:t,initialCsat:n,initialCsatReason:r,initialIsResolved:s})=>{const[o,i]=Ws({csatType:t,csat:n,csatReason:r,isResolved:s}),[c,u]=Ws({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(sh.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===Ze.AI_AGENT_CSAT_5||t===Ze.HELPDESK_CSAT_5)&&typeof o.csat=="number")return"submittable";if(t===Ze.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"}}},ih=({csat:e,csatExpireAt:t,csatPayload:n,isSubmitInFlight:r=!1})=>{const s=!!n&&n.visibility&&!!Ze[n.type],o=!r&&typeof e!="number"&&hi(t),i=Nn();return l.useEffect(()=>{if(!s||typeof e=="number"||t==null||o)return;const c=t-Date.now();if(c<=0&&r)return;const u=setTimeout(i,Math.max(0,c));return()=>clearTimeout(u)},[i,e,t,o,s,r]),{isRenderableCSAT:s,isExpiredNow:o}},tr=5,Ht=250,Ni=50,ah=1500,nr=e=>Math.max(0,e-Ni),_n=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():0,ch=(e,t)=>{const n=e&&t.length<=Ni,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,ah);return()=>clearTimeout(d)},[s,c,t]),!s&&!c},lh=e=>e<1e3?{speed:tr*.5,chunkSize:2}:e<2e3?{speed:tr*.8,chunkSize:2}:{speed:tr*.6,chunkSize:3},En=(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(En(e,o)){o++;continue}e[o]===n?s++:e[o]===r&&s--,o++}return s>0?-1:o},Di=(e,{hideImages:t,hideLinks:n})=>{let r="",s=0,o=0;for(;s<e.length;){if(e[s]==="`"&&!En(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]==="["&&!En(e,s),c=e[s]==="["&&!En(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},uh=({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:Di(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,L=T-i.lastReportedAt>=Ht;if(!I&&!L)return;const N=m(A);g(N,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=_n();h(y,I,!0),g(y,I,!0)},[u,g,h,e]);return{resetProgress:v,reportVisibleTextProgress:f,reportRenderedTextProgress:p,reportNonStreamingVisibleTextProgress:E,reportMarkdownRevealProgress:_}},dh=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=ch(n,t),f=s.includes("image"),g=s.includes("link"),[p,v]=l.useState(()=>n?h?0:nr(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=le(()=>o==null?void 0:o()),I=le(()=>i==null?void 0:i()),L=le(()=>c==null?void 0:c()),N=le(z=>u==null?void 0:u(z)),{resetProgress:k,reportVisibleTextProgress:R,reportRenderedTextProgress:G,reportNonStreamingVisibleTextProgress:D,reportMarkdownRevealProgress:Q}=uh({trackedRef:y,onVisibleTextProgress:d,onRenderedTextProgress:m}),ne=n,B=p<t.length,H=y.initialEnabled&&(ne||B);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 z=_n();R(t.length,z,!0),G(t.length,t.length,z);return}v(z=>t.length<z?t.length:z)}},[T,G,R,t]),l.useEffect(()=>{if(!y.initialEnabled)return;let z=h?0:nr(t.length),Y=h;_.lastUpdate=0,_.startTime=0,_.lastProgressCall=0,k();const W=K=>{_.lastUpdate===0&&(_.lastUpdate=K,_.startTime=K,_.lastProgressCall=K,z>0&&R(z,K,!0));const V=y.textLength;Y&&!y.isGatingStreamingStart&&(z=nr(V),v(z),z>0&&R(z,K,!0),_.lastUpdate=K,Y=!1),!y.enabled&&y.snapOnDisable&&z<V&&(z=V,v(z),R(z,K,!0),G(z,V,K));const w=K-_.lastUpdate,oe=K-_.startTime,{speed:Se,chunkSize:xe}=lh(oe),Re=Se*xe;!y.isGatingStreamingStart&&w>=Re&&z<V&&(z=Math.min(z+xe,V),v(z),R(z,K,z>=V),G(z,V,K),_.lastUpdate=K),K-_.lastProgressCall>=Ht&&(_.lastProgressCall=K,I()),(z<V||y.enabled)&&(E.current=requestAnimationFrame(W))};return E.current=requestAnimationFrame(W),()=>{E.current&&cancelAnimationFrame(E.current),A.startCalled&&!A.completeCalled&&(A.completeCalled=!0,L())}},[L,I,G,R,k]),l.useEffect(()=>{y.initialEnabled&&(n||t.length>0)||(D(t.length),G(t.length,t.length,_n()))},[n,m,d,D,G,t.length,y]),l.useEffect(()=>{const z=y.initialEnabled&&A.startCalled,Y=!n,W=p>=t.length;z&&Y&&W&&!A.completeCalled&&(A.completeCalled=!0,L())},[n,p,L,t.length]);const q=l.useMemo(()=>{let z=t;y.initialEnabled&&(z=h?"":t.slice(0,p));const Y=H&&f,W=H&&g;return!Y&&!W?z:Di(z,{hideImages:Y,hideLinks:W})},[t,p,f,g,H,h]);l.useEffect(()=>{!y.initialEnabled||H||R(p,_n(),!0)},[p,H,R]),l.useEffect(()=>{Q({displayedLength:p,streamTextLength:q.length})},[p,Q,q.length]);const Z=q.length===0&&H;return l.useLayoutEffect(()=>(N(Z),()=>N(!1)),[N,Z]),{streamText:q,isAnimating:H,isHolding:Z}},Xs={visible:!1,remainingTime:0,showDescription:!1,targetTimeMs:null},mh=e=>({visible:!0,remainingTime:e,showDescription:!0,targetTimeMs:Date.now()+e*1e3}),hh=(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}},fh=()=>{const{chatSDK:e}=ye(),[t,n]=l.useState(Xs),r=()=>n(Xs);return Qt(e,{onConnectionDelayed:s=>{s>0?n(mh(s)):r()},onReconnectSucceeded:r,onConnected:r}),l.useEffect(()=>{if(!t.visible||!t.showDescription||t.targetTimeMs==null)return;const s=setTimeout(()=>{n(o=>hh(o))},1e3);return()=>clearTimeout(s)},[t.visible,t.showDescription,t.targetTimeMs,t.remainingTime]),{visible:t.visible,remainingTime:t.remainingTime,showDescription:t.showDescription}},gh=e=>{const t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`},ph=(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)}},_h=({enabled:e=!0}={})=>{const t=Ot();return l.useCallback(({message:n,isBotMessage:r,aiAgentUserId:s})=>{if(!e)return;const o=n.messageId,i=ke.isStreaming(n),c=Xt(n.extendedMessagePayload),u=c.hasMessageTemplate,d=c.hasForm,m=r&&n.isUserMessage()&&!i&&!Gc(n)&&!ke.isWelcomeMessage(n,s),h=i||t.streamStalled.hasPendingStream(o),f=t.userPerceivedResponseTime.hasPendingAIResponse(o);if(!h&&!f&&!m&&!u&&!d)return;let g=!1,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])},Eh=e=>{const t=l.useRef(!1);l.useEffect(()=>{t.current||e!=null&&e.onVisibleTextProgress&&(t.current=!0,e.onVisibleTextProgress(0))},[e])},rr=5e3,Ch=({channelUrl:e,enabled:t=!0,isInitiallyBackgrounded:n,isForegrounded:r,subscribeToForegroundState:s})=>{const o=Ot(),i=l.useRef(t),c=l.useRef(n),u=l.useRef(t&&n()?performance.now()-rr: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<rr){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()-rr):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])},bh=e=>{const{conversationInitialRender:t,conversationListInitialRender:n}=Ot();l.useLayoutEffect(()=>{t.setPresentMethod(e),n.setPresentMethod(e)},[t,n,e])},vh=(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]),Qt(e,{onConnected:c,onReconnectSucceeded:c}),s},Rt=e=>e.replace(/\s+/g," ").trim(),Sh="Code block",$i=e=>`A11Y_INLINE_CODE_${e}`,Pi=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}},Fi=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}},yh=e=>{const{blockquotePrefix:t,content:n}=Pi(e),{content:r}=Fi(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}},Ah=(e,t)=>{const{blockquotePrefix:n,content:r}=Pi(e);if(n!==t.blockquotePrefix)return!1;const{content:s,hasListPrefix:o}=Fi(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)},Th=(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},Ih=(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},xh=(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},Rh=e=>{let t=0,n="";for(;t<e.length;){const r=Th(e,"[",t);if(r===-1){n+=e.slice(t);break}const s=Ih(e,r+1);if(s===-1){n+=e.slice(t);break}if(r>0&&e[r-1]==="!"&&Tn(e,r-1)){n+=e.slice(t,s+1),t=s+1;continue}if(e[s+1]!=="("){n+=e.slice(t,s+1),t=s+1;continue}const o=r>0&&e[r-1]==="!"&&!Tn(e,r-1)?r-1:r;n+=e.slice(t,o);const i=e.slice(r+1,s),c=xh(e,s+2);if(c===-1){n+=e.slice(o);break}n+=i,t=c}return n},Ui=(e,t,n)=>{if(!/^\d+$/.test(t))return!1;const r=e.slice(-1);return/\d/.test(r)&&/\d/.test(n)},Mh=e=>e.replace(/(^|[^*\\])\*\*([^\s*](?:[\s\S]*?[^\s*])?)\*\*(?!\*)/g,(t,n,r,s,o)=>{const i=o[s+t.length]??"";return Ui(n,r,i)?t:`${n}${r}`}),wh=e=>e.replace(/(^|[^_\\])__([^\s_](?:[\s\S]*?[^\s_])?)__(?!_)/g,"$1$2"),kh=e=>e.replace(/(^|[^~\\])~~([^\s~](?:[\s\S]*?[^\s~])?)~~(?!~)/g,"$1$2"),Lh=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 Ui(r,s,c)?n:`${r}${s}`}),t=t.replace(/(^|[\s([{"'])_([^_\s](?:[\s\S]*?[^_\s])?)_(?=$|[\s)\]}"'.,!?:;])/g,"$1$2"),t},Oh=e=>e.replace(/\\([\\`*_[\]()#+.!~|-])/g,"$1"),Nh=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},Zs=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))},Js=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},Dh=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=Ph(s,t),s=Nh(s);const o=Fh(s);s=o.text,r.push(...o.inlineCodes),s=Rh(s),s=Mh(s),s=wh(s),s=kh(s),s=Lh(s),s=Dh(s),s=$h(s),s=Oh(s);for(let c=0;c<r.length;c++)s=s.replaceAll($i(c),r[c]);return Rt(s)||void 0},Uh=(e,t)=>{var s;const n=((s=e.name)==null?void 0:s.trim())||"",r=e.mimeType??"";return Ye(r)?t.image:Zt(r)?t.video:ii({name:n,mimeType:r})?t.pdf(n):t.document(n)},In=e=>(e==null?void 0:e.trim())||"",Bh=e=>(e?Rt(e):void 0)||void 0,Qs=30,Hh=e=>e.length>Qs?`${e.slice(0,Qs)}…`:e,Gh=({agent:e,status:t,lastMessage:n,time:r,unreadCount:s},o)=>{const i=Hh(Rt(n)),c=[t,i].filter(Boolean).join(", ");return o(Rt(e),Rt(c),r,s)},vr=e=>({text:In(e),format:"plain"}),zh=e=>({text:In(e),format:"markdown"}),Vh=({markdownText:e,plainText:t,comparisonText:n})=>{const r=In(e);return r&&r!==In(n)?zh(r):vr(t)},qt=({sender:e,message:t,messageFormat:n="plain",time:r,codeBlockPlaceholder:s})=>{const o=[],i=n==="markdown"?Bi(t,{codeBlockPlaceholder:s}):Bh(t);if(r&&o.push(r),e&&o.push(e),i&&o.push(i),o.length!==0)return o.join(", ")},Hi=(e,t)=>Bi(e==null?void 0:e.trim(),t!==void 0?{codeBlockPlaceholder:t}:void 0),qh=(...e)=>Rt(e.filter(Boolean).join(", "))||void 0,eo=(e,t,n,r)=>{if(!t||ai(t,n))return e;const s=Hi(t,r);return s?qh(e,s):e},Gi=(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=Uh({name:o,mimeType:e.type},t);return eo(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 eo(d,n,c,t.codeBlockPlaceholder)}return Hi(n,t.codeBlockPlaceholder)},Kh=(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,G)=>({text:k,ignoreSuppression:R,queueOrder:f++,dedupeKey:G}),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,G,D)=>R!=null&&D!=null?R===D:R==null&&D==null?k!=null&&k===G:!1,y=(k,R,G)=>{if(!k||!R&&(r!=null&&r()))return;const D=G==null?void 0:G.dedupeKey;if(!(h&&A(k,D,u,d)))if(h){if(((G==null?void 0:G.mode)??"latestOnly")==="ordered"){const ne=c[c.length-1];if(ne&&A(k,D,ne.text,ne.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 G of k)_(G)},destroy:()=>{m!==null&&(clearTimeout(m),m=null),i=null,c.length=0,u=null,d=null,h=!1}}},Yh=e=>{switch(e){case"newMessage":case"conversationClosed":case"csatDisplayed":case"csatSubmitted":case"csatExpired":return"ordered";default:return"latestOnly"}},Wh=(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(". "),jh=(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}},Xh=(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}},Zh=(e,t)=>!t||!Je(e)||e.sender.userId!==t?null:e.reqId||(e.messageId>0?String(e.messageId):null),Jh=(e,t)=>we.isAdmin(e)?we.isCSAT(e):"sender"in e?e.sender.userId!==t:!1,Qh=e=>"messageId"in e&&e.messageId>0?String(e.messageId):"reqId"in e&&typeof e.reqId=="string"&&e.reqId.length>0?e.reqId:null,ef=e=>e===_e.CollectionEventSource.EVENT_MESSAGE_RECEIVED||e===_e.CollectionEventSource.EVENT_MESSAGE_UPDATED,tf=({isOpened:e,opensConversationList:t})=>e?t?"closeConversationList":"closeConversation":t?"openConversationList":"openConversation",nf=(e,t)=>{switch(e){case"closeConversationList":return t.closeConversationList;case"closeConversation":return t.closeConversation;case"openConversationList":return t.openConversationList;case"openConversation":return t.openConversation}},rf=(e,t)=>{switch(e){case"closeConversation":return t.hintCloseConversation;case"openConversationList":return t.hintOpenConversationList;case"openConversation":return t.hintOpenConversation;default:return}},sf=({intent:e,strings:t})=>({label:nf(e,t),hint:rf(e,t)}),of="1.39.1",Ue="sb-agent",ve={ENTRY:`${Ue}-entry`,MODAL_ROOT:`${Ue}-modal-root`,WINDOW:`${Ue}-window`,LAUNCHER:`${Ue}-launcher`,WINDOW_TITLE:`${Ue}-window-title`},zi="data-sb-initial-focus",Vi="true",af=`[${zi}="${Vi}"]`,qi={[zi]:Vi},Qr="data-sb-focus-trap-sentinel",cf="true",Ki="data-sb-initial-focus-header",Yi="true",lf=`[${Ki}="${Yi}"]`,Wi={[Ki]:Yi},ji="data-sb-message-input",Xi="true",uf=`textarea[${ji}="${Xi}"]:not(:disabled)`,df={[ji]:Xi},Zi=1e3,dn=2147483647,gt={MODAL:dn-1,TOOLTIP:dn-2,WINDOW:dn-3,LAUNCHER:dn-4},Ji=36,mf=100,hf=of,es="noopener noreferrer nofollow",ff=()=>typeof document>"u"||document.visibilityState==="visible",Sr=()=>typeof document<"u"&&document.visibilityState==="hidden",to=()=>Sr()?"backgrounded":"foregrounded",gf={getState:to,subscribe:e=>{if(typeof document>"u")return()=>{};const t=()=>e(to());return document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t)}};function pf(){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 mn={};function _f(){return{get:e=>{try{return localStorage.getItem(e)}catch{return mn[e]??null}},set:(e,t)=>{try{localStorage.setItem(e,t)}catch{mn[e]=t}},delete:e=>{try{localStorage.removeItem(e)}catch{delete mn[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(mn).filter(t=>t.startsWith(e))}}}}const Ef={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}`}},yr={language:"en",strings:Ef,dateLocale:Ac.enUS},Qi=e=>({MESSAGE_INPUT__PLACE_HOLDER:e.conversation.input_placeholder,MESSAGE_INPUT__PLACE_HOLDER__DISABLED:e.conversation.input_placeholder_disabled,MESSAGE_INPUT__PLACE_HOLDER__STEWARD:e.conversation.input_placeholder_steward,MESSAGE_INPUT__PLACE_HOLDER__WAIT_AI_AGENT_RESPONSE:e.conversation.input_placeholder_wait_ai_agent_response,MESSAGE_INPUT__PLACE_HOLDER__RECONNECTING:e.conversation.input_placeholder_reconnecting,UNKNOWN__UNKNOWN_MESSAGE_TYPE:e.conversation.unknown_message_type,POWERED_BY:e.conversation.powered_by,CSAT_TITLE_UNSUBMITTED:e.csat.title,CSAT_TITLE_SUBMITTED:e.csat.submitted_label,CSAT_CRE_TITLE:e.csat.cre_question,CSAT_CRE_SOLVED:e.csat.cre_positive_label,CSAT_CRE_NOT_SOLVED:e.csat.cre_negative_label,CSAT_REASON_PLACEHOLDER:e.csat.reason_placeholder,CSAT_RATING_TITLE:e.csat.question,CSAT_SUBMIT_LABEL:e.csat.submit_label,CSAT_SUBMISSION_EXPIRED:e.csat.submission_expired,DATE_FORMAT__JUST_NOW:e.date_format.just_now,DATE_FORMAT__MINUTES_AGO:e.date_format.minutes_ago,DATE_FORMAT__HOURS_AGO:e.date_format.hours_ago,DATE_FORMAT__DATE_SHORT:e.date_format.date_short,DATE_FORMAT__MESSAGE_LIST__DATE_SEPARATOR:e.date_format.date_separator,DATE_FORMAT__MESSAGE_TIMESTAMP:e.date_format.message_timestamp,CONVERSATION_LIST__HEADER_TITLE:e.conversation_list.header_title,CONVERSATION_LIST__ENDED:e.conversation_list.ended,CONVERSATION_LIST__SYSTEM_MESSAGE:e.conversation_list.system_message,CONVERSATION_LIST__NO_CONVERSATIONS:e.common.placeholder_no_conversations,CONVERSATION_LIST__MULTIPLE_FILES_COUNT:e.conversation_list.multiple_files_count,TALK_TO_AGENT:e.conversation.start_new_conversation_label,CITATION_SOURCE_TITLE:e.conversation.citation_title,FORM_PLACEHOLDER:e.conversation.input_placeholder_active_form,FORM_VALIDATION_REQUIRED:e.form.validation_required,OPTIONAL:e.form.optional_label,PLACE_HOLDER__WRONG:e.common.placeholder_something_went_wrong,PLACE_HOLDER__NO_MESSAGES:e.common.placeholder_no_messages,RETRY:e.common.placeholder_something_went_wrong_retry_label,BUTTON__OK:e.common.button_ok,BUTTON__CANCEL:e.common.button_cancel,FAILED_MESSAGE_RESEND:e.conversation.failed_message_resend,FAILED_MESSAGE_REMOVE:e.conversation.failed_message_remove,FILE_UPLOAD_NO_SUPPORTED_FILES:e.conversation.file_upload_no_supported_files,FILE_UPLOAD_REPLACE_ALERT__TITLE:e.conversation.file_upload_replace_alert_title,FILE_UPLOAD_REPLACE_ALERT__DESCRIPTION:e.conversation.file_upload_replace_alert_description,FILE_UPLOAD_FILES:e.conversation.attachment_document,FEEDBACK_TITLE:e.feedback.title,FEEDBACK_GOOD:e.feedback.good,FEEDBACK_BAD:e.feedback.bad,FEEDBACK_COMMENT_LABEL:e.feedback.comment_label,FEEDBACK_COMMENT_PLACEHOLDER:e.feedback.comment_placeholder,FEEDBACK_CANCEL:e.feedback.cancel,FEEDBACK_SUBMIT:e.feedback.submit,FEEDBACK_SAVE:e.feedback.save,FEEDBACK_EDIT:e.feedback.edit,FEEDBACK_REMOVE:e.feedback.remove,A11Y_MESSAGE_LIST:e.conversation.a11y_message_list,A11Y_SCROLL_TO_BOTTOM:e.conversation.a11y_scroll_to_bottom,A11Y_SCROLL_TO_NEW_MESSAGES:e.conversation.a11y_scroll_to_new_messages,A11Y_OPEN_CONVERSATION_LIST:e.conversation.a11y_open_conversation_list,A11Y_OPEN_CONVERSATION:e.conversation.a11y_open_conversation,A11Y_OPEN_CONVERSATIONS:e.conversation.a11y_open_conversations,A11Y_CLOSE_CONVERSATION:e.conversation.a11y_close_conversation,A11Y_CLOSE_CONVERSATIONS:e.conversation.a11y_close_conversations,A11Y_MENU:e.conversation.a11y_menu,A11Y_MESSAGE_INPUT:e.conversation.a11y_message_input,A11Y_SEND_MESSAGE:e.conversation.a11y_send_message,A11Y_ATTACH_FILE:e.conversation.a11y_attach_file,A11Y_CONNECT_AGENT:e.conversation.a11y_connect_agent,A11Y_CLOSE_MESSENGER:e.conversation.a11y_close_messenger,A11Y_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}),ea=e=>{var t;return((t=e.split("-"))==null?void 0:t[0])??en},en="en",ta=new Set([en,"ko","es","pt","fr","hi","it","de","tr","ja"]),Cf='@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:bf,useContext:ts}=be("AgentUIElementResolver"),vf=({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===ve.MODAL_ROOT?c:i.querySelector(`#${d}`);return{resolveElement:u,resolvePortalContainer:d=>u(d)??c}},[e,t,n]);return a.createElement(bf,{value:s},r)};function ut(e,t){const n=e.getRootNode({composed:t});return n instanceof ShadowRoot||n instanceof Document?n:document}const no=()=>{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:Sf,useContext:ns}=be("EscapeDismissStack"),ro=e=>{e.stopPropagation(),e.stopImmediatePropagation()},yf=({rootElement:e=document.body,boundaryElement:t,children:n})=>{const r=l.useRef(null),s=l.useRef(null);r.current||(r.current=no()),s.current||(s.current=no());const o=r.current,i=s.current;l.useLayoutEffect(()=>{const u=t??ut(e),d=m=>{if(m.key==="Escape"){if(o.dismissTopmost()){ro(m);return}i.dismissTopmost()&&ro(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(Sf,{value:c},n)},na=(e,t,n)=>{const r=l.useRef(t);l.useLayoutEffect(()=>{r.current=t},[t]),l.useLayoutEffect(()=>{if(e)return n(()=>r.current())},[e,n])},Af=(e,t)=>{const{register:n}=ns();na(e,t,n)},Tf=(e,t)=>{const{registerShellDismissHandler:n}=ns();na(e,t,n)},ra=()=>{const{subscribe:e,getOpenCount:t}=ns();return l.useSyncExternalStore(e,()=>t()>0,()=>!1)},If=(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.":""))))})},so=Qi(yr.strings),xf={...so,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:so.DATE_FORMAT__DATE_SHORT,DATE_FORMAT__CONVERSATION_LIST__LIST_ITEM_TITLE_CAPTION:"h:mma",CONVERSATION_LIST__TOPICS_FALLBACK:"No category",CONVERSATION_CLOSED_FOOTER_LABEL:"Your conversation has ended",START_NEW_CONVERSATION:"💬 Start a new conversation",RETURN_TO_CONVERSATION:"💬 Return to conversation",BUTTON__SAVE:"Save",NO_NAME:"(No name)",CHANNEL_FROZEN:"Channel frozen"},xn={language:yr.language,dateLocale:yr.dateLocale,stringSet:xf},Rf=Object.freeze(Object.defineProperty({__proto__:null,default:xn},Symbol.toStringTag,{value:"Module"})),Ar=new Map([[en,xn]]);async function Mf(e){const t=Ar.get(e);if(t)return t;try{if(ta.has(e)){const{default:n}=await If(Object.assign({"./languages/de.ts":()=>Promise.resolve().then(()=>require("./cjs/CIjjIGUs.cjs")),"./languages/en.ts":()=>Promise.resolve().then(()=>Rf),"./languages/es.ts":()=>Promise.resolve().then(()=>require("./cjs/B9JzuCyz.cjs")),"./languages/fr.ts":()=>Promise.resolve().then(()=>require("./cjs/BQ8EaWkc.cjs")),"./languages/hi.ts":()=>Promise.resolve().then(()=>require("./cjs/Cr2LxvlJ.cjs")),"./languages/it.ts":()=>Promise.resolve().then(()=>require("./cjs/C2Oi-KA4.cjs")),"./languages/ja.ts":()=>Promise.resolve().then(()=>require("./cjs/LFX2h7v2.cjs")),"./languages/ko.ts":()=>Promise.resolve().then(()=>require("./cjs/CKr98WbE.cjs")),"./languages/pt.ts":()=>Promise.resolve().then(()=>require("./cjs/C3VEshQr.cjs")),"./languages/tr.ts":()=>Promise.resolve().then(()=>require("./cjs/C116E0pr.cjs"))}),`./languages/${e}.ts`,3);return Ar.set(e,n),n}return xn}catch{return xn}}const{Provider:wf,useContext:ie}=be("Localization"),kf=({language:e=navigator.language,languageCode:t,logger:n,stringSet:r,children:s})=>{const[o,i]=l.useState(Ar.get(en));return l.useEffect(()=>{const c=t??ea(e);o.language!==c&&(n==null||n.debug("localization.useEffect: update language",{from:o.language,to:c}),Mf(c).then(i))},[e,t,n]),a.createElement(wf,{value:{language:o.language,defaultStringSet:o.stringSet,stringSet:{...o.stringSet,...r},dateLocale:o.dateLocale,format:(c,u,d)=>ct.format(c,u,{locale:o.dateLocale,...d})}},s)},Rn="data-sb-agent-theme",oo=e=>(t,...n)=>{let r="";return t.forEach((s,o)=>{r+=s+(n[o]??"")}),`[${Rn}='${e}'] & { ${r} }`},te={light:oo("light"),dark:oo("dark")},Lf=F.css(({theme:e})=>{const{palette:t}=e;return`
|
|
10
|
+
`),r=Br(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("")},Er=(...e)=>(t,n)=>e.reduce((r,s)=>s(r,n),t),xs=Er(Xc(Er(Is(tl,{anchorsLineEnd:!0}),Zc,Is(Jc),nl)),el),sl=({convertSoftBreaks:e=!1}={})=>e?Er(rl,xs):xs,ol=typeof navigator<"u"&&navigator.product==="ReactNative",Cr=(e,t)=>{const n=r=>!t||t.length===0?!0:Qe(r)&&t.includes(r.sendingStatus);return ol?e.find(n):e.findLast(n)},il=(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 al(){const e=typeof navigator<"u"?navigator.userAgent:"",t=/iPad|iPhone|iPod/.test(e),n=/Android/.test(e);return t||n}function cl(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 Pc(e.data)},isExplicitWelcomeMessage(e){var t;return((t=e.extendedMessagePayload)==null?void 0:t.bot_message_type)==="welcome"},isWelcomeMessage(e,t){var r;if(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}`,ll=({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=cl(`${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},ul=()=>{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 dl{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 dl(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-${ul()}`,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=ml(),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 ml=()=>{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 hl(e),MessengerSettingsUpdated:e=>new fl(e),ActiveChannelUpdated:e=>new gl(e),AnonymousSessionTokenExpired:()=>new pl,AuthTokenRefreshed:()=>new _l,NudgeMessageReceived:e=>new El(e)};class hl extends kt{constructor(){super(...arguments);S(this,"type","conv.close")}}class fl extends kt{constructor(){super(...arguments);S(this,"type","messenger.settings.updated")}}class gl extends kt{constructor(){super(...arguments);S(this,"type","active.channel.updated")}}class pl extends kt{constructor(){super(...arguments);S(this,"type","anon.token.expired")}}class _l extends kt{constructor(){super(...arguments);S(this,"type","auth.token.refreshed")}}class El 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 Cl extends Jt{constructor(){super(...arguments);S(this,"metricKey","connection_connected")}}class bl extends Jt{constructor(){super(...arguments);S(this,"metricKey","connection_reconnect_started")}}class vl extends Jt{constructor(){super(...arguments);S(this,"metricKey","connection_reconnect_succeeded")}}class Sl extends Jt{constructor(){super(...arguments);S(this,"metricKey","connection_reconnect_failed")}}class yl extends Jt{constructor(){super(...arguments);S(this,"metricKey","connection_disconnected")}}class Al{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 Cl(n):t==="reconnectStarted"?new bl(n):t==="reconnectSucceeded"?new vl(n):t==="reconnectFailed"?new Sl(n):new yl(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 Tl extends Hr{constructor(){super(...arguments);S(this,"metricKey","conversation_initialized")}}class Il extends Hr{constructor(){super(...arguments);S(this,"metricKey","conversation_open")}}class xl extends Hr{constructor(){super(...arguments);S(this,"metricKey","conversation_closed")}}class Rl{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 Tl(t.url,n.id):s===he.ConversationStatus.OPEN?new Il(t.url,n.id):new xl(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 Ml(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 wl(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 kl(e){return!e.title}function Ll(e,t){var n;if(e)return kl(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 Ol extends zr{constructor(){super(...arguments);S(this,"metricKey","handoff_started")}}class Nl extends zr{constructor(){super(...arguments);S(this,"metricKey","handoff_succeeded")}}class Dl extends zr{constructor(){super(...arguments);S(this,"metricKey","handoff_failed")}}class $l{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 Ol(t.url,r.id):o==="succeeded"?new Nl(t.url,r.id):new Dl(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 Pl{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 Fl=(e,t)=>{const n=Qe(e)?e.sender.userId:void 0;return n===void 0?"system":n===t?"ai_agent":"human_agent"};class Ul{constructor(t,n){this.dispatch=t,this.getCurrentUserId=n}handleEvent({channel:t,message:n}){const{conversation:r}=t;this.shouldEmit(n,r)&&this.dispatch(new Pl({channelUrl:t.url,messageId:n.messageId,senderType:Fl(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 Bl extends Vr{constructor(){super(...arguments);S(this,"metricKey","memory_consent")}}class Hl extends Vr{constructor(){super(...arguments);S(this,"metricKey","memory_on")}}class Gl extends Vr{constructor(){super(...arguments);S(this,"metricKey","memory_off")}}const zl={consent:{Metric:Bl,actions:{shown:"shown",confirm:"enable",cancel:"disable"}},on:{Metric:Hl,actions:{shown:"shown",confirm:"keep",cancel:"disable",dismiss:"dismiss"}},off:{Metric:Gl,actions:{shown:"shown",confirm:"keep",cancel:"enable",dismiss:"dismiss"}}};class Vl{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}=zl[t],i=o[n];i&&this.dispatch(new s({action:i,deleteOnOff:t==="on"?r:void 0,userId:this.getCurrentUserId()}))}}class Kl{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 ql=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 Wl{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=ql(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 Kl({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 Yl{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 Al(this.emit),conversation:new Rl(this.emit),handoff:new $l(this.emit),incomingMessage:new Ul(this.emit,n),outgoingMessage:new Wl(this.emit,n),memory:new Vl(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 jl=e=>({onSessionTokenRequired:t=>{t(null),e.send(it.AnonymousSessionTokenExpired())}}),qr=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!=null)),Xl="ai_agent:stats",Zl="conversation_initial_render",Jl="conversation_not_interactive_timeout",Ql="recovery_not_interactive_timeout",eu="conversation_list_initial_render",tu="message_pending_stuck",nu="aiev_auth_expired_unhandled",ru="user_perceived_response_time",su="stream_stalled",ou="ai_typing_indicator_absent_timeout",iu="rendered_content_unusable",au=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,cu=e=>{if(bi(e))return typeof e.code=="number"?e.code:void 0},lu=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=cu(t)??au,this.errorDescription=lu(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(Xl,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 nu}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 uu 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 du 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 Zl}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 mu 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 hu 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 du().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 mu(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 fu 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 eu}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 gu 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 pu 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 fu().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 gu(r,this.visible),this.activeSpan}clear(){var n;(n=this.activeSpan)==null||n.cancel(),this.activeSpan=null,this.stats=null,this.authState="idle"}}class _u 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 Jl}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 Eu extends Ot{start(t){const n=this.getKey(t==null?void 0:t.channelUrl);this.clearKey(n);const r={stats:new _u().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 Cu 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 tu}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 bu=5e3,Ms=1e4;class vu extends Ot{start(t){if(!t.requestId||this.records.has(t.requestId))return;const n=t.messageType!=="text"&&t.tracksUploadProgress===!0,s={stats:new Cu().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:bu;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 Ql}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 Su 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 yu 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 iu}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 Au=500;class Tu 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,Au),this.measure.committed.add(r),new yu().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 Iu 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 su}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,xu=500;class Ru 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 Iu().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,xu),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 Mu 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 ou}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,wu=3e4;class ku extends Ot{constructor(){super(...arguments);S(this,"pendingAIResponseStartsByUserMessageId",new Map)}startTurn(n){this.cancelTurn(n.requestId);const r={stats:new Mu().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),wu),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 Lu 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 ru}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 Ou=.15,Nu=10,Du=e=>e<=0?!1:e>=1?!0:Math.random()<e;class $u 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)??Ou}startTurn(n){if(this.collectedCount>=Nu||!Du(this.samplingRate))return;this.collectedCount+=1;const r={stats:new Lu().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 Pu(){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:Bu(e.conversation),launcher:Fu(e.launcher)}:Wr,Fu=e=>At(Wr.launcher,e),Uu=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},Bu=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:Uu(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},Hu=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}),Gu=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 zu{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 Vu{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),Ku=e=>JSON.parse(e);function qu(e,t){const[n,r]=t.split(",").map(s=>s.trim());return e==="dark"&&r||n}function Wu(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 Yu({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 ju({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]!=="",Xu=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},Zu={1:Xu};function Ju(e){if(!Ti(e)||!("cat"in e)||typeof e.cat!="number"||!("data"in e))return null;const t=e.cat,n=Zu[t];if(!n)return null;const r=n(e.data);return r?{category:t,data:r}:null}function Qu(e,t,n,r){const s=Dc.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 ed(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 td=[400300,400301,400302,400310],nd=Yr.EXTERNAL_AUTH_TOKEN_EXPIRED.toString(),rd=e=>`${nd}:${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=Ju(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=>td.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=rd(n),this._logger=r,this._cache=s,this._statsTrackers=o}static init(t){let n;return t.chatSDK?(ed(t.chatSDK),n=t.chatSDK):n=Qu(t.appId,t.extensions,t.messengerVersion,t.chatParams),new jr(n,t.aiAgentId,t.logger,t.cache,t.statsTrackers)}}const sd=e=>t=>{if(!e||e.getState()==="foregrounded"){t();return}const n=e.subscribe(r=>{r==="foregrounded"&&(n(),t())});return n},od=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 id=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 ad=e=>e==="desk401103"||e==="desk401106"||e==="desk401107"||e==="desk401108"||e==="desk401109";class cd{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(!ad(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 cd(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 ld(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,dd=typeof __SBA_USE_DESK_CLIENT__>"u"||__SBA_USE_DESK_CLIENT__;function He(e){if(!e)throw new Error("Not authenticated. Call authenticate() first.")}function md(e,t){return Object.entries(t).every(([n,r])=>e[n]===r)}const hd=e=>{const t={conversationInitialRender:new hu(e),conversationNotInteractiveTimeout:new Eu(e),recoveryNotInteractiveTimeout:new Su(e),conversationListInitialRender:new pu(e),aievAuthExpiredUnhandled:new uu(e),messagePendingStuck:new vu(e),userPerceivedResponseTime:new $u(e),streamStalled:new Ru(e),typingIndicatorAbsentTimeout:new ku(e),renderedContentUnusable:new Tu(e)};return{...t,clear:()=>{Object.values(t).forEach(n=>n.clear())}}};class In extends zu{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",Pu());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"?jl(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 Vu({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)md(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-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 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=sd(n.foregroundStateAdapter),this._watchBackgrounded=n.foregroundStateAdapter&&od(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 Yl(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?ld(n.useMMKVStorage):r.keyValueStorage,c=n.useMMKVStorage?{...n.chatParams,useMMKVStorageStore:n.useMMKVStorage}:n.chatParams,u=ll({appId:n.appId,aiAgentId:n.aiAgentId,storage:i});let d;const h=hd((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=dd?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 fd(...e){return function({children:n}){return e.reduce((r,s)=>a.createElement(s,null,r),n)}}function gd(e,t){const n=e.lastMessage;return n!=null&&n.isAdminMessage()?n.message??"":pd(e,t)}function pd(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 _d(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 Ed=typeof __SBA_USE_DESK_CLIENT__>"u"||__SBA_USE_DESK_CLIENT__,Cd=({data:e,extendedMessagePayload:t,ticketClosureLabels:n})=>{if(Ed){const r=id(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}))},bd=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=bd(e);return r?`#${un(r[0])}${un(r[1])}${un(r[2])}${n}`:e},vd=(e,t)=>{if(!t)return e;const n={...e};for(const[r,s]of Object.entries(t))s&&(n[r]=s);return n},Sd=e=>e.consentDialog?"consent":e.toggleAllowed?e.enabled?"on":"off":"readonly",yd=e=>e.length>0,Ad=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",Td=({currentFiles:e,incomingFiles:t,maxAttachmentCount:n})=>{const r=Ad(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,Id=e=>e%xt===0?xt:Mi,xd=({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"),Rd=wi.Provider,ye=wi.useContext;function Md(e){const t=wd(e);return a.createElement(Rd,{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 wd(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=kd(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 kd(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 Ld=0;function Od(){return l.useState(()=>`${Ld++}`)[0]}const _t=(e,t,n)=>{const r=l.useRef(t),o=Od();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 Nd(e,t){return!e||!t?!0:e.url!==t.url}function ze(e){return e!=null&&"sendingStatus"in e}function Dd(e,t="##__USER_ID_IS_NOT_PROVIDED__##"){var n;return ze(e)?((n=e.sender)==null?void 0:n.userId)===t:!1}function $d(e,t){return Dd(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 Pd=({...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=Fd(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];Ud(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=>$d(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}}},Fd=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),{}),Ud=(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},Bd=(e=Hd)=>{const[{initialized:t,loading:n,refreshing:r,messageMap:s,newMessageMap:o},i]=l.useReducer(Pd,{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 Hd(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 Gd=(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 zd=(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}=Bd(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=Gd(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()&&!Nd(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}},Vd=e=>e.customType==="SENDBIRD_DESK_ADMIN_MESSAGE_CUSTOM_TYPE"?!0:e.isAdminMessage()?e.message==="The channel's custom_type was updated.":!1,Kd=(e,t,n)=>{const r=zd(e,t,{...n,strictStreamingOrder:!0}),s=l.useMemo(()=>r.messages.filter(o=>!Vd(o)),[r.messages]);return{...r,messages:s}},qd=()=>{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=qd(),Wd=({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}},Yd=({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 jd(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 Xd(e){return`#${e.map(t=>t.toString(16).padStart(2,"0")).join("")}`}function Zd(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 Jd(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]=jd(e),[i,c,u]=Zd(r,s,o),d=Math.max(0,Math.min(1,u*t)),m=Math.max(0,Math.min(1,c*n)),[h,f,g]=Jd(i,m,d);return Xd([Math.round(h),Math.round(f),Math.round(g)])}function Qd(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 em(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 tm=(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=nm(e),n=rm(e,t),r=om(n,e.colors,e.selectedTheme),s=am(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 nm({selectedTheme:e,palette:t,primary:n}){const r=t!=null&&t.primary?t.primary:n?n===mn.primary.main?mn.primary:Qd(n,e):mn.primary;return{...mn,primary:r,...t}}function rm({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"?em:tm)(s,o,i,c,u)}function sm(e,t,n){return typeof e=="string"?e:e[t]??n}function om(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]=sm(m,n,h)}}}return r}function im(e,t,n){const r={...e};return n.forEach(s=>{const o=t[s];o!=null&&(r[s]=o)}),r}function am({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]=im(s,r,o)}}),t}const{Provider:cm,useContext:Fn}=be("AIAgentTheme");function lm({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(cm,{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"]),um={off:"off",always:"always",handed_off_only:"handed_off_only"},dm=()=>{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:um[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:mm,useContext:ft}=be("AIAgentMessengerSession"),hm=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}=dm();l.useEffect(()=>{const D=r.onMessengerSettingsUpdated(({settings:G})=>{const{appearance:H,bot:K,launcher:J,memory:q}=G;c(H.selected_theme,H),_(Hu(K)),y(Gu(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(mm,{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)}),fm={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"},gm=e=>e.disabled?fm[e.disabledBy]==="ready":!0,pm=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&&Wc(t)?"file_audio":"file_document"};let Ws=0;const _m=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)},Em=(e,t)=>{Oi(e,t)},Cm=(e,t)=>{Ni(e,t)},bm=(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))},vm=({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])},Sm=({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])},ym=({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=>bm(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&&(Em(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&&(Cm(r,E),E.tracked=!0)},onLocalMessageDeleted:g=>{h(m)&&Tt(n,g.channelUrl)&&Ys(g,r)}}),[e,m,t,h,n,r])},Am=({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])},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,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:pm(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])},Im=({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=_m(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])},xm=({requestedChannelUrl:e,activeChannelUrl:t,statsEnabled:n=!0,statsTrackers:r})=>{const{aiAgentInfo:s}=ft();vm({activeChannelUrl:t,statsTrackers:r}),Sm({enabled:n,requestedChannelUrl:e,statsTrackers:r});const o=ym({aiAgentUserId:s==null?void 0:s.userId,statsEnabled:n,requestedChannelUrl:e,statsTrackers:r}),i=Tm({channelUrl:t,enabled:n,statsTrackers:r}),c=Im({channelUrl:t,enabled:n,statsTrackers:r});return l.useMemo(()=>({messageCallbacks:o,runWithPendingStuckStats:i,runWithUserTurnStats:c}),[o,i,c])},Nt=()=>ye()._aiAgentSDK.statsTrackers,Rm=({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 Mm(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 wm=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}},km=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},Lm=()=>{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},Om=3e4,Nm=({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=Om-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},Dm=({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},$m=({channel:e,messages:t,isStreamAnimating:n,isInitializingConversation:r})=>{const{aiAgentInfo:s,userSession:o}=ft(),i=Lm(),c=Dm({channel:e,lastMessage:Cr(t,[Le.SendingStatus.SUCCEEDED]),aiAgentUserId:(s==null?void 0:s.userId)??"",isStreamAnimating:n}),u=Nm({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(Ml(e))return d("handoff_pending");if(km(e))return d("form_active");const m=wm(e);return d(m||(c||u||r?"ai_responding":""))},Pm=()=>{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:Fm}=be("AIAgentConversation");function Um({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=Wd({...I,statsTracker:T.conversationNotInteractiveTimeout}),O=Yd({...I,scheduleForegroundTask:E.scheduleForegroundTask,statsTracker:T.recoveryNotInteractiveTimeout}),k=Rm(I),{channel:R,channelFetchError:F,getChannel:D,isInitializingConversation:Q}=Mm(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=xm({requestedChannelUrl:t,activeChannelUrl:re,statsEnabled:m,statsTrackers:T}),H=Kd(_,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=Pm(),J=$m({channel:R,messages:H.messages,isStreamAnimating:K.isAnimating,isInitializingConversation:Q});Am({enabled:m,channelUrl:re,initialized:H.initialized,inputReady:gm(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(Fm,{value:Te},e)}function Bm(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}},Hm=({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:Gm}=be("AIAgentConversationList");function zm({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=Hm({enabled:n}),d=Bm(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(Gm,{value:m},r)}function Vm(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:Km,useContext:qm}=be("MessageTemplateFetching");function Wm({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=Vm(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(Km,{value:u},e)}const Ym="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(Ym)),[i])}throw new Error("Unsupported feature")},jm={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"},Xm={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}}},Zm={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}}},Jm={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}}},Qm={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}}},eh={text:Xm,number:Zm,"single-select":Jm,"multi-select":Qm},th={getValueOrDefault:()=>null,validate:()=>({isValid:!1})};function Pi(e){return eh[e.type]||th}function Xs(e){return Pi(e).getValueOrDefault(e)}function nh(e,t,n={}){const r={...jm,...n};return Pi(e).validate(e,t,r)}const rh=(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=nh(_,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())}}},sh=({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}},oh=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}},ih=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?ih(r.metaData):void 0;return{user:s?t:r,isBot:s,thinkingMessage:o}},ah=250,ch=(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),ah);return()=>clearTimeout(c)},[n,e!==null]),e??(n?s.current:null)},lh=(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},[])},uh=(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()}}},dh=(e,t,n=1e4,r=!0)=>{const s=l.useRef(null),o=l.useRef(null),i=l.useRef(!1);s.current||(s.current=uh(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])},mh=({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 hh=new Set(["free_text","single_choice"]),fh=({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(hh.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"}}},gh=({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,ph=1500,or=e=>Math.max(0,e-Ui),Cn=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():0,_h=(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,ph);return()=>clearTimeout(d)},[s,c,t]),!s&&!c},Eh=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},Ch=({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:_}},bh=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=_h(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}=Ch({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}=Eh(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},vh=e=>({visible:!0,remainingTime:e,showDescription:!0,targetTimeMs:Date.now()+e*1e3}),Sh=(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}},yh=()=>{const{chatSDK:e}=ye(),[t,n]=l.useState(Qs),r=()=>n(Qs);return Qt(e,{onConnectionDelayed:s=>{s>0?n(vh(s)):r()},onReconnectSucceeded:r,onConnected:r}),l.useEffect(()=>{if(!t.visible||!t.showDescription||t.targetTimeMs==null)return;const s=setTimeout(()=>{n(o=>Sh(o))},1e3);return()=>clearTimeout(s)},[t.visible,t.showDescription,t.targetTimeMs,t.remainingTime]),{visible:t.visible,remainingTime:t.remainingTime,showDescription:t.showDescription}},Ah=e=>{const t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`},Th=(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)}},Ih=({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&&!Yc(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])},xh=e=>{const t=l.useRef(!1);l.useEffect(()=>{t.current||e!=null&&e.onVisibleTextProgress&&(t.current=!0,e.onVisibleTextProgress(0))},[e])},ir=5e3,Rh=({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])},Mh=e=>{const{conversationInitialRender:t,conversationListInitialRender:n}=Nt();l.useLayoutEffect(()=>{t.setPresentMethod(e),n.setPresentMethod(e)},[t,n,e])},wh=(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(),kh="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}},Lh=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}},Oh=(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)},Nh=(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},Dh=(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},$h=(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},Ph=e=>{let t=0,n="";for(;t<e.length;){const r=Nh(e,"[",t);if(r===-1){n+=e.slice(t);break}const s=Dh(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=$h(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)},Fh=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}`}),Uh=e=>e.replace(/(^|[^_\\])__([^\s_](?:[\s\S]*?[^\s_])?)__(?!_)/g,"$1$2"),Bh=e=>e.replace(/(^|[^~\\])~~([^\s~](?:[\s\S]*?[^\s~])?)~~(?!~)/g,"$1$2"),Hh=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},Gh=e=>e.replace(/\\([\\`*_[\]()#+.!~|-])/g,"$1"),zh=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},Vh=e=>{const t=e.split(`
|
|
12
|
+
`),n=[];let r=0;for(;r<t.length;){const s=t[r],o=t[r+1],i=to(s);if(i.length>0&&o&&eo(o)){for(n.push(i.join(" ")),r+=2;r<t.length;){const c=t[r],u=to(c);if(u.length===0||eo(c))break;n.push(u.join(" ")),r+=1}continue}n.push(s),r+=1}return n.join(`
|
|
13
|
+
`)},Kh=e=>e.replace(/^\s{0,3}(?:(?:-\s*){3,}|(?:\*\s*){3,}|(?:_\s*){3,})$/gm,""),qh=(e,t)=>{const n=e.split(`
|
|
14
|
+
`),r=[];let s=0;for(;s<n.length;){const o=n[s],i=Lh(o);if(!i){r.push(o),s+=1;continue}let c=-1;for(let u=s+1;u<n.length;u++)if(Oh(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
|
+
`)},Rn=(e,t)=>{let n=0,r=t-1;for(;r>=0&&e[r]==="\\";)n+=1,r-=1;return n%2===1},Wh=e=>{const t=[];let n=0,r="";for(;n<e.length;){const s=e[n];if(s!=="`"||Rn(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]==="`"&&!Rn(e,c)&&e.startsWith(i,c)){const d=e.slice(o,c),m=t.push(d)-1;r+=Hi(m),n=c+i.length,u=!0;break}c+=1}u||(r+=i,n=o)}return{text:r,inlineCodes:t}},Ki=(e,{codeBlockPlaceholder:t=kh}={})=>{const n=e==null?void 0:e.replace(/\r\n?/g,`
|
|
17
|
+
`);if(!n)return;const r=[];let s=n;s=qh(s,t),s=zh(s);const o=Wh(s);s=o.text,r.push(...o.inlineCodes),s=Ph(s),s=Fh(s),s=Uh(s),s=Bh(s),s=Hh(s),s=Vh(s),s=Kh(s),s=Gh(s);for(let c=0;c<r.length;c++)s=s.replaceAll(Hi(c),r[c]);return Mt(s)||void 0},Yh=(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())||"",jh=e=>(e?Mt(e):void 0)||void 0,no=30,Xh=e=>e.length>no?`${e.slice(0,no)}…`:e,Zh=({agent:e,status:t,lastMessage:n,time:r,unreadCount:s},o)=>{const i=Xh(Mt(n)),c=[t,i].filter(Boolean).join(", ");return o(Mt(e),Mt(c),r,s)},Tr=e=>({text:Mn(e),format:"plain"}),Jh=e=>({text:Mn(e),format:"markdown"}),Qh=({markdownText:e,plainText:t,comparisonText:n})=>{const r=Mn(e);return r&&r!==Mn(n)?Jh(r):Tr(t)},Kt=({sender:e,message:t,messageFormat:n="plain",time:r,codeBlockPlaceholder:s})=>{const o=[],i=n==="markdown"?Ki(t,{codeBlockPlaceholder:s}):jh(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),ef=(...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?ef(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=Yh({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)},tf=(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}}},nf=e=>{switch(e){case"newMessage":case"conversationClosed":case"csatDisplayed":case"csatSubmitted":case"csatExpired":return"ordered";default:return"latestOnly"}},rf=(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(". "),sf=(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}},of=(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}},af=(e,t)=>!t||!Qe(e)||e.sender.userId!==t?null:e.reqId||(e.messageId>0?String(e.messageId):null),cf=(e,t)=>Me.isAdmin(e)?Me.isCSAT(e):"sender"in e?e.sender.userId!==t:!1,lf=e=>"messageId"in e&&e.messageId>0?String(e.messageId):"reqId"in e&&typeof e.reqId=="string"&&e.reqId.length>0?e.reqId:null,uf=e=>e===Ee.CollectionEventSource.EVENT_MESSAGE_RECEIVED||e===Ee.CollectionEventSource.EVENT_MESSAGE_UPDATED,df=({isOpened:e,opensConversationList:t})=>e?t?"closeConversationList":"closeConversation":t?"openConversationList":"openConversation",mf=(e,t)=>{switch(e){case"closeConversationList":return t.closeConversationList;case"closeConversation":return t.closeConversation;case"openConversationList":return t.openConversationList;case"openConversation":return t.openConversation}},hf=(e,t)=>{switch(e){case"closeConversation":return t.hintCloseConversation;case"openConversationList":return t.hintOpenConversationList;case"openConversation":return t.hintOpenConversation;default:return}},ff=({intent:e,strings:t})=>({label:mf(e,t),hint:hf(e,t)}),gf="1.40.1",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",pf=`[${Yi}="${ji}"]`,Xi={[Yi]:ji},ns="data-sb-focus-trap-sentinel",_f="true",Zi="data-sb-initial-focus-header",Ji="true",Ef=`[${Zi}="${Ji}"]`,Qi={[Zi]:Ji},ea="data-sb-message-input",ta="true",Cf=`textarea[${ea}="${ta}"]:not(:disabled)`,bf={[ea]:ta},na=1e3,hn=2147483647,Et={MODAL:hn-1,TOOLTIP:hn-2,WINDOW:hn-3,LAUNCHER:hn-4},ra=36,vf=100,Sf=gf,rs="noopener noreferrer nofollow",yf=()=>typeof document>"u"||document.visibilityState==="visible",Ir=()=>typeof document<"u"&&document.visibilityState==="hidden",so=()=>Ir()?"backgrounded":"foregrounded",Af={getState:so,subscribe:e=>{if(typeof document>"u")return()=>{};const t=()=>e(so());return document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t)}};function Tf(){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 If(){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 xf={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:xf,dateLocale:wc.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"]),Rf='@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:Mf,useContext:ss}=be("AgentUIElementResolver"),wf=({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(Mf,{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:kf,useContext:os}=be("EscapeDismissStack"),io=e=>{e.stopPropagation(),e.stopImmediatePropagation()},Lf=({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(kf,{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])},Of=(e,t)=>{const{register:n}=os();aa(e,t,n)},Nf=(e,t)=>{const{registerShellDismissHandler:n}=os();aa(e,t,n)},ca=()=>{const{subscribe:e,getOpenCount:t}=os();return l.useSyncExternalStore(e,()=>t()>0,()=>!1)},Df=(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),$f={...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:$f},Pf=Object.freeze(Object.defineProperty({__proto__:null,default:wn},Symbol.toStringTag,{value:"Module"})),Rr=new Map([[en,wn]]);async function Ff(e){const t=Rr.get(e);if(t)return t;try{if(ia.has(e)){const{default:n}=await Df(Object.assign({"./languages/de.ts":()=>Promise.resolve().then(()=>require("./cjs/qr4Ghr48.cjs")),"./languages/en.ts":()=>Promise.resolve().then(()=>Pf),"./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:Uf,useContext:ie}=be("Localization"),Bf=({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}),Ff(c).then(i))},[e,t,n]),a.createElement(Uf,{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")},Hf=U.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
|
+
`}),Gf=U.css`[${kn}='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);}[${kn}='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);}`,b={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 Xe=e=>{const t=e;return typeof t=="number"?`${t}px`:t},zf=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"})),Vf=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"})),Kf=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"})),qf=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"})),Wf=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"})),Yf=new Set(["send","chat","message","chevron-right","good","good-filled","bad","bad-filled"]),jf={close:zf,send:Wf,menu:qf,expand:Kf,collapse:Vf,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")))},Xf=e=>({size:t=24,color:n=b.color.primary.main,flipInRtl:r=!1})=>a.createElement(Jf,{$size:t,$color:n,$rtlFlip:r},a.createElement(Yt,{errorFallback:a.createElement(Qf,null)},a.createElement(e,null))),la=Object.fromEntries(Object.entries(jf).map(([e,t])=>[e,Xf(t)])),Zf=U.css`[dir='rtl'] &:not([dir='ltr']),&[dir='rtl']{transform:scaleX(-1);}`,Jf=C.default.span.attrs({"aria-hidden":"true"})`
|
|
67
|
+
width: ${({$size:e})=>Xe(e)};
|
|
68
|
+
height: ${({$size:e})=>Xe(e)};
|
|
69
69
|
display: inline-block;
|
|
70
70
|
|
|
71
71
|
svg {
|
|
@@ -84,24 +84,24 @@ $2
|
|
|
84
84
|
stroke-linejoin: round;
|
|
85
85
|
}
|
|
86
86
|
|
|
87
|
-
${({$rtlFlip:e})=>e&&
|
|
88
|
-
`,
|
|
87
|
+
${({$rtlFlip:e})=>e&&Zf};
|
|
88
|
+
`,Qf=()=>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:eg,useContext:tg}=be("MessengerIcon",{icons:la}),ng=({icons:e,children:t})=>{const n=l.useMemo(()=>({icons:vd(la,e)}),[e]);return a.createElement(eg,{value:n},t)},{Provider:rg,useContext:ua}=be("MessengerTheme");function sg(e){const{theme:t,appearance:n,logger:r}=e;return a.createElement(lm,{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(og,{...e}))}function og({rootElement:e=document.body,children:t}){const{theme:n,updateTheme:r}=Fn();return l.useLayoutEffect(()=>{e.setAttribute(kn,n.selectedTheme)},[e,n.selectedTheme]),a.createElement(U.ThemeProvider,{theme:n},a.createElement(rg,{value:{theme:n,updateTheme:r,rootElement:e}},t))}const ig=(e,t)=>{l.useEffect(()=>{const n=mt(t)instanceof ShadowRoot,r=mt(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])},ag=(e,t=document.body)=>{l.useEffect(()=>{if(!e)return;const n=mt(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])},cg=80,lg=()=>{const{stringSet:e}=ie(),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},da=be("AriaLiveRegion",{announce:me,announceScreenEntry:me,announceStatus:me,announceError:me,flush:me,setSuppressionState:me}),ug=da.Provider,is=da.useContext,dg={position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},mg=({children:e})=>{const t=l.useRef(null),n=l.useRef(new Set),r=l.useRef(me),s=lg(),[o]=l.useState(()=>tf(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=rf(g,s.current);i(p)},[i]),d=l.useCallback((g,p)=>{const v=sf(g,s.current),E=(p==null?void 0:p.mode)??nf(g.event);i(v,{mode:E,dedupeKey:p==null?void 0:p.dedupeKey})},[i]),m=l.useCallback((g,p)=>{const v=of(g,s.current);o.announceIgnoringSuppression(v),p&&setTimeout(()=>{p.focus()},cg)},[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(ug,{value:f},e,a.createElement("div",{ref:t,role:"status","aria-live":"polite","aria-atomic":"true",style:dg}))},ma=be("ConversationAnnouncements",{announcementsEnabled:!0,announce:me,announceScreenEntry:me,announceStatus:me,announceError:me,setIsSuppressed:me,setStatusPauseState:me,flush:me}),hg=ma.Provider,ct=ma.useContext,fg=({children:e,announcementsEnabled:t=!0})=>{const{announce:n,announceScreenEntry:r,announceStatus:s,announceError:o,flush:i,setSuppressionState:c}=is(),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(I=>{i(),s(I.params,I.options)})},[s,t,f,i]),p=l.useCallback((T,I)=>{if(I){d.current.add(T);return}d.current.delete(T),d.current.size===0&&g()},[g]),v=l.useCallback(T=>{t&&n(T)},[n,t]),E=l.useCallback(T=>{t&&r(T)},[r,t]),_=l.useCallback((T,I)=>{if(t){if(d.current.size>0){u.current.push({params:T,options:I});return}s(T,I)}},[s,t]),A=l.useCallback((T,I)=>{t&&o(T,I)},[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:v,announceScreenEntry:E,announceStatus:_,announceError:A,setIsSuppressed:h,setStatusPauseState:p,flush:i}),[t,i,v,A,E,_,h,p]);return a.createElement(hg,{value:y},e)},Un=["a[href]","button:not(:disabled)","input:not(:disabled)","select:not(:disabled)","textarea:not(:disabled)",'[tabindex]:not([tabindex="-1"])'].join(", "),ha=`${Un}, [tabindex="-1"]`,wt=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},jt=(e,t)=>{for(const n of e.querySelectorAll(t))if(!n.hasAttribute(ns)&&wt(n))return n;return null},fa=e=>{let t=null,n=null;for(const r of e.querySelectorAll(Un))r.hasAttribute(ns)||wt(r)&&(t??(t=r),n=r);return t?{first:t,last:n}:null},ga=(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,gg=(e,t,n)=>ga(e,t)||n!=null&&t instanceof HTMLElement&&n.contains(t),as=e=>jt(e,pf),pa=e=>as(e)??jt(e,Un),pg=e=>{const t=as(e);if(t)return t;const n=e.querySelector(Ef);return(n?jt(n,ha):null)??jt(e,Un)},B=({as:e,variant:t="body1",color:n,maxTextLines:r,className:s,...o})=>a.createElement(Cg,{as:e,$variant:t,className:s,$color:n,$maxTextLines:r,...o}),lo=new WeakMap,_g=(e,t)=>{let n=lo.get(t);n||(n=new Map,lo.set(t,n));const r=n.get(e);if(r)return r;const s=t[e]??t.body1,o=U.css`font-size:${Xe(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},lg=e=>e?F.css`display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:${e};overflow:hidden;`:"",ug=C.default.span`font-stretch:normal;letter-spacing:normal;${({$variant:e,theme:t})=>cg(e,t.typography)}color:${({$color:e})=>e};${({$maxTextLines:e})=>lg(e)}`;async function os(e){let t=e;t&&(!t.startsWith("http://")&&!t.startsWith("https://")&&(t="https://"+t),window.open(t,"_blank","noopener,noreferrer"))}const Tr='[role="dialog"][aria-modal="true"]',dg=(e,t)=>{const n=new Set(Array.from(e.ownerDocument.querySelectorAll(Tr)).filter(s=>s!==e&&(s.contains(e)||e.contains(s)))),r=t==null?void 0:t.closest(Tr);return r&&r!==e&&n.add(r),n},mg=(e,t)=>Array.from(e.ownerDocument.querySelectorAll(Tr)).some(n=>n!==e&&!t.has(n)&&!n.contains(e)&&Mt(n)),hg=e=>{const t=da(e)??e;t===e&&ma(e),t.focus()},ma=e=>{e.hasAttribute("tabindex")||e.setAttribute("tabindex","-1")},fg=(e,t)=>{const n=la(e);if(!n){ma(e),e.focus();return}n[t].focus()},ao=(e,t)=>{const n=e.ownerDocument.createElement("span");return n.tabIndex=0,n.setAttribute(Qr,cf),n.style.cssText=["position: fixed","width: 1px","height: 1px","opacity: 0","overflow: hidden","pointer-events: none"].join(";"),n.addEventListener("focus",()=>fg(e,t)),n},gg=(e,t)=>{e.key==="Tab"&&(e.defaultPrevented||e.target===t&&(la(t)||(e.preventDefault(),t.focus())))},$n=(e,t,{nameReady:n=!0}={})=>{const r=l.useRef(0),s=l.useRef(!1);l.useEffect(()=>{if(!e||!t.current){s.current=!1;return}r.current+=1;const o=r.current,i=t.current,c=i.getRootNode(),u=c.activeElement instanceof HTMLElement?c.activeElement:null,d=dg(i,u);return()=>{u&&Te(()=>{if(r.current!==o)return;const m=c.activeElement;i.isConnected&&m instanceof HTMLElement&&m!==i&&!i.contains(m)&&!ua(c,m)&&m.matches(ca)&&Mt(m)||mg(i,d)||!u.isConnected||!Mt(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)&&Mt(m)){s.current=!0;return}s.current=!0,hg(o)};if(n)return Te(c),()=>{i=!0};const u=setTimeout(()=>Te(c),Zi);return()=>{i=!0,clearTimeout(u)}},[e,t,n]),l.useEffect(()=>{if(!e||!t.current)return;const o=t.current,i=ao(o,"last"),c=ao(o,"first"),u=d=>gg(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])},mt=({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}=ts();return $n(n,d),Af(n,o?r:de),n?Tc.createPortal(a.createElement(pg,{onClick:o?r:void 0,style:e},a.createElement(_g,{ref:d,role:"dialog","aria-modal":"true","aria-label":i,"aria-labelledby":c,"aria-describedby":u,onClick:h=>h.stopPropagation()},s)),m(t)):null},pg=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:${gt.MODAL};`,_g=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:${gt.MODAL};`,Eg=({id:e,children:t})=>a.createElement(Cg,{id:e},t),Cg=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;`,co=(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?{}:qi}:n},bg=()=>{const e=`${l.useId()}-`;return(t,n)=>{if(!t)return{props:{},node:null};const r=e+n,s=l.createElement(Eg,{id:r,children:t});return{props:{"aria-describedby":r},node:s}}},lo=({name:e,mimeType:t,selected:n},r)=>{var o;const s=Ye(t??"")?r.A11Y_FILE_IMAGE(e):Zt(t??"")?r.A11Y_FILE_VIDEO(e):ii({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},vg=e=>t=>{t.repeat||(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())},Gt=({onActivate:e})=>({role:"button",tabIndex:0,onClick:e,onKeyDown:vg(e)}),Sg=({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()},uo=(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:Sg({disabled:t,currentIndex:n,totalCount:r,onNavigate:o}),tabIndex:i}},ae=()=>{const{stringSet:e}=ie(),t=bg(),n=(i,c)=>{let u=e.A11Y_HINT_OPEN_FILE,d="of";Ye(i??"")&&(u=e.A11Y_HINT_OPEN_IMAGE,d="oi"),c!==void 0&&(d+=c);const m=t(u,d);return{props:m.props,descriptionNode:m.node}},r=i=>({"aria-label":lo(i,e)});return{launcher:{button:({isOpened:i,opensConversationList:c})=>{const u=sf({intent:tf({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:co(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,...df},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":qt({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?lo({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),...uo(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:{...uo(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:co(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=Gh({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}}}}},yg=({title:e,description:t,highlightedText:n})=>{const r=ph(t,n);return a.createElement(Tg,null,a.createElement(Ig,null,a.createElement(U,{as:"div",variant:"h1",color:b.themedColor.textHighEmphasis},e),t&&a.createElement(xg,null,a.createElement(U,{as:"div",variant:"body3",color:b.themedColor.textMidEmphasis},r.beforeText,r.highlightedText?a.createElement(Rg,null,r.highlightedText):null,r.afterText))))},Ag=()=>{const{components:e}=Pn.useContext(),{stringSet:t}=ie(),{messenger:n}=ae(),r=fh(),s=r.showDescription?gh(r.remainingTime):"",o=r.showDescription?t.CONNECTION_DELAY__DESCRIPTION(s):"";return a.createElement(mt,{portalContainerId:ve.WINDOW,visible:r.visible,onClose:de,...n.connectionDelayDialog().props},a.createElement(e.Dialog,{title:t.CONNECTION_DELAY__TITLE,description:o,highlightedText:s||void 0}))},Pn=We({template:Ag,components:{Dialog:yg}}),Tg=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};`,Ig=C.default.div`display:flex;flex-direction:column;`,xg=C.default.div`margin-top:16px;`,Rg=C.default.strong`font-weight:700;`,Mg=({url:e})=>os(e),{Provider:wg,Consumer:ha,useContext:ue}=be("Messenger");function kg({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}=ts(),f=l.useCallback(()=>{m.setOpened(!1)},[m.setOpened]);Tf(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 _=ut(o.rootElement),A=h(ve.WINDOW);let y=!1;return Te(()=>{var T;y||ig(_,_.activeElement,A)&&((T=h(ve.LAUNCHER))==null||T.focus())}),()=>{y=!0}},[m.opened,o.rootElement,h]);const{Template:p}=Pn.useContext(),v=l.useMemo(()=>{var E;return{...o.handlers,onClickLink:((E=o.handlers)==null?void 0:E.onClickLink)??Mg}},[o.handlers]);return a.createElement(bd,{...o},E=>a.createElement(wg,{value:{...o,...E,state:m,enableCloseConversationButton:n,enableExpandButton:r,enableAutoDisconnectInLauncher:s,handlers:v}},a.createElement(p,null),e))}const fa=/iPad|iPhone|iPod/.test(navigator.userAgent),Lg=/Android/.test(navigator.userAgent),tn=e=>fa||Lg;let Ut=null,sr=null;const Og=(e,t=5e3)=>{Ut&&(clearInterval(Ut),clearTimeout(sr));const n=document.title;Ut=setInterval(()=>{document.title=document.title===e?n:e},750),sr=setTimeout(()=>{clearInterval(Ut),Ut=null,sr=null,document.title=n},t)},ga=()=>{Promise.resolve().then(()=>require("./cjs/B93o4u0P.cjs")).then(e=>{new Audio(e.default).play().catch(()=>{})})},pa="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)",Ie=F.css`&:focus-visible{outline:2px solid ${b.themedColor.primary};outline-offset:2px;}`,mo=e=>{if(typeof e=="string"||typeof e=="number")return String(e)},Fn=({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??mo(t)??mo(n),f=u?void 0:t?d:n?m:void 0,g=t&&n?m:void 0,p=()=>{c(),Te(()=>o==null?void 0:o())},v=()=>{c(),Te(()=>i==null?void 0:i())};return a.createElement(mt,{portalContainerId:ve.WINDOW,visible:e,onClose:c,"aria-label":h,"aria-labelledby":f,"aria-describedby":g},a.createElement(Ng,null,a.createElement(Dg,null,t&&a.createElement("div",{id:d},a.createElement(U,{variant:"h1",color:b.themedColor.textHighEmphasis},t)),n&&a.createElement($g,{id:m},a.createElement(U,{variant:"body3",color:b.themedColor.textMidEmphasis},n))),a.createElement(Pg,null,s&&a.createElement(ho,{onClick:v},a.createElement(U,{variant:"button",color:b.themedColor.textHighEmphasis},s)),a.createElement(ho,{onClick:p},a.createElement(U,{variant:"button",color:b.themedColor.primary},r)))))},Ng=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};`,Dg=C.default.div`margin-bottom:16px;`,$g=C.default.div`margin-top:16px;`,Pg=C.default.div`display:flex;flex-direction:row;justify-content:flex-end;`,ho=C.default.button`all:unset;display:flex;justify-content:center;align-items:center;border-radius:4px;cursor:pointer;background-color:transparent;padding:10px 16px;${Ie}`,{Provider:Fg,useContext:Ne}=be("MessengerSession"),Ug=l.forwardRef(function({children:e,...t},n){return a.createElement(sm,{ref:n,...t},r=>a.createElement(Bg,{...r},e))}),Bg=({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);ft(n,{async onUserJoined(T,I){var N,k,R,G;T.conversation&&T.conversation.type===me.ConversationType.PROACTIVE&&I.userId===((N=n.currentUser)==null?void 0:N.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),Hg({sound:document.hidden||!c.opened}),(G=A.current)==null||G.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(Fg,{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(Fn,{visible:E,title:"Session timed out",description:"Start a new conversation.",onConfirm:y,onClose:de}))};function Hg({sound:e}){Og("🔔You have received a new message"),e&&ga()}const Mn=`@${Ue}-focused-channel`,_a=`${Date.now()}-${Math.random().toString(36).slice(2)}`,Gg=()=>{try{const e=localStorage.getItem(Mn);return e?JSON.parse(e).channelUrl??null:null}catch{return null}},fo=e=>{try{localStorage.setItem(Mn,JSON.stringify({channelUrl:e,tabId:_a}))}catch{}},go=()=>{try{const e=localStorage.getItem(Mn);if(!e)return;JSON.parse(e).tabId===_a&&localStorage.removeItem(Mn)}catch{}},zg=(e,t)=>(l.useEffect(()=>{if(!t||!e)return;const n=()=>fo(e),r=()=>go();return document.hasFocus()&&fo(e),window.addEventListener("focus",n),window.addEventListener("blur",r),()=>{window.removeEventListener("focus",n),window.removeEventListener("blur",r),go()}},[t,e]),{isChannelViewedInAnyTab:()=>document.hasFocus()||Gg()===e}),Vg=e=>{const{config:t,chatSDK:n}=ue(),{sdkUser:r}=Ne(),s=t.conversation.messageAlertSoundEnabled,{isChannelViewedInAnyTab:o}=zg(e,s);ft(n,{onMessageReceived(i,c){if(!s||i.url!==e||o())return;(Je(c)&&c.sender.userId!==(r==null?void 0:r.userId)||c.isAdminMessage()&&!c.silent)&&ga()}})};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 Kg(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 Oe.MessageMetaArray({key:ri,value:[t,n]})}}const Yg=({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 Kg(s),i={...s,metaArrays:o?[o]:void 0},c=Wg(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===Oe.SendingStatus.SUCCEEDED?(i=n==null?void 0:n.onCustomEvent)==null||i.call(n,{type:"message-sent-succeeded",data:{message:s}}):s.sendingStatus===Oe.SendingStatus.PENDING&&((c=n==null?void 0:n.onCustomEvent)==null||c.call(n,{type:"message-sent-pending",data:{message:s}}))}}},Wg=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},Tt=50,or=Tt-40,{Provider:jg,useContext:Ea}=be("ConversationScroll"),po={viewport:0,contentHeight:0,contentSnapshotHeight:0,shouldRecalc:!1,shouldUpdate:!1},ir=e=>Math.max(0,e.scrollHeight-e.scrollTop-e.clientHeight),_o=e=>Array.from(e.querySelectorAll(`#${Ue}-message-item`));function Xg({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(po),[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=ir($);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]),L=()=>{c.current.contentSnapshotHeight=c.current.contentHeight,c.current.shouldUpdate=!0,c.current.shouldRecalc=!0},N=()=>{const $=r.current;!$||!c.current.shouldUpdate||d(M=>{c.current.shouldUpdate=!1;const{contentHeight:x,contentSnapshotHeight:O,shouldRecalc:P}=c.current,X=$.clientHeight;if(O>x)return M;const re=k($,{messageType:"outgoing"});let J=0;if(re){const Ee=re.message.offsetTop-or+X;J=Math.max(0,Ee-x)}else{const Ee=x-O,$e=X-or;J=Math.max(0,Ee-$e)}return M===0||J!==M||P?(c.current.shouldRecalc=!1,J):M})},k=l.useCallback(($,M)=>{const{messageType:x="all"}=M??{},O=_o($);let P=O;x==="outgoing"&&(P=O.filter(Ct=>Ct.getAttribute("data-layout-id")==="outgoingmessage"));const X=P[P.length-1];if(!X)return null;const re=$.getBoundingClientRect(),J=X.getBoundingClientRect(),Ee=$.scrollTop+(J.top-re.top),$e=Ee+X.offsetHeight;return{message:X,scrollTop:Ee,lastMessageBottom:$e}},[]),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&&L(),i.current.programmatic?o.current.distanceFromBottom=ir($):A($),N()},[I,k]),G=l.useCallback(()=>{T(),y(),c.current=po,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>Tt;if(i.current.awayByUser=!1,h(0),!M){Te(()=>{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()),Te(()=>{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 O=()=>{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(O,500);i.current.reconcileTimer=P,x.addEventListener("scrollend",()=>{clearTimeout(P),i.current.reconcileTimer=null,O()},{once:!0})}x.scrollTo({top:x.scrollHeight,behavior:$?"smooth":"auto"}),$||O()})},[]),Q=l.useCallback(()=>{const $=r.current;if($){if(i.current.awayByUser){A($);return}D(!1)}},[D]),ne=l.useCallback(()=>{const $=r.current,M=s.current;if(!$||!M.resize)return;const x=new Set(_o($));for(const O of M.resizeTargets)x.has(O)||(M.resize.unobserve(O),M.resizeTargets.delete(O));for(const O of x)M.resizeTargets.has(O)||(M.resize.observe(O),M.resizeTargets.add(O))},[]),B=l.useCallback($=>{T();const M=s.current;typeof ResizeObserver<"u"&&(M.resize=new ResizeObserver(Q),ne());const x=new MutationObserver(()=>{ne(),Q()});M.mutation=x,x.observe($,{childList:!0})},[T,Q,ne]),H=l.useCallback($=>{if(!$){r.current=null,T();return}if(r.current=$,I!=="fixed"){B($);return}G(),c.current.viewport=$.clientHeight;const M=new MutationObserver(()=>{R()});s.current.mutation=M,M.observe($,{childList:!0,subtree:!0})},[T,I,R,G,B]),q=l.useCallback(()=>{const $=r.current;if(!$)return;const M=k($,{messageType:"outgoing"});M&&($.scrollTo({top:M.message.offsetTop-or,behavior:"smooth"}),i.current.userMessageTimer&&clearTimeout(i.current.userMessageTimer),i.current.userMessageTimer=setTimeout(()=>{v(!1)},500))},[k]),Z=($,M,x)=>{const O=ir($);if(x&&O>Tt){i.current.programmatic=!1,i.current.awayByUser=!0,y(),A($),_(!0),o.current.prevScrollTop=M;return}o.current.distanceFromBottom=O},z=($,M,x)=>{const P=A($)<=Tt;M&&!P&&(i.current.awayByUser=!0,y()),x&&P&&(i.current.awayByUser=!1)},Y=$=>{const{scrollTop:M}=$.currentTarget,x=o.current.prevScrollTop;i.current.programmatic?Z($.currentTarget,M,M<x):z($.currentTarget,M<x,M>x),o.current.prevScrollTop=M},W=l.useCallback(()=>{I==="fixed"&&(v(!0),L())},[I]),K=l.useCallback(()=>{I==="fixed"?setTimeout(()=>q(),300):D()},[I,q]),V=l.useCallback($=>{i.current.streaming=$,I==="fixed"?L():i.current.awayByUser||D()},[I,D]),w=l.useCallback($=>{g($),$&&(d(0),I==="fixed"&&T())},[T,I]),oe=l.useCallback($=>{I==="auto"&&$&&!i.current.awayByUser&&D()},[I,D]),xe=!(m<=Tt)&&!p,Re=l.useCallback(()=>o.current.distanceFromBottom>Tt,[]);return a.createElement(jg,{value:{ref:H,state:{bottomSpace:u,isAwayFromBottom:xe,isScrollPositionReconciled:E,shouldCountNewMessages:Re},props:{onScroll:Y},actions:{scrollToBottom:D,onBeforeMessageSend:W,onAfterMessageSend:K,onStreamingUpdate:V,onConversationClosed:w,onTypingIndicatorUpdate:oe}}},n)}const{Provider:Zg,Context:Jg,useContext:Ae}=be("Conversation"),Qg=({children:e})=>{var s;const{channelSource:t}=Ae(),n=(s=t.channel)==null?void 0:s.url,{checkForUserActionRequired:r}=Xm(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)},ep=({channelUrl:e,onClearChannelUrl:t,onNavigateToConversationList:n,conversationStatsEnabled:r,shouldMarkAsRead:s,shouldInitializeConversation:o,initialUserMessage:i,children:c})=>{const{activeChannel:u,refreshActiveChannel:d}=Ne(),m=Ea(),h=e||(u==null?void 0:u.url);Vg(h);const{onBeforeSendMessage:f,onAfterSendMessage:g}=Yg({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=>ke.isStreaming(T));m.actions.onStreamingUpdate(y)},[m.actions.onStreamingUpdate]),E=l.useCallback(A=>{m.actions.onConversationClosed(A===me.ConversationStatus.CLOSED)},[m.actions.onConversationClosed]),_=l.useCallback(async()=>{await d(),e&&(t==null||t())},[d,e,t]);return a.createElement(wm,{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(Zg,{value:{...A,scrollSource:m,goToActiveConversation:_,onNavigateToConversationList:n}},a.createElement(Qg,null,c)))},Ca=({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(Xg,{scrollMode:s,messageStackDirection:o},a.createElement(ep,{...t},e))},is=l.createContext({onDrop:de,subscribe:()=>de}),Ir=({children:e})=>{const t=l.useRef(new Set);return a.createElement(is.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)},tp=({onDropFiles:e})=>{const{subscribe:t}=l.useContext(is);l.useEffect(()=>t(e),[e])};Ir.Consumer=({children:e})=>{const{onDrop:t}=l.useContext(is);return e({onDrop:t,onDragOver:s=>s.preventDefault()})};const ba=be("WindowTitle",{hasWindowTitleReference:!1,isTitlePending:!1,isWindowNameReady:!0,registerWindowTitleReference:()=>de,registerWindowTitlePending:()=>de}),np=ba.Provider,va=ba.useContext,Eo=()=>{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]},as=({children:e})=>{const[t,n]=Eo(),[r,s]=Eo(),o=!r||t,i=l.useMemo(()=>({hasWindowTitleReference:t,isTitlePending:r,isWindowNameReady:o,registerWindowTitleReference:n,registerWindowTitlePending:s}),[t,r,n,s]);return a.createElement(np,{value:i},e)},Un=va,Sa=({enabled:e,label:t})=>{const{registerWindowTitleReference:n,registerWindowTitlePending:r}=va(),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?ve.WINDOW_TITLE:void 0}},rp=(e,t)=>{const r=(t?jt(e,t):null)??ag(e)??e;r===e&&!e.hasAttribute("tabindex")&&e.setAttribute("tabindex","-1"),r.focus({focusVisible:!1})},ya=(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=ss(e.current)!=null;if(!s&&!c&&!n)return;let u=!1;const d=()=>{u||i.current||!e.current||(i.current=!0,rp(e.current,s))};if(r)return Te(d),()=>{u=!0};const m=setTimeout(()=>Te(d),Zi);return()=>{u=!0,clearTimeout(m)}},[t,n,r,s,e,o])},sp=(e,t)=>{const{announcementsEnabled:n}=it(),{channelSource:r}=Ae(),{isWindowNameReady:s}=Un(),o=ra(),i=r.channel!=null||r.error!=null;ya(e,{enabled:n,ready:i,nameReady:s,targetSelector:t==="messageInput"?uf:void 0,suppressed:o})},op=()=>{var s;const{_statsEnabled:e,channelSource:t}=Ae(),n=(s=t.channel)==null?void 0:s.url,r=l.useCallback(o=>{const i=()=>{o(Sr()?"backgrounded":"foregrounded")};return document.addEventListener("visibilitychange",i),()=>document.removeEventListener("visibilitychange",i)},[]);Ch({channelUrl:n,enabled:e,isInitiallyBackgrounded:Sr,isForegrounded:ff,subscribeToForegroundState:r})},ip=e=>Ye(e)||Zt(e);function ap(e,t){return e.filter(n=>ke.isWelcomeMessage(n,t))}const Aa=(e,{previewWelcomeMessages:t,aiAgentUserId:n})=>e.filter(r=>t.length>0?!ke.isWelcomeMessage(r,n):!0),cp=[],Ta=()=>{var p,v,E,_,A,y;const{agentPreviewConfigs:e={},aiAgentId:t}=ue(),{aiAgentInfo:n,userSession:r}=Ne(),{channelSource:s,messageSource:o,state:{input:i,streamAnimation:c}}=Ae(),u=e.welcomeMessages??cp,d=l.useMemo(()=>Aa(o.messages,{previewWelcomeMessages:u,aiAgentUserId:t}),[t,o.messages,u]),m=ot(s.channel),h=(v=(p=mi(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:De(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}},lp=(e={})=>{const{announceScreenEntry:t,announcementsEnabled:n}=it(),{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=>we.isAdmin(f)&&we.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])},up=()=>{const e=Ta();lp(e)},Ia=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}),Co=(e,t,n=ct.format)=>{const r=Gi(e,Ia(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}},dp={senderName:!0,body:!0,time:!0},mp=Object.keys(dp),hp=(e,t)=>mp.every(n=>e[n]===t[n]),bo=2e3,vo=400,xr=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]},xa=e=>{if(!we.isAdmin(e)||!we.isCSAT(e))return null;const t=Qh(e);return t?`csat:${t}`:null},fp=e=>{const t=new Set;for(const n of e){const r=xa(n);r&&t.add(r)}return t},gp=(e,t)=>{for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r&&xr(r).some(s=>t.includes(s)))return r}},ar=(e,t)=>e.some(n=>t.includes(n)),So=()=>typeof document>"u"?null:document.activeElement instanceof HTMLElement?document.activeElement:null,cr=e=>new Map(e.map(({key:t,sendingStatus:n})=>[t,n])),pp=()=>{const{announceStatus:e,announcementsEnabled:t}=it(),{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}=Ta(),{outgoingMessageStates:p,outgoingMessageStatusSignature:v}=l.useMemo(()=>{if(!g)return{outgoingMessageStates:[],outgoingMessageStatusSignature:""};const Y=o.flatMap(W=>{const K=Zh(W,g);return!K||!("sendingStatus"in W)?[]:[{key:K,sendingStatus:W.sendingStatus}]});return{outgoingMessageStates:Y,outgoingMessageStatusSignature:Y.map(({key:W,sendingStatus:K})=>`${W}:${K}`).join(",")}},[g,o]),E=l.useRef({isClosed:!1,isHandedOff:!1,inputDisabled:m,inputDisabledBy:h,outgoingMessageStatuses:cr(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),L=l.useRef(new Set),N=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",G=()=>{y.current!=null&&(clearTimeout(y.current),y.current=null)},D=(Y,W,K)=>{const V=K==null?void 0:K.replaceableForMs;if(Y.length===0||!V)return;const w=Date.now();T.current=[...T.current.filter(({replaceableUntil:oe})=>oe>w),{eventKeys:Y,parts:W,replaceableUntil:w+V}]},Q=()=>A.current.length>0,ne=()=>{A.current=[]},B=()=>{const[Y,...W]=A.current;if(!Y)return!1;A.current=W;const{eventKeys:K,parts:V,dedupeKey:w}=Y,oe=Re=>{D(K,Re,{replaceableForMs:K.length>0?bo:void 0}),e({event:"newMessage",...Re},w?{dedupeKey:w}:void 0)};if(K.length===0)return oe(V),!0;const Se=_.current,xe=gp(Se.messages,K);if(xe){const Re=Co(xe,Se.stringSet,Se.format);return oe(Re),!0}return oe(V),!0},H=()=>{for(G();B(););},q=(Y=bo)=>{G(),y.current=setTimeout(()=>{if(y.current=null,R())return;const W=So(),[K]=A.current;if(!K)return;if(K.focusTarget!==W){A.current=[{...K,focusTarget:W},...A.current.slice(1)],q(vo);return}B()&&Q()&&q(vo)},Y)},Z=(Y,W,K)=>{const V={eventKeys:W,parts:Y,focusTarget:So(),dedupeKey:K?K.dedupeKey??void 0:W[0]},w=W.length===0?-1:A.current.findIndex(({eventKeys:oe})=>ar(oe,W));w>=0?A.current=A.current.map((oe,Se)=>Se===w?{...V,dedupeKey:K?V.dedupeKey:oe.dedupeKey}:oe):A.current=[...A.current,V],q()},z=(Y,W,K)=>{if(Y!=="messagesUpdated"||W.length===0)return!1;const V=Date.now(),w=T.current.find(oe=>oe.replaceableUntil>V&&ar(oe.eventKeys,W));return w?!hp(K,w.parts):!1};l.useEffect(()=>{const Y=k.current!==s;(!t||!d||Y)&&(N.current=!1,L.current.clear(),ne(),T.current=[],I.current.clear(),G(),Y&&(k.current=s),!t||!d)||N.current||(N.current=!0,k.current=s,E.current={isClosed:i,isHandedOff:c,inputDisabled:m,inputDisabledBy:h,outgoingMessageStatuses:cr(p)},I.current=new Set(o.flatMap(W=>{if(!ke.isStreaming(W))return[];const K="sender"in W?W.sender:void 0;return(K==null?void 0:K.userId)===_.current.currentUserId?[]:xr(W)})),L.current=fp(o))},[e,t,s,d,m,i,c,v]),l.useEffect(()=>{const Y=(W,K)=>{const V=_.current,w=xr(W),oe=xa(W);if(oe!=null){if(L.current.has(oe))return;L.current.add(oe),e({event:"csatDisplayed"});return}if(ke.isStreaming(W)){w.forEach(P=>{I.current.add(P)});return}const Se=w.filter(P=>I.current.has(P)),xe=K==="messagesUpdated"&&Se.length>0;xe&&Se.forEach(P=>{I.current.delete(P)});const Re=K==="messagesUpdated"&&A.current.some(({eventKeys:P})=>ar(P,w)),$=Co(W,V.stringSet,V.format),M=z(K,w,$);if(!xe&&K!=="messagesAdded"&&!Re&&!M)return;const x=M?{dedupeKey:null}:void 0;if(xe||R()||Re){Z($,[...new Set([...Se,...w])],x);return}if(M){Z($,w,x);return}Q()&&H();const O=w[0];e({event:"newMessage",...$},O?{dedupeKey:O}:void 0)};return Ii.subscribe(W=>{if(!N.current||W.channelUrl!==s||W.kind==="initialized"||W.kind==="messagesDeleted"||!ef(W.source))return;const K=_.current.currentUserId;for(const V of W.messages)V&&Jh(V,K)&&Y(V,W.kind)})},[e,s]),l.useEffect(()=>{N.current&&(R()||Q()&&q())},[h,f]),l.useEffect(()=>()=>{G()},[]),l.useEffect(()=>{if(!N.current)return;const Y=E.current,W=Y.outgoingMessageStatuses;Y.outgoingMessageStatuses=cr(p),p.some(({key:V,sendingStatus:w})=>{const oe=W.get(V);return oe!==void 0&&oe!=="failed"&&w==="failed"})&&e({event:"sendFailed"})},[e,v]),l.useEffect(()=>{if(!N.current)return;const Y=E.current;i&&!Y.isClosed&&e({event:"conversationClosed"}),Y.isClosed=i},[e,i]),l.useEffect(()=>{if(!N.current)return;const Y=E.current;c&&!Y.isHandedOff&&e({event:"agentConnected",agentName:u}),Y.isHandedOff=c},[u,e,c]),l.useEffect(()=>{if(!N.current)return;const Y=E.current;m&&h!=="ai_responding"&&(!Y.inputDisabled||Y.inputDisabledBy==="ai_responding")&&e({event:"inputDisabled"}),Y.inputDisabled=m,Y.inputDisabledBy=h},[e,m,h])},_p=()=>{const{channelSource:e}=Ae(),t=Oi(e.channel);return!(t!=null&&t.user.userId)||!t.user.nickname?null:{userId:t.user.userId,nickname:t.user.nickname}},Ep=e=>{const{announceStatus:t,announcementsEnabled:n}=it();nh(e??null,r=>{t({event:"typing",agentName:r})},1e4,n)},Cp=()=>{const e=_p();Ep(e)},ee=({type:e,size:t=24,className:n,color:r})=>{const{icons:s}=Kf(),o=s[e];return a.createElement(bp,{className:n},a.createElement(o,{size:t,color:r??b.color.primary.main,flipInRtl:Uf.has(e)}))},bp=C.default.span.attrs({"aria-hidden":"true"})`
|
|
90
|
+
`;return n.set(e,o),o},Eg=e=>e?U.css`display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:${e};overflow:hidden;`:"",Cg=C.default.span`font-stretch:normal;letter-spacing:normal;${({$variant:e,theme:t})=>_g(e,t.typography)}color:${({$color:e})=>e};${({$maxTextLines:e})=>Eg(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"]',bg=(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},vg=(e,t)=>Array.from(e.ownerDocument.querySelectorAll(Mr)).some(n=>n!==e&&!t.has(n)&&!n.contains(e)&&wt(n)),Sg=e=>{const t=pa(e)??e;t===e&&_a(e),t.focus()},_a=e=>{e.hasAttribute("tabindex")||e.setAttribute("tabindex","-1")},yg=(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,_f),n.style.cssText=["position: fixed","width: 1px","height: 1px","opacity: 0","overflow: hidden","pointer-events: none"].join(";"),n.addEventListener("focus",()=>yg(e,t)),n},Ag=(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=bg(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)||vg(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,Sg(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=>Ag(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),Of(n,o?r:me),n?kc.createPortal(a.createElement(Tg,{onClick:o?r:void 0,style:e},a.createElement(Ig,{ref:d,role:"dialog","aria-modal":"true","aria-label":i,"aria-labelledby":c,"aria-describedby":u,onClick:h=>h.stopPropagation()},s)),m(t)):null},Tg=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};`,Ig=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};`,xg=({id:e,children:t})=>a.createElement(Rg,{id:e},t),Rg=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},Mg=()=>{const e=`${l.useId()}-`;return(t,n)=>{if(!t)return{props:{},node:null};const r=e+n,s=l.createElement(xg,{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},wg=e=>t=>{t.repeat||(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())},Gt=({onActivate:e})=>({role:"button",tabIndex:0,onClick:e,onKeyDown:wg(e)}),kg=({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:kg({disabled:t,currentIndex:n,totalCount:r,onNavigate:o}),tabIndex:i}},ae=()=>{const{stringSet:e}=ie(),t=Mg(),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=ff({intent:df({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,...bf},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=Zh({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}}}}},Lg=({title:e,description:t,highlightedText:n})=>{const r=Th(t,n);return a.createElement(Ng,null,a.createElement(Dg,null,a.createElement(B,{as:"div",variant:"h1",color:b.themedColor.textHighEmphasis},e),t&&a.createElement($g,null,a.createElement(B,{as:"div",variant:"body3",color:b.themedColor.textMidEmphasis},r.beforeText,r.highlightedText?a.createElement(Pg,null,r.highlightedText):null,r.afterText))))},Og=()=>{const{components:e}=Hn.useContext(),{stringSet:t}=ie(),{messenger:n}=ae(),r=yh(),s=r.showDescription?Ah(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:Og,components:{Dialog:Lg}}),Ng=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};`,Dg=C.default.div`display:flex;flex-direction:column;`,$g=C.default.div`margin-top:16px;`,Pg=C.default.strong`font-weight:700;`,Fg=({url:e})=>cs(e),{Provider:Ug,Consumer:Ea,useContext:ue}=be("Messenger");function Bg({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]);Nf(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||gg(_,_.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)??Fg}},[o.handlers]);return a.createElement(Md,{...o},E=>a.createElement(Ug,{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),Hg=/Android/.test(navigator.userAgent),tn=e=>Ca||Hg;let Ut=null,ar=null;const Gg=(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(zg,null,a.createElement(Vg,null,t&&a.createElement("div",{id:d},a.createElement(B,{variant:"h1",color:b.themedColor.textHighEmphasis},t)),n&&a.createElement(Kg,{id:m},a.createElement(B,{variant:"body3",color:b.themedColor.textMidEmphasis},n))),a.createElement(qg,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)))))},zg=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};`,Vg=C.default.div`margin-bottom:16px;`,Kg=C.default.div`margin-top:16px;`,qg=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:Wg,useContext:Oe}=be("MessengerSession"),Yg=l.forwardRef(function({children:e,...t},n){return a.createElement(hm,{ref:n,...t},r=>a.createElement(jg,{...r},e))}),jg=({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),Xg({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(Wg,{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 Xg({sound:e}){Gg("🔔You have received a new message"),e&&ba()}const Ln=`@${Ue}-focused-channel`,Sa=`${Date.now()}-${Math.random().toString(36).slice(2)}`,Zg=()=>{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{}},Jg=(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()||Zg()===e}),Qg=e=>{const{config:t,chatSDK:n}=ue(),{sdkUser:r}=Oe(),s=t.conversation.messageAlertSoundEnabled,{isChannelViewedInAnyTab:o}=Jg(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 ep(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 tp(e){if("file"in e&&e.file instanceof File&&e.file.type.startsWith("image/")){const{width:t,height:n}=await ep(e.file);return new Le.MessageMetaArray({key:ai,value:[t,n]})}}const np=({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 tp(s),i={...s,metaArrays:o?[o]:void 0},c=rp(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}}))}}},rp=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:sp,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 op({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(sp,{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:ip,Context:ap,useContext:Ae}=be("Conversation"),cp=({children:e})=>{var s;const{channelSource:t}=Ae(),n=(s=t.channel)==null?void 0:s.url,{checkForUserActionRequired:r}=oh(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)},lp=({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);Qg(h);const{onBeforeSendMessage:f,onAfterSendMessage:g}=np({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(Um,{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(ip,{value:{...A,scrollSource:m,goToActiveConversation:_,onNavigateToConversationList:n}},a.createElement(cp,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(op,{scrollMode:s,messageStackDirection:o},a.createElement(lp,{...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)},up=({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}),dp=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(dp,{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}},mp=(e,t)=>{const r=(t?jt(e,t):null)??pg(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,mp(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])},hp=(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"?Cf:void 0,suppressed:o})},fp=()=>{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)},[]);Rh({channelUrl:n,enabled:e,isInitiallyBackgrounded:Ir,isForegrounded:yf,subscribeToForegroundState:r})},gp=e=>Ke(e)||Zt(e);function pp(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),_p=[],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??_p,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}},Ep=(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])},Cp=()=>{const e=wa();Ep(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}},bp={senderName:!0,body:!0,time:!0},vp=Object.keys(bp),Sp=(e,t)=>vp.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=lf(e);return t?`csat:${t}`:null},yp=e=>{const t=new Set;for(const n of e){const r=La(n);r&&t.add(r)}return t},Ap=(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])),Tp=()=>{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=af(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=Ap(_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?!Sp(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=yp(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"||!uf(W.source))return;const Y=_.current.currentUserId;for(const V of W.messages)V&&cf(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])},Ip=()=>{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}},xp=e=>{const{announceStatus:t,announcementsEnabled:n}=ct();dh(e??null,r=>{t({event:"typing",agentName:r})},1e4,n)},Rp=()=>{const e=Ip();xp(e)},ee=({type:e,size:t=24,className:n,color:r})=>{const{icons:s}=tg(),o=s[e];return a.createElement(Mp,{className:n},a.createElement(o,{size:t,color:r??b.color.primary.main,flipInRtl:Yf.has(e)}))},Mp=C.default.span.attrs({"aria-hidden":"true"})`
|
|
91
91
|
display: inline-flex;
|
|
92
92
|
&:focus {
|
|
93
93
|
outline: none;
|
|
94
94
|
}
|
|
95
|
-
`,vp=({visible:e,onClose:t,children:n,"aria-label":r})=>a.createElement(mt,{portalContainerId:ve.WINDOW,visible:e,onClose:t,"aria-label":r},a.createElement(Tp,null,n)),Sp=({onClick:e,destructive:t,icon:n,initialFocus:r,children:s})=>a.createElement(yp,{onClick:e,$destructive:t,"data-sb-initial-focus":r?"true":void 0},n&&a.createElement(Ap,null,a.createElement(ee,{type:n,size:24,color:b.themedColor.primary})),s),lt=Object.assign(vp,{ActionItem:Sp}),yp=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};${Ie}`,Ap=C.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,Tp=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};`,yo=40,Ao=.9,Ip="[data-message-listitem]",xp='input, textarea, select, [role="textbox"], [contenteditable="true"]',Rp=({event:e,list:t,isMessageAnchor:n})=>{switch(e.key){case"PageDown":return t.clientHeight*Ao;case"PageUp":return t.clientHeight*-Ao;case"ArrowDown":return n?yo:void 0;case"ArrowUp":return n?yo*-1:void 0;default:return}},Mp=({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(xp))return;const o=s===r||s.matches(Ip),i=Rp({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]),wp="[data-message-listitem]",kp=e=>Math.min(Math.max(0,e),1),Lp=e=>{const n=e.getRootNode().activeElement,r=n==null?void 0:n.closest(wp),s=n===e||n===r;return!n||!e.contains(n)?null:s?e:n},Op=({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})},Np=({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,Op({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*kp(n);if(A.scrollTop<=y){c.current=!0,u.current="top",h.current=Lp(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}},Dp=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:_=de,depsForResetScrollPositionToBottom:A,stackDirection:y="top",bottomSpacerHeight:T=0,"aria-label":I}=t,L=l.useRef(null),N=l.useCallback(D=>{L.current=D,n&&(typeof n=="function"?n(D):n.current=D)},[n]),{handleScroll:k,syncScrollPosition:R}=Np({depsForResetScrollPositionToBottom:A,listRef:L,loadThreshold:E,messagesLength:r.length,onLoadNext:v,onLoadPrev:p,onScroll:_}),G=Mp({listRef:L,syncScrollPosition:R});return c?a.createElement(a.Fragment,null,u):o?a.createElement(a.Fragment,null,i):a.createElement($p,{id:"infinite-list-container"},a.createElement(Pp,{id:"infinite-list-inner",ref:N,onScroll:k,onKeyDown:G,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(Fp,{id:"infinite-list-overlay-container"},a.createElement(Up,{id:"infinite-list-overlay"},g)))}),$p=C.default.div`display:flex;position:relative;flex:1;overflow:hidden;`,Pp=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;}`,Fp=C.default.div`position:absolute;top:0;bottom:0;left:0;right:0;pointer-events:none;`,Up=C.default.div`pointer-events:auto;`,tt=({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(Bp,{as:e,disabled:s,...i},a.createElement(ee,{type:t,size:n,color:r??c}),o)},Bp=C.default.button`all:unset;padding:4px;cursor:pointer;display:flex;align-items:center;justify-content:center;${Ie}&:disabled{cursor:not-allowed;}`,pt=({className:e,children:t,size:n=26})=>a.createElement(Hp,{className:e,$size:n},t??a.createElement(ee,{type:"spinner",size:n})),Hp=C.default.div`display:flex;align-items:center;justify-content:center;width:${({$size:e})=>je(e)};height:${({$size:e})=>je(e)};animation:1s infinite linear;animation-name:rotate;@keyframes rotate{from{transform:rotate(0);}to{transform:rotate(360deg);}}`,Gp=({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=Ye(v),_=Zt(v),A=!ip(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=L=>{L.key==="ArrowLeft"?y():L.key==="ArrowRight"&&T()};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[r,y,T]),!r||!f?null:a.createElement(mt,{onClose:n,visible:r,portalContainerId:ve.MODAL_ROOT,"aria-label":(f==null?void 0:f.name)||u.IMAGE_VIEWER__DEFAULT_TITLE},a.createElement(zp,null,a.createElement(Vp,null,a.createElement(qp,null,a.createElement(Kp,null,a.createElement(U,{variant:"button",maxTextLines:1,color:b.color.ondark.textHighEmphasis},f.name||u.IMAGE_VIEWER__DEFAULT_TITLE),f.timestamp&&a.createElement(U,{variant:"caption2",color:b.color.ondark.textHighEmphasis},d(new Date(f.timestamp),"h:mm a")))),a.createElement(Yp,{type:"close",size:18,color:b.color.ondark.textHighEmphasis,"aria-label":u.A11Y_IMAGE_VIEWER_CLOSE,onClick:n})),a.createElement(Wp,null,p&&a.createElement(To,{$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(jp,{onClick:I=>I.currentTarget===I.target&&n()},E&&a.createElement(a.Fragment,null,!i&&a.createElement(Xp,null,a.createElement(pt,{size:32},a.createElement(ee,{type:"spinner",color:"textLowEmphasis",size:32}))),a.createElement(Zp,{src:f.url,alt:f.name||"Image",$loaded:i,onLoad:()=>c(!0)})),_&&a.createElement(Jp,{controls:!0},a.createElement("source",{src:f.url,type:v})),A&&a.createElement(Qp,null,a.createElement(U,{variant:"h1",color:b.themedColor.textHighEmphasis},u.FILE_VIEWER__UNSUPPORT))),p&&a.createElement(To,{$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(e_,null,p&&a.createElement(U,{variant:"body2",color:b.color.ondark.textHighEmphasis},s+1,"/",h),g&&!A&&a.createElement(t_,{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};`,Vp=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;`,Kp=C.default.div`display:flex;flex-direction:column;gap:2px;`,Yp=C.default(tt)`flex-shrink:0;width:28px;height:28px;border-radius:50%;`,Bn=C.default.div`display:flex;align-items:center;justify-content:center;`,Wp=C.default(Bn)`flex:1;min-height:0;position:relative;`,jp=C.default(Bn)`position:relative;width:100%;height:100%;min-width:0;min-height:0;`,Xp=C.default(Bn)`position:absolute;inset:0;pointer-events:none;`,Zp=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;`,Jp=C.default.video`max-width:100%;max-height:100%;object-fit:contain;`,Qp=C.default(Bn)`flex-direction:column;gap:16px;`,To=C.default(tt)`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;}`,e_=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};`,t_=C.default(tt)`position:absolute;right:16px;top:50%;transform:translateY(-50%);padding:0;width:24px;height:24px;`,n_=.75,Ra=6,r_=Ra*2;let Rr=null;typeof Intl<"u"&&"Segmenter"in Intl&&(Rr=new Intl.Segmenter(void 0,{granularity:"grapheme"}));const s_=e=>Rr?Array.from(Rr.segment(e),t=>t.segment):[...e],o_=e=>{const t=Math.floor(e.length*n_),n=Math.max(0,e.length-Ra);return Math.max(t,n)},Io=(e,t="")=>{if(e.length<r_)return{start:e+t,end:""};const n=s_(e),r=o_(n);return{start:n.slice(0,r).join(""),end:n.slice(r).join("")+t}},i_=e=>{const t=e.normalize("NFC").trim(),n=t.lastIndexOf(".");if(!(n>0&&n<t.length-1))return Io(t);const s=t.slice(0,n),o=t.slice(n);return Io(s,o)},Ma=({children:e,...t})=>{const{start:n,end:r}=l.useMemo(()=>i_(e),[e]);return r?a.createElement(a_,null,a.createElement(c_,{...t},n),a.createElement(l_,{...t},r)):a.createElement(U,{...t},n)},a_=C.default.span`display:flex;width:100%;min-width:0;overflow:hidden;direction:inherit;`,c_=C.default(U)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex-shrink:1;min-width:0;`,l_=C.default(U)`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}=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(u_,{...d.props,$clickable:!!o},a.createElement(m_,{$bgColor:s??c.base.primary},a.createElement(ee,{type:"file-document",size:24,color:r??c.base.primaryContrastContent})),a.createElement(h_,null,a.createElement(Ma,{variant:"button",color:b.themedColor.textHighEmphasis},e),a.createElement(U,{color:b.themedColor.textMidEmphasis,variant:"caption3"},n)),d.descriptionNode)},u_=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&&d_}`,d_=F.css`cursor:pointer;${Ie}&:hover{background-color:${b.themedColor.bg_100_500};}`,m_=C.default.div`border-radius:8px;width:40px;height:40px;display:flex;align-items:center;justify-content:center;background-color:${({$bgColor:e})=>e};`,h_=C.default.div`display:flex;flex:1;flex-direction:column;gap:4px;min-width:0;`;function f_({file:e,children:t,onClickFile:n}){const r=n?()=>n(e):void 0;return a.createElement(g_,null,a.createElement(cs,{name:e.name,mimeType:e.type,type:Dr(e.name,e.type),onClick:r}),t)}const g_=C.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${se.GAP_GROUPED}px;`,nt=`${Ue}-incoming-msg`,wa=`${Ue}-marked-text`;function p_({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(C_,{src:e.url,alt:"image-message"}):e.type.startsWith("video")?a.createElement(b_,{controls:!0},a.createElement("source",{src:e.url}),a.createElement("track",{kind:"captions"})):null;if(u){const d={id:`${nt}-media-body`,...c.props};return a.createElement(__,null,a.createElement(E_,{...d},u(),c.descriptionNode),r)}return null}const __=C.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${se.GAP_GROUPED}px;`,E_=C.default.div`width:${se.BODY_MAX_WIDTH}px;height:160px;border-radius:12px;overflow:hidden;cursor:pointer;${te.light`
|
|
95
|
+
`,wp=({visible:e,onClose:t,children:n,"aria-label":r})=>a.createElement(gt,{portalContainerId:Se.WINDOW,visible:e,onClose:t,"aria-label":r},a.createElement(Np,null,n)),kp=({onClick:e,destructive:t,icon:n,initialFocus:r,children:s})=>a.createElement(Lp,{onClick:e,$destructive:t,"data-sb-initial-focus":r?"true":void 0},n&&a.createElement(Op,null,a.createElement(ee,{type:n,size:24,color:b.themedColor.primary})),s),dt=Object.assign(wp,{ActionItem:kp}),Lp=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}`,Op=C.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,Np=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,Dp="[data-message-listitem]",$p='input, textarea, select, [role="textbox"], [contenteditable="true"]',Pp=({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}},Fp=({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($p))return;const o=s===r||s.matches(Dp),i=Pp({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]),Up="[data-message-listitem]",Bp=e=>Math.min(Math.max(0,e),1),Hp=e=>{const n=e.getRootNode().activeElement,r=n==null?void 0:n.closest(Up),s=n===e||n===r;return!n||!e.contains(n)?null:s?e:n},Gp=({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})},zp=({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,Gp({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*Bp(n);if(A.scrollTop<=y){c.current=!0,u.current="top",h.current=Hp(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}},Vp=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}=zp({depsForResetScrollPositionToBottom:A,listRef:N,loadThreshold:E,messagesLength:r.length,onLoadNext:v,onLoadPrev:p,onScroll:_}),F=Fp({listRef:N,syncScrollPosition:R});return c?a.createElement(a.Fragment,null,u):o?a.createElement(a.Fragment,null,i):a.createElement(Kp,{id:"infinite-list-container"},a.createElement(qp,{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(Wp,{id:"infinite-list-overlay-container"},a.createElement(Yp,{id:"infinite-list-overlay"},g)))}),Kp=C.default.div`display:flex;position:relative;flex:1;overflow:hidden;`,qp=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;}`,Wp=C.default.div`position:absolute;top:0;bottom:0;left:0;right:0;pointer-events:none;`,Yp=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(jp,{as:e,disabled:s,...i},a.createElement(ee,{type:t,size:n,color:r??c}),o)},jp=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(Xp,{className:e,$size:n},t??a.createElement(ee,{type:"spinner",size:n})),Xp=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);}}`,Zp=({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=!gp(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(Jp,null,a.createElement(Qp,null,a.createElement(e_,null,a.createElement(t_,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(n_,{type:"close",size:18,color:b.color.ondark.textHighEmphasis,"aria-label":u.A11Y_IMAGE_VIEWER_CLOSE,onClick:n})),a.createElement(r_,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(s_,{onClick:I=>I.currentTarget===I.target&&n()},E&&a.createElement(a.Fragment,null,!i&&a.createElement(o_,null,a.createElement(Ct,{size:32},a.createElement(ee,{type:"spinner",color:"textLowEmphasis",size:32}))),a.createElement(i_,{src:f.url,alt:f.name||"Image",$loaded:i,onLoad:()=>c(!0)})),_&&a.createElement(a_,{controls:!0},a.createElement("source",{src:f.url,type:v})),A&&a.createElement(c_,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(l_,null,p&&a.createElement(B,{variant:"body2",color:b.color.ondark.textHighEmphasis},s+1,"/",h),g&&!A&&a.createElement(u_,{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}))))},Jp=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};`,Qp=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};`,e_=C.default.div`flex:1;min-width:0;padding-right:8px;`,t_=C.default.div`display:flex;flex-direction:column;gap:2px;`,n_=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;`,r_=C.default(zn)`flex:1;min-height:0;position:relative;`,s_=C.default(zn)`position:relative;width:100%;height:100%;min-width:0;min-height:0;`,o_=C.default(zn)`position:absolute;inset:0;pointer-events:none;`,i_=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;`,a_=C.default.video`max-width:100%;max-height:100%;object-fit:contain;`,c_=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;}`,l_=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};`,u_=C.default(nt)`position:absolute;right:16px;top:50%;transform:translateY(-50%);padding:0;width:24px;height:24px;`,d_=.75,Oa=6,m_=Oa*2;let Lr=null;typeof Intl<"u"&&"Segmenter"in Intl&&(Lr=new Intl.Segmenter(void 0,{granularity:"grapheme"}));const h_=e=>Lr?Array.from(Lr.segment(e),t=>t.segment):[...e],f_=e=>{const t=Math.floor(e.length*d_),n=Math.max(0,e.length-Oa);return Math.max(t,n)},Mo=(e,t="")=>{if(e.length<m_)return{start:e+t,end:""};const n=h_(e),r=f_(n);return{start:n.slice(0,r).join(""),end:n.slice(r).join("")+t}},g_=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(()=>g_(e),[e]);return r?a.createElement(p_,null,a.createElement(__,{...t},n),a.createElement(E_,{...t},r)):a.createElement(B,{...t},n)},p_=C.default.span`display:flex;width:100%;min-width:0;overflow:hidden;direction:inherit;`,__=C.default(B)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex-shrink:1;min-width:0;`,E_=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(C_,{...d.props,$clickable:!!o},a.createElement(v_,{$bgColor:s??c.base.primary},a.createElement(ee,{type:"file-document",size:24,color:r??c.base.primaryContrastContent})),a.createElement(S_,null,a.createElement(Na,{variant:"button",color:b.themedColor.textHighEmphasis},e),a.createElement(B,{color:b.themedColor.textMidEmphasis,variant:"caption3"},n)),d.descriptionNode)},C_=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&&b_}`,b_=U.css`cursor:pointer;${xe}&:hover{background-color:${b.themedColor.bg_100_500};}`,v_=C.default.div`border-radius:8px;width:40px;height:40px;display:flex;align-items:center;justify-content:center;background-color:${({$bgColor:e})=>e};`,S_=C.default.div`display:flex;flex:1;flex-direction:column;gap:4px;min-width:0;`;function y_({file:e,children:t,onClickFile:n}){const r=n?()=>n(e):void 0;return a.createElement(A_,null,a.createElement(ds,{name:e.name,mimeType:e.type,type:Ur(e.name,e.type),onClick:r}),t)}const A_=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`,T_="masked-text";function I_({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(M_,{src:e.url,alt:"image-message"}):e.type.startsWith("video")?a.createElement(w_,{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(x_,null,a.createElement(R_,{...d},u(),c.descriptionNode),r)}return null}const x_=C.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${se.GAP_GROUPED}px;`,R_=C.default.div`width:${se.BODY_MAX_WIDTH}px;height:160px;border-radius:12px;overflow:hidden;cursor:pointer;${ne.light`
|
|
96
96
|
background-color: ${b.color.background100};
|
|
97
97
|
`}
|
|
98
|
-
${
|
|
98
|
+
${ne.dark`
|
|
99
99
|
background-color: ${b.color.background400};
|
|
100
100
|
`}
|
|
101
|
-
`,
|
|
101
|
+
`,M_=C.default.img`width:100%;height:100%;object-fit:cover;`,w_=C.default.video`width:100%;height:100%;object-fit:cover;`,Da=({images:e,isPending:t=!1,onClickImage:n})=>{const{conversation:r}=ae(),s=e.length;if(s===0)return null;const o=Id(s),i=!!n&&!t;return a.createElement(L_,{$width:se.BODY_MAX_WIDTH,$columns:o},e.map((c,u)=>{const{columnSpan:d}=xd({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(O_,{key:c.url,$clickable:i,$itemSpan:d,$isPending:t,...g.props},a.createElement(k_,{src:c.url,alt:c.name||""}),t&&a.createElement(N_,null),g.descriptionNode)}))},k_=({src:e,alt:t})=>{const[n,r]=l.useState(!1),[s,o]=l.useState(!1);return a.createElement(a.Fragment,null,!n&&!s&&a.createElement(D_,null,a.createElement(Ct,{size:20},a.createElement(ee,{type:"spinner",color:"textLowEmphasis",size:20}))),s&&a.createElement($_,null,a.createElement(ee,{type:"photo",color:"textLowEmphasis",size:24})),!s&&a.createElement(P_,{src:e,alt:t,$loaded:n,onLoad:()=>r(!0),onError:()=>o(!0)}))},L_=C.default.div`display:grid;grid-template-columns:repeat(${({$columns:e})=>e},1fr);width:${({$width:e})=>e}px;gap:2px;border-radius:16px;overflow:hidden;`,O_=C.default.div`position:relative;width:100%;aspect-ratio:1;overflow:hidden;cursor:${e=>e.$clickable?"pointer":"default"};${ne.light`
|
|
102
102
|
background-color: ${b.color.background100};
|
|
103
103
|
`}
|
|
104
|
-
${
|
|
104
|
+
${ne.dark`
|
|
105
105
|
background-color: ${b.color.background400};
|
|
106
106
|
`}
|
|
107
107
|
${e=>e.$itemSpan&&e.$itemSpan>1&&`
|
|
@@ -121,19 +121,19 @@ $2
|
|
|
121
121
|
}
|
|
122
122
|
`}
|
|
123
123
|
}
|
|
124
|
-
`,
|
|
124
|
+
`,N_=C.default.div`position:absolute;top:0;left:0;width:100%;height:100%;background-color:${b.color.overlay.dark};pointer-events:none;`,$a=C.default.div`display:flex;align-items:center;justify-content:center;`,D_=C.default($a)`position:absolute;inset:0;`,$_=C.default($a)`position:absolute;inset:0;${ne.light`
|
|
125
125
|
background-color: ${b.color.background200};
|
|
126
126
|
`}
|
|
127
|
-
${
|
|
127
|
+
${ne.dark`
|
|
128
128
|
background-color: ${b.color.background500};
|
|
129
129
|
`}
|
|
130
|
-
`,
|
|
130
|
+
`,P_=C.default.img`position:absolute;inset:0;width:100%;height:100%;object-fit:cover;opacity:${({$loaded:e})=>e?1:0};transition:opacity 0.3s ease;`,F_=({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(U_,null,a.createElement(Da,{images:e,onClickImage:s}),t)},U_=C.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${se.GAP_GROUPED}px;`,B_=l.lazy(async()=>({default:(await Promise.resolve().then(()=>require("./cjs/TEfZbcKQ.cjs"))).MarkdownText})),ko=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 H_(e){var s,o;const t=e.maxBodyWidth??se.BODY_MAX_WIDTH,n=l.useMemo(()=>jc(e.message),[e.message]),r={id:`${We}-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(Lo,{...r},e.children):null:a.createElement(Lo,{...r},n.map((i,c)=>i.type==="text"?a.createElement(Oo,{key:c,variant:"body3"},a.createElement(Yt,{fallback:i.value},a.createElement(B_,{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"?ko?a.createElement(Yt,{key:c,fallback:a.createElement(Oo,{variant:"body3"},i.value)},a.createElement(ko,{code:i.value,language:i.language})):a.createElement(G_,{key:c},a.createElement("code",null,i.value)):null),e.children)}const Lo=C.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})=>U.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
|
+
`,Oo=C.default(B)`align-items:flex-start;line-height:140%;white-space:pre-wrap;padding:0 12px;`,G_=C.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 Pa({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(z_,{id:e,tabIndex:r?0:void 0,onClick:r,$size:Xe(n),$backgroundColor:c,style:i,...u},t&&t!==d?a.createElement(V_,{src:t,alt:"",onLoad:()=>o==null?void 0:o(t),onError:()=>{m(t),s==null||s(t)}}):a.createElement(ee,{type:"user",size:n}))}const z_=C.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??b.themedColor.bg_100_500};&:focus{outline:none;}${xe}`,V_=C.default.img`object-fit:cover;width:100%;height:100%;position:absolute;`,K_=({sender:e,isBotMessage:t})=>{const n=`${We}-sender-avatar`,[r,s]=l.useState();return t&&(!e.profileUrl||e.profileUrl===r)?a.createElement(q_,{id:n},a.createElement(ee,{type:"delight",size:"100%"})):a.createElement(Pa,{id:n,size:se.AVATAR_SIZE,src:e.profileUrl,onImageError:t?s:void 0})},q_=C.default.div`flex-shrink:0;width:${se.AVATAR_SIZE}px;height:${se.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;}}`,W_=({sender:e})=>a.createElement(Y_,{id:`${We}-sender-name`,variant:"caption1",color:b.themedColor.textMidEmphasis},e.nickname),Y_=C.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;`,j_=({createdAt:e})=>{const{stringSet:t,format:n}=ie();return e?a.createElement(B,{id:`${We}-sent-time`,variant:"caption4",color:b.themedColor.textLowEmphasis},n(e,t.DATE_FORMAT__MESSAGE_TIMESTAMP)):null},Fa="(prefers-reduced-motion: reduce)",X_=()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(Fa).matches,Ua=()=>{const[e,t]=l.useState(X_);return l.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const n=window.matchMedia(Fa);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},Z_=({thinkingMessage:e,customStyle:t})=>{const n=Ua();return e?a.createElement(eE,{$prefersReducedMotion:n},a.createElement(tE,null,e),!n&&a.createElement(nE,null)):a.createElement(J_,{$bgColor:t==null?void 0:t.bubbleBackgroundColor},[0,1,2].map(r=>a.createElement(Q_,{key:r,$color:t==null?void 0:t.bubbleContentColor,$prefersReducedMotion:n})))},J_=C.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};`,Q_=C.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;}`,eE=C.default.div.attrs({id:`${We}-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
|
+
`,tE=C.default(B).attrs({variant:"body3"})`
|
|
149
149
|
white-space: pre-wrap;
|
|
150
150
|
word-break: break-word;
|
|
151
151
|
color: ${b.themedColor.textHighEmphasis};
|
|
152
|
-
`,
|
|
153
|
-
`,
|
|
152
|
+
`,nE=C.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=Ds(e.colors.base.background,.5),n=Ds(e.colors.base.background,0);return`linear-gradient(90deg, ${n} 0%, ${t} 30%, ${t} 60%, ${n} 100%)`}};
|
|
153
|
+
`,rE=({extendedMessagePayload:e,onClickCTA:t=({url:n})=>cs(n)})=>{const n=e==null?void 0:e.cta_button;if(!n)return null;const r=()=>t(n);return a.createElement(sE,{id:`${We}-ext-cta-button`,onClick:r},a.createElement(oE,{variant:"button"},n.label))},sE=C.default.button.attrs({type:"button"})`
|
|
154
154
|
all: unset;
|
|
155
155
|
display: flex;
|
|
156
156
|
width: 100%;
|
|
@@ -162,12 +162,12 @@ $2
|
|
|
162
162
|
padding: 8px;
|
|
163
163
|
color: ${b.themedColor.textHighEmphasis};
|
|
164
164
|
background-color: ${b.color.background50};
|
|
165
|
-
${
|
|
165
|
+
${ne.dark`
|
|
166
166
|
background-color: ${b.color.ondark.textDisabled};
|
|
167
167
|
`}
|
|
168
168
|
|
|
169
|
-
${
|
|
170
|
-
`,
|
|
169
|
+
${xe}
|
|
170
|
+
`,oE=C.default(B)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,iE=e=>a.createElement(a.Fragment,null),aE=({extendedMessagePayload:e,onClickCitation:t=n=>cs(n.link)})=>{const{stringSet:n}=ie(),{theme:r}=Fn(),s=e==null?void 0:e.citations;return!s||s.length===0?null:a.createElement(cE,{id:`${We}-ext-citation`},a.createElement(lE,{variant:"caption1",color:r.colors.messageIncoming.text},n.CITATION_SOURCE_TITLE),a.createElement(uE,null,s.map((o,i)=>a.createElement(mE,{key:`${o.embedding_id}-${i}`,onClick:()=>t(o)},a.createElement(ee,{type:"source",size:16,color:r.colors.messageIncoming.text}),a.createElement(dE,{variant:"body3",color:r.colors.messageIncoming.text},o.title)))))},cE=C.default.div`display:flex;flex-direction:column;gap:8px;border-radius:8px;padding:8px 12px 6px;`,lE=C.default(B)`opacity:0.5;`,uE=C.default.div`display:flex;flex-direction:column;gap:8px;`,dE=C.default(B)`text-decoration:underline;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,mE=C.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
|
+
`,hE=e=>a.createElement(a.Fragment,null),Or=e=>`${e}-filled`,fE=e=>e==="good"?he.AIAgentMessageFeedbackRating.GOOD:he.AIAgentMessageFeedbackRating.BAD,ms=U.css`&:hover{opacity:0.8;}&:active{opacity:0.6;}`,gn={good:{onlight:b.color.secondary.dark,ondark:b.color.secondary.light},bad:{onlight:b.color.error.dark,ondark:b.color.error.light}},gE={good:b.themedColor.secondary,bad:b.themedColor.error},Ba=e=>U.css`color:${gn[e].onlight};border-color:${gn[e].onlight};${ne.dark`
|
|
186
|
+
color: ${gn[e].ondark};
|
|
187
|
+
border-color: ${gn[e].ondark};
|
|
188
188
|
`}
|
|
189
|
-
`,
|
|
189
|
+
`,pE=({visible:e,onClose:t,isEdit:n,initialRating:r,initialComment:s="",onSubmit:o,isCommentEnabled:i=!1})=>{const{stringSet:c}=ie(),{conversation:u}=ae(),{rootElement:d}=ua(),m=mt(d),[h,f]=l.useState(r),[g,p]=l.useState(s),[v,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 O=R=>{const F=R;F.metaKey||F.altKey||F.ctrlKey||(_.current=!0)},k=()=>{_.current=!1,E(!1)};return m.addEventListener("keydown",O),m.addEventListener("pointerdown",k),()=>{m.removeEventListener("keydown",O),m.removeEventListener("pointerdown",k)}},[m,e]);const T=()=>{h&&(o({rating:h,comment:g.trim()||void 0}),t())},I=()=>{t()};if(!e)return null;const N={feedback:y.container()};return a.createElement(gt,{portalContainerId:Se.WINDOW,visible:e,onClose:I,"aria-label":c.FEEDBACK_TITLE},a.createElement(_E,null,a.createElement(EE,null,a.createElement(B,{variant:"h2",color:b.themedColor.textHighEmphasis},c.FEEDBACK_TITLE)),a.createElement(CE,null,a.createElement(bE,{...N.feedback.props},["good","bad"].map(O=>{const k=h===O,R=O==="good"?c.FEEDBACK_GOOD:c.FEEDBACK_BAD,F=y.button(O,k);return a.createElement(l.Fragment,{key:O},a.createElement(vE,{type:"button",$selected:k,$rating:O,...F.props,onClick:()=>f(O),"data-sb-initial-focus":O===A?"true":void 0},a.createElement(ee,{type:k?Or(O):O,size:24,color:"currentColor"}),a.createElement(B,{variant:"caption1",color:"currentColor"},R)),F.descriptionNode)}),N.feedback.descriptionNode),i&&a.createElement(SE,null,a.createElement(B,{variant:"caption3",color:b.themedColor.textHighEmphasis},c.FEEDBACK_COMMENT_LABEL),a.createElement(yE,{placeholder:c.FEEDBACK_COMMENT_PLACEHOLDER,value:g,onChange:O=>p(O.target.value),onFocus:()=>E(_.current),onBlur:()=>E(!1),maxLength:100,$focusVisible:v,"data-focus-visible":v?"true":"false"}))),a.createElement(AE,null,a.createElement(TE,{onClick:I},a.createElement(B,{variant:"button",color:b.themedColor.textHighEmphasis},c.FEEDBACK_CANCEL)),a.createElement(IE,{onClick:T,disabled:!h},a.createElement(B,{variant:"button"},n?c.FEEDBACK_SAVE:c.FEEDBACK_SUBMIT)))))},_E=C.default.div`width:280px;background-color:${({theme:e})=>e.colors.base.modalContentBackground};border-radius:12px;overflow:hidden;`,EE=C.default.div`padding:24px;`,CE=C.default.div`padding-inline:24px;display:flex;flex-direction:column;gap:24px;`,bE=C.default.div`display:flex;gap:4px;`,vE=C.default.button`width:114px;height:64px;border-radius:12px;border:1px solid ${b.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:${b.themedColor.textLowEmphasis};background-color:transparent;${({$selected:e,$rating:t})=>e&&Ba(t)}${ms}`,SE=C.default.label`display:flex;flex-direction:column;gap:6px;`,yE=C.default.textarea`font-family:inherit;font-size:12px;line-height:16px;border:1px solid ${b.themedColor.textDisabled};border-radius:4px;padding:6px 12px;color:${b.themedColor.textHighEmphasis};background-color:${b.themedColor.textLowEmphasisInverse};resize:none;field-sizing:content;min-height:28px;max-height:118px;overflow-y:auto;&::placeholder{color:${b.themedColor.textLowEmphasis};}&:focus{outline:none;}${({$focusVisible:e})=>e&&U.css`
|
|
190
190
|
outline: 2px solid ${b.themedColor.primary};
|
|
191
191
|
outline-offset: 2px;
|
|
192
192
|
`}
|
|
193
|
-
`,
|
|
193
|
+
`,AE=C.default.div`padding-inline:24px;padding-block:16px;display:flex;justify-content:flex-end;gap:4px;`,Ha=C.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;`,TE=C.default(Ha)`background-color:transparent;${ms}`,IE=C.default(Ha)`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};}`,xE=({isBotMessage:e,isConversationClosed:t,isStreaming:n,isFeedbackEnabled:r,isFeedbackCommentEnabled:s,extendedMessagePayload:o,onFeedbackUpdate:i})=>{const{stringSet:c}=ie(),{conversation:u}=ae(),[d,m]=l.useState(!1),[h,f]=l.useState(!1),[g,p]=l.useState(void 0),[v,E]=l.useState(""),_=l.useRef(null),A=l.useRef(null),y=l.useRef(null),T=l.useRef(!1),I=u.feedback,N=o==null?void 0:o.feedback,O=(N==null?void 0:N.rating)??"none";if(O!=="none"?!1:!!(n||!e||!r||(o==null?void 0:o.bot_message_type)!=="generated"||t))return null;const R=K=>{K&&Ie(()=>{const J=K==="good"?_.current:A.current;J==null||J.focus()})},F=({restoreTrigger:K=!0}={})=>{f(!1),K&&R(y.current)},D=K=>{O==="none"?(p(K),E(""),m(!0)):(y.current=K,f(!0))},Q=()=>{i==null||i(null),F()},re=()=>{T.current=!0,F({restoreTrigger:!1}),p(N==null?void 0:N.rating),E((N==null?void 0:N.comment)??""),m(!0)},G=K=>{T.current=!1,i==null||i(K),m(!1),R(y.current)},H=()=>{m(!1),T.current&&(T.current=!1,f(!0))};return t&&O!=="none"?a.createElement(No,{role:"presentation",$horizontal:!0},a.createElement(RE,null,a.createElement(ee,{type:Or(O),size:12,color:gE[O]})),(N==null?void 0:N.comment)&&a.createElement(Do,{variant:"caption2",style:{lineHeight:"16px"}},N.comment)):a.createElement(a.Fragment,null,a.createElement(No,{role:"presentation"},a.createElement(ME,{role:"presentation"},["good","bad"].map(K=>{const J=O===K,q=I.button(K,J);return a.createElement(l.Fragment,{key:K},a.createElement(wE,{$selected:J,$rating:K,ref:K==="good"?_:A,...q.props,onClick:()=>D(K)},a.createElement(ee,{type:J?Or(K):K,size:14,color:"currentColor"})),q.descriptionNode)})),O!=="none"&&(N==null?void 0:N.comment)&&a.createElement(Do,{variant:"caption2"},N.comment)),a.createElement(dt,{visible:h,onClose:F,...I.optionsBottomSheet().props},a.createElement(dt.ActionItem,{onClick:re,initialFocus:!0},c.FEEDBACK_EDIT),a.createElement(dt.ActionItem,{onClick:Q,destructive:!0},c.FEEDBACK_REMOVE)),a.createElement(pE,{visible:d,onClose:H,isEdit:O!=="none",initialRating:g,initialComment:v,onSubmit:G,isCommentEnabled:s}))},No=C.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:${se.BODY_MAX_WIDTH}px;`,RE=C.default.div`padding:2px;flex-shrink:0;display:flex;align-items:center;`,ME=C.default.div`display:flex;gap:2px;`,wE=C.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:${b.themedColor.textMidEmphasis};border:1px solid ${b.color.background200};background-color:transparent;${ne.dark`
|
|
194
194
|
border: 1px solid ${b.color.background400};
|
|
195
195
|
`}
|
|
196
196
|
|
|
197
|
-
${({$selected:e,$rating:t})=>e
|
|
197
|
+
${({$selected:e,$rating:t})=>e&&Ba(t)}
|
|
198
198
|
|
|
199
|
-
${
|
|
200
|
-
`,
|
|
199
|
+
${ms}
|
|
200
|
+
`,Do=C.default(B)`color:${b.themedColor.textMidEmphasis};${ne.dark`
|
|
201
201
|
color: ${b.themedColor.textHighEmphasis};
|
|
202
202
|
`}
|
|
203
|
-
`,
|
|
203
|
+
`,hs=U.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;${xe}&:disabled{cursor:not-allowed;}`,$o=C.default.button`${hs};background-color:${b.themedColor.primary};color:${b.themedColor.textHighEmphasis};&:hover:not(:disabled){opacity:0.9;}`,kE=C.default.button`${hs};color:${b.themedColor.primary};${ne.light`
|
|
204
204
|
background-color: ${b.color.background50};
|
|
205
205
|
`};
|
|
206
|
-
${
|
|
206
|
+
${ne.dark`
|
|
207
207
|
background-color: ${b.color.background700};
|
|
208
208
|
`};
|
|
209
209
|
|
|
210
210
|
&:hover:not(:disabled) {
|
|
211
211
|
opacity: 0.9;
|
|
212
212
|
}
|
|
213
|
-
`,
|
|
213
|
+
`,LE=C.default.button`${hs};background-color:transparent;color:${b.themedColor.textHighEmphasis};&:hover:not(:disabled){opacity:0.7;}`,OE=e=>{switch(e){case"primary":return $o;case"secondary":return kE;case"clear":return LE;default:return $o}},NE=C.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);}}`,DE=({children:e,onClick:t,variant:n="primary",disabled:r=!1,loading:s=!1,className:o,...i})=>{const c=()=>{switch(n){case"primary":return b.themedColor.textHighEmphasisInverse;case"secondary":return b.themedColor.primary;case"clear":return b.themedColor.textHighEmphasis;default:return b.themedColor.textHighEmphasisInverse}},u=OE(n);return a.createElement(u,{onClick:t,disabled:r||s,className:o,...i},s?a.createElement(NE,null,a.createElement(ee,{type:"spinner",size:22,color:c()})):a.createElement(B,{variant:"button",color:c()},e))},$E=({children:e,className:t,style:n,id:r,role:s})=>a.createElement(B,{variant:"caption4",color:b.themedColor.error,className:t,style:n,id:r,role:s},e),PE=({id:e,children:t,className:n,style:r,required:s,"aria-hidden":o})=>{const{stringSet:i}=ie();return a.createElement(B,{id:e,variant:"caption3",color:b.themedColor.textMidEmphasis,className:n,style:r,"aria-hidden":o},t,!s&&a.createElement("span",{style:{color:b.themedColor.textLowEmphasis}},` (${i.OPTIONAL})`))},FE=({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(zE,{type:"text",value:m,onChange:d,placeholder:n,className:o,disabled:i||s,inputMode:"decimal",$error:r,$submitted:s,...u})},UE=U.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;${xe}&::placeholder{color:${b.themedColor.textLowEmphasis};}&::-webkit-inner-spin-button,&::-webkit-outer-spin-button{-webkit-appearance:none;margin:0;}`,BE=U.css`color:${b.themedColor.textHighEmphasis};border:1px solid transparent;cursor:not-allowed;${ne.light`
|
|
214
214
|
background-color: ${b.color.ondark.textMidEmphasis};
|
|
215
215
|
`}
|
|
216
|
-
${
|
|
216
|
+
${ne.dark`
|
|
217
217
|
background-color: ${b.color.onlight.textLowEmphasis};
|
|
218
218
|
`}
|
|
219
219
|
|
|
220
220
|
&::placeholder {
|
|
221
221
|
color: ${b.themedColor.textLowEmphasis};
|
|
222
222
|
}
|
|
223
|
-
`,
|
|
223
|
+
`,HE=U.css`border:1px solid ${b.themedColor.error};color:${b.themedColor.textHighEmphasis};${ne.light`
|
|
224
224
|
background-color: ${b.color.background50};
|
|
225
225
|
`}
|
|
226
|
-
${
|
|
226
|
+
${ne.dark`
|
|
227
227
|
background-color: ${b.color.onlight.textLowEmphasis};
|
|
228
228
|
`}
|
|
229
|
-
`,
|
|
229
|
+
`,GE=U.css`border:1px solid ${b.themedColor.textDisabled};color:${b.themedColor.textHighEmphasis};${ne.light`
|
|
230
230
|
background-color: ${b.color.background50};
|
|
231
231
|
`}
|
|
232
|
-
${
|
|
232
|
+
${ne.dark`
|
|
233
233
|
background-color: ${b.color.onlight.textLowEmphasis};
|
|
234
234
|
`}
|
|
235
235
|
|
|
236
236
|
&:focus {
|
|
237
237
|
border-color: ${b.themedColor.primary};
|
|
238
238
|
}
|
|
239
|
-
`,
|
|
239
|
+
`,zE=C.default.input`${UE}${({$error:e,$submitted:t})=>t?BE:e?HE:GE}`,VE=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))}}}},Ga=e=>{const{options:t,submitted:n=!1,error:r=!1,className:s,groupLabel:o}=e,{conversation:i}=ae(),c=e.multiple===!0,{selectedValues:u,handleOptionClick:d}=VE(e),m=t.some(h=>u.includes(h.value));return a.createElement(qE,{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(QE,{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,v=>{const E=t[v];E&&d(E.value)})).props,disabled:n,onClick:()=>d(h.value)},a.createElement(B,{variant:"caption1",color:KE(g,n)},h.label))}))},KE=(e,t)=>t?e?b.themedColor.textHighEmphasis:b.themedColor.textDisabled:e?b.themedColor.primary:b.themedColor.textMidEmphasis,qE=C.default.div`display:flex;flex-wrap:wrap;gap:4px 2px;`,WE=U.css`display:inline-flex;align-items:center;padding:8px 12px;border-radius:15px;transition:all 0.2s ease;`,YE=U.css`cursor:default;background-color:${b.color.ondark.textMidEmphasis};color:${b.themedColor.textHighEmphasis};${ne.dark`
|
|
240
240
|
background-color: transparent;
|
|
241
241
|
border: 1px solid white;
|
|
242
242
|
color: white;
|
|
243
243
|
`}
|
|
244
|
-
`,
|
|
244
|
+
`,jE=U.css`cursor:default;${ne.light`
|
|
245
245
|
background-color: ${b.color.ondark.textMidEmphasis};
|
|
246
246
|
color: ${b.themedColor.textDisabled};
|
|
247
247
|
`}
|
|
248
|
-
${
|
|
248
|
+
${ne.dark`
|
|
249
249
|
background-color: ${b.color.onlight.textLowEmphasis};
|
|
250
250
|
border: 1px solid ${b.color.onlight.textLowEmphasis};
|
|
251
251
|
color: ${b.themedColor.textDisabled};
|
|
252
252
|
`}
|
|
253
|
-
`,
|
|
253
|
+
`,XE=U.css`cursor:pointer;border:1px solid ${b.themedColor.primary};${ne.light`
|
|
254
254
|
background-color: ${b.color.background50};
|
|
255
255
|
color: ${b.themedColor.primary};
|
|
256
256
|
`}
|
|
257
|
-
${
|
|
257
|
+
${ne.dark`
|
|
258
258
|
background-color: ${b.color.onlight.textLowEmphasis};
|
|
259
259
|
color: ${b.themedColor.primary};
|
|
260
260
|
`}
|
|
261
|
-
`,
|
|
261
|
+
`,ZE=U.css`cursor:pointer;border:1px solid ${b.themedColor.textDisabled};${ne.light`
|
|
262
262
|
background-color: ${b.color.background50};
|
|
263
263
|
color: ${b.themedColor.textMidEmphasis};
|
|
264
264
|
`}
|
|
265
|
-
${
|
|
265
|
+
${ne.dark`
|
|
266
266
|
background-color: ${b.color.onlight.textLowEmphasis};
|
|
267
267
|
color: ${b.themedColor.textMidEmphasis};
|
|
268
268
|
`}
|
|
269
|
-
`,
|
|
270
|
-
${r} ${
|
|
269
|
+
`,JE=U.css`border-color:${b.themedColor.error}!important;`,QE=C.default.button`${WE}${({$active:e,$submitted:t,$error:n})=>{if(t)return e?YE:jE;const r=e?XE:ZE;return n?U.css`
|
|
270
|
+
${r} ${JE}
|
|
271
271
|
`:r}}
|
|
272
|
-
`,
|
|
272
|
+
`,eC=e=>a.createElement(Ga,{...e,multiple:!1}),tC=e=>a.createElement(Ga,{...e,multiple:!0}),nC=C.default.div`width:100%;height:1px;background-color:${b.themedColor.textDisabled};`,rC=({className:e})=>a.createElement(nC,{className:e}),sC=({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(iC,{...f}):a.createElement(oC,{...f})},za=U.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;${xe}&::placeholder{color:${b.themedColor.textLowEmphasis};}`,Va=U.css`color:${b.themedColor.textHighEmphasis};border:1px solid transparent;cursor:not-allowed;${ne.light`
|
|
273
273
|
background-color: ${b.color.ondark.textMidEmphasis};
|
|
274
274
|
`}
|
|
275
|
-
${
|
|
275
|
+
${ne.dark`
|
|
276
276
|
background-color: ${b.color.onlight.textLowEmphasis};
|
|
277
277
|
`}
|
|
278
278
|
|
|
279
279
|
&::placeholder {
|
|
280
280
|
color: ${b.themedColor.textLowEmphasis};
|
|
281
281
|
}
|
|
282
|
-
`,
|
|
282
|
+
`,Ka=U.css`border:1px solid ${b.themedColor.error};color:${b.themedColor.textHighEmphasis};${ne.light`
|
|
283
283
|
background-color: ${b.color.background50};
|
|
284
284
|
`}
|
|
285
|
-
${
|
|
285
|
+
${ne.dark`
|
|
286
286
|
background-color: ${b.color.onlight.textLowEmphasis};
|
|
287
287
|
`}
|
|
288
|
-
`,
|
|
288
|
+
`,qa=U.css`border:1px solid ${b.themedColor.textDisabled};color:${b.themedColor.textHighEmphasis};${ne.light`
|
|
289
289
|
background-color: ${b.color.background50};
|
|
290
290
|
`}
|
|
291
|
-
${
|
|
291
|
+
${ne.dark`
|
|
292
292
|
background-color: ${b.color.onlight.textLowEmphasis};
|
|
293
293
|
`}
|
|
294
294
|
|
|
295
295
|
&:focus {
|
|
296
296
|
border-color: ${b.themedColor.primary};
|
|
297
297
|
}
|
|
298
|
-
`,
|
|
298
|
+
`,oC=C.default.input`${za};height:36px;${({$error:e,$submitted:t})=>t?Va:e?Ka:qa}`,iC=C.default.textarea`${za};height:96px;resize:none;font-family:inherit;${({$error:e,$submitted:t})=>t?Va:e?Ka:qa}`,aC=({children:e,className:t,style:n})=>a.createElement(B,{variant:"button",color:b.themedColor.textHighEmphasis,className:t,style:n},e),ke={Title:aC,Label:PE,ErrorLabel:$E,Separator:rC,Button:DE,TextInput:sC,NumberInput:FE,SingleSelect:eC,MultiSelect:tC},cC=1,lC=new Set(["text","number","single-select","multi-select"]),Wa=typeof __SBA_USE_FORM__>"u"||__SBA_USE_FORM__,uC=({messageForm:e,onError:t})=>{const n=l.useRef(void 0);l.useEffect(()=>{if(Wa||!e||!t)return;const r=e.key??"";n.current!==r&&(t(new Error("Form rendering is disabled")),n.current=r)},[e,t])},dC=e=>{var _,A;const t=(_=e.extendedMessagePayload)==null?void 0:_.form;if(uC({messageForm:t,onError:(A=e.statsCallbacks)==null?void 0:A.onFormRenderError}),!Wa)return null;if(!t)throw new Error("Form is not provided");const{stringSet:n}=ie(),{conversation:r}=ae(),[s,o]=l.useState({submitting:!1,canceling:!1}),[i,c]=l.useState({visible:!1}),{state:u,fields:d,submit:m,cancel:h,updateFieldValue:f}=rh(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}))}},v=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>cC,T=()=>t.fields.some(I=>!lC.has(I.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(Po,{$maxWidth:e.maxBodyWidth??se.BODY_MAX_WIDTH},a.createElement(ke.Title,null,t.title),a.createElement(mC,null,d.map(y=>a.createElement(hC,{key:y.key},a.createElement(ke.Label,{style:{marginBottom:"6px"},required:y.required},y.label),y.type==="text"&&a.createElement(ke.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(ke.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(ke.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(ke.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(ke.ErrorLabel,{style:{marginTop:"4px"}},y.error)))),a.createElement(ke.Separator,null),a.createElement(fC,null,a.createElement(ke.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(ke.Button,{variant:"secondary",...r.form.button(n.BUTTON__CANCEL).props,onClick:v,disabled:s.submitting,loading:s.canceling},n.BUTTON__CANCEL))),a.createElement(nn,{...i,onClose:()=>c({visible:!1,title:""})})):a.createElement(Po,{$maxWidth:e.maxBodyWidth??se.BODY_MAX_WIDTH},a.createElement(B,{variant:"body3"},E.reason),E.cancelable&&a.createElement(ke.Button,{variant:"primary",...r.form.button(n.BUTTON__CANCEL).props,onClick:v,loading:s.canceling},n.BUTTON__CANCEL))},Po=C.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})=>U.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
|
+
`,mC=C.default.div`display:flex;flex-direction:column;gap:12px;`,hC=C.default.div`display:flex;flex-direction:column;`,fC=C.default.div`display:flex;flex-direction:column;gap:8px;`,gC=e=>a.createElement(a.Fragment,null),Nr=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,pC=({messageTemplate:e,onError:t})=>{const n=l.useRef(void 0);l.useEffect(()=>{if(Nr||!e||!t)return;const r=e.key??"";n.current!==r&&(t(new Error("Message template rendering is disabled")),n.current=r)},[e,t])},_C=e=>{var n,r,s;const t=(n=e.extendedMessagePayload)==null?void 0:n.message_template;return pC({messageTemplate:t,onError:(r=e.statsCallbacks)==null?void 0:r.onMessageTemplateError}),Nr?a.createElement(Yt,{errorFallback:e.messageTemplateErrorFallback,loadingFallback:e.messageTemplateLoadingFallback,onError:(s=e.statsCallbacks)==null?void 0:s.onMessageTemplateError},a.createElement(Nr,{...e})):null},EC=e=>a.createElement(a.Fragment,null),CC=({data:e,extendedMessagePayload:t,onClickSuggestedReply:n,onConfirmTicketClosure:r,suggestedRepliesDirection:s="vertical"})=>{const{conversation:o}=ae(),{stringSet:i}=ie(),[c,u]=l.useState(!1),[d,m]=l.useState(!1),h=l.useRef(!1),{suggestedReplies:f}=o,g=Cd({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=v=>{if(v.action==="confirmTicketClosure"){if(h.current||!r)return;h.current=!0,r({ticketId:v.ticketId,confirmed:v.confirmed}).catch(()=>{h.current=!1,m(!0)});return}n&&(n({reply:v.label}),u(!0))};return a.createElement(a.Fragment,null,a.createElement(bC,{id:`${We}-ext-suggested-replies`,role:"presentation",$type:s},g.map((v,E)=>{const _=f.item(v.label,E);return a.createElement(l.Fragment,{key:E},a.createElement(vC,{$type:s,..._.props,onClick:()=>p(v)},a.createElement(SC,{variant:"body3"},v.label)),_.descriptionNode)})),a.createElement(nn,{visible:d,title:i.PLACE_HOLDER__WRONG,description:i.DESK__TICKET_CLOSURE_ERROR_MESSAGE,onClose:()=>m(!1)}))},bC=C.default.div`margin:16px 0;padding:0 ${se.HORIZONTAL_PADDING}px;position:relative;display:flex;align-self:stretch;gap:8px;${({$type:e})=>e==="vertical"?yC:AC};`,vC=C.default.button.attrs({type:"button"})`
|
|
306
306
|
all: unset;
|
|
307
307
|
box-sizing: border-box;
|
|
308
308
|
padding: 8px 12px;
|
|
@@ -320,61 +320,62 @@ $2
|
|
|
320
320
|
background-color: ${b.themedColor.bg_100_500};
|
|
321
321
|
}
|
|
322
322
|
|
|
323
|
-
${
|
|
323
|
+
${xe}
|
|
324
324
|
|
|
325
|
-
${({$type:e,theme:t})=>
|
|
326
|
-
`,
|
|
325
|
+
${({$type:e,theme:t})=>U.css`${e==="vertical"?TC:IC};&:active{background-color:${t.colors.base.primary};color:${t.colors.base.primaryContrastContent};}`}
|
|
326
|
+
`,SC=C.default(B)`color:inherit;`,yC=U.css`flex-direction:column;align-items:flex-end;`,AC=U.css`flex-direction:row;overflow-x:scroll;-ms-overflow-style:none;scrollbar-width:none;&::-webkit-scrollbar{display:none;}`,TC=U.css`max-width:calc(100% - 70px);white-space:pre-wrap;`,IC=U.css`white-space:nowrap;`,xC=e=>{const{components:t}=ht.useContext(),{stringSet:n}=ie(),r=mi(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})},RC=e=>{var T,I,N,O,k;const{components:t}=ht.useContext(),{streamText:n,isAnimating:r,isHolding:s}=bh({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:(I=e.statsCallbacks)==null?void 0:I.onVisibleTextProgress,onRenderedTextProgress:(N=e.statsCallbacks)==null?void 0:N.onRenderedTextProgress});if(s)return null;const o={...e,message:n,extendedMessagePayload:r?{}:e.extendedMessagePayload},i=!!o.isTyping,c=!!o.isSenderAvatarVisible,u=Xt(o.extendedMessagePayload),d=u.hasCTAButton,m=u.hasChallenge,h=u.hasCitations,f=u.hasForm,g=u.hasMessageTemplate,p=!!o.createdAt,v=d||h,E=o.groupType==="top"||o.groupType==="single",_=o.groupType==="bottom"||o.groupType==="single",A=c?se.AVATAR_SIZE:0,y=v&&a.createElement(l.Fragment,null,d&&a.createElement(wC,{$marginTop:12,$paddingInline:12},a.createElement(t.CTAButton,{...o})),h&&a.createElement(t.Citation,{...o}));return a.createElement(MC,{$marginBottom:i?0:Nn(o.groupType)},E&&a.createElement(kC,null,c&&a.createElement(t.SenderAvatar,{...o}),a.createElement(t.SenderName,{...o})),a.createElement(t.Prechecks,{...o}),a.createElement(OC,null,a.createElement(mr,{$extraStartPadding:A},i?a.createElement(t.TypingIndicator,{...o}):a.createElement(t.MessageBody,{...o},y)),g&&a.createElement(Fo,{$startPadding:0,$endPadding:0},a.createElement(t.MessageTemplate,{...o,messageTemplateErrorFallback:o.messageTemplateErrorFallback??a.createElement(mr,{$extraStartPadding:A},a.createElement(t.MessageBody,{...o,messageType:"user",message:((k=(O=o.extendedMessagePayload)==null?void 0:O.message_template)==null?void 0:k.fallback_message)??"Cannot read this template."})),messageTemplateLoadingFallback:o.messageTemplateLoadingFallback??a.createElement(mr,{$extraStartPadding:A},a.createElement(t.TypingIndicator,{...o}))})),a.createElement(t.CustomMessageTemplate,{...o}),m&&a.createElement(t.Challenge,{...o}),f&&a.createElement(Fo,{$extraStartPadding:A},a.createElement(t.Form,{...o}))),a.createElement(t.MessageLogs,{...o}),_&&p&&a.createElement(LC,{$extraStartPadding:A+8},a.createElement(t.SentTime,{...o})),a.createElement(l.Fragment,null,!i&&a.createElement(rn,{$extraStartPadding:A+8},a.createElement(t.Feedback,{...o})),o.suggestedRepliesVisible&&a.createElement(t.SuggestedReplies,{...o})))},ht=qe({template:RC,components:{SenderName:W_,SenderAvatar:K_,SentTime:j_,MessageBody:xC,TextMessageBody:H_,MediaMessageBody:I_,FileMessageBody:y_,MultipleFilesMessageBody:F_,TypingIndicator:Z_,SuggestedReplies:CC,MessageTemplate:_C,CustomMessageTemplate:hE,Challenge:iE,CTAButton:rE,Citation:aE,Form:dC,Feedback:xE,MessageLogs:gC,Prechecks:EC}}),MC=C.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
|
+
`,rn=C.default.div.attrs({role:"presentation"})`
|
|
332
332
|
display: flex;
|
|
333
333
|
align-self: stretch;
|
|
334
334
|
justify-content: flex-start;
|
|
335
335
|
${({$startPadding:e=se.HORIZONTAL_PADDING,$endPadding:t=se.HORIZONTAL_PADDING,$extraStartPadding:n=0})=>`
|
|
336
336
|
padding-inline: ${e+n}px ${t}px;
|
|
337
337
|
`}
|
|
338
|
-
`,
|
|
338
|
+
`,wC=C.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})=>U.css`margin-top:${e}px;padding-inline:${t}px;`}
|
|
343
|
+
`,kC=C.default(rn)`display:flex;flex-direction:row;align-items:center;gap:8px;`,mr=C.default(rn)`display:flex;`,LC=C.default(rn)`margin-top:${se.BODY_TIME_GAP}px;display:flex;align-items:flex-start;justify-content:flex-start;`,Fo=C.default(rn).attrs({role:"presentation"})`
|
|
344
344
|
display: flex;
|
|
345
345
|
${({$startPadding:e=se.HORIZONTAL_PADDING,$endPadding:t=se.HORIZONTAL_PADDING,$extraStartPadding:n=0})=>`
|
|
346
346
|
padding-inline: ${e+n}px ${t}px;
|
|
347
347
|
`}
|
|
348
|
-
`,
|
|
348
|
+
`,OC=C.default.div.attrs({role:"presentation"})`
|
|
349
349
|
display: flex;
|
|
350
350
|
flex-direction: column;
|
|
351
|
+
align-self: stretch;
|
|
351
352
|
min-width: 0;
|
|
352
353
|
max-width: 100%;
|
|
353
354
|
gap: ${se.GAP_GROUPED}px;
|
|
354
|
-
`;function
|
|
355
|
+
`;function NC({file:e,children:t,onClickFile:n,sendingStatus:r}){const s=(()=>{if(!(!n||r==="failed"))return()=>n==null?void 0:n(e)})();return a.createElement(DC,null,a.createElement(ds,{name:e.name,mimeType:e.type,type:Ur(e.name,e.type),onClick:s}),t)}const DC=C.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${se.GAP_GROUPED}px;`;function $C({sendingStatus:e,file:t,metadata:n,onClickMedia:r,onClickMediaFiles:s,children:o}){const{conversation:i}=ae(),{aspectRatio:c,localFile:u}=n,[d]=l.useState(()=>u instanceof Blob?URL.createObjectURL(u):t.url),[m,h]=l.useState(!1),f=(()=>{if(e!=="failed"){if(s)return()=>s({files:[{url:d,type:t.type,name:t.name}],index:0});if(r)return()=>r({...t,url:d})}})(),g=f?i.file.buttonLikePreview({name:t.name,mimeType:t.type,onActivate:f}):i.file.preview({name:t.name,mimeType:t.type}),p={...g.props,$ratio:c,$clickable:!!f};return a.createElement(PC,null,a.createElement(FC,{...p},!m&&a.createElement(Ct,{size:26},a.createElement(ee,{type:"spinner",color:"textLowEmphasis",size:26})),a.createElement(UC,{$loaded:m,src:d,alt:"image-message",onLoad:()=>h(!0)}),g.descriptionNode),o)}const PC=C.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${se.GAP_GROUPED}px;`,FC=C.default.div`width:${se.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`
|
|
355
356
|
background-color: ${b.color.background100};
|
|
356
357
|
`}
|
|
357
|
-
${
|
|
358
|
+
${ne.dark`
|
|
358
359
|
background-color: ${b.color.background400};
|
|
359
360
|
`}
|
|
360
|
-
`,
|
|
361
|
+
`,UC=C.default.img`position:absolute;width:100%;height:100%;inset-block-start:0;inset-inline-start:0;object-fit:cover;opacity:${e=>e.$loaded?1:0};transition:opacity 0.5s ease;`,BC=({sendingStatus:e,files:t,metadata:n,onClickMedia:r,onClickMediaFiles:s,children:o})=>{const[i]=l.useState(()=>n.localFiles?n.localFiles.filter(m=>m instanceof Blob).map(m=>({...m,url:URL.createObjectURL(m)})):t),c=e==="pending",u=e==="failed",d=m=>{if(u||c)return;const h=i[m];h&&(s?s({files:i,index:m}):r&&r({url:h.url,type:h.type||"image/*"}))};return a.createElement(HC,null,a.createElement(Da,{images:i,isPending:c,onClickImage:d}),o)},HC=C.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${se.GAP_GROUPED}px;`,Ya=({children:e})=>a.createElement("span",{id:wo,className:wo,"aria-label":T_},e),ja="✱",Uo=e=>{var t;return{files:e.fileInfoList.map(n=>({url:n.url,type:n.mimeType??"",name:n.fileName??""})),metadata:{localFiles:(t=e.messageParams)==null?void 0:t.fileInfoList.map(n=>n.file)}}},GC=e=>{const t=new RegExp(`(\`+)[^\`]+?\\1|(${ja}+)`,"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},hr=(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(Ya,{key:i.start},i.text)),o=i.end);return o<n&&s.push(e.slice(o,n)),s},zC=e=>{const t=GC(e),n=/\*\*.*?\*\*/g,r=[];let s=0,o;for(;(o=n.exec(e))!==null;){const i=o.index+o[0].length;r.push(...hr(e,s,o.index,t)),r.push(a.createElement("b",{key:o.index},hr(e,o.index+2,i-2,t))),s=i}return r.push(...hr(e,s,e.length,t)),r};function VC(e){var n,r;const t=l.useMemo(()=>zC(e.message),[e.message]);return a.createElement(KC,{$maxWidth:e.maxBodyWidth??se.BODY_MAX_WIDTH,$color:(n=e.customStyle)==null?void 0:n.bubbleContentColor,$bgColor:(r=e.customStyle)==null?void 0:r.bubbleBackgroundColor},a.createElement(qC,{variant:"body3"},t))}const KC=C.default.div`display:flex;flex-direction:column;border-radius:12px;overflow:hidden;max-width:${({$maxWidth:e})=>e}px;${({theme:e,$color:t,$bgColor:n})=>U.css`
|
|
361
362
|
color: ${t||e.colors.messageOutgoing.text};
|
|
362
363
|
background-color: ${n||e.colors.messageOutgoing.background};
|
|
363
364
|
`}
|
|
364
365
|
padding: 12px 0;
|
|
365
366
|
transition: max-width 0.3s;
|
|
366
367
|
overflow-wrap: break-word;
|
|
367
|
-
`,
|
|
368
|
-
`,
|
|
369
|
-
`,zC=C.default(qa)``,VC=C.default(qa)`margin-top:${se.BODY_TIME_GAP}px;`,qC=e=>e.messageType!=="admin"?null:a.createElement(KC,null,a.createElement(U,{variant:"caption2",color:b.themedColor.textMidEmphasis},YC(Qo.default.sanitize(e.message),e.onClickLink))),KC=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;}`,YC=(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:es,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]}},WC=({direction:e,currentIndex:t,totalCount:n})=>n<=0?t:e==="next"?(t+1)%n:(t-1+n)%n,Ka=({options:e,value:t,disabled:n,hasError:r=!1,errorId:s,onChange:o})=>{const i=l.useRef([]),c=e.findIndex(h=>h.value===t),u=c>=0?c:0,d=h=>{requestAnimationFrame(()=>{var f;(f=i.current[h])==null||f.focus()})},m=h=>{const f=e[h];!f||n||(o==null||o(f.value),d(h))};return{radioGroupProps:h=>({role:"radiogroup","aria-label":h,...r&&s?{"aria-invalid":!0,"aria-errormessage":s}:{}}),getRadioProps:h=>({ref:f=>{i.current[h]=f},tabIndex:n?-1:h===u?0:-1,describedBy:r&&s?s:void 0,onArrowNavigate:f=>{m(WC({direction:f,currentIndex:h,totalCount:e.length}))}})}},jC=e=>{switch(e.key){case"ArrowDown":case"ArrowRight":return"next";case"ArrowUp":case"ArrowLeft":return"previous";default:return}},XC=({event:e,onClick:t,onArrowNavigate:n})=>{if(ZC(e))return;const r=jC(e);if(r){e.preventDefault(),n==null||n(r);return}e.key!=="Enter"&&e.key!==" "||(e.preventDefault(),t==null||t())},ZC=e=>e.repeat||e.currentTarget.getAttribute("aria-disabled")==="true",ds=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(eb,{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=>XC({event:h,onClick:e,onArrowNavigate:c})},a.createElement(JC,{"aria-hidden":"true"},a.createElement(ee,{size:20,type:t?"radio-on":"radio-off",color:d})),a.createElement(QC,{"aria-hidden":"true",variant:o,color:m},n))});ds.displayName="Radio";const JC=C.default.div`width:20px;height:20px;`,QC=C.default(U)`line-height:20px;word-break:break-word;`,eb=C.default.div`display:flex;align-items:flex-start;justify-content:flex-start;gap:2px;${Ie}&[aria-disabled='false']{cursor:pointer;}`,tb=({csatPayload:e,submitted:t,defaultValue:n,value:r,onChange:s})=>{var u,d;const o=[{label:((u=e.cre)==null?void 0:u.positive_label)??"",value:!0},{label:((d=e.cre)==null?void 0:d.negative_label)??"",value:!1}],i=Ka({options:o,value:r,disabled:t,onChange:s});if(l.useEffect(()=>{typeof r>"u"&&typeof n=="boolean"&&(s==null||s(n))},[r,n]),!e.cre)return null;const c=e.cre;return a.createElement(nb,null,a.createElement(Le.Label,{required:c.required,"aria-hidden":!0},c.question),a.createElement(rb,{...i.radioGroupProps(c.question)},o.map((m,h)=>a.createElement(ds,{key:m.label,checked:r===m.value,label:m.label,disabled:t,...i.getRadioProps(h),onClick:()=>s==null?void 0:s(m.value)}))))},nb=C.default.div`display:flex;flex-direction:column;gap:8px;`,rb=C.default.div`display:flex;flex-direction:column;gap:8px;`,sb=({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=Ka({options:m,value:n,disabled:t,hasError:s,errorId:c,onChange:r});return a.createElement(ob,null,a.createElement(Le.Label,{id:u,required:e.required,"aria-hidden":d},e.question),e.response_type==="free_text"&&a.createElement(Le.TextInput,{variant:"multi-line",disabled:t,submitted:t,maxLength:100,value:n,onChange:f=>r(f),error:s,...i.form.textInput(o.A11Y_CSAT_TEXT_INPUT_LABEL,e.required??!1,t,{labelId:u}).props,"aria-invalid":s,"aria-errormessage":s?c:void 0}),e.response_type==="single_choice"&&a.createElement(ib,{...h.radioGroupProps(e.question)},m.map((f,g)=>a.createElement(ds,{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(ab,{role:"alert",id:c},o.FORM_VALIDATION_REQUIRED))},ob=C.default.div`display:flex;flex-direction:column;gap:8px;`,ib=C.default.div`display:flex;flex-direction:column;gap:8px;`,ab=C.default(Le.ErrorLabel)``,cb=({value:e,selected:t})=>a.createElement(lb,{$selected:t,"aria-hidden":"true"},ub[e-1]),lb=C.default.div`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,ub=[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)"}))))],db=({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(hb,null,a.createElement(U,{variant:"caption3",color:b.themedColor.textMidEmphasis,"aria-hidden":"true"},e.csat_question),a.createElement(fb,{...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(gb,{key:d,type:"button",...g.props},a.createElement(mb,{value:m,selected:s||h,src:u}),!!c&&a.createElement(U,{"aria-hidden":"true",color:h?b.themedColor.textHighEmphasis:b.themedColor.textLowEmphasis,variant:"caption3"},c),g.descriptionNode)})))},mb=({value:e,src:t,selected:n})=>{const[r,s]=l.useState(!1),o=r?a.createElement(cb,{value:e,selected:n}):a.createElement(_b,{$selected:n,alt:"","aria-hidden":"true",src:t,onError:()=>s(!0)});return a.createElement(pb,null,o)},hb=C.default.div`display:flex;flex-direction:column;gap:8px;`,fb=C.default.div`display:flex;justify-content:space-between;align-self:center;width:100%;max-width:400px;gap:16px;`,gb=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;${Ie}&:not(:disabled):hover span{color:${b.themedColor.textHighEmphasis};}`,pb=C.default.div`button:not(:disabled):hover &{border-radius:4px;cursor:pointer;background-color:${b.color.background200};${te.dark`
|
|
368
|
+
`,qC=C.default(B)`align-items:flex-start;line-height:140%;white-space:pre-wrap;padding:0 12px;`,WC=({sendingStatus:e})=>{const t=U.useTheme();switch(e){case"pending":return a.createElement(YC,{size:16},a.createElement(ee,{type:"spinner",color:t.colors.messageOutgoing.background,size:16}));case"failed":return a.createElement("div",{style:{marginBottom:2}},a.createElement(ee,{type:"error",color:b.themedColor.error,size:16}));case"scheduled":case"canceled":return null;default:return a.createElement("div",{style:{marginBottom:2}},a.createElement(ee,{type:"done",color:b.themedColor.secondary,size:16}))}},YC=C.default(Ct)`margin-bottom:2px;width:16px;height:16px;`,jC=({createdAt:e})=>{const{stringSet:t,format:n}=ie();return e?a.createElement(B,{variant:"caption4",color:b.themedColor.textLowEmphasis},n(e,t.DATE_FORMAT__MESSAGE_TIMESTAMP)):null},XC=e=>{const{components:t}=Dt.useContext(),{stringSet:n}=ie(),r=()=>{const i=mi(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?Gt({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())},ZC=e=>a.createElement(a.Fragment,null),JC=e=>{const{components:t}=Dt.useContext(),n=e.sendingStatus==="succeeded",r=e.groupType==="bottom"||e.groupType==="single";return a.createElement(QC,{$marginBottom:Nn(e.groupType)},a.createElement(eb,null,a.createElement(t.MessageBody,{...e})),a.createElement(t.MessageLogs,{...e}),r&&a.createElement(tb,{$extraEndPadding:8},n?a.createElement(t.SentTime,{...e}):a.createElement(t.SendingStatus,{...e})))},Dt=qe({template:JC,components:{SendingStatus:WC,SentTime:jC,MessageBody:XC,TextMessageBody:VC,MediaMessageBody:$C,FileMessageBody:NC,MultipleFilesMessageBody:BC,MessageLogs:ZC}}),QC=C.default.div`display:flex;flex:1;flex-direction:column;align-items:flex-end;margin-bottom:${({$marginBottom:e})=>`${e}px`};
|
|
369
|
+
`,Xa=C.default.div`display:flex;align-self:stretch;justify-content:flex-end;${({$startPadding:e=se.HORIZONTAL_PADDING,$endPadding:t=se.HORIZONTAL_PADDING,$extraEndPadding:n=0})=>`padding-inline: ${e}px ${t+n}px;`};
|
|
370
|
+
`,eb=C.default(Xa)``,tb=C.default(Xa)`margin-top:${se.BODY_TIME_GAP}px;`,nb=e=>e.messageType!=="admin"?null:a.createElement(rb,null,a.createElement(B,{variant:"caption2",color:b.themedColor.textMidEmphasis},sb($c.default.sanitize(e.message),e.onClickLink))),rb=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;}`,sb=(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]}},ob=({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(ob({direction:f,currentIndex:h,totalCount:e.length}))}})}},ib=e=>{switch(e.key){case"ArrowDown":case"ArrowRight":return"next";case"ArrowUp":case"ArrowLeft":return"previous";default:return}},ab=({event:e,onClick:t,onArrowNavigate:n})=>{if(cb(e))return;const r=ib(e);if(r){e.preventDefault(),n==null||n(r);return}e.key!=="Enter"&&e.key!==" "||(e.preventDefault(),t==null||t())},cb=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(db,{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=>ab({event:h,onClick:e,onArrowNavigate:c})},a.createElement(lb,{"aria-hidden":"true"},a.createElement(ee,{size:20,type:t?"radio-on":"radio-off",color:d})),a.createElement(ub,{"aria-hidden":"true",variant:o,color:m},n))});fs.displayName="Radio";const lb=C.default.div`width:20px;height:20px;`,ub=C.default(B)`line-height:20px;word-break:break-word;`,db=C.default.div`display:flex;align-items:flex-start;justify-content:flex-start;gap:2px;${xe}&[aria-disabled='false']{cursor:pointer;}`,mb=({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(hb,null,a.createElement(ke.Label,{required:c.required,"aria-hidden":!0},c.question),a.createElement(fb,{...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)}))))},hb=C.default.div`display:flex;flex-direction:column;gap:8px;`,fb=C.default.div`display:flex;flex-direction:column;gap:8px;`,gb=({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(pb,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(_b,{...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(Eb,{role:"alert",id:c},o.FORM_VALIDATION_REQUIRED))},pb=C.default.div`display:flex;flex-direction:column;gap:8px;`,_b=C.default.div`display:flex;flex-direction:column;gap:8px;`,Eb=C.default(ke.ErrorLabel)``,Cb=({value:e,selected:t})=>a.createElement(bb,{$selected:t,"aria-hidden":"true"},vb[e-1]),bb=C.default.div`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,vb=[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)"}))))],Sb=({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(Ab,null,a.createElement(B,{variant:"caption3",color:b.themedColor.textMidEmphasis,"aria-hidden":"true"},e.csat_question),a.createElement(Tb,{...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(Ib,{key:d,type:"button",...g.props},a.createElement(yb,{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)})))},yb=({value:e,src:t,selected:n})=>{const[r,s]=l.useState(!1),o=r?a.createElement(Cb,{value:e,selected:n}):a.createElement(Rb,{$selected:n,alt:"","aria-hidden":"true",src:t,onError:()=>s(!0)});return a.createElement(xb,null,o)},Ab=C.default.div`display:flex;flex-direction:column;gap:8px;`,Tb=C.default.div`display:flex;justify-content:space-between;align-self:center;width:100%;max-width:400px;gap:16px;`,Ib=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};}`,xb=C.default.div`button:not(:disabled):hover &{border-radius:4px;cursor:pointer;background-color:${b.color.background200};${ne.dark`
|
|
370
371
|
background-color: ${b.color.background500};
|
|
371
372
|
`}
|
|
372
373
|
}
|
|
373
|
-
`,
|
|
374
|
+
`,Rb=C.default.img`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,Mb=({csatPayload:e})=>a.createElement(B,{variant:"button",color:b.themedColor.textHighEmphasis},e.title),fr=({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}=fh({csatPayload:e,type:t,initialCsat:r,initialCsatReason:s,initialIsResolved:o});return a.createElement(a.Fragment,null,a.createElement(wb,null,a.createElement(Mb,{...g}),t===Je.AI_AGENT_CSAT_5_WITH_CRE&&a.createElement(mb,{...g,defaultValue:o,value:i.isResolved,onChange:p=>c({isResolved:p})}),a.createElement(Sb,{...g,value:i.csat,onChange:p=>c({csat:p})}),m&&a.createElement(gb,{...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(ke.Separator,null),n({state:h,params:i,validateParams:f})))},wb=C.default.div`display:flex;flex-direction:column;gap:12px;`,kb=e=>{const{stringSet:t}=ie();return Ll(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})},Lb=()=>{const{stringSet:e}=ie();return a.createElement(B,{variant:"body2",color:b.themedColor.textMidEmphasis,style:{textAlign:"center"}},e.CSAT_SUBMISSION_EXPIRED)},Ob=({onMount:e,children:t})=>(l.useEffect(()=>{e&&Ie(e)},[]),t),Nb=e=>{const{conversation:t}=ae();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=Pn(),m=kb(n==null?void 0:n.csat),h=l.useRef(null),f=l.useRef(null),[g,p]=l.useState(!1),v=l.useRef(!1),E=l.useCallback(()=>{Ie(()=>{var I;return(I=f.current)==null?void 0:I.focus()})},[]),{isExpiredNow:_,isRenderableCSAT:A}=gh({csat:o,csatExpireAt:c,csatPayload:m,isSubmitInFlight:g});if(mh({csat:o,csatPayload:m,isRenderableCSAT:A,isExpiredNow:_,announceStatus:e.announceStatus,onSubmittedAnnounced:E}),!A||!m)return null;const y=()=>{var N;const I=(N=h.current)==null?void 0:N.querySelector('[aria-invalid="true"]');return I?I.getAttribute("role")==="radiogroup"?I.querySelector('[role="radio"]'):I:null},T=m.type===Je.AI_AGENT_CSAT_5||m.type===Je.AI_AGENT_CSAT_5_WITH_CRE||m.type===Je.HELPDESK_CSAT_5?fr:()=>null;return a.createElement(Db,{ref:h},!o&&_?a.createElement(Lb,null):a.createElement(T,{csatPayload:m,type:m.type,initialCsat:o,initialCsatReason:i,initialIsResolved:u,renderSubmitButton:({state:I,params:N,validateParams:O})=>I==="submitted"?a.createElement(Pb,{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(Ob,{onMount:s},a.createElement($b,{type:"button",...t.csat.submitButton(m.csat_submit_label).props,onClick:async()=>{if(v.current)return;const k=_i(c);if(!k&&O()){v.current=!0,p(!0);try{await r(N)}catch(R){throw v.current=!1,p(!1),R}}else d(),k||Ie(()=>{var R;(R=e.announceError)==null||R.call(e,{type:"csatFormError"},y())})}},a.createElement(B,{variant:"button"},m.csat_submit_label)))}))},Db=C.default.div`display:flex;flex-direction:column;background-color:${({theme:e})=>e.colors.csat.background};border-radius:16px;gap:16px;padding:16px;`,$b=C.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;${xe}&:hover{background-color:${b.color.primary.dark};}`,Pb=C.default.div`width:100%;box-sizing:border-box;color:${b.themedColor.textHighEmphasis};background-color:${b.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`
|
|
374
375
|
background-color: ${b.color.onlight.textDisabled};
|
|
375
376
|
`}
|
|
376
|
-
`,
|
|
377
|
-
`,
|
|
377
|
+
`,Fb=e=>{const{components:t}=Vn.useContext(),n=e.messageType==="admin"?a.createElement(t.AdminMessage,{...e}):e.messageType==="admin.csat"?a.createElement(t.CSATMessage,{...e}):null;return a.createElement(Ub,{$marginBottom:Nn(e.groupType)},n)},Vn=qe({template:Fb,components:{AdminMessage:nb,CSATMessage:Nb}}),Ub=C.default.div`padding-inline:${se.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>e}px;`,gs=({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(Vb,{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)??b.themedColor.textHighEmphasis},s)):null,g=h?a.createElement(Kb,{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)??b.themedColor.textHighEmphasisInverse},o)):null;return a.createElement(Bb,null,a.createElement(Hb,null,a.createElement(B,{as:"div",id:t,variant:"h2",color:(d==null?void 0:d.titleColor)??b.themedColor.textHighEmphasis},e)),a.createElement(Gb,null,a.createElement(B,{as:"div",id:r,variant:"body3",color:(d==null?void 0:d.descriptionColor)??b.themedColor.textMidEmphasis},n)),a.createElement(zb,{$buttonLayout:u},u==="horizontal"?a.createElement(a.Fragment,null,f,g):a.createElement(a.Fragment,null,g,f)))},Bb=C.default.div`display:flex;flex-direction:column;width:280px;border-radius:16px;overflow:hidden;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,Hb=C.default.div`padding:24px 24px 16px;`,Gb=C.default.div`padding-inline:24px;`,zb=C.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;`,Vb=C.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;}`,Kb=C.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??b.themedColor.textHighEmphasis};white-space:nowrap;overflow:hidden;text-overflow:ellipsis;&:hover{opacity:0.8;}`,pn=16,qb=({status:e})=>e===yn.COMPLETED?a.createElement(ee,{type:"done-circle",size:pn,color:b.themedColor.textHighEmphasis}):e===yn.CANCELED?a.createElement(ee,{type:"stop-circle",size:pn,color:b.themedColor.textLowEmphasis}):a.createElement(Ct,{size:pn},a.createElement(ee,{type:"spinner",size:pn,color:b.themedColor.textHighEmphasis})),Ja=24,Wb=8,Yb=40,jb=({task:e,isFirst:t,isLast:n})=>a.createElement(Xb,{role:"listitem"},a.createElement(Zb,null,a.createElement(Bo,{$hidden:t}),a.createElement(Jb,null,a.createElement(qb,{status:e.status})),a.createElement(Bo,{$hidden:n})),a.createElement(Qb,null,a.createElement(B,{as:"div",variant:"body3",color:e.status===yn.CANCELED?b.themedColor.textLowEmphasis:b.themedColor.textHighEmphasis},e.user_facing_title))),Xb=C.default.div`display:flex;gap:4px;`,Zb=C.default.div`display:flex;flex-direction:column;align-items:center;width:${Ja}px;flex-shrink:0;`,Bo=C.default.div`width:1px;flex:1;transform:translateX(-25%);${({$hidden:e})=>e&&"visibility: hidden;"}background-image:repeating-linear-gradient( to bottom,${b.themedColor.textHighEmphasis}0 2px,transparent 2px 4px );`,Jb=C.default.div`display:flex;height:${Ja}px;align-items:center;justify-content:center;`,Qb=C.default.div`display:flex;flex:1;align-items:center;box-sizing:border-box;min-width:0;min-height:${Yb}px;padding-block:${Wb}px;`,ev=({steward:e,onCancelSteward:t})=>{const{logger:n}=ue(),[r,s]=l.useState(!1),[o,i]=l.useState(!1),c=!!e.cancellation_option,u=zc(e.status);return a.createElement(tv,{$marginBottom:Nn("single")},a.createElement(nv,null,a.createElement(rv,null,a.createElement(sv,null,a.createElement(B,{as:"div",variant:"caption1",color:b.themedColor.textHighEmphasis},e.title),!!e.description&&a.createElement(B,{as:"div",variant:"caption4",color:b.themedColor.textLowEmphasis},e.description)),c&&a.createElement(cv,{type:"button","aria-label":"Stop steward",disabled:o,onClick:()=>s(!0)},a.createElement(ee,{type:"stop",size:16,color:o?b.themedColor.textDisabled:b.themedColor.textHighEmphasis}))),a.createElement(ov,null),e.tasks.length===0?u!==Vt.IN_PROGRESS?null:a.createElement(av,null,a.createElement(Ct,{size:16},a.createElement(ee,{type:"spinner",size:16,color:b.themedColor.textHighEmphasis}))):a.createElement(iv,{role:"list"},e.tasks.map((d,m)=>a.createElement(jb,{key:d.id,task:d,isFirst:m===0,isLast:m===e.tasks.length-1})))),r&&e.cancellation_option&&a.createElement(gt,{portalContainerId:Se.WINDOW,visible:r,onClose:()=>s(!1)},a.createElement(gs,{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)}}})))},tv=C.default.div`display:flex;flex-direction:column;margin:0 ${se.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>`${e}px`};
|
|
378
|
+
`,nv=C.default.div`display:flex;flex-direction:column;border-radius:12px;overflow:hidden;padding:16px;border:1px solid ${b.themedColor.bg_300_500};background-color:${b.themedColor.bg_50_600};box-shadow:0 8px 20px rgba(0,0,0,0.12);`,rv=C.default.div`display:flex;flex-direction:row;align-items:flex-start;gap:8px;`,sv=C.default.div`display:flex;flex-direction:column;gap:4px;flex:1;min-width:0;`,ov=C.default.div`height:1px;margin-block:12px;background-color:${b.themedColor.bg_200_400};`,iv=C.default.div`display:flex;flex-direction:column;`,av=C.default.div`display:flex;width:100%;height:40px;align-items:center;justify-content:center;`,cv=C.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:${b.themedColor.textHighEmphasis};background-color:${b.themedColor.bg_200_400};&:hover:not(:disabled){opacity:0.8;}&:disabled{cursor:default;}`,lv=({className:e,label:t,onClick:n})=>{const{colors:r}=U.useTheme(),{conversation:s}=ae(),o={newMessages:s.newMessagesButton()};return a.createElement(uv,{className:e,onClick:n,...o.newMessages.props},a.createElement(B,{variant:"button",color:r.base.primaryContrastContent},t),a.createElement(ee,{size:16,type:"chevron-down",color:r.base.primaryContrastContent}),o.newMessages.descriptionNode)},uv=C.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;}${xe}`,ps=({iconSize:e=64,icon:t,className:n,label:r,children:s})=>a.createElement(mv,{className:n},t&&a.createElement(ee,{type:t,size:e,color:b.themedColor.textLowEmphasis}),r&&a.createElement(B,{variant:"body1",color:b.themedColor.textMidEmphasis},r),s),dv=C.default.div`position:relative;display:flex;justify-content:center;align-items:center;width:100%;height:100%;`,mv=C.default.div`display:flex;flex-direction:column;min-height:104px;align-items:center;gap:20px;text-align:center;`,hv=({label:e="Something went wrong",icon:t="error",action:n,...r})=>a.createElement(ps,{icon:t,label:e,...r},n&&a.createElement(fv,{onClick:n.onClick,label:n.label??"Retry"})),fv=({label:e,onClick:t})=>{const{conversation:n}=ae();return a.createElement(gv,{tabIndex:0,...n.retryButton(e).props,onClick:t},a.createElement(ee,{type:"refresh",size:20}),a.createElement(B,{variant:"button",color:b.color.primary.main},e))},gv=C.default.button`all:unset;display:flex;cursor:pointer;gap:4px;align-items:center;justify-content:center;${xe}`,pv=({iconSize:e=48,className:t})=>a.createElement(Ct,{size:e,className:t}),_v=({label:e="No channels",icon:t="chat",...n})=>a.createElement(ps,{icon:t,label:e,...n}),Ev=({label:e="No messages",icon:t="message",...n})=>a.createElement(ps,{icon:t,label:e,...n}),Cv=e=>{const{components:t}=Kn.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(dv,null,n)},Kn=qe({template:Cv,components:{Loading:pv,Error:hv,NoChannels:_v,NoMessages:Ev}}),qt=e=>{const{Template:t}=Kn.useContext();return a.createElement(t,{...e})},bv=[0,150,450];function vv({enabled:e}){const{state:t,actions:n}=ya(),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=bv.map(c=>setTimeout(()=>{Ie(()=>{r.current===o&&(s.current||n.scrollToBottom(!1))})},c));return()=>{r.current+=1,i.forEach(c=>clearTimeout(c))}},[n.scrollToBottom,e])}const Sv=({className:e,date:t=Date.now(),role:n,style:r})=>{const{format:s,stringSet:o}=ie();return a.createElement(yv,{id:`${Ue}-date-separator`,role:n,style:r,className:e},a.createElement(B,{variant:"caption4",color:b.themedColor.textMidEmphasis},s(t,o.DATE_FORMAT__MESSAGE_LIST__DATE_SEPARATOR)))},yv=C.default.div`display:flex;justify-content:center;align-items:center;text-align:center;word-break:break-word;`,Av=({className:e,style:t,onClick:n})=>{const{conversation:r}=ae(),s={scrollToBottom:r.scrollToBottomButton()};return a.createElement(Tv,{className:e,style:t,onClick:n,tabIndex:0,...s.scrollToBottom.props},a.createElement(ee,{size:24,type:"chevron-down",color:b.color.primary.main}),s.scrollToBottom.descriptionNode??null)},Tv=C.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`
|
|
378
379
|
background-color: ${b.color.background50};
|
|
379
380
|
&:hover {
|
|
380
381
|
background-color: ${b.color.background100};
|
|
@@ -383,7 +384,7 @@ $2
|
|
|
383
384
|
background-color: ${b.color.background200};
|
|
384
385
|
}
|
|
385
386
|
`}
|
|
386
|
-
${
|
|
387
|
+
${ne.dark`
|
|
387
388
|
background-color: ${b.color.background400};
|
|
388
389
|
&:hover {
|
|
389
390
|
background-color: ${b.color.background500};
|
|
@@ -397,22 +398,22 @@ $2
|
|
|
397
398
|
outline: none;
|
|
398
399
|
}
|
|
399
400
|
|
|
400
|
-
${
|
|
401
|
-
`,
|
|
401
|
+
${xe}
|
|
402
|
+
`,Iv=()=>null,qn=qe({template:Iv,components:{DateSeparator:Sv,ScrollToBottomButton:Av}}),xv=()=>{const{stringSet:e,format:t}=ie(),{agentPreviewConfigs:n={},aiAgentId:r}=ue(),{aiAgentInfo:s}=Oe(),{messageSource:o}=Ae(),{Template:i}=ht.useContext(),{components:c}=qn.useContext(),u=n.welcomeMessages??[],d=o.messages,m=pp(d,r),h=d[m.length+1],f=m[0]??h;return{filteredMessages:Ma(d,{previewWelcomeMessages:u,aiAgentUserId:r}),shouldShowOriginalDate:g=>g>0||u.length===0?!0:h&&!ut.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 v=p===u.length-1,E=m.length!==d.length,_=u.length===1?"single":p===0?"top":v||E?"bottom":"middle",A=(f==null?void 0:f.createdAt)??Date.now();return a.createElement("div",{key:p,role:"listitem",tabIndex:-1,"aria-label":Kt({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:v&&!E,isBotMessage:!0,onClickSuggestedReply:async({reply:y})=>{o.sendUserMessage({message:y})}}))}))}},Rv=()=>{const{messageSource:e,scrollSource:t}=Ae();l.useEffect(()=>{!t.state.isAwayFromBottom&&t.state.isScrollPositionReconciled&&e.resetNewMessages()},[t.state.isAwayFromBottom,t.state.isScrollPositionReconciled])},Ho="https://delight.ai?utm_medium=product&utm_source=aiagent&utm_campaign=fy26-glbl-ai-agent-poweredby",Mv=({style:e})=>{const{stringSet:t}=ie(),{handlers:n}=ue(),{conversation:r}=ae();return es("powered-by")?a.createElement(wv,{variant:"caption2",style:e},t.POWERED_BY+" ",a.createElement(kv,{variant:"caption2",forwardedAs:"a",href:Ho,...r.poweredByLink().props,rel:rs,target:"_blank",onClick:o=>{o.preventDefault(),n.onClickLink({url:Ho})}},"Sendbird")):null},wv=C.default(B)`color:${b.themedColor.textLowEmphasis};text-align:center;`,kv=C.default(B)`color:${b.themedColor.textLowEmphasis};cursor:pointer;text-decoration:none;`,Lv=()=>{var c;const{stringSet:e}=ie(),{conversation:t}=ae(),{channelSource:n,goToActiveConversation:r,scrollSource:s}=Ae(),o=Ne(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(Ov,null,a.createElement(Nv,{variant:"button",color:b.themedColor.textHighEmphasis,...t.startNewConversationButton({onActivate:r}).props},e.TALK_TO_AGENT))},Ov=C.default.div`display:flex;justify-content:center;margin-bottom:16px;`,Nv=C.default(B)`border-radius:6px;box-sizing:border-box;padding:10px 20px;cursor:pointer;user-select:none;background-color:${b.color.background50};border:1px solid ${b.color.onlight.textDisabled};${ne.dark`
|
|
402
403
|
background-color: ${b.color.background700};
|
|
403
404
|
border-color: ${b.color.ondark.textLowEmphasis};
|
|
404
405
|
`}
|
|
405
|
-
`,Av=({statsCallbacks:e,...t})=>(Eh(e),a.createElement(zb,{...t})),Tv=(e,t,n)=>t&&ke.isWelcomeMessage(e,n)&&ke.isWelcomeMessage(t,n)?!1:!Ic.isSameDay((t==null?void 0:t.createdAt)??0,e.createdAt),Iv=()=>{var V;const{Template:e}=Nt.useContext(),{Template:t}=_t.useContext(),{Template:n}=Hn.useContext(),{components:r}=zn.useContext(),{stringSet:s,format:o}=ie(),{announceError:i,announceStatus:c}=it(),{messageList:u}=ae().conversation,{config:d,cache:m,agentPreviewConfigs:h,chatSDK:f,handlers:g,state:p}=ue(),{userSession:v,aiAgentInfo:E,connectionError:_}=Ne(),{_statsEnabled:A,conversation:y,channelSource:T,messageSource:I,scrollSource:L,state:{input:N,streamAnimation:k}}=Ae(),{filteredMessages:R,shouldShowOriginalDate:G,renderAgentPreviewWelcomeMessages:D}=pv(),Q=_h({enabled:A}),ne=Qm(Oi(T.channel),el(R,v.userId)),[B,H]=l.useState(null),[q,Z]=l.useState(null),z=De(T.channel)?void 0:ne??k.heldTypingInfo;l.useEffect(()=>{L.actions.onTypingIndicatorUpdate(!!z)},[!!z,L.actions.onTypingIndicatorUpdate]),_v(),uv({enabled:I.initialized&&I.messages.length>0});const Y=w=>{var oe;return Fc(w,{aiAgentInfo:E,members:(oe=T.channel)==null?void 0:oe.members})},W=w=>{if(w.sendingStatus==="failed"&&!N.disabled)return()=>Z(w)},K=({message:w,index:oe})=>{const Se=Uc(w),xe=R[oe-1],Re=R[oe+1],$=R[R.length-1],M=w===$,x=Qe(w,E.userId),O=!(E.isUserFeedbackEnabled&&x&&!ke.isWelcomeMessage(w)),P=Bc(w,xe,Re,O),X=Tv(w,xe,E.userId)&&G(oe),re=pe=>{H({files:pe.files.map(Me=>({...Me,timestamp:w.createdAt})),index:pe.index})},J=pe=>{re({files:[pe],index:0})},Ee=X?a.createElement(r.DateSeparator,{role:"listitem",style:{margin:"16px 0"},date:w.createdAt}):null,$e={data:w.data,maxBodyWidth:p.expanded?se.WIDE_BODY_MAX_WIDTH:void 0,extendedMessagePayload:w.extendedMessagePayload,createdAt:w.createdAt,groupType:P,onClickMedia:J,onClickMediaFiles:re,onClickFile:g.onClickLink,onClickCTA:g.onClickLink,onClickCitation:pe=>g.onClickLink({url:pe.link}),onClickLink:g.onClickLink},Ct=()=>{if(we.isOutgoing(w,v.userId))return"outgoingmessage";if(we.isIncoming(w,v.userId))return"incomingmessage"},Pt=w.createdAt!=null&&w.createdAt!==0?o(w.createdAt,s.DATE_FORMAT__MESSAGE_TIMESTAMP):void 0,ce=(()=>{var Me;const pe=(Me=w.message)==null?void 0:Me.trim();return w.isFileMessage()||w.isMultipleFilesMessage()?vr(Gi(w,Ia(s))):pe?Vh({markdownText:pe}):vr("")})(),Ce=(()=>{if(we.isAdmin(w))return qt({message:ce.text,messageFormat:ce.format,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER});if(we.isOutgoing(w,v.userId))return qt({sender:s.A11Y_MESSAGE_SENDER_YOU,message:ce.text,messageFormat:"plain",time:Pt,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER});if(we.isIncoming(w,v.userId))return qt({sender:Y(w).nickname,message:ce.text,messageFormat:ce.format,time:Pt,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER})})(),he=(()=>{var pe,Me;if(we.isAdmin(w))return we.isCSAT(w)?y?a.createElement(n,{...$e,...y,isResolvedWhenDeterminedByUser:Al(y),messageType:"admin.csat",announceError:i,announceStatus:c,onSubmitCSAT:async Be=>{var He;await((He=T.channel)==null?void 0:He.submitCSAT(Be))},onScrollToBottom:()=>L.actions.scrollToBottom()}):null:a.createElement(n,{...$e,messageType:"admin",message:w.message});if(we.isSteward(w)){const Be=Q({message:w,isBotMessage:x,aiAgentUserId:E.userId});return a.createElement(Av,{steward:w.extendedMessagePayload.steward,statsCallbacks:Be,onCancelSteward:async()=>{await f.aiAgent.cancelStewardTask({channelUrl:w.channelUrl,messageId:w.messageId})}})}if(we.isOutgoing(w,v.userId)){const Be={...$e,message:w.message,sender:Y(w),sendingStatus:w.sendingStatus,onClickFailedMessage:W(w)};if(w.isUserMessage())return a.createElement(e,{messageType:"user",...Be});if(w.isFileMessage()){const[He,at]=((pe=w.metaArrays.find(ge=>ge.key===ri))==null?void 0:pe.value)??[];return a.createElement(e,{messageType:"file",file:w,metadata:{aspectRatio:He&&at?`${He}/${at}`:"1/1",localFile:(Me=w.messageParams)==null?void 0:Me.file},...Be})}if(w.isMultipleFilesMessage()){const{files:He,metadata:at}=Do(w);return a.createElement(e,{messageType:"multipleFiles",files:He,metadata:at,...Be})}}if(we.isIncoming(w,v.userId)){const Be=ke.isStreaming(w),He=Q({message:w,isBotMessage:x,aiAgentUserId:E.userId}),at={...$e,statsCallbacks:He,sender:Y(w),message:w.message,suggestedRepliesVisible:M,suggestedRepliesDirection:h==null?void 0:h.suggestedRepliesDirection,isBotMessage:x,isStreaming:Be,isHandedOff:ot(T.channel),isConversationClosed:De(T.channel),isFeedbackEnabled:E.isUserFeedbackEnabled,isFeedbackCommentEnabled:E.isUserFeedbackCommentOptionEnabled,isSenderAvatarVisible:d.conversation.list.senderAvatarEnabled,deferredMarkdownElements:d.conversation.list.deferredMarkdownElements,onClickSuggestedReply:async({reply:ge})=>{I.sendUserMessage({message:ge})},onRequestMessageTemplate:async ge=>{const{template:Ve}=await f.aiAgent.getMessageTemplate(ge);return m.template.set(ge,Ve),Ve},onGetCachedMessageTemplate:ge=>m.template.get(ge),onHandleTemplateInternalAction:ge=>{if(ge.type==="internal"&&ge.internalData){const{method:Ve,payload:rt}=ge.internalData;Ve==="message.send"&&(rt!=null&&rt.message)&&I.sendUserMessage({message:rt.message})}},onFeedbackUpdate:ge=>{const Ve={messageId:w.messageId,channelUrl:w.channelUrl};if(!ge)return f.aiAgent.deleteMessageFeedback(Ve);const rt={...Ve,rating:sE(ge.rating),comment:ge.comment};return ke.hasFeedback(w)?f.aiAgent.updateMessageFeedback(rt):f.aiAgent.createMessageFeedback(rt)},onSubmitForm:({key:ge,data:Ve})=>f.aiAgent.submitForm({messageId:w.messageId,channelUrl:w.channelUrl,formKey:ge,formData:Ve}),onCancelForm:({key:ge})=>f.aiAgent.cancelForm({messageId:w.messageId,channelUrl:w.channelUrl,formKey:ge}),onSendChallengeAction:({key:ge,requestId:Ve,action:rt,data:vc})=>f.aiAgent.sendChallengeAction({channelUrl:w.channelUrl,key:ge,requestId:Ve,action:rt,data:vc}),onStreamAnimationStart:()=>{k.start(w.messageId)},onStreamAnimationProgress:()=>{L.actions.onStreamingUpdate(!0)},onStreamAnimationComplete:()=>{k.stop(w.messageId),L.actions.onStreamingUpdate(!1)},onStreamAnimationHoldChange:ge=>{ge?k.holdStart(w.messageId,{user:Y(w),isBot:x}):k.holdStop(w.messageId)}};if(w.isUserMessage())return a.createElement(t,{messageType:"user",...at});if(w.isFileMessage())return a.createElement(t,{messageType:"file",file:w,...at});if(w.isMultipleFilesMessage()){const{files:ge}=Do(w);return a.createElement(t,{messageType:"multipleFiles",files:ge,...at})}}})(),fe=k.isHolding(w.messageId),Pe=u.item({label:Ce,holding:fe});return a.createElement(l.Fragment,{key:Se},Ee,a.createElement("div",{id:`${Ue}-message-item`,...Pe.props,"data-message-listitem":"","data-layout-id":Ct()},he))};return a.createElement(xv,{id:`${Ue}-message-list`},a.createElement(Dp,{ref:L.ref,onScroll:L.props.onScroll,stackDirection:h==null?void 0:h.messageStackDirection,messages:R,renderMessage:K,onLoadPrev:I.loadPrevious,onLoadNext:I.loadNext,depsForResetScrollPositionToBottom:[I.initialized,I.messages.length!==0],bottomSpacerHeight:L.state.bottomSpace,"aria-label":s.A11Y_MESSAGE_LIST,loading:!I.initialized||!T.channel,empty:R.length===0&&!z,error:!!(_||T.error),LoadingComponent:a.createElement(Kt,{type:"loading"}),EmptyComponent:(()=>{const w=D();return w?a.createElement("div",{style:{width:"100%"}},w):a.createElement(Kt,{type:"noMessages",label:s.PLACE_HOLDER__NO_MESSAGES})})(),ErrorComponent:a.createElement(Kt,{type:"error",label:(_==null?void 0:_.message)??((V=T.error)==null?void 0:V.message),action:T.error?{label:s.RETRY,onClick:()=>T.refetch()}:void 0}),messageTopArea:a.createElement(a.Fragment,null,a.createElement(Ev,{style:{marginTop:16}}),D()),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:R.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(vv,null)),overlayArea:a.createElement(a.Fragment,null,d.conversation.list.newMessageIndicatorEnabled&&L.state.isAwayFromBottom&&I.newMessages.length>0&&a.createElement(Rv,{label:s.SCROLL_TO_NEW_MESSAGES_LABEL(I.newMessages),onClick:()=>L.actions.scrollToBottom()}),L.state.isAwayFromBottom&&I.newMessages.length===0&&!z&&a.createElement(r.ScrollToBottomButton,{onClick:()=>L.actions.scrollToBottom(),style:{position:"absolute",bottom:12,insetInlineEnd:16}}))}),B&&a.createElement(Gp,{files:B.files,initialIndex:B.index,onClose:()=>H(null),visible:!0}),q&&a.createElement(lt,{visible:!0,onClose:()=>Z(null),"aria-label":s.A11Y_FAILED_MESSAGE_OPTIONS},a.createElement(lt.ActionItem,{onClick:()=>{I.resendMessage(q),Z(null)}},s.FAILED_MESSAGE_RESEND),a.createElement(lt.ActionItem,{destructive:!0,onClick:()=>{I.deleteMessage(q),Z(null)}},s.FAILED_MESSAGE_REMOVE)))},xv=C.default.div`overflow-y:hidden;display:flex;flex:1;position:relative;`,Rv=C.default(Jb)`position:absolute;bottom:12px;left:50%;transform:translateX(-50%);`,Mv=()=>a.createElement(Iv,null),Fo={file:"attach",snippet:"snippet",site:"website",sb_sprinklr:"sprinklr",sb_salesforce:"salesforce",sb_confluence:"confluence",sb_zendesk:"zendesk",sb_desk:"snippet"},Wa=({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=Yt.DEFAULT_PRIMARY}=g;return a.createElement(Uo,null,m,e&&a.createElement(Uo,null,a.createElement(wn,null,a.createElement(Bt,null,a.createElement(ee,{size:16,type:"actionbook",color:p})),a.createElement(gn,{$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(Cn,{key:_.key},a.createElement(Bt,null,a.createElement(ee,{size:16,type:"function",color:p})),a.createElement(wn,null,a.createElement(gn,{$clickable:!!i,$highlightColor:E,variant:"body2",color:v,onClick:()=>i==null?void 0:i(_),maxTextLines:1},_.name),c&&a.createElement(wv,{role:"button",onClick:()=>c==null?void 0:c(_)},a.createElement(U,{variant:"body2",color:E},"View details"),a.createElement(ee,{type:"chevron-right",size:16,color:E}))))),n==null?void 0:n.map(_=>a.createElement(Cn,{key:_.id},a.createElement(Bt,null,f({default:a.createElement(ee,{size:16,type:Fo[_.source_type]??Fo.snippet,color:p}),sourceType:_.source_type})),a.createElement(gn,{$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(Cn,{key:_.key},a.createElement(Bt,null,a.createElement(ee,{size:16,type:"template",color:p})),a.createElement(gn,{$clickable:!!d,$highlightColor:E,variant:"body2",color:v,onClick:()=>d==null?void 0:d(_),maxTextLines:1},_.name))),!!(s!=null&&s.length)&&a.createElement(kv,null,a.createElement(Bt,null,a.createElement(ee,{size:16,type:"activity",color:p})),a.createElement(Lv,{variant:"body2",color:v},s.map(_=>_.replace(/_/g," ")).join(" · "))),h)},ja=C.default(U)`font-weight:400;`,gn=C.default(ja)`${({$clickable:e,$highlightColor:t})=>e&&F.css`
|
|
406
|
+
`,Dv=({statsCallbacks:e,...t})=>(xh(e),a.createElement(ev,{...t})),$v=(e,t,n)=>t&&we.isWelcomeMessage(e,n)&&we.isWelcomeMessage(t,n)?!1:!Lc.isSameDay((t==null?void 0:t.createdAt)??0,e.createdAt),Pv=()=>{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}=xv(),re=Ih({enabled:y}),G=ch(Fi(I.channel),il(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]),Rv(),vv({enabled:N.initialized&&N.messages.length>0});const W=w=>{var _e;return Vc(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=Kc(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=qc(w,Te,$,P),oe=$v(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?Qh({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:wl(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(Dv,{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:fE(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:xc})=>f.aiAgent.sendChallengeAction({channelUrl:w.channelUrl,key:de,requestId:Pe,action:ot,data:xc}),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(Fv,{id:`${Ue}-message-list`},a.createElement(Vp,{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(Mv,{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(Lv,null)),overlayArea:a.createElement(a.Fragment,null,d.conversation.list.newMessageIndicatorEnabled&&O.state.isAwayFromBottom&&N.newMessages.length>0&&a.createElement(Uv,{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(Zp,{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)))},Fv=C.default.div`overflow-y:hidden;display:flex;flex:1;position:relative;`,Uv=C.default(lv)`position:absolute;bottom:12px;left:50%;transform:translateX(-50%);`,Bv=()=>a.createElement(Pv,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(Hv,{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(Gv,null,a.createElement(Bt,null,a.createElement(ee,{size:16,type:"activity",color:p})),a.createElement(zv,{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
407
|
cursor: pointer;
|
|
407
408
|
text-decoration: underline;
|
|
408
409
|
&:hover {
|
|
409
410
|
color: ${t};
|
|
410
411
|
}
|
|
411
412
|
`}
|
|
412
|
-
`,Bt=C.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,
|
|
413
|
+
`,Bt=C.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,On=C.default.div`display:flex;gap:8px;align-items:center;word-break:break-word;`,Hv=C.default(On)`cursor:pointer;gap:4px;`,vn=C.default(On)`flex-direction:row;align-items:center;`,Gv=C.default(vn)`align-items:flex-start;max-width:100%;`,zv=C.default(ec)`min-width:0;`,zo=C.default.div`display:flex;gap:4px;flex-direction:column;align-items:flex-start;`,Vv=e=>{const t=e.replace(/[_-]+/g," ").trim().toLowerCase();return t?t.charAt(0).toUpperCase()+t.slice(1):""},tc=({prechecks:e,maxBodyWidth:t})=>{const{theme:n}=Fn();return e.length===0?null:a.createElement(Kv,{id:`${We}-ext-prechecks`},a.createElement(qv,{$maxWidth:t??se.BODY_MAX_WIDTH},e.map(r=>a.createElement(Wv,{key:r.key},a.createElement(Yv,{type:"done-circle",size:16,color:b.themedColor.secondary}),a.createElement(B,{variant:"caption2",color:n.colors.messageIncoming.text},Vv(r.key))))))},Kv=C.default.div`align-self:stretch;padding-block-end:8px;padding-inline-start:${se.HORIZONTAL_PADDING+se.AVATAR_SIZE}px;padding-inline-end:${se.HORIZONTAL_PADDING}px;`,qv=C.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};`,Wv=C.default.div`display:flex;align-items:center;gap:6px;min-width:0;overflow-wrap:anywhere;`,Yv=C.default(ee)`flex-shrink:0;`,nc=be("DashboardTester"),jv=nc.Provider;function Xv({testerType:e,origin:t,children:n}){return a.createElement(jv,{value:{testerType:e,origin:t}},e&&a.createElement(Zv,null),n)}const rc=nc.useContext,Zv=()=>a.createElement(a.Fragment,null,a.createElement(ht.Prechecks,{component:Jv}),a.createElement(ht.MessageLogs,{component:Vo}),a.createElement(Dt.MessageLogs,{component:Vo})),Jv=({extendedMessagePayload:e={},maxBodyWidth:t})=>a.createElement(tc,{prechecks:e.prechecks??[],maxBodyWidth:t}),Vo=({extendedMessagePayload:e={}})=>{const{handlers:t}=ue(),{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(Qv,null,a.createElement(eS,{$width:4}),a.createElement(Qa,{actionbook:n,functionCalls:s,groundedness:r,agentMessageTemplates:o,flaggedTypes:i,onClickFunctionCallDetail:t==null?void 0:t.onFunctionCallDetailClick,style:{iconColor:b.themedColor.textHighEmphasis,textColor:b.themedColor.textHighEmphasis,barColor:b.themedColor.textDisabled},topContent:a.createElement(B,{variant:"caption4",color:b.themedColor.textLowEmphasis},"Only visible in the tester")}))},Qv=C.default.div`display:flex;gap:16px;margin:6px ${se.HORIZONTAL_PADDING}px 4px ${se.HORIZONTAL_PADDING+se.AVATAR_SIZE}px;align-self:stretch;`,eS=C.default.div`width:${({$width:e})=>e}px;background-color:${b.themedColor.textDisabled};border-radius:100px;flex-shrink:0;`,tS=()=>{var s;const{origin:e}=rc(),{appId:t,aiAgentId:n}=ye(),{channelSource:r}=Ae();return(s=r.channel)!=null&&s.conversation?a.createElement(nS,null,a.createElement(Dr,{style:{gap:4}},a.createElement(ee,{color:b.themedColor.textLowEmphasis,size:12,type:"show"}),a.createElement(B,{as:"i",color:b.themedColor.textLowEmphasis,variant:"caption2"},"Only visible in the tester")),a.createElement(Dr,{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:b.themedColor.textHighEmphasis},"Copy ",a.createElement("span",{style:{color:b.themedColor.primary}},"conversation link")),a.createElement(ee,{color:b.themedColor.primary,size:14,type:"copy"}))):null},Dr=C.default.div`display:flex;justify-content:center;align-items:center;`,nS=C.default(Dr)`flex-direction:column;padding-block:16px;background-color:${b.themedColor.bg_100_500};gap:8px;`,rS=(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}},sc=l.createContext(void 0),sS=({children:e})=>{var Q,re;const{chatSDK:t}=ue(),{createAttachmentRules:n}=Oe(),{stringSet:r}=ie(),{channelSource:s,state:o}=Ae(),[i,c]=l.useState([]),{announceError:u}=is(),[d,m]=l.useState(null),h=n({channel:s.channel,uploadSizeLimit:(Q=t.appInfo)==null?void 0:Q.uploadSizeLimit}),f=((re=o==null?void 0:o.input)==null?void 0:re.disabled)??!1,g=h.isEnabled(),p=h.maxAttachmentCount,v=()=>m(null),E=G=>m(G),_=()=>{E({title:r.FILE_UPLOAD_NOTIFICATION__COUNT_LIMIT.replace("%d",p.toString())})},A=G=>{E({title:r.FILE_UPLOAD_NOTIFICATION__SIZE_LIMIT.replace("%d",G.toString())}),u({type:"fileSizeExceeded",maxSizeMB:G})},y=G=>{E({title:r.FILE_UPLOAD_NOTIFICATION__FILES_EXCLUDED_BY_VALIDATION.replace("%d",G.toString())})},T=G=>G.map(H=>({file:H,preview:{url:URL.createObjectURL(H),type:H.type,name:H.name}})),I=G=>{c(H=>[...H,...T(G)])},N=G=>{c(H=>(H.forEach(K=>URL.revokeObjectURL(K.preview.url)),T(G)))},O=G=>{const{passed:H,failedBySize:K,failedByType:J}=rS(G,h),q=K.length+J.length,z=G.length===1?K[0]:void 0;return z?A(h.getUploadSizeLimitInMB(z.type)):q>0&&y(q),H},k=G=>{const H=O(G.files);H.length!==0&&(G.type==="append"?I(H):N(H))},R=G=>{if(!g||f||!yd(G))return;const H=Td({currentFiles:i.map(({file:K})=>K),incomingFiles:G,maxAttachmentCount:p});switch(H.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:()=>k(H.action)});return;case"apply":k(H.action);return}},F=G=>{c(H=>{var J;const K=(J=H[G])==null?void 0:J.preview;return K&&URL.revokeObjectURL(K.url),H.filter((q,z)=>z!==G)})},D=()=>{c(G=>(G.forEach(H=>URL.revokeObjectURL(H.preview.url)),[]))};return a.createElement(sc.Provider,{value:{files:i,addFiles:R,removeFile:F,clearFiles:D,isFileUploadEnabled:g,acceptableMimeTypes:h.supportedMimeTypes,maxAttachmentCount:h.maxAttachmentCount,showFileUploadAlert:E}},e,a.createElement(nn,{visible:!!d,...d??{},onClose:v}))},_s=()=>{const e=l.useContext(sc);if(!e)throw new Error("useFileUpload must be used within FileUploadProvider");return e};function oS({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 iS({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 aS=()=>{const{announceError:e}=ct();return l.useCallback(t=>{e({type:"sendFailed"},t)},[e])},cS=1e3,lS=(e,t,n)=>{const{announcementsEnabled:r,setIsSuppressed:s}=ct(),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]),lh(t,u,{enabled:o,idleMs:cS})},uS=({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}}},dS=C.default.div`&::-webkit-scrollbar{display:none;}overflow-x:auto;display:flex;flex-direction:row;gap:10px;padding:8px 16px;background-color:transparent;`,mS=C.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;}`,hS=C.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`
|
|
413
414
|
background-color: ${b.color.background50};
|
|
414
415
|
`}
|
|
415
|
-
${
|
|
416
|
+
${ne.dark`
|
|
416
417
|
background-color: ${b.color.background500};
|
|
417
418
|
`}
|
|
418
419
|
path {
|
|
@@ -434,7 +435,7 @@ $2
|
|
|
434
435
|
circle {
|
|
435
436
|
stroke: ${b.themedColor.bg_50_600};
|
|
436
437
|
}
|
|
437
|
-
`,
|
|
438
|
+
`,fS=()=>{const e=tn(),{conversation:t}=ae(),{files:n,removeFile:r,isFileUploadEnabled:s}=_s();return s&&n.length>0?a.createElement(dS,null,n.map(({preview:{type:i,name:c,url:u}},d)=>{let m=a.createElement(ds,{name:c,mimeType:i,type:Ur(c,i),selected:!0});return i.startsWith("image/")&&(m=a.createElement("img",{alt:t.file.label(c,i,!0),src:u})),a.createElement(mS,{key:u},a.createElement(hS,{type:"button",...t.file.removeButton(c).props,$mobile:e,onClick:()=>r(d)},a.createElement(ee,{type:"close-filled",color:b.themedColor.textMidEmphasis})),m)})):null},gS={textArea:U.css`min-height:40px;height:40px;font-size:16px;line-height:24px;`},oc=C.default.button`all:unset;cursor:pointer;display:flex;align-items:center;justify-content:center;width:32px;height:32px;${xe}`,Ko=C.default.div`width:100%;position:relative;background-color:${({theme:e})=>e.colors.messageInput.background};border-radius:20px;`,qo=C.default.div`display:flex;flex-direction:row;align-items:flex-end;position:relative;`,Wo=C.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:${ra}px;overflow-wrap:break-word;white-space:pre-wrap;overflow-x:hidden;${Ca&&gS.textArea};${({$focusVisible:e})=>e&&U.css`
|
|
438
439
|
outline: 2px solid ${b.themedColor.primary};
|
|
439
440
|
outline-offset: 2px;
|
|
440
441
|
`}
|
|
@@ -450,18 +451,18 @@ $2
|
|
|
450
451
|
}
|
|
451
452
|
}
|
|
452
453
|
|
|
453
|
-
${({$blocked:e})=>e&&
|
|
454
|
-
`,
|
|
454
|
+
${({$blocked:e})=>e&&U.css`cursor:not-allowed;&::placeholder{color:${b.themedColor.textDisabled};}`}
|
|
455
|
+
`,pS=C.default.input`display:none;`;C.default.div`display:flex;align-items:center;gap:24px;`;const _S=C.default(oc)`flex-shrink:0;border-radius:8px;&:disabled{cursor:not-allowed;}&:not(:disabled){&:hover{background-color:${b.themedColor.bg_100_500};path{fill:${b.themedColor.textHighEmphasis};}}&:active{background-color:${b.themedColor.bg_200_400};}}`,Yo=C.default.div`padding:10px 16px 10px 12px;position:relative;display:flex;align-items:center;gap:8px;`,jo=e=>e.startsWith("image/"),Xo=({disabled:e})=>{const{stringSet:t}=ie(),{conversation:n}=ae(),{config:r}=ue(),s=l.useRef(null),o=l.useRef(null),[i,c]=l.useState(!1),{addFiles:u,isFileUploadEnabled:d,acceptableMimeTypes:m,showFileUploadAlert:h}=_s(),f=m.includes(_r),g=f?["image/*"]:m.filter(jo),p=f?[_r]:m.filter(O=>!jo(O)),v=r.conversation.input.gallery.photoEnabled,E=r.conversation.input.fileEnabled,_=()=>f||g.length>0,A=()=>f||p.length>0,y=O=>{const k=O.currentTarget.files;k&&u(Array.from(k)),O.target.value=""},T=()=>{c(!0)},I=l.useMemo(()=>{const O=[];return v&&O.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 k;return(k=s.current)==null?void 0:k.click()},100)}}),E&&O.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 k;return(k=o.current)==null?void 0:k.click()},100)}}),O},[g,m,t,v,E]);if(!d)return null;const N={attach:n.messageInput.attachFileButton()};return a.createElement(a.Fragment,null,a.createElement(_S,{...N.attach.props,disabled:e,onClick:T},a.createElement(ee,{type:"add",color:e?b.themedColor.textDisabled:b.color.primary.main,size:20}),N.attach.descriptionNode),I.map(O=>a.createElement(pS,{key:O.type,type:"file",ref:O.inputRef,multiple:O.type==="image",onChange:y,accept:O.accept})),a.createElement(dt,{visible:i,onClose:()=>c(!1),"aria-label":t.A11Y_FILE_UPLOAD_OPTIONS},I.map(O=>a.createElement(dt.ActionItem,{key:O.type,onClick:O.onSelect,icon:O.icon},O.label))))},ES=()=>{const e=l.useRef(null),[t,n]=l.useState(""),{stringSet:r}=ie(),{conversation:s}=ae(),{rootElement:o}=ue(),i=mt(o),{focusHandlers:c,isFocusVisible:u,suppressNextFocusVisible:d}=uS({focusRoot:i}),{channelSource:m,messageSource:h,state:f}=Ae(),{files:g,addFiles:p,clearFiles:v}=_s(),E=aS(),{focusPolicy:_,disabled:A,disabledBy:y}=f.input,T=_==="preserve",I=_==="release",N=(()=>{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}})();up({onDropFiles:V=>{p(V)}}),iS({blurred:I,elementRef:e,document:i,onRecoverFocus:()=>{d()}}),lS(m.channel,t,!A);const O=t.trim().length>0,k=g.length>0,R=!A&&(O||k),F={input:s.messageInput.textInput(r.A11Y_MESSAGE_INPUT),send:s.messageInput.sendButton()},D=()=>{e.current&&(e.current.value="",e.current.style.height=""),v(),n("")},Q=()=>{var V;d(),(V=e.current)==null||V.focus()},{requestRestore:re,cancelRestore:G}=oS({elementRef:e,ready:T,onRestore:d}),H=V=>{G(),E(V)},K=()=>{G()},J=async V=>{try{await V(),K()}catch{H(e.current)}},q=async()=>{if(A)return;const V=t.trim();if(!V&&!g.length)return;const te=[...g];if(re(),D(),Q(),te.length===0){await J(()=>h.sendUserMessage({message:V}));return}if(te.length===1)await J(()=>h.sendFileMessage({message:V,file:te[0].file}));else{const w=te.map(({file:_e})=>({file:_e}));await J(()=>h.sendMultipleFilesMessage({message:V,fileInfoList:w}))}},z=V=>{const te=Array.from(V.clipboardData.files);te.length>0&&(V.preventDefault(),p(te))},W=V=>{V.key!=="Enter"||V.nativeEvent.isComposing||V.shiftKey||(V.preventDefault(),q())},Y=V=>{if(A){e.current&&(e.current.value=t);return}if(e.current){e.current.style.height="";const te=Math.min(vf,e.current.scrollHeight);ra<te&&(e.current.style.height=`${te}px`)}n(V.target.value)};return I?a.createElement(Yo,null,a.createElement(Xo,{disabled:!0}),a.createElement(Ko,null,a.createElement(qo,null,a.createElement(Wo,{rows:1,...F.input.props,disabled:!0,placeholder:N,$blocked:!0,$focusVisible:!1,"data-focus-visible":"false"})))):a.createElement(Yo,{"data-message-composer":""},a.createElement(Xo,{disabled:A}),a.createElement(Ko,null,a.createElement(fS,null),a.createElement(qo,null,a.createElement(Wo,{ref:e,rows:1,...F.input.props,readOnly:T,"aria-disabled":T?"true":void 0,placeholder:N,maxLength:5e3,$blocked:A,$focusVisible:u,"data-focus-visible":u?"true":"false",onKeyDown:W,onChange:Y,onFocus:c.onFocus,onBlur:c.onBlur,onPaste:z}))),R&&a.createElement(oc,{...F.send.props,onClick:()=>q()},a.createElement(ee,{type:"send",color:b.color.primary.main,size:20}),F.send.descriptionNode))},CS=C.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:${b.themedColor.textLowEmphasis};&& a{font-weight:700;text-decoration:none;${ne.light`
|
|
455
456
|
color: ${b.color.information.light};
|
|
456
457
|
`};
|
|
457
|
-
${
|
|
458
|
+
${ne.dark`
|
|
458
459
|
color: ${b.color.information.main};
|
|
459
460
|
`};
|
|
460
461
|
}
|
|
461
|
-
`,rS=l.lazy(()=>Promise.resolve().then(()=>require("./cjs/6HoSeQJQ.cjs")).then(e=>({default:e.MarkdownText}))),sS=()=>{const{aiAgentInfo:e,userSession:t}=Ne(),{handlers:n}=ue(),{messageSource:r,channelSource:s}=Ae(),[o,i]=l.useState(null),c=Zr("special-notice",s.channel),u=l.useCallback(()=>s.channel?c?r.messages.some(d=>Qe(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(nS,null,a.createElement(rS,{onClickLink:n.onClickLink},e.specialNotice))},oS=()=>a.createElement(iS,null,a.createElement(sS,null),a.createElement(Hv,null,a.createElement(tS,null))),iS=C.default.div`z-index:0;border:none;width:100%;`,aS=()=>{var s;const{testerType:e}=Za(),{channelSource:t}=Ae(),n=De(t.channel),r=!!e&&((s=t.channel)==null?void 0:s.isAIAgent);return n&&r?a.createElement(Fv,null):a.createElement(oS,null)},ec=({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(cS,{...s},a.createElement(lS,null,n==="center"&&t&&a.createElement(uS,{$sideWidth:Math.max(c,d)},a.createElement(dS,null,t)),a.createElement(mS,null,a.createElement(hS,{ref:o},e),(n==="start"||n==="end")&&t&&a.createElement(gS,{$align:n,$hasStart:!!e,$hasEnd:!!r},t),a.createElement(fS,{ref:i},r))))},cS=C.default.div`position:relative;width:100%;background-color:${({theme:e})=>e.colors.base.headerBackground};border-bottom:1px solid ${b.themedColor.textDisabled};`,lS=C.default.div`position:relative;height:56px;padding:11px 12px;`,uS=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;`,dS=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;`,hS=C.default.div`flex-shrink:0;display:flex;align-items:center;`,fS=C.default.div`flex-shrink:0;display:flex;align-items:center;`,gS=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;`,Dt=(e=16)=>tn()?e*1.5:e,pS=()=>{const{state:e}=ue(),{messenger:t}=ae(),n=Dt(),r=()=>{e.setOpened(!1)};return a.createElement(tt,{...t.closeButton().props,type:"close",size:n,onClick:r})},_S=()=>{const{enableCloseConversationButton:e,dispatcher:t}=ue(),{channelSource:n}=Ae(),{conversation:r}=ae(),s=n.channel,o=Dt(),i=(s==null?void 0:s.isAIAgent)&&e,c=!Fr(s);if(!i)return null;const u={close:r.header.closeConversationButton()},d=async()=>{s&&await t.send(st.CloseConversation({channelUrl:s.url}))};return a.createElement(a.Fragment,null,a.createElement(tt,{...u.close.props,type:"mute",size:o,disabled:c,onClick:d}),u.close.descriptionNode)},ES=()=>{const{state:e,enableExpandButton:t}=ue(),{messenger:n}=ae(),r=Dt();return t?a.createElement(tt,{...n.expandButton(e.expanded).props,type:e.expanded?"collapse":"expand",size:r,onClick:()=>e.setExpanded(!e.expanded)}):null},CS=({label:e,children:t,position:n="top",disabled:r})=>r?t:a.createElement(Lr,null,t,a.createElement(SS,{$position:n},a.createElement(yS,{variant:"caption1"},e),a.createElement(bS,{$position:n}))),bS=({$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})),vS={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%);`},Lr=C.default.div`position:relative;`,SS=C.default.div`display:flex;align-items:center;position:absolute;left:50%;z-index:${gt.TOOLTIP};${({$position:e})=>vS[e]}opacity:0;transition:opacity 0.2s ease-in-out;pointer-events:none;${Lr}:hover &,${Lr}:focus-within &{opacity:1;}`,yS=C.default(U)`padding:6px 8px;background:${b.themedColor.textHighEmphasis};color:${b.themedColor.textHighEmphasisInverse};border-radius:4px;font-size:12px;white-space:nowrap;`,AS=2e3,Yo=0,TS=1500,pn=Symbol("header-focus-status-pause"),Wo="data-sb-header-focus-protected",IS="[data-message-composer]",jo=new WeakMap,dr=e=>{const t=jo.get(e);if(t)return t;const n={focusedTargetIds:new Set,pendingBlurTimeouts:new Map,maxPauseTimeout:null};return jo.set(e,n),n},mr=(e,t)=>{const n=e.pendingBlurTimeouts.get(t);n&&(clearTimeout(n),e.pendingBlurTimeouts.delete(t))},bn=e=>{e.maxPauseTimeout&&(clearTimeout(e.maxPauseTimeout),e.maxPauseTimeout=null)},xS=e=>{e.pendingBlurTimeouts.forEach(t=>clearTimeout(t)),e.pendingBlurTimeouts.clear(),e.focusedTargetIds.clear(),bn(e)},RS=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)})},MS=e=>e instanceof HTMLBodyElement||(e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&e.disabled?!0:(e instanceof HTMLElement&&e.closest(IS),!1),gs=()=>{const{setStatusPauseState:e}=it(),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()+TS,o();const u=dr(e);mr(u,t.current),u.focusedTargetIds.add(t.current),u.focusedTargetIds.size===1&&e(pn,!0),bn(u),u.maxPauseTimeout=setTimeout(()=>{xS(u),e(pn,!1)},AS)},[o,e]),c=l.useCallback(u=>{if(!n.current)return;n.current=!1;const d=u.currentTarget,m=dr(e),h=d instanceof HTMLElement&&Date.now()<=r.current;mr(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(Wo);if(g===d||p||!MS(g))return;const v=RS(d);d.focus({preventScroll:!0}),v()},Yo)),m.pendingBlurTimeouts.set(t.current,setTimeout(()=>{m.pendingBlurTimeouts.delete(t.current),m.focusedTargetIds.delete(t.current),m.focusedTargetIds.size===0&&(bn(m),e(pn,!1))},Yo))},[o,e]);return l.useEffect(()=>()=>{const u=dr(e);n.current=!1,o(),mr(u,t.current),u.focusedTargetIds.delete(t.current)&&u.focusedTargetIds.size===0&&(bn(u),e(pn,!1))},[o,e]),{[Wo]:"true",onFocus:i,onBlur:c}},wS=()=>{const{logger:e}=ue(),{stringSet:t}=ie(),{channelSource:n}=Ae(),{conversation:r}=ae(),s=n.channel,o=Dt(),i=Zr("handoff-button",s),c=!Fr(s)||ot(s),[u,d]=l.useState(!1),m=gs(),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(CS,{label:t.HEADER_BUTTON__AGENT_HANDOFF,position:"bottom",disabled:c},a.createElement(tt,{...f.handoff.props,type:"agent",size:o,disabled:c,...m,onClick:()=>d(!0)})),f.handoff.descriptionNode),a.createElement(mt,{portalContainerId:ve.WINDOW,visible:u,onClose:()=>d(!1)},a.createElement(ms,{title:t.HANDOFF_CONFIRM__TITLE,description:t.HANDOFF_CONFIRM__DESCRIPTION,negativeText:t.HANDOFF_CONFIRM__CANCEL,positiveText:t.HANDOFF_CONFIRM__HANDOFF,onCancel:()=>d(!1),onConfirm:h})))},kS=l.lazy(()=>Promise.resolve().then(()=>require("./cjs/6HoSeQJQ.cjs")).then(e=>({default:e.MarkdownText}))),LS=()=>{const{logger:e,_aiAgentSDK:t}=ue(),{stringSet:n}=ie(),{memoryInfo:r,sdkUser:s}=Ne(),{actions:o}=Ae(),{conversation:i}=ae(),c=Dt(20),u=gs(),[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($S,{...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(PS,{$enabled:r.enabled})),p.descriptionNode),d&&a.createElement(OS,{memoryInfo:d,onClose:E,onSetEnabled:_,trackMemory:v}),a.createElement(Fn,{visible:h,title:n.PLACE_HOLDER__WRONG,description:n.MEMORY__ERROR_MESSAGE,onClose:()=>f(!1)}))},OS=({memoryInfo:e,onClose:t,onSetEnabled:n,trackMemory:r})=>{var _;const{stringSet:s}=ie(),{colors:o}=F.useTheme(),i=l.useId(),c=l.useId(),u=hd(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(mt,{visible:!0,portalContainerId:ve.WINDOW,onClose:g,cancelable:!d,"aria-labelledby":i,"aria-describedby":c},a.createElement(ms,{title:s.MEMORY__DIALOG_TITLE,titleId:i,description:a.createElement(NS,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}}))},NS=({children:e})=>{const{handlers:t}=ue();return a.createElement(FS,null,a.createElement(Wt,{fallback:e},a.createElement(kS,{onClickLink:t.onClickLink},e)))},DS=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;`,$S=C.default.button`${DS};cursor:pointer;${Ie}`,PS=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};${te.dark`
|
|
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}=rc(),{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)},ic=({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=Sd(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`
|
|
462
463
|
box-shadow: 0 0 0 2px ${b.color.background500};
|
|
463
464
|
`}
|
|
464
|
-
`,
|
|
465
|
+
`,ty=C.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;}`,ny=()=>{const{conversation:e}=ae(),{onNavigateToConversationList:t}=Ae();if(!t)return null;const n={menu:e.header.menuButton()};return a.createElement(a.Fragment,null,a.createElement(nt,{...n.menu.props,...Xi,type:"menu",size:24,onClick:()=>t()}),n.menu.descriptionNode)},ac=({channel:e,size:t=40,skeletonColor:n=b.themedColor.bg_100_500})=>{const{userSession:r,aiAgentInfo:s}=Oe(),{fallbackIcon:o,url:i}=ts({channel:e,aiAgentInfo:s,userSession:r}),[c,u]=l.useState();c&&c.url!==i&&u(void 0);const d=U.useTheme(),{primary:m,primaryContrastContent:h}=d.colors.base;if(!o)return a.createElement(ei,{"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(Pa,{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(ei,{"aria-hidden":"true",$size:t,$bgColor:m},a.createElement(ee,{type:o,size:t*.55,color:h}))},ei=C.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;`,ry=e=>{const{channelSource:t}=Ae(),{aiAgentInfo:n,userSession:r}=Oe(),{conversation:s}=ae(),{config:o}=ye(),{announcementsEnabled:i}=ct(),c=U.useTheme(),u=t.channel,d=ts({channel:u,userSession:r,aiAgentInfo:n}),m=e.title??d.title,h=o.conversation.header.avatarEnabled,f=Es(),g=xa({enabled:i,label:m}),p={title:s.header.title(m,{active:g.enabled,titleId:g.id,initialFocus:!1})};return a.createElement(sy,null,h&&a.createElement(ac,{channel:u,size:34,skeletonColor:c.colors.conversation.headerProfileSkeleton}),a.createElement(oy,{...p.title.props,...f},m))},sy=C.default.div`display:flex;flex-direction:row;align-items:center;gap:6px;min-width:0;width:100%;overflow:hidden;`,oy=C.default(B).attrs({variant:"h2",color:b.themedColor.textHighEmphasis})`
|
|
465
466
|
margin: 0;
|
|
466
467
|
flex: 1;
|
|
467
468
|
min-width: 0;
|
|
@@ -473,10 +474,10 @@ $2
|
|
|
473
474
|
&:focus {
|
|
474
475
|
outline: none;
|
|
475
476
|
}
|
|
476
|
-
`,
|
|
477
|
+
`,iy=e=>{const{components:t}=bt.useContext();return a.createElement(ic,{start:a.createElement(t.StartArea,null),title:a.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:a.createElement(t.EndArea,null),containerProps:Qi})},ay=()=>{const{components:e}=bt.useContext();return a.createElement(e.MenuButton,null)},cy=()=>{const{components:e}=bt.useContext();return a.createElement(e.Title,null)},ly=()=>{const{components:e}=bt.useContext();return a.createElement(dy,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))},bt=qe({template:iy,components:{StartArea:ay,TitleArea:cy,EndArea:ly,MenuButton:ny,Title:ry,MemoryIndicator:jS,HandoffButton:WS,ConversationCloseButton:NS,ExpandButton:DS,CloseButton:OS}}),uy=()=>{const{Template:e}=bt.useContext();return a.createElement(e,{titleAlign:"start"})},dy=C.default.div`display:flex;gap:10px;align-items:center;justify-content:center;`,Cs=({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}=Wn.useContext();return a.createElement(Aa,{onNavigateToConversationList:t,channelUrl:n??h,onClearChannelUrl:r??f,conversationStatsEnabled:u,shouldMarkAsRead:s,shouldInitializeConversation:o,initialUserMessage:i},a.createElement(wr,null,a.createElement(wr.Consumer,null,p=>a.createElement(fg,{announcementsEnabled:c},a.createElement(my,null),a.createElement(hy,null),a.createElement(fy,{style:m,dragHandlers:p,initialFocusTarget:d},a.createElement(g,null)),e))))},my=()=>(fp(),null),hy=()=>(Rp(),Cp(),Tp(),null),fy=({style:e,dragHandlers:t,initialFocusTarget:n,children:r})=>{const s=l.useRef(null);return hp(s,n),a.createElement(py,{ref:s,style:e,...t},r)},gy=e=>{const{components:t}=Wn.useContext();return a.createElement(a.Fragment,null,a.createElement(t.Header,null),a.createElement(t.Body,null),a.createElement(t.Footer,null))},Wn=qe({template:gy,components:{Header:uy,Body:Bv,Footer:AS}}),py=C.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,cc=be("ConversationListAnnouncements",{announcementsEnabled:!0,announceScreenEntry:me}),_y=cc.Provider,bs=cc.useContext,Ey=({children:e,announcementsEnabled:t=!0})=>{const{announceScreenEntry:n}=is(),r=l.useCallback(o=>{t&&n(o)},[n,t]),s=l.useMemo(()=>({announcementsEnabled:t,announceScreenEntry:r}),[t,r]);return a.createElement(_y,{value:s},e)},{Provider:Cy,Context:by,useContext:sn}=be("ConversationList");function lc({conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:n,onOpenConversationView:r=me,children:s}){return a.createElement(zm,{conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:n},o=>a.createElement(Cy,{value:{...o,onOpenConversationView:r}},s))}const vy=e=>{const{announcementsEnabled:t}=bs(),{listSource:n}=sn(),r=ca();Ra(e,{enabled:t,ready:n.initialized,suppressed:r})},Sy=()=>{const{announceScreenEntry:e,announcementsEnabled:t}=bs(),{listSource:n}=sn(),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])},yy=({channel:e})=>a.createElement(ac,{channel:e}),Pr=99,Ay=e=>{var E,_;const{channel:t,onClick:n}=e,{stringSet:r,format:s}=ie(),{userSession:o,aiAgentInfo:i}=Oe(),{conversationList:c}=ae(),u=ts({channel:t,userSession:o,aiAgentInfo:i}),d=gd(t,{formatMultipleFilesCount:r.CONVERSATION_LIST__MULTIPLE_FILES_COUNT}),m=_d(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=Ne(t)?r.CONVERSATION_LIST__ENDED:"",p=n?()=>n():void 0,v=c.item({agent:f,status:g,lastMessage:d,time:m,unreadCount:h,onActivate:p});return a.createElement(Ty,{"data-testid":"sb-conversation-list-item",$clickable:!!p,...v.props},a.createElement(Iy,null,a.createElement(yy,{...e})),a.createElement(xy,null,a.createElement(Ry,null,(_=t.lastMessage)!=null&&_.isFileMessage()&&(!t.lastMessage.message||t.lastMessage.name===t.lastMessage.message)?a.createElement(Na,{variant:"subtitle1",color:b.themedColor.textHighEmphasis},d):a.createElement(B,{variant:"subtitle1",color:b.themedColor.textHighEmphasis,maxTextLines:1},d),a.createElement(My,null,Ne(t)&&a.createElement(a.Fragment,null,a.createElement(B,{variant:"caption1",color:b.themedColor.textMidEmphasis,maxTextLines:1},r.CONVERSATION_LIST__ENDED),a.createElement(wy,null)),a.createElement(B,{variant:"caption2",color:b.themedColor.textLowEmphasis,maxTextLines:1},m))),h>0&&a.createElement(ky,{$count:h},a.createElement(B,{variant:"caption3",color:b.themedColor.textHighEmphasisInverse},h<=Pr?h:`${Pr}+`))),v.descriptionNode)},vs=qe({template:Ay,components:{}}),Ty=C.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"};`,Iy=C.default.div`display:flex;align-items:center;justify-content:center;padding-inline-start:16px;`,xy=C.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 ${b.themedColor.textDisabled};`,Ry=C.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;`,My=C.default.div`display:flex;align-items:center;gap:6px;`,wy=C.default.div`width:2px;height:2px;border-radius:1px;background-color:${b.themedColor.textLowEmphasis};`,ky=C.default.div`display:flex;align-items:center;justify-content:center;height:20px;padding:4px;border-radius:10px;background-color:${b.themedColor.error};${({$count:e})=>e<=Pr&&U.css`
|
|
477
478
|
width: 20px;
|
|
478
479
|
`}
|
|
479
|
-
`,
|
|
480
|
+
`,Ly=({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(Oy,{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(Ny,{key:d,role:"listitem"},u)}))},Oy=C.default.div`width:100%;height:100%;display:flex;flex-direction:column;flex:1;overflow:auto;overscroll-behavior:contain;`,Ny=C.default.div`flex-shrink:0;`,Dy=()=>{const{stringSet:e}=ie(),{listSource:t,onOpenConversationView:n}=sn(),{Template:r}=vs.useContext();return t.initialized?t.channels.length===0?a.createElement(qt,{type:"noChannels",label:e.CONVERSATION_LIST__NO_CONVERSATIONS}):a.createElement(Ly,{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,Ne(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(qt,{type:"loading"})},$y=()=>{const{stringSet:e}=ie(),{_aiAgentSDK:t}=ye(),{language:n,countryCode:r,context:s}=ue(),{aiAgentInfo:o,refreshActiveChannel:i,createConversation:c}=Oe(),{onOpenConversationView:u}=sn(),{conversationList:d}=ae(),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(Py,{...d.footer.button({onActivate:m}).props},a.createElement(Fy,{variant:"h1"},e.TALK_TO_AGENT))},Py=C.default.div`background-color:${({theme:e})=>e.colors.base.primary};display:flex;align-items:center;justify-content:center;padding:16px;cursor:pointer;`,Fy=C.default(B)`color:${({theme:e})=>e.colors.base.primaryContrastContent};overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,Uy=()=>{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})},By=()=>{const{stringSet:e}=ie(),{announcementsEnabled:t}=bs(),{conversationList:n}=ae(),r=e.CONVERSATION_LIST__HEADER_TITLE,s=xa({enabled:t,label:r}),o={title:n.headerTitle(r,{active:s.enabled,titleId:s.id})};return a.createElement(Hy,{forwardedAs:"h2",variant:"h2",color:b.themedColor.textHighEmphasis,...o.title.props},r)},Hy=C.default(B)`margin:0;padding:0 4px;min-width:0;width:100%;box-sizing:border-box;text-overflow:ellipsis;overflow:hidden;white-space:nowrap;`,Gy=e=>{const{components:t}=Pt.useContext();return a.createElement(ic,{start:a.createElement(t.StartArea,null),title:a.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:a.createElement(t.EndArea,null),containerProps:Qi})},zy=()=>null,Vy=()=>{const{components:e}=Pt.useContext();return a.createElement(e.Title,null)},Ky=()=>{const{components:e}=Pt.useContext();return a.createElement(e.CloseButton,null)},Pt=qe({template:Gy,components:{StartArea:zy,TitleArea:Vy,EndArea:Ky,Title:By,CloseButton:Uy}}),qy=()=>{const{Template:e}=Pt.useContext();return a.createElement(e,{titleAlign:"start"})},Wy=()=>(Sy(),null),Ss=({conversationListLimit:e,conversationListFilter:t,children:n,onOpenConversationView:r,announcementsEnabled:s=!0,conversationListStatsEnabled:o,style:i})=>{const{Template:c}=Yn.useContext();return a.createElement(lc,{conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:o,onOpenConversationView:r},a.createElement(Ey,{announcementsEnabled:s},a.createElement(Wy,null),a.createElement(Yy,{style:i},a.createElement(c,null)),n))},Yy=({style:e,children:t})=>{const n=l.useRef(null);return vy(n),a.createElement(Xy,{ref:n,style:e},t)},jy=()=>{const{components:e}=Yn.useContext();return a.createElement(a.Fragment,null,a.createElement(e.Header,null),a.createElement(e.Body,null),a.createElement(e.Footer,null))},Yn=qe({template:jy,components:{Header:qy,Body:Dy,Footer:$y}}),Xy=C.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,Zy=U.css`:where(#${Se.ENTRY}) :not(code *){font-family:'Roboto',sans-serif;box-sizing:border-box;}`,Jy=[Zy,Hf,Gf],Qy=(e,...t)=>U.createGlobalStyle(e,...Jy,...t),eA=Qy``,tA=fd(Wn,ht,Dt,Vn,qn,Yn,bt,vs,Pt,Kn,Hn),nA=typeof __SBA_USE_MESSAGE_TEMPLATE__>"u"||__SBA_USE_MESSAGE_TEMPLATE__;function uc({appearance:e,rootElement:t,logger:n,language:r,languageCode:s,stringSet:o,children:i,messageTemplate:c,icons:u,theme:d,entryElement:m,modalRootElement:h}){ag(nA?Rf:"",t);const[f,g]=l.useState(null),p=l.useCallback(_=>{g(A=>A===_?A:_)},[]),v=m??f,E=a.createElement(U.StyleSheetManager,{target:t},a.createElement(sg,{rootElement:t,logger:n,appearance:e,theme:d},a.createElement(Lf,{rootElement:t,boundaryElement:v},a.createElement(Wm,{internalVariables:c==null?void 0:c.__internalVariables},a.createElement(Bf,{stringSet:o,logger:n,language:r,languageCode:s},a.createElement(ng,{icons:u},a.createElement(tA,null,a.createElement(wf,{entryElement:v,modalRootElement:h,rootElement:t},i),a.createElement(eA,null))))))));return m?E:a.createElement("div",{ref:p,style:{display:"contents"}},E)}const rA=()=>{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}},ys=l.forwardRef(function({rootElement:t=document.body,logLevel:n=Ee.LogLevel.WARN,language:r=navigator.language,userSessionInfo:s,children:o,chatParams:i,icons:c,...u},d){var E,_,A;zt.level!==n&&(zt.level=n);const{entryElement:m,modalRootElement:h,setEntryElement:f,setModalRootElement:g}=rA();ig("https://fonts.googleapis.com/css2?family=Roboto&display=swap",t);const p=oa(r),v=ia.has(p)?p:en;return a.createElement("div",{ref:f,id:Se.ENTRY,lang:v,style:{width:"fit-content",height:"fit-content",...u.entryStyle}},m&&h&&a.createElement(uc,{logger:zt,rootElement:t,appearance:(E=u.agentPreviewConfigs)==null?void 0:E.appearance,stringSet:u.stringSet,language:v,messageTemplate:u.messageTemplate,icons:c,theme:u.theme,entryElement:m,modalRootElement:h},a.createElement(Bg,{rootElement:t,language:r,logger:zt,dispatcher:dc,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(Yg,{ref:d,userSessionInfo:s},a.createElement(Xv,{...u._UNSAFE_INTERNAL_dashboardTester},a.createElement(mg,null,o))))),a.createElement("div",{ref:g,id:Se.MODAL_ROOT,dir:u.dir}))}),zt=new Ei(Ee.LogLevel.WARN),dc=new gi(zt),{Provider:sA,useContext:on}=be("PageChildren"),mc=({children:e})=>{const[t,n]=l.useState(()=>Cs),[r,s]=l.useState(null),[o,i]=l.useState(()=>Ss),[c,u]=l.useState(null),d=l.useCallback(h=>{n(()=>h)},[]),m=l.useCallback(h=>{i(()=>h)},[]);return a.createElement(sA,{value:{conversationComponent:t,setConversationComponent:d,conversationChildren:r,setConversationChildren:s,conversationListComponent:o,setConversationListComponent:m,conversationListChildren:c,setConversationListChildren:u}},e)},As=(e,t)=>e?{role:"dialog","aria-modal":"true",...t?{"aria-labelledby":Se.WINDOW_TITLE}:{"aria-label":"Messenger"}}:{"aria-hidden":"true",inert:!0},hc=({children:e,isOpened:t,zIndex:n=Et.WINDOW})=>a.createElement(us,null,a.createElement(oA,{isOpened:t,zIndex:n},e)),oA=({children:e,isOpened:t,zIndex:n=Et.WINDOW})=>{const{dir:r,rootElement:s}=ue(),o=mt(s,!0),i=l.useRef(null),{hasWindowTitleReference:c,isWindowNameReady:u}=Gn();return Bn(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(iA,{ref:i,id:Se.WINDOW,dir:r,...As(t,c),$visible:t,$zIndex:n},e)},iA=C.default.div`width:100%;height:100%;position:fixed;top:0;left:0;z-index:${({$zIndex:e})=>e};visibility:${({$visible:e})=>e?"visible":"hidden"};`,aA=48,cA=2/3,ti=12;function fc({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=aA,hasUnread:f=!1}){const g=Ua(),p=d&&!g,v=Ar(m),E=Math.round(h*cA);return a.createElement(dA,{dir:u,id:Se.LAUNCHER,className:e,"aria-label":s,"aria-describedby":o,onClick:r,$animated:p,$backgroundColor:m,$prefersReducedMotion:g,$size:h},a.createElement(mA,{$isOpened:n,$animated:p,$fillColor:v,$iconSize:E,$prefersReducedMotion:g},a.createElement(ni.Open,{url:c,isDefaultIcon:i==="default_icon",size:E})),a.createElement(hA,{$isOpened:n,$animated:p,$fillColor:v,$iconSize:E,$prefersReducedMotion:g},a.createElement(ni.Close,{size:E})),f&&a.createElement(fA,null),t)}const lA=U.css`&:hover{transition:transform 250ms cubic-bezier(0.33,0,0,1);transform:scale(1.1);}&:active{transform:scale(0.8);}`,uA=U.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===Wt.WHITE?"grayscale(100%) brightness(2000%)":"grayscale(100%) invert(100%) saturate(0%) brightness(0%) contrast(1000%)"};}}`,gc=U.css`svg{width:${({$iconSize:e})=>e}px;height:${({$iconSize:e})=>e}px;${({$fillColor:e})=>U.css`
|
|
480
481
|
ellipse,
|
|
481
482
|
path {
|
|
482
483
|
fill: ${e};
|
|
@@ -486,7 +487,7 @@ $2
|
|
|
486
487
|
}
|
|
487
488
|
`}
|
|
488
489
|
}
|
|
489
|
-
`,
|
|
490
|
+
`,dA=C.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:${va};${({$animated:e})=>e&&lA}`,pc=C.default.span.attrs({"aria-hidden":"true"})`
|
|
490
491
|
position: absolute;
|
|
491
492
|
width: 100%;
|
|
492
493
|
height: 100%;
|
|
@@ -496,23 +497,23 @@ $2
|
|
|
496
497
|
display: flex;
|
|
497
498
|
justify-content: center;
|
|
498
499
|
align-items: center;
|
|
499
|
-
`,
|
|
500
|
+
`,mA=C.default(pc)`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)")};${uA}${gc}`,hA=C.default(pc)`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)")};${gc}`,fA=C.default.span.attrs({"aria-hidden":"true"})`
|
|
500
501
|
position: absolute;
|
|
501
502
|
top: 1px;
|
|
502
503
|
inset-inline-end: 1px;
|
|
503
|
-
width: ${
|
|
504
|
-
height: ${
|
|
504
|
+
width: ${ti}px;
|
|
505
|
+
height: ${ti}px;
|
|
505
506
|
border-radius: 50%;
|
|
506
507
|
background-color: ${b.themedColor.error};
|
|
507
|
-
`,
|
|
508
|
+
`,ni={Open:e=>e.url?a.createElement("img",{src:e.url,alt:"","data-default-icon":e.isDefaultIcon}):a.createElement(ee,{size:e.size,type:"delight"}),Close:({size:e})=>a.createElement(ee,{size:e,type:"chevron-down"})};function _c({className:e,size:t,entryPoint:n="Conversation",activeRoute:r}){const{colors:s}=U.useTheme(),{chatSDK:o,config:i,dir:c,state:u}=ue(),{resolveElement:d}=ss(),{launcher:m}=ae(),{launcherInfo:h}=Oe(),f=i.launcher.unreadBadgeEnabled,g=$i(),p=wh(o,{enabled:f,opened:u.opened,filter:g}),v=(r??n)==="ConversationList",E={launcher:m.button({isOpened:u.opened,opensConversationList:v})};Mh("launcher_toggle"),pA();const _=()=>{Ie(()=>{const T=d(Se.WINDOW),I=T?pa(T):null;I==null||I.focus()})},A=()=>{Ie(()=>{var T;(T=d(Se.LAUNCHER))==null||T.focus()})},y=()=>{const T=!u.opened;u.setOpened(T),T?_():A()};return a.createElement(fc,{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 gA=1e3*60;function pA(){const{chatSDK:e,state:t,logger:n,enableAutoDisconnectInLauncher:r}=ue(),s=l.useRef(null);l.useEffect(()=>{if(!r)return;function o(){s.current&&(clearTimeout(s.current),s.current=null)}function i(){e.connectionState===Ee.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")},gA)}t.opened?i():(c(),n.debug("useSDKInactivityTimeout: schedule disconnect"))},[r,e,t.opened])}const Ec=l.createContext(null);function jn(){const e=l.useContext(Ec);if(!e)throw new Error("useNavigator() must be used within <Navigator />");return e}function Cc({children:e}){const t=jn();return typeof e=="function"?e(t):a.createElement(a.Fragment,null,e)}function bc({children:e}){return a.createElement(a.Fragment,null,e)}const _A=U.keyframes`0%{transform:translateY(40px);opacity:0;}100%{transform:translateY(0px);opacity:1;}`,EA=U.keyframes`0%{transform:translateY(0px);opacity:1;}100%{transform:translateY(40px);opacity:0;}`,CA=U.css`animation-name:${_A};animation-duration:0.3s;animation-fill-mode:forwards;`,bA=U.css``,vA=U.css`animation-name:${EA};animation-duration:0.3s;animation-fill-mode:forwards;`,SA=U.css`visibility:hidden;`,yA=C.default.div`position:absolute;top:0;left:0;width:100%;height:100%;${({$transitionState:e})=>{switch(e){case"entering":return CA;case"entered":return bA;case"exiting":return vA;case"exited":return SA;default:return""}}}${({$active:e})=>e?U.css`
|
|
508
509
|
z-index: 999;
|
|
509
|
-
`:
|
|
510
|
-
`;function
|
|
510
|
+
`:U.css`z-index:1;pointer-events:none;`}
|
|
511
|
+
`;function Rt({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===Cc),[t]),d=l.useMemo(()=>l.Children.toArray(t).filter(_=>_.type===bc),[t]),m=l.useMemo(()=>{const _={};return u.forEach(A=>{const{id:y,lazy:T,children:I}=A.props;_[y]={lazy:T,element:typeof I=="function"?I(c):I}}),_},[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"}),_}),[v,E]=l.useState({});return a.createElement(Ec.Provider,{value:c},d,a.createElement(AA,null,Object.keys(m).map(_=>{var I;if(!h[_])return null;const A=g[_]||"exited",y=_===s,T=`${_}-${v[_]||0}`;return a.createElement(yA,{key:T,$transitionState:A,$active:y,"aria-hidden":y?void 0:!0,inert:y?void 0:!0},(I=m[_])==null?void 0:I.element)})))}const AA=C.default.div`position:relative;width:100%;height:100%;`;Rt.Screen=Cc;Rt.Effect=bc;const Ge={conv:"conv",convList:"conv-list"},TA=e=>e===Ge.convList?"ConversationList":"Conversation",vc=({isOpened:e,entryPoint:t,selectedChannelUrl:n,setSelectedChannelUrl:r,nudgeConversation:s,onActiveRouteChange:o})=>{const{conversationComponent:i,conversationChildren:c,conversationListComponent:u,conversationListChildren:d}=on(),[m,h]=l.useState(),f=(()=>{switch(t){case"Conversation":return Ge.conv;case"ConversationList":return Ge.convList;default:return Ge.conv}})(),g=a.createElement(a.Fragment,null,a.createElement(IA,{onOpenConversationView:(p,v)=>{r(v),h(void 0),p.navigate(Ge.conv)}}),a.createElement(RA,{onActiveRouteChange:o}));return a.createElement(Rt,{initialId:f},a.createElement(Rt.Effect,null,a.createElement(xA,{nudgeConversation:s,onNavigate:p=>{h("messageInput"),p.navigate(Ge.conv)}})),a.createElement(Rt.Screen,{id:Ge.conv},({navigation:p,activeScreenId:v})=>{const E=v===Ge.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(Ge.convList)},announcementsEnabled:_,conversationStatsEnabled:_,shouldMarkAsRead:_,shouldInitializeConversation:_,initialUserMessage:s&&s.channelUrl===n?s.initialUserMessage:void 0,initialFocusTarget:m},c))}),a.createElement(Rt.Screen,{id:Ge.convList,lazy:!0},({navigation:p,activeScreenId:v})=>{const E=v===Ge.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(Ge.conv)}},d))}))},IA=({onOpenConversationView:e})=>{const{registerOnJoinedProactiveConversation:t}=Oe(),{navigation:n}=jn();return t(({channel:r})=>{e(n,r.url)}),null},xA=({nudgeConversation:e,onNavigate:t})=>{const{navigation:n}=jn();return l.useEffect(()=>{e&&t(n)},[e]),null},RA=({onActiveRouteChange:e})=>{const{activeScreenId:t}=jn();return l.useEffect(()=>{e==null||e(TA(t))},[t,e]),null},MA=({isExpanded:e,isOpened:t,children:n,launcher:r})=>a.createElement(us,null,a.createElement(wA,{isExpanded:e,isOpened:t,launcher:r},n)),wA=({isExpanded:e,isOpened:t,children:n,launcher:r})=>{const{dir:s}=ue(),o=l.useRef(null),{hasWindowTitleReference:i,isWindowNameReady:c}=Gn();return Bn(t,o,{nameReady:c}),a.createElement(kA,null,a.createElement(LA,{ref:o,dir:s,id:Se.WINDOW,...As(t,i),$isExpanded:e,$isOpened:t},n),r)},kA=C.default.div`display:flex;flex-direction:column;gap:8px;align-items:flex-end;`,LA=C.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&&NA};${({$isExpanded:e})=>e&&OA};`,OA=U.css`width:743px;height:723px;`,NA=U.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;`,Sc=({isMessengerOpened:e,onConversationStarted:t,className:n})=>{const{stringSet:r}=ie(),{dir:s}=ue(),{nudgeMessage:o,nudgeMessageKey:i,dismissNudgeMessage:c,startNudgeConversation:u}=sh({isMessengerOpened:e,onConversationStarted:t});return o?a.createElement($A,{key:i,className:n,dir:s},a.createElement(PA,{onClick:u},a.createElement(FA,{variant:"body3",color:b.themedColor.textHighEmphasis,maxTextLines:2},o.message)),a.createElement(UA,{type:"close",size:16,"aria-label":r.A11Y_DISMISS_NUDGE_MESSAGE,onClick:c})):null},yc=12,DA=U.keyframes`from{opacity:0;transform:scale(0.8);}`,$A=C.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:${yc}px;background-color:${b.themedColor.bg_50_600};box-shadow:${va};animation-name:${DA};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;}`,PA=C.default.button`all:unset;flex:1;min-width:0;cursor:pointer;text-align:start;${xe}&::after{content:'';position:absolute;inset:0;border-radius:${yc}px;}`,FA=C.default(B)`line-height:20px;overflow-wrap:anywhere;white-space:pre-line;`,UA=C.default(nt)`position:relative;margin:-4px;`,BA=l.forwardRef(function({children:e,initialChannelUrl:t,...n},r){const s=tn(),[o,i]=l.useState(t),[c,u]=l.useState(),[d,m]=l.useState(n.entryPoint??"Conversation"),h=s?hc:MA;return a.createElement(ys,{enableExpandButton:!s,ref:r,...n},a.createElement(Ea,null,({state:f})=>a.createElement(mc,null,a.createElement(h,{isExpanded:f.expanded,isOpened:f.opened,...s&&{zIndex:"auto"},launcher:a.createElement(a.Fragment,null,a.createElement(Sc,{isMessengerOpened:f.opened,onConversationStarted:g=>{i(g.channelUrl),u(g),f.setOpened(!0)}}),a.createElement(_c,{entryPoint:n.entryPoint,activeRoute:d}))},a.createElement(vc,{isOpened:f.opened,entryPoint:n.entryPoint,selectedChannelUrl:o,setSelectedChannelUrl:i,nudgeConversation:c,onActiveRouteChange:m})),e)))}),{Provider:HA,useContext:Xn}=be("FixedMessengerStyle");function Ac(e,t,n,r=0){return U.css`&&{position:fixed;z-index:${Et.LAUNCHER};${Tc(e,t,n,r)};}`}function Tc(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: ${Xe(i)}`;break;case"end":d=`inset-inline-end: ${Xe(c)}`;break}switch(t){case"top":u=`top: calc(${Xe(s)} + ${r}px)`;break;case"bottom":u=`bottom: calc(${Xe(o)} + ${r}px)`;break}return U.css`${u};${d};`}function GA(e){const{horizontal:t,vertical:n,margin:r,launcherSize:s}=Xn();return a.createElement(zA,{...e,size:s,$horizontal:t,$vertical:n,$margin:r})}const zA=C.default(_c)`${({$horizontal:e,$vertical:t,$margin:n})=>Ac(e,t,n)};`,VA=({isExpanded:e,isOpened:t,children:n})=>a.createElement(us,null,a.createElement(KA,{isExpanded:e,isOpened:t},n)),KA=({isExpanded:e,isOpened:t,children:n})=>{const{dir:r}=ue(),{horizontal:s,vertical:o,margin:i,launcherSize:c}=Xn(),u=l.useRef(null),{hasWindowTitleReference:d,isWindowNameReady:m}=Gn();return Bn(t,u,{nameReady:m}),a.createElement(qA,{ref:u,dir:r,id:Se.WINDOW,...As(t,d),$isExpanded:e,$isOpened:t,$horizontal:s,$vertical:o,$margin:i,$launcherSize:c},n)},qA=C.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})=>Tc(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}`};
|
|
511
512
|
[dir='rtl'] &:not([dir='ltr']),
|
|
512
513
|
&[dir='rtl'] {
|
|
513
514
|
transform-origin: ${({$horizontal:e,$vertical:t})=>`${e==="start"?"right":"left"} ${t}`};
|
|
514
515
|
}
|
|
515
516
|
|
|
516
|
-
${({$isOpened:e})=>e&&
|
|
517
|
-
${({$isExpanded:e})=>e&&
|
|
518
|
-
`,
|
|
517
|
+
${({$isOpened:e})=>e&&YA};
|
|
518
|
+
${({$isExpanded:e})=>e&&WA};
|
|
519
|
+
`,WA=U.css`width:743px;height:723px;`,YA=U.css`z-index:${Et.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;`,jA=8,XA=e=>{const{horizontal:t,vertical:n,margin:r,launcherSize:s}=Xn();return a.createElement(ZA,{...e,$horizontal:t,$vertical:n,$margin:r,$launcherSize:s})},ZA=C.default(Sc)`${({$horizontal:e,$vertical:t,$margin:n,$launcherSize:r})=>Ac(e,t,n,r+jA)};`,Ic={top:24,bottom:24,start:24,end:24},JA=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(Ic),[p,v]=l.useState(48),E=tn(),_=E?hc:VA,{horizontal:A,vertical:y}=l.useMemo(()=>{const[T,I]=m.split("-");return{horizontal:T==="start"?"start":"end",vertical:I==="top"?"top":"bottom"}},[m]);return a.createElement(ys,{enableExpandButton:!E,ref:r,...n},a.createElement(Ea,null,({state:T})=>a.createElement(HA,{value:{horizontal:A,vertical:y,margin:f,launcherSize:p,setPosition:h,setMargin:g,setLauncherSize:v}},a.createElement(mc,null,a.createElement(_,{isExpanded:T.expanded,isOpened:T.opened},a.createElement(vc,{isOpened:T.opened,entryPoint:n.entryPoint,selectedChannelUrl:s,setSelectedChannelUrl:o,nudgeConversation:i,onActiveRouteChange:d})),a.createElement(GA,{entryPoint:n.entryPoint,activeRoute:u}),a.createElement(XA,{isMessengerOpened:T.opened,onConversationStarted:I=>{o(I.channelUrl),c(I),T.setOpened(!0)}}),e))))}),QA=e=>{var s,o,i,c;const{setPosition:t,setMargin:n,setLauncherSize:r}=Xn();return l.useLayoutEffect(()=>{e.position&&t(e.position),e.margin&&n({...Ic,...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},e0=({children:e})=>{const{setConversationChildren:t}=on();return l.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},t0=({component:e})=>{const{setConversationComponent:t}=on();return l.useLayoutEffect(()=>(t(e),()=>t(Cs)),[e,t]),null},n0=({children:e})=>{const{setConversationListChildren:t}=on();return l.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},r0=({component:e})=>{const{setConversationListComponent:t}=on();return l.useLayoutEffect(()=>(t(e),()=>t(Ss)),[e,t]),null},s0=Object.assign(JA,{Style:QA,Conversation:t0,ConversationChildren:e0,ConversationList:r0,ConversationListChildren:n0}),o0=e=>{const{refreshActiveChannel:t}=Oe(),[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])};Ii.set(Ee.SendbirdPlatform.JS,{deviceOSPlatform:al()?Ee.DeviceOsPlatform.MOBILE_WEB:Ee.DeviceOsPlatform.WEB,messengerVersion:Sf,keyValueStorage:If(),networkStateAdapter:Tf(),foregroundStateAdapter:Af});exports.ANCHOR_REL=rs;exports.AgentProviderContainer=ys;exports.AgentUIProviderContainer=uc;exports.AnonymousSessionInfo=br;exports.CSATType=Je;exports.Commands=it;exports.ConnectionDelayLayout=Hn;exports.Conversation=Cs;exports.ConversationContext=ap;exports.ConversationContextProvider=Aa;exports.ConversationHeaderLayout=bt;exports.ConversationLayout=Wn;exports.ConversationList=Ss;exports.ConversationListContext=by;exports.ConversationListContextProvider=lc;exports.ConversationListHeaderLayout=Pt;exports.ConversationListItemLayout=vs;exports.ConversationListLayout=Yn;exports.DefaultMessenger=BA;exports.DeskTicketPriority=Zr;exports.DeskTicketStatus=Xr;exports.FixedMessenger=s0;exports.ID_INCOMING=We;exports.IncomingMessageLayout=ht;exports.LauncherBase=fc;exports.LogLevel=Kr;exports.MARK_CHAR=ja;exports.ManualSessionInfo=Ci;exports.MaskedText=Ya;exports.MessageListUILayout=qn;exports.MessageLogs=Qa;exports.OutgoingMessageLayout=Dt;exports.PlaceholderLayout=Kn;exports.Prechecks=tc;exports.SystemMessageLayout=Vn;exports.createMarkdownPreprocessor=sl;exports.cssVars=b;exports.flattenObject=Wu;exports.mapCommonStringsToReactFormat=sa;exports.messengerDispatcher=dc;exports.noop=me;exports.parseToMessageTemplate=Ai;exports.parseToUITemplate=Ku;exports.pickColorByTheme=qu;exports.replaceVariablesAsync=ju;exports.replaceVariablesSync=Yu;exports.useAIAgentContext=ye;exports.useConversationContext=Ae;exports.useConversationListContext=sn;exports.useLocalizationContext=ie;exports.useMessageTemplateFetchingContext=qm;exports.useMessengerContext=ue;exports.useMessengerSessionContext=Oe;exports.useMessengerThemeContext=ua;exports.useRefreshActiveChannel=o0;
|