@ujet/websdk-headless 6.22.0 → 6.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +4 -4
- package/dist/index.mjs +3 -3
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"use strict";var Pq=Object.defineProperty;var CE=r=>{throw TypeError(r)};var Iq=(r,e,t)=>e in r?Pq(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var be=(r,e,t)=>Iq(r,typeof e!="symbol"?e+"":e,t),EE=(r,e,t)=>e.has(r)||CE("Cannot "+t);var Rc=(r,e,t)=>(EE(r,e,"read from private field"),t?t.call(r):e.get(r)),hy=(r,e,t)=>e.has(r)?CE("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),py=(r,e,t,n)=>(EE(r,e,"write to private field"),n?n.call(r,t):e.set(r,t),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function Aq(r,e){for(var t=0;t<e.length;t++){const n=e[t];if(typeof n!="string"&&!Array.isArray(n)){for(const i in n)if(i!=="default"&&!(i in r)){const s=Object.getOwnPropertyDescriptor(n,i);s&&Object.defineProperty(r,i,s.get?s:{enumerable:!0,get:()=>n[i]})}}}return Object.freeze(Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}))}class Oq{constructor(){be(this,"_hostPath","")}setPath(e){this._hostPath=e}getPath(){return this._hostPath}}const rO=new Oq;let $q=class{constructor(){be(this,"currentAudio",null);be(this,"cleanupCallback",null)}async playPing(){rO.getPath();const e="https://websdk.ujet.co/v3/ping.mp3";try{await this.playSound(e)}catch(t){console.warn("Chat audio play failed",{error:t})}}async playSound(e,t=1){this.cleanup();const n=new window.Audio(e);n.volume=t,this.currentAudio=n;const i=()=>{this.currentAudio===n&&(this.currentAudio=null,this.cleanupCallback=null),n.removeEventListener("ended",i),n.removeEventListener("error",i)};this.cleanupCallback=i,n.addEventListener("ended",i),n.addEventListener("error",i);try{await n.play()}catch(s){i(),console.warn("Audio play failed",{error:s})}}cleanup(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.currentTime=0),this.cleanupCallback&&this.cleanupCallback()}};var ul=(r=>(r.WAITING="waiting",r.READY="ready",r.IN_PROGRESS="in_progress",r.FINISHED="finished",r))(ul||{}),nO=(r=>(r.CONFIRMED="confirmed",r.EXITED="exited",r.PENDING="pending",r.REQUESTED="requested",r.SKIPPED="skipped",r.TIMED_OUT="timed_out",r))(nO||{}),Wu=(r=>(r.UJET="ujet_conversations",r.TWILIO="twilio_conversations",r.NEXMO="nexmo_conversations",r.MOCK="mock",r))(Wu||{}),iv=(r=>(r.INBOUND_CALL="inbound_call",r.VOICEMAIL="voicemail",r))(iv||{}),ln=(r=>(r.TEXT="text",r.NOTI="noti",r.SERVER_MESSAGE="server_message",r.TYPING="typing",r.PREVIEW="preview",r.TRANSLATION_UPDATE="translation_update",r))(ln||{}),Gn=(r=>(r.MEMBER_JOINED="memberJoined",r.MEMBER_LEFT="memberLeft",r.CHAT_ENDED="chatEnded",r.CHAT_DISMISSED="chatDismissed",r.TASK_VA_STARTED="taskVaStarted",r.TASK_VA_FINISHED="taskVaFinished",r.TASK_VA_FAILED="taskVaFailed",r.ESCALATION_STARTED="escalationStarted",r.ESCALATION_ACCEPTED="escalationAccepted",r.ESCALATION_FAILED="escalationFailed",r.CHECK_IN_REQUIRED="checkInRequired",r.CHECK_IN_TIMED_OUT="checkInTimedOut",r.COBROWSE_REQUESTED_FROM_AGENT="cobrowseRequestedFromAgent",r.COBROWSE_REQUESTED_FROM_END_USER="cobrowseRequestedFromEndUser",r))(Gn||{}),_i=(r=>(r.END_USER="end_user",r.USER="user",r.VIRTUAL_AGENT="virtual_agent",r.SYSTEM="system",r))(_i||{});function Fp(r,e){return`${r}-${e}`}/*! @license DOMPurify 3.3.1 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.3.1/LICENSE */const{entries:iO,setPrototypeOf:kE,isFrozen:xq,getPrototypeOf:Mq,getOwnPropertyDescriptor:Dq}=Object;let{freeze:Si,seal:bs,create:Ib}=Object,{apply:Ab,construct:Ob}=typeof Reflect<"u"&&Reflect;Si||(Si=function(e){return e});bs||(bs=function(e){return e});Ab||(Ab=function(e,t){for(var n=arguments.length,i=new Array(n>2?n-2:0),s=2;s<n;s++)i[s-2]=arguments[s];return e.apply(t,i)});Ob||(Ob=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return new e(...n)});const Eh=wi(Array.prototype.forEach),Nq=wi(Array.prototype.lastIndexOf),RE=wi(Array.prototype.pop),td=wi(Array.prototype.push),Lq=wi(Array.prototype.splice),jp=wi(String.prototype.toLowerCase),vy=wi(String.prototype.toString),gy=wi(String.prototype.match),rd=wi(String.prototype.replace),Uq=wi(String.prototype.indexOf),Fq=wi(String.prototype.trim),Fs=wi(Object.prototype.hasOwnProperty),pi=wi(RegExp.prototype.test),nd=jq(TypeError);function wi(r){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return Ab(r,e,n)}}function jq(r){return function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return Ob(r,t)}}function ar(r,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:jp;kE&&kE(r,null);let n=e.length;for(;n--;){let i=e[n];if(typeof i=="string"){const s=t(i);s!==i&&(xq(e)||(e[n]=s),i=s)}r[i]=!0}return r}function Bq(r){for(let e=0;e<r.length;e++)Fs(r,e)||(r[e]=null);return r}function ua(r){const e=Ib(null);for(const[t,n]of iO(r))Fs(r,t)&&(Array.isArray(n)?e[t]=Bq(n):n&&typeof n=="object"&&n.constructor===Object?e[t]=ua(n):e[t]=n);return e}function id(r,e){for(;r!==null;){const n=Dq(r,e);if(n){if(n.get)return wi(n.get);if(typeof n.value=="function")return wi(n.value)}r=Mq(r)}function t(){return null}return t}const PE=Si(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),my=Si(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),yy=Si(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),qq=Si(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),_y=Si(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),Wq=Si(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),IE=Si(["#text"]),AE=Si(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),by=Si(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),OE=Si(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),kh=Si(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),Vq=bs(/\{\{[\w\W]*|[\w\W]*\}\}/gm),Hq=bs(/<%[\w\W]*|[\w\W]*%>/gm),Gq=bs(/\$\{[\w\W]*/gm),zq=bs(/^data-[\-\w.\u00B7-\uFFFF]+$/),Kq=bs(/^aria-[\-\w]+$/),sO=bs(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Jq=bs(/^(?:\w+script|data):/i),Yq=bs(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),aO=bs(/^html$/i),Xq=bs(/^[a-z][.\w]*(-[.\w]+)+$/i);var $E=Object.freeze({__proto__:null,ARIA_ATTR:Kq,ATTR_WHITESPACE:Yq,CUSTOM_ELEMENT:Xq,DATA_ATTR:zq,DOCTYPE_NAME:aO,ERB_EXPR:Hq,IS_ALLOWED_URI:sO,IS_SCRIPT_OR_DATA:Jq,MUSTACHE_EXPR:Vq,TMPLIT_EXPR:Gq});const sd={element:1,text:3,progressingInstruction:7,comment:8,document:9},Qq=function(){return typeof window>"u"?null:window},Zq=function(e,t){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let n=null;const i="data-tt-policy-suffix";t&&t.hasAttribute(i)&&(n=t.getAttribute(i));const s="dompurify"+(n?"#"+n:"");try{return e.createPolicy(s,{createHTML(a){return a},createScriptURL(a){return a}})}catch{return console.warn("TrustedTypes policy "+s+" could not be created."),null}},xE=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function oO(){let r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Qq();const e=vt=>oO(vt);if(e.version="3.3.1",e.removed=[],!r||!r.document||r.document.nodeType!==sd.document||!r.Element)return e.isSupported=!1,e;let{document:t}=r;const n=t,i=n.currentScript,{DocumentFragment:s,HTMLTemplateElement:a,Node:c,Element:o,NodeFilter:l,NamedNodeMap:d=r.NamedNodeMap||r.MozNamedAttrMap,HTMLFormElement:h,DOMParser:v,trustedTypes:y}=r,w=o.prototype,k=id(w,"cloneNode"),I=id(w,"remove"),A=id(w,"nextSibling"),j=id(w,"childNodes"),L=id(w,"parentNode");if(typeof a=="function"){const vt=t.createElement("template");vt.content&&vt.content.ownerDocument&&(t=vt.content.ownerDocument)}let x,B="";const{implementation:G,createNodeIterator:K,createDocumentFragment:D,getElementsByTagName:fe}=t,{importNode:X}=n;let pe=xE();e.isSupported=typeof iO=="function"&&typeof L=="function"&&G&&G.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:Q,ERB_EXPR:Oe,TMPLIT_EXPR:Ve,DATA_ATTR:Ze,ARIA_ATTR:Xe,IS_SCRIPT_OR_DATA:Re,ATTR_WHITESPACE:Je,CUSTOM_ELEMENT:Ke}=$E;let{IS_ALLOWED_URI:Y}=$E,Ce=null;const Et=ar({},[...PE,...my,...yy,..._y,...IE]);let Nt=null;const Ct=ar({},[...AE,...by,...OE,...kh]);let wt=Object.seal(Ib(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),te=null,ne=null;const ut=Object.seal(Ib(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let Pt=!0,Zt=!0,rt=!1,on=!0,Ot=!1,$e=!0,_t=!1,zt=!1,Fe=!1,pr=!1,er=!1,Mr=!1,lr=!0,Xr=!1;const mn="user-content-";let fn=!0,Kt=!1,Vt={},kt=null;const yt=ar({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let Xt=null;const Zr=ar({},["audio","video","img","source","image","track"]);let Kr=null;const xn=ar({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),En="http://www.w3.org/1998/Math/MathML",kn="http://www.w3.org/2000/svg",ir="http://www.w3.org/1999/xhtml";let Dr=ir,ke=!1,Ie=null;const ye=ar({},[En,kn,ir],vy);let we=ar({},["mi","mo","mn","ms","mtext"]),le=ar({},["annotation-xml"]);const xe=ar({},["title","style","font","a","script"]);let Le=null;const he=["application/xhtml+xml","text/html"],_e="text/html";let se=null,ve=null;const oe=t.createElement("form"),Qe=function(ue){return ue instanceof RegExp||ue instanceof Function},Me=function(){let ue=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(ve&&ve===ue)){if((!ue||typeof ue!="object")&&(ue={}),ue=ua(ue),Le=he.indexOf(ue.PARSER_MEDIA_TYPE)===-1?_e:ue.PARSER_MEDIA_TYPE,se=Le==="application/xhtml+xml"?vy:jp,Ce=Fs(ue,"ALLOWED_TAGS")?ar({},ue.ALLOWED_TAGS,se):Et,Nt=Fs(ue,"ALLOWED_ATTR")?ar({},ue.ALLOWED_ATTR,se):Ct,Ie=Fs(ue,"ALLOWED_NAMESPACES")?ar({},ue.ALLOWED_NAMESPACES,vy):ye,Kr=Fs(ue,"ADD_URI_SAFE_ATTR")?ar(ua(xn),ue.ADD_URI_SAFE_ATTR,se):xn,Xt=Fs(ue,"ADD_DATA_URI_TAGS")?ar(ua(Zr),ue.ADD_DATA_URI_TAGS,se):Zr,kt=Fs(ue,"FORBID_CONTENTS")?ar({},ue.FORBID_CONTENTS,se):yt,te=Fs(ue,"FORBID_TAGS")?ar({},ue.FORBID_TAGS,se):ua({}),ne=Fs(ue,"FORBID_ATTR")?ar({},ue.FORBID_ATTR,se):ua({}),Vt=Fs(ue,"USE_PROFILES")?ue.USE_PROFILES:!1,Pt=ue.ALLOW_ARIA_ATTR!==!1,Zt=ue.ALLOW_DATA_ATTR!==!1,rt=ue.ALLOW_UNKNOWN_PROTOCOLS||!1,on=ue.ALLOW_SELF_CLOSE_IN_ATTR!==!1,Ot=ue.SAFE_FOR_TEMPLATES||!1,$e=ue.SAFE_FOR_XML!==!1,_t=ue.WHOLE_DOCUMENT||!1,pr=ue.RETURN_DOM||!1,er=ue.RETURN_DOM_FRAGMENT||!1,Mr=ue.RETURN_TRUSTED_TYPE||!1,Fe=ue.FORCE_BODY||!1,lr=ue.SANITIZE_DOM!==!1,Xr=ue.SANITIZE_NAMED_PROPS||!1,fn=ue.KEEP_CONTENT!==!1,Kt=ue.IN_PLACE||!1,Y=ue.ALLOWED_URI_REGEXP||sO,Dr=ue.NAMESPACE||ir,we=ue.MATHML_TEXT_INTEGRATION_POINTS||we,le=ue.HTML_INTEGRATION_POINTS||le,wt=ue.CUSTOM_ELEMENT_HANDLING||{},ue.CUSTOM_ELEMENT_HANDLING&&Qe(ue.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(wt.tagNameCheck=ue.CUSTOM_ELEMENT_HANDLING.tagNameCheck),ue.CUSTOM_ELEMENT_HANDLING&&Qe(ue.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(wt.attributeNameCheck=ue.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),ue.CUSTOM_ELEMENT_HANDLING&&typeof ue.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(wt.allowCustomizedBuiltInElements=ue.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),Ot&&(Zt=!1),er&&(pr=!0),Vt&&(Ce=ar({},IE),Nt=[],Vt.html===!0&&(ar(Ce,PE),ar(Nt,AE)),Vt.svg===!0&&(ar(Ce,my),ar(Nt,by),ar(Nt,kh)),Vt.svgFilters===!0&&(ar(Ce,yy),ar(Nt,by),ar(Nt,kh)),Vt.mathMl===!0&&(ar(Ce,_y),ar(Nt,OE),ar(Nt,kh))),ue.ADD_TAGS&&(typeof ue.ADD_TAGS=="function"?ut.tagCheck=ue.ADD_TAGS:(Ce===Et&&(Ce=ua(Ce)),ar(Ce,ue.ADD_TAGS,se))),ue.ADD_ATTR&&(typeof ue.ADD_ATTR=="function"?ut.attributeCheck=ue.ADD_ATTR:(Nt===Ct&&(Nt=ua(Nt)),ar(Nt,ue.ADD_ATTR,se))),ue.ADD_URI_SAFE_ATTR&&ar(Kr,ue.ADD_URI_SAFE_ATTR,se),ue.FORBID_CONTENTS&&(kt===yt&&(kt=ua(kt)),ar(kt,ue.FORBID_CONTENTS,se)),ue.ADD_FORBID_CONTENTS&&(kt===yt&&(kt=ua(kt)),ar(kt,ue.ADD_FORBID_CONTENTS,se)),fn&&(Ce["#text"]=!0),_t&&ar(Ce,["html","head","body"]),Ce.table&&(ar(Ce,["tbody"]),delete te.tbody),ue.TRUSTED_TYPES_POLICY){if(typeof ue.TRUSTED_TYPES_POLICY.createHTML!="function")throw nd('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof ue.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw nd('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');x=ue.TRUSTED_TYPES_POLICY,B=x.createHTML("")}else x===void 0&&(x=Zq(y,i)),x!==null&&typeof B=="string"&&(B=x.createHTML(""));Si&&Si(ue),ve=ue}},ot=ar({},[...my,...yy,...qq]),tt=ar({},[..._y,...Wq]),it=function(ue){let je=L(ue);(!je||!je.tagName)&&(je={namespaceURI:Dr,tagName:"template"});const st=jp(ue.tagName),Jt=jp(je.tagName);return Ie[ue.namespaceURI]?ue.namespaceURI===kn?je.namespaceURI===ir?st==="svg":je.namespaceURI===En?st==="svg"&&(Jt==="annotation-xml"||we[Jt]):!!ot[st]:ue.namespaceURI===En?je.namespaceURI===ir?st==="math":je.namespaceURI===kn?st==="math"&&le[Jt]:!!tt[st]:ue.namespaceURI===ir?je.namespaceURI===kn&&!le[Jt]||je.namespaceURI===En&&!we[Jt]?!1:!tt[st]&&(xe[st]||!ot[st]):!!(Le==="application/xhtml+xml"&&Ie[ue.namespaceURI]):!1},at=function(ue){td(e.removed,{element:ue});try{L(ue).removeChild(ue)}catch{I(ue)}},ht=function(ue,je){try{td(e.removed,{attribute:je.getAttributeNode(ue),from:je})}catch{td(e.removed,{attribute:null,from:je})}if(je.removeAttribute(ue),ue==="is")if(pr||er)try{at(je)}catch{}else try{je.setAttribute(ue,"")}catch{}},jt=function(ue){let je=null,st=null;if(Fe)ue="<remove></remove>"+ue;else{const Pr=gy(ue,/^[\r\n\t ]+/);st=Pr&&Pr[0]}Le==="application/xhtml+xml"&&Dr===ir&&(ue='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+ue+"</body></html>");const Jt=x?x.createHTML(ue):ue;if(Dr===ir)try{je=new v().parseFromString(Jt,Le)}catch{}if(!je||!je.documentElement){je=G.createDocument(Dr,"template",null);try{je.documentElement.innerHTML=ke?B:Jt}catch{}}const or=je.body||je.documentElement;return ue&&st&&or.insertBefore(t.createTextNode(st),or.childNodes[0]||null),Dr===ir?fe.call(je,_t?"html":"body")[0]:_t?je.documentElement:or},pt=function(ue){return K.call(ue.ownerDocument||ue,ue,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},bt=function(ue){return ue instanceof h&&(typeof ue.nodeName!="string"||typeof ue.textContent!="string"||typeof ue.removeChild!="function"||!(ue.attributes instanceof d)||typeof ue.removeAttribute!="function"||typeof ue.setAttribute!="function"||typeof ue.namespaceURI!="string"||typeof ue.insertBefore!="function"||typeof ue.hasChildNodes!="function")},It=function(ue){return typeof c=="function"&&ue instanceof c};function Nr(vt,ue,je){Eh(vt,st=>{st.call(e,ue,je,ve)})}const un=function(ue){let je=null;if(Nr(pe.beforeSanitizeElements,ue,null),bt(ue))return at(ue),!0;const st=se(ue.nodeName);if(Nr(pe.uponSanitizeElement,ue,{tagName:st,allowedTags:Ce}),$e&&ue.hasChildNodes()&&!It(ue.firstElementChild)&&pi(/<[/\w!]/g,ue.innerHTML)&&pi(/<[/\w!]/g,ue.textContent)||ue.nodeType===sd.progressingInstruction||$e&&ue.nodeType===sd.comment&&pi(/<[/\w]/g,ue.data))return at(ue),!0;if(!(ut.tagCheck instanceof Function&&ut.tagCheck(st))&&(!Ce[st]||te[st])){if(!te[st]&&Mn(st)&&(wt.tagNameCheck instanceof RegExp&&pi(wt.tagNameCheck,st)||wt.tagNameCheck instanceof Function&&wt.tagNameCheck(st)))return!1;if(fn&&!kt[st]){const Jt=L(ue)||ue.parentNode,or=j(ue)||ue.childNodes;if(or&&Jt){const Pr=or.length;for(let en=Pr-1;en>=0;--en){const yn=k(or[en],!0);yn.__removalCount=(ue.__removalCount||0)+1,Jt.insertBefore(yn,A(ue))}}}return at(ue),!0}return ue instanceof o&&!it(ue)||(st==="noscript"||st==="noembed"||st==="noframes")&&pi(/<\/no(script|embed|frames)/i,ue.innerHTML)?(at(ue),!0):(Ot&&ue.nodeType===sd.text&&(je=ue.textContent,Eh([Q,Oe,Ve],Jt=>{je=rd(je,Jt," ")}),ue.textContent!==je&&(td(e.removed,{element:ue.cloneNode()}),ue.textContent=je)),Nr(pe.afterSanitizeElements,ue,null),!1)},qt=function(ue,je,st){if(lr&&(je==="id"||je==="name")&&(st in t||st in oe))return!1;if(!(Zt&&!ne[je]&&pi(Ze,je))){if(!(Pt&&pi(Xe,je))){if(!(ut.attributeCheck instanceof Function&&ut.attributeCheck(je,ue))){if(!Nt[je]||ne[je]){if(!(Mn(ue)&&(wt.tagNameCheck instanceof RegExp&&pi(wt.tagNameCheck,ue)||wt.tagNameCheck instanceof Function&&wt.tagNameCheck(ue))&&(wt.attributeNameCheck instanceof RegExp&&pi(wt.attributeNameCheck,je)||wt.attributeNameCheck instanceof Function&&wt.attributeNameCheck(je,ue))||je==="is"&&wt.allowCustomizedBuiltInElements&&(wt.tagNameCheck instanceof RegExp&&pi(wt.tagNameCheck,st)||wt.tagNameCheck instanceof Function&&wt.tagNameCheck(st))))return!1}else if(!Kr[je]){if(!pi(Y,rd(st,Je,""))){if(!((je==="src"||je==="xlink:href"||je==="href")&&ue!=="script"&&Uq(st,"data:")===0&&Xt[ue])){if(!(rt&&!pi(Re,rd(st,Je,"")))){if(st)return!1}}}}}}}return!0},Mn=function(ue){return ue!=="annotation-xml"&&gy(ue,Ke)},Ri=function(ue){Nr(pe.beforeSanitizeAttributes,ue,null);const{attributes:je}=ue;if(!je||bt(ue))return;const st={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:Nt,forceKeepAttr:void 0};let Jt=je.length;for(;Jt--;){const or=je[Jt],{name:Pr,namespaceURI:en,value:yn}=or,ci=se(Pr),Pi=yn;let Wr=Pr==="value"?Pi:Fq(Pi);if(st.attrName=ci,st.attrValue=Wr,st.keepAttr=!0,st.forceKeepAttr=void 0,Nr(pe.uponSanitizeAttribute,ue,st),Wr=st.attrValue,Xr&&(ci==="id"||ci==="name")&&(ht(Pr,ue),Wr=mn+Wr),$e&&pi(/((--!?|])>)|<\/(style|title|textarea)/i,Wr)){ht(Pr,ue);continue}if(ci==="attributename"&&gy(Wr,"href")){ht(Pr,ue);continue}if(st.forceKeepAttr)continue;if(!st.keepAttr){ht(Pr,ue);continue}if(!on&&pi(/\/>/i,Wr)){ht(Pr,ue);continue}Ot&&Eh([Q,Oe,Ve],Zs=>{Wr=rd(Wr,Zs," ")});const Qs=se(ue.nodeName);if(!qt(Qs,ci,Wr)){ht(Pr,ue);continue}if(x&&typeof y=="object"&&typeof y.getAttributeType=="function"&&!en)switch(y.getAttributeType(Qs,ci)){case"TrustedHTML":{Wr=x.createHTML(Wr);break}case"TrustedScriptURL":{Wr=x.createScriptURL(Wr);break}}if(Wr!==Pi)try{en?ue.setAttributeNS(en,Pr,Wr):ue.setAttribute(Pr,Wr),bt(ue)?at(ue):RE(e.removed)}catch{ht(Pr,ue)}}Nr(pe.afterSanitizeAttributes,ue,null)},jn=function vt(ue){let je=null;const st=pt(ue);for(Nr(pe.beforeSanitizeShadowDOM,ue,null);je=st.nextNode();)Nr(pe.uponSanitizeShadowNode,je,null),un(je),Ri(je),je.content instanceof s&&vt(je.content);Nr(pe.afterSanitizeShadowDOM,ue,null)};return e.sanitize=function(vt){let ue=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},je=null,st=null,Jt=null,or=null;if(ke=!vt,ke&&(vt="<!-->"),typeof vt!="string"&&!It(vt))if(typeof vt.toString=="function"){if(vt=vt.toString(),typeof vt!="string")throw nd("dirty is not a string, aborting")}else throw nd("toString is not a function");if(!e.isSupported)return vt;if(zt||Me(ue),e.removed=[],typeof vt=="string"&&(Kt=!1),Kt){if(vt.nodeName){const yn=se(vt.nodeName);if(!Ce[yn]||te[yn])throw nd("root node is forbidden and cannot be sanitized in-place")}}else if(vt instanceof c)je=jt("<!---->"),st=je.ownerDocument.importNode(vt,!0),st.nodeType===sd.element&&st.nodeName==="BODY"||st.nodeName==="HTML"?je=st:je.appendChild(st);else{if(!pr&&!Ot&&!_t&&vt.indexOf("<")===-1)return x&&Mr?x.createHTML(vt):vt;if(je=jt(vt),!je)return pr?null:Mr?B:""}je&&Fe&&at(je.firstChild);const Pr=pt(Kt?vt:je);for(;Jt=Pr.nextNode();)un(Jt),Ri(Jt),Jt.content instanceof s&&jn(Jt.content);if(Kt)return vt;if(pr){if(er)for(or=D.call(je.ownerDocument);je.firstChild;)or.appendChild(je.firstChild);else or=je;return(Nt.shadowroot||Nt.shadowrootmode)&&(or=X.call(n,or,!0)),or}let en=_t?je.outerHTML:je.innerHTML;return _t&&Ce["!doctype"]&&je.ownerDocument&&je.ownerDocument.doctype&&je.ownerDocument.doctype.name&&pi(aO,je.ownerDocument.doctype.name)&&(en="<!DOCTYPE "+je.ownerDocument.doctype.name+`>
|
|
2
|
-
`+en),Ot&&Eh([Q,Oe,Ve],yn=>{en=rd(en,yn," ")}),x&&Mr?x.createHTML(en):en},e.setConfig=function(){let vt=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Me(vt),zt=!0},e.clearConfig=function(){ve=null,zt=!1},e.isValidAttribute=function(vt,ue,je){ve||Me({});const st=se(vt),Jt=se(ue);return qt(st,Jt,je)},e.addHook=function(vt,ue){typeof ue=="function"&&td(pe[vt],ue)},e.removeHook=function(vt,ue){if(ue!==void 0){const je=Nq(pe[vt],ue);return je===-1?void 0:Lq(pe[vt],je,1)[0]}return RE(pe[vt])},e.removeHooks=function(vt){pe[vt]=[]},e.removeAllHooks=function(){pe=xE()},e}var e6=oO();const t6={ALLOWED_TAGS:["b","i","em","strong","p","br","ul","ol","li","a"],ALLOWED_ATTR:["href","src","alt","title","target","class","id","style"],ALLOW_DATA_ATTR:!1,FORBID_TAGS:["img","iframe","object","input","style","script","embed","svg","video","audio","body","input","form","link"],FORBID_ATTR:["onerror","onclick","onload","onmouseover","onfocus","onblur","onchange","onsubmit","scr","href","style","action","value"],IN_PLACE:!0},r6="javascript:";var Lu;let Xc=(Lu=class extends Error{constructor(t,n,i){super(t);be(this,"code",Lu.CODE);be(this,"refusedBy");this.name="UnauthorizedError",this.refusedBy=n,i&&"cause"in i&&(this.cause=i.cause)}},be(Lu,"CODE","UNAUTHORIZED"),Lu);function n6(r){return(r==null?void 0:r.constructor)===Object}async function ME(r,e=3){let t=0,n;for(;t<=e;){t+=1;try{return await r()}catch(i){if(i instanceof Xc)throw i;n=i,console.error(i),await sv(1e3*Math.pow(2,t))}}throw n}function sv(r){return new Promise(e=>{setTimeout(()=>{e(0)},r)})}function Rw(){return Math.random().toString(36).slice(2)}const i6=new TextDecoder,s6=r=>{const e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return i6.decode(t)},a6=r=>r.length===0,o6=(...r)=>r.every(a6),$b=r=>{const e=e6.sanitize(r,t6);return e.includes(r6)?(console.warn("Suspicious content detected and removed."),""):e},u6=[8,4,4,4,12],c6=()=>{const r=globalThis.crypto;if(!r)return null;if(typeof r.randomUUID=="function")return r.randomUUID();if(typeof r.getRandomValues!="function")return null;const e=r.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=Array.from(e,i=>i.toString(16).padStart(2,"0")).join("");let n=0;return u6.map(i=>{const s=t.slice(n,n+i);return n+=i,s}).join("-")},l6="prod",Pw="6.22.0",DE="https://main.api.ujet.co",zn={companyId:"",tenant:"",trackerId:"",deviceId:"",application:"websdk",version:Pw};class d6{constructor(e){be(this,"buffer");be(this,"writeIndex",0);be(this,"size",0);be(this,"capacity");this.capacity=e,this.buffer=new Array(e)}push(e){this.buffer[this.writeIndex]=e,this.writeIndex++,this.writeIndex>=this.capacity&&(this.writeIndex=0),this.size<this.capacity&&this.size++}toArray(){return this.size<this.capacity?this.buffer.slice(0,this.size):[...this.buffer.slice(this.writeIndex),...this.buffer.slice(0,this.writeIndex)]}clear(){this.writeIndex=0,this.size=0,this.buffer=new Array(this.capacity)}}const Lo=class Lo{constructor(e){be(this,"channel");this.channel=e}static addHandler(e){Lo.logHandlers.push(e)}static printLogHistoryData(e){Lo.consoleLog(e.channel,e.level,...e.args)}static consoleLog(e,t,...n){console[t](`[${t}][${e}]`,...n)}debug(...e){this.log("debug",...e)}info(...e){this.log("info",...e)}warn(...e){this.log("warn",...e)}error(...e){this.log("error",...e)}log(e,...t){const n=t.map(Iw);Lo.logHandlers.forEach(i=>i(this.channel,e,...n)),Lo.logHistory.push({date:new Date().toISOString(),channel:this.channel,level:e,args:n})}};be(Lo,"logHandlers",[]),be(Lo,"logHistory",new d6(1e3));let an=Lo;const f6=(r,e,...t)=>{let n=t.pop();return typeof n=="string"&&(t.push(n),n={}),{loglevel:e,channel:r,timestamp:new Date().toISOString(),application:zn.application,sdk_version:zn.version,device_uuid:zn.deviceId,tenant:zn.tenant,company_id:zn.companyId,tracker_id:zn.trackerId||void 0,location_url:location.href,data:p6(n),message:Iw(t.join(" "))}},NE=["user","phone","phone_number","phoneNumber","email","token","access_token","accessToken","authorization","Authorization"],h6=[/(?:3[47]\d|(?:4\d|5[1-5]|65)\d{2}|6011)\d{12}/g,/(?!(000|666|9))\d{3}-(?!00)\d{2}-(?!0000)\d{4}/g,/[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)+/g,/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g];function Iw(r){return Lc(r,new WeakSet)}function Lc(r,e){if(!r)return r;if(typeof r=="string")return h6.forEach(t=>{r=r.replace(t,"__MASKED__")}),r;if(typeof r=="object"&&e.has(r))return"[Circular]";if(typeof r=="object"&&e.add(r),Array.isArray(r))return r.map(t=>Lc(t,e));if(r instanceof Error){const t={name:r.name,message:Lc(r.message,e)};r.stack&&(t.stack=Lc(r.stack,e));for(const n of Object.getOwnPropertyNames(r))n==="name"||n==="message"||n==="stack"||(NE.indexOf(n)!==-1?t[n]="__MASKED__":t[n]=Lc(r[n],e));return t}return n6(r)&&(r={...r},Object.keys(r).forEach(t=>{NE.indexOf(t)!==-1?r[t]="__MASKED__":r[t]=Lc(r[t],e)})),r}function p6(r){if(r.error){const e=r.error;return{error:{name:e.name,message:e.message,stack:e.stack}}}return Iw(r.data)}const v6=new an("chat-provider");class Hv{constructor(e,t,n,i){be(this,"audio");be(this,"issueChatToken");be(this,"identity");be(this,"channelId");be(this,"region");be(this,"inTask",!1);be(this,"muted",!1);be(this,"providerContext");be(this,"events");this.events=e,this.region=t.region,this.audio=new $q,this.issueChatToken=n,this.providerContext=i}async reconnect(){}ping(){if(!this.muted)try{this.audio.playPing()}catch(e){v6.warn("Chat audio play failed",{error:e})}}cleanupAudio(){this.audio&&this.audio.cleanup()}on(e,t){this.events.addEventListener(e,t)}off(e,t){this.events.removeEventListener(e,t)}trackInTask(e){e.type===ln.NOTI&&e.event===Gn.TASK_VA_STARTED?this.inTask=!0:e.type===ln.NOTI&&(e.event===Gn.TASK_VA_FINISHED||e.event===Gn.TASK_VA_FAILED)&&(this.inTask=!1)}}be(Hv,"type","base");const uO={};function Gv(r){uO[r.type]=r}function g6(r){return uO[r]}const Dv=class Dv extends Error{constructor(t){super("Cannot send a message: the chat has already ended");be(this,"code",Dv.CODE);be(this,"status");this.name="ChatEndedError",this.status=t}};be(Dv,"CODE","CHAT_ENDED");let av=Dv;const LE=new an("MediaStore"),m6=window.indexedDB||window.webkitIndexedDB||window.mozIndexedDB||window.OIndexedDB||window.msIndexedDB,y6="chat-media",UE=1,ov="file";class cO{constructor(){be(this,"db")}store(){return new Promise((e,t)=>{if(this.db)return e(FE(this.db));const n=m6.open(y6,UE);n.onerror=()=>{t(new Error("indexedDB open failed"))},n.onsuccess=()=>{const i=n.result;this.db=i,e(FE(i))},n.onupgradeneeded=i=>{const s=n.result;i.oldVersion>0&&i.oldVersion<UE&&(LE.info("deprecating media store"),s.deleteObjectStore(ov)),LE.info("creating media store"),s.createObjectStore(ov)}})}async save(e,t){(await this.store()).put({index:e,file:t},e)}async getAll(){const e=await this.store();return await new Promise((t,n)=>{const i=e.getAll();i.onerror=()=>{n(new Error("indexedDB getAll failed"))},i.onsuccess=()=>{t(i.result)}})}async getAllFiles(){const e={};return(await this.getAll()).forEach(n=>{e[n.index]=n.file}),e}async clear(){(await this.store()).clear()}}function FE(r){return r.transaction(ov,"readwrite").objectStore(ov)}const Bp={LOADED:"cobrowse.loaded",UPDATED:"cobrowse.updated",ENDED:"cobrowse.ended"},jE=1e4,_6=3e4,b6=9e5,lO={UPDATED:"riskFlagsUpdated"},wu=new an("Communicator");var Fo,rf;class S6{constructor(e,t){be(this,"user");be(this,"clientEventManager");be(this,"clientAuthenticate");be(this,"config");be(this,"channel");be(this,"channelReady",!1);be(this,"hasAuthenticated",!1);be(this,"hasInitializedLogProxy",!1);be(this,"queuedMessagesToBridge",[]);be(this,"pendingBridgeRequests",{});be(this,"bridgeIframe");be(this,"bridgeMessageHandlers");be(this,"tokenRefreshTimeout");be(this,"logProxyQueue",[]);hy(this,Fo,"");hy(this,rf,0);be(this,"authRefreshInFlight",null);be(this,"riskFlags",null);this.onReady=this.onReady.bind(this),this.onCallback=this.onCallback.bind(this),this.onRefreshToken=this.onRefreshToken.bind(this),this.onRiskFlags=this.onRiskFlags.bind(this),this.onMessageFromBridge=this.onMessageFromBridge.bind(this),this.clientAuthenticate=e.authenticate,this.clientEventManager=t,this.initConfig(e),this.channel=new MessageChannel,this.channel.port1.onmessage=this.onMessageFromBridge,this.initBridge()}get wsUrl(){return this.config.host.replace(/^http/,"ws")+"/ws"}async getAuthToken(e=!1){if(!e&&this.isAuthTokenFresh())return Rc(this,Fo);const t=await this.refreshAuthToken();if(!t)throw new Error("Auth refresh completed without a token");return t}async request(e,t){!this.hasAuthenticated&&e!=="proactive_chat_triggers"&&await this.onRefreshToken();const n={url:e,options:t};return this.postMessageWithCallbackToBridge("request",n)}leaveChatBeacon(e){var n;if(!Rc(this,Fo)||!((n=this.config)!=null&&n.host))return;const t=`${this.config.host}/api/v2/chats/${e}/leave`;fetch(t,{method:"POST",body:"{}",keepalive:!0,headers:{Authorization:`Bearer ${Rc(this,Fo)}`,"Content-Type":"application/json","UJET-SDK-Type":"Web"}}).catch(()=>{})}destroy(){delete this.channel,this.bridgeIframe&&(this.bridgeIframe.remove(),this.bridgeIframe=void 0),this.tokenRefreshTimeout&&clearTimeout(this.tokenRefreshTimeout)}getBridgeLogHistory(){return this.postMessageWithCallbackToBridge("_getLogHistory",{})}isRiskFlagEnabled(e){var t;return((t=this.riskFlags)==null?void 0:t[e])??!0}getRiskFlags(){return{...this.riskFlags??{}}}initBridge(){const e=document.createElement("iframe");e.src=this.config.bridge,e.setAttribute("style","display:none"),e.addEventListener("load",()=>{if(wu.debug("initialized iframe for origin:",this.config.bridgeOrigin),!this.channelReady){const t={type:"_init",data:this.config};wu.debug("sending message to bridge:",t),e.contentWindow.postMessage(t,this.config.bridgeOrigin,[this.channel.port2])}}),document.body.appendChild(e),this.bridgeIframe=e,this.bridgeMessageHandlers={ready:this.onReady,callback:this.onCallback,refreshToken:this.onRefreshToken,_riskFlags:this.onRiskFlags}}onReady(e){this.channelReady=!0,zn.deviceId=e.result.deviceId,zn.deviceId||wu.error("Device Id has not been provided. SDK will not work properly."),this.flushQueuedMessagesToBridge(),this.clientEventManager.triggerEvent("ready")}onCallback(e){if(!e.callbackId)return;const[t,n]=this.pendingBridgeRequests[e.callbackId];e.error?n(e.error):t(e.result),delete this.pendingBridgeRequests[e.callbackId]}async onRefreshToken(){try{await this.refreshAuthToken()}catch(e){if(!(e instanceof Xc))throw e;if(e.refusedBy==="client")throw e.cause;wu.error(e.message)}}isAuthTokenFresh(){return!!Rc(this,Fo)&&Rc(this,rf)-Date.now()>_6}refreshAuthToken(){return this.authRefreshInFlight??(this.authRefreshInFlight=this.performAuth().finally(()=>{this.authRefreshInFlight=null})),this.authRefreshInFlight}async performAuth(){this.hasAuthenticated=!0;let e;try{e=await this.clientAuthenticate()}catch(i){throw new Xc("Client authenticate callback rejected","client",{cause:i})}const t=await this.serverAuthenticate(e.token);if(t.error)throw new Xc("Failed to validate client authenticate response token with UJET server","server");t.auth_token&&this.setAuthToken(t.auth_token);const n=this.decodeJwt(e.token);return this.user={identifier:n.identifier,name:n.name,email:n.email},n.exp&&this.enqueueTokenRefresh(n.exp),this.initLogProxyHandler(t),wu.info("Web SDK authenticated"),this.clientEventManager.triggerEvent("authenticate"),this.clientEventManager.triggerEvent("authenticated"),t.auth_token??""}setAuthToken(e){py(this,Fo,e),py(this,rf,this.readTokenExpiry(e))}readTokenExpiry(e){try{const{exp:t}=this.decodeJwt(e);return typeof t!="number"?0:t.toString().length===13?t:t*1e3}catch{return 0}}onRiskFlags(e){var n;const t=(n=e.result)==null?void 0:n.flags;t&&(this.riskFlags=t,this.clientEventManager.triggerEvent(lO.UPDATED,this.getRiskFlags()))}onMessageFromBridge(e){var n;wu.debug("received message from bridge:",e.data);const t=this.bridgeMessageHandlers[(n=e.data)==null?void 0:n.type];t&&t(e.data)}postMessageToBridge(e){this.channel&&this.channelReady?(wu.debug("sending message to bridge:",e),this.channel.port1.postMessage(e)):this.queuedMessagesToBridge.push(e)}flushQueuedMessagesToBridge(){for(;this.queuedMessagesToBridge.length;){const e=this.queuedMessagesToBridge.shift();this.postMessageToBridge(e)}}postMessageWithCallbackToBridge(e,t){return new Promise((n,i)=>{const s=Rw()+"_"+Date.now();this.pendingBridgeRequests[s]=[n,i];const a={type:e,callbackId:s,data:t};this.postMessageToBridge(a)})}initConfig(e){var l;let t=e.host;t||(e.tenant?t=DE.replace("main.api",e.tenant):t=DE);const n=e.lang||"en",i=!!((l=e.cobrowse)!=null&&l.enabled),a=(e.bridge||"https://websdk.ujet.co/v3/bridge.html")+"?6.22.0",c=/^https:/.test(a)?new URL(a).origin:"*",o=["twilio_chat","nexmo_chat","ujet_chat"];i&&o.push("cobrowse"),this.config={host:t,lang:n,cobrowse:i,companyId:e.companyId,location:location.href,version:e.version||"6.22.0",bridge:a,bridgeOrigin:c,modules:o}}initLogProxyHandler(e){!this.hasInitializedLogProxy&&e.log_proxy_url&&(this.hasInitializedLogProxy=!0,an.addHandler((t,n,...i)=>{if(n==="debug")return;const s=f6(t,n,...i);this.logProxyQueue.push(s)}),this.sendLogsToBridge())}sendLogsToBridge(){this.logProxyQueue.length&&(this.postMessageToBridge({type:"_log",data:{num_of_logs:this.logProxyQueue.length,logs:this.logProxyQueue}}),this.logProxyQueue=[]),setTimeout(()=>{this.sendLogsToBridge()},2e3)}serverAuthenticate(e){return this.postMessageWithCallbackToBridge("_auth",{modules:this.config.modules,user:{token:e,company_id:this.config.companyId}})}enqueueTokenRefresh(e){clearTimeout(this.tokenRefreshTimeout);const t=this.normalizeJwtExp(e),n=Math.max(t-Date.now()-jE,jE);this.tokenRefreshTimeout=setTimeout(()=>{this.onRefreshToken()},n)}decodeJwt(e){const t=e.split(".")[1];return JSON.parse(s6(t))}normalizeJwtExp(e){return e.toString().length===13?e:e.toString().length===10?e*1e3:Date.now()+b6}}Fo=new WeakMap,rf=new WeakMap;const w6=new an("EventManager");class zv{constructor(){be(this,"handlers",{})}addEventListener(e,t){this.handlers[e]||(this.handlers[e]=[]),this.handlers[e].push(t)}triggerEvent(e,t){w6.debug(`event triggered: ${e}`);const n=this.handlers[e];n&&n.forEach(i=>{i(t)})}removeEventListener(e,t){if(this.handlers[e]){const n=this.handlers[e].indexOf(t);n!==-1&&this.handlers[e].splice(n,1)}}destroy(){this.handlers={}}}function T6(r,e){const t={};return e.forEach(n=>{t[n.id]=n}),r.map(n=>{if(n.type===ln.SERVER_MESSAGE){const i=n.server_message_id??n.message_id,s=t[i];dO(n,s.content)}return n})}function C6(r,e){return dO(r,e.content)}function dO(r,e){return Object.keys(e).forEach(t=>{r[t]=e[t]}),r}const BE={photo:2,video:2,audio:1,document:1};function E6(r){return r.toSorted((e,t)=>!e.groupMessageId||!t.groupMessageId||e.groupMessageId!==t.groupMessageId?0:(BE[t.type]||0)-(BE[e.type]||0))}function k6(r){try{const{pathname:e}=new URL(r),t=e.split("/").filter(n=>n.length>0);return t.length>0?decodeURIComponent(t[t.length-1]):"document"}catch{return"document"}}function R6(r,e){r.forEach(t=>{if(t.type==="document"&&t.media_id!=null){const n=e.find(i=>i.media_id===t.media_id);n&&n.url&&(t.document={url:n.url},t.title||(t.title=k6(n.url)))}})}const P6={confirmSessionTitle:"Screen Share Session Request",confirmSessionContent:"Do you want to share your current screen with the agent?",endSessionText:"End Screen Share Session",confirmRemoteControlTitle:"Remote Access Request",confirmRemoteControlContent:"The agent would like to have access to your currently shared screen to further assist you. Do you want to allow this?",confirmFullDeviceTitle:"Screen Share Request",confirmFullDeviceContent:"Do you want to share your full screen with the agent? The agent will not be able to control anything on the screen.",allowText:"Allow",denyText:"Deny"},I6={confirmSessionTitle:"Solicitud de sesión de conavegación",confirmSessionContent:"¿Desea compartir su pantalla actual con el agente?",endSessionText:"Fin de la sesión de conavegación",confirmRemoteControlTitle:"Solicitud de acceso remoto",confirmRemoteControlContent:"El agente desea tener acceso a su pantalla actual compartida para seguir asistiéndole. ¿Desea permitirlo?",confirmFullDeviceTitle:"Solicitud de compartir pantalla",confirmFullDeviceContent:"¿Desea compartir su pantalla completa con el agente? El agente no podrá controlar nada de la pantalla.",allowText:"Permitir",denyText:"Denegar"},A6={confirmSessionTitle:"Demande de session de co-navigation",confirmSessionContent:"Voulez-vous partager votre écran actuel avec l'agent ?",endSessionText:"Terminer la session de co-navigation",confirmRemoteControlTitle:"Demande d'accès à distance",confirmRemoteControlContent:"L'agent souhaite avoir accès à l'écran que vous partagez actuellement pour mieux vous aider. Voulez-vous l'y autoriser ?",confirmFullDeviceTitle:"Demande de partage d'écran",confirmFullDeviceContent:"Voulez-vous partager votre écran complet avec l'agent ? L'agent ne sera pas en mesure de contrôler quoi que ce soit sur l'écran.",allowText:"Autoriser",denyText:"Refuser"},O6={confirmSessionTitle:"Screen Share-Sitzungsanfrage",confirmSessionContent:"Möchten Sie Ihren aktuellen Bildschirm für den Agenten freigeben?",endSessionText:"Screen Share-Sitzung beenden",confirmRemoteControlTitle:"Fernzugriff-Anfrage",confirmRemoteControlContent:"Der Agent möchte Zugriff auf Ihren aktuell freigegebenen Bildschirm erhalten, um Ihnen weiterhelfen zu können. Möchten Sie dies erlauben?",confirmFullDeviceTitle:"Bildschirmfreigabe",confirmFullDeviceContent:"Möchten Sie Ihren gesamten Bildschirm für den Agenten freigeben? Der Agent ist dadurch nicht in der Lage, Elemente auf Ihrem Bildschirm zu steuern.",allowText:"Erlauben",denyText:"Verweigern"},$6={confirmSessionTitle:"共同ブラウジングセッションリクエスト",confirmSessionContent:"現在の画面を担当者と共有したいですか。",endSessionText:"共同ブラウジングセッションを終了",confirmRemoteControlTitle:"リモートアクセスリクエスト",confirmRemoteControlContent:"担当者は、お客様をさらにお手伝いするために、現在共有中の画面へのアクセスを希望しています。許可しますか。",confirmFullDeviceTitle:"画面共有リクエスト",confirmFullDeviceContent:"画面全体を担当者と共有したいですか。担当者は画面上で一切の操作ができません。",allowText:"許可",denyText:"拒否"},x6={confirmSessionTitle:"코브라우징 세션 요청",confirmSessionContent:"현재 화면을 상담원과 공유하시겠습니까?",endSessionText:"코브라우징 세션 종료",confirmRemoteControlTitle:"원격 액세스 요청",confirmRemoteControlContent:"상담원이 추가 지원을 위해 현재 공유된 화면에 액세스할 수 있기를 원합니다. 허용하시겠습니까?",confirmFullDeviceTitle:"화면 공유 요청",confirmFullDeviceContent:"상담원과 전체 화면을 공유하시겠습니까? 상담원은 화면의 어떤 부분도 제어할 수 없습니다.",allowText:"허용",denyText:"거절"},M6={confirmSessionTitle:"Richiesta di sessione di Screen Share",confirmSessionContent:"Vuoi condividere la tua schermata attuale con l'operatore?",endSessionText:"Termina sessione di Screen Share",confirmRemoteControlTitle:"Richiesta di accesso remoto",confirmRemoteControlContent:"L'operatore vorrebbe accedere alla tua schermata attualmente condivisa per assisterti al meglio. Acconsenti?",confirmFullDeviceTitle:"Richiesta di condivisione schermo",confirmFullDeviceContent:"Vuoi condividere il tuo intero schermo con l'operatore? L'operatore non potrà controllare nessun elemento sullo schermo.",allowText:"Consenti",denyText:"Rifiuta"},D6={confirmSessionTitle:"同步浏览会话请求",confirmSessionContent:"您是否要向该客服代表共享当前的屏幕?",endSessionText:"结束同步浏览会话",confirmRemoteControlTitle:"远程访问请求",confirmRemoteControlContent:"为了进一步协助您,客服代表想访问您当前的共享屏幕。您是否允许这样做?",confirmFullDeviceTitle:"屏幕共享请求",confirmFullDeviceContent:"您是否要向该客服代表共享全屏?客服代表将不能控制屏幕上的任何东西。",allowText:"允许",denyText:"拒绝"},N6={confirmSessionTitle:"Samwebbläsningssession har begärts",confirmSessionContent:"Vill du dela din aktuella skärm med vår medarbetare?",endSessionText:"Avsluta samwebbläsningssession",confirmRemoteControlTitle:"Begäran om fjärråtkomst",confirmRemoteControlContent:"Vår medarbetare skulle vilja få åtkomst till skärmen som du delar just nu för att kunna hjälpa dig vidare. Vill du tillåta detta?",confirmFullDeviceTitle:"Begäran om skärmdelning",confirmFullDeviceContent:"Vill du dela hela skärmen med medarbetaren? Medarbetaren kommer inte kunna kontrollera något på skärmen.",allowText:"Tillåt",denyText:"Neka"},L6={confirmSessionTitle:"Solicitação de Sessão de Co-navegação",confirmSessionContent:"Deseja partilhar o seu ecrã atual com o agente?",endSessionText:"Terminar Sessão de Co-navegação",confirmRemoteControlTitle:"Solicitação de Acesso Remoto",confirmRemoteControlContent:"O agente gostaria de ter acesso ao seu ecrã partilhado atualmente para ajudá-lo ainda mais. Quer permitir isto?",confirmFullDeviceTitle:"Solicitação de Partilha de Ecrã",confirmFullDeviceContent:"Deseja partilhar o seu ecrã inteiro com o agente? O agente não poderá controlar nada no ecrã.",allowText:"Permitir",denyText:"Negar"},U6={confirmSessionTitle:"Pyyntö yhteisselausistunnosta",confirmSessionContent:"Haluatko jakaa nykyisen näyttösi edustajan kanssa?",endSessionText:"Lopeta yhteisselausistunto",confirmRemoteControlTitle:"Etäkäyttöpyyntö",confirmRemoteControlContent:"Edustaja haluaisi saada käyttää tällä hetkellä jakamaasi näyttöä voidakseen auttaa sinua enemmän. Haluatko antaa siihen luvan?",confirmFullDeviceTitle:"Näytön jakamispyyntö",confirmFullDeviceContent:"Haluatko jakaa koko näyttösi edustajan kanssa? Edustaja ei pysty käyttämään mitään näytöllä olevaa.",allowText:"Salli",denyText:"Estä"},F6={confirmSessionTitle:"Samlesingsøkten er startet",confirmSessionContent:"Vil du dele skjermen din med agenten?",endSessionText:"Avslutt samlesingsøkt",confirmRemoteControlTitle:"Forespørsel om fjerntilgang",confirmRemoteControlContent:"Agenten vil ha tilgang til skjermen din for å kunne hjelpe deg videre. Vil du tillate dette?",confirmFullDeviceTitle:"Forespørsel om skjermdeling",confirmFullDeviceContent:"Vil du dele hele skjermen din med agenten? Agenten kan ikke kontrollere noe på skjermen.",allowText:"Tillat",denyText:"Avvis"},j6={confirmSessionTitle:"Forespørgsel om sambrowsingsession",confirmSessionContent:"Vil du dele din nuværende skærm med agenten",endSessionText:"Afslut sambrowsingsession",confirmRemoteControlTitle:"Anmodning om fjernadgang",confirmRemoteControlContent:"Agenten vil gerne have adgang til din nuværende delte skærm for at kunne hjælpe dig yderligere. Ønsker du at tillade dette?",confirmFullDeviceTitle:"Forespørgsel om skærmdeling",confirmFullDeviceContent:"Vil du dele din fulde skærm med agenten? Agenten vil ikke kunne styre noget på skærmen",allowText:"Tillad",denyText:"Afvis"},B6={confirmSessionTitle:"Verzoek om cobrowse-sessie",confirmSessionContent:"Wilt u uw huidige scherm delen met de agent?",endSessionText:"Cobrowse-sessie beëindigen",confirmRemoteControlTitle:"Verzoek om toegang op afstand",confirmRemoteControlContent:"De agent wil graag toegang hebben tot uw momenteel gedeelde scherm om u verder te helpen. Wilt u dit toestaan?",confirmFullDeviceTitle:"Verzoek om scherm te delen",confirmFullDeviceContent:"Wilt u uw volledige scherm delen met de agent? De agent kan niets op het scherm bedienen.",allowText:"Toestaan",denyText:"Weigeren"},q6={confirmSessionTitle:"Oturum İsteğini Eş Zamanlı Tara",confirmSessionContent:"Mevcut ekranınızı temsilciyle paylaşmak ister misiniz?",endSessionText:"Eş zamanlı Oturum Taramayı Sonlandır",confirmRemoteControlTitle:"Uzaktan Erişim İsteği",confirmRemoteControlContent:"Temsilci şu anda paylaşılan ekranınıza size daha fazla yardımcı olabilmek için erişim sağlamak istiyor. Buna izin vermek istiyor musunuz?",confirmFullDeviceTitle:"Ekran Paylaşım İsteği",confirmFullDeviceContent:"Temsilciyle tam ekranınızı paylaşmak istiyor musunuz? Temsilci ekrandaki hiçbir şeyi kontrol edemez.",allowText:"İzin Ver",denyText:"Reddet"},W6={confirmSessionTitle:"Yêu cầu phiên cùng duyệt",confirmSessionContent:"Bạn có muốn chia sẻ màn hình hiện tại của mình với chuyên viên không?",endSessionText:"Kết thúc phiên cùng duyệt",confirmRemoteControlTitle:"Yêu cầu truy cập từ xa",confirmRemoteControlContent:"Chuyên viên muốn được cấp quyền truy cập vào màn hình bạn đang chia sẻ để hỗ trợ bạn nhiều hơn. Bạn có muốn cho phép không?",confirmFullDeviceTitle:"Yêu cầu chia sẻ màn hình",confirmFullDeviceContent:"Bạn có muốn chia sẻ toàn bộ màn hình của mình với chuyên viên không? Chuyên viên sẽ không thể điều khiển bất cứ phần nào trên màn hình.",allowText:"Cho phép",denyText:"Từ chối"},V6={confirmSessionTitle:"ขอเซสชันเรียกดูร่วม",confirmSessionContent:"คุณต้องการแชร์หน้าจอปัจจุบันกับตัวแทนหรือไม่",endSessionText:"สิ้นสุดเซสชันเรียกดูร่วม",confirmRemoteControlTitle:"ขอการเข้าถึงระยะไกล",confirmRemoteControlContent:"ตัวแทนต้องการเข้าถึงหน้าจอของคุณที่แชร์อยู่ในปัจจุบันเพื่อให้ความช่วยเหลือคุณต่อไป คุณจะอนุญาตหรือไม่",confirmFullDeviceTitle:"ขอแชร์หน้าจอ",confirmFullDeviceContent:"คุณต้องการแชร์ทั้งหน้าของคุณกับตัวแทนหรือไม่ ตัวแทนจะไม่สามารถควบคุมอะไรบนหน้าจอ",allowText:"ยินยอม",denyText:"ปฏิเสธ"},H6={confirmSessionTitle:"طلب جلسة تصفح مشترك",confirmSessionContent:"هل تريد مشاركة شاشتك الحالية مع الموظف؟",endSessionText:"إنهاء جلسة التصفح المشترك",confirmRemoteControlTitle:"طلب التحكم عن بعد",confirmRemoteControlContent:"يرغب مسئول الدعم في رؤية شاشتك المشاركة حالياً لمساعدتك بشكلٍ أكبر. هل تسمح بذلك؟",confirmFullDeviceTitle:"طلب مشاركة الشاشة",confirmFullDeviceContent:"هل تريد مشاركة شاشتك الكاملة مع مسئول الدعم؟ لن يتمكن المسئول من التحكم في أي شيء على الشاشة.",allowText:"السماح",denyText:"الرفض"},G6={confirmSessionTitle:"Žádost o relaci Screen Share",confirmSessionContent:"Chcete svou současnou obrazovku sdílet s agentem?",endSessionText:"Ukončit relaci Screen Share",confirmRemoteControlTitle:"Žádost o vzdálený přístup",confirmRemoteControlContent:"Agent by rád získal přístup k vaší stávající sdílené obrazovce, aby vám mohl dál pomoci. Chcete mu přístup povolit?",confirmFullDeviceTitle:"Žádost o sdílení obrazovky",confirmFullDeviceContent:"Chcete svou celou obrazovku sdílet s agentem? Agent nebude moci ovládat nic, co na obrazovce je.",allowText:"Povolit",denyText:"Zamítnout"},z6={confirmSessionTitle:"Prośba o sesję Screen Share",confirmSessionContent:"Czy chcesz udostępnić konsultantowi swój bieżący ekran?",endSessionText:"Zakończ sesję Screen Share",confirmRemoteControlTitle:"Prośba o zdalny dostęp",confirmRemoteControlContent:"Konsultant prosi o dostęp do Twojego aktualnie udostępnionego ekranu, aby udzielić Ci dalszej pomocy. Czy chcesz na to zezwolić?",confirmFullDeviceTitle:"Prośba o udostępnienie ekranu",confirmFullDeviceContent:"Czy chcesz udostępnić konsultantowi swój cały ekran? Konsultant nie będzie mógł kontrolować niczego na ekranie.",allowText:"Zezwól",denyText:"Odmów"},K6={confirmSessionTitle:"Screen Share munkameneti kérés",confirmSessionContent:"Megosztja az aktuális képernyőjét a képviselővel?",endSessionText:"Screen Share munkamenet befejezése",confirmRemoteControlTitle:"Távoli hozzáférési kérés",confirmRemoteControlContent:"A képviselő szeretne hozzáférni a jelenleg megosztott képernyőjéhez, hogy további segítséget nyújthasson. Engedélyezi ezt?",confirmFullDeviceTitle:"Képernyőmegosztási kérelem",confirmFullDeviceContent:"Megosztja a teljes képernyőjét az ügynökkel? Az ügynök semmit sem tud majd irányítani a képernyőn.",allowText:"Engedélyezés",denyText:"Elutasítás"},J6={confirmSessionTitle:"Запрос сеанса совместного просмотра веб-страниц",confirmSessionContent:"Хотите поделиться вашим текущим экраном с представителем?",endSessionText:"Завершить сеанс совместного просмотра веб-страниц",confirmRemoteControlTitle:"Запрос на удаленный доступ",confirmRemoteControlContent:"Представитель хочет получить доступ к вашему текущему экрану, которым вы делитесь, чтобы помочь вам. Хотите разрешить это?",confirmFullDeviceTitle:"Запрос на совместный просмотр экрана",confirmFullDeviceContent:"Хотите поделиться вашим полный экраном с представителем? Агент не сможет выполнять никаких действий на экране.",allowText:"Разрешить",denyText:"Отказать"},Y6={confirmSessionTitle:"सह-ब्राउज़ सत्र अनुरोध किया गया",confirmSessionContent:"क्या आप अपनी वर्तमान स्क्रीन को एजेंट के साथ साझा करना चाहते हैं?",endSessionText:"सह-ब्राउज़ सत्र समाप्त करें",confirmRemoteControlTitle:"रिमोट पहुँच का अनुरोध किया गया",confirmRemoteControlContent:"एजेंट आपकी वर्तमान साझा स्क्रीन तक पहुँच प्राप्त करना चाहेगा ताकि वह आपकी और सहायता कर सके। क्या आप इसकी अनुमति देना चाहते हैं?",confirmFullDeviceTitle:"स्क्रीन साझाकरण अनुरोध",confirmFullDeviceContent:"क्या आप अपनी पूरी स्क्रीन एजेंट के साथ साझा करना चाहते हैं? एजेंट स्क्रीन पर कुछ भी नियंत्रित नहीं कर पाएगा।",allowText:"अनुमति दें",denyText:"अस्वीकार करें"},X6={confirmSessionTitle:"Solicitare sesiune de co-navigare",confirmSessionContent:"Doriți să partajați ecranul dumneavoastră curent cu agentul?",endSessionText:"Încheiați sesiunea de co-navigare",confirmRemoteControlTitle:"Cerere de acces la distanță",confirmRemoteControlContent:"Agentul ar dori să aibă acces la ecranul dumneavoastră partajat pentru a vă ajuta în continuare. Doriți să permiteți acest lucru?",confirmFullDeviceTitle:"Cerere de partajare a ecranului",confirmFullDeviceContent:"Doriți să partajați ecranul dumneavoastră complet cu agentul? Agentul nu va putea controla nimic de pe ecran.",allowText:"Permiteți",denyText:"Refuzați"},Q6={confirmSessionTitle:"Zahtjev za sesiju zajedničkog pregledavanja",confirmSessionContent:"Želite li podijeliti svoj trenutni zaslon s agentom?",endSessionText:"Završi sesiju zajedničkog pregledavanja",confirmRemoteControlTitle:"Zahtjev za daljinski pristup",confirmRemoteControlContent:"Agent želi imati pristup vašem trenutno dijeljenom zaslonu kako bi Vam dodatno pomogao. Želite li to dopustiti?",confirmFullDeviceTitle:"Zahtjev za dijeljenje zaslona",confirmFullDeviceContent:"Želite li s agentom podijeliti svoj cijeli zaslon? Agent neće moći ništa kontrolirati na ekranu.",allowText:"Dopustiti",denyText:"Odbiti"},Z6={confirmSessionTitle:"Запит на сесію спільного перегляду",confirmSessionContent:"Чи Ви хочете поділитись з агентом своїм поточним екраном?",endSessionText:"Завершити сесію спільного перегляду",confirmRemoteControlTitle:"Запит на віддалений доступ",confirmRemoteControlContent:"Агент хоче отримати доступ до Вашого поточного екрану, який переглядається спільно, щоб допомогти Вам. Ви дозволяєте?",confirmFullDeviceTitle:"Запит на спільний перегляд екрану",confirmFullDeviceContent:"Чи Ви хочете поділитись з агентом своїм екраном повністю? Агент не зможе нічого на ньому контролювати.",allowText:"Дозволити",denyText:"Відмовити"},eW={confirmSessionTitle:"Kahilingan sa Screen Share na Sesyon",confirmSessionContent:"Gusto mo bang ibahagi ang iyong kasalukuyang screen sa agent?",endSessionText:"Tapusin ang Screen Share na Sesyon",confirmRemoteControlTitle:"Kahilingan sa Remote Access",confirmRemoteControlContent:"Gusto ng agent na magkaroon ng access sa iyong nakabahaging screen sa kasalukuyan upang mas matulungan ka. Gusto mo bang payagan ito?",confirmFullDeviceTitle:"Kahilingan sa Pagbahagi ng Screen",confirmFullDeviceContent:"Gusto mo bang ibahagi ang buong screen sa agent? Hindi makokontrol ng agent ang kahit ano sa screen.",allowText:"Payagan",denyText:"Tanggihan"},ad={en:P6,es:I6,"es-MX":{confirmSessionTitle:"Solicitud de Sesión de Co-navegación",confirmSessionContent:"¿Quiere compartir su pantalla actual con el agente?",endSessionText:"Fin de la sesión de co-navegación",confirmRemoteControlContent:"El agente desea tener acceso a su pantalla actualmente compartida para poder ayudarlo. ¿Quiere permitirlo?",confirmFullDeviceTitle:"Petición de pantalla compartida",confirmFullDeviceContent:"¿Quiere compartir su pantalla completa con el agente? El agente no podrá controlar nada en la pantalla."},fr:A6,"fr-CA":{confirmSessionTitle:"Demande de session co-navigation",confirmSessionContent:"Voulez-vous partager votre écran actuel avec l'agent?",endSessionText:"Fin de la session de co-navigation",confirmRemoteControlContent:"L'agent souhaiterait avoir accès à votre écran actuellement partagé pour mieux vous aider. Voulez-vous l'autoriser?",confirmFullDeviceContent:"Voulez-vous partager votre écran complet avec l'agent? L'agent ne sera pas en mesure de contrôler quoi que ce soit sur l'écran."},de:O6,ja:$6,ko:x6,it:M6,zh:D6,"zh-Hant":{confirmSessionTitle:"共同瀏覽工作階段要求",confirmSessionContent:"要與專員分享您目前的畫面嗎?",endSessionText:"結束共同瀏覽工作階段",confirmRemoteControlTitle:"遠端存取要求",confirmRemoteControlContent:"專員想要存取您目前分享的螢幕畫面以進一步協助您。要允許嗎?",confirmFullDeviceTitle:"螢幕畫面分享要求",confirmFullDeviceContent:"要與專員分享全螢幕嗎?專員將無法控制畫面上的任何項目。",allowText:"允許",denyText:"拒絕"},sv:N6,pt:L6,"pt-BR":{confirmSessionContent:"Você deseja compartilhar sua tela atual com o agente?",endSessionText:"Encerrar Sessão de Co-navegação",confirmRemoteControlContent:"O agente gostaria de acessar sua tela atualmente compartilhada para melhor ajudá-lo. Você deseja permitir isso?",confirmFullDeviceTitle:"Solicitação de Compartilhamento de Tela",confirmFullDeviceContent:"Você deseja compartilhar sua tela inteira com o agente? O agente não poderá controlar nada na tela."},fi:U6,nb:F6,da:j6,nl:B6,tr:q6,vi:W6,th:V6,ar:H6,cs:G6,pl:z6,hu:K6,ru:J6,hi:Y6,ro:X6,hr:Q6,uk:Z6,tl:eW};function tW(r){const e=r.split("-")[0];return ad[r]?r===e?ad[r]:{...ad[e],...ad[r]}:ad[e]}async function rW(r,e,t,n){const i=new FormData;Object.keys(t).forEach(c=>{i.append(c,t[c])}),e instanceof File?i.append("file",e,e.name):e.fileBits&&i.append("file",new File(e.fileBits,e.name,e.options),e.name);const s=await fetch(r,{method:"POST",body:i,signal:n});if(!s.ok)throw new Error(`upload failed: HTTP ${s.status}`);const a=await s.text();return nW(a)}function nW(r){var n,i;const t=(i=(n=new window.DOMParser().parseFromString(r,"text/xml").getElementsByTagName("Key")[0])==null?void 0:n.childNodes[0])==null?void 0:i.nodeValue;if(!t)throw new Error("upload response missing <Key> element");return t}const Rh=new an("chat-originals"),iW="web-4258-local-original-cache",sW=1e3,aW=4,qE=1e4,oW=100;function WE(r){return typeof r=="number"&&Number.isSafeInteger(r)&&r>0}class uW{constructor(){be(this,"byClientMessageId",new Map);be(this,"byRedactionRef",new Map);be(this,"inFlight",new Map);be(this,"queue",[]);be(this,"active",0);be(this,"generation",0)}get currentGeneration(){return this.generation}remember(e,t){!e||!t||Sy(this.byClientMessageId,e,t)}lookup(e){if(typeof e=="string")return this.byClientMessageId.get(e)}forget(e){this.byClientMessageId.delete(e)}lookupFetched(e){return this.byRedactionRef.get(e)}fetch(e,t){const n=this.byRedactionRef.get(e);if(n!==void 0)return Promise.resolve(n);const i=this.inFlight.get(e);if(i)return i;const s=this.generation,a=this.runInSlot(s,()=>{const c=this.call(t,e);return{result:this.withTimeout(c).then(l=>this.settle(s,e,l),l=>(s===this.generation&&(l==null?void 0:l.status)===404?Sy(this.byRedactionRef,e,null):Rh.info("original lookup failed",{redactionRef:e,status:l==null?void 0:l.status}),null)),transport:c}}).finally(()=>{this.inFlight.get(e)===a&&this.inFlight.delete(e)});return this.inFlight.set(e,a),a}invalidate(){this.generation+=1,this.byClientMessageId.clear(),this.byRedactionRef.clear(),this.inFlight.clear();const e=this.queue;this.queue=[],e.forEach(t=>t.cancel())}settle(e,t,n){return e!==this.generation?null:(n==null?void 0:n.redaction_ref)!==t||typeof n.content!="string"?(Rh.warn("original lookup returned an unusable payload",{redactionRef:t}),null):(Sy(this.byRedactionRef,t,n.content),n.content)}call(e,t){try{return Promise.resolve(e(t))}catch(n){return Promise.reject(n)}}runInSlot(e,t){const n=()=>{if(e!==this.generation)return Promise.resolve(null);this.active+=1;const{result:i,transport:s}=t();return s.catch(()=>{}).finally(()=>this.releaseSlot()),i};return this.active<aW?n():this.queue.length>=oW?(Rh.info("original lookup queue full, skipping"),Promise.resolve(null)):new Promise(i=>{const s={start:()=>{clearTimeout(a),i(n())},cancel:()=>{clearTimeout(a),i(null)}},a=setTimeout(()=>{this.queue=this.queue.filter(c=>c!==s),Rh.info("original lookup gave up waiting for a slot"),i(null)},qE);this.queue.push(s)})}releaseSlot(){this.active-=1;const e=this.queue.shift();e&&e.start()}withTimeout(e){return new Promise((t,n)=>{const i=setTimeout(()=>{n(Object.assign(new Error("original lookup timed out"),{code:"TIMEOUT"}))},qE);e.then(s=>{clearTimeout(i),t(s)},s=>{clearTimeout(i),n(s)})})}}function Sy(r,e,t){r.delete(e),r.set(e,t),r.size>sW&&r.delete(r.keys().next().value)}const fO=["assigned","va_assigned"],hO=["dismissed","va_dismissed"],cW=["va_assigned","va_dismissed"],lW=["queued","check_in_timeout",...fO,...hO],dW=["timeout","canceled","failed","finished"],ja=new an("Chat"),fW=Symbol("owner-conflict"),wy=1e3;function hW(r){return typeof WeakRef=="function"?new WeakRef(r):{deref:()=>r}}const pW="web-4206-media-pairing-guard";class vW{constructor(e,t,n={},i){be(this,"provider");be(this,"store");be(this,"globalEvents");be(this,"state");be(this,"connected",!1);be(this,"allowSkipVirtualAgent",!1);be(this,"inEscalation",!1);be(this,"events");be(this,"cachedFiles");be(this,"hooks");be(this,"originals",new uW);be(this,"cacheOwner",null);be(this,"restoredMessages",new Map);be(this,"nextTrackedSweepAt",wy);be(this,"destroying",!1);be(this,"leaveSent",!1);be(this,"beaconAttempted",!1);this.state=e,this.store=new cO,this.cachedFiles={},this.events=new zv,this.hooks=n;const s=g6(this.state.provider_type);this.provider=new s(this.events,e,t,i)}_setGlobalEvents(e,t){this.globalEvents=e,this.on("message",n=>{if(!this.destroying)if(n.content=$b(n.content),this.syncCacheOwner(),n.type===ln.SERVER_MESSAGE){const i=n.server_message_id??n.message_id;t(this.id,i).then(s=>{this.destroying||(n=C6(n,s),e.triggerEvent("chat.message",n))})}else if(n.type==="photo"||n.type==="video"||n.type==="document")setTimeout(()=>{if(this.destroying)return;const i=n.$index.toString();n.file=this.cachedFiles[i],e.triggerEvent("chat.message",n)},100);else{const i=this.restoreOwnOriginal(n);e.triggerEvent("chat.message",n),this.registerMessageEvents(n),i&&this.lookupOwnOriginal(n)}}),this.on("memberJoined",n=>{e.triggerEvent("chat.memberJoined",n)}),this.on("memberLeft",n=>{e.triggerEvent("chat.memberLeft",n)}),this.on("typingStarted",n=>{e.triggerEvent("chat.typingStarted",n)}),this.on("typingEnded",n=>{e.triggerEvent("chat.typingEnded",n)}),this.on("checkInRequired",()=>{e.triggerEvent("chat.checkInRequested")}),this.on("checkInTimedOut",()=>{e.triggerEvent("chat.checkInTimedOut")}),this.on("error",n=>{ja.warn("Chat connection ended",{error:n}),this.handleConnectionEnded()})}handleConnectionEnded(){this.connected&&(this.connected=!1,this.triggerEvent("connectionEnded",this),this.triggerEvent("disconnected",this),this.provider&&this.provider.destroy().catch(e=>ja.warn("provider destroy failed",{error:e})))}get id(){var e;return((e=this.state)==null?void 0:e.id)||-1}get menuId(){return this.state?this.state.menus[this.state.menus.length-1].id:-1}get channelId(){var e;return((e=this.state)==null?void 0:e.provider_channel_id)||""}get lang(){var e;return((e=this.state)==null?void 0:e.lang)||""}get virtual(){return cW.indexOf(this.status)!==-1}get muted(){var e;return((e=this.provider)==null?void 0:e.muted)||!1}set muted(e){this.provider&&(this.provider.muted=e)}get agent(){return this.state?this.virtual?this.state.external_agent||this.state.virtual_agent:this.state.agent||this.state.virtual_agent:null}get allAgents(){var e,t;return{virtual:((e=this.state)==null?void 0:e.all_virtual_agents)||[],human:((t=this.state)==null?void 0:t.all_agents)||[]}}get userIdentity(){var e;return((e=this.provider)==null?void 0:e.identity)||""}get ownUserId(){return this.ownerConflict?null:this.payloadOwnerId??this.providerOwnerId}get ownerConflict(){const e=this.payloadOwnerId,t=this.providerOwnerId;return e!=null&&t!=null&&e!==t}get payloadOwnerId(){var t,n;const e=(n=(t=this.state)==null?void 0:t.end_user)==null?void 0:n.id;return typeof e=="number"&&Number.isFinite(e)?e:null}get providerOwnerId(){const[e,t]=this.userIdentity.split("-"),n=parseInt(t,10);return e===_i.END_USER&&Number.isFinite(n)?n:null}get status(){var e;return((e=this.state)==null?void 0:e.status)||""}get postSessionStatus(){var e;return((e=this.state)==null?void 0:e.post_session_transfer_status)||""}get statusText(){var e;return((e=this.state)==null?void 0:e.status_text)||""}get cobrowsable(){return this.state?this.state.features.indexOf("cobrowse")!==-1:!1}get ongoing(){return lW.indexOf(this.status)!=-1}get assigned(){return fO.indexOf(this.status)!=-1}get dismissed(){return hO.indexOf(this.status)!=-1}get ended(){return dW.indexOf(this.status)!=-1}get transcriptCount(){var e;return((e=this.state)==null?void 0:e.transcript_requested_count)||0}get createdAt(){var e;return((e=this.state)==null?void 0:e.created_at)||""}get inTask(){var e;return((e=this.provider)==null?void 0:e.inTask)||!1}get feedbackType(){var e;return this.state?this.state.survey_enabled?"survey":(e=this.state.csat_settings)!=null&&e.enabled?"rate":"none":"none"}get optInRequired(){var e;return((e=this.state)==null?void 0:e.post_session_opt_in_required)||!1}get postSessionRequired(){var e;return((e=this.state)==null?void 0:e.post_session_required)||!1}get postSessionInProgress(){return this.state?this.state.post_session_transfer_status===ul.IN_PROGRESS:!1}get checkInStatus(){var e;return((e=this.state)==null?void 0:e.check_in_status)??null}set checkInStatus(e){this.state&&(this.state.check_in_status=e)}update(e){if(!this.state||this.state.id!==e.id)return;const t=e.menus[e.menus.length-1].id,n=this.state.menus[this.state.menus.length-1].id;this.state=e,this.syncCacheOwner(),t!==n&&this.triggerEvent("_menuChanged",this),e.status==="canceled"?this.triggerEvent("ended",this):this.triggerEvent("updated",this)}on(e,t){this.events.addEventListener(e,t)}off(e,t){this.events.removeEventListener(e,t)}async connect(){if(!this.provider)return ja.info("connecting interrupted"),!1;try{await ME(()=>this.provider.create(),3),await ME(()=>this.provider.join(this.state.provider_channel_id),3),this.syncCacheOwner(),this.connected=!0;const e=await this.fetchMessages();if(this.destroying)return ja.info("connect abandoned: chat destroyed while loading history"),!1;const t={chat:this,messages:e};return this.triggerEvent("connectedMessages",t),this.triggerEvent("connected",this),this.registerProviderEvents(),ja.info("connected with provider",this.state.provider_type),!0}catch(e){return ja.error("Failed to connect with provider",e),!1}}async disconnect(){this.connected=!1,this.triggerEvent("disconnected",this),await this.sendLeave(),this.events.destroy(),this.provider&&(await this.provider.destroy(),ja.info("disconnect with provider",this.state.provider_type))}async sendLeave(){var e;if(!this.leaveSent&&((e=this.state)==null?void 0:e.provider_type)===Wu.UJET&&this.hooks.leaveChat)try{await this.hooks.leaveChat(),this.leaveSent=!0}catch(t){ja.warn("leaveChat failed",{error:t})}}leaveBeacon(){var e;this.leaveSent||this.beaconAttempted||((e=this.state)==null?void 0:e.provider_type)===Wu.UJET&&this.hooks.leaveChatBeacon&&(this.beaconAttempted=!0,this.hooks.leaveChatBeacon())}resetBeaconState(){this.beaconAttempted=!1}async sendMessage(e,t){var s,a;if(this.ended)throw new av(this.status);const n=await this.provider.sendMessage(e),i=((a=(s=this.hooks).isRiskFlagEnabled)==null?void 0:a.call(s,pW))??!0;return t&&(!i||n!=null&&n!=="")&&this.saveMedia(n,t),typeof n=="number"?n:-1}preview(e){if(!this.inTask)return this.provider.preview(e)}async fetchMessages(){if(this.connected){const e=await this.store.getAllFiles(),t=await this.provider.fetchMessages(e);return this.destroying||!this.state||!this.provider?[]:(this.syncCacheOwner(),t.filter(i=>this.restoreOwnOriginal(i)).forEach(i=>this.lookupOwnOriginal(i)),t)}else throw new Error("Please fetchMessages after chat connected.")}rememberOwnOriginal(e,t){this.destroying||!this.localOriginalCacheEnabled()||(this.syncCacheOwner(),this.originals.remember(e,t))}syncCacheOwner(){if(this.ownerConflict)return this.rebindCacheOwner(fW),null;const e=this.ownUserId;return e==null?typeof this.cacheOwner=="number"?this.cacheOwner:null:(this.rebindCacheOwner(e),e)}rebindCacheOwner(e){e!==this.cacheOwner&&(this.cacheOwner=e,this.revokeOriginals())}revokeOriginals(){this.originals.invalidate();const e=Array.from(this.restoredMessages.values());this.restoredMessages.clear(),this.nextTrackedSweepAt=wy,e.forEach(t=>{const n=t.deref();!n||n.unredacted===void 0||(delete n.unredacted,this.triggerEvent("messageUpdated",n))})}trackRestored(e){const t=hW(e);this.restoredMessages.set(e.$sid||t,t),this.restoredMessages.size>this.nextTrackedSweepAt&&(this.restoredMessages.forEach((n,i)=>{n.deref()===void 0&&this.restoredMessages.delete(i)}),this.nextTrackedSweepAt=Math.max(wy,this.restoredMessages.size*2))}forgetOwnOriginal(e){this.originals.forget(e)}localOriginalCacheEnabled(){var e,t;return((t=(e=this.hooks).isRiskFlagEnabled)==null?void 0:t.call(e,iW))??!0}restoreOwnOriginal(e){if(this.destroying||e.$userType!==_i.END_USER)return!1;const t=this.syncCacheOwner();if(t==null)return this.ownerConflict?(delete e.unredacted,!1):(this.applyOriginal(e,e.unredacted),!1);if(e.$userId!==t)return delete e.unredacted,!1;if(this.localOriginalCacheEnabled()&&this.applyOriginal(e,this.originals.lookup(e.client_message_id))||this.applyOriginal(e,e.unredacted))return!1;const n=e.redaction_ref;if(!WE(n)||!this.hooks.fetchMessageOriginal)return!1;const i=this.originals.lookupFetched(n);return i===null?!1:!this.applyOriginal(e,i)}applyOriginal(e,t){if(t===void 0)return!1;const n=typeof t=="string"&&t?$b(t):"";return n?(e.unredacted=n,this.trackRestored(e),!0):(delete e.unredacted,!1)}lookupOwnOriginal(e){const t=e.redaction_ref,n=this.hooks.fetchMessageOriginal;if(this.destroying||!WE(t)||!n)return;const i=this.id,s=this.syncCacheOwner(),a=this.originals.currentGeneration;this.originals.fetch(t,n).then(c=>{if(!c||this.destroying||!this.state||this.id!==i||this.syncCacheOwner()!==s||a!==this.originals.currentGeneration)return;const o=e.unredacted;!this.applyOriginal(e,c)||e.unredacted===o||this.triggerEvent("messageUpdated",e)}).catch(c=>{ja.warn("original lookup failed",{error:c})})}startTyping(){return this.provider.startTyping()}stopTyping(){return this.provider.stopTyping()}saveMedia(e,t){this.cachedFiles[e.toString()]=t,this.store.save(e,t)}async destroy(){this.destroying=!0,this.originals.invalidate(),this.restoredMessages.clear(),await this.clearMediaStore(),this.connected&&await this.disconnect(),this.provider&&(this.triggerEvent("destroyed"),this.provider=null),this.events.destroy(),this.state=null,this.originals.invalidate(),this.restoredMessages.clear()}async clearMediaStore(){await this.store.clear()}_handleChatEndedEvent(e){this.state&&(this.disconnect(),e.timeout?(this.state.status="timeout",this.triggerEvent("timeout",this)):(this.state.status="finished",this.triggerEvent("ended",this)))}triggerEvent(e,t){this.events.triggerEvent(e,t),this.globalEvents&&this.globalEvents.triggerEvent("chat."+e,t)}registerProviderEvents(){this.provider&&this.provider.registerConversationEvents()}registerMessageEvents(e){switch(e.event){case Gn.COBROWSE_REQUESTED_FROM_AGENT:this.events.triggerEvent("_requestCobrowse","agent");break;case Gn.COBROWSE_REQUESTED_FROM_END_USER:this.events.triggerEvent("_requestCobrowse","end_user");break;case Gn.CHAT_DISMISSED:this.state&&(this.state.status="dismissed",this.triggerEvent("dismissed",this));break;case Gn.CHAT_ENDED:this.events.triggerEvent("_chatEnded",e);break;case Gn.ESCALATION_STARTED:this.inEscalation=!0;break;case Gn.ESCALATION_FAILED:case Gn.ESCALATION_ACCEPTED:this.inEscalation=!1;break;case Gn.CHECK_IN_REQUIRED:this.events.triggerEvent("checkInRequired");break;case Gn.CHECK_IN_TIMED_OUT:this.events.triggerEvent("checkInTimedOut");break}}}const gW=()=>typeof navigator<"u"&&/Android/.test(navigator.userAgent),mW=()=>typeof navigator<"u"&&/Chrome/.test(navigator.userAgent),pO=()=>typeof navigator>"u"?!1:/Android|iPhone|iPad|iPod/.test(navigator.userAgent)?!0:navigator.platform==="MacIntel"&&(navigator.maxTouchPoints??0)>1,Ty=()=>mW()&&!gW();function VE(r){return r.chats=r.chats.map(e=>{const t=e.entries.map((n,i)=>yW(n,`${e.comm_id}-${i}`));return e.entries=E6(t),e}),r}function yW(r,e){var t;return{$index:r.timestamp,$sid:e,$timestamp:new Date(r.timestamp),$userType:r.role,$userId:((t=r.user_data)==null?void 0:t.id)||0,user:r.user_data,type:r.type,...r.body}}const _W={en:"English (US)","en-CA":"English (Canada)","en-GB":"English (UK)",es:"Español (España)","es-MX":"Español (México)",fr:"Français (France)","fr-CA":"Français (Canada)",de:"Deutsch",ja:"日本語",ko:"한국어",it:"Italiano",zh:"中文 (简体)","zh-Hant":"中文 (繁體)",sv:"Svenska",pt:"Português (Portugal)","pt-BR":"Português (Brasil)",fi:"Suomi",nb:"Norsk",da:"Dansk",nl:"Nederlands",tr:"Türk",vi:"Tiếng Việt",th:"คนไทย",ar:"اَلْعَرَبِيَّةُ",cs:"Czech",pl:"Polish",hu:"Hungarian"};function bW(r){var t,n;return{languages:r.languages.filter(i=>i.enabled).map(i=>({lang:i.lang,name:i.name,localeName:_W[i.lang]})),name:r.display_name,subdomain:r.subdomain,support_email:r.support_email,action_tracking:r.action_tracking_enabled,email_transcripts:r.chat_settings.email_transcripts,message_preview:r.chat_settings.message_preview,email_enhancement:r.email_enhancement_enabled,display_history:((t=r.chat_settings.display_history)==null?void 0:t.enabled)&&((n=r.chat_settings.display_history)==null?void 0:n.to_end_user),use_recording:r.use_recording,use_web:r.use_web,cobrowse_domain:r.cobrowse_domain}}function vO(r){return r.map(SW).filter(e=>e.enabled)}function SW(r){const e={id:r.id,enabled:!0,channels:[],hidden:!!r.hidden};if(!r.name||!r.name.trim())return e.enabled=!1,e;e.name=r.name.trim();const t=wW(r);if(t&&(e.redirection=r.redirection),r.children&&r.children.length){const n=vO(r.children);return e.enabled=n.length>0||t,e.children=n,e}if(!r.channels)e.enabled=t;else{const{channels:n,deflection:i}=TW(r.channels);e.deflection=i,t||(e.channels=n),e.enabled=n.length>0||t}return e}function wW(r){let e=!1;const t=r.redirection;return t&&(t.option==="message"||t.option==="url")&&(e=!!t.data),e}function TW(r){let e=null;const t=[],n=r.chat,i=s=>{!s.deflection_type&&s.deflected_reason&&(s.deflection_type=s.deflected_reason),s.deflected===void 0&&s.deflection_type&&(s.deflected=!0),t.push(s)};return n&&n.deflected&&(e={enabled:!0,type:n.deflected_reason}),n&&(n.enabled||n.virtual_agent_available)&&i({...r.chat,type:"chat"}),r.voice_call&&r.voice_call.instant_enabled&&i({...r.voice_call,type:"instant_call"}),r.voice_call&&r.voice_call.schedule_enabled&&i({...r.voice_call,type:"scheduled_call",deflection_type:r.voice_call.schedule_deflection_type}),r.voice_call&&r.voice_call.inbound_enabled&&i({...r.voice_call,type:iv.INBOUND_CALL}),r.voice_call&&r.voice_call.deflected&&r.voice_call.voicemail_reason&&i({...r.voice_call,type:iv.VOICEMAIL,deflection_type:r.voice_call.deflected_reason??r.voice_call.voicemail_reason}),r.email&&r.email.enabled&&i({...r.email,type:"email"}),n&&n.deflected&&n.deflected_reason==="over_capacity"&&n.keep_waiting&&i({...n,enabled:!0,type:"keep_waiting",deflection_type:n.deflected_reason}),r.external_deflection_link&&r.external_deflection_link.enabled&&r.external_deflection_link.links.forEach(a=>{a.enabled&&i({...a,type:"external_link"})}),{channels:t,deflection:e}}const CW="ujet_voice_call",gO="twilio_voice",Kn={STATUS_CHANGED:"voice.statusChanged",RECONNECTING:"voice.reconnecting",RECONNECTED:"voice.reconnected",ERROR:"voice.error",SMART_ACTION_REQUESTED:"voice.smartActionRequested",SMART_ACTION_RESOLVED:"voice.smartActionResolved",COBROWSE_REQUESTED:"voice.cobrowseRequested",COBROWSE_RESOLVED:"voice.cobrowseResolved",RECORDING_PERMISSION_REQUIRED:"voice.recordingPermissionRequired",MIC_PERMISSION_REQUIRED:"voice.micPermissionRequired",CONNECTION_QUALITY:"voice.connectionQuality"},Aw=r=>{var e;if(r&&typeof r=="object"){const t=r;if(typeof((e=t.data)==null?void 0:e.message)=="string")return t.data.message;if(typeof t.message=="string")return t.message}return typeof r=="string"?r:String(r)},EW=(r,e)=>!!r&&typeof r=="object"&&"code"in r&&r.code===e,mO=r=>{if(r&&typeof r=="object"&&"status"in r){const e=r.status;if(typeof e=="number")return e}};class ws extends Error{constructor(t,n,i){super(t,i!==void 0?{cause:i}:void 0);be(this,"code");this.name="VoiceCallError",this.code=n,i!==void 0&&(this.cause=i)}}const Nv=class Nv extends ws{constructor(e="End user has a call in progress"){super(e,Nv.CODE),this.name="CallInProgressError"}};be(Nv,"CODE","CALL_IN_PROGRESS");let Vu=Nv;const Lv=class Lv extends ws{constructor(e="Inbound voice is disabled for this menu"){super(e,Lv.CODE),this.name="InboundDisabledError"}};be(Lv,"CODE","INBOUND_DISABLED");let cl=Lv;const Uv=class Uv extends ws{constructor(e="Outside operation hours"){super(e,Uv.CODE),this.name="OperationHoursError"}};be(Uv,"CODE","OPERATION_HOURS");let Hu=Uv;const Fv=class Fv extends ws{constructor(e="Inbound voice feature is not enabled for this tenant"){super(e,Fv.CODE),this.name="FeatureNotEnabledError"}};be(Fv,"CODE","FEATURE_NOT_ENABLED");let ll=Fv;const jv=class jv extends ws{constructor(e="Microphone permission denied",t){super(e,jv.CODE,t),this.name="MicPermissionDeniedError"}};be(jv,"CODE","MIC_PERMISSION_DENIED");let dl=jv;const Bv=class Bv extends ws{constructor(e="No active voice call"){super(e,Bv.CODE),this.name="NoActiveVoiceCallError"}};be(Bv,"CODE","NO_ACTIVE_VOICE_CALL");let Uo=Bv;const qv=class qv extends ws{constructor(e="A voice call is active in another tab"){super(e,qv.CODE),this.name="AnotherTabVoiceCallError"}};be(qv,"CODE","ANOTHER_TAB_VOICE_CALL");let fl=qv;const Wv=class Wv extends ws{constructor(e,t){super(e,Wv.CODE,t),this.name="ProviderError"}};be(Wv,"CODE","PROVIDER_ERROR");let la=Wv;const Yc=class Yc extends ws{constructor(e,t){super(e,Yc.CODE,t),this.name="SmartActionError"}get isAlreadyEnded(){return this.message===Yc.ENDED_MESSAGE}};be(Yc,"CODE","SMART_ACTION_ERROR"),be(Yc,"ENDED_MESSAGE","smart action is already ended");let ni=Yc;const Vv=class Vv extends ws{constructor(e,t){super(`Unrecognized voice error: ${e}`,Vv.CODE,t),this.name="UnknownVoiceError"}};be(Vv,"CODE","UNKNOWN_VOICE_ERROR");let uv=Vv;const kW=r=>r instanceof Hu||r instanceof cl||r instanceof ll||r instanceof Vu,Ba=new an("BackgroundKeepAlive");class RW{constructor(e={}){be(this,"active",!1);be(this,"currentAgentName",null);be(this,"wakeLock",null);be(this,"audioCtx",null);be(this,"silentSource",null);be(this,"visibilityListener",null);be(this,"pagehideListener",null);be(this,"pageshowListener",null);be(this,"resumeListener",null);be(this,"cleanupInvoked",!1);this.deps=e}async start(e={}){this.active||(this.active=!0,this.currentAgentName=e.agentName??null,this.attachLifecycleListeners(),await this.acquireWakeLock(),this.active&&(this.applyMediaMetadata(),this.startSilentAudioLoop()))}updateAgentName(e){this.active&&this.currentAgentName!==e&&(this.currentAgentName=e,this.applyMediaMetadata())}async stop(){this.active&&(this.active=!1,this.detachLifecycleListeners(),await this.releaseWakeLock(),this.clearMediaSession(),this.stopSilentAudioLoop())}attachLifecycleListeners(){typeof document<"u"&&(this.visibilityListener=()=>{document.visibilityState==="visible"&&this.handleVisible()},document.addEventListener("visibilitychange",this.visibilityListener)),!(typeof window>"u")&&(this.pagehideListener=e=>{e!=null&&e.persisted||this.runCleanupOnce()},window.addEventListener("pagehide",this.pagehideListener),this.pageshowListener=e=>{e!=null&&e.persisted&&this.handleVisible()},window.addEventListener("pageshow",this.pageshowListener),this.resumeListener=()=>this.handleVisible(),window.addEventListener("resume",this.resumeListener))}detachLifecycleListeners(){typeof document<"u"&&this.visibilityListener&&document.removeEventListener("visibilitychange",this.visibilityListener),this.visibilityListener=null,typeof window<"u"&&(this.pagehideListener&&window.removeEventListener("pagehide",this.pagehideListener),this.pageshowListener&&window.removeEventListener("pageshow",this.pageshowListener),this.resumeListener&&window.removeEventListener("resume",this.resumeListener)),this.pagehideListener=null,this.pageshowListener=null,this.resumeListener=null}runCleanupOnce(){var e,t;if(!this.cleanupInvoked){this.cleanupInvoked=!0;try{(t=(e=this.deps).onCleanup)==null||t.call(e)}catch(n){Ba.debug("onCleanup threw during unload",n)}this.stop().catch(n=>Ba.debug("stop() during cleanup failed",n))}}handleVisible(){var e,t;(t=(e=this.audioCtx)==null?void 0:e.resume)==null||t.call(e).catch(n=>Ba.debug("audioCtx.resume failed",n)),this.acquireWakeLock(),this.applyMediaMetadata()}async acquireWakeLock(){if(typeof navigator>"u")return;const e=navigator.wakeLock;if(e!=null&&e.request&&!this.wakeLock)try{this.wakeLock=await e.request("screen")}catch(t){Ba.debug("wakeLock.request failed",t)}}async releaseWakeLock(){if(this.wakeLock){try{await this.wakeLock.release()}catch(e){Ba.debug("wakeLock.release failed",e)}this.wakeLock=null}}applyMediaMetadata(){if(typeof navigator>"u")return;const e=navigator.mediaSession;if(!e)return;const t=globalThis.MediaMetadata;if(typeof t=="function")try{e.metadata=new t({title:this.currentAgentName?`Call with ${this.currentAgentName}`:"Voice call"})}catch(n){Ba.debug("mediaSession.metadata set failed",n)}}clearMediaSession(){if(typeof navigator>"u")return;const e=navigator.mediaSession;if(e)try{e.metadata=null}catch(t){Ba.debug("mediaSession.metadata clear failed",t)}}startSilentAudioLoop(){if(typeof window>"u")return;const e=window.AudioContext||window.webkitAudioContext;if(typeof e=="function")try{this.audioCtx=new e;const t=this.audioCtx.createBuffer(1,1,22050),n=this.audioCtx.createBufferSource();n.buffer=t,n.loop=!0,n.connect(this.audioCtx.destination),n.start(),this.silentSource=n}catch(t){Ba.debug("silent audio loop start failed",t),this.audioCtx=null,this.silentSource=null}}stopSilentAudioLoop(){var e,t,n,i;try{(e=this.silentSource)==null||e.stop()}catch{}try{(t=this.silentSource)==null||t.disconnect()}catch{}this.silentSource=null,(i=(n=this.audioCtx)==null?void 0:n.close)==null||i.call(n).catch(s=>Ba.debug("audioCtx.close failed",s)),this.audioCtx=null}}const ps={CONNECTED:"voice:internal:connected",DISCONNECTED:"voice:internal:disconnected",ERROR:"voice:internal:error"},yO="_provider.messageReceived",Oo={SMART_ACTION_REQUESTED:"smart_action_requested",SMART_ACTION_RESOLVED:"smart_action_resolved",RECORDING_PERMISSION_REQUIRED:"recording_permission_required",STATUS_CHANGED:"status_changed",SMART_ACTION_NOTIFIED:"smart_action_notified",SMART_ACTION_RESPONSE:"smart_action_response",RECORDING_PERMISSION:"recording_permission"},qc=new Set(["finished","failed","canceled","timeout","recovered","voicemail"]),Cy=r=>{switch(r){case"queued":case"assigned":return"queued";case"connecting":case"va_assigned":case"switching":return"connecting";case"connected":case"va_connected":return"connected";case"reconnecting":return"interrupted";case"finished":case"recovered":case"voicemail":case"canceled":case"timeout":return"ended";case"failed":return"error";case"scheduled":return"idle";default:return"error"}};class PW{constructor(e){be(this,"_status");this._status=e}get status(){return this._status}get isTerminal(){return qc.has(this._status)}transitionTo(e){if(this.isTerminal)return null;const t=this._status;return this._status=e,t}}const Ey="ujet:",_r={set(r,e){try{localStorage.setItem(Ey+r,e)}catch{}},get(r){try{return localStorage.getItem(Ey+r)}catch{return null}},del(r){try{localStorage.removeItem(Ey+r)}catch{}}},cv="voice",IW=r=>{_r.set(cv,String(r))},HE=()=>{const r=_r.get(cv);if(!r)return null;const e=Number(r);return Number.isFinite(e)&&e>0?e:(_r.del(cv),null)},Wc=()=>{_r.del(cv)},AW=new Set(["connected","va_connected"]),ky=r=>AW.has(r),OW=new Set(["finished","canceled","expired"]),$W=[Kn.RECONNECTING,Kn.RECONNECTED,Kn.CONNECTION_QUALITY];class xW{constructor(e,t,n,i,s){be(this,"_state");be(this,"_publicState",null);be(this,"events");be(this,"provider");be(this,"methods");be(this,"globalEvents");be(this,"logger");be(this,"destroyed",!1);be(this,"isProviderConnected",!1);be(this,"isUnloading",!1);be(this,"startedAt",null);be(this,"fetchEpoch",0);be(this,"keepAlive",null);be(this,"stateMachine");be(this,"handledSmartActionIds",new Set);be(this,"smartActionQueue",[]);be(this,"currentCobrowseSmartActionId",null);be(this,"recordingPermissionAsked",!1);be(this,"speakerOn",!1);be(this,"cobrowseStarter");this._state=e,this.methods=t,this.events=new zv,this.logger=new an(`VoiceCall:${e.id}`),this.provider=new n(this.events,e,t.issueToken),this.globalEvents=i,this.cobrowseStarter=s,this.stateMachine=new PW(e.status),ky(e.status)&&(this.startedAt=this.resolveStartedAtFromState()),this.registerProviderEvents()}setInternalState(e){this._state=e,this._publicState=null}get state(){if(!this._publicState){const{status:e,...t}=this._state;this._publicState=t}return this._publicState}serverStatus(){return this._state.status}get currentSmartActionId(){return this.smartActionQueue[0]??null}resolveStartedAtFromState(){const t=(this.state.participants??[]).find(n=>(n.type==="agent"||n.type==="virtual_agent")&&n.connected_at);if(t!=null&&t.connected_at){const n=new Date(t.connected_at).getTime();if(!Number.isNaN(n))return n}return Date.now()}setStatus(e,t){if(this.isUnloading)return!1;const n=this.stateMachine.transitionTo(e);if(n===null)return!1;if(this.setInternalState({...this._state,status:e}),this.stateMachine.isTerminal&&Wc(),(t==null?void 0:t.emit)!==!1){const i=(t==null?void 0:t.serverPrev)??n;this.globalEvents.triggerEvent(Kn.STATUS_CHANGED,{id:this.id,status:Cy(e),prevStatus:Cy(i)})}return!0}teardownActiveResources(){this.keepAlive&&(this.keepAlive.stop().catch(e=>this.logger.debug("keepAlive.stop failed",e)),this.keepAlive=null)}get id(){return this.state.id}get status(){return Cy(this._state.status)}get agent(){return this.state.agent??this.state.virtual_agent??null}get duration(){return this.startedAt?Math.floor((Date.now()-this.startedAt)/1e3):0}get feedbackType(){var e;return this.state.survey_enabled?"survey":(e=this.state.csat_settings)!=null&&e.enabled?"rate":"none"}get recordingPermissionRequired(){return this.state.recording_option==="record_ask_user"&&this.state.recording_permission==="recording_permission_not_asked"&&!this.recordingPermissionAsked}async _connect(){var t;if(this.destroyed||this.isProviderConnected)return;if(await this.provider.create(),this.destroyed){await this.provider.destroy().catch(n=>{this.logger.debug("provider.destroy() during _connect race failed",n)});return}this.isProviderConnected=!0,this.recordingPermissionRequired&&this.globalEvents.triggerEvent(Kn.RECORDING_PERMISSION_REQUIRED,{id:this.id});const e=(this.state.smart_actions??[]).filter(n=>!OW.has(n.status));for(const n of e)this.handleSmartActionRequested(n);this.keepAlive=new RW({onCleanup:()=>{this.isUnloading=!0;const n=this._state.status;ky(n)||n==="reconnecting"||Wc();try{this.provider.destroy()}catch{}}}),this.keepAlive.start({agentName:(t=this.agent)==null?void 0:t.name}).catch(n=>{this.logger.warn("background keep-alive start failed",n)})}_markUnloading(){this.isUnloading=!0}async _abandonOrFinish(){if(this.stateMachine.isTerminal)return;this.teardownActiveResources();const e=ky(this._state.status);if(this.isProviderConnected)try{await this.provider.hangup()}catch(t){this.logger.warn("provider hangup failed",t)}try{!e&&this.methods.failCall?await this.methods.failCall(this.id,"abandoned"):this.methods.finishCall&&await this.methods.finishCall(this.id)}catch(t){this.logger.warn("server-side hangup failed",t)}this.setStatus("finished",{emit:!this.isProviderConnected})}async _destroy(){this.destroyed||(this.destroyed=!0,this.teardownActiveResources(),await this._abandonOrFinish().catch(e=>this.logger.warn("hangup during destroy failed",e)),await this.provider.destroy(),this.events.destroy())}mute(e){this.destroyed||this.isMuted()!==e&&this.provider.mute(e)}isMuted(){return this.provider.isMuted()}getRemoteAudioStream(){return this.destroyed?null:this.provider.getRemoteStream()}isSpeakerSupported(){return this.destroyed?!1:this.provider.isOutputSelectionSupported()}isSpeakerOn(){return this.speakerOn}async setSpeakerOn(e){if(!this.destroyed){if(!this.provider.isOutputSelectionSupported()){this.speakerOn=e;return}if(e){const t=this.provider.getAvailableOutputDevices().find(n=>/speaker|loud|external/i.test(n.label));if(!t)throw new la("no loudspeaker output available");await this.provider.setOutputDevice(t.deviceId)}else await this.provider.setOutputDevice("default");this.speakerOn=e}}async _escalate(){this.methods.escalateCall&&await this.methods.escalateCall(this.id)}async grantRecording(){this.recordingPermissionAsked=!0,!this.sendProviderMessage(Oo.RECORDING_PERMISSION,{granted:!0})&&this.methods.updateRecordingPermission&&await this.methods.updateRecordingPermission(this.id,!0)}async denyRecording(){this.recordingPermissionAsked=!0,!this.sendProviderMessage(Oo.RECORDING_PERMISSION,{granted:!1})&&this.methods.updateRecordingPermission&&await this.methods.updateRecordingPermission(this.id,!1)}async startCobrowse(e,t="end_user"){return this.cobrowseStarter(e??this.state.lang,t)}async submitTextSmartAction(e,t){await this.resolveSmartAction(e,{status:"finished",data:{text:t}})}async confirmVerificationSmartAction(e){await this.resolveSmartAction(e,{status:"finished"})}async cancelSmartAction(e){await this.resolveSmartAction(e,{status:"canceled"})}async uploadMediaForSmartAction(e,t,n){if(n==="video"){if(!this.methods.uploadVideos)throw new ni("uploadVideos not configured");await this.methods.uploadVideos(this.id,t,e)}else{if(!this.methods.uploadPhotos)throw new ni("uploadPhotos not configured");await this.methods.uploadPhotos(this.id,t,n,e)}this.markSmartActionHandled(e)}async prepareMediaUpload(e,t,n){if(this.destroyed)throw new ni("call destroyed");if(t==="video"){if(!this.methods.uploadOneVideo)throw new ni("uploadOneVideo not configured");return{ref:await this.methods.uploadOneVideo(this.id,e,n),kind:t}}if(!this.methods.uploadOnePhoto)throw new ni("uploadOnePhoto not configured");return{ref:await this.methods.uploadOnePhoto(this.id,e,n),kind:t}}async submitMediaRefsForSmartAction(e,t,n){if(this.destroyed)throw new ni("call destroyed");if(n.length===0)throw new ni("submitMediaRefsForSmartAction called with empty refs");const i=n.find(a=>a.kind!==t);if(i)throw new ni(`media ref kind '${i.kind}' does not match SmartAction type '${t}'`);const s=n.map(a=>a.ref);if(t==="video"){if(!this.methods.registerVideos)throw new ni("registerVideos not configured");await this.methods.registerVideos(this.id,s,e)}else{if(!this.methods.registerPhotos)throw new ni("registerPhotos not configured");await this.methods.registerPhotos(this.id,t,s,e)}this.markSmartActionHandled(e)}registerProviderEvents(){this.events.addEventListener(ps.CONNECTED,async()=>{this.destroyed||(await this.fetchAndUpdateState(),!(this.destroyed||this._state.status==="finished")&&(this.startedAt=this.resolveStartedAtFromState()))}),this.events.addEventListener(ps.DISCONNECTED,()=>{this.destroyed||this.stateMachine.isTerminal||(this.isProviderConnected=!1,this.setStatus("finished"),this.fetchAndUpdateState())}),this.events.addEventListener(ps.ERROR,e=>{this.destroyed||this.stateMachine.isTerminal||(this.logger.warn("provider reported a fatal error",e),this.isProviderConnected=!1,this.teardownActiveResources(),this.globalEvents.triggerEvent(Kn.ERROR,{id:this.id,error:e==null?void 0:e.error}),this.setStatus("failed"))});for(const e of $W)this.events.addEventListener(e,t=>{this.globalEvents.triggerEvent(e,t)});this.events.addEventListener(yO,e=>{this.handleProviderMessage(e)})}async fetchAndUpdateState(){const e=++this.fetchEpoch;try{const t=await this.methods.fetchCall(this.id);if(e!==this.fetchEpoch||this.destroyed)return;this.setInternalState({...this._state,...t,status:this._state.status})}catch(t){this.logger.warn("on-demand fetchCall failed",t)}}handleProviderMessage(e){if(this.destroyed||this.isUnloading)return;const{type:t,data:n={}}=e;switch(t){case Oo.SMART_ACTION_REQUESTED:this.handleSmartActionRequested(n.smart_action);break;case Oo.SMART_ACTION_RESOLVED:this.handleSmartActionResolved(n);break;case Oo.RECORDING_PERMISSION_REQUIRED:if(this.recordingPermissionAsked)break;this.globalEvents.triggerEvent(Kn.RECORDING_PERMISSION_REQUIRED,{id:this.id});break;case Oo.STATUS_CHANGED:this.handleStatusChanged(n);break;default:this.logger.debug("unhandled provider message type",t)}}handleSmartActionRequested(e){if(!e||this.handledSmartActionIds.has(e.id))return;if(e.type==="cobrowse"){if(this.currentCobrowseSmartActionId===e.id)return;this.currentCobrowseSmartActionId=e.id,this.globalEvents.triggerEvent(Kn.COBROWSE_REQUESTED,{smartAction:e})}else{if(this.smartActionQueue.includes(e.id))return;this.smartActionQueue.push(e.id),this.globalEvents.triggerEvent(Kn.SMART_ACTION_REQUESTED,{smartAction:e})}this.sendProviderMessage(Oo.SMART_ACTION_NOTIFIED,{smart_action_id:e.id})}handleSmartActionResolved(e){const t=e.smart_action_id;t&&(this.smartActionQueue.includes(t)&&this.globalEvents.triggerEvent(Kn.SMART_ACTION_RESOLVED,{smartActionId:t}),this.currentCobrowseSmartActionId===t&&(this.currentCobrowseSmartActionId=null,this.globalEvents.triggerEvent(Kn.COBROWSE_RESOLVED,{smartActionId:t})),this.markSmartActionHandled(t))}handleStatusChanged(e){var n,i,s;if(!e.status||this.stateMachine.isTerminal)return;if(this.fetchEpoch++,(e.agent||e.virtual_agent)&&this.setInternalState({...this._state,...e.agent&&{agent:e.agent},...e.virtual_agent&&{virtual_agent:e.virtual_agent}}),!qc.has(e.status)){const a=((n=this._state.agent)==null?void 0:n.name)??((i=this._state.virtual_agent)==null?void 0:i.name)??null;(s=this.keepAlive)==null||s.updateAgentName(a),e.status==="connected"&&this.fetchAndUpdateState().then(()=>{this.destroyed||this._state.status!=="connected"||(this.startedAt=this.resolveStartedAtFromState())})}this.setStatus(e.status,{serverPrev:e.prev_status})}sendProviderMessage(e,t){return this.provider.sendMessage({type:e,data:t})!==null}markSmartActionHandled(e){this.handledSmartActionIds.add(e);const t=this.smartActionQueue.indexOf(e);t>=0&&this.smartActionQueue.splice(t,1)}async resolveSmartAction(e,t){if(this.sendProviderMessage(Oo.SMART_ACTION_RESPONSE,{smart_action_id:e,status:t.status,data:t.data,fail_reason:t.fail_reason})){this.markSmartActionHandled(e);return}if(!this.methods.updateSmartAction)throw new ni("updateSmartAction not configured");try{await this.methods.updateSmartAction(this.id,e,t),this.markSmartActionHandled(e)}catch(n){const i=Aw(n);if(i===ni.ENDED_MESSAGE){this.markSmartActionHandled(e);return}throw new ni(i,n)}}}class Ow{constructor(e,t,n){be(this,"events");be(this,"state");be(this,"issueVoiceToken");this.events=e,this.state=t,this.issueVoiceToken=n}getRemoteStream(){return null}sendMessage(e){return null}}be(Ow,"type","base");const _O={},bO=r=>{_O[r.type]=r},SO=r=>_O[r],Ph=new an("methods"),GE=!0,MW="web-4191-refresh-unknown-chat-agent";class DW{constructor(e,t,n,i){be(this,"request");be(this,"lastDapRequestId",null);be(this,"lastDirectAccessKeyId",null);be(this,"dapPollGeneration",0);be(this,"beaconLeaveChat");be(this,"authContext");be(this,"isRiskFlagEnabled");be(this,"getCustomFormData",async e=>{const t=`forms/${e}/details`;try{return await this.get(t)}catch(n){Ph.error(`Error fetching form data:, ${n}`)}});this.request=e,this.beaconLeaveChat=t,this.authContext=n,this.isRiskFlagEnabled=i}get(e,t){if(t){const n=[];Object.keys(t).forEach(i=>{const s=t[i];s!==void 0&&n.push(`${encodeURIComponent(i)}=${encodeURIComponent(s)}`)}),e+="?"+n.join("&")}return this.request(e,{method:"GET"})}post(e,t){const n={method:"POST"};return n.body=JSON.stringify(t),this.request(e,n)}patch(e,t){const n={method:"PATCH"};return n.body=JSON.stringify(t),this.request(e,n)}put(e,t){const n={method:"PUT"};return n.body=JSON.stringify(t),this.request(e,n)}async getTriggers(e){const t={"UJET-Company-Id":e};return(await this.request("proactive_chat_triggers",{method:"GET",headers:t})).data}submitCustomForm(e){return this.post("forms/submit",e)}async trackClientEvents(e){return await this.post("/client_events",{events:e})}async getCompany(){const e=await this.get("company");return bW(e.data)}async getFeatureFlags(){return(await this.get("feature_flags")).data}async getMenus(e,t,n){const i=this.dapPollGeneration,s={type:"web_menu",lang:e,direct_access_key:t};n!=null&&n.initialMessage&&(s.initial_message=n.initialMessage),n!=null&&n.signedCustomData&&(s.custom_data_signed=n.signedCustomData),n!=null&&n.customData&&(s.custom_data_unsigned=n.customData);let a=await this.post("menus",s);this.stashDapRequestId(a),this.isChatDapPending(a.data)&&(a=await this.pollChatDap(e,Number(a.data.max_timeout)||0,i));const c=a.headers["ujet-direct-access"],l={key:!!t,user:!!c&&c!=="false",key_id:null},d=a.headers["ujet-direct-access-key-id"];if(d){const y=Number(d);Number.isFinite(y)&&(l.key_id=y)}this.lastDirectAccessKeyId=l.key_id;let h=[];return Array.isArray(a.data)?h=a.data:Ph.warn("unexpected /menus response shape; rendering an empty menu list"),{menus:vO(h),direct:l}}stashDapRequestId(e){const t=e.headers["ujet-dap-request-id"];this.lastDapRequestId=typeof t=="string"&&t?t:null}isChatDapPending(e){return e&&!Array.isArray(e)&&e.status==="PENDING"}cancelDapPolling(){this.dapPollGeneration++}fetchRootMenus(e){return this.get("menus",{type:"web_menu",lang:e})}async pollChatDap(e,t,n){const i=this.lastDapRequestId;if(!i)return Ph.warn("chat DAP pending response missing dap_request_id; falling back to root menus"),await this.fetchRootMenus(e);const s=2e3,a=Math.max(t,0)*1e3;let c=0;for(;c<a;){if(await sv(s),c+=s,this.dapPollGeneration!==n)return{headers:{},data:[]};const o=await this.get("menus",{type:"web_menu",lang:e,dap_request_id:i});if(!this.isChatDapPending(o.data))return o}return await this.fetchRootMenus(e)}async getAfterHourMessage(e){return(await this.get(`audible_messages/${e}`)).data["after_hours.message"].text}async getTimeSlots(e,t={}){const n=t.lang||"en",i=t.rescheduleCallId;return(await this.get(`menus/${e}/time_slots`,{type:"web_menu",lang:n,reschedule_call_id:i,use_advanced_call_scheduling:GE})).data}async fetchTimeSlotAvailability(e,t="en"){return(await this.get(`menus/${e}/time_slots_available`,{type:"web_menu",lang:t})).data.slots_available}async getWaitTimes(e,t="en"){return(await this.get(`menus/${e}/wait_times`,{type:"web_menu",lang:t})).data}async verifyForm(e){try{return await this.post("forms/verify",e),!0}catch{return!1}}async finishChat(e){return(await this.patch(`chats/${e}`,{status:"finished"})).data}async fetchUjetConversationMessages(e,t={}){return(await this.get(`chats/${e}/ujet_conversation/messages`,{limit:t.limit,before:t.before})).data}async leaveChat(e){await this.post(`chats/${e}/leave`,{})}leaveChatBeacon(e){var t;(t=this.beaconLeaveChat)==null||t.call(this,e)}async updatePostSession(e,t,n){const i={post_session_transfer_status:t};n!==void 0&&(i.post_session_opt_in_selection=n);try{return(await this.patch(`chats/${e}`,i)).data}catch(s){if(t===ul.IN_PROGRESS&&s.status===400)return(await this.patch(`chats/${e}`,i)).data;throw s}}async getChatDeflection(e){const{data:t}=await this.get(`chats/${e}/deflections`);return t&&t.enabled?t:null}sendChatCustomData(e,t){let n;return typeof t=="string"?n={signed:!0,signed_data:t}:n={signed:!1,data:t},this.post(`chats/${e}/custom_data`,n)}async downloadChatTranscript(e){return(await this.post(`chats/${e}/generate_transcript_pdf`,{})).data}async getPdfStatus(e){return await this.get(`chat_transcript_pdfs/${e}/download_transcript`)}async sendChatTranscripts(e,t){return await this.post(`chats/${e}/transcripts`,{emails:t.join(",")})}async listChatTaskMessages(e){return(await this.get(`chats/${e}/task_va_messages`)).data}async getChatTaskMessage(e,t){return(await this.get(`chats/${e}/task_va_messages/${t}`)).data}async sendChatTaskMessage(e,t){const n={content:{content:t,type:"text"}};return(await this.post(`chats/${e}/task_va_messages`,n)).data}async sendChatTextMessage(e,t,n){const i={message:{content:t,timestamp:new Date().toISOString()}};n&&(i.message.client_message_id=n),await this.post(`chats/${e}/messages`,i)}async getChatMessageOriginal(e,t){return(await this.get(`chats/${e}/messages/${t}/original`)).data}async sendPreviewMessage(e,t,n){const i={message:{content:t,timestamp:n}},{data:s}=await this.post(`chats/${e}/redact_messages`,i);return s}escalateChat(e,t){return this.post(`chats/${e}/escalations`,t)}trackEscalation(e,t,n){return this.put(`chats/${e}/escalations/${t}`,{escalation_id:t,deflection_channel:n})}requestChatCobrowse(e,t){return this.post(`chats/${e}/cobrowse`,t)}requestVoiceCallCobrowse(e,t){return this.post(`calls/${e}/cobrowse`,t)}rateChat(e,t){return this.patch(`chats/${e}/rating`,t)}async getChatSurvey(e){return(await this.get(`chats/${e}/survey`)).data}sendChatSurvey(e,t){const n={chat_id:e,answers:t};return this.put(`chats/${e}/survey`,n)}trackChatEndUserEvent(e,t){return this.post(`chats/${e}/end_user_event`,t)}async createChat(e,t,n,i){const s={menu_id:e,lang:t,email:n.email,greeting:n.greeting,trigger_id:n.trigger_id,ticket_id:n.ticket_id,custom_data:n.custom_data};this.lastDirectAccessKeyId!==null&&(s.direct_access_key_id=this.lastDirectAccessKeyId),this.lastDapRequestId&&(s.dap_request_id=this.lastDapRequestId);const a={chat:s,cobrowsable:n.cobrowsable},c=await this.post("chats",a);this.lastDapRequestId=null;const o=c.data;return this.wrapChat(o,i)}async loadChat(e,t){const n=await this.getChat(e);return this.wrapChat(n,t)}async resumeChat(e,t){const n=await this.patch(`chats/${e}`,{status:"queued"});return this.wrapChat(n.data,t)}async getChatHistory(e=1){if(e===1){const{data:t}=await this.get("/chats/histories?page=1&per_page=2");return VE(t)}else{const{data:t}=await this.get(`/chats/histories?page=${e}&per_page=1`);return VE(t)}}async uploadChatFile(e,t){let n="file";/^image/.test(t.type)?n="photo":/^video/.test(t.type)?n="video":t.type==="application/pdf"&&(n="document");const i=t.name.replace(/\.[^.]+$/i,""),s=await this.post(`chats/${e}/${n}s/upload`,{filename:i}),a={file:t,fields:s.data.fields};Ty()&&(a.file=await xb(t));const o=(await this.request(s.data.url,a)).data.key,d=(await this.post(`chats/${e}/${n}s`,{chat_id:e,[n]:{s3_path:o,photo_type:n,filename:t.name,content_type:t.type,file_size:t.size}})).data;return d.type=n,d}buildProviderContext(e){if(this.authContext)return{getAuthToken:this.authContext.getAuthToken,wsUrl:this.authContext.wsUrl,fetchHistory:t=>this.fetchUjetConversationMessages(e,t)}}async getChat(e){return(await this.get(`chats/${e}`)).data}async wrapChat(e,t){const n=async()=>(await this.post(`chats/${e.id}/tokens`,{provider_type:e.provider_type,device_id:t})).data,i=()=>this.leaveChat(e.id),s=()=>this.leaveChatBeacon(e.id),a=d=>this.getChatMessageOriginal(e.id,d),c=new vW(e,n,{leaveChat:i,leaveChatBeacon:s,isRiskFlagEnabled:this.isRiskFlagEnabled,fetchMessageOriginal:a},this.buildProviderContext(e.id)),o=async d=>{if(c.status==="va_assigned"){const h=await this.getSkipVirtualAgentSettings(c.menuId,c.lang);c.allowSkipVirtualAgent=h,c.update(d)}};c.on("initialized",async()=>{if(c.status==="queued"){const d=await this.getChat(c.id);c.update(d)}}),c.on("memberJoined",async()=>{const d=await this.getChat(c.id);c.update(d)}),c.on("memberLeft",async()=>{const d=await this.getChat(c.id);c.update(d)});let l=!1;if(c.on("message",d=>{var h;!c.connected||!c.ongoing||l||d.$userType!==_i.USER||!Number.isSafeInteger(d.$userId)||d.$userId<=0||c.allAgents.human.some(v=>v.id===d.$userId)||((h=this.isRiskFlagEnabled)==null?void 0:h.call(this,MW))===!1||(l=!0,this.getChat(c.id).then(v=>{c.connected&&c.ongoing&&c.update(v)}).catch(()=>{Ph.warn("Unable to refresh chat agents after an unknown human message")}).finally(()=>{l=!1}))}),c.on("_chatEnded",async d=>{const h=await this.getChat(c.id);c.update(h),(!c.state||c.ended)&&c._handleChatEndedEvent(d)}),c.on("_menuChanged",async d=>{const h=await this.getChat(d.id);o(h)}),c.on("checkInRequired",async()=>{const d=await this.getChat(c.id);c.update(d)}),c.on("checkInTimedOut",async()=>{const d=await this.getChat(c.id);c.update(d)}),c.channelId)c.connect(),o(e);else{let d;for(;!d;)await this.getChat(c.id).then(h=>{h.provider_channel_id&&c.state?(d=!0,c.update(h),c.connect(),o(h)):(h.status==="canceled"||h.status==="finished")&&(d=!0)}),d||await sv(1500)}return c}async createVoiceCall(e,t,n,i,s,a){const c={call:{type:"web_inbound_call",menu_id:e,lang:t,email:n.email,ticket_id:n.ticket_id,recording_permission:n.recording_permission,custom_data:n.custom_data,voicemail_reason:n.voicemail_reason},cobrowsable:n.cobrowsable??!1},o=await this.post("calls",c);return this.wrapVoiceCall(o.data,i,s,a)}async requestVoiceToken(e,t){return(await this.post(`calls/${e}/tokens`,{device_id:t})).data}async fetchVoiceCall(e){return(await this.get(`calls/${e}`)).data}async hangupVoiceCall(e){await this.patch(`calls/${e}`,{status:"finished"})}async failVoiceCall(e,t="abandoned",n){await this.patch(`calls/${e}`,{status:"failed",fail_reason:t,fail_details:n})}async updateVoiceCallRecordingPermission(e,t){await this.patch(`calls/${e}`,{recording_permission:t?"recording_permission_granted":"recording_permission_denied"})}async escalateVoiceCall(e){await this.post(`calls/${e}/escalate`,{})}rateVoiceCall(e,t){return this.put(`calls/${e}/rating`,t)}async getVoiceCallSurvey(e){return(await this.get(`calls/${e}/survey`)).data}submitVoiceCallSurvey(e,t){const n={call_id:e,answers:t};return this.put(`calls/${e}/survey`,n)}async updateVoiceSmartAction(e,t,n){await this.put(`calls/${e}/smart_actions/${t}`,n)}async uploadVoiceCallPhotoSingle(e,t,n){return await this.uploadFileToExternalStorage(`calls/${e}/photos/upload`,t,n)}async registerVoiceCallPhotos(e,t,n,i){const s=n.map(c=>({s3_path:c,photo_type:t}));return((await this.post(`calls/${e}/photos`,{photo:s,photo_type:t,multiple:!0,smart_action_id:i})).data||[]).map(c=>c.media_id)}async uploadVoiceCallPhotos(e,t,n,i){const s=await Promise.all(t.map(a=>this.uploadVoiceCallPhotoSingle(e,a)));return await this.registerVoiceCallPhotos(e,n,s,i)}async uploadVoiceCallVideoSingle(e,t,n){return await this.uploadFileToExternalStorage(`calls/${e}/videos/upload`,t,n)}async registerVoiceCallVideos(e,t,n){return await Promise.all(t.map(async i=>(await this.post(`calls/${e}/videos`,{video:{s3_path:i},smart_action_id:n})).data.media_id))}async uploadVoiceCallVideos(e,t,n){const i=await Promise.all(t.map(s=>this.uploadVoiceCallVideoSingle(e,s)));return await this.registerVoiceCallVideos(e,i,n)}async uploadFileToExternalStorage(e,t,n){const i=t.name.replace(/\.[^.]+$/i,""),s=await this.post(e,{filename:i});if(pO())return await rW(s.data.url,t,s.data.fields,n);const a={file:t,fields:s.data.fields};return Ty()&&(a.file=await xb(t)),(await this.request(s.data.url,a)).data.key}async _wrapVoiceCallForRestore(e,t,n,i){return this.wrapVoiceCall(e,t,n,i)}async wrapVoiceCall(e,t,n,i){const s=async()=>await this.requestVoiceToken(e.id,t),a=async L=>await this.fetchVoiceCall(L),c=async L=>await this.hangupVoiceCall(L),o=async(L,x,B)=>await this.failVoiceCall(L,x,B),l=async L=>await this.escalateVoiceCall(L),d=async(L,x)=>await this.updateVoiceCallRecordingPermission(L,x),h=async(L,x,B)=>await this.updateVoiceSmartAction(L,x,B),v=async(L,x,B,G)=>{await this.uploadVoiceCallPhotos(L,x,B,G)},y=async(L,x,B)=>{await this.uploadVoiceCallVideos(L,x,B)},w=async(L,x,B)=>await this.uploadVoiceCallPhotoSingle(L,x,B),k=async(L,x,B)=>await this.uploadVoiceCallVideoSingle(L,x,B),I=async(L,x,B,G)=>{await this.registerVoiceCallPhotos(L,x,B,G)},A=async(L,x,B)=>{await this.registerVoiceCallVideos(L,x,B)},j=SO(this.resolveVoiceProviderType(e));if(!j)throw new la(`No voice provider registered for ${e.voip_provider}`);return new xW(e,{issueToken:s,fetchCall:a,finishCall:c,failCall:o,escalateCall:l,updateRecordingPermission:d,updateSmartAction:h,uploadPhotos:v,uploadVideos:y,uploadOnePhoto:w,uploadOneVideo:k,registerPhotos:I,registerVideos:A},j,n,i)}resolveVoiceProviderType(e){return e.voip_provider==="voip_provider_twilio"?gO:e.voip_provider}async createCall(e,t){const n={type:t.scheduled_at?"web_scheduled_call":"web_instant_call",menu_id:e,lang:t.lang,email:t.email,ticket_id:t.ticket_id,recording_permission:t.recording_permission||"recording_permission_not_asked",scheduled_at:t.scheduled_at,custom_data:t.custom_data,end_user:{phone_number:t.phone_number}},s=(await this.post("calls",{call:n,cobrowsable:!1,use_advanced_call_scheduling:GE,reschedule_call_id:t.reschedule_call_id})).data,{selected_menu:a,...c}=s;return{...c,menu_id:a.id}}async fetchCall(e){const n=(await this.get(`calls/${e}`)).data,{selected_menu:i,...s}=n;return{...s,menu_id:i.id}}async cancelCall(e){const n=(await this.patch(`calls/${e}`,{status:"failed",fail_reason:"canceled"})).data,{selected_menu:i,...s}=n;return{...s,menu_id:i.id}}async listFileTypes(){return(await this.get("email_prohibited_file_types")).data}async createEmail(e,t,n){const i={end_user_email:n.email,email_body:n.content,menu_id:e.toString(),lang:t};return n.name&&(i.end_user_name=n.name),n.recaptcha&&(i.recaptcha_response=n.recaptcha),n.files&&Ty()?i["email_attachments[]"]=await NW(n.files):n.files&&(i["email_attachments[]"]=[...n.files]),(await this.request("emails",{form:i})).data}async getMedia(e,t){const n=await this.get(`media/${e}?type=${t}`);if(!n.data)return null;const i=n.headers["x-file-name"];return new File([n.data],i,{type:n.data.type})}async getChatDocuments(e){const t=await this.get(`chats/${e}/documents`);return Array.isArray(t.data)?t.data:[]}async getSkipVirtualAgentSettings(e,t){return(await this.get(`menus/${e}/virtual_agent_settings`,{lang:t})).data.allow_skip_virtual_agent}async confirmCheckIn(e){return(await this.post(`chats/${e}/check_in/confirm`,null)).data}async rejoinQueue(e){return(await this.post(`chats/${e}/check_in/rejoin`,null)).data}async exitCheckIn(e){return(await this.post(`chats/${e}/check_in/exit`,null)).data}async trackCheckIn(e,t){await this.post(`chats/${e}/check_in/modal_shown`,t)}async notifyCheckInState(e,t){await this.post(`chats/${e}/check_in/end_user_status`,t)}}function NW(r){return Promise.all(r.map(xb))}function xb(r){return new Promise((e,t)=>{const n=new FileReader;n.onload=()=>{const i=[n.result],s={type:r.type,lastModified:r.lastModified};e({name:r.name,fileBits:i,options:s})},n.onerror=t,n.readAsArrayBuffer(r)})}const wO=new an("CobrowseService");async function LW(r){return window.CobrowseIO?window.CobrowseIO:await UW(r)}async function UW(r){return new Promise(e=>{const t=document.createElement("script");t.src=r,t.async=!0;const n=document.getElementsByTagName("script")[0];n.parentNode.insertBefore(t,n),t.onload=function(){e(window.CobrowseIO)},t.onerror=function(){wO.error("Failed to load cobrowse script",r),e(null)}})}const zE="https://js.cobrowse.io/CobrowseIO.js";function FW(r){return!r||r.toLowerCase()==="https://cobrowse.io"?zE:r.toLowerCase().startsWith("https://")?`${r}/sdk-js/CobrowseIO.js`:(wO.warn("customCobrowseDomain must use HTTPS; falling back to default",{cobrowseDomain:r}),zE)}async function jW(r,e){let t=r.instance;if(!t){const n=FW(e);t=await LW(n)}return new BW(t,r)}class BW{constructor(e,t){be(this,"_cobrowseIO");if(this._cobrowseIO=e,!e)return;e.license=t.license;const n=t.trustedOrigins||[];n.push(location.origin),e.trustedOrigins=n,["api","capabilities","registration","messages","redactedViews","unredactedViews","confirmSession","confirmRemoteControl","confirmFullDevice","showSessionControls","hideSessionControls"].forEach(s=>{t[s]!==void 0&&(e[s]=t[s])})}get cobrowseIO(){return this._cobrowseIO}async start(){await this._cobrowseIO.client(),await this._cobrowseIO.start()}}const qW=Date.now(),TO={href:window.location.href,interval:24*60*60};function WW(r){if(!Array.isArray(r)||!r.length)return null;const e=KW(),t=e===0,n=e+1;return JW(n),r.filter(s=>{const a=HW(s,TO.href),c=GW(s.visitor_type,t),o=n>=s.page_visit_count,l=!zW(s.id);return a&&c&&o&&l}).sort((s,a)=>s.stay_time-a.stay_time)[0]||null}function VW(r,e){const t=r.stay_time*1e3,n=Math.max(t-(Date.now()-qW),0);setTimeout(()=>{e(r),_r.set(`trigger:${r.id}`,(Date.now()/1e3).toString())},n)}const HW=(r,e)=>{const{keywords_included_or:t=[],keywords_excluded_or:n=[],keywords_included:i=[],keywords_excluded:s=[]}=r;if(o6(t,n,i,s))return!0;if(t.length||n.length){const o=t.some(d=>d.every(h=>e.includes(h))),l=n.length>0&&n.every(d=>d.every(h=>!e.includes(h)));return o||l}const a=i.filter(o=>e.indexOf(o)!==-1).length,c=s.filter(o=>e.indexOf(o)===-1).length;return!!a||!!c};function GW(r,e){return r==="visitor_type_new"?e:r==="visitor_type_returning"?!e:!0}function zW(r){try{const e=parseInt(_r.get(`trigger:${r}`),10);return Date.now()/1e3-e<TO.interval}catch(e){return console.error("Couldn't parse trigger time",e),!1}}function KW(){try{const r=_r.get("visits");return r?parseInt(r,10):0}catch(r){return console.error("Couldn't get visit count",r),0}}function JW(r){try{_r.set("visits",r.toString())}catch(e){console.error(e)}}function YW(r){return r.replace(/\/+$/,"")}const Ry=new an("VoiceMultiTab"),Mb="voice:tab-lock",XW=5e3,QW=2e3,ZW=250,Py=()=>{const r=_r.get(Mb);if(!r)return null;try{return JSON.parse(r)}catch{return null}},Iy=()=>{var i;const r=Py();if(r&&typeof r.ts=="number"&&Date.now()-r.ts<XW)throw new fl;const e=Rw(),t=()=>{_r.set(Mb,JSON.stringify({id:e,ts:Date.now()}))};if(t(),((i=Py())==null?void 0:i.id)!==e)throw new fl;const n=setInterval(t,QW);return{release(){clearInterval(n);const s=Py();(!s||s.id===e)&&_r.del(Mb)}}},KE=async()=>{if(typeof BroadcastChannel>"u")return Iy();let r;try{r=new BroadcastChannel(CW)}catch{return Iy()}const e=Rw();let t=!1;r.onmessage=n=>{const i=n.data;(i.kind==="present"||i.kind==="claim")&&i.id!==e&&(t=!0)};try{r.postMessage({kind:"claim",id:e})}catch(n){Ry.debug("BC postMessage(claim) failed; falling back to localStorage path",n);try{r.close()}catch{}return Iy()}if(await new Promise(n=>setTimeout(n,ZW)),t)throw r.close(),new fl;return r.onmessage=n=>{const i=n.data;if(i.kind==="claim"&&i.id!==e)try{r.postMessage({kind:"present",id:e})}catch(s){Ry.debug("BC postMessage(present) failed",s)}},{release(){try{r.postMessage({kind:"release",id:e})}catch(n){Ry.debug("BC postMessage(release) failed",n)}r.close()}}},eV=["photo","video","audio","document"],qa=new an("client");function tV(r){const e=r==null?void 0:r.status;return typeof e=="number"&&e>=400&&e<500}let rV=class{constructor(e){be(this,"VERSION",Pw);be(this,"options");be(this,"communicator");be(this,"methods");be(this,"events",new zv);be(this,"request");be(this,"chat");be(this,"_cobrowse");be(this,"_voiceCall",null);be(this,"_voiceTabLock",null);be(this,"redactionSendQueue",Promise.resolve());be(this,"fileSendQueue",Promise.resolve());be(this,"_rehydratePromise",null);be(this,"onPageHide");be(this,"onPageShow");this.options=e.host?{...e,host:YW(e.host)}:e,this.communicator=new S6(this.options,this.events);const t=this.communicator.request.bind(this.communicator),n=this.communicator.leaveChatBeacon.bind(this.communicator);this.methods=new DW(t,n,{getAuthToken:this.communicator.getAuthToken.bind(this.communicator),wsUrl:this.communicator.wsUrl},this.communicator.isRiskFlagEnabled.bind(this.communicator)),this.request=t,this.options.host&&rO.setPath(this.options.host),zn.companyId=e.companyId,e.tenant&&(zn.tenant=e.tenant),this.events.addEventListener(Kn.STATUS_CHANGED,i=>{(i==null?void 0:i.status)==="error"&&this.releaseVoiceTabLock()}),this.registerUnloadHandlers()}registerUnloadHandlers(){typeof window>"u"||(this.onPageHide=e=>{var t,n;e.persisted||((t=this.chat)==null||t.leaveBeacon(),(n=this._voiceCall)==null||n._markUnloading(),this.releaseVoiceTabLock())},this.onPageShow=e=>{var t;e.persisted&&((t=this.chat)==null||t.resetBeaconState())},window.addEventListener("pagehide",this.onPageHide),window.addEventListener("pageshow",this.onPageShow))}unregisterUnloadHandlers(){typeof window>"u"||(this.onPageHide&&(window.removeEventListener("pagehide",this.onPageHide),this.onPageHide=void 0),this.onPageShow&&(window.removeEventListener("pageshow",this.onPageShow),this.onPageShow=void 0))}get deviceId(){return zn.deviceId}get user(){return this.communicator.user}get lang(){return this.options.lang?this.options.lang:_r.get("lang")||"en"}set lang(e){this.options.lang||_r.set("lang",e)}get cobrowse(){return this._cobrowse.cobrowseIO}get cobrowseEnabled(){var e;return!!((e=this.options.cobrowse)!=null&&e.enabled)}destroy(){this.destroyVoiceCall().catch(()=>{}),this.unregisterUnloadHandlers(),this.communicator.destroy(),this.events.destroy()}destroyDuplicate(){this.unregisterUnloadHandlers(),this.communicator.destroy(),this.events.destroy()}releaseVoiceTabLock(){var e;(e=this._voiceTabLock)==null||e.release(),this._voiceTabLock=null}on(e,t){this.events.addEventListener(e,t)}off(e,t){this.events.removeEventListener(e,t)}async checkMicPermission(){var e;if(typeof navigator>"u"||!((e=navigator.permissions)!=null&&e.query))return"unknown";try{const n=(await navigator.permissions.query({name:"microphone"})).state;return n==="granted"||n==="denied"||n==="prompt"?n:"unknown"}catch{return"unknown"}}async getCompany(){const e=await this.methods.getCompany();return zn.tenant=e.subdomain,e}async getFeatureFlags(){return await this.methods.getFeatureFlags()}isRiskFlagEnabled(e){return this.communicator.isRiskFlagEnabled(e)}getRiskFlags(){return this.communicator.getRiskFlags()}async runTrigger(e){const t=await this.methods.getTriggers(this.options.companyId),n=WW(t);n&&VW(n,e)}async trackClientEvents(e){await this.methods.trackClientEvents(e)}async getProhibitedFileTypes(){return await this.methods.listFileTypes()}async getMenus(e,t,n){return await this.methods.getMenus(t||this.lang,e,n)}cancelMenuPolling(){this.methods.cancelDapPolling()}getCustomFormData(e){return this.methods.getCustomFormData(e)}submitCustomForm(e){return this.methods.submitCustomForm(e)}async getAfterHourMessage(e){return await this.methods.getAfterHourMessage(e||this.lang)}async getTimeSlots(e,t){return(i=>typeof i=="object"&&i!==null)(t)?await this.methods.getTimeSlots(e,{lang:t.lang||this.lang,rescheduleCallId:t.rescheduleCallId}):await this.methods.getTimeSlots(e,{lang:t||this.lang})}async fetchTimeSlotAvailability(e,t){return await this.methods.fetchTimeSlotAvailability(e,t||this.lang)}async getWaitTimes(e,t){return await this.methods.getWaitTimes(e,t||this.lang)}async verifyForm(e){return await this.methods.verifyForm(e)}async createCall(e,t){var i;!t.email&&((i=this.user)!=null&&i.email)&&(t.email=this.user.email);const n={...t,lang:t.lang||this.lang};return await this.methods.createCall(Number(e),n)}async loadCall(e){return await this.methods.fetchCall(e)}async cancelCall(e){return await this.methods.cancelCall(e)}async createEmail(e,t){return await this.methods.createEmail(e,t.lang||this.lang,t)}async createChat(e,t={}){var i,s;if(!this.chat&&_r.get("chat")&&await this.loadOngoingChat().catch(()=>null),this.chat&&this.chat.ongoing)throw new Error("There is an ongoing chat.");!t.email&&((i=this.user)!=null&&i.email)&&(t.email=this.user.email),t.cobrowsable===void 0&&(t.cobrowsable=!!((s=this.options.cobrowse)!=null&&s.enabled));const n=await this.methods.createChat(Number(e),t.lang||this.lang,t,this.deviceId);return this.registerOngoingChat(n),await n.clearMediaStore(),n}async loadChat(e){try{const t=await this.methods.loadChat(e,this.deviceId);return t.ongoing?this.registerOngoingChat(t):(_r.del("chat"),_r.del("cobrowse")),t}catch(t){throw _r.del("chat"),_r.del("cobrowse"),t}}async resumeChat(e){var n;if(((n=this.chat)==null?void 0:n.id)===Number(e)){const i=await this.methods.patch(`chats/${e}`,{status:"queued"});return this.chat.update(i.data),this.chat}const t=await this.methods.resumeChat(e,this.deviceId);return this.registerOngoingChat(t),t}async loadOngoingChat(){return this._rehydratePromise?this._rehydratePromise:(this._rehydratePromise=this._doLoadOngoingChat().finally(()=>{this._rehydratePromise=null}),this._rehydratePromise)}async _doLoadOngoingChat(){const e=_r.get("chat");if(!e)return _r.del("chat"),null;try{const t=await this.loadChat(e);return t&&t.ongoing?t:(_r.del("chat"),null)}catch(t){throw _r.del("chat"),t}}async restoreCobrowseSession(){var t;const e=_r.get("cobrowse");if(!(!e||!((t=this.options.cobrowse)!=null&&t.enabled)))try{await this.initializeCobrowse(this.lang),qa.debug("cobrowse session restored with nonce:",e)}catch(n){qa.error("Failed to restore cobrowse session",n),_r.del("cobrowse")}}async finishChat(){if(!this.chat)return;const e=await this.methods.finishChat(this.chat.id);this.chat.update(e),this.chat.connected&&this.chat.ended&&await this.chat.disconnect()}async updatePostSession(e,t){if(!this.chat||e===ul.FINISHED||e===ul.WAITING)return;const n=await this.methods.updatePostSession(this.chat.id,e,t);this.chat.update(n)}async destroyChat(){if(this.chat){if(this.chat.muted=!0,this.chat.ongoing)try{await this.finishChat()}catch(e){qa.warn("finishChat during destroy failed",{error:e})}await this.chat.destroy(),this.chat=null,zn.trackerId=""}}get voiceCall(){return this._voiceCall}hasStoredVoiceCall(){return HE()!==null}async startVoiceCall(e,t={}){var i;if(this._voiceCall&&!qc.has(this._voiceCall.serverStatus()))throw new Vu("A voice call is already active in this session");!t.email&&((i=this.user)!=null&&i.email)&&(t.email=this.user.email),t.cobrowsable===void 0&&(t.cobrowsable=this.cobrowseEnabled);try{await nV()}catch(s){const a=s instanceof dl?s.cause:void 0,c=a&&typeof a=="object"&&"name"in a?a.name:void 0;if(c==="NotAllowedError"||c==="PermissionDeniedError")try{this.events.triggerEvent(Kn.MIC_PERMISSION_REQUIRED)}catch{}throw s}this.releaseVoiceTabLock(),this._voiceTabLock=await KE();let n;try{n=await this.methods.createVoiceCall(Number(e),t.lang||this.lang,t,this.deviceId,this.events,(s,a)=>this.startVoiceCobrowseInternal(s,a))}catch(s){throw this.releaseVoiceTabLock(),JE(s)}this._voiceCall=n;try{await n._connect()}catch(s){throw await n._destroy().catch(()=>{}),this._voiceCall=null,this.releaseVoiceTabLock(),s}return IW(n.id),n}async loadVoiceCall(e){if(this._voiceCall&&!qc.has(this._voiceCall.serverStatus()))return this._voiceCall;let t=null;if(e!==void 0?t=Number(e):t=HE(),t===null)return null;this.releaseVoiceTabLock(),this._voiceTabLock=await KE();let n;try{n=await this.methods.fetchVoiceCall(t)}catch(s){if(mO(s)===404)return Wc(),this.releaseVoiceTabLock(),null;throw this.releaseVoiceTabLock(),JE(s)}if(qc.has(n.status))return Wc(),this.releaseVoiceTabLock(),null;let i;try{i=await this.methods._wrapVoiceCallForRestore(n,this.deviceId,this.events,(s,a)=>this.startVoiceCobrowseInternal(s,a))}catch(s){throw this.releaseVoiceTabLock(),s}this._voiceCall=i;try{await i._connect()}catch(s){throw await i._destroy().catch(()=>{}),this._voiceCall=null,this.releaseVoiceTabLock(),Wc(),s}return this.restoreCobrowseSession().catch(s=>{qa.warn("cobrowse restore failed during voice restore",s)}),i}async endVoiceCall(){this._voiceCall&&(qc.has(this._voiceCall.serverStatus())||await this._voiceCall._abandonOrFinish())}async escalateVoiceCall(){if(!this._voiceCall)throw new Uo;await this._voiceCall._escalate()}async destroyVoiceCall(){if(!this._voiceCall){this.releaseVoiceTabLock(),Wc();return}try{await this._voiceCall._destroy()}finally{this._voiceCall=null,this.releaseVoiceTabLock()}}async getChatDeflection(){return await this.methods.getChatDeflection(this.chat.id)}async sendChatTranscripts(e){await this.methods.sendChatTranscripts(this.chat.id,e)}async downloadChatTranscript(){return await this.methods.downloadChatTranscript(this.chat.id)}async getPdfStatus(e){return await this.methods.getPdfStatus(e)}async getChatSurvey(){return await this.methods.getChatSurvey(this.chat.id)}async sendChatSurvey(e){if(this.chat.feedbackType!=="survey")throw new Error("Chat feedback type is: "+this.chat.feedbackType);await this.methods.sendChatSurvey(this.chat.id,e)}async sendChatRate(e){if(this.chat.feedbackType!=="rate")throw new Error("Chat feedback type is: "+this.chat.feedbackType);await this.methods.rateChat(this.chat.id,e)}async rateVoiceCall(e){if(!this._voiceCall)throw new Uo;if(this._voiceCall.feedbackType!=="rate")throw new Error("Voice call feedback type is: "+this._voiceCall.feedbackType);await this.methods.rateVoiceCall(this._voiceCall.id,e)}async getVoiceCallSurvey(){if(!this._voiceCall)throw new Uo;return await this.methods.getVoiceCallSurvey(this._voiceCall.id)}async submitVoiceCallSurvey(e){if(!this._voiceCall)throw new Uo;if(this._voiceCall.feedbackType!=="survey")throw new Error("Voice call feedback type is: "+this._voiceCall.feedbackType);await this.methods.submitVoiceCallSurvey(this._voiceCall.id,e)}async escalateChat(e){await this.methods.escalateChat(this.chat.id,e)}async trackChatEscalation(e,t){await this.methods.trackEscalation(this.chat.id,e,t)}async trackChatEndUserEvent(e){var t;!e.end_user_name&&((t=this.user)!=null&&t.name)&&(e.end_user_name=this.user.name),await this.methods.trackChatEndUserEvent(this.chat.id,e)}async getChatHistory(e=1){return await this.methods.getChatHistory(e)}async fetchMessages(){try{const e=await this.chat.fetchMessages();if(e.some(t=>t.type==="document"))try{const t=await this.methods.getChatDocuments(this.chat.id);R6(e,t)}catch(t){qa.warn("[fetchMessages] Failed to fetch chat documents",t)}if(e.filter(t=>t.type===ln.SERVER_MESSAGE).length>0){const t=await this.methods.listChatTaskMessages(this.chat.id);return T6(e,t)}return e}catch{return[]}}async sendFileMessage(e){const t=this.chat.id,n=this.fileSendQueue.then(async()=>{let i;try{i=await this.methods.uploadChatFile(t,e)}catch(s){return qa.warn("[sendFileMessage] upload failed",s),-1}return this.chat.sendMessage(i,e)});return this.fileSendQueue=n.catch(()=>{}),await n}async sendTextMessage(e){const t=$b(e);if(t){if(this.chat.inTask){const n=await this.methods.sendChatTaskMessage(this.chat.id,t);this.chat.sendMessage({type:ln.SERVER_MESSAGE,visibility:"task_virtual_agent",message_id:n.id});return}if(this.chat.state.redaction_enabled){const n=this.chat,i=n.id,s=c6();s&&n.rememberOwnOriginal(s,t);const a=this.redactionSendQueue.then(()=>this.methods.sendChatTextMessage(i,t,s??void 0));this.redactionSendQueue=a.catch(()=>{});try{await a}catch(c){throw s&&tV(c)&&n.forgetOwnOriginal(s),c}return}this.chat.sendMessage({type:ln.TEXT,content:t})}}async sendPreviewMessage(e){if(this.isRedactionAgentEnabled()){const t=new Date().toISOString(),n=await this.methods.sendPreviewMessage(this.chat.id,e,t);this.chat.preview(n==null?void 0:n.content);return}this.chat.preview(e)}isRedactionAgentEnabled(){return this.chat.state.redaction_enabled&&this.chat.state.agent_incoming_ha_enabled}async createCobrowseCode(e,t){var n;try{await this.initializeCobrowse(e||this.lang);let i=_r.get("cobrowse");i||(i=Date.now().toString(),_r.set("cobrowse",i));const s={device_id:this.deviceId,device_name:`${zn.application} / ${zn.version}`,nonce:i,...t};return(n=this.user)!=null&&n.name&&(s.user_name=this.user.name),this.cobrowse.customData=s,await this.cobrowse.createSessionCode()}catch{return""}}async startCobrowse(e="end_user"){if(!this.chat.cobrowsable)throw new Error(`Chat ${this.chat.id} does not support cobrowse.`);const t={chatId:`chat_${this.chat.id}`},n=await this.createCobrowseCode(this.chat.lang,t);if(!n)return;const i=_r.get("cobrowse");await this.methods.requestChatCobrowse(this.chat.id,{code:n,from:e,nonce:i})}async startVoiceCobrowseInternal(e,t){if(!this.cobrowseEnabled)throw new Error("Cobrowse is not enabled.");if(!this._voiceCall)throw new Uo;const n=this._voiceCall.id,i={callId:`call_${n}`},s=await this.createCobrowseCode(e||this.lang,i);if(!s)return"";const a=_r.get("cobrowse")??"";return await this.methods.requestVoiceCallCobrowse(n,{code:s,from:t,nonce:a}),this.events.triggerEvent("cobrowse.request",{from:t}),s}async getMessageAttachment(e){if(e.$userType!==_i.END_USER&&eV.includes(e.type)){const t=await this.methods.getMedia(e.media_id,e.type);return this.chat&&this.chat.saveMedia(e.$index,t),t}return null}async checkIn(){const e=await this.methods.confirmCheckIn(this.chat.id);return this.updateCheckIn(e),e}async exitCheckIn(){const e=await this.methods.exitCheckIn(this.chat.id);return this.updateCheckIn(e),e}async notifyCheckInState(e){await this.methods.notifyCheckInState(this.chat.id,e)}async rejoinChat(){const e=await this.methods.rejoinQueue(this.chat.id);return this.updateCheckIn(e),e}async trackCheckInEvent(){const e={modal_type:"check_in"};await this.methods.trackCheckIn(this.chat.id,e)}async getLogs(){const e=await this.communicator.getBridgeLogHistory(),t=an.logHistory.toArray();return{bridgeLogs:e,rootLogs:t}}async printLogs(){const e=await this.getLogs();console.log("Printing bridge logs:"),e.bridgeLogs.forEach(t=>{an.printLogHistoryData(t)}),console.log("Printing root logs:"),e.rootLogs.forEach(t=>{an.printLogHistoryData(t)})}updateCheckIn(e){const t={...this.chat.state};t.check_in_status=e.check_in_status,this.chat.update(t)}async initializeCobrowse(e){if(!this._cobrowse){const t=await this.getCompany(),n=this.options.cobrowse.messages||tW(e),i={...this.options.cobrowse,messages:n,lang:e};this._cobrowse=await jW(i,t.cobrowse_domain),await this._cobrowse.start(),[["session.loaded",Bp.LOADED],["session.updated",Bp.UPDATED],["session.ended",Bp.ENDED]].forEach(([a,c])=>{this.cobrowse.on(a,o=>{this.events.triggerEvent(c,o)})}),qa.debug("cobrowse has been initialized"),this.events.triggerEvent("cobrowse.initialized",this._cobrowse)}}registerOngoingChat(e){this.events.triggerEvent("chat.ongoing",e),e._setGlobalEvents(this.events,this.methods.getChatTaskMessage.bind(this.methods)),e.on("_requestCobrowse",t=>{t==="agent"?this.startCobrowse(t):this.initializeCobrowse(e.lang).catch(n=>{qa.error("Failed to initialize cobrowse on request",n)}),this.events.triggerEvent("cobrowse.request",{from:t})}),e.on("disconnected",()=>{_r.del("chat"),_r.del("cobrowse")}),this.chat=e,zn.trackerId=`chat_${e.id}`,_r.set("chat",e.id.toString()),e.cobrowsable&&_r.get("cobrowse")&&this.initializeCobrowse(e.lang).catch(t=>{qa.error("Failed to initialize cobrowse for ongoing chat",t)})}_triggerEvent(e,t){this.events.triggerEvent(e,t)}};const nV=async()=>{var r;if(typeof navigator>"u"||!((r=navigator.mediaDevices)!=null&&r.getUserMedia))throw new dl("Browser does not support microphone access");try{(await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(t=>t.stop())}catch(e){throw new dl(Aw(e),e)}},iV=new Map([["call_in_progress",Vu],["inbound_disabled",cl],["outside_operation_hours",Hu],["operation_hours",Hu],["feature_not_enabled",ll],["invalid_call_type",ll]]),sV=new Map([[409,Hu],[403,cl],[400,Vu]]),JE=r=>{var a,c;if(r instanceof ws)return r;const e=r&&typeof r=="object"?r:{},t=(a=e.data)==null?void 0:a.error_code,n=((c=e.data)==null?void 0:c.message)??e.message??"",i=t?iV.get(t):void 0;if(i)return new i(n);const s=e.status!==void 0?sV.get(e.status):void 0;return s?new s(n):new uv(n,r)};var Ye=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Kv(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}function CO(r){if(r.__esModule)return r;var e=r.default;if(typeof e=="function"){var t=function n(){return this instanceof n?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(r).forEach(function(n){var i=Object.getOwnPropertyDescriptor(r,n);Object.defineProperty(t,n,i.get?i:{enumerable:!0,get:function(){return r[n]}})}),t}var Db={exports:{}},Zo=lv;function lv(){}lv.mixin=function(r){var e=r.prototype||r;e.isWildEmitter=!0,e.on=function(t,n,i){this.callbacks=this.callbacks||{};var s=arguments.length===3,a=s?arguments[1]:void 0,c=s?arguments[2]:arguments[1];return c._groupName=a,(this.callbacks[t]=this.callbacks[t]||[]).push(c),this},e.once=function(t,n,i){var s=this,a=arguments.length===3,c=a?arguments[1]:void 0,o=a?arguments[2]:arguments[1];function l(){s.off(t,l),o.apply(this,arguments)}return this.on(t,c,l),this},e.releaseGroup=function(t){this.callbacks=this.callbacks||{};var n,i,s,a;for(n in this.callbacks)for(a=this.callbacks[n],i=0,s=a.length;i<s;i++)a[i]._groupName===t&&(a.splice(i,1),i--,s--);return this},e.off=function(t,n){this.callbacks=this.callbacks||{};var i=this.callbacks[t],s;return i?arguments.length===1?(delete this.callbacks[t],this):(s=i.indexOf(n),s!==-1&&(i.splice(s,1),i.length===0&&delete this.callbacks[t]),this):this},e.emit=function(t){this.callbacks=this.callbacks||{};var n=[].slice.call(arguments,1),i=this.callbacks[t],s=this.getWildcardCallbacks(t),a,c,o;if(i)for(o=i.slice(),a=0,c=o.length;a<c&&o[a];++a)o[a].apply(this,n);if(s)for(c=s.length,o=s.slice(),a=0,c=o.length;a<c&&o[a];++a)o[a].apply(this,[t].concat(n));return this},e.getWildcardCallbacks=function(t){this.callbacks=this.callbacks||{};var n,i,s=[];for(n in this.callbacks)i=n.split("*"),(n==="*"||i.length===2&&t.slice(0,i[0].length)===i[0])&&(s=s.concat(this.callbacks[n]));return s}};lv.mixin(lv);var EO={exports:{}};(function(r){(function(e,t){r.exports?r.exports=t():e.prefix=t(e)})(Ye,function(e){var t=function(d){for(var h=1,v=arguments.length,y;h<v;h++)for(y in arguments[h])Object.prototype.hasOwnProperty.call(arguments[h],y)&&(d[y]=arguments[h][y]);return d},n={template:"[%t] %l:",levelFormatter:function(d){return d.toUpperCase()},nameFormatter:function(d){return d||"root"},timestampFormatter:function(d){return d.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")},format:void 0},i,s={},a=function(d){if(!d||!d.getLogger)throw new TypeError("Argument is not a root logger");i=d},c=function(d,h){if(!d||!d.setLevel)throw new TypeError("Argument is not a logger");var v=d.methodFactory,y=d.name||"",w=s[y]||s[""]||n;function k(I,A,j){var L=v(I,A,j),x=s[j]||s[""],B=x.template.indexOf("%t")!==-1,G=x.template.indexOf("%l")!==-1,K=x.template.indexOf("%n")!==-1;return function(){for(var D="",fe=arguments.length,X=Array(fe),pe=0;pe<fe;pe++)X[pe]=arguments[pe];if(y||!s[j]){var Q=x.timestampFormatter(new Date),Oe=x.levelFormatter(I),Ve=x.nameFormatter(j);x.format?D+=x.format(Oe,Ve,Q):(D+=x.template,B&&(D=D.replace(/%t/,Q)),G&&(D=D.replace(/%l/,Oe)),K&&(D=D.replace(/%n/,Ve))),X.length&&typeof X[0]=="string"?X[0]=D+" "+X[0]:X.unshift(D)}L.apply(void 0,X)}}return s[y]||(d.methodFactory=k),h=h||{},h.template&&(h.format=void 0),s[y]=t({},w,h),d.setLevel(d.getLevel()),i||d.warn("It is necessary to call the function reg() of loglevel-plugin-prefix before calling apply. From the next release, it will throw an error. See more: https://github.com/kutuluk/loglevel-plugin-prefix/blob/master/README.md"),d},o={reg:a,apply:c},l;return e&&(l=e.prefix,o.noConflict=function(){return e.prefix===o&&(e.prefix=l),o}),o})})(EO);var aV=EO.exports,kO={exports:{}};(function(r){(function(e,t){r.exports?r.exports=t():e.log=t()})(Ye,function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"],s={},a=null;function c(k,I){var A=k[I];if(typeof A.bind=="function")return A.bind(k);try{return Function.prototype.bind.call(A,k)}catch{return function(){return Function.prototype.apply.apply(A,[k,arguments])}}}function o(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function l(k){return k==="debug"&&(k="log"),typeof console===t?!1:k==="trace"&&n?o:console[k]!==void 0?c(console,k):console.log!==void 0?c(console,"log"):e}function d(){for(var k=this.getLevel(),I=0;I<i.length;I++){var A=i[I];this[A]=I<k?e:this.methodFactory(A,k,this.name)}if(this.log=this.debug,typeof console===t&&k<this.levels.SILENT)return"No console available for logging"}function h(k){return function(){typeof console!==t&&(d.call(this),this[k].apply(this,arguments))}}function v(k,I,A){return l(k)||h.apply(this,arguments)}function y(k,I){var A=this,j,L,x,B="loglevel";typeof k=="string"?B+=":"+k:typeof k=="symbol"&&(B=void 0);function G(pe){var Q=(i[pe]||"silent").toUpperCase();if(!(typeof window===t||!B)){try{window.localStorage[B]=Q;return}catch{}try{window.document.cookie=encodeURIComponent(B)+"="+Q+";"}catch{}}}function K(){var pe;if(!(typeof window===t||!B)){try{pe=window.localStorage[B]}catch{}if(typeof pe===t)try{var Q=window.document.cookie,Oe=encodeURIComponent(B),Ve=Q.indexOf(Oe+"=");Ve!==-1&&(pe=/^([^;]+)/.exec(Q.slice(Ve+Oe.length+1))[1])}catch{}return A.levels[pe]===void 0&&(pe=void 0),pe}}function D(){if(!(typeof window===t||!B)){try{window.localStorage.removeItem(B)}catch{}try{window.document.cookie=encodeURIComponent(B)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function fe(pe){var Q=pe;if(typeof Q=="string"&&A.levels[Q.toUpperCase()]!==void 0&&(Q=A.levels[Q.toUpperCase()]),typeof Q=="number"&&Q>=0&&Q<=A.levels.SILENT)return Q;throw new TypeError("log.setLevel() called with invalid level: "+pe)}A.name=k,A.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},A.methodFactory=I||v,A.getLevel=function(){return x??L??j},A.setLevel=function(pe,Q){return x=fe(pe),Q!==!1&&G(x),d.call(A)},A.setDefaultLevel=function(pe){L=fe(pe),K()||A.setLevel(pe,!1)},A.resetLevel=function(){x=null,D(),d.call(A)},A.enableAll=function(pe){A.setLevel(A.levels.TRACE,pe)},A.disableAll=function(pe){A.setLevel(A.levels.SILENT,pe)},A.rebuild=function(){if(a!==A&&(j=fe(a.getLevel())),d.call(A),a===A)for(var pe in s)s[pe].rebuild()},j=fe(a?a.getLevel():"WARN");var X=K();X!=null&&(x=fe(X)),d.call(A)}a=new y,a.getLogger=function(I){if(typeof I!="symbol"&&typeof I!="string"||I==="")throw new TypeError("You must supply a name when creating a logger.");var A=s[I];return A||(A=s[I]=new y(I,a.methodFactory)),A};var w=typeof window!==t?window.log:void 0;return a.noConflict=function(){return typeof window!==t&&window.log===a&&(window.log=w),a},a.getLoggers=function(){return s},a.default=a,a})})(kO);var Gr=kO.exports;const oV=Kv(Gr),uV=Aq({__proto__:null,default:oV},[Gr]);var Nb={exports:{}},cV={"error:application:call:params":{type:"error:application:call:params",description:"not a valid String[] of usernames param"},"error:application:callServer:params":{type:"error:application:call:params",description:"not a valid String of phone number"},"error:call:reject":{type:"error:call:reject",description:"failed to reject the call"},"error:getUserMedia:permissions":{type:"error:getUserMedia:permissions",description:"missing getUserMedia permissions"},"error:media:params":{type:"error:media:params",description:"currently supported params media type= {audio:{muted:false, earmuffed:false}}"},"error:media:reenable":{type:"error:media:reenable",description:"missing reconnectRtcId required to reenable media"},"error:self":{type:"error:self",description:"Conversation Object is missing self (me)"},"error:user:relogin":{type:"error:user:relogin",description:"please relogin"},"error:seen:own-message":{type:"error:seen:own-message",description:"attempt to send seen for own message"},"error:already-seen":{type:"error:already-seen",description:"already marked as seen"},"error:delivered:own-message":{type:"error:delivered:own-message",description:"attempt to send delivered for own message"},"error:already-delivered":{type:"error:already-delivered",description:"already marked as delivered"},"error:fetch-image":{type:"error:fetch-image",description:"xhr.status received other than 200"},"error:delete-image":{type:"error:delete-image",description:"xhr.status received other than 204"},"error:missing:params":{type:"error:missing:params",description:"missing parameters"},"error:invite:missing:params":{type:"error:missing:params",description:"This invite cannot be sent to empty username and user_id"},"error:invalid:param:type":{type:"error:invalid:param:type",description:"Invalid Object type, passed in the parameters"},"error:audio:already-connecting":{type:"error:audio:already-connecting",description:"Audio call already in progress"},"error:audio:not-enabled":{type:"error:audio:not-enabled",description:"Audio is not enabled"},"error:media:already-connecting":{type:"error:media:already-connecting",description:"Media is already in progress"},"error:media:unsupported-browser":{type:"error:media:unsupported-browser",description:"This action is not supported on this browser"},"error:media:extension":{type:"error:media:extension",description:"Chrome extension has thrown an error"},"error:media:extension-not-installed":{type:"error:media:extension-not-installed",description:"Chrome extension should be installed"},"error:media:update:streams":{type:"error:media:update:streams",description:"cant update more than one stream"},"error:media:update:invalid":{type:"error:media:update:invalid",description:"state of media is not supported for this update"},"error:media:stream:not-found":{type:"error:media:stream:not-found",description:"A stream with the given index was not found"},"error:audio:dtmf:invalid-digit":{type:"error:audio:dtmf:invalid-digit",description:"not a valid string of dtmf digits (0-9,a-d,A-D,p,P,*,#)"},"error:audio:dtmf:audio-disabled":{type:"error:audio:dtmf:audio-disabled",description:"Audio must be enabled to send DTMF"},"error:invalid-order":{type:"error:invalid-order",description:"params not valid. Order must be asc or desc"},"error:custom-event:invalid":{type:"error:custom-event:invalid",description:"Custom event type not valid"},"error:message-event:invalid":{type:"error:message-event:invalid",description:"message_type is missing or is invalid"},"error:invalid-cursor":{type:"error:invalid-cursor",description:"page does not exist"},"error:client:reconnection_failed":{type:"error:client:reconnection_failed",description:"websocket failed to reconnect"},"error:conversation-service:version":{type:"error:conversation:version",description:'Wrong version of Conversation Service API. It should be one of "v1" or "v3"'},"error:no-media-offer":{type:"error:no-media-offer",description:"Media preload attempt without having an offer available"}};(function(r,e){Object.defineProperty(e,"__esModule",{value:!0}),e.NexmoApiError=e.NexmoClientError=void 0;const t=cV,n=Gr;function i(c,o){o&&o.code&&(o.type=o.code,delete o.code),Object.assign(c,o),c.message="type: "+c.type+", description: "+(c.description?c.description:"")}class s{constructor(o){const l=t[o];l?i(this,l):(this.message=o&&o.message?o.message:o,this.stack=o.stack),this.log=n.getLogger(this.constructor.name),this.log.error(this),this.name="NexmoClientError",typeof Ye.NXMbugsnagClient<"u"&&Ye.NXMbugsnagClient.notify(this,{severity:"info"})}}e.NexmoClientError=s;class a{constructor(o){this.log=n.getLogger(this.constructor.name),o?i(this,o):(this.message=o&&o.message?o.message:o,this.stack=o&&o.stack?o.stack:new Error().stack),this.name="NexmoApiError",this.log=n.getLogger(this.constructor.name),this.log.error(this),typeof Ye.NXMbugsnagClient<"u"&&Ye.NXMbugsnagClient.notify(this,{severity:"info"})}}e.NexmoApiError=a,r.exports={NexmoClientError:s,NexmoApiError:a}})(Nb,Nb.exports);var Ts=Nb.exports,Lb={exports:{}},$w={},Jv={},eo={},nf={},ha={},sf={},ro={},Tl={},af={},pa={};Object.defineProperty(pa,"__esModule",{value:!0});pa.ERROR_PACKET=pa.PACKET_TYPES_REVERSE=pa.PACKET_TYPES=void 0;const ma=Object.create(null);pa.PACKET_TYPES=ma;ma.open="0";ma.close="1";ma.ping="2";ma.pong="3";ma.message="4";ma.upgrade="5";ma.noop="6";const RO=Object.create(null);pa.PACKET_TYPES_REVERSE=RO;Object.keys(ma).forEach(r=>{RO[ma[r]]=r});const lV={type:"error",data:"parser error"};pa.ERROR_PACKET=lV;Object.defineProperty(af,"__esModule",{value:!0});af.encodePacket=void 0;af.encodePacketToBinary=fV;const dV=pa,PO=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",IO=typeof ArrayBuffer=="function",AO=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r&&r.buffer instanceof ArrayBuffer,OO=({type:r,data:e},t,n)=>PO&&e instanceof Blob?t?n(e):YE(e,n):IO&&(e instanceof ArrayBuffer||AO(e))?t?n(e):YE(new Blob([e]),n):n(dV.PACKET_TYPES[r]+(e||""));af.encodePacket=OO;const YE=(r,e)=>{const t=new FileReader;return t.onload=function(){const n=t.result.split(",")[1];e("b"+(n||""))},t.readAsDataURL(r)};function XE(r){return r instanceof Uint8Array?r:r instanceof ArrayBuffer?new Uint8Array(r):new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}let Ay;function fV(r,e){if(PO&&r.data instanceof Blob)return r.data.arrayBuffer().then(XE).then(e);if(IO&&(r.data instanceof ArrayBuffer||AO(r.data)))return e(XE(r.data));OO(r,!1,t=>{Ay||(Ay=new TextEncoder),e(Ay.encode(t))})}var Yv={},hl={};Object.defineProperty(hl,"__esModule",{value:!0});hl.decode=hl.encode=void 0;const Vc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",kd=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let r=0;r<Vc.length;r++)kd[Vc.charCodeAt(r)]=r;const hV=r=>{let e=new Uint8Array(r),t,n=e.length,i="";for(t=0;t<n;t+=3)i+=Vc[e[t]>>2],i+=Vc[(e[t]&3)<<4|e[t+1]>>4],i+=Vc[(e[t+1]&15)<<2|e[t+2]>>6],i+=Vc[e[t+2]&63];return n%3===2?i=i.substring(0,i.length-1)+"=":n%3===1&&(i=i.substring(0,i.length-2)+"=="),i};hl.encode=hV;const pV=r=>{let e=r.length*.75,t=r.length,n,i=0,s,a,c,o;r[r.length-1]==="="&&(e--,r[r.length-2]==="="&&e--);const l=new ArrayBuffer(e),d=new Uint8Array(l);for(n=0;n<t;n+=4)s=kd[r.charCodeAt(n)],a=kd[r.charCodeAt(n+1)],c=kd[r.charCodeAt(n+2)],o=kd[r.charCodeAt(n+3)],d[i++]=s<<2|a>>4,d[i++]=(a&15)<<4|c>>2,d[i++]=(c&3)<<6|o&63;return l};hl.decode=pV;Object.defineProperty(Yv,"__esModule",{value:!0});Yv.decodePacket=void 0;const Ih=pa,vV=hl,gV=typeof ArrayBuffer=="function",mV=(r,e)=>{if(typeof r!="string")return{type:"message",data:$O(r,e)};const t=r.charAt(0);return t==="b"?{type:"message",data:yV(r.substring(1),e)}:Ih.PACKET_TYPES_REVERSE[t]?r.length>1?{type:Ih.PACKET_TYPES_REVERSE[t],data:r.substring(1)}:{type:Ih.PACKET_TYPES_REVERSE[t]}:Ih.ERROR_PACKET};Yv.decodePacket=mV;const yV=(r,e)=>{if(gV){const t=(0,vV.decode)(r);return $O(t,e)}else return{base64:!0,data:r}},$O=(r,e)=>{switch(e){case"blob":return r instanceof Blob?r:new Blob([r]);case"arraybuffer":default:return r instanceof ArrayBuffer?r:r.buffer}};(function(r){Object.defineProperty(r,"__esModule",{value:!0}),r.decodePayload=r.decodePacket=r.encodePayload=r.encodePacket=r.protocol=void 0,r.createPacketEncoderStream=c,r.createPacketDecoderStream=h;const e=af;Object.defineProperty(r,"encodePacket",{enumerable:!0,get:function(){return e.encodePacket}});const t=Yv;Object.defineProperty(r,"decodePacket",{enumerable:!0,get:function(){return t.decodePacket}});const n=pa,i="",s=(v,y)=>{const w=v.length,k=new Array(w);let I=0;v.forEach((A,j)=>{(0,e.encodePacket)(A,!1,L=>{k[j]=L,++I===w&&y(k.join(i))})})};r.encodePayload=s;const a=(v,y)=>{const w=v.split(i),k=[];for(let I=0;I<w.length;I++){const A=(0,t.decodePacket)(w[I],y);if(k.push(A),A.type==="error")break}return k};r.decodePayload=a;function c(){return new TransformStream({transform(v,y){(0,e.encodePacketToBinary)(v,w=>{const k=w.length;let I;if(k<126)I=new Uint8Array(1),new DataView(I.buffer).setUint8(0,k);else if(k<65536){I=new Uint8Array(3);const A=new DataView(I.buffer);A.setUint8(0,126),A.setUint16(1,k)}else{I=new Uint8Array(9);const A=new DataView(I.buffer);A.setUint8(0,127),A.setBigUint64(1,BigInt(k))}v.data&&typeof v.data!="string"&&(I[0]|=128),y.enqueue(I),y.enqueue(w)})}})}let o;function l(v){return v.reduce((y,w)=>y+w.length,0)}function d(v,y){if(v[0].length===y)return v.shift();const w=new Uint8Array(y);let k=0;for(let I=0;I<y;I++)w[I]=v[0][k++],k===v[0].length&&(v.shift(),k=0);return v.length&&k<v[0].length&&(v[0]=v[0].slice(k)),w}function h(v,y){o||(o=new TextDecoder);const w=[];let k=0,I=-1,A=!1;return new TransformStream({transform(j,L){for(w.push(j);;){if(k===0){if(l(w)<1)break;const x=d(w,1);A=(x[0]&128)===128,I=x[0]&127,I<126?k=3:I===126?k=1:k=2}else if(k===1){if(l(w)<2)break;const x=d(w,2);I=new DataView(x.buffer,x.byteOffset,x.length).getUint16(0),k=3}else if(k===2){if(l(w)<8)break;const x=d(w,8),B=new DataView(x.buffer,x.byteOffset,x.length),G=B.getUint32(0);if(G>Math.pow(2,21)-1){L.enqueue(n.ERROR_PACKET);break}I=G*Math.pow(2,32)+B.getUint32(4),k=3}else{if(l(w)<I)break;const x=d(w,I);L.enqueue((0,t.decodePacket)(A?x:o.decode(x),y)),k=0}if(I===0||I>v){L.enqueue(n.ERROR_PACKET);break}}}})}r.protocol=4})(Tl);function bi(r){if(r)return _V(r)}function _V(r){for(var e in bi.prototype)r[e]=bi.prototype[e];return r}bi.prototype.on=bi.prototype.addEventListener=function(r,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+r]=this._callbacks["$"+r]||[]).push(e),this};bi.prototype.once=function(r,e){function t(){this.off(r,t),e.apply(this,arguments)}return t.fn=e,this.on(r,t),this};bi.prototype.off=bi.prototype.removeListener=bi.prototype.removeAllListeners=bi.prototype.removeEventListener=function(r,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var t=this._callbacks["$"+r];if(!t)return this;if(arguments.length==1)return delete this._callbacks["$"+r],this;for(var n,i=0;i<t.length;i++)if(n=t[i],n===e||n.fn===e){t.splice(i,1);break}return t.length===0&&delete this._callbacks["$"+r],this};bi.prototype.emit=function(r){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),t=this._callbacks["$"+r],n=1;n<arguments.length;n++)e[n-1]=arguments[n];if(t){t=t.slice(0);for(var n=0,i=t.length;n<i;++n)t[n].apply(this,e)}return this};bi.prototype.emitReserved=bi.prototype.emit;bi.prototype.listeners=function(r){return this._callbacks=this._callbacks||{},this._callbacks["$"+r]||[]};bi.prototype.hasListeners=function(r){return!!this.listeners(r).length};const bV=Object.freeze(Object.defineProperty({__proto__:null,Emitter:bi},Symbol.toStringTag,{value:"Module"})),Cl=CO(bV);var Js={},Li={};Object.defineProperty(Li,"__esModule",{value:!0});Li.defaultBinaryType=Li.globalThisShim=Li.nextTick=void 0;Li.createCookieJar=SV;Li.nextTick=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,t)=>t(e,0);Li.globalThisShim=typeof self<"u"?self:typeof window<"u"?window:Function("return this")();Li.defaultBinaryType="arraybuffer";function SV(){}Object.defineProperty(Js,"__esModule",{value:!0});Js.pick=wV;Js.installTimerFunctions=EV;Js.byteLength=RV;Js.randomString=IV;const No=Li;function wV(r,...e){return e.reduce((t,n)=>(r.hasOwnProperty(n)&&(t[n]=r[n]),t),{})}const TV=No.globalThisShim.setTimeout,CV=No.globalThisShim.clearTimeout;function EV(r,e){e.useNativeTimers?(r.setTimeoutFn=TV.bind(No.globalThisShim),r.clearTimeoutFn=CV.bind(No.globalThisShim)):(r.setTimeoutFn=No.globalThisShim.setTimeout.bind(No.globalThisShim),r.clearTimeoutFn=No.globalThisShim.clearTimeout.bind(No.globalThisShim))}const kV=1.33;function RV(r){return typeof r=="string"?PV(r):Math.ceil((r.byteLength||r.size)*kV)}function PV(r){let e=0,t=0;for(let n=0,i=r.length;n<i;n++)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:e<55296||e>=57344?t+=3:(n++,t+=4);return t}function IV(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}var of={};Object.defineProperty(of,"__esModule",{value:!0});of.encode=AV;of.decode=OV;function AV(r){let e="";for(let t in r)r.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(r[t]));return e}function OV(r){let e={},t=r.split("&");for(let n=0,i=t.length;n<i;n++){let s=t[n].split("=");e[decodeURIComponent(s[0])]=decodeURIComponent(s[1])}return e}var Ub={exports:{}},Oy,QE;function $V(){if(QE)return Oy;QE=1;var r=1e3,e=r*60,t=e*60,n=t*24,i=n*7,s=n*365.25;Oy=function(d,h){h=h||{};var v=typeof d;if(v==="string"&&d.length>0)return a(d);if(v==="number"&&isFinite(d))return h.long?o(d):c(d);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(d))};function a(d){if(d=String(d),!(d.length>100)){var h=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(d);if(h){var v=parseFloat(h[1]),y=(h[2]||"ms").toLowerCase();switch(y){case"years":case"year":case"yrs":case"yr":case"y":return v*s;case"weeks":case"week":case"w":return v*i;case"days":case"day":case"d":return v*n;case"hours":case"hour":case"hrs":case"hr":case"h":return v*t;case"minutes":case"minute":case"mins":case"min":case"m":return v*e;case"seconds":case"second":case"secs":case"sec":case"s":return v*r;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return v;default:return}}}}function c(d){var h=Math.abs(d);return h>=n?Math.round(d/n)+"d":h>=t?Math.round(d/t)+"h":h>=e?Math.round(d/e)+"m":h>=r?Math.round(d/r)+"s":d+"ms"}function o(d){var h=Math.abs(d);return h>=n?l(d,h,n,"day"):h>=t?l(d,h,t,"hour"):h>=e?l(d,h,e,"minute"):h>=r?l(d,h,r,"second"):d+" ms"}function l(d,h,v,y){var w=h>=v*1.5;return Math.round(d/v)+" "+y+(w?"s":"")}return Oy}function xV(r){t.debug=t,t.default=t,t.coerce=o,t.disable=a,t.enable=i,t.enabled=c,t.humanize=$V(),t.destroy=l,Object.keys(r).forEach(d=>{t[d]=r[d]}),t.names=[],t.skips=[],t.formatters={};function e(d){let h=0;for(let v=0;v<d.length;v++)h=(h<<5)-h+d.charCodeAt(v),h|=0;return t.colors[Math.abs(h)%t.colors.length]}t.selectColor=e;function t(d){let h,v=null,y,w;function k(...I){if(!k.enabled)return;const A=k,j=Number(new Date),L=j-(h||j);A.diff=L,A.prev=h,A.curr=j,h=j,I[0]=t.coerce(I[0]),typeof I[0]!="string"&&I.unshift("%O");let x=0;I[0]=I[0].replace(/%([a-zA-Z%])/g,(G,K)=>{if(G==="%%")return"%";x++;const D=t.formatters[K];if(typeof D=="function"){const fe=I[x];G=D.call(A,fe),I.splice(x,1),x--}return G}),t.formatArgs.call(A,I),(A.log||t.log).apply(A,I)}return k.namespace=d,k.useColors=t.useColors(),k.color=t.selectColor(d),k.extend=n,k.destroy=t.destroy,Object.defineProperty(k,"enabled",{enumerable:!0,configurable:!1,get:()=>v!==null?v:(y!==t.namespaces&&(y=t.namespaces,w=t.enabled(d)),w),set:I=>{v=I}}),typeof t.init=="function"&&t.init(k),k}function n(d,h){const v=t(this.namespace+(typeof h>"u"?":":h)+d);return v.log=this.log,v}function i(d){t.save(d),t.namespaces=d,t.names=[],t.skips=[];const h=(typeof d=="string"?d:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const v of h)v[0]==="-"?t.skips.push(v.slice(1)):t.names.push(v)}function s(d,h){let v=0,y=0,w=-1,k=0;for(;v<d.length;)if(y<h.length&&(h[y]===d[v]||h[y]==="*"))h[y]==="*"?(w=y,k=v,y++):(v++,y++);else if(w!==-1)y=w+1,k++,v=k;else return!1;for(;y<h.length&&h[y]==="*";)y++;return y===h.length}function a(){const d=[...t.names,...t.skips.map(h=>"-"+h)].join(",");return t.enable(""),d}function c(d){for(const h of t.skips)if(s(d,h))return!1;for(const h of t.names)if(s(d,h))return!0;return!1}function o(d){return d instanceof Error?d.stack||d.message:d}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}var MV=xV;(function(r,e){e.formatArgs=n,e.save=i,e.load=s,e.useColors=t,e.storage=a(),e.destroy=(()=>{let o=!1;return()=>{o||(o=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function t(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let o;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(o=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(o[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function n(o){if(o[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+o[0]+(this.useColors?"%c ":" ")+"+"+r.exports.humanize(this.diff),!this.useColors)return;const l="color: "+this.color;o.splice(1,0,l,"color: inherit");let d=0,h=0;o[0].replace(/%[a-zA-Z%]/g,v=>{v!=="%%"&&(d++,v==="%c"&&(h=d))}),o.splice(h,0,l)}e.log=console.debug||console.log||(()=>{});function i(o){try{o?e.storage.setItem("debug",o):e.storage.removeItem("debug")}catch{}}function s(){let o;try{o=e.storage.getItem("debug")||e.storage.getItem("DEBUG")}catch{}return!o&&typeof process<"u"&&"env"in process&&(o=process.env.DEBUG),o}function a(){try{return localStorage}catch{}}r.exports=MV(e);const{formatters:c}=r.exports;c.j=function(o){try{return JSON.stringify(o)}catch(l){return"[UnexpectedJSONParseError]: "+l.message}}})(Ub,Ub.exports);var Ys=Ub.exports,DV=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ro,"__esModule",{value:!0});ro.Transport=ro.TransportError=void 0;const NV=Tl,LV=Cl,UV=Js,FV=of,jV=DV(Ys),BV=(0,jV.default)("engine.io-client:transport");class xO extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}ro.TransportError=xO;class qV extends LV.Emitter{constructor(e){super(),this.writable=!1,(0,UV.installTimerFunctions)(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,n){return super.emitReserved("error",new xO(e,t,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(e){this.readyState==="open"?this.write(e):BV("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=(0,NV.decodePacket)(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return e.indexOf(":")===-1?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(e){const t=(0,FV.encode)(e);return t.length?"?"+t:""}}ro.Transport=qV;var WV=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(sf,"__esModule",{value:!0});sf.Polling=void 0;const VV=ro,HV=Js,ZE=Tl,GV=WV(Ys),Ds=(0,GV.default)("engine.io-client:polling");class zV extends VV.Transport{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";const t=()=>{Ds("paused"),this.readyState="paused",e()};if(this._polling||!this.writable){let n=0;this._polling&&(Ds("we are currently polling - waiting to pause"),n++,this.once("pollComplete",function(){Ds("pre-pause polling complete"),--n||t()})),this.writable||(Ds("we are currently writing - waiting to pause"),n++,this.once("drain",function(){Ds("pre-pause writing complete"),--n||t()}))}else t()}_poll(){Ds("polling"),this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){Ds("polling got data %s",e);const t=n=>{if(this.readyState==="opening"&&n.type==="open"&&this.onOpen(),n.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(n)};(0,ZE.decodePayload)(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"?this._poll():Ds('ignoring poll - transport state "%s"',this.readyState))}doClose(){const e=()=>{Ds("writing close packet"),this.write([{type:"close"}])};this.readyState==="open"?(Ds("transport open - closing"),e()):(Ds("transport not open - deferring close"),this.once("open",e))}write(e){this.writable=!1,(0,ZE.encodePayload)(e,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return this.opts.timestampRequests!==!1&&(t[this.opts.timestampParam]=(0,HV.randomString)()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}}sf.Polling=zV;var Xv={};Object.defineProperty(Xv,"__esModule",{value:!0});Xv.hasCORS=void 0;let MO=!1;try{MO=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}Xv.hasCORS=MO;var KV=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ha,"__esModule",{value:!0});ha.XHR=ha.Request=ha.BaseXHR=void 0;const JV=sf,YV=Cl,ek=Js,DO=Li,XV=Xv,QV=KV(Ys),Fb=(0,QV.default)("engine.io-client:polling");function ZV(){}class NO extends JV.Polling{constructor(e){if(super(e),typeof location<"u"){const t=location.protocol==="https:";let n=location.port;n||(n=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){const n=this.request({method:"POST",data:e});n.on("success",t),n.on("error",(i,s)=>{this.onError("xhr post error",i,s)})}doPoll(){Fb("xhr poll");const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,n)=>{this.onError("xhr poll error",t,n)}),this.pollXhr=e}}ha.BaseXHR=NO;let Uu=class qp extends YV.Emitter{constructor(e,t,n){super(),this.createRequest=e,(0,ek.installTimerFunctions)(this,n),this._opts=n,this._method=n.method||"GET",this._uri=t,this._data=n.data!==void 0?n.data:null,this._create()}_create(){var e;const t=(0,ek.pick)(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(t);try{Fb("xhr open %s: %s",this._method,this._uri),n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let i in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(i)&&n.setRequestHeader(i,this._opts.extraHeaders[i])}}catch{}if(this._method==="POST")try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{n.setRequestHeader("Accept","*/*")}catch{}(e=this._opts.cookieJar)===null||e===void 0||e.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var i;n.readyState===3&&((i=this._opts.cookieJar)===null||i===void 0||i.parseCookies(n.getResponseHeader("set-cookie"))),n.readyState===4&&(n.status===200||n.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof n.status=="number"?n.status:0)},0))},Fb("xhr data %s",this._data),n.send(this._data)}catch(i){this.setTimeoutFn(()=>{this._onError(i)},0);return}typeof document<"u"&&(this._index=qp.requestsCount++,qp.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=ZV,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete qp.requests[this._index],this._xhr=null}}_onLoad(){const e=this._xhr.responseText;e!==null&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}};ha.Request=Uu;Uu.requestsCount=0;Uu.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",tk);else if(typeof addEventListener=="function"){const r="onpagehide"in DO.globalThisShim?"pagehide":"unload";addEventListener(r,tk,!1)}}function tk(){for(let r in Uu.requests)Uu.requests.hasOwnProperty(r)&&Uu.requests[r].abort()}const e5=function(){const r=LO({xdomain:!1});return r&&r.responseType!==null}();class t5 extends NO{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=e5&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new Uu(LO,this.uri(),e)}}ha.XHR=t5;function LO(r){const e=r.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||XV.hasCORS))return new XMLHttpRequest}catch{}if(!e)try{return new DO.globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}var Jo={},r5=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Jo,"__esModule",{value:!0});Jo.WS=Jo.BaseWS=void 0;const n5=ro,rk=Js,i5=Tl,jb=Li,s5=r5(Ys),a5=(0,s5.default)("engine.io-client:websocket"),UO=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class FO extends n5.Transport{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,n=UO?{}:(0,rk.pick)(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,n)}catch(i){return this.emitReserved("error",i)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],i=t===e.length-1;(0,i5.encodePacket)(n,this.supportsBinary,s=>{try{this.doWrite(n,s)}catch{a5("websocket closed before onclose event")}i&&(0,jb.nextTick)(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=(0,rk.randomString)()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}Jo.BaseWS=FO;const $y=jb.globalThisShim.WebSocket||jb.globalThisShim.MozWebSocket;class o5 extends FO{createSocket(e,t,n){return UO?new $y(e,t,n):t?new $y(e,t):new $y(e)}doWrite(e,t){this.ws.send(t)}}Jo.WS=o5;var uf={},u5=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(uf,"__esModule",{value:!0});uf.WT=void 0;const c5=ro,l5=Li,nk=Tl,d5=u5(Ys),od=(0,d5.default)("engine.io-client:webtransport");class f5 extends c5.Transport{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{od("transport closed gracefully"),this.onClose()}).catch(e=>{od("transport closed due to %s",e),this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{const t=(0,nk.createPacketDecoderStream)(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),i=(0,nk.createPacketEncoderStream)();i.readable.pipeTo(e.writable),this._writer=i.writable.getWriter();const s=()=>{n.read().then(({done:c,value:o})=>{if(c){od("session is closed");return}od("received chunk: %o",o),this.onPacket(o),s()}).catch(c=>{od("an error occurred while reading: %s",c)})};s();const a={type:"open"};this.query.sid&&(a.data=`{"sid":"${this.query.sid}"}`),this._writer.write(a).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],i=t===e.length-1;this._writer.write(n).then(()=>{i&&(0,l5.nextTick)(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}uf.WT=f5;Object.defineProperty(nf,"__esModule",{value:!0});nf.transports=void 0;const h5=ha,p5=Jo,v5=uf;nf.transports={websocket:p5.WS,webtransport:v5.WT,polling:h5.XHR};var Qv={};Object.defineProperty(Qv,"__esModule",{value:!0});Qv.parse=y5;const g5=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,m5=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function y5(r){if(r.length>8e3)throw"URI too long";const e=r,t=r.indexOf("["),n=r.indexOf("]");t!=-1&&n!=-1&&(r=r.substring(0,t)+r.substring(t,n).replace(/:/g,";")+r.substring(n,r.length));let i=g5.exec(r||""),s={},a=14;for(;a--;)s[m5[a]]=i[a]||"";return t!=-1&&n!=-1&&(s.source=e,s.host=s.host.substring(1,s.host.length-1).replace(/;/g,":"),s.authority=s.authority.replace("[","").replace("]","").replace(/;/g,":"),s.ipv6uri=!0),s.pathNames=_5(s,s.path),s.queryKey=b5(s,s.query),s}function _5(r,e){const t=/\/{2,9}/g,n=e.replace(t,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&n.splice(0,1),e.slice(-1)=="/"&&n.splice(n.length-1,1),n}function b5(r,e){const t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,i,s){i&&(t[i]=s)}),t}var S5=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(eo,"__esModule",{value:!0});eo.Socket=eo.SocketWithUpgrade=eo.SocketWithoutUpgrade=void 0;const w5=nf,ik=Js,T5=of,sk=Qv,C5=Cl,jO=Tl,xy=Li,E5=S5(Ys),Hr=(0,E5.default)("engine.io-client:socket"),Bb=typeof addEventListener=="function"&&typeof removeEventListener=="function",Nd=[];Bb&&addEventListener("offline",()=>{Hr("closing %d connection(s) because the network was lost",Nd.length),Nd.forEach(r=>r())},!1);class to extends C5.Emitter{constructor(e,t){if(super(),this.binaryType=xy.defaultBinaryType,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e=="object"&&(t=e,e=null),e){const n=(0,sk.parse)(e);t.hostname=n.host,t.secure=n.protocol==="https"||n.protocol==="wss",t.port=n.port,n.query&&(t.query=n.query)}else t.host&&(t.hostname=(0,sk.parse)(t.host).host);(0,ik.installTimerFunctions)(this,t),this.secure=t.secure!=null?t.secure:typeof location<"u"&&location.protocol==="https:",t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=t.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(n=>{const i=n.prototype.name;this.transports.push(i),this._transportsByName[i]=n}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=(0,T5.decode)(this.opts.query)),Bb&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(Hr("adding listener for the 'offline' event"),this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Nd.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=(0,xy.createCookieJar)()),this._open()}createTransport(e){Hr('creating transport "%s"',e);const t=Object.assign({},this.opts.query);t.EIO=jO.protocol,t.transport=e,this.id&&(t.sid=this.id);const n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return Hr("options: %j",n),new this._transportsByName[e](n)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const e=this.opts.rememberUpgrade&&to.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){Hr("setting transport %s",e.name),this.transport&&(Hr("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){Hr("socket open"),this.readyState="open",to.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(Hr('socket receive: type "%s", data "%s"',e.type,e.data),this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data);break}else Hr('packet received with socket readyState "%s"',this.readyState)}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this._getWritablePackets();Hr("flushing %d packets in socket",e.length),this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let n=0;n<this.writeBuffer.length;n++){const i=this.writeBuffer[n].data;if(i&&(t+=(0,ik.byteLength)(i)),n>0&&t>this._maxPayload)return Hr("only send %d out of %d packets",n,this.writeBuffer.length),this.writeBuffer.slice(0,n);t+=2}return Hr("payload size is %d (max: %d)",t,this._maxPayload),this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(Hr("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,(0,xy.nextTick)(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,n){return this._sendPacket("message",e,t,n),this}send(e,t,n){return this._sendPacket("message",e,t,n),this}_sendPacket(e,t,n,i){if(typeof t=="function"&&(i=t,t=void 0),typeof n=="function"&&(i=n,n=null),this.readyState==="closing"||this.readyState==="closed")return;n=n||{},n.compress=n.compress!==!1;const s={type:e,data:t,options:n};this.emitReserved("packetCreate",s),this.writeBuffer.push(s),i&&this.once("flush",i),this.flush()}close(){const e=()=>{this._onClose("forced close"),Hr("socket closing - telling transport to close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},n=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():e()}):this.upgrading?n():e()),this}_onError(e){if(Hr("socket error %j",e),to.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return Hr("trying next transport"),this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(Hr('socket close with reason: "%s"',e),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Bb&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const n=Nd.indexOf(this._offlineEventListener);n!==-1&&(Hr("removing listener for the 'offline' event"),Nd.splice(n,1))}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}eo.SocketWithoutUpgrade=to;to.protocol=jO.protocol;class BO extends to{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){Hr("starting upgrade probes");for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}}_probe(e){Hr('probing transport "%s"',e);let t=this.createTransport(e),n=!1;to.priorWebsocketSuccess=!1;const i=()=>{n||(Hr('probe transport "%s" opened',e),t.send([{type:"ping",data:"probe"}]),t.once("packet",h=>{if(!n)if(h.type==="pong"&&h.data==="probe"){if(Hr('probe transport "%s" pong',e),this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;to.priorWebsocketSuccess=t.name==="websocket",Hr('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{n||this.readyState!=="closed"&&(Hr("changing transport and sending upgrade packet"),d(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{Hr('probe transport "%s" failed',e);const v=new Error("probe error");v.transport=t.name,this.emitReserved("upgradeError",v)}}))};function s(){n||(n=!0,d(),t.close(),t=null)}const a=h=>{const v=new Error("probe error: "+h);v.transport=t.name,s(),Hr('probe transport "%s" failed because of error: %s',e,h),this.emitReserved("upgradeError",v)};function c(){a("transport closed")}function o(){a("socket closed")}function l(h){t&&h.name!==t.name&&(Hr('"%s" works - aborting "%s"',h.name,t.name),s())}const d=()=>{t.removeListener("open",i),t.removeListener("error",a),t.removeListener("close",c),this.off("close",o),this.off("upgrading",l)};t.once("open",i),t.once("error",a),t.once("close",c),this.once("close",o),this.once("upgrading",l),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}}eo.SocketWithUpgrade=BO;let k5=class extends BO{constructor(e,t={}){const n=typeof e=="object"?e:t;(!n.transports||n.transports&&typeof n.transports[0]=="string")&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(i=>w5.transports[i]).filter(i=>!!i)),super(e,n)}};eo.Socket=k5;var Zv={};Object.defineProperty(Zv,"__esModule",{value:!0});Zv.Fetch=void 0;const R5=sf;class P5 extends R5.Polling{doPoll(){this._fetch().then(e=>{if(!e.ok)return this.onError("fetch read error",e.status,e);e.text().then(t=>this.onData(t))}).catch(e=>{this.onError("fetch read error",e)})}doWrite(e,t){this._fetch(e).then(n=>{if(!n.ok)return this.onError("fetch write error",n.status,n);t()}).catch(n=>{this.onError("fetch write error",n)})}_fetch(e){var t;const n=e!==void 0,i=new Headers(this.opts.extraHeaders);return n&&i.set("content-type","text/plain;charset=UTF-8"),(t=this.socket._cookieJar)===null||t===void 0||t.appendCookies(i),fetch(this.uri(),{method:n?"POST":"GET",body:n?e:null,headers:i,credentials:this.opts.withCredentials?"include":"omit"}).then(s=>{var a;return(a=this.socket._cookieJar)===null||a===void 0||a.parseCookies(s.headers.getSetCookie()),s})}}Zv.Fetch=P5;(function(r){Object.defineProperty(r,"__esModule",{value:!0}),r.WebTransport=r.WebSocket=r.NodeWebSocket=r.XHR=r.NodeXHR=r.Fetch=r.nextTick=r.parse=r.installTimerFunctions=r.transports=r.TransportError=r.Transport=r.protocol=r.SocketWithUpgrade=r.SocketWithoutUpgrade=r.Socket=void 0;const e=eo;Object.defineProperty(r,"Socket",{enumerable:!0,get:function(){return e.Socket}});var t=eo;Object.defineProperty(r,"SocketWithoutUpgrade",{enumerable:!0,get:function(){return t.SocketWithoutUpgrade}}),Object.defineProperty(r,"SocketWithUpgrade",{enumerable:!0,get:function(){return t.SocketWithUpgrade}}),r.protocol=e.Socket.protocol;var n=ro;Object.defineProperty(r,"Transport",{enumerable:!0,get:function(){return n.Transport}}),Object.defineProperty(r,"TransportError",{enumerable:!0,get:function(){return n.TransportError}});var i=nf;Object.defineProperty(r,"transports",{enumerable:!0,get:function(){return i.transports}});var s=Js;Object.defineProperty(r,"installTimerFunctions",{enumerable:!0,get:function(){return s.installTimerFunctions}});var a=Qv;Object.defineProperty(r,"parse",{enumerable:!0,get:function(){return a.parse}});var c=Li;Object.defineProperty(r,"nextTick",{enumerable:!0,get:function(){return c.nextTick}});var o=Zv;Object.defineProperty(r,"Fetch",{enumerable:!0,get:function(){return o.Fetch}});var l=ha;Object.defineProperty(r,"NodeXHR",{enumerable:!0,get:function(){return l.XHR}});var d=ha;Object.defineProperty(r,"XHR",{enumerable:!0,get:function(){return d.XHR}});var h=Jo;Object.defineProperty(r,"NodeWebSocket",{enumerable:!0,get:function(){return h.WS}});var v=Jo;Object.defineProperty(r,"WebSocket",{enumerable:!0,get:function(){return v.WS}});var y=uf;Object.defineProperty(r,"WebTransport",{enumerable:!0,get:function(){return y.WT}})})(Jv);var I5=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty($w,"__esModule",{value:!0});$w.url=$5;const A5=Jv,O5=I5(Ys),ak=(0,O5.default)("socket.io-client:url");function $5(r,e="",t){let n=r;t=t||typeof location<"u"&&location,r==null&&(r=t.protocol+"//"+t.host),typeof r=="string"&&(r.charAt(0)==="/"&&(r.charAt(1)==="/"?r=t.protocol+r:r=t.host+r),/^(https?|wss?):\/\//.test(r)||(ak("protocol-less url %s",r),typeof t<"u"?r=t.protocol+"//"+r:r="https://"+r),ak("parse %s",r),n=(0,A5.parse)(r)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const s=n.host.indexOf(":")!==-1?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+s+":"+n.port+e,n.href=n.protocol+"://"+s+(t&&t.port===n.port?"":":"+n.port),n}var eg={},cf={},Qi={},tg={},lf={};Object.defineProperty(lf,"__esModule",{value:!0});lf.isBinary=WO;lf.hasBinary=Wp;const x5=typeof ArrayBuffer=="function",M5=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r.buffer instanceof ArrayBuffer,qO=Object.prototype.toString,D5=typeof Blob=="function"||typeof Blob<"u"&&qO.call(Blob)==="[object BlobConstructor]",N5=typeof File=="function"||typeof File<"u"&&qO.call(File)==="[object FileConstructor]";function WO(r){return x5&&(r instanceof ArrayBuffer||M5(r))||D5&&r instanceof Blob||N5&&r instanceof File}function Wp(r,e){if(!r||typeof r!="object")return!1;if(Array.isArray(r)){for(let t=0,n=r.length;t<n;t++)if(Wp(r[t]))return!0;return!1}if(WO(r))return!0;if(r.toJSON&&typeof r.toJSON=="function"&&arguments.length===1)return Wp(r.toJSON(),!0);for(const t in r)if(Object.prototype.hasOwnProperty.call(r,t)&&Wp(r[t]))return!0;return!1}Object.defineProperty(tg,"__esModule",{value:!0});tg.deconstructPacket=U5;tg.reconstructPacket=F5;const L5=lf;function U5(r){const e=[],t=r.data,n=r;return n.data=qb(t,e),n.attachments=e.length,{packet:n,buffers:e}}function qb(r,e){if(!r)return r;if((0,L5.isBinary)(r)){const t={_placeholder:!0,num:e.length};return e.push(r),t}else if(Array.isArray(r)){const t=new Array(r.length);for(let n=0;n<r.length;n++)t[n]=qb(r[n],e);return t}else if(typeof r=="object"&&!(r instanceof Date)){const t={};for(const n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=qb(r[n],e));return t}return r}function F5(r,e){return r.data=Wb(r.data,e),delete r.attachments,r}function Wb(r,e){if(!r)return r;if(r&&r._placeholder===!0){if(typeof r.num=="number"&&r.num>=0&&r.num<e.length)return e[r.num];throw new Error("illegal attachments")}else if(Array.isArray(r))for(let t=0;t<r.length;t++)r[t]=Wb(r[t],e);else if(typeof r=="object")for(const t in r)Object.prototype.hasOwnProperty.call(r,t)&&(r[t]=Wb(r[t],e));return r}Object.defineProperty(Qi,"__esModule",{value:!0});Qi.Decoder=Qi.Encoder=Qi.PacketType=Qi.protocol=void 0;Qi.isPacketValid=K5;const j5=Cl,VO=tg,HO=lf,B5=Ys,Vb=(0,B5.default)("socket.io-parser"),GO=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];Qi.protocol=5;var Lr;(function(r){r[r.CONNECT=0]="CONNECT",r[r.DISCONNECT=1]="DISCONNECT",r[r.EVENT=2]="EVENT",r[r.ACK=3]="ACK",r[r.CONNECT_ERROR=4]="CONNECT_ERROR",r[r.BINARY_EVENT=5]="BINARY_EVENT",r[r.BINARY_ACK=6]="BINARY_ACK"})(Lr||(Qi.PacketType=Lr={}));class q5{constructor(e){this.replacer=e}encode(e){return Vb("encoding packet %j",e),(e.type===Lr.EVENT||e.type===Lr.ACK)&&(0,HO.hasBinary)(e)?this.encodeAsBinary({type:e.type===Lr.EVENT?Lr.BINARY_EVENT:Lr.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===Lr.BINARY_EVENT||e.type===Lr.BINARY_ACK)&&(t+=e.attachments+"-"),e.nsp&&e.nsp!=="/"&&(t+=e.nsp+","),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),Vb("encoded %j as %s",e,t),t}encodeAsBinary(e){const t=(0,VO.deconstructPacket)(e),n=this.encodeAsString(t.packet),i=t.buffers;return i.unshift(n),i}}Qi.Encoder=q5;class xw extends j5.Emitter{constructor(e){super(),this.reviver=e}add(e){let t;if(typeof e=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const n=t.type===Lr.BINARY_EVENT;n||t.type===Lr.BINARY_ACK?(t.type=n?Lr.EVENT:Lr.ACK,this.reconstructor=new W5(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if((0,HO.isBinary)(e)||e.base64)if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+e)}decodeString(e){let t=0;const n={type:Number(e.charAt(0))};if(Lr[n.type]===void 0)throw new Error("unknown packet type "+n.type);if(n.type===Lr.BINARY_EVENT||n.type===Lr.BINARY_ACK){const s=t+1;for(;e.charAt(++t)!=="-"&&t!=e.length;);const a=e.substring(s,t);if(a!=Number(a)||e.charAt(t)!=="-")throw new Error("Illegal attachments");n.attachments=Number(a)}if(e.charAt(t+1)==="/"){const s=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););n.nsp=e.substring(s,t)}else n.nsp="/";const i=e.charAt(t+1);if(i!==""&&Number(i)==i){const s=t+1;for(;++t;){const a=e.charAt(t);if(a==null||Number(a)!=a){--t;break}if(t===e.length)break}n.id=Number(e.substring(s,t+1))}if(e.charAt(++t)){const s=this.tryParse(e.substr(t));if(xw.isPayloadValid(n.type,s))n.data=s;else throw new Error("invalid payload")}return Vb("decoded %s as %j",e,n),n}tryParse(e){try{return JSON.parse(e,this.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case Lr.CONNECT:return dv(t);case Lr.DISCONNECT:return t===void 0;case Lr.CONNECT_ERROR:return typeof t=="string"||dv(t);case Lr.EVENT:case Lr.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&GO.indexOf(t[0])===-1);case Lr.ACK:case Lr.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}Qi.Decoder=xw;class W5{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const t=(0,VO.reconstructPacket)(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}function V5(r){return typeof r=="string"}const H5=Number.isInteger||function(r){return typeof r=="number"&&isFinite(r)&&Math.floor(r)===r};function G5(r){return r===void 0||H5(r)}function dv(r){return Object.prototype.toString.call(r)==="[object Object]"}function z5(r,e){switch(r){case Lr.CONNECT:return e===void 0||dv(e);case Lr.DISCONNECT:return e===void 0;case Lr.EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&GO.indexOf(e[0])===-1);case Lr.ACK:return Array.isArray(e);case Lr.CONNECT_ERROR:return typeof e=="string"||dv(e);default:return!1}}function K5(r){return V5(r.nsp)&&G5(r.id)&&z5(r.type,r.data)}var rg={};Object.defineProperty(rg,"__esModule",{value:!0});rg.on=J5;function J5(r,e,t){return r.on(e,t),function(){r.off(e,t)}}var Y5=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(cf,"__esModule",{value:!0});cf.Socket=void 0;const Ns=Qi,Ah=rg,X5=Cl,Q5=Y5(Ys),_n=(0,Q5.default)("socket.io-client:socket"),Z5=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class eH extends X5.Emitter{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[(0,Ah.on)(e,"open",this.onopen.bind(this)),(0,Ah.on)(e,"packet",this.onpacket.bind(this)),(0,Ah.on)(e,"error",this.onerror.bind(this)),(0,Ah.on)(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var n,i,s;if(Z5.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const a={type:Ns.PacketType.EVENT,data:t};if(a.options={},a.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){const d=this.ids++;_n("emitting packet with ack id %d",d);const h=t.pop();this._registerAckCallback(d,h),a.id=d}const c=(i=(n=this.io.engine)===null||n===void 0?void 0:n.transport)===null||i===void 0?void 0:i.writable,o=this.connected&&!(!((s=this.io.engine)===null||s===void 0)&&s._hasPingExpired());return this.flags.volatile&&!c?_n("discard packet as the transport is not currently writable"):o?(this.notifyOutgoingListeners(a),this.packet(a)):this.sendBuffer.push(a),this.flags={},this}_registerAckCallback(e,t){var n;const i=(n=this.flags.timeout)!==null&&n!==void 0?n:this._opts.ackTimeout;if(i===void 0){this.acks[e]=t;return}const s=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let c=0;c<this.sendBuffer.length;c++)this.sendBuffer[c].id===e&&(_n("removing packet with ack id %d from the buffer",e),this.sendBuffer.splice(c,1));_n("event with ack id %d has timed out after %d ms",e,i),t.call(this,new Error("operation has timed out"))},i),a=(...c)=>{this.io.clearTimeoutFn(s),t.apply(this,c)};a.withError=!0,this.acks[e]=a}emitWithAck(e,...t){return new Promise((n,i)=>{const s=(a,c)=>a?i(a):n(c);s.withError=!0,t.push(s),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((i,...s)=>n!==this._queue[0]?_n("packet [%d] already acknowledged",n.id):(i!==null?n.tryCount>this._opts.retries&&(_n("packet [%d] is discarded after %d tries",n.id,n.tryCount),this._queue.shift(),t&&t(i)):(_n("packet [%d] was successfully sent",n.id),this._queue.shift(),t&&t(null,...s)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(_n("draining queue"),!this.connected||this._queue.length===0)return;const t=this._queue[0];if(t.pending&&!e){_n("packet [%d] has already been sent and is waiting for an ack",t.id);return}t.pending=!0,t.tryCount++,_n("sending packet [%d] (try n°%d)",t.id,t.tryCount),this.flags=t.flags,this.emit.apply(this,t.args)}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){_n("transport is open - connecting"),typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:Ns.PacketType.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){_n("close (%s)",e),this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(n=>String(n.id)===e)){const n=this.acks[e];delete this.acks[e],n.withError&&n.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case Ns.PacketType.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Ns.PacketType.EVENT:case Ns.PacketType.BINARY_EVENT:this.onevent(e);break;case Ns.PacketType.ACK:case Ns.PacketType.BINARY_ACK:this.onack(e);break;case Ns.PacketType.DISCONNECT:this.ondisconnect();break;case Ns.PacketType.CONNECT_ERROR:this.destroy();const n=new Error(e.data.message);n.data=e.data.data,this.emitReserved("connect_error",n);break}}onevent(e){const t=e.data||[];_n("emitting event %j",t),e.id!=null&&(_n("attaching ack callback to event"),t.push(this.ack(e.id))),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let n=!1;return function(...i){n||(n=!0,_n("sending ack %j",i),t.packet({type:Ns.PacketType.ACK,id:e,data:i}))}}onack(e){const t=this.acks[e.id];if(typeof t!="function"){_n("bad ack %s",e.id);return}delete this.acks[e.id],_n("calling ack %s with %j",e.id,e.data),t.withError&&e.data.unshift(null),t.apply(this,e.data)}onconnect(e,t){_n("socket connected with id %s",e),this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){_n("server disconnect (%s)",this.nsp),this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&(_n("performing disconnect (%s)",this.nsp),this.packet({type:Ns.PacketType.DISCONNECT})),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const n of t)n.apply(this,e.data)}}}cf.Socket=eH;var Mw={};Object.defineProperty(Mw,"__esModule",{value:!0});Mw.Backoff=El;function El(r){r=r||{},this.ms=r.min||100,this.max=r.max||1e4,this.factor=r.factor||2,this.jitter=r.jitter>0&&r.jitter<=1?r.jitter:0,this.attempts=0}El.prototype.duration=function(){var r=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),t=Math.floor(e*this.jitter*r);r=Math.floor(e*10)&1?r+t:r-t}return Math.min(r,this.max)|0};El.prototype.reset=function(){this.attempts=0};El.prototype.setMin=function(r){this.ms=r};El.prototype.setMax=function(r){this.max=r};El.prototype.setJitter=function(r){this.jitter=r};var tH=Ye&&Ye.__createBinding||(Object.create?function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}:function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]}),rH=Ye&&Ye.__setModuleDefault||(Object.create?function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}:function(r,e){r.default=e}),nH=Ye&&Ye.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&tH(e,r,t);return rH(e,r),e},iH=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(eg,"__esModule",{value:!0});eg.Manager=void 0;const My=Jv,sH=cf,aH=nH(Qi),Tu=rg,oH=Mw,uH=Cl,cH=iH(Ys),Vn=(0,cH.default)("socket.io-client:manager");class lH extends uH.Emitter{constructor(e,t){var n;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(t=e,e=void 0),t=t||{},t.path=t.path||"/socket.io",this.opts=t,(0,My.installTimerFunctions)(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor((n=t.randomizationFactor)!==null&&n!==void 0?n:.5),this.backoff=new oH.Backoff({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;const i=t.parser||aH;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(Vn("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;Vn("opening %s",this.uri),this.engine=new My.Socket(this.uri,this.opts);const t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const i=(0,Tu.on)(t,"open",function(){n.onopen(),e&&e()}),s=c=>{Vn("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",c),e?e(c):this.maybeReconnectOnOpen()},a=(0,Tu.on)(t,"error",s);if(this._timeout!==!1){const c=this._timeout;Vn("connect attempt will timeout after %d",c);const o=this.setTimeoutFn(()=>{Vn("connect attempt timed out after %d",c),i(),s(new Error("timeout")),t.close()},c);this.opts.autoUnref&&o.unref(),this.subs.push(()=>{this.clearTimeoutFn(o)})}return this.subs.push(i),this.subs.push(a),this}connect(e){return this.open(e)}onopen(){Vn("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push((0,Tu.on)(e,"ping",this.onping.bind(this)),(0,Tu.on)(e,"data",this.ondata.bind(this)),(0,Tu.on)(e,"error",this.onerror.bind(this)),(0,Tu.on)(e,"close",this.onclose.bind(this)),(0,Tu.on)(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){(0,My.nextTick)(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){Vn("error",e),this.emitReserved("error",e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new sH.Socket(this,e,t),this.nsps[e]=n),n}_destroy(e){const t=Object.keys(this.nsps);for(const n of t)if(this.nsps[n].active){Vn("socket %s is still active, skipping close",n);return}this._close()}_packet(e){Vn("writing packet %j",e);const t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){Vn("cleanup"),this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){Vn("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var n;Vn("closed due to %s",e),this.cleanup(),(n=this.engine)===null||n===void 0||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)Vn("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();Vn("will wait %dms before reconnect attempt",t),this._reconnecting=!0;const n=this.setTimeoutFn(()=>{e.skipReconnect||(Vn("attempting reconnect"),this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(i=>{i?(Vn("reconnect attempt error"),e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",i)):(Vn("reconnect success"),e.onreconnect())}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}eg.Manager=lH;(function(r,e){var t=Ye&&Ye.__importDefault||function(v){return v&&v.__esModule?v:{default:v}};Object.defineProperty(e,"__esModule",{value:!0}),e.WebTransport=e.WebSocket=e.NodeWebSocket=e.XHR=e.NodeXHR=e.Fetch=e.Socket=e.Manager=e.protocol=void 0,e.io=l,e.connect=l,e.default=l;const n=$w,i=eg;Object.defineProperty(e,"Manager",{enumerable:!0,get:function(){return i.Manager}});const s=cf;Object.defineProperty(e,"Socket",{enumerable:!0,get:function(){return s.Socket}});const c=(0,t(Ys).default)("socket.io-client"),o={};function l(v,y){typeof v=="object"&&(y=v,v=void 0),y=y||{};const w=(0,n.url)(v,y.path||"/socket.io"),k=w.source,I=w.id,A=w.path,j=o[I]&&A in o[I].nsps,L=y.forceNew||y["force new connection"]||y.multiplex===!1||j;let x;return L?(c("ignoring socket cache for %s",k),x=new i.Manager(k,y)):(o[I]||(c("new io instance for %s",k),o[I]=new i.Manager(k,y)),x=o[I]),w.query&&!y.query&&(y.query=w.queryKey),x.socket(w.path,y)}Object.assign(l,{Manager:i.Manager,Socket:s.Socket,io:l,connect:l});var d=Qi;Object.defineProperty(e,"protocol",{enumerable:!0,get:function(){return d.protocol}});var h=Jv;Object.defineProperty(e,"Fetch",{enumerable:!0,get:function(){return h.Fetch}}),Object.defineProperty(e,"NodeXHR",{enumerable:!0,get:function(){return h.NodeXHR}}),Object.defineProperty(e,"XHR",{enumerable:!0,get:function(){return h.XHR}}),Object.defineProperty(e,"NodeWebSocket",{enumerable:!0,get:function(){return h.NodeWebSocket}}),Object.defineProperty(e,"WebSocket",{enumerable:!0,get:function(){return h.WebSocket}}),Object.defineProperty(e,"WebTransport",{enumerable:!0,get:function(){return h.WebTransport}}),r.exports=l})(Lb,Lb.exports);var zO=Lb.exports,KO={exports:{}};(function(r,e){(function(t){r.exports=t()})(function(){var t=function(p,g,b){for(var _=b,S=0,T=p.length;S<T;S++)_=g(_,p[S],S,p);return _},n=function(p,g){return t(p,function(b,_,S,T){return g(_,S,T)?b.concat(_):b},[])},i=function(p,g){return t(p,function(b,_,S,T){return b.concat(g(_,S,T))},[])},s=function(p,g){return t(p,function(b,_,S,T){return b===!0||_===g},!1)},a=!{toString:null}.propertyIsEnumerable("toString"),c=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],o=function(p){var g=[],b;for(b in p)Object.prototype.hasOwnProperty.call(p,b)&&g.push(b);if(!a)return g;for(var _=0,S=c.length;_<S;_++)Object.prototype.hasOwnProperty.call(p,c[_])&&g.push(c[_]);return g},l=function(p){return Object.prototype.toString.call(p)==="[object Array]"},d=function(p){return p<10?"0"+p:p},h=function(){var p=new Date;return p.getUTCFullYear()+"-"+d(p.getUTCMonth()+1)+"-"+d(p.getUTCDate())+"T"+d(p.getUTCHours())+":"+d(p.getUTCMinutes())+":"+d(p.getUTCSeconds())+"."+(p.getUTCMilliseconds()/1e3).toFixed(3).slice(2,5)+"Z"},v={map:i,reduce:t,filter:n,includes:s,keys:o,isArray:l,isoDate:h},y={};y.intRange=function(p,g){return p===void 0&&(p=1),g===void 0&&(g=1/0),function(b){return typeof b=="number"&&parseInt(""+b,10)===b&&b>=p&&b<=g}},y.stringWithLength=function(p){return typeof p=="string"&&!!p.length};var w={},k=v.filter,I=v.reduce,A=v.keys,j=v.isArray,L=v.includes,x=y.intRange,B=y.stringWithLength;w.schema={apiKey:{defaultValue:function(){return null},message:"is required",validate:B},appVersion:{defaultValue:function(){return null},message:"should be a string",validate:function(p){return p===null||B(p)}},appType:{defaultValue:function(){return null},message:"should be a string",validate:function(p){return p===null||B(p)}},autoNotify:{defaultValue:function(){return!0},message:"should be true|false",validate:function(p){return p===!0||p===!1}},beforeSend:{defaultValue:function(){return[]},message:"should be a function or array of functions",validate:function(p){return typeof p=="function"||j(p)&&k(p,function(g){return typeof g=="function"}).length===p.length}},endpoints:{defaultValue:function(){return{notify:"https://notify.bugsnag.com",sessions:"https://sessions.bugsnag.com"}},message:"should be an object containing endpoint URLs { notify, sessions }. sessions is optional if autoCaptureSessions=false",validate:function(p,g){return p&&typeof p=="object"&&B(p.notify)&&(g.autoCaptureSessions===!1||B(p.sessions))&&k(A(p),function(b){return!L(["notify","sessions"],b)}).length===0}},autoCaptureSessions:{defaultValue:function(p,g){return g.endpoints===void 0||!!g.endpoints&&!!g.endpoints.sessions},message:"should be true|false",validate:function(p){return p===!0||p===!1}},notifyReleaseStages:{defaultValue:function(){return null},message:"should be an array of strings",validate:function(p){return p===null||j(p)&&k(p,function(g){return typeof g=="string"}).length===p.length}},releaseStage:{defaultValue:function(){return"production"},message:"should be a string",validate:function(p){return typeof p=="string"&&p.length}},maxBreadcrumbs:{defaultValue:function(){return 20},message:"should be a number ≤40",validate:function(p){return x(0,40)(p)}},autoBreadcrumbs:{defaultValue:function(){return!0},message:"should be true|false",validate:function(p){return typeof p=="boolean"}},user:{defaultValue:function(){return null},message:"(object) user should be an object",validate:function(p){return typeof p=="object"}},metaData:{defaultValue:function(){return null},message:"should be an object",validate:function(p){return typeof p=="object"}},logger:{defaultValue:function(){},message:"should be null or an object with methods { debug, info, warn, error }",validate:function(p){return!p||p&&I(["debug","info","warn","error"],function(g,b){return g&&typeof p[b]=="function"},!0)}},filters:{defaultValue:function(){return["password"]},message:"should be an array of strings|regexes",validate:function(p){return j(p)&&p.length===k(p,function(g){return typeof g=="string"||g&&typeof g.test=="function"}).length}}},w.mergeDefaults=function(p,g){if(!p||!g)throw new Error("opts and schema objects are required");return I(A(g),function(b,_){return b[_]=p[_]!==void 0?p[_]:g[_].defaultValue(p[_],p),b},{})},w.validate=function(p,g){if(!p||!g)throw new Error("opts and schema objects are required");var b=I(A(g),function(_,S){return g[S].validate(p[S],p)?_:_.concat({key:S,message:g[S].message,value:p[S]})},[]);return{valid:!b.length,errors:b}};function G(){return G=Object.assign||function(p){for(var g=1;g<arguments.length;g++){var b=arguments[g];for(var _ in b)Object.prototype.hasOwnProperty.call(b,_)&&(p[_]=b[_])}return p},G.apply(this,arguments)}var K=w.schema,D=v.map,fe=y.stringWithLength,X={releaseStage:{defaultValue:function(){return/^localhost(:\d+)?$/.test(window.location.host)?"development":"production"},message:"should be set",validate:fe},logger:G({},K.logger,{defaultValue:function(){return typeof console<"u"&&typeof console.debug=="function"?pe():void 0}})},pe=function(){var p={},g=console.log;return D(["debug","info","warn","error"],function(b){var _=console[b];p[b]=typeof _=="function"?_.bind(console,"[bugsnag]"):g.bind(console,"[bugsnag]")}),p},Q=v.isoDate,Oe=function(){function p(b,_,S,T){b===void 0&&(b="[anonymous]"),_===void 0&&(_={}),S===void 0&&(S="manual"),T===void 0&&(T=Q()),this.type=S,this.name=b,this.metaData=_,this.timestamp=T}var g=p.prototype;return g.toJSON=function(){return{type:this.type,name:this.name,timestamp:this.timestamp,metaData:this.metaData}},p}(),Ve=Oe,Ze=function(p,g,b){var _=p.length,S=0,T=function(){if(S>=_)return b(null,!1);g(p[S],function(C,P){if(C)return b(C,!1);if(P===!0)return b(null,!0);S++,T()})};T()},Xe=function(p){return p.app&&typeof p.app.releaseStage=="string"?p.app.releaseStage:p.config.releaseStage},Re=Je;function Je(p){switch(Object.prototype.toString.call(p)){case"[object Error]":return!0;case"[object Exception]":return!0;case"[object DOMException]":return!0;default:return p instanceof Error}}var Ke=Re,Y=function(p,g){return function(b,_){if(typeof b!="function")return _(null,!1);try{if(b.length!==2){var S=b(p);return S&&typeof S.then=="function"?S.then(function(T){return setTimeout(function(){return _(null,Ce(p,T))},0)},function(T){setTimeout(function(){return g(T),_(null,!1)})}):_(null,Ce(p,S))}b(p,function(T,C){if(T)return g(T),_(null,!1);_(null,Ce(p,C))})}catch(T){g(T),_(null,!1)}}},Ce=function(p,g){return p.isIgnored()||g===!1},Et={};(function(p,g){typeof Et=="object"?Et=g():p.StackFrame=g()})(this,function(){function p(Se){return!isNaN(parseFloat(Se))&&isFinite(Se)}function g(Se){return Se.charAt(0).toUpperCase()+Se.substring(1)}function b(Se){return function(){return this[Se]}}var _=["isConstructor","isEval","isNative","isToplevel"],S=["columnNumber","lineNumber"],T=["fileName","functionName","source"],C=["args"],P=_.concat(S,T,C);function q(Se){if(Se instanceof Object)for(var Ge=0;Ge<P.length;Ge++)Se.hasOwnProperty(P[Ge])&&Se[P[Ge]]!==void 0&&this["set"+g(P[Ge])](Se[P[Ge]])}q.prototype={getArgs:function(){return this.args},setArgs:function(Se){if(Object.prototype.toString.call(Se)!=="[object Array]")throw new TypeError("Args must be an Array");this.args=Se},getEvalOrigin:function(){return this.evalOrigin},setEvalOrigin:function(Se){if(Se instanceof q)this.evalOrigin=Se;else if(Se instanceof Object)this.evalOrigin=new q(Se);else throw new TypeError("Eval Origin must be an Object or StackFrame")},toString:function(){var Se=this.getFunctionName()||"{anonymous}",Ge="("+(this.getArgs()||[]).join(",")+")",gt=this.getFileName()?"@"+this.getFileName():"",et=p(this.getLineNumber())?":"+this.getLineNumber():"",ct=p(this.getColumnNumber())?":"+this.getColumnNumber():"";return Se+Ge+gt+et+ct}};for(var H=0;H<_.length;H++)q.prototype["get"+g(_[H])]=b(_[H]),q.prototype["set"+g(_[H])]=function(Se){return function(Ge){this[Se]=!!Ge}}(_[H]);for(var J=0;J<S.length;J++)q.prototype["get"+g(S[J])]=b(S[J]),q.prototype["set"+g(S[J])]=function(Se){return function(Ge){if(!p(Ge))throw new TypeError(Se+" must be a Number");this[Se]=Number(Ge)}}(S[J]);for(var ae=0;ae<T.length;ae++)q.prototype["get"+g(T[ae])]=b(T[ae]),q.prototype["set"+g(T[ae])]=function(Se){return function(Ge){this[Se]=String(Ge)}}(T[ae]);return q});var Nt={};(function(p,g){typeof Nt=="object"?Nt=g(Et):p.ErrorStackParser=g(p.StackFrame)})(this,function(g){var b=/(^|@)\S+\:\d+/,_=/^\s*at .*(\S+\:\d+|\(native\))/m,S=/^(eval@)?(\[native code\])?$/;return{parse:function(C){if(typeof C.stacktrace<"u"||typeof C["opera#sourceloc"]<"u")return this.parseOpera(C);if(C.stack&&C.stack.match(_))return this.parseV8OrIE(C);if(C.stack)return this.parseFFOrSafari(C);throw new Error("Cannot parse given Error object")},extractLocation:function(C){if(C.indexOf(":")===-1)return[C];var P=/(.+?)(?:\:(\d+))?(?:\:(\d+))?$/,q=P.exec(C.replace(/[\(\)]/g,""));return[q[1],q[2]||void 0,q[3]||void 0]},parseV8OrIE:function(C){var P=C.stack.split(`
|
|
2
|
+
`+en),Ot&&Eh([Q,Oe,Ve],yn=>{en=rd(en,yn," ")}),x&&Mr?x.createHTML(en):en},e.setConfig=function(){let vt=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Me(vt),zt=!0},e.clearConfig=function(){ve=null,zt=!1},e.isValidAttribute=function(vt,ue,je){ve||Me({});const st=se(vt),Jt=se(ue);return qt(st,Jt,je)},e.addHook=function(vt,ue){typeof ue=="function"&&td(pe[vt],ue)},e.removeHook=function(vt,ue){if(ue!==void 0){const je=Nq(pe[vt],ue);return je===-1?void 0:Lq(pe[vt],je,1)[0]}return RE(pe[vt])},e.removeHooks=function(vt){pe[vt]=[]},e.removeAllHooks=function(){pe=xE()},e}var e6=oO();const t6={ALLOWED_TAGS:["b","i","em","strong","p","br","ul","ol","li","a"],ALLOWED_ATTR:["href","src","alt","title","target","class","id","style"],ALLOW_DATA_ATTR:!1,FORBID_TAGS:["img","iframe","object","input","style","script","embed","svg","video","audio","body","input","form","link"],FORBID_ATTR:["onerror","onclick","onload","onmouseover","onfocus","onblur","onchange","onsubmit","scr","href","style","action","value"],IN_PLACE:!0},r6="javascript:";var Lu;let Xc=(Lu=class extends Error{constructor(t,n,i){super(t);be(this,"code",Lu.CODE);be(this,"refusedBy");this.name="UnauthorizedError",this.refusedBy=n,i&&"cause"in i&&(this.cause=i.cause)}},be(Lu,"CODE","UNAUTHORIZED"),Lu);function n6(r){return(r==null?void 0:r.constructor)===Object}async function ME(r,e=3){let t=0,n;for(;t<=e;){t+=1;try{return await r()}catch(i){if(i instanceof Xc)throw i;n=i,console.error(i),await sv(1e3*Math.pow(2,t))}}throw n}function sv(r){return new Promise(e=>{setTimeout(()=>{e(0)},r)})}function Rw(){return Math.random().toString(36).slice(2)}const i6=new TextDecoder,s6=r=>{const e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return i6.decode(t)},a6=r=>r.length===0,o6=(...r)=>r.every(a6),$b=r=>{const e=e6.sanitize(r,t6);return e.includes(r6)?(console.warn("Suspicious content detected and removed."),""):e},u6=[8,4,4,4,12],c6=()=>{const r=globalThis.crypto;if(!r)return null;if(typeof r.randomUUID=="function")return r.randomUUID();if(typeof r.getRandomValues!="function")return null;const e=r.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=Array.from(e,i=>i.toString(16).padStart(2,"0")).join("");let n=0;return u6.map(i=>{const s=t.slice(n,n+i);return n+=i,s}).join("-")},l6="prod",Pw="6.25.0",DE="https://main.api.ujet.co",zn={companyId:"",tenant:"",trackerId:"",deviceId:"",application:"websdk",version:Pw};class d6{constructor(e){be(this,"buffer");be(this,"writeIndex",0);be(this,"size",0);be(this,"capacity");this.capacity=e,this.buffer=new Array(e)}push(e){this.buffer[this.writeIndex]=e,this.writeIndex++,this.writeIndex>=this.capacity&&(this.writeIndex=0),this.size<this.capacity&&this.size++}toArray(){return this.size<this.capacity?this.buffer.slice(0,this.size):[...this.buffer.slice(this.writeIndex),...this.buffer.slice(0,this.writeIndex)]}clear(){this.writeIndex=0,this.size=0,this.buffer=new Array(this.capacity)}}const Lo=class Lo{constructor(e){be(this,"channel");this.channel=e}static addHandler(e){Lo.logHandlers.push(e)}static printLogHistoryData(e){Lo.consoleLog(e.channel,e.level,...e.args)}static consoleLog(e,t,...n){console[t](`[${t}][${e}]`,...n)}debug(...e){this.log("debug",...e)}info(...e){this.log("info",...e)}warn(...e){this.log("warn",...e)}error(...e){this.log("error",...e)}log(e,...t){const n=t.map(Iw);Lo.logHandlers.forEach(i=>i(this.channel,e,...n)),Lo.logHistory.push({date:new Date().toISOString(),channel:this.channel,level:e,args:n})}};be(Lo,"logHandlers",[]),be(Lo,"logHistory",new d6(1e3));let an=Lo;const f6=(r,e,...t)=>{let n=t.pop();return typeof n=="string"&&(t.push(n),n={}),{loglevel:e,channel:r,timestamp:new Date().toISOString(),application:zn.application,sdk_version:zn.version,device_uuid:zn.deviceId,tenant:zn.tenant,company_id:zn.companyId,tracker_id:zn.trackerId||void 0,location_url:location.href,data:p6(n),message:Iw(t.join(" "))}},NE=["user","phone","phone_number","phoneNumber","email","token","access_token","accessToken","authorization","Authorization"],h6=[/(?:3[47]\d|(?:4\d|5[1-5]|65)\d{2}|6011)\d{12}/g,/(?!(000|666|9))\d{3}-(?!00)\d{2}-(?!0000)\d{4}/g,/[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)+/g,/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g];function Iw(r){return Lc(r,new WeakSet)}function Lc(r,e){if(!r)return r;if(typeof r=="string")return h6.forEach(t=>{r=r.replace(t,"__MASKED__")}),r;if(typeof r=="object"&&e.has(r))return"[Circular]";if(typeof r=="object"&&e.add(r),Array.isArray(r))return r.map(t=>Lc(t,e));if(r instanceof Error){const t={name:r.name,message:Lc(r.message,e)};r.stack&&(t.stack=Lc(r.stack,e));for(const n of Object.getOwnPropertyNames(r))n==="name"||n==="message"||n==="stack"||(NE.indexOf(n)!==-1?t[n]="__MASKED__":t[n]=Lc(r[n],e));return t}return n6(r)&&(r={...r},Object.keys(r).forEach(t=>{NE.indexOf(t)!==-1?r[t]="__MASKED__":r[t]=Lc(r[t],e)})),r}function p6(r){if(r.error){const e=r.error;return{error:{name:e.name,message:e.message,stack:e.stack}}}return Iw(r.data)}const v6=new an("chat-provider");class Hv{constructor(e,t,n,i){be(this,"audio");be(this,"issueChatToken");be(this,"identity");be(this,"channelId");be(this,"region");be(this,"inTask",!1);be(this,"muted",!1);be(this,"providerContext");be(this,"events");this.events=e,this.region=t.region,this.audio=new $q,this.issueChatToken=n,this.providerContext=i}async reconnect(){}ping(){if(!this.muted)try{this.audio.playPing()}catch(e){v6.warn("Chat audio play failed",{error:e})}}cleanupAudio(){this.audio&&this.audio.cleanup()}on(e,t){this.events.addEventListener(e,t)}off(e,t){this.events.removeEventListener(e,t)}trackInTask(e){e.type===ln.NOTI&&e.event===Gn.TASK_VA_STARTED?this.inTask=!0:e.type===ln.NOTI&&(e.event===Gn.TASK_VA_FINISHED||e.event===Gn.TASK_VA_FAILED)&&(this.inTask=!1)}}be(Hv,"type","base");const uO={};function Gv(r){uO[r.type]=r}function g6(r){return uO[r]}const Dv=class Dv extends Error{constructor(t){super("Cannot send a message: the chat has already ended");be(this,"code",Dv.CODE);be(this,"status");this.name="ChatEndedError",this.status=t}};be(Dv,"CODE","CHAT_ENDED");let av=Dv;const LE=new an("MediaStore"),m6=window.indexedDB||window.webkitIndexedDB||window.mozIndexedDB||window.OIndexedDB||window.msIndexedDB,y6="chat-media",UE=1,ov="file";class cO{constructor(){be(this,"db")}store(){return new Promise((e,t)=>{if(this.db)return e(FE(this.db));const n=m6.open(y6,UE);n.onerror=()=>{t(new Error("indexedDB open failed"))},n.onsuccess=()=>{const i=n.result;this.db=i,e(FE(i))},n.onupgradeneeded=i=>{const s=n.result;i.oldVersion>0&&i.oldVersion<UE&&(LE.info("deprecating media store"),s.deleteObjectStore(ov)),LE.info("creating media store"),s.createObjectStore(ov)}})}async save(e,t){(await this.store()).put({index:e,file:t},e)}async getAll(){const e=await this.store();return await new Promise((t,n)=>{const i=e.getAll();i.onerror=()=>{n(new Error("indexedDB getAll failed"))},i.onsuccess=()=>{t(i.result)}})}async getAllFiles(){const e={};return(await this.getAll()).forEach(n=>{e[n.index]=n.file}),e}async clear(){(await this.store()).clear()}}function FE(r){return r.transaction(ov,"readwrite").objectStore(ov)}const Bp={LOADED:"cobrowse.loaded",UPDATED:"cobrowse.updated",ENDED:"cobrowse.ended"},jE=1e4,_6=3e4,b6=9e5,lO={UPDATED:"riskFlagsUpdated"},wu=new an("Communicator");var Fo,rf;class S6{constructor(e,t){be(this,"user");be(this,"clientEventManager");be(this,"clientAuthenticate");be(this,"config");be(this,"channel");be(this,"channelReady",!1);be(this,"hasAuthenticated",!1);be(this,"hasInitializedLogProxy",!1);be(this,"queuedMessagesToBridge",[]);be(this,"pendingBridgeRequests",{});be(this,"bridgeIframe");be(this,"bridgeMessageHandlers");be(this,"tokenRefreshTimeout");be(this,"logProxyQueue",[]);hy(this,Fo,"");hy(this,rf,0);be(this,"authRefreshInFlight",null);be(this,"riskFlags",null);this.onReady=this.onReady.bind(this),this.onCallback=this.onCallback.bind(this),this.onRefreshToken=this.onRefreshToken.bind(this),this.onRiskFlags=this.onRiskFlags.bind(this),this.onMessageFromBridge=this.onMessageFromBridge.bind(this),this.clientAuthenticate=e.authenticate,this.clientEventManager=t,this.initConfig(e),this.channel=new MessageChannel,this.channel.port1.onmessage=this.onMessageFromBridge,this.initBridge()}get wsUrl(){return this.config.host.replace(/^http/,"ws")+"/ws"}async getAuthToken(e=!1){if(!e&&this.isAuthTokenFresh())return Rc(this,Fo);const t=await this.refreshAuthToken();if(!t)throw new Error("Auth refresh completed without a token");return t}async request(e,t){!this.hasAuthenticated&&e!=="proactive_chat_triggers"&&await this.onRefreshToken();const n={url:e,options:t};return this.postMessageWithCallbackToBridge("request",n)}leaveChatBeacon(e){var n;if(!Rc(this,Fo)||!((n=this.config)!=null&&n.host))return;const t=`${this.config.host}/api/v2/chats/${e}/leave`;fetch(t,{method:"POST",body:"{}",keepalive:!0,headers:{Authorization:`Bearer ${Rc(this,Fo)}`,"Content-Type":"application/json","UJET-SDK-Type":"Web"}}).catch(()=>{})}destroy(){delete this.channel,this.bridgeIframe&&(this.bridgeIframe.remove(),this.bridgeIframe=void 0),this.tokenRefreshTimeout&&clearTimeout(this.tokenRefreshTimeout)}getBridgeLogHistory(){return this.postMessageWithCallbackToBridge("_getLogHistory",{})}isRiskFlagEnabled(e){var t;return((t=this.riskFlags)==null?void 0:t[e])??!0}getRiskFlags(){return{...this.riskFlags??{}}}initBridge(){const e=document.createElement("iframe");e.src=this.config.bridge,e.setAttribute("style","display:none"),e.addEventListener("load",()=>{if(wu.debug("initialized iframe for origin:",this.config.bridgeOrigin),!this.channelReady){const t={type:"_init",data:this.config};wu.debug("sending message to bridge:",t),e.contentWindow.postMessage(t,this.config.bridgeOrigin,[this.channel.port2])}}),document.body.appendChild(e),this.bridgeIframe=e,this.bridgeMessageHandlers={ready:this.onReady,callback:this.onCallback,refreshToken:this.onRefreshToken,_riskFlags:this.onRiskFlags}}onReady(e){this.channelReady=!0,zn.deviceId=e.result.deviceId,zn.deviceId||wu.error("Device Id has not been provided. SDK will not work properly."),this.flushQueuedMessagesToBridge(),this.clientEventManager.triggerEvent("ready")}onCallback(e){if(!e.callbackId)return;const[t,n]=this.pendingBridgeRequests[e.callbackId];e.error?n(e.error):t(e.result),delete this.pendingBridgeRequests[e.callbackId]}async onRefreshToken(){try{await this.refreshAuthToken()}catch(e){if(!(e instanceof Xc))throw e;if(e.refusedBy==="client")throw e.cause;wu.error(e.message)}}isAuthTokenFresh(){return!!Rc(this,Fo)&&Rc(this,rf)-Date.now()>_6}refreshAuthToken(){return this.authRefreshInFlight??(this.authRefreshInFlight=this.performAuth().finally(()=>{this.authRefreshInFlight=null})),this.authRefreshInFlight}async performAuth(){this.hasAuthenticated=!0;let e;try{e=await this.clientAuthenticate()}catch(i){throw new Xc("Client authenticate callback rejected","client",{cause:i})}const t=await this.serverAuthenticate(e.token);if(t.error)throw new Xc("Failed to validate client authenticate response token with UJET server","server");t.auth_token&&this.setAuthToken(t.auth_token);const n=this.decodeJwt(e.token);return this.user={identifier:n.identifier,name:n.name,email:n.email},n.exp&&this.enqueueTokenRefresh(n.exp),this.initLogProxyHandler(t),wu.info("Web SDK authenticated"),this.clientEventManager.triggerEvent("authenticate"),this.clientEventManager.triggerEvent("authenticated"),t.auth_token??""}setAuthToken(e){py(this,Fo,e),py(this,rf,this.readTokenExpiry(e))}readTokenExpiry(e){try{const{exp:t}=this.decodeJwt(e);return typeof t!="number"?0:t.toString().length===13?t:t*1e3}catch{return 0}}onRiskFlags(e){var n;const t=(n=e.result)==null?void 0:n.flags;t&&(this.riskFlags=t,this.clientEventManager.triggerEvent(lO.UPDATED,this.getRiskFlags()))}onMessageFromBridge(e){var n;wu.debug("received message from bridge:",e.data);const t=this.bridgeMessageHandlers[(n=e.data)==null?void 0:n.type];t&&t(e.data)}postMessageToBridge(e){this.channel&&this.channelReady?(wu.debug("sending message to bridge:",e),this.channel.port1.postMessage(e)):this.queuedMessagesToBridge.push(e)}flushQueuedMessagesToBridge(){for(;this.queuedMessagesToBridge.length;){const e=this.queuedMessagesToBridge.shift();this.postMessageToBridge(e)}}postMessageWithCallbackToBridge(e,t){return new Promise((n,i)=>{const s=Rw()+"_"+Date.now();this.pendingBridgeRequests[s]=[n,i];const a={type:e,callbackId:s,data:t};this.postMessageToBridge(a)})}initConfig(e){var l;let t=e.host;t||(e.tenant?t=DE.replace("main.api",e.tenant):t=DE);const n=e.lang||"en",i=!!((l=e.cobrowse)!=null&&l.enabled),a=(e.bridge||"https://websdk.ujet.co/v3/bridge.html")+"?6.25.0",c=/^https:/.test(a)?new URL(a).origin:"*",o=["twilio_chat","nexmo_chat","ujet_chat"];i&&o.push("cobrowse"),this.config={host:t,lang:n,cobrowse:i,companyId:e.companyId,location:location.href,version:e.version||"6.25.0",bridge:a,bridgeOrigin:c,modules:o}}initLogProxyHandler(e){!this.hasInitializedLogProxy&&e.log_proxy_url&&(this.hasInitializedLogProxy=!0,an.addHandler((t,n,...i)=>{if(n==="debug")return;const s=f6(t,n,...i);this.logProxyQueue.push(s)}),this.sendLogsToBridge())}sendLogsToBridge(){this.logProxyQueue.length&&(this.postMessageToBridge({type:"_log",data:{num_of_logs:this.logProxyQueue.length,logs:this.logProxyQueue}}),this.logProxyQueue=[]),setTimeout(()=>{this.sendLogsToBridge()},2e3)}serverAuthenticate(e){return this.postMessageWithCallbackToBridge("_auth",{modules:this.config.modules,user:{token:e,company_id:this.config.companyId}})}enqueueTokenRefresh(e){clearTimeout(this.tokenRefreshTimeout);const t=this.normalizeJwtExp(e),n=Math.max(t-Date.now()-jE,jE);this.tokenRefreshTimeout=setTimeout(()=>{this.onRefreshToken()},n)}decodeJwt(e){const t=e.split(".")[1];return JSON.parse(s6(t))}normalizeJwtExp(e){return e.toString().length===13?e:e.toString().length===10?e*1e3:Date.now()+b6}}Fo=new WeakMap,rf=new WeakMap;const w6=new an("EventManager");class zv{constructor(){be(this,"handlers",{})}addEventListener(e,t){this.handlers[e]||(this.handlers[e]=[]),this.handlers[e].push(t)}triggerEvent(e,t){w6.debug(`event triggered: ${e}`);const n=this.handlers[e];n&&n.forEach(i=>{i(t)})}removeEventListener(e,t){if(this.handlers[e]){const n=this.handlers[e].indexOf(t);n!==-1&&this.handlers[e].splice(n,1)}}destroy(){this.handlers={}}}function T6(r,e){const t={};return e.forEach(n=>{t[n.id]=n}),r.map(n=>{if(n.type===ln.SERVER_MESSAGE){const i=n.server_message_id??n.message_id,s=t[i];dO(n,s.content)}return n})}function C6(r,e){return dO(r,e.content)}function dO(r,e){return Object.keys(e).forEach(t=>{r[t]=e[t]}),r}const BE={photo:2,video:2,audio:1,document:1};function E6(r){return r.toSorted((e,t)=>!e.groupMessageId||!t.groupMessageId||e.groupMessageId!==t.groupMessageId?0:(BE[t.type]||0)-(BE[e.type]||0))}function k6(r){try{const{pathname:e}=new URL(r),t=e.split("/").filter(n=>n.length>0);return t.length>0?decodeURIComponent(t[t.length-1]):"document"}catch{return"document"}}function R6(r,e){r.forEach(t=>{if(t.type==="document"&&t.media_id!=null){const n=e.find(i=>i.media_id===t.media_id);n&&n.url&&(t.document={url:n.url},t.title||(t.title=k6(n.url)))}})}const P6={confirmSessionTitle:"Screen Share Session Request",confirmSessionContent:"Do you want to share your current screen with the agent?",endSessionText:"End Screen Share Session",confirmRemoteControlTitle:"Remote Access Request",confirmRemoteControlContent:"The agent would like to have access to your currently shared screen to further assist you. Do you want to allow this?",confirmFullDeviceTitle:"Screen Share Request",confirmFullDeviceContent:"Do you want to share your full screen with the agent? The agent will not be able to control anything on the screen.",allowText:"Allow",denyText:"Deny"},I6={confirmSessionTitle:"Solicitud de sesión de conavegación",confirmSessionContent:"¿Desea compartir su pantalla actual con el agente?",endSessionText:"Fin de la sesión de conavegación",confirmRemoteControlTitle:"Solicitud de acceso remoto",confirmRemoteControlContent:"El agente desea tener acceso a su pantalla actual compartida para seguir asistiéndole. ¿Desea permitirlo?",confirmFullDeviceTitle:"Solicitud de compartir pantalla",confirmFullDeviceContent:"¿Desea compartir su pantalla completa con el agente? El agente no podrá controlar nada de la pantalla.",allowText:"Permitir",denyText:"Denegar"},A6={confirmSessionTitle:"Demande de session de co-navigation",confirmSessionContent:"Voulez-vous partager votre écran actuel avec l'agent ?",endSessionText:"Terminer la session de co-navigation",confirmRemoteControlTitle:"Demande d'accès à distance",confirmRemoteControlContent:"L'agent souhaite avoir accès à l'écran que vous partagez actuellement pour mieux vous aider. Voulez-vous l'y autoriser ?",confirmFullDeviceTitle:"Demande de partage d'écran",confirmFullDeviceContent:"Voulez-vous partager votre écran complet avec l'agent ? L'agent ne sera pas en mesure de contrôler quoi que ce soit sur l'écran.",allowText:"Autoriser",denyText:"Refuser"},O6={confirmSessionTitle:"Screen Share-Sitzungsanfrage",confirmSessionContent:"Möchten Sie Ihren aktuellen Bildschirm für den Agenten freigeben?",endSessionText:"Screen Share-Sitzung beenden",confirmRemoteControlTitle:"Fernzugriff-Anfrage",confirmRemoteControlContent:"Der Agent möchte Zugriff auf Ihren aktuell freigegebenen Bildschirm erhalten, um Ihnen weiterhelfen zu können. Möchten Sie dies erlauben?",confirmFullDeviceTitle:"Bildschirmfreigabe",confirmFullDeviceContent:"Möchten Sie Ihren gesamten Bildschirm für den Agenten freigeben? Der Agent ist dadurch nicht in der Lage, Elemente auf Ihrem Bildschirm zu steuern.",allowText:"Erlauben",denyText:"Verweigern"},$6={confirmSessionTitle:"共同ブラウジングセッションリクエスト",confirmSessionContent:"現在の画面を担当者と共有したいですか。",endSessionText:"共同ブラウジングセッションを終了",confirmRemoteControlTitle:"リモートアクセスリクエスト",confirmRemoteControlContent:"担当者は、お客様をさらにお手伝いするために、現在共有中の画面へのアクセスを希望しています。許可しますか。",confirmFullDeviceTitle:"画面共有リクエスト",confirmFullDeviceContent:"画面全体を担当者と共有したいですか。担当者は画面上で一切の操作ができません。",allowText:"許可",denyText:"拒否"},x6={confirmSessionTitle:"코브라우징 세션 요청",confirmSessionContent:"현재 화면을 상담원과 공유하시겠습니까?",endSessionText:"코브라우징 세션 종료",confirmRemoteControlTitle:"원격 액세스 요청",confirmRemoteControlContent:"상담원이 추가 지원을 위해 현재 공유된 화면에 액세스할 수 있기를 원합니다. 허용하시겠습니까?",confirmFullDeviceTitle:"화면 공유 요청",confirmFullDeviceContent:"상담원과 전체 화면을 공유하시겠습니까? 상담원은 화면의 어떤 부분도 제어할 수 없습니다.",allowText:"허용",denyText:"거절"},M6={confirmSessionTitle:"Richiesta di sessione di Screen Share",confirmSessionContent:"Vuoi condividere la tua schermata attuale con l'operatore?",endSessionText:"Termina sessione di Screen Share",confirmRemoteControlTitle:"Richiesta di accesso remoto",confirmRemoteControlContent:"L'operatore vorrebbe accedere alla tua schermata attualmente condivisa per assisterti al meglio. Acconsenti?",confirmFullDeviceTitle:"Richiesta di condivisione schermo",confirmFullDeviceContent:"Vuoi condividere il tuo intero schermo con l'operatore? L'operatore non potrà controllare nessun elemento sullo schermo.",allowText:"Consenti",denyText:"Rifiuta"},D6={confirmSessionTitle:"同步浏览会话请求",confirmSessionContent:"您是否要向该客服代表共享当前的屏幕?",endSessionText:"结束同步浏览会话",confirmRemoteControlTitle:"远程访问请求",confirmRemoteControlContent:"为了进一步协助您,客服代表想访问您当前的共享屏幕。您是否允许这样做?",confirmFullDeviceTitle:"屏幕共享请求",confirmFullDeviceContent:"您是否要向该客服代表共享全屏?客服代表将不能控制屏幕上的任何东西。",allowText:"允许",denyText:"拒绝"},N6={confirmSessionTitle:"Samwebbläsningssession har begärts",confirmSessionContent:"Vill du dela din aktuella skärm med vår medarbetare?",endSessionText:"Avsluta samwebbläsningssession",confirmRemoteControlTitle:"Begäran om fjärråtkomst",confirmRemoteControlContent:"Vår medarbetare skulle vilja få åtkomst till skärmen som du delar just nu för att kunna hjälpa dig vidare. Vill du tillåta detta?",confirmFullDeviceTitle:"Begäran om skärmdelning",confirmFullDeviceContent:"Vill du dela hela skärmen med medarbetaren? Medarbetaren kommer inte kunna kontrollera något på skärmen.",allowText:"Tillåt",denyText:"Neka"},L6={confirmSessionTitle:"Solicitação de Sessão de Co-navegação",confirmSessionContent:"Deseja partilhar o seu ecrã atual com o agente?",endSessionText:"Terminar Sessão de Co-navegação",confirmRemoteControlTitle:"Solicitação de Acesso Remoto",confirmRemoteControlContent:"O agente gostaria de ter acesso ao seu ecrã partilhado atualmente para ajudá-lo ainda mais. Quer permitir isto?",confirmFullDeviceTitle:"Solicitação de Partilha de Ecrã",confirmFullDeviceContent:"Deseja partilhar o seu ecrã inteiro com o agente? O agente não poderá controlar nada no ecrã.",allowText:"Permitir",denyText:"Negar"},U6={confirmSessionTitle:"Pyyntö yhteisselausistunnosta",confirmSessionContent:"Haluatko jakaa nykyisen näyttösi edustajan kanssa?",endSessionText:"Lopeta yhteisselausistunto",confirmRemoteControlTitle:"Etäkäyttöpyyntö",confirmRemoteControlContent:"Edustaja haluaisi saada käyttää tällä hetkellä jakamaasi näyttöä voidakseen auttaa sinua enemmän. Haluatko antaa siihen luvan?",confirmFullDeviceTitle:"Näytön jakamispyyntö",confirmFullDeviceContent:"Haluatko jakaa koko näyttösi edustajan kanssa? Edustaja ei pysty käyttämään mitään näytöllä olevaa.",allowText:"Salli",denyText:"Estä"},F6={confirmSessionTitle:"Samlesingsøkten er startet",confirmSessionContent:"Vil du dele skjermen din med agenten?",endSessionText:"Avslutt samlesingsøkt",confirmRemoteControlTitle:"Forespørsel om fjerntilgang",confirmRemoteControlContent:"Agenten vil ha tilgang til skjermen din for å kunne hjelpe deg videre. Vil du tillate dette?",confirmFullDeviceTitle:"Forespørsel om skjermdeling",confirmFullDeviceContent:"Vil du dele hele skjermen din med agenten? Agenten kan ikke kontrollere noe på skjermen.",allowText:"Tillat",denyText:"Avvis"},j6={confirmSessionTitle:"Forespørgsel om sambrowsingsession",confirmSessionContent:"Vil du dele din nuværende skærm med agenten",endSessionText:"Afslut sambrowsingsession",confirmRemoteControlTitle:"Anmodning om fjernadgang",confirmRemoteControlContent:"Agenten vil gerne have adgang til din nuværende delte skærm for at kunne hjælpe dig yderligere. Ønsker du at tillade dette?",confirmFullDeviceTitle:"Forespørgsel om skærmdeling",confirmFullDeviceContent:"Vil du dele din fulde skærm med agenten? Agenten vil ikke kunne styre noget på skærmen",allowText:"Tillad",denyText:"Afvis"},B6={confirmSessionTitle:"Verzoek om cobrowse-sessie",confirmSessionContent:"Wilt u uw huidige scherm delen met de agent?",endSessionText:"Cobrowse-sessie beëindigen",confirmRemoteControlTitle:"Verzoek om toegang op afstand",confirmRemoteControlContent:"De agent wil graag toegang hebben tot uw momenteel gedeelde scherm om u verder te helpen. Wilt u dit toestaan?",confirmFullDeviceTitle:"Verzoek om scherm te delen",confirmFullDeviceContent:"Wilt u uw volledige scherm delen met de agent? De agent kan niets op het scherm bedienen.",allowText:"Toestaan",denyText:"Weigeren"},q6={confirmSessionTitle:"Oturum İsteğini Eş Zamanlı Tara",confirmSessionContent:"Mevcut ekranınızı temsilciyle paylaşmak ister misiniz?",endSessionText:"Eş zamanlı Oturum Taramayı Sonlandır",confirmRemoteControlTitle:"Uzaktan Erişim İsteği",confirmRemoteControlContent:"Temsilci şu anda paylaşılan ekranınıza size daha fazla yardımcı olabilmek için erişim sağlamak istiyor. Buna izin vermek istiyor musunuz?",confirmFullDeviceTitle:"Ekran Paylaşım İsteği",confirmFullDeviceContent:"Temsilciyle tam ekranınızı paylaşmak istiyor musunuz? Temsilci ekrandaki hiçbir şeyi kontrol edemez.",allowText:"İzin Ver",denyText:"Reddet"},W6={confirmSessionTitle:"Yêu cầu phiên cùng duyệt",confirmSessionContent:"Bạn có muốn chia sẻ màn hình hiện tại của mình với chuyên viên không?",endSessionText:"Kết thúc phiên cùng duyệt",confirmRemoteControlTitle:"Yêu cầu truy cập từ xa",confirmRemoteControlContent:"Chuyên viên muốn được cấp quyền truy cập vào màn hình bạn đang chia sẻ để hỗ trợ bạn nhiều hơn. Bạn có muốn cho phép không?",confirmFullDeviceTitle:"Yêu cầu chia sẻ màn hình",confirmFullDeviceContent:"Bạn có muốn chia sẻ toàn bộ màn hình của mình với chuyên viên không? Chuyên viên sẽ không thể điều khiển bất cứ phần nào trên màn hình.",allowText:"Cho phép",denyText:"Từ chối"},V6={confirmSessionTitle:"ขอเซสชันเรียกดูร่วม",confirmSessionContent:"คุณต้องการแชร์หน้าจอปัจจุบันกับตัวแทนหรือไม่",endSessionText:"สิ้นสุดเซสชันเรียกดูร่วม",confirmRemoteControlTitle:"ขอการเข้าถึงระยะไกล",confirmRemoteControlContent:"ตัวแทนต้องการเข้าถึงหน้าจอของคุณที่แชร์อยู่ในปัจจุบันเพื่อให้ความช่วยเหลือคุณต่อไป คุณจะอนุญาตหรือไม่",confirmFullDeviceTitle:"ขอแชร์หน้าจอ",confirmFullDeviceContent:"คุณต้องการแชร์ทั้งหน้าของคุณกับตัวแทนหรือไม่ ตัวแทนจะไม่สามารถควบคุมอะไรบนหน้าจอ",allowText:"ยินยอม",denyText:"ปฏิเสธ"},H6={confirmSessionTitle:"طلب جلسة تصفح مشترك",confirmSessionContent:"هل تريد مشاركة شاشتك الحالية مع الموظف؟",endSessionText:"إنهاء جلسة التصفح المشترك",confirmRemoteControlTitle:"طلب التحكم عن بعد",confirmRemoteControlContent:"يرغب مسئول الدعم في رؤية شاشتك المشاركة حالياً لمساعدتك بشكلٍ أكبر. هل تسمح بذلك؟",confirmFullDeviceTitle:"طلب مشاركة الشاشة",confirmFullDeviceContent:"هل تريد مشاركة شاشتك الكاملة مع مسئول الدعم؟ لن يتمكن المسئول من التحكم في أي شيء على الشاشة.",allowText:"السماح",denyText:"الرفض"},G6={confirmSessionTitle:"Žádost o relaci Screen Share",confirmSessionContent:"Chcete svou současnou obrazovku sdílet s agentem?",endSessionText:"Ukončit relaci Screen Share",confirmRemoteControlTitle:"Žádost o vzdálený přístup",confirmRemoteControlContent:"Agent by rád získal přístup k vaší stávající sdílené obrazovce, aby vám mohl dál pomoci. Chcete mu přístup povolit?",confirmFullDeviceTitle:"Žádost o sdílení obrazovky",confirmFullDeviceContent:"Chcete svou celou obrazovku sdílet s agentem? Agent nebude moci ovládat nic, co na obrazovce je.",allowText:"Povolit",denyText:"Zamítnout"},z6={confirmSessionTitle:"Prośba o sesję Screen Share",confirmSessionContent:"Czy chcesz udostępnić konsultantowi swój bieżący ekran?",endSessionText:"Zakończ sesję Screen Share",confirmRemoteControlTitle:"Prośba o zdalny dostęp",confirmRemoteControlContent:"Konsultant prosi o dostęp do Twojego aktualnie udostępnionego ekranu, aby udzielić Ci dalszej pomocy. Czy chcesz na to zezwolić?",confirmFullDeviceTitle:"Prośba o udostępnienie ekranu",confirmFullDeviceContent:"Czy chcesz udostępnić konsultantowi swój cały ekran? Konsultant nie będzie mógł kontrolować niczego na ekranie.",allowText:"Zezwól",denyText:"Odmów"},K6={confirmSessionTitle:"Screen Share munkameneti kérés",confirmSessionContent:"Megosztja az aktuális képernyőjét a képviselővel?",endSessionText:"Screen Share munkamenet befejezése",confirmRemoteControlTitle:"Távoli hozzáférési kérés",confirmRemoteControlContent:"A képviselő szeretne hozzáférni a jelenleg megosztott képernyőjéhez, hogy további segítséget nyújthasson. Engedélyezi ezt?",confirmFullDeviceTitle:"Képernyőmegosztási kérelem",confirmFullDeviceContent:"Megosztja a teljes képernyőjét az ügynökkel? Az ügynök semmit sem tud majd irányítani a képernyőn.",allowText:"Engedélyezés",denyText:"Elutasítás"},J6={confirmSessionTitle:"Запрос сеанса совместного просмотра веб-страниц",confirmSessionContent:"Хотите поделиться вашим текущим экраном с представителем?",endSessionText:"Завершить сеанс совместного просмотра веб-страниц",confirmRemoteControlTitle:"Запрос на удаленный доступ",confirmRemoteControlContent:"Представитель хочет получить доступ к вашему текущему экрану, которым вы делитесь, чтобы помочь вам. Хотите разрешить это?",confirmFullDeviceTitle:"Запрос на совместный просмотр экрана",confirmFullDeviceContent:"Хотите поделиться вашим полный экраном с представителем? Агент не сможет выполнять никаких действий на экране.",allowText:"Разрешить",denyText:"Отказать"},Y6={confirmSessionTitle:"सह-ब्राउज़ सत्र अनुरोध किया गया",confirmSessionContent:"क्या आप अपनी वर्तमान स्क्रीन को एजेंट के साथ साझा करना चाहते हैं?",endSessionText:"सह-ब्राउज़ सत्र समाप्त करें",confirmRemoteControlTitle:"रिमोट पहुँच का अनुरोध किया गया",confirmRemoteControlContent:"एजेंट आपकी वर्तमान साझा स्क्रीन तक पहुँच प्राप्त करना चाहेगा ताकि वह आपकी और सहायता कर सके। क्या आप इसकी अनुमति देना चाहते हैं?",confirmFullDeviceTitle:"स्क्रीन साझाकरण अनुरोध",confirmFullDeviceContent:"क्या आप अपनी पूरी स्क्रीन एजेंट के साथ साझा करना चाहते हैं? एजेंट स्क्रीन पर कुछ भी नियंत्रित नहीं कर पाएगा।",allowText:"अनुमति दें",denyText:"अस्वीकार करें"},X6={confirmSessionTitle:"Solicitare sesiune de co-navigare",confirmSessionContent:"Doriți să partajați ecranul dumneavoastră curent cu agentul?",endSessionText:"Încheiați sesiunea de co-navigare",confirmRemoteControlTitle:"Cerere de acces la distanță",confirmRemoteControlContent:"Agentul ar dori să aibă acces la ecranul dumneavoastră partajat pentru a vă ajuta în continuare. Doriți să permiteți acest lucru?",confirmFullDeviceTitle:"Cerere de partajare a ecranului",confirmFullDeviceContent:"Doriți să partajați ecranul dumneavoastră complet cu agentul? Agentul nu va putea controla nimic de pe ecran.",allowText:"Permiteți",denyText:"Refuzați"},Q6={confirmSessionTitle:"Zahtjev za sesiju zajedničkog pregledavanja",confirmSessionContent:"Želite li podijeliti svoj trenutni zaslon s agentom?",endSessionText:"Završi sesiju zajedničkog pregledavanja",confirmRemoteControlTitle:"Zahtjev za daljinski pristup",confirmRemoteControlContent:"Agent želi imati pristup vašem trenutno dijeljenom zaslonu kako bi Vam dodatno pomogao. Želite li to dopustiti?",confirmFullDeviceTitle:"Zahtjev za dijeljenje zaslona",confirmFullDeviceContent:"Želite li s agentom podijeliti svoj cijeli zaslon? Agent neće moći ništa kontrolirati na ekranu.",allowText:"Dopustiti",denyText:"Odbiti"},Z6={confirmSessionTitle:"Запит на сесію спільного перегляду",confirmSessionContent:"Чи Ви хочете поділитись з агентом своїм поточним екраном?",endSessionText:"Завершити сесію спільного перегляду",confirmRemoteControlTitle:"Запит на віддалений доступ",confirmRemoteControlContent:"Агент хоче отримати доступ до Вашого поточного екрану, який переглядається спільно, щоб допомогти Вам. Ви дозволяєте?",confirmFullDeviceTitle:"Запит на спільний перегляд екрану",confirmFullDeviceContent:"Чи Ви хочете поділитись з агентом своїм екраном повністю? Агент не зможе нічого на ньому контролювати.",allowText:"Дозволити",denyText:"Відмовити"},eW={confirmSessionTitle:"Kahilingan sa Screen Share na Sesyon",confirmSessionContent:"Gusto mo bang ibahagi ang iyong kasalukuyang screen sa agent?",endSessionText:"Tapusin ang Screen Share na Sesyon",confirmRemoteControlTitle:"Kahilingan sa Remote Access",confirmRemoteControlContent:"Gusto ng agent na magkaroon ng access sa iyong nakabahaging screen sa kasalukuyan upang mas matulungan ka. Gusto mo bang payagan ito?",confirmFullDeviceTitle:"Kahilingan sa Pagbahagi ng Screen",confirmFullDeviceContent:"Gusto mo bang ibahagi ang buong screen sa agent? Hindi makokontrol ng agent ang kahit ano sa screen.",allowText:"Payagan",denyText:"Tanggihan"},ad={en:P6,es:I6,"es-MX":{confirmSessionTitle:"Solicitud de Sesión de Co-navegación",confirmSessionContent:"¿Quiere compartir su pantalla actual con el agente?",endSessionText:"Fin de la sesión de co-navegación",confirmRemoteControlContent:"El agente desea tener acceso a su pantalla actualmente compartida para poder ayudarlo. ¿Quiere permitirlo?",confirmFullDeviceTitle:"Petición de pantalla compartida",confirmFullDeviceContent:"¿Quiere compartir su pantalla completa con el agente? El agente no podrá controlar nada en la pantalla."},fr:A6,"fr-CA":{confirmSessionTitle:"Demande de session co-navigation",confirmSessionContent:"Voulez-vous partager votre écran actuel avec l'agent?",endSessionText:"Fin de la session de co-navigation",confirmRemoteControlContent:"L'agent souhaiterait avoir accès à votre écran actuellement partagé pour mieux vous aider. Voulez-vous l'autoriser?",confirmFullDeviceContent:"Voulez-vous partager votre écran complet avec l'agent? L'agent ne sera pas en mesure de contrôler quoi que ce soit sur l'écran."},de:O6,ja:$6,ko:x6,it:M6,zh:D6,"zh-Hant":{confirmSessionTitle:"共同瀏覽工作階段要求",confirmSessionContent:"要與專員分享您目前的畫面嗎?",endSessionText:"結束共同瀏覽工作階段",confirmRemoteControlTitle:"遠端存取要求",confirmRemoteControlContent:"專員想要存取您目前分享的螢幕畫面以進一步協助您。要允許嗎?",confirmFullDeviceTitle:"螢幕畫面分享要求",confirmFullDeviceContent:"要與專員分享全螢幕嗎?專員將無法控制畫面上的任何項目。",allowText:"允許",denyText:"拒絕"},sv:N6,pt:L6,"pt-BR":{confirmSessionContent:"Você deseja compartilhar sua tela atual com o agente?",endSessionText:"Encerrar Sessão de Co-navegação",confirmRemoteControlContent:"O agente gostaria de acessar sua tela atualmente compartilhada para melhor ajudá-lo. Você deseja permitir isso?",confirmFullDeviceTitle:"Solicitação de Compartilhamento de Tela",confirmFullDeviceContent:"Você deseja compartilhar sua tela inteira com o agente? O agente não poderá controlar nada na tela."},fi:U6,nb:F6,da:j6,nl:B6,tr:q6,vi:W6,th:V6,ar:H6,cs:G6,pl:z6,hu:K6,ru:J6,hi:Y6,ro:X6,hr:Q6,uk:Z6,tl:eW};function tW(r){const e=r.split("-")[0];return ad[r]?r===e?ad[r]:{...ad[e],...ad[r]}:ad[e]}async function rW(r,e,t,n){const i=new FormData;Object.keys(t).forEach(c=>{i.append(c,t[c])}),e instanceof File?i.append("file",e,e.name):e.fileBits&&i.append("file",new File(e.fileBits,e.name,e.options),e.name);const s=await fetch(r,{method:"POST",body:i,signal:n});if(!s.ok)throw new Error(`upload failed: HTTP ${s.status}`);const a=await s.text();return nW(a)}function nW(r){var n,i;const t=(i=(n=new window.DOMParser().parseFromString(r,"text/xml").getElementsByTagName("Key")[0])==null?void 0:n.childNodes[0])==null?void 0:i.nodeValue;if(!t)throw new Error("upload response missing <Key> element");return t}const Rh=new an("chat-originals"),iW="web-4258-local-original-cache",sW=1e3,aW=4,qE=1e4,oW=100;function WE(r){return typeof r=="number"&&Number.isSafeInteger(r)&&r>0}class uW{constructor(){be(this,"byClientMessageId",new Map);be(this,"byRedactionRef",new Map);be(this,"inFlight",new Map);be(this,"queue",[]);be(this,"active",0);be(this,"generation",0)}get currentGeneration(){return this.generation}remember(e,t){!e||!t||Sy(this.byClientMessageId,e,t)}lookup(e){if(typeof e=="string")return this.byClientMessageId.get(e)}forget(e){this.byClientMessageId.delete(e)}lookupFetched(e){return this.byRedactionRef.get(e)}fetch(e,t){const n=this.byRedactionRef.get(e);if(n!==void 0)return Promise.resolve(n);const i=this.inFlight.get(e);if(i)return i;const s=this.generation,a=this.runInSlot(s,()=>{const c=this.call(t,e);return{result:this.withTimeout(c).then(l=>this.settle(s,e,l),l=>(s===this.generation&&(l==null?void 0:l.status)===404?Sy(this.byRedactionRef,e,null):Rh.info("original lookup failed",{redactionRef:e,status:l==null?void 0:l.status}),null)),transport:c}}).finally(()=>{this.inFlight.get(e)===a&&this.inFlight.delete(e)});return this.inFlight.set(e,a),a}invalidate(){this.generation+=1,this.byClientMessageId.clear(),this.byRedactionRef.clear(),this.inFlight.clear();const e=this.queue;this.queue=[],e.forEach(t=>t.cancel())}settle(e,t,n){return e!==this.generation?null:(n==null?void 0:n.redaction_ref)!==t||typeof n.content!="string"?(Rh.warn("original lookup returned an unusable payload",{redactionRef:t}),null):(Sy(this.byRedactionRef,t,n.content),n.content)}call(e,t){try{return Promise.resolve(e(t))}catch(n){return Promise.reject(n)}}runInSlot(e,t){const n=()=>{if(e!==this.generation)return Promise.resolve(null);this.active+=1;const{result:i,transport:s}=t();return s.catch(()=>{}).finally(()=>this.releaseSlot()),i};return this.active<aW?n():this.queue.length>=oW?(Rh.info("original lookup queue full, skipping"),Promise.resolve(null)):new Promise(i=>{const s={start:()=>{clearTimeout(a),i(n())},cancel:()=>{clearTimeout(a),i(null)}},a=setTimeout(()=>{this.queue=this.queue.filter(c=>c!==s),Rh.info("original lookup gave up waiting for a slot"),i(null)},qE);this.queue.push(s)})}releaseSlot(){this.active-=1;const e=this.queue.shift();e&&e.start()}withTimeout(e){return new Promise((t,n)=>{const i=setTimeout(()=>{n(Object.assign(new Error("original lookup timed out"),{code:"TIMEOUT"}))},qE);e.then(s=>{clearTimeout(i),t(s)},s=>{clearTimeout(i),n(s)})})}}function Sy(r,e,t){r.delete(e),r.set(e,t),r.size>sW&&r.delete(r.keys().next().value)}const fO=["assigned","va_assigned"],hO=["dismissed","va_dismissed"],cW=["va_assigned","va_dismissed"],lW=["queued","check_in_timeout",...fO,...hO],dW=["timeout","canceled","failed","finished"],ja=new an("Chat"),fW=Symbol("owner-conflict"),wy=1e3;function hW(r){return typeof WeakRef=="function"?new WeakRef(r):{deref:()=>r}}const pW="web-4206-media-pairing-guard";class vW{constructor(e,t,n={},i){be(this,"provider");be(this,"store");be(this,"globalEvents");be(this,"state");be(this,"connected",!1);be(this,"allowSkipVirtualAgent",!1);be(this,"inEscalation",!1);be(this,"events");be(this,"cachedFiles");be(this,"hooks");be(this,"originals",new uW);be(this,"cacheOwner",null);be(this,"restoredMessages",new Map);be(this,"nextTrackedSweepAt",wy);be(this,"destroying",!1);be(this,"leaveSent",!1);be(this,"beaconAttempted",!1);this.state=e,this.store=new cO,this.cachedFiles={},this.events=new zv,this.hooks=n;const s=g6(this.state.provider_type);this.provider=new s(this.events,e,t,i)}_setGlobalEvents(e,t){this.globalEvents=e,this.on("message",n=>{if(!this.destroying)if(n.content=$b(n.content),this.syncCacheOwner(),n.type===ln.SERVER_MESSAGE){const i=n.server_message_id??n.message_id;t(this.id,i).then(s=>{this.destroying||(n=C6(n,s),e.triggerEvent("chat.message",n))})}else if(n.type==="photo"||n.type==="video"||n.type==="document")setTimeout(()=>{if(this.destroying)return;const i=n.$index.toString();n.file=this.cachedFiles[i],e.triggerEvent("chat.message",n)},100);else{const i=this.restoreOwnOriginal(n);e.triggerEvent("chat.message",n),this.registerMessageEvents(n),i&&this.lookupOwnOriginal(n)}}),this.on("memberJoined",n=>{e.triggerEvent("chat.memberJoined",n)}),this.on("memberLeft",n=>{e.triggerEvent("chat.memberLeft",n)}),this.on("typingStarted",n=>{e.triggerEvent("chat.typingStarted",n)}),this.on("typingEnded",n=>{e.triggerEvent("chat.typingEnded",n)}),this.on("checkInRequired",()=>{e.triggerEvent("chat.checkInRequested")}),this.on("checkInTimedOut",()=>{e.triggerEvent("chat.checkInTimedOut")}),this.on("error",n=>{ja.warn("Chat connection ended",{error:n}),this.handleConnectionEnded()})}handleConnectionEnded(){this.connected&&(this.connected=!1,this.triggerEvent("connectionEnded",this),this.triggerEvent("disconnected",this),this.provider&&this.provider.destroy().catch(e=>ja.warn("provider destroy failed",{error:e})))}get id(){var e;return((e=this.state)==null?void 0:e.id)||-1}get menuId(){return this.state?this.state.menus[this.state.menus.length-1].id:-1}get channelId(){var e;return((e=this.state)==null?void 0:e.provider_channel_id)||""}get lang(){var e;return((e=this.state)==null?void 0:e.lang)||""}get virtual(){return cW.indexOf(this.status)!==-1}get muted(){var e;return((e=this.provider)==null?void 0:e.muted)||!1}set muted(e){this.provider&&(this.provider.muted=e)}get agent(){return this.state?this.virtual?this.state.external_agent||this.state.virtual_agent:this.state.agent||this.state.virtual_agent:null}get allAgents(){var e,t;return{virtual:((e=this.state)==null?void 0:e.all_virtual_agents)||[],human:((t=this.state)==null?void 0:t.all_agents)||[]}}get userIdentity(){var e;return((e=this.provider)==null?void 0:e.identity)||""}get ownUserId(){return this.ownerConflict?null:this.payloadOwnerId??this.providerOwnerId}get ownerConflict(){const e=this.payloadOwnerId,t=this.providerOwnerId;return e!=null&&t!=null&&e!==t}get payloadOwnerId(){var t,n;const e=(n=(t=this.state)==null?void 0:t.end_user)==null?void 0:n.id;return typeof e=="number"&&Number.isFinite(e)?e:null}get providerOwnerId(){const[e,t]=this.userIdentity.split("-"),n=parseInt(t,10);return e===_i.END_USER&&Number.isFinite(n)?n:null}get status(){var e;return((e=this.state)==null?void 0:e.status)||""}get postSessionStatus(){var e;return((e=this.state)==null?void 0:e.post_session_transfer_status)||""}get statusText(){var e;return((e=this.state)==null?void 0:e.status_text)||""}get cobrowsable(){return this.state?this.state.features.indexOf("cobrowse")!==-1:!1}get ongoing(){return lW.indexOf(this.status)!=-1}get assigned(){return fO.indexOf(this.status)!=-1}get dismissed(){return hO.indexOf(this.status)!=-1}get ended(){return dW.indexOf(this.status)!=-1}get transcriptCount(){var e;return((e=this.state)==null?void 0:e.transcript_requested_count)||0}get createdAt(){var e;return((e=this.state)==null?void 0:e.created_at)||""}get inTask(){var e;return((e=this.provider)==null?void 0:e.inTask)||!1}get feedbackType(){var e;return this.state?this.state.survey_enabled?"survey":(e=this.state.csat_settings)!=null&&e.enabled?"rate":"none":"none"}get optInRequired(){var e;return((e=this.state)==null?void 0:e.post_session_opt_in_required)||!1}get postSessionRequired(){var e;return((e=this.state)==null?void 0:e.post_session_required)||!1}get postSessionInProgress(){return this.state?this.state.post_session_transfer_status===ul.IN_PROGRESS:!1}get checkInStatus(){var e;return((e=this.state)==null?void 0:e.check_in_status)??null}set checkInStatus(e){this.state&&(this.state.check_in_status=e)}update(e){if(!this.state||this.state.id!==e.id)return;const t=e.menus[e.menus.length-1].id,n=this.state.menus[this.state.menus.length-1].id;this.state=e,this.syncCacheOwner(),t!==n&&this.triggerEvent("_menuChanged",this),e.status==="canceled"?this.triggerEvent("ended",this):this.triggerEvent("updated",this)}on(e,t){this.events.addEventListener(e,t)}off(e,t){this.events.removeEventListener(e,t)}async connect(){if(!this.provider)return ja.info("connecting interrupted"),!1;try{await ME(()=>this.provider.create(),3),await ME(()=>this.provider.join(this.state.provider_channel_id),3),this.syncCacheOwner(),this.connected=!0;const e=await this.fetchMessages();if(this.destroying)return ja.info("connect abandoned: chat destroyed while loading history"),!1;const t={chat:this,messages:e};return this.triggerEvent("connectedMessages",t),this.triggerEvent("connected",this),this.registerProviderEvents(),ja.info("connected with provider",this.state.provider_type),!0}catch(e){return ja.error("Failed to connect with provider",e),!1}}async disconnect(){this.connected=!1,this.triggerEvent("disconnected",this),await this.sendLeave(),this.events.destroy(),this.provider&&(await this.provider.destroy(),ja.info("disconnect with provider",this.state.provider_type))}async sendLeave(){var e;if(!this.leaveSent&&((e=this.state)==null?void 0:e.provider_type)===Wu.UJET&&this.hooks.leaveChat)try{await this.hooks.leaveChat(),this.leaveSent=!0}catch(t){ja.warn("leaveChat failed",{error:t})}}leaveBeacon(){var e;this.leaveSent||this.beaconAttempted||((e=this.state)==null?void 0:e.provider_type)===Wu.UJET&&this.hooks.leaveChatBeacon&&(this.beaconAttempted=!0,this.hooks.leaveChatBeacon())}resetBeaconState(){this.beaconAttempted=!1}async sendMessage(e,t){var s,a;if(this.ended)throw new av(this.status);const n=await this.provider.sendMessage(e),i=((a=(s=this.hooks).isRiskFlagEnabled)==null?void 0:a.call(s,pW))??!0;return t&&(!i||n!=null&&n!=="")&&this.saveMedia(n,t),typeof n=="number"?n:-1}preview(e){if(!this.inTask)return this.provider.preview(e)}async fetchMessages(){if(this.connected){const e=await this.store.getAllFiles(),t=await this.provider.fetchMessages(e);return this.destroying||!this.state||!this.provider?[]:(this.syncCacheOwner(),t.filter(i=>this.restoreOwnOriginal(i)).forEach(i=>this.lookupOwnOriginal(i)),t)}else throw new Error("Please fetchMessages after chat connected.")}rememberOwnOriginal(e,t){this.destroying||!this.localOriginalCacheEnabled()||(this.syncCacheOwner(),this.originals.remember(e,t))}syncCacheOwner(){if(this.ownerConflict)return this.rebindCacheOwner(fW),null;const e=this.ownUserId;return e==null?typeof this.cacheOwner=="number"?this.cacheOwner:null:(this.rebindCacheOwner(e),e)}rebindCacheOwner(e){e!==this.cacheOwner&&(this.cacheOwner=e,this.revokeOriginals())}revokeOriginals(){this.originals.invalidate();const e=Array.from(this.restoredMessages.values());this.restoredMessages.clear(),this.nextTrackedSweepAt=wy,e.forEach(t=>{const n=t.deref();!n||n.unredacted===void 0||(delete n.unredacted,this.triggerEvent("messageUpdated",n))})}trackRestored(e){const t=hW(e);this.restoredMessages.set(e.$sid||t,t),this.restoredMessages.size>this.nextTrackedSweepAt&&(this.restoredMessages.forEach((n,i)=>{n.deref()===void 0&&this.restoredMessages.delete(i)}),this.nextTrackedSweepAt=Math.max(wy,this.restoredMessages.size*2))}forgetOwnOriginal(e){this.originals.forget(e)}localOriginalCacheEnabled(){var e,t;return((t=(e=this.hooks).isRiskFlagEnabled)==null?void 0:t.call(e,iW))??!0}restoreOwnOriginal(e){if(this.destroying||e.$userType!==_i.END_USER)return!1;const t=this.syncCacheOwner();if(t==null)return this.ownerConflict?(delete e.unredacted,!1):(this.applyOriginal(e,e.unredacted),!1);if(e.$userId!==t)return delete e.unredacted,!1;if(this.localOriginalCacheEnabled()&&this.applyOriginal(e,this.originals.lookup(e.client_message_id))||this.applyOriginal(e,e.unredacted))return!1;const n=e.redaction_ref;if(!WE(n)||!this.hooks.fetchMessageOriginal)return!1;const i=this.originals.lookupFetched(n);return i===null?!1:!this.applyOriginal(e,i)}applyOriginal(e,t){if(t===void 0)return!1;const n=typeof t=="string"&&t?$b(t):"";return n?(e.unredacted=n,this.trackRestored(e),!0):(delete e.unredacted,!1)}lookupOwnOriginal(e){const t=e.redaction_ref,n=this.hooks.fetchMessageOriginal;if(this.destroying||!WE(t)||!n)return;const i=this.id,s=this.syncCacheOwner(),a=this.originals.currentGeneration;this.originals.fetch(t,n).then(c=>{if(!c||this.destroying||!this.state||this.id!==i||this.syncCacheOwner()!==s||a!==this.originals.currentGeneration)return;const o=e.unredacted;!this.applyOriginal(e,c)||e.unredacted===o||this.triggerEvent("messageUpdated",e)}).catch(c=>{ja.warn("original lookup failed",{error:c})})}startTyping(){return this.provider.startTyping()}stopTyping(){return this.provider.stopTyping()}saveMedia(e,t){this.cachedFiles[e.toString()]=t,this.store.save(e,t)}async destroy(){this.destroying=!0,this.originals.invalidate(),this.restoredMessages.clear(),await this.clearMediaStore(),this.connected&&await this.disconnect(),this.provider&&(this.triggerEvent("destroyed"),this.provider=null),this.events.destroy(),this.state=null,this.originals.invalidate(),this.restoredMessages.clear()}async clearMediaStore(){await this.store.clear()}_handleChatEndedEvent(e){this.state&&(this.disconnect(),e.timeout?(this.state.status="timeout",this.triggerEvent("timeout",this)):(this.state.status="finished",this.triggerEvent("ended",this)))}triggerEvent(e,t){this.events.triggerEvent(e,t),this.globalEvents&&this.globalEvents.triggerEvent("chat."+e,t)}registerProviderEvents(){this.provider&&this.provider.registerConversationEvents()}registerMessageEvents(e){switch(e.event){case Gn.COBROWSE_REQUESTED_FROM_AGENT:this.events.triggerEvent("_requestCobrowse","agent");break;case Gn.COBROWSE_REQUESTED_FROM_END_USER:this.events.triggerEvent("_requestCobrowse","end_user");break;case Gn.CHAT_DISMISSED:this.state&&(this.state.status="dismissed",this.triggerEvent("dismissed",this));break;case Gn.CHAT_ENDED:this.events.triggerEvent("_chatEnded",e);break;case Gn.ESCALATION_STARTED:this.inEscalation=!0;break;case Gn.ESCALATION_FAILED:case Gn.ESCALATION_ACCEPTED:this.inEscalation=!1;break;case Gn.CHECK_IN_REQUIRED:this.events.triggerEvent("checkInRequired");break;case Gn.CHECK_IN_TIMED_OUT:this.events.triggerEvent("checkInTimedOut");break}}}const gW=()=>typeof navigator<"u"&&/Android/.test(navigator.userAgent),mW=()=>typeof navigator<"u"&&/Chrome/.test(navigator.userAgent),pO=()=>typeof navigator>"u"?!1:/Android|iPhone|iPad|iPod/.test(navigator.userAgent)?!0:navigator.platform==="MacIntel"&&(navigator.maxTouchPoints??0)>1,Ty=()=>mW()&&!gW();function VE(r){return r.chats=r.chats.map(e=>{const t=e.entries.map((n,i)=>yW(n,`${e.comm_id}-${i}`));return e.entries=E6(t),e}),r}function yW(r,e){var t;return{$index:r.timestamp,$sid:e,$timestamp:new Date(r.timestamp),$userType:r.role,$userId:((t=r.user_data)==null?void 0:t.id)||0,user:r.user_data,type:r.type,...r.body}}const _W={en:"English (US)","en-CA":"English (Canada)","en-GB":"English (UK)",es:"Español (España)","es-MX":"Español (México)",fr:"Français (France)","fr-CA":"Français (Canada)",de:"Deutsch",ja:"日本語",ko:"한국어",it:"Italiano",zh:"中文 (简体)","zh-Hant":"中文 (繁體)",sv:"Svenska",pt:"Português (Portugal)","pt-BR":"Português (Brasil)",fi:"Suomi",nb:"Norsk",da:"Dansk",nl:"Nederlands",tr:"Türk",vi:"Tiếng Việt",th:"คนไทย",ar:"اَلْعَرَبِيَّةُ",cs:"Czech",pl:"Polish",hu:"Hungarian"};function bW(r){var t,n;return{languages:r.languages.filter(i=>i.enabled).map(i=>({lang:i.lang,name:i.name,localeName:_W[i.lang]})),name:r.display_name,subdomain:r.subdomain,support_email:r.support_email,action_tracking:r.action_tracking_enabled,email_transcripts:r.chat_settings.email_transcripts,message_preview:r.chat_settings.message_preview,email_enhancement:r.email_enhancement_enabled,display_history:((t=r.chat_settings.display_history)==null?void 0:t.enabled)&&((n=r.chat_settings.display_history)==null?void 0:n.to_end_user),use_recording:r.use_recording,use_web:r.use_web,cobrowse_domain:r.cobrowse_domain}}function vO(r){return r.map(SW).filter(e=>e.enabled)}function SW(r){const e={id:r.id,enabled:!0,channels:[],hidden:!!r.hidden};if(!r.name||!r.name.trim())return e.enabled=!1,e;e.name=r.name.trim();const t=wW(r);if(t&&(e.redirection=r.redirection),r.children&&r.children.length){const n=vO(r.children);return e.enabled=n.length>0||t,e.children=n,e}if(!r.channels)e.enabled=t;else{const{channels:n,deflection:i}=TW(r.channels);e.deflection=i,t||(e.channels=n),e.enabled=n.length>0||t}return e}function wW(r){let e=!1;const t=r.redirection;return t&&(t.option==="message"||t.option==="url")&&(e=!!t.data),e}function TW(r){let e=null;const t=[],n=r.chat,i=s=>{!s.deflection_type&&s.deflected_reason&&(s.deflection_type=s.deflected_reason),s.deflected===void 0&&s.deflection_type&&(s.deflected=!0),t.push(s)};return n&&n.deflected&&(e={enabled:!0,type:n.deflected_reason}),n&&(n.enabled||n.virtual_agent_available)&&i({...r.chat,type:"chat"}),r.voice_call&&r.voice_call.instant_enabled&&i({...r.voice_call,type:"instant_call"}),r.voice_call&&r.voice_call.schedule_enabled&&i({...r.voice_call,type:"scheduled_call",deflection_type:r.voice_call.schedule_deflection_type}),r.voice_call&&r.voice_call.inbound_enabled&&i({...r.voice_call,type:iv.INBOUND_CALL}),r.voice_call&&r.voice_call.deflected&&r.voice_call.voicemail_reason&&i({...r.voice_call,type:iv.VOICEMAIL,deflection_type:r.voice_call.deflected_reason??r.voice_call.voicemail_reason}),r.email&&r.email.enabled&&i({...r.email,type:"email"}),n&&n.deflected&&n.deflected_reason==="over_capacity"&&n.keep_waiting&&i({...n,enabled:!0,type:"keep_waiting",deflection_type:n.deflected_reason}),r.external_deflection_link&&r.external_deflection_link.enabled&&r.external_deflection_link.links.forEach(a=>{a.enabled&&i({...a,type:"external_link"})}),{channels:t,deflection:e}}const CW="ujet_voice_call",gO="twilio_voice",Kn={STATUS_CHANGED:"voice.statusChanged",RECONNECTING:"voice.reconnecting",RECONNECTED:"voice.reconnected",ERROR:"voice.error",SMART_ACTION_REQUESTED:"voice.smartActionRequested",SMART_ACTION_RESOLVED:"voice.smartActionResolved",COBROWSE_REQUESTED:"voice.cobrowseRequested",COBROWSE_RESOLVED:"voice.cobrowseResolved",RECORDING_PERMISSION_REQUIRED:"voice.recordingPermissionRequired",MIC_PERMISSION_REQUIRED:"voice.micPermissionRequired",CONNECTION_QUALITY:"voice.connectionQuality"},Aw=r=>{var e;if(r&&typeof r=="object"){const t=r;if(typeof((e=t.data)==null?void 0:e.message)=="string")return t.data.message;if(typeof t.message=="string")return t.message}return typeof r=="string"?r:String(r)},EW=(r,e)=>!!r&&typeof r=="object"&&"code"in r&&r.code===e,mO=r=>{if(r&&typeof r=="object"&&"status"in r){const e=r.status;if(typeof e=="number")return e}};class ws extends Error{constructor(t,n,i){super(t,i!==void 0?{cause:i}:void 0);be(this,"code");this.name="VoiceCallError",this.code=n,i!==void 0&&(this.cause=i)}}const Nv=class Nv extends ws{constructor(e="End user has a call in progress"){super(e,Nv.CODE),this.name="CallInProgressError"}};be(Nv,"CODE","CALL_IN_PROGRESS");let Vu=Nv;const Lv=class Lv extends ws{constructor(e="Inbound voice is disabled for this menu"){super(e,Lv.CODE),this.name="InboundDisabledError"}};be(Lv,"CODE","INBOUND_DISABLED");let cl=Lv;const Uv=class Uv extends ws{constructor(e="Outside operation hours"){super(e,Uv.CODE),this.name="OperationHoursError"}};be(Uv,"CODE","OPERATION_HOURS");let Hu=Uv;const Fv=class Fv extends ws{constructor(e="Inbound voice feature is not enabled for this tenant"){super(e,Fv.CODE),this.name="FeatureNotEnabledError"}};be(Fv,"CODE","FEATURE_NOT_ENABLED");let ll=Fv;const jv=class jv extends ws{constructor(e="Microphone permission denied",t){super(e,jv.CODE,t),this.name="MicPermissionDeniedError"}};be(jv,"CODE","MIC_PERMISSION_DENIED");let dl=jv;const Bv=class Bv extends ws{constructor(e="No active voice call"){super(e,Bv.CODE),this.name="NoActiveVoiceCallError"}};be(Bv,"CODE","NO_ACTIVE_VOICE_CALL");let Uo=Bv;const qv=class qv extends ws{constructor(e="A voice call is active in another tab"){super(e,qv.CODE),this.name="AnotherTabVoiceCallError"}};be(qv,"CODE","ANOTHER_TAB_VOICE_CALL");let fl=qv;const Wv=class Wv extends ws{constructor(e,t){super(e,Wv.CODE,t),this.name="ProviderError"}};be(Wv,"CODE","PROVIDER_ERROR");let la=Wv;const Yc=class Yc extends ws{constructor(e,t){super(e,Yc.CODE,t),this.name="SmartActionError"}get isAlreadyEnded(){return this.message===Yc.ENDED_MESSAGE}};be(Yc,"CODE","SMART_ACTION_ERROR"),be(Yc,"ENDED_MESSAGE","smart action is already ended");let ni=Yc;const Vv=class Vv extends ws{constructor(e,t){super(`Unrecognized voice error: ${e}`,Vv.CODE,t),this.name="UnknownVoiceError"}};be(Vv,"CODE","UNKNOWN_VOICE_ERROR");let uv=Vv;const kW=r=>r instanceof Hu||r instanceof cl||r instanceof ll||r instanceof Vu,Ba=new an("BackgroundKeepAlive");class RW{constructor(e={}){be(this,"active",!1);be(this,"currentAgentName",null);be(this,"wakeLock",null);be(this,"audioCtx",null);be(this,"silentSource",null);be(this,"visibilityListener",null);be(this,"pagehideListener",null);be(this,"pageshowListener",null);be(this,"resumeListener",null);be(this,"cleanupInvoked",!1);this.deps=e}async start(e={}){this.active||(this.active=!0,this.currentAgentName=e.agentName??null,this.attachLifecycleListeners(),await this.acquireWakeLock(),this.active&&(this.applyMediaMetadata(),this.startSilentAudioLoop()))}updateAgentName(e){this.active&&this.currentAgentName!==e&&(this.currentAgentName=e,this.applyMediaMetadata())}async stop(){this.active&&(this.active=!1,this.detachLifecycleListeners(),await this.releaseWakeLock(),this.clearMediaSession(),this.stopSilentAudioLoop())}attachLifecycleListeners(){typeof document<"u"&&(this.visibilityListener=()=>{document.visibilityState==="visible"&&this.handleVisible()},document.addEventListener("visibilitychange",this.visibilityListener)),!(typeof window>"u")&&(this.pagehideListener=e=>{e!=null&&e.persisted||this.runCleanupOnce()},window.addEventListener("pagehide",this.pagehideListener),this.pageshowListener=e=>{e!=null&&e.persisted&&this.handleVisible()},window.addEventListener("pageshow",this.pageshowListener),this.resumeListener=()=>this.handleVisible(),window.addEventListener("resume",this.resumeListener))}detachLifecycleListeners(){typeof document<"u"&&this.visibilityListener&&document.removeEventListener("visibilitychange",this.visibilityListener),this.visibilityListener=null,typeof window<"u"&&(this.pagehideListener&&window.removeEventListener("pagehide",this.pagehideListener),this.pageshowListener&&window.removeEventListener("pageshow",this.pageshowListener),this.resumeListener&&window.removeEventListener("resume",this.resumeListener)),this.pagehideListener=null,this.pageshowListener=null,this.resumeListener=null}runCleanupOnce(){var e,t;if(!this.cleanupInvoked){this.cleanupInvoked=!0;try{(t=(e=this.deps).onCleanup)==null||t.call(e)}catch(n){Ba.debug("onCleanup threw during unload",n)}this.stop().catch(n=>Ba.debug("stop() during cleanup failed",n))}}handleVisible(){var e,t;(t=(e=this.audioCtx)==null?void 0:e.resume)==null||t.call(e).catch(n=>Ba.debug("audioCtx.resume failed",n)),this.acquireWakeLock(),this.applyMediaMetadata()}async acquireWakeLock(){if(typeof navigator>"u")return;const e=navigator.wakeLock;if(e!=null&&e.request&&!this.wakeLock)try{this.wakeLock=await e.request("screen")}catch(t){Ba.debug("wakeLock.request failed",t)}}async releaseWakeLock(){if(this.wakeLock){try{await this.wakeLock.release()}catch(e){Ba.debug("wakeLock.release failed",e)}this.wakeLock=null}}applyMediaMetadata(){if(typeof navigator>"u")return;const e=navigator.mediaSession;if(!e)return;const t=globalThis.MediaMetadata;if(typeof t=="function")try{e.metadata=new t({title:this.currentAgentName?`Call with ${this.currentAgentName}`:"Voice call"})}catch(n){Ba.debug("mediaSession.metadata set failed",n)}}clearMediaSession(){if(typeof navigator>"u")return;const e=navigator.mediaSession;if(e)try{e.metadata=null}catch(t){Ba.debug("mediaSession.metadata clear failed",t)}}startSilentAudioLoop(){if(typeof window>"u")return;const e=window.AudioContext||window.webkitAudioContext;if(typeof e=="function")try{this.audioCtx=new e;const t=this.audioCtx.createBuffer(1,1,22050),n=this.audioCtx.createBufferSource();n.buffer=t,n.loop=!0,n.connect(this.audioCtx.destination),n.start(),this.silentSource=n}catch(t){Ba.debug("silent audio loop start failed",t),this.audioCtx=null,this.silentSource=null}}stopSilentAudioLoop(){var e,t,n,i;try{(e=this.silentSource)==null||e.stop()}catch{}try{(t=this.silentSource)==null||t.disconnect()}catch{}this.silentSource=null,(i=(n=this.audioCtx)==null?void 0:n.close)==null||i.call(n).catch(s=>Ba.debug("audioCtx.close failed",s)),this.audioCtx=null}}const ps={CONNECTED:"voice:internal:connected",DISCONNECTED:"voice:internal:disconnected",ERROR:"voice:internal:error"},yO="_provider.messageReceived",Oo={SMART_ACTION_REQUESTED:"smart_action_requested",SMART_ACTION_RESOLVED:"smart_action_resolved",RECORDING_PERMISSION_REQUIRED:"recording_permission_required",STATUS_CHANGED:"status_changed",SMART_ACTION_NOTIFIED:"smart_action_notified",SMART_ACTION_RESPONSE:"smart_action_response",RECORDING_PERMISSION:"recording_permission"},qc=new Set(["finished","failed","canceled","timeout","recovered","voicemail"]),Cy=r=>{switch(r){case"queued":case"assigned":return"queued";case"connecting":case"va_assigned":case"switching":return"connecting";case"connected":case"va_connected":return"connected";case"reconnecting":return"interrupted";case"finished":case"recovered":case"voicemail":case"canceled":case"timeout":return"ended";case"failed":return"error";case"scheduled":return"idle";default:return"error"}};class PW{constructor(e){be(this,"_status");this._status=e}get status(){return this._status}get isTerminal(){return qc.has(this._status)}transitionTo(e){if(this.isTerminal)return null;const t=this._status;return this._status=e,t}}const Ey="ujet:",_r={set(r,e){try{localStorage.setItem(Ey+r,e)}catch{}},get(r){try{return localStorage.getItem(Ey+r)}catch{return null}},del(r){try{localStorage.removeItem(Ey+r)}catch{}}},cv="voice",IW=r=>{_r.set(cv,String(r))},HE=()=>{const r=_r.get(cv);if(!r)return null;const e=Number(r);return Number.isFinite(e)&&e>0?e:(_r.del(cv),null)},Wc=()=>{_r.del(cv)},AW=new Set(["connected","va_connected"]),ky=r=>AW.has(r),OW=new Set(["finished","canceled","expired"]),$W=[Kn.RECONNECTING,Kn.RECONNECTED,Kn.CONNECTION_QUALITY];class xW{constructor(e,t,n,i,s){be(this,"_state");be(this,"_publicState",null);be(this,"events");be(this,"provider");be(this,"methods");be(this,"globalEvents");be(this,"logger");be(this,"destroyed",!1);be(this,"isProviderConnected",!1);be(this,"isUnloading",!1);be(this,"startedAt",null);be(this,"fetchEpoch",0);be(this,"keepAlive",null);be(this,"stateMachine");be(this,"handledSmartActionIds",new Set);be(this,"smartActionQueue",[]);be(this,"currentCobrowseSmartActionId",null);be(this,"recordingPermissionAsked",!1);be(this,"speakerOn",!1);be(this,"cobrowseStarter");this._state=e,this.methods=t,this.events=new zv,this.logger=new an(`VoiceCall:${e.id}`),this.provider=new n(this.events,e,t.issueToken),this.globalEvents=i,this.cobrowseStarter=s,this.stateMachine=new PW(e.status),ky(e.status)&&(this.startedAt=this.resolveStartedAtFromState()),this.registerProviderEvents()}setInternalState(e){this._state=e,this._publicState=null}get state(){if(!this._publicState){const{status:e,...t}=this._state;this._publicState=t}return this._publicState}serverStatus(){return this._state.status}get currentSmartActionId(){return this.smartActionQueue[0]??null}resolveStartedAtFromState(){const t=(this.state.participants??[]).find(n=>(n.type==="agent"||n.type==="virtual_agent")&&n.connected_at);if(t!=null&&t.connected_at){const n=new Date(t.connected_at).getTime();if(!Number.isNaN(n))return n}return Date.now()}setStatus(e,t){if(this.isUnloading)return!1;const n=this.stateMachine.transitionTo(e);if(n===null)return!1;if(this.setInternalState({...this._state,status:e}),this.stateMachine.isTerminal&&Wc(),(t==null?void 0:t.emit)!==!1){const i=(t==null?void 0:t.serverPrev)??n;this.globalEvents.triggerEvent(Kn.STATUS_CHANGED,{id:this.id,status:Cy(e),prevStatus:Cy(i)})}return!0}teardownActiveResources(){this.keepAlive&&(this.keepAlive.stop().catch(e=>this.logger.debug("keepAlive.stop failed",e)),this.keepAlive=null)}get id(){return this.state.id}get status(){return Cy(this._state.status)}get agent(){return this.state.agent??this.state.virtual_agent??null}get duration(){return this.startedAt?Math.floor((Date.now()-this.startedAt)/1e3):0}get feedbackType(){var e;return this.state.survey_enabled?"survey":(e=this.state.csat_settings)!=null&&e.enabled?"rate":"none"}get recordingPermissionRequired(){return this.state.recording_option==="record_ask_user"&&this.state.recording_permission==="recording_permission_not_asked"&&!this.recordingPermissionAsked}async _connect(){var t;if(this.destroyed||this.isProviderConnected)return;if(await this.provider.create(),this.destroyed){await this.provider.destroy().catch(n=>{this.logger.debug("provider.destroy() during _connect race failed",n)});return}this.isProviderConnected=!0,this.recordingPermissionRequired&&this.globalEvents.triggerEvent(Kn.RECORDING_PERMISSION_REQUIRED,{id:this.id});const e=(this.state.smart_actions??[]).filter(n=>!OW.has(n.status));for(const n of e)this.handleSmartActionRequested(n);this.keepAlive=new RW({onCleanup:()=>{this.isUnloading=!0;const n=this._state.status;ky(n)||n==="reconnecting"||Wc();try{this.provider.destroy()}catch{}}}),this.keepAlive.start({agentName:(t=this.agent)==null?void 0:t.name}).catch(n=>{this.logger.warn("background keep-alive start failed",n)})}_markUnloading(){this.isUnloading=!0}async _abandonOrFinish(){if(this.stateMachine.isTerminal)return;this.teardownActiveResources();const e=ky(this._state.status);if(this.isProviderConnected)try{await this.provider.hangup()}catch(t){this.logger.warn("provider hangup failed",t)}try{!e&&this.methods.failCall?await this.methods.failCall(this.id,"abandoned"):this.methods.finishCall&&await this.methods.finishCall(this.id)}catch(t){this.logger.warn("server-side hangup failed",t)}this.setStatus("finished",{emit:!this.isProviderConnected})}async _destroy(){this.destroyed||(this.destroyed=!0,this.teardownActiveResources(),await this._abandonOrFinish().catch(e=>this.logger.warn("hangup during destroy failed",e)),await this.provider.destroy(),this.events.destroy())}mute(e){this.destroyed||this.isMuted()!==e&&this.provider.mute(e)}isMuted(){return this.provider.isMuted()}getRemoteAudioStream(){return this.destroyed?null:this.provider.getRemoteStream()}isSpeakerSupported(){return this.destroyed?!1:this.provider.isOutputSelectionSupported()}isSpeakerOn(){return this.speakerOn}async setSpeakerOn(e){if(!this.destroyed){if(!this.provider.isOutputSelectionSupported()){this.speakerOn=e;return}if(e){const t=this.provider.getAvailableOutputDevices().find(n=>/speaker|loud|external/i.test(n.label));if(!t)throw new la("no loudspeaker output available");await this.provider.setOutputDevice(t.deviceId)}else await this.provider.setOutputDevice("default");this.speakerOn=e}}async _escalate(){this.methods.escalateCall&&await this.methods.escalateCall(this.id)}async grantRecording(){this.recordingPermissionAsked=!0,!this.sendProviderMessage(Oo.RECORDING_PERMISSION,{granted:!0})&&this.methods.updateRecordingPermission&&await this.methods.updateRecordingPermission(this.id,!0)}async denyRecording(){this.recordingPermissionAsked=!0,!this.sendProviderMessage(Oo.RECORDING_PERMISSION,{granted:!1})&&this.methods.updateRecordingPermission&&await this.methods.updateRecordingPermission(this.id,!1)}async startCobrowse(e,t="end_user"){return this.cobrowseStarter(e??this.state.lang,t)}async submitTextSmartAction(e,t){await this.resolveSmartAction(e,{status:"finished",data:{text:t}})}async confirmVerificationSmartAction(e){await this.resolveSmartAction(e,{status:"finished"})}async cancelSmartAction(e){await this.resolveSmartAction(e,{status:"canceled"})}async uploadMediaForSmartAction(e,t,n){if(n==="video"){if(!this.methods.uploadVideos)throw new ni("uploadVideos not configured");await this.methods.uploadVideos(this.id,t,e)}else{if(!this.methods.uploadPhotos)throw new ni("uploadPhotos not configured");await this.methods.uploadPhotos(this.id,t,n,e)}this.markSmartActionHandled(e)}async prepareMediaUpload(e,t,n){if(this.destroyed)throw new ni("call destroyed");if(t==="video"){if(!this.methods.uploadOneVideo)throw new ni("uploadOneVideo not configured");return{ref:await this.methods.uploadOneVideo(this.id,e,n),kind:t}}if(!this.methods.uploadOnePhoto)throw new ni("uploadOnePhoto not configured");return{ref:await this.methods.uploadOnePhoto(this.id,e,n),kind:t}}async submitMediaRefsForSmartAction(e,t,n){if(this.destroyed)throw new ni("call destroyed");if(n.length===0)throw new ni("submitMediaRefsForSmartAction called with empty refs");const i=n.find(a=>a.kind!==t);if(i)throw new ni(`media ref kind '${i.kind}' does not match SmartAction type '${t}'`);const s=n.map(a=>a.ref);if(t==="video"){if(!this.methods.registerVideos)throw new ni("registerVideos not configured");await this.methods.registerVideos(this.id,s,e)}else{if(!this.methods.registerPhotos)throw new ni("registerPhotos not configured");await this.methods.registerPhotos(this.id,t,s,e)}this.markSmartActionHandled(e)}registerProviderEvents(){this.events.addEventListener(ps.CONNECTED,async()=>{this.destroyed||(await this.fetchAndUpdateState(),!(this.destroyed||this._state.status==="finished")&&(this.startedAt=this.resolveStartedAtFromState()))}),this.events.addEventListener(ps.DISCONNECTED,()=>{this.destroyed||this.stateMachine.isTerminal||(this.isProviderConnected=!1,this.setStatus("finished"),this.fetchAndUpdateState())}),this.events.addEventListener(ps.ERROR,e=>{this.destroyed||this.stateMachine.isTerminal||(this.logger.warn("provider reported a fatal error",e),this.isProviderConnected=!1,this.teardownActiveResources(),this.globalEvents.triggerEvent(Kn.ERROR,{id:this.id,error:e==null?void 0:e.error}),this.setStatus("failed"))});for(const e of $W)this.events.addEventListener(e,t=>{this.globalEvents.triggerEvent(e,t)});this.events.addEventListener(yO,e=>{this.handleProviderMessage(e)})}async fetchAndUpdateState(){const e=++this.fetchEpoch;try{const t=await this.methods.fetchCall(this.id);if(e!==this.fetchEpoch||this.destroyed)return;this.setInternalState({...this._state,...t,status:this._state.status})}catch(t){this.logger.warn("on-demand fetchCall failed",t)}}handleProviderMessage(e){if(this.destroyed||this.isUnloading)return;const{type:t,data:n={}}=e;switch(t){case Oo.SMART_ACTION_REQUESTED:this.handleSmartActionRequested(n.smart_action);break;case Oo.SMART_ACTION_RESOLVED:this.handleSmartActionResolved(n);break;case Oo.RECORDING_PERMISSION_REQUIRED:if(this.recordingPermissionAsked)break;this.globalEvents.triggerEvent(Kn.RECORDING_PERMISSION_REQUIRED,{id:this.id});break;case Oo.STATUS_CHANGED:this.handleStatusChanged(n);break;default:this.logger.debug("unhandled provider message type",t)}}handleSmartActionRequested(e){if(!e||this.handledSmartActionIds.has(e.id))return;if(e.type==="cobrowse"){if(this.currentCobrowseSmartActionId===e.id)return;this.currentCobrowseSmartActionId=e.id,this.globalEvents.triggerEvent(Kn.COBROWSE_REQUESTED,{smartAction:e})}else{if(this.smartActionQueue.includes(e.id))return;this.smartActionQueue.push(e.id),this.globalEvents.triggerEvent(Kn.SMART_ACTION_REQUESTED,{smartAction:e})}this.sendProviderMessage(Oo.SMART_ACTION_NOTIFIED,{smart_action_id:e.id})}handleSmartActionResolved(e){const t=e.smart_action_id;t&&(this.smartActionQueue.includes(t)&&this.globalEvents.triggerEvent(Kn.SMART_ACTION_RESOLVED,{smartActionId:t}),this.currentCobrowseSmartActionId===t&&(this.currentCobrowseSmartActionId=null,this.globalEvents.triggerEvent(Kn.COBROWSE_RESOLVED,{smartActionId:t})),this.markSmartActionHandled(t))}handleStatusChanged(e){var n,i,s;if(!e.status||this.stateMachine.isTerminal)return;if(this.fetchEpoch++,(e.agent||e.virtual_agent)&&this.setInternalState({...this._state,...e.agent&&{agent:e.agent},...e.virtual_agent&&{virtual_agent:e.virtual_agent}}),!qc.has(e.status)){const a=((n=this._state.agent)==null?void 0:n.name)??((i=this._state.virtual_agent)==null?void 0:i.name)??null;(s=this.keepAlive)==null||s.updateAgentName(a),e.status==="connected"&&this.fetchAndUpdateState().then(()=>{this.destroyed||this._state.status!=="connected"||(this.startedAt=this.resolveStartedAtFromState())})}this.setStatus(e.status,{serverPrev:e.prev_status})}sendProviderMessage(e,t){return this.provider.sendMessage({type:e,data:t})!==null}markSmartActionHandled(e){this.handledSmartActionIds.add(e);const t=this.smartActionQueue.indexOf(e);t>=0&&this.smartActionQueue.splice(t,1)}async resolveSmartAction(e,t){if(this.sendProviderMessage(Oo.SMART_ACTION_RESPONSE,{smart_action_id:e,status:t.status,data:t.data,fail_reason:t.fail_reason})){this.markSmartActionHandled(e);return}if(!this.methods.updateSmartAction)throw new ni("updateSmartAction not configured");try{await this.methods.updateSmartAction(this.id,e,t),this.markSmartActionHandled(e)}catch(n){const i=Aw(n);if(i===ni.ENDED_MESSAGE){this.markSmartActionHandled(e);return}throw new ni(i,n)}}}class Ow{constructor(e,t,n){be(this,"events");be(this,"state");be(this,"issueVoiceToken");this.events=e,this.state=t,this.issueVoiceToken=n}getRemoteStream(){return null}sendMessage(e){return null}}be(Ow,"type","base");const _O={},bO=r=>{_O[r.type]=r},SO=r=>_O[r],Ph=new an("methods"),GE=!0,MW="web-4191-refresh-unknown-chat-agent";class DW{constructor(e,t,n,i){be(this,"request");be(this,"lastDapRequestId",null);be(this,"lastDirectAccessKeyId",null);be(this,"dapPollGeneration",0);be(this,"beaconLeaveChat");be(this,"authContext");be(this,"isRiskFlagEnabled");be(this,"getCustomFormData",async e=>{const t=`forms/${e}/details`;try{return await this.get(t)}catch(n){Ph.error(`Error fetching form data:, ${n}`)}});this.request=e,this.beaconLeaveChat=t,this.authContext=n,this.isRiskFlagEnabled=i}get(e,t){if(t){const n=[];Object.keys(t).forEach(i=>{const s=t[i];s!==void 0&&n.push(`${encodeURIComponent(i)}=${encodeURIComponent(s)}`)}),e+="?"+n.join("&")}return this.request(e,{method:"GET"})}post(e,t){const n={method:"POST"};return n.body=JSON.stringify(t),this.request(e,n)}patch(e,t){const n={method:"PATCH"};return n.body=JSON.stringify(t),this.request(e,n)}put(e,t){const n={method:"PUT"};return n.body=JSON.stringify(t),this.request(e,n)}async getTriggers(e){const t={"UJET-Company-Id":e};return(await this.request("proactive_chat_triggers",{method:"GET",headers:t})).data}submitCustomForm(e){return this.post("forms/submit",e)}async trackClientEvents(e){return await this.post("/client_events",{events:e})}async getCompany(){const e=await this.get("company");return bW(e.data)}async getFeatureFlags(){return(await this.get("feature_flags")).data}async getMenus(e,t,n){const i=this.dapPollGeneration,s={type:"web_menu",lang:e,direct_access_key:t};n!=null&&n.initialMessage&&(s.initial_message=n.initialMessage),n!=null&&n.signedCustomData&&(s.custom_data_signed=n.signedCustomData),n!=null&&n.customData&&(s.custom_data_unsigned=n.customData);let a=await this.post("menus",s);this.stashDapRequestId(a),this.isChatDapPending(a.data)&&(a=await this.pollChatDap(e,Number(a.data.max_timeout)||0,i));const c=a.headers["ujet-direct-access"],l={key:!!t,user:!!c&&c!=="false",key_id:null},d=a.headers["ujet-direct-access-key-id"];if(d){const y=Number(d);Number.isFinite(y)&&(l.key_id=y)}this.lastDirectAccessKeyId=l.key_id;let h=[];return Array.isArray(a.data)?h=a.data:Ph.warn("unexpected /menus response shape; rendering an empty menu list"),{menus:vO(h),direct:l}}stashDapRequestId(e){const t=e.headers["ujet-dap-request-id"];this.lastDapRequestId=typeof t=="string"&&t?t:null}isChatDapPending(e){return e&&!Array.isArray(e)&&e.status==="PENDING"}cancelDapPolling(){this.dapPollGeneration++}fetchRootMenus(e){return this.get("menus",{type:"web_menu",lang:e})}async pollChatDap(e,t,n){const i=this.lastDapRequestId;if(!i)return Ph.warn("chat DAP pending response missing dap_request_id; falling back to root menus"),await this.fetchRootMenus(e);const s=2e3,a=Math.max(t,0)*1e3;let c=0;for(;c<a;){if(await sv(s),c+=s,this.dapPollGeneration!==n)return{headers:{},data:[]};const o=await this.get("menus",{type:"web_menu",lang:e,dap_request_id:i});if(!this.isChatDapPending(o.data))return o}return await this.fetchRootMenus(e)}async getAfterHourMessage(e){return(await this.get(`audible_messages/${e}`)).data["after_hours.message"].text}async getTimeSlots(e,t={}){const n=t.lang||"en",i=t.rescheduleCallId;return(await this.get(`menus/${e}/time_slots`,{type:"web_menu",lang:n,reschedule_call_id:i,use_advanced_call_scheduling:GE})).data}async fetchTimeSlotAvailability(e,t="en"){return(await this.get(`menus/${e}/time_slots_available`,{type:"web_menu",lang:t})).data.slots_available}async getWaitTimes(e,t="en"){return(await this.get(`menus/${e}/wait_times`,{type:"web_menu",lang:t})).data}async verifyForm(e){try{return await this.post("forms/verify",e),!0}catch{return!1}}async finishChat(e){return(await this.patch(`chats/${e}`,{status:"finished"})).data}async fetchUjetConversationMessages(e,t={}){return(await this.get(`chats/${e}/ujet_conversation/messages`,{limit:t.limit,before:t.before})).data}async leaveChat(e){await this.post(`chats/${e}/leave`,{})}leaveChatBeacon(e){var t;(t=this.beaconLeaveChat)==null||t.call(this,e)}async updatePostSession(e,t,n){const i={post_session_transfer_status:t};n!==void 0&&(i.post_session_opt_in_selection=n);try{return(await this.patch(`chats/${e}`,i)).data}catch(s){if(t===ul.IN_PROGRESS&&s.status===400)return(await this.patch(`chats/${e}`,i)).data;throw s}}async getChatDeflection(e){const{data:t}=await this.get(`chats/${e}/deflections`);return t&&t.enabled?t:null}sendChatCustomData(e,t){let n;return typeof t=="string"?n={signed:!0,signed_data:t}:n={signed:!1,data:t},this.post(`chats/${e}/custom_data`,n)}async downloadChatTranscript(e){return(await this.post(`chats/${e}/generate_transcript_pdf`,{})).data}async getPdfStatus(e){return await this.get(`chat_transcript_pdfs/${e}/download_transcript`)}async sendChatTranscripts(e,t){return await this.post(`chats/${e}/transcripts`,{emails:t.join(",")})}async listChatTaskMessages(e){return(await this.get(`chats/${e}/task_va_messages`)).data}async getChatTaskMessage(e,t){return(await this.get(`chats/${e}/task_va_messages/${t}`)).data}async sendChatTaskMessage(e,t){const n={content:{content:t,type:"text"}};return(await this.post(`chats/${e}/task_va_messages`,n)).data}async sendChatTextMessage(e,t,n){const i={message:{content:t,timestamp:new Date().toISOString()}};n&&(i.message.client_message_id=n),await this.post(`chats/${e}/messages`,i)}async getChatMessageOriginal(e,t){return(await this.get(`chats/${e}/messages/${t}/original`)).data}async sendPreviewMessage(e,t,n){const i={message:{content:t,timestamp:n}},{data:s}=await this.post(`chats/${e}/redact_messages`,i);return s}escalateChat(e,t){return this.post(`chats/${e}/escalations`,t)}trackEscalation(e,t,n){return this.put(`chats/${e}/escalations/${t}`,{escalation_id:t,deflection_channel:n})}requestChatCobrowse(e,t){return this.post(`chats/${e}/cobrowse`,t)}requestVoiceCallCobrowse(e,t){return this.post(`calls/${e}/cobrowse`,t)}rateChat(e,t){return this.patch(`chats/${e}/rating`,t)}async getChatSurvey(e){return(await this.get(`chats/${e}/survey`)).data}sendChatSurvey(e,t){const n={chat_id:e,answers:t};return this.put(`chats/${e}/survey`,n)}trackChatEndUserEvent(e,t){return this.post(`chats/${e}/end_user_event`,t)}async createChat(e,t,n,i){const s={menu_id:e,lang:t,email:n.email,greeting:n.greeting,trigger_id:n.trigger_id,ticket_id:n.ticket_id,custom_data:n.custom_data};this.lastDirectAccessKeyId!==null&&(s.direct_access_key_id=this.lastDirectAccessKeyId),this.lastDapRequestId&&(s.dap_request_id=this.lastDapRequestId);const a={chat:s,cobrowsable:n.cobrowsable},c=await this.post("chats",a);this.lastDapRequestId=null;const o=c.data;return this.wrapChat(o,i)}async loadChat(e,t){const n=await this.getChat(e);return this.wrapChat(n,t)}async resumeChat(e,t){const n=await this.patch(`chats/${e}`,{status:"queued"});return this.wrapChat(n.data,t)}async getChatHistory(e=1){if(e===1){const{data:t}=await this.get("/chats/histories?page=1&per_page=2");return VE(t)}else{const{data:t}=await this.get(`/chats/histories?page=${e}&per_page=1`);return VE(t)}}async uploadChatFile(e,t){let n="file";/^image/.test(t.type)?n="photo":/^video/.test(t.type)?n="video":t.type==="application/pdf"&&(n="document");const i=t.name.replace(/\.[^.]+$/i,""),s=await this.post(`chats/${e}/${n}s/upload`,{filename:i}),a={file:t,fields:s.data.fields};Ty()&&(a.file=await xb(t));const o=(await this.request(s.data.url,a)).data.key,d=(await this.post(`chats/${e}/${n}s`,{chat_id:e,[n]:{s3_path:o,photo_type:n,filename:t.name,content_type:t.type,file_size:t.size}})).data;return d.type=n,d}buildProviderContext(e){if(this.authContext)return{getAuthToken:this.authContext.getAuthToken,wsUrl:this.authContext.wsUrl,fetchHistory:t=>this.fetchUjetConversationMessages(e,t)}}async getChat(e){return(await this.get(`chats/${e}`)).data}async wrapChat(e,t){const n=async()=>(await this.post(`chats/${e.id}/tokens`,{provider_type:e.provider_type,device_id:t})).data,i=()=>this.leaveChat(e.id),s=()=>this.leaveChatBeacon(e.id),a=d=>this.getChatMessageOriginal(e.id,d),c=new vW(e,n,{leaveChat:i,leaveChatBeacon:s,isRiskFlagEnabled:this.isRiskFlagEnabled,fetchMessageOriginal:a},this.buildProviderContext(e.id)),o=async d=>{if(c.status==="va_assigned"){const h=await this.getSkipVirtualAgentSettings(c.menuId,c.lang);c.allowSkipVirtualAgent=h,c.update(d)}};c.on("initialized",async()=>{if(c.status==="queued"){const d=await this.getChat(c.id);c.update(d)}}),c.on("memberJoined",async()=>{const d=await this.getChat(c.id);c.update(d)}),c.on("memberLeft",async()=>{const d=await this.getChat(c.id);c.update(d)});let l=!1;if(c.on("message",d=>{var h;!c.connected||!c.ongoing||l||d.$userType!==_i.USER||!Number.isSafeInteger(d.$userId)||d.$userId<=0||c.allAgents.human.some(v=>v.id===d.$userId)||((h=this.isRiskFlagEnabled)==null?void 0:h.call(this,MW))===!1||(l=!0,this.getChat(c.id).then(v=>{c.connected&&c.ongoing&&c.update(v)}).catch(()=>{Ph.warn("Unable to refresh chat agents after an unknown human message")}).finally(()=>{l=!1}))}),c.on("_chatEnded",async d=>{const h=await this.getChat(c.id);c.update(h),(!c.state||c.ended)&&c._handleChatEndedEvent(d)}),c.on("_menuChanged",async d=>{const h=await this.getChat(d.id);o(h)}),c.on("checkInRequired",async()=>{const d=await this.getChat(c.id);c.update(d)}),c.on("checkInTimedOut",async()=>{const d=await this.getChat(c.id);c.update(d)}),c.channelId)c.connect(),o(e);else{let d;for(;!d;)await this.getChat(c.id).then(h=>{h.provider_channel_id&&c.state?(d=!0,c.update(h),c.connect(),o(h)):(h.status==="canceled"||h.status==="finished")&&(d=!0)}),d||await sv(1500)}return c}async createVoiceCall(e,t,n,i,s,a){const c={call:{type:"web_inbound_call",menu_id:e,lang:t,email:n.email,ticket_id:n.ticket_id,recording_permission:n.recording_permission,custom_data:n.custom_data,voicemail_reason:n.voicemail_reason},cobrowsable:n.cobrowsable??!1},o=await this.post("calls",c);return this.wrapVoiceCall(o.data,i,s,a)}async requestVoiceToken(e,t){return(await this.post(`calls/${e}/tokens`,{device_id:t})).data}async fetchVoiceCall(e){return(await this.get(`calls/${e}`)).data}async hangupVoiceCall(e){await this.patch(`calls/${e}`,{status:"finished"})}async failVoiceCall(e,t="abandoned",n){await this.patch(`calls/${e}`,{status:"failed",fail_reason:t,fail_details:n})}async updateVoiceCallRecordingPermission(e,t){await this.patch(`calls/${e}`,{recording_permission:t?"recording_permission_granted":"recording_permission_denied"})}async escalateVoiceCall(e){await this.post(`calls/${e}/escalate`,{})}rateVoiceCall(e,t){return this.put(`calls/${e}/rating`,t)}async getVoiceCallSurvey(e){return(await this.get(`calls/${e}/survey`)).data}submitVoiceCallSurvey(e,t){const n={call_id:e,answers:t};return this.put(`calls/${e}/survey`,n)}async updateVoiceSmartAction(e,t,n){await this.put(`calls/${e}/smart_actions/${t}`,n)}async uploadVoiceCallPhotoSingle(e,t,n){return await this.uploadFileToExternalStorage(`calls/${e}/photos/upload`,t,n)}async registerVoiceCallPhotos(e,t,n,i){const s=n.map(c=>({s3_path:c,photo_type:t}));return((await this.post(`calls/${e}/photos`,{photo:s,photo_type:t,multiple:!0,smart_action_id:i})).data||[]).map(c=>c.media_id)}async uploadVoiceCallPhotos(e,t,n,i){const s=await Promise.all(t.map(a=>this.uploadVoiceCallPhotoSingle(e,a)));return await this.registerVoiceCallPhotos(e,n,s,i)}async uploadVoiceCallVideoSingle(e,t,n){return await this.uploadFileToExternalStorage(`calls/${e}/videos/upload`,t,n)}async registerVoiceCallVideos(e,t,n){return await Promise.all(t.map(async i=>(await this.post(`calls/${e}/videos`,{video:{s3_path:i},smart_action_id:n})).data.media_id))}async uploadVoiceCallVideos(e,t,n){const i=await Promise.all(t.map(s=>this.uploadVoiceCallVideoSingle(e,s)));return await this.registerVoiceCallVideos(e,i,n)}async uploadFileToExternalStorage(e,t,n){const i=t.name.replace(/\.[^.]+$/i,""),s=await this.post(e,{filename:i});if(pO())return await rW(s.data.url,t,s.data.fields,n);const a={file:t,fields:s.data.fields};return Ty()&&(a.file=await xb(t)),(await this.request(s.data.url,a)).data.key}async _wrapVoiceCallForRestore(e,t,n,i){return this.wrapVoiceCall(e,t,n,i)}async wrapVoiceCall(e,t,n,i){const s=async()=>await this.requestVoiceToken(e.id,t),a=async L=>await this.fetchVoiceCall(L),c=async L=>await this.hangupVoiceCall(L),o=async(L,x,B)=>await this.failVoiceCall(L,x,B),l=async L=>await this.escalateVoiceCall(L),d=async(L,x)=>await this.updateVoiceCallRecordingPermission(L,x),h=async(L,x,B)=>await this.updateVoiceSmartAction(L,x,B),v=async(L,x,B,G)=>{await this.uploadVoiceCallPhotos(L,x,B,G)},y=async(L,x,B)=>{await this.uploadVoiceCallVideos(L,x,B)},w=async(L,x,B)=>await this.uploadVoiceCallPhotoSingle(L,x,B),k=async(L,x,B)=>await this.uploadVoiceCallVideoSingle(L,x,B),I=async(L,x,B,G)=>{await this.registerVoiceCallPhotos(L,x,B,G)},A=async(L,x,B)=>{await this.registerVoiceCallVideos(L,x,B)},j=SO(this.resolveVoiceProviderType(e));if(!j)throw new la(`No voice provider registered for ${e.voip_provider}`);return new xW(e,{issueToken:s,fetchCall:a,finishCall:c,failCall:o,escalateCall:l,updateRecordingPermission:d,updateSmartAction:h,uploadPhotos:v,uploadVideos:y,uploadOnePhoto:w,uploadOneVideo:k,registerPhotos:I,registerVideos:A},j,n,i)}resolveVoiceProviderType(e){return e.voip_provider==="voip_provider_twilio"?gO:e.voip_provider}async createCall(e,t){const n={type:t.scheduled_at?"web_scheduled_call":"web_instant_call",menu_id:e,lang:t.lang,email:t.email,ticket_id:t.ticket_id,recording_permission:t.recording_permission||"recording_permission_not_asked",scheduled_at:t.scheduled_at,custom_data:t.custom_data,end_user:{phone_number:t.phone_number}},s=(await this.post("calls",{call:n,cobrowsable:!1,use_advanced_call_scheduling:GE,reschedule_call_id:t.reschedule_call_id})).data,{selected_menu:a,...c}=s;return{...c,menu_id:a.id}}async fetchCall(e){const n=(await this.get(`calls/${e}`)).data,{selected_menu:i,...s}=n;return{...s,menu_id:i.id}}async cancelCall(e){const n=(await this.patch(`calls/${e}`,{status:"failed",fail_reason:"canceled"})).data,{selected_menu:i,...s}=n;return{...s,menu_id:i.id}}async listFileTypes(){return(await this.get("email_prohibited_file_types")).data}async createEmail(e,t,n){const i={end_user_email:n.email,email_body:n.content,menu_id:e.toString(),lang:t};return n.name&&(i.end_user_name=n.name),n.recaptcha&&(i.recaptcha_response=n.recaptcha),n.files&&Ty()?i["email_attachments[]"]=await NW(n.files):n.files&&(i["email_attachments[]"]=[...n.files]),(await this.request("emails",{form:i})).data}async getMedia(e,t){const n=await this.get(`media/${e}?type=${t}`);if(!n.data)return null;const i=n.headers["x-file-name"];return new File([n.data],i,{type:n.data.type})}async getChatDocuments(e){const t=await this.get(`chats/${e}/documents`);return Array.isArray(t.data)?t.data:[]}async getSkipVirtualAgentSettings(e,t){return(await this.get(`menus/${e}/virtual_agent_settings`,{lang:t})).data.allow_skip_virtual_agent}async confirmCheckIn(e){return(await this.post(`chats/${e}/check_in/confirm`,null)).data}async rejoinQueue(e){return(await this.post(`chats/${e}/check_in/rejoin`,null)).data}async exitCheckIn(e){return(await this.post(`chats/${e}/check_in/exit`,null)).data}async trackCheckIn(e,t){await this.post(`chats/${e}/check_in/modal_shown`,t)}async notifyCheckInState(e,t){await this.post(`chats/${e}/check_in/end_user_status`,t)}}function NW(r){return Promise.all(r.map(xb))}function xb(r){return new Promise((e,t)=>{const n=new FileReader;n.onload=()=>{const i=[n.result],s={type:r.type,lastModified:r.lastModified};e({name:r.name,fileBits:i,options:s})},n.onerror=t,n.readAsArrayBuffer(r)})}const wO=new an("CobrowseService");async function LW(r){return window.CobrowseIO?window.CobrowseIO:await UW(r)}async function UW(r){return new Promise(e=>{const t=document.createElement("script");t.src=r,t.async=!0;const n=document.getElementsByTagName("script")[0];n.parentNode.insertBefore(t,n),t.onload=function(){e(window.CobrowseIO)},t.onerror=function(){wO.error("Failed to load cobrowse script",r),e(null)}})}const zE="https://js.cobrowse.io/CobrowseIO.js";function FW(r){return!r||r.toLowerCase()==="https://cobrowse.io"?zE:r.toLowerCase().startsWith("https://")?`${r}/sdk-js/CobrowseIO.js`:(wO.warn("customCobrowseDomain must use HTTPS; falling back to default",{cobrowseDomain:r}),zE)}async function jW(r,e){let t=r.instance;if(!t){const n=FW(e);t=await LW(n)}return new BW(t,r)}class BW{constructor(e,t){be(this,"_cobrowseIO");if(this._cobrowseIO=e,!e)return;e.license=t.license;const n=t.trustedOrigins||[];n.push(location.origin),e.trustedOrigins=n,["api","capabilities","registration","messages","redactedViews","unredactedViews","confirmSession","confirmRemoteControl","confirmFullDevice","showSessionControls","hideSessionControls"].forEach(s=>{t[s]!==void 0&&(e[s]=t[s])})}get cobrowseIO(){return this._cobrowseIO}async start(){await this._cobrowseIO.client(),await this._cobrowseIO.start()}}const qW=Date.now(),TO={href:window.location.href,interval:24*60*60};function WW(r){if(!Array.isArray(r)||!r.length)return null;const e=KW(),t=e===0,n=e+1;return JW(n),r.filter(s=>{const a=HW(s,TO.href),c=GW(s.visitor_type,t),o=n>=s.page_visit_count,l=!zW(s.id);return a&&c&&o&&l}).sort((s,a)=>s.stay_time-a.stay_time)[0]||null}function VW(r,e){const t=r.stay_time*1e3,n=Math.max(t-(Date.now()-qW),0);setTimeout(()=>{e(r),_r.set(`trigger:${r.id}`,(Date.now()/1e3).toString())},n)}const HW=(r,e)=>{const{keywords_included_or:t=[],keywords_excluded_or:n=[],keywords_included:i=[],keywords_excluded:s=[]}=r;if(o6(t,n,i,s))return!0;if(t.length||n.length){const o=t.some(d=>d.every(h=>e.includes(h))),l=n.length>0&&n.every(d=>d.every(h=>!e.includes(h)));return o||l}const a=i.filter(o=>e.indexOf(o)!==-1).length,c=s.filter(o=>e.indexOf(o)===-1).length;return!!a||!!c};function GW(r,e){return r==="visitor_type_new"?e:r==="visitor_type_returning"?!e:!0}function zW(r){try{const e=parseInt(_r.get(`trigger:${r}`),10);return Date.now()/1e3-e<TO.interval}catch(e){return console.error("Couldn't parse trigger time",e),!1}}function KW(){try{const r=_r.get("visits");return r?parseInt(r,10):0}catch(r){return console.error("Couldn't get visit count",r),0}}function JW(r){try{_r.set("visits",r.toString())}catch(e){console.error(e)}}function YW(r){return r.replace(/\/+$/,"")}const Ry=new an("VoiceMultiTab"),Mb="voice:tab-lock",XW=5e3,QW=2e3,ZW=250,Py=()=>{const r=_r.get(Mb);if(!r)return null;try{return JSON.parse(r)}catch{return null}},Iy=()=>{var i;const r=Py();if(r&&typeof r.ts=="number"&&Date.now()-r.ts<XW)throw new fl;const e=Rw(),t=()=>{_r.set(Mb,JSON.stringify({id:e,ts:Date.now()}))};if(t(),((i=Py())==null?void 0:i.id)!==e)throw new fl;const n=setInterval(t,QW);return{release(){clearInterval(n);const s=Py();(!s||s.id===e)&&_r.del(Mb)}}},KE=async()=>{if(typeof BroadcastChannel>"u")return Iy();let r;try{r=new BroadcastChannel(CW)}catch{return Iy()}const e=Rw();let t=!1;r.onmessage=n=>{const i=n.data;(i.kind==="present"||i.kind==="claim")&&i.id!==e&&(t=!0)};try{r.postMessage({kind:"claim",id:e})}catch(n){Ry.debug("BC postMessage(claim) failed; falling back to localStorage path",n);try{r.close()}catch{}return Iy()}if(await new Promise(n=>setTimeout(n,ZW)),t)throw r.close(),new fl;return r.onmessage=n=>{const i=n.data;if(i.kind==="claim"&&i.id!==e)try{r.postMessage({kind:"present",id:e})}catch(s){Ry.debug("BC postMessage(present) failed",s)}},{release(){try{r.postMessage({kind:"release",id:e})}catch(n){Ry.debug("BC postMessage(release) failed",n)}r.close()}}},e5=["photo","video","audio","document"],qa=new an("client");function t5(r){const e=r==null?void 0:r.status;return typeof e=="number"&&e>=400&&e<500}let r5=class{constructor(e){be(this,"VERSION",Pw);be(this,"options");be(this,"communicator");be(this,"methods");be(this,"events",new zv);be(this,"request");be(this,"chat");be(this,"_cobrowse");be(this,"_voiceCall",null);be(this,"_voiceTabLock",null);be(this,"redactionSendQueue",Promise.resolve());be(this,"fileSendQueue",Promise.resolve());be(this,"_rehydratePromise",null);be(this,"onPageHide");be(this,"onPageShow");this.options=e.host?{...e,host:YW(e.host)}:e,this.communicator=new S6(this.options,this.events);const t=this.communicator.request.bind(this.communicator),n=this.communicator.leaveChatBeacon.bind(this.communicator);this.methods=new DW(t,n,{getAuthToken:this.communicator.getAuthToken.bind(this.communicator),wsUrl:this.communicator.wsUrl},this.communicator.isRiskFlagEnabled.bind(this.communicator)),this.request=t,this.options.host&&rO.setPath(this.options.host),zn.companyId=e.companyId,e.tenant&&(zn.tenant=e.tenant),this.events.addEventListener(Kn.STATUS_CHANGED,i=>{(i==null?void 0:i.status)==="error"&&this.releaseVoiceTabLock()}),this.registerUnloadHandlers()}registerUnloadHandlers(){typeof window>"u"||(this.onPageHide=e=>{var t,n;e.persisted||((t=this.chat)==null||t.leaveBeacon(),(n=this._voiceCall)==null||n._markUnloading(),this.releaseVoiceTabLock())},this.onPageShow=e=>{var t;e.persisted&&((t=this.chat)==null||t.resetBeaconState())},window.addEventListener("pagehide",this.onPageHide),window.addEventListener("pageshow",this.onPageShow))}unregisterUnloadHandlers(){typeof window>"u"||(this.onPageHide&&(window.removeEventListener("pagehide",this.onPageHide),this.onPageHide=void 0),this.onPageShow&&(window.removeEventListener("pageshow",this.onPageShow),this.onPageShow=void 0))}get deviceId(){return zn.deviceId}get user(){return this.communicator.user}get lang(){return this.options.lang?this.options.lang:_r.get("lang")||"en"}set lang(e){this.options.lang||_r.set("lang",e)}get cobrowse(){return this._cobrowse.cobrowseIO}get cobrowseEnabled(){var e;return!!((e=this.options.cobrowse)!=null&&e.enabled)}destroy(){this.destroyVoiceCall().catch(()=>{}),this.unregisterUnloadHandlers(),this.communicator.destroy(),this.events.destroy()}destroyDuplicate(){this.unregisterUnloadHandlers(),this.communicator.destroy(),this.events.destroy()}releaseVoiceTabLock(){var e;(e=this._voiceTabLock)==null||e.release(),this._voiceTabLock=null}on(e,t){this.events.addEventListener(e,t)}off(e,t){this.events.removeEventListener(e,t)}async checkMicPermission(){var e;if(typeof navigator>"u"||!((e=navigator.permissions)!=null&&e.query))return"unknown";try{const n=(await navigator.permissions.query({name:"microphone"})).state;return n==="granted"||n==="denied"||n==="prompt"?n:"unknown"}catch{return"unknown"}}async getCompany(){const e=await this.methods.getCompany();return zn.tenant=e.subdomain,e}async getFeatureFlags(){return await this.methods.getFeatureFlags()}isRiskFlagEnabled(e){return this.communicator.isRiskFlagEnabled(e)}getRiskFlags(){return this.communicator.getRiskFlags()}async runTrigger(e){const t=await this.methods.getTriggers(this.options.companyId),n=WW(t);n&&VW(n,e)}async trackClientEvents(e){await this.methods.trackClientEvents(e)}async getProhibitedFileTypes(){return await this.methods.listFileTypes()}async getMenus(e,t,n){return await this.methods.getMenus(t||this.lang,e,n)}cancelMenuPolling(){this.methods.cancelDapPolling()}getCustomFormData(e){return this.methods.getCustomFormData(e)}submitCustomForm(e){return this.methods.submitCustomForm(e)}async getAfterHourMessage(e){return await this.methods.getAfterHourMessage(e||this.lang)}async getTimeSlots(e,t){return(i=>typeof i=="object"&&i!==null)(t)?await this.methods.getTimeSlots(e,{lang:t.lang||this.lang,rescheduleCallId:t.rescheduleCallId}):await this.methods.getTimeSlots(e,{lang:t||this.lang})}async fetchTimeSlotAvailability(e,t){return await this.methods.fetchTimeSlotAvailability(e,t||this.lang)}async getWaitTimes(e,t){return await this.methods.getWaitTimes(e,t||this.lang)}async verifyForm(e){return await this.methods.verifyForm(e)}async createCall(e,t){var i;!t.email&&((i=this.user)!=null&&i.email)&&(t.email=this.user.email);const n={...t,lang:t.lang||this.lang};return await this.methods.createCall(Number(e),n)}async loadCall(e){return await this.methods.fetchCall(e)}async cancelCall(e){return await this.methods.cancelCall(e)}async createEmail(e,t){return await this.methods.createEmail(e,t.lang||this.lang,t)}async createChat(e,t={}){var i,s;if(!this.chat&&_r.get("chat")&&await this.loadOngoingChat().catch(()=>null),this.chat&&this.chat.ongoing)throw new Error("There is an ongoing chat.");!t.email&&((i=this.user)!=null&&i.email)&&(t.email=this.user.email),t.cobrowsable===void 0&&(t.cobrowsable=!!((s=this.options.cobrowse)!=null&&s.enabled));const n=await this.methods.createChat(Number(e),t.lang||this.lang,t,this.deviceId);return this.registerOngoingChat(n),await n.clearMediaStore(),n}async loadChat(e){try{const t=await this.methods.loadChat(e,this.deviceId);return t.ongoing?this.registerOngoingChat(t):(_r.del("chat"),_r.del("cobrowse")),t}catch(t){throw _r.del("chat"),_r.del("cobrowse"),t}}async resumeChat(e){var n;if(((n=this.chat)==null?void 0:n.id)===Number(e)){const i=await this.methods.patch(`chats/${e}`,{status:"queued"});return this.chat.update(i.data),this.chat}const t=await this.methods.resumeChat(e,this.deviceId);return this.registerOngoingChat(t),t}async loadOngoingChat(){return this._rehydratePromise?this._rehydratePromise:(this._rehydratePromise=this._doLoadOngoingChat().finally(()=>{this._rehydratePromise=null}),this._rehydratePromise)}async _doLoadOngoingChat(){const e=_r.get("chat");if(!e)return _r.del("chat"),null;try{const t=await this.loadChat(e);return t&&t.ongoing?t:(_r.del("chat"),null)}catch(t){throw _r.del("chat"),t}}async restoreCobrowseSession(){var t;const e=_r.get("cobrowse");if(!(!e||!((t=this.options.cobrowse)!=null&&t.enabled)))try{await this.initializeCobrowse(this.lang),qa.debug("cobrowse session restored with nonce:",e)}catch(n){qa.error("Failed to restore cobrowse session",n),_r.del("cobrowse")}}async finishChat(){if(!this.chat)return;const e=await this.methods.finishChat(this.chat.id);this.chat.update(e),this.chat.connected&&this.chat.ended&&await this.chat.disconnect()}async updatePostSession(e,t){if(!this.chat||e===ul.FINISHED||e===ul.WAITING)return;const n=await this.methods.updatePostSession(this.chat.id,e,t);this.chat.update(n)}async destroyChat(){if(this.chat){if(this.chat.muted=!0,this.chat.ongoing)try{await this.finishChat()}catch(e){qa.warn("finishChat during destroy failed",{error:e})}await this.chat.destroy(),this.chat=null,zn.trackerId=""}}get voiceCall(){return this._voiceCall}hasStoredVoiceCall(){return HE()!==null}async startVoiceCall(e,t={}){var i;if(this._voiceCall&&!qc.has(this._voiceCall.serverStatus()))throw new Vu("A voice call is already active in this session");!t.email&&((i=this.user)!=null&&i.email)&&(t.email=this.user.email),t.cobrowsable===void 0&&(t.cobrowsable=this.cobrowseEnabled);try{await n5()}catch(s){const a=s instanceof dl?s.cause:void 0,c=a&&typeof a=="object"&&"name"in a?a.name:void 0;if(c==="NotAllowedError"||c==="PermissionDeniedError")try{this.events.triggerEvent(Kn.MIC_PERMISSION_REQUIRED)}catch{}throw s}this.releaseVoiceTabLock(),this._voiceTabLock=await KE();let n;try{n=await this.methods.createVoiceCall(Number(e),t.lang||this.lang,t,this.deviceId,this.events,(s,a)=>this.startVoiceCobrowseInternal(s,a))}catch(s){throw this.releaseVoiceTabLock(),JE(s)}this._voiceCall=n;try{await n._connect()}catch(s){throw await n._destroy().catch(()=>{}),this._voiceCall=null,this.releaseVoiceTabLock(),s}return IW(n.id),n}async loadVoiceCall(e){if(this._voiceCall&&!qc.has(this._voiceCall.serverStatus()))return this._voiceCall;let t=null;if(e!==void 0?t=Number(e):t=HE(),t===null)return null;this.releaseVoiceTabLock(),this._voiceTabLock=await KE();let n;try{n=await this.methods.fetchVoiceCall(t)}catch(s){if(mO(s)===404)return Wc(),this.releaseVoiceTabLock(),null;throw this.releaseVoiceTabLock(),JE(s)}if(qc.has(n.status))return Wc(),this.releaseVoiceTabLock(),null;let i;try{i=await this.methods._wrapVoiceCallForRestore(n,this.deviceId,this.events,(s,a)=>this.startVoiceCobrowseInternal(s,a))}catch(s){throw this.releaseVoiceTabLock(),s}this._voiceCall=i;try{await i._connect()}catch(s){throw await i._destroy().catch(()=>{}),this._voiceCall=null,this.releaseVoiceTabLock(),Wc(),s}return this.restoreCobrowseSession().catch(s=>{qa.warn("cobrowse restore failed during voice restore",s)}),i}async endVoiceCall(){this._voiceCall&&(qc.has(this._voiceCall.serverStatus())||await this._voiceCall._abandonOrFinish())}async escalateVoiceCall(){if(!this._voiceCall)throw new Uo;await this._voiceCall._escalate()}async destroyVoiceCall(){if(!this._voiceCall){this.releaseVoiceTabLock(),Wc();return}try{await this._voiceCall._destroy()}finally{this._voiceCall=null,this.releaseVoiceTabLock()}}async getChatDeflection(){return await this.methods.getChatDeflection(this.chat.id)}async sendChatTranscripts(e){await this.methods.sendChatTranscripts(this.chat.id,e)}async downloadChatTranscript(){return await this.methods.downloadChatTranscript(this.chat.id)}async getPdfStatus(e){return await this.methods.getPdfStatus(e)}async getChatSurvey(){return await this.methods.getChatSurvey(this.chat.id)}async sendChatSurvey(e){if(this.chat.feedbackType!=="survey")throw new Error("Chat feedback type is: "+this.chat.feedbackType);await this.methods.sendChatSurvey(this.chat.id,e)}async sendChatRate(e){if(this.chat.feedbackType!=="rate")throw new Error("Chat feedback type is: "+this.chat.feedbackType);await this.methods.rateChat(this.chat.id,e)}async rateVoiceCall(e){if(!this._voiceCall)throw new Uo;if(this._voiceCall.feedbackType!=="rate")throw new Error("Voice call feedback type is: "+this._voiceCall.feedbackType);await this.methods.rateVoiceCall(this._voiceCall.id,e)}async getVoiceCallSurvey(){if(!this._voiceCall)throw new Uo;return await this.methods.getVoiceCallSurvey(this._voiceCall.id)}async submitVoiceCallSurvey(e){if(!this._voiceCall)throw new Uo;if(this._voiceCall.feedbackType!=="survey")throw new Error("Voice call feedback type is: "+this._voiceCall.feedbackType);await this.methods.submitVoiceCallSurvey(this._voiceCall.id,e)}async escalateChat(e){await this.methods.escalateChat(this.chat.id,e)}async trackChatEscalation(e,t){await this.methods.trackEscalation(this.chat.id,e,t)}async trackChatEndUserEvent(e){var t;!e.end_user_name&&((t=this.user)!=null&&t.name)&&(e.end_user_name=this.user.name),await this.methods.trackChatEndUserEvent(this.chat.id,e)}async getChatHistory(e=1){return await this.methods.getChatHistory(e)}async fetchMessages(){try{const e=await this.chat.fetchMessages();if(e.some(t=>t.type==="document"))try{const t=await this.methods.getChatDocuments(this.chat.id);R6(e,t)}catch(t){qa.warn("[fetchMessages] Failed to fetch chat documents",t)}if(e.filter(t=>t.type===ln.SERVER_MESSAGE).length>0){const t=await this.methods.listChatTaskMessages(this.chat.id);return T6(e,t)}return e}catch{return[]}}async sendFileMessage(e){const t=this.chat.id,n=this.fileSendQueue.then(async()=>{let i;try{i=await this.methods.uploadChatFile(t,e)}catch(s){return qa.warn("[sendFileMessage] upload failed",s),-1}return this.chat.sendMessage(i,e)});return this.fileSendQueue=n.catch(()=>{}),await n}async sendTextMessage(e){const t=$b(e);if(t){if(this.chat.inTask){const n=await this.methods.sendChatTaskMessage(this.chat.id,t);this.chat.sendMessage({type:ln.SERVER_MESSAGE,visibility:"task_virtual_agent",message_id:n.id});return}if(this.chat.state.redaction_enabled){const n=this.chat,i=n.id,s=c6();s&&n.rememberOwnOriginal(s,t);const a=this.redactionSendQueue.then(()=>this.methods.sendChatTextMessage(i,t,s??void 0));this.redactionSendQueue=a.catch(()=>{});try{await a}catch(c){throw s&&t5(c)&&n.forgetOwnOriginal(s),c}return}this.chat.sendMessage({type:ln.TEXT,content:t})}}async sendPreviewMessage(e){if(this.isRedactionAgentEnabled()){const t=new Date().toISOString(),n=await this.methods.sendPreviewMessage(this.chat.id,e,t);this.chat.preview(n==null?void 0:n.content);return}this.chat.preview(e)}isRedactionAgentEnabled(){return this.chat.state.redaction_enabled&&this.chat.state.agent_incoming_ha_enabled}async createCobrowseCode(e,t){var n;try{await this.initializeCobrowse(e||this.lang);let i=_r.get("cobrowse");i||(i=Date.now().toString(),_r.set("cobrowse",i));const s={device_id:this.deviceId,device_name:`${zn.application} / ${zn.version}`,nonce:i,...t};return(n=this.user)!=null&&n.name&&(s.user_name=this.user.name),this.cobrowse.customData=s,await this.cobrowse.createSessionCode()}catch{return""}}async startCobrowse(e="end_user"){if(!this.chat.cobrowsable)throw new Error(`Chat ${this.chat.id} does not support cobrowse.`);const t={chatId:`chat_${this.chat.id}`},n=await this.createCobrowseCode(this.chat.lang,t);if(!n)return;const i=_r.get("cobrowse");await this.methods.requestChatCobrowse(this.chat.id,{code:n,from:e,nonce:i})}async startVoiceCobrowseInternal(e,t){if(!this.cobrowseEnabled)throw new Error("Cobrowse is not enabled.");if(!this._voiceCall)throw new Uo;const n=this._voiceCall.id,i={callId:`call_${n}`},s=await this.createCobrowseCode(e||this.lang,i);if(!s)return"";const a=_r.get("cobrowse")??"";return await this.methods.requestVoiceCallCobrowse(n,{code:s,from:t,nonce:a}),this.events.triggerEvent("cobrowse.request",{from:t}),s}async getMessageAttachment(e){if(e.$userType!==_i.END_USER&&e5.includes(e.type)){const t=await this.methods.getMedia(e.media_id,e.type);return this.chat&&this.chat.saveMedia(e.$index,t),t}return null}async checkIn(){const e=await this.methods.confirmCheckIn(this.chat.id);return this.updateCheckIn(e),e}async exitCheckIn(){const e=await this.methods.exitCheckIn(this.chat.id);return this.updateCheckIn(e),e}async notifyCheckInState(e){await this.methods.notifyCheckInState(this.chat.id,e)}async rejoinChat(){const e=await this.methods.rejoinQueue(this.chat.id);return this.updateCheckIn(e),e}async trackCheckInEvent(){const e={modal_type:"check_in"};await this.methods.trackCheckIn(this.chat.id,e)}async getLogs(){const e=await this.communicator.getBridgeLogHistory(),t=an.logHistory.toArray();return{bridgeLogs:e,rootLogs:t}}async printLogs(){const e=await this.getLogs();console.log("Printing bridge logs:"),e.bridgeLogs.forEach(t=>{an.printLogHistoryData(t)}),console.log("Printing root logs:"),e.rootLogs.forEach(t=>{an.printLogHistoryData(t)})}updateCheckIn(e){const t={...this.chat.state};t.check_in_status=e.check_in_status,this.chat.update(t)}async initializeCobrowse(e){if(!this._cobrowse){const t=await this.getCompany(),n=this.options.cobrowse.messages||tW(e),i={...this.options.cobrowse,messages:n,lang:e};this._cobrowse=await jW(i,t.cobrowse_domain),await this._cobrowse.start(),[["session.loaded",Bp.LOADED],["session.updated",Bp.UPDATED],["session.ended",Bp.ENDED]].forEach(([a,c])=>{this.cobrowse.on(a,o=>{this.events.triggerEvent(c,o)})}),qa.debug("cobrowse has been initialized"),this.events.triggerEvent("cobrowse.initialized",this._cobrowse)}}registerOngoingChat(e){this.events.triggerEvent("chat.ongoing",e),e._setGlobalEvents(this.events,this.methods.getChatTaskMessage.bind(this.methods)),e.on("_requestCobrowse",t=>{t==="agent"?this.startCobrowse(t):this.initializeCobrowse(e.lang).catch(n=>{qa.error("Failed to initialize cobrowse on request",n)}),this.events.triggerEvent("cobrowse.request",{from:t})}),e.on("disconnected",()=>{_r.del("chat"),_r.del("cobrowse")}),this.chat=e,zn.trackerId=`chat_${e.id}`,_r.set("chat",e.id.toString()),e.cobrowsable&&_r.get("cobrowse")&&this.initializeCobrowse(e.lang).catch(t=>{qa.error("Failed to initialize cobrowse for ongoing chat",t)})}_triggerEvent(e,t){this.events.triggerEvent(e,t)}};const n5=async()=>{var r;if(typeof navigator>"u"||!((r=navigator.mediaDevices)!=null&&r.getUserMedia))throw new dl("Browser does not support microphone access");try{(await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(t=>t.stop())}catch(e){throw new dl(Aw(e),e)}},i5=new Map([["call_in_progress",Vu],["inbound_disabled",cl],["outside_operation_hours",Hu],["operation_hours",Hu],["feature_not_enabled",ll],["invalid_call_type",ll]]),s5=new Map([[409,Hu],[403,cl],[400,Vu]]),JE=r=>{var a,c;if(r instanceof ws)return r;const e=r&&typeof r=="object"?r:{},t=(a=e.data)==null?void 0:a.error_code,n=((c=e.data)==null?void 0:c.message)??e.message??"",i=t?i5.get(t):void 0;if(i)return new i(n);const s=e.status!==void 0?s5.get(e.status):void 0;return s?new s(n):new uv(n,r)};var Ye=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Kv(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}function CO(r){if(r.__esModule)return r;var e=r.default;if(typeof e=="function"){var t=function n(){return this instanceof n?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(r).forEach(function(n){var i=Object.getOwnPropertyDescriptor(r,n);Object.defineProperty(t,n,i.get?i:{enumerable:!0,get:function(){return r[n]}})}),t}var Db={exports:{}},Zo=lv;function lv(){}lv.mixin=function(r){var e=r.prototype||r;e.isWildEmitter=!0,e.on=function(t,n,i){this.callbacks=this.callbacks||{};var s=arguments.length===3,a=s?arguments[1]:void 0,c=s?arguments[2]:arguments[1];return c._groupName=a,(this.callbacks[t]=this.callbacks[t]||[]).push(c),this},e.once=function(t,n,i){var s=this,a=arguments.length===3,c=a?arguments[1]:void 0,o=a?arguments[2]:arguments[1];function l(){s.off(t,l),o.apply(this,arguments)}return this.on(t,c,l),this},e.releaseGroup=function(t){this.callbacks=this.callbacks||{};var n,i,s,a;for(n in this.callbacks)for(a=this.callbacks[n],i=0,s=a.length;i<s;i++)a[i]._groupName===t&&(a.splice(i,1),i--,s--);return this},e.off=function(t,n){this.callbacks=this.callbacks||{};var i=this.callbacks[t],s;return i?arguments.length===1?(delete this.callbacks[t],this):(s=i.indexOf(n),s!==-1&&(i.splice(s,1),i.length===0&&delete this.callbacks[t]),this):this},e.emit=function(t){this.callbacks=this.callbacks||{};var n=[].slice.call(arguments,1),i=this.callbacks[t],s=this.getWildcardCallbacks(t),a,c,o;if(i)for(o=i.slice(),a=0,c=o.length;a<c&&o[a];++a)o[a].apply(this,n);if(s)for(c=s.length,o=s.slice(),a=0,c=o.length;a<c&&o[a];++a)o[a].apply(this,[t].concat(n));return this},e.getWildcardCallbacks=function(t){this.callbacks=this.callbacks||{};var n,i,s=[];for(n in this.callbacks)i=n.split("*"),(n==="*"||i.length===2&&t.slice(0,i[0].length)===i[0])&&(s=s.concat(this.callbacks[n]));return s}};lv.mixin(lv);var EO={exports:{}};(function(r){(function(e,t){r.exports?r.exports=t():e.prefix=t(e)})(Ye,function(e){var t=function(d){for(var h=1,v=arguments.length,y;h<v;h++)for(y in arguments[h])Object.prototype.hasOwnProperty.call(arguments[h],y)&&(d[y]=arguments[h][y]);return d},n={template:"[%t] %l:",levelFormatter:function(d){return d.toUpperCase()},nameFormatter:function(d){return d||"root"},timestampFormatter:function(d){return d.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")},format:void 0},i,s={},a=function(d){if(!d||!d.getLogger)throw new TypeError("Argument is not a root logger");i=d},c=function(d,h){if(!d||!d.setLevel)throw new TypeError("Argument is not a logger");var v=d.methodFactory,y=d.name||"",w=s[y]||s[""]||n;function k(I,A,j){var L=v(I,A,j),x=s[j]||s[""],B=x.template.indexOf("%t")!==-1,G=x.template.indexOf("%l")!==-1,K=x.template.indexOf("%n")!==-1;return function(){for(var D="",fe=arguments.length,X=Array(fe),pe=0;pe<fe;pe++)X[pe]=arguments[pe];if(y||!s[j]){var Q=x.timestampFormatter(new Date),Oe=x.levelFormatter(I),Ve=x.nameFormatter(j);x.format?D+=x.format(Oe,Ve,Q):(D+=x.template,B&&(D=D.replace(/%t/,Q)),G&&(D=D.replace(/%l/,Oe)),K&&(D=D.replace(/%n/,Ve))),X.length&&typeof X[0]=="string"?X[0]=D+" "+X[0]:X.unshift(D)}L.apply(void 0,X)}}return s[y]||(d.methodFactory=k),h=h||{},h.template&&(h.format=void 0),s[y]=t({},w,h),d.setLevel(d.getLevel()),i||d.warn("It is necessary to call the function reg() of loglevel-plugin-prefix before calling apply. From the next release, it will throw an error. See more: https://github.com/kutuluk/loglevel-plugin-prefix/blob/master/README.md"),d},o={reg:a,apply:c},l;return e&&(l=e.prefix,o.noConflict=function(){return e.prefix===o&&(e.prefix=l),o}),o})})(EO);var a5=EO.exports,kO={exports:{}};(function(r){(function(e,t){r.exports?r.exports=t():e.log=t()})(Ye,function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"],s={},a=null;function c(k,I){var A=k[I];if(typeof A.bind=="function")return A.bind(k);try{return Function.prototype.bind.call(A,k)}catch{return function(){return Function.prototype.apply.apply(A,[k,arguments])}}}function o(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function l(k){return k==="debug"&&(k="log"),typeof console===t?!1:k==="trace"&&n?o:console[k]!==void 0?c(console,k):console.log!==void 0?c(console,"log"):e}function d(){for(var k=this.getLevel(),I=0;I<i.length;I++){var A=i[I];this[A]=I<k?e:this.methodFactory(A,k,this.name)}if(this.log=this.debug,typeof console===t&&k<this.levels.SILENT)return"No console available for logging"}function h(k){return function(){typeof console!==t&&(d.call(this),this[k].apply(this,arguments))}}function v(k,I,A){return l(k)||h.apply(this,arguments)}function y(k,I){var A=this,j,L,x,B="loglevel";typeof k=="string"?B+=":"+k:typeof k=="symbol"&&(B=void 0);function G(pe){var Q=(i[pe]||"silent").toUpperCase();if(!(typeof window===t||!B)){try{window.localStorage[B]=Q;return}catch{}try{window.document.cookie=encodeURIComponent(B)+"="+Q+";"}catch{}}}function K(){var pe;if(!(typeof window===t||!B)){try{pe=window.localStorage[B]}catch{}if(typeof pe===t)try{var Q=window.document.cookie,Oe=encodeURIComponent(B),Ve=Q.indexOf(Oe+"=");Ve!==-1&&(pe=/^([^;]+)/.exec(Q.slice(Ve+Oe.length+1))[1])}catch{}return A.levels[pe]===void 0&&(pe=void 0),pe}}function D(){if(!(typeof window===t||!B)){try{window.localStorage.removeItem(B)}catch{}try{window.document.cookie=encodeURIComponent(B)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function fe(pe){var Q=pe;if(typeof Q=="string"&&A.levels[Q.toUpperCase()]!==void 0&&(Q=A.levels[Q.toUpperCase()]),typeof Q=="number"&&Q>=0&&Q<=A.levels.SILENT)return Q;throw new TypeError("log.setLevel() called with invalid level: "+pe)}A.name=k,A.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},A.methodFactory=I||v,A.getLevel=function(){return x??L??j},A.setLevel=function(pe,Q){return x=fe(pe),Q!==!1&&G(x),d.call(A)},A.setDefaultLevel=function(pe){L=fe(pe),K()||A.setLevel(pe,!1)},A.resetLevel=function(){x=null,D(),d.call(A)},A.enableAll=function(pe){A.setLevel(A.levels.TRACE,pe)},A.disableAll=function(pe){A.setLevel(A.levels.SILENT,pe)},A.rebuild=function(){if(a!==A&&(j=fe(a.getLevel())),d.call(A),a===A)for(var pe in s)s[pe].rebuild()},j=fe(a?a.getLevel():"WARN");var X=K();X!=null&&(x=fe(X)),d.call(A)}a=new y,a.getLogger=function(I){if(typeof I!="symbol"&&typeof I!="string"||I==="")throw new TypeError("You must supply a name when creating a logger.");var A=s[I];return A||(A=s[I]=new y(I,a.methodFactory)),A};var w=typeof window!==t?window.log:void 0;return a.noConflict=function(){return typeof window!==t&&window.log===a&&(window.log=w),a},a.getLoggers=function(){return s},a.default=a,a})})(kO);var Gr=kO.exports;const o5=Kv(Gr),u5=Aq({__proto__:null,default:o5},[Gr]);var Nb={exports:{}},c5={"error:application:call:params":{type:"error:application:call:params",description:"not a valid String[] of usernames param"},"error:application:callServer:params":{type:"error:application:call:params",description:"not a valid String of phone number"},"error:call:reject":{type:"error:call:reject",description:"failed to reject the call"},"error:getUserMedia:permissions":{type:"error:getUserMedia:permissions",description:"missing getUserMedia permissions"},"error:media:params":{type:"error:media:params",description:"currently supported params media type= {audio:{muted:false, earmuffed:false}}"},"error:media:reenable":{type:"error:media:reenable",description:"missing reconnectRtcId required to reenable media"},"error:self":{type:"error:self",description:"Conversation Object is missing self (me)"},"error:user:relogin":{type:"error:user:relogin",description:"please relogin"},"error:seen:own-message":{type:"error:seen:own-message",description:"attempt to send seen for own message"},"error:already-seen":{type:"error:already-seen",description:"already marked as seen"},"error:delivered:own-message":{type:"error:delivered:own-message",description:"attempt to send delivered for own message"},"error:already-delivered":{type:"error:already-delivered",description:"already marked as delivered"},"error:fetch-image":{type:"error:fetch-image",description:"xhr.status received other than 200"},"error:delete-image":{type:"error:delete-image",description:"xhr.status received other than 204"},"error:missing:params":{type:"error:missing:params",description:"missing parameters"},"error:invite:missing:params":{type:"error:missing:params",description:"This invite cannot be sent to empty username and user_id"},"error:invalid:param:type":{type:"error:invalid:param:type",description:"Invalid Object type, passed in the parameters"},"error:audio:already-connecting":{type:"error:audio:already-connecting",description:"Audio call already in progress"},"error:audio:not-enabled":{type:"error:audio:not-enabled",description:"Audio is not enabled"},"error:media:already-connecting":{type:"error:media:already-connecting",description:"Media is already in progress"},"error:media:unsupported-browser":{type:"error:media:unsupported-browser",description:"This action is not supported on this browser"},"error:media:extension":{type:"error:media:extension",description:"Chrome extension has thrown an error"},"error:media:extension-not-installed":{type:"error:media:extension-not-installed",description:"Chrome extension should be installed"},"error:media:update:streams":{type:"error:media:update:streams",description:"cant update more than one stream"},"error:media:update:invalid":{type:"error:media:update:invalid",description:"state of media is not supported for this update"},"error:media:stream:not-found":{type:"error:media:stream:not-found",description:"A stream with the given index was not found"},"error:audio:dtmf:invalid-digit":{type:"error:audio:dtmf:invalid-digit",description:"not a valid string of dtmf digits (0-9,a-d,A-D,p,P,*,#)"},"error:audio:dtmf:audio-disabled":{type:"error:audio:dtmf:audio-disabled",description:"Audio must be enabled to send DTMF"},"error:invalid-order":{type:"error:invalid-order",description:"params not valid. Order must be asc or desc"},"error:custom-event:invalid":{type:"error:custom-event:invalid",description:"Custom event type not valid"},"error:message-event:invalid":{type:"error:message-event:invalid",description:"message_type is missing or is invalid"},"error:invalid-cursor":{type:"error:invalid-cursor",description:"page does not exist"},"error:client:reconnection_failed":{type:"error:client:reconnection_failed",description:"websocket failed to reconnect"},"error:conversation-service:version":{type:"error:conversation:version",description:'Wrong version of Conversation Service API. It should be one of "v1" or "v3"'},"error:no-media-offer":{type:"error:no-media-offer",description:"Media preload attempt without having an offer available"}};(function(r,e){Object.defineProperty(e,"__esModule",{value:!0}),e.NexmoApiError=e.NexmoClientError=void 0;const t=c5,n=Gr;function i(c,o){o&&o.code&&(o.type=o.code,delete o.code),Object.assign(c,o),c.message="type: "+c.type+", description: "+(c.description?c.description:"")}class s{constructor(o){const l=t[o];l?i(this,l):(this.message=o&&o.message?o.message:o,this.stack=o.stack),this.log=n.getLogger(this.constructor.name),this.log.error(this),this.name="NexmoClientError",typeof Ye.NXMbugsnagClient<"u"&&Ye.NXMbugsnagClient.notify(this,{severity:"info"})}}e.NexmoClientError=s;class a{constructor(o){this.log=n.getLogger(this.constructor.name),o?i(this,o):(this.message=o&&o.message?o.message:o,this.stack=o&&o.stack?o.stack:new Error().stack),this.name="NexmoApiError",this.log=n.getLogger(this.constructor.name),this.log.error(this),typeof Ye.NXMbugsnagClient<"u"&&Ye.NXMbugsnagClient.notify(this,{severity:"info"})}}e.NexmoApiError=a,r.exports={NexmoClientError:s,NexmoApiError:a}})(Nb,Nb.exports);var Ts=Nb.exports,Lb={exports:{}},$w={},Jv={},eo={},nf={},ha={},sf={},ro={},Tl={},af={},pa={};Object.defineProperty(pa,"__esModule",{value:!0});pa.ERROR_PACKET=pa.PACKET_TYPES_REVERSE=pa.PACKET_TYPES=void 0;const ma=Object.create(null);pa.PACKET_TYPES=ma;ma.open="0";ma.close="1";ma.ping="2";ma.pong="3";ma.message="4";ma.upgrade="5";ma.noop="6";const RO=Object.create(null);pa.PACKET_TYPES_REVERSE=RO;Object.keys(ma).forEach(r=>{RO[ma[r]]=r});const l5={type:"error",data:"parser error"};pa.ERROR_PACKET=l5;Object.defineProperty(af,"__esModule",{value:!0});af.encodePacket=void 0;af.encodePacketToBinary=f5;const d5=pa,PO=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",IO=typeof ArrayBuffer=="function",AO=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r&&r.buffer instanceof ArrayBuffer,OO=({type:r,data:e},t,n)=>PO&&e instanceof Blob?t?n(e):YE(e,n):IO&&(e instanceof ArrayBuffer||AO(e))?t?n(e):YE(new Blob([e]),n):n(d5.PACKET_TYPES[r]+(e||""));af.encodePacket=OO;const YE=(r,e)=>{const t=new FileReader;return t.onload=function(){const n=t.result.split(",")[1];e("b"+(n||""))},t.readAsDataURL(r)};function XE(r){return r instanceof Uint8Array?r:r instanceof ArrayBuffer?new Uint8Array(r):new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}let Ay;function f5(r,e){if(PO&&r.data instanceof Blob)return r.data.arrayBuffer().then(XE).then(e);if(IO&&(r.data instanceof ArrayBuffer||AO(r.data)))return e(XE(r.data));OO(r,!1,t=>{Ay||(Ay=new TextEncoder),e(Ay.encode(t))})}var Yv={},hl={};Object.defineProperty(hl,"__esModule",{value:!0});hl.decode=hl.encode=void 0;const Vc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",kd=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let r=0;r<Vc.length;r++)kd[Vc.charCodeAt(r)]=r;const h5=r=>{let e=new Uint8Array(r),t,n=e.length,i="";for(t=0;t<n;t+=3)i+=Vc[e[t]>>2],i+=Vc[(e[t]&3)<<4|e[t+1]>>4],i+=Vc[(e[t+1]&15)<<2|e[t+2]>>6],i+=Vc[e[t+2]&63];return n%3===2?i=i.substring(0,i.length-1)+"=":n%3===1&&(i=i.substring(0,i.length-2)+"=="),i};hl.encode=h5;const p5=r=>{let e=r.length*.75,t=r.length,n,i=0,s,a,c,o;r[r.length-1]==="="&&(e--,r[r.length-2]==="="&&e--);const l=new ArrayBuffer(e),d=new Uint8Array(l);for(n=0;n<t;n+=4)s=kd[r.charCodeAt(n)],a=kd[r.charCodeAt(n+1)],c=kd[r.charCodeAt(n+2)],o=kd[r.charCodeAt(n+3)],d[i++]=s<<2|a>>4,d[i++]=(a&15)<<4|c>>2,d[i++]=(c&3)<<6|o&63;return l};hl.decode=p5;Object.defineProperty(Yv,"__esModule",{value:!0});Yv.decodePacket=void 0;const Ih=pa,v5=hl,g5=typeof ArrayBuffer=="function",m5=(r,e)=>{if(typeof r!="string")return{type:"message",data:$O(r,e)};const t=r.charAt(0);return t==="b"?{type:"message",data:y5(r.substring(1),e)}:Ih.PACKET_TYPES_REVERSE[t]?r.length>1?{type:Ih.PACKET_TYPES_REVERSE[t],data:r.substring(1)}:{type:Ih.PACKET_TYPES_REVERSE[t]}:Ih.ERROR_PACKET};Yv.decodePacket=m5;const y5=(r,e)=>{if(g5){const t=(0,v5.decode)(r);return $O(t,e)}else return{base64:!0,data:r}},$O=(r,e)=>{switch(e){case"blob":return r instanceof Blob?r:new Blob([r]);case"arraybuffer":default:return r instanceof ArrayBuffer?r:r.buffer}};(function(r){Object.defineProperty(r,"__esModule",{value:!0}),r.decodePayload=r.decodePacket=r.encodePayload=r.encodePacket=r.protocol=void 0,r.createPacketEncoderStream=c,r.createPacketDecoderStream=h;const e=af;Object.defineProperty(r,"encodePacket",{enumerable:!0,get:function(){return e.encodePacket}});const t=Yv;Object.defineProperty(r,"decodePacket",{enumerable:!0,get:function(){return t.decodePacket}});const n=pa,i="",s=(v,y)=>{const w=v.length,k=new Array(w);let I=0;v.forEach((A,j)=>{(0,e.encodePacket)(A,!1,L=>{k[j]=L,++I===w&&y(k.join(i))})})};r.encodePayload=s;const a=(v,y)=>{const w=v.split(i),k=[];for(let I=0;I<w.length;I++){const A=(0,t.decodePacket)(w[I],y);if(k.push(A),A.type==="error")break}return k};r.decodePayload=a;function c(){return new TransformStream({transform(v,y){(0,e.encodePacketToBinary)(v,w=>{const k=w.length;let I;if(k<126)I=new Uint8Array(1),new DataView(I.buffer).setUint8(0,k);else if(k<65536){I=new Uint8Array(3);const A=new DataView(I.buffer);A.setUint8(0,126),A.setUint16(1,k)}else{I=new Uint8Array(9);const A=new DataView(I.buffer);A.setUint8(0,127),A.setBigUint64(1,BigInt(k))}v.data&&typeof v.data!="string"&&(I[0]|=128),y.enqueue(I),y.enqueue(w)})}})}let o;function l(v){return v.reduce((y,w)=>y+w.length,0)}function d(v,y){if(v[0].length===y)return v.shift();const w=new Uint8Array(y);let k=0;for(let I=0;I<y;I++)w[I]=v[0][k++],k===v[0].length&&(v.shift(),k=0);return v.length&&k<v[0].length&&(v[0]=v[0].slice(k)),w}function h(v,y){o||(o=new TextDecoder);const w=[];let k=0,I=-1,A=!1;return new TransformStream({transform(j,L){for(w.push(j);;){if(k===0){if(l(w)<1)break;const x=d(w,1);A=(x[0]&128)===128,I=x[0]&127,I<126?k=3:I===126?k=1:k=2}else if(k===1){if(l(w)<2)break;const x=d(w,2);I=new DataView(x.buffer,x.byteOffset,x.length).getUint16(0),k=3}else if(k===2){if(l(w)<8)break;const x=d(w,8),B=new DataView(x.buffer,x.byteOffset,x.length),G=B.getUint32(0);if(G>Math.pow(2,21)-1){L.enqueue(n.ERROR_PACKET);break}I=G*Math.pow(2,32)+B.getUint32(4),k=3}else{if(l(w)<I)break;const x=d(w,I);L.enqueue((0,t.decodePacket)(A?x:o.decode(x),y)),k=0}if(I===0||I>v){L.enqueue(n.ERROR_PACKET);break}}}})}r.protocol=4})(Tl);function bi(r){if(r)return _5(r)}function _5(r){for(var e in bi.prototype)r[e]=bi.prototype[e];return r}bi.prototype.on=bi.prototype.addEventListener=function(r,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+r]=this._callbacks["$"+r]||[]).push(e),this};bi.prototype.once=function(r,e){function t(){this.off(r,t),e.apply(this,arguments)}return t.fn=e,this.on(r,t),this};bi.prototype.off=bi.prototype.removeListener=bi.prototype.removeAllListeners=bi.prototype.removeEventListener=function(r,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var t=this._callbacks["$"+r];if(!t)return this;if(arguments.length==1)return delete this._callbacks["$"+r],this;for(var n,i=0;i<t.length;i++)if(n=t[i],n===e||n.fn===e){t.splice(i,1);break}return t.length===0&&delete this._callbacks["$"+r],this};bi.prototype.emit=function(r){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),t=this._callbacks["$"+r],n=1;n<arguments.length;n++)e[n-1]=arguments[n];if(t){t=t.slice(0);for(var n=0,i=t.length;n<i;++n)t[n].apply(this,e)}return this};bi.prototype.emitReserved=bi.prototype.emit;bi.prototype.listeners=function(r){return this._callbacks=this._callbacks||{},this._callbacks["$"+r]||[]};bi.prototype.hasListeners=function(r){return!!this.listeners(r).length};const b5=Object.freeze(Object.defineProperty({__proto__:null,Emitter:bi},Symbol.toStringTag,{value:"Module"})),Cl=CO(b5);var Js={},Li={};Object.defineProperty(Li,"__esModule",{value:!0});Li.defaultBinaryType=Li.globalThisShim=Li.nextTick=void 0;Li.createCookieJar=S5;Li.nextTick=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,t)=>t(e,0);Li.globalThisShim=typeof self<"u"?self:typeof window<"u"?window:Function("return this")();Li.defaultBinaryType="arraybuffer";function S5(){}Object.defineProperty(Js,"__esModule",{value:!0});Js.pick=w5;Js.installTimerFunctions=E5;Js.byteLength=R5;Js.randomString=I5;const No=Li;function w5(r,...e){return e.reduce((t,n)=>(r.hasOwnProperty(n)&&(t[n]=r[n]),t),{})}const T5=No.globalThisShim.setTimeout,C5=No.globalThisShim.clearTimeout;function E5(r,e){e.useNativeTimers?(r.setTimeoutFn=T5.bind(No.globalThisShim),r.clearTimeoutFn=C5.bind(No.globalThisShim)):(r.setTimeoutFn=No.globalThisShim.setTimeout.bind(No.globalThisShim),r.clearTimeoutFn=No.globalThisShim.clearTimeout.bind(No.globalThisShim))}const k5=1.33;function R5(r){return typeof r=="string"?P5(r):Math.ceil((r.byteLength||r.size)*k5)}function P5(r){let e=0,t=0;for(let n=0,i=r.length;n<i;n++)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:e<55296||e>=57344?t+=3:(n++,t+=4);return t}function I5(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}var of={};Object.defineProperty(of,"__esModule",{value:!0});of.encode=A5;of.decode=O5;function A5(r){let e="";for(let t in r)r.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(r[t]));return e}function O5(r){let e={},t=r.split("&");for(let n=0,i=t.length;n<i;n++){let s=t[n].split("=");e[decodeURIComponent(s[0])]=decodeURIComponent(s[1])}return e}var Ub={exports:{}},Oy,QE;function $5(){if(QE)return Oy;QE=1;var r=1e3,e=r*60,t=e*60,n=t*24,i=n*7,s=n*365.25;Oy=function(d,h){h=h||{};var v=typeof d;if(v==="string"&&d.length>0)return a(d);if(v==="number"&&isFinite(d))return h.long?o(d):c(d);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(d))};function a(d){if(d=String(d),!(d.length>100)){var h=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(d);if(h){var v=parseFloat(h[1]),y=(h[2]||"ms").toLowerCase();switch(y){case"years":case"year":case"yrs":case"yr":case"y":return v*s;case"weeks":case"week":case"w":return v*i;case"days":case"day":case"d":return v*n;case"hours":case"hour":case"hrs":case"hr":case"h":return v*t;case"minutes":case"minute":case"mins":case"min":case"m":return v*e;case"seconds":case"second":case"secs":case"sec":case"s":return v*r;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return v;default:return}}}}function c(d){var h=Math.abs(d);return h>=n?Math.round(d/n)+"d":h>=t?Math.round(d/t)+"h":h>=e?Math.round(d/e)+"m":h>=r?Math.round(d/r)+"s":d+"ms"}function o(d){var h=Math.abs(d);return h>=n?l(d,h,n,"day"):h>=t?l(d,h,t,"hour"):h>=e?l(d,h,e,"minute"):h>=r?l(d,h,r,"second"):d+" ms"}function l(d,h,v,y){var w=h>=v*1.5;return Math.round(d/v)+" "+y+(w?"s":"")}return Oy}function x5(r){t.debug=t,t.default=t,t.coerce=o,t.disable=a,t.enable=i,t.enabled=c,t.humanize=$5(),t.destroy=l,Object.keys(r).forEach(d=>{t[d]=r[d]}),t.names=[],t.skips=[],t.formatters={};function e(d){let h=0;for(let v=0;v<d.length;v++)h=(h<<5)-h+d.charCodeAt(v),h|=0;return t.colors[Math.abs(h)%t.colors.length]}t.selectColor=e;function t(d){let h,v=null,y,w;function k(...I){if(!k.enabled)return;const A=k,j=Number(new Date),L=j-(h||j);A.diff=L,A.prev=h,A.curr=j,h=j,I[0]=t.coerce(I[0]),typeof I[0]!="string"&&I.unshift("%O");let x=0;I[0]=I[0].replace(/%([a-zA-Z%])/g,(G,K)=>{if(G==="%%")return"%";x++;const D=t.formatters[K];if(typeof D=="function"){const fe=I[x];G=D.call(A,fe),I.splice(x,1),x--}return G}),t.formatArgs.call(A,I),(A.log||t.log).apply(A,I)}return k.namespace=d,k.useColors=t.useColors(),k.color=t.selectColor(d),k.extend=n,k.destroy=t.destroy,Object.defineProperty(k,"enabled",{enumerable:!0,configurable:!1,get:()=>v!==null?v:(y!==t.namespaces&&(y=t.namespaces,w=t.enabled(d)),w),set:I=>{v=I}}),typeof t.init=="function"&&t.init(k),k}function n(d,h){const v=t(this.namespace+(typeof h>"u"?":":h)+d);return v.log=this.log,v}function i(d){t.save(d),t.namespaces=d,t.names=[],t.skips=[];const h=(typeof d=="string"?d:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const v of h)v[0]==="-"?t.skips.push(v.slice(1)):t.names.push(v)}function s(d,h){let v=0,y=0,w=-1,k=0;for(;v<d.length;)if(y<h.length&&(h[y]===d[v]||h[y]==="*"))h[y]==="*"?(w=y,k=v,y++):(v++,y++);else if(w!==-1)y=w+1,k++,v=k;else return!1;for(;y<h.length&&h[y]==="*";)y++;return y===h.length}function a(){const d=[...t.names,...t.skips.map(h=>"-"+h)].join(",");return t.enable(""),d}function c(d){for(const h of t.skips)if(s(d,h))return!1;for(const h of t.names)if(s(d,h))return!0;return!1}function o(d){return d instanceof Error?d.stack||d.message:d}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}var M5=x5;(function(r,e){e.formatArgs=n,e.save=i,e.load=s,e.useColors=t,e.storage=a(),e.destroy=(()=>{let o=!1;return()=>{o||(o=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function t(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let o;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(o=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(o[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function n(o){if(o[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+o[0]+(this.useColors?"%c ":" ")+"+"+r.exports.humanize(this.diff),!this.useColors)return;const l="color: "+this.color;o.splice(1,0,l,"color: inherit");let d=0,h=0;o[0].replace(/%[a-zA-Z%]/g,v=>{v!=="%%"&&(d++,v==="%c"&&(h=d))}),o.splice(h,0,l)}e.log=console.debug||console.log||(()=>{});function i(o){try{o?e.storage.setItem("debug",o):e.storage.removeItem("debug")}catch{}}function s(){let o;try{o=e.storage.getItem("debug")||e.storage.getItem("DEBUG")}catch{}return!o&&typeof process<"u"&&"env"in process&&(o=process.env.DEBUG),o}function a(){try{return localStorage}catch{}}r.exports=M5(e);const{formatters:c}=r.exports;c.j=function(o){try{return JSON.stringify(o)}catch(l){return"[UnexpectedJSONParseError]: "+l.message}}})(Ub,Ub.exports);var Ys=Ub.exports,D5=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ro,"__esModule",{value:!0});ro.Transport=ro.TransportError=void 0;const N5=Tl,L5=Cl,U5=Js,F5=of,j5=D5(Ys),B5=(0,j5.default)("engine.io-client:transport");class xO extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}ro.TransportError=xO;class q5 extends L5.Emitter{constructor(e){super(),this.writable=!1,(0,U5.installTimerFunctions)(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,n){return super.emitReserved("error",new xO(e,t,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(e){this.readyState==="open"?this.write(e):B5("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=(0,N5.decodePacket)(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return e.indexOf(":")===-1?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(e){const t=(0,F5.encode)(e);return t.length?"?"+t:""}}ro.Transport=q5;var W5=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(sf,"__esModule",{value:!0});sf.Polling=void 0;const V5=ro,H5=Js,ZE=Tl,G5=W5(Ys),Ds=(0,G5.default)("engine.io-client:polling");class z5 extends V5.Transport{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";const t=()=>{Ds("paused"),this.readyState="paused",e()};if(this._polling||!this.writable){let n=0;this._polling&&(Ds("we are currently polling - waiting to pause"),n++,this.once("pollComplete",function(){Ds("pre-pause polling complete"),--n||t()})),this.writable||(Ds("we are currently writing - waiting to pause"),n++,this.once("drain",function(){Ds("pre-pause writing complete"),--n||t()}))}else t()}_poll(){Ds("polling"),this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){Ds("polling got data %s",e);const t=n=>{if(this.readyState==="opening"&&n.type==="open"&&this.onOpen(),n.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(n)};(0,ZE.decodePayload)(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"?this._poll():Ds('ignoring poll - transport state "%s"',this.readyState))}doClose(){const e=()=>{Ds("writing close packet"),this.write([{type:"close"}])};this.readyState==="open"?(Ds("transport open - closing"),e()):(Ds("transport not open - deferring close"),this.once("open",e))}write(e){this.writable=!1,(0,ZE.encodePayload)(e,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return this.opts.timestampRequests!==!1&&(t[this.opts.timestampParam]=(0,H5.randomString)()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}}sf.Polling=z5;var Xv={};Object.defineProperty(Xv,"__esModule",{value:!0});Xv.hasCORS=void 0;let MO=!1;try{MO=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}Xv.hasCORS=MO;var K5=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ha,"__esModule",{value:!0});ha.XHR=ha.Request=ha.BaseXHR=void 0;const J5=sf,Y5=Cl,ek=Js,DO=Li,X5=Xv,Q5=K5(Ys),Fb=(0,Q5.default)("engine.io-client:polling");function Z5(){}class NO extends J5.Polling{constructor(e){if(super(e),typeof location<"u"){const t=location.protocol==="https:";let n=location.port;n||(n=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){const n=this.request({method:"POST",data:e});n.on("success",t),n.on("error",(i,s)=>{this.onError("xhr post error",i,s)})}doPoll(){Fb("xhr poll");const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,n)=>{this.onError("xhr poll error",t,n)}),this.pollXhr=e}}ha.BaseXHR=NO;let Uu=class qp extends Y5.Emitter{constructor(e,t,n){super(),this.createRequest=e,(0,ek.installTimerFunctions)(this,n),this._opts=n,this._method=n.method||"GET",this._uri=t,this._data=n.data!==void 0?n.data:null,this._create()}_create(){var e;const t=(0,ek.pick)(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(t);try{Fb("xhr open %s: %s",this._method,this._uri),n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let i in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(i)&&n.setRequestHeader(i,this._opts.extraHeaders[i])}}catch{}if(this._method==="POST")try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{n.setRequestHeader("Accept","*/*")}catch{}(e=this._opts.cookieJar)===null||e===void 0||e.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var i;n.readyState===3&&((i=this._opts.cookieJar)===null||i===void 0||i.parseCookies(n.getResponseHeader("set-cookie"))),n.readyState===4&&(n.status===200||n.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof n.status=="number"?n.status:0)},0))},Fb("xhr data %s",this._data),n.send(this._data)}catch(i){this.setTimeoutFn(()=>{this._onError(i)},0);return}typeof document<"u"&&(this._index=qp.requestsCount++,qp.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=Z5,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete qp.requests[this._index],this._xhr=null}}_onLoad(){const e=this._xhr.responseText;e!==null&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}};ha.Request=Uu;Uu.requestsCount=0;Uu.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",tk);else if(typeof addEventListener=="function"){const r="onpagehide"in DO.globalThisShim?"pagehide":"unload";addEventListener(r,tk,!1)}}function tk(){for(let r in Uu.requests)Uu.requests.hasOwnProperty(r)&&Uu.requests[r].abort()}const eV=function(){const r=LO({xdomain:!1});return r&&r.responseType!==null}();class tV extends NO{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=eV&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new Uu(LO,this.uri(),e)}}ha.XHR=tV;function LO(r){const e=r.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||X5.hasCORS))return new XMLHttpRequest}catch{}if(!e)try{return new DO.globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}var Jo={},rV=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Jo,"__esModule",{value:!0});Jo.WS=Jo.BaseWS=void 0;const nV=ro,rk=Js,iV=Tl,jb=Li,sV=rV(Ys),aV=(0,sV.default)("engine.io-client:websocket"),UO=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class FO extends nV.Transport{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,n=UO?{}:(0,rk.pick)(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,n)}catch(i){return this.emitReserved("error",i)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],i=t===e.length-1;(0,iV.encodePacket)(n,this.supportsBinary,s=>{try{this.doWrite(n,s)}catch{aV("websocket closed before onclose event")}i&&(0,jb.nextTick)(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=(0,rk.randomString)()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}Jo.BaseWS=FO;const $y=jb.globalThisShim.WebSocket||jb.globalThisShim.MozWebSocket;class oV extends FO{createSocket(e,t,n){return UO?new $y(e,t,n):t?new $y(e,t):new $y(e)}doWrite(e,t){this.ws.send(t)}}Jo.WS=oV;var uf={},uV=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(uf,"__esModule",{value:!0});uf.WT=void 0;const cV=ro,lV=Li,nk=Tl,dV=uV(Ys),od=(0,dV.default)("engine.io-client:webtransport");class fV extends cV.Transport{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{od("transport closed gracefully"),this.onClose()}).catch(e=>{od("transport closed due to %s",e),this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{const t=(0,nk.createPacketDecoderStream)(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),i=(0,nk.createPacketEncoderStream)();i.readable.pipeTo(e.writable),this._writer=i.writable.getWriter();const s=()=>{n.read().then(({done:c,value:o})=>{if(c){od("session is closed");return}od("received chunk: %o",o),this.onPacket(o),s()}).catch(c=>{od("an error occurred while reading: %s",c)})};s();const a={type:"open"};this.query.sid&&(a.data=`{"sid":"${this.query.sid}"}`),this._writer.write(a).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],i=t===e.length-1;this._writer.write(n).then(()=>{i&&(0,lV.nextTick)(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}uf.WT=fV;Object.defineProperty(nf,"__esModule",{value:!0});nf.transports=void 0;const hV=ha,pV=Jo,vV=uf;nf.transports={websocket:pV.WS,webtransport:vV.WT,polling:hV.XHR};var Qv={};Object.defineProperty(Qv,"__esModule",{value:!0});Qv.parse=yV;const gV=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,mV=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function yV(r){if(r.length>8e3)throw"URI too long";const e=r,t=r.indexOf("["),n=r.indexOf("]");t!=-1&&n!=-1&&(r=r.substring(0,t)+r.substring(t,n).replace(/:/g,";")+r.substring(n,r.length));let i=gV.exec(r||""),s={},a=14;for(;a--;)s[mV[a]]=i[a]||"";return t!=-1&&n!=-1&&(s.source=e,s.host=s.host.substring(1,s.host.length-1).replace(/;/g,":"),s.authority=s.authority.replace("[","").replace("]","").replace(/;/g,":"),s.ipv6uri=!0),s.pathNames=_V(s,s.path),s.queryKey=bV(s,s.query),s}function _V(r,e){const t=/\/{2,9}/g,n=e.replace(t,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&n.splice(0,1),e.slice(-1)=="/"&&n.splice(n.length-1,1),n}function bV(r,e){const t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,i,s){i&&(t[i]=s)}),t}var SV=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(eo,"__esModule",{value:!0});eo.Socket=eo.SocketWithUpgrade=eo.SocketWithoutUpgrade=void 0;const wV=nf,ik=Js,TV=of,sk=Qv,CV=Cl,jO=Tl,xy=Li,EV=SV(Ys),Hr=(0,EV.default)("engine.io-client:socket"),Bb=typeof addEventListener=="function"&&typeof removeEventListener=="function",Nd=[];Bb&&addEventListener("offline",()=>{Hr("closing %d connection(s) because the network was lost",Nd.length),Nd.forEach(r=>r())},!1);class to extends CV.Emitter{constructor(e,t){if(super(),this.binaryType=xy.defaultBinaryType,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e=="object"&&(t=e,e=null),e){const n=(0,sk.parse)(e);t.hostname=n.host,t.secure=n.protocol==="https"||n.protocol==="wss",t.port=n.port,n.query&&(t.query=n.query)}else t.host&&(t.hostname=(0,sk.parse)(t.host).host);(0,ik.installTimerFunctions)(this,t),this.secure=t.secure!=null?t.secure:typeof location<"u"&&location.protocol==="https:",t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=t.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(n=>{const i=n.prototype.name;this.transports.push(i),this._transportsByName[i]=n}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=(0,TV.decode)(this.opts.query)),Bb&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(Hr("adding listener for the 'offline' event"),this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Nd.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=(0,xy.createCookieJar)()),this._open()}createTransport(e){Hr('creating transport "%s"',e);const t=Object.assign({},this.opts.query);t.EIO=jO.protocol,t.transport=e,this.id&&(t.sid=this.id);const n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return Hr("options: %j",n),new this._transportsByName[e](n)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const e=this.opts.rememberUpgrade&&to.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){Hr("setting transport %s",e.name),this.transport&&(Hr("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){Hr("socket open"),this.readyState="open",to.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(Hr('socket receive: type "%s", data "%s"',e.type,e.data),this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data);break}else Hr('packet received with socket readyState "%s"',this.readyState)}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this._getWritablePackets();Hr("flushing %d packets in socket",e.length),this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let n=0;n<this.writeBuffer.length;n++){const i=this.writeBuffer[n].data;if(i&&(t+=(0,ik.byteLength)(i)),n>0&&t>this._maxPayload)return Hr("only send %d out of %d packets",n,this.writeBuffer.length),this.writeBuffer.slice(0,n);t+=2}return Hr("payload size is %d (max: %d)",t,this._maxPayload),this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(Hr("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,(0,xy.nextTick)(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,n){return this._sendPacket("message",e,t,n),this}send(e,t,n){return this._sendPacket("message",e,t,n),this}_sendPacket(e,t,n,i){if(typeof t=="function"&&(i=t,t=void 0),typeof n=="function"&&(i=n,n=null),this.readyState==="closing"||this.readyState==="closed")return;n=n||{},n.compress=n.compress!==!1;const s={type:e,data:t,options:n};this.emitReserved("packetCreate",s),this.writeBuffer.push(s),i&&this.once("flush",i),this.flush()}close(){const e=()=>{this._onClose("forced close"),Hr("socket closing - telling transport to close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},n=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():e()}):this.upgrading?n():e()),this}_onError(e){if(Hr("socket error %j",e),to.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return Hr("trying next transport"),this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(Hr('socket close with reason: "%s"',e),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Bb&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const n=Nd.indexOf(this._offlineEventListener);n!==-1&&(Hr("removing listener for the 'offline' event"),Nd.splice(n,1))}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}eo.SocketWithoutUpgrade=to;to.protocol=jO.protocol;class BO extends to{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){Hr("starting upgrade probes");for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}}_probe(e){Hr('probing transport "%s"',e);let t=this.createTransport(e),n=!1;to.priorWebsocketSuccess=!1;const i=()=>{n||(Hr('probe transport "%s" opened',e),t.send([{type:"ping",data:"probe"}]),t.once("packet",h=>{if(!n)if(h.type==="pong"&&h.data==="probe"){if(Hr('probe transport "%s" pong',e),this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;to.priorWebsocketSuccess=t.name==="websocket",Hr('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{n||this.readyState!=="closed"&&(Hr("changing transport and sending upgrade packet"),d(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{Hr('probe transport "%s" failed',e);const v=new Error("probe error");v.transport=t.name,this.emitReserved("upgradeError",v)}}))};function s(){n||(n=!0,d(),t.close(),t=null)}const a=h=>{const v=new Error("probe error: "+h);v.transport=t.name,s(),Hr('probe transport "%s" failed because of error: %s',e,h),this.emitReserved("upgradeError",v)};function c(){a("transport closed")}function o(){a("socket closed")}function l(h){t&&h.name!==t.name&&(Hr('"%s" works - aborting "%s"',h.name,t.name),s())}const d=()=>{t.removeListener("open",i),t.removeListener("error",a),t.removeListener("close",c),this.off("close",o),this.off("upgrading",l)};t.once("open",i),t.once("error",a),t.once("close",c),this.once("close",o),this.once("upgrading",l),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}}eo.SocketWithUpgrade=BO;let kV=class extends BO{constructor(e,t={}){const n=typeof e=="object"?e:t;(!n.transports||n.transports&&typeof n.transports[0]=="string")&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(i=>wV.transports[i]).filter(i=>!!i)),super(e,n)}};eo.Socket=kV;var Zv={};Object.defineProperty(Zv,"__esModule",{value:!0});Zv.Fetch=void 0;const RV=sf;class PV extends RV.Polling{doPoll(){this._fetch().then(e=>{if(!e.ok)return this.onError("fetch read error",e.status,e);e.text().then(t=>this.onData(t))}).catch(e=>{this.onError("fetch read error",e)})}doWrite(e,t){this._fetch(e).then(n=>{if(!n.ok)return this.onError("fetch write error",n.status,n);t()}).catch(n=>{this.onError("fetch write error",n)})}_fetch(e){var t;const n=e!==void 0,i=new Headers(this.opts.extraHeaders);return n&&i.set("content-type","text/plain;charset=UTF-8"),(t=this.socket._cookieJar)===null||t===void 0||t.appendCookies(i),fetch(this.uri(),{method:n?"POST":"GET",body:n?e:null,headers:i,credentials:this.opts.withCredentials?"include":"omit"}).then(s=>{var a;return(a=this.socket._cookieJar)===null||a===void 0||a.parseCookies(s.headers.getSetCookie()),s})}}Zv.Fetch=PV;(function(r){Object.defineProperty(r,"__esModule",{value:!0}),r.WebTransport=r.WebSocket=r.NodeWebSocket=r.XHR=r.NodeXHR=r.Fetch=r.nextTick=r.parse=r.installTimerFunctions=r.transports=r.TransportError=r.Transport=r.protocol=r.SocketWithUpgrade=r.SocketWithoutUpgrade=r.Socket=void 0;const e=eo;Object.defineProperty(r,"Socket",{enumerable:!0,get:function(){return e.Socket}});var t=eo;Object.defineProperty(r,"SocketWithoutUpgrade",{enumerable:!0,get:function(){return t.SocketWithoutUpgrade}}),Object.defineProperty(r,"SocketWithUpgrade",{enumerable:!0,get:function(){return t.SocketWithUpgrade}}),r.protocol=e.Socket.protocol;var n=ro;Object.defineProperty(r,"Transport",{enumerable:!0,get:function(){return n.Transport}}),Object.defineProperty(r,"TransportError",{enumerable:!0,get:function(){return n.TransportError}});var i=nf;Object.defineProperty(r,"transports",{enumerable:!0,get:function(){return i.transports}});var s=Js;Object.defineProperty(r,"installTimerFunctions",{enumerable:!0,get:function(){return s.installTimerFunctions}});var a=Qv;Object.defineProperty(r,"parse",{enumerable:!0,get:function(){return a.parse}});var c=Li;Object.defineProperty(r,"nextTick",{enumerable:!0,get:function(){return c.nextTick}});var o=Zv;Object.defineProperty(r,"Fetch",{enumerable:!0,get:function(){return o.Fetch}});var l=ha;Object.defineProperty(r,"NodeXHR",{enumerable:!0,get:function(){return l.XHR}});var d=ha;Object.defineProperty(r,"XHR",{enumerable:!0,get:function(){return d.XHR}});var h=Jo;Object.defineProperty(r,"NodeWebSocket",{enumerable:!0,get:function(){return h.WS}});var v=Jo;Object.defineProperty(r,"WebSocket",{enumerable:!0,get:function(){return v.WS}});var y=uf;Object.defineProperty(r,"WebTransport",{enumerable:!0,get:function(){return y.WT}})})(Jv);var IV=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty($w,"__esModule",{value:!0});$w.url=$V;const AV=Jv,OV=IV(Ys),ak=(0,OV.default)("socket.io-client:url");function $V(r,e="",t){let n=r;t=t||typeof location<"u"&&location,r==null&&(r=t.protocol+"//"+t.host),typeof r=="string"&&(r.charAt(0)==="/"&&(r.charAt(1)==="/"?r=t.protocol+r:r=t.host+r),/^(https?|wss?):\/\//.test(r)||(ak("protocol-less url %s",r),typeof t<"u"?r=t.protocol+"//"+r:r="https://"+r),ak("parse %s",r),n=(0,AV.parse)(r)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const s=n.host.indexOf(":")!==-1?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+s+":"+n.port+e,n.href=n.protocol+"://"+s+(t&&t.port===n.port?"":":"+n.port),n}var eg={},cf={},Qi={},tg={},lf={};Object.defineProperty(lf,"__esModule",{value:!0});lf.isBinary=WO;lf.hasBinary=Wp;const xV=typeof ArrayBuffer=="function",MV=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r.buffer instanceof ArrayBuffer,qO=Object.prototype.toString,DV=typeof Blob=="function"||typeof Blob<"u"&&qO.call(Blob)==="[object BlobConstructor]",NV=typeof File=="function"||typeof File<"u"&&qO.call(File)==="[object FileConstructor]";function WO(r){return xV&&(r instanceof ArrayBuffer||MV(r))||DV&&r instanceof Blob||NV&&r instanceof File}function Wp(r,e){if(!r||typeof r!="object")return!1;if(Array.isArray(r)){for(let t=0,n=r.length;t<n;t++)if(Wp(r[t]))return!0;return!1}if(WO(r))return!0;if(r.toJSON&&typeof r.toJSON=="function"&&arguments.length===1)return Wp(r.toJSON(),!0);for(const t in r)if(Object.prototype.hasOwnProperty.call(r,t)&&Wp(r[t]))return!0;return!1}Object.defineProperty(tg,"__esModule",{value:!0});tg.deconstructPacket=UV;tg.reconstructPacket=FV;const LV=lf;function UV(r){const e=[],t=r.data,n=r;return n.data=qb(t,e),n.attachments=e.length,{packet:n,buffers:e}}function qb(r,e){if(!r)return r;if((0,LV.isBinary)(r)){const t={_placeholder:!0,num:e.length};return e.push(r),t}else if(Array.isArray(r)){const t=new Array(r.length);for(let n=0;n<r.length;n++)t[n]=qb(r[n],e);return t}else if(typeof r=="object"&&!(r instanceof Date)){const t={};for(const n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=qb(r[n],e));return t}return r}function FV(r,e){return r.data=Wb(r.data,e),delete r.attachments,r}function Wb(r,e){if(!r)return r;if(r&&r._placeholder===!0){if(typeof r.num=="number"&&r.num>=0&&r.num<e.length)return e[r.num];throw new Error("illegal attachments")}else if(Array.isArray(r))for(let t=0;t<r.length;t++)r[t]=Wb(r[t],e);else if(typeof r=="object")for(const t in r)Object.prototype.hasOwnProperty.call(r,t)&&(r[t]=Wb(r[t],e));return r}Object.defineProperty(Qi,"__esModule",{value:!0});Qi.Decoder=Qi.Encoder=Qi.PacketType=Qi.protocol=void 0;Qi.isPacketValid=KV;const jV=Cl,VO=tg,HO=lf,BV=Ys,Vb=(0,BV.default)("socket.io-parser"),GO=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];Qi.protocol=5;var Lr;(function(r){r[r.CONNECT=0]="CONNECT",r[r.DISCONNECT=1]="DISCONNECT",r[r.EVENT=2]="EVENT",r[r.ACK=3]="ACK",r[r.CONNECT_ERROR=4]="CONNECT_ERROR",r[r.BINARY_EVENT=5]="BINARY_EVENT",r[r.BINARY_ACK=6]="BINARY_ACK"})(Lr||(Qi.PacketType=Lr={}));class qV{constructor(e){this.replacer=e}encode(e){return Vb("encoding packet %j",e),(e.type===Lr.EVENT||e.type===Lr.ACK)&&(0,HO.hasBinary)(e)?this.encodeAsBinary({type:e.type===Lr.EVENT?Lr.BINARY_EVENT:Lr.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===Lr.BINARY_EVENT||e.type===Lr.BINARY_ACK)&&(t+=e.attachments+"-"),e.nsp&&e.nsp!=="/"&&(t+=e.nsp+","),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),Vb("encoded %j as %s",e,t),t}encodeAsBinary(e){const t=(0,VO.deconstructPacket)(e),n=this.encodeAsString(t.packet),i=t.buffers;return i.unshift(n),i}}Qi.Encoder=qV;class xw extends jV.Emitter{constructor(e){super(),this.reviver=e}add(e){let t;if(typeof e=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const n=t.type===Lr.BINARY_EVENT;n||t.type===Lr.BINARY_ACK?(t.type=n?Lr.EVENT:Lr.ACK,this.reconstructor=new WV(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if((0,HO.isBinary)(e)||e.base64)if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+e)}decodeString(e){let t=0;const n={type:Number(e.charAt(0))};if(Lr[n.type]===void 0)throw new Error("unknown packet type "+n.type);if(n.type===Lr.BINARY_EVENT||n.type===Lr.BINARY_ACK){const s=t+1;for(;e.charAt(++t)!=="-"&&t!=e.length;);const a=e.substring(s,t);if(a!=Number(a)||e.charAt(t)!=="-")throw new Error("Illegal attachments");n.attachments=Number(a)}if(e.charAt(t+1)==="/"){const s=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););n.nsp=e.substring(s,t)}else n.nsp="/";const i=e.charAt(t+1);if(i!==""&&Number(i)==i){const s=t+1;for(;++t;){const a=e.charAt(t);if(a==null||Number(a)!=a){--t;break}if(t===e.length)break}n.id=Number(e.substring(s,t+1))}if(e.charAt(++t)){const s=this.tryParse(e.substr(t));if(xw.isPayloadValid(n.type,s))n.data=s;else throw new Error("invalid payload")}return Vb("decoded %s as %j",e,n),n}tryParse(e){try{return JSON.parse(e,this.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case Lr.CONNECT:return dv(t);case Lr.DISCONNECT:return t===void 0;case Lr.CONNECT_ERROR:return typeof t=="string"||dv(t);case Lr.EVENT:case Lr.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&GO.indexOf(t[0])===-1);case Lr.ACK:case Lr.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}Qi.Decoder=xw;class WV{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const t=(0,VO.reconstructPacket)(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}function VV(r){return typeof r=="string"}const HV=Number.isInteger||function(r){return typeof r=="number"&&isFinite(r)&&Math.floor(r)===r};function GV(r){return r===void 0||HV(r)}function dv(r){return Object.prototype.toString.call(r)==="[object Object]"}function zV(r,e){switch(r){case Lr.CONNECT:return e===void 0||dv(e);case Lr.DISCONNECT:return e===void 0;case Lr.EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&GO.indexOf(e[0])===-1);case Lr.ACK:return Array.isArray(e);case Lr.CONNECT_ERROR:return typeof e=="string"||dv(e);default:return!1}}function KV(r){return VV(r.nsp)&&GV(r.id)&&zV(r.type,r.data)}var rg={};Object.defineProperty(rg,"__esModule",{value:!0});rg.on=JV;function JV(r,e,t){return r.on(e,t),function(){r.off(e,t)}}var YV=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(cf,"__esModule",{value:!0});cf.Socket=void 0;const Ns=Qi,Ah=rg,XV=Cl,QV=YV(Ys),_n=(0,QV.default)("socket.io-client:socket"),ZV=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class eH extends XV.Emitter{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[(0,Ah.on)(e,"open",this.onopen.bind(this)),(0,Ah.on)(e,"packet",this.onpacket.bind(this)),(0,Ah.on)(e,"error",this.onerror.bind(this)),(0,Ah.on)(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var n,i,s;if(ZV.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const a={type:Ns.PacketType.EVENT,data:t};if(a.options={},a.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){const d=this.ids++;_n("emitting packet with ack id %d",d);const h=t.pop();this._registerAckCallback(d,h),a.id=d}const c=(i=(n=this.io.engine)===null||n===void 0?void 0:n.transport)===null||i===void 0?void 0:i.writable,o=this.connected&&!(!((s=this.io.engine)===null||s===void 0)&&s._hasPingExpired());return this.flags.volatile&&!c?_n("discard packet as the transport is not currently writable"):o?(this.notifyOutgoingListeners(a),this.packet(a)):this.sendBuffer.push(a),this.flags={},this}_registerAckCallback(e,t){var n;const i=(n=this.flags.timeout)!==null&&n!==void 0?n:this._opts.ackTimeout;if(i===void 0){this.acks[e]=t;return}const s=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let c=0;c<this.sendBuffer.length;c++)this.sendBuffer[c].id===e&&(_n("removing packet with ack id %d from the buffer",e),this.sendBuffer.splice(c,1));_n("event with ack id %d has timed out after %d ms",e,i),t.call(this,new Error("operation has timed out"))},i),a=(...c)=>{this.io.clearTimeoutFn(s),t.apply(this,c)};a.withError=!0,this.acks[e]=a}emitWithAck(e,...t){return new Promise((n,i)=>{const s=(a,c)=>a?i(a):n(c);s.withError=!0,t.push(s),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((i,...s)=>n!==this._queue[0]?_n("packet [%d] already acknowledged",n.id):(i!==null?n.tryCount>this._opts.retries&&(_n("packet [%d] is discarded after %d tries",n.id,n.tryCount),this._queue.shift(),t&&t(i)):(_n("packet [%d] was successfully sent",n.id),this._queue.shift(),t&&t(null,...s)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(_n("draining queue"),!this.connected||this._queue.length===0)return;const t=this._queue[0];if(t.pending&&!e){_n("packet [%d] has already been sent and is waiting for an ack",t.id);return}t.pending=!0,t.tryCount++,_n("sending packet [%d] (try n°%d)",t.id,t.tryCount),this.flags=t.flags,this.emit.apply(this,t.args)}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){_n("transport is open - connecting"),typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:Ns.PacketType.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){_n("close (%s)",e),this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(n=>String(n.id)===e)){const n=this.acks[e];delete this.acks[e],n.withError&&n.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case Ns.PacketType.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Ns.PacketType.EVENT:case Ns.PacketType.BINARY_EVENT:this.onevent(e);break;case Ns.PacketType.ACK:case Ns.PacketType.BINARY_ACK:this.onack(e);break;case Ns.PacketType.DISCONNECT:this.ondisconnect();break;case Ns.PacketType.CONNECT_ERROR:this.destroy();const n=new Error(e.data.message);n.data=e.data.data,this.emitReserved("connect_error",n);break}}onevent(e){const t=e.data||[];_n("emitting event %j",t),e.id!=null&&(_n("attaching ack callback to event"),t.push(this.ack(e.id))),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let n=!1;return function(...i){n||(n=!0,_n("sending ack %j",i),t.packet({type:Ns.PacketType.ACK,id:e,data:i}))}}onack(e){const t=this.acks[e.id];if(typeof t!="function"){_n("bad ack %s",e.id);return}delete this.acks[e.id],_n("calling ack %s with %j",e.id,e.data),t.withError&&e.data.unshift(null),t.apply(this,e.data)}onconnect(e,t){_n("socket connected with id %s",e),this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){_n("server disconnect (%s)",this.nsp),this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&(_n("performing disconnect (%s)",this.nsp),this.packet({type:Ns.PacketType.DISCONNECT})),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const n of t)n.apply(this,e.data)}}}cf.Socket=eH;var Mw={};Object.defineProperty(Mw,"__esModule",{value:!0});Mw.Backoff=El;function El(r){r=r||{},this.ms=r.min||100,this.max=r.max||1e4,this.factor=r.factor||2,this.jitter=r.jitter>0&&r.jitter<=1?r.jitter:0,this.attempts=0}El.prototype.duration=function(){var r=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),t=Math.floor(e*this.jitter*r);r=Math.floor(e*10)&1?r+t:r-t}return Math.min(r,this.max)|0};El.prototype.reset=function(){this.attempts=0};El.prototype.setMin=function(r){this.ms=r};El.prototype.setMax=function(r){this.max=r};El.prototype.setJitter=function(r){this.jitter=r};var tH=Ye&&Ye.__createBinding||(Object.create?function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}:function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]}),rH=Ye&&Ye.__setModuleDefault||(Object.create?function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}:function(r,e){r.default=e}),nH=Ye&&Ye.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&tH(e,r,t);return rH(e,r),e},iH=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(eg,"__esModule",{value:!0});eg.Manager=void 0;const My=Jv,sH=cf,aH=nH(Qi),Tu=rg,oH=Mw,uH=Cl,cH=iH(Ys),Vn=(0,cH.default)("socket.io-client:manager");class lH extends uH.Emitter{constructor(e,t){var n;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(t=e,e=void 0),t=t||{},t.path=t.path||"/socket.io",this.opts=t,(0,My.installTimerFunctions)(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor((n=t.randomizationFactor)!==null&&n!==void 0?n:.5),this.backoff=new oH.Backoff({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;const i=t.parser||aH;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(Vn("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;Vn("opening %s",this.uri),this.engine=new My.Socket(this.uri,this.opts);const t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const i=(0,Tu.on)(t,"open",function(){n.onopen(),e&&e()}),s=c=>{Vn("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",c),e?e(c):this.maybeReconnectOnOpen()},a=(0,Tu.on)(t,"error",s);if(this._timeout!==!1){const c=this._timeout;Vn("connect attempt will timeout after %d",c);const o=this.setTimeoutFn(()=>{Vn("connect attempt timed out after %d",c),i(),s(new Error("timeout")),t.close()},c);this.opts.autoUnref&&o.unref(),this.subs.push(()=>{this.clearTimeoutFn(o)})}return this.subs.push(i),this.subs.push(a),this}connect(e){return this.open(e)}onopen(){Vn("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push((0,Tu.on)(e,"ping",this.onping.bind(this)),(0,Tu.on)(e,"data",this.ondata.bind(this)),(0,Tu.on)(e,"error",this.onerror.bind(this)),(0,Tu.on)(e,"close",this.onclose.bind(this)),(0,Tu.on)(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){(0,My.nextTick)(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){Vn("error",e),this.emitReserved("error",e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new sH.Socket(this,e,t),this.nsps[e]=n),n}_destroy(e){const t=Object.keys(this.nsps);for(const n of t)if(this.nsps[n].active){Vn("socket %s is still active, skipping close",n);return}this._close()}_packet(e){Vn("writing packet %j",e);const t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){Vn("cleanup"),this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){Vn("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var n;Vn("closed due to %s",e),this.cleanup(),(n=this.engine)===null||n===void 0||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)Vn("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();Vn("will wait %dms before reconnect attempt",t),this._reconnecting=!0;const n=this.setTimeoutFn(()=>{e.skipReconnect||(Vn("attempting reconnect"),this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(i=>{i?(Vn("reconnect attempt error"),e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",i)):(Vn("reconnect success"),e.onreconnect())}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}eg.Manager=lH;(function(r,e){var t=Ye&&Ye.__importDefault||function(v){return v&&v.__esModule?v:{default:v}};Object.defineProperty(e,"__esModule",{value:!0}),e.WebTransport=e.WebSocket=e.NodeWebSocket=e.XHR=e.NodeXHR=e.Fetch=e.Socket=e.Manager=e.protocol=void 0,e.io=l,e.connect=l,e.default=l;const n=$w,i=eg;Object.defineProperty(e,"Manager",{enumerable:!0,get:function(){return i.Manager}});const s=cf;Object.defineProperty(e,"Socket",{enumerable:!0,get:function(){return s.Socket}});const c=(0,t(Ys).default)("socket.io-client"),o={};function l(v,y){typeof v=="object"&&(y=v,v=void 0),y=y||{};const w=(0,n.url)(v,y.path||"/socket.io"),k=w.source,I=w.id,A=w.path,j=o[I]&&A in o[I].nsps,L=y.forceNew||y["force new connection"]||y.multiplex===!1||j;let x;return L?(c("ignoring socket cache for %s",k),x=new i.Manager(k,y)):(o[I]||(c("new io instance for %s",k),o[I]=new i.Manager(k,y)),x=o[I]),w.query&&!y.query&&(y.query=w.queryKey),x.socket(w.path,y)}Object.assign(l,{Manager:i.Manager,Socket:s.Socket,io:l,connect:l});var d=Qi;Object.defineProperty(e,"protocol",{enumerable:!0,get:function(){return d.protocol}});var h=Jv;Object.defineProperty(e,"Fetch",{enumerable:!0,get:function(){return h.Fetch}}),Object.defineProperty(e,"NodeXHR",{enumerable:!0,get:function(){return h.NodeXHR}}),Object.defineProperty(e,"XHR",{enumerable:!0,get:function(){return h.XHR}}),Object.defineProperty(e,"NodeWebSocket",{enumerable:!0,get:function(){return h.NodeWebSocket}}),Object.defineProperty(e,"WebSocket",{enumerable:!0,get:function(){return h.WebSocket}}),Object.defineProperty(e,"WebTransport",{enumerable:!0,get:function(){return h.WebTransport}}),r.exports=l})(Lb,Lb.exports);var zO=Lb.exports,KO={exports:{}};(function(r,e){(function(t){r.exports=t()})(function(){var t=function(p,g,b){for(var _=b,S=0,T=p.length;S<T;S++)_=g(_,p[S],S,p);return _},n=function(p,g){return t(p,function(b,_,S,T){return g(_,S,T)?b.concat(_):b},[])},i=function(p,g){return t(p,function(b,_,S,T){return b.concat(g(_,S,T))},[])},s=function(p,g){return t(p,function(b,_,S,T){return b===!0||_===g},!1)},a=!{toString:null}.propertyIsEnumerable("toString"),c=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],o=function(p){var g=[],b;for(b in p)Object.prototype.hasOwnProperty.call(p,b)&&g.push(b);if(!a)return g;for(var _=0,S=c.length;_<S;_++)Object.prototype.hasOwnProperty.call(p,c[_])&&g.push(c[_]);return g},l=function(p){return Object.prototype.toString.call(p)==="[object Array]"},d=function(p){return p<10?"0"+p:p},h=function(){var p=new Date;return p.getUTCFullYear()+"-"+d(p.getUTCMonth()+1)+"-"+d(p.getUTCDate())+"T"+d(p.getUTCHours())+":"+d(p.getUTCMinutes())+":"+d(p.getUTCSeconds())+"."+(p.getUTCMilliseconds()/1e3).toFixed(3).slice(2,5)+"Z"},v={map:i,reduce:t,filter:n,includes:s,keys:o,isArray:l,isoDate:h},y={};y.intRange=function(p,g){return p===void 0&&(p=1),g===void 0&&(g=1/0),function(b){return typeof b=="number"&&parseInt(""+b,10)===b&&b>=p&&b<=g}},y.stringWithLength=function(p){return typeof p=="string"&&!!p.length};var w={},k=v.filter,I=v.reduce,A=v.keys,j=v.isArray,L=v.includes,x=y.intRange,B=y.stringWithLength;w.schema={apiKey:{defaultValue:function(){return null},message:"is required",validate:B},appVersion:{defaultValue:function(){return null},message:"should be a string",validate:function(p){return p===null||B(p)}},appType:{defaultValue:function(){return null},message:"should be a string",validate:function(p){return p===null||B(p)}},autoNotify:{defaultValue:function(){return!0},message:"should be true|false",validate:function(p){return p===!0||p===!1}},beforeSend:{defaultValue:function(){return[]},message:"should be a function or array of functions",validate:function(p){return typeof p=="function"||j(p)&&k(p,function(g){return typeof g=="function"}).length===p.length}},endpoints:{defaultValue:function(){return{notify:"https://notify.bugsnag.com",sessions:"https://sessions.bugsnag.com"}},message:"should be an object containing endpoint URLs { notify, sessions }. sessions is optional if autoCaptureSessions=false",validate:function(p,g){return p&&typeof p=="object"&&B(p.notify)&&(g.autoCaptureSessions===!1||B(p.sessions))&&k(A(p),function(b){return!L(["notify","sessions"],b)}).length===0}},autoCaptureSessions:{defaultValue:function(p,g){return g.endpoints===void 0||!!g.endpoints&&!!g.endpoints.sessions},message:"should be true|false",validate:function(p){return p===!0||p===!1}},notifyReleaseStages:{defaultValue:function(){return null},message:"should be an array of strings",validate:function(p){return p===null||j(p)&&k(p,function(g){return typeof g=="string"}).length===p.length}},releaseStage:{defaultValue:function(){return"production"},message:"should be a string",validate:function(p){return typeof p=="string"&&p.length}},maxBreadcrumbs:{defaultValue:function(){return 20},message:"should be a number ≤40",validate:function(p){return x(0,40)(p)}},autoBreadcrumbs:{defaultValue:function(){return!0},message:"should be true|false",validate:function(p){return typeof p=="boolean"}},user:{defaultValue:function(){return null},message:"(object) user should be an object",validate:function(p){return typeof p=="object"}},metaData:{defaultValue:function(){return null},message:"should be an object",validate:function(p){return typeof p=="object"}},logger:{defaultValue:function(){},message:"should be null or an object with methods { debug, info, warn, error }",validate:function(p){return!p||p&&I(["debug","info","warn","error"],function(g,b){return g&&typeof p[b]=="function"},!0)}},filters:{defaultValue:function(){return["password"]},message:"should be an array of strings|regexes",validate:function(p){return j(p)&&p.length===k(p,function(g){return typeof g=="string"||g&&typeof g.test=="function"}).length}}},w.mergeDefaults=function(p,g){if(!p||!g)throw new Error("opts and schema objects are required");return I(A(g),function(b,_){return b[_]=p[_]!==void 0?p[_]:g[_].defaultValue(p[_],p),b},{})},w.validate=function(p,g){if(!p||!g)throw new Error("opts and schema objects are required");var b=I(A(g),function(_,S){return g[S].validate(p[S],p)?_:_.concat({key:S,message:g[S].message,value:p[S]})},[]);return{valid:!b.length,errors:b}};function G(){return G=Object.assign||function(p){for(var g=1;g<arguments.length;g++){var b=arguments[g];for(var _ in b)Object.prototype.hasOwnProperty.call(b,_)&&(p[_]=b[_])}return p},G.apply(this,arguments)}var K=w.schema,D=v.map,fe=y.stringWithLength,X={releaseStage:{defaultValue:function(){return/^localhost(:\d+)?$/.test(window.location.host)?"development":"production"},message:"should be set",validate:fe},logger:G({},K.logger,{defaultValue:function(){return typeof console<"u"&&typeof console.debug=="function"?pe():void 0}})},pe=function(){var p={},g=console.log;return D(["debug","info","warn","error"],function(b){var _=console[b];p[b]=typeof _=="function"?_.bind(console,"[bugsnag]"):g.bind(console,"[bugsnag]")}),p},Q=v.isoDate,Oe=function(){function p(b,_,S,T){b===void 0&&(b="[anonymous]"),_===void 0&&(_={}),S===void 0&&(S="manual"),T===void 0&&(T=Q()),this.type=S,this.name=b,this.metaData=_,this.timestamp=T}var g=p.prototype;return g.toJSON=function(){return{type:this.type,name:this.name,timestamp:this.timestamp,metaData:this.metaData}},p}(),Ve=Oe,Ze=function(p,g,b){var _=p.length,S=0,T=function(){if(S>=_)return b(null,!1);g(p[S],function(C,P){if(C)return b(C,!1);if(P===!0)return b(null,!0);S++,T()})};T()},Xe=function(p){return p.app&&typeof p.app.releaseStage=="string"?p.app.releaseStage:p.config.releaseStage},Re=Je;function Je(p){switch(Object.prototype.toString.call(p)){case"[object Error]":return!0;case"[object Exception]":return!0;case"[object DOMException]":return!0;default:return p instanceof Error}}var Ke=Re,Y=function(p,g){return function(b,_){if(typeof b!="function")return _(null,!1);try{if(b.length!==2){var S=b(p);return S&&typeof S.then=="function"?S.then(function(T){return setTimeout(function(){return _(null,Ce(p,T))},0)},function(T){setTimeout(function(){return g(T),_(null,!1)})}):_(null,Ce(p,S))}b(p,function(T,C){if(T)return g(T),_(null,!1);_(null,Ce(p,C))})}catch(T){g(T),_(null,!1)}}},Ce=function(p,g){return p.isIgnored()||g===!1},Et={};(function(p,g){typeof Et=="object"?Et=g():p.StackFrame=g()})(this,function(){function p(Se){return!isNaN(parseFloat(Se))&&isFinite(Se)}function g(Se){return Se.charAt(0).toUpperCase()+Se.substring(1)}function b(Se){return function(){return this[Se]}}var _=["isConstructor","isEval","isNative","isToplevel"],S=["columnNumber","lineNumber"],T=["fileName","functionName","source"],C=["args"],P=_.concat(S,T,C);function q(Se){if(Se instanceof Object)for(var Ge=0;Ge<P.length;Ge++)Se.hasOwnProperty(P[Ge])&&Se[P[Ge]]!==void 0&&this["set"+g(P[Ge])](Se[P[Ge]])}q.prototype={getArgs:function(){return this.args},setArgs:function(Se){if(Object.prototype.toString.call(Se)!=="[object Array]")throw new TypeError("Args must be an Array");this.args=Se},getEvalOrigin:function(){return this.evalOrigin},setEvalOrigin:function(Se){if(Se instanceof q)this.evalOrigin=Se;else if(Se instanceof Object)this.evalOrigin=new q(Se);else throw new TypeError("Eval Origin must be an Object or StackFrame")},toString:function(){var Se=this.getFunctionName()||"{anonymous}",Ge="("+(this.getArgs()||[]).join(",")+")",gt=this.getFileName()?"@"+this.getFileName():"",et=p(this.getLineNumber())?":"+this.getLineNumber():"",ct=p(this.getColumnNumber())?":"+this.getColumnNumber():"";return Se+Ge+gt+et+ct}};for(var H=0;H<_.length;H++)q.prototype["get"+g(_[H])]=b(_[H]),q.prototype["set"+g(_[H])]=function(Se){return function(Ge){this[Se]=!!Ge}}(_[H]);for(var J=0;J<S.length;J++)q.prototype["get"+g(S[J])]=b(S[J]),q.prototype["set"+g(S[J])]=function(Se){return function(Ge){if(!p(Ge))throw new TypeError(Se+" must be a Number");this[Se]=Number(Ge)}}(S[J]);for(var ae=0;ae<T.length;ae++)q.prototype["get"+g(T[ae])]=b(T[ae]),q.prototype["set"+g(T[ae])]=function(Se){return function(Ge){this[Se]=String(Ge)}}(T[ae]);return q});var Nt={};(function(p,g){typeof Nt=="object"?Nt=g(Et):p.ErrorStackParser=g(p.StackFrame)})(this,function(g){var b=/(^|@)\S+\:\d+/,_=/^\s*at .*(\S+\:\d+|\(native\))/m,S=/^(eval@)?(\[native code\])?$/;return{parse:function(C){if(typeof C.stacktrace<"u"||typeof C["opera#sourceloc"]<"u")return this.parseOpera(C);if(C.stack&&C.stack.match(_))return this.parseV8OrIE(C);if(C.stack)return this.parseFFOrSafari(C);throw new Error("Cannot parse given Error object")},extractLocation:function(C){if(C.indexOf(":")===-1)return[C];var P=/(.+?)(?:\:(\d+))?(?:\:(\d+))?$/,q=P.exec(C.replace(/[\(\)]/g,""));return[q[1],q[2]||void 0,q[3]||void 0]},parseV8OrIE:function(C){var P=C.stack.split(`
|
|
3
3
|
`).filter(function(q){return!!q.match(_)},this);return P.map(function(q){q.indexOf("(eval ")>-1&&(q=q.replace(/eval code/g,"eval").replace(/(\(eval at [^\()]*)|(\)\,.*$)/g,""));var H=q.replace(/^\s+/,"").replace(/\(eval code/g,"("),J=H.match(/ (\((.+):(\d+):(\d+)\)$)/);H=J?H.replace(J[0],""):H;var ae=H.split(/\s+/).slice(1),Se=this.extractLocation(J?J[1]:ae.pop()),Ge=ae.join(" ")||void 0,gt=["eval","<anonymous>"].indexOf(Se[0])>-1?void 0:Se[0];return new g({functionName:Ge,fileName:gt,lineNumber:Se[1],columnNumber:Se[2],source:q})},this)},parseFFOrSafari:function(C){var P=C.stack.split(`
|
|
4
4
|
`).filter(function(q){return!q.match(S)},this);return P.map(function(q){if(q.indexOf(" > eval")>-1&&(q=q.replace(/ line (\d+)(?: > eval line \d+)* > eval\:\d+\:\d+/g,":$1")),q.indexOf("@")===-1&&q.indexOf(":")===-1)return new g({functionName:q});var H=/((.*".+"[^@]*)?[^@]*)(?:@)/,J=q.match(H),ae=J&&J[1]?J[1]:void 0,Se=this.extractLocation(q.replace(H,""));return new g({functionName:ae,fileName:Se[0],lineNumber:Se[1],columnNumber:Se[2],source:q})},this)},parseOpera:function(C){return!C.stacktrace||C.message.indexOf(`
|
|
5
5
|
`)>-1&&C.message.split(`
|
|
@@ -98,7 +98,7 @@ a=extmap-allow-mixed`)!==-1){const s=i.sdp.split(`
|
|
|
98
98
|
`).filter(a=>a.trim()!=="a=extmap-allow-mixed").join(`
|
|
99
99
|
`);r.RTCSessionDescription&&i instanceof r.RTCSessionDescription?arguments[0]=new r.RTCSessionDescription({type:i.type,sdp:s}):i.sdp=s}return t.apply(this,arguments)}}function Gp(r,e){if(!(r.RTCPeerConnection&&r.RTCPeerConnection.prototype))return;const t=r.RTCPeerConnection.prototype.addIceCandidate;!t||t.length===0||(r.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():t.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}const jH=Object.freeze(Object.defineProperty({__proto__:null,removeExtmapAllowMixed:tS,shimAddIceCandidateNullOrEmpty:Gp,shimConnectionState:eS,shimMaxMessageSize:Pd,shimRTCIceCandidate:Hp,shimSendThrowTypeError:Id},Symbol.toStringTag,{value:"Module"}));function BH({window:r}={},e={shimChrome:!0,shimFirefox:!0,shimEdge:!0,shimSafari:!0}){const t=Bw,n=$H(r),i={browserDetails:n,commonShim:jH,extractVersion:Rd,disableLog:AH,disableWarnings:OH};switch(n.browser){case"chrome":if(!mk||!Xb||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),i;if(n.version===null)return t("Chrome shim can not determine version, not shimming."),i;t("adapter.js shimming chrome."),i.browserShim=mk,Gp(r,n),n$(r,n),i$(r),Xb(r,n),s$(r),l$(r,n),a$(r),o$(r),u$(r),d$(r,n),Hp(r),eS(r),Pd(r,n),Id(r),tS(r,n);break;case"firefox":if(!Sk||!Zb||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),i;t("adapter.js shimming firefox."),i.browserShim=Sk,Gp(r,n),m$(r,n),Zb(r,n),y$(r),S$(r),_$(r),b$(r),w$(r),T$(r),C$(r),E$(r),k$(r),Hp(r),eS(r),Pd(r,n),Id(r);break;case"edge":if(!bk||!Qb||!e.shimEdge)return t("MS edge shim is not included in this adapter release."),i;t("adapter.js shimming edge."),i.browserShim=bk,p$(r),v$(r),Qb(r,n),g$(r),Pd(r,n),Id(r);break;case"safari":if(!wk||!e.shimSafari)return t("Safari shim is not included in this adapter release."),i;t("adapter.js shimming safari."),i.browserShim=wk,Gp(r,n),$$(r),M$(r),I$(r),R$(r),P$(r),x$(r),A$(r),D$(r),Hp(r),Pd(r,n),Id(r),tS(r,n);break;default:t("Unsupported browser!");break}return i}BH({window:typeof window>"u"?void 0:window});var ya={},N$={},L$={exports:{}},Tk=L$.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(r){return r.encoding?"rtpmap:%d %s/%s/%s":r.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(r){return r.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(r){return r.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(r){return"extmap:%d"+(r.direction?"/%s":"%v")+(r["encrypt-uri"]?" %s":"%v")+" %s"+(r.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(r){return r.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(r){var e="candidate:%s %d %s %d %s %d typ %s";return e+=r.raddr!=null?" raddr %s rport %d":"%v%v",e+=r.tcptype!=null?" tcptype %s":"%v",r.generation!=null&&(e+=" generation %d"),e+=r["network-id"]!=null?" network-id %d":"%v",e+=r["network-cost"]!=null?" network-cost %d":"%v",e}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(r){var e="ssrc:%d";return r.attribute!=null&&(e+=" %s",r.value!=null&&(e+=":%s")),e}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(r){return r.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(r){return r.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(r){return"imageattr:%s %s %s"+(r.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(r){return"simulcast:%s %s"+(r.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(r){return"ts-refclk:%s"+(r.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(r){var e="mediaclk:";return e+=r.id!=null?"id=%s %s":"%v%s",e+=r.mediaClockValue!=null?"=%s":"",e+=r.rateNumerator!=null?" rate=%s":"",e+=r.rateDenominator!=null?"/%s":"",e}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(Tk).forEach(function(r){var e=Tk[r];e.forEach(function(t){t.reg||(t.reg=/(.*)/),t.format||(t.format="%s")})});var qw=L$.exports;(function(r){var e=function(c){return String(Number(c))===c?Number(c):c},t=function(c,o,l,d){if(d&&!l)o[d]=e(c[1]);else for(var h=0;h<l.length;h+=1)c[h+1]!=null&&(o[l[h]]=e(c[h+1]))},n=function(c,o,l){var d=c.name&&c.names;c.push&&!o[c.push]?o[c.push]=[]:d&&!o[c.name]&&(o[c.name]={});var h=c.push?{}:d?o[c.name]:o;t(l.match(c.reg),h,c.names,c.name),c.push&&o[c.push].push(h)},i=qw,s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);r.parse=function(c){var o={},l=[],d=o;return c.split(/(\r\n|\r|\n)/).filter(s).forEach(function(h){var v=h[0],y=h.slice(2);v==="m"&&(l.push({rtp:[],fmtp:[]}),d=l[l.length-1]);for(var w=0;w<(i[v]||[]).length;w+=1){var k=i[v][w];if(k.reg.test(y))return n(k,d,y)}}),o.media=l,o};var a=function(c,o){var l=o.split(/=(.+)/,2);return l.length===2?c[l[0]]=e(l[1]):l.length===1&&o.length>1&&(c[l[0]]=void 0),c};r.parseParams=function(c){return c.split(/;\s?/).reduce(a,{})},r.parseFmtpConfig=r.parseParams,r.parsePayloads=function(c){return c.toString().split(" ").map(Number)},r.parseRemoteCandidates=function(c){for(var o=[],l=c.split(" ").map(e),d=0;d<l.length;d+=3)o.push({component:l[d],ip:l[d+1],port:l[d+2]});return o},r.parseImageAttributes=function(c){return c.split(" ").map(function(o){return o.substring(1,o.length-1).split(",").reduce(a,{})})},r.parseSimulcastStreamList=function(c){return c.split(";").map(function(o){return o.split(",").map(function(l){var d,h=!1;return l[0]!=="~"?d=e(l):(d=e(l.substring(1,l.length)),h=!0),{scid:d,paused:h}})})}})(N$);var Fy=qw,qH=/%[sdv%]/g,WH=function(r){var e=1,t=arguments,n=t.length;return r.replace(qH,function(i){if(e>=n)return i;var s=t[e];switch(e+=1,i){case"%%":return"%";case"%s":return String(s);case"%d":return Number(s);case"%v":return""}})},ud=function(r,e,t){var n=e.format instanceof Function?e.format(e.push?t:t[e.name]):e.format,i=[r+"="+n];if(e.names)for(var s=0;s<e.names.length;s+=1){var a=e.names[s];e.name?i.push(t[e.name][a]):i.push(t[e.names[s]])}else i.push(t[e.name]);return WH.apply(null,i)},VH=["v","o","s","i","u","e","p","c","b","t","r","z","a"],HH=["i","c","b","a"],GH=function(r,e){e=e||{},r.version==null&&(r.version=0),r.name==null&&(r.name=" "),r.media.forEach(function(s){s.payloads==null&&(s.payloads="")});var t=e.outerOrder||VH,n=e.innerOrder||HH,i=[];return t.forEach(function(s){Fy[s].forEach(function(a){a.name in r&&r[a.name]!=null?i.push(ud(s,a,r)):a.push in r&&r[a.push]!=null&&r[a.push].forEach(function(c){i.push(ud(s,a,c))})})}),r.media.forEach(function(s){i.push(ud("m",Fy.m[0],s)),n.forEach(function(a){Fy[a].forEach(function(c){c.name in s&&s[c.name]!=null?i.push(ud(a,c,s)):c.push in s&&s[c.push]!=null&&s[c.push].forEach(function(o){i.push(ud(a,c,o))})})})}),i.join(`\r
|
|
100
100
|
`)+`\r
|
|
101
|
-
`},zu=N$,zH=GH,KH=qw;ya.grammar=KH;ya.write=zH;ya.parse=zu.parse;ya.parseParams=zu.parseParams;ya.parseFmtpConfig=zu.parseFmtpConfig;ya.parsePayloads=zu.parsePayloads;ya.parseRemoteCandidates=zu.parseRemoteCandidates;ya.parseImageAttributes=zu.parseImageAttributes;ya.parseSimulcastStreamList=zu.parseSimulcastStreamList;var uo={},JH=Ye&&Ye.__spreadArrays||function(){for(var r=0,e=0,t=arguments.length;e<t;e++)r+=arguments[e].length;for(var n=Array(r),i=0,e=0;e<t;e++)for(var s=arguments[e],a=0,c=s.length;a<c;a++,i++)n[i]=s[a];return n};Object.defineProperty(uo,"__esModule",{value:!0});var U$=function(){function r(e,t,n){this.name=e,this.version=t,this.os=n}return r}();uo.BrowserInfo=U$;var F$=function(){function r(e){this.version=e,this.name="node",this.os=process.platform}return r}();uo.NodeInfo=F$;var j$=function(){function r(){this.bot=!0,this.name="bot",this.version=null,this.os=null}return r}();uo.BotInfo=j$;var YH=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,XH=/(nuhk)|(Googlebot)|(Yammybot)|(Openbot)|(Slurp)|(MSNBot)|(Ask Jeeves\/Teoma)|(ia_archiver)/,Ck=3,QH=[["aol",/AOLShield\/([0-9\._]+)/],["edge",/Edge\/([0-9\._]+)/],["edge-ios",/EdgiOS\/([0-9\._]+)/],["yandexbrowser",/YaBrowser\/([0-9\._]+)/],["vivaldi",/Vivaldi\/([0-9\.]+)/],["kakaotalk",/KAKAOTALK\s([0-9\.]+)/],["samsung",/SamsungBrowser\/([0-9\.]+)/],["silk",/\bSilk\/([0-9._-]+)\b/],["miui",/MiuiBrowser\/([0-9\.]+)$/],["beaker",/BeakerBrowser\/([0-9\.]+)/],["edge-chromium",/Edg\/([0-9\.]+)/],["chromium-webview",/(?!Chrom.*OPR)wv\).*Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["chrome",/(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["phantomjs",/PhantomJS\/([0-9\.]+)(:?\s|$)/],["crios",/CriOS\/([0-9\.]+)(:?\s|$)/],["firefox",/Firefox\/([0-9\.]+)(?:\s|$)/],["fxios",/FxiOS\/([0-9\.]+)/],["opera-mini",/Opera Mini.*Version\/([0-9\.]+)/],["opera",/Opera\/([0-9\.]+)(?:\s|$)/],["opera",/OPR\/([0-9\.]+)(:?\s|$)/],["ie",/Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/],["ie",/MSIE\s([0-9\.]+);.*Trident\/[4-7].0/],["ie",/MSIE\s(7\.0)/],["bb10",/BB10;\sTouch.*Version\/([0-9\.]+)/],["android",/Android\s([0-9\.]+)/],["ios",/Version\/([0-9\._]+).*Mobile.*Safari.*/],["safari",/Version\/([0-9\._]+).*Safari/],["facebook",/FBAV\/([0-9\.]+)/],["instagram",/Instagram\s([0-9\.]+)/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Mobile/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Gecko\)$/],["searchbot",YH]],Ek=[["iOS",/iP(hone|od|ad)/],["Android OS",/Android/],["BlackBerry OS",/BlackBerry|BB10/],["Windows Mobile",/IEMobile/],["Amazon OS",/Kindle/],["Windows 3.11",/Win16/],["Windows 95",/(Windows 95)|(Win95)|(Windows_95)/],["Windows 98",/(Windows 98)|(Win98)/],["Windows 2000",/(Windows NT 5.0)|(Windows 2000)/],["Windows XP",/(Windows NT 5.1)|(Windows XP)/],["Windows Server 2003",/(Windows NT 5.2)/],["Windows Vista",/(Windows NT 6.0)/],["Windows 7",/(Windows NT 6.1)/],["Windows 8",/(Windows NT 6.2)/],["Windows 8.1",/(Windows NT 6.3)/],["Windows 10",/(Windows NT 10.0)/],["Windows ME",/Windows ME/],["Open BSD",/OpenBSD/],["Sun OS",/SunOS/],["Chrome OS",/CrOS/],["Linux",/(Linux)|(X11)/],["Mac OS",/(Mac_PowerPC)|(Macintosh)/],["QNX",/QNX/],["BeOS",/BeOS/],["OS/2",/OS\/2/],["Search Bot",XH]];function ZH(r){return r?rS(r):typeof navigator<"u"?rS(navigator.userAgent):q$()}uo.detect=ZH;function rS(r){var e=r!==""&&QH.reduce(function(s,a){var c=a[0],o=a[1];if(s)return s;var l=o.exec(r);return!!l&&[c,l]},!1);if(!e)return null;var t=e[0],n=e[1];if(t==="searchbot")return new j$;var i=n[1]&&n[1].split(/[._]/).slice(0,3);return i?i.length<Ck&&(i=JH(i,eG(Ck-i.length))):i=[],new U$(t,i.join("."),B$(r))}uo.parseUserAgent=rS;function B$(r){for(var e=0,t=Ek.length;e<t;e++){var n=Ek[e],i=n[0],s=n[1],a=s.test(r);if(a)return i}return null}uo.detectOS=B$;function q$(){var r=typeof process<"u"&&process.version;return r?new F$(process.version.slice(1)):null}uo.getNodeVersion=q$;function eG(r){for(var e=[],t=0;t<r;t++)e.push("0");return e}var jh={exports:{}};function tG(r,e){if(typeof r[Symbol.iterator]=="function")for(const t of r){const n=Array.isArray(t)?t[1]:t;e(n)}else for(const t in r)if(r.hasOwnProperty(t)){const n=r[t];e(n)}}var W$={iterateReports:tG};const rG={"outbound-rtp":{packetsSent:"audioSentPackets",bytesSent:"audioSentBytes"},"inbound-rtp":{packetsReceived:"audioRecvPackets",packetsLost:"audioRecvPacketsLost",bytesReceived:"audioRecvBytes",jitter:"audioRecvJitter"},"remote-inbound-rtp":{packetsLost:"audioSentPacketsLost",roundTripTime:"audioRtt",jitter:"audioSentJitter"}},nG={"remote-candidate":function(r){return Bh(r)},"inbound-rtp":function(r){return Bh(r)},"outbound-rtp":function(r){return Bh(r)},"remote-inbound-rtp":function(r){return Bh(r)}},Bh=r=>{const{type:e}=r,t=rG[e],n={};for(let i in t)if(i in r){let s;typeof t[i]=="function"?s=t[i](r):s=t[i],n[s]=r[i]}else n[t[i]]=null;return n};var iG={parsers:nG};const{iterateReports:sG}=W$;function aG(r){let e=0,t=0,n=0,i=100,s=0,a,c,o;return sG(r,l=>{l.type==="inbound-rtp"&&(e=l.jitter,n=l.packetsLost,t=l.packetsReceived)}),t+n>0&&(s=100*(n/(t+n))),a=i+e*2+10,a<160?c=93.2-a/40:c=93.2-(a-120)/10,c=c-s*2.5,c<1&&(c=1),o=1+.035*c+7e-6*c*(c-60)*(100-c),parseFloat(o).toFixed(6)}var V$=aG;const{iterateReports:oG}=W$,{parsers:kk}=iG,uG=V$;function cG(r){const e={};return oG(r,t=>{if(t.type in kk){const n=kk[t.type](t);Object.assign(e,n)}}),e.networkMos=parseFloat(uG(r)),e}var lG=cG,Rk;function dG(){return Rk||(Rk=1,function(r,e){var t=Ye&&Ye.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(e,"__esModule",{value:!0});const n=lG,i=V$,s=t(_a());class a{constructor(o){this.mos_report={min:5,max:0},this._reportsCount=0,this._mosSum=0,this.intervals=[],this._deprecationWarningSent=!1,!(!o||!o.application||!o.rtc_id||!o.pc)&&(this.conversation=null,this.application_id=null,this.attachHandlers(o),this.startSendingStats(o),this.startEmittingStats(o))}attachHandlers(o){const{pc:l}=o,d=l.onconnectionstatechange?l.onconnectionstatechange:()=>{};l.onconnectionstatechange=h=>{switch(d.call(l,h),l.connectionState){case"disconnected":case"failed":case"closed":this.removeIntervals(),this.emitLastReport(o)}},o.conversation?o.conversation.on("member:media",(v,y)=>{!this.application_id&&(o==null?void 0:o.rtc_id)===y.body.channel.id&&(this.application_id=y.application_id)}):o.application.on("member:joined",(v,y)=>{(!this.conversation||!this.application_id)&&(o==null?void 0:o.rtc_id)===y.body.channel.id&&(this.conversation=v.conversation,this.application_id=y.application_id)})}emitLastReport(o){const{application:l,conversation:d=null,rtc_id:h,config:{emit_events:v,emit_rtc_analytics:y}}=o,w=this.getMOSReport(),k=w.last;k&&(y&&l.emit("rtcstats:analytics",{type:"mos_report",mos:k,rtc_id:h,mos_report:w,api_key:l.session.apiKey,...this.application_id&&{application_id:this.application_id},...d&&{conversation_id:d.id,conversation_name:d.name}}),v&&(this._deprecationWarningSent||(this._deprecationWarningSent=!0,console.warn('"rtcstats:report" event is deprecated. Use "rtcstats:analytics" instead')),l.emit("rtcstats:report",k,null,d,w)))}startSendingStats(o){const{application:l,conversation:d=null,pc:h,rtc_id:v,config:{remote_collection:y,remote_collection_url:w,remote_collection_interval:k}}=o;if(!y)return;const I=setInterval(()=>{h.getStats(null).then(A=>{var j;const L=(j=d??this.conversation)!==null&&j!==void 0?j:null;s.default.networkRequest({url:w,type:"POST",data:{...n(A),legId:v,apiKey:l.session.apiKey,...this.application_id&&{applicationId:this.application_id},...L&&{conversationId:L.id,conversationName:L.name}}}).catch(()=>{})}).catch(()=>{}),(h.connectionState==="closed"||h.signalingState==="closed")&&this.removeIntervals()},k);this.intervals.push(I)}startEmittingStats(o){const{application:l,conversation:d=null,pc:h,rtc_id:v,config:{emit_events:y,emit_rtc_analytics:w,emit_interval:k}}=o;if(!y&&!w)return;const I=setInterval(()=>{var A;h.getStats(null).then(j=>{var L;const x=this.getMos(j);if(!x)return;const B=(L=d??this.conversation)!==null&&L!==void 0?L:null;w&&l.emit("rtcstats:analytics",{type:"mos",mos:x,report:j,rtc_id:v,api_key:l.session.apiKey,...this.application_id&&{application_id:this.application_id},...B&&{conversation_id:B.id,conversation_name:B.name}}),y&&(this._deprecationWarningSent||(this._deprecationWarningSent=!0,console.warn('"rtcstats:report" event is deprecated. Use "rtcstats:analytics" instead')),l.emit("rtcstats:report",x,j,d))}).catch(()=>{}),(h.connectionState==="closed"||h.signalingState==="closed")&&(this.removeIntervals(),this.emitLastReport({...o,conversation:(A=d??this.conversation)!==null&&A!==void 0?A:null}))},k);this.intervals.push(I)}removeIntervals(){this.intervals.forEach(o=>clearInterval(o)),this.intervals=[]}getMos(o){const l=i(o);return this.updateMOSReport(parseInt(l)),l}updateMOSReport(o){this._reportsCount++,this._mosSum+=o,this.mos_report.last=o,this.mos_report.min=o<this.mos_report.min?o:this.mos_report.min,this.mos_report.max=o>this.mos_report.max?o:this.mos_report.max,this.mos_report.average=this._mosSum/this._reportsCount}getMOSReport(){return this.mos_report.min=a.normaliseFloat(this.mos_report.min),this.mos_report.max=a.normaliseFloat(this.mos_report.max),this.mos_report.last=a.normaliseFloat(this.mos_report.last),this.mos_report.average=a.normaliseFloat(this.mos_report.average),this.mos_report}static normaliseFloat(o){return parseFloat(o).toFixed(6)}}e.default=a,r.exports=a}(jh,jh.exports)),jh.exports}var Pk;function sg(){return Pk||(Pk=1,function(r,e){var t=Ye&&Ye.__createBinding||(Object.create?function(y,w,k,I){I===void 0&&(I=k),Object.defineProperty(y,I,{enumerable:!0,get:function(){return w[k]}})}:function(y,w,k,I){I===void 0&&(I=k),y[I]=w[k]}),n=Ye&&Ye.__setModuleDefault||(Object.create?function(y,w){Object.defineProperty(y,"default",{enumerable:!0,value:w})}:function(y,w){y.default=w}),i=Ye&&Ye.__importStar||function(y){if(y&&y.__esModule)return y;var w={};if(y!=null)for(var k in y)k!=="default"&&Object.hasOwnProperty.call(y,k)&&t(w,y,k);return n(w,y),w},s=Ye&&Ye.__importDefault||function(y){return y&&y.__esModule?y:{default:y}};Object.defineProperty(e,"__esModule",{value:!0});const a=ya,c=Gr,o=i(uo),l=Ts,d=s(dG()),h=2e4;class v{constructor(){this.log=c.getLogger(this.constructor.name)}static getUserAudio(w=!0){let k={video:!1,audio:w};return navigator.mediaDevices.getUserMedia(k)}createRTCPeerConnection(w){const k=new RTCPeerConnection(w);return k.trace=()=>{},k}_getWindowLocationProtocol(){return window.location.protocol}static _getBrowserName(){return o.detect().name}static isNode(){return this._getBrowserName()==="node"}checkValidKeys(w,k){let I=!0;return Object.keys(w).forEach(A=>{k.hasOwnProperty(A)||(I=!1)}),I}static cleanCallMediaIfFailed(w){setTimeout(()=>{w.conversation||(this.cleanMediaProperties(w),w.status=w.CALL_STATUS.FAILED,w.application.emit("call:status:changed",w))},5e3)}static callDisconnectHandler(w,k){const I=[w.CALL_STATUS.ANSWERED,w.CALL_STATUS.STARTED,w.CALL_STATUS.RINGING];if(!(k.connectionState!=="disconnected"||!w||!w.conversation))return setTimeout(()=>{k.connectionState==="connected"||I.indexOf(w.status)==-1||(this.cleanMediaProperties(w),w.status=w.CALL_STATUS.COMPLETED,w.application.emit("call:status:changed",w))},h)}static cleanMediaProperties(w){if(w.rtcObjects)for(const k in w.rtcObjects)w.rtcObjects[k].pc.close(),delete w.rtcObjects[k].pc,v.closeStream(w.rtcObjects[k].stream);w.application.activeStreams=[],w.rtcObjects={},w.conversation&&w.conversation.media&&(w.conversation.media.rtcStats=null)}static playAudioStream(w){const k=new Audio;return k.srcObject=w,k.autoplay=!0,k}static createDummyCandidateSDP(w){const k={foundation:1176891032,component:1,transport:"udp",priority:2122260223,ip:"0.0.0.0",port:9,type:"host",generation:0,"network-id":1,"network-cost":50},I=a.parse(w.localDescription.sdp);return I.media[0].candidates=[k],a.write(I)}static createRTCPeerConnectionConfig(w){return{iceTransportPolicy:"all",bundlePolicy:"balanced",rtcpMuxPolicy:"require",iceCandidatePoolSize:"0",...w.session.config&&w.session.config.iceServers&&{iceServers:w.session.config.iceServers}}}static createPeerConnection(w){const k=this.createRTCPeerConnectionConfig(w);return new RTCPeerConnection(k)}static sendOffer(w,k,I,A){const L={sdp:this.createDummyCandidateSDP(k)};let x={from:I.me.id,body:{offer:L}},B=`conversations/${I.id}/rtc`;return A&&(B+=`/${A}/offer`),w.session.sendNetworkRequest({type:"POST",path:B,data:x})}static sendAnswer(w,k,I,A){const j=this.createDummyCandidateSDP(k);let L={from:I.me.id,body:{answer:j}},x=`conversations/${I.id}/rtc/${A}/answer`;return w.session.sendNetworkRequest({type:"POST",path:x,data:L})}static createLeg(w,k){const A={sdp:this.createDummyCandidateSDP(k),type:"offer"};return w.session.sendNetworkRequest({type:"POST",path:"legs",version:"beta",data:{body:{offer:A}}})}static closeStream(w){w.getTracks().forEach(k=>{k.stop()})}static emitMediaStream(w,k,I){w.emit("media:stream:on",{pc:k,stream:I,type:"audio",streamIndex:0})}static _initStatsEvents(w){var k,I,A;if(!v.isNode()&&!((A=(I=(k=w==null?void 0:w.application)===null||k===void 0?void 0:k.session)===null||I===void 0?void 0:I.config)===null||A===void 0)&&A.rtcstats){const j=w.application.session.config.rtcstats,{emit_events:L,remote_collection:x,emit_rtc_analytics:B}=j;if(L||x||B){const G={...w,config:{...j}};return new d.default(G)}}}static attachConversationEventHandlers(w){const{conversation:k,pc:I,log:A}=w;k.once("rtc:answer",j=>{if(!I){A.warn("RTC: received an answer too late");return}I.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:j.body.answer}))})}static doAnswer(w,k,I){const{application:A,conversation:j,pc:L,reject:x,localStream:B}=w;this.addPeerConnectionListeners(w,()=>v.sendAnswer(A,L,j,I).then(()=>({rtc_id:I}))),L.setRemoteDescription(new RTCSessionDescription({type:"offer",sdp:k})).then(()=>L.createAnswer()).then(G=>L.setLocalDescription(G)).catch(G=>{B&&this.closeStream(B),x(G)})}static attachPeerConnectionEventHandlers(w){const{application:k,conversation:I,pc:A,reconnectRtcId:j}=w;this.addPeerConnectionListeners(w,()=>v.sendOffer(k,A,I,j))}static addPeerConnectionListeners(w,k){const{application:I,conversation:A,pc:j,streamIndex:L,localStream:x,log:B,rtcObjects:G,resolve:K,reject:D}=w;let fe,X=!1,pe;A.id&&(pe=I.calls.get(A.id)),j.ontrack=Q=>{fe=Q.streams[0],I.activeStreams.push(fe),v.emitMediaStream(A.me,j,fe)},j.onconnectionstatechange=Q=>this.onconnectionstatechangeHandler(j,B,pe,()=>K(fe),()=>D()),j.onnegotiationneeded=()=>this.onnegotiationneededHandler(j,Q=>D(Q)),j.oniceconnectionstatechange=Q=>this.oniceconnectionstatechange(Q,j,B,Oe=>D(Oe)),j.onicecandidate=async Q=>{if(Q.candidate&&!X&&j){X=!0;try{const{rtc_id:Oe}=await k();v._initStatsEvents({application:I,rtc_id:Oe,pc:j,conversation:A}),j.trace&&j.trace("rtc_id",Oe),G[Oe]={rtc_id:Oe,pc:j,stream:x,type:"audio",streamIndex:L}}catch(Oe){x&&this.closeStream(x),D(new l.NexmoClientError(Oe))}}},x.getTracks().forEach(Q=>j.addTrack(Q))}static prewarmLeg(w){const k=w.application;return new Promise(async(I,A)=>{let j=!1,L,x,B={};const G=c.getLogger(this.constructor.name);try{let K=await this.getUserAudio();const D=this.createPeerConnection(k);D.ontrack=fe=>{L=fe.streams[0],k.activeStreams.push(L)},D.onconnectionstatechange=fe=>this.onconnectionstatechangeHandler(D,G,w,()=>I({stream:L,legId:x,rtcObjects:B}),()=>A()),D.onnegotiationneeded=()=>this.onnegotiationneededHandler(D,fe=>A(fe)),D.oniceconnectionstatechange=fe=>this.oniceconnectionstatechange(fe,D,G,X=>A(X)),D.onicecandidate=async fe=>{if(fe.candidate&&!j&&D){j=!0;const{rtc_id:X,sdp:pe}=await this.createLeg(k,D);return v._initStatsEvents({application:k,rtc_id:X,pc:D}),x=X,B[x]={rtc_id:X,pc:D,stream:K,type:"audio",streamIndex:1},D.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:pe}))}},K.getTracks().forEach(fe=>D.addTrack(fe))}catch(K){A(new l.NexmoClientError(K))}})}}e.default=v,v.onconnectionstatechangeHandler=(y,w,k,I,A)=>{switch(y.connectionState){case"connected":w.info("The connection has become fully connected"),I();break;case"disconnected":if(!k)break;k.call_disconnect_timeout&&clearTimeout(k.call_disconnect_timeout),k.call_disconnect_timeout=v.callDisconnectHandler(k,y);break;case"failed":A(),w.info("One or more transports has terminated unexpectedly or in an error");break;case"closed":w.info("The connection has been closed");break}},v.oniceconnectionstatechange=(y,w,k,I)=>{switch(w.iceConnectionState){case"disconnected":k.warn("One or more transports is disconnected",w.iceConnectionState);break;case"failed":I(new l.NexmoClientError(y)),k.warn("One or more transports has terminated unexpectedly or in an error",y);break;default:k.info("The ice connection status changed",w.iceConnectionState)}},v.onnegotiationneededHandler=async(y,w)=>{try{const k=await y.createOffer();return y.setLocalDescription(k)}catch(k){w(new l.NexmoClientError(k))}},r.exports=v}(Uh,Uh.exports)),Uh.exports}var Ik;function fG(){return Ik||(Ik=1,function(r,e){var t=Ye&&Ye.__importDefault||function(h){return h&&h.__esModule?h:{default:h}};Object.defineProperty(e,"__esModule",{value:!0});const n=Gr,i=Ts,s=t(sg()),a=t(_a()),c=t(oo),o=t(z$()),l=t(og());class d{constructor(v){var y,w,k;const I=v instanceof o.default?v:null,A=v instanceof l.default?v:null;this.log=n.getLogger(this.constructor.name),I?(this.rtcHelper=new s.default,this.application=I.application,this.application.activeStreams=this.application.activeStreams||[],this.parentConversation=I,this.rtcObjects={},this.streamIndex=0,this.rtcstats_conf=((k=(w=(y=this.application)===null||y===void 0?void 0:y.session)===null||w===void 0?void 0:w.config)===null||k===void 0?void 0:k.rtcStats)||{},this.rtcStats=null):A?(this.rtcHelper=new s.default,this.application=A):this.log.warn("No conversation object in Media")}_attachEndingEventHandlers(){this.parentConversation&&(this.log.debug("attaching leave listeners in media for "+this.parentConversation.id),this.parentConversation.on("rtc:hangup",async v=>{let y;if(this.parentConversation.members.has(v.from))y=this.parentConversation.members.get(v.from);else try{y=await this.parentConversation.getMember(v.from)}catch(w){this.log.warn(`There is an error getting the member ${w}`)}y.user.id===this.application.me.id&&this.application.activeStreams.length&&this._cleanMediaProperties(),y.user.id===this.application.me.id&&y.transferred_from&&y.transferred_from.media._cleanMediaProperties(),y.user.id===this.application.me.id&&this.parentConversation.off("rtc:hangup")}))}_enableStatsEvents(){this.rtcstats_conf.emit_rtc_analytics=!0,this.rtcstats_conf.remote_collection=!0;const v=this._findRtcObjectByType("audio");!this.rtcStats&&v&&(this.log.debug(`enabling stats events for ${v.rtc_id}`),this.rtcStats=s.default._initStatsEvents({application:this.application,rtc_id:v.rtc_id,pc:this.pc,conversation:this.parentConversation}))}_disableStatsEvents(){this.rtcstats_conf.emit_events=!1,this.rtcstats_conf.emit_rtc_analytics=!1,this.rtcstats_conf.remote_collection=!1,this.rtcStats.removeIntervals(),delete this.rtcStats}_audioInitHandler(v={},y){return new Promise(async(w,k)=>{const I=this.streamIndex;this.streamIndex++;const{audioConstraints:A}=v;try{const j=await s.default.getUserAudio(A),L=s.default.createPeerConnection(this.application);this.pc=L;const{application:x,log:B,parentConversation:G,rtcObjects:K}=this,D={pc:L,streamIndex:I,localStream:j,application:x,conversation:G,log:B,rtcObjects:K};y({...D,resolve:w,reject:k}),s.default.attachConversationEventHandlers(D),this._attachEndingEventHandlers()}catch(j){k(new i.NexmoClientError(j))}})}_execAnswer(v={}){const{offer:{sdp:y,leg_id:w}}=v;return this._audioInitHandler(v,k=>s.default.doAnswer(k,y,w))}_handleAudio(v={}){const{reconnectRtcId:y}=v;return this._audioInitHandler(v,w=>s.default.attachPeerConnectionEventHandlers({...w,reconnectRtcId:y}))}_findRtcObjectByType(v){return Object.values(this.rtcObjects).find(y=>y.type===v)}async _cleanConversationProperties(){this.pc&&this.pc.close(),delete this.pc,this.rtcStats=null,this.application.activeStreams=[],this.listeningToRtcEvent=!1,await Promise.resolve()}_cleanMediaProperties(){if(this.pc&&this.pc.close(),this.rtcObjects)for(const v in this.rtcObjects)s.default.closeStream(this.rtcObjects[v].stream);delete this.pc,this.rtcStats=null,this.application.activeStreams=[],this.rtcObjects={},this.listeningToRtcEvent=!1}async _disableLeg(v){const y=new Promise(async(k,I)=>{try{await this.application.session.sendNetworkRequest({type:"DELETE",path:`conversations/${this.parentConversation.id}/rtc/${v}?from=${this.parentConversation.me.id}&originating_session=${this.application.session.session_id}`,version:"beta2"}),k("rtc:terminate:success")}catch(A){I(new i.NexmoApiError(A))}}),w=new Promise(k=>{this.rtcObjects[v].pc&&this.rtcObjects[v].pc.close(),this.rtcObjects[v].stream&&s.default.closeStream(this.rtcObjects[v].stream),k()});try{return await Promise.all([y,w]),this.parentConversation.me.emit("media:stream:off",this.rtcObjects[v].streamIndex),delete this.rtcObjects[v],"rtc:terminate:success"}catch(k){throw k}}_enableMediaTracks(v,y){v.forEach(w=>{w.enabled=y})}async _setMediaTracksAndMute(v,y,w,k){this._enableMediaTracks(y,!w);try{return await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.parentConversation.id}/events`,data:{type:k,to:this.parentConversation.me.id,from:this.parentConversation.me.id,body:{rtc_id:v}}})}catch(I){throw this._enableMediaTracks(y,w),new i.NexmoApiError(I)}}async updateAudioConstraints(v={}){let y=this._findRtcObjectByType("audio");if(y&&y.pc)try{const w=await s.default.getUserAudio(v);return w.getTracks().forEach(k=>{const I=y.pc.getSenders().find(A=>A.track.kind===k.kind);I&&(k.enabled=I.track.enabled,I.replaceTrack(k))}),s.default.closeStream(y.stream),y.stream=w,w}catch(w){return w}else throw new i.NexmoApiError("error:media:stream:not-found")}mute(v=!1,y=null){const k="audio:mute:"+(v?"on":"off");let I=[],A={};if(y!==null){if(A[0]=Object.values(this.rtcObjects).find(j=>j.streamIndex===y),!A[0])throw new i.NexmoClientError("error:media:stream:not-found")}else A=this.rtcObjects;return Object.values(A).forEach(j=>{const L=j.stream.getAudioTracks(),x=this._setMediaTracksAndMute(j.rtc_id,L,v,k);I.push(x)}),Promise.all(I)}async earmuff(v){try{if(this.me===null)throw new i.NexmoClientError("error:self");{let y="audio:earmuff:off";v&&(y="audio:earmuff:on");const{response:w}=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.parentConversation.id}/events`,data:{type:y,to:this.parentConversation.me.id}});return w}}catch(y){throw new i.NexmoApiError(y)}}async enable(v){try{if(this.parentConversation.me===null)throw new i.NexmoClientError("error:self");{const{offer:y}=v??{};let w=await(y!==void 0?this._execAnswer(v):this._handleAudio(v)),k=v&&(v.autoPlayAudio||v.autoPlayAudio===void 0);return(!v||k)&&s.default.playAudioStream(w),w}}catch(y){throw y}}disable(){let v=[];v.push(this._cleanConversationProperties());for(const y in this.rtcObjects)v.push(this._disableLeg(y));return Promise.all(v)}async sayText(v){try{const y=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.parentConversation.id}/events`,data:{type:"audio:say",cid:this.parentConversation.id,from:this.parentConversation.me.id,body:{text:v.text,voice_name:v.voice_name||"Amy",level:v.level||1,queue:v.queue||!0,loop:v.loop||1,ssml:v.ssml||!1}}});return new c.default(this.parentConversation,y)}catch(y){throw new i.NexmoApiError(y)}}async sendDTMF(v){try{if(!a.default.validateDTMF(v))throw new i.NexmoClientError("error:audio:dtmf:invalid-digit");if(!(this._findRtcObjectByType("audio")||{}).rtc_id)throw new i.NexmoClientError("error:audio:dtmf:audio-disabled");const{id:w,timestamp:k}=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.parentConversation.id}/events`,data:{type:"audio:dtmf",from:this.parentConversation.me.id,body:{digit:v,channel:{type:"app",id:this._findRtcObjectByType("audio").rtc_id}}}}),I={body:{digit:v,dtmf_id:""},cid:this.parentConversation.id,from:this.parentConversation.me.id,id:w,timestamp:k,type:"audio:dtmf"},A=new c.default(this.parentConversation,I);return this.parentConversation.events.set(I.id,A),A}catch(y){throw new i.NexmoApiError(y)}}async playStream(v){try{const y=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.parentConversation.id}/events`,data:{type:"audio:play",body:v}});return new c.default(this.parentConversation,y)}catch(y){throw new i.NexmoApiError(y)}}async startRinging(){try{const v=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.parentConversation.id}/events`,data:{type:"audio:ringing:start",from:this.parentConversation.me.id,body:{}}});return new c.default(this.parentConversation,v)}catch(v){throw new i.NexmoApiError(v)}}async stopRinging(){try{const v=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.parentConversation.id}/events`,data:{type:"audio:ringing:stop",from:this.parentConversation.me.id,body:{}}});return new c.default(this.parentConversation,v)}catch(v){throw new i.NexmoApiError(v)}}}e.default=d,r.exports=d}(Lh,Lh.exports)),Lh.exports}var qh={exports:{}},Wh={exports:{}},Ak;function H$(){return Ak||(Ak=1,function(r,e){var t=Ye&&Ye.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(e,"__esModule",{value:!0});const n=t(_a()),i=Gr,s=t(oo);class a extends s.default{constructor(o,l){super(o,l),this.log=i.getLogger(this.constructor.name),this.type="image",this.conversation=o,this.state={seen_by:{},delivered_to:{}},l&&l.body&&l.body.timestamp&&(this.timestamp=l.body.timestamp),Object.assign(this,l)}seen(){return super.seen()}delivered(){return super.delivered()}async del(){return await n.default.networkRequest({type:"DELETE",url:this.body.representations.original.url,token:this.conversation.application.session.config.token}),super.del()}async fetchImage(o="thumbnail",l=this.body.representations){try{return n.default._fetchImage(l[o].url,this.conversation.application.session.config.token)}catch(d){throw this.log.error(d),d}}}e.default=a,r.exports=a}(Wh,Wh.exports)),Wh.exports}var Ok;function hG(){return Ok||(Ok=1,function(r,e){var t=Ye&&Ye.__importDefault||function(l){return l&&l.__esModule?l:{default:l}};Object.defineProperty(e,"__esModule",{value:!0});const n=Gr,i=t(oo),s=t(Fw),a=t(H$()),c=t(jw());class o{constructor(d,h){this.log=n.getLogger(this.constructor.name),this.application=d,this.conversation=h,this.constructed_event=null,this._handleEventMap={"event:delete":this._processDelete,image:this._processImage,"image:delivered":this._processDelivered,"image:seen":this._processSeen,"member:invited":this._processMember,"member:joined":this._processMember,"member:left":this._processMember,"audio:ringing:start":this._processMember,"leg:status:update":this._processLegStatus,"member:media":this._processMedia,text:this._processText,"text:delivered":this._processDelivered,"text:seen":this._processSeen,"audio:mute:on":this._processMuteForMedia,"audio:mute:off":this._processMuteForMedia,message:this._processMessage,"message:delivered":this._processDelivered,"message:seen":this._processSeen,"message:submitted":this._processSubmitted,"message:rejected":this._processRejected,"message:undeliverable":this._processUndeliverable}}handleEvent(d){return this._handleEventMap.hasOwnProperty(d.type)?this._handleEventMap[d.type].call(this,d)||new i.default(this.conversation,d):new i.default(this.conversation,d)}_processDelivered(d){let h=this.conversation.events.get(d.body.event_id);return h?(h.state=h.state||{},h.state.delivered_to=h.state.delivered_to||{},h.state.delivered_to[d.from]=d.timestamp,h):(this.log.warn("NXMEvent not found"),null)}_processDelete(d){var h;let v=this.conversation.events.get((h=d==null?void 0:d.body)===null||h===void 0?void 0:h.event_id);return v?(v.body.text&&(v.body.text=""),v.body.representations&&(v.body.representations=""),v.body.timestamp={deleted:d.timestamp},v):(this.log.warn("NXMEvent not found"),null)}_processImage(d){var h;const v=new a.default(this.conversation,d);return((h=this.conversation.me)===null||h===void 0?void 0:h.id)!==v.from&&v.delivered(),v}_processMember(d){return this.application.calls.has(this.conversation.id)&&this.application.calls.get(this.conversation.id)._handleStatusChange(d),this.conversation.members.has(d.from)&&this.conversation.members.get(d.from)._handleEvent(d),new i.default(this.conversation,d)}_processLegStatus(d){return this.conversation.members.has(d.from)&&this.conversation.members.get(d.from)._handleEvent(d),new i.default(this.conversation,d)}_processMedia(d){return this.conversation.members.has(d.from)&&this.conversation.members.get(d.from)._handleEvent(d),null}_processMuteForMedia(d){return this.conversation.media.rtcObjects[d.body.rtc_id]?d.streamIndex=this.conversation.media.rtcObjects[d.body.rtc_id].streamIndex:this.log.warn("No audio stream was found"),null}_processSeen(d){let h=this.conversation.events.get(d.body.event_id);return h?(h.state=h.state||{},h.state.seen_by=h.state.seen_by||{},h.state.seen_by[d.from]=d.timestamp,h):(this.log.warn("NXMEvent not found"),null)}_processText(d){var h,v;const y=new s.default(this.conversation,d);return((v=(h=this.conversation)===null||h===void 0?void 0:h.me)===null||v===void 0?void 0:v.id)!==y.from&&y.delivered(),y}_processMessage(d){var h,v;const y=new c.default(this.conversation,d);return((v=(h=this.conversation)===null||h===void 0?void 0:h.me)===null||v===void 0?void 0:v.id)!==y.from&&y.delivered(),y}_processSubmitted(d){let h=this.conversation.events.get(d.body.event_id);return h?(h.state=h.state||{},h.state.submitted_to=h.state.submitted_to||{},h.state.submitted_to[d.from]=d.timestamp,h):(this.log.warn("NXMEvent not found"),null)}_processRejected(d){let h=this.conversation.events.get(d.body.event_id);return h?(h.state=h.state||{},h.state.rejected_by=h.state.rejected_by||{},h.state.rejected_by[d.from]=d.timestamp,h):(this.log.warn("NXMEvent not found"),null)}_processUndeliverable(d){let h=this.conversation.events.get(d.body.event_id);return h?(h.state=h.state||{},h.state.undeliverable_to=h.state.undeliverable_to||{},h.state.undeliverable_to[d.from]=d.timestamp,h):(this.log.warn("NXMEvent not found"),null)}}e.default=o,r.exports=o}(qh,qh.exports)),qh.exports}var nS={exports:{}};(function(r,e){Object.defineProperty(e,"__esModule",{value:!0});class t{constructor(i={}){this.page_size=i.page_size||10,this.order=i.order||"asc",this.cursor=i.cursor||"",i.event_type&&(this.event_type=i.event_type)}}e.default=t,r.exports=t})(nS,nS.exports);var G$=nS.exports,Vh={exports:{}},iS={exports:{}};(function(r,e){Object.defineProperty(e,"__esModule",{value:!0});const t=Ts;class n{constructor(s={}){this.page_size=s.page_size,this.order=s.order,this.cursor=s.cursor,this.application=s.application,s.event_type&&s.event_type.length>0&&(this.event_type=s.event_type)}hasPrev(){return this.cursor.prev?this.cursor.prev.length>0:!1}hasNext(){return this.cursor.next?this.cursor.next.length>0:!1}_getConfig(s){return{page_size:this.page_size,order:this.order,cursor:s,...this.event_type&&{event_type:this.event_type}}}_getError(){return Promise.reject(new t.NexmoClientError("error:invalid-cursor"))}}e.default=n,r.exports=n})(iS,iS.exports);var ag=iS.exports,$k;function pG(){return $k||($k=1,function(r,e){var t=Ye&&Ye.__importDefault||function(l){return l&&l.__esModule?l:{default:l}};Object.defineProperty(e,"__esModule",{value:!0});const n=t(ag),i=t(oo),s=t(Fw),a=t(H$()),c=t(jw());class o extends n.default{constructor(d){super(d),this.items=new Map,this.conversation=d.conversation,d.items.forEach(h=>{switch(h.type){case"text":this.items.set(h.id,new s.default(this.conversation,h));break;case"image":this.items.set(h.id,new a.default(this.conversation,h));break;case"message":this.items.set(h.id,new c.default(this.conversation,h));break;default:this.items.set(h.id,new i.default(this.conversation,h));break}}),this.conversation.events=new Map([...this.conversation.events,...this.items])}getPrev(){return this.hasPrev()?this.conversation.getEvents(this._getConfig(this.cursor.prev)):this._getError()}getNext(){return this.hasNext()?this.conversation.getEvents(this._getConfig(this.cursor.next)):this._getError()}}e.default=o,r.exports=o}(Vh,Vh.exports)),Vh.exports}var Hh={exports:{}},xk;function vG(){return xk||(xk=1,function(r,e){var t=Ye&&Ye.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(e,"__esModule",{value:!0});const n=t(ag),i=t(Uw());class s extends n.default{constructor(c){super(c),this.conversation=c.conversation,this.items=new Map,c.items.forEach(o=>{this.items.set(o.id,new i.default(this.conversation,o))})}getPrev(){return this.hasPrev()?this.conversation.getMembers(this._getConfig(this.cursor.prev)):this._getError()}getNext(){return this.hasNext()?this.conversation.getMembers(this._getConfig(this.cursor.next)):this._getError()}}e.default=s,r.exports=s}(Hh,Hh.exports)),Hh.exports}var Mk;function z$(){return Mk||(Mk=1,function(r,e){var t=Ye&&Ye.__importDefault||function(j){return j&&j.__esModule?j:{default:j}};Object.defineProperty(e,"__esModule",{value:!0});const n=Zo,i=Gr,s=Ts,a=t(Uw()),c=t(oo),o=t(Fw),l=t(jw()),d=t(fG()),h=t(hG()),v=t(_a()),y=t(G$),w=t(pG()),k=t(vG()),I=t(og());class A{constructor(L,x){this.log=i.getLogger(this.constructor.name),this.application=L,this.id=null,this.name=null,this.display_name=null,this.timestamp=null,this.members=new Map,this.events=new Map,this.sequence_number=0,this.pageConfig=new y.default(((this.application.session||{}).config||{}).events_page_config),this.events_page_last=null,this.members_page_last=null,this.conversationEventHandler=new h.default(L,this),this.media=new d.default(this),this.me=null,this._updateObjectInstance(x),n.mixin(A)}_updateObjectInstance(L){for(let x in L)switch(x){case"id":this.id=L.id;break;case"name":this.name=L.name;break;case"display_name":this.display_name=L.display_name;break;case"members":L.members.forEach(G=>{if(this.members.has(G.member_id))this.members.get(G.member_id)._normalise(G),G.user_id===this.application.me.id&&G.state!=="LEFT"&&(this.me=this.members.get(G.member_id),this.members.set(this.me.id,this.me));else{const K=new a.default(this,G);G.user_id===this.application.me.id&&G.state!=="LEFT"&&(this.me=K),this.members.set(K.id,K)}});break;case"timestamp":this.timestamp=L.timestamp;break;case"sequence_number":this.sequence_number=L.sequence_number;break;case"member_id":const B={id:L.member_id,state:L.state,user:this.application.me};if(this.members.has(L.member_id)){const G=this.members.get(L.member_id);Object.assign(G,B)}else{const G=new a.default(this,B);this.me=G,this.members.set(G.id,G)}break}}async join(L){var x,B;try{let G={state:"joined",channel:{type:"app"},user:{...!L&&{name:this.application.me.name,id:this.application.me.id},...L&&L.user_name&&{name:L.user_name},...L&&L.user_id&&{id:L.user_id}}};!((x=this===null||this===void 0?void 0:this.me)===null||x===void 0)&&x.id&&((B=this===null||this===void 0?void 0:this.me)===null||B===void 0?void 0:B.state)!=="LEFT"&&(G.from=this.me.id);const K=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.id}/members`,version:"v0.3",data:G}),D=new a.default(this,K);return K._embedded.user.id===this.application.me.id&&(this.me=D,this.members.set(D.id,D)),this.application.getConversation(this.id,I.default.CONVERSATION_API_VERSION.v3),D}catch(G){throw new s.NexmoApiError(G)}}async del(){try{const L=await this.application.session.sendNetworkRequest({type:"DELETE",path:`conversations/${this.id}`});return this.application.conversations.delete(this.id),L}catch(L){throw new s.NexmoApiError(L)}}deleteEvent(L){return L.del()}async invite(L){var x,B;if(!L||!L.id&&!L.user_name)throw new s.NexmoClientError("error:invite:missing:params");const G={state:"invited",user:{...L.id&&{id:L.id},...L.user_name&&{name:L.user_name}},media:L.media,channel:{from:{type:"app"},to:{type:"app"},type:"app"}};!((x=this===null||this===void 0?void 0:this.me)===null||x===void 0)&&x.id&&((B=this===null||this===void 0?void 0:this.me)===null||B===void 0?void 0:B.state)!=="LEFT"&&(G.from=this.me.id);try{const K=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.id}/members`,version:"v0.3",data:G});return new a.default(this,K)}catch(K){throw new s.NexmoApiError(K)}}inviteWithAudio(L){return!L||!L.id&&!L.user_name?Promise.reject(new s.NexmoClientError("error:invite:missing:params")):(L.media={audio_settings:{enabled:!0,muted:!1,earmuffed:!1}},this.invite(L))}leave(L){return this.me.kick(L)}async sendText(L){try{if(this.me===null)throw new s.NexmoClientError("error:self");const x={type:"text",cid:this.id,from:this.me.id,body:{text:L}},{id:B,timestamp:G}=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.id}/events`,data:x});return x.id=B,x.body.timestamp=G,new o.default(this,x)}catch(x){throw new s.NexmoApiError(x)}}async sendCustomEvent({type:L,body:x}){try{if(this.me===null)throw new s.NexmoClientError("error:self");if(!L||typeof L!="string"||L.length<1)throw new s.NexmoClientError("error:custom-event:invalid");const B={type:`custom:${L}`,cid:this.id,from:this.me.id,body:x},{id:G,timestamp:K}=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.id}/events`,data:B});return B.id=G,B.timestamp=K,new c.default(this,B)}catch(B){throw new s.NexmoApiError(B)}}async uploadImage(L,x={quality_ratio:"100",medium_size_ratio:"50",thumbnail_size_ratio:"30"}){const B=new FormData;B.append("file",L),B.append("quality_ratio",x.quality_ratio),B.append("medium_size_ratio",x.medium_size_ratio),B.append("thumbnail_size_ratio",x.thumbnail_size_ratio);const G=await v.default.networkRequest({type:"POST",url:this.application.session.config.ips_url,data:B,token:this.application.session.config.token});return G.upload.addEventListener("progress",K=>{K.lengthComputable&&this.log.debug("uploading image "+K.loaded+"/"+K.total)},!1),G.onreadystatechange=()=>{G.status!==200&&this.log.error(G)},G}async sendImage(L,x={quality_ratio:"100",medium_size_ratio:"50",thumbnail_size_ratio:"30"}){const B=await this.uploadImage(L,x);return B.onreadystatechange=()=>{if(B.readyState===4&&B.status===200)try{this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.id}/events`,data:{type:"image",from:this.me.id,body:{representations:JSON.parse(B.responseText)}}}),this.log.info(B)}catch(G){this.log.error(new s.NexmoApiError(G))}},B}abortSendImage(L){return L instanceof XMLHttpRequest?L.abort():new s.NexmoClientError("error:invalid:param:type")}async sendMessage(L){if(this.me===null)throw new s.NexmoClientError("error:self");if(!(L!=null&&L.message_type))throw new s.NexmoClientError("error:message-event:invalid");try{const x={type:"message",cid:this.id,from:this.me.id,body:{...L}},{id:B,timestamp:G}=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.id}/events`,data:x});return x.id=B,x.body.timestamp=G,new l.default(this,x)}catch(x){throw new s.NexmoApiError(x)}}async _typing(L){const x={activity:L==="on"?1:0},B={type:"text:typing:"+L,cid:this.id,from:this.me.id,body:x};try{return await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.id}/events`,data:B}),`text:typing:${L}:success`}catch(G){throw new s.NexmoApiError(G)}}startTyping(){return this._typing("on")}stopTyping(){return this._typing("off")}async getEvents(L={}){const x=`${this.application.session.config.nexmo_api_url}/beta2/conversations/${this.id}/events`;let B=Object.keys(L).length===0?this.pageConfig:new y.default(L);try{const G=await v.default.paginationRequest(x,B,this.application.session.config.token);G.application=this.application,G.conversation=this;const K=new w.default(G);return this.events_page_last=K,K}catch(G){throw new s.NexmoApiError(G)}}async getMembers(L={}){const x=`${this.application.session.config.nexmo_api_url}/beta2/conversations/${this.id}/members`;let B=Object.keys(L).length===0?this.pageConfig:new y.default(L);try{const G=await v.default.paginationRequest(x,B,this.application.session.config.token);G.application=this.application,G.conversation=this;const K=new k.default(G);return this.members_page_last=K,K}catch(G){throw new s.NexmoApiError(G)}}async getMyMember(){try{const L=await this.application.session.sendNetworkRequest({type:"GET",path:`conversations/${this.id}/members/me`,version:"v0.3"});return new a.default(this,L)}catch(L){throw new s.NexmoApiError(L)}}async getMember(L){try{const x=await this.application.session.sendNetworkRequest({type:"GET",path:`conversations/${this.id}/members/${L}`,version:"v0.3"});return new a.default(this,x)}catch(x){throw new s.NexmoApiError(x)}}_handleEvent(L){var x,B;if(L.type.startsWith("rtc"))return this.emit(L.type,L),Promise.resolve(L);this.sequence_number++,L.body&&L.body.event_id&&typeof L.body.event_id=="string"&&(L.body.event_id=parseInt(L.body.event_id));let G={memberId:L.from};if(!((x=L==null?void 0:L.body)===null||x===void 0)&&x.user){const{id:D,name:fe,display_name:X,image_url:pe,custom_data:Q}=L.body.user;G={...G,...D&&{userId:D},...fe&&{userName:fe},...X&&{displayName:X},...pe&&{imageUrl:pe},...Q&&{customData:Q}}}else if(!((B=L==null?void 0:L._embedded)===null||B===void 0)&&B.from_user){const{id:D,name:fe,display_name:X,image_url:pe,custom_data:Q}=L._embedded.from_user;G={...G,...D&&{userId:D},...fe&&{userName:fe},...X&&{displayName:X},...pe&&{imageUrl:pe},...Q&&{customData:Q}}}let K=this.conversationEventHandler.handleEvent(L);return["text:typing:on","text:typing:off"].includes(L.type)||this.events.set(K.id,K),L.type.startsWith("custom:")?(this.emit(K.type,G,K),Promise.resolve(L)):(this.emit(L.type,G,K),Promise.resolve(L))}}e.default=A,r.exports=A}(Mh,Mh.exports)),Mh.exports}var Gh={exports:{}},Dk;function K$(){return Dk||(Dk=1,function(r,e){var t=Ye&&Ye.__importDefault||function(o){return o&&o.__esModule?o:{default:o}};Object.defineProperty(e,"__esModule",{value:!0});const n=Zo,i=Gr,s=Ts,a=t(sg());class c{constructor(l,d,h){this.application=l,this.log=i.getLogger(this.constructor.name),this.from=h,this.conversation=null,this.rtcObjects={},this.CALL_STATUS={STARTED:"started",RINGING:"ringing",ANSWERED:"answered",COMPLETED:"completed",BUSY:"busy",TIMEOUT:"timeout",UNANSWERED:"unanswered",REJECTED:"rejected",FAILED:"failed"},this.CALL_DIRECTION={INBOUND:"inbound",OUTBOUND:"outbound"},Object.freeze(this.CALL_DIRECTION),this.STATUS_PERMITTED_FLOW=new Map([["STARTED",new Set([this.CALL_STATUS.RINGING,this.CALL_STATUS.ANSWERED,this.CALL_STATUS.FAILED,this.CALL_STATUS.TIMEOUT,this.CALL_STATUS.UNANSWERED,this.CALL_STATUS.REJECTED,this.CALL_STATUS.BUSY])],["RINGING",new Set([this.CALL_STATUS.ANSWERED,this.CALL_STATUS.FAILED,this.CALL_STATUS.TIMEOUT,this.CALL_STATUS.UNANSWERED,this.CALL_STATUS.REJECTED,this.CALL_STATUS.BUSY])],["ANSWERED",new Set([this.CALL_STATUS.COMPLETED,this.CALL_STATUS.FAILED])]]),Object.freeze(this.STATUS_PERMITTED_FLOW),this.status=null,this.call_disconnect_timeout=null,this.direction=this.CALL_DIRECTION.INBOUND,this._setupConversationObject(d),n.mixin(c)}_enableStatsEvents(){this.conversation.media._enableStatsEvents()}_attachCallListeners(){this.log.debug("_attachCallListeners : ",{nxmCall:this});try{this.conversation.releaseGroup("call_module"),this.conversation.on("member:media","call_module",(l,d)=>{this.application.calls&&this.application.calls.has(this.conversation.id)&&this.application.calls.get(this.conversation.id)._handleStatusChange(d)})}catch(l){this.log.error("_attachCallListeners_error: ",{e:l})}}_isValidStatusTransition(l){if(!l)throw new s.NexmoClientError(`Provide the status to validate the transition from '${this.status}'`);if(!this.status)return!0;const d=this.status.toUpperCase();return!this.STATUS_PERMITTED_FLOW.has(d)||this.status===l?!1:this.STATUS_PERMITTED_FLOW.get(d).has(l)}hangUpIfAllLeft(){if(this.log.debug("hangUpIfAllLeft: ",{nxmCall:this}),!this.conversation.me||this.conversation.me.state==="LEFT"||this.conversation.members.size<=1)return Promise.resolve();for(let l of this.conversation.members.values())if(l.state!=="LEFT"&&this.conversation.me.user.id!==l.user.id)return Promise.resolve();return this.hangUp()}_setupConversationObject(l,d){l&&(this.conversation=l,l.me?(this.to=new Map(l.members),this.from&&this.to.delete(this.from.id)):this.log.warn("missing own member object"),this._attachCallListeners())}_setFrom(l){this.from=l}_setOffer(l){this.offer=l}_handleStatusChange(l){var d;const h=this.conversation?((d=this.conversation.me)===null||d===void 0?void 0:d.id)===l.from:!0,v=this.direction===this.CALL_DIRECTION.OUTBOUND;this.log.debug("_handleStatusChange: ",{event:l},`_isEventFromMe: ${h} _isOutbound: ${v}`);let y=new Map;if(y.set("member:joined",async()=>{if(l.body.channel&&l.body.channel.id)try{this._setStatusAndEmit(this.CALL_STATUS.STARTED);return}catch(w){throw this._setStatusAndEmit(this.CALL_STATUS.FAILED),this.log.error(w),w}return Promise.resolve()}),y.set("member:invited",()=>(l.body.invited_by===null&&l.body.user.media&&l.body.user.media.audio_settings&&this._setStatusAndEmit(this.CALL_STATUS.STARTED),Promise.resolve())),y.set("rtc:hangup",()=>this.status===this.CALL_STATUS.ANSWERED?(this._setStatusAndEmit(this.CALL_STATUS.COMPLETED),Promise.resolve()):h&&v||!h&&!v?(this._setStatusAndEmit(this.CALL_STATUS.UNANSWERED),Promise.resolve()):(this._setStatusAndEmit(this.CALL_STATUS.REJECTED),Promise.resolve())),y.set("member:left",()=>{if(!l.body.timestamp.hasOwnProperty("joined")&&this.status!==this.CALL_STATUS.ANSWERED)return h&&v||!h&&!v?(this._setStatusAndEmit(this.CALL_STATUS.UNANSWERED),Promise.resolve()):(this._setStatusAndEmit(this.CALL_STATUS.REJECTED),Promise.resolve())}),y.set("member:media",()=>(this.status!==this.CALL_STATUS.ANSWERED&&l.body.audio&&(h&&l.body.channel&&(this.id=l.body.channel.id),(!h||!v)&&this.id&&this._setStatusAndEmit(this.CALL_STATUS.ANSWERED)),Promise.resolve())),y.set("sip:ringing",()=>(this.status!==this.CALL_STATUS.RINGING&&this._setStatusAndEmit(this.CALL_STATUS.RINGING),Promise.resolve())),y.set("sip:hangup",()=>{switch(l.body.reason.sip_code){case 486:this._setStatusAndEmit(this.CALL_STATUS.BUSY);break;case 487:this._setStatusAndEmit(this.CALL_STATUS.TIMEOUT);break;case 403:this._setStatusAndEmit(this.CALL_STATUS.FAILED);break}return Promise.resolve()}),y.set("knocking:delete:success",()=>(this._setStatusAndEmit(this.CALL_STATUS.UNANSWERED),Promise.resolve())),y.has(l.type))return y.get(l.type).call(this)}_setStatusAndEmit(l){this._isValidStatusTransition(l)&&(this.status=l,this.log.debug(`_setStatusAndEmit: ${l}`,{nxmCall:this}),this.application.emit("call:status:changed",this))}async answer(l=!0){if(this.log.debug(`answer: { autoPlayAudio: ${l}`),this.conversation)try{await this.conversation.join();const d=await this.conversation.media.enable({autoPlayAudio:l,offer:this.offer});return this.offer=void 0,d}catch(d){throw this._setStatusAndEmit(this.CALL_STATUS.FAILED),this.log.error(d),d}else throw new s.NexmoClientError("error:call:answer")}async createCall(l,d=!0){if(this.log.debug(`createCall: { usernames: ${l}, autoPlayAudio: ${d} }`),!l||!Array.isArray(l)||l.length===0)return Promise.reject(new s.NexmoClientError("error:application:call:params"));try{const h=await this.application.newConversationAndJoin({display_name:"CALL_"+this.application.me.name+"_"+l.join("_").replace(" ","")});h.members.set(h.me.id,h.me),this.from=h.me,this.successful_invited_members=new Map;const v=l.map(async w=>{try{const k=await h.inviteWithAudio({user_name:w});return h.members.set(k.id,k),this.successful_invited_members.set(k.id,k),k}catch(k){return this.log.error(k),k}}),y=async()=>{if(this.successful_invited_members.size>0)return await h.media.enable({audio:{muted:!1,earmuffed:!1},autoPlayAudio:d}),this.application.calls.set(h.id,this),v;throw v};return await Promise.all(v),this._setupConversationObject(h),await y()}catch(h){throw this.log.error(h),this._setStatusAndEmit(this.CALL_STATUS.FAILED),h}}async createServerCall(l,d,h){this.log.debug(`createServerCall: { user: ${l}, type: ${d}, custom_data: `,{custom_data:h});const v={type:d};d==="phone"?v.number=l:v.user=l;try{const{stream:y,legId:w,rtcObjects:k}=await a.default.prewarmLeg(this);this.log.debug("createServerCall: ",{stream:y},{legId:w},{rtcObjects:k}),this.rtcObjects=k,this.stream=y,this.id=w,this.application._call_draft_list.set(w,this),a.default.playAudioStream(y);const I={type:"POST",path:"knocking",data:{channel:{type:"app",from:{type:"app"},to:v,id:w||null},...h&&Object.keys(h).length&&{properties:{custom_data:h}}}};try{const A=await this.application.session.sendNetworkRequest(I);this.knocking_id=A.id}catch(A){throw new s.NexmoApiError(A)}return a.default.cleanCallMediaIfFailed(this),y}catch(y){throw a.default.cleanMediaProperties(this),y}}async hangUp(l){if(this.log.debug(`hangUp: { reason: ${l} }`),this.conversation&&await this.conversation.media.disable(),!this.knocking_id&&this.conversation)return this.conversation.leave(l).catch(d=>{if(d.type!=="conversation:error:invalid-member-state")return Promise.reject(d)});{let d=`knocking/${this.knocking_id}`;if(l){let h=new URLSearchParams;Object.keys(l).forEach(v=>{h.append(v,l[v])}),d+=`?${h.toString()}`}try{const h=await this.application.session.sendNetworkRequest({type:"DELETE",path:d});return this.application._call_draft_list.get(this.client_ref)._handleStatusChange(h),this.application._call_draft_list.delete(this.client_ref),h}catch(h){if(this.conversation)return this.log.error(new s.NexmoApiError(h)),this.conversation.leave(l).catch(v=>{if(v.type!=="conversation:error:invalid-member-state")return Promise.reject(v)});this.log.debug("hangup: Problem cancelling the call. Knocking cancel failed and Conversation. Leave not available",h);return}}}reject(l){return this.log.debug(`reject: { reason: ${l} }`),this.conversation?this.conversation.leave(l):Promise.reject(new s.NexmoClientError("error:call:reject"))}}e.default=c,r.exports=c}(Gh,Gh.exports)),Gh.exports}var sS={exports:{}};(function(r,e){Object.defineProperty(e,"__esModule",{value:!0});const t=Gr;class n{constructor(s){this.log=t.getLogger(this.constructor.name),this.application=s,this._handleSipCallEventMap={"sip:hangup":this._processSipHangup,"sip:ringing":this._processSipRinging}}_handleSipCallEvent(s){if(this.log.debug("_handleSipCallEvent: ",{event:s}),!this.application.calls.has(s.cid)){this.log.warn("There is no call object for this Conversation id.");return}const a=this.application.calls.get(s.cid);if(this._handleSipCallEventMap.hasOwnProperty(s.type))return this._handleSipCallEventMap[s.type].call(this,a,s)}_processSipHangup(s,a){this.log.debug("_processSipHangup: ",a),s._handleStatusChange(a)}_processSipRinging(s,a){this.log.debug("_processSipRinging: ",a),s._handleStatusChange(a)}}e.default=n,r.exports=n})(sS,sS.exports);var gG=sS.exports,aS={exports:{}};(function(r,e){Object.defineProperty(e,"__esModule",{value:!0});const t=Gr;class n{constructor(s){this.log=t.getLogger(this.constructor.name),this.application=s,this._handleRtcEventMap={"rtc:transfer":this._processRtcTransfer,"rtc:answer":this._processRtcAnswer,"rtc:hangup":this._processRtcHangup}}_handleRtcEvent(s){if(this._handleRtcEventMap.hasOwnProperty(s.type))return this._handleRtcEventMap[s.type].call(this,s)}_processRtcTransfer(s){this.log.debug("_processRtcTransfer: ",{event:s});const a=this.application.conversations.get(s.body.transferred_from),c=this.application.conversations.get(s.cid),o=this.application.calls.get(s.body.transferred_from);if(!o){this.log.warn("NXMCall transfer for unknown nxmCall");return}o.conversation.members.get(s.body.was_member).transferred_to=c,o._setupConversationObject(c),o.transferred=!0,this.application.calls.set(s.cid,o),this.application.calls.delete(s.body.transferred_from),a&&(c.members.get(s.from).transferred_from=a,c.media._attachEndingEventHandlers(),Object.entries(c.media.rtcObjects).length===0&&Object.entries(a.media.rtcObjects).length!==0&&Object.assign(c.media.rtcObjects,a.media.rtcObjects),!c.media.pc&&a.media.pc&&Object.assign(c.media.pc=a.media.pc),c.application.activeStreams.length===0&&a.application.activeStreams.length>0&&(c.application.activeStreams=a.application.activeStreams))}_processRtcAnswer(s){this.log.debug("_processRtcAnswer: ",{event:s}),this.application.calls.has(s.cid)&&(this.application.calls.get(s.cid).id=s.body.rtc_id)}_processRtcHangup(s){this.log.debug("_processRtcHangup: ",{event:s}),this.application.calls.has(s.cid)&&this.application.calls.get(s.cid)._handleStatusChange(s)}}e.default=n,r.exports=n})(aS,aS.exports);var mG=aS.exports,zh={exports:{}},Nk;function yG(){return Nk||(Nk=1,function(r,e){var t=Ye&&Ye.__importDefault||function(l){return l&&l.__esModule?l:{default:l}};Object.defineProperty(e,"__esModule",{value:!0});const n=Gr,i=t(oo),s=t(K$()),a=t(_a()),c=t(sg());class o{constructor(d){this.log=n.getLogger(this.constructor.name),this.application=d,this._handleApplicationEventMap={"member:joined":this._processMemberJoined,"member:invited":this._processMemberInvited}}handleEvent(d){const h=this.application.conversations.get(d.cid),v=Object.assign({},d);return this._handleApplicationEventMap.hasOwnProperty(d.type)?this._handleApplicationEventMap[d.type].call(this,h,new i.default(h,v),d):new i.default(h,v)}_processMemberJoined(d,h,v){try{if(h.body.channel&&this.application._call_draft_list.has(h.body.channel.id)){this.log.debug("_processMemberJoined: outbound serverCall from sdk",{event:h});const y=this.application._call_draft_list.get(h.body.channel.id);let w=((y.rtcObjects||{})[h.body.channel.id]||{}).pc;if(y._setFrom(d.me),y._setupConversationObject(d,h.body.channel.id),d.media._attachEndingEventHandlers(),Object.entries(d.media.rtcObjects).length===0&&Object.entries(y.rtcObjects).length!==0&&Object.assign(d.media.rtcObjects,y.rtcObjects),!d.media.pc&&w&&Object.assign(d.media.pc=w),d.application.activeStreams.length===0&&y.application.activeStreams.length>0&&(d.application.activeStreams=y.application.activeStreams),delete y.client_ref,delete y.knocking_id,y.rtcStats&&(d.media.rtcStats=y.rtcStats),this.application._call_draft_list.delete(h.body.channel.id),this.application.calls.set(d.id,y),y._handleStatusChange(h),this.log.debug("_processMemberJoined: processedCall ",{nxmCall:y}),d.members&&h.body.member_id){const k=d.members.get(h.body.member_id);k&&this.application.emit("member:call",k,y)}setTimeout(()=>{d!=null&&d.me&&c.default.emitMediaStream(d.me,w,y.stream)},200)}return this.log.debug("_processMemberJoined: default member joined: ",{event:h}),h}catch(y){this.log.error("_processMemberJoined: ",{e:y})}}_processMemberInvited(d,h){var v,y,w,k,I,A;try{if(!d)return this.log.warn(`no conversation object for ${h.type}`),h;if(((v=d.me)===null||v===void 0?void 0:v.user.id)===h.body.invited_by||!(!((w=(y=h.body.user.media)===null||y===void 0?void 0:y.audio_settings)===null||w===void 0)&&w.enabled))return h;const j=a.default.getMemberNumberFromEventOrNull(h.body.channel)||a.default.getMemberFromNameOrNull(d,h.body.invited_by)||"unknown",L=new s.default(this.application,d,j);return this.application.calls.set(d.id,L),!((k=h.body)===null||k===void 0)&&k.sdp&&this.application.session.config.enableInboundOffer&&L._setOffer({sdp:h.body.sdp,leg_id:h.body.channel.id}),!((I=d.display_name)===null||I===void 0)&&I.startsWith("CALL_")||L._handleStatusChange(h),this.application.emit("member:call",this.application.conversations.get(h.cid).members.get((A=h.body)===null||A===void 0?void 0:A.member_id),L),h}catch(j){this.log.error("_processMemberInvited: ",{e:j})}}}e.default=o,r.exports=o}(zh,zh.exports)),zh.exports}var oS={exports:{}};(function(r,e){var t=Ye&&Ye.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(e,"__esModule",{value:!0});const n=t(ag);class i extends n.default{constructor(a){super(a),this.items=new Map,a.items.forEach(c=>{const o=this.application.updateOrCreateConversation(c);this.items.set(o.id,o)})}getPrev(){return this.hasPrev()?this.application.getConversations(this._getConfig(this.cursor.prev)):this._getError()}getNext(){return this.hasNext()?this.application.getConversations(this._getConfig(this.cursor.next)):this._getError()}}e.default=i,r.exports=i})(oS,oS.exports);var _G=oS.exports,uS={exports:{}},cS={exports:{}};(function(r,e){Object.defineProperty(e,"__esModule",{value:!0});const t=Zo;class n{constructor(s,a){var c,o;this.application=s,this.id=(c=a==null?void 0:a.id)!==null&&c!==void 0?c:null,this._embedded=(o=a==null?void 0:a._embedded)!==null&&o!==void 0?o:null,t.mixin(n)}}e.default=n,r.exports=n})(cS,cS.exports);var bG=cS.exports;(function(r,e){var t=Ye&&Ye.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(e,"__esModule",{value:!0});const n=t(ag),i=t(bG);class s extends n.default{constructor(c){super(c),this.items=new Map,c.items.forEach(o=>{this.items.set(o.id,new i.default(this.application,o))})}getPrev(){return this.hasPrev()?this.application.getUserSessions(this._getConfig(this.cursor.prev)):this._getError()}getNext(){return this.hasNext()?this.application.getUserSessions(this._getConfig(this.cursor.next)):this._getError()}}e.default=s,r.exports=s})(uS,uS.exports);var SG=uS.exports,Kh={exports:{}},Lk;function wG(){return Lk||(Lk=1,function(r,e){var t=Ye&&Ye.__importDefault||function(o){return o&&o.__esModule?o:{default:o}};Object.defineProperty(e,"__esModule",{value:!0}),e.ConversationEventsProcessor=e.EventsQueue=void 0;const n=Ts,i=t(_a()),s=Gr;class a{constructor(l){this.callback=l,this.cidMap=new Map,this.log=s.getLogger(this.constructor.name)}async enqueue(l,d){var h,v,y,w;const{cid:k,id:I}=l,A=Number(I);if(!k||isNaN(A))return this.callback(l);if(!this.cidMap.get(k)){this.log.debug(`enqueue: create new ConversationEventsProcessor for ${k}`);const L=new c(k,A-1,d);if(this.cidMap.set(k,L),l.type=="member:media"&&(!((v=(h=l.body)===null||h===void 0?void 0:h.media)===null||v===void 0)&&v.audio)||l.type=="member:joined"&&(!((w=(y=l.body)===null||y===void 0?void 0:y.channel)===null||w===void 0)&&w.id)){const x=A-20<1?1:A-20,B=await L.fetchConversationEvents(x,20);let G=!1;B.forEach(K=>{K.type==="rtc:transfer"&&K.from===l.from&&(G=!0,L.lastEventIdProcessed=Number(K.id)-1),G&&L.enqueue(Number(K.id),K)})}}const j=this.cidMap.get(k);j.enqueue(A,l),j.processing||(j.processing=!0,await j.processEvents())}}e.EventsQueue=a;class c{constructor(l,d,h){this.cid=l,this.eventsMap=new Map,this.callback=v=>h._handleEvent(v),this.lastEventIdProcessed=d,this.largestEventIdInQueue=d,this.processing=!1,this.application=h,this.eventsFetchRange=9,this.log=s.getLogger(this.constructor.name)}enqueue(l,d){return l>this.largestEventIdInQueue&&(this.largestEventIdInQueue=l),l>this.lastEventIdProcessed&&this.eventsMap.set(l,d),d}dequeue(l){const d=this.eventsMap.get(l);return this.eventsMap.delete(l),d}async processEvents(){const l=()=>(this.eventsMap.clear(),this.log.debug("processEvents: Done Processing"),this.processing=!1);if(this.eventsMap.size<1)return l();const d=this.lastEventIdProcessed+1,h=await this.processNextEvent(d);return h?(this.lastEventIdProcessed=Number(h.id),this.processEvents()):l()}async processNextEvent(l){this.log.debug(`processNextEvent: processing event number ${l}`);const d=this.dequeue(l);try{if(d)return await this.callback(d),d;if(this.largestEventIdInQueue>l){this.log.debug(`processNextEvent: largestEventIdInQueue-${this.largestEventIdInQueue} > eventId-${l}`);const h=await this.fetchEventsAndProcess(l);return h?(this.log.debug("processNextEvent: foundEvent ",{foundEvent:h}),await this.callback(h),h):(this.log.debug(`processNextEvent: not found process next ${l+1}`),this.processNextEvent(l+1))}return}catch{return}}async fetchEventsAndProcess(l){try{const d=await this.fetchConversationEvents(l,this.eventsFetchRange);this.log.debug("fetchEventsAndProcess: fetched events list ",{eventsList:d});let h;return d.forEach(v=>{v.cid=this.cid;const y=Number(v.id);isNaN(y)||y<l||(y>l?(this.log.debug(`fetchEventsAndProcess: event > missingEvent ${y} `,{missingEvent:l}),this.enqueue(y,v)):(this.log.debug("fetchEventsAndProcess: foundEvent ",{event:v}),h=v))}),h}catch(d){this.log.debug("fetchEventsAndProcess: error ",{e:d});return}}async fetchConversationEvents(l,d){this.log.debug("fetchConversationEvents: ",this.cid,l);const h=this.largestEventIdInQueue>l?this.largestEventIdInQueue+d:l+d,v=`${this.application.session.config.nexmo_api_url}/beta2/conversations/${this.cid}/events`;try{return(await i.default.paginationRequest(v,{start_id:l,end_id:h},this.application.session.config.token)).items}catch(y){throw new n.NexmoApiError(y)}}}e.ConversationEventsProcessor=c,r.exports={EventsQueue:a,ConversationEventsProcessor:c}}(Kh,Kh.exports)),Kh.exports}var Uk;function og(){return Uk||(Uk=1,function(r,e){var t=Ye&&Ye.__importDefault||function(G){return G&&G.__esModule?G:{default:G}};Object.defineProperty(e,"__esModule",{value:!0});const n=Zo,i=Gr,s=Ts,a=t(ZO),c=t(z$()),o=t(K$()),l=t(gG),d=t(mG),h=t(yG()),v=t(_a()),y=t(G$),w=t(_G),k=t(SG),I=wG(),A=t(Uw());let j=null,L=null,x=null;class B{constructor(K,D){this.log=i.getLogger(this.constructor.name),this.session=K,this.conversations=new Map,this.synced_conversations_count=0,this.start_sync_time=0,this.stop_sync_time=0,this.calls=new Map,this._call_draft_list=new Map,this.pageConfig=new y.default((K.config||{}).conversations_page_config),this.conversations_page_last=null,this.activeStreams=[],j=new l.default(this),L=new d.default(this),x=new h.default(this),this.me=null,Object.assign(this,D),n.mixin(B)}updateOrCreateConversation(K){const D=this.conversations.get(K.id);return D?(D._updateObjectInstance(K),this.conversations.set(K.id,D)):this.conversations.set(K.id,new c.default(this,K)),this.conversations.get(K.id)}async _enqueueEvent(K){this.session.config.enableEventsQueue?(this.eventsQueue||(this.eventsQueue=new I.EventsQueue(D=>this._handleEvent(D))),this.eventsQueue.enqueue(K,this)):this._handleEvent(K)}async _handleEvent(K){var D,fe,X,pe,Q,Oe,Ve;const Ze=!((D=K._embedded)===null||D===void 0)&&D.from_user?((X=(fe=K._embedded)===null||fe===void 0?void 0:fe.from_user)===null||X===void 0?void 0:X.id)===((pe=this.me)===null||pe===void 0?void 0:pe.id):((Oe=(Q=K.body)===null||Q===void 0?void 0:Q.user)===null||Oe===void 0?void 0:Oe.user_id)===((Ve=this.me)===null||Ve===void 0?void 0:Ve.id),Xe=v.default._checkIfUserIsReInvited(this.conversations,K);if(K.type.startsWith("sip"))return j._handleSipCallEvent(K),K;if(this.conversations.has(K.cid)&&K.type!=="rtc:transfer"&&!Xe)return K.type.startsWith("rtc")&&L._handleRtcEvent(K),this.conversations.get(K.cid)._handleEvent(K),(K.type==="member:joined"||K.type==="member:invited")&&Ze&&this._handleApplicationEvent(K),K;if(K.cid)try{Xe&&this.conversations.delete(K.cid);let Re;return v.default._isCallEvent(K)?Re=await this.getConversation(K.cid,B.CONVERSATION_API_VERSION.v1):Re=await this.getConversation(K.cid,B.CONVERSATION_API_VERSION.v3),this.conversations.set(K.cid,Re),await Re._handleEvent(K),await this._handleApplicationEvent(K),K.type.startsWith("rtc")&&L._handleRtcEvent(K),Promise.resolve(K)}catch(Re){return this.log.error(Re),Promise.reject(Re)}}async updateToken(K){if(this.session.connection&&this.session.connection.disconnected)return this.session.config.token=K,this.session.connection.io.opts.query.token=K,Promise.resolve();const D={url:`${this.session.config.nexmo_api_url}/v0.2/sessions/${this.session.session_id}`,type:"PUT",token:K};try{await v.default.networkRequest(D),this.me&&(this.session.config.token=K,this.session.connection.io.opts.query.token=K)}catch(fe){throw new s.NexmoApiError(fe)}}async _handleApplicationEvent(K){try{this.log.debug("_handleApplicationEvent: ",{event:K});const D=x.handleEvent(K),fe=this.conversations.get(K.cid);let X;if(fe.members.has((D||{}).from))X=fe.members.get(D.from);else if(K.type==="member:joined"||K.type==="member:invited"){const pe={...K.body,...K.from&&{member_id:K.from}};X=new A.default(fe,pe)}else try{X=await fe.getMember(D.from)}catch(pe){this.log.warn(`There is an error getting the member ${pe}`)}return this.emit(D.type,X,D),K}catch(D){throw this.log.error("_handleApplicationEvent: ",D),D}}async inAppCall(K){if(!K||!Array.isArray(K)||K.length===0)return Promise.reject(new s.NexmoClientError("error:application:call:params"));try{const D=new o.default(this);return await D.createCall(K),D.direction=D.CALL_DIRECTION.OUTBOUND,D}catch(D){throw D}}async callServer(K,D="phone",fe={}){try{const X=new o.default(this);return X.direction=X.CALL_DIRECTION.OUTBOUND,await X.createServerCall(K,D,fe),X}catch(X){throw X}}async reconnectCall(K,D,fe={}){try{if(!K||!D)throw new s.NexmoClientError("error:missing:params");const X=await this.getConversation(K,B.CONVERSATION_API_VERSION.v1);await X.media.enable({...fe,reconnectRtcId:D});const pe=new o.default(this,X),Q=Array.from(X.events.values()).map(Oe=>Oe.type);return Q.includes("sip:answered")?pe.status=pe.CALL_STATUS.ANSWERED:Q.includes("sip:ringing")?pe.status=pe.CALL_STATUS.RINGING:pe.status=pe.CALL_STATUS.STARTED,pe.rtcObjects=X.media.rtcObjects,this.calls.set(X.id,pe),pe}catch(X){throw X}}async newConversation(K={}){try{const D=await this.session.sendNetworkRequest({type:"POST",path:"conversations",data:K}),fe=new c.default(this,D);return this.conversations.set(fe.id,fe),this.getConversation(fe.id,B.CONVERSATION_API_VERSION.v1)}catch(D){throw new s.NexmoApiError(D)}}async newConversationAndJoin(K){const D=await this.newConversation(K);return await D.join(),D}async getConversation(K,D=B.CONVERSATION_API_VERSION.v3){if(D!==B.CONVERSATION_API_VERSION.v1&&D!==B.CONVERSATION_API_VERSION.v3)throw new s.NexmoClientError("error:conversation-service:version");let fe;if(D===B.CONVERSATION_API_VERSION.v1)try{fe=await this.session.sendNetworkRequest({type:"GET",path:`conversations/${K}`}),fe.id=fe.uuid,delete fe.uuid}catch(pe){throw new s.NexmoApiError(pe)}else try{fe=await this.session.sendNetworkRequest({type:"GET",path:`conversations/${K}`,version:"v0.3"})}catch(pe){throw new s.NexmoApiError(pe)}const X=this.updateOrCreateConversation(fe);if(D===B.CONVERSATION_API_VERSION.v3&&!X.me)try{const pe=await X.getMyMember();X.me=pe,X.members.set(pe.id,pe)}catch{try{const Q=await X.getMyMember();X.me=Q,X.members.set(Q.id,Q)}catch{this.log.warn(`You don't have any membership in ${X.id}`)}}if(this.session.config.sync==="full"){const{items:pe}=await X.getEvents();return X.events=pe,X}else return X}async getConversations(K={}){const D=`${this.session.config.nexmo_api_url}/beta2/users/${this.me.id}/conversations`;let fe=Object.keys(K).length===0?this.pageConfig:new y.default(K);try{const X=await v.default.paginationRequest(D,fe,this.session.config.token);X.application=this;const pe=new w.default(X);return this.conversations_page_last=pe,pe}catch(X){throw new s.NexmoApiError(X)}}syncConversations(K){const D=Array.from(K.values()),fe=D.length,X=new Date;this.start_sync_time=typeof window<"u"&&window.performance?window.performance.now():X.getTime();const pe=async()=>{this.synced_conversations_percentage=Number((this.synced_conversations_count/fe*100).toFixed(2));const Q={sync_progress:this.synced_conversations_percentage};if(this.emit("sync:progress",Q),this.log.info("Loading sync progress: "+this.synced_conversations_count+"/"+fe+" - "+this.synced_conversations_percentage+"%"),this.synced_conversations_percentage>=100){const Oe=new Date;this.stop_sync_time=typeof window<"u"&&window.performance?window.performance.now():Oe.getTime(),this.log.info("Loaded conversations in "+(this.stop_sync_time-this.start_sync_time)+"ms")}this.synced_conversations_count<fe&&(await this.getConversation(D[this.synced_conversations_count].id),pe(),this.synced_conversations_count++,this.sync_progress_buffer++)};pe()}async getUser(K=this.me.id){try{const D=await this.session.sendNetworkRequest({type:"GET",path:`users/${K}`});return new a.default(this,D)}catch(D){throw new s.NexmoApiError(D)}}async getUserSessions(K={}){var D;const fe=((D=K)===null||D===void 0?void 0:D.user_id)||this.me.id,X=`${this.session.config.nexmo_api_url}/v0.3/users/${fe}/sessions`;let pe=Object.keys(K).length===0?this.pageConfig:new y.default(K);try{const Q=await v.default.paginationRequest(X,pe,this.session.config.token,B.CONVERSATION_API_VERSION.v3);Q.application=this;const Oe=new k.default(Q);return this.user_sessions_page_last=Oe,Oe}catch(Q){throw new s.NexmoApiError(Q)}}}e.default=B,B.CONVERSATION_API_VERSION={v1:"v0.1",v3:"v0.3"},r.exports=B}(xh,xh.exports)),xh.exports}var Fk;function _a(){return Fk||(Fk=1,function(r,e){var t=Ye&&Ye.__importDefault||function(l){return l&&l.__esModule?l:{default:l}};Object.defineProperty(e,"__esModule",{value:!0});const n=t(IH),i=t(zO),s=t(og()),a=4e4,c=2e4;class o{static getMemberFromNameOrNull(d,h){if(!d||!h)return null;for(let v of d.members.values())if(v.user.name===h)return v;return null}static getMemberNumberFromEventOrNull(d){const h=d&&d.from;return h&&(h.number||h.uri)?h.number||h.uri:null}static networkRequest(d){return new Promise((h,v)=>{!d.token&&!d.url.includes("logging")&&!d.url.includes("ping")&&v({response:{type:"error:user:token",description:"network error on request. Please create a new session."}});const y=new XMLHttpRequest;let w;y.open(d.type,d.url,!0),d.token&&y.setRequestHeader("Authorization","Bearer "+d.token),d&&d.url.includes("image")?(y.responseType="",w=d.data,y.onloadstart=()=>{h(y)}):(y.responseType=d.responseType||"json",w=JSON.stringify(d.data)||null,y.setRequestHeader("Content-type","application/json; charset=utf-8")),y.onload=()=>{y.status===200||y.status===201||y.status===204?h(y):v(y)},y.onerror=k=>{v(k)},y.send(w)})}static async paginationRequest(d,h,v,y=s.default.CONVERSATION_API_VERSION.v1){try{const w=await o.networkRequest({type:"GET",url:o.addUrlSearchParams(d,h),token:v}),{page_size:k,_embedded:I,_links:A}=w.response,j=d.split("/").pop().trim();return{items:y===s.default.CONVERSATION_API_VERSION.v1?I.data[j]:I[j],cursor:{prev:A.prev?new URLSearchParams(A.prev.href).get("cursor"):"",next:A.next?new URLSearchParams(A.next.href).get("cursor"):"",self:A.self?new URLSearchParams(A.self.href).get("cursor"):""},page_size:k,order:h.order||"asc",event_type:h.event_type||null}}catch({response:w}){const k=w||{type:"error:network:get-request",description:"network error on nexmo get request"};throw k.validation&&(k.description=k.validation[Object.keys(k.validation)[0]]),k}}static addUrlSearchParams(d,h={}){let v=new URL(d);return Object.keys(h).forEach(y=>{h[y]&&!(typeof h[y]=="string"&&h[y].length<1)&&h[y]!==null&&v.searchParams.set(y,h[y])}),v.href}static deepMergeObj(d,h){const v=JSON.parse(JSON.stringify(d));for(let y in h)Object.prototype.toString.call(h[y])==="[object Object]"?v[y]=o.deepMergeObj(v[y],h[y]):v[y]=h[y];return v}static injectScript(d,h){if(typeof document<"u"){let v=document.getElementsByTagName("head")[0],y=document.createElement("script");y.async=!0,y.src=d,y.onload=y.onreadystatechange=()=>{(!y.readyState||/loaded|complete/.test(y.readyState))&&(y.onload=y.onreadystatechange=null,y=null,h&&h())},v.insertBefore(y,v.firstChild)}}static allocateUUID(){return n.default.v4()}static validateDTMF(d){return typeof d=="string"?/^[\da-dA-D#*pP]{1,45}$$/.test(d):!1}static _getBugsnagKey(){return"76498fc1ca8d9b0a173a44e2b873d7ed"}static updateMemberLegs(d,h){if(d){const v=d.find(y=>y.leg_id===h.body.leg_id);if(!v)d.push({leg_id:h.body.leg_id,status:h.body.status});else if(v.status!==h.body.status){let y=d.indexOf(v);d.fill(v.status=h.body.status,y,y++)}}else d=[{leg_id:h.body.leg_id,status:h.body.status}];return d}static _isCallEvent(d){const{channel:h,media:v}=d.body;return!!(d.type==="rtc:transfer"||h&&(v&&v.audio_settings&&v.audio_settings.enabled||v&&v.audio&&v.audio.enabled||h.knocking_id))}static async _fetchImage(d,h){const{response:v}=await o.networkRequest({type:"GET",url:d,responseType:"arraybuffer",token:h}),y=new Uint8Array(v);let w="";const k=8*1024;let I;for(I=0;I<y.length/k;I++)w+=String.fromCharCode.apply(null,y.subarray(I*k,(I+1)*k));return w+=String.fromCharCode.apply(null,y.subarray(I*k)),"data:image/jpeg;base64,"+btoa(w)}static async _checkHttpConnectivity(d){const h=Date.now();try{await o.networkRequest({type:"GET",url:d});const v=Date.now()-h;return{url:d,canConnect:!0,connectionTime:v}}catch(v){return{url:d,canConnect:!1,error:v}}}static _checkWsConnectivity(d,h,v){return new Promise((y,w)=>{const k=Object.assign({path:h},v),I=Date.now(),A=i.default.connect(d,k),j=setTimeout(()=>y({url:d,canConnect:!1}),c);A.on("connect",()=>{const L=Date.now()-I;A.disconnect(),clearTimeout(j),y({url:d,canConnect:!0,connectionTime:L})}),A.on("error",L=>{A.disconnect(),clearTimeout(j),y({url:d,canConnect:!1,error:L})})})}static async _checkMediaServers(d,h,v){try{const{response:y}=await o.networkRequest({type:"GET",url:`${h}/v0.3/discovery/media/${v}`,token:d}),w=y.map(k=>o._checkMediaConnectivity(k.ip,k.port));return await Promise.all(w)}catch{return[]}}static async _checkMediaConnectivity(d,h){return new Promise(async(v,y)=>{const w={iceServers:[{urls:`stun:${d}:${h}`}]},k=new RTCPeerConnection(w),I=Date.now(),A=await k.createOffer({offerToReceiveAudio:!0});k.setLocalDescription(A);const j=setTimeout(()=>{k.close(),v({ip:d,canConnect:!1})},a);k.onicecandidate=({candidate:L})=>{if((L==null?void 0:L.type)==="srflx"){const x=Date.now()-I;clearTimeout(j),k.close(),v({ip:d,canConnect:!0,connectionTime:x})}},k.onicecandidateerror=L=>{L.errorCode&&(k.close(),clearTimeout(j),v({ip:d,canConnect:!1,error:L}))}})}static _checkIfUserIsReInvited(d,h){var v;if(!d.has(h.cid)||!(h.type==="member:invited"||h.type==="member:joined"))return!1;const y=(v=d.get(h.cid))===null||v===void 0?void 0:v.me;return y?y.user.name===h.body.user.name&&y.state==="LEFT":!1}}e.default=o,r.exports=o}(Oh,Oh.exports)),Oh.exports}var lS={exports:{}};(function(r,e){Object.defineProperty(e,"__esModule",{value:!0});const t=Gr,n=Ts;class i{constructor(a){if(this.log=t.getLogger(this.constructor.name),!a)throw new n.NexmoClientError("no emitter object passed for the Error Emitter");this.emitter=a,this.LISTENER_GROUP="NXM-errors"}emitResponseIfError(a){if(this._isTypeError(a.type))return this.emitter.emit(a.type,this.LISTENER_GROUP,a)}cleanup(){return this.emitter.releaseGroup(this.LISTENER_GROUP)}_isTypeError(a){return a.indexOf("error")!==-1}}e.default=i,r.exports=i})(lS,lS.exports);var TG=lS.exports;(function(r,e){var t=Ye&&Ye.__importDefault||function(I){return I&&I.__esModule?I:{default:I}};Object.defineProperty(e,"__esModule",{value:!0});const n=Zo,i=t(aV),s=t(Gr),a=Ts,c=t(zO),o=t(fH),l=t(yH),d=t(_a()),h=t(og()),v=t(TG),y=t(ZO),w=t(sg());i.default.reg(s.default),i.default.apply(s.default,{template:"[%t] %l (NXM-%n):",timestampFormatter:I=>I.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1"),levelFormatter:I=>I.toUpperCase(),nameFormatter:I=>I||"SDK"});class k{constructor(A={}){const j=A;if(this.config={debug:"silent",log_reporter:{enabled:!1,bugsnag_key:null},environment:"production",ips_url:"https://api-us.vonage.com/v1/image",nexmo_api_url:"https://api-us.vonage.com",path:"/v2/rtc",repository:"https://github.com/Nexmo/conversation-js-sdk",SDK_version:"9.2.4",socket_io:{reconnection:!0,reconnectionAttempts:5,reconnectionDelay:2e3,randomizationFactor:.75,reconnectionDelayMax:15e3,forceNew:!0,autoConnect:!0,transports:["websocket"]},sync:"none",url:"https://ws-us.vonage.com",iceServers:[],rtcstats:{remote_collection:!0,remote_collection_url:"https://hlg.tokbox.com/prod/logging/nexmo_client_js_stats",remote_collection_interval:5e3,emit_events:!1,emit_rtc_analytics:!1,emit_interval:1e3},conversations_page_config:{page_size:10,order:"asc",cursor:""},events_page_config:{page_size:10,order:"asc",event_type:""},enableEventsQueue:!0,enableInboundOffer:!1,token:null},this.config.socket_io.query={token:"",SDK_version:this.config.SDK_version,session_version:"0.0.2",OS_family:"js",OS_revision:typeof navigator<"u"?navigator.userAgent:typeof window<"u"?window.navigator.userAgent:"Generic JS navigator"},this.sessionReady=!1,this.session_id=null,this.apiKey=null,this.requests={},this.application=null,["debug","info","warn","error"].includes(j.debug)?s.default.setLevel(j.debug):j.debug===!0?s.default.setLevel("debug"):s.default.setLevel("silent"),this.log=s.default.noConflict(),this.config=d.default.deepMergeObj(this.config,this._sanitizeConfig(j)),this.config.log_reporter.enabled){const L={apiKey:this.config.log_reporter.bugsnag_key||d.default._getBugsnagKey(),appVersion:this.config.socket_io.query.SDK_version,releaseStage:this.config.environment};Ye.NXMbugsnagClient=o.default(L)}n.mixin(k)}_createAndSetConnection(){let A,j=Object.assign({path:this.config.path},this.config.socket_io);return A=c.default.connect(this.config.url,j),this.connection=A,A.on("connect",()=>{this.emit("ready"),this.sessionReady=!0,this.log.info("websocket ready")}),A.on("disconnect",(L,x)=>{this.emit("disconnect",L==="io client disconnect"?k.DISCONNECT_REASON.ClientDisconnected:L==="io server disconnect"&&this.session_id?k.DISCONNECT_REASON.TokenExpired:k.DISCONNECT_REASON.ConnectionError),this.log.info("websocket disconnected",L,x)}),A.io.on("reconnect",L=>{this.emit("reconnect",L),this.log.info("websocket reconnect",L)}),A.io.on("reconnect_attempt",L=>{this.emit("reconnecting",L),this.log.info("websocket reconnecting",L)}),A.on("connect_error",L=>{this.emit("error",new a.NexmoClientError(L)),this.log.error("Socket.io reported a generic error",L)}),A.io.on("reconnect_failed",()=>{this.emit("error",new a.NexmoClientError("error:client:reconnection_failed")),this.log.error("websocket reconnection error")}),A.io.on("packet",L=>{if(L.type!==2||L.data[0]==="echo")return;const x=L.data[1];if(x.type=L.data[0],this.log.debug("<--",x.type,x),this.requests["session:login"]){const B=this.requests["session:login"].callback;delete this.requests["session:login"],B(x)}else if(x.rid in this.requests){const B=this.requests[x.rid].callback;delete this.requests[x.rid],delete x.delay,this.errorsEmitter&&this.errorsEmitter.emitResponseIfError(x),B(x)}else this.errorsEmitter&&x.type.startsWith("system:error:")?this.errorsEmitter.emitResponseIfError(x):x.type.startsWith("session:")?this.updateSession(x):this.application&&this.application._enqueueEvent(x)}),A}_sanitizeConfig(A){let j=A;return A.sync&&["none","lite","full"].indexOf(A.sync)===-1&&(this.log.warn(`invalid param '${A.sync}' for sync, reverting to ${this.config.sync}`),j.sync=this.config.sync),j}sendRequest(A,j){A.tid=d.default.allocateUUID();const L=A.type;delete A.type,this.log.debug("-->",L,A),this.log.info("-->",L,A.tid),this.connection.emit(L,A),this.requests[A.tid]={type:L,request:A,callback:j}}async sendNetworkRequest(A){const j=A.version||"beta",L=`${this.config.nexmo_api_url}/${j}/${A.path}`;A.type==="GET"||A.type==="DELETE"||(A.data?A.data.originating_session=this.session_id:A.data={originating_session:this.session_id});try{const x={type:A.type,url:L,data:A.data?A.data:null,token:(A.data||{}).token?A.data.token:this.config.token||null};this.log.debug("sendNetworkRequest: ",{request:x});const{response:B}=await d.default.networkRequest(x);return B}catch({response:x}){throw x}}createSession(A){return this.config.socket_io.query.token=A,this._createAndSetConnection(),new Promise((j,L)=>{this.log.info(`Client-SDK Version: ${this.config.SDK_version}`),this.config.token=null,this.requests["session:login"]={type:"session:login",callback:async x=>{if(x.type==="session:success")if(this.session_id=x.body.id,this.apiKey=x.body.api_key,this.config.token=A,this.connection.io.opts.query={session_id:this.session_id,token:this.config.token},(!this.application||this.application.me&&this.application.me.id!==x.body.user_id)&&(this.application=new h.default(this,{})),this.application.me||(this.application.me=new y.default(this.application,{id:x.body.user_id,name:x.body.name})),this.errorsEmitter||(this.errorsEmitter=new v.default(this.application)),this.config.log_reporter.enabled&&(Ye.NXMbugsnagClient.user={id:this.application.me.id,name:this.application.me.name,session_id:x.body.id}),this.config.sync!=="none")try{await this.application.getConversations(),j(this.application)}catch(B){L(B)}else j(this.application);else L(new a.NexmoApiError(x))}}})}deleteSession(){return new Promise(async(A,j)=>{const L=()=>this.sendRequest({type:"session:logout",body:{}},x=>{x.type==="session:logged-out"||x.type==="session:terminated"?(this.disconnect(),delete this.errorsEmitter,delete this.application,delete this.connection,this.requests={},this.sessionReady=!1,A(x)):j(x)});if(this.application){let x=[];if(this.application.conversations.size)for(let B of this.application.conversations.values())x.push(B.media.disable());try{await Promise.all(x)}catch(B){this.log.error("deleteSession: ",B)}return L()}else return L()})}updateSession(A){A.type==="session:success"&&(this.session_id=A.body.id,this.connection.io.opts.query.session_id=A.body.id)}disconnect(){return this.connection.disconnect()}connect(){return this.connection.connect()}async connectivityReport(A,j){const x={machineInfo:{ip:w.default.isNode()?void 0:await l.default.v4()},connectivityReport:[]};try{const{response:B}=await d.default.networkRequest({type:"GET",url:`${this.config.nexmo_api_url}/v0.3/discovery/api`,token:A});let G=B;j!=null&&j.dcListCallback&&(G=j.dcListCallback(G));for(const K in G){const D=G[K].endpoint,fe=G[K].https,X=G[K].ws;try{const pe=await d.default._checkHttpConnectivity(fe),Q=await d.default._checkWsConnectivity(X,this.config.path,this.config.socket_io),Oe=await d.default._checkMediaServers(A,D,K),Ve={name:K,signalConnectionReport:{https:pe,ws:Q},mediaConnectionReport:Oe};x.connectivityReport.push(Ve)}catch(pe){this.log.error(`Error generating report for ${K}`,pe)}}}catch(B){this.log.error("Error fetching nexmo servers information",B)}return x}async checkMediaServers(A,j,L){return await d.default._checkMediaServers(A,j,L)}async checkMediaConnectivity(A,j){return await d.default._checkMediaConnectivity(A,j)}}e.default=k,k.DISCONNECT_REASON={ClientDisconnected:"ClientDisconnected",TokenExpired:"TokenExpired",ConnectionError:"ConnectionError"},r.exports=k})(Db,Db.exports);var CG=Db.exports;const EG=Kv(CG),Va=new an("nexmo-chat"),kG=["us-3","us-4","eu-3","eu-4","ap-3","ap-4"];class J$ extends Hv{constructor(){super(...arguments);be(this,"rtc");be(this,"application");be(this,"conversation")}get _client(){if(this.rtc)return this.rtc;const t=RG(this.region);return this.rtc=new EG({nexmo_api_url:`https://api-${this.region}.${t}`,url:`wss://ws-${this.region}.${t}`}),this.rtc}async create(){const{identity:t,token:n}=await this.issueChatToken();Va.info(`Connecting chat, identity: ${t}, token: ${n}`),this.identity=t,this.application=await this._client.createSession(n)}async destroy(){this.cleanupAudio(),this.rtc&&(await this.rtc.deleteSession(),this.rtc=null,this.application=null,this.conversation=null)}async join(t){const n=await this.application.getConversation(t);n.me.state==="JOINED"?Va.info("already joined conversation:",t):(await n.join(),Va.info("success joined conversation:",t)),this.conversation=n}async preview(t){await this.conversation.sendCustomEvent({type:"ujet_preview",body:{chat_preview:t,chat_preview_updated_at:new Date().toJSON()}})}async fetchMessages(t){const n=await this.conversation.getEvents({event_type:"message",order:"desc",page_size:100}),i=[];return n.items.forEach(s=>{const a=s._embedded.from_user.name,c=jk(s,a);t[c.$index]&&(c.file=t[c.$index]),this.trackInTask(c),i.push(c)}),i.reverse()}async sendMessage(t){try{const n=await this.conversation.sendMessage({message_type:"text",text:JSON.stringify(t)});return Va.info(`Message sent from ${this.conversation.id}, id: ${n.id}`),parseInt(n.id,10)}catch(n){Va.warn(`Failed to send a message from ${this.conversation.id}`,{error:n})}}startTyping(){this.conversation&&this.conversation.startTyping()}stopTyping(){this.conversation&&this.conversation.stopTyping()}registerConversationEvents(){this.registerEvents(this.conversation)}registerEvents(t){t.on("message",(n,i)=>{const s=jk(i,n.userName);Va.info(`Message added from ${this.conversation.id}, index: ${s.$index}, sid: ${s.$sid}, timestamp: ${s.$timestamp}, user type: ${s.$userType}`),s.$userType!==_i.END_USER&&this.ping(),this.trackInTask(s),this.events.triggerEvent("message",s)}),t.on("member:joined",n=>{Va.info("conversation: memberJoined",n),this.events.triggerEvent("memberJoined",n.userName)}),t.on("member:left",n=>{Va.info("conversation: memberLeft",n),this.events.triggerEvent("memberLeft",n.userName)}),t.on("text:typing:on",n=>{/^end_user/.test(n.userName)||this.events.triggerEvent("typingStarted",n.userName)}),t.on("text:typing:off",n=>{/^end_user/.test(n.userName)||this.events.triggerEvent("typingEnded",n.userName)})}}be(J$,"type",Wu.NEXMO);Gv(J$);function RG(r){return kG.indexOf(r)>-1?"vonage.com":"nexmo.com"}function jk(r,e){const{id:t,timestamp:n,body:i}=r,[s,a]=e.split("-");let c=0;a&&(c=parseInt(a,10));const o={$index:parseInt(t,10),$sid:t,$timestamp:new Date(Date.parse(n)),$userType:s,$userId:c};try{const l=JSON.parse(i.text);return l.message&&!l.type?{...l,type:"message",...o}:{...l,...o}}catch(l){return Va.warn("Format message failed",{error:l,data:i.text}),{...o,type:ln.TEXT,content:i.text}}}var Y$={},cd=function(r){return r&&r.Math===Math&&r},Qt=cd(typeof globalThis=="object"&&globalThis)||cd(typeof window=="object"&&window)||cd(typeof self=="object"&&self)||cd(typeof Ye=="object"&&Ye)||cd(typeof Ye=="object"&&Ye)||function(){return this}()||Function("return this")(),co={},Ft=function(r){try{return!!r()}catch{return!0}},PG=Ft,jr=!PG(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7}),IG=Ft,df=!IG(function(){var r=(function(){}).bind();return typeof r!="function"||r.hasOwnProperty("prototype")}),AG=df,Jh=Function.prototype.call,$r=AG?Jh.bind(Jh):function(){return Jh.apply(Jh,arguments)},ff={},X$={}.propertyIsEnumerable,Q$=Object.getOwnPropertyDescriptor,OG=Q$&&!X$.call({1:2},1);ff.f=OG?function(e){var t=Q$(this,e);return!!t&&t.enumerable}:X$;var Ku=function(r,e){return{enumerable:!(r&1),configurable:!(r&2),writable:!(r&4),value:e}},Z$=df,ex=Function.prototype,dS=ex.call,$G=Z$&&ex.bind.bind(dS,dS),Wt=Z$?$G:function(r){return function(){return dS.apply(r,arguments)}},tx=Wt,xG=tx({}.toString),MG=tx("".slice),ba=function(r){return MG(xG(r),8,-1)},DG=Wt,NG=Ft,LG=ba,jy=Object,UG=DG("".split),hf=NG(function(){return!jy("z").propertyIsEnumerable(0)})?function(r){return LG(r)==="String"?UG(r,""):jy(r)}:jy,Ju=function(r){return r==null},FG=Ju,jG=TypeError,Xs=function(r){if(FG(r))throw new jG("Can't call method on "+r);return r},BG=hf,qG=Xs,rs=function(r){return BG(qG(r))},By=typeof document=="object"&&document.all,Br=typeof By>"u"&&By!==void 0?function(r){return typeof r=="function"||r===By}:function(r){return typeof r=="function"},WG=Br,Tr=function(r){return typeof r=="object"?r!==null:WG(r)},qy=Qt,VG=Br,HG=function(r){return VG(r)?r:void 0},Cs=function(r,e){return arguments.length<2?HG(qy[r]):qy[r]&&qy[r][e]},GG=Wt,lo=GG({}.isPrototypeOf),zG=Qt,Bk=zG.navigator,qk=Bk&&Bk.userAgent,eu=qk?String(qk):"",rx=Qt,Wy=eu,Wk=rx.process,Vk=rx.Deno,Hk=Wk&&Wk.versions||Vk&&Vk.version,Gk=Hk&&Hk.v8,Ws,fv;Gk&&(Ws=Gk.split("."),fv=Ws[0]>0&&Ws[0]<4?1:+(Ws[0]+Ws[1]));!fv&&Wy&&(Ws=Wy.match(/Edge\/(\d+)/),(!Ws||Ws[1]>=74)&&(Ws=Wy.match(/Chrome\/(\d+)/),Ws&&(fv=+Ws[1])));var Rl=fv,zk=Rl,KG=Ft,JG=Qt,YG=JG.String,Pl=!!Object.getOwnPropertySymbols&&!KG(function(){var r=Symbol("symbol detection");return!YG(r)||!(Object(r)instanceof Symbol)||!Symbol.sham&&zk&&zk<41}),XG=Pl,nx=XG&&!Symbol.sham&&typeof Symbol.iterator=="symbol",QG=Cs,ZG=Br,ez=lo,tz=nx,rz=Object,Il=tz?function(r){return typeof r=="symbol"}:function(r){var e=QG("Symbol");return ZG(e)&&ez(e.prototype,rz(r))},nz=String,Yu=function(r){try{return nz(r)}catch{return"Object"}},iz=Br,sz=Yu,az=TypeError,Es=function(r){if(iz(r))return r;throw new az(sz(r)+" is not a function")},oz=Es,uz=Ju,Xu=function(r,e){var t=r[e];return uz(t)?void 0:oz(t)},Vy=$r,Hy=Br,Gy=Tr,cz=TypeError,lz=function(r,e){var t,n;if(e==="string"&&Hy(t=r.toString)&&!Gy(n=Vy(t,r))||Hy(t=r.valueOf)&&!Gy(n=Vy(t,r))||e!=="string"&&Hy(t=r.toString)&&!Gy(n=Vy(t,r)))return n;throw new cz("Can't convert object to primitive value")},ix={exports:{}},sx=!1,Kk=Qt,dz=Object.defineProperty,Ww=function(r,e){try{dz(Kk,r,{value:e,configurable:!0,writable:!0})}catch{Kk[r]=e}return e},fz=Qt,hz=Ww,Jk="__core-js_shared__",Yk=ix.exports=fz[Jk]||hz(Jk,{});(Yk.versions||(Yk.versions=[])).push({version:"3.48.0",mode:"global",copyright:"© 2013–2025 Denis Pushkarev (zloirock.ru), 2025–2026 CoreJS Company (core-js.io). All rights reserved.",license:"https://github.com/zloirock/core-js/blob/v3.48.0/LICENSE",source:"https://github.com/zloirock/core-js"});var Vw=ix.exports,Xk=Vw,Al=function(r,e){return Xk[r]||(Xk[r]=e||{})},pz=Xs,vz=Object,oi=function(r){return vz(pz(r))},gz=Wt,mz=oi,yz=gz({}.hasOwnProperty),Yr=Object.hasOwn||function(e,t){return yz(mz(e),t)},_z=Wt,bz=0,Sz=Math.random(),wz=_z(1.1.toString),Ol=function(r){return"Symbol("+(r===void 0?"":r)+")_"+wz(++bz+Sz,36)},Tz=Qt,Cz=Al,Qk=Yr,Ez=Ol,kz=Pl,Rz=nx,Hc=Tz.Symbol,zy=Cz("wks"),Pz=Rz?Hc.for||Hc:Hc&&Hc.withoutSetter||Ez,xr=function(r){return Qk(zy,r)||(zy[r]=kz&&Qk(Hc,r)?Hc[r]:Pz("Symbol."+r)),zy[r]},Iz=$r,Zk=Tr,eR=Il,Az=Xu,Oz=lz,$z=xr,xz=TypeError,Mz=$z("toPrimitive"),Hw=function(r,e){if(!Zk(r)||eR(r))return r;var t=Az(r,Mz),n;if(t){if(e===void 0&&(e="default"),n=Iz(t,r,e),!Zk(n)||eR(n))return n;throw new xz("Can't convert object to primitive value")}return e===void 0&&(e="number"),Oz(r,e)},Dz=Hw,Nz=Il,ug=function(r){var e=Dz(r,"string");return Nz(e)?e:e+""},Lz=Qt,tR=Tr,fS=Lz.document,Uz=tR(fS)&&tR(fS.createElement),cg=function(r){return Uz?fS.createElement(r):{}},Fz=jr,jz=Ft,Bz=cg,ax=!Fz&&!jz(function(){return Object.defineProperty(Bz("div"),"a",{get:function(){return 7}}).a!==7}),qz=jr,Wz=$r,Vz=ff,Hz=Ku,Gz=rs,zz=ug,Kz=Yr,Jz=ax,rR=Object.getOwnPropertyDescriptor;co.f=qz?rR:function(e,t){if(e=Gz(e),t=zz(t),Jz)try{return rR(e,t)}catch{}if(Kz(e,t))return Hz(!Wz(Vz.f,e,t),e[t])};var Ci={},Yz=jr,Xz=Ft,ox=Yz&&Xz(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42}),Qz=Tr,Zz=String,e8=TypeError,dn=function(r){if(Qz(r))return r;throw new e8(Zz(r)+" is not an object")},t8=jr,r8=ax,n8=ox,Yh=dn,nR=ug,i8=TypeError,Ky=Object.defineProperty,s8=Object.getOwnPropertyDescriptor,Jy="enumerable",Yy="configurable",Xy="writable";Ci.f=t8?n8?function(e,t,n){if(Yh(e),t=nR(t),Yh(n),typeof e=="function"&&t==="prototype"&&"value"in n&&Xy in n&&!n[Xy]){var i=s8(e,t);i&&i[Xy]&&(e[t]=n.value,n={configurable:Yy in n?n[Yy]:i[Yy],enumerable:Jy in n?n[Jy]:i[Jy],writable:!1})}return Ky(e,t,n)}:Ky:function(e,t,n){if(Yh(e),t=nR(t),Yh(n),r8)try{return Ky(e,t,n)}catch{}if("get"in n||"set"in n)throw new i8("Accessors not supported");return"value"in n&&(e[t]=n.value),e};var a8=jr,o8=Ci,u8=Ku,fo=a8?function(r,e,t){return o8.f(r,e,u8(1,t))}:function(r,e,t){return r[e]=t,r},ux={exports:{}},hS=jr,c8=Yr,cx=Function.prototype,l8=hS&&Object.getOwnPropertyDescriptor,Gw=c8(cx,"name"),d8=Gw&&(function(){}).name==="something",f8=Gw&&(!hS||hS&&l8(cx,"name").configurable),pf={EXISTS:Gw,PROPER:d8,CONFIGURABLE:f8},h8=Wt,p8=Br,pS=Vw,v8=h8(Function.toString);p8(pS.inspectSource)||(pS.inspectSource=function(r){return v8(r)});var zw=pS.inspectSource,g8=Qt,m8=Br,iR=g8.WeakMap,y8=m8(iR)&&/native code/.test(String(iR)),_8=Al,b8=Ol,sR=_8("keys"),lg=function(r){return sR[r]||(sR[r]=b8(r))},vf={},S8=y8,lx=Qt,w8=Tr,T8=fo,Qy=Yr,Zy=Vw,C8=lg,E8=vf,aR="Object already initialized",vS=lx.TypeError,k8=lx.WeakMap,hv,Kd,pv,R8=function(r){return pv(r)?Kd(r):hv(r,{})},P8=function(r){return function(e){var t;if(!w8(e)||(t=Kd(e)).type!==r)throw new vS("Incompatible receiver, "+r+" required");return t}};if(S8||Zy.state){var aa=Zy.state||(Zy.state=new k8);aa.get=aa.get,aa.has=aa.has,aa.set=aa.set,hv=function(r,e){if(aa.has(r))throw new vS(aR);return e.facade=r,aa.set(r,e),e},Kd=function(r){return aa.get(r)||{}},pv=function(r){return aa.has(r)}}else{var Pc=C8("state");E8[Pc]=!0,hv=function(r,e){if(Qy(r,Pc))throw new vS(aR);return e.facade=r,T8(r,Pc,e),e},Kd=function(r){return Qy(r,Pc)?r[Pc]:{}},pv=function(r){return Qy(r,Pc)}}var Fi={set:hv,get:Kd,has:pv,enforce:R8,getterFor:P8},Kw=Wt,I8=Ft,A8=Br,Xh=Yr,gS=jr,O8=pf.CONFIGURABLE,$8=zw,dx=Fi,x8=dx.enforce,M8=dx.get,oR=String,zp=Object.defineProperty,D8=Kw("".slice),N8=Kw("".replace),L8=Kw([].join),U8=gS&&!I8(function(){return zp(function(){},"length",{value:8}).length!==8}),F8=String(String).split("String"),j8=ux.exports=function(r,e,t){D8(oR(e),0,7)==="Symbol("&&(e="["+N8(oR(e),/^Symbol\(([^)]*)\).*$/,"$1")+"]"),t&&t.getter&&(e="get "+e),t&&t.setter&&(e="set "+e),(!Xh(r,"name")||O8&&r.name!==e)&&(gS?zp(r,"name",{value:e,configurable:!0}):r.name=e),U8&&t&&Xh(t,"arity")&&r.length!==t.arity&&zp(r,"length",{value:t.arity});try{t&&Xh(t,"constructor")&&t.constructor?gS&&zp(r,"prototype",{writable:!1}):r.prototype&&(r.prototype=void 0)}catch{}var n=x8(r);return Xh(n,"source")||(n.source=L8(F8,typeof e=="string"?e:"")),r};Function.prototype.toString=j8(function(){return A8(this)&&M8(this).source||$8(this)},"toString");var fx=ux.exports,B8=Br,q8=Ci,W8=fx,V8=Ww,Ei=function(r,e,t,n){n||(n={});var i=n.enumerable,s=n.name!==void 0?n.name:e;if(B8(t)&&W8(t,s,n),n.global)i?r[e]=t:V8(e,t);else{try{n.unsafe?r[e]&&(i=!0):delete r[e]}catch{}i?r[e]=t:q8.f(r,e,{value:t,enumerable:!1,configurable:!n.nonConfigurable,writable:!n.nonWritable})}return r},Qu={},H8=Math.ceil,G8=Math.floor,z8=Math.trunc||function(e){var t=+e;return(t>0?G8:H8)(t)},K8=z8,Sa=function(r){var e=+r;return e!==e||e===0?0:K8(e)},J8=Sa,Y8=Math.max,X8=Math.min,Zu=function(r,e){var t=J8(r);return t<0?Y8(t+e,0):X8(t,e)},Q8=Sa,Z8=Math.min,ho=function(r){var e=Q8(r);return e>0?Z8(e,9007199254740991):0},e9=ho,ui=function(r){return e9(r.length)},t9=rs,r9=Zu,n9=ui,uR=function(r){return function(e,t,n){var i=t9(e),s=n9(i);if(s===0)return!r&&-1;var a=r9(n,s),c;if(r&&t!==t){for(;s>a;)if(c=i[a++],c!==c)return!0}else for(;s>a;a++)if((r||a in i)&&i[a]===t)return r||a||0;return!r&&-1}},dg={includes:uR(!0),indexOf:uR(!1)},i9=Wt,e_=Yr,s9=rs,a9=dg.indexOf,o9=vf,cR=i9([].push),hx=function(r,e){var t=s9(r),n=0,i=[],s;for(s in t)!e_(o9,s)&&e_(t,s)&&cR(i,s);for(;e.length>n;)e_(t,s=e[n++])&&(~a9(i,s)||cR(i,s));return i},Jw=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],u9=hx,c9=Jw,l9=c9.concat("length","prototype");Qu.f=Object.getOwnPropertyNames||function(e){return u9(e,l9)};var gf={};gf.f=Object.getOwnPropertySymbols;var d9=Cs,f9=Wt,h9=Qu,p9=gf,v9=dn,g9=f9([].concat),px=d9("Reflect","ownKeys")||function(e){var t=h9.f(v9(e)),n=p9.f;return n?g9(t,n(e)):t},lR=Yr,m9=px,y9=co,_9=Ci,Yw=function(r,e,t){for(var n=m9(e),i=_9.f,s=y9.f,a=0;a<n.length;a++){var c=n[a];!lR(r,c)&&!(t&&lR(t,c))&&i(r,c,s(e,c))}},b9=Ft,S9=Br,w9=/#|\.prototype\./,mf=function(r,e){var t=C9[T9(r)];return t===k9?!0:t===E9?!1:S9(e)?b9(e):!!e},T9=mf.normalize=function(r){return String(r).replace(w9,".").toLowerCase()},C9=mf.data={},E9=mf.NATIVE="N",k9=mf.POLYFILL="P",fg=mf,Qh=Qt,R9=co.f,P9=fo,I9=Ei,A9=Ww,O9=Yw,$9=fg,Gt=function(r,e){var t=r.target,n=r.global,i=r.stat,s,a,c,o,l,d;if(n?a=Qh:i?a=Qh[t]||A9(t,{}):a=Qh[t]&&Qh[t].prototype,a)for(c in e){if(l=e[c],r.dontCallGetSet?(d=R9(a,c),o=d&&d.value):o=a[c],s=$9(n?c:t+(i?".":"#")+c,r.forced),!s&&o!==void 0){if(typeof l==typeof o)continue;O9(l,o)}(r.sham||o&&o.sham)&&P9(l,"sham",!0),I9(a,c,l,r)}},x9=Ci.f,M9=Yr,D9=xr,dR=D9("toStringTag"),wa=function(r,e,t){r&&!t&&(r=r.prototype),r&&!M9(r,dR)&&x9(r,dR,{configurable:!0,value:e})},N9=Gt,L9=Qt,U9=wa;N9({global:!0},{Reflect:{}});U9(L9.Reflect,"Reflect",!0);var F9=df,vx=Function.prototype,fR=vx.apply,hR=vx.call,ec=typeof Reflect=="object"&&Reflect.apply||(F9?hR.bind(fR):function(){return hR.apply(fR,arguments)}),j9=Wt,Ta=j9([].slice),gx=Wt,B9=Es,q9=Tr,W9=Yr,pR=Ta,V9=df,mx=Function,H9=gx([].concat),G9=gx([].join),t_={},z9=function(r,e,t){if(!W9(t_,e)){for(var n=[],i=0;i<e;i++)n[i]="a["+i+"]";t_[e]=mx("C,a","return new C("+G9(n,",")+")")}return t_[e](r,t)},K9=V9?mx.bind:function(e){var t=B9(this),n=t.prototype,i=pR(arguments,1),s=function(){var c=H9(i,pR(arguments));return this instanceof s?z9(t,c.length,c):t.apply(e,c)};return q9(n)&&(s.prototype=n),s},J9=xr,Y9=J9("toStringTag"),yx={};yx[Y9]="z";var Xw=String(yx)==="[object z]",X9=Xw,Q9=Br,Kp=ba,Z9=xr,e7=Z9("toStringTag"),t7=Object,r7=Kp(function(){return arguments}())==="Arguments",n7=function(r,e){try{return r[e]}catch{}},po=X9?Kp:function(r){var e,t,n;return r===void 0?"Undefined":r===null?"Null":typeof(t=n7(e=t7(r),e7))=="string"?t:r7?Kp(e):(n=Kp(e))==="Object"&&Q9(e.callee)?"Arguments":n},i7=Wt,s7=Ft,_x=Br,a7=po,o7=Cs,u7=zw,bx=function(){},Sx=o7("Reflect","construct"),Qw=/^\s*(?:class|function)\b/,c7=i7(Qw.exec),l7=!Qw.test(bx),ld=function(e){if(!_x(e))return!1;try{return Sx(bx,[],e),!0}catch{return!1}},wx=function(e){if(!_x(e))return!1;switch(a7(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return l7||!!c7(Qw,u7(e))}catch{return!0}};wx.sham=!0;var hg=!Sx||s7(function(){var r;return ld(ld.call)||!ld(Object)||!ld(function(){r=!0})||r})?wx:ld,d7=hg,f7=Yu,h7=TypeError,Zw=function(r){if(d7(r))return r;throw new h7(f7(r)+" is not a constructor")},e0={},p7=hx,v7=Jw,yf=Object.keys||function(e){return p7(e,v7)},g7=jr,m7=ox,y7=Ci,_7=dn,b7=rs,S7=yf;e0.f=g7&&!m7?Object.defineProperties:function(e,t){_7(e);for(var n=b7(t),i=S7(t),s=i.length,a=0,c;s>a;)y7.f(e,c=i[a++],n[c]);return e};var w7=Cs,Tx=w7("document","documentElement"),T7=dn,C7=e0,vR=Jw,E7=vf,k7=Tx,R7=cg,P7=lg,gR=">",mR="<",mS="prototype",yS="script",Cx=P7("IE_PROTO"),r_=function(){},Ex=function(r){return mR+yS+gR+r+mR+"/"+yS+gR},yR=function(r){r.write(Ex("")),r.close();var e=r.parentWindow.Object;return r=null,e},I7=function(){var r=R7("iframe"),e="java"+yS+":",t;return r.style.display="none",k7.appendChild(r),r.src=String(e),t=r.contentWindow.document,t.open(),t.write(Ex("document.F=Object")),t.close(),t.F},Zh,Jp=function(){try{Zh=new ActiveXObject("htmlfile")}catch{}Jp=typeof document<"u"?document.domain&&Zh?yR(Zh):I7():yR(Zh);for(var r=vR.length;r--;)delete Jp[mS][vR[r]];return Jp()};E7[Cx]=!0;var tu=Object.create||function(e,t){var n;return e!==null?(r_[mS]=T7(e),n=new r_,r_[mS]=null,n[Cx]=e):n=Jp(),t===void 0?n:C7.f(n,t)},A7=Gt,O7=Cs,n_=ec,$7=K9,_R=Zw,x7=dn,bR=Tr,M7=tu,kx=Ft,t0=O7("Reflect","construct"),D7=Object.prototype,N7=[].push,Rx=kx(function(){function r(){}return!(t0(function(){},[],r)instanceof r)}),Px=!kx(function(){t0(function(){})}),SR=Rx||Px;A7({target:"Reflect",stat:!0,forced:SR,sham:SR},{construct:function(e,t){_R(e),x7(t);var n=arguments.length<3?e:_R(arguments[2]);if(Px&&!Rx)return t0(e,t,n);if(e===n){switch(t.length){case 0:return new e;case 1:return new e(t[0]);case 2:return new e(t[0],t[1]);case 3:return new e(t[0],t[1],t[2]);case 4:return new e(t[0],t[1],t[2],t[3])}var i=[null];return n_(N7,i,t),new(n_($7,e,i))}var s=n.prototype,a=M7(bR(s)?s:D7),c=n_(e,a,t);return bR(c)?c:a}});var L7=Gt,U7=oi,Ix=yf,F7=Ft,j7=F7(function(){Ix(1)});L7({target:"Object",stat:!0,forced:j7},{keys:function(e){return Ix(U7(e))}});var B7=po,q7=String,$n=function(r){if(B7(r)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return q7(r)},r0={},W7=ba,V7=rs,Ax=Qu.f,H7=Ta,Ox=typeof window=="object"&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],G7=function(r){try{return Ax(r)}catch{return H7(Ox)}};r0.f=function(e){return Ox&&W7(e)==="Window"?G7(e):Ax(V7(e))};var wR=fx,z7=Ci,Ca=function(r,e,t){return t.get&&wR(t.get,e,{getter:!0}),t.set&&wR(t.set,e,{setter:!0}),z7.f(r,e,t)},n0={},K7=xr;n0.f=K7;var J7=Qt,i0=J7,TR=i0,Y7=Yr,X7=n0,Q7=Ci.f,$x=function(r){var e=TR.Symbol||(TR.Symbol={});Y7(e,r)||Q7(e,r,{value:X7.f(r)})},Z7=$r,eK=Cs,tK=xr,rK=Ei,nK=function(){var r=eK("Symbol"),e=r&&r.prototype,t=e&&e.valueOf,n=tK("toPrimitive");e&&!e[n]&&rK(e,n,function(i){return Z7(t,this)},{arity:1})},iK=ba,sK=Wt,s0=function(r){if(iK(r)==="Function")return sK(r)},CR=s0,aK=Es,oK=df,uK=CR(CR.bind),vo=function(r,e){return aK(r),e===void 0?r:oK?uK(r,e):function(){return r.apply(e,arguments)}},cK=ba,_f=Array.isArray||function(e){return cK(e)==="Array"},ER=_f,lK=hg,dK=Tr,fK=xr,hK=fK("species"),kR=Array,pK=function(r){var e;return ER(r)&&(e=r.constructor,lK(e)&&(e===kR||ER(e.prototype))?e=void 0:dK(e)&&(e=e[hK],e===null&&(e=void 0))),e===void 0?kR:e},vK=pK,a0=function(r,e){return new(vK(r))(e===0?0:e)},gK=jr,mK=Ci,yK=Ku,$l=function(r,e,t){gK?mK.f(r,e,yK(0,t)):r[e]=t},_K=vo,bK=hf,SK=oi,wK=ui,RR=a0,i_=$l,Cu=function(r){var e=r===1,t=r===2,n=r===3,i=r===4,s=r===6,a=r===7,c=r===5||s;return function(o,l,d){for(var h=SK(o),v=bK(h),y=wK(v),w=_K(l,d),k=0,I=0,A=e?RR(o,y):t||a?RR(o,0):void 0,j,L;y>k;k++)if((c||k in v)&&(j=v[k],L=w(j,k,h),r))if(e)i_(A,k,L);else if(L)switch(r){case 3:return!0;case 5:return j;case 6:return k;case 2:i_(A,I++,j)}else switch(r){case 4:return!1;case 7:i_(A,I++,j)}return s?-1:n||i?i:A}},ji={forEach:Cu(0),map:Cu(1),filter:Cu(2),some:Cu(3),every:Cu(4),find:Cu(5),findIndex:Cu(6)},pg=Gt,bf=Qt,o0=$r,TK=Wt,pl=jr,vl=Pl,CK=Ft,Un=Yr,EK=lo,_S=dn,vg=rs,u0=ug,kK=$n,bS=Ku,gl=tu,xx=yf,RK=Qu,Mx=r0,PK=gf,Dx=co,Nx=Ci,IK=e0,Lx=ff,s_=Ei,AK=Ca,c0=Al,OK=lg,Ux=vf,PR=Ol,$K=xr,xK=n0,MK=$x,DK=nK,NK=wa,Fx=Fi,gg=ji.forEach,Di=OK("hidden"),mg="Symbol",Jd="prototype",LK=Fx.set,IR=Fx.getterFor(mg),ys=Object[Jd],Fu=bf.Symbol,Ad=Fu&&Fu[Jd],UK=bf.RangeError,FK=bf.TypeError,a_=bf.QObject,jx=Dx.f,ju=Nx.f,Bx=Mx.f,jK=Lx.f,qx=TK([].push),no=c0("symbols"),Sf=c0("op-symbols"),BK=c0("wks"),SS=!a_||!a_[Jd]||!a_[Jd].findChild,Wx=function(r,e,t){var n=jx(ys,e);n&&delete ys[e],ju(r,e,t),n&&r!==ys&&ju(ys,e,n)},wS=pl&&CK(function(){return gl(ju({},"a",{get:function(){return ju(this,"a",{value:7}).a}})).a!==7})?Wx:ju,o_=function(r,e){var t=no[r]=gl(Ad);return LK(t,{type:mg,tag:r,description:e}),pl||(t.description=e),t},yg=function(e,t,n){e===ys&&yg(Sf,t,n),_S(e);var i=u0(t);return _S(n),Un(no,i)?(n.enumerable?(Un(e,Di)&&e[Di][i]&&(e[Di][i]=!1),n=gl(n,{enumerable:bS(0,!1)})):(Un(e,Di)||ju(e,Di,bS(1,gl(null))),e[Di][i]=!0),wS(e,i,n)):ju(e,i,n)},l0=function(e,t){_S(e);var n=vg(t),i=xx(n).concat(Gx(n));return gg(i,function(s){(!pl||o0(TS,n,s))&&yg(e,s,n[s])}),e},qK=function(e,t){return t===void 0?gl(e):l0(gl(e),t)},TS=function(e){var t=u0(e),n=o0(jK,this,t);return this===ys&&Un(no,t)&&!Un(Sf,t)?!1:n||!Un(this,t)||!Un(no,t)||Un(this,Di)&&this[Di][t]?n:!0},Vx=function(e,t){var n=vg(e),i=u0(t);if(!(n===ys&&Un(no,i)&&!Un(Sf,i))){var s=jx(n,i);return s&&Un(no,i)&&!(Un(n,Di)&&n[Di][i])&&(s.enumerable=!0),s}},Hx=function(e){var t=Bx(vg(e)),n=[];return gg(t,function(i){!Un(no,i)&&!Un(Ux,i)&&qx(n,i)}),n},Gx=function(r){var e=r===ys,t=Bx(e?Sf:vg(r)),n=[];return gg(t,function(i){Un(no,i)&&(!e||Un(ys,i))&&qx(n,no[i])}),n};vl||(Fu=function(){if(EK(Ad,this))throw new FK("Symbol is not a constructor");var e=!arguments.length||arguments[0]===void 0?void 0:kK(arguments[0]),t=PR(e),n=function(i){var s=this===void 0?bf:this;s===ys&&o0(n,Sf,i),Un(s,Di)&&Un(s[Di],t)&&(s[Di][t]=!1);var a=bS(1,i);try{wS(s,t,a)}catch(c){if(!(c instanceof UK))throw c;Wx(s,t,a)}};return pl&&SS&&wS(ys,t,{configurable:!0,set:n}),o_(t,e)},Ad=Fu[Jd],s_(Ad,"toString",function(){return IR(this).tag}),s_(Fu,"withoutSetter",function(r){return o_(PR(r),r)}),Lx.f=TS,Nx.f=yg,IK.f=l0,Dx.f=Vx,RK.f=Mx.f=Hx,PK.f=Gx,xK.f=function(r){return o_($K(r),r)},pl&&(AK(Ad,"description",{configurable:!0,get:function(){return IR(this).description}}),s_(ys,"propertyIsEnumerable",TS,{unsafe:!0})));pg({global:!0,constructor:!0,wrap:!0,forced:!vl,sham:!vl},{Symbol:Fu});gg(xx(BK),function(r){MK(r)});pg({target:mg,stat:!0,forced:!vl},{useSetter:function(){SS=!0},useSimple:function(){SS=!1}});pg({target:"Object",stat:!0,forced:!vl,sham:!pl},{create:qK,defineProperty:yg,defineProperties:l0,getOwnPropertyDescriptor:Vx});pg({target:"Object",stat:!0,forced:!vl},{getOwnPropertyNames:Hx});DK();NK(Fu,mg);Ux[Di]=!0;var WK=Pl,zx=WK&&!!Symbol.for&&!!Symbol.keyFor,VK=Gt,HK=Cs,GK=Yr,zK=$n,Kx=Al,KK=zx,u_=Kx("string-to-symbol-registry"),JK=Kx("symbol-to-string-registry");VK({target:"Symbol",stat:!0,forced:!KK},{for:function(r){var e=zK(r);if(GK(u_,e))return u_[e];var t=HK("Symbol")(e);return u_[e]=t,JK[t]=e,t}});var YK=Gt,XK=Yr,QK=Il,ZK=Yu,eJ=Al,tJ=zx,AR=eJ("symbol-to-string-registry");YK({target:"Symbol",stat:!0,forced:!tJ},{keyFor:function(e){if(!QK(e))throw new TypeError(ZK(e)+" is not a symbol");if(XK(AR,e))return AR[e]}});var rJ=Tr,nJ=Fi.get,iJ=function(e){if(!rJ(e))return!1;var t=nJ(e);return!!t&&t.type==="RawJSON"},d0=Wt,sJ=Yr,ep=SyntaxError,aJ=parseInt,oJ=String.fromCharCode,uJ=d0("".charAt),OR=d0("".slice),$R=d0(/./.exec),xR={'\\"':'"',"\\\\":"\\","\\/":"/","\\b":"\b","\\f":"\f","\\n":`
|
|
101
|
+
`},zu=N$,zH=GH,KH=qw;ya.grammar=KH;ya.write=zH;ya.parse=zu.parse;ya.parseParams=zu.parseParams;ya.parseFmtpConfig=zu.parseFmtpConfig;ya.parsePayloads=zu.parsePayloads;ya.parseRemoteCandidates=zu.parseRemoteCandidates;ya.parseImageAttributes=zu.parseImageAttributes;ya.parseSimulcastStreamList=zu.parseSimulcastStreamList;var uo={},JH=Ye&&Ye.__spreadArrays||function(){for(var r=0,e=0,t=arguments.length;e<t;e++)r+=arguments[e].length;for(var n=Array(r),i=0,e=0;e<t;e++)for(var s=arguments[e],a=0,c=s.length;a<c;a++,i++)n[i]=s[a];return n};Object.defineProperty(uo,"__esModule",{value:!0});var U$=function(){function r(e,t,n){this.name=e,this.version=t,this.os=n}return r}();uo.BrowserInfo=U$;var F$=function(){function r(e){this.version=e,this.name="node",this.os=process.platform}return r}();uo.NodeInfo=F$;var j$=function(){function r(){this.bot=!0,this.name="bot",this.version=null,this.os=null}return r}();uo.BotInfo=j$;var YH=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,XH=/(nuhk)|(Googlebot)|(Yammybot)|(Openbot)|(Slurp)|(MSNBot)|(Ask Jeeves\/Teoma)|(ia_archiver)/,Ck=3,QH=[["aol",/AOLShield\/([0-9\._]+)/],["edge",/Edge\/([0-9\._]+)/],["edge-ios",/EdgiOS\/([0-9\._]+)/],["yandexbrowser",/YaBrowser\/([0-9\._]+)/],["vivaldi",/Vivaldi\/([0-9\.]+)/],["kakaotalk",/KAKAOTALK\s([0-9\.]+)/],["samsung",/SamsungBrowser\/([0-9\.]+)/],["silk",/\bSilk\/([0-9._-]+)\b/],["miui",/MiuiBrowser\/([0-9\.]+)$/],["beaker",/BeakerBrowser\/([0-9\.]+)/],["edge-chromium",/Edg\/([0-9\.]+)/],["chromium-webview",/(?!Chrom.*OPR)wv\).*Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["chrome",/(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["phantomjs",/PhantomJS\/([0-9\.]+)(:?\s|$)/],["crios",/CriOS\/([0-9\.]+)(:?\s|$)/],["firefox",/Firefox\/([0-9\.]+)(?:\s|$)/],["fxios",/FxiOS\/([0-9\.]+)/],["opera-mini",/Opera Mini.*Version\/([0-9\.]+)/],["opera",/Opera\/([0-9\.]+)(?:\s|$)/],["opera",/OPR\/([0-9\.]+)(:?\s|$)/],["ie",/Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/],["ie",/MSIE\s([0-9\.]+);.*Trident\/[4-7].0/],["ie",/MSIE\s(7\.0)/],["bb10",/BB10;\sTouch.*Version\/([0-9\.]+)/],["android",/Android\s([0-9\.]+)/],["ios",/Version\/([0-9\._]+).*Mobile.*Safari.*/],["safari",/Version\/([0-9\._]+).*Safari/],["facebook",/FBAV\/([0-9\.]+)/],["instagram",/Instagram\s([0-9\.]+)/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Mobile/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Gecko\)$/],["searchbot",YH]],Ek=[["iOS",/iP(hone|od|ad)/],["Android OS",/Android/],["BlackBerry OS",/BlackBerry|BB10/],["Windows Mobile",/IEMobile/],["Amazon OS",/Kindle/],["Windows 3.11",/Win16/],["Windows 95",/(Windows 95)|(Win95)|(Windows_95)/],["Windows 98",/(Windows 98)|(Win98)/],["Windows 2000",/(Windows NT 5.0)|(Windows 2000)/],["Windows XP",/(Windows NT 5.1)|(Windows XP)/],["Windows Server 2003",/(Windows NT 5.2)/],["Windows Vista",/(Windows NT 6.0)/],["Windows 7",/(Windows NT 6.1)/],["Windows 8",/(Windows NT 6.2)/],["Windows 8.1",/(Windows NT 6.3)/],["Windows 10",/(Windows NT 10.0)/],["Windows ME",/Windows ME/],["Open BSD",/OpenBSD/],["Sun OS",/SunOS/],["Chrome OS",/CrOS/],["Linux",/(Linux)|(X11)/],["Mac OS",/(Mac_PowerPC)|(Macintosh)/],["QNX",/QNX/],["BeOS",/BeOS/],["OS/2",/OS\/2/],["Search Bot",XH]];function ZH(r){return r?rS(r):typeof navigator<"u"?rS(navigator.userAgent):q$()}uo.detect=ZH;function rS(r){var e=r!==""&&QH.reduce(function(s,a){var c=a[0],o=a[1];if(s)return s;var l=o.exec(r);return!!l&&[c,l]},!1);if(!e)return null;var t=e[0],n=e[1];if(t==="searchbot")return new j$;var i=n[1]&&n[1].split(/[._]/).slice(0,3);return i?i.length<Ck&&(i=JH(i,eG(Ck-i.length))):i=[],new U$(t,i.join("."),B$(r))}uo.parseUserAgent=rS;function B$(r){for(var e=0,t=Ek.length;e<t;e++){var n=Ek[e],i=n[0],s=n[1],a=s.test(r);if(a)return i}return null}uo.detectOS=B$;function q$(){var r=typeof process<"u"&&process.version;return r?new F$(process.version.slice(1)):null}uo.getNodeVersion=q$;function eG(r){for(var e=[],t=0;t<r;t++)e.push("0");return e}var jh={exports:{}};function tG(r,e){if(typeof r[Symbol.iterator]=="function")for(const t of r){const n=Array.isArray(t)?t[1]:t;e(n)}else for(const t in r)if(r.hasOwnProperty(t)){const n=r[t];e(n)}}var W$={iterateReports:tG};const rG={"outbound-rtp":{packetsSent:"audioSentPackets",bytesSent:"audioSentBytes"},"inbound-rtp":{packetsReceived:"audioRecvPackets",packetsLost:"audioRecvPacketsLost",bytesReceived:"audioRecvBytes",jitter:"audioRecvJitter"},"remote-inbound-rtp":{packetsLost:"audioSentPacketsLost",roundTripTime:"audioRtt",jitter:"audioSentJitter"}},nG={"remote-candidate":function(r){return Bh(r)},"inbound-rtp":function(r){return Bh(r)},"outbound-rtp":function(r){return Bh(r)},"remote-inbound-rtp":function(r){return Bh(r)}},Bh=r=>{const{type:e}=r,t=rG[e],n={};for(let i in t)if(i in r){let s;typeof t[i]=="function"?s=t[i](r):s=t[i],n[s]=r[i]}else n[t[i]]=null;return n};var iG={parsers:nG};const{iterateReports:sG}=W$;function aG(r){let e=0,t=0,n=0,i=100,s=0,a,c,o;return sG(r,l=>{l.type==="inbound-rtp"&&(e=l.jitter,n=l.packetsLost,t=l.packetsReceived)}),t+n>0&&(s=100*(n/(t+n))),a=i+e*2+10,a<160?c=93.2-a/40:c=93.2-(a-120)/10,c=c-s*2.5,c<1&&(c=1),o=1+.035*c+7e-6*c*(c-60)*(100-c),parseFloat(o).toFixed(6)}var V$=aG;const{iterateReports:oG}=W$,{parsers:kk}=iG,uG=V$;function cG(r){const e={};return oG(r,t=>{if(t.type in kk){const n=kk[t.type](t);Object.assign(e,n)}}),e.networkMos=parseFloat(uG(r)),e}var lG=cG,Rk;function dG(){return Rk||(Rk=1,function(r,e){var t=Ye&&Ye.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(e,"__esModule",{value:!0});const n=lG,i=V$,s=t(_a());class a{constructor(o){this.mos_report={min:5,max:0},this._reportsCount=0,this._mosSum=0,this.intervals=[],this._deprecationWarningSent=!1,!(!o||!o.application||!o.rtc_id||!o.pc)&&(this.conversation=null,this.application_id=null,this.attachHandlers(o),this.startSendingStats(o),this.startEmittingStats(o))}attachHandlers(o){const{pc:l}=o,d=l.onconnectionstatechange?l.onconnectionstatechange:()=>{};l.onconnectionstatechange=h=>{switch(d.call(l,h),l.connectionState){case"disconnected":case"failed":case"closed":this.removeIntervals(),this.emitLastReport(o)}},o.conversation?o.conversation.on("member:media",(v,y)=>{!this.application_id&&(o==null?void 0:o.rtc_id)===y.body.channel.id&&(this.application_id=y.application_id)}):o.application.on("member:joined",(v,y)=>{(!this.conversation||!this.application_id)&&(o==null?void 0:o.rtc_id)===y.body.channel.id&&(this.conversation=v.conversation,this.application_id=y.application_id)})}emitLastReport(o){const{application:l,conversation:d=null,rtc_id:h,config:{emit_events:v,emit_rtc_analytics:y}}=o,w=this.getMOSReport(),k=w.last;k&&(y&&l.emit("rtcstats:analytics",{type:"mos_report",mos:k,rtc_id:h,mos_report:w,api_key:l.session.apiKey,...this.application_id&&{application_id:this.application_id},...d&&{conversation_id:d.id,conversation_name:d.name}}),v&&(this._deprecationWarningSent||(this._deprecationWarningSent=!0,console.warn('"rtcstats:report" event is deprecated. Use "rtcstats:analytics" instead')),l.emit("rtcstats:report",k,null,d,w)))}startSendingStats(o){const{application:l,conversation:d=null,pc:h,rtc_id:v,config:{remote_collection:y,remote_collection_url:w,remote_collection_interval:k}}=o;if(!y)return;const I=setInterval(()=>{h.getStats(null).then(A=>{var j;const L=(j=d??this.conversation)!==null&&j!==void 0?j:null;s.default.networkRequest({url:w,type:"POST",data:{...n(A),legId:v,apiKey:l.session.apiKey,...this.application_id&&{applicationId:this.application_id},...L&&{conversationId:L.id,conversationName:L.name}}}).catch(()=>{})}).catch(()=>{}),(h.connectionState==="closed"||h.signalingState==="closed")&&this.removeIntervals()},k);this.intervals.push(I)}startEmittingStats(o){const{application:l,conversation:d=null,pc:h,rtc_id:v,config:{emit_events:y,emit_rtc_analytics:w,emit_interval:k}}=o;if(!y&&!w)return;const I=setInterval(()=>{var A;h.getStats(null).then(j=>{var L;const x=this.getMos(j);if(!x)return;const B=(L=d??this.conversation)!==null&&L!==void 0?L:null;w&&l.emit("rtcstats:analytics",{type:"mos",mos:x,report:j,rtc_id:v,api_key:l.session.apiKey,...this.application_id&&{application_id:this.application_id},...B&&{conversation_id:B.id,conversation_name:B.name}}),y&&(this._deprecationWarningSent||(this._deprecationWarningSent=!0,console.warn('"rtcstats:report" event is deprecated. Use "rtcstats:analytics" instead')),l.emit("rtcstats:report",x,j,d))}).catch(()=>{}),(h.connectionState==="closed"||h.signalingState==="closed")&&(this.removeIntervals(),this.emitLastReport({...o,conversation:(A=d??this.conversation)!==null&&A!==void 0?A:null}))},k);this.intervals.push(I)}removeIntervals(){this.intervals.forEach(o=>clearInterval(o)),this.intervals=[]}getMos(o){const l=i(o);return this.updateMOSReport(parseInt(l)),l}updateMOSReport(o){this._reportsCount++,this._mosSum+=o,this.mos_report.last=o,this.mos_report.min=o<this.mos_report.min?o:this.mos_report.min,this.mos_report.max=o>this.mos_report.max?o:this.mos_report.max,this.mos_report.average=this._mosSum/this._reportsCount}getMOSReport(){return this.mos_report.min=a.normaliseFloat(this.mos_report.min),this.mos_report.max=a.normaliseFloat(this.mos_report.max),this.mos_report.last=a.normaliseFloat(this.mos_report.last),this.mos_report.average=a.normaliseFloat(this.mos_report.average),this.mos_report}static normaliseFloat(o){return parseFloat(o).toFixed(6)}}e.default=a,r.exports=a}(jh,jh.exports)),jh.exports}var Pk;function sg(){return Pk||(Pk=1,function(r,e){var t=Ye&&Ye.__createBinding||(Object.create?function(y,w,k,I){I===void 0&&(I=k),Object.defineProperty(y,I,{enumerable:!0,get:function(){return w[k]}})}:function(y,w,k,I){I===void 0&&(I=k),y[I]=w[k]}),n=Ye&&Ye.__setModuleDefault||(Object.create?function(y,w){Object.defineProperty(y,"default",{enumerable:!0,value:w})}:function(y,w){y.default=w}),i=Ye&&Ye.__importStar||function(y){if(y&&y.__esModule)return y;var w={};if(y!=null)for(var k in y)k!=="default"&&Object.hasOwnProperty.call(y,k)&&t(w,y,k);return n(w,y),w},s=Ye&&Ye.__importDefault||function(y){return y&&y.__esModule?y:{default:y}};Object.defineProperty(e,"__esModule",{value:!0});const a=ya,c=Gr,o=i(uo),l=Ts,d=s(dG()),h=2e4;class v{constructor(){this.log=c.getLogger(this.constructor.name)}static getUserAudio(w=!0){let k={video:!1,audio:w};return navigator.mediaDevices.getUserMedia(k)}createRTCPeerConnection(w){const k=new RTCPeerConnection(w);return k.trace=()=>{},k}_getWindowLocationProtocol(){return window.location.protocol}static _getBrowserName(){return o.detect().name}static isNode(){return this._getBrowserName()==="node"}checkValidKeys(w,k){let I=!0;return Object.keys(w).forEach(A=>{k.hasOwnProperty(A)||(I=!1)}),I}static cleanCallMediaIfFailed(w){setTimeout(()=>{w.conversation||(this.cleanMediaProperties(w),w.status=w.CALL_STATUS.FAILED,w.application.emit("call:status:changed",w))},5e3)}static callDisconnectHandler(w,k){const I=[w.CALL_STATUS.ANSWERED,w.CALL_STATUS.STARTED,w.CALL_STATUS.RINGING];if(!(k.connectionState!=="disconnected"||!w||!w.conversation))return setTimeout(()=>{k.connectionState==="connected"||I.indexOf(w.status)==-1||(this.cleanMediaProperties(w),w.status=w.CALL_STATUS.COMPLETED,w.application.emit("call:status:changed",w))},h)}static cleanMediaProperties(w){if(w.rtcObjects)for(const k in w.rtcObjects)w.rtcObjects[k].pc.close(),delete w.rtcObjects[k].pc,v.closeStream(w.rtcObjects[k].stream);w.application.activeStreams=[],w.rtcObjects={},w.conversation&&w.conversation.media&&(w.conversation.media.rtcStats=null)}static playAudioStream(w){const k=new Audio;return k.srcObject=w,k.autoplay=!0,k}static createDummyCandidateSDP(w){const k={foundation:1176891032,component:1,transport:"udp",priority:2122260223,ip:"0.0.0.0",port:9,type:"host",generation:0,"network-id":1,"network-cost":50},I=a.parse(w.localDescription.sdp);return I.media[0].candidates=[k],a.write(I)}static createRTCPeerConnectionConfig(w){return{iceTransportPolicy:"all",bundlePolicy:"balanced",rtcpMuxPolicy:"require",iceCandidatePoolSize:"0",...w.session.config&&w.session.config.iceServers&&{iceServers:w.session.config.iceServers}}}static createPeerConnection(w){const k=this.createRTCPeerConnectionConfig(w);return new RTCPeerConnection(k)}static sendOffer(w,k,I,A){const L={sdp:this.createDummyCandidateSDP(k)};let x={from:I.me.id,body:{offer:L}},B=`conversations/${I.id}/rtc`;return A&&(B+=`/${A}/offer`),w.session.sendNetworkRequest({type:"POST",path:B,data:x})}static sendAnswer(w,k,I,A){const j=this.createDummyCandidateSDP(k);let L={from:I.me.id,body:{answer:j}},x=`conversations/${I.id}/rtc/${A}/answer`;return w.session.sendNetworkRequest({type:"POST",path:x,data:L})}static createLeg(w,k){const A={sdp:this.createDummyCandidateSDP(k),type:"offer"};return w.session.sendNetworkRequest({type:"POST",path:"legs",version:"beta",data:{body:{offer:A}}})}static closeStream(w){w.getTracks().forEach(k=>{k.stop()})}static emitMediaStream(w,k,I){w.emit("media:stream:on",{pc:k,stream:I,type:"audio",streamIndex:0})}static _initStatsEvents(w){var k,I,A;if(!v.isNode()&&!((A=(I=(k=w==null?void 0:w.application)===null||k===void 0?void 0:k.session)===null||I===void 0?void 0:I.config)===null||A===void 0)&&A.rtcstats){const j=w.application.session.config.rtcstats,{emit_events:L,remote_collection:x,emit_rtc_analytics:B}=j;if(L||x||B){const G={...w,config:{...j}};return new d.default(G)}}}static attachConversationEventHandlers(w){const{conversation:k,pc:I,log:A}=w;k.once("rtc:answer",j=>{if(!I){A.warn("RTC: received an answer too late");return}I.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:j.body.answer}))})}static doAnswer(w,k,I){const{application:A,conversation:j,pc:L,reject:x,localStream:B}=w;this.addPeerConnectionListeners(w,()=>v.sendAnswer(A,L,j,I).then(()=>({rtc_id:I}))),L.setRemoteDescription(new RTCSessionDescription({type:"offer",sdp:k})).then(()=>L.createAnswer()).then(G=>L.setLocalDescription(G)).catch(G=>{B&&this.closeStream(B),x(G)})}static attachPeerConnectionEventHandlers(w){const{application:k,conversation:I,pc:A,reconnectRtcId:j}=w;this.addPeerConnectionListeners(w,()=>v.sendOffer(k,A,I,j))}static addPeerConnectionListeners(w,k){const{application:I,conversation:A,pc:j,streamIndex:L,localStream:x,log:B,rtcObjects:G,resolve:K,reject:D}=w;let fe,X=!1,pe;A.id&&(pe=I.calls.get(A.id)),j.ontrack=Q=>{fe=Q.streams[0],I.activeStreams.push(fe),v.emitMediaStream(A.me,j,fe)},j.onconnectionstatechange=Q=>this.onconnectionstatechangeHandler(j,B,pe,()=>K(fe),()=>D()),j.onnegotiationneeded=()=>this.onnegotiationneededHandler(j,Q=>D(Q)),j.oniceconnectionstatechange=Q=>this.oniceconnectionstatechange(Q,j,B,Oe=>D(Oe)),j.onicecandidate=async Q=>{if(Q.candidate&&!X&&j){X=!0;try{const{rtc_id:Oe}=await k();v._initStatsEvents({application:I,rtc_id:Oe,pc:j,conversation:A}),j.trace&&j.trace("rtc_id",Oe),G[Oe]={rtc_id:Oe,pc:j,stream:x,type:"audio",streamIndex:L}}catch(Oe){x&&this.closeStream(x),D(new l.NexmoClientError(Oe))}}},x.getTracks().forEach(Q=>j.addTrack(Q))}static prewarmLeg(w){const k=w.application;return new Promise(async(I,A)=>{let j=!1,L,x,B={};const G=c.getLogger(this.constructor.name);try{let K=await this.getUserAudio();const D=this.createPeerConnection(k);D.ontrack=fe=>{L=fe.streams[0],k.activeStreams.push(L)},D.onconnectionstatechange=fe=>this.onconnectionstatechangeHandler(D,G,w,()=>I({stream:L,legId:x,rtcObjects:B}),()=>A()),D.onnegotiationneeded=()=>this.onnegotiationneededHandler(D,fe=>A(fe)),D.oniceconnectionstatechange=fe=>this.oniceconnectionstatechange(fe,D,G,X=>A(X)),D.onicecandidate=async fe=>{if(fe.candidate&&!j&&D){j=!0;const{rtc_id:X,sdp:pe}=await this.createLeg(k,D);return v._initStatsEvents({application:k,rtc_id:X,pc:D}),x=X,B[x]={rtc_id:X,pc:D,stream:K,type:"audio",streamIndex:1},D.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:pe}))}},K.getTracks().forEach(fe=>D.addTrack(fe))}catch(K){A(new l.NexmoClientError(K))}})}}e.default=v,v.onconnectionstatechangeHandler=(y,w,k,I,A)=>{switch(y.connectionState){case"connected":w.info("The connection has become fully connected"),I();break;case"disconnected":if(!k)break;k.call_disconnect_timeout&&clearTimeout(k.call_disconnect_timeout),k.call_disconnect_timeout=v.callDisconnectHandler(k,y);break;case"failed":A(),w.info("One or more transports has terminated unexpectedly or in an error");break;case"closed":w.info("The connection has been closed");break}},v.oniceconnectionstatechange=(y,w,k,I)=>{switch(w.iceConnectionState){case"disconnected":k.warn("One or more transports is disconnected",w.iceConnectionState);break;case"failed":I(new l.NexmoClientError(y)),k.warn("One or more transports has terminated unexpectedly or in an error",y);break;default:k.info("The ice connection status changed",w.iceConnectionState)}},v.onnegotiationneededHandler=async(y,w)=>{try{const k=await y.createOffer();return y.setLocalDescription(k)}catch(k){w(new l.NexmoClientError(k))}},r.exports=v}(Uh,Uh.exports)),Uh.exports}var Ik;function fG(){return Ik||(Ik=1,function(r,e){var t=Ye&&Ye.__importDefault||function(h){return h&&h.__esModule?h:{default:h}};Object.defineProperty(e,"__esModule",{value:!0});const n=Gr,i=Ts,s=t(sg()),a=t(_a()),c=t(oo),o=t(z$()),l=t(og());class d{constructor(v){var y,w,k;const I=v instanceof o.default?v:null,A=v instanceof l.default?v:null;this.log=n.getLogger(this.constructor.name),I?(this.rtcHelper=new s.default,this.application=I.application,this.application.activeStreams=this.application.activeStreams||[],this.parentConversation=I,this.rtcObjects={},this.streamIndex=0,this.rtcstats_conf=((k=(w=(y=this.application)===null||y===void 0?void 0:y.session)===null||w===void 0?void 0:w.config)===null||k===void 0?void 0:k.rtcStats)||{},this.rtcStats=null):A?(this.rtcHelper=new s.default,this.application=A):this.log.warn("No conversation object in Media")}_attachEndingEventHandlers(){this.parentConversation&&(this.log.debug("attaching leave listeners in media for "+this.parentConversation.id),this.parentConversation.on("rtc:hangup",async v=>{let y;if(this.parentConversation.members.has(v.from))y=this.parentConversation.members.get(v.from);else try{y=await this.parentConversation.getMember(v.from)}catch(w){this.log.warn(`There is an error getting the member ${w}`)}y.user.id===this.application.me.id&&this.application.activeStreams.length&&this._cleanMediaProperties(),y.user.id===this.application.me.id&&y.transferred_from&&y.transferred_from.media._cleanMediaProperties(),y.user.id===this.application.me.id&&this.parentConversation.off("rtc:hangup")}))}_enableStatsEvents(){this.rtcstats_conf.emit_rtc_analytics=!0,this.rtcstats_conf.remote_collection=!0;const v=this._findRtcObjectByType("audio");!this.rtcStats&&v&&(this.log.debug(`enabling stats events for ${v.rtc_id}`),this.rtcStats=s.default._initStatsEvents({application:this.application,rtc_id:v.rtc_id,pc:this.pc,conversation:this.parentConversation}))}_disableStatsEvents(){this.rtcstats_conf.emit_events=!1,this.rtcstats_conf.emit_rtc_analytics=!1,this.rtcstats_conf.remote_collection=!1,this.rtcStats.removeIntervals(),delete this.rtcStats}_audioInitHandler(v={},y){return new Promise(async(w,k)=>{const I=this.streamIndex;this.streamIndex++;const{audioConstraints:A}=v;try{const j=await s.default.getUserAudio(A),L=s.default.createPeerConnection(this.application);this.pc=L;const{application:x,log:B,parentConversation:G,rtcObjects:K}=this,D={pc:L,streamIndex:I,localStream:j,application:x,conversation:G,log:B,rtcObjects:K};y({...D,resolve:w,reject:k}),s.default.attachConversationEventHandlers(D),this._attachEndingEventHandlers()}catch(j){k(new i.NexmoClientError(j))}})}_execAnswer(v={}){const{offer:{sdp:y,leg_id:w}}=v;return this._audioInitHandler(v,k=>s.default.doAnswer(k,y,w))}_handleAudio(v={}){const{reconnectRtcId:y}=v;return this._audioInitHandler(v,w=>s.default.attachPeerConnectionEventHandlers({...w,reconnectRtcId:y}))}_findRtcObjectByType(v){return Object.values(this.rtcObjects).find(y=>y.type===v)}async _cleanConversationProperties(){this.pc&&this.pc.close(),delete this.pc,this.rtcStats=null,this.application.activeStreams=[],this.listeningToRtcEvent=!1,await Promise.resolve()}_cleanMediaProperties(){if(this.pc&&this.pc.close(),this.rtcObjects)for(const v in this.rtcObjects)s.default.closeStream(this.rtcObjects[v].stream);delete this.pc,this.rtcStats=null,this.application.activeStreams=[],this.rtcObjects={},this.listeningToRtcEvent=!1}async _disableLeg(v){const y=new Promise(async(k,I)=>{try{await this.application.session.sendNetworkRequest({type:"DELETE",path:`conversations/${this.parentConversation.id}/rtc/${v}?from=${this.parentConversation.me.id}&originating_session=${this.application.session.session_id}`,version:"beta2"}),k("rtc:terminate:success")}catch(A){I(new i.NexmoApiError(A))}}),w=new Promise(k=>{this.rtcObjects[v].pc&&this.rtcObjects[v].pc.close(),this.rtcObjects[v].stream&&s.default.closeStream(this.rtcObjects[v].stream),k()});try{return await Promise.all([y,w]),this.parentConversation.me.emit("media:stream:off",this.rtcObjects[v].streamIndex),delete this.rtcObjects[v],"rtc:terminate:success"}catch(k){throw k}}_enableMediaTracks(v,y){v.forEach(w=>{w.enabled=y})}async _setMediaTracksAndMute(v,y,w,k){this._enableMediaTracks(y,!w);try{return await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.parentConversation.id}/events`,data:{type:k,to:this.parentConversation.me.id,from:this.parentConversation.me.id,body:{rtc_id:v}}})}catch(I){throw this._enableMediaTracks(y,w),new i.NexmoApiError(I)}}async updateAudioConstraints(v={}){let y=this._findRtcObjectByType("audio");if(y&&y.pc)try{const w=await s.default.getUserAudio(v);return w.getTracks().forEach(k=>{const I=y.pc.getSenders().find(A=>A.track.kind===k.kind);I&&(k.enabled=I.track.enabled,I.replaceTrack(k))}),s.default.closeStream(y.stream),y.stream=w,w}catch(w){return w}else throw new i.NexmoApiError("error:media:stream:not-found")}mute(v=!1,y=null){const k="audio:mute:"+(v?"on":"off");let I=[],A={};if(y!==null){if(A[0]=Object.values(this.rtcObjects).find(j=>j.streamIndex===y),!A[0])throw new i.NexmoClientError("error:media:stream:not-found")}else A=this.rtcObjects;return Object.values(A).forEach(j=>{const L=j.stream.getAudioTracks(),x=this._setMediaTracksAndMute(j.rtc_id,L,v,k);I.push(x)}),Promise.all(I)}async earmuff(v){try{if(this.me===null)throw new i.NexmoClientError("error:self");{let y="audio:earmuff:off";v&&(y="audio:earmuff:on");const{response:w}=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.parentConversation.id}/events`,data:{type:y,to:this.parentConversation.me.id}});return w}}catch(y){throw new i.NexmoApiError(y)}}async enable(v){try{if(this.parentConversation.me===null)throw new i.NexmoClientError("error:self");{const{offer:y}=v??{};let w=await(y!==void 0?this._execAnswer(v):this._handleAudio(v)),k=v&&(v.autoPlayAudio||v.autoPlayAudio===void 0);return(!v||k)&&s.default.playAudioStream(w),w}}catch(y){throw y}}disable(){let v=[];v.push(this._cleanConversationProperties());for(const y in this.rtcObjects)v.push(this._disableLeg(y));return Promise.all(v)}async sayText(v){try{const y=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.parentConversation.id}/events`,data:{type:"audio:say",cid:this.parentConversation.id,from:this.parentConversation.me.id,body:{text:v.text,voice_name:v.voice_name||"Amy",level:v.level||1,queue:v.queue||!0,loop:v.loop||1,ssml:v.ssml||!1}}});return new c.default(this.parentConversation,y)}catch(y){throw new i.NexmoApiError(y)}}async sendDTMF(v){try{if(!a.default.validateDTMF(v))throw new i.NexmoClientError("error:audio:dtmf:invalid-digit");if(!(this._findRtcObjectByType("audio")||{}).rtc_id)throw new i.NexmoClientError("error:audio:dtmf:audio-disabled");const{id:w,timestamp:k}=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.parentConversation.id}/events`,data:{type:"audio:dtmf",from:this.parentConversation.me.id,body:{digit:v,channel:{type:"app",id:this._findRtcObjectByType("audio").rtc_id}}}}),I={body:{digit:v,dtmf_id:""},cid:this.parentConversation.id,from:this.parentConversation.me.id,id:w,timestamp:k,type:"audio:dtmf"},A=new c.default(this.parentConversation,I);return this.parentConversation.events.set(I.id,A),A}catch(y){throw new i.NexmoApiError(y)}}async playStream(v){try{const y=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.parentConversation.id}/events`,data:{type:"audio:play",body:v}});return new c.default(this.parentConversation,y)}catch(y){throw new i.NexmoApiError(y)}}async startRinging(){try{const v=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.parentConversation.id}/events`,data:{type:"audio:ringing:start",from:this.parentConversation.me.id,body:{}}});return new c.default(this.parentConversation,v)}catch(v){throw new i.NexmoApiError(v)}}async stopRinging(){try{const v=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.parentConversation.id}/events`,data:{type:"audio:ringing:stop",from:this.parentConversation.me.id,body:{}}});return new c.default(this.parentConversation,v)}catch(v){throw new i.NexmoApiError(v)}}}e.default=d,r.exports=d}(Lh,Lh.exports)),Lh.exports}var qh={exports:{}},Wh={exports:{}},Ak;function H$(){return Ak||(Ak=1,function(r,e){var t=Ye&&Ye.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(e,"__esModule",{value:!0});const n=t(_a()),i=Gr,s=t(oo);class a extends s.default{constructor(o,l){super(o,l),this.log=i.getLogger(this.constructor.name),this.type="image",this.conversation=o,this.state={seen_by:{},delivered_to:{}},l&&l.body&&l.body.timestamp&&(this.timestamp=l.body.timestamp),Object.assign(this,l)}seen(){return super.seen()}delivered(){return super.delivered()}async del(){return await n.default.networkRequest({type:"DELETE",url:this.body.representations.original.url,token:this.conversation.application.session.config.token}),super.del()}async fetchImage(o="thumbnail",l=this.body.representations){try{return n.default._fetchImage(l[o].url,this.conversation.application.session.config.token)}catch(d){throw this.log.error(d),d}}}e.default=a,r.exports=a}(Wh,Wh.exports)),Wh.exports}var Ok;function hG(){return Ok||(Ok=1,function(r,e){var t=Ye&&Ye.__importDefault||function(l){return l&&l.__esModule?l:{default:l}};Object.defineProperty(e,"__esModule",{value:!0});const n=Gr,i=t(oo),s=t(Fw),a=t(H$()),c=t(jw());class o{constructor(d,h){this.log=n.getLogger(this.constructor.name),this.application=d,this.conversation=h,this.constructed_event=null,this._handleEventMap={"event:delete":this._processDelete,image:this._processImage,"image:delivered":this._processDelivered,"image:seen":this._processSeen,"member:invited":this._processMember,"member:joined":this._processMember,"member:left":this._processMember,"audio:ringing:start":this._processMember,"leg:status:update":this._processLegStatus,"member:media":this._processMedia,text:this._processText,"text:delivered":this._processDelivered,"text:seen":this._processSeen,"audio:mute:on":this._processMuteForMedia,"audio:mute:off":this._processMuteForMedia,message:this._processMessage,"message:delivered":this._processDelivered,"message:seen":this._processSeen,"message:submitted":this._processSubmitted,"message:rejected":this._processRejected,"message:undeliverable":this._processUndeliverable}}handleEvent(d){return this._handleEventMap.hasOwnProperty(d.type)?this._handleEventMap[d.type].call(this,d)||new i.default(this.conversation,d):new i.default(this.conversation,d)}_processDelivered(d){let h=this.conversation.events.get(d.body.event_id);return h?(h.state=h.state||{},h.state.delivered_to=h.state.delivered_to||{},h.state.delivered_to[d.from]=d.timestamp,h):(this.log.warn("NXMEvent not found"),null)}_processDelete(d){var h;let v=this.conversation.events.get((h=d==null?void 0:d.body)===null||h===void 0?void 0:h.event_id);return v?(v.body.text&&(v.body.text=""),v.body.representations&&(v.body.representations=""),v.body.timestamp={deleted:d.timestamp},v):(this.log.warn("NXMEvent not found"),null)}_processImage(d){var h;const v=new a.default(this.conversation,d);return((h=this.conversation.me)===null||h===void 0?void 0:h.id)!==v.from&&v.delivered(),v}_processMember(d){return this.application.calls.has(this.conversation.id)&&this.application.calls.get(this.conversation.id)._handleStatusChange(d),this.conversation.members.has(d.from)&&this.conversation.members.get(d.from)._handleEvent(d),new i.default(this.conversation,d)}_processLegStatus(d){return this.conversation.members.has(d.from)&&this.conversation.members.get(d.from)._handleEvent(d),new i.default(this.conversation,d)}_processMedia(d){return this.conversation.members.has(d.from)&&this.conversation.members.get(d.from)._handleEvent(d),null}_processMuteForMedia(d){return this.conversation.media.rtcObjects[d.body.rtc_id]?d.streamIndex=this.conversation.media.rtcObjects[d.body.rtc_id].streamIndex:this.log.warn("No audio stream was found"),null}_processSeen(d){let h=this.conversation.events.get(d.body.event_id);return h?(h.state=h.state||{},h.state.seen_by=h.state.seen_by||{},h.state.seen_by[d.from]=d.timestamp,h):(this.log.warn("NXMEvent not found"),null)}_processText(d){var h,v;const y=new s.default(this.conversation,d);return((v=(h=this.conversation)===null||h===void 0?void 0:h.me)===null||v===void 0?void 0:v.id)!==y.from&&y.delivered(),y}_processMessage(d){var h,v;const y=new c.default(this.conversation,d);return((v=(h=this.conversation)===null||h===void 0?void 0:h.me)===null||v===void 0?void 0:v.id)!==y.from&&y.delivered(),y}_processSubmitted(d){let h=this.conversation.events.get(d.body.event_id);return h?(h.state=h.state||{},h.state.submitted_to=h.state.submitted_to||{},h.state.submitted_to[d.from]=d.timestamp,h):(this.log.warn("NXMEvent not found"),null)}_processRejected(d){let h=this.conversation.events.get(d.body.event_id);return h?(h.state=h.state||{},h.state.rejected_by=h.state.rejected_by||{},h.state.rejected_by[d.from]=d.timestamp,h):(this.log.warn("NXMEvent not found"),null)}_processUndeliverable(d){let h=this.conversation.events.get(d.body.event_id);return h?(h.state=h.state||{},h.state.undeliverable_to=h.state.undeliverable_to||{},h.state.undeliverable_to[d.from]=d.timestamp,h):(this.log.warn("NXMEvent not found"),null)}}e.default=o,r.exports=o}(qh,qh.exports)),qh.exports}var nS={exports:{}};(function(r,e){Object.defineProperty(e,"__esModule",{value:!0});class t{constructor(i={}){this.page_size=i.page_size||10,this.order=i.order||"asc",this.cursor=i.cursor||"",i.event_type&&(this.event_type=i.event_type)}}e.default=t,r.exports=t})(nS,nS.exports);var G$=nS.exports,Vh={exports:{}},iS={exports:{}};(function(r,e){Object.defineProperty(e,"__esModule",{value:!0});const t=Ts;class n{constructor(s={}){this.page_size=s.page_size,this.order=s.order,this.cursor=s.cursor,this.application=s.application,s.event_type&&s.event_type.length>0&&(this.event_type=s.event_type)}hasPrev(){return this.cursor.prev?this.cursor.prev.length>0:!1}hasNext(){return this.cursor.next?this.cursor.next.length>0:!1}_getConfig(s){return{page_size:this.page_size,order:this.order,cursor:s,...this.event_type&&{event_type:this.event_type}}}_getError(){return Promise.reject(new t.NexmoClientError("error:invalid-cursor"))}}e.default=n,r.exports=n})(iS,iS.exports);var ag=iS.exports,$k;function pG(){return $k||($k=1,function(r,e){var t=Ye&&Ye.__importDefault||function(l){return l&&l.__esModule?l:{default:l}};Object.defineProperty(e,"__esModule",{value:!0});const n=t(ag),i=t(oo),s=t(Fw),a=t(H$()),c=t(jw());class o extends n.default{constructor(d){super(d),this.items=new Map,this.conversation=d.conversation,d.items.forEach(h=>{switch(h.type){case"text":this.items.set(h.id,new s.default(this.conversation,h));break;case"image":this.items.set(h.id,new a.default(this.conversation,h));break;case"message":this.items.set(h.id,new c.default(this.conversation,h));break;default:this.items.set(h.id,new i.default(this.conversation,h));break}}),this.conversation.events=new Map([...this.conversation.events,...this.items])}getPrev(){return this.hasPrev()?this.conversation.getEvents(this._getConfig(this.cursor.prev)):this._getError()}getNext(){return this.hasNext()?this.conversation.getEvents(this._getConfig(this.cursor.next)):this._getError()}}e.default=o,r.exports=o}(Vh,Vh.exports)),Vh.exports}var Hh={exports:{}},xk;function vG(){return xk||(xk=1,function(r,e){var t=Ye&&Ye.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(e,"__esModule",{value:!0});const n=t(ag),i=t(Uw());class s extends n.default{constructor(c){super(c),this.conversation=c.conversation,this.items=new Map,c.items.forEach(o=>{this.items.set(o.id,new i.default(this.conversation,o))})}getPrev(){return this.hasPrev()?this.conversation.getMembers(this._getConfig(this.cursor.prev)):this._getError()}getNext(){return this.hasNext()?this.conversation.getMembers(this._getConfig(this.cursor.next)):this._getError()}}e.default=s,r.exports=s}(Hh,Hh.exports)),Hh.exports}var Mk;function z$(){return Mk||(Mk=1,function(r,e){var t=Ye&&Ye.__importDefault||function(j){return j&&j.__esModule?j:{default:j}};Object.defineProperty(e,"__esModule",{value:!0});const n=Zo,i=Gr,s=Ts,a=t(Uw()),c=t(oo),o=t(Fw),l=t(jw()),d=t(fG()),h=t(hG()),v=t(_a()),y=t(G$),w=t(pG()),k=t(vG()),I=t(og());class A{constructor(L,x){this.log=i.getLogger(this.constructor.name),this.application=L,this.id=null,this.name=null,this.display_name=null,this.timestamp=null,this.members=new Map,this.events=new Map,this.sequence_number=0,this.pageConfig=new y.default(((this.application.session||{}).config||{}).events_page_config),this.events_page_last=null,this.members_page_last=null,this.conversationEventHandler=new h.default(L,this),this.media=new d.default(this),this.me=null,this._updateObjectInstance(x),n.mixin(A)}_updateObjectInstance(L){for(let x in L)switch(x){case"id":this.id=L.id;break;case"name":this.name=L.name;break;case"display_name":this.display_name=L.display_name;break;case"members":L.members.forEach(G=>{if(this.members.has(G.member_id))this.members.get(G.member_id)._normalise(G),G.user_id===this.application.me.id&&G.state!=="LEFT"&&(this.me=this.members.get(G.member_id),this.members.set(this.me.id,this.me));else{const K=new a.default(this,G);G.user_id===this.application.me.id&&G.state!=="LEFT"&&(this.me=K),this.members.set(K.id,K)}});break;case"timestamp":this.timestamp=L.timestamp;break;case"sequence_number":this.sequence_number=L.sequence_number;break;case"member_id":const B={id:L.member_id,state:L.state,user:this.application.me};if(this.members.has(L.member_id)){const G=this.members.get(L.member_id);Object.assign(G,B)}else{const G=new a.default(this,B);this.me=G,this.members.set(G.id,G)}break}}async join(L){var x,B;try{let G={state:"joined",channel:{type:"app"},user:{...!L&&{name:this.application.me.name,id:this.application.me.id},...L&&L.user_name&&{name:L.user_name},...L&&L.user_id&&{id:L.user_id}}};!((x=this===null||this===void 0?void 0:this.me)===null||x===void 0)&&x.id&&((B=this===null||this===void 0?void 0:this.me)===null||B===void 0?void 0:B.state)!=="LEFT"&&(G.from=this.me.id);const K=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.id}/members`,version:"v0.3",data:G}),D=new a.default(this,K);return K._embedded.user.id===this.application.me.id&&(this.me=D,this.members.set(D.id,D)),this.application.getConversation(this.id,I.default.CONVERSATION_API_VERSION.v3),D}catch(G){throw new s.NexmoApiError(G)}}async del(){try{const L=await this.application.session.sendNetworkRequest({type:"DELETE",path:`conversations/${this.id}`});return this.application.conversations.delete(this.id),L}catch(L){throw new s.NexmoApiError(L)}}deleteEvent(L){return L.del()}async invite(L){var x,B;if(!L||!L.id&&!L.user_name)throw new s.NexmoClientError("error:invite:missing:params");const G={state:"invited",user:{...L.id&&{id:L.id},...L.user_name&&{name:L.user_name}},media:L.media,channel:{from:{type:"app"},to:{type:"app"},type:"app"}};!((x=this===null||this===void 0?void 0:this.me)===null||x===void 0)&&x.id&&((B=this===null||this===void 0?void 0:this.me)===null||B===void 0?void 0:B.state)!=="LEFT"&&(G.from=this.me.id);try{const K=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.id}/members`,version:"v0.3",data:G});return new a.default(this,K)}catch(K){throw new s.NexmoApiError(K)}}inviteWithAudio(L){return!L||!L.id&&!L.user_name?Promise.reject(new s.NexmoClientError("error:invite:missing:params")):(L.media={audio_settings:{enabled:!0,muted:!1,earmuffed:!1}},this.invite(L))}leave(L){return this.me.kick(L)}async sendText(L){try{if(this.me===null)throw new s.NexmoClientError("error:self");const x={type:"text",cid:this.id,from:this.me.id,body:{text:L}},{id:B,timestamp:G}=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.id}/events`,data:x});return x.id=B,x.body.timestamp=G,new o.default(this,x)}catch(x){throw new s.NexmoApiError(x)}}async sendCustomEvent({type:L,body:x}){try{if(this.me===null)throw new s.NexmoClientError("error:self");if(!L||typeof L!="string"||L.length<1)throw new s.NexmoClientError("error:custom-event:invalid");const B={type:`custom:${L}`,cid:this.id,from:this.me.id,body:x},{id:G,timestamp:K}=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.id}/events`,data:B});return B.id=G,B.timestamp=K,new c.default(this,B)}catch(B){throw new s.NexmoApiError(B)}}async uploadImage(L,x={quality_ratio:"100",medium_size_ratio:"50",thumbnail_size_ratio:"30"}){const B=new FormData;B.append("file",L),B.append("quality_ratio",x.quality_ratio),B.append("medium_size_ratio",x.medium_size_ratio),B.append("thumbnail_size_ratio",x.thumbnail_size_ratio);const G=await v.default.networkRequest({type:"POST",url:this.application.session.config.ips_url,data:B,token:this.application.session.config.token});return G.upload.addEventListener("progress",K=>{K.lengthComputable&&this.log.debug("uploading image "+K.loaded+"/"+K.total)},!1),G.onreadystatechange=()=>{G.status!==200&&this.log.error(G)},G}async sendImage(L,x={quality_ratio:"100",medium_size_ratio:"50",thumbnail_size_ratio:"30"}){const B=await this.uploadImage(L,x);return B.onreadystatechange=()=>{if(B.readyState===4&&B.status===200)try{this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.id}/events`,data:{type:"image",from:this.me.id,body:{representations:JSON.parse(B.responseText)}}}),this.log.info(B)}catch(G){this.log.error(new s.NexmoApiError(G))}},B}abortSendImage(L){return L instanceof XMLHttpRequest?L.abort():new s.NexmoClientError("error:invalid:param:type")}async sendMessage(L){if(this.me===null)throw new s.NexmoClientError("error:self");if(!(L!=null&&L.message_type))throw new s.NexmoClientError("error:message-event:invalid");try{const x={type:"message",cid:this.id,from:this.me.id,body:{...L}},{id:B,timestamp:G}=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.id}/events`,data:x});return x.id=B,x.body.timestamp=G,new l.default(this,x)}catch(x){throw new s.NexmoApiError(x)}}async _typing(L){const x={activity:L==="on"?1:0},B={type:"text:typing:"+L,cid:this.id,from:this.me.id,body:x};try{return await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.id}/events`,data:B}),`text:typing:${L}:success`}catch(G){throw new s.NexmoApiError(G)}}startTyping(){return this._typing("on")}stopTyping(){return this._typing("off")}async getEvents(L={}){const x=`${this.application.session.config.nexmo_api_url}/beta2/conversations/${this.id}/events`;let B=Object.keys(L).length===0?this.pageConfig:new y.default(L);try{const G=await v.default.paginationRequest(x,B,this.application.session.config.token);G.application=this.application,G.conversation=this;const K=new w.default(G);return this.events_page_last=K,K}catch(G){throw new s.NexmoApiError(G)}}async getMembers(L={}){const x=`${this.application.session.config.nexmo_api_url}/beta2/conversations/${this.id}/members`;let B=Object.keys(L).length===0?this.pageConfig:new y.default(L);try{const G=await v.default.paginationRequest(x,B,this.application.session.config.token);G.application=this.application,G.conversation=this;const K=new k.default(G);return this.members_page_last=K,K}catch(G){throw new s.NexmoApiError(G)}}async getMyMember(){try{const L=await this.application.session.sendNetworkRequest({type:"GET",path:`conversations/${this.id}/members/me`,version:"v0.3"});return new a.default(this,L)}catch(L){throw new s.NexmoApiError(L)}}async getMember(L){try{const x=await this.application.session.sendNetworkRequest({type:"GET",path:`conversations/${this.id}/members/${L}`,version:"v0.3"});return new a.default(this,x)}catch(x){throw new s.NexmoApiError(x)}}_handleEvent(L){var x,B;if(L.type.startsWith("rtc"))return this.emit(L.type,L),Promise.resolve(L);this.sequence_number++,L.body&&L.body.event_id&&typeof L.body.event_id=="string"&&(L.body.event_id=parseInt(L.body.event_id));let G={memberId:L.from};if(!((x=L==null?void 0:L.body)===null||x===void 0)&&x.user){const{id:D,name:fe,display_name:X,image_url:pe,custom_data:Q}=L.body.user;G={...G,...D&&{userId:D},...fe&&{userName:fe},...X&&{displayName:X},...pe&&{imageUrl:pe},...Q&&{customData:Q}}}else if(!((B=L==null?void 0:L._embedded)===null||B===void 0)&&B.from_user){const{id:D,name:fe,display_name:X,image_url:pe,custom_data:Q}=L._embedded.from_user;G={...G,...D&&{userId:D},...fe&&{userName:fe},...X&&{displayName:X},...pe&&{imageUrl:pe},...Q&&{customData:Q}}}let K=this.conversationEventHandler.handleEvent(L);return["text:typing:on","text:typing:off"].includes(L.type)||this.events.set(K.id,K),L.type.startsWith("custom:")?(this.emit(K.type,G,K),Promise.resolve(L)):(this.emit(L.type,G,K),Promise.resolve(L))}}e.default=A,r.exports=A}(Mh,Mh.exports)),Mh.exports}var Gh={exports:{}},Dk;function K$(){return Dk||(Dk=1,function(r,e){var t=Ye&&Ye.__importDefault||function(o){return o&&o.__esModule?o:{default:o}};Object.defineProperty(e,"__esModule",{value:!0});const n=Zo,i=Gr,s=Ts,a=t(sg());class c{constructor(l,d,h){this.application=l,this.log=i.getLogger(this.constructor.name),this.from=h,this.conversation=null,this.rtcObjects={},this.CALL_STATUS={STARTED:"started",RINGING:"ringing",ANSWERED:"answered",COMPLETED:"completed",BUSY:"busy",TIMEOUT:"timeout",UNANSWERED:"unanswered",REJECTED:"rejected",FAILED:"failed"},this.CALL_DIRECTION={INBOUND:"inbound",OUTBOUND:"outbound"},Object.freeze(this.CALL_DIRECTION),this.STATUS_PERMITTED_FLOW=new Map([["STARTED",new Set([this.CALL_STATUS.RINGING,this.CALL_STATUS.ANSWERED,this.CALL_STATUS.FAILED,this.CALL_STATUS.TIMEOUT,this.CALL_STATUS.UNANSWERED,this.CALL_STATUS.REJECTED,this.CALL_STATUS.BUSY])],["RINGING",new Set([this.CALL_STATUS.ANSWERED,this.CALL_STATUS.FAILED,this.CALL_STATUS.TIMEOUT,this.CALL_STATUS.UNANSWERED,this.CALL_STATUS.REJECTED,this.CALL_STATUS.BUSY])],["ANSWERED",new Set([this.CALL_STATUS.COMPLETED,this.CALL_STATUS.FAILED])]]),Object.freeze(this.STATUS_PERMITTED_FLOW),this.status=null,this.call_disconnect_timeout=null,this.direction=this.CALL_DIRECTION.INBOUND,this._setupConversationObject(d),n.mixin(c)}_enableStatsEvents(){this.conversation.media._enableStatsEvents()}_attachCallListeners(){this.log.debug("_attachCallListeners : ",{nxmCall:this});try{this.conversation.releaseGroup("call_module"),this.conversation.on("member:media","call_module",(l,d)=>{this.application.calls&&this.application.calls.has(this.conversation.id)&&this.application.calls.get(this.conversation.id)._handleStatusChange(d)})}catch(l){this.log.error("_attachCallListeners_error: ",{e:l})}}_isValidStatusTransition(l){if(!l)throw new s.NexmoClientError(`Provide the status to validate the transition from '${this.status}'`);if(!this.status)return!0;const d=this.status.toUpperCase();return!this.STATUS_PERMITTED_FLOW.has(d)||this.status===l?!1:this.STATUS_PERMITTED_FLOW.get(d).has(l)}hangUpIfAllLeft(){if(this.log.debug("hangUpIfAllLeft: ",{nxmCall:this}),!this.conversation.me||this.conversation.me.state==="LEFT"||this.conversation.members.size<=1)return Promise.resolve();for(let l of this.conversation.members.values())if(l.state!=="LEFT"&&this.conversation.me.user.id!==l.user.id)return Promise.resolve();return this.hangUp()}_setupConversationObject(l,d){l&&(this.conversation=l,l.me?(this.to=new Map(l.members),this.from&&this.to.delete(this.from.id)):this.log.warn("missing own member object"),this._attachCallListeners())}_setFrom(l){this.from=l}_setOffer(l){this.offer=l}_handleStatusChange(l){var d;const h=this.conversation?((d=this.conversation.me)===null||d===void 0?void 0:d.id)===l.from:!0,v=this.direction===this.CALL_DIRECTION.OUTBOUND;this.log.debug("_handleStatusChange: ",{event:l},`_isEventFromMe: ${h} _isOutbound: ${v}`);let y=new Map;if(y.set("member:joined",async()=>{if(l.body.channel&&l.body.channel.id)try{this._setStatusAndEmit(this.CALL_STATUS.STARTED);return}catch(w){throw this._setStatusAndEmit(this.CALL_STATUS.FAILED),this.log.error(w),w}return Promise.resolve()}),y.set("member:invited",()=>(l.body.invited_by===null&&l.body.user.media&&l.body.user.media.audio_settings&&this._setStatusAndEmit(this.CALL_STATUS.STARTED),Promise.resolve())),y.set("rtc:hangup",()=>this.status===this.CALL_STATUS.ANSWERED?(this._setStatusAndEmit(this.CALL_STATUS.COMPLETED),Promise.resolve()):h&&v||!h&&!v?(this._setStatusAndEmit(this.CALL_STATUS.UNANSWERED),Promise.resolve()):(this._setStatusAndEmit(this.CALL_STATUS.REJECTED),Promise.resolve())),y.set("member:left",()=>{if(!l.body.timestamp.hasOwnProperty("joined")&&this.status!==this.CALL_STATUS.ANSWERED)return h&&v||!h&&!v?(this._setStatusAndEmit(this.CALL_STATUS.UNANSWERED),Promise.resolve()):(this._setStatusAndEmit(this.CALL_STATUS.REJECTED),Promise.resolve())}),y.set("member:media",()=>(this.status!==this.CALL_STATUS.ANSWERED&&l.body.audio&&(h&&l.body.channel&&(this.id=l.body.channel.id),(!h||!v)&&this.id&&this._setStatusAndEmit(this.CALL_STATUS.ANSWERED)),Promise.resolve())),y.set("sip:ringing",()=>(this.status!==this.CALL_STATUS.RINGING&&this._setStatusAndEmit(this.CALL_STATUS.RINGING),Promise.resolve())),y.set("sip:hangup",()=>{switch(l.body.reason.sip_code){case 486:this._setStatusAndEmit(this.CALL_STATUS.BUSY);break;case 487:this._setStatusAndEmit(this.CALL_STATUS.TIMEOUT);break;case 403:this._setStatusAndEmit(this.CALL_STATUS.FAILED);break}return Promise.resolve()}),y.set("knocking:delete:success",()=>(this._setStatusAndEmit(this.CALL_STATUS.UNANSWERED),Promise.resolve())),y.has(l.type))return y.get(l.type).call(this)}_setStatusAndEmit(l){this._isValidStatusTransition(l)&&(this.status=l,this.log.debug(`_setStatusAndEmit: ${l}`,{nxmCall:this}),this.application.emit("call:status:changed",this))}async answer(l=!0){if(this.log.debug(`answer: { autoPlayAudio: ${l}`),this.conversation)try{await this.conversation.join();const d=await this.conversation.media.enable({autoPlayAudio:l,offer:this.offer});return this.offer=void 0,d}catch(d){throw this._setStatusAndEmit(this.CALL_STATUS.FAILED),this.log.error(d),d}else throw new s.NexmoClientError("error:call:answer")}async createCall(l,d=!0){if(this.log.debug(`createCall: { usernames: ${l}, autoPlayAudio: ${d} }`),!l||!Array.isArray(l)||l.length===0)return Promise.reject(new s.NexmoClientError("error:application:call:params"));try{const h=await this.application.newConversationAndJoin({display_name:"CALL_"+this.application.me.name+"_"+l.join("_").replace(" ","")});h.members.set(h.me.id,h.me),this.from=h.me,this.successful_invited_members=new Map;const v=l.map(async w=>{try{const k=await h.inviteWithAudio({user_name:w});return h.members.set(k.id,k),this.successful_invited_members.set(k.id,k),k}catch(k){return this.log.error(k),k}}),y=async()=>{if(this.successful_invited_members.size>0)return await h.media.enable({audio:{muted:!1,earmuffed:!1},autoPlayAudio:d}),this.application.calls.set(h.id,this),v;throw v};return await Promise.all(v),this._setupConversationObject(h),await y()}catch(h){throw this.log.error(h),this._setStatusAndEmit(this.CALL_STATUS.FAILED),h}}async createServerCall(l,d,h){this.log.debug(`createServerCall: { user: ${l}, type: ${d}, custom_data: `,{custom_data:h});const v={type:d};d==="phone"?v.number=l:v.user=l;try{const{stream:y,legId:w,rtcObjects:k}=await a.default.prewarmLeg(this);this.log.debug("createServerCall: ",{stream:y},{legId:w},{rtcObjects:k}),this.rtcObjects=k,this.stream=y,this.id=w,this.application._call_draft_list.set(w,this),a.default.playAudioStream(y);const I={type:"POST",path:"knocking",data:{channel:{type:"app",from:{type:"app"},to:v,id:w||null},...h&&Object.keys(h).length&&{properties:{custom_data:h}}}};try{const A=await this.application.session.sendNetworkRequest(I);this.knocking_id=A.id}catch(A){throw new s.NexmoApiError(A)}return a.default.cleanCallMediaIfFailed(this),y}catch(y){throw a.default.cleanMediaProperties(this),y}}async hangUp(l){if(this.log.debug(`hangUp: { reason: ${l} }`),this.conversation&&await this.conversation.media.disable(),!this.knocking_id&&this.conversation)return this.conversation.leave(l).catch(d=>{if(d.type!=="conversation:error:invalid-member-state")return Promise.reject(d)});{let d=`knocking/${this.knocking_id}`;if(l){let h=new URLSearchParams;Object.keys(l).forEach(v=>{h.append(v,l[v])}),d+=`?${h.toString()}`}try{const h=await this.application.session.sendNetworkRequest({type:"DELETE",path:d});return this.application._call_draft_list.get(this.client_ref)._handleStatusChange(h),this.application._call_draft_list.delete(this.client_ref),h}catch(h){if(this.conversation)return this.log.error(new s.NexmoApiError(h)),this.conversation.leave(l).catch(v=>{if(v.type!=="conversation:error:invalid-member-state")return Promise.reject(v)});this.log.debug("hangup: Problem cancelling the call. Knocking cancel failed and Conversation. Leave not available",h);return}}}reject(l){return this.log.debug(`reject: { reason: ${l} }`),this.conversation?this.conversation.leave(l):Promise.reject(new s.NexmoClientError("error:call:reject"))}}e.default=c,r.exports=c}(Gh,Gh.exports)),Gh.exports}var sS={exports:{}};(function(r,e){Object.defineProperty(e,"__esModule",{value:!0});const t=Gr;class n{constructor(s){this.log=t.getLogger(this.constructor.name),this.application=s,this._handleSipCallEventMap={"sip:hangup":this._processSipHangup,"sip:ringing":this._processSipRinging}}_handleSipCallEvent(s){if(this.log.debug("_handleSipCallEvent: ",{event:s}),!this.application.calls.has(s.cid)){this.log.warn("There is no call object for this Conversation id.");return}const a=this.application.calls.get(s.cid);if(this._handleSipCallEventMap.hasOwnProperty(s.type))return this._handleSipCallEventMap[s.type].call(this,a,s)}_processSipHangup(s,a){this.log.debug("_processSipHangup: ",a),s._handleStatusChange(a)}_processSipRinging(s,a){this.log.debug("_processSipRinging: ",a),s._handleStatusChange(a)}}e.default=n,r.exports=n})(sS,sS.exports);var gG=sS.exports,aS={exports:{}};(function(r,e){Object.defineProperty(e,"__esModule",{value:!0});const t=Gr;class n{constructor(s){this.log=t.getLogger(this.constructor.name),this.application=s,this._handleRtcEventMap={"rtc:transfer":this._processRtcTransfer,"rtc:answer":this._processRtcAnswer,"rtc:hangup":this._processRtcHangup}}_handleRtcEvent(s){if(this._handleRtcEventMap.hasOwnProperty(s.type))return this._handleRtcEventMap[s.type].call(this,s)}_processRtcTransfer(s){this.log.debug("_processRtcTransfer: ",{event:s});const a=this.application.conversations.get(s.body.transferred_from),c=this.application.conversations.get(s.cid),o=this.application.calls.get(s.body.transferred_from);if(!o){this.log.warn("NXMCall transfer for unknown nxmCall");return}o.conversation.members.get(s.body.was_member).transferred_to=c,o._setupConversationObject(c),o.transferred=!0,this.application.calls.set(s.cid,o),this.application.calls.delete(s.body.transferred_from),a&&(c.members.get(s.from).transferred_from=a,c.media._attachEndingEventHandlers(),Object.entries(c.media.rtcObjects).length===0&&Object.entries(a.media.rtcObjects).length!==0&&Object.assign(c.media.rtcObjects,a.media.rtcObjects),!c.media.pc&&a.media.pc&&Object.assign(c.media.pc=a.media.pc),c.application.activeStreams.length===0&&a.application.activeStreams.length>0&&(c.application.activeStreams=a.application.activeStreams))}_processRtcAnswer(s){this.log.debug("_processRtcAnswer: ",{event:s}),this.application.calls.has(s.cid)&&(this.application.calls.get(s.cid).id=s.body.rtc_id)}_processRtcHangup(s){this.log.debug("_processRtcHangup: ",{event:s}),this.application.calls.has(s.cid)&&this.application.calls.get(s.cid)._handleStatusChange(s)}}e.default=n,r.exports=n})(aS,aS.exports);var mG=aS.exports,zh={exports:{}},Nk;function yG(){return Nk||(Nk=1,function(r,e){var t=Ye&&Ye.__importDefault||function(l){return l&&l.__esModule?l:{default:l}};Object.defineProperty(e,"__esModule",{value:!0});const n=Gr,i=t(oo),s=t(K$()),a=t(_a()),c=t(sg());class o{constructor(d){this.log=n.getLogger(this.constructor.name),this.application=d,this._handleApplicationEventMap={"member:joined":this._processMemberJoined,"member:invited":this._processMemberInvited}}handleEvent(d){const h=this.application.conversations.get(d.cid),v=Object.assign({},d);return this._handleApplicationEventMap.hasOwnProperty(d.type)?this._handleApplicationEventMap[d.type].call(this,h,new i.default(h,v),d):new i.default(h,v)}_processMemberJoined(d,h,v){try{if(h.body.channel&&this.application._call_draft_list.has(h.body.channel.id)){this.log.debug("_processMemberJoined: outbound serverCall from sdk",{event:h});const y=this.application._call_draft_list.get(h.body.channel.id);let w=((y.rtcObjects||{})[h.body.channel.id]||{}).pc;if(y._setFrom(d.me),y._setupConversationObject(d,h.body.channel.id),d.media._attachEndingEventHandlers(),Object.entries(d.media.rtcObjects).length===0&&Object.entries(y.rtcObjects).length!==0&&Object.assign(d.media.rtcObjects,y.rtcObjects),!d.media.pc&&w&&Object.assign(d.media.pc=w),d.application.activeStreams.length===0&&y.application.activeStreams.length>0&&(d.application.activeStreams=y.application.activeStreams),delete y.client_ref,delete y.knocking_id,y.rtcStats&&(d.media.rtcStats=y.rtcStats),this.application._call_draft_list.delete(h.body.channel.id),this.application.calls.set(d.id,y),y._handleStatusChange(h),this.log.debug("_processMemberJoined: processedCall ",{nxmCall:y}),d.members&&h.body.member_id){const k=d.members.get(h.body.member_id);k&&this.application.emit("member:call",k,y)}setTimeout(()=>{d!=null&&d.me&&c.default.emitMediaStream(d.me,w,y.stream)},200)}return this.log.debug("_processMemberJoined: default member joined: ",{event:h}),h}catch(y){this.log.error("_processMemberJoined: ",{e:y})}}_processMemberInvited(d,h){var v,y,w,k,I,A;try{if(!d)return this.log.warn(`no conversation object for ${h.type}`),h;if(((v=d.me)===null||v===void 0?void 0:v.user.id)===h.body.invited_by||!(!((w=(y=h.body.user.media)===null||y===void 0?void 0:y.audio_settings)===null||w===void 0)&&w.enabled))return h;const j=a.default.getMemberNumberFromEventOrNull(h.body.channel)||a.default.getMemberFromNameOrNull(d,h.body.invited_by)||"unknown",L=new s.default(this.application,d,j);return this.application.calls.set(d.id,L),!((k=h.body)===null||k===void 0)&&k.sdp&&this.application.session.config.enableInboundOffer&&L._setOffer({sdp:h.body.sdp,leg_id:h.body.channel.id}),!((I=d.display_name)===null||I===void 0)&&I.startsWith("CALL_")||L._handleStatusChange(h),this.application.emit("member:call",this.application.conversations.get(h.cid).members.get((A=h.body)===null||A===void 0?void 0:A.member_id),L),h}catch(j){this.log.error("_processMemberInvited: ",{e:j})}}}e.default=o,r.exports=o}(zh,zh.exports)),zh.exports}var oS={exports:{}};(function(r,e){var t=Ye&&Ye.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(e,"__esModule",{value:!0});const n=t(ag);class i extends n.default{constructor(a){super(a),this.items=new Map,a.items.forEach(c=>{const o=this.application.updateOrCreateConversation(c);this.items.set(o.id,o)})}getPrev(){return this.hasPrev()?this.application.getConversations(this._getConfig(this.cursor.prev)):this._getError()}getNext(){return this.hasNext()?this.application.getConversations(this._getConfig(this.cursor.next)):this._getError()}}e.default=i,r.exports=i})(oS,oS.exports);var _G=oS.exports,uS={exports:{}},cS={exports:{}};(function(r,e){Object.defineProperty(e,"__esModule",{value:!0});const t=Zo;class n{constructor(s,a){var c,o;this.application=s,this.id=(c=a==null?void 0:a.id)!==null&&c!==void 0?c:null,this._embedded=(o=a==null?void 0:a._embedded)!==null&&o!==void 0?o:null,t.mixin(n)}}e.default=n,r.exports=n})(cS,cS.exports);var bG=cS.exports;(function(r,e){var t=Ye&&Ye.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(e,"__esModule",{value:!0});const n=t(ag),i=t(bG);class s extends n.default{constructor(c){super(c),this.items=new Map,c.items.forEach(o=>{this.items.set(o.id,new i.default(this.application,o))})}getPrev(){return this.hasPrev()?this.application.getUserSessions(this._getConfig(this.cursor.prev)):this._getError()}getNext(){return this.hasNext()?this.application.getUserSessions(this._getConfig(this.cursor.next)):this._getError()}}e.default=s,r.exports=s})(uS,uS.exports);var SG=uS.exports,Kh={exports:{}},Lk;function wG(){return Lk||(Lk=1,function(r,e){var t=Ye&&Ye.__importDefault||function(o){return o&&o.__esModule?o:{default:o}};Object.defineProperty(e,"__esModule",{value:!0}),e.ConversationEventsProcessor=e.EventsQueue=void 0;const n=Ts,i=t(_a()),s=Gr;class a{constructor(l){this.callback=l,this.cidMap=new Map,this.log=s.getLogger(this.constructor.name)}async enqueue(l,d){var h,v,y,w;const{cid:k,id:I}=l,A=Number(I);if(!k||isNaN(A))return this.callback(l);if(!this.cidMap.get(k)){this.log.debug(`enqueue: create new ConversationEventsProcessor for ${k}`);const L=new c(k,A-1,d);if(this.cidMap.set(k,L),l.type=="member:media"&&(!((v=(h=l.body)===null||h===void 0?void 0:h.media)===null||v===void 0)&&v.audio)||l.type=="member:joined"&&(!((w=(y=l.body)===null||y===void 0?void 0:y.channel)===null||w===void 0)&&w.id)){const x=A-20<1?1:A-20,B=await L.fetchConversationEvents(x,20);let G=!1;B.forEach(K=>{K.type==="rtc:transfer"&&K.from===l.from&&(G=!0,L.lastEventIdProcessed=Number(K.id)-1),G&&L.enqueue(Number(K.id),K)})}}const j=this.cidMap.get(k);j.enqueue(A,l),j.processing||(j.processing=!0,await j.processEvents())}}e.EventsQueue=a;class c{constructor(l,d,h){this.cid=l,this.eventsMap=new Map,this.callback=v=>h._handleEvent(v),this.lastEventIdProcessed=d,this.largestEventIdInQueue=d,this.processing=!1,this.application=h,this.eventsFetchRange=9,this.log=s.getLogger(this.constructor.name)}enqueue(l,d){return l>this.largestEventIdInQueue&&(this.largestEventIdInQueue=l),l>this.lastEventIdProcessed&&this.eventsMap.set(l,d),d}dequeue(l){const d=this.eventsMap.get(l);return this.eventsMap.delete(l),d}async processEvents(){const l=()=>(this.eventsMap.clear(),this.log.debug("processEvents: Done Processing"),this.processing=!1);if(this.eventsMap.size<1)return l();const d=this.lastEventIdProcessed+1,h=await this.processNextEvent(d);return h?(this.lastEventIdProcessed=Number(h.id),this.processEvents()):l()}async processNextEvent(l){this.log.debug(`processNextEvent: processing event number ${l}`);const d=this.dequeue(l);try{if(d)return await this.callback(d),d;if(this.largestEventIdInQueue>l){this.log.debug(`processNextEvent: largestEventIdInQueue-${this.largestEventIdInQueue} > eventId-${l}`);const h=await this.fetchEventsAndProcess(l);return h?(this.log.debug("processNextEvent: foundEvent ",{foundEvent:h}),await this.callback(h),h):(this.log.debug(`processNextEvent: not found process next ${l+1}`),this.processNextEvent(l+1))}return}catch{return}}async fetchEventsAndProcess(l){try{const d=await this.fetchConversationEvents(l,this.eventsFetchRange);this.log.debug("fetchEventsAndProcess: fetched events list ",{eventsList:d});let h;return d.forEach(v=>{v.cid=this.cid;const y=Number(v.id);isNaN(y)||y<l||(y>l?(this.log.debug(`fetchEventsAndProcess: event > missingEvent ${y} `,{missingEvent:l}),this.enqueue(y,v)):(this.log.debug("fetchEventsAndProcess: foundEvent ",{event:v}),h=v))}),h}catch(d){this.log.debug("fetchEventsAndProcess: error ",{e:d});return}}async fetchConversationEvents(l,d){this.log.debug("fetchConversationEvents: ",this.cid,l);const h=this.largestEventIdInQueue>l?this.largestEventIdInQueue+d:l+d,v=`${this.application.session.config.nexmo_api_url}/beta2/conversations/${this.cid}/events`;try{return(await i.default.paginationRequest(v,{start_id:l,end_id:h},this.application.session.config.token)).items}catch(y){throw new n.NexmoApiError(y)}}}e.ConversationEventsProcessor=c,r.exports={EventsQueue:a,ConversationEventsProcessor:c}}(Kh,Kh.exports)),Kh.exports}var Uk;function og(){return Uk||(Uk=1,function(r,e){var t=Ye&&Ye.__importDefault||function(G){return G&&G.__esModule?G:{default:G}};Object.defineProperty(e,"__esModule",{value:!0});const n=Zo,i=Gr,s=Ts,a=t(ZO),c=t(z$()),o=t(K$()),l=t(gG),d=t(mG),h=t(yG()),v=t(_a()),y=t(G$),w=t(_G),k=t(SG),I=wG(),A=t(Uw());let j=null,L=null,x=null;class B{constructor(K,D){this.log=i.getLogger(this.constructor.name),this.session=K,this.conversations=new Map,this.synced_conversations_count=0,this.start_sync_time=0,this.stop_sync_time=0,this.calls=new Map,this._call_draft_list=new Map,this.pageConfig=new y.default((K.config||{}).conversations_page_config),this.conversations_page_last=null,this.activeStreams=[],j=new l.default(this),L=new d.default(this),x=new h.default(this),this.me=null,Object.assign(this,D),n.mixin(B)}updateOrCreateConversation(K){const D=this.conversations.get(K.id);return D?(D._updateObjectInstance(K),this.conversations.set(K.id,D)):this.conversations.set(K.id,new c.default(this,K)),this.conversations.get(K.id)}async _enqueueEvent(K){this.session.config.enableEventsQueue?(this.eventsQueue||(this.eventsQueue=new I.EventsQueue(D=>this._handleEvent(D))),this.eventsQueue.enqueue(K,this)):this._handleEvent(K)}async _handleEvent(K){var D,fe,X,pe,Q,Oe,Ve;const Ze=!((D=K._embedded)===null||D===void 0)&&D.from_user?((X=(fe=K._embedded)===null||fe===void 0?void 0:fe.from_user)===null||X===void 0?void 0:X.id)===((pe=this.me)===null||pe===void 0?void 0:pe.id):((Oe=(Q=K.body)===null||Q===void 0?void 0:Q.user)===null||Oe===void 0?void 0:Oe.user_id)===((Ve=this.me)===null||Ve===void 0?void 0:Ve.id),Xe=v.default._checkIfUserIsReInvited(this.conversations,K);if(K.type.startsWith("sip"))return j._handleSipCallEvent(K),K;if(this.conversations.has(K.cid)&&K.type!=="rtc:transfer"&&!Xe)return K.type.startsWith("rtc")&&L._handleRtcEvent(K),this.conversations.get(K.cid)._handleEvent(K),(K.type==="member:joined"||K.type==="member:invited")&&Ze&&this._handleApplicationEvent(K),K;if(K.cid)try{Xe&&this.conversations.delete(K.cid);let Re;return v.default._isCallEvent(K)?Re=await this.getConversation(K.cid,B.CONVERSATION_API_VERSION.v1):Re=await this.getConversation(K.cid,B.CONVERSATION_API_VERSION.v3),this.conversations.set(K.cid,Re),await Re._handleEvent(K),await this._handleApplicationEvent(K),K.type.startsWith("rtc")&&L._handleRtcEvent(K),Promise.resolve(K)}catch(Re){return this.log.error(Re),Promise.reject(Re)}}async updateToken(K){if(this.session.connection&&this.session.connection.disconnected)return this.session.config.token=K,this.session.connection.io.opts.query.token=K,Promise.resolve();const D={url:`${this.session.config.nexmo_api_url}/v0.2/sessions/${this.session.session_id}`,type:"PUT",token:K};try{await v.default.networkRequest(D),this.me&&(this.session.config.token=K,this.session.connection.io.opts.query.token=K)}catch(fe){throw new s.NexmoApiError(fe)}}async _handleApplicationEvent(K){try{this.log.debug("_handleApplicationEvent: ",{event:K});const D=x.handleEvent(K),fe=this.conversations.get(K.cid);let X;if(fe.members.has((D||{}).from))X=fe.members.get(D.from);else if(K.type==="member:joined"||K.type==="member:invited"){const pe={...K.body,...K.from&&{member_id:K.from}};X=new A.default(fe,pe)}else try{X=await fe.getMember(D.from)}catch(pe){this.log.warn(`There is an error getting the member ${pe}`)}return this.emit(D.type,X,D),K}catch(D){throw this.log.error("_handleApplicationEvent: ",D),D}}async inAppCall(K){if(!K||!Array.isArray(K)||K.length===0)return Promise.reject(new s.NexmoClientError("error:application:call:params"));try{const D=new o.default(this);return await D.createCall(K),D.direction=D.CALL_DIRECTION.OUTBOUND,D}catch(D){throw D}}async callServer(K,D="phone",fe={}){try{const X=new o.default(this);return X.direction=X.CALL_DIRECTION.OUTBOUND,await X.createServerCall(K,D,fe),X}catch(X){throw X}}async reconnectCall(K,D,fe={}){try{if(!K||!D)throw new s.NexmoClientError("error:missing:params");const X=await this.getConversation(K,B.CONVERSATION_API_VERSION.v1);await X.media.enable({...fe,reconnectRtcId:D});const pe=new o.default(this,X),Q=Array.from(X.events.values()).map(Oe=>Oe.type);return Q.includes("sip:answered")?pe.status=pe.CALL_STATUS.ANSWERED:Q.includes("sip:ringing")?pe.status=pe.CALL_STATUS.RINGING:pe.status=pe.CALL_STATUS.STARTED,pe.rtcObjects=X.media.rtcObjects,this.calls.set(X.id,pe),pe}catch(X){throw X}}async newConversation(K={}){try{const D=await this.session.sendNetworkRequest({type:"POST",path:"conversations",data:K}),fe=new c.default(this,D);return this.conversations.set(fe.id,fe),this.getConversation(fe.id,B.CONVERSATION_API_VERSION.v1)}catch(D){throw new s.NexmoApiError(D)}}async newConversationAndJoin(K){const D=await this.newConversation(K);return await D.join(),D}async getConversation(K,D=B.CONVERSATION_API_VERSION.v3){if(D!==B.CONVERSATION_API_VERSION.v1&&D!==B.CONVERSATION_API_VERSION.v3)throw new s.NexmoClientError("error:conversation-service:version");let fe;if(D===B.CONVERSATION_API_VERSION.v1)try{fe=await this.session.sendNetworkRequest({type:"GET",path:`conversations/${K}`}),fe.id=fe.uuid,delete fe.uuid}catch(pe){throw new s.NexmoApiError(pe)}else try{fe=await this.session.sendNetworkRequest({type:"GET",path:`conversations/${K}`,version:"v0.3"})}catch(pe){throw new s.NexmoApiError(pe)}const X=this.updateOrCreateConversation(fe);if(D===B.CONVERSATION_API_VERSION.v3&&!X.me)try{const pe=await X.getMyMember();X.me=pe,X.members.set(pe.id,pe)}catch{try{const Q=await X.getMyMember();X.me=Q,X.members.set(Q.id,Q)}catch{this.log.warn(`You don't have any membership in ${X.id}`)}}if(this.session.config.sync==="full"){const{items:pe}=await X.getEvents();return X.events=pe,X}else return X}async getConversations(K={}){const D=`${this.session.config.nexmo_api_url}/beta2/users/${this.me.id}/conversations`;let fe=Object.keys(K).length===0?this.pageConfig:new y.default(K);try{const X=await v.default.paginationRequest(D,fe,this.session.config.token);X.application=this;const pe=new w.default(X);return this.conversations_page_last=pe,pe}catch(X){throw new s.NexmoApiError(X)}}syncConversations(K){const D=Array.from(K.values()),fe=D.length,X=new Date;this.start_sync_time=typeof window<"u"&&window.performance?window.performance.now():X.getTime();const pe=async()=>{this.synced_conversations_percentage=Number((this.synced_conversations_count/fe*100).toFixed(2));const Q={sync_progress:this.synced_conversations_percentage};if(this.emit("sync:progress",Q),this.log.info("Loading sync progress: "+this.synced_conversations_count+"/"+fe+" - "+this.synced_conversations_percentage+"%"),this.synced_conversations_percentage>=100){const Oe=new Date;this.stop_sync_time=typeof window<"u"&&window.performance?window.performance.now():Oe.getTime(),this.log.info("Loaded conversations in "+(this.stop_sync_time-this.start_sync_time)+"ms")}this.synced_conversations_count<fe&&(await this.getConversation(D[this.synced_conversations_count].id),pe(),this.synced_conversations_count++,this.sync_progress_buffer++)};pe()}async getUser(K=this.me.id){try{const D=await this.session.sendNetworkRequest({type:"GET",path:`users/${K}`});return new a.default(this,D)}catch(D){throw new s.NexmoApiError(D)}}async getUserSessions(K={}){var D;const fe=((D=K)===null||D===void 0?void 0:D.user_id)||this.me.id,X=`${this.session.config.nexmo_api_url}/v0.3/users/${fe}/sessions`;let pe=Object.keys(K).length===0?this.pageConfig:new y.default(K);try{const Q=await v.default.paginationRequest(X,pe,this.session.config.token,B.CONVERSATION_API_VERSION.v3);Q.application=this;const Oe=new k.default(Q);return this.user_sessions_page_last=Oe,Oe}catch(Q){throw new s.NexmoApiError(Q)}}}e.default=B,B.CONVERSATION_API_VERSION={v1:"v0.1",v3:"v0.3"},r.exports=B}(xh,xh.exports)),xh.exports}var Fk;function _a(){return Fk||(Fk=1,function(r,e){var t=Ye&&Ye.__importDefault||function(l){return l&&l.__esModule?l:{default:l}};Object.defineProperty(e,"__esModule",{value:!0});const n=t(IH),i=t(zO),s=t(og()),a=4e4,c=2e4;class o{static getMemberFromNameOrNull(d,h){if(!d||!h)return null;for(let v of d.members.values())if(v.user.name===h)return v;return null}static getMemberNumberFromEventOrNull(d){const h=d&&d.from;return h&&(h.number||h.uri)?h.number||h.uri:null}static networkRequest(d){return new Promise((h,v)=>{!d.token&&!d.url.includes("logging")&&!d.url.includes("ping")&&v({response:{type:"error:user:token",description:"network error on request. Please create a new session."}});const y=new XMLHttpRequest;let w;y.open(d.type,d.url,!0),d.token&&y.setRequestHeader("Authorization","Bearer "+d.token),d&&d.url.includes("image")?(y.responseType="",w=d.data,y.onloadstart=()=>{h(y)}):(y.responseType=d.responseType||"json",w=JSON.stringify(d.data)||null,y.setRequestHeader("Content-type","application/json; charset=utf-8")),y.onload=()=>{y.status===200||y.status===201||y.status===204?h(y):v(y)},y.onerror=k=>{v(k)},y.send(w)})}static async paginationRequest(d,h,v,y=s.default.CONVERSATION_API_VERSION.v1){try{const w=await o.networkRequest({type:"GET",url:o.addUrlSearchParams(d,h),token:v}),{page_size:k,_embedded:I,_links:A}=w.response,j=d.split("/").pop().trim();return{items:y===s.default.CONVERSATION_API_VERSION.v1?I.data[j]:I[j],cursor:{prev:A.prev?new URLSearchParams(A.prev.href).get("cursor"):"",next:A.next?new URLSearchParams(A.next.href).get("cursor"):"",self:A.self?new URLSearchParams(A.self.href).get("cursor"):""},page_size:k,order:h.order||"asc",event_type:h.event_type||null}}catch({response:w}){const k=w||{type:"error:network:get-request",description:"network error on nexmo get request"};throw k.validation&&(k.description=k.validation[Object.keys(k.validation)[0]]),k}}static addUrlSearchParams(d,h={}){let v=new URL(d);return Object.keys(h).forEach(y=>{h[y]&&!(typeof h[y]=="string"&&h[y].length<1)&&h[y]!==null&&v.searchParams.set(y,h[y])}),v.href}static deepMergeObj(d,h){const v=JSON.parse(JSON.stringify(d));for(let y in h)Object.prototype.toString.call(h[y])==="[object Object]"?v[y]=o.deepMergeObj(v[y],h[y]):v[y]=h[y];return v}static injectScript(d,h){if(typeof document<"u"){let v=document.getElementsByTagName("head")[0],y=document.createElement("script");y.async=!0,y.src=d,y.onload=y.onreadystatechange=()=>{(!y.readyState||/loaded|complete/.test(y.readyState))&&(y.onload=y.onreadystatechange=null,y=null,h&&h())},v.insertBefore(y,v.firstChild)}}static allocateUUID(){return n.default.v4()}static validateDTMF(d){return typeof d=="string"?/^[\da-dA-D#*pP]{1,45}$$/.test(d):!1}static _getBugsnagKey(){return"76498fc1ca8d9b0a173a44e2b873d7ed"}static updateMemberLegs(d,h){if(d){const v=d.find(y=>y.leg_id===h.body.leg_id);if(!v)d.push({leg_id:h.body.leg_id,status:h.body.status});else if(v.status!==h.body.status){let y=d.indexOf(v);d.fill(v.status=h.body.status,y,y++)}}else d=[{leg_id:h.body.leg_id,status:h.body.status}];return d}static _isCallEvent(d){const{channel:h,media:v}=d.body;return!!(d.type==="rtc:transfer"||h&&(v&&v.audio_settings&&v.audio_settings.enabled||v&&v.audio&&v.audio.enabled||h.knocking_id))}static async _fetchImage(d,h){const{response:v}=await o.networkRequest({type:"GET",url:d,responseType:"arraybuffer",token:h}),y=new Uint8Array(v);let w="";const k=8*1024;let I;for(I=0;I<y.length/k;I++)w+=String.fromCharCode.apply(null,y.subarray(I*k,(I+1)*k));return w+=String.fromCharCode.apply(null,y.subarray(I*k)),"data:image/jpeg;base64,"+btoa(w)}static async _checkHttpConnectivity(d){const h=Date.now();try{await o.networkRequest({type:"GET",url:d});const v=Date.now()-h;return{url:d,canConnect:!0,connectionTime:v}}catch(v){return{url:d,canConnect:!1,error:v}}}static _checkWsConnectivity(d,h,v){return new Promise((y,w)=>{const k=Object.assign({path:h},v),I=Date.now(),A=i.default.connect(d,k),j=setTimeout(()=>y({url:d,canConnect:!1}),c);A.on("connect",()=>{const L=Date.now()-I;A.disconnect(),clearTimeout(j),y({url:d,canConnect:!0,connectionTime:L})}),A.on("error",L=>{A.disconnect(),clearTimeout(j),y({url:d,canConnect:!1,error:L})})})}static async _checkMediaServers(d,h,v){try{const{response:y}=await o.networkRequest({type:"GET",url:`${h}/v0.3/discovery/media/${v}`,token:d}),w=y.map(k=>o._checkMediaConnectivity(k.ip,k.port));return await Promise.all(w)}catch{return[]}}static async _checkMediaConnectivity(d,h){return new Promise(async(v,y)=>{const w={iceServers:[{urls:`stun:${d}:${h}`}]},k=new RTCPeerConnection(w),I=Date.now(),A=await k.createOffer({offerToReceiveAudio:!0});k.setLocalDescription(A);const j=setTimeout(()=>{k.close(),v({ip:d,canConnect:!1})},a);k.onicecandidate=({candidate:L})=>{if((L==null?void 0:L.type)==="srflx"){const x=Date.now()-I;clearTimeout(j),k.close(),v({ip:d,canConnect:!0,connectionTime:x})}},k.onicecandidateerror=L=>{L.errorCode&&(k.close(),clearTimeout(j),v({ip:d,canConnect:!1,error:L}))}})}static _checkIfUserIsReInvited(d,h){var v;if(!d.has(h.cid)||!(h.type==="member:invited"||h.type==="member:joined"))return!1;const y=(v=d.get(h.cid))===null||v===void 0?void 0:v.me;return y?y.user.name===h.body.user.name&&y.state==="LEFT":!1}}e.default=o,r.exports=o}(Oh,Oh.exports)),Oh.exports}var lS={exports:{}};(function(r,e){Object.defineProperty(e,"__esModule",{value:!0});const t=Gr,n=Ts;class i{constructor(a){if(this.log=t.getLogger(this.constructor.name),!a)throw new n.NexmoClientError("no emitter object passed for the Error Emitter");this.emitter=a,this.LISTENER_GROUP="NXM-errors"}emitResponseIfError(a){if(this._isTypeError(a.type))return this.emitter.emit(a.type,this.LISTENER_GROUP,a)}cleanup(){return this.emitter.releaseGroup(this.LISTENER_GROUP)}_isTypeError(a){return a.indexOf("error")!==-1}}e.default=i,r.exports=i})(lS,lS.exports);var TG=lS.exports;(function(r,e){var t=Ye&&Ye.__importDefault||function(I){return I&&I.__esModule?I:{default:I}};Object.defineProperty(e,"__esModule",{value:!0});const n=Zo,i=t(a5),s=t(Gr),a=Ts,c=t(zO),o=t(fH),l=t(yH),d=t(_a()),h=t(og()),v=t(TG),y=t(ZO),w=t(sg());i.default.reg(s.default),i.default.apply(s.default,{template:"[%t] %l (NXM-%n):",timestampFormatter:I=>I.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1"),levelFormatter:I=>I.toUpperCase(),nameFormatter:I=>I||"SDK"});class k{constructor(A={}){const j=A;if(this.config={debug:"silent",log_reporter:{enabled:!1,bugsnag_key:null},environment:"production",ips_url:"https://api-us.vonage.com/v1/image",nexmo_api_url:"https://api-us.vonage.com",path:"/v2/rtc",repository:"https://github.com/Nexmo/conversation-js-sdk",SDK_version:"9.2.4",socket_io:{reconnection:!0,reconnectionAttempts:5,reconnectionDelay:2e3,randomizationFactor:.75,reconnectionDelayMax:15e3,forceNew:!0,autoConnect:!0,transports:["websocket"]},sync:"none",url:"https://ws-us.vonage.com",iceServers:[],rtcstats:{remote_collection:!0,remote_collection_url:"https://hlg.tokbox.com/prod/logging/nexmo_client_js_stats",remote_collection_interval:5e3,emit_events:!1,emit_rtc_analytics:!1,emit_interval:1e3},conversations_page_config:{page_size:10,order:"asc",cursor:""},events_page_config:{page_size:10,order:"asc",event_type:""},enableEventsQueue:!0,enableInboundOffer:!1,token:null},this.config.socket_io.query={token:"",SDK_version:this.config.SDK_version,session_version:"0.0.2",OS_family:"js",OS_revision:typeof navigator<"u"?navigator.userAgent:typeof window<"u"?window.navigator.userAgent:"Generic JS navigator"},this.sessionReady=!1,this.session_id=null,this.apiKey=null,this.requests={},this.application=null,["debug","info","warn","error"].includes(j.debug)?s.default.setLevel(j.debug):j.debug===!0?s.default.setLevel("debug"):s.default.setLevel("silent"),this.log=s.default.noConflict(),this.config=d.default.deepMergeObj(this.config,this._sanitizeConfig(j)),this.config.log_reporter.enabled){const L={apiKey:this.config.log_reporter.bugsnag_key||d.default._getBugsnagKey(),appVersion:this.config.socket_io.query.SDK_version,releaseStage:this.config.environment};Ye.NXMbugsnagClient=o.default(L)}n.mixin(k)}_createAndSetConnection(){let A,j=Object.assign({path:this.config.path},this.config.socket_io);return A=c.default.connect(this.config.url,j),this.connection=A,A.on("connect",()=>{this.emit("ready"),this.sessionReady=!0,this.log.info("websocket ready")}),A.on("disconnect",(L,x)=>{this.emit("disconnect",L==="io client disconnect"?k.DISCONNECT_REASON.ClientDisconnected:L==="io server disconnect"&&this.session_id?k.DISCONNECT_REASON.TokenExpired:k.DISCONNECT_REASON.ConnectionError),this.log.info("websocket disconnected",L,x)}),A.io.on("reconnect",L=>{this.emit("reconnect",L),this.log.info("websocket reconnect",L)}),A.io.on("reconnect_attempt",L=>{this.emit("reconnecting",L),this.log.info("websocket reconnecting",L)}),A.on("connect_error",L=>{this.emit("error",new a.NexmoClientError(L)),this.log.error("Socket.io reported a generic error",L)}),A.io.on("reconnect_failed",()=>{this.emit("error",new a.NexmoClientError("error:client:reconnection_failed")),this.log.error("websocket reconnection error")}),A.io.on("packet",L=>{if(L.type!==2||L.data[0]==="echo")return;const x=L.data[1];if(x.type=L.data[0],this.log.debug("<--",x.type,x),this.requests["session:login"]){const B=this.requests["session:login"].callback;delete this.requests["session:login"],B(x)}else if(x.rid in this.requests){const B=this.requests[x.rid].callback;delete this.requests[x.rid],delete x.delay,this.errorsEmitter&&this.errorsEmitter.emitResponseIfError(x),B(x)}else this.errorsEmitter&&x.type.startsWith("system:error:")?this.errorsEmitter.emitResponseIfError(x):x.type.startsWith("session:")?this.updateSession(x):this.application&&this.application._enqueueEvent(x)}),A}_sanitizeConfig(A){let j=A;return A.sync&&["none","lite","full"].indexOf(A.sync)===-1&&(this.log.warn(`invalid param '${A.sync}' for sync, reverting to ${this.config.sync}`),j.sync=this.config.sync),j}sendRequest(A,j){A.tid=d.default.allocateUUID();const L=A.type;delete A.type,this.log.debug("-->",L,A),this.log.info("-->",L,A.tid),this.connection.emit(L,A),this.requests[A.tid]={type:L,request:A,callback:j}}async sendNetworkRequest(A){const j=A.version||"beta",L=`${this.config.nexmo_api_url}/${j}/${A.path}`;A.type==="GET"||A.type==="DELETE"||(A.data?A.data.originating_session=this.session_id:A.data={originating_session:this.session_id});try{const x={type:A.type,url:L,data:A.data?A.data:null,token:(A.data||{}).token?A.data.token:this.config.token||null};this.log.debug("sendNetworkRequest: ",{request:x});const{response:B}=await d.default.networkRequest(x);return B}catch({response:x}){throw x}}createSession(A){return this.config.socket_io.query.token=A,this._createAndSetConnection(),new Promise((j,L)=>{this.log.info(`Client-SDK Version: ${this.config.SDK_version}`),this.config.token=null,this.requests["session:login"]={type:"session:login",callback:async x=>{if(x.type==="session:success")if(this.session_id=x.body.id,this.apiKey=x.body.api_key,this.config.token=A,this.connection.io.opts.query={session_id:this.session_id,token:this.config.token},(!this.application||this.application.me&&this.application.me.id!==x.body.user_id)&&(this.application=new h.default(this,{})),this.application.me||(this.application.me=new y.default(this.application,{id:x.body.user_id,name:x.body.name})),this.errorsEmitter||(this.errorsEmitter=new v.default(this.application)),this.config.log_reporter.enabled&&(Ye.NXMbugsnagClient.user={id:this.application.me.id,name:this.application.me.name,session_id:x.body.id}),this.config.sync!=="none")try{await this.application.getConversations(),j(this.application)}catch(B){L(B)}else j(this.application);else L(new a.NexmoApiError(x))}}})}deleteSession(){return new Promise(async(A,j)=>{const L=()=>this.sendRequest({type:"session:logout",body:{}},x=>{x.type==="session:logged-out"||x.type==="session:terminated"?(this.disconnect(),delete this.errorsEmitter,delete this.application,delete this.connection,this.requests={},this.sessionReady=!1,A(x)):j(x)});if(this.application){let x=[];if(this.application.conversations.size)for(let B of this.application.conversations.values())x.push(B.media.disable());try{await Promise.all(x)}catch(B){this.log.error("deleteSession: ",B)}return L()}else return L()})}updateSession(A){A.type==="session:success"&&(this.session_id=A.body.id,this.connection.io.opts.query.session_id=A.body.id)}disconnect(){return this.connection.disconnect()}connect(){return this.connection.connect()}async connectivityReport(A,j){const x={machineInfo:{ip:w.default.isNode()?void 0:await l.default.v4()},connectivityReport:[]};try{const{response:B}=await d.default.networkRequest({type:"GET",url:`${this.config.nexmo_api_url}/v0.3/discovery/api`,token:A});let G=B;j!=null&&j.dcListCallback&&(G=j.dcListCallback(G));for(const K in G){const D=G[K].endpoint,fe=G[K].https,X=G[K].ws;try{const pe=await d.default._checkHttpConnectivity(fe),Q=await d.default._checkWsConnectivity(X,this.config.path,this.config.socket_io),Oe=await d.default._checkMediaServers(A,D,K),Ve={name:K,signalConnectionReport:{https:pe,ws:Q},mediaConnectionReport:Oe};x.connectivityReport.push(Ve)}catch(pe){this.log.error(`Error generating report for ${K}`,pe)}}}catch(B){this.log.error("Error fetching nexmo servers information",B)}return x}async checkMediaServers(A,j,L){return await d.default._checkMediaServers(A,j,L)}async checkMediaConnectivity(A,j){return await d.default._checkMediaConnectivity(A,j)}}e.default=k,k.DISCONNECT_REASON={ClientDisconnected:"ClientDisconnected",TokenExpired:"TokenExpired",ConnectionError:"ConnectionError"},r.exports=k})(Db,Db.exports);var CG=Db.exports;const EG=Kv(CG),Va=new an("nexmo-chat"),kG=["us-3","us-4","eu-3","eu-4","ap-3","ap-4"];class J$ extends Hv{constructor(){super(...arguments);be(this,"rtc");be(this,"application");be(this,"conversation")}get _client(){if(this.rtc)return this.rtc;const t=RG(this.region);return this.rtc=new EG({nexmo_api_url:`https://api-${this.region}.${t}`,url:`wss://ws-${this.region}.${t}`}),this.rtc}async create(){const{identity:t,token:n}=await this.issueChatToken();Va.info(`Connecting chat, identity: ${t}, token: ${n}`),this.identity=t,this.application=await this._client.createSession(n)}async destroy(){this.cleanupAudio(),this.rtc&&(await this.rtc.deleteSession(),this.rtc=null,this.application=null,this.conversation=null)}async join(t){const n=await this.application.getConversation(t);n.me.state==="JOINED"?Va.info("already joined conversation:",t):(await n.join(),Va.info("success joined conversation:",t)),this.conversation=n}async preview(t){await this.conversation.sendCustomEvent({type:"ujet_preview",body:{chat_preview:t,chat_preview_updated_at:new Date().toJSON()}})}async fetchMessages(t){const n=await this.conversation.getEvents({event_type:"message",order:"desc",page_size:100}),i=[];return n.items.forEach(s=>{const a=s._embedded.from_user.name,c=jk(s,a);t[c.$index]&&(c.file=t[c.$index]),this.trackInTask(c),i.push(c)}),i.reverse()}async sendMessage(t){try{const n=await this.conversation.sendMessage({message_type:"text",text:JSON.stringify(t)});return Va.info(`Message sent from ${this.conversation.id}, id: ${n.id}`),parseInt(n.id,10)}catch(n){Va.warn(`Failed to send a message from ${this.conversation.id}`,{error:n})}}startTyping(){this.conversation&&this.conversation.startTyping()}stopTyping(){this.conversation&&this.conversation.stopTyping()}registerConversationEvents(){this.registerEvents(this.conversation)}registerEvents(t){t.on("message",(n,i)=>{const s=jk(i,n.userName);Va.info(`Message added from ${this.conversation.id}, index: ${s.$index}, sid: ${s.$sid}, timestamp: ${s.$timestamp}, user type: ${s.$userType}`),s.$userType!==_i.END_USER&&this.ping(),this.trackInTask(s),this.events.triggerEvent("message",s)}),t.on("member:joined",n=>{Va.info("conversation: memberJoined",n),this.events.triggerEvent("memberJoined",n.userName)}),t.on("member:left",n=>{Va.info("conversation: memberLeft",n),this.events.triggerEvent("memberLeft",n.userName)}),t.on("text:typing:on",n=>{/^end_user/.test(n.userName)||this.events.triggerEvent("typingStarted",n.userName)}),t.on("text:typing:off",n=>{/^end_user/.test(n.userName)||this.events.triggerEvent("typingEnded",n.userName)})}}be(J$,"type",Wu.NEXMO);Gv(J$);function RG(r){return kG.indexOf(r)>-1?"vonage.com":"nexmo.com"}function jk(r,e){const{id:t,timestamp:n,body:i}=r,[s,a]=e.split("-");let c=0;a&&(c=parseInt(a,10));const o={$index:parseInt(t,10),$sid:t,$timestamp:new Date(Date.parse(n)),$userType:s,$userId:c};try{const l=JSON.parse(i.text);return l.message&&!l.type?{...l,type:"message",...o}:{...l,...o}}catch(l){return Va.warn("Format message failed",{error:l,data:i.text}),{...o,type:ln.TEXT,content:i.text}}}var Y$={},cd=function(r){return r&&r.Math===Math&&r},Qt=cd(typeof globalThis=="object"&&globalThis)||cd(typeof window=="object"&&window)||cd(typeof self=="object"&&self)||cd(typeof Ye=="object"&&Ye)||cd(typeof Ye=="object"&&Ye)||function(){return this}()||Function("return this")(),co={},Ft=function(r){try{return!!r()}catch{return!0}},PG=Ft,jr=!PG(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7}),IG=Ft,df=!IG(function(){var r=(function(){}).bind();return typeof r!="function"||r.hasOwnProperty("prototype")}),AG=df,Jh=Function.prototype.call,$r=AG?Jh.bind(Jh):function(){return Jh.apply(Jh,arguments)},ff={},X$={}.propertyIsEnumerable,Q$=Object.getOwnPropertyDescriptor,OG=Q$&&!X$.call({1:2},1);ff.f=OG?function(e){var t=Q$(this,e);return!!t&&t.enumerable}:X$;var Ku=function(r,e){return{enumerable:!(r&1),configurable:!(r&2),writable:!(r&4),value:e}},Z$=df,ex=Function.prototype,dS=ex.call,$G=Z$&&ex.bind.bind(dS,dS),Wt=Z$?$G:function(r){return function(){return dS.apply(r,arguments)}},tx=Wt,xG=tx({}.toString),MG=tx("".slice),ba=function(r){return MG(xG(r),8,-1)},DG=Wt,NG=Ft,LG=ba,jy=Object,UG=DG("".split),hf=NG(function(){return!jy("z").propertyIsEnumerable(0)})?function(r){return LG(r)==="String"?UG(r,""):jy(r)}:jy,Ju=function(r){return r==null},FG=Ju,jG=TypeError,Xs=function(r){if(FG(r))throw new jG("Can't call method on "+r);return r},BG=hf,qG=Xs,rs=function(r){return BG(qG(r))},By=typeof document=="object"&&document.all,Br=typeof By>"u"&&By!==void 0?function(r){return typeof r=="function"||r===By}:function(r){return typeof r=="function"},WG=Br,Tr=function(r){return typeof r=="object"?r!==null:WG(r)},qy=Qt,VG=Br,HG=function(r){return VG(r)?r:void 0},Cs=function(r,e){return arguments.length<2?HG(qy[r]):qy[r]&&qy[r][e]},GG=Wt,lo=GG({}.isPrototypeOf),zG=Qt,Bk=zG.navigator,qk=Bk&&Bk.userAgent,eu=qk?String(qk):"",rx=Qt,Wy=eu,Wk=rx.process,Vk=rx.Deno,Hk=Wk&&Wk.versions||Vk&&Vk.version,Gk=Hk&&Hk.v8,Ws,fv;Gk&&(Ws=Gk.split("."),fv=Ws[0]>0&&Ws[0]<4?1:+(Ws[0]+Ws[1]));!fv&&Wy&&(Ws=Wy.match(/Edge\/(\d+)/),(!Ws||Ws[1]>=74)&&(Ws=Wy.match(/Chrome\/(\d+)/),Ws&&(fv=+Ws[1])));var Rl=fv,zk=Rl,KG=Ft,JG=Qt,YG=JG.String,Pl=!!Object.getOwnPropertySymbols&&!KG(function(){var r=Symbol("symbol detection");return!YG(r)||!(Object(r)instanceof Symbol)||!Symbol.sham&&zk&&zk<41}),XG=Pl,nx=XG&&!Symbol.sham&&typeof Symbol.iterator=="symbol",QG=Cs,ZG=Br,ez=lo,tz=nx,rz=Object,Il=tz?function(r){return typeof r=="symbol"}:function(r){var e=QG("Symbol");return ZG(e)&&ez(e.prototype,rz(r))},nz=String,Yu=function(r){try{return nz(r)}catch{return"Object"}},iz=Br,sz=Yu,az=TypeError,Es=function(r){if(iz(r))return r;throw new az(sz(r)+" is not a function")},oz=Es,uz=Ju,Xu=function(r,e){var t=r[e];return uz(t)?void 0:oz(t)},Vy=$r,Hy=Br,Gy=Tr,cz=TypeError,lz=function(r,e){var t,n;if(e==="string"&&Hy(t=r.toString)&&!Gy(n=Vy(t,r))||Hy(t=r.valueOf)&&!Gy(n=Vy(t,r))||e!=="string"&&Hy(t=r.toString)&&!Gy(n=Vy(t,r)))return n;throw new cz("Can't convert object to primitive value")},ix={exports:{}},sx=!1,Kk=Qt,dz=Object.defineProperty,Ww=function(r,e){try{dz(Kk,r,{value:e,configurable:!0,writable:!0})}catch{Kk[r]=e}return e},fz=Qt,hz=Ww,Jk="__core-js_shared__",Yk=ix.exports=fz[Jk]||hz(Jk,{});(Yk.versions||(Yk.versions=[])).push({version:"3.48.0",mode:"global",copyright:"© 2013–2025 Denis Pushkarev (zloirock.ru), 2025–2026 CoreJS Company (core-js.io). All rights reserved.",license:"https://github.com/zloirock/core-js/blob/v3.48.0/LICENSE",source:"https://github.com/zloirock/core-js"});var Vw=ix.exports,Xk=Vw,Al=function(r,e){return Xk[r]||(Xk[r]=e||{})},pz=Xs,vz=Object,oi=function(r){return vz(pz(r))},gz=Wt,mz=oi,yz=gz({}.hasOwnProperty),Yr=Object.hasOwn||function(e,t){return yz(mz(e),t)},_z=Wt,bz=0,Sz=Math.random(),wz=_z(1.1.toString),Ol=function(r){return"Symbol("+(r===void 0?"":r)+")_"+wz(++bz+Sz,36)},Tz=Qt,Cz=Al,Qk=Yr,Ez=Ol,kz=Pl,Rz=nx,Hc=Tz.Symbol,zy=Cz("wks"),Pz=Rz?Hc.for||Hc:Hc&&Hc.withoutSetter||Ez,xr=function(r){return Qk(zy,r)||(zy[r]=kz&&Qk(Hc,r)?Hc[r]:Pz("Symbol."+r)),zy[r]},Iz=$r,Zk=Tr,eR=Il,Az=Xu,Oz=lz,$z=xr,xz=TypeError,Mz=$z("toPrimitive"),Hw=function(r,e){if(!Zk(r)||eR(r))return r;var t=Az(r,Mz),n;if(t){if(e===void 0&&(e="default"),n=Iz(t,r,e),!Zk(n)||eR(n))return n;throw new xz("Can't convert object to primitive value")}return e===void 0&&(e="number"),Oz(r,e)},Dz=Hw,Nz=Il,ug=function(r){var e=Dz(r,"string");return Nz(e)?e:e+""},Lz=Qt,tR=Tr,fS=Lz.document,Uz=tR(fS)&&tR(fS.createElement),cg=function(r){return Uz?fS.createElement(r):{}},Fz=jr,jz=Ft,Bz=cg,ax=!Fz&&!jz(function(){return Object.defineProperty(Bz("div"),"a",{get:function(){return 7}}).a!==7}),qz=jr,Wz=$r,Vz=ff,Hz=Ku,Gz=rs,zz=ug,Kz=Yr,Jz=ax,rR=Object.getOwnPropertyDescriptor;co.f=qz?rR:function(e,t){if(e=Gz(e),t=zz(t),Jz)try{return rR(e,t)}catch{}if(Kz(e,t))return Hz(!Wz(Vz.f,e,t),e[t])};var Ci={},Yz=jr,Xz=Ft,ox=Yz&&Xz(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42}),Qz=Tr,Zz=String,e8=TypeError,dn=function(r){if(Qz(r))return r;throw new e8(Zz(r)+" is not an object")},t8=jr,r8=ax,n8=ox,Yh=dn,nR=ug,i8=TypeError,Ky=Object.defineProperty,s8=Object.getOwnPropertyDescriptor,Jy="enumerable",Yy="configurable",Xy="writable";Ci.f=t8?n8?function(e,t,n){if(Yh(e),t=nR(t),Yh(n),typeof e=="function"&&t==="prototype"&&"value"in n&&Xy in n&&!n[Xy]){var i=s8(e,t);i&&i[Xy]&&(e[t]=n.value,n={configurable:Yy in n?n[Yy]:i[Yy],enumerable:Jy in n?n[Jy]:i[Jy],writable:!1})}return Ky(e,t,n)}:Ky:function(e,t,n){if(Yh(e),t=nR(t),Yh(n),r8)try{return Ky(e,t,n)}catch{}if("get"in n||"set"in n)throw new i8("Accessors not supported");return"value"in n&&(e[t]=n.value),e};var a8=jr,o8=Ci,u8=Ku,fo=a8?function(r,e,t){return o8.f(r,e,u8(1,t))}:function(r,e,t){return r[e]=t,r},ux={exports:{}},hS=jr,c8=Yr,cx=Function.prototype,l8=hS&&Object.getOwnPropertyDescriptor,Gw=c8(cx,"name"),d8=Gw&&(function(){}).name==="something",f8=Gw&&(!hS||hS&&l8(cx,"name").configurable),pf={EXISTS:Gw,PROPER:d8,CONFIGURABLE:f8},h8=Wt,p8=Br,pS=Vw,v8=h8(Function.toString);p8(pS.inspectSource)||(pS.inspectSource=function(r){return v8(r)});var zw=pS.inspectSource,g8=Qt,m8=Br,iR=g8.WeakMap,y8=m8(iR)&&/native code/.test(String(iR)),_8=Al,b8=Ol,sR=_8("keys"),lg=function(r){return sR[r]||(sR[r]=b8(r))},vf={},S8=y8,lx=Qt,w8=Tr,T8=fo,Qy=Yr,Zy=Vw,C8=lg,E8=vf,aR="Object already initialized",vS=lx.TypeError,k8=lx.WeakMap,hv,Kd,pv,R8=function(r){return pv(r)?Kd(r):hv(r,{})},P8=function(r){return function(e){var t;if(!w8(e)||(t=Kd(e)).type!==r)throw new vS("Incompatible receiver, "+r+" required");return t}};if(S8||Zy.state){var aa=Zy.state||(Zy.state=new k8);aa.get=aa.get,aa.has=aa.has,aa.set=aa.set,hv=function(r,e){if(aa.has(r))throw new vS(aR);return e.facade=r,aa.set(r,e),e},Kd=function(r){return aa.get(r)||{}},pv=function(r){return aa.has(r)}}else{var Pc=C8("state");E8[Pc]=!0,hv=function(r,e){if(Qy(r,Pc))throw new vS(aR);return e.facade=r,T8(r,Pc,e),e},Kd=function(r){return Qy(r,Pc)?r[Pc]:{}},pv=function(r){return Qy(r,Pc)}}var Fi={set:hv,get:Kd,has:pv,enforce:R8,getterFor:P8},Kw=Wt,I8=Ft,A8=Br,Xh=Yr,gS=jr,O8=pf.CONFIGURABLE,$8=zw,dx=Fi,x8=dx.enforce,M8=dx.get,oR=String,zp=Object.defineProperty,D8=Kw("".slice),N8=Kw("".replace),L8=Kw([].join),U8=gS&&!I8(function(){return zp(function(){},"length",{value:8}).length!==8}),F8=String(String).split("String"),j8=ux.exports=function(r,e,t){D8(oR(e),0,7)==="Symbol("&&(e="["+N8(oR(e),/^Symbol\(([^)]*)\).*$/,"$1")+"]"),t&&t.getter&&(e="get "+e),t&&t.setter&&(e="set "+e),(!Xh(r,"name")||O8&&r.name!==e)&&(gS?zp(r,"name",{value:e,configurable:!0}):r.name=e),U8&&t&&Xh(t,"arity")&&r.length!==t.arity&&zp(r,"length",{value:t.arity});try{t&&Xh(t,"constructor")&&t.constructor?gS&&zp(r,"prototype",{writable:!1}):r.prototype&&(r.prototype=void 0)}catch{}var n=x8(r);return Xh(n,"source")||(n.source=L8(F8,typeof e=="string"?e:"")),r};Function.prototype.toString=j8(function(){return A8(this)&&M8(this).source||$8(this)},"toString");var fx=ux.exports,B8=Br,q8=Ci,W8=fx,V8=Ww,Ei=function(r,e,t,n){n||(n={});var i=n.enumerable,s=n.name!==void 0?n.name:e;if(B8(t)&&W8(t,s,n),n.global)i?r[e]=t:V8(e,t);else{try{n.unsafe?r[e]&&(i=!0):delete r[e]}catch{}i?r[e]=t:q8.f(r,e,{value:t,enumerable:!1,configurable:!n.nonConfigurable,writable:!n.nonWritable})}return r},Qu={},H8=Math.ceil,G8=Math.floor,z8=Math.trunc||function(e){var t=+e;return(t>0?G8:H8)(t)},K8=z8,Sa=function(r){var e=+r;return e!==e||e===0?0:K8(e)},J8=Sa,Y8=Math.max,X8=Math.min,Zu=function(r,e){var t=J8(r);return t<0?Y8(t+e,0):X8(t,e)},Q8=Sa,Z8=Math.min,ho=function(r){var e=Q8(r);return e>0?Z8(e,9007199254740991):0},e9=ho,ui=function(r){return e9(r.length)},t9=rs,r9=Zu,n9=ui,uR=function(r){return function(e,t,n){var i=t9(e),s=n9(i);if(s===0)return!r&&-1;var a=r9(n,s),c;if(r&&t!==t){for(;s>a;)if(c=i[a++],c!==c)return!0}else for(;s>a;a++)if((r||a in i)&&i[a]===t)return r||a||0;return!r&&-1}},dg={includes:uR(!0),indexOf:uR(!1)},i9=Wt,e_=Yr,s9=rs,a9=dg.indexOf,o9=vf,cR=i9([].push),hx=function(r,e){var t=s9(r),n=0,i=[],s;for(s in t)!e_(o9,s)&&e_(t,s)&&cR(i,s);for(;e.length>n;)e_(t,s=e[n++])&&(~a9(i,s)||cR(i,s));return i},Jw=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],u9=hx,c9=Jw,l9=c9.concat("length","prototype");Qu.f=Object.getOwnPropertyNames||function(e){return u9(e,l9)};var gf={};gf.f=Object.getOwnPropertySymbols;var d9=Cs,f9=Wt,h9=Qu,p9=gf,v9=dn,g9=f9([].concat),px=d9("Reflect","ownKeys")||function(e){var t=h9.f(v9(e)),n=p9.f;return n?g9(t,n(e)):t},lR=Yr,m9=px,y9=co,_9=Ci,Yw=function(r,e,t){for(var n=m9(e),i=_9.f,s=y9.f,a=0;a<n.length;a++){var c=n[a];!lR(r,c)&&!(t&&lR(t,c))&&i(r,c,s(e,c))}},b9=Ft,S9=Br,w9=/#|\.prototype\./,mf=function(r,e){var t=C9[T9(r)];return t===k9?!0:t===E9?!1:S9(e)?b9(e):!!e},T9=mf.normalize=function(r){return String(r).replace(w9,".").toLowerCase()},C9=mf.data={},E9=mf.NATIVE="N",k9=mf.POLYFILL="P",fg=mf,Qh=Qt,R9=co.f,P9=fo,I9=Ei,A9=Ww,O9=Yw,$9=fg,Gt=function(r,e){var t=r.target,n=r.global,i=r.stat,s,a,c,o,l,d;if(n?a=Qh:i?a=Qh[t]||A9(t,{}):a=Qh[t]&&Qh[t].prototype,a)for(c in e){if(l=e[c],r.dontCallGetSet?(d=R9(a,c),o=d&&d.value):o=a[c],s=$9(n?c:t+(i?".":"#")+c,r.forced),!s&&o!==void 0){if(typeof l==typeof o)continue;O9(l,o)}(r.sham||o&&o.sham)&&P9(l,"sham",!0),I9(a,c,l,r)}},x9=Ci.f,M9=Yr,D9=xr,dR=D9("toStringTag"),wa=function(r,e,t){r&&!t&&(r=r.prototype),r&&!M9(r,dR)&&x9(r,dR,{configurable:!0,value:e})},N9=Gt,L9=Qt,U9=wa;N9({global:!0},{Reflect:{}});U9(L9.Reflect,"Reflect",!0);var F9=df,vx=Function.prototype,fR=vx.apply,hR=vx.call,ec=typeof Reflect=="object"&&Reflect.apply||(F9?hR.bind(fR):function(){return hR.apply(fR,arguments)}),j9=Wt,Ta=j9([].slice),gx=Wt,B9=Es,q9=Tr,W9=Yr,pR=Ta,V9=df,mx=Function,H9=gx([].concat),G9=gx([].join),t_={},z9=function(r,e,t){if(!W9(t_,e)){for(var n=[],i=0;i<e;i++)n[i]="a["+i+"]";t_[e]=mx("C,a","return new C("+G9(n,",")+")")}return t_[e](r,t)},K9=V9?mx.bind:function(e){var t=B9(this),n=t.prototype,i=pR(arguments,1),s=function(){var c=H9(i,pR(arguments));return this instanceof s?z9(t,c.length,c):t.apply(e,c)};return q9(n)&&(s.prototype=n),s},J9=xr,Y9=J9("toStringTag"),yx={};yx[Y9]="z";var Xw=String(yx)==="[object z]",X9=Xw,Q9=Br,Kp=ba,Z9=xr,e7=Z9("toStringTag"),t7=Object,r7=Kp(function(){return arguments}())==="Arguments",n7=function(r,e){try{return r[e]}catch{}},po=X9?Kp:function(r){var e,t,n;return r===void 0?"Undefined":r===null?"Null":typeof(t=n7(e=t7(r),e7))=="string"?t:r7?Kp(e):(n=Kp(e))==="Object"&&Q9(e.callee)?"Arguments":n},i7=Wt,s7=Ft,_x=Br,a7=po,o7=Cs,u7=zw,bx=function(){},Sx=o7("Reflect","construct"),Qw=/^\s*(?:class|function)\b/,c7=i7(Qw.exec),l7=!Qw.test(bx),ld=function(e){if(!_x(e))return!1;try{return Sx(bx,[],e),!0}catch{return!1}},wx=function(e){if(!_x(e))return!1;switch(a7(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return l7||!!c7(Qw,u7(e))}catch{return!0}};wx.sham=!0;var hg=!Sx||s7(function(){var r;return ld(ld.call)||!ld(Object)||!ld(function(){r=!0})||r})?wx:ld,d7=hg,f7=Yu,h7=TypeError,Zw=function(r){if(d7(r))return r;throw new h7(f7(r)+" is not a constructor")},e0={},p7=hx,v7=Jw,yf=Object.keys||function(e){return p7(e,v7)},g7=jr,m7=ox,y7=Ci,_7=dn,b7=rs,S7=yf;e0.f=g7&&!m7?Object.defineProperties:function(e,t){_7(e);for(var n=b7(t),i=S7(t),s=i.length,a=0,c;s>a;)y7.f(e,c=i[a++],n[c]);return e};var w7=Cs,Tx=w7("document","documentElement"),T7=dn,C7=e0,vR=Jw,E7=vf,k7=Tx,R7=cg,P7=lg,gR=">",mR="<",mS="prototype",yS="script",Cx=P7("IE_PROTO"),r_=function(){},Ex=function(r){return mR+yS+gR+r+mR+"/"+yS+gR},yR=function(r){r.write(Ex("")),r.close();var e=r.parentWindow.Object;return r=null,e},I7=function(){var r=R7("iframe"),e="java"+yS+":",t;return r.style.display="none",k7.appendChild(r),r.src=String(e),t=r.contentWindow.document,t.open(),t.write(Ex("document.F=Object")),t.close(),t.F},Zh,Jp=function(){try{Zh=new ActiveXObject("htmlfile")}catch{}Jp=typeof document<"u"?document.domain&&Zh?yR(Zh):I7():yR(Zh);for(var r=vR.length;r--;)delete Jp[mS][vR[r]];return Jp()};E7[Cx]=!0;var tu=Object.create||function(e,t){var n;return e!==null?(r_[mS]=T7(e),n=new r_,r_[mS]=null,n[Cx]=e):n=Jp(),t===void 0?n:C7.f(n,t)},A7=Gt,O7=Cs,n_=ec,$7=K9,_R=Zw,x7=dn,bR=Tr,M7=tu,kx=Ft,t0=O7("Reflect","construct"),D7=Object.prototype,N7=[].push,Rx=kx(function(){function r(){}return!(t0(function(){},[],r)instanceof r)}),Px=!kx(function(){t0(function(){})}),SR=Rx||Px;A7({target:"Reflect",stat:!0,forced:SR,sham:SR},{construct:function(e,t){_R(e),x7(t);var n=arguments.length<3?e:_R(arguments[2]);if(Px&&!Rx)return t0(e,t,n);if(e===n){switch(t.length){case 0:return new e;case 1:return new e(t[0]);case 2:return new e(t[0],t[1]);case 3:return new e(t[0],t[1],t[2]);case 4:return new e(t[0],t[1],t[2],t[3])}var i=[null];return n_(N7,i,t),new(n_($7,e,i))}var s=n.prototype,a=M7(bR(s)?s:D7),c=n_(e,a,t);return bR(c)?c:a}});var L7=Gt,U7=oi,Ix=yf,F7=Ft,j7=F7(function(){Ix(1)});L7({target:"Object",stat:!0,forced:j7},{keys:function(e){return Ix(U7(e))}});var B7=po,q7=String,$n=function(r){if(B7(r)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return q7(r)},r0={},W7=ba,V7=rs,Ax=Qu.f,H7=Ta,Ox=typeof window=="object"&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],G7=function(r){try{return Ax(r)}catch{return H7(Ox)}};r0.f=function(e){return Ox&&W7(e)==="Window"?G7(e):Ax(V7(e))};var wR=fx,z7=Ci,Ca=function(r,e,t){return t.get&&wR(t.get,e,{getter:!0}),t.set&&wR(t.set,e,{setter:!0}),z7.f(r,e,t)},n0={},K7=xr;n0.f=K7;var J7=Qt,i0=J7,TR=i0,Y7=Yr,X7=n0,Q7=Ci.f,$x=function(r){var e=TR.Symbol||(TR.Symbol={});Y7(e,r)||Q7(e,r,{value:X7.f(r)})},Z7=$r,eK=Cs,tK=xr,rK=Ei,nK=function(){var r=eK("Symbol"),e=r&&r.prototype,t=e&&e.valueOf,n=tK("toPrimitive");e&&!e[n]&&rK(e,n,function(i){return Z7(t,this)},{arity:1})},iK=ba,sK=Wt,s0=function(r){if(iK(r)==="Function")return sK(r)},CR=s0,aK=Es,oK=df,uK=CR(CR.bind),vo=function(r,e){return aK(r),e===void 0?r:oK?uK(r,e):function(){return r.apply(e,arguments)}},cK=ba,_f=Array.isArray||function(e){return cK(e)==="Array"},ER=_f,lK=hg,dK=Tr,fK=xr,hK=fK("species"),kR=Array,pK=function(r){var e;return ER(r)&&(e=r.constructor,lK(e)&&(e===kR||ER(e.prototype))?e=void 0:dK(e)&&(e=e[hK],e===null&&(e=void 0))),e===void 0?kR:e},vK=pK,a0=function(r,e){return new(vK(r))(e===0?0:e)},gK=jr,mK=Ci,yK=Ku,$l=function(r,e,t){gK?mK.f(r,e,yK(0,t)):r[e]=t},_K=vo,bK=hf,SK=oi,wK=ui,RR=a0,i_=$l,Cu=function(r){var e=r===1,t=r===2,n=r===3,i=r===4,s=r===6,a=r===7,c=r===5||s;return function(o,l,d){for(var h=SK(o),v=bK(h),y=wK(v),w=_K(l,d),k=0,I=0,A=e?RR(o,y):t||a?RR(o,0):void 0,j,L;y>k;k++)if((c||k in v)&&(j=v[k],L=w(j,k,h),r))if(e)i_(A,k,L);else if(L)switch(r){case 3:return!0;case 5:return j;case 6:return k;case 2:i_(A,I++,j)}else switch(r){case 4:return!1;case 7:i_(A,I++,j)}return s?-1:n||i?i:A}},ji={forEach:Cu(0),map:Cu(1),filter:Cu(2),some:Cu(3),every:Cu(4),find:Cu(5),findIndex:Cu(6)},pg=Gt,bf=Qt,o0=$r,TK=Wt,pl=jr,vl=Pl,CK=Ft,Un=Yr,EK=lo,_S=dn,vg=rs,u0=ug,kK=$n,bS=Ku,gl=tu,xx=yf,RK=Qu,Mx=r0,PK=gf,Dx=co,Nx=Ci,IK=e0,Lx=ff,s_=Ei,AK=Ca,c0=Al,OK=lg,Ux=vf,PR=Ol,$K=xr,xK=n0,MK=$x,DK=nK,NK=wa,Fx=Fi,gg=ji.forEach,Di=OK("hidden"),mg="Symbol",Jd="prototype",LK=Fx.set,IR=Fx.getterFor(mg),ys=Object[Jd],Fu=bf.Symbol,Ad=Fu&&Fu[Jd],UK=bf.RangeError,FK=bf.TypeError,a_=bf.QObject,jx=Dx.f,ju=Nx.f,Bx=Mx.f,jK=Lx.f,qx=TK([].push),no=c0("symbols"),Sf=c0("op-symbols"),BK=c0("wks"),SS=!a_||!a_[Jd]||!a_[Jd].findChild,Wx=function(r,e,t){var n=jx(ys,e);n&&delete ys[e],ju(r,e,t),n&&r!==ys&&ju(ys,e,n)},wS=pl&&CK(function(){return gl(ju({},"a",{get:function(){return ju(this,"a",{value:7}).a}})).a!==7})?Wx:ju,o_=function(r,e){var t=no[r]=gl(Ad);return LK(t,{type:mg,tag:r,description:e}),pl||(t.description=e),t},yg=function(e,t,n){e===ys&&yg(Sf,t,n),_S(e);var i=u0(t);return _S(n),Un(no,i)?(n.enumerable?(Un(e,Di)&&e[Di][i]&&(e[Di][i]=!1),n=gl(n,{enumerable:bS(0,!1)})):(Un(e,Di)||ju(e,Di,bS(1,gl(null))),e[Di][i]=!0),wS(e,i,n)):ju(e,i,n)},l0=function(e,t){_S(e);var n=vg(t),i=xx(n).concat(Gx(n));return gg(i,function(s){(!pl||o0(TS,n,s))&&yg(e,s,n[s])}),e},qK=function(e,t){return t===void 0?gl(e):l0(gl(e),t)},TS=function(e){var t=u0(e),n=o0(jK,this,t);return this===ys&&Un(no,t)&&!Un(Sf,t)?!1:n||!Un(this,t)||!Un(no,t)||Un(this,Di)&&this[Di][t]?n:!0},Vx=function(e,t){var n=vg(e),i=u0(t);if(!(n===ys&&Un(no,i)&&!Un(Sf,i))){var s=jx(n,i);return s&&Un(no,i)&&!(Un(n,Di)&&n[Di][i])&&(s.enumerable=!0),s}},Hx=function(e){var t=Bx(vg(e)),n=[];return gg(t,function(i){!Un(no,i)&&!Un(Ux,i)&&qx(n,i)}),n},Gx=function(r){var e=r===ys,t=Bx(e?Sf:vg(r)),n=[];return gg(t,function(i){Un(no,i)&&(!e||Un(ys,i))&&qx(n,no[i])}),n};vl||(Fu=function(){if(EK(Ad,this))throw new FK("Symbol is not a constructor");var e=!arguments.length||arguments[0]===void 0?void 0:kK(arguments[0]),t=PR(e),n=function(i){var s=this===void 0?bf:this;s===ys&&o0(n,Sf,i),Un(s,Di)&&Un(s[Di],t)&&(s[Di][t]=!1);var a=bS(1,i);try{wS(s,t,a)}catch(c){if(!(c instanceof UK))throw c;Wx(s,t,a)}};return pl&&SS&&wS(ys,t,{configurable:!0,set:n}),o_(t,e)},Ad=Fu[Jd],s_(Ad,"toString",function(){return IR(this).tag}),s_(Fu,"withoutSetter",function(r){return o_(PR(r),r)}),Lx.f=TS,Nx.f=yg,IK.f=l0,Dx.f=Vx,RK.f=Mx.f=Hx,PK.f=Gx,xK.f=function(r){return o_($K(r),r)},pl&&(AK(Ad,"description",{configurable:!0,get:function(){return IR(this).description}}),s_(ys,"propertyIsEnumerable",TS,{unsafe:!0})));pg({global:!0,constructor:!0,wrap:!0,forced:!vl,sham:!vl},{Symbol:Fu});gg(xx(BK),function(r){MK(r)});pg({target:mg,stat:!0,forced:!vl},{useSetter:function(){SS=!0},useSimple:function(){SS=!1}});pg({target:"Object",stat:!0,forced:!vl,sham:!pl},{create:qK,defineProperty:yg,defineProperties:l0,getOwnPropertyDescriptor:Vx});pg({target:"Object",stat:!0,forced:!vl},{getOwnPropertyNames:Hx});DK();NK(Fu,mg);Ux[Di]=!0;var WK=Pl,zx=WK&&!!Symbol.for&&!!Symbol.keyFor,VK=Gt,HK=Cs,GK=Yr,zK=$n,Kx=Al,KK=zx,u_=Kx("string-to-symbol-registry"),JK=Kx("symbol-to-string-registry");VK({target:"Symbol",stat:!0,forced:!KK},{for:function(r){var e=zK(r);if(GK(u_,e))return u_[e];var t=HK("Symbol")(e);return u_[e]=t,JK[t]=e,t}});var YK=Gt,XK=Yr,QK=Il,ZK=Yu,eJ=Al,tJ=zx,AR=eJ("symbol-to-string-registry");YK({target:"Symbol",stat:!0,forced:!tJ},{keyFor:function(e){if(!QK(e))throw new TypeError(ZK(e)+" is not a symbol");if(XK(AR,e))return AR[e]}});var rJ=Tr,nJ=Fi.get,iJ=function(e){if(!rJ(e))return!1;var t=nJ(e);return!!t&&t.type==="RawJSON"},d0=Wt,sJ=Yr,ep=SyntaxError,aJ=parseInt,oJ=String.fromCharCode,uJ=d0("".charAt),OR=d0("".slice),$R=d0(/./.exec),xR={'\\"':'"',"\\\\":"\\","\\/":"/","\\b":"\b","\\f":"\f","\\n":`
|
|
102
102
|
`,"\\r":"\r","\\t":" "},cJ=/^[\da-f]{4}$/i,lJ=/^[\u0000-\u001F]$/,dJ=function(r,e){for(var t=!0,n="";e<r.length;){var i=uJ(r,e);if(i==="\\"){var s=OR(r,e,e+2);if(sJ(xR,s))n+=xR[s],e+=2;else if(s==="\\u"){e+=2;var a=OR(r,e,e+4);if(!$R(cJ,a))throw new ep("Bad Unicode escape at: "+e);n+=oJ(aJ(a,16)),e+=4}else throw new ep('Unknown escape sequence: "'+s+'"')}else if(i==='"'){t=!1,e++;break}else{if($R(lJ,i))throw new ep("Bad control character in string literal at: "+e);n+=i,e++}}if(t)throw new ep("Unterminated string at: "+e);return{value:n,end:e}},fJ=Ft,hJ=!fJ(function(){var r="9007199254740993",e=JSON.rawJSON(r);return!JSON.isRawJSON(e)||JSON.stringify(e)!==r}),pJ=Gt,Jx=Cs,vJ=ec,Yx=$r,tc=Wt,Xx=Ft,MR=_f,vv=Br,gJ=iJ,DR=Il,NR=ba,mJ=$n,yJ=Ta,_J=dJ,bJ=Ol,SJ=Pl,c_=hJ,Qx=String,Go=Jx("JSON","stringify"),tp=tc(/./.exec),CS=tc("".charAt),wJ=tc("".charCodeAt),TJ=tc("".replace),l_=tc("".slice),ES=tc([].push),CJ=tc(1.1.toString),EJ=/[\uD800-\uDFFF]/g,LR=/^[\uD800-\uDBFF]$/,UR=/^[\uDC00-\uDFFF]$/,kS=bJ(),FR=kS.length,Zx=!SJ||Xx(function(){var r=Jx("Symbol")("stringify detection");return Go([r])!=="[null]"||Go({a:r})!=="{}"||Go(Object(r))!=="{}"}),jR=Xx(function(){return Go("\uDF06\uD834")!=='"\\udf06\\ud834"'||Go("\uDEAD")!=='"\\udead"'}),kJ=Zx?function(r,e){var t=yJ(arguments),n=eM(e);if(!(!vv(n)&&(r===void 0||DR(r))))return t[1]=function(i,s){if(vv(n)&&(s=Yx(n,this,Qx(i),s)),!DR(s))return s},vJ(Go,null,t)}:Go,RJ=function(r,e,t){var n=CS(t,e-1),i=CS(t,e+1);return tp(LR,r)&&!tp(UR,i)||tp(UR,r)&&!tp(LR,n)?"\\u"+CJ(wJ(r,0),16):r},eM=function(r){if(vv(r))return r;if(MR(r)){for(var e=r.length,t=[],n=0;n<e;n++){var i=r[n];typeof i=="string"?ES(t,i):(typeof i=="number"||NR(i)==="Number"||NR(i)==="String")&&ES(t,mJ(i))}var s=t.length,a=!0;return function(c,o){if(a)return a=!1,o;if(MR(this))return o;for(var l=0;l<s;l++)if(t[l]===c)return o}}};Go&&pJ({target:"JSON",stat:!0,arity:3,forced:Zx||jR||!c_},{stringify:function(e,t,n){var i=eM(t),s=[],a=kJ(e,function(y,w){var k=vv(i)?Yx(i,this,Qx(y),w):w;return!c_&&gJ(k)?kS+(ES(s,k.rawJSON)-1):k},n);if(typeof a!="string"||(jR&&(a=TJ(a,EJ,RJ)),c_))return a;for(var c="",o=a.length,l=0;l<o;l++){var d=CS(a,l);if(d==='"'){var h=_J(a,++l).end-1,v=l_(a,l,h);c+=l_(v,0,FR)===kS?s[l_(v,FR)]:'"'+v+'"',l=h}else c+=d}return c}});var PJ=Gt,IJ=Pl,AJ=Ft,tM=gf,OJ=oi,$J=!IJ||AJ(function(){tM.f(1)});PJ({target:"Object",stat:!0,forced:$J},{getOwnPropertySymbols:function(e){var t=tM.f;return t?t(OJ(e)):[]}});var xJ=Ft,MJ=xr,DJ=Rl,NJ=MJ("species"),wf=function(r){return DJ>=51||!xJ(function(){var e=[],t=e.constructor={};return t[NJ]=function(){return{foo:1}},e[r](Boolean).foo!==1})},LJ=Gt,UJ=ji.filter,FJ=wf,jJ=FJ("filter");LJ({target:"Array",proto:!0,forced:!jJ},{filter:function(e){return UJ(this,e,arguments.length>1?arguments[1]:void 0)}});var BJ=Gt,qJ=Ft,WJ=rs,rM=co.f,nM=jr,VJ=!nM||qJ(function(){rM(1)});BJ({target:"Object",stat:!0,forced:VJ,sham:!nM},{getOwnPropertyDescriptor:function(e,t){return rM(WJ(e),t)}});var HJ=Gt,GJ=jr,zJ=px,KJ=rs,JJ=co,YJ=$l;HJ({target:"Object",stat:!0,sham:!GJ},{getOwnPropertyDescriptors:function(e){for(var t=KJ(e),n=JJ.f,i=zJ(t),s={},a=0,c,o;i.length>a;)o=n(t,c=i[a++]),o!==void 0&&YJ(s,c,o);return s}});var iM={exports:{}};(function(r){function e(n,i,s,a,c,o,l){try{var d=n[o](l),h=d.value}catch(v){return void s(v)}d.done?i(h):Promise.resolve(h).then(a,c)}function t(n){return function(){var i=this,s=arguments;return new Promise(function(a,c){var o=n.apply(i,s);function l(h){e(o,a,c,l,d,"next",h)}function d(h){e(o,a,c,l,d,"throw",h)}l(void 0)})}}r.exports=t,r.exports.__esModule=!0,r.exports.default=r.exports})(iM);var Tf=iM.exports,sM={exports:{}};(function(r){function e(t){if(t===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}r.exports=e,r.exports.__esModule=!0,r.exports.default=r.exports})(sM);var rc=sM.exports,aM={exports:{}},oM={exports:{}};(function(r){function e(t,n){return r.exports=e=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(i,s){return i.__proto__=s,i},r.exports.__esModule=!0,r.exports.default=r.exports,e(t,n)}r.exports=e,r.exports.__esModule=!0,r.exports.default=r.exports})(oM);var f0=oM.exports;(function(r){var e=f0;function t(n,i){if(typeof i!="function"&&i!==null)throw new TypeError("Super expression must either be null or a function");n.prototype=Object.create(i&&i.prototype,{constructor:{value:n,writable:!0,configurable:!0}}),Object.defineProperty(n,"prototype",{writable:!1}),i&&e(n,i)}r.exports=t,r.exports.__esModule=!0,r.exports.default=r.exports})(aM);var ru=aM.exports,uM={exports:{}},cM={exports:{}};(function(r){function e(t){"@babel/helpers - typeof";return r.exports=e=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(n){return typeof n}:function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},r.exports.__esModule=!0,r.exports.default=r.exports,e(t)}r.exports=e,r.exports.__esModule=!0,r.exports.default=r.exports})(cM);var Ea=cM.exports;(function(r){var e=Ea.default,t=rc;function n(i,s){if(s&&(e(s)=="object"||typeof s=="function"))return s;if(s!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return t(i)}r.exports=n,r.exports.__esModule=!0,r.exports.default=r.exports})(uM);var nu=uM.exports,lM={exports:{}};(function(r){function e(t){return r.exports=e=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(n){return n.__proto__||Object.getPrototypeOf(n)},r.exports.__esModule=!0,r.exports.default=r.exports,e(t)}r.exports=e,r.exports.__esModule=!0,r.exports.default=r.exports})(lM);var ka=lM.exports,dM={exports:{}},fM={exports:{}},hM={exports:{}};(function(r){var e=Ea.default;function t(n,i){if(e(n)!="object"||!n)return n;var s=n[Symbol.toPrimitive];if(s!==void 0){var a=s.call(n,i||"default");if(e(a)!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(i==="string"?String:Number)(n)}r.exports=t,r.exports.__esModule=!0,r.exports.default=r.exports})(hM);var XJ=hM.exports;(function(r){var e=Ea.default,t=XJ;function n(i){var s=t(i,"string");return e(s)=="symbol"?s:s+""}r.exports=n,r.exports.__esModule=!0,r.exports.default=r.exports})(fM);var pM=fM.exports;(function(r){var e=pM;function t(n,i,s){return(i=e(i))in n?Object.defineProperty(n,i,{value:s,enumerable:!0,configurable:!0,writable:!0}):n[i]=s,n}r.exports=t,r.exports.__esModule=!0,r.exports.default=r.exports})(dM);var nc=dM.exports,vM={exports:{}};(function(r){var e=pM;function t(i,s){for(var a=0;a<s.length;a++){var c=s[a];c.enumerable=c.enumerable||!1,c.configurable=!0,"value"in c&&(c.writable=!0),Object.defineProperty(i,e(c.key),c)}}function n(i,s,a){return s&&t(i.prototype,s),a&&t(i,a),Object.defineProperty(i,"prototype",{writable:!1}),i}r.exports=n,r.exports.__esModule=!0,r.exports.default=r.exports})(vM);var iu=vM.exports,gM={exports:{}};(function(r){function e(t,n){if(!(t instanceof n))throw new TypeError("Cannot call a class as a function")}r.exports=e,r.exports.__esModule=!0,r.exports.default=r.exports})(gM);var su=gM.exports,QJ=Gt,ZJ=ji.map,eY=wf,tY=eY("map");QJ({target:"Array",proto:!0,forced:!tY},{map:function(e){return ZJ(this,e,arguments.length>1?arguments[1]:void 0)}});var rY=Xw,nY=po,iY=rY?{}.toString:function(){return"[object "+nY(this)+"]"},sY=Xw,aY=Ei,oY=iY;sY||aY(Object.prototype,"toString",oY,{unsafe:!0});var mM={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0},uY=cg,d_=uY("span").classList,BR=d_&&d_.constructor&&d_.constructor.prototype,yM=BR===Object.prototype?void 0:BR,cY=Ft,_g=function(r,e){var t=[][r];return!!t&&cY(function(){t.call(null,e||function(){return 1},1)})},lY=ji.forEach,dY=_g,fY=dY("forEach"),hY=fY?[].forEach:function(e){return lY(this,e,arguments.length>1?arguments[1]:void 0)},qR=Qt,WR=mM,pY=yM,f_=hY,vY=fo,_M=function(r){if(r&&r.forEach!==f_)try{vY(r,"forEach",f_)}catch{r.forEach=f_}};for(var h_ in WR)WR[h_]&&_M(qR[h_]&&qR[h_].prototype);_M(pY);var dd=Qt,gY=eu,mY=ba,rp=function(r){return gY.slice(0,r.length)===r},bM=function(){return rp("Bun/")?"BUN":rp("Cloudflare-Workers")?"CLOUDFLARE":rp("Deno/")?"DENO":rp("Node.js/")?"NODE":dd.Bun&&typeof Bun.version=="string"?"BUN":dd.Deno&&typeof Deno.version=="object"?"DENO":mY(dd.process)==="process"?"NODE":dd.window&&dd.document?"BROWSER":"REST"}(),yY=bM,h0=yY==="NODE",_Y=Wt,bY=Es,SY=function(r,e,t){try{return _Y(bY(Object.getOwnPropertyDescriptor(r,e)[t]))}catch{}},wY=Tr,TY=function(r){return wY(r)||r===null},CY=TY,EY=String,kY=TypeError,RY=function(r){if(CY(r))return r;throw new kY("Can't set "+EY(r)+" as a prototype")},PY=SY,IY=Tr,AY=Xs,OY=RY,xl=Object.setPrototypeOf||("__proto__"in{}?function(){var r=!1,e={},t;try{t=PY(Object.prototype,"__proto__","set"),t(e,[]),r=e instanceof Array}catch{}return function(i,s){return AY(i),OY(s),IY(i)&&(r?t(i,s):i.__proto__=s),i}}():void 0),$Y=Cs,xY=Ca,MY=xr,DY=jr,VR=MY("species"),bg=function(r){var e=$Y(r);DY&&e&&!e[VR]&&xY(e,VR,{configurable:!0,get:function(){return this}})},NY=lo,LY=TypeError,au=function(r,e){if(NY(e,r))return r;throw new LY("Incorrect invocation")},HR=dn,UY=Zw,FY=Ju,jY=xr,BY=jY("species"),SM=function(r,e){var t=HR(r).constructor,n;return t===void 0||FY(n=HR(t)[BY])?e:UY(n)},qY=TypeError,p0=function(r,e){if(r<e)throw new qY("Not enough arguments");return r},WY=eu,wM=/(?:ipad|iphone|ipod).*applewebkit/i.test(WY),Zi=Qt,VY=ec,HY=vo,GR=Br,GY=Yr,TM=Ft,zR=Tx,zY=Ta,KR=cg,KY=p0,JY=wM,YY=h0,RS=Zi.setImmediate,JR=Zi.clearImmediate,XY=Zi.process,p_=Zi.Dispatch,QY=Zi.Function,YR=Zi.MessageChannel,ZY=Zi.String,v_=0,Ld={},XR="onreadystatechange",Yd,Eu,g_,m_;TM(function(){Yd=Zi.location});var v0=function(r){if(GY(Ld,r)){var e=Ld[r];delete Ld[r],e()}},y_=function(r){return function(){v0(r)}},QR=function(r){v0(r.data)},ZR=function(r){Zi.postMessage(ZY(r),Yd.protocol+"//"+Yd.host)};(!RS||!JR)&&(RS=function(e){KY(arguments.length,1);var t=GR(e)?e:QY(e),n=zY(arguments,1);return Ld[++v_]=function(){VY(t,void 0,n)},Eu(v_),v_},JR=function(e){delete Ld[e]},YY?Eu=function(r){XY.nextTick(y_(r))}:p_&&p_.now?Eu=function(r){p_.now(y_(r))}:YR&&!JY?(g_=new YR,m_=g_.port2,g_.port1.onmessage=QR,Eu=HY(m_.postMessage,m_)):Zi.addEventListener&&GR(Zi.postMessage)&&!Zi.importScripts&&Yd&&Yd.protocol!=="file:"&&!TM(ZR)?(Eu=ZR,Zi.addEventListener("message",QR,!1)):XR in KR("script")?Eu=function(r){zR.appendChild(KR("script"))[XR]=function(){zR.removeChild(this),v0(r)}}:Eu=function(r){setTimeout(y_(r),0)});var CM={set:RS},eP=Qt,eX=jr,tX=Object.getOwnPropertyDescriptor,EM=function(r){if(!eX)return eP[r];var e=tX(eP,r);return e&&e.value},kM=function(){this.head=null,this.tail=null};kM.prototype={add:function(r){var e={item:r,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var r=this.head;if(r){var e=this.head=r.next;return e===null&&(this.tail=null),r.item}}};var RM=kM,rX=eu,nX=/ipad|iphone|ipod/i.test(rX)&&typeof Pebble<"u",iX=eu,sX=/web0s(?!.*chrome)/i.test(iX),ml=Qt,aX=EM,tP=vo,__=CM.set,oX=RM,uX=wM,cX=nX,lX=sX,b_=h0,rP=ml.MutationObserver||ml.WebKitMutationObserver,nP=ml.document,iP=ml.process,np=ml.Promise,PS=aX("queueMicrotask"),Ic,S_,w_,ip,sP;if(!PS){var sp=new oX,ap=function(){var r,e;for(b_&&(r=iP.domain)&&r.exit();e=sp.get();)try{e()}catch(t){throw sp.head&&Ic(),t}r&&r.enter()};!uX&&!b_&&!lX&&rP&&nP?(S_=!0,w_=nP.createTextNode(""),new rP(ap).observe(w_,{characterData:!0}),Ic=function(){w_.data=S_=!S_}):!cX&&np&&np.resolve?(ip=np.resolve(void 0),ip.constructor=np,sP=tP(ip.then,ip),Ic=function(){sP(ap)}):b_?Ic=function(){iP.nextTick(ap)}:(__=tP(__,ml),Ic=function(){__(ap)}),PS=function(r){sp.head||Ic(),sp.add(r)}}var dX=PS,fX=function(r,e){try{arguments.length===1?console.error(r):console.error(r,e)}catch{}},g0=function(r){try{return{error:!1,value:r()}}catch(e){return{error:!0,value:e}}},hX=Qt,Sg=hX.Promise,pX=Qt,Ud=Sg,vX=Br,gX=fg,mX=zw,yX=xr,aP=bM,T_=Rl;Ud&&Ud.prototype;var _X=yX("species"),IS=!1,PM=vX(pX.PromiseRejectionEvent),bX=gX("Promise",function(){var r=mX(Ud),e=r!==String(Ud);if(!e&&T_===66)return!0;if(!T_||T_<51||!/native code/.test(r)){var t=new Ud(function(s){s(1)}),n=function(s){s(function(){},function(){})},i=t.constructor={};if(i[_X]=n,IS=t.then(function(){})instanceof n,!IS)return!0}return!e&&(aP==="BROWSER"||aP==="DENO")&&!PM}),Cf={CONSTRUCTOR:bX,REJECTION_EVENT:PM,SUBCLASSING:IS},Ml={},oP=Es,SX=TypeError,wX=function(r){var e,t;this.promise=new r(function(n,i){if(e!==void 0||t!==void 0)throw new SX("Bad Promise constructor");e=n,t=i}),this.resolve=oP(e),this.reject=oP(t)};Ml.f=function(r){return new wX(r)};var TX=Gt,gv=h0,Yo=Qt,CX=i0,yl=$r,uP=Ei,cP=xl,EX=wa,kX=bg,RX=Es,Yp=Br,PX=Tr,IX=au,AX=SM,IM=CM.set,m0=dX,OX=fX,$X=g0,xX=RM,AM=Fi,mv=Sg,y0=Cf,OM=Ml,wg="Promise",$M=y0.CONSTRUCTOR,MX=y0.REJECTION_EVENT,DX=y0.SUBCLASSING,C_=AM.getterFor(wg),NX=AM.set,Uc=mv&&mv.prototype,xu=mv,op=Uc,xM=Yo.TypeError,AS=Yo.document,_0=Yo.process,OS=OM.f,LX=OS,UX=!!(AS&&AS.createEvent&&Yo.dispatchEvent),MM="unhandledrejection",FX="rejectionhandled",lP=0,DM=1,jX=2,b0=1,NM=2,up,dP,LM,fP,UM=function(r){var e;return PX(r)&&Yp(e=r.then)?e:!1},FM=function(r,e){var t=e.value,n=e.state===DM,i=n?r.ok:r.fail,s=r.resolve,a=r.reject,c=r.domain,o,l,d;try{i?(n||(e.rejection===NM&&qX(e),e.rejection=b0),i===!0?o=t:(c&&c.enter(),o=i(t),c&&(c.exit(),d=!0)),o===r.promise?a(new xM("Promise-chain cycle")):(l=UM(o))?yl(l,o,s,a):s(o)):a(t)}catch(h){c&&!d&&c.exit(),a(h)}},jM=function(r,e){r.notified||(r.notified=!0,m0(function(){for(var t=r.reactions,n;n=t.get();)FM(n,r);r.notified=!1,e&&!r.rejection&&BX(r)}))},BM=function(r,e,t){var n,i;UX?(n=AS.createEvent("Event"),n.promise=e,n.reason=t,n.initEvent(r,!1,!0),Yo.dispatchEvent(n)):n={promise:e,reason:t},!MX&&(i=Yo["on"+r])?i(n):r===MM&&OX("Unhandled promise rejection",t)},BX=function(r){yl(IM,Yo,function(){var e=r.facade,t=r.value,n=hP(r),i;if(n&&(i=$X(function(){gv?_0.emit("unhandledRejection",t,e):BM(MM,e,t)}),r.rejection=gv||hP(r)?NM:b0,i.error))throw i.value})},hP=function(r){return r.rejection!==b0&&!r.parent},qX=function(r){yl(IM,Yo,function(){var e=r.facade;gv?_0.emit("rejectionHandled",e):BM(FX,e,r.value)})},Gc=function(r,e,t){return function(n){r(e,n,t)}},Zc=function(r,e,t){r.done||(r.done=!0,t&&(r=t),r.value=e,r.state=jX,jM(r,!0))},$S=function(r,e,t){if(!r.done){r.done=!0,t&&(r=t);try{if(r.facade===e)throw new xM("Promise can't be resolved itself");var n=UM(e);n?m0(function(){var i={done:!1};try{yl(n,e,Gc($S,i,r),Gc(Zc,i,r))}catch(s){Zc(i,s,r)}}):(r.value=e,r.state=DM,jM(r,!1))}catch(i){Zc({done:!1},i,r)}}};if($M&&(xu=function(e){IX(this,op),RX(e),yl(up,this);var t=C_(this);try{e(Gc($S,t),Gc(Zc,t))}catch(n){Zc(t,n)}},op=xu.prototype,up=function(e){NX(this,{type:wg,done:!1,notified:!1,parent:!1,reactions:new xX,rejection:!1,state:lP,value:null})},up.prototype=uP(op,"then",function(e,t){var n=C_(this),i=OS(AX(this,xu));return n.parent=!0,i.ok=Yp(e)?e:!0,i.fail=Yp(t)&&t,i.domain=gv?_0.domain:void 0,n.state===lP?n.reactions.add(i):m0(function(){FM(i,n)}),i.promise}),dP=function(){var r=new up,e=C_(r);this.promise=r,this.resolve=Gc($S,e),this.reject=Gc(Zc,e)},OM.f=OS=function(r){return r===xu||r===LM?new dP(r):LX(r)},Yp(mv)&&Uc!==Object.prototype)){fP=Uc.then,DX||uP(Uc,"then",function(e,t){var n=this;return new xu(function(i,s){yl(fP,n,i,s)}).then(e,t)},{unsafe:!0});try{delete Uc.constructor}catch{}cP&&cP(Uc,op)}TX({global:!0,constructor:!0,wrap:!0,forced:$M},{Promise:xu});LM=CX.Promise;EX(xu,wg,!1);kX(wg);var Ef={},WX=xr,VX=Ef,HX=WX("iterator"),GX=Array.prototype,S0=function(r){return r!==void 0&&(VX.Array===r||GX[HX]===r)},zX=po,pP=Xu,KX=Ju,JX=Ef,YX=xr,XX=YX("iterator"),kf=function(r){if(!KX(r))return pP(r,XX)||pP(r,"@@iterator")||JX[zX(r)]},QX=$r,ZX=Es,eQ=dn,tQ=Yu,rQ=kf,nQ=TypeError,Tg=function(r,e){var t=arguments.length<2?rQ(r):e;if(ZX(t))return eQ(QX(t,r));throw new nQ(tQ(r)+" is not iterable")},iQ=$r,vP=dn,sQ=Xu,qM=function(r,e,t){var n,i;vP(r);try{if(n=sQ(r,"return"),!n){if(e==="throw")throw t;return t}n=iQ(n,r)}catch(s){i=!0,n=s}if(e==="throw")throw t;if(i)throw n;return vP(n),t},aQ=vo,oQ=$r,uQ=dn,cQ=Yu,lQ=S0,dQ=ui,gP=lo,fQ=Tg,hQ=kf,mP=qM,pQ=TypeError,Xp=function(r,e){this.stopped=r,this.result=e},yP=Xp.prototype,Rf=function(r,e,t){var n=t&&t.that,i=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),a=!!(t&&t.IS_ITERATOR),c=!!(t&&t.INTERRUPTED),o=aQ(e,n),l,d,h,v,y,w,k,I=function(j){return l&&mP(l,"normal"),new Xp(!0,j)},A=function(j){return i?(uQ(j),c?o(j[0],j[1],I):o(j[0],j[1])):c?o(j,I):o(j)};if(s)l=r.iterator;else if(a)l=r;else{if(d=hQ(r),!d)throw new pQ(cQ(r)+" is not iterable");if(lQ(d)){for(h=0,v=dQ(r);v>h;h++)if(y=A(r[h]),y&&gP(yP,y))return y;return new Xp(!1)}l=fQ(r,d)}for(w=s?r.next:l.next;!(k=oQ(w,l)).done;){try{y=A(k.value)}catch(j){mP(l,"throw",j)}if(typeof y=="object"&&y&&gP(yP,y))return y}return new Xp(!1)},vQ=xr,WM=vQ("iterator"),VM=!1;try{var gQ=0,_P={next:function(){return{done:!!gQ++}},return:function(){VM=!0}};_P[WM]=function(){return this},Array.from(_P,function(){throw 2})}catch{}var Cg=function(r,e){try{if(!e&&!VM)return!1}catch{return!1}var t=!1;try{var n={};n[WM]=function(){return{next:function(){return{done:t=!0}}}},r(n)}catch{}return t},mQ=Sg,yQ=Cg,_Q=Cf.CONSTRUCTOR,HM=_Q||!yQ(function(r){mQ.all(r).then(void 0,function(){})}),bQ=Gt,SQ=$r,wQ=Es,TQ=Ml,CQ=g0,EQ=Rf,kQ=HM;bQ({target:"Promise",stat:!0,forced:kQ},{all:function(e){var t=this,n=TQ.f(t),i=n.resolve,s=n.reject,a=CQ(function(){var c=wQ(t.resolve),o=[],l=0,d=1;EQ(e,function(h){var v=l++,y=!1;d++,SQ(c,t,h).then(function(w){y||(y=!0,o[v]=w,--d||i(o))},s)}),--d||i(o)});return a.error&&s(a.value),n.promise}});var RQ=Gt,PQ=Cf.CONSTRUCTOR,xS=Sg,IQ=Cs,AQ=Br,OQ=Ei,bP=xS&&xS.prototype;RQ({target:"Promise",proto:!0,forced:PQ,real:!0},{catch:function(r){return this.then(void 0,r)}});if(AQ(xS)){var SP=IQ("Promise").prototype.catch;bP.catch!==SP&&OQ(bP,"catch",SP,{unsafe:!0})}var $Q=Gt,xQ=$r,MQ=Es,DQ=Ml,NQ=g0,LQ=Rf,UQ=HM;$Q({target:"Promise",stat:!0,forced:UQ},{race:function(e){var t=this,n=DQ.f(t),i=n.reject,s=NQ(function(){var a=MQ(t.resolve);LQ(e,function(c){xQ(a,t,c).then(n.resolve,i)})});return s.error&&i(s.value),n.promise}});var FQ=Gt,jQ=Ml,BQ=Cf.CONSTRUCTOR;FQ({target:"Promise",stat:!0,forced:BQ},{reject:function(e){var t=jQ.f(this),n=t.reject;return n(e),t.promise}});var qQ=dn,WQ=Tr,VQ=Ml,HQ=function(r,e){if(qQ(r),WQ(e)&&e.constructor===r)return e;var t=VQ.f(r),n=t.resolve;return n(e),t.promise},GQ=Gt,zQ=Cs,KQ=Cf.CONSTRUCTOR,JQ=HQ;zQ("Promise");GQ({target:"Promise",stat:!0,forced:KQ},{resolve:function(e){return JQ(this,e)}});var GM={exports:{}},zM={exports:{}};(function(r){function e(t,n){this.v=t,this.k=n}r.exports=e,r.exports.__esModule=!0,r.exports.default=r.exports})(zM);var KM=zM.exports,JM={exports:{}},YM={exports:{}};(function(r){function e(t,n,i,s){var a=Object.defineProperty;try{a({},"",{})}catch{a=0}r.exports=e=function(o,l,d,h){function v(y,w){e(o,y,function(k){return this._invoke(y,w,k)})}l?a?a(o,l,{value:d,enumerable:!h,configurable:!h,writable:!h}):o[l]=d:(v("next",0),v("throw",1),v("return",2))},r.exports.__esModule=!0,r.exports.default=r.exports,e(t,n,i,s)}r.exports=e,r.exports.__esModule=!0,r.exports.default=r.exports})(YM);var XM=YM.exports;(function(r){var e=XM;function t(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */var n,i,s=typeof Symbol=="function"?Symbol:{},a=s.iterator||"@@iterator",c=s.toStringTag||"@@toStringTag";function o(I,A,j,L){var x=A&&A.prototype instanceof d?A:d,B=Object.create(x.prototype);return e(B,"_invoke",function(G,K,D){var fe,X,pe,Q=0,Oe=D||[],Ve=!1,Ze={p:0,n:0,v:n,a:Xe,f:Xe.bind(n,4),d:function(Je,Ke){return fe=Je,X=0,pe=n,Ze.n=Ke,l}};function Xe(Re,Je){for(X=Re,pe=Je,i=0;!Ve&&Q&&!Ke&&i<Oe.length;i++){var Ke,Y=Oe[i],Ce=Ze.p,Et=Y[2];Re>3?(Ke=Et===Je)&&(pe=Y[(X=Y[4])?5:(X=3,3)],Y[4]=Y[5]=n):Y[0]<=Ce&&((Ke=Re<2&&Ce<Y[1])?(X=0,Ze.v=Je,Ze.n=Y[1]):Ce<Et&&(Ke=Re<3||Y[0]>Je||Je>Et)&&(Y[4]=Re,Y[5]=Je,Ze.n=Et,X=0))}if(Ke||Re>1)return l;throw Ve=!0,Je}return function(Re,Je,Ke){if(Q>1)throw TypeError("Generator is already running");for(Ve&&Je===1&&Xe(Je,Ke),X=Je,pe=Ke;(i=X<2?n:pe)||!Ve;){fe||(X?X<3?(X>1&&(Ze.n=-1),Xe(X,pe)):Ze.n=pe:Ze.v=pe);try{if(Q=2,fe){if(X||(Re="next"),i=fe[Re]){if(!(i=i.call(fe,pe)))throw TypeError("iterator result is not an object");if(!i.done)return i;pe=i.value,X<2&&(X=0)}else X===1&&(i=fe.return)&&i.call(fe),X<2&&(pe=TypeError("The iterator does not provide a '"+Re+"' method"),X=1);fe=n}else if((i=(Ve=Ze.n<0)?pe:G.call(K,Ze))!==l)break}catch(Y){fe=n,X=1,pe=Y}finally{Q=1}}return{value:i,done:Ve}}}(I,j,L),!0),B}var l={};function d(){}function h(){}function v(){}i=Object.getPrototypeOf;var y=[][a]?i(i([][a]())):(e(i={},a,function(){return this}),i),w=v.prototype=d.prototype=Object.create(y);function k(I){return Object.setPrototypeOf?Object.setPrototypeOf(I,v):(I.__proto__=v,e(I,c,"GeneratorFunction")),I.prototype=Object.create(w),I}return h.prototype=v,e(w,"constructor",v),e(v,"constructor",h),h.displayName="GeneratorFunction",e(v,c,"GeneratorFunction"),e(w),e(w,c,"Generator"),e(w,a,function(){return this}),e(w,"toString",function(){return"[object Generator]"}),(r.exports=t=function(){return{w:o,m:k}},r.exports.__esModule=!0,r.exports.default=r.exports)()}r.exports=t,r.exports.__esModule=!0,r.exports.default=r.exports})(JM);var QM=JM.exports,ZM={exports:{}},eD={exports:{}},tD={exports:{}};(function(r){var e=KM,t=XM;function n(i,s){function a(o,l,d,h){try{var v=i[o](l),y=v.value;return y instanceof e?s.resolve(y.v).then(function(w){a("next",w,d,h)},function(w){a("throw",w,d,h)}):s.resolve(y).then(function(w){v.value=w,d(v)},function(w){return a("throw",w,d,h)})}catch(w){h(w)}}var c;this.next||(t(n.prototype),t(n.prototype,typeof Symbol=="function"&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),t(this,"_invoke",function(o,l,d){function h(){return new s(function(v,y){a(o,d,v,y)})}return c=c?c.then(h,h):h()},!0)}r.exports=n,r.exports.__esModule=!0,r.exports.default=r.exports})(tD);var rD=tD.exports;(function(r){var e=QM,t=rD;function n(i,s,a,c,o){return new t(e().w(i,s,a,c),o||Promise)}r.exports=n,r.exports.__esModule=!0,r.exports.default=r.exports})(eD);var nD=eD.exports;(function(r){var e=nD;function t(n,i,s,a,c){var o=e(n,i,s,a,c);return o.next().then(function(l){return l.done?l.value:o.next()})}r.exports=t,r.exports.__esModule=!0,r.exports.default=r.exports})(ZM);var YQ=ZM.exports,iD={exports:{}};(function(r){function e(t){var n=Object(t),i=[];for(var s in n)i.unshift(s);return function a(){for(;i.length;)if((s=i.pop())in n)return a.value=s,a.done=!1,a;return a.done=!0,a}}r.exports=e,r.exports.__esModule=!0,r.exports.default=r.exports})(iD);var XQ=iD.exports,sD={exports:{}};(function(r){var e=Ea.default;function t(n){if(n!=null){var i=n[typeof Symbol=="function"&&Symbol.iterator||"@@iterator"],s=0;if(i)return i.call(n);if(typeof n.next=="function")return n;if(!isNaN(n.length))return{next:function(){return n&&s>=n.length&&(n=void 0),{value:n&&n[s++],done:!n}}}}throw new TypeError(e(n)+" is not iterable")}r.exports=t,r.exports.__esModule=!0,r.exports.default=r.exports})(sD);var QQ=sD.exports;(function(r){var e=KM,t=QM,n=YQ,i=nD,s=rD,a=XQ,c=QQ;function o(){var l=t(),d=l.m(o),h=(Object.getPrototypeOf?Object.getPrototypeOf(d):d.__proto__).constructor;function v(k){var I=typeof k=="function"&&k.constructor;return!!I&&(I===h||(I.displayName||I.name)==="GeneratorFunction")}var y={throw:1,return:2,break:3,continue:3};function w(k){var I,A;return function(j){I||(I={stop:function(){return A(j.a,2)},catch:function(){return j.v},abrupt:function(x,B){return A(j.a,y[x],B)},delegateYield:function(x,B,G){return I.resultName=B,A(j.d,c(x),G)},finish:function(x){return A(j.f,x)}},A=function(x,B,G){j.p=I.prev,j.n=I.next;try{return x(B,G)}finally{I.next=j.n}}),I.resultName&&(I[I.resultName]=j.v,I.resultName=void 0),I.sent=j.v,I.next=j.n;try{return k.call(this,I)}finally{j.p=I.prev,j.n=I.next}}}return(r.exports=o=function(){return{wrap:function(A,j,L,x){return l.w(w(A),j,L,x&&x.reverse())},isGeneratorFunction:v,mark:l.m,awrap:function(A,j){return new e(A,j)},AsyncIterator:s,async:function(A,j,L,x,B){return(v(j)?i:n)(w(A),j,L,x,B)},keys:a,values:c}},r.exports.__esModule=!0,r.exports.default=r.exports)()}r.exports=o,r.exports.__esModule=!0,r.exports.default=r.exports})(GM);var ZQ=GM.exports,Qp=ZQ(),Pf=Qp;try{regeneratorRuntime=Qp}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=Qp:Function("r","regeneratorRuntime = r")(Qp)}var eZ=TypeError,tZ=9007199254740991,aD=function(r){if(r>tZ)throw eZ("Maximum allowed index exceeded");return r},rZ=jr,nZ=_f,iZ=TypeError,sZ=Object.getOwnPropertyDescriptor,aZ=rZ&&!function(){if(this!==void 0)return!0;try{Object.defineProperty([],"length",{writable:!1}).length=1}catch(r){return r instanceof TypeError}}(),Eg=aZ?function(r,e){if(nZ(r)&&!sZ(r,"length").writable)throw new iZ("Cannot set read only .length");return r.length=e}:function(r,e){return r.length=e},oZ=Gt,uZ=Ft,cZ=_f,lZ=Tr,dZ=oi,fZ=ui,wP=aD,TP=$l,hZ=Eg,pZ=a0,vZ=wf,gZ=xr,mZ=Rl,oD=gZ("isConcatSpreadable"),yZ=mZ>=51||!uZ(function(){var r=[];return r[oD]=!1,r.concat()[0]!==r}),_Z=function(r){if(!lZ(r))return!1;var e=r[oD];return e!==void 0?!!e:cZ(r)},bZ=!yZ||!vZ("concat");oZ({target:"Array",proto:!0,arity:1,forced:bZ},{concat:function(e){var t=dZ(this),n=pZ(t,0),i=0,s,a,c,o,l;for(s=-1,c=arguments.length;s<c;s++)if(l=s===-1?t:arguments[s],_Z(l))for(o=fZ(l),wP(i+o),a=0;a<o;a++,i++)a in l&&TP(n,i,l[a]);else wP(i+1),TP(n,i++,l);return hZ(n,i),n}});var SZ=dn,wZ=qM,TZ=function(r,e,t,n){try{return n?e(SZ(t)[0],t[1]):e(t)}catch(i){wZ(r,"throw",i)}},CZ=vo,EZ=$r,kZ=oi,RZ=TZ,PZ=S0,IZ=hg,AZ=ui,CP=$l,OZ=Eg,$Z=Tg,xZ=kf,EP=Array,uD=function(e){var t=kZ(e),n=IZ(this),i=arguments.length,s=i>1?arguments[1]:void 0,a=s!==void 0;a&&(s=CZ(s,i>2?arguments[2]:void 0));var c=xZ(t),o=0,l,d,h,v,y,w;if(c&&!(this===EP&&PZ(c)))for(d=n?new this:[],v=$Z(t,c),y=v.next;!(h=EZ(y,v)).done;o++)w=a?RZ(v,s,[h.value,o],!0):h.value,CP(d,o,w);else for(l=AZ(t),d=n?new this(l):EP(l);l>o;o++)w=a?s(t[o],o):t[o],CP(d,o,w);return OZ(d,o),d},MZ=Gt,DZ=uD,NZ=Cg,LZ=!NZ(function(r){Array.from(r)});MZ({target:"Array",stat:!0,forced:LZ},{from:DZ});var w0=Wt,UZ=Sa,FZ=$n,jZ=Xs,BZ=w0("".charAt),kP=w0("".charCodeAt),qZ=w0("".slice),RP=function(r){return function(e,t){var n=FZ(jZ(e)),i=UZ(t),s=n.length,a,c;return i<0||i>=s?r?"":void 0:(a=kP(n,i),a<55296||a>56319||i+1===s||(c=kP(n,i+1))<56320||c>57343?r?BZ(n,i):a:r?qZ(n,i,i+2):(a-55296<<10)+(c-56320)+65536)}},T0={codeAt:RP(!1),charAt:RP(!0)},WZ=Ft,VZ=!WZ(function(){function r(){}return r.prototype.constructor=null,Object.getPrototypeOf(new r)!==r.prototype}),HZ=Yr,GZ=Br,zZ=oi,KZ=lg,JZ=VZ,PP=KZ("IE_PROTO"),MS=Object,YZ=MS.prototype,If=JZ?MS.getPrototypeOf:function(r){var e=zZ(r);if(HZ(e,PP))return e[PP];var t=e.constructor;return GZ(t)&&e instanceof t?t.prototype:e instanceof MS?YZ:null},XZ=Ft,QZ=Br,ZZ=Tr,IP=If,eee=Ei,tee=xr,DS=tee("iterator"),cD=!1,Gu,E_,k_;[].keys&&(k_=[].keys(),"next"in k_?(E_=IP(IP(k_)),E_!==Object.prototype&&(Gu=E_)):cD=!0);var ree=!ZZ(Gu)||XZ(function(){var r={};return Gu[DS].call(r)!==r});ree&&(Gu={});QZ(Gu[DS])||eee(Gu,DS,function(){return this});var lD={IteratorPrototype:Gu,BUGGY_SAFARI_ITERATORS:cD},nee=lD.IteratorPrototype,iee=tu,see=Ku,aee=wa,oee=Ef,uee=function(){return this},dD=function(r,e,t,n){var i=e+" Iterator";return r.prototype=iee(nee,{next:see(+!n,t)}),aee(r,i,!1),oee[i]=uee,r},cee=Gt,lee=$r,fD=pf,dee=Br,fee=dD,AP=If,OP=xl,hee=wa,pee=fo,R_=Ei,vee=xr,gee=Ef,hD=lD,mee=fD.PROPER,yee=fD.CONFIGURABLE,$P=hD.IteratorPrototype,cp=hD.BUGGY_SAFARI_ITERATORS,fd=vee("iterator"),xP="keys",hd="values",MP="entries",_ee=function(){return this},C0=function(r,e,t,n,i,s,a){fee(t,e,n);var c=function(A){if(A===i&&v)return v;if(!cp&&A&&A in d)return d[A];switch(A){case xP:return function(){return new t(this,A)};case hd:return function(){return new t(this,A)};case MP:return function(){return new t(this,A)}}return function(){return new t(this)}},o=e+" Iterator",l=!1,d=r.prototype,h=d[fd]||d["@@iterator"]||i&&d[i],v=!cp&&h||c(i),y=e==="Array"&&d.entries||h,w,k,I;if(y&&(w=AP(y.call(new r)),w!==Object.prototype&&w.next&&(AP(w)!==$P&&(OP?OP(w,$P):dee(w[fd])||R_(w,fd,_ee)),hee(w,o,!0))),mee&&i===hd&&h&&h.name!==hd&&(yee?pee(d,"name",hd):(l=!0,v=function(){return lee(h,this)})),i)if(k={values:c(hd),keys:s?v:c(xP),entries:c(MP)},a)for(I in k)(cp||l||!(I in d))&&R_(d,I,k[I]);else cee({target:e,proto:!0,forced:cp||l},k);return d[fd]!==v&&R_(d,fd,v,{name:i}),gee[e]=v,k},kg=function(r,e){return{value:r,done:e}},bee=T0.charAt,See=$n,pD=Fi,wee=C0,DP=kg,vD="String Iterator",Tee=pD.set,Cee=pD.getterFor(vD);wee(String,"String",function(r){Tee(this,{type:vD,string:See(r),index:0})},function(){var e=Cee(this),t=e.string,n=e.index,i;return n>=t.length?DP(void 0,!0):(i=bee(t,n),e.index+=i.length,DP(i,!1))});const Bu="\\d+(?:[\\.,]\\d+)?",Eee=`(${Bu}W)`,kee=`(${Bu}Y)?(${Bu}M)?(${Bu}D)?`,Ree=`T(${Bu}H)?(${Bu}M)?(${Bu}S)?`,Pee=`P(?:${Eee}|${kee}(?:${Ree})?)`,Iee=["weeks","years","months","days","hours","minutes","seconds"],E0=new RegExp(Pee),gD=r=>r.match(E0).slice(1).reduce((e,t,n)=>(e[Iee[n]]=parseFloat(t)||0,e),{}),k0=(r,e)=>{const t=e?e.getTime():Date.now(),n=new Date(t);return n.setFullYear(n.getFullYear()+r.years),n.setMonth(n.getMonth()+r.months),n.setDate(n.getDate()+r.days),n.setHours(n.getHours()+r.hours),n.setMinutes(n.getMinutes()+r.minutes),n.setMilliseconds(n.getMilliseconds()+r.seconds*1e3),n.setDate(n.getDate()+r.weeks*7),n},mD=(r,e)=>{const t=e?e.getTime():Date.now(),n=new Date(t);return(k0(r,n).getTime()-n.getTime())/1e3},Aee={end:k0,toSeconds:mD,pattern:E0,parse:gD},Oee=Object.freeze(Object.defineProperty({__proto__:null,default:Aee,end:k0,parse:gD,pattern:E0,toSeconds:mD},Symbol.toStringTag,{value:"Module"})),$ee=CO(Oee);var xee=xr,Mee=tu,Dee=Ci.f,NS=xee("unscopables"),LS=Array.prototype;LS[NS]===void 0&&Dee(LS,NS,{configurable:!0,value:Mee(null)});var R0=function(r){LS[NS][r]=!0},Nee=rs,P0=R0,NP=Ef,yD=Fi,Lee=Ci.f,Uee=C0,lp=kg,Fee=jr,_D="Array Iterator",jee=yD.set,Bee=yD.getterFor(_D),bD=Uee(Array,"Array",function(r,e){jee(this,{type:_D,target:Nee(r),index:0,kind:e})},function(){var r=Bee(this),e=r.target,t=r.index++;if(!e||t>=e.length)return r.target=null,lp(void 0,!0);switch(r.kind){case"keys":return lp(t,!1);case"values":return lp(e[t],!1)}return lp([t,e[t]],!1)},"values"),LP=NP.Arguments=NP.Array;P0("keys");P0("values");P0("entries");if(Fee&&LP.name!=="values")try{Lee(LP,"name",{value:"values"})}catch{}var UP=Qt,SD=mM,qee=yM,Od=bD,FP=fo,Wee=wa,Vee=xr,P_=Vee("iterator"),I_=Od.values,wD=function(r,e){if(r){if(r[P_]!==I_)try{FP(r,P_,I_)}catch{r[P_]=I_}if(Wee(r,e,!0),SD[e]){for(var t in Od)if(r[t]!==Od[t])try{FP(r,t,Od[t])}catch{r[t]=Od[t]}}}};for(var A_ in SD)wD(UP[A_]&&UP[A_].prototype,A_);wD(qee,"DOMTokenList");var Hee=Br,Gee=Tr,jP=xl,Rg=function(r,e,t){var n,i;return jP&&Hee(n=e.constructor)&&n!==t&&Gee(i=n.prototype)&&i!==t.prototype&&jP(r,i),r},zee=Wt,Kee=zee(1.1.valueOf),Jee=`
|
|
103
103
|
\v\f\r \u2028\u2029\uFEFF`,Yee=Wt,Xee=Xs,Qee=$n,US=Jee,BP=Yee("".replace),Zee=RegExp("^["+US+"]+"),ete=RegExp("(^|[^"+US+"])["+US+"]+$"),tte=function(r){return function(e){var t=Qee(Xee(e));return r&1&&(t=BP(t,Zee,"")),r&2&&(t=BP(t,ete,"$1")),t}},rte={trim:tte(3)},nte=Gt,TD=sx,ite=jr,CD=Qt,ED=i0,kD=Wt,ste=fg,qP=Yr,ate=Rg,ote=lo,ute=Il,RD=Hw,cte=Ft,lte=Qu.f,dte=co.f,fte=Ci.f,hte=Kee,pte=rte.trim,Pg="Number",el=CD[Pg];ED[Pg];var I0=el.prototype,vte=CD.TypeError,gte=kD("".slice),dp=kD("".charCodeAt),mte=function(r){var e=RD(r,"number");return typeof e=="bigint"?e:yte(e)},yte=function(r){var e=RD(r,"number"),t,n,i,s,a,c,o,l;if(ute(e))throw new vte("Cannot convert a Symbol value to a number");if(typeof e=="string"&&e.length>2){if(e=pte(e),t=dp(e,0),t===43||t===45){if(n=dp(e,2),n===88||n===120)return NaN}else if(t===48){switch(dp(e,1)){case 66:case 98:i=2,s=49;break;case 79:case 111:i=8,s=55;break;default:return+e}for(a=gte(e,2),c=a.length,o=0;o<c;o++)if(l=dp(a,o),l<48||l>s)return NaN;return parseInt(a,i)}}return+e},A0=ste(Pg,!el(" 0o1")||!el("0b1")||el("+0x1")),_te=function(r){return ote(I0,r)&&cte(function(){hte(r)})},Ig=function(e){var t=arguments.length<1?0:el(mte(e));return _te(this)?ate(Object(t),this,Ig):t};Ig.prototype=I0;A0&&!TD&&(I0.constructor=Ig);nte({global:!0,constructor:!0,wrap:!0,forced:A0},{Number:Ig});var bte=function(r,e){for(var t=ite?lte(e):"MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,EPSILON,MAX_SAFE_INTEGER,MIN_SAFE_INTEGER,isFinite,isInteger,isNaN,isSafeInteger,parseFloat,parseInt,fromString,range".split(","),n=0,i;t.length>n;n++)qP(e,i=t[n])&&!qP(r,i)&&fte(r,i,dte(e,i))};(A0||TD)&&bte(ED[Pg],el);var Ste=dn,PD=function(){var r=Ste(this),e="";return r.hasIndices&&(e+="d"),r.global&&(e+="g"),r.ignoreCase&&(e+="i"),r.multiline&&(e+="m"),r.dotAll&&(e+="s"),r.unicode&&(e+="u"),r.unicodeSets&&(e+="v"),r.sticky&&(e+="y"),e},O0=Ft,wte=Qt,$0=wte.RegExp,x0=O0(function(){var r=$0("a","y");return r.lastIndex=2,r.exec("abcd")!==null});x0||O0(function(){return!$0("a","y").sticky});var Tte=x0||O0(function(){var r=$0("^r","gy");return r.lastIndex=2,r.exec("str")!==null}),ID={BROKEN_CARET:Tte,UNSUPPORTED_Y:x0},Cte=Ft,Ete=Qt,kte=Ete.RegExp,Rte=Cte(function(){var r=kte(".","s");return!(r.dotAll&&r.test(`
|
|
104
104
|
`)&&r.flags==="s")}),Pte=Ft,Ite=Qt,Ate=Ite.RegExp,Ote=Pte(function(){var r=Ate("(?<a>b)","g");return r.exec("b").groups.a!=="b"||"b".replace(r,"$<a>c")!=="bc"}),zc=$r,Ag=Wt,$te=$n,xte=PD,Mte=ID,Dte=Al,Nte=tu,Lte=Fi.get,Ute=Rte,Fte=Ote,jte=Dte("native-string-replace",String.prototype.replace),yv=RegExp.prototype.exec,FS=yv,Bte=Ag("".charAt),qte=Ag("".indexOf),Wte=Ag("".replace),O_=Ag("".slice),jS=function(){var r=/a/,e=/b*/g;return zc(yv,r,"a"),zc(yv,e,"a"),r.lastIndex!==0||e.lastIndex!==0}(),AD=Mte.BROKEN_CARET,BS=/()??/.exec("")[1]!==void 0,Vte=jS||BS||AD||Ute||Fte;Vte&&(FS=function(e){var t=this,n=Lte(t),i=$te(e),s=n.raw,a,c,o,l,d,h,v;if(s)return s.lastIndex=t.lastIndex,a=zc(FS,s,i),t.lastIndex=s.lastIndex,a;var y=n.groups,w=AD&&t.sticky,k=zc(xte,t),I=t.source,A=0,j=i;if(w&&(k=Wte(k,"y",""),qte(k,"g")===-1&&(k+="g"),j=O_(i,t.lastIndex),t.lastIndex>0&&(!t.multiline||t.multiline&&Bte(i,t.lastIndex-1)!==`
|
|
@@ -551,7 +551,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
551
551
|
`):t=e;try{yield this._writer.write(t)}catch{this.close()}})}}const gme=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,-1,-1,-1,-1,36,-1,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,-1,-1,-1,63,-1];class mme{constructor(e){this.a=e,this.pos=0}haveBytes(){return this.pos<this.a.length}getByte(){const e=this.a[this.pos];if(this.pos++,this.pos>this.a.length)throw new RangeError("out of bounds");return e}getChar(){return String.fromCharCode(this.getByte())}getInt(){let e=0,t;for(;this.haveBytes()&&(t=gme[127&this.getByte()])>=0;)e=(e<<6)+t;return this.pos--,e>>>0}}class yme{constructor(){this.a=[]}toByteArray(e){return Array.isArray(e)?this.a:new Uint8Array(this.a)}putArray(e,t,n){for(let i=t;i<n;i++)this.a.push(e[i])}}function _me(r){let e=0,t=0,n=0,i=0,s=0,a=r.length;for(;a>=16;)e=e+r[s+0]|0,t=t+r[s+1]|0,n=n+r[s+2]|0,i=i+r[s+3]|0,e=e+r[s+4]|0,t=t+r[s+5]|0,n=n+r[s+6]|0,i=i+r[s+7]|0,e=e+r[s+8]|0,t=t+r[s+9]|0,n=n+r[s+10]|0,i=i+r[s+11]|0,e=e+r[s+12]|0,t=t+r[s+13]|0,n=n+r[s+14]|0,i=i+r[s+15]|0,s+=16,a-=16;for(;a>=4;)e=e+r[s+0]|0,t=t+r[s+1]|0,n=n+r[s+2]|0,i=i+r[s+3]|0,s+=4,a-=4;switch(i=((i+(n<<8)|0)+(t<<16)|0)+(e<<24)|0,a){case 3:i=i+(r[s+2]<<8)|0;case 2:i=i+(r[s+1]<<16)|0;case 1:i=i+(r[s+0]<<24)|0}return i>>>0}function bme(r,e){let t=0;const n=new mme(e),i=r.length,s=e.length,a=n.getInt();if(n.getChar()!==`
|
|
552
552
|
`)throw new Error("size integer not terminated by '\\n'");const c=new yme;for(;n.haveBytes();){const o=n.getInt();let l;switch(n.getChar()){case"@":if(l=n.getInt(),n.haveBytes()&&n.getChar()!==",")throw new Error("copy command not terminated by ','");if(t+=o,t>a)throw new Error("copy exceeds output file size");if(l+o>i)throw new Error("copy extends past end of input");c.putArray(r,l,l+o);break;case":":if(t+=o,t>a)throw new Error("insert command gives an output larger than predicted");if(o>s)throw new Error("insert count exceeds size of delta");c.putArray(n.a,n.pos,n.pos+o),n.pos+=o;break;case";":{const d=c.toByteArray(r);if(o!==_me(d))throw new Error("bad checksum");if(t!==a)throw new Error("generated size does not match predicted size");return d}default:throw new Error("unknown delta operator")}}throw new Error("unterminated delta")}class OA{name(){return"json"}encodeCommands(e){return e.map(t=>JSON.stringify(t)).join(`
|
|
553
553
|
`)}decodeReplies(e){return e.trim().split(`
|
|
554
|
-
`).map(t=>JSON.parse(t))}applyDeltaIfNeeded(e,t){let n,i,s;if(e.delta){s=!0;const a=new TextEncoder().encode(e.data),c=bme(t,a);n=JSON.parse(new TextDecoder().decode(c)),i=c}else s=!1,n=JSON.parse(e.data),i=new TextEncoder().encode(e.data);return{newData:n,newPrevValue:i,isDelta:s,wireBytes:e.data.length,fullBytes:i.length}}}const Sme={headers:{},token:"",getToken:null,data:null,getData:null,debug:!1,name:"js",version:"",fetch:null,readableStream:null,websocket:null,eventsource:null,sockjs:null,sockjsOptions:{},emulationEndpoint:"/emulation",minReconnectDelay:500,maxReconnectDelay:2e4,timeout:5e3,maxServerPingDelay:1e4,networkEventTarget:null};class fa extends Error{constructor(e){super(e),this.name=this.constructor.name}}class om extends $2{constructor(e,t){super(),this._reconnectTimeout=null,this._refreshTimeout=null,this._serverPingTimeout=null,this.state=Sn.Disconnected,this._transportIsOpen=!1,this._endpoint=e,this._emulation=!1,this._transports=[],this._currentTransportIndex=0,this._triedAllTransports=!1,this._transportWasOpen=!1,this._transport=null,this._transportId=0,this._deviceWentOffline=!1,this._transportClosed=!0,this._codec=new OA,this._reconnecting=!1,this._reconnectTimeout=null,this._reconnectAttempts=0,this._client=null,this._session="",this._node="",this._subs={},this._serverSubs={},this._commandId=0,this._commands=[],this._batching=!1,this._refreshRequired=!1,this._refreshTimeout=null,this._callbacks={},this._token="",this._data=null,this._dispatchPromise=Promise.resolve(),this._serverPing=0,this._serverPingTimeout=null,this._sendPong=!1,this._promises={},this._promiseId=0,this._debugEnabled=!1,this._networkEventsSet=!1,this._config=Object.assign(Object.assign({},Sme),t),this._configure(),this._debugEnabled?(this.on("state",n=>{this._debug("client state",n.oldState,"->",n.newState)}),this.on("error",n=>{this._debug("client error",n)})):this.on("error",function(){Function.prototype()})}newSubscription(e,t){if(this.getSubscription(e)!==null)throw new Error("Subscription to the channel "+e+" already exists");const n=new lme(this,e,t);return this._subs[e]=n,n}newMapSubscription(e,t){if(this.getSubscription(e)!==null)throw new Error("Subscription to the channel "+e+" already exists");const n=new Eb(this,e,{token:t==null?void 0:t.token,getToken:t==null?void 0:t.getToken,data:t==null?void 0:t.data,minResubscribeDelay:t==null?void 0:t.minResubscribeDelay,maxResubscribeDelay:t==null?void 0:t.maxResubscribeDelay,delta:t==null?void 0:t.delta,tagsFilter:t==null?void 0:t.tagsFilter,map:!0,mapPageSize:t==null?void 0:t.pageSize,mapUnrecoverableStrategy:t==null?void 0:t.unrecoverableStrategy});return this._subs[e]=n,n}newMapClientsSubscription(e,t){if(this.getSubscription(e)!==null)throw new Error("Subscription to the channel "+e+" already exists");const n=new Eb(this,e,{token:t==null?void 0:t.token,getToken:t==null?void 0:t.getToken,data:t==null?void 0:t.data,minResubscribeDelay:t==null?void 0:t.minResubscribeDelay,maxResubscribeDelay:t==null?void 0:t.maxResubscribeDelay,delta:t==null?void 0:t.delta,tagsFilter:t==null?void 0:t.tagsFilter,map:!0,mapPresenceType:2,mapPageSize:t==null?void 0:t.pageSize,mapUnrecoverableStrategy:t==null?void 0:t.unrecoverableStrategy});return this._subs[e]=n,n}newMapUsersSubscription(e,t){if(this.getSubscription(e)!==null)throw new Error("Subscription to the channel "+e+" already exists");const n=new Eb(this,e,{token:t==null?void 0:t.token,getToken:t==null?void 0:t.getToken,data:t==null?void 0:t.data,minResubscribeDelay:t==null?void 0:t.minResubscribeDelay,maxResubscribeDelay:t==null?void 0:t.maxResubscribeDelay,delta:t==null?void 0:t.delta,tagsFilter:t==null?void 0:t.tagsFilter,map:!0,mapPresenceType:3,mapPageSize:t==null?void 0:t.pageSize,mapUnrecoverableStrategy:t==null?void 0:t.unrecoverableStrategy});return this._subs[e]=n,n}newSharedPollSubscription(e,t){if(this.getSubscription(e)!==null)throw new Error("Subscription to the channel "+e+" already exists");const n=new dme(this,e,{token:t==null?void 0:t.token,getToken:t==null?void 0:t.getToken,data:t==null?void 0:t.data,minResubscribeDelay:t==null?void 0:t.minResubscribeDelay,maxResubscribeDelay:t==null?void 0:t.maxResubscribeDelay,delta:t==null?void 0:t.delta,sharedPoll:!0,sharedPollGetSignature:t==null?void 0:t.getSignature});return this._subs[e]=n,n}getSubscription(e){return this._getSub(e)}getMapSubscription(e){return this._getSub(e)}getSharedPollSubscription(e){return this._getSub(e)}removeSubscription(e){e&&(e.state!==ii.Unsubscribed&&e.unsubscribe(),this._removeSubscription(e))}removeMapSubscription(e){this.removeSubscription(e)}removeSharedPollSubscription(e){this.removeSubscription(e)}subscriptions(){return this._subs}mapSubscriptions(){const e={};for(const[t,n]of Object.entries(this._subs))n.type==="map"&&(e[t]=n);return e}sharedPollSubscriptions(){const e={};for(const[t,n]of Object.entries(this._subs))n.type==="shared_poll"&&(e[t]=n);return e}ready(e){return wn(this,void 0,void 0,function*(){switch(this.state){case Sn.Disconnected:throw{code:br.clientDisconnected,message:"client disconnected"};case Sn.Connected:return;default:return new Promise((t,n)=>{const i={resolve:t,reject:n};e&&(i.timeout=setTimeout(()=>{n({code:br.timeout,message:"timeout"})},e)),this._promises[this._nextPromiseId()]=i})}})}connect(){if(this._isConnected()){this._debug("connect called when already connected");return}if(this._isConnecting()){this._debug("connect called when already connecting");return}this._debug("connect called"),this._reconnectAttempts=0,this._startConnecting()}disconnect(){this._disconnect(Jc.disconnectCalled,"disconnect called",!1)}setToken(e){this._token=e}setData(e){this._data=e}setHeaders(e){this._config.headers=e}send(e){return wn(this,void 0,void 0,function*(){const t={send:{data:e}};if(yield this._methodCall(),!this._transportSendCommands([t]))throw this._createErrorObject(br.transportWriteError,"transport write error")})}rpc(e,t){return wn(this,void 0,void 0,function*(){const n={rpc:{method:e,data:t}};return yield this._methodCall(),{data:(yield this._callPromise(n,s=>s.rpc)).data}})}publish(e,t){return wn(this,void 0,void 0,function*(){const n={publish:{channel:e,data:t}};return yield this._methodCall(),yield this._callPromise(n,()=>({})),{}})}mapPublish(e,t,n){return wn(this,void 0,void 0,function*(){const i={publish:{channel:e,type:1,key:t,data:n}};return yield this._methodCall(),yield this._callPromise(i,()=>({})),{}})}mapRemove(e,t){return wn(this,void 0,void 0,function*(){const n={publish:{channel:e,type:1,key:t,removed:!0}};return yield this._methodCall(),yield this._callPromise(n,()=>({})),{}})}history(e,t){return wn(this,void 0,void 0,function*(){const n={history:this._getHistoryRequest(e,t)};yield this._methodCall();const i=yield this._callPromise(n,a=>a.history),s=[];if(i.publications)for(let a=0;a<i.publications.length;a++)s.push(this._getPublicationContext(e,i.publications[a]));return{publications:s,epoch:i.epoch||"",offset:i.offset||0}})}presence(e){return wn(this,void 0,void 0,function*(){const t={presence:{channel:e}};yield this._methodCall();const i=(yield this._callPromise(t,s=>s.presence)).presence;for(const s in i)if(Object.prototype.hasOwnProperty.call(i,s)){const a=i[s],c=a.conn_info,o=a.chan_info;c&&(a.connInfo=c),o&&(a.chanInfo=o)}return{clients:i}})}presenceStats(e){return wn(this,void 0,void 0,function*(){const t={presence_stats:{channel:e}};yield this._methodCall();const n=yield this._callPromise(t,i=>i.presence_stats);return{numUsers:n.num_users,numClients:n.num_clients}})}startBatching(){this._batching=!0}stopBatching(){const e=this;Promise.resolve().then(function(){Promise.resolve().then(function(){e._batching=!1,e._flush()})})}_debug(...e){this._debugEnabled&&ome("debug",e)}_codecName(){return this._codec.name()}_formatOverride(){}_configure(){if(!("Promise"in globalThis))throw new Error("Promise polyfill required");if(!this._endpoint)throw new Error("endpoint configuration required");if(this._config.token!==null&&(this._token=this._config.token),this._config.data!==null&&(this._data=this._config.data),this._codec=new OA,this._formatOverride(),(this._config.debug===!0||typeof localStorage<"u"&&typeof localStorage.getItem=="function"&&localStorage.getItem("centrifuge.debug"))&&(this._debugEnabled=!0),this._debug("config",this._config),typeof this._endpoint!="string")if(Array.isArray(this._endpoint)){this._transports=this._endpoint,this._emulation=!0;for(const e in this._transports)if(this._transports.hasOwnProperty(e)){const t=this._transports[e];if(!t.endpoint||!t.transport)throw new Error("malformed transport configuration");const n=t.transport;if(["websocket","http_stream","sse","sockjs","webtransport"].indexOf(n)<0)throw new Error("unsupported transport name: "+n)}}else throw new Error("unsupported url configuration type: only string or array of objects are supported")}_setState(e){if(this.state!==e){this._reconnecting=!1;const t=this.state;return this.state=e,this.emit("state",{newState:e,oldState:t}),!0}return!1}_isDisconnected(){return this.state===Sn.Disconnected}_isConnecting(){return this.state===Sn.Connecting}_isConnected(){return this.state===Sn.Connected}_nextCommandId(){return++this._commandId}_setNetworkEvents(){if(this._networkEventsSet)return;let e=null;this._config.networkEventTarget!==null?e=this._config.networkEventTarget:typeof globalThis.addEventListener<"u"&&(e=globalThis),e&&(e.addEventListener("offline",()=>{this._debug("offline event triggered"),(this.state===Sn.Connected||this.state===Sn.Connecting)&&(this._disconnect(Za.transportClosed,"transport closed",!0),this._deviceWentOffline=!0)}),e.addEventListener("online",()=>{this._debug("online event triggered"),this.state===Sn.Connecting&&(this._deviceWentOffline&&!this._transportClosed&&(this._deviceWentOffline=!1,this._transportClosed=!0),this._clearReconnectTimeout(),this._startReconnecting())}),this._networkEventsSet=!0)}_getReconnectDelay(){const e=Mu(this._reconnectAttempts,this._config.minReconnectDelay,this._config.maxReconnectDelay);return this._reconnectAttempts+=1,e}_clearOutgoingRequests(){for(const e in this._callbacks)if(this._callbacks.hasOwnProperty(e)){const t=this._callbacks[e];clearTimeout(t.timeout);const n=t.errback;if(!n)continue;n({error:this._createErrorObject(br.connectionClosed,"connection closed")})}this._callbacks={}}_clearConnectedState(){this._client=null,this._clearServerPingTimeout(),this._clearRefreshTimeout();for(const e in this._subs){if(!this._subs.hasOwnProperty(e))continue;const t=this._subs[e];t.state===ii.Subscribed&&t._setSubscribing(xv.transportClosed,"transport closed")}for(const e in this._serverSubs)this._serverSubs.hasOwnProperty(e)&&this.emit("subscribing",{channel:e})}_handleWriteError(e){for(const t of e){const n=t.id;if(!(n in this._callbacks))continue;const i=this._callbacks[n];clearTimeout(this._callbacks[n].timeout),delete this._callbacks[n];const s=i.errback;s({error:this._createErrorObject(br.transportWriteError,"transport write error")})}}_transportSendCommands(e){if(!e.length)return!0;if(!this._transport)return!1;try{this._transport.send(this._codec.encodeCommands(e),this._session,this._node)}catch(t){return this._debug("error writing commands",t),this._handleWriteError(e),!1}return!0}_initializeTransport(){let e;this._config.websocket!==null?e=this._config.websocket:typeof globalThis.WebSocket!="function"&&typeof globalThis.WebSocket!="object"||(e=globalThis.WebSocket);let t=null;this._config.sockjs!==null?t=this._config.sockjs:typeof globalThis.SockJS<"u"&&(t=globalThis.SockJS);let n=null;this._config.eventsource!==null?n=this._config.eventsource:typeof globalThis.EventSource<"u"&&(n=globalThis.EventSource);let i=null;this._config.fetch!==null?i=this._config.fetch:typeof globalThis.fetch<"u"&&(i=globalThis.fetch);let s=null;if(this._config.readableStream!==null?s=this._config.readableStream:typeof globalThis.ReadableStream<"u"&&(s=globalThis.ReadableStream),this._emulation){this._currentTransportIndex>=this._transports.length&&(this._triedAllTransports=!0,this._currentTransportIndex=0);let y=0;for(;;){if(y>=this._transports.length)throw new Error("no supported transport found");const w=this._transports[this._currentTransportIndex],k=w.transport,I=w.endpoint;if(k==="websocket"){if(this._debug("trying websocket transport"),this._transport=new AA(I,{websocket:e}),!this._transport.supported()){this._debug("websocket transport not available"),this._currentTransportIndex++,y++;continue}}else if(k==="webtransport"){if(this._debug("trying webtransport transport"),this._transport=new vme(I,{webtransport:globalThis.WebTransport,decoder:this._codec,encoder:this._codec}),!this._transport.supported()){this._debug("webtransport transport not available"),this._currentTransportIndex++,y++;continue}}else if(k==="http_stream"){if(this._debug("trying http_stream transport"),this._transport=new hme(I,{fetch:i,readableStream:s,emulationEndpoint:this._config.emulationEndpoint,decoder:this._codec,encoder:this._codec}),!this._transport.supported()){this._debug("http_stream transport not available"),this._currentTransportIndex++,y++;continue}}else if(k==="sse"){if(this._debug("trying sse transport"),this._transport=new pme(I,{eventsource:n,fetch:i,emulationEndpoint:this._config.emulationEndpoint}),!this._transport.supported()){this._debug("sse transport not available"),this._currentTransportIndex++,y++;continue}}else if(k==="sockjs"){if(this._debug("trying sockjs"),this._transport=new fme(I,{sockjs:t,sockjsOptions:this._config.sockjsOptions}),!this._transport.supported()){this._debug("sockjs transport not available"),this._currentTransportIndex++,y++;continue}}else throw new Error("unknown transport "+k);break}}else{if(ame(this._endpoint,"http"))throw new Error("Provide explicit transport endpoints configuration in case of using HTTP (i.e. using array of TransportEndpoint instead of a single string), or use ws(s):// scheme in an endpoint if you aimed using WebSocket transport");if(this._debug("client will use websocket"),this._transport=new AA(this._endpoint,{websocket:e}),!this._transport.supported())throw new Error("WebSocket constructor not found, make sure it is available globally or passed as a dependency in Centrifuge options")}const a=this,c=this._transport,o=this._nextTransportId();a._debug("id of transport",o);let l=!1;const d=[];if(this._transport.emulation()){const y=a._sendConnect(!0);d.push(y)}this._setNetworkEvents();const h=this._codec.encodeCommands(d);this._transportClosed=!1;let v;v=setTimeout(function(){c.close()},this._config.timeout),this._transport.initialize(this._codecName(),{onOpen:function(){if(v&&(clearTimeout(v),v=null),a._transportId!=o){a._debug("open callback from non-actual transport"),c.close();return}l=!0,a._debug(c.subName(),"transport open"),!c.emulation()&&(a._transportIsOpen=!0,a._transportWasOpen=!0,a.startBatching(),a._sendConnect(!1),a._sendSubscribeCommands(),a.stopBatching(),a.emit("__centrifuge_debug:connect_frame_sent",{}))},onError:function(y){if(a._transportId!=o){a._debug("error callback from non-actual transport");return}a._debug("transport level error",y)},onClose:function(y){if(v&&(clearTimeout(v),v=null),a._transportId!=o){a._debug("close callback from non-actual transport");return}a._debug(c.subName(),"transport closed"),a._transportClosed=!0,a._transportIsOpen=!1;let w="connection closed",k=!0,I=0;if(y&&"code"in y&&y.code&&(I=y.code),y&&y.reason)try{const A=JSON.parse(y.reason);w=A.reason,k=A.reconnect}catch{w=y.reason,(I>=3500&&I<4e3||I>=4500&&I<5e3)&&(k=!1)}I<3e3?(I===1009?(I=Jc.messageSizeLimit,w="message size limit exceeded",k=!1):(I=Za.transportClosed,w="transport closed"),a._emulation&&!a._transportWasOpen&&(a._currentTransportIndex++,a._currentTransportIndex>=a._transports.length&&(a._triedAllTransports=!0,a._currentTransportIndex=0))):a._transportWasOpen=!0,a._isConnecting()&&!l&&a.emit("error",{type:"transport",error:{code:br.transportClosed,message:"transport closed"},transport:c.name()}),a._reconnecting=!1,a._disconnect(I,w,k)},onMessage:function(y){a._dataReceived(y)}},h),a.emit("__centrifuge_debug:transport_initialized",{})}_sendConnect(e){const t=this._constructConnectCommand(),n=this;return this._call(t,e).then(i=>{const s=i.reply.connect;n._connectResponse(s),i.next&&i.next()},i=>{n._connectError(i.error),i.next&&i.next()}),t}_startReconnecting(){if(this._debug("start reconnecting"),!this._isConnecting()){this._debug("stop reconnecting: client not in connecting state");return}if(this._reconnecting){this._debug("reconnect already in progress, return from reconnect routine");return}if(this._transportClosed===!1){this._debug("waiting for transport close");return}this._reconnecting=!0;const e=this._token==="";if(!(this._refreshRequired||e&&this._config.getToken!==null)){this._config.getData?this._config.getData().then(i=>{this._isConnecting()&&(this._data=i,this._initializeTransport())}).catch(i=>this._handleGetDataError(i)):this._initializeTransport();return}const n=this;this._getToken().then(function(i){if(n._isConnecting()){if(i==null||i==null){n._failUnauthorized();return}n._token=i,n._debug("connection token refreshed"),n._config.getData?n._config.getData().then(function(s){n._isConnecting()&&(n._data=s,n._initializeTransport())}).catch(s=>n._handleGetDataError(s)):n._initializeTransport()}}).catch(function(i){if(!n._isConnecting())return;if(i instanceof fa){n._failUnauthorized();return}n.emit("error",{type:"connectToken",error:{code:br.clientConnectToken,message:i!==void 0?i.toString():""}});const s=n._getReconnectDelay();n._debug("error on getting connection token, reconnect after "+s+" milliseconds",i),n._reconnecting=!1,n._reconnectTimeout=setTimeout(()=>{n._startReconnecting()},s)})}_handleGetDataError(e){if(e instanceof fa){this._failUnauthorized();return}this.emit("error",{type:"connectData",error:{code:br.badConfiguration,message:(e==null?void 0:e.toString())||""}});const t=this._getReconnectDelay();this._debug("error on getting connect data, reconnect after "+t+" milliseconds",e),this._reconnecting=!1,this._reconnectTimeout=setTimeout(()=>{this._startReconnecting()},t)}_connectError(e){this.state===Sn.Connecting&&(e.code===109&&(this._refreshRequired=!0),e.code<100||e.temporary===!0||e.code===109?(this.emit("error",{type:"connect",error:e}),this._debug("closing transport due to connect error"),this._disconnect(e.code,e.message,!0)):this._disconnect(e.code,e.message,!1))}_scheduleReconnect(){if(!this._isConnecting())return;let e=!1;this._emulation&&!this._transportWasOpen&&!this._triedAllTransports&&(e=!0);let t=this._getReconnectDelay();e&&(t=0),this._debug("reconnect after "+t+" milliseconds"),this._clearReconnectTimeout(),this._reconnectTimeout=setTimeout(()=>{this._startReconnecting()},t)}_constructConnectCommand(){const e={};this._token&&(e.token=this._token),this._data&&(e.data=this._data),this._config.name&&(e.name=this._config.name),this._config.version&&(e.version=this._config.version),Object.keys(this._config.headers).length>0&&(e.headers=this._config.headers);const t={};let n=!1;for(const i in this._serverSubs)if(this._serverSubs.hasOwnProperty(i)&&this._serverSubs[i].recoverable){n=!0;const s={recover:!0};this._serverSubs[i].offset&&(s.offset=this._serverSubs[i].offset),this._serverSubs[i].epoch&&(s.epoch=this._serverSubs[i].epoch),t[i]=s}return n&&(e.subs=t),{connect:e}}_getHistoryRequest(e,t){const n={channel:e};return t!==void 0&&(t.since&&(n.since={offset:t.since.offset},t.since.epoch&&(n.since.epoch=t.since.epoch)),t.limit!==void 0&&(n.limit=t.limit),t.reverse===!0&&(n.reverse=!0)),n}_methodCall(){return this._isConnected()?Promise.resolve():new Promise((e,t)=>{const n=setTimeout(function(){t({code:br.timeout,message:"timeout"})},this._config.timeout);this._promises[this._nextPromiseId()]={timeout:n,resolve:e,reject:t}})}_callPromise(e,t){return new Promise((n,i)=>{this._call(e,!1).then(s=>{var a;const c=t(s.reply);n(c),(a=s.next)===null||a===void 0||a.call(s)},s=>{var a;i(s.error),(a=s.next)===null||a===void 0||a.call(s)})})}_dataReceived(e){this._serverPing>0&&this._waitServerPing();const t=this._codec.decodeReplies(e);this._dispatchPromise=this._dispatchPromise.then(()=>{let n;this._dispatchPromise=new Promise(i=>{n=i}),this._dispatchSynchronized(t,n)})}_dispatchSynchronized(e,t){let n=Promise.resolve();for(const i in e)e.hasOwnProperty(i)&&(n=n.then(()=>this._dispatchReply(e[i])));n=n.then(()=>{t()})}_dispatchReply(e){let t;const n=new Promise(s=>{t=s});if(e==null)return this._debug("dispatch: got undefined or null reply"),t(),n;const i=e.id;return i&&i>0?this._handleReply(e,t):e.push?this._handlePush(e.push,t):this._handleServerPing(t),n}_call(e,t){return new Promise((n,i)=>{e.id=this._nextCommandId(),this._registerCall(e.id,n,i),t||this._addCommand(e)})}_startConnecting(){this._debug("start connecting"),this._setState(Sn.Connecting)&&this.emit("connecting",{code:Za.connectCalled,reason:"connect called"}),this._client=null,this._startReconnecting()}_disconnect(e,t,n){if(e===Jc.stateInvalidated){this._token="",this._refreshRequired=!0;for(const c in this._subs)this._subs.hasOwnProperty(c)&&this._subs[c]._invalidateState()}if(this._isDisconnected())return;this._transportIsOpen=!1;const i=this.state;this._reconnecting=!1;const s={code:e,reason:t};let a=!1;if(n?a=this._setState(Sn.Connecting):(a=this._setState(Sn.Disconnected),this._rejectPromises({code:br.clientDisconnected,message:"disconnected"})),this._clearOutgoingRequests(),i===Sn.Connecting&&this._clearReconnectTimeout(),i===Sn.Connected&&this._clearConnectedState(),a&&(this._isConnecting()?this.emit("connecting",s):this.emit("disconnected",s)),this._transport){this._debug("closing existing transport");const c=this._transport;this._transport=null,c.close(),this._transportClosed=!0,this._nextTransportId()}else this._debug("no transport to close");this._scheduleReconnect()}_failUnauthorized(){this._disconnect(Jc.unauthorized,"unauthorized",!1)}_getToken(){return this._debug("get connection token"),this._config.getToken?this._config.getToken({}):(this.emit("error",{type:"configuration",error:{code:br.badConfiguration,message:"token expired but no getToken function set in the configuration"}}),Promise.reject(new fa("")))}_refresh(){const e=this._client,t=this;this._getToken().then(function(n){if(e!==t._client)return;if(!n){t._failUnauthorized();return}if(t._token=n,t._debug("connection token refreshed"),!t._isConnected())return;const i={refresh:{token:t._token}};t._call(i,!1).then(s=>{const a=s.reply.refresh;t._refreshResponse(a),s.next&&s.next()},s=>{t._refreshError(s.error),s.next&&s.next()})}).catch(function(n){if(t._isConnected()){if(n instanceof fa){t._failUnauthorized();return}t.emit("error",{type:"refreshToken",error:{code:br.clientRefreshToken,message:n!==void 0?n.toString():""}}),t._refreshTimeout=setTimeout(()=>t._refresh(),t._getRefreshRetryDelay())}})}_refreshError(e){e.code<100||e.temporary===!0?(this.emit("error",{type:"refresh",error:e}),this._refreshTimeout=setTimeout(()=>this._refresh(),this._getRefreshRetryDelay())):this._disconnect(e.code,e.message,!1)}_getRefreshRetryDelay(){return Mu(0,5e3,1e4)}_refreshResponse(e){this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null),e.expires&&(this._client=e.client,this._refreshTimeout=setTimeout(()=>this._refresh(),Hd(e.ttl)))}_removeSubscription(e){e!==null&&delete this._subs[e.channel]}_unsubscribe(e){if(!this._transportIsOpen)return Promise.resolve();const n={unsubscribe:{channel:e.channel}},i=this;return new Promise((a,c)=>{this._call(n,!1).then(o=>{a(),o.next&&o.next()},o=>{a(),o.next&&o.next(),i._disconnect(Za.unsubscribeError,"unsubscribe error",!0)})})}_getSub(e,t){if(t&&t>0){for(const i in this._subs)if(this._subs.hasOwnProperty(i)){const s=this._subs[i];if(s._id===t)return s}return null}const n=this._subs[e];return n||null}_isServerSub(e){return this._serverSubs[e]!==void 0}_sendSubscribeCommands(){const e=[];for(const t in this._subs){if(!this._subs.hasOwnProperty(t))continue;const n=this._subs[t];if(n._inflight!==!0&&n.state===ii.Subscribing){const i=n._subscribe();i&&e.push(i)}}return e}_connectResponse(e){if(this._transportIsOpen=!0,this._transportWasOpen=!0,this._reconnectAttempts=0,this._refreshRequired=!1,this._isConnected())return;this._client=e.client,this._setState(Sn.Connected),this._refreshTimeout&&clearTimeout(this._refreshTimeout),e.expires&&(this._refreshTimeout=setTimeout(()=>this._refresh(),Hd(e.ttl))),this._session=e.session,this._node=e.node,this.startBatching(),this._sendSubscribeCommands(),this.stopBatching();const t={client:e.client,transport:this._transport.subName()};e.data&&(t.data=e.data),this.emit("connected",t),this._resolvePromises(),this._processServerSubs(e.subs||{}),e.ping&&e.ping>0?(this._serverPing=e.ping*1e3,this._sendPong=e.pong===!0,this._waitServerPing()):this._serverPing=0}_processServerSubs(e){for(const t in e){if(!e.hasOwnProperty(t))continue;const n=e[t];this._serverSubs[t]={offset:n.offset,epoch:n.epoch,recoverable:n.recoverable||!1};const i=this._getSubscribeContext(t,n);this.emit("subscribed",i)}for(const t in e){if(!e.hasOwnProperty(t))continue;const n=e[t];if(n.recovered){const i=n.publications;if(i&&i.length>0)for(const s in i)i.hasOwnProperty(s)&&this._handlePublication(t,i[s])}}for(const t in this._serverSubs)this._serverSubs.hasOwnProperty(t)&&(e[t]||(this.emit("unsubscribed",{channel:t}),delete this._serverSubs[t]))}_clearRefreshTimeout(){this._refreshTimeout!==null&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null)}_clearReconnectTimeout(){this._reconnectTimeout!==null&&(clearTimeout(this._reconnectTimeout),this._reconnectTimeout=null)}_clearServerPingTimeout(){this._serverPingTimeout!==null&&(clearTimeout(this._serverPingTimeout),this._serverPingTimeout=null)}_waitServerPing(){this._config.maxServerPingDelay!==0&&this._isConnected()&&(this._clearServerPingTimeout(),this._serverPingTimeout=setTimeout(()=>{this._isConnected()&&this._disconnect(Za.noPing,"no ping",!0)},this._serverPing+this._config.maxServerPingDelay))}_getSubscribeContext(e,t){const n={channel:e,positioned:!1,recoverable:!1,wasRecovering:!1,recovered:!1,hasRecoveredPublications:!1};t.recovered&&(n.recovered=!0),t.positioned&&(n.positioned=!0),t.recoverable&&(n.recoverable=!0),t.was_recovering&&(n.wasRecovering=!0);let i="";"epoch"in t&&(i=t.epoch);let s=0;return"offset"in t&&(s=t.offset),(n.positioned||n.recoverable)&&(n.streamPosition={offset:s,epoch:i}),Array.isArray(t.publications)&&t.publications.length>0&&(n.hasRecoveredPublications=!0),t.data&&(n.data=t.data),n}_handleReply(e,t){const n=e.id;if(!(n in this._callbacks)){t();return}const i=this._callbacks[n];if(clearTimeout(this._callbacks[n].timeout),delete this._callbacks[n],cme(e)){const s=i.errback;if(!s){t();return}const a={code:e.error.code,message:e.error.message||"",temporary:e.error.temporary||!1};s({error:a,next:t})}else{const s=i.callback;if(!s)return;s({reply:e,next:t})}}_handleJoin(e,t,n){const i=this._getSub(e,n);if(!i){if(e&&this._isServerSub(e)){const s={channel:e,info:this._getJoinLeaveContext(t.info)};this.emit("join",s)}return}i._handleJoin(t)}_handleLeave(e,t,n){const i=this._getSub(e,n);if(!i){if(e&&this._isServerSub(e)){const s={channel:e,info:this._getJoinLeaveContext(t.info)};this.emit("leave",s)}return}i._handleLeave(t)}_handleUnsubscribe(e,t){const n=this._getSub(e,0);if(!n&&e){this._isServerSub(e)&&(delete this._serverSubs[e],this.emit("unsubscribed",{channel:e}));return}t.code<2500?n._setUnsubscribed(t.code,t.reason,!1):(t.code===tf.stateInvalidated&&n._invalidateState(),n._setSubscribing(t.code,t.reason))}_handleSubscribe(e,t){this._serverSubs[e]={offset:t.offset,epoch:t.epoch,recoverable:t.recoverable||!1},this.emit("subscribed",this._getSubscribeContext(e,t))}_handleDisconnect(e){const t=e.code;let n=!0;(t>=3500&&t<4e3||t>=4500&&t<5e3)&&(n=!1),this._disconnect(t,e.reason,n)}_getPublicationContext(e,t){const n={channel:e,data:t.data};return t.offset&&(n.offset=t.offset),t.info&&(n.info=this._getJoinLeaveContext(t.info)),t.tags&&(n.tags=t.tags),n}_getJoinLeaveContext(e){const t={client:e.client,user:e.user},n=e.conn_info;n&&(t.connInfo=n);const i=e.chan_info;return i&&(t.chanInfo=i),t}_handlePublication(e,t,n){const i=this._getSub(e,n);if(!i){if(e&&this._isServerSub(e)){const s=this._getPublicationContext(e,t);this.emit("publication",s),t.offset!==void 0&&(this._serverSubs[e].offset=t.offset)}return}i._handlePublication(t)}_handleMessage(e){this.emit("message",{data:e.data})}_handleServerPing(e){if(this._sendPong){const t={};this._transportSendCommands([t])}e()}_handlePush(e,t){const n=e.channel,i=e.id;e.pub?this._handlePublication(n,e.pub,i):e.message?this._handleMessage(e.message):e.join?this._handleJoin(n,e.join,i):e.leave?this._handleLeave(n,e.leave,i):e.unsubscribe?this._handleUnsubscribe(n,e.unsubscribe):e.subscribe?this._handleSubscribe(n,e.subscribe):e.disconnect&&this._handleDisconnect(e.disconnect),t()}_flush(){const e=this._commands.slice(0);this._commands=[],this._transportSendCommands(e)}_createErrorObject(e,t,n){const i={code:e,message:t};return n&&(i.temporary=!0),i}_registerCall(e,t,n){this._callbacks[e]={callback:t,errback:n,timeout:null},this._callbacks[e].timeout=setTimeout(()=>{delete this._callbacks[e],x2(n)&&n({error:this._createErrorObject(br.timeout,"timeout")})},this._config.timeout)}_addCommand(e){this._batching?this._commands.push(e):this._transportSendCommands([e])}_nextPromiseId(){return++this._promiseId}_nextTransportId(){return++this._transportId}_resolvePromises(){for(const e in this._promises)this._promises.hasOwnProperty(e)&&(this._promises[e].timeout&&clearTimeout(this._promises[e].timeout),this._promises[e].resolve(),delete this._promises[e])}_rejectPromises(e){for(const t in this._promises)this._promises.hasOwnProperty(t)&&(this._promises[t].timeout&&clearTimeout(this._promises[t].timeout),this._promises[t].reject(e),delete this._promises[t])}}om.SubscriptionState=ii;om.State=Sn;om.UnauthorizedError=fa;const nn=new an("ujet-chat"),wme=15e3,Tme=15e3,Cme=3e3,Eme=8e3,kme=2e3,kb=50,$A=3,xA=10;function Rme(r){return r.type===_i.USER||r.type===_i.VIRTUAL_AGENT?Fp(r.type,r.id):r.email?Fp(_i.USER,r.id):Fp(_i.VIRTUAL_AGENT,r.id)}function Pme(r){var e;if(/^wss?:\/\//.test(r))return r;if(typeof window>"u"||!((e=window.location)!=null&&e.origin))throw new Error(`Cannot resolve relative websocket URL "${r}" outside a browser context`);return new URL(r,window.location.origin).toString().replace(/^http/,"ws")}function M2(r){const[e,t]=(r.user??"").split("-"),n=r.published_at??r.timestamp;return{...r,$index:r.media_id!=null?`${r.type}-${r.media_id}`:r.message_id,$sid:r.message_id,$timestamp:typeof n=="string"?new Date(n):new Date,$userType:e||_i.SYSTEM,$userId:parseInt(t,10)||0}}function D2(r){return{...r.data,message_id:r.message_id,user:r.user,published_at:r.published_at}}function Ime(r){return M2(D2(r))}function MA(r,e){if(r instanceof Error)return r;const t=r==null?void 0:r.message;return new Error(t?`${e}: ${t}`:e)}class N2 extends Hv{constructor(){super(...arguments);be(this,"client",null);be(this,"subscription",null);be(this,"tenant",null);be(this,"lastAuthError",null);be(this,"conversationEventsRegistered",!1);be(this,"isDestroyed",!1);be(this,"terminalRetryUsed",!1);be(this,"forceTokenRefreshOnce",!1);be(this,"lastMessageId",null);be(this,"lastTypingStartSentAt",0);be(this,"typingClearTimers",new Map);be(this,"pendingHistoryBuffer",null)}async create(){const t=this.providerContext;if(!t)throw new Error("UjetProvider requires a ProviderContext");this.lastAuthError=null,this.isDestroyed=!1,this.terminalRetryUsed=!1,this.forceTokenRefreshOnce=!1;const n=new om(Pme(t.wsUrl),{getData:async()=>{const i=this.forceTokenRefreshOnce;this.forceTokenRefreshOnce=!1;try{return{token:await t.getAuthToken(i)}}catch(s){throw s instanceof Xc?(this.lastAuthError=s,new fa(s.message)):s}}});n.on("connected",i=>{var s;this.tenant=(s=i.data)==null?void 0:s.tenant,this.terminalRetryUsed=!1,nn.info("client: connected",{transport:i.transport})}),n.once("connected",()=>{n.on("disconnected",i=>this.onTerminalDisconnect(n,i))}),n.on("error",i=>{i.type==="configuration"?nn.info("client: configuration error at token expiry",{error:i.error}):nn.warn("client: transport error",{type:i.type,error:i.error})}),n.connect();try{await n.ready(wme)}catch(i){throw n.disconnect(),nn.warn("client: connection failed",{error:i}),this.lastAuthError??MA(i,"Ujet chat connection failed")}this.client=n,this.events.triggerEvent("initialized")}async join(t){if(!this.client)throw new Error("UjetProvider.join called before create()");if(!this.tenant)throw new Error("Ujet chat connect reply carried no tenant");const n=`chats:${this.tenant}:${t}`,i=this.client.getSubscription(n),s=i??this.client.newSubscription(n);this.subscription=s,i||this.registerConversationEvents(),this.pendingHistoryBuffer=[],s.subscribe();try{await s.ready(Tme)}catch(a){throw nn.warn("subscription: failed",{channel:n,error:a}),MA(a,`Ujet chat subscription failed for ${n}`)}nn.info("subscription: established",{channel:n})}onTerminalDisconnect(t,n){if(!this.isDestroyed){if(this.lastAuthError||this.terminalRetryUsed){nn.warn("client: connection ended",{code:n.code,reason:n.reason,authRejected:this.lastAuthError!=null}),this.events.triggerEvent("error",new Error("Chat connection ended"));return}this.terminalRetryUsed=!0,this.forceTokenRefreshOnce=!0,nn.info("client: terminal disconnect, reconnecting once",{code:n.code,reason:n.reason}),t.connect()}}registerConversationEvents(){this.conversationEventsRegistered||!this.subscription||(this.conversationEventsRegistered=!0,this.subscription.on("publication",({data:t,info:n})=>this.onPublication(t,n)),this.subscription.on("subscribed",t=>{t.wasRecovering&&!t.recovered&&this.backfillFromHistory()}))}onPublication(t,n){switch(t==null?void 0:t.type){case ln.TYPING:this.handleTypingPublication(t,n);return;case ln.PREVIEW:return;case ln.TRANSLATION_UPDATE:return;default:{if(!(t!=null&&t.message_id)){nn.warn("persistent publication without message_id",{type:t==null?void 0:t.type,user:t==null?void 0:t.user});return}if(this.pendingHistoryBuffer){this.pendingHistoryBuffer.push(t);return}this.events.triggerEvent("message",this.ingestPersistentMessage(t))}}}ingestPersistentMessage(t){var i;const n=M2(t);return nn.info("publication: message",{index:n.$index,sid:n.$sid,timestamp:n.$timestamp,userType:n.$userType}),this.lastMessageId=n.$sid,this.clearTypingIndicator(t.user),this.trackInTask(n),n.$userType!==_i.END_USER&&this.ping(),n.type===ln.NOTI&&(n.event===Gn.MEMBER_JOINED||n.event===Gn.MEMBER_LEFT)&&this.events.triggerEvent(n.event,t.memberIdentity),n.type===ln.NOTI&&n.event===Gn.ESCALATION_ACCEPTED&&((i=t.to_agent)==null?void 0:i.id)!=null&&this.events.triggerEvent("memberJoined",Rme(t.to_agent)),n}drainHistoryBuffer(t){const n=this.pendingHistoryBuffer??[];return this.pendingHistoryBuffer=null,n.filter(i=>!t.has(i.message_id))}handleTypingPublication(t,n){const i=n==null?void 0:n.user;!i||i.startsWith(_i.END_USER)||(t.action==="start"?(this.events.triggerEvent("typingStarted",i),this.armTypingClear(i,Eme)):t.action==="stop"&&this.armTypingClear(i,kme))}armTypingClear(t,n){clearTimeout(this.typingClearTimers.get(t)),this.typingClearTimers.set(t,setTimeout(()=>{this.typingClearTimers.delete(t),this.events.triggerEvent("typingEnded",t)},n))}clearTypingIndicator(t){const n=this.typingClearTimers.get(t);n!=null&&(clearTimeout(n),this.typingClearTimers.delete(t),this.events.triggerEvent("typingEnded",t))}backfillFromHistory(){const t=this.providerContext;!t||this.pendingHistoryBuffer||(this.pendingHistoryBuffer=[],this.runBackfill(t).catch(n=>{nn.warn("backfill: failed",{error:n})}))}async runBackfill(t){var o;const n=this.subscription,i=this.lastMessageId,s=[],a=new Set;try{let l=null;for(let d=0;;d++){if(d>=xA){nn.warn("backfill: page cap reached, proceeding with the collected range",{cap:xA,stopPoint:i});break}const h=await this.fetchHistoryPage(t,l==null?{limit:kb}:{limit:kb,before:l});if(this.subscription!==n)return;for(const y of h.messages)a.add(y.message_id),!(i!=null&&y.message_id<=i)&&((o=y.data)==null?void 0:o.type)!==ln.TRANSLATION_UPDATE&&s.push(D2(y));if(i==null)break;const v=h.messages[h.messages.length-1];if(v==null||v.message_id<=i||!h.has_more||h.next_cursor==null)break;l=h.next_cursor}}catch(l){if(nn.warn("backfill: fetch failed, flushing the window buffer live",{error:l}),this.subscription===n)for(const d of this.drainHistoryBuffer(new Set))this.events.triggerEvent("message",this.ingestPersistentMessage(d));return}const c=this.drainHistoryBuffer(a);nn.info("backfill: emitting the missed range",{collected:s.length,flushed:c.length,stopPoint:i}),s.reverse();for(const l of[...s,...c])this.events.triggerEvent("message",this.ingestPersistentMessage(l))}async destroy(){var t;this.isDestroyed=!0,this.cleanupAudio(),this.subscription&&(this.subscription.unsubscribe(),(t=this.client)==null||t.removeSubscription(this.subscription),this.subscription=null),this.pendingHistoryBuffer=null,this.lastTypingStartSentAt=0;for(const n of this.typingClearTimers.values())clearTimeout(n);this.typingClearTimers.clear(),this.client&&(this.client.disconnect(),this.client=null),this.tenant=null,this.lastMessageId=null,this.lastAuthError=null,this.conversationEventsRegistered=!1}async sendMessage(t){if(!this.subscription)return nn.warn("publish: no active subscription",{type:t.type}),"";try{await this.subscription.publish({...t})}catch(n){return nn.warn("publish: message failed",{type:t.type,error:n}),""}return t.media_id!=null?`${t.type}-${t.media_id}`:""}async preview(t){if(!this.subscription){nn.warn("publish: no active subscription",{type:ln.PREVIEW});return}try{await this.subscription.publish({type:ln.PREVIEW,text:t??""})}catch(n){nn.warn("publish: preview failed",{error:n})}}startTyping(){var n;const t=Date.now();t-this.lastTypingStartSentAt<Cme||(this.lastTypingStartSentAt=t,(n=this.subscription)==null||n.publish({type:ln.TYPING,action:"start"}).catch(i=>nn.warn("publish: typing start failed",{error:i})))}stopTyping(){var t;this.lastTypingStartSentAt!==0&&(this.lastTypingStartSentAt=0,(t=this.subscription)==null||t.publish({type:ln.TYPING,action:"stop"}).catch(n=>nn.warn("publish: typing stop failed",{error:n})))}async fetchMessages(t){const n=this.providerContext;if(!n)throw new Error("UjetProvider requires a ProviderContext");let i;try{i=await this.fetchHistoryPage(n,{limit:kb})}catch(o){nn.warn("history: fetch failed, flushing the window buffer live",{error:o});for(const l of this.drainHistoryBuffer(new Set))this.events.triggerEvent("message",this.ingestPersistentMessage(l));throw o}const s=i.messages.filter(o=>{var l;return((l=o.data)==null?void 0:l.type)!==ln.TRANSLATION_UPDATE});s.length>0&&(this.lastMessageId=s[0].message_id),s.reverse();const a=s.map(o=>{const l=Ime(o);this.trackInTask(l);const d=t[l.$index];return d&&(l.file=d),l}),c=this.drainHistoryBuffer(new Set(i.messages.map(o=>o.message_id))).map(o=>this.ingestPersistentMessage(o));return[...a,...c]}async fetchHistoryPage(t,n){let i=await t.fetchHistory(n);for(let s=0;s<$A&&i.retry_after_ms!=null;s++)nn.info("history: not yet persisted, re-fetching",{attempt:s+1,retryAfterMs:i.retry_after_ms}),await sv(i.retry_after_ms),i=await t.fetchHistory(n);return i.retry_after_ms!=null&&nn.warn("history: retry cap reached, proceeding with the current page",{limit:$A,retryAfterMs:i.retry_after_ms}),i}}be(N2,"type",Wu.UJET);Gv(N2);var TT={exports:{}},al=typeof Reflect=="object"?Reflect:null,DA=al&&typeof al.apply=="function"?al.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)},rv;al&&typeof al.ownKeys=="function"?rv=al.ownKeys:Object.getOwnPropertySymbols?rv=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:rv=function(e){return Object.getOwnPropertyNames(e)};function Ame(r){console&&console.warn&&console.warn(r)}var L2=Number.isNaN||function(e){return e!==e};function Fr(){Fr.init.call(this)}TT.exports=Fr;TT.exports.once=Mme;Fr.EventEmitter=Fr;Fr.prototype._events=void 0;Fr.prototype._eventsCount=0;Fr.prototype._maxListeners=void 0;var NA=10;function um(r){if(typeof r!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof r)}Object.defineProperty(Fr,"defaultMaxListeners",{enumerable:!0,get:function(){return NA},set:function(r){if(typeof r!="number"||r<0||L2(r))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+r+".");NA=r}});Fr.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};Fr.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||L2(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function U2(r){return r._maxListeners===void 0?Fr.defaultMaxListeners:r._maxListeners}Fr.prototype.getMaxListeners=function(){return U2(this)};Fr.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var i=e==="error",s=this._events;if(s!==void 0)i=i&&s.error===void 0;else if(!i)return!1;if(i){var a;if(t.length>0&&(a=t[0]),a instanceof Error)throw a;var c=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw c.context=a,c}var o=s[e];if(o===void 0)return!1;if(typeof o=="function")DA(o,this,t);else for(var l=o.length,d=W2(o,l),n=0;n<l;++n)DA(d[n],this,t);return!0};function F2(r,e,t,n){var i,s,a;if(um(t),s=r._events,s===void 0?(s=r._events=Object.create(null),r._eventsCount=0):(s.newListener!==void 0&&(r.emit("newListener",e,t.listener?t.listener:t),s=r._events),a=s[e]),a===void 0)a=s[e]=t,++r._eventsCount;else if(typeof a=="function"?a=s[e]=n?[t,a]:[a,t]:n?a.unshift(t):a.push(t),i=U2(r),i>0&&a.length>i&&!a.warned){a.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=r,c.type=e,c.count=a.length,Ame(c)}return r}Fr.prototype.addListener=function(e,t){return F2(this,e,t,!1)};Fr.prototype.on=Fr.prototype.addListener;Fr.prototype.prependListener=function(e,t){return F2(this,e,t,!0)};function Ome(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function j2(r,e,t){var n={fired:!1,wrapFn:void 0,target:r,type:e,listener:t},i=Ome.bind(n);return i.listener=t,n.wrapFn=i,i}Fr.prototype.once=function(e,t){return um(t),this.on(e,j2(this,e,t)),this};Fr.prototype.prependOnceListener=function(e,t){return um(t),this.prependListener(e,j2(this,e,t)),this};Fr.prototype.removeListener=function(e,t){var n,i,s,a,c;if(um(t),i=this._events,i===void 0)return this;if(n=i[e],n===void 0)return this;if(n===t||n.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||t));else if(typeof n!="function"){for(s=-1,a=n.length-1;a>=0;a--)if(n[a]===t||n[a].listener===t){c=n[a].listener,s=a;break}if(s<0)return this;s===0?n.shift():$me(n,s),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,c||t)}return this};Fr.prototype.off=Fr.prototype.removeListener;Fr.prototype.removeAllListeners=function(e){var t,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var s=Object.keys(n),a;for(i=0;i<s.length;++i)a=s[i],a!=="removeListener"&&this.removeAllListeners(a);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(t=n[e],typeof t=="function")this.removeListener(e,t);else if(t!==void 0)for(i=t.length-1;i>=0;i--)this.removeListener(e,t[i]);return this};function B2(r,e,t){var n=r._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?t?[i.listener||i]:[i]:t?xme(i):W2(i,i.length)}Fr.prototype.listeners=function(e){return B2(this,e,!0)};Fr.prototype.rawListeners=function(e){return B2(this,e,!1)};Fr.listenerCount=function(r,e){return typeof r.listenerCount=="function"?r.listenerCount(e):q2.call(r,e)};Fr.prototype.listenerCount=q2;function q2(r){var e=this._events;if(e!==void 0){var t=e[r];if(typeof t=="function")return 1;if(t!==void 0)return t.length}return 0}Fr.prototype.eventNames=function(){return this._eventsCount>0?rv(this._events):[]};function W2(r,e){for(var t=new Array(e),n=0;n<e;++n)t[n]=r[n];return t}function $me(r,e){for(;e+1<r.length;e++)r[e]=r[e+1];r.pop()}function xme(r){for(var e=new Array(r.length),t=0;t<e.length;++t)e[t]=r[t].listener||r[t];return e}function Mme(r,e){return new Promise(function(t,n){function i(a){r.removeListener(e,s),n(a)}function s(){typeof r.removeListener=="function"&&r.removeListener("error",i),t([].slice.call(arguments))}V2(r,e,s,{once:!0}),e!=="error"&&Dme(r,i,{once:!0})})}function Dme(r,e,t){typeof r.on=="function"&&V2(r,"error",e,t)}function V2(r,e,t,n){if(typeof r.on=="function")n.once?r.once(e,t):r.on(e,t);else if(typeof r.addEventListener=="function")r.addEventListener(e,function i(s){n.once&&r.removeEventListener(e,i),t(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof r)}var Ss=TT.exports;class gw extends Ss.EventEmitter{constructor(e){super(),Object.defineProperties(this,{_attempts:{value:0,writable:!0},_duration:{enumerable:!1,get(){if(this._useInitialValue&&this._attempts===0)return this._min;let t=this._min*Math.pow(this._factor,this._attempts);if(this._jitter){const n=Math.random(),i=Math.floor(n*this._jitter*t);t=Math.floor(n*10)&1?t+i:t-i}return Math.min(t,this._max)|0}},_factor:{value:e.factor||2},_jitter:{value:e.jitter>0&&e.jitter<=1?e.jitter:0},_max:{value:e.max||1e4},_min:{value:e.min||100},_timeoutID:{value:null,writable:!0},_useInitialValue:{value:e.useInitialValue||!1}})}backoff(){const e=this._duration;this._timeoutID&&(clearTimeout(this._timeoutID),this._timeoutID=null),this.emit("backoff",this._attempts,e),this._timeoutID=setTimeout(()=>{this.emit("ready",this._attempts,e),this._attempts++},e)}reset(){this._attempts=0,this._timeoutID&&(clearTimeout(this._timeoutID),this._timeoutID=null)}}function yi(r,e,t,n){function i(s){return s instanceof t?s:new t(function(a){a(s)})}return new(t||(t=Promise))(function(s,a){function c(d){try{l(n.next(d))}catch(h){a(h)}}function o(d){try{l(n.throw(d))}catch(h){a(h)}}function l(d){d.done?s(d.value):i(d.value).then(c,o)}l((n=n.apply(r,e||[])).next())})}class rr extends Error{constructor(e,t){super(),Object.setPrototypeOf(this,rr.prototype);const n=typeof e=="string"?e:this.explanation,i=typeof e=="object"?e:t;this.message=`${this.name} (${this.code}): ${n}`,this.originalError=i}}var In;(function(r){class e extends rr{constructor(s,a){super(s,a),this.causes=[],this.code=20101,this.description="Invalid access token",this.explanation="Twilio was unable to validate your Access Token",this.name="AccessTokenInvalid",this.solutions=[],Object.setPrototypeOf(this,r.AccessTokenInvalid.prototype);const c=typeof s=="string"?s:this.explanation,o=typeof s=="object"?s:a;this.message=`${this.name} (${this.code}): ${c}`,this.originalError=o}}r.AccessTokenInvalid=e;class t extends rr{constructor(s,a){super(s,a),this.causes=[],this.code=20104,this.description="Access token expired or expiration date invalid",this.explanation="The Access Token provided to the Twilio API has expired, the expiration time specified in the token was invalid, or the expiration time specified was too far in the future",this.name="AccessTokenExpired",this.solutions=[],Object.setPrototypeOf(this,r.AccessTokenExpired.prototype);const c=typeof s=="string"?s:this.explanation,o=typeof s=="object"?s:a;this.message=`${this.name} (${this.code}): ${c}`,this.originalError=o}}r.AccessTokenExpired=t;class n extends rr{constructor(s,a){super(s,a),this.causes=[],this.code=20151,this.description="Authentication Failed",this.explanation="The Authentication with the provided JWT failed",this.name="AuthenticationFailed",this.solutions=[],Object.setPrototypeOf(this,r.AuthenticationFailed.prototype);const c=typeof s=="string"?s:this.explanation,o=typeof s=="object"?s:a;this.message=`${this.name} (${this.code}): ${c}`,this.originalError=o}}r.AuthenticationFailed=n})(In||(In={}));var mw;(function(r){class e extends rr{constructor(n,i){super(n,i),this.causes=["The access token has an invalid Account SID, API Key, or API Key Secret."],this.code=31202,this.description="Signature validation failed.",this.explanation="The provided access token failed signature validation.",this.name="AccessTokenSignatureValidationFailed",this.solutions=["Ensure the Account SID, API Key, and API Key Secret are valid when generating your access token."],Object.setPrototypeOf(this,r.AccessTokenSignatureValidationFailed.prototype);const s=typeof n=="string"?n:this.explanation,a=typeof n=="object"?n:i;this.message=`${this.name} (${this.code}): ${s}`,this.originalError=a}}r.AccessTokenSignatureValidationFailed=e})(mw||(mw={}));var Nu;(function(r){class e extends rr{constructor(a,c){super(a,c),this.causes=[],this.code=31400,this.description="Bad Request (HTTP/SIP)",this.explanation="The request could not be understood due to malformed syntax.",this.name="BadRequest",this.solutions=[],Object.setPrototypeOf(this,r.BadRequest.prototype);const o=typeof a=="string"?a:this.explanation,l=typeof a=="object"?a:c;this.message=`${this.name} (${this.code}): ${o}`,this.originalError=l}}r.BadRequest=e;class t extends rr{constructor(a,c){super(a,c),this.causes=["The outbound call was made to an invalid phone number.","The TwiML application sid is missing a Voice URL."],this.code=31404,this.description="Not Found (HTTP/SIP)",this.explanation="The server has not found anything matching the request.",this.name="NotFound",this.solutions=["Ensure the phone number dialed is valid.","Ensure the TwiML application is configured correctly with a Voice URL link."],Object.setPrototypeOf(this,r.NotFound.prototype);const o=typeof a=="string"?a:this.explanation,l=typeof a=="object"?a:c;this.message=`${this.name} (${this.code}): ${o}`,this.originalError=l}}r.NotFound=t;class n extends rr{constructor(a,c){super(a,c),this.causes=[],this.code=31480,this.description="Temporarily Unavailable (SIP)",this.explanation="The callee is currently unavailable.",this.name="TemporarilyUnavailable",this.solutions=[],Object.setPrototypeOf(this,r.TemporarilyUnavailable.prototype);const o=typeof a=="string"?a:this.explanation,l=typeof a=="object"?a:c;this.message=`${this.name} (${this.code}): ${o}`,this.originalError=l}}r.TemporarilyUnavailable=n;class i extends rr{constructor(a,c){super(a,c),this.causes=[],this.code=31486,this.description="Busy Here (SIP)",this.explanation="The callee is busy.",this.name="BusyHere",this.solutions=[],Object.setPrototypeOf(this,r.BusyHere.prototype);const o=typeof a=="string"?a:this.explanation,l=typeof a=="object"?a:c;this.message=`${this.name} (${this.code}): ${o}`,this.originalError=l}}r.BusyHere=i})(Nu||(Nu={}));var yw;(function(r){class e extends rr{constructor(n,i){super(n,i),this.causes=[],this.code=31603,this.description="Decline (SIP)",this.explanation="The callee does not wish to participate in the call.",this.name="Decline",this.solutions=[],Object.setPrototypeOf(this,r.Decline.prototype);const s=typeof n=="string"?n:this.explanation,a=typeof n=="object"?n:i;this.message=`${this.name} (${this.code}): ${s}`,this.originalError=a}}r.Decline=e})(yw||(yw={}));var ai;(function(r){class e extends rr{constructor(l,d){super(l,d),this.causes=[],this.code=31e3,this.description="Unknown Error",this.explanation="An unknown error has occurred. See error details for more information.",this.name="UnknownError",this.solutions=[],Object.setPrototypeOf(this,r.UnknownError.prototype);const h=typeof l=="string"?l:this.explanation,v=typeof l=="object"?l:d;this.message=`${this.name} (${this.code}): ${h}`,this.originalError=v}}r.UnknownError=e;class t extends rr{constructor(l,d){super(l,d),this.causes=[],this.code=31001,this.description="Application Not Found",this.explanation="",this.name="ApplicationNotFoundError",this.solutions=[],Object.setPrototypeOf(this,r.ApplicationNotFoundError.prototype);const h=typeof l=="string"?l:this.explanation,v=typeof l=="object"?l:d;this.message=`${this.name} (${this.code}): ${h}`,this.originalError=v}}r.ApplicationNotFoundError=t;class n extends rr{constructor(l,d){super(l,d),this.causes=[],this.code=31002,this.description="Connection Declined",this.explanation="",this.name="ConnectionDeclinedError",this.solutions=[],Object.setPrototypeOf(this,r.ConnectionDeclinedError.prototype);const h=typeof l=="string"?l:this.explanation,v=typeof l=="object"?l:d;this.message=`${this.name} (${this.code}): ${h}`,this.originalError=v}}r.ConnectionDeclinedError=n;class i extends rr{constructor(l,d){super(l,d),this.causes=[],this.code=31003,this.description="Connection Timeout",this.explanation="The server could not produce a response within a suitable amount of time.",this.name="ConnectionTimeoutError",this.solutions=[],Object.setPrototypeOf(this,r.ConnectionTimeoutError.prototype);const h=typeof l=="string"?l:this.explanation,v=typeof l=="object"?l:d;this.message=`${this.name} (${this.code}): ${h}`,this.originalError=v}}r.ConnectionTimeoutError=i;class s extends rr{constructor(l,d){super(l,d),this.causes=[],this.code=31005,this.description="Connection error",this.explanation="A connection error occurred during the call",this.name="ConnectionError",this.solutions=[],Object.setPrototypeOf(this,r.ConnectionError.prototype);const h=typeof l=="string"?l:this.explanation,v=typeof l=="object"?l:d;this.message=`${this.name} (${this.code}): ${h}`,this.originalError=v}}r.ConnectionError=s;class a extends rr{constructor(l,d){super(l,d),this.causes=["The incoming call was cancelled because it was not answered in time or it was accepted/rejected by another application instance registered with the same identity."],this.code=31008,this.description="Call cancelled",this.explanation="Unable to answer because the call has ended",this.name="CallCancelledError",this.solutions=[],Object.setPrototypeOf(this,r.CallCancelledError.prototype);const h=typeof l=="string"?l:this.explanation,v=typeof l=="object"?l:d;this.message=`${this.name} (${this.code}): ${h}`,this.originalError=v}}r.CallCancelledError=a;class c extends rr{constructor(l,d){super(l,d),this.causes=[],this.code=31009,this.description="Transport error",this.explanation="No transport available to send or receive messages",this.name="TransportError",this.solutions=[],Object.setPrototypeOf(this,r.TransportError.prototype);const h=typeof l=="string"?l:this.explanation,v=typeof l=="object"?l:d;this.message=`${this.name} (${this.code}): ${h}`,this.originalError=v}}r.TransportError=c})(ai||(ai={}));var Ja;(function(r){class e extends rr{constructor(l,d){super(l,d),this.causes=["Invalid content or MessageType passed to sendMessage method."],this.code=31100,this.description="The request had malformed syntax.",this.explanation="The request could not be understood due to malformed syntax.",this.name="MalformedRequestError",this.solutions=["Ensure content and MessageType passed to sendMessage method are valid."],Object.setPrototypeOf(this,r.MalformedRequestError.prototype);const h=typeof l=="string"?l:this.explanation,v=typeof l=="object"?l:d;this.message=`${this.name} (${this.code}): ${h}`,this.originalError=v}}r.MalformedRequestError=e;class t extends rr{constructor(l,d){super(l,d),this.causes=[],this.code=31101,this.description="Missing parameter array in request",this.explanation="",this.name="MissingParameterArrayError",this.solutions=[],Object.setPrototypeOf(this,r.MissingParameterArrayError.prototype);const h=typeof l=="string"?l:this.explanation,v=typeof l=="object"?l:d;this.message=`${this.name} (${this.code}): ${h}`,this.originalError=v}}r.MissingParameterArrayError=t;class n extends rr{constructor(l,d){super(l,d),this.causes=[],this.code=31102,this.description="Authorization token missing in request.",this.explanation="",this.name="AuthorizationTokenMissingError",this.solutions=[],Object.setPrototypeOf(this,r.AuthorizationTokenMissingError.prototype);const h=typeof l=="string"?l:this.explanation,v=typeof l=="object"?l:d;this.message=`${this.name} (${this.code}): ${h}`,this.originalError=v}}r.AuthorizationTokenMissingError=n;class i extends rr{constructor(l,d){super(l,d),this.causes=[],this.code=31103,this.description="Maximum parameter length has been exceeded.",this.explanation="Length of parameters cannot exceed MAX_PARAM_LENGTH.",this.name="MaxParameterLengthExceededError",this.solutions=[],Object.setPrototypeOf(this,r.MaxParameterLengthExceededError.prototype);const h=typeof l=="string"?l:this.explanation,v=typeof l=="object"?l:d;this.message=`${this.name} (${this.code}): ${h}`,this.originalError=v}}r.MaxParameterLengthExceededError=i;class s extends rr{constructor(l,d){super(l,d),this.causes=[],this.code=31104,this.description="Invalid bridge token",this.explanation="",this.name="InvalidBridgeTokenError",this.solutions=[],Object.setPrototypeOf(this,r.InvalidBridgeTokenError.prototype);const h=typeof l=="string"?l:this.explanation,v=typeof l=="object"?l:d;this.message=`${this.name} (${this.code}): ${h}`,this.originalError=v}}r.InvalidBridgeTokenError=s;class a extends rr{constructor(l,d){super(l,d),this.causes=["Client name contains invalid characters."],this.code=31105,this.description="Invalid client name",this.explanation="Client name should not contain control, space, delims, or unwise characters.",this.name="InvalidClientNameError",this.solutions=["Make sure that client name does not contain any of the invalid characters."],Object.setPrototypeOf(this,r.InvalidClientNameError.prototype);const h=typeof l=="string"?l:this.explanation,v=typeof l=="object"?l:d;this.message=`${this.name} (${this.code}): ${h}`,this.originalError=v}}r.InvalidClientNameError=a;class c extends rr{constructor(l,d){super(l,d),this.causes=[],this.code=31107,this.description="The reconnect parameter is invalid",this.explanation="",this.name="ReconnectParameterInvalidError",this.solutions=[],Object.setPrototypeOf(this,r.ReconnectParameterInvalidError.prototype);const h=typeof l=="string"?l:this.explanation,v=typeof l=="object"?l:d;this.message=`${this.name} (${this.code}): ${h}`,this.originalError=v}}r.ReconnectParameterInvalidError=c})(Ja||(Ja={}));(function(r){class e extends rr{constructor(h,v){super(h,v),this.causes=[],this.code=31201,this.description="Authorization error",this.explanation="The request requires user authentication. The server understood the request, but is refusing to fulfill it.",this.name="AuthorizationError",this.solutions=[],Object.setPrototypeOf(this,r.AuthorizationError.prototype);const y=typeof h=="string"?h:this.explanation,w=typeof h=="object"?h:v;this.message=`${this.name} (${this.code}): ${y}`,this.originalError=w}}r.AuthorizationError=e;class t extends rr{constructor(h,v){super(h,v),this.causes=[],this.code=31203,this.description="No valid account",this.explanation="",this.name="NoValidAccountError",this.solutions=[],Object.setPrototypeOf(this,r.NoValidAccountError.prototype);const y=typeof h=="string"?h:this.explanation,w=typeof h=="object"?h:v;this.message=`${this.name} (${this.code}): ${y}`,this.originalError=w}}r.NoValidAccountError=t;class n extends rr{constructor(h,v){super(h,v),this.causes=[],this.code=31204,this.description="Invalid JWT token",this.explanation="",this.name="InvalidJWTTokenError",this.solutions=[],Object.setPrototypeOf(this,r.InvalidJWTTokenError.prototype);const y=typeof h=="string"?h:this.explanation,w=typeof h=="object"?h:v;this.message=`${this.name} (${this.code}): ${y}`,this.originalError=w}}r.InvalidJWTTokenError=n;class i extends rr{constructor(h,v){super(h,v),this.causes=[],this.code=31205,this.description="JWT token expired",this.explanation="",this.name="JWTTokenExpiredError",this.solutions=[],Object.setPrototypeOf(this,r.JWTTokenExpiredError.prototype);const y=typeof h=="string"?h:this.explanation,w=typeof h=="object"?h:v;this.message=`${this.name} (${this.code}): ${y}`,this.originalError=w}}r.JWTTokenExpiredError=i;class s extends rr{constructor(h,v){super(h,v),this.causes=["Rate limit exceeded."],this.code=31206,this.description="Rate exceeded authorized limit.",this.explanation="The request performed exceeds the authorized limit.",this.name="RateExceededError",this.solutions=["Ensure message send rate does not exceed authorized limits."],Object.setPrototypeOf(this,r.RateExceededError.prototype);const y=typeof h=="string"?h:this.explanation,w=typeof h=="object"?h:v;this.message=`${this.name} (${this.code}): ${y}`,this.originalError=w}}r.RateExceededError=s;class a extends rr{constructor(h,v){super(h,v),this.causes=[],this.code=31207,this.description="JWT token expiration too long",this.explanation="",this.name="JWTTokenExpirationTooLongError",this.solutions=[],Object.setPrototypeOf(this,r.JWTTokenExpirationTooLongError.prototype);const y=typeof h=="string"?h:this.explanation,w=typeof h=="object"?h:v;this.message=`${this.name} (${this.code}): ${y}`,this.originalError=w}}r.JWTTokenExpirationTooLongError=a;class c extends rr{constructor(h,v){super(h,v),this.causes=[],this.code=31209,this.description="Reconnect attempt is not authorized.",this.explanation="",this.name="ReconnectAttemptError",this.solutions=[],Object.setPrototypeOf(this,r.ReconnectAttemptError.prototype);const y=typeof h=="string"?h:this.explanation,w=typeof h=="object"?h:v;this.message=`${this.name} (${this.code}): ${y}`,this.originalError=w}}r.ReconnectAttemptError=c;class o extends rr{constructor(h,v){super(h,v),this.causes=["The Call Message Event Type is invalid and is not understood by Twilio Voice."],this.code=31210,this.description="Call Message Event Type is invalid.",this.explanation="The Call Message Event Type is invalid and is not understood by Twilio Voice.",this.name="CallMessageEventTypeInvalidError",this.solutions=["Ensure the Call Message Event Type is Valid and understood by Twilio Voice and try again."],Object.setPrototypeOf(this,r.CallMessageEventTypeInvalidError.prototype);const y=typeof h=="string"?h:this.explanation,w=typeof h=="object"?h:v;this.message=`${this.name} (${this.code}): ${y}`,this.originalError=w}}r.CallMessageEventTypeInvalidError=o;class l extends rr{constructor(h,v){super(h,v),this.causes=["The payload size of Call Message Event exceeds the authorized limit."],this.code=31212,this.description="Call Message Event Payload size exceeded authorized limit.",this.explanation="The request performed to send a Call Message Event exceeds the payload size authorized limit",this.name="PayloadSizeExceededError",this.solutions=["Reduce payload size of Call Message Event to be within the authorized limit and try again."],Object.setPrototypeOf(this,r.PayloadSizeExceededError.prototype);const y=typeof h=="string"?h:this.explanation,w=typeof h=="object"?h:v;this.message=`${this.name} (${this.code}): ${y}`,this.originalError=w}}r.PayloadSizeExceededError=l})(In||(In={}));var wl;(function(r){class e extends rr{constructor(i,s){super(i,s),this.causes=["The user denied the getUserMedia request.","The browser denied the getUserMedia request."],this.code=31401,this.description="UserMedia Permission Denied Error",this.explanation="The browser or end-user denied permissions to user media. Therefore we were unable to acquire input audio.",this.name="PermissionDeniedError",this.solutions=["The user should accept the request next time prompted. If the browser saved the deny, the user should change that permission in their browser.","The user should to verify that the browser has permission to access the microphone at this address."],Object.setPrototypeOf(this,r.PermissionDeniedError.prototype);const a=typeof i=="string"?i:this.explanation,c=typeof i=="object"?i:s;this.message=`${this.name} (${this.code}): ${a}`,this.originalError=c}}r.PermissionDeniedError=e;class t extends rr{constructor(i,s){super(i,s),this.causes=["NotFoundError - The deviceID specified was not found.","The getUserMedia constraints were overconstrained and no devices matched."],this.code=31402,this.description="UserMedia Acquisition Failed Error",this.explanation="The browser and end-user allowed permissions, however getting the media failed. Usually this is due to bad constraints, but can sometimes fail due to browser, OS or hardware issues.",this.name="AcquisitionFailedError",this.solutions=["Ensure the deviceID being specified exists.","Try acquiring media with fewer constraints."],Object.setPrototypeOf(this,r.AcquisitionFailedError.prototype);const a=typeof i=="string"?i:this.explanation,c=typeof i=="object"?i:s;this.message=`${this.name} (${this.code}): ${a}`,this.originalError=c}}r.AcquisitionFailedError=t})(wl||(wl={}));var _s;(function(r){class e extends rr{constructor(i,s){super(i,s),this.causes=[],this.code=53e3,this.description="Signaling connection error",this.explanation="Raised whenever a signaling connection error occurs that is not covered by a more specific error code.",this.name="ConnectionError",this.solutions=[],Object.setPrototypeOf(this,r.ConnectionError.prototype);const a=typeof i=="string"?i:this.explanation,c=typeof i=="object"?i:s;this.message=`${this.name} (${this.code}): ${a}`,this.originalError=c}}r.ConnectionError=e;class t extends rr{constructor(i,s){super(i,s),this.causes=["The device running your application lost its Internet connection."],this.code=53001,this.description="Signaling connection disconnected",this.explanation="Raised whenever the signaling connection is unexpectedly disconnected.",this.name="ConnectionDisconnected",this.solutions=["Ensure the device running your application has access to a stable Internet connection."],Object.setPrototypeOf(this,r.ConnectionDisconnected.prototype);const a=typeof i=="string"?i:this.explanation,c=typeof i=="object"?i:s;this.message=`${this.name} (${this.code}): ${a}`,this.originalError=c}}r.ConnectionDisconnected=t})(_s||(_s={}));var ga;(function(r){class e extends rr{constructor(s,a){super(s,a),this.causes=["The Client may not be using a supported WebRTC implementation.","The Client may not have the necessary resources to create or apply a new media description."],this.code=53400,this.description="Client is unable to create or apply a local media description",this.explanation="Raised whenever a Client is unable to create or apply a local media description.",this.name="ClientLocalDescFailed",this.solutions=["If you are experiencing this error using the JavaScript SDK, ensure you are running it with a supported WebRTC implementation."],Object.setPrototypeOf(this,r.ClientLocalDescFailed.prototype);const c=typeof s=="string"?s:this.explanation,o=typeof s=="object"?s:a;this.message=`${this.name} (${this.code}): ${c}`,this.originalError=o}}r.ClientLocalDescFailed=e;class t extends rr{constructor(s,a){super(s,a),this.causes=["The Client may not be using a supported WebRTC implementation.","The Client may be connecting peer-to-peer with another Participant that is not using a supported WebRTC implementation.","The Client may not have the necessary resources to apply a new media description."],this.code=53402,this.description="Client is unable to apply a remote media description",this.explanation="Raised whenever the Client receives a remote media description but is unable to apply it.",this.name="ClientRemoteDescFailed",this.solutions=["If you are experiencing this error using the JavaScript SDK, ensure you are running it with a supported WebRTC implementation."],Object.setPrototypeOf(this,r.ClientRemoteDescFailed.prototype);const c=typeof s=="string"?s:this.explanation,o=typeof s=="object"?s:a;this.message=`${this.name} (${this.code}): ${c}`,this.originalError=o}}r.ClientRemoteDescFailed=t;class n extends rr{constructor(s,a){super(s,a),this.causes=["The Client was unable to establish a media connection.","A media connection which was active failed liveliness checks."],this.code=53405,this.description="Media connection failed",this.explanation="Raised by the Client or Server whenever a media connection fails.",this.name="ConnectionError",this.solutions=["If the problem persists, try connecting to another region.","Check your Client's network connectivity.","If you've provided custom ICE Servers then ensure that the URLs and credentials are valid."],Object.setPrototypeOf(this,r.ConnectionError.prototype);const c=typeof s=="string"?s:this.explanation,o=typeof s=="object"?s:a;this.message=`${this.name} (${this.code}): ${c}`,this.originalError=o}}r.ConnectionError=n})(ga||(ga={}));const CT=new Map([[20101,In.AccessTokenInvalid],[20104,In.AccessTokenExpired],[20151,In.AuthenticationFailed],[31202,mw.AccessTokenSignatureValidationFailed],[31400,Nu.BadRequest],[31404,Nu.NotFound],[31480,Nu.TemporarilyUnavailable],[31486,Nu.BusyHere],[31603,yw.Decline],[31e3,ai.UnknownError],[31001,ai.ApplicationNotFoundError],[31002,ai.ConnectionDeclinedError],[31003,ai.ConnectionTimeoutError],[31005,ai.ConnectionError],[31008,ai.CallCancelledError],[31009,ai.TransportError],[31100,Ja.MalformedRequestError],[31101,Ja.MissingParameterArrayError],[31102,Ja.AuthorizationTokenMissingError],[31103,Ja.MaxParameterLengthExceededError],[31104,Ja.InvalidBridgeTokenError],[31105,Ja.InvalidClientNameError],[31107,Ja.ReconnectParameterInvalidError],[31201,In.AuthorizationError],[31203,In.NoValidAccountError],[31204,In.InvalidJWTTokenError],[31205,In.JWTTokenExpiredError],[31206,In.RateExceededError],[31207,In.JWTTokenExpirationTooLongError],[31209,In.ReconnectAttemptError],[31210,In.CallMessageEventTypeInvalidError],[31212,In.PayloadSizeExceededError],[31401,wl.PermissionDeniedError],[31402,wl.AcquisitionFailedError],[53e3,_s.ConnectionError],[53001,_s.ConnectionDisconnected],[53400,ga.ClientLocalDescFailed],[53402,ga.ClientRemoteDescFailed],[53405,ga.ConnectionError]]);Object.freeze(CT);const Nme=new Set([31001,31002,31003,31101,31102,31103,31104,31105,31107,31201,31202,31203,31204,31205,31207,31404,31480,31486,31603]);function _w(r,e){if(!(typeof e!="number"||!Ume(e)||!(r||!Nme.has(e))))return Lme(e)}class kr extends Error{constructor(e){super(e),this.name="InvalidArgumentError"}}class Bs extends Error{constructor(e){super(e),this.name="InvalidStateError"}}class Fn extends Error{constructor(e){super(e),this.name="NotSupportedError"}}function Lme(r){const e=CT.get(r);if(!e)throw new kr(`Error code ${r} not found`);return e}function Ume(r){return CT.has(r)}const H2="@twilio/voice-sdk",ol="2.18.2",ET="https://sdk.twilio.com/js/client/sounds/releases/1.0.0",Fme=`${ET}/cowbell.mp3?cache=${ol}`,jme=2e4;class On{static getLogLevelInstance(e){if(!On.loglevelInstance)try{On.loglevelInstance=(e&&e.LogLevelModule?e.LogLevelModule:uV).getLogger(H2)}catch{console.warn("Cannot create custom logger"),On.loglevelInstance=console}return On.loglevelInstance}constructor(e,t){this._log=On.getLogLevelInstance(t),this._prefix=`[TwilioVoice][${e}]`}debug(...e){this._log.debug(this._prefix,...e)}error(...e){this._log.error(this._prefix,...e)}info(...e){this._log.info(this._prefix,...e)}setDefaultLevel(e){this._log.setDefaultLevel?this._log.setDefaultLevel(e):console.warn("Logger cannot setDefaultLevel")}warn(...e){this._log.warn(this._prefix,...e)}}On.levels=Gr.levels;On.getLogLevelInstance();const Bme=`${ET}/outgoing.mp3`;class LA{constructor(e,t,n,i){this._name=e,this._availableDevices=t,this._beforeChange=n,this._isSupported=i,this._activeDevices=new Set,this._log=new On("OutputDeviceCollection")}delete(e){this._log.debug(".delete",e);const t=!!this._activeDevices.delete(e),n=this._availableDevices.get("default")||Array.from(this._availableDevices.values())[0];!this._activeDevices.size&&n&&this._activeDevices.add(n);const i=Array.from(this._activeDevices.values()).map(s=>s.deviceId);return this._beforeChange(this._name,i),!!t}get(){return this._activeDevices}set(e){if(this._log.debug(".set",e),!this._isSupported)return Promise.reject(new Fn("This browser does not support audio output selection"));const t=Array.isArray(e)?e:[e];if(!t.length)return Promise.reject(new kr("Must specify at least one device to set"));const n=[],i=t.map(s=>{const a=this._availableDevices.get(s);return a||n.push(s),a});return n.length?Promise.reject(new kr(`Devices not found: ${n.join(", ")}`)):new Promise(s=>{s(this._beforeChange(this._name,t))}).then(()=>{this._activeDevices.clear(),i.forEach(this._activeDevices.add,this._activeDevices)})}test(e=Bme){return this._isSupported?this._activeDevices.size?Promise.all(Array.from(this._activeDevices).map(t=>{let n;return new Promise(i=>{n=new Audio(e),n.oncanplay=i}).then(()=>n.setSinkId(t.deviceId).then(()=>n.play()))})):Promise.reject(new Bs("No active output devices to test")):Promise.reject(new Fn("This browser does not support audio output selection"))}}class qme{constructor(e){Object.defineProperties(this,{deviceId:{get(){return e.deviceId}},groupId:{get(){return e.groupId}},kind:{get(){return e.kind}},label:{get(){return e.label}}})}}function Mv(r){if(!(this instanceof Mv))return new Mv(r);this.message=r}Mv.prototype.toString=function(){return`Twilio.Exception: ${this.message}`};function Gd(r){return r&&r.length?r.reduce((e,t)=>e+t)/r.length:0}function kT(r,e,t){t=t||(i=>i);const n=new Set(e.map(t));return r.filter(i=>!n.has(t(i)))}function G2(r){return!!r.userAgent.match("Electron")}function RT(r,e){const t=!!e.userAgent.match("CriOS"),n=!!e.userAgent.match("HeadlessChrome"),i=typeof r.chrome<"u"&&e.vendor==="Google Inc."&&e.userAgent.indexOf("OPR")===-1&&e.userAgent.indexOf("Edge")===-1;return t||G2(e)||i||n}function Wme(r){return r=r||(typeof window>"u"?global.navigator:window.navigator),!!r&&typeof r.userAgent=="string"&&/firefox|fxios/i.test(r.userAgent)}function cm(r){return r=r||(typeof window>"u"?global.navigator:window.navigator),!!r&&typeof r.userAgent=="string"&&/edge\/\d+/i.test(r.userAgent)}function Vme(r){return!!r.vendor&&r.vendor.indexOf("Apple")!==-1&&r.userAgent&&r.userAgent.indexOf("CriOS")===-1&&r.userAgent.indexOf("FxiOS")===-1}function z2(r){return r?r.split("&").reduce((e,t)=>{const n=t.split("="),i=n[0],s=decodeURIComponent((n[1]||"").replace(/\+/g,"%20"));return i&&(e[i]=s),e},{}):""}function bw(r,e){const t=r instanceof Map||r instanceof Set?Array.from(r.values()):r;return e=e||(n=>n),t.reduce((n,i)=>{const s=e(i);return n.concat(s)},[])}function Sw(r,e,t){return new Promise((n,i)=>{function s(){r.removeListener(t,a),n()}function a(){r.removeListener(e,s),i()}r.once(e,s),r.once(t,a)})}function K2(r,e){const t=e.map(n=>"audio/"+n.toLowerCase());return r.sort((n,i)=>{const s=t.indexOf(n.mimeType.toLowerCase()),a=t.indexOf(i.mimeType.toLowerCase()),c=s>=0?s:Number.MAX_VALUE,o=a>=0?a:Number.MAX_VALUE;return c-o})}const Hme=Mv,J2=Object.freeze(Object.defineProperty({__proto__:null,Exception:Hme,average:Gd,difference:kT,flatMap:bw,isChrome:RT,isElectron:G2,isFirefox:Wme,isLegacyEdge:cm,isSafari:Vme,promisifyEvents:Sw,queryToJson:z2,sortByMimeTypes:K2},Symbol.toStringTag,{value:"Module"})),Gme={audioinput:"Audio Input",audiooutput:"Audio Output"};class ww extends Ss.EventEmitter{get audioConstraints(){return this._audioConstraints}get inputDevice(){return this._inputDevice}get inputStream(){return this._localProcessedStream||this._selectedInputDeviceStream}get processedStream(){return this._log.warn("AudioHelper#processedStream is deprecated. Please use AudioHelper#localProcessedStream instead."),this._localProcessedStream}get localProcessedStream(){return this._localProcessedStream}get remoteProcessedStream(){return this._remoteProcessedStream}constructor(e,t,n){super(),this.availableInputDevices=new Map,this.availableOutputDevices=new Map,this._audioConstraints=null,this._defaultInputDeviceStream=null,this._enabledSounds={[ft.SoundName.Disconnect]:!0,[ft.SoundName.Incoming]:!0,[ft.SoundName.Outgoing]:!0},this._inputDevice=null,this._inputDevicePromise=null,this._isPollingInputVolume=!1,this._log=new On("AudioHelper"),this._localProcessedStream=null,this._remoteProcessedStream=null,this._selectedInputDeviceStream=null,this._unknownDeviceIndexes={audioinput:{},audiooutput:{}},this._updateAvailableDevices=()=>!this._mediaDevices||!this._enumerateDevices?Promise.reject("Enumeration not supported"):this._enumerateDevices().then(c=>{this._updateDevices(c.filter(l=>l.kind==="audiooutput"),this.availableOutputDevices,this._removeLostOutput),this._updateDevices(c.filter(l=>l.kind==="audioinput"),this.availableInputDevices,this._removeLostInput);const o=this.availableOutputDevices.get("default")||Array.from(this.availableOutputDevices.values())[0];[this.speakerDevices,this.ringtoneDevices].forEach(l=>{!l.get().size&&this.availableOutputDevices.size&&this.isOutputSelectionSupported&&l.set(o.deviceId).catch(d=>{this._log.warn(`Unable to set audio output devices. ${d}`)})})}),this._removeLostInput=c=>{if(!this.inputDevice||this.inputDevice.deviceId!==c.deviceId)return!1;this._destroyLocalProcessedStream(),this._replaceStream(null),this._inputDevice=null,this._maybeStopPollingVolume();const o=this.availableInputDevices.get("default")||Array.from(this.availableInputDevices.values())[0];return o&&this.setInputDevice(o.deviceId),!0},this._removeLostOutput=c=>{const o=this.speakerDevices.delete(c),l=this.ringtoneDevices.delete(c);return o||l},n=Object.assign({AudioContext:typeof AudioContext<"u"&&AudioContext,setSinkId:typeof HTMLAudioElement<"u"&&HTMLAudioElement.prototype.setSinkId},n),this._beforeSetInputDevice=n.beforeSetInputDevice||(()=>Promise.resolve()),this._updateUserOptions(n),this._audioProcessorEventObserver=n.audioProcessorEventObserver,this._mediaDevices=n.mediaDevices||navigator.mediaDevices,this._onActiveInputChanged=t,this._enumerateDevices=typeof n.enumerateDevices=="function"?n.enumerateDevices:this._mediaDevices&&this._mediaDevices.enumerateDevices.bind(this._mediaDevices);const i=!!(n.AudioContext||n.audioContext),s=!!this._enumerateDevices;n.enabledSounds&&(this._enabledSounds=n.enabledSounds);const a=typeof n.setSinkId=="function";this.isOutputSelectionSupported=s&&a,this.isVolumeSupported=i,this.isVolumeSupported&&(this._audioContext=n.audioContext||n.AudioContext&&new n.AudioContext,this._audioContext&&(this._inputVolumeAnalyser=this._audioContext.createAnalyser(),this._inputVolumeAnalyser.fftSize=32,this._inputVolumeAnalyser.smoothingTimeConstant=.3)),this.ringtoneDevices=new LA("ringtone",this.availableOutputDevices,e,this.isOutputSelectionSupported),this.speakerDevices=new LA("speaker",this.availableOutputDevices,e,this.isOutputSelectionSupported),this.addListener("newListener",c=>{c==="inputVolume"&&this._maybeStartPollingVolume()}),this.addListener("removeListener",c=>{c==="inputVolume"&&this._maybeStopPollingVolume()}),this.once("newListener",()=>{this.isOutputSelectionSupported||this._log.warn("Warning: This browser does not support audio output selection."),this.isVolumeSupported||this._log.warn("Warning: This browser does not support Twilio's volume indicator feature.")}),s&&this._initializeEnumeration(),navigator&&navigator.permissions&&typeof navigator.permissions.query=="function"?navigator.permissions.query({name:"microphone"}).then(c=>{if(c.state!=="granted"){const o=()=>{this._updateAvailableDevices(),this._stopMicrophonePermissionListener()};c.addEventListener("change",o),this._microphonePermissionStatus=c,this._onMicrophonePermissionStatusChanged=o}}).catch(c=>this._log.warn(`Warning: unable to listen for microphone permission changes. ${c}`)):this._log.warn("Warning: current browser does not support permissions API.")}_destroy(){this._stopDefaultInputDeviceStream(),this._stopSelectedInputDeviceStream(),this._destroyLocalProcessedStream(),this._destroyRemoteProcessedStream(),this._maybeStopPollingVolume(),this.removeAllListeners(),this._stopMicrophonePermissionListener(),this._unbind()}_destroyRemoteProcessedStream(){if(this._remoteProcessor&&this._remoteProcessedStream){this._log.info("destroying remote processed stream");const e=this._remoteProcessedStream;this._remoteProcessedStream.getTracks().forEach(t=>t.stop()),this._remoteProcessedStream=null,this._remoteProcessor.destroyProcessedStream(e),this._audioProcessorEventObserver.emit("destroy",!0)}}_getInputDevicePromise(){return this._inputDevicePromise}_getAudioProcessorEventObserver(){return this._audioProcessorEventObserver}_maybeCreateRemoteProcessedStream(e){return this._remoteProcessor?(this._log.info("Creating remote processed stream"),this._remoteProcessor.createProcessedStream(e).then(t=>(this._remoteProcessedStream=t,this._audioProcessorEventObserver.emit("create",!0),this._remoteProcessedStream))):Promise.resolve(e)}_maybeStartPollingVolume(){if(!this.isVolumeSupported||!this.inputStream||(this._updateVolumeSource(),this._isPollingInputVolume||!this._inputVolumeAnalyser))return;const e=this._inputVolumeAnalyser.frequencyBinCount,t=new Uint8Array(e);this._isPollingInputVolume=!0;const n=()=>{if(this._isPollingInputVolume){if(this._inputVolumeAnalyser){this._inputVolumeAnalyser.getByteFrequencyData(t);const i=Gd(t);this.emit("inputVolume",i/255)}requestAnimationFrame(n)}};requestAnimationFrame(n)}_maybeStopPollingVolume(){this.isVolumeSupported&&(!this._isPollingInputVolume||this.inputStream&&this.listenerCount("inputVolume")||(this._inputVolumeSource&&(this._inputVolumeSource.disconnect(),delete this._inputVolumeSource),this._isPollingInputVolume=!1))}_openDefaultDeviceWithConstraints(e){return this._log.info("Opening default device with constraints",e),this._getUserMedia(e).then(t=>(this._log.info("Opened default device. Updating available devices."),this._updateAvailableDevices().catch(n=>{this._log.warn("Unable to updateAvailableDevices after gUM call",n)}),this._defaultInputDeviceStream=t,this._maybeCreateLocalProcessedStream(t)))}_stopDefaultInputDeviceStream(){this._defaultInputDeviceStream&&(this._log.info("stopping default device stream"),this._defaultInputDeviceStream.getTracks().forEach(e=>e.stop()),this._defaultInputDeviceStream=null,this._destroyLocalProcessedStream())}_unbind(){var e;!((e=this._mediaDevices)===null||e===void 0)&&e.removeEventListener&&this._mediaDevices.removeEventListener("devicechange",this._updateAvailableDevices)}_updateUserOptions(e){typeof e.enumerateDevices=="function"&&(this._enumerateDevices=e.enumerateDevices),typeof e.getUserMedia=="function"&&(this._getUserMedia=e.getUserMedia)}addProcessor(e,t=!1){if(this._log.debug(".addProcessor"),this._localProcessor&&!t)throw new Fn("Can only have one Local AudioProcessor at a time.");if(this._remoteProcessor&&t)throw new Fn("Can only have one Remote AudioProcessor at a time.");if(typeof e!="object"||e===null)throw new kr("Missing AudioProcessor argument.");if(typeof e.createProcessedStream!="function")throw new kr("Missing createProcessedStream() method.");if(typeof e.destroyProcessedStream!="function")throw new kr("Missing destroyProcessedStream() method.");return t?(this._remoteProcessor=e,this._audioProcessorEventObserver.emit("add",!0),Promise.resolve()):(this._localProcessor=e,this._audioProcessorEventObserver.emit("add",!1),this._restartInputStreams())}disconnect(e){return this._log.debug(".disconnect",e),this._maybeEnableSound(ft.SoundName.Disconnect,e)}incoming(e){return this._log.debug(".incoming",e),this._maybeEnableSound(ft.SoundName.Incoming,e)}outgoing(e){return this._log.debug(".outgoing",e),this._maybeEnableSound(ft.SoundName.Outgoing,e)}removeProcessor(e,t=!1){if(this._log.debug(".removeProcessor"),typeof e!="object"||e===null)throw new kr("Missing AudioProcessor argument.");if(this._localProcessor!==e&&!t)throw new kr("Cannot remove a Local AudioProcessor that has not been previously added.");if(this._remoteProcessor!==e&&t)throw new kr("Cannot remove a Remote AudioProcessor that has not been previously added.");return t?(this._destroyRemoteProcessedStream(),this._remoteProcessor=null,this._audioProcessorEventObserver.emit("remove",!0),Promise.resolve()):(this._destroyLocalProcessedStream(),this._localProcessor=null,this._audioProcessorEventObserver.emit("remove",!1),this._restartInputStreams())}setAudioConstraints(e){return this._log.debug(".setAudioConstraints",e),this._audioConstraints=Object.assign({},e),delete this._audioConstraints.deviceId,this.inputDevice?this._setInputDevice(this.inputDevice.deviceId,!0):Promise.resolve()}setInputDevice(e){return this._log.debug(".setInputDevice",e),this._setInputDevice(e,!1)}unsetAudioConstraints(){return this._log.debug(".unsetAudioConstraints"),this._audioConstraints=null,this.inputDevice?this._setInputDevice(this.inputDevice.deviceId,!0):Promise.resolve()}unsetInputDevice(){return this._log.debug(".unsetInputDevice",this.inputDevice),this.inputDevice?(this._destroyLocalProcessedStream(),this._onActiveInputChanged(null).then(()=>{this._replaceStream(null),this._inputDevice=null,this._maybeStopPollingVolume()})):Promise.resolve()}_destroyLocalProcessedStream(){if(this._localProcessor&&this._localProcessedStream){this._log.info("destroying local processed stream");const e=this._localProcessedStream;this._localProcessedStream.getTracks().forEach(t=>t.stop()),this._localProcessedStream=null,this._localProcessor.destroyProcessedStream(e),this._audioProcessorEventObserver.emit("destroy",!1)}}_getUnknownDeviceIndex(e){const t=e.deviceId,n=e.kind;let i=this._unknownDeviceIndexes[n][t];return i||(i=Object.keys(this._unknownDeviceIndexes[n]).length+1,this._unknownDeviceIndexes[n][t]=i),i}_initializeEnumeration(){if(!this._mediaDevices||!this._enumerateDevices)throw new Fn("Enumeration is not supported");this._mediaDevices.addEventListener&&this._mediaDevices.addEventListener("devicechange",this._updateAvailableDevices),this._updateAvailableDevices().then(()=>{this.isOutputSelectionSupported&&Promise.all([this.speakerDevices.set("default"),this.ringtoneDevices.set("default")]).catch(e=>{this._log.warn(`Warning: Unable to set audio output devices. ${e}`)})})}_maybeCreateLocalProcessedStream(e){return this._localProcessor?(this._log.info("Creating local processed stream"),this._localProcessor.createProcessedStream(e).then(t=>(this._localProcessedStream=t,this._audioProcessorEventObserver.emit("create",!1),this._localProcessedStream))):Promise.resolve(e)}_maybeEnableSound(e,t){return typeof t<"u"&&(this._enabledSounds[e]=t),this._enabledSounds[e]}_replaceStream(e){this._log.info("Replacing with new stream."),this._selectedInputDeviceStream&&(this._log.info("Old stream detected. Stopping tracks."),this._stopSelectedInputDeviceStream()),this._selectedInputDeviceStream=e}_restartInputStreams(){if(this.inputDevice&&this._selectedInputDeviceStream)return this._log.info("Restarting selected input device"),this._setInputDevice(this.inputDevice.deviceId,!0);if(this._defaultInputDeviceStream){const e=this.availableInputDevices.get("default")||Array.from(this.availableInputDevices.values())[0];return this._log.info("Restarting default input device, now becoming selected."),this._setInputDevice(e.deviceId,!0)}return Promise.resolve()}_setInputDevice(e,t){return yi(this,void 0,void 0,function*(){const n=()=>yi(this,void 0,void 0,function*(){if(yield this._beforeSetInputDevice(),typeof e!="string")return Promise.reject(new kr("Must specify the device to set"));const i=this.availableInputDevices.get(e);if(!i)return Promise.reject(new kr(`Device not found: ${e}`));if(this._log.info("Setting input device. ID: "+e),this._inputDevice&&this._inputDevice.deviceId===e&&this._selectedInputDeviceStream){if(!t)return Promise.resolve();this._log.info("Same track detected on setInputDevice, stopping old tracks."),this._stopSelectedInputDeviceStream()}this._stopDefaultInputDeviceStream();const s={audio:Object.assign({deviceId:{exact:e}},this.audioConstraints)};return this._log.info("setInputDevice: getting new tracks."),this._getUserMedia(s).then(a=>(this._destroyLocalProcessedStream(),this._maybeCreateLocalProcessedStream(a).then(c=>(this._log.info("setInputDevice: invoking _onActiveInputChanged."),this._onActiveInputChanged(c).then(()=>{this._replaceStream(a),this._inputDevice=i,this._maybeStartPollingVolume()})))))});return this._inputDevicePromise=n().finally(()=>{this._inputDevicePromise=null})})}_stopMicrophonePermissionListener(){var e;!((e=this._microphonePermissionStatus)===null||e===void 0)&&e.removeEventListener&&this._microphonePermissionStatus.removeEventListener("change",this._onMicrophonePermissionStatusChanged)}_stopSelectedInputDeviceStream(){this._selectedInputDeviceStream&&(this._log.info("Stopping selected device stream"),this._selectedInputDeviceStream.getTracks().forEach(e=>e.stop()))}_updateDevices(e,t,n){const i=e.map(l=>l.deviceId),s=Array.from(t.values()).map(l=>l.deviceId),a=[],c=kT(s,i);c.forEach(l=>{const d=t.get(l);d&&(t.delete(l),n(d)&&a.push(d))});let o=!1;if(e.forEach(l=>{const d=t.get(l.deviceId),h=this._wrapMediaDeviceInfo(l);(!d||d.label!==h.label)&&(t.set(l.deviceId,h),o=!0)}),o||c.length){const l="default",d=this.inputDevice&&this.inputDevice.deviceId===l,h=this._defaultInputDeviceStream&&this.availableInputDevices.get(l);(d||h)&&(this._log.warn("Calling getUserMedia after device change to ensure that the tracks of the active device (default) have not gone stale."),setTimeout(()=>{this._setInputDevice(l,!0)},0)),this._log.debug("#deviceChange",a),this.emit("deviceChange",a)}}_updateVolumeSource(){if(!(!this.inputStream||!this._audioContext||!this._inputVolumeAnalyser)){this._inputVolumeSource&&this._inputVolumeSource.disconnect();try{this._inputVolumeSource=this._audioContext.createMediaStreamSource(this.inputStream),this._inputVolumeSource.connect(this._inputVolumeAnalyser)}catch(e){this._log.warn("Unable to update volume source",e),delete this._inputVolumeSource}}}_wrapMediaDeviceInfo(e){const t={deviceId:e.deviceId,groupId:e.groupId,kind:e.kind,label:e.label};if(!t.label)if(t.deviceId==="default")t.label="Default";else{const n=this._getUnknownDeviceIndex(e);t.label=`Unknown ${Gme[t.kind]} Device ${n}`}return new qme(t)}}ww||(ww={});var zme=ww;class Kme extends Ss.EventEmitter{constructor(){super(),this._log=new On("AudioProcessorEventObserver"),this._log.info("Creating AudioProcessorEventObserver instance"),this.on("enabled",e=>this._reEmitEvent("enabled",e)),this.on("add",e=>this._reEmitEvent("add",e)),this.on("remove",e=>this._reEmitEvent("remove",e)),this.on("create",e=>this._reEmitEvent("create-processed-stream",e)),this.on("destroy",e=>this._reEmitEvent("destroy-processed-stream",e))}destroy(){this.removeAllListeners()}_reEmitEvent(e,t){this._log.info(`${t?"Remote":"Local"} AudioProcessor:${e}`),this.emit("event",{name:e,group:"audio-processor",isRemote:t})}}const Jme={dtmf0:[1360,960],dtmf1:[1230,720],dtmf2:[1360,720],dtmf3:[1480,720],dtmf4:[1230,790],dtmf5:[1360,790],dtmf6:[1480,790],dtmf7:[1230,870],dtmf8:[1360,870],dtmf9:[1480,870],dtmfh:[1480,960],dtmfs:[1230,960]};class Yme{constructor(e){this._context=e,this._gainNodes=[],this._gainNodes=[this._context.createGain(),this._context.createGain()],this._gainNodes.forEach(t=>{t.connect(this._context.destination),t.gain.value=.1,this._gainNodes.push(t)})}cleanup(){this._gainNodes.forEach(e=>{e.disconnect()})}play(e){const t=Jme[e];if(!t)throw new kr("Invalid DTMF sound name");[this._context.createOscillator(),this._context.createOscillator()].forEach((i,s)=>{i.type="sine",i.frequency.value=t[s],i.connect(this._gainNodes[s]),i.start(),i.stop(this._context.currentTime+.1),i.addEventListener("ended",()=>i.disconnect())})}}function Xme(r,e,t){const n=JSON.stringify(e.body||{}),i=new Headers;e.headers=e.headers||[],Object.entries(e.headers).forEach(([s,a])=>i.append(s,a)),fetch(e.url,{body:n,headers:i,method:r}).then(s=>s.text(),t).then(s=>t(null,s),t)}const PT=Xme;PT.get=function(e,t){return new this("GET",e,t)};PT.post=function(e,t){return new this("POST",e,t)};class Ti extends Ss.EventEmitter{constructor(e,t,n){if(super(),!(this instanceof Ti))return new Ti(e,t,n);n=Object.assign({defaultPayload(){return{}}},n);let i=n.defaultPayload;typeof i!="function"&&(i=()=>Object.assign({},n.defaultPayload));let s=!0;const a=Object.assign({app_name:void 0,app_version:void 0},n.metadata);Object.defineProperties(this,{_defaultPayload:{value:i},_host:{value:n.host,writable:!0},_isEnabled:{get(){return s},set(c){s=c}},_log:{value:new On("EventPublisher")},_request:{value:n.request||PT,writable:!0},_token:{value:t,writable:!0},isEnabled:{enumerable:!0,get(){return s}},metadata:{enumerable:!0,get(){return a}},productName:{enumerable:!0,value:e},token:{enumerable:!0,get(){return this._token}}})}}Ti.prototype._post=function(e,t,n,i,s,a,c){if(!this.isEnabled&&!c||!this._host)return this._log.debug("Publishing cancelled",JSON.stringify({isEnabled:this.isEnabled,force:c,host:this._host})),Promise.resolve();if(!a||(!a.parameters||!a.parameters.CallSid)&&!a.outboundConnectionId)return a?this._log.debug("Publishing cancelled. Missing connection info",JSON.stringify({outboundConnectionId:a.outboundConnectionId,parameters:a.parameters})):this._log.debug("Publishing cancelled. Missing connection object"),Promise.resolve();const o={group:n,level:t.toUpperCase(),name:i,payload:s&&s.forEach?s.slice(0):Object.assign(this._defaultPayload(a),s),payload_type:"application/json",private:!1,publisher:this.productName,timestamp:new Date().toISOString()};this.metadata&&(o.publisher_metadata=this.metadata),e==="EndpointEvents"&&this._log.debug("Publishing insights",JSON.stringify({endpointName:e,event:o,force:c,host:this._host}));const l={body:o,headers:{"Content-Type":"application/json","X-Twilio-Token":this.token},url:`https://${this._host}/v4/${e}`};return new Promise((d,h)=>{this._request.post(l,v=>{v?(this.emit("error",v),h(v)):d()})}).catch(d=>{this._log.error(`Unable to post ${n} ${i} event to Insights. Received error: ${d}`)})};Ti.prototype.post=function(e,t,n,i,s,a){return this._post("EndpointEvents",e,t,n,i,s,a)};Ti.prototype.debug=function(e,t,n,i){return this.post("debug",e,t,n,i)};Ti.prototype.info=function(e,t,n,i){return this.post("info",e,t,n,i)};Ti.prototype.warn=function(e,t,n,i){return this.post("warning",e,t,n,i)};Ti.prototype.error=function(e,t,n,i){return this.post("error",e,t,n,i)};Ti.prototype.postMetrics=function(e,t,n,i,s){return new Promise(a=>{const c=n.map(Qme).map(o=>Object.assign(o,i));a(this._post("EndpointMetrics","info",e,t,c,s))})};Ti.prototype.setHost=function(e){this._host=e};Ti.prototype.setToken=function(e){this._token=e};Ti.prototype.enable=function(){this._isEnabled=!0};Ti.prototype.disable=function(){this._isEnabled=!1};function Qme(r){return{audio_codec:r.codecName,audio_level_in:r.audioInputLevel,audio_level_out:r.audioOutputLevel,bytes_received:r.bytesReceived,bytes_sent:r.bytesSent,call_volume_input:r.inputVolume,call_volume_output:r.outputVolume,jitter:r.jitter,mos:r.mos&&Math.round(r.mos*100)/100,packets_lost:r.packetsLost,packets_lost_fraction:r.packetsLostFraction&&Math.round(r.packetsLostFraction*100)/100,packets_received:r.packetsReceived,rtt:r.rtt,timestamp:new Date(r.timestamp).toISOString(),total_bytes_received:r.totals.bytesReceived,total_bytes_sent:r.totals.bytesSent,total_packets_lost:r.totals.packetsLost,total_packets_received:r.totals.packetsReceived,total_packets_sent:r.totals.packetsSent}}const UA=32767,FA=typeof window<"u"?window.RTCStatsReport:void 0;function zs(r){if(!(this instanceof zs))return new zs(r);const e=this;Object.defineProperties(this,{_map:{value:r},size:{enumerable:!0,get(){return e._map.size}}}),this[Symbol.iterator]=r[Symbol.iterator]}FA&&(zs.prototype=Object.create(FA.prototype),zs.prototype.constructor=zs);["entries","forEach","get","has","keys","values"].forEach(r=>{zs.prototype[r]=function(...e){return this._map[r](...e)}});zs.fromArray=function(e){return new zs(e.reduce((t,n)=>(t.set(n.id,n),t),new Map))};zs.fromRTCStatsResponse=function(e){let t;const n=new Map,i=e.result().reduce((s,a)=>{const c=a.id;switch(a.type){case"googCertificate":s.set(c,iye(a));break;case"datachannel":s.set(c,sye(a));break;case"googCandidatePair":X2(a,"googActiveConnection")&&(t=c),s.set(c,nye(a));break;case"localcandidate":s.set(c,BA(a,!1));break;case"remotecandidate":s.set(c,BA(a,!0));break;case"ssrc":qu(a,"packetsReceived")?s.set(`rtp-${c}`,tye(a)):s.set(`rtp-${c}`,rye(a)),s.set(`track-${c}`,eye(a)),s.set(`codec-${c}`,Zme(a));break;case"googComponent":const o=jA(a);n.set(o.selectedCandidatePairId,c),s.set(c,jA(a));break}return s},new Map);if(t){const s=n.get(t);s&&(i.get(s).dtlsState="connected")}return new zs(i)};function jA(r){return{bytesReceived:void 0,bytesSent:void 0,dtlsState:void 0,id:r.id,localCertificateId:r.stat("localCertificateId"),remoteCertificateId:r.stat("remoteCertificateId"),rtcpTransportStatsId:void 0,selectedCandidatePairId:r.stat("selectedCandidatePairId"),timestamp:Date.parse(r.timestamp),type:"transport"}}function Zme(r){return{channels:void 0,clockRate:void 0,id:r.id,implementation:void 0,mimeType:`${r.stat("mediaType")}/${r.stat("googCodecName")}`,payloadType:void 0,sdpFmtpLine:void 0,timestamp:Date.parse(r.timestamp),type:"codec"}}function eye(r){return{audioLevel:qu(r,"audioOutputLevel")?Or(r,"audioOutputLevel")/UA:(Or(r,"audioInputLevel")||0)/UA,detached:void 0,echoReturnLoss:Cw(r,"googEchoCancellationReturnLoss"),echoReturnLossEnhancement:Cw(r,"googEchoCancellationReturnLossEnhancement"),ended:void 0,frameHeight:qu(r,"googFrameHeightReceived")?Or(r,"googFrameHeightReceived"):Or(r,"googFrameHeightSent"),frameWidth:qu(r,"googFrameWidthReceived")?Or(r,"googFrameWidthReceived"):Or(r,"googFrameWidthSent"),framesCorrupted:void 0,framesDecoded:Or(r,"framesDecoded"),framesDropped:void 0,framesPerSecond:void 0,framesReceived:void 0,framesSent:Or(r,"framesEncoded"),fullFramesLost:void 0,id:r.id,kind:r.stat("mediaType"),partialFramesLost:void 0,remoteSource:void 0,ssrcIds:void 0,timestamp:Date.parse(r.timestamp),trackIdentifier:r.stat("googTrackId"),type:"track"}}function Y2(r,e){return{associateStatsId:void 0,codecId:`codec-${r.id}`,firCount:e?Or(r,"googFirsSent"):void 0,id:r.id,isRemote:void 0,mediaType:r.stat("mediaType"),nackCount:e?Or(r,"googNacksSent"):Or(r,"googNacksReceived"),pliCount:e?Or(r,"googPlisSent"):Or(r,"googPlisReceived"),qpSum:Or(r,"qpSum"),sliCount:void 0,ssrc:r.stat("ssrc"),timestamp:Date.parse(r.timestamp),trackId:`track-${r.id}`,transportId:r.stat("transportId")}}function tye(r){const e=Y2(r,!0);return Object.assign(e,{burstDiscardCount:void 0,burstDiscardRate:void 0,burstLossCount:void 0,burstLossRate:void 0,burstPacketsDiscarded:void 0,burstPacketsLost:void 0,bytesReceived:Or(r,"bytesReceived"),fractionLost:void 0,framesDecoded:Or(r,"framesDecoded"),gapDiscardRate:void 0,gapLossRate:void 0,jitter:Tw(r.stat("googJitterReceived")),packetsDiscarded:void 0,packetsLost:Or(r,"packetsLost"),packetsReceived:Or(r,"packetsReceived"),packetsRepaired:void 0,roundTripTime:Tw(r.stat("googRtt")),type:"inbound-rtp"}),e}function rye(r){const e=Y2(r,!1);return Object.assign(e,{bytesSent:Or(r,"bytesSent"),framesEncoded:Or(r,"framesEncoded"),packetsSent:Or(r,"packetsSent"),remoteTimestamp:void 0,targetBitrate:void 0,type:"outbound-rtp"}),e}function BA(r,e){return{candidateType:aye(r.stat("candidateType")),deleted:void 0,id:r.id,ip:r.stat("ipAddress"),isRemote:e,port:Or(r,"portNumber"),priority:Cw(r,"priority"),protocol:r.stat("transport"),relayProtocol:void 0,timestamp:Date.parse(r.timestamp),transportId:void 0,type:e?"remote-candidate":"local-candidate",url:void 0}}function nye(r){return{availableIncomingBitrate:void 0,availableOutgoingBitrate:void 0,bytesReceived:Or(r,"bytesReceived"),bytesSent:Or(r,"bytesSent"),consentRequestsSent:Or(r,"consentRequestsSent"),currentRoundTripTime:Tw(r.stat("googRtt")),id:r.id,lastPacketReceivedTimestamp:void 0,lastPacketSentTimestamp:void 0,localCandidateId:r.stat("localCandidateId"),nominated:void 0,priority:void 0,readable:void 0,remoteCandidateId:r.stat("remoteCandidateId"),requestsReceived:Or(r,"requestsReceived"),requestsSent:Or(r,"requestsSent"),responsesReceived:Or(r,"responsesReceived"),responsesSent:Or(r,"responsesSent"),retransmissionsReceived:void 0,retransmissionsSent:void 0,state:void 0,timestamp:Date.parse(r.timestamp),totalRoundTripTime:void 0,transportId:r.stat("googChannelId"),type:"candidate-pair",writable:X2(r,"googWritable")}}function iye(r){return{base64Certificate:r.stat("googDerBase64"),fingerprint:r.stat("googFingerprint"),fingerprintAlgorithm:r.stat("googFingerprintAlgorithm"),id:r.id,issuerCertificateId:r.stat("googIssuerId"),timestamp:Date.parse(r.timestamp),type:"certificate"}}function sye(r){return{bytesReceived:void 0,bytesSent:void 0,datachannelid:r.stat("datachannelid"),id:r.id,label:r.stat("label"),messagesReceived:void 0,messagesSent:void 0,protocol:r.stat("protocol"),state:r.stat("state"),timestamp:Date.parse(r.timestamp),transportId:r.stat("transportId"),type:"data-channel"}}function Tw(r){return isNaN(r)||r===""?void 0:parseInt(r,10)/1e3}function aye(r){switch(r){case"peerreflexive":return"prflx";case"serverreflexive":return"srflx";case"host":case"relay":default:return r}}function Or(r,e){const t=r.stat(e);return qu(r,e)?parseInt(t,10):void 0}function Cw(r,e){const t=r.stat(e);return qu(r,e)?parseFloat(t):void 0}function X2(r,e){const t=r.stat(e);return qu(r,e)?t==="true"||t===!0:void 0}function qu(r,e){const t=r.stat(e);return typeof t<"u"&&t!==""}const oye="PeerConnection is null",uye="WebRTC statistics are unsupported";function Nc(r,e){return typeof r.get=="function"?r.get(e):r.find(t=>t.id===e)}function Q2(r){if(!r)return Promise.reject(new kr(oye));if(typeof r.getStats!="function")return Promise.reject(new Fn(uye));let e;try{e=r.getStats()}catch{e=new Promise(n=>r.getStats(n)).then(zs.fromRTCStatsResponse)}return e}function cye(r,e){return e=Object.assign({createRTCSample:fye},e),Q2(r).then(e.createRTCSample)}function lye(r){return Q2(r).then(e=>{const{candidatePairs:t,localCandidates:n,remoteCandidates:i,transport:s}=Array.from(e.values()).reduce((o,l)=>{switch(["candidatePairs","localCandidates","remoteCandidates"].forEach(d=>{o[d]||(o[d]=[])}),l.type){case"candidate-pair":o.candidatePairs.push(l);break;case"local-candidate":o.localCandidates.push(l);break;case"remote-candidate":o.remoteCandidates.push(l);break;case"transport":l.selectedCandidatePairId&&(o.transport=l);break}return o},{}),a=t.find(o=>o.selected||s&&o.id===s.selectedCandidatePairId);let c;return a&&(c={localCandidate:n.find(o=>o.id===a.localCandidateId),remoteCandidate:i.find(o=>o.id===a.remoteCandidateId)}),{iceCandidateStats:[...n,...i],selectedIceCandidatePairStats:c}})}function dye(){}function fye(r){let e=null;const t=new dye;let n;Array.from(r.values()).forEach(o=>{if(o.isRemote)return;const l=o.type.replace("-","");if(n=n||o.timestamp,o.remoteId){const d=Nc(r,o.remoteId);d&&d.roundTripTime&&(t.rtt=d.roundTripTime*1e3)}switch(l){case"inboundrtp":t.timestamp=t.timestamp||o.timestamp,t.jitter=o.jitter*1e3,t.packetsLost=o.packetsLost,t.packetsReceived=o.packetsReceived,t.bytesReceived=o.bytesReceived;break;case"outboundrtp":if(t.timestamp=o.timestamp,t.packetsSent=o.packetsSent,t.bytesSent=o.bytesSent,o.codecId){const d=Nc(r,o.codecId);t.codecName=d?d.mimeType&&d.mimeType.match(/(.*\/)?(.*)/)[2]:o.codecId}break;case"transport":e=o.id;break}}),t.timestamp||(t.timestamp=n);const i=Nc(r,e);if(!i)return t;const s=Nc(r,i.selectedCandidatePairId);if(!s)return t;const a=Nc(r,s.localCandidateId),c=Nc(r,s.remoteCandidateId);return t.rtt||(t.rtt=s&&s.currentRoundTripTime*1e3),Object.assign(t,{localAddress:a&&(a.address||a.ip),remoteAddress:c&&(c.address||c.ip)}),t}class Qr extends Ss.EventEmitter{constructor(e,t){super(),this._hasInsightsErrored=!1,this._log=new On("PreflightTest"),this._networkTiming={},this._options={codecPreferences:[dt.Codec.PCMU,dt.Codec.Opus],edge:"roaming",fakeMicInput:!1,logLevel:"error",signalingTimeoutMs:1e4},this._status=Qr.Status.Connecting,Object.assign(this._options,t),this._samples=[],this._warnings=[],this._startTime=Date.now(),this._initDevice(e,Object.assign(Object.assign({},this._options),{fileInputStream:this._options.fakeMicInput?this._getStreamFromFile():void 0}));const n=["codecPreferences","edge","fakeMicInput","logLevel","signalingTimeoutMs"],i=["audioContext","deviceFactory","fileInputStream","getRTCIceCandidateStatsReport","iceServers","rtcConfiguration"];if(typeof t=="object"){const s=Object.assign({},t);Object.keys(s).forEach(a=>{!n.includes(a)&&!i.includes(a)&&delete s[a],i.includes(a)&&(s[a]=!0)}),this._log.debug(".constructor",JSON.stringify(s))}}stop(){this._log.debug(".stop");const e=new ai.CallCancelledError;this._device?(this._device.once(ft.EventName.Unregistered,()=>this._onFailed(e)),this._device.destroy()):this._onFailed(e)}_emitWarning(e,t,n){const i={name:e,description:t};n&&(i.rtcWarning=n),this._warnings.push(i),this._log.debug(`#${Qr.Events.Warning}`,JSON.stringify(i)),this.emit(Qr.Events.Warning,i)}_getCallQuality(e){return e>4.2?Qr.CallQuality.Excellent:e>=4.1&&e<=4.2?Qr.CallQuality.Great:e>=3.7&&e<=4?Qr.CallQuality.Good:e>=3.1&&e<=3.6?Qr.CallQuality.Fair:Qr.CallQuality.Degraded}_getReport(){var e,t,n;const i=this._getRTCStats(),s={start:this._startTime};this._endTime&&(s.end=this._endTime,s.duration=this._endTime-this._startTime);const a={callSid:this._callSid,edge:this._edge,iceCandidateStats:(t=(e=this._rtcIceCandidateStatsReport)===null||e===void 0?void 0:e.iceCandidateStats)!==null&&t!==void 0?t:[],networkTiming:this._networkTiming,samples:this._samples,selectedEdge:this._options.edge,stats:i,testTiming:s,totals:this._getRTCSampleTotals(),warnings:this._warnings},c=(n=this._rtcIceCandidateStatsReport)===null||n===void 0?void 0:n.selectedIceCandidatePairStats;return c&&(a.selectedIceCandidatePairStats=c,a.isTurnRequired=c.localCandidate.candidateType==="relay"||c.remoteCandidate.candidateType==="relay"),i&&(a.callQuality=this._getCallQuality(i.mos.average)),a}_getRTCSampleTotals(){if(this._latestSample)return Object.assign({},this._latestSample.totals)}_getRTCStats(){const e=this._samples.findIndex(n=>typeof n.mos=="number"&&n.mos>0),t=e>=0?this._samples.slice(e):[];if(!(!t||!t.length))return["jitter","mos","rtt"].reduce((n,i)=>{const s=t.map(a=>a[i]);return Object.assign(Object.assign({},n),{[i]:{average:Number((s.reduce((a,c)=>a+c)/s.length).toPrecision(5)),max:Math.max(...s),min:Math.min(...s)}})},{})}_getStreamFromFile(){const e=this._options.audioContext;if(!e)throw new Fn("Cannot fake input audio stream: AudioContext is not supported by this browser.");const t=new Audio(Fme);t.addEventListener("canplaythrough",()=>t.play()),typeof t.setAttribute=="function"&&t.setAttribute("crossorigin","anonymous");const n=e.createMediaElementSource(t),i=e.createMediaStreamDestination();return n.connect(i),i.stream}_initDevice(e,t){try{this._device=new(t.deviceFactory||ft)(e,{chunderw:t.chunderw,codecPreferences:t.codecPreferences,edge:t.edge,eventgw:t.eventgw,fileInputStream:t.fileInputStream,logLevel:t.logLevel,preflight:!0}),this._device.once(ft.EventName.Registered,()=>{this._onDeviceRegistered()}),this._device.once(ft.EventName.Error,n=>{this._onDeviceError(n)}),this._device.register()}catch(n){setTimeout(()=>{this._onFailed(n)});return}this._signalingTimeoutTimer=setTimeout(()=>{this._onDeviceError(new _s.ConnectionError("WebSocket Connection Timeout"))},t.signalingTimeoutMs)}_onDeviceError(e){this._device.destroy(),this._onFailed(e)}_onDeviceRegistered(){return yi(this,void 0,void 0,function*(){if(clearTimeout(this._echoTimer),clearTimeout(this._signalingTimeoutTimer),this._call=yield this._device.connect({rtcConfiguration:this._options.rtcConfiguration}),this._networkTiming.signaling={start:Date.now()},this._setupCallHandlers(this._call),this._edge=this._device.edge||void 0,this._options.fakeMicInput){this._echoTimer=setTimeout(()=>this._device.disconnectAll(),jme);const t=this._device.audio;t&&(t.disconnect(!1),t.outgoing(!1))}this._call.once("disconnect",()=>{this._device.once(ft.EventName.Unregistered,()=>this._onUnregistered()),this._device.destroy()}),this._call._publisher.on("error",()=>{this._hasInsightsErrored||this._emitWarning("insights-connection-error","Received an error when attempting to connect to Insights gateway"),this._hasInsightsErrored=!0})})}_onFailed(e){clearTimeout(this._echoTimer),clearTimeout(this._signalingTimeoutTimer),this._releaseHandlers(),this._endTime=Date.now(),this._status=Qr.Status.Failed,this._log.debug(`#${Qr.Events.Failed}`,e),this.emit(Qr.Events.Failed,e)}_onUnregistered(){setTimeout(()=>{this._status!==Qr.Status.Failed&&(clearTimeout(this._echoTimer),clearTimeout(this._signalingTimeoutTimer),this._releaseHandlers(),this._endTime=Date.now(),this._status=Qr.Status.Completed,this._report=this._getReport(),this._log.debug(`#${Qr.Events.Completed}`,JSON.stringify(this._report)),this.emit(Qr.Events.Completed,this._report))},10)}_releaseHandlers(){[this._device,this._call].forEach(e=>{e&&e.eventNames().forEach(t=>e.removeAllListeners(t))})}_setupCallHandlers(e){this._options.fakeMicInput&&e.once("volume",()=>{e._mediaHandler.outputs.forEach(t=>t.audio.muted=!0)}),e.on("warning",(t,n)=>{this._emitWarning(t,"Received an RTCWarning. See .rtcWarning for the RTCWarning",n)}),e.once("accept",()=>{this._callSid=e._mediaHandler.callSid,this._status=Qr.Status.Connected,this._log.debug(`#${Qr.Events.Connected}`),this.emit(Qr.Events.Connected)}),e.on("sample",t=>yi(this,void 0,void 0,function*(){this._latestSample||(this._rtcIceCandidateStatsReport=yield(this._options.getRTCIceCandidateStatsReport||lye)(e._mediaHandler.version.pc)),this._latestSample=t,this._samples.push(t),this._log.debug(`#${Qr.Events.Sample}`,JSON.stringify(t)),this.emit(Qr.Events.Sample,t)})),[{reportLabel:"peerConnection",type:"pcconnection"},{reportLabel:"ice",type:"iceconnection"},{reportLabel:"dtls",type:"dtlstransport"},{reportLabel:"signaling",type:"signaling"}].forEach(({type:t,reportLabel:n})=>{const i=`on${t}statechange`,s=e._mediaHandler[i];e._mediaHandler[i]=a=>{const c=this._networkTiming[n]=this._networkTiming[n]||{start:0};a==="connecting"||a==="checking"?c.start=Date.now():(a==="connected"||a==="stable")&&!c.duration&&(c.end=Date.now(),c.duration=c.end-c.start),s(a)}})}get callSid(){return this._callSid}get endTime(){return this._endTime}get latestSample(){return this._latestSample}get report(){return this._report}get startTime(){return this._startTime}get status(){return this._status}}(function(r){(function(e){e.Excellent="excellent",e.Great="great",e.Good="good",e.Fair="fair",e.Degraded="degraded"})(r.CallQuality||(r.CallQuality={})),function(e){e.Completed="completed",e.Connected="connected",e.Failed="failed",e.Sample="sample",e.Warning="warning"}(r.Events||(r.Events={})),function(e){e.Connecting="connecting",e.Connected="connected",e.Completed="completed",e.Failed="failed"}(r.Status||(r.Status={}))})(Qr||(Qr={}));const Bc=globalThis.WebSocket,hye=1e4,pye=5e3,qA=15e3,vye=15e3,gye=1/0,mye=75e3,yye=1e3,_ye=2e4,bye=6e4;var Yi;(function(r){r.Connecting="connecting",r.Closed="closed",r.Open="open"})(Yi||(Yi={}));class lm extends Ss.EventEmitter{constructor(e,t={}){super(),this.state=Yi.Closed,this._backoffStartTime={preferred:null,primary:null},this._connectedUri=null,this._log=new On("WSTransport"),this._retryAfter=null,this._shouldFallback=!1,this._uriIndex=0,this._moveUriIndex=()=>{this._uriIndex++,this._uriIndex>=this._uris.length&&(this._uriIndex=0)},this._onSocketClose=n=>{if(this._log.error(`Received websocket close event code: ${n.code}. Reason: ${n.reason}`),n.code===1006||n.code===1015){this.emit("error",{code:31005,message:n.reason||"Websocket connection to Twilio's signaling servers were unexpectedly ended. If this is happening consistently, there may be an issue resolving the hostname provided. If a region or an edge is being specified in Device setup, ensure it is valid.",twilioError:new _s.ConnectionError});const i=this.state===Yi.Open||this._previousState===Yi.Open;(this._shouldFallback||!i)&&this._moveUriIndex(),this._shouldFallback=!0}this._closeSocket()},this._onSocketError=n=>{this._log.error(`WebSocket received error: ${n.message}`),this.emit("error",{code:31e3,message:n.message||"WSTransport socket error",twilioError:new _s.ConnectionDisconnected})},this._onSocketMessage=n=>{if(this._setHeartbeatTimeout(),this._socket&&n.data===`
|
|
554
|
+
`).map(t=>JSON.parse(t))}applyDeltaIfNeeded(e,t){let n,i,s;if(e.delta){s=!0;const a=new TextEncoder().encode(e.data),c=bme(t,a);n=JSON.parse(new TextDecoder().decode(c)),i=c}else s=!1,n=JSON.parse(e.data),i=new TextEncoder().encode(e.data);return{newData:n,newPrevValue:i,isDelta:s,wireBytes:e.data.length,fullBytes:i.length}}}const Sme={headers:{},token:"",getToken:null,data:null,getData:null,debug:!1,name:"js",version:"",fetch:null,readableStream:null,websocket:null,eventsource:null,sockjs:null,sockjsOptions:{},emulationEndpoint:"/emulation",minReconnectDelay:500,maxReconnectDelay:2e4,timeout:5e3,maxServerPingDelay:1e4,networkEventTarget:null};class fa extends Error{constructor(e){super(e),this.name=this.constructor.name}}class om extends $2{constructor(e,t){super(),this._reconnectTimeout=null,this._refreshTimeout=null,this._serverPingTimeout=null,this.state=Sn.Disconnected,this._transportIsOpen=!1,this._endpoint=e,this._emulation=!1,this._transports=[],this._currentTransportIndex=0,this._triedAllTransports=!1,this._transportWasOpen=!1,this._transport=null,this._transportId=0,this._deviceWentOffline=!1,this._transportClosed=!0,this._codec=new OA,this._reconnecting=!1,this._reconnectTimeout=null,this._reconnectAttempts=0,this._client=null,this._session="",this._node="",this._subs={},this._serverSubs={},this._commandId=0,this._commands=[],this._batching=!1,this._refreshRequired=!1,this._refreshTimeout=null,this._callbacks={},this._token="",this._data=null,this._dispatchPromise=Promise.resolve(),this._serverPing=0,this._serverPingTimeout=null,this._sendPong=!1,this._promises={},this._promiseId=0,this._debugEnabled=!1,this._networkEventsSet=!1,this._config=Object.assign(Object.assign({},Sme),t),this._configure(),this._debugEnabled?(this.on("state",n=>{this._debug("client state",n.oldState,"->",n.newState)}),this.on("error",n=>{this._debug("client error",n)})):this.on("error",function(){Function.prototype()})}newSubscription(e,t){if(this.getSubscription(e)!==null)throw new Error("Subscription to the channel "+e+" already exists");const n=new lme(this,e,t);return this._subs[e]=n,n}newMapSubscription(e,t){if(this.getSubscription(e)!==null)throw new Error("Subscription to the channel "+e+" already exists");const n=new Eb(this,e,{token:t==null?void 0:t.token,getToken:t==null?void 0:t.getToken,data:t==null?void 0:t.data,minResubscribeDelay:t==null?void 0:t.minResubscribeDelay,maxResubscribeDelay:t==null?void 0:t.maxResubscribeDelay,delta:t==null?void 0:t.delta,tagsFilter:t==null?void 0:t.tagsFilter,map:!0,mapPageSize:t==null?void 0:t.pageSize,mapUnrecoverableStrategy:t==null?void 0:t.unrecoverableStrategy});return this._subs[e]=n,n}newMapClientsSubscription(e,t){if(this.getSubscription(e)!==null)throw new Error("Subscription to the channel "+e+" already exists");const n=new Eb(this,e,{token:t==null?void 0:t.token,getToken:t==null?void 0:t.getToken,data:t==null?void 0:t.data,minResubscribeDelay:t==null?void 0:t.minResubscribeDelay,maxResubscribeDelay:t==null?void 0:t.maxResubscribeDelay,delta:t==null?void 0:t.delta,tagsFilter:t==null?void 0:t.tagsFilter,map:!0,mapPresenceType:2,mapPageSize:t==null?void 0:t.pageSize,mapUnrecoverableStrategy:t==null?void 0:t.unrecoverableStrategy});return this._subs[e]=n,n}newMapUsersSubscription(e,t){if(this.getSubscription(e)!==null)throw new Error("Subscription to the channel "+e+" already exists");const n=new Eb(this,e,{token:t==null?void 0:t.token,getToken:t==null?void 0:t.getToken,data:t==null?void 0:t.data,minResubscribeDelay:t==null?void 0:t.minResubscribeDelay,maxResubscribeDelay:t==null?void 0:t.maxResubscribeDelay,delta:t==null?void 0:t.delta,tagsFilter:t==null?void 0:t.tagsFilter,map:!0,mapPresenceType:3,mapPageSize:t==null?void 0:t.pageSize,mapUnrecoverableStrategy:t==null?void 0:t.unrecoverableStrategy});return this._subs[e]=n,n}newSharedPollSubscription(e,t){if(this.getSubscription(e)!==null)throw new Error("Subscription to the channel "+e+" already exists");const n=new dme(this,e,{token:t==null?void 0:t.token,getToken:t==null?void 0:t.getToken,data:t==null?void 0:t.data,minResubscribeDelay:t==null?void 0:t.minResubscribeDelay,maxResubscribeDelay:t==null?void 0:t.maxResubscribeDelay,delta:t==null?void 0:t.delta,sharedPoll:!0,sharedPollGetSignature:t==null?void 0:t.getSignature});return this._subs[e]=n,n}getSubscription(e){return this._getSub(e)}getMapSubscription(e){return this._getSub(e)}getSharedPollSubscription(e){return this._getSub(e)}removeSubscription(e){e&&(e.state!==ii.Unsubscribed&&e.unsubscribe(),this._removeSubscription(e))}removeMapSubscription(e){this.removeSubscription(e)}removeSharedPollSubscription(e){this.removeSubscription(e)}subscriptions(){return this._subs}mapSubscriptions(){const e={};for(const[t,n]of Object.entries(this._subs))n.type==="map"&&(e[t]=n);return e}sharedPollSubscriptions(){const e={};for(const[t,n]of Object.entries(this._subs))n.type==="shared_poll"&&(e[t]=n);return e}ready(e){return wn(this,void 0,void 0,function*(){switch(this.state){case Sn.Disconnected:throw{code:br.clientDisconnected,message:"client disconnected"};case Sn.Connected:return;default:return new Promise((t,n)=>{const i={resolve:t,reject:n};e&&(i.timeout=setTimeout(()=>{n({code:br.timeout,message:"timeout"})},e)),this._promises[this._nextPromiseId()]=i})}})}connect(){if(this._isConnected()){this._debug("connect called when already connected");return}if(this._isConnecting()){this._debug("connect called when already connecting");return}this._debug("connect called"),this._reconnectAttempts=0,this._startConnecting()}disconnect(){this._disconnect(Jc.disconnectCalled,"disconnect called",!1)}setToken(e){this._token=e}setData(e){this._data=e}setHeaders(e){this._config.headers=e}send(e){return wn(this,void 0,void 0,function*(){const t={send:{data:e}};if(yield this._methodCall(),!this._transportSendCommands([t]))throw this._createErrorObject(br.transportWriteError,"transport write error")})}rpc(e,t){return wn(this,void 0,void 0,function*(){const n={rpc:{method:e,data:t}};return yield this._methodCall(),{data:(yield this._callPromise(n,s=>s.rpc)).data}})}publish(e,t){return wn(this,void 0,void 0,function*(){const n={publish:{channel:e,data:t}};return yield this._methodCall(),yield this._callPromise(n,()=>({})),{}})}mapPublish(e,t,n){return wn(this,void 0,void 0,function*(){const i={publish:{channel:e,type:1,key:t,data:n}};return yield this._methodCall(),yield this._callPromise(i,()=>({})),{}})}mapRemove(e,t){return wn(this,void 0,void 0,function*(){const n={publish:{channel:e,type:1,key:t,removed:!0}};return yield this._methodCall(),yield this._callPromise(n,()=>({})),{}})}history(e,t){return wn(this,void 0,void 0,function*(){const n={history:this._getHistoryRequest(e,t)};yield this._methodCall();const i=yield this._callPromise(n,a=>a.history),s=[];if(i.publications)for(let a=0;a<i.publications.length;a++)s.push(this._getPublicationContext(e,i.publications[a]));return{publications:s,epoch:i.epoch||"",offset:i.offset||0}})}presence(e){return wn(this,void 0,void 0,function*(){const t={presence:{channel:e}};yield this._methodCall();const i=(yield this._callPromise(t,s=>s.presence)).presence;for(const s in i)if(Object.prototype.hasOwnProperty.call(i,s)){const a=i[s],c=a.conn_info,o=a.chan_info;c&&(a.connInfo=c),o&&(a.chanInfo=o)}return{clients:i}})}presenceStats(e){return wn(this,void 0,void 0,function*(){const t={presence_stats:{channel:e}};yield this._methodCall();const n=yield this._callPromise(t,i=>i.presence_stats);return{numUsers:n.num_users,numClients:n.num_clients}})}startBatching(){this._batching=!0}stopBatching(){const e=this;Promise.resolve().then(function(){Promise.resolve().then(function(){e._batching=!1,e._flush()})})}_debug(...e){this._debugEnabled&&ome("debug",e)}_codecName(){return this._codec.name()}_formatOverride(){}_configure(){if(!("Promise"in globalThis))throw new Error("Promise polyfill required");if(!this._endpoint)throw new Error("endpoint configuration required");if(this._config.token!==null&&(this._token=this._config.token),this._config.data!==null&&(this._data=this._config.data),this._codec=new OA,this._formatOverride(),(this._config.debug===!0||typeof localStorage<"u"&&typeof localStorage.getItem=="function"&&localStorage.getItem("centrifuge.debug"))&&(this._debugEnabled=!0),this._debug("config",this._config),typeof this._endpoint!="string")if(Array.isArray(this._endpoint)){this._transports=this._endpoint,this._emulation=!0;for(const e in this._transports)if(this._transports.hasOwnProperty(e)){const t=this._transports[e];if(!t.endpoint||!t.transport)throw new Error("malformed transport configuration");const n=t.transport;if(["websocket","http_stream","sse","sockjs","webtransport"].indexOf(n)<0)throw new Error("unsupported transport name: "+n)}}else throw new Error("unsupported url configuration type: only string or array of objects are supported")}_setState(e){if(this.state!==e){this._reconnecting=!1;const t=this.state;return this.state=e,this.emit("state",{newState:e,oldState:t}),!0}return!1}_isDisconnected(){return this.state===Sn.Disconnected}_isConnecting(){return this.state===Sn.Connecting}_isConnected(){return this.state===Sn.Connected}_nextCommandId(){return++this._commandId}_setNetworkEvents(){if(this._networkEventsSet)return;let e=null;this._config.networkEventTarget!==null?e=this._config.networkEventTarget:typeof globalThis.addEventListener<"u"&&(e=globalThis),e&&(e.addEventListener("offline",()=>{this._debug("offline event triggered"),(this.state===Sn.Connected||this.state===Sn.Connecting)&&(this._disconnect(Za.transportClosed,"transport closed",!0),this._deviceWentOffline=!0)}),e.addEventListener("online",()=>{this._debug("online event triggered"),this.state===Sn.Connecting&&(this._deviceWentOffline&&!this._transportClosed&&(this._deviceWentOffline=!1,this._transportClosed=!0),this._clearReconnectTimeout(),this._startReconnecting())}),this._networkEventsSet=!0)}_getReconnectDelay(){const e=Mu(this._reconnectAttempts,this._config.minReconnectDelay,this._config.maxReconnectDelay);return this._reconnectAttempts+=1,e}_clearOutgoingRequests(){for(const e in this._callbacks)if(this._callbacks.hasOwnProperty(e)){const t=this._callbacks[e];clearTimeout(t.timeout);const n=t.errback;if(!n)continue;n({error:this._createErrorObject(br.connectionClosed,"connection closed")})}this._callbacks={}}_clearConnectedState(){this._client=null,this._clearServerPingTimeout(),this._clearRefreshTimeout();for(const e in this._subs){if(!this._subs.hasOwnProperty(e))continue;const t=this._subs[e];t.state===ii.Subscribed&&t._setSubscribing(xv.transportClosed,"transport closed")}for(const e in this._serverSubs)this._serverSubs.hasOwnProperty(e)&&this.emit("subscribing",{channel:e})}_handleWriteError(e){for(const t of e){const n=t.id;if(!(n in this._callbacks))continue;const i=this._callbacks[n];clearTimeout(this._callbacks[n].timeout),delete this._callbacks[n];const s=i.errback;s({error:this._createErrorObject(br.transportWriteError,"transport write error")})}}_transportSendCommands(e){if(!e.length)return!0;if(!this._transport)return!1;try{this._transport.send(this._codec.encodeCommands(e),this._session,this._node)}catch(t){return this._debug("error writing commands",t),this._handleWriteError(e),!1}return!0}_initializeTransport(){let e;this._config.websocket!==null?e=this._config.websocket:typeof globalThis.WebSocket!="function"&&typeof globalThis.WebSocket!="object"||(e=globalThis.WebSocket);let t=null;this._config.sockjs!==null?t=this._config.sockjs:typeof globalThis.SockJS<"u"&&(t=globalThis.SockJS);let n=null;this._config.eventsource!==null?n=this._config.eventsource:typeof globalThis.EventSource<"u"&&(n=globalThis.EventSource);let i=null;this._config.fetch!==null?i=this._config.fetch:typeof globalThis.fetch<"u"&&(i=globalThis.fetch);let s=null;if(this._config.readableStream!==null?s=this._config.readableStream:typeof globalThis.ReadableStream<"u"&&(s=globalThis.ReadableStream),this._emulation){this._currentTransportIndex>=this._transports.length&&(this._triedAllTransports=!0,this._currentTransportIndex=0);let y=0;for(;;){if(y>=this._transports.length)throw new Error("no supported transport found");const w=this._transports[this._currentTransportIndex],k=w.transport,I=w.endpoint;if(k==="websocket"){if(this._debug("trying websocket transport"),this._transport=new AA(I,{websocket:e}),!this._transport.supported()){this._debug("websocket transport not available"),this._currentTransportIndex++,y++;continue}}else if(k==="webtransport"){if(this._debug("trying webtransport transport"),this._transport=new vme(I,{webtransport:globalThis.WebTransport,decoder:this._codec,encoder:this._codec}),!this._transport.supported()){this._debug("webtransport transport not available"),this._currentTransportIndex++,y++;continue}}else if(k==="http_stream"){if(this._debug("trying http_stream transport"),this._transport=new hme(I,{fetch:i,readableStream:s,emulationEndpoint:this._config.emulationEndpoint,decoder:this._codec,encoder:this._codec}),!this._transport.supported()){this._debug("http_stream transport not available"),this._currentTransportIndex++,y++;continue}}else if(k==="sse"){if(this._debug("trying sse transport"),this._transport=new pme(I,{eventsource:n,fetch:i,emulationEndpoint:this._config.emulationEndpoint}),!this._transport.supported()){this._debug("sse transport not available"),this._currentTransportIndex++,y++;continue}}else if(k==="sockjs"){if(this._debug("trying sockjs"),this._transport=new fme(I,{sockjs:t,sockjsOptions:this._config.sockjsOptions}),!this._transport.supported()){this._debug("sockjs transport not available"),this._currentTransportIndex++,y++;continue}}else throw new Error("unknown transport "+k);break}}else{if(ame(this._endpoint,"http"))throw new Error("Provide explicit transport endpoints configuration in case of using HTTP (i.e. using array of TransportEndpoint instead of a single string), or use ws(s):// scheme in an endpoint if you aimed using WebSocket transport");if(this._debug("client will use websocket"),this._transport=new AA(this._endpoint,{websocket:e}),!this._transport.supported())throw new Error("WebSocket constructor not found, make sure it is available globally or passed as a dependency in Centrifuge options")}const a=this,c=this._transport,o=this._nextTransportId();a._debug("id of transport",o);let l=!1;const d=[];if(this._transport.emulation()){const y=a._sendConnect(!0);d.push(y)}this._setNetworkEvents();const h=this._codec.encodeCommands(d);this._transportClosed=!1;let v;v=setTimeout(function(){c.close()},this._config.timeout),this._transport.initialize(this._codecName(),{onOpen:function(){if(v&&(clearTimeout(v),v=null),a._transportId!=o){a._debug("open callback from non-actual transport"),c.close();return}l=!0,a._debug(c.subName(),"transport open"),!c.emulation()&&(a._transportIsOpen=!0,a._transportWasOpen=!0,a.startBatching(),a._sendConnect(!1),a._sendSubscribeCommands(),a.stopBatching(),a.emit("__centrifuge_debug:connect_frame_sent",{}))},onError:function(y){if(a._transportId!=o){a._debug("error callback from non-actual transport");return}a._debug("transport level error",y)},onClose:function(y){if(v&&(clearTimeout(v),v=null),a._transportId!=o){a._debug("close callback from non-actual transport");return}a._debug(c.subName(),"transport closed"),a._transportClosed=!0,a._transportIsOpen=!1;let w="connection closed",k=!0,I=0;if(y&&"code"in y&&y.code&&(I=y.code),y&&y.reason)try{const A=JSON.parse(y.reason);w=A.reason,k=A.reconnect}catch{w=y.reason,(I>=3500&&I<4e3||I>=4500&&I<5e3)&&(k=!1)}I<3e3?(I===1009?(I=Jc.messageSizeLimit,w="message size limit exceeded",k=!1):(I=Za.transportClosed,w="transport closed"),a._emulation&&!a._transportWasOpen&&(a._currentTransportIndex++,a._currentTransportIndex>=a._transports.length&&(a._triedAllTransports=!0,a._currentTransportIndex=0))):a._transportWasOpen=!0,a._isConnecting()&&!l&&a.emit("error",{type:"transport",error:{code:br.transportClosed,message:"transport closed"},transport:c.name()}),a._reconnecting=!1,a._disconnect(I,w,k)},onMessage:function(y){a._dataReceived(y)}},h),a.emit("__centrifuge_debug:transport_initialized",{})}_sendConnect(e){const t=this._constructConnectCommand(),n=this;return this._call(t,e).then(i=>{const s=i.reply.connect;n._connectResponse(s),i.next&&i.next()},i=>{n._connectError(i.error),i.next&&i.next()}),t}_startReconnecting(){if(this._debug("start reconnecting"),!this._isConnecting()){this._debug("stop reconnecting: client not in connecting state");return}if(this._reconnecting){this._debug("reconnect already in progress, return from reconnect routine");return}if(this._transportClosed===!1){this._debug("waiting for transport close");return}this._reconnecting=!0;const e=this._token==="";if(!(this._refreshRequired||e&&this._config.getToken!==null)){this._config.getData?this._config.getData().then(i=>{this._isConnecting()&&(this._data=i,this._initializeTransport())}).catch(i=>this._handleGetDataError(i)):this._initializeTransport();return}const n=this;this._getToken().then(function(i){if(n._isConnecting()){if(i==null||i==null){n._failUnauthorized();return}n._token=i,n._debug("connection token refreshed"),n._config.getData?n._config.getData().then(function(s){n._isConnecting()&&(n._data=s,n._initializeTransport())}).catch(s=>n._handleGetDataError(s)):n._initializeTransport()}}).catch(function(i){if(!n._isConnecting())return;if(i instanceof fa){n._failUnauthorized();return}n.emit("error",{type:"connectToken",error:{code:br.clientConnectToken,message:i!==void 0?i.toString():""}});const s=n._getReconnectDelay();n._debug("error on getting connection token, reconnect after "+s+" milliseconds",i),n._reconnecting=!1,n._reconnectTimeout=setTimeout(()=>{n._startReconnecting()},s)})}_handleGetDataError(e){if(e instanceof fa){this._failUnauthorized();return}this.emit("error",{type:"connectData",error:{code:br.badConfiguration,message:(e==null?void 0:e.toString())||""}});const t=this._getReconnectDelay();this._debug("error on getting connect data, reconnect after "+t+" milliseconds",e),this._reconnecting=!1,this._reconnectTimeout=setTimeout(()=>{this._startReconnecting()},t)}_connectError(e){this.state===Sn.Connecting&&(e.code===109&&(this._refreshRequired=!0),e.code<100||e.temporary===!0||e.code===109?(this.emit("error",{type:"connect",error:e}),this._debug("closing transport due to connect error"),this._disconnect(e.code,e.message,!0)):this._disconnect(e.code,e.message,!1))}_scheduleReconnect(){if(!this._isConnecting())return;let e=!1;this._emulation&&!this._transportWasOpen&&!this._triedAllTransports&&(e=!0);let t=this._getReconnectDelay();e&&(t=0),this._debug("reconnect after "+t+" milliseconds"),this._clearReconnectTimeout(),this._reconnectTimeout=setTimeout(()=>{this._startReconnecting()},t)}_constructConnectCommand(){const e={};this._token&&(e.token=this._token),this._data&&(e.data=this._data),this._config.name&&(e.name=this._config.name),this._config.version&&(e.version=this._config.version),Object.keys(this._config.headers).length>0&&(e.headers=this._config.headers);const t={};let n=!1;for(const i in this._serverSubs)if(this._serverSubs.hasOwnProperty(i)&&this._serverSubs[i].recoverable){n=!0;const s={recover:!0};this._serverSubs[i].offset&&(s.offset=this._serverSubs[i].offset),this._serverSubs[i].epoch&&(s.epoch=this._serverSubs[i].epoch),t[i]=s}return n&&(e.subs=t),{connect:e}}_getHistoryRequest(e,t){const n={channel:e};return t!==void 0&&(t.since&&(n.since={offset:t.since.offset},t.since.epoch&&(n.since.epoch=t.since.epoch)),t.limit!==void 0&&(n.limit=t.limit),t.reverse===!0&&(n.reverse=!0)),n}_methodCall(){return this._isConnected()?Promise.resolve():new Promise((e,t)=>{const n=setTimeout(function(){t({code:br.timeout,message:"timeout"})},this._config.timeout);this._promises[this._nextPromiseId()]={timeout:n,resolve:e,reject:t}})}_callPromise(e,t){return new Promise((n,i)=>{this._call(e,!1).then(s=>{var a;const c=t(s.reply);n(c),(a=s.next)===null||a===void 0||a.call(s)},s=>{var a;i(s.error),(a=s.next)===null||a===void 0||a.call(s)})})}_dataReceived(e){this._serverPing>0&&this._waitServerPing();const t=this._codec.decodeReplies(e);this._dispatchPromise=this._dispatchPromise.then(()=>{let n;this._dispatchPromise=new Promise(i=>{n=i}),this._dispatchSynchronized(t,n)})}_dispatchSynchronized(e,t){let n=Promise.resolve();for(const i in e)e.hasOwnProperty(i)&&(n=n.then(()=>this._dispatchReply(e[i])));n=n.then(()=>{t()})}_dispatchReply(e){let t;const n=new Promise(s=>{t=s});if(e==null)return this._debug("dispatch: got undefined or null reply"),t(),n;const i=e.id;return i&&i>0?this._handleReply(e,t):e.push?this._handlePush(e.push,t):this._handleServerPing(t),n}_call(e,t){return new Promise((n,i)=>{e.id=this._nextCommandId(),this._registerCall(e.id,n,i),t||this._addCommand(e)})}_startConnecting(){this._debug("start connecting"),this._setState(Sn.Connecting)&&this.emit("connecting",{code:Za.connectCalled,reason:"connect called"}),this._client=null,this._startReconnecting()}_disconnect(e,t,n){if(e===Jc.stateInvalidated){this._token="",this._refreshRequired=!0;for(const c in this._subs)this._subs.hasOwnProperty(c)&&this._subs[c]._invalidateState()}if(this._isDisconnected())return;this._transportIsOpen=!1;const i=this.state;this._reconnecting=!1;const s={code:e,reason:t};let a=!1;if(n?a=this._setState(Sn.Connecting):(a=this._setState(Sn.Disconnected),this._rejectPromises({code:br.clientDisconnected,message:"disconnected"})),this._clearOutgoingRequests(),i===Sn.Connecting&&this._clearReconnectTimeout(),i===Sn.Connected&&this._clearConnectedState(),a&&(this._isConnecting()?this.emit("connecting",s):this.emit("disconnected",s)),this._transport){this._debug("closing existing transport");const c=this._transport;this._transport=null,c.close(),this._transportClosed=!0,this._nextTransportId()}else this._debug("no transport to close");this._scheduleReconnect()}_failUnauthorized(){this._disconnect(Jc.unauthorized,"unauthorized",!1)}_getToken(){return this._debug("get connection token"),this._config.getToken?this._config.getToken({}):(this.emit("error",{type:"configuration",error:{code:br.badConfiguration,message:"token expired but no getToken function set in the configuration"}}),Promise.reject(new fa("")))}_refresh(){const e=this._client,t=this;this._getToken().then(function(n){if(e!==t._client)return;if(!n){t._failUnauthorized();return}if(t._token=n,t._debug("connection token refreshed"),!t._isConnected())return;const i={refresh:{token:t._token}};t._call(i,!1).then(s=>{const a=s.reply.refresh;t._refreshResponse(a),s.next&&s.next()},s=>{t._refreshError(s.error),s.next&&s.next()})}).catch(function(n){if(t._isConnected()){if(n instanceof fa){t._failUnauthorized();return}t.emit("error",{type:"refreshToken",error:{code:br.clientRefreshToken,message:n!==void 0?n.toString():""}}),t._refreshTimeout=setTimeout(()=>t._refresh(),t._getRefreshRetryDelay())}})}_refreshError(e){e.code<100||e.temporary===!0?(this.emit("error",{type:"refresh",error:e}),this._refreshTimeout=setTimeout(()=>this._refresh(),this._getRefreshRetryDelay())):this._disconnect(e.code,e.message,!1)}_getRefreshRetryDelay(){return Mu(0,5e3,1e4)}_refreshResponse(e){this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null),e.expires&&(this._client=e.client,this._refreshTimeout=setTimeout(()=>this._refresh(),Hd(e.ttl)))}_removeSubscription(e){e!==null&&delete this._subs[e.channel]}_unsubscribe(e){if(!this._transportIsOpen)return Promise.resolve();const n={unsubscribe:{channel:e.channel}},i=this;return new Promise((a,c)=>{this._call(n,!1).then(o=>{a(),o.next&&o.next()},o=>{a(),o.next&&o.next(),i._disconnect(Za.unsubscribeError,"unsubscribe error",!0)})})}_getSub(e,t){if(t&&t>0){for(const i in this._subs)if(this._subs.hasOwnProperty(i)){const s=this._subs[i];if(s._id===t)return s}return null}const n=this._subs[e];return n||null}_isServerSub(e){return this._serverSubs[e]!==void 0}_sendSubscribeCommands(){const e=[];for(const t in this._subs){if(!this._subs.hasOwnProperty(t))continue;const n=this._subs[t];if(n._inflight!==!0&&n.state===ii.Subscribing){const i=n._subscribe();i&&e.push(i)}}return e}_connectResponse(e){if(this._transportIsOpen=!0,this._transportWasOpen=!0,this._reconnectAttempts=0,this._refreshRequired=!1,this._isConnected())return;this._client=e.client,this._setState(Sn.Connected),this._refreshTimeout&&clearTimeout(this._refreshTimeout),e.expires&&(this._refreshTimeout=setTimeout(()=>this._refresh(),Hd(e.ttl))),this._session=e.session,this._node=e.node,this.startBatching(),this._sendSubscribeCommands(),this.stopBatching();const t={client:e.client,transport:this._transport.subName()};e.data&&(t.data=e.data),this.emit("connected",t),this._resolvePromises(),this._processServerSubs(e.subs||{}),e.ping&&e.ping>0?(this._serverPing=e.ping*1e3,this._sendPong=e.pong===!0,this._waitServerPing()):this._serverPing=0}_processServerSubs(e){for(const t in e){if(!e.hasOwnProperty(t))continue;const n=e[t];this._serverSubs[t]={offset:n.offset,epoch:n.epoch,recoverable:n.recoverable||!1};const i=this._getSubscribeContext(t,n);this.emit("subscribed",i)}for(const t in e){if(!e.hasOwnProperty(t))continue;const n=e[t];if(n.recovered){const i=n.publications;if(i&&i.length>0)for(const s in i)i.hasOwnProperty(s)&&this._handlePublication(t,i[s])}}for(const t in this._serverSubs)this._serverSubs.hasOwnProperty(t)&&(e[t]||(this.emit("unsubscribed",{channel:t}),delete this._serverSubs[t]))}_clearRefreshTimeout(){this._refreshTimeout!==null&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null)}_clearReconnectTimeout(){this._reconnectTimeout!==null&&(clearTimeout(this._reconnectTimeout),this._reconnectTimeout=null)}_clearServerPingTimeout(){this._serverPingTimeout!==null&&(clearTimeout(this._serverPingTimeout),this._serverPingTimeout=null)}_waitServerPing(){this._config.maxServerPingDelay!==0&&this._isConnected()&&(this._clearServerPingTimeout(),this._serverPingTimeout=setTimeout(()=>{this._isConnected()&&this._disconnect(Za.noPing,"no ping",!0)},this._serverPing+this._config.maxServerPingDelay))}_getSubscribeContext(e,t){const n={channel:e,positioned:!1,recoverable:!1,wasRecovering:!1,recovered:!1,hasRecoveredPublications:!1};t.recovered&&(n.recovered=!0),t.positioned&&(n.positioned=!0),t.recoverable&&(n.recoverable=!0),t.was_recovering&&(n.wasRecovering=!0);let i="";"epoch"in t&&(i=t.epoch);let s=0;return"offset"in t&&(s=t.offset),(n.positioned||n.recoverable)&&(n.streamPosition={offset:s,epoch:i}),Array.isArray(t.publications)&&t.publications.length>0&&(n.hasRecoveredPublications=!0),t.data&&(n.data=t.data),n}_handleReply(e,t){const n=e.id;if(!(n in this._callbacks)){t();return}const i=this._callbacks[n];if(clearTimeout(this._callbacks[n].timeout),delete this._callbacks[n],cme(e)){const s=i.errback;if(!s){t();return}const a={code:e.error.code,message:e.error.message||"",temporary:e.error.temporary||!1};s({error:a,next:t})}else{const s=i.callback;if(!s)return;s({reply:e,next:t})}}_handleJoin(e,t,n){const i=this._getSub(e,n);if(!i){if(e&&this._isServerSub(e)){const s={channel:e,info:this._getJoinLeaveContext(t.info)};this.emit("join",s)}return}i._handleJoin(t)}_handleLeave(e,t,n){const i=this._getSub(e,n);if(!i){if(e&&this._isServerSub(e)){const s={channel:e,info:this._getJoinLeaveContext(t.info)};this.emit("leave",s)}return}i._handleLeave(t)}_handleUnsubscribe(e,t){const n=this._getSub(e,0);if(!n&&e){this._isServerSub(e)&&(delete this._serverSubs[e],this.emit("unsubscribed",{channel:e}));return}t.code<2500?n._setUnsubscribed(t.code,t.reason,!1):(t.code===tf.stateInvalidated&&n._invalidateState(),n._setSubscribing(t.code,t.reason))}_handleSubscribe(e,t){this._serverSubs[e]={offset:t.offset,epoch:t.epoch,recoverable:t.recoverable||!1},this.emit("subscribed",this._getSubscribeContext(e,t))}_handleDisconnect(e){const t=e.code;let n=!0;(t>=3500&&t<4e3||t>=4500&&t<5e3)&&(n=!1),this._disconnect(t,e.reason,n)}_getPublicationContext(e,t){const n={channel:e,data:t.data};return t.offset&&(n.offset=t.offset),t.info&&(n.info=this._getJoinLeaveContext(t.info)),t.tags&&(n.tags=t.tags),n}_getJoinLeaveContext(e){const t={client:e.client,user:e.user},n=e.conn_info;n&&(t.connInfo=n);const i=e.chan_info;return i&&(t.chanInfo=i),t}_handlePublication(e,t,n){const i=this._getSub(e,n);if(!i){if(e&&this._isServerSub(e)){const s=this._getPublicationContext(e,t);this.emit("publication",s),t.offset!==void 0&&(this._serverSubs[e].offset=t.offset)}return}i._handlePublication(t)}_handleMessage(e){this.emit("message",{data:e.data})}_handleServerPing(e){if(this._sendPong){const t={};this._transportSendCommands([t])}e()}_handlePush(e,t){const n=e.channel,i=e.id;e.pub?this._handlePublication(n,e.pub,i):e.message?this._handleMessage(e.message):e.join?this._handleJoin(n,e.join,i):e.leave?this._handleLeave(n,e.leave,i):e.unsubscribe?this._handleUnsubscribe(n,e.unsubscribe):e.subscribe?this._handleSubscribe(n,e.subscribe):e.disconnect&&this._handleDisconnect(e.disconnect),t()}_flush(){const e=this._commands.slice(0);this._commands=[],this._transportSendCommands(e)}_createErrorObject(e,t,n){const i={code:e,message:t};return n&&(i.temporary=!0),i}_registerCall(e,t,n){this._callbacks[e]={callback:t,errback:n,timeout:null},this._callbacks[e].timeout=setTimeout(()=>{delete this._callbacks[e],x2(n)&&n({error:this._createErrorObject(br.timeout,"timeout")})},this._config.timeout)}_addCommand(e){this._batching?this._commands.push(e):this._transportSendCommands([e])}_nextPromiseId(){return++this._promiseId}_nextTransportId(){return++this._transportId}_resolvePromises(){for(const e in this._promises)this._promises.hasOwnProperty(e)&&(this._promises[e].timeout&&clearTimeout(this._promises[e].timeout),this._promises[e].resolve(),delete this._promises[e])}_rejectPromises(e){for(const t in this._promises)this._promises.hasOwnProperty(t)&&(this._promises[t].timeout&&clearTimeout(this._promises[t].timeout),this._promises[t].reject(e),delete this._promises[t])}}om.SubscriptionState=ii;om.State=Sn;om.UnauthorizedError=fa;const nn=new an("ujet-chat"),wme=15e3,Tme=15e3,Cme=3e3,Eme=8e3,kme=2e3,kb=50,$A=3,xA=10;function Rme(r){return r.type===_i.USER||r.type===_i.VIRTUAL_AGENT?Fp(r.type,r.id):r.email?Fp(_i.USER,r.id):Fp(_i.VIRTUAL_AGENT,r.id)}function Pme(r){var e;if(/^wss?:\/\//.test(r))return r;if(typeof window>"u"||!((e=window.location)!=null&&e.origin))throw new Error(`Cannot resolve relative websocket URL "${r}" outside a browser context`);return new URL(r,window.location.origin).toString().replace(/^http/,"ws")}function M2(r){const[e,t]=(r.user??"").split("-"),n=r.published_at??r.timestamp;return{...r,$index:r.media_id!=null?`${r.type}-${r.media_id}`:r.message_id,$sid:r.message_id,$timestamp:typeof n=="string"?new Date(n):new Date,$userType:e||_i.SYSTEM,$userId:parseInt(t,10)||0}}function D2(r){return{...r.data,message_id:r.message_id,user:r.user,published_at:r.published_at}}function Ime(r){return M2(D2(r))}function MA(r,e){if(r instanceof Error)return r;const t=r==null?void 0:r.message;return new Error(t?`${e}: ${t}`:e)}class N2 extends Hv{constructor(){super(...arguments);be(this,"client",null);be(this,"subscription",null);be(this,"tenant",null);be(this,"lastAuthError",null);be(this,"conversationEventsRegistered",!1);be(this,"isDestroyed",!1);be(this,"terminalRetryUsed",!1);be(this,"forceTokenRefreshOnce",!1);be(this,"lastMessageId",null);be(this,"lastTypingStartSentAt",0);be(this,"typingClearTimers",new Map);be(this,"pendingHistoryBuffer",null)}async create(){const t=this.providerContext;if(!t)throw new Error("UjetProvider requires a ProviderContext");this.lastAuthError=null,this.isDestroyed=!1,this.terminalRetryUsed=!1,this.forceTokenRefreshOnce=!1;const n=new om(Pme(t.wsUrl),{getData:async()=>{const i=this.forceTokenRefreshOnce;this.forceTokenRefreshOnce=!1;try{return{token:await t.getAuthToken(i)}}catch(s){throw s instanceof Xc?(this.lastAuthError=s,new fa(s.message)):s}}});n.on("connected",i=>{var s;this.tenant=(s=i.data)==null?void 0:s.tenant,this.terminalRetryUsed=!1,nn.info("client: connected",{transport:i.transport})}),n.once("connected",()=>{n.on("disconnected",i=>this.onTerminalDisconnect(n,i))}),n.on("error",i=>{i.type==="configuration"?nn.info("client: configuration error at token expiry",{error:i.error}):nn.warn("client: transport error",{type:i.type,error:i.error})}),n.connect();try{await n.ready(wme)}catch(i){throw n.disconnect(),nn.warn("client: connection failed",{error:i}),this.lastAuthError??MA(i,"Ujet chat connection failed")}this.client=n,this.events.triggerEvent("initialized")}async join(t){if(!this.client)throw new Error("UjetProvider.join called before create()");if(!this.tenant)throw new Error("Ujet chat connect reply carried no tenant");const n=`chats:${this.tenant}:${t}`,i=this.client.getSubscription(n),s=i??this.client.newSubscription(n);this.subscription=s,i||this.registerConversationEvents(),this.pendingHistoryBuffer=[],s.subscribe();try{await s.ready(Tme)}catch(a){throw nn.warn("subscription: failed",{channel:n,error:a}),MA(a,`Ujet chat subscription failed for ${n}`)}nn.info("subscription: established",{channel:n})}onTerminalDisconnect(t,n){if(!this.isDestroyed){if(this.lastAuthError||this.terminalRetryUsed){nn.warn("client: connection ended",{code:n.code,reason:n.reason,authRejected:this.lastAuthError!=null}),this.events.triggerEvent("error",new Error("Chat connection ended"));return}this.terminalRetryUsed=!0,this.forceTokenRefreshOnce=!0,nn.info("client: terminal disconnect, reconnecting once",{code:n.code,reason:n.reason}),t.connect()}}registerConversationEvents(){this.conversationEventsRegistered||!this.subscription||(this.conversationEventsRegistered=!0,this.subscription.on("publication",({data:t,info:n})=>this.onPublication(t,n)),this.subscription.on("subscribed",t=>{t.wasRecovering&&!t.recovered&&this.backfillFromHistory()}))}onPublication(t,n){switch(t==null?void 0:t.type){case ln.TYPING:this.handleTypingPublication(t,n);return;case ln.PREVIEW:return;case ln.TRANSLATION_UPDATE:return;default:{if(!(t!=null&&t.message_id)){nn.warn("persistent publication without message_id",{type:t==null?void 0:t.type,user:t==null?void 0:t.user});return}if(this.pendingHistoryBuffer){this.pendingHistoryBuffer.push(t);return}this.events.triggerEvent("message",this.ingestPersistentMessage(t))}}}ingestPersistentMessage(t){var i;const n=M2(t);return nn.info("publication: message",{index:n.$index,sid:n.$sid,timestamp:n.$timestamp,userType:n.$userType}),this.lastMessageId=n.$sid,this.clearTypingIndicator(t.user),this.trackInTask(n),n.$userType!==_i.END_USER&&this.ping(),n.type===ln.NOTI&&(n.event===Gn.MEMBER_JOINED||n.event===Gn.MEMBER_LEFT)&&this.events.triggerEvent(n.event,t.memberIdentity),n.type===ln.NOTI&&n.event===Gn.ESCALATION_ACCEPTED&&((i=t.to_agent)==null?void 0:i.id)!=null&&this.events.triggerEvent("memberJoined",Rme(t.to_agent)),n}drainHistoryBuffer(t){const n=this.pendingHistoryBuffer??[];return this.pendingHistoryBuffer=null,n.filter(i=>!t.has(i.message_id))}handleTypingPublication(t,n){const i=n==null?void 0:n.user;!i||i.startsWith(_i.END_USER)||(t.action==="start"?(this.events.triggerEvent("typingStarted",i),this.armTypingClear(i,Eme)):t.action==="stop"&&this.armTypingClear(i,kme))}armTypingClear(t,n){clearTimeout(this.typingClearTimers.get(t)),this.typingClearTimers.set(t,setTimeout(()=>{this.typingClearTimers.delete(t),this.events.triggerEvent("typingEnded",t)},n))}clearTypingIndicator(t){const n=this.typingClearTimers.get(t);n!=null&&(clearTimeout(n),this.typingClearTimers.delete(t),this.events.triggerEvent("typingEnded",t))}backfillFromHistory(){const t=this.providerContext;!t||this.pendingHistoryBuffer||(this.pendingHistoryBuffer=[],this.runBackfill(t).catch(n=>{nn.warn("backfill: failed",{error:n})}))}async runBackfill(t){var o;const n=this.subscription,i=this.lastMessageId,s=[],a=new Set;try{let l=null;for(let d=0;;d++){if(d>=xA){nn.warn("backfill: page cap reached, proceeding with the collected range",{cap:xA,stopPoint:i});break}const h=await this.fetchHistoryPage(t,l==null?{limit:kb}:{limit:kb,before:l});if(this.subscription!==n)return;for(const y of h.messages)a.add(y.message_id),!(i!=null&&y.message_id<=i)&&((o=y.data)==null?void 0:o.type)!==ln.TRANSLATION_UPDATE&&s.push(D2(y));if(i==null)break;const v=h.messages[h.messages.length-1];if(v==null||v.message_id<=i||!h.has_more||h.next_cursor==null)break;l=h.next_cursor}}catch(l){if(nn.warn("backfill: fetch failed, flushing the window buffer live",{error:l}),this.subscription===n)for(const d of this.drainHistoryBuffer(new Set))this.events.triggerEvent("message",this.ingestPersistentMessage(d));return}const c=this.drainHistoryBuffer(a);nn.info("backfill: emitting the missed range",{collected:s.length,flushed:c.length,stopPoint:i}),s.reverse();for(const l of[...s,...c])this.events.triggerEvent("message",this.ingestPersistentMessage(l))}async destroy(){var t;this.isDestroyed=!0,this.cleanupAudio(),this.subscription&&(this.subscription.unsubscribe(),(t=this.client)==null||t.removeSubscription(this.subscription),this.subscription=null),this.pendingHistoryBuffer=null,this.lastTypingStartSentAt=0;for(const n of this.typingClearTimers.values())clearTimeout(n);this.typingClearTimers.clear(),this.client&&(this.client.disconnect(),this.client=null),this.tenant=null,this.lastMessageId=null,this.lastAuthError=null,this.conversationEventsRegistered=!1}async sendMessage(t){if(!this.subscription)return nn.warn("publish: no active subscription",{type:t.type}),"";try{await this.subscription.publish({...t})}catch(n){return nn.warn("publish: message failed",{type:t.type,error:n}),""}return t.media_id!=null?`${t.type}-${t.media_id}`:""}async preview(t){if(!this.subscription){nn.warn("publish: no active subscription",{type:ln.PREVIEW});return}try{await this.subscription.publish({type:ln.PREVIEW,text:t??""})}catch(n){nn.warn("publish: preview failed",{error:n})}}startTyping(){var n;const t=Date.now();t-this.lastTypingStartSentAt<Cme||(this.lastTypingStartSentAt=t,(n=this.subscription)==null||n.publish({type:ln.TYPING,action:"start"}).catch(i=>nn.warn("publish: typing start failed",{error:i})))}stopTyping(){var t;this.lastTypingStartSentAt!==0&&(this.lastTypingStartSentAt=0,(t=this.subscription)==null||t.publish({type:ln.TYPING,action:"stop"}).catch(n=>nn.warn("publish: typing stop failed",{error:n})))}async fetchMessages(t){const n=this.providerContext;if(!n)throw new Error("UjetProvider requires a ProviderContext");let i;try{i=await this.fetchHistoryPage(n,{limit:kb})}catch(o){nn.warn("history: fetch failed, flushing the window buffer live",{error:o});for(const l of this.drainHistoryBuffer(new Set))this.events.triggerEvent("message",this.ingestPersistentMessage(l));throw o}const s=i.messages.filter(o=>{var l;return((l=o.data)==null?void 0:l.type)!==ln.TRANSLATION_UPDATE});s.length>0&&(this.lastMessageId=s[0].message_id),s.reverse();const a=s.map(o=>{const l=Ime(o);this.trackInTask(l);const d=t[l.$index];return d&&(l.file=d),l}),c=this.drainHistoryBuffer(new Set(i.messages.map(o=>o.message_id))).map(o=>this.ingestPersistentMessage(o));return[...a,...c]}async fetchHistoryPage(t,n){let i=await t.fetchHistory(n);for(let s=0;s<$A&&i.retry_after_ms!=null;s++)nn.info("history: not yet persisted, re-fetching",{attempt:s+1,retryAfterMs:i.retry_after_ms}),await sv(i.retry_after_ms),i=await t.fetchHistory(n);return i.retry_after_ms!=null&&nn.warn("history: retry cap reached, proceeding with the current page",{limit:$A,retryAfterMs:i.retry_after_ms}),i}}be(N2,"type",Wu.UJET);Gv(N2);var TT={exports:{}},al=typeof Reflect=="object"?Reflect:null,DA=al&&typeof al.apply=="function"?al.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)},rv;al&&typeof al.ownKeys=="function"?rv=al.ownKeys:Object.getOwnPropertySymbols?rv=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:rv=function(e){return Object.getOwnPropertyNames(e)};function Ame(r){console&&console.warn&&console.warn(r)}var L2=Number.isNaN||function(e){return e!==e};function Fr(){Fr.init.call(this)}TT.exports=Fr;TT.exports.once=Mme;Fr.EventEmitter=Fr;Fr.prototype._events=void 0;Fr.prototype._eventsCount=0;Fr.prototype._maxListeners=void 0;var NA=10;function um(r){if(typeof r!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof r)}Object.defineProperty(Fr,"defaultMaxListeners",{enumerable:!0,get:function(){return NA},set:function(r){if(typeof r!="number"||r<0||L2(r))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+r+".");NA=r}});Fr.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};Fr.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||L2(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function U2(r){return r._maxListeners===void 0?Fr.defaultMaxListeners:r._maxListeners}Fr.prototype.getMaxListeners=function(){return U2(this)};Fr.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var i=e==="error",s=this._events;if(s!==void 0)i=i&&s.error===void 0;else if(!i)return!1;if(i){var a;if(t.length>0&&(a=t[0]),a instanceof Error)throw a;var c=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw c.context=a,c}var o=s[e];if(o===void 0)return!1;if(typeof o=="function")DA(o,this,t);else for(var l=o.length,d=W2(o,l),n=0;n<l;++n)DA(d[n],this,t);return!0};function F2(r,e,t,n){var i,s,a;if(um(t),s=r._events,s===void 0?(s=r._events=Object.create(null),r._eventsCount=0):(s.newListener!==void 0&&(r.emit("newListener",e,t.listener?t.listener:t),s=r._events),a=s[e]),a===void 0)a=s[e]=t,++r._eventsCount;else if(typeof a=="function"?a=s[e]=n?[t,a]:[a,t]:n?a.unshift(t):a.push(t),i=U2(r),i>0&&a.length>i&&!a.warned){a.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=r,c.type=e,c.count=a.length,Ame(c)}return r}Fr.prototype.addListener=function(e,t){return F2(this,e,t,!1)};Fr.prototype.on=Fr.prototype.addListener;Fr.prototype.prependListener=function(e,t){return F2(this,e,t,!0)};function Ome(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function j2(r,e,t){var n={fired:!1,wrapFn:void 0,target:r,type:e,listener:t},i=Ome.bind(n);return i.listener=t,n.wrapFn=i,i}Fr.prototype.once=function(e,t){return um(t),this.on(e,j2(this,e,t)),this};Fr.prototype.prependOnceListener=function(e,t){return um(t),this.prependListener(e,j2(this,e,t)),this};Fr.prototype.removeListener=function(e,t){var n,i,s,a,c;if(um(t),i=this._events,i===void 0)return this;if(n=i[e],n===void 0)return this;if(n===t||n.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||t));else if(typeof n!="function"){for(s=-1,a=n.length-1;a>=0;a--)if(n[a]===t||n[a].listener===t){c=n[a].listener,s=a;break}if(s<0)return this;s===0?n.shift():$me(n,s),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,c||t)}return this};Fr.prototype.off=Fr.prototype.removeListener;Fr.prototype.removeAllListeners=function(e){var t,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var s=Object.keys(n),a;for(i=0;i<s.length;++i)a=s[i],a!=="removeListener"&&this.removeAllListeners(a);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(t=n[e],typeof t=="function")this.removeListener(e,t);else if(t!==void 0)for(i=t.length-1;i>=0;i--)this.removeListener(e,t[i]);return this};function B2(r,e,t){var n=r._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?t?[i.listener||i]:[i]:t?xme(i):W2(i,i.length)}Fr.prototype.listeners=function(e){return B2(this,e,!0)};Fr.prototype.rawListeners=function(e){return B2(this,e,!1)};Fr.listenerCount=function(r,e){return typeof r.listenerCount=="function"?r.listenerCount(e):q2.call(r,e)};Fr.prototype.listenerCount=q2;function q2(r){var e=this._events;if(e!==void 0){var t=e[r];if(typeof t=="function")return 1;if(t!==void 0)return t.length}return 0}Fr.prototype.eventNames=function(){return this._eventsCount>0?rv(this._events):[]};function W2(r,e){for(var t=new Array(e),n=0;n<e;++n)t[n]=r[n];return t}function $me(r,e){for(;e+1<r.length;e++)r[e]=r[e+1];r.pop()}function xme(r){for(var e=new Array(r.length),t=0;t<e.length;++t)e[t]=r[t].listener||r[t];return e}function Mme(r,e){return new Promise(function(t,n){function i(a){r.removeListener(e,s),n(a)}function s(){typeof r.removeListener=="function"&&r.removeListener("error",i),t([].slice.call(arguments))}V2(r,e,s,{once:!0}),e!=="error"&&Dme(r,i,{once:!0})})}function Dme(r,e,t){typeof r.on=="function"&&V2(r,"error",e,t)}function V2(r,e,t,n){if(typeof r.on=="function")n.once?r.once(e,t):r.on(e,t);else if(typeof r.addEventListener=="function")r.addEventListener(e,function i(s){n.once&&r.removeEventListener(e,i),t(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof r)}var Ss=TT.exports;class gw extends Ss.EventEmitter{constructor(e){super(),Object.defineProperties(this,{_attempts:{value:0,writable:!0},_duration:{enumerable:!1,get(){if(this._useInitialValue&&this._attempts===0)return this._min;let t=this._min*Math.pow(this._factor,this._attempts);if(this._jitter){const n=Math.random(),i=Math.floor(n*this._jitter*t);t=Math.floor(n*10)&1?t+i:t-i}return Math.min(t,this._max)|0}},_factor:{value:e.factor||2},_jitter:{value:e.jitter>0&&e.jitter<=1?e.jitter:0},_max:{value:e.max||1e4},_min:{value:e.min||100},_timeoutID:{value:null,writable:!0},_useInitialValue:{value:e.useInitialValue||!1}})}backoff(){const e=this._duration;this._timeoutID&&(clearTimeout(this._timeoutID),this._timeoutID=null),this.emit("backoff",this._attempts,e),this._timeoutID=setTimeout(()=>{this.emit("ready",this._attempts,e),this._attempts++},e)}reset(){this._attempts=0,this._timeoutID&&(clearTimeout(this._timeoutID),this._timeoutID=null)}}function yi(r,e,t,n){function i(s){return s instanceof t?s:new t(function(a){a(s)})}return new(t||(t=Promise))(function(s,a){function c(d){try{l(n.next(d))}catch(h){a(h)}}function o(d){try{l(n.throw(d))}catch(h){a(h)}}function l(d){d.done?s(d.value):i(d.value).then(c,o)}l((n=n.apply(r,e||[])).next())})}class rr extends Error{constructor(e,t){super(),Object.setPrototypeOf(this,rr.prototype);const n=typeof e=="string"?e:this.explanation,i=typeof e=="object"?e:t;this.message=`${this.name} (${this.code}): ${n}`,this.originalError=i}}var In;(function(r){class e extends rr{constructor(s,a){super(s,a),this.causes=[],this.code=20101,this.description="Invalid access token",this.explanation="Twilio was unable to validate your Access Token",this.name="AccessTokenInvalid",this.solutions=[],Object.setPrototypeOf(this,r.AccessTokenInvalid.prototype);const c=typeof s=="string"?s:this.explanation,o=typeof s=="object"?s:a;this.message=`${this.name} (${this.code}): ${c}`,this.originalError=o}}r.AccessTokenInvalid=e;class t extends rr{constructor(s,a){super(s,a),this.causes=[],this.code=20104,this.description="Access token expired or expiration date invalid",this.explanation="The Access Token provided to the Twilio API has expired, the expiration time specified in the token was invalid, or the expiration time specified was too far in the future",this.name="AccessTokenExpired",this.solutions=[],Object.setPrototypeOf(this,r.AccessTokenExpired.prototype);const c=typeof s=="string"?s:this.explanation,o=typeof s=="object"?s:a;this.message=`${this.name} (${this.code}): ${c}`,this.originalError=o}}r.AccessTokenExpired=t;class n extends rr{constructor(s,a){super(s,a),this.causes=[],this.code=20151,this.description="Authentication Failed",this.explanation="The Authentication with the provided JWT failed",this.name="AuthenticationFailed",this.solutions=[],Object.setPrototypeOf(this,r.AuthenticationFailed.prototype);const c=typeof s=="string"?s:this.explanation,o=typeof s=="object"?s:a;this.message=`${this.name} (${this.code}): ${c}`,this.originalError=o}}r.AuthenticationFailed=n})(In||(In={}));var mw;(function(r){class e extends rr{constructor(n,i){super(n,i),this.causes=["The access token has an invalid Account SID, API Key, or API Key Secret."],this.code=31202,this.description="Signature validation failed.",this.explanation="The provided access token failed signature validation.",this.name="AccessTokenSignatureValidationFailed",this.solutions=["Ensure the Account SID, API Key, and API Key Secret are valid when generating your access token."],Object.setPrototypeOf(this,r.AccessTokenSignatureValidationFailed.prototype);const s=typeof n=="string"?n:this.explanation,a=typeof n=="object"?n:i;this.message=`${this.name} (${this.code}): ${s}`,this.originalError=a}}r.AccessTokenSignatureValidationFailed=e})(mw||(mw={}));var Nu;(function(r){class e extends rr{constructor(a,c){super(a,c),this.causes=[],this.code=31400,this.description="Bad Request (HTTP/SIP)",this.explanation="The request could not be understood due to malformed syntax.",this.name="BadRequest",this.solutions=[],Object.setPrototypeOf(this,r.BadRequest.prototype);const o=typeof a=="string"?a:this.explanation,l=typeof a=="object"?a:c;this.message=`${this.name} (${this.code}): ${o}`,this.originalError=l}}r.BadRequest=e;class t extends rr{constructor(a,c){super(a,c),this.causes=["The outbound call was made to an invalid phone number.","The TwiML application sid is missing a Voice URL."],this.code=31404,this.description="Not Found (HTTP/SIP)",this.explanation="The server has not found anything matching the request.",this.name="NotFound",this.solutions=["Ensure the phone number dialed is valid.","Ensure the TwiML application is configured correctly with a Voice URL link."],Object.setPrototypeOf(this,r.NotFound.prototype);const o=typeof a=="string"?a:this.explanation,l=typeof a=="object"?a:c;this.message=`${this.name} (${this.code}): ${o}`,this.originalError=l}}r.NotFound=t;class n extends rr{constructor(a,c){super(a,c),this.causes=[],this.code=31480,this.description="Temporarily Unavailable (SIP)",this.explanation="The callee is currently unavailable.",this.name="TemporarilyUnavailable",this.solutions=[],Object.setPrototypeOf(this,r.TemporarilyUnavailable.prototype);const o=typeof a=="string"?a:this.explanation,l=typeof a=="object"?a:c;this.message=`${this.name} (${this.code}): ${o}`,this.originalError=l}}r.TemporarilyUnavailable=n;class i extends rr{constructor(a,c){super(a,c),this.causes=[],this.code=31486,this.description="Busy Here (SIP)",this.explanation="The callee is busy.",this.name="BusyHere",this.solutions=[],Object.setPrototypeOf(this,r.BusyHere.prototype);const o=typeof a=="string"?a:this.explanation,l=typeof a=="object"?a:c;this.message=`${this.name} (${this.code}): ${o}`,this.originalError=l}}r.BusyHere=i})(Nu||(Nu={}));var yw;(function(r){class e extends rr{constructor(n,i){super(n,i),this.causes=[],this.code=31603,this.description="Decline (SIP)",this.explanation="The callee does not wish to participate in the call.",this.name="Decline",this.solutions=[],Object.setPrototypeOf(this,r.Decline.prototype);const s=typeof n=="string"?n:this.explanation,a=typeof n=="object"?n:i;this.message=`${this.name} (${this.code}): ${s}`,this.originalError=a}}r.Decline=e})(yw||(yw={}));var ai;(function(r){class e extends rr{constructor(l,d){super(l,d),this.causes=[],this.code=31e3,this.description="Unknown Error",this.explanation="An unknown error has occurred. See error details for more information.",this.name="UnknownError",this.solutions=[],Object.setPrototypeOf(this,r.UnknownError.prototype);const h=typeof l=="string"?l:this.explanation,v=typeof l=="object"?l:d;this.message=`${this.name} (${this.code}): ${h}`,this.originalError=v}}r.UnknownError=e;class t extends rr{constructor(l,d){super(l,d),this.causes=[],this.code=31001,this.description="Application Not Found",this.explanation="",this.name="ApplicationNotFoundError",this.solutions=[],Object.setPrototypeOf(this,r.ApplicationNotFoundError.prototype);const h=typeof l=="string"?l:this.explanation,v=typeof l=="object"?l:d;this.message=`${this.name} (${this.code}): ${h}`,this.originalError=v}}r.ApplicationNotFoundError=t;class n extends rr{constructor(l,d){super(l,d),this.causes=[],this.code=31002,this.description="Connection Declined",this.explanation="",this.name="ConnectionDeclinedError",this.solutions=[],Object.setPrototypeOf(this,r.ConnectionDeclinedError.prototype);const h=typeof l=="string"?l:this.explanation,v=typeof l=="object"?l:d;this.message=`${this.name} (${this.code}): ${h}`,this.originalError=v}}r.ConnectionDeclinedError=n;class i extends rr{constructor(l,d){super(l,d),this.causes=[],this.code=31003,this.description="Connection Timeout",this.explanation="The server could not produce a response within a suitable amount of time.",this.name="ConnectionTimeoutError",this.solutions=[],Object.setPrototypeOf(this,r.ConnectionTimeoutError.prototype);const h=typeof l=="string"?l:this.explanation,v=typeof l=="object"?l:d;this.message=`${this.name} (${this.code}): ${h}`,this.originalError=v}}r.ConnectionTimeoutError=i;class s extends rr{constructor(l,d){super(l,d),this.causes=[],this.code=31005,this.description="Connection error",this.explanation="A connection error occurred during the call",this.name="ConnectionError",this.solutions=[],Object.setPrototypeOf(this,r.ConnectionError.prototype);const h=typeof l=="string"?l:this.explanation,v=typeof l=="object"?l:d;this.message=`${this.name} (${this.code}): ${h}`,this.originalError=v}}r.ConnectionError=s;class a extends rr{constructor(l,d){super(l,d),this.causes=["The incoming call was cancelled because it was not answered in time or it was accepted/rejected by another application instance registered with the same identity."],this.code=31008,this.description="Call cancelled",this.explanation="Unable to answer because the call has ended",this.name="CallCancelledError",this.solutions=[],Object.setPrototypeOf(this,r.CallCancelledError.prototype);const h=typeof l=="string"?l:this.explanation,v=typeof l=="object"?l:d;this.message=`${this.name} (${this.code}): ${h}`,this.originalError=v}}r.CallCancelledError=a;class c extends rr{constructor(l,d){super(l,d),this.causes=[],this.code=31009,this.description="Transport error",this.explanation="No transport available to send or receive messages",this.name="TransportError",this.solutions=[],Object.setPrototypeOf(this,r.TransportError.prototype);const h=typeof l=="string"?l:this.explanation,v=typeof l=="object"?l:d;this.message=`${this.name} (${this.code}): ${h}`,this.originalError=v}}r.TransportError=c})(ai||(ai={}));var Ja;(function(r){class e extends rr{constructor(l,d){super(l,d),this.causes=["Invalid content or MessageType passed to sendMessage method."],this.code=31100,this.description="The request had malformed syntax.",this.explanation="The request could not be understood due to malformed syntax.",this.name="MalformedRequestError",this.solutions=["Ensure content and MessageType passed to sendMessage method are valid."],Object.setPrototypeOf(this,r.MalformedRequestError.prototype);const h=typeof l=="string"?l:this.explanation,v=typeof l=="object"?l:d;this.message=`${this.name} (${this.code}): ${h}`,this.originalError=v}}r.MalformedRequestError=e;class t extends rr{constructor(l,d){super(l,d),this.causes=[],this.code=31101,this.description="Missing parameter array in request",this.explanation="",this.name="MissingParameterArrayError",this.solutions=[],Object.setPrototypeOf(this,r.MissingParameterArrayError.prototype);const h=typeof l=="string"?l:this.explanation,v=typeof l=="object"?l:d;this.message=`${this.name} (${this.code}): ${h}`,this.originalError=v}}r.MissingParameterArrayError=t;class n extends rr{constructor(l,d){super(l,d),this.causes=[],this.code=31102,this.description="Authorization token missing in request.",this.explanation="",this.name="AuthorizationTokenMissingError",this.solutions=[],Object.setPrototypeOf(this,r.AuthorizationTokenMissingError.prototype);const h=typeof l=="string"?l:this.explanation,v=typeof l=="object"?l:d;this.message=`${this.name} (${this.code}): ${h}`,this.originalError=v}}r.AuthorizationTokenMissingError=n;class i extends rr{constructor(l,d){super(l,d),this.causes=[],this.code=31103,this.description="Maximum parameter length has been exceeded.",this.explanation="Length of parameters cannot exceed MAX_PARAM_LENGTH.",this.name="MaxParameterLengthExceededError",this.solutions=[],Object.setPrototypeOf(this,r.MaxParameterLengthExceededError.prototype);const h=typeof l=="string"?l:this.explanation,v=typeof l=="object"?l:d;this.message=`${this.name} (${this.code}): ${h}`,this.originalError=v}}r.MaxParameterLengthExceededError=i;class s extends rr{constructor(l,d){super(l,d),this.causes=[],this.code=31104,this.description="Invalid bridge token",this.explanation="",this.name="InvalidBridgeTokenError",this.solutions=[],Object.setPrototypeOf(this,r.InvalidBridgeTokenError.prototype);const h=typeof l=="string"?l:this.explanation,v=typeof l=="object"?l:d;this.message=`${this.name} (${this.code}): ${h}`,this.originalError=v}}r.InvalidBridgeTokenError=s;class a extends rr{constructor(l,d){super(l,d),this.causes=["Client name contains invalid characters."],this.code=31105,this.description="Invalid client name",this.explanation="Client name should not contain control, space, delims, or unwise characters.",this.name="InvalidClientNameError",this.solutions=["Make sure that client name does not contain any of the invalid characters."],Object.setPrototypeOf(this,r.InvalidClientNameError.prototype);const h=typeof l=="string"?l:this.explanation,v=typeof l=="object"?l:d;this.message=`${this.name} (${this.code}): ${h}`,this.originalError=v}}r.InvalidClientNameError=a;class c extends rr{constructor(l,d){super(l,d),this.causes=[],this.code=31107,this.description="The reconnect parameter is invalid",this.explanation="",this.name="ReconnectParameterInvalidError",this.solutions=[],Object.setPrototypeOf(this,r.ReconnectParameterInvalidError.prototype);const h=typeof l=="string"?l:this.explanation,v=typeof l=="object"?l:d;this.message=`${this.name} (${this.code}): ${h}`,this.originalError=v}}r.ReconnectParameterInvalidError=c})(Ja||(Ja={}));(function(r){class e extends rr{constructor(h,v){super(h,v),this.causes=[],this.code=31201,this.description="Authorization error",this.explanation="The request requires user authentication. The server understood the request, but is refusing to fulfill it.",this.name="AuthorizationError",this.solutions=[],Object.setPrototypeOf(this,r.AuthorizationError.prototype);const y=typeof h=="string"?h:this.explanation,w=typeof h=="object"?h:v;this.message=`${this.name} (${this.code}): ${y}`,this.originalError=w}}r.AuthorizationError=e;class t extends rr{constructor(h,v){super(h,v),this.causes=[],this.code=31203,this.description="No valid account",this.explanation="",this.name="NoValidAccountError",this.solutions=[],Object.setPrototypeOf(this,r.NoValidAccountError.prototype);const y=typeof h=="string"?h:this.explanation,w=typeof h=="object"?h:v;this.message=`${this.name} (${this.code}): ${y}`,this.originalError=w}}r.NoValidAccountError=t;class n extends rr{constructor(h,v){super(h,v),this.causes=[],this.code=31204,this.description="Invalid JWT token",this.explanation="",this.name="InvalidJWTTokenError",this.solutions=[],Object.setPrototypeOf(this,r.InvalidJWTTokenError.prototype);const y=typeof h=="string"?h:this.explanation,w=typeof h=="object"?h:v;this.message=`${this.name} (${this.code}): ${y}`,this.originalError=w}}r.InvalidJWTTokenError=n;class i extends rr{constructor(h,v){super(h,v),this.causes=[],this.code=31205,this.description="JWT token expired",this.explanation="",this.name="JWTTokenExpiredError",this.solutions=[],Object.setPrototypeOf(this,r.JWTTokenExpiredError.prototype);const y=typeof h=="string"?h:this.explanation,w=typeof h=="object"?h:v;this.message=`${this.name} (${this.code}): ${y}`,this.originalError=w}}r.JWTTokenExpiredError=i;class s extends rr{constructor(h,v){super(h,v),this.causes=["Rate limit exceeded."],this.code=31206,this.description="Rate exceeded authorized limit.",this.explanation="The request performed exceeds the authorized limit.",this.name="RateExceededError",this.solutions=["Ensure message send rate does not exceed authorized limits."],Object.setPrototypeOf(this,r.RateExceededError.prototype);const y=typeof h=="string"?h:this.explanation,w=typeof h=="object"?h:v;this.message=`${this.name} (${this.code}): ${y}`,this.originalError=w}}r.RateExceededError=s;class a extends rr{constructor(h,v){super(h,v),this.causes=[],this.code=31207,this.description="JWT token expiration too long",this.explanation="",this.name="JWTTokenExpirationTooLongError",this.solutions=[],Object.setPrototypeOf(this,r.JWTTokenExpirationTooLongError.prototype);const y=typeof h=="string"?h:this.explanation,w=typeof h=="object"?h:v;this.message=`${this.name} (${this.code}): ${y}`,this.originalError=w}}r.JWTTokenExpirationTooLongError=a;class c extends rr{constructor(h,v){super(h,v),this.causes=[],this.code=31209,this.description="Reconnect attempt is not authorized.",this.explanation="",this.name="ReconnectAttemptError",this.solutions=[],Object.setPrototypeOf(this,r.ReconnectAttemptError.prototype);const y=typeof h=="string"?h:this.explanation,w=typeof h=="object"?h:v;this.message=`${this.name} (${this.code}): ${y}`,this.originalError=w}}r.ReconnectAttemptError=c;class o extends rr{constructor(h,v){super(h,v),this.causes=["The Call Message Event Type is invalid and is not understood by Twilio Voice."],this.code=31210,this.description="Call Message Event Type is invalid.",this.explanation="The Call Message Event Type is invalid and is not understood by Twilio Voice.",this.name="CallMessageEventTypeInvalidError",this.solutions=["Ensure the Call Message Event Type is Valid and understood by Twilio Voice and try again."],Object.setPrototypeOf(this,r.CallMessageEventTypeInvalidError.prototype);const y=typeof h=="string"?h:this.explanation,w=typeof h=="object"?h:v;this.message=`${this.name} (${this.code}): ${y}`,this.originalError=w}}r.CallMessageEventTypeInvalidError=o;class l extends rr{constructor(h,v){super(h,v),this.causes=["The payload size of Call Message Event exceeds the authorized limit."],this.code=31212,this.description="Call Message Event Payload size exceeded authorized limit.",this.explanation="The request performed to send a Call Message Event exceeds the payload size authorized limit",this.name="PayloadSizeExceededError",this.solutions=["Reduce payload size of Call Message Event to be within the authorized limit and try again."],Object.setPrototypeOf(this,r.PayloadSizeExceededError.prototype);const y=typeof h=="string"?h:this.explanation,w=typeof h=="object"?h:v;this.message=`${this.name} (${this.code}): ${y}`,this.originalError=w}}r.PayloadSizeExceededError=l})(In||(In={}));var wl;(function(r){class e extends rr{constructor(i,s){super(i,s),this.causes=["The user denied the getUserMedia request.","The browser denied the getUserMedia request."],this.code=31401,this.description="UserMedia Permission Denied Error",this.explanation="The browser or end-user denied permissions to user media. Therefore we were unable to acquire input audio.",this.name="PermissionDeniedError",this.solutions=["The user should accept the request next time prompted. If the browser saved the deny, the user should change that permission in their browser.","The user should to verify that the browser has permission to access the microphone at this address."],Object.setPrototypeOf(this,r.PermissionDeniedError.prototype);const a=typeof i=="string"?i:this.explanation,c=typeof i=="object"?i:s;this.message=`${this.name} (${this.code}): ${a}`,this.originalError=c}}r.PermissionDeniedError=e;class t extends rr{constructor(i,s){super(i,s),this.causes=["NotFoundError - The deviceID specified was not found.","The getUserMedia constraints were overconstrained and no devices matched."],this.code=31402,this.description="UserMedia Acquisition Failed Error",this.explanation="The browser and end-user allowed permissions, however getting the media failed. Usually this is due to bad constraints, but can sometimes fail due to browser, OS or hardware issues.",this.name="AcquisitionFailedError",this.solutions=["Ensure the deviceID being specified exists.","Try acquiring media with fewer constraints."],Object.setPrototypeOf(this,r.AcquisitionFailedError.prototype);const a=typeof i=="string"?i:this.explanation,c=typeof i=="object"?i:s;this.message=`${this.name} (${this.code}): ${a}`,this.originalError=c}}r.AcquisitionFailedError=t})(wl||(wl={}));var _s;(function(r){class e extends rr{constructor(i,s){super(i,s),this.causes=[],this.code=53e3,this.description="Signaling connection error",this.explanation="Raised whenever a signaling connection error occurs that is not covered by a more specific error code.",this.name="ConnectionError",this.solutions=[],Object.setPrototypeOf(this,r.ConnectionError.prototype);const a=typeof i=="string"?i:this.explanation,c=typeof i=="object"?i:s;this.message=`${this.name} (${this.code}): ${a}`,this.originalError=c}}r.ConnectionError=e;class t extends rr{constructor(i,s){super(i,s),this.causes=["The device running your application lost its Internet connection."],this.code=53001,this.description="Signaling connection disconnected",this.explanation="Raised whenever the signaling connection is unexpectedly disconnected.",this.name="ConnectionDisconnected",this.solutions=["Ensure the device running your application has access to a stable Internet connection."],Object.setPrototypeOf(this,r.ConnectionDisconnected.prototype);const a=typeof i=="string"?i:this.explanation,c=typeof i=="object"?i:s;this.message=`${this.name} (${this.code}): ${a}`,this.originalError=c}}r.ConnectionDisconnected=t})(_s||(_s={}));var ga;(function(r){class e extends rr{constructor(s,a){super(s,a),this.causes=["The Client may not be using a supported WebRTC implementation.","The Client may not have the necessary resources to create or apply a new media description."],this.code=53400,this.description="Client is unable to create or apply a local media description",this.explanation="Raised whenever a Client is unable to create or apply a local media description.",this.name="ClientLocalDescFailed",this.solutions=["If you are experiencing this error using the JavaScript SDK, ensure you are running it with a supported WebRTC implementation."],Object.setPrototypeOf(this,r.ClientLocalDescFailed.prototype);const c=typeof s=="string"?s:this.explanation,o=typeof s=="object"?s:a;this.message=`${this.name} (${this.code}): ${c}`,this.originalError=o}}r.ClientLocalDescFailed=e;class t extends rr{constructor(s,a){super(s,a),this.causes=["The Client may not be using a supported WebRTC implementation.","The Client may be connecting peer-to-peer with another Participant that is not using a supported WebRTC implementation.","The Client may not have the necessary resources to apply a new media description."],this.code=53402,this.description="Client is unable to apply a remote media description",this.explanation="Raised whenever the Client receives a remote media description but is unable to apply it.",this.name="ClientRemoteDescFailed",this.solutions=["If you are experiencing this error using the JavaScript SDK, ensure you are running it with a supported WebRTC implementation."],Object.setPrototypeOf(this,r.ClientRemoteDescFailed.prototype);const c=typeof s=="string"?s:this.explanation,o=typeof s=="object"?s:a;this.message=`${this.name} (${this.code}): ${c}`,this.originalError=o}}r.ClientRemoteDescFailed=t;class n extends rr{constructor(s,a){super(s,a),this.causes=["The Client was unable to establish a media connection.","A media connection which was active failed liveliness checks."],this.code=53405,this.description="Media connection failed",this.explanation="Raised by the Client or Server whenever a media connection fails.",this.name="ConnectionError",this.solutions=["If the problem persists, try connecting to another region.","Check your Client's network connectivity.","If you've provided custom ICE Servers then ensure that the URLs and credentials are valid."],Object.setPrototypeOf(this,r.ConnectionError.prototype);const c=typeof s=="string"?s:this.explanation,o=typeof s=="object"?s:a;this.message=`${this.name} (${this.code}): ${c}`,this.originalError=o}}r.ConnectionError=n})(ga||(ga={}));const CT=new Map([[20101,In.AccessTokenInvalid],[20104,In.AccessTokenExpired],[20151,In.AuthenticationFailed],[31202,mw.AccessTokenSignatureValidationFailed],[31400,Nu.BadRequest],[31404,Nu.NotFound],[31480,Nu.TemporarilyUnavailable],[31486,Nu.BusyHere],[31603,yw.Decline],[31e3,ai.UnknownError],[31001,ai.ApplicationNotFoundError],[31002,ai.ConnectionDeclinedError],[31003,ai.ConnectionTimeoutError],[31005,ai.ConnectionError],[31008,ai.CallCancelledError],[31009,ai.TransportError],[31100,Ja.MalformedRequestError],[31101,Ja.MissingParameterArrayError],[31102,Ja.AuthorizationTokenMissingError],[31103,Ja.MaxParameterLengthExceededError],[31104,Ja.InvalidBridgeTokenError],[31105,Ja.InvalidClientNameError],[31107,Ja.ReconnectParameterInvalidError],[31201,In.AuthorizationError],[31203,In.NoValidAccountError],[31204,In.InvalidJWTTokenError],[31205,In.JWTTokenExpiredError],[31206,In.RateExceededError],[31207,In.JWTTokenExpirationTooLongError],[31209,In.ReconnectAttemptError],[31210,In.CallMessageEventTypeInvalidError],[31212,In.PayloadSizeExceededError],[31401,wl.PermissionDeniedError],[31402,wl.AcquisitionFailedError],[53e3,_s.ConnectionError],[53001,_s.ConnectionDisconnected],[53400,ga.ClientLocalDescFailed],[53402,ga.ClientRemoteDescFailed],[53405,ga.ConnectionError]]);Object.freeze(CT);const Nme=new Set([31001,31002,31003,31101,31102,31103,31104,31105,31107,31201,31202,31203,31204,31205,31207,31404,31480,31486,31603]);function _w(r,e){if(!(typeof e!="number"||!Ume(e)||!(r||!Nme.has(e))))return Lme(e)}class kr extends Error{constructor(e){super(e),this.name="InvalidArgumentError"}}class Bs extends Error{constructor(e){super(e),this.name="InvalidStateError"}}class Fn extends Error{constructor(e){super(e),this.name="NotSupportedError"}}function Lme(r){const e=CT.get(r);if(!e)throw new kr(`Error code ${r} not found`);return e}function Ume(r){return CT.has(r)}const H2="@twilio/voice-sdk",ol="2.18.2",ET="https://sdk.twilio.com/js/client/sounds/releases/1.0.0",Fme=`${ET}/cowbell.mp3?cache=${ol}`,jme=2e4;class On{static getLogLevelInstance(e){if(!On.loglevelInstance)try{On.loglevelInstance=(e&&e.LogLevelModule?e.LogLevelModule:u5).getLogger(H2)}catch{console.warn("Cannot create custom logger"),On.loglevelInstance=console}return On.loglevelInstance}constructor(e,t){this._log=On.getLogLevelInstance(t),this._prefix=`[TwilioVoice][${e}]`}debug(...e){this._log.debug(this._prefix,...e)}error(...e){this._log.error(this._prefix,...e)}info(...e){this._log.info(this._prefix,...e)}setDefaultLevel(e){this._log.setDefaultLevel?this._log.setDefaultLevel(e):console.warn("Logger cannot setDefaultLevel")}warn(...e){this._log.warn(this._prefix,...e)}}On.levels=Gr.levels;On.getLogLevelInstance();const Bme=`${ET}/outgoing.mp3`;class LA{constructor(e,t,n,i){this._name=e,this._availableDevices=t,this._beforeChange=n,this._isSupported=i,this._activeDevices=new Set,this._log=new On("OutputDeviceCollection")}delete(e){this._log.debug(".delete",e);const t=!!this._activeDevices.delete(e),n=this._availableDevices.get("default")||Array.from(this._availableDevices.values())[0];!this._activeDevices.size&&n&&this._activeDevices.add(n);const i=Array.from(this._activeDevices.values()).map(s=>s.deviceId);return this._beforeChange(this._name,i),!!t}get(){return this._activeDevices}set(e){if(this._log.debug(".set",e),!this._isSupported)return Promise.reject(new Fn("This browser does not support audio output selection"));const t=Array.isArray(e)?e:[e];if(!t.length)return Promise.reject(new kr("Must specify at least one device to set"));const n=[],i=t.map(s=>{const a=this._availableDevices.get(s);return a||n.push(s),a});return n.length?Promise.reject(new kr(`Devices not found: ${n.join(", ")}`)):new Promise(s=>{s(this._beforeChange(this._name,t))}).then(()=>{this._activeDevices.clear(),i.forEach(this._activeDevices.add,this._activeDevices)})}test(e=Bme){return this._isSupported?this._activeDevices.size?Promise.all(Array.from(this._activeDevices).map(t=>{let n;return new Promise(i=>{n=new Audio(e),n.oncanplay=i}).then(()=>n.setSinkId(t.deviceId).then(()=>n.play()))})):Promise.reject(new Bs("No active output devices to test")):Promise.reject(new Fn("This browser does not support audio output selection"))}}class qme{constructor(e){Object.defineProperties(this,{deviceId:{get(){return e.deviceId}},groupId:{get(){return e.groupId}},kind:{get(){return e.kind}},label:{get(){return e.label}}})}}function Mv(r){if(!(this instanceof Mv))return new Mv(r);this.message=r}Mv.prototype.toString=function(){return`Twilio.Exception: ${this.message}`};function Gd(r){return r&&r.length?r.reduce((e,t)=>e+t)/r.length:0}function kT(r,e,t){t=t||(i=>i);const n=new Set(e.map(t));return r.filter(i=>!n.has(t(i)))}function G2(r){return!!r.userAgent.match("Electron")}function RT(r,e){const t=!!e.userAgent.match("CriOS"),n=!!e.userAgent.match("HeadlessChrome"),i=typeof r.chrome<"u"&&e.vendor==="Google Inc."&&e.userAgent.indexOf("OPR")===-1&&e.userAgent.indexOf("Edge")===-1;return t||G2(e)||i||n}function Wme(r){return r=r||(typeof window>"u"?global.navigator:window.navigator),!!r&&typeof r.userAgent=="string"&&/firefox|fxios/i.test(r.userAgent)}function cm(r){return r=r||(typeof window>"u"?global.navigator:window.navigator),!!r&&typeof r.userAgent=="string"&&/edge\/\d+/i.test(r.userAgent)}function Vme(r){return!!r.vendor&&r.vendor.indexOf("Apple")!==-1&&r.userAgent&&r.userAgent.indexOf("CriOS")===-1&&r.userAgent.indexOf("FxiOS")===-1}function z2(r){return r?r.split("&").reduce((e,t)=>{const n=t.split("="),i=n[0],s=decodeURIComponent((n[1]||"").replace(/\+/g,"%20"));return i&&(e[i]=s),e},{}):""}function bw(r,e){const t=r instanceof Map||r instanceof Set?Array.from(r.values()):r;return e=e||(n=>n),t.reduce((n,i)=>{const s=e(i);return n.concat(s)},[])}function Sw(r,e,t){return new Promise((n,i)=>{function s(){r.removeListener(t,a),n()}function a(){r.removeListener(e,s),i()}r.once(e,s),r.once(t,a)})}function K2(r,e){const t=e.map(n=>"audio/"+n.toLowerCase());return r.sort((n,i)=>{const s=t.indexOf(n.mimeType.toLowerCase()),a=t.indexOf(i.mimeType.toLowerCase()),c=s>=0?s:Number.MAX_VALUE,o=a>=0?a:Number.MAX_VALUE;return c-o})}const Hme=Mv,J2=Object.freeze(Object.defineProperty({__proto__:null,Exception:Hme,average:Gd,difference:kT,flatMap:bw,isChrome:RT,isElectron:G2,isFirefox:Wme,isLegacyEdge:cm,isSafari:Vme,promisifyEvents:Sw,queryToJson:z2,sortByMimeTypes:K2},Symbol.toStringTag,{value:"Module"})),Gme={audioinput:"Audio Input",audiooutput:"Audio Output"};class ww extends Ss.EventEmitter{get audioConstraints(){return this._audioConstraints}get inputDevice(){return this._inputDevice}get inputStream(){return this._localProcessedStream||this._selectedInputDeviceStream}get processedStream(){return this._log.warn("AudioHelper#processedStream is deprecated. Please use AudioHelper#localProcessedStream instead."),this._localProcessedStream}get localProcessedStream(){return this._localProcessedStream}get remoteProcessedStream(){return this._remoteProcessedStream}constructor(e,t,n){super(),this.availableInputDevices=new Map,this.availableOutputDevices=new Map,this._audioConstraints=null,this._defaultInputDeviceStream=null,this._enabledSounds={[ft.SoundName.Disconnect]:!0,[ft.SoundName.Incoming]:!0,[ft.SoundName.Outgoing]:!0},this._inputDevice=null,this._inputDevicePromise=null,this._isPollingInputVolume=!1,this._log=new On("AudioHelper"),this._localProcessedStream=null,this._remoteProcessedStream=null,this._selectedInputDeviceStream=null,this._unknownDeviceIndexes={audioinput:{},audiooutput:{}},this._updateAvailableDevices=()=>!this._mediaDevices||!this._enumerateDevices?Promise.reject("Enumeration not supported"):this._enumerateDevices().then(c=>{this._updateDevices(c.filter(l=>l.kind==="audiooutput"),this.availableOutputDevices,this._removeLostOutput),this._updateDevices(c.filter(l=>l.kind==="audioinput"),this.availableInputDevices,this._removeLostInput);const o=this.availableOutputDevices.get("default")||Array.from(this.availableOutputDevices.values())[0];[this.speakerDevices,this.ringtoneDevices].forEach(l=>{!l.get().size&&this.availableOutputDevices.size&&this.isOutputSelectionSupported&&l.set(o.deviceId).catch(d=>{this._log.warn(`Unable to set audio output devices. ${d}`)})})}),this._removeLostInput=c=>{if(!this.inputDevice||this.inputDevice.deviceId!==c.deviceId)return!1;this._destroyLocalProcessedStream(),this._replaceStream(null),this._inputDevice=null,this._maybeStopPollingVolume();const o=this.availableInputDevices.get("default")||Array.from(this.availableInputDevices.values())[0];return o&&this.setInputDevice(o.deviceId),!0},this._removeLostOutput=c=>{const o=this.speakerDevices.delete(c),l=this.ringtoneDevices.delete(c);return o||l},n=Object.assign({AudioContext:typeof AudioContext<"u"&&AudioContext,setSinkId:typeof HTMLAudioElement<"u"&&HTMLAudioElement.prototype.setSinkId},n),this._beforeSetInputDevice=n.beforeSetInputDevice||(()=>Promise.resolve()),this._updateUserOptions(n),this._audioProcessorEventObserver=n.audioProcessorEventObserver,this._mediaDevices=n.mediaDevices||navigator.mediaDevices,this._onActiveInputChanged=t,this._enumerateDevices=typeof n.enumerateDevices=="function"?n.enumerateDevices:this._mediaDevices&&this._mediaDevices.enumerateDevices.bind(this._mediaDevices);const i=!!(n.AudioContext||n.audioContext),s=!!this._enumerateDevices;n.enabledSounds&&(this._enabledSounds=n.enabledSounds);const a=typeof n.setSinkId=="function";this.isOutputSelectionSupported=s&&a,this.isVolumeSupported=i,this.isVolumeSupported&&(this._audioContext=n.audioContext||n.AudioContext&&new n.AudioContext,this._audioContext&&(this._inputVolumeAnalyser=this._audioContext.createAnalyser(),this._inputVolumeAnalyser.fftSize=32,this._inputVolumeAnalyser.smoothingTimeConstant=.3)),this.ringtoneDevices=new LA("ringtone",this.availableOutputDevices,e,this.isOutputSelectionSupported),this.speakerDevices=new LA("speaker",this.availableOutputDevices,e,this.isOutputSelectionSupported),this.addListener("newListener",c=>{c==="inputVolume"&&this._maybeStartPollingVolume()}),this.addListener("removeListener",c=>{c==="inputVolume"&&this._maybeStopPollingVolume()}),this.once("newListener",()=>{this.isOutputSelectionSupported||this._log.warn("Warning: This browser does not support audio output selection."),this.isVolumeSupported||this._log.warn("Warning: This browser does not support Twilio's volume indicator feature.")}),s&&this._initializeEnumeration(),navigator&&navigator.permissions&&typeof navigator.permissions.query=="function"?navigator.permissions.query({name:"microphone"}).then(c=>{if(c.state!=="granted"){const o=()=>{this._updateAvailableDevices(),this._stopMicrophonePermissionListener()};c.addEventListener("change",o),this._microphonePermissionStatus=c,this._onMicrophonePermissionStatusChanged=o}}).catch(c=>this._log.warn(`Warning: unable to listen for microphone permission changes. ${c}`)):this._log.warn("Warning: current browser does not support permissions API.")}_destroy(){this._stopDefaultInputDeviceStream(),this._stopSelectedInputDeviceStream(),this._destroyLocalProcessedStream(),this._destroyRemoteProcessedStream(),this._maybeStopPollingVolume(),this.removeAllListeners(),this._stopMicrophonePermissionListener(),this._unbind()}_destroyRemoteProcessedStream(){if(this._remoteProcessor&&this._remoteProcessedStream){this._log.info("destroying remote processed stream");const e=this._remoteProcessedStream;this._remoteProcessedStream.getTracks().forEach(t=>t.stop()),this._remoteProcessedStream=null,this._remoteProcessor.destroyProcessedStream(e),this._audioProcessorEventObserver.emit("destroy",!0)}}_getInputDevicePromise(){return this._inputDevicePromise}_getAudioProcessorEventObserver(){return this._audioProcessorEventObserver}_maybeCreateRemoteProcessedStream(e){return this._remoteProcessor?(this._log.info("Creating remote processed stream"),this._remoteProcessor.createProcessedStream(e).then(t=>(this._remoteProcessedStream=t,this._audioProcessorEventObserver.emit("create",!0),this._remoteProcessedStream))):Promise.resolve(e)}_maybeStartPollingVolume(){if(!this.isVolumeSupported||!this.inputStream||(this._updateVolumeSource(),this._isPollingInputVolume||!this._inputVolumeAnalyser))return;const e=this._inputVolumeAnalyser.frequencyBinCount,t=new Uint8Array(e);this._isPollingInputVolume=!0;const n=()=>{if(this._isPollingInputVolume){if(this._inputVolumeAnalyser){this._inputVolumeAnalyser.getByteFrequencyData(t);const i=Gd(t);this.emit("inputVolume",i/255)}requestAnimationFrame(n)}};requestAnimationFrame(n)}_maybeStopPollingVolume(){this.isVolumeSupported&&(!this._isPollingInputVolume||this.inputStream&&this.listenerCount("inputVolume")||(this._inputVolumeSource&&(this._inputVolumeSource.disconnect(),delete this._inputVolumeSource),this._isPollingInputVolume=!1))}_openDefaultDeviceWithConstraints(e){return this._log.info("Opening default device with constraints",e),this._getUserMedia(e).then(t=>(this._log.info("Opened default device. Updating available devices."),this._updateAvailableDevices().catch(n=>{this._log.warn("Unable to updateAvailableDevices after gUM call",n)}),this._defaultInputDeviceStream=t,this._maybeCreateLocalProcessedStream(t)))}_stopDefaultInputDeviceStream(){this._defaultInputDeviceStream&&(this._log.info("stopping default device stream"),this._defaultInputDeviceStream.getTracks().forEach(e=>e.stop()),this._defaultInputDeviceStream=null,this._destroyLocalProcessedStream())}_unbind(){var e;!((e=this._mediaDevices)===null||e===void 0)&&e.removeEventListener&&this._mediaDevices.removeEventListener("devicechange",this._updateAvailableDevices)}_updateUserOptions(e){typeof e.enumerateDevices=="function"&&(this._enumerateDevices=e.enumerateDevices),typeof e.getUserMedia=="function"&&(this._getUserMedia=e.getUserMedia)}addProcessor(e,t=!1){if(this._log.debug(".addProcessor"),this._localProcessor&&!t)throw new Fn("Can only have one Local AudioProcessor at a time.");if(this._remoteProcessor&&t)throw new Fn("Can only have one Remote AudioProcessor at a time.");if(typeof e!="object"||e===null)throw new kr("Missing AudioProcessor argument.");if(typeof e.createProcessedStream!="function")throw new kr("Missing createProcessedStream() method.");if(typeof e.destroyProcessedStream!="function")throw new kr("Missing destroyProcessedStream() method.");return t?(this._remoteProcessor=e,this._audioProcessorEventObserver.emit("add",!0),Promise.resolve()):(this._localProcessor=e,this._audioProcessorEventObserver.emit("add",!1),this._restartInputStreams())}disconnect(e){return this._log.debug(".disconnect",e),this._maybeEnableSound(ft.SoundName.Disconnect,e)}incoming(e){return this._log.debug(".incoming",e),this._maybeEnableSound(ft.SoundName.Incoming,e)}outgoing(e){return this._log.debug(".outgoing",e),this._maybeEnableSound(ft.SoundName.Outgoing,e)}removeProcessor(e,t=!1){if(this._log.debug(".removeProcessor"),typeof e!="object"||e===null)throw new kr("Missing AudioProcessor argument.");if(this._localProcessor!==e&&!t)throw new kr("Cannot remove a Local AudioProcessor that has not been previously added.");if(this._remoteProcessor!==e&&t)throw new kr("Cannot remove a Remote AudioProcessor that has not been previously added.");return t?(this._destroyRemoteProcessedStream(),this._remoteProcessor=null,this._audioProcessorEventObserver.emit("remove",!0),Promise.resolve()):(this._destroyLocalProcessedStream(),this._localProcessor=null,this._audioProcessorEventObserver.emit("remove",!1),this._restartInputStreams())}setAudioConstraints(e){return this._log.debug(".setAudioConstraints",e),this._audioConstraints=Object.assign({},e),delete this._audioConstraints.deviceId,this.inputDevice?this._setInputDevice(this.inputDevice.deviceId,!0):Promise.resolve()}setInputDevice(e){return this._log.debug(".setInputDevice",e),this._setInputDevice(e,!1)}unsetAudioConstraints(){return this._log.debug(".unsetAudioConstraints"),this._audioConstraints=null,this.inputDevice?this._setInputDevice(this.inputDevice.deviceId,!0):Promise.resolve()}unsetInputDevice(){return this._log.debug(".unsetInputDevice",this.inputDevice),this.inputDevice?(this._destroyLocalProcessedStream(),this._onActiveInputChanged(null).then(()=>{this._replaceStream(null),this._inputDevice=null,this._maybeStopPollingVolume()})):Promise.resolve()}_destroyLocalProcessedStream(){if(this._localProcessor&&this._localProcessedStream){this._log.info("destroying local processed stream");const e=this._localProcessedStream;this._localProcessedStream.getTracks().forEach(t=>t.stop()),this._localProcessedStream=null,this._localProcessor.destroyProcessedStream(e),this._audioProcessorEventObserver.emit("destroy",!1)}}_getUnknownDeviceIndex(e){const t=e.deviceId,n=e.kind;let i=this._unknownDeviceIndexes[n][t];return i||(i=Object.keys(this._unknownDeviceIndexes[n]).length+1,this._unknownDeviceIndexes[n][t]=i),i}_initializeEnumeration(){if(!this._mediaDevices||!this._enumerateDevices)throw new Fn("Enumeration is not supported");this._mediaDevices.addEventListener&&this._mediaDevices.addEventListener("devicechange",this._updateAvailableDevices),this._updateAvailableDevices().then(()=>{this.isOutputSelectionSupported&&Promise.all([this.speakerDevices.set("default"),this.ringtoneDevices.set("default")]).catch(e=>{this._log.warn(`Warning: Unable to set audio output devices. ${e}`)})})}_maybeCreateLocalProcessedStream(e){return this._localProcessor?(this._log.info("Creating local processed stream"),this._localProcessor.createProcessedStream(e).then(t=>(this._localProcessedStream=t,this._audioProcessorEventObserver.emit("create",!1),this._localProcessedStream))):Promise.resolve(e)}_maybeEnableSound(e,t){return typeof t<"u"&&(this._enabledSounds[e]=t),this._enabledSounds[e]}_replaceStream(e){this._log.info("Replacing with new stream."),this._selectedInputDeviceStream&&(this._log.info("Old stream detected. Stopping tracks."),this._stopSelectedInputDeviceStream()),this._selectedInputDeviceStream=e}_restartInputStreams(){if(this.inputDevice&&this._selectedInputDeviceStream)return this._log.info("Restarting selected input device"),this._setInputDevice(this.inputDevice.deviceId,!0);if(this._defaultInputDeviceStream){const e=this.availableInputDevices.get("default")||Array.from(this.availableInputDevices.values())[0];return this._log.info("Restarting default input device, now becoming selected."),this._setInputDevice(e.deviceId,!0)}return Promise.resolve()}_setInputDevice(e,t){return yi(this,void 0,void 0,function*(){const n=()=>yi(this,void 0,void 0,function*(){if(yield this._beforeSetInputDevice(),typeof e!="string")return Promise.reject(new kr("Must specify the device to set"));const i=this.availableInputDevices.get(e);if(!i)return Promise.reject(new kr(`Device not found: ${e}`));if(this._log.info("Setting input device. ID: "+e),this._inputDevice&&this._inputDevice.deviceId===e&&this._selectedInputDeviceStream){if(!t)return Promise.resolve();this._log.info("Same track detected on setInputDevice, stopping old tracks."),this._stopSelectedInputDeviceStream()}this._stopDefaultInputDeviceStream();const s={audio:Object.assign({deviceId:{exact:e}},this.audioConstraints)};return this._log.info("setInputDevice: getting new tracks."),this._getUserMedia(s).then(a=>(this._destroyLocalProcessedStream(),this._maybeCreateLocalProcessedStream(a).then(c=>(this._log.info("setInputDevice: invoking _onActiveInputChanged."),this._onActiveInputChanged(c).then(()=>{this._replaceStream(a),this._inputDevice=i,this._maybeStartPollingVolume()})))))});return this._inputDevicePromise=n().finally(()=>{this._inputDevicePromise=null})})}_stopMicrophonePermissionListener(){var e;!((e=this._microphonePermissionStatus)===null||e===void 0)&&e.removeEventListener&&this._microphonePermissionStatus.removeEventListener("change",this._onMicrophonePermissionStatusChanged)}_stopSelectedInputDeviceStream(){this._selectedInputDeviceStream&&(this._log.info("Stopping selected device stream"),this._selectedInputDeviceStream.getTracks().forEach(e=>e.stop()))}_updateDevices(e,t,n){const i=e.map(l=>l.deviceId),s=Array.from(t.values()).map(l=>l.deviceId),a=[],c=kT(s,i);c.forEach(l=>{const d=t.get(l);d&&(t.delete(l),n(d)&&a.push(d))});let o=!1;if(e.forEach(l=>{const d=t.get(l.deviceId),h=this._wrapMediaDeviceInfo(l);(!d||d.label!==h.label)&&(t.set(l.deviceId,h),o=!0)}),o||c.length){const l="default",d=this.inputDevice&&this.inputDevice.deviceId===l,h=this._defaultInputDeviceStream&&this.availableInputDevices.get(l);(d||h)&&(this._log.warn("Calling getUserMedia after device change to ensure that the tracks of the active device (default) have not gone stale."),setTimeout(()=>{this._setInputDevice(l,!0)},0)),this._log.debug("#deviceChange",a),this.emit("deviceChange",a)}}_updateVolumeSource(){if(!(!this.inputStream||!this._audioContext||!this._inputVolumeAnalyser)){this._inputVolumeSource&&this._inputVolumeSource.disconnect();try{this._inputVolumeSource=this._audioContext.createMediaStreamSource(this.inputStream),this._inputVolumeSource.connect(this._inputVolumeAnalyser)}catch(e){this._log.warn("Unable to update volume source",e),delete this._inputVolumeSource}}}_wrapMediaDeviceInfo(e){const t={deviceId:e.deviceId,groupId:e.groupId,kind:e.kind,label:e.label};if(!t.label)if(t.deviceId==="default")t.label="Default";else{const n=this._getUnknownDeviceIndex(e);t.label=`Unknown ${Gme[t.kind]} Device ${n}`}return new qme(t)}}ww||(ww={});var zme=ww;class Kme extends Ss.EventEmitter{constructor(){super(),this._log=new On("AudioProcessorEventObserver"),this._log.info("Creating AudioProcessorEventObserver instance"),this.on("enabled",e=>this._reEmitEvent("enabled",e)),this.on("add",e=>this._reEmitEvent("add",e)),this.on("remove",e=>this._reEmitEvent("remove",e)),this.on("create",e=>this._reEmitEvent("create-processed-stream",e)),this.on("destroy",e=>this._reEmitEvent("destroy-processed-stream",e))}destroy(){this.removeAllListeners()}_reEmitEvent(e,t){this._log.info(`${t?"Remote":"Local"} AudioProcessor:${e}`),this.emit("event",{name:e,group:"audio-processor",isRemote:t})}}const Jme={dtmf0:[1360,960],dtmf1:[1230,720],dtmf2:[1360,720],dtmf3:[1480,720],dtmf4:[1230,790],dtmf5:[1360,790],dtmf6:[1480,790],dtmf7:[1230,870],dtmf8:[1360,870],dtmf9:[1480,870],dtmfh:[1480,960],dtmfs:[1230,960]};class Yme{constructor(e){this._context=e,this._gainNodes=[],this._gainNodes=[this._context.createGain(),this._context.createGain()],this._gainNodes.forEach(t=>{t.connect(this._context.destination),t.gain.value=.1,this._gainNodes.push(t)})}cleanup(){this._gainNodes.forEach(e=>{e.disconnect()})}play(e){const t=Jme[e];if(!t)throw new kr("Invalid DTMF sound name");[this._context.createOscillator(),this._context.createOscillator()].forEach((i,s)=>{i.type="sine",i.frequency.value=t[s],i.connect(this._gainNodes[s]),i.start(),i.stop(this._context.currentTime+.1),i.addEventListener("ended",()=>i.disconnect())})}}function Xme(r,e,t){const n=JSON.stringify(e.body||{}),i=new Headers;e.headers=e.headers||[],Object.entries(e.headers).forEach(([s,a])=>i.append(s,a)),fetch(e.url,{body:n,headers:i,method:r}).then(s=>s.text(),t).then(s=>t(null,s),t)}const PT=Xme;PT.get=function(e,t){return new this("GET",e,t)};PT.post=function(e,t){return new this("POST",e,t)};class Ti extends Ss.EventEmitter{constructor(e,t,n){if(super(),!(this instanceof Ti))return new Ti(e,t,n);n=Object.assign({defaultPayload(){return{}}},n);let i=n.defaultPayload;typeof i!="function"&&(i=()=>Object.assign({},n.defaultPayload));let s=!0;const a=Object.assign({app_name:void 0,app_version:void 0},n.metadata);Object.defineProperties(this,{_defaultPayload:{value:i},_host:{value:n.host,writable:!0},_isEnabled:{get(){return s},set(c){s=c}},_log:{value:new On("EventPublisher")},_request:{value:n.request||PT,writable:!0},_token:{value:t,writable:!0},isEnabled:{enumerable:!0,get(){return s}},metadata:{enumerable:!0,get(){return a}},productName:{enumerable:!0,value:e},token:{enumerable:!0,get(){return this._token}}})}}Ti.prototype._post=function(e,t,n,i,s,a,c){if(!this.isEnabled&&!c||!this._host)return this._log.debug("Publishing cancelled",JSON.stringify({isEnabled:this.isEnabled,force:c,host:this._host})),Promise.resolve();if(!a||(!a.parameters||!a.parameters.CallSid)&&!a.outboundConnectionId)return a?this._log.debug("Publishing cancelled. Missing connection info",JSON.stringify({outboundConnectionId:a.outboundConnectionId,parameters:a.parameters})):this._log.debug("Publishing cancelled. Missing connection object"),Promise.resolve();const o={group:n,level:t.toUpperCase(),name:i,payload:s&&s.forEach?s.slice(0):Object.assign(this._defaultPayload(a),s),payload_type:"application/json",private:!1,publisher:this.productName,timestamp:new Date().toISOString()};this.metadata&&(o.publisher_metadata=this.metadata),e==="EndpointEvents"&&this._log.debug("Publishing insights",JSON.stringify({endpointName:e,event:o,force:c,host:this._host}));const l={body:o,headers:{"Content-Type":"application/json","X-Twilio-Token":this.token},url:`https://${this._host}/v4/${e}`};return new Promise((d,h)=>{this._request.post(l,v=>{v?(this.emit("error",v),h(v)):d()})}).catch(d=>{this._log.error(`Unable to post ${n} ${i} event to Insights. Received error: ${d}`)})};Ti.prototype.post=function(e,t,n,i,s,a){return this._post("EndpointEvents",e,t,n,i,s,a)};Ti.prototype.debug=function(e,t,n,i){return this.post("debug",e,t,n,i)};Ti.prototype.info=function(e,t,n,i){return this.post("info",e,t,n,i)};Ti.prototype.warn=function(e,t,n,i){return this.post("warning",e,t,n,i)};Ti.prototype.error=function(e,t,n,i){return this.post("error",e,t,n,i)};Ti.prototype.postMetrics=function(e,t,n,i,s){return new Promise(a=>{const c=n.map(Qme).map(o=>Object.assign(o,i));a(this._post("EndpointMetrics","info",e,t,c,s))})};Ti.prototype.setHost=function(e){this._host=e};Ti.prototype.setToken=function(e){this._token=e};Ti.prototype.enable=function(){this._isEnabled=!0};Ti.prototype.disable=function(){this._isEnabled=!1};function Qme(r){return{audio_codec:r.codecName,audio_level_in:r.audioInputLevel,audio_level_out:r.audioOutputLevel,bytes_received:r.bytesReceived,bytes_sent:r.bytesSent,call_volume_input:r.inputVolume,call_volume_output:r.outputVolume,jitter:r.jitter,mos:r.mos&&Math.round(r.mos*100)/100,packets_lost:r.packetsLost,packets_lost_fraction:r.packetsLostFraction&&Math.round(r.packetsLostFraction*100)/100,packets_received:r.packetsReceived,rtt:r.rtt,timestamp:new Date(r.timestamp).toISOString(),total_bytes_received:r.totals.bytesReceived,total_bytes_sent:r.totals.bytesSent,total_packets_lost:r.totals.packetsLost,total_packets_received:r.totals.packetsReceived,total_packets_sent:r.totals.packetsSent}}const UA=32767,FA=typeof window<"u"?window.RTCStatsReport:void 0;function zs(r){if(!(this instanceof zs))return new zs(r);const e=this;Object.defineProperties(this,{_map:{value:r},size:{enumerable:!0,get(){return e._map.size}}}),this[Symbol.iterator]=r[Symbol.iterator]}FA&&(zs.prototype=Object.create(FA.prototype),zs.prototype.constructor=zs);["entries","forEach","get","has","keys","values"].forEach(r=>{zs.prototype[r]=function(...e){return this._map[r](...e)}});zs.fromArray=function(e){return new zs(e.reduce((t,n)=>(t.set(n.id,n),t),new Map))};zs.fromRTCStatsResponse=function(e){let t;const n=new Map,i=e.result().reduce((s,a)=>{const c=a.id;switch(a.type){case"googCertificate":s.set(c,iye(a));break;case"datachannel":s.set(c,sye(a));break;case"googCandidatePair":X2(a,"googActiveConnection")&&(t=c),s.set(c,nye(a));break;case"localcandidate":s.set(c,BA(a,!1));break;case"remotecandidate":s.set(c,BA(a,!0));break;case"ssrc":qu(a,"packetsReceived")?s.set(`rtp-${c}`,tye(a)):s.set(`rtp-${c}`,rye(a)),s.set(`track-${c}`,eye(a)),s.set(`codec-${c}`,Zme(a));break;case"googComponent":const o=jA(a);n.set(o.selectedCandidatePairId,c),s.set(c,jA(a));break}return s},new Map);if(t){const s=n.get(t);s&&(i.get(s).dtlsState="connected")}return new zs(i)};function jA(r){return{bytesReceived:void 0,bytesSent:void 0,dtlsState:void 0,id:r.id,localCertificateId:r.stat("localCertificateId"),remoteCertificateId:r.stat("remoteCertificateId"),rtcpTransportStatsId:void 0,selectedCandidatePairId:r.stat("selectedCandidatePairId"),timestamp:Date.parse(r.timestamp),type:"transport"}}function Zme(r){return{channels:void 0,clockRate:void 0,id:r.id,implementation:void 0,mimeType:`${r.stat("mediaType")}/${r.stat("googCodecName")}`,payloadType:void 0,sdpFmtpLine:void 0,timestamp:Date.parse(r.timestamp),type:"codec"}}function eye(r){return{audioLevel:qu(r,"audioOutputLevel")?Or(r,"audioOutputLevel")/UA:(Or(r,"audioInputLevel")||0)/UA,detached:void 0,echoReturnLoss:Cw(r,"googEchoCancellationReturnLoss"),echoReturnLossEnhancement:Cw(r,"googEchoCancellationReturnLossEnhancement"),ended:void 0,frameHeight:qu(r,"googFrameHeightReceived")?Or(r,"googFrameHeightReceived"):Or(r,"googFrameHeightSent"),frameWidth:qu(r,"googFrameWidthReceived")?Or(r,"googFrameWidthReceived"):Or(r,"googFrameWidthSent"),framesCorrupted:void 0,framesDecoded:Or(r,"framesDecoded"),framesDropped:void 0,framesPerSecond:void 0,framesReceived:void 0,framesSent:Or(r,"framesEncoded"),fullFramesLost:void 0,id:r.id,kind:r.stat("mediaType"),partialFramesLost:void 0,remoteSource:void 0,ssrcIds:void 0,timestamp:Date.parse(r.timestamp),trackIdentifier:r.stat("googTrackId"),type:"track"}}function Y2(r,e){return{associateStatsId:void 0,codecId:`codec-${r.id}`,firCount:e?Or(r,"googFirsSent"):void 0,id:r.id,isRemote:void 0,mediaType:r.stat("mediaType"),nackCount:e?Or(r,"googNacksSent"):Or(r,"googNacksReceived"),pliCount:e?Or(r,"googPlisSent"):Or(r,"googPlisReceived"),qpSum:Or(r,"qpSum"),sliCount:void 0,ssrc:r.stat("ssrc"),timestamp:Date.parse(r.timestamp),trackId:`track-${r.id}`,transportId:r.stat("transportId")}}function tye(r){const e=Y2(r,!0);return Object.assign(e,{burstDiscardCount:void 0,burstDiscardRate:void 0,burstLossCount:void 0,burstLossRate:void 0,burstPacketsDiscarded:void 0,burstPacketsLost:void 0,bytesReceived:Or(r,"bytesReceived"),fractionLost:void 0,framesDecoded:Or(r,"framesDecoded"),gapDiscardRate:void 0,gapLossRate:void 0,jitter:Tw(r.stat("googJitterReceived")),packetsDiscarded:void 0,packetsLost:Or(r,"packetsLost"),packetsReceived:Or(r,"packetsReceived"),packetsRepaired:void 0,roundTripTime:Tw(r.stat("googRtt")),type:"inbound-rtp"}),e}function rye(r){const e=Y2(r,!1);return Object.assign(e,{bytesSent:Or(r,"bytesSent"),framesEncoded:Or(r,"framesEncoded"),packetsSent:Or(r,"packetsSent"),remoteTimestamp:void 0,targetBitrate:void 0,type:"outbound-rtp"}),e}function BA(r,e){return{candidateType:aye(r.stat("candidateType")),deleted:void 0,id:r.id,ip:r.stat("ipAddress"),isRemote:e,port:Or(r,"portNumber"),priority:Cw(r,"priority"),protocol:r.stat("transport"),relayProtocol:void 0,timestamp:Date.parse(r.timestamp),transportId:void 0,type:e?"remote-candidate":"local-candidate",url:void 0}}function nye(r){return{availableIncomingBitrate:void 0,availableOutgoingBitrate:void 0,bytesReceived:Or(r,"bytesReceived"),bytesSent:Or(r,"bytesSent"),consentRequestsSent:Or(r,"consentRequestsSent"),currentRoundTripTime:Tw(r.stat("googRtt")),id:r.id,lastPacketReceivedTimestamp:void 0,lastPacketSentTimestamp:void 0,localCandidateId:r.stat("localCandidateId"),nominated:void 0,priority:void 0,readable:void 0,remoteCandidateId:r.stat("remoteCandidateId"),requestsReceived:Or(r,"requestsReceived"),requestsSent:Or(r,"requestsSent"),responsesReceived:Or(r,"responsesReceived"),responsesSent:Or(r,"responsesSent"),retransmissionsReceived:void 0,retransmissionsSent:void 0,state:void 0,timestamp:Date.parse(r.timestamp),totalRoundTripTime:void 0,transportId:r.stat("googChannelId"),type:"candidate-pair",writable:X2(r,"googWritable")}}function iye(r){return{base64Certificate:r.stat("googDerBase64"),fingerprint:r.stat("googFingerprint"),fingerprintAlgorithm:r.stat("googFingerprintAlgorithm"),id:r.id,issuerCertificateId:r.stat("googIssuerId"),timestamp:Date.parse(r.timestamp),type:"certificate"}}function sye(r){return{bytesReceived:void 0,bytesSent:void 0,datachannelid:r.stat("datachannelid"),id:r.id,label:r.stat("label"),messagesReceived:void 0,messagesSent:void 0,protocol:r.stat("protocol"),state:r.stat("state"),timestamp:Date.parse(r.timestamp),transportId:r.stat("transportId"),type:"data-channel"}}function Tw(r){return isNaN(r)||r===""?void 0:parseInt(r,10)/1e3}function aye(r){switch(r){case"peerreflexive":return"prflx";case"serverreflexive":return"srflx";case"host":case"relay":default:return r}}function Or(r,e){const t=r.stat(e);return qu(r,e)?parseInt(t,10):void 0}function Cw(r,e){const t=r.stat(e);return qu(r,e)?parseFloat(t):void 0}function X2(r,e){const t=r.stat(e);return qu(r,e)?t==="true"||t===!0:void 0}function qu(r,e){const t=r.stat(e);return typeof t<"u"&&t!==""}const oye="PeerConnection is null",uye="WebRTC statistics are unsupported";function Nc(r,e){return typeof r.get=="function"?r.get(e):r.find(t=>t.id===e)}function Q2(r){if(!r)return Promise.reject(new kr(oye));if(typeof r.getStats!="function")return Promise.reject(new Fn(uye));let e;try{e=r.getStats()}catch{e=new Promise(n=>r.getStats(n)).then(zs.fromRTCStatsResponse)}return e}function cye(r,e){return e=Object.assign({createRTCSample:fye},e),Q2(r).then(e.createRTCSample)}function lye(r){return Q2(r).then(e=>{const{candidatePairs:t,localCandidates:n,remoteCandidates:i,transport:s}=Array.from(e.values()).reduce((o,l)=>{switch(["candidatePairs","localCandidates","remoteCandidates"].forEach(d=>{o[d]||(o[d]=[])}),l.type){case"candidate-pair":o.candidatePairs.push(l);break;case"local-candidate":o.localCandidates.push(l);break;case"remote-candidate":o.remoteCandidates.push(l);break;case"transport":l.selectedCandidatePairId&&(o.transport=l);break}return o},{}),a=t.find(o=>o.selected||s&&o.id===s.selectedCandidatePairId);let c;return a&&(c={localCandidate:n.find(o=>o.id===a.localCandidateId),remoteCandidate:i.find(o=>o.id===a.remoteCandidateId)}),{iceCandidateStats:[...n,...i],selectedIceCandidatePairStats:c}})}function dye(){}function fye(r){let e=null;const t=new dye;let n;Array.from(r.values()).forEach(o=>{if(o.isRemote)return;const l=o.type.replace("-","");if(n=n||o.timestamp,o.remoteId){const d=Nc(r,o.remoteId);d&&d.roundTripTime&&(t.rtt=d.roundTripTime*1e3)}switch(l){case"inboundrtp":t.timestamp=t.timestamp||o.timestamp,t.jitter=o.jitter*1e3,t.packetsLost=o.packetsLost,t.packetsReceived=o.packetsReceived,t.bytesReceived=o.bytesReceived;break;case"outboundrtp":if(t.timestamp=o.timestamp,t.packetsSent=o.packetsSent,t.bytesSent=o.bytesSent,o.codecId){const d=Nc(r,o.codecId);t.codecName=d?d.mimeType&&d.mimeType.match(/(.*\/)?(.*)/)[2]:o.codecId}break;case"transport":e=o.id;break}}),t.timestamp||(t.timestamp=n);const i=Nc(r,e);if(!i)return t;const s=Nc(r,i.selectedCandidatePairId);if(!s)return t;const a=Nc(r,s.localCandidateId),c=Nc(r,s.remoteCandidateId);return t.rtt||(t.rtt=s&&s.currentRoundTripTime*1e3),Object.assign(t,{localAddress:a&&(a.address||a.ip),remoteAddress:c&&(c.address||c.ip)}),t}class Qr extends Ss.EventEmitter{constructor(e,t){super(),this._hasInsightsErrored=!1,this._log=new On("PreflightTest"),this._networkTiming={},this._options={codecPreferences:[dt.Codec.PCMU,dt.Codec.Opus],edge:"roaming",fakeMicInput:!1,logLevel:"error",signalingTimeoutMs:1e4},this._status=Qr.Status.Connecting,Object.assign(this._options,t),this._samples=[],this._warnings=[],this._startTime=Date.now(),this._initDevice(e,Object.assign(Object.assign({},this._options),{fileInputStream:this._options.fakeMicInput?this._getStreamFromFile():void 0}));const n=["codecPreferences","edge","fakeMicInput","logLevel","signalingTimeoutMs"],i=["audioContext","deviceFactory","fileInputStream","getRTCIceCandidateStatsReport","iceServers","rtcConfiguration"];if(typeof t=="object"){const s=Object.assign({},t);Object.keys(s).forEach(a=>{!n.includes(a)&&!i.includes(a)&&delete s[a],i.includes(a)&&(s[a]=!0)}),this._log.debug(".constructor",JSON.stringify(s))}}stop(){this._log.debug(".stop");const e=new ai.CallCancelledError;this._device?(this._device.once(ft.EventName.Unregistered,()=>this._onFailed(e)),this._device.destroy()):this._onFailed(e)}_emitWarning(e,t,n){const i={name:e,description:t};n&&(i.rtcWarning=n),this._warnings.push(i),this._log.debug(`#${Qr.Events.Warning}`,JSON.stringify(i)),this.emit(Qr.Events.Warning,i)}_getCallQuality(e){return e>4.2?Qr.CallQuality.Excellent:e>=4.1&&e<=4.2?Qr.CallQuality.Great:e>=3.7&&e<=4?Qr.CallQuality.Good:e>=3.1&&e<=3.6?Qr.CallQuality.Fair:Qr.CallQuality.Degraded}_getReport(){var e,t,n;const i=this._getRTCStats(),s={start:this._startTime};this._endTime&&(s.end=this._endTime,s.duration=this._endTime-this._startTime);const a={callSid:this._callSid,edge:this._edge,iceCandidateStats:(t=(e=this._rtcIceCandidateStatsReport)===null||e===void 0?void 0:e.iceCandidateStats)!==null&&t!==void 0?t:[],networkTiming:this._networkTiming,samples:this._samples,selectedEdge:this._options.edge,stats:i,testTiming:s,totals:this._getRTCSampleTotals(),warnings:this._warnings},c=(n=this._rtcIceCandidateStatsReport)===null||n===void 0?void 0:n.selectedIceCandidatePairStats;return c&&(a.selectedIceCandidatePairStats=c,a.isTurnRequired=c.localCandidate.candidateType==="relay"||c.remoteCandidate.candidateType==="relay"),i&&(a.callQuality=this._getCallQuality(i.mos.average)),a}_getRTCSampleTotals(){if(this._latestSample)return Object.assign({},this._latestSample.totals)}_getRTCStats(){const e=this._samples.findIndex(n=>typeof n.mos=="number"&&n.mos>0),t=e>=0?this._samples.slice(e):[];if(!(!t||!t.length))return["jitter","mos","rtt"].reduce((n,i)=>{const s=t.map(a=>a[i]);return Object.assign(Object.assign({},n),{[i]:{average:Number((s.reduce((a,c)=>a+c)/s.length).toPrecision(5)),max:Math.max(...s),min:Math.min(...s)}})},{})}_getStreamFromFile(){const e=this._options.audioContext;if(!e)throw new Fn("Cannot fake input audio stream: AudioContext is not supported by this browser.");const t=new Audio(Fme);t.addEventListener("canplaythrough",()=>t.play()),typeof t.setAttribute=="function"&&t.setAttribute("crossorigin","anonymous");const n=e.createMediaElementSource(t),i=e.createMediaStreamDestination();return n.connect(i),i.stream}_initDevice(e,t){try{this._device=new(t.deviceFactory||ft)(e,{chunderw:t.chunderw,codecPreferences:t.codecPreferences,edge:t.edge,eventgw:t.eventgw,fileInputStream:t.fileInputStream,logLevel:t.logLevel,preflight:!0}),this._device.once(ft.EventName.Registered,()=>{this._onDeviceRegistered()}),this._device.once(ft.EventName.Error,n=>{this._onDeviceError(n)}),this._device.register()}catch(n){setTimeout(()=>{this._onFailed(n)});return}this._signalingTimeoutTimer=setTimeout(()=>{this._onDeviceError(new _s.ConnectionError("WebSocket Connection Timeout"))},t.signalingTimeoutMs)}_onDeviceError(e){this._device.destroy(),this._onFailed(e)}_onDeviceRegistered(){return yi(this,void 0,void 0,function*(){if(clearTimeout(this._echoTimer),clearTimeout(this._signalingTimeoutTimer),this._call=yield this._device.connect({rtcConfiguration:this._options.rtcConfiguration}),this._networkTiming.signaling={start:Date.now()},this._setupCallHandlers(this._call),this._edge=this._device.edge||void 0,this._options.fakeMicInput){this._echoTimer=setTimeout(()=>this._device.disconnectAll(),jme);const t=this._device.audio;t&&(t.disconnect(!1),t.outgoing(!1))}this._call.once("disconnect",()=>{this._device.once(ft.EventName.Unregistered,()=>this._onUnregistered()),this._device.destroy()}),this._call._publisher.on("error",()=>{this._hasInsightsErrored||this._emitWarning("insights-connection-error","Received an error when attempting to connect to Insights gateway"),this._hasInsightsErrored=!0})})}_onFailed(e){clearTimeout(this._echoTimer),clearTimeout(this._signalingTimeoutTimer),this._releaseHandlers(),this._endTime=Date.now(),this._status=Qr.Status.Failed,this._log.debug(`#${Qr.Events.Failed}`,e),this.emit(Qr.Events.Failed,e)}_onUnregistered(){setTimeout(()=>{this._status!==Qr.Status.Failed&&(clearTimeout(this._echoTimer),clearTimeout(this._signalingTimeoutTimer),this._releaseHandlers(),this._endTime=Date.now(),this._status=Qr.Status.Completed,this._report=this._getReport(),this._log.debug(`#${Qr.Events.Completed}`,JSON.stringify(this._report)),this.emit(Qr.Events.Completed,this._report))},10)}_releaseHandlers(){[this._device,this._call].forEach(e=>{e&&e.eventNames().forEach(t=>e.removeAllListeners(t))})}_setupCallHandlers(e){this._options.fakeMicInput&&e.once("volume",()=>{e._mediaHandler.outputs.forEach(t=>t.audio.muted=!0)}),e.on("warning",(t,n)=>{this._emitWarning(t,"Received an RTCWarning. See .rtcWarning for the RTCWarning",n)}),e.once("accept",()=>{this._callSid=e._mediaHandler.callSid,this._status=Qr.Status.Connected,this._log.debug(`#${Qr.Events.Connected}`),this.emit(Qr.Events.Connected)}),e.on("sample",t=>yi(this,void 0,void 0,function*(){this._latestSample||(this._rtcIceCandidateStatsReport=yield(this._options.getRTCIceCandidateStatsReport||lye)(e._mediaHandler.version.pc)),this._latestSample=t,this._samples.push(t),this._log.debug(`#${Qr.Events.Sample}`,JSON.stringify(t)),this.emit(Qr.Events.Sample,t)})),[{reportLabel:"peerConnection",type:"pcconnection"},{reportLabel:"ice",type:"iceconnection"},{reportLabel:"dtls",type:"dtlstransport"},{reportLabel:"signaling",type:"signaling"}].forEach(({type:t,reportLabel:n})=>{const i=`on${t}statechange`,s=e._mediaHandler[i];e._mediaHandler[i]=a=>{const c=this._networkTiming[n]=this._networkTiming[n]||{start:0};a==="connecting"||a==="checking"?c.start=Date.now():(a==="connected"||a==="stable")&&!c.duration&&(c.end=Date.now(),c.duration=c.end-c.start),s(a)}})}get callSid(){return this._callSid}get endTime(){return this._endTime}get latestSample(){return this._latestSample}get report(){return this._report}get startTime(){return this._startTime}get status(){return this._status}}(function(r){(function(e){e.Excellent="excellent",e.Great="great",e.Good="good",e.Fair="fair",e.Degraded="degraded"})(r.CallQuality||(r.CallQuality={})),function(e){e.Completed="completed",e.Connected="connected",e.Failed="failed",e.Sample="sample",e.Warning="warning"}(r.Events||(r.Events={})),function(e){e.Connecting="connecting",e.Connected="connected",e.Completed="completed",e.Failed="failed"}(r.Status||(r.Status={}))})(Qr||(Qr={}));const Bc=globalThis.WebSocket,hye=1e4,pye=5e3,qA=15e3,vye=15e3,gye=1/0,mye=75e3,yye=1e3,_ye=2e4,bye=6e4;var Yi;(function(r){r.Connecting="connecting",r.Closed="closed",r.Open="open"})(Yi||(Yi={}));class lm extends Ss.EventEmitter{constructor(e,t={}){super(),this.state=Yi.Closed,this._backoffStartTime={preferred:null,primary:null},this._connectedUri=null,this._log=new On("WSTransport"),this._retryAfter=null,this._shouldFallback=!1,this._uriIndex=0,this._moveUriIndex=()=>{this._uriIndex++,this._uriIndex>=this._uris.length&&(this._uriIndex=0)},this._onSocketClose=n=>{if(this._log.error(`Received websocket close event code: ${n.code}. Reason: ${n.reason}`),n.code===1006||n.code===1015){this.emit("error",{code:31005,message:n.reason||"Websocket connection to Twilio's signaling servers were unexpectedly ended. If this is happening consistently, there may be an issue resolving the hostname provided. If a region or an edge is being specified in Device setup, ensure it is valid.",twilioError:new _s.ConnectionError});const i=this.state===Yi.Open||this._previousState===Yi.Open;(this._shouldFallback||!i)&&this._moveUriIndex(),this._shouldFallback=!0}this._closeSocket()},this._onSocketError=n=>{this._log.error(`WebSocket received error: ${n.message}`),this.emit("error",{code:31e3,message:n.message||"WSTransport socket error",twilioError:new _s.ConnectionDisconnected})},this._onSocketMessage=n=>{if(this._setHeartbeatTimeout(),this._socket&&n.data===`
|
|
555
555
|
`){this._socket.send(`
|
|
556
556
|
`),this._log.debug("heartbeat");return}if(n&&typeof n.data=="string"){this._log.debug(`Received: ${n.data}`);const{type:i,payload:s={}}=JSON.parse(n.data);i==="error"&&s.error&&s.error.retryAfter&&(this._retryAfter=s.error.retryAfter*1e3)}this.emit("message",n)},this._onSocketOpen=()=>{this._log.info("WebSocket opened successfully."),this._timeOpened=Date.now(),this._shouldFallback=!1,this._setState(Yi.Open),clearTimeout(this._connectTimeout),this._backoff&&this._resetBackoffs(),this._setHeartbeatTimeout(),this.emit("open")},this._options=Object.assign(Object.assign({},lm.defaultConstructorOptions),t),this._uris=e,this._backoff=null}close(){this._log.info("WSTransport.close() called..."),this._close()}open(){if(this._log.info("WSTransport.open() called..."),this._socket&&(this._socket.readyState===Bc.CONNECTING||this._socket.readyState===Bc.OPEN)){this._log.info("WebSocket already open.");return}this._preferredUri?this._connect(this._preferredUri):this._connect(this._uris[this._uriIndex])}send(e){if(this._log.debug(`Sending: ${e}`),!this._socket||this._socket.readyState!==Bc.OPEN)return this._log.debug("Cannot send message. WebSocket is not open."),!1;try{this._socket.send(e)}catch(t){return this._log.error("Error while sending message:",t.message),this._closeSocket(),!1}return!0}updatePreferredURI(e){this._preferredUri=e}updateURIs(e){typeof e=="string"&&(e=[e]),this._uris=e,this._uriIndex=0}_close(){this._setState(Yi.Closed),this._closeSocket()}_closeSocket(){if(clearTimeout(this._connectTimeout),clearTimeout(this._heartbeatTimeout),this._log.info("Closing and cleaning up WebSocket..."),!this._socket){this._log.info("No WebSocket to clean up.");return}this._socket.removeEventListener("close",this._onSocketClose),this._socket.removeEventListener("error",this._onSocketError),this._socket.removeEventListener("message",this._onSocketMessage),this._socket.removeEventListener("open",this._onSocketOpen),(this._socket.readyState===Bc.CONNECTING||this._socket.readyState===Bc.OPEN)&&this._socket.close(),this._backoff&&this._timeOpened&&Date.now()-this._timeOpened>hye&&this._resetBackoffs(),this.state!==Yi.Closed&&(this._backoff||(this._backoff=this._setupBackoffs()),this._performBackoff()),delete this._socket,this.emit("close")}_connect(e,t){this._log.info(typeof t=="number"?`Attempting to reconnect (retry #${t})...`:"Attempting to connect..."),this._closeSocket(),this._setState(Yi.Connecting),this._connectedUri=e;try{this._socket=new this._options.WebSocket(this._connectedUri)}catch(n){this._log.error("Could not connect to endpoint:",n.message),this._close(),this.emit("error",{code:31e3,message:n.message||`Could not connect to ${this._connectedUri}`,twilioError:new _s.ConnectionDisconnected});return}this._socket.addEventListener("close",this._onSocketClose),this._socket.addEventListener("error",this._onSocketError),this._socket.addEventListener("message",this._onSocketMessage),this._socket.addEventListener("open",this._onSocketOpen),delete this._timeOpened,this._connectTimeout=setTimeout(()=>{this._log.info("WebSocket connection attempt timed out."),this._moveUriIndex(),this._closeSocket()},this._options.connectTimeoutMs)}_performBackoff(){if(!this._backoff){this._log.info("No backoff instance to perform backoff.");return}this._preferredUri?(this._log.info("Preferred URI set; backing off."),this._backoff.preferred.backoff()):(this._log.info("Preferred URI not set; backing off."),this._backoff.primary.backoff())}_resetBackoffs(){if(!this._backoff){this._log.info("No backoff instance to reset.");return}this._backoff.preferred.removeAllListeners("backoff"),this._backoff.preferred.removeAllListeners("ready"),this._backoff.primary.removeAllListeners("backoff"),this._backoff.primary.removeAllListeners("ready"),this._backoff=null,this._retryAfter=null,this._backoffStartTime.preferred=null,this._backoffStartTime.primary=null}_setHeartbeatTimeout(){clearTimeout(this._heartbeatTimeout),this._heartbeatTimeout=setTimeout(()=>{this._log.info(`No messages received in ${qA/1e3} seconds. Reconnecting...`),this._shouldFallback=!0,this._closeSocket()},qA)}_setState(e){this._previousState=this.state,this.state=e}_setupBackoffs(){const e=this._retryAfter!==null&&this._preferredUri?this._retryAfter:null;e&&this._log.info(`Setting initial preferred backoff value to retryAfter: ${e}ms`);const t=e?this._options.maxRetryAfterDurationMs:this._options.maxPreferredDurationMs,n={factor:2,jitter:.4,max:e?this._options.maxRetryAfterDelayMs:this._options.maxPreferredDelayMs,min:e||100,useInitialValue:!!e};this._log.info("Initializing preferred transport backoff using config: ",n);const i=new gw(n);i.on("backoff",(c,o)=>{if(this.state===Yi.Closed){this._log.info("Preferred backoff initiated but transport state is closed; not attempting a connection.");return}this._log.info(`Will attempt to reconnect Websocket to preferred URI in ${o}ms`),c===0&&(this._backoffStartTime.preferred=Date.now(),this._log.info(`Preferred backoff start; ${this._backoffStartTime.preferred}`))}),i.on("ready",(c,o)=>{if(this.state===Yi.Closed){this._log.info("Preferred backoff ready but transport state is closed; not attempting a connection.");return}if(this._backoffStartTime.preferred===null){this._log.info("Preferred backoff start time invalid; not attempting a connection.");return}if(!this._backoff){this._log.info("Preferred backoff instance invalid; not attempting a connection.");return}if(Date.now()-this._backoffStartTime.preferred>t){this._log.info("Max preferred backoff attempt time exceeded; falling back to primary backoff."),this._preferredUri=null,this._backoff.primary.backoff();return}if(typeof this._preferredUri!="string"){this._log.info("Preferred URI cleared; falling back to primary backoff."),this._preferredUri=null,this._backoff.primary.backoff();return}this._connect(this._preferredUri,c+1)});const s={factor:2,jitter:.4,max:this._options.maxPrimaryDelayMs,min:this._uris&&this._uris.length>1?Math.floor(Math.random()*4001)+1e3:100};this._log.info("Initializing primary transport backoff using config: ",s);const a=new gw(s);return a.on("backoff",(c,o)=>{if(this.state===Yi.Closed){this._log.info("Primary backoff initiated but transport state is closed; not attempting a connection.");return}this._log.info(`Will attempt to reconnect WebSocket in ${o}ms`),c===0&&(this._backoffStartTime.primary=Date.now(),this._log.info(`Primary backoff start; ${this._backoffStartTime.primary}`))}),a.on("ready",(c,o)=>{if(this.state===Yi.Closed){this._log.info("Primary backoff ready but transport state is closed; not attempting a connection.");return}if(this._backoffStartTime.primary===null){this._log.info("Primary backoff start time invalid; not attempting a connection.");return}if(Date.now()-this._backoffStartTime.primary>this._options.maxPrimaryDurationMs){this._log.info("Max primary backoff attempt time exceeded; not attempting a connection.");return}this._connect(this._uris[this._uriIndex],c+1)}),{preferred:i,primary:a}}get uri(){return this._connectedUri}}lm.defaultConstructorOptions={WebSocket:Bc,connectTimeoutMs:pye,maxPreferredDelayMs:yye,maxPreferredDurationMs:vye,maxPrimaryDelayMs:_ye,maxPrimaryDurationMs:gye,maxRetryAfterDelayMs:bye,maxRetryAfterDurationMs:mye};const Sye="1.6",wye=30;class zr extends Ss.EventEmitter{constructor(e,t,n){if(super(),!(this instanceof zr))return new zr(e,t,n);const i={TransportFactory:lm};n=n||{};for(const a in i)a in n||(n[a]=i[a]);this.options=n,this.token=e||"",this.status="disconnected",this.gateway=null,this.region=null,this._messageQueue=[],this._preferredUri=null,this._uris=t,this._handleTransportClose=this._handleTransportClose.bind(this),this._handleTransportError=this._handleTransportError.bind(this),this._handleTransportMessage=this._handleTransportMessage.bind(this),this._handleTransportOpen=this._handleTransportOpen.bind(this),this._log=new On("PStream"),this.on("error",()=>{this._log.warn("Unexpected error handled in pstream")});const s=this;return this.addListener("ready",()=>{s.status="ready"}),this.addListener("offline",()=>{s.status="offline"}),this.addListener("close",()=>{s._log.info('Received "close" from server. Destroying PStream...'),s._destroy()}),this.transport=new this.options.TransportFactory(this._uris,{backoffMaxMs:this.options.backoffMaxMs,maxPreferredDurationMs:this.options.maxPreferredDurationMs}),Object.defineProperties(this,{uri:{enumerable:!0,get(){return this.transport.uri}}}),this.transport.on("close",this._handleTransportClose),this.transport.on("error",this._handleTransportError),this.transport.on("message",this._handleTransportMessage),this.transport.on("open",this._handleTransportOpen),this.transport.open(),this}}zr.prototype._handleTransportClose=function(){this.emit("transportClose"),this.status!=="disconnected"&&(this.status!=="offline"&&this.emit("offline",this),this.status="disconnected")};zr.prototype._handleTransportError=function(r){if(!r){this.emit("error",{error:{code:31e3,message:"Websocket closed without a provided reason",twilioError:new _s.ConnectionDisconnected}});return}this.emit("error",typeof r.code<"u"?{error:r}:r)};zr.prototype._handleTransportMessage=function(r){if(!r||!r.data||typeof r.data!="string")return;const{type:e,payload:t={}}=JSON.parse(r.data);this.gateway=t.gateway||this.gateway,this.region=t.region||this.region,e==="error"&&t.error&&(t.error.twilioError=new _s.ConnectionError),this.emit(e,t)};zr.prototype._handleTransportOpen=function(){this.status="connected",this.setToken(this.token),this.emit("transportOpen"),this._messageQueue.splice(0,this._messageQueue.length).forEach(e=>this._publish(...e))};zr.toString=()=>"[Twilio.PStream class]";zr.prototype.toString=()=>"[Twilio.PStream instance]";zr.prototype.setToken=function(r){this._log.info("Setting token and publishing listen"),this.token=r;let e=0;const t=this.options.maxPreferredDurationMs;this._log.info(`maxPreferredDurationMs:${t}`),typeof t=="number"&&t>=0&&(e=Math.min(Math.ceil(t/1e3),wye)),this._log.info(`reconnectTimeout:${e}`);const n={browserinfo:Tye(),reconnectTimeout:e,token:r};this._publish("listen",n)};zr.prototype.sendMessage=function(r,e,t="application/json",n,i){const s={callsid:r,content:e,contenttype:t,messagetype:n,voiceeventsid:i};this._publish("message",s,!0)};zr.prototype.register=function(r){const e={media:r};this._publish("register",e,!0)};zr.prototype.invite=function(r,e,t){const n={callsid:e,sdp:r,twilio:t?{params:t}:{}};this._publish("invite",n,!0)};zr.prototype.reconnect=function(r,e,t){const n={callsid:e,reconnect:t,sdp:r,twilio:{}};this._publish("invite",n,!0)};zr.prototype.answer=function(r,e){this._publish("answer",{sdp:r,callsid:e},!0)};zr.prototype.dtmf=function(r,e){this._publish("dtmf",{callsid:r,dtmf:e},!0)};zr.prototype.hangup=function(r,e){const t=e?{callsid:r,message:e}:{callsid:r};this._publish("hangup",t,!0)};zr.prototype.reject=function(r){this._publish("reject",{callsid:r},!0)};zr.prototype.reinvite=function(r,e){this._publish("reinvite",{sdp:r,callsid:e},!1)};zr.prototype._destroy=function(){this.transport.removeListener("close",this._handleTransportClose),this.transport.removeListener("error",this._handleTransportError),this.transport.removeListener("message",this._handleTransportMessage),this.transport.removeListener("open",this._handleTransportOpen),this.transport.close(),this.emit("offline",this)};zr.prototype.destroy=function(){return this._log.info("PStream.destroy() called..."),this._destroy(),this};zr.prototype.updatePreferredURI=function(r){this._preferredUri=r,this.transport.updatePreferredURI(r)};zr.prototype.updateURIs=function(r){this._uris=r,this.transport.updateURIs(this._uris)};zr.prototype.publish=function(r,e){return this._publish(r,e,!0)};zr.prototype._publish=function(r,e,t){const n=JSON.stringify({payload:e,type:r,version:Sye});!!this.transport.send(n)||(this.emit("error",{error:{code:31009,message:"No transport available to send or receive messages",twilioError:new ai.TransportError}}),t&&this._messageQueue.push([r,e,!0]))};function Tye(){const r=typeof navigator<"u"?navigator:{};return{browser:{platform:r.platform||"unknown",userAgent:r.userAgent||"unknown"},p:"browser",plugin:"rtc",v:ol}}var sn;(function(r){r.Sydney="sydney",r.SaoPaulo="sao-paulo",r.Dublin="dublin",r.Frankfurt="frankfurt",r.Tokyo="tokyo",r.Singapore="singapore",r.Ashburn="ashburn",r.Umatilla="umatilla",r.Roaming="roaming",r.AshburnIx="ashburn-ix",r.SanJoseIx="san-jose-ix",r.LondonIx="london-ix",r.FrankfurtIx="frankfurt-ix",r.SingaporeIx="singapore-ix",r.SydneyIx="sydney-ix",r.TokyoIx="tokyo-ix"})(sn||(sn={}));var Er;(function(r){r.Au1="au1",r.Au1Ix="au1-ix",r.Br1="br1",r.De1="de1",r.De1Ix="de1-ix",r.Gll="gll",r.Ie1="ie1",r.Ie1Ix="ie1-ix",r.Ie1Tnx="ie1-tnx",r.Jp1="jp1",r.Jp1Ix="jp1-ix",r.Sg1="sg1",r.Sg1Ix="sg1-ix",r.Sg1Tnx="sg1-tnx",r.Us1="us1",r.Us1Ix="us1-ix",r.Us1Tnx="us1-tnx",r.Us2="us2",r.Us2Ix="us2-ix",r.Us2Tnx="us2-tnx"})(Er||(Er={}));const Cye={ASIAPAC_SINGAPORE:Er.Sg1,ASIAPAC_SYDNEY:Er.Au1,ASIAPAC_TOKYO:Er.Jp1,EU_FRANKFURT:Er.De1,EU_IRELAND:Er.Ie1,SOUTH_AMERICA_SAO_PAULO:Er.Br1,US_EAST_VIRGINIA:Er.Us1,US_WEST_OREGON:Er.Us2},Eye={[Er.Au1]:sn.Sydney,[Er.Br1]:sn.SaoPaulo,[Er.Ie1]:sn.Dublin,[Er.De1]:sn.Frankfurt,[Er.Jp1]:sn.Tokyo,[Er.Sg1]:sn.Singapore,[Er.Us1]:sn.Ashburn,[Er.Us2]:sn.Umatilla,[Er.Gll]:sn.Roaming,[Er.Us1Ix]:sn.AshburnIx,[Er.Us2Ix]:sn.SanJoseIx,[Er.Ie1Ix]:sn.LondonIx,[Er.De1Ix]:sn.FrankfurtIx,[Er.Sg1Ix]:sn.SingaporeIx,[Er.Au1Ix]:sn.SydneyIx,[Er.Jp1Ix]:sn.TokyoIx,[Er.Us1Tnx]:sn.AshburnIx,[Er.Us2Tnx]:sn.AshburnIx,[Er.Ie1Tnx]:sn.LondonIx,[Er.Sg1Tnx]:sn.SingaporeIx},kye=sn.Roaming,Rye="eventgw.twilio.com";function WA(r){return`voice-js.${r}.twilio.com`}function VA(r){return r?`eventgw.${r}.twilio.com`:Rye}function HA(r){return`wss://${r}/signal`}function GA(r){if(r&&typeof r!="string"&&!Array.isArray(r))throw new kr("If `edge` is provided, it must be of type `string` or an array of strings.");let e;return r?e=(Array.isArray(r)?r:[r]).map(n=>WA(n)):e=[WA(kye)],e}function Pye(r){return Cye[r]||null}const zA={0:"PCMU",8:"PCMA"},Iye=111,Aye=51e4,Oye=6e3;function $ye(r){const[,e,t]=/a=rtpmap:(\d+) (\S+)/m.exec(r)||[null,"",""],n=new RegExp(`a=fmtp:${e} (\\S+)`,"m"),[,i]=n.exec(r)||[null,""];return{codecName:t,codecParams:i}}function xye(r){return RT(window,window.navigator)?r.split(`
|
|
557
557
|
`).filter(e=>e.indexOf("a=ice-lite")===-1).join(`
|
|
@@ -565,4 +565,4 @@ m=`).slice(1).map(n=>`m=${n}`).filter(n=>{const i=new RegExp("m=.*","gm"),s=new
|
|
|
565
565
|
`);let n=t[0];const i=t.slice(1);return n=n.replace(/([0-9]+\s?)+$/,r.join(" ")),[n].concat(i).join(`\r
|
|
566
566
|
`)}function Uye(r){return Fye(r).reduce((e,t)=>{const n=new RegExp(`a=rtpmap:${t} ([^/]+)`),i=r.match(n),s=i?i[1].toLowerCase():zA[t]?zA[t].toLowerCase():"";return e.set(t,s)},new Map)}function Fye(r){const t=r.split(`\r
|
|
567
567
|
`)[0].match(/([0-9]+)/g);return t?t.slice(1).map(n=>parseInt(n,10)):[]}function ts(r){if(this.log=new On("RTCPC"),typeof window>"u"){this.log.info("No RTCPeerConnection implementation available. The window object was not found.");return}r&&r.RTCPeerConnection?this.RTCPeerConnection=r.RTCPeerConnection:typeof window.RTCPeerConnection=="function"?this.RTCPeerConnection=window.RTCPeerConnection:typeof window.webkitRTCPeerConnection=="function"?this.RTCPeerConnection=webkitRTCPeerConnection:typeof window.mozRTCPeerConnection=="function"?(this.RTCPeerConnection=mozRTCPeerConnection,window.RTCSessionDescription=mozRTCSessionDescription,window.RTCIceCandidate=mozRTCIceCandidate):this.log.info("No RTCPeerConnection implementation available")}ts.prototype.create=function(r){this.pc=new this.RTCPeerConnection(r)};ts.prototype.createModernConstraints=r=>{if(typeof r>"u")return null;const e=Object.assign({},r);return typeof webkitRTCPeerConnection<"u"&&!cm()?(e.mandatory={},typeof r.audio<"u"&&(e.mandatory.OfferToReceiveAudio=r.audio),typeof r.video<"u"&&(e.mandatory.OfferToReceiveVideo=r.video)):(typeof r.audio<"u"&&(e.offerToReceiveAudio=r.audio),typeof r.video<"u"&&(e.offerToReceiveVideo=r.video)),delete e.audio,delete e.video,e};ts.prototype.createOffer=function(r,e,t,n){return e=this.createModernConstraints(e),rU(this.pc.createOffer,this.pc)(e).then(i=>{if(!this.pc)return Promise.resolve();const s=Z2(i.sdp,r);return dm(this.pc.setLocalDescription,this.pc)(new RTCSessionDescription({sdp:s,type:"offer"}))}).then(t,n)};ts.prototype.createAnswer=function(r,e,t,n){return e=this.createModernConstraints(e),rU(this.pc.createAnswer,this.pc)(e).then(i=>{if(!this.pc)return Promise.resolve();const s=Z2(i.sdp,r);return dm(this.pc.setLocalDescription,this.pc)(new RTCSessionDescription({sdp:s,type:"answer"}))}).then(t,n)};ts.prototype.processSDP=function(r,e,t,n,i,s){t=eU(t,e);const a=new RTCSessionDescription({sdp:t,type:"offer"});return dm(this.pc.setRemoteDescription,this.pc)(a).then(()=>{this.createAnswer(r,n,i,s)})};ts.prototype.getSDP=function(){return this.pc.localDescription.sdp};ts.prototype.processAnswer=function(r,e,t,n){return this.pc?(e=eU(e,r),dm(this.pc.setRemoteDescription,this.pc)(new RTCSessionDescription({sdp:e,type:"answer"})).then(t,n)):Promise.resolve()};ts.test=()=>{if(typeof navigator=="object"){const r=navigator.mediaDevices&&navigator.mediaDevices.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.getUserMedia;if(cm(navigator))return!1;if(r&&typeof window.RTCPeerConnection=="function")return!0;if(r&&typeof window.webkitRTCPeerConnection=="function")return!0;if(r&&typeof window.mozRTCPeerConnection=="function"){try{if(typeof new window.mozRTCPeerConnection().getLocalStreams!="function")return!1}catch{return!1}return!0}else if(typeof RTCIceGatherer<"u")return!0}return!1};function tU(r,e,t,n){return function(){const i=Array.prototype.slice.call(arguments);return new Promise(s=>{const a=r.apply(e,i);if(!n){s(a);return}if(typeof a=="object"&&typeof a.then=="function")s(a);else throw new Error}).catch(()=>new Promise((s,a)=>{r.apply(e,t?[s,a].concat(i):i.concat([s,a]))}))}}function rU(r,e){return tU(r,e,!0,!0)}function dm(r,e){return tU(r,e,!1,!1)}const jye=15e3,Bye="none",qye="timeout",Wye="new",KA=50;function Dt(r,e,t){if(!r||!e)throw new kr("Audiohelper, and pstream are required arguments");if(!(this instanceof Dt))return new Dt(r,e,t);this._log=new On("PeerConnection");function n(){this._log.warn("Unexpected noop call in peerconnection")}this.onaudio=n,this.onopen=n,this.onerror=n,this.onclose=n,this.ondisconnected=n,this.onfailed=n,this.onconnected=n,this.onreconnected=n,this.onsignalingstatechange=n,this.ondtlstransportstatechange=n,this.onicegatheringfailure=n,this.onicegatheringstatechange=n,this.oniceconnectionstatechange=n,this.onpcconnectionstatechange=n,this.onicecandidate=n,this.onselectedcandidatepairchange=n,this.onvolume=n,this.version=null,this.pstream=e,this.stream=null,this.sinkIds=new Set(["default"]),this.outputs=new Map,this.status="connecting",this.callSid=null,this.isMuted=!1;const i=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);return this._isSinkSupported=!!i&&typeof HTMLAudioElement<"u"&&HTMLAudioElement.prototype.setSinkId,this._audioContext=i&&r._audioContext,this._audioHelper=r,this._audioProcessorEventObserver=r._getAudioProcessorEventObserver(),this._hasIceCandidates=!1,this._hasIceGatheringFailures=!1,this._iceGatheringTimeoutId=null,this._masterAudio=null,this._masterAudioDeviceId=null,this._mediaStreamSource=null,this._dtmfSender=null,this._dtmfSenderUnsupported=!1,this._callEvents=[],this._nextTimeToPublish=Date.now(),this._onAnswerOrRinging=n,this._onHangup=n,this._remoteStream=null,this._shouldManageStream=!0,this._iceState=Wye,this.options=t=t||{},this.navigator=t.navigator||(typeof navigator<"u"?navigator:null),this.util=t.util||J2,this.codecPreferences=t.codecPreferences,this._onAudioProcessorAdded=s=>{this._handleAudioProcessorEvent(s,!0)},this._onAudioProcessorRemoved=s=>{this._handleAudioProcessorEvent(s,!1)},this._audioProcessorEventObserver.on("add",this._onAudioProcessorAdded),this._audioProcessorEventObserver.on("remove",this._onAudioProcessorRemoved),this}Dt.prototype.uri=function(){return this._uri};Dt.prototype.openDefaultDeviceWithConstraints=function(r){return this._audioHelper._openDefaultDeviceWithConstraints(r).then(this._setInputTracksFromStream.bind(this,!1))};Dt.prototype.setInputTracksFromStream=function(r){const e=this;return this._setInputTracksFromStream(!0,r).then(()=>{e._shouldManageStream=!1})};Dt.prototype._createAnalyser=(r,e)=>{e=Object.assign({fftSize:32,smoothingTimeConstant:.3},e);const t=r.createAnalyser();for(const n in e)t[n]=e[n];return t};Dt.prototype._setVolumeHandler=function(r){this.onvolume=r};Dt.prototype._startPollingVolume=function(){if(!this._audioContext||!this.stream||!this._remoteStream)return;const r=this._audioContext,t=(this._inputAnalyser=this._createAnalyser(r)).frequencyBinCount,n=new Uint8Array(t);this._inputAnalyser2=this._createAnalyser(r,{maxDecibels:0,minDecibels:-127,smoothingTimeConstant:0});const s=(this._outputAnalyser=this._createAnalyser(r)).frequencyBinCount,a=new Uint8Array(s);this._outputAnalyser2=this._createAnalyser(r,{maxDecibels:0,minDecibels:-127,smoothingTimeConstant:0}),this._updateInputStreamSource(this.stream),this._updateOutputStreamSource(this._remoteStream);const c=this;setTimeout(function o(){if(c._audioContext){if(c.status==="closed"){c._inputAnalyser.disconnect(),c._outputAnalyser.disconnect(),c._inputAnalyser2.disconnect(),c._outputAnalyser2.disconnect();return}}else return;c._inputAnalyser.getByteFrequencyData(n);const l=c.util.average(n);c._inputAnalyser2.getByteFrequencyData(n);const d=c.util.average(n);c._outputAnalyser.getByteFrequencyData(a);const h=c.util.average(a);c._outputAnalyser2.getByteFrequencyData(a);const v=c.util.average(a);c.onvolume(l/255,h/255,d,v),setTimeout(o,KA)},KA)};Dt.prototype._stopStream=function(){this._shouldManageStream&&this._audioHelper._stopDefaultInputDeviceStream()};Dt.prototype._updateInputStreamSource=function(r){this._inputStreamSource&&this._inputStreamSource.disconnect();try{this._inputStreamSource=this._audioContext.createMediaStreamSource(r),this._inputStreamSource.connect(this._inputAnalyser),this._inputStreamSource.connect(this._inputAnalyser2)}catch(e){this._log.warn("Unable to update input MediaStreamSource",e),this._inputStreamSource=null}};Dt.prototype._updateOutputStreamSource=function(r){this._outputStreamSource&&this._outputStreamSource.disconnect();try{this._outputStreamSource=this._audioContext.createMediaStreamSource(r),this._outputStreamSource.connect(this._outputAnalyser),this._outputStreamSource.connect(this._outputAnalyser2)}catch(e){this._log.warn("Unable to update output MediaStreamSource",e),this._outputStreamSource=null}};Dt.prototype._setInputTracksFromStream=function(r,e){if(!e)return Promise.reject(new kr("Can not set input stream to null while in a call"));if(!e.getAudioTracks().length)return Promise.reject(new kr("Supplied input stream has no audio tracks"));const t=this.stream,n=()=>(this.mute(this.isMuted),Promise.resolve(this.stream));if(!t)this.stream=r?JA(e,this.options.MediaStream):e;else return this._shouldManageStream&&this._stopStream(),this._sender||(this._sender=this.version.pc.getSenders()[0]),this._sender.replaceTrack(e.getAudioTracks()[0]).then(()=>(this._updateInputStreamSource(e),this.stream=r?JA(e,this.options.MediaStream):e,n()));return n()};Dt.prototype._onInputDevicesChanged=function(){if(!this.stream)return;this.stream.getAudioTracks().every(e=>e.readyState==="ended")&&this._shouldManageStream&&this.openDefaultDeviceWithConstraints({audio:!0})};Dt.prototype._onIceGatheringFailure=function(r){this._hasIceGatheringFailures=!0,this.onicegatheringfailure(r)};Dt.prototype._onMediaConnectionStateChange=function(r){const e=this._iceState;if(e===r||r!=="connected"&&r!=="disconnected"&&r!=="failed")return;this._iceState=r;let t;switch(r){case"connected":e==="disconnected"||e==="failed"?(t="ICE liveliness check succeeded. Connection with Twilio restored",this._log.info(t),this.onreconnected(t)):(t="Media connection established.",this._log.info(t),this.onconnected(t)),this._stopIceGatheringTimeout(),this._hasIceGatheringFailures=!1;break;case"disconnected":t="ICE liveliness check failed. May be having trouble connecting to Twilio",this._log.warn(t),this.ondisconnected(t);break;case"failed":t="Connection with Twilio was interrupted.",this._log.warn(t),this.onfailed(t);break}};Dt.prototype._setSinkIds=function(r){return this._isSinkSupported?(this.sinkIds=new Set(r.forEach?r:[r]),this.version?this._updateAudioOutputs():Promise.resolve()):Promise.reject(new Fn("Audio output selection is not supported by this browser"))};Dt.prototype._startIceGatheringTimeout=function(){this._stopIceGatheringTimeout(),this._iceGatheringTimeoutId=setTimeout(()=>{this._onIceGatheringFailure(qye)},jye)};Dt.prototype._stopIceGatheringTimeout=function(){clearInterval(this._iceGatheringTimeoutId)};Dt.prototype._updateAudioOutputs=function(){const e=Array.from(this.sinkIds).filter(function(s){return!this.outputs.has(s)},this),t=Array.from(this.outputs.keys()).filter(function(s){return!this.sinkIds.has(s)},this),n=this,i=e.map(this._createAudioOutput,this);return Promise.all(i).then(()=>Promise.all(t.map(n._removeAudioOutput,n)))};Dt.prototype._createAudio=function(e){const t=new Audio(e);return this.onaudio(t),t};Dt.prototype._createAudioOutput=function(e){let t=null;this._mediaStreamSource&&(t=this._audioContext.createMediaStreamDestination(),this._mediaStreamSource.connect(t));const n=this._createAudio();fm(n,t&&t.stream?t.stream:this.pcStream,this._audioHelper).catch(()=>this._log.error("Error attaching stream to element (_createAudioOutput)."));const i=this;return n.setSinkId(e).then(()=>n.play()).then(()=>{i.outputs.set(e,{audio:n,dest:t})})};Dt.prototype._removeAudioOutputs=function(){return this._masterAudio&&typeof this._masterAudioDeviceId<"u"&&(this._disableOutput(this,this._masterAudioDeviceId),this.outputs.delete(this._masterAudioDeviceId),this._masterAudioDeviceId=null,this._masterAudio.paused||this._masterAudio.pause(),typeof this._masterAudio.srcObject<"u"?this._masterAudio.srcObject=null:this._masterAudio.src="",this._masterAudio=null),Array.from(this.outputs.keys()).map(this._removeAudioOutput,this)};Dt.prototype._disableOutput=function(e,t){const n=e.outputs.get(t);n&&(n.audio&&(n.audio.pause(),n.audio.src=""),n.dest&&n.dest.disconnect())};Dt.prototype._reassignMasterOutput=function(e,t){const n=e.outputs.get(t);e.outputs.delete(t);const i=this,s=Array.from(e.outputs.keys())[0],a=typeof s=="string"?s:"default";return n.audio.setSinkId(a).then(()=>{i._disableOutput(e,a),e.outputs.set(a,n),e._masterAudioDeviceId=a}).catch(function(){e.outputs.set(t,n),i._log.info("Could not reassign master output. Attempted to roll back.")})};Dt.prototype._removeAudioOutput=function(e){return this._masterAudioDeviceId===e?this._reassignMasterOutput(this,e):(this._disableOutput(this,e),this.outputs.delete(e),Promise.resolve())};Dt.prototype._onAddTrack=function(e,t){const n=e._masterAudio=this._createAudio();fm(n,t,this._audioHelper).then(()=>n.play()).catch(()=>e._log.error("Error attaching stream to element (_onAddTrack)."));const i=Array.from(e.outputs.keys())[0],s=typeof i=="string"?i:"default";e._masterAudioDeviceId=s,e.outputs.set(s,{audio:n});try{e._mediaStreamSource=e._audioContext.createMediaStreamSource(t)}catch(a){this._log.warn("Unable to create a MediaStreamSource from onAddTrack",a),this._mediaStreamSource=null}e.pcStream=t,e._updateAudioOutputs()};Dt.prototype._fallbackOnAddTrack=function(e,t){const n=document&&document.createElement("audio");fm(n,t,this._audioHelper).then(()=>n.play()).catch(()=>e._log.error("Error attaching stream to element (_fallbackOnAddTrack).")),e.outputs.set("default",{audio:n})};Dt.prototype._setEncodingParameters=function(r){if(!r||!this._sender||typeof this._sender.getParameters!="function"||typeof this._sender.setParameters!="function")return;const e=this._sender.getParameters();!e.priority&&!(e.encodings&&e.encodings.length)||(e.priority="high",e.encodings&&e.encodings.length&&e.encodings.forEach(t=>{t.priority="high",t.networkPriority="high"}),this._sender.setParameters(e))};Dt.prototype._setupPeerConnection=function(r){const e=this,t=new(this.options.rtcpcFactory||ts)({RTCPeerConnection:this.options.RTCPeerConnection});t.create(r),Vye(t.pc,this.stream);const n=RTCRtpReceiver.getCapabilities("audio").codecs;this._log.debug("sorting codecs",n,this.codecPreferences);const i=K2(n,this.codecPreferences),[s]=t.pc.getTransceivers();this._log.debug("setting sorted codecs",i),s.setCodecPreferences(i);const a="ontrack"in t.pc?"ontrack":"onaddstream";return t.pc[a]=c=>{const o=e._remoteStream=c.stream||c.streams[0];typeof t.pc.getSenders=="function"&&(this._sender=t.pc.getSenders()[0]),e._isSinkSupported?e._onAddTrack(e,o):e._fallbackOnAddTrack(e,o),e._startPollingVolume()},t};Dt.prototype._maybeSetIceAggressiveNomination=function(r){return this.options.forceAggressiveIceNomination?xye(r):r};Dt.prototype._setupChannel=function(){const r=this.version.pc;this.version.pc.onopen=()=>{this.status="open",this.onopen()},this.version.pc.onstatechange=()=>{this.version.pc&&this.version.pc.readyState==="stable"&&(this.status="open",this.onopen())},this.version.pc.onsignalingstatechange=()=>{const e=r.signalingState;this._log.info(`signalingState is "${e}"`),this.version.pc&&this.version.pc.signalingState==="stable"&&(this.status="open",this.onopen()),this.onsignalingstatechange(r.signalingState)},r.onconnectionstatechange=e=>{let t=r.connectionState;if(!t&&e&&e.target){const n=e.target;t=n.connectionState||n.connectionState_,this._log.info(`pc.connectionState not detected. Using target PC. State=${t}`)}t?this._log.info(`pc.connectionState is "${t}"`):this._log.warn(`onconnectionstatechange detected but state is "${t}"`),this.onpcconnectionstatechange(t),this._onMediaConnectionStateChange(t)},r.onicecandidate=e=>{const{candidate:t}=e;t&&(this._hasIceCandidates=!0,this.onicecandidate(t),this._setupRTCIceTransportListener()),this._log.info(`ICE Candidate: ${JSON.stringify(t)}`)},r.onicegatheringstatechange=()=>{const e=r.iceGatheringState;e==="gathering"?this._startIceGatheringTimeout():e==="complete"&&(this._stopIceGatheringTimeout(),this._hasIceCandidates||this._onIceGatheringFailure(Bye),this._hasIceCandidates&&this._hasIceGatheringFailures&&this._startIceGatheringTimeout()),this._log.info(`pc.iceGatheringState is "${r.iceGatheringState}"`),this.onicegatheringstatechange(e)},r.oniceconnectionstatechange=()=>{this._log.info(`pc.iceConnectionState is "${r.iceConnectionState}"`),this.oniceconnectionstatechange(r.iceConnectionState),this._onMediaConnectionStateChange(r.iceConnectionState)}};Dt.prototype._initializeMediaStream=function(r){return this.status==="open"?!1:this.pstream.status==="disconnected"?(this.onerror({info:{code:31e3,message:"Cannot establish connection. Client is disconnected",twilioError:new _s.ConnectionDisconnected}}),this.close(),!1):(this.version=this._setupPeerConnection(r),this._setupChannel(),!0)};Dt.prototype._removeReconnectionListeners=function(){this.pstream&&(this.pstream.removeListener("answer",this._onAnswerOrRinging),this.pstream.removeListener("hangup",this._onHangup))};Dt.prototype._setupRTCDtlsTransportListener=function(){const r=this.getRTCDtlsTransport();if(!r||r.onstatechange)return;const e=()=>{this._log.info(`dtlsTransportState is "${r.state}"`),this.ondtlstransportstatechange(r.state)};e(),r.onstatechange=e};Dt.prototype._setupRTCIceTransportListener=function(){const r=this._getRTCIceTransport();!r||r.onselectedcandidatepairchange||(r.onselectedcandidatepairchange=()=>this.onselectedcandidatepairchange(r.getSelectedCandidatePair()))};Dt.prototype.iceRestart=function(){this._log.info("Attempting to restart ICE..."),this._hasIceCandidates=!1,this.version.createOffer(this.options.maxAverageBitrate,{iceRestart:!0}).then(()=>{this._removeReconnectionListeners(),this._onAnswerOrRinging=r=>{if(this._removeReconnectionListeners(),!r.sdp||this.version.pc.signalingState!=="have-local-offer"){const t=`Invalid state or param during ICE Restart:hasSdp:${!!r.sdp}, signalingState:${this.version.pc.signalingState}`;this._log.warn(t);return}const e=this._maybeSetIceAggressiveNomination(r.sdp);this._answerSdp=e,this.status!=="closed"&&this.version.processAnswer(this.codecPreferences,e,null,t=>{const n=t&&t.message?t.message:t;this._log.error(`Failed to process answer during ICE Restart. Error: ${n}`)})},this._onHangup=()=>{this._log.info("Received hangup during ICE Restart"),this._removeReconnectionListeners()},this.pstream.on("answer",this._onAnswerOrRinging),this.pstream.on("hangup",this._onHangup),this.pstream.reinvite(this.version.getSDP(),this.callSid)}).catch(r=>{const e=r&&r.message?r.message:r;this._log.error(`Failed to createOffer during ICE Restart. Error: ${e}`),this.onfailed(e)})};Dt.prototype.makeOutgoingCall=function(r,e,t,n,i){if(!this._initializeMediaStream(n))return;const s=this;this.callSid=t;function a(){s.options&&s._setEncodingParameters(s.options.dscp),i(s.version.pc)}function c(d){const h=d.message||d;s.onerror({info:{code:31e3,message:`Error processing answer: ${h}`,twilioError:new ga.ClientRemoteDescFailed}})}this._onAnswerOrRinging=d=>{if(!d.sdp)return;const h=this._maybeSetIceAggressiveNomination(d.sdp);s._answerSdp=h,s.status!=="closed"&&s.version.processAnswer(this.codecPreferences,h,a,c),s.pstream.removeListener("answer",s._onAnswerOrRinging),s.pstream.removeListener("ringing",s._onAnswerOrRinging)},this.pstream.on("answer",this._onAnswerOrRinging),this.pstream.on("ringing",this._onAnswerOrRinging);function o(){s.status!=="closed"&&(e?s.pstream.reconnect(s.version.getSDP(),s.callSid,e):s.pstream.invite(s.version.getSDP(),s.callSid,r),s._setupRTCDtlsTransportListener())}function l(d){const h=d.message||d;s.onerror({info:{code:31e3,message:`Error creating the offer: ${h}`,twilioError:new ga.ClientLocalDescFailed}})}this.version.createOffer(this.options.maxAverageBitrate,{audio:!0},o,l)};Dt.prototype.answerIncomingCall=function(r,e,t,n){if(!this._initializeMediaStream(t))return;e=this._maybeSetIceAggressiveNomination(e),this._answerSdp=e.replace(/^a=setup:actpass$/gm,"a=setup:passive"),this.callSid=r;const i=this;function s(){i.status!=="closed"&&(i.pstream.answer(i.version.getSDP(),r),i.options&&i._setEncodingParameters(i.options.dscp),n(i.version.pc),i._setupRTCDtlsTransportListener())}function a(c){const o=c.message||c;i.onerror({info:{code:31e3,message:`Error creating the answer: ${o}`,twilioError:new ga.ClientRemoteDescFailed}})}this.version.processSDP(this.options.maxAverageBitrate,this.codecPreferences,e,{audio:!0},s,a)};Dt.prototype.close=function(){this.version&&this.version.pc&&(this.version.pc.signalingState!=="closed"&&this.version.pc.close(),this.version.pc=null),this.stream&&(this.mute(!1),this._stopStream()),this.stream=null,this._removeReconnectionListeners(),this._stopIceGatheringTimeout(),this._audioHelper._destroyRemoteProcessedStream(),this._audioProcessorEventObserver.removeListener("add",this._onAudioProcessorAdded),this._audioProcessorEventObserver.removeListener("remove",this._onAudioProcessorRemoved),Promise.all(this._removeAudioOutputs()).catch(()=>{}),this._mediaStreamSource&&this._mediaStreamSource.disconnect(),this._inputAnalyser&&this._inputAnalyser.disconnect(),this._outputAnalyser&&this._outputAnalyser.disconnect(),this._inputAnalyser2&&this._inputAnalyser2.disconnect(),this._outputAnalyser2&&this._outputAnalyser2.disconnect(),this.status="closed",this.onclose()};Dt.prototype.reject=function(r){this.callSid=r};Dt.prototype.ignore=function(r){this.callSid=r};Dt.prototype.mute=function(r){this.isMuted=r,this.stream&&(this._sender&&this._sender.track?this._sender.track.enabled=!r:(typeof this.stream.getAudioTracks=="function"?this.stream.getAudioTracks():this.stream.audioTracks).forEach(t=>{t.enabled=!r}))};Dt.prototype.getOrCreateDTMFSender=function(){if(this._dtmfSender||this._dtmfSenderUnsupported)return this._dtmfSender||null;const e=this,t=this.version.pc;if(!t)return this._log.warn("No RTCPeerConnection available to call createDTMFSender on"),null;if(typeof t.getSenders=="function"&&(typeof RTCDTMFSender=="function"||typeof RTCDtmfSender=="function")){const n=t.getSenders().find(i=>i.dtmf);if(n)return this._log.info("Using RTCRtpSender#dtmf"),this._dtmfSender=n.dtmf,this._dtmfSender}if(typeof t.createDTMFSender=="function"&&typeof t.getLocalStreams=="function"){const n=t.getLocalStreams().map(i=>{const s=e._getAudioTracks(i);return s&&s[0]})[0];return n?(this._log.info("Creating RTCDTMFSender"),this._dtmfSender=t.createDTMFSender(n),this._dtmfSender):(this._log.warn("No local audio MediaStreamTrack available on the RTCPeerConnection to pass to createDTMFSender"),null)}return this._log.info("RTCPeerConnection does not support RTCDTMFSender"),this._dtmfSenderUnsupported=!0,null};Dt.prototype.getRTCDtlsTransport=function(){const e=this.version&&this.version.pc&&typeof this.version.pc.getSenders=="function"&&this.version.pc.getSenders()[0];return e&&e.transport||null};Dt.prototype._canStopMediaStreamTrack=()=>typeof MediaStreamTrack.prototype.stop=="function";Dt.prototype._getAudioTracks=r=>typeof r.getAudioTracks=="function"?r.getAudioTracks():r.audioTracks;Dt.prototype._getRTCIceTransport=function(){const e=this.getRTCDtlsTransport();return e&&e.iceTransport||null};Dt.protocol=ts.test()?new ts:null;Dt.prototype._handleAudioProcessorEvent=function(r,e){if(!r||!this._remoteStream)return;let t=null;this._masterAudio?(this._log.info("Setting audio source for master audio."),t=this._masterAudio):(this._log.info("No master audio. Setting audio source for default audio output."),t=this.outputs.get("default").audio),fm(t,this._remoteStream,this._audioHelper).then(()=>{const n=e?"Successfully updated audio source with processed stream":"Successfully reverted audio source to original stream";this._log.info(n),t.paused&&(this._log.info("Resuming audio playback"),t.play())}).catch(()=>{const n=e?"Failed to update audio source":"Failed to revert audio source";this._log.error(n)})};function Vye(r,e){typeof r.addTrack=="function"?e.getAudioTracks().forEach(t=>{r.addTrack(t,e)}):r.addStream(e)}function JA(r,e){let t;return e?t=new e:typeof MediaStream<"u"?t=new MediaStream:t=new webkitMediaStream,r.getAudioTracks().forEach(t.addTrack,t),t}function fm(r,e,t){return t._maybeCreateRemoteProcessedStream(e).then(n=>{if(typeof r.srcObject<"u")r.srcObject=n;else if(typeof r.mozSrcObject<"u")r.mozSrcObject=n;else if(typeof r.src<"u"){const i=r.options.window||window;r.src=(i.URL||i.webkitURL).createObjectURL(n)}else return Promise.reject();return Promise.resolve()})}Dt.enabled=ts.test();function Hye(){return ts.test()}function Gye(){return typeof RTCIceGatherer<"u"?"ORTC":"WebRTC"}function zye(r,e){return e=e||{},e.util=e.util||J2,e.navigator=e.navigator||(typeof navigator<"u"?navigator:null),new Promise((t,n)=>{if(!e.navigator)throw new Fn("getUserMedia is not supported");switch("function"){case typeof(e.navigator.mediaDevices&&e.navigator.mediaDevices.getUserMedia):return t(e.navigator.mediaDevices.getUserMedia(r));case typeof e.navigator.webkitGetUserMedia:return e.navigator.webkitGetUserMedia(r,t,n);case typeof e.navigator.mozGetUserMedia:return e.navigator.mozGetUserMedia(r,t,n);case typeof e.navigator.getUserMedia:return e.navigator.getUserMedia(r,t,n);default:throw new Fn("getUserMedia is not supported")}}).catch(t=>{throw e.util.isFirefox()&&t.name==="NotReadableError"?new Fn(`Firefox does not currently support opening multiple audio input trackssimultaneously, even across different tabs.
|
|
568
|
-
Related Bugzilla thread: https://bugzilla.mozilla.org/show_bug.cgi?id=1299324`):t})}function Kye(){if(typeof window!="object")throw new Fn("This platform is not supported.");const{crypto:r}=window;if(typeof r!="object")throw new Fn("The `crypto` module is not available on this platform.");if(typeof r.getRandomValues!="function")throw new Fn("The function `crypto.getRandomValues` is not available on this platform.");if(typeof window.Uint8Array!="function")throw new Fn("The `Uint8Array` module is not available on this platform.");return r.getRandomValues(new window.Uint8Array(16)).reduce((e,t)=>`${e}${t.toString(16).padStart(2,"0")}`,"")}function Ew(){return`KX${Kye()}`}let Jye=class{constructor(){this._promise=new Promise((e,t)=>{this._resolve=e,this._reject=t})}get promise(){return this._promise}reject(e){this._reject(e)}resolve(e){this._resolve(e)}};class Yye{constructor(){this._operations=[]}enqueue(e){const t=!!this._operations.length,n=new Jye;return this._operations.push({deferred:n,callback:e}),t||this._processQueue(),n.promise}_processQueue(){return yi(this,void 0,void 0,function*(){for(;this._operations.length;){const{deferred:e,callback:t}=this._operations[0];let n,i,s;try{n=yield t(),s=!0}catch(a){i=a}this._operations.shift(),s?e.resolve(n):e.reject(i)}})}}class Xye{get reject(){return this._reject}get resolve(){return this._resolve}constructor(){this.promise=new Promise((e,t)=>{this._resolve=e,this._reject=t})}}let Qye=class{constructor(){this._eventEmitter=new Ss.EventEmitter}addEventListener(e,t){return this._eventEmitter.addListener(e,t)}dispatchEvent(e,...t){return this._eventEmitter.emit(e,...t)}removeEventListener(e,t){return this._eventEmitter.removeListener(e,t)}};class YA extends Qye{get destination(){return this._destination}get loop(){return this._loop}set loop(e){const t=this;function n(){t._audioNode.removeEventListener("ended",n),t.pause()}!e&&this.loop&&!this.paused&&this._audioNode.addEventListener("ended",n),this._loop=e}get muted(){return this._gainNode.gain.value===0}set muted(e){this._gainNode.gain.value=e?0:1}get paused(){return this._audioNode===null}get src(){return this._src}set src(e){this._load(e)}get srcObject(){return this._audioElement.srcObject}set srcObject(e){this._audioElement.srcObject=e}get sinkId(){return this._sinkId}constructor(e,t={},n={}){super(),this._audioNode=null,this._loop=!1,this._pendingPlayDeferreds=[],this._sinkId="default",this._src="",typeof t!="string"&&(n=t),this._audioContext=e,this._audioElement=new(n.AudioFactory||Audio),this._bufferPromise=this._createPlayDeferred().promise,this._destination=this._audioContext.destination,this._gainNode=this._audioContext.createGain(),this._gainNode.connect(this._destination),this._XMLHttpRequest=n.XMLHttpRequestFactory||XMLHttpRequest,this.addEventListener("canplaythrough",()=>{this._resolvePlayDeferreds()}),typeof t=="string"&&(this.src=t)}load(){this._load(this._src)}pause(){this.paused||(this._audioElement.pause(),this._audioNode.stop(),this._audioNode.disconnect(this._gainNode),this._audioNode=null,this._rejectPlayDeferreds(new Error("The play() request was interrupted by a call to pause().")))}play(){return yi(this,void 0,void 0,function*(){if(!this.paused){if(yield this._bufferPromise,!this.paused)return;throw new Error("The play() request was interrupted by a call to pause().")}this._audioNode=this._audioContext.createBufferSource(),this._audioNode.loop=this.loop,this._audioNode.addEventListener("ended",()=>{this._audioNode&&this._audioNode.loop||this.dispatchEvent("ended")});const e=yield this._bufferPromise;if(this.paused)throw new Error("The play() request was interrupted by a call to pause().");if(this._audioNode.buffer=e,this._audioNode.connect(this._gainNode),this._audioNode.start(),this._audioElement.srcObject)return this._audioElement.play()})}setSinkId(e){return yi(this,void 0,void 0,function*(){if(typeof this._audioElement.setSinkId!="function")throw new Error("This browser does not support setSinkId.");if(e!==this.sinkId){if(e==="default"){this.paused||this._gainNode.disconnect(this._destination),this._audioElement.srcObject=null,this._destination=this._audioContext.destination,this._gainNode.connect(this._destination),this._sinkId=e;return}yield this._audioElement.setSinkId(e),!this._audioElement.srcObject&&(this._gainNode.disconnect(this._audioContext.destination),this._destination=this._audioContext.createMediaStreamDestination(),this._audioElement.srcObject=this._destination.stream,this._sinkId=e,this._gainNode.connect(this._destination))}})}_createPlayDeferred(){const e=new Xye;return this._pendingPlayDeferreds.push(e),e}_load(e){this._src&&this._src!==e&&this.pause(),this._src=e,this._bufferPromise=new Promise((t,n)=>yi(this,void 0,void 0,function*(){if(!e)return this._createPlayDeferred().promise;const i=yield Zye(this._audioContext,this._XMLHttpRequest,e);this.dispatchEvent("canplaythrough"),t(i)}))}_rejectPlayDeferreds(e){const t=this._pendingPlayDeferreds;t.splice(0,t.length).forEach(({reject:n})=>n(e))}_resolvePlayDeferreds(e){const t=this._pendingPlayDeferreds;t.splice(0,t.length).forEach(({resolve:n})=>n(e))}}function Zye(r,e,t){return yi(this,void 0,void 0,function*(){const n=new e;n.open("GET",t,!0),n.responseType="arraybuffer";const i=yield new Promise(s=>{n.addEventListener("load",s),n.send()});try{return r.decodeAudioData(i.target.response)}catch{return new Promise(a=>{r.decodeAudioData(i.target.response,a)})}})}function ao(r,e,t){if(!(this instanceof ao))return new ao(r,e,t);if(!r||!e)throw new kr("name and url are required arguments");t=Object.assign({AudioFactory:typeof Audio<"u"?Audio:null,maxDuration:0,shouldLoop:!1},t),t.AudioPlayer=t.audioContext?YA.bind(YA,t.audioContext):t.AudioFactory,Object.defineProperties(this,{_Audio:{value:t.AudioPlayer},_activeEls:{value:new Map},_isSinkSupported:{value:t.AudioFactory!==null&&typeof t.AudioFactory.prototype.setSinkId=="function"},_maxDuration:{value:t.maxDuration},_maxDurationTimeout:{value:null,writable:!0},_operations:{value:new Yye},_playPromise:{value:null,writable:!0},_shouldLoop:{value:t.shouldLoop},_sinkIds:{value:["default"]},isPlaying:{enumerable:!0,get(){return!!this._playPromise}},name:{enumerable:!0,value:r},url:{enumerable:!0,value:e}}),this._Audio&&this._play(!0,!1)}function nU(r){r&&(r.pause(),r.src="",r.srcObject=null,r.load())}ao.prototype._playAudioElement=function(e,t,n){const i=this._activeEls.get(e);if(!i)throw new kr(`sinkId: "${e}" doesn't have an audio element`);return i.muted=!!t,i.loop=!!n,i.play().then(()=>i).catch(s=>{throw nU(i),this._activeEls.delete(e),s})};ao.prototype._play=function(e,t){this.isPlaying&&this._stop(),this._maxDuration>0&&(this._maxDurationTimeout=setTimeout(this._stop.bind(this),this._maxDuration)),t=typeof t=="boolean"?t:this._shouldLoop;const n=this;return this._playPromise=Promise.all(this._sinkIds.map(function(a){if(!n._Audio)return Promise.resolve();let c=n._activeEls.get(a);return c?n._playAudioElement(a,e,t):(c=new n._Audio(n.url),typeof c.setAttribute=="function"&&c.setAttribute("crossorigin","anonymous"),new Promise(o=>{c.addEventListener("canplaythrough",o)}).then(()=>(n._isSinkSupported?c.setSinkId(a):Promise.resolve()).then(function(){return n._activeEls.set(a,c),n._playPromise?n._playAudioElement(a,e,t):Promise.resolve()})))}))};ao.prototype._stop=function(){this._activeEls.forEach((e,t)=>{this._sinkIds.includes(t)?(e.pause(),e.currentTime=0):(nU(e),this._activeEls.delete(t))}),clearTimeout(this._maxDurationTimeout),this._playPromise=null,this._maxDurationTimeout=null};ao.prototype.setSinkIds=function(e){this._isSinkSupported&&(e=e.forEach?e:[e],[].splice.apply(this._sinkIds,[0,this._sinkIds.length].concat(e)))};ao.prototype.stop=function(){this._operations.enqueue(()=>(this._stop(),Promise.resolve()))};ao.prototype.play=function(){return this._operations.enqueue(()=>this._play())};const e_e=3e4,t_e=2e3,r_e="twilio-js-sdk",n_e='Parameter "token" must be of type "string".';class ft extends Ss.EventEmitter{static get audioContext(){return ft._audioContext}static get extension(){const e=typeof document<"u"?document.createElement("audio"):{canPlayType:!1};let t;try{t=e.canPlayType&&!!e.canPlayType("audio/mpeg").replace(/no/,"")}catch{t=!1}let n;try{n=e.canPlayType&&!!e.canPlayType("audio/ogg;codecs='vorbis'").replace(/no/,"")}catch{n=!1}return n&&!t?"ogg":"mp3"}static get isSupported(){return Hye()}static get packageName(){return H2}static runPreflight(e,t){return new Qr(e,Object.assign({audioContext:ft._getOrCreateAudioContext()},t))}static toString(){return"[Twilio.Device class]"}static get version(){return ol}static _getOrCreateAudioContext(){return ft._audioContext||(typeof AudioContext<"u"?ft._audioContext=new AudioContext:typeof webkitAudioContext<"u"&&(ft._audioContext=new webkitAudioContext)),ft._audioContext}constructor(e,t={}){if(super(),this._activeCall=null,this._audio=null,this._audioProcessorEventObserver=null,this._callInputStream=null,this._calls=[],this._callSinkIds=["default"],this._chunderURIs=[],this._defaultOptions={allowIncomingWhileBusy:!1,closeProtection:!1,codecPreferences:[dt.Codec.PCMU,dt.Codec.Opus],dscp:!0,enableImprovedSignalingErrorPrecision:!1,forceAggressiveIceNomination:!1,logLevel:Gr.levels.ERROR,maxCallSignalingTimeoutMs:0,preflight:!1,sounds:{},tokenRefreshMs:1e4,voiceEventSidGenerator:Ew},this._edge=null,this._home=null,this._identity=null,this._log=new On("Device"),this._makeCallPromise=null,this._options={},this._preferredURI=null,this._publisher=null,this._region=null,this._regTimer=null,this._shouldReRegister=!1,this._soundcache=new Map,this._state=ft.State.Unregistered,this._stateEventMapping={[ft.State.Destroyed]:ft.EventName.Destroyed,[ft.State.Unregistered]:ft.EventName.Unregistered,[ft.State.Registering]:ft.EventName.Registering,[ft.State.Registered]:ft.EventName.Registered},this._stream=null,this._streamConnectedPromise=null,this._tokenWillExpireTimeout=null,this._createDefaultPayload=s=>{const a={aggressive_nomination:this._options.forceAggressiveIceNomination,browser_extension:this._isBrowserExtension,dscp:!!this._options.dscp,ice_restart_enabled:!0,platform:Gye(),sdk_version:ol};function c(o,l){l&&(a[o]=l)}if(s){const o=s.parameters.CallSid;c("call_sid",/^TJ/.test(o)?void 0:o),c("temp_call_sid",s.outboundConnectionId),c("audio_codec",s.codec),a.direction=s.direction}return c("gateway",this._stream&&this._stream.gateway),c("region",this._stream&&this._stream.region),a},this._onSignalingClose=()=>{this._stream=null,this._streamConnectedPromise=null},this._onSignalingConnected=s=>{var a;const c=Pye(s.region);if(this._edge=s.edge||Eye[c]||s.region,this._region=c||s.region,this._home=s.home,(a=this._publisher)===null||a===void 0||a.setHost(VA(s.home)),s.token&&(this._identity=s.token.identity,typeof s.token.ttl=="number"&&typeof this._options.tokenRefreshMs=="number")){const l=s.token.ttl*1e3,d=Math.max(0,l-this._options.tokenRefreshMs);this._tokenWillExpireTimeout=setTimeout(()=>{this._log.debug("#tokenWillExpire"),this.emit("tokenWillExpire",this),this._tokenWillExpireTimeout&&(clearTimeout(this._tokenWillExpireTimeout),this._tokenWillExpireTimeout=null)},d)}const o=this._getChunderws()||GA(this._edge);if(o.length>0){const[l]=o;this._preferredURI=HA(l)}else this._log.warn("Could not parse a preferred URI from the stream#connected event.");this._shouldReRegister&&this.register()},this._onSignalingError=s=>{if(typeof s!="object"){this._log.warn("Invalid signaling error payload",s);return}const{error:a,callsid:c,voiceeventsid:o}=s;if(typeof a!="object"||o){this._log.warn("Ignoring signaling error payload",{originalError:a,voiceeventsid:o});return}const l=typeof c=="string"&&this._findCall(c)||void 0,{code:d,message:h}=a;let{twilioError:v}=a;if(typeof d=="number")if(d===31201)v=new In.AuthenticationFailed(a);else if(d===31204)v=new In.AccessTokenInvalid(a);else if(d===31205)this._stopRegistrationTimer(),v=new In.AccessTokenExpired(a);else{const y=_w(!!this._options.enableImprovedSignalingErrorPrecision,d);typeof y<"u"&&(v=new y(a))}v||(this._log.error("Unknown signaling error: ",a),v=new ai.UnknownError(h,a)),this._log.error("Received error: ",v),this._log.debug("#error",a),this.emit(ft.EventName.Error,v,l)},this._onSignalingInvite=s=>yi(this,void 0,void 0,function*(){var a;const c=!!this._activeCall;if(c&&!this._options.allowIncomingWhileBusy){this._log.info("Device busy; ignoring incoming invite");return}if(!s.callsid||!s.sdp){this._log.debug("#error",s),this.emit(ft.EventName.Error,new Nu.BadRequest("Malformed invite from gateway"));return}const o=s.parameters||{};o.CallSid=o.CallSid||s.callsid;const l=Object.assign({},z2(o.Params));this._makeCallPromise=this._makeCall(l,{callParameters:o,enableImprovedSignalingErrorPrecision:!!this._options.enableImprovedSignalingErrorPrecision,offerSdp:s.sdp,reconnectToken:s.reconnect,voiceEventSidGenerator:this._options.voiceEventSidGenerator});let d;try{d=yield this._makeCallPromise}finally{this._makeCallPromise=null}this._calls.push(d),d.once("accept",()=>{this._soundcache.get(ft.SoundName.Incoming).stop(),this._publishNetworkChange()});const h=!((a=this._audio)===null||a===void 0)&&a.incoming()&&!c?()=>this._soundcache.get(ft.SoundName.Incoming).play():()=>Promise.resolve();this._showIncomingCall(d,h)}),this._onSignalingOffline=()=>{this._log.info("Stream is offline"),this._edge=null,this._region=null,this._shouldReRegister=this.state!==ft.State.Unregistered,this._setState(ft.State.Unregistered)},this._onSignalingReady=()=>{this._log.info("Stream is ready"),this._setState(ft.State.Registered)},this._publishNetworkChange=()=>{this._activeCall&&this._networkInformation&&this._publisher.info("network-information","network-change",{connection_type:this._networkInformation.type,downlink:this._networkInformation.downlink,downlinkMax:this._networkInformation.downlinkMax,effective_type:this._networkInformation.effectiveType,rtt:this._networkInformation.rtt},this._activeCall)},this._updateInputStream=s=>{const a=this._activeCall;return a&&!s?Promise.reject(new Bs("Cannot unset input device while a call is in progress.")):(this._callInputStream=s,a?a._setInputTracksFromStream(s):Promise.resolve())},this._updateSinkIds=(s,a)=>(s==="ringtone"?this._updateRingtoneSinkIds(a):this._updateSpeakerSinkIds(a)).then(()=>{this._publisher.info("audio",`${s}-devices-set`,{audio_device_ids:a},this._activeCall)},o=>{throw this._publisher.error("audio",`${s}-devices-set-failed`,{audio_device_ids:a,message:o.message},this._activeCall),o}),this._setupLoglevel(t.logLevel),this._logOptions("constructor",t),this.updateToken(e),cm())throw new Fn("Microsoft Edge Legacy (https://support.microsoft.com/en-us/help/4533505/what-is-microsoft-edge-legacy) is deprecated and will not be able to connect to Twilio to make or receive calls after September 1st, 2020. Please see this documentation for a list of supported browsers https://www.twilio.com/docs/voice/client/javascript#supported-browsers");if(!ft.isSupported&&t.ignoreBrowserSupport)throw window&&window.location&&window.location.protocol==="http:"?new Fn("twilio.js wasn't able to find WebRTC browser support. This is most likely because this page is served over http rather than https, which does not support WebRTC in many browsers. Please load this page over https and try again."):new Fn("twilio.js 1.3+ SDKs require WebRTC browser support. For more information, see <https://www.twilio.com/docs/api/client/twilio-js>. If you have any questions about this announcement, please contact Twilio Support at <help@twilio.com>.");const n=globalThis,i=n.msBrowser||n.browser||n.chrome;if(this._isBrowserExtension=!!i&&!!i.runtime&&!!i.runtime.id||!!n.safari&&!!n.safari.extension,this._isBrowserExtension&&this._log.info("Running as browser extension."),navigator){const s=navigator;this._networkInformation=s.connection||s.mozConnection||s.webkitConnection}this._networkInformation&&typeof this._networkInformation.addEventListener=="function"&&this._networkInformation.addEventListener("change",this._publishNetworkChange),ft._getOrCreateAudioContext(),ft._audioContext&&(ft._dialtonePlayer||(ft._dialtonePlayer=new Yme(ft._audioContext))),this._boundDestroy=this.destroy.bind(this),this._boundConfirmClose=this._confirmClose.bind(this),typeof window<"u"&&window.addEventListener&&window.addEventListener("pagehide",this._boundDestroy),this.updateOptions(t)}get audio(){return this._audio}connect(){return yi(this,arguments,void 0,function*(e={}){if(this._log.debug(".connect",JSON.stringify(e)),this._throwIfDestroyed(),this._activeCall||this._makeCallPromise)throw new Bs("A Call is already active");let t,n,i;if(e.connectToken){try{const l=JSON.parse(decodeURIComponent(atob(e.connectToken)));t=l.customParameters,n=l.parameters,i=l.signalingReconnectToken}catch{throw new kr("Cannot parse connectToken")}if(!n||!n.CallSid||!i)throw new kr("Invalid connectToken")}let s=!1,a={};const c={enableImprovedSignalingErrorPrecision:!!this._options.enableImprovedSignalingErrorPrecision,rtcConfiguration:e.rtcConfiguration,voiceEventSidGenerator:this._options.voiceEventSidGenerator};i&&n?(s=!0,c.callParameters=n,c.reconnectCallSid=n.CallSid,c.reconnectToken=i,a=t||a):a=e.params||a;let o;this._makeCallPromise=this._makeCall(a,c,s);try{o=this._activeCall=yield this._makeCallPromise}finally{this._makeCallPromise=null}return this._calls.splice(0).forEach(l=>l.ignore()),this._soundcache.get(ft.SoundName.Incoming).stop(),o.accept({rtcConstraints:e.rtcConstraints}),this._publishNetworkChange(),o})}get calls(){return this._calls}destroy(){var e;this._log.debug(".destroy"),this._log.debug("Rejecting any incoming calls"),this._calls.slice(0).forEach(n=>n.reject()),this.disconnectAll(),this._stopRegistrationTimer(),this._destroyStream(),this._destroyAudioHelper(),(e=this._audioProcessorEventObserver)===null||e===void 0||e.destroy(),this._destroyPublisher(),this._networkInformation&&typeof this._networkInformation.removeEventListener=="function"&&this._networkInformation.removeEventListener("change",this._publishNetworkChange),typeof window<"u"&&window.removeEventListener&&(window.removeEventListener("beforeunload",this._boundConfirmClose),window.removeEventListener("pagehide",this._boundDestroy)),this._setState(ft.State.Destroyed),Ss.EventEmitter.prototype.removeAllListeners.call(this)}disconnectAll(){this._log.debug(".disconnectAll"),this._calls.splice(0).forEach(t=>t.disconnect()),this._activeCall&&this._activeCall.disconnect()}get edge(){return this._edge}get home(){return this._home}get identity(){return this._identity}get isBusy(){return!!this._activeCall}register(){return yi(this,void 0,void 0,function*(){if(this._log.debug(".register"),this.state!==ft.State.Unregistered)throw new Bs(`Attempt to register when device is in state "${this.state}". Must be "${ft.State.Unregistered}".`);this._shouldReRegister=!1,this._setState(ft.State.Registering),yield this._streamConnectedPromise||this._setupStream(),yield this._sendPresence(!0),yield Sw(this,ft.State.Registered,ft.State.Unregistered)})}get state(){return this._state}get token(){return this._token}toString(){return"[Twilio.Device instance]"}unregister(){return yi(this,void 0,void 0,function*(){if(this._log.debug(".unregister"),this.state!==ft.State.Registered)throw new Bs(`Attempt to unregister when device is in state "${this.state}". Must be "${ft.State.Registered}".`);this._shouldReRegister=!1;const e=yield this._streamConnectedPromise,t=new Promise(n=>{e.on("offline",n)});yield this._sendPresence(!1),yield t})}updateOptions(e={}){if(this._logOptions("updateOptions",e),this.state===ft.State.Destroyed)throw new Bs(`Attempt to "updateOptions" when device is in state "${this.state}".`);this._options=Object.assign(Object.assign(Object.assign({},this._defaultOptions),this._options),e);const t=new Set(this._chunderURIs),n=this._chunderURIs=(this._getChunderws()||GA(this._options.edge)).map(HA);let i=t.size!==n.length;if(!i){for(const s of n)if(!t.has(s)){i=!0;break}}if(this.isBusy&&i)throw new Bs("Cannot change Edge while on an active Call");this._setupLoglevel(this._options.logLevel);for(const s of Object.keys(ft._defaultSounds)){const a=ft._defaultSounds[s],c=`${ET}/${a.filename}.${ft.extension}?cache=${ol}`,o=this._options.sounds&&this._options.sounds[s]||c,l=new(this._options.Sound||ao)(s,o,{audioContext:this._options.disableAudioContextSounds?null:ft.audioContext,maxDuration:a.maxDuration,shouldLoop:a.shouldLoop});this._soundcache.set(s,l)}this._setupAudioHelper(),this._setupPublisher(),i&&this._streamConnectedPromise&&this._setupStream(),typeof window<"u"&&typeof window.addEventListener=="function"&&this._options.closeProtection&&(window.removeEventListener("beforeunload",this._boundConfirmClose),window.addEventListener("beforeunload",this._boundConfirmClose))}updateToken(e){if(this._log.debug(".updateToken"),this.state===ft.State.Destroyed)throw new Bs(`Attempt to "updateToken" when device is in state "${this.state}".`);if(typeof e!="string")throw new kr(n_e);this._token=e,this._stream&&this._stream.setToken(this._token),this._publisher&&this._publisher.setToken(this._token)}_confirmClose(e){if(!this._activeCall)return"";const t=this._options.closeProtection||!1,n=typeof t!="string"?"A call is currently in-progress. Leaving or reloading this page will end the call.":t;return(e||window.event).returnValue=n,n}_destroyAudioHelper(){this._audio&&(this._audio._destroy(),this._audio=null)}_destroyPublisher(){this._publisher&&(this._publisher=null)}_destroyStream(){this._stream&&(this._stream.removeListener("close",this._onSignalingClose),this._stream.removeListener("connected",this._onSignalingConnected),this._stream.removeListener("error",this._onSignalingError),this._stream.removeListener("invite",this._onSignalingInvite),this._stream.removeListener("offline",this._onSignalingOffline),this._stream.removeListener("ready",this._onSignalingReady),this._stream.destroy(),this._stream=null),this._onSignalingOffline(),this._streamConnectedPromise=null}_findCall(e){return this._calls.find(t=>t.parameters.CallSid===e||t.outboundConnectionId===e)||null}_getChunderws(){return typeof this._options.chunderw=="string"?[this._options.chunderw]:Array.isArray(this._options.chunderw)?this._options.chunderw:null}_logOptions(e,t={}){const n=["allowIncomingWhileBusy","appName","appVersion","closeProtection","codecPreferences","disableAudioContextSounds","dscp","edge","enableImprovedSignalingErrorPrecision","forceAggressiveIceNomination","logLevel","maxAverageBitrate","maxCallSignalingTimeoutMs","sounds","tokenRefreshMs"],i=["RTCPeerConnection","enumerateDevices","getUserMedia","MediaStream"];if(typeof t=="object"){const s=Object.assign({},t);Object.keys(s).forEach(a=>{!n.includes(a)&&!i.includes(a)&&delete s[a],i.includes(a)&&(s[a]=!0)}),this._log.debug(`.${e}`,JSON.stringify(s))}}_makeCall(e,t){return yi(this,arguments,void 0,function*(n,i,s=!1){var a;const c=(a=this._audio)===null||a===void 0?void 0:a._getInputDevicePromise();c&&(this._log.debug("inputDevicePromise detected, waiting..."),yield c,this._log.debug("inputDevicePromise resolved"));const o={audioHelper:this._audio,onIgnore:()=>{this._soundcache.get(ft.SoundName.Incoming).stop()},pstream:yield this._streamConnectedPromise||this._setupStream(),publisher:this._publisher,soundcache:this._soundcache};i=Object.assign({MediaStream:this._options.MediaStream,RTCPeerConnection:this._options.RTCPeerConnection,beforeAccept:h=>{!this._activeCall||this._activeCall===h||(this._activeCall.disconnect(),this._removeCall(this._activeCall))},codecPreferences:this._options.codecPreferences,customSounds:this._options.sounds,dialtonePlayer:ft._dialtonePlayer,dscp:this._options.dscp,forceAggressiveIceNomination:this._options.forceAggressiveIceNomination,getInputStream:()=>this._options.fileInputStream||this._callInputStream,getSinkIds:()=>this._callSinkIds,maxAverageBitrate:this._options.maxAverageBitrate,preflight:this._options.preflight,rtcConstraints:this._options.rtcConstraints,shouldPlayDisconnect:()=>{var h;return(h=this._audio)===null||h===void 0?void 0:h.disconnect()},twimlParams:n,voiceEventSidGenerator:this._options.voiceEventSidGenerator},i);const l=()=>{if(!this._stream){this._log.warn("UnsetPreferredUri called without a stream");return}this._activeCall===null&&this._calls.length===0&&this._stream.updatePreferredURI(null)},d=new(this._options.Call||dt)(o,i);return this._publisher.info("settings","init",{MediaStream:!!this._options.MediaStream,RTCPeerConnection:!!this._options.RTCPeerConnection,enumerateDevices:!!this._options.enumerateDevices,getUserMedia:!!this._options.getUserMedia},d),d.once("accept",()=>{var h,v,y,w,k;this._stream.updatePreferredURI(this._preferredURI),this._removeCall(d),this._activeCall=d,this._audio&&this._audio._maybeStartPollingVolume(),d.direction===dt.CallDirection.Outgoing&&(!((h=this._audio)===null||h===void 0)&&h.outgoing())&&!s&&this._soundcache.get(ft.SoundName.Outgoing).play();const I={edge:this._edge||this._region};this._options.edge&&(I.selected_edge=Array.isArray(this._options.edge)?this._options.edge:[this._options.edge]),this._publisher.info("settings","edge",I,d),!((v=this._audio)===null||v===void 0)&&v.localProcessedStream&&((y=this._audioProcessorEventObserver)===null||y===void 0||y.emit("enabled",!1)),!((w=this._audio)===null||w===void 0)&&w.remoteProcessedStream&&((k=this._audioProcessorEventObserver)===null||k===void 0||k.emit("enabled",!0))}),d.addListener("error",h=>{d.status()==="closed"&&(this._removeCall(d),l()),this._audio&&this._audio._maybeStopPollingVolume(),this._maybeStopIncomingSound()}),d.once("cancel",()=>{this._log.info(`Canceled: ${d.parameters.CallSid}`),this._removeCall(d),l(),this._audio&&this._audio._maybeStopPollingVolume(),this._maybeStopIncomingSound()}),d.once("disconnect",()=>{this._audio&&this._audio._maybeStopPollingVolume(),this._removeCall(d),l(),this._maybeStopIncomingSound()}),d.once("reject",()=>{this._log.info(`Rejected: ${d.parameters.CallSid}`),this._audio&&this._audio._maybeStopPollingVolume(),this._removeCall(d),l(),this._maybeStopIncomingSound()}),d.on("transportClose",()=>{d.status()===dt.State.Pending&&(this._audio&&this._audio._maybeStopPollingVolume(),this._removeCall(d),this._maybeStopIncomingSound())}),d})}_maybeStopIncomingSound(){this._calls.length||this._soundcache.get(ft.SoundName.Incoming).stop()}_removeCall(e){this._activeCall===e&&(this._activeCall=null,this._makeCallPromise=null);for(let t=this._calls.length-1;t>=0;t--)e===this._calls[t]&&this._calls.splice(t,1)}_sendPresence(e){return yi(this,void 0,void 0,function*(){const t=yield this._streamConnectedPromise;t&&(t.register({audio:e}),e?this._startRegistrationTimer():this._stopRegistrationTimer())})}_setState(e){if(e===this.state)return;this._state=e;const t=this._stateEventMapping[e];this._log.debug(`#${t}`),this.emit(t)}_setupAudioHelper(){this._audioProcessorEventObserver||(this._audioProcessorEventObserver=new Kme,this._audioProcessorEventObserver.on("event",({name:t,group:n,isRemote:i})=>{this._publisher.info(n,t,{is_remote:i},this._activeCall)}));const e={audioContext:ft.audioContext,audioProcessorEventObserver:this._audioProcessorEventObserver,beforeSetInputDevice:()=>this._makeCallPromise?(this._log.debug("beforeSetInputDevice pause detected"),this._makeCallPromise):(this._log.debug("beforeSetInputDevice pause not detected, setting default"),Promise.resolve()),enumerateDevices:this._options.enumerateDevices,getUserMedia:this._options.getUserMedia||zye};if(this._audio){this._log.info("Found existing audio helper; updating options..."),this._audio._updateUserOptions(e);return}this._audio=new(this._options.AudioHelper||zme)(this._updateSinkIds,this._updateInputStream,e),this._audio.on("deviceChange",t=>{const n=this._activeCall,i=t.map(s=>s.deviceId);this._publisher.info("audio","device-change",{lost_active_device_ids:i},n),n&&n._mediaHandler._onInputDevicesChanged()})}_setupLoglevel(e){const t=typeof e=="number"||typeof e=="string"?e:Gr.levels.ERROR;this._log.setDefaultLevel(t),this._log.info("Set logger default level to",t)}_setupPublisher(){this._publisher&&(this._log.info("Found existing publisher; destroying..."),this._destroyPublisher());const e={defaultPayload:this._createDefaultPayload,metadata:{app_name:this._options.appName,app_version:this._options.appVersion}};return this._options.eventgw&&(e.host=this._options.eventgw),this._home&&(e.host=VA(this._home)),this._publisher=new(this._options.Publisher||Ti)(r_e,this.token,e),this._options.publishEvents===!1?this._publisher.disable():this._publisher.on("error",t=>{this._log.warn("Cannot connect to insights.",t)}),this._publisher}_setupStream(){return this._stream&&(this._log.info("Found existing stream; destroying..."),this._destroyStream()),this._log.info("Setting up VSP"),this._stream=new(this._options.PStream||zr)(this.token,this._chunderURIs,{backoffMaxMs:this._options.backoffMaxMs,maxPreferredDurationMs:this._options.maxCallSignalingTimeoutMs}),this._stream.addListener("close",this._onSignalingClose),this._stream.addListener("connected",this._onSignalingConnected),this._stream.addListener("error",this._onSignalingError),this._stream.addListener("invite",this._onSignalingInvite),this._stream.addListener("offline",this._onSignalingOffline),this._stream.addListener("ready",this._onSignalingReady),this._streamConnectedPromise=Sw(this._stream,"connected","close").then(()=>this._stream)}_showIncomingCall(e,t){let n;return Promise.race([t(),new Promise((i,s)=>{n=setTimeout(()=>{const a="Playing incoming ringtone took too long; it might not play. Continuing execution...";s(new Error(a))},t_e)})]).catch(i=>{this._log.warn(i.message)}).then(()=>{clearTimeout(n),this._log.debug("#incoming",JSON.stringify({customParameters:e.customParameters,parameters:e.parameters})),this.emit(ft.EventName.Incoming,e)})}_startRegistrationTimer(){this._stopRegistrationTimer(),this._regTimer=setTimeout(()=>{this._sendPresence(!0)},e_e)}_stopRegistrationTimer(){this._regTimer&&clearTimeout(this._regTimer)}_throwIfDestroyed(){if(this.state===ft.State.Destroyed)throw new Bs("Device has been destroyed.")}_updateRingtoneSinkIds(e){return Promise.resolve(this._soundcache.get(ft.SoundName.Incoming).setSinkIds(e))}_updateSpeakerSinkIds(e){Array.from(this._soundcache.entries()).filter(n=>n[0]!==ft.SoundName.Incoming).forEach(n=>n[1].setSinkIds(e)),this._callSinkIds=e;const t=this._activeCall;return t?t._setSinkIds(e):Promise.resolve()}}ft._defaultSounds={disconnect:{filename:"disconnect",maxDuration:3e3},dtmf0:{filename:"dtmf-0",maxDuration:1e3},dtmf1:{filename:"dtmf-1",maxDuration:1e3},dtmf2:{filename:"dtmf-2",maxDuration:1e3},dtmf3:{filename:"dtmf-3",maxDuration:1e3},dtmf4:{filename:"dtmf-4",maxDuration:1e3},dtmf5:{filename:"dtmf-5",maxDuration:1e3},dtmf6:{filename:"dtmf-6",maxDuration:1e3},dtmf7:{filename:"dtmf-7",maxDuration:1e3},dtmf8:{filename:"dtmf-8",maxDuration:1e3},dtmf9:{filename:"dtmf-9",maxDuration:1e3},dtmfh:{filename:"dtmf-hash",maxDuration:1e3},dtmfs:{filename:"dtmf-star",maxDuration:1e3},incoming:{filename:"incoming",shouldLoop:!0},outgoing:{filename:"outgoing",maxDuration:3e3}};(function(r){(function(e){e.Error="error",e.Incoming="incoming",e.Destroyed="destroyed",e.Unregistered="unregistered",e.Registering="registering",e.Registered="registered",e.TokenWillExpire="tokenWillExpire"})(r.EventName||(r.EventName={})),function(e){e.Destroyed="destroyed",e.Unregistered="unregistered",e.Registering="registering",e.Registered="registered"}(r.State||(r.State={})),function(e){e.Incoming="incoming",e.Outgoing="outgoing",e.Disconnect="disconnect",e.Dtmf0="dtmf0",e.Dtmf1="dtmf1",e.Dtmf2="dtmf2",e.Dtmf3="dtmf3",e.Dtmf4="dtmf4",e.Dtmf5="dtmf5",e.Dtmf6="dtmf6",e.Dtmf7="dtmf7",e.Dtmf8="dtmf8",e.Dtmf9="dtmf9",e.DtmfS="dtmfs",e.DtmfH="dtmfh"}(r.SoundName||(r.SoundName={}))})(ft||(ft={}));class Rb{constructor(e,t=!1){this.deleted=!1;let n;const i=e.candidate.split("network-cost ");i[1]&&(n=parseInt(i[1],10)),this.candidateType=e.type,this.ip=e.ip||e.address,this.isRemote=t,this.networkCost=n,this.port=e.port,this.priority=e.priority,this.protocol=e.protocol,this.relatedAddress=e.relatedAddress,this.relatedPort=e.relatedPort,this.tcpType=e.tcpType,this.transportId=e.sdpMid}toPayload(){return{candidate_type:this.candidateType,deleted:this.deleted,ip:this.ip,is_remote:this.isRemote,"network-cost":this.networkCost,port:this.port,priority:this.priority,protocol:this.protocol,related_address:this.relatedAddress,related_port:this.relatedPort,tcp_type:this.tcpType,transport_id:this.transportId}}}const XA=94.768;function i_e(r,e,t){if(typeof r!="number"||typeof e!="number"||typeof t!="number"||!nv(r)||!nv(e)||!nv(t))return null;const n=r+e*2+10;let i=0;switch(!0){case n<160:i=XA-n/40;break;case n<1e3:i=XA-(n-120)/10;break}switch(!0){case t<=i/2.5:i=Math.max(i-t*2.5,6.52);break;default:i=0;break}return 1+.035*i+7e-6*i*(i-60)*(100-i)}function nv(r){return typeof r=="number"&&!isNaN(r)&&isFinite(r)&&r>=0}var s_e={calculate:i_e,isNonNegativeNumber:nv};const a_e=5,o_e=0,u_e=3,c_e=1e3,l_e=5*1e3,d_e={audioInputLevel:{minStandardDeviation:327.67,sampleCount:10},audioOutputLevel:{minStandardDeviation:327.67,sampleCount:10},bytesReceived:{clearCount:2,min:1,raiseCount:3,sampleCount:3},bytesSent:{clearCount:2,min:1,raiseCount:3,sampleCount:3},jitter:{max:30},mos:{min:3},packetsLostFraction:[{max:1},{clearValue:1,maxAverage:3,sampleCount:7}],rtt:{max:400}};function f_e(r,e){return e.reduce((t,n)=>t+=n>r?1:0,0)}function h_e(r,e){return e.reduce((t,n)=>t+=n<r?1:0,0)}function p_e(r){if(r.length<=0)return null;const e=r.reduce((i,s)=>i+s,0)/r.length,t=r.map(i=>Math.pow(i-e,2));return Math.sqrt(t.reduce((i,s)=>i+s,0)/t.length)}function v_e(r){return r.reduce((e,t)=>[...e,...t],[])}class g_e extends Ss.EventEmitter{constructor(e){super(),this._activeWarnings=new Map,this._currentStreaks=new Map,this._inputVolumes=[],this._outputVolumes=[],this._sampleBuffer=[],this._supplementalSampleBuffers={audioInputLevel:[],audioOutputLevel:[]},this._warningsEnabled=!0,e=e||{},this._getRTCStats=e.getRTCStats||cye,this._mos=e.Mos||s_e,this._peerConnection=e.peerConnection,this._thresholds=Object.assign(Object.assign({},d_e),e.thresholds);const t=Object.values(this._thresholds).map(n=>n.sampleCount).filter(n=>!!n);this._maxSampleCount=Math.max(a_e,...t),this._peerConnection&&this.enable(this._peerConnection)}addVolumes(e,t){this._inputVolumes.push(e),this._outputVolumes.push(t)}disable(){return this._sampleInterval&&(clearInterval(this._sampleInterval),delete this._sampleInterval),this}disableWarnings(){return this._warningsEnabled&&this._activeWarnings.clear(),this._warningsEnabled=!1,this}enable(e){if(e){if(this._peerConnection&&e!==this._peerConnection)throw new kr("Attempted to replace an existing PeerConnection in StatsMonitor.enable");this._peerConnection=e}if(!this._peerConnection)throw new kr("Can not enable StatsMonitor without a PeerConnection");return this._sampleInterval=this._sampleInterval||setInterval(this._fetchSample.bind(this),c_e),this}enableWarnings(){return this._warningsEnabled=!0,this}hasActiveWarning(e,t){const n=`${e}:${t}`;return!!this._activeWarnings.get(n)}_addSample(e){const t=this._sampleBuffer;t.push(e),t.length>this._maxSampleCount&&t.splice(0,t.length-this._maxSampleCount)}_clearWarning(e,t,n){const i=`${e}:${t}`,s=this._activeWarnings.get(i);!s||Date.now()-s.timeRaised<l_e||(this._activeWarnings.delete(i),this.emit("warning-cleared",Object.assign(Object.assign({},n),{name:e,threshold:{name:t,value:this._thresholds[e][t]}})))}_createSample(e,t){const n=t&&t.totals.bytesSent||0,i=t&&t.totals.bytesReceived||0,s=t&&t.totals.packetsSent||0,a=t&&t.totals.packetsReceived||0,c=t&&t.totals.packetsLost||0,o=e.bytesSent-n,l=e.bytesReceived-i,d=e.packetsSent-s,h=e.packetsReceived-a,v=e.packetsLost-c,y=h+v,w=y>0?v/y*100:0,k=e.packetsReceived+e.packetsLost,I=k>0?e.packetsLost/k*100:100,A=typeof e.rtt=="number"||!t?e.rtt:t.rtt,j=this._inputVolumes.splice(0);this._supplementalSampleBuffers.audioInputLevel.push(j);const L=this._outputVolumes.splice(0);return this._supplementalSampleBuffers.audioOutputLevel.push(L),{audioInputLevel:Math.round(Gd(j)),audioOutputLevel:Math.round(Gd(L)),bytesReceived:l,bytesSent:o,codecName:e.codecName,jitter:e.jitter,mos:this._mos.calculate(A,e.jitter,t&&w),packetsLost:v,packetsLostFraction:w,packetsReceived:h,packetsSent:d,rtt:A,timestamp:e.timestamp,totals:{bytesReceived:e.bytesReceived,bytesSent:e.bytesSent,packetsLost:e.packetsLost,packetsLostFraction:I,packetsReceived:e.packetsReceived,packetsSent:e.packetsSent}}}_fetchSample(){this._getSample().then(e=>{this._addSample(e),this._raiseWarnings(),this.emit("sample",e)}).catch(e=>{this.disable(),this.emit("error",e)})}_getSample(){return this._getRTCStats(this._peerConnection).then(e=>{let t=null;return this._sampleBuffer.length&&(t=this._sampleBuffer[this._sampleBuffer.length-1]),this._createSample(e,t)})}_raiseWarning(e,t,n){const i=`${e}:${t}`;if(this._activeWarnings.has(i))return;this._activeWarnings.set(i,{timeRaised:Date.now()});const s=this._thresholds[e];let a;if(Array.isArray(s)){const c=s.find(o=>t in o);c&&(a=c[t])}else a=this._thresholds[e][t];this.emit("warning",Object.assign(Object.assign({},n),{name:e,threshold:{name:t,value:a}}))}_raiseWarnings(){this._warningsEnabled&&Object.keys(this._thresholds).forEach(e=>this._raiseWarningsForStat(e))}_raiseWarningsForStat(e){(Array.isArray(this._thresholds[e])?this._thresholds[e]:[this._thresholds[e]]).forEach(n=>{const i=this._sampleBuffer,s=n.clearCount||o_e,a=n.raiseCount||u_e,c=n.sampleCount||this._maxSampleCount;let o=i.slice(-c);const l=o.map(v=>v[e]);if(l.some(v=>typeof v>"u"||v===null))return;let h;if(typeof n.max=="number"&&(h=f_e(n.max,l),h>=a?this._raiseWarning(e,"max",{values:l,samples:o}):h<=s&&this._clearWarning(e,"max",{values:l,samples:o})),typeof n.min=="number"&&(h=h_e(n.min,l),h>=a?this._raiseWarning(e,"min",{values:l,samples:o}):h<=s&&this._clearWarning(e,"min",{values:l,samples:o})),typeof n.maxDuration=="number"&&i.length>1){o=i.slice(-2);const v=o[0][e],y=o[1][e],w=this._currentStreaks.get(e)||0,k=v===y?w+1:0;this._currentStreaks.set(e,k),k>=n.maxDuration?this._raiseWarning(e,"maxDuration",{value:k}):k===0&&this._clearWarning(e,"maxDuration",{value:w})}if(typeof n.minStandardDeviation=="number"){const v=this._supplementalSampleBuffers[e];if(!v||v.length<n.sampleCount)return;v.length>n.sampleCount&&v.splice(0,v.length-n.sampleCount);const y=v_e(v.slice(-c)),w=p_e(y);if(typeof w!="number")return;w<n.minStandardDeviation?this._raiseWarning(e,"minStandardDeviation",{value:w}):this._clearWarning(e,"minStandardDeviation",{value:w})}[["maxAverage",(v,y)=>v>y],["minAverage",(v,y)=>v<y]].forEach(([v,y])=>{if(typeof n[v]=="number"&&l.length>=c){const w=Gd(l);y(w,n[v])?this._raiseWarning(e,v,{values:l,samples:o}):y(w,n.clearValue||n[v])||this._clearWarning(e,v,{values:l,samples:o})}})})}}const QA={factor:1.1,jitter:.5,max:3e4,min:1},m_e=70,y_e=500,__e=160,b_e=10,S_e=5e3,ZA={disconnect:!0,info:{code:31003,message:"Connection with Twilio was interrupted.",twilioError:new ga.ConnectionError}},eO={packetsLostFraction:{max:"packet-loss",maxAverage:"packets-lost-fraction"}},tO={audioInputLevel:"audio-input-level",audioOutputLevel:"audio-output-level",bytesReceived:"bytes-received",bytesSent:"bytes-sent",jitter:"jitter",mos:"mos",rtt:"rtt"},w_e={max:"high-",maxAverage:"high-",maxDuration:"constant-",min:"low-",minStandardDeviation:"constant-"};class dt extends Ss.EventEmitter{get direction(){return this._direction}get codec(){return this._codec}get connectToken(){const e=this._signalingReconnectToken,t=this.parameters&&this.parameters.CallSid?this.parameters.CallSid:void 0;if(!e||!t)return;const n=this.customParameters&&typeof this.customParameters.keys=="function"?Array.from(this.customParameters.keys()).reduce((s,a)=>(s[a]=this.customParameters.get(a),s),{}):{},i=this.parameters||{};return btoa(encodeURIComponent(JSON.stringify({customParameters:n,parameters:i,signalingReconnectToken:e})))}constructor(e,t){super(),this.parameters={},this._inputVolumeStreak=0,this._isAnswered=!1,this._isCancelled=!1,this._isRejected=!1,this._latestInputVolume=0,this._latestOutputVolume=0,this._log=new On("Call"),this._mediaStatus=dt.State.Pending,this._messages=new Map,this._metricsSamples=[],this._options={MediaHandler:Dt,MediaStream:null,enableImprovedSignalingErrorPrecision:!1,offerSdp:null,shouldPlayDisconnect:()=>!0,voiceEventSidGenerator:Ew},this._outputVolumeStreak=0,this._shouldSendHangup=!0,this._signalingStatus=dt.State.Pending,this._soundcache=new Map,this._status=dt.State.Pending,this._wasConnected=!1,this.toString=()=>"[Twilio.Call instance]",this._emitWarning=(a,c,o,l,d,h)=>{const y=`${a}warning${d?"-cleared":"-raised"}`;if(c==="constant-audio-input-level"&&this.isMuted())return;let w=d?"info":"warning";c==="constant-audio-output-level"&&(w="info");const k={threshold:o};if(l&&(l instanceof Array?k.values=l.map(I=>typeof I=="number"?Math.round(I*100)/100:l):k.value=l),this._publisher.post(w,y,c,{data:k},this),c!=="constant-audio-output-level"){const I=d?"warning-cleared":"warning";this._log.debug(`#${I}`,c),this.emit(I,c,h&&!d?h:null)}},this._onAck=a=>{const{acktype:c,callsid:o,voiceeventsid:l}=a;if(this.parameters.CallSid!==o){this._log.warn(`Received ack from a different callsid: ${o}`);return}c==="message"&&this._onMessageSent(l)},this._onAnswer=a=>{typeof a.reconnect=="string"&&(this._signalingReconnectToken=a.reconnect),!(this._isAnswered&&this._status!==dt.State.Reconnecting)&&(this._setCallSid(a),this._isAnswered=!0,this._maybeTransitionToOpen())},this._onCancel=a=>{const c=a.callsid;this.parameters.CallSid===c&&(this._isCancelled=!0,this._publisher.info("connection","cancel",null,this),this._cleanupEventListeners(),this._mediaHandler.close(),this._status=dt.State.Closed,this._log.debug("#cancel"),this.emit("cancel"),this._pstream.removeListener("cancel",this._onCancel))},this._onConnected=()=>{this._log.info("Received connected from pstream"),this._signalingReconnectToken&&this._mediaHandler.version&&this._pstream.reconnect(this._mediaHandler.version.getSDP(),this.parameters.CallSid,this._signalingReconnectToken)},this._onHangup=a=>{if(this.status()!==dt.State.Closed){if(a.callsid&&(this.parameters.CallSid||this.outboundConnectionId)){if(a.callsid!==this.parameters.CallSid&&a.callsid!==this.outboundConnectionId)return}else if(a.callsid)return;if(this._log.info("Received HANGUP from gateway"),a.error){const c=a.error.code,o=_w(this._options.enableImprovedSignalingErrorPrecision,c),l=typeof o<"u"?new o(a.error.message):new ai.ConnectionError("Error sent from gateway in HANGUP",a.error);this._log.error("Received an error from the gateway:",l),this._log.debug("#error",l),this.emit("error",l)}this._shouldSendHangup=!1,this._publisher.info("connection","disconnected-by-remote",null,this),this._disconnect(null,!0),this._cleanupEventListeners()}},this._onMediaFailure=a=>{const{ConnectionDisconnected:c,ConnectionFailed:o,IceGatheringFailed:l,LowBytes:d}=dt.MediaFailure,h=a===o||a===l;if(!RT(window,window.navigator)&&a===o)return this._mediaHandler.onerror(ZA);if(this._mediaStatus===dt.State.Reconnecting){if(h){if(Date.now()-this._mediaReconnectStartTime>QA.max)return this._log.warn("Exceeded max ICE retries"),this._mediaHandler.onerror(ZA);try{this._mediaReconnectBackoff.backoff()}catch(k){if(!(k.message&&k.message==="Backoff in progress."))throw k}}return}const v=this._mediaHandler.version.pc,y=v&&v.iceConnectionState==="disconnected",w=this._monitor.hasActiveWarning("bytesSent","min")||this._monitor.hasActiveWarning("bytesReceived","min");if(a===d&&y||a===c&&w||h){const k=new ga.ConnectionError("Media connection failed.");this._log.warn("ICE Connection disconnected."),this._publisher.warn("connection","error",k,this),this._publisher.info("connection","reconnecting",null,this),this._mediaReconnectStartTime=Date.now(),this._status=dt.State.Reconnecting,this._mediaStatus=dt.State.Reconnecting,this._mediaReconnectBackoff.reset(),this._mediaReconnectBackoff.backoff(),this._log.debug("#reconnecting"),this.emit("reconnecting",k)}},this._onMediaReconnected=()=>{this._mediaStatus===dt.State.Reconnecting&&(this._log.info("ICE Connection reestablished."),this._mediaStatus=dt.State.Open,this._signalingStatus===dt.State.Open&&(this._publisher.info("connection","reconnected",null,this),this._log.debug("#reconnected"),this.emit("reconnected"),this._status=dt.State.Open))},this._onMessageReceived=a=>{const{callsid:c,content:o,contenttype:l,messagetype:d,voiceeventsid:h}=a;if(this.parameters.CallSid!==c){this._log.warn(`Received a message from a different callsid: ${c}`);return}const v={content:o,contentType:l,messageType:d,voiceEventSid:h};this._publisher.info("call-message",d,{content_type:l,event_type:"received",voice_event_sid:h},this),this._log.debug("#messageReceived",JSON.stringify(v)),this.emit("messageReceived",v)},this._onMessageSent=a=>{if(!this._messages.has(a)){this._log.warn(`Received a messageSent with a voiceEventSid that doesn't exists: ${a}`);return}const c=this._messages.get(a);this._messages.delete(a),this._publisher.info("call-message",c==null?void 0:c.messageType,{content_type:c==null?void 0:c.contentType,event_type:"sent",voice_event_sid:a},this),this._log.debug("#messageSent",JSON.stringify(c)),this.emit("messageSent",c)},this._onRinging=a=>{if(this._setCallSid(a),this._status!==dt.State.Connecting&&this._status!==dt.State.Ringing)return;const c=!!a.sdp;this._status=dt.State.Ringing,this._publisher.info("connection","outgoing-ringing",{hasEarlyMedia:c},this),this._log.debug("#ringing"),this.emit("ringing",c)},this._onRTCSample=a=>{const c=Object.assign(Object.assign({},a),{inputVolume:this._latestInputVolume,outputVolume:this._latestOutputVolume});this._codec=c.codecName,this._metricsSamples.push(c),this._metricsSamples.length>=b_e&&this._publishMetrics(),this.emit("sample",a)},this._onSignalingError=a=>{const{callsid:c,voiceeventsid:o,error:l}=a;if(this.parameters.CallSid!==c){this._log.warn(`Received an error from a different callsid: ${c}`);return}if(o&&this._messages.has(o)){this._messages.delete(o),this._log.warn("Received an error while sending a message.",a),this._publisher.error("call-message","error",{code:l.code,message:l.message,voice_event_sid:o},this);let d;const h=_w(!!this._options.enableImprovedSignalingErrorPrecision,l.code);typeof h<"u"&&(d=new h(l)),d||(this._log.error("Unknown Call Message Error: ",l),d=new ai.UnknownError(l.message,l)),this._log.debug("#error",l,d),this.emit("error",d)}},this._onSignalingReconnected=()=>{this._signalingStatus===dt.State.Reconnecting&&(this._log.info("Signaling Connection reestablished."),this._signalingStatus=dt.State.Open,this._mediaStatus===dt.State.Open&&(this._publisher.info("connection","reconnected",null,this),this._log.debug("#reconnected"),this.emit("reconnected"),this._status=dt.State.Open))},this._onTransportClose=()=>{this._log.error("Received transportClose from pstream"),this._log.debug("#transportClose"),this.emit("transportClose"),this._signalingReconnectToken?(this._status=dt.State.Reconnecting,this._signalingStatus=dt.State.Reconnecting,this._publisher.info("connection","reconnecting",null,this),this._log.debug("#reconnecting"),this.emit("reconnecting",new _s.ConnectionDisconnected)):(this._status=dt.State.Closed,this._signalingStatus=dt.State.Closed)},this._reemitWarning=(a,c)=>{const o=/^audio/.test(a.name)?"audio-level-":"network-quality-",l=w_e[a.threshold.name];let d;a.name in eO?d=eO[a.name][a.threshold.name]:a.name in tO&&(d=tO[a.name]);const h=l+d;this._emitWarning(o,h,a.threshold.value,a.values||a.value,c,a)},this._reemitWarningCleared=a=>{this._reemitWarning(a,!0)},this._soundcache=e.soundcache,typeof e.onIgnore=="function"&&(this._onIgnore=e.onIgnore);const n=t&&t.twimlParams||{};this.customParameters=new Map(Object.entries(n).map(([a,c])=>[a,String(c)])),Object.assign(this._options,t),this._options.callParameters&&(this.parameters=this._options.callParameters),this._options.reconnectToken&&(this._signalingReconnectToken=this._options.reconnectToken),this._voiceEventSidGenerator=this._options.voiceEventSidGenerator||Ew,this._direction=this.parameters.CallSid&&!this._options.reconnectCallSid?dt.CallDirection.Incoming:dt.CallDirection.Outgoing,this.parameters?this.callerInfo=this.parameters.StirStatus?{isVerified:this.parameters.StirStatus==="TN-Validation-Passed-A"}:null:this.callerInfo=null,this._mediaReconnectBackoff=new gw(QA),this._mediaReconnectBackoff.on("ready",()=>this._mediaHandler.iceRestart()),this.outboundConnectionId=T_e();const i=this._publisher=e.publisher;this._direction===dt.CallDirection.Incoming?i.info("connection","incoming",null,this):i.info("connection","outgoing",{preflight:this._options.preflight,reconnect:!!this._options.reconnectCallSid},this);const s=this._monitor=new(this._options.StatsMonitor||g_e);s.on("sample",this._onRTCSample),s.disableWarnings(),setTimeout(()=>s.enableWarnings(),S_e),s.on("warning",(a,c)=>{(a.name==="bytesSent"||a.name==="bytesReceived")&&this._onMediaFailure(dt.MediaFailure.LowBytes),this._reemitWarning(a,c)}),s.on("warning-cleared",a=>{this._reemitWarningCleared(a)}),this._mediaHandler=new this._options.MediaHandler(e.audioHelper,e.pstream,{MediaStream:this._options.MediaStream,RTCPeerConnection:this._options.RTCPeerConnection,codecPreferences:this._options.codecPreferences,dscp:this._options.dscp,forceAggressiveIceNomination:this._options.forceAggressiveIceNomination,maxAverageBitrate:this._options.maxAverageBitrate}),this.on("volume",(a,c)=>{this._inputVolumeStreak=this._checkVolume(a,this._inputVolumeStreak,this._latestInputVolume,"input"),this._outputVolumeStreak=this._checkVolume(c,this._outputVolumeStreak,this._latestOutputVolume,"output"),this._latestInputVolume=a,this._latestOutputVolume=c}),this._mediaHandler.onaudio=a=>{this._log.debug("#audio"),this.emit("audio",a)},this._mediaHandler.onvolume=(a,c,o,l)=>{s.addVolumes(o/255*32767,l/255*32767),this.emit("volume",a,c)},this._mediaHandler.ondtlstransportstatechange=a=>{const c=a==="failed"?"error":"debug";this._publisher.post(c,"dtls-transport-state",a,null,this)},this._mediaHandler.onpcconnectionstatechange=a=>{let c="debug";const o=this._mediaHandler.getRTCDtlsTransport();a==="failed"&&(c=o&&o.state==="failed"?"error":"warning"),this._publisher.post(c,"pc-connection-state",a,null,this)},this._mediaHandler.onicecandidate=a=>{const c=new Rb(a).toPayload();this._publisher.debug("ice-candidate","ice-candidate",c,this)},this._mediaHandler.onselectedcandidatepairchange=a=>{const c=new Rb(a.local).toPayload(),o=new Rb(a.remote,!0).toPayload();this._publisher.debug("ice-candidate","selected-ice-candidate-pair",{local_candidate:c,remote_candidate:o},this)},this._mediaHandler.oniceconnectionstatechange=a=>{const c=a==="failed"?"error":"debug";this._publisher.post(c,"ice-connection-state",a,null,this)},this._mediaHandler.onicegatheringfailure=a=>{this._publisher.warn("ice-gathering-state",a,null,this),this._onMediaFailure(dt.MediaFailure.IceGatheringFailed)},this._mediaHandler.onicegatheringstatechange=a=>{this._publisher.debug("ice-gathering-state",a,null,this)},this._mediaHandler.onsignalingstatechange=a=>{this._publisher.debug("signaling-state",a,null,this)},this._mediaHandler.ondisconnected=a=>{this._log.warn(a),this._publisher.warn("network-quality-warning-raised","ice-connectivity-lost",{message:a},this),this._log.debug("#warning","ice-connectivity-lost"),this.emit("warning","ice-connectivity-lost"),this._onMediaFailure(dt.MediaFailure.ConnectionDisconnected)},this._mediaHandler.onfailed=a=>{this._onMediaFailure(dt.MediaFailure.ConnectionFailed)},this._mediaHandler.onconnected=()=>{this._status===dt.State.Reconnecting&&this._onMediaReconnected()},this._mediaHandler.onreconnected=a=>{this._log.info(a),this._publisher.info("network-quality-warning-cleared","ice-connectivity-lost",{message:a},this),this._log.debug("#warning-cleared","ice-connectivity-lost"),this.emit("warning-cleared","ice-connectivity-lost"),this._onMediaReconnected()},this._mediaHandler.onerror=a=>{a.disconnect===!0&&this._disconnect(a.info&&a.info.message);const c=a.info.twilioError||new ai.UnknownError(a.info.message);this._log.error("Received an error from MediaStream:",a),this._log.debug("#error",c),this.emit("error",c)},this._mediaHandler.onopen=()=>{this._status===dt.State.Open||this._status===dt.State.Reconnecting||(this._status===dt.State.Ringing||this._status===dt.State.Connecting?(this.mute(this._mediaHandler.isMuted),this._mediaStatus=dt.State.Open,this._maybeTransitionToOpen()):this._mediaHandler.close())},this._mediaHandler.onclose=()=>{this._status=dt.State.Closed,this._options.shouldPlayDisconnect&&this._options.shouldPlayDisconnect()&&!this._isCancelled&&!this._isRejected&&this._soundcache.get(ft.SoundName.Disconnect).play(),s.disable(),this._publishMetrics(),!this._isCancelled&&!this._isRejected&&(this._log.debug("#disconnect"),this.emit("disconnect",this))},this._pstream=e.pstream,this._pstream.on("ack",this._onAck),this._pstream.on("cancel",this._onCancel),this._pstream.on("error",this._onSignalingError),this._pstream.on("ringing",this._onRinging),this._pstream.on("transportClose",this._onTransportClose),this._pstream.on("connected",this._onConnected),this._pstream.on("message",this._onMessageReceived),this.on("error",a=>{this._publisher.error("connection","error",{code:a.code,message:a.message},this),this._pstream&&this._pstream.status==="disconnected"&&this._cleanupEventListeners()}),this.on("disconnect",()=>{this._cleanupEventListeners()})}_setInputTracksFromStream(e){return this._mediaHandler.setInputTracksFromStream(e)}_setSinkIds(e){return this._mediaHandler._setSinkIds(e)}accept(e){if(this._log.debug(".accept",e),this._status!==dt.State.Pending){this._log.debug(`.accept noop. status is '${this._status}'`);return}e=e||{};const t=e.rtcConfiguration||this._options.rtcConfiguration,n=e.rtcConstraints||this._options.rtcConstraints||{},i={audio:typeof n.audio<"u"?n.audio:!0};this._status=dt.State.Connecting;const s=()=>{if(this._status!==dt.State.Connecting){this._cleanupEventListeners(),this._mediaHandler.close();return}const o=d=>{const h=this._direction===dt.CallDirection.Incoming?"accepted-by-local":"accepted-by-remote";this._publisher.info("connection",h,null,this);const{codecName:v,codecParams:y}=$ye(this._mediaHandler.version.getSDP());this._publisher.info("settings","codec",{codec_params:y,selected_codec:v},this),this._monitor.enable(d)},l=typeof this._options.getSinkIds=="function"&&this._options.getSinkIds();if(Array.isArray(l)&&this._mediaHandler._setSinkIds(l).catch(()=>{}),this._pstream.addListener("hangup",this._onHangup),this._direction===dt.CallDirection.Incoming)this._isAnswered=!0,this._pstream.on("answer",this._onAnswer),this._mediaHandler.answerIncomingCall(this.parameters.CallSid,this._options.offerSdp,t,o);else{const d=Array.from(this.customParameters.entries()).map(h=>`${encodeURIComponent(h[0])}=${encodeURIComponent(h[1])}`).join("&");this._pstream.on("answer",this._onAnswer),this._mediaHandler.makeOutgoingCall(d,this._signalingReconnectToken,this._options.reconnectCallSid||this.outboundConnectionId,t,o)}};this._options.beforeAccept&&this._options.beforeAccept(this);const a=typeof this._options.getInputStream=="function"&&this._options.getInputStream();(a?this._mediaHandler.setInputTracksFromStream(a):this._mediaHandler.openDefaultDeviceWithConstraints(i)).then(()=>{this._publisher.info("get-user-media","succeeded",{data:{audioConstraints:i}},this),s()},o=>{let l;o.code===31208||["PermissionDeniedError","NotAllowedError"].indexOf(o.name)!==-1?(l=new wl.PermissionDeniedError,this._publisher.error("get-user-media","denied",{data:{audioConstraints:i,error:o}},this)):(l=new wl.AcquisitionFailedError,this._publisher.error("get-user-media","failed",{data:{audioConstraints:i,error:o}},this)),this._disconnect(),this._log.debug("#error",o),this.emit("error",l)})}disconnect(){this._log.debug(".disconnect"),this._disconnect()}getLocalStream(){return this._mediaHandler&&this._mediaHandler.stream}getRemoteStream(){return this._mediaHandler&&this._mediaHandler._remoteStream}ignore(){if(this._log.debug(".ignore"),this._status!==dt.State.Pending){this._log.debug(`.ignore noop. status is '${this._status}'`);return}this._status=dt.State.Closed,this._mediaHandler.ignore(this.parameters.CallSid),this._publisher.info("connection","ignored-by-local",null,this),this._onIgnore&&this._onIgnore()}isMuted(){return this._mediaHandler.isMuted}mute(e=!0){this._log.debug(".mute",e);const t=this._mediaHandler.isMuted;this._mediaHandler.mute(e);const n=this._mediaHandler.isMuted;t!==n&&(this._publisher.info("connection",n?"muted":"unmuted",null,this),this._log.debug("#mute",n),this.emit("mute",n,this))}postFeedback(e,t){if(typeof e>"u"||e===null)return this._postFeedbackDeclined();if(!Object.values(dt.FeedbackScore).includes(e))throw new kr(`Feedback score must be one of: ${Object.values(dt.FeedbackScore)}`);if(typeof t<"u"&&t!==null&&!Object.values(dt.FeedbackIssue).includes(t))throw new kr(`Feedback issue must be one of: ${Object.values(dt.FeedbackIssue)}`);return this._publisher.info("feedback","received",{issue_name:t,quality_score:e},this,!0)}reject(){if(this._log.debug(".reject"),this._status!==dt.State.Pending){this._log.debug(`.reject noop. status is '${this._status}'`);return}this._isRejected=!0,this._pstream.reject(this.parameters.CallSid),this._mediaHandler.reject(this.parameters.CallSid),this._publisher.info("connection","rejected-by-local",null,this),this._cleanupEventListeners(),this._mediaHandler.close(),this._status=dt.State.Closed,this._log.debug("#reject"),this.emit("reject")}sendDigits(e){if(this._log.debug(".sendDigits",e),e.match(/[^0-9*#w]/))throw new kr("Illegal character passed into sendDigits");const t=this._options.customSounds||{},n=[];e.split("").forEach(c=>{let o=c!=="w"?`dtmf${c}`:"";o==="dtmf*"&&(o="dtmfs"),o==="dtmf#"&&(o="dtmfh"),n.push(o)});const i=()=>{const c=n.shift();c&&(this._options.dialtonePlayer&&!t[c]?this._options.dialtonePlayer.play(c):this._soundcache.get(c).play()),n.length&&setTimeout(()=>i(),200)};i();const s=this._mediaHandler.getOrCreateDTMFSender();function a(c){if(!c.length)return;const o=c.shift();o&&o.length&&s.insertDTMF(o,__e,m_e),setTimeout(a.bind(null,c),y_e)}if(s){if(!("canInsertDTMF"in s)||s.canInsertDTMF){this._log.info("Sending digits using RTCDTMFSender"),a(e.split("w"));return}this._log.info("RTCDTMFSender cannot insert DTMF")}if(this._log.info("Sending digits over PStream"),this._pstream!==null&&this._pstream.status!=="disconnected")this._pstream.dtmf(this.parameters.CallSid,e);else{const c=new ai.ConnectionError("Could not send DTMF: Signaling channel is disconnected");this._log.debug("#error",c),this.emit("error",c)}}sendMessage(e){this._log.debug(".sendMessage",JSON.stringify(e));const{content:t,contentType:n,messageType:i}=e;if(typeof t>"u"||t===null)throw new kr("`content` is empty");if(typeof i!="string")throw new kr("`messageType` must be a string.");if(i.length===0)throw new kr("`messageType` must be a non-empty string.");if(this._pstream===null)throw new Bs("Could not send CallMessage; Signaling channel is disconnected");const s=this.parameters.CallSid;if(typeof this.parameters.CallSid>"u")throw new Bs("Could not send CallMessage; Call has no CallSid");const a=this._voiceEventSidGenerator();return this._messages.set(a,{content:t,contentType:n,messageType:i,voiceEventSid:a}),this._pstream.sendMessage(s,t,n,i,a),a}status(){return this._status}_checkVolume(e,t,n,i){const s=t>=10;let a=0;return n===e&&(a=t),a>=10?this._emitWarning("audio-level-",`constant-audio-${i}-level`,10,a,!1):s&&this._emitWarning("audio-level-",`constant-audio-${i}-level`,10,a,!0),a}_cleanupEventListeners(){const e=()=>{this._pstream&&(this._pstream.removeListener("ack",this._onAck),this._pstream.removeListener("answer",this._onAnswer),this._pstream.removeListener("cancel",this._onCancel),this._pstream.removeListener("error",this._onSignalingError),this._pstream.removeListener("hangup",this._onHangup),this._pstream.removeListener("ringing",this._onRinging),this._pstream.removeListener("transportClose",this._onTransportClose),this._pstream.removeListener("connected",this._onConnected),this._pstream.removeListener("message",this._onMessageReceived))};e(),setTimeout(e,0)}_createMetricPayload(){const e={call_sid:this.parameters.CallSid,dscp:!!this._options.dscp,sdk_version:ol};return this._options.gateway&&(e.gateway=this._options.gateway),e.direction=this._direction,e}_disconnect(e,t){if(e=typeof e=="string"?e:null,!(this._status!==dt.State.Open&&this._status!==dt.State.Connecting&&this._status!==dt.State.Reconnecting&&this._status!==dt.State.Ringing)){if(this._log.info("Disconnecting..."),this._pstream!==null&&this._pstream.status!=="disconnected"&&this._shouldSendHangup){const n=this.parameters.CallSid||this.outboundConnectionId;n&&this._pstream.hangup(n,e)}this._cleanupEventListeners(),this._mediaHandler.close(),t||this._publisher.info("connection","disconnected-by-local",null,this)}}_maybeTransitionToOpen(){this._wasConnected,this._isAnswered&&(this._onSignalingReconnected(),this._signalingStatus=dt.State.Open,this._mediaHandler&&this._mediaHandler.status==="open"&&(this._status=dt.State.Open,this._wasConnected||(this._wasConnected=!0,this._log.debug("#accept"),this.emit("accept",this))))}_postFeedbackDeclined(){return this._publisher.info("feedback","received-none",null,this,!0)}_publishMetrics(){this._metricsSamples.length!==0&&this._publisher.postMetrics("quality-metrics-samples","metrics-sample",this._metricsSamples.splice(0),this._createMetricPayload(),this).catch(e=>{this._log.warn("Unable to post metrics to Insights. Received error:",e)})}_setCallSid(e){const t=e.callsid;t&&(this.parameters.CallSid=t,this._mediaHandler.callSid=t)}}dt.toString=()=>"[Twilio.Call class]";(function(r){(function(e){e.Closed="closed",e.Connecting="connecting",e.Open="open",e.Pending="pending",e.Reconnecting="reconnecting",e.Ringing="ringing"})(r.State||(r.State={})),function(e){e.AudioLatency="audio-latency",e.ChoppyAudio="choppy-audio",e.DroppedCall="dropped-call",e.Echo="echo",e.NoisyCall="noisy-call",e.OneWayAudio="one-way-audio"}(r.FeedbackIssue||(r.FeedbackIssue={})),function(e){e[e.One=1]="One",e[e.Two=2]="Two",e[e.Three=3]="Three",e[e.Four=4]="Four",e[e.Five=5]="Five"}(r.FeedbackScore||(r.FeedbackScore={})),function(e){e.Incoming="INCOMING",e.Outgoing="OUTGOING"}(r.CallDirection||(r.CallDirection={})),function(e){e.Opus="opus",e.PCMU="pcmu"}(r.Codec||(r.Codec={})),function(e){e.None="none",e.Timeout="timeout"}(r.IceGatheringFailureReason||(r.IceGatheringFailureReason={})),function(e){e.ConnectionDisconnected="ConnectionDisconnected",e.ConnectionFailed="ConnectionFailed",e.IceGatheringFailed="IceGatheringFailed",e.LowBytes="LowBytes"}(r.MediaFailure||(r.MediaFailure={}))})(dt||(dt={}));function T_e(){return"TJSxxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{const e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)})}const Up=new an("TwilioVoiceProvider"),Pb={"high-rtt":"high-latency","high-jitter":"jitter","high-packet-loss":"packet-loss","high-packets-lost-fraction":"packet-loss","low-mos":"low-quality"},C_e=1500,zd=class zd extends Ow{constructor(){super(...arguments);be(this,"device",null);be(this,"call",null);be(this,"callListeners",[]);be(this,"deviceListeners",[]);be(this,"activeRawWarnings",new Set);be(this,"qualityEmitTimer",null);be(this,"lastQualityKey","good|");be(this,"disposed",!1)}getRemoteStream(){var t,n;return((n=(t=this.call)==null?void 0:t.getRemoteStream)==null?void 0:n.call(t))??null}async create(){var n,i;let t;try{t=await this.issueVoiceToken()}catch(s){if(this.disposed)return;throw s}if(!this.disposed){if(this.device=new ft(t.token,{logLevel:"warn"}),this.attachDeviceListeners(this.device),this.call=await this.device.connect({params:{call_id:String(this.state.id),from:"end_user"}}),this.disposed){try{(n=this.call)==null||n.disconnect()}catch{}try{(i=this.device)==null||i.destroy()}catch{}this.call=null,this.device=null;return}this.attachCallListeners(this.call)}}async destroy(){var t,n;if(this.disposed=!0,this.call)for(const[i,s]of this.callListeners)try{this.call.off(i,s)}catch{}if(this.callListeners.length=0,this.qualityEmitTimer&&(clearTimeout(this.qualityEmitTimer),this.qualityEmitTimer=null),this.activeRawWarnings.clear(),this.lastQualityKey="good|",this.device)for(const[i,s]of this.deviceListeners)try{this.device.off(i,s)}catch{}this.deviceListeners.length=0;try{(t=this.call)==null||t.disconnect()}catch{}try{(n=this.device)==null||n.destroy()}catch{}this.call=null,this.device=null}mute(t){var n;(n=this.call)==null||n.mute(t)}isMuted(){var t;return((t=this.call)==null?void 0:t.isMuted())??!1}isOutputSelectionSupported(){var t,n;return!!((n=(t=this.device)==null?void 0:t.audio)!=null&&n.isOutputSelectionSupported)}getAvailableOutputDevices(){var n;const t=(n=this.device)==null?void 0:n.audio;return t?Array.from(t.availableOutputDevices.values()):[]}async setOutputDevice(t){var i;const n=(i=this.device)==null?void 0:i.audio;if(!n)throw new la("output selection unavailable: Twilio Device not initialized");await n.speakerDevices.set(t)}async hangup(){if(!this.call){this.events.triggerEvent(ps.DISCONNECTED,{reason:"ended"});return}try{this.call.disconnect()}catch{this.events.triggerEvent(ps.DISCONNECTED,{reason:"ended"})}}sendMessage(t){if(!this.call||typeof this.call.sendMessage!="function")return null;try{return this.call.sendMessage({content:{type:t.type,data:t.data??{}},contentType:"application/json",messageType:"user-defined-message"})}catch(n){return Up.warn("sendMessage failed; caller will fall back to REST",n),null}}logInnerTwilioError(t,n,i){var c;const s=(c=n==null?void 0:n.originalError)==null?void 0:c.twilioError;if(!s)return;const a=i!=null?`[${i}]`:"[?]";Up.warn(`${t} error ${a} inner=${s.name}/${s.code}`,{inner:{name:s.name,code:s.code}})}isTransientTwilioError(t,n){var i,s;if(n===31005)return!0;if(n===31e3){const a=(s=(i=t==null?void 0:t.originalError)==null?void 0:i.twilioError)==null?void 0:s.code;return a!=null&&zd.TRANSIENT_SIGNALING_INNER.has(a)}return!1}attachDeviceListeners(t){const n=async()=>{try{const a=await this.issueVoiceToken();t.updateToken(a.token)}catch(a){this.events.triggerEvent(ps.ERROR,{error:new la("token refresh failed",a)})}};t.on("tokenWillExpire",n),this.deviceListeners.push(["tokenWillExpire",n]);const i=a=>{const c=a==null?void 0:a.code;if(this.logInnerTwilioError("device",a,c),this.isTransientTwilioError(a,c)){Up.warn(`transient device error [${c}], awaiting Twilio reconnect`,a);return}const o=(a==null?void 0:a.message)??"device error",l=c!=null?`[twilio:${c}] ${o}`:o;this.events.triggerEvent(ps.ERROR,{error:new la(l,a)})};t.on("error",i),this.deviceListeners.push(["error",i]);const s=()=>{this.events.triggerEvent(ps.ERROR,{error:new la("device session lost (unregistered)")})};t.on("unregistered",s),this.deviceListeners.push(["unregistered",s])}attachCallListeners(t){const n=()=>{this.events.triggerEvent(ps.CONNECTED,{agent:this.state.agent??this.state.virtual_agent??null})};t.on("accept",n),this.callListeners.push(["accept",n]);const i=()=>{this.events.triggerEvent(ps.DISCONNECTED,{reason:"ended"})};t.on("disconnect",i),this.callListeners.push(["disconnect",i]);const s=()=>{this.events.triggerEvent(ps.DISCONNECTED,{reason:"canceled"})};t.on("cancel",s),this.callListeners.push(["cancel",s]);const a=()=>{this.events.triggerEvent(Kn.RECONNECTING)};t.on("reconnecting",a),this.callListeners.push(["reconnecting",a]);const c=()=>{this.events.triggerEvent(Kn.RECONNECTED)};t.on("reconnected",c),this.callListeners.push(["reconnected",c]);const o=v=>{Pb[v]&&(this.activeRawWarnings.add(v),this.scheduleQualityEmit())};t.on("warning",o),this.callListeners.push(["warning",o]);const l=v=>{Pb[v]&&(this.activeRawWarnings.delete(v),this.scheduleQualityEmit())};t.on("warning-cleared",l),this.callListeners.push(["warning-cleared",l]);const d=v=>{const y=this.parseIncomingMessage(v);y&&this.events.triggerEvent(yO,y)};t.on("messageReceived",d),this.callListeners.push(["messageReceived",d]);const h=v=>{const y=v==null?void 0:v.code;if(this.logInnerTwilioError("call",v,y),this.isTransientTwilioError(v,y)){Up.warn(`transient call error [${y}], awaiting Twilio reconnect`,v);return}const w=(v==null?void 0:v.message)??"call error",k=y!=null?`[twilio:${y}] ${w}`:w;this.events.triggerEvent(ps.ERROR,{error:new la(k,v)})};t.on("error",h),this.callListeners.push(["error",h])}scheduleQualityEmit(){this.qualityEmitTimer&&clearTimeout(this.qualityEmitTimer),this.qualityEmitTimer=setTimeout(()=>{this.qualityEmitTimer=null;const t=[...new Set([...this.activeRawWarnings].map(s=>Pb[s]))].filter(s=>s!==void 0).sort(),n=t.length>0?"degraded":"good",i=`${n}|${t.join(",")}`;i!==this.lastQualityKey&&(this.lastQualityKey=i,this.events.triggerEvent(Kn.CONNECTION_QUALITY,{level:n,warnings:t}))},C_e)}parseIncomingMessage(t){if(!t)return null;let n=t.content;if(typeof n=="string")try{n=JSON.parse(n)}catch{return null}return!n||typeof n.type!="string"?null:{type:n.type,data:n.data??{}}}};be(zd,"type",gO),be(zd,"TRANSIENT_SIGNALING_INNER",new Set([53e3,53001]));let kw=zd;bO(kw);exports.AnotherTabVoiceCallError=fl;exports.BaseVoiceProvider=Ow;exports.COBROWSE_EVENTS=Bp;exports.CallInProgressError=Vu;exports.ChannelType=iv;exports.ChatEndedError=av;exports.CheckInStatus=nO;exports.Client=rV;exports.ENVIRONMENT=l6;exports.EventManager=zv;exports.FeatureNotEnabledError=ll;exports.InboundDisabledError=cl;exports.Logger=an;exports.MediaStore=cO;exports.MessageType=ln;exports.MicPermissionDeniedError=dl;exports.NoActiveVoiceCallError=Uo;exports.NotiEvent=Gn;exports.OPTIONS=zn;exports.OperationHoursError=Hu;exports.PostSessionStatus=ul;exports.ProviderError=la;exports.ProviderType=Wu;exports.RISK_FLAG_EVENTS=lO;exports.SmartActionError=ni;exports.UnauthorizedError=Xc;exports.UnknownVoiceError=uv;exports.UserType=_i;exports.VERSION=Pw;exports.VOICE_EVENTS=Kn;exports.VoiceCallError=ws;exports.addProviderType=Gv;exports.addVoiceProviderType=bO;exports.getErrorMessage=Aw;exports.getErrorStatus=mO;exports.getVoiceProviderType=SO;exports.hasErrorCode=EW;exports.isAfterHoursError=kW;exports.isMobilePlatform=pO;exports.toIdentity=Fp;
|
|
568
|
+
Related Bugzilla thread: https://bugzilla.mozilla.org/show_bug.cgi?id=1299324`):t})}function Kye(){if(typeof window!="object")throw new Fn("This platform is not supported.");const{crypto:r}=window;if(typeof r!="object")throw new Fn("The `crypto` module is not available on this platform.");if(typeof r.getRandomValues!="function")throw new Fn("The function `crypto.getRandomValues` is not available on this platform.");if(typeof window.Uint8Array!="function")throw new Fn("The `Uint8Array` module is not available on this platform.");return r.getRandomValues(new window.Uint8Array(16)).reduce((e,t)=>`${e}${t.toString(16).padStart(2,"0")}`,"")}function Ew(){return`KX${Kye()}`}let Jye=class{constructor(){this._promise=new Promise((e,t)=>{this._resolve=e,this._reject=t})}get promise(){return this._promise}reject(e){this._reject(e)}resolve(e){this._resolve(e)}};class Yye{constructor(){this._operations=[]}enqueue(e){const t=!!this._operations.length,n=new Jye;return this._operations.push({deferred:n,callback:e}),t||this._processQueue(),n.promise}_processQueue(){return yi(this,void 0,void 0,function*(){for(;this._operations.length;){const{deferred:e,callback:t}=this._operations[0];let n,i,s;try{n=yield t(),s=!0}catch(a){i=a}this._operations.shift(),s?e.resolve(n):e.reject(i)}})}}class Xye{get reject(){return this._reject}get resolve(){return this._resolve}constructor(){this.promise=new Promise((e,t)=>{this._resolve=e,this._reject=t})}}let Qye=class{constructor(){this._eventEmitter=new Ss.EventEmitter}addEventListener(e,t){return this._eventEmitter.addListener(e,t)}dispatchEvent(e,...t){return this._eventEmitter.emit(e,...t)}removeEventListener(e,t){return this._eventEmitter.removeListener(e,t)}};class YA extends Qye{get destination(){return this._destination}get loop(){return this._loop}set loop(e){const t=this;function n(){t._audioNode.removeEventListener("ended",n),t.pause()}!e&&this.loop&&!this.paused&&this._audioNode.addEventListener("ended",n),this._loop=e}get muted(){return this._gainNode.gain.value===0}set muted(e){this._gainNode.gain.value=e?0:1}get paused(){return this._audioNode===null}get src(){return this._src}set src(e){this._load(e)}get srcObject(){return this._audioElement.srcObject}set srcObject(e){this._audioElement.srcObject=e}get sinkId(){return this._sinkId}constructor(e,t={},n={}){super(),this._audioNode=null,this._loop=!1,this._pendingPlayDeferreds=[],this._sinkId="default",this._src="",typeof t!="string"&&(n=t),this._audioContext=e,this._audioElement=new(n.AudioFactory||Audio),this._bufferPromise=this._createPlayDeferred().promise,this._destination=this._audioContext.destination,this._gainNode=this._audioContext.createGain(),this._gainNode.connect(this._destination),this._XMLHttpRequest=n.XMLHttpRequestFactory||XMLHttpRequest,this.addEventListener("canplaythrough",()=>{this._resolvePlayDeferreds()}),typeof t=="string"&&(this.src=t)}load(){this._load(this._src)}pause(){this.paused||(this._audioElement.pause(),this._audioNode.stop(),this._audioNode.disconnect(this._gainNode),this._audioNode=null,this._rejectPlayDeferreds(new Error("The play() request was interrupted by a call to pause().")))}play(){return yi(this,void 0,void 0,function*(){if(!this.paused){if(yield this._bufferPromise,!this.paused)return;throw new Error("The play() request was interrupted by a call to pause().")}this._audioNode=this._audioContext.createBufferSource(),this._audioNode.loop=this.loop,this._audioNode.addEventListener("ended",()=>{this._audioNode&&this._audioNode.loop||this.dispatchEvent("ended")});const e=yield this._bufferPromise;if(this.paused)throw new Error("The play() request was interrupted by a call to pause().");if(this._audioNode.buffer=e,this._audioNode.connect(this._gainNode),this._audioNode.start(),this._audioElement.srcObject)return this._audioElement.play()})}setSinkId(e){return yi(this,void 0,void 0,function*(){if(typeof this._audioElement.setSinkId!="function")throw new Error("This browser does not support setSinkId.");if(e!==this.sinkId){if(e==="default"){this.paused||this._gainNode.disconnect(this._destination),this._audioElement.srcObject=null,this._destination=this._audioContext.destination,this._gainNode.connect(this._destination),this._sinkId=e;return}yield this._audioElement.setSinkId(e),!this._audioElement.srcObject&&(this._gainNode.disconnect(this._audioContext.destination),this._destination=this._audioContext.createMediaStreamDestination(),this._audioElement.srcObject=this._destination.stream,this._sinkId=e,this._gainNode.connect(this._destination))}})}_createPlayDeferred(){const e=new Xye;return this._pendingPlayDeferreds.push(e),e}_load(e){this._src&&this._src!==e&&this.pause(),this._src=e,this._bufferPromise=new Promise((t,n)=>yi(this,void 0,void 0,function*(){if(!e)return this._createPlayDeferred().promise;const i=yield Zye(this._audioContext,this._XMLHttpRequest,e);this.dispatchEvent("canplaythrough"),t(i)}))}_rejectPlayDeferreds(e){const t=this._pendingPlayDeferreds;t.splice(0,t.length).forEach(({reject:n})=>n(e))}_resolvePlayDeferreds(e){const t=this._pendingPlayDeferreds;t.splice(0,t.length).forEach(({resolve:n})=>n(e))}}function Zye(r,e,t){return yi(this,void 0,void 0,function*(){const n=new e;n.open("GET",t,!0),n.responseType="arraybuffer";const i=yield new Promise(s=>{n.addEventListener("load",s),n.send()});try{return r.decodeAudioData(i.target.response)}catch{return new Promise(a=>{r.decodeAudioData(i.target.response,a)})}})}function ao(r,e,t){if(!(this instanceof ao))return new ao(r,e,t);if(!r||!e)throw new kr("name and url are required arguments");t=Object.assign({AudioFactory:typeof Audio<"u"?Audio:null,maxDuration:0,shouldLoop:!1},t),t.AudioPlayer=t.audioContext?YA.bind(YA,t.audioContext):t.AudioFactory,Object.defineProperties(this,{_Audio:{value:t.AudioPlayer},_activeEls:{value:new Map},_isSinkSupported:{value:t.AudioFactory!==null&&typeof t.AudioFactory.prototype.setSinkId=="function"},_maxDuration:{value:t.maxDuration},_maxDurationTimeout:{value:null,writable:!0},_operations:{value:new Yye},_playPromise:{value:null,writable:!0},_shouldLoop:{value:t.shouldLoop},_sinkIds:{value:["default"]},isPlaying:{enumerable:!0,get(){return!!this._playPromise}},name:{enumerable:!0,value:r},url:{enumerable:!0,value:e}}),this._Audio&&this._play(!0,!1)}function nU(r){r&&(r.pause(),r.src="",r.srcObject=null,r.load())}ao.prototype._playAudioElement=function(e,t,n){const i=this._activeEls.get(e);if(!i)throw new kr(`sinkId: "${e}" doesn't have an audio element`);return i.muted=!!t,i.loop=!!n,i.play().then(()=>i).catch(s=>{throw nU(i),this._activeEls.delete(e),s})};ao.prototype._play=function(e,t){this.isPlaying&&this._stop(),this._maxDuration>0&&(this._maxDurationTimeout=setTimeout(this._stop.bind(this),this._maxDuration)),t=typeof t=="boolean"?t:this._shouldLoop;const n=this;return this._playPromise=Promise.all(this._sinkIds.map(function(a){if(!n._Audio)return Promise.resolve();let c=n._activeEls.get(a);return c?n._playAudioElement(a,e,t):(c=new n._Audio(n.url),typeof c.setAttribute=="function"&&c.setAttribute("crossorigin","anonymous"),new Promise(o=>{c.addEventListener("canplaythrough",o)}).then(()=>(n._isSinkSupported?c.setSinkId(a):Promise.resolve()).then(function(){return n._activeEls.set(a,c),n._playPromise?n._playAudioElement(a,e,t):Promise.resolve()})))}))};ao.prototype._stop=function(){this._activeEls.forEach((e,t)=>{this._sinkIds.includes(t)?(e.pause(),e.currentTime=0):(nU(e),this._activeEls.delete(t))}),clearTimeout(this._maxDurationTimeout),this._playPromise=null,this._maxDurationTimeout=null};ao.prototype.setSinkIds=function(e){this._isSinkSupported&&(e=e.forEach?e:[e],[].splice.apply(this._sinkIds,[0,this._sinkIds.length].concat(e)))};ao.prototype.stop=function(){this._operations.enqueue(()=>(this._stop(),Promise.resolve()))};ao.prototype.play=function(){return this._operations.enqueue(()=>this._play())};const e_e=3e4,t_e=2e3,r_e="twilio-js-sdk",n_e='Parameter "token" must be of type "string".';class ft extends Ss.EventEmitter{static get audioContext(){return ft._audioContext}static get extension(){const e=typeof document<"u"?document.createElement("audio"):{canPlayType:!1};let t;try{t=e.canPlayType&&!!e.canPlayType("audio/mpeg").replace(/no/,"")}catch{t=!1}let n;try{n=e.canPlayType&&!!e.canPlayType("audio/ogg;codecs='vorbis'").replace(/no/,"")}catch{n=!1}return n&&!t?"ogg":"mp3"}static get isSupported(){return Hye()}static get packageName(){return H2}static runPreflight(e,t){return new Qr(e,Object.assign({audioContext:ft._getOrCreateAudioContext()},t))}static toString(){return"[Twilio.Device class]"}static get version(){return ol}static _getOrCreateAudioContext(){return ft._audioContext||(typeof AudioContext<"u"?ft._audioContext=new AudioContext:typeof webkitAudioContext<"u"&&(ft._audioContext=new webkitAudioContext)),ft._audioContext}constructor(e,t={}){if(super(),this._activeCall=null,this._audio=null,this._audioProcessorEventObserver=null,this._callInputStream=null,this._calls=[],this._callSinkIds=["default"],this._chunderURIs=[],this._defaultOptions={allowIncomingWhileBusy:!1,closeProtection:!1,codecPreferences:[dt.Codec.PCMU,dt.Codec.Opus],dscp:!0,enableImprovedSignalingErrorPrecision:!1,forceAggressiveIceNomination:!1,logLevel:Gr.levels.ERROR,maxCallSignalingTimeoutMs:0,preflight:!1,sounds:{},tokenRefreshMs:1e4,voiceEventSidGenerator:Ew},this._edge=null,this._home=null,this._identity=null,this._log=new On("Device"),this._makeCallPromise=null,this._options={},this._preferredURI=null,this._publisher=null,this._region=null,this._regTimer=null,this._shouldReRegister=!1,this._soundcache=new Map,this._state=ft.State.Unregistered,this._stateEventMapping={[ft.State.Destroyed]:ft.EventName.Destroyed,[ft.State.Unregistered]:ft.EventName.Unregistered,[ft.State.Registering]:ft.EventName.Registering,[ft.State.Registered]:ft.EventName.Registered},this._stream=null,this._streamConnectedPromise=null,this._tokenWillExpireTimeout=null,this._createDefaultPayload=s=>{const a={aggressive_nomination:this._options.forceAggressiveIceNomination,browser_extension:this._isBrowserExtension,dscp:!!this._options.dscp,ice_restart_enabled:!0,platform:Gye(),sdk_version:ol};function c(o,l){l&&(a[o]=l)}if(s){const o=s.parameters.CallSid;c("call_sid",/^TJ/.test(o)?void 0:o),c("temp_call_sid",s.outboundConnectionId),c("audio_codec",s.codec),a.direction=s.direction}return c("gateway",this._stream&&this._stream.gateway),c("region",this._stream&&this._stream.region),a},this._onSignalingClose=()=>{this._stream=null,this._streamConnectedPromise=null},this._onSignalingConnected=s=>{var a;const c=Pye(s.region);if(this._edge=s.edge||Eye[c]||s.region,this._region=c||s.region,this._home=s.home,(a=this._publisher)===null||a===void 0||a.setHost(VA(s.home)),s.token&&(this._identity=s.token.identity,typeof s.token.ttl=="number"&&typeof this._options.tokenRefreshMs=="number")){const l=s.token.ttl*1e3,d=Math.max(0,l-this._options.tokenRefreshMs);this._tokenWillExpireTimeout=setTimeout(()=>{this._log.debug("#tokenWillExpire"),this.emit("tokenWillExpire",this),this._tokenWillExpireTimeout&&(clearTimeout(this._tokenWillExpireTimeout),this._tokenWillExpireTimeout=null)},d)}const o=this._getChunderws()||GA(this._edge);if(o.length>0){const[l]=o;this._preferredURI=HA(l)}else this._log.warn("Could not parse a preferred URI from the stream#connected event.");this._shouldReRegister&&this.register()},this._onSignalingError=s=>{if(typeof s!="object"){this._log.warn("Invalid signaling error payload",s);return}const{error:a,callsid:c,voiceeventsid:o}=s;if(typeof a!="object"||o){this._log.warn("Ignoring signaling error payload",{originalError:a,voiceeventsid:o});return}const l=typeof c=="string"&&this._findCall(c)||void 0,{code:d,message:h}=a;let{twilioError:v}=a;if(typeof d=="number")if(d===31201)v=new In.AuthenticationFailed(a);else if(d===31204)v=new In.AccessTokenInvalid(a);else if(d===31205)this._stopRegistrationTimer(),v=new In.AccessTokenExpired(a);else{const y=_w(!!this._options.enableImprovedSignalingErrorPrecision,d);typeof y<"u"&&(v=new y(a))}v||(this._log.error("Unknown signaling error: ",a),v=new ai.UnknownError(h,a)),this._log.error("Received error: ",v),this._log.debug("#error",a),this.emit(ft.EventName.Error,v,l)},this._onSignalingInvite=s=>yi(this,void 0,void 0,function*(){var a;const c=!!this._activeCall;if(c&&!this._options.allowIncomingWhileBusy){this._log.info("Device busy; ignoring incoming invite");return}if(!s.callsid||!s.sdp){this._log.debug("#error",s),this.emit(ft.EventName.Error,new Nu.BadRequest("Malformed invite from gateway"));return}const o=s.parameters||{};o.CallSid=o.CallSid||s.callsid;const l=Object.assign({},z2(o.Params));this._makeCallPromise=this._makeCall(l,{callParameters:o,enableImprovedSignalingErrorPrecision:!!this._options.enableImprovedSignalingErrorPrecision,offerSdp:s.sdp,reconnectToken:s.reconnect,voiceEventSidGenerator:this._options.voiceEventSidGenerator});let d;try{d=yield this._makeCallPromise}finally{this._makeCallPromise=null}this._calls.push(d),d.once("accept",()=>{this._soundcache.get(ft.SoundName.Incoming).stop(),this._publishNetworkChange()});const h=!((a=this._audio)===null||a===void 0)&&a.incoming()&&!c?()=>this._soundcache.get(ft.SoundName.Incoming).play():()=>Promise.resolve();this._showIncomingCall(d,h)}),this._onSignalingOffline=()=>{this._log.info("Stream is offline"),this._edge=null,this._region=null,this._shouldReRegister=this.state!==ft.State.Unregistered,this._setState(ft.State.Unregistered)},this._onSignalingReady=()=>{this._log.info("Stream is ready"),this._setState(ft.State.Registered)},this._publishNetworkChange=()=>{this._activeCall&&this._networkInformation&&this._publisher.info("network-information","network-change",{connection_type:this._networkInformation.type,downlink:this._networkInformation.downlink,downlinkMax:this._networkInformation.downlinkMax,effective_type:this._networkInformation.effectiveType,rtt:this._networkInformation.rtt},this._activeCall)},this._updateInputStream=s=>{const a=this._activeCall;return a&&!s?Promise.reject(new Bs("Cannot unset input device while a call is in progress.")):(this._callInputStream=s,a?a._setInputTracksFromStream(s):Promise.resolve())},this._updateSinkIds=(s,a)=>(s==="ringtone"?this._updateRingtoneSinkIds(a):this._updateSpeakerSinkIds(a)).then(()=>{this._publisher.info("audio",`${s}-devices-set`,{audio_device_ids:a},this._activeCall)},o=>{throw this._publisher.error("audio",`${s}-devices-set-failed`,{audio_device_ids:a,message:o.message},this._activeCall),o}),this._setupLoglevel(t.logLevel),this._logOptions("constructor",t),this.updateToken(e),cm())throw new Fn("Microsoft Edge Legacy (https://support.microsoft.com/en-us/help/4533505/what-is-microsoft-edge-legacy) is deprecated and will not be able to connect to Twilio to make or receive calls after September 1st, 2020. Please see this documentation for a list of supported browsers https://www.twilio.com/docs/voice/client/javascript#supported-browsers");if(!ft.isSupported&&t.ignoreBrowserSupport)throw window&&window.location&&window.location.protocol==="http:"?new Fn("twilio.js wasn't able to find WebRTC browser support. This is most likely because this page is served over http rather than https, which does not support WebRTC in many browsers. Please load this page over https and try again."):new Fn("twilio.js 1.3+ SDKs require WebRTC browser support. For more information, see <https://www.twilio.com/docs/api/client/twilio-js>. If you have any questions about this announcement, please contact Twilio Support at <help@twilio.com>.");const n=globalThis,i=n.msBrowser||n.browser||n.chrome;if(this._isBrowserExtension=!!i&&!!i.runtime&&!!i.runtime.id||!!n.safari&&!!n.safari.extension,this._isBrowserExtension&&this._log.info("Running as browser extension."),navigator){const s=navigator;this._networkInformation=s.connection||s.mozConnection||s.webkitConnection}this._networkInformation&&typeof this._networkInformation.addEventListener=="function"&&this._networkInformation.addEventListener("change",this._publishNetworkChange),ft._getOrCreateAudioContext(),ft._audioContext&&(ft._dialtonePlayer||(ft._dialtonePlayer=new Yme(ft._audioContext))),this._boundDestroy=this.destroy.bind(this),this._boundConfirmClose=this._confirmClose.bind(this),typeof window<"u"&&window.addEventListener&&window.addEventListener("pagehide",this._boundDestroy),this.updateOptions(t)}get audio(){return this._audio}connect(){return yi(this,arguments,void 0,function*(e={}){if(this._log.debug(".connect",JSON.stringify(e)),this._throwIfDestroyed(),this._activeCall||this._makeCallPromise)throw new Bs("A Call is already active");let t,n,i;if(e.connectToken){try{const l=JSON.parse(decodeURIComponent(atob(e.connectToken)));t=l.customParameters,n=l.parameters,i=l.signalingReconnectToken}catch{throw new kr("Cannot parse connectToken")}if(!n||!n.CallSid||!i)throw new kr("Invalid connectToken")}let s=!1,a={};const c={enableImprovedSignalingErrorPrecision:!!this._options.enableImprovedSignalingErrorPrecision,rtcConfiguration:e.rtcConfiguration,voiceEventSidGenerator:this._options.voiceEventSidGenerator};i&&n?(s=!0,c.callParameters=n,c.reconnectCallSid=n.CallSid,c.reconnectToken=i,a=t||a):a=e.params||a;let o;this._makeCallPromise=this._makeCall(a,c,s);try{o=this._activeCall=yield this._makeCallPromise}finally{this._makeCallPromise=null}return this._calls.splice(0).forEach(l=>l.ignore()),this._soundcache.get(ft.SoundName.Incoming).stop(),o.accept({rtcConstraints:e.rtcConstraints}),this._publishNetworkChange(),o})}get calls(){return this._calls}destroy(){var e;this._log.debug(".destroy"),this._log.debug("Rejecting any incoming calls"),this._calls.slice(0).forEach(n=>n.reject()),this.disconnectAll(),this._stopRegistrationTimer(),this._destroyStream(),this._destroyAudioHelper(),(e=this._audioProcessorEventObserver)===null||e===void 0||e.destroy(),this._destroyPublisher(),this._networkInformation&&typeof this._networkInformation.removeEventListener=="function"&&this._networkInformation.removeEventListener("change",this._publishNetworkChange),typeof window<"u"&&window.removeEventListener&&(window.removeEventListener("beforeunload",this._boundConfirmClose),window.removeEventListener("pagehide",this._boundDestroy)),this._setState(ft.State.Destroyed),Ss.EventEmitter.prototype.removeAllListeners.call(this)}disconnectAll(){this._log.debug(".disconnectAll"),this._calls.splice(0).forEach(t=>t.disconnect()),this._activeCall&&this._activeCall.disconnect()}get edge(){return this._edge}get home(){return this._home}get identity(){return this._identity}get isBusy(){return!!this._activeCall}register(){return yi(this,void 0,void 0,function*(){if(this._log.debug(".register"),this.state!==ft.State.Unregistered)throw new Bs(`Attempt to register when device is in state "${this.state}". Must be "${ft.State.Unregistered}".`);this._shouldReRegister=!1,this._setState(ft.State.Registering),yield this._streamConnectedPromise||this._setupStream(),yield this._sendPresence(!0),yield Sw(this,ft.State.Registered,ft.State.Unregistered)})}get state(){return this._state}get token(){return this._token}toString(){return"[Twilio.Device instance]"}unregister(){return yi(this,void 0,void 0,function*(){if(this._log.debug(".unregister"),this.state!==ft.State.Registered)throw new Bs(`Attempt to unregister when device is in state "${this.state}". Must be "${ft.State.Registered}".`);this._shouldReRegister=!1;const e=yield this._streamConnectedPromise,t=new Promise(n=>{e.on("offline",n)});yield this._sendPresence(!1),yield t})}updateOptions(e={}){if(this._logOptions("updateOptions",e),this.state===ft.State.Destroyed)throw new Bs(`Attempt to "updateOptions" when device is in state "${this.state}".`);this._options=Object.assign(Object.assign(Object.assign({},this._defaultOptions),this._options),e);const t=new Set(this._chunderURIs),n=this._chunderURIs=(this._getChunderws()||GA(this._options.edge)).map(HA);let i=t.size!==n.length;if(!i){for(const s of n)if(!t.has(s)){i=!0;break}}if(this.isBusy&&i)throw new Bs("Cannot change Edge while on an active Call");this._setupLoglevel(this._options.logLevel);for(const s of Object.keys(ft._defaultSounds)){const a=ft._defaultSounds[s],c=`${ET}/${a.filename}.${ft.extension}?cache=${ol}`,o=this._options.sounds&&this._options.sounds[s]||c,l=new(this._options.Sound||ao)(s,o,{audioContext:this._options.disableAudioContextSounds?null:ft.audioContext,maxDuration:a.maxDuration,shouldLoop:a.shouldLoop});this._soundcache.set(s,l)}this._setupAudioHelper(),this._setupPublisher(),i&&this._streamConnectedPromise&&this._setupStream(),typeof window<"u"&&typeof window.addEventListener=="function"&&this._options.closeProtection&&(window.removeEventListener("beforeunload",this._boundConfirmClose),window.addEventListener("beforeunload",this._boundConfirmClose))}updateToken(e){if(this._log.debug(".updateToken"),this.state===ft.State.Destroyed)throw new Bs(`Attempt to "updateToken" when device is in state "${this.state}".`);if(typeof e!="string")throw new kr(n_e);this._token=e,this._stream&&this._stream.setToken(this._token),this._publisher&&this._publisher.setToken(this._token)}_confirmClose(e){if(!this._activeCall)return"";const t=this._options.closeProtection||!1,n=typeof t!="string"?"A call is currently in-progress. Leaving or reloading this page will end the call.":t;return(e||window.event).returnValue=n,n}_destroyAudioHelper(){this._audio&&(this._audio._destroy(),this._audio=null)}_destroyPublisher(){this._publisher&&(this._publisher=null)}_destroyStream(){this._stream&&(this._stream.removeListener("close",this._onSignalingClose),this._stream.removeListener("connected",this._onSignalingConnected),this._stream.removeListener("error",this._onSignalingError),this._stream.removeListener("invite",this._onSignalingInvite),this._stream.removeListener("offline",this._onSignalingOffline),this._stream.removeListener("ready",this._onSignalingReady),this._stream.destroy(),this._stream=null),this._onSignalingOffline(),this._streamConnectedPromise=null}_findCall(e){return this._calls.find(t=>t.parameters.CallSid===e||t.outboundConnectionId===e)||null}_getChunderws(){return typeof this._options.chunderw=="string"?[this._options.chunderw]:Array.isArray(this._options.chunderw)?this._options.chunderw:null}_logOptions(e,t={}){const n=["allowIncomingWhileBusy","appName","appVersion","closeProtection","codecPreferences","disableAudioContextSounds","dscp","edge","enableImprovedSignalingErrorPrecision","forceAggressiveIceNomination","logLevel","maxAverageBitrate","maxCallSignalingTimeoutMs","sounds","tokenRefreshMs"],i=["RTCPeerConnection","enumerateDevices","getUserMedia","MediaStream"];if(typeof t=="object"){const s=Object.assign({},t);Object.keys(s).forEach(a=>{!n.includes(a)&&!i.includes(a)&&delete s[a],i.includes(a)&&(s[a]=!0)}),this._log.debug(`.${e}`,JSON.stringify(s))}}_makeCall(e,t){return yi(this,arguments,void 0,function*(n,i,s=!1){var a;const c=(a=this._audio)===null||a===void 0?void 0:a._getInputDevicePromise();c&&(this._log.debug("inputDevicePromise detected, waiting..."),yield c,this._log.debug("inputDevicePromise resolved"));const o={audioHelper:this._audio,onIgnore:()=>{this._soundcache.get(ft.SoundName.Incoming).stop()},pstream:yield this._streamConnectedPromise||this._setupStream(),publisher:this._publisher,soundcache:this._soundcache};i=Object.assign({MediaStream:this._options.MediaStream,RTCPeerConnection:this._options.RTCPeerConnection,beforeAccept:h=>{!this._activeCall||this._activeCall===h||(this._activeCall.disconnect(),this._removeCall(this._activeCall))},codecPreferences:this._options.codecPreferences,customSounds:this._options.sounds,dialtonePlayer:ft._dialtonePlayer,dscp:this._options.dscp,forceAggressiveIceNomination:this._options.forceAggressiveIceNomination,getInputStream:()=>this._options.fileInputStream||this._callInputStream,getSinkIds:()=>this._callSinkIds,maxAverageBitrate:this._options.maxAverageBitrate,preflight:this._options.preflight,rtcConstraints:this._options.rtcConstraints,shouldPlayDisconnect:()=>{var h;return(h=this._audio)===null||h===void 0?void 0:h.disconnect()},twimlParams:n,voiceEventSidGenerator:this._options.voiceEventSidGenerator},i);const l=()=>{if(!this._stream){this._log.warn("UnsetPreferredUri called without a stream");return}this._activeCall===null&&this._calls.length===0&&this._stream.updatePreferredURI(null)},d=new(this._options.Call||dt)(o,i);return this._publisher.info("settings","init",{MediaStream:!!this._options.MediaStream,RTCPeerConnection:!!this._options.RTCPeerConnection,enumerateDevices:!!this._options.enumerateDevices,getUserMedia:!!this._options.getUserMedia},d),d.once("accept",()=>{var h,v,y,w,k;this._stream.updatePreferredURI(this._preferredURI),this._removeCall(d),this._activeCall=d,this._audio&&this._audio._maybeStartPollingVolume(),d.direction===dt.CallDirection.Outgoing&&(!((h=this._audio)===null||h===void 0)&&h.outgoing())&&!s&&this._soundcache.get(ft.SoundName.Outgoing).play();const I={edge:this._edge||this._region};this._options.edge&&(I.selected_edge=Array.isArray(this._options.edge)?this._options.edge:[this._options.edge]),this._publisher.info("settings","edge",I,d),!((v=this._audio)===null||v===void 0)&&v.localProcessedStream&&((y=this._audioProcessorEventObserver)===null||y===void 0||y.emit("enabled",!1)),!((w=this._audio)===null||w===void 0)&&w.remoteProcessedStream&&((k=this._audioProcessorEventObserver)===null||k===void 0||k.emit("enabled",!0))}),d.addListener("error",h=>{d.status()==="closed"&&(this._removeCall(d),l()),this._audio&&this._audio._maybeStopPollingVolume(),this._maybeStopIncomingSound()}),d.once("cancel",()=>{this._log.info(`Canceled: ${d.parameters.CallSid}`),this._removeCall(d),l(),this._audio&&this._audio._maybeStopPollingVolume(),this._maybeStopIncomingSound()}),d.once("disconnect",()=>{this._audio&&this._audio._maybeStopPollingVolume(),this._removeCall(d),l(),this._maybeStopIncomingSound()}),d.once("reject",()=>{this._log.info(`Rejected: ${d.parameters.CallSid}`),this._audio&&this._audio._maybeStopPollingVolume(),this._removeCall(d),l(),this._maybeStopIncomingSound()}),d.on("transportClose",()=>{d.status()===dt.State.Pending&&(this._audio&&this._audio._maybeStopPollingVolume(),this._removeCall(d),this._maybeStopIncomingSound())}),d})}_maybeStopIncomingSound(){this._calls.length||this._soundcache.get(ft.SoundName.Incoming).stop()}_removeCall(e){this._activeCall===e&&(this._activeCall=null,this._makeCallPromise=null);for(let t=this._calls.length-1;t>=0;t--)e===this._calls[t]&&this._calls.splice(t,1)}_sendPresence(e){return yi(this,void 0,void 0,function*(){const t=yield this._streamConnectedPromise;t&&(t.register({audio:e}),e?this._startRegistrationTimer():this._stopRegistrationTimer())})}_setState(e){if(e===this.state)return;this._state=e;const t=this._stateEventMapping[e];this._log.debug(`#${t}`),this.emit(t)}_setupAudioHelper(){this._audioProcessorEventObserver||(this._audioProcessorEventObserver=new Kme,this._audioProcessorEventObserver.on("event",({name:t,group:n,isRemote:i})=>{this._publisher.info(n,t,{is_remote:i},this._activeCall)}));const e={audioContext:ft.audioContext,audioProcessorEventObserver:this._audioProcessorEventObserver,beforeSetInputDevice:()=>this._makeCallPromise?(this._log.debug("beforeSetInputDevice pause detected"),this._makeCallPromise):(this._log.debug("beforeSetInputDevice pause not detected, setting default"),Promise.resolve()),enumerateDevices:this._options.enumerateDevices,getUserMedia:this._options.getUserMedia||zye};if(this._audio){this._log.info("Found existing audio helper; updating options..."),this._audio._updateUserOptions(e);return}this._audio=new(this._options.AudioHelper||zme)(this._updateSinkIds,this._updateInputStream,e),this._audio.on("deviceChange",t=>{const n=this._activeCall,i=t.map(s=>s.deviceId);this._publisher.info("audio","device-change",{lost_active_device_ids:i},n),n&&n._mediaHandler._onInputDevicesChanged()})}_setupLoglevel(e){const t=typeof e=="number"||typeof e=="string"?e:Gr.levels.ERROR;this._log.setDefaultLevel(t),this._log.info("Set logger default level to",t)}_setupPublisher(){this._publisher&&(this._log.info("Found existing publisher; destroying..."),this._destroyPublisher());const e={defaultPayload:this._createDefaultPayload,metadata:{app_name:this._options.appName,app_version:this._options.appVersion}};return this._options.eventgw&&(e.host=this._options.eventgw),this._home&&(e.host=VA(this._home)),this._publisher=new(this._options.Publisher||Ti)(r_e,this.token,e),this._options.publishEvents===!1?this._publisher.disable():this._publisher.on("error",t=>{this._log.warn("Cannot connect to insights.",t)}),this._publisher}_setupStream(){return this._stream&&(this._log.info("Found existing stream; destroying..."),this._destroyStream()),this._log.info("Setting up VSP"),this._stream=new(this._options.PStream||zr)(this.token,this._chunderURIs,{backoffMaxMs:this._options.backoffMaxMs,maxPreferredDurationMs:this._options.maxCallSignalingTimeoutMs}),this._stream.addListener("close",this._onSignalingClose),this._stream.addListener("connected",this._onSignalingConnected),this._stream.addListener("error",this._onSignalingError),this._stream.addListener("invite",this._onSignalingInvite),this._stream.addListener("offline",this._onSignalingOffline),this._stream.addListener("ready",this._onSignalingReady),this._streamConnectedPromise=Sw(this._stream,"connected","close").then(()=>this._stream)}_showIncomingCall(e,t){let n;return Promise.race([t(),new Promise((i,s)=>{n=setTimeout(()=>{const a="Playing incoming ringtone took too long; it might not play. Continuing execution...";s(new Error(a))},t_e)})]).catch(i=>{this._log.warn(i.message)}).then(()=>{clearTimeout(n),this._log.debug("#incoming",JSON.stringify({customParameters:e.customParameters,parameters:e.parameters})),this.emit(ft.EventName.Incoming,e)})}_startRegistrationTimer(){this._stopRegistrationTimer(),this._regTimer=setTimeout(()=>{this._sendPresence(!0)},e_e)}_stopRegistrationTimer(){this._regTimer&&clearTimeout(this._regTimer)}_throwIfDestroyed(){if(this.state===ft.State.Destroyed)throw new Bs("Device has been destroyed.")}_updateRingtoneSinkIds(e){return Promise.resolve(this._soundcache.get(ft.SoundName.Incoming).setSinkIds(e))}_updateSpeakerSinkIds(e){Array.from(this._soundcache.entries()).filter(n=>n[0]!==ft.SoundName.Incoming).forEach(n=>n[1].setSinkIds(e)),this._callSinkIds=e;const t=this._activeCall;return t?t._setSinkIds(e):Promise.resolve()}}ft._defaultSounds={disconnect:{filename:"disconnect",maxDuration:3e3},dtmf0:{filename:"dtmf-0",maxDuration:1e3},dtmf1:{filename:"dtmf-1",maxDuration:1e3},dtmf2:{filename:"dtmf-2",maxDuration:1e3},dtmf3:{filename:"dtmf-3",maxDuration:1e3},dtmf4:{filename:"dtmf-4",maxDuration:1e3},dtmf5:{filename:"dtmf-5",maxDuration:1e3},dtmf6:{filename:"dtmf-6",maxDuration:1e3},dtmf7:{filename:"dtmf-7",maxDuration:1e3},dtmf8:{filename:"dtmf-8",maxDuration:1e3},dtmf9:{filename:"dtmf-9",maxDuration:1e3},dtmfh:{filename:"dtmf-hash",maxDuration:1e3},dtmfs:{filename:"dtmf-star",maxDuration:1e3},incoming:{filename:"incoming",shouldLoop:!0},outgoing:{filename:"outgoing",maxDuration:3e3}};(function(r){(function(e){e.Error="error",e.Incoming="incoming",e.Destroyed="destroyed",e.Unregistered="unregistered",e.Registering="registering",e.Registered="registered",e.TokenWillExpire="tokenWillExpire"})(r.EventName||(r.EventName={})),function(e){e.Destroyed="destroyed",e.Unregistered="unregistered",e.Registering="registering",e.Registered="registered"}(r.State||(r.State={})),function(e){e.Incoming="incoming",e.Outgoing="outgoing",e.Disconnect="disconnect",e.Dtmf0="dtmf0",e.Dtmf1="dtmf1",e.Dtmf2="dtmf2",e.Dtmf3="dtmf3",e.Dtmf4="dtmf4",e.Dtmf5="dtmf5",e.Dtmf6="dtmf6",e.Dtmf7="dtmf7",e.Dtmf8="dtmf8",e.Dtmf9="dtmf9",e.DtmfS="dtmfs",e.DtmfH="dtmfh"}(r.SoundName||(r.SoundName={}))})(ft||(ft={}));class Rb{constructor(e,t=!1){this.deleted=!1;let n;const i=e.candidate.split("network-cost ");i[1]&&(n=parseInt(i[1],10)),this.candidateType=e.type,this.ip=e.ip||e.address,this.isRemote=t,this.networkCost=n,this.port=e.port,this.priority=e.priority,this.protocol=e.protocol,this.relatedAddress=e.relatedAddress,this.relatedPort=e.relatedPort,this.tcpType=e.tcpType,this.transportId=e.sdpMid}toPayload(){return{candidate_type:this.candidateType,deleted:this.deleted,ip:this.ip,is_remote:this.isRemote,"network-cost":this.networkCost,port:this.port,priority:this.priority,protocol:this.protocol,related_address:this.relatedAddress,related_port:this.relatedPort,tcp_type:this.tcpType,transport_id:this.transportId}}}const XA=94.768;function i_e(r,e,t){if(typeof r!="number"||typeof e!="number"||typeof t!="number"||!nv(r)||!nv(e)||!nv(t))return null;const n=r+e*2+10;let i=0;switch(!0){case n<160:i=XA-n/40;break;case n<1e3:i=XA-(n-120)/10;break}switch(!0){case t<=i/2.5:i=Math.max(i-t*2.5,6.52);break;default:i=0;break}return 1+.035*i+7e-6*i*(i-60)*(100-i)}function nv(r){return typeof r=="number"&&!isNaN(r)&&isFinite(r)&&r>=0}var s_e={calculate:i_e,isNonNegativeNumber:nv};const a_e=5,o_e=0,u_e=3,c_e=1e3,l_e=5*1e3,d_e={audioInputLevel:{minStandardDeviation:327.67,sampleCount:10},audioOutputLevel:{minStandardDeviation:327.67,sampleCount:10},bytesReceived:{clearCount:2,min:1,raiseCount:3,sampleCount:3},bytesSent:{clearCount:2,min:1,raiseCount:3,sampleCount:3},jitter:{max:30},mos:{min:3},packetsLostFraction:[{max:1},{clearValue:1,maxAverage:3,sampleCount:7}],rtt:{max:400}};function f_e(r,e){return e.reduce((t,n)=>t+=n>r?1:0,0)}function h_e(r,e){return e.reduce((t,n)=>t+=n<r?1:0,0)}function p_e(r){if(r.length<=0)return null;const e=r.reduce((i,s)=>i+s,0)/r.length,t=r.map(i=>Math.pow(i-e,2));return Math.sqrt(t.reduce((i,s)=>i+s,0)/t.length)}function v_e(r){return r.reduce((e,t)=>[...e,...t],[])}class g_e extends Ss.EventEmitter{constructor(e){super(),this._activeWarnings=new Map,this._currentStreaks=new Map,this._inputVolumes=[],this._outputVolumes=[],this._sampleBuffer=[],this._supplementalSampleBuffers={audioInputLevel:[],audioOutputLevel:[]},this._warningsEnabled=!0,e=e||{},this._getRTCStats=e.getRTCStats||cye,this._mos=e.Mos||s_e,this._peerConnection=e.peerConnection,this._thresholds=Object.assign(Object.assign({},d_e),e.thresholds);const t=Object.values(this._thresholds).map(n=>n.sampleCount).filter(n=>!!n);this._maxSampleCount=Math.max(a_e,...t),this._peerConnection&&this.enable(this._peerConnection)}addVolumes(e,t){this._inputVolumes.push(e),this._outputVolumes.push(t)}disable(){return this._sampleInterval&&(clearInterval(this._sampleInterval),delete this._sampleInterval),this}disableWarnings(){return this._warningsEnabled&&this._activeWarnings.clear(),this._warningsEnabled=!1,this}enable(e){if(e){if(this._peerConnection&&e!==this._peerConnection)throw new kr("Attempted to replace an existing PeerConnection in StatsMonitor.enable");this._peerConnection=e}if(!this._peerConnection)throw new kr("Can not enable StatsMonitor without a PeerConnection");return this._sampleInterval=this._sampleInterval||setInterval(this._fetchSample.bind(this),c_e),this}enableWarnings(){return this._warningsEnabled=!0,this}hasActiveWarning(e,t){const n=`${e}:${t}`;return!!this._activeWarnings.get(n)}_addSample(e){const t=this._sampleBuffer;t.push(e),t.length>this._maxSampleCount&&t.splice(0,t.length-this._maxSampleCount)}_clearWarning(e,t,n){const i=`${e}:${t}`,s=this._activeWarnings.get(i);!s||Date.now()-s.timeRaised<l_e||(this._activeWarnings.delete(i),this.emit("warning-cleared",Object.assign(Object.assign({},n),{name:e,threshold:{name:t,value:this._thresholds[e][t]}})))}_createSample(e,t){const n=t&&t.totals.bytesSent||0,i=t&&t.totals.bytesReceived||0,s=t&&t.totals.packetsSent||0,a=t&&t.totals.packetsReceived||0,c=t&&t.totals.packetsLost||0,o=e.bytesSent-n,l=e.bytesReceived-i,d=e.packetsSent-s,h=e.packetsReceived-a,v=e.packetsLost-c,y=h+v,w=y>0?v/y*100:0,k=e.packetsReceived+e.packetsLost,I=k>0?e.packetsLost/k*100:100,A=typeof e.rtt=="number"||!t?e.rtt:t.rtt,j=this._inputVolumes.splice(0);this._supplementalSampleBuffers.audioInputLevel.push(j);const L=this._outputVolumes.splice(0);return this._supplementalSampleBuffers.audioOutputLevel.push(L),{audioInputLevel:Math.round(Gd(j)),audioOutputLevel:Math.round(Gd(L)),bytesReceived:l,bytesSent:o,codecName:e.codecName,jitter:e.jitter,mos:this._mos.calculate(A,e.jitter,t&&w),packetsLost:v,packetsLostFraction:w,packetsReceived:h,packetsSent:d,rtt:A,timestamp:e.timestamp,totals:{bytesReceived:e.bytesReceived,bytesSent:e.bytesSent,packetsLost:e.packetsLost,packetsLostFraction:I,packetsReceived:e.packetsReceived,packetsSent:e.packetsSent}}}_fetchSample(){this._getSample().then(e=>{this._addSample(e),this._raiseWarnings(),this.emit("sample",e)}).catch(e=>{this.disable(),this.emit("error",e)})}_getSample(){return this._getRTCStats(this._peerConnection).then(e=>{let t=null;return this._sampleBuffer.length&&(t=this._sampleBuffer[this._sampleBuffer.length-1]),this._createSample(e,t)})}_raiseWarning(e,t,n){const i=`${e}:${t}`;if(this._activeWarnings.has(i))return;this._activeWarnings.set(i,{timeRaised:Date.now()});const s=this._thresholds[e];let a;if(Array.isArray(s)){const c=s.find(o=>t in o);c&&(a=c[t])}else a=this._thresholds[e][t];this.emit("warning",Object.assign(Object.assign({},n),{name:e,threshold:{name:t,value:a}}))}_raiseWarnings(){this._warningsEnabled&&Object.keys(this._thresholds).forEach(e=>this._raiseWarningsForStat(e))}_raiseWarningsForStat(e){(Array.isArray(this._thresholds[e])?this._thresholds[e]:[this._thresholds[e]]).forEach(n=>{const i=this._sampleBuffer,s=n.clearCount||o_e,a=n.raiseCount||u_e,c=n.sampleCount||this._maxSampleCount;let o=i.slice(-c);const l=o.map(v=>v[e]);if(l.some(v=>typeof v>"u"||v===null))return;let h;if(typeof n.max=="number"&&(h=f_e(n.max,l),h>=a?this._raiseWarning(e,"max",{values:l,samples:o}):h<=s&&this._clearWarning(e,"max",{values:l,samples:o})),typeof n.min=="number"&&(h=h_e(n.min,l),h>=a?this._raiseWarning(e,"min",{values:l,samples:o}):h<=s&&this._clearWarning(e,"min",{values:l,samples:o})),typeof n.maxDuration=="number"&&i.length>1){o=i.slice(-2);const v=o[0][e],y=o[1][e],w=this._currentStreaks.get(e)||0,k=v===y?w+1:0;this._currentStreaks.set(e,k),k>=n.maxDuration?this._raiseWarning(e,"maxDuration",{value:k}):k===0&&this._clearWarning(e,"maxDuration",{value:w})}if(typeof n.minStandardDeviation=="number"){const v=this._supplementalSampleBuffers[e];if(!v||v.length<n.sampleCount)return;v.length>n.sampleCount&&v.splice(0,v.length-n.sampleCount);const y=v_e(v.slice(-c)),w=p_e(y);if(typeof w!="number")return;w<n.minStandardDeviation?this._raiseWarning(e,"minStandardDeviation",{value:w}):this._clearWarning(e,"minStandardDeviation",{value:w})}[["maxAverage",(v,y)=>v>y],["minAverage",(v,y)=>v<y]].forEach(([v,y])=>{if(typeof n[v]=="number"&&l.length>=c){const w=Gd(l);y(w,n[v])?this._raiseWarning(e,v,{values:l,samples:o}):y(w,n.clearValue||n[v])||this._clearWarning(e,v,{values:l,samples:o})}})})}}const QA={factor:1.1,jitter:.5,max:3e4,min:1},m_e=70,y_e=500,__e=160,b_e=10,S_e=5e3,ZA={disconnect:!0,info:{code:31003,message:"Connection with Twilio was interrupted.",twilioError:new ga.ConnectionError}},eO={packetsLostFraction:{max:"packet-loss",maxAverage:"packets-lost-fraction"}},tO={audioInputLevel:"audio-input-level",audioOutputLevel:"audio-output-level",bytesReceived:"bytes-received",bytesSent:"bytes-sent",jitter:"jitter",mos:"mos",rtt:"rtt"},w_e={max:"high-",maxAverage:"high-",maxDuration:"constant-",min:"low-",minStandardDeviation:"constant-"};class dt extends Ss.EventEmitter{get direction(){return this._direction}get codec(){return this._codec}get connectToken(){const e=this._signalingReconnectToken,t=this.parameters&&this.parameters.CallSid?this.parameters.CallSid:void 0;if(!e||!t)return;const n=this.customParameters&&typeof this.customParameters.keys=="function"?Array.from(this.customParameters.keys()).reduce((s,a)=>(s[a]=this.customParameters.get(a),s),{}):{},i=this.parameters||{};return btoa(encodeURIComponent(JSON.stringify({customParameters:n,parameters:i,signalingReconnectToken:e})))}constructor(e,t){super(),this.parameters={},this._inputVolumeStreak=0,this._isAnswered=!1,this._isCancelled=!1,this._isRejected=!1,this._latestInputVolume=0,this._latestOutputVolume=0,this._log=new On("Call"),this._mediaStatus=dt.State.Pending,this._messages=new Map,this._metricsSamples=[],this._options={MediaHandler:Dt,MediaStream:null,enableImprovedSignalingErrorPrecision:!1,offerSdp:null,shouldPlayDisconnect:()=>!0,voiceEventSidGenerator:Ew},this._outputVolumeStreak=0,this._shouldSendHangup=!0,this._signalingStatus=dt.State.Pending,this._soundcache=new Map,this._status=dt.State.Pending,this._wasConnected=!1,this.toString=()=>"[Twilio.Call instance]",this._emitWarning=(a,c,o,l,d,h)=>{const y=`${a}warning${d?"-cleared":"-raised"}`;if(c==="constant-audio-input-level"&&this.isMuted())return;let w=d?"info":"warning";c==="constant-audio-output-level"&&(w="info");const k={threshold:o};if(l&&(l instanceof Array?k.values=l.map(I=>typeof I=="number"?Math.round(I*100)/100:l):k.value=l),this._publisher.post(w,y,c,{data:k},this),c!=="constant-audio-output-level"){const I=d?"warning-cleared":"warning";this._log.debug(`#${I}`,c),this.emit(I,c,h&&!d?h:null)}},this._onAck=a=>{const{acktype:c,callsid:o,voiceeventsid:l}=a;if(this.parameters.CallSid!==o){this._log.warn(`Received ack from a different callsid: ${o}`);return}c==="message"&&this._onMessageSent(l)},this._onAnswer=a=>{typeof a.reconnect=="string"&&(this._signalingReconnectToken=a.reconnect),!(this._isAnswered&&this._status!==dt.State.Reconnecting)&&(this._setCallSid(a),this._isAnswered=!0,this._maybeTransitionToOpen())},this._onCancel=a=>{const c=a.callsid;this.parameters.CallSid===c&&(this._isCancelled=!0,this._publisher.info("connection","cancel",null,this),this._cleanupEventListeners(),this._mediaHandler.close(),this._status=dt.State.Closed,this._log.debug("#cancel"),this.emit("cancel"),this._pstream.removeListener("cancel",this._onCancel))},this._onConnected=()=>{this._log.info("Received connected from pstream"),this._signalingReconnectToken&&this._mediaHandler.version&&this._pstream.reconnect(this._mediaHandler.version.getSDP(),this.parameters.CallSid,this._signalingReconnectToken)},this._onHangup=a=>{if(this.status()!==dt.State.Closed){if(a.callsid&&(this.parameters.CallSid||this.outboundConnectionId)){if(a.callsid!==this.parameters.CallSid&&a.callsid!==this.outboundConnectionId)return}else if(a.callsid)return;if(this._log.info("Received HANGUP from gateway"),a.error){const c=a.error.code,o=_w(this._options.enableImprovedSignalingErrorPrecision,c),l=typeof o<"u"?new o(a.error.message):new ai.ConnectionError("Error sent from gateway in HANGUP",a.error);this._log.error("Received an error from the gateway:",l),this._log.debug("#error",l),this.emit("error",l)}this._shouldSendHangup=!1,this._publisher.info("connection","disconnected-by-remote",null,this),this._disconnect(null,!0),this._cleanupEventListeners()}},this._onMediaFailure=a=>{const{ConnectionDisconnected:c,ConnectionFailed:o,IceGatheringFailed:l,LowBytes:d}=dt.MediaFailure,h=a===o||a===l;if(!RT(window,window.navigator)&&a===o)return this._mediaHandler.onerror(ZA);if(this._mediaStatus===dt.State.Reconnecting){if(h){if(Date.now()-this._mediaReconnectStartTime>QA.max)return this._log.warn("Exceeded max ICE retries"),this._mediaHandler.onerror(ZA);try{this._mediaReconnectBackoff.backoff()}catch(k){if(!(k.message&&k.message==="Backoff in progress."))throw k}}return}const v=this._mediaHandler.version.pc,y=v&&v.iceConnectionState==="disconnected",w=this._monitor.hasActiveWarning("bytesSent","min")||this._monitor.hasActiveWarning("bytesReceived","min");if(a===d&&y||a===c&&w||h){const k=new ga.ConnectionError("Media connection failed.");this._log.warn("ICE Connection disconnected."),this._publisher.warn("connection","error",k,this),this._publisher.info("connection","reconnecting",null,this),this._mediaReconnectStartTime=Date.now(),this._status=dt.State.Reconnecting,this._mediaStatus=dt.State.Reconnecting,this._mediaReconnectBackoff.reset(),this._mediaReconnectBackoff.backoff(),this._log.debug("#reconnecting"),this.emit("reconnecting",k)}},this._onMediaReconnected=()=>{this._mediaStatus===dt.State.Reconnecting&&(this._log.info("ICE Connection reestablished."),this._mediaStatus=dt.State.Open,this._signalingStatus===dt.State.Open&&(this._publisher.info("connection","reconnected",null,this),this._log.debug("#reconnected"),this.emit("reconnected"),this._status=dt.State.Open))},this._onMessageReceived=a=>{const{callsid:c,content:o,contenttype:l,messagetype:d,voiceeventsid:h}=a;if(this.parameters.CallSid!==c){this._log.warn(`Received a message from a different callsid: ${c}`);return}const v={content:o,contentType:l,messageType:d,voiceEventSid:h};this._publisher.info("call-message",d,{content_type:l,event_type:"received",voice_event_sid:h},this),this._log.debug("#messageReceived",JSON.stringify(v)),this.emit("messageReceived",v)},this._onMessageSent=a=>{if(!this._messages.has(a)){this._log.warn(`Received a messageSent with a voiceEventSid that doesn't exists: ${a}`);return}const c=this._messages.get(a);this._messages.delete(a),this._publisher.info("call-message",c==null?void 0:c.messageType,{content_type:c==null?void 0:c.contentType,event_type:"sent",voice_event_sid:a},this),this._log.debug("#messageSent",JSON.stringify(c)),this.emit("messageSent",c)},this._onRinging=a=>{if(this._setCallSid(a),this._status!==dt.State.Connecting&&this._status!==dt.State.Ringing)return;const c=!!a.sdp;this._status=dt.State.Ringing,this._publisher.info("connection","outgoing-ringing",{hasEarlyMedia:c},this),this._log.debug("#ringing"),this.emit("ringing",c)},this._onRTCSample=a=>{const c=Object.assign(Object.assign({},a),{inputVolume:this._latestInputVolume,outputVolume:this._latestOutputVolume});this._codec=c.codecName,this._metricsSamples.push(c),this._metricsSamples.length>=b_e&&this._publishMetrics(),this.emit("sample",a)},this._onSignalingError=a=>{const{callsid:c,voiceeventsid:o,error:l}=a;if(this.parameters.CallSid!==c){this._log.warn(`Received an error from a different callsid: ${c}`);return}if(o&&this._messages.has(o)){this._messages.delete(o),this._log.warn("Received an error while sending a message.",a),this._publisher.error("call-message","error",{code:l.code,message:l.message,voice_event_sid:o},this);let d;const h=_w(!!this._options.enableImprovedSignalingErrorPrecision,l.code);typeof h<"u"&&(d=new h(l)),d||(this._log.error("Unknown Call Message Error: ",l),d=new ai.UnknownError(l.message,l)),this._log.debug("#error",l,d),this.emit("error",d)}},this._onSignalingReconnected=()=>{this._signalingStatus===dt.State.Reconnecting&&(this._log.info("Signaling Connection reestablished."),this._signalingStatus=dt.State.Open,this._mediaStatus===dt.State.Open&&(this._publisher.info("connection","reconnected",null,this),this._log.debug("#reconnected"),this.emit("reconnected"),this._status=dt.State.Open))},this._onTransportClose=()=>{this._log.error("Received transportClose from pstream"),this._log.debug("#transportClose"),this.emit("transportClose"),this._signalingReconnectToken?(this._status=dt.State.Reconnecting,this._signalingStatus=dt.State.Reconnecting,this._publisher.info("connection","reconnecting",null,this),this._log.debug("#reconnecting"),this.emit("reconnecting",new _s.ConnectionDisconnected)):(this._status=dt.State.Closed,this._signalingStatus=dt.State.Closed)},this._reemitWarning=(a,c)=>{const o=/^audio/.test(a.name)?"audio-level-":"network-quality-",l=w_e[a.threshold.name];let d;a.name in eO?d=eO[a.name][a.threshold.name]:a.name in tO&&(d=tO[a.name]);const h=l+d;this._emitWarning(o,h,a.threshold.value,a.values||a.value,c,a)},this._reemitWarningCleared=a=>{this._reemitWarning(a,!0)},this._soundcache=e.soundcache,typeof e.onIgnore=="function"&&(this._onIgnore=e.onIgnore);const n=t&&t.twimlParams||{};this.customParameters=new Map(Object.entries(n).map(([a,c])=>[a,String(c)])),Object.assign(this._options,t),this._options.callParameters&&(this.parameters=this._options.callParameters),this._options.reconnectToken&&(this._signalingReconnectToken=this._options.reconnectToken),this._voiceEventSidGenerator=this._options.voiceEventSidGenerator||Ew,this._direction=this.parameters.CallSid&&!this._options.reconnectCallSid?dt.CallDirection.Incoming:dt.CallDirection.Outgoing,this.parameters?this.callerInfo=this.parameters.StirStatus?{isVerified:this.parameters.StirStatus==="TN-Validation-Passed-A"}:null:this.callerInfo=null,this._mediaReconnectBackoff=new gw(QA),this._mediaReconnectBackoff.on("ready",()=>this._mediaHandler.iceRestart()),this.outboundConnectionId=T_e();const i=this._publisher=e.publisher;this._direction===dt.CallDirection.Incoming?i.info("connection","incoming",null,this):i.info("connection","outgoing",{preflight:this._options.preflight,reconnect:!!this._options.reconnectCallSid},this);const s=this._monitor=new(this._options.StatsMonitor||g_e);s.on("sample",this._onRTCSample),s.disableWarnings(),setTimeout(()=>s.enableWarnings(),S_e),s.on("warning",(a,c)=>{(a.name==="bytesSent"||a.name==="bytesReceived")&&this._onMediaFailure(dt.MediaFailure.LowBytes),this._reemitWarning(a,c)}),s.on("warning-cleared",a=>{this._reemitWarningCleared(a)}),this._mediaHandler=new this._options.MediaHandler(e.audioHelper,e.pstream,{MediaStream:this._options.MediaStream,RTCPeerConnection:this._options.RTCPeerConnection,codecPreferences:this._options.codecPreferences,dscp:this._options.dscp,forceAggressiveIceNomination:this._options.forceAggressiveIceNomination,maxAverageBitrate:this._options.maxAverageBitrate}),this.on("volume",(a,c)=>{this._inputVolumeStreak=this._checkVolume(a,this._inputVolumeStreak,this._latestInputVolume,"input"),this._outputVolumeStreak=this._checkVolume(c,this._outputVolumeStreak,this._latestOutputVolume,"output"),this._latestInputVolume=a,this._latestOutputVolume=c}),this._mediaHandler.onaudio=a=>{this._log.debug("#audio"),this.emit("audio",a)},this._mediaHandler.onvolume=(a,c,o,l)=>{s.addVolumes(o/255*32767,l/255*32767),this.emit("volume",a,c)},this._mediaHandler.ondtlstransportstatechange=a=>{const c=a==="failed"?"error":"debug";this._publisher.post(c,"dtls-transport-state",a,null,this)},this._mediaHandler.onpcconnectionstatechange=a=>{let c="debug";const o=this._mediaHandler.getRTCDtlsTransport();a==="failed"&&(c=o&&o.state==="failed"?"error":"warning"),this._publisher.post(c,"pc-connection-state",a,null,this)},this._mediaHandler.onicecandidate=a=>{const c=new Rb(a).toPayload();this._publisher.debug("ice-candidate","ice-candidate",c,this)},this._mediaHandler.onselectedcandidatepairchange=a=>{const c=new Rb(a.local).toPayload(),o=new Rb(a.remote,!0).toPayload();this._publisher.debug("ice-candidate","selected-ice-candidate-pair",{local_candidate:c,remote_candidate:o},this)},this._mediaHandler.oniceconnectionstatechange=a=>{const c=a==="failed"?"error":"debug";this._publisher.post(c,"ice-connection-state",a,null,this)},this._mediaHandler.onicegatheringfailure=a=>{this._publisher.warn("ice-gathering-state",a,null,this),this._onMediaFailure(dt.MediaFailure.IceGatheringFailed)},this._mediaHandler.onicegatheringstatechange=a=>{this._publisher.debug("ice-gathering-state",a,null,this)},this._mediaHandler.onsignalingstatechange=a=>{this._publisher.debug("signaling-state",a,null,this)},this._mediaHandler.ondisconnected=a=>{this._log.warn(a),this._publisher.warn("network-quality-warning-raised","ice-connectivity-lost",{message:a},this),this._log.debug("#warning","ice-connectivity-lost"),this.emit("warning","ice-connectivity-lost"),this._onMediaFailure(dt.MediaFailure.ConnectionDisconnected)},this._mediaHandler.onfailed=a=>{this._onMediaFailure(dt.MediaFailure.ConnectionFailed)},this._mediaHandler.onconnected=()=>{this._status===dt.State.Reconnecting&&this._onMediaReconnected()},this._mediaHandler.onreconnected=a=>{this._log.info(a),this._publisher.info("network-quality-warning-cleared","ice-connectivity-lost",{message:a},this),this._log.debug("#warning-cleared","ice-connectivity-lost"),this.emit("warning-cleared","ice-connectivity-lost"),this._onMediaReconnected()},this._mediaHandler.onerror=a=>{a.disconnect===!0&&this._disconnect(a.info&&a.info.message);const c=a.info.twilioError||new ai.UnknownError(a.info.message);this._log.error("Received an error from MediaStream:",a),this._log.debug("#error",c),this.emit("error",c)},this._mediaHandler.onopen=()=>{this._status===dt.State.Open||this._status===dt.State.Reconnecting||(this._status===dt.State.Ringing||this._status===dt.State.Connecting?(this.mute(this._mediaHandler.isMuted),this._mediaStatus=dt.State.Open,this._maybeTransitionToOpen()):this._mediaHandler.close())},this._mediaHandler.onclose=()=>{this._status=dt.State.Closed,this._options.shouldPlayDisconnect&&this._options.shouldPlayDisconnect()&&!this._isCancelled&&!this._isRejected&&this._soundcache.get(ft.SoundName.Disconnect).play(),s.disable(),this._publishMetrics(),!this._isCancelled&&!this._isRejected&&(this._log.debug("#disconnect"),this.emit("disconnect",this))},this._pstream=e.pstream,this._pstream.on("ack",this._onAck),this._pstream.on("cancel",this._onCancel),this._pstream.on("error",this._onSignalingError),this._pstream.on("ringing",this._onRinging),this._pstream.on("transportClose",this._onTransportClose),this._pstream.on("connected",this._onConnected),this._pstream.on("message",this._onMessageReceived),this.on("error",a=>{this._publisher.error("connection","error",{code:a.code,message:a.message},this),this._pstream&&this._pstream.status==="disconnected"&&this._cleanupEventListeners()}),this.on("disconnect",()=>{this._cleanupEventListeners()})}_setInputTracksFromStream(e){return this._mediaHandler.setInputTracksFromStream(e)}_setSinkIds(e){return this._mediaHandler._setSinkIds(e)}accept(e){if(this._log.debug(".accept",e),this._status!==dt.State.Pending){this._log.debug(`.accept noop. status is '${this._status}'`);return}e=e||{};const t=e.rtcConfiguration||this._options.rtcConfiguration,n=e.rtcConstraints||this._options.rtcConstraints||{},i={audio:typeof n.audio<"u"?n.audio:!0};this._status=dt.State.Connecting;const s=()=>{if(this._status!==dt.State.Connecting){this._cleanupEventListeners(),this._mediaHandler.close();return}const o=d=>{const h=this._direction===dt.CallDirection.Incoming?"accepted-by-local":"accepted-by-remote";this._publisher.info("connection",h,null,this);const{codecName:v,codecParams:y}=$ye(this._mediaHandler.version.getSDP());this._publisher.info("settings","codec",{codec_params:y,selected_codec:v},this),this._monitor.enable(d)},l=typeof this._options.getSinkIds=="function"&&this._options.getSinkIds();if(Array.isArray(l)&&this._mediaHandler._setSinkIds(l).catch(()=>{}),this._pstream.addListener("hangup",this._onHangup),this._direction===dt.CallDirection.Incoming)this._isAnswered=!0,this._pstream.on("answer",this._onAnswer),this._mediaHandler.answerIncomingCall(this.parameters.CallSid,this._options.offerSdp,t,o);else{const d=Array.from(this.customParameters.entries()).map(h=>`${encodeURIComponent(h[0])}=${encodeURIComponent(h[1])}`).join("&");this._pstream.on("answer",this._onAnswer),this._mediaHandler.makeOutgoingCall(d,this._signalingReconnectToken,this._options.reconnectCallSid||this.outboundConnectionId,t,o)}};this._options.beforeAccept&&this._options.beforeAccept(this);const a=typeof this._options.getInputStream=="function"&&this._options.getInputStream();(a?this._mediaHandler.setInputTracksFromStream(a):this._mediaHandler.openDefaultDeviceWithConstraints(i)).then(()=>{this._publisher.info("get-user-media","succeeded",{data:{audioConstraints:i}},this),s()},o=>{let l;o.code===31208||["PermissionDeniedError","NotAllowedError"].indexOf(o.name)!==-1?(l=new wl.PermissionDeniedError,this._publisher.error("get-user-media","denied",{data:{audioConstraints:i,error:o}},this)):(l=new wl.AcquisitionFailedError,this._publisher.error("get-user-media","failed",{data:{audioConstraints:i,error:o}},this)),this._disconnect(),this._log.debug("#error",o),this.emit("error",l)})}disconnect(){this._log.debug(".disconnect"),this._disconnect()}getLocalStream(){return this._mediaHandler&&this._mediaHandler.stream}getRemoteStream(){return this._mediaHandler&&this._mediaHandler._remoteStream}ignore(){if(this._log.debug(".ignore"),this._status!==dt.State.Pending){this._log.debug(`.ignore noop. status is '${this._status}'`);return}this._status=dt.State.Closed,this._mediaHandler.ignore(this.parameters.CallSid),this._publisher.info("connection","ignored-by-local",null,this),this._onIgnore&&this._onIgnore()}isMuted(){return this._mediaHandler.isMuted}mute(e=!0){this._log.debug(".mute",e);const t=this._mediaHandler.isMuted;this._mediaHandler.mute(e);const n=this._mediaHandler.isMuted;t!==n&&(this._publisher.info("connection",n?"muted":"unmuted",null,this),this._log.debug("#mute",n),this.emit("mute",n,this))}postFeedback(e,t){if(typeof e>"u"||e===null)return this._postFeedbackDeclined();if(!Object.values(dt.FeedbackScore).includes(e))throw new kr(`Feedback score must be one of: ${Object.values(dt.FeedbackScore)}`);if(typeof t<"u"&&t!==null&&!Object.values(dt.FeedbackIssue).includes(t))throw new kr(`Feedback issue must be one of: ${Object.values(dt.FeedbackIssue)}`);return this._publisher.info("feedback","received",{issue_name:t,quality_score:e},this,!0)}reject(){if(this._log.debug(".reject"),this._status!==dt.State.Pending){this._log.debug(`.reject noop. status is '${this._status}'`);return}this._isRejected=!0,this._pstream.reject(this.parameters.CallSid),this._mediaHandler.reject(this.parameters.CallSid),this._publisher.info("connection","rejected-by-local",null,this),this._cleanupEventListeners(),this._mediaHandler.close(),this._status=dt.State.Closed,this._log.debug("#reject"),this.emit("reject")}sendDigits(e){if(this._log.debug(".sendDigits",e),e.match(/[^0-9*#w]/))throw new kr("Illegal character passed into sendDigits");const t=this._options.customSounds||{},n=[];e.split("").forEach(c=>{let o=c!=="w"?`dtmf${c}`:"";o==="dtmf*"&&(o="dtmfs"),o==="dtmf#"&&(o="dtmfh"),n.push(o)});const i=()=>{const c=n.shift();c&&(this._options.dialtonePlayer&&!t[c]?this._options.dialtonePlayer.play(c):this._soundcache.get(c).play()),n.length&&setTimeout(()=>i(),200)};i();const s=this._mediaHandler.getOrCreateDTMFSender();function a(c){if(!c.length)return;const o=c.shift();o&&o.length&&s.insertDTMF(o,__e,m_e),setTimeout(a.bind(null,c),y_e)}if(s){if(!("canInsertDTMF"in s)||s.canInsertDTMF){this._log.info("Sending digits using RTCDTMFSender"),a(e.split("w"));return}this._log.info("RTCDTMFSender cannot insert DTMF")}if(this._log.info("Sending digits over PStream"),this._pstream!==null&&this._pstream.status!=="disconnected")this._pstream.dtmf(this.parameters.CallSid,e);else{const c=new ai.ConnectionError("Could not send DTMF: Signaling channel is disconnected");this._log.debug("#error",c),this.emit("error",c)}}sendMessage(e){this._log.debug(".sendMessage",JSON.stringify(e));const{content:t,contentType:n,messageType:i}=e;if(typeof t>"u"||t===null)throw new kr("`content` is empty");if(typeof i!="string")throw new kr("`messageType` must be a string.");if(i.length===0)throw new kr("`messageType` must be a non-empty string.");if(this._pstream===null)throw new Bs("Could not send CallMessage; Signaling channel is disconnected");const s=this.parameters.CallSid;if(typeof this.parameters.CallSid>"u")throw new Bs("Could not send CallMessage; Call has no CallSid");const a=this._voiceEventSidGenerator();return this._messages.set(a,{content:t,contentType:n,messageType:i,voiceEventSid:a}),this._pstream.sendMessage(s,t,n,i,a),a}status(){return this._status}_checkVolume(e,t,n,i){const s=t>=10;let a=0;return n===e&&(a=t),a>=10?this._emitWarning("audio-level-",`constant-audio-${i}-level`,10,a,!1):s&&this._emitWarning("audio-level-",`constant-audio-${i}-level`,10,a,!0),a}_cleanupEventListeners(){const e=()=>{this._pstream&&(this._pstream.removeListener("ack",this._onAck),this._pstream.removeListener("answer",this._onAnswer),this._pstream.removeListener("cancel",this._onCancel),this._pstream.removeListener("error",this._onSignalingError),this._pstream.removeListener("hangup",this._onHangup),this._pstream.removeListener("ringing",this._onRinging),this._pstream.removeListener("transportClose",this._onTransportClose),this._pstream.removeListener("connected",this._onConnected),this._pstream.removeListener("message",this._onMessageReceived))};e(),setTimeout(e,0)}_createMetricPayload(){const e={call_sid:this.parameters.CallSid,dscp:!!this._options.dscp,sdk_version:ol};return this._options.gateway&&(e.gateway=this._options.gateway),e.direction=this._direction,e}_disconnect(e,t){if(e=typeof e=="string"?e:null,!(this._status!==dt.State.Open&&this._status!==dt.State.Connecting&&this._status!==dt.State.Reconnecting&&this._status!==dt.State.Ringing)){if(this._log.info("Disconnecting..."),this._pstream!==null&&this._pstream.status!=="disconnected"&&this._shouldSendHangup){const n=this.parameters.CallSid||this.outboundConnectionId;n&&this._pstream.hangup(n,e)}this._cleanupEventListeners(),this._mediaHandler.close(),t||this._publisher.info("connection","disconnected-by-local",null,this)}}_maybeTransitionToOpen(){this._wasConnected,this._isAnswered&&(this._onSignalingReconnected(),this._signalingStatus=dt.State.Open,this._mediaHandler&&this._mediaHandler.status==="open"&&(this._status=dt.State.Open,this._wasConnected||(this._wasConnected=!0,this._log.debug("#accept"),this.emit("accept",this))))}_postFeedbackDeclined(){return this._publisher.info("feedback","received-none",null,this,!0)}_publishMetrics(){this._metricsSamples.length!==0&&this._publisher.postMetrics("quality-metrics-samples","metrics-sample",this._metricsSamples.splice(0),this._createMetricPayload(),this).catch(e=>{this._log.warn("Unable to post metrics to Insights. Received error:",e)})}_setCallSid(e){const t=e.callsid;t&&(this.parameters.CallSid=t,this._mediaHandler.callSid=t)}}dt.toString=()=>"[Twilio.Call class]";(function(r){(function(e){e.Closed="closed",e.Connecting="connecting",e.Open="open",e.Pending="pending",e.Reconnecting="reconnecting",e.Ringing="ringing"})(r.State||(r.State={})),function(e){e.AudioLatency="audio-latency",e.ChoppyAudio="choppy-audio",e.DroppedCall="dropped-call",e.Echo="echo",e.NoisyCall="noisy-call",e.OneWayAudio="one-way-audio"}(r.FeedbackIssue||(r.FeedbackIssue={})),function(e){e[e.One=1]="One",e[e.Two=2]="Two",e[e.Three=3]="Three",e[e.Four=4]="Four",e[e.Five=5]="Five"}(r.FeedbackScore||(r.FeedbackScore={})),function(e){e.Incoming="INCOMING",e.Outgoing="OUTGOING"}(r.CallDirection||(r.CallDirection={})),function(e){e.Opus="opus",e.PCMU="pcmu"}(r.Codec||(r.Codec={})),function(e){e.None="none",e.Timeout="timeout"}(r.IceGatheringFailureReason||(r.IceGatheringFailureReason={})),function(e){e.ConnectionDisconnected="ConnectionDisconnected",e.ConnectionFailed="ConnectionFailed",e.IceGatheringFailed="IceGatheringFailed",e.LowBytes="LowBytes"}(r.MediaFailure||(r.MediaFailure={}))})(dt||(dt={}));function T_e(){return"TJSxxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{const e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)})}const Up=new an("TwilioVoiceProvider"),Pb={"high-rtt":"high-latency","high-jitter":"jitter","high-packet-loss":"packet-loss","high-packets-lost-fraction":"packet-loss","low-mos":"low-quality"},C_e=1500,zd=class zd extends Ow{constructor(){super(...arguments);be(this,"device",null);be(this,"call",null);be(this,"callListeners",[]);be(this,"deviceListeners",[]);be(this,"activeRawWarnings",new Set);be(this,"qualityEmitTimer",null);be(this,"lastQualityKey","good|");be(this,"disposed",!1)}getRemoteStream(){var t,n;return((n=(t=this.call)==null?void 0:t.getRemoteStream)==null?void 0:n.call(t))??null}async create(){var n,i;let t;try{t=await this.issueVoiceToken()}catch(s){if(this.disposed)return;throw s}if(!this.disposed){if(this.device=new ft(t.token,{logLevel:"warn"}),this.attachDeviceListeners(this.device),this.call=await this.device.connect({params:{call_id:String(this.state.id),from:"end_user"}}),this.disposed){try{(n=this.call)==null||n.disconnect()}catch{}try{(i=this.device)==null||i.destroy()}catch{}this.call=null,this.device=null;return}this.attachCallListeners(this.call)}}async destroy(){var t,n;if(this.disposed=!0,this.call)for(const[i,s]of this.callListeners)try{this.call.off(i,s)}catch{}if(this.callListeners.length=0,this.qualityEmitTimer&&(clearTimeout(this.qualityEmitTimer),this.qualityEmitTimer=null),this.activeRawWarnings.clear(),this.lastQualityKey="good|",this.device)for(const[i,s]of this.deviceListeners)try{this.device.off(i,s)}catch{}this.deviceListeners.length=0;try{(t=this.call)==null||t.disconnect()}catch{}try{(n=this.device)==null||n.destroy()}catch{}this.call=null,this.device=null}mute(t){var n;(n=this.call)==null||n.mute(t)}isMuted(){var t;return((t=this.call)==null?void 0:t.isMuted())??!1}isOutputSelectionSupported(){var t,n;return!!((n=(t=this.device)==null?void 0:t.audio)!=null&&n.isOutputSelectionSupported)}getAvailableOutputDevices(){var n;const t=(n=this.device)==null?void 0:n.audio;return t?Array.from(t.availableOutputDevices.values()):[]}async setOutputDevice(t){var i;const n=(i=this.device)==null?void 0:i.audio;if(!n)throw new la("output selection unavailable: Twilio Device not initialized");await n.speakerDevices.set(t)}async hangup(){if(!this.call){this.events.triggerEvent(ps.DISCONNECTED,{reason:"ended"});return}try{this.call.disconnect()}catch{this.events.triggerEvent(ps.DISCONNECTED,{reason:"ended"})}}sendMessage(t){if(!this.call||typeof this.call.sendMessage!="function")return null;try{return this.call.sendMessage({content:{type:t.type,data:t.data??{}},contentType:"application/json",messageType:"user-defined-message"})}catch(n){return Up.warn("sendMessage failed; caller will fall back to REST",n),null}}logInnerTwilioError(t,n,i){var c;const s=(c=n==null?void 0:n.originalError)==null?void 0:c.twilioError;if(!s)return;const a=i!=null?`[${i}]`:"[?]";Up.warn(`${t} error ${a} inner=${s.name}/${s.code}`,{inner:{name:s.name,code:s.code}})}isTransientTwilioError(t,n){var i,s;if(n===31005)return!0;if(n===31e3){const a=(s=(i=t==null?void 0:t.originalError)==null?void 0:i.twilioError)==null?void 0:s.code;return a!=null&&zd.TRANSIENT_SIGNALING_INNER.has(a)}return!1}attachDeviceListeners(t){const n=async()=>{try{const a=await this.issueVoiceToken();t.updateToken(a.token)}catch(a){this.events.triggerEvent(ps.ERROR,{error:new la("token refresh failed",a)})}};t.on("tokenWillExpire",n),this.deviceListeners.push(["tokenWillExpire",n]);const i=a=>{const c=a==null?void 0:a.code;if(this.logInnerTwilioError("device",a,c),this.isTransientTwilioError(a,c)){Up.warn(`transient device error [${c}], awaiting Twilio reconnect`,a);return}const o=(a==null?void 0:a.message)??"device error",l=c!=null?`[twilio:${c}] ${o}`:o;this.events.triggerEvent(ps.ERROR,{error:new la(l,a)})};t.on("error",i),this.deviceListeners.push(["error",i]);const s=()=>{this.events.triggerEvent(ps.ERROR,{error:new la("device session lost (unregistered)")})};t.on("unregistered",s),this.deviceListeners.push(["unregistered",s])}attachCallListeners(t){const n=()=>{this.events.triggerEvent(ps.CONNECTED,{agent:this.state.agent??this.state.virtual_agent??null})};t.on("accept",n),this.callListeners.push(["accept",n]);const i=()=>{this.events.triggerEvent(ps.DISCONNECTED,{reason:"ended"})};t.on("disconnect",i),this.callListeners.push(["disconnect",i]);const s=()=>{this.events.triggerEvent(ps.DISCONNECTED,{reason:"canceled"})};t.on("cancel",s),this.callListeners.push(["cancel",s]);const a=()=>{this.events.triggerEvent(Kn.RECONNECTING)};t.on("reconnecting",a),this.callListeners.push(["reconnecting",a]);const c=()=>{this.events.triggerEvent(Kn.RECONNECTED)};t.on("reconnected",c),this.callListeners.push(["reconnected",c]);const o=v=>{Pb[v]&&(this.activeRawWarnings.add(v),this.scheduleQualityEmit())};t.on("warning",o),this.callListeners.push(["warning",o]);const l=v=>{Pb[v]&&(this.activeRawWarnings.delete(v),this.scheduleQualityEmit())};t.on("warning-cleared",l),this.callListeners.push(["warning-cleared",l]);const d=v=>{const y=this.parseIncomingMessage(v);y&&this.events.triggerEvent(yO,y)};t.on("messageReceived",d),this.callListeners.push(["messageReceived",d]);const h=v=>{const y=v==null?void 0:v.code;if(this.logInnerTwilioError("call",v,y),this.isTransientTwilioError(v,y)){Up.warn(`transient call error [${y}], awaiting Twilio reconnect`,v);return}const w=(v==null?void 0:v.message)??"call error",k=y!=null?`[twilio:${y}] ${w}`:w;this.events.triggerEvent(ps.ERROR,{error:new la(k,v)})};t.on("error",h),this.callListeners.push(["error",h])}scheduleQualityEmit(){this.qualityEmitTimer&&clearTimeout(this.qualityEmitTimer),this.qualityEmitTimer=setTimeout(()=>{this.qualityEmitTimer=null;const t=[...new Set([...this.activeRawWarnings].map(s=>Pb[s]))].filter(s=>s!==void 0).sort(),n=t.length>0?"degraded":"good",i=`${n}|${t.join(",")}`;i!==this.lastQualityKey&&(this.lastQualityKey=i,this.events.triggerEvent(Kn.CONNECTION_QUALITY,{level:n,warnings:t}))},C_e)}parseIncomingMessage(t){if(!t)return null;let n=t.content;if(typeof n=="string")try{n=JSON.parse(n)}catch{return null}return!n||typeof n.type!="string"?null:{type:n.type,data:n.data??{}}}};be(zd,"type",gO),be(zd,"TRANSIENT_SIGNALING_INNER",new Set([53e3,53001]));let kw=zd;bO(kw);exports.AnotherTabVoiceCallError=fl;exports.BaseVoiceProvider=Ow;exports.COBROWSE_EVENTS=Bp;exports.CallInProgressError=Vu;exports.ChannelType=iv;exports.ChatEndedError=av;exports.CheckInStatus=nO;exports.Client=r5;exports.ENVIRONMENT=l6;exports.EventManager=zv;exports.FeatureNotEnabledError=ll;exports.InboundDisabledError=cl;exports.Logger=an;exports.MediaStore=cO;exports.MessageType=ln;exports.MicPermissionDeniedError=dl;exports.NoActiveVoiceCallError=Uo;exports.NotiEvent=Gn;exports.OPTIONS=zn;exports.OperationHoursError=Hu;exports.PostSessionStatus=ul;exports.ProviderError=la;exports.ProviderType=Wu;exports.RISK_FLAG_EVENTS=lO;exports.SmartActionError=ni;exports.UnauthorizedError=Xc;exports.UnknownVoiceError=uv;exports.UserType=_i;exports.VERSION=Pw;exports.VOICE_EVENTS=Kn;exports.VoiceCallError=ws;exports.addProviderType=Gv;exports.addVoiceProviderType=bO;exports.getErrorMessage=Aw;exports.getErrorStatus=mO;exports.getVoiceProviderType=SO;exports.hasErrorCode=EW;exports.isAfterHoursError=kW;exports.isMobilePlatform=pO;exports.toIdentity=Fp;
|