@ujet/websdk-headless 3.37.4 → 3.38.4

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 CHANGED
@@ -1,12 +1,12 @@
1
- "use strict";var HI=Object.defineProperty;var VI=(e,t,r)=>t in e?HI(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var ht=(e,t,r)=>VI(e,typeof t!="symbol"?t+"":t,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function KI(e,t){for(var r=0;r<t.length;r++){const n=t[r];if(typeof n!="string"&&!Array.isArray(n)){for(const i in n)if(i!=="default"&&!(i in e)){const a=Object.getOwnPropertyDescriptor(n,i);a&&Object.defineProperty(e,i,a.get?a:{enumerable:!0,get:()=>n[i]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}var to=(e=>(e.WAITING="waiting",e.READY="ready",e.IN_PROGRESS="in_progress",e.FINISHED="finished",e))(to||{});const JI="prod",Qv="3.37.4",ey="https://main.api.ujet.co",Br={companyId:"",tenant:"",trackerId:"",deviceId:"",application:"websdk",version:Qv};/*! @license DOMPurify 3.2.4 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.2.4/LICENSE */const{entries:mT,setPrototypeOf:ty,isFrozen:YI,getPrototypeOf:XI,getOwnPropertyDescriptor:QI}=Object;let{freeze:tn,seal:Fn,create:gT}=Object,{apply:hh,construct:vh}=typeof Reflect<"u"&&Reflect;tn||(tn=function(t){return t});Fn||(Fn=function(t){return t});hh||(hh=function(t,r,n){return t.apply(r,n)});vh||(vh=function(t,r){return new t(...r)});const nc=rn(Array.prototype.forEach),ZI=rn(Array.prototype.lastIndexOf),ry=rn(Array.prototype.pop),Ro=rn(Array.prototype.push),eO=rn(Array.prototype.splice),pl=rn(String.prototype.toLowerCase),nd=rn(String.prototype.toString),ny=rn(String.prototype.match),$o=rn(String.prototype.replace),tO=rn(String.prototype.indexOf),rO=rn(String.prototype.trim),Xn=rn(Object.prototype.hasOwnProperty),Xr=rn(RegExp.prototype.test),Io=nO(TypeError);function rn(e){return function(t){for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];return hh(e,t,n)}}function nO(e){return function(){for(var t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];return vh(e,r)}}function xt(e,t){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:pl;ty&&ty(e,null);let n=t.length;for(;n--;){let i=t[n];if(typeof i=="string"){const a=r(i);a!==i&&(YI(t)||(t[n]=a),i=a)}e[i]=!0}return e}function iO(e){for(let t=0;t<e.length;t++)Xn(e,t)||(e[t]=null);return e}function Qa(e){const t=gT(null);for(const[r,n]of mT(e))Xn(e,r)&&(Array.isArray(n)?t[r]=iO(n):n&&typeof n=="object"&&n.constructor===Object?t[r]=Qa(n):t[r]=n);return t}function Oo(e,t){for(;e!==null;){const n=QI(e,t);if(n){if(n.get)return rn(n.get);if(typeof n.value=="function")return rn(n.value)}e=XI(e)}function r(){return null}return r}const iy=tn(["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","section","select","shadow","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"]),id=tn(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","filter","font","g","glyph","glyphref","hkern","image","line","lineargradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),ad=tn(["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"]),aO=tn(["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"]),sd=tn(["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"]),sO=tn(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),ay=tn(["#text"]),sy=tn(["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","face","for","headers","height","hidden","high","href","hreflang","id","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","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),od=tn(["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","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"]),oy=tn(["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"]),ic=tn(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),oO=Fn(/\{\{[\w\W]*|[\w\W]*\}\}/gm),uO=Fn(/<%[\w\W]*|[\w\W]*%>/gm),cO=Fn(/\$\{[\w\W]*/gm),lO=Fn(/^data-[\-\w.\u00B7-\uFFFF]+$/),fO=Fn(/^aria-[\-\w]+$/),yT=Fn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),dO=Fn(/^(?:\w+script|data):/i),pO=Fn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),bT=Fn(/^html$/i),hO=Fn(/^[a-z][.\w]*(-[.\w]+)+$/i);var uy=Object.freeze({__proto__:null,ARIA_ATTR:fO,ATTR_WHITESPACE:pO,CUSTOM_ELEMENT:hO,DATA_ATTR:lO,DOCTYPE_NAME:bT,ERB_EXPR:uO,IS_ALLOWED_URI:yT,IS_SCRIPT_OR_DATA:dO,MUSTACHE_EXPR:oO,TMPLIT_EXPR:cO});const Ao={element:1,text:3,progressingInstruction:7,comment:8,document:9},vO=function(){return typeof window>"u"?null:window},mO=function(t,r){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let n=null;const i="data-tt-policy-suffix";r&&r.hasAttribute(i)&&(n=r.getAttribute(i));const a="dompurify"+(n?"#"+n:"");try{return t.createPolicy(a,{createHTML(s){return s},createScriptURL(s){return s}})}catch{return console.warn("TrustedTypes policy "+a+" could not be created."),null}},cy=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function _T(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:vO();const t=it=>_T(it);if(t.version="3.2.4",t.removed=[],!e||!e.document||e.document.nodeType!==Ao.document||!e.Element)return t.isSupported=!1,t;let{document:r}=e;const n=r,i=n.currentScript,{DocumentFragment:a,HTMLTemplateElement:s,Node:o,Element:u,NodeFilter:c,NamedNodeMap:l=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:p,DOMParser:v,trustedTypes:m}=e,b=u.prototype,T=Oo(b,"cloneNode"),I=Oo(b,"remove"),R=Oo(b,"nextSibling"),x=Oo(b,"childNodes"),N=Oo(b,"parentNode");if(typeof s=="function"){const it=r.createElement("template");it.content&&it.content.ownerDocument&&(r=it.content.ownerDocument)}let j,X="";const{implementation:J,createNodeIterator:V,createDocumentFragment:D,getElementsByTagName:te}=r,{importNode:ue}=n;let ee=cy();t.isSupported=typeof mT=="function"&&typeof N=="function"&&J&&J.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:ge,ERB_EXPR:L,TMPLIT_EXPR:pe,DATA_ATTR:Te,ARIA_ATTR:rt,IS_SCRIPT_OR_DATA:Ke,ATTR_WHITESPACE:Se,CUSTOM_ELEMENT:ce}=uy;let{IS_ALLOWED_URI:he}=uy,P=null;const Ie=xt({},[...iy,...id,...ad,...sd,...ay]);let qe=null;const Ne=xt({},[...sy,...od,...oy,...ic]);let _e=Object.seal(gT(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}})),Q=null,kt=null,Ce=!0,de=!0,Rt=!1,Ue=!0,Dt=!1,mt=!0,ke=!1,ft=!1,St=!1,Oe=!1,Bt=!1,vt=!1,qt=!0,sr=!1;const ze="user-content-";let Tr=!0,mr=!1,Et={},It=null;const bt=xt({},["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 ct=null;const Ft=xt({},["audio","video","img","source","image","track"]);let Pt=null;const cr=xt({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Cr="http://www.w3.org/1998/Math/MathML",Dr="http://www.w3.org/2000/svg",gr="http://www.w3.org/1999/xhtml";let zt=gr,lr=!1,ye=null;const we=xt({},[Cr,Dr,gr],nd);let se=xt({},["mi","mo","mn","ms","mtext"]),me=xt({},["annotation-xml"]);const le=xt({},["title","style","font","a","script"]);let be=null;const $e=["application/xhtml+xml","text/html"],re="text/html";let ae=null,K=null;const oe=r.createElement("form"),Y=function(Z){return Z instanceof RegExp||Z instanceof Function},De=function(){let Z=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(K&&K===Z)){if((!Z||typeof Z!="object")&&(Z={}),Z=Qa(Z),be=$e.indexOf(Z.PARSER_MEDIA_TYPE)===-1?re:Z.PARSER_MEDIA_TYPE,ae=be==="application/xhtml+xml"?nd:pl,P=Xn(Z,"ALLOWED_TAGS")?xt({},Z.ALLOWED_TAGS,ae):Ie,qe=Xn(Z,"ALLOWED_ATTR")?xt({},Z.ALLOWED_ATTR,ae):Ne,ye=Xn(Z,"ALLOWED_NAMESPACES")?xt({},Z.ALLOWED_NAMESPACES,nd):we,Pt=Xn(Z,"ADD_URI_SAFE_ATTR")?xt(Qa(cr),Z.ADD_URI_SAFE_ATTR,ae):cr,ct=Xn(Z,"ADD_DATA_URI_TAGS")?xt(Qa(Ft),Z.ADD_DATA_URI_TAGS,ae):Ft,It=Xn(Z,"FORBID_CONTENTS")?xt({},Z.FORBID_CONTENTS,ae):bt,Q=Xn(Z,"FORBID_TAGS")?xt({},Z.FORBID_TAGS,ae):{},kt=Xn(Z,"FORBID_ATTR")?xt({},Z.FORBID_ATTR,ae):{},Et=Xn(Z,"USE_PROFILES")?Z.USE_PROFILES:!1,Ce=Z.ALLOW_ARIA_ATTR!==!1,de=Z.ALLOW_DATA_ATTR!==!1,Rt=Z.ALLOW_UNKNOWN_PROTOCOLS||!1,Ue=Z.ALLOW_SELF_CLOSE_IN_ATTR!==!1,Dt=Z.SAFE_FOR_TEMPLATES||!1,mt=Z.SAFE_FOR_XML!==!1,ke=Z.WHOLE_DOCUMENT||!1,Oe=Z.RETURN_DOM||!1,Bt=Z.RETURN_DOM_FRAGMENT||!1,vt=Z.RETURN_TRUSTED_TYPE||!1,St=Z.FORCE_BODY||!1,qt=Z.SANITIZE_DOM!==!1,sr=Z.SANITIZE_NAMED_PROPS||!1,Tr=Z.KEEP_CONTENT!==!1,mr=Z.IN_PLACE||!1,he=Z.ALLOWED_URI_REGEXP||yT,zt=Z.NAMESPACE||gr,se=Z.MATHML_TEXT_INTEGRATION_POINTS||se,me=Z.HTML_INTEGRATION_POINTS||me,_e=Z.CUSTOM_ELEMENT_HANDLING||{},Z.CUSTOM_ELEMENT_HANDLING&&Y(Z.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(_e.tagNameCheck=Z.CUSTOM_ELEMENT_HANDLING.tagNameCheck),Z.CUSTOM_ELEMENT_HANDLING&&Y(Z.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(_e.attributeNameCheck=Z.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),Z.CUSTOM_ELEMENT_HANDLING&&typeof Z.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(_e.allowCustomizedBuiltInElements=Z.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),Dt&&(de=!1),Bt&&(Oe=!0),Et&&(P=xt({},ay),qe=[],Et.html===!0&&(xt(P,iy),xt(qe,sy)),Et.svg===!0&&(xt(P,id),xt(qe,od),xt(qe,ic)),Et.svgFilters===!0&&(xt(P,ad),xt(qe,od),xt(qe,ic)),Et.mathMl===!0&&(xt(P,sd),xt(qe,oy),xt(qe,ic))),Z.ADD_TAGS&&(P===Ie&&(P=Qa(P)),xt(P,Z.ADD_TAGS,ae)),Z.ADD_ATTR&&(qe===Ne&&(qe=Qa(qe)),xt(qe,Z.ADD_ATTR,ae)),Z.ADD_URI_SAFE_ATTR&&xt(Pt,Z.ADD_URI_SAFE_ATTR,ae),Z.FORBID_CONTENTS&&(It===bt&&(It=Qa(It)),xt(It,Z.FORBID_CONTENTS,ae)),Tr&&(P["#text"]=!0),ke&&xt(P,["html","head","body"]),P.table&&(xt(P,["tbody"]),delete Q.tbody),Z.TRUSTED_TYPES_POLICY){if(typeof Z.TRUSTED_TYPES_POLICY.createHTML!="function")throw Io('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof Z.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Io('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');j=Z.TRUSTED_TYPES_POLICY,X=j.createHTML("")}else j===void 0&&(j=mO(m,i)),j!==null&&typeof X=="string"&&(X=j.createHTML(""));tn&&tn(Z),K=Z}},Re=xt({},[...id,...ad,...aO]),Je=xt({},[...sd,...sO]),Ge=function(Z){let xe=N(Z);(!xe||!xe.tagName)&&(xe={namespaceURI:zt,tagName:"template"});const Ye=pl(Z.tagName),Mt=pl(xe.tagName);return ye[Z.namespaceURI]?Z.namespaceURI===Dr?xe.namespaceURI===gr?Ye==="svg":xe.namespaceURI===Cr?Ye==="svg"&&(Mt==="annotation-xml"||se[Mt]):!!Re[Ye]:Z.namespaceURI===Cr?xe.namespaceURI===gr?Ye==="math":xe.namespaceURI===Dr?Ye==="math"&&me[Mt]:!!Je[Ye]:Z.namespaceURI===gr?xe.namespaceURI===Dr&&!me[Mt]||xe.namespaceURI===Cr&&!se[Mt]?!1:!Je[Ye]&&(le[Ye]||!Re[Ye]):!!(be==="application/xhtml+xml"&&ye[Z.namespaceURI]):!1},He=function(Z){Ro(t.removed,{element:Z});try{N(Z).removeChild(Z)}catch{I(Z)}},et=function(Z,xe){try{Ro(t.removed,{attribute:xe.getAttributeNode(Z),from:xe})}catch{Ro(t.removed,{attribute:null,from:xe})}if(xe.removeAttribute(Z),Z==="is")if(Oe||Bt)try{He(xe)}catch{}else try{xe.setAttribute(Z,"")}catch{}},nt=function(Z){let xe=null,Ye=null;if(St)Z="<remove></remove>"+Z;else{const Ot=ny(Z,/^[\r\n\t ]+/);Ye=Ot&&Ot[0]}be==="application/xhtml+xml"&&zt===gr&&(Z='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+Z+"</body></html>");const Mt=j?j.createHTML(Z):Z;if(zt===gr)try{xe=new v().parseFromString(Mt,be)}catch{}if(!xe||!xe.documentElement){xe=J.createDocument(zt,"template",null);try{xe.documentElement.innerHTML=lr?X:Mt}catch{}}const nr=xe.body||xe.documentElement;return Z&&Ye&&nr.insertBefore(r.createTextNode(Ye),nr.childNodes[0]||null),zt===gr?te.call(xe,ke?"html":"body")[0]:ke?xe.documentElement:nr},Qe=function(Z){return V.call(Z.ownerDocument||Z,Z,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},tt=function(Z){return Z instanceof p&&(typeof Z.nodeName!="string"||typeof Z.textContent!="string"||typeof Z.removeChild!="function"||!(Z.attributes instanceof l)||typeof Z.removeAttribute!="function"||typeof Z.setAttribute!="function"||typeof Z.namespaceURI!="string"||typeof Z.insertBefore!="function"||typeof Z.hasChildNodes!="function")},at=function(Z){return typeof o=="function"&&Z instanceof o};function st(it,Z,xe){nc(it,Ye=>{Ye.call(t,Z,xe,K)})}const yr=function(Z){let xe=null;if(st(ee.beforeSanitizeElements,Z,null),tt(Z))return He(Z),!0;const Ye=ae(Z.nodeName);if(st(ee.uponSanitizeElement,Z,{tagName:Ye,allowedTags:P}),Z.hasChildNodes()&&!at(Z.firstElementChild)&&Xr(/<[/\w]/g,Z.innerHTML)&&Xr(/<[/\w]/g,Z.textContent)||Z.nodeType===Ao.progressingInstruction||mt&&Z.nodeType===Ao.comment&&Xr(/<[/\w]/g,Z.data))return He(Z),!0;if(!P[Ye]||Q[Ye]){if(!Q[Ye]&&dt(Ye)&&(_e.tagNameCheck instanceof RegExp&&Xr(_e.tagNameCheck,Ye)||_e.tagNameCheck instanceof Function&&_e.tagNameCheck(Ye)))return!1;if(Tr&&!It[Ye]){const Mt=N(Z)||Z.parentNode,nr=x(Z)||Z.childNodes;if(nr&&Mt){const Ot=nr.length;for(let ir=Ot-1;ir>=0;--ir){const Pr=T(nr[ir],!0);Pr.__removalCount=(Z.__removalCount||0)+1,Mt.insertBefore(Pr,R(Z))}}}return He(Z),!0}return Z instanceof u&&!Ge(Z)||(Ye==="noscript"||Ye==="noembed"||Ye==="noframes")&&Xr(/<\/no(script|embed|frames)/i,Z.innerHTML)?(He(Z),!0):(Dt&&Z.nodeType===Ao.text&&(xe=Z.textContent,nc([ge,L,pe],Mt=>{xe=$o(xe,Mt," ")}),Z.textContent!==xe&&(Ro(t.removed,{element:Z.cloneNode()}),Z.textContent=xe)),st(ee.afterSanitizeElements,Z,null),!1)},fr=function(Z,xe,Ye){if(qt&&(xe==="id"||xe==="name")&&(Ye in r||Ye in oe))return!1;if(!(de&&!kt[xe]&&Xr(Te,xe))){if(!(Ce&&Xr(rt,xe))){if(!qe[xe]||kt[xe]){if(!(dt(Z)&&(_e.tagNameCheck instanceof RegExp&&Xr(_e.tagNameCheck,Z)||_e.tagNameCheck instanceof Function&&_e.tagNameCheck(Z))&&(_e.attributeNameCheck instanceof RegExp&&Xr(_e.attributeNameCheck,xe)||_e.attributeNameCheck instanceof Function&&_e.attributeNameCheck(xe))||xe==="is"&&_e.allowCustomizedBuiltInElements&&(_e.tagNameCheck instanceof RegExp&&Xr(_e.tagNameCheck,Ye)||_e.tagNameCheck instanceof Function&&_e.tagNameCheck(Ye))))return!1}else if(!Pt[xe]){if(!Xr(he,$o(Ye,Se,""))){if(!((xe==="src"||xe==="xlink:href"||xe==="href")&&Z!=="script"&&tO(Ye,"data:")===0&&ct[Z])){if(!(Rt&&!Xr(Ke,$o(Ye,Se,"")))){if(Ye)return!1}}}}}}return!0},dt=function(Z){return Z!=="annotation-xml"&&ny(Z,ce)},Wr=function(Z){st(ee.beforeSanitizeAttributes,Z,null);const{attributes:xe}=Z;if(!xe||tt(Z))return;const Ye={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:qe,forceKeepAttr:void 0};let Mt=xe.length;for(;Mt--;){const nr=xe[Mt],{name:Ot,namespaceURI:ir,value:Pr}=nr,Mr=ae(Ot);let dr=Ot==="value"?Pr:rO(Pr);if(Ye.attrName=Mr,Ye.attrValue=dr,Ye.keepAttr=!0,Ye.forceKeepAttr=void 0,st(ee.uponSanitizeAttribute,Z,Ye),dr=Ye.attrValue,sr&&(Mr==="id"||Mr==="name")&&(et(Ot,Z),dr=ze+dr),mt&&Xr(/((--!?|])>)|<\/(style|title)/i,dr)){et(Ot,Z);continue}if(Ye.forceKeepAttr||(et(Ot,Z),!Ye.keepAttr))continue;if(!Ue&&Xr(/\/>/i,dr)){et(Ot,Z);continue}Dt&&nc([ge,L,pe],Gr=>{dr=$o(dr,Gr," ")});const $n=ae(Z.nodeName);if(fr($n,Mr,dr)){if(j&&typeof m=="object"&&typeof m.getAttributeType=="function"&&!ir)switch(m.getAttributeType($n,Mr)){case"TrustedHTML":{dr=j.createHTML(dr);break}case"TrustedScriptURL":{dr=j.createScriptURL(dr);break}}try{ir?Z.setAttributeNS(ir,Ot,dr):Z.setAttribute(Ot,dr),tt(Z)?He(Z):ry(t.removed)}catch{}}}st(ee.afterSanitizeAttributes,Z,null)},cn=function it(Z){let xe=null;const Ye=Qe(Z);for(st(ee.beforeSanitizeShadowDOM,Z,null);xe=Ye.nextNode();)st(ee.uponSanitizeShadowNode,xe,null),yr(xe),Wr(xe),xe.content instanceof a&&it(xe.content);st(ee.afterSanitizeShadowDOM,Z,null)};return t.sanitize=function(it){let Z=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},xe=null,Ye=null,Mt=null,nr=null;if(lr=!it,lr&&(it="<!-->"),typeof it!="string"&&!at(it))if(typeof it.toString=="function"){if(it=it.toString(),typeof it!="string")throw Io("dirty is not a string, aborting")}else throw Io("toString is not a function");if(!t.isSupported)return it;if(ft||De(Z),t.removed=[],typeof it=="string"&&(mr=!1),mr){if(it.nodeName){const Pr=ae(it.nodeName);if(!P[Pr]||Q[Pr])throw Io("root node is forbidden and cannot be sanitized in-place")}}else if(it instanceof o)xe=nt("<!---->"),Ye=xe.ownerDocument.importNode(it,!0),Ye.nodeType===Ao.element&&Ye.nodeName==="BODY"||Ye.nodeName==="HTML"?xe=Ye:xe.appendChild(Ye);else{if(!Oe&&!Dt&&!ke&&it.indexOf("<")===-1)return j&&vt?j.createHTML(it):it;if(xe=nt(it),!xe)return Oe?null:vt?X:""}xe&&St&&He(xe.firstChild);const Ot=Qe(mr?it:xe);for(;Mt=Ot.nextNode();)yr(Mt),Wr(Mt),Mt.content instanceof a&&cn(Mt.content);if(mr)return it;if(Oe){if(Bt)for(nr=D.call(xe.ownerDocument);xe.firstChild;)nr.appendChild(xe.firstChild);else nr=xe;return(qe.shadowroot||qe.shadowrootmode)&&(nr=ue.call(n,nr,!0)),nr}let ir=ke?xe.outerHTML:xe.innerHTML;return ke&&P["!doctype"]&&xe.ownerDocument&&xe.ownerDocument.doctype&&xe.ownerDocument.doctype.name&&Xr(bT,xe.ownerDocument.doctype.name)&&(ir="<!DOCTYPE "+xe.ownerDocument.doctype.name+`>
2
- `+ir),Dt&&nc([ge,L,pe],Pr=>{ir=$o(ir,Pr," ")}),j&&vt?j.createHTML(ir):ir},t.setConfig=function(){let it=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};De(it),ft=!0},t.clearConfig=function(){K=null,ft=!1},t.isValidAttribute=function(it,Z,xe){K||De({});const Ye=ae(it),Mt=ae(Z);return fr(Ye,Mt,xe)},t.addHook=function(it,Z){typeof Z=="function"&&Ro(ee[it],Z)},t.removeHook=function(it,Z){if(Z!==void 0){const xe=ZI(ee[it],Z);return xe===-1?void 0:eO(ee[it],xe,1)[0]}return ry(ee[it])},t.removeHooks=function(it){ee[it]=[]},t.removeAllHooks=function(){ee=cy()},t}var gO=_T();const yO={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},bO="javascript:";function _O(e){return(e==null?void 0:e.constructor)===Object}async function ly(e,t=3){let r=0,n;for(;r<=t;){r+=1;try{return await e()}catch(i){n=i,console.error(i),await wT(1e3*Math.pow(2,r))}}throw n}function wT(e){return new Promise(t=>{setTimeout(()=>{t(0)},e)})}function wO(){return Math.random().toString(36).slice(2)}const SO=new TextDecoder,TO=e=>{const t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return SO.decode(r)},CO=e=>e.length===0,EO=(...e)=>e.every(CO),ST=e=>{const t=gO.sanitize(e,yO);return t.includes(bO)?(console.warn("Suspicious content detected and removed."),""):t},fy=[];class $a{constructor(t){ht(this,"channel");this.channel=t}static addHandler(t){fy.push(t)}debug(...t){this._log("debug",...t)}info(...t){this._log("info",...t)}warn(...t){this._log("warn",...t)}error(...t){this._log("error",...t)}_log(t,...r){fy.forEach(n=>{n(this.channel,t,...r)})}}const kO=(e,t,...r)=>{console[t](`[${t}][${e}]`,...r)},RO=e=>{let t=[],r;return(i,a,...s)=>{a==="debug"||i==="communicator"||(t.push($O(i,a,...s)),clearTimeout(r),r=window.setTimeout(()=>{if(t.length){const o={num_of_logs:t.length,logs:t};e(o)}t=[]},2e3))}};function $O(e,t,...r){let n=r.pop();typeof n=="string"&&(r.push(n),n={});const i=r.join(" "),a={loglevel:t,channel:e,timestamp:new Date().toISOString(),application:Br.application,version:Br.version,device:Br.deviceId,tenant:Br.tenant,company_id:Br.companyId,location_url:location.href,data:AO(n),message:Zv(i)};return Br.trackerId&&(a.tracker_id=Br.trackerId),a}const IO=["user","phone","phone_number","phoneNumber","email"],OO=[/(?: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];function Zv(e){return typeof e=="string"?OO.forEach(t=>{e=e.replace(t,"__MASKED__")}):e&&_O(e)&&(e={...e},Object.keys(e).forEach(t=>{IO.indexOf(t)!==-1?e[t]="__MASKED__":Zv(e[t])})),e}function AO(e){if(e.error){const t=e.error;return{error:{name:t.name,message:t.message,stack:t.stack}}}return Zv(e.data)}const ud=new $a("communicator");let dy=!1;class PO{constructor(t,r){ht(this,"events");ht(this,"options");ht(this,"channel");ht(this,"authenticate");ht(this,"channelReady",!1);ht(this,"__authed",!1);ht(this,"pending",[]);ht(this,"promises",{});ht(this,"user");ht(this,"iframe");this.authenticate=t.authenticate,this.events=r,this.options=MO(t),this.channel=new MessageChannel,this.useConnect(this.options)}useConnect(t){const r=document.createElement("iframe");r.src=t.bridge,r.setAttribute("style","display:none");let n="*";/^https:/.test(t.bridge)&&(n=new URL(t.bridge).origin),r.addEventListener("load",()=>{if(ud.debug("iframe bridge ready for",n),!this.channelReady){const i={type:"_init",data:t};r.contentWindow.postMessage(i,n,[this.channel.port2])}}),this.channel.port1.onmessage=i=>{this.receiveMessage(i)},document.body.appendChild(r),this.iframe=r}receiveMessage(t){const r=t.data;if(r){if(ud.debug("receiveMessage",r),r.type==="ready")this.channelReady=!0,Br.deviceId=r.result.deviceId,Br.deviceId||console.error("Device Id has not been provided. SDK will not work properly."),this.runPending(),this.events.triggerEvent("ready");else if(r.type==="callback"&&r.callbackId){const[n,i]=this.promises[r.callbackId];r.error?i(r.error):n(r.result),delete this.promises[r.callbackId]}else if(r.type==="refreshToken")this.refreshToken();else if(r.request==="_auth"&&(this.events.triggerEvent("authenticated"),r.result&&r.result.log_proxy_url&&!dy)){dy=!0;const n=RO(i=>{this.postMessage({type:"_log",data:i})});$a.addHandler(n)}}}postMessage(t){this.channel&&this.channelReady?(ud.debug("postMessage",t),this.channel.port1.postMessage(t)):this.pending.push(t)}runPending(){for(;this.pending.length;){const t=this.pending.shift();this.postMessage(t)}}postPromise(t,r){return new Promise((n,i)=>{const a=wO()+"_"+Date.now();this.promises[a]=[n,i];const s={type:t,callbackId:a,data:r};this.postMessage(s)})}async refreshToken(){this.__authed=!0;const t=await this.authenticate(),r=["twilio_chat","nexmo_chat"];this.options.cobrowse&&r.push("cobrowse");const i={type:"_auth",data:{modules:r,user:{token:t.token,company_id:this.options.companyId}}};this.postMessage(i);const a=JSON.parse(TO(t.token.split(".")[1]));if(this.user={identifier:a.identifier,name:a.name,email:a.email},this.events.triggerEvent("authenticate"),a.exp){let s;a.exp.toString().length===13?s=a.exp:a.exp.toString().length===10&&(s=a.exp*1e3),s&&setTimeout(()=>{this.refreshToken()},s-Date.now()-12e4)}}request(t,r){!this.__authed&&t!=="proactive_chat_triggers"&&this.refreshToken();const n={url:t,options:r};return this.postPromise("request",n)}destroy(){delete this.channel,this.iframe&&(document.body.removeChild(this.iframe),this.iframe=void 0)}}function MO(e){var a;let t=e.host;t||(e.tenant?t=ey.replace("main.api",e.tenant+".api"):t=ey);const r=e.lang||"en",n=!!((a=e.cobrowse)!=null&&a.enabled),i=e.bridge||"https://websdk.ujet.co/v3/bridge.html";return{host:t,lang:r,cobrowse:n,companyId:e.companyId,location:location.href,version:e.version||"3.37.4",bridge:i}}class em{constructor(){ht(this,"handlers",{})}addEventListener(t,r){this.handlers[t]||(this.handlers[t]=[]),this.handlers[t].push(r)}triggerEvent(t,r){const n=this.handlers[t];n&&n.forEach(i=>{i(r)})}removeEventListener(t,r){if(this.handlers[t]){const n=this.handlers[t].indexOf(r);n!==-1&&this.handlers[t].splice(n,1)}}destroy(){this.handlers={}}}function xO(e,t){const r={};return t.forEach(n=>{r[n.id]=n}),e.map(n=>{if(n.type==="server_message"){const i=n.message_id,a=r[i];TT(n,a.content)}return n})}function NO(e,t){return TT(e,t.content)}function TT(e,t){return Object.keys(t).forEach(r=>{e[r]=t[r]}),e}const py={photo:2,video:2,audio:1,document:1};function LO(e){const t=e.toSorted((r,n)=>!r.groupMessageId||!n.groupMessageId||r.groupMessageId!==n.groupMessageId?0:(py[n.type]||0)-(py[r.type]||0));return t.forEach((r,n,i)=>{const a=!r.groupMessageId,s=i[n+1];s&&(a&&s.$userId===r.$userId&&r.$time||!a&&s.groupMessageId===r.groupMessageId&&r.$time)&&(s.$time=r.$time,r.$time=null)}),t}const hy=new $a("MediaStore"),DO=window.indexedDB||window.webkitIndexedDB||window.mozIndexedDB||window.OIndexedDB||window.msIndexedDB,jO="chat-media",vy=1,Ol="file";class CT{constructor(){ht(this,"db")}store(){return new Promise((t,r)=>{if(this.db)return t(my(this.db));const n=DO.open(jO,vy);n.onerror=()=>{r(new Error("indexedDB open failed"))},n.onsuccess=()=>{const i=n.result;this.db=i,t(my(i))},n.onupgradeneeded=i=>{const a=n.result;i.oldVersion>0&&i.oldVersion<vy&&(hy.info("deprecating media store"),a.deleteObjectStore(Ol)),hy.info("creating media store"),a.createObjectStore(Ol)}})}async save(t,r){(await this.store()).put({index:t,file:r},t)}async getAll(){const t=await this.store();return await new Promise((r,n)=>{const i=t.getAll();i.onerror=()=>{n(new Error("indexedDB getAll failed"))},i.onsuccess=()=>{r(i.result)}})}async getAllFiles(){const t={};return(await this.getAll()).forEach(n=>{t[n.index]=n.file}),t}async clear(){(await this.store()).clear()}}function my(e){return e.transaction(Ol,"readwrite").objectStore(Ol)}class FO{constructor(){ht(this,"_hostPath","")}setPath(t){this._hostPath=t}getPath(){return this._hostPath}}const ET=new FO,UO=new $a("chat-provider");class tm{constructor(t,r,n){ht(this,"audio");ht(this,"issueChatToken");ht(this,"identity");ht(this,"channelId");ht(this,"region");ht(this,"inTask",!1);ht(this,"muted",!1);ht(this,"events");this.events=t,this.region=r.region,this.issueChatToken=n}ping(){if(!this.muted){if(!this.audio){ET.getPath();const t="https://websdk.ujet.co/v3/ping.mp3";this.audio=new window.Audio(t)}try{this.audio.play()}catch(t){UO.warn("Chat audio play failed",{error:t})}}}on(t,r){this.events.addEventListener(t,r)}off(t,r){this.events.removeEventListener(t,r)}trackInTask(t){t.type==="noti"&&t.event==="taskVaStarted"?this.inTask=!0:t.type==="noti"&&t.event==="taskVaFinished"&&(this.inTask=!1)}}ht(tm,"type","base");const kT={};function rm(e){kT[e.type]=e}function BO(e){return kT[e]}const RT=["assigned","va_assigned"],$T=["dismissed","va_dismissed"],qO=["va_assigned","va_dismissed"],zO=["queued",...RT,...$T],WO=["timeout","canceled","failed","finished"],cd=new $a("Chat");class GO{constructor(t,r){ht(this,"provider");ht(this,"store");ht(this,"globalEvents");ht(this,"state");ht(this,"connected",!1);ht(this,"allowSkipVirtualAgent",!1);ht(this,"inEscalation",!1);ht(this,"events");ht(this,"cachedFiles");this.state=t,this.store=new CT,this.cachedFiles={},this.events=new em;const n=BO(this.state.provider_type);this.provider=new n(this.events,t,r)}_setGlobalEvents(t,r){this.globalEvents=t,this.on("message",n=>{if(n.content=ST(n.content),n.type==="server_message"){const i=n.message_id;r(this.id,i).then(a=>{n=NO(n,a),t.triggerEvent("chat.message",n)})}else n.type==="photo"||n.type==="video"?setTimeout(()=>{const i=n.$index.toString();n.file=this.cachedFiles[i],t.triggerEvent("chat.message",n)},100):(t.triggerEvent("chat.message",n),this.registerMessageEvents(n))}),this.on("memberJoined",n=>{t.triggerEvent("chat.memberJoined",n)}),this.on("memberLeft",n=>{t.triggerEvent("chat.memberLeft",n)}),this.on("typingStarted",n=>{t.triggerEvent("chat.typingStarted",n)}),this.on("typingEnded",n=>{t.triggerEvent("chat.typingEnded",n)})}get id(){var t;return((t=this.state)==null?void 0:t.id)||-1}get menuId(){return this.state?this.state.menus[this.state.menus.length-1].id:-1}get channelId(){var t;return((t=this.state)==null?void 0:t.provider_channel_id)||""}get lang(){var t;return((t=this.state)==null?void 0:t.lang)||""}get virtual(){return qO.indexOf(this.status)!==-1}get muted(){var t;return((t=this.provider)==null?void 0:t.muted)||!1}set muted(t){this.provider&&(this.provider.muted=t)}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 t,r;return{virtual:((t=this.state)==null?void 0:t.all_virtual_agents)||[],human:((r=this.state)==null?void 0:r.all_agents)||[]}}get userIdentity(){var t;return((t=this.provider)==null?void 0:t.identity)||""}get status(){var t;return((t=this.state)==null?void 0:t.status)||""}get postSessionStatus(){var t;return((t=this.state)==null?void 0:t.post_session_transfer_status)||""}get statusText(){var t;return((t=this.state)==null?void 0:t.status_text)||""}get cobrowsable(){return this.state?this.state.features.indexOf("cobrowse")!==-1:!1}get ongoing(){return zO.indexOf(this.status)!=-1}get assigned(){return RT.indexOf(this.status)!=-1}get dismissed(){return $T.indexOf(this.status)!=-1}get ended(){return WO.indexOf(this.status)!=-1}get transcriptCount(){var t;return((t=this.state)==null?void 0:t.transcript_requested_count)||0}get createdAt(){var t;return((t=this.state)==null?void 0:t.created_at)||""}get inTask(){var t;return((t=this.provider)==null?void 0:t.inTask)||!1}get feedbackType(){var t;return this.state?this.state.survey_enabled?"survey":(t=this.state.csat_settings)!=null&&t.enabled?"rate":"none":"none"}get optInRequired(){var t;return((t=this.state)==null?void 0:t.post_session_opt_in_required)||!1}get postSessionRequired(){var t;return((t=this.state)==null?void 0:t.post_session_required)||!1}get postSessionInProgress(){return this.state?this.state.post_session_transfer_status===to.IN_PROGRESS:!1}update(t){if(!this.state||this.state.id!==t.id)return;const r=t.menus[t.menus.length-1].id,n=this.state.menus[this.state.menus.length-1].id;this.state=t,r!==n&&this.triggerEvent("_menuChanged",this),t.status==="canceled"?this.triggerEvent("ended",this):this.triggerEvent("updated",this)}on(t,r){this.events.addEventListener(t,r)}off(t,r){this.events.removeEventListener(t,r)}async connect(){if(!this.provider)return cd.info("connecting interrupted"),!1;try{await ly(()=>this.provider.create(),3),await ly(()=>this.provider.join(this.state.provider_channel_id),3),this.connected=!0;const t=await this.fetchMessages(),r={chat:this,messages:t};return this.triggerEvent("connectedMessages",r),this.triggerEvent("connected",this),this.registerProviderEvents(),cd.info("connected with provider",this.state.provider_type),!0}catch{return!1}}async disconnect(){this.connected=!1,this.triggerEvent("disconnected",this),this.events.destroy(),this.provider&&(await this.provider.destroy(),cd.info("disconnect with provider",this.state.provider_type))}async sendMessage(t,r){const n=await this.provider.sendMessage(t);return r&&this.saveMedia(n,r),n}preview(t){if(!this.inTask)return this.provider.preview(t)}async fetchMessages(){if(this.connected){const t=await this.store.getAllFiles();return this.provider.fetchMessages(t)}else throw new Error("Please fetchMessages after chat connected.")}startTyping(){return this.provider.startTyping()}stopTyping(){return this.provider.stopTyping()}saveMedia(t,r){this.cachedFiles[t.toString()]=r,this.store.save(t,r)}async destroy(){await this.clearMediaStore(),this.connected&&await this.disconnect(),this.provider&&(this.triggerEvent("destroyed"),this.provider=null),this.events.destroy(),this.state=null}async clearMediaStore(){await this.store.clear()}_handleChatEndedEvent(t){this.disconnect(),this.state&&(t.timeout?(this.state.status="timeout",this.triggerEvent("timeout",this)):(this.state.status="finished",this.triggerEvent("ended",this)))}triggerEvent(t,r){this.events.triggerEvent(t,r),this.globalEvents&&this.globalEvents.triggerEvent("chat."+t,r)}registerProviderEvents(){this.provider&&this.provider.registerConversationEvents()}registerMessageEvents(t){t.event==="cobrowseRequestedFromAgent"?this.events.triggerEvent("_requestCobrowse","agent"):t.event==="cobrowseRequestedFromEndUser"?this.events.triggerEvent("_requestCobrowse","end_user"):t.event==="chatDismissed"&&this.state?(this.state.status="dismissed",this.triggerEvent("dismissed",this)):t.event==="chatEnded"?this.events.triggerEvent("_chatEnded",t):t.event==="escalationStarted"?this.inEscalation=!0:(t.event==="escalationFailed"||t.event==="escalationAccepted")&&(this.inEscalation=!1)}}function IT(e){return e.map(HO).filter(t=>t.enabled)}function HO(e){const t={id:e.id,enabled:!0,channels:[],hidden:!!e.hidden};if(!e.name||!e.name.trim())return t.enabled=!1,t;t.name=e.name.trim();const r=VO(e);if(r&&(t.redirection=e.redirection),e.children&&e.children.length){const n=IT(e.children);return t.enabled=n.length>0||r,t.children=n,t}if(!e.channels)t.enabled=r;else{const{channels:n,deflection:i}=KO(e.channels);t.deflection=i,r||(t.channels=n),t.enabled=n.length>0||r}return t}function VO(e){let t=!1;const r=e.redirection;return r&&(r.option==="message"||r.option==="url")&&(t=!!r.data),t}function KO(e){let t=null;const r=[],n=e.chat,i=a=>{!a.deflection_type&&a.deflected_reason&&(a.deflection_type=a.deflected_reason),a.deflected===void 0&&a.deflection_type&&(a.deflected=!0),r.push(a)};return n&&n.deflected&&(t={enabled:!0,type:n.deflected_reason}),n&&(n.enabled||n.virtual_agent_available)&&i({...e.chat,type:"chat"}),e.voice_call&&e.voice_call.instant_enabled&&i({...e.voice_call,type:"instant_call"}),e.voice_call&&e.voice_call.schedule_enabled&&i({...e.voice_call,type:"scheduled_call",deflection_type:e.voice_call.schedule_deflection_type}),e.email&&e.email.enabled&&i({...e.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}),e.external_deflection_link&&e.external_deflection_link.enabled&&e.external_deflection_link.links.forEach(s=>{s.enabled&&i({...s,type:"external_link"})}),{channels:r,deflection:t}}const JO={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 YO(e){var r,n;return{languages:e.languages.filter(i=>i.enabled).map(i=>({lang:i.lang,name:i.name,localeName:JO[i.lang]})),name:e.display_name,subdomain:e.subdomain,support_email:e.support_email,action_tracking:e.action_tracking_enabled,email_transcripts:e.chat_settings.email_transcripts,message_preview:e.chat_settings.message_preview,email_enhancement:e.email_enhancement_enabled,display_history:((r=e.chat_settings.display_history)==null?void 0:r.enabled)&&((n=e.chat_settings.display_history)==null?void 0:n.to_end_user),use_recording:e.use_recording,use_web:e.use_web,cobrowse_domain:e.cobrowse_domain}}function gy(e){return e.chats=e.chats.map(t=>{const r=t.entries.map((n,i)=>XO(n,`${t.comm_id}-${i}`));return t.entries=LO(r),t}),e}function XO(e,t){var r;return{$index:e.timestamp,$sid:t,$timestamp:new Date(e.timestamp),$userType:e.role,$userId:((r=e.user_data)==null?void 0:r.id)||0,user:e.user_data,type:e.type,...e.body}}const yy=/Chrome/.test(navigator.userAgent);class QO{constructor(t){ht(this,"request");this.request=t}get(t,r){if(r){const n=[];Object.keys(r).forEach(i=>{const a=r[i];a!==void 0&&n.push(`${encodeURIComponent(i)}=${encodeURIComponent(a)}`)}),t+="?"+n.join("&")}return this.request(t,{method:"GET"})}post(t,r){const n={method:"POST"};return n.body=JSON.stringify(r),this.request(t,n)}patch(t,r){const n={method:"PATCH"};return n.body=JSON.stringify(r),this.request(t,n)}put(t,r){const n={method:"PUT"};return n.body=JSON.stringify(r),this.request(t,n)}async getTriggers(t){const r={"UJET-Company-Id":t};return(await this.request("proactive_chat_triggers",{method:"GET",headers:r})).data}trackClientEvents(t){return this.post("/client_events",{events:t})}async getCompany(){const t=await this.get("company");return YO(t.data)}async getMenus(t,r){const n={type:"web_menu",lang:t,direct_access_key:r},i=await this.get("menus",n),a={key:!!r,user:!1},s=i.headers["ujet-direct-access"];return s&&s!="false"&&(a.user=!0),{menus:IT(i.data),direct:a}}async getAfterHourMessage(t){return(await this.get(`audible_messages/${t}`)).data["after_hours.message"].text}async getTimeSlots(t,r="en"){return(await this.get(`menus/${t}/time_slots`,{type:"web_menu",lang:r})).data}async getWaitTimes(t,r="en"){return(await this.get(`menus/${t}/wait_times`,{type:"web_menu",lang:r})).data}async verifyForm(t){try{return await this.post("forms/verify",t),!0}catch{return!1}}async finishChat(t){return(await this.patch(`chats/${t}`,{status:"finished"})).data}async updatePostSession(t,r){const n={post_session_transfer_status:r};try{return(await this.patch(`chats/${t}`,n)).data}catch(i){if(r===to.IN_PROGRESS&&i.status===400)return(await this.patch(`chats/${t}`,n)).data;throw i}}async getChatDeflection(t){const{data:r}=await this.get(`chats/${t}/deflections`);return r&&r.enabled?r:null}sendChatCustomData(t,r){let n;return typeof r=="string"?n={signed:!0,signed_data:r}:n={signed:!1,data:r},this.post(`chats/${t}/custom_data`,n)}async downloadChatTranscript(t){return(await this.post(`chats/${t}/generate_transcript_pdf`,{})).data}async getPdfStatus(t){return await this.get(`chat_transcript_pdfs/${t}/download_transcript`)}sendChatTranscripts(t,r){return this.post(`chats/${t}/transcripts`,{emails:r.join(",")})}async listChatTaskMessages(t){return(await this.get(`chats/${t}/task_va_messages`)).data}async getChatTaskMessage(t,r){return(await this.get(`chats/${t}/task_va_messages/${r}`)).data}async sendChatTaskMessage(t,r){const n={content:{content:r,type:"text"}};return(await this.post(`chats/${t}/task_va_messages`,n)).data}async sendChatTextMessage(t,r){const n={message:{content:r,timestamp:new Date().toISOString()}};await this.post(`chats/${t}/messages`,n)}async sendPreviewMessage(t,r,n){const i={message:{content:r,timestamp:n}},{data:a}=await this.post(`chats/${t}/redact_messages`,i);return a}escalateChat(t,r){return this.post(`chats/${t}/escalations`,r)}trackEscalation(t,r,n){return this.put(`chats/${t}/escalations/${r}`,{escalation_id:r,deflection_channel:n})}requestChatCobrowse(t,r){return this.post(`chats/${t}/cobrowse`,r)}rateChat(t,r){return this.patch(`chats/${t}/rating`,r)}async getChatSurvey(t){return(await this.get(`chats/${t}/survey`)).data}sendChatSurvey(t,r){const n={chat_id:t,answers:r};return this.put(`chats/${t}/survey`,n)}trackChatEndUserEvent(t,r){return this.post(`chats/${t}/end_user_event`,r)}async createChat(t,r,n,i){const a={chat:{menu_id:t,lang:r,email:n.email,greeting:n.greeting,trigger_id:n.trigger_id,ticket_id:n==null?void 0:n.ticket_id,custom_data:n==null?void 0:n.custom_data},cobrowsable:n.cobrowsable},o=(await this.post("chats",a)).data;return this.wrapChat(o,i)}async loadChat(t,r){const n=await this.getChat(t);return this.wrapChat(n,r)}async resumeChat(t,r){const n=await this.patch(`chats/${t}`,{status:"queued"});return this.wrapChat(n.data,r)}async getChatHistory(t=1){if(t===1){const{data:r}=await this.get("/chats/histories?page=1&per_page=2");return gy(r)}else{const{data:r}=await this.get(`/chats/histories?page=${t}&per_page=1`);return gy(r)}}async uploadChatFile(t,r){let n="file";/^image/.test(r.type)?n="photo":/^video/.test(r.type)?n="video":n="file";const i=r.name.replace(/\.[^.]+$/i,""),a=await this.post(`chats/${t}/${n}s/upload`,{filename:i}),s={file:r,fields:a.data.fields};yy&&(s.file=await OT(r));const u=(await this.request(a.data.url,s)).data.key,l=(await this.post(`chats/${t}/${n}s`,{chat_id:t,[n]:{s3_path:u,photo_type:n}})).data;return l.type=n,l}async getChat(t){return(await this.get(`chats/${t}`)).data}async wrapChat(t,r){const n=async()=>(await this.post(`chats/${t.id}/tokens`,{provider_type:t.provider_type,device_id:r})).data,i=new GO(t,n),a=async s=>{if(i.status==="va_assigned"){const o=await this.getSkipVirtualAgentSettings(i.menuId,i.lang);i.allowSkipVirtualAgent=o,i.update(s)}};if(i.channelId)i.connect(),a(t);else{let s;for(;!s;)await this.getChat(i.id).then(o=>{o.provider_channel_id&&i.state?(s=!0,i.update(o),i.connect(),a(o)):(o.status==="canceled"||o.status==="finished")&&(s=!0)}),s||await wT(1500)}return i.on("initialized",async()=>{if(i.status==="queued"){const s=await this.getChat(i.id);i.update(s)}}),i.on("memberJoined",async()=>{const s=await this.getChat(i.id);i.update(s)}),i.on("memberLeft",async()=>{const s=await this.getChat(i.id);i.update(s)}),i.on("_chatEnded",async s=>{const o=await this.getChat(i.id);i.update(o),(!i.state||i.ended)&&i._handleChatEndedEvent(s)}),i.on("_menuChanged",async s=>{const o=await this.getChat(s.id);a(o)}),i}async createCall(t,r,n){const i={type:n.scheduled_at?"web_scheduled_call":"web_instant_call",menu_id:t,lang:r,email:n.email,ticket_id:n.ticket_id,recording_permission:n.recording_permission||"recording_permission_not_asked",scheduled_at:n.scheduled_at,custom_data:n.custom_data,end_user:{phone_number:n.phone_number}},s=(await this.post("calls",{call:i,cobrowsable:!1})).data;return s.menu_id=s.selected_menu.id,s}async fetchCall(t){const n=(await this.get(`calls/${t}`)).data;return n.menu_id=n.selected_menu.id,n}async cancelCall(t){const n=(await this.patch(`calls/${t}`,{status:"failed",fail_reason:"canceled"})).data;return n.menu_id=n.selected_menu.id,n}async listFileTypes(){return(await this.get("email_prohibited_file_types")).data}async createEmail(t,r,n){const i={end_user_email:n.email,email_body:n.content,menu_id:t.toString(),lang:r};return n.name&&(i.end_user_name=n.name),n.recaptcha&&(i.recaptcha_response=n.recaptcha),n.files&&yy?i["email_attachments[]"]=await ZO(n.files):n.files&&(i["email_attachments[]"]=[...n.files]),this.request("emails",{form:i})}async getMedia(t,r){const n=await this.get(`media/${t}?type=${r}`);if(!n.data)return null;const i=n.headers["x-file-name"];return new File([n.data],i,{type:n.data.type})}async getSkipVirtualAgentSettings(t,r){return(await this.get(`menus/${t}/virtual_agent_settings`,{lang:r})).data.allow_skip_virtual_agent}}function ZO(e){return Promise.all(e.map(OT))}function OT(e){return new Promise((t,r)=>{const n=new FileReader;n.onload=()=>{const i=[n.result],a={type:e.type,lastModified:e.lastModified};t({name:e.name,fileBits:i,options:a})},n.onerror=r,n.readAsArrayBuffer(e)})}const ld="ujet:",Kr={set(e,t){return localStorage.setItem(ld+e,t)},get(e){return localStorage.getItem(ld+e)},del(e){return localStorage.removeItem(ld+e)}},eA=Date.now(),AT={href:window.location.href,interval:24*60*60};function tA(e){if(!Array.isArray(e)||!e.length)return null;const t=sA(),r=t===0,n=t+1;return oA(n),e.filter(a=>{const s=nA(a,AT.href),o=iA(a.visitor_type,r),u=n>=a.page_visit_count,c=!aA(a.id);return s&&o&&u&&c}).sort((a,s)=>a.stay_time-s.stay_time)[0]||null}function rA(e,t){const r=e.stay_time*1e3,n=Math.max(r-(Date.now()-eA),0);setTimeout(()=>{t(e),Kr.set(`trigger:${e.id}`,(Date.now()/1e3).toString())},n)}const nA=(e,t)=>{const{keywords_included_or:r=[],keywords_excluded_or:n=[],keywords_included:i=[],keywords_excluded:a=[]}=e;if(EO(r,n,i,a))return!0;if(r.length||n.length){const u=r.some(l=>l.every(p=>t.includes(p))),c=n.length>0&&n.every(l=>l.every(p=>!t.includes(p)));return u||c}const s=i.filter(u=>t.indexOf(u)!==-1).length,o=a.filter(u=>t.indexOf(u)===-1).length;return!!s||!!o};function iA(e,t){return e==="visitor_type_new"?t:e==="visitor_type_returning"?!t:!0}function aA(e){try{const t=parseInt(Kr.get(`trigger:${e}`),10);return Date.now()/1e3-t<AT.interval}catch{return!1}}function sA(){try{const e=Kr.get("visits");return e?parseInt(e,10):0}catch{return 0}}function oA(e){try{Kr.set("visits",e.toString())}catch(t){console.error(t)}}/*!
1
+ "use strict";var HI=Object.defineProperty;var VI=(e,t,r)=>t in e?HI(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var ht=(e,t,r)=>VI(e,typeof t!="symbol"?t+"":t,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function KI(e,t){for(var r=0;r<t.length;r++){const n=t[r];if(typeof n!="string"&&!Array.isArray(n)){for(const i in n)if(i!=="default"&&!(i in e)){const a=Object.getOwnPropertyDescriptor(n,i);a&&Object.defineProperty(e,i,a.get?a:{enumerable:!0,get:()=>n[i]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}class JI{constructor(){ht(this,"_hostPath","")}setPath(t){this._hostPath=t}getPath(){return this._hostPath}}const mT=new JI,YI="prod",Qv="3.38.4",ey="https://main.api.ujet.co",qr={companyId:"",tenant:"",trackerId:"",deviceId:"",application:"websdk",version:Qv};/*! @license DOMPurify 3.2.4 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.2.4/LICENSE */const{entries:gT,setPrototypeOf:ty,isFrozen:XI,getPrototypeOf:QI,getOwnPropertyDescriptor:ZI}=Object;let{freeze:tn,seal:Fn,create:yT}=Object,{apply:hh,construct:vh}=typeof Reflect<"u"&&Reflect;tn||(tn=function(t){return t});Fn||(Fn=function(t){return t});hh||(hh=function(t,r,n){return t.apply(r,n)});vh||(vh=function(t,r){return new t(...r)});const nc=rn(Array.prototype.forEach),eO=rn(Array.prototype.lastIndexOf),ry=rn(Array.prototype.pop),Ro=rn(Array.prototype.push),tO=rn(Array.prototype.splice),pl=rn(String.prototype.toLowerCase),nd=rn(String.prototype.toString),ny=rn(String.prototype.match),$o=rn(String.prototype.replace),rO=rn(String.prototype.indexOf),nO=rn(String.prototype.trim),Xn=rn(Object.prototype.hasOwnProperty),Xr=rn(RegExp.prototype.test),Io=iO(TypeError);function rn(e){return function(t){for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];return hh(e,t,n)}}function iO(e){return function(){for(var t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];return vh(e,r)}}function xt(e,t){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:pl;ty&&ty(e,null);let n=t.length;for(;n--;){let i=t[n];if(typeof i=="string"){const a=r(i);a!==i&&(XI(t)||(t[n]=a),i=a)}e[i]=!0}return e}function aO(e){for(let t=0;t<e.length;t++)Xn(e,t)||(e[t]=null);return e}function Qa(e){const t=yT(null);for(const[r,n]of gT(e))Xn(e,r)&&(Array.isArray(n)?t[r]=aO(n):n&&typeof n=="object"&&n.constructor===Object?t[r]=Qa(n):t[r]=n);return t}function Oo(e,t){for(;e!==null;){const n=ZI(e,t);if(n){if(n.get)return rn(n.get);if(typeof n.value=="function")return rn(n.value)}e=QI(e)}function r(){return null}return r}const iy=tn(["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","section","select","shadow","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"]),id=tn(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","filter","font","g","glyph","glyphref","hkern","image","line","lineargradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),ad=tn(["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"]),sO=tn(["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"]),sd=tn(["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"]),oO=tn(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),ay=tn(["#text"]),sy=tn(["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","face","for","headers","height","hidden","high","href","hreflang","id","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","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),od=tn(["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","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"]),oy=tn(["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"]),ic=tn(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),uO=Fn(/\{\{[\w\W]*|[\w\W]*\}\}/gm),cO=Fn(/<%[\w\W]*|[\w\W]*%>/gm),lO=Fn(/\$\{[\w\W]*/gm),fO=Fn(/^data-[\-\w.\u00B7-\uFFFF]+$/),dO=Fn(/^aria-[\-\w]+$/),bT=Fn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),pO=Fn(/^(?:\w+script|data):/i),hO=Fn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),_T=Fn(/^html$/i),vO=Fn(/^[a-z][.\w]*(-[.\w]+)+$/i);var uy=Object.freeze({__proto__:null,ARIA_ATTR:dO,ATTR_WHITESPACE:hO,CUSTOM_ELEMENT:vO,DATA_ATTR:fO,DOCTYPE_NAME:_T,ERB_EXPR:cO,IS_ALLOWED_URI:bT,IS_SCRIPT_OR_DATA:pO,MUSTACHE_EXPR:uO,TMPLIT_EXPR:lO});const Ao={element:1,text:3,progressingInstruction:7,comment:8,document:9},mO=function(){return typeof window>"u"?null:window},gO=function(t,r){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let n=null;const i="data-tt-policy-suffix";r&&r.hasAttribute(i)&&(n=r.getAttribute(i));const a="dompurify"+(n?"#"+n:"");try{return t.createPolicy(a,{createHTML(s){return s},createScriptURL(s){return s}})}catch{return console.warn("TrustedTypes policy "+a+" could not be created."),null}},cy=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function wT(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:mO();const t=it=>wT(it);if(t.version="3.2.4",t.removed=[],!e||!e.document||e.document.nodeType!==Ao.document||!e.Element)return t.isSupported=!1,t;let{document:r}=e;const n=r,i=n.currentScript,{DocumentFragment:a,HTMLTemplateElement:s,Node:o,Element:u,NodeFilter:c,NamedNodeMap:l=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:p,DOMParser:v,trustedTypes:m}=e,b=u.prototype,T=Oo(b,"cloneNode"),I=Oo(b,"remove"),R=Oo(b,"nextSibling"),x=Oo(b,"childNodes"),N=Oo(b,"parentNode");if(typeof s=="function"){const it=r.createElement("template");it.content&&it.content.ownerDocument&&(r=it.content.ownerDocument)}let j,X="";const{implementation:J,createNodeIterator:V,createDocumentFragment:D,getElementsByTagName:te}=r,{importNode:ue}=n;let ee=cy();t.isSupported=typeof gT=="function"&&typeof N=="function"&&J&&J.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:ge,ERB_EXPR:L,TMPLIT_EXPR:pe,DATA_ATTR:Te,ARIA_ATTR:rt,IS_SCRIPT_OR_DATA:Ke,ATTR_WHITESPACE:Se,CUSTOM_ELEMENT:ce}=uy;let{IS_ALLOWED_URI:he}=uy,P=null;const Ie=xt({},[...iy,...id,...ad,...sd,...ay]);let qe=null;const Ne=xt({},[...sy,...od,...oy,...ic]);let _e=Object.seal(yT(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}})),Q=null,kt=null,Ce=!0,de=!0,Rt=!1,Ue=!0,Dt=!1,mt=!0,ke=!1,ft=!1,St=!1,Oe=!1,Bt=!1,vt=!1,qt=!0,sr=!1;const ze="user-content-";let Tr=!0,mr=!1,Et={},It=null;const bt=xt({},["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 ct=null;const Ft=xt({},["audio","video","img","source","image","track"]);let Pt=null;const cr=xt({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Cr="http://www.w3.org/1998/Math/MathML",Dr="http://www.w3.org/2000/svg",gr="http://www.w3.org/1999/xhtml";let zt=gr,lr=!1,ye=null;const we=xt({},[Cr,Dr,gr],nd);let se=xt({},["mi","mo","mn","ms","mtext"]),me=xt({},["annotation-xml"]);const le=xt({},["title","style","font","a","script"]);let be=null;const $e=["application/xhtml+xml","text/html"],re="text/html";let ae=null,K=null;const oe=r.createElement("form"),Y=function(Z){return Z instanceof RegExp||Z instanceof Function},De=function(){let Z=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(K&&K===Z)){if((!Z||typeof Z!="object")&&(Z={}),Z=Qa(Z),be=$e.indexOf(Z.PARSER_MEDIA_TYPE)===-1?re:Z.PARSER_MEDIA_TYPE,ae=be==="application/xhtml+xml"?nd:pl,P=Xn(Z,"ALLOWED_TAGS")?xt({},Z.ALLOWED_TAGS,ae):Ie,qe=Xn(Z,"ALLOWED_ATTR")?xt({},Z.ALLOWED_ATTR,ae):Ne,ye=Xn(Z,"ALLOWED_NAMESPACES")?xt({},Z.ALLOWED_NAMESPACES,nd):we,Pt=Xn(Z,"ADD_URI_SAFE_ATTR")?xt(Qa(cr),Z.ADD_URI_SAFE_ATTR,ae):cr,ct=Xn(Z,"ADD_DATA_URI_TAGS")?xt(Qa(Ft),Z.ADD_DATA_URI_TAGS,ae):Ft,It=Xn(Z,"FORBID_CONTENTS")?xt({},Z.FORBID_CONTENTS,ae):bt,Q=Xn(Z,"FORBID_TAGS")?xt({},Z.FORBID_TAGS,ae):{},kt=Xn(Z,"FORBID_ATTR")?xt({},Z.FORBID_ATTR,ae):{},Et=Xn(Z,"USE_PROFILES")?Z.USE_PROFILES:!1,Ce=Z.ALLOW_ARIA_ATTR!==!1,de=Z.ALLOW_DATA_ATTR!==!1,Rt=Z.ALLOW_UNKNOWN_PROTOCOLS||!1,Ue=Z.ALLOW_SELF_CLOSE_IN_ATTR!==!1,Dt=Z.SAFE_FOR_TEMPLATES||!1,mt=Z.SAFE_FOR_XML!==!1,ke=Z.WHOLE_DOCUMENT||!1,Oe=Z.RETURN_DOM||!1,Bt=Z.RETURN_DOM_FRAGMENT||!1,vt=Z.RETURN_TRUSTED_TYPE||!1,St=Z.FORCE_BODY||!1,qt=Z.SANITIZE_DOM!==!1,sr=Z.SANITIZE_NAMED_PROPS||!1,Tr=Z.KEEP_CONTENT!==!1,mr=Z.IN_PLACE||!1,he=Z.ALLOWED_URI_REGEXP||bT,zt=Z.NAMESPACE||gr,se=Z.MATHML_TEXT_INTEGRATION_POINTS||se,me=Z.HTML_INTEGRATION_POINTS||me,_e=Z.CUSTOM_ELEMENT_HANDLING||{},Z.CUSTOM_ELEMENT_HANDLING&&Y(Z.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(_e.tagNameCheck=Z.CUSTOM_ELEMENT_HANDLING.tagNameCheck),Z.CUSTOM_ELEMENT_HANDLING&&Y(Z.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(_e.attributeNameCheck=Z.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),Z.CUSTOM_ELEMENT_HANDLING&&typeof Z.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(_e.allowCustomizedBuiltInElements=Z.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),Dt&&(de=!1),Bt&&(Oe=!0),Et&&(P=xt({},ay),qe=[],Et.html===!0&&(xt(P,iy),xt(qe,sy)),Et.svg===!0&&(xt(P,id),xt(qe,od),xt(qe,ic)),Et.svgFilters===!0&&(xt(P,ad),xt(qe,od),xt(qe,ic)),Et.mathMl===!0&&(xt(P,sd),xt(qe,oy),xt(qe,ic))),Z.ADD_TAGS&&(P===Ie&&(P=Qa(P)),xt(P,Z.ADD_TAGS,ae)),Z.ADD_ATTR&&(qe===Ne&&(qe=Qa(qe)),xt(qe,Z.ADD_ATTR,ae)),Z.ADD_URI_SAFE_ATTR&&xt(Pt,Z.ADD_URI_SAFE_ATTR,ae),Z.FORBID_CONTENTS&&(It===bt&&(It=Qa(It)),xt(It,Z.FORBID_CONTENTS,ae)),Tr&&(P["#text"]=!0),ke&&xt(P,["html","head","body"]),P.table&&(xt(P,["tbody"]),delete Q.tbody),Z.TRUSTED_TYPES_POLICY){if(typeof Z.TRUSTED_TYPES_POLICY.createHTML!="function")throw Io('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof Z.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Io('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');j=Z.TRUSTED_TYPES_POLICY,X=j.createHTML("")}else j===void 0&&(j=gO(m,i)),j!==null&&typeof X=="string"&&(X=j.createHTML(""));tn&&tn(Z),K=Z}},Re=xt({},[...id,...ad,...sO]),Je=xt({},[...sd,...oO]),Ge=function(Z){let xe=N(Z);(!xe||!xe.tagName)&&(xe={namespaceURI:zt,tagName:"template"});const Ye=pl(Z.tagName),Mt=pl(xe.tagName);return ye[Z.namespaceURI]?Z.namespaceURI===Dr?xe.namespaceURI===gr?Ye==="svg":xe.namespaceURI===Cr?Ye==="svg"&&(Mt==="annotation-xml"||se[Mt]):!!Re[Ye]:Z.namespaceURI===Cr?xe.namespaceURI===gr?Ye==="math":xe.namespaceURI===Dr?Ye==="math"&&me[Mt]:!!Je[Ye]:Z.namespaceURI===gr?xe.namespaceURI===Dr&&!me[Mt]||xe.namespaceURI===Cr&&!se[Mt]?!1:!Je[Ye]&&(le[Ye]||!Re[Ye]):!!(be==="application/xhtml+xml"&&ye[Z.namespaceURI]):!1},He=function(Z){Ro(t.removed,{element:Z});try{N(Z).removeChild(Z)}catch{I(Z)}},et=function(Z,xe){try{Ro(t.removed,{attribute:xe.getAttributeNode(Z),from:xe})}catch{Ro(t.removed,{attribute:null,from:xe})}if(xe.removeAttribute(Z),Z==="is")if(Oe||Bt)try{He(xe)}catch{}else try{xe.setAttribute(Z,"")}catch{}},nt=function(Z){let xe=null,Ye=null;if(St)Z="<remove></remove>"+Z;else{const Ot=ny(Z,/^[\r\n\t ]+/);Ye=Ot&&Ot[0]}be==="application/xhtml+xml"&&zt===gr&&(Z='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+Z+"</body></html>");const Mt=j?j.createHTML(Z):Z;if(zt===gr)try{xe=new v().parseFromString(Mt,be)}catch{}if(!xe||!xe.documentElement){xe=J.createDocument(zt,"template",null);try{xe.documentElement.innerHTML=lr?X:Mt}catch{}}const nr=xe.body||xe.documentElement;return Z&&Ye&&nr.insertBefore(r.createTextNode(Ye),nr.childNodes[0]||null),zt===gr?te.call(xe,ke?"html":"body")[0]:ke?xe.documentElement:nr},Qe=function(Z){return V.call(Z.ownerDocument||Z,Z,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},tt=function(Z){return Z instanceof p&&(typeof Z.nodeName!="string"||typeof Z.textContent!="string"||typeof Z.removeChild!="function"||!(Z.attributes instanceof l)||typeof Z.removeAttribute!="function"||typeof Z.setAttribute!="function"||typeof Z.namespaceURI!="string"||typeof Z.insertBefore!="function"||typeof Z.hasChildNodes!="function")},at=function(Z){return typeof o=="function"&&Z instanceof o};function st(it,Z,xe){nc(it,Ye=>{Ye.call(t,Z,xe,K)})}const yr=function(Z){let xe=null;if(st(ee.beforeSanitizeElements,Z,null),tt(Z))return He(Z),!0;const Ye=ae(Z.nodeName);if(st(ee.uponSanitizeElement,Z,{tagName:Ye,allowedTags:P}),Z.hasChildNodes()&&!at(Z.firstElementChild)&&Xr(/<[/\w]/g,Z.innerHTML)&&Xr(/<[/\w]/g,Z.textContent)||Z.nodeType===Ao.progressingInstruction||mt&&Z.nodeType===Ao.comment&&Xr(/<[/\w]/g,Z.data))return He(Z),!0;if(!P[Ye]||Q[Ye]){if(!Q[Ye]&&dt(Ye)&&(_e.tagNameCheck instanceof RegExp&&Xr(_e.tagNameCheck,Ye)||_e.tagNameCheck instanceof Function&&_e.tagNameCheck(Ye)))return!1;if(Tr&&!It[Ye]){const Mt=N(Z)||Z.parentNode,nr=x(Z)||Z.childNodes;if(nr&&Mt){const Ot=nr.length;for(let ir=Ot-1;ir>=0;--ir){const Pr=T(nr[ir],!0);Pr.__removalCount=(Z.__removalCount||0)+1,Mt.insertBefore(Pr,R(Z))}}}return He(Z),!0}return Z instanceof u&&!Ge(Z)||(Ye==="noscript"||Ye==="noembed"||Ye==="noframes")&&Xr(/<\/no(script|embed|frames)/i,Z.innerHTML)?(He(Z),!0):(Dt&&Z.nodeType===Ao.text&&(xe=Z.textContent,nc([ge,L,pe],Mt=>{xe=$o(xe,Mt," ")}),Z.textContent!==xe&&(Ro(t.removed,{element:Z.cloneNode()}),Z.textContent=xe)),st(ee.afterSanitizeElements,Z,null),!1)},fr=function(Z,xe,Ye){if(qt&&(xe==="id"||xe==="name")&&(Ye in r||Ye in oe))return!1;if(!(de&&!kt[xe]&&Xr(Te,xe))){if(!(Ce&&Xr(rt,xe))){if(!qe[xe]||kt[xe]){if(!(dt(Z)&&(_e.tagNameCheck instanceof RegExp&&Xr(_e.tagNameCheck,Z)||_e.tagNameCheck instanceof Function&&_e.tagNameCheck(Z))&&(_e.attributeNameCheck instanceof RegExp&&Xr(_e.attributeNameCheck,xe)||_e.attributeNameCheck instanceof Function&&_e.attributeNameCheck(xe))||xe==="is"&&_e.allowCustomizedBuiltInElements&&(_e.tagNameCheck instanceof RegExp&&Xr(_e.tagNameCheck,Ye)||_e.tagNameCheck instanceof Function&&_e.tagNameCheck(Ye))))return!1}else if(!Pt[xe]){if(!Xr(he,$o(Ye,Se,""))){if(!((xe==="src"||xe==="xlink:href"||xe==="href")&&Z!=="script"&&rO(Ye,"data:")===0&&ct[Z])){if(!(Rt&&!Xr(Ke,$o(Ye,Se,"")))){if(Ye)return!1}}}}}}return!0},dt=function(Z){return Z!=="annotation-xml"&&ny(Z,ce)},Gr=function(Z){st(ee.beforeSanitizeAttributes,Z,null);const{attributes:xe}=Z;if(!xe||tt(Z))return;const Ye={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:qe,forceKeepAttr:void 0};let Mt=xe.length;for(;Mt--;){const nr=xe[Mt],{name:Ot,namespaceURI:ir,value:Pr}=nr,Mr=ae(Ot);let dr=Ot==="value"?Pr:nO(Pr);if(Ye.attrName=Mr,Ye.attrValue=dr,Ye.keepAttr=!0,Ye.forceKeepAttr=void 0,st(ee.uponSanitizeAttribute,Z,Ye),dr=Ye.attrValue,sr&&(Mr==="id"||Mr==="name")&&(et(Ot,Z),dr=ze+dr),mt&&Xr(/((--!?|])>)|<\/(style|title)/i,dr)){et(Ot,Z);continue}if(Ye.forceKeepAttr||(et(Ot,Z),!Ye.keepAttr))continue;if(!Ue&&Xr(/\/>/i,dr)){et(Ot,Z);continue}Dt&&nc([ge,L,pe],Hr=>{dr=$o(dr,Hr," ")});const $n=ae(Z.nodeName);if(fr($n,Mr,dr)){if(j&&typeof m=="object"&&typeof m.getAttributeType=="function"&&!ir)switch(m.getAttributeType($n,Mr)){case"TrustedHTML":{dr=j.createHTML(dr);break}case"TrustedScriptURL":{dr=j.createScriptURL(dr);break}}try{ir?Z.setAttributeNS(ir,Ot,dr):Z.setAttribute(Ot,dr),tt(Z)?He(Z):ry(t.removed)}catch{}}}st(ee.afterSanitizeAttributes,Z,null)},cn=function it(Z){let xe=null;const Ye=Qe(Z);for(st(ee.beforeSanitizeShadowDOM,Z,null);xe=Ye.nextNode();)st(ee.uponSanitizeShadowNode,xe,null),yr(xe),Gr(xe),xe.content instanceof a&&it(xe.content);st(ee.afterSanitizeShadowDOM,Z,null)};return t.sanitize=function(it){let Z=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},xe=null,Ye=null,Mt=null,nr=null;if(lr=!it,lr&&(it="<!-->"),typeof it!="string"&&!at(it))if(typeof it.toString=="function"){if(it=it.toString(),typeof it!="string")throw Io("dirty is not a string, aborting")}else throw Io("toString is not a function");if(!t.isSupported)return it;if(ft||De(Z),t.removed=[],typeof it=="string"&&(mr=!1),mr){if(it.nodeName){const Pr=ae(it.nodeName);if(!P[Pr]||Q[Pr])throw Io("root node is forbidden and cannot be sanitized in-place")}}else if(it instanceof o)xe=nt("<!---->"),Ye=xe.ownerDocument.importNode(it,!0),Ye.nodeType===Ao.element&&Ye.nodeName==="BODY"||Ye.nodeName==="HTML"?xe=Ye:xe.appendChild(Ye);else{if(!Oe&&!Dt&&!ke&&it.indexOf("<")===-1)return j&&vt?j.createHTML(it):it;if(xe=nt(it),!xe)return Oe?null:vt?X:""}xe&&St&&He(xe.firstChild);const Ot=Qe(mr?it:xe);for(;Mt=Ot.nextNode();)yr(Mt),Gr(Mt),Mt.content instanceof a&&cn(Mt.content);if(mr)return it;if(Oe){if(Bt)for(nr=D.call(xe.ownerDocument);xe.firstChild;)nr.appendChild(xe.firstChild);else nr=xe;return(qe.shadowroot||qe.shadowrootmode)&&(nr=ue.call(n,nr,!0)),nr}let ir=ke?xe.outerHTML:xe.innerHTML;return ke&&P["!doctype"]&&xe.ownerDocument&&xe.ownerDocument.doctype&&xe.ownerDocument.doctype.name&&Xr(_T,xe.ownerDocument.doctype.name)&&(ir="<!DOCTYPE "+xe.ownerDocument.doctype.name+`>
2
+ `+ir),Dt&&nc([ge,L,pe],Pr=>{ir=$o(ir,Pr," ")}),j&&vt?j.createHTML(ir):ir},t.setConfig=function(){let it=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};De(it),ft=!0},t.clearConfig=function(){K=null,ft=!1},t.isValidAttribute=function(it,Z,xe){K||De({});const Ye=ae(it),Mt=ae(Z);return fr(Ye,Mt,xe)},t.addHook=function(it,Z){typeof Z=="function"&&Ro(ee[it],Z)},t.removeHook=function(it,Z){if(Z!==void 0){const xe=eO(ee[it],Z);return xe===-1?void 0:tO(ee[it],xe,1)[0]}return ry(ee[it])},t.removeHooks=function(it){ee[it]=[]},t.removeAllHooks=function(){ee=cy()},t}var yO=wT();const bO={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},_O="javascript:";function wO(e){return(e==null?void 0:e.constructor)===Object}async function ly(e,t=3){let r=0,n;for(;r<=t;){r+=1;try{return await e()}catch(i){n=i,console.error(i),await ST(1e3*Math.pow(2,r))}}throw n}function ST(e){return new Promise(t=>{setTimeout(()=>{t(0)},e)})}function SO(){return Math.random().toString(36).slice(2)}const TO=new TextDecoder,CO=e=>{const t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return TO.decode(r)},EO=e=>e.length===0,kO=(...e)=>e.every(EO),TT=e=>{const t=yO.sanitize(e,bO);return t.includes(_O)?(console.warn("Suspicious content detected and removed."),""):t},fy=[];class $a{constructor(t){ht(this,"channel");this.channel=t}static addHandler(t){fy.push(t)}debug(...t){this._log("debug",...t)}info(...t){this._log("info",...t)}warn(...t){this._log("warn",...t)}error(...t){this._log("error",...t)}_log(t,...r){fy.forEach(n=>{n(this.channel,t,...r)})}}const RO=(e,t,...r)=>{console[t](`[${t}][${e}]`,...r)},$O=e=>{let t=[],r;return(i,a,...s)=>{a==="debug"||i==="communicator"||(t.push(IO(i,a,...s)),clearTimeout(r),r=window.setTimeout(()=>{if(t.length){const o={num_of_logs:t.length,logs:t};e(o)}t=[]},2e3))}};function IO(e,t,...r){let n=r.pop();typeof n=="string"&&(r.push(n),n={});const i=r.join(" "),a={loglevel:t,channel:e,timestamp:new Date().toISOString(),application:qr.application,version:qr.version,device:qr.deviceId,tenant:qr.tenant,company_id:qr.companyId,location_url:location.href,data:PO(n),message:Zv(i)};return qr.trackerId&&(a.tracker_id=qr.trackerId),a}const OO=["user","phone","phone_number","phoneNumber","email"],AO=[/(?: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];function Zv(e){return typeof e=="string"?AO.forEach(t=>{e=e.replace(t,"__MASKED__")}):e&&wO(e)&&(e={...e},Object.keys(e).forEach(t=>{OO.indexOf(t)!==-1?e[t]="__MASKED__":Zv(e[t])})),e}function PO(e){if(e.error){const t=e.error;return{error:{name:t.name,message:t.message,stack:t.stack}}}return Zv(e.data)}const ud=new $a("communicator");let dy=!1;class MO{constructor(t,r){ht(this,"events");ht(this,"options");ht(this,"channel");ht(this,"authenticate");ht(this,"channelReady",!1);ht(this,"__authed",!1);ht(this,"pending",[]);ht(this,"promises",{});ht(this,"user");ht(this,"iframe");this.authenticate=t.authenticate,this.events=r,this.options=xO(t),this.channel=new MessageChannel,this.useConnect(this.options)}useConnect(t){const r=document.createElement("iframe");r.src=t.bridge,r.setAttribute("style","display:none");let n="*";/^https:/.test(t.bridge)&&(n=new URL(t.bridge).origin),r.addEventListener("load",()=>{if(ud.debug("iframe bridge ready for",n),!this.channelReady){const i={type:"_init",data:t};r.contentWindow.postMessage(i,n,[this.channel.port2])}}),this.channel.port1.onmessage=i=>{this.receiveMessage(i)},document.body.appendChild(r),this.iframe=r}receiveMessage(t){const r=t.data;if(r){if(ud.debug("receiveMessage",r),r.type==="ready")this.channelReady=!0,qr.deviceId=r.result.deviceId,qr.deviceId||console.error("Device Id has not been provided. SDK will not work properly."),this.runPending(),this.events.triggerEvent("ready");else if(r.type==="callback"&&r.callbackId){const[n,i]=this.promises[r.callbackId];r.error?i(r.error):n(r.result),delete this.promises[r.callbackId]}else if(r.type==="refreshToken")this.refreshToken();else if(r.request==="_auth"&&(this.events.triggerEvent("authenticated"),r.result&&r.result.log_proxy_url&&!dy)){dy=!0;const n=$O(i=>{this.postMessage({type:"_log",data:i})});$a.addHandler(n)}}}postMessage(t){this.channel&&this.channelReady?(ud.debug("postMessage",t),this.channel.port1.postMessage(t)):this.pending.push(t)}runPending(){for(;this.pending.length;){const t=this.pending.shift();this.postMessage(t)}}postPromise(t,r){return new Promise((n,i)=>{const a=SO()+"_"+Date.now();this.promises[a]=[n,i];const s={type:t,callbackId:a,data:r};this.postMessage(s)})}async refreshToken(){this.__authed=!0;const t=await this.authenticate(),r=["twilio_chat","nexmo_chat"];this.options.cobrowse&&r.push("cobrowse");const i={type:"_auth",data:{modules:r,user:{token:t.token,company_id:this.options.companyId}}};this.postMessage(i);const a=JSON.parse(CO(t.token.split(".")[1]));if(this.user={identifier:a.identifier,name:a.name,email:a.email},this.events.triggerEvent("authenticate"),a.exp){let s;a.exp.toString().length===13?s=a.exp:a.exp.toString().length===10&&(s=a.exp*1e3),s&&setTimeout(()=>{this.refreshToken()},s-Date.now()-12e4)}}request(t,r){!this.__authed&&t!=="proactive_chat_triggers"&&this.refreshToken();const n={url:t,options:r};return this.postPromise("request",n)}destroy(){delete this.channel,this.iframe&&(document.body.removeChild(this.iframe),this.iframe=void 0)}}function xO(e){var a;let t=e.host;t||(e.tenant?t=ey.replace("main.api",e.tenant+".api"):t=ey);const r=e.lang||"en",n=!!((a=e.cobrowse)!=null&&a.enabled),i=e.bridge||"https://websdk.ujet.co/v3/bridge.html";return{host:t,lang:r,cobrowse:n,companyId:e.companyId,location:location.href,version:e.version||"3.38.4",bridge:i}}var to=(e=>(e.WAITING="waiting",e.READY="ready",e.IN_PROGRESS="in_progress",e.FINISHED="finished",e))(to||{});class em{constructor(){ht(this,"handlers",{})}addEventListener(t,r){this.handlers[t]||(this.handlers[t]=[]),this.handlers[t].push(r)}triggerEvent(t,r){const n=this.handlers[t];n&&n.forEach(i=>{i(r)})}removeEventListener(t,r){if(this.handlers[t]){const n=this.handlers[t].indexOf(r);n!==-1&&this.handlers[t].splice(n,1)}}destroy(){this.handlers={}}}function NO(e,t){const r={};return t.forEach(n=>{r[n.id]=n}),e.map(n=>{if(n.type==="server_message"){const i=n.message_id,a=r[i];CT(n,a.content)}return n})}function LO(e,t){return CT(e,t.content)}function CT(e,t){return Object.keys(t).forEach(r=>{e[r]=t[r]}),e}const py={photo:2,video:2,audio:1,document:1};function DO(e){const t=e.toSorted((r,n)=>!r.groupMessageId||!n.groupMessageId||r.groupMessageId!==n.groupMessageId?0:(py[n.type]||0)-(py[r.type]||0));return t.forEach((r,n,i)=>{const a=!r.groupMessageId,s=i[n+1];s&&(a&&s.$userId===r.$userId&&r.$time||!a&&s.groupMessageId===r.groupMessageId&&r.$time)&&(s.$time=r.$time,r.$time=null)}),t}const jO={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"},FO={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"},UO={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"},BO={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"},qO={confirmSessionTitle:"共同ブラウジングセッションリクエスト",confirmSessionContent:"現在の画面を担当者と共有したいですか。",endSessionText:"共同ブラウジングセッションを終了",confirmRemoteControlTitle:"リモートアクセスリクエスト",confirmRemoteControlContent:"担当者は、お客様をさらにお手伝いするために、現在共有中の画面へのアクセスを希望しています。許可しますか。",confirmFullDeviceTitle:"画面共有リクエスト",confirmFullDeviceContent:"画面全体を担当者と共有したいですか。担当者は画面上で一切の操作ができません。",allowText:"許可",denyText:"拒否"},zO={confirmSessionTitle:"코브라우징 세션 요청",confirmSessionContent:"현재 화면을 상담원과 공유하시겠습니까?",endSessionText:"코브라우징 세션 종료",confirmRemoteControlTitle:"원격 액세스 요청",confirmRemoteControlContent:"상담원이 추가 지원을 위해 현재 공유된 화면에 액세스할 수 있기를 원합니다. 허용하시겠습니까?",confirmFullDeviceTitle:"화면 공유 요청",confirmFullDeviceContent:"상담원과 전체 화면을 공유하시겠습니까? 상담원은 화면의 어떤 부분도 제어할 수 없습니다.",allowText:"허용",denyText:"거절"},WO={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"},GO={confirmSessionTitle:"同步浏览会话请求",confirmSessionContent:"您是否要向该客服代表共享当前的屏幕?",endSessionText:"结束同步浏览会话",confirmRemoteControlTitle:"远程访问请求",confirmRemoteControlContent:"为了进一步协助您,客服代表想访问您当前的共享屏幕。您是否允许这样做?",confirmFullDeviceTitle:"屏幕共享请求",confirmFullDeviceContent:"您是否要向该客服代表共享全屏?客服代表将不能控制屏幕上的任何东西。",allowText:"允许",denyText:"拒绝"},HO={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"},VO={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"},KO={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ä"},JO={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"},YO={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"},XO={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"},QO={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"},ZO={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"},eA={confirmSessionTitle:"ขอเซสชันเรียกดูร่วม",confirmSessionContent:"คุณต้องการแชร์หน้าจอปัจจุบันกับตัวแทนหรือไม่",endSessionText:"สิ้นสุดเซสชันเรียกดูร่วม",confirmRemoteControlTitle:"ขอการเข้าถึงระยะไกล",confirmRemoteControlContent:"ตัวแทนต้องการเข้าถึงหน้าจอของคุณที่แชร์อยู่ในปัจจุบันเพื่อให้ความช่วยเหลือคุณต่อไป คุณจะอนุญาตหรือไม่",confirmFullDeviceTitle:"ขอแชร์หน้าจอ",confirmFullDeviceContent:"คุณต้องการแชร์ทั้งหน้าของคุณกับตัวแทนหรือไม่ ตัวแทนจะไม่สามารถควบคุมอะไรบนหน้าจอ",allowText:"ยินยอม",denyText:"ปฏิเสธ"},tA={confirmSessionTitle:"طلب جلسة تصفح مشترك",confirmSessionContent:"هل تريد مشاركة شاشتك الحالية مع الموظف؟",endSessionText:"إنهاء جلسة التصفح المشترك",confirmRemoteControlTitle:"طلب التحكم عن بعد",confirmRemoteControlContent:"يرغب مسئول الدعم في رؤية شاشتك المشاركة حالياً لمساعدتك بشكلٍ أكبر. هل تسمح بذلك؟",confirmFullDeviceTitle:"طلب مشاركة الشاشة",confirmFullDeviceContent:"هل تريد مشاركة شاشتك الكاملة مع مسئول الدعم؟ لن يتمكن المسئول من التحكم في أي شيء على الشاشة.",allowText:"السماح",denyText:"الرفض"},rA={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"},nA={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"},iA={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"},aA={confirmSessionTitle:"Запрос сеанса совместного просмотра веб-страниц",confirmSessionContent:"Хотите поделиться вашим текущим экраном с представителем?",endSessionText:"Завершить сеанс совместного просмотра веб-страниц",confirmRemoteControlTitle:"Запрос на удаленный доступ",confirmRemoteControlContent:"Представитель хочет получить доступ к вашему текущему экрану, которым вы делитесь, чтобы помочь вам. Хотите разрешить это?",confirmFullDeviceTitle:"Запрос на совместный просмотр экрана",confirmFullDeviceContent:"Хотите поделиться вашим полный экраном с представителем? Агент не сможет выполнять никаких действий на экране.",allowText:"Разрешить",denyText:"Отказать"},sA={confirmSessionTitle:"सह-ब्राउज़ सत्र अनुरोध किया गया",confirmSessionContent:"क्या आप अपनी वर्तमान स्क्रीन को एजेंट के साथ साझा करना चाहते हैं?",endSessionText:"सह-ब्राउज़ सत्र समाप्त करें",confirmRemoteControlTitle:"रिमोट पहुँच का अनुरोध किया गया",confirmRemoteControlContent:"एजेंट आपकी वर्तमान साझा स्क्रीन तक पहुँच प्राप्त करना चाहेगा ताकि वह आपकी और सहायता कर सके। क्या आप इसकी अनुमति देना चाहते हैं?",confirmFullDeviceTitle:"स्क्रीन साझाकरण अनुरोध",confirmFullDeviceContent:"क्या आप अपनी पूरी स्क्रीन एजेंट के साथ साझा करना चाहते हैं? एजेंट स्क्रीन पर कुछ भी नियंत्रित नहीं कर पाएगा।",allowText:"अनुमति दें",denyText:"अस्वीकार करें"},oA={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"},uA={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"},cA={confirmSessionTitle:"Запит на сесію спільного перегляду",confirmSessionContent:"Чи Ви хочете поділитись з агентом своїм поточним екраном?",endSessionText:"Завершити сесію спільного перегляду",confirmRemoteControlTitle:"Запит на віддалений доступ",confirmRemoteControlContent:"Агент хоче отримати доступ до Вашого поточного екрану, який переглядається спільно, щоб допомогти Вам. Ви дозволяєте?",confirmFullDeviceTitle:"Запит на спільний перегляд екрану",confirmFullDeviceContent:"Чи Ви хочете поділитись з агентом своїм екраном повністю? Агент не зможе нічого на ньому контролювати.",allowText:"Дозволити",denyText:"Відмовити"},lA={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"},Po={en:jO,es:FO,"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:UO,"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:BO,ja:qO,ko:zO,it:WO,zh:GO,"zh-Hant":{confirmSessionTitle:"共同瀏覽工作階段要求",confirmSessionContent:"要與專員分享您目前的畫面嗎?",endSessionText:"結束共同瀏覽工作階段",confirmRemoteControlTitle:"遠端存取要求",confirmRemoteControlContent:"專員想要存取您目前分享的螢幕畫面以進一步協助您。要允許嗎?",confirmFullDeviceTitle:"螢幕畫面分享要求",confirmFullDeviceContent:"要與專員分享全螢幕嗎?專員將無法控制畫面上的任何項目。",allowText:"允許",denyText:"拒絕"},sv:HO,pt:VO,"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:KO,nb:JO,da:YO,nl:XO,tr:QO,vi:ZO,th:eA,ar:tA,cs:rA,pl:nA,hu:iA,ru:aA,hi:sA,ro:oA,hr:uA,uk:cA,tl:lA};function fA(e){const t=e.split("-")[0];return Po[e]?e===t?Po[e]:{...Po[t],...Po[e]}:Po[t]}const hy=new $a("MediaStore"),dA=window.indexedDB||window.webkitIndexedDB||window.mozIndexedDB||window.OIndexedDB||window.msIndexedDB,pA="chat-media",vy=1,Ol="file";class ET{constructor(){ht(this,"db")}store(){return new Promise((t,r)=>{if(this.db)return t(my(this.db));const n=dA.open(pA,vy);n.onerror=()=>{r(new Error("indexedDB open failed"))},n.onsuccess=()=>{const i=n.result;this.db=i,t(my(i))},n.onupgradeneeded=i=>{const a=n.result;i.oldVersion>0&&i.oldVersion<vy&&(hy.info("deprecating media store"),a.deleteObjectStore(Ol)),hy.info("creating media store"),a.createObjectStore(Ol)}})}async save(t,r){(await this.store()).put({index:t,file:r},t)}async getAll(){const t=await this.store();return await new Promise((r,n)=>{const i=t.getAll();i.onerror=()=>{n(new Error("indexedDB getAll failed"))},i.onsuccess=()=>{r(i.result)}})}async getAllFiles(){const t={};return(await this.getAll()).forEach(n=>{t[n.index]=n.file}),t}async clear(){(await this.store()).clear()}}function my(e){return e.transaction(Ol,"readwrite").objectStore(Ol)}const hA=new $a("chat-provider");class tm{constructor(t,r,n){ht(this,"audio");ht(this,"issueChatToken");ht(this,"identity");ht(this,"channelId");ht(this,"region");ht(this,"inTask",!1);ht(this,"muted",!1);ht(this,"events");this.events=t,this.region=r.region,this.issueChatToken=n}ping(){if(!this.muted){if(!this.audio){mT.getPath();const t="https://websdk.ujet.co/v3/ping.mp3";this.audio=new window.Audio(t)}try{this.audio.play()}catch(t){hA.warn("Chat audio play failed",{error:t})}}}on(t,r){this.events.addEventListener(t,r)}off(t,r){this.events.removeEventListener(t,r)}trackInTask(t){t.type==="noti"&&t.event==="taskVaStarted"?this.inTask=!0:t.type==="noti"&&t.event==="taskVaFinished"&&(this.inTask=!1)}}ht(tm,"type","base");const kT={};function rm(e){kT[e.type]=e}function vA(e){return kT[e]}const RT=["assigned","va_assigned"],$T=["dismissed","va_dismissed"],mA=["va_assigned","va_dismissed"],gA=["queued",...RT,...$T],yA=["timeout","canceled","failed","finished"],cd=new $a("Chat");class bA{constructor(t,r){ht(this,"provider");ht(this,"store");ht(this,"globalEvents");ht(this,"state");ht(this,"connected",!1);ht(this,"allowSkipVirtualAgent",!1);ht(this,"inEscalation",!1);ht(this,"events");ht(this,"cachedFiles");this.state=t,this.store=new ET,this.cachedFiles={},this.events=new em;const n=vA(this.state.provider_type);this.provider=new n(this.events,t,r)}_setGlobalEvents(t,r){this.globalEvents=t,this.on("message",n=>{if(n.content=TT(n.content),n.type==="server_message"){const i=n.message_id;r(this.id,i).then(a=>{n=LO(n,a),t.triggerEvent("chat.message",n)})}else n.type==="photo"||n.type==="video"?setTimeout(()=>{const i=n.$index.toString();n.file=this.cachedFiles[i],t.triggerEvent("chat.message",n)},100):(t.triggerEvent("chat.message",n),this.registerMessageEvents(n))}),this.on("memberJoined",n=>{t.triggerEvent("chat.memberJoined",n)}),this.on("memberLeft",n=>{t.triggerEvent("chat.memberLeft",n)}),this.on("typingStarted",n=>{t.triggerEvent("chat.typingStarted",n)}),this.on("typingEnded",n=>{t.triggerEvent("chat.typingEnded",n)})}get id(){var t;return((t=this.state)==null?void 0:t.id)||-1}get menuId(){return this.state?this.state.menus[this.state.menus.length-1].id:-1}get channelId(){var t;return((t=this.state)==null?void 0:t.provider_channel_id)||""}get lang(){var t;return((t=this.state)==null?void 0:t.lang)||""}get virtual(){return mA.indexOf(this.status)!==-1}get muted(){var t;return((t=this.provider)==null?void 0:t.muted)||!1}set muted(t){this.provider&&(this.provider.muted=t)}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 t,r;return{virtual:((t=this.state)==null?void 0:t.all_virtual_agents)||[],human:((r=this.state)==null?void 0:r.all_agents)||[]}}get userIdentity(){var t;return((t=this.provider)==null?void 0:t.identity)||""}get status(){var t;return((t=this.state)==null?void 0:t.status)||""}get postSessionStatus(){var t;return((t=this.state)==null?void 0:t.post_session_transfer_status)||""}get statusText(){var t;return((t=this.state)==null?void 0:t.status_text)||""}get cobrowsable(){return this.state?this.state.features.indexOf("cobrowse")!==-1:!1}get ongoing(){return gA.indexOf(this.status)!=-1}get assigned(){return RT.indexOf(this.status)!=-1}get dismissed(){return $T.indexOf(this.status)!=-1}get ended(){return yA.indexOf(this.status)!=-1}get transcriptCount(){var t;return((t=this.state)==null?void 0:t.transcript_requested_count)||0}get createdAt(){var t;return((t=this.state)==null?void 0:t.created_at)||""}get inTask(){var t;return((t=this.provider)==null?void 0:t.inTask)||!1}get feedbackType(){var t;return this.state?this.state.survey_enabled?"survey":(t=this.state.csat_settings)!=null&&t.enabled?"rate":"none":"none"}get optInRequired(){var t;return((t=this.state)==null?void 0:t.post_session_opt_in_required)||!1}get postSessionRequired(){var t;return((t=this.state)==null?void 0:t.post_session_required)||!1}get postSessionInProgress(){return this.state?this.state.post_session_transfer_status===to.IN_PROGRESS:!1}update(t){if(!this.state||this.state.id!==t.id)return;const r=t.menus[t.menus.length-1].id,n=this.state.menus[this.state.menus.length-1].id;this.state=t,r!==n&&this.triggerEvent("_menuChanged",this),t.status==="canceled"?this.triggerEvent("ended",this):this.triggerEvent("updated",this)}on(t,r){this.events.addEventListener(t,r)}off(t,r){this.events.removeEventListener(t,r)}async connect(){if(!this.provider)return cd.info("connecting interrupted"),!1;try{await ly(()=>this.provider.create(),3),await ly(()=>this.provider.join(this.state.provider_channel_id),3),this.connected=!0;const t=await this.fetchMessages(),r={chat:this,messages:t};return this.triggerEvent("connectedMessages",r),this.triggerEvent("connected",this),this.registerProviderEvents(),cd.info("connected with provider",this.state.provider_type),!0}catch{return!1}}async disconnect(){this.connected=!1,this.triggerEvent("disconnected",this),this.events.destroy(),this.provider&&(await this.provider.destroy(),cd.info("disconnect with provider",this.state.provider_type))}async sendMessage(t,r){const n=await this.provider.sendMessage(t);return r&&this.saveMedia(n,r),n}preview(t){if(!this.inTask)return this.provider.preview(t)}async fetchMessages(){if(this.connected){const t=await this.store.getAllFiles();return this.provider.fetchMessages(t)}else throw new Error("Please fetchMessages after chat connected.")}startTyping(){return this.provider.startTyping()}stopTyping(){return this.provider.stopTyping()}saveMedia(t,r){this.cachedFiles[t.toString()]=r,this.store.save(t,r)}async destroy(){await this.clearMediaStore(),this.connected&&await this.disconnect(),this.provider&&(this.triggerEvent("destroyed"),this.provider=null),this.events.destroy(),this.state=null}async clearMediaStore(){await this.store.clear()}_handleChatEndedEvent(t){this.disconnect(),this.state&&(t.timeout?(this.state.status="timeout",this.triggerEvent("timeout",this)):(this.state.status="finished",this.triggerEvent("ended",this)))}triggerEvent(t,r){this.events.triggerEvent(t,r),this.globalEvents&&this.globalEvents.triggerEvent("chat."+t,r)}registerProviderEvents(){this.provider&&this.provider.registerConversationEvents()}registerMessageEvents(t){t.event==="cobrowseRequestedFromAgent"?this.events.triggerEvent("_requestCobrowse","agent"):t.event==="cobrowseRequestedFromEndUser"?this.events.triggerEvent("_requestCobrowse","end_user"):t.event==="chatDismissed"&&this.state?(this.state.status="dismissed",this.triggerEvent("dismissed",this)):t.event==="chatEnded"?this.events.triggerEvent("_chatEnded",t):t.event==="escalationStarted"?this.inEscalation=!0:(t.event==="escalationFailed"||t.event==="escalationAccepted")&&(this.inEscalation=!1)}}function gy(e){return e.chats=e.chats.map(t=>{const r=t.entries.map((n,i)=>_A(n,`${t.comm_id}-${i}`));return t.entries=DO(r),t}),e}function _A(e,t){var r;return{$index:e.timestamp,$sid:t,$timestamp:new Date(e.timestamp),$userType:e.role,$userId:((r=e.user_data)==null?void 0:r.id)||0,user:e.user_data,type:e.type,...e.body}}const wA={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 SA(e){var r,n;return{languages:e.languages.filter(i=>i.enabled).map(i=>({lang:i.lang,name:i.name,localeName:wA[i.lang]})),name:e.display_name,subdomain:e.subdomain,support_email:e.support_email,action_tracking:e.action_tracking_enabled,email_transcripts:e.chat_settings.email_transcripts,message_preview:e.chat_settings.message_preview,email_enhancement:e.email_enhancement_enabled,display_history:((r=e.chat_settings.display_history)==null?void 0:r.enabled)&&((n=e.chat_settings.display_history)==null?void 0:n.to_end_user),use_recording:e.use_recording,use_web:e.use_web,cobrowse_domain:e.cobrowse_domain}}function IT(e){return e.map(TA).filter(t=>t.enabled)}function TA(e){const t={id:e.id,enabled:!0,channels:[],hidden:!!e.hidden};if(!e.name||!e.name.trim())return t.enabled=!1,t;t.name=e.name.trim();const r=CA(e);if(r&&(t.redirection=e.redirection),e.children&&e.children.length){const n=IT(e.children);return t.enabled=n.length>0||r,t.children=n,t}if(!e.channels)t.enabled=r;else{const{channels:n,deflection:i}=EA(e.channels);t.deflection=i,r||(t.channels=n),t.enabled=n.length>0||r}return t}function CA(e){let t=!1;const r=e.redirection;return r&&(r.option==="message"||r.option==="url")&&(t=!!r.data),t}function EA(e){let t=null;const r=[],n=e.chat,i=a=>{!a.deflection_type&&a.deflected_reason&&(a.deflection_type=a.deflected_reason),a.deflected===void 0&&a.deflection_type&&(a.deflected=!0),r.push(a)};return n&&n.deflected&&(t={enabled:!0,type:n.deflected_reason}),n&&(n.enabled||n.virtual_agent_available)&&i({...e.chat,type:"chat"}),e.voice_call&&e.voice_call.instant_enabled&&i({...e.voice_call,type:"instant_call"}),e.voice_call&&e.voice_call.schedule_enabled&&i({...e.voice_call,type:"scheduled_call",deflection_type:e.voice_call.schedule_deflection_type}),e.email&&e.email.enabled&&i({...e.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}),e.external_deflection_link&&e.external_deflection_link.enabled&&e.external_deflection_link.links.forEach(s=>{s.enabled&&i({...s,type:"external_link"})}),{channels:r,deflection:t}}const yy=/Chrome/.test(navigator.userAgent);class kA{constructor(t){ht(this,"request");this.request=t}get(t,r){if(r){const n=[];Object.keys(r).forEach(i=>{const a=r[i];a!==void 0&&n.push(`${encodeURIComponent(i)}=${encodeURIComponent(a)}`)}),t+="?"+n.join("&")}return this.request(t,{method:"GET"})}post(t,r){const n={method:"POST"};return n.body=JSON.stringify(r),this.request(t,n)}patch(t,r){const n={method:"PATCH"};return n.body=JSON.stringify(r),this.request(t,n)}put(t,r){const n={method:"PUT"};return n.body=JSON.stringify(r),this.request(t,n)}async getTriggers(t){const r={"UJET-Company-Id":t};return(await this.request("proactive_chat_triggers",{method:"GET",headers:r})).data}trackClientEvents(t){return this.post("/client_events",{events:t})}async getCompany(){const t=await this.get("company");return SA(t.data)}async getMenus(t,r){const n={type:"web_menu",lang:t,direct_access_key:r},i=await this.get("menus",n),a={key:!!r,user:!1},s=i.headers["ujet-direct-access"];return s&&s!="false"&&(a.user=!0),{menus:IT(i.data),direct:a}}async getAfterHourMessage(t){return(await this.get(`audible_messages/${t}`)).data["after_hours.message"].text}async getTimeSlots(t,r="en"){return(await this.get(`menus/${t}/time_slots`,{type:"web_menu",lang:r})).data}async getWaitTimes(t,r="en"){return(await this.get(`menus/${t}/wait_times`,{type:"web_menu",lang:r})).data}async verifyForm(t){try{return await this.post("forms/verify",t),!0}catch{return!1}}async finishChat(t){return(await this.patch(`chats/${t}`,{status:"finished"})).data}async updatePostSession(t,r){const n={post_session_transfer_status:r};try{return(await this.patch(`chats/${t}`,n)).data}catch(i){if(r===to.IN_PROGRESS&&i.status===400)return(await this.patch(`chats/${t}`,n)).data;throw i}}async getChatDeflection(t){const{data:r}=await this.get(`chats/${t}/deflections`);return r&&r.enabled?r:null}sendChatCustomData(t,r){let n;return typeof r=="string"?n={signed:!0,signed_data:r}:n={signed:!1,data:r},this.post(`chats/${t}/custom_data`,n)}async downloadChatTranscript(t){return(await this.post(`chats/${t}/generate_transcript_pdf`,{})).data}async getPdfStatus(t){return await this.get(`chat_transcript_pdfs/${t}/download_transcript`)}sendChatTranscripts(t,r){this.post(`chats/${t}/transcripts`,{emails:r.join(",")})}async listChatTaskMessages(t){return(await this.get(`chats/${t}/task_va_messages`)).data}async getChatTaskMessage(t,r){return(await this.get(`chats/${t}/task_va_messages/${r}`)).data}async sendChatTaskMessage(t,r){const n={content:{content:r,type:"text"}};return(await this.post(`chats/${t}/task_va_messages`,n)).data}async sendChatTextMessage(t,r){const n={message:{content:r,timestamp:new Date().toISOString()}};await this.post(`chats/${t}/messages`,n)}async sendPreviewMessage(t,r,n){const i={message:{content:r,timestamp:n}},{data:a}=await this.post(`chats/${t}/redact_messages`,i);return a}escalateChat(t,r){return this.post(`chats/${t}/escalations`,r)}trackEscalation(t,r,n){return this.put(`chats/${t}/escalations/${r}`,{escalation_id:r,deflection_channel:n})}requestChatCobrowse(t,r){return this.post(`chats/${t}/cobrowse`,r)}rateChat(t,r){return this.patch(`chats/${t}/rating`,r)}async getChatSurvey(t){return(await this.get(`chats/${t}/survey`)).data}sendChatSurvey(t,r){const n={chat_id:t,answers:r};return this.put(`chats/${t}/survey`,n)}trackChatEndUserEvent(t,r){return this.post(`chats/${t}/end_user_event`,r)}async createChat(t,r,n,i){const a={chat:{menu_id:t,lang:r,email:n.email,greeting:n.greeting,trigger_id:n.trigger_id,ticket_id:n==null?void 0:n.ticket_id,custom_data:n==null?void 0:n.custom_data},cobrowsable:n.cobrowsable},o=(await this.post("chats",a)).data;return this.wrapChat(o,i)}async loadChat(t,r){const n=await this.getChat(t);return this.wrapChat(n,r)}async resumeChat(t,r){const n=await this.patch(`chats/${t}`,{status:"queued"});return this.wrapChat(n.data,r)}async getChatHistory(t=1){if(t===1){const{data:r}=await this.get("/chats/histories?page=1&per_page=2");return gy(r)}else{const{data:r}=await this.get(`/chats/histories?page=${t}&per_page=1`);return gy(r)}}async uploadChatFile(t,r){let n="file";/^image/.test(r.type)?n="photo":/^video/.test(r.type)?n="video":n="file";const i=r.name.replace(/\.[^.]+$/i,""),a=await this.post(`chats/${t}/${n}s/upload`,{filename:i}),s={file:r,fields:a.data.fields};yy&&(s.file=await OT(r));const u=(await this.request(a.data.url,s)).data.key,l=(await this.post(`chats/${t}/${n}s`,{chat_id:t,[n]:{s3_path:u,photo_type:n}})).data;return l.type=n,l}async getChat(t){return(await this.get(`chats/${t}`)).data}async wrapChat(t,r){const n=async()=>(await this.post(`chats/${t.id}/tokens`,{provider_type:t.provider_type,device_id:r})).data,i=new bA(t,n),a=async s=>{if(i.status==="va_assigned"){const o=await this.getSkipVirtualAgentSettings(i.menuId,i.lang);i.allowSkipVirtualAgent=o,i.update(s)}};if(i.channelId)i.connect(),a(t);else{let s;for(;!s;)await this.getChat(i.id).then(o=>{o.provider_channel_id&&i.state?(s=!0,i.update(o),i.connect(),a(o)):(o.status==="canceled"||o.status==="finished")&&(s=!0)}),s||await ST(1500)}return i.on("initialized",async()=>{if(i.status==="queued"){const s=await this.getChat(i.id);i.update(s)}}),i.on("memberJoined",async()=>{const s=await this.getChat(i.id);i.update(s)}),i.on("memberLeft",async()=>{const s=await this.getChat(i.id);i.update(s)}),i.on("_chatEnded",async s=>{const o=await this.getChat(i.id);i.update(o),(!i.state||i.ended)&&i._handleChatEndedEvent(s)}),i.on("_menuChanged",async s=>{const o=await this.getChat(s.id);a(o)}),i}async createCall(t,r,n){const i={type:n.scheduled_at?"web_scheduled_call":"web_instant_call",menu_id:t,lang:r,email:n.email,ticket_id:n.ticket_id,recording_permission:n.recording_permission||"recording_permission_not_asked",scheduled_at:n.scheduled_at,custom_data:n.custom_data,end_user:{phone_number:n.phone_number}},s=(await this.post("calls",{call:i,cobrowsable:!1})).data;return s.menu_id=s.selected_menu.id,s}async fetchCall(t){const n=(await this.get(`calls/${t}`)).data;return n.menu_id=n.selected_menu.id,n}async cancelCall(t){const n=(await this.patch(`calls/${t}`,{status:"failed",fail_reason:"canceled"})).data;return n.menu_id=n.selected_menu.id,n}async listFileTypes(){return(await this.get("email_prohibited_file_types")).data}async createEmail(t,r,n){const i={end_user_email:n.email,email_body:n.content,menu_id:t.toString(),lang:r};return n.name&&(i.end_user_name=n.name),n.recaptcha&&(i.recaptcha_response=n.recaptcha),n.files&&yy?i["email_attachments[]"]=await RA(n.files):n.files&&(i["email_attachments[]"]=[...n.files]),await this.request("emails",{form:i})}async getMedia(t,r){const n=await this.get(`media/${t}?type=${r}`);if(!n.data)return null;const i=n.headers["x-file-name"];return new File([n.data],i,{type:n.data.type})}async getSkipVirtualAgentSettings(t,r){return(await this.get(`menus/${t}/virtual_agent_settings`,{lang:r})).data.allow_skip_virtual_agent}}function RA(e){return Promise.all(e.map(OT))}function OT(e){return new Promise((t,r)=>{const n=new FileReader;n.onload=()=>{const i=[n.result],a={type:e.type,lastModified:e.lastModified};t({name:e.name,fileBits:i,options:a})},n.onerror=r,n.readAsArrayBuffer(e)})}/*!
3
3
  * tabbable 6.2.0
4
4
  * @license MIT, https://github.com/focus-trap/tabbable/blob/master/LICENSE
5
- */var PT=["input:not([inert])","select:not([inert])","textarea:not([inert])","a[href]:not([inert])","button:not([inert])","[tabindex]:not(slot):not([inert])","audio[controls]:not([inert])","video[controls]:not([inert])",'[contenteditable]:not([contenteditable="false"]):not([inert])',"details>summary:first-of-type:not([inert])","details:not([inert])"],Al=PT.join(","),MT=typeof Element>"u",as=MT?function(){}:Element.prototype.matches||Element.prototype.msMatchesSelector||Element.prototype.webkitMatchesSelector,Pl=!MT&&Element.prototype.getRootNode?function(e){var t;return e==null||(t=e.getRootNode)===null||t===void 0?void 0:t.call(e)}:function(e){return e==null?void 0:e.ownerDocument},Ml=function e(t,r){var n;r===void 0&&(r=!0);var i=t==null||(n=t.getAttribute)===null||n===void 0?void 0:n.call(t,"inert"),a=i===""||i==="true",s=a||r&&t&&e(t.parentNode);return s},uA=function(t){var r,n=t==null||(r=t.getAttribute)===null||r===void 0?void 0:r.call(t,"contenteditable");return n===""||n==="true"},xT=function(t,r,n){if(Ml(t))return[];var i=Array.prototype.slice.apply(t.querySelectorAll(Al));return r&&as.call(t,Al)&&i.unshift(t),i=i.filter(n),i},NT=function e(t,r,n){for(var i=[],a=Array.from(t);a.length;){var s=a.shift();if(!Ml(s,!1))if(s.tagName==="SLOT"){var o=s.assignedElements(),u=o.length?o:s.children,c=e(u,!0,n);n.flatten?i.push.apply(i,c):i.push({scopeParent:s,candidates:c})}else{var l=as.call(s,Al);l&&n.filter(s)&&(r||!t.includes(s))&&i.push(s);var p=s.shadowRoot||typeof n.getShadowRoot=="function"&&n.getShadowRoot(s),v=!Ml(p,!1)&&(!n.shadowRootFilter||n.shadowRootFilter(s));if(p&&v){var m=e(p===!0?s.children:p.children,!0,n);n.flatten?i.push.apply(i,m):i.push({scopeParent:s,candidates:m})}else a.unshift.apply(a,s.children)}}return i},LT=function(t){return!isNaN(parseInt(t.getAttribute("tabindex"),10))},Za=function(t){if(!t)throw new Error("No node provided");return t.tabIndex<0&&(/^(AUDIO|VIDEO|DETAILS)$/.test(t.tagName)||uA(t))&&!LT(t)?0:t.tabIndex},cA=function(t,r){var n=Za(t);return n<0&&r&&!LT(t)?0:n},lA=function(t,r){return t.tabIndex===r.tabIndex?t.documentOrder-r.documentOrder:t.tabIndex-r.tabIndex},DT=function(t){return t.tagName==="INPUT"},fA=function(t){return DT(t)&&t.type==="hidden"},dA=function(t){var r=t.tagName==="DETAILS"&&Array.prototype.slice.apply(t.children).some(function(n){return n.tagName==="SUMMARY"});return r},pA=function(t,r){for(var n=0;n<t.length;n++)if(t[n].checked&&t[n].form===r)return t[n]},hA=function(t){if(!t.name)return!0;var r=t.form||Pl(t),n=function(o){return r.querySelectorAll('input[type="radio"][name="'+o+'"]')},i;if(typeof window<"u"&&typeof window.CSS<"u"&&typeof window.CSS.escape=="function")i=n(window.CSS.escape(t.name));else try{i=n(t.name)}catch(s){return console.error("Looks like you have a radio button with a name attribute containing invalid CSS selector characters and need the CSS.escape polyfill: %s",s.message),!1}var a=pA(i,t.form);return!a||a===t},vA=function(t){return DT(t)&&t.type==="radio"},mA=function(t){return vA(t)&&!hA(t)},gA=function(t){var r,n=t&&Pl(t),i=(r=n)===null||r===void 0?void 0:r.host,a=!1;if(n&&n!==t){var s,o,u;for(a=!!((s=i)!==null&&s!==void 0&&(o=s.ownerDocument)!==null&&o!==void 0&&o.contains(i)||t!=null&&(u=t.ownerDocument)!==null&&u!==void 0&&u.contains(t));!a&&i;){var c,l,p;n=Pl(i),i=(c=n)===null||c===void 0?void 0:c.host,a=!!((l=i)!==null&&l!==void 0&&(p=l.ownerDocument)!==null&&p!==void 0&&p.contains(i))}}return a},by=function(t){var r=t.getBoundingClientRect(),n=r.width,i=r.height;return n===0&&i===0},yA=function(t,r){var n=r.displayCheck,i=r.getShadowRoot;if(getComputedStyle(t).visibility==="hidden")return!0;var a=as.call(t,"details>summary:first-of-type"),s=a?t.parentElement:t;if(as.call(s,"details:not([open]) *"))return!0;if(!n||n==="full"||n==="legacy-full"){if(typeof i=="function"){for(var o=t;t;){var u=t.parentElement,c=Pl(t);if(u&&!u.shadowRoot&&i(u)===!0)return by(t);t.assignedSlot?t=t.assignedSlot:!u&&c!==t.ownerDocument?t=c.host:t=u}t=o}if(gA(t))return!t.getClientRects().length;if(n!=="legacy-full")return!0}else if(n==="non-zero-area")return by(t);return!1},bA=function(t){if(/^(INPUT|BUTTON|SELECT|TEXTAREA)$/.test(t.tagName))for(var r=t.parentElement;r;){if(r.tagName==="FIELDSET"&&r.disabled){for(var n=0;n<r.children.length;n++){var i=r.children.item(n);if(i.tagName==="LEGEND")return as.call(r,"fieldset[disabled] *")?!0:!i.contains(t)}return!0}r=r.parentElement}return!1},xl=function(t,r){return!(r.disabled||Ml(r)||fA(r)||yA(r,t)||dA(r)||bA(r))},mh=function(t,r){return!(mA(r)||Za(r)<0||!xl(t,r))},_A=function(t){var r=parseInt(t.getAttribute("tabindex"),10);return!!(isNaN(r)||r>=0)},wA=function e(t){var r=[],n=[];return t.forEach(function(i,a){var s=!!i.scopeParent,o=s?i.scopeParent:i,u=cA(o,s),c=s?e(i.candidates):o;u===0?s?r.push.apply(r,c):r.push(o):n.push({documentOrder:a,tabIndex:u,item:i,isScope:s,content:c})}),n.sort(lA).reduce(function(i,a){return a.isScope?i.push.apply(i,a.content):i.push(a.content),i},[]).concat(r)},SA=function(t,r){r=r||{};var n;return r.getShadowRoot?n=NT([t],r.includeContainer,{filter:mh.bind(null,r),flatten:!1,getShadowRoot:r.getShadowRoot,shadowRootFilter:_A}):n=xT(t,r.includeContainer,mh.bind(null,r)),wA(n)},TA=function(t,r){r=r||{};var n;return r.getShadowRoot?n=NT([t],r.includeContainer,{filter:xl.bind(null,r),flatten:!0,getShadowRoot:r.getShadowRoot}):n=xT(t,r.includeContainer,xl.bind(null,r)),n},Es=function(t,r){if(r=r||{},!t)throw new Error("No node provided");return as.call(t,Al)===!1?!1:mh(r,t)},CA=PT.concat("iframe").join(","),fd=function(t,r){if(r=r||{},!t)throw new Error("No node provided");return as.call(t,CA)===!1?!1:xl(r,t)};/*!
5
+ */var AT=["input:not([inert])","select:not([inert])","textarea:not([inert])","a[href]:not([inert])","button:not([inert])","[tabindex]:not(slot):not([inert])","audio[controls]:not([inert])","video[controls]:not([inert])",'[contenteditable]:not([contenteditable="false"]):not([inert])',"details>summary:first-of-type:not([inert])","details:not([inert])"],Al=AT.join(","),PT=typeof Element>"u",as=PT?function(){}:Element.prototype.matches||Element.prototype.msMatchesSelector||Element.prototype.webkitMatchesSelector,Pl=!PT&&Element.prototype.getRootNode?function(e){var t;return e==null||(t=e.getRootNode)===null||t===void 0?void 0:t.call(e)}:function(e){return e==null?void 0:e.ownerDocument},Ml=function e(t,r){var n;r===void 0&&(r=!0);var i=t==null||(n=t.getAttribute)===null||n===void 0?void 0:n.call(t,"inert"),a=i===""||i==="true",s=a||r&&t&&e(t.parentNode);return s},$A=function(t){var r,n=t==null||(r=t.getAttribute)===null||r===void 0?void 0:r.call(t,"contenteditable");return n===""||n==="true"},MT=function(t,r,n){if(Ml(t))return[];var i=Array.prototype.slice.apply(t.querySelectorAll(Al));return r&&as.call(t,Al)&&i.unshift(t),i=i.filter(n),i},xT=function e(t,r,n){for(var i=[],a=Array.from(t);a.length;){var s=a.shift();if(!Ml(s,!1))if(s.tagName==="SLOT"){var o=s.assignedElements(),u=o.length?o:s.children,c=e(u,!0,n);n.flatten?i.push.apply(i,c):i.push({scopeParent:s,candidates:c})}else{var l=as.call(s,Al);l&&n.filter(s)&&(r||!t.includes(s))&&i.push(s);var p=s.shadowRoot||typeof n.getShadowRoot=="function"&&n.getShadowRoot(s),v=!Ml(p,!1)&&(!n.shadowRootFilter||n.shadowRootFilter(s));if(p&&v){var m=e(p===!0?s.children:p.children,!0,n);n.flatten?i.push.apply(i,m):i.push({scopeParent:s,candidates:m})}else a.unshift.apply(a,s.children)}}return i},NT=function(t){return!isNaN(parseInt(t.getAttribute("tabindex"),10))},Za=function(t){if(!t)throw new Error("No node provided");return t.tabIndex<0&&(/^(AUDIO|VIDEO|DETAILS)$/.test(t.tagName)||$A(t))&&!NT(t)?0:t.tabIndex},IA=function(t,r){var n=Za(t);return n<0&&r&&!NT(t)?0:n},OA=function(t,r){return t.tabIndex===r.tabIndex?t.documentOrder-r.documentOrder:t.tabIndex-r.tabIndex},LT=function(t){return t.tagName==="INPUT"},AA=function(t){return LT(t)&&t.type==="hidden"},PA=function(t){var r=t.tagName==="DETAILS"&&Array.prototype.slice.apply(t.children).some(function(n){return n.tagName==="SUMMARY"});return r},MA=function(t,r){for(var n=0;n<t.length;n++)if(t[n].checked&&t[n].form===r)return t[n]},xA=function(t){if(!t.name)return!0;var r=t.form||Pl(t),n=function(o){return r.querySelectorAll('input[type="radio"][name="'+o+'"]')},i;if(typeof window<"u"&&typeof window.CSS<"u"&&typeof window.CSS.escape=="function")i=n(window.CSS.escape(t.name));else try{i=n(t.name)}catch(s){return console.error("Looks like you have a radio button with a name attribute containing invalid CSS selector characters and need the CSS.escape polyfill: %s",s.message),!1}var a=MA(i,t.form);return!a||a===t},NA=function(t){return LT(t)&&t.type==="radio"},LA=function(t){return NA(t)&&!xA(t)},DA=function(t){var r,n=t&&Pl(t),i=(r=n)===null||r===void 0?void 0:r.host,a=!1;if(n&&n!==t){var s,o,u;for(a=!!((s=i)!==null&&s!==void 0&&(o=s.ownerDocument)!==null&&o!==void 0&&o.contains(i)||t!=null&&(u=t.ownerDocument)!==null&&u!==void 0&&u.contains(t));!a&&i;){var c,l,p;n=Pl(i),i=(c=n)===null||c===void 0?void 0:c.host,a=!!((l=i)!==null&&l!==void 0&&(p=l.ownerDocument)!==null&&p!==void 0&&p.contains(i))}}return a},by=function(t){var r=t.getBoundingClientRect(),n=r.width,i=r.height;return n===0&&i===0},jA=function(t,r){var n=r.displayCheck,i=r.getShadowRoot;if(getComputedStyle(t).visibility==="hidden")return!0;var a=as.call(t,"details>summary:first-of-type"),s=a?t.parentElement:t;if(as.call(s,"details:not([open]) *"))return!0;if(!n||n==="full"||n==="legacy-full"){if(typeof i=="function"){for(var o=t;t;){var u=t.parentElement,c=Pl(t);if(u&&!u.shadowRoot&&i(u)===!0)return by(t);t.assignedSlot?t=t.assignedSlot:!u&&c!==t.ownerDocument?t=c.host:t=u}t=o}if(DA(t))return!t.getClientRects().length;if(n!=="legacy-full")return!0}else if(n==="non-zero-area")return by(t);return!1},FA=function(t){if(/^(INPUT|BUTTON|SELECT|TEXTAREA)$/.test(t.tagName))for(var r=t.parentElement;r;){if(r.tagName==="FIELDSET"&&r.disabled){for(var n=0;n<r.children.length;n++){var i=r.children.item(n);if(i.tagName==="LEGEND")return as.call(r,"fieldset[disabled] *")?!0:!i.contains(t)}return!0}r=r.parentElement}return!1},xl=function(t,r){return!(r.disabled||Ml(r)||AA(r)||jA(r,t)||PA(r)||FA(r))},mh=function(t,r){return!(LA(r)||Za(r)<0||!xl(t,r))},UA=function(t){var r=parseInt(t.getAttribute("tabindex"),10);return!!(isNaN(r)||r>=0)},BA=function e(t){var r=[],n=[];return t.forEach(function(i,a){var s=!!i.scopeParent,o=s?i.scopeParent:i,u=IA(o,s),c=s?e(i.candidates):o;u===0?s?r.push.apply(r,c):r.push(o):n.push({documentOrder:a,tabIndex:u,item:i,isScope:s,content:c})}),n.sort(OA).reduce(function(i,a){return a.isScope?i.push.apply(i,a.content):i.push(a.content),i},[]).concat(r)},qA=function(t,r){r=r||{};var n;return r.getShadowRoot?n=xT([t],r.includeContainer,{filter:mh.bind(null,r),flatten:!1,getShadowRoot:r.getShadowRoot,shadowRootFilter:UA}):n=MT(t,r.includeContainer,mh.bind(null,r)),BA(n)},zA=function(t,r){r=r||{};var n;return r.getShadowRoot?n=xT([t],r.includeContainer,{filter:xl.bind(null,r),flatten:!0,getShadowRoot:r.getShadowRoot}):n=MT(t,r.includeContainer,xl.bind(null,r)),n},Es=function(t,r){if(r=r||{},!t)throw new Error("No node provided");return as.call(t,Al)===!1?!1:mh(r,t)},WA=AT.concat("iframe").join(","),ld=function(t,r){if(r=r||{},!t)throw new Error("No node provided");return as.call(t,WA)===!1?!1:xl(r,t)};/*!
6
6
  * focus-trap 7.6.5
7
7
  * @license MIT, https://github.com/focus-trap/focus-trap/blob/master/LICENSE
8
- */function gh(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function EA(e){if(Array.isArray(e))return gh(e)}function kA(e,t,r){return(t=AA(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function RA(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function $A(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
9
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function _y(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function wy(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?_y(Object(r),!0).forEach(function(n){kA(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):_y(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function IA(e){return EA(e)||RA(e)||PA(e)||$A()}function OA(e,t){if(typeof e!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function AA(e){var t=OA(e,"string");return typeof t=="symbol"?t:t+""}function PA(e,t){if(e){if(typeof e=="string")return gh(e,t);var r={}.toString.call(e).slice(8,-1);return r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set"?Array.from(e):r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?gh(e,t):void 0}}var Sy={activateTrap:function(t,r){if(t.length>0){var n=t[t.length-1];n!==r&&n._setPausedState(!0)}var i=t.indexOf(r);i===-1||t.splice(i,1),t.push(r)},deactivateTrap:function(t,r){var n=t.indexOf(r);n!==-1&&t.splice(n,1),t.length>0&&!t[t.length-1]._isManuallyPaused()&&t[t.length-1]._setPausedState(!1)}},MA=function(t){return t.tagName&&t.tagName.toLowerCase()==="input"&&typeof t.select=="function"},xA=function(t){return(t==null?void 0:t.key)==="Escape"||(t==null?void 0:t.key)==="Esc"||(t==null?void 0:t.keyCode)===27},ru=function(t){return(t==null?void 0:t.key)==="Tab"||(t==null?void 0:t.keyCode)===9},NA=function(t){return ru(t)&&!t.shiftKey},LA=function(t){return ru(t)&&t.shiftKey},Ty=function(t){return setTimeout(t,0)},Po=function(t){for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];return typeof t=="function"?t.apply(void 0,n):t},ac=function(t){return t.target.shadowRoot&&typeof t.composedPath=="function"?t.composedPath()[0]:t.target},DA=[],jA=function(t,r){var n=(r==null?void 0:r.document)||document,i=(r==null?void 0:r.trapStack)||DA,a=wy({returnFocusOnDeactivate:!0,escapeDeactivates:!0,delayInitialFocus:!0,isKeyForward:NA,isKeyBackward:LA},r),s={containers:[],containerGroups:[],tabbableGroups:[],nodeFocusedBeforeActivation:null,mostRecentlyFocusedNode:null,active:!1,paused:!1,manuallyPaused:!1,delayInitialFocusTimer:void 0,recentNavEvent:void 0},o,u=function(L,pe,Te){return L&&L[pe]!==void 0?L[pe]:a[Te||pe]},c=function(L,pe){var Te=typeof(pe==null?void 0:pe.composedPath)=="function"?pe.composedPath():void 0;return s.containerGroups.findIndex(function(rt){var Ke=rt.container,Se=rt.tabbableNodes;return Ke.contains(L)||(Te==null?void 0:Te.includes(Ke))||Se.find(function(ce){return ce===L})})},l=function(L){var pe=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},Te=pe.hasFallback,rt=Te===void 0?!1:Te,Ke=pe.params,Se=Ke===void 0?[]:Ke,ce=a[L];if(typeof ce=="function"&&(ce=ce.apply(void 0,IA(Se))),ce===!0&&(ce=void 0),!ce){if(ce===void 0||ce===!1)return ce;throw new Error("`".concat(L,"` was specified but was not a node, or did not return a node"))}var he=ce;if(typeof ce=="string"){try{he=n.querySelector(ce)}catch(P){throw new Error("`".concat(L,'` appears to be an invalid selector; error="').concat(P.message,'"'))}if(!he&&!rt)throw new Error("`".concat(L,"` as selector refers to no known node"))}return he},p=function(){var L=l("initialFocus",{hasFallback:!0});if(L===!1)return!1;if(L===void 0||L&&!fd(L,a.tabbableOptions))if(c(n.activeElement)>=0)L=n.activeElement;else{var pe=s.tabbableGroups[0],Te=pe&&pe.firstTabbableNode;L=Te||l("fallbackFocus")}else L===null&&(L=l("fallbackFocus"));if(!L)throw new Error("Your focus-trap needs to have at least one focusable element");return L},v=function(){if(s.containerGroups=s.containers.map(function(L){var pe=SA(L,a.tabbableOptions),Te=TA(L,a.tabbableOptions),rt=pe.length>0?pe[0]:void 0,Ke=pe.length>0?pe[pe.length-1]:void 0,Se=Te.find(function(P){return Es(P)}),ce=Te.slice().reverse().find(function(P){return Es(P)}),he=!!pe.find(function(P){return Za(P)>0});return{container:L,tabbableNodes:pe,focusableNodes:Te,posTabIndexesFound:he,firstTabbableNode:rt,lastTabbableNode:Ke,firstDomTabbableNode:Se,lastDomTabbableNode:ce,nextTabbableNode:function(Ie){var qe=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0,Ne=pe.indexOf(Ie);return Ne<0?qe?Te.slice(Te.indexOf(Ie)+1).find(function(_e){return Es(_e)}):Te.slice(0,Te.indexOf(Ie)).reverse().find(function(_e){return Es(_e)}):pe[Ne+(qe?1:-1)]}}}),s.tabbableGroups=s.containerGroups.filter(function(L){return L.tabbableNodes.length>0}),s.tabbableGroups.length<=0&&!l("fallbackFocus"))throw new Error("Your focus-trap must have at least one container with at least one tabbable node in it at all times");if(s.containerGroups.find(function(L){return L.posTabIndexesFound})&&s.containerGroups.length>1)throw new Error("At least one node with a positive tabindex was found in one of your focus-trap's multiple containers. Positive tabindexes are only supported in single-container focus-traps.")},m=function(L){var pe=L.activeElement;if(pe)return pe.shadowRoot&&pe.shadowRoot.activeElement!==null?m(pe.shadowRoot):pe},b=function(L){if(L!==!1&&L!==m(document)){if(!L||!L.focus){b(p());return}L.focus({preventScroll:!!a.preventScroll}),s.mostRecentlyFocusedNode=L,MA(L)&&L.select()}},T=function(L){var pe=l("setReturnFocus",{params:[L]});return pe||(pe===!1?!1:L)},I=function(L){var pe=L.target,Te=L.event,rt=L.isBackward,Ke=rt===void 0?!1:rt;pe=pe||ac(Te),v();var Se=null;if(s.tabbableGroups.length>0){var ce=c(pe,Te),he=ce>=0?s.containerGroups[ce]:void 0;if(ce<0)Ke?Se=s.tabbableGroups[s.tabbableGroups.length-1].lastTabbableNode:Se=s.tabbableGroups[0].firstTabbableNode;else if(Ke){var P=s.tabbableGroups.findIndex(function(kt){var Ce=kt.firstTabbableNode;return pe===Ce});if(P<0&&(he.container===pe||fd(pe,a.tabbableOptions)&&!Es(pe,a.tabbableOptions)&&!he.nextTabbableNode(pe,!1))&&(P=ce),P>=0){var Ie=P===0?s.tabbableGroups.length-1:P-1,qe=s.tabbableGroups[Ie];Se=Za(pe)>=0?qe.lastTabbableNode:qe.lastDomTabbableNode}else ru(Te)||(Se=he.nextTabbableNode(pe,!1))}else{var Ne=s.tabbableGroups.findIndex(function(kt){var Ce=kt.lastTabbableNode;return pe===Ce});if(Ne<0&&(he.container===pe||fd(pe,a.tabbableOptions)&&!Es(pe,a.tabbableOptions)&&!he.nextTabbableNode(pe))&&(Ne=ce),Ne>=0){var _e=Ne===s.tabbableGroups.length-1?0:Ne+1,Q=s.tabbableGroups[_e];Se=Za(pe)>=0?Q.firstTabbableNode:Q.firstDomTabbableNode}else ru(Te)||(Se=he.nextTabbableNode(pe))}}else Se=l("fallbackFocus");return Se},R=function(L){var pe=ac(L);if(!(c(pe,L)>=0)){if(Po(a.clickOutsideDeactivates,L)){o.deactivate({returnFocus:a.returnFocusOnDeactivate});return}Po(a.allowOutsideClick,L)||L.preventDefault()}},x=function(L){var pe=ac(L),Te=c(pe,L)>=0;if(Te||pe instanceof Document)Te&&(s.mostRecentlyFocusedNode=pe);else{L.stopImmediatePropagation();var rt,Ke=!0;if(s.mostRecentlyFocusedNode)if(Za(s.mostRecentlyFocusedNode)>0){var Se=c(s.mostRecentlyFocusedNode),ce=s.containerGroups[Se].tabbableNodes;if(ce.length>0){var he=ce.findIndex(function(P){return P===s.mostRecentlyFocusedNode});he>=0&&(a.isKeyForward(s.recentNavEvent)?he+1<ce.length&&(rt=ce[he+1],Ke=!1):he-1>=0&&(rt=ce[he-1],Ke=!1))}}else s.containerGroups.some(function(P){return P.tabbableNodes.some(function(Ie){return Za(Ie)>0})})||(Ke=!1);else Ke=!1;Ke&&(rt=I({target:s.mostRecentlyFocusedNode,isBackward:a.isKeyBackward(s.recentNavEvent)})),b(rt||s.mostRecentlyFocusedNode||p())}s.recentNavEvent=void 0},N=function(L){var pe=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;s.recentNavEvent=L;var Te=I({event:L,isBackward:pe});Te&&(ru(L)&&L.preventDefault(),b(Te))},j=function(L){(a.isKeyForward(L)||a.isKeyBackward(L))&&N(L,a.isKeyBackward(L))},X=function(L){xA(L)&&Po(a.escapeDeactivates,L)!==!1&&(L.preventDefault(),o.deactivate())},J=function(L){var pe=ac(L);c(pe,L)>=0||Po(a.clickOutsideDeactivates,L)||Po(a.allowOutsideClick,L)||(L.preventDefault(),L.stopImmediatePropagation())},V=function(){if(s.active)return Sy.activateTrap(i,o),s.delayInitialFocusTimer=a.delayInitialFocus?Ty(function(){b(p())}):b(p()),n.addEventListener("focusin",x,!0),n.addEventListener("mousedown",R,{capture:!0,passive:!1}),n.addEventListener("touchstart",R,{capture:!0,passive:!1}),n.addEventListener("click",J,{capture:!0,passive:!1}),n.addEventListener("keydown",j,{capture:!0,passive:!1}),n.addEventListener("keydown",X),o},D=function(){if(s.active)return n.removeEventListener("focusin",x,!0),n.removeEventListener("mousedown",R,!0),n.removeEventListener("touchstart",R,!0),n.removeEventListener("click",J,!0),n.removeEventListener("keydown",j,!0),n.removeEventListener("keydown",X),o},te=function(L){var pe=L.some(function(Te){var rt=Array.from(Te.removedNodes);return rt.some(function(Ke){return Ke===s.mostRecentlyFocusedNode})});pe&&b(p())},ue=typeof window<"u"&&"MutationObserver"in window?new MutationObserver(te):void 0,ee=function(){ue&&(ue.disconnect(),s.active&&!s.paused&&s.containers.map(function(L){ue.observe(L,{subtree:!0,childList:!0})}))};return o={get active(){return s.active},get paused(){return s.paused},activate:function(L){if(s.active)return this;var pe=u(L,"onActivate"),Te=u(L,"onPostActivate"),rt=u(L,"checkCanFocusTrap");rt||v(),s.active=!0,s.paused=!1,s.nodeFocusedBeforeActivation=m(n),pe==null||pe();var Ke=function(){rt&&v(),V(),ee(),Te==null||Te()};return rt?(rt(s.containers.concat()).then(Ke,Ke),this):(Ke(),this)},deactivate:function(L){if(!s.active)return this;var pe=wy({onDeactivate:a.onDeactivate,onPostDeactivate:a.onPostDeactivate,checkCanReturnFocus:a.checkCanReturnFocus},L);clearTimeout(s.delayInitialFocusTimer),s.delayInitialFocusTimer=void 0,D(),s.active=!1,s.paused=!1,ee(),Sy.deactivateTrap(i,o);var Te=u(pe,"onDeactivate"),rt=u(pe,"onPostDeactivate"),Ke=u(pe,"checkCanReturnFocus"),Se=u(pe,"returnFocus","returnFocusOnDeactivate");Te==null||Te();var ce=function(){Ty(function(){Se&&b(T(s.nodeFocusedBeforeActivation)),rt==null||rt()})};return Se&&Ke?(Ke(T(s.nodeFocusedBeforeActivation)).then(ce,ce),this):(ce(),this)},pause:function(L){return s.active?(s.manuallyPaused=!0,this._setPausedState(!0,L)):this},unpause:function(L){return s.active?(s.manuallyPaused=!1,i[i.length-1]!==this?this:this._setPausedState(!1,L)):this},updateContainerElements:function(L){var pe=[].concat(L).filter(Boolean);return s.containers=pe.map(function(Te){return typeof Te=="string"?n.querySelector(Te):Te}),s.active&&v(),ee(),this}},Object.defineProperties(o,{_isManuallyPaused:{value:function(){return s.manuallyPaused}},_setPausedState:{value:function(L,pe){if(s.paused===L)return this;if(s.paused=L,L){var Te=u(pe,"onPause"),rt=u(pe,"onPostPause");Te==null||Te(),D(),ee(),rt==null||rt()}else{var Ke=u(pe,"onUnpause"),Se=u(pe,"onPostUnpause");Ke==null||Ke(),v(),V(),ee(),Se==null||Se()}return this}}}),o.updateContainerElements(t),o};const FA=`
8
+ */function gh(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function GA(e){if(Array.isArray(e))return gh(e)}function HA(e,t,r){return(t=XA(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function VA(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function KA(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
9
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function _y(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function wy(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?_y(Object(r),!0).forEach(function(n){HA(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):_y(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function JA(e){return GA(e)||VA(e)||QA(e)||KA()}function YA(e,t){if(typeof e!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function XA(e){var t=YA(e,"string");return typeof t=="symbol"?t:t+""}function QA(e,t){if(e){if(typeof e=="string")return gh(e,t);var r={}.toString.call(e).slice(8,-1);return r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set"?Array.from(e):r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?gh(e,t):void 0}}var Sy={activateTrap:function(t,r){if(t.length>0){var n=t[t.length-1];n!==r&&n._setPausedState(!0)}var i=t.indexOf(r);i===-1||t.splice(i,1),t.push(r)},deactivateTrap:function(t,r){var n=t.indexOf(r);n!==-1&&t.splice(n,1),t.length>0&&!t[t.length-1]._isManuallyPaused()&&t[t.length-1]._setPausedState(!1)}},ZA=function(t){return t.tagName&&t.tagName.toLowerCase()==="input"&&typeof t.select=="function"},eP=function(t){return(t==null?void 0:t.key)==="Escape"||(t==null?void 0:t.key)==="Esc"||(t==null?void 0:t.keyCode)===27},ru=function(t){return(t==null?void 0:t.key)==="Tab"||(t==null?void 0:t.keyCode)===9},tP=function(t){return ru(t)&&!t.shiftKey},rP=function(t){return ru(t)&&t.shiftKey},Ty=function(t){return setTimeout(t,0)},Mo=function(t){for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];return typeof t=="function"?t.apply(void 0,n):t},ac=function(t){return t.target.shadowRoot&&typeof t.composedPath=="function"?t.composedPath()[0]:t.target},nP=[],iP=function(t,r){var n=(r==null?void 0:r.document)||document,i=(r==null?void 0:r.trapStack)||nP,a=wy({returnFocusOnDeactivate:!0,escapeDeactivates:!0,delayInitialFocus:!0,isKeyForward:tP,isKeyBackward:rP},r),s={containers:[],containerGroups:[],tabbableGroups:[],nodeFocusedBeforeActivation:null,mostRecentlyFocusedNode:null,active:!1,paused:!1,manuallyPaused:!1,delayInitialFocusTimer:void 0,recentNavEvent:void 0},o,u=function(L,pe,Te){return L&&L[pe]!==void 0?L[pe]:a[Te||pe]},c=function(L,pe){var Te=typeof(pe==null?void 0:pe.composedPath)=="function"?pe.composedPath():void 0;return s.containerGroups.findIndex(function(rt){var Ke=rt.container,Se=rt.tabbableNodes;return Ke.contains(L)||(Te==null?void 0:Te.includes(Ke))||Se.find(function(ce){return ce===L})})},l=function(L){var pe=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},Te=pe.hasFallback,rt=Te===void 0?!1:Te,Ke=pe.params,Se=Ke===void 0?[]:Ke,ce=a[L];if(typeof ce=="function"&&(ce=ce.apply(void 0,JA(Se))),ce===!0&&(ce=void 0),!ce){if(ce===void 0||ce===!1)return ce;throw new Error("`".concat(L,"` was specified but was not a node, or did not return a node"))}var he=ce;if(typeof ce=="string"){try{he=n.querySelector(ce)}catch(P){throw new Error("`".concat(L,'` appears to be an invalid selector; error="').concat(P.message,'"'))}if(!he&&!rt)throw new Error("`".concat(L,"` as selector refers to no known node"))}return he},p=function(){var L=l("initialFocus",{hasFallback:!0});if(L===!1)return!1;if(L===void 0||L&&!ld(L,a.tabbableOptions))if(c(n.activeElement)>=0)L=n.activeElement;else{var pe=s.tabbableGroups[0],Te=pe&&pe.firstTabbableNode;L=Te||l("fallbackFocus")}else L===null&&(L=l("fallbackFocus"));if(!L)throw new Error("Your focus-trap needs to have at least one focusable element");return L},v=function(){if(s.containerGroups=s.containers.map(function(L){var pe=qA(L,a.tabbableOptions),Te=zA(L,a.tabbableOptions),rt=pe.length>0?pe[0]:void 0,Ke=pe.length>0?pe[pe.length-1]:void 0,Se=Te.find(function(P){return Es(P)}),ce=Te.slice().reverse().find(function(P){return Es(P)}),he=!!pe.find(function(P){return Za(P)>0});return{container:L,tabbableNodes:pe,focusableNodes:Te,posTabIndexesFound:he,firstTabbableNode:rt,lastTabbableNode:Ke,firstDomTabbableNode:Se,lastDomTabbableNode:ce,nextTabbableNode:function(Ie){var qe=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0,Ne=pe.indexOf(Ie);return Ne<0?qe?Te.slice(Te.indexOf(Ie)+1).find(function(_e){return Es(_e)}):Te.slice(0,Te.indexOf(Ie)).reverse().find(function(_e){return Es(_e)}):pe[Ne+(qe?1:-1)]}}}),s.tabbableGroups=s.containerGroups.filter(function(L){return L.tabbableNodes.length>0}),s.tabbableGroups.length<=0&&!l("fallbackFocus"))throw new Error("Your focus-trap must have at least one container with at least one tabbable node in it at all times");if(s.containerGroups.find(function(L){return L.posTabIndexesFound})&&s.containerGroups.length>1)throw new Error("At least one node with a positive tabindex was found in one of your focus-trap's multiple containers. Positive tabindexes are only supported in single-container focus-traps.")},m=function(L){var pe=L.activeElement;if(pe)return pe.shadowRoot&&pe.shadowRoot.activeElement!==null?m(pe.shadowRoot):pe},b=function(L){if(L!==!1&&L!==m(document)){if(!L||!L.focus){b(p());return}L.focus({preventScroll:!!a.preventScroll}),s.mostRecentlyFocusedNode=L,ZA(L)&&L.select()}},T=function(L){var pe=l("setReturnFocus",{params:[L]});return pe||(pe===!1?!1:L)},I=function(L){var pe=L.target,Te=L.event,rt=L.isBackward,Ke=rt===void 0?!1:rt;pe=pe||ac(Te),v();var Se=null;if(s.tabbableGroups.length>0){var ce=c(pe,Te),he=ce>=0?s.containerGroups[ce]:void 0;if(ce<0)Ke?Se=s.tabbableGroups[s.tabbableGroups.length-1].lastTabbableNode:Se=s.tabbableGroups[0].firstTabbableNode;else if(Ke){var P=s.tabbableGroups.findIndex(function(kt){var Ce=kt.firstTabbableNode;return pe===Ce});if(P<0&&(he.container===pe||ld(pe,a.tabbableOptions)&&!Es(pe,a.tabbableOptions)&&!he.nextTabbableNode(pe,!1))&&(P=ce),P>=0){var Ie=P===0?s.tabbableGroups.length-1:P-1,qe=s.tabbableGroups[Ie];Se=Za(pe)>=0?qe.lastTabbableNode:qe.lastDomTabbableNode}else ru(Te)||(Se=he.nextTabbableNode(pe,!1))}else{var Ne=s.tabbableGroups.findIndex(function(kt){var Ce=kt.lastTabbableNode;return pe===Ce});if(Ne<0&&(he.container===pe||ld(pe,a.tabbableOptions)&&!Es(pe,a.tabbableOptions)&&!he.nextTabbableNode(pe))&&(Ne=ce),Ne>=0){var _e=Ne===s.tabbableGroups.length-1?0:Ne+1,Q=s.tabbableGroups[_e];Se=Za(pe)>=0?Q.firstTabbableNode:Q.firstDomTabbableNode}else ru(Te)||(Se=he.nextTabbableNode(pe))}}else Se=l("fallbackFocus");return Se},R=function(L){var pe=ac(L);if(!(c(pe,L)>=0)){if(Mo(a.clickOutsideDeactivates,L)){o.deactivate({returnFocus:a.returnFocusOnDeactivate});return}Mo(a.allowOutsideClick,L)||L.preventDefault()}},x=function(L){var pe=ac(L),Te=c(pe,L)>=0;if(Te||pe instanceof Document)Te&&(s.mostRecentlyFocusedNode=pe);else{L.stopImmediatePropagation();var rt,Ke=!0;if(s.mostRecentlyFocusedNode)if(Za(s.mostRecentlyFocusedNode)>0){var Se=c(s.mostRecentlyFocusedNode),ce=s.containerGroups[Se].tabbableNodes;if(ce.length>0){var he=ce.findIndex(function(P){return P===s.mostRecentlyFocusedNode});he>=0&&(a.isKeyForward(s.recentNavEvent)?he+1<ce.length&&(rt=ce[he+1],Ke=!1):he-1>=0&&(rt=ce[he-1],Ke=!1))}}else s.containerGroups.some(function(P){return P.tabbableNodes.some(function(Ie){return Za(Ie)>0})})||(Ke=!1);else Ke=!1;Ke&&(rt=I({target:s.mostRecentlyFocusedNode,isBackward:a.isKeyBackward(s.recentNavEvent)})),b(rt||s.mostRecentlyFocusedNode||p())}s.recentNavEvent=void 0},N=function(L){var pe=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;s.recentNavEvent=L;var Te=I({event:L,isBackward:pe});Te&&(ru(L)&&L.preventDefault(),b(Te))},j=function(L){(a.isKeyForward(L)||a.isKeyBackward(L))&&N(L,a.isKeyBackward(L))},X=function(L){eP(L)&&Mo(a.escapeDeactivates,L)!==!1&&(L.preventDefault(),o.deactivate())},J=function(L){var pe=ac(L);c(pe,L)>=0||Mo(a.clickOutsideDeactivates,L)||Mo(a.allowOutsideClick,L)||(L.preventDefault(),L.stopImmediatePropagation())},V=function(){if(s.active)return Sy.activateTrap(i,o),s.delayInitialFocusTimer=a.delayInitialFocus?Ty(function(){b(p())}):b(p()),n.addEventListener("focusin",x,!0),n.addEventListener("mousedown",R,{capture:!0,passive:!1}),n.addEventListener("touchstart",R,{capture:!0,passive:!1}),n.addEventListener("click",J,{capture:!0,passive:!1}),n.addEventListener("keydown",j,{capture:!0,passive:!1}),n.addEventListener("keydown",X),o},D=function(){if(s.active)return n.removeEventListener("focusin",x,!0),n.removeEventListener("mousedown",R,!0),n.removeEventListener("touchstart",R,!0),n.removeEventListener("click",J,!0),n.removeEventListener("keydown",j,!0),n.removeEventListener("keydown",X),o},te=function(L){var pe=L.some(function(Te){var rt=Array.from(Te.removedNodes);return rt.some(function(Ke){return Ke===s.mostRecentlyFocusedNode})});pe&&b(p())},ue=typeof window<"u"&&"MutationObserver"in window?new MutationObserver(te):void 0,ee=function(){ue&&(ue.disconnect(),s.active&&!s.paused&&s.containers.map(function(L){ue.observe(L,{subtree:!0,childList:!0})}))};return o={get active(){return s.active},get paused(){return s.paused},activate:function(L){if(s.active)return this;var pe=u(L,"onActivate"),Te=u(L,"onPostActivate"),rt=u(L,"checkCanFocusTrap");rt||v(),s.active=!0,s.paused=!1,s.nodeFocusedBeforeActivation=m(n),pe==null||pe();var Ke=function(){rt&&v(),V(),ee(),Te==null||Te()};return rt?(rt(s.containers.concat()).then(Ke,Ke),this):(Ke(),this)},deactivate:function(L){if(!s.active)return this;var pe=wy({onDeactivate:a.onDeactivate,onPostDeactivate:a.onPostDeactivate,checkCanReturnFocus:a.checkCanReturnFocus},L);clearTimeout(s.delayInitialFocusTimer),s.delayInitialFocusTimer=void 0,D(),s.active=!1,s.paused=!1,ee(),Sy.deactivateTrap(i,o);var Te=u(pe,"onDeactivate"),rt=u(pe,"onPostDeactivate"),Ke=u(pe,"checkCanReturnFocus"),Se=u(pe,"returnFocus","returnFocusOnDeactivate");Te==null||Te();var ce=function(){Ty(function(){Se&&b(T(s.nodeFocusedBeforeActivation)),rt==null||rt()})};return Se&&Ke?(Ke(T(s.nodeFocusedBeforeActivation)).then(ce,ce),this):(ce(),this)},pause:function(L){return s.active?(s.manuallyPaused=!0,this._setPausedState(!0,L)):this},unpause:function(L){return s.active?(s.manuallyPaused=!1,i[i.length-1]!==this?this:this._setPausedState(!1,L)):this},updateContainerElements:function(L){var pe=[].concat(L).filter(Boolean);return s.containers=pe.map(function(Te){return typeof Te=="string"?n.querySelector(Te):Te}),s.active&&v(),ee(),this}},Object.defineProperties(o,{_isManuallyPaused:{value:function(){return s.manuallyPaused}},_setPausedState:{value:function(L,pe){if(s.paused===L)return this;if(s.paused=L,L){var Te=u(pe,"onPause"),rt=u(pe,"onPostPause");Te==null||Te(),D(),ee(),rt==null||rt()}else{var Ke=u(pe,"onUnpause"),Se=u(pe,"onPostUnpause");Ke==null||Ke(),v(),V(),ee(),Se==null||Se()}return this}}}),o.updateContainerElements(t),o};const aP=`
10
10
  <dialog open class="cobrowse-dialog" data-test-id="cobrowse-dialog" role="alertdialog" aria-labelledby="cobrowse-dialog-title" aria-describedby="cobrowse-dialog-content">
11
11
  <h1 id="cobrowse-dialog-title">$title</h1>
12
12
  <p id="cobrowse-dialog-content" class="cobrowse-dialog_content">$content</p>
@@ -14,10 +14,10 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
14
14
  <button class="cobrowse-dialog_allow js-cobrowse-allow" data-test-id="cobrowse-dialog_allow">$allow</button>
15
15
  <button class="cobrowse-dialog_deny js-cobrowse-deny" data-test-id="cobrowse-dialog_deny">$deny</button>
16
16
  </div>
17
- </dialog>`,UA='<button class="cobrowse-end js-cobrowse-end">$end</button>';class nm{constructor(t,r){ht(this,"_cobrowse");ht(this,"_options");ht(this,"_started",!1);ht(this,"focusTrap");this._cobrowse=t,this._options=r}get root(){return this._options.root||document.body}get lang(){return this._options.lang}get messages(){return this._options.messages}get template(){return this._options.template||FA}static async create(t,r){const n=await BA(r);n.license=t.license;const i=t.trustedOrigins||[];return i.push(location.origin),n.trustedOrigins=i,["api","capabilities","registration","redactedViews","unredactedViews"].forEach(s=>{t[s]!==void 0&&(n[s]=t[s])}),new nm(n,t)}setCustomData(t){this._cobrowse.customData=t}on(t,r){this._cobrowse.on(t,r)}async start(){this._started||(await this._cobrowse.client(),await this._cobrowse.start(),this._started=!0,this.setupConfirms(),this.setupSessionControl())}async stop(){await this._cobrowse.stop(),this._started=!1}async endSession(){this._cobrowse.currentSession&&await this._cobrowse.currentSession.end()}async createSessionCode(){return this._cobrowse.currentSession?this._cobrowse.currentSession.code():await this._cobrowse.createSessionCode()}createConfirmConsent(t){return()=>{const r=document.createElement("div");r.className="cobrowse-wrapper",r.lang=this.lang,r.innerHTML=t;const n=()=>{r.parentNode&&r.parentNode.removeChild(r),this.focusTrap&&(this.focusTrap.deactivate(),this.focusTrap=null)};return new Promise(i=>{this.root.appendChild(r);const a=r.querySelector(".js-cobrowse-allow");a==null||a.addEventListener("click",()=>{i(!0),n()});const s=r.querySelector(".js-cobrowse-deny");s==null||s.addEventListener("click",()=>{i(!1),n()}),this.focusTrap=jA(r,{clickOutsideDeactivates:!0,returnFocusOnDeactivate:!0}),this.focusTrap.activate()})}}setupConfirms(){this._cobrowse.confirmSession=this.createConfirmConsent(sc(this._options.confirmSessionTemplate||this.template,{title:this.messages.confirmSessionTitle,content:this.messages.confirmSessionContent,allow:this.messages.allowText,deny:this.messages.denyText})),this._cobrowse.confirmRemoteControl=this.createConfirmConsent(sc(this._options.confirmRemoteControlTemplate||this.template,{title:this.messages.confirmRemoteControlTitle,content:this.messages.confirmRemoteControlContent,allow:this.messages.allowText,deny:this.messages.denyText})),this._cobrowse.confirmFullDevice=this.createConfirmConsent(sc(this._options.confirmFullDeviceTemplate||this.template,{title:this.messages.confirmFullDeviceTitle,content:this.messages.confirmFullDeviceContent,allow:this.messages.allowText,deny:this.messages.denyText}))}setupSessionControl(){const t=this._options.sessionControlsTemplate||UA,r=document.createElement("div");r.className="cobrowse-end-wrapper",r.setAttribute("lang",this.lang),r.innerHTML=sc(t,{end:this.messages.endSessionText});const n=()=>{this.endSession()};this._cobrowse.showSessionControls=()=>{if(!this.root.contains(r)){const i=r.querySelector(".js-cobrowse-end");i&&i.addEventListener("click",n),this.root.appendChild(r)}},this._cobrowse.hideSessionControls=()=>{if(this.root.contains(r)){const i=r.querySelector(".js-cobrowse-end");i&&i.removeEventListener("click",n),this.root.removeChild(r)}}}}function BA(e){return window.CobrowseIO?window.CobrowseIO:new Promise(t=>{const r=document.createElement("script");r.src=e,r.async=!0;const n=document.getElementsByTagName("script")[0];n.parentNode.insertBefore(r,n),r.onload=function(){t(window.CobrowseIO)}})}function sc(e,t){let r=e;return Object.keys(t).forEach(n=>{const i=new RegExp("\\$"+n,"g");r=r.replace(i,t[n])}),r}const qA={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"},zA={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"},WA={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"},GA={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"},HA={confirmSessionTitle:"共同ブラウジングセッションリクエスト",confirmSessionContent:"現在の画面を担当者と共有したいですか。",endSessionText:"共同ブラウジングセッションを終了",confirmRemoteControlTitle:"リモートアクセスリクエスト",confirmRemoteControlContent:"担当者は、お客様をさらにお手伝いするために、現在共有中の画面へのアクセスを希望しています。許可しますか。",confirmFullDeviceTitle:"画面共有リクエスト",confirmFullDeviceContent:"画面全体を担当者と共有したいですか。担当者は画面上で一切の操作ができません。",allowText:"許可",denyText:"拒否"},VA={confirmSessionTitle:"코브라우징 세션 요청",confirmSessionContent:"현재 화면을 상담원과 공유하시겠습니까?",endSessionText:"코브라우징 세션 종료",confirmRemoteControlTitle:"원격 액세스 요청",confirmRemoteControlContent:"상담원이 추가 지원을 위해 현재 공유된 화면에 액세스할 수 있기를 원합니다. 허용하시겠습니까?",confirmFullDeviceTitle:"화면 공유 요청",confirmFullDeviceContent:"상담원과 전체 화면을 공유하시겠습니까? 상담원은 화면의 어떤 부분도 제어할 수 없습니다.",allowText:"허용",denyText:"거절"},KA={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"},JA={confirmSessionTitle:"同步浏览会话请求",confirmSessionContent:"您是否要向该客服代表共享当前的屏幕?",endSessionText:"结束同步浏览会话",confirmRemoteControlTitle:"远程访问请求",confirmRemoteControlContent:"为了进一步协助您,客服代表想访问您当前的共享屏幕。您是否允许这样做?",confirmFullDeviceTitle:"屏幕共享请求",confirmFullDeviceContent:"您是否要向该客服代表共享全屏?客服代表将不能控制屏幕上的任何东西。",allowText:"允许",denyText:"拒绝"},YA={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"},XA={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"},QA={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ä"},ZA={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"},eP={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"},tP={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"},rP={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"},nP={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"},iP={confirmSessionTitle:"ขอเซสชันเรียกดูร่วม",confirmSessionContent:"คุณต้องการแชร์หน้าจอปัจจุบันกับตัวแทนหรือไม่",endSessionText:"สิ้นสุดเซสชันเรียกดูร่วม",confirmRemoteControlTitle:"ขอการเข้าถึงระยะไกล",confirmRemoteControlContent:"ตัวแทนต้องการเข้าถึงหน้าจอของคุณที่แชร์อยู่ในปัจจุบันเพื่อให้ความช่วยเหลือคุณต่อไป คุณจะอนุญาตหรือไม่",confirmFullDeviceTitle:"ขอแชร์หน้าจอ",confirmFullDeviceContent:"คุณต้องการแชร์ทั้งหน้าของคุณกับตัวแทนหรือไม่ ตัวแทนจะไม่สามารถควบคุมอะไรบนหน้าจอ",allowText:"ยินยอม",denyText:"ปฏิเสธ"},aP={confirmSessionTitle:"طلب جلسة تصفح مشترك",confirmSessionContent:"هل تريد مشاركة شاشتك الحالية مع الموظف؟",endSessionText:"إنهاء جلسة التصفح المشترك",confirmRemoteControlTitle:"طلب التحكم عن بعد",confirmRemoteControlContent:"يرغب مسئول الدعم في رؤية شاشتك المشاركة حالياً لمساعدتك بشكلٍ أكبر. هل تسمح بذلك؟",confirmFullDeviceTitle:"طلب مشاركة الشاشة",confirmFullDeviceContent:"هل تريد مشاركة شاشتك الكاملة مع مسئول الدعم؟ لن يتمكن المسئول من التحكم في أي شيء على الشاشة.",allowText:"السماح",denyText:"الرفض"},sP={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"},oP={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"},uP={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"},cP={confirmSessionTitle:"Запрос сеанса совместного просмотра веб-страниц",confirmSessionContent:"Хотите поделиться вашим текущим экраном с представителем?",endSessionText:"Завершить сеанс совместного просмотра веб-страниц",confirmRemoteControlTitle:"Запрос на удаленный доступ",confirmRemoteControlContent:"Представитель хочет получить доступ к вашему текущему экрану, которым вы делитесь, чтобы помочь вам. Хотите разрешить это?",confirmFullDeviceTitle:"Запрос на совместный просмотр экрана",confirmFullDeviceContent:"Хотите поделиться вашим полный экраном с представителем? Агент не сможет выполнять никаких действий на экране.",allowText:"Разрешить",denyText:"Отказать"},lP={confirmSessionTitle:"सह-ब्राउज़ सत्र अनुरोध किया गया",confirmSessionContent:"क्या आप अपनी वर्तमान स्क्रीन को एजेंट के साथ साझा करना चाहते हैं?",endSessionText:"सह-ब्राउज़ सत्र समाप्त करें",confirmRemoteControlTitle:"रिमोट पहुँच का अनुरोध किया गया",confirmRemoteControlContent:"एजेंट आपकी वर्तमान साझा स्क्रीन तक पहुँच प्राप्त करना चाहेगा ताकि वह आपकी और सहायता कर सके। क्या आप इसकी अनुमति देना चाहते हैं?",confirmFullDeviceTitle:"स्क्रीन साझाकरण अनुरोध",confirmFullDeviceContent:"क्या आप अपनी पूरी स्क्रीन एजेंट के साथ साझा करना चाहते हैं? एजेंट स्क्रीन पर कुछ भी नियंत्रित नहीं कर पाएगा।",allowText:"अनुमति दें",denyText:"अस्वीकार करें"},fP={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"},dP={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"},pP={confirmSessionTitle:"Запит на сесію спільного перегляду",confirmSessionContent:"Чи Ви хочете поділитись з агентом своїм поточним екраном?",endSessionText:"Завершити сесію спільного перегляду",confirmRemoteControlTitle:"Запит на віддалений доступ",confirmRemoteControlContent:"Агент хоче отримати доступ до Вашого поточного екрану, який переглядається спільно, щоб допомогти Вам. Ви дозволяєте?",confirmFullDeviceTitle:"Запит на спільний перегляд екрану",confirmFullDeviceContent:"Чи Ви хочете поділитись з агентом своїм екраном повністю? Агент не зможе нічого на ньому контролювати.",allowText:"Дозволити",denyText:"Відмовити"},hP={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"},Mo={en:qA,es:zA,"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:WA,"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:GA,ja:HA,ko:VA,it:KA,zh:JA,"zh-Hant":{confirmSessionTitle:"共同瀏覽工作階段要求",confirmSessionContent:"要與專員分享您目前的畫面嗎?",endSessionText:"結束共同瀏覽工作階段",confirmRemoteControlTitle:"遠端存取要求",confirmRemoteControlContent:"專員想要存取您目前分享的螢幕畫面以進一步協助您。要允許嗎?",confirmFullDeviceTitle:"螢幕畫面分享要求",confirmFullDeviceContent:"要與專員分享全螢幕嗎?專員將無法控制畫面上的任何項目。",allowText:"允許",denyText:"拒絕"},sv:YA,pt:XA,"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:QA,nb:ZA,da:eP,nl:tP,tr:rP,vi:nP,th:iP,ar:aP,cs:sP,pl:oP,hu:uP,ru:cP,hi:lP,ro:fP,hr:dP,uk:pP,tl:hP};function vP(e){const t=e.split("-")[0];return Mo[e]?e===t?Mo[e]:{...Mo[t],...Mo[e]}:Mo[t]}const mP=["photo","video","audio","document"];let gP=class{constructor(t){ht(this,"VERSION",Qv);ht(this,"options");ht(this,"communicator");ht(this,"methods");ht(this,"events",new em);ht(this,"request");ht(this,"chat");ht(this,"cobrowse");this.options=t,this.communicator=new PO(t,this.events);const r=this.communicator.request.bind(this.communicator);this.methods=new QO(r),this.request=r,t.host&&ET.setPath(t.host),Br.companyId=t.companyId,t.tenant&&(Br.tenant=t.tenant)}get deviceId(){return Br.deviceId}get user(){return this.communicator.user}get lang(){return this.options.lang?this.options.lang:Kr.get("lang")||"en"}set lang(t){this.options.lang||Kr.set("lang",t)}destroy(){this.communicator.destroy(),this.events.destroy()}on(t,r){this.events.addEventListener(t,r)}off(t,r){this.events.removeEventListener(t,r)}_triggerEvent(t,r){this.events.triggerEvent(t,r)}async getCompany(){const t=await this.methods.getCompany();return Br.tenant=t.subdomain,t}async runTrigger(t){const r=await this.methods.getTriggers(this.options.companyId),n=tA(r);n&&rA(n,t)}trackClientEvents(t){return this.methods.trackClientEvents(t)}getProhibitedFileTypes(){return this.methods.listFileTypes()}getMenus(t,r){return this.methods.getMenus(r||this.lang,t)}getAfterHourMessage(t){return this.methods.getAfterHourMessage(t||this.lang)}getTimeSlots(t,r){return this.methods.getTimeSlots(t,r||this.lang)}getWaitTimes(t,r){return this.methods.getWaitTimes(t,r||this.lang)}verifyForm(t){return this.methods.verifyForm(t)}createCall(t,r){var n;return!r.email&&((n=this.user)!=null&&n.email)&&(r.email=this.user.email),this.methods.createCall(Number(t),r.lang||this.lang,r)}loadCall(t){return this.methods.fetchCall(t)}cancelCall(t){return this.methods.cancelCall(t)}createEmail(t,r){return this.methods.createEmail(t,r.lang||this.lang,r)}async createChat(t,r={}){var i,a;if(this.chat&&this.chat.ongoing)throw new Error("There is an ongoing chat.");!r.email&&((i=this.user)!=null&&i.email)&&(r.email=this.user.email),r.cobrowsable===void 0&&(r.cobrowsable=!!((a=this.options.cobrowse)!=null&&a.enabled));const n=await this.methods.createChat(Number(t),r.lang||this.lang,r,this.deviceId);return this.registerOngoingChat(n),await n.clearMediaStore(),n}async loadChat(t){const r=await this.methods.loadChat(t,this.deviceId);return r.ongoing?this.registerOngoingChat(r):(Kr.del("chat"),Kr.del("cobrowse")),r}async resumeChat(t){var r;if(((r=this.chat)==null?void 0:r.id)===Number(t)){const n=await this.methods.patch(`chats/${t}`,{status:"queued"});return this.chat.update(n.data),this.chat}else{const n=await this.methods.resumeChat(t,this.deviceId);return this.registerOngoingChat(n),n}}async loadOngoingChat(){const t=Kr.get("chat");if(t){const r=await this.loadChat(t);if(r.ongoing)return r;Kr.del("chat")}}async finishChat(){if(!this.chat)return;const t=await this.methods.finishChat(this.chat.id);this.chat.update(t),this.chat.connected&&this.chat.ended&&await this.chat.disconnect()}async updatePostSession(t){if(!this.chat||t===to.FINISHED||t===to.WAITING)return;const r=await this.methods.updatePostSession(this.chat.id,t);this.chat.update(r)}async destroyChat(){if(this.chat){if(this.chat.muted=!0,this.chat.ongoing){const t=await this.methods.finishChat(this.chat.id);this.chat.update(t)}await this.chat.destroy(),this.chat=null,Br.trackerId=""}}getChatDeflection(){return this.methods.getChatDeflection(this.chat.id)}sendChatTranscripts(t){return this.methods.sendChatTranscripts(this.chat.id,t)}async downloadChatTranscript(){return await this.methods.downloadChatTranscript(this.chat.id)}async getPdfStatus(t){return await this.methods.getPdfStatus(t)}getChatSurvey(){return this.methods.getChatSurvey(this.chat.id)}sendChatSurvey(t){if(this.chat.feedbackType!=="survey")throw new Error("Chat feedback type is: "+this.chat.feedbackType);return this.methods.sendChatSurvey(this.chat.id,t)}sendChatRate(t){if(this.chat.feedbackType!=="rate")throw new Error("Chat feedback type is: "+this.chat.feedbackType);return this.methods.rateChat(this.chat.id,t)}escalateChat(t){return this.methods.escalateChat(this.chat.id,t)}trackChatEscalation(t,r){return this.methods.trackEscalation(this.chat.id,t,r)}trackChatEndUserEvent(t){var r;return!t.end_user_name&&((r=this.user)!=null&&r.name)&&(t.end_user_name=this.user.name),this.methods.trackChatEndUserEvent(this.chat.id,t)}getChatHistory(t=1){return this.methods.getChatHistory(t)}async fetchMessages(){const t=await this.chat.fetchMessages();if(t.filter(r=>r.type==="server_message").length>0){const r=await this.methods.listChatTaskMessages(this.chat.id);return xO(t,r)}return t}async sendFileMessage(t){const r=await this.methods.uploadChatFile(this.chat.id,t);return this.chat.sendMessage(r,t)}async sendTextMessage(t){const r=ST(t);if(r){if(this.chat.inTask){const n=await this.methods.sendChatTaskMessage(this.chat.id,r);this.chat.sendMessage({type:"server_message",visibility:"task_virtual_agent",message_id:n.id});return}if(this.chat.state.redaction_enabled){await this.methods.sendChatTextMessage(this.chat.id,r);return}this.chat.sendMessage({type:"text",content:r})}}async sendPreviewMessage(t){try{if(this.isRedactionAgentEnabled()){const r=new Date().toISOString(),n=await this.methods.sendPreviewMessage(this.chat.id,t,r);return this.chat.preview(n==null?void 0:n.content)}return this.chat.preview(t)}catch(r){console.error("Error sending preview message:",r)}}isRedactionAgentEnabled(){return this.chat.state.redaction_enabled&&this.chat.state.agent_incoming_ha_enabled}async createCobrowseCode(t,r){var a;await this.initializeCobrowse(t||this.lang);let n=Kr.get("cobrowse");n||(n=Date.now().toString(),Kr.set("cobrowse",n));const i={device_id:this.deviceId,device_name:`${Br.application} / ${Br.version}`,nonce:n,...r};return(a=this.user)!=null&&a.name&&(i.user_name=this.user.name),this.cobrowse.setCustomData(i),this.cobrowse.createSessionCode()}async startCobrowse(t="end_user"){if(!this.chat.cobrowsable)throw new Error(`Chat ${this.chat.id} does not support cobrowse.`);const r={chatId:`chat_${this.chat.id}`},n=await this.createCobrowseCode(this.chat.lang,r);if(n){const i=Kr.get("cobrowse");await this.methods.requestChatCobrowse(this.chat.id,{code:n,from:t,nonce:i})}}async getMessageAttachment(t){if(t.$userType!=="end_user"&&mP.includes(t.type)){const r=await this.methods.getMedia(t.media_id,t.type);return this.chat&&this.chat.saveMedia(t.$index,r),r}return null}async initializeCobrowse(t){if(!this.cobrowse){const r=await this.getCompany(),n=this.getCobrowseScript(r.cobrowse_domain),i=this.options.cobrowse.messages||vP(t),a={...this.options.cobrowse,messages:i,lang:t};this.cobrowse=await nm.create(a,n),this.cobrowse.start(),["loaded","updated","ended"].forEach(o=>{this.cobrowse.on(`session.${o}`,u=>{this.events.triggerEvent(`cobrowse.${o}`,u)})})}}registerOngoingChat(t){this.events.triggerEvent("chat.ongoing",t),t._setGlobalEvents(this.events,this.methods.getChatTaskMessage.bind(this.methods)),t.on("_requestCobrowse",r=>{r==="agent"?this.startCobrowse(r):this.initializeCobrowse(t.lang),this.events.triggerEvent("cobrowse.request",{from:r})}),t.on("disconnected",()=>{Kr.del("chat"),Kr.del("cobrowse")}),this.chat=t,Br.trackerId=`chat_${t.id}`,Kr.set("chat",t.id.toString()),t.cobrowsable&&Kr.get("cobrowse")&&this.initializeCobrowse(t.lang)}getCobrowseScript(t){return!t||t.toLowerCase()==="https://cobrowse.io"?"https://js.cobrowse.io/CobrowseIO.js":`${t}/sdk-js/CobrowseIO.js`}};var je=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function jT(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function FT(e){if(e.__esModule)return e;var t=e.default;if(typeof t=="function"){var r=function n(){return this instanceof n?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(n){var i=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(r,n,i.get?i:{enumerable:!0,get:function(){return e[n]}})}),r}var UT={},xo=function(e){return e&&e.Math===Math&&e},$t=xo(typeof globalThis=="object"&&globalThis)||xo(typeof window=="object"&&window)||xo(typeof self=="object"&&self)||xo(typeof je=="object"&&je)||xo(typeof je=="object"&&je)||function(){return this}()||Function("return this")(),Ji={},yt=function(e){try{return!!e()}catch{return!0}},yP=yt,er=!yP(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7}),bP=yt,_u=!bP(function(){var e=(function(){}).bind();return typeof e!="function"||e.hasOwnProperty("prototype")}),_P=_u,oc=Function.prototype.call,Yt=_P?oc.bind(oc):function(){return oc.apply(oc,arguments)},wu={},BT={}.propertyIsEnumerable,qT=Object.getOwnPropertyDescriptor,wP=qT&&!BT.call({1:2},1);wu.f=wP?function(t){var r=qT(this,t);return!!r&&r.enumerable}:BT;var ls=function(e,t){return{enumerable:!(e&1),configurable:!(e&2),writable:!(e&4),value:t}},zT=_u,WT=Function.prototype,yh=WT.call,SP=zT&&WT.bind.bind(yh,yh),wt=zT?SP:function(e){return function(){return yh.apply(e,arguments)}},GT=wt,TP=GT({}.toString),CP=GT("".slice),wi=function(e){return CP(TP(e),8,-1)},EP=wt,kP=yt,RP=wi,dd=Object,$P=EP("".split),Su=kP(function(){return!dd("z").propertyIsEnumerable(0)})?function(e){return RP(e)==="String"?$P(e,""):dd(e)}:dd,ai=function(e){return e==null},IP=ai,OP=TypeError,si=function(e){if(IP(e))throw new OP("Can't call method on "+e);return e},AP=Su,PP=si,Cn=function(e){return AP(PP(e))},pd=typeof document=="object"&&document.all,Xt=typeof pd>"u"&&pd!==void 0?function(e){return typeof e=="function"||e===pd}:function(e){return typeof e=="function"},MP=Xt,ar=function(e){return typeof e=="object"?e!==null:MP(e)},hd=$t,xP=Xt,NP=function(e){return xP(e)?e:void 0},Un=function(e,t){return arguments.length<2?NP(hd[e]):hd[e]&&hd[e][t]},LP=wt,Yi=LP({}.isPrototypeOf),DP=$t,Cy=DP.navigator,Ey=Cy&&Cy.userAgent,Ia=Ey?String(Ey):"",HT=$t,vd=Ia,ky=HT.process,Ry=HT.Deno,$y=ky&&ky.versions||Ry&&Ry.version,Iy=$y&&$y.v8,Zn,Nl;Iy&&(Zn=Iy.split("."),Nl=Zn[0]>0&&Zn[0]<4?1:+(Zn[0]+Zn[1]));!Nl&&vd&&(Zn=vd.match(/Edge\/(\d+)/),(!Zn||Zn[1]>=74)&&(Zn=vd.match(/Chrome\/(\d+)/),Zn&&(Nl=+Zn[1])));var po=Nl,Oy=po,jP=yt,FP=$t,UP=FP.String,ho=!!Object.getOwnPropertySymbols&&!jP(function(){var e=Symbol("symbol detection");return!UP(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&Oy&&Oy<41}),BP=ho,VT=BP&&!Symbol.sham&&typeof Symbol.iterator=="symbol",qP=Un,zP=Xt,WP=Yi,GP=VT,HP=Object,vo=GP?function(e){return typeof e=="symbol"}:function(e){var t=qP("Symbol");return zP(t)&&WP(t.prototype,HP(e))},VP=String,fs=function(e){try{return VP(e)}catch{return"Object"}},KP=Xt,JP=fs,YP=TypeError,Bn=function(e){if(KP(e))return e;throw new YP(JP(e)+" is not a function")},XP=Bn,QP=ai,ds=function(e,t){var r=e[t];return QP(r)?void 0:XP(r)},md=Yt,gd=Xt,yd=ar,ZP=TypeError,eM=function(e,t){var r,n;if(t==="string"&&gd(r=e.toString)&&!yd(n=md(r,e))||gd(r=e.valueOf)&&!yd(n=md(r,e))||t!=="string"&&gd(r=e.toString)&&!yd(n=md(r,e)))return n;throw new ZP("Can't convert object to primitive value")},KT={exports:{}},JT=!1,Ay=$t,tM=Object.defineProperty,im=function(e,t){try{tM(Ay,e,{value:t,configurable:!0,writable:!0})}catch{Ay[e]=t}return t},rM=$t,nM=im,Py="__core-js_shared__",My=KT.exports=rM[Py]||nM(Py,{});(My.versions||(My.versions=[])).push({version:"3.39.0",mode:"global",copyright:"© 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.39.0/LICENSE",source:"https://github.com/zloirock/core-js"});var am=KT.exports,xy=am,mo=function(e,t){return xy[e]||(xy[e]=t||{})},iM=si,aM=Object,Jr=function(e){return aM(iM(e))},sM=wt,oM=Jr,uM=sM({}.hasOwnProperty),vr=Object.hasOwn||function(t,r){return uM(oM(t),r)},cM=wt,lM=0,fM=Math.random(),dM=cM(1 .toString),Tu=function(e){return"Symbol("+(e===void 0?"":e)+")_"+dM(++lM+fM,36)},pM=$t,hM=mo,Ny=vr,vM=Tu,mM=ho,gM=VT,Fs=pM.Symbol,bd=hM("wks"),yM=gM?Fs.for||Fs:Fs&&Fs.withoutSetter||vM,Qt=function(e){return Ny(bd,e)||(bd[e]=mM&&Ny(Fs,e)?Fs[e]:yM("Symbol."+e)),bd[e]},bM=Yt,Ly=ar,Dy=vo,_M=ds,wM=eM,SM=Qt,TM=TypeError,CM=SM("toPrimitive"),sm=function(e,t){if(!Ly(e)||Dy(e))return e;var r=_M(e,CM),n;if(r){if(t===void 0&&(t="default"),n=bM(r,e,t),!Ly(n)||Dy(n))return n;throw new TM("Can't convert object to primitive value")}return t===void 0&&(t="number"),wM(e,t)},EM=sm,kM=vo,nf=function(e){var t=EM(e,"string");return kM(t)?t:t+""},RM=$t,jy=ar,bh=RM.document,$M=jy(bh)&&jy(bh.createElement),af=function(e){return $M?bh.createElement(e):{}},IM=er,OM=yt,AM=af,YT=!IM&&!OM(function(){return Object.defineProperty(AM("div"),"a",{get:function(){return 7}}).a!==7}),PM=er,MM=Yt,xM=wu,NM=ls,LM=Cn,DM=nf,jM=vr,FM=YT,Fy=Object.getOwnPropertyDescriptor;Ji.f=PM?Fy:function(t,r){if(t=LM(t),r=DM(r),FM)try{return Fy(t,r)}catch{}if(jM(t,r))return NM(!MM(xM.f,t,r),t[r])};var nn={},UM=er,BM=yt,XT=UM&&BM(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42}),qM=ar,zM=String,WM=TypeError,wr=function(e){if(qM(e))return e;throw new WM(zM(e)+" is not an object")},GM=er,HM=YT,VM=XT,uc=wr,Uy=nf,KM=TypeError,_d=Object.defineProperty,JM=Object.getOwnPropertyDescriptor,wd="enumerable",Sd="configurable",Td="writable";nn.f=GM?VM?function(t,r,n){if(uc(t),r=Uy(r),uc(n),typeof t=="function"&&r==="prototype"&&"value"in n&&Td in n&&!n[Td]){var i=JM(t,r);i&&i[Td]&&(t[r]=n.value,n={configurable:Sd in n?n[Sd]:i[Sd],enumerable:wd in n?n[wd]:i[wd],writable:!1})}return _d(t,r,n)}:_d:function(t,r,n){if(uc(t),r=Uy(r),uc(n),HM)try{return _d(t,r,n)}catch{}if("get"in n||"set"in n)throw new KM("Accessors not supported");return"value"in n&&(t[r]=n.value),t};var YM=er,XM=nn,QM=ls,Xi=YM?function(e,t,r){return XM.f(e,t,QM(1,r))}:function(e,t,r){return e[t]=r,e},QT={exports:{}},_h=er,ZM=vr,ZT=Function.prototype,ex=_h&&Object.getOwnPropertyDescriptor,om=ZM(ZT,"name"),tx=om&&(function(){}).name==="something",rx=om&&(!_h||_h&&ex(ZT,"name").configurable),Cu={EXISTS:om,PROPER:tx,CONFIGURABLE:rx},nx=wt,ix=Xt,wh=am,ax=nx(Function.toString);ix(wh.inspectSource)||(wh.inspectSource=function(e){return ax(e)});var um=wh.inspectSource,sx=$t,ox=Xt,By=sx.WeakMap,ux=ox(By)&&/native code/.test(String(By)),cx=mo,lx=Tu,qy=cx("keys"),sf=function(e){return qy[e]||(qy[e]=lx(e))},Eu={},fx=ux,eC=$t,dx=ar,px=Xi,Cd=vr,Ed=am,hx=sf,vx=Eu,zy="Object already initialized",Sh=eC.TypeError,mx=eC.WeakMap,Ll,fu,Dl,gx=function(e){return Dl(e)?fu(e):Ll(e,{})},yx=function(e){return function(t){var r;if(!dx(t)||(r=fu(t)).type!==e)throw new Sh("Incompatible receiver, "+e+" required");return r}};if(fx||Ed.state){var pi=Ed.state||(Ed.state=new mx);pi.get=pi.get,pi.has=pi.has,pi.set=pi.set,Ll=function(e,t){if(pi.has(e))throw new Sh(zy);return t.facade=e,pi.set(e,t),t},fu=function(e){return pi.get(e)||{}},Dl=function(e){return pi.has(e)}}else{var ks=hx("state");vx[ks]=!0,Ll=function(e,t){if(Cd(e,ks))throw new Sh(zy);return t.facade=e,px(e,ks,t),t},fu=function(e){return Cd(e,ks)?e[ks]:{}},Dl=function(e){return Cd(e,ks)}}var En={set:Ll,get:fu,has:Dl,enforce:gx,getterFor:yx},cm=wt,bx=yt,_x=Xt,cc=vr,Th=er,wx=Cu.CONFIGURABLE,Sx=um,tC=En,Tx=tC.enforce,Cx=tC.get,Wy=String,hl=Object.defineProperty,Ex=cm("".slice),kx=cm("".replace),Rx=cm([].join),$x=Th&&!bx(function(){return hl(function(){},"length",{value:8}).length!==8}),Ix=String(String).split("String"),Ox=QT.exports=function(e,t,r){Ex(Wy(t),0,7)==="Symbol("&&(t="["+kx(Wy(t),/^Symbol\(([^)]*)\).*$/,"$1")+"]"),r&&r.getter&&(t="get "+t),r&&r.setter&&(t="set "+t),(!cc(e,"name")||wx&&e.name!==t)&&(Th?hl(e,"name",{value:t,configurable:!0}):e.name=t),$x&&r&&cc(r,"arity")&&e.length!==r.arity&&hl(e,"length",{value:r.arity});try{r&&cc(r,"constructor")&&r.constructor?Th&&hl(e,"prototype",{writable:!1}):e.prototype&&(e.prototype=void 0)}catch{}var n=Tx(e);return cc(n,"source")||(n.source=Rx(Ix,typeof t=="string"?t:"")),e};Function.prototype.toString=Ox(function(){return _x(this)&&Cx(this).source||Sx(this)},"toString");var rC=QT.exports,Ax=Xt,Px=nn,Mx=rC,xx=im,an=function(e,t,r,n){n||(n={});var i=n.enumerable,a=n.name!==void 0?n.name:t;if(Ax(r)&&Mx(r,a,n),n.global)i?e[t]=r:xx(t,r);else{try{n.unsafe?e[t]&&(i=!0):delete e[t]}catch{}i?e[t]=r:Px.f(e,t,{value:r,enumerable:!1,configurable:!n.nonConfigurable,writable:!n.nonWritable})}return e},ps={},Nx=Math.ceil,Lx=Math.floor,Dx=Math.trunc||function(t){var r=+t;return(r>0?Lx:Nx)(r)},jx=Dx,Si=function(e){var t=+e;return t!==t||t===0?0:jx(t)},Fx=Si,Ux=Math.max,Bx=Math.min,hs=function(e,t){var r=Fx(e);return r<0?Ux(r+t,0):Bx(r,t)},qx=Si,zx=Math.min,Qi=function(e){var t=qx(e);return t>0?zx(t,9007199254740991):0},Wx=Qi,Yr=function(e){return Wx(e.length)},Gx=Cn,Hx=hs,Vx=Yr,Gy=function(e){return function(t,r,n){var i=Gx(t),a=Vx(i);if(a===0)return!e&&-1;var s=Hx(n,a),o;if(e&&r!==r){for(;a>s;)if(o=i[s++],o!==o)return!0}else for(;a>s;s++)if((e||s in i)&&i[s]===r)return e||s||0;return!e&&-1}},of={includes:Gy(!0),indexOf:Gy(!1)},Kx=wt,kd=vr,Jx=Cn,Yx=of.indexOf,Xx=Eu,Hy=Kx([].push),nC=function(e,t){var r=Jx(e),n=0,i=[],a;for(a in r)!kd(Xx,a)&&kd(r,a)&&Hy(i,a);for(;t.length>n;)kd(r,a=t[n++])&&(~Yx(i,a)||Hy(i,a));return i},lm=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Qx=nC,Zx=lm,eN=Zx.concat("length","prototype");ps.f=Object.getOwnPropertyNames||function(t){return Qx(t,eN)};var ku={};ku.f=Object.getOwnPropertySymbols;var tN=Un,rN=wt,nN=ps,iN=ku,aN=wr,sN=rN([].concat),iC=tN("Reflect","ownKeys")||function(t){var r=nN.f(aN(t)),n=iN.f;return n?sN(r,n(t)):r},Vy=vr,oN=iC,uN=Ji,cN=nn,fm=function(e,t,r){for(var n=oN(t),i=cN.f,a=uN.f,s=0;s<n.length;s++){var o=n[s];!Vy(e,o)&&!(r&&Vy(r,o))&&i(e,o,a(t,o))}},lN=yt,fN=Xt,dN=/#|\.prototype\./,Ru=function(e,t){var r=hN[pN(e)];return r===mN?!0:r===vN?!1:fN(t)?lN(t):!!t},pN=Ru.normalize=function(e){return String(e).replace(dN,".").toLowerCase()},hN=Ru.data={},vN=Ru.NATIVE="N",mN=Ru.POLYFILL="P",uf=Ru,lc=$t,gN=Ji.f,yN=Xi,bN=an,_N=im,wN=fm,SN=uf,Ct=function(e,t){var r=e.target,n=e.global,i=e.stat,a,s,o,u,c,l;if(n?s=lc:i?s=lc[r]||_N(r,{}):s=lc[r]&&lc[r].prototype,s)for(o in t){if(c=t[o],e.dontCallGetSet?(l=gN(s,o),u=l&&l.value):u=s[o],a=SN(n?o:r+(i?".":"#")+o,e.forced),!a&&u!==void 0){if(typeof c==typeof u)continue;wN(c,u)}(e.sham||u&&u.sham)&&yN(c,"sham",!0),bN(s,o,c,e)}},TN=nn.f,CN=vr,EN=Qt,Ky=EN("toStringTag"),Ti=function(e,t,r){e&&!r&&(e=e.prototype),e&&!CN(e,Ky)&&TN(e,Ky,{configurable:!0,value:t})},kN=Ct,RN=$t,$N=Ti;kN({global:!0},{Reflect:{}});$N(RN.Reflect,"Reflect",!0);var IN=_u,aC=Function.prototype,Jy=aC.apply,Yy=aC.call,vs=typeof Reflect=="object"&&Reflect.apply||(IN?Yy.bind(Jy):function(){return Yy.apply(Jy,arguments)}),ON=wt,Ci=ON([].slice),sC=wt,AN=Bn,PN=ar,MN=vr,Xy=Ci,xN=_u,oC=Function,NN=sC([].concat),LN=sC([].join),Rd={},DN=function(e,t,r){if(!MN(Rd,t)){for(var n=[],i=0;i<t;i++)n[i]="a["+i+"]";Rd[t]=oC("C,a","return new C("+LN(n,",")+")")}return Rd[t](e,r)},jN=xN?oC.bind:function(t){var r=AN(this),n=r.prototype,i=Xy(arguments,1),a=function(){var o=NN(i,Xy(arguments));return this instanceof a?DN(r,o.length,o):r.apply(t,o)};return PN(n)&&(a.prototype=n),a},FN=Qt,UN=FN("toStringTag"),uC={};uC[UN]="z";var dm=String(uC)==="[object z]",BN=dm,qN=Xt,vl=wi,zN=Qt,WN=zN("toStringTag"),GN=Object,HN=vl(function(){return arguments}())==="Arguments",VN=function(e,t){try{return e[t]}catch{}},Zi=BN?vl:function(e){var t,r,n;return e===void 0?"Undefined":e===null?"Null":typeof(r=VN(t=GN(e),WN))=="string"?r:HN?vl(t):(n=vl(t))==="Object"&&qN(t.callee)?"Arguments":n},KN=wt,JN=yt,cC=Xt,YN=Zi,XN=Un,QN=um,lC=function(){},fC=XN("Reflect","construct"),pm=/^\s*(?:class|function)\b/,ZN=KN(pm.exec),eL=!pm.test(lC),No=function(t){if(!cC(t))return!1;try{return fC(lC,[],t),!0}catch{return!1}},dC=function(t){if(!cC(t))return!1;switch(YN(t)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return eL||!!ZN(pm,QN(t))}catch{return!0}};dC.sham=!0;var cf=!fC||JN(function(){var e;return No(No.call)||!No(Object)||!No(function(){e=!0})||e})?dC:No,tL=cf,rL=fs,nL=TypeError,hm=function(e){if(tL(e))return e;throw new nL(rL(e)+" is not a constructor")},vm={},iL=nC,aL=lm,$u=Object.keys||function(t){return iL(t,aL)},sL=er,oL=XT,uL=nn,cL=wr,lL=Cn,fL=$u;vm.f=sL&&!oL?Object.defineProperties:function(t,r){cL(t);for(var n=lL(r),i=fL(r),a=i.length,s=0,o;a>s;)uL.f(t,o=i[s++],n[o]);return t};var dL=Un,pC=dL("document","documentElement"),pL=wr,hL=vm,Qy=lm,vL=Eu,mL=pC,gL=af,yL=sf,Zy=">",eb="<",Ch="prototype",Eh="script",hC=yL("IE_PROTO"),$d=function(){},vC=function(e){return eb+Eh+Zy+e+eb+"/"+Eh+Zy},tb=function(e){e.write(vC("")),e.close();var t=e.parentWindow.Object;return e=null,t},bL=function(){var e=gL("iframe"),t="java"+Eh+":",r;return e.style.display="none",mL.appendChild(e),e.src=String(t),r=e.contentWindow.document,r.open(),r.write(vC("document.F=Object")),r.close(),r.F},fc,ml=function(){try{fc=new ActiveXObject("htmlfile")}catch{}ml=typeof document<"u"?document.domain&&fc?tb(fc):bL():tb(fc);for(var e=Qy.length;e--;)delete ml[Ch][Qy[e]];return ml()};vL[hC]=!0;var Oa=Object.create||function(t,r){var n;return t!==null?($d[Ch]=pL(t),n=new $d,$d[Ch]=null,n[hC]=t):n=ml(),r===void 0?n:hL.f(n,r)},_L=Ct,wL=Un,Id=vs,SL=jN,rb=hm,TL=wr,nb=ar,CL=Oa,mC=yt,mm=wL("Reflect","construct"),EL=Object.prototype,kL=[].push,gC=mC(function(){function e(){}return!(mm(function(){},[],e)instanceof e)}),yC=!mC(function(){mm(function(){})}),ib=gC||yC;_L({target:"Reflect",stat:!0,forced:ib,sham:ib},{construct:function(t,r){rb(t),TL(r);var n=arguments.length<3?t:rb(arguments[2]);if(yC&&!gC)return mm(t,r,n);if(t===n){switch(r.length){case 0:return new t;case 1:return new t(r[0]);case 2:return new t(r[0],r[1]);case 3:return new t(r[0],r[1],r[2]);case 4:return new t(r[0],r[1],r[2],r[3])}var i=[null];return Id(kL,i,r),new(Id(SL,t,i))}var a=n.prototype,s=CL(nb(a)?a:EL),o=Id(t,s,r);return nb(o)?o:s}});var RL=Ct,$L=Jr,bC=$u,IL=yt,OL=IL(function(){bC(1)});RL({target:"Object",stat:!0,forced:OL},{keys:function(t){return bC($L(t))}});var AL=Zi,PL=String,Lr=function(e){if(AL(e)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return PL(e)},gm={},ML=wi,xL=Cn,_C=ps.f,NL=Ci,wC=typeof window=="object"&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],LL=function(e){try{return _C(e)}catch{return NL(wC)}};gm.f=function(t){return wC&&ML(t)==="Window"?LL(t):_C(xL(t))};var ab=rC,DL=nn,Ei=function(e,t,r){return r.get&&ab(r.get,t,{getter:!0}),r.set&&ab(r.set,t,{setter:!0}),DL.f(e,t,r)},ym={},jL=Qt;ym.f=jL;var FL=$t,SC=FL,sb=SC,UL=vr,BL=ym,qL=nn.f,TC=function(e){var t=sb.Symbol||(sb.Symbol={});UL(t,e)||qL(t,e,{value:BL.f(e)})},zL=Yt,WL=Un,GL=Qt,HL=an,VL=function(){var e=WL("Symbol"),t=e&&e.prototype,r=t&&t.valueOf,n=GL("toPrimitive");t&&!t[n]&&HL(t,n,function(i){return zL(r,this)},{arity:1})},KL=wi,JL=wt,bm=function(e){if(KL(e)==="Function")return JL(e)},ob=bm,YL=Bn,XL=_u,QL=ob(ob.bind),ea=function(e,t){return YL(e),t===void 0?e:XL?QL(e,t):function(){return e.apply(t,arguments)}},ZL=wi,Iu=Array.isArray||function(t){return ZL(t)==="Array"},ub=Iu,eD=cf,tD=ar,rD=Qt,nD=rD("species"),cb=Array,iD=function(e){var t;return ub(e)&&(t=e.constructor,eD(t)&&(t===cb||ub(t.prototype))?t=void 0:tD(t)&&(t=t[nD],t===null&&(t=void 0))),t===void 0?cb:t},aD=iD,_m=function(e,t){return new(aD(e))(t===0?0:t)},sD=ea,oD=wt,uD=Su,cD=Jr,lD=Yr,fD=_m,lb=oD([].push),za=function(e){var t=e===1,r=e===2,n=e===3,i=e===4,a=e===6,s=e===7,o=e===5||a;return function(u,c,l,p){for(var v=cD(u),m=uD(v),b=lD(m),T=sD(c,l),I=0,R=p||fD,x=t?R(u,b):r||s?R(u,0):void 0,N,j;b>I;I++)if((o||I in m)&&(N=m[I],j=T(N,I,v),e))if(t)x[I]=j;else if(j)switch(e){case 3:return!0;case 5:return N;case 6:return I;case 2:lb(x,N)}else switch(e){case 4:return!1;case 7:lb(x,N)}return a?-1:n||i?i:x}},vn={forEach:za(0),map:za(1),filter:za(2),some:za(3),every:za(4),find:za(5),findIndex:za(6)},lf=Ct,Ou=$t,wm=Yt,dD=wt,ro=er,no=ho,pD=yt,qr=vr,hD=Yi,kh=wr,ff=Cn,Sm=nf,vD=Lr,Rh=ls,io=Oa,CC=$u,mD=ps,EC=gm,gD=ku,kC=Ji,RC=nn,yD=vm,$C=wu,Od=an,bD=Ei,Tm=mo,_D=sf,IC=Eu,fb=Tu,wD=Qt,SD=ym,TD=TC,CD=VL,ED=Ti,OC=En,df=vn.forEach,fn=_D("hidden"),pf="Symbol",du="prototype",kD=OC.set,db=OC.getterFor(pf),jn=Object[du],rs=Ou.Symbol,Yo=rs&&rs[du],RD=Ou.RangeError,$D=Ou.TypeError,Ad=Ou.QObject,AC=kC.f,ns=RC.f,PC=EC.f,ID=$C.f,MC=dD([].push),Gi=Tm("symbols"),Au=Tm("op-symbols"),OD=Tm("wks"),$h=!Ad||!Ad[du]||!Ad[du].findChild,xC=function(e,t,r){var n=AC(jn,t);n&&delete jn[t],ns(e,t,r),n&&e!==jn&&ns(jn,t,n)},Ih=ro&&pD(function(){return io(ns({},"a",{get:function(){return ns(this,"a",{value:7}).a}})).a!==7})?xC:ns,Pd=function(e,t){var r=Gi[e]=io(Yo);return kD(r,{type:pf,tag:e,description:t}),ro||(r.description=t),r},hf=function(t,r,n){t===jn&&hf(Au,r,n),kh(t);var i=Sm(r);return kh(n),qr(Gi,i)?(n.enumerable?(qr(t,fn)&&t[fn][i]&&(t[fn][i]=!1),n=io(n,{enumerable:Rh(0,!1)})):(qr(t,fn)||ns(t,fn,Rh(1,io(null))),t[fn][i]=!0),Ih(t,i,n)):ns(t,i,n)},Cm=function(t,r){kh(t);var n=ff(r),i=CC(n).concat(DC(n));return df(i,function(a){(!ro||wm(Oh,n,a))&&hf(t,a,n[a])}),t},AD=function(t,r){return r===void 0?io(t):Cm(io(t),r)},Oh=function(t){var r=Sm(t),n=wm(ID,this,r);return this===jn&&qr(Gi,r)&&!qr(Au,r)?!1:n||!qr(this,r)||!qr(Gi,r)||qr(this,fn)&&this[fn][r]?n:!0},NC=function(t,r){var n=ff(t),i=Sm(r);if(!(n===jn&&qr(Gi,i)&&!qr(Au,i))){var a=AC(n,i);return a&&qr(Gi,i)&&!(qr(n,fn)&&n[fn][i])&&(a.enumerable=!0),a}},LC=function(t){var r=PC(ff(t)),n=[];return df(r,function(i){!qr(Gi,i)&&!qr(IC,i)&&MC(n,i)}),n},DC=function(e){var t=e===jn,r=PC(t?Au:ff(e)),n=[];return df(r,function(i){qr(Gi,i)&&(!t||qr(jn,i))&&MC(n,Gi[i])}),n};no||(rs=function(){if(hD(Yo,this))throw new $D("Symbol is not a constructor");var t=!arguments.length||arguments[0]===void 0?void 0:vD(arguments[0]),r=fb(t),n=function(i){var a=this===void 0?Ou:this;a===jn&&wm(n,Au,i),qr(a,fn)&&qr(a[fn],r)&&(a[fn][r]=!1);var s=Rh(1,i);try{Ih(a,r,s)}catch(o){if(!(o instanceof RD))throw o;xC(a,r,s)}};return ro&&$h&&Ih(jn,r,{configurable:!0,set:n}),Pd(r,t)},Yo=rs[du],Od(Yo,"toString",function(){return db(this).tag}),Od(rs,"withoutSetter",function(e){return Pd(fb(e),e)}),$C.f=Oh,RC.f=hf,yD.f=Cm,kC.f=NC,mD.f=EC.f=LC,gD.f=DC,SD.f=function(e){return Pd(wD(e),e)},ro&&(bD(Yo,"description",{configurable:!0,get:function(){return db(this).description}}),Od(jn,"propertyIsEnumerable",Oh,{unsafe:!0})));lf({global:!0,constructor:!0,wrap:!0,forced:!no,sham:!no},{Symbol:rs});df(CC(OD),function(e){TD(e)});lf({target:pf,stat:!0,forced:!no},{useSetter:function(){$h=!0},useSimple:function(){$h=!1}});lf({target:"Object",stat:!0,forced:!no,sham:!ro},{create:AD,defineProperty:hf,defineProperties:Cm,getOwnPropertyDescriptor:NC});lf({target:"Object",stat:!0,forced:!no},{getOwnPropertyNames:LC});CD();ED(rs,pf);IC[fn]=!0;var PD=ho,jC=PD&&!!Symbol.for&&!!Symbol.keyFor,MD=Ct,xD=Un,ND=vr,LD=Lr,FC=mo,DD=jC,Md=FC("string-to-symbol-registry"),jD=FC("symbol-to-string-registry");MD({target:"Symbol",stat:!0,forced:!DD},{for:function(e){var t=LD(e);if(ND(Md,t))return Md[t];var r=xD("Symbol")(t);return Md[t]=r,jD[r]=t,r}});var FD=Ct,UD=vr,BD=vo,qD=fs,zD=mo,WD=jC,pb=zD("symbol-to-string-registry");FD({target:"Symbol",stat:!0,forced:!WD},{keyFor:function(t){if(!BD(t))throw new TypeError(qD(t)+" is not a symbol");if(UD(pb,t))return pb[t]}});var GD=wt,hb=Iu,HD=Xt,vb=wi,VD=Lr,mb=GD([].push),KD=function(e){if(HD(e))return e;if(hb(e)){for(var t=e.length,r=[],n=0;n<t;n++){var i=e[n];typeof i=="string"?mb(r,i):(typeof i=="number"||vb(i)==="Number"||vb(i)==="String")&&mb(r,VD(i))}var a=r.length,s=!0;return function(o,u){if(s)return s=!1,u;if(hb(this))return u;for(var c=0;c<a;c++)if(r[c]===o)return u}}},JD=Ct,UC=Un,BC=vs,YD=Yt,Pu=wt,qC=yt,gb=Xt,yb=vo,zC=Ci,XD=KD,QD=ho,ZD=String,wa=UC("JSON","stringify"),dc=Pu(/./.exec),bb=Pu("".charAt),e2=Pu("".charCodeAt),t2=Pu("".replace),r2=Pu(1 .toString),n2=/[\uD800-\uDFFF]/g,_b=/^[\uD800-\uDBFF]$/,wb=/^[\uDC00-\uDFFF]$/,Sb=!QD||qC(function(){var e=UC("Symbol")("stringify detection");return wa([e])!=="[null]"||wa({a:e})!=="{}"||wa(Object(e))!=="{}"}),Tb=qC(function(){return wa("\uDF06\uD834")!=='"\\udf06\\ud834"'||wa("\uDEAD")!=='"\\udead"'}),i2=function(e,t){var r=zC(arguments),n=XD(t);if(!(!gb(n)&&(e===void 0||yb(e))))return r[1]=function(i,a){if(gb(n)&&(a=YD(n,this,ZD(i),a)),!yb(a))return a},BC(wa,null,r)},a2=function(e,t,r){var n=bb(r,t-1),i=bb(r,t+1);return dc(_b,e)&&!dc(wb,i)||dc(wb,e)&&!dc(_b,n)?"\\u"+r2(e2(e,0),16):e};wa&&JD({target:"JSON",stat:!0,arity:3,forced:Sb||Tb},{stringify:function(t,r,n){var i=zC(arguments),a=BC(Sb?i2:wa,null,i);return Tb&&typeof a=="string"?t2(a,n2,a2):a}});var s2=Ct,o2=ho,u2=yt,WC=ku,c2=Jr,l2=!o2||u2(function(){WC.f(1)});s2({target:"Object",stat:!0,forced:l2},{getOwnPropertySymbols:function(t){var r=WC.f;return r?r(c2(t)):[]}});var f2=yt,d2=Qt,p2=po,h2=d2("species"),Mu=function(e){return p2>=51||!f2(function(){var t=[],r=t.constructor={};return r[h2]=function(){return{foo:1}},t[e](Boolean).foo!==1})},v2=Ct,m2=vn.filter,g2=Mu,y2=g2("filter");v2({target:"Array",proto:!0,forced:!y2},{filter:function(t){return m2(this,t,arguments.length>1?arguments[1]:void 0)}});var b2=Ct,_2=yt,w2=Cn,GC=Ji.f,HC=er,S2=!HC||_2(function(){GC(1)});b2({target:"Object",stat:!0,forced:S2,sham:!HC},{getOwnPropertyDescriptor:function(t,r){return GC(w2(t),r)}});var T2=er,C2=nn,E2=ls,xu=function(e,t,r){T2?C2.f(e,t,E2(0,r)):e[t]=r},k2=Ct,R2=er,$2=iC,I2=Cn,O2=Ji,A2=xu;k2({target:"Object",stat:!0,sham:!R2},{getOwnPropertyDescriptors:function(t){for(var r=I2(t),n=O2.f,i=$2(r),a={},s=0,o,u;i.length>s;)u=n(r,o=i[s++]),u!==void 0&&A2(a,o,u);return a}});var VC={exports:{}};(function(e){function t(n,i,a,s,o,u,c){try{var l=n[u](c),p=l.value}catch(v){return void a(v)}l.done?i(p):Promise.resolve(p).then(s,o)}function r(n){return function(){var i=this,a=arguments;return new Promise(function(s,o){var u=n.apply(i,a);function c(p){t(u,s,o,c,l,"next",p)}function l(p){t(u,s,o,c,l,"throw",p)}c(void 0)})}}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports})(VC);var Nu=VC.exports,KC={exports:{}};(function(e){function t(r){if(r===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return r}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports})(KC);var ms=KC.exports,JC={exports:{}},YC={exports:{}};(function(e){function t(r,n){return e.exports=t=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(i,a){return i.__proto__=a,i},e.exports.__esModule=!0,e.exports.default=e.exports,t(r,n)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports})(YC);var Em=YC.exports;(function(e){var t=Em;function r(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&&t(n,i)}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports})(JC);var ki=JC.exports,XC={exports:{}},QC={exports:{}};(function(e){function t(r){"@babel/helpers - typeof";return e.exports=t=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},e.exports.__esModule=!0,e.exports.default=e.exports,t(r)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports})(QC);var qn=QC.exports;(function(e){var t=qn.default,r=ms;function n(i,a){if(a&&(t(a)=="object"||typeof a=="function"))return a;if(a!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return r(i)}e.exports=n,e.exports.__esModule=!0,e.exports.default=e.exports})(XC);var Ri=XC.exports,ZC={exports:{}};(function(e){function t(r){return e.exports=t=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(n){return n.__proto__||Object.getPrototypeOf(n)},e.exports.__esModule=!0,e.exports.default=e.exports,t(r)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports})(ZC);var zn=ZC.exports,eE={exports:{}},tE={exports:{}},rE={exports:{}};(function(e){var t=qn.default;function r(n,i){if(t(n)!="object"||!n)return n;var a=n[Symbol.toPrimitive];if(a!==void 0){var s=a.call(n,i||"default");if(t(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(i==="string"?String:Number)(n)}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports})(rE);var P2=rE.exports;(function(e){var t=qn.default,r=P2;function n(i){var a=r(i,"string");return t(a)=="symbol"?a:a+""}e.exports=n,e.exports.__esModule=!0,e.exports.default=e.exports})(tE);var nE=tE.exports;(function(e){var t=nE;function r(n,i,a){return(i=t(i))in n?Object.defineProperty(n,i,{value:a,enumerable:!0,configurable:!0,writable:!0}):n[i]=a,n}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports})(eE);var gs=eE.exports,iE={exports:{}};(function(e){var t=nE;function r(i,a){for(var s=0;s<a.length;s++){var o=a[s];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(i,t(o.key),o)}}function n(i,a,s){return a&&r(i.prototype,a),s&&r(i,s),Object.defineProperty(i,"prototype",{writable:!1}),i}e.exports=n,e.exports.__esModule=!0,e.exports.default=e.exports})(iE);var Aa=iE.exports,aE={exports:{}};(function(e){function t(r,n){if(!(r instanceof n))throw new TypeError("Cannot call a class as a function")}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports})(aE);var $i=aE.exports,M2=Ct,x2=vn.map,N2=Mu,L2=N2("map");M2({target:"Array",proto:!0,forced:!L2},{map:function(t){return x2(this,t,arguments.length>1?arguments[1]:void 0)}});var D2=dm,j2=Zi,F2=D2?{}.toString:function(){return"[object "+j2(this)+"]"},U2=dm,B2=an,q2=F2;U2||B2(Object.prototype,"toString",q2,{unsafe:!0});var sE={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},z2=af,xd=z2("span").classList,Cb=xd&&xd.constructor&&xd.constructor.prototype,oE=Cb===Object.prototype?void 0:Cb,W2=yt,vf=function(e,t){var r=[][e];return!!r&&W2(function(){r.call(null,t||function(){return 1},1)})},G2=vn.forEach,H2=vf,V2=H2("forEach"),K2=V2?[].forEach:function(t){return G2(this,t,arguments.length>1?arguments[1]:void 0)},Eb=$t,kb=sE,J2=oE,Nd=K2,Y2=Xi,uE=function(e){if(e&&e.forEach!==Nd)try{Y2(e,"forEach",Nd)}catch{e.forEach=Nd}};for(var Ld in kb)kb[Ld]&&uE(Eb[Ld]&&Eb[Ld].prototype);uE(J2);var Lo=$t,X2=Ia,Q2=wi,pc=function(e){return X2.slice(0,e.length)===e},cE=function(){return pc("Bun/")?"BUN":pc("Cloudflare-Workers")?"CLOUDFLARE":pc("Deno/")?"DENO":pc("Node.js/")?"NODE":Lo.Bun&&typeof Bun.version=="string"?"BUN":Lo.Deno&&typeof Deno.version=="object"?"DENO":Q2(Lo.process)==="process"?"NODE":Lo.window&&Lo.document?"BROWSER":"REST"}(),Z2=cE,km=Z2==="NODE",ej=wt,tj=Bn,rj=function(e,t,r){try{return ej(tj(Object.getOwnPropertyDescriptor(e,t)[r]))}catch{}},nj=ar,ij=function(e){return nj(e)||e===null},aj=ij,sj=String,oj=TypeError,uj=function(e){if(aj(e))return e;throw new oj("Can't set "+sj(e)+" as a prototype")},cj=rj,lj=ar,fj=si,dj=uj,go=Object.setPrototypeOf||("__proto__"in{}?function(){var e=!1,t={},r;try{r=cj(Object.prototype,"__proto__","set"),r(t,[]),e=t instanceof Array}catch{}return function(i,a){return fj(i),dj(a),lj(i)&&(e?r(i,a):i.__proto__=a),i}}():void 0),pj=Un,hj=Ei,vj=Qt,mj=er,Rb=vj("species"),mf=function(e){var t=pj(e);mj&&t&&!t[Rb]&&hj(t,Rb,{configurable:!0,get:function(){return this}})},gj=Yi,yj=TypeError,Pa=function(e,t){if(gj(t,e))return e;throw new yj("Incorrect invocation")},$b=wr,bj=hm,_j=ai,wj=Qt,Sj=wj("species"),lE=function(e,t){var r=$b(e).constructor,n;return r===void 0||_j(n=$b(r)[Sj])?t:bj(n)},Tj=TypeError,Rm=function(e,t){if(e<t)throw new Tj("Not enough arguments");return e},Cj=Ia,fE=/(?:ipad|iphone|ipod).*applewebkit/i.test(Cj),Sn=$t,Ej=vs,kj=ea,Ib=Xt,Rj=vr,dE=yt,Ob=pC,$j=Ci,Ab=af,Ij=Rm,Oj=fE,Aj=km,Ah=Sn.setImmediate,Pb=Sn.clearImmediate,Pj=Sn.process,Dd=Sn.Dispatch,Mj=Sn.Function,Mb=Sn.MessageChannel,xj=Sn.String,jd=0,nu={},xb="onreadystatechange",pu,Wa,Fd,Ud;dE(function(){pu=Sn.location});var $m=function(e){if(Rj(nu,e)){var t=nu[e];delete nu[e],t()}},Bd=function(e){return function(){$m(e)}},Nb=function(e){$m(e.data)},Lb=function(e){Sn.postMessage(xj(e),pu.protocol+"//"+pu.host)};(!Ah||!Pb)&&(Ah=function(t){Ij(arguments.length,1);var r=Ib(t)?t:Mj(t),n=$j(arguments,1);return nu[++jd]=function(){Ej(r,void 0,n)},Wa(jd),jd},Pb=function(t){delete nu[t]},Aj?Wa=function(e){Pj.nextTick(Bd(e))}:Dd&&Dd.now?Wa=function(e){Dd.now(Bd(e))}:Mb&&!Oj?(Fd=new Mb,Ud=Fd.port2,Fd.port1.onmessage=Nb,Wa=kj(Ud.postMessage,Ud)):Sn.addEventListener&&Ib(Sn.postMessage)&&!Sn.importScripts&&pu&&pu.protocol!=="file:"&&!dE(Lb)?(Wa=Lb,Sn.addEventListener("message",Nb,!1)):xb in Ab("script")?Wa=function(e){Ob.appendChild(Ab("script"))[xb]=function(){Ob.removeChild(this),$m(e)}}:Wa=function(e){setTimeout(Bd(e),0)});var pE={set:Ah},Db=$t,Nj=er,Lj=Object.getOwnPropertyDescriptor,hE=function(e){if(!Nj)return Db[e];var t=Lj(Db,e);return t&&t.value},vE=function(){this.head=null,this.tail=null};vE.prototype={add:function(e){var t={item:e,next:null},r=this.tail;r?r.next=t:this.head=t,this.tail=t},get:function(){var e=this.head;if(e){var t=this.head=e.next;return t===null&&(this.tail=null),e.item}}};var mE=vE,Dj=Ia,jj=/ipad|iphone|ipod/i.test(Dj)&&typeof Pebble<"u",Fj=Ia,Uj=/web0s(?!.*chrome)/i.test(Fj),ao=$t,Bj=hE,jb=ea,qd=pE.set,qj=mE,zj=fE,Wj=jj,Gj=Uj,zd=km,Fb=ao.MutationObserver||ao.WebKitMutationObserver,Ub=ao.document,Bb=ao.process,hc=ao.Promise,Ph=Bj("queueMicrotask"),Rs,Wd,Gd,vc,qb;if(!Ph){var mc=new qj,gc=function(){var e,t;for(zd&&(e=Bb.domain)&&e.exit();t=mc.get();)try{t()}catch(r){throw mc.head&&Rs(),r}e&&e.enter()};!zj&&!zd&&!Gj&&Fb&&Ub?(Wd=!0,Gd=Ub.createTextNode(""),new Fb(gc).observe(Gd,{characterData:!0}),Rs=function(){Gd.data=Wd=!Wd}):!Wj&&hc&&hc.resolve?(vc=hc.resolve(void 0),vc.constructor=hc,qb=jb(vc.then,vc),Rs=function(){qb(gc)}):zd?Rs=function(){Bb.nextTick(gc)}:(qd=jb(qd,ao),Rs=function(){qd(gc)}),Ph=function(e){mc.head||Rs(),mc.add(e)}}var Hj=Ph,Vj=function(e,t){try{arguments.length===1?console.error(e):console.error(e,t)}catch{}},Im=function(e){try{return{error:!1,value:e()}}catch(t){return{error:!0,value:t}}},Kj=$t,gf=Kj.Promise,Jj=$t,iu=gf,Yj=Xt,Xj=uf,Qj=um,Zj=Qt,zb=cE,Hd=po;iu&&iu.prototype;var eF=Zj("species"),Mh=!1,gE=Yj(Jj.PromiseRejectionEvent),tF=Xj("Promise",function(){var e=Qj(iu),t=e!==String(iu);if(!t&&Hd===66)return!0;if(!Hd||Hd<51||!/native code/.test(e)){var r=new iu(function(a){a(1)}),n=function(a){a(function(){},function(){})},i=r.constructor={};if(i[eF]=n,Mh=r.then(function(){})instanceof n,!Mh)return!0}return!t&&(zb==="BROWSER"||zb==="DENO")&&!gE}),Lu={CONSTRUCTOR:tF,REJECTION_EVENT:gE,SUBCLASSING:Mh},yo={},Wb=Bn,rF=TypeError,nF=function(e){var t,r;this.promise=new e(function(n,i){if(t!==void 0||r!==void 0)throw new rF("Bad Promise constructor");t=n,r=i}),this.resolve=Wb(t),this.reject=Wb(r)};yo.f=function(e){return new nF(e)};var iF=Ct,jl=km,Ea=$t,so=Yt,Gb=an,Hb=go,aF=Ti,sF=mf,oF=Bn,gl=Xt,uF=ar,cF=Pa,lF=lE,yE=pE.set,Om=Hj,fF=Vj,dF=Im,pF=mE,bE=En,Fl=gf,Am=Lu,_E=yo,yf="Promise",wE=Am.CONSTRUCTOR,hF=Am.REJECTION_EVENT,vF=Am.SUBCLASSING,Vd=bE.getterFor(yf),mF=bE.set,Ls=Fl&&Fl.prototype,es=Fl,yc=Ls,SE=Ea.TypeError,xh=Ea.document,Pm=Ea.process,Nh=_E.f,gF=Nh,yF=!!(xh&&xh.createEvent&&Ea.dispatchEvent),TE="unhandledrejection",bF="rejectionhandled",Vb=0,CE=1,_F=2,Mm=1,EE=2,bc,Kb,wF,Jb,kE=function(e){var t;return uF(e)&&gl(t=e.then)?t:!1},RE=function(e,t){var r=t.value,n=t.state===CE,i=n?e.ok:e.fail,a=e.resolve,s=e.reject,o=e.domain,u,c,l;try{i?(n||(t.rejection===EE&&TF(t),t.rejection=Mm),i===!0?u=r:(o&&o.enter(),u=i(r),o&&(o.exit(),l=!0)),u===e.promise?s(new SE("Promise-chain cycle")):(c=kE(u))?so(c,u,a,s):a(u)):s(r)}catch(p){o&&!l&&o.exit(),s(p)}},$E=function(e,t){e.notified||(e.notified=!0,Om(function(){for(var r=e.reactions,n;n=r.get();)RE(n,e);e.notified=!1,t&&!e.rejection&&SF(e)}))},IE=function(e,t,r){var n,i;yF?(n=xh.createEvent("Event"),n.promise=t,n.reason=r,n.initEvent(e,!1,!0),Ea.dispatchEvent(n)):n={promise:t,reason:r},!hF&&(i=Ea["on"+e])?i(n):e===TE&&fF("Unhandled promise rejection",r)},SF=function(e){so(yE,Ea,function(){var t=e.facade,r=e.value,n=Yb(e),i;if(n&&(i=dF(function(){jl?Pm.emit("unhandledRejection",r,t):IE(TE,t,r)}),e.rejection=jl||Yb(e)?EE:Mm,i.error))throw i.value})},Yb=function(e){return e.rejection!==Mm&&!e.parent},TF=function(e){so(yE,Ea,function(){var t=e.facade;jl?Pm.emit("rejectionHandled",t):IE(bF,t,e.value)})},Us=function(e,t,r){return function(n){e(t,n,r)}},Ws=function(e,t,r){e.done||(e.done=!0,r&&(e=r),e.value=t,e.state=_F,$E(e,!0))},Lh=function(e,t,r){if(!e.done){e.done=!0,r&&(e=r);try{if(e.facade===t)throw new SE("Promise can't be resolved itself");var n=kE(t);n?Om(function(){var i={done:!1};try{so(n,t,Us(Lh,i,e),Us(Ws,i,e))}catch(a){Ws(i,a,e)}}):(e.value=t,e.state=CE,$E(e,!1))}catch(i){Ws({done:!1},i,e)}}};if(wE&&(es=function(t){cF(this,yc),oF(t),so(bc,this);var r=Vd(this);try{t(Us(Lh,r),Us(Ws,r))}catch(n){Ws(r,n)}},yc=es.prototype,bc=function(t){mF(this,{type:yf,done:!1,notified:!1,parent:!1,reactions:new pF,rejection:!1,state:Vb,value:null})},bc.prototype=Gb(yc,"then",function(t,r){var n=Vd(this),i=Nh(lF(this,es));return n.parent=!0,i.ok=gl(t)?t:!0,i.fail=gl(r)&&r,i.domain=jl?Pm.domain:void 0,n.state===Vb?n.reactions.add(i):Om(function(){RE(i,n)}),i.promise}),Kb=function(){var e=new bc,t=Vd(e);this.promise=e,this.resolve=Us(Lh,t),this.reject=Us(Ws,t)},_E.f=Nh=function(e){return e===es||e===wF?new Kb(e):gF(e)},gl(Fl)&&Ls!==Object.prototype)){Jb=Ls.then,vF||Gb(Ls,"then",function(t,r){var n=this;return new es(function(i,a){so(Jb,n,i,a)}).then(t,r)},{unsafe:!0});try{delete Ls.constructor}catch{}Hb&&Hb(Ls,yc)}iF({global:!0,constructor:!0,wrap:!0,forced:wE},{Promise:es});aF(es,yf,!1);sF(yf);var Du={},CF=Qt,EF=Du,kF=CF("iterator"),RF=Array.prototype,xm=function(e){return e!==void 0&&(EF.Array===e||RF[kF]===e)},$F=Zi,Xb=ds,IF=ai,OF=Du,AF=Qt,PF=AF("iterator"),ju=function(e){if(!IF(e))return Xb(e,PF)||Xb(e,"@@iterator")||OF[$F(e)]},MF=Yt,xF=Bn,NF=wr,LF=fs,DF=ju,jF=TypeError,bf=function(e,t){var r=arguments.length<2?DF(e):t;if(xF(r))return NF(MF(r,e));throw new jF(LF(e)+" is not iterable")},FF=Yt,Qb=wr,UF=ds,OE=function(e,t,r){var n,i;Qb(e);try{if(n=UF(e,"return"),!n){if(t==="throw")throw r;return r}n=FF(n,e)}catch(a){i=!0,n=a}if(t==="throw")throw r;if(i)throw n;return Qb(n),r},BF=ea,qF=Yt,zF=wr,WF=fs,GF=xm,HF=Yr,Zb=Yi,VF=bf,KF=ju,e_=OE,JF=TypeError,yl=function(e,t){this.stopped=e,this.result=t},t_=yl.prototype,Fu=function(e,t,r){var n=r&&r.that,i=!!(r&&r.AS_ENTRIES),a=!!(r&&r.IS_RECORD),s=!!(r&&r.IS_ITERATOR),o=!!(r&&r.INTERRUPTED),u=BF(t,n),c,l,p,v,m,b,T,I=function(x){return c&&e_(c,"normal",x),new yl(!0,x)},R=function(x){return i?(zF(x),o?u(x[0],x[1],I):u(x[0],x[1])):o?u(x,I):u(x)};if(a)c=e.iterator;else if(s)c=e;else{if(l=KF(e),!l)throw new JF(WF(e)+" is not iterable");if(GF(l)){for(p=0,v=HF(e);v>p;p++)if(m=R(e[p]),m&&Zb(t_,m))return m;return new yl(!1)}c=VF(e,l)}for(b=a?e.next:c.next;!(T=qF(b,c)).done;){try{m=R(T.value)}catch(x){e_(c,"throw",x)}if(typeof m=="object"&&m&&Zb(t_,m))return m}return new yl(!1)},YF=Qt,AE=YF("iterator"),PE=!1;try{var XF=0,r_={next:function(){return{done:!!XF++}},return:function(){PE=!0}};r_[AE]=function(){return this},Array.from(r_,function(){throw 2})}catch{}var _f=function(e,t){try{if(!t&&!PE)return!1}catch{return!1}var r=!1;try{var n={};n[AE]=function(){return{next:function(){return{done:r=!0}}}},e(n)}catch{}return r},QF=gf,ZF=_f,eU=Lu.CONSTRUCTOR,ME=eU||!ZF(function(e){QF.all(e).then(void 0,function(){})}),tU=Ct,rU=Yt,nU=Bn,iU=yo,aU=Im,sU=Fu,oU=ME;tU({target:"Promise",stat:!0,forced:oU},{all:function(t){var r=this,n=iU.f(r),i=n.resolve,a=n.reject,s=aU(function(){var o=nU(r.resolve),u=[],c=0,l=1;sU(t,function(p){var v=c++,m=!1;l++,rU(o,r,p).then(function(b){m||(m=!0,u[v]=b,--l||i(u))},a)}),--l||i(u)});return s.error&&a(s.value),n.promise}});var uU=Ct,cU=Lu.CONSTRUCTOR,Dh=gf,lU=Un,fU=Xt,dU=an,n_=Dh&&Dh.prototype;uU({target:"Promise",proto:!0,forced:cU,real:!0},{catch:function(e){return this.then(void 0,e)}});if(fU(Dh)){var i_=lU("Promise").prototype.catch;n_.catch!==i_&&dU(n_,"catch",i_,{unsafe:!0})}var pU=Ct,hU=Yt,vU=Bn,mU=yo,gU=Im,yU=Fu,bU=ME;pU({target:"Promise",stat:!0,forced:bU},{race:function(t){var r=this,n=mU.f(r),i=n.reject,a=gU(function(){var s=vU(r.resolve);yU(t,function(o){hU(s,r,o).then(n.resolve,i)})});return a.error&&i(a.value),n.promise}});var _U=Ct,wU=yo,SU=Lu.CONSTRUCTOR;_U({target:"Promise",stat:!0,forced:SU},{reject:function(t){var r=wU.f(this),n=r.reject;return n(t),r.promise}});var TU=wr,CU=ar,EU=yo,kU=function(e,t){if(TU(e),CU(t)&&t.constructor===e)return t;var r=EU.f(e),n=r.resolve;return n(t),r.promise},RU=Ct,$U=Un,IU=Lu.CONSTRUCTOR,OU=kU;$U("Promise");RU({target:"Promise",stat:!0,forced:IU},{resolve:function(t){return OU(this,t)}});var xE={exports:{}};(function(e){var t=qn.default;function r(){e.exports=r=function(){return i},e.exports.__esModule=!0,e.exports.default=e.exports;var n,i={},a=Object.prototype,s=a.hasOwnProperty,o=Object.defineProperty||function(ce,he,P){ce[he]=P.value},u=typeof Symbol=="function"?Symbol:{},c=u.iterator||"@@iterator",l=u.asyncIterator||"@@asyncIterator",p=u.toStringTag||"@@toStringTag";function v(ce,he,P){return Object.defineProperty(ce,he,{value:P,enumerable:!0,configurable:!0,writable:!0}),ce[he]}try{v({},"")}catch{v=function(P,Ie,qe){return P[Ie]=qe}}function m(ce,he,P,Ie){var qe=he&&he.prototype instanceof j?he:j,Ne=Object.create(qe.prototype),_e=new Ke(Ie||[]);return o(Ne,"_invoke",{value:L(ce,P,_e)}),Ne}function b(ce,he,P){try{return{type:"normal",arg:ce.call(he,P)}}catch(Ie){return{type:"throw",arg:Ie}}}i.wrap=m;var T="suspendedStart",I="suspendedYield",R="executing",x="completed",N={};function j(){}function X(){}function J(){}var V={};v(V,c,function(){return this});var D=Object.getPrototypeOf,te=D&&D(D(Se([])));te&&te!==a&&s.call(te,c)&&(V=te);var ue=J.prototype=j.prototype=Object.create(V);function ee(ce){["next","throw","return"].forEach(function(he){v(ce,he,function(P){return this._invoke(he,P)})})}function ge(ce,he){function P(qe,Ne,_e,Q){var kt=b(ce[qe],ce,Ne);if(kt.type!=="throw"){var Ce=kt.arg,de=Ce.value;return de&&t(de)=="object"&&s.call(de,"__await")?he.resolve(de.__await).then(function(Rt){P("next",Rt,_e,Q)},function(Rt){P("throw",Rt,_e,Q)}):he.resolve(de).then(function(Rt){Ce.value=Rt,_e(Ce)},function(Rt){return P("throw",Rt,_e,Q)})}Q(kt.arg)}var Ie;o(this,"_invoke",{value:function(Ne,_e){function Q(){return new he(function(kt,Ce){P(Ne,_e,kt,Ce)})}return Ie=Ie?Ie.then(Q,Q):Q()}})}function L(ce,he,P){var Ie=T;return function(qe,Ne){if(Ie===R)throw Error("Generator is already running");if(Ie===x){if(qe==="throw")throw Ne;return{value:n,done:!0}}for(P.method=qe,P.arg=Ne;;){var _e=P.delegate;if(_e){var Q=pe(_e,P);if(Q){if(Q===N)continue;return Q}}if(P.method==="next")P.sent=P._sent=P.arg;else if(P.method==="throw"){if(Ie===T)throw Ie=x,P.arg;P.dispatchException(P.arg)}else P.method==="return"&&P.abrupt("return",P.arg);Ie=R;var kt=b(ce,he,P);if(kt.type==="normal"){if(Ie=P.done?x:I,kt.arg===N)continue;return{value:kt.arg,done:P.done}}kt.type==="throw"&&(Ie=x,P.method="throw",P.arg=kt.arg)}}}function pe(ce,he){var P=he.method,Ie=ce.iterator[P];if(Ie===n)return he.delegate=null,P==="throw"&&ce.iterator.return&&(he.method="return",he.arg=n,pe(ce,he),he.method==="throw")||P!=="return"&&(he.method="throw",he.arg=new TypeError("The iterator does not provide a '"+P+"' method")),N;var qe=b(Ie,ce.iterator,he.arg);if(qe.type==="throw")return he.method="throw",he.arg=qe.arg,he.delegate=null,N;var Ne=qe.arg;return Ne?Ne.done?(he[ce.resultName]=Ne.value,he.next=ce.nextLoc,he.method!=="return"&&(he.method="next",he.arg=n),he.delegate=null,N):Ne:(he.method="throw",he.arg=new TypeError("iterator result is not an object"),he.delegate=null,N)}function Te(ce){var he={tryLoc:ce[0]};1 in ce&&(he.catchLoc=ce[1]),2 in ce&&(he.finallyLoc=ce[2],he.afterLoc=ce[3]),this.tryEntries.push(he)}function rt(ce){var he=ce.completion||{};he.type="normal",delete he.arg,ce.completion=he}function Ke(ce){this.tryEntries=[{tryLoc:"root"}],ce.forEach(Te,this),this.reset(!0)}function Se(ce){if(ce||ce===""){var he=ce[c];if(he)return he.call(ce);if(typeof ce.next=="function")return ce;if(!isNaN(ce.length)){var P=-1,Ie=function qe(){for(;++P<ce.length;)if(s.call(ce,P))return qe.value=ce[P],qe.done=!1,qe;return qe.value=n,qe.done=!0,qe};return Ie.next=Ie}}throw new TypeError(t(ce)+" is not iterable")}return X.prototype=J,o(ue,"constructor",{value:J,configurable:!0}),o(J,"constructor",{value:X,configurable:!0}),X.displayName=v(J,p,"GeneratorFunction"),i.isGeneratorFunction=function(ce){var he=typeof ce=="function"&&ce.constructor;return!!he&&(he===X||(he.displayName||he.name)==="GeneratorFunction")},i.mark=function(ce){return Object.setPrototypeOf?Object.setPrototypeOf(ce,J):(ce.__proto__=J,v(ce,p,"GeneratorFunction")),ce.prototype=Object.create(ue),ce},i.awrap=function(ce){return{__await:ce}},ee(ge.prototype),v(ge.prototype,l,function(){return this}),i.AsyncIterator=ge,i.async=function(ce,he,P,Ie,qe){qe===void 0&&(qe=Promise);var Ne=new ge(m(ce,he,P,Ie),qe);return i.isGeneratorFunction(he)?Ne:Ne.next().then(function(_e){return _e.done?_e.value:Ne.next()})},ee(ue),v(ue,p,"Generator"),v(ue,c,function(){return this}),v(ue,"toString",function(){return"[object Generator]"}),i.keys=function(ce){var he=Object(ce),P=[];for(var Ie in he)P.push(Ie);return P.reverse(),function qe(){for(;P.length;){var Ne=P.pop();if(Ne in he)return qe.value=Ne,qe.done=!1,qe}return qe.done=!0,qe}},i.values=Se,Ke.prototype={constructor:Ke,reset:function(he){if(this.prev=0,this.next=0,this.sent=this._sent=n,this.done=!1,this.delegate=null,this.method="next",this.arg=n,this.tryEntries.forEach(rt),!he)for(var P in this)P.charAt(0)==="t"&&s.call(this,P)&&!isNaN(+P.slice(1))&&(this[P]=n)},stop:function(){this.done=!0;var he=this.tryEntries[0].completion;if(he.type==="throw")throw he.arg;return this.rval},dispatchException:function(he){if(this.done)throw he;var P=this;function Ie(Ce,de){return _e.type="throw",_e.arg=he,P.next=Ce,de&&(P.method="next",P.arg=n),!!de}for(var qe=this.tryEntries.length-1;qe>=0;--qe){var Ne=this.tryEntries[qe],_e=Ne.completion;if(Ne.tryLoc==="root")return Ie("end");if(Ne.tryLoc<=this.prev){var Q=s.call(Ne,"catchLoc"),kt=s.call(Ne,"finallyLoc");if(Q&&kt){if(this.prev<Ne.catchLoc)return Ie(Ne.catchLoc,!0);if(this.prev<Ne.finallyLoc)return Ie(Ne.finallyLoc)}else if(Q){if(this.prev<Ne.catchLoc)return Ie(Ne.catchLoc,!0)}else{if(!kt)throw Error("try statement without catch or finally");if(this.prev<Ne.finallyLoc)return Ie(Ne.finallyLoc)}}}},abrupt:function(he,P){for(var Ie=this.tryEntries.length-1;Ie>=0;--Ie){var qe=this.tryEntries[Ie];if(qe.tryLoc<=this.prev&&s.call(qe,"finallyLoc")&&this.prev<qe.finallyLoc){var Ne=qe;break}}Ne&&(he==="break"||he==="continue")&&Ne.tryLoc<=P&&P<=Ne.finallyLoc&&(Ne=null);var _e=Ne?Ne.completion:{};return _e.type=he,_e.arg=P,Ne?(this.method="next",this.next=Ne.finallyLoc,N):this.complete(_e)},complete:function(he,P){if(he.type==="throw")throw he.arg;return he.type==="break"||he.type==="continue"?this.next=he.arg:he.type==="return"?(this.rval=this.arg=he.arg,this.method="return",this.next="end"):he.type==="normal"&&P&&(this.next=P),N},finish:function(he){for(var P=this.tryEntries.length-1;P>=0;--P){var Ie=this.tryEntries[P];if(Ie.finallyLoc===he)return this.complete(Ie.completion,Ie.afterLoc),rt(Ie),N}},catch:function(he){for(var P=this.tryEntries.length-1;P>=0;--P){var Ie=this.tryEntries[P];if(Ie.tryLoc===he){var qe=Ie.completion;if(qe.type==="throw"){var Ne=qe.arg;rt(Ie)}return Ne}}throw Error("illegal catch attempt")},delegateYield:function(he,P,Ie){return this.delegate={iterator:Se(he),resultName:P,nextLoc:Ie},this.method==="next"&&(this.arg=n),N}},i}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports})(xE);var AU=xE.exports,bl=AU(),Uu=bl;try{regeneratorRuntime=bl}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=bl:Function("r","regeneratorRuntime = r")(bl)}var PU=TypeError,MU=9007199254740991,NE=function(e){if(e>MU)throw PU("Maximum allowed index exceeded");return e},xU=Ct,NU=yt,LU=Iu,DU=ar,jU=Jr,FU=Yr,a_=NE,s_=xu,UU=_m,BU=Mu,qU=Qt,zU=po,LE=qU("isConcatSpreadable"),WU=zU>=51||!NU(function(){var e=[];return e[LE]=!1,e.concat()[0]!==e}),GU=function(e){if(!DU(e))return!1;var t=e[LE];return t!==void 0?!!t:LU(e)},HU=!WU||!BU("concat");xU({target:"Array",proto:!0,arity:1,forced:HU},{concat:function(t){var r=jU(this),n=UU(r,0),i=0,a,s,o,u,c;for(a=-1,o=arguments.length;a<o;a++)if(c=a===-1?r:arguments[a],GU(c))for(u=FU(c),a_(i+u),s=0;s<u;s++,i++)s in c&&s_(n,i,c[s]);else a_(i+1),s_(n,i++,c);return n.length=i,n}});var VU=wr,KU=OE,JU=function(e,t,r,n){try{return n?t(VU(r)[0],r[1]):t(r)}catch(i){KU(e,"throw",i)}},YU=ea,XU=Yt,QU=Jr,ZU=JU,eB=xm,tB=cf,rB=Yr,o_=xu,nB=bf,iB=ju,u_=Array,DE=function(t){var r=QU(t),n=tB(this),i=arguments.length,a=i>1?arguments[1]:void 0,s=a!==void 0;s&&(a=YU(a,i>2?arguments[2]:void 0));var o=iB(r),u=0,c,l,p,v,m,b;if(o&&!(this===u_&&eB(o)))for(l=n?new this:[],v=nB(r,o),m=v.next;!(p=XU(m,v)).done;u++)b=s?ZU(v,a,[p.value,u],!0):p.value,o_(l,u,b);else for(c=rB(r),l=n?new this(c):u_(c);c>u;u++)b=s?a(r[u],u):r[u],o_(l,u,b);return l.length=u,l},aB=Ct,sB=DE,oB=_f,uB=!oB(function(e){Array.from(e)});aB({target:"Array",stat:!0,forced:uB},{from:sB});var Nm=wt,cB=Si,lB=Lr,fB=si,dB=Nm("".charAt),c_=Nm("".charCodeAt),pB=Nm("".slice),l_=function(e){return function(t,r){var n=lB(fB(t)),i=cB(r),a=n.length,s,o;return i<0||i>=a?e?"":void 0:(s=c_(n,i),s<55296||s>56319||i+1===a||(o=c_(n,i+1))<56320||o>57343?e?dB(n,i):s:e?pB(n,i,i+2):(s-55296<<10)+(o-56320)+65536)}},Lm={codeAt:l_(!1),charAt:l_(!0)},hB=yt,vB=!hB(function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype}),mB=vr,gB=Xt,yB=Jr,bB=sf,_B=vB,f_=bB("IE_PROTO"),jh=Object,wB=jh.prototype,Bu=_B?jh.getPrototypeOf:function(e){var t=yB(e);if(mB(t,f_))return t[f_];var r=t.constructor;return gB(r)&&t instanceof r?r.prototype:t instanceof jh?wB:null},SB=yt,TB=Xt,CB=ar,d_=Bu,EB=an,kB=Qt,Fh=kB("iterator"),jE=!1,ss,Kd,Jd;[].keys&&(Jd=[].keys(),"next"in Jd?(Kd=d_(d_(Jd)),Kd!==Object.prototype&&(ss=Kd)):jE=!0);var RB=!CB(ss)||SB(function(){var e={};return ss[Fh].call(e)!==e});RB&&(ss={});TB(ss[Fh])||EB(ss,Fh,function(){return this});var FE={IteratorPrototype:ss,BUGGY_SAFARI_ITERATORS:jE},$B=FE.IteratorPrototype,IB=Oa,OB=ls,AB=Ti,PB=Du,MB=function(){return this},UE=function(e,t,r,n){var i=t+" Iterator";return e.prototype=IB($B,{next:OB(+!n,r)}),AB(e,i,!1),PB[i]=MB,e},xB=Ct,NB=Yt,BE=Cu,LB=Xt,DB=UE,p_=Bu,h_=go,jB=Ti,FB=Xi,Yd=an,UB=Qt,BB=Du,qE=FE,qB=BE.PROPER,zB=BE.CONFIGURABLE,v_=qE.IteratorPrototype,_c=qE.BUGGY_SAFARI_ITERATORS,Do=UB("iterator"),m_="keys",jo="values",g_="entries",WB=function(){return this},Dm=function(e,t,r,n,i,a,s){DB(r,t,n);var o=function(R){if(R===i&&v)return v;if(!_c&&R&&R in l)return l[R];switch(R){case m_:return function(){return new r(this,R)};case jo:return function(){return new r(this,R)};case g_:return function(){return new r(this,R)}}return function(){return new r(this)}},u=t+" Iterator",c=!1,l=e.prototype,p=l[Do]||l["@@iterator"]||i&&l[i],v=!_c&&p||o(i),m=t==="Array"&&l.entries||p,b,T,I;if(m&&(b=p_(m.call(new e)),b!==Object.prototype&&b.next&&(p_(b)!==v_&&(h_?h_(b,v_):LB(b[Do])||Yd(b,Do,WB)),jB(b,u,!0))),qB&&i===jo&&p&&p.name!==jo&&(zB?FB(l,"name",jo):(c=!0,v=function(){return NB(p,this)})),i)if(T={values:o(jo),keys:a?v:o(m_),entries:o(g_)},s)for(I in T)(_c||c||!(I in l))&&Yd(l,I,T[I]);else xB({target:t,proto:!0,forced:_c||c},T);return l[Do]!==v&&Yd(l,Do,v,{name:i}),BB[t]=v,T},wf=function(e,t){return{value:e,done:t}},GB=Lm.charAt,HB=Lr,zE=En,VB=Dm,y_=wf,WE="String Iterator",KB=zE.set,JB=zE.getterFor(WE);VB(String,"String",function(e){KB(this,{type:WE,string:HB(e),index:0})},function(){var t=JB(this),r=t.string,n=t.index,i;return n>=r.length?y_(void 0,!0):(i=GB(r,n),t.index+=i.length,y_(i,!1))});var GE={exports:{}};(function(e){(function(t,r){e.exports?e.exports=r():t.log=r()})(je,function(){var t=function(){},r="undefined",n=typeof window!==r&&typeof window.navigator!==r&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"],a={},s=null;function o(T,I){var R=T[I];if(typeof R.bind=="function")return R.bind(T);try{return Function.prototype.bind.call(R,T)}catch{return function(){return Function.prototype.apply.apply(R,[T,arguments])}}}function u(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(T){return T==="debug"&&(T="log"),typeof console===r?!1:T==="trace"&&n?u:console[T]!==void 0?o(console,T):console.log!==void 0?o(console,"log"):t}function l(){for(var T=this.getLevel(),I=0;I<i.length;I++){var R=i[I];this[R]=I<T?t:this.methodFactory(R,T,this.name)}if(this.log=this.debug,typeof console===r&&T<this.levels.SILENT)return"No console available for logging"}function p(T){return function(){typeof console!==r&&(l.call(this),this[T].apply(this,arguments))}}function v(T,I,R){return c(T)||p.apply(this,arguments)}function m(T,I){var R=this,x,N,j,X="loglevel";typeof T=="string"?X+=":"+T:typeof T=="symbol"&&(X=void 0);function J(ee){var ge=(i[ee]||"silent").toUpperCase();if(!(typeof window===r||!X)){try{window.localStorage[X]=ge;return}catch{}try{window.document.cookie=encodeURIComponent(X)+"="+ge+";"}catch{}}}function V(){var ee;if(!(typeof window===r||!X)){try{ee=window.localStorage[X]}catch{}if(typeof ee===r)try{var ge=window.document.cookie,L=encodeURIComponent(X),pe=ge.indexOf(L+"=");pe!==-1&&(ee=/^([^;]+)/.exec(ge.slice(pe+L.length+1))[1])}catch{}return R.levels[ee]===void 0&&(ee=void 0),ee}}function D(){if(!(typeof window===r||!X)){try{window.localStorage.removeItem(X)}catch{}try{window.document.cookie=encodeURIComponent(X)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function te(ee){var ge=ee;if(typeof ge=="string"&&R.levels[ge.toUpperCase()]!==void 0&&(ge=R.levels[ge.toUpperCase()]),typeof ge=="number"&&ge>=0&&ge<=R.levels.SILENT)return ge;throw new TypeError("log.setLevel() called with invalid level: "+ee)}R.name=T,R.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},R.methodFactory=I||v,R.getLevel=function(){return j??N??x},R.setLevel=function(ee,ge){return j=te(ee),ge!==!1&&J(j),l.call(R)},R.setDefaultLevel=function(ee){N=te(ee),V()||R.setLevel(ee,!1)},R.resetLevel=function(){j=null,D(),l.call(R)},R.enableAll=function(ee){R.setLevel(R.levels.TRACE,ee)},R.disableAll=function(ee){R.setLevel(R.levels.SILENT,ee)},R.rebuild=function(){if(s!==R&&(x=te(s.getLevel())),l.call(R),s===R)for(var ee in a)a[ee].rebuild()},x=te(s?s.getLevel():"WARN");var ue=V();ue!=null&&(j=te(ue)),l.call(R)}s=new m,s.getLogger=function(I){if(typeof I!="symbol"&&typeof I!="string"||I==="")throw new TypeError("You must supply a name when creating a logger.");var R=a[I];return R||(R=a[I]=new m(I,s.methodFactory)),R};var b=typeof window!==r?window.log:void 0;return s.noConflict=function(){return typeof window!==r&&window.log===s&&(window.log=b),s},s.getLoggers=function(){return a},s.default=s,s})})(GE);var Ar=GE.exports;const is="\\d+(?:[\\.,]\\d+)?",YB=`(${is}W)`,XB=`(${is}Y)?(${is}M)?(${is}D)?`,QB=`T(${is}H)?(${is}M)?(${is}S)?`,ZB=`P(?:${YB}|${XB}(?:${QB})?)`,e3=["weeks","years","months","days","hours","minutes","seconds"],jm=new RegExp(ZB),HE=e=>e.match(jm).slice(1).reduce((t,r,n)=>(t[e3[n]]=parseFloat(r)||0,t),{}),Fm=(e,t)=>{const r=t?t.getTime():Date.now(),n=new Date(r);return n.setFullYear(n.getFullYear()+e.years),n.setMonth(n.getMonth()+e.months),n.setDate(n.getDate()+e.days),n.setHours(n.getHours()+e.hours),n.setMinutes(n.getMinutes()+e.minutes),n.setMilliseconds(n.getMilliseconds()+e.seconds*1e3),n.setDate(n.getDate()+e.weeks*7),n},VE=(e,t)=>{const r=t?t.getTime():Date.now(),n=new Date(r);return(Fm(e,n).getTime()-n.getTime())/1e3},t3={end:Fm,toSeconds:VE,pattern:jm,parse:HE},r3=Object.freeze(Object.defineProperty({__proto__:null,default:t3,end:Fm,parse:HE,pattern:jm,toSeconds:VE},Symbol.toStringTag,{value:"Module"})),n3=FT(r3);var i3=Qt,a3=Oa,s3=nn.f,Uh=i3("unscopables"),Bh=Array.prototype;Bh[Uh]===void 0&&s3(Bh,Uh,{configurable:!0,value:a3(null)});var Um=function(e){Bh[Uh][e]=!0},o3=Cn,Bm=Um,b_=Du,KE=En,u3=nn.f,c3=Dm,wc=wf,l3=er,JE="Array Iterator",f3=KE.set,d3=KE.getterFor(JE),YE=c3(Array,"Array",function(e,t){f3(this,{type:JE,target:o3(e),index:0,kind:t})},function(){var e=d3(this),t=e.target,r=e.index++;if(!t||r>=t.length)return e.target=null,wc(void 0,!0);switch(e.kind){case"keys":return wc(r,!1);case"values":return wc(t[r],!1)}return wc([r,t[r]],!1)},"values"),__=b_.Arguments=b_.Array;Bm("keys");Bm("values");Bm("entries");if(l3&&__.name!=="values")try{u3(__,"name",{value:"values"})}catch{}var w_=$t,XE=sE,p3=oE,Xo=YE,S_=Xi,h3=Ti,v3=Qt,Xd=v3("iterator"),Qd=Xo.values,QE=function(e,t){if(e){if(e[Xd]!==Qd)try{S_(e,Xd,Qd)}catch{e[Xd]=Qd}if(h3(e,t,!0),XE[t]){for(var r in Xo)if(e[r]!==Xo[r])try{S_(e,r,Xo[r])}catch{e[r]=Xo[r]}}}};for(var Zd in XE)QE(w_[Zd]&&w_[Zd].prototype,Zd);QE(p3,"DOMTokenList");var m3=Xt,g3=ar,T_=go,Sf=function(e,t,r){var n,i;return T_&&m3(n=t.constructor)&&n!==r&&g3(i=n.prototype)&&i!==r.prototype&&T_(e,i),e},y3=wt,b3=y3(1 .valueOf),_3=`
17
+ </dialog>`,sP='<button class="cobrowse-end js-cobrowse-end">$end</button>';class nm{constructor(t,r){ht(this,"_cobrowse");ht(this,"_options");ht(this,"_started",!1);ht(this,"focusTrap");this._cobrowse=t,this._options=r}get root(){return this._options.root||document.body}get lang(){return this._options.lang}get messages(){return this._options.messages}get template(){return this._options.template||aP}static async create(t,r){const n=await oP(r);n.license=t.license;const i=t.trustedOrigins||[];return i.push(location.origin),n.trustedOrigins=i,["api","capabilities","registration","redactedViews","unredactedViews"].forEach(s=>{t[s]!==void 0&&(n[s]=t[s])}),new nm(n,t)}setCustomData(t){this._cobrowse.customData=t}on(t,r){this._cobrowse.on(t,r)}async start(){this._started||(await this._cobrowse.client(),await this._cobrowse.start(),this._started=!0,this.setupConfirms(),this.setupSessionControl())}async stop(){await this._cobrowse.stop(),this._started=!1}async endSession(){this._cobrowse.currentSession&&await this._cobrowse.currentSession.end()}async createSessionCode(){return this._cobrowse.currentSession?this._cobrowse.currentSession.code():await this._cobrowse.createSessionCode()}createConfirmConsent(t){return()=>{const r=document.createElement("div");r.className="cobrowse-wrapper",r.lang=this.lang,r.innerHTML=t;const n=()=>{r.parentNode&&r.parentNode.removeChild(r),this.focusTrap&&(this.focusTrap.deactivate(),this.focusTrap=null)};return new Promise(i=>{this.root.appendChild(r);const a=r.querySelector(".js-cobrowse-allow");a==null||a.addEventListener("click",()=>{i(!0),n()});const s=r.querySelector(".js-cobrowse-deny");s==null||s.addEventListener("click",()=>{i(!1),n()}),this.focusTrap=iP(r,{clickOutsideDeactivates:!0,returnFocusOnDeactivate:!0}),this.focusTrap.activate()})}}setupConfirms(){this._cobrowse.confirmSession=this.createConfirmConsent(sc(this._options.confirmSessionTemplate||this.template,{title:this.messages.confirmSessionTitle,content:this.messages.confirmSessionContent,allow:this.messages.allowText,deny:this.messages.denyText})),this._cobrowse.confirmRemoteControl=this.createConfirmConsent(sc(this._options.confirmRemoteControlTemplate||this.template,{title:this.messages.confirmRemoteControlTitle,content:this.messages.confirmRemoteControlContent,allow:this.messages.allowText,deny:this.messages.denyText})),this._cobrowse.confirmFullDevice=this.createConfirmConsent(sc(this._options.confirmFullDeviceTemplate||this.template,{title:this.messages.confirmFullDeviceTitle,content:this.messages.confirmFullDeviceContent,allow:this.messages.allowText,deny:this.messages.denyText}))}setupSessionControl(){const t=this._options.sessionControlsTemplate||sP,r=document.createElement("div");r.className="cobrowse-end-wrapper",r.setAttribute("lang",this.lang),r.innerHTML=sc(t,{end:this.messages.endSessionText});const n=()=>{this.endSession()};this._cobrowse.showSessionControls=()=>{if(!this.root.contains(r)){const i=r.querySelector(".js-cobrowse-end");i&&i.addEventListener("click",n),this.root.appendChild(r)}},this._cobrowse.hideSessionControls=()=>{if(this.root.contains(r)){const i=r.querySelector(".js-cobrowse-end");i&&i.removeEventListener("click",n),this.root.removeChild(r)}}}}function oP(e){return window.CobrowseIO?window.CobrowseIO:new Promise(t=>{const r=document.createElement("script");r.src=e,r.async=!0;const n=document.getElementsByTagName("script")[0];n.parentNode.insertBefore(r,n),r.onload=function(){t(window.CobrowseIO)}})}function sc(e,t){let r=e;return Object.keys(t).forEach(n=>{const i=new RegExp("\\$"+n,"g");r=r.replace(i,t[n])}),r}const fd="ujet:",Br={set(e,t){return localStorage.setItem(fd+e,t)},get(e){return localStorage.getItem(fd+e)},del(e){return localStorage.removeItem(fd+e)}},uP=Date.now(),DT={href:window.location.href,interval:24*60*60};function cP(e){if(!Array.isArray(e)||!e.length)return null;const t=hP(),r=t===0,n=t+1;return vP(n),e.filter(a=>{const s=fP(a,DT.href),o=dP(a.visitor_type,r),u=n>=a.page_visit_count,c=!pP(a.id);return s&&o&&u&&c}).sort((a,s)=>a.stay_time-s.stay_time)[0]||null}function lP(e,t){const r=e.stay_time*1e3,n=Math.max(r-(Date.now()-uP),0);setTimeout(()=>{t(e),Br.set(`trigger:${e.id}`,(Date.now()/1e3).toString())},n)}const fP=(e,t)=>{const{keywords_included_or:r=[],keywords_excluded_or:n=[],keywords_included:i=[],keywords_excluded:a=[]}=e;if(kO(r,n,i,a))return!0;if(r.length||n.length){const u=r.some(l=>l.every(p=>t.includes(p))),c=n.length>0&&n.every(l=>l.every(p=>!t.includes(p)));return u||c}const s=i.filter(u=>t.indexOf(u)!==-1).length,o=a.filter(u=>t.indexOf(u)===-1).length;return!!s||!!o};function dP(e,t){return e==="visitor_type_new"?t:e==="visitor_type_returning"?!t:!0}function pP(e){try{const t=parseInt(Br.get(`trigger:${e}`),10);return Date.now()/1e3-t<DT.interval}catch{return!1}}function hP(){try{const e=Br.get("visits");return e?parseInt(e,10):0}catch{return 0}}function vP(e){try{Br.set("visits",e.toString())}catch(t){console.error(t)}}const mP=["photo","video","audio","document"];let gP=class{constructor(t){ht(this,"VERSION",Qv);ht(this,"options");ht(this,"communicator");ht(this,"methods");ht(this,"events",new em);ht(this,"request");ht(this,"chat");ht(this,"cobrowse");this.options=t,this.communicator=new MO(t,this.events);const r=this.communicator.request.bind(this.communicator);this.methods=new kA(r),this.request=r,t.host&&mT.setPath(t.host),qr.companyId=t.companyId,t.tenant&&(qr.tenant=t.tenant)}get deviceId(){return qr.deviceId}get user(){return this.communicator.user}get lang(){return this.options.lang?this.options.lang:Br.get("lang")||"en"}set lang(t){this.options.lang||Br.set("lang",t)}destroy(){this.communicator.destroy(),this.events.destroy()}on(t,r){this.events.addEventListener(t,r)}off(t,r){this.events.removeEventListener(t,r)}async getCompany(){return this.methods.getCompany().then(t=>(qr.tenant=t.subdomain,t)).catch(()=>null)}async runTrigger(t){const r=await this.methods.getTriggers(this.options.companyId).then(i=>i).catch(()=>[]),n=cP(r);n&&lP(n,t)}trackClientEvents(t){return this.methods.trackClientEvents(t)}async getProhibitedFileTypes(){return this.methods.listFileTypes().then(t=>t).catch(()=>[])}async getMenus(t,r){return this.methods.getMenus(r||this.lang,t).then(n=>n).catch(()=>null)}async getAfterHourMessage(t){return this.methods.getAfterHourMessage(t||this.lang).then(r=>r).catch(()=>"")}async getTimeSlots(t,r){return this.methods.getTimeSlots(t,r||this.lang).then(n=>n).catch(()=>[])}async getWaitTimes(t,r){return this.methods.getWaitTimes(t,r||this.lang).then(n=>n).catch(()=>null)}async verifyForm(t){return this.methods.verifyForm(t).then(r=>r).catch(()=>!1)}async createCall(t,r){var n;return!r.email&&((n=this.user)!=null&&n.email)&&(r.email=this.user.email),this.methods.createCall(Number(t),r.lang||this.lang,r).then(i=>i).catch(()=>null)}async loadCall(t){return this.methods.fetchCall(t).then(r=>r).catch(()=>null)}async cancelCall(t){return this.methods.cancelCall(t).then(r=>r).catch(()=>null)}async createEmail(t,r){await this.methods.createEmail(t,r.lang||this.lang,r)}async createChat(t,r={}){var n,i;if(this.chat&&this.chat.ongoing)throw new Error("There is an ongoing chat.");return!r.email&&((n=this.user)!=null&&n.email)&&(r.email=this.user.email),r.cobrowsable===void 0&&(r.cobrowsable=!!((i=this.options.cobrowse)!=null&&i.enabled)),this.methods.createChat(Number(t),r.lang||this.lang,r,this.deviceId).then(async a=>(this.registerOngoingChat(a),await a.clearMediaStore(),a)).catch(()=>null)}async loadChat(t){return this.methods.loadChat(t,this.deviceId).then(r=>(r.ongoing?this.registerOngoingChat(r):(Br.del("chat"),Br.del("cobrowse")),r)).catch(()=>null)}async resumeChat(t){var r;return((r=this.chat)==null?void 0:r.id)===Number(t)?this.methods.patch(`chats/${t}`,{status:"queued"}).then(n=>(this.chat.update(n.data),this.chat)).catch(()=>null):this.methods.resumeChat(t,this.deviceId).then(n=>(this.registerOngoingChat(n),n)).catch(()=>null)}async loadOngoingChat(){const t=Br.get("chat");return t?this.loadChat(t).then(r=>r.ongoing?r:(Br.del("chat"),null)).catch(()=>(Br.del("chat"),null)):null}async finishChat(){this.chat&&await this.methods.finishChat(this.chat.id).then(async t=>{this.chat.update(t),this.chat.connected&&this.chat.ended&&await this.chat.disconnect()})}async updatePostSession(t){this.chat&&(t===to.FINISHED||t===to.WAITING||await this.methods.updatePostSession(this.chat.id,t).then(r=>{this.chat.update(r)}))}async destroyChat(){if(this.chat){if(this.chat.muted=!0,this.chat.ongoing){const t=await this.methods.finishChat(this.chat.id);this.chat.update(t)}await this.chat.destroy(),this.chat=null,qr.trackerId=""}}async getChatDeflection(){return this.methods.getChatDeflection(this.chat.id).then(t=>t).catch(()=>null)}sendChatTranscripts(t){this.methods.sendChatTranscripts(this.chat.id,t)}async downloadChatTranscript(){return await this.methods.downloadChatTranscript(this.chat.id)}async getPdfStatus(t){return await this.methods.getPdfStatus(t)}async getChatSurvey(){return this.methods.getChatSurvey(this.chat.id).then(t=>t).catch(()=>null)}sendChatSurvey(t){if(this.chat.feedbackType!=="survey")throw new Error("Chat feedback type is: "+this.chat.feedbackType);this.methods.sendChatSurvey(this.chat.id,t)}sendChatRate(t){if(this.chat.feedbackType!=="rate")throw new Error("Chat feedback type is: "+this.chat.feedbackType);this.methods.rateChat(this.chat.id,t)}escalateChat(t){this.methods.escalateChat(this.chat.id,t)}trackChatEscalation(t,r){this.methods.trackEscalation(this.chat.id,t,r)}trackChatEndUserEvent(t){var r;!t.end_user_name&&((r=this.user)!=null&&r.name)&&(t.end_user_name=this.user.name),this.methods.trackChatEndUserEvent(this.chat.id,t)}async getChatHistory(t=1){return this.methods.getChatHistory(t).then(r=>r).catch(()=>null)}async fetchMessages(){return this.chat.fetchMessages().then(async t=>{if(t.filter(r=>r.type==="server_message").length>0){const r=await this.methods.listChatTaskMessages(this.chat.id);return NO(t,r)}return t}).catch(()=>[])}async sendFileMessage(t){return this.methods.uploadChatFile(this.chat.id,t).then(r=>this.chat.sendMessage(r,t)).catch(()=>-1)}async sendTextMessage(t){const r=TT(t);if(r){if(this.chat.inTask){const n=await this.methods.sendChatTaskMessage(this.chat.id,r);this.chat.sendMessage({type:"server_message",visibility:"task_virtual_agent",message_id:n.id});return}if(this.chat.state.redaction_enabled){await this.methods.sendChatTextMessage(this.chat.id,r);return}this.chat.sendMessage({type:"text",content:r})}}async sendPreviewMessage(t){try{if(this.isRedactionAgentEnabled()){const r=new Date().toISOString(),n=await this.methods.sendPreviewMessage(this.chat.id,t,r);return this.chat.preview(n==null?void 0:n.content)}return this.chat.preview(t)}catch(r){console.error("Error sending preview message:",r)}}isRedactionAgentEnabled(){return this.chat.state.redaction_enabled&&this.chat.state.agent_incoming_ha_enabled}async createCobrowseCode(t,r){var a;await this.initializeCobrowse(t||this.lang);let n=Br.get("cobrowse");n||(n=Date.now().toString(),Br.set("cobrowse",n));const i={device_id:this.deviceId,device_name:`${qr.application} / ${qr.version}`,nonce:n,...r};return(a=this.user)!=null&&a.name&&(i.user_name=this.user.name),this.cobrowse.setCustomData(i),this.cobrowse.createSessionCode().then(s=>s).catch(()=>null)}async startCobrowse(t="end_user"){if(!this.chat.cobrowsable)throw new Error(`Chat ${this.chat.id} does not support cobrowse.`);const r={chatId:`chat_${this.chat.id}`},n=await this.createCobrowseCode(this.chat.lang,r);if(!n)return;const i=Br.get("cobrowse");await this.methods.requestChatCobrowse(this.chat.id,{code:n,from:t,nonce:i})}async getMessageAttachment(t){if(t.$userType!=="end_user"&&mP.includes(t.type)){const r=await this.methods.getMedia(t.media_id,t.type);return this.chat&&this.chat.saveMedia(t.$index,r),r}return null}async initializeCobrowse(t){if(!this.cobrowse){const r=await this.getCompany(),n=this.getCobrowseScript(r.cobrowse_domain),i=this.options.cobrowse.messages||fA(t),a={...this.options.cobrowse,messages:i,lang:t};this.cobrowse=await nm.create(a,n),this.cobrowse.start(),["loaded","updated","ended"].forEach(o=>{this.cobrowse.on(`session.${o}`,u=>{this.events.triggerEvent(`cobrowse.${o}`,u)})})}}registerOngoingChat(t){this.events.triggerEvent("chat.ongoing",t),t._setGlobalEvents(this.events,this.methods.getChatTaskMessage.bind(this.methods)),t.on("_requestCobrowse",r=>{r==="agent"?this.startCobrowse(r):this.initializeCobrowse(t.lang),this.events.triggerEvent("cobrowse.request",{from:r})}),t.on("disconnected",()=>{Br.del("chat"),Br.del("cobrowse")}),this.chat=t,qr.trackerId=`chat_${t.id}`,Br.set("chat",t.id.toString()),t.cobrowsable&&Br.get("cobrowse")&&this.initializeCobrowse(t.lang)}getCobrowseScript(t){return!t||t.toLowerCase()==="https://cobrowse.io"?"https://js.cobrowse.io/CobrowseIO.js":`${t}/sdk-js/CobrowseIO.js`}_triggerEvent(t,r){this.events.triggerEvent(t,r)}};var je=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function jT(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function FT(e){if(e.__esModule)return e;var t=e.default;if(typeof t=="function"){var r=function n(){return this instanceof n?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(n){var i=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(r,n,i.get?i:{enumerable:!0,get:function(){return e[n]}})}),r}var UT={},xo=function(e){return e&&e.Math===Math&&e},$t=xo(typeof globalThis=="object"&&globalThis)||xo(typeof window=="object"&&window)||xo(typeof self=="object"&&self)||xo(typeof je=="object"&&je)||xo(typeof je=="object"&&je)||function(){return this}()||Function("return this")(),Ji={},yt=function(e){try{return!!e()}catch{return!0}},yP=yt,er=!yP(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7}),bP=yt,_u=!bP(function(){var e=(function(){}).bind();return typeof e!="function"||e.hasOwnProperty("prototype")}),_P=_u,oc=Function.prototype.call,Yt=_P?oc.bind(oc):function(){return oc.apply(oc,arguments)},wu={},BT={}.propertyIsEnumerable,qT=Object.getOwnPropertyDescriptor,wP=qT&&!BT.call({1:2},1);wu.f=wP?function(t){var r=qT(this,t);return!!r&&r.enumerable}:BT;var ls=function(e,t){return{enumerable:!(e&1),configurable:!(e&2),writable:!(e&4),value:t}},zT=_u,WT=Function.prototype,yh=WT.call,SP=zT&&WT.bind.bind(yh,yh),wt=zT?SP:function(e){return function(){return yh.apply(e,arguments)}},GT=wt,TP=GT({}.toString),CP=GT("".slice),wi=function(e){return CP(TP(e),8,-1)},EP=wt,kP=yt,RP=wi,dd=Object,$P=EP("".split),Su=kP(function(){return!dd("z").propertyIsEnumerable(0)})?function(e){return RP(e)==="String"?$P(e,""):dd(e)}:dd,ai=function(e){return e==null},IP=ai,OP=TypeError,si=function(e){if(IP(e))throw new OP("Can't call method on "+e);return e},AP=Su,PP=si,Cn=function(e){return AP(PP(e))},pd=typeof document=="object"&&document.all,Xt=typeof pd>"u"&&pd!==void 0?function(e){return typeof e=="function"||e===pd}:function(e){return typeof e=="function"},MP=Xt,ar=function(e){return typeof e=="object"?e!==null:MP(e)},hd=$t,xP=Xt,NP=function(e){return xP(e)?e:void 0},Un=function(e,t){return arguments.length<2?NP(hd[e]):hd[e]&&hd[e][t]},LP=wt,Yi=LP({}.isPrototypeOf),DP=$t,Cy=DP.navigator,Ey=Cy&&Cy.userAgent,Ia=Ey?String(Ey):"",HT=$t,vd=Ia,ky=HT.process,Ry=HT.Deno,$y=ky&&ky.versions||Ry&&Ry.version,Iy=$y&&$y.v8,Zn,Nl;Iy&&(Zn=Iy.split("."),Nl=Zn[0]>0&&Zn[0]<4?1:+(Zn[0]+Zn[1]));!Nl&&vd&&(Zn=vd.match(/Edge\/(\d+)/),(!Zn||Zn[1]>=74)&&(Zn=vd.match(/Chrome\/(\d+)/),Zn&&(Nl=+Zn[1])));var po=Nl,Oy=po,jP=yt,FP=$t,UP=FP.String,ho=!!Object.getOwnPropertySymbols&&!jP(function(){var e=Symbol("symbol detection");return!UP(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&Oy&&Oy<41}),BP=ho,VT=BP&&!Symbol.sham&&typeof Symbol.iterator=="symbol",qP=Un,zP=Xt,WP=Yi,GP=VT,HP=Object,vo=GP?function(e){return typeof e=="symbol"}:function(e){var t=qP("Symbol");return zP(t)&&WP(t.prototype,HP(e))},VP=String,fs=function(e){try{return VP(e)}catch{return"Object"}},KP=Xt,JP=fs,YP=TypeError,Bn=function(e){if(KP(e))return e;throw new YP(JP(e)+" is not a function")},XP=Bn,QP=ai,ds=function(e,t){var r=e[t];return QP(r)?void 0:XP(r)},md=Yt,gd=Xt,yd=ar,ZP=TypeError,eM=function(e,t){var r,n;if(t==="string"&&gd(r=e.toString)&&!yd(n=md(r,e))||gd(r=e.valueOf)&&!yd(n=md(r,e))||t!=="string"&&gd(r=e.toString)&&!yd(n=md(r,e)))return n;throw new ZP("Can't convert object to primitive value")},KT={exports:{}},JT=!1,Ay=$t,tM=Object.defineProperty,im=function(e,t){try{tM(Ay,e,{value:t,configurable:!0,writable:!0})}catch{Ay[e]=t}return t},rM=$t,nM=im,Py="__core-js_shared__",My=KT.exports=rM[Py]||nM(Py,{});(My.versions||(My.versions=[])).push({version:"3.39.0",mode:"global",copyright:"© 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.39.0/LICENSE",source:"https://github.com/zloirock/core-js"});var am=KT.exports,xy=am,mo=function(e,t){return xy[e]||(xy[e]=t||{})},iM=si,aM=Object,Jr=function(e){return aM(iM(e))},sM=wt,oM=Jr,uM=sM({}.hasOwnProperty),vr=Object.hasOwn||function(t,r){return uM(oM(t),r)},cM=wt,lM=0,fM=Math.random(),dM=cM(1 .toString),Tu=function(e){return"Symbol("+(e===void 0?"":e)+")_"+dM(++lM+fM,36)},pM=$t,hM=mo,Ny=vr,vM=Tu,mM=ho,gM=VT,Fs=pM.Symbol,bd=hM("wks"),yM=gM?Fs.for||Fs:Fs&&Fs.withoutSetter||vM,Qt=function(e){return Ny(bd,e)||(bd[e]=mM&&Ny(Fs,e)?Fs[e]:yM("Symbol."+e)),bd[e]},bM=Yt,Ly=ar,Dy=vo,_M=ds,wM=eM,SM=Qt,TM=TypeError,CM=SM("toPrimitive"),sm=function(e,t){if(!Ly(e)||Dy(e))return e;var r=_M(e,CM),n;if(r){if(t===void 0&&(t="default"),n=bM(r,e,t),!Ly(n)||Dy(n))return n;throw new TM("Can't convert object to primitive value")}return t===void 0&&(t="number"),wM(e,t)},EM=sm,kM=vo,nf=function(e){var t=EM(e,"string");return kM(t)?t:t+""},RM=$t,jy=ar,bh=RM.document,$M=jy(bh)&&jy(bh.createElement),af=function(e){return $M?bh.createElement(e):{}},IM=er,OM=yt,AM=af,YT=!IM&&!OM(function(){return Object.defineProperty(AM("div"),"a",{get:function(){return 7}}).a!==7}),PM=er,MM=Yt,xM=wu,NM=ls,LM=Cn,DM=nf,jM=vr,FM=YT,Fy=Object.getOwnPropertyDescriptor;Ji.f=PM?Fy:function(t,r){if(t=LM(t),r=DM(r),FM)try{return Fy(t,r)}catch{}if(jM(t,r))return NM(!MM(xM.f,t,r),t[r])};var nn={},UM=er,BM=yt,XT=UM&&BM(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42}),qM=ar,zM=String,WM=TypeError,wr=function(e){if(qM(e))return e;throw new WM(zM(e)+" is not an object")},GM=er,HM=YT,VM=XT,uc=wr,Uy=nf,KM=TypeError,_d=Object.defineProperty,JM=Object.getOwnPropertyDescriptor,wd="enumerable",Sd="configurable",Td="writable";nn.f=GM?VM?function(t,r,n){if(uc(t),r=Uy(r),uc(n),typeof t=="function"&&r==="prototype"&&"value"in n&&Td in n&&!n[Td]){var i=JM(t,r);i&&i[Td]&&(t[r]=n.value,n={configurable:Sd in n?n[Sd]:i[Sd],enumerable:wd in n?n[wd]:i[wd],writable:!1})}return _d(t,r,n)}:_d:function(t,r,n){if(uc(t),r=Uy(r),uc(n),HM)try{return _d(t,r,n)}catch{}if("get"in n||"set"in n)throw new KM("Accessors not supported");return"value"in n&&(t[r]=n.value),t};var YM=er,XM=nn,QM=ls,Xi=YM?function(e,t,r){return XM.f(e,t,QM(1,r))}:function(e,t,r){return e[t]=r,e},QT={exports:{}},_h=er,ZM=vr,ZT=Function.prototype,ex=_h&&Object.getOwnPropertyDescriptor,om=ZM(ZT,"name"),tx=om&&(function(){}).name==="something",rx=om&&(!_h||_h&&ex(ZT,"name").configurable),Cu={EXISTS:om,PROPER:tx,CONFIGURABLE:rx},nx=wt,ix=Xt,wh=am,ax=nx(Function.toString);ix(wh.inspectSource)||(wh.inspectSource=function(e){return ax(e)});var um=wh.inspectSource,sx=$t,ox=Xt,By=sx.WeakMap,ux=ox(By)&&/native code/.test(String(By)),cx=mo,lx=Tu,qy=cx("keys"),sf=function(e){return qy[e]||(qy[e]=lx(e))},Eu={},fx=ux,eC=$t,dx=ar,px=Xi,Cd=vr,Ed=am,hx=sf,vx=Eu,zy="Object already initialized",Sh=eC.TypeError,mx=eC.WeakMap,Ll,fu,Dl,gx=function(e){return Dl(e)?fu(e):Ll(e,{})},yx=function(e){return function(t){var r;if(!dx(t)||(r=fu(t)).type!==e)throw new Sh("Incompatible receiver, "+e+" required");return r}};if(fx||Ed.state){var pi=Ed.state||(Ed.state=new mx);pi.get=pi.get,pi.has=pi.has,pi.set=pi.set,Ll=function(e,t){if(pi.has(e))throw new Sh(zy);return t.facade=e,pi.set(e,t),t},fu=function(e){return pi.get(e)||{}},Dl=function(e){return pi.has(e)}}else{var ks=hx("state");vx[ks]=!0,Ll=function(e,t){if(Cd(e,ks))throw new Sh(zy);return t.facade=e,px(e,ks,t),t},fu=function(e){return Cd(e,ks)?e[ks]:{}},Dl=function(e){return Cd(e,ks)}}var En={set:Ll,get:fu,has:Dl,enforce:gx,getterFor:yx},cm=wt,bx=yt,_x=Xt,cc=vr,Th=er,wx=Cu.CONFIGURABLE,Sx=um,tC=En,Tx=tC.enforce,Cx=tC.get,Wy=String,hl=Object.defineProperty,Ex=cm("".slice),kx=cm("".replace),Rx=cm([].join),$x=Th&&!bx(function(){return hl(function(){},"length",{value:8}).length!==8}),Ix=String(String).split("String"),Ox=QT.exports=function(e,t,r){Ex(Wy(t),0,7)==="Symbol("&&(t="["+kx(Wy(t),/^Symbol\(([^)]*)\).*$/,"$1")+"]"),r&&r.getter&&(t="get "+t),r&&r.setter&&(t="set "+t),(!cc(e,"name")||wx&&e.name!==t)&&(Th?hl(e,"name",{value:t,configurable:!0}):e.name=t),$x&&r&&cc(r,"arity")&&e.length!==r.arity&&hl(e,"length",{value:r.arity});try{r&&cc(r,"constructor")&&r.constructor?Th&&hl(e,"prototype",{writable:!1}):e.prototype&&(e.prototype=void 0)}catch{}var n=Tx(e);return cc(n,"source")||(n.source=Rx(Ix,typeof t=="string"?t:"")),e};Function.prototype.toString=Ox(function(){return _x(this)&&Cx(this).source||Sx(this)},"toString");var rC=QT.exports,Ax=Xt,Px=nn,Mx=rC,xx=im,an=function(e,t,r,n){n||(n={});var i=n.enumerable,a=n.name!==void 0?n.name:t;if(Ax(r)&&Mx(r,a,n),n.global)i?e[t]=r:xx(t,r);else{try{n.unsafe?e[t]&&(i=!0):delete e[t]}catch{}i?e[t]=r:Px.f(e,t,{value:r,enumerable:!1,configurable:!n.nonConfigurable,writable:!n.nonWritable})}return e},ps={},Nx=Math.ceil,Lx=Math.floor,Dx=Math.trunc||function(t){var r=+t;return(r>0?Lx:Nx)(r)},jx=Dx,Si=function(e){var t=+e;return t!==t||t===0?0:jx(t)},Fx=Si,Ux=Math.max,Bx=Math.min,hs=function(e,t){var r=Fx(e);return r<0?Ux(r+t,0):Bx(r,t)},qx=Si,zx=Math.min,Qi=function(e){var t=qx(e);return t>0?zx(t,9007199254740991):0},Wx=Qi,Yr=function(e){return Wx(e.length)},Gx=Cn,Hx=hs,Vx=Yr,Gy=function(e){return function(t,r,n){var i=Gx(t),a=Vx(i);if(a===0)return!e&&-1;var s=Hx(n,a),o;if(e&&r!==r){for(;a>s;)if(o=i[s++],o!==o)return!0}else for(;a>s;s++)if((e||s in i)&&i[s]===r)return e||s||0;return!e&&-1}},of={includes:Gy(!0),indexOf:Gy(!1)},Kx=wt,kd=vr,Jx=Cn,Yx=of.indexOf,Xx=Eu,Hy=Kx([].push),nC=function(e,t){var r=Jx(e),n=0,i=[],a;for(a in r)!kd(Xx,a)&&kd(r,a)&&Hy(i,a);for(;t.length>n;)kd(r,a=t[n++])&&(~Yx(i,a)||Hy(i,a));return i},lm=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Qx=nC,Zx=lm,eN=Zx.concat("length","prototype");ps.f=Object.getOwnPropertyNames||function(t){return Qx(t,eN)};var ku={};ku.f=Object.getOwnPropertySymbols;var tN=Un,rN=wt,nN=ps,iN=ku,aN=wr,sN=rN([].concat),iC=tN("Reflect","ownKeys")||function(t){var r=nN.f(aN(t)),n=iN.f;return n?sN(r,n(t)):r},Vy=vr,oN=iC,uN=Ji,cN=nn,fm=function(e,t,r){for(var n=oN(t),i=cN.f,a=uN.f,s=0;s<n.length;s++){var o=n[s];!Vy(e,o)&&!(r&&Vy(r,o))&&i(e,o,a(t,o))}},lN=yt,fN=Xt,dN=/#|\.prototype\./,Ru=function(e,t){var r=hN[pN(e)];return r===mN?!0:r===vN?!1:fN(t)?lN(t):!!t},pN=Ru.normalize=function(e){return String(e).replace(dN,".").toLowerCase()},hN=Ru.data={},vN=Ru.NATIVE="N",mN=Ru.POLYFILL="P",uf=Ru,lc=$t,gN=Ji.f,yN=Xi,bN=an,_N=im,wN=fm,SN=uf,Ct=function(e,t){var r=e.target,n=e.global,i=e.stat,a,s,o,u,c,l;if(n?s=lc:i?s=lc[r]||_N(r,{}):s=lc[r]&&lc[r].prototype,s)for(o in t){if(c=t[o],e.dontCallGetSet?(l=gN(s,o),u=l&&l.value):u=s[o],a=SN(n?o:r+(i?".":"#")+o,e.forced),!a&&u!==void 0){if(typeof c==typeof u)continue;wN(c,u)}(e.sham||u&&u.sham)&&yN(c,"sham",!0),bN(s,o,c,e)}},TN=nn.f,CN=vr,EN=Qt,Ky=EN("toStringTag"),Ti=function(e,t,r){e&&!r&&(e=e.prototype),e&&!CN(e,Ky)&&TN(e,Ky,{configurable:!0,value:t})},kN=Ct,RN=$t,$N=Ti;kN({global:!0},{Reflect:{}});$N(RN.Reflect,"Reflect",!0);var IN=_u,aC=Function.prototype,Jy=aC.apply,Yy=aC.call,vs=typeof Reflect=="object"&&Reflect.apply||(IN?Yy.bind(Jy):function(){return Yy.apply(Jy,arguments)}),ON=wt,Ci=ON([].slice),sC=wt,AN=Bn,PN=ar,MN=vr,Xy=Ci,xN=_u,oC=Function,NN=sC([].concat),LN=sC([].join),Rd={},DN=function(e,t,r){if(!MN(Rd,t)){for(var n=[],i=0;i<t;i++)n[i]="a["+i+"]";Rd[t]=oC("C,a","return new C("+LN(n,",")+")")}return Rd[t](e,r)},jN=xN?oC.bind:function(t){var r=AN(this),n=r.prototype,i=Xy(arguments,1),a=function(){var o=NN(i,Xy(arguments));return this instanceof a?DN(r,o.length,o):r.apply(t,o)};return PN(n)&&(a.prototype=n),a},FN=Qt,UN=FN("toStringTag"),uC={};uC[UN]="z";var dm=String(uC)==="[object z]",BN=dm,qN=Xt,vl=wi,zN=Qt,WN=zN("toStringTag"),GN=Object,HN=vl(function(){return arguments}())==="Arguments",VN=function(e,t){try{return e[t]}catch{}},Zi=BN?vl:function(e){var t,r,n;return e===void 0?"Undefined":e===null?"Null":typeof(r=VN(t=GN(e),WN))=="string"?r:HN?vl(t):(n=vl(t))==="Object"&&qN(t.callee)?"Arguments":n},KN=wt,JN=yt,cC=Xt,YN=Zi,XN=Un,QN=um,lC=function(){},fC=XN("Reflect","construct"),pm=/^\s*(?:class|function)\b/,ZN=KN(pm.exec),eL=!pm.test(lC),No=function(t){if(!cC(t))return!1;try{return fC(lC,[],t),!0}catch{return!1}},dC=function(t){if(!cC(t))return!1;switch(YN(t)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return eL||!!ZN(pm,QN(t))}catch{return!0}};dC.sham=!0;var cf=!fC||JN(function(){var e;return No(No.call)||!No(Object)||!No(function(){e=!0})||e})?dC:No,tL=cf,rL=fs,nL=TypeError,hm=function(e){if(tL(e))return e;throw new nL(rL(e)+" is not a constructor")},vm={},iL=nC,aL=lm,$u=Object.keys||function(t){return iL(t,aL)},sL=er,oL=XT,uL=nn,cL=wr,lL=Cn,fL=$u;vm.f=sL&&!oL?Object.defineProperties:function(t,r){cL(t);for(var n=lL(r),i=fL(r),a=i.length,s=0,o;a>s;)uL.f(t,o=i[s++],n[o]);return t};var dL=Un,pC=dL("document","documentElement"),pL=wr,hL=vm,Qy=lm,vL=Eu,mL=pC,gL=af,yL=sf,Zy=">",eb="<",Ch="prototype",Eh="script",hC=yL("IE_PROTO"),$d=function(){},vC=function(e){return eb+Eh+Zy+e+eb+"/"+Eh+Zy},tb=function(e){e.write(vC("")),e.close();var t=e.parentWindow.Object;return e=null,t},bL=function(){var e=gL("iframe"),t="java"+Eh+":",r;return e.style.display="none",mL.appendChild(e),e.src=String(t),r=e.contentWindow.document,r.open(),r.write(vC("document.F=Object")),r.close(),r.F},fc,ml=function(){try{fc=new ActiveXObject("htmlfile")}catch{}ml=typeof document<"u"?document.domain&&fc?tb(fc):bL():tb(fc);for(var e=Qy.length;e--;)delete ml[Ch][Qy[e]];return ml()};vL[hC]=!0;var Oa=Object.create||function(t,r){var n;return t!==null?($d[Ch]=pL(t),n=new $d,$d[Ch]=null,n[hC]=t):n=ml(),r===void 0?n:hL.f(n,r)},_L=Ct,wL=Un,Id=vs,SL=jN,rb=hm,TL=wr,nb=ar,CL=Oa,mC=yt,mm=wL("Reflect","construct"),EL=Object.prototype,kL=[].push,gC=mC(function(){function e(){}return!(mm(function(){},[],e)instanceof e)}),yC=!mC(function(){mm(function(){})}),ib=gC||yC;_L({target:"Reflect",stat:!0,forced:ib,sham:ib},{construct:function(t,r){rb(t),TL(r);var n=arguments.length<3?t:rb(arguments[2]);if(yC&&!gC)return mm(t,r,n);if(t===n){switch(r.length){case 0:return new t;case 1:return new t(r[0]);case 2:return new t(r[0],r[1]);case 3:return new t(r[0],r[1],r[2]);case 4:return new t(r[0],r[1],r[2],r[3])}var i=[null];return Id(kL,i,r),new(Id(SL,t,i))}var a=n.prototype,s=CL(nb(a)?a:EL),o=Id(t,s,r);return nb(o)?o:s}});var RL=Ct,$L=Jr,bC=$u,IL=yt,OL=IL(function(){bC(1)});RL({target:"Object",stat:!0,forced:OL},{keys:function(t){return bC($L(t))}});var AL=Zi,PL=String,Lr=function(e){if(AL(e)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return PL(e)},gm={},ML=wi,xL=Cn,_C=ps.f,NL=Ci,wC=typeof window=="object"&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],LL=function(e){try{return _C(e)}catch{return NL(wC)}};gm.f=function(t){return wC&&ML(t)==="Window"?LL(t):_C(xL(t))};var ab=rC,DL=nn,Ei=function(e,t,r){return r.get&&ab(r.get,t,{getter:!0}),r.set&&ab(r.set,t,{setter:!0}),DL.f(e,t,r)},ym={},jL=Qt;ym.f=jL;var FL=$t,SC=FL,sb=SC,UL=vr,BL=ym,qL=nn.f,TC=function(e){var t=sb.Symbol||(sb.Symbol={});UL(t,e)||qL(t,e,{value:BL.f(e)})},zL=Yt,WL=Un,GL=Qt,HL=an,VL=function(){var e=WL("Symbol"),t=e&&e.prototype,r=t&&t.valueOf,n=GL("toPrimitive");t&&!t[n]&&HL(t,n,function(i){return zL(r,this)},{arity:1})},KL=wi,JL=wt,bm=function(e){if(KL(e)==="Function")return JL(e)},ob=bm,YL=Bn,XL=_u,QL=ob(ob.bind),ea=function(e,t){return YL(e),t===void 0?e:XL?QL(e,t):function(){return e.apply(t,arguments)}},ZL=wi,Iu=Array.isArray||function(t){return ZL(t)==="Array"},ub=Iu,eD=cf,tD=ar,rD=Qt,nD=rD("species"),cb=Array,iD=function(e){var t;return ub(e)&&(t=e.constructor,eD(t)&&(t===cb||ub(t.prototype))?t=void 0:tD(t)&&(t=t[nD],t===null&&(t=void 0))),t===void 0?cb:t},aD=iD,_m=function(e,t){return new(aD(e))(t===0?0:t)},sD=ea,oD=wt,uD=Su,cD=Jr,lD=Yr,fD=_m,lb=oD([].push),za=function(e){var t=e===1,r=e===2,n=e===3,i=e===4,a=e===6,s=e===7,o=e===5||a;return function(u,c,l,p){for(var v=cD(u),m=uD(v),b=lD(m),T=sD(c,l),I=0,R=p||fD,x=t?R(u,b):r||s?R(u,0):void 0,N,j;b>I;I++)if((o||I in m)&&(N=m[I],j=T(N,I,v),e))if(t)x[I]=j;else if(j)switch(e){case 3:return!0;case 5:return N;case 6:return I;case 2:lb(x,N)}else switch(e){case 4:return!1;case 7:lb(x,N)}return a?-1:n||i?i:x}},vn={forEach:za(0),map:za(1),filter:za(2),some:za(3),every:za(4),find:za(5),findIndex:za(6)},lf=Ct,Ou=$t,wm=Yt,dD=wt,ro=er,no=ho,pD=yt,zr=vr,hD=Yi,kh=wr,ff=Cn,Sm=nf,vD=Lr,Rh=ls,io=Oa,CC=$u,mD=ps,EC=gm,gD=ku,kC=Ji,RC=nn,yD=vm,$C=wu,Od=an,bD=Ei,Tm=mo,_D=sf,IC=Eu,fb=Tu,wD=Qt,SD=ym,TD=TC,CD=VL,ED=Ti,OC=En,df=vn.forEach,fn=_D("hidden"),pf="Symbol",du="prototype",kD=OC.set,db=OC.getterFor(pf),jn=Object[du],rs=Ou.Symbol,Yo=rs&&rs[du],RD=Ou.RangeError,$D=Ou.TypeError,Ad=Ou.QObject,AC=kC.f,ns=RC.f,PC=EC.f,ID=$C.f,MC=dD([].push),Gi=Tm("symbols"),Au=Tm("op-symbols"),OD=Tm("wks"),$h=!Ad||!Ad[du]||!Ad[du].findChild,xC=function(e,t,r){var n=AC(jn,t);n&&delete jn[t],ns(e,t,r),n&&e!==jn&&ns(jn,t,n)},Ih=ro&&pD(function(){return io(ns({},"a",{get:function(){return ns(this,"a",{value:7}).a}})).a!==7})?xC:ns,Pd=function(e,t){var r=Gi[e]=io(Yo);return kD(r,{type:pf,tag:e,description:t}),ro||(r.description=t),r},hf=function(t,r,n){t===jn&&hf(Au,r,n),kh(t);var i=Sm(r);return kh(n),zr(Gi,i)?(n.enumerable?(zr(t,fn)&&t[fn][i]&&(t[fn][i]=!1),n=io(n,{enumerable:Rh(0,!1)})):(zr(t,fn)||ns(t,fn,Rh(1,io(null))),t[fn][i]=!0),Ih(t,i,n)):ns(t,i,n)},Cm=function(t,r){kh(t);var n=ff(r),i=CC(n).concat(DC(n));return df(i,function(a){(!ro||wm(Oh,n,a))&&hf(t,a,n[a])}),t},AD=function(t,r){return r===void 0?io(t):Cm(io(t),r)},Oh=function(t){var r=Sm(t),n=wm(ID,this,r);return this===jn&&zr(Gi,r)&&!zr(Au,r)?!1:n||!zr(this,r)||!zr(Gi,r)||zr(this,fn)&&this[fn][r]?n:!0},NC=function(t,r){var n=ff(t),i=Sm(r);if(!(n===jn&&zr(Gi,i)&&!zr(Au,i))){var a=AC(n,i);return a&&zr(Gi,i)&&!(zr(n,fn)&&n[fn][i])&&(a.enumerable=!0),a}},LC=function(t){var r=PC(ff(t)),n=[];return df(r,function(i){!zr(Gi,i)&&!zr(IC,i)&&MC(n,i)}),n},DC=function(e){var t=e===jn,r=PC(t?Au:ff(e)),n=[];return df(r,function(i){zr(Gi,i)&&(!t||zr(jn,i))&&MC(n,Gi[i])}),n};no||(rs=function(){if(hD(Yo,this))throw new $D("Symbol is not a constructor");var t=!arguments.length||arguments[0]===void 0?void 0:vD(arguments[0]),r=fb(t),n=function(i){var a=this===void 0?Ou:this;a===jn&&wm(n,Au,i),zr(a,fn)&&zr(a[fn],r)&&(a[fn][r]=!1);var s=Rh(1,i);try{Ih(a,r,s)}catch(o){if(!(o instanceof RD))throw o;xC(a,r,s)}};return ro&&$h&&Ih(jn,r,{configurable:!0,set:n}),Pd(r,t)},Yo=rs[du],Od(Yo,"toString",function(){return db(this).tag}),Od(rs,"withoutSetter",function(e){return Pd(fb(e),e)}),$C.f=Oh,RC.f=hf,yD.f=Cm,kC.f=NC,mD.f=EC.f=LC,gD.f=DC,SD.f=function(e){return Pd(wD(e),e)},ro&&(bD(Yo,"description",{configurable:!0,get:function(){return db(this).description}}),Od(jn,"propertyIsEnumerable",Oh,{unsafe:!0})));lf({global:!0,constructor:!0,wrap:!0,forced:!no,sham:!no},{Symbol:rs});df(CC(OD),function(e){TD(e)});lf({target:pf,stat:!0,forced:!no},{useSetter:function(){$h=!0},useSimple:function(){$h=!1}});lf({target:"Object",stat:!0,forced:!no,sham:!ro},{create:AD,defineProperty:hf,defineProperties:Cm,getOwnPropertyDescriptor:NC});lf({target:"Object",stat:!0,forced:!no},{getOwnPropertyNames:LC});CD();ED(rs,pf);IC[fn]=!0;var PD=ho,jC=PD&&!!Symbol.for&&!!Symbol.keyFor,MD=Ct,xD=Un,ND=vr,LD=Lr,FC=mo,DD=jC,Md=FC("string-to-symbol-registry"),jD=FC("symbol-to-string-registry");MD({target:"Symbol",stat:!0,forced:!DD},{for:function(e){var t=LD(e);if(ND(Md,t))return Md[t];var r=xD("Symbol")(t);return Md[t]=r,jD[r]=t,r}});var FD=Ct,UD=vr,BD=vo,qD=fs,zD=mo,WD=jC,pb=zD("symbol-to-string-registry");FD({target:"Symbol",stat:!0,forced:!WD},{keyFor:function(t){if(!BD(t))throw new TypeError(qD(t)+" is not a symbol");if(UD(pb,t))return pb[t]}});var GD=wt,hb=Iu,HD=Xt,vb=wi,VD=Lr,mb=GD([].push),KD=function(e){if(HD(e))return e;if(hb(e)){for(var t=e.length,r=[],n=0;n<t;n++){var i=e[n];typeof i=="string"?mb(r,i):(typeof i=="number"||vb(i)==="Number"||vb(i)==="String")&&mb(r,VD(i))}var a=r.length,s=!0;return function(o,u){if(s)return s=!1,u;if(hb(this))return u;for(var c=0;c<a;c++)if(r[c]===o)return u}}},JD=Ct,UC=Un,BC=vs,YD=Yt,Pu=wt,qC=yt,gb=Xt,yb=vo,zC=Ci,XD=KD,QD=ho,ZD=String,wa=UC("JSON","stringify"),dc=Pu(/./.exec),bb=Pu("".charAt),e2=Pu("".charCodeAt),t2=Pu("".replace),r2=Pu(1 .toString),n2=/[\uD800-\uDFFF]/g,_b=/^[\uD800-\uDBFF]$/,wb=/^[\uDC00-\uDFFF]$/,Sb=!QD||qC(function(){var e=UC("Symbol")("stringify detection");return wa([e])!=="[null]"||wa({a:e})!=="{}"||wa(Object(e))!=="{}"}),Tb=qC(function(){return wa("\uDF06\uD834")!=='"\\udf06\\ud834"'||wa("\uDEAD")!=='"\\udead"'}),i2=function(e,t){var r=zC(arguments),n=XD(t);if(!(!gb(n)&&(e===void 0||yb(e))))return r[1]=function(i,a){if(gb(n)&&(a=YD(n,this,ZD(i),a)),!yb(a))return a},BC(wa,null,r)},a2=function(e,t,r){var n=bb(r,t-1),i=bb(r,t+1);return dc(_b,e)&&!dc(wb,i)||dc(wb,e)&&!dc(_b,n)?"\\u"+r2(e2(e,0),16):e};wa&&JD({target:"JSON",stat:!0,arity:3,forced:Sb||Tb},{stringify:function(t,r,n){var i=zC(arguments),a=BC(Sb?i2:wa,null,i);return Tb&&typeof a=="string"?t2(a,n2,a2):a}});var s2=Ct,o2=ho,u2=yt,WC=ku,c2=Jr,l2=!o2||u2(function(){WC.f(1)});s2({target:"Object",stat:!0,forced:l2},{getOwnPropertySymbols:function(t){var r=WC.f;return r?r(c2(t)):[]}});var f2=yt,d2=Qt,p2=po,h2=d2("species"),Mu=function(e){return p2>=51||!f2(function(){var t=[],r=t.constructor={};return r[h2]=function(){return{foo:1}},t[e](Boolean).foo!==1})},v2=Ct,m2=vn.filter,g2=Mu,y2=g2("filter");v2({target:"Array",proto:!0,forced:!y2},{filter:function(t){return m2(this,t,arguments.length>1?arguments[1]:void 0)}});var b2=Ct,_2=yt,w2=Cn,GC=Ji.f,HC=er,S2=!HC||_2(function(){GC(1)});b2({target:"Object",stat:!0,forced:S2,sham:!HC},{getOwnPropertyDescriptor:function(t,r){return GC(w2(t),r)}});var T2=er,C2=nn,E2=ls,xu=function(e,t,r){T2?C2.f(e,t,E2(0,r)):e[t]=r},k2=Ct,R2=er,$2=iC,I2=Cn,O2=Ji,A2=xu;k2({target:"Object",stat:!0,sham:!R2},{getOwnPropertyDescriptors:function(t){for(var r=I2(t),n=O2.f,i=$2(r),a={},s=0,o,u;i.length>s;)u=n(r,o=i[s++]),u!==void 0&&A2(a,o,u);return a}});var VC={exports:{}};(function(e){function t(n,i,a,s,o,u,c){try{var l=n[u](c),p=l.value}catch(v){return void a(v)}l.done?i(p):Promise.resolve(p).then(s,o)}function r(n){return function(){var i=this,a=arguments;return new Promise(function(s,o){var u=n.apply(i,a);function c(p){t(u,s,o,c,l,"next",p)}function l(p){t(u,s,o,c,l,"throw",p)}c(void 0)})}}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports})(VC);var Nu=VC.exports,KC={exports:{}};(function(e){function t(r){if(r===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return r}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports})(KC);var ms=KC.exports,JC={exports:{}},YC={exports:{}};(function(e){function t(r,n){return e.exports=t=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(i,a){return i.__proto__=a,i},e.exports.__esModule=!0,e.exports.default=e.exports,t(r,n)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports})(YC);var Em=YC.exports;(function(e){var t=Em;function r(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&&t(n,i)}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports})(JC);var ki=JC.exports,XC={exports:{}},QC={exports:{}};(function(e){function t(r){"@babel/helpers - typeof";return e.exports=t=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},e.exports.__esModule=!0,e.exports.default=e.exports,t(r)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports})(QC);var qn=QC.exports;(function(e){var t=qn.default,r=ms;function n(i,a){if(a&&(t(a)=="object"||typeof a=="function"))return a;if(a!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return r(i)}e.exports=n,e.exports.__esModule=!0,e.exports.default=e.exports})(XC);var Ri=XC.exports,ZC={exports:{}};(function(e){function t(r){return e.exports=t=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(n){return n.__proto__||Object.getPrototypeOf(n)},e.exports.__esModule=!0,e.exports.default=e.exports,t(r)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports})(ZC);var zn=ZC.exports,eE={exports:{}},tE={exports:{}},rE={exports:{}};(function(e){var t=qn.default;function r(n,i){if(t(n)!="object"||!n)return n;var a=n[Symbol.toPrimitive];if(a!==void 0){var s=a.call(n,i||"default");if(t(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(i==="string"?String:Number)(n)}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports})(rE);var P2=rE.exports;(function(e){var t=qn.default,r=P2;function n(i){var a=r(i,"string");return t(a)=="symbol"?a:a+""}e.exports=n,e.exports.__esModule=!0,e.exports.default=e.exports})(tE);var nE=tE.exports;(function(e){var t=nE;function r(n,i,a){return(i=t(i))in n?Object.defineProperty(n,i,{value:a,enumerable:!0,configurable:!0,writable:!0}):n[i]=a,n}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports})(eE);var gs=eE.exports,iE={exports:{}};(function(e){var t=nE;function r(i,a){for(var s=0;s<a.length;s++){var o=a[s];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(i,t(o.key),o)}}function n(i,a,s){return a&&r(i.prototype,a),s&&r(i,s),Object.defineProperty(i,"prototype",{writable:!1}),i}e.exports=n,e.exports.__esModule=!0,e.exports.default=e.exports})(iE);var Aa=iE.exports,aE={exports:{}};(function(e){function t(r,n){if(!(r instanceof n))throw new TypeError("Cannot call a class as a function")}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports})(aE);var $i=aE.exports,M2=Ct,x2=vn.map,N2=Mu,L2=N2("map");M2({target:"Array",proto:!0,forced:!L2},{map:function(t){return x2(this,t,arguments.length>1?arguments[1]:void 0)}});var D2=dm,j2=Zi,F2=D2?{}.toString:function(){return"[object "+j2(this)+"]"},U2=dm,B2=an,q2=F2;U2||B2(Object.prototype,"toString",q2,{unsafe:!0});var sE={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},z2=af,xd=z2("span").classList,Cb=xd&&xd.constructor&&xd.constructor.prototype,oE=Cb===Object.prototype?void 0:Cb,W2=yt,vf=function(e,t){var r=[][e];return!!r&&W2(function(){r.call(null,t||function(){return 1},1)})},G2=vn.forEach,H2=vf,V2=H2("forEach"),K2=V2?[].forEach:function(t){return G2(this,t,arguments.length>1?arguments[1]:void 0)},Eb=$t,kb=sE,J2=oE,Nd=K2,Y2=Xi,uE=function(e){if(e&&e.forEach!==Nd)try{Y2(e,"forEach",Nd)}catch{e.forEach=Nd}};for(var Ld in kb)kb[Ld]&&uE(Eb[Ld]&&Eb[Ld].prototype);uE(J2);var Lo=$t,X2=Ia,Q2=wi,pc=function(e){return X2.slice(0,e.length)===e},cE=function(){return pc("Bun/")?"BUN":pc("Cloudflare-Workers")?"CLOUDFLARE":pc("Deno/")?"DENO":pc("Node.js/")?"NODE":Lo.Bun&&typeof Bun.version=="string"?"BUN":Lo.Deno&&typeof Deno.version=="object"?"DENO":Q2(Lo.process)==="process"?"NODE":Lo.window&&Lo.document?"BROWSER":"REST"}(),Z2=cE,km=Z2==="NODE",ej=wt,tj=Bn,rj=function(e,t,r){try{return ej(tj(Object.getOwnPropertyDescriptor(e,t)[r]))}catch{}},nj=ar,ij=function(e){return nj(e)||e===null},aj=ij,sj=String,oj=TypeError,uj=function(e){if(aj(e))return e;throw new oj("Can't set "+sj(e)+" as a prototype")},cj=rj,lj=ar,fj=si,dj=uj,go=Object.setPrototypeOf||("__proto__"in{}?function(){var e=!1,t={},r;try{r=cj(Object.prototype,"__proto__","set"),r(t,[]),e=t instanceof Array}catch{}return function(i,a){return fj(i),dj(a),lj(i)&&(e?r(i,a):i.__proto__=a),i}}():void 0),pj=Un,hj=Ei,vj=Qt,mj=er,Rb=vj("species"),mf=function(e){var t=pj(e);mj&&t&&!t[Rb]&&hj(t,Rb,{configurable:!0,get:function(){return this}})},gj=Yi,yj=TypeError,Pa=function(e,t){if(gj(t,e))return e;throw new yj("Incorrect invocation")},$b=wr,bj=hm,_j=ai,wj=Qt,Sj=wj("species"),lE=function(e,t){var r=$b(e).constructor,n;return r===void 0||_j(n=$b(r)[Sj])?t:bj(n)},Tj=TypeError,Rm=function(e,t){if(e<t)throw new Tj("Not enough arguments");return e},Cj=Ia,fE=/(?:ipad|iphone|ipod).*applewebkit/i.test(Cj),Sn=$t,Ej=vs,kj=ea,Ib=Xt,Rj=vr,dE=yt,Ob=pC,$j=Ci,Ab=af,Ij=Rm,Oj=fE,Aj=km,Ah=Sn.setImmediate,Pb=Sn.clearImmediate,Pj=Sn.process,Dd=Sn.Dispatch,Mj=Sn.Function,Mb=Sn.MessageChannel,xj=Sn.String,jd=0,nu={},xb="onreadystatechange",pu,Wa,Fd,Ud;dE(function(){pu=Sn.location});var $m=function(e){if(Rj(nu,e)){var t=nu[e];delete nu[e],t()}},Bd=function(e){return function(){$m(e)}},Nb=function(e){$m(e.data)},Lb=function(e){Sn.postMessage(xj(e),pu.protocol+"//"+pu.host)};(!Ah||!Pb)&&(Ah=function(t){Ij(arguments.length,1);var r=Ib(t)?t:Mj(t),n=$j(arguments,1);return nu[++jd]=function(){Ej(r,void 0,n)},Wa(jd),jd},Pb=function(t){delete nu[t]},Aj?Wa=function(e){Pj.nextTick(Bd(e))}:Dd&&Dd.now?Wa=function(e){Dd.now(Bd(e))}:Mb&&!Oj?(Fd=new Mb,Ud=Fd.port2,Fd.port1.onmessage=Nb,Wa=kj(Ud.postMessage,Ud)):Sn.addEventListener&&Ib(Sn.postMessage)&&!Sn.importScripts&&pu&&pu.protocol!=="file:"&&!dE(Lb)?(Wa=Lb,Sn.addEventListener("message",Nb,!1)):xb in Ab("script")?Wa=function(e){Ob.appendChild(Ab("script"))[xb]=function(){Ob.removeChild(this),$m(e)}}:Wa=function(e){setTimeout(Bd(e),0)});var pE={set:Ah},Db=$t,Nj=er,Lj=Object.getOwnPropertyDescriptor,hE=function(e){if(!Nj)return Db[e];var t=Lj(Db,e);return t&&t.value},vE=function(){this.head=null,this.tail=null};vE.prototype={add:function(e){var t={item:e,next:null},r=this.tail;r?r.next=t:this.head=t,this.tail=t},get:function(){var e=this.head;if(e){var t=this.head=e.next;return t===null&&(this.tail=null),e.item}}};var mE=vE,Dj=Ia,jj=/ipad|iphone|ipod/i.test(Dj)&&typeof Pebble<"u",Fj=Ia,Uj=/web0s(?!.*chrome)/i.test(Fj),ao=$t,Bj=hE,jb=ea,qd=pE.set,qj=mE,zj=fE,Wj=jj,Gj=Uj,zd=km,Fb=ao.MutationObserver||ao.WebKitMutationObserver,Ub=ao.document,Bb=ao.process,hc=ao.Promise,Ph=Bj("queueMicrotask"),Rs,Wd,Gd,vc,qb;if(!Ph){var mc=new qj,gc=function(){var e,t;for(zd&&(e=Bb.domain)&&e.exit();t=mc.get();)try{t()}catch(r){throw mc.head&&Rs(),r}e&&e.enter()};!zj&&!zd&&!Gj&&Fb&&Ub?(Wd=!0,Gd=Ub.createTextNode(""),new Fb(gc).observe(Gd,{characterData:!0}),Rs=function(){Gd.data=Wd=!Wd}):!Wj&&hc&&hc.resolve?(vc=hc.resolve(void 0),vc.constructor=hc,qb=jb(vc.then,vc),Rs=function(){qb(gc)}):zd?Rs=function(){Bb.nextTick(gc)}:(qd=jb(qd,ao),Rs=function(){qd(gc)}),Ph=function(e){mc.head||Rs(),mc.add(e)}}var Hj=Ph,Vj=function(e,t){try{arguments.length===1?console.error(e):console.error(e,t)}catch{}},Im=function(e){try{return{error:!1,value:e()}}catch(t){return{error:!0,value:t}}},Kj=$t,gf=Kj.Promise,Jj=$t,iu=gf,Yj=Xt,Xj=uf,Qj=um,Zj=Qt,zb=cE,Hd=po;iu&&iu.prototype;var eF=Zj("species"),Mh=!1,gE=Yj(Jj.PromiseRejectionEvent),tF=Xj("Promise",function(){var e=Qj(iu),t=e!==String(iu);if(!t&&Hd===66)return!0;if(!Hd||Hd<51||!/native code/.test(e)){var r=new iu(function(a){a(1)}),n=function(a){a(function(){},function(){})},i=r.constructor={};if(i[eF]=n,Mh=r.then(function(){})instanceof n,!Mh)return!0}return!t&&(zb==="BROWSER"||zb==="DENO")&&!gE}),Lu={CONSTRUCTOR:tF,REJECTION_EVENT:gE,SUBCLASSING:Mh},yo={},Wb=Bn,rF=TypeError,nF=function(e){var t,r;this.promise=new e(function(n,i){if(t!==void 0||r!==void 0)throw new rF("Bad Promise constructor");t=n,r=i}),this.resolve=Wb(t),this.reject=Wb(r)};yo.f=function(e){return new nF(e)};var iF=Ct,jl=km,Ea=$t,so=Yt,Gb=an,Hb=go,aF=Ti,sF=mf,oF=Bn,gl=Xt,uF=ar,cF=Pa,lF=lE,yE=pE.set,Om=Hj,fF=Vj,dF=Im,pF=mE,bE=En,Fl=gf,Am=Lu,_E=yo,yf="Promise",wE=Am.CONSTRUCTOR,hF=Am.REJECTION_EVENT,vF=Am.SUBCLASSING,Vd=bE.getterFor(yf),mF=bE.set,Ls=Fl&&Fl.prototype,es=Fl,yc=Ls,SE=Ea.TypeError,xh=Ea.document,Pm=Ea.process,Nh=_E.f,gF=Nh,yF=!!(xh&&xh.createEvent&&Ea.dispatchEvent),TE="unhandledrejection",bF="rejectionhandled",Vb=0,CE=1,_F=2,Mm=1,EE=2,bc,Kb,wF,Jb,kE=function(e){var t;return uF(e)&&gl(t=e.then)?t:!1},RE=function(e,t){var r=t.value,n=t.state===CE,i=n?e.ok:e.fail,a=e.resolve,s=e.reject,o=e.domain,u,c,l;try{i?(n||(t.rejection===EE&&TF(t),t.rejection=Mm),i===!0?u=r:(o&&o.enter(),u=i(r),o&&(o.exit(),l=!0)),u===e.promise?s(new SE("Promise-chain cycle")):(c=kE(u))?so(c,u,a,s):a(u)):s(r)}catch(p){o&&!l&&o.exit(),s(p)}},$E=function(e,t){e.notified||(e.notified=!0,Om(function(){for(var r=e.reactions,n;n=r.get();)RE(n,e);e.notified=!1,t&&!e.rejection&&SF(e)}))},IE=function(e,t,r){var n,i;yF?(n=xh.createEvent("Event"),n.promise=t,n.reason=r,n.initEvent(e,!1,!0),Ea.dispatchEvent(n)):n={promise:t,reason:r},!hF&&(i=Ea["on"+e])?i(n):e===TE&&fF("Unhandled promise rejection",r)},SF=function(e){so(yE,Ea,function(){var t=e.facade,r=e.value,n=Yb(e),i;if(n&&(i=dF(function(){jl?Pm.emit("unhandledRejection",r,t):IE(TE,t,r)}),e.rejection=jl||Yb(e)?EE:Mm,i.error))throw i.value})},Yb=function(e){return e.rejection!==Mm&&!e.parent},TF=function(e){so(yE,Ea,function(){var t=e.facade;jl?Pm.emit("rejectionHandled",t):IE(bF,t,e.value)})},Us=function(e,t,r){return function(n){e(t,n,r)}},Ws=function(e,t,r){e.done||(e.done=!0,r&&(e=r),e.value=t,e.state=_F,$E(e,!0))},Lh=function(e,t,r){if(!e.done){e.done=!0,r&&(e=r);try{if(e.facade===t)throw new SE("Promise can't be resolved itself");var n=kE(t);n?Om(function(){var i={done:!1};try{so(n,t,Us(Lh,i,e),Us(Ws,i,e))}catch(a){Ws(i,a,e)}}):(e.value=t,e.state=CE,$E(e,!1))}catch(i){Ws({done:!1},i,e)}}};if(wE&&(es=function(t){cF(this,yc),oF(t),so(bc,this);var r=Vd(this);try{t(Us(Lh,r),Us(Ws,r))}catch(n){Ws(r,n)}},yc=es.prototype,bc=function(t){mF(this,{type:yf,done:!1,notified:!1,parent:!1,reactions:new pF,rejection:!1,state:Vb,value:null})},bc.prototype=Gb(yc,"then",function(t,r){var n=Vd(this),i=Nh(lF(this,es));return n.parent=!0,i.ok=gl(t)?t:!0,i.fail=gl(r)&&r,i.domain=jl?Pm.domain:void 0,n.state===Vb?n.reactions.add(i):Om(function(){RE(i,n)}),i.promise}),Kb=function(){var e=new bc,t=Vd(e);this.promise=e,this.resolve=Us(Lh,t),this.reject=Us(Ws,t)},_E.f=Nh=function(e){return e===es||e===wF?new Kb(e):gF(e)},gl(Fl)&&Ls!==Object.prototype)){Jb=Ls.then,vF||Gb(Ls,"then",function(t,r){var n=this;return new es(function(i,a){so(Jb,n,i,a)}).then(t,r)},{unsafe:!0});try{delete Ls.constructor}catch{}Hb&&Hb(Ls,yc)}iF({global:!0,constructor:!0,wrap:!0,forced:wE},{Promise:es});aF(es,yf,!1);sF(yf);var Du={},CF=Qt,EF=Du,kF=CF("iterator"),RF=Array.prototype,xm=function(e){return e!==void 0&&(EF.Array===e||RF[kF]===e)},$F=Zi,Xb=ds,IF=ai,OF=Du,AF=Qt,PF=AF("iterator"),ju=function(e){if(!IF(e))return Xb(e,PF)||Xb(e,"@@iterator")||OF[$F(e)]},MF=Yt,xF=Bn,NF=wr,LF=fs,DF=ju,jF=TypeError,bf=function(e,t){var r=arguments.length<2?DF(e):t;if(xF(r))return NF(MF(r,e));throw new jF(LF(e)+" is not iterable")},FF=Yt,Qb=wr,UF=ds,OE=function(e,t,r){var n,i;Qb(e);try{if(n=UF(e,"return"),!n){if(t==="throw")throw r;return r}n=FF(n,e)}catch(a){i=!0,n=a}if(t==="throw")throw r;if(i)throw n;return Qb(n),r},BF=ea,qF=Yt,zF=wr,WF=fs,GF=xm,HF=Yr,Zb=Yi,VF=bf,KF=ju,e_=OE,JF=TypeError,yl=function(e,t){this.stopped=e,this.result=t},t_=yl.prototype,Fu=function(e,t,r){var n=r&&r.that,i=!!(r&&r.AS_ENTRIES),a=!!(r&&r.IS_RECORD),s=!!(r&&r.IS_ITERATOR),o=!!(r&&r.INTERRUPTED),u=BF(t,n),c,l,p,v,m,b,T,I=function(x){return c&&e_(c,"normal",x),new yl(!0,x)},R=function(x){return i?(zF(x),o?u(x[0],x[1],I):u(x[0],x[1])):o?u(x,I):u(x)};if(a)c=e.iterator;else if(s)c=e;else{if(l=KF(e),!l)throw new JF(WF(e)+" is not iterable");if(GF(l)){for(p=0,v=HF(e);v>p;p++)if(m=R(e[p]),m&&Zb(t_,m))return m;return new yl(!1)}c=VF(e,l)}for(b=a?e.next:c.next;!(T=qF(b,c)).done;){try{m=R(T.value)}catch(x){e_(c,"throw",x)}if(typeof m=="object"&&m&&Zb(t_,m))return m}return new yl(!1)},YF=Qt,AE=YF("iterator"),PE=!1;try{var XF=0,r_={next:function(){return{done:!!XF++}},return:function(){PE=!0}};r_[AE]=function(){return this},Array.from(r_,function(){throw 2})}catch{}var _f=function(e,t){try{if(!t&&!PE)return!1}catch{return!1}var r=!1;try{var n={};n[AE]=function(){return{next:function(){return{done:r=!0}}}},e(n)}catch{}return r},QF=gf,ZF=_f,eU=Lu.CONSTRUCTOR,ME=eU||!ZF(function(e){QF.all(e).then(void 0,function(){})}),tU=Ct,rU=Yt,nU=Bn,iU=yo,aU=Im,sU=Fu,oU=ME;tU({target:"Promise",stat:!0,forced:oU},{all:function(t){var r=this,n=iU.f(r),i=n.resolve,a=n.reject,s=aU(function(){var o=nU(r.resolve),u=[],c=0,l=1;sU(t,function(p){var v=c++,m=!1;l++,rU(o,r,p).then(function(b){m||(m=!0,u[v]=b,--l||i(u))},a)}),--l||i(u)});return s.error&&a(s.value),n.promise}});var uU=Ct,cU=Lu.CONSTRUCTOR,Dh=gf,lU=Un,fU=Xt,dU=an,n_=Dh&&Dh.prototype;uU({target:"Promise",proto:!0,forced:cU,real:!0},{catch:function(e){return this.then(void 0,e)}});if(fU(Dh)){var i_=lU("Promise").prototype.catch;n_.catch!==i_&&dU(n_,"catch",i_,{unsafe:!0})}var pU=Ct,hU=Yt,vU=Bn,mU=yo,gU=Im,yU=Fu,bU=ME;pU({target:"Promise",stat:!0,forced:bU},{race:function(t){var r=this,n=mU.f(r),i=n.reject,a=gU(function(){var s=vU(r.resolve);yU(t,function(o){hU(s,r,o).then(n.resolve,i)})});return a.error&&i(a.value),n.promise}});var _U=Ct,wU=yo,SU=Lu.CONSTRUCTOR;_U({target:"Promise",stat:!0,forced:SU},{reject:function(t){var r=wU.f(this),n=r.reject;return n(t),r.promise}});var TU=wr,CU=ar,EU=yo,kU=function(e,t){if(TU(e),CU(t)&&t.constructor===e)return t;var r=EU.f(e),n=r.resolve;return n(t),r.promise},RU=Ct,$U=Un,IU=Lu.CONSTRUCTOR,OU=kU;$U("Promise");RU({target:"Promise",stat:!0,forced:IU},{resolve:function(t){return OU(this,t)}});var xE={exports:{}};(function(e){var t=qn.default;function r(){e.exports=r=function(){return i},e.exports.__esModule=!0,e.exports.default=e.exports;var n,i={},a=Object.prototype,s=a.hasOwnProperty,o=Object.defineProperty||function(ce,he,P){ce[he]=P.value},u=typeof Symbol=="function"?Symbol:{},c=u.iterator||"@@iterator",l=u.asyncIterator||"@@asyncIterator",p=u.toStringTag||"@@toStringTag";function v(ce,he,P){return Object.defineProperty(ce,he,{value:P,enumerable:!0,configurable:!0,writable:!0}),ce[he]}try{v({},"")}catch{v=function(P,Ie,qe){return P[Ie]=qe}}function m(ce,he,P,Ie){var qe=he&&he.prototype instanceof j?he:j,Ne=Object.create(qe.prototype),_e=new Ke(Ie||[]);return o(Ne,"_invoke",{value:L(ce,P,_e)}),Ne}function b(ce,he,P){try{return{type:"normal",arg:ce.call(he,P)}}catch(Ie){return{type:"throw",arg:Ie}}}i.wrap=m;var T="suspendedStart",I="suspendedYield",R="executing",x="completed",N={};function j(){}function X(){}function J(){}var V={};v(V,c,function(){return this});var D=Object.getPrototypeOf,te=D&&D(D(Se([])));te&&te!==a&&s.call(te,c)&&(V=te);var ue=J.prototype=j.prototype=Object.create(V);function ee(ce){["next","throw","return"].forEach(function(he){v(ce,he,function(P){return this._invoke(he,P)})})}function ge(ce,he){function P(qe,Ne,_e,Q){var kt=b(ce[qe],ce,Ne);if(kt.type!=="throw"){var Ce=kt.arg,de=Ce.value;return de&&t(de)=="object"&&s.call(de,"__await")?he.resolve(de.__await).then(function(Rt){P("next",Rt,_e,Q)},function(Rt){P("throw",Rt,_e,Q)}):he.resolve(de).then(function(Rt){Ce.value=Rt,_e(Ce)},function(Rt){return P("throw",Rt,_e,Q)})}Q(kt.arg)}var Ie;o(this,"_invoke",{value:function(Ne,_e){function Q(){return new he(function(kt,Ce){P(Ne,_e,kt,Ce)})}return Ie=Ie?Ie.then(Q,Q):Q()}})}function L(ce,he,P){var Ie=T;return function(qe,Ne){if(Ie===R)throw Error("Generator is already running");if(Ie===x){if(qe==="throw")throw Ne;return{value:n,done:!0}}for(P.method=qe,P.arg=Ne;;){var _e=P.delegate;if(_e){var Q=pe(_e,P);if(Q){if(Q===N)continue;return Q}}if(P.method==="next")P.sent=P._sent=P.arg;else if(P.method==="throw"){if(Ie===T)throw Ie=x,P.arg;P.dispatchException(P.arg)}else P.method==="return"&&P.abrupt("return",P.arg);Ie=R;var kt=b(ce,he,P);if(kt.type==="normal"){if(Ie=P.done?x:I,kt.arg===N)continue;return{value:kt.arg,done:P.done}}kt.type==="throw"&&(Ie=x,P.method="throw",P.arg=kt.arg)}}}function pe(ce,he){var P=he.method,Ie=ce.iterator[P];if(Ie===n)return he.delegate=null,P==="throw"&&ce.iterator.return&&(he.method="return",he.arg=n,pe(ce,he),he.method==="throw")||P!=="return"&&(he.method="throw",he.arg=new TypeError("The iterator does not provide a '"+P+"' method")),N;var qe=b(Ie,ce.iterator,he.arg);if(qe.type==="throw")return he.method="throw",he.arg=qe.arg,he.delegate=null,N;var Ne=qe.arg;return Ne?Ne.done?(he[ce.resultName]=Ne.value,he.next=ce.nextLoc,he.method!=="return"&&(he.method="next",he.arg=n),he.delegate=null,N):Ne:(he.method="throw",he.arg=new TypeError("iterator result is not an object"),he.delegate=null,N)}function Te(ce){var he={tryLoc:ce[0]};1 in ce&&(he.catchLoc=ce[1]),2 in ce&&(he.finallyLoc=ce[2],he.afterLoc=ce[3]),this.tryEntries.push(he)}function rt(ce){var he=ce.completion||{};he.type="normal",delete he.arg,ce.completion=he}function Ke(ce){this.tryEntries=[{tryLoc:"root"}],ce.forEach(Te,this),this.reset(!0)}function Se(ce){if(ce||ce===""){var he=ce[c];if(he)return he.call(ce);if(typeof ce.next=="function")return ce;if(!isNaN(ce.length)){var P=-1,Ie=function qe(){for(;++P<ce.length;)if(s.call(ce,P))return qe.value=ce[P],qe.done=!1,qe;return qe.value=n,qe.done=!0,qe};return Ie.next=Ie}}throw new TypeError(t(ce)+" is not iterable")}return X.prototype=J,o(ue,"constructor",{value:J,configurable:!0}),o(J,"constructor",{value:X,configurable:!0}),X.displayName=v(J,p,"GeneratorFunction"),i.isGeneratorFunction=function(ce){var he=typeof ce=="function"&&ce.constructor;return!!he&&(he===X||(he.displayName||he.name)==="GeneratorFunction")},i.mark=function(ce){return Object.setPrototypeOf?Object.setPrototypeOf(ce,J):(ce.__proto__=J,v(ce,p,"GeneratorFunction")),ce.prototype=Object.create(ue),ce},i.awrap=function(ce){return{__await:ce}},ee(ge.prototype),v(ge.prototype,l,function(){return this}),i.AsyncIterator=ge,i.async=function(ce,he,P,Ie,qe){qe===void 0&&(qe=Promise);var Ne=new ge(m(ce,he,P,Ie),qe);return i.isGeneratorFunction(he)?Ne:Ne.next().then(function(_e){return _e.done?_e.value:Ne.next()})},ee(ue),v(ue,p,"Generator"),v(ue,c,function(){return this}),v(ue,"toString",function(){return"[object Generator]"}),i.keys=function(ce){var he=Object(ce),P=[];for(var Ie in he)P.push(Ie);return P.reverse(),function qe(){for(;P.length;){var Ne=P.pop();if(Ne in he)return qe.value=Ne,qe.done=!1,qe}return qe.done=!0,qe}},i.values=Se,Ke.prototype={constructor:Ke,reset:function(he){if(this.prev=0,this.next=0,this.sent=this._sent=n,this.done=!1,this.delegate=null,this.method="next",this.arg=n,this.tryEntries.forEach(rt),!he)for(var P in this)P.charAt(0)==="t"&&s.call(this,P)&&!isNaN(+P.slice(1))&&(this[P]=n)},stop:function(){this.done=!0;var he=this.tryEntries[0].completion;if(he.type==="throw")throw he.arg;return this.rval},dispatchException:function(he){if(this.done)throw he;var P=this;function Ie(Ce,de){return _e.type="throw",_e.arg=he,P.next=Ce,de&&(P.method="next",P.arg=n),!!de}for(var qe=this.tryEntries.length-1;qe>=0;--qe){var Ne=this.tryEntries[qe],_e=Ne.completion;if(Ne.tryLoc==="root")return Ie("end");if(Ne.tryLoc<=this.prev){var Q=s.call(Ne,"catchLoc"),kt=s.call(Ne,"finallyLoc");if(Q&&kt){if(this.prev<Ne.catchLoc)return Ie(Ne.catchLoc,!0);if(this.prev<Ne.finallyLoc)return Ie(Ne.finallyLoc)}else if(Q){if(this.prev<Ne.catchLoc)return Ie(Ne.catchLoc,!0)}else{if(!kt)throw Error("try statement without catch or finally");if(this.prev<Ne.finallyLoc)return Ie(Ne.finallyLoc)}}}},abrupt:function(he,P){for(var Ie=this.tryEntries.length-1;Ie>=0;--Ie){var qe=this.tryEntries[Ie];if(qe.tryLoc<=this.prev&&s.call(qe,"finallyLoc")&&this.prev<qe.finallyLoc){var Ne=qe;break}}Ne&&(he==="break"||he==="continue")&&Ne.tryLoc<=P&&P<=Ne.finallyLoc&&(Ne=null);var _e=Ne?Ne.completion:{};return _e.type=he,_e.arg=P,Ne?(this.method="next",this.next=Ne.finallyLoc,N):this.complete(_e)},complete:function(he,P){if(he.type==="throw")throw he.arg;return he.type==="break"||he.type==="continue"?this.next=he.arg:he.type==="return"?(this.rval=this.arg=he.arg,this.method="return",this.next="end"):he.type==="normal"&&P&&(this.next=P),N},finish:function(he){for(var P=this.tryEntries.length-1;P>=0;--P){var Ie=this.tryEntries[P];if(Ie.finallyLoc===he)return this.complete(Ie.completion,Ie.afterLoc),rt(Ie),N}},catch:function(he){for(var P=this.tryEntries.length-1;P>=0;--P){var Ie=this.tryEntries[P];if(Ie.tryLoc===he){var qe=Ie.completion;if(qe.type==="throw"){var Ne=qe.arg;rt(Ie)}return Ne}}throw Error("illegal catch attempt")},delegateYield:function(he,P,Ie){return this.delegate={iterator:Se(he),resultName:P,nextLoc:Ie},this.method==="next"&&(this.arg=n),N}},i}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports})(xE);var AU=xE.exports,bl=AU(),Uu=bl;try{regeneratorRuntime=bl}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=bl:Function("r","regeneratorRuntime = r")(bl)}var PU=TypeError,MU=9007199254740991,NE=function(e){if(e>MU)throw PU("Maximum allowed index exceeded");return e},xU=Ct,NU=yt,LU=Iu,DU=ar,jU=Jr,FU=Yr,a_=NE,s_=xu,UU=_m,BU=Mu,qU=Qt,zU=po,LE=qU("isConcatSpreadable"),WU=zU>=51||!NU(function(){var e=[];return e[LE]=!1,e.concat()[0]!==e}),GU=function(e){if(!DU(e))return!1;var t=e[LE];return t!==void 0?!!t:LU(e)},HU=!WU||!BU("concat");xU({target:"Array",proto:!0,arity:1,forced:HU},{concat:function(t){var r=jU(this),n=UU(r,0),i=0,a,s,o,u,c;for(a=-1,o=arguments.length;a<o;a++)if(c=a===-1?r:arguments[a],GU(c))for(u=FU(c),a_(i+u),s=0;s<u;s++,i++)s in c&&s_(n,i,c[s]);else a_(i+1),s_(n,i++,c);return n.length=i,n}});var VU=wr,KU=OE,JU=function(e,t,r,n){try{return n?t(VU(r)[0],r[1]):t(r)}catch(i){KU(e,"throw",i)}},YU=ea,XU=Yt,QU=Jr,ZU=JU,eB=xm,tB=cf,rB=Yr,o_=xu,nB=bf,iB=ju,u_=Array,DE=function(t){var r=QU(t),n=tB(this),i=arguments.length,a=i>1?arguments[1]:void 0,s=a!==void 0;s&&(a=YU(a,i>2?arguments[2]:void 0));var o=iB(r),u=0,c,l,p,v,m,b;if(o&&!(this===u_&&eB(o)))for(l=n?new this:[],v=nB(r,o),m=v.next;!(p=XU(m,v)).done;u++)b=s?ZU(v,a,[p.value,u],!0):p.value,o_(l,u,b);else for(c=rB(r),l=n?new this(c):u_(c);c>u;u++)b=s?a(r[u],u):r[u],o_(l,u,b);return l.length=u,l},aB=Ct,sB=DE,oB=_f,uB=!oB(function(e){Array.from(e)});aB({target:"Array",stat:!0,forced:uB},{from:sB});var Nm=wt,cB=Si,lB=Lr,fB=si,dB=Nm("".charAt),c_=Nm("".charCodeAt),pB=Nm("".slice),l_=function(e){return function(t,r){var n=lB(fB(t)),i=cB(r),a=n.length,s,o;return i<0||i>=a?e?"":void 0:(s=c_(n,i),s<55296||s>56319||i+1===a||(o=c_(n,i+1))<56320||o>57343?e?dB(n,i):s:e?pB(n,i,i+2):(s-55296<<10)+(o-56320)+65536)}},Lm={codeAt:l_(!1),charAt:l_(!0)},hB=yt,vB=!hB(function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype}),mB=vr,gB=Xt,yB=Jr,bB=sf,_B=vB,f_=bB("IE_PROTO"),jh=Object,wB=jh.prototype,Bu=_B?jh.getPrototypeOf:function(e){var t=yB(e);if(mB(t,f_))return t[f_];var r=t.constructor;return gB(r)&&t instanceof r?r.prototype:t instanceof jh?wB:null},SB=yt,TB=Xt,CB=ar,d_=Bu,EB=an,kB=Qt,Fh=kB("iterator"),jE=!1,ss,Kd,Jd;[].keys&&(Jd=[].keys(),"next"in Jd?(Kd=d_(d_(Jd)),Kd!==Object.prototype&&(ss=Kd)):jE=!0);var RB=!CB(ss)||SB(function(){var e={};return ss[Fh].call(e)!==e});RB&&(ss={});TB(ss[Fh])||EB(ss,Fh,function(){return this});var FE={IteratorPrototype:ss,BUGGY_SAFARI_ITERATORS:jE},$B=FE.IteratorPrototype,IB=Oa,OB=ls,AB=Ti,PB=Du,MB=function(){return this},UE=function(e,t,r,n){var i=t+" Iterator";return e.prototype=IB($B,{next:OB(+!n,r)}),AB(e,i,!1),PB[i]=MB,e},xB=Ct,NB=Yt,BE=Cu,LB=Xt,DB=UE,p_=Bu,h_=go,jB=Ti,FB=Xi,Yd=an,UB=Qt,BB=Du,qE=FE,qB=BE.PROPER,zB=BE.CONFIGURABLE,v_=qE.IteratorPrototype,_c=qE.BUGGY_SAFARI_ITERATORS,Do=UB("iterator"),m_="keys",jo="values",g_="entries",WB=function(){return this},Dm=function(e,t,r,n,i,a,s){DB(r,t,n);var o=function(R){if(R===i&&v)return v;if(!_c&&R&&R in l)return l[R];switch(R){case m_:return function(){return new r(this,R)};case jo:return function(){return new r(this,R)};case g_:return function(){return new r(this,R)}}return function(){return new r(this)}},u=t+" Iterator",c=!1,l=e.prototype,p=l[Do]||l["@@iterator"]||i&&l[i],v=!_c&&p||o(i),m=t==="Array"&&l.entries||p,b,T,I;if(m&&(b=p_(m.call(new e)),b!==Object.prototype&&b.next&&(p_(b)!==v_&&(h_?h_(b,v_):LB(b[Do])||Yd(b,Do,WB)),jB(b,u,!0))),qB&&i===jo&&p&&p.name!==jo&&(zB?FB(l,"name",jo):(c=!0,v=function(){return NB(p,this)})),i)if(T={values:o(jo),keys:a?v:o(m_),entries:o(g_)},s)for(I in T)(_c||c||!(I in l))&&Yd(l,I,T[I]);else xB({target:t,proto:!0,forced:_c||c},T);return l[Do]!==v&&Yd(l,Do,v,{name:i}),BB[t]=v,T},wf=function(e,t){return{value:e,done:t}},GB=Lm.charAt,HB=Lr,zE=En,VB=Dm,y_=wf,WE="String Iterator",KB=zE.set,JB=zE.getterFor(WE);VB(String,"String",function(e){KB(this,{type:WE,string:HB(e),index:0})},function(){var t=JB(this),r=t.string,n=t.index,i;return n>=r.length?y_(void 0,!0):(i=GB(r,n),t.index+=i.length,y_(i,!1))});var GE={exports:{}};(function(e){(function(t,r){e.exports?e.exports=r():t.log=r()})(je,function(){var t=function(){},r="undefined",n=typeof window!==r&&typeof window.navigator!==r&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"],a={},s=null;function o(T,I){var R=T[I];if(typeof R.bind=="function")return R.bind(T);try{return Function.prototype.bind.call(R,T)}catch{return function(){return Function.prototype.apply.apply(R,[T,arguments])}}}function u(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(T){return T==="debug"&&(T="log"),typeof console===r?!1:T==="trace"&&n?u:console[T]!==void 0?o(console,T):console.log!==void 0?o(console,"log"):t}function l(){for(var T=this.getLevel(),I=0;I<i.length;I++){var R=i[I];this[R]=I<T?t:this.methodFactory(R,T,this.name)}if(this.log=this.debug,typeof console===r&&T<this.levels.SILENT)return"No console available for logging"}function p(T){return function(){typeof console!==r&&(l.call(this),this[T].apply(this,arguments))}}function v(T,I,R){return c(T)||p.apply(this,arguments)}function m(T,I){var R=this,x,N,j,X="loglevel";typeof T=="string"?X+=":"+T:typeof T=="symbol"&&(X=void 0);function J(ee){var ge=(i[ee]||"silent").toUpperCase();if(!(typeof window===r||!X)){try{window.localStorage[X]=ge;return}catch{}try{window.document.cookie=encodeURIComponent(X)+"="+ge+";"}catch{}}}function V(){var ee;if(!(typeof window===r||!X)){try{ee=window.localStorage[X]}catch{}if(typeof ee===r)try{var ge=window.document.cookie,L=encodeURIComponent(X),pe=ge.indexOf(L+"=");pe!==-1&&(ee=/^([^;]+)/.exec(ge.slice(pe+L.length+1))[1])}catch{}return R.levels[ee]===void 0&&(ee=void 0),ee}}function D(){if(!(typeof window===r||!X)){try{window.localStorage.removeItem(X)}catch{}try{window.document.cookie=encodeURIComponent(X)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function te(ee){var ge=ee;if(typeof ge=="string"&&R.levels[ge.toUpperCase()]!==void 0&&(ge=R.levels[ge.toUpperCase()]),typeof ge=="number"&&ge>=0&&ge<=R.levels.SILENT)return ge;throw new TypeError("log.setLevel() called with invalid level: "+ee)}R.name=T,R.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},R.methodFactory=I||v,R.getLevel=function(){return j??N??x},R.setLevel=function(ee,ge){return j=te(ee),ge!==!1&&J(j),l.call(R)},R.setDefaultLevel=function(ee){N=te(ee),V()||R.setLevel(ee,!1)},R.resetLevel=function(){j=null,D(),l.call(R)},R.enableAll=function(ee){R.setLevel(R.levels.TRACE,ee)},R.disableAll=function(ee){R.setLevel(R.levels.SILENT,ee)},R.rebuild=function(){if(s!==R&&(x=te(s.getLevel())),l.call(R),s===R)for(var ee in a)a[ee].rebuild()},x=te(s?s.getLevel():"WARN");var ue=V();ue!=null&&(j=te(ue)),l.call(R)}s=new m,s.getLogger=function(I){if(typeof I!="symbol"&&typeof I!="string"||I==="")throw new TypeError("You must supply a name when creating a logger.");var R=a[I];return R||(R=a[I]=new m(I,s.methodFactory)),R};var b=typeof window!==r?window.log:void 0;return s.noConflict=function(){return typeof window!==r&&window.log===s&&(window.log=b),s},s.getLoggers=function(){return a},s.default=s,s})})(GE);var Ar=GE.exports;const is="\\d+(?:[\\.,]\\d+)?",YB=`(${is}W)`,XB=`(${is}Y)?(${is}M)?(${is}D)?`,QB=`T(${is}H)?(${is}M)?(${is}S)?`,ZB=`P(?:${YB}|${XB}(?:${QB})?)`,e3=["weeks","years","months","days","hours","minutes","seconds"],jm=new RegExp(ZB),HE=e=>e.match(jm).slice(1).reduce((t,r,n)=>(t[e3[n]]=parseFloat(r)||0,t),{}),Fm=(e,t)=>{const r=t?t.getTime():Date.now(),n=new Date(r);return n.setFullYear(n.getFullYear()+e.years),n.setMonth(n.getMonth()+e.months),n.setDate(n.getDate()+e.days),n.setHours(n.getHours()+e.hours),n.setMinutes(n.getMinutes()+e.minutes),n.setMilliseconds(n.getMilliseconds()+e.seconds*1e3),n.setDate(n.getDate()+e.weeks*7),n},VE=(e,t)=>{const r=t?t.getTime():Date.now(),n=new Date(r);return(Fm(e,n).getTime()-n.getTime())/1e3},t3={end:Fm,toSeconds:VE,pattern:jm,parse:HE},r3=Object.freeze(Object.defineProperty({__proto__:null,default:t3,end:Fm,parse:HE,pattern:jm,toSeconds:VE},Symbol.toStringTag,{value:"Module"})),n3=FT(r3);var i3=Qt,a3=Oa,s3=nn.f,Uh=i3("unscopables"),Bh=Array.prototype;Bh[Uh]===void 0&&s3(Bh,Uh,{configurable:!0,value:a3(null)});var Um=function(e){Bh[Uh][e]=!0},o3=Cn,Bm=Um,b_=Du,KE=En,u3=nn.f,c3=Dm,wc=wf,l3=er,JE="Array Iterator",f3=KE.set,d3=KE.getterFor(JE),YE=c3(Array,"Array",function(e,t){f3(this,{type:JE,target:o3(e),index:0,kind:t})},function(){var e=d3(this),t=e.target,r=e.index++;if(!t||r>=t.length)return e.target=null,wc(void 0,!0);switch(e.kind){case"keys":return wc(r,!1);case"values":return wc(t[r],!1)}return wc([r,t[r]],!1)},"values"),__=b_.Arguments=b_.Array;Bm("keys");Bm("values");Bm("entries");if(l3&&__.name!=="values")try{u3(__,"name",{value:"values"})}catch{}var w_=$t,XE=sE,p3=oE,Xo=YE,S_=Xi,h3=Ti,v3=Qt,Xd=v3("iterator"),Qd=Xo.values,QE=function(e,t){if(e){if(e[Xd]!==Qd)try{S_(e,Xd,Qd)}catch{e[Xd]=Qd}if(h3(e,t,!0),XE[t]){for(var r in Xo)if(e[r]!==Xo[r])try{S_(e,r,Xo[r])}catch{e[r]=Xo[r]}}}};for(var Zd in XE)QE(w_[Zd]&&w_[Zd].prototype,Zd);QE(p3,"DOMTokenList");var m3=Xt,g3=ar,T_=go,Sf=function(e,t,r){var n,i;return T_&&m3(n=t.constructor)&&n!==r&&g3(i=n.prototype)&&i!==r.prototype&&T_(e,i),e},y3=wt,b3=y3(1 .valueOf),_3=`
18
18
  \v\f\r                 \u2028\u2029\uFEFF`,w3=wt,S3=si,T3=Lr,qh=_3,C_=w3("".replace),C3=RegExp("^["+qh+"]+"),E3=RegExp("(^|[^"+qh+"])["+qh+"]+$"),k3=function(e){return function(t){var r=T3(S3(t));return e&1&&(r=C_(r,C3,"")),e&2&&(r=C_(r,E3,"$1")),r}},R3={trim:k3(3)},$3=Ct,ZE=JT,I3=er,ek=$t,tk=SC,rk=wt,O3=uf,E_=vr,A3=Sf,P3=Yi,M3=vo,nk=sm,x3=yt,N3=ps.f,L3=Ji.f,D3=nn.f,j3=b3,F3=R3.trim,Tf="Number",Gs=ek[Tf];tk[Tf];var qm=Gs.prototype,U3=ek.TypeError,B3=rk("".slice),Sc=rk("".charCodeAt),q3=function(e){var t=nk(e,"number");return typeof t=="bigint"?t:z3(t)},z3=function(e){var t=nk(e,"number"),r,n,i,a,s,o,u,c;if(M3(t))throw new U3("Cannot convert a Symbol value to a number");if(typeof t=="string"&&t.length>2){if(t=F3(t),r=Sc(t,0),r===43||r===45){if(n=Sc(t,2),n===88||n===120)return NaN}else if(r===48){switch(Sc(t,1)){case 66:case 98:i=2,a=49;break;case 79:case 111:i=8,a=55;break;default:return+t}for(s=B3(t,2),o=s.length,u=0;u<o;u++)if(c=Sc(s,u),c<48||c>a)return NaN;return parseInt(s,i)}}return+t},zm=O3(Tf,!Gs(" 0o1")||!Gs("0b1")||Gs("+0x1")),W3=function(e){return P3(qm,e)&&x3(function(){j3(e)})},Cf=function(t){var r=arguments.length<1?0:Gs(q3(t));return W3(this)?A3(Object(r),this,Cf):r};Cf.prototype=qm;zm&&!ZE&&(qm.constructor=Cf);$3({global:!0,constructor:!0,wrap:!0,forced:zm},{Number:Cf});var G3=function(e,t){for(var r=I3?N3(t):"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;r.length>n;n++)E_(t,i=r[n])&&!E_(e,i)&&D3(e,i,L3(t,i))};(zm||ZE)&&G3(tk[Tf],Gs);var H3=wr,ik=function(){var e=H3(this),t="";return e.hasIndices&&(t+="d"),e.global&&(t+="g"),e.ignoreCase&&(t+="i"),e.multiline&&(t+="m"),e.dotAll&&(t+="s"),e.unicode&&(t+="u"),e.unicodeSets&&(t+="v"),e.sticky&&(t+="y"),t},Wm=yt,V3=$t,Gm=V3.RegExp,Hm=Wm(function(){var e=Gm("a","y");return e.lastIndex=2,e.exec("abcd")!==null});Hm||Wm(function(){return!Gm("a","y").sticky});var K3=Hm||Wm(function(){var e=Gm("^r","gy");return e.lastIndex=2,e.exec("str")!==null}),ak={BROKEN_CARET:K3,UNSUPPORTED_Y:Hm},J3=yt,Y3=$t,X3=Y3.RegExp,Q3=J3(function(){var e=X3(".","s");return!(e.dotAll&&e.test(`
19
19
  `)&&e.flags==="s")}),Z3=yt,e4=$t,t4=e4.RegExp,r4=Z3(function(){var e=t4("(?<a>b)","g");return e.exec("b").groups.a!=="b"||"b".replace(e,"$<a>c")!=="bc"}),Bs=Yt,Ef=wt,n4=Lr,i4=ik,a4=ak,s4=mo,o4=Oa,u4=En.get,c4=Q3,l4=r4,f4=s4("native-string-replace",String.prototype.replace),Ul=RegExp.prototype.exec,zh=Ul,d4=Ef("".charAt),p4=Ef("".indexOf),h4=Ef("".replace),ep=Ef("".slice),Wh=function(){var e=/a/,t=/b*/g;return Bs(Ul,e,"a"),Bs(Ul,t,"a"),e.lastIndex!==0||t.lastIndex!==0}(),sk=a4.BROKEN_CARET,Gh=/()??/.exec("")[1]!==void 0,v4=Wh||Gh||sk||c4||l4;v4&&(zh=function(t){var r=this,n=u4(r),i=n4(t),a=n.raw,s,o,u,c,l,p,v;if(a)return a.lastIndex=r.lastIndex,s=Bs(zh,a,i),r.lastIndex=a.lastIndex,s;var m=n.groups,b=sk&&r.sticky,T=Bs(i4,r),I=r.source,R=0,x=i;if(b&&(T=h4(T,"y",""),p4(T,"g")===-1&&(T+="g"),x=ep(i,r.lastIndex),r.lastIndex>0&&(!r.multiline||r.multiline&&d4(i,r.lastIndex-1)!==`
20
- `)&&(I="(?: "+I+")",x=" "+x,R++),o=new RegExp("^(?:"+I+")",T)),Gh&&(o=new RegExp("^"+I+"$(?!\\s)",T)),Wh&&(u=r.lastIndex),c=Bs(Ul,b?o:r,x),b?c?(c.input=ep(c.input,R),c[0]=ep(c[0],R),c.index=r.lastIndex,r.lastIndex+=c[0].length):r.lastIndex=0:Wh&&c&&(r.lastIndex=r.global?c.index+c[0].length:u),Gh&&c&&c.length>1&&Bs(f4,c[0],o,function(){for(l=1;l<arguments.length-2;l++)arguments[l]===void 0&&(c[l]=void 0)}),c&&m)for(c.groups=p=o4(null),l=0;l<m.length;l++)v=m[l],p[v[0]]=c[v[1]];return c});var Vm=zh,m4=Ct,k_=Vm;m4({target:"RegExp",proto:!0,forced:/./.exec!==k_},{exec:k_});var R_=Yt,$_=an,g4=Vm,I_=yt,ok=Qt,y4=Xi,b4=ok("species"),tp=RegExp.prototype,kf=function(e,t,r,n){var i=ok(e),a=!I_(function(){var c={};return c[i]=function(){return 7},""[e](c)!==7}),s=a&&!I_(function(){var c=!1,l=/a/;return e==="split"&&(l={},l.constructor={},l.constructor[b4]=function(){return l},l.flags="",l[i]=/./[i]),l.exec=function(){return c=!0,null},l[i](""),!c});if(!a||!s||r){var o=/./[i],u=t(i,""[e],function(c,l,p,v,m){var b=l.exec;return b===g4||b===tp.exec?a&&!m?{done:!0,value:R_(o,l,p,v)}:{done:!0,value:R_(c,p,l,v)}:{done:!1}});$_(String.prototype,e,u[0]),$_(tp,i,u[1])}n&&y4(tp[i],"sham",!0)},_4=Lm.charAt,Km=function(e,t,r){return t+(r?_4(e,t).length:1)},Jm=wt,w4=Jr,S4=Math.floor,rp=Jm("".charAt),T4=Jm("".replace),np=Jm("".slice),C4=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,E4=/\$([$&'`]|\d{1,2})/g,k4=function(e,t,r,n,i,a){var s=r+e.length,o=n.length,u=E4;return i!==void 0&&(i=w4(i),u=C4),T4(a,u,function(c,l){var p;switch(rp(l,0)){case"$":return"$";case"&":return e;case"`":return np(t,0,r);case"'":return np(t,s);case"<":p=i[np(l,1,-1)];break;default:var v=+l;if(v===0)return c;if(v>o){var m=S4(v/10);return m===0?c:m<=o?n[m-1]===void 0?rp(l,1):n[m-1]+rp(l,1):c}p=n[v-1]}return p===void 0?"":p})},O_=Yt,R4=wr,$4=Xt,I4=wi,O4=Vm,A4=TypeError,Rf=function(e,t){var r=e.exec;if($4(r)){var n=O_(r,e,t);return n!==null&&R4(n),n}if(I4(e)==="RegExp")return O_(O4,e,t);throw new A4("RegExp#exec called on incompatible receiver")},P4=vs,A_=Yt,$f=wt,M4=kf,x4=yt,N4=wr,L4=Xt,D4=ai,j4=Si,F4=Qi,$s=Lr,U4=si,B4=Km,q4=ds,z4=k4,W4=Rf,G4=Qt,Hh=G4("replace"),H4=Math.max,V4=Math.min,K4=$f([].concat),ip=$f([].push),P_=$f("".indexOf),M_=$f("".slice),J4=function(e){return e===void 0?e:String(e)},Y4=function(){return"a".replace(/./,"$0")==="$0"}(),x_=function(){return/./[Hh]?/./[Hh]("a","$0")==="":!1}(),X4=!x4(function(){var e=/./;return e.exec=function(){var t=[];return t.groups={a:"7"},t},"".replace(e,"$<a>")!=="7"});M4("replace",function(e,t,r){var n=x_?"$":"$0";return[function(a,s){var o=U4(this),u=D4(a)?void 0:q4(a,Hh);return u?A_(u,a,o,s):A_(t,$s(o),a,s)},function(i,a){var s=N4(this),o=$s(i);if(typeof a=="string"&&P_(a,n)===-1&&P_(a,"$<")===-1){var u=r(t,s,o,a);if(u.done)return u.value}var c=L4(a);c||(a=$s(a));var l=s.global,p;l&&(p=s.unicode,s.lastIndex=0);for(var v=[],m;m=W4(s,o),!(m===null||(ip(v,m),!l));){var b=$s(m[0]);b===""&&(s.lastIndex=B4(o,F4(s.lastIndex),p))}for(var T="",I=0,R=0;R<v.length;R++){m=v[R];for(var x=$s(m[0]),N=H4(V4(j4(m.index),o.length),0),j=[],X,J=1;J<m.length;J++)ip(j,J4(m[J]));var V=m.groups;if(c){var D=K4([x],j,N,o);V!==void 0&&ip(D,V),X=$s(P4(a,void 0,D))}else X=z4(x,o,N,j,V,a);N>=I&&(T+=M_(o,I,N)+X,I=N+x.length)}return T+M_(o,I)}]},!X4||!Y4||x_);var Q4=Ct,Z4=wt,eq=Su,tq=Cn,rq=vf,nq=Z4([].join),iq=eq!==Object,aq=iq||!rq("join",",");Q4({target:"Array",proto:!0,forced:aq},{join:function(t){return nq(tq(this),t===void 0?",":t)}});var zr={},sq=er,oq=Cu.EXISTS,uk=wt,uq=Ei,ck=Function.prototype,cq=uk(ck.toString),lk=/function\b(?:\s|\/\*[\S\s]*?\*\/|\/\/[^\n\r]*[\n\r]+)*([^\s(/]*)/,lq=uk(lk.exec),fq="name";sq&&!oq&&uq(ck,fq,{configurable:!0,get:function(){try{return lq(lk,cq(this))[1]}catch{return""}}});var fk={exports:{}},dk={exports:{}};(function(e){function t(r){if(Array.isArray(r))return r}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports})(dk);var dq=dk.exports,pk={exports:{}};(function(e){function t(r,n){var i=r==null?null:typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(i!=null){var a,s,o,u,c=[],l=!0,p=!1;try{if(o=(i=i.call(r)).next,n===0){if(Object(i)!==i)return;l=!1}else for(;!(l=(a=o.call(i)).done)&&(c.push(a.value),c.length!==n);l=!0);}catch(v){p=!0,s=v}finally{try{if(!l&&i.return!=null&&(u=i.return(),Object(u)!==u))return}finally{if(p)throw s}}return c}}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports})(pk);var pq=pk.exports,hk={exports:{}},vk={exports:{}};(function(e){function t(r,n){(n==null||n>r.length)&&(n=r.length);for(var i=0,a=Array(n);i<n;i++)a[i]=r[i];return a}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports})(vk);var mk=vk.exports;(function(e){var t=mk;function r(n,i){if(n){if(typeof n=="string")return t(n,i);var a={}.toString.call(n).slice(8,-1);return a==="Object"&&n.constructor&&(a=n.constructor.name),a==="Map"||a==="Set"?Array.from(n):a==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(a)?t(n,i):void 0}}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports})(hk);var gk=hk.exports,yk={exports:{}};(function(e){function t(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
20
+ `)&&(I="(?: "+I+")",x=" "+x,R++),o=new RegExp("^(?:"+I+")",T)),Gh&&(o=new RegExp("^"+I+"$(?!\\s)",T)),Wh&&(u=r.lastIndex),c=Bs(Ul,b?o:r,x),b?c?(c.input=ep(c.input,R),c[0]=ep(c[0],R),c.index=r.lastIndex,r.lastIndex+=c[0].length):r.lastIndex=0:Wh&&c&&(r.lastIndex=r.global?c.index+c[0].length:u),Gh&&c&&c.length>1&&Bs(f4,c[0],o,function(){for(l=1;l<arguments.length-2;l++)arguments[l]===void 0&&(c[l]=void 0)}),c&&m)for(c.groups=p=o4(null),l=0;l<m.length;l++)v=m[l],p[v[0]]=c[v[1]];return c});var Vm=zh,m4=Ct,k_=Vm;m4({target:"RegExp",proto:!0,forced:/./.exec!==k_},{exec:k_});var R_=Yt,$_=an,g4=Vm,I_=yt,ok=Qt,y4=Xi,b4=ok("species"),tp=RegExp.prototype,kf=function(e,t,r,n){var i=ok(e),a=!I_(function(){var c={};return c[i]=function(){return 7},""[e](c)!==7}),s=a&&!I_(function(){var c=!1,l=/a/;return e==="split"&&(l={},l.constructor={},l.constructor[b4]=function(){return l},l.flags="",l[i]=/./[i]),l.exec=function(){return c=!0,null},l[i](""),!c});if(!a||!s||r){var o=/./[i],u=t(i,""[e],function(c,l,p,v,m){var b=l.exec;return b===g4||b===tp.exec?a&&!m?{done:!0,value:R_(o,l,p,v)}:{done:!0,value:R_(c,p,l,v)}:{done:!1}});$_(String.prototype,e,u[0]),$_(tp,i,u[1])}n&&y4(tp[i],"sham",!0)},_4=Lm.charAt,Km=function(e,t,r){return t+(r?_4(e,t).length:1)},Jm=wt,w4=Jr,S4=Math.floor,rp=Jm("".charAt),T4=Jm("".replace),np=Jm("".slice),C4=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,E4=/\$([$&'`]|\d{1,2})/g,k4=function(e,t,r,n,i,a){var s=r+e.length,o=n.length,u=E4;return i!==void 0&&(i=w4(i),u=C4),T4(a,u,function(c,l){var p;switch(rp(l,0)){case"$":return"$";case"&":return e;case"`":return np(t,0,r);case"'":return np(t,s);case"<":p=i[np(l,1,-1)];break;default:var v=+l;if(v===0)return c;if(v>o){var m=S4(v/10);return m===0?c:m<=o?n[m-1]===void 0?rp(l,1):n[m-1]+rp(l,1):c}p=n[v-1]}return p===void 0?"":p})},O_=Yt,R4=wr,$4=Xt,I4=wi,O4=Vm,A4=TypeError,Rf=function(e,t){var r=e.exec;if($4(r)){var n=O_(r,e,t);return n!==null&&R4(n),n}if(I4(e)==="RegExp")return O_(O4,e,t);throw new A4("RegExp#exec called on incompatible receiver")},P4=vs,A_=Yt,$f=wt,M4=kf,x4=yt,N4=wr,L4=Xt,D4=ai,j4=Si,F4=Qi,$s=Lr,U4=si,B4=Km,q4=ds,z4=k4,W4=Rf,G4=Qt,Hh=G4("replace"),H4=Math.max,V4=Math.min,K4=$f([].concat),ip=$f([].push),P_=$f("".indexOf),M_=$f("".slice),J4=function(e){return e===void 0?e:String(e)},Y4=function(){return"a".replace(/./,"$0")==="$0"}(),x_=function(){return/./[Hh]?/./[Hh]("a","$0")==="":!1}(),X4=!x4(function(){var e=/./;return e.exec=function(){var t=[];return t.groups={a:"7"},t},"".replace(e,"$<a>")!=="7"});M4("replace",function(e,t,r){var n=x_?"$":"$0";return[function(a,s){var o=U4(this),u=D4(a)?void 0:q4(a,Hh);return u?A_(u,a,o,s):A_(t,$s(o),a,s)},function(i,a){var s=N4(this),o=$s(i);if(typeof a=="string"&&P_(a,n)===-1&&P_(a,"$<")===-1){var u=r(t,s,o,a);if(u.done)return u.value}var c=L4(a);c||(a=$s(a));var l=s.global,p;l&&(p=s.unicode,s.lastIndex=0);for(var v=[],m;m=W4(s,o),!(m===null||(ip(v,m),!l));){var b=$s(m[0]);b===""&&(s.lastIndex=B4(o,F4(s.lastIndex),p))}for(var T="",I=0,R=0;R<v.length;R++){m=v[R];for(var x=$s(m[0]),N=H4(V4(j4(m.index),o.length),0),j=[],X,J=1;J<m.length;J++)ip(j,J4(m[J]));var V=m.groups;if(c){var D=K4([x],j,N,o);V!==void 0&&ip(D,V),X=$s(P4(a,void 0,D))}else X=z4(x,o,N,j,V,a);N>=I&&(T+=M_(o,I,N)+X,I=N+x.length)}return T+M_(o,I)}]},!X4||!Y4||x_);var Q4=Ct,Z4=wt,eq=Su,tq=Cn,rq=vf,nq=Z4([].join),iq=eq!==Object,aq=iq||!rq("join",",");Q4({target:"Array",proto:!0,forced:aq},{join:function(t){return nq(tq(this),t===void 0?",":t)}});var Wr={},sq=er,oq=Cu.EXISTS,uk=wt,uq=Ei,ck=Function.prototype,cq=uk(ck.toString),lk=/function\b(?:\s|\/\*[\S\s]*?\*\/|\/\/[^\n\r]*[\n\r]+)*([^\s(/]*)/,lq=uk(lk.exec),fq="name";sq&&!oq&&uq(ck,fq,{configurable:!0,get:function(){try{return lq(lk,cq(this))[1]}catch{return""}}});var fk={exports:{}},dk={exports:{}};(function(e){function t(r){if(Array.isArray(r))return r}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports})(dk);var dq=dk.exports,pk={exports:{}};(function(e){function t(r,n){var i=r==null?null:typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(i!=null){var a,s,o,u,c=[],l=!0,p=!1;try{if(o=(i=i.call(r)).next,n===0){if(Object(i)!==i)return;l=!1}else for(;!(l=(a=o.call(i)).done)&&(c.push(a.value),c.length!==n);l=!0);}catch(v){p=!0,s=v}finally{try{if(!l&&i.return!=null&&(u=i.return(),Object(u)!==u))return}finally{if(p)throw s}}return c}}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports})(pk);var pq=pk.exports,hk={exports:{}},vk={exports:{}};(function(e){function t(r,n){(n==null||n>r.length)&&(n=r.length);for(var i=0,a=Array(n);i<n;i++)a[i]=r[i];return a}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports})(vk);var mk=vk.exports;(function(e){var t=mk;function r(n,i){if(n){if(typeof n=="string")return t(n,i);var a={}.toString.call(n).slice(8,-1);return a==="Object"&&n.constructor&&(a=n.constructor.name),a==="Map"||a==="Set"?Array.from(n):a==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(a)?t(n,i):void 0}}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports})(hk);var gk=hk.exports,yk={exports:{}};(function(e){function t(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
21
21
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports})(yk);var hq=yk.exports;(function(e){var t=dq,r=pq,n=gk,i=hq;function a(s,o){return t(s)||r(s,o)||n(s,o)||i()}e.exports=a,e.exports.__esModule=!0,e.exports.default=e.exports})(fk);var bo=fk.exports,vq=Ct,N_=Iu,mq=cf,gq=ar,L_=hs,yq=Yr,bq=Cn,_q=xu,wq=Qt,Sq=Mu,Tq=Ci,Cq=Sq("slice"),Eq=wq("species"),ap=Array,kq=Math.max;vq({target:"Array",proto:!0,forced:!Cq},{slice:function(t,r){var n=bq(this),i=yq(n),a=L_(t,i),s=L_(r===void 0?i:r,i),o,u,c;if(N_(n)&&(o=n.constructor,mq(o)&&(o===ap||N_(o.prototype))?o=void 0:gq(o)&&(o=o[Eq],o===null&&(o=void 0)),o===ap||o===void 0))return Tq(n,a,s);for(u=new(o===void 0?ap:o)(kq(s-a,0)),c=0;a<s;a++,c++)a in n&&_q(u,c,n[a]);return u.length=c,u}});var Rq=Ct,D_=Yt,$q=Xt,j_=wr,Iq=Lr,Oq=function(){var e=!1,t=/[ac]/;return t.exec=function(){return e=!0,/./.exec.apply(this,arguments)},t.test("abc")===!0&&e}(),Aq=/./.test;Rq({target:"RegExp",proto:!0,forced:!Oq},{test:function(e){var t=j_(this),r=Iq(e),n=t.exec;if(!$q(n))return D_(Aq,t,r);var i=D_(n,t,r);return i===null?!1:(j_(i),!0)}});var Pq=Ct,Mq=er,xq=$t,Tc=wt,Nq=vr,Lq=Xt,Dq=Yi,jq=Lr,Fq=Ei,Uq=fm,Di=xq.Symbol,Ga=Di&&Di.prototype;if(Mq&&Lq(Di)&&(!("description"in Ga)||Di().description!==void 0)){var F_={},Cc=function(){var t=arguments.length<1||arguments[0]===void 0?void 0:jq(arguments[0]),r=Dq(Ga,this)?new Di(t):t===void 0?Di():Di(t);return t===""&&(F_[r]=!0),r};Uq(Cc,Di),Cc.prototype=Ga,Ga.constructor=Cc;var Bq=String(Di("description detection"))==="Symbol(description detection)",qq=Tc(Ga.valueOf),zq=Tc(Ga.toString),Wq=/^Symbol\((.*)\)[^)]+$/,Gq=Tc("".replace),Hq=Tc("".slice);Fq(Ga,"description",{configurable:!0,get:function(){var t=qq(this);if(Nq(F_,t))return"";var r=zq(t),n=Bq?Hq(r,7,-1):Gq(r,Wq,"$1");return n===""?void 0:n}}),Pq({global:!0,constructor:!0,forced:!0},{Symbol:Cc})}var Vq=TC;Vq("iterator");var bk={exports:{}},_k={exports:{}};(function(e){var t=mk;function r(n){if(Array.isArray(n))return t(n)}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports})(_k);var Kq=_k.exports,wk={exports:{}};(function(e){function t(r){if(typeof Symbol<"u"&&r[Symbol.iterator]!=null||r["@@iterator"]!=null)return Array.from(r)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports})(wk);var Jq=wk.exports,Sk={exports:{}};(function(e){function t(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
22
22
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports})(Sk);var Yq=Sk.exports;(function(e){var t=Kq,r=Jq,n=gk,i=Yq;function a(s){return t(s)||r(s)||n(s)||i()}e.exports=a,e.exports.__esModule=!0,e.exports.default=e.exports})(bk);var _o=bk.exports,Xq=Ct,Qq=of.includes,Zq=yt,e6=Um,t6=Zq(function(){return!Array(1).includes()});Xq({target:"Array",proto:!0,forced:t6},{includes:function(t){return Qq(this,t,arguments.length>1?arguments[1]:void 0)}});e6("includes");var r6=ar,n6=Math.floor,Tk=Number.isInteger||function(t){return!r6(t)&&isFinite(t)&&n6(t)===t},i6=Ct,a6=Tk;i6({target:"Number",stat:!0},{isInteger:a6});var Ck=er,s6=yt,Ek=wt,o6=Bu,u6=$u,c6=Cn,l6=wu.f,kk=Ek(l6),f6=Ek([].push),d6=Ck&&s6(function(){var e=Object.create(null);return e[2]=2,!kk(e,2)}),p6=function(e){return function(t){for(var r=c6(t),n=u6(r),i=d6&&o6(r)===null,a=n.length,s=0,o=[],u;a>s;)u=n[s++],(!Ck||(i?u in r:kk(r,u)))&&f6(o,e?[u,r[u]]:r[u]);return o}},h6={entries:p6(!0)},v6=Ct,m6=h6.entries;v6({target:"Object",stat:!0},{entries:function(t){return m6(t)}});/*
23
23
  @license
@@ -30,10 +30,10 @@ The above copyright notice and this permission notice shall be included in all c
30
30
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
31
31
 
32
32
 
33
- */Object.defineProperty(zr,"__esModule",{value:!0});var g6=qn,y6=bo,b6=_o,_6=Aa,w6=$i,S6=ki,T6=Ri,C6=zn;function Ma(e){return e&&typeof e=="object"&&"default"in e?e:{default:e}}var Hs=Ma(g6),Hi=Ma(y6),sp=Ma(b6),E6=Ma(_6),k6=Ma(w6),R6=Ma(S6),$6=Ma(T6),U_=Ma(C6),ta=function(){for(var t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];return{checks:r}},Rk=function(){for(var t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];return ta(function(i){for(var a=!1,s=[],o=0,u=r;o<u.length;o++){var c=u[o];if(typeof c=="string"){a=a||Hs.default(i)===c,s.push("of type ".concat(c));continue}a=a||i instanceof c,s.push("an instance of ".concat(c.name))}return[a,s]})},I6=function(){for(var t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];return ta(function(i){for(var a=!1,s=[],o=0,u=r;o<u.length;o++){var c=u[o];a=a||i===c,s.push(typeof c=="string"?'"'.concat(c,'"'):"".concat(c))}return[a,s]})};function O6(e){var t=A6();return function(){var n=U_.default(e),i;if(t){var a=U_.default(this).constructor;i=Reflect.construct(n,arguments,a)}else i=n.apply(this,arguments);return $6.default(this,i)}}function A6(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function hu(e,t){var r=typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=P6(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(c){throw c},f:i}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
33
+ */Object.defineProperty(Wr,"__esModule",{value:!0});var g6=qn,y6=bo,b6=_o,_6=Aa,w6=$i,S6=ki,T6=Ri,C6=zn;function Ma(e){return e&&typeof e=="object"&&"default"in e?e:{default:e}}var Hs=Ma(g6),Hi=Ma(y6),sp=Ma(b6),E6=Ma(_6),k6=Ma(w6),R6=Ma(S6),$6=Ma(T6),U_=Ma(C6),ta=function(){for(var t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];return{checks:r}},Rk=function(){for(var t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];return ta(function(i){for(var a=!1,s=[],o=0,u=r;o<u.length;o++){var c=u[o];if(typeof c=="string"){a=a||Hs.default(i)===c,s.push("of type ".concat(c));continue}a=a||i instanceof c,s.push("an instance of ".concat(c.name))}return[a,s]})},I6=function(){for(var t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];return ta(function(i){for(var a=!1,s=[],o=0,u=r;o<u.length;o++){var c=u[o];a=a||i===c,s.push(typeof c=="string"?'"'.concat(c,'"'):"".concat(c))}return[a,s]})};function O6(e){var t=A6();return function(){var n=U_.default(e),i;if(t){var a=U_.default(this).constructor;i=Reflect.construct(n,arguments,a)}else i=n.apply(this,arguments);return $6.default(this,i)}}function A6(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function hu(e,t){var r=typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=P6(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(c){throw c},f:i}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
34
34
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var a=!0,s=!1,o;return{s:function(){r=r.call(e)},n:function(){var c=r.next();return a=c.done,c},e:function(c){s=!0,o=c},f:function(){try{!a&&r.return!=null&&r.return()}finally{if(s)throw o}}}}function P6(e,t){if(e){if(typeof e=="string")return B_(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return B_(e,t)}}function B_(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}var If=function(t,r){if(r.length>t.length)throw new Error("Expected at most ".concat(t.length," argument(s), but got ").concat(r.length));for(;r.length<t.length;)r.push(void 0);var n=hu(r.entries()),i;try{for(n.s();!(i=n.n()).done;){var a=Hi.default(i.value,2),s=a[0],o=a[1],u=Af(t[s],o),c=Hi.default(u,4),l=c[0],p=c[1],v=c[2],m=c[3];if(!l){var b=s+1;throw new Error("Argument ".concat(b," is expected to be ").concat(v).concat(m," but got ").concat(p))}}}catch(T){n.e(T)}finally{n.f()}},$k=function(t){var r,n,i=["undefined","boolean","number","bigint","string"];if(i.includes(Hs.default(t))&&(n=typeof t=="string"?'"'.concat(t,'"'):"".concat(t)),Hs.default(t)==="object"&&(t==null||(r=t.constructor)===null||r===void 0?void 0:r.name)!=="Object"){var a;n=t===null?"null":"instance of ".concat(t==null||(a=t.constructor)===null||a===void 0?void 0:a.name)}return n||(n=Hs.default(t)),n},M6=function(){for(var t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];var i=Ym(r);return function(a){return function(s){R6.default(u,s);var o=O6(u);function u(){k6.default(this,u);for(var c=arguments.length,l=new Array(c),p=0;p<c;p++)l[p]=arguments[p];return If(i,l),o.call.apply(o,[this].concat(l))}return E6.default(u)}(a)}},x6=function(){for(var t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];var i=Ym(r);return function(a,s,o){if(typeof o.value!="function")throw new Error("The validateTypes decorator can only be applied to methods");var u=o.value;o.value=function(){for(var c=arguments.length,l=new Array(c),p=0;p<c;p++)l[p]=arguments[p];return If(i,l),u.apply(this,l)}}},N6=function(){for(var t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];var i=Ym(r);return function(a,s,o){if(typeof o.value!="function")throw new Error("The validateTypesAsync decorator can only be applied to methods");var u=o.value;o.value=function(){for(var c=arguments.length,l=new Array(c),p=0;p<c;p++)l[p]=arguments[p];try{If(i,l)}catch(v){return Promise.reject(v)}return u.apply(this,l)}}},Ym=function(t){var r=[],n=hu(t),i;try{for(n.s();!(i=n.n()).done;){var a=i.value;r.push(Of(a))}}catch(s){n.e(s)}finally{n.f()}return r},Of=function(t){var r=[],n=Array.isArray(t)?t:[t],i=hu(n),a;try{for(i.s();!(a=i.n()).done;){var s=a.value;if(typeof s=="string"||typeof s=="function"){r.push(Rk(s));continue}r.push(s)}}catch(o){i.e(o)}finally{i.f()}return r},Af=function(t,r){var n=[],i,a=!1,s=hu(t),o;try{for(s.s();!(o=s.n()).done;){var u=o.value,c=hu(u.checks),l;try{for(c.s();!(l=c.n()).done;){var p=l.value,v=p(r),m=Hi.default(v,3),b=m[0],T=m[1],I=m[2];a=a||b,!i&&I&&(i=I),T&&(n=typeof T=="string"?[].concat(sp.default(n),[T]):[].concat(sp.default(n),sp.default(T)))}}catch(j){c.e(j)}finally{c.f()}}}catch(j){s.e(j)}finally{s.f()}if(a)return[!0];var R=i||$k(r),x=n.length-1,N=x>0?"".concat(n.slice(0,x).join(", ")," or ").concat(n[x]):n.join(", ");return[!1,R,N,x>1?";":","]};function L6(e,t){var r=typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=D6(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(c){throw c},f:i}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
35
35
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var a=!0,s=!1,o;return{s:function(){r=r.call(e)},n:function(){var c=r.next();return a=c.done,c},e:function(c){s=!0,o=c},f:function(){try{!a&&r.return!=null&&r.return()}finally{if(s)throw o}}}}function D6(e,t){if(e){if(typeof e=="string")return q_(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return q_(e,t)}}function q_(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}var j6=function(t,r){return ta(function(n){if(!Array.isArray(n)||n.length<1)return[!1,"a non-empty array of ".concat(t)];var i=L6(n.entries()),a;try{for(i.s();!(a=i.n()).done;){var s=Hi.default(a.value,2),o=s[0],u=s[1],c=Af(Of(r),u),l=Hi.default(c,3),p=l[0],v=l[1],m=l[2];if(!p)return[!1,"a valid non-empty array of ".concat(t," (index ").concat(o," should be ").concat(m,")"),"malformed array of ".concat(t," (index ").concat(o," is ").concat(v,")")]}}catch(b){i.e(b)}finally{i.f()}return[!0]})},F6=ta(function(e){return[typeof e=="string"&&e.length>0,"a non-empty string"]}),U6=ta(function(e){return[typeof e=="number"&&Number.isInteger(e)&&e>=0,"a non-negative integer"]}),B6=ta(function(e){return[Hs.default(e)==="object"&&e!==null&&!Array.isArray(e),"a pure object (non-null and non-array)"]}),q6=function(t,r){return ta(function(n){if(Hs.default(n)!=="object"||n===null||Array.isArray(n))return[!1,"valid ".concat(t," (should be a pure object)")];for(var i=0,a=Object.entries(r);i<a.length;i++){var s=Hi.default(a[i],2),o=s[0],u=s[1],c=Af(Of(u),n[o]),l=Hi.default(c,3),p=l[0],v=l[1],m=l[2];if(!p)return[!1,"valid ".concat(t,' (key "').concat(o,'" should be ').concat(m,")"),"malformed ".concat(t,' (key "').concat(o,'" is ').concat(v,")")]}return[!0]})};function z6(e,t){var r=typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=W6(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(c){throw c},f:i}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
36
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var a=!0,s=!1,o;return{s:function(){r=r.call(e)},n:function(){var c=r.next();return a=c.done,c},e:function(c){s=!0,o=c},f:function(){try{!a&&r.return!=null&&r.return()}finally{if(s)throw o}}}}function W6(e,t){if(e){if(typeof e=="string")return z_(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return z_(e,t)}}function z_(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}var G6=function(t,r){return ta(function(n){if(!Array.isArray(n))return[!1,"an array of ".concat(t)];var i=z6(n.entries()),a;try{for(i.s();!(a=i.n()).done;){var s=Hi.default(a.value,2),o=s[0],u=s[1],c=Af(Of(r),u),l=Hi.default(c,3),p=l[0],v=l[1],m=l[2];if(!p)return[!1,"a valid array of ".concat(t," (index ").concat(o," should be ").concat(m,")"),"malformed array of ".concat(t," (index ").concat(o," is ").concat(v,")")]}}catch(b){i.e(b)}finally{i.f()}return[!0]})};zr.array=G6;zr.custom=ta;zr.literal=I6;zr.nonEmptyArray=j6;zr.nonEmptyString=F6;zr.nonNegativeInteger=U6;zr.objectSchema=q6;zr.pureObject=B6;zr.runtimeTypeValidation=If;zr.stringifyReceivedType=$k;zr.type=Rk;zr.validateConstructorTypes=M6;zr.validateTypes=x6;zr.validateTypesAsync=N6;var Xm={},Ik={exports:{}},Ok={exports:{}};(function(e){var t=zn;function r(n,i){for(;!{}.hasOwnProperty.call(n,i)&&(n=t(n))!==null;);return n}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports})(Ok);var H6=Ok.exports;(function(e){var t=H6;function r(){return e.exports=r=typeof Reflect<"u"&&Reflect.get?Reflect.get.bind():function(n,i,a){var s=t(n,i);if(s){var o=Object.getOwnPropertyDescriptor(s,i);return o.get?o.get.call(arguments.length<3?n:a):o.value}},e.exports.__esModule=!0,e.exports.default=e.exports,r.apply(null,arguments)}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports})(Ik);var Qm=Ik.exports;/*
36
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var a=!0,s=!1,o;return{s:function(){r=r.call(e)},n:function(){var c=r.next();return a=c.done,c},e:function(c){s=!0,o=c},f:function(){try{!a&&r.return!=null&&r.return()}finally{if(s)throw o}}}}function W6(e,t){if(e){if(typeof e=="string")return z_(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return z_(e,t)}}function z_(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}var G6=function(t,r){return ta(function(n){if(!Array.isArray(n))return[!1,"an array of ".concat(t)];var i=z6(n.entries()),a;try{for(i.s();!(a=i.n()).done;){var s=Hi.default(a.value,2),o=s[0],u=s[1],c=Af(Of(r),u),l=Hi.default(c,3),p=l[0],v=l[1],m=l[2];if(!p)return[!1,"a valid array of ".concat(t," (index ").concat(o," should be ").concat(m,")"),"malformed array of ".concat(t," (index ").concat(o," is ").concat(v,")")]}}catch(b){i.e(b)}finally{i.f()}return[!0]})};Wr.array=G6;Wr.custom=ta;Wr.literal=I6;Wr.nonEmptyArray=j6;Wr.nonEmptyString=F6;Wr.nonNegativeInteger=U6;Wr.objectSchema=q6;Wr.pureObject=B6;Wr.runtimeTypeValidation=If;Wr.stringifyReceivedType=$k;Wr.type=Rk;Wr.validateConstructorTypes=M6;Wr.validateTypes=x6;Wr.validateTypesAsync=N6;var Xm={},Ik={exports:{}},Ok={exports:{}};(function(e){var t=zn;function r(n,i){for(;!{}.hasOwnProperty.call(n,i)&&(n=t(n))!==null;);return n}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports})(Ok);var H6=Ok.exports;(function(e){var t=H6;function r(){return e.exports=r=typeof Reflect<"u"&&Reflect.get?Reflect.get.bind():function(n,i,a){var s=t(n,i);if(s){var o=Object.getOwnPropertyDescriptor(s,i);return o.get?o.get.call(arguments.length<3?n:a):o.value}},e.exports.__esModule=!0,e.exports.default=e.exports,r.apply(null,arguments)}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports})(Ik);var Qm=Ik.exports;/*
37
37
  @license
38
38
  Copyright (c) 2021 Twilio Inc.
39
39
 
@@ -43,7 +43,7 @@ The above copyright notice and this permission notice shall be included in all c
43
43
 
44
44
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
45
45
 
46
- */Object.defineProperty(Xm,"__esModule",{value:!0});var V6=_o,K6=$i,J6=Aa,Y6=ms,X6=Qm,Q6=ki,Z6=Ri,ez=zn,tz=gs;function ra(e){return e&&typeof e=="object"&&"default"in e?e:{default:e}}var W_=ra(V6),rz=ra(K6),nz=ra(J6),iz=ra(Y6),Ha=ra(X6),az=ra(Q6),sz=ra(Z6),ji=ra(ez),oz=ra(tz),uz;function Sa(){}Sa.prototype=Object.create(null);function Zt(){Zt.init.call(this)}Zt.EventEmitter=Zt;Zt.usingDomains=!1;Zt.prototype.domain=void 0;Zt.prototype._events=void 0;Zt.prototype._maxListeners=void 0;Zt.defaultMaxListeners=10;Zt.init=function(){this.domain=null,Zt.usingDomains&&uz.active,(!this._events||this._events===Object.getPrototypeOf(this)._events)&&(this._events=new Sa,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};Zt.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||isNaN(t))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=t,this};function Ak(e){return e._maxListeners===void 0?Zt.defaultMaxListeners:e._maxListeners}Zt.prototype.getMaxListeners=function(){return Ak(this)};function cz(e,t,r){if(t)e.call(r);else for(var n=e.length,i=qu(e,n),a=0;a<n;++a)i[a].call(r)}function lz(e,t,r,n){if(t)e.call(r,n);else for(var i=e.length,a=qu(e,i),s=0;s<i;++s)a[s].call(r,n)}function fz(e,t,r,n,i){if(t)e.call(r,n,i);else for(var a=e.length,s=qu(e,a),o=0;o<a;++o)s[o].call(r,n,i)}function dz(e,t,r,n,i,a){if(t)e.call(r,n,i,a);else for(var s=e.length,o=qu(e,s),u=0;u<s;++u)o[u].call(r,n,i,a)}function pz(e,t,r,n){if(t)e.apply(r,n);else for(var i=e.length,a=qu(e,i),s=0;s<i;++s)a[s].apply(r,n)}Zt.prototype.emit=function(t){var r,n,i,a,s,o,u,c=t==="error";if(o=this._events,o)c=c&&o.error==null;else if(!c)return!1;if(u=this.domain,c){if(r=arguments[1],u)r||(r=new Error('Uncaught, unspecified "error" event')),r.domainEmitter=this,r.domain=u,r.domainThrown=!1,u.emit("error",r);else{if(r instanceof Error)throw r;var l=new Error('Uncaught, unspecified "error" event. ('+r+")");throw l.context=r,l}return!1}if(n=o[t],!n)return!1;var p=typeof n=="function";switch(i=arguments.length,i){case 1:cz(n,p,this);break;case 2:lz(n,p,this,arguments[1]);break;case 3:fz(n,p,this,arguments[1],arguments[2]);break;case 4:dz(n,p,this,arguments[1],arguments[2],arguments[3]);break;default:for(a=new Array(i-1),s=1;s<i;s++)a[s-1]=arguments[s];pz(n,p,this,a)}return!0};function Pk(e,t,r,n){var i,a,s;if(typeof r!="function")throw new TypeError('"listener" argument must be a function');if(a=e._events,a?(a.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),a=e._events),s=a[t]):(a=e._events=new Sa,e._eventsCount=0),!s)s=a[t]=r,++e._eventsCount;else if(typeof s=="function"?s=a[t]=n?[r,s]:[s,r]:n?s.unshift(r):s.push(r),!s.warned&&(i=Ak(e),i&&i>0&&s.length>i)){s.warned=!0;var o=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");o.name="MaxListenersExceededWarning",o.emitter=e,o.type=t,o.count=s.length,hz(o)}return e}function hz(e){typeof console.warn=="function"?console.warn(e):console.log(e)}Zt.prototype.addListener=function(t,r){return Pk(this,t,r,!1)};Zt.prototype.on=Zt.prototype.addListener;Zt.prototype.prependListener=function(t,r){return Pk(this,t,r,!0)};function Mk(e,t,r){var n=!1;function i(){e.removeListener(t,i),n||(n=!0,r.apply(e,arguments))}return i.listener=r,i}Zt.prototype.once=function(t,r){if(typeof r!="function")throw new TypeError('"listener" argument must be a function');return this.on(t,Mk(this,t,r)),this};Zt.prototype.prependOnceListener=function(t,r){if(typeof r!="function")throw new TypeError('"listener" argument must be a function');return this.prependListener(t,Mk(this,t,r)),this};Zt.prototype.removeListener=function(t,r){var n,i,a,s,o;if(typeof r!="function")throw new TypeError('"listener" argument must be a function');if(i=this._events,!i)return this;if(n=i[t],!n)return this;if(n===r||n.listener&&n.listener===r)--this._eventsCount===0?this._events=new Sa:(delete i[t],i.removeListener&&this.emit("removeListener",t,n.listener||r));else if(typeof n!="function"){for(a=-1,s=n.length;s-- >0;)if(n[s]===r||n[s].listener&&n[s].listener===r){o=n[s].listener,a=s;break}if(a<0)return this;if(n.length===1){if(n[0]=void 0,--this._eventsCount===0)return this._events=new Sa,this;delete i[t]}else vz(n,a);i.removeListener&&this.emit("removeListener",t,o||r)}return this};Zt.prototype.off=function(e,t){return this.removeListener(e,t)};Zt.prototype.removeAllListeners=function(t){var r,n;if(n=this._events,!n)return this;if(!n.removeListener)return arguments.length===0?(this._events=new Sa,this._eventsCount=0):n[t]&&(--this._eventsCount===0?this._events=new Sa:delete n[t]),this;if(arguments.length===0){for(var i=Object.keys(n),a=0,s;a<i.length;++a)s=i[a],s!=="removeListener"&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=new Sa,this._eventsCount=0,this}if(r=n[t],typeof r=="function")this.removeListener(t,r);else if(r)do this.removeListener(t,r[r.length-1]);while(r[0]);return this};Zt.prototype.listeners=function(t){var r,n,i=this._events;return i?(r=i[t],r?typeof r=="function"?n=[r.listener||r]:n=mz(r):n=[]):n=[],n};Zt.listenerCount=function(e,t){return typeof e.listenerCount=="function"?e.listenerCount(t):xk.call(e,t)};Zt.prototype.listenerCount=xk;function xk(e){var t=this._events;if(t){var r=t[e];if(typeof r=="function")return 1;if(r)return r.length}return 0}Zt.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};function vz(e,t){for(var r=t,n=r+1,i=e.length;n<i;r+=1,n+=1)e[r]=e[n];e.pop()}function qu(e,t){for(var r=new Array(t);t--;)r[t]=e[t];return r}function mz(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}function gz(e){var t=yz();return function(){var n=ji.default(e),i;if(t){var a=ji.default(this).constructor;i=Reflect.construct(n,arguments,a)}else i=n.apply(this,arguments);return sz.default(this,i)}}function yz(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var bz=function(e){az.default(r,e);var t=gz(r);function r(){var n;return rz.default(this,r),n=t.call(this),oz.default(iz.default(n),"eventHistory",new Map),n}return nz.default(r,[{key:"on",value:function(i,a){return Ha.default(ji.default(r.prototype),"on",this).call(this,i,a)}},{key:"once",value:function(i,a){return Ha.default(ji.default(r.prototype),"once",this).call(this,i,a)}},{key:"off",value:function(i,a){return Ha.default(ji.default(r.prototype),"off",this).call(this,i,a)}},{key:"emit",value:function(i){for(var a,s=arguments.length,o=new Array(s>1?s-1:0),u=1;u<s;u++)o[u-1]=arguments[u];return this.eventHistory.set(i,o),(a=Ha.default(ji.default(r.prototype),"emit",this)).call.apply(a,[this,i].concat(o))}},{key:"addListener",value:function(i,a){return Ha.default(ji.default(r.prototype),"addListener",this).call(this,i,a)}},{key:"removeListener",value:function(i,a){return Ha.default(ji.default(r.prototype),"removeListener",this).call(this,i,a)}},{key:"addListenerWithReplay",value:function(i,a){var s=this.eventHistory.get(i);return s!==void 0&&a.apply(void 0,W_.default(s)),this.addListener(i,a)}},{key:"onWithReplay",value:function(i,a){return this.addListenerWithReplay(i,a)}},{key:"onceWithReplay",value:function(i,a){var s=this.eventHistory.get(i);return s!==void 0?(a.apply(void 0,W_.default(s)),this):Ha.default(ji.default(r.prototype),"once",this).call(this,i,a)}}]),r}(Zt);Xm.ReplayEventEmitter=bz;var Bl={exports:{}};Bl.exports;(function(e,t){var r=200,n="__lodash_hash_undefined__",i=1,a=2,s=9007199254740991,o="[object Arguments]",u="[object Array]",c="[object AsyncFunction]",l="[object Boolean]",p="[object Date]",v="[object Error]",m="[object Function]",b="[object GeneratorFunction]",T="[object Map]",I="[object Number]",R="[object Null]",x="[object Object]",N="[object Promise]",j="[object Proxy]",X="[object RegExp]",J="[object Set]",V="[object String]",D="[object Symbol]",te="[object Undefined]",ue="[object WeakMap]",ee="[object ArrayBuffer]",ge="[object DataView]",L="[object Float32Array]",pe="[object Float64Array]",Te="[object Int8Array]",rt="[object Int16Array]",Ke="[object Int32Array]",Se="[object Uint8Array]",ce="[object Uint8ClampedArray]",he="[object Uint16Array]",P="[object Uint32Array]",Ie=/[\\^$.*+?()[\]{}|]/g,qe=/^\[object .+?Constructor\]$/,Ne=/^(?:0|[1-9]\d*)$/,_e={};_e[L]=_e[pe]=_e[Te]=_e[rt]=_e[Ke]=_e[Se]=_e[ce]=_e[he]=_e[P]=!0,_e[o]=_e[u]=_e[ee]=_e[l]=_e[ge]=_e[p]=_e[v]=_e[m]=_e[T]=_e[I]=_e[x]=_e[X]=_e[J]=_e[V]=_e[ue]=!1;var Q=typeof je=="object"&&je&&je.Object===Object&&je,kt=typeof self=="object"&&self&&self.Object===Object&&self,Ce=Q||kt||Function("return this")(),de=t&&!t.nodeType&&t,Rt=de&&!0&&e&&!e.nodeType&&e,Ue=Rt&&Rt.exports===de,Dt=Ue&&Q.process,mt=function(){try{return Dt&&Dt.binding&&Dt.binding("util")}catch{}}(),ke=mt&&mt.isTypedArray;function ft(W,ie){for(var Ee=-1,Ze=W==null?0:W.length,Kt=0,_t=[];++Ee<Ze;){var Jt=W[Ee];ie(Jt,Ee,W)&&(_t[Kt++]=Jt)}return _t}function St(W,ie){for(var Ee=-1,Ze=ie.length,Kt=W.length;++Ee<Ze;)W[Kt+Ee]=ie[Ee];return W}function Oe(W,ie){for(var Ee=-1,Ze=W==null?0:W.length;++Ee<Ze;)if(ie(W[Ee],Ee,W))return!0;return!1}function Bt(W,ie){for(var Ee=-1,Ze=Array(W);++Ee<W;)Ze[Ee]=ie(Ee);return Ze}function vt(W){return function(ie){return W(ie)}}function qt(W,ie){return W.has(ie)}function sr(W,ie){return W==null?void 0:W[ie]}function ze(W){var ie=-1,Ee=Array(W.size);return W.forEach(function(Ze,Kt){Ee[++ie]=[Kt,Ze]}),Ee}function Tr(W,ie){return function(Ee){return W(ie(Ee))}}function mr(W){var ie=-1,Ee=Array(W.size);return W.forEach(function(Ze){Ee[++ie]=Ze}),Ee}var Et=Array.prototype,It=Function.prototype,bt=Object.prototype,ct=Ce["__core-js_shared__"],Ft=It.toString,Pt=bt.hasOwnProperty,cr=function(){var W=/[^.]+$/.exec(ct&&ct.keys&&ct.keys.IE_PROTO||"");return W?"Symbol(src)_1."+W:""}(),Cr=bt.toString,Dr=RegExp("^"+Ft.call(Pt).replace(Ie,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),gr=Ue?Ce.Buffer:void 0,zt=Ce.Symbol,lr=Ce.Uint8Array,ye=bt.propertyIsEnumerable,we=Et.splice,se=zt?zt.toStringTag:void 0,me=Object.getOwnPropertySymbols,le=gr?gr.isBuffer:void 0,be=Tr(Object.keys,Object),$e=kr(Ce,"DataView"),re=kr(Ce,"Map"),ae=kr(Ce,"Promise"),K=kr(Ce,"Set"),oe=kr(Ce,"WeakMap"),Y=kr(Object,"create"),De=k($e),Re=k(re),Je=k(ae),Ge=k(K),He=k(oe),et=zt?zt.prototype:void 0,nt=et?et.valueOf:void 0;function Qe(W){var ie=-1,Ee=W==null?0:W.length;for(this.clear();++ie<Ee;){var Ze=W[ie];this.set(Ze[0],Ze[1])}}function tt(){this.__data__=Y?Y(null):{},this.size=0}function at(W){var ie=this.has(W)&&delete this.__data__[W];return this.size-=ie?1:0,ie}function st(W){var ie=this.__data__;if(Y){var Ee=ie[W];return Ee===n?void 0:Ee}return Pt.call(ie,W)?ie[W]:void 0}function yr(W){var ie=this.__data__;return Y?ie[W]!==void 0:Pt.call(ie,W)}function fr(W,ie){var Ee=this.__data__;return this.size+=this.has(W)?0:1,Ee[W]=Y&&ie===void 0?n:ie,this}Qe.prototype.clear=tt,Qe.prototype.delete=at,Qe.prototype.get=st,Qe.prototype.has=yr,Qe.prototype.set=fr;function dt(W){var ie=-1,Ee=W==null?0:W.length;for(this.clear();++ie<Ee;){var Ze=W[ie];this.set(Ze[0],Ze[1])}}function Wr(){this.__data__=[],this.size=0}function cn(W){var ie=this.__data__,Ee=or(ie,W);if(Ee<0)return!1;var Ze=ie.length-1;return Ee==Ze?ie.pop():we.call(ie,Ee,1),--this.size,!0}function it(W){var ie=this.__data__,Ee=or(ie,W);return Ee<0?void 0:ie[Ee][1]}function Z(W){return or(this.__data__,W)>-1}function xe(W,ie){var Ee=this.__data__,Ze=or(Ee,W);return Ze<0?(++this.size,Ee.push([W,ie])):Ee[Ze][1]=ie,this}dt.prototype.clear=Wr,dt.prototype.delete=cn,dt.prototype.get=it,dt.prototype.has=Z,dt.prototype.set=xe;function Ye(W){var ie=-1,Ee=W==null?0:W.length;for(this.clear();++ie<Ee;){var Ze=W[ie];this.set(Ze[0],Ze[1])}}function Mt(){this.size=0,this.__data__={hash:new Qe,map:new(re||dt),string:new Qe}}function nr(W){var ie=Hn(this,W).delete(W);return this.size-=ie?1:0,ie}function Ot(W){return Hn(this,W).get(W)}function ir(W){return Hn(this,W).has(W)}function Pr(W,ie){var Ee=Hn(this,W),Ze=Ee.size;return Ee.set(W,ie),this.size+=Ee.size==Ze?0:1,this}Ye.prototype.clear=Mt,Ye.prototype.delete=nr,Ye.prototype.get=Ot,Ye.prototype.has=ir,Ye.prototype.set=Pr;function Mr(W){var ie=-1,Ee=W==null?0:W.length;for(this.__data__=new Ye;++ie<Ee;)this.add(W[ie])}function dr(W){return this.__data__.set(W,n),this}function $n(W){return this.__data__.has(W)}Mr.prototype.add=Mr.prototype.push=dr,Mr.prototype.has=$n;function Gr(W){var ie=this.__data__=new dt(W);this.size=ie.size}function oa(){this.__data__=new dt,this.size=0}function ja(W){var ie=this.__data__,Ee=ie.delete(W);return this.size=ie.size,Ee}function Fa(W){return this.__data__.get(W)}function Er(W){return this.__data__.has(W)}function Ua(W,ie){var Ee=this.__data__;if(Ee instanceof dt){var Ze=Ee.__data__;if(!re||Ze.length<r-1)return Ze.push([W,ie]),this.size=++Ee.size,this;Ee=this.__data__=new Ye(Ze)}return Ee.set(W,ie),this.size=Ee.size,this}Gr.prototype.clear=oa,Gr.prototype.delete=ja,Gr.prototype.get=Fa,Gr.prototype.has=Er,Gr.prototype.set=Ua;function ci(W,ie){var Ee=M(W),Ze=!Ee&&q(W),Kt=!Ee&&!Ze&&fe(W),_t=!Ee&&!Ze&&!Kt&&br(W),Jt=Ee||Ze||Kt||_t,ur=Jt?Bt(W.length,String):[],_r=ur.length;for(var lt in W)Pt.call(W,lt)&&!(Jt&&(lt=="length"||Kt&&(lt=="offset"||lt=="parent")||_t&&(lt=="buffer"||lt=="byteLength"||lt=="byteOffset")||bn(lt,_r)))&&ur.push(lt);return ur}function or(W,ie){for(var Ee=W.length;Ee--;)if(E(W[Ee][0],ie))return Ee;return-1}function Ba(W,ie,Ee){var Ze=ie(W);return M(W)?Ze:St(Ze,Ee(W))}function gn(W){return W==null?W===void 0?te:R:se&&se in Object(W)?la(W):$(W)}function Oi(W){return ln(W)&&gn(W)==o}function Ai(W,ie,Ee,Ze,Kt){return W===ie?!0:W==null||ie==null||!ln(W)&&!ln(ie)?W!==W&&ie!==ie:qa(W,ie,Ee,Ze,Ai,Kt)}function qa(W,ie,Ee,Ze,Kt,_t){var Jt=M(W),ur=M(ie),_r=Jt?u:Hr(W),lt=ur?u:Hr(ie);_r=_r==o?x:_r,lt=lt==o?x:lt;var jr=_r==x,Fr=lt==x,pr=_r==lt;if(pr&&fe(W)){if(!fe(ie))return!1;Jt=!0,jr=!1}if(pr&&!jr)return _t||(_t=new Gr),Jt||br(W)?ca(W,ie,Ee,Ze,Kt,_t):Pi(W,ie,_r,Ee,Ze,Kt,_t);if(!(Ee&i)){var Ur=jr&&Pt.call(W,"__wrapped__"),gt=Fr&&Pt.call(ie,"__wrapped__");if(Ur||gt){var In=Ur?W.value():W,O=gt?ie.value():ie;return _t||(_t=new Gr),Kt(In,O,Ee,Ze,_t)}}return pr?(_t||(_t=new Gr),Mi(W,ie,Ee,Ze,Kt,_t)):!1}function yn(W){if(!$r(W)||F(W))return!1;var ie=Be(W)?Dr:qe;return ie.test(k(W))}function At(W){return ln(W)&&ot(W.length)&&!!_e[gn(W)]}function ua(W){if(!z(W))return be(W);var ie=[];for(var Ee in Object(W))Pt.call(W,Ee)&&Ee!="constructor"&&ie.push(Ee);return ie}function ca(W,ie,Ee,Ze,Kt,_t){var Jt=Ee&i,ur=W.length,_r=ie.length;if(ur!=_r&&!(Jt&&_r>ur))return!1;var lt=_t.get(W);if(lt&&_t.get(ie))return lt==ie;var jr=-1,Fr=!0,pr=Ee&a?new Mr:void 0;for(_t.set(W,ie),_t.set(ie,W);++jr<ur;){var Ur=W[jr],gt=ie[jr];if(Ze)var In=Jt?Ze(gt,Ur,jr,ie,W,_t):Ze(Ur,gt,jr,W,ie,_t);if(In!==void 0){if(In)continue;Fr=!1;break}if(pr){if(!Oe(ie,function(O,A){if(!qt(pr,A)&&(Ur===O||Kt(Ur,O,Ee,Ze,_t)))return pr.push(A)})){Fr=!1;break}}else if(!(Ur===gt||Kt(Ur,gt,Ee,Ze,_t))){Fr=!1;break}}return _t.delete(W),_t.delete(ie),Fr}function Pi(W,ie,Ee,Ze,Kt,_t,Jt){switch(Ee){case ge:if(W.byteLength!=ie.byteLength||W.byteOffset!=ie.byteOffset)return!1;W=W.buffer,ie=ie.buffer;case ee:return!(W.byteLength!=ie.byteLength||!_t(new lr(W),new lr(ie)));case l:case p:case I:return E(+W,+ie);case v:return W.name==ie.name&&W.message==ie.message;case X:case V:return W==ie+"";case T:var ur=ze;case J:var _r=Ze&i;if(ur||(ur=mr),W.size!=ie.size&&!_r)return!1;var lt=Jt.get(W);if(lt)return lt==ie;Ze|=a,Jt.set(W,ie);var jr=ca(ur(W),ur(ie),Ze,Kt,_t,Jt);return Jt.delete(W),jr;case D:if(nt)return nt.call(W)==nt.call(ie)}return!1}function Mi(W,ie,Ee,Ze,Kt,_t){var Jt=Ee&i,ur=li(W),_r=ur.length,lt=li(ie),jr=lt.length;if(_r!=jr&&!Jt)return!1;for(var Fr=_r;Fr--;){var pr=ur[Fr];if(!(Jt?pr in ie:Pt.call(ie,pr)))return!1}var Ur=_t.get(W);if(Ur&&_t.get(ie))return Ur==ie;var gt=!0;_t.set(W,ie),_t.set(ie,W);for(var In=Jt;++Fr<_r;){pr=ur[Fr];var O=W[pr],A=ie[pr];if(Ze)var f=Jt?Ze(A,O,pr,ie,W,_t):Ze(O,A,pr,W,ie,_t);if(!(f===void 0?O===A||Kt(O,A,Ee,Ze,_t):f)){gt=!1;break}In||(In=pr=="constructor")}if(gt&&!In){var d=W.constructor,h=ie.constructor;d!=h&&"constructor"in W&&"constructor"in ie&&!(typeof d=="function"&&d instanceof d&&typeof h=="function"&&h instanceof h)&&(gt=!1)}return _t.delete(W),_t.delete(ie),gt}function li(W){return Ba(W,_n,Rr)}function Hn(W,ie){var Ee=W.__data__;return fa(ie)?Ee[typeof ie=="string"?"string":"hash"]:Ee.map}function kr(W,ie){var Ee=sr(W,ie);return yn(Ee)?Ee:void 0}function la(W){var ie=Pt.call(W,se),Ee=W[se];try{W[se]=void 0;var Ze=!0}catch{}var Kt=Cr.call(W);return Ze&&(ie?W[se]=Ee:delete W[se]),Kt}var Rr=me?function(W){return W==null?[]:(W=Object(W),ft(me(W),function(ie){return ye.call(W,ie)}))}:Cs,Hr=gn;($e&&Hr(new $e(new ArrayBuffer(1)))!=ge||re&&Hr(new re)!=T||ae&&Hr(ae.resolve())!=N||K&&Hr(new K)!=J||oe&&Hr(new oe)!=ue)&&(Hr=function(W){var ie=gn(W),Ee=ie==x?W.constructor:void 0,Ze=Ee?k(Ee):"";if(Ze)switch(Ze){case De:return ge;case Re:return T;case Je:return N;case Ge:return J;case He:return ue}return ie});function bn(W,ie){return ie=ie??s,!!ie&&(typeof W=="number"||Ne.test(W))&&W>-1&&W%1==0&&W<ie}function fa(W){var ie=typeof W;return ie=="string"||ie=="number"||ie=="symbol"||ie=="boolean"?W!=="__proto__":W===null}function F(W){return!!cr&&cr in W}function z(W){var ie=W&&W.constructor,Ee=typeof ie=="function"&&ie.prototype||bt;return W===Ee}function $(W){return Cr.call(W)}function k(W){if(W!=null){try{return Ft.call(W)}catch{}try{return W+""}catch{}}return""}function E(W,ie){return W===ie||W!==W&&ie!==ie}var q=Oi(function(){return arguments}())?Oi:function(W){return ln(W)&&Pt.call(W,"callee")&&!ye.call(W,"callee")},M=Array.isArray;function ve(W){return W!=null&&ot(W.length)&&!Be(W)}var fe=le||ko;function Ae(W,ie){return Ai(W,ie)}function Be(W){if(!$r(W))return!1;var ie=gn(W);return ie==m||ie==b||ie==c||ie==j}function ot(W){return typeof W=="number"&&W>-1&&W%1==0&&W<=s}function $r(W){var ie=typeof W;return W!=null&&(ie=="object"||ie=="function")}function ln(W){return W!=null&&typeof W=="object"}var br=ke?vt(ke):At;function _n(W){return ve(W)?ci(W):ua(W)}function Cs(){return[]}function ko(){return!1}e.exports=Ae})(Bl,Bl.exports);var _z=Bl.exports,Nk={exports:{}},wz=yt,Sz=wz(function(){if(typeof ArrayBuffer=="function"){var e=new ArrayBuffer(8);Object.isExtensible(e)&&Object.defineProperty(e,"a",{value:8})}}),Tz=yt,Cz=ar,Ez=wi,G_=Sz,_l=Object.isExtensible,kz=Tz(function(){_l(1)}),Rz=kz||G_?function(t){return!Cz(t)||G_&&Ez(t)==="ArrayBuffer"?!1:_l?_l(t):!0}:_l,$z=yt,Lk=!$z(function(){return Object.isExtensible(Object.preventExtensions({}))}),Iz=Ct,Oz=wt,Az=Eu,Pz=ar,Zm=vr,Mz=nn.f,H_=ps,xz=gm,eg=Rz,Nz=Tu,Lz=Lk,Dk=!1,Vi=Nz("meta"),Dz=0,tg=function(e){Mz(e,Vi,{value:{objectID:"O"+Dz++,weakData:{}}})},jz=function(e,t){if(!Pz(e))return typeof e=="symbol"?e:(typeof e=="string"?"S":"P")+e;if(!Zm(e,Vi)){if(!eg(e))return"F";if(!t)return"E";tg(e)}return e[Vi].objectID},Fz=function(e,t){if(!Zm(e,Vi)){if(!eg(e))return!0;if(!t)return!1;tg(e)}return e[Vi].weakData},Uz=function(e){return Lz&&Dk&&eg(e)&&!Zm(e,Vi)&&tg(e),e},Bz=function(){qz.enable=function(){},Dk=!0;var e=H_.f,t=Oz([].splice),r={};r[Vi]=1,e(r).length&&(H_.f=function(n){for(var i=e(n),a=0,s=i.length;a<s;a++)if(i[a]===Vi){t(i,a,1);break}return i},Iz({target:"Object",stat:!0,forced:!0},{getOwnPropertyNames:xz.f}))},qz=Nk.exports={enable:Bz,fastKey:jz,getWeakData:Fz,onFreeze:Uz};Az[Vi]=!0;var Pf=Nk.exports,zz=Ct,Wz=$t,Gz=wt,V_=uf,Hz=an,Vz=Pf,Kz=Fu,Jz=Pa,Yz=Xt,Xz=ai,op=ar,up=yt,Qz=_f,Zz=Ti,eW=Sf,rg=function(e,t,r){var n=e.indexOf("Map")!==-1,i=e.indexOf("Weak")!==-1,a=n?"set":"add",s=Wz[e],o=s&&s.prototype,u=s,c={},l=function(R){var x=Gz(o[R]);Hz(o,R,R==="add"?function(j){return x(this,j===0?0:j),this}:R==="delete"?function(N){return i&&!op(N)?!1:x(this,N===0?0:N)}:R==="get"?function(j){return i&&!op(j)?void 0:x(this,j===0?0:j)}:R==="has"?function(j){return i&&!op(j)?!1:x(this,j===0?0:j)}:function(j,X){return x(this,j===0?0:j,X),this})},p=V_(e,!Yz(s)||!(i||o.forEach&&!up(function(){new s().entries().next()})));if(p)u=r.getConstructor(t,e,n,a),Vz.enable();else if(V_(e,!0)){var v=new u,m=v[a](i?{}:-0,1)!==v,b=up(function(){v.has(1)}),T=Qz(function(R){new s(R)}),I=!i&&up(function(){for(var R=new s,x=5;x--;)R[a](x,x);return!R.has(-0)});T||(u=t(function(R,x){Jz(R,o);var N=eW(new s,R,u);return Xz(x)||Kz(x,N[a],{that:N,AS_ENTRIES:n}),N}),u.prototype=o,o.constructor=u),(b||I)&&(l("delete"),l("has"),n&&l("get")),(I||m)&&l(a),i&&o.clear&&delete o.clear}return c[e]=u,zz({global:!0,constructor:!0,forced:u!==s},c),Zz(u,e),i||r.setStrong(u,e,n),u},tW=an,Mf=function(e,t,r){for(var n in t)tW(e,n,t[n],r);return e},K_=Oa,rW=Ei,J_=Mf,nW=ea,iW=Pa,aW=ai,sW=Fu,oW=Dm,Ec=wf,uW=mf,Fo=er,Y_=Pf.fastKey,jk=En,X_=jk.set,cp=jk.getterFor,Fk={getConstructor:function(e,t,r,n){var i=e(function(c,l){iW(c,a),X_(c,{type:t,index:K_(null),first:null,last:null,size:0}),Fo||(c.size=0),aW(l)||sW(l,c[n],{that:c,AS_ENTRIES:r})}),a=i.prototype,s=cp(t),o=function(c,l,p){var v=s(c),m=u(c,l),b,T;return m?m.value=p:(v.last=m={index:T=Y_(l,!0),key:l,value:p,previous:b=v.last,next:null,removed:!1},v.first||(v.first=m),b&&(b.next=m),Fo?v.size++:c.size++,T!=="F"&&(v.index[T]=m)),c},u=function(c,l){var p=s(c),v=Y_(l),m;if(v!=="F")return p.index[v];for(m=p.first;m;m=m.next)if(m.key===l)return m};return J_(a,{clear:function(){for(var l=this,p=s(l),v=p.first;v;)v.removed=!0,v.previous&&(v.previous=v.previous.next=null),v=v.next;p.first=p.last=null,p.index=K_(null),Fo?p.size=0:l.size=0},delete:function(c){var l=this,p=s(l),v=u(l,c);if(v){var m=v.next,b=v.previous;delete p.index[v.index],v.removed=!0,b&&(b.next=m),m&&(m.previous=b),p.first===v&&(p.first=m),p.last===v&&(p.last=b),Fo?p.size--:l.size--}return!!v},forEach:function(l){for(var p=s(this),v=nW(l,arguments.length>1?arguments[1]:void 0),m;m=m?m.next:p.first;)for(v(m.value,m.key,this);m&&m.removed;)m=m.previous},has:function(l){return!!u(this,l)}}),J_(a,r?{get:function(l){var p=u(this,l);return p&&p.value},set:function(l,p){return o(this,l===0?0:l,p)}}:{add:function(l){return o(this,l=l===0?0:l,l)}}),Fo&&rW(a,"size",{configurable:!0,get:function(){return s(this).size}}),i},setStrong:function(e,t,r){var n=t+" Iterator",i=cp(t),a=cp(n);oW(e,t,function(s,o){X_(this,{type:n,target:s,state:i(s),kind:o,last:null})},function(){for(var s=a(this),o=s.kind,u=s.last;u&&u.removed;)u=u.previous;return!s.target||!(s.last=u=u?u.next:s.state.first)?(s.target=null,Ec(void 0,!0)):Ec(o==="keys"?u.key:o==="values"?u.value:[u.key,u.value],!1)},r?"entries":"values",!r,!0),uW(t)}},cW=rg,lW=Fk;cW("Map",function(e){return function(){return e(this,arguments.length?arguments[0]:void 0)}},lW);var na={};/*
46
+ */Object.defineProperty(Xm,"__esModule",{value:!0});var V6=_o,K6=$i,J6=Aa,Y6=ms,X6=Qm,Q6=ki,Z6=Ri,ez=zn,tz=gs;function ra(e){return e&&typeof e=="object"&&"default"in e?e:{default:e}}var W_=ra(V6),rz=ra(K6),nz=ra(J6),iz=ra(Y6),Ha=ra(X6),az=ra(Q6),sz=ra(Z6),ji=ra(ez),oz=ra(tz),uz;function Sa(){}Sa.prototype=Object.create(null);function Zt(){Zt.init.call(this)}Zt.EventEmitter=Zt;Zt.usingDomains=!1;Zt.prototype.domain=void 0;Zt.prototype._events=void 0;Zt.prototype._maxListeners=void 0;Zt.defaultMaxListeners=10;Zt.init=function(){this.domain=null,Zt.usingDomains&&uz.active,(!this._events||this._events===Object.getPrototypeOf(this)._events)&&(this._events=new Sa,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};Zt.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||isNaN(t))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=t,this};function Ak(e){return e._maxListeners===void 0?Zt.defaultMaxListeners:e._maxListeners}Zt.prototype.getMaxListeners=function(){return Ak(this)};function cz(e,t,r){if(t)e.call(r);else for(var n=e.length,i=qu(e,n),a=0;a<n;++a)i[a].call(r)}function lz(e,t,r,n){if(t)e.call(r,n);else for(var i=e.length,a=qu(e,i),s=0;s<i;++s)a[s].call(r,n)}function fz(e,t,r,n,i){if(t)e.call(r,n,i);else for(var a=e.length,s=qu(e,a),o=0;o<a;++o)s[o].call(r,n,i)}function dz(e,t,r,n,i,a){if(t)e.call(r,n,i,a);else for(var s=e.length,o=qu(e,s),u=0;u<s;++u)o[u].call(r,n,i,a)}function pz(e,t,r,n){if(t)e.apply(r,n);else for(var i=e.length,a=qu(e,i),s=0;s<i;++s)a[s].apply(r,n)}Zt.prototype.emit=function(t){var r,n,i,a,s,o,u,c=t==="error";if(o=this._events,o)c=c&&o.error==null;else if(!c)return!1;if(u=this.domain,c){if(r=arguments[1],u)r||(r=new Error('Uncaught, unspecified "error" event')),r.domainEmitter=this,r.domain=u,r.domainThrown=!1,u.emit("error",r);else{if(r instanceof Error)throw r;var l=new Error('Uncaught, unspecified "error" event. ('+r+")");throw l.context=r,l}return!1}if(n=o[t],!n)return!1;var p=typeof n=="function";switch(i=arguments.length,i){case 1:cz(n,p,this);break;case 2:lz(n,p,this,arguments[1]);break;case 3:fz(n,p,this,arguments[1],arguments[2]);break;case 4:dz(n,p,this,arguments[1],arguments[2],arguments[3]);break;default:for(a=new Array(i-1),s=1;s<i;s++)a[s-1]=arguments[s];pz(n,p,this,a)}return!0};function Pk(e,t,r,n){var i,a,s;if(typeof r!="function")throw new TypeError('"listener" argument must be a function');if(a=e._events,a?(a.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),a=e._events),s=a[t]):(a=e._events=new Sa,e._eventsCount=0),!s)s=a[t]=r,++e._eventsCount;else if(typeof s=="function"?s=a[t]=n?[r,s]:[s,r]:n?s.unshift(r):s.push(r),!s.warned&&(i=Ak(e),i&&i>0&&s.length>i)){s.warned=!0;var o=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");o.name="MaxListenersExceededWarning",o.emitter=e,o.type=t,o.count=s.length,hz(o)}return e}function hz(e){typeof console.warn=="function"?console.warn(e):console.log(e)}Zt.prototype.addListener=function(t,r){return Pk(this,t,r,!1)};Zt.prototype.on=Zt.prototype.addListener;Zt.prototype.prependListener=function(t,r){return Pk(this,t,r,!0)};function Mk(e,t,r){var n=!1;function i(){e.removeListener(t,i),n||(n=!0,r.apply(e,arguments))}return i.listener=r,i}Zt.prototype.once=function(t,r){if(typeof r!="function")throw new TypeError('"listener" argument must be a function');return this.on(t,Mk(this,t,r)),this};Zt.prototype.prependOnceListener=function(t,r){if(typeof r!="function")throw new TypeError('"listener" argument must be a function');return this.prependListener(t,Mk(this,t,r)),this};Zt.prototype.removeListener=function(t,r){var n,i,a,s,o;if(typeof r!="function")throw new TypeError('"listener" argument must be a function');if(i=this._events,!i)return this;if(n=i[t],!n)return this;if(n===r||n.listener&&n.listener===r)--this._eventsCount===0?this._events=new Sa:(delete i[t],i.removeListener&&this.emit("removeListener",t,n.listener||r));else if(typeof n!="function"){for(a=-1,s=n.length;s-- >0;)if(n[s]===r||n[s].listener&&n[s].listener===r){o=n[s].listener,a=s;break}if(a<0)return this;if(n.length===1){if(n[0]=void 0,--this._eventsCount===0)return this._events=new Sa,this;delete i[t]}else vz(n,a);i.removeListener&&this.emit("removeListener",t,o||r)}return this};Zt.prototype.off=function(e,t){return this.removeListener(e,t)};Zt.prototype.removeAllListeners=function(t){var r,n;if(n=this._events,!n)return this;if(!n.removeListener)return arguments.length===0?(this._events=new Sa,this._eventsCount=0):n[t]&&(--this._eventsCount===0?this._events=new Sa:delete n[t]),this;if(arguments.length===0){for(var i=Object.keys(n),a=0,s;a<i.length;++a)s=i[a],s!=="removeListener"&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=new Sa,this._eventsCount=0,this}if(r=n[t],typeof r=="function")this.removeListener(t,r);else if(r)do this.removeListener(t,r[r.length-1]);while(r[0]);return this};Zt.prototype.listeners=function(t){var r,n,i=this._events;return i?(r=i[t],r?typeof r=="function"?n=[r.listener||r]:n=mz(r):n=[]):n=[],n};Zt.listenerCount=function(e,t){return typeof e.listenerCount=="function"?e.listenerCount(t):xk.call(e,t)};Zt.prototype.listenerCount=xk;function xk(e){var t=this._events;if(t){var r=t[e];if(typeof r=="function")return 1;if(r)return r.length}return 0}Zt.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};function vz(e,t){for(var r=t,n=r+1,i=e.length;n<i;r+=1,n+=1)e[r]=e[n];e.pop()}function qu(e,t){for(var r=new Array(t);t--;)r[t]=e[t];return r}function mz(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}function gz(e){var t=yz();return function(){var n=ji.default(e),i;if(t){var a=ji.default(this).constructor;i=Reflect.construct(n,arguments,a)}else i=n.apply(this,arguments);return sz.default(this,i)}}function yz(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var bz=function(e){az.default(r,e);var t=gz(r);function r(){var n;return rz.default(this,r),n=t.call(this),oz.default(iz.default(n),"eventHistory",new Map),n}return nz.default(r,[{key:"on",value:function(i,a){return Ha.default(ji.default(r.prototype),"on",this).call(this,i,a)}},{key:"once",value:function(i,a){return Ha.default(ji.default(r.prototype),"once",this).call(this,i,a)}},{key:"off",value:function(i,a){return Ha.default(ji.default(r.prototype),"off",this).call(this,i,a)}},{key:"emit",value:function(i){for(var a,s=arguments.length,o=new Array(s>1?s-1:0),u=1;u<s;u++)o[u-1]=arguments[u];return this.eventHistory.set(i,o),(a=Ha.default(ji.default(r.prototype),"emit",this)).call.apply(a,[this,i].concat(o))}},{key:"addListener",value:function(i,a){return Ha.default(ji.default(r.prototype),"addListener",this).call(this,i,a)}},{key:"removeListener",value:function(i,a){return Ha.default(ji.default(r.prototype),"removeListener",this).call(this,i,a)}},{key:"addListenerWithReplay",value:function(i,a){var s=this.eventHistory.get(i);return s!==void 0&&a.apply(void 0,W_.default(s)),this.addListener(i,a)}},{key:"onWithReplay",value:function(i,a){return this.addListenerWithReplay(i,a)}},{key:"onceWithReplay",value:function(i,a){var s=this.eventHistory.get(i);return s!==void 0?(a.apply(void 0,W_.default(s)),this):Ha.default(ji.default(r.prototype),"once",this).call(this,i,a)}}]),r}(Zt);Xm.ReplayEventEmitter=bz;var Bl={exports:{}};Bl.exports;(function(e,t){var r=200,n="__lodash_hash_undefined__",i=1,a=2,s=9007199254740991,o="[object Arguments]",u="[object Array]",c="[object AsyncFunction]",l="[object Boolean]",p="[object Date]",v="[object Error]",m="[object Function]",b="[object GeneratorFunction]",T="[object Map]",I="[object Number]",R="[object Null]",x="[object Object]",N="[object Promise]",j="[object Proxy]",X="[object RegExp]",J="[object Set]",V="[object String]",D="[object Symbol]",te="[object Undefined]",ue="[object WeakMap]",ee="[object ArrayBuffer]",ge="[object DataView]",L="[object Float32Array]",pe="[object Float64Array]",Te="[object Int8Array]",rt="[object Int16Array]",Ke="[object Int32Array]",Se="[object Uint8Array]",ce="[object Uint8ClampedArray]",he="[object Uint16Array]",P="[object Uint32Array]",Ie=/[\\^$.*+?()[\]{}|]/g,qe=/^\[object .+?Constructor\]$/,Ne=/^(?:0|[1-9]\d*)$/,_e={};_e[L]=_e[pe]=_e[Te]=_e[rt]=_e[Ke]=_e[Se]=_e[ce]=_e[he]=_e[P]=!0,_e[o]=_e[u]=_e[ee]=_e[l]=_e[ge]=_e[p]=_e[v]=_e[m]=_e[T]=_e[I]=_e[x]=_e[X]=_e[J]=_e[V]=_e[ue]=!1;var Q=typeof je=="object"&&je&&je.Object===Object&&je,kt=typeof self=="object"&&self&&self.Object===Object&&self,Ce=Q||kt||Function("return this")(),de=t&&!t.nodeType&&t,Rt=de&&!0&&e&&!e.nodeType&&e,Ue=Rt&&Rt.exports===de,Dt=Ue&&Q.process,mt=function(){try{return Dt&&Dt.binding&&Dt.binding("util")}catch{}}(),ke=mt&&mt.isTypedArray;function ft(W,ie){for(var Ee=-1,Ze=W==null?0:W.length,Kt=0,_t=[];++Ee<Ze;){var Jt=W[Ee];ie(Jt,Ee,W)&&(_t[Kt++]=Jt)}return _t}function St(W,ie){for(var Ee=-1,Ze=ie.length,Kt=W.length;++Ee<Ze;)W[Kt+Ee]=ie[Ee];return W}function Oe(W,ie){for(var Ee=-1,Ze=W==null?0:W.length;++Ee<Ze;)if(ie(W[Ee],Ee,W))return!0;return!1}function Bt(W,ie){for(var Ee=-1,Ze=Array(W);++Ee<W;)Ze[Ee]=ie(Ee);return Ze}function vt(W){return function(ie){return W(ie)}}function qt(W,ie){return W.has(ie)}function sr(W,ie){return W==null?void 0:W[ie]}function ze(W){var ie=-1,Ee=Array(W.size);return W.forEach(function(Ze,Kt){Ee[++ie]=[Kt,Ze]}),Ee}function Tr(W,ie){return function(Ee){return W(ie(Ee))}}function mr(W){var ie=-1,Ee=Array(W.size);return W.forEach(function(Ze){Ee[++ie]=Ze}),Ee}var Et=Array.prototype,It=Function.prototype,bt=Object.prototype,ct=Ce["__core-js_shared__"],Ft=It.toString,Pt=bt.hasOwnProperty,cr=function(){var W=/[^.]+$/.exec(ct&&ct.keys&&ct.keys.IE_PROTO||"");return W?"Symbol(src)_1."+W:""}(),Cr=bt.toString,Dr=RegExp("^"+Ft.call(Pt).replace(Ie,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),gr=Ue?Ce.Buffer:void 0,zt=Ce.Symbol,lr=Ce.Uint8Array,ye=bt.propertyIsEnumerable,we=Et.splice,se=zt?zt.toStringTag:void 0,me=Object.getOwnPropertySymbols,le=gr?gr.isBuffer:void 0,be=Tr(Object.keys,Object),$e=kr(Ce,"DataView"),re=kr(Ce,"Map"),ae=kr(Ce,"Promise"),K=kr(Ce,"Set"),oe=kr(Ce,"WeakMap"),Y=kr(Object,"create"),De=k($e),Re=k(re),Je=k(ae),Ge=k(K),He=k(oe),et=zt?zt.prototype:void 0,nt=et?et.valueOf:void 0;function Qe(W){var ie=-1,Ee=W==null?0:W.length;for(this.clear();++ie<Ee;){var Ze=W[ie];this.set(Ze[0],Ze[1])}}function tt(){this.__data__=Y?Y(null):{},this.size=0}function at(W){var ie=this.has(W)&&delete this.__data__[W];return this.size-=ie?1:0,ie}function st(W){var ie=this.__data__;if(Y){var Ee=ie[W];return Ee===n?void 0:Ee}return Pt.call(ie,W)?ie[W]:void 0}function yr(W){var ie=this.__data__;return Y?ie[W]!==void 0:Pt.call(ie,W)}function fr(W,ie){var Ee=this.__data__;return this.size+=this.has(W)?0:1,Ee[W]=Y&&ie===void 0?n:ie,this}Qe.prototype.clear=tt,Qe.prototype.delete=at,Qe.prototype.get=st,Qe.prototype.has=yr,Qe.prototype.set=fr;function dt(W){var ie=-1,Ee=W==null?0:W.length;for(this.clear();++ie<Ee;){var Ze=W[ie];this.set(Ze[0],Ze[1])}}function Gr(){this.__data__=[],this.size=0}function cn(W){var ie=this.__data__,Ee=or(ie,W);if(Ee<0)return!1;var Ze=ie.length-1;return Ee==Ze?ie.pop():we.call(ie,Ee,1),--this.size,!0}function it(W){var ie=this.__data__,Ee=or(ie,W);return Ee<0?void 0:ie[Ee][1]}function Z(W){return or(this.__data__,W)>-1}function xe(W,ie){var Ee=this.__data__,Ze=or(Ee,W);return Ze<0?(++this.size,Ee.push([W,ie])):Ee[Ze][1]=ie,this}dt.prototype.clear=Gr,dt.prototype.delete=cn,dt.prototype.get=it,dt.prototype.has=Z,dt.prototype.set=xe;function Ye(W){var ie=-1,Ee=W==null?0:W.length;for(this.clear();++ie<Ee;){var Ze=W[ie];this.set(Ze[0],Ze[1])}}function Mt(){this.size=0,this.__data__={hash:new Qe,map:new(re||dt),string:new Qe}}function nr(W){var ie=Hn(this,W).delete(W);return this.size-=ie?1:0,ie}function Ot(W){return Hn(this,W).get(W)}function ir(W){return Hn(this,W).has(W)}function Pr(W,ie){var Ee=Hn(this,W),Ze=Ee.size;return Ee.set(W,ie),this.size+=Ee.size==Ze?0:1,this}Ye.prototype.clear=Mt,Ye.prototype.delete=nr,Ye.prototype.get=Ot,Ye.prototype.has=ir,Ye.prototype.set=Pr;function Mr(W){var ie=-1,Ee=W==null?0:W.length;for(this.__data__=new Ye;++ie<Ee;)this.add(W[ie])}function dr(W){return this.__data__.set(W,n),this}function $n(W){return this.__data__.has(W)}Mr.prototype.add=Mr.prototype.push=dr,Mr.prototype.has=$n;function Hr(W){var ie=this.__data__=new dt(W);this.size=ie.size}function oa(){this.__data__=new dt,this.size=0}function ja(W){var ie=this.__data__,Ee=ie.delete(W);return this.size=ie.size,Ee}function Fa(W){return this.__data__.get(W)}function Er(W){return this.__data__.has(W)}function Ua(W,ie){var Ee=this.__data__;if(Ee instanceof dt){var Ze=Ee.__data__;if(!re||Ze.length<r-1)return Ze.push([W,ie]),this.size=++Ee.size,this;Ee=this.__data__=new Ye(Ze)}return Ee.set(W,ie),this.size=Ee.size,this}Hr.prototype.clear=oa,Hr.prototype.delete=ja,Hr.prototype.get=Fa,Hr.prototype.has=Er,Hr.prototype.set=Ua;function ci(W,ie){var Ee=M(W),Ze=!Ee&&q(W),Kt=!Ee&&!Ze&&fe(W),_t=!Ee&&!Ze&&!Kt&&br(W),Jt=Ee||Ze||Kt||_t,ur=Jt?Bt(W.length,String):[],_r=ur.length;for(var lt in W)Pt.call(W,lt)&&!(Jt&&(lt=="length"||Kt&&(lt=="offset"||lt=="parent")||_t&&(lt=="buffer"||lt=="byteLength"||lt=="byteOffset")||bn(lt,_r)))&&ur.push(lt);return ur}function or(W,ie){for(var Ee=W.length;Ee--;)if(E(W[Ee][0],ie))return Ee;return-1}function Ba(W,ie,Ee){var Ze=ie(W);return M(W)?Ze:St(Ze,Ee(W))}function gn(W){return W==null?W===void 0?te:R:se&&se in Object(W)?la(W):$(W)}function Oi(W){return ln(W)&&gn(W)==o}function Ai(W,ie,Ee,Ze,Kt){return W===ie?!0:W==null||ie==null||!ln(W)&&!ln(ie)?W!==W&&ie!==ie:qa(W,ie,Ee,Ze,Ai,Kt)}function qa(W,ie,Ee,Ze,Kt,_t){var Jt=M(W),ur=M(ie),_r=Jt?u:Vr(W),lt=ur?u:Vr(ie);_r=_r==o?x:_r,lt=lt==o?x:lt;var jr=_r==x,Fr=lt==x,pr=_r==lt;if(pr&&fe(W)){if(!fe(ie))return!1;Jt=!0,jr=!1}if(pr&&!jr)return _t||(_t=new Hr),Jt||br(W)?ca(W,ie,Ee,Ze,Kt,_t):Pi(W,ie,_r,Ee,Ze,Kt,_t);if(!(Ee&i)){var Ur=jr&&Pt.call(W,"__wrapped__"),gt=Fr&&Pt.call(ie,"__wrapped__");if(Ur||gt){var In=Ur?W.value():W,O=gt?ie.value():ie;return _t||(_t=new Hr),Kt(In,O,Ee,Ze,_t)}}return pr?(_t||(_t=new Hr),Mi(W,ie,Ee,Ze,Kt,_t)):!1}function yn(W){if(!$r(W)||F(W))return!1;var ie=Be(W)?Dr:qe;return ie.test(k(W))}function At(W){return ln(W)&&ot(W.length)&&!!_e[gn(W)]}function ua(W){if(!z(W))return be(W);var ie=[];for(var Ee in Object(W))Pt.call(W,Ee)&&Ee!="constructor"&&ie.push(Ee);return ie}function ca(W,ie,Ee,Ze,Kt,_t){var Jt=Ee&i,ur=W.length,_r=ie.length;if(ur!=_r&&!(Jt&&_r>ur))return!1;var lt=_t.get(W);if(lt&&_t.get(ie))return lt==ie;var jr=-1,Fr=!0,pr=Ee&a?new Mr:void 0;for(_t.set(W,ie),_t.set(ie,W);++jr<ur;){var Ur=W[jr],gt=ie[jr];if(Ze)var In=Jt?Ze(gt,Ur,jr,ie,W,_t):Ze(Ur,gt,jr,W,ie,_t);if(In!==void 0){if(In)continue;Fr=!1;break}if(pr){if(!Oe(ie,function(O,A){if(!qt(pr,A)&&(Ur===O||Kt(Ur,O,Ee,Ze,_t)))return pr.push(A)})){Fr=!1;break}}else if(!(Ur===gt||Kt(Ur,gt,Ee,Ze,_t))){Fr=!1;break}}return _t.delete(W),_t.delete(ie),Fr}function Pi(W,ie,Ee,Ze,Kt,_t,Jt){switch(Ee){case ge:if(W.byteLength!=ie.byteLength||W.byteOffset!=ie.byteOffset)return!1;W=W.buffer,ie=ie.buffer;case ee:return!(W.byteLength!=ie.byteLength||!_t(new lr(W),new lr(ie)));case l:case p:case I:return E(+W,+ie);case v:return W.name==ie.name&&W.message==ie.message;case X:case V:return W==ie+"";case T:var ur=ze;case J:var _r=Ze&i;if(ur||(ur=mr),W.size!=ie.size&&!_r)return!1;var lt=Jt.get(W);if(lt)return lt==ie;Ze|=a,Jt.set(W,ie);var jr=ca(ur(W),ur(ie),Ze,Kt,_t,Jt);return Jt.delete(W),jr;case D:if(nt)return nt.call(W)==nt.call(ie)}return!1}function Mi(W,ie,Ee,Ze,Kt,_t){var Jt=Ee&i,ur=li(W),_r=ur.length,lt=li(ie),jr=lt.length;if(_r!=jr&&!Jt)return!1;for(var Fr=_r;Fr--;){var pr=ur[Fr];if(!(Jt?pr in ie:Pt.call(ie,pr)))return!1}var Ur=_t.get(W);if(Ur&&_t.get(ie))return Ur==ie;var gt=!0;_t.set(W,ie),_t.set(ie,W);for(var In=Jt;++Fr<_r;){pr=ur[Fr];var O=W[pr],A=ie[pr];if(Ze)var f=Jt?Ze(A,O,pr,ie,W,_t):Ze(O,A,pr,W,ie,_t);if(!(f===void 0?O===A||Kt(O,A,Ee,Ze,_t):f)){gt=!1;break}In||(In=pr=="constructor")}if(gt&&!In){var d=W.constructor,h=ie.constructor;d!=h&&"constructor"in W&&"constructor"in ie&&!(typeof d=="function"&&d instanceof d&&typeof h=="function"&&h instanceof h)&&(gt=!1)}return _t.delete(W),_t.delete(ie),gt}function li(W){return Ba(W,_n,Rr)}function Hn(W,ie){var Ee=W.__data__;return fa(ie)?Ee[typeof ie=="string"?"string":"hash"]:Ee.map}function kr(W,ie){var Ee=sr(W,ie);return yn(Ee)?Ee:void 0}function la(W){var ie=Pt.call(W,se),Ee=W[se];try{W[se]=void 0;var Ze=!0}catch{}var Kt=Cr.call(W);return Ze&&(ie?W[se]=Ee:delete W[se]),Kt}var Rr=me?function(W){return W==null?[]:(W=Object(W),ft(me(W),function(ie){return ye.call(W,ie)}))}:Cs,Vr=gn;($e&&Vr(new $e(new ArrayBuffer(1)))!=ge||re&&Vr(new re)!=T||ae&&Vr(ae.resolve())!=N||K&&Vr(new K)!=J||oe&&Vr(new oe)!=ue)&&(Vr=function(W){var ie=gn(W),Ee=ie==x?W.constructor:void 0,Ze=Ee?k(Ee):"";if(Ze)switch(Ze){case De:return ge;case Re:return T;case Je:return N;case Ge:return J;case He:return ue}return ie});function bn(W,ie){return ie=ie??s,!!ie&&(typeof W=="number"||Ne.test(W))&&W>-1&&W%1==0&&W<ie}function fa(W){var ie=typeof W;return ie=="string"||ie=="number"||ie=="symbol"||ie=="boolean"?W!=="__proto__":W===null}function F(W){return!!cr&&cr in W}function z(W){var ie=W&&W.constructor,Ee=typeof ie=="function"&&ie.prototype||bt;return W===Ee}function $(W){return Cr.call(W)}function k(W){if(W!=null){try{return Ft.call(W)}catch{}try{return W+""}catch{}}return""}function E(W,ie){return W===ie||W!==W&&ie!==ie}var q=Oi(function(){return arguments}())?Oi:function(W){return ln(W)&&Pt.call(W,"callee")&&!ye.call(W,"callee")},M=Array.isArray;function ve(W){return W!=null&&ot(W.length)&&!Be(W)}var fe=le||ko;function Ae(W,ie){return Ai(W,ie)}function Be(W){if(!$r(W))return!1;var ie=gn(W);return ie==m||ie==b||ie==c||ie==j}function ot(W){return typeof W=="number"&&W>-1&&W%1==0&&W<=s}function $r(W){var ie=typeof W;return W!=null&&(ie=="object"||ie=="function")}function ln(W){return W!=null&&typeof W=="object"}var br=ke?vt(ke):At;function _n(W){return ve(W)?ci(W):ua(W)}function Cs(){return[]}function ko(){return!1}e.exports=Ae})(Bl,Bl.exports);var _z=Bl.exports,Nk={exports:{}},wz=yt,Sz=wz(function(){if(typeof ArrayBuffer=="function"){var e=new ArrayBuffer(8);Object.isExtensible(e)&&Object.defineProperty(e,"a",{value:8})}}),Tz=yt,Cz=ar,Ez=wi,G_=Sz,_l=Object.isExtensible,kz=Tz(function(){_l(1)}),Rz=kz||G_?function(t){return!Cz(t)||G_&&Ez(t)==="ArrayBuffer"?!1:_l?_l(t):!0}:_l,$z=yt,Lk=!$z(function(){return Object.isExtensible(Object.preventExtensions({}))}),Iz=Ct,Oz=wt,Az=Eu,Pz=ar,Zm=vr,Mz=nn.f,H_=ps,xz=gm,eg=Rz,Nz=Tu,Lz=Lk,Dk=!1,Vi=Nz("meta"),Dz=0,tg=function(e){Mz(e,Vi,{value:{objectID:"O"+Dz++,weakData:{}}})},jz=function(e,t){if(!Pz(e))return typeof e=="symbol"?e:(typeof e=="string"?"S":"P")+e;if(!Zm(e,Vi)){if(!eg(e))return"F";if(!t)return"E";tg(e)}return e[Vi].objectID},Fz=function(e,t){if(!Zm(e,Vi)){if(!eg(e))return!0;if(!t)return!1;tg(e)}return e[Vi].weakData},Uz=function(e){return Lz&&Dk&&eg(e)&&!Zm(e,Vi)&&tg(e),e},Bz=function(){qz.enable=function(){},Dk=!0;var e=H_.f,t=Oz([].splice),r={};r[Vi]=1,e(r).length&&(H_.f=function(n){for(var i=e(n),a=0,s=i.length;a<s;a++)if(i[a]===Vi){t(i,a,1);break}return i},Iz({target:"Object",stat:!0,forced:!0},{getOwnPropertyNames:xz.f}))},qz=Nk.exports={enable:Bz,fastKey:jz,getWeakData:Fz,onFreeze:Uz};Az[Vi]=!0;var Pf=Nk.exports,zz=Ct,Wz=$t,Gz=wt,V_=uf,Hz=an,Vz=Pf,Kz=Fu,Jz=Pa,Yz=Xt,Xz=ai,op=ar,up=yt,Qz=_f,Zz=Ti,eW=Sf,rg=function(e,t,r){var n=e.indexOf("Map")!==-1,i=e.indexOf("Weak")!==-1,a=n?"set":"add",s=Wz[e],o=s&&s.prototype,u=s,c={},l=function(R){var x=Gz(o[R]);Hz(o,R,R==="add"?function(j){return x(this,j===0?0:j),this}:R==="delete"?function(N){return i&&!op(N)?!1:x(this,N===0?0:N)}:R==="get"?function(j){return i&&!op(j)?void 0:x(this,j===0?0:j)}:R==="has"?function(j){return i&&!op(j)?!1:x(this,j===0?0:j)}:function(j,X){return x(this,j===0?0:j,X),this})},p=V_(e,!Yz(s)||!(i||o.forEach&&!up(function(){new s().entries().next()})));if(p)u=r.getConstructor(t,e,n,a),Vz.enable();else if(V_(e,!0)){var v=new u,m=v[a](i?{}:-0,1)!==v,b=up(function(){v.has(1)}),T=Qz(function(R){new s(R)}),I=!i&&up(function(){for(var R=new s,x=5;x--;)R[a](x,x);return!R.has(-0)});T||(u=t(function(R,x){Jz(R,o);var N=eW(new s,R,u);return Xz(x)||Kz(x,N[a],{that:N,AS_ENTRIES:n}),N}),u.prototype=o,o.constructor=u),(b||I)&&(l("delete"),l("has"),n&&l("get")),(I||m)&&l(a),i&&o.clear&&delete o.clear}return c[e]=u,zz({global:!0,constructor:!0,forced:u!==s},c),Zz(u,e),i||r.setStrong(u,e,n),u},tW=an,Mf=function(e,t,r){for(var n in t)tW(e,n,t[n],r);return e},K_=Oa,rW=Ei,J_=Mf,nW=ea,iW=Pa,aW=ai,sW=Fu,oW=Dm,Ec=wf,uW=mf,Fo=er,Y_=Pf.fastKey,jk=En,X_=jk.set,cp=jk.getterFor,Fk={getConstructor:function(e,t,r,n){var i=e(function(c,l){iW(c,a),X_(c,{type:t,index:K_(null),first:null,last:null,size:0}),Fo||(c.size=0),aW(l)||sW(l,c[n],{that:c,AS_ENTRIES:r})}),a=i.prototype,s=cp(t),o=function(c,l,p){var v=s(c),m=u(c,l),b,T;return m?m.value=p:(v.last=m={index:T=Y_(l,!0),key:l,value:p,previous:b=v.last,next:null,removed:!1},v.first||(v.first=m),b&&(b.next=m),Fo?v.size++:c.size++,T!=="F"&&(v.index[T]=m)),c},u=function(c,l){var p=s(c),v=Y_(l),m;if(v!=="F")return p.index[v];for(m=p.first;m;m=m.next)if(m.key===l)return m};return J_(a,{clear:function(){for(var l=this,p=s(l),v=p.first;v;)v.removed=!0,v.previous&&(v.previous=v.previous.next=null),v=v.next;p.first=p.last=null,p.index=K_(null),Fo?p.size=0:l.size=0},delete:function(c){var l=this,p=s(l),v=u(l,c);if(v){var m=v.next,b=v.previous;delete p.index[v.index],v.removed=!0,b&&(b.next=m),m&&(m.previous=b),p.first===v&&(p.first=m),p.last===v&&(p.last=b),Fo?p.size--:l.size--}return!!v},forEach:function(l){for(var p=s(this),v=nW(l,arguments.length>1?arguments[1]:void 0),m;m=m?m.next:p.first;)for(v(m.value,m.key,this);m&&m.removed;)m=m.previous},has:function(l){return!!u(this,l)}}),J_(a,r?{get:function(l){var p=u(this,l);return p&&p.value},set:function(l,p){return o(this,l===0?0:l,p)}}:{add:function(l){return o(this,l=l===0?0:l,l)}}),Fo&&rW(a,"size",{configurable:!0,get:function(){return s(this).size}}),i},setStrong:function(e,t,r){var n=t+" Iterator",i=cp(t),a=cp(n);oW(e,t,function(s,o){X_(this,{type:n,target:s,state:i(s),kind:o,last:null})},function(){for(var s=a(this),o=s.kind,u=s.last;u&&u.removed;)u=u.previous;return!s.target||!(s.last=u=u?u.next:s.state.first)?(s.target=null,Ec(void 0,!0)):Ec(o==="keys"?u.key:o==="values"?u.value:[u.key,u.value],!1)},r?"entries":"values",!r,!0),uW(t)}},cW=rg,lW=Fk;cW("Map",function(e){return function(){return e(this,arguments.length?arguments[0]:void 0)}},lW);var na={};/*
47
47
  @license
48
48
  Copyright (c) 2016, Twilio, Inc.
49
49
 
@@ -164,8 +164,8 @@ This software includes loglevel under the following license.
164
164
 
165
165
  */(function(e){var t=typeof t<"u"?t:typeof self<"u"?self:typeof window<"u"?window:{};Object.defineProperty(e,"__esModule",{value:!0});var r=Nu,n=Aa,i=ms,a=Qm,s=ki,o=Ri,u=zn,c=$i,l=gs,p=Uu,v=qn,m=sn,b=Ar,T=_8,I=A8,R=Bf,x=na,N=h1;function j(F){return F&&typeof F=="object"&&"default"in F?F:{default:F}}function X(F){if(F&&F.__esModule)return F;var z=Object.create(null);return F&&Object.keys(F).forEach(function($){if($!=="default"){var k=Object.getOwnPropertyDescriptor(F,$);Object.defineProperty(z,$,k.get?k:{enumerable:!0,get:function(){return F[$]}})}}),z.default=F,Object.freeze(z)}var J=j(r),V=j(n),D=j(i),te=j(a),ue=j(s),ee=j(o),ge=j(u),L=j(c),pe=j(l),Te=j(p),rt=j(v),Ke=X(b),Se=X(T),ce=j(R),he=X(N);function P(F,z,$,k){var E=arguments.length,q=E<3?z:k===null?k=Object.getOwnPropertyDescriptor(z,$):k,M;if((typeof Reflect>"u"?"undefined":rt.default(Reflect))==="object"&&typeof Reflect.decorate=="function")q=Reflect.decorate(F,z,$,k);else for(var ve=F.length-1;ve>=0;ve--)(M=F[ve])&&(q=(E<3?M(q):E>3?M(z,$,q):M(z,$))||q);return E>3&&q&&Object.defineProperty(z,$,q),q}function Ie(F,z){if((typeof Reflect>"u"?"undefined":rt.default(Reflect))==="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(F,z)}var qe;function Ne(){}Ne.prototype=Object.create(null);function _e(){_e.init.call(this)}_e.EventEmitter=_e,_e.usingDomains=!1,_e.prototype.domain=void 0,_e.prototype._events=void 0,_e.prototype._maxListeners=void 0,_e.defaultMaxListeners=10,_e.init=function(){this.domain=null,_e.usingDomains&&qe.active,(!this._events||this._events===Object.getPrototypeOf(this)._events)&&(this._events=new Ne,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},_e.prototype.setMaxListeners=function(z){if(typeof z!="number"||z<0||isNaN(z))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=z,this};function Q(F){return F._maxListeners===void 0?_e.defaultMaxListeners:F._maxListeners}_e.prototype.getMaxListeners=function(){return Q(this)};function kt(F,z,$){if(z)F.call($);else for(var k=F.length,E=Oe(F,k),q=0;q<k;++q)E[q].call($)}function Ce(F,z,$,k){if(z)F.call($,k);else for(var E=F.length,q=Oe(F,E),M=0;M<E;++M)q[M].call($,k)}function de(F,z,$,k,E){if(z)F.call($,k,E);else for(var q=F.length,M=Oe(F,q),ve=0;ve<q;++ve)M[ve].call($,k,E)}function Rt(F,z,$,k,E,q){if(z)F.call($,k,E,q);else for(var M=F.length,ve=Oe(F,M),fe=0;fe<M;++fe)ve[fe].call($,k,E,q)}function Ue(F,z,$,k){if(z)F.apply($,k);else for(var E=F.length,q=Oe(F,E),M=0;M<E;++M)q[M].apply($,k)}_e.prototype.emit=function(z){var $,k,E,q,M,ve,fe,Ae=z==="error";if(ve=this._events,ve)Ae=Ae&&ve.error==null;else if(!Ae)return!1;if(fe=this.domain,Ae){if($=arguments[1],fe)$||($=new Error('Uncaught, unspecified "error" event')),$.domainEmitter=this,$.domain=fe,$.domainThrown=!1,fe.emit("error",$);else{if($ instanceof Error)throw $;var Be=new Error('Uncaught, unspecified "error" event. ('+$+")");throw Be.context=$,Be}return!1}if(k=ve[z],!k)return!1;var ot=typeof k=="function";switch(E=arguments.length,E){case 1:kt(k,ot,this);break;case 2:Ce(k,ot,this,arguments[1]);break;case 3:de(k,ot,this,arguments[1],arguments[2]);break;case 4:Rt(k,ot,this,arguments[1],arguments[2],arguments[3]);break;default:for(q=new Array(E-1),M=1;M<E;M++)q[M-1]=arguments[M];Ue(k,ot,this,q)}return!0};function Dt(F,z,$,k){var E,q,M;if(typeof $!="function")throw new TypeError('"listener" argument must be a function');if(q=F._events,q?(q.newListener&&(F.emit("newListener",z,$.listener?$.listener:$),q=F._events),M=q[z]):(q=F._events=new Ne,F._eventsCount=0),!M)M=q[z]=$,++F._eventsCount;else if(typeof M=="function"?M=q[z]=k?[$,M]:[M,$]:k?M.unshift($):M.push($),!M.warned&&(E=Q(F),E&&E>0&&M.length>E)){M.warned=!0;var ve=new Error("Possible EventEmitter memory leak detected. "+M.length+" "+z+" listeners added. Use emitter.setMaxListeners() to increase limit");ve.name="MaxListenersExceededWarning",ve.emitter=F,ve.type=z,ve.count=M.length,mt(ve)}return F}function mt(F){typeof console.warn=="function"?console.warn(F):console.log(F)}_e.prototype.addListener=function(z,$){return Dt(this,z,$,!1)},_e.prototype.on=_e.prototype.addListener,_e.prototype.prependListener=function(z,$){return Dt(this,z,$,!0)};function ke(F,z,$){var k=!1;function E(){F.removeListener(z,E),k||(k=!0,$.apply(F,arguments))}return E.listener=$,E}_e.prototype.once=function(z,$){if(typeof $!="function")throw new TypeError('"listener" argument must be a function');return this.on(z,ke(this,z,$)),this},_e.prototype.prependOnceListener=function(z,$){if(typeof $!="function")throw new TypeError('"listener" argument must be a function');return this.prependListener(z,ke(this,z,$)),this},_e.prototype.removeListener=function(z,$){var k,E,q,M,ve;if(typeof $!="function")throw new TypeError('"listener" argument must be a function');if(E=this._events,!E)return this;if(k=E[z],!k)return this;if(k===$||k.listener&&k.listener===$)--this._eventsCount===0?this._events=new Ne:(delete E[z],E.removeListener&&this.emit("removeListener",z,k.listener||$));else if(typeof k!="function"){for(q=-1,M=k.length;M-- >0;)if(k[M]===$||k[M].listener&&k[M].listener===$){ve=k[M].listener,q=M;break}if(q<0)return this;if(k.length===1){if(k[0]=void 0,--this._eventsCount===0)return this._events=new Ne,this;delete E[z]}else St(k,q);E.removeListener&&this.emit("removeListener",z,ve||$)}return this},_e.prototype.off=function(F,z){return this.removeListener(F,z)},_e.prototype.removeAllListeners=function(z){var $,k;if(k=this._events,!k)return this;if(!k.removeListener)return arguments.length===0?(this._events=new Ne,this._eventsCount=0):k[z]&&(--this._eventsCount===0?this._events=new Ne:delete k[z]),this;if(arguments.length===0){for(var E=Object.keys(k),q=0,M;q<E.length;++q)M=E[q],M!=="removeListener"&&this.removeAllListeners(M);return this.removeAllListeners("removeListener"),this._events=new Ne,this._eventsCount=0,this}if($=k[z],typeof $=="function")this.removeListener(z,$);else if($)do this.removeListener(z,$[$.length-1]);while($[0]);return this},_e.prototype.listeners=function(z){var $,k,E=this._events;return E?($=E[z],$?typeof $=="function"?k=[$.listener||$]:k=Bt($):k=[]):k=[],k},_e.listenerCount=function(F,z){return typeof F.listenerCount=="function"?F.listenerCount(z):ft.call(F,z)},_e.prototype.listenerCount=ft;function ft(F){var z=this._events;if(z){var $=z[F];if(typeof $=="function")return 1;if($)return $.length}return 0}_e.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};function St(F,z){for(var $=z,k=$+1,E=F.length;k<E;$+=1,k+=1)F[$]=F[k];F.pop()}function Oe(F,z){for(var $=new Array(z);z--;)$[z]=F[z];return $}function Bt(F){for(var z=new Array(F.length),$=0;$<z.length;++$)z[$]=F[$].listener||F[$];return z}var vt=Ke.getLogger("twilsock");function qt(F,z){return["".concat(new Date().toISOString()," Twilsock ").concat(F,":")].concat(Array.from(z))}var sr=function(){function F(z){L.default(this,F),pe.default(this,"prefix",""),this.prefix=z!=null&&z.length>0?" "+z+":":""}return V.default(F,[{key:"setLevel",value:function($){vt.setLevel($)}},{key:"trace",value:function(){for(var $=arguments.length,k=new Array($),E=0;E<$;E++)k[E]=arguments[E];vt.trace.apply(null,qt("T",k))}},{key:"debug",value:function(){for(var $=arguments.length,k=new Array($),E=0;E<$;E++)k[E]=arguments[E];vt.debug.apply(null,qt("D",k))}},{key:"info",value:function(){for(var $=arguments.length,k=new Array($),E=0;E<$;E++)k[E]=arguments[E];vt.info.apply(null,qt("I",k))}},{key:"warn",value:function(){for(var $=arguments.length,k=new Array($),E=0;E<$;E++)k[E]=arguments[E];vt.warn.apply(null,qt("W",k))}},{key:"error",value:function(){for(var $=arguments.length,k=new Array($),E=0;E<$;E++)k[E]=arguments[E];vt.error.apply(null,qt("E",k))}}],[{key:"setLevel",value:function($){vt.setLevel($)}},{key:"trace",value:function(){for(var $=arguments.length,k=new Array($),E=0;E<$;E++)k[E]=arguments[E];vt.trace.apply(null,qt("T",k))}},{key:"debug",value:function(){for(var $=arguments.length,k=new Array($),E=0;E<$;E++)k[E]=arguments[E];vt.debug.apply(null,qt("D",k))}},{key:"info",value:function(){for(var $=arguments.length,k=new Array($),E=0;E<$;E++)k[E]=arguments[E];vt.info.apply(null,qt("I",k))}},{key:"warn",value:function(){for(var $=arguments.length,k=new Array($),E=0;E<$;E++)k[E]=arguments[E];vt.warn.apply(null,qt("W",k))}},{key:"error",value:function(){for(var $=arguments.length,k=new Array($),E=0;E<$;E++)k[E]=arguments[E];vt.error.apply(null,qt("E",k))}}]),F}(),ze=new sr(""),Tr="0.12.2",mr=function(){function F(z,$,k){L.default(this,F),pe.default(this,"confirmedCapabilities",new Set),this.activeGrant=$,this._token=z;var E=k.region||"us1",q="wss://tsock.".concat(E,".twilio.com/v3/wsconnect"),M=k.twilsock||k.Twilsock||{};this.url=M.uri||q,this._continuationToken=k.continuationToken?k.continuationToken:null,this.logLevel=k.logLevel?k.logLevel:"error",this.retryPolicy=k.retryPolicy?k.retryPolicy:{min:1*1e3,max:2*60*1e3,randomness:.2},this.clientMetadata=k.clientMetadata?k.clientMetadata:{},this.clientMetadata.ver=Tr,this.initRegistrations=k.initRegistrations?k.initRegistrations:null,this.tweaks=k.tweaks?k.tweaks:null}return V.default(F,[{key:"token",get:function(){return this._token}},{key:"continuationToken",get:function(){return this._continuationToken}},{key:"updateToken",value:function($){this._token=$}},{key:"updateContinuationToken",value:function($){this._continuationToken=$}}]),F}(),Et=function F(z){L.default(this,F),this.id=z||"TM".concat(I.v4())};function It(F){var z=bt();return function(){var k=ge.default(F),E;if(z){var q=ge.default(this).constructor;E=Reflect.construct(k,arguments,q)}else E=k.apply(this,arguments);return ee.default(this,E)}}function bt(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var ct=function(F){ue.default($,F);var z=It($);function $(k,E,q,M,ve){var fe;return L.default(this,$),fe=z.call(this),pe.default(D.default(fe),"method","init"),fe.token=k,fe.continuation_token=E,fe.metadata=q,fe.registrations=M,fe.tweaks=ve,fe.capabilities=["client_update","offline_storage","telemetry.v1"],fe}return $}(Et);function Ft(F){var z=Pt();return function(){var k=ge.default(F),E;if(z){var q=ge.default(this).constructor;E=Reflect.construct(k,arguments,q)}else E=k.apply(this,arguments);return ee.default(this,E)}}function Pt(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var cr=function(F){ue.default($,F);var z=Ft($);function $(k,E,q,M,ve,fe,Ae){var Be;return L.default(this,$),Be=z.call(this,k),Be.continuationToken=E,Be.continuationTokenStatus=M,Be.offlineStorage=ve,Be.initRegistrations=fe,Be.debugInfo=Ae,Be.confirmedCapabilities=q,Be}return $}(Et);function Cr(F){var z=Dr();return function(){var k=ge.default(F),E;if(z){var q=ge.default(this).constructor;E=Reflect.construct(k,arguments,q)}else E=k.apply(this,arguments);return ee.default(this,E)}}function Dr(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var gr=function(F){ue.default($,F);var z=Cr($);function $(k){var E;return L.default(this,$),E=z.call(this),pe.default(D.default(E),"method","update"),E.token=k,E}return $}(Et);function zt(F){var z=lr();return function(){var k=ge.default(F),E;if(z){var q=ge.default(this).constructor;E=Reflect.construct(k,arguments,q)}else E=k.apply(this,arguments);return ee.default(this,E)}}function lr(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var ye=function(F){ue.default($,F);var z=zt($);function $(k,E,q){var M;return L.default(this,$),M=z.call(this),pe.default(D.default(M),"method","message"),M.active_grant=k,M.payload_type=E,M.http_request=q,M}return $}(Et);function we(F){var z=se();return function(){var k=ge.default(F),E;if(z){var q=ge.default(this).constructor;E=Reflect.construct(k,arguments,q)}else E=k.apply(this,arguments);return ee.default(this,E)}}function se(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var me=function(F){ue.default($,F);var z=we($);function $(k){var E;return L.default(this,$),E=z.call(this,k),pe.default(D.default(E),"method","reply"),pe.default(D.default(E),"payload_type","application/json"),pe.default(D.default(E),"status",{code:200,status:"OK"}),E}return $}(Et);function le(F){var z=be();return function(){var k=ge.default(F),E;if(z){var q=ge.default(this).constructor;E=Reflect.construct(k,arguments,q)}else E=k.apply(this,arguments);return ee.default(this,E)}}function be(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var $e=function(F){ue.default($,F);var z=le($);function $(){var k;return L.default(this,$),k=z.call(this),pe.default(D.default(k),"method","close"),k}return $}(Et);function re(F){var z=ae();return function(){var k=ge.default(F),E;if(z){var q=ge.default(this).constructor;E=Reflect.construct(k,arguments,q)}else E=k.apply(this,arguments);return ee.default(this,E)}}function ae(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var K=function F(z,$,k,E,q,M){L.default(this,F),this.start=z,this.end=$,this.title=k,this.details=E,this.id=q,this.type=M},oe=function(F){ue.default($,F);var z=re($);function $(k){var E;return L.default(this,$),E=z.call(this),pe.default(D.default(E),"method","telemetry.v1"),E.events=k,E}return $}(Et);function Y(F){var z=encodeURIComponent(F),$=z.replace(/%([0-9A-F]{2})/g,function(k,E){return String.fromCharCode(+("0x"+E))});return $.length}function De(F){var z=encodeURIComponent(F),$=z.replace(/%([0-9A-F]{2})/g,function(E,q){return String.fromCharCode(+("0x"+q))}),k=new Uint8Array($.length);return Array.prototype.forEach.call($,function(E,q){k[q]=E.charCodeAt(0)}),k}function Re(F){var z=Array.prototype.map.call(F,function(k){return String.fromCharCode(k)}).join(""),$=z.replace(/(.)/g,function(k,E){var q=E.charCodeAt(0).toString(16).toUpperCase();return q.length<2&&(q="0"+q),"%"+q});return decodeURIComponent($)}function Je(F){return JSON.parse(Re(F))}function Ge(F){for(var z="",$=0;$<F.length;++$){var k=String.fromCharCode(F[$]);if(z+=k,k==="\r"){$+=2;break}}var E=z.split(" ");return{size:$,protocol:E[0],version:E[1],headerSize:Number(E[2])}}var He=function(){function F(){L.default(this,F)}return V.default(F,null,[{key:"parse",value:function($){var k=2,E=new Uint8Array($),q=Ge(E);if(q.protocol!=="TWILSOCK"||q.version!=="V3.0")return ze.error("unsupported protocol: ".concat(q.protocol," ver ").concat(q.version)),null;var M;try{M=Je(E.subarray(q.size,q.size+q.headerSize))}catch(Be){return ze.error("failed to parse message header",Be,$),null}ze.debug("message received: ",M.method),ze.trace("message received: ",M);var ve;if(M.payload_size>0){var fe=k+q.size+q.headerSize,Ae=M.payload_size;if(!M.hasOwnProperty("payload_type")||M.payload_type.indexOf("application/json")===0)try{ve=Je(E.subarray(fe,fe+Ae))}catch(Be){return ze.error("failed to parse message body",Be,$),null}else M.payload_type.indexOf("text/plain")===0&&(ve=Re(E.subarray(fe,fe+Ae)))}return{method:M.method,header:M,payload:ve}}},{key:"createPacket",value:function($){var k=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"";$.payload_size=Y(k);var E=JSON.stringify($),q="TWILSOCK V3.0 "+Y(E);ze.debug("send request:",q+E+k);var M=De(q+`\r
166
166
  `+E+`\r
167
- `+k);return M.buffer}}]),F}();function et(F){var z=nt();return function(){var k=ge.default(F),E;if(z){var q=ge.default(this).constructor;E=Reflect.construct(k,arguments,q)}else E=k.apply(this,arguments);return ee.default(this,E)}}function nt(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var Qe=function(F){ue.default($,F);var z=et($);function $(k){return L.default(this,$),z.call(this,k)}return $}(ce.default(Error));function tt(F){var z=at();return function(){var k=ge.default(F),E;if(z){var q=ge.default(this).constructor;E=Reflect.construct(k,arguments,q)}else E=k.apply(this,arguments);return ee.default(this,E)}}function at(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var st=function(F){ue.default($,F);var z=tt($);function $(k,E){var q;return L.default(this,$),q=z.call(this,k),q.reply=E,q}return $}(Qe);function yr(F,z){var $=Object.keys(F);if(Object.getOwnPropertySymbols){var k=Object.getOwnPropertySymbols(F);z&&(k=k.filter(function(E){return Object.getOwnPropertyDescriptor(F,E).enumerable})),$.push.apply($,k)}return $}function fr(F){for(var z=1;z<arguments.length;z++){var $=arguments[z]!=null?arguments[z]:{};z%2?yr(Object($),!0).forEach(function(k){pe.default(F,k,$[k])}):Object.getOwnPropertyDescriptors?Object.defineProperties(F,Object.getOwnPropertyDescriptors($)):yr(Object($)).forEach(function(k){Object.defineProperty(F,k,Object.getOwnPropertyDescriptor($,k))})}return F}function dt(F){var z=Wr();return function(){var k=ge.default(F),E;if(z){var q=ge.default(this).constructor;E=Reflect.construct(k,arguments,q)}else E=k.apply(this,arguments);return ee.default(this,E)}}function Wr(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var cn=function(F){ue.default($,F);var z=dt($);function $(k){var E;return L.default(this,$),E=z.call(this),pe.default(D.default(E),"newBackoff",null),pe.default(D.default(E),"usedBackoff",null),pe.default(D.default(E),"retrier",null),E.options=k?fr({},k):{},E}return V.default($,[{key:"inProgress",get:function(){return!!this.retrier}},{key:"start",value:function(){if(this.inProgress)throw new Error("Already waiting for next attempt, call finishAttempt(success : boolean) to finish it");this.createRetrier()}},{key:"stop",value:function(){this.cleanRetrier(),this.newBackoff=null,this.usedBackoff=null}},{key:"modifyBackoff",value:function(E){this.newBackoff=E}},{key:"attemptFailed",value:function(){if(!this.inProgress)throw new Error("No attempt is in progress");if(this.newBackoff){var E=!this.usedBackoff||this.usedBackoff<this.newBackoff;if(E)this.createRetrier();else{var q;(q=this.retrier)===null||q===void 0||q.failed(new Error)}}else{var M;(M=this.retrier)===null||M===void 0||M.failed(new Error)}}},{key:"cancel",value:function(){var E;(E=this.retrier)===null||E===void 0||E.cancel()}},{key:"cleanRetrier",value:function(){var E,q;(E=this.retrier)===null||E===void 0||E.removeAllListeners(),(q=this.retrier)===null||q===void 0||q.cancel(),this.retrier=null}},{key:"getRetryPolicy",value:function(){var E=fr({},this.options);return this.newBackoff&&(E.min=this.newBackoff,E.max=this.options.max&&this.options.max>this.newBackoff?this.options.max:this.newBackoff),E.maxAttemptsCount=this.options.maxAttemptsCount?this.options.maxAttemptsCount+1:void 0,E}},{key:"createRetrier",value:function(){var E=this;this.cleanRetrier();var q=this.getRetryPolicy();this.retrier=new x.Retrier(q),this.retrier.once("attempt",function(){var M,ve;(M=E.retrier)===null||M===void 0||M.on("attempt",function(){return E.emit("attempt")}),(ve=E.retrier)===null||ve===void 0||ve.failed(new Error("Skipping first attempt"))}),this.retrier.on("failed",function(M){return E.emit("failed",M)}),this.usedBackoff=this.newBackoff,this.newBackoff=null,this.retrier.start()}}]),$}(_e);function it(F){var z=Z();return function(){var k=ge.default(F),E;if(z){var q=ge.default(this).constructor;E=Reflect.construct(k,arguments,q)}else E=k.apply(this,arguments);return ee.default(this,E)}}function Z(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var xe=3e3;function Ye(F){setTimeout(F,0)}var Mt=function(F){ue.default($,F);var z=it($);function $(k,E,q){var M;L.default(this,$),M=z.call(this),pe.default(D.default(M),"disconnectingTimer",null),pe.default(D.default(M),"disconnectedPromiseResolve",null),pe.default(D.default(M),"terminalStates",["disconnected","rejected"]),pe.default(D.default(M),"tokenExpiredSasCode",20104),pe.default(D.default(M),"terminationReason","Connection is not initialized"),M.websocket=k,M.websocket.on("connected",function(){return M.fsm.socketConnected()}),M.websocket.on("disconnected",function(){return M.fsm.socketClosed()}),M.websocket.on("message",function(fe){return M.onIncomingMessage(fe)}),M.websocket.on("socketError",function(fe){return M.emit("connectionError",{terminal:!1,message:"Socket error: ".concat(fe.message),httpStatusCode:null,errorCode:null})}),M.transport=E,M.config=q,M.retrier=new cn(q.retryPolicy),M.retrier.on("attempt",function(){return M.retry()}),M.retrier.on("failed",function(fe){ze.warn("Retrying failed: ".concat(fe.message)),M.disconnect()}),typeof window<"u"&&typeof window.addEventListener<"u"&&(window.addEventListener("online",function(){ze.debug("Browser reported connectivity state: online"),M.resetBackoff(),M.fsm.systemOnline()}),window.addEventListener("offline",function(){ze.debug("Browser reported connectivity state: offline"),M.websocket.close(),M.fsm.socketClosed()}));var ve=Se.factory({init:"disconnected",transitions:[{name:"userConnect",from:["disconnected","rejected"],to:"connecting"},{name:"userConnect",from:["connecting","connected"]},{name:"userDisconnect",from:["connecting","initialising","connected","updating","retrying","rejected","waitSocketClosed","waitOffloadSocketClosed"],to:"disconnecting"},{name:"userRetry",from:["retrying"],to:"connecting"},{name:"socketConnected",from:["connecting"],to:"initialising"},{name:"socketClosed",from:["connecting","initialising","connected","updating","error","waitOffloadSocketClosed"],to:"retrying"},{name:"socketClosed",from:["disconnecting"],to:"disconnected"},{name:"socketClosed",from:["waitSocketClosed"],to:"disconnected"},{name:"socketClosed",from:["rejected"],to:"rejected"},{name:"initSuccess",from:["initialising"],to:"connected"},{name:"initError",from:["initialising"],to:"error"},{name:"tokenRejected",from:["initialising","updating"],to:"rejected"},{name:"protocolError",from:["initialising","connected","updating"],to:"error"},{name:"receiveClose",from:["initialising","connected","updating"],to:"waitSocketClosed"},{name:"receiveOffload",from:["initialising","connected","updating"],to:"waitOffloadSocketClosed"},{name:"unsupportedProtocol",from:["initialising","connected","updating"],to:"unsupported"},{name:"receiveFatalClose",from:["initialising","connected","updating"],to:"unsupported"},{name:"userUpdateToken",from:["disconnected","rejected","connecting","retrying"],to:"connecting"},{name:"userUpdateToken",from:["connected"],to:"updating"},{name:"updateSuccess",from:["updating"],to:"connected"},{name:"updateError",from:["updating"],to:"error"},{name:"userSend",from:["connected"],to:"connected"},{name:"systemOnline",from:["retrying"],to:"connecting"}],methods:{onConnecting:function(){M.setupSocket(),M.emit("connecting")},onEnterInitialising:function(){M.sendInit()},onLeaveInitialising:function(){M.cancelInit()},onEnterUpdating:function(){M.sendUpdate()},onLeaveUpdating:function(){M.cancelUpdate()},onEnterRetrying:function(){M.initRetry(),M.emit("connecting")},onEnterConnected:function(){M.resetBackoff(),M.onConnected()},onUserUpdateToken:function(){M.resetBackoff()},onTokenRejected:function(){M.resetBackoff(),M.closeSocket(!0),M.finalizeSocket()},onUserDisconnect:function(){M.closeSocket(!0)},onEnterDisconnecting:function(){M.startDisconnectTimer()},onLeaveDisconnecting:function(){M.cancelDisconnectTimer()},onEnterWaitSocketClosed:function(){M.startDisconnectTimer()},onLeaveWaitSocketClosed:function(){M.cancelDisconnectTimer()},onEnterWaitOffloadSocketClosed:function(){M.startDisconnectTimer()},onLeaveWaitOffloadSocketClosed:function(){M.cancelDisconnectTimer()},onDisconnected:function(){M.resetBackoff(),M.finalizeSocket()},onReceiveClose:function(){M.onCloseReceived()},onReceiveOffload:function(Ae,Be){ze.debug("onreceiveoffload: ",Be),M.modifyBackoff(Be.body),M.onCloseReceived()},onUnsupported:function(){M.closeSocket(!0),M.finalizeSocket()},onError:function(Ae,Be){M.closeSocket(Be),M.finalizeSocket()},onEnterState:function(Ae){Ae.from!=="none"&&M.changeState(Ae)},onInvalidTransition:function(Ae,Be,ot){ze.warn("FSM: unexpected transition",Be,ot)}}});return M.fsm=new ve,M}return V.default($,[{key:"changeState",value:function(E){ze.debug("FSM: ".concat(E.transition,": ").concat(E.from," --> ").concat(E.to)),this.lastEmittedState!==this.state&&(this.lastEmittedState=this.state,this.emit("stateChanged",this.state))}},{key:"resetBackoff",value:function(){ze.trace("resetBackoff"),this.retrier.stop()}},{key:"modifyBackoff",value:function(E){ze.trace("modifyBackoff",E);var q=E?E.backoff_policy:null;q&&typeof q.reconnect_min_ms=="number"&&this.retrier.modifyBackoff(q.reconnect_min_ms)}},{key:"startDisconnectTimer",value:function(){var E=this;ze.trace("startDisconnectTimer"),this.disconnectingTimer&&(clearTimeout(this.disconnectingTimer),this.disconnectingTimer=null),this.disconnectingTimer=setTimeout(function(){ze.debug("disconnecting is timed out"),E.closeSocket(!0)},xe)}},{key:"cancelDisconnectTimer",value:function(){ze.trace("cancelDisconnectTimer"),this.disconnectingTimer&&(clearTimeout(this.disconnectingTimer),this.disconnectingTimer=null)}},{key:"isConnected",get:function(){return this.state==="connected"&&this.websocket.isConnected}},{key:"state",get:function(){switch(this.fsm.state){case"connecting":case"initialising":case"retrying":case"error":return"connecting";case"updating":case"connected":return"connected";case"rejected":return"denied";case"disconnecting":case"waitSocketClosed":case"waitOffloadSocketClosed":return"disconnecting";case"disconnected":default:return"disconnected"}}},{key:"initRetry",value:function(){ze.debug("initRetry"),this.retrier.inProgress?this.retrier.attemptFailed():this.retrier.start()}},{key:"retry",value:function(){this.fsm.state!="connecting"?(ze.trace("retry"),this.websocket.close(),this.fsm.userRetry()):ze.trace("can retry as already connecting")}},{key:"onConnected",value:function(){this.emit("connected")}},{key:"finalizeSocket",value:function(){ze.trace("finalizeSocket"),this.websocket.close(),this.emit("disconnected"),this.disconnectedPromiseResolve&&(this.disconnectedPromiseResolve(),this.disconnectedPromiseResolve=null)}},{key:"setupSocket",value:function(){ze.trace("setupSocket:",this.config.token),this.emit("beforeConnect"),this.websocket.connect()}},{key:"onIncomingMessage",value:function(E){var q=He.parse(E);if(q){var M=q.method,ve=q.header,fe=q.payload;if(M!=="reply"&&this.confirmReceiving(ve),M==="notification")this.emit("message",ve.message_type,fe);else if(ve.method==="reply")this.transport.processReply({id:ve.id,status:ve.status,header:ve,body:fe});else if(ve.method==="client_update")ve.client_update_type==="token_about_to_expire"&&this.emit("tokenAboutToExpire");else if(ve.method==="close")if(ve.status.code===308)ze.debug("Connection has been offloaded"),this.fsm.receiveOffload({status:ve.status.status,body:fe});else if(ve.status.code===406){var Ae="Server closed connection because can't parse protocol: ".concat(JSON.stringify(ve.status));this.emitReplyConnectionError(Ae,ve,!0),ze.error(Ae),this.fsm.receiveFatalClose()}else ve.status.code===417?(ze.error("Server closed connection because can't parse client reply: ".concat(JSON.stringify(ve.status))),this.fsm.receiveFatalClose(ve.status.status)):ve.status.code===410?(ze.warn("Server closed connection: ".concat(JSON.stringify(ve.status))),this.fsm.receiveClose(ve.status.status),this.emit("tokenExpired")):ve.status.code===401?(ze.error("Server closed connection: ".concat(JSON.stringify(ve.status))),this.fsm.receiveClose(ve.status.status)):(ze.warn("unexpected message: ",ve.status),this.fsm.receiveOffload({status:ve.status.status,body:null}))}}},{key:"sendInit",value:function(){var k=J.default(Te.default.mark(function q(){var M,ve;return Te.default.wrap(function(Ae){for(;;)switch(Ae.prev=Ae.next){case 0:return ze.trace("sendInit"),Ae.prev=1,this.emit("beforeSendInit"),Ae.next=5,this.transport.sendInit();case 5:M=Ae.sent,this.config.updateContinuationToken(M.continuationToken),this.config.confirmedCapabilities=M.confirmedCapabilities,this.fsm.initSuccess(M),this.emit("initialized",M),this.emit("tokenUpdated"),Ae.next=17;break;case 13:Ae.prev=13,Ae.t0=Ae.catch(1),Ae.t0 instanceof st?(ve=!1,ze.warn("Init rejected by server: ".concat(JSON.stringify(Ae.t0.reply.status))),this.emit("sendInitFailed"),Ae.t0.reply.status.code===401||Ae.t0.reply.status.code===403?(ve=!0,this.fsm.tokenRejected(Ae.t0.reply.status),Ae.t0.reply.status.errorCode===this.tokenExpiredSasCode&&this.emit("tokenExpired")):Ae.t0.reply.status.code===429?(this.modifyBackoff(Ae.t0.reply.body),this.fsm.initError(!0)):Ae.t0.reply.status.code===500?this.fsm.initError(!1):this.fsm.initError(!0),this.emitReplyConnectionError(Ae.t0.message,Ae.t0.reply,ve)):(this.terminationReason=Ae.t0.message,this.emit("connectionError",{terminal:!0,message:"Unknown error during connection initialisation: ".concat(Ae.t0.message,`
168
- `).concat(JSON.stringify(Ae.t0,null,2)),httpStatusCode:null,errorCode:null}),this.fsm.initError(!0)),this.emit("tokenUpdated",Ae.t0);case 17:case"end":return Ae.stop()}},q,this,[[1,13]])}));function E(){return k.apply(this,arguments)}return E}()},{key:"sendUpdate",value:function(){var k=J.default(Te.default.mark(function q(){var M,ve,fe;return Te.default.wrap(function(Be){for(;;)switch(Be.prev=Be.next){case 0:return ze.trace("sendUpdate"),M=new gr(this.config.token),Be.prev=2,Be.next=5,this.transport.sendWithReply(M);case 5:ve=Be.sent,this.fsm.updateSuccess(ve.body),this.emit("tokenUpdated"),Be.next=14;break;case 10:Be.prev=10,Be.t0=Be.catch(2),Be.t0 instanceof st?(fe=!1,ze.warn("Token update rejected by server: ".concat(JSON.stringify(Be.t0.reply.status))),Be.t0.reply.status.code===401||Be.t0.reply.status.code===403?(fe=!0,this.fsm.tokenRejected(Be.t0.reply.status),Be.t0.reply.status.errorCode===this.tokenExpiredSasCode&&this.emit("tokenExpired")):Be.t0.reply.status.code===429?(this.modifyBackoff(Be.t0.reply.body),this.fsm.updateError(Be.t0.reply.status)):this.fsm.updateError(Be.t0.reply.status),this.emitReplyConnectionError(Be.t0.message,Be.t0.reply,fe)):(this.emit("error",!1,Be.t0.message,null,null),this.fsm.updateError(Be.t0)),this.emit("tokenUpdated",Be.t0);case 14:case"end":return Be.stop()}},q,this,[[2,10]])}));function E(){return k.apply(this,arguments)}return E}()},{key:"emitReplyConnectionError",value:function(E,q,M){var ve=q.status&&q.status.description?q.status.description:E,fe=q.status.code,Ae=q.status&&q.status.errorCode?q.status.errorCode:null;M&&(this.terminationReason=ve),this.emit("connectionError",{terminal:M,message:"Connection error: ".concat(ve),httpStatusCode:fe,errorCode:Ae})}},{key:"cancelInit",value:function(){ze.trace("cancelInit")}},{key:"cancelUpdate",value:function(){ze.trace("cancelUpdate")}},{key:"confirmReceiving",value:function(E){ze.trace("confirmReceiving");try{this.transport.send(new me(E.id))}catch(q){ze.debug("failed to confirm packet receiving",q)}}},{key:"closeSocket",value:function(E){var q=this;ze.trace("closeSocket (graceful: ".concat(E,")")),E&&this.transport.isConnected&&this.transport.sendClose(),this.websocket.close(),Ye(function(){return q.fsm.socketClosed()})}},{key:"connect",value:function(){ze.trace("connect"),this.fsm.userConnect()}},{key:"disconnect",value:function(){var E=this;return ze.trace("disconnect"),this.fsm.is("disconnected")?Promise.resolve():new Promise(function(q){E.disconnectedPromiseResolve=q,E.fsm.userDisconnect()})}},{key:"updateToken",value:function(E){var q=this;return ze.trace("updateToken:",E),new Promise(function(M,ve){q.once("tokenUpdated",function(fe){fe?ve(fe):M()}),q.fsm.userUpdateToken()})}},{key:"isTerminalState",get:function(){return this.terminalStates.indexOf(this.fsm.state)!==-1}},{key:"getTerminationReason",get:function(){return this.terminationReason}},{key:"onCloseReceived",value:function(){this.websocket.close()}}]),$}(_e),nr=function(){function F(){L.default(this,F)}return V.default(F,null,[{key:"getMetadata",value:function($){var k,E,q,M,ve,fe,Ae,Be,ot=$&&$.clientMetadata?$.clientMetadata:{},$r=["ver","env","envv","os","osv","osa","type","sdk","sdkv","dev","devv","devt","app","appv"],ln={env:(k=he.name)!==null&&k!==void 0?k:"unknown",envv:(E=he.version)!==null&&E!==void 0?E:"unknown",os:(q=(M=he.os)===null||M===void 0?void 0:M.family)!==null&&q!==void 0?q:"unknown",osv:(ve=(fe=he.os)===null||fe===void 0?void 0:fe.version)!==null&&ve!==void 0?ve:"unknown",osa:(Ae=(Be=he.os)===null||Be===void 0?void 0:Be.architecture)!==null&&Ae!==void 0?Ae:"unknown",sdk:"js-default"},br={};return $r.filter(function(_n){return _n in ot||_n in ln}).forEach(function(_n){return br[_n]=_n in ot?ot[_n]:ln[_n]}),br}}]),F}(),Ot=3e4;function ir(F){return F>=200&&F<300}function Pr(F){switch(rt.default(F)){case"undefined":return"";case"object":return JSON.stringify(F);default:return F}}var Mr=function(){function F(z,$){var k=this;L.default(this,F),this.config=$,this.activeRequests=new Map,this.channel=z,this.channel.on("reply",function(E){return k.processReply(E)}),this.channel.on("disconnected",function(){k.activeRequests.forEach(function(E){clearTimeout(E.timeout),E.reject(new Qe("disconnected"))}),k.activeRequests.clear()})}return V.default(F,[{key:"isConnected",get:function(){return this.channel.isConnected}},{key:"processReply",value:function($){var k=this.activeRequests.get($.id);k&&(clearTimeout(k.timeout),this.activeRequests.delete($.id),ir($.status.code)?k.resolve($):(k.reject(new st("Transport failure: "+$.status.status,$)),ze.trace("message rejected")))}},{key:"storeRequest",value:function($,k,E){var q={resolve:k,reject:E,timeout:setTimeout(function(){ze.trace("request",$,"is timed out"),E(new Qe("Twilsock: request timeout: "+$))},Ot)};this.activeRequests.set($,q)}},{key:"shutdown",value:function(){this.activeRequests.forEach(function($){clearTimeout($.timeout),$.reject(new Qe("Twilsock: request cancelled by user"))}),this.activeRequests.clear()}},{key:"sendInit",value:function(){var z=J.default(Te.default.mark(function k(){var E,q,M;return Te.default.wrap(function(fe){for(;;)switch(fe.prev=fe.next){case 0:return ze.trace("sendInit"),E=nr.getMetadata(this.config),q=new ct(this.config.token,this.config.continuationToken,E,this.config.initRegistrations,this.config.tweaks),fe.next=5,this.sendWithReply(q);case 5:return M=fe.sent,fe.abrupt("return",new cr(M.id,M.header.continuation_token,new Set(M.header.capabilities),M.header.continuation_token_status,M.header.offline_storage,M.header.init_registrations,M.header.debug_info));case 7:case"end":return fe.stop()}},k,this)}));function $(){return z.apply(this,arguments)}return $}()},{key:"sendClose",value:function(){var $=new $e;this.send($)}},{key:"sendWithReply",value:function($,k){var E=this;return new Promise(function(q,M){var ve=E.send($,k);E.storeRequest(ve,q,M)})}},{key:"send",value:function($,k){$.id=$.id||"TM".concat(I.v4());var E=He.createPacket($,Pr(k));try{return this.channel.send(E),$.id}catch(q){throw ze.debug("failed to send ",$,q),ze.trace(q.stack),q}}}]),F}();function dr(F){var z=$n();return function(){var k=ge.default(F),E;if(z){var q=ge.default(this).constructor;E=Reflect.construct(k,arguments,q)}else E=k.apply(this,arguments);return ee.default(this,E)}}function $n(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var Gr=function(F){ue.default($,F);var z=dr($);function $(k){var E;return L.default(this,$),E=z.call(this),pe.default(D.default(E),"socket",null),E.url=k,E.url=k,E.WebSocket=t.WebSocket||t.MozWebSocket||{},E}return V.default($,[{key:"isConnected",get:function(){return!!this.socket&&this.socket.readyState===1}},{key:"connect",value:function(){var E=this;ze.trace("connecting to socket");var q;try{q=new this.WebSocket(this.url)}catch(M){ze.debug("Socket error: ".concat(this.url)),this.emit("socketError",M);return}q.binaryType="arraybuffer",q.onopen=function(){ze.debug("socket opened ".concat(E.url)),E.emit("connected")},q.onclose=function(M){ze.debug("socket closed",M),E.emit("disconnected",M)},q.onerror=function(M){ze.debug("Socket error:",M),E.emit("socketError",M)},q.onmessage=function(M){E.emit("message",M.data)},this.socket=q}},{key:"send",value:function(E){return this.socket&&this.socket.send(E)}},{key:"close",value:function(){if(ze.trace("closing socket"),this.socket){this.socket.onopen=null,this.socket.onclose=null,this.socket.onerror=null,this.socket.onmessage=null;try{this.socket.close()}finally{}}}}]),$}(_e);function oa(F){var z=ja();return function(){var k=ge.default(F),E;if(z){var q=ge.default(this).constructor;E=Reflect.construct(k,arguments,q)}else E=k.apply(this,arguments);return ee.default(this,E)}}function ja(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var Fa=function(F){ue.default($,F);var z=oa($);function $(k){var E;return L.default(this,$),E=z.call(this),E.transport=k,E.registrations=new Map,E.registrationsInProgress=new Map,E}return V.default($,[{key:"putNotificationContext",value:function(){var k=J.default(Te.default.mark(function q(M,ve){var fe;return Te.default.wrap(function(Be){for(;;)switch(Be.prev=Be.next){case 0:return fe={method:"put_notification_ctx",notification_ctx_id:M},Be.next=3,this.transport.sendWithReply(fe,ve);case 3:case"end":return Be.stop()}},q,this)}));function E(q,M){return k.apply(this,arguments)}return E}()},{key:"deleteNotificationContext",value:function(){var k=J.default(Te.default.mark(function q(M){var ve;return Te.default.wrap(function(Ae){for(;;)switch(Ae.prev=Ae.next){case 0:return ve={method:"delete_notification_ctx",notification_ctx_id:M},Ae.next=3,this.transport.sendWithReply(ve);case 3:case"end":return Ae.stop()}},q,this)}));function E(q){return k.apply(this,arguments)}return E}()},{key:"updateRegistration",value:function(){var k=J.default(Te.default.mark(function q(M,ve){var fe,Ae;return Te.default.wrap(function(ot){for(;;)switch(ot.prev=ot.next){case 0:return ze.debug("update registration for context",M),fe=this.registrationsInProgress.get(M),fe||(fe=new Set,this.registrationsInProgress.set(M,fe)),Ae=I.v4(),fe.add(Ae),ot.prev=5,ot.next=8,this.putNotificationContext(M,ve);case 8:ze.debug("registration attempt succeeded for context",ve),fe.delete(Ae),fe.size===0&&(this.registrationsInProgress.delete(M),this.emit("registered",M)),ot.next=19;break;case 13:ot.prev=13,ot.t0=ot.catch(5),ze.warn("registration attempt failed for context",ve),ze.debug(ot.t0),fe.delete(Ae),fe.size===0&&(this.registrationsInProgress.delete(M),this.emit("registrationFailed",M,ot.t0));case 19:case"end":return ot.stop()}},q,this,[[5,13]])}));function E(q,M){return k.apply(this,arguments)}return E}()},{key:"updateRegistrations",value:function(){var k=J.default(Te.default.mark(function q(){var M=this,ve;return Te.default.wrap(function(Ae){for(;;)switch(Ae.prev=Ae.next){case 0:return ze.trace("refreshing ".concat(this.registrations.size," registrations")),ve=[],this.registrations.forEach(function(Be,ot){ve.push(M.updateRegistration(ot,Be))}),Ae.next=5,Promise.all(ve);case 5:case"end":return Ae.stop()}},q,this)}));function E(){return k.apply(this,arguments)}return E}()},{key:"setNotificationsContext",value:function(){var k=J.default(Te.default.mark(function q(M,ve){return Te.default.wrap(function(Ae){for(;;)switch(Ae.prev=Ae.next){case 0:if(!(!M||!ve)){Ae.next=2;break}throw new Qe("Invalid arguments provided");case 2:return this.registrations.set(M,ve),Ae.next=5,this.updateRegistration(M,ve);case 5:return Ae.abrupt("return",Ae.sent);case 6:case"end":return Ae.stop()}},q,this)}));function E(q,M){return k.apply(this,arguments)}return E}()},{key:"removeNotificationsContext",value:function(){var k=J.default(Te.default.mark(function q(M){return Te.default.wrap(function(fe){for(;;)switch(fe.prev=fe.next){case 0:if(this.registrations.has(M)){fe.next=2;break}return fe.abrupt("return");case 2:return fe.next=4,this.deleteNotificationContext(M);case 4:this.transport.isConnected&&this.registrations.delete(M);case 5:case"end":return fe.stop()}},q,this)}));function E(q){return k.apply(this,arguments)}return E}()}]),$}(_e);function Er(F){var z=Ua();return function(){var k=ge.default(F),E;if(z){var q=ge.default(this).constructor;E=Reflect.construct(k,arguments,q)}else E=k.apply(this,arguments);return ee.default(this,E)}}function Ua(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var ci=function(F){ue.default($,F);var z=Er($);function $(k,E,q){var M;return L.default(this,$),M=z.call(this,E),M.status=k,M.description=E,M.body=q,M}return $}(Qe);function or(F){var z=Ba();return function(){var k=ge.default(F),E;if(z){var q=ge.default(this).constructor;E=Reflect.construct(k,arguments,q)}else E=k.apply(this,arguments);return ee.default(this,E)}}function Ba(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var gn=function(F){ue.default($,F);var z=or($);function $(k){return L.default(this,$),z.call(this,k)}return $}(Qe),Oi=2e4;function Ai(F){return F>=200&&F<300}function qa(F){return F&&F.header&&F.header.http_status}function yn(F){var z=F.match(/^(https?\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)(\/[^?#]*)(\?[^#]*|)(#.*|)$/);if(z){var $={protocol:z[1],host:z[2],hostname:z[3],port:z[4],pathname:z[5],search:z[6],hash:z[7],params:{}};if($.search.length>0){var k=$.search.substring(1);$.params=k.split("&").map(function(E){return E.split("=")}).reduce(function(E,q){return E.hasOwnProperty(q[0])?Array.isArray(E[q[0]])?E[q[0]].push(q[1]):E[q[0]]=[E[q[0]],q[1]]:E[q[0]]=q[1],E},{})}return $}throw new Qe("Incorrect URI: "+F)}function At(F,z){var $=yn(z),k={method:F,host:$.host,path:$.pathname};return $.params&&(k.params=$.params),k}function ua(F,z,$,k,E){return{to:At(F,z),headers:$,body:k,grant:E}}var ca=function(){function F(z,$,k){L.default(this,F),this.config=k,this.transport=z,this.pendingMessages=[],this.twilsock=$}return V.default(F,[{key:"saveMessage",value:function($){var k=this;return new Promise(function(E,q){var M={message:$,resolve:E,reject:q,alreadyRejected:!1,timeout:setTimeout(function(){ze.debug("request is timed out"),q(new Qe("request '".concat($.to.method,"' to '").concat($.to.host,"' timed out"))),M.alreadyRejected=!0},Oi)};k.pendingMessages.push(M)})}},{key:"sendPendingMessages",value:function(){for(var $=this,k=function(){var M=$.pendingMessages[0];if(!M.alreadyRejected)try{var ve=M.message;$.actualSend(ve).then(function(fe){return M.resolve(fe)}).catch(function(fe){return M.reject(fe)}),clearTimeout(M.timeout)}catch(fe){return ze.debug("Failed to send pending message",fe),"break"}$.pendingMessages.splice(0,1)};this.pendingMessages.length>0;){var E=k();if(E==="break")break}}},{key:"rejectPendingMessages",value:function(){var $=this;this.pendingMessages.forEach(function(k){k.reject(new gn("Unable to connect: "+$.twilsock.getTerminationReason)),k.alreadyRejected=!0,clearTimeout(k.timeout)}),this.pendingMessages.splice(0,this.pendingMessages.length)}},{key:"actualSend",value:function(){var z=J.default(Te.default.mark(function k(E){var q,M,ve,fe,Ae,Be,ot,$r;return Te.default.wrap(function(br){for(;;)switch(br.prev=br.next){case 0:return M=E.to,ve=E.headers,fe=E.body,Ae=(q=E.grant)!==null&&q!==void 0?q:this.config.activeGrant,Be={host:M.host,path:M.path,method:M.method,params:M.params,headers:ve},ot=new ye(Ae,ve["Content-Type"]||"application/json",Be),ze.trace("Sending upstream message",ot),br.next=9,this.transport.sendWithReply(ot,fe);case 9:if($r=br.sent,ze.trace("Received upstream message response",$r),!(qa($r)&&!Ai($r.header.http_status.code))){br.next=13;break}throw new ci($r.header.http_status.code,$r.header.http_status.status,$r.body);case 13:return br.abrupt("return",{status:$r.header.http_status,headers:$r.header.http_headers,body:$r.body});case 14:case"end":return br.stop()}},k,this)}));function $(k){return z.apply(this,arguments)}return $}()},{key:"send",value:function($,k){var E=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},q=arguments.length>3?arguments[3]:void 0,M=arguments.length>4?arguments[4]:void 0;if(this.twilsock.isTerminalState)return Promise.reject(new gn("Unable to connect: "+this.twilsock.getTerminationReason));var ve=ua($,k,E,q,M);return this.twilsock.isConnected?this.actualSend(ve):this.saveMessage(ve)}}]),F}(),Pi=function(){function F(){var z=this;L.default(this,F),this._promise=new Promise(function($,k){z._resolve=$,z._reject=k})}return V.default(F,[{key:"promise",get:function(){return this._promise}},{key:"update",value:function($){this._resolve($)}},{key:"set",value:function($){this._resolve($)}},{key:"fail",value:function($){this._reject($)}}]),F}(),Mi=function(){function F(z){L.default(this,F),this.id=z}return V.default(F,null,[{key:"create",value:function($){if($ instanceof Object&&"storage_id"in $)return new F($.storage_id);throw new Qe('Field "storage_id" is missing')}}]),F}(),li=function(){function F(){return L.default(this,F),pe.default(this,"initializedFlag","twilio_twilsock_token_storage"),pe.default(this,"tokenStoragePrefix","twilio_continuation_token_"),F._instance||(this.initialize(),F._instance=this),F._instance}return V.default(F,[{key:"sessionStorage",value:function(){try{return t.sessionStorage}catch{return null}}},{key:"window",value:function(){try{return t.window}catch{return null}}},{key:"storeToken",value:function($,k){this.canStore()&&this.sessionStorage.setItem(this.getKeyName(k),$)}},{key:"getStoredToken",value:function($){return this.canStore()?this.sessionStorage.getItem(this.getKeyName($)):null}},{key:"initialize",value:function(){var $=this;if(this.canStore()){var k=this.sessionStorage.getItem(this.initializedFlag);k&&this.clear(),this.sessionStorage.setItem(this.initializedFlag,"true");var E=this.sessionStorage.removeItem;this.window.addEventListener("unload",function(){E($.initializedFlag)})}}},{key:"clear",value:function(){if(this.canStore()){for(var $=[],k=0;k<this.sessionStorage.length;k++){var E=this.sessionStorage.key(k);E&&E.indexOf(this.tokenStoragePrefix)===0&&$.push(E)}var q=this.sessionStorage.removeItem;$.forEach(function(M){return q(M)}),q(this.initializedFlag)}}},{key:"getKeyName",value:function($){return"".concat(this.tokenStoragePrefix).concat($)}},{key:"canStore",value:function(){return!!(this.sessionStorage&&this.sessionStorage.length&&this.window)}}]),F}();pe.default(li,"_instance",null);var Hn=new li,kr=function(){function F(z,$,k,E,q,M){L.default(this,F),this.title=z,this.details=$,this.start=k,this.type=q,this.id=M,this.end=E}return V.default(F,[{key:"toTelemetryEvent",value:function(){var $=new Date,k=this.start,E=this.end?this.end:$;if(E<k){var q=E;E=k,k=q}var M=k.getTime()-$.getTime(),ve=E.getTime()-$.getTime(),fe=new K(M,ve,this.title,this.details,this.id,this.type);return fe}}]),F}();e.TelemetryPoint=void 0,function(F){F[F.Start=0]="Start",F[F.End=1]="End"}(e.TelemetryPoint||(e.TelemetryPoint={})),e.EventSendingLimitation=void 0,function(F){F[F.MinEventsPortion=0]="MinEventsPortion",F[F.AnyEvents=1]="AnyEvents",F[F.AnyEventsIncludingUnfinished=2]="AnyEventsIncludingUnfinished"}(e.EventSendingLimitation||(e.EventSendingLimitation={}));var la=function(){function F(z,$){L.default(this,F),pe.default(this,"minEventsPortionToSend",50),pe.default(this,"maxEventsPortionToSend",100),pe.default(this,"pendingEvents",new Map),pe.default(this,"readyEvents",[]),pe.default(this,"hasInitializationFinished",!1),pe.default(this,"_canSendTelemetry",!1),this.config=z,this.packetInterface=$}return V.default(F,[{key:"isTelemetryEnabled",get:function(){return this.config.confirmedCapabilities.has("telemetry.v1")}},{key:"canSendTelemetry",get:function(){return this._canSendTelemetry&&this.isTelemetryEnabled},set:function($){ze.debug("TelemetryTracker.canSendTelemetry: ".concat($," TelemetryTracker.isTelemetryEnabled: ").concat(this.isTelemetryEnabled)),this._canSendTelemetry&&!$&&(this.pendingEvents.clear(),this.readyEvents=[]),this._canSendTelemetry=$,$&&this.sendTelemetry(e.EventSendingLimitation.AnyEvents),$&&!this.hasInitializationFinished&&(this.hasInitializationFinished=!0)}},{key:"addTelemetryEvent",value:function($){!this.canSendTelemetry&&this.hasInitializationFinished||this.readyEvents.push($)}},{key:"addPartialEvent",value:function($,k,E){ze.debug("Adding ".concat(E===e.TelemetryPoint.Start?"starting":"ending"," timepoint for '").concat(k,"' event"));var q=this.pendingEvents.has(k);if(E===e.TelemetryPoint.Start)q&&ze.debug("Overwriting starting point for '".concat(k,"' event")),this.pendingEvents.set(k,$);else{if(!q){ze.info("Could not find started event for '".concat(k,"' event"));return}this.addTelemetryEvent(this.merge(this.pendingEvents.get(k),$)),this.pendingEvents.delete(k)}}},{key:"getTelemetryToSend",value:function($){return!this.canSendTelemetry||this.readyEvents.length==0?[]:$==e.EventSendingLimitation.MinEventsPortion&&this.readyEvents.length<this.minEventsPortionToSend?[]:this.getTelemetryPortion($==e.EventSendingLimitation.AnyEventsIncludingUnfinished)}},{key:"getTelemetryPortion",value:function($){var k=this,E=Math.min(this.readyEvents.length,this.maxEventsPortionToSend),q=this.readyEvents.splice(0,E);return $&&q.length<this.maxEventsPortionToSend&&this.pendingEvents.forEach(function(M,ve){if(!(q.length>=k.maxEventsPortionToSend)){var fe=k.pendingEvents.get(ve);k.pendingEvents.delete(ve),q.push(new kr("[UNFINISHED] ".concat(fe.title),fe.details,fe.start,null,fe.type,fe.id))}}),q}},{key:"merge",value:function($,k){return new kr(k.title?k.title:$.title,k.details?k.details:$.details,$.start,k.end,k.type?k.type:$.type,k.id?k.id:$.id)}},{key:"sendTelemetryIfMinimalPortionCollected",value:function(){this.sendTelemetry(e.EventSendingLimitation.MinEventsPortion)}},{key:"sendTelemetry",value:function($){var k=this.getTelemetryToSend($);if(k.length!==0)try{this.packetInterface.send(new oe(k.map(function(E){return E.toTelemetryEvent()})))}catch(E){ze.debug("Error while sending ".concat(k.length," telemetry events due to ").concat(E,"; they will be resubmitted")),this.readyEvents=this.readyEvents.concat(k)}}}]),F}();function Rr(F){var z=Hr();return function(){var k=ge.default(F),E;if(z){var q=ge.default(this).constructor;E=Reflect.construct(k,arguments,q)}else E=k.apply(this,arguments);return ee.default(this,E)}}function Hr(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var bn=function F(){L.default(this,F)};pe.default(bn,"TWILSOCK_CONNECT","twilsock.sdk.connect"),pe.default(bn,"TWILSOCK_INIT","twilsock.sdk.init"),e.TwilsockClient=function(F){ue.default($,F);var z=Rr($);function $(k,E,q){var M;L.default(this,$),M=z.call(this),pe.default(D.default(M),"version",Tr),pe.default(D.default(M),"offlineStorageDeferred",new Pi),q.continuationToken=q.continuationToken?q.continuationToken:Hn.getStoredToken(E);var ve=M.config=new mr(k,E,q);ze.setLevel(ve.logLevel);var fe=new Gr(ve.url),Ae=new Mr(fe,ve);return M.channel=new Mt(fe,Ae,ve),M.registrations=new Fa(Ae),M.upstream=new ca(Ae,M.channel,ve),M.telemetryTracker=new la(ve,Ae),M.channel.on("initialized",function(){return M.telemetryTracker.canSendTelemetry=!0}),fe.on("disconnected",function(){return M.telemetryTracker.canSendTelemetry=!1}),M.registrations.on("registered",function(Be){return M.emit("registered",Be)}),M.channel.on("message",function(Be,ot){return setTimeout(function(){return M.emit("message",Be,ot)},0)}),M.channel.on("stateChanged",function(Be){return setTimeout(function(){return M.emit("stateChanged",Be)},0)}),M.channel.on("connectionError",function(Be){return setTimeout(function(){return M.emit("connectionError",Be)},0)}),M.channel.on("tokenAboutToExpire",function(){return setTimeout(function(){return M.emit("tokenAboutToExpire")},0)}),M.channel.on("tokenExpired",function(){return setTimeout(function(){return M.emit("tokenExpired")},0)}),M.channel.on("connected",function(){return M.registrations.updateRegistrations()}),M.channel.on("connected",function(){return M.upstream.sendPendingMessages()}),M.channel.on("connected",function(){return setTimeout(function(){return M.emit("connected")},0)}),M.channel.on("beforeConnect",function(){return M.telemetryTracker.addPartialEvent(new kr("Establish WebSocket connection","",new Date),bn.TWILSOCK_CONNECT,e.TelemetryPoint.Start)}),M.channel.on("connected",function(){return M.telemetryTracker.addPartialEvent(new kr("Establish WebSocket connection","",new Date,new Date),bn.TWILSOCK_CONNECT,e.TelemetryPoint.End)}),M.channel.on("beforeSendInit",function(){return M.telemetryTracker.addPartialEvent(new kr("Send Twilsock init","",new Date),bn.TWILSOCK_INIT,e.TelemetryPoint.Start)}),M.channel.on("initialized",function(){return M.telemetryTracker.addPartialEvent(new kr("Send Twilsock init","Succeeded",new Date,new Date),bn.TWILSOCK_INIT,e.TelemetryPoint.End)}),M.channel.on("sendInitFailed",function(){return M.telemetryTracker.addPartialEvent(new kr("Send Twilsock init","Failed",new Date,new Date),bn.TWILSOCK_INIT,e.TelemetryPoint.End)}),M.channel.on("initialized",function(Be){M.handleStorageId(E,Be),Hn.storeToken(Be.continuationToken,E),setTimeout(function(){return M.emit("initialized",Be)},0)}),M.channel.on("disconnected",function(){return setTimeout(function(){return M.emit("disconnected")},0)}),M.channel.on("disconnected",function(){return M.upstream.rejectPendingMessages()}),M.channel.on("disconnected",function(){return M.offlineStorageDeferred.fail(new Qe("Client disconnected"))}),M.offlineStorageDeferred.promise.catch(function(){}),M}return V.default($,[{key:"emit",value:function(E){for(var q,M=arguments.length,ve=new Array(M>1?M-1:0),fe=1;fe<M;fe++)ve[fe-1]=arguments[fe];return ze.debug("Emitting ".concat(E.toString(),"(").concat(ve.map(function(Ae){return JSON.stringify(Ae)}).join(", "),")")),(q=te.default(ge.default($.prototype),"emit",this)).call.apply(q,[this,E].concat(ve))}},{key:"handleStorageId",value:function(E,q){if(!q.offlineStorage)this.offlineStorageDeferred.fail(new Qe("No offline storage id"));else if(q.offlineStorage.hasOwnProperty(E))try{this.offlineStorageDeferred.set(Mi.create(q.offlineStorage[E])),ze.debug("Offline storage for '".concat(E,"' product: ").concat(JSON.stringify(q.offlineStorage[E]),"."))}catch(M){this.offlineStorageDeferred.fail(new Qe("Failed to parse offline storage for ".concat(E," ").concat(JSON.stringify(q.offlineStorage[E]),". ").concat(M,".")))}else this.offlineStorageDeferred.fail(new Qe("No offline storage id for '".concat(E,"' product: ").concat(JSON.stringify(q.offlineStorage))))}},{key:"storageId",value:function(){return this.offlineStorageDeferred.promise}},{key:"isConnected",get:function(){return this.channel.isConnected}},{key:"state",get:function(){return this.channel.state}},{key:"updateToken",value:function(){var k=J.default(Te.default.mark(function q(M){return Te.default.wrap(function(fe){for(;;)switch(fe.prev=fe.next){case 0:if(ze.trace("updating token '".concat(M,"'")),this.config.token!==M){fe.next=3;break}return fe.abrupt("return");case 3:return this.config.updateToken(M),fe.next=6,this.channel.updateToken(M);case 6:return fe.abrupt("return",fe.sent);case 7:case"end":return fe.stop()}},q,this)}));function E(q){return k.apply(this,arguments)}return E}()},{key:"setNotificationsContext",value:function(){var k=J.default(Te.default.mark(function q(M,ve){return Te.default.wrap(function(Ae){for(;;)switch(Ae.prev=Ae.next){case 0:return Ae.next=2,this.registrations.setNotificationsContext(M,ve);case 2:case"end":return Ae.stop()}},q,this)}));function E(q,M){return k.apply(this,arguments)}return E}()},{key:"removeNotificationsContext",value:function(){var k=J.default(Te.default.mark(function q(M){return Te.default.wrap(function(fe){for(;;)switch(fe.prev=fe.next){case 0:return fe.next=2,this.registrations.removeNotificationsContext(M);case 2:case"end":return fe.stop()}},q,this)}));function E(q){return k.apply(this,arguments)}return E}()},{key:"connect",value:function(){return this.channel.connect()}},{key:"disconnect",value:function(){var k=J.default(Te.default.mark(function q(){return Te.default.wrap(function(ve){for(;;)switch(ve.prev=ve.next){case 0:return this.telemetryTracker.sendTelemetry(e.EventSendingLimitation.AnyEventsIncludingUnfinished),ve.next=3,this.channel.disconnect();case 3:return ve.abrupt("return",ve.sent);case 4:case"end":return ve.stop()}},q,this)}));function E(){return k.apply(this,arguments)}return E}()},{key:"get",value:function(){var k=J.default(Te.default.mark(function q(M,ve,fe){return Te.default.wrap(function(Be){for(;;)switch(Be.prev=Be.next){case 0:return this.telemetryTracker.sendTelemetry(e.EventSendingLimitation.AnyEvents),Be.next=3,this.upstream.send("GET",M,ve,void 0,fe);case 3:return Be.abrupt("return",Be.sent);case 4:case"end":return Be.stop()}},q,this)}));function E(q,M,ve){return k.apply(this,arguments)}return E}()},{key:"post",value:function(){var k=J.default(Te.default.mark(function q(M,ve,fe,Ae){return Te.default.wrap(function(ot){for(;;)switch(ot.prev=ot.next){case 0:return this.telemetryTracker.sendTelemetry(e.EventSendingLimitation.AnyEvents),ot.next=3,this.upstream.send("POST",M,ve,fe,Ae);case 3:return ot.abrupt("return",ot.sent);case 4:case"end":return ot.stop()}},q,this)}));function E(q,M,ve,fe){return k.apply(this,arguments)}return E}()},{key:"put",value:function(){var k=J.default(Te.default.mark(function q(M,ve,fe,Ae){return Te.default.wrap(function(ot){for(;;)switch(ot.prev=ot.next){case 0:return this.telemetryTracker.sendTelemetry(e.EventSendingLimitation.AnyEvents),ot.next=3,this.upstream.send("PUT",M,ve,fe,Ae);case 3:return ot.abrupt("return",ot.sent);case 4:case"end":return ot.stop()}},q,this)}));function E(q,M,ve,fe){return k.apply(this,arguments)}return E}()},{key:"delete",value:function(){var k=J.default(Te.default.mark(function q(M,ve,fe,Ae){return Te.default.wrap(function(ot){for(;;)switch(ot.prev=ot.next){case 0:return this.telemetryTracker.sendTelemetry(e.EventSendingLimitation.AnyEvents),ot.next=3,this.upstream.send("DELETE",M,ve,fe,Ae);case 3:return ot.abrupt("return",ot.sent);case 4:case"end":return ot.stop()}},q,this)}));function E(q,M,ve,fe){return k.apply(this,arguments)}return E}()},{key:"addTelemetryEvent",value:function(E){this.telemetryTracker.addTelemetryEvent(E),this.telemetryTracker.sendTelemetryIfMinimalPortionCollected()}},{key:"addPartialTelemetryEvent",value:function(E,q,M){this.telemetryTracker.addPartialEvent(E,q,M),M===e.TelemetryPoint.End&&this.telemetryTracker.sendTelemetryIfMinimalPortionCollected()}}]),$}(_e),e.TwilsockClient=P([m.validateConstructorTypes(m.nonEmptyString,m.nonEmptyString,[m.pureObject,"undefined",m.literal(null)]),Ie("design:paramtypes",[String,String,Object])],e.TwilsockClient);var fa=function(){function F(z){L.default(this,F),this.product=z,this.type="ers",this.notification_protocol_version=0,this.message_types=[]}return V.default(F,[{key:"populateInitRegistrations",value:function($){var k=new Set(this.message_types);for(var E in $)k.add($[E]);this.message_types=Array.from(k)}}]),F}();e.InitRegistration=fa,e.TelemetryEventDescription=kr,e.TelemetryTracker=la,e.TransportUnavailableError=gn,e.Twilsock=e.TwilsockClient,e.TwilsockError=Qe})(xf);var v1={},oS=er,K9=wt,J9=Yt,Y9=yt,kp=$u,X9=ku,Q9=wu,Z9=Jr,eK=Su,As=Object.assign,uS=Object.defineProperty,tK=K9([].concat),m1=!As||Y9(function(){if(oS&&As({b:1},As(uS({},"a",{enumerable:!0,get:function(){uS(this,"b",{value:3,enumerable:!1})}}),{b:2})).b!==1)return!0;var e={},t={},r=Symbol("assign detection"),n="abcdefghijklmnopqrst";return e[r]=7,n.split("").forEach(function(i){t[i]=i}),As({},e)[r]!==7||kp(As({},t)).join("")!==n})?function(t,r){for(var n=Z9(t),i=arguments.length,a=1,s=X9.f,o=Q9.f;i>a;)for(var u=eK(arguments[a++]),c=s?tK(kp(u),s(u)):kp(u),l=c.length,p=0,v;l>p;)v=c[p++],(!oS||J9(o,u,v))&&(n[v]=u[v]);return n}:As,rK=Ct,cS=m1;rK({target:"Object",stat:!0,arity:2,forced:Object.assign!==cS},{assign:cS});var sv={exports:{}},lS=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof window.msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto);if(lS){var fS=new Uint8Array(16);sv.exports=function(){return lS(fS),fS}}else{var dS=new Array(16);sv.exports=function(){for(var t=0,r;t<16;t++)t&3||(r=Math.random()*4294967296),dS[t]=r>>>((t&3)<<3)&255;return dS}}var g1=sv.exports,y1=[];for(var Nc=0;Nc<256;++Nc)y1[Nc]=(Nc+256).toString(16).substr(1);function nK(e,t){var r=t||0,n=y1;return[n[e[r++]],n[e[r++]],n[e[r++]],n[e[r++]],"-",n[e[r++]],n[e[r++]],"-",n[e[r++]],n[e[r++]],"-",n[e[r++]],n[e[r++]],"-",n[e[r++]],n[e[r++]],n[e[r++]],n[e[r++]],n[e[r++]],n[e[r++]]].join("")}var b1=nK,iK=g1,aK=b1,pS,Rp,$p=0,Ip=0;function sK(e,t,r){var n=t&&r||0,i=t||[];e=e||{};var a=e.node||pS,s=e.clockseq!==void 0?e.clockseq:Rp;if(a==null||s==null){var o=iK();a==null&&(a=pS=[o[0]|1,o[1],o[2],o[3],o[4],o[5]]),s==null&&(s=Rp=(o[6]<<8|o[7])&16383)}var u=e.msecs!==void 0?e.msecs:new Date().getTime(),c=e.nsecs!==void 0?e.nsecs:Ip+1,l=u-$p+(c-Ip)/1e4;if(l<0&&e.clockseq===void 0&&(s=s+1&16383),(l<0||u>$p)&&e.nsecs===void 0&&(c=0),c>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");$p=u,Ip=c,Rp=s,u+=122192928e5;var p=((u&268435455)*1e4+c)%4294967296;i[n++]=p>>>24&255,i[n++]=p>>>16&255,i[n++]=p>>>8&255,i[n++]=p&255;var v=u/4294967296*1e4&268435455;i[n++]=v>>>8&255,i[n++]=v&255,i[n++]=v>>>24&15|16,i[n++]=v>>>16&255,i[n++]=s>>>8|128,i[n++]=s&255;for(var m=0;m<6;++m)i[n+m]=a[m];return t||aK(i)}var oK=sK,uK=g1,cK=b1;function lK(e,t,r){var n=t&&r||0;typeof e=="string"&&(t=e==="binary"?new Array(16):null,e=null),e=e||{};var i=e.random||(e.rng||uK)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t)for(var a=0;a<16;++a)t[n+a]=i[a];return t||cK(i)}var fK=lK,dK=oK,_1=fK,kg=_1;kg.v1=dK;kg.v4=_1;var pK=kg;/*
167
+ `+k);return M.buffer}}]),F}();function et(F){var z=nt();return function(){var k=ge.default(F),E;if(z){var q=ge.default(this).constructor;E=Reflect.construct(k,arguments,q)}else E=k.apply(this,arguments);return ee.default(this,E)}}function nt(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var Qe=function(F){ue.default($,F);var z=et($);function $(k){return L.default(this,$),z.call(this,k)}return $}(ce.default(Error));function tt(F){var z=at();return function(){var k=ge.default(F),E;if(z){var q=ge.default(this).constructor;E=Reflect.construct(k,arguments,q)}else E=k.apply(this,arguments);return ee.default(this,E)}}function at(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var st=function(F){ue.default($,F);var z=tt($);function $(k,E){var q;return L.default(this,$),q=z.call(this,k),q.reply=E,q}return $}(Qe);function yr(F,z){var $=Object.keys(F);if(Object.getOwnPropertySymbols){var k=Object.getOwnPropertySymbols(F);z&&(k=k.filter(function(E){return Object.getOwnPropertyDescriptor(F,E).enumerable})),$.push.apply($,k)}return $}function fr(F){for(var z=1;z<arguments.length;z++){var $=arguments[z]!=null?arguments[z]:{};z%2?yr(Object($),!0).forEach(function(k){pe.default(F,k,$[k])}):Object.getOwnPropertyDescriptors?Object.defineProperties(F,Object.getOwnPropertyDescriptors($)):yr(Object($)).forEach(function(k){Object.defineProperty(F,k,Object.getOwnPropertyDescriptor($,k))})}return F}function dt(F){var z=Gr();return function(){var k=ge.default(F),E;if(z){var q=ge.default(this).constructor;E=Reflect.construct(k,arguments,q)}else E=k.apply(this,arguments);return ee.default(this,E)}}function Gr(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var cn=function(F){ue.default($,F);var z=dt($);function $(k){var E;return L.default(this,$),E=z.call(this),pe.default(D.default(E),"newBackoff",null),pe.default(D.default(E),"usedBackoff",null),pe.default(D.default(E),"retrier",null),E.options=k?fr({},k):{},E}return V.default($,[{key:"inProgress",get:function(){return!!this.retrier}},{key:"start",value:function(){if(this.inProgress)throw new Error("Already waiting for next attempt, call finishAttempt(success : boolean) to finish it");this.createRetrier()}},{key:"stop",value:function(){this.cleanRetrier(),this.newBackoff=null,this.usedBackoff=null}},{key:"modifyBackoff",value:function(E){this.newBackoff=E}},{key:"attemptFailed",value:function(){if(!this.inProgress)throw new Error("No attempt is in progress");if(this.newBackoff){var E=!this.usedBackoff||this.usedBackoff<this.newBackoff;if(E)this.createRetrier();else{var q;(q=this.retrier)===null||q===void 0||q.failed(new Error)}}else{var M;(M=this.retrier)===null||M===void 0||M.failed(new Error)}}},{key:"cancel",value:function(){var E;(E=this.retrier)===null||E===void 0||E.cancel()}},{key:"cleanRetrier",value:function(){var E,q;(E=this.retrier)===null||E===void 0||E.removeAllListeners(),(q=this.retrier)===null||q===void 0||q.cancel(),this.retrier=null}},{key:"getRetryPolicy",value:function(){var E=fr({},this.options);return this.newBackoff&&(E.min=this.newBackoff,E.max=this.options.max&&this.options.max>this.newBackoff?this.options.max:this.newBackoff),E.maxAttemptsCount=this.options.maxAttemptsCount?this.options.maxAttemptsCount+1:void 0,E}},{key:"createRetrier",value:function(){var E=this;this.cleanRetrier();var q=this.getRetryPolicy();this.retrier=new x.Retrier(q),this.retrier.once("attempt",function(){var M,ve;(M=E.retrier)===null||M===void 0||M.on("attempt",function(){return E.emit("attempt")}),(ve=E.retrier)===null||ve===void 0||ve.failed(new Error("Skipping first attempt"))}),this.retrier.on("failed",function(M){return E.emit("failed",M)}),this.usedBackoff=this.newBackoff,this.newBackoff=null,this.retrier.start()}}]),$}(_e);function it(F){var z=Z();return function(){var k=ge.default(F),E;if(z){var q=ge.default(this).constructor;E=Reflect.construct(k,arguments,q)}else E=k.apply(this,arguments);return ee.default(this,E)}}function Z(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var xe=3e3;function Ye(F){setTimeout(F,0)}var Mt=function(F){ue.default($,F);var z=it($);function $(k,E,q){var M;L.default(this,$),M=z.call(this),pe.default(D.default(M),"disconnectingTimer",null),pe.default(D.default(M),"disconnectedPromiseResolve",null),pe.default(D.default(M),"terminalStates",["disconnected","rejected"]),pe.default(D.default(M),"tokenExpiredSasCode",20104),pe.default(D.default(M),"terminationReason","Connection is not initialized"),M.websocket=k,M.websocket.on("connected",function(){return M.fsm.socketConnected()}),M.websocket.on("disconnected",function(){return M.fsm.socketClosed()}),M.websocket.on("message",function(fe){return M.onIncomingMessage(fe)}),M.websocket.on("socketError",function(fe){return M.emit("connectionError",{terminal:!1,message:"Socket error: ".concat(fe.message),httpStatusCode:null,errorCode:null})}),M.transport=E,M.config=q,M.retrier=new cn(q.retryPolicy),M.retrier.on("attempt",function(){return M.retry()}),M.retrier.on("failed",function(fe){ze.warn("Retrying failed: ".concat(fe.message)),M.disconnect()}),typeof window<"u"&&typeof window.addEventListener<"u"&&(window.addEventListener("online",function(){ze.debug("Browser reported connectivity state: online"),M.resetBackoff(),M.fsm.systemOnline()}),window.addEventListener("offline",function(){ze.debug("Browser reported connectivity state: offline"),M.websocket.close(),M.fsm.socketClosed()}));var ve=Se.factory({init:"disconnected",transitions:[{name:"userConnect",from:["disconnected","rejected"],to:"connecting"},{name:"userConnect",from:["connecting","connected"]},{name:"userDisconnect",from:["connecting","initialising","connected","updating","retrying","rejected","waitSocketClosed","waitOffloadSocketClosed"],to:"disconnecting"},{name:"userRetry",from:["retrying"],to:"connecting"},{name:"socketConnected",from:["connecting"],to:"initialising"},{name:"socketClosed",from:["connecting","initialising","connected","updating","error","waitOffloadSocketClosed"],to:"retrying"},{name:"socketClosed",from:["disconnecting"],to:"disconnected"},{name:"socketClosed",from:["waitSocketClosed"],to:"disconnected"},{name:"socketClosed",from:["rejected"],to:"rejected"},{name:"initSuccess",from:["initialising"],to:"connected"},{name:"initError",from:["initialising"],to:"error"},{name:"tokenRejected",from:["initialising","updating"],to:"rejected"},{name:"protocolError",from:["initialising","connected","updating"],to:"error"},{name:"receiveClose",from:["initialising","connected","updating"],to:"waitSocketClosed"},{name:"receiveOffload",from:["initialising","connected","updating"],to:"waitOffloadSocketClosed"},{name:"unsupportedProtocol",from:["initialising","connected","updating"],to:"unsupported"},{name:"receiveFatalClose",from:["initialising","connected","updating"],to:"unsupported"},{name:"userUpdateToken",from:["disconnected","rejected","connecting","retrying"],to:"connecting"},{name:"userUpdateToken",from:["connected"],to:"updating"},{name:"updateSuccess",from:["updating"],to:"connected"},{name:"updateError",from:["updating"],to:"error"},{name:"userSend",from:["connected"],to:"connected"},{name:"systemOnline",from:["retrying"],to:"connecting"}],methods:{onConnecting:function(){M.setupSocket(),M.emit("connecting")},onEnterInitialising:function(){M.sendInit()},onLeaveInitialising:function(){M.cancelInit()},onEnterUpdating:function(){M.sendUpdate()},onLeaveUpdating:function(){M.cancelUpdate()},onEnterRetrying:function(){M.initRetry(),M.emit("connecting")},onEnterConnected:function(){M.resetBackoff(),M.onConnected()},onUserUpdateToken:function(){M.resetBackoff()},onTokenRejected:function(){M.resetBackoff(),M.closeSocket(!0),M.finalizeSocket()},onUserDisconnect:function(){M.closeSocket(!0)},onEnterDisconnecting:function(){M.startDisconnectTimer()},onLeaveDisconnecting:function(){M.cancelDisconnectTimer()},onEnterWaitSocketClosed:function(){M.startDisconnectTimer()},onLeaveWaitSocketClosed:function(){M.cancelDisconnectTimer()},onEnterWaitOffloadSocketClosed:function(){M.startDisconnectTimer()},onLeaveWaitOffloadSocketClosed:function(){M.cancelDisconnectTimer()},onDisconnected:function(){M.resetBackoff(),M.finalizeSocket()},onReceiveClose:function(){M.onCloseReceived()},onReceiveOffload:function(Ae,Be){ze.debug("onreceiveoffload: ",Be),M.modifyBackoff(Be.body),M.onCloseReceived()},onUnsupported:function(){M.closeSocket(!0),M.finalizeSocket()},onError:function(Ae,Be){M.closeSocket(Be),M.finalizeSocket()},onEnterState:function(Ae){Ae.from!=="none"&&M.changeState(Ae)},onInvalidTransition:function(Ae,Be,ot){ze.warn("FSM: unexpected transition",Be,ot)}}});return M.fsm=new ve,M}return V.default($,[{key:"changeState",value:function(E){ze.debug("FSM: ".concat(E.transition,": ").concat(E.from," --> ").concat(E.to)),this.lastEmittedState!==this.state&&(this.lastEmittedState=this.state,this.emit("stateChanged",this.state))}},{key:"resetBackoff",value:function(){ze.trace("resetBackoff"),this.retrier.stop()}},{key:"modifyBackoff",value:function(E){ze.trace("modifyBackoff",E);var q=E?E.backoff_policy:null;q&&typeof q.reconnect_min_ms=="number"&&this.retrier.modifyBackoff(q.reconnect_min_ms)}},{key:"startDisconnectTimer",value:function(){var E=this;ze.trace("startDisconnectTimer"),this.disconnectingTimer&&(clearTimeout(this.disconnectingTimer),this.disconnectingTimer=null),this.disconnectingTimer=setTimeout(function(){ze.debug("disconnecting is timed out"),E.closeSocket(!0)},xe)}},{key:"cancelDisconnectTimer",value:function(){ze.trace("cancelDisconnectTimer"),this.disconnectingTimer&&(clearTimeout(this.disconnectingTimer),this.disconnectingTimer=null)}},{key:"isConnected",get:function(){return this.state==="connected"&&this.websocket.isConnected}},{key:"state",get:function(){switch(this.fsm.state){case"connecting":case"initialising":case"retrying":case"error":return"connecting";case"updating":case"connected":return"connected";case"rejected":return"denied";case"disconnecting":case"waitSocketClosed":case"waitOffloadSocketClosed":return"disconnecting";case"disconnected":default:return"disconnected"}}},{key:"initRetry",value:function(){ze.debug("initRetry"),this.retrier.inProgress?this.retrier.attemptFailed():this.retrier.start()}},{key:"retry",value:function(){this.fsm.state!="connecting"?(ze.trace("retry"),this.websocket.close(),this.fsm.userRetry()):ze.trace("can retry as already connecting")}},{key:"onConnected",value:function(){this.emit("connected")}},{key:"finalizeSocket",value:function(){ze.trace("finalizeSocket"),this.websocket.close(),this.emit("disconnected"),this.disconnectedPromiseResolve&&(this.disconnectedPromiseResolve(),this.disconnectedPromiseResolve=null)}},{key:"setupSocket",value:function(){ze.trace("setupSocket:",this.config.token),this.emit("beforeConnect"),this.websocket.connect()}},{key:"onIncomingMessage",value:function(E){var q=He.parse(E);if(q){var M=q.method,ve=q.header,fe=q.payload;if(M!=="reply"&&this.confirmReceiving(ve),M==="notification")this.emit("message",ve.message_type,fe);else if(ve.method==="reply")this.transport.processReply({id:ve.id,status:ve.status,header:ve,body:fe});else if(ve.method==="client_update")ve.client_update_type==="token_about_to_expire"&&this.emit("tokenAboutToExpire");else if(ve.method==="close")if(ve.status.code===308)ze.debug("Connection has been offloaded"),this.fsm.receiveOffload({status:ve.status.status,body:fe});else if(ve.status.code===406){var Ae="Server closed connection because can't parse protocol: ".concat(JSON.stringify(ve.status));this.emitReplyConnectionError(Ae,ve,!0),ze.error(Ae),this.fsm.receiveFatalClose()}else ve.status.code===417?(ze.error("Server closed connection because can't parse client reply: ".concat(JSON.stringify(ve.status))),this.fsm.receiveFatalClose(ve.status.status)):ve.status.code===410?(ze.warn("Server closed connection: ".concat(JSON.stringify(ve.status))),this.fsm.receiveClose(ve.status.status),this.emit("tokenExpired")):ve.status.code===401?(ze.error("Server closed connection: ".concat(JSON.stringify(ve.status))),this.fsm.receiveClose(ve.status.status)):(ze.warn("unexpected message: ",ve.status),this.fsm.receiveOffload({status:ve.status.status,body:null}))}}},{key:"sendInit",value:function(){var k=J.default(Te.default.mark(function q(){var M,ve;return Te.default.wrap(function(Ae){for(;;)switch(Ae.prev=Ae.next){case 0:return ze.trace("sendInit"),Ae.prev=1,this.emit("beforeSendInit"),Ae.next=5,this.transport.sendInit();case 5:M=Ae.sent,this.config.updateContinuationToken(M.continuationToken),this.config.confirmedCapabilities=M.confirmedCapabilities,this.fsm.initSuccess(M),this.emit("initialized",M),this.emit("tokenUpdated"),Ae.next=17;break;case 13:Ae.prev=13,Ae.t0=Ae.catch(1),Ae.t0 instanceof st?(ve=!1,ze.warn("Init rejected by server: ".concat(JSON.stringify(Ae.t0.reply.status))),this.emit("sendInitFailed"),Ae.t0.reply.status.code===401||Ae.t0.reply.status.code===403?(ve=!0,this.fsm.tokenRejected(Ae.t0.reply.status),Ae.t0.reply.status.errorCode===this.tokenExpiredSasCode&&this.emit("tokenExpired")):Ae.t0.reply.status.code===429?(this.modifyBackoff(Ae.t0.reply.body),this.fsm.initError(!0)):Ae.t0.reply.status.code===500?this.fsm.initError(!1):this.fsm.initError(!0),this.emitReplyConnectionError(Ae.t0.message,Ae.t0.reply,ve)):(this.terminationReason=Ae.t0.message,this.emit("connectionError",{terminal:!0,message:"Unknown error during connection initialisation: ".concat(Ae.t0.message,`
168
+ `).concat(JSON.stringify(Ae.t0,null,2)),httpStatusCode:null,errorCode:null}),this.fsm.initError(!0)),this.emit("tokenUpdated",Ae.t0);case 17:case"end":return Ae.stop()}},q,this,[[1,13]])}));function E(){return k.apply(this,arguments)}return E}()},{key:"sendUpdate",value:function(){var k=J.default(Te.default.mark(function q(){var M,ve,fe;return Te.default.wrap(function(Be){for(;;)switch(Be.prev=Be.next){case 0:return ze.trace("sendUpdate"),M=new gr(this.config.token),Be.prev=2,Be.next=5,this.transport.sendWithReply(M);case 5:ve=Be.sent,this.fsm.updateSuccess(ve.body),this.emit("tokenUpdated"),Be.next=14;break;case 10:Be.prev=10,Be.t0=Be.catch(2),Be.t0 instanceof st?(fe=!1,ze.warn("Token update rejected by server: ".concat(JSON.stringify(Be.t0.reply.status))),Be.t0.reply.status.code===401||Be.t0.reply.status.code===403?(fe=!0,this.fsm.tokenRejected(Be.t0.reply.status),Be.t0.reply.status.errorCode===this.tokenExpiredSasCode&&this.emit("tokenExpired")):Be.t0.reply.status.code===429?(this.modifyBackoff(Be.t0.reply.body),this.fsm.updateError(Be.t0.reply.status)):this.fsm.updateError(Be.t0.reply.status),this.emitReplyConnectionError(Be.t0.message,Be.t0.reply,fe)):(this.emit("error",!1,Be.t0.message,null,null),this.fsm.updateError(Be.t0)),this.emit("tokenUpdated",Be.t0);case 14:case"end":return Be.stop()}},q,this,[[2,10]])}));function E(){return k.apply(this,arguments)}return E}()},{key:"emitReplyConnectionError",value:function(E,q,M){var ve=q.status&&q.status.description?q.status.description:E,fe=q.status.code,Ae=q.status&&q.status.errorCode?q.status.errorCode:null;M&&(this.terminationReason=ve),this.emit("connectionError",{terminal:M,message:"Connection error: ".concat(ve),httpStatusCode:fe,errorCode:Ae})}},{key:"cancelInit",value:function(){ze.trace("cancelInit")}},{key:"cancelUpdate",value:function(){ze.trace("cancelUpdate")}},{key:"confirmReceiving",value:function(E){ze.trace("confirmReceiving");try{this.transport.send(new me(E.id))}catch(q){ze.debug("failed to confirm packet receiving",q)}}},{key:"closeSocket",value:function(E){var q=this;ze.trace("closeSocket (graceful: ".concat(E,")")),E&&this.transport.isConnected&&this.transport.sendClose(),this.websocket.close(),Ye(function(){return q.fsm.socketClosed()})}},{key:"connect",value:function(){ze.trace("connect"),this.fsm.userConnect()}},{key:"disconnect",value:function(){var E=this;return ze.trace("disconnect"),this.fsm.is("disconnected")?Promise.resolve():new Promise(function(q){E.disconnectedPromiseResolve=q,E.fsm.userDisconnect()})}},{key:"updateToken",value:function(E){var q=this;return ze.trace("updateToken:",E),new Promise(function(M,ve){q.once("tokenUpdated",function(fe){fe?ve(fe):M()}),q.fsm.userUpdateToken()})}},{key:"isTerminalState",get:function(){return this.terminalStates.indexOf(this.fsm.state)!==-1}},{key:"getTerminationReason",get:function(){return this.terminationReason}},{key:"onCloseReceived",value:function(){this.websocket.close()}}]),$}(_e),nr=function(){function F(){L.default(this,F)}return V.default(F,null,[{key:"getMetadata",value:function($){var k,E,q,M,ve,fe,Ae,Be,ot=$&&$.clientMetadata?$.clientMetadata:{},$r=["ver","env","envv","os","osv","osa","type","sdk","sdkv","dev","devv","devt","app","appv"],ln={env:(k=he.name)!==null&&k!==void 0?k:"unknown",envv:(E=he.version)!==null&&E!==void 0?E:"unknown",os:(q=(M=he.os)===null||M===void 0?void 0:M.family)!==null&&q!==void 0?q:"unknown",osv:(ve=(fe=he.os)===null||fe===void 0?void 0:fe.version)!==null&&ve!==void 0?ve:"unknown",osa:(Ae=(Be=he.os)===null||Be===void 0?void 0:Be.architecture)!==null&&Ae!==void 0?Ae:"unknown",sdk:"js-default"},br={};return $r.filter(function(_n){return _n in ot||_n in ln}).forEach(function(_n){return br[_n]=_n in ot?ot[_n]:ln[_n]}),br}}]),F}(),Ot=3e4;function ir(F){return F>=200&&F<300}function Pr(F){switch(rt.default(F)){case"undefined":return"";case"object":return JSON.stringify(F);default:return F}}var Mr=function(){function F(z,$){var k=this;L.default(this,F),this.config=$,this.activeRequests=new Map,this.channel=z,this.channel.on("reply",function(E){return k.processReply(E)}),this.channel.on("disconnected",function(){k.activeRequests.forEach(function(E){clearTimeout(E.timeout),E.reject(new Qe("disconnected"))}),k.activeRequests.clear()})}return V.default(F,[{key:"isConnected",get:function(){return this.channel.isConnected}},{key:"processReply",value:function($){var k=this.activeRequests.get($.id);k&&(clearTimeout(k.timeout),this.activeRequests.delete($.id),ir($.status.code)?k.resolve($):(k.reject(new st("Transport failure: "+$.status.status,$)),ze.trace("message rejected")))}},{key:"storeRequest",value:function($,k,E){var q={resolve:k,reject:E,timeout:setTimeout(function(){ze.trace("request",$,"is timed out"),E(new Qe("Twilsock: request timeout: "+$))},Ot)};this.activeRequests.set($,q)}},{key:"shutdown",value:function(){this.activeRequests.forEach(function($){clearTimeout($.timeout),$.reject(new Qe("Twilsock: request cancelled by user"))}),this.activeRequests.clear()}},{key:"sendInit",value:function(){var z=J.default(Te.default.mark(function k(){var E,q,M;return Te.default.wrap(function(fe){for(;;)switch(fe.prev=fe.next){case 0:return ze.trace("sendInit"),E=nr.getMetadata(this.config),q=new ct(this.config.token,this.config.continuationToken,E,this.config.initRegistrations,this.config.tweaks),fe.next=5,this.sendWithReply(q);case 5:return M=fe.sent,fe.abrupt("return",new cr(M.id,M.header.continuation_token,new Set(M.header.capabilities),M.header.continuation_token_status,M.header.offline_storage,M.header.init_registrations,M.header.debug_info));case 7:case"end":return fe.stop()}},k,this)}));function $(){return z.apply(this,arguments)}return $}()},{key:"sendClose",value:function(){var $=new $e;this.send($)}},{key:"sendWithReply",value:function($,k){var E=this;return new Promise(function(q,M){var ve=E.send($,k);E.storeRequest(ve,q,M)})}},{key:"send",value:function($,k){$.id=$.id||"TM".concat(I.v4());var E=He.createPacket($,Pr(k));try{return this.channel.send(E),$.id}catch(q){throw ze.debug("failed to send ",$,q),ze.trace(q.stack),q}}}]),F}();function dr(F){var z=$n();return function(){var k=ge.default(F),E;if(z){var q=ge.default(this).constructor;E=Reflect.construct(k,arguments,q)}else E=k.apply(this,arguments);return ee.default(this,E)}}function $n(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var Hr=function(F){ue.default($,F);var z=dr($);function $(k){var E;return L.default(this,$),E=z.call(this),pe.default(D.default(E),"socket",null),E.url=k,E.url=k,E.WebSocket=t.WebSocket||t.MozWebSocket||{},E}return V.default($,[{key:"isConnected",get:function(){return!!this.socket&&this.socket.readyState===1}},{key:"connect",value:function(){var E=this;ze.trace("connecting to socket");var q;try{q=new this.WebSocket(this.url)}catch(M){ze.debug("Socket error: ".concat(this.url)),this.emit("socketError",M);return}q.binaryType="arraybuffer",q.onopen=function(){ze.debug("socket opened ".concat(E.url)),E.emit("connected")},q.onclose=function(M){ze.debug("socket closed",M),E.emit("disconnected",M)},q.onerror=function(M){ze.debug("Socket error:",M),E.emit("socketError",M)},q.onmessage=function(M){E.emit("message",M.data)},this.socket=q}},{key:"send",value:function(E){return this.socket&&this.socket.send(E)}},{key:"close",value:function(){if(ze.trace("closing socket"),this.socket){this.socket.onopen=null,this.socket.onclose=null,this.socket.onerror=null,this.socket.onmessage=null;try{this.socket.close()}finally{}}}}]),$}(_e);function oa(F){var z=ja();return function(){var k=ge.default(F),E;if(z){var q=ge.default(this).constructor;E=Reflect.construct(k,arguments,q)}else E=k.apply(this,arguments);return ee.default(this,E)}}function ja(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var Fa=function(F){ue.default($,F);var z=oa($);function $(k){var E;return L.default(this,$),E=z.call(this),E.transport=k,E.registrations=new Map,E.registrationsInProgress=new Map,E}return V.default($,[{key:"putNotificationContext",value:function(){var k=J.default(Te.default.mark(function q(M,ve){var fe;return Te.default.wrap(function(Be){for(;;)switch(Be.prev=Be.next){case 0:return fe={method:"put_notification_ctx",notification_ctx_id:M},Be.next=3,this.transport.sendWithReply(fe,ve);case 3:case"end":return Be.stop()}},q,this)}));function E(q,M){return k.apply(this,arguments)}return E}()},{key:"deleteNotificationContext",value:function(){var k=J.default(Te.default.mark(function q(M){var ve;return Te.default.wrap(function(Ae){for(;;)switch(Ae.prev=Ae.next){case 0:return ve={method:"delete_notification_ctx",notification_ctx_id:M},Ae.next=3,this.transport.sendWithReply(ve);case 3:case"end":return Ae.stop()}},q,this)}));function E(q){return k.apply(this,arguments)}return E}()},{key:"updateRegistration",value:function(){var k=J.default(Te.default.mark(function q(M,ve){var fe,Ae;return Te.default.wrap(function(ot){for(;;)switch(ot.prev=ot.next){case 0:return ze.debug("update registration for context",M),fe=this.registrationsInProgress.get(M),fe||(fe=new Set,this.registrationsInProgress.set(M,fe)),Ae=I.v4(),fe.add(Ae),ot.prev=5,ot.next=8,this.putNotificationContext(M,ve);case 8:ze.debug("registration attempt succeeded for context",ve),fe.delete(Ae),fe.size===0&&(this.registrationsInProgress.delete(M),this.emit("registered",M)),ot.next=19;break;case 13:ot.prev=13,ot.t0=ot.catch(5),ze.warn("registration attempt failed for context",ve),ze.debug(ot.t0),fe.delete(Ae),fe.size===0&&(this.registrationsInProgress.delete(M),this.emit("registrationFailed",M,ot.t0));case 19:case"end":return ot.stop()}},q,this,[[5,13]])}));function E(q,M){return k.apply(this,arguments)}return E}()},{key:"updateRegistrations",value:function(){var k=J.default(Te.default.mark(function q(){var M=this,ve;return Te.default.wrap(function(Ae){for(;;)switch(Ae.prev=Ae.next){case 0:return ze.trace("refreshing ".concat(this.registrations.size," registrations")),ve=[],this.registrations.forEach(function(Be,ot){ve.push(M.updateRegistration(ot,Be))}),Ae.next=5,Promise.all(ve);case 5:case"end":return Ae.stop()}},q,this)}));function E(){return k.apply(this,arguments)}return E}()},{key:"setNotificationsContext",value:function(){var k=J.default(Te.default.mark(function q(M,ve){return Te.default.wrap(function(Ae){for(;;)switch(Ae.prev=Ae.next){case 0:if(!(!M||!ve)){Ae.next=2;break}throw new Qe("Invalid arguments provided");case 2:return this.registrations.set(M,ve),Ae.next=5,this.updateRegistration(M,ve);case 5:return Ae.abrupt("return",Ae.sent);case 6:case"end":return Ae.stop()}},q,this)}));function E(q,M){return k.apply(this,arguments)}return E}()},{key:"removeNotificationsContext",value:function(){var k=J.default(Te.default.mark(function q(M){return Te.default.wrap(function(fe){for(;;)switch(fe.prev=fe.next){case 0:if(this.registrations.has(M)){fe.next=2;break}return fe.abrupt("return");case 2:return fe.next=4,this.deleteNotificationContext(M);case 4:this.transport.isConnected&&this.registrations.delete(M);case 5:case"end":return fe.stop()}},q,this)}));function E(q){return k.apply(this,arguments)}return E}()}]),$}(_e);function Er(F){var z=Ua();return function(){var k=ge.default(F),E;if(z){var q=ge.default(this).constructor;E=Reflect.construct(k,arguments,q)}else E=k.apply(this,arguments);return ee.default(this,E)}}function Ua(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var ci=function(F){ue.default($,F);var z=Er($);function $(k,E,q){var M;return L.default(this,$),M=z.call(this,E),M.status=k,M.description=E,M.body=q,M}return $}(Qe);function or(F){var z=Ba();return function(){var k=ge.default(F),E;if(z){var q=ge.default(this).constructor;E=Reflect.construct(k,arguments,q)}else E=k.apply(this,arguments);return ee.default(this,E)}}function Ba(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var gn=function(F){ue.default($,F);var z=or($);function $(k){return L.default(this,$),z.call(this,k)}return $}(Qe),Oi=2e4;function Ai(F){return F>=200&&F<300}function qa(F){return F&&F.header&&F.header.http_status}function yn(F){var z=F.match(/^(https?\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)(\/[^?#]*)(\?[^#]*|)(#.*|)$/);if(z){var $={protocol:z[1],host:z[2],hostname:z[3],port:z[4],pathname:z[5],search:z[6],hash:z[7],params:{}};if($.search.length>0){var k=$.search.substring(1);$.params=k.split("&").map(function(E){return E.split("=")}).reduce(function(E,q){return E.hasOwnProperty(q[0])?Array.isArray(E[q[0]])?E[q[0]].push(q[1]):E[q[0]]=[E[q[0]],q[1]]:E[q[0]]=q[1],E},{})}return $}throw new Qe("Incorrect URI: "+F)}function At(F,z){var $=yn(z),k={method:F,host:$.host,path:$.pathname};return $.params&&(k.params=$.params),k}function ua(F,z,$,k,E){return{to:At(F,z),headers:$,body:k,grant:E}}var ca=function(){function F(z,$,k){L.default(this,F),this.config=k,this.transport=z,this.pendingMessages=[],this.twilsock=$}return V.default(F,[{key:"saveMessage",value:function($){var k=this;return new Promise(function(E,q){var M={message:$,resolve:E,reject:q,alreadyRejected:!1,timeout:setTimeout(function(){ze.debug("request is timed out"),q(new Qe("request '".concat($.to.method,"' to '").concat($.to.host,"' timed out"))),M.alreadyRejected=!0},Oi)};k.pendingMessages.push(M)})}},{key:"sendPendingMessages",value:function(){for(var $=this,k=function(){var M=$.pendingMessages[0];if(!M.alreadyRejected)try{var ve=M.message;$.actualSend(ve).then(function(fe){return M.resolve(fe)}).catch(function(fe){return M.reject(fe)}),clearTimeout(M.timeout)}catch(fe){return ze.debug("Failed to send pending message",fe),"break"}$.pendingMessages.splice(0,1)};this.pendingMessages.length>0;){var E=k();if(E==="break")break}}},{key:"rejectPendingMessages",value:function(){var $=this;this.pendingMessages.forEach(function(k){k.reject(new gn("Unable to connect: "+$.twilsock.getTerminationReason)),k.alreadyRejected=!0,clearTimeout(k.timeout)}),this.pendingMessages.splice(0,this.pendingMessages.length)}},{key:"actualSend",value:function(){var z=J.default(Te.default.mark(function k(E){var q,M,ve,fe,Ae,Be,ot,$r;return Te.default.wrap(function(br){for(;;)switch(br.prev=br.next){case 0:return M=E.to,ve=E.headers,fe=E.body,Ae=(q=E.grant)!==null&&q!==void 0?q:this.config.activeGrant,Be={host:M.host,path:M.path,method:M.method,params:M.params,headers:ve},ot=new ye(Ae,ve["Content-Type"]||"application/json",Be),ze.trace("Sending upstream message",ot),br.next=9,this.transport.sendWithReply(ot,fe);case 9:if($r=br.sent,ze.trace("Received upstream message response",$r),!(qa($r)&&!Ai($r.header.http_status.code))){br.next=13;break}throw new ci($r.header.http_status.code,$r.header.http_status.status,$r.body);case 13:return br.abrupt("return",{status:$r.header.http_status,headers:$r.header.http_headers,body:$r.body});case 14:case"end":return br.stop()}},k,this)}));function $(k){return z.apply(this,arguments)}return $}()},{key:"send",value:function($,k){var E=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},q=arguments.length>3?arguments[3]:void 0,M=arguments.length>4?arguments[4]:void 0;if(this.twilsock.isTerminalState)return Promise.reject(new gn("Unable to connect: "+this.twilsock.getTerminationReason));var ve=ua($,k,E,q,M);return this.twilsock.isConnected?this.actualSend(ve):this.saveMessage(ve)}}]),F}(),Pi=function(){function F(){var z=this;L.default(this,F),this._promise=new Promise(function($,k){z._resolve=$,z._reject=k})}return V.default(F,[{key:"promise",get:function(){return this._promise}},{key:"update",value:function($){this._resolve($)}},{key:"set",value:function($){this._resolve($)}},{key:"fail",value:function($){this._reject($)}}]),F}(),Mi=function(){function F(z){L.default(this,F),this.id=z}return V.default(F,null,[{key:"create",value:function($){if($ instanceof Object&&"storage_id"in $)return new F($.storage_id);throw new Qe('Field "storage_id" is missing')}}]),F}(),li=function(){function F(){return L.default(this,F),pe.default(this,"initializedFlag","twilio_twilsock_token_storage"),pe.default(this,"tokenStoragePrefix","twilio_continuation_token_"),F._instance||(this.initialize(),F._instance=this),F._instance}return V.default(F,[{key:"sessionStorage",value:function(){try{return t.sessionStorage}catch{return null}}},{key:"window",value:function(){try{return t.window}catch{return null}}},{key:"storeToken",value:function($,k){this.canStore()&&this.sessionStorage.setItem(this.getKeyName(k),$)}},{key:"getStoredToken",value:function($){return this.canStore()?this.sessionStorage.getItem(this.getKeyName($)):null}},{key:"initialize",value:function(){var $=this;if(this.canStore()){var k=this.sessionStorage.getItem(this.initializedFlag);k&&this.clear(),this.sessionStorage.setItem(this.initializedFlag,"true");var E=this.sessionStorage.removeItem;this.window.addEventListener("unload",function(){E($.initializedFlag)})}}},{key:"clear",value:function(){if(this.canStore()){for(var $=[],k=0;k<this.sessionStorage.length;k++){var E=this.sessionStorage.key(k);E&&E.indexOf(this.tokenStoragePrefix)===0&&$.push(E)}var q=this.sessionStorage.removeItem;$.forEach(function(M){return q(M)}),q(this.initializedFlag)}}},{key:"getKeyName",value:function($){return"".concat(this.tokenStoragePrefix).concat($)}},{key:"canStore",value:function(){return!!(this.sessionStorage&&this.sessionStorage.length&&this.window)}}]),F}();pe.default(li,"_instance",null);var Hn=new li,kr=function(){function F(z,$,k,E,q,M){L.default(this,F),this.title=z,this.details=$,this.start=k,this.type=q,this.id=M,this.end=E}return V.default(F,[{key:"toTelemetryEvent",value:function(){var $=new Date,k=this.start,E=this.end?this.end:$;if(E<k){var q=E;E=k,k=q}var M=k.getTime()-$.getTime(),ve=E.getTime()-$.getTime(),fe=new K(M,ve,this.title,this.details,this.id,this.type);return fe}}]),F}();e.TelemetryPoint=void 0,function(F){F[F.Start=0]="Start",F[F.End=1]="End"}(e.TelemetryPoint||(e.TelemetryPoint={})),e.EventSendingLimitation=void 0,function(F){F[F.MinEventsPortion=0]="MinEventsPortion",F[F.AnyEvents=1]="AnyEvents",F[F.AnyEventsIncludingUnfinished=2]="AnyEventsIncludingUnfinished"}(e.EventSendingLimitation||(e.EventSendingLimitation={}));var la=function(){function F(z,$){L.default(this,F),pe.default(this,"minEventsPortionToSend",50),pe.default(this,"maxEventsPortionToSend",100),pe.default(this,"pendingEvents",new Map),pe.default(this,"readyEvents",[]),pe.default(this,"hasInitializationFinished",!1),pe.default(this,"_canSendTelemetry",!1),this.config=z,this.packetInterface=$}return V.default(F,[{key:"isTelemetryEnabled",get:function(){return this.config.confirmedCapabilities.has("telemetry.v1")}},{key:"canSendTelemetry",get:function(){return this._canSendTelemetry&&this.isTelemetryEnabled},set:function($){ze.debug("TelemetryTracker.canSendTelemetry: ".concat($," TelemetryTracker.isTelemetryEnabled: ").concat(this.isTelemetryEnabled)),this._canSendTelemetry&&!$&&(this.pendingEvents.clear(),this.readyEvents=[]),this._canSendTelemetry=$,$&&this.sendTelemetry(e.EventSendingLimitation.AnyEvents),$&&!this.hasInitializationFinished&&(this.hasInitializationFinished=!0)}},{key:"addTelemetryEvent",value:function($){!this.canSendTelemetry&&this.hasInitializationFinished||this.readyEvents.push($)}},{key:"addPartialEvent",value:function($,k,E){ze.debug("Adding ".concat(E===e.TelemetryPoint.Start?"starting":"ending"," timepoint for '").concat(k,"' event"));var q=this.pendingEvents.has(k);if(E===e.TelemetryPoint.Start)q&&ze.debug("Overwriting starting point for '".concat(k,"' event")),this.pendingEvents.set(k,$);else{if(!q){ze.info("Could not find started event for '".concat(k,"' event"));return}this.addTelemetryEvent(this.merge(this.pendingEvents.get(k),$)),this.pendingEvents.delete(k)}}},{key:"getTelemetryToSend",value:function($){return!this.canSendTelemetry||this.readyEvents.length==0?[]:$==e.EventSendingLimitation.MinEventsPortion&&this.readyEvents.length<this.minEventsPortionToSend?[]:this.getTelemetryPortion($==e.EventSendingLimitation.AnyEventsIncludingUnfinished)}},{key:"getTelemetryPortion",value:function($){var k=this,E=Math.min(this.readyEvents.length,this.maxEventsPortionToSend),q=this.readyEvents.splice(0,E);return $&&q.length<this.maxEventsPortionToSend&&this.pendingEvents.forEach(function(M,ve){if(!(q.length>=k.maxEventsPortionToSend)){var fe=k.pendingEvents.get(ve);k.pendingEvents.delete(ve),q.push(new kr("[UNFINISHED] ".concat(fe.title),fe.details,fe.start,null,fe.type,fe.id))}}),q}},{key:"merge",value:function($,k){return new kr(k.title?k.title:$.title,k.details?k.details:$.details,$.start,k.end,k.type?k.type:$.type,k.id?k.id:$.id)}},{key:"sendTelemetryIfMinimalPortionCollected",value:function(){this.sendTelemetry(e.EventSendingLimitation.MinEventsPortion)}},{key:"sendTelemetry",value:function($){var k=this.getTelemetryToSend($);if(k.length!==0)try{this.packetInterface.send(new oe(k.map(function(E){return E.toTelemetryEvent()})))}catch(E){ze.debug("Error while sending ".concat(k.length," telemetry events due to ").concat(E,"; they will be resubmitted")),this.readyEvents=this.readyEvents.concat(k)}}}]),F}();function Rr(F){var z=Vr();return function(){var k=ge.default(F),E;if(z){var q=ge.default(this).constructor;E=Reflect.construct(k,arguments,q)}else E=k.apply(this,arguments);return ee.default(this,E)}}function Vr(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var bn=function F(){L.default(this,F)};pe.default(bn,"TWILSOCK_CONNECT","twilsock.sdk.connect"),pe.default(bn,"TWILSOCK_INIT","twilsock.sdk.init"),e.TwilsockClient=function(F){ue.default($,F);var z=Rr($);function $(k,E,q){var M;L.default(this,$),M=z.call(this),pe.default(D.default(M),"version",Tr),pe.default(D.default(M),"offlineStorageDeferred",new Pi),q.continuationToken=q.continuationToken?q.continuationToken:Hn.getStoredToken(E);var ve=M.config=new mr(k,E,q);ze.setLevel(ve.logLevel);var fe=new Hr(ve.url),Ae=new Mr(fe,ve);return M.channel=new Mt(fe,Ae,ve),M.registrations=new Fa(Ae),M.upstream=new ca(Ae,M.channel,ve),M.telemetryTracker=new la(ve,Ae),M.channel.on("initialized",function(){return M.telemetryTracker.canSendTelemetry=!0}),fe.on("disconnected",function(){return M.telemetryTracker.canSendTelemetry=!1}),M.registrations.on("registered",function(Be){return M.emit("registered",Be)}),M.channel.on("message",function(Be,ot){return setTimeout(function(){return M.emit("message",Be,ot)},0)}),M.channel.on("stateChanged",function(Be){return setTimeout(function(){return M.emit("stateChanged",Be)},0)}),M.channel.on("connectionError",function(Be){return setTimeout(function(){return M.emit("connectionError",Be)},0)}),M.channel.on("tokenAboutToExpire",function(){return setTimeout(function(){return M.emit("tokenAboutToExpire")},0)}),M.channel.on("tokenExpired",function(){return setTimeout(function(){return M.emit("tokenExpired")},0)}),M.channel.on("connected",function(){return M.registrations.updateRegistrations()}),M.channel.on("connected",function(){return M.upstream.sendPendingMessages()}),M.channel.on("connected",function(){return setTimeout(function(){return M.emit("connected")},0)}),M.channel.on("beforeConnect",function(){return M.telemetryTracker.addPartialEvent(new kr("Establish WebSocket connection","",new Date),bn.TWILSOCK_CONNECT,e.TelemetryPoint.Start)}),M.channel.on("connected",function(){return M.telemetryTracker.addPartialEvent(new kr("Establish WebSocket connection","",new Date,new Date),bn.TWILSOCK_CONNECT,e.TelemetryPoint.End)}),M.channel.on("beforeSendInit",function(){return M.telemetryTracker.addPartialEvent(new kr("Send Twilsock init","",new Date),bn.TWILSOCK_INIT,e.TelemetryPoint.Start)}),M.channel.on("initialized",function(){return M.telemetryTracker.addPartialEvent(new kr("Send Twilsock init","Succeeded",new Date,new Date),bn.TWILSOCK_INIT,e.TelemetryPoint.End)}),M.channel.on("sendInitFailed",function(){return M.telemetryTracker.addPartialEvent(new kr("Send Twilsock init","Failed",new Date,new Date),bn.TWILSOCK_INIT,e.TelemetryPoint.End)}),M.channel.on("initialized",function(Be){M.handleStorageId(E,Be),Hn.storeToken(Be.continuationToken,E),setTimeout(function(){return M.emit("initialized",Be)},0)}),M.channel.on("disconnected",function(){return setTimeout(function(){return M.emit("disconnected")},0)}),M.channel.on("disconnected",function(){return M.upstream.rejectPendingMessages()}),M.channel.on("disconnected",function(){return M.offlineStorageDeferred.fail(new Qe("Client disconnected"))}),M.offlineStorageDeferred.promise.catch(function(){}),M}return V.default($,[{key:"emit",value:function(E){for(var q,M=arguments.length,ve=new Array(M>1?M-1:0),fe=1;fe<M;fe++)ve[fe-1]=arguments[fe];return ze.debug("Emitting ".concat(E.toString(),"(").concat(ve.map(function(Ae){return JSON.stringify(Ae)}).join(", "),")")),(q=te.default(ge.default($.prototype),"emit",this)).call.apply(q,[this,E].concat(ve))}},{key:"handleStorageId",value:function(E,q){if(!q.offlineStorage)this.offlineStorageDeferred.fail(new Qe("No offline storage id"));else if(q.offlineStorage.hasOwnProperty(E))try{this.offlineStorageDeferred.set(Mi.create(q.offlineStorage[E])),ze.debug("Offline storage for '".concat(E,"' product: ").concat(JSON.stringify(q.offlineStorage[E]),"."))}catch(M){this.offlineStorageDeferred.fail(new Qe("Failed to parse offline storage for ".concat(E," ").concat(JSON.stringify(q.offlineStorage[E]),". ").concat(M,".")))}else this.offlineStorageDeferred.fail(new Qe("No offline storage id for '".concat(E,"' product: ").concat(JSON.stringify(q.offlineStorage))))}},{key:"storageId",value:function(){return this.offlineStorageDeferred.promise}},{key:"isConnected",get:function(){return this.channel.isConnected}},{key:"state",get:function(){return this.channel.state}},{key:"updateToken",value:function(){var k=J.default(Te.default.mark(function q(M){return Te.default.wrap(function(fe){for(;;)switch(fe.prev=fe.next){case 0:if(ze.trace("updating token '".concat(M,"'")),this.config.token!==M){fe.next=3;break}return fe.abrupt("return");case 3:return this.config.updateToken(M),fe.next=6,this.channel.updateToken(M);case 6:return fe.abrupt("return",fe.sent);case 7:case"end":return fe.stop()}},q,this)}));function E(q){return k.apply(this,arguments)}return E}()},{key:"setNotificationsContext",value:function(){var k=J.default(Te.default.mark(function q(M,ve){return Te.default.wrap(function(Ae){for(;;)switch(Ae.prev=Ae.next){case 0:return Ae.next=2,this.registrations.setNotificationsContext(M,ve);case 2:case"end":return Ae.stop()}},q,this)}));function E(q,M){return k.apply(this,arguments)}return E}()},{key:"removeNotificationsContext",value:function(){var k=J.default(Te.default.mark(function q(M){return Te.default.wrap(function(fe){for(;;)switch(fe.prev=fe.next){case 0:return fe.next=2,this.registrations.removeNotificationsContext(M);case 2:case"end":return fe.stop()}},q,this)}));function E(q){return k.apply(this,arguments)}return E}()},{key:"connect",value:function(){return this.channel.connect()}},{key:"disconnect",value:function(){var k=J.default(Te.default.mark(function q(){return Te.default.wrap(function(ve){for(;;)switch(ve.prev=ve.next){case 0:return this.telemetryTracker.sendTelemetry(e.EventSendingLimitation.AnyEventsIncludingUnfinished),ve.next=3,this.channel.disconnect();case 3:return ve.abrupt("return",ve.sent);case 4:case"end":return ve.stop()}},q,this)}));function E(){return k.apply(this,arguments)}return E}()},{key:"get",value:function(){var k=J.default(Te.default.mark(function q(M,ve,fe){return Te.default.wrap(function(Be){for(;;)switch(Be.prev=Be.next){case 0:return this.telemetryTracker.sendTelemetry(e.EventSendingLimitation.AnyEvents),Be.next=3,this.upstream.send("GET",M,ve,void 0,fe);case 3:return Be.abrupt("return",Be.sent);case 4:case"end":return Be.stop()}},q,this)}));function E(q,M,ve){return k.apply(this,arguments)}return E}()},{key:"post",value:function(){var k=J.default(Te.default.mark(function q(M,ve,fe,Ae){return Te.default.wrap(function(ot){for(;;)switch(ot.prev=ot.next){case 0:return this.telemetryTracker.sendTelemetry(e.EventSendingLimitation.AnyEvents),ot.next=3,this.upstream.send("POST",M,ve,fe,Ae);case 3:return ot.abrupt("return",ot.sent);case 4:case"end":return ot.stop()}},q,this)}));function E(q,M,ve,fe){return k.apply(this,arguments)}return E}()},{key:"put",value:function(){var k=J.default(Te.default.mark(function q(M,ve,fe,Ae){return Te.default.wrap(function(ot){for(;;)switch(ot.prev=ot.next){case 0:return this.telemetryTracker.sendTelemetry(e.EventSendingLimitation.AnyEvents),ot.next=3,this.upstream.send("PUT",M,ve,fe,Ae);case 3:return ot.abrupt("return",ot.sent);case 4:case"end":return ot.stop()}},q,this)}));function E(q,M,ve,fe){return k.apply(this,arguments)}return E}()},{key:"delete",value:function(){var k=J.default(Te.default.mark(function q(M,ve,fe,Ae){return Te.default.wrap(function(ot){for(;;)switch(ot.prev=ot.next){case 0:return this.telemetryTracker.sendTelemetry(e.EventSendingLimitation.AnyEvents),ot.next=3,this.upstream.send("DELETE",M,ve,fe,Ae);case 3:return ot.abrupt("return",ot.sent);case 4:case"end":return ot.stop()}},q,this)}));function E(q,M,ve,fe){return k.apply(this,arguments)}return E}()},{key:"addTelemetryEvent",value:function(E){this.telemetryTracker.addTelemetryEvent(E),this.telemetryTracker.sendTelemetryIfMinimalPortionCollected()}},{key:"addPartialTelemetryEvent",value:function(E,q,M){this.telemetryTracker.addPartialEvent(E,q,M),M===e.TelemetryPoint.End&&this.telemetryTracker.sendTelemetryIfMinimalPortionCollected()}}]),$}(_e),e.TwilsockClient=P([m.validateConstructorTypes(m.nonEmptyString,m.nonEmptyString,[m.pureObject,"undefined",m.literal(null)]),Ie("design:paramtypes",[String,String,Object])],e.TwilsockClient);var fa=function(){function F(z){L.default(this,F),this.product=z,this.type="ers",this.notification_protocol_version=0,this.message_types=[]}return V.default(F,[{key:"populateInitRegistrations",value:function($){var k=new Set(this.message_types);for(var E in $)k.add($[E]);this.message_types=Array.from(k)}}]),F}();e.InitRegistration=fa,e.TelemetryEventDescription=kr,e.TelemetryTracker=la,e.TransportUnavailableError=gn,e.Twilsock=e.TwilsockClient,e.TwilsockError=Qe})(xf);var v1={},oS=er,K9=wt,J9=Yt,Y9=yt,kp=$u,X9=ku,Q9=wu,Z9=Jr,eK=Su,As=Object.assign,uS=Object.defineProperty,tK=K9([].concat),m1=!As||Y9(function(){if(oS&&As({b:1},As(uS({},"a",{enumerable:!0,get:function(){uS(this,"b",{value:3,enumerable:!1})}}),{b:2})).b!==1)return!0;var e={},t={},r=Symbol("assign detection"),n="abcdefghijklmnopqrst";return e[r]=7,n.split("").forEach(function(i){t[i]=i}),As({},e)[r]!==7||kp(As({},t)).join("")!==n})?function(t,r){for(var n=Z9(t),i=arguments.length,a=1,s=X9.f,o=Q9.f;i>a;)for(var u=eK(arguments[a++]),c=s?tK(kp(u),s(u)):kp(u),l=c.length,p=0,v;l>p;)v=c[p++],(!oS||J9(o,u,v))&&(n[v]=u[v]);return n}:As,rK=Ct,cS=m1;rK({target:"Object",stat:!0,arity:2,forced:Object.assign!==cS},{assign:cS});var sv={exports:{}},lS=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof window.msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto);if(lS){var fS=new Uint8Array(16);sv.exports=function(){return lS(fS),fS}}else{var dS=new Array(16);sv.exports=function(){for(var t=0,r;t<16;t++)t&3||(r=Math.random()*4294967296),dS[t]=r>>>((t&3)<<3)&255;return dS}}var g1=sv.exports,y1=[];for(var Nc=0;Nc<256;++Nc)y1[Nc]=(Nc+256).toString(16).substr(1);function nK(e,t){var r=t||0,n=y1;return[n[e[r++]],n[e[r++]],n[e[r++]],n[e[r++]],"-",n[e[r++]],n[e[r++]],"-",n[e[r++]],n[e[r++]],"-",n[e[r++]],n[e[r++]],"-",n[e[r++]],n[e[r++]],n[e[r++]],n[e[r++]],n[e[r++]],n[e[r++]]].join("")}var b1=nK,iK=g1,aK=b1,pS,Rp,$p=0,Ip=0;function sK(e,t,r){var n=t&&r||0,i=t||[];e=e||{};var a=e.node||pS,s=e.clockseq!==void 0?e.clockseq:Rp;if(a==null||s==null){var o=iK();a==null&&(a=pS=[o[0]|1,o[1],o[2],o[3],o[4],o[5]]),s==null&&(s=Rp=(o[6]<<8|o[7])&16383)}var u=e.msecs!==void 0?e.msecs:new Date().getTime(),c=e.nsecs!==void 0?e.nsecs:Ip+1,l=u-$p+(c-Ip)/1e4;if(l<0&&e.clockseq===void 0&&(s=s+1&16383),(l<0||u>$p)&&e.nsecs===void 0&&(c=0),c>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");$p=u,Ip=c,Rp=s,u+=122192928e5;var p=((u&268435455)*1e4+c)%4294967296;i[n++]=p>>>24&255,i[n++]=p>>>16&255,i[n++]=p>>>8&255,i[n++]=p&255;var v=u/4294967296*1e4&268435455;i[n++]=v>>>8&255,i[n++]=v&255,i[n++]=v>>>24&15|16,i[n++]=v>>>16&255,i[n++]=s>>>8|128,i[n++]=s&255;for(var m=0;m<6;++m)i[n+m]=a[m];return t||aK(i)}var oK=sK,uK=g1,cK=b1;function lK(e,t,r){var n=t&&r||0;typeof e=="string"&&(t=e==="binary"?new Array(16):null,e=null),e=e||{};var i=e.random||(e.rng||uK)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t)for(var a=0;a<16;++a)t[n+a]=i[a];return t||cK(i)}var fK=lK,dK=oK,_1=fK,kg=_1;kg.v1=dK;kg.v4=_1;var pK=kg;/*
169
169
  @license
170
170
  The MIT License (MIT)
171
171
 
@@ -189,7 +189,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
189
189
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
190
190
  SOFTWARE.
191
191
 
192
- */(function(e){Object.defineProperty(e,"__esModule",{value:!0});var t=Nu,r=$i,n=Aa,i=ki,a=Ri,s=zn,o=Uu,u=qn,c=xf,l=ms,p=gs,v=na,m=bo,b=_o,T=Ar,I=pK,R=zr;function x(ye){return ye&&typeof ye=="object"&&"default"in ye?ye:{default:ye}}function N(ye){if(ye&&ye.__esModule)return ye;var we=Object.create(null);return ye&&Object.keys(ye).forEach(function(se){if(se!=="default"){var me=Object.getOwnPropertyDescriptor(ye,se);Object.defineProperty(we,se,me.get?me:{enumerable:!0,get:function(){return ye[se]}})}}),we.default=ye,Object.freeze(we)}var j=x(t),X=x(r),J=x(n),V=x(i),D=x(a),te=x(s),ue=x(o),ee=x(u),ge=x(l),L=x(p),pe=x(m),Te=x(b),rt=N(T),Ke=N(I);function Se(ye,we,se,me){var le=arguments.length,be=le<3?we:me===null?me=Object.getOwnPropertyDescriptor(we,se):me,$e;if((typeof Reflect>"u"?"undefined":ee.default(Reflect))==="object"&&typeof Reflect.decorate=="function")be=Reflect.decorate(ye,we,se,me);else for(var re=ye.length-1;re>=0;re--)($e=ye[re])&&(be=(le<3?$e(be):le>3?$e(we,se,be):$e(we,se))||be);return le>3&&be&&Object.defineProperty(we,se,be),be}function ce(ye,we){if((typeof Reflect>"u"?"undefined":ee.default(Reflect))==="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(ye,we)}var he;function P(){}P.prototype=Object.create(null);function Ie(){Ie.init.call(this)}Ie.EventEmitter=Ie,Ie.usingDomains=!1,Ie.prototype.domain=void 0,Ie.prototype._events=void 0,Ie.prototype._maxListeners=void 0,Ie.defaultMaxListeners=10,Ie.init=function(){this.domain=null,Ie.usingDomains&&he.active,(!this._events||this._events===Object.getPrototypeOf(this)._events)&&(this._events=new P,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},Ie.prototype.setMaxListeners=function(we){if(typeof we!="number"||we<0||isNaN(we))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=we,this};function qe(ye){return ye._maxListeners===void 0?Ie.defaultMaxListeners:ye._maxListeners}Ie.prototype.getMaxListeners=function(){return qe(this)};function Ne(ye,we,se){if(we)ye.call(se);else for(var me=ye.length,le=ke(ye,me),be=0;be<me;++be)le[be].call(se)}function _e(ye,we,se,me){if(we)ye.call(se,me);else for(var le=ye.length,be=ke(ye,le),$e=0;$e<le;++$e)be[$e].call(se,me)}function Q(ye,we,se,me,le){if(we)ye.call(se,me,le);else for(var be=ye.length,$e=ke(ye,be),re=0;re<be;++re)$e[re].call(se,me,le)}function kt(ye,we,se,me,le,be){if(we)ye.call(se,me,le,be);else for(var $e=ye.length,re=ke(ye,$e),ae=0;ae<$e;++ae)re[ae].call(se,me,le,be)}function Ce(ye,we,se,me){if(we)ye.apply(se,me);else for(var le=ye.length,be=ke(ye,le),$e=0;$e<le;++$e)be[$e].apply(se,me)}Ie.prototype.emit=function(we){var se,me,le,be,$e,re,ae,K=we==="error";if(re=this._events,re)K=K&&re.error==null;else if(!K)return!1;if(ae=this.domain,K){if(se=arguments[1],ae)se||(se=new Error('Uncaught, unspecified "error" event')),se.domainEmitter=this,se.domain=ae,se.domainThrown=!1,ae.emit("error",se);else{if(se instanceof Error)throw se;var oe=new Error('Uncaught, unspecified "error" event. ('+se+")");throw oe.context=se,oe}return!1}if(me=re[we],!me)return!1;var Y=typeof me=="function";switch(le=arguments.length,le){case 1:Ne(me,Y,this);break;case 2:_e(me,Y,this,arguments[1]);break;case 3:Q(me,Y,this,arguments[1],arguments[2]);break;case 4:kt(me,Y,this,arguments[1],arguments[2],arguments[3]);break;default:for(be=new Array(le-1),$e=1;$e<le;$e++)be[$e-1]=arguments[$e];Ce(me,Y,this,be)}return!0};function de(ye,we,se,me){var le,be,$e;if(typeof se!="function")throw new TypeError('"listener" argument must be a function');if(be=ye._events,be?(be.newListener&&(ye.emit("newListener",we,se.listener?se.listener:se),be=ye._events),$e=be[we]):(be=ye._events=new P,ye._eventsCount=0),!$e)$e=be[we]=se,++ye._eventsCount;else if(typeof $e=="function"?$e=be[we]=me?[se,$e]:[$e,se]:me?$e.unshift(se):$e.push(se),!$e.warned&&(le=qe(ye),le&&le>0&&$e.length>le)){$e.warned=!0;var re=new Error("Possible EventEmitter memory leak detected. "+$e.length+" "+we+" listeners added. Use emitter.setMaxListeners() to increase limit");re.name="MaxListenersExceededWarning",re.emitter=ye,re.type=we,re.count=$e.length,Rt(re)}return ye}function Rt(ye){typeof console.warn=="function"?console.warn(ye):console.log(ye)}Ie.prototype.addListener=function(we,se){return de(this,we,se,!1)},Ie.prototype.on=Ie.prototype.addListener,Ie.prototype.prependListener=function(we,se){return de(this,we,se,!0)};function Ue(ye,we,se){var me=!1;function le(){ye.removeListener(we,le),me||(me=!0,se.apply(ye,arguments))}return le.listener=se,le}Ie.prototype.once=function(we,se){if(typeof se!="function")throw new TypeError('"listener" argument must be a function');return this.on(we,Ue(this,we,se)),this},Ie.prototype.prependOnceListener=function(we,se){if(typeof se!="function")throw new TypeError('"listener" argument must be a function');return this.prependListener(we,Ue(this,we,se)),this},Ie.prototype.removeListener=function(we,se){var me,le,be,$e,re;if(typeof se!="function")throw new TypeError('"listener" argument must be a function');if(le=this._events,!le)return this;if(me=le[we],!me)return this;if(me===se||me.listener&&me.listener===se)--this._eventsCount===0?this._events=new P:(delete le[we],le.removeListener&&this.emit("removeListener",we,me.listener||se));else if(typeof me!="function"){for(be=-1,$e=me.length;$e-- >0;)if(me[$e]===se||me[$e].listener&&me[$e].listener===se){re=me[$e].listener,be=$e;break}if(be<0)return this;if(me.length===1){if(me[0]=void 0,--this._eventsCount===0)return this._events=new P,this;delete le[we]}else mt(me,be);le.removeListener&&this.emit("removeListener",we,re||se)}return this},Ie.prototype.off=function(ye,we){return this.removeListener(ye,we)},Ie.prototype.removeAllListeners=function(we){var se,me;if(me=this._events,!me)return this;if(!me.removeListener)return arguments.length===0?(this._events=new P,this._eventsCount=0):me[we]&&(--this._eventsCount===0?this._events=new P:delete me[we]),this;if(arguments.length===0){for(var le=Object.keys(me),be=0,$e;be<le.length;++be)$e=le[be],$e!=="removeListener"&&this.removeAllListeners($e);return this.removeAllListeners("removeListener"),this._events=new P,this._eventsCount=0,this}if(se=me[we],typeof se=="function")this.removeListener(we,se);else if(se)do this.removeListener(we,se[se.length-1]);while(se[0]);return this},Ie.prototype.listeners=function(we){var se,me,le=this._events;return le?(se=le[we],se?typeof se=="function"?me=[se.listener||se]:me=ft(se):me=[]):me=[],me},Ie.listenerCount=function(ye,we){return typeof ye.listenerCount=="function"?ye.listenerCount(we):Dt.call(ye,we)},Ie.prototype.listenerCount=Dt;function Dt(ye){var we=this._events;if(we){var se=we[ye];if(typeof se=="function")return 1;if(se)return se.length}return 0}Ie.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};function mt(ye,we){for(var se=we,me=se+1,le=ye.length;me<le;se+=1,me+=1)ye[se]=ye[me];ye.pop()}function ke(ye,we){for(var se=new Array(we);we--;)se[we]=ye[we];return se}function ft(ye){for(var we=new Array(ye.length),se=0;se<we.length;++se)we[se]=ye[se].listener||ye[se];return we}var St=rt.getLogger("twilio-notificatiions");function Oe(ye,we){return["".concat(new Date().toISOString()," Twilio.Notifications ").concat(ye,":")].concat(Array.from(we))}var Bt=function(){function ye(){X.default(this,ye)}return J.default(ye,[{key:"setLevel",value:function(se){St.setLevel(se)}},{key:"trace",value:function(){if(St.getLevel()==St.levels.TRACE){for(var se=arguments.length,me=new Array(se),le=0;le<se;le++)me[le]=arguments[le];St.debug.apply(null,Oe("T",me))}}},{key:"debug",value:function(){for(var se=arguments.length,me=new Array(se),le=0;le<se;le++)me[le]=arguments[le];St.debug.apply(null,Oe("D",me))}},{key:"info",value:function(){for(var se=arguments.length,me=new Array(se),le=0;le<se;le++)me[le]=arguments[le];St.info.apply(null,Oe("I",me))}},{key:"warn",value:function(){for(var se=arguments.length,me=new Array(se),le=0;le<se;le++)me[le]=arguments[le];St.warn.apply(null,Oe("W",me))}},{key:"error",value:function(){for(var se=arguments.length,me=new Array(se),le=0;le<se;le++)me[le]=arguments[le];St.error.apply(null,Oe("E",me))}}]),ye}(),vt=new Bt;function qt(ye){var we=sr();return function(){var me=te.default(ye),le;if(we){var be=te.default(this).constructor;le=Reflect.construct(me,arguments,be)}else le=me.apply(this,arguments);return D.default(this,le)}}function sr(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var ze=J.default(function ye(){var we=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"",se=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"",me=arguments.length>2&&arguments[2]!==void 0?arguments[2]:new Set;X.default(this,ye),this.token=we,this.notificationId=se,this.messageTypes=me});function Tr(ye,we){return[].concat(Te.default(Te.default(ye).filter(function(se){return!we.has(se)})),Te.default(Te.default(we).filter(function(se){return!ye.has(se)})))}function mr(ye,we){var se=new Set;return ye.notificationId!==we.notificationId&&se.add("notificationId"),ye.token!==we.token&&se.add("token"),Tr(ye.messageTypes,we.messageTypes).length>0&&se.add("messageType"),[se.size>0,se]}var Et=function(ye){V.default(se,ye);var we=qt(se);function se(me){var le;return X.default(this,se),le=we.call(this),L.default(ge.default(le),"desiredState",new ze),L.default(ge.default(le),"currentState",new ze),L.default(ge.default(le),"_hasActiveAttempt",!1),le.channelType=me,le}return J.default(se,[{key:"setNotificationId",value:function(le){this.desiredState.notificationId=le}},{key:"isActive",value:function(){return this.desiredState.notificationId!==""}},{key:"subscribe",value:function(le){if(this.desiredState.messageTypes.has(le)){vt.debug("message type '".concat(le,"' for channel ").concat(this.channelType," is already registered"));return}this.desiredState.messageTypes.add(le)}},{key:"unsubscribe",value:function(le){this.desiredState.messageTypes.has(le)&&this.desiredState.messageTypes.delete(le)}},{key:"updateToken",value:function(le){this.desiredState.token=le}},{key:"commitChanges",value:function(){var me=j.default(ue.default.mark(function be(){var $e,re,ae,K,oe,Y;return ue.default.wrap(function(Re){for(;;)switch(Re.prev=Re.next){case 0:if(!this._hasActiveAttempt){Re.next=3;break}throw vt.error("One registration attempt is already in progress"),new Error("One registration attempt is already in progress");case 3:if($e=mr(this.desiredState,this.currentState),re=pe.default($e,2),ae=re[0],K=re[1],ae){Re.next=6;break}return Re.abrupt("return");case 6:if(this.currentState.notificationId||K.delete("notificationId"),vt.trace("Persisting ".concat(this.channelType," registration"),K,this.desiredState),Re.prev=8,this._hasActiveAttempt=!0,oe=new ze,oe.token=this.desiredState.token,oe.notificationId=this.desiredState.notificationId,oe.messageTypes=new Set(this.desiredState.messageTypes),!(oe.messageTypes.size>0)){Re.next=24;break}return Re.next=17,this.updateRegistration(oe,K);case 17:Y=Re.sent,this.currentState.token=Y.token,this.currentState.notificationId=Y.notificationId,this.currentState.messageTypes=new Set(Y.messageTypes),this.emit("stateChanged",this.channelType,"registered",this.currentState),Re.next=30;break;case 24:return Re.next=26,this.removeRegistration();case 26:this.currentState.token=oe.token,this.currentState.notificationId=oe.notificationId,this.currentState.messageTypes.clear(),this.emit("stateChanged",this.channelType,"unregistered",this.currentState);case 30:Re.next=35;break;case 32:throw Re.prev=32,Re.t0=Re.catch(8),Re.t0;case 35:return Re.prev=35,this._hasActiveAttempt=!1,Re.finish(35);case 38:case"end":return Re.stop()}},be,this,[[8,32,35,38]])}));function le(){return me.apply(this,arguments)}return le}()}]),se}(Ie);function It(ye){var we=bt();return function(){var me=te.default(ye),le;if(we){var be=te.default(this).constructor;le=Reflect.construct(me,arguments,be)}else le=me.apply(this,arguments);return D.default(this,le)}}function bt(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var ct={min:2e3,max:12e4,randomness:.2},Ft=function(ye){V.default(se,ye);var we=It(se);function se(me,le,be,$e){var re;return X.default(this,se),re=we.call(this,me),L.default(ge.default(re),"registrationId",null),re.context=le,re.twilsock=be,re.registrarUrl=$e,re}return J.default(se,[{key:"updateRegistration",value:function(){var me=j.default(ue.default.mark(function be($e,re){var ae=this,K,oe,Y,De,Re;return ue.default.wrap(function(Ge){for(;;)switch(Ge.prev=Ge.next){case 0:if(!re.has("notificationId")){Ge.next=3;break}return Ge.next=3,this.removeRegistration();case 3:if(!(!$e.notificationId||!$e.notificationId.length)){Ge.next=6;break}throw vt.error("No push notification ID for registration"),new Error("No push notification ID for registration");case 6:return vt.trace("Registering",this.channelType,$e),K={endpoint_platform:this.context.platform,channel_type:this.channelType,version:this.context.protocolVersion.toString(),message_types:Array.from($e.messageTypes),data:{registration_id:$e.notificationId}},oe=this.context.productId,Y="".concat(this.registrarUrl,"?productId=").concat(oe),De={"Content-Type":"application/json"},vt.trace("Creating registration for channel ".concat(this.channelType)),Ge.prev=12,Ge.next=15,new v.AsyncRetrier(ct).run(function(){return ae.twilsock.post(Y,De,K,oe)});case 15:Re=Ge.sent,this.registrationId=Re.body.id,vt.debug("Registration created: ",Re),Ge.next=24;break;case 20:throw Ge.prev=20,Ge.t0=Ge.catch(12),vt.error("Registration failed: ",Ge.t0),Ge.t0;case 24:return Ge.abrupt("return",$e);case 25:case"end":return Ge.stop()}},be,this,[[12,20]])}));function le(be,$e){return me.apply(this,arguments)}return le}()},{key:"removeRegistration",value:function(){var me=j.default(ue.default.mark(function be(){var $e=this,re,ae,K;return ue.default.wrap(function(Y){for(;;)switch(Y.prev=Y.next){case 0:if(this.registrationId){Y.next=2;break}return Y.abrupt("return");case 2:return re=this.context.productId,ae="".concat(this.registrarUrl,"/").concat(this.registrationId,"?productId=").concat(re),K={"Content-Type":"application/json"},vt.trace("Removing registration for ".concat(this.channelType)),Y.prev=6,Y.next=9,new v.AsyncRetrier(Object.assign(ct,{maxAttemptsCount:3})).run(function(){return $e.twilsock.delete(ae,K,{},re)});case 9:this.registrationId=null,this.currentState.notificationId="",vt.debug("Registration removed for ".concat(this.channelType)),Y.next=18;break;case 14:throw Y.prev=14,Y.t0=Y.catch(6),vt.error("Failed to remove registration ",this.channelType,Y.t0),Y.t0;case 18:case"end":return Y.stop()}},be,this,[[6,14]])}));function le(){return me.apply(this,arguments)}return le}()},{key:"sendDeviceRemoveRequest",value:function(){var me=j.default(ue.default.mark(function be($e){var re=this,ae,K,oe,Y;return ue.default.wrap(function(Re){for(;;)switch(Re.prev=Re.next){case 0:if($e!==""){Re.next=2;break}throw new Error("Empty registration ID");case 2:return ae=this.context.productId,K="".concat(this.registrarUrl,"?productId=").concat(ae),oe={"Content-Type":"application/json"},Y={binding_type:this.channelType,address:$e},Re.prev=6,vt.trace("Removing old registrations for ".concat(this.channelType)),Re.next=10,new v.AsyncRetrier(Object.assign(ct,{maxAttemptsCount:3})).run(function(){return re.twilsock.delete(K,oe,Y,ae)});case 10:this.registrationId=null,this.currentState.notificationId="",vt.debug("Registration removed for ".concat(this.channelType)),Re.next=19;break;case 15:throw Re.prev=15,Re.t0=Re.catch(6),vt.error("Failed to remove registration ",this.channelType,Re.t0),Re.t0;case 19:case"end":return Re.stop()}},be,this,[[6,15]])}));function le(be){return me.apply(this,arguments)}return le}()}]),se}(Et);function Pt(ye){var we=cr();return function(){var me=te.default(ye),le;if(we){var be=te.default(this).constructor;le=Reflect.construct(me,arguments,be)}else le=me.apply(this,arguments);return D.default(this,le)}}function cr(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var Cr=function(ye){V.default(se,ye);var we=Pt(se);function se(me,le,be){var $e;return X.default(this,se),$e=we.call(this,"twilsock"),L.default(ge.default($e),"contextId",Ke.v4()),$e.productId=me,$e.platform=le,$e.twilsock=be,$e}return J.default(se,[{key:"updateRegistration",value:function(){var me=j.default(ue.default.mark(function be($e,re){var ae,K;return ue.default.wrap(function(Y){for(;;)switch(Y.prev=Y.next){case 0:if(re.has("messageType")){Y.next=2;break}return Y.abrupt("return",$e);case 2:return ae=Array.from($e.messageTypes),K={product_id:this.productId,notification_protocol_version:4,endpoint_platform:this.platform,message_types:ae},Y.prev=4,Y.next=7,this.twilsock.setNotificationsContext(this.contextId,K);case 7:Y.next=13;break;case 9:throw Y.prev=9,Y.t0=Y.catch(4),vt.error("Failed to update twilsock notification context: ".concat(Y.t0)),Y.t0;case 13:return Y.abrupt("return",$e);case 14:case"end":return Y.stop()}},be,this,[[4,9]])}));function le(be,$e){return me.apply(this,arguments)}return le}()},{key:"removeRegistration",value:function(){var me=j.default(ue.default.mark(function be(){return ue.default.wrap(function(re){for(;;)switch(re.prev=re.next){case 0:return re.prev=0,re.next=3,this.twilsock.removeNotificationsContext(this.contextId);case 3:re.next=9;break;case 5:throw re.prev=5,re.t0=re.catch(0),vt.error("Failed to remove twilsock notification context: ".concat(re.t0)),re.t0;case 9:case"end":return re.stop()}},be,this,[[0,5]])}));function le(){return me.apply(this,arguments)}return le}()},{key:"sendDeviceRemoveRequest",value:function(){var me=j.default(ue.default.mark(function be($e){return ue.default.wrap(function(ae){for(;;)switch(ae.prev=ae.next){case 0:case"end":return ae.stop()}},be)}));function le(be){return me.apply(this,arguments)}return le}()}]),se}(Et);function Dr(ye){var we=gr();return function(){var me=te.default(ye),le;if(we){var be=te.default(this).constructor;le=Reflect.construct(me,arguments,be)}else le=me.apply(this,arguments);return D.default(this,le)}}function gr(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var zt,lr=R.literal("apn","fcm","twilsock");e.Notifications=zt=function(ye){V.default(se,ye);var we=Dr(se);function se(me){var le,be,$e,re,ae,K,oe,Y=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};X.default(this,se),oe=we.call(this),Y.logLevel=(le=Y.logLevel)!==null&&le!==void 0?le:"error",vt.setLevel(Y.logLevel);var De=(be=Y.productId)!==null&&be!==void 0?be:"notifications",Re=!Y.twilsockClient,Je=Y.twilsockClient=($e=Y.twilsockClient)!==null&&$e!==void 0?$e:new c.TwilsockClient(me,De,Y),Ge=(re=Y.notifications)!==null&&re!==void 0?re:{},He=(ae=(K=Ge.region)!==null&&K!==void 0?K:Y.region)!==null&&ae!==void 0?ae:"us1",et="https://ers.".concat(He,".twilio.com/v1/registrations"),nt=Ge.ersUrl||et;oe.connectors=new Map;var Qe=zt._detectPlatform();return oe.connectors.set("apn",new Ft("apn",{protocolVersion:4,productId:De,platform:Qe},Je,nt)),oe.connectors.set("fcm",new Ft("fcm",{protocolVersion:3,productId:De,platform:Qe},Je,nt)),oe.connectors.set("twilsock",new Cr(De,Qe,Je)),Je.on("stateChanged",function(tt){return oe.emit("transportState",tt)}),oe._connector("twilsock").on("stateChanged",function(tt,at,st){return oe.emit("stateChanged",tt,at,st)}),oe._connector("apn").on("stateChanged",function(tt,at,st){return oe.emit("stateChanged",tt,at,st)}),oe._connector("fcm").on("stateChanged",function(tt,at,st){return oe.emit("stateChanged",tt,at,st)}),Je.on("message",function(tt,at){return oe._routeMessage(tt,at)}),oe.updateToken(me),Re&&(Je.connect(),oe.twilsock=Je),oe}return J.default(se,[{key:"shutdown",value:function(){var me=j.default(ue.default.mark(function be(){return ue.default.wrap(function(re){for(;;)switch(re.prev=re.next){case 0:if(this.connectors.clear(),!this.twilsock){re.next=4;break}return re.next=4,this.twilsock.disconnect();case 4:case"end":return re.stop()}},be,this)}));function le(){return me.apply(this,arguments)}return le}()},{key:"setPushRegistrationId",value:function(le,be){vt.debug("Set ".concat(le," push registration id '").concat(be,"'")),this._connector(le).setNotificationId(be)}},{key:"subscribe",value:function(le,be){vt.debug("Add ".concat(le," subscriptions for message type ").concat(be)),this._connector(le).subscribe(be)}},{key:"unsubscribe",value:function(le,be){vt.debug("Remove ".concat(le," subscriptions for message type ").concat(be)),this._connector(le).unsubscribe(be)}},{key:"updateToken",value:function(le){this.connectors.forEach(function(be){return be.updateToken(le)})}},{key:"commitChanges",value:function(){var me=j.default(ue.default.mark(function be(){var $e;return ue.default.wrap(function(ae){for(;;)switch(ae.prev=ae.next){case 0:return $e=[],this.connectors.forEach(function(K){K.isActive()&&$e.push(K.commitChanges())}),ae.next=4,Promise.all($e);case 4:case"end":return ae.stop()}},be,this)}));function le(){return me.apply(this,arguments)}return le}()},{key:"removeRegistrations",value:function(){var me=j.default(ue.default.mark(function be($e,re){return ue.default.wrap(function(K){for(;;)switch(K.prev=K.next){case 0:return K.next=2,this._connector($e).sendDeviceRemoveRequest(re);case 2:case"end":return K.stop()}},be,this)}));function le(be,$e){return me.apply(this,arguments)}return le}()},{key:"handlePushNotification",value:function(le){return{messageType:le.twi_message_type,payload:le.payload}}},{key:"_routeMessage",value:function(le,be){vt.debug("Notification message arrived: ",le,be),this.emit("message",le,be)}},{key:"_connector",value:function(le){var be=this.connectors.get(le);if(!be)throw new Error("Unknown channel type: ".concat(le));return be}}],[{key:"_detectPlatform",value:function(){var le="";return typeof navigator<"u"?(le="unknown",typeof navigator.product<"u"&&(le=navigator.product),typeof navigator.userAgent<"u"&&(le=navigator.userAgent)):le="web",le.substring(0,128)}}]),se}(Ie),Se([R.validateTypes(lr,R.nonEmptyString),ce("design:type",Function),ce("design:paramtypes",[String,String]),ce("design:returntype",void 0)],e.Notifications.prototype,"setPushRegistrationId",null),Se([R.validateTypes(lr,R.nonEmptyString),ce("design:type",Function),ce("design:paramtypes",[String,String]),ce("design:returntype",void 0)],e.Notifications.prototype,"subscribe",null),Se([R.validateTypes(lr,R.nonEmptyString),ce("design:type",Function),ce("design:paramtypes",[String,String]),ce("design:returntype",void 0)],e.Notifications.prototype,"unsubscribe",null),Se([R.validateTypes(R.nonEmptyString),ce("design:type",Function),ce("design:paramtypes",[String]),ce("design:returntype",void 0)],e.Notifications.prototype,"updateToken",null),Se([R.validateTypesAsync(lr,R.nonEmptyString),ce("design:type",Function),ce("design:paramtypes",[String,String]),ce("design:returntype",Promise)],e.Notifications.prototype,"removeRegistrations",null),e.Notifications=zt=Se([R.validateConstructorTypes(R.nonEmptyString,[R.pureObject,"undefined",R.literal(null)]),ce("design:paramtypes",[String,Object])],e.Notifications)})(v1);var mn={},on={};/*
192
+ */(function(e){Object.defineProperty(e,"__esModule",{value:!0});var t=Nu,r=$i,n=Aa,i=ki,a=Ri,s=zn,o=Uu,u=qn,c=xf,l=ms,p=gs,v=na,m=bo,b=_o,T=Ar,I=pK,R=Wr;function x(ye){return ye&&typeof ye=="object"&&"default"in ye?ye:{default:ye}}function N(ye){if(ye&&ye.__esModule)return ye;var we=Object.create(null);return ye&&Object.keys(ye).forEach(function(se){if(se!=="default"){var me=Object.getOwnPropertyDescriptor(ye,se);Object.defineProperty(we,se,me.get?me:{enumerable:!0,get:function(){return ye[se]}})}}),we.default=ye,Object.freeze(we)}var j=x(t),X=x(r),J=x(n),V=x(i),D=x(a),te=x(s),ue=x(o),ee=x(u),ge=x(l),L=x(p),pe=x(m),Te=x(b),rt=N(T),Ke=N(I);function Se(ye,we,se,me){var le=arguments.length,be=le<3?we:me===null?me=Object.getOwnPropertyDescriptor(we,se):me,$e;if((typeof Reflect>"u"?"undefined":ee.default(Reflect))==="object"&&typeof Reflect.decorate=="function")be=Reflect.decorate(ye,we,se,me);else for(var re=ye.length-1;re>=0;re--)($e=ye[re])&&(be=(le<3?$e(be):le>3?$e(we,se,be):$e(we,se))||be);return le>3&&be&&Object.defineProperty(we,se,be),be}function ce(ye,we){if((typeof Reflect>"u"?"undefined":ee.default(Reflect))==="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(ye,we)}var he;function P(){}P.prototype=Object.create(null);function Ie(){Ie.init.call(this)}Ie.EventEmitter=Ie,Ie.usingDomains=!1,Ie.prototype.domain=void 0,Ie.prototype._events=void 0,Ie.prototype._maxListeners=void 0,Ie.defaultMaxListeners=10,Ie.init=function(){this.domain=null,Ie.usingDomains&&he.active,(!this._events||this._events===Object.getPrototypeOf(this)._events)&&(this._events=new P,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},Ie.prototype.setMaxListeners=function(we){if(typeof we!="number"||we<0||isNaN(we))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=we,this};function qe(ye){return ye._maxListeners===void 0?Ie.defaultMaxListeners:ye._maxListeners}Ie.prototype.getMaxListeners=function(){return qe(this)};function Ne(ye,we,se){if(we)ye.call(se);else for(var me=ye.length,le=ke(ye,me),be=0;be<me;++be)le[be].call(se)}function _e(ye,we,se,me){if(we)ye.call(se,me);else for(var le=ye.length,be=ke(ye,le),$e=0;$e<le;++$e)be[$e].call(se,me)}function Q(ye,we,se,me,le){if(we)ye.call(se,me,le);else for(var be=ye.length,$e=ke(ye,be),re=0;re<be;++re)$e[re].call(se,me,le)}function kt(ye,we,se,me,le,be){if(we)ye.call(se,me,le,be);else for(var $e=ye.length,re=ke(ye,$e),ae=0;ae<$e;++ae)re[ae].call(se,me,le,be)}function Ce(ye,we,se,me){if(we)ye.apply(se,me);else for(var le=ye.length,be=ke(ye,le),$e=0;$e<le;++$e)be[$e].apply(se,me)}Ie.prototype.emit=function(we){var se,me,le,be,$e,re,ae,K=we==="error";if(re=this._events,re)K=K&&re.error==null;else if(!K)return!1;if(ae=this.domain,K){if(se=arguments[1],ae)se||(se=new Error('Uncaught, unspecified "error" event')),se.domainEmitter=this,se.domain=ae,se.domainThrown=!1,ae.emit("error",se);else{if(se instanceof Error)throw se;var oe=new Error('Uncaught, unspecified "error" event. ('+se+")");throw oe.context=se,oe}return!1}if(me=re[we],!me)return!1;var Y=typeof me=="function";switch(le=arguments.length,le){case 1:Ne(me,Y,this);break;case 2:_e(me,Y,this,arguments[1]);break;case 3:Q(me,Y,this,arguments[1],arguments[2]);break;case 4:kt(me,Y,this,arguments[1],arguments[2],arguments[3]);break;default:for(be=new Array(le-1),$e=1;$e<le;$e++)be[$e-1]=arguments[$e];Ce(me,Y,this,be)}return!0};function de(ye,we,se,me){var le,be,$e;if(typeof se!="function")throw new TypeError('"listener" argument must be a function');if(be=ye._events,be?(be.newListener&&(ye.emit("newListener",we,se.listener?se.listener:se),be=ye._events),$e=be[we]):(be=ye._events=new P,ye._eventsCount=0),!$e)$e=be[we]=se,++ye._eventsCount;else if(typeof $e=="function"?$e=be[we]=me?[se,$e]:[$e,se]:me?$e.unshift(se):$e.push(se),!$e.warned&&(le=qe(ye),le&&le>0&&$e.length>le)){$e.warned=!0;var re=new Error("Possible EventEmitter memory leak detected. "+$e.length+" "+we+" listeners added. Use emitter.setMaxListeners() to increase limit");re.name="MaxListenersExceededWarning",re.emitter=ye,re.type=we,re.count=$e.length,Rt(re)}return ye}function Rt(ye){typeof console.warn=="function"?console.warn(ye):console.log(ye)}Ie.prototype.addListener=function(we,se){return de(this,we,se,!1)},Ie.prototype.on=Ie.prototype.addListener,Ie.prototype.prependListener=function(we,se){return de(this,we,se,!0)};function Ue(ye,we,se){var me=!1;function le(){ye.removeListener(we,le),me||(me=!0,se.apply(ye,arguments))}return le.listener=se,le}Ie.prototype.once=function(we,se){if(typeof se!="function")throw new TypeError('"listener" argument must be a function');return this.on(we,Ue(this,we,se)),this},Ie.prototype.prependOnceListener=function(we,se){if(typeof se!="function")throw new TypeError('"listener" argument must be a function');return this.prependListener(we,Ue(this,we,se)),this},Ie.prototype.removeListener=function(we,se){var me,le,be,$e,re;if(typeof se!="function")throw new TypeError('"listener" argument must be a function');if(le=this._events,!le)return this;if(me=le[we],!me)return this;if(me===se||me.listener&&me.listener===se)--this._eventsCount===0?this._events=new P:(delete le[we],le.removeListener&&this.emit("removeListener",we,me.listener||se));else if(typeof me!="function"){for(be=-1,$e=me.length;$e-- >0;)if(me[$e]===se||me[$e].listener&&me[$e].listener===se){re=me[$e].listener,be=$e;break}if(be<0)return this;if(me.length===1){if(me[0]=void 0,--this._eventsCount===0)return this._events=new P,this;delete le[we]}else mt(me,be);le.removeListener&&this.emit("removeListener",we,re||se)}return this},Ie.prototype.off=function(ye,we){return this.removeListener(ye,we)},Ie.prototype.removeAllListeners=function(we){var se,me;if(me=this._events,!me)return this;if(!me.removeListener)return arguments.length===0?(this._events=new P,this._eventsCount=0):me[we]&&(--this._eventsCount===0?this._events=new P:delete me[we]),this;if(arguments.length===0){for(var le=Object.keys(me),be=0,$e;be<le.length;++be)$e=le[be],$e!=="removeListener"&&this.removeAllListeners($e);return this.removeAllListeners("removeListener"),this._events=new P,this._eventsCount=0,this}if(se=me[we],typeof se=="function")this.removeListener(we,se);else if(se)do this.removeListener(we,se[se.length-1]);while(se[0]);return this},Ie.prototype.listeners=function(we){var se,me,le=this._events;return le?(se=le[we],se?typeof se=="function"?me=[se.listener||se]:me=ft(se):me=[]):me=[],me},Ie.listenerCount=function(ye,we){return typeof ye.listenerCount=="function"?ye.listenerCount(we):Dt.call(ye,we)},Ie.prototype.listenerCount=Dt;function Dt(ye){var we=this._events;if(we){var se=we[ye];if(typeof se=="function")return 1;if(se)return se.length}return 0}Ie.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};function mt(ye,we){for(var se=we,me=se+1,le=ye.length;me<le;se+=1,me+=1)ye[se]=ye[me];ye.pop()}function ke(ye,we){for(var se=new Array(we);we--;)se[we]=ye[we];return se}function ft(ye){for(var we=new Array(ye.length),se=0;se<we.length;++se)we[se]=ye[se].listener||ye[se];return we}var St=rt.getLogger("twilio-notificatiions");function Oe(ye,we){return["".concat(new Date().toISOString()," Twilio.Notifications ").concat(ye,":")].concat(Array.from(we))}var Bt=function(){function ye(){X.default(this,ye)}return J.default(ye,[{key:"setLevel",value:function(se){St.setLevel(se)}},{key:"trace",value:function(){if(St.getLevel()==St.levels.TRACE){for(var se=arguments.length,me=new Array(se),le=0;le<se;le++)me[le]=arguments[le];St.debug.apply(null,Oe("T",me))}}},{key:"debug",value:function(){for(var se=arguments.length,me=new Array(se),le=0;le<se;le++)me[le]=arguments[le];St.debug.apply(null,Oe("D",me))}},{key:"info",value:function(){for(var se=arguments.length,me=new Array(se),le=0;le<se;le++)me[le]=arguments[le];St.info.apply(null,Oe("I",me))}},{key:"warn",value:function(){for(var se=arguments.length,me=new Array(se),le=0;le<se;le++)me[le]=arguments[le];St.warn.apply(null,Oe("W",me))}},{key:"error",value:function(){for(var se=arguments.length,me=new Array(se),le=0;le<se;le++)me[le]=arguments[le];St.error.apply(null,Oe("E",me))}}]),ye}(),vt=new Bt;function qt(ye){var we=sr();return function(){var me=te.default(ye),le;if(we){var be=te.default(this).constructor;le=Reflect.construct(me,arguments,be)}else le=me.apply(this,arguments);return D.default(this,le)}}function sr(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var ze=J.default(function ye(){var we=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"",se=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"",me=arguments.length>2&&arguments[2]!==void 0?arguments[2]:new Set;X.default(this,ye),this.token=we,this.notificationId=se,this.messageTypes=me});function Tr(ye,we){return[].concat(Te.default(Te.default(ye).filter(function(se){return!we.has(se)})),Te.default(Te.default(we).filter(function(se){return!ye.has(se)})))}function mr(ye,we){var se=new Set;return ye.notificationId!==we.notificationId&&se.add("notificationId"),ye.token!==we.token&&se.add("token"),Tr(ye.messageTypes,we.messageTypes).length>0&&se.add("messageType"),[se.size>0,se]}var Et=function(ye){V.default(se,ye);var we=qt(se);function se(me){var le;return X.default(this,se),le=we.call(this),L.default(ge.default(le),"desiredState",new ze),L.default(ge.default(le),"currentState",new ze),L.default(ge.default(le),"_hasActiveAttempt",!1),le.channelType=me,le}return J.default(se,[{key:"setNotificationId",value:function(le){this.desiredState.notificationId=le}},{key:"isActive",value:function(){return this.desiredState.notificationId!==""}},{key:"subscribe",value:function(le){if(this.desiredState.messageTypes.has(le)){vt.debug("message type '".concat(le,"' for channel ").concat(this.channelType," is already registered"));return}this.desiredState.messageTypes.add(le)}},{key:"unsubscribe",value:function(le){this.desiredState.messageTypes.has(le)&&this.desiredState.messageTypes.delete(le)}},{key:"updateToken",value:function(le){this.desiredState.token=le}},{key:"commitChanges",value:function(){var me=j.default(ue.default.mark(function be(){var $e,re,ae,K,oe,Y;return ue.default.wrap(function(Re){for(;;)switch(Re.prev=Re.next){case 0:if(!this._hasActiveAttempt){Re.next=3;break}throw vt.error("One registration attempt is already in progress"),new Error("One registration attempt is already in progress");case 3:if($e=mr(this.desiredState,this.currentState),re=pe.default($e,2),ae=re[0],K=re[1],ae){Re.next=6;break}return Re.abrupt("return");case 6:if(this.currentState.notificationId||K.delete("notificationId"),vt.trace("Persisting ".concat(this.channelType," registration"),K,this.desiredState),Re.prev=8,this._hasActiveAttempt=!0,oe=new ze,oe.token=this.desiredState.token,oe.notificationId=this.desiredState.notificationId,oe.messageTypes=new Set(this.desiredState.messageTypes),!(oe.messageTypes.size>0)){Re.next=24;break}return Re.next=17,this.updateRegistration(oe,K);case 17:Y=Re.sent,this.currentState.token=Y.token,this.currentState.notificationId=Y.notificationId,this.currentState.messageTypes=new Set(Y.messageTypes),this.emit("stateChanged",this.channelType,"registered",this.currentState),Re.next=30;break;case 24:return Re.next=26,this.removeRegistration();case 26:this.currentState.token=oe.token,this.currentState.notificationId=oe.notificationId,this.currentState.messageTypes.clear(),this.emit("stateChanged",this.channelType,"unregistered",this.currentState);case 30:Re.next=35;break;case 32:throw Re.prev=32,Re.t0=Re.catch(8),Re.t0;case 35:return Re.prev=35,this._hasActiveAttempt=!1,Re.finish(35);case 38:case"end":return Re.stop()}},be,this,[[8,32,35,38]])}));function le(){return me.apply(this,arguments)}return le}()}]),se}(Ie);function It(ye){var we=bt();return function(){var me=te.default(ye),le;if(we){var be=te.default(this).constructor;le=Reflect.construct(me,arguments,be)}else le=me.apply(this,arguments);return D.default(this,le)}}function bt(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var ct={min:2e3,max:12e4,randomness:.2},Ft=function(ye){V.default(se,ye);var we=It(se);function se(me,le,be,$e){var re;return X.default(this,se),re=we.call(this,me),L.default(ge.default(re),"registrationId",null),re.context=le,re.twilsock=be,re.registrarUrl=$e,re}return J.default(se,[{key:"updateRegistration",value:function(){var me=j.default(ue.default.mark(function be($e,re){var ae=this,K,oe,Y,De,Re;return ue.default.wrap(function(Ge){for(;;)switch(Ge.prev=Ge.next){case 0:if(!re.has("notificationId")){Ge.next=3;break}return Ge.next=3,this.removeRegistration();case 3:if(!(!$e.notificationId||!$e.notificationId.length)){Ge.next=6;break}throw vt.error("No push notification ID for registration"),new Error("No push notification ID for registration");case 6:return vt.trace("Registering",this.channelType,$e),K={endpoint_platform:this.context.platform,channel_type:this.channelType,version:this.context.protocolVersion.toString(),message_types:Array.from($e.messageTypes),data:{registration_id:$e.notificationId}},oe=this.context.productId,Y="".concat(this.registrarUrl,"?productId=").concat(oe),De={"Content-Type":"application/json"},vt.trace("Creating registration for channel ".concat(this.channelType)),Ge.prev=12,Ge.next=15,new v.AsyncRetrier(ct).run(function(){return ae.twilsock.post(Y,De,K,oe)});case 15:Re=Ge.sent,this.registrationId=Re.body.id,vt.debug("Registration created: ",Re),Ge.next=24;break;case 20:throw Ge.prev=20,Ge.t0=Ge.catch(12),vt.error("Registration failed: ",Ge.t0),Ge.t0;case 24:return Ge.abrupt("return",$e);case 25:case"end":return Ge.stop()}},be,this,[[12,20]])}));function le(be,$e){return me.apply(this,arguments)}return le}()},{key:"removeRegistration",value:function(){var me=j.default(ue.default.mark(function be(){var $e=this,re,ae,K;return ue.default.wrap(function(Y){for(;;)switch(Y.prev=Y.next){case 0:if(this.registrationId){Y.next=2;break}return Y.abrupt("return");case 2:return re=this.context.productId,ae="".concat(this.registrarUrl,"/").concat(this.registrationId,"?productId=").concat(re),K={"Content-Type":"application/json"},vt.trace("Removing registration for ".concat(this.channelType)),Y.prev=6,Y.next=9,new v.AsyncRetrier(Object.assign(ct,{maxAttemptsCount:3})).run(function(){return $e.twilsock.delete(ae,K,{},re)});case 9:this.registrationId=null,this.currentState.notificationId="",vt.debug("Registration removed for ".concat(this.channelType)),Y.next=18;break;case 14:throw Y.prev=14,Y.t0=Y.catch(6),vt.error("Failed to remove registration ",this.channelType,Y.t0),Y.t0;case 18:case"end":return Y.stop()}},be,this,[[6,14]])}));function le(){return me.apply(this,arguments)}return le}()},{key:"sendDeviceRemoveRequest",value:function(){var me=j.default(ue.default.mark(function be($e){var re=this,ae,K,oe,Y;return ue.default.wrap(function(Re){for(;;)switch(Re.prev=Re.next){case 0:if($e!==""){Re.next=2;break}throw new Error("Empty registration ID");case 2:return ae=this.context.productId,K="".concat(this.registrarUrl,"?productId=").concat(ae),oe={"Content-Type":"application/json"},Y={binding_type:this.channelType,address:$e},Re.prev=6,vt.trace("Removing old registrations for ".concat(this.channelType)),Re.next=10,new v.AsyncRetrier(Object.assign(ct,{maxAttemptsCount:3})).run(function(){return re.twilsock.delete(K,oe,Y,ae)});case 10:this.registrationId=null,this.currentState.notificationId="",vt.debug("Registration removed for ".concat(this.channelType)),Re.next=19;break;case 15:throw Re.prev=15,Re.t0=Re.catch(6),vt.error("Failed to remove registration ",this.channelType,Re.t0),Re.t0;case 19:case"end":return Re.stop()}},be,this,[[6,15]])}));function le(be){return me.apply(this,arguments)}return le}()}]),se}(Et);function Pt(ye){var we=cr();return function(){var me=te.default(ye),le;if(we){var be=te.default(this).constructor;le=Reflect.construct(me,arguments,be)}else le=me.apply(this,arguments);return D.default(this,le)}}function cr(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var Cr=function(ye){V.default(se,ye);var we=Pt(se);function se(me,le,be){var $e;return X.default(this,se),$e=we.call(this,"twilsock"),L.default(ge.default($e),"contextId",Ke.v4()),$e.productId=me,$e.platform=le,$e.twilsock=be,$e}return J.default(se,[{key:"updateRegistration",value:function(){var me=j.default(ue.default.mark(function be($e,re){var ae,K;return ue.default.wrap(function(Y){for(;;)switch(Y.prev=Y.next){case 0:if(re.has("messageType")){Y.next=2;break}return Y.abrupt("return",$e);case 2:return ae=Array.from($e.messageTypes),K={product_id:this.productId,notification_protocol_version:4,endpoint_platform:this.platform,message_types:ae},Y.prev=4,Y.next=7,this.twilsock.setNotificationsContext(this.contextId,K);case 7:Y.next=13;break;case 9:throw Y.prev=9,Y.t0=Y.catch(4),vt.error("Failed to update twilsock notification context: ".concat(Y.t0)),Y.t0;case 13:return Y.abrupt("return",$e);case 14:case"end":return Y.stop()}},be,this,[[4,9]])}));function le(be,$e){return me.apply(this,arguments)}return le}()},{key:"removeRegistration",value:function(){var me=j.default(ue.default.mark(function be(){return ue.default.wrap(function(re){for(;;)switch(re.prev=re.next){case 0:return re.prev=0,re.next=3,this.twilsock.removeNotificationsContext(this.contextId);case 3:re.next=9;break;case 5:throw re.prev=5,re.t0=re.catch(0),vt.error("Failed to remove twilsock notification context: ".concat(re.t0)),re.t0;case 9:case"end":return re.stop()}},be,this,[[0,5]])}));function le(){return me.apply(this,arguments)}return le}()},{key:"sendDeviceRemoveRequest",value:function(){var me=j.default(ue.default.mark(function be($e){return ue.default.wrap(function(ae){for(;;)switch(ae.prev=ae.next){case 0:case"end":return ae.stop()}},be)}));function le(be){return me.apply(this,arguments)}return le}()}]),se}(Et);function Dr(ye){var we=gr();return function(){var me=te.default(ye),le;if(we){var be=te.default(this).constructor;le=Reflect.construct(me,arguments,be)}else le=me.apply(this,arguments);return D.default(this,le)}}function gr(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var zt,lr=R.literal("apn","fcm","twilsock");e.Notifications=zt=function(ye){V.default(se,ye);var we=Dr(se);function se(me){var le,be,$e,re,ae,K,oe,Y=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};X.default(this,se),oe=we.call(this),Y.logLevel=(le=Y.logLevel)!==null&&le!==void 0?le:"error",vt.setLevel(Y.logLevel);var De=(be=Y.productId)!==null&&be!==void 0?be:"notifications",Re=!Y.twilsockClient,Je=Y.twilsockClient=($e=Y.twilsockClient)!==null&&$e!==void 0?$e:new c.TwilsockClient(me,De,Y),Ge=(re=Y.notifications)!==null&&re!==void 0?re:{},He=(ae=(K=Ge.region)!==null&&K!==void 0?K:Y.region)!==null&&ae!==void 0?ae:"us1",et="https://ers.".concat(He,".twilio.com/v1/registrations"),nt=Ge.ersUrl||et;oe.connectors=new Map;var Qe=zt._detectPlatform();return oe.connectors.set("apn",new Ft("apn",{protocolVersion:4,productId:De,platform:Qe},Je,nt)),oe.connectors.set("fcm",new Ft("fcm",{protocolVersion:3,productId:De,platform:Qe},Je,nt)),oe.connectors.set("twilsock",new Cr(De,Qe,Je)),Je.on("stateChanged",function(tt){return oe.emit("transportState",tt)}),oe._connector("twilsock").on("stateChanged",function(tt,at,st){return oe.emit("stateChanged",tt,at,st)}),oe._connector("apn").on("stateChanged",function(tt,at,st){return oe.emit("stateChanged",tt,at,st)}),oe._connector("fcm").on("stateChanged",function(tt,at,st){return oe.emit("stateChanged",tt,at,st)}),Je.on("message",function(tt,at){return oe._routeMessage(tt,at)}),oe.updateToken(me),Re&&(Je.connect(),oe.twilsock=Je),oe}return J.default(se,[{key:"shutdown",value:function(){var me=j.default(ue.default.mark(function be(){return ue.default.wrap(function(re){for(;;)switch(re.prev=re.next){case 0:if(this.connectors.clear(),!this.twilsock){re.next=4;break}return re.next=4,this.twilsock.disconnect();case 4:case"end":return re.stop()}},be,this)}));function le(){return me.apply(this,arguments)}return le}()},{key:"setPushRegistrationId",value:function(le,be){vt.debug("Set ".concat(le," push registration id '").concat(be,"'")),this._connector(le).setNotificationId(be)}},{key:"subscribe",value:function(le,be){vt.debug("Add ".concat(le," subscriptions for message type ").concat(be)),this._connector(le).subscribe(be)}},{key:"unsubscribe",value:function(le,be){vt.debug("Remove ".concat(le," subscriptions for message type ").concat(be)),this._connector(le).unsubscribe(be)}},{key:"updateToken",value:function(le){this.connectors.forEach(function(be){return be.updateToken(le)})}},{key:"commitChanges",value:function(){var me=j.default(ue.default.mark(function be(){var $e;return ue.default.wrap(function(ae){for(;;)switch(ae.prev=ae.next){case 0:return $e=[],this.connectors.forEach(function(K){K.isActive()&&$e.push(K.commitChanges())}),ae.next=4,Promise.all($e);case 4:case"end":return ae.stop()}},be,this)}));function le(){return me.apply(this,arguments)}return le}()},{key:"removeRegistrations",value:function(){var me=j.default(ue.default.mark(function be($e,re){return ue.default.wrap(function(K){for(;;)switch(K.prev=K.next){case 0:return K.next=2,this._connector($e).sendDeviceRemoveRequest(re);case 2:case"end":return K.stop()}},be,this)}));function le(be,$e){return me.apply(this,arguments)}return le}()},{key:"handlePushNotification",value:function(le){return{messageType:le.twi_message_type,payload:le.payload}}},{key:"_routeMessage",value:function(le,be){vt.debug("Notification message arrived: ",le,be),this.emit("message",le,be)}},{key:"_connector",value:function(le){var be=this.connectors.get(le);if(!be)throw new Error("Unknown channel type: ".concat(le));return be}}],[{key:"_detectPlatform",value:function(){var le="";return typeof navigator<"u"?(le="unknown",typeof navigator.product<"u"&&(le=navigator.product),typeof navigator.userAgent<"u"&&(le=navigator.userAgent)):le="web",le.substring(0,128)}}]),se}(Ie),Se([R.validateTypes(lr,R.nonEmptyString),ce("design:type",Function),ce("design:paramtypes",[String,String]),ce("design:returntype",void 0)],e.Notifications.prototype,"setPushRegistrationId",null),Se([R.validateTypes(lr,R.nonEmptyString),ce("design:type",Function),ce("design:paramtypes",[String,String]),ce("design:returntype",void 0)],e.Notifications.prototype,"subscribe",null),Se([R.validateTypes(lr,R.nonEmptyString),ce("design:type",Function),ce("design:paramtypes",[String,String]),ce("design:returntype",void 0)],e.Notifications.prototype,"unsubscribe",null),Se([R.validateTypes(R.nonEmptyString),ce("design:type",Function),ce("design:paramtypes",[String]),ce("design:returntype",void 0)],e.Notifications.prototype,"updateToken",null),Se([R.validateTypesAsync(lr,R.nonEmptyString),ce("design:type",Function),ce("design:paramtypes",[String,String]),ce("design:returntype",Promise)],e.Notifications.prototype,"removeRegistrations",null),e.Notifications=zt=Se([R.validateConstructorTypes(R.nonEmptyString,[R.pureObject,"undefined",R.literal(null)]),ce("design:paramtypes",[String,Object])],e.Notifications)})(v1);var mn={},on={};/*
193
193
  @license
194
194
  Copyright (c) 2021 Twilio Inc.
195
195
 
@@ -323,9 +323,9 @@ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
323
323
  OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
324
324
  CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
325
325
 
326
- */(function(e){var t=typeof t<"u"?t:typeof self<"u"?self:typeof window<"u"?window:{};Object.defineProperty(e,"__esModule",{value:!0});var r=$i,n=Aa,i=ki,a=Ri,s=zn,o=Bf,u=gs,c=Nu,l=Uu,p=qn,v=Ar,m=na,b=zr;function T(re){return re&&typeof re=="object"&&"default"in re?re:{default:re}}function I(re){if(re&&re.__esModule)return re;var ae=Object.create(null);return re&&Object.keys(re).forEach(function(K){if(K!=="default"){var oe=Object.getOwnPropertyDescriptor(re,K);Object.defineProperty(ae,K,oe.get?oe:{enumerable:!0,get:function(){return re[K]}})}}),ae.default=re,Object.freeze(ae)}var R=T(r),x=T(n),N=T(i),j=T(a),X=T(s),J=T(o),V=T(u),D=T(c),te=T(l),ue=T(p),ee=I(v),ge={exports:{}},L=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof window.msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto);if(L){var pe=new Uint8Array(16);ge.exports=function(){return L(pe),pe}}else{var Te=new Array(16);ge.exports=function(){for(var ae=0,K;ae<16;ae++)ae&3||(K=Math.random()*4294967296),Te[ae]=K>>>((ae&3)<<3)&255;return Te}}for(var rt=[],Ke=0;Ke<256;++Ke)rt[Ke]=(Ke+256).toString(16).substr(1);function Se(re,ae){var K=ae||0,oe=rt;return[oe[re[K++]],oe[re[K++]],oe[re[K++]],oe[re[K++]],"-",oe[re[K++]],oe[re[K++]],"-",oe[re[K++]],oe[re[K++]],"-",oe[re[K++]],oe[re[K++]],"-",oe[re[K++]],oe[re[K++]],oe[re[K++]],oe[re[K++]],oe[re[K++]],oe[re[K++]]].join("")}var ce=Se,he=ge.exports,P=ce,Ie,qe,Ne=0,_e=0;function Q(re,ae,K){var oe=ae&&K||0,Y=ae||[];re=re||{};var De=re.node||Ie,Re=re.clockseq!==void 0?re.clockseq:qe;if(De==null||Re==null){var Je=he();De==null&&(De=Ie=[Je[0]|1,Je[1],Je[2],Je[3],Je[4],Je[5]]),Re==null&&(Re=qe=(Je[6]<<8|Je[7])&16383)}var Ge=re.msecs!==void 0?re.msecs:new Date().getTime(),He=re.nsecs!==void 0?re.nsecs:_e+1,et=Ge-Ne+(He-_e)/1e4;if(et<0&&re.clockseq===void 0&&(Re=Re+1&16383),(et<0||Ge>Ne)&&re.nsecs===void 0&&(He=0),He>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");Ne=Ge,_e=He,qe=Re,Ge+=122192928e5;var nt=((Ge&268435455)*1e4+He)%4294967296;Y[oe++]=nt>>>24&255,Y[oe++]=nt>>>16&255,Y[oe++]=nt>>>8&255,Y[oe++]=nt&255;var Qe=Ge/4294967296*1e4&268435455;Y[oe++]=Qe>>>8&255,Y[oe++]=Qe&255,Y[oe++]=Qe>>>24&15|16,Y[oe++]=Qe>>>16&255,Y[oe++]=Re>>>8|128,Y[oe++]=Re&255;for(var tt=0;tt<6;++tt)Y[oe+tt]=De[tt];return ae||P(Y)}var kt=Q,Ce=ge.exports,de=ce;function Rt(re,ae,K){var oe=ae&&K||0;typeof re=="string"&&(ae=re==="binary"?new Array(16):null,re=null),re=re||{};var Y=re.random||(re.rng||Ce)();if(Y[6]=Y[6]&15|64,Y[8]=Y[8]&63|128,ae)for(var De=0;De<16;++De)ae[oe+De]=Y[De];return ae||de(Y)}var Ue=Rt,Dt=kt,mt=Ue,ke=mt;ke.v1=Dt,ke.v4=mt;var ft=ke;function St(re){var ae=Oe();return function(){var oe=X.default(re),Y;if(ae){var De=X.default(this).constructor;Y=Reflect.construct(oe,arguments,De)}else Y=oe.apply(this,arguments);return j.default(this,Y)}}function Oe(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var Bt=function(re){N.default(K,re);var ae=St(K);function K(oe){var Y;R.default(this,K);var De=ft.v4(),Re;return Y=ae.call(this,function(Je,Ge){return Re=Ge,oe(function(He){K.cancellationMap.delete(De),Je(He)},function(He){K.cancellationMap.delete(De),Ge(He)},function(He){K.cancellationMap.set(De,He)})}),Y.id=De,Y.rejectPromise=Re,Y}return x.default(K,[{key:"cancel",value:function(){var Y=K.cancellationMap.get(this.id);return Y==null||Y(),this.rejectPromise&&(this.catch(function(){}),this.rejectPromise(new Error("Promise was cancelled"))),this}}]),K}(J.default(Promise));V.default(Bt,"cancellationMap",new Map);function vt(re,ae,K,oe){var Y=arguments.length,De=Y<3?ae:oe===null?oe=Object.getOwnPropertyDescriptor(ae,K):oe,Re;if((typeof Reflect>"u"?"undefined":ue.default(Reflect))==="object"&&typeof Reflect.decorate=="function")De=Reflect.decorate(re,ae,K,oe);else for(var Je=re.length-1;Je>=0;Je--)(Re=re[Je])&&(De=(Y<3?Re(De):Y>3?Re(ae,K,De):Re(ae,K))||De);return Y>3&&De&&Object.defineProperty(ae,K,De),De}function qt(re,ae){if((typeof Reflect>"u"?"undefined":ue.default(Reflect))==="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(re,ae)}function sr(re,ae){return["".concat(new Date().toISOString()," MCS Client ").concat(re,":")].concat(Array.from(ae))}var ze=function(){function re(ae){R.default(this,re),V.default(this,"prefix",""),this.prefix=ae!=null&&ae.length>0?ae+" ":""}return x.default(re,[{key:"setLevel",value:function(K){ee.setLevel(K)}},{key:"trace",value:function(){if(ee.getLevel()==ee.levels.TRACE){for(var K=arguments.length,oe=new Array(K),Y=0;Y<K;Y++)oe[Y]=arguments[Y];ee.debug.apply(null,sr(this.prefix+"T",oe))}}},{key:"debug",value:function(){for(var K=arguments.length,oe=new Array(K),Y=0;Y<K;Y++)oe[Y]=arguments[Y];ee.debug.apply(null,sr(this.prefix+"D",oe))}},{key:"info",value:function(){for(var K=arguments.length,oe=new Array(K),Y=0;Y<K;Y++)oe[Y]=arguments[Y];ee.info.apply(null,sr(this.prefix+"I",oe))}},{key:"warn",value:function(){for(var K=arguments.length,oe=new Array(K),Y=0;Y<K;Y++)oe[Y]=arguments[Y];ee.warn.apply(null,sr(this.prefix+"W",oe))}},{key:"error",value:function(){for(var K=arguments.length,oe=new Array(K),Y=0;Y<K;Y++)oe[Y]=arguments[Y];ee.error.apply(null,sr(this.prefix+"E",oe))}}],[{key:"scope",value:function(K){return new re(K)}},{key:"setLevel",value:function(K){ee.setLevel(K)}},{key:"trace",value:function(){if(ee.getLevel()==ee.levels.TRACE){for(var K=arguments.length,oe=new Array(K),Y=0;Y<K;Y++)oe[Y]=arguments[Y];ee.debug.apply(null,sr("T",oe))}}},{key:"debug",value:function(){for(var K=arguments.length,oe=new Array(K),Y=0;Y<K;Y++)oe[Y]=arguments[Y];ee.debug.apply(null,sr("D",oe))}},{key:"info",value:function(){for(var K=arguments.length,oe=new Array(K),Y=0;Y<K;Y++)oe[Y]=arguments[Y];ee.info.apply(null,sr("I",oe))}},{key:"warn",value:function(){for(var K=arguments.length,oe=new Array(K),Y=0;Y<K;Y++)oe[Y]=arguments[Y];ee.warn.apply(null,sr("W",oe))}},{key:"error",value:function(){for(var K=arguments.length,oe=new Array(K),Y=0;Y<K;Y++)oe[Y]=arguments[Y];ee.error.apply(null,sr("E",oe))}}]),re}(),Tr=1e3,mr=4e3,Et=3,It=!0,bt=function(ae){return"https://mcs.".concat(ae??"us1",".twilio.com")},ct=function(ae){return ae.startsWith("http")},Ft=function(ae,K){return"".concat(ct(ae)?"":bt(K)).concat(ae)},Pt=function(){function re(ae,K,oe,Y){var De,Re,Je,Ge,He,et;R.default(this,re);var nt=(De=(Re=Y.MCS)!==null&&Re!==void 0?Re:Y)!==null&&De!==void 0?De:{};this.region=(Je=(Ge=nt.region)!==null&&Ge!==void 0?Ge:Y.region)!==null&&Je!==void 0?Je:"us1",this.mediaUrl=Ft(K,this.region),this.mediaSetUrl=oe?Ft(oe):"".concat(this.mediaUrl,"Set"),this.token=ae,this.retryWhenThrottledOverride=(He=nt.retryWhenThrottledOverride)!==null&&He!==void 0?He:It,this.backoffConfigOverride=(et=nt.backoffConfigOverride)!==null&&et!==void 0?et:re.backoffConfigDefault}return x.default(re,[{key:"updateToken",value:function(K){this.token=K}}],[{key:"backoffConfigDefault",get:function(){return{min:Tr,max:mr,maxAttemptsCount:Et}}},{key:"retryWhenThrottledDefault",get:function(){return It}}]),re}(),cr=function(){function re(ae,K,oe){R.default(this,re),this.config=ae,this.network=K,this._update(oe)}return x.default(re,[{key:"sid",get:function(){return this.state.sid}},{key:"serviceSid",get:function(){return this.state.serviceSid}},{key:"dateCreated",get:function(){return this.state.dateCreated}},{key:"dateUpdated",get:function(){return this.state.dateUpdated}},{key:"contentType",get:function(){return this.state.contentType}},{key:"size",get:function(){return this.state.size}},{key:"fileName",get:function(){return this.state.filename}},{key:"filename",get:function(){return this.state.filename}},{key:"category",get:function(){return this.state.category}},{key:"getContentUrl",value:function(){var K=this;return new Bt(function(){var oe=D.default(te.default.mark(function Y(De,Re,Je){var Ge,He;return te.default.wrap(function(nt){for(;;)switch(nt.prev=nt.next){case 0:return Ge=K.network.get("".concat(K.config.mediaUrl,"/").concat(K.sid)),Je(function(){return Ge.cancel()}),nt.prev=2,nt.next=5,Ge;case 5:He=nt.sent,K._update(He.body),De(K.state.contentDirectUrl),nt.next=13;break;case 10:nt.prev=10,nt.t0=nt.catch(2),Re(nt.t0);case 13:case"end":return nt.stop()}},Y,null,[[2,10]])}));return function(Y,De,Re){return oe.apply(this,arguments)}}())}},{key:"_update",value:function(K){var oe,Y,De,Re;this.state={sid:K.sid,serviceSid:K.service_sid,channelSid:K.channel_sid,messageSid:K.message_sid,dateCreated:K.date_created?new Date(K.date_created):null,dateUploadUpdated:K.date_upload_updated?new Date(K.date_upload_updated):null,dateUpdated:K.date_updated?new Date(K.date_updated):null,size:K.size,contentType:K.content_type,author:K.author,url:K.url,contentUrl:K.links.content,contentDirectUrl:(oe=K.links.content_direct_temporary)!==null&&oe!==void 0?oe:null,filename:(Y=K.filename)!==null&&Y!==void 0?Y:null,category:(De=K.category)!==null&&De!==void 0?De:"media",isMultipartUpstream:(Re=K.is_multipart_upstream)!==null&&Re!==void 0?Re:!1}}},{key:"_state",value:function(){var K;return{sid:this.state.sid,category:this.state.category,filename:(K=this.state.filename)!==null&&K!==void 0?K:null,contentType:this.state.contentType,size:this.state.size}}}]),re}();function Cr(re){var ae=Dr();return function(){var oe=X.default(re),Y;if(ae){var De=X.default(this).constructor;Y=Reflect.construct(oe,arguments,De)}else Y=oe.apply(this,arguments);return j.default(this,Y)}}function Dr(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var gr=function(re){N.default(K,re);var ae=Cr(K);function K(oe,Y,De,Re,Je){var Ge;return R.default(this,K),Ge=ae.call(this,oe),Ge.code=Y,Ge.body=De,Ge.status=Re,Ge.headers=Je,Ge}return x.default(K)}(J.default(Error)),zt=t.XMLHttpRequest||{};function lr(re){return re?re.split(`\r
326
+ */(function(e){var t=typeof t<"u"?t:typeof self<"u"?self:typeof window<"u"?window:{};Object.defineProperty(e,"__esModule",{value:!0});var r=$i,n=Aa,i=ki,a=Ri,s=zn,o=Bf,u=gs,c=Nu,l=Uu,p=qn,v=Ar,m=na,b=Wr;function T(re){return re&&typeof re=="object"&&"default"in re?re:{default:re}}function I(re){if(re&&re.__esModule)return re;var ae=Object.create(null);return re&&Object.keys(re).forEach(function(K){if(K!=="default"){var oe=Object.getOwnPropertyDescriptor(re,K);Object.defineProperty(ae,K,oe.get?oe:{enumerable:!0,get:function(){return re[K]}})}}),ae.default=re,Object.freeze(ae)}var R=T(r),x=T(n),N=T(i),j=T(a),X=T(s),J=T(o),V=T(u),D=T(c),te=T(l),ue=T(p),ee=I(v),ge={exports:{}},L=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof window.msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto);if(L){var pe=new Uint8Array(16);ge.exports=function(){return L(pe),pe}}else{var Te=new Array(16);ge.exports=function(){for(var ae=0,K;ae<16;ae++)ae&3||(K=Math.random()*4294967296),Te[ae]=K>>>((ae&3)<<3)&255;return Te}}for(var rt=[],Ke=0;Ke<256;++Ke)rt[Ke]=(Ke+256).toString(16).substr(1);function Se(re,ae){var K=ae||0,oe=rt;return[oe[re[K++]],oe[re[K++]],oe[re[K++]],oe[re[K++]],"-",oe[re[K++]],oe[re[K++]],"-",oe[re[K++]],oe[re[K++]],"-",oe[re[K++]],oe[re[K++]],"-",oe[re[K++]],oe[re[K++]],oe[re[K++]],oe[re[K++]],oe[re[K++]],oe[re[K++]]].join("")}var ce=Se,he=ge.exports,P=ce,Ie,qe,Ne=0,_e=0;function Q(re,ae,K){var oe=ae&&K||0,Y=ae||[];re=re||{};var De=re.node||Ie,Re=re.clockseq!==void 0?re.clockseq:qe;if(De==null||Re==null){var Je=he();De==null&&(De=Ie=[Je[0]|1,Je[1],Je[2],Je[3],Je[4],Je[5]]),Re==null&&(Re=qe=(Je[6]<<8|Je[7])&16383)}var Ge=re.msecs!==void 0?re.msecs:new Date().getTime(),He=re.nsecs!==void 0?re.nsecs:_e+1,et=Ge-Ne+(He-_e)/1e4;if(et<0&&re.clockseq===void 0&&(Re=Re+1&16383),(et<0||Ge>Ne)&&re.nsecs===void 0&&(He=0),He>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");Ne=Ge,_e=He,qe=Re,Ge+=122192928e5;var nt=((Ge&268435455)*1e4+He)%4294967296;Y[oe++]=nt>>>24&255,Y[oe++]=nt>>>16&255,Y[oe++]=nt>>>8&255,Y[oe++]=nt&255;var Qe=Ge/4294967296*1e4&268435455;Y[oe++]=Qe>>>8&255,Y[oe++]=Qe&255,Y[oe++]=Qe>>>24&15|16,Y[oe++]=Qe>>>16&255,Y[oe++]=Re>>>8|128,Y[oe++]=Re&255;for(var tt=0;tt<6;++tt)Y[oe+tt]=De[tt];return ae||P(Y)}var kt=Q,Ce=ge.exports,de=ce;function Rt(re,ae,K){var oe=ae&&K||0;typeof re=="string"&&(ae=re==="binary"?new Array(16):null,re=null),re=re||{};var Y=re.random||(re.rng||Ce)();if(Y[6]=Y[6]&15|64,Y[8]=Y[8]&63|128,ae)for(var De=0;De<16;++De)ae[oe+De]=Y[De];return ae||de(Y)}var Ue=Rt,Dt=kt,mt=Ue,ke=mt;ke.v1=Dt,ke.v4=mt;var ft=ke;function St(re){var ae=Oe();return function(){var oe=X.default(re),Y;if(ae){var De=X.default(this).constructor;Y=Reflect.construct(oe,arguments,De)}else Y=oe.apply(this,arguments);return j.default(this,Y)}}function Oe(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var Bt=function(re){N.default(K,re);var ae=St(K);function K(oe){var Y;R.default(this,K);var De=ft.v4(),Re;return Y=ae.call(this,function(Je,Ge){return Re=Ge,oe(function(He){K.cancellationMap.delete(De),Je(He)},function(He){K.cancellationMap.delete(De),Ge(He)},function(He){K.cancellationMap.set(De,He)})}),Y.id=De,Y.rejectPromise=Re,Y}return x.default(K,[{key:"cancel",value:function(){var Y=K.cancellationMap.get(this.id);return Y==null||Y(),this.rejectPromise&&(this.catch(function(){}),this.rejectPromise(new Error("Promise was cancelled"))),this}}]),K}(J.default(Promise));V.default(Bt,"cancellationMap",new Map);function vt(re,ae,K,oe){var Y=arguments.length,De=Y<3?ae:oe===null?oe=Object.getOwnPropertyDescriptor(ae,K):oe,Re;if((typeof Reflect>"u"?"undefined":ue.default(Reflect))==="object"&&typeof Reflect.decorate=="function")De=Reflect.decorate(re,ae,K,oe);else for(var Je=re.length-1;Je>=0;Je--)(Re=re[Je])&&(De=(Y<3?Re(De):Y>3?Re(ae,K,De):Re(ae,K))||De);return Y>3&&De&&Object.defineProperty(ae,K,De),De}function qt(re,ae){if((typeof Reflect>"u"?"undefined":ue.default(Reflect))==="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(re,ae)}function sr(re,ae){return["".concat(new Date().toISOString()," MCS Client ").concat(re,":")].concat(Array.from(ae))}var ze=function(){function re(ae){R.default(this,re),V.default(this,"prefix",""),this.prefix=ae!=null&&ae.length>0?ae+" ":""}return x.default(re,[{key:"setLevel",value:function(K){ee.setLevel(K)}},{key:"trace",value:function(){if(ee.getLevel()==ee.levels.TRACE){for(var K=arguments.length,oe=new Array(K),Y=0;Y<K;Y++)oe[Y]=arguments[Y];ee.debug.apply(null,sr(this.prefix+"T",oe))}}},{key:"debug",value:function(){for(var K=arguments.length,oe=new Array(K),Y=0;Y<K;Y++)oe[Y]=arguments[Y];ee.debug.apply(null,sr(this.prefix+"D",oe))}},{key:"info",value:function(){for(var K=arguments.length,oe=new Array(K),Y=0;Y<K;Y++)oe[Y]=arguments[Y];ee.info.apply(null,sr(this.prefix+"I",oe))}},{key:"warn",value:function(){for(var K=arguments.length,oe=new Array(K),Y=0;Y<K;Y++)oe[Y]=arguments[Y];ee.warn.apply(null,sr(this.prefix+"W",oe))}},{key:"error",value:function(){for(var K=arguments.length,oe=new Array(K),Y=0;Y<K;Y++)oe[Y]=arguments[Y];ee.error.apply(null,sr(this.prefix+"E",oe))}}],[{key:"scope",value:function(K){return new re(K)}},{key:"setLevel",value:function(K){ee.setLevel(K)}},{key:"trace",value:function(){if(ee.getLevel()==ee.levels.TRACE){for(var K=arguments.length,oe=new Array(K),Y=0;Y<K;Y++)oe[Y]=arguments[Y];ee.debug.apply(null,sr("T",oe))}}},{key:"debug",value:function(){for(var K=arguments.length,oe=new Array(K),Y=0;Y<K;Y++)oe[Y]=arguments[Y];ee.debug.apply(null,sr("D",oe))}},{key:"info",value:function(){for(var K=arguments.length,oe=new Array(K),Y=0;Y<K;Y++)oe[Y]=arguments[Y];ee.info.apply(null,sr("I",oe))}},{key:"warn",value:function(){for(var K=arguments.length,oe=new Array(K),Y=0;Y<K;Y++)oe[Y]=arguments[Y];ee.warn.apply(null,sr("W",oe))}},{key:"error",value:function(){for(var K=arguments.length,oe=new Array(K),Y=0;Y<K;Y++)oe[Y]=arguments[Y];ee.error.apply(null,sr("E",oe))}}]),re}(),Tr=1e3,mr=4e3,Et=3,It=!0,bt=function(ae){return"https://mcs.".concat(ae??"us1",".twilio.com")},ct=function(ae){return ae.startsWith("http")},Ft=function(ae,K){return"".concat(ct(ae)?"":bt(K)).concat(ae)},Pt=function(){function re(ae,K,oe,Y){var De,Re,Je,Ge,He,et;R.default(this,re);var nt=(De=(Re=Y.MCS)!==null&&Re!==void 0?Re:Y)!==null&&De!==void 0?De:{};this.region=(Je=(Ge=nt.region)!==null&&Ge!==void 0?Ge:Y.region)!==null&&Je!==void 0?Je:"us1",this.mediaUrl=Ft(K,this.region),this.mediaSetUrl=oe?Ft(oe):"".concat(this.mediaUrl,"Set"),this.token=ae,this.retryWhenThrottledOverride=(He=nt.retryWhenThrottledOverride)!==null&&He!==void 0?He:It,this.backoffConfigOverride=(et=nt.backoffConfigOverride)!==null&&et!==void 0?et:re.backoffConfigDefault}return x.default(re,[{key:"updateToken",value:function(K){this.token=K}}],[{key:"backoffConfigDefault",get:function(){return{min:Tr,max:mr,maxAttemptsCount:Et}}},{key:"retryWhenThrottledDefault",get:function(){return It}}]),re}(),cr=function(){function re(ae,K,oe){R.default(this,re),this.config=ae,this.network=K,this._update(oe)}return x.default(re,[{key:"sid",get:function(){return this.state.sid}},{key:"serviceSid",get:function(){return this.state.serviceSid}},{key:"dateCreated",get:function(){return this.state.dateCreated}},{key:"dateUpdated",get:function(){return this.state.dateUpdated}},{key:"contentType",get:function(){return this.state.contentType}},{key:"size",get:function(){return this.state.size}},{key:"fileName",get:function(){return this.state.filename}},{key:"filename",get:function(){return this.state.filename}},{key:"category",get:function(){return this.state.category}},{key:"getContentUrl",value:function(){var K=this;return new Bt(function(){var oe=D.default(te.default.mark(function Y(De,Re,Je){var Ge,He;return te.default.wrap(function(nt){for(;;)switch(nt.prev=nt.next){case 0:return Ge=K.network.get("".concat(K.config.mediaUrl,"/").concat(K.sid)),Je(function(){return Ge.cancel()}),nt.prev=2,nt.next=5,Ge;case 5:He=nt.sent,K._update(He.body),De(K.state.contentDirectUrl),nt.next=13;break;case 10:nt.prev=10,nt.t0=nt.catch(2),Re(nt.t0);case 13:case"end":return nt.stop()}},Y,null,[[2,10]])}));return function(Y,De,Re){return oe.apply(this,arguments)}}())}},{key:"_update",value:function(K){var oe,Y,De,Re;this.state={sid:K.sid,serviceSid:K.service_sid,channelSid:K.channel_sid,messageSid:K.message_sid,dateCreated:K.date_created?new Date(K.date_created):null,dateUploadUpdated:K.date_upload_updated?new Date(K.date_upload_updated):null,dateUpdated:K.date_updated?new Date(K.date_updated):null,size:K.size,contentType:K.content_type,author:K.author,url:K.url,contentUrl:K.links.content,contentDirectUrl:(oe=K.links.content_direct_temporary)!==null&&oe!==void 0?oe:null,filename:(Y=K.filename)!==null&&Y!==void 0?Y:null,category:(De=K.category)!==null&&De!==void 0?De:"media",isMultipartUpstream:(Re=K.is_multipart_upstream)!==null&&Re!==void 0?Re:!1}}},{key:"_state",value:function(){var K;return{sid:this.state.sid,category:this.state.category,filename:(K=this.state.filename)!==null&&K!==void 0?K:null,contentType:this.state.contentType,size:this.state.size}}}]),re}();function Cr(re){var ae=Dr();return function(){var oe=X.default(re),Y;if(ae){var De=X.default(this).constructor;Y=Reflect.construct(oe,arguments,De)}else Y=oe.apply(this,arguments);return j.default(this,Y)}}function Dr(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var gr=function(re){N.default(K,re);var ae=Cr(K);function K(oe,Y,De,Re,Je){var Ge;return R.default(this,K),Ge=ae.call(this,oe),Ge.code=Y,Ge.body=De,Ge.status=Re,Ge.headers=Je,Ge}return x.default(K)}(J.default(Error)),zt=t.XMLHttpRequest||{};function lr(re){return re?re.split(`\r
327
327
  `).map(function(ae){return ae.split(": ")}).filter(function(ae){return ae.length===2&&ae[1].length>0}).reduce(function(ae,K){return ae[K[0]]=K[1],ae},{}):{}}function ye(re){var ae=re.getResponseHeader("Content-Type");if(!ae||ae.indexOf("application/json")!==0||re.responseText.length===0)return re.responseText;try{return JSON.parse(re.responseText)}catch{return re.responseText}}var we=function(){function re(){R.default(this,re)}return x.default(re,[{key:"get",value:function(K,oe){return re.request("GET",K,oe)}},{key:"post",value:function(K,oe,Y){return re.request("POST",K,oe,Y)}}],[{key:"request",value:function(K,oe,Y,De){return new Bt(function(Re,Je,Ge){var He=new zt,et=!1;Ge(function(){He.abort(),et=!0}),He.open(K,oe,!0),He.onreadystatechange=function(){if(!(He.readyState!==4||et)){var tt=lr(He.getAllResponseHeaders()),at=ye(He);if(200<=He.status&&He.status<300)Re({status:He.status,headers:tt,body:at});else{var st,yr=(st=He.statusText)!==null&&st!==void 0?st:"NONE",fr;if(typeof at=="string")if(at&&at.split(`
328
- `,2).length===1)fr=at;else{var dt,Wr=(dt=at.replace(/<.*?>/g,"").split(/\r\n/g).filter(function(it){return it.length})[0])===null||dt===void 0?void 0:dt.split(" ");fr=(Wr==null?void 0:Wr.length)>2?Wr==null?void 0:Wr.slice(1).join(" "):""}else fr=JSON.stringify(at);var cn="".concat(He.status,": [").concat(yr,"] ").concat(fr);Je(new gr(cn,He.status,at,yr,tt))}}};for(var nt in Y)He.setRequestHeader(nt,Y[nt]),nt==="Content-Type"&&Y[nt]==="application/json"&&(De=JSON.stringify(De));He.send(De)})}}]),re}(),se=ze.scope("Network"),me=function(){function re(ae,K){R.default(this,re),this.config=ae,this.transport=K}return x.default(re,[{key:"backoffConfig",value:function(){return Object.assign(Pt.backoffConfigDefault,this.config.backoffConfigOverride)}},{key:"retryWhenThrottled",value:function(){var K,oe;return(K=(oe=this.config.retryWhenThrottledOverride)!==null&&oe!==void 0?oe:Pt.retryWhenThrottledDefault)!==null&&K!==void 0?K:!1}},{key:"executeWithRetry",value:function(K,oe){var Y=this;return new Bt(function(){var De=D.default(te.default.mark(function Re(Je,Ge,He){var et,nt;return te.default.wrap(function(tt){for(;;)switch(tt.prev=tt.next){case 0:et=new m.Retrier(Y.backoffConfig()),nt=[502,503,504],oe&&nt.push(429),He(function(){et.cancel(),et.removeAllListeners()}),et.on("attempt",D.default(te.default.mark(function at(){var st,yr;return te.default.wrap(function(dt){for(;;)switch(dt.prev=dt.next){case 0:return dt.prev=0,st=K(),He(function(){st.cancel(),et.cancel(),et.removeAllListeners()}),dt.next=5,st;case 5:yr=dt.sent,et.succeeded(yr),dt.next=12;break;case 9:dt.prev=9,dt.t0=dt.catch(0),nt.indexOf(dt.t0.status)>-1||dt.t0.message==="Twilsock disconnected"?et.failed(dt.t0):(et.removeAllListeners(),et.cancel(),Ge(dt.t0));case 12:case"end":return dt.stop()}},at,null,[[0,9]])}))),et.on("succeeded",function(at){Je(at)}),et.on("cancelled",function(at){return Ge(at)}),et.on("failed",function(at){return Ge(at)}),et.start();case 9:case"end":return tt.stop()}},Re)}));return function(Re,Je,Ge){return De.apply(this,arguments)}}())}},{key:"get",value:function(K){var oe=this;return new Bt(function(){var Y=D.default(te.default.mark(function De(Re,Je,Ge){var He,et,nt;return te.default.wrap(function(tt){for(;;)switch(tt.prev=tt.next){case 0:return He={"X-Twilio-Token":oe.config.token},et=oe.executeWithRetry(function(){return oe.transport.get(K,He)},oe.retryWhenThrottled()),se.trace("sending GET request to ",K," headers ",He),Ge(function(){return et.cancel()}),tt.prev=4,tt.next=7,et;case 7:nt=tt.sent,se.trace("response",nt),Re(nt),tt.next=16;break;case 12:tt.prev=12,tt.t0=tt.catch(4),se.debug("get() error ".concat(tt.t0)),Je(tt.t0);case 16:case"end":return tt.stop()}},De,null,[[4,12]])}));return function(De,Re,Je){return Y.apply(this,arguments)}}())}},{key:"post",value:function(K,oe,Y,De,Re){var Je=this,Ge={"X-Twilio-Token":this.config.token};(typeof FormData>"u"||!(Y instanceof FormData))&&De&&Object.assign(Ge,{"Content-Type":De});var He=new URL(K);return oe&&He.searchParams.append("Category",oe),Re&&He.searchParams.append("Filename",Re),new Bt(function(){var et=D.default(te.default.mark(function nt(Qe,tt,at){var st,yr;return te.default.wrap(function(dt){for(;;)switch(dt.prev=dt.next){case 0:return st=Je.transport.post(He.href,Ge,Y),at(function(){return st.cancel()}),se.trace("sending POST request to ".concat(K," with headers ").concat(Ge)),dt.prev=3,dt.next=6,st;case 6:yr=dt.sent,dt.next=17;break;case 9:if(dt.prev=9,dt.t0=dt.catch(3),!(t.XMLHttpRequest===void 0&&Y instanceof FormData)){dt.next=14;break}return tt(new TypeError("Posting FormData supported only with browser engine's FormData")),dt.abrupt("return");case 14:return se.debug("post() error ".concat(dt.t0)),tt(dt.t0),dt.abrupt("return");case 17:se.trace("response",yr),Qe(yr);case 19:case"end":return dt.stop()}},nt,null,[[3,9]])}));return function(nt,Qe,tt){return et.apply(this,arguments)}}())}}]),re}(),le="0.6.8",be,$e=ze.scope("");e.default=(be=function(){function re(ae,K,oe){var Y,De,Re=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};R.default(this,re),this.options=Re,this.options.logLevel=(Y=this.options.logLevel)!==null&&Y!==void 0?Y:"silent",this.config=new Pt(ae,K,oe,this.options),$e.setLevel(this.options.logLevel),this.options.transport=(De=this.options.transport)!==null&&De!==void 0?De:new we,this.transport=this.options.transport,this.network=new me(this.config,this.transport)}return x.default(re,[{key:"updateToken",value:function(K){$e.info("updateToken"),this.config.updateToken(K)}},{key:"get",value:function(K){var oe=this;return new Bt(function(){var Y=D.default(te.default.mark(function De(Re,Je,Ge){var He,et;return te.default.wrap(function(Qe){for(;;)switch(Qe.prev=Qe.next){case 0:return He=oe.network.get("".concat(oe.config.mediaUrl,"/").concat(K)),Ge(function(){return He.cancel()}),Qe.prev=2,Qe.next=5,He;case 5:et=Qe.sent,Re(new cr(oe.config,oe.network,et.body)),Qe.next=12;break;case 9:Qe.prev=9,Qe.t0=Qe.catch(2),Je(Qe.t0);case 12:case"end":return Qe.stop()}},De,null,[[2,9]])}));return function(De,Re,Je){return Y.apply(this,arguments)}}())}},{key:"post",value:function(K,oe,Y,De){var Re=this;return new Bt(function(){var Je=D.default(te.default.mark(function Ge(He,et,nt){var Qe,tt;return te.default.wrap(function(st){for(;;)switch(st.prev=st.next){case 0:return Qe=Re.network.post(Re.config.mediaUrl,Y??"media",oe,K,De),nt(function(){return Qe.cancel()}),st.prev=2,st.next=5,Qe;case 5:tt=st.sent,He(new cr(Re.config,Re.network,tt.body)),st.next=12;break;case 9:st.prev=9,st.t0=st.catch(2),et(st.t0);case 12:case"end":return st.stop()}},Ge,null,[[2,9]])}));return function(Ge,He,et){return Je.apply(this,arguments)}}())}},{key:"postFormData",value:function(K,oe){var Y=this;return new Bt(function(){var De=D.default(te.default.mark(function Re(Je,Ge,He){var et,nt;return te.default.wrap(function(tt){for(;;)switch(tt.prev=tt.next){case 0:return et=Y.network.post(Y.config.mediaUrl,oe??"media",K),He(function(){return et.cancel()}),tt.prev=2,tt.next=5,et;case 5:nt=tt.sent,Je(new cr(Y.config,Y.network,nt.body)),tt.next=12;break;case 9:tt.prev=9,tt.t0=tt.catch(2),Ge(tt.t0);case 12:case"end":return tt.stop()}},Re,null,[[2,9]])}));return function(Re,Je,Ge){return De.apply(this,arguments)}}())}},{key:"mediaSetGet",value:function(K){var oe=this;return new Bt(function(){var Y=D.default(te.default.mark(function De(Re,Je,Ge){var He,et,nt,Qe;return te.default.wrap(function(at){for(;;)switch(at.prev=at.next){case 0:return He={command:"get",list:K.map(function(st){return{media_sid:st}})},et=oe.network.post("".concat(oe.config.mediaSetUrl),null,He,"application/json"),Ge(function(){return et.cancel()}),at.prev=3,at.next=6,et;case 6:nt=at.sent,Qe=nt.body.map(function(st){if(st.code!==200){Je("Failed to obtain detailed information about Media items (failed SID ".concat(st.media_record.sid,")"));return}return new cr(oe.config,oe.network,st.media_record)}),Re(Qe),at.next=14;break;case 11:at.prev=11,at.t0=at.catch(3),Je(at.t0);case 14:case"end":return at.stop()}},De,null,[[3,11]])}));return function(De,Re,Je){return Y.apply(this,arguments)}}())}},{key:"mediaSetGetContentUrls",value:function(K){var oe=this;return new Bt(function(){var Y=D.default(te.default.mark(function De(Re,Je,Ge){var He,et,nt,Qe;return te.default.wrap(function(at){for(;;)switch(at.prev=at.next){case 0:return He={command:"get",list:K.map(function(st){return{media_sid:st}})},et=oe.network.post("".concat(oe.config.mediaSetUrl),null,He,"application/json"),Ge(function(){return et.cancel()}),at.prev=3,at.next=6,et;case 6:nt=at.sent,Qe=new Map,nt.body.forEach(function(st){if(st.code!==200){Je("Failed to obtain detailed information about Media items (failed SID ".concat(st.media_record.sid,")"));return}Qe.set(st.media_record.sid,st.media_record.links.content_direct_temporary)}),Re(Qe),at.next=15;break;case 12:at.prev=12,at.t0=at.catch(3),Je(at.t0);case 15:case"end":return at.stop()}},De,null,[[3,12]])}));return function(De,Re,Je){return Y.apply(this,arguments)}}())}}]),re}(),V.default(be,"version",le),be),vt([b.validateTypes(b.nonEmptyString),qt("design:type",Function),qt("design:paramtypes",[String]),qt("design:returntype",void 0)],e.default.prototype,"updateToken",null),vt([b.validateTypesAsync(b.nonEmptyString),qt("design:type",Function),qt("design:paramtypes",[String]),qt("design:returntype",Bt)],e.default.prototype,"get",null),e.default=vt([b.validateConstructorTypes(b.nonEmptyString,b.nonEmptyString,[b.nonEmptyString,b.literal(null)],[b.pureObject,"undefined"]),qt("design:paramtypes",[String,String,Object,Object])],e.default),e.CancellablePromise=Bt,e.Client=e.default,e.McsClient=e.default,e.McsMedia=cr,e.Media=cr})(W1);var h$=tr,hX=Yr,vX=Si,mX=h$.aTypedArray,gX=h$.exportTypedArrayMethod;gX("at",function(t){var r=mX(this),n=hX(r),i=vX(t),a=i>=0?i:n+i;return a<0||a>=n?void 0:r[a]});var yX=Ct,bX=$t,_X=wR,wX=mf,qg="ArrayBuffer",p0=_X[qg],SX=bX[qg];yX({global:!0,constructor:!0,forced:SX!==p0},{ArrayBuffer:p0});wX(qg);var TX=Ct,v$=wt,CX=Bn,EX=Jr,h0=Yr,kX=mg,v0=Lr,zg=yt,RX=Cg,$X=vf,m0=n1,IX=i1,g0=po,y0=a1,ba=[],b0=v$(ba.sort),OX=v$(ba.push),AX=zg(function(){ba.sort(void 0)}),PX=zg(function(){ba.sort(null)}),MX=$X("sort"),m$=!zg(function(){if(g0)return g0<70;if(!(m0&&m0>3)){if(IX)return!0;if(y0)return y0<603;var e="",t,r,n,i;for(t=65;t<76;t++){switch(r=String.fromCharCode(t),t){case 66:case 69:case 70:case 72:n=3;break;case 68:case 71:n=4;break;default:n=2}for(i=0;i<47;i++)ba.push({k:r+i,v:n})}for(ba.sort(function(a,s){return s.v-a.v}),i=0;i<ba.length;i++)r=ba[i].k.charAt(0),e.charAt(e.length-1)!==r&&(e+=r);return e!=="DGBEFHACIJK"}}),xX=AX||!PX||!MX||!m$,NX=function(e){return function(t,r){return r===void 0?-1:t===void 0?1:e!==void 0?+e(t,r)||0:v0(t)>v0(r)?1:-1}};TX({target:"Array",proto:!0,forced:xX},{sort:function(t){t!==void 0&&CX(t);var r=EX(this);if(m$)return t===void 0?b0(r):b0(r,t);var n=[],i=h0(r),a,s;for(s=0;s<i;s++)s in r&&OX(n,r[s]);for(RX(n,NX(t)),a=h0(n),s=0;s<a;)r[s]=n[s++];for(;s<i;)kX(r,s++);return r}});var LX=Ct,DX=wt,jX=G1,FX=si,_0=Lr,UX=H1,BX=DX("".indexOf);LX({target:"String",proto:!0,forced:!UX("includes")},{includes:function(t){return!!~BX(_0(FX(this)),_0(jX(t)),arguments.length>1?arguments[1]:void 0)}});var qX=wt,w0=Mf,Wc=Pf.getWeakData,zX=Pa,WX=wr,GX=ai,eh=ar,HX=Fu,g$=vn,S0=vr,y$=En,VX=y$.set,KX=y$.getterFor,JX=g$.find,YX=g$.findIndex,XX=qX([].splice),QX=0,Gc=function(e){return e.frozen||(e.frozen=new b$)},b$=function(){this.entries=[]},th=function(e,t){return JX(e.entries,function(r){return r[0]===t})};b$.prototype={get:function(e){var t=th(this,e);if(t)return t[1]},has:function(e){return!!th(this,e)},set:function(e,t){var r=th(this,e);r?r[1]=t:this.entries.push([e,t])},delete:function(e){var t=YX(this.entries,function(r){return r[0]===e});return~t&&XX(this.entries,t,1),!!~t}};var ZX={getConstructor:function(e,t,r,n){var i=e(function(u,c){zX(u,a),VX(u,{type:t,id:QX++,frozen:null}),GX(c)||HX(c,u[n],{that:u,AS_ENTRIES:r})}),a=i.prototype,s=KX(t),o=function(u,c,l){var p=s(u),v=Wc(WX(c),!0);return v===!0?Gc(p).set(c,l):v[p.id]=l,u};return w0(a,{delete:function(u){var c=s(this);if(!eh(u))return!1;var l=Wc(u);return l===!0?Gc(c).delete(u):l&&S0(l,c.id)&&delete l[c.id]},has:function(c){var l=s(this);if(!eh(c))return!1;var p=Wc(c);return p===!0?Gc(l).has(c):p&&S0(p,l.id)}}),w0(a,r?{get:function(c){var l=s(this);if(eh(c)){var p=Wc(c);if(p===!0)return Gc(l).get(c);if(p)return p[l.id]}},set:function(c,l){return o(this,c,l)}}:{add:function(c){return o(this,c,!0)}}),i}},eQ=rg,tQ=ZX;eQ("WeakSet",function(e){return function(){return e(this,arguments.length?arguments[0]:void 0)}},tQ);var Wf={},_$={exports:{}};(function(e){(function(t,r){e.exports?e.exports=r():t.log=r()})(je,function(){var t=function(){},r="undefined",n=typeof window!==r&&typeof window.navigator!==r&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"];function a(T,I){var R=T[I];if(typeof R.bind=="function")return R.bind(T);try{return Function.prototype.bind.call(R,T)}catch{return function(){return Function.prototype.apply.apply(R,[T,arguments])}}}function s(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function o(T){return T==="debug"&&(T="log"),typeof console===r?!1:T==="trace"&&n?s:console[T]!==void 0?a(console,T):console.log!==void 0?a(console,"log"):t}function u(T,I){for(var R=0;R<i.length;R++){var x=i[R];this[x]=R<T?t:this.methodFactory(x,T,I)}this.log=this.debug}function c(T,I,R){return function(){typeof console!==r&&(u.call(this,I,R),this[T].apply(this,arguments))}}function l(T,I,R){return o(T)||c.apply(this,arguments)}function p(T,I,R){var x=this,N;I=I??"WARN";var j="loglevel";typeof T=="string"?j+=":"+T:typeof T=="symbol"&&(j=void 0);function X(te){var ue=(i[te]||"silent").toUpperCase();if(!(typeof window===r||!j)){try{window.localStorage[j]=ue;return}catch{}try{window.document.cookie=encodeURIComponent(j)+"="+ue+";"}catch{}}}function J(){var te;if(!(typeof window===r||!j)){try{te=window.localStorage[j]}catch{}if(typeof te===r)try{var ue=window.document.cookie,ee=ue.indexOf(encodeURIComponent(j)+"=");ee!==-1&&(te=/^([^;]+)/.exec(ue.slice(ee))[1])}catch{}return x.levels[te]===void 0&&(te=void 0),te}}function V(){if(!(typeof window===r||!j)){try{window.localStorage.removeItem(j);return}catch{}try{window.document.cookie=encodeURIComponent(j)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}x.name=T,x.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},x.methodFactory=R||l,x.getLevel=function(){return N},x.setLevel=function(te,ue){if(typeof te=="string"&&x.levels[te.toUpperCase()]!==void 0&&(te=x.levels[te.toUpperCase()]),typeof te=="number"&&te>=0&&te<=x.levels.SILENT){if(N=te,ue!==!1&&X(te),u.call(x,te,T),typeof console===r&&te<x.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+te},x.setDefaultLevel=function(te){I=te,J()||x.setLevel(te,!1)},x.resetLevel=function(){x.setLevel(I,!1),V()},x.enableAll=function(te){x.setLevel(x.levels.TRACE,te)},x.disableAll=function(te){x.setLevel(x.levels.SILENT,te)};var D=J();D==null&&(D=I),x.setLevel(D,!1)}var v=new p,m={};v.getLogger=function(I){if(typeof I!="symbol"&&typeof I!="string"||I==="")throw new TypeError("You must supply a name when creating a logger.");var R=m[I];return R||(R=m[I]=new p(I,v.getLevel(),v.methodFactory)),R};var b=typeof window!==r?window.log:void 0;return v.noConflict=function(){return typeof window!==r&&window.log===v&&(window.log=b),v},v.getLoggers=function(){return m},v.default=v,v})})(_$);var rQ=_$.exports;/*
328
+ `,2).length===1)fr=at;else{var dt,Gr=(dt=at.replace(/<.*?>/g,"").split(/\r\n/g).filter(function(it){return it.length})[0])===null||dt===void 0?void 0:dt.split(" ");fr=(Gr==null?void 0:Gr.length)>2?Gr==null?void 0:Gr.slice(1).join(" "):""}else fr=JSON.stringify(at);var cn="".concat(He.status,": [").concat(yr,"] ").concat(fr);Je(new gr(cn,He.status,at,yr,tt))}}};for(var nt in Y)He.setRequestHeader(nt,Y[nt]),nt==="Content-Type"&&Y[nt]==="application/json"&&(De=JSON.stringify(De));He.send(De)})}}]),re}(),se=ze.scope("Network"),me=function(){function re(ae,K){R.default(this,re),this.config=ae,this.transport=K}return x.default(re,[{key:"backoffConfig",value:function(){return Object.assign(Pt.backoffConfigDefault,this.config.backoffConfigOverride)}},{key:"retryWhenThrottled",value:function(){var K,oe;return(K=(oe=this.config.retryWhenThrottledOverride)!==null&&oe!==void 0?oe:Pt.retryWhenThrottledDefault)!==null&&K!==void 0?K:!1}},{key:"executeWithRetry",value:function(K,oe){var Y=this;return new Bt(function(){var De=D.default(te.default.mark(function Re(Je,Ge,He){var et,nt;return te.default.wrap(function(tt){for(;;)switch(tt.prev=tt.next){case 0:et=new m.Retrier(Y.backoffConfig()),nt=[502,503,504],oe&&nt.push(429),He(function(){et.cancel(),et.removeAllListeners()}),et.on("attempt",D.default(te.default.mark(function at(){var st,yr;return te.default.wrap(function(dt){for(;;)switch(dt.prev=dt.next){case 0:return dt.prev=0,st=K(),He(function(){st.cancel(),et.cancel(),et.removeAllListeners()}),dt.next=5,st;case 5:yr=dt.sent,et.succeeded(yr),dt.next=12;break;case 9:dt.prev=9,dt.t0=dt.catch(0),nt.indexOf(dt.t0.status)>-1||dt.t0.message==="Twilsock disconnected"?et.failed(dt.t0):(et.removeAllListeners(),et.cancel(),Ge(dt.t0));case 12:case"end":return dt.stop()}},at,null,[[0,9]])}))),et.on("succeeded",function(at){Je(at)}),et.on("cancelled",function(at){return Ge(at)}),et.on("failed",function(at){return Ge(at)}),et.start();case 9:case"end":return tt.stop()}},Re)}));return function(Re,Je,Ge){return De.apply(this,arguments)}}())}},{key:"get",value:function(K){var oe=this;return new Bt(function(){var Y=D.default(te.default.mark(function De(Re,Je,Ge){var He,et,nt;return te.default.wrap(function(tt){for(;;)switch(tt.prev=tt.next){case 0:return He={"X-Twilio-Token":oe.config.token},et=oe.executeWithRetry(function(){return oe.transport.get(K,He)},oe.retryWhenThrottled()),se.trace("sending GET request to ",K," headers ",He),Ge(function(){return et.cancel()}),tt.prev=4,tt.next=7,et;case 7:nt=tt.sent,se.trace("response",nt),Re(nt),tt.next=16;break;case 12:tt.prev=12,tt.t0=tt.catch(4),se.debug("get() error ".concat(tt.t0)),Je(tt.t0);case 16:case"end":return tt.stop()}},De,null,[[4,12]])}));return function(De,Re,Je){return Y.apply(this,arguments)}}())}},{key:"post",value:function(K,oe,Y,De,Re){var Je=this,Ge={"X-Twilio-Token":this.config.token};(typeof FormData>"u"||!(Y instanceof FormData))&&De&&Object.assign(Ge,{"Content-Type":De});var He=new URL(K);return oe&&He.searchParams.append("Category",oe),Re&&He.searchParams.append("Filename",Re),new Bt(function(){var et=D.default(te.default.mark(function nt(Qe,tt,at){var st,yr;return te.default.wrap(function(dt){for(;;)switch(dt.prev=dt.next){case 0:return st=Je.transport.post(He.href,Ge,Y),at(function(){return st.cancel()}),se.trace("sending POST request to ".concat(K," with headers ").concat(Ge)),dt.prev=3,dt.next=6,st;case 6:yr=dt.sent,dt.next=17;break;case 9:if(dt.prev=9,dt.t0=dt.catch(3),!(t.XMLHttpRequest===void 0&&Y instanceof FormData)){dt.next=14;break}return tt(new TypeError("Posting FormData supported only with browser engine's FormData")),dt.abrupt("return");case 14:return se.debug("post() error ".concat(dt.t0)),tt(dt.t0),dt.abrupt("return");case 17:se.trace("response",yr),Qe(yr);case 19:case"end":return dt.stop()}},nt,null,[[3,9]])}));return function(nt,Qe,tt){return et.apply(this,arguments)}}())}}]),re}(),le="0.6.8",be,$e=ze.scope("");e.default=(be=function(){function re(ae,K,oe){var Y,De,Re=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};R.default(this,re),this.options=Re,this.options.logLevel=(Y=this.options.logLevel)!==null&&Y!==void 0?Y:"silent",this.config=new Pt(ae,K,oe,this.options),$e.setLevel(this.options.logLevel),this.options.transport=(De=this.options.transport)!==null&&De!==void 0?De:new we,this.transport=this.options.transport,this.network=new me(this.config,this.transport)}return x.default(re,[{key:"updateToken",value:function(K){$e.info("updateToken"),this.config.updateToken(K)}},{key:"get",value:function(K){var oe=this;return new Bt(function(){var Y=D.default(te.default.mark(function De(Re,Je,Ge){var He,et;return te.default.wrap(function(Qe){for(;;)switch(Qe.prev=Qe.next){case 0:return He=oe.network.get("".concat(oe.config.mediaUrl,"/").concat(K)),Ge(function(){return He.cancel()}),Qe.prev=2,Qe.next=5,He;case 5:et=Qe.sent,Re(new cr(oe.config,oe.network,et.body)),Qe.next=12;break;case 9:Qe.prev=9,Qe.t0=Qe.catch(2),Je(Qe.t0);case 12:case"end":return Qe.stop()}},De,null,[[2,9]])}));return function(De,Re,Je){return Y.apply(this,arguments)}}())}},{key:"post",value:function(K,oe,Y,De){var Re=this;return new Bt(function(){var Je=D.default(te.default.mark(function Ge(He,et,nt){var Qe,tt;return te.default.wrap(function(st){for(;;)switch(st.prev=st.next){case 0:return Qe=Re.network.post(Re.config.mediaUrl,Y??"media",oe,K,De),nt(function(){return Qe.cancel()}),st.prev=2,st.next=5,Qe;case 5:tt=st.sent,He(new cr(Re.config,Re.network,tt.body)),st.next=12;break;case 9:st.prev=9,st.t0=st.catch(2),et(st.t0);case 12:case"end":return st.stop()}},Ge,null,[[2,9]])}));return function(Ge,He,et){return Je.apply(this,arguments)}}())}},{key:"postFormData",value:function(K,oe){var Y=this;return new Bt(function(){var De=D.default(te.default.mark(function Re(Je,Ge,He){var et,nt;return te.default.wrap(function(tt){for(;;)switch(tt.prev=tt.next){case 0:return et=Y.network.post(Y.config.mediaUrl,oe??"media",K),He(function(){return et.cancel()}),tt.prev=2,tt.next=5,et;case 5:nt=tt.sent,Je(new cr(Y.config,Y.network,nt.body)),tt.next=12;break;case 9:tt.prev=9,tt.t0=tt.catch(2),Ge(tt.t0);case 12:case"end":return tt.stop()}},Re,null,[[2,9]])}));return function(Re,Je,Ge){return De.apply(this,arguments)}}())}},{key:"mediaSetGet",value:function(K){var oe=this;return new Bt(function(){var Y=D.default(te.default.mark(function De(Re,Je,Ge){var He,et,nt,Qe;return te.default.wrap(function(at){for(;;)switch(at.prev=at.next){case 0:return He={command:"get",list:K.map(function(st){return{media_sid:st}})},et=oe.network.post("".concat(oe.config.mediaSetUrl),null,He,"application/json"),Ge(function(){return et.cancel()}),at.prev=3,at.next=6,et;case 6:nt=at.sent,Qe=nt.body.map(function(st){if(st.code!==200){Je("Failed to obtain detailed information about Media items (failed SID ".concat(st.media_record.sid,")"));return}return new cr(oe.config,oe.network,st.media_record)}),Re(Qe),at.next=14;break;case 11:at.prev=11,at.t0=at.catch(3),Je(at.t0);case 14:case"end":return at.stop()}},De,null,[[3,11]])}));return function(De,Re,Je){return Y.apply(this,arguments)}}())}},{key:"mediaSetGetContentUrls",value:function(K){var oe=this;return new Bt(function(){var Y=D.default(te.default.mark(function De(Re,Je,Ge){var He,et,nt,Qe;return te.default.wrap(function(at){for(;;)switch(at.prev=at.next){case 0:return He={command:"get",list:K.map(function(st){return{media_sid:st}})},et=oe.network.post("".concat(oe.config.mediaSetUrl),null,He,"application/json"),Ge(function(){return et.cancel()}),at.prev=3,at.next=6,et;case 6:nt=at.sent,Qe=new Map,nt.body.forEach(function(st){if(st.code!==200){Je("Failed to obtain detailed information about Media items (failed SID ".concat(st.media_record.sid,")"));return}Qe.set(st.media_record.sid,st.media_record.links.content_direct_temporary)}),Re(Qe),at.next=15;break;case 12:at.prev=12,at.t0=at.catch(3),Je(at.t0);case 15:case"end":return at.stop()}},De,null,[[3,12]])}));return function(De,Re,Je){return Y.apply(this,arguments)}}())}}]),re}(),V.default(be,"version",le),be),vt([b.validateTypes(b.nonEmptyString),qt("design:type",Function),qt("design:paramtypes",[String]),qt("design:returntype",void 0)],e.default.prototype,"updateToken",null),vt([b.validateTypesAsync(b.nonEmptyString),qt("design:type",Function),qt("design:paramtypes",[String]),qt("design:returntype",Bt)],e.default.prototype,"get",null),e.default=vt([b.validateConstructorTypes(b.nonEmptyString,b.nonEmptyString,[b.nonEmptyString,b.literal(null)],[b.pureObject,"undefined"]),qt("design:paramtypes",[String,String,Object,Object])],e.default),e.CancellablePromise=Bt,e.Client=e.default,e.McsClient=e.default,e.McsMedia=cr,e.Media=cr})(W1);var h$=tr,hX=Yr,vX=Si,mX=h$.aTypedArray,gX=h$.exportTypedArrayMethod;gX("at",function(t){var r=mX(this),n=hX(r),i=vX(t),a=i>=0?i:n+i;return a<0||a>=n?void 0:r[a]});var yX=Ct,bX=$t,_X=wR,wX=mf,qg="ArrayBuffer",p0=_X[qg],SX=bX[qg];yX({global:!0,constructor:!0,forced:SX!==p0},{ArrayBuffer:p0});wX(qg);var TX=Ct,v$=wt,CX=Bn,EX=Jr,h0=Yr,kX=mg,v0=Lr,zg=yt,RX=Cg,$X=vf,m0=n1,IX=i1,g0=po,y0=a1,ba=[],b0=v$(ba.sort),OX=v$(ba.push),AX=zg(function(){ba.sort(void 0)}),PX=zg(function(){ba.sort(null)}),MX=$X("sort"),m$=!zg(function(){if(g0)return g0<70;if(!(m0&&m0>3)){if(IX)return!0;if(y0)return y0<603;var e="",t,r,n,i;for(t=65;t<76;t++){switch(r=String.fromCharCode(t),t){case 66:case 69:case 70:case 72:n=3;break;case 68:case 71:n=4;break;default:n=2}for(i=0;i<47;i++)ba.push({k:r+i,v:n})}for(ba.sort(function(a,s){return s.v-a.v}),i=0;i<ba.length;i++)r=ba[i].k.charAt(0),e.charAt(e.length-1)!==r&&(e+=r);return e!=="DGBEFHACIJK"}}),xX=AX||!PX||!MX||!m$,NX=function(e){return function(t,r){return r===void 0?-1:t===void 0?1:e!==void 0?+e(t,r)||0:v0(t)>v0(r)?1:-1}};TX({target:"Array",proto:!0,forced:xX},{sort:function(t){t!==void 0&&CX(t);var r=EX(this);if(m$)return t===void 0?b0(r):b0(r,t);var n=[],i=h0(r),a,s;for(s=0;s<i;s++)s in r&&OX(n,r[s]);for(RX(n,NX(t)),a=h0(n),s=0;s<a;)r[s]=n[s++];for(;s<i;)kX(r,s++);return r}});var LX=Ct,DX=wt,jX=G1,FX=si,_0=Lr,UX=H1,BX=DX("".indexOf);LX({target:"String",proto:!0,forced:!UX("includes")},{includes:function(t){return!!~BX(_0(FX(this)),_0(jX(t)),arguments.length>1?arguments[1]:void 0)}});var qX=wt,w0=Mf,Wc=Pf.getWeakData,zX=Pa,WX=wr,GX=ai,eh=ar,HX=Fu,g$=vn,S0=vr,y$=En,VX=y$.set,KX=y$.getterFor,JX=g$.find,YX=g$.findIndex,XX=qX([].splice),QX=0,Gc=function(e){return e.frozen||(e.frozen=new b$)},b$=function(){this.entries=[]},th=function(e,t){return JX(e.entries,function(r){return r[0]===t})};b$.prototype={get:function(e){var t=th(this,e);if(t)return t[1]},has:function(e){return!!th(this,e)},set:function(e,t){var r=th(this,e);r?r[1]=t:this.entries.push([e,t])},delete:function(e){var t=YX(this.entries,function(r){return r[0]===e});return~t&&XX(this.entries,t,1),!!~t}};var ZX={getConstructor:function(e,t,r,n){var i=e(function(u,c){zX(u,a),VX(u,{type:t,id:QX++,frozen:null}),GX(c)||HX(c,u[n],{that:u,AS_ENTRIES:r})}),a=i.prototype,s=KX(t),o=function(u,c,l){var p=s(u),v=Wc(WX(c),!0);return v===!0?Gc(p).set(c,l):v[p.id]=l,u};return w0(a,{delete:function(u){var c=s(this);if(!eh(u))return!1;var l=Wc(u);return l===!0?Gc(c).delete(u):l&&S0(l,c.id)&&delete l[c.id]},has:function(c){var l=s(this);if(!eh(c))return!1;var p=Wc(c);return p===!0?Gc(l).has(c):p&&S0(p,l.id)}}),w0(a,r?{get:function(c){var l=s(this);if(eh(c)){var p=Wc(c);if(p===!0)return Gc(l).get(c);if(p)return p[l.id]}},set:function(c,l){return o(this,c,l)}}:{add:function(c){return o(this,c,!0)}}),i}},eQ=rg,tQ=ZX;eQ("WeakSet",function(e){return function(){return e(this,arguments.length?arguments[0]:void 0)}},tQ);var Wf={},_$={exports:{}};(function(e){(function(t,r){e.exports?e.exports=r():t.log=r()})(je,function(){var t=function(){},r="undefined",n=typeof window!==r&&typeof window.navigator!==r&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"];function a(T,I){var R=T[I];if(typeof R.bind=="function")return R.bind(T);try{return Function.prototype.bind.call(R,T)}catch{return function(){return Function.prototype.apply.apply(R,[T,arguments])}}}function s(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function o(T){return T==="debug"&&(T="log"),typeof console===r?!1:T==="trace"&&n?s:console[T]!==void 0?a(console,T):console.log!==void 0?a(console,"log"):t}function u(T,I){for(var R=0;R<i.length;R++){var x=i[R];this[x]=R<T?t:this.methodFactory(x,T,I)}this.log=this.debug}function c(T,I,R){return function(){typeof console!==r&&(u.call(this,I,R),this[T].apply(this,arguments))}}function l(T,I,R){return o(T)||c.apply(this,arguments)}function p(T,I,R){var x=this,N;I=I??"WARN";var j="loglevel";typeof T=="string"?j+=":"+T:typeof T=="symbol"&&(j=void 0);function X(te){var ue=(i[te]||"silent").toUpperCase();if(!(typeof window===r||!j)){try{window.localStorage[j]=ue;return}catch{}try{window.document.cookie=encodeURIComponent(j)+"="+ue+";"}catch{}}}function J(){var te;if(!(typeof window===r||!j)){try{te=window.localStorage[j]}catch{}if(typeof te===r)try{var ue=window.document.cookie,ee=ue.indexOf(encodeURIComponent(j)+"=");ee!==-1&&(te=/^([^;]+)/.exec(ue.slice(ee))[1])}catch{}return x.levels[te]===void 0&&(te=void 0),te}}function V(){if(!(typeof window===r||!j)){try{window.localStorage.removeItem(j);return}catch{}try{window.document.cookie=encodeURIComponent(j)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}x.name=T,x.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},x.methodFactory=R||l,x.getLevel=function(){return N},x.setLevel=function(te,ue){if(typeof te=="string"&&x.levels[te.toUpperCase()]!==void 0&&(te=x.levels[te.toUpperCase()]),typeof te=="number"&&te>=0&&te<=x.levels.SILENT){if(N=te,ue!==!1&&X(te),u.call(x,te,T),typeof console===r&&te<x.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+te},x.setDefaultLevel=function(te){I=te,J()||x.setLevel(te,!1)},x.resetLevel=function(){x.setLevel(I,!1),V()},x.enableAll=function(te){x.setLevel(x.levels.TRACE,te)},x.disableAll=function(te){x.setLevel(x.levels.SILENT,te)};var D=J();D==null&&(D=I),x.setLevel(D,!1)}var v=new p,m={};v.getLogger=function(I){if(typeof I!="symbol"&&typeof I!="string"||I==="")throw new TypeError("You must supply a name when creating a logger.");var R=m[I];return R||(R=m[I]=new p(I,v.getLevel(),v.methodFactory)),R};var b=typeof window!==r?window.log:void 0;return v.noConflict=function(){return typeof window!==r&&window.log===v&&(window.log=b),v},v.getLoggers=function(){return m},v.default=v,v})})(_$);var rQ=_$.exports;/*
329
329
  @license
330
330
  Copyright (c) 2022 Twilio Inc.
331
331
 
@@ -463,13 +463,13 @@ This software includes platform.js under the following license.
463
463
  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
464
464
  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
465
465
 
466
- */(function(e){var t=typeof t<"u"?t:typeof self<"u"?self:typeof window<"u"?window:{};Object.defineProperty(e,"__esModule",{value:!0});var r=Nu,n=ms,i=ki,a=Ri,s=zn,o=gs,u=Aa,c=$i,l=Uu,p=qn,v=Ar,m=n3,b=zr,T=_o,I=Xm,R=_z,x=bo,N=na,j=xf,X=v1,J=mn,V=W1,D=Wf,te=Bf,ue=bQ;function ee(O){return O&&typeof O=="object"&&"default"in O?O:{default:O}}function ge(O){if(O&&O.__esModule)return O;var A=Object.create(null);return O&&Object.keys(O).forEach(function(f){if(f!=="default"){var d=Object.getOwnPropertyDescriptor(O,f);Object.defineProperty(A,f,d.get?d:{enumerable:!0,get:function(){return O[f]}})}}),A.default=O,Object.freeze(A)}var L=ee(r),pe=ee(n),Te=ee(i),rt=ee(a),Ke=ee(s),Se=ee(o),ce=ee(u),he=ee(c),P=ee(l),Ie=ee(p),qe=ge(v),Ne=ee(T),_e=ee(R),Q=ee(x),kt=ee(te);function Ce(O,A,f,d){var h=arguments.length,y=h<3?A:d===null?d=Object.getOwnPropertyDescriptor(A,f):d,g;if((typeof Reflect>"u"?"undefined":Ie.default(Reflect))==="object"&&typeof Reflect.decorate=="function")y=Reflect.decorate(O,A,f,d);else for(var _=O.length-1;_>=0;_--)(g=O[_])&&(y=(h<3?g(y):h>3?g(A,f,y):g(A,f))||y);return h>3&&y&&Object.defineProperty(A,f,y),y}function de(O,A){if((typeof Reflect>"u"?"undefined":Ie.default(Reflect))==="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(O,A)}function Rt(O,A){return["".concat(new Date().toISOString()," Conversations ").concat(O,":")].concat(Array.from(A))}var Ue=qe.getLogger("twilio-conversations"),Dt=function(){function O(A){he.default(this,O),Se.default(this,"prefix",""),this.prefix=A!=null&&A.length>0?A+" ":""}return ce.default(O,[{key:"setLevel",value:function(f){Ue.setLevel(f)}},{key:"trace",value:function(){if(Ue.getLevel()==Ue.levels.TRACE){for(var f=arguments.length,d=new Array(f),h=0;h<f;h++)d[h]=arguments[h];Ue.debug.apply(null,Rt(this.prefix+"T",d))}}},{key:"debug",value:function(){for(var f=arguments.length,d=new Array(f),h=0;h<f;h++)d[h]=arguments[h];Ue.debug.apply(null,Rt(this.prefix+"D",d))}},{key:"info",value:function(){for(var f=arguments.length,d=new Array(f),h=0;h<f;h++)d[h]=arguments[h];Ue.info.apply(null,Rt(this.prefix+"I",d))}},{key:"warn",value:function(){for(var f=arguments.length,d=new Array(f),h=0;h<f;h++)d[h]=arguments[h];Ue.warn.apply(null,Rt(this.prefix+"W",d))}},{key:"error",value:function(){for(var f=arguments.length,d=new Array(f),h=0;h<f;h++)d[h]=arguments[h];Ue.error.apply(null,Rt(this.prefix+"E",d))}}],[{key:"scope",value:function(f){return new O(f)}},{key:"setLevel",value:function(f){Ue.setLevel(f)}},{key:"trace",value:function(){if(Ue.getLevel()==Ue.levels.TRACE){for(var f=arguments.length,d=new Array(f),h=0;h<f;h++)d[h]=arguments[h];Ue.debug.apply(null,Rt("T",d))}}},{key:"debug",value:function(){for(var f=arguments.length,d=new Array(f),h=0;h<f;h++)d[h]=arguments[h];Ue.debug.apply(null,Rt("D",d))}},{key:"info",value:function(){for(var f=arguments.length,d=new Array(f),h=0;h<f;h++)d[h]=arguments[h];Ue.info.apply(null,Rt("I",d))}},{key:"warn",value:function(){for(var f=arguments.length,d=new Array(f),h=0;h<f;h++)d[h]=arguments[h];Ue.warn.apply(null,Rt("W",d))}},{key:"error",value:function(){for(var f=arguments.length,d=new Array(f),h=0;h<f;h++)d[h]=arguments[h];Ue.error.apply(null,Rt("E",d))}}]),O}();function mt(O,A){var f=Object.keys(O);if(Object.getOwnPropertySymbols){var d=Object.getOwnPropertySymbols(O);A&&(d=d.filter(function(h){return Object.getOwnPropertyDescriptor(O,h).enumerable})),f.push.apply(f,d)}return f}function ke(O){for(var A=1;A<arguments.length;A++){var f=arguments[A]!=null?arguments[A]:{};A%2?mt(Object(f),!0).forEach(function(d){Se.default(O,d,f[d])}):Object.getOwnPropertyDescriptors?Object.defineProperties(O,Object.getOwnPropertyDescriptors(f)):mt(Object(f)).forEach(function(d){Object.defineProperty(O,d,Object.getOwnPropertyDescriptor(f,d))})}return O}var ft=5,St="PT5S",Oe="PT5S",Bt=100,vt=1e3,qt=4e3,sr=3,ze=!0,Tr=100,mr=1e3,Et=ce.default(function O(){var A,f,d,h,y,g,_,w,S=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},C=arguments.length>1?arguments[1]:void 0,B=arguments.length>2?arguments[2]:void 0;he.default(this,O),Se.default(this,"typingIndicatorTimeoutDefault",ft*1e3);var U=S.Chat||S.IPMessaging||S||{};this.productId=U.productId,this.links={myConversations:C.links.my_conversations,conversations:C.links.conversations,users:C.links.users,currentUser:C.links.current_user,typing:C.links.typing,mediaService:C.links.media_service,mediaSetService:C.links.media_set_service,messagesReceipts:C.links.messages_receipts},this.limits={mediaAttachmentsCountLimit:C.options.media_attachments_count_limit,mediaAttachmentSizeLimitInMb:C.options.media_attachment_size_limit_in_mb,mediaAttachmentsTotalSizeLimitInMb:C.options.media_attachments_total_size_limit_in_mb,emailHistoriesAllowedContentTypes:C.options.email_histories_allowed_mime_types,emailBodiesAllowedContentTypes:C.options.email_bodies_allowed_mime_types},this.typingIndicatorTimeoutOverride=U.typingIndicatorTimeoutOverride,this.backoffConfiguration=ke({min:vt,max:qt,maxAttemptsCount:sr},U.backoffConfigOverride),this.retryWhenThrottled=U.retryWhenThrottledOverride!==void 0?U.retryWhenThrottledOverride:ze,this.userInfosToSubscribe=(A=(f=U.userInfosToSubscribeOverride)!==null&&f!==void 0?f:C.options.user_infos_to_subscribe)!==null&&A!==void 0?A:Bt,this.reachabilityEnabled=C.options.reachability_enabled,this.userIdentity=C.identity,this.userInfo=C.sync_objects.my_user_info,this.myConversations=C.sync_objects.my_conversations;var H=(d=(h=U.httpCacheIntervalOverride)!==null&&h!==void 0?h:C.options.http_cache_interval)!==null&&d!==void 0?d:St;try{this.httpCacheInterval=m.toSeconds(m.parse(H))}catch{B.error("Failed to parse http cache interval ".concat(H,", using default value ").concat(St)),this.httpCacheInterval=m.toSeconds(m.parse(St))}var G=(y=(g=U.consumptionReportIntervalOverride)!==null&&g!==void 0?g:C.options.consumption_report_interval)!==null&&y!==void 0?y:Oe;try{this.consumptionReportInterval=m.toSeconds(m.parse(G))}catch{B.error("Failed to parse consumption report interval ".concat(G,", using default value ").concat(Oe)),this.consumptionReportInterval=m.toSeconds(m.parse(Oe))}this.channelMetadataCacheCapacity=(_=S.channelMetadataCacheCapacity)!==null&&_!==void 0?_:Tr,this.messageRecipientsCacheCapacity=(w=S.messageRecipientsCacheCapacity)!==null&&w!==void 0?w:mr});function It(O){return JSON.parse(JSON.stringify(O))}function bt(O){return typeof O<"u"&&!isNaN(Number(O))?Number(O):null}function ct(O){try{return new Date(O)}catch{return null}}function Ft(O,A,f){var d={};if(O)try{d=JSON.parse(O)}catch(h){f.warn(A,h)}return d}var Pt=function(){function O(A){he.default(this,O),this.base=A.replace(/\/$/,""),this.args=[],this.paths=[]}return ce.default(O,[{key:"arg",value:function(f,d){return typeof d<"u"&&this.args.push(encodeURIComponent(f)+"="+encodeURIComponent(d)),this}},{key:"path",value:function(f){return this.paths.push(encodeURIComponent(f)),this}},{key:"build",value:function(){var f=this.base;return this.paths.length&&(f+="/"+this.paths.join("/")),this.args.length&&(f+="?"+this.args.join("&")),f}}]),O}(),cr=b.custom(function(O){return[["string","number","boolean","object"].includes(Ie.default(O)),"a JSON type"]}),Cr=b.custom(function(O){return[["undefined","string","number","boolean","object"].includes(Ie.default(O)),"an optional JSON type"]}),Dr=b.objectSchema("send media options",{contentType:[b.literal(null),"string"],filename:["string","undefined"],media:[b.literal("null"),"string"].concat(Ne.default(typeof Buffer=="function"?[Buffer]:[]),Ne.default(typeof Blob=="function"?[Blob]:[]))});function gr(O){var A=zt();return function(){var d=Ke.default(O),h;if(A){var y=Ke.default(this).constructor;h=Reflect.construct(d,arguments,y)}else h=d.apply(this,arguments);return rt.default(this,h)}}function zt(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var lr=Dt.scope("User"),ye=function(O){Te.default(f,O);var A=gr(f);function f(d,h,y,g){var _;return he.default(this,f),_=A.call(this),Se.default(pe.default(_),"promiseToFetch",null),Se.default(pe.default(_),"updated","updated"),Se.default(pe.default(_),"userSubscribed","userSubscribed"),Se.default(pe.default(_),"userUnsubscribed","userUnsubscribed"),_.services=g,_.subscribed="initializing",_.setMaxListeners(0),_.state={identity:d,entityName:h,friendlyName:null,attributes:{},online:null,notifiable:null},_._initializationPromise=new Promise(function(w){_._resolveInitializationPromise=w}),y!==null&&_._resolveInitialization(y,d,h,!1),_}return ce.default(f,[{key:"identity",get:function(){return this.state.identity},set:function(h){this.state.identity=h}},{key:"entityName",set:function(h){this.state.entityName=h}},{key:"attributes",get:function(){return this.state.attributes}},{key:"friendlyName",get:function(){return this.state.friendlyName}},{key:"isOnline",get:function(){return this.state.online}},{key:"isNotifiable",get:function(){return this.state.notifiable}},{key:"isSubscribed",get:function(){return this.subscribed=="subscribed"}},{key:"_update",value:function(){var d=L.default(P.default.mark(function y(g,_){var w,S;return P.default.wrap(function(B){for(;;)switch(B.prev=B.next){case 0:return B.next=2,this._initializationPromise;case 2:w=[],lr.debug("User for",this.state.identity,"updated:",g,_),B.t0=g,B.next=B.t0==="friendlyName"?7:B.t0==="attributes"?9:B.t0==="reachability"?12:15;break;case 7:return this.state.friendlyName!==_.value&&(w.push("friendlyName"),this.state.friendlyName=_.value),B.abrupt("break",16);case 9:return S=Ft(_.value,"Retrieved malformed attributes from the server for user: ".concat(this.state.identity),lr),_e.default(this.state.attributes,S)||(this.state.attributes=S,w.push("attributes")),B.abrupt("break",16);case 12:return this.state.online!==_.online&&(this.state.online=_.online,w.push("reachabilityOnline")),this.state.notifiable!==_.notifiable&&(this.state.notifiable=_.notifiable,w.push("reachabilityNotifiable")),B.abrupt("break",16);case 15:return B.abrupt("return");case 16:w.length>0&&this.emit("updated",{user:this,updateReasons:w});case 17:case"end":return B.stop()}},y,this)}));function h(y,g){return d.apply(this,arguments)}return h}()},{key:"_updateReachabilityInfo",value:function(){var d=L.default(P.default.mark(function y(g,_){var w=this;return P.default.wrap(function(C){for(;;)switch(C.prev=C.next){case 0:return C.next=2,this._initializationPromise;case 2:if(this.configuration.reachabilityEnabled){C.next=4;break}return C.abrupt("return",Promise.resolve());case 4:return C.abrupt("return",g.get("reachability").then(_).catch(function(B){lr.warn("Failed to get reachability info for ",w.state.identity,B)}));case 5:case"end":return C.stop()}},y,this)}));function h(y,g){return d.apply(this,arguments)}return h}()},{key:"_fetch",value:function(){var d=L.default(P.default.mark(function y(){var g=this;return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this._initializationPromise;case 2:if(this.state.entityName){w.next=4;break}return w.abrupt("return",this);case 4:return this.promiseToFetch=this.services.syncClient.map({id:this.state.entityName,mode:"open_existing",includeItems:!0}).then(function(S){return g.entity=S,S.on("itemUpdated",function(C){return lr.debug(g.state.entityName+" ("+g.state.identity+") itemUpdated: "+C.item.key),g._update(C.item.key,C.item.data)}),S.on("itemAdded",function(C){return lr.debug(g.state.entityName+" ("+g.state.identity+") itemAdded: "+C.item.key),g._update(C.item.key,C.item.data)}),Promise.all([S.get("friendlyName").then(function(C){return g._update(C.key,C.data)}),S.get("attributes").then(function(C){return g._update(C.key,C.data)}),g._updateReachabilityInfo(S,function(C){return g._update(C.key,C.data)})])}).then(function(){return lr.debug("Fetched for",g.identity),g.subscribed="subscribed",g.emit("userSubscribed",g),g}).catch(function(S){throw g.promiseToFetch=null,S}),w.abrupt("return",this.promiseToFetch);case 6:case"end":return w.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"_ensureFetched",value:function(){var d=L.default(P.default.mark(function y(){return P.default.wrap(function(_){for(;;)switch(_.prev=_.next){case 0:return _.next=2,this._initializationPromise;case 2:return _.abrupt("return",this.promiseToFetch||this._fetch());case 3:case"end":return _.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"updateAttributes",value:function(){var d=L.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this._initializationPromise;case 2:if(this.subscribed!="unsubscribed"){w.next=4;break}throw new Error("Can't modify unsubscribed object");case 4:return w.next=6,this.services.commandExecutor.mutateResource("post",this.links.self,{attributes:JSON.stringify(g)});case 6:return w.abrupt("return",this);case 7:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"updateFriendlyName",value:function(){var d=L.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this._initializationPromise;case 2:if(this.subscribed!="unsubscribed"){w.next=4;break}throw new Error("Can't modify unsubscribed object");case 4:return w.next=6,this.services.commandExecutor.mutateResource("post",this.links.self,{friendly_name:g});case 6:return w.abrupt("return",this);case 7:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"unsubscribe",value:function(){var d=L.default(P.default.mark(function y(){return P.default.wrap(function(_){for(;;)switch(_.prev=_.next){case 0:return _.next=2,this._initializationPromise;case 2:if(!this.promiseToFetch){_.next=9;break}return _.next=5,this.promiseToFetch;case 5:this.entity.close(),this.promiseToFetch=null,this.subscribed="unsubscribed",this.emit("userUnsubscribed",this);case 9:case"end":return _.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"_resolveInitialization",value:function(h,y,g,_){this.configuration=h,this.identity=y,this.entityName=g,this.links={self:"".concat(this.configuration.links.users,"/").concat(encodeURIComponent(this.identity))},this._resolveInitializationPromise(),_&&this.emit("updated",{user:this,updateReasons:["friendlyName","attributes","reachabilityOnline","reachabilityNotifiable"]})}}]),f}(I.ReplayEventEmitter);Ce([b.validateTypesAsync(cr),de("design:type",Function),de("design:paramtypes",[Object]),de("design:returntype",Promise)],ye.prototype,"updateAttributes",null),Ce([b.validateTypesAsync(["string"]),de("design:type",Function),de("design:paramtypes",[String]),de("design:returntype",Promise)],ye.prototype,"updateFriendlyName",null);function we(O,A){var f=typeof Symbol<"u"&&O[Symbol.iterator]||O["@@iterator"];if(!f){if(Array.isArray(O)||(f=se(O))||A){f&&(O=f);var d=0,h=function(){};return{s:h,n:function(){return d>=O.length?{done:!0}:{done:!1,value:O[d++]}},e:function(S){throw S},f:h}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
467
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var y=!0,g=!1,_;return{s:function(){f=f.call(O)},n:function(){var S=f.next();return y=S.done,S},e:function(S){g=!0,_=S},f:function(){try{!y&&f.return!=null&&f.return()}finally{if(g)throw _}}}}function se(O,A){if(O){if(typeof O=="string")return me(O,A);var f=Object.prototype.toString.call(O).slice(8,-1);if(f==="Object"&&O.constructor&&(f=O.constructor.name),f==="Map"||f==="Set")return Array.from(O);if(f==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(f))return me(O,A)}}function me(O,A){(A==null||A>O.length)&&(A=O.length);for(var f=0,d=new Array(A);f<A;f++)d[f]=O[f];return d}var le=function(){function O(A,f){he.default(this,O),this.configuration=A,this.services=f,this.cache=new Map,this.cacheLifetime=this.configuration.httpCacheInterval*100,this.cleanupCache()}return ce.default(O,[{key:"isExpired",value:function(f){return!this.cacheLifetime||Date.now()-f>this.cacheLifetime}},{key:"cleanupCache",value:function(){var f=we(this.cache),d;try{for(f.s();!(d=f.n()).done;){var h=Q.default(d.value,2),y=h[0],g=h[1];this.isExpired(g.timestamp)&&this.cache.delete(y)}}catch(_){f.e(_)}finally{f.f()}this.cache.size===0&&clearInterval(this.timer)}},{key:"pokeTimer",value:function(){var f=this;this.timer=this.timer||setInterval(function(){return f.cleanupCache()},this.cacheLifetime*2)}},{key:"executeWithRetry",value:function(f){var d=this,h=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return new Promise(function(y,g){var _=[502,503,504];h&&_.push(429);var w=new N.Retrier(d.configuration.backoffConfiguration);w.on("attempt",function(){f().then(function(S){return w.succeeded(S)}).catch(function(S){_.indexOf(S.status)>-1||S.message==="Twilsock disconnected"?w.failed(S):(w.removeAllListeners(),w.cancel(),g(S))})}),w.on("succeeded",function(S){y(S)}),w.on("cancelled",function(S){return g(S)}),w.on("failed",function(S){return g(S)}),w.start()})}},{key:"get",value:function(){var A=L.default(P.default.mark(function d(h){var y=this,g,_,w;return P.default.wrap(function(C){for(;;)switch(C.prev=C.next){case 0:if(g=this.cache.get(h),!(g&&!this.isExpired(g.timestamp))){C.next=3;break}return C.abrupt("return",g.response);case 3:return _={},C.next=6,this.executeWithRetry(function(){return y.services.transport.get(h,_,y.configuration.productId)},this.configuration.retryWhenThrottled);case 6:return w=C.sent,this.cache.set(h,{response:w,timestamp:Date.now()}),this.pokeTimer(),C.abrupt("return",w);case 10:case"end":return C.stop()}},d,this)}));function f(d){return A.apply(this,arguments)}return f}()}]),O}(),be=ce.default(function O(){he.default(this,O)});Se.default(be,"TYPING_INDICATOR","twilio.ipmsg.typing_indicator"),Se.default(be,"NEW_MESSAGE","twilio.conversations.new_message"),Se.default(be,"ADDED_TO_CONVERSATION","twilio.conversations.added_to_conversation"),Se.default(be,"REMOVED_FROM_CONVERSATION","twilio.conversations.removed_from_conversation"),Se.default(be,"CONSUMPTION_UPDATE","twilio.channel.consumption_update");function $e(O){var A=re();return function(){var d=Ke.default(O),h;if(A){var y=Ke.default(this).constructor;h=Reflect.construct(d,arguments,y)}else h=d.apply(this,arguments);return rt.default(this,h)}}function re(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var ae=Dt.scope("Participant"),K=function(O){Te.default(f,O);var A=$e(f);function f(d,h,y,g,_){var w,S,C;if(he.default(this,f),C=A.call(this),C.conversation=y,C.links=g,C.services=_,C.state={attributes:Ft(d.attributes,"Retrieved malformed attributes from the server for participant: "+h,ae),dateCreated:d.dateCreated?ct(d.dateCreated):null,dateUpdated:d.dateCreated?ct(d.dateUpdated):null,sid:h,typingTimeout:null,isTyping:!1,identity:d.identity,roleSid:(w=d.roleSid)!==null&&w!==void 0?w:"",lastReadMessageIndex:Number.isInteger(d.lastConsumedMessageIndex)?d.lastConsumedMessageIndex:null,lastReadTimestamp:d.lastConsumptionTimestamp?ct(d.lastConsumptionTimestamp):null,type:d.type||"chat",userInfo:d.userInfo,bindings:(S=d.bindings)!==null&&S!==void 0?S:{}},!d.identity&&!d.type)throw new Error("Received invalid Participant object from server: Missing identity or type of Participant.");return C}return ce.default(f,[{key:"sid",get:function(){return this.state.sid}},{key:"attributes",get:function(){return this.state.attributes}},{key:"dateCreated",get:function(){return this.state.dateCreated}},{key:"dateUpdated",get:function(){return this.state.dateUpdated}},{key:"identity",get:function(){return this.state.identity}},{key:"isTyping",get:function(){return this.state.isTyping}},{key:"lastReadMessageIndex",get:function(){return this.state.lastReadMessageIndex}},{key:"lastReadTimestamp",get:function(){return this.state.lastReadTimestamp}},{key:"roleSid",get:function(){return this.state.roleSid}},{key:"type",get:function(){return this.state.type}},{key:"bindings",get:function(){var h;return(h=this.state.bindings)!==null&&h!==void 0?h:{}}},{key:"_startTyping",value:function(h){var y=this;return this.state.typingTimeout&&clearTimeout(this.state.typingTimeout),this.state.isTyping=!0,this.emit(f.typingStarted,this),this.conversation.emit(At.typingStarted,this),this.state.typingTimeout=Number(setTimeout(function(){return y._endTyping()},h)),this}},{key:"_endTyping",value:function(){this.state.typingTimeout&&(this.state.isTyping=!1,this.emit(f.typingEnded,this),this.conversation.emit(At.typingEnded,this),clearInterval(this.state.typingTimeout),this.state.typingTimeout=null)}},{key:"_update",value:function(h){var y=[],g=Ft(h.attributes,"Retrieved malformed attributes from the server for participant: "+this.state.sid,ae);h.attributes&&!_e.default(this.state.attributes,g)&&(this.state.attributes=g,y.push("attributes"));var _=ct(h.dateUpdated);h.dateUpdated&&(_==null?void 0:_.getTime())!==(this.state.dateUpdated&&this.state.dateUpdated.getTime())&&(this.state.dateUpdated=_,y.push("dateUpdated"));var w=ct(h.dateCreated);if(h.dateCreated&&(w==null?void 0:w.getTime())!==(this.state.dateCreated&&this.state.dateCreated.getTime())&&(this.state.dateCreated=w,y.push("dateCreated")),h.roleSid&&this.state.roleSid!==h.roleSid&&(this.state.roleSid=h.roleSid,y.push("roleSid")),(Number.isInteger(h.lastConsumedMessageIndex)||h.lastConsumedMessageIndex===null)&&this.state.lastReadMessageIndex!==h.lastConsumedMessageIndex&&(this.state.lastReadMessageIndex=h.lastConsumedMessageIndex,y.push("lastReadMessageIndex")),h.lastConsumptionTimestamp){var S=new Date(h.lastConsumptionTimestamp);(!this.state.lastReadTimestamp||this.state.lastReadTimestamp.getTime()!==S.getTime())&&(this.state.lastReadTimestamp=S,y.push("lastReadTimestamp"))}return h.bindings&&!_e.default(this.state.bindings,h.bindings)&&(this.state.bindings=h.bindings,y.push("bindings")),y.length>0&&this.emit(f.updated,{participant:this,updateReasons:y}),this}},{key:"getUser",value:function(){var d=L.default(P.default.mark(function y(){return P.default.wrap(function(_){for(;;)switch(_.prev=_.next){case 0:if(this.type=="chat"){_.next=2;break}throw new Error("Getting User is not supported for this Participant type: "+this.type);case 2:return _.abrupt("return",this.services.users.getUser(this.state.identity,this.state.userInfo));case 3:case"end":return _.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"remove",value:function(){var d=L.default(P.default.mark(function y(){return P.default.wrap(function(_){for(;;)switch(_.prev=_.next){case 0:return _.abrupt("return",this.conversation.removeParticipant(this));case 1:case"end":return _.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"updateAttributes",value:function(){var d=L.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this.services.commandExecutor.mutateResource("post",this.links.self,{attributes:JSON.stringify(g)});case 2:return w.abrupt("return",this);case 3:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()}]),f}(I.ReplayEventEmitter);Se.default(K,"typingStarted","typingStarted"),Se.default(K,"typingEnded","typingEnded"),Se.default(K,"updated","updated"),Ce([b.validateTypesAsync(cr),de("design:type",Function),de("design:paramtypes",[Object]),de("design:returntype",Promise)],K.prototype,"updateAttributes",null);function oe(O){var A=Y();return function(){var d=Ke.default(O),h;if(A){var y=Ke.default(this).constructor;h=Reflect.construct(d,arguments,y)}else h=d.apply(this,arguments);return rt.default(this,h)}}function Y(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var De=Dt.scope("Participants"),Re=function(O){Te.default(f,O);var A=oe(f);function f(d,h,y,g){var _;return he.default(this,f),_=A.call(this),Se.default(pe.default(_),"rosterEntityPromise",null),_.conversation=d,_.participants=h,_.links=y,_.services=g,_}return ce.default(f,[{key:"unsubscribe",value:function(){var d=L.default(P.default.mark(function y(){var g;return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:if(!this.rosterEntityPromise){w.next=6;break}return w.next=3,this.rosterEntityPromise;case 3:g=w.sent,g.close(),this.rosterEntityPromise=null;case 6:case"end":return w.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"subscribe",value:function(h){var y=this,g=typeof h=="string"?this.services.syncClient.map({id:h,mode:"open_existing"}):Promise.resolve(h);return this.rosterEntityPromise=this.rosterEntityPromise||g.then(function(_){_.on(J.SyncMap.itemAdded,function(C){De.debug(y.conversation.sid+" itemAdded: "+C.item.key),y.upsertParticipant(C.item.key,C.item.data).then(function(B){y.emit(At.participantJoined,B)})}),_.on(J.SyncMap.itemRemoved,function(C){De.debug(y.conversation.sid+" itemRemoved: "+C.key);var B=C.key;if(y.participants.has(B)){var U=y.participants.get(B);y.participants.delete(B),U&&y.emit(At.participantLeft,U)}}),_.on(J.SyncMap.itemUpdated,function(C){De.debug(y.conversation.sid+" itemUpdated: "+C.item.key),y.upsertParticipant(C.item.key,C.item.data).catch(function(B){return De.error(B)})});var w=[],S=function C(B){return B.items.forEach(function(U){w.push(y.upsertParticipant(U.key,U.data))}),B.hasNextPage?B.nextPage().then(C):null};return _.getItems().then(S).then(function(){return Promise.all(w)}).then(function(){return _})}).catch(function(_){throw y.rosterEntityPromise=null,y.services.syncClient.connectionState!="disconnected"&&De.error("Failed to get roster object for conversation",y.conversation.sid,_),De.debug("ERROR: Failed to get roster object for conversation",y.conversation.sid,_),_})}},{key:"upsertParticipantFromResponse",value:function(){var d=L.default(P.default.mark(function y(g){var _,w,S,C,B,U,H,G;return P.default.wrap(function(Xe){for(;;)switch(Xe.prev=Xe.next){case 0:return w=g.sid,S=g.attributes,C=g.date_created,B=g.date_updated,U=g.identity,H=g.role_sid,G=g.messaging_binding,Xe.next=3,this.upsertParticipant(w,{attributes:S,dateCreated:new Date(C),dateUpdated:new Date(B),identity:U,roleSid:H,lastConsumedMessageIndex:null,lastConsumptionTimestamp:null,type:(_=G==null?void 0:G.type)!==null&&_!==void 0?_:"chat"});case 3:return Xe.abrupt("return",Xe.sent);case 4:case"end":return Xe.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"upsertParticipant",value:function(){var d=L.default(P.default.mark(function y(g,_){var w=this,S,C;return P.default.wrap(function(U){for(;;)switch(U.prev=U.next){case 0:if(S=this.participants.get(g),!S){U.next=3;break}return U.abrupt("return",S._update(_));case 3:return C={self:"".concat(this.links.participants,"/").concat(g)},S=new K(_,g,this.conversation,C,this.services),this.participants.set(g,S),S.on(K.updated,function(H){return w.emit(At.participantUpdated,H)}),U.abrupt("return",S);case 8:case"end":return U.stop()}},y,this)}));function h(y,g){return d.apply(this,arguments)}return h}()},{key:"getParticipants",value:function(){var d=L.default(P.default.mark(function y(){var g=this;return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.abrupt("return",this.rosterEntityPromise?this.rosterEntityPromise.then(function(){var S=[];return g.participants.forEach(function(C){return S.push(C)}),S}):[]);case 1:case"end":return w.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"getParticipantBySid",value:function(){var d=L.default(P.default.mark(function y(g){var _=this;return P.default.wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return S.abrupt("return",this.rosterEntityPromise?this.rosterEntityPromise.then(function(){var C=_.participants.get(g);if(!C)throw new Error("Participant with SID "+g+" was not found");return C}):null);case 1:case"end":return S.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"getParticipantByIdentity",value:function(){var d=L.default(P.default.mark(function y(g){var _=this,w;return P.default.wrap(function(C){for(;;)switch(C.prev=C.next){case 0:return w=null,C.abrupt("return",this.rosterEntityPromise?this.rosterEntityPromise.then(function(){if(_.participants.forEach(function(B){B.identity===g&&(w=B)}),!w)throw new Error("Participant with identity "+g+" was not found");return w}):null);case 2:case"end":return C.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"add",value:function(){var d=L.default(P.default.mark(function y(g,_){return P.default.wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return S.next=2,this.services.commandExecutor.mutateResource("post",this.links.participants,{identity:g,attributes:typeof _<"u"?JSON.stringify(_):void 0});case 2:return S.abrupt("return",S.sent);case 3:case"end":return S.stop()}},y,this)}));function h(y,g){return d.apply(this,arguments)}return h}()},{key:"addNonChatParticipant",value:function(){var d=L.default(P.default.mark(function y(g,_){var w,S,C,B,U=arguments;return P.default.wrap(function(G){for(;;)switch(G.prev=G.next){case 0:return C=U.length>2&&U[2]!==void 0?U[2]:{},B=U.length>3&&U[3]!==void 0?U[3]:{},G.next=4,this.services.commandExecutor.mutateResource("post",this.links.participants,{attributes:typeof C<"u"?JSON.stringify(C):void 0,messaging_binding:{address:_,proxy_address:g,name:B==null||(w=B.email)===null||w===void 0?void 0:w.name,level:B==null||(S=B.email)===null||S===void 0?void 0:S.level}});case 4:return G.abrupt("return",G.sent);case 5:case"end":return G.stop()}},y,this)}));function h(y,g){return d.apply(this,arguments)}return h}()},{key:"remove",value:function(h){return this.services.commandExecutor.mutateResource("delete","".concat(this.links.participants,"/").concat(encodeURIComponent(h)))}}]),f}(I.ReplayEventEmitter),Je=function(){function O(A,f){var d;he.default(this,O),Se.default(this,"mcsMedia",null),this.services=f,A instanceof V.McsMedia&&(this.mcsMedia=A),this.state={sid:A.sid,category:A.category,filename:(d=A.filename)!==null&&d!==void 0?d:null,contentType:A.contentType,size:A.size}}return ce.default(O,[{key:"sid",get:function(){return this.state.sid}},{key:"filename",get:function(){return this.state.filename}},{key:"contentType",get:function(){return this.state.contentType}},{key:"size",get:function(){return this.state.size}},{key:"category",get:function(){return this.state.category}},{key:"getContentTemporaryUrl",value:function(){var f=this;return new V.CancellablePromise(function(){var d=L.default(P.default.mark(function h(y,g,_){var w,S,C,B;return P.default.wrap(function(H){for(;;)switch(H.prev=H.next){case 0:if(S=f.mcsMedia?void 0:f._fetchMcsMedia(),C=(w=f.mcsMedia)===null||w===void 0?void 0:w.getContentUrl(),_(function(){S&&S.cancel(),C&&C.cancel()}),H.prev=3,C){H.next=9;break}return H.next=7,S;case 7:B=H.sent,C=B==null?void 0:B.getContentUrl();case 9:if(H.t0=y,!C){H.next=16;break}return H.next=13,C;case 13:H.t1=H.sent,H.next=17;break;case 16:H.t1=null;case 17:H.t2=H.t1,(0,H.t0)(H.t2),H.next=24;break;case 21:H.prev=21,H.t3=H.catch(3),g(H.t3);case 24:case"end":return H.stop()}},h,null,[[3,21]])}));return function(h,y,g){return d.apply(this,arguments)}}())}},{key:"_fetchMcsMedia",value:function(){var f=this;return new V.CancellablePromise(function(){var d=L.default(P.default.mark(function h(y,g,_){var w;return P.default.wrap(function(C){for(;;)switch(C.prev=C.next){case 0:return f.services.mcsClient===null&&g(new Error("Media Content Service is unavailable")),w=f.services.mcsClient.get(f.state.sid),_(function(){return w.cancel()}),C.prev=3,C.next=6,w;case 6:f.mcsMedia=C.sent,f.state=f.mcsMedia._state(),y(f.mcsMedia),C.next=14;break;case 11:C.prev=11,C.t0=C.catch(3),g(C.t0);case 14:case"end":return C.stop()}},h,null,[[3,11]])}));return function(h,y,g){return d.apply(this,arguments)}}())}},{key:"_state",value:function(){return this.state}}]),O}(),Ge=function(){function O(A){he.default(this,O),this.state=A}return ce.default(O,[{key:"total",get:function(){return this.state.total}},{key:"sent",get:function(){return this.state.sent}},{key:"delivered",get:function(){return this.state.delivered}},{key:"read",get:function(){return this.state.read}},{key:"undelivered",get:function(){return this.state.undelivered}},{key:"failed",get:function(){return this.state.failed}},{key:"_update",value:function(f){this.state=f}},{key:"_isEquals",value:function(f){var d=this.total===f.total,h=this.sent===f.sent,y=this.delivered===f.delivered,g=this.read===f.read,_=this.undelivered===f.undelivered,w=this.failed===f.failed;return d&&h&&y&&g&&_&&w}}]),O}(),He=function(){function O(A,f,d,h){he.default(this,O),this.state={prevToken:d,nextToken:h,source:f,items:A}}return ce.default(O,[{key:"hasNextPage",get:function(){return!!this.state.nextToken}},{key:"hasPrevPage",get:function(){return!!this.state.prevToken}},{key:"items",get:function(){return this.state.items}},{key:"nextPage",value:function(){return this.hasNextPage?this.state.source(this.state.nextToken):Promise.reject(new Error("No next page"))}},{key:"prevPage",value:function(){return this.hasPrevPage?this.state.source(this.state.prevToken):Promise.reject(new Error("No previous page"))}}]),O}(),et=ce.default(function O(A){he.default(this,O),this.sid=A.sid,this.messageSid=A.message_sid,this.conversationSid=A.conversation_sid,this.channelMessageSid=A.channel_message_sid,this.participantSid=A.participant_sid,this.status=A.status||"queued",this.errorCode=A.error_code||0,this.dateCreated=A.date_created,this.dateUpdated=A.date_updated}),nt=function(A){return A.map(function(f){var d,h,y,g,_=JSON.stringify(f);switch(f.type){case"QUICK_REPLY":return{type:"reply",title:f.title,id:(d=f.id)!==null&&d!==void 0?d:"",index:(h=f.index)!==null&&h!==void 0?h:0,rawData:_};case"PHONE_NUMBER":return{type:"phone",title:f.title,phone:(y=f.phone)!==null&&y!==void 0?y:"",rawData:_};case"URL":return{type:"url",title:f.title,url:(g=f.url)!==null&&g!==void 0?g:"",rawData:_};default:return{type:"other",rawData:_}}})},Qe=function(A,f){var d=JSON.stringify(f);switch(A){case"twilio/text":{var h=f;return{type:"text",body:h.body,rawData:d}}case"twilio/media":{var y=f;return{type:"media",body:y.body,media:y.media,rawData:d}}case"twilio/location":{var g=f;return{type:"location",longitude:g.longitude,latitude:g.latitude,label:g.label,rawData:d}}case"twilio/quick-reply":{var _=f;return{type:"quickReply",body:_.body,replies:_.actions,rawData:d}}case"twilio/call-to-action":{var w=f;return{type:"callToAction",body:w.body,actions:nt(w.actions),rawData:d}}case"twilio/list-picker":{var S=f;return{type:"listPicker",body:S.body,button:S.button,items:S.items,rawData:d}}case"twilio/card":{var C,B,U=f;return{type:"card",title:U.title,subtitle:U.subtitle,media:(C=U.media)!==null&&C!==void 0?C:[],actions:nt((B=U.actions)!==null&&B!==void 0?B:[]),rawData:d}}default:return{type:"other",rawData:d}}},tt=function(A){for(var f=new Map,d=0,h=Object.entries(A);d<h.length;d++){var y=Q.default(h[d],2),g=y[0],_=y[1];f.set(g,Qe(g,_))}return f},at=function(){function O(A,f){he.default(this,O),this.name=A,this.value=f}return ce.default(O,[{key:"copyWithValue",value:function(f){return new O(this.name,f)}}]),O}(),st=ce.default(function O(A){he.default(this,O),this.sid=A.sid,this.friendlyName=A.friendly_name,this.variables=Object.entries(JSON.parse(A.variables)).map(function(f){var d=Q.default(f,2),h=d[0],y=d[1];return new at(h,y)}),this.variants=tt(A.variants),this.dateCreated=new Date(A.date_created),this.dateUpdated=new Date(A.date_updated)});function yr(O,A){var f=Object.keys(O);if(Object.getOwnPropertySymbols){var d=Object.getOwnPropertySymbols(O);A&&(d=d.filter(function(h){return Object.getOwnPropertyDescriptor(O,h).enumerable})),f.push.apply(f,d)}return f}function fr(O){for(var A=1;A<arguments.length;A++){var f=arguments[A]!=null?arguments[A]:{};A%2?yr(Object(f),!0).forEach(function(d){Se.default(O,d,f[d])}):Object.getOwnPropertyDescriptors?Object.defineProperties(O,Object.getOwnPropertyDescriptors(f)):yr(Object(f)).forEach(function(d){Object.defineProperty(O,d,Object.getOwnPropertyDescriptor(f,d))})}return O}function dt(O){var A=Wr();return function(){var d=Ke.default(O),h;if(A){var y=Ke.default(this).constructor;h=Reflect.construct(d,arguments,y)}else h=d.apply(this,arguments);return rt.default(this,h)}}function Wr(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function cn(O,A){it(O,A),A.add(O)}function it(O,A){if(A.has(O))throw new TypeError("Cannot initialize the same private elements twice on an object")}function Z(O,A,f){if(!A.has(O))throw new TypeError("attempted to get private field on non-instance");return f}var xe=Dt.scope("Message"),Ye=t.XMLHttpRequest||{},Mt=new WeakSet,nr=new WeakSet,Ot=function(O){Te.default(f,O);var A=dt(f);function f(d,h,y,g,_,w){var S,C,B,U,H,G,Le,Xe;return he.default(this,f),Xe=A.call(this),cn(pe.default(Xe),nr),cn(pe.default(Xe),Mt),Xe.conversation=y,Xe.links=g,Xe.configuration=_,Xe.services=w,Xe.state={sid:h.sid,index:d,author:h.author,subject:h.subject,contentSid:h.contentSid,body:(S=h.text)!==null&&S!==void 0?S:null,timestamp:h.timestamp?new Date(h.timestamp):null,dateUpdated:h.dateUpdated?new Date(h.dateUpdated):null,lastUpdatedBy:(C=h.lastUpdatedBy)!==null&&C!==void 0?C:null,attributes:Ft(h.attributes,"Got malformed attributes for the message ".concat(h.sid),xe),type:(B=h.type)!==null&&B!==void 0?B:"text",media:null,medias:null,participantSid:(U=h.memberSid)!==null&&U!==void 0?U:null,aggregatedDeliveryReceipt:h.delivery?new Ge(h.delivery):null,hasChannelMetadata:(H=h.channelMetadata)!==null&&H!==void 0?H:!1},Z(pe.default(Xe),nr,Pr).call(pe.default(Xe),(G=h.medias)!==null&&G!==void 0?G:null,(Le=h.media)!==null&&Le!==void 0?Le:null),Xe}return ce.default(f,[{key:"sid",get:function(){return this.state.sid}},{key:"author",get:function(){return this.state.author}},{key:"subject",get:function(){return this.state.subject}},{key:"contentSid",get:function(){return this.state.contentSid}},{key:"body",get:function(){return this.state.body}},{key:"dateUpdated",get:function(){return this.state.dateUpdated}},{key:"index",get:function(){return this.state.index}},{key:"lastUpdatedBy",get:function(){return this.state.lastUpdatedBy}},{key:"dateCreated",get:function(){return this.state.timestamp}},{key:"attributes",get:function(){return this.state.attributes}},{key:"type",get:function(){return this.state.type}},{key:"media",get:function(){return this.state.media}},{key:"attachedMedia",get:function(){return this.getMediaByCategories(["media"])}},{key:"participantSid",get:function(){return this.state.participantSid}},{key:"aggregatedDeliveryReceipt",get:function(){return this.state.aggregatedDeliveryReceipt}},{key:"getMediaByCategory",value:function(h){return this.getMediaByCategories(h)}},{key:"getMediaByCategories",value:function(h){var y;return((y=this.state.medias)!==null&&y!==void 0?y:[]).filter(function(g){return h.includes(g.category)})}},{key:"getEmailBody",value:function(){var h,y,g=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"text/plain";return(h=(y=this.getMediaByCategories(["body"]))===null||y===void 0?void 0:y.filter(function(_){return _.contentType==g}).shift())!==null&&h!==void 0?h:null}},{key:"getEmailHistory",value:function(){var h,y,g=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"text/plain";return(h=(y=this.getMediaByCategories(["history"]))===null||y===void 0?void 0:y.filter(function(_){return _.contentType==g}).shift())!==null&&h!==void 0?h:null}},{key:"_update",value:function(h){var y,g=this,_,w,S,C=[];(h.text||typeof h.text=="string")&&h.text!==this.state.body&&(this.state.body=h.text,C.push("body")),h.subject&&h.subject!==this.state.subject&&(this.state.subject=h.subject,C.push("subject")),h.lastUpdatedBy&&h.lastUpdatedBy!==this.state.lastUpdatedBy&&(this.state.lastUpdatedBy=h.lastUpdatedBy,C.push("lastUpdatedBy")),h.author&&h.author!==this.state.author&&(this.state.author=h.author,C.push("author")),h.dateUpdated&&new Date(h.dateUpdated).getTime()!==(this.state.dateUpdated&&this.state.dateUpdated.getTime())&&(this.state.dateUpdated=new Date(h.dateUpdated),C.push("dateUpdated")),h.timestamp&&new Date(h.timestamp).getTime()!==(this.state.timestamp&&this.state.timestamp.getTime())&&(this.state.timestamp=new Date(h.timestamp),C.push("dateCreated"));var B=Ft(h.attributes,"Got malformed attributes for the message ".concat(this.sid),xe);_e.default(this.state.attributes,B)||(this.state.attributes=B,C.push("attributes"));var U=h.delivery,H=this.state.aggregatedDeliveryReceipt,G=!!U&&!!U.total&&!!U.delivered&&!!U.failed&&!!U.read&&!!U.sent&&!!U.undelivered;G&&(H?H._isEquals(U)||(H._update(U),C.push("deliveryReceipt")):(this.state.aggregatedDeliveryReceipt=new Ge(U),C.push("deliveryReceipt")));var Le=((y=h.medias)!==null&&y!==void 0?y:[]).map(function(Nt){var Tt;return(Tt=Z(g,Mt,ir).call(g,Nt))===null||Tt===void 0?void 0:Tt._state()}).filter(function(Nt){return Nt!==null}),Xe=((_=this.state.medias)!==null&&_!==void 0?_:[]).map(function(Nt){return Nt._state()}).filter(function(Nt){return Nt!==null});if(!_e.default(Le,Xe)||!_e.default((w=Z(this,Mt,ir).call(this,h.media))===null||w===void 0?void 0:w._state(),(S=this.state.media)===null||S===void 0?void 0:S._state())){var We,Ve;Z(this,nr,Pr).call(this,(We=h.medias)!==null&&We!==void 0?We:null,(Ve=h.media)!==null&&Ve!==void 0?Ve:null),C.push("media")}C.length>0&&this.emit("updated",{message:this,updateReasons:C})}},{key:"getParticipant",value:function(){var d=L.default(P.default.mark(function y(){var g=this,_,w;return P.default.wrap(function(C){for(;;)switch(C.prev=C.next){case 0:if(_=null,!this.state.participantSid){C.next=5;break}return C.next=4,this.conversation.getParticipantBySid(this.state.participantSid).catch(function(){return xe.debug('Participant with sid "'.concat(g.participantSid,'" not found for message ').concat(g.sid)),null});case 4:_=C.sent;case 5:if(!(!_&&this.state.author)){C.next=9;break}return C.next=8,this.conversation.getParticipantByIdentity(this.state.author).catch(function(){return xe.debug('Participant with identity "'.concat(g.author,'" not found for message ').concat(g.sid)),null});case 8:_=C.sent;case 9:if(!_){C.next=11;break}return C.abrupt("return",_);case 11:throw w="Participant with ",this.state.participantSid&&(w+="SID '"+this.state.participantSid+"' "),this.state.author&&(this.state.participantSid&&(w+="or "),w+="identity '"+this.state.author+"' "),w==="Participant with "&&(w="Participant "),w+="was not found",new Error(w);case 17:case"end":return C.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"getDetailedDeliveryReceipts",value:function(){var d=L.default(P.default.mark(function y(){var g,_;return P.default.wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return S.next=2,this._getDetailedDeliveryReceiptsPaginator();case 2:g=S.sent,_=g.items;case 4:if(!g.hasNextPage){S.next=11;break}return S.next=7,g.nextPage();case 7:g=S.sent,_=[].concat(Ne.default(_),Ne.default(g.items)),S.next=4;break;case 11:return S.abrupt("return",_);case 12:case"end":return S.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"remove",value:function(){var d=L.default(P.default.mark(function y(){return P.default.wrap(function(_){for(;;)switch(_.prev=_.next){case 0:return _.next=2,this.services.commandExecutor.mutateResource("delete",this.links.self);case 2:return _.abrupt("return",this);case 3:case"end":return _.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"updateBody",value:function(){var d=L.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this.services.commandExecutor.mutateResource("post",this.links.self,{body:g});case 2:return w.abrupt("return",this);case 3:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"updateAttributes",value:function(){var d=L.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this.services.commandExecutor.mutateResource("post",this.links.self,{attributes:typeof g<"u"?JSON.stringify(g):void 0});case 2:return w.abrupt("return",this);case 3:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"attachTemporaryUrlsFor",value:function(){var d=L.default(P.default.mark(function y(g){var _=this,w;return P.default.wrap(function(C){for(;;)switch(C.prev=C.next){case 0:if(w=g==null?void 0:g.map(function(B){return B.sid}),!(this.services.mcsClient&&w)){C.next=7;break}return C.next=4,this.services.mcsClient.mediaSetGet(w);case 4:return C.abrupt("return",C.sent.map(function(B){return new Je(B,_.services)}));case 7:throw new Error("Media Content Service is unavailable");case 8:case"end":return C.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"getTemporaryContentUrlsForMedia",value:function(h){var y=h.map(function(g){return g.sid});return this.getTemporaryContentUrlsForMediaSids(y)}},{key:"getTemporaryContentUrlsForMediaSids",value:function(h){var y=this;return new V.CancellablePromise(function(){var g=L.default(P.default.mark(function _(w,S,C){var B,U;return P.default.wrap(function(G){for(;;)switch(G.prev=G.next){case 0:if(B=y.services.mcsClient.mediaSetGetContentUrls(h??[]),!(!y.services.mcsClient||!h)){G.next=4;break}return S(new Error("Media Content Service is unavailable")),G.abrupt("return");case 4:return C(function(){B.cancel()}),G.prev=5,G.next=8,B;case 8:U=G.sent,w(U),G.next=15;break;case 12:G.prev=12,G.t0=G.catch(5),S(G.t0);case 15:case"end":return G.stop()}},_,null,[[5,12]])}));return function(_,w,S){return g.apply(this,arguments)}}())}},{key:"getTemporaryContentUrlsForAttachedMedia",value:function(){var h,y=this.attachedMedia,g=(h=y==null?void 0:y.map(function(_){return _.sid}))!==null&&h!==void 0?h:[];return this.getTemporaryContentUrlsForMediaSids(g)}},{key:"_getDetailedDeliveryReceiptsPaginator",value:function(){var d=L.default(P.default.mark(function y(g){var _=this,w,S,C;return P.default.wrap(function(U){for(;;)switch(U.prev=U.next){case 0:return w=this.configuration.links.messagesReceipts.replace("%s",this.conversation.sid).replace("%s",this.sid),S=new Pt(w).arg("PageToken",g==null?void 0:g.pageToken).arg("PageSize",g==null?void 0:g.pageSize).build(),U.next=4,this.services.network.get(S);case 4:return C=U.sent,U.abrupt("return",new He(C.body.delivery_receipts.map(function(H){return new et(H)}),function(H,G){return _._getDetailedDeliveryReceiptsPaginator({pageToken:H,pageSize:G})},C.body.meta.previous_token,C.body.meta.next_token));case 6:case"end":return U.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"getContentData",value:function(){var h=this;return new V.CancellablePromise(function(){var y=L.default(P.default.mark(function g(_,w,S){var C,B,U,H,G,Le,Xe,We,Ve,Nt;return P.default.wrap(function(pt){for(;;)switch(pt.prev=pt.next){case 0:if(h.state.contentSid!==null){pt.next=3;break}return _(null),pt.abrupt("return");case 3:if(C=h.getMediaByCategories(["body"]),C!==null){pt.next=7;break}return _(null),pt.abrupt("return");case 7:if(B="application/x-vnd.com.twilio.rich.",U=C.filter(function(hr){return hr.contentType.startsWith(B)}),U.length!==0){pt.next=12;break}return _(null),pt.abrupt("return");case 12:return H=U[0],G=H.getContentTemporaryUrl(),S(function(){G.cancel()}),pt.prev=15,pt.next=18,G;case 18:Le=pt.sent,pt.next=25;break;case 21:return pt.prev=21,pt.t0=pt.catch(15),w(pt.t0),pt.abrupt("return");case 25:if(Le!==null){pt.next=28;break}return _(null),pt.abrupt("return");case 28:return Xe=new Promise(function(hr,fi){var ut,di=!1,On=new Ye;On.open("GET",(ut=Le)!==null&&ut!==void 0?ut:"",!0),On.responseType="text",On.onreadystatechange=function(){On.readyState!==4||di||hr(On.responseText)},On.onerror=function(){fi(On.statusText)},S(function(){di=!0,On.abort(),fi(new Error("XHR has been aborted"))}),On.send()}),pt.prev=29,pt.next=32,Xe;case 32:Ve=pt.sent,We=JSON.parse(Ve),pt.next=40;break;case 36:return pt.prev=36,pt.t1=pt.catch(29),w(pt.t1),pt.abrupt("return");case 40:Nt=H.contentType.replace(B,"").replace(".","/"),_(Qe(Nt,We.data));case 42:case"end":return pt.stop()}},g,null,[[15,21],[29,36]])}));return function(g,_,w){return y.apply(this,arguments)}}())}},{key:"getChannelMetadata",value:function(){var d=L.default(P.default.mark(function y(){return P.default.wrap(function(_){for(;;)switch(_.prev=_.next){case 0:if(this.state.hasChannelMetadata){_.next=2;break}return _.abrupt("return",null);case 2:return _.next=4,this.services.channelMetadataClient.getChannelMetadata(this.conversation.sid,this.sid);case 4:return _.abrupt("return",_.sent);case 5:case"end":return _.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"getMessageRecipients",value:function(){var d=L.default(P.default.mark(function y(){return P.default.wrap(function(_){for(;;)switch(_.prev=_.next){case 0:return _.next=2,this.services.messageRecipientsClient.getRecipientsFromMessage(this.conversation.sid,this.sid);case 2:return _.abrupt("return",_.sent);case 3:case"end":return _.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()}]),f}(I.ReplayEventEmitter);function ir(O){var A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null;return O?A?new Je(fr(fr({},O),{},{category:A}),this.services):new Je(O,this.services):null}function Pr(O,A){var f=this;this.state.media=Z(this,Mt,ir).call(this,A),this.state.medias=O?O.map(function(d){return Z(f,Mt,ir).call(f,d)}).filter(function(d){return d!==null}):A&&!O?[Z(this,Mt,ir).call(this,A,"media")].filter(function(d){return d!==null}):null}Se.default(Ot,"updated","updated"),Ce([D.deprecated("getMediaByCategory","getMediaByCategories"),de("design:type",Function),de("design:paramtypes",[Array]),de("design:returntype",Array)],Ot.prototype,"getMediaByCategory",null),Ce([b.validateTypes([b.nonEmptyString,"undefined"]),de("design:type",Function),de("design:paramtypes",[Object]),de("design:returntype",Je)],Ot.prototype,"getEmailBody",null),Ce([b.validateTypes([b.nonEmptyString,"undefined"]),de("design:type",Function),de("design:paramtypes",[Object]),de("design:returntype",Je)],Ot.prototype,"getEmailHistory",null),Ce([b.validateTypesAsync("string"),de("design:type",Function),de("design:paramtypes",[String]),de("design:returntype",Promise)],Ot.prototype,"updateBody",null),Ce([b.validateTypesAsync(cr),de("design:type",Function),de("design:paramtypes",[Object]),de("design:returntype",Promise)],Ot.prototype,"updateAttributes",null),Ce([D.deprecated("attachTemporaryUrlsFor","getTemporaryContentUrlsForMedia"),de("design:type",Function),de("design:paramtypes",[Array]),de("design:returntype",Promise)],Ot.prototype,"attachTemporaryUrlsFor",null),Ce([b.validateTypesAsync(b.nonEmptyArray("media",Je)),de("design:type",Function),de("design:paramtypes",[Array]),de("design:returntype",V.CancellablePromise)],Ot.prototype,"getTemporaryContentUrlsForMedia",null),Ce([b.validateTypesAsync(b.nonEmptyArray("strings","string")),de("design:type",Function),de("design:paramtypes",[Array]),de("design:returntype",V.CancellablePromise)],Ot.prototype,"getTemporaryContentUrlsForMediaSids",null);function Mr(O,A){var f=Object.keys(O);if(Object.getOwnPropertySymbols){var d=Object.getOwnPropertySymbols(O);A&&(d=d.filter(function(h){return Object.getOwnPropertyDescriptor(O,h).enumerable})),f.push.apply(f,d)}return f}function dr(O){for(var A=1;A<arguments.length;A++){var f=arguments[A]!=null?arguments[A]:{};A%2?Mr(Object(f),!0).forEach(function(d){Se.default(O,d,f[d])}):Object.getOwnPropertyDescriptors?Object.defineProperties(O,Object.getOwnPropertyDescriptors(f)):Mr(Object(f)).forEach(function(d){Object.defineProperty(O,d,Object.getOwnPropertyDescriptor(f,d))})}return O}function $n(O,A){var f=typeof Symbol<"u"&&O[Symbol.iterator]||O["@@iterator"];if(!f){if(Array.isArray(O)||(f=Gr(O))||A){f&&(O=f);var d=0,h=function(){};return{s:h,n:function(){return d>=O.length?{done:!0}:{done:!1,value:O[d++]}},e:function(S){throw S},f:h}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
468
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var y=!0,g=!1,_;return{s:function(){f=f.call(O)},n:function(){var S=f.next();return y=S.done,S},e:function(S){g=!0,_=S},f:function(){try{!y&&f.return!=null&&f.return()}finally{if(g)throw _}}}}function Gr(O,A){if(O){if(typeof O=="string")return oa(O,A);var f=Object.prototype.toString.call(O).slice(8,-1);if(f==="Object"&&O.constructor&&(f=O.constructor.name),f==="Map"||f==="Set")return Array.from(O);if(f==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(f))return oa(O,A)}}function oa(O,A){(A==null||A>O.length)&&(A=O.length);for(var f=0,d=new Array(A);f<A;f++)d[f]=O[f];return d}function ja(O){var A=Fa();return function(){var d=Ke.default(O),h;if(A){var y=Ke.default(this).constructor;h=Reflect.construct(d,arguments,y)}else h=d.apply(this,arguments);return rt.default(this,h)}}function Fa(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var Er=Dt.scope("Messages"),Ua=function(O){Te.default(f,O);var A=ja(f);function f(d,h,y){var g;return he.default(this,f),g=A.call(this),g.conversation=d,g.configuration=h,g.services=y,g.messagesByIndex=new Map,g.messagesListPromise=null,g}return ce.default(f,[{key:"subscribe",value:function(){var d=L.default(P.default.mark(function y(g){var _=this,w;return P.default.wrap(function(C){for(;;)switch(C.prev=C.next){case 0:if(!this.messagesListPromise){C.next=2;break}return C.abrupt("return",this.messagesListPromise);case 2:return this.messagesListPromise=typeof g=="string"?this.services.syncClient.list({id:g,mode:"open_existing"}):Promise.resolve(g),C.prev=3,C.next=6,this.messagesListPromise;case 6:return w=C.sent,w.on("itemAdded",function(B){Er.debug("".concat(_.conversation.sid," itemAdded: ").concat(B.item.index));var U={self:"".concat(_.conversation._links.messages,"/").concat(B.item.data.sid),conversation:_.conversation._links.self,messages_receipts:"".concat(_.conversation._links.messages,"/").concat(B.item.data.sid,"/Receipts")},H=new Ot(B.item.index,B.item.data,_.conversation,U,_.configuration,_.services);if(_.messagesByIndex.has(H.index)){Er.debug("Message arrived, but is already known and ignored",_.conversation.sid,H.index);return}_.messagesByIndex.set(H.index,H),H.on("updated",function(G){return _.emit("messageUpdated",G)}),_.emit("messageAdded",H)}),w.on("itemRemoved",function(B){Er.debug("#{this.conversation.sid} itemRemoved: ".concat(B.index));var U=B.index;if(_.messagesByIndex.has(U)){var H=_.messagesByIndex.get(U);if(!H)return;_.messagesByIndex.delete(H.index),H.removeAllListeners("updated"),_.emit("messageRemoved",H)}}),w.on("itemUpdated",function(B){Er.debug("".concat(_.conversation.sid," itemUpdated: ").concat(B.item.index));var U=_.messagesByIndex.get(B.item.index);U&&U._update(B.item.data)}),C.abrupt("return",w);case 13:throw C.prev=13,C.t0=C.catch(3),this.messagesListPromise=null,this.services.syncClient.connectionState!=="disconnected"&&Er.error("Failed to get messages object for conversation",this.conversation.sid,C.t0),Er.debug("ERROR: Failed to get messages object for conversation",this.conversation.sid,C.t0),C.t0;case 19:case"end":return C.stop()}},y,this,[[3,13]])}));function h(y){return d.apply(this,arguments)}return h}()},{key:"unsubscribe",value:function(){var d=L.default(P.default.mark(function y(){var g;return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:if(this.messagesListPromise){w.next=2;break}return w.abrupt("return");case 2:return w.next=4,this.messagesListPromise;case 4:g=w.sent,g.close(),this.messagesListPromise=null;case 7:case"end":return w.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"sendV2",value:function(h){var y=this;return Er.debug("Sending message V2",h.mediaContent,h.attributes,h.emailOptions),new V.CancellablePromise(function(){var g=L.default(P.default.mark(function _(w,S,C){var B,U,H,G,Le,Xe,We,Ve,Nt,Tt,pt,hr;return P.default.wrap(function(ut){for(;;)switch(ut.prev=ut.next){case 0:U=[],H=[],C(function(){H.forEach(function(di){return di.cancel()})}),G=$n(h.mediaContent),ut.prev=4,G.s();case 6:if((Le=G.n()).done){ut.next=25;break}return Xe=Q.default(Le.value,2),We=Xe[0],Ve=Xe[1],ut.prev=8,Er.debug("Adding media to a message as ".concat(Ve instanceof FormData?"FormData":"SendMediaOptions"),Ve),pt=Ve instanceof FormData?y.services.mcsClient.postFormData(Ve,We):y.services.mcsClient.post((Nt=Ve.contentType)!==null&&Nt!==void 0?Nt:"",(Tt=Ve.media)!==null&&Tt!==void 0?Tt:"",We,Ve.filename),H.push(pt),ut.t0=U,ut.next=15,pt;case 15:ut.t1=ut.sent,ut.t0.push.call(ut.t0,ut.t1),ut.next=23;break;case 19:return ut.prev=19,ut.t2=ut.catch(8),S(ut.t2),ut.abrupt("return");case 23:ut.next=6;break;case 25:ut.next=30;break;case 27:ut.prev=27,ut.t3=ut.catch(4),G.e(ut.t3);case 30:return ut.prev=30,G.f(),ut.finish(30);case 33:return hr=y.services.commandExecutor.mutateResource("post",y.conversation._links.messages,{body:h.text,subject:(B=h.emailOptions)===null||B===void 0?void 0:B.subject,media_sids:U.map(function(di){return di.sid}),attributes:typeof h.attributes<"u"?JSON.stringify(h.attributes):void 0,content_sid:h.contentSid,content_variables:typeof h.contentVariables<"u"?JSON.stringify(h.contentVariables.reduce(function(di,On){return dr(dr({},di),{},Se.default({},On.name,On.value))},{})):void 0}),ut.prev=34,ut.t4=w,ut.next=38,hr;case 38:ut.t5=ut.sent,(0,ut.t4)(ut.t5),ut.next=45;break;case 42:ut.prev=42,ut.t6=ut.catch(34),S(ut.t6);case 45:case"end":return ut.stop()}},_,null,[[4,27,30,33],[8,19],[34,42]])}));return function(_,w,S){return g.apply(this,arguments)}}())}},{key:"send",value:function(){var d=L.default(P.default.mark(function y(g){var _,w,S=arguments;return P.default.wrap(function(B){for(;;)switch(B.prev=B.next){case 0:return _=S.length>1&&S[1]!==void 0?S[1]:{},w=S.length>2?S[2]:void 0,Er.debug("Sending text message",g,_,w),B.abrupt("return",this.services.commandExecutor.mutateResource("post",this.conversation._links.messages,{body:g??"",attributes:typeof _<"u"?JSON.stringify(_):void 0,subject:w==null?void 0:w.subject}));case 4:case"end":return B.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"sendMedia",value:function(){var d=L.default(P.default.mark(function y(g){var _,w,S,C,B,U=arguments;return P.default.wrap(function(G){for(;;)switch(G.prev=G.next){case 0:if(S=U.length>1&&U[1]!==void 0?U[1]:{},C=U.length>2?U[2]:void 0,Er.debug("Sending media message",g,S,C),Er.debug("Sending media message as ".concat(g instanceof FormData?"FormData":"SendMediaOptions"),g,S),!(g instanceof FormData)){G.next=10;break}return G.next=7,this.services.mcsClient.postFormData(g);case 7:G.t0=G.sent,G.next=13;break;case 10:return G.next=12,this.services.mcsClient.post((_=g.contentType)!==null&&_!==void 0?_:"",(w=g.media)!==null&&w!==void 0?w:"","media",g.filename);case 12:G.t0=G.sent;case 13:return B=G.t0,G.next=16,this.services.commandExecutor.mutateResource("post",this.conversation._links.messages,{media_sids:[B.sid],attributes:typeof S<"u"?JSON.stringify(S):void 0});case 16:return G.abrupt("return",G.sent);case 17:case"end":return G.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"getMessages",value:function(){var d=L.default(P.default.mark(function y(g,_){var w,S=arguments;return P.default.wrap(function(B){for(;;)switch(B.prev=B.next){case 0:return w=S.length>2&&S[2]!==void 0?S[2]:"backwards",B.abrupt("return",this._getMessages(g,_,w));case 2:case"end":return B.stop()}},y,this)}));function h(y,g){return d.apply(this,arguments)}return h}()},{key:"_wrapPaginator",value:function(h,y,g){var _=this,w=h==="desc",S=function(){return y.nextPage().then(function(U){return _._wrapPaginator(h,U,g)})},C=function(){return y.prevPage().then(function(U){return _._wrapPaginator(h,U,g)})};return g(y.items).then(function(B){return{items:B.sort(function(U,H){return U.index-H.index}),hasPrevPage:w?y.hasNextPage:y.hasPrevPage,hasNextPage:w?y.hasPrevPage:y.hasNextPage,prevPage:w?S:C,nextPage:w?C:S}})}},{key:"_upsertMessage",value:function(h,y){var g=this,_=this.messagesByIndex.get(h);if(_)return _;var w={self:"".concat(this.conversation._links.messages,"/").concat(y.sid),conversation:this.conversation._links.self,messages_receipts:"".concat(this.conversation._links.messages,"/").concat(y.sid,"/Receipts")},S=new Ot(h,y,this.conversation,w,this.configuration,this.services);return this.messagesByIndex.set(S.index,S),S.on("updated",function(C){return g.emit("messageUpdated",C)}),S}},{key:"_getMessages",value:function(){var d=L.default(P.default.mark(function y(){var g=this,_,w,S,C,B,U,H=arguments;return P.default.wrap(function(Le){for(;;)switch(Le.prev=Le.next){case 0:return _=H.length>0&&H[0]!==void 0?H[0]:30,w=H.length>1&&H[1]!==void 0?H[1]:"end",S=H.length>2&&H[2]!==void 0?H[2]:"forward",C=S==="backwards"?"desc":"asc",Le.next=6,this.messagesListPromise;case 6:return B=Le.sent,Le.next=9,B==null?void 0:B.getItems({from:w!=="end"?w:void 0,pageSize:_,order:C,limit:_});case 9:return U=Le.sent,Le.next=12,this._wrapPaginator(C,U,function(Xe){return Promise.all(Xe.map(function(We){return g._upsertMessage(We.index,We.data)}))});case 12:return Le.abrupt("return",Le.sent);case 13:case"end":return Le.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()}]),f}(I.ReplayEventEmitter),ci=function(){function O(A){he.default(this,O),Se.default(this,"attributes",{}),Se.default(this,"mediaContent",[]),Se.default(this,"emailOptions",{}),this.messagesEntity=A}return ce.default(O,[{key:"send",value:function(){var f=this;return new V.CancellablePromise(function(){var d=L.default(P.default.mark(function h(y,g,_){var w,S;return P.default.wrap(function(B){for(;;)switch(B.prev=B.next){case 0:return w=f.messagesEntity.sendV2(f),_(function(){return w.cancel()}),B.prev=2,B.next=5,w;case 5:S=B.sent,y(bt(S.index)),B.next=12;break;case 9:B.prev=9,B.t0=B.catch(2),g(B.t0);case 12:case"end":return B.stop()}},h,null,[[2,9]])}));return function(h,y,g){return d.apply(this,arguments)}}())}}]),O}(),or=function(){function O(A,f){he.default(this,O),this.limits=A,this.message=new ci(f),this.emailBodies=new Map,this.emailHistories=new Map}return ce.default(O,[{key:"setBody",value:function(f){return this.message.text=f,this}},{key:"setSubject",value:function(f){return this.message.emailOptions.subject=f,this}},{key:"setAttributes",value:function(f){return this.message.attributes=f,this}},{key:"setEmailBody",value:function(f,d){return this.emailBodies.set(f,d),this}},{key:"setEmailHistory",value:function(f,d){return this.emailHistories.set(f,d),this}},{key:"setContentTemplate",value:function(f){var d=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];return this.message.contentSid=f,this.message.contentVariables=d,this}},{key:"addMedia",value:function(f){if(typeof FormData>"u"&&f instanceof FormData)throw new Error("Could not add FormData content whilst not in a browser");if(!(f instanceof FormData)){var d=f;if(!d.contentType||!d.media)throw new Error("Media content in SendMediaOptions must contain non-empty contentType and media")}return this.message.mediaContent.push(["media",f]),this}},{key:"build",value:function(){var f=this;if(this.emailBodies.forEach(function(d,h){if(!f.limits.emailBodiesAllowedContentTypes.includes(h))throw new Error("Unsupported email body content type ".concat(h))}),this.emailHistories.forEach(function(d,h){if(!f.limits.emailHistoriesAllowedContentTypes.includes(h))throw new Error("Unsupported email history content type ".concat(h))}),this.emailBodies.size>this.limits.emailBodiesAllowedContentTypes.length)throw new Error("Too many email bodies attached to the message (".concat(this.emailBodies.size," > ").concat(this.limits.emailBodiesAllowedContentTypes.length,")"));if(this.emailHistories.size>this.limits.emailHistoriesAllowedContentTypes.length)throw new Error("Too many email histories attached to the message (".concat(this.emailHistories.size," > ").concat(this.limits.emailHistoriesAllowedContentTypes.length,")"));if(this.message.mediaContent.length>this.limits.mediaAttachmentsCountLimit)throw new Error("Too many media attachments in the message (".concat(this.message.mediaContent.length," > ").concat(this.limits.mediaAttachmentsCountLimit,")"));return this.emailBodies.forEach(function(d){f.message.mediaContent.push(["body",d])}),this.emailHistories.forEach(function(d){f.message.mediaContent.push(["history",d])}),this.message}},{key:"buildAndSend",value:function(){return this.build().send()}}]),O}();Ce([b.validateTypes("string"),de("design:type",Function),de("design:paramtypes",[String]),de("design:returntype",or)],or.prototype,"setBody",null),Ce([b.validateTypes("string"),de("design:type",Function),de("design:paramtypes",[String]),de("design:returntype",or)],or.prototype,"setSubject",null),Ce([b.validateTypes(cr),de("design:type",Function),de("design:paramtypes",[Object]),de("design:returntype",or)],or.prototype,"setAttributes",null),Ce([b.validateTypes("string",[FormData,Dr]),de("design:type",Function),de("design:paramtypes",[String,Object]),de("design:returntype",or)],or.prototype,"setEmailBody",null),Ce([b.validateTypes("string",[FormData,Dr]),de("design:type",Function),de("design:paramtypes",[String,Object]),de("design:returntype",or)],or.prototype,"setEmailHistory",null),Ce([b.validateTypes("string",[b.array("content variables",at),"undefined"]),de("design:type",Function),de("design:paramtypes",[String,Array]),de("design:returntype",or)],or.prototype,"setContentTemplate",null),Ce([b.validateTypes([FormData,Dr]),de("design:type",Function),de("design:paramtypes",[Object]),de("design:returntype",or)],or.prototype,"addMedia",null);function Ba(O,A){var f=typeof Symbol<"u"&&O[Symbol.iterator]||O["@@iterator"];if(!f){if(Array.isArray(O)||(f=gn(O))||A){f&&(O=f);var d=0,h=function(){};return{s:h,n:function(){return d>=O.length?{done:!0}:{done:!1,value:O[d++]}},e:function(S){throw S},f:h}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
466
+ */(function(e){var t=typeof t<"u"?t:typeof self<"u"?self:typeof window<"u"?window:{};Object.defineProperty(e,"__esModule",{value:!0});var r=Nu,n=ms,i=ki,a=Ri,s=zn,o=gs,u=Aa,c=$i,l=Uu,p=qn,v=Ar,m=n3,b=Wr,T=_o,I=Xm,R=_z,x=bo,N=na,j=xf,X=v1,J=mn,V=W1,D=Wf,te=Bf,ue=bQ;function ee(O){return O&&typeof O=="object"&&"default"in O?O:{default:O}}function ge(O){if(O&&O.__esModule)return O;var A=Object.create(null);return O&&Object.keys(O).forEach(function(f){if(f!=="default"){var d=Object.getOwnPropertyDescriptor(O,f);Object.defineProperty(A,f,d.get?d:{enumerable:!0,get:function(){return O[f]}})}}),A.default=O,Object.freeze(A)}var L=ee(r),pe=ee(n),Te=ee(i),rt=ee(a),Ke=ee(s),Se=ee(o),ce=ee(u),he=ee(c),P=ee(l),Ie=ee(p),qe=ge(v),Ne=ee(T),_e=ee(R),Q=ee(x),kt=ee(te);function Ce(O,A,f,d){var h=arguments.length,y=h<3?A:d===null?d=Object.getOwnPropertyDescriptor(A,f):d,g;if((typeof Reflect>"u"?"undefined":Ie.default(Reflect))==="object"&&typeof Reflect.decorate=="function")y=Reflect.decorate(O,A,f,d);else for(var _=O.length-1;_>=0;_--)(g=O[_])&&(y=(h<3?g(y):h>3?g(A,f,y):g(A,f))||y);return h>3&&y&&Object.defineProperty(A,f,y),y}function de(O,A){if((typeof Reflect>"u"?"undefined":Ie.default(Reflect))==="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(O,A)}function Rt(O,A){return["".concat(new Date().toISOString()," Conversations ").concat(O,":")].concat(Array.from(A))}var Ue=qe.getLogger("twilio-conversations"),Dt=function(){function O(A){he.default(this,O),Se.default(this,"prefix",""),this.prefix=A!=null&&A.length>0?A+" ":""}return ce.default(O,[{key:"setLevel",value:function(f){Ue.setLevel(f)}},{key:"trace",value:function(){if(Ue.getLevel()==Ue.levels.TRACE){for(var f=arguments.length,d=new Array(f),h=0;h<f;h++)d[h]=arguments[h];Ue.debug.apply(null,Rt(this.prefix+"T",d))}}},{key:"debug",value:function(){for(var f=arguments.length,d=new Array(f),h=0;h<f;h++)d[h]=arguments[h];Ue.debug.apply(null,Rt(this.prefix+"D",d))}},{key:"info",value:function(){for(var f=arguments.length,d=new Array(f),h=0;h<f;h++)d[h]=arguments[h];Ue.info.apply(null,Rt(this.prefix+"I",d))}},{key:"warn",value:function(){for(var f=arguments.length,d=new Array(f),h=0;h<f;h++)d[h]=arguments[h];Ue.warn.apply(null,Rt(this.prefix+"W",d))}},{key:"error",value:function(){for(var f=arguments.length,d=new Array(f),h=0;h<f;h++)d[h]=arguments[h];Ue.error.apply(null,Rt(this.prefix+"E",d))}}],[{key:"scope",value:function(f){return new O(f)}},{key:"setLevel",value:function(f){Ue.setLevel(f)}},{key:"trace",value:function(){if(Ue.getLevel()==Ue.levels.TRACE){for(var f=arguments.length,d=new Array(f),h=0;h<f;h++)d[h]=arguments[h];Ue.debug.apply(null,Rt("T",d))}}},{key:"debug",value:function(){for(var f=arguments.length,d=new Array(f),h=0;h<f;h++)d[h]=arguments[h];Ue.debug.apply(null,Rt("D",d))}},{key:"info",value:function(){for(var f=arguments.length,d=new Array(f),h=0;h<f;h++)d[h]=arguments[h];Ue.info.apply(null,Rt("I",d))}},{key:"warn",value:function(){for(var f=arguments.length,d=new Array(f),h=0;h<f;h++)d[h]=arguments[h];Ue.warn.apply(null,Rt("W",d))}},{key:"error",value:function(){for(var f=arguments.length,d=new Array(f),h=0;h<f;h++)d[h]=arguments[h];Ue.error.apply(null,Rt("E",d))}}]),O}();function mt(O,A){var f=Object.keys(O);if(Object.getOwnPropertySymbols){var d=Object.getOwnPropertySymbols(O);A&&(d=d.filter(function(h){return Object.getOwnPropertyDescriptor(O,h).enumerable})),f.push.apply(f,d)}return f}function ke(O){for(var A=1;A<arguments.length;A++){var f=arguments[A]!=null?arguments[A]:{};A%2?mt(Object(f),!0).forEach(function(d){Se.default(O,d,f[d])}):Object.getOwnPropertyDescriptors?Object.defineProperties(O,Object.getOwnPropertyDescriptors(f)):mt(Object(f)).forEach(function(d){Object.defineProperty(O,d,Object.getOwnPropertyDescriptor(f,d))})}return O}var ft=5,St="PT5S",Oe="PT5S",Bt=100,vt=1e3,qt=4e3,sr=3,ze=!0,Tr=100,mr=1e3,Et=ce.default(function O(){var A,f,d,h,y,g,_,w,S=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},C=arguments.length>1?arguments[1]:void 0,B=arguments.length>2?arguments[2]:void 0;he.default(this,O),Se.default(this,"typingIndicatorTimeoutDefault",ft*1e3);var U=S.Chat||S.IPMessaging||S||{};this.productId=U.productId,this.links={myConversations:C.links.my_conversations,conversations:C.links.conversations,users:C.links.users,currentUser:C.links.current_user,typing:C.links.typing,mediaService:C.links.media_service,mediaSetService:C.links.media_set_service,messagesReceipts:C.links.messages_receipts},this.limits={mediaAttachmentsCountLimit:C.options.media_attachments_count_limit,mediaAttachmentSizeLimitInMb:C.options.media_attachment_size_limit_in_mb,mediaAttachmentsTotalSizeLimitInMb:C.options.media_attachments_total_size_limit_in_mb,emailHistoriesAllowedContentTypes:C.options.email_histories_allowed_mime_types,emailBodiesAllowedContentTypes:C.options.email_bodies_allowed_mime_types},this.typingIndicatorTimeoutOverride=U.typingIndicatorTimeoutOverride,this.backoffConfiguration=ke({min:vt,max:qt,maxAttemptsCount:sr},U.backoffConfigOverride),this.retryWhenThrottled=U.retryWhenThrottledOverride!==void 0?U.retryWhenThrottledOverride:ze,this.userInfosToSubscribe=(A=(f=U.userInfosToSubscribeOverride)!==null&&f!==void 0?f:C.options.user_infos_to_subscribe)!==null&&A!==void 0?A:Bt,this.reachabilityEnabled=C.options.reachability_enabled,this.userIdentity=C.identity,this.userInfo=C.sync_objects.my_user_info,this.myConversations=C.sync_objects.my_conversations;var H=(d=(h=U.httpCacheIntervalOverride)!==null&&h!==void 0?h:C.options.http_cache_interval)!==null&&d!==void 0?d:St;try{this.httpCacheInterval=m.toSeconds(m.parse(H))}catch{B.error("Failed to parse http cache interval ".concat(H,", using default value ").concat(St)),this.httpCacheInterval=m.toSeconds(m.parse(St))}var G=(y=(g=U.consumptionReportIntervalOverride)!==null&&g!==void 0?g:C.options.consumption_report_interval)!==null&&y!==void 0?y:Oe;try{this.consumptionReportInterval=m.toSeconds(m.parse(G))}catch{B.error("Failed to parse consumption report interval ".concat(G,", using default value ").concat(Oe)),this.consumptionReportInterval=m.toSeconds(m.parse(Oe))}this.channelMetadataCacheCapacity=(_=S.channelMetadataCacheCapacity)!==null&&_!==void 0?_:Tr,this.messageRecipientsCacheCapacity=(w=S.messageRecipientsCacheCapacity)!==null&&w!==void 0?w:mr});function It(O){return JSON.parse(JSON.stringify(O))}function bt(O){return typeof O<"u"&&!isNaN(Number(O))?Number(O):null}function ct(O){try{return new Date(O)}catch{return null}}function Ft(O,A,f){var d={};if(O)try{d=JSON.parse(O)}catch(h){f.warn(A,h)}return d}var Pt=function(){function O(A){he.default(this,O),this.base=A.replace(/\/$/,""),this.args=[],this.paths=[]}return ce.default(O,[{key:"arg",value:function(f,d){return typeof d<"u"&&this.args.push(encodeURIComponent(f)+"="+encodeURIComponent(d)),this}},{key:"path",value:function(f){return this.paths.push(encodeURIComponent(f)),this}},{key:"build",value:function(){var f=this.base;return this.paths.length&&(f+="/"+this.paths.join("/")),this.args.length&&(f+="?"+this.args.join("&")),f}}]),O}(),cr=b.custom(function(O){return[["string","number","boolean","object"].includes(Ie.default(O)),"a JSON type"]}),Cr=b.custom(function(O){return[["undefined","string","number","boolean","object"].includes(Ie.default(O)),"an optional JSON type"]}),Dr=b.objectSchema("send media options",{contentType:[b.literal(null),"string"],filename:["string","undefined"],media:[b.literal("null"),"string"].concat(Ne.default(typeof Buffer=="function"?[Buffer]:[]),Ne.default(typeof Blob=="function"?[Blob]:[]))});function gr(O){var A=zt();return function(){var d=Ke.default(O),h;if(A){var y=Ke.default(this).constructor;h=Reflect.construct(d,arguments,y)}else h=d.apply(this,arguments);return rt.default(this,h)}}function zt(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var lr=Dt.scope("User"),ye=function(O){Te.default(f,O);var A=gr(f);function f(d,h,y,g){var _;return he.default(this,f),_=A.call(this),Se.default(pe.default(_),"promiseToFetch",null),Se.default(pe.default(_),"updated","updated"),Se.default(pe.default(_),"userSubscribed","userSubscribed"),Se.default(pe.default(_),"userUnsubscribed","userUnsubscribed"),_.services=g,_.subscribed="initializing",_.setMaxListeners(0),_.state={identity:d,entityName:h,friendlyName:null,attributes:{},online:null,notifiable:null},_._initializationPromise=new Promise(function(w){_._resolveInitializationPromise=w}),y!==null&&_._resolveInitialization(y,d,h,!1),_}return ce.default(f,[{key:"identity",get:function(){return this.state.identity},set:function(h){this.state.identity=h}},{key:"entityName",set:function(h){this.state.entityName=h}},{key:"attributes",get:function(){return this.state.attributes}},{key:"friendlyName",get:function(){return this.state.friendlyName}},{key:"isOnline",get:function(){return this.state.online}},{key:"isNotifiable",get:function(){return this.state.notifiable}},{key:"isSubscribed",get:function(){return this.subscribed=="subscribed"}},{key:"_update",value:function(){var d=L.default(P.default.mark(function y(g,_){var w,S;return P.default.wrap(function(B){for(;;)switch(B.prev=B.next){case 0:return B.next=2,this._initializationPromise;case 2:w=[],lr.debug("User for",this.state.identity,"updated:",g,_),B.t0=g,B.next=B.t0==="friendlyName"?7:B.t0==="attributes"?9:B.t0==="reachability"?12:15;break;case 7:return this.state.friendlyName!==_.value&&(w.push("friendlyName"),this.state.friendlyName=_.value),B.abrupt("break",16);case 9:return S=Ft(_.value,"Retrieved malformed attributes from the server for user: ".concat(this.state.identity),lr),_e.default(this.state.attributes,S)||(this.state.attributes=S,w.push("attributes")),B.abrupt("break",16);case 12:return this.state.online!==_.online&&(this.state.online=_.online,w.push("reachabilityOnline")),this.state.notifiable!==_.notifiable&&(this.state.notifiable=_.notifiable,w.push("reachabilityNotifiable")),B.abrupt("break",16);case 15:return B.abrupt("return");case 16:w.length>0&&this.emit("updated",{user:this,updateReasons:w});case 17:case"end":return B.stop()}},y,this)}));function h(y,g){return d.apply(this,arguments)}return h}()},{key:"_updateReachabilityInfo",value:function(){var d=L.default(P.default.mark(function y(g,_){var w=this;return P.default.wrap(function(C){for(;;)switch(C.prev=C.next){case 0:return C.next=2,this._initializationPromise;case 2:if(this.configuration.reachabilityEnabled){C.next=4;break}return C.abrupt("return",Promise.resolve());case 4:return C.abrupt("return",g.get("reachability").then(_).catch(function(B){lr.warn("Failed to get reachability info for ",w.state.identity,B)}));case 5:case"end":return C.stop()}},y,this)}));function h(y,g){return d.apply(this,arguments)}return h}()},{key:"_fetch",value:function(){var d=L.default(P.default.mark(function y(){var g=this;return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this._initializationPromise;case 2:if(this.state.entityName){w.next=4;break}return w.abrupt("return",this);case 4:return this.promiseToFetch=this.services.syncClient.map({id:this.state.entityName,mode:"open_existing",includeItems:!0}).then(function(S){return g.entity=S,S.on("itemUpdated",function(C){return lr.debug(g.state.entityName+" ("+g.state.identity+") itemUpdated: "+C.item.key),g._update(C.item.key,C.item.data)}),S.on("itemAdded",function(C){return lr.debug(g.state.entityName+" ("+g.state.identity+") itemAdded: "+C.item.key),g._update(C.item.key,C.item.data)}),Promise.all([S.get("friendlyName").then(function(C){return g._update(C.key,C.data)}),S.get("attributes").then(function(C){return g._update(C.key,C.data)}),g._updateReachabilityInfo(S,function(C){return g._update(C.key,C.data)})])}).then(function(){return lr.debug("Fetched for",g.identity),g.subscribed="subscribed",g.emit("userSubscribed",g),g}).catch(function(S){throw g.promiseToFetch=null,S}),w.abrupt("return",this.promiseToFetch);case 6:case"end":return w.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"_ensureFetched",value:function(){var d=L.default(P.default.mark(function y(){return P.default.wrap(function(_){for(;;)switch(_.prev=_.next){case 0:return _.next=2,this._initializationPromise;case 2:return _.abrupt("return",this.promiseToFetch||this._fetch());case 3:case"end":return _.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"updateAttributes",value:function(){var d=L.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this._initializationPromise;case 2:if(this.subscribed!="unsubscribed"){w.next=4;break}throw new Error("Can't modify unsubscribed object");case 4:return w.next=6,this.services.commandExecutor.mutateResource("post",this.links.self,{attributes:JSON.stringify(g)});case 6:return w.abrupt("return",this);case 7:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"updateFriendlyName",value:function(){var d=L.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this._initializationPromise;case 2:if(this.subscribed!="unsubscribed"){w.next=4;break}throw new Error("Can't modify unsubscribed object");case 4:return w.next=6,this.services.commandExecutor.mutateResource("post",this.links.self,{friendly_name:g});case 6:return w.abrupt("return",this);case 7:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"unsubscribe",value:function(){var d=L.default(P.default.mark(function y(){return P.default.wrap(function(_){for(;;)switch(_.prev=_.next){case 0:return _.next=2,this._initializationPromise;case 2:if(!this.promiseToFetch){_.next=9;break}return _.next=5,this.promiseToFetch;case 5:this.entity.close(),this.promiseToFetch=null,this.subscribed="unsubscribed",this.emit("userUnsubscribed",this);case 9:case"end":return _.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"_resolveInitialization",value:function(h,y,g,_){this.configuration=h,this.identity=y,this.entityName=g,this.links={self:"".concat(this.configuration.links.users,"/").concat(encodeURIComponent(this.identity))},this._resolveInitializationPromise(),_&&this.emit("updated",{user:this,updateReasons:["friendlyName","attributes","reachabilityOnline","reachabilityNotifiable"]})}}]),f}(I.ReplayEventEmitter);Ce([b.validateTypesAsync(cr),de("design:type",Function),de("design:paramtypes",[Object]),de("design:returntype",Promise)],ye.prototype,"updateAttributes",null),Ce([b.validateTypesAsync(["string"]),de("design:type",Function),de("design:paramtypes",[String]),de("design:returntype",Promise)],ye.prototype,"updateFriendlyName",null);function we(O,A){var f=typeof Symbol<"u"&&O[Symbol.iterator]||O["@@iterator"];if(!f){if(Array.isArray(O)||(f=se(O))||A){f&&(O=f);var d=0,h=function(){};return{s:h,n:function(){return d>=O.length?{done:!0}:{done:!1,value:O[d++]}},e:function(S){throw S},f:h}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
467
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var y=!0,g=!1,_;return{s:function(){f=f.call(O)},n:function(){var S=f.next();return y=S.done,S},e:function(S){g=!0,_=S},f:function(){try{!y&&f.return!=null&&f.return()}finally{if(g)throw _}}}}function se(O,A){if(O){if(typeof O=="string")return me(O,A);var f=Object.prototype.toString.call(O).slice(8,-1);if(f==="Object"&&O.constructor&&(f=O.constructor.name),f==="Map"||f==="Set")return Array.from(O);if(f==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(f))return me(O,A)}}function me(O,A){(A==null||A>O.length)&&(A=O.length);for(var f=0,d=new Array(A);f<A;f++)d[f]=O[f];return d}var le=function(){function O(A,f){he.default(this,O),this.configuration=A,this.services=f,this.cache=new Map,this.cacheLifetime=this.configuration.httpCacheInterval*100,this.cleanupCache()}return ce.default(O,[{key:"isExpired",value:function(f){return!this.cacheLifetime||Date.now()-f>this.cacheLifetime}},{key:"cleanupCache",value:function(){var f=we(this.cache),d;try{for(f.s();!(d=f.n()).done;){var h=Q.default(d.value,2),y=h[0],g=h[1];this.isExpired(g.timestamp)&&this.cache.delete(y)}}catch(_){f.e(_)}finally{f.f()}this.cache.size===0&&clearInterval(this.timer)}},{key:"pokeTimer",value:function(){var f=this;this.timer=this.timer||setInterval(function(){return f.cleanupCache()},this.cacheLifetime*2)}},{key:"executeWithRetry",value:function(f){var d=this,h=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return new Promise(function(y,g){var _=[502,503,504];h&&_.push(429);var w=new N.Retrier(d.configuration.backoffConfiguration);w.on("attempt",function(){f().then(function(S){return w.succeeded(S)}).catch(function(S){_.indexOf(S.status)>-1||S.message==="Twilsock disconnected"?w.failed(S):(w.removeAllListeners(),w.cancel(),g(S))})}),w.on("succeeded",function(S){y(S)}),w.on("cancelled",function(S){return g(S)}),w.on("failed",function(S){return g(S)}),w.start()})}},{key:"get",value:function(){var A=L.default(P.default.mark(function d(h){var y=this,g,_,w;return P.default.wrap(function(C){for(;;)switch(C.prev=C.next){case 0:if(g=this.cache.get(h),!(g&&!this.isExpired(g.timestamp))){C.next=3;break}return C.abrupt("return",g.response);case 3:return _={},C.next=6,this.executeWithRetry(function(){return y.services.transport.get(h,_,y.configuration.productId)},this.configuration.retryWhenThrottled);case 6:return w=C.sent,this.cache.set(h,{response:w,timestamp:Date.now()}),this.pokeTimer(),C.abrupt("return",w);case 10:case"end":return C.stop()}},d,this)}));function f(d){return A.apply(this,arguments)}return f}()}]),O}(),be=ce.default(function O(){he.default(this,O)});Se.default(be,"TYPING_INDICATOR","twilio.ipmsg.typing_indicator"),Se.default(be,"NEW_MESSAGE","twilio.conversations.new_message"),Se.default(be,"ADDED_TO_CONVERSATION","twilio.conversations.added_to_conversation"),Se.default(be,"REMOVED_FROM_CONVERSATION","twilio.conversations.removed_from_conversation"),Se.default(be,"CONSUMPTION_UPDATE","twilio.channel.consumption_update");function $e(O){var A=re();return function(){var d=Ke.default(O),h;if(A){var y=Ke.default(this).constructor;h=Reflect.construct(d,arguments,y)}else h=d.apply(this,arguments);return rt.default(this,h)}}function re(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var ae=Dt.scope("Participant"),K=function(O){Te.default(f,O);var A=$e(f);function f(d,h,y,g,_){var w,S,C;if(he.default(this,f),C=A.call(this),C.conversation=y,C.links=g,C.services=_,C.state={attributes:Ft(d.attributes,"Retrieved malformed attributes from the server for participant: "+h,ae),dateCreated:d.dateCreated?ct(d.dateCreated):null,dateUpdated:d.dateCreated?ct(d.dateUpdated):null,sid:h,typingTimeout:null,isTyping:!1,identity:d.identity,roleSid:(w=d.roleSid)!==null&&w!==void 0?w:"",lastReadMessageIndex:Number.isInteger(d.lastConsumedMessageIndex)?d.lastConsumedMessageIndex:null,lastReadTimestamp:d.lastConsumptionTimestamp?ct(d.lastConsumptionTimestamp):null,type:d.type||"chat",userInfo:d.userInfo,bindings:(S=d.bindings)!==null&&S!==void 0?S:{}},!d.identity&&!d.type)throw new Error("Received invalid Participant object from server: Missing identity or type of Participant.");return C}return ce.default(f,[{key:"sid",get:function(){return this.state.sid}},{key:"attributes",get:function(){return this.state.attributes}},{key:"dateCreated",get:function(){return this.state.dateCreated}},{key:"dateUpdated",get:function(){return this.state.dateUpdated}},{key:"identity",get:function(){return this.state.identity}},{key:"isTyping",get:function(){return this.state.isTyping}},{key:"lastReadMessageIndex",get:function(){return this.state.lastReadMessageIndex}},{key:"lastReadTimestamp",get:function(){return this.state.lastReadTimestamp}},{key:"roleSid",get:function(){return this.state.roleSid}},{key:"type",get:function(){return this.state.type}},{key:"bindings",get:function(){var h;return(h=this.state.bindings)!==null&&h!==void 0?h:{}}},{key:"_startTyping",value:function(h){var y=this;return this.state.typingTimeout&&clearTimeout(this.state.typingTimeout),this.state.isTyping=!0,this.emit(f.typingStarted,this),this.conversation.emit(At.typingStarted,this),this.state.typingTimeout=Number(setTimeout(function(){return y._endTyping()},h)),this}},{key:"_endTyping",value:function(){this.state.typingTimeout&&(this.state.isTyping=!1,this.emit(f.typingEnded,this),this.conversation.emit(At.typingEnded,this),clearInterval(this.state.typingTimeout),this.state.typingTimeout=null)}},{key:"_update",value:function(h){var y=[],g=Ft(h.attributes,"Retrieved malformed attributes from the server for participant: "+this.state.sid,ae);h.attributes&&!_e.default(this.state.attributes,g)&&(this.state.attributes=g,y.push("attributes"));var _=ct(h.dateUpdated);h.dateUpdated&&(_==null?void 0:_.getTime())!==(this.state.dateUpdated&&this.state.dateUpdated.getTime())&&(this.state.dateUpdated=_,y.push("dateUpdated"));var w=ct(h.dateCreated);if(h.dateCreated&&(w==null?void 0:w.getTime())!==(this.state.dateCreated&&this.state.dateCreated.getTime())&&(this.state.dateCreated=w,y.push("dateCreated")),h.roleSid&&this.state.roleSid!==h.roleSid&&(this.state.roleSid=h.roleSid,y.push("roleSid")),(Number.isInteger(h.lastConsumedMessageIndex)||h.lastConsumedMessageIndex===null)&&this.state.lastReadMessageIndex!==h.lastConsumedMessageIndex&&(this.state.lastReadMessageIndex=h.lastConsumedMessageIndex,y.push("lastReadMessageIndex")),h.lastConsumptionTimestamp){var S=new Date(h.lastConsumptionTimestamp);(!this.state.lastReadTimestamp||this.state.lastReadTimestamp.getTime()!==S.getTime())&&(this.state.lastReadTimestamp=S,y.push("lastReadTimestamp"))}return h.bindings&&!_e.default(this.state.bindings,h.bindings)&&(this.state.bindings=h.bindings,y.push("bindings")),y.length>0&&this.emit(f.updated,{participant:this,updateReasons:y}),this}},{key:"getUser",value:function(){var d=L.default(P.default.mark(function y(){return P.default.wrap(function(_){for(;;)switch(_.prev=_.next){case 0:if(this.type=="chat"){_.next=2;break}throw new Error("Getting User is not supported for this Participant type: "+this.type);case 2:return _.abrupt("return",this.services.users.getUser(this.state.identity,this.state.userInfo));case 3:case"end":return _.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"remove",value:function(){var d=L.default(P.default.mark(function y(){return P.default.wrap(function(_){for(;;)switch(_.prev=_.next){case 0:return _.abrupt("return",this.conversation.removeParticipant(this));case 1:case"end":return _.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"updateAttributes",value:function(){var d=L.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this.services.commandExecutor.mutateResource("post",this.links.self,{attributes:JSON.stringify(g)});case 2:return w.abrupt("return",this);case 3:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()}]),f}(I.ReplayEventEmitter);Se.default(K,"typingStarted","typingStarted"),Se.default(K,"typingEnded","typingEnded"),Se.default(K,"updated","updated"),Ce([b.validateTypesAsync(cr),de("design:type",Function),de("design:paramtypes",[Object]),de("design:returntype",Promise)],K.prototype,"updateAttributes",null);function oe(O){var A=Y();return function(){var d=Ke.default(O),h;if(A){var y=Ke.default(this).constructor;h=Reflect.construct(d,arguments,y)}else h=d.apply(this,arguments);return rt.default(this,h)}}function Y(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var De=Dt.scope("Participants"),Re=function(O){Te.default(f,O);var A=oe(f);function f(d,h,y,g){var _;return he.default(this,f),_=A.call(this),Se.default(pe.default(_),"rosterEntityPromise",null),_.conversation=d,_.participants=h,_.links=y,_.services=g,_}return ce.default(f,[{key:"unsubscribe",value:function(){var d=L.default(P.default.mark(function y(){var g;return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:if(!this.rosterEntityPromise){w.next=6;break}return w.next=3,this.rosterEntityPromise;case 3:g=w.sent,g.close(),this.rosterEntityPromise=null;case 6:case"end":return w.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"subscribe",value:function(h){var y=this,g=typeof h=="string"?this.services.syncClient.map({id:h,mode:"open_existing"}):Promise.resolve(h);return this.rosterEntityPromise=this.rosterEntityPromise||g.then(function(_){_.on(J.SyncMap.itemAdded,function(C){De.debug(y.conversation.sid+" itemAdded: "+C.item.key),y.upsertParticipant(C.item.key,C.item.data).then(function(B){y.emit(At.participantJoined,B)})}),_.on(J.SyncMap.itemRemoved,function(C){De.debug(y.conversation.sid+" itemRemoved: "+C.key);var B=C.key;if(y.participants.has(B)){var U=y.participants.get(B);y.participants.delete(B),U&&y.emit(At.participantLeft,U)}}),_.on(J.SyncMap.itemUpdated,function(C){De.debug(y.conversation.sid+" itemUpdated: "+C.item.key),y.upsertParticipant(C.item.key,C.item.data).catch(function(B){return De.error(B)})});var w=[],S=function C(B){return B.items.forEach(function(U){w.push(y.upsertParticipant(U.key,U.data))}),B.hasNextPage?B.nextPage().then(C):null};return _.getItems().then(S).then(function(){return Promise.all(w)}).then(function(){return _})}).catch(function(_){throw y.rosterEntityPromise=null,y.services.syncClient.connectionState!="disconnected"&&De.error("Failed to get roster object for conversation",y.conversation.sid,_),De.debug("ERROR: Failed to get roster object for conversation",y.conversation.sid,_),_})}},{key:"upsertParticipantFromResponse",value:function(){var d=L.default(P.default.mark(function y(g){var _,w,S,C,B,U,H,G;return P.default.wrap(function(Xe){for(;;)switch(Xe.prev=Xe.next){case 0:return w=g.sid,S=g.attributes,C=g.date_created,B=g.date_updated,U=g.identity,H=g.role_sid,G=g.messaging_binding,Xe.next=3,this.upsertParticipant(w,{attributes:S,dateCreated:new Date(C),dateUpdated:new Date(B),identity:U,roleSid:H,lastConsumedMessageIndex:null,lastConsumptionTimestamp:null,type:(_=G==null?void 0:G.type)!==null&&_!==void 0?_:"chat"});case 3:return Xe.abrupt("return",Xe.sent);case 4:case"end":return Xe.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"upsertParticipant",value:function(){var d=L.default(P.default.mark(function y(g,_){var w=this,S,C;return P.default.wrap(function(U){for(;;)switch(U.prev=U.next){case 0:if(S=this.participants.get(g),!S){U.next=3;break}return U.abrupt("return",S._update(_));case 3:return C={self:"".concat(this.links.participants,"/").concat(g)},S=new K(_,g,this.conversation,C,this.services),this.participants.set(g,S),S.on(K.updated,function(H){return w.emit(At.participantUpdated,H)}),U.abrupt("return",S);case 8:case"end":return U.stop()}},y,this)}));function h(y,g){return d.apply(this,arguments)}return h}()},{key:"getParticipants",value:function(){var d=L.default(P.default.mark(function y(){var g=this;return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.abrupt("return",this.rosterEntityPromise?this.rosterEntityPromise.then(function(){var S=[];return g.participants.forEach(function(C){return S.push(C)}),S}):[]);case 1:case"end":return w.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"getParticipantBySid",value:function(){var d=L.default(P.default.mark(function y(g){var _=this;return P.default.wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return S.abrupt("return",this.rosterEntityPromise?this.rosterEntityPromise.then(function(){var C=_.participants.get(g);if(!C)throw new Error("Participant with SID "+g+" was not found");return C}):null);case 1:case"end":return S.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"getParticipantByIdentity",value:function(){var d=L.default(P.default.mark(function y(g){var _=this,w;return P.default.wrap(function(C){for(;;)switch(C.prev=C.next){case 0:return w=null,C.abrupt("return",this.rosterEntityPromise?this.rosterEntityPromise.then(function(){if(_.participants.forEach(function(B){B.identity===g&&(w=B)}),!w)throw new Error("Participant with identity "+g+" was not found");return w}):null);case 2:case"end":return C.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"add",value:function(){var d=L.default(P.default.mark(function y(g,_){return P.default.wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return S.next=2,this.services.commandExecutor.mutateResource("post",this.links.participants,{identity:g,attributes:typeof _<"u"?JSON.stringify(_):void 0});case 2:return S.abrupt("return",S.sent);case 3:case"end":return S.stop()}},y,this)}));function h(y,g){return d.apply(this,arguments)}return h}()},{key:"addNonChatParticipant",value:function(){var d=L.default(P.default.mark(function y(g,_){var w,S,C,B,U=arguments;return P.default.wrap(function(G){for(;;)switch(G.prev=G.next){case 0:return C=U.length>2&&U[2]!==void 0?U[2]:{},B=U.length>3&&U[3]!==void 0?U[3]:{},G.next=4,this.services.commandExecutor.mutateResource("post",this.links.participants,{attributes:typeof C<"u"?JSON.stringify(C):void 0,messaging_binding:{address:_,proxy_address:g,name:B==null||(w=B.email)===null||w===void 0?void 0:w.name,level:B==null||(S=B.email)===null||S===void 0?void 0:S.level}});case 4:return G.abrupt("return",G.sent);case 5:case"end":return G.stop()}},y,this)}));function h(y,g){return d.apply(this,arguments)}return h}()},{key:"remove",value:function(h){return this.services.commandExecutor.mutateResource("delete","".concat(this.links.participants,"/").concat(encodeURIComponent(h)))}}]),f}(I.ReplayEventEmitter),Je=function(){function O(A,f){var d;he.default(this,O),Se.default(this,"mcsMedia",null),this.services=f,A instanceof V.McsMedia&&(this.mcsMedia=A),this.state={sid:A.sid,category:A.category,filename:(d=A.filename)!==null&&d!==void 0?d:null,contentType:A.contentType,size:A.size}}return ce.default(O,[{key:"sid",get:function(){return this.state.sid}},{key:"filename",get:function(){return this.state.filename}},{key:"contentType",get:function(){return this.state.contentType}},{key:"size",get:function(){return this.state.size}},{key:"category",get:function(){return this.state.category}},{key:"getContentTemporaryUrl",value:function(){var f=this;return new V.CancellablePromise(function(){var d=L.default(P.default.mark(function h(y,g,_){var w,S,C,B;return P.default.wrap(function(H){for(;;)switch(H.prev=H.next){case 0:if(S=f.mcsMedia?void 0:f._fetchMcsMedia(),C=(w=f.mcsMedia)===null||w===void 0?void 0:w.getContentUrl(),_(function(){S&&S.cancel(),C&&C.cancel()}),H.prev=3,C){H.next=9;break}return H.next=7,S;case 7:B=H.sent,C=B==null?void 0:B.getContentUrl();case 9:if(H.t0=y,!C){H.next=16;break}return H.next=13,C;case 13:H.t1=H.sent,H.next=17;break;case 16:H.t1=null;case 17:H.t2=H.t1,(0,H.t0)(H.t2),H.next=24;break;case 21:H.prev=21,H.t3=H.catch(3),g(H.t3);case 24:case"end":return H.stop()}},h,null,[[3,21]])}));return function(h,y,g){return d.apply(this,arguments)}}())}},{key:"_fetchMcsMedia",value:function(){var f=this;return new V.CancellablePromise(function(){var d=L.default(P.default.mark(function h(y,g,_){var w;return P.default.wrap(function(C){for(;;)switch(C.prev=C.next){case 0:return f.services.mcsClient===null&&g(new Error("Media Content Service is unavailable")),w=f.services.mcsClient.get(f.state.sid),_(function(){return w.cancel()}),C.prev=3,C.next=6,w;case 6:f.mcsMedia=C.sent,f.state=f.mcsMedia._state(),y(f.mcsMedia),C.next=14;break;case 11:C.prev=11,C.t0=C.catch(3),g(C.t0);case 14:case"end":return C.stop()}},h,null,[[3,11]])}));return function(h,y,g){return d.apply(this,arguments)}}())}},{key:"_state",value:function(){return this.state}}]),O}(),Ge=function(){function O(A){he.default(this,O),this.state=A}return ce.default(O,[{key:"total",get:function(){return this.state.total}},{key:"sent",get:function(){return this.state.sent}},{key:"delivered",get:function(){return this.state.delivered}},{key:"read",get:function(){return this.state.read}},{key:"undelivered",get:function(){return this.state.undelivered}},{key:"failed",get:function(){return this.state.failed}},{key:"_update",value:function(f){this.state=f}},{key:"_isEquals",value:function(f){var d=this.total===f.total,h=this.sent===f.sent,y=this.delivered===f.delivered,g=this.read===f.read,_=this.undelivered===f.undelivered,w=this.failed===f.failed;return d&&h&&y&&g&&_&&w}}]),O}(),He=function(){function O(A,f,d,h){he.default(this,O),this.state={prevToken:d,nextToken:h,source:f,items:A}}return ce.default(O,[{key:"hasNextPage",get:function(){return!!this.state.nextToken}},{key:"hasPrevPage",get:function(){return!!this.state.prevToken}},{key:"items",get:function(){return this.state.items}},{key:"nextPage",value:function(){return this.hasNextPage?this.state.source(this.state.nextToken):Promise.reject(new Error("No next page"))}},{key:"prevPage",value:function(){return this.hasPrevPage?this.state.source(this.state.prevToken):Promise.reject(new Error("No previous page"))}}]),O}(),et=ce.default(function O(A){he.default(this,O),this.sid=A.sid,this.messageSid=A.message_sid,this.conversationSid=A.conversation_sid,this.channelMessageSid=A.channel_message_sid,this.participantSid=A.participant_sid,this.status=A.status||"queued",this.errorCode=A.error_code||0,this.dateCreated=A.date_created,this.dateUpdated=A.date_updated}),nt=function(A){return A.map(function(f){var d,h,y,g,_=JSON.stringify(f);switch(f.type){case"QUICK_REPLY":return{type:"reply",title:f.title,id:(d=f.id)!==null&&d!==void 0?d:"",index:(h=f.index)!==null&&h!==void 0?h:0,rawData:_};case"PHONE_NUMBER":return{type:"phone",title:f.title,phone:(y=f.phone)!==null&&y!==void 0?y:"",rawData:_};case"URL":return{type:"url",title:f.title,url:(g=f.url)!==null&&g!==void 0?g:"",rawData:_};default:return{type:"other",rawData:_}}})},Qe=function(A,f){var d=JSON.stringify(f);switch(A){case"twilio/text":{var h=f;return{type:"text",body:h.body,rawData:d}}case"twilio/media":{var y=f;return{type:"media",body:y.body,media:y.media,rawData:d}}case"twilio/location":{var g=f;return{type:"location",longitude:g.longitude,latitude:g.latitude,label:g.label,rawData:d}}case"twilio/quick-reply":{var _=f;return{type:"quickReply",body:_.body,replies:_.actions,rawData:d}}case"twilio/call-to-action":{var w=f;return{type:"callToAction",body:w.body,actions:nt(w.actions),rawData:d}}case"twilio/list-picker":{var S=f;return{type:"listPicker",body:S.body,button:S.button,items:S.items,rawData:d}}case"twilio/card":{var C,B,U=f;return{type:"card",title:U.title,subtitle:U.subtitle,media:(C=U.media)!==null&&C!==void 0?C:[],actions:nt((B=U.actions)!==null&&B!==void 0?B:[]),rawData:d}}default:return{type:"other",rawData:d}}},tt=function(A){for(var f=new Map,d=0,h=Object.entries(A);d<h.length;d++){var y=Q.default(h[d],2),g=y[0],_=y[1];f.set(g,Qe(g,_))}return f},at=function(){function O(A,f){he.default(this,O),this.name=A,this.value=f}return ce.default(O,[{key:"copyWithValue",value:function(f){return new O(this.name,f)}}]),O}(),st=ce.default(function O(A){he.default(this,O),this.sid=A.sid,this.friendlyName=A.friendly_name,this.variables=Object.entries(JSON.parse(A.variables)).map(function(f){var d=Q.default(f,2),h=d[0],y=d[1];return new at(h,y)}),this.variants=tt(A.variants),this.dateCreated=new Date(A.date_created),this.dateUpdated=new Date(A.date_updated)});function yr(O,A){var f=Object.keys(O);if(Object.getOwnPropertySymbols){var d=Object.getOwnPropertySymbols(O);A&&(d=d.filter(function(h){return Object.getOwnPropertyDescriptor(O,h).enumerable})),f.push.apply(f,d)}return f}function fr(O){for(var A=1;A<arguments.length;A++){var f=arguments[A]!=null?arguments[A]:{};A%2?yr(Object(f),!0).forEach(function(d){Se.default(O,d,f[d])}):Object.getOwnPropertyDescriptors?Object.defineProperties(O,Object.getOwnPropertyDescriptors(f)):yr(Object(f)).forEach(function(d){Object.defineProperty(O,d,Object.getOwnPropertyDescriptor(f,d))})}return O}function dt(O){var A=Gr();return function(){var d=Ke.default(O),h;if(A){var y=Ke.default(this).constructor;h=Reflect.construct(d,arguments,y)}else h=d.apply(this,arguments);return rt.default(this,h)}}function Gr(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function cn(O,A){it(O,A),A.add(O)}function it(O,A){if(A.has(O))throw new TypeError("Cannot initialize the same private elements twice on an object")}function Z(O,A,f){if(!A.has(O))throw new TypeError("attempted to get private field on non-instance");return f}var xe=Dt.scope("Message"),Ye=t.XMLHttpRequest||{},Mt=new WeakSet,nr=new WeakSet,Ot=function(O){Te.default(f,O);var A=dt(f);function f(d,h,y,g,_,w){var S,C,B,U,H,G,Le,Xe;return he.default(this,f),Xe=A.call(this),cn(pe.default(Xe),nr),cn(pe.default(Xe),Mt),Xe.conversation=y,Xe.links=g,Xe.configuration=_,Xe.services=w,Xe.state={sid:h.sid,index:d,author:h.author,subject:h.subject,contentSid:h.contentSid,body:(S=h.text)!==null&&S!==void 0?S:null,timestamp:h.timestamp?new Date(h.timestamp):null,dateUpdated:h.dateUpdated?new Date(h.dateUpdated):null,lastUpdatedBy:(C=h.lastUpdatedBy)!==null&&C!==void 0?C:null,attributes:Ft(h.attributes,"Got malformed attributes for the message ".concat(h.sid),xe),type:(B=h.type)!==null&&B!==void 0?B:"text",media:null,medias:null,participantSid:(U=h.memberSid)!==null&&U!==void 0?U:null,aggregatedDeliveryReceipt:h.delivery?new Ge(h.delivery):null,hasChannelMetadata:(H=h.channelMetadata)!==null&&H!==void 0?H:!1},Z(pe.default(Xe),nr,Pr).call(pe.default(Xe),(G=h.medias)!==null&&G!==void 0?G:null,(Le=h.media)!==null&&Le!==void 0?Le:null),Xe}return ce.default(f,[{key:"sid",get:function(){return this.state.sid}},{key:"author",get:function(){return this.state.author}},{key:"subject",get:function(){return this.state.subject}},{key:"contentSid",get:function(){return this.state.contentSid}},{key:"body",get:function(){return this.state.body}},{key:"dateUpdated",get:function(){return this.state.dateUpdated}},{key:"index",get:function(){return this.state.index}},{key:"lastUpdatedBy",get:function(){return this.state.lastUpdatedBy}},{key:"dateCreated",get:function(){return this.state.timestamp}},{key:"attributes",get:function(){return this.state.attributes}},{key:"type",get:function(){return this.state.type}},{key:"media",get:function(){return this.state.media}},{key:"attachedMedia",get:function(){return this.getMediaByCategories(["media"])}},{key:"participantSid",get:function(){return this.state.participantSid}},{key:"aggregatedDeliveryReceipt",get:function(){return this.state.aggregatedDeliveryReceipt}},{key:"getMediaByCategory",value:function(h){return this.getMediaByCategories(h)}},{key:"getMediaByCategories",value:function(h){var y;return((y=this.state.medias)!==null&&y!==void 0?y:[]).filter(function(g){return h.includes(g.category)})}},{key:"getEmailBody",value:function(){var h,y,g=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"text/plain";return(h=(y=this.getMediaByCategories(["body"]))===null||y===void 0?void 0:y.filter(function(_){return _.contentType==g}).shift())!==null&&h!==void 0?h:null}},{key:"getEmailHistory",value:function(){var h,y,g=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"text/plain";return(h=(y=this.getMediaByCategories(["history"]))===null||y===void 0?void 0:y.filter(function(_){return _.contentType==g}).shift())!==null&&h!==void 0?h:null}},{key:"_update",value:function(h){var y,g=this,_,w,S,C=[];(h.text||typeof h.text=="string")&&h.text!==this.state.body&&(this.state.body=h.text,C.push("body")),h.subject&&h.subject!==this.state.subject&&(this.state.subject=h.subject,C.push("subject")),h.lastUpdatedBy&&h.lastUpdatedBy!==this.state.lastUpdatedBy&&(this.state.lastUpdatedBy=h.lastUpdatedBy,C.push("lastUpdatedBy")),h.author&&h.author!==this.state.author&&(this.state.author=h.author,C.push("author")),h.dateUpdated&&new Date(h.dateUpdated).getTime()!==(this.state.dateUpdated&&this.state.dateUpdated.getTime())&&(this.state.dateUpdated=new Date(h.dateUpdated),C.push("dateUpdated")),h.timestamp&&new Date(h.timestamp).getTime()!==(this.state.timestamp&&this.state.timestamp.getTime())&&(this.state.timestamp=new Date(h.timestamp),C.push("dateCreated"));var B=Ft(h.attributes,"Got malformed attributes for the message ".concat(this.sid),xe);_e.default(this.state.attributes,B)||(this.state.attributes=B,C.push("attributes"));var U=h.delivery,H=this.state.aggregatedDeliveryReceipt,G=!!U&&!!U.total&&!!U.delivered&&!!U.failed&&!!U.read&&!!U.sent&&!!U.undelivered;G&&(H?H._isEquals(U)||(H._update(U),C.push("deliveryReceipt")):(this.state.aggregatedDeliveryReceipt=new Ge(U),C.push("deliveryReceipt")));var Le=((y=h.medias)!==null&&y!==void 0?y:[]).map(function(Nt){var Tt;return(Tt=Z(g,Mt,ir).call(g,Nt))===null||Tt===void 0?void 0:Tt._state()}).filter(function(Nt){return Nt!==null}),Xe=((_=this.state.medias)!==null&&_!==void 0?_:[]).map(function(Nt){return Nt._state()}).filter(function(Nt){return Nt!==null});if(!_e.default(Le,Xe)||!_e.default((w=Z(this,Mt,ir).call(this,h.media))===null||w===void 0?void 0:w._state(),(S=this.state.media)===null||S===void 0?void 0:S._state())){var We,Ve;Z(this,nr,Pr).call(this,(We=h.medias)!==null&&We!==void 0?We:null,(Ve=h.media)!==null&&Ve!==void 0?Ve:null),C.push("media")}C.length>0&&this.emit("updated",{message:this,updateReasons:C})}},{key:"getParticipant",value:function(){var d=L.default(P.default.mark(function y(){var g=this,_,w;return P.default.wrap(function(C){for(;;)switch(C.prev=C.next){case 0:if(_=null,!this.state.participantSid){C.next=5;break}return C.next=4,this.conversation.getParticipantBySid(this.state.participantSid).catch(function(){return xe.debug('Participant with sid "'.concat(g.participantSid,'" not found for message ').concat(g.sid)),null});case 4:_=C.sent;case 5:if(!(!_&&this.state.author)){C.next=9;break}return C.next=8,this.conversation.getParticipantByIdentity(this.state.author).catch(function(){return xe.debug('Participant with identity "'.concat(g.author,'" not found for message ').concat(g.sid)),null});case 8:_=C.sent;case 9:if(!_){C.next=11;break}return C.abrupt("return",_);case 11:throw w="Participant with ",this.state.participantSid&&(w+="SID '"+this.state.participantSid+"' "),this.state.author&&(this.state.participantSid&&(w+="or "),w+="identity '"+this.state.author+"' "),w==="Participant with "&&(w="Participant "),w+="was not found",new Error(w);case 17:case"end":return C.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"getDetailedDeliveryReceipts",value:function(){var d=L.default(P.default.mark(function y(){var g,_;return P.default.wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return S.next=2,this._getDetailedDeliveryReceiptsPaginator();case 2:g=S.sent,_=g.items;case 4:if(!g.hasNextPage){S.next=11;break}return S.next=7,g.nextPage();case 7:g=S.sent,_=[].concat(Ne.default(_),Ne.default(g.items)),S.next=4;break;case 11:return S.abrupt("return",_);case 12:case"end":return S.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"remove",value:function(){var d=L.default(P.default.mark(function y(){return P.default.wrap(function(_){for(;;)switch(_.prev=_.next){case 0:return _.next=2,this.services.commandExecutor.mutateResource("delete",this.links.self);case 2:return _.abrupt("return",this);case 3:case"end":return _.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"updateBody",value:function(){var d=L.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this.services.commandExecutor.mutateResource("post",this.links.self,{body:g});case 2:return w.abrupt("return",this);case 3:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"updateAttributes",value:function(){var d=L.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this.services.commandExecutor.mutateResource("post",this.links.self,{attributes:typeof g<"u"?JSON.stringify(g):void 0});case 2:return w.abrupt("return",this);case 3:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"attachTemporaryUrlsFor",value:function(){var d=L.default(P.default.mark(function y(g){var _=this,w;return P.default.wrap(function(C){for(;;)switch(C.prev=C.next){case 0:if(w=g==null?void 0:g.map(function(B){return B.sid}),!(this.services.mcsClient&&w)){C.next=7;break}return C.next=4,this.services.mcsClient.mediaSetGet(w);case 4:return C.abrupt("return",C.sent.map(function(B){return new Je(B,_.services)}));case 7:throw new Error("Media Content Service is unavailable");case 8:case"end":return C.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"getTemporaryContentUrlsForMedia",value:function(h){var y=h.map(function(g){return g.sid});return this.getTemporaryContentUrlsForMediaSids(y)}},{key:"getTemporaryContentUrlsForMediaSids",value:function(h){var y=this;return new V.CancellablePromise(function(){var g=L.default(P.default.mark(function _(w,S,C){var B,U;return P.default.wrap(function(G){for(;;)switch(G.prev=G.next){case 0:if(B=y.services.mcsClient.mediaSetGetContentUrls(h??[]),!(!y.services.mcsClient||!h)){G.next=4;break}return S(new Error("Media Content Service is unavailable")),G.abrupt("return");case 4:return C(function(){B.cancel()}),G.prev=5,G.next=8,B;case 8:U=G.sent,w(U),G.next=15;break;case 12:G.prev=12,G.t0=G.catch(5),S(G.t0);case 15:case"end":return G.stop()}},_,null,[[5,12]])}));return function(_,w,S){return g.apply(this,arguments)}}())}},{key:"getTemporaryContentUrlsForAttachedMedia",value:function(){var h,y=this.attachedMedia,g=(h=y==null?void 0:y.map(function(_){return _.sid}))!==null&&h!==void 0?h:[];return this.getTemporaryContentUrlsForMediaSids(g)}},{key:"_getDetailedDeliveryReceiptsPaginator",value:function(){var d=L.default(P.default.mark(function y(g){var _=this,w,S,C;return P.default.wrap(function(U){for(;;)switch(U.prev=U.next){case 0:return w=this.configuration.links.messagesReceipts.replace("%s",this.conversation.sid).replace("%s",this.sid),S=new Pt(w).arg("PageToken",g==null?void 0:g.pageToken).arg("PageSize",g==null?void 0:g.pageSize).build(),U.next=4,this.services.network.get(S);case 4:return C=U.sent,U.abrupt("return",new He(C.body.delivery_receipts.map(function(H){return new et(H)}),function(H,G){return _._getDetailedDeliveryReceiptsPaginator({pageToken:H,pageSize:G})},C.body.meta.previous_token,C.body.meta.next_token));case 6:case"end":return U.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"getContentData",value:function(){var h=this;return new V.CancellablePromise(function(){var y=L.default(P.default.mark(function g(_,w,S){var C,B,U,H,G,Le,Xe,We,Ve,Nt;return P.default.wrap(function(pt){for(;;)switch(pt.prev=pt.next){case 0:if(h.state.contentSid!==null){pt.next=3;break}return _(null),pt.abrupt("return");case 3:if(C=h.getMediaByCategories(["body"]),C!==null){pt.next=7;break}return _(null),pt.abrupt("return");case 7:if(B="application/x-vnd.com.twilio.rich.",U=C.filter(function(hr){return hr.contentType.startsWith(B)}),U.length!==0){pt.next=12;break}return _(null),pt.abrupt("return");case 12:return H=U[0],G=H.getContentTemporaryUrl(),S(function(){G.cancel()}),pt.prev=15,pt.next=18,G;case 18:Le=pt.sent,pt.next=25;break;case 21:return pt.prev=21,pt.t0=pt.catch(15),w(pt.t0),pt.abrupt("return");case 25:if(Le!==null){pt.next=28;break}return _(null),pt.abrupt("return");case 28:return Xe=new Promise(function(hr,fi){var ut,di=!1,On=new Ye;On.open("GET",(ut=Le)!==null&&ut!==void 0?ut:"",!0),On.responseType="text",On.onreadystatechange=function(){On.readyState!==4||di||hr(On.responseText)},On.onerror=function(){fi(On.statusText)},S(function(){di=!0,On.abort(),fi(new Error("XHR has been aborted"))}),On.send()}),pt.prev=29,pt.next=32,Xe;case 32:Ve=pt.sent,We=JSON.parse(Ve),pt.next=40;break;case 36:return pt.prev=36,pt.t1=pt.catch(29),w(pt.t1),pt.abrupt("return");case 40:Nt=H.contentType.replace(B,"").replace(".","/"),_(Qe(Nt,We.data));case 42:case"end":return pt.stop()}},g,null,[[15,21],[29,36]])}));return function(g,_,w){return y.apply(this,arguments)}}())}},{key:"getChannelMetadata",value:function(){var d=L.default(P.default.mark(function y(){return P.default.wrap(function(_){for(;;)switch(_.prev=_.next){case 0:if(this.state.hasChannelMetadata){_.next=2;break}return _.abrupt("return",null);case 2:return _.next=4,this.services.channelMetadataClient.getChannelMetadata(this.conversation.sid,this.sid);case 4:return _.abrupt("return",_.sent);case 5:case"end":return _.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"getMessageRecipients",value:function(){var d=L.default(P.default.mark(function y(){return P.default.wrap(function(_){for(;;)switch(_.prev=_.next){case 0:return _.next=2,this.services.messageRecipientsClient.getRecipientsFromMessage(this.conversation.sid,this.sid);case 2:return _.abrupt("return",_.sent);case 3:case"end":return _.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()}]),f}(I.ReplayEventEmitter);function ir(O){var A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null;return O?A?new Je(fr(fr({},O),{},{category:A}),this.services):new Je(O,this.services):null}function Pr(O,A){var f=this;this.state.media=Z(this,Mt,ir).call(this,A),this.state.medias=O?O.map(function(d){return Z(f,Mt,ir).call(f,d)}).filter(function(d){return d!==null}):A&&!O?[Z(this,Mt,ir).call(this,A,"media")].filter(function(d){return d!==null}):null}Se.default(Ot,"updated","updated"),Ce([D.deprecated("getMediaByCategory","getMediaByCategories"),de("design:type",Function),de("design:paramtypes",[Array]),de("design:returntype",Array)],Ot.prototype,"getMediaByCategory",null),Ce([b.validateTypes([b.nonEmptyString,"undefined"]),de("design:type",Function),de("design:paramtypes",[Object]),de("design:returntype",Je)],Ot.prototype,"getEmailBody",null),Ce([b.validateTypes([b.nonEmptyString,"undefined"]),de("design:type",Function),de("design:paramtypes",[Object]),de("design:returntype",Je)],Ot.prototype,"getEmailHistory",null),Ce([b.validateTypesAsync("string"),de("design:type",Function),de("design:paramtypes",[String]),de("design:returntype",Promise)],Ot.prototype,"updateBody",null),Ce([b.validateTypesAsync(cr),de("design:type",Function),de("design:paramtypes",[Object]),de("design:returntype",Promise)],Ot.prototype,"updateAttributes",null),Ce([D.deprecated("attachTemporaryUrlsFor","getTemporaryContentUrlsForMedia"),de("design:type",Function),de("design:paramtypes",[Array]),de("design:returntype",Promise)],Ot.prototype,"attachTemporaryUrlsFor",null),Ce([b.validateTypesAsync(b.nonEmptyArray("media",Je)),de("design:type",Function),de("design:paramtypes",[Array]),de("design:returntype",V.CancellablePromise)],Ot.prototype,"getTemporaryContentUrlsForMedia",null),Ce([b.validateTypesAsync(b.nonEmptyArray("strings","string")),de("design:type",Function),de("design:paramtypes",[Array]),de("design:returntype",V.CancellablePromise)],Ot.prototype,"getTemporaryContentUrlsForMediaSids",null);function Mr(O,A){var f=Object.keys(O);if(Object.getOwnPropertySymbols){var d=Object.getOwnPropertySymbols(O);A&&(d=d.filter(function(h){return Object.getOwnPropertyDescriptor(O,h).enumerable})),f.push.apply(f,d)}return f}function dr(O){for(var A=1;A<arguments.length;A++){var f=arguments[A]!=null?arguments[A]:{};A%2?Mr(Object(f),!0).forEach(function(d){Se.default(O,d,f[d])}):Object.getOwnPropertyDescriptors?Object.defineProperties(O,Object.getOwnPropertyDescriptors(f)):Mr(Object(f)).forEach(function(d){Object.defineProperty(O,d,Object.getOwnPropertyDescriptor(f,d))})}return O}function $n(O,A){var f=typeof Symbol<"u"&&O[Symbol.iterator]||O["@@iterator"];if(!f){if(Array.isArray(O)||(f=Hr(O))||A){f&&(O=f);var d=0,h=function(){};return{s:h,n:function(){return d>=O.length?{done:!0}:{done:!1,value:O[d++]}},e:function(S){throw S},f:h}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
468
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var y=!0,g=!1,_;return{s:function(){f=f.call(O)},n:function(){var S=f.next();return y=S.done,S},e:function(S){g=!0,_=S},f:function(){try{!y&&f.return!=null&&f.return()}finally{if(g)throw _}}}}function Hr(O,A){if(O){if(typeof O=="string")return oa(O,A);var f=Object.prototype.toString.call(O).slice(8,-1);if(f==="Object"&&O.constructor&&(f=O.constructor.name),f==="Map"||f==="Set")return Array.from(O);if(f==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(f))return oa(O,A)}}function oa(O,A){(A==null||A>O.length)&&(A=O.length);for(var f=0,d=new Array(A);f<A;f++)d[f]=O[f];return d}function ja(O){var A=Fa();return function(){var d=Ke.default(O),h;if(A){var y=Ke.default(this).constructor;h=Reflect.construct(d,arguments,y)}else h=d.apply(this,arguments);return rt.default(this,h)}}function Fa(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var Er=Dt.scope("Messages"),Ua=function(O){Te.default(f,O);var A=ja(f);function f(d,h,y){var g;return he.default(this,f),g=A.call(this),g.conversation=d,g.configuration=h,g.services=y,g.messagesByIndex=new Map,g.messagesListPromise=null,g}return ce.default(f,[{key:"subscribe",value:function(){var d=L.default(P.default.mark(function y(g){var _=this,w;return P.default.wrap(function(C){for(;;)switch(C.prev=C.next){case 0:if(!this.messagesListPromise){C.next=2;break}return C.abrupt("return",this.messagesListPromise);case 2:return this.messagesListPromise=typeof g=="string"?this.services.syncClient.list({id:g,mode:"open_existing"}):Promise.resolve(g),C.prev=3,C.next=6,this.messagesListPromise;case 6:return w=C.sent,w.on("itemAdded",function(B){Er.debug("".concat(_.conversation.sid," itemAdded: ").concat(B.item.index));var U={self:"".concat(_.conversation._links.messages,"/").concat(B.item.data.sid),conversation:_.conversation._links.self,messages_receipts:"".concat(_.conversation._links.messages,"/").concat(B.item.data.sid,"/Receipts")},H=new Ot(B.item.index,B.item.data,_.conversation,U,_.configuration,_.services);if(_.messagesByIndex.has(H.index)){Er.debug("Message arrived, but is already known and ignored",_.conversation.sid,H.index);return}_.messagesByIndex.set(H.index,H),H.on("updated",function(G){return _.emit("messageUpdated",G)}),_.emit("messageAdded",H)}),w.on("itemRemoved",function(B){Er.debug("#{this.conversation.sid} itemRemoved: ".concat(B.index));var U=B.index;if(_.messagesByIndex.has(U)){var H=_.messagesByIndex.get(U);if(!H)return;_.messagesByIndex.delete(H.index),H.removeAllListeners("updated"),_.emit("messageRemoved",H)}}),w.on("itemUpdated",function(B){Er.debug("".concat(_.conversation.sid," itemUpdated: ").concat(B.item.index));var U=_.messagesByIndex.get(B.item.index);U&&U._update(B.item.data)}),C.abrupt("return",w);case 13:throw C.prev=13,C.t0=C.catch(3),this.messagesListPromise=null,this.services.syncClient.connectionState!=="disconnected"&&Er.error("Failed to get messages object for conversation",this.conversation.sid,C.t0),Er.debug("ERROR: Failed to get messages object for conversation",this.conversation.sid,C.t0),C.t0;case 19:case"end":return C.stop()}},y,this,[[3,13]])}));function h(y){return d.apply(this,arguments)}return h}()},{key:"unsubscribe",value:function(){var d=L.default(P.default.mark(function y(){var g;return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:if(this.messagesListPromise){w.next=2;break}return w.abrupt("return");case 2:return w.next=4,this.messagesListPromise;case 4:g=w.sent,g.close(),this.messagesListPromise=null;case 7:case"end":return w.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"sendV2",value:function(h){var y=this;return Er.debug("Sending message V2",h.mediaContent,h.attributes,h.emailOptions),new V.CancellablePromise(function(){var g=L.default(P.default.mark(function _(w,S,C){var B,U,H,G,Le,Xe,We,Ve,Nt,Tt,pt,hr;return P.default.wrap(function(ut){for(;;)switch(ut.prev=ut.next){case 0:U=[],H=[],C(function(){H.forEach(function(di){return di.cancel()})}),G=$n(h.mediaContent),ut.prev=4,G.s();case 6:if((Le=G.n()).done){ut.next=25;break}return Xe=Q.default(Le.value,2),We=Xe[0],Ve=Xe[1],ut.prev=8,Er.debug("Adding media to a message as ".concat(Ve instanceof FormData?"FormData":"SendMediaOptions"),Ve),pt=Ve instanceof FormData?y.services.mcsClient.postFormData(Ve,We):y.services.mcsClient.post((Nt=Ve.contentType)!==null&&Nt!==void 0?Nt:"",(Tt=Ve.media)!==null&&Tt!==void 0?Tt:"",We,Ve.filename),H.push(pt),ut.t0=U,ut.next=15,pt;case 15:ut.t1=ut.sent,ut.t0.push.call(ut.t0,ut.t1),ut.next=23;break;case 19:return ut.prev=19,ut.t2=ut.catch(8),S(ut.t2),ut.abrupt("return");case 23:ut.next=6;break;case 25:ut.next=30;break;case 27:ut.prev=27,ut.t3=ut.catch(4),G.e(ut.t3);case 30:return ut.prev=30,G.f(),ut.finish(30);case 33:return hr=y.services.commandExecutor.mutateResource("post",y.conversation._links.messages,{body:h.text,subject:(B=h.emailOptions)===null||B===void 0?void 0:B.subject,media_sids:U.map(function(di){return di.sid}),attributes:typeof h.attributes<"u"?JSON.stringify(h.attributes):void 0,content_sid:h.contentSid,content_variables:typeof h.contentVariables<"u"?JSON.stringify(h.contentVariables.reduce(function(di,On){return dr(dr({},di),{},Se.default({},On.name,On.value))},{})):void 0}),ut.prev=34,ut.t4=w,ut.next=38,hr;case 38:ut.t5=ut.sent,(0,ut.t4)(ut.t5),ut.next=45;break;case 42:ut.prev=42,ut.t6=ut.catch(34),S(ut.t6);case 45:case"end":return ut.stop()}},_,null,[[4,27,30,33],[8,19],[34,42]])}));return function(_,w,S){return g.apply(this,arguments)}}())}},{key:"send",value:function(){var d=L.default(P.default.mark(function y(g){var _,w,S=arguments;return P.default.wrap(function(B){for(;;)switch(B.prev=B.next){case 0:return _=S.length>1&&S[1]!==void 0?S[1]:{},w=S.length>2?S[2]:void 0,Er.debug("Sending text message",g,_,w),B.abrupt("return",this.services.commandExecutor.mutateResource("post",this.conversation._links.messages,{body:g??"",attributes:typeof _<"u"?JSON.stringify(_):void 0,subject:w==null?void 0:w.subject}));case 4:case"end":return B.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"sendMedia",value:function(){var d=L.default(P.default.mark(function y(g){var _,w,S,C,B,U=arguments;return P.default.wrap(function(G){for(;;)switch(G.prev=G.next){case 0:if(S=U.length>1&&U[1]!==void 0?U[1]:{},C=U.length>2?U[2]:void 0,Er.debug("Sending media message",g,S,C),Er.debug("Sending media message as ".concat(g instanceof FormData?"FormData":"SendMediaOptions"),g,S),!(g instanceof FormData)){G.next=10;break}return G.next=7,this.services.mcsClient.postFormData(g);case 7:G.t0=G.sent,G.next=13;break;case 10:return G.next=12,this.services.mcsClient.post((_=g.contentType)!==null&&_!==void 0?_:"",(w=g.media)!==null&&w!==void 0?w:"","media",g.filename);case 12:G.t0=G.sent;case 13:return B=G.t0,G.next=16,this.services.commandExecutor.mutateResource("post",this.conversation._links.messages,{media_sids:[B.sid],attributes:typeof S<"u"?JSON.stringify(S):void 0});case 16:return G.abrupt("return",G.sent);case 17:case"end":return G.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"getMessages",value:function(){var d=L.default(P.default.mark(function y(g,_){var w,S=arguments;return P.default.wrap(function(B){for(;;)switch(B.prev=B.next){case 0:return w=S.length>2&&S[2]!==void 0?S[2]:"backwards",B.abrupt("return",this._getMessages(g,_,w));case 2:case"end":return B.stop()}},y,this)}));function h(y,g){return d.apply(this,arguments)}return h}()},{key:"_wrapPaginator",value:function(h,y,g){var _=this,w=h==="desc",S=function(){return y.nextPage().then(function(U){return _._wrapPaginator(h,U,g)})},C=function(){return y.prevPage().then(function(U){return _._wrapPaginator(h,U,g)})};return g(y.items).then(function(B){return{items:B.sort(function(U,H){return U.index-H.index}),hasPrevPage:w?y.hasNextPage:y.hasPrevPage,hasNextPage:w?y.hasPrevPage:y.hasNextPage,prevPage:w?S:C,nextPage:w?C:S}})}},{key:"_upsertMessage",value:function(h,y){var g=this,_=this.messagesByIndex.get(h);if(_)return _;var w={self:"".concat(this.conversation._links.messages,"/").concat(y.sid),conversation:this.conversation._links.self,messages_receipts:"".concat(this.conversation._links.messages,"/").concat(y.sid,"/Receipts")},S=new Ot(h,y,this.conversation,w,this.configuration,this.services);return this.messagesByIndex.set(S.index,S),S.on("updated",function(C){return g.emit("messageUpdated",C)}),S}},{key:"_getMessages",value:function(){var d=L.default(P.default.mark(function y(){var g=this,_,w,S,C,B,U,H=arguments;return P.default.wrap(function(Le){for(;;)switch(Le.prev=Le.next){case 0:return _=H.length>0&&H[0]!==void 0?H[0]:30,w=H.length>1&&H[1]!==void 0?H[1]:"end",S=H.length>2&&H[2]!==void 0?H[2]:"forward",C=S==="backwards"?"desc":"asc",Le.next=6,this.messagesListPromise;case 6:return B=Le.sent,Le.next=9,B==null?void 0:B.getItems({from:w!=="end"?w:void 0,pageSize:_,order:C,limit:_});case 9:return U=Le.sent,Le.next=12,this._wrapPaginator(C,U,function(Xe){return Promise.all(Xe.map(function(We){return g._upsertMessage(We.index,We.data)}))});case 12:return Le.abrupt("return",Le.sent);case 13:case"end":return Le.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()}]),f}(I.ReplayEventEmitter),ci=function(){function O(A){he.default(this,O),Se.default(this,"attributes",{}),Se.default(this,"mediaContent",[]),Se.default(this,"emailOptions",{}),this.messagesEntity=A}return ce.default(O,[{key:"send",value:function(){var f=this;return new V.CancellablePromise(function(){var d=L.default(P.default.mark(function h(y,g,_){var w,S;return P.default.wrap(function(B){for(;;)switch(B.prev=B.next){case 0:return w=f.messagesEntity.sendV2(f),_(function(){return w.cancel()}),B.prev=2,B.next=5,w;case 5:S=B.sent,y(bt(S.index)),B.next=12;break;case 9:B.prev=9,B.t0=B.catch(2),g(B.t0);case 12:case"end":return B.stop()}},h,null,[[2,9]])}));return function(h,y,g){return d.apply(this,arguments)}}())}}]),O}(),or=function(){function O(A,f){he.default(this,O),this.limits=A,this.message=new ci(f),this.emailBodies=new Map,this.emailHistories=new Map}return ce.default(O,[{key:"setBody",value:function(f){return this.message.text=f,this}},{key:"setSubject",value:function(f){return this.message.emailOptions.subject=f,this}},{key:"setAttributes",value:function(f){return this.message.attributes=f,this}},{key:"setEmailBody",value:function(f,d){return this.emailBodies.set(f,d),this}},{key:"setEmailHistory",value:function(f,d){return this.emailHistories.set(f,d),this}},{key:"setContentTemplate",value:function(f){var d=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];return this.message.contentSid=f,this.message.contentVariables=d,this}},{key:"addMedia",value:function(f){if(typeof FormData>"u"&&f instanceof FormData)throw new Error("Could not add FormData content whilst not in a browser");if(!(f instanceof FormData)){var d=f;if(!d.contentType||!d.media)throw new Error("Media content in SendMediaOptions must contain non-empty contentType and media")}return this.message.mediaContent.push(["media",f]),this}},{key:"build",value:function(){var f=this;if(this.emailBodies.forEach(function(d,h){if(!f.limits.emailBodiesAllowedContentTypes.includes(h))throw new Error("Unsupported email body content type ".concat(h))}),this.emailHistories.forEach(function(d,h){if(!f.limits.emailHistoriesAllowedContentTypes.includes(h))throw new Error("Unsupported email history content type ".concat(h))}),this.emailBodies.size>this.limits.emailBodiesAllowedContentTypes.length)throw new Error("Too many email bodies attached to the message (".concat(this.emailBodies.size," > ").concat(this.limits.emailBodiesAllowedContentTypes.length,")"));if(this.emailHistories.size>this.limits.emailHistoriesAllowedContentTypes.length)throw new Error("Too many email histories attached to the message (".concat(this.emailHistories.size," > ").concat(this.limits.emailHistoriesAllowedContentTypes.length,")"));if(this.message.mediaContent.length>this.limits.mediaAttachmentsCountLimit)throw new Error("Too many media attachments in the message (".concat(this.message.mediaContent.length," > ").concat(this.limits.mediaAttachmentsCountLimit,")"));return this.emailBodies.forEach(function(d){f.message.mediaContent.push(["body",d])}),this.emailHistories.forEach(function(d){f.message.mediaContent.push(["history",d])}),this.message}},{key:"buildAndSend",value:function(){return this.build().send()}}]),O}();Ce([b.validateTypes("string"),de("design:type",Function),de("design:paramtypes",[String]),de("design:returntype",or)],or.prototype,"setBody",null),Ce([b.validateTypes("string"),de("design:type",Function),de("design:paramtypes",[String]),de("design:returntype",or)],or.prototype,"setSubject",null),Ce([b.validateTypes(cr),de("design:type",Function),de("design:paramtypes",[Object]),de("design:returntype",or)],or.prototype,"setAttributes",null),Ce([b.validateTypes("string",[FormData,Dr]),de("design:type",Function),de("design:paramtypes",[String,Object]),de("design:returntype",or)],or.prototype,"setEmailBody",null),Ce([b.validateTypes("string",[FormData,Dr]),de("design:type",Function),de("design:paramtypes",[String,Object]),de("design:returntype",or)],or.prototype,"setEmailHistory",null),Ce([b.validateTypes("string",[b.array("content variables",at),"undefined"]),de("design:type",Function),de("design:paramtypes",[String,Array]),de("design:returntype",or)],or.prototype,"setContentTemplate",null),Ce([b.validateTypes([FormData,Dr]),de("design:type",Function),de("design:paramtypes",[Object]),de("design:returntype",or)],or.prototype,"addMedia",null);function Ba(O,A){var f=typeof Symbol<"u"&&O[Symbol.iterator]||O["@@iterator"];if(!f){if(Array.isArray(O)||(f=gn(O))||A){f&&(O=f);var d=0,h=function(){};return{s:h,n:function(){return d>=O.length?{done:!0}:{done:!1,value:O[d++]}},e:function(S){throw S},f:h}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
469
469
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var y=!0,g=!1,_;return{s:function(){f=f.call(O)},n:function(){var S=f.next();return y=S.done,S},e:function(S){g=!0,_=S},f:function(){try{!y&&f.return!=null&&f.return()}finally{if(g)throw _}}}}function gn(O,A){if(O){if(typeof O=="string")return Oi(O,A);var f=Object.prototype.toString.call(O).slice(8,-1);if(f==="Object"&&O.constructor&&(f=O.constructor.name),f==="Map"||f==="Set")return Array.from(O);if(f==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(f))return Oi(O,A)}}function Oi(O,A){(A==null||A>O.length)&&(A=O.length);for(var f=0,d=new Array(A);f<A;f++)d[f]=O[f];return d}function Ai(O){var A=qa();return function(){var d=Ke.default(O),h;if(A){var y=Ke.default(this).constructor;h=Reflect.construct(d,arguments,y)}else h=d.apply(this,arguments);return rt.default(this,h)}}function qa(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var yn={lastMessage:"lastMessage",attributes:"attributes",createdBy:"createdBy",dateCreated:"dateCreated",dateUpdated:"dateUpdated",friendlyName:"friendlyName",lastConsumedMessageIndex:"lastConsumedMessageIndex",notificationLevel:"notificationLevel",sid:"sid",status:"status",uniqueName:"uniqueName",state:"state",bindings:"bindings"},At=function(O){Te.default(f,O);var A=Ai(f);function f(d,h,y,g,_){var w,S,C;he.default(this,f),C=A.call(this),C.sid=h,C._links=y,C._configuration=g,C._services=_,C._entityName=d.channel,C._internalState={uniqueName:d.uniqueName||null,status:"notParticipating",attributes:(w=d.attributes)!==null&&w!==void 0?w:{},createdBy:d.createdBy,dateCreated:ct(d.dateCreated),dateUpdated:ct(d.dateUpdated),friendlyName:d.friendlyName||null,lastReadMessageIndex:Number.isInteger(d.lastConsumedMessageIndex)?d.lastConsumedMessageIndex:null,bindings:(S=d.bindings)!==null&&S!==void 0?S:{}},d.notificationLevel&&(C._internalState.notificationLevel=d.notificationLevel);var B={participants:C._links.participants};return C._participants=new Map,C._participantsEntity=new Re(pe.default(C),C._participants,B,C._services),C._participantsEntity.on(f.participantJoined,function(U){return C.emit(f.participantJoined,U)}),C._participantsEntity.on(f.participantLeft,function(U){return C.emit(f.participantLeft,U)}),C._participantsEntity.on(f.participantUpdated,function(U){return C.emit(f.participantUpdated,U)}),C._messagesEntity=new Ua(pe.default(C),g,_),C._messagesEntity.on(f.messageAdded,function(U){return C._onMessageAdded(U)}),C._messagesEntity.on(f.messageUpdated,function(U){return C.emit(f.messageUpdated,U)}),C._messagesEntity.on(f.messageRemoved,function(U){return C.emit(f.messageRemoved,U)}),C}return ce.default(f,[{key:"uniqueName",get:function(){return this._internalState.uniqueName}},{key:"status",get:function(){return this._internalState.status}},{key:"friendlyName",get:function(){return this._internalState.friendlyName}},{key:"dateUpdated",get:function(){return this._internalState.dateUpdated}},{key:"dateCreated",get:function(){return this._internalState.dateCreated}},{key:"createdBy",get:function(){var h;return(h=this._internalState.createdBy)!==null&&h!==void 0?h:""}},{key:"attributes",get:function(){return this._internalState.attributes}},{key:"lastReadMessageIndex",get:function(){return this._internalState.lastReadMessageIndex}},{key:"lastMessage",get:function(){var h;return(h=this._internalState.lastMessage)!==null&&h!==void 0?h:void 0}},{key:"notificationLevel",get:function(){var h;return(h=this._internalState.notificationLevel)!==null&&h!==void 0?h:"default"}},{key:"bindings",get:function(){return this._internalState.bindings}},{key:"limits",get:function(){return this._configuration.limits}},{key:"state",get:function(){return this._internalState.state}},{key:"_statusSource",get:function(){return this._dataSource}},{key:"add",value:function(){var d=L.default(P.default.mark(function y(g,_){return P.default.wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return S.abrupt("return",this._participantsEntity.add(g,_??{}));case 1:case"end":return S.stop()}},y,this)}));function h(y,g){return d.apply(this,arguments)}return h}()},{key:"addNonChatParticipant",value:function(){var d=L.default(P.default.mark(function y(g,_){var w,S,C=arguments;return P.default.wrap(function(U){for(;;)switch(U.prev=U.next){case 0:return w=C.length>2&&C[2]!==void 0?C[2]:{},S=C.length>3&&C[3]!==void 0?C[3]:{},U.abrupt("return",this._participantsEntity.addNonChatParticipant(g,_,w??{},S??{}));case 3:case"end":return U.stop()}},y,this)}));function h(y,g){return d.apply(this,arguments)}return h}()},{key:"advanceLastReadMessageIndex",value:function(){var d=L.default(P.default.mark(function y(g){var _;return P.default.wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return S.next=2,this._subscribeStreams();case 2:if(!(g<((_=this.lastReadMessageIndex)!==null&&_!==void 0?_:0))){S.next=6;break}return S.next=5,this._setLastReadMessageIndex(this.lastReadMessageIndex);case 5:return S.abrupt("return",S.sent);case 6:return S.next=8,this._setLastReadMessageIndex(g);case 8:return S.abrupt("return",S.sent);case 9:case"end":return S.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"delete",value:function(){var d=L.default(P.default.mark(function y(){return P.default.wrap(function(_){for(;;)switch(_.prev=_.next){case 0:return _.next=2,this._services.commandExecutor.mutateResource("delete",this._links.self);case 2:return _.abrupt("return",this);case 3:case"end":return _.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"getAttributes",value:function(){var d=L.default(P.default.mark(function y(){return P.default.wrap(function(_){for(;;)switch(_.prev=_.next){case 0:return _.next=2,this._subscribe();case 2:return _.abrupt("return",this.attributes);case 3:case"end":return _.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"getMessages",value:function(){var d=L.default(P.default.mark(function y(g,_,w){return P.default.wrap(function(C){for(;;)switch(C.prev=C.next){case 0:return C.next=2,this._subscribeStreams();case 2:return C.abrupt("return",this._messagesEntity.getMessages(g,_,w));case 3:case"end":return C.stop()}},y,this)}));function h(y,g,_){return d.apply(this,arguments)}return h}()},{key:"getParticipants",value:function(){var d=L.default(P.default.mark(function y(){return P.default.wrap(function(_){for(;;)switch(_.prev=_.next){case 0:return _.next=2,this._subscribeStreams();case 2:return _.abrupt("return",this._participantsEntity.getParticipants());case 3:case"end":return _.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"getParticipantsCount",value:function(){var d=L.default(P.default.mark(function y(){var g,_,w;return P.default.wrap(function(C){for(;;)switch(C.prev=C.next){case 0:return _=new Pt(this._configuration.links.conversations).path(this.sid).build(),C.next=3,this._services.network.get(_);case 3:return w=C.sent,C.abrupt("return",(g=w.body.participants_count)!==null&&g!==void 0?g:0);case 5:case"end":return C.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"getParticipantBySid",value:function(){var d=L.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.abrupt("return",this._participantsEntity.getParticipantBySid(g));case 1:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"getParticipantByIdentity",value:function(){var d=L.default(P.default.mark(function y(){var g,_=arguments;return P.default.wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return g=_.length>0&&_[0]!==void 0?_[0]:"",S.abrupt("return",this._participantsEntity.getParticipantByIdentity(g??""));case 2:case"end":return S.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"getMessagesCount",value:function(){var d=L.default(P.default.mark(function y(){var g,_,w;return P.default.wrap(function(C){for(;;)switch(C.prev=C.next){case 0:return _=new Pt(this._configuration.links.conversations).path(this.sid).build(),C.next=3,this._services.network.get(_);case 3:return w=C.sent,C.abrupt("return",(g=w.body.messages_count)!==null&&g!==void 0?g:0);case 5:case"end":return C.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"getUnreadMessagesCount",value:function(){var d=L.default(P.default.mark(function y(){var g,_,w;return P.default.wrap(function(C){for(;;)switch(C.prev=C.next){case 0:return g=new Pt(this._configuration.links.myConversations).path(this.sid).build(),C.next=3,this._services.network.get(g);case 3:if(_=C.sent,_.body.conversation_sid===this.sid){C.next=6;break}throw new Error("Conversation was not found in the user conversations list");case 6:if(w=_.body.unread_messages_count,typeof w!="number"){C.next=9;break}return C.abrupt("return",w);case 9:return C.abrupt("return",null);case 10:case"end":return C.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"join",value:function(){var d=L.default(P.default.mark(function y(){return P.default.wrap(function(_){for(;;)switch(_.prev=_.next){case 0:return _.next=2,this._services.commandExecutor.mutateResource("post",this._links.participants,{identity:this._configuration.userIdentity});case 2:return _.abrupt("return",this);case 3:case"end":return _.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"leave",value:function(){var d=L.default(P.default.mark(function y(){return P.default.wrap(function(_){for(;;)switch(_.prev=_.next){case 0:if(this._internalState.status!=="joined"){_.next=3;break}return _.next=3,this._services.commandExecutor.mutateResource("delete","".concat(this._links.participants,"/").concat(encodeURIComponent(this._configuration.userIdentity)));case 3:return _.abrupt("return",this);case 4:case"end":return _.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"removeParticipant",value:function(){var d=L.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this._participantsEntity.remove(typeof g=="string"?g:g.sid);case 2:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"sendMessage",value:function(){var d=L.default(P.default.mark(function y(g,_,w){var S,C,B,U;return P.default.wrap(function(G){for(;;)switch(G.prev=G.next){case 0:if(!(typeof g=="string"||g===null)){G.next=5;break}return G.next=3,this._messagesEntity.send(g,_,w);case 3:return B=G.sent,G.abrupt("return",(C=bt(B.index))!==null&&C!==void 0?C:0);case 5:return G.next=7,this._messagesEntity.sendMedia(g,_,w);case 7:return U=G.sent,G.abrupt("return",(S=bt(U.index))!==null&&S!==void 0?S:0);case 9:case"end":return G.stop()}},y,this)}));function h(y,g,_){return d.apply(this,arguments)}return h}()},{key:"prepareMessage",value:function(){return new or(this.limits,this._messagesEntity)}},{key:"setAllMessagesRead",value:function(){var d=L.default(P.default.mark(function y(){var g;return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this._subscribeStreams();case 2:return w.next=4,this.getMessages(1);case 4:if(g=w.sent,!(g.items.length>0)){w.next=7;break}return w.abrupt("return",this.advanceLastReadMessageIndex(g.items[0].index));case 7:return w.abrupt("return",0);case 8:case"end":return w.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"setAllMessagesUnread",value:function(){var d=L.default(P.default.mark(function y(){return P.default.wrap(function(_){for(;;)switch(_.prev=_.next){case 0:return _.next=2,this._subscribeStreams();case 2:return _.next=4,this._setLastReadMessageIndex(null);case 4:return _.abrupt("return",_.sent);case 5:case"end":return _.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"setUserNotificationLevel",value:function(){var d=L.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this._services.commandExecutor.mutateResource("post","".concat(this._configuration.links.myConversations,"/").concat(this.sid),{notification_level:g});case 2:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"typing",value:function(){return this._services.typingIndicator.send(this.sid)}},{key:"updateAttributes",value:function(){var d=L.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this._services.commandExecutor.mutateResource("post",this._links.self,{attributes:g!==void 0?JSON.stringify(g):void 0});case 2:return w.abrupt("return",this);case 3:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"updateFriendlyName",value:function(){var d=L.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:if(this._internalState.friendlyName===g){w.next=3;break}return w.next=3,this._services.commandExecutor.mutateResource("post",this._links.self,{friendly_name:g});case 3:return w.abrupt("return",this);case 4:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"updateLastReadMessageIndex",value:function(){var d=L.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this._subscribeStreams();case 2:return w.abrupt("return",this._setLastReadMessageIndex(g));case 3:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"updateUniqueName",value:function(){var d=L.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:if(this._internalState.uniqueName===g){w.next=4;break}return g||(g=""),w.next=4,this._services.commandExecutor.mutateResource("post",this._links.self,{unique_name:g});case 4:return w.abrupt("return",this);case 5:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"getMessageRecipients",value:function(){var d=L.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this._services.messageRecipientsClient.getRecipientsFromConversation(this.sid,g);case 2:return w.abrupt("return",w.sent);case 3:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"_subscribe",value:function(){var d=L.default(P.default.mark(function y(){var g=this;return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:if(!this._entityPromise){w.next=2;break}return w.abrupt("return",this._entityPromise);case 2:return this._entityPromise=this._services.syncClient.document({id:this._entityName,mode:"open_existing"}),w.prev=3,w.next=6,this._entityPromise;case 6:return this._entity=w.sent,this._entity.on(J.SyncDocument.updated,function(S){return g._update(S.data)}),this._entity.on(J.SyncDocument.removed,function(){return g.emit(f.removed,g)}),this._update(this._entity.data),w.abrupt("return",this._entity);case 13:throw w.prev=13,w.t0=w.catch(3),this._entity=null,this._entityPromise=null,this._services.syncClient.connectionState!="disconnected"&&f._logger.error("Failed to get conversation object",w.t0),f._logger.debug("ERROR: Failed to get conversation object",w.t0),w.t0;case 20:case"end":return w.stop()}},y,this,[[3,13]])}));function h(){return d.apply(this,arguments)}return h}()},{key:"_fetchStreams",value:function(){var d=L.default(P.default.mark(function y(){var g,_,w;return P.default.wrap(function(C){for(;;)switch(C.prev=C.next){case 0:return C.next=2,this._subscribe();case 2:return f._logger.trace("_streamsAvailable, this.entity.data=",(g=this._entity)===null||g===void 0?void 0:g.data),w=(_=this._entity)===null||_===void 0?void 0:_.data,C.next=6,this._services.syncClient.list({id:w.messages,mode:"open_existing"});case 6:return this._messagesList=C.sent,C.next=9,this._services.syncClient.map({id:w.roster,mode:"open_existing"});case 9:this._participantsMap=C.sent;case 10:case"end":return C.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"_subscribeStreams",value:function(){var d=L.default(P.default.mark(function y(){var g,_,w,S,C,B,U;return P.default.wrap(function(G){for(;;)switch(G.prev=G.next){case 0:return G.prev=0,G.next=3,this._subscribe();case 3:return f._logger.trace("_subscribeStreams, this.entity.data=",(g=this._entity)===null||g===void 0?void 0:g.data),C=(_=this._entity)===null||_===void 0?void 0:_.data,B=C.messages,U=C.roster,G.next=9,Promise.all([this._messagesEntity.subscribe((w=this._messagesList)!==null&&w!==void 0?w:B),this._participantsEntity.subscribe((S=this._participantsMap)!==null&&S!==void 0?S:U)]);case 9:G.next=16;break;case 11:throw G.prev=11,G.t0=G.catch(0),this._services.syncClient.connectionState!=="disconnected"&&f._logger.error("Failed to subscribe on conversation objects",this.sid,G.t0),f._logger.debug("ERROR: Failed to subscribe on conversation objects",this.sid,G.t0),G.t0;case 16:case"end":return G.stop()}},y,this,[[0,11]])}));function h(){return d.apply(this,arguments)}return h}()},{key:"_unsubscribe",value:function(){var d=L.default(P.default.mark(function y(){return P.default.wrap(function(_){for(;;)switch(_.prev=_.next){case 0:return this._entity&&(this._entity.close(),this._entity=null,this._entityPromise=null),_.abrupt("return",Promise.all([this._participantsEntity.unsubscribe(),this._messagesEntity.unsubscribe()]));case 2:case"end":return _.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"_setStatus",value:function(h,y){var g=this;if(this._dataSource=y,this._internalState.status!==h){if(this._internalState.status=h,h==="joined"){this._subscribeStreams().catch(function(_){if(f._logger.debug("ERROR while setting conversation status "+h,_),g._services.syncClient.connectionState!=="disconnected")throw _});return}this._entityPromise&&this._unsubscribe().catch(function(_){if(f._logger.debug("ERROR while setting conversation status "+h,_),g._services.syncClient.connectionState!=="disconnected")throw _})}}},{key:"_update",value:function(h){var y,g,_,w,S;f._logger.trace("_update",h),f.preprocessUpdate(h,this.sid);for(var C=new Set,B=0,U=Object.keys(h);B<U.length;B++){var H=U[B],G=yn[H];if(G)switch(G){case yn.status:if(!h.status||h.status==="unknown"||this._internalState.status===h.status)break;this._internalState.status=h.status,C.add(G);break;case yn.attributes:if(_e.default(this._internalState.attributes,h.attributes))break;this._internalState.attributes=h.attributes,C.add(G);break;case yn.lastConsumedMessageIndex:if(h.lastConsumedMessageIndex===void 0||h.lastConsumedMessageIndex===this._internalState.lastReadMessageIndex)break;this._internalState.lastReadMessageIndex=h.lastConsumedMessageIndex,C.add("lastReadMessageIndex");break;case yn.lastMessage:if(this._internalState.lastMessage&&!h.lastMessage){delete this._internalState.lastMessage,C.add(G);break}this._internalState.lastMessage=this._internalState.lastMessage||{},((y=h.lastMessage)===null||y===void 0?void 0:y.index)!==void 0&&h.lastMessage.index!==this._internalState.lastMessage.index&&(this._internalState.lastMessage.index=h.lastMessage.index,C.add(G)),((g=h.lastMessage)===null||g===void 0?void 0:g.timestamp)!==void 0&&((_=this._internalState.lastMessage)===null||_===void 0||(w=_.dateCreated)===null||w===void 0?void 0:w.getTime())!==h.lastMessage.timestamp.getTime()&&(this._internalState.lastMessage.dateCreated=h.lastMessage.timestamp,C.add(G)),_e.default(this._internalState.lastMessage,{})&&delete this._internalState.lastMessage;break;case yn.state:var Le=h.state||void 0;if(Le!==void 0&&(Le.dateUpdated=new Date(Le.dateUpdated)),_e.default(this._internalState.state,Le))break;this._internalState.state=Le,C.add(G);break;case yn.bindings:if(_e.default(this._internalState.bindings,h.bindings))break;this._internalState.bindings=h.bindings,C.add(G);break;default:var Xe=h[H]instanceof Date,We=Xe&&((S=this._internalState[G])===null||S===void 0?void 0:S.getTime())===h[H].getTime(),Ve=!Xe&&this[G]===h[H];if(We||Ve)break;this._internalState[G]=h[H],C.add(G)}}C.size>0&&this.emit(f.updated,{conversation:this,updateReasons:Ne.default(C)})}},{key:"_onMessageAdded",value:function(h){var y=Ba(this._participants.values()),g;try{for(y.s();!(g=y.n()).done;){var _=g.value;if(_.identity===h.author){_._endTyping();break}}}catch(w){y.e(w)}finally{y.f()}this.emit(f.messageAdded,h)}},{key:"_setLastReadMessageIndex",value:function(){var d=L.default(P.default.mark(function y(g){var _;return P.default.wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return S.next=2,this._services.commandExecutor.mutateResource("post","".concat(this._configuration.links.myConversations,"/").concat(this.sid),{last_read_message_index:g});case 2:return _=S.sent,S.abrupt("return",_.unread_messages_count);case 4:case"end":return S.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()}],[{key:"preprocessUpdate",value:function(h,y){try{typeof h.attributes=="string"?h.attributes=JSON.parse(h.attributes):h.attributes&&JSON.stringify(h.attributes)}catch{f._logger.warn("Retrieved malformed attributes from the server for conversation: "+y),h.attributes={}}try{h.dateCreated&&(h.dateCreated=new Date(h.dateCreated))}catch{f._logger.warn("Retrieved malformed dateCreated from the server for conversation: "+y),delete h.dateCreated}try{h.dateUpdated&&(h.dateUpdated=new Date(h.dateUpdated))}catch{f._logger.warn("Retrieved malformed dateUpdated from the server for conversation: "+y),delete h.dateUpdated}try{h.lastMessage&&h.lastMessage.timestamp&&(h.lastMessage.timestamp=new Date(h.lastMessage.timestamp))}catch{f._logger.warn("Retrieved malformed lastMessage.timestamp from the server for conversation: "+y),delete h.lastMessage.timestamp}}}]),f}(I.ReplayEventEmitter);Se.default(At,"participantJoined","participantJoined"),Se.default(At,"participantLeft","participantLeft"),Se.default(At,"participantUpdated","participantUpdated"),Se.default(At,"messageAdded","messageAdded"),Se.default(At,"messageRemoved","messageRemoved"),Se.default(At,"messageUpdated","messageUpdated"),Se.default(At,"typingEnded","typingEnded"),Se.default(At,"typingStarted","typingStarted"),Se.default(At,"updated","updated"),Se.default(At,"removed","removed"),Se.default(At,"_logger",Dt.scope("Conversation")),Ce([b.validateTypesAsync(b.nonEmptyString,Cr),de("design:type",Function),de("design:paramtypes",[String,Object]),de("design:returntype",Promise)],At.prototype,"add",null),Ce([b.validateTypesAsync(b.nonEmptyString,b.nonEmptyString,Cr,Cr),de("design:type",Function),de("design:paramtypes",[String,String,Object,Object]),de("design:returntype",Promise)],At.prototype,"addNonChatParticipant",null),Ce([b.validateTypesAsync(b.nonNegativeInteger),de("design:type",Function),de("design:paramtypes",[Number]),de("design:returntype",Promise)],At.prototype,"advanceLastReadMessageIndex",null),Ce([b.validateTypesAsync(["undefined",b.nonNegativeInteger],["undefined",b.nonNegativeInteger],["undefined",b.literal("backwards","forward")]),de("design:type",Function),de("design:paramtypes",[Number,Number,String]),de("design:returntype",Promise)],At.prototype,"getMessages",null),Ce([b.validateTypesAsync(b.nonEmptyString),de("design:type",Function),de("design:paramtypes",[String]),de("design:returntype",Promise)],At.prototype,"getParticipantBySid",null),Ce([b.validateTypesAsync(b.nonEmptyString),de("design:type",Function),de("design:paramtypes",[String]),de("design:returntype",Promise)],At.prototype,"getParticipantByIdentity",null),Ce([b.validateTypesAsync([b.nonEmptyString,K]),de("design:type",Function),de("design:paramtypes",[Object]),de("design:returntype",Promise)],At.prototype,"removeParticipant",null),Ce([b.validateTypesAsync(["string",FormData,b.literal(null),b.objectSchema("media options",{contentType:b.nonEmptyString,media:b.custom(function(O){var A=typeof O=="string"&&O.length>0||O instanceof Uint8Array||O instanceof ArrayBuffer;return typeof Blob=="function"&&(A=A||O instanceof Blob),[A,"a non-empty string, an instance of Buffer or an instance of Blob"]})})],Cr,["undefined",b.literal(null),b.objectSchema("email attributes",{subject:[b.nonEmptyString,"undefined"]})]),de("design:type",Function),de("design:paramtypes",[Object,Object,Object]),de("design:returntype",Promise)],At.prototype,"sendMessage",null),Ce([b.validateTypesAsync(b.literal("default","muted")),de("design:type",Function),de("design:paramtypes",[String]),de("design:returntype",Promise)],At.prototype,"setUserNotificationLevel",null),Ce([b.validateTypesAsync(cr),de("design:type",Function),de("design:paramtypes",[Object]),de("design:returntype",Promise)],At.prototype,"updateAttributes",null),Ce([b.validateTypesAsync("string"),de("design:type",Function),de("design:paramtypes",[String]),de("design:returntype",Promise)],At.prototype,"updateFriendlyName",null),Ce([b.validateTypesAsync([b.literal(null),b.nonNegativeInteger]),de("design:type",Function),de("design:paramtypes",[Number]),de("design:returntype",Promise)],At.prototype,"updateLastReadMessageIndex",null),Ce([b.validateTypesAsync(["string",b.literal(null)]),de("design:type",Function),de("design:paramtypes",[String]),de("design:returntype",Promise)],At.prototype,"updateUniqueName",null);var ua=function(){function O(){var A=this;he.default(this,O),this._promise=new Promise(function(f,d){A._resolve=f,A._reject=d})}return ce.default(O,[{key:"promise",get:function(){return this._promise}},{key:"update",value:function(f){this._resolve(f)}},{key:"set",value:function(f){this.current=f,this._resolve(f)}},{key:"fail",value:function(f){this._reject(f)}}]),O}();function ca(O,A){var f=typeof Symbol<"u"&&O[Symbol.iterator]||O["@@iterator"];if(!f){if(Array.isArray(O)||(f=Pi(O))||A){f&&(O=f);var d=0,h=function(){};return{s:h,n:function(){return d>=O.length?{done:!0}:{done:!1,value:O[d++]}},e:function(S){throw S},f:h}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
470
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var y=!0,g=!1,_;return{s:function(){f=f.call(O)},n:function(){var S=f.next();return y=S.done,S},e:function(S){g=!0,_=S},f:function(){try{!y&&f.return!=null&&f.return()}finally{if(g)throw _}}}}function Pi(O,A){if(O){if(typeof O=="string")return Mi(O,A);var f=Object.prototype.toString.call(O).slice(8,-1);if(f==="Object"&&O.constructor&&(f=O.constructor.name),f==="Map"||f==="Set")return Array.from(O);if(f==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(f))return Mi(O,A)}}function Mi(O,A){(A==null||A>O.length)&&(A=O.length);for(var f=0,d=new Array(A);f<A;f++)d[f]=O[f];return d}function li(O,A){var f=Object.keys(O);if(Object.getOwnPropertySymbols){var d=Object.getOwnPropertySymbols(O);A&&(d=d.filter(function(h){return Object.getOwnPropertyDescriptor(O,h).enumerable})),f.push.apply(f,d)}return f}function Hn(O){for(var A=1;A<arguments.length;A++){var f=arguments[A]!=null?arguments[A]:{};A%2?li(Object(f),!0).forEach(function(d){Se.default(O,d,f[d])}):Object.getOwnPropertyDescriptors?Object.defineProperties(O,Object.getOwnPropertyDescriptors(f)):li(Object(f)).forEach(function(d){Object.defineProperty(O,d,Object.getOwnPropertyDescriptor(f,d))})}return O}function kr(O){var A=la();return function(){var d=Ke.default(O),h;if(A){var y=Ke.default(this).constructor;h=Reflect.construct(d,arguments,y)}else h=d.apply(this,arguments);return rt.default(this,h)}}function la(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var Rr=Dt.scope("Conversations"),Hr=function(O){Te.default(f,O);var A=kr(f);function f(d,h){var y;return he.default(this,f),y=A.call(this),Se.default(pe.default(y),"conversations",new Map),Se.default(pe.default(y),"myConversationsRead",new ua),Se.default(pe.default(y),"tombstones",new Set),Se.default(pe.default(y),"myConversationsFetched",!1),y.configuration=d,y.services=h,y}return ce.default(f,[{key:"addConversation",value:function(){var d=L.default(P.default.mark(function y(g){var _,w,S,C,B,U,H,G,Le,Xe;return P.default.wrap(function(Ve){for(;;)switch(Ve.prev=Ve.next){case 0:return C=typeof(g==null?void 0:g.attributes)<"u"?g.attributes:{},Ve.next=3,this.services.commandExecutor.mutateResource("post",this.configuration.links.conversations,{friendly_name:g.friendlyName,unique_name:g.uniqueName,attributes:typeof C<"u"?JSON.stringify(C):void 0});case 3:if(B=Ve.sent,U=(_=B.sid)!==null&&_!==void 0?_:null,H=(w=(S=B.sync_objects)===null||S===void 0?void 0:S.conversation)!==null&&w!==void 0?w:null,G=Hn({self:B.url},B.links),Le=this.conversations.get(U),!Le){Ve.next=12;break}return Ve.next=11,Le._subscribe();case 11:return Ve.abrupt("return",Le);case 12:return Xe=new At({channel:H,entityName:"",uniqueName:"",attributes:null,createdBy:"",friendlyName:"",lastConsumedMessageIndex:0,dateCreated:null,dateUpdated:null},U,G,this.configuration,this.services),this.conversations.set(Xe.sid,Xe),this._registerForEvents(Xe),Ve.next=17,Xe._subscribe();case 17:return this.emit("conversationAdded",Xe),Ve.abrupt("return",Xe);case 19:case"end":return Ve.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"fetchConversations",value:function(){var d=L.default(P.default.mark(function y(){var g=this,_,w,S,C,B,U,H;return P.default.wrap(function(Le){for(;;)switch(Le.prev=Le.next){case 0:return Le.prev=0,Le.next=3,this._getMap();case 3:return _=Le.sent,_.on(J.SyncMap.itemAdded,function(Xe){Rr.debug("itemAdded: ".concat(Xe.item.key)),g._upsertConversation("sync",Xe.item.key,Xe.item.data)}),_.on(J.SyncMap.itemRemoved,function(Xe){Rr.debug("itemRemoved: ".concat(Xe.key));var We=Xe.key;g.myConversationsFetched||g.tombstones.add(We);var Ve=g.conversations.get(We);Ve&&(Ve.status==="joined"&&(Ve._setStatus("notParticipating","sync"),g.emit("conversationLeft",Ve)),g.conversations.delete(We),g.emit("conversationRemoved",Ve),Ve.emit("removed",Ve))}),_.on(J.SyncMap.itemUpdated,function(Xe){Rr.debug("itemUpdated: ".concat(Xe.item.key)),g._upsertConversation("sync",Xe.item.key,Xe.item.data)}),Le.next=9,this._fetchMyConversations();case 9:w=Le.sent,S=[],C=ca(w);try{for(C.s();!(B=C.n()).done;)U=B.value,S.push(this._upsertConversation("rest",U.channel_sid,U))}catch(Xe){C.e(Xe)}finally{C.f()}return this.myConversationsRead.set(!0),Le.next=16,Promise.all(S);case 16:return this.myConversationsFetched=!0,this.tombstones.clear(),Rr.debug("The conversations list has been successfully fetched"),Le.abrupt("return",this);case 22:throw Le.prev=22,Le.t0=Le.catch(0),H="Failed to fetch the conversations list",this.services.syncClient.connectionState!=="disconnected"&&Rr.error(H,Le.t0),Rr.debug("ERROR: ".concat(H),Le.t0),Le.t0;case 28:case"end":return Le.stop()}},y,this,[[0,22]])}));function h(){return d.apply(this,arguments)}return h}()},{key:"getConversations",value:function(){var d=L.default(P.default.mark(function y(){var g=this,_,w;return P.default.wrap(function(C){for(;;)switch(C.prev=C.next){case 0:return C.next=2,this._getMap();case 2:return _=C.sent,C.next=5,_.getItems();case 5:return w=C.sent,C.abrupt("return",this._wrapPaginator(w,function(B){return Promise.all(B.map(function(U){return g._upsertConversation("sync",U.key,U.data)}))}));case 7:case"end":return C.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"getConversation",value:function(){var d=L.default(P.default.mark(function y(g){var _=this,w,S,C;return P.default.wrap(function(U){for(;;)switch(U.prev=U.next){case 0:return U.next=2,this._getMap();case 2:return w=U.sent,U.next=5,w.getItems({key:g});case 5:return S=U.sent,C=S.items.map(function(H){return _._upsertConversation("sync",H.key,H.data)}),U.abrupt("return",C.length>0?C[0]:null);case 8:case"end":return U.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"getConversationByUniqueName",value:function(){var d=L.default(P.default.mark(function y(g){var _,w,S,C,B;return P.default.wrap(function(H){for(;;)switch(H.prev=H.next){case 0:return _=new Pt(this.configuration.links.myConversations).path(g).build(),H.next=3,this.services.network.get(_);case 3:return w=H.sent,S=w.body,C=S.conversation_sid,B={entityName:null,lastConsumedMessageIndex:S.last_read_message_index,status:(S==null?void 0:S.status)||"unknown",friendlyName:S.friendly_name,dateUpdated:S.date_updated,dateCreated:S.date_created,uniqueName:S.unique_name,createdBy:S.created_by,attributes:S.attributes,channel:S.sync_objects.conversation,notificationLevel:S==null?void 0:S.notification_level,sid:C},H.abrupt("return",C?this._upsertConversation("sync",C,B):null);case 8:case"end":return H.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"peekConversation",value:function(){var d=L.default(P.default.mark(function y(g){var _,w,S,C;return P.default.wrap(function(U){for(;;)switch(U.prev=U.next){case 0:return _=new Pt(this.configuration.links.conversations).path(g).build(),U.next=3,this.services.network.get(_);case 3:return w=U.sent,S=w.body,C={entityName:null,status:(S==null?void 0:S.status)||"unknown",friendlyName:S.friendly_name,dateUpdated:S.date_updated,dateCreated:S.date_created,uniqueName:S.unique_name,createdBy:S.created_by,attributes:S.attributes,channel:"".concat(g,".channel"),sid:g},U.abrupt("return",this._upsertConversation("sync",g,C));case 7:case"end":return U.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"_getMap",value:function(){var d=L.default(P.default.mark(function y(){return P.default.wrap(function(_){for(;;)switch(_.prev=_.next){case 0:return _.next=2,this.services.syncClient.map({id:this.configuration.myConversations,mode:"open_existing"});case 2:return _.abrupt("return",_.sent);case 3:case"end":return _.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"_wrapPaginator",value:function(){var d=L.default(P.default.mark(function y(g,_){var w=this,S;return P.default.wrap(function(B){for(;;)switch(B.prev=B.next){case 0:return B.next=2,_(g.items);case 2:return S=B.sent,B.abrupt("return",{items:S.filter(function(U){return U!==null}),hasNextPage:g.hasNextPage,hasPrevPage:g.hasPrevPage,nextPage:function(){return g.nextPage().then(function(H){return w._wrapPaginator(H,_)})},prevPage:function(){return g.prevPage().then(function(H){return w._wrapPaginator(H,_)})}});case 4:case"end":return B.stop()}},y)}));function h(y,g){return d.apply(this,arguments)}return h}()},{key:"_updateConversation",value:function(){var d=L.default(P.default.mark(function y(g,_,w){var S,C,B;return P.default.wrap(function(H){for(;;)switch(H.prev=H.next){case 0:if(S=_._statusSource!==void 0&&g!==_._statusSource,C=g!=="rest"||_._statusSource==="sync",!(S&&C&&g!=="sync")){H.next=5;break}return Rr.trace("upsertConversation: conversation is known from sync and came from REST, ignoring",{sid:_.sid,data:w.status,conversation:_.status}),H.abrupt("return");case 5:if(!(w.status==="joined"&&_.status!=="joined")){H.next=15;break}return _._setStatus("joined",g),B={},typeof w.notificationLevel<"u"&&(B.notificationLevel=w.notificationLevel),typeof w.lastConsumedMessageIndex<"u"&&(B.lastConsumedMessageIndex=w.lastConsumedMessageIndex),_e.default(B,{})||_._update(B),H.next=13,_._subscribe();case 13:return this.emit("conversationJoined",_),H.abrupt("return");case 15:if(!(w.status==="notParticipating"&&_.status==="joined")){H.next=22;break}return _._setStatus("notParticipating",g),_._update(w),H.next=20,_._subscribe();case 20:return this.emit("conversationLeft",_),H.abrupt("return");case 22:if(w.status!=="notParticipating"){H.next=26;break}return H.next=25,_._subscribe();case 25:return H.abrupt("return");case 26:_._update(w);case 27:case"end":return H.stop()}},y,this)}));function h(y,g,_){return d.apply(this,arguments)}return h}()},{key:"_upsertConversation",value:function(){var d=L.default(P.default.mark(function y(g,_,w){var S,C,B,U;return P.default.wrap(function(G){for(;;)switch(G.prev=G.next){case 0:if(Rr.trace("upsertConversation called for ".concat(_),w),S=this.conversations.get(_),!S){G.next=9;break}return Rr.trace("upsertConversation: the conversation ".concat(S.sid," is known;")+"its status is known from the source ".concat(S._statusSource," ")+"and the update came from the source ".concat(g),S),G.next=6,this._updateConversation(g,S,w);case 6:return G.next=8,S._subscribe();case 8:return G.abrupt("return",S);case 9:if(!(g==="rest"&&this.tombstones.has(_))){G.next=12;break}return Rr.trace("upsertChannel: the conversation is deleted but reappeared again from REST, ignoring",_),G.abrupt("return",null);case 12:return Rr.trace("upsertConversation: creating a local conversation object with sid "+_,w),C="".concat(this.configuration.links.conversations,"/").concat(_),B={self:C,messages:"".concat(C,"/Messages"),participants:"".concat(C,"/Participants")},U=new At(w,_,B,this.configuration,this.services),this.conversations.set(_,U),G.prev=17,G.next=20,U._subscribe();case 20:if(w.status!=="joined"){G.next=23;break}return G.next=23,U._fetchStreams();case 23:G.next=32;break;case 25:if(G.prev=25,G.t0=G.catch(17),G.t0.name==="SyncError"){G.next=29;break}throw G.t0;case 29:return Rr.trace("upsertChannel: the conversation is missing some Sync entity(ies), ignoring",_,G.t0),this.conversations.delete(_),G.abrupt("return",null);case 32:return this._registerForEvents(U),this.emit("conversationAdded",U),w.status==="joined"&&(U._setStatus("joined",g),this.emit("conversationJoined",U)),G.abrupt("return",U);case 36:case"end":return G.stop()}},y,this,[[17,25]])}));function h(y,g,_){return d.apply(this,arguments)}return h}()},{key:"_fetchMyConversations",value:function(){var d=L.default(P.default.mark(function y(){var g,_,w,S,C,B;return P.default.wrap(function(H){for(;;)switch(H.prev=H.next){case 0:g=[],_=null;case 2:return S=new Pt(this.configuration.links.myConversations),_&&S.arg("PageToken",_),H.next=6,this.services.network.get(S.build());case 6:C=H.sent,B=(w=C.body)===null||w===void 0?void 0:w.conversations.map(function(G){return{descriptor:G,channel_sid:G.conversation_sid,status:G.status,channel:G.sync_objects.conversation,messages:G.sync_objects.messages,roster:"".concat(G.conversation_sid,".roster"),lastConsumedMessageIndex:G.last_read_message_index,notificationLevel:G.notification_level}}),_=C.body.meta.next_token,g=[].concat(Ne.default(g),Ne.default(B));case 10:if(_){H.next=2;break}case 11:return H.abrupt("return",g);case 12:case"end":return H.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"_onConversationRemoved",value:function(h){var y=this.conversations.get(h);y&&(this.conversations.delete(h),this.emit("conversationRemoved",y))}},{key:"_registerForEvents",value:function(h){var y=this;h.on("removed",function(){return y._onConversationRemoved(h.sid)}),h.on("updated",function(g){return y.emit("conversationUpdated",g)}),h.on("participantJoined",function(g){return y.emit("participantJoined",g)}),h.on("participantLeft",function(g){return y.emit("participantLeft",g)}),h.on("participantUpdated",function(g){return y.emit("participantUpdated",g)}),h.on("messageAdded",function(g){return y.emit("messageAdded",g)}),h.on("messageUpdated",function(g){return y.emit("messageUpdated",g)}),h.on("messageRemoved",function(g){return y.emit("messageRemoved",g)}),h.on("typingStarted",function(g){return y.emit("typingStarted",g)}),h.on("typingEnded",function(g){return y.emit("typingEnded",g)})}}]),f}(I.ReplayEventEmitter);function bn(O){var A=fa();return function(){var d=Ke.default(O),h;if(A){var y=Ke.default(this).constructor;h=Reflect.construct(d,arguments,y)}else h=d.apply(this,arguments);return rt.default(this,h)}}function fa(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var F=function(O){Te.default(f,O);var A=bn(f);function f(d,h,y){var g;return he.default(this,f),g=A.call(this),g.configuration=h,g.services=y,g.fifoStack=[],g.myself=d,g.myself.on("updated",function(_){return g.emit("userUpdated",_)}),g.myself.on("userSubscribed",function(){return g.emit("userSubscribed",g.myself)}),g.myself.on("userUnsubscribed",function(){g.emit("userUnsubscribed",g.myself),g.myself._ensureFetched()}),g.subscribedUsers=new Map,g}return ce.default(f,[{key:"handleUnsubscribeUser",value:function(h){this.subscribedUsers.has(h.identity)&&this.subscribedUsers.delete(h.identity);var y=0,g=this.fifoStack.find(function(_,w){return _==h.identity?(y=w,!0):!1});g&&this.fifoStack.splice(y,1),this.emit("userUnsubscribed",h)}},{key:"handleSubscribeUser",value:function(h){if(!this.subscribedUsers.has(h.identity)){if(this.fifoStack.length>=this.configuration.userInfosToSubscribe){var y,g,_=this.fifoStack.shift();(y=this.subscribedUsers)===null||y===void 0||(g=y.get(_))===null||g===void 0||g.unsubscribe()}this.fifoStack.push(h.identity),this.subscribedUsers.set(h.identity,h),this.emit("userSubscribed",h)}}},{key:"getUser",value:function(){var d=L.default(P.default.mark(function y(g,_){var w,S=this,C,B;return P.default.wrap(function(H){for(;;)switch(H.prev=H.next){case 0:return H.next=2,this.myself._ensureFetched();case 2:if(g!=this.myself.identity){H.next=4;break}return H.abrupt("return",this.myself);case 4:if(C=this.subscribedUsers.get(g),!C){H.next=7;break}return H.abrupt("return",C);case 7:if(!((w=_)!==null&&w!==void 0)){H.next=11;break}H.next=14;break;case 11:return H.next=13,this.getSyncUniqueName(g);case 13:_=H.sent;case 14:return B=new ye(g,_,this.configuration,this.services),B.on("updated",function(G){return S.emit("userUpdated",G)}),B.on("userSubscribed",function(){return S.handleSubscribeUser(B)}),B.on("userUnsubscribed",function(){return S.handleUnsubscribeUser(B)}),H.next=20,B._ensureFetched();case 20:return H.abrupt("return",B);case 21:case"end":return H.stop()}},y,this)}));function h(y,g){return d.apply(this,arguments)}return h}()},{key:"getSubscribedUsers",value:function(){var d=L.default(P.default.mark(function y(){var g;return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this.myself._ensureFetched();case 2:return g=[this.myself],this.subscribedUsers.forEach(function(S){return g.push(S)}),w.abrupt("return",g);case 5:case"end":return w.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"getSyncUniqueName",value:function(){var d=L.default(P.default.mark(function y(g){var _,w,S,C;return P.default.wrap(function(U){for(;;)switch(U.prev=U.next){case 0:return S=new Pt(this.configuration.links.users).path(g).build(),U.next=3,this.services.network.get(S);case 3:return C=U.sent,U.abrupt("return",(_=(w=C.body)===null||w===void 0?void 0:w.sync_objects.user_info_map)!==null&&_!==void 0?_:"");case 5:case"end":return U.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()}]),f}(I.ReplayEventEmitter),z=Dt.scope("TypingIndicator"),$=function(){function O(A,f,d){he.default(this,O),this.configuration=f,this.services=d,this.getConversation=A,this.serviceTypingTimeout=null,this.sentUpdates=new Map}return ce.default(O,[{key:"typingTimeout",get:function(){return this.configuration.typingIndicatorTimeoutOverride||this.serviceTypingTimeout||this.configuration.typingIndicatorTimeoutDefault}},{key:"initialize",value:function(){var f=this;this.services.notificationClient.on("message",function(){var d=L.default(P.default.mark(function h(y,g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:if(y!==be.TYPING_INDICATOR){w.next=3;break}return w.next=3,f._handleRemoteTyping(g);case 3:case"end":return w.stop()}},h)}));return function(h,y){return d.apply(this,arguments)}}())}},{key:"_handleRemoteTyping",value:function(){var A=L.default(P.default.mark(function d(h){var y=this;return P.default.wrap(function(_){for(;;)switch(_.prev=_.next){case 0:z.trace("Got new typing indicator ",h),this.getConversation(h.channel_sid).then(function(w){w&&w._participants.forEach(function(S){if(S.identity===h.identity){var C=y.configuration.typingIndicatorTimeoutOverride?y.configuration.typingIndicatorTimeoutOverride+1e3:h.typing_timeout*1e3;S._startTyping(C)}})}).catch(function(w){throw z.error(w),w});case 2:case"end":return _.stop()}},d,this)}));function f(d){return A.apply(this,arguments)}return f}()},{key:"send",value:function(f){var d=this.sentUpdates.get(f);return d&&d>Date.now()-this.typingTimeout?Promise.resolve():(this.sentUpdates.set(f,Date.now()),this._send(f))}},{key:"_send",value:function(f){var d=this;z.trace("Sending typing indicator");var h=this.configuration.links.typing,y={"Content-Type":"application/x-www-form-urlencoded"},g="ChannelSid=".concat(f);return this.services.twilsockClient.post(h,y,g,this.configuration.productId).then(function(_){_.body.hasOwnProperty("typing_timeout")&&(d.serviceTypingTimeout=_.body.typing_timeout*1e3)}).catch(function(_){throw z.error("Failed to send typing indicator:",_),_})}}]),O}(),k=ce.default(function O(A){he.default(this,O),this.title=A.title||null,this.body=A.body||null,this.sound=A.sound||null,this.badge=A.badge||null,this.action=A.action||null,this.type=A.type||null,this.data=A.data||{}}),E="2.6.0";function q(O,A){var f=Object.keys(O);if(Object.getOwnPropertySymbols){var d=Object.getOwnPropertySymbols(O);A&&(d=d.filter(function(h){return Object.getOwnPropertyDescriptor(O,h).enumerable})),f.push.apply(f,d)}return f}function M(O){for(var A=1;A<arguments.length;A++){var f=arguments[A]!=null?arguments[A]:{};A%2?q(Object(f),!0).forEach(function(d){Se.default(O,d,f[d])}):Object.getOwnPropertyDescriptors?Object.defineProperties(O,Object.getOwnPropertyDescriptors(f)):q(Object(f)).forEach(function(d){Object.defineProperty(O,d,Object.getOwnPropertyDescriptor(f,d))})}return O}function ve(O){var A=fe();return function(){var d=Ke.default(O),h;if(A){var y=Ke.default(this).constructor;h=Reflect.construct(d,arguments,y)}else h=d.apply(this,arguments);return rt.default(this,h)}}function fe(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var Ae=function(A){return A.replace(/(^\/+|\/+$)/g,"")},Be=function(A){return A.status.code===202},ot=function(O){Te.default(f,O);var A=ve(f);function f(d){return he.default(this,f),A.call(this,d)}return ce.default(f)}(kt.default(Error)),$r=function(){function O(A,f,d){he.default(this,O),this._serviceUrl=A,this._services=f,this._productId=d}return ce.default(O,[{key:"_preProcessUrl",value:function(f){var d=Ae(f);return/^https?:\/\//.test(f)?d:"".concat(Ae(this._serviceUrl),"/").concat(d)}},{key:"_makeRequest",value:function(){var A=L.default(P.default.mark(function d(h,y,g,_){var w,S,C,B;return P.default.wrap(function(H){for(;;)switch(H.prev=H.next){case 0:w=this._preProcessUrl(y),S=M({"Content-Type":"application/json; charset=utf-8"},_||{}),H.t0=h,H.next=H.t0==="get"?5:H.t0==="post"?11:H.t0==="delete"?15:19;break;case 5:return B=w,g&&(B+="?"+Object.entries(g).map(function(G){return G.map(encodeURIComponent).join("=")}).join("&")),H.next=9,this._services.transport.get(B,S,this._productId);case 9:return C=H.sent,H.abrupt("break",19);case 11:return H.next=13,this._services.transport.post(w,S,JSON.stringify(g),this._productId);case 13:return C=H.sent,H.abrupt("break",19);case 15:return H.next=17,this._services.transport.delete(w,S,{},this._productId);case 17:return C=H.sent,H.abrupt("break",19);case 19:if(!(C.status.code<200||C.status.code>=300)){H.next=21;break}throw new Error("Request responded with a non-success code ".concat(C.status.code));case 21:return H.abrupt("return",C);case 22:case"end":return H.stop()}},d,this)}));function f(d,h,y,g){return A.apply(this,arguments)}return f}()},{key:"fetchResource",value:function(){var A=L.default(P.default.mark(function d(h,y){var g=this,_,w,S;return P.default.wrap(function(B){for(;;)switch(B.prev=B.next){case 0:return _=6,w=new N.AsyncRetrier({min:50,max:1600,maxAttemptsCount:_}),B.prev=2,B.next=5,w.run(L.default(P.default.mark(function U(){var H,G,Le;return P.default.wrap(function(We){for(;;)switch(We.prev=We.next){case 0:return We.prev=0,We.next=3,g._makeRequest("get",h,y);case 3:return H=We.sent,We.abrupt("return",{type:"success",data:H.body});case 7:if(We.prev=7,We.t0=We.catch(0),!((We.t0===null||We.t0===void 0||(G=We.t0.body)===null||G===void 0?void 0:G.status)===404&&(We.t0===null||We.t0===void 0||(Le=We.t0.body)===null||Le===void 0?void 0:Le.code)===50530)){We.next=11;break}return We.abrupt("return",{type:"noMetadata"});case 11:throw We.t0;case 12:case"end":return We.stop()}},U,null,[[0,7]])})));case 5:S=B.sent,B.next=11;break;case 8:throw B.prev=8,B.t0=B.catch(2),new Error('Fetch resource from "'.concat(h,'" failed.'));case 11:if(S.type!=="noMetadata"){B.next=13;break}throw new ot("No metadata found.");case 13:return B.abrupt("return",S.data);case 14:case"end":return B.stop()}},d,null,[[2,8]])}));function f(d,h){return A.apply(this,arguments)}return f}()},{key:"mutateResource",value:function(){var A=L.default(P.default.mark(function d(h,y,g){var _;return P.default.wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return S.next=2,this._makeRequest(h,y,g,{"X-Twilio-Mutation-Id":ue.v4()});case 2:if(_=S.sent,!Be(_)){S.next=7;break}return S.next=6,this.fetchResource(_.body.resource_url);case 6:return S.abrupt("return",S.sent);case 7:return S.abrupt("return",_.body);case 8:case"end":return S.stop()}},d,this)}));function f(d,h,y){return A.apply(this,arguments)}return f}()}]),O}(),ln=function(){function O(A){var f=arguments.length>1&&arguments[1]!==void 0?arguments[1]:100,d=arguments.length>2&&arguments[2]!==void 0?arguments[2]:5e3;he.default(this,O),Se.default(this,"_cachedTemplates",null),this._services=A,this._pageSize=f,this._cacheTtlMs=d}return ce.default(O,[{key:"getContentTemplates",value:function(){var A=L.default(P.default.mark(function d(){var h=this,y,g,_,w,S,C,B;return P.default.wrap(function(H){for(;;)switch(H.prev=H.next){case 0:if(this._cachedTemplates===null){H.next=2;break}return H.abrupt("return",this._cachedTemplates);case 2:return H.next=4,this._fetchContentTemplates();case 4:y=H.sent,g=Q.default(y,2),_=g[0],w=g[1],S=_;case 9:if(w===null){H.next=19;break}return H.next=12,this._fetchContentTemplates(w);case 12:C=H.sent,B=Q.default(C,2),_=B[0],w=B[1],S=[].concat(Ne.default(S),Ne.default(_)),H.next=9;break;case 19:return this._cachedTemplates=Object.freeze(S),setTimeout(function(){h._cachedTemplates=null},this._cacheTtlMs),H.abrupt("return",S);case 22:case"end":return H.stop()}},d,this)}));function f(){return A.apply(this,arguments)}return f}()},{key:"_fetchContentTemplates",value:function(){var A=L.default(P.default.mark(function d(h){var y,g,_;return P.default.wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return y="Client/v2/ContentTemplates",g=new Pt(y),g.arg("PageSize",this._pageSize),h!==void 0&&g.arg("PageToken",h),S.next=6,this._services.commandExecutor.fetchResource(g.build());case 6:return _=S.sent,S.abrupt("return",[_.templates.map(function(C){return new st(C)}),_.meta.next_token]);case 8:case"end":return S.stop()}},d,this)}));function f(d){return A.apply(this,arguments)}return f}()}]),O}();function br(O,A){var f=typeof Symbol<"u"&&O[Symbol.iterator]||O["@@iterator"];if(!f){if(Array.isArray(O)||(f=_n(O))||A){f&&(O=f);var d=0,h=function(){};return{s:h,n:function(){return d>=O.length?{done:!0}:{done:!1,value:O[d++]}},e:function(S){throw S},f:h}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
470
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var y=!0,g=!1,_;return{s:function(){f=f.call(O)},n:function(){var S=f.next();return y=S.done,S},e:function(S){g=!0,_=S},f:function(){try{!y&&f.return!=null&&f.return()}finally{if(g)throw _}}}}function Pi(O,A){if(O){if(typeof O=="string")return Mi(O,A);var f=Object.prototype.toString.call(O).slice(8,-1);if(f==="Object"&&O.constructor&&(f=O.constructor.name),f==="Map"||f==="Set")return Array.from(O);if(f==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(f))return Mi(O,A)}}function Mi(O,A){(A==null||A>O.length)&&(A=O.length);for(var f=0,d=new Array(A);f<A;f++)d[f]=O[f];return d}function li(O,A){var f=Object.keys(O);if(Object.getOwnPropertySymbols){var d=Object.getOwnPropertySymbols(O);A&&(d=d.filter(function(h){return Object.getOwnPropertyDescriptor(O,h).enumerable})),f.push.apply(f,d)}return f}function Hn(O){for(var A=1;A<arguments.length;A++){var f=arguments[A]!=null?arguments[A]:{};A%2?li(Object(f),!0).forEach(function(d){Se.default(O,d,f[d])}):Object.getOwnPropertyDescriptors?Object.defineProperties(O,Object.getOwnPropertyDescriptors(f)):li(Object(f)).forEach(function(d){Object.defineProperty(O,d,Object.getOwnPropertyDescriptor(f,d))})}return O}function kr(O){var A=la();return function(){var d=Ke.default(O),h;if(A){var y=Ke.default(this).constructor;h=Reflect.construct(d,arguments,y)}else h=d.apply(this,arguments);return rt.default(this,h)}}function la(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var Rr=Dt.scope("Conversations"),Vr=function(O){Te.default(f,O);var A=kr(f);function f(d,h){var y;return he.default(this,f),y=A.call(this),Se.default(pe.default(y),"conversations",new Map),Se.default(pe.default(y),"myConversationsRead",new ua),Se.default(pe.default(y),"tombstones",new Set),Se.default(pe.default(y),"myConversationsFetched",!1),y.configuration=d,y.services=h,y}return ce.default(f,[{key:"addConversation",value:function(){var d=L.default(P.default.mark(function y(g){var _,w,S,C,B,U,H,G,Le,Xe;return P.default.wrap(function(Ve){for(;;)switch(Ve.prev=Ve.next){case 0:return C=typeof(g==null?void 0:g.attributes)<"u"?g.attributes:{},Ve.next=3,this.services.commandExecutor.mutateResource("post",this.configuration.links.conversations,{friendly_name:g.friendlyName,unique_name:g.uniqueName,attributes:typeof C<"u"?JSON.stringify(C):void 0});case 3:if(B=Ve.sent,U=(_=B.sid)!==null&&_!==void 0?_:null,H=(w=(S=B.sync_objects)===null||S===void 0?void 0:S.conversation)!==null&&w!==void 0?w:null,G=Hn({self:B.url},B.links),Le=this.conversations.get(U),!Le){Ve.next=12;break}return Ve.next=11,Le._subscribe();case 11:return Ve.abrupt("return",Le);case 12:return Xe=new At({channel:H,entityName:"",uniqueName:"",attributes:null,createdBy:"",friendlyName:"",lastConsumedMessageIndex:0,dateCreated:null,dateUpdated:null},U,G,this.configuration,this.services),this.conversations.set(Xe.sid,Xe),this._registerForEvents(Xe),Ve.next=17,Xe._subscribe();case 17:return this.emit("conversationAdded",Xe),Ve.abrupt("return",Xe);case 19:case"end":return Ve.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"fetchConversations",value:function(){var d=L.default(P.default.mark(function y(){var g=this,_,w,S,C,B,U,H;return P.default.wrap(function(Le){for(;;)switch(Le.prev=Le.next){case 0:return Le.prev=0,Le.next=3,this._getMap();case 3:return _=Le.sent,_.on(J.SyncMap.itemAdded,function(Xe){Rr.debug("itemAdded: ".concat(Xe.item.key)),g._upsertConversation("sync",Xe.item.key,Xe.item.data)}),_.on(J.SyncMap.itemRemoved,function(Xe){Rr.debug("itemRemoved: ".concat(Xe.key));var We=Xe.key;g.myConversationsFetched||g.tombstones.add(We);var Ve=g.conversations.get(We);Ve&&(Ve.status==="joined"&&(Ve._setStatus("notParticipating","sync"),g.emit("conversationLeft",Ve)),g.conversations.delete(We),g.emit("conversationRemoved",Ve),Ve.emit("removed",Ve))}),_.on(J.SyncMap.itemUpdated,function(Xe){Rr.debug("itemUpdated: ".concat(Xe.item.key)),g._upsertConversation("sync",Xe.item.key,Xe.item.data)}),Le.next=9,this._fetchMyConversations();case 9:w=Le.sent,S=[],C=ca(w);try{for(C.s();!(B=C.n()).done;)U=B.value,S.push(this._upsertConversation("rest",U.channel_sid,U))}catch(Xe){C.e(Xe)}finally{C.f()}return this.myConversationsRead.set(!0),Le.next=16,Promise.all(S);case 16:return this.myConversationsFetched=!0,this.tombstones.clear(),Rr.debug("The conversations list has been successfully fetched"),Le.abrupt("return",this);case 22:throw Le.prev=22,Le.t0=Le.catch(0),H="Failed to fetch the conversations list",this.services.syncClient.connectionState!=="disconnected"&&Rr.error(H,Le.t0),Rr.debug("ERROR: ".concat(H),Le.t0),Le.t0;case 28:case"end":return Le.stop()}},y,this,[[0,22]])}));function h(){return d.apply(this,arguments)}return h}()},{key:"getConversations",value:function(){var d=L.default(P.default.mark(function y(){var g=this,_,w;return P.default.wrap(function(C){for(;;)switch(C.prev=C.next){case 0:return C.next=2,this._getMap();case 2:return _=C.sent,C.next=5,_.getItems();case 5:return w=C.sent,C.abrupt("return",this._wrapPaginator(w,function(B){return Promise.all(B.map(function(U){return g._upsertConversation("sync",U.key,U.data)}))}));case 7:case"end":return C.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"getConversation",value:function(){var d=L.default(P.default.mark(function y(g){var _=this,w,S,C;return P.default.wrap(function(U){for(;;)switch(U.prev=U.next){case 0:return U.next=2,this._getMap();case 2:return w=U.sent,U.next=5,w.getItems({key:g});case 5:return S=U.sent,C=S.items.map(function(H){return _._upsertConversation("sync",H.key,H.data)}),U.abrupt("return",C.length>0?C[0]:null);case 8:case"end":return U.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"getConversationByUniqueName",value:function(){var d=L.default(P.default.mark(function y(g){var _,w,S,C,B;return P.default.wrap(function(H){for(;;)switch(H.prev=H.next){case 0:return _=new Pt(this.configuration.links.myConversations).path(g).build(),H.next=3,this.services.network.get(_);case 3:return w=H.sent,S=w.body,C=S.conversation_sid,B={entityName:null,lastConsumedMessageIndex:S.last_read_message_index,status:(S==null?void 0:S.status)||"unknown",friendlyName:S.friendly_name,dateUpdated:S.date_updated,dateCreated:S.date_created,uniqueName:S.unique_name,createdBy:S.created_by,attributes:S.attributes,channel:S.sync_objects.conversation,notificationLevel:S==null?void 0:S.notification_level,sid:C},H.abrupt("return",C?this._upsertConversation("sync",C,B):null);case 8:case"end":return H.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"peekConversation",value:function(){var d=L.default(P.default.mark(function y(g){var _,w,S,C;return P.default.wrap(function(U){for(;;)switch(U.prev=U.next){case 0:return _=new Pt(this.configuration.links.conversations).path(g).build(),U.next=3,this.services.network.get(_);case 3:return w=U.sent,S=w.body,C={entityName:null,status:(S==null?void 0:S.status)||"unknown",friendlyName:S.friendly_name,dateUpdated:S.date_updated,dateCreated:S.date_created,uniqueName:S.unique_name,createdBy:S.created_by,attributes:S.attributes,channel:"".concat(g,".channel"),sid:g},U.abrupt("return",this._upsertConversation("sync",g,C));case 7:case"end":return U.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"_getMap",value:function(){var d=L.default(P.default.mark(function y(){return P.default.wrap(function(_){for(;;)switch(_.prev=_.next){case 0:return _.next=2,this.services.syncClient.map({id:this.configuration.myConversations,mode:"open_existing"});case 2:return _.abrupt("return",_.sent);case 3:case"end":return _.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"_wrapPaginator",value:function(){var d=L.default(P.default.mark(function y(g,_){var w=this,S;return P.default.wrap(function(B){for(;;)switch(B.prev=B.next){case 0:return B.next=2,_(g.items);case 2:return S=B.sent,B.abrupt("return",{items:S.filter(function(U){return U!==null}),hasNextPage:g.hasNextPage,hasPrevPage:g.hasPrevPage,nextPage:function(){return g.nextPage().then(function(H){return w._wrapPaginator(H,_)})},prevPage:function(){return g.prevPage().then(function(H){return w._wrapPaginator(H,_)})}});case 4:case"end":return B.stop()}},y)}));function h(y,g){return d.apply(this,arguments)}return h}()},{key:"_updateConversation",value:function(){var d=L.default(P.default.mark(function y(g,_,w){var S,C,B;return P.default.wrap(function(H){for(;;)switch(H.prev=H.next){case 0:if(S=_._statusSource!==void 0&&g!==_._statusSource,C=g!=="rest"||_._statusSource==="sync",!(S&&C&&g!=="sync")){H.next=5;break}return Rr.trace("upsertConversation: conversation is known from sync and came from REST, ignoring",{sid:_.sid,data:w.status,conversation:_.status}),H.abrupt("return");case 5:if(!(w.status==="joined"&&_.status!=="joined")){H.next=15;break}return _._setStatus("joined",g),B={},typeof w.notificationLevel<"u"&&(B.notificationLevel=w.notificationLevel),typeof w.lastConsumedMessageIndex<"u"&&(B.lastConsumedMessageIndex=w.lastConsumedMessageIndex),_e.default(B,{})||_._update(B),H.next=13,_._subscribe();case 13:return this.emit("conversationJoined",_),H.abrupt("return");case 15:if(!(w.status==="notParticipating"&&_.status==="joined")){H.next=22;break}return _._setStatus("notParticipating",g),_._update(w),H.next=20,_._subscribe();case 20:return this.emit("conversationLeft",_),H.abrupt("return");case 22:if(w.status!=="notParticipating"){H.next=26;break}return H.next=25,_._subscribe();case 25:return H.abrupt("return");case 26:_._update(w);case 27:case"end":return H.stop()}},y,this)}));function h(y,g,_){return d.apply(this,arguments)}return h}()},{key:"_upsertConversation",value:function(){var d=L.default(P.default.mark(function y(g,_,w){var S,C,B,U;return P.default.wrap(function(G){for(;;)switch(G.prev=G.next){case 0:if(Rr.trace("upsertConversation called for ".concat(_),w),S=this.conversations.get(_),!S){G.next=9;break}return Rr.trace("upsertConversation: the conversation ".concat(S.sid," is known;")+"its status is known from the source ".concat(S._statusSource," ")+"and the update came from the source ".concat(g),S),G.next=6,this._updateConversation(g,S,w);case 6:return G.next=8,S._subscribe();case 8:return G.abrupt("return",S);case 9:if(!(g==="rest"&&this.tombstones.has(_))){G.next=12;break}return Rr.trace("upsertChannel: the conversation is deleted but reappeared again from REST, ignoring",_),G.abrupt("return",null);case 12:return Rr.trace("upsertConversation: creating a local conversation object with sid "+_,w),C="".concat(this.configuration.links.conversations,"/").concat(_),B={self:C,messages:"".concat(C,"/Messages"),participants:"".concat(C,"/Participants")},U=new At(w,_,B,this.configuration,this.services),this.conversations.set(_,U),G.prev=17,G.next=20,U._subscribe();case 20:if(w.status!=="joined"){G.next=23;break}return G.next=23,U._fetchStreams();case 23:G.next=32;break;case 25:if(G.prev=25,G.t0=G.catch(17),G.t0.name==="SyncError"){G.next=29;break}throw G.t0;case 29:return Rr.trace("upsertChannel: the conversation is missing some Sync entity(ies), ignoring",_,G.t0),this.conversations.delete(_),G.abrupt("return",null);case 32:return this._registerForEvents(U),this.emit("conversationAdded",U),w.status==="joined"&&(U._setStatus("joined",g),this.emit("conversationJoined",U)),G.abrupt("return",U);case 36:case"end":return G.stop()}},y,this,[[17,25]])}));function h(y,g,_){return d.apply(this,arguments)}return h}()},{key:"_fetchMyConversations",value:function(){var d=L.default(P.default.mark(function y(){var g,_,w,S,C,B;return P.default.wrap(function(H){for(;;)switch(H.prev=H.next){case 0:g=[],_=null;case 2:return S=new Pt(this.configuration.links.myConversations),_&&S.arg("PageToken",_),H.next=6,this.services.network.get(S.build());case 6:C=H.sent,B=(w=C.body)===null||w===void 0?void 0:w.conversations.map(function(G){return{descriptor:G,channel_sid:G.conversation_sid,status:G.status,channel:G.sync_objects.conversation,messages:G.sync_objects.messages,roster:"".concat(G.conversation_sid,".roster"),lastConsumedMessageIndex:G.last_read_message_index,notificationLevel:G.notification_level}}),_=C.body.meta.next_token,g=[].concat(Ne.default(g),Ne.default(B));case 10:if(_){H.next=2;break}case 11:return H.abrupt("return",g);case 12:case"end":return H.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"_onConversationRemoved",value:function(h){var y=this.conversations.get(h);y&&(this.conversations.delete(h),this.emit("conversationRemoved",y))}},{key:"_registerForEvents",value:function(h){var y=this;h.on("removed",function(){return y._onConversationRemoved(h.sid)}),h.on("updated",function(g){return y.emit("conversationUpdated",g)}),h.on("participantJoined",function(g){return y.emit("participantJoined",g)}),h.on("participantLeft",function(g){return y.emit("participantLeft",g)}),h.on("participantUpdated",function(g){return y.emit("participantUpdated",g)}),h.on("messageAdded",function(g){return y.emit("messageAdded",g)}),h.on("messageUpdated",function(g){return y.emit("messageUpdated",g)}),h.on("messageRemoved",function(g){return y.emit("messageRemoved",g)}),h.on("typingStarted",function(g){return y.emit("typingStarted",g)}),h.on("typingEnded",function(g){return y.emit("typingEnded",g)})}}]),f}(I.ReplayEventEmitter);function bn(O){var A=fa();return function(){var d=Ke.default(O),h;if(A){var y=Ke.default(this).constructor;h=Reflect.construct(d,arguments,y)}else h=d.apply(this,arguments);return rt.default(this,h)}}function fa(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var F=function(O){Te.default(f,O);var A=bn(f);function f(d,h,y){var g;return he.default(this,f),g=A.call(this),g.configuration=h,g.services=y,g.fifoStack=[],g.myself=d,g.myself.on("updated",function(_){return g.emit("userUpdated",_)}),g.myself.on("userSubscribed",function(){return g.emit("userSubscribed",g.myself)}),g.myself.on("userUnsubscribed",function(){g.emit("userUnsubscribed",g.myself),g.myself._ensureFetched()}),g.subscribedUsers=new Map,g}return ce.default(f,[{key:"handleUnsubscribeUser",value:function(h){this.subscribedUsers.has(h.identity)&&this.subscribedUsers.delete(h.identity);var y=0,g=this.fifoStack.find(function(_,w){return _==h.identity?(y=w,!0):!1});g&&this.fifoStack.splice(y,1),this.emit("userUnsubscribed",h)}},{key:"handleSubscribeUser",value:function(h){if(!this.subscribedUsers.has(h.identity)){if(this.fifoStack.length>=this.configuration.userInfosToSubscribe){var y,g,_=this.fifoStack.shift();(y=this.subscribedUsers)===null||y===void 0||(g=y.get(_))===null||g===void 0||g.unsubscribe()}this.fifoStack.push(h.identity),this.subscribedUsers.set(h.identity,h),this.emit("userSubscribed",h)}}},{key:"getUser",value:function(){var d=L.default(P.default.mark(function y(g,_){var w,S=this,C,B;return P.default.wrap(function(H){for(;;)switch(H.prev=H.next){case 0:return H.next=2,this.myself._ensureFetched();case 2:if(g!=this.myself.identity){H.next=4;break}return H.abrupt("return",this.myself);case 4:if(C=this.subscribedUsers.get(g),!C){H.next=7;break}return H.abrupt("return",C);case 7:if(!((w=_)!==null&&w!==void 0)){H.next=11;break}H.next=14;break;case 11:return H.next=13,this.getSyncUniqueName(g);case 13:_=H.sent;case 14:return B=new ye(g,_,this.configuration,this.services),B.on("updated",function(G){return S.emit("userUpdated",G)}),B.on("userSubscribed",function(){return S.handleSubscribeUser(B)}),B.on("userUnsubscribed",function(){return S.handleUnsubscribeUser(B)}),H.next=20,B._ensureFetched();case 20:return H.abrupt("return",B);case 21:case"end":return H.stop()}},y,this)}));function h(y,g){return d.apply(this,arguments)}return h}()},{key:"getSubscribedUsers",value:function(){var d=L.default(P.default.mark(function y(){var g;return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this.myself._ensureFetched();case 2:return g=[this.myself],this.subscribedUsers.forEach(function(S){return g.push(S)}),w.abrupt("return",g);case 5:case"end":return w.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"getSyncUniqueName",value:function(){var d=L.default(P.default.mark(function y(g){var _,w,S,C;return P.default.wrap(function(U){for(;;)switch(U.prev=U.next){case 0:return S=new Pt(this.configuration.links.users).path(g).build(),U.next=3,this.services.network.get(S);case 3:return C=U.sent,U.abrupt("return",(_=(w=C.body)===null||w===void 0?void 0:w.sync_objects.user_info_map)!==null&&_!==void 0?_:"");case 5:case"end":return U.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()}]),f}(I.ReplayEventEmitter),z=Dt.scope("TypingIndicator"),$=function(){function O(A,f,d){he.default(this,O),this.configuration=f,this.services=d,this.getConversation=A,this.serviceTypingTimeout=null,this.sentUpdates=new Map}return ce.default(O,[{key:"typingTimeout",get:function(){return this.configuration.typingIndicatorTimeoutOverride||this.serviceTypingTimeout||this.configuration.typingIndicatorTimeoutDefault}},{key:"initialize",value:function(){var f=this;this.services.notificationClient.on("message",function(){var d=L.default(P.default.mark(function h(y,g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:if(y!==be.TYPING_INDICATOR){w.next=3;break}return w.next=3,f._handleRemoteTyping(g);case 3:case"end":return w.stop()}},h)}));return function(h,y){return d.apply(this,arguments)}}())}},{key:"_handleRemoteTyping",value:function(){var A=L.default(P.default.mark(function d(h){var y=this;return P.default.wrap(function(_){for(;;)switch(_.prev=_.next){case 0:z.trace("Got new typing indicator ",h),this.getConversation(h.channel_sid).then(function(w){w&&w._participants.forEach(function(S){if(S.identity===h.identity){var C=y.configuration.typingIndicatorTimeoutOverride?y.configuration.typingIndicatorTimeoutOverride+1e3:h.typing_timeout*1e3;S._startTyping(C)}})}).catch(function(w){throw z.error(w),w});case 2:case"end":return _.stop()}},d,this)}));function f(d){return A.apply(this,arguments)}return f}()},{key:"send",value:function(f){var d=this.sentUpdates.get(f);return d&&d>Date.now()-this.typingTimeout?Promise.resolve():(this.sentUpdates.set(f,Date.now()),this._send(f))}},{key:"_send",value:function(f){var d=this;z.trace("Sending typing indicator");var h=this.configuration.links.typing,y={"Content-Type":"application/x-www-form-urlencoded"},g="ChannelSid=".concat(f);return this.services.twilsockClient.post(h,y,g,this.configuration.productId).then(function(_){_.body.hasOwnProperty("typing_timeout")&&(d.serviceTypingTimeout=_.body.typing_timeout*1e3)}).catch(function(_){throw z.error("Failed to send typing indicator:",_),_})}}]),O}(),k=ce.default(function O(A){he.default(this,O),this.title=A.title||null,this.body=A.body||null,this.sound=A.sound||null,this.badge=A.badge||null,this.action=A.action||null,this.type=A.type||null,this.data=A.data||{}}),E="2.6.0";function q(O,A){var f=Object.keys(O);if(Object.getOwnPropertySymbols){var d=Object.getOwnPropertySymbols(O);A&&(d=d.filter(function(h){return Object.getOwnPropertyDescriptor(O,h).enumerable})),f.push.apply(f,d)}return f}function M(O){for(var A=1;A<arguments.length;A++){var f=arguments[A]!=null?arguments[A]:{};A%2?q(Object(f),!0).forEach(function(d){Se.default(O,d,f[d])}):Object.getOwnPropertyDescriptors?Object.defineProperties(O,Object.getOwnPropertyDescriptors(f)):q(Object(f)).forEach(function(d){Object.defineProperty(O,d,Object.getOwnPropertyDescriptor(f,d))})}return O}function ve(O){var A=fe();return function(){var d=Ke.default(O),h;if(A){var y=Ke.default(this).constructor;h=Reflect.construct(d,arguments,y)}else h=d.apply(this,arguments);return rt.default(this,h)}}function fe(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var Ae=function(A){return A.replace(/(^\/+|\/+$)/g,"")},Be=function(A){return A.status.code===202},ot=function(O){Te.default(f,O);var A=ve(f);function f(d){return he.default(this,f),A.call(this,d)}return ce.default(f)}(kt.default(Error)),$r=function(){function O(A,f,d){he.default(this,O),this._serviceUrl=A,this._services=f,this._productId=d}return ce.default(O,[{key:"_preProcessUrl",value:function(f){var d=Ae(f);return/^https?:\/\//.test(f)?d:"".concat(Ae(this._serviceUrl),"/").concat(d)}},{key:"_makeRequest",value:function(){var A=L.default(P.default.mark(function d(h,y,g,_){var w,S,C,B;return P.default.wrap(function(H){for(;;)switch(H.prev=H.next){case 0:w=this._preProcessUrl(y),S=M({"Content-Type":"application/json; charset=utf-8"},_||{}),H.t0=h,H.next=H.t0==="get"?5:H.t0==="post"?11:H.t0==="delete"?15:19;break;case 5:return B=w,g&&(B+="?"+Object.entries(g).map(function(G){return G.map(encodeURIComponent).join("=")}).join("&")),H.next=9,this._services.transport.get(B,S,this._productId);case 9:return C=H.sent,H.abrupt("break",19);case 11:return H.next=13,this._services.transport.post(w,S,JSON.stringify(g),this._productId);case 13:return C=H.sent,H.abrupt("break",19);case 15:return H.next=17,this._services.transport.delete(w,S,{},this._productId);case 17:return C=H.sent,H.abrupt("break",19);case 19:if(!(C.status.code<200||C.status.code>=300)){H.next=21;break}throw new Error("Request responded with a non-success code ".concat(C.status.code));case 21:return H.abrupt("return",C);case 22:case"end":return H.stop()}},d,this)}));function f(d,h,y,g){return A.apply(this,arguments)}return f}()},{key:"fetchResource",value:function(){var A=L.default(P.default.mark(function d(h,y){var g=this,_,w,S;return P.default.wrap(function(B){for(;;)switch(B.prev=B.next){case 0:return _=6,w=new N.AsyncRetrier({min:50,max:1600,maxAttemptsCount:_}),B.prev=2,B.next=5,w.run(L.default(P.default.mark(function U(){var H,G,Le;return P.default.wrap(function(We){for(;;)switch(We.prev=We.next){case 0:return We.prev=0,We.next=3,g._makeRequest("get",h,y);case 3:return H=We.sent,We.abrupt("return",{type:"success",data:H.body});case 7:if(We.prev=7,We.t0=We.catch(0),!((We.t0===null||We.t0===void 0||(G=We.t0.body)===null||G===void 0?void 0:G.status)===404&&(We.t0===null||We.t0===void 0||(Le=We.t0.body)===null||Le===void 0?void 0:Le.code)===50530)){We.next=11;break}return We.abrupt("return",{type:"noMetadata"});case 11:throw We.t0;case 12:case"end":return We.stop()}},U,null,[[0,7]])})));case 5:S=B.sent,B.next=11;break;case 8:throw B.prev=8,B.t0=B.catch(2),new Error('Fetch resource from "'.concat(h,'" failed.'));case 11:if(S.type!=="noMetadata"){B.next=13;break}throw new ot("No metadata found.");case 13:return B.abrupt("return",S.data);case 14:case"end":return B.stop()}},d,null,[[2,8]])}));function f(d,h){return A.apply(this,arguments)}return f}()},{key:"mutateResource",value:function(){var A=L.default(P.default.mark(function d(h,y,g){var _;return P.default.wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return S.next=2,this._makeRequest(h,y,g,{"X-Twilio-Mutation-Id":ue.v4()});case 2:if(_=S.sent,!Be(_)){S.next=7;break}return S.next=6,this.fetchResource(_.body.resource_url);case 6:return S.abrupt("return",S.sent);case 7:return S.abrupt("return",_.body);case 8:case"end":return S.stop()}},d,this)}));function f(d,h,y){return A.apply(this,arguments)}return f}()}]),O}(),ln=function(){function O(A){var f=arguments.length>1&&arguments[1]!==void 0?arguments[1]:100,d=arguments.length>2&&arguments[2]!==void 0?arguments[2]:5e3;he.default(this,O),Se.default(this,"_cachedTemplates",null),this._services=A,this._pageSize=f,this._cacheTtlMs=d}return ce.default(O,[{key:"getContentTemplates",value:function(){var A=L.default(P.default.mark(function d(){var h=this,y,g,_,w,S,C,B;return P.default.wrap(function(H){for(;;)switch(H.prev=H.next){case 0:if(this._cachedTemplates===null){H.next=2;break}return H.abrupt("return",this._cachedTemplates);case 2:return H.next=4,this._fetchContentTemplates();case 4:y=H.sent,g=Q.default(y,2),_=g[0],w=g[1],S=_;case 9:if(w===null){H.next=19;break}return H.next=12,this._fetchContentTemplates(w);case 12:C=H.sent,B=Q.default(C,2),_=B[0],w=B[1],S=[].concat(Ne.default(S),Ne.default(_)),H.next=9;break;case 19:return this._cachedTemplates=Object.freeze(S),setTimeout(function(){h._cachedTemplates=null},this._cacheTtlMs),H.abrupt("return",S);case 22:case"end":return H.stop()}},d,this)}));function f(){return A.apply(this,arguments)}return f}()},{key:"_fetchContentTemplates",value:function(){var A=L.default(P.default.mark(function d(h){var y,g,_;return P.default.wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return y="Client/v2/ContentTemplates",g=new Pt(y),g.arg("PageSize",this._pageSize),h!==void 0&&g.arg("PageToken",h),S.next=6,this._services.commandExecutor.fetchResource(g.build());case 6:return _=S.sent,S.abrupt("return",[_.templates.map(function(C){return new st(C)}),_.meta.next_token]);case 8:case"end":return S.stop()}},d,this)}));function f(d){return A.apply(this,arguments)}return f}()}]),O}();function br(O,A){var f=typeof Symbol<"u"&&O[Symbol.iterator]||O["@@iterator"];if(!f){if(Array.isArray(O)||(f=_n(O))||A){f&&(O=f);var d=0,h=function(){};return{s:h,n:function(){return d>=O.length?{done:!0}:{done:!1,value:O[d++]}},e:function(S){throw S},f:h}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
471
471
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var y=!0,g=!1,_;return{s:function(){f=f.call(O)},n:function(){var S=f.next();return y=S.done,S},e:function(S){g=!0,_=S},f:function(){try{!y&&f.return!=null&&f.return()}finally{if(g)throw _}}}}function _n(O,A){if(O){if(typeof O=="string")return Cs(O,A);var f=Object.prototype.toString.call(O).slice(8,-1);if(f==="Object"&&O.constructor&&(f=O.constructor.name),f==="Map"||f==="Set")return Array.from(O);if(f==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(f))return Cs(O,A)}}function Cs(O,A){(A==null||A>O.length)&&(A=O.length);for(var f=0,d=new Array(A);f<A;f++)d[f]=O[f];return d}var ko=function(O){function A(){var f=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(he.default(this,A),!(f.maxSize&&f.maxSize>0))throw new TypeError("`maxSize` must be a number greater than 0");this.maxSize=f.maxSize,this.onEviction=f.onEviction,this.cache=new Map,this.oldCache=new Map,this._size=0}return ce.default(A,[{key:"_set",value:function(d,h){if(this.cache.set(d,h),this._size++,this._size>=this.maxSize){if(this._size=0,typeof this.onEviction=="function"){var y=br(this.oldCache.entries()),g;try{for(y.s();!(g=y.n()).done;){var _=Q.default(g.value,2),w=_[0],S=_[1];this.onEviction(w,S)}}catch(C){y.e(C)}finally{y.f()}}this.oldCache=this.cache,this.cache=new Map}}},{key:"get",value:function(d){if(this.cache.has(d))return this.cache.get(d);if(this.oldCache.has(d)){var h=this.oldCache.get(d);return this.oldCache.delete(d),this._set(d,h),h}}},{key:"set",value:function(d,h){return this.cache.has(d)?this.cache.set(d,h):this._set(d,h),this}},{key:"has",value:function(d){return this.cache.has(d)||this.oldCache.has(d)}},{key:"peek",value:function(d){if(this.cache.has(d))return this.cache.get(d);if(this.oldCache.has(d))return this.oldCache.get(d)}},{key:"delete",value:function(d){var h=this.cache.delete(d);return h&&this._size--,this.oldCache.delete(d)||h}},{key:"clear",value:function(){this.cache.clear(),this.oldCache.clear(),this._size=0}},{key:"keys",value:P.default.mark(function f(){var d,h,y,g;return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:d=br(this),w.prev=1,d.s();case 3:if((h=d.n()).done){w.next=9;break}return y=Q.default(h.value,1),g=y[0],w.next=7,g;case 7:w.next=3;break;case 9:w.next=14;break;case 11:w.prev=11,w.t0=w.catch(1),d.e(w.t0);case 14:return w.prev=14,d.f(),w.finish(14);case 17:case"end":return w.stop()}},f,this,[[1,11,14,17]])})},{key:"values",value:P.default.mark(function f(){var d,h,y,g;return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:d=br(this),w.prev=1,d.s();case 3:if((h=d.n()).done){w.next=9;break}return y=Q.default(h.value,2),g=y[1],w.next=7,g;case 7:w.next=3;break;case 9:w.next=14;break;case 11:w.prev=11,w.t0=w.catch(1),d.e(w.t0);case 14:return w.prev=14,d.f(),w.finish(14);case 17:case"end":return w.stop()}},f,this,[[1,11,14,17]])})},{key:O,value:P.default.mark(function f(){var d,h,y,g,_,w,S,C;return P.default.wrap(function(U){for(;;)switch(U.prev=U.next){case 0:d=br(this.cache),U.prev=1,d.s();case 3:if((h=d.n()).done){U.next=9;break}return y=h.value,U.next=7,y;case 7:U.next=3;break;case 9:U.next=14;break;case 11:U.prev=11,U.t0=U.catch(1),d.e(U.t0);case 14:return U.prev=14,d.f(),U.finish(14);case 17:g=br(this.oldCache),U.prev=18,g.s();case 20:if((_=g.n()).done){U.next=28;break}if(w=_.value,S=Q.default(w,1),C=S[0],this.cache.has(C)){U.next=26;break}return U.next=26,w;case 26:U.next=20;break;case 28:U.next=33;break;case 30:U.prev=30,U.t1=U.catch(18),g.e(U.t1);case 33:return U.prev=33,g.f(),U.finish(33);case 36:case"end":return U.stop()}},f,this,[[1,11,14,17],[18,30,33,36]])})},{key:"size",get:function(){var d=0,h=br(this.oldCache.keys()),y;try{for(h.s();!(y=h.n()).done;){var g=y.value;this.cache.has(g)||d++}}catch(_){h.e(_)}finally{h.f()}return Math.min(this._size+d,this.maxSize)}}]),A}(Symbol.iterator),W=ko,ie=ce.default(function O(A,f){he.default(this,O),this.type=A,this.data=f,Object.freeze(f)}),Ee=function(){function O(A,f){he.default(this,O),this._services=A,this._configuration=f,this._cache=new W({maxSize:f.channelMetadataCacheCapacity})}return ce.default(O,[{key:"getChannelMetadata",value:function(){var A=L.default(P.default.mark(function d(h,y){var g,_,w,S,C;return P.default.wrap(function(U){for(;;)switch(U.prev=U.next){case 0:if(g="".concat(h,",").concat(y),_=this._cache.get(g),!_){U.next=4;break}return U.abrupt("return",_.item);case 4:return w="".concat(this._configuration.links.conversations,"/").concat(h,"/Messages/").concat(y,"/ChannelMetadata"),U.prev=5,U.next=8,this._services.commandExecutor.fetchResource(w);case 8:S=U.sent,U.next=17;break;case 11:if(U.prev=11,U.t0=U.catch(5),!(U.t0 instanceof ot)){U.next=16;break}return this._cache.set(g,{item:null}),U.abrupt("return",null);case 16:throw new Error(U.t0);case 17:return C=new ie(S.type,S.data),this._cache.set(g,{item:C}),U.abrupt("return",C);case 20:case"end":return U.stop()}},d,this,[[5,11]])}));function f(d,h){return A.apply(this,arguments)}return f}()}]),O}();function Ze(O,A){var f=typeof Symbol<"u"&&O[Symbol.iterator]||O["@@iterator"];if(!f){if(Array.isArray(O)||(f=Kt(O))||A){f&&(O=f);var d=0,h=function(){};return{s:h,n:function(){return d>=O.length?{done:!0}:{done:!1,value:O[d++]}},e:function(S){throw S},f:h}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
472
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var y=!0,g=!1,_;return{s:function(){f=f.call(O)},n:function(){var S=f.next();return y=S.done,S},e:function(S){g=!0,_=S},f:function(){try{!y&&f.return!=null&&f.return()}finally{if(g)throw _}}}}function Kt(O,A){if(O){if(typeof O=="string")return _t(O,A);var f=Object.prototype.toString.call(O).slice(8,-1);if(f==="Object"&&O.constructor&&(f=O.constructor.name),f==="Map"||f==="Set")return Array.from(O);if(f==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(f))return _t(O,A)}}function _t(O,A){(A==null||A>O.length)&&(A=O.length);for(var f=0,d=new Array(A);f<A;f++)d[f]=O[f];return d}var Jt=ce.default(function O(A){he.default(this,O),Se.default(this,"type","email"),this.messageSid=A.message_sid,this.level=A.level,this.name=A.name,this.address=A.address}),ur=ce.default(function O(A){he.default(this,O),this.type=A.type,this.messageSid=A.message_sid,this.rawData=JSON.stringify(A)}),_r=function(){function O(A,f){he.default(this,O),this._services=A,this._configuration=f,this._cache=new W({maxSize:f.messageRecipientsCacheCapacity})}return ce.default(O,[{key:"getRecipientsFromMessage",value:function(){var A=L.default(P.default.mark(function d(h,y){var g=this,_,w,S,C,B;return P.default.wrap(function(H){for(;;)switch(H.prev=H.next){case 0:if(_="".concat(h,",").concat(y),w=this._cache.get(_),!w){H.next=4;break}return H.abrupt("return",w.item);case 4:return S=new Pt(this._configuration.links.conversations).path(h).path("MessageRecipients").arg("MessageSid",y).build(),H.next=7,this._services.commandExecutor.fetchResource(S);case 7:return C=H.sent,B=C.message_recipients.map(function(G){return g._wrapResponse(G)}),B.length>0&&this._cache.set(_,{item:B}),H.abrupt("return",B);case 11:case"end":return H.stop()}},d,this)}));function f(d,h){return A.apply(this,arguments)}return f}()},{key:"getRecipientsFromConversation",value:function(){var A=L.default(P.default.mark(function d(h,y){var g,_,w=this,S,C,B,U,H,G,Le,Xe,We,Ve;return P.default.wrap(function(Tt){for(;;)switch(Tt.prev=Tt.next){case 0:return S=new Pt(this._configuration.links.conversations).path(h).path("MessageRecipients").arg("PageToken",(g=y==null?void 0:y.pageToken)!==null&&g!==void 0?g:void 0).arg("PageSize",(_=y==null?void 0:y.pageSize)!==null&&_!==void 0?_:void 0).build(),Tt.next=3,this._services.commandExecutor.fetchResource(S);case 3:C=Tt.sent,B=C.message_recipients.map(function(pt){return w._wrapResponse(pt)}),U=Ze(B);try{for(U.s();!(H=U.n()).done;)Xe=H.value,We="".concat(h,",").concat(Xe.messageSid),Ve=(G=(Le=this._cache.get(We))===null||Le===void 0?void 0:Le.item)!==null&&G!==void 0?G:[],this._cache.set(We,{item:[].concat(Ne.default(Ve),[Xe])})}catch(pt){U.e(pt)}finally{U.f()}return Tt.abrupt("return",new He(B,function(pt,hr){return w.getRecipientsFromConversation(h,{pageToken:pt,pageSize:hr})},C.meta.previous_token,C.meta.next_token));case 8:case"end":return Tt.stop()}},d,this)}));function f(d,h){return A.apply(this,arguments)}return f}()},{key:"_wrapResponse",value:function(f){switch(f.type){case"email":return new Jt(f);default:return new ur(f)}}}]),O}(),lt;function jr(O,A){var f=Object.keys(O);if(Object.getOwnPropertySymbols){var d=Object.getOwnPropertySymbols(O);A&&(d=d.filter(function(h){return Object.getOwnPropertyDescriptor(O,h).enumerable})),f.push.apply(f,d)}return f}function Fr(O){for(var A=1;A<arguments.length;A++){var f=arguments[A]!=null?arguments[A]:{};A%2?jr(Object(f),!0).forEach(function(d){Se.default(O,d,f[d])}):Object.getOwnPropertyDescriptors?Object.defineProperties(O,Object.getOwnPropertyDescriptors(f)):jr(Object(f)).forEach(function(d){Object.defineProperty(O,d,Object.getOwnPropertyDescriptor(f,d))})}return O}function pr(O){var A=Ur();return function(){var d=Ke.default(O),h;if(A){var y=Ke.default(this).constructor;h=Reflect.construct(d,arguments,y)}else h=d.apply(this,arguments);return rt.default(this,h)}}function Ur(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var gt,In=ce.default(function O(){he.default(this,O)});e.Client=gt=(lt=function(O){Te.default(f,O);var A=pr(f);function f(d){var h,y,g,_,w,S,C=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(he.default(this,f),S=A.call(this),Se.default(pe.default(S),"version",E),Se.default(pe.default(S),"connectionState","unknown"),Se.default(pe.default(S),"parsePushNotification",gt.parsePushNotification),S._fpaToken=d??"",S._options=C??{},!S._options.disableDeepClone){var B=Fr(Fr({},S._options),{},{transport:void 0,twilsockClient:void 0});B=It(B),B.transport=S._options.transport,B.twilsockClient=S._options.twilsockClient,S._options=B}S._options.logLevel=(h=S._options.logLevel)!==null&&h!==void 0?h:"silent",gt._logger.setLevel(S._options.logLevel);var U=S._options.productId="ip_messaging";if(S._options.clientMetadata=S._options.clientMetadata||{},S._options.clientMetadata.hasOwnProperty("type")||(S._options.clientMetadata.type="conversations"),S._options.clientMetadata.hasOwnProperty("sdk")||(S._options.clientMetadata.sdk="JS",S._options.clientMetadata.sdkv=E),S._options.Sync=S._options.Sync||{},typeof S._options.Sync.enableSessionStorage>"u"&&(S._options.Sync.enableSessionStorage=!0),S._options.region&&(S._options.Sync.region=S._options.region),!d)throw new Error("A valid Twilio token should be provided");S._services=new In,S._myself=new ye("","",null,S._services);var H=!S._options.twilsockClient;if(!S._options.initRegistrations){var G=new j.InitRegistration(U);gt.populateInitRegistrations(G),S._options.initRegistrations=[G]}S._services.twilsockClient=S._options.twilsockClient=(y=S._options.twilsockClient)!==null&&y!==void 0?y:new j.TwilsockClient(d,U,S._options),S._services.twilsockClient.on(gt.tokenAboutToExpire,function(){return S.emit(gt.tokenAboutToExpire)}),S._services.twilsockClient.on(gt.tokenExpired,function(){return S.emit(gt.tokenExpired)}),S._services.twilsockClient.on(gt.connectionError,function(Tt){return S.emit(gt.connectionError,Tt)}),S._services.twilsockClient.on("stateChanged",function(Tt){gt._logger.debug("Handling stateChanged for ConversationsClient: new state ".concat(Tt)),Tt!==S.connectionState&&(S.connectionState=Tt,S.emit(gt.connectionStateChanged,S.connectionState))}),S._services.transport=S._options.transport=(g=S._options.transport)!==null&&g!==void 0?g:S._options.twilsockClient,S._services.notificationClient=S._options.notificationsClient=(_=S._options.notificationsClient)!==null&&_!==void 0?_:new X.Notifications(d,S._options),S._services.syncClient=S._options.syncClient=(w=S._options.syncClient)!==null&&w!==void 0?w:new J.SyncClient(d,S._options);var Le=(C==null?void 0:C.Chat)||(C==null?void 0:C.IPMessaging)||C||{},Xe=Le.region||(C==null?void 0:C.region),We=Le.apiUri||Le.typingUri||"https://aim.".concat(Xe||"us1",".twilio.com");S._services.commandExecutor=new $r(We,{transport:S._options.transport},U),S._services.contentClient=new ln(S._services);var Ve=function(pt){S._rejectEnsureReady(pt),S.emit(gt.stateChanged,"failed"),S.emit(gt.initFailed,{error:pt})},Nt=function(){Ve({terminal:!0,message:"Twilsock has disconnected."}),S._initializeEnsureReady((C==null?void 0:C.throwErrorsAlways)||!1)};return S._services.twilsockClient.once("connectionError",Ve),S._services.twilsockClient.once("disconnected",Nt),S._services.twilsockClient.once("connected",L.default(P.default.mark(function Tt(){var pt,hr;return P.default.wrap(function(ut){for(;;)switch(ut.prev=ut.next){case 0:return gt._logger.debug("ConversationsClient started INITIALIZING"),S._services.twilsockClient.off("connectionError",Ve),S._services.twilsockClient.off("disconnected",Nt),ut.prev=3,pt="conversations.client.startup",S._services.twilsockClient.addPartialTelemetryEvent(new j.TelemetryEventDescription(pt,"Conversations client startup",new Date),pt,j.TelemetryPoint.Start),ut.next=8,S._initialize();case 8:S._services.twilsockClient.addPartialTelemetryEvent(new j.TelemetryEventDescription("","",new Date),pt,j.TelemetryPoint.End),ut.next=17;break;case 11:ut.prev=11,ut.t0=ut.catch(3),hr={terminal:!0,message:ut.t0.message},S._rejectEnsureReady(hr),S.emit(gt.stateChanged,"failed"),S.emit(gt.initFailed,{error:hr});case 17:case"end":return ut.stop()}},Tt,null,[[3,11]])}))),S._initializeEnsureReady((C==null?void 0:C.throwErrorsAlways)||!1),H&&S._services.twilsockClient.connect(),S}return ce.default(f,[{key:"user",get:function(){return this._myself}},{key:"reachabilityEnabled",get:function(){if(!this._configuration)throw new Error("Reachability information could not yet be accessed as the client has not yet been initialized. Subscribe to the 'stateChanged' event to properly react to the client initialization.");return this._configuration.reachabilityEnabled}},{key:"token",get:function(){return this._fpaToken}},{key:"shutdown",value:function(){var d=L.default(P.default.mark(function y(){return P.default.wrap(function(_){for(;;)switch(_.prev=_.next){case 0:return _.next=2,this._ensureReady;case 2:return _.next=4,this._services.twilsockClient.disconnect();case 4:case"end":return _.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"updateToken",value:function(){var d=L.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this._ensureReady;case 2:if(gt._logger.info("updateToken"),this._fpaToken!==g){w.next=5;break}return w.abrupt("return",this);case 5:return w.next=7,this._services.twilsockClient.updateToken(g);case 7:return w.next=9,this._services.notificationClient.updateToken(g);case 9:return w.next=11,this._services.mcsClient.updateToken(g);case 11:return this._fpaToken=g,w.abrupt("return",this);case 13:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"getConversationBySid",value:function(){var d=L.default(P.default.mark(function y(g){var _;return P.default.wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return S.next=2,this._ensureReady;case 2:return S.next=4,this._conversationsEntity.myConversationsRead.promise;case 4:return S.next=6,this._conversationsEntity.getConversation(g);case 6:if(_=S.sent,_){S.next=12;break}return S.next=10,this.peekConversationBySid(g);case 10:_=S.sent,_&&D.deprecationWarning("The method getConversationBySid is deprecated to retrieve conversations you're not part of. Use peekConversationBySid instead.");case 12:if(_){S.next=14;break}throw new Error("Conversation with SID ".concat(g," was not found."));case 14:return S.abrupt("return",_);case 15:case"end":return S.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"peekConversationBySid",value:function(){var d=L.default(P.default.mark(function y(g){var _;return P.default.wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return S.next=2,this._ensureReady;case 2:return S.next=4,this._conversationsEntity.peekConversation(g);case 4:if(_=S.sent,_){S.next=7;break}throw new Error("Conversation with SID ".concat(g," was not found."));case 7:return S.abrupt("return",_);case 8:case"end":return S.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"getConversationByUniqueName",value:function(){var d=L.default(P.default.mark(function y(g){var _;return P.default.wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return S.next=2,this._ensureReady;case 2:return S.next=4,this._conversationsEntity.myConversationsRead.promise;case 4:return S.next=6,this._conversationsEntity.getConversationByUniqueName(g);case 6:if(_=S.sent,_){S.next=9;break}throw new Error("Conversation with unique name ".concat(g," was not found."));case 9:return S.abrupt("return",_);case 10:case"end":return S.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"getSubscribedConversations",value:function(){var d=L.default(P.default.mark(function y(){return P.default.wrap(function(_){for(;;)switch(_.prev=_.next){case 0:return _.next=2,this._ensureReady;case 2:return _.abrupt("return",this._conversationsPromise.then(function(w){return w.getConversations()}));case 3:case"end":return _.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"createConversation",value:function(){var d=L.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this._ensureReady;case 2:return g=g||{},w.abrupt("return",this._conversationsPromise.then(function(S){return S.addConversation(g)}));case 4:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"setPushRegistrationId",value:function(){var d=L.default(P.default.mark(function y(g,_){return P.default.wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return S.next=2,this._ensureReady;case 2:return this._subscribeToPushNotifications(g),this._services.notificationClient.setPushRegistrationId(g,_),S.next=6,this._services.notificationClient.commitChanges();case 6:case"end":return S.stop()}},y,this)}));function h(y,g){return d.apply(this,arguments)}return h}()},{key:"unsetPushRegistrationId",value:function(){var d=L.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this._ensureReady;case 2:return this._unsubscribeFromPushNotifications(g),w.next=5,this._services.notificationClient.commitChanges();case 5:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"removePushRegistrations",value:function(){var d=L.default(P.default.mark(function y(g,_){return P.default.wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return S.next=2,this._services.notificationClient.removeRegistrations(g,_);case 2:case"end":return S.stop()}},y,this)}));function h(y,g){return d.apply(this,arguments)}return h}()},{key:"handlePushNotification",value:function(){var d=L.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this._ensureReady;case 2:gt._logger.debug("handlePushNotification, notificationPayload=",g),this.emit("pushNotification",gt.parsePushNotification(g));case 4:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"getUser",value:function(){var d=L.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this._ensureReady;case 2:return w.abrupt("return",this._services.users.getUser(g));case 3:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"getSubscribedUsers",value:function(){var d=L.default(P.default.mark(function y(){return P.default.wrap(function(_){for(;;)switch(_.prev=_.next){case 0:return _.next=2,this._ensureReady;case 2:return _.abrupt("return",this._services.users.getSubscribedUsers());case 3:case"end":return _.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"getTemporaryContentUrlsForMediaSids",value:function(h){var y=this;return new V.CancellablePromise(function(){var g=L.default(P.default.mark(function _(w,S,C){var B,U;return P.default.wrap(function(G){for(;;)switch(G.prev=G.next){case 0:if(!(!y._services.mcsClient||!h)){G.next=3;break}return S(new Error("Media Content Service is unavailable")),G.abrupt("return");case 3:return B=y._services.mcsClient.mediaSetGetContentUrls(h),C(function(){B.cancel()}),G.prev=5,G.next=8,B;case 8:U=G.sent,w(U),G.next=15;break;case 12:G.prev=12,G.t0=G.catch(5),S(G.t0);case 15:case"end":return G.stop()}},_,null,[[5,12]])}));return function(_,w,S){return g.apply(this,arguments)}}())}},{key:"getTemporaryContentUrlsForMedia",value:function(h){var y=h.map(function(g){return g.sid});return this.getTemporaryContentUrlsForMediaSids(y)}},{key:"getContentTemplates",value:function(){var d=L.default(P.default.mark(function y(){return P.default.wrap(function(_){for(;;)switch(_.prev=_.next){case 0:return _.next=2,this._ensureReady;case 2:return _.next=4,this._services.contentClient.getContentTemplates();case 4:return _.abrupt("return",_.sent);case 5:case"end":return _.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"_initialize",value:function(){var d=L.default(P.default.mark(function y(){var g=this,_;return P.default.wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return S.next=2,this._services.commandExecutor.fetchResource("Client/v2/Configuration");case 2:return _=S.sent,this._configuration=new Et(this._options,_,gt._logger),this._services.channelMetadataClient=new Ee(this._services,this._configuration),this._services.messageRecipientsClient=new _r(this._services,this._configuration),this._myself._resolveInitialization(this._configuration,this._configuration.userIdentity,this._configuration.userInfo,!0),this._services.typingIndicator=new $(this.getConversationBySid.bind(this),this._configuration,this._services),this._services.network=new le(this._configuration,this._services),this._services.users=new F(this._myself,this._configuration,this._services),this._services.users.on("userSubscribed",function(C){g.emit("userSubscribed",C)}),this._services.users.on("userUpdated",function(C){return g.emit("userUpdated",C)}),this._services.users.on("userUnsubscribed",function(C){g.emit("userUnsubscribed",C)}),this._conversationsEntity=new Hr(this._configuration,this._services),this._conversationsEntity.on("conversationAdded",function(C){g.emit("conversationAdded",C)}),this._conversationsEntity.on("conversationRemoved",function(C){g.emit("conversationRemoved",C)}),this._conversationsEntity.on("conversationJoined",function(C){g.emit("conversationJoined",C)}),this._conversationsEntity.on("conversationLeft",function(C){g.emit("conversationLeft",C)}),this._conversationsEntity.on("conversationUpdated",function(C){return g.emit("conversationUpdated",C)}),this._conversationsEntity.on("participantJoined",function(C){g.emit("participantJoined",C)}),this._conversationsEntity.on("participantLeft",function(C){g.emit("participantLeft",C)}),this._conversationsEntity.on("participantUpdated",function(C){return g.emit("participantUpdated",C)}),this._conversationsEntity.on("messageAdded",function(C){return g.emit("messageAdded",C)}),this._conversationsEntity.on("messageUpdated",function(C){return g.emit("messageUpdated",C)}),this._conversationsEntity.on("messageRemoved",function(C){return g.emit("messageRemoved",C)}),this._conversationsEntity.on("typingStarted",function(C){return g.emit("typingStarted",C)}),this._conversationsEntity.on("typingEnded",function(C){return g.emit("typingEnded",C)}),this._conversationsPromise=this._conversationsEntity.fetchConversations().then(function(){return g._conversationsEntity}).catch(function(C){throw C}),S.next=30,this._services.users.myself._ensureFetched();case 30:gt._supportedPushChannels.forEach(function(C){return g._subscribeToPushNotifications(C)}),this._services.typingIndicator.initialize(),this._services.mcsClient=new V.McsClient(this._fpaToken,this._configuration.links.mediaService,this._configuration.links.mediaSetService,Fr(Fr({},this._options),{},{transport:void 0})),this._resolveEnsureReady(),this.emit(gt.stateChanged,"initialized"),this.emit(gt.initialized);case 36:case"end":return S.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"_subscribeToPushNotifications",value:function(h){var y=this;[be.NEW_MESSAGE,be.ADDED_TO_CONVERSATION,be.REMOVED_FROM_CONVERSATION,be.TYPING_INDICATOR,be.CONSUMPTION_UPDATE].forEach(function(g){y._services.notificationClient.subscribe(h,g)})}},{key:"_unsubscribeFromPushNotifications",value:function(h){var y=this;[be.NEW_MESSAGE,be.ADDED_TO_CONVERSATION,be.REMOVED_FROM_CONVERSATION,be.TYPING_INDICATOR,be.CONSUMPTION_UPDATE].forEach(function(g){y._services.notificationClient.unsubscribe(h,g)})}},{key:"_initializeEnsureReady",value:function(h){var y=this;this._ensureReady=new Promise(function(g,_){y._resolveEnsureReady=g,y._rejectEnsureReady=_}).catch(function(g){if(h)throw g})}}],[{key:"create",value:function(){var d=L.default(P.default.mark(function y(g,_){var w;return P.default.wrap(function(C){for(;;)switch(C.prev=C.next){case 0:if(!(_!=null&&_.twilsockClient)){C.next=2;break}throw new Error("Obsolete usage of ConversationsClient.create() factory method: if you pass twilsock from the outside then you must use ConversationsClient constructor and be prepared to work with uninitialized client.");case 2:return w=new gt(g,_),C.next=5,w._ensureReady;case 5:return C.abrupt("return",w);case 6:case"end":return C.stop()}},y)}));function h(y,g){return d.apply(this,arguments)}return h}()},{key:"parsePushNotification",value:function(h){if(gt._logger.debug("parsePushNotification, notificationPayload=",h),typeof h.aps<"u"){if(!h.twi_message_type)throw new Error("Provided push notification payload does not contain Programmable Chat push notification type");var y=gt._parsePushNotificationChatData(h),g=h.aps,_,w=null;if(typeof g.alert=="string")_=g.alert||null;else{var S,C;_=((S=g.alert)===null||S===void 0?void 0:S.body)||null,w=((C=g.alert)===null||C===void 0?void 0:C.title)||null}return new k({title:w,body:_,sound:g.sound||null,badge:g.badge||null,action:g.category||null,type:h.twi_message_type,data:y})}if(typeof h.data<"u"){var B=h.data;if(!B.twi_message_type)throw new Error("Provided push notification payload does not contain Programmable Chat push notification type");var U=gt._parsePushNotificationChatData(h.data);return new k({title:B.twi_title||null,body:B.twi_body||null,sound:B.twi_sound||null,badge:null,action:B.twi_action||null,type:B.twi_message_type,data:U})}throw new Error("Provided push notification payload is not Programmable Chat notification")}},{key:"_parsePushNotificationChatData",value:function(h){var y={};for(var g in gt._supportedPushDataFields){var _=h[g];if(!(typeof _>"u"||_===null)){if(g==="message_index"||g==="media_count"){var w=bt(_);w!==null&&(y[gt._supportedPushDataFields[g]]=w);continue}if(g==="media"){if(typeof _=="string")try{y[gt._supportedPushDataFields[g]]=JSON.parse(_)}catch{gt._logger.debug("Media message notification parsing error")}continue}y[gt._supportedPushDataFields[g]]=_}}return y}},{key:"populateInitRegistrations",value:function(h){h.populateInitRegistrations([be.TYPING_INDICATOR]),J.SyncClient.populateInitRegistrations(h)}}]),f}(I.ReplayEventEmitter),Se.default(lt,"conversationAdded","conversationAdded"),Se.default(lt,"conversationJoined","conversationJoined"),Se.default(lt,"conversationLeft","conversationLeft"),Se.default(lt,"conversationRemoved","conversationRemoved"),Se.default(lt,"conversationUpdated","conversationUpdated"),Se.default(lt,"participantJoined","participantJoined"),Se.default(lt,"participantLeft","participantLeft"),Se.default(lt,"participantUpdated","participantUpdated"),Se.default(lt,"messageAdded","messageAdded"),Se.default(lt,"messageRemoved","messageRemoved"),Se.default(lt,"messageUpdated","messageUpdated"),Se.default(lt,"tokenAboutToExpire","tokenAboutToExpire"),Se.default(lt,"tokenExpired","tokenExpired"),Se.default(lt,"typingEnded","typingEnded"),Se.default(lt,"typingStarted","typingStarted"),Se.default(lt,"pushNotification","pushNotification"),Se.default(lt,"userSubscribed","userSubscribed"),Se.default(lt,"userUnsubscribed","userUnsubscribed"),Se.default(lt,"userUpdated","userUpdated"),Se.default(lt,"stateChanged","stateChanged"),Se.default(lt,"initialized","initialized"),Se.default(lt,"initFailed","initFailed"),Se.default(lt,"connectionStateChanged","connectionStateChanged"),Se.default(lt,"connectionError","connectionError"),Se.default(lt,"version",E),Se.default(lt,"_logger",Dt.scope("Client")),Se.default(lt,"_supportedPushChannels",["fcm","apn"]),Se.default(lt,"_supportedPushDataFields",{conversation_sid:"conversationSid",conversation_title:"conversationTitle",message_sid:"messageSid",message_index:"messageIndex",media_count:"mediaCount",media:"media"}),lt),Ce([D.deprecated("token"),de("design:type",String),de("design:paramtypes",[])],e.Client.prototype,"token",null),Ce([b.validateTypesAsync(b.nonEmptyString),de("design:type",Function),de("design:paramtypes",[String]),de("design:returntype",Promise)],e.Client.prototype,"updateToken",null),Ce([b.validateTypesAsync(b.nonEmptyString),de("design:type",Function),de("design:paramtypes",[String]),de("design:returntype",Promise)],e.Client.prototype,"getConversationBySid",null),Ce([b.validateTypesAsync(b.nonEmptyString),de("design:type",Function),de("design:paramtypes",[String]),de("design:returntype",Promise)],e.Client.prototype,"peekConversationBySid",null),Ce([b.validateTypesAsync(b.nonEmptyString),de("design:type",Function),de("design:paramtypes",[String]),de("design:returntype",Promise)],e.Client.prototype,"getConversationByUniqueName",null),Ce([b.validateTypesAsync(["undefined",b.objectSchema("conversation options",{friendlyName:["string","undefined"],isPrivate:["boolean","undefined"],uniqueName:["string","undefined"]})]),de("design:type",Function),de("design:paramtypes",[Object]),de("design:returntype",Promise)],e.Client.prototype,"createConversation",null),Ce([b.validateTypesAsync(b.literal("fcm","apn"),"string"),de("design:type",Function),de("design:paramtypes",[String,String]),de("design:returntype",Promise)],e.Client.prototype,"setPushRegistrationId",null),Ce([b.validateTypesAsync(b.literal("fcm","apn")),de("design:type",Function),de("design:paramtypes",[String]),de("design:returntype",Promise)],e.Client.prototype,"unsetPushRegistrationId",null),Ce([b.validateTypesAsync(b.literal("fcm","apn"),b.nonEmptyString),de("design:type",Function),de("design:paramtypes",[String,String]),de("design:returntype",Promise)],e.Client.prototype,"removePushRegistrations",null),Ce([b.validateTypesAsync(b.pureObject),de("design:type",Function),de("design:paramtypes",[Object]),de("design:returntype",Promise)],e.Client.prototype,"handlePushNotification",null),Ce([b.validateTypesAsync(b.nonEmptyString),de("design:type",Function),de("design:paramtypes",[String]),de("design:returntype",Promise)],e.Client.prototype,"getUser",null),Ce([b.validateTypesAsync(b.nonEmptyArray("strings","string")),de("design:type",Function),de("design:paramtypes",[Array]),de("design:returntype",V.CancellablePromise)],e.Client.prototype,"getTemporaryContentUrlsForMediaSids",null),Ce([b.validateTypesAsync(b.nonEmptyArray("media",Je)),de("design:type",Function),de("design:paramtypes",[Array]),de("design:returntype",V.CancellablePromise)],e.Client.prototype,"getTemporaryContentUrlsForMedia",null),Ce([D.deprecated("Client.create()","new Client()"),b.validateTypesAsync("string",["undefined",b.pureObject]),de("design:type",Function),de("design:paramtypes",[String,Object]),de("design:returntype",Promise)],e.Client,"create",null),Ce([b.validateTypes(b.pureObject),de("design:type",Function),de("design:paramtypes",[Object]),de("design:returntype",k)],e.Client,"parsePushNotification",null),e.Client=gt=Ce([b.validateConstructorTypes(b.nonEmptyString,[b.pureObject,"undefined"]),de("design:paramtypes",[String,Object])],e.Client),Object.defineProperty(e,"CancellablePromise",{enumerable:!0,get:function(){return V.CancellablePromise}}),e.AggregatedDeliveryReceipt=Ge,e.ChannelMetadata=ie,e.ContentTemplate=st,e.ContentTemplateVariable=at,e.Conversation=At,e.DetailedDeliveryReceipt=et,e.EmailRecipientDescriptor=Jt,e.Media=Je,e.Message=Ot,e.MessageBuilder=or,e.NotificationTypes=be,e.Participant=K,e.PushNotification=k,e.RestPaginator=He,e.UnknownRecipientDescriptor=ur,e.UnsentMessage=ci,e.User=ye})(UT);const xn=new $a("twilio-chat");class k$ extends tm{constructor(){super(...arguments);ht(this,"client");ht(this,"conversation")}async create(){const{token:r,identity:n}=await this.issueChatToken();this.identity=n,xn.info(`Connecting chat, identity: ${n}, token: ${r}`);const i=new UT.Client(r);i.on("initialized",()=>{xn.info("client: initialized"),this.events.triggerEvent("initialized")}),i.on("tokenAboutToExpire",()=>{xn.info("client: tokenAboutToExpire"),this.refreshToken()}),i.on("tokenExpired",()=>{xn.info("client: tokenExpired"),this.refreshToken()}),this.client=i}async refreshToken(){const{token:r}=await this.issueChatToken();await this.client.updateToken(r)}async join(r){const n=await this.client.getConversationBySid(r);n.status==="joined"?xn.info("already joined conversation:",r):(await n.join(),xn.info("successfully joined conversation:",r)),this.conversation=n}async preview(r){await(await this.conversation.getParticipantByIdentity(this.identity)).updateAttributes({chat_preview:r,chat_preview_updated_at:new Date().toJSON()})}async destroy(){this.conversation=null,this.client&&(await this.client.shutdown(),this.client=null)}async fetchMessages(r){return(await this.conversation.getMessages()).items.map(i=>{const a=R0(i);return r[a.$index]&&(a.file=r[a.$index]),this.trackInTask(a),a})}async sendMessage(r){try{const n=await this.conversation.sendMessage(JSON.stringify(r));return xn.info(`Message sent from ${this.conversation.sid}, index: ${n}`),n}catch(n){xn.warn(`Failed to send a message from ${this.conversation.sid}`,{error:n})}}startTyping(){this.conversation&&this.conversation.typing()}stopTyping(){}registerConversationEvents(){this.registerEvents(this.conversation)}registerEvents(r){r.on("messageAdded",n=>{const i=R0(n);xn.info(`Message added from ${this.conversation.sid}, index: ${i.$index}, sid: ${i.$sid}, timestamp: ${i.$timestamp}, user type: ${i.$userType}`),i.$userType!=="end_user"&&this.ping(),this.trackInTask(i),this.events.triggerEvent("message",i)}),r.on("participantJoined",n=>{xn.info("conversation: memberJoined",n),this.events.triggerEvent("memberJoined",n.identity)}),r.on("participantLeft",n=>{xn.info("conversation: memberLeft",n),this.events.triggerEvent("memberLeft",n.identity)}),r.on("typingStarted",n=>{this.events.triggerEvent("typingStarted",n.identity)}),r.on("typingEnded",n=>{this.events.triggerEvent("typingEnded",n.identity)})}}ht(k$,"type","twilio_conversations");rm(k$);function R0(e){const{index:t,sid:r,author:n,dateCreated:i,body:a}=e,[s,o]=n.split("-");let u=0;o&&(u=parseInt(o,10));const c={$index:t,$sid:r,$timestamp:i,$userType:s,$userId:u};try{const l=JSON.parse(a);return l.message&&!l.type?{...c,...l,type:"message"}:{...c,...l}}catch(l){return xn.warn("Format message failed",{error:l,data:a}),{...c,type:"text",content:a}}}var Tv={exports:{}},Da=rf;function rf(){}rf.mixin=function(e){var t=e.prototype||e;t.isWildEmitter=!0,t.on=function(r,n,i){this.callbacks=this.callbacks||{};var a=arguments.length===3,s=a?arguments[1]:void 0,o=a?arguments[2]:arguments[1];return o._groupName=s,(this.callbacks[r]=this.callbacks[r]||[]).push(o),this},t.once=function(r,n,i){var a=this,s=arguments.length===3,o=s?arguments[1]:void 0,u=s?arguments[2]:arguments[1];function c(){a.off(r,c),u.apply(this,arguments)}return this.on(r,o,c),this},t.releaseGroup=function(r){this.callbacks=this.callbacks||{};var n,i,a,s;for(n in this.callbacks)for(s=this.callbacks[n],i=0,a=s.length;i<a;i++)s[i]._groupName===r&&(s.splice(i,1),i--,a--);return this},t.off=function(r,n){this.callbacks=this.callbacks||{};var i=this.callbacks[r],a;return i?arguments.length===1?(delete this.callbacks[r],this):(a=i.indexOf(n),a!==-1&&(i.splice(a,1),i.length===0&&delete this.callbacks[r]),this):this},t.emit=function(r){this.callbacks=this.callbacks||{};var n=[].slice.call(arguments,1),i=this.callbacks[r],a=this.getWildcardCallbacks(r),s,o,u;if(i)for(u=i.slice(),s=0,o=u.length;s<o&&u[s];++s)u[s].apply(this,n);if(a)for(o=a.length,u=a.slice(),s=0,o=u.length;s<o&&u[s];++s)u[s].apply(this,[r].concat(n));return this},t.getWildcardCallbacks=function(r){this.callbacks=this.callbacks||{};var n,i,a=[];for(n in this.callbacks)i=n.split("*"),(n==="*"||i.length===2&&r.slice(0,i[0].length)===i[0])&&(a=a.concat(this.callbacks[n]));return a}};rf.mixin(rf);var R$={exports:{}};(function(e){(function(t,r){e.exports?e.exports=r():t.prefix=r(t)})(je,function(t){var r=function(l){for(var p=1,v=arguments.length,m;p<v;p++)for(m in arguments[p])Object.prototype.hasOwnProperty.call(arguments[p],m)&&(l[m]=arguments[p][m]);return l},n={template:"[%t] %l:",levelFormatter:function(l){return l.toUpperCase()},nameFormatter:function(l){return l||"root"},timestampFormatter:function(l){return l.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")},format:void 0},i,a={},s=function(l){if(!l||!l.getLogger)throw new TypeError("Argument is not a root logger");i=l},o=function(l,p){if(!l||!l.setLevel)throw new TypeError("Argument is not a logger");var v=l.methodFactory,m=l.name||"",b=a[m]||a[""]||n;function T(I,R,x){var N=v(I,R,x),j=a[x]||a[""],X=j.template.indexOf("%t")!==-1,J=j.template.indexOf("%l")!==-1,V=j.template.indexOf("%n")!==-1;return function(){for(var D="",te=arguments.length,ue=Array(te),ee=0;ee<te;ee++)ue[ee]=arguments[ee];if(m||!a[x]){var ge=j.timestampFormatter(new Date),L=j.levelFormatter(I),pe=j.nameFormatter(x);j.format?D+=j.format(L,pe,ge):(D+=j.template,X&&(D=D.replace(/%t/,ge)),J&&(D=D.replace(/%l/,L)),V&&(D=D.replace(/%n/,pe))),ue.length&&typeof ue[0]=="string"?ue[0]=D+" "+ue[0]:ue.unshift(D)}N.apply(void 0,ue)}}return a[m]||(l.methodFactory=T),p=p||{},p.template&&(p.format=void 0),a[m]=r({},b,p),l.setLevel(l.getLevel()),i||l.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"),l},u={reg:s,apply:o},c;return t&&(c=t.prefix,u.noConflict=function(){return t.prefix===u&&(t.prefix=c),u}),u})})(R$);var kQ=R$.exports,Cv={exports:{}},RQ={"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"},"error:input:unsanitized":{type:"error:input:unsanitized",description:"Input is not sanitized"}};(function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.NexmoApiError=t.NexmoClientError=void 0;const r=RQ,n=Ar;function i(o,u){var c,l;u!=null&&u.code&&(u.type=u.code,delete u.code),Object.assign(o,u),o.message="type: "+o.type+", description: "+((l=(c=o.description)!==null&&c!==void 0?c:o.detail)!==null&&l!==void 0?l:"")}class a{constructor(u){const c=r[u];c?i(this,c):(this.message=u&&u.message?u.message:u,this.stack=u.stack),this.log=n.getLogger(this.constructor.name),this.log.error(this),this.name="NexmoClientError",typeof je.NXMbugsnagClient<"u"&&je.NXMbugsnagClient.notify(this,{severity:"info"})}}t.NexmoClientError=a;class s{constructor(u){this.log=n.getLogger(this.constructor.name),u?i(this,u):(this.message=u&&u.message?u.message:u,this.stack=u&&u.stack?u.stack:new Error().stack),this.name="NexmoApiError",this.log=n.getLogger(this.constructor.name),this.log.error(this),typeof je.NXMbugsnagClient<"u"&&je.NXMbugsnagClient.notify(this,{severity:"info"})}}t.NexmoApiError=s,e.exports={NexmoClientError:a,NexmoApiError:s}})(Cv,Cv.exports);var Gn=Cv.exports,Ev={exports:{}},Gg={},Gf={},zi={},Xu={},yi={},Qu={},Ki={},To={},Zu={},bi={};Object.defineProperty(bi,"__esModule",{value:!0});bi.ERROR_PACKET=bi.PACKET_TYPES_REVERSE=bi.PACKET_TYPES=void 0;const _i=Object.create(null);bi.PACKET_TYPES=_i;_i.open="0";_i.close="1";_i.ping="2";_i.pong="3";_i.message="4";_i.upgrade="5";_i.noop="6";const $$=Object.create(null);bi.PACKET_TYPES_REVERSE=$$;Object.keys(_i).forEach(e=>{$$[_i[e]]=e});const $Q={type:"error",data:"parser error"};bi.ERROR_PACKET=$Q;Object.defineProperty(Zu,"__esModule",{value:!0});Zu.encodePacket=void 0;Zu.encodePacketToBinary=OQ;const IQ=bi,I$=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",O$=typeof ArrayBuffer=="function",A$=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,P$=({type:e,data:t},r,n)=>I$&&t instanceof Blob?r?n(t):$0(t,n):O$&&(t instanceof ArrayBuffer||A$(t))?r?n(t):$0(new Blob([t]),n):n(IQ.PACKET_TYPES[e]+(t||""));Zu.encodePacket=P$;const $0=(e,t)=>{const r=new FileReader;return r.onload=function(){const n=r.result.split(",")[1];t("b"+(n||""))},r.readAsDataURL(e)};function I0(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let ah;function OQ(e,t){if(I$&&e.data instanceof Blob)return e.data.arrayBuffer().then(I0).then(t);if(O$&&(e.data instanceof ArrayBuffer||A$(e.data)))return t(I0(e.data));P$(e,!1,r=>{ah||(ah=new TextEncoder),t(ah.encode(r))})}var Hf={},lo={};Object.defineProperty(lo,"__esModule",{value:!0});lo.decode=lo.encode=void 0;const zs="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",tu=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e<zs.length;e++)tu[zs.charCodeAt(e)]=e;const AQ=e=>{let t=new Uint8Array(e),r,n=t.length,i="";for(r=0;r<n;r+=3)i+=zs[t[r]>>2],i+=zs[(t[r]&3)<<4|t[r+1]>>4],i+=zs[(t[r+1]&15)<<2|t[r+2]>>6],i+=zs[t[r+2]&63];return n%3===2?i=i.substring(0,i.length-1)+"=":n%3===1&&(i=i.substring(0,i.length-2)+"=="),i};lo.encode=AQ;const PQ=e=>{let t=e.length*.75,r=e.length,n,i=0,a,s,o,u;e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);const c=new ArrayBuffer(t),l=new Uint8Array(c);for(n=0;n<r;n+=4)a=tu[e.charCodeAt(n)],s=tu[e.charCodeAt(n+1)],o=tu[e.charCodeAt(n+2)],u=tu[e.charCodeAt(n+3)],l[i++]=a<<2|s>>4,l[i++]=(s&15)<<4|o>>2,l[i++]=(o&3)<<6|u&63;return c};lo.decode=PQ;Object.defineProperty(Hf,"__esModule",{value:!0});Hf.decodePacket=void 0;const Kc=bi,MQ=lo,xQ=typeof ArrayBuffer=="function",NQ=(e,t)=>{if(typeof e!="string")return{type:"message",data:M$(e,t)};const r=e.charAt(0);return r==="b"?{type:"message",data:LQ(e.substring(1),t)}:Kc.PACKET_TYPES_REVERSE[r]?e.length>1?{type:Kc.PACKET_TYPES_REVERSE[r],data:e.substring(1)}:{type:Kc.PACKET_TYPES_REVERSE[r]}:Kc.ERROR_PACKET};Hf.decodePacket=NQ;const LQ=(e,t)=>{if(xQ){const r=(0,MQ.decode)(e);return M$(r,t)}else return{base64:!0,data:e}},M$=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.decodePayload=e.decodePacket=e.encodePayload=e.encodePacket=e.protocol=void 0,e.createPacketEncoderStream=o,e.createPacketDecoderStream=p;const t=Zu;Object.defineProperty(e,"encodePacket",{enumerable:!0,get:function(){return t.encodePacket}});const r=Hf;Object.defineProperty(e,"decodePacket",{enumerable:!0,get:function(){return r.decodePacket}});const n=bi,i="",a=(v,m)=>{const b=v.length,T=new Array(b);let I=0;v.forEach((R,x)=>{(0,t.encodePacket)(R,!1,N=>{T[x]=N,++I===b&&m(T.join(i))})})};e.encodePayload=a;const s=(v,m)=>{const b=v.split(i),T=[];for(let I=0;I<b.length;I++){const R=(0,r.decodePacket)(b[I],m);if(T.push(R),R.type==="error")break}return T};e.decodePayload=s;function o(){return new TransformStream({transform(v,m){(0,t.encodePacketToBinary)(v,b=>{const T=b.length;let I;if(T<126)I=new Uint8Array(1),new DataView(I.buffer).setUint8(0,T);else if(T<65536){I=new Uint8Array(3);const R=new DataView(I.buffer);R.setUint8(0,126),R.setUint16(1,T)}else{I=new Uint8Array(9);const R=new DataView(I.buffer);R.setUint8(0,127),R.setBigUint64(1,BigInt(T))}v.data&&typeof v.data!="string"&&(I[0]|=128),m.enqueue(I),m.enqueue(b)})}})}let u;function c(v){return v.reduce((m,b)=>m+b.length,0)}function l(v,m){if(v[0].length===m)return v.shift();const b=new Uint8Array(m);let T=0;for(let I=0;I<m;I++)b[I]=v[0][T++],T===v[0].length&&(v.shift(),T=0);return v.length&&T<v[0].length&&(v[0]=v[0].slice(T)),b}function p(v,m){u||(u=new TextDecoder);const b=[];let T=0,I=-1,R=!1;return new TransformStream({transform(x,N){for(b.push(x);;){if(T===0){if(c(b)<1)break;const j=l(b,1);R=(j[0]&128)===128,I=j[0]&127,I<126?T=3:I===126?T=1:T=2}else if(T===1){if(c(b)<2)break;const j=l(b,2);I=new DataView(j.buffer,j.byteOffset,j.length).getUint16(0),T=3}else if(T===2){if(c(b)<8)break;const j=l(b,8),X=new DataView(j.buffer,j.byteOffset,j.length),J=X.getUint32(0);if(J>Math.pow(2,21)-1){N.enqueue(n.ERROR_PACKET);break}I=J*Math.pow(2,32)+X.getUint32(4),T=3}else{if(c(b)<I)break;const j=l(b,I);N.enqueue((0,r.decodePacket)(R?j:u.decode(j),m)),T=0}if(I===0||I>v){N.enqueue(n.ERROR_PACKET);break}}}})}e.protocol=4})(To);function en(e){if(e)return DQ(e)}function DQ(e){for(var t in en.prototype)e[t]=en.prototype[t];return e}en.prototype.on=en.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};en.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this};en.prototype.off=en.prototype.removeListener=en.prototype.removeAllListeners=en.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var r=this._callbacks["$"+e];if(!r)return this;if(arguments.length==1)return delete this._callbacks["$"+e],this;for(var n,i=0;i<r.length;i++)if(n=r[i],n===t||n.fn===t){r.splice(i,1);break}return r.length===0&&delete this._callbacks["$"+e],this};en.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),r=this._callbacks["$"+e],n=1;n<arguments.length;n++)t[n-1]=arguments[n];if(r){r=r.slice(0);for(var n=0,i=r.length;n<i;++n)r[n].apply(this,t)}return this};en.prototype.emitReserved=en.prototype.emit;en.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]};en.prototype.hasListeners=function(e){return!!this.listeners(e).length};const jQ=Object.freeze(Object.defineProperty({__proto__:null,Emitter:en},Symbol.toStringTag,{value:"Module"})),Co=FT(jQ);var oi={},pn={};Object.defineProperty(pn,"__esModule",{value:!0});pn.defaultBinaryType=pn.globalThisShim=pn.nextTick=void 0;pn.createCookieJar=FQ;pn.nextTick=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,r)=>r(t,0);pn.globalThisShim=typeof self<"u"?self:typeof window<"u"?window:Function("return this")();pn.defaultBinaryType="arraybuffer";function FQ(){}Object.defineProperty(oi,"__esModule",{value:!0});oi.pick=UQ;oi.installTimerFunctions=zQ;oi.byteLength=GQ;oi.randomString=VQ;const va=pn;function UQ(e,...t){return t.reduce((r,n)=>(e.hasOwnProperty(n)&&(r[n]=e[n]),r),{})}const BQ=va.globalThisShim.setTimeout,qQ=va.globalThisShim.clearTimeout;function zQ(e,t){t.useNativeTimers?(e.setTimeoutFn=BQ.bind(va.globalThisShim),e.clearTimeoutFn=qQ.bind(va.globalThisShim)):(e.setTimeoutFn=va.globalThisShim.setTimeout.bind(va.globalThisShim),e.clearTimeoutFn=va.globalThisShim.clearTimeout.bind(va.globalThisShim))}const WQ=1.33;function GQ(e){return typeof e=="string"?HQ(e):Math.ceil((e.byteLength||e.size)*WQ)}function HQ(e){let t=0,r=0;for(let n=0,i=e.length;n<i;n++)t=e.charCodeAt(n),t<128?r+=1:t<2048?r+=2:t<55296||t>=57344?r+=3:(n++,r+=4);return r}function VQ(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}var ec={};Object.defineProperty(ec,"__esModule",{value:!0});ec.encode=KQ;ec.decode=JQ;function KQ(e){let t="";for(let r in e)e.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(e[r]));return t}function JQ(e){let t={},r=e.split("&");for(let n=0,i=r.length;n<i;n++){let a=r[n].split("=");t[decodeURIComponent(a[0])]=decodeURIComponent(a[1])}return t}var kv={exports:{}},sh,O0;function YQ(){if(O0)return sh;O0=1;var e=1e3,t=e*60,r=t*60,n=r*24,i=n*7,a=n*365.25;sh=function(l,p){p=p||{};var v=typeof l;if(v==="string"&&l.length>0)return s(l);if(v==="number"&&isFinite(l))return p.long?u(l):o(l);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(l))};function s(l){if(l=String(l),!(l.length>100)){var p=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(l);if(p){var v=parseFloat(p[1]),m=(p[2]||"ms").toLowerCase();switch(m){case"years":case"year":case"yrs":case"yr":case"y":return v*a;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*r;case"minutes":case"minute":case"mins":case"min":case"m":return v*t;case"seconds":case"second":case"secs":case"sec":case"s":return v*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return v;default:return}}}}function o(l){var p=Math.abs(l);return p>=n?Math.round(l/n)+"d":p>=r?Math.round(l/r)+"h":p>=t?Math.round(l/t)+"m":p>=e?Math.round(l/e)+"s":l+"ms"}function u(l){var p=Math.abs(l);return p>=n?c(l,p,n,"day"):p>=r?c(l,p,r,"hour"):p>=t?c(l,p,t,"minute"):p>=e?c(l,p,e,"second"):l+" ms"}function c(l,p,v,m){var b=p>=v*1.5;return Math.round(l/v)+" "+m+(b?"s":"")}return sh}function XQ(e){r.debug=r,r.default=r,r.coerce=u,r.disable=a,r.enable=i,r.enabled=s,r.humanize=YQ(),r.destroy=c,Object.keys(e).forEach(l=>{r[l]=e[l]}),r.names=[],r.skips=[],r.formatters={};function t(l){let p=0;for(let v=0;v<l.length;v++)p=(p<<5)-p+l.charCodeAt(v),p|=0;return r.colors[Math.abs(p)%r.colors.length]}r.selectColor=t;function r(l){let p,v=null,m,b;function T(...I){if(!T.enabled)return;const R=T,x=Number(new Date),N=x-(p||x);R.diff=N,R.prev=p,R.curr=x,p=x,I[0]=r.coerce(I[0]),typeof I[0]!="string"&&I.unshift("%O");let j=0;I[0]=I[0].replace(/%([a-zA-Z%])/g,(J,V)=>{if(J==="%%")return"%";j++;const D=r.formatters[V];if(typeof D=="function"){const te=I[j];J=D.call(R,te),I.splice(j,1),j--}return J}),r.formatArgs.call(R,I),(R.log||r.log).apply(R,I)}return T.namespace=l,T.useColors=r.useColors(),T.color=r.selectColor(l),T.extend=n,T.destroy=r.destroy,Object.defineProperty(T,"enabled",{enumerable:!0,configurable:!1,get:()=>v!==null?v:(m!==r.namespaces&&(m=r.namespaces,b=r.enabled(l)),b),set:I=>{v=I}}),typeof r.init=="function"&&r.init(T),T}function n(l,p){const v=r(this.namespace+(typeof p>"u"?":":p)+l);return v.log=this.log,v}function i(l){r.save(l),r.namespaces=l,r.names=[],r.skips=[];let p;const v=(typeof l=="string"?l:"").split(/[\s,]+/),m=v.length;for(p=0;p<m;p++)v[p]&&(l=v[p].replace(/\*/g,".*?"),l[0]==="-"?r.skips.push(new RegExp("^"+l.slice(1)+"$")):r.names.push(new RegExp("^"+l+"$")))}function a(){const l=[...r.names.map(o),...r.skips.map(o).map(p=>"-"+p)].join(",");return r.enable(""),l}function s(l){if(l[l.length-1]==="*")return!0;let p,v;for(p=0,v=r.skips.length;p<v;p++)if(r.skips[p].test(l))return!1;for(p=0,v=r.names.length;p<v;p++)if(r.names[p].test(l))return!0;return!1}function o(l){return l.toString().substring(2,l.toString().length-2).replace(/\.\*\?$/,"*")}function u(l){return l instanceof Error?l.stack||l.message:l}function c(){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 r.enable(r.load()),r}var QQ=XQ;(function(e,t){t.formatArgs=n,t.save=i,t.load=a,t.useColors=r,t.storage=s(),t.destroy=(()=>{let u=!1;return()=>{u||(u=!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`."))}})(),t.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 r(){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 u;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&&(u=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(u[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function n(u){if(u[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+u[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const c="color: "+this.color;u.splice(1,0,c,"color: inherit");let l=0,p=0;u[0].replace(/%[a-zA-Z%]/g,v=>{v!=="%%"&&(l++,v==="%c"&&(p=l))}),u.splice(p,0,c)}t.log=console.debug||console.log||(()=>{});function i(u){try{u?t.storage.setItem("debug",u):t.storage.removeItem("debug")}catch{}}function a(){let u;try{u=t.storage.getItem("debug")}catch{}return!u&&typeof process<"u"&&"env"in process&&(u=process.env.DEBUG),u}function s(){try{return localStorage}catch{}}e.exports=QQ(t);const{formatters:o}=e.exports;o.j=function(u){try{return JSON.stringify(u)}catch(c){return"[UnexpectedJSONParseError]: "+c.message}}})(kv,kv.exports);var ui=kv.exports,ZQ=je&&je.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Ki,"__esModule",{value:!0});Ki.Transport=Ki.TransportError=void 0;const eZ=To,tZ=Co,rZ=oi,nZ=ec,iZ=ZQ(ui),aZ=(0,iZ.default)("engine.io-client:transport");class x$ extends Error{constructor(t,r,n){super(t),this.description=r,this.context=n,this.type="TransportError"}}Ki.TransportError=x$;class sZ extends tZ.Emitter{constructor(t){super(),this.writable=!1,(0,rZ.installTimerFunctions)(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,r,n){return super.emitReserved("error",new x$(t,r,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(t){this.readyState==="open"?this.write(t):aZ("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const r=(0,eZ.decodePacket)(t,this.socket.binaryType);this.onPacket(r)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,r={}){return t+"://"+this._hostname()+this._port()+this.opts.path+this._query(r)}_hostname(){const t=this.opts.hostname;return t.indexOf(":")===-1?t:"["+t+"]"}_port(){return this.opts.port&&(this.opts.secure&&+(this.opts.port!==443)||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(t){const r=(0,nZ.encode)(t);return r.length?"?"+r:""}}Ki.Transport=sZ;var oZ=je&&je.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Qu,"__esModule",{value:!0});Qu.Polling=void 0;const uZ=Ki,cZ=oi,A0=To,lZ=oZ(ui),Kn=(0,lZ.default)("engine.io-client:polling");class fZ extends uZ.Transport{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(t){this.readyState="pausing";const r=()=>{Kn("paused"),this.readyState="paused",t()};if(this._polling||!this.writable){let n=0;this._polling&&(Kn("we are currently polling - waiting to pause"),n++,this.once("pollComplete",function(){Kn("pre-pause polling complete"),--n||r()})),this.writable||(Kn("we are currently writing - waiting to pause"),n++,this.once("drain",function(){Kn("pre-pause writing complete"),--n||r()}))}else r()}_poll(){Kn("polling"),this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){Kn("polling got data %s",t);const r=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,A0.decodePayload)(t,this.socket.binaryType).forEach(r),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"?this._poll():Kn('ignoring poll - transport state "%s"',this.readyState))}doClose(){const t=()=>{Kn("writing close packet"),this.write([{type:"close"}])};this.readyState==="open"?(Kn("transport open - closing"),t()):(Kn("transport not open - deferring close"),this.once("open",t))}write(t){this.writable=!1,(0,A0.encodePayload)(t,r=>{this.doWrite(r,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",r=this.query||{};return this.opts.timestampRequests!==!1&&(r[this.opts.timestampParam]=(0,cZ.randomString)()),!this.supportsBinary&&!r.sid&&(r.b64=1),this.createUri(t,r)}}Qu.Polling=fZ;var Vf={};Object.defineProperty(Vf,"__esModule",{value:!0});Vf.hasCORS=void 0;let N$=!1;try{N$=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}Vf.hasCORS=N$;var dZ=je&&je.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(yi,"__esModule",{value:!0});yi.XHR=yi.Request=yi.BaseXHR=void 0;const pZ=Qu,hZ=Co,P0=oi,L$=pn,vZ=Vf,mZ=dZ(ui),Rv=(0,mZ.default)("engine.io-client:polling");function gZ(){}class D$ extends pZ.Polling{constructor(t){if(super(t),typeof location<"u"){const r=location.protocol==="https:";let n=location.port;n||(n=r?"443":"80"),this.xd=typeof location<"u"&&t.hostname!==location.hostname||n!==t.port}}doWrite(t,r){const n=this.request({method:"POST",data:t});n.on("success",r),n.on("error",(i,a)=>{this.onError("xhr post error",i,a)})}doPoll(){Rv("xhr poll");const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(r,n)=>{this.onError("xhr poll error",r,n)}),this.pollXhr=t}}yi.BaseXHR=D$;class ni extends hZ.Emitter{constructor(t,r,n){super(),this.createRequest=t,(0,P0.installTimerFunctions)(this,n),this._opts=n,this._method=n.method||"GET",this._uri=r,this._data=n.data!==void 0?n.data:null,this._create()}_create(){var t;const r=(0,P0.pick)(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");r.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(r);try{Rv("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{}(t=this._opts.cookieJar)===null||t===void 0||t.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))},Rv("xhr data %s",this._data),n.send(this._data)}catch(i){this.setTimeoutFn(()=>{this._onError(i)},0);return}typeof document<"u"&&(this._index=ni.requestsCount++,ni.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=gZ,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete ni.requests[this._index],this._xhr=null}}_onLoad(){const t=this._xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}yi.Request=ni;ni.requestsCount=0;ni.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",M0);else if(typeof addEventListener=="function"){const e="onpagehide"in L$.globalThisShim?"pagehide":"unload";addEventListener(e,M0,!1)}}function M0(){for(let e in ni.requests)ni.requests.hasOwnProperty(e)&&ni.requests[e].abort()}const yZ=function(){const e=j$({xdomain:!1});return e&&e.responseType!==null}();class bZ extends D${constructor(t){super(t);const r=t&&t.forceBase64;this.supportsBinary=yZ&&!r}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new ni(j$,this.uri(),t)}}yi.XHR=bZ;function j$(e){const t=e.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||vZ.hasCORS))return new XMLHttpRequest}catch{}if(!t)try{return new L$.globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}var Ra={},_Z=je&&je.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Ra,"__esModule",{value:!0});Ra.WS=Ra.BaseWS=void 0;const wZ=Ki,x0=oi,SZ=To,$v=pn,TZ=_Z(ui),CZ=(0,TZ.default)("engine.io-client:websocket"),F$=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class U$ extends wZ.Transport{get name(){return"websocket"}doOpen(){const t=this.uri(),r=this.opts.protocols,n=F$?{}:(0,x0.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(t,r,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=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let r=0;r<t.length;r++){const n=t[r],i=r===t.length-1;(0,SZ.encodePacket)(n,this.supportsBinary,a=>{try{this.doWrite(n,a)}catch{CZ("websocket closed before onclose event")}i&&(0,$v.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 t=this.opts.secure?"wss":"ws",r=this.query||{};return this.opts.timestampRequests&&(r[this.opts.timestampParam]=(0,x0.randomString)()),this.supportsBinary||(r.b64=1),this.createUri(t,r)}}Ra.BaseWS=U$;const oh=$v.globalThisShim.WebSocket||$v.globalThisShim.MozWebSocket;class EZ extends U${createSocket(t,r,n){return F$?new oh(t,r,n):r?new oh(t,r):new oh(t)}doWrite(t,r){this.ws.send(r)}}Ra.WS=EZ;var tc={},kZ=je&&je.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(tc,"__esModule",{value:!0});tc.WT=void 0;const RZ=Ki,$Z=pn,N0=To,IZ=kZ(ui),Ko=(0,IZ.default)("engine.io-client:webtransport");class OZ extends RZ.Transport{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this._transport.closed.then(()=>{Ko("transport closed gracefully"),this.onClose()}).catch(t=>{Ko("transport closed due to %s",t),this.onError("webtransport error",t)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(t=>{const r=(0,N0.createPacketDecoderStream)(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=t.readable.pipeThrough(r).getReader(),i=(0,N0.createPacketEncoderStream)();i.readable.pipeTo(t.writable),this._writer=i.writable.getWriter();const a=()=>{n.read().then(({done:o,value:u})=>{if(o){Ko("session is closed");return}Ko("received chunk: %o",u),this.onPacket(u),a()}).catch(o=>{Ko("an error occurred while reading: %s",o)})};a();const s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this._writer.write(s).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let r=0;r<t.length;r++){const n=t[r],i=r===t.length-1;this._writer.write(n).then(()=>{i&&(0,$Z.nextTick)(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}}tc.WT=OZ;Object.defineProperty(Xu,"__esModule",{value:!0});Xu.transports=void 0;const AZ=yi,PZ=Ra,MZ=tc;Xu.transports={websocket:PZ.WS,webtransport:MZ.WT,polling:AZ.XHR};var Kf={};Object.defineProperty(Kf,"__esModule",{value:!0});Kf.parse=LZ;const xZ=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,NZ=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function LZ(e){if(e.length>8e3)throw"URI too long";const t=e,r=e.indexOf("["),n=e.indexOf("]");r!=-1&&n!=-1&&(e=e.substring(0,r)+e.substring(r,n).replace(/:/g,";")+e.substring(n,e.length));let i=xZ.exec(e||""),a={},s=14;for(;s--;)a[NZ[s]]=i[s]||"";return r!=-1&&n!=-1&&(a.source=t,a.host=a.host.substring(1,a.host.length-1).replace(/;/g,":"),a.authority=a.authority.replace("[","").replace("]","").replace(/;/g,":"),a.ipv6uri=!0),a.pathNames=DZ(a,a.path),a.queryKey=jZ(a,a.query),a}function DZ(e,t){const r=/\/{2,9}/g,n=t.replace(r,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&n.splice(0,1),t.slice(-1)=="/"&&n.splice(n.length-1,1),n}function jZ(e,t){const r={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,i,a){i&&(r[i]=a)}),r}var FZ=je&&je.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(zi,"__esModule",{value:!0});zi.Socket=zi.SocketWithUpgrade=zi.SocketWithoutUpgrade=void 0;const UZ=Xu,L0=oi,BZ=ec,D0=Kf,qZ=Co,B$=To,uh=pn,zZ=FZ(ui),rr=(0,zZ.default)("engine.io-client:socket"),Iv=typeof addEventListener=="function"&&typeof removeEventListener=="function",lu=[];Iv&&addEventListener("offline",()=>{rr("closing %d connection(s) because the network was lost",lu.length),lu.forEach(e=>e())},!1);class Wi extends qZ.Emitter{constructor(t,r){if(super(),this.binaryType=uh.defaultBinaryType,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,t&&typeof t=="object"&&(r=t,t=null),t){const n=(0,D0.parse)(t);r.hostname=n.host,r.secure=n.protocol==="https"||n.protocol==="wss",r.port=n.port,n.query&&(r.query=n.query)}else r.host&&(r.hostname=(0,D0.parse)(r.host).host);(0,L0.installTimerFunctions)(this,r),this.secure=r.secure!=null?r.secure:typeof location<"u"&&location.protocol==="https:",r.hostname&&!r.port&&(r.port=this.secure?"443":"80"),this.hostname=r.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=r.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},r.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},r),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=(0,BZ.decode)(this.opts.query)),Iv&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(rr("adding listener for the 'offline' event"),this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},lu.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=(0,uh.createCookieJar)()),this._open()}createTransport(t){rr('creating transport "%s"',t);const r=Object.assign({},this.opts.query);r.EIO=B$.protocol,r.transport=t,this.id&&(r.sid=this.id);const n=Object.assign({},this.opts,{query:r,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return rr("options: %j",n),new this._transportsByName[t](n)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const t=this.opts.rememberUpgrade&&Wi.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const r=this.createTransport(t);r.open(),this.setTransport(r)}setTransport(t){rr("setting transport %s",t.name),this.transport&&(rr("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",r=>this._onClose("transport close",r))}onOpen(){rr("socket open"),this.readyState="open",Wi.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(rr('socket receive: type "%s", data "%s"',t.type,t.data),this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const r=new Error("server error");r.code=t.data,this._onError(r);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data);break}else rr('packet received with socket readyState "%s"',this.readyState)}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),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 t=this._getWritablePackets();rr("flushing %d packets in socket",t.length),this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let r=1;for(let n=0;n<this.writeBuffer.length;n++){const i=this.writeBuffer[n].data;if(i&&(r+=(0,L0.byteLength)(i)),n>0&&r>this._maxPayload)return rr("only send %d out of %d packets",n,this.writeBuffer.length),this.writeBuffer.slice(0,n);r+=2}return rr("payload size is %d (max: %d)",r,this._maxPayload),this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const t=Date.now()>this._pingTimeoutTime;return t&&(rr("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,(0,uh.nextTick)(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,r,n){return this._sendPacket("message",t,r,n),this}send(t,r,n){return this._sendPacket("message",t,r,n),this}_sendPacket(t,r,n,i){if(typeof r=="function"&&(i=r,r=void 0),typeof n=="function"&&(i=n,n=null),this.readyState==="closing"||this.readyState==="closed")return;n=n||{},n.compress=n.compress!==!1;const a={type:t,data:r,options:n};this.emitReserved("packetCreate",a),this.writeBuffer.push(a),i&&this.once("flush",i),this.flush()}close(){const t=()=>{this._onClose("forced close"),rr("socket closing - telling transport to close"),this.transport.close()},r=()=>{this.off("upgrade",r),this.off("upgradeError",r),t()},n=()=>{this.once("upgrade",r),this.once("upgradeError",r)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():t()}):this.upgrading?n():t()),this}_onError(t){if(rr("socket error %j",t),Wi.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return rr("trying next transport"),this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,r){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(rr('socket close with reason: "%s"',t),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Iv&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const n=lu.indexOf(this._offlineEventListener);n!==-1&&(rr("removing listener for the 'offline' event"),lu.splice(n,1))}this.readyState="closed",this.id=null,this.emitReserved("close",t,r),this.writeBuffer=[],this._prevBufferLen=0}}}zi.SocketWithoutUpgrade=Wi;Wi.protocol=B$.protocol;class q$ extends Wi{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){rr("starting upgrade probes");for(let t=0;t<this._upgrades.length;t++)this._probe(this._upgrades[t])}}_probe(t){rr('probing transport "%s"',t);let r=this.createTransport(t),n=!1;Wi.priorWebsocketSuccess=!1;const i=()=>{n||(rr('probe transport "%s" opened',t),r.send([{type:"ping",data:"probe"}]),r.once("packet",p=>{if(!n)if(p.type==="pong"&&p.data==="probe"){if(rr('probe transport "%s" pong',t),this.upgrading=!0,this.emitReserved("upgrading",r),!r)return;Wi.priorWebsocketSuccess=r.name==="websocket",rr('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{n||this.readyState!=="closed"&&(rr("changing transport and sending upgrade packet"),l(),this.setTransport(r),r.send([{type:"upgrade"}]),this.emitReserved("upgrade",r),r=null,this.upgrading=!1,this.flush())})}else{rr('probe transport "%s" failed',t);const v=new Error("probe error");v.transport=r.name,this.emitReserved("upgradeError",v)}}))};function a(){n||(n=!0,l(),r.close(),r=null)}const s=p=>{const v=new Error("probe error: "+p);v.transport=r.name,a(),rr('probe transport "%s" failed because of error: %s',t,p),this.emitReserved("upgradeError",v)};function o(){s("transport closed")}function u(){s("socket closed")}function c(p){r&&p.name!==r.name&&(rr('"%s" works - aborting "%s"',p.name,r.name),a())}const l=()=>{r.removeListener("open",i),r.removeListener("error",s),r.removeListener("close",o),this.off("close",u),this.off("upgrading",c)};r.once("open",i),r.once("error",s),r.once("close",o),this.once("close",u),this.once("upgrading",c),this._upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{n||r.open()},200):r.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const r=[];for(let n=0;n<t.length;n++)~this.transports.indexOf(t[n])&&r.push(t[n]);return r}}zi.SocketWithUpgrade=q$;let WZ=class extends q${constructor(t,r={}){const n=typeof t=="object"?t:r;(!n.transports||n.transports&&typeof n.transports[0]=="string")&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(i=>UZ.transports[i]).filter(i=>!!i)),super(t,n)}};zi.Socket=WZ;var Jf={};Object.defineProperty(Jf,"__esModule",{value:!0});Jf.Fetch=void 0;const GZ=Qu;class HZ extends GZ.Polling{doPoll(){this._fetch().then(t=>{if(!t.ok)return this.onError("fetch read error",t.status,t);t.text().then(r=>this.onData(r))}).catch(t=>{this.onError("fetch read error",t)})}doWrite(t,r){this._fetch(t).then(n=>{if(!n.ok)return this.onError("fetch write error",n.status,n);r()}).catch(n=>{this.onError("fetch write error",n)})}_fetch(t){var r;const n=t!==void 0,i=new Headers(this.opts.extraHeaders);return n&&i.set("content-type","text/plain;charset=UTF-8"),(r=this.socket._cookieJar)===null||r===void 0||r.appendCookies(i),fetch(this.uri(),{method:n?"POST":"GET",body:n?t:null,headers:i,credentials:this.opts.withCredentials?"include":"omit"}).then(a=>{var s;return(s=this.socket._cookieJar)===null||s===void 0||s.parseCookies(a.headers.getSetCookie()),a})}}Jf.Fetch=HZ;(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.WebTransport=e.WebSocket=e.NodeWebSocket=e.XHR=e.NodeXHR=e.Fetch=e.nextTick=e.parse=e.installTimerFunctions=e.transports=e.TransportError=e.Transport=e.protocol=e.SocketWithUpgrade=e.SocketWithoutUpgrade=e.Socket=void 0;const t=zi;Object.defineProperty(e,"Socket",{enumerable:!0,get:function(){return t.Socket}});var r=zi;Object.defineProperty(e,"SocketWithoutUpgrade",{enumerable:!0,get:function(){return r.SocketWithoutUpgrade}}),Object.defineProperty(e,"SocketWithUpgrade",{enumerable:!0,get:function(){return r.SocketWithUpgrade}}),e.protocol=t.Socket.protocol;var n=Ki;Object.defineProperty(e,"Transport",{enumerable:!0,get:function(){return n.Transport}}),Object.defineProperty(e,"TransportError",{enumerable:!0,get:function(){return n.TransportError}});var i=Xu;Object.defineProperty(e,"transports",{enumerable:!0,get:function(){return i.transports}});var a=oi;Object.defineProperty(e,"installTimerFunctions",{enumerable:!0,get:function(){return a.installTimerFunctions}});var s=Kf;Object.defineProperty(e,"parse",{enumerable:!0,get:function(){return s.parse}});var o=pn;Object.defineProperty(e,"nextTick",{enumerable:!0,get:function(){return o.nextTick}});var u=Jf;Object.defineProperty(e,"Fetch",{enumerable:!0,get:function(){return u.Fetch}});var c=yi;Object.defineProperty(e,"NodeXHR",{enumerable:!0,get:function(){return c.XHR}});var l=yi;Object.defineProperty(e,"XHR",{enumerable:!0,get:function(){return l.XHR}});var p=Ra;Object.defineProperty(e,"NodeWebSocket",{enumerable:!0,get:function(){return p.WS}});var v=Ra;Object.defineProperty(e,"WebSocket",{enumerable:!0,get:function(){return v.WS}});var m=tc;Object.defineProperty(e,"WebTransport",{enumerable:!0,get:function(){return m.WT}})})(Gf);var VZ=je&&je.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Gg,"__esModule",{value:!0});Gg.url=YZ;const KZ=Gf,JZ=VZ(ui),j0=(0,JZ.default)("socket.io-client:url");function YZ(e,t="",r){let n=e;r=r||typeof location<"u"&&location,e==null&&(e=r.protocol+"//"+r.host),typeof e=="string"&&(e.charAt(0)==="/"&&(e.charAt(1)==="/"?e=r.protocol+e:e=r.host+e),/^(https?|wss?):\/\//.test(e)||(j0("protocol-less url %s",e),typeof r<"u"?e=r.protocol+"//"+e:e="https://"+e),j0("parse %s",e),n=(0,KZ.parse)(e)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const a=n.host.indexOf(":")!==-1?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+a+":"+n.port+t,n.href=n.protocol+"://"+a+(r&&r.port===n.port?"":":"+n.port),n}var Yf={},rc={},Xf={},fo={},cs={};Object.defineProperty(cs,"__esModule",{value:!0});cs.hasBinary=cs.isBinary=void 0;const XZ=typeof ArrayBuffer=="function",QZ=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,z$=Object.prototype.toString,ZZ=typeof Blob=="function"||typeof Blob<"u"&&z$.call(Blob)==="[object BlobConstructor]",eee=typeof File=="function"||typeof File<"u"&&z$.call(File)==="[object FileConstructor]";function W$(e){return XZ&&(e instanceof ArrayBuffer||QZ(e))||ZZ&&e instanceof Blob||eee&&e instanceof File}cs.isBinary=W$;function Tl(e,t){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let r=0,n=e.length;r<n;r++)if(Tl(e[r]))return!0;return!1}if(W$(e))return!0;if(e.toJSON&&typeof e.toJSON=="function"&&arguments.length===1)return Tl(e.toJSON(),!0);for(const r in e)if(Object.prototype.hasOwnProperty.call(e,r)&&Tl(e[r]))return!0;return!1}cs.hasBinary=Tl;Object.defineProperty(fo,"__esModule",{value:!0});fo.reconstructPacket=fo.deconstructPacket=void 0;const tee=cs;function ree(e){const t=[],r=e.data,n=e;return n.data=Ov(r,t),n.attachments=t.length,{packet:n,buffers:t}}fo.deconstructPacket=ree;function Ov(e,t){if(!e)return e;if((0,tee.isBinary)(e)){const r={_placeholder:!0,num:t.length};return t.push(e),r}else if(Array.isArray(e)){const r=new Array(e.length);for(let n=0;n<e.length;n++)r[n]=Ov(e[n],t);return r}else if(typeof e=="object"&&!(e instanceof Date)){const r={};for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=Ov(e[n],t));return r}return e}function nee(e,t){return e.data=Av(e.data,t),delete e.attachments,e}fo.reconstructPacket=nee;function Av(e,t){if(!e)return e;if(e&&e._placeholder===!0){if(typeof e.num=="number"&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}else if(Array.isArray(e))for(let r=0;r<e.length;r++)e[r]=Av(e[r],t);else if(typeof e=="object")for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e[r]=Av(e[r],t));return e}(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Decoder=e.Encoder=e.PacketType=e.protocol=void 0;const t=Co,r=fo,n=cs,a=(0,ui.default)("socket.io-parser"),s=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];e.protocol=5;var o;(function(v){v[v.CONNECT=0]="CONNECT",v[v.DISCONNECT=1]="DISCONNECT",v[v.EVENT=2]="EVENT",v[v.ACK=3]="ACK",v[v.CONNECT_ERROR=4]="CONNECT_ERROR",v[v.BINARY_EVENT=5]="BINARY_EVENT",v[v.BINARY_ACK=6]="BINARY_ACK"})(o=e.PacketType||(e.PacketType={}));class u{constructor(m){this.replacer=m}encode(m){return a("encoding packet %j",m),(m.type===o.EVENT||m.type===o.ACK)&&(0,n.hasBinary)(m)?this.encodeAsBinary({type:m.type===o.EVENT?o.BINARY_EVENT:o.BINARY_ACK,nsp:m.nsp,data:m.data,id:m.id}):[this.encodeAsString(m)]}encodeAsString(m){let b=""+m.type;return(m.type===o.BINARY_EVENT||m.type===o.BINARY_ACK)&&(b+=m.attachments+"-"),m.nsp&&m.nsp!=="/"&&(b+=m.nsp+","),m.id!=null&&(b+=m.id),m.data!=null&&(b+=JSON.stringify(m.data,this.replacer)),a("encoded %j as %s",m,b),b}encodeAsBinary(m){const b=(0,r.deconstructPacket)(m),T=this.encodeAsString(b.packet),I=b.buffers;return I.unshift(T),I}}e.Encoder=u;function c(v){return Object.prototype.toString.call(v)==="[object Object]"}class l extends t.Emitter{constructor(m){super(),this.reviver=m}add(m){let b;if(typeof m=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");b=this.decodeString(m);const T=b.type===o.BINARY_EVENT;T||b.type===o.BINARY_ACK?(b.type=T?o.EVENT:o.ACK,this.reconstructor=new p(b),b.attachments===0&&super.emitReserved("decoded",b)):super.emitReserved("decoded",b)}else if((0,n.isBinary)(m)||m.base64)if(this.reconstructor)b=this.reconstructor.takeBinaryData(m),b&&(this.reconstructor=null,super.emitReserved("decoded",b));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+m)}decodeString(m){let b=0;const T={type:Number(m.charAt(0))};if(o[T.type]===void 0)throw new Error("unknown packet type "+T.type);if(T.type===o.BINARY_EVENT||T.type===o.BINARY_ACK){const R=b+1;for(;m.charAt(++b)!=="-"&&b!=m.length;);const x=m.substring(R,b);if(x!=Number(x)||m.charAt(b)!=="-")throw new Error("Illegal attachments");T.attachments=Number(x)}if(m.charAt(b+1)==="/"){const R=b+1;for(;++b&&!(m.charAt(b)===","||b===m.length););T.nsp=m.substring(R,b)}else T.nsp="/";const I=m.charAt(b+1);if(I!==""&&Number(I)==I){const R=b+1;for(;++b;){const x=m.charAt(b);if(x==null||Number(x)!=x){--b;break}if(b===m.length)break}T.id=Number(m.substring(R,b+1))}if(m.charAt(++b)){const R=this.tryParse(m.substr(b));if(l.isPayloadValid(T.type,R))T.data=R;else throw new Error("invalid payload")}return a("decoded %s as %j",m,T),T}tryParse(m){try{return JSON.parse(m,this.reviver)}catch{return!1}}static isPayloadValid(m,b){switch(m){case o.CONNECT:return c(b);case o.DISCONNECT:return b===void 0;case o.CONNECT_ERROR:return typeof b=="string"||c(b);case o.EVENT:case o.BINARY_EVENT:return Array.isArray(b)&&(typeof b[0]=="number"||typeof b[0]=="string"&&s.indexOf(b[0])===-1);case o.ACK:case o.BINARY_ACK:return Array.isArray(b)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}e.Decoder=l;class p{constructor(m){this.packet=m,this.buffers=[],this.reconPack=m}takeBinaryData(m){if(this.buffers.push(m),this.buffers.length===this.reconPack.attachments){const b=(0,r.reconstructPacket)(this.reconPack,this.buffers);return this.finishedReconstruction(),b}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}})(Xf);var Qf={};Object.defineProperty(Qf,"__esModule",{value:!0});Qf.on=iee;function iee(e,t,r){return e.on(t,r),function(){e.off(t,r)}}var aee=je&&je.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(rc,"__esModule",{value:!0});rc.Socket=void 0;const Jn=Xf,Jc=Qf,see=Co,oee=aee(ui),xr=(0,oee.default)("socket.io-client:socket"),uee=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class cee extends see.Emitter{constructor(t,r,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=t,this.nsp=r,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 t=this.io;this.subs=[(0,Jc.on)(t,"open",this.onopen.bind(this)),(0,Jc.on)(t,"packet",this.onpacket.bind(this)),(0,Jc.on)(t,"error",this.onerror.bind(this)),(0,Jc.on)(t,"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(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...r){var n,i,a;if(uee.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(r.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(r),this;const s={type:Jn.PacketType.EVENT,data:r};if(s.options={},s.options.compress=this.flags.compress!==!1,typeof r[r.length-1]=="function"){const l=this.ids++;xr("emitting packet with ack id %d",l);const p=r.pop();this._registerAckCallback(l,p),s.id=l}const o=(i=(n=this.io.engine)===null||n===void 0?void 0:n.transport)===null||i===void 0?void 0:i.writable,u=this.connected&&!(!((a=this.io.engine)===null||a===void 0)&&a._hasPingExpired());return this.flags.volatile&&!o?xr("discard packet as the transport is not currently writable"):u?(this.notifyOutgoingListeners(s),this.packet(s)):this.sendBuffer.push(s),this.flags={},this}_registerAckCallback(t,r){var n;const i=(n=this.flags.timeout)!==null&&n!==void 0?n:this._opts.ackTimeout;if(i===void 0){this.acks[t]=r;return}const a=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let o=0;o<this.sendBuffer.length;o++)this.sendBuffer[o].id===t&&(xr("removing packet with ack id %d from the buffer",t),this.sendBuffer.splice(o,1));xr("event with ack id %d has timed out after %d ms",t,i),r.call(this,new Error("operation has timed out"))},i),s=(...o)=>{this.io.clearTimeoutFn(a),r.apply(this,o)};s.withError=!0,this.acks[t]=s}emitWithAck(t,...r){return new Promise((n,i)=>{const a=(s,o)=>s?i(s):n(o);a.withError=!0,r.push(a),this.emit(t,...r)})}_addToQueue(t){let r;typeof t[t.length-1]=="function"&&(r=t.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((i,...a)=>n!==this._queue[0]?void 0:(i!==null?n.tryCount>this._opts.retries&&(xr("packet [%d] is discarded after %d tries",n.id,n.tryCount),this._queue.shift(),r&&r(i)):(xr("packet [%d] was successfully sent",n.id),this._queue.shift(),r&&r(null,...a)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(t=!1){if(xr("draining queue"),!this.connected||this._queue.length===0)return;const r=this._queue[0];if(r.pending&&!t){xr("packet [%d] has already been sent and is waiting for an ack",r.id);return}r.pending=!0,r.tryCount++,xr("sending packet [%d] (try n°%d)",r.id,r.tryCount),this.flags=r.flags,this.emit.apply(this,r.args)}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){xr("transport is open - connecting"),typeof this.auth=="function"?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:Jn.PacketType.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,r){xr("close (%s)",t),this.connected=!1,delete this.id,this.emitReserved("disconnect",t,r),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(n=>String(n.id)===t)){const n=this.acks[t];delete this.acks[t],n.withError&&n.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case Jn.PacketType.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.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 Jn.PacketType.EVENT:case Jn.PacketType.BINARY_EVENT:this.onevent(t);break;case Jn.PacketType.ACK:case Jn.PacketType.BINARY_ACK:this.onack(t);break;case Jn.PacketType.DISCONNECT:this.ondisconnect();break;case Jn.PacketType.CONNECT_ERROR:this.destroy();const n=new Error(t.data.message);n.data=t.data.data,this.emitReserved("connect_error",n);break}}onevent(t){const r=t.data||[];xr("emitting event %j",r),t.id!=null&&(xr("attaching ack callback to event"),r.push(this.ack(t.id))),this.connected?this.emitEvent(r):this.receiveBuffer.push(Object.freeze(r))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const r=this._anyListeners.slice();for(const n of r)n.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&typeof t[t.length-1]=="string"&&(this._lastOffset=t[t.length-1])}ack(t){const r=this;let n=!1;return function(...i){n||(n=!0,xr("sending ack %j",i),r.packet({type:Jn.PacketType.ACK,id:t,data:i}))}}onack(t){const r=this.acks[t.id];if(typeof r!="function"){xr("bad ack %s",t.id);return}delete this.acks[t.id],xr("calling ack %s with %j",t.id,t.data),r.withError&&t.data.unshift(null),r.apply(this,t.data)}onconnect(t,r){xr("socket connected with id %s",t),this.id=t,this.recovered=r&&this._pid===r,this._pid=r,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){xr("server disconnect (%s)",this.nsp),this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&(xr("performing disconnect (%s)",this.nsp),this.packet({type:Jn.PacketType.DISCONNECT})),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const r=this._anyListeners;for(let n=0;n<r.length;n++)if(t===r[n])return r.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(t),this}prependAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(t),this}offAnyOutgoing(t){if(!this._anyOutgoingListeners)return this;if(t){const r=this._anyOutgoingListeners;for(let n=0;n<r.length;n++)if(t===r[n])return r.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(t){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const r=this._anyOutgoingListeners.slice();for(const n of r)n.apply(this,t.data)}}}rc.Socket=cee;var Hg={};Object.defineProperty(Hg,"__esModule",{value:!0});Hg.Backoff=Eo;function Eo(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}Eo.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),r=Math.floor(t*this.jitter*e);e=Math.floor(t*10)&1?e+r:e-r}return Math.min(e,this.max)|0};Eo.prototype.reset=function(){this.attempts=0};Eo.prototype.setMin=function(e){this.ms=e};Eo.prototype.setMax=function(e){this.max=e};Eo.prototype.setJitter=function(e){this.jitter=e};var lee=je&&je.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),fee=je&&je.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),dee=je&&je.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&lee(t,e,r);return fee(t,e),t},pee=je&&je.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Yf,"__esModule",{value:!0});Yf.Manager=void 0;const ch=Gf,hee=rc,vee=dee(Xf),Xa=Qf,mee=Hg,gee=Co,yee=pee(ui),Vr=(0,yee.default)("socket.io-client:manager");class bee extends gee.Emitter{constructor(t,r){var n;super(),this.nsps={},this.subs=[],t&&typeof t=="object"&&(r=t,t=void 0),r=r||{},r.path=r.path||"/socket.io",this.opts=r,(0,ch.installTimerFunctions)(this,r),this.reconnection(r.reconnection!==!1),this.reconnectionAttempts(r.reconnectionAttempts||1/0),this.reconnectionDelay(r.reconnectionDelay||1e3),this.reconnectionDelayMax(r.reconnectionDelayMax||5e3),this.randomizationFactor((n=r.randomizationFactor)!==null&&n!==void 0?n:.5),this.backoff=new mee.Backoff({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(r.timeout==null?2e4:r.timeout),this._readyState="closed",this.uri=t;const i=r.parser||vee;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=r.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return t===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var r;return t===void 0?this._reconnectionDelay:(this._reconnectionDelay=t,(r=this.backoff)===null||r===void 0||r.setMin(t),this)}randomizationFactor(t){var r;return t===void 0?this._randomizationFactor:(this._randomizationFactor=t,(r=this.backoff)===null||r===void 0||r.setJitter(t),this)}reconnectionDelayMax(t){var r;return t===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,(r=this.backoff)===null||r===void 0||r.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(t){if(Vr("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;Vr("opening %s",this.uri),this.engine=new ch.Socket(this.uri,this.opts);const r=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const i=(0,Xa.on)(r,"open",function(){n.onopen(),t&&t()}),a=o=>{Vr("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",o),t?t(o):this.maybeReconnectOnOpen()},s=(0,Xa.on)(r,"error",a);if(this._timeout!==!1){const o=this._timeout;Vr("connect attempt will timeout after %d",o);const u=this.setTimeoutFn(()=>{Vr("connect attempt timed out after %d",o),i(),a(new Error("timeout")),r.close()},o);this.opts.autoUnref&&u.unref(),this.subs.push(()=>{this.clearTimeoutFn(u)})}return this.subs.push(i),this.subs.push(s),this}connect(t){return this.open(t)}onopen(){Vr("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push((0,Xa.on)(t,"ping",this.onping.bind(this)),(0,Xa.on)(t,"data",this.ondata.bind(this)),(0,Xa.on)(t,"error",this.onerror.bind(this)),(0,Xa.on)(t,"close",this.onclose.bind(this)),(0,Xa.on)(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(r){this.onclose("parse error",r)}}ondecoded(t){(0,ch.nextTick)(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){Vr("error",t),this.emitReserved("error",t)}socket(t,r){let n=this.nsps[t];return n?this._autoConnect&&!n.active&&n.connect():(n=new hee.Socket(this,t,r),this.nsps[t]=n),n}_destroy(t){const r=Object.keys(this.nsps);for(const n of r)if(this.nsps[n].active){Vr("socket %s is still active, skipping close",n);return}this._close()}_packet(t){Vr("writing packet %j",t);const r=this.encoder.encode(t);for(let n=0;n<r.length;n++)this.engine.write(r[n],t.options)}cleanup(){Vr("cleanup"),this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}_close(){Vr("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,r){var n;Vr("closed due to %s",t),this.cleanup(),(n=this.engine)===null||n===void 0||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,r),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)Vr("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const r=this.backoff.duration();Vr("will wait %dms before reconnect attempt",r),this._reconnecting=!0;const n=this.setTimeoutFn(()=>{t.skipReconnect||(Vr("attempting reconnect"),this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(i=>{i?(Vr("reconnect attempt error"),t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",i)):(Vr("reconnect success"),t.onreconnect())}))},r);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}Yf.Manager=bee;(function(e,t){var r=je&&je.__importDefault||function(v){return v&&v.__esModule?v:{default:v}};Object.defineProperty(t,"__esModule",{value:!0}),t.WebTransport=t.WebSocket=t.NodeWebSocket=t.XHR=t.NodeXHR=t.Fetch=t.Socket=t.Manager=t.protocol=void 0,t.io=c,t.connect=c,t.default=c;const n=Gg,i=Yf;Object.defineProperty(t,"Manager",{enumerable:!0,get:function(){return i.Manager}});const a=rc;Object.defineProperty(t,"Socket",{enumerable:!0,get:function(){return a.Socket}});const o=(0,r(ui).default)("socket.io-client"),u={};function c(v,m){typeof v=="object"&&(m=v,v=void 0),m=m||{};const b=(0,n.url)(v,m.path||"/socket.io"),T=b.source,I=b.id,R=b.path,x=u[I]&&R in u[I].nsps,N=m.forceNew||m["force new connection"]||m.multiplex===!1||x;let j;return N?(o("ignoring socket cache for %s",T),j=new i.Manager(T,m)):(u[I]||(o("new io instance for %s",T),u[I]=new i.Manager(T,m)),j=u[I]),b.query&&!m.query&&(m.query=b.queryKey),j.socket(b.path,m)}Object.assign(c,{Manager:i.Manager,Socket:a.Socket,io:c,connect:c});var l=Xf;Object.defineProperty(t,"protocol",{enumerable:!0,get:function(){return l.protocol}});var p=Gf;Object.defineProperty(t,"Fetch",{enumerable:!0,get:function(){return p.Fetch}}),Object.defineProperty(t,"NodeXHR",{enumerable:!0,get:function(){return p.NodeXHR}}),Object.defineProperty(t,"XHR",{enumerable:!0,get:function(){return p.XHR}}),Object.defineProperty(t,"NodeWebSocket",{enumerable:!0,get:function(){return p.NodeWebSocket}}),Object.defineProperty(t,"WebSocket",{enumerable:!0,get:function(){return p.WebSocket}}),Object.defineProperty(t,"WebTransport",{enumerable:!0,get:function(){return p.WebTransport}}),e.exports=c})(Ev,Ev.exports);var G$=Ev.exports,H$={exports:{}};(function(e,t){(function(r){e.exports=r()})(function(){var r=function(f,d,h){for(var y=h,g=0,_=f.length;g<_;g++)y=d(y,f[g],g,f);return y},n=function(f,d){return r(f,function(h,y,g,_){return d(y,g,_)?h.concat(y):h},[])},i=function(f,d){return r(f,function(h,y,g,_){return h.concat(d(y,g,_))},[])},a=function(f,d){return r(f,function(h,y,g,_){return h===!0||y===d},!1)},s=!{toString:null}.propertyIsEnumerable("toString"),o=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],u=function(f){var d=[],h;for(h in f)Object.prototype.hasOwnProperty.call(f,h)&&d.push(h);if(!s)return d;for(var y=0,g=o.length;y<g;y++)Object.prototype.hasOwnProperty.call(f,o[y])&&d.push(o[y]);return d},c=function(f){return Object.prototype.toString.call(f)==="[object Array]"},l=function(f){return f<10?"0"+f:f},p=function(){var f=new Date;return f.getUTCFullYear()+"-"+l(f.getUTCMonth()+1)+"-"+l(f.getUTCDate())+"T"+l(f.getUTCHours())+":"+l(f.getUTCMinutes())+":"+l(f.getUTCSeconds())+"."+(f.getUTCMilliseconds()/1e3).toFixed(3).slice(2,5)+"Z"},v={map:i,reduce:r,filter:n,includes:a,keys:u,isArray:c,isoDate:p},m={};m.intRange=function(f,d){return f===void 0&&(f=1),d===void 0&&(d=1/0),function(h){return typeof h=="number"&&parseInt(""+h,10)===h&&h>=f&&h<=d}},m.stringWithLength=function(f){return typeof f=="string"&&!!f.length};var b={},T=v.filter,I=v.reduce,R=v.keys,x=v.isArray,N=v.includes,j=m.intRange,X=m.stringWithLength;b.schema={apiKey:{defaultValue:function(){return null},message:"is required",validate:X},appVersion:{defaultValue:function(){return null},message:"should be a string",validate:function(f){return f===null||X(f)}},appType:{defaultValue:function(){return null},message:"should be a string",validate:function(f){return f===null||X(f)}},autoNotify:{defaultValue:function(){return!0},message:"should be true|false",validate:function(f){return f===!0||f===!1}},beforeSend:{defaultValue:function(){return[]},message:"should be a function or array of functions",validate:function(f){return typeof f=="function"||x(f)&&T(f,function(d){return typeof d=="function"}).length===f.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(f,d){return f&&typeof f=="object"&&X(f.notify)&&(d.autoCaptureSessions===!1||X(f.sessions))&&T(R(f),function(h){return!N(["notify","sessions"],h)}).length===0}},autoCaptureSessions:{defaultValue:function(f,d){return d.endpoints===void 0||!!d.endpoints&&!!d.endpoints.sessions},message:"should be true|false",validate:function(f){return f===!0||f===!1}},notifyReleaseStages:{defaultValue:function(){return null},message:"should be an array of strings",validate:function(f){return f===null||x(f)&&T(f,function(d){return typeof d=="string"}).length===f.length}},releaseStage:{defaultValue:function(){return"production"},message:"should be a string",validate:function(f){return typeof f=="string"&&f.length}},maxBreadcrumbs:{defaultValue:function(){return 20},message:"should be a number ≤40",validate:function(f){return j(0,40)(f)}},autoBreadcrumbs:{defaultValue:function(){return!0},message:"should be true|false",validate:function(f){return typeof f=="boolean"}},user:{defaultValue:function(){return null},message:"(object) user should be an object",validate:function(f){return typeof f=="object"}},metaData:{defaultValue:function(){return null},message:"should be an object",validate:function(f){return typeof f=="object"}},logger:{defaultValue:function(){},message:"should be null or an object with methods { debug, info, warn, error }",validate:function(f){return!f||f&&I(["debug","info","warn","error"],function(d,h){return d&&typeof f[h]=="function"},!0)}},filters:{defaultValue:function(){return["password"]},message:"should be an array of strings|regexes",validate:function(f){return x(f)&&f.length===T(f,function(d){return typeof d=="string"||d&&typeof d.test=="function"}).length}}},b.mergeDefaults=function(f,d){if(!f||!d)throw new Error("opts and schema objects are required");return I(R(d),function(h,y){return h[y]=f[y]!==void 0?f[y]:d[y].defaultValue(f[y],f),h},{})},b.validate=function(f,d){if(!f||!d)throw new Error("opts and schema objects are required");var h=I(R(d),function(y,g){return d[g].validate(f[g],f)?y:y.concat({key:g,message:d[g].message,value:f[g]})},[]);return{valid:!h.length,errors:h}};function J(){return J=Object.assign||function(f){for(var d=1;d<arguments.length;d++){var h=arguments[d];for(var y in h)Object.prototype.hasOwnProperty.call(h,y)&&(f[y]=h[y])}return f},J.apply(this,arguments)}var V=b.schema,D=v.map,te=m.stringWithLength,ue={releaseStage:{defaultValue:function(){return/^localhost(:\d+)?$/.test(window.location.host)?"development":"production"},message:"should be set",validate:te},logger:J({},V.logger,{defaultValue:function(){return typeof console<"u"&&typeof console.debug=="function"?ee():void 0}})},ee=function(){var f={},d=console.log;return D(["debug","info","warn","error"],function(h){var y=console[h];f[h]=typeof y=="function"?y.bind(console,"[bugsnag]"):d.bind(console,"[bugsnag]")}),f},ge=v.isoDate,L=function(){function f(h,y,g,_){h===void 0&&(h="[anonymous]"),y===void 0&&(y={}),g===void 0&&(g="manual"),_===void 0&&(_=ge()),this.type=g,this.name=h,this.metaData=y,this.timestamp=_}var d=f.prototype;return d.toJSON=function(){return{type:this.type,name:this.name,timestamp:this.timestamp,metaData:this.metaData}},f}(),pe=L,Te=function(f,d,h){var y=f.length,g=0,_=function(){if(g>=y)return h(null,!1);d(f[g],function(w,S){if(w)return h(w,!1);if(S===!0)return h(null,!0);g++,_()})};_()},rt=function(f){return f.app&&typeof f.app.releaseStage=="string"?f.app.releaseStage:f.config.releaseStage},Ke=Se;function Se(f){switch(Object.prototype.toString.call(f)){case"[object Error]":return!0;case"[object Exception]":return!0;case"[object DOMException]":return!0;default:return f instanceof Error}}var ce=Ke,he=function(f,d){return function(h,y){if(typeof h!="function")return y(null,!1);try{if(h.length!==2){var g=h(f);return g&&typeof g.then=="function"?g.then(function(_){return setTimeout(function(){return y(null,P(f,_))},0)},function(_){setTimeout(function(){return d(_),y(null,!1)})}):y(null,P(f,g))}h(f,function(_,w){if(_)return d(_),y(null,!1);y(null,P(f,w))})}catch(_){d(_),y(null,!1)}}},P=function(f,d){return f.isIgnored()||d===!1},Ie={};(function(f,d){typeof Ie=="object"?Ie=d():f.StackFrame=d()})(this,function(){function f(G){return!isNaN(parseFloat(G))&&isFinite(G)}function d(G){return G.charAt(0).toUpperCase()+G.substring(1)}function h(G){return function(){return this[G]}}var y=["isConstructor","isEval","isNative","isToplevel"],g=["columnNumber","lineNumber"],_=["fileName","functionName","source"],w=["args"],S=y.concat(g,_,w);function C(G){if(G instanceof Object)for(var Le=0;Le<S.length;Le++)G.hasOwnProperty(S[Le])&&G[S[Le]]!==void 0&&this["set"+d(S[Le])](G[S[Le]])}C.prototype={getArgs:function(){return this.args},setArgs:function(G){if(Object.prototype.toString.call(G)!=="[object Array]")throw new TypeError("Args must be an Array");this.args=G},getEvalOrigin:function(){return this.evalOrigin},setEvalOrigin:function(G){if(G instanceof C)this.evalOrigin=G;else if(G instanceof Object)this.evalOrigin=new C(G);else throw new TypeError("Eval Origin must be an Object or StackFrame")},toString:function(){var G=this.getFunctionName()||"{anonymous}",Le="("+(this.getArgs()||[]).join(",")+")",Xe=this.getFileName()?"@"+this.getFileName():"",We=f(this.getLineNumber())?":"+this.getLineNumber():"",Ve=f(this.getColumnNumber())?":"+this.getColumnNumber():"";return G+Le+Xe+We+Ve}};for(var B=0;B<y.length;B++)C.prototype["get"+d(y[B])]=h(y[B]),C.prototype["set"+d(y[B])]=function(G){return function(Le){this[G]=!!Le}}(y[B]);for(var U=0;U<g.length;U++)C.prototype["get"+d(g[U])]=h(g[U]),C.prototype["set"+d(g[U])]=function(G){return function(Le){if(!f(Le))throw new TypeError(G+" must be a Number");this[G]=Number(Le)}}(g[U]);for(var H=0;H<_.length;H++)C.prototype["get"+d(_[H])]=h(_[H]),C.prototype["set"+d(_[H])]=function(G){return function(Le){this[G]=String(Le)}}(_[H]);return C});var qe={};(function(f,d){typeof qe=="object"?qe=d(Ie):f.ErrorStackParser=d(f.StackFrame)})(this,function(d){var h=/(^|@)\S+\:\d+/,y=/^\s*at .*(\S+\:\d+|\(native\))/m,g=/^(eval@)?(\[native code\])?$/;return{parse:function(w){if(typeof w.stacktrace<"u"||typeof w["opera#sourceloc"]<"u")return this.parseOpera(w);if(w.stack&&w.stack.match(y))return this.parseV8OrIE(w);if(w.stack)return this.parseFFOrSafari(w);throw new Error("Cannot parse given Error object")},extractLocation:function(w){if(w.indexOf(":")===-1)return[w];var S=/(.+?)(?:\:(\d+))?(?:\:(\d+))?$/,C=S.exec(w.replace(/[\(\)]/g,""));return[C[1],C[2]||void 0,C[3]||void 0]},parseV8OrIE:function(w){var S=w.stack.split(`
472
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var y=!0,g=!1,_;return{s:function(){f=f.call(O)},n:function(){var S=f.next();return y=S.done,S},e:function(S){g=!0,_=S},f:function(){try{!y&&f.return!=null&&f.return()}finally{if(g)throw _}}}}function Kt(O,A){if(O){if(typeof O=="string")return _t(O,A);var f=Object.prototype.toString.call(O).slice(8,-1);if(f==="Object"&&O.constructor&&(f=O.constructor.name),f==="Map"||f==="Set")return Array.from(O);if(f==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(f))return _t(O,A)}}function _t(O,A){(A==null||A>O.length)&&(A=O.length);for(var f=0,d=new Array(A);f<A;f++)d[f]=O[f];return d}var Jt=ce.default(function O(A){he.default(this,O),Se.default(this,"type","email"),this.messageSid=A.message_sid,this.level=A.level,this.name=A.name,this.address=A.address}),ur=ce.default(function O(A){he.default(this,O),this.type=A.type,this.messageSid=A.message_sid,this.rawData=JSON.stringify(A)}),_r=function(){function O(A,f){he.default(this,O),this._services=A,this._configuration=f,this._cache=new W({maxSize:f.messageRecipientsCacheCapacity})}return ce.default(O,[{key:"getRecipientsFromMessage",value:function(){var A=L.default(P.default.mark(function d(h,y){var g=this,_,w,S,C,B;return P.default.wrap(function(H){for(;;)switch(H.prev=H.next){case 0:if(_="".concat(h,",").concat(y),w=this._cache.get(_),!w){H.next=4;break}return H.abrupt("return",w.item);case 4:return S=new Pt(this._configuration.links.conversations).path(h).path("MessageRecipients").arg("MessageSid",y).build(),H.next=7,this._services.commandExecutor.fetchResource(S);case 7:return C=H.sent,B=C.message_recipients.map(function(G){return g._wrapResponse(G)}),B.length>0&&this._cache.set(_,{item:B}),H.abrupt("return",B);case 11:case"end":return H.stop()}},d,this)}));function f(d,h){return A.apply(this,arguments)}return f}()},{key:"getRecipientsFromConversation",value:function(){var A=L.default(P.default.mark(function d(h,y){var g,_,w=this,S,C,B,U,H,G,Le,Xe,We,Ve;return P.default.wrap(function(Tt){for(;;)switch(Tt.prev=Tt.next){case 0:return S=new Pt(this._configuration.links.conversations).path(h).path("MessageRecipients").arg("PageToken",(g=y==null?void 0:y.pageToken)!==null&&g!==void 0?g:void 0).arg("PageSize",(_=y==null?void 0:y.pageSize)!==null&&_!==void 0?_:void 0).build(),Tt.next=3,this._services.commandExecutor.fetchResource(S);case 3:C=Tt.sent,B=C.message_recipients.map(function(pt){return w._wrapResponse(pt)}),U=Ze(B);try{for(U.s();!(H=U.n()).done;)Xe=H.value,We="".concat(h,",").concat(Xe.messageSid),Ve=(G=(Le=this._cache.get(We))===null||Le===void 0?void 0:Le.item)!==null&&G!==void 0?G:[],this._cache.set(We,{item:[].concat(Ne.default(Ve),[Xe])})}catch(pt){U.e(pt)}finally{U.f()}return Tt.abrupt("return",new He(B,function(pt,hr){return w.getRecipientsFromConversation(h,{pageToken:pt,pageSize:hr})},C.meta.previous_token,C.meta.next_token));case 8:case"end":return Tt.stop()}},d,this)}));function f(d,h){return A.apply(this,arguments)}return f}()},{key:"_wrapResponse",value:function(f){switch(f.type){case"email":return new Jt(f);default:return new ur(f)}}}]),O}(),lt;function jr(O,A){var f=Object.keys(O);if(Object.getOwnPropertySymbols){var d=Object.getOwnPropertySymbols(O);A&&(d=d.filter(function(h){return Object.getOwnPropertyDescriptor(O,h).enumerable})),f.push.apply(f,d)}return f}function Fr(O){for(var A=1;A<arguments.length;A++){var f=arguments[A]!=null?arguments[A]:{};A%2?jr(Object(f),!0).forEach(function(d){Se.default(O,d,f[d])}):Object.getOwnPropertyDescriptors?Object.defineProperties(O,Object.getOwnPropertyDescriptors(f)):jr(Object(f)).forEach(function(d){Object.defineProperty(O,d,Object.getOwnPropertyDescriptor(f,d))})}return O}function pr(O){var A=Ur();return function(){var d=Ke.default(O),h;if(A){var y=Ke.default(this).constructor;h=Reflect.construct(d,arguments,y)}else h=d.apply(this,arguments);return rt.default(this,h)}}function Ur(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var gt,In=ce.default(function O(){he.default(this,O)});e.Client=gt=(lt=function(O){Te.default(f,O);var A=pr(f);function f(d){var h,y,g,_,w,S,C=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(he.default(this,f),S=A.call(this),Se.default(pe.default(S),"version",E),Se.default(pe.default(S),"connectionState","unknown"),Se.default(pe.default(S),"parsePushNotification",gt.parsePushNotification),S._fpaToken=d??"",S._options=C??{},!S._options.disableDeepClone){var B=Fr(Fr({},S._options),{},{transport:void 0,twilsockClient:void 0});B=It(B),B.transport=S._options.transport,B.twilsockClient=S._options.twilsockClient,S._options=B}S._options.logLevel=(h=S._options.logLevel)!==null&&h!==void 0?h:"silent",gt._logger.setLevel(S._options.logLevel);var U=S._options.productId="ip_messaging";if(S._options.clientMetadata=S._options.clientMetadata||{},S._options.clientMetadata.hasOwnProperty("type")||(S._options.clientMetadata.type="conversations"),S._options.clientMetadata.hasOwnProperty("sdk")||(S._options.clientMetadata.sdk="JS",S._options.clientMetadata.sdkv=E),S._options.Sync=S._options.Sync||{},typeof S._options.Sync.enableSessionStorage>"u"&&(S._options.Sync.enableSessionStorage=!0),S._options.region&&(S._options.Sync.region=S._options.region),!d)throw new Error("A valid Twilio token should be provided");S._services=new In,S._myself=new ye("","",null,S._services);var H=!S._options.twilsockClient;if(!S._options.initRegistrations){var G=new j.InitRegistration(U);gt.populateInitRegistrations(G),S._options.initRegistrations=[G]}S._services.twilsockClient=S._options.twilsockClient=(y=S._options.twilsockClient)!==null&&y!==void 0?y:new j.TwilsockClient(d,U,S._options),S._services.twilsockClient.on(gt.tokenAboutToExpire,function(){return S.emit(gt.tokenAboutToExpire)}),S._services.twilsockClient.on(gt.tokenExpired,function(){return S.emit(gt.tokenExpired)}),S._services.twilsockClient.on(gt.connectionError,function(Tt){return S.emit(gt.connectionError,Tt)}),S._services.twilsockClient.on("stateChanged",function(Tt){gt._logger.debug("Handling stateChanged for ConversationsClient: new state ".concat(Tt)),Tt!==S.connectionState&&(S.connectionState=Tt,S.emit(gt.connectionStateChanged,S.connectionState))}),S._services.transport=S._options.transport=(g=S._options.transport)!==null&&g!==void 0?g:S._options.twilsockClient,S._services.notificationClient=S._options.notificationsClient=(_=S._options.notificationsClient)!==null&&_!==void 0?_:new X.Notifications(d,S._options),S._services.syncClient=S._options.syncClient=(w=S._options.syncClient)!==null&&w!==void 0?w:new J.SyncClient(d,S._options);var Le=(C==null?void 0:C.Chat)||(C==null?void 0:C.IPMessaging)||C||{},Xe=Le.region||(C==null?void 0:C.region),We=Le.apiUri||Le.typingUri||"https://aim.".concat(Xe||"us1",".twilio.com");S._services.commandExecutor=new $r(We,{transport:S._options.transport},U),S._services.contentClient=new ln(S._services);var Ve=function(pt){S._rejectEnsureReady(pt),S.emit(gt.stateChanged,"failed"),S.emit(gt.initFailed,{error:pt})},Nt=function(){Ve({terminal:!0,message:"Twilsock has disconnected."}),S._initializeEnsureReady((C==null?void 0:C.throwErrorsAlways)||!1)};return S._services.twilsockClient.once("connectionError",Ve),S._services.twilsockClient.once("disconnected",Nt),S._services.twilsockClient.once("connected",L.default(P.default.mark(function Tt(){var pt,hr;return P.default.wrap(function(ut){for(;;)switch(ut.prev=ut.next){case 0:return gt._logger.debug("ConversationsClient started INITIALIZING"),S._services.twilsockClient.off("connectionError",Ve),S._services.twilsockClient.off("disconnected",Nt),ut.prev=3,pt="conversations.client.startup",S._services.twilsockClient.addPartialTelemetryEvent(new j.TelemetryEventDescription(pt,"Conversations client startup",new Date),pt,j.TelemetryPoint.Start),ut.next=8,S._initialize();case 8:S._services.twilsockClient.addPartialTelemetryEvent(new j.TelemetryEventDescription("","",new Date),pt,j.TelemetryPoint.End),ut.next=17;break;case 11:ut.prev=11,ut.t0=ut.catch(3),hr={terminal:!0,message:ut.t0.message},S._rejectEnsureReady(hr),S.emit(gt.stateChanged,"failed"),S.emit(gt.initFailed,{error:hr});case 17:case"end":return ut.stop()}},Tt,null,[[3,11]])}))),S._initializeEnsureReady((C==null?void 0:C.throwErrorsAlways)||!1),H&&S._services.twilsockClient.connect(),S}return ce.default(f,[{key:"user",get:function(){return this._myself}},{key:"reachabilityEnabled",get:function(){if(!this._configuration)throw new Error("Reachability information could not yet be accessed as the client has not yet been initialized. Subscribe to the 'stateChanged' event to properly react to the client initialization.");return this._configuration.reachabilityEnabled}},{key:"token",get:function(){return this._fpaToken}},{key:"shutdown",value:function(){var d=L.default(P.default.mark(function y(){return P.default.wrap(function(_){for(;;)switch(_.prev=_.next){case 0:return _.next=2,this._ensureReady;case 2:return _.next=4,this._services.twilsockClient.disconnect();case 4:case"end":return _.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"updateToken",value:function(){var d=L.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this._ensureReady;case 2:if(gt._logger.info("updateToken"),this._fpaToken!==g){w.next=5;break}return w.abrupt("return",this);case 5:return w.next=7,this._services.twilsockClient.updateToken(g);case 7:return w.next=9,this._services.notificationClient.updateToken(g);case 9:return w.next=11,this._services.mcsClient.updateToken(g);case 11:return this._fpaToken=g,w.abrupt("return",this);case 13:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"getConversationBySid",value:function(){var d=L.default(P.default.mark(function y(g){var _;return P.default.wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return S.next=2,this._ensureReady;case 2:return S.next=4,this._conversationsEntity.myConversationsRead.promise;case 4:return S.next=6,this._conversationsEntity.getConversation(g);case 6:if(_=S.sent,_){S.next=12;break}return S.next=10,this.peekConversationBySid(g);case 10:_=S.sent,_&&D.deprecationWarning("The method getConversationBySid is deprecated to retrieve conversations you're not part of. Use peekConversationBySid instead.");case 12:if(_){S.next=14;break}throw new Error("Conversation with SID ".concat(g," was not found."));case 14:return S.abrupt("return",_);case 15:case"end":return S.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"peekConversationBySid",value:function(){var d=L.default(P.default.mark(function y(g){var _;return P.default.wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return S.next=2,this._ensureReady;case 2:return S.next=4,this._conversationsEntity.peekConversation(g);case 4:if(_=S.sent,_){S.next=7;break}throw new Error("Conversation with SID ".concat(g," was not found."));case 7:return S.abrupt("return",_);case 8:case"end":return S.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"getConversationByUniqueName",value:function(){var d=L.default(P.default.mark(function y(g){var _;return P.default.wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return S.next=2,this._ensureReady;case 2:return S.next=4,this._conversationsEntity.myConversationsRead.promise;case 4:return S.next=6,this._conversationsEntity.getConversationByUniqueName(g);case 6:if(_=S.sent,_){S.next=9;break}throw new Error("Conversation with unique name ".concat(g," was not found."));case 9:return S.abrupt("return",_);case 10:case"end":return S.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"getSubscribedConversations",value:function(){var d=L.default(P.default.mark(function y(){return P.default.wrap(function(_){for(;;)switch(_.prev=_.next){case 0:return _.next=2,this._ensureReady;case 2:return _.abrupt("return",this._conversationsPromise.then(function(w){return w.getConversations()}));case 3:case"end":return _.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"createConversation",value:function(){var d=L.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this._ensureReady;case 2:return g=g||{},w.abrupt("return",this._conversationsPromise.then(function(S){return S.addConversation(g)}));case 4:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"setPushRegistrationId",value:function(){var d=L.default(P.default.mark(function y(g,_){return P.default.wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return S.next=2,this._ensureReady;case 2:return this._subscribeToPushNotifications(g),this._services.notificationClient.setPushRegistrationId(g,_),S.next=6,this._services.notificationClient.commitChanges();case 6:case"end":return S.stop()}},y,this)}));function h(y,g){return d.apply(this,arguments)}return h}()},{key:"unsetPushRegistrationId",value:function(){var d=L.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this._ensureReady;case 2:return this._unsubscribeFromPushNotifications(g),w.next=5,this._services.notificationClient.commitChanges();case 5:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"removePushRegistrations",value:function(){var d=L.default(P.default.mark(function y(g,_){return P.default.wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return S.next=2,this._services.notificationClient.removeRegistrations(g,_);case 2:case"end":return S.stop()}},y,this)}));function h(y,g){return d.apply(this,arguments)}return h}()},{key:"handlePushNotification",value:function(){var d=L.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this._ensureReady;case 2:gt._logger.debug("handlePushNotification, notificationPayload=",g),this.emit("pushNotification",gt.parsePushNotification(g));case 4:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"getUser",value:function(){var d=L.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this._ensureReady;case 2:return w.abrupt("return",this._services.users.getUser(g));case 3:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"getSubscribedUsers",value:function(){var d=L.default(P.default.mark(function y(){return P.default.wrap(function(_){for(;;)switch(_.prev=_.next){case 0:return _.next=2,this._ensureReady;case 2:return _.abrupt("return",this._services.users.getSubscribedUsers());case 3:case"end":return _.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"getTemporaryContentUrlsForMediaSids",value:function(h){var y=this;return new V.CancellablePromise(function(){var g=L.default(P.default.mark(function _(w,S,C){var B,U;return P.default.wrap(function(G){for(;;)switch(G.prev=G.next){case 0:if(!(!y._services.mcsClient||!h)){G.next=3;break}return S(new Error("Media Content Service is unavailable")),G.abrupt("return");case 3:return B=y._services.mcsClient.mediaSetGetContentUrls(h),C(function(){B.cancel()}),G.prev=5,G.next=8,B;case 8:U=G.sent,w(U),G.next=15;break;case 12:G.prev=12,G.t0=G.catch(5),S(G.t0);case 15:case"end":return G.stop()}},_,null,[[5,12]])}));return function(_,w,S){return g.apply(this,arguments)}}())}},{key:"getTemporaryContentUrlsForMedia",value:function(h){var y=h.map(function(g){return g.sid});return this.getTemporaryContentUrlsForMediaSids(y)}},{key:"getContentTemplates",value:function(){var d=L.default(P.default.mark(function y(){return P.default.wrap(function(_){for(;;)switch(_.prev=_.next){case 0:return _.next=2,this._ensureReady;case 2:return _.next=4,this._services.contentClient.getContentTemplates();case 4:return _.abrupt("return",_.sent);case 5:case"end":return _.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"_initialize",value:function(){var d=L.default(P.default.mark(function y(){var g=this,_;return P.default.wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return S.next=2,this._services.commandExecutor.fetchResource("Client/v2/Configuration");case 2:return _=S.sent,this._configuration=new Et(this._options,_,gt._logger),this._services.channelMetadataClient=new Ee(this._services,this._configuration),this._services.messageRecipientsClient=new _r(this._services,this._configuration),this._myself._resolveInitialization(this._configuration,this._configuration.userIdentity,this._configuration.userInfo,!0),this._services.typingIndicator=new $(this.getConversationBySid.bind(this),this._configuration,this._services),this._services.network=new le(this._configuration,this._services),this._services.users=new F(this._myself,this._configuration,this._services),this._services.users.on("userSubscribed",function(C){g.emit("userSubscribed",C)}),this._services.users.on("userUpdated",function(C){return g.emit("userUpdated",C)}),this._services.users.on("userUnsubscribed",function(C){g.emit("userUnsubscribed",C)}),this._conversationsEntity=new Vr(this._configuration,this._services),this._conversationsEntity.on("conversationAdded",function(C){g.emit("conversationAdded",C)}),this._conversationsEntity.on("conversationRemoved",function(C){g.emit("conversationRemoved",C)}),this._conversationsEntity.on("conversationJoined",function(C){g.emit("conversationJoined",C)}),this._conversationsEntity.on("conversationLeft",function(C){g.emit("conversationLeft",C)}),this._conversationsEntity.on("conversationUpdated",function(C){return g.emit("conversationUpdated",C)}),this._conversationsEntity.on("participantJoined",function(C){g.emit("participantJoined",C)}),this._conversationsEntity.on("participantLeft",function(C){g.emit("participantLeft",C)}),this._conversationsEntity.on("participantUpdated",function(C){return g.emit("participantUpdated",C)}),this._conversationsEntity.on("messageAdded",function(C){return g.emit("messageAdded",C)}),this._conversationsEntity.on("messageUpdated",function(C){return g.emit("messageUpdated",C)}),this._conversationsEntity.on("messageRemoved",function(C){return g.emit("messageRemoved",C)}),this._conversationsEntity.on("typingStarted",function(C){return g.emit("typingStarted",C)}),this._conversationsEntity.on("typingEnded",function(C){return g.emit("typingEnded",C)}),this._conversationsPromise=this._conversationsEntity.fetchConversations().then(function(){return g._conversationsEntity}).catch(function(C){throw C}),S.next=30,this._services.users.myself._ensureFetched();case 30:gt._supportedPushChannels.forEach(function(C){return g._subscribeToPushNotifications(C)}),this._services.typingIndicator.initialize(),this._services.mcsClient=new V.McsClient(this._fpaToken,this._configuration.links.mediaService,this._configuration.links.mediaSetService,Fr(Fr({},this._options),{},{transport:void 0})),this._resolveEnsureReady(),this.emit(gt.stateChanged,"initialized"),this.emit(gt.initialized);case 36:case"end":return S.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"_subscribeToPushNotifications",value:function(h){var y=this;[be.NEW_MESSAGE,be.ADDED_TO_CONVERSATION,be.REMOVED_FROM_CONVERSATION,be.TYPING_INDICATOR,be.CONSUMPTION_UPDATE].forEach(function(g){y._services.notificationClient.subscribe(h,g)})}},{key:"_unsubscribeFromPushNotifications",value:function(h){var y=this;[be.NEW_MESSAGE,be.ADDED_TO_CONVERSATION,be.REMOVED_FROM_CONVERSATION,be.TYPING_INDICATOR,be.CONSUMPTION_UPDATE].forEach(function(g){y._services.notificationClient.unsubscribe(h,g)})}},{key:"_initializeEnsureReady",value:function(h){var y=this;this._ensureReady=new Promise(function(g,_){y._resolveEnsureReady=g,y._rejectEnsureReady=_}).catch(function(g){if(h)throw g})}}],[{key:"create",value:function(){var d=L.default(P.default.mark(function y(g,_){var w;return P.default.wrap(function(C){for(;;)switch(C.prev=C.next){case 0:if(!(_!=null&&_.twilsockClient)){C.next=2;break}throw new Error("Obsolete usage of ConversationsClient.create() factory method: if you pass twilsock from the outside then you must use ConversationsClient constructor and be prepared to work with uninitialized client.");case 2:return w=new gt(g,_),C.next=5,w._ensureReady;case 5:return C.abrupt("return",w);case 6:case"end":return C.stop()}},y)}));function h(y,g){return d.apply(this,arguments)}return h}()},{key:"parsePushNotification",value:function(h){if(gt._logger.debug("parsePushNotification, notificationPayload=",h),typeof h.aps<"u"){if(!h.twi_message_type)throw new Error("Provided push notification payload does not contain Programmable Chat push notification type");var y=gt._parsePushNotificationChatData(h),g=h.aps,_,w=null;if(typeof g.alert=="string")_=g.alert||null;else{var S,C;_=((S=g.alert)===null||S===void 0?void 0:S.body)||null,w=((C=g.alert)===null||C===void 0?void 0:C.title)||null}return new k({title:w,body:_,sound:g.sound||null,badge:g.badge||null,action:g.category||null,type:h.twi_message_type,data:y})}if(typeof h.data<"u"){var B=h.data;if(!B.twi_message_type)throw new Error("Provided push notification payload does not contain Programmable Chat push notification type");var U=gt._parsePushNotificationChatData(h.data);return new k({title:B.twi_title||null,body:B.twi_body||null,sound:B.twi_sound||null,badge:null,action:B.twi_action||null,type:B.twi_message_type,data:U})}throw new Error("Provided push notification payload is not Programmable Chat notification")}},{key:"_parsePushNotificationChatData",value:function(h){var y={};for(var g in gt._supportedPushDataFields){var _=h[g];if(!(typeof _>"u"||_===null)){if(g==="message_index"||g==="media_count"){var w=bt(_);w!==null&&(y[gt._supportedPushDataFields[g]]=w);continue}if(g==="media"){if(typeof _=="string")try{y[gt._supportedPushDataFields[g]]=JSON.parse(_)}catch{gt._logger.debug("Media message notification parsing error")}continue}y[gt._supportedPushDataFields[g]]=_}}return y}},{key:"populateInitRegistrations",value:function(h){h.populateInitRegistrations([be.TYPING_INDICATOR]),J.SyncClient.populateInitRegistrations(h)}}]),f}(I.ReplayEventEmitter),Se.default(lt,"conversationAdded","conversationAdded"),Se.default(lt,"conversationJoined","conversationJoined"),Se.default(lt,"conversationLeft","conversationLeft"),Se.default(lt,"conversationRemoved","conversationRemoved"),Se.default(lt,"conversationUpdated","conversationUpdated"),Se.default(lt,"participantJoined","participantJoined"),Se.default(lt,"participantLeft","participantLeft"),Se.default(lt,"participantUpdated","participantUpdated"),Se.default(lt,"messageAdded","messageAdded"),Se.default(lt,"messageRemoved","messageRemoved"),Se.default(lt,"messageUpdated","messageUpdated"),Se.default(lt,"tokenAboutToExpire","tokenAboutToExpire"),Se.default(lt,"tokenExpired","tokenExpired"),Se.default(lt,"typingEnded","typingEnded"),Se.default(lt,"typingStarted","typingStarted"),Se.default(lt,"pushNotification","pushNotification"),Se.default(lt,"userSubscribed","userSubscribed"),Se.default(lt,"userUnsubscribed","userUnsubscribed"),Se.default(lt,"userUpdated","userUpdated"),Se.default(lt,"stateChanged","stateChanged"),Se.default(lt,"initialized","initialized"),Se.default(lt,"initFailed","initFailed"),Se.default(lt,"connectionStateChanged","connectionStateChanged"),Se.default(lt,"connectionError","connectionError"),Se.default(lt,"version",E),Se.default(lt,"_logger",Dt.scope("Client")),Se.default(lt,"_supportedPushChannels",["fcm","apn"]),Se.default(lt,"_supportedPushDataFields",{conversation_sid:"conversationSid",conversation_title:"conversationTitle",message_sid:"messageSid",message_index:"messageIndex",media_count:"mediaCount",media:"media"}),lt),Ce([D.deprecated("token"),de("design:type",String),de("design:paramtypes",[])],e.Client.prototype,"token",null),Ce([b.validateTypesAsync(b.nonEmptyString),de("design:type",Function),de("design:paramtypes",[String]),de("design:returntype",Promise)],e.Client.prototype,"updateToken",null),Ce([b.validateTypesAsync(b.nonEmptyString),de("design:type",Function),de("design:paramtypes",[String]),de("design:returntype",Promise)],e.Client.prototype,"getConversationBySid",null),Ce([b.validateTypesAsync(b.nonEmptyString),de("design:type",Function),de("design:paramtypes",[String]),de("design:returntype",Promise)],e.Client.prototype,"peekConversationBySid",null),Ce([b.validateTypesAsync(b.nonEmptyString),de("design:type",Function),de("design:paramtypes",[String]),de("design:returntype",Promise)],e.Client.prototype,"getConversationByUniqueName",null),Ce([b.validateTypesAsync(["undefined",b.objectSchema("conversation options",{friendlyName:["string","undefined"],isPrivate:["boolean","undefined"],uniqueName:["string","undefined"]})]),de("design:type",Function),de("design:paramtypes",[Object]),de("design:returntype",Promise)],e.Client.prototype,"createConversation",null),Ce([b.validateTypesAsync(b.literal("fcm","apn"),"string"),de("design:type",Function),de("design:paramtypes",[String,String]),de("design:returntype",Promise)],e.Client.prototype,"setPushRegistrationId",null),Ce([b.validateTypesAsync(b.literal("fcm","apn")),de("design:type",Function),de("design:paramtypes",[String]),de("design:returntype",Promise)],e.Client.prototype,"unsetPushRegistrationId",null),Ce([b.validateTypesAsync(b.literal("fcm","apn"),b.nonEmptyString),de("design:type",Function),de("design:paramtypes",[String,String]),de("design:returntype",Promise)],e.Client.prototype,"removePushRegistrations",null),Ce([b.validateTypesAsync(b.pureObject),de("design:type",Function),de("design:paramtypes",[Object]),de("design:returntype",Promise)],e.Client.prototype,"handlePushNotification",null),Ce([b.validateTypesAsync(b.nonEmptyString),de("design:type",Function),de("design:paramtypes",[String]),de("design:returntype",Promise)],e.Client.prototype,"getUser",null),Ce([b.validateTypesAsync(b.nonEmptyArray("strings","string")),de("design:type",Function),de("design:paramtypes",[Array]),de("design:returntype",V.CancellablePromise)],e.Client.prototype,"getTemporaryContentUrlsForMediaSids",null),Ce([b.validateTypesAsync(b.nonEmptyArray("media",Je)),de("design:type",Function),de("design:paramtypes",[Array]),de("design:returntype",V.CancellablePromise)],e.Client.prototype,"getTemporaryContentUrlsForMedia",null),Ce([D.deprecated("Client.create()","new Client()"),b.validateTypesAsync("string",["undefined",b.pureObject]),de("design:type",Function),de("design:paramtypes",[String,Object]),de("design:returntype",Promise)],e.Client,"create",null),Ce([b.validateTypes(b.pureObject),de("design:type",Function),de("design:paramtypes",[Object]),de("design:returntype",k)],e.Client,"parsePushNotification",null),e.Client=gt=Ce([b.validateConstructorTypes(b.nonEmptyString,[b.pureObject,"undefined"]),de("design:paramtypes",[String,Object])],e.Client),Object.defineProperty(e,"CancellablePromise",{enumerable:!0,get:function(){return V.CancellablePromise}}),e.AggregatedDeliveryReceipt=Ge,e.ChannelMetadata=ie,e.ContentTemplate=st,e.ContentTemplateVariable=at,e.Conversation=At,e.DetailedDeliveryReceipt=et,e.EmailRecipientDescriptor=Jt,e.Media=Je,e.Message=Ot,e.MessageBuilder=or,e.NotificationTypes=be,e.Participant=K,e.PushNotification=k,e.RestPaginator=He,e.UnknownRecipientDescriptor=ur,e.UnsentMessage=ci,e.User=ye})(UT);const xn=new $a("twilio-chat");class k$ extends tm{constructor(){super(...arguments);ht(this,"client");ht(this,"conversation")}async create(){const{token:r,identity:n}=await this.issueChatToken();this.identity=n,xn.info(`Connecting chat, identity: ${n}, token: ${r}`);const i=new UT.Client(r);i.on("initialized",()=>{xn.info("client: initialized"),this.events.triggerEvent("initialized")}),i.on("tokenAboutToExpire",()=>{xn.info("client: tokenAboutToExpire"),this.refreshToken()}),i.on("tokenExpired",()=>{xn.info("client: tokenExpired"),this.refreshToken()}),this.client=i}async refreshToken(){const{token:r}=await this.issueChatToken();await this.client.updateToken(r)}async join(r){const n=await this.client.getConversationBySid(r);n.status==="joined"?xn.info("already joined conversation:",r):(await n.join(),xn.info("successfully joined conversation:",r)),this.conversation=n}async preview(r){await(await this.conversation.getParticipantByIdentity(this.identity)).updateAttributes({chat_preview:r,chat_preview_updated_at:new Date().toJSON()})}async destroy(){this.conversation=null,this.client&&(await this.client.shutdown(),this.client=null)}async fetchMessages(r){return(await this.conversation.getMessages()).items.map(i=>{const a=R0(i);return r[a.$index]&&(a.file=r[a.$index]),this.trackInTask(a),a})}async sendMessage(r){try{const n=await this.conversation.sendMessage(JSON.stringify(r));return xn.info(`Message sent from ${this.conversation.sid}, index: ${n}`),n}catch(n){xn.warn(`Failed to send a message from ${this.conversation.sid}`,{error:n})}}startTyping(){this.conversation&&this.conversation.typing()}stopTyping(){}registerConversationEvents(){this.registerEvents(this.conversation)}registerEvents(r){r.on("messageAdded",n=>{const i=R0(n);xn.info(`Message added from ${this.conversation.sid}, index: ${i.$index}, sid: ${i.$sid}, timestamp: ${i.$timestamp}, user type: ${i.$userType}`),i.$userType!=="end_user"&&this.ping(),this.trackInTask(i),this.events.triggerEvent("message",i)}),r.on("participantJoined",n=>{xn.info("conversation: memberJoined",n),this.events.triggerEvent("memberJoined",n.identity)}),r.on("participantLeft",n=>{xn.info("conversation: memberLeft",n),this.events.triggerEvent("memberLeft",n.identity)}),r.on("typingStarted",n=>{this.events.triggerEvent("typingStarted",n.identity)}),r.on("typingEnded",n=>{this.events.triggerEvent("typingEnded",n.identity)})}}ht(k$,"type","twilio_conversations");rm(k$);function R0(e){const{index:t,sid:r,author:n,dateCreated:i,body:a}=e,[s,o]=n.split("-");let u=0;o&&(u=parseInt(o,10));const c={$index:t,$sid:r,$timestamp:i,$userType:s,$userId:u};try{const l=JSON.parse(a);return l.message&&!l.type?{...c,...l,type:"message"}:{...c,...l}}catch(l){return xn.warn("Format message failed",{error:l,data:a}),{...c,type:"text",content:a}}}var Tv={exports:{}},Da=rf;function rf(){}rf.mixin=function(e){var t=e.prototype||e;t.isWildEmitter=!0,t.on=function(r,n,i){this.callbacks=this.callbacks||{};var a=arguments.length===3,s=a?arguments[1]:void 0,o=a?arguments[2]:arguments[1];return o._groupName=s,(this.callbacks[r]=this.callbacks[r]||[]).push(o),this},t.once=function(r,n,i){var a=this,s=arguments.length===3,o=s?arguments[1]:void 0,u=s?arguments[2]:arguments[1];function c(){a.off(r,c),u.apply(this,arguments)}return this.on(r,o,c),this},t.releaseGroup=function(r){this.callbacks=this.callbacks||{};var n,i,a,s;for(n in this.callbacks)for(s=this.callbacks[n],i=0,a=s.length;i<a;i++)s[i]._groupName===r&&(s.splice(i,1),i--,a--);return this},t.off=function(r,n){this.callbacks=this.callbacks||{};var i=this.callbacks[r],a;return i?arguments.length===1?(delete this.callbacks[r],this):(a=i.indexOf(n),a!==-1&&(i.splice(a,1),i.length===0&&delete this.callbacks[r]),this):this},t.emit=function(r){this.callbacks=this.callbacks||{};var n=[].slice.call(arguments,1),i=this.callbacks[r],a=this.getWildcardCallbacks(r),s,o,u;if(i)for(u=i.slice(),s=0,o=u.length;s<o&&u[s];++s)u[s].apply(this,n);if(a)for(o=a.length,u=a.slice(),s=0,o=u.length;s<o&&u[s];++s)u[s].apply(this,[r].concat(n));return this},t.getWildcardCallbacks=function(r){this.callbacks=this.callbacks||{};var n,i,a=[];for(n in this.callbacks)i=n.split("*"),(n==="*"||i.length===2&&r.slice(0,i[0].length)===i[0])&&(a=a.concat(this.callbacks[n]));return a}};rf.mixin(rf);var R$={exports:{}};(function(e){(function(t,r){e.exports?e.exports=r():t.prefix=r(t)})(je,function(t){var r=function(l){for(var p=1,v=arguments.length,m;p<v;p++)for(m in arguments[p])Object.prototype.hasOwnProperty.call(arguments[p],m)&&(l[m]=arguments[p][m]);return l},n={template:"[%t] %l:",levelFormatter:function(l){return l.toUpperCase()},nameFormatter:function(l){return l||"root"},timestampFormatter:function(l){return l.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")},format:void 0},i,a={},s=function(l){if(!l||!l.getLogger)throw new TypeError("Argument is not a root logger");i=l},o=function(l,p){if(!l||!l.setLevel)throw new TypeError("Argument is not a logger");var v=l.methodFactory,m=l.name||"",b=a[m]||a[""]||n;function T(I,R,x){var N=v(I,R,x),j=a[x]||a[""],X=j.template.indexOf("%t")!==-1,J=j.template.indexOf("%l")!==-1,V=j.template.indexOf("%n")!==-1;return function(){for(var D="",te=arguments.length,ue=Array(te),ee=0;ee<te;ee++)ue[ee]=arguments[ee];if(m||!a[x]){var ge=j.timestampFormatter(new Date),L=j.levelFormatter(I),pe=j.nameFormatter(x);j.format?D+=j.format(L,pe,ge):(D+=j.template,X&&(D=D.replace(/%t/,ge)),J&&(D=D.replace(/%l/,L)),V&&(D=D.replace(/%n/,pe))),ue.length&&typeof ue[0]=="string"?ue[0]=D+" "+ue[0]:ue.unshift(D)}N.apply(void 0,ue)}}return a[m]||(l.methodFactory=T),p=p||{},p.template&&(p.format=void 0),a[m]=r({},b,p),l.setLevel(l.getLevel()),i||l.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"),l},u={reg:s,apply:o},c;return t&&(c=t.prefix,u.noConflict=function(){return t.prefix===u&&(t.prefix=c),u}),u})})(R$);var kQ=R$.exports,Cv={exports:{}},RQ={"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"},"error:input:unsanitized":{type:"error:input:unsanitized",description:"Input is not sanitized"}};(function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.NexmoApiError=t.NexmoClientError=void 0;const r=RQ,n=Ar;function i(o,u){var c,l;u!=null&&u.code&&(u.type=u.code,delete u.code),Object.assign(o,u),o.message="type: "+o.type+", description: "+((l=(c=o.description)!==null&&c!==void 0?c:o.detail)!==null&&l!==void 0?l:"")}class a{constructor(u){const c=r[u];c?i(this,c):(this.message=u&&u.message?u.message:u,this.stack=u.stack),this.log=n.getLogger(this.constructor.name),this.log.error(this),this.name="NexmoClientError",typeof je.NXMbugsnagClient<"u"&&je.NXMbugsnagClient.notify(this,{severity:"info"})}}t.NexmoClientError=a;class s{constructor(u){this.log=n.getLogger(this.constructor.name),u?i(this,u):(this.message=u&&u.message?u.message:u,this.stack=u&&u.stack?u.stack:new Error().stack),this.name="NexmoApiError",this.log=n.getLogger(this.constructor.name),this.log.error(this),typeof je.NXMbugsnagClient<"u"&&je.NXMbugsnagClient.notify(this,{severity:"info"})}}t.NexmoApiError=s,e.exports={NexmoClientError:a,NexmoApiError:s}})(Cv,Cv.exports);var Gn=Cv.exports,Ev={exports:{}},Gg={},Gf={},zi={},Xu={},yi={},Qu={},Ki={},To={},Zu={},bi={};Object.defineProperty(bi,"__esModule",{value:!0});bi.ERROR_PACKET=bi.PACKET_TYPES_REVERSE=bi.PACKET_TYPES=void 0;const _i=Object.create(null);bi.PACKET_TYPES=_i;_i.open="0";_i.close="1";_i.ping="2";_i.pong="3";_i.message="4";_i.upgrade="5";_i.noop="6";const $$=Object.create(null);bi.PACKET_TYPES_REVERSE=$$;Object.keys(_i).forEach(e=>{$$[_i[e]]=e});const $Q={type:"error",data:"parser error"};bi.ERROR_PACKET=$Q;Object.defineProperty(Zu,"__esModule",{value:!0});Zu.encodePacket=void 0;Zu.encodePacketToBinary=OQ;const IQ=bi,I$=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",O$=typeof ArrayBuffer=="function",A$=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,P$=({type:e,data:t},r,n)=>I$&&t instanceof Blob?r?n(t):$0(t,n):O$&&(t instanceof ArrayBuffer||A$(t))?r?n(t):$0(new Blob([t]),n):n(IQ.PACKET_TYPES[e]+(t||""));Zu.encodePacket=P$;const $0=(e,t)=>{const r=new FileReader;return r.onload=function(){const n=r.result.split(",")[1];t("b"+(n||""))},r.readAsDataURL(e)};function I0(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let ah;function OQ(e,t){if(I$&&e.data instanceof Blob)return e.data.arrayBuffer().then(I0).then(t);if(O$&&(e.data instanceof ArrayBuffer||A$(e.data)))return t(I0(e.data));P$(e,!1,r=>{ah||(ah=new TextEncoder),t(ah.encode(r))})}var Hf={},lo={};Object.defineProperty(lo,"__esModule",{value:!0});lo.decode=lo.encode=void 0;const zs="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",tu=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e<zs.length;e++)tu[zs.charCodeAt(e)]=e;const AQ=e=>{let t=new Uint8Array(e),r,n=t.length,i="";for(r=0;r<n;r+=3)i+=zs[t[r]>>2],i+=zs[(t[r]&3)<<4|t[r+1]>>4],i+=zs[(t[r+1]&15)<<2|t[r+2]>>6],i+=zs[t[r+2]&63];return n%3===2?i=i.substring(0,i.length-1)+"=":n%3===1&&(i=i.substring(0,i.length-2)+"=="),i};lo.encode=AQ;const PQ=e=>{let t=e.length*.75,r=e.length,n,i=0,a,s,o,u;e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);const c=new ArrayBuffer(t),l=new Uint8Array(c);for(n=0;n<r;n+=4)a=tu[e.charCodeAt(n)],s=tu[e.charCodeAt(n+1)],o=tu[e.charCodeAt(n+2)],u=tu[e.charCodeAt(n+3)],l[i++]=a<<2|s>>4,l[i++]=(s&15)<<4|o>>2,l[i++]=(o&3)<<6|u&63;return c};lo.decode=PQ;Object.defineProperty(Hf,"__esModule",{value:!0});Hf.decodePacket=void 0;const Kc=bi,MQ=lo,xQ=typeof ArrayBuffer=="function",NQ=(e,t)=>{if(typeof e!="string")return{type:"message",data:M$(e,t)};const r=e.charAt(0);return r==="b"?{type:"message",data:LQ(e.substring(1),t)}:Kc.PACKET_TYPES_REVERSE[r]?e.length>1?{type:Kc.PACKET_TYPES_REVERSE[r],data:e.substring(1)}:{type:Kc.PACKET_TYPES_REVERSE[r]}:Kc.ERROR_PACKET};Hf.decodePacket=NQ;const LQ=(e,t)=>{if(xQ){const r=(0,MQ.decode)(e);return M$(r,t)}else return{base64:!0,data:e}},M$=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.decodePayload=e.decodePacket=e.encodePayload=e.encodePacket=e.protocol=void 0,e.createPacketEncoderStream=o,e.createPacketDecoderStream=p;const t=Zu;Object.defineProperty(e,"encodePacket",{enumerable:!0,get:function(){return t.encodePacket}});const r=Hf;Object.defineProperty(e,"decodePacket",{enumerable:!0,get:function(){return r.decodePacket}});const n=bi,i="",a=(v,m)=>{const b=v.length,T=new Array(b);let I=0;v.forEach((R,x)=>{(0,t.encodePacket)(R,!1,N=>{T[x]=N,++I===b&&m(T.join(i))})})};e.encodePayload=a;const s=(v,m)=>{const b=v.split(i),T=[];for(let I=0;I<b.length;I++){const R=(0,r.decodePacket)(b[I],m);if(T.push(R),R.type==="error")break}return T};e.decodePayload=s;function o(){return new TransformStream({transform(v,m){(0,t.encodePacketToBinary)(v,b=>{const T=b.length;let I;if(T<126)I=new Uint8Array(1),new DataView(I.buffer).setUint8(0,T);else if(T<65536){I=new Uint8Array(3);const R=new DataView(I.buffer);R.setUint8(0,126),R.setUint16(1,T)}else{I=new Uint8Array(9);const R=new DataView(I.buffer);R.setUint8(0,127),R.setBigUint64(1,BigInt(T))}v.data&&typeof v.data!="string"&&(I[0]|=128),m.enqueue(I),m.enqueue(b)})}})}let u;function c(v){return v.reduce((m,b)=>m+b.length,0)}function l(v,m){if(v[0].length===m)return v.shift();const b=new Uint8Array(m);let T=0;for(let I=0;I<m;I++)b[I]=v[0][T++],T===v[0].length&&(v.shift(),T=0);return v.length&&T<v[0].length&&(v[0]=v[0].slice(T)),b}function p(v,m){u||(u=new TextDecoder);const b=[];let T=0,I=-1,R=!1;return new TransformStream({transform(x,N){for(b.push(x);;){if(T===0){if(c(b)<1)break;const j=l(b,1);R=(j[0]&128)===128,I=j[0]&127,I<126?T=3:I===126?T=1:T=2}else if(T===1){if(c(b)<2)break;const j=l(b,2);I=new DataView(j.buffer,j.byteOffset,j.length).getUint16(0),T=3}else if(T===2){if(c(b)<8)break;const j=l(b,8),X=new DataView(j.buffer,j.byteOffset,j.length),J=X.getUint32(0);if(J>Math.pow(2,21)-1){N.enqueue(n.ERROR_PACKET);break}I=J*Math.pow(2,32)+X.getUint32(4),T=3}else{if(c(b)<I)break;const j=l(b,I);N.enqueue((0,r.decodePacket)(R?j:u.decode(j),m)),T=0}if(I===0||I>v){N.enqueue(n.ERROR_PACKET);break}}}})}e.protocol=4})(To);function en(e){if(e)return DQ(e)}function DQ(e){for(var t in en.prototype)e[t]=en.prototype[t];return e}en.prototype.on=en.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};en.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this};en.prototype.off=en.prototype.removeListener=en.prototype.removeAllListeners=en.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var r=this._callbacks["$"+e];if(!r)return this;if(arguments.length==1)return delete this._callbacks["$"+e],this;for(var n,i=0;i<r.length;i++)if(n=r[i],n===t||n.fn===t){r.splice(i,1);break}return r.length===0&&delete this._callbacks["$"+e],this};en.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),r=this._callbacks["$"+e],n=1;n<arguments.length;n++)t[n-1]=arguments[n];if(r){r=r.slice(0);for(var n=0,i=r.length;n<i;++n)r[n].apply(this,t)}return this};en.prototype.emitReserved=en.prototype.emit;en.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]};en.prototype.hasListeners=function(e){return!!this.listeners(e).length};const jQ=Object.freeze(Object.defineProperty({__proto__:null,Emitter:en},Symbol.toStringTag,{value:"Module"})),Co=FT(jQ);var oi={},pn={};Object.defineProperty(pn,"__esModule",{value:!0});pn.defaultBinaryType=pn.globalThisShim=pn.nextTick=void 0;pn.createCookieJar=FQ;pn.nextTick=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,r)=>r(t,0);pn.globalThisShim=typeof self<"u"?self:typeof window<"u"?window:Function("return this")();pn.defaultBinaryType="arraybuffer";function FQ(){}Object.defineProperty(oi,"__esModule",{value:!0});oi.pick=UQ;oi.installTimerFunctions=zQ;oi.byteLength=GQ;oi.randomString=VQ;const va=pn;function UQ(e,...t){return t.reduce((r,n)=>(e.hasOwnProperty(n)&&(r[n]=e[n]),r),{})}const BQ=va.globalThisShim.setTimeout,qQ=va.globalThisShim.clearTimeout;function zQ(e,t){t.useNativeTimers?(e.setTimeoutFn=BQ.bind(va.globalThisShim),e.clearTimeoutFn=qQ.bind(va.globalThisShim)):(e.setTimeoutFn=va.globalThisShim.setTimeout.bind(va.globalThisShim),e.clearTimeoutFn=va.globalThisShim.clearTimeout.bind(va.globalThisShim))}const WQ=1.33;function GQ(e){return typeof e=="string"?HQ(e):Math.ceil((e.byteLength||e.size)*WQ)}function HQ(e){let t=0,r=0;for(let n=0,i=e.length;n<i;n++)t=e.charCodeAt(n),t<128?r+=1:t<2048?r+=2:t<55296||t>=57344?r+=3:(n++,r+=4);return r}function VQ(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}var ec={};Object.defineProperty(ec,"__esModule",{value:!0});ec.encode=KQ;ec.decode=JQ;function KQ(e){let t="";for(let r in e)e.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(e[r]));return t}function JQ(e){let t={},r=e.split("&");for(let n=0,i=r.length;n<i;n++){let a=r[n].split("=");t[decodeURIComponent(a[0])]=decodeURIComponent(a[1])}return t}var kv={exports:{}},sh,O0;function YQ(){if(O0)return sh;O0=1;var e=1e3,t=e*60,r=t*60,n=r*24,i=n*7,a=n*365.25;sh=function(l,p){p=p||{};var v=typeof l;if(v==="string"&&l.length>0)return s(l);if(v==="number"&&isFinite(l))return p.long?u(l):o(l);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(l))};function s(l){if(l=String(l),!(l.length>100)){var p=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(l);if(p){var v=parseFloat(p[1]),m=(p[2]||"ms").toLowerCase();switch(m){case"years":case"year":case"yrs":case"yr":case"y":return v*a;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*r;case"minutes":case"minute":case"mins":case"min":case"m":return v*t;case"seconds":case"second":case"secs":case"sec":case"s":return v*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return v;default:return}}}}function o(l){var p=Math.abs(l);return p>=n?Math.round(l/n)+"d":p>=r?Math.round(l/r)+"h":p>=t?Math.round(l/t)+"m":p>=e?Math.round(l/e)+"s":l+"ms"}function u(l){var p=Math.abs(l);return p>=n?c(l,p,n,"day"):p>=r?c(l,p,r,"hour"):p>=t?c(l,p,t,"minute"):p>=e?c(l,p,e,"second"):l+" ms"}function c(l,p,v,m){var b=p>=v*1.5;return Math.round(l/v)+" "+m+(b?"s":"")}return sh}function XQ(e){r.debug=r,r.default=r,r.coerce=u,r.disable=a,r.enable=i,r.enabled=s,r.humanize=YQ(),r.destroy=c,Object.keys(e).forEach(l=>{r[l]=e[l]}),r.names=[],r.skips=[],r.formatters={};function t(l){let p=0;for(let v=0;v<l.length;v++)p=(p<<5)-p+l.charCodeAt(v),p|=0;return r.colors[Math.abs(p)%r.colors.length]}r.selectColor=t;function r(l){let p,v=null,m,b;function T(...I){if(!T.enabled)return;const R=T,x=Number(new Date),N=x-(p||x);R.diff=N,R.prev=p,R.curr=x,p=x,I[0]=r.coerce(I[0]),typeof I[0]!="string"&&I.unshift("%O");let j=0;I[0]=I[0].replace(/%([a-zA-Z%])/g,(J,V)=>{if(J==="%%")return"%";j++;const D=r.formatters[V];if(typeof D=="function"){const te=I[j];J=D.call(R,te),I.splice(j,1),j--}return J}),r.formatArgs.call(R,I),(R.log||r.log).apply(R,I)}return T.namespace=l,T.useColors=r.useColors(),T.color=r.selectColor(l),T.extend=n,T.destroy=r.destroy,Object.defineProperty(T,"enabled",{enumerable:!0,configurable:!1,get:()=>v!==null?v:(m!==r.namespaces&&(m=r.namespaces,b=r.enabled(l)),b),set:I=>{v=I}}),typeof r.init=="function"&&r.init(T),T}function n(l,p){const v=r(this.namespace+(typeof p>"u"?":":p)+l);return v.log=this.log,v}function i(l){r.save(l),r.namespaces=l,r.names=[],r.skips=[];let p;const v=(typeof l=="string"?l:"").split(/[\s,]+/),m=v.length;for(p=0;p<m;p++)v[p]&&(l=v[p].replace(/\*/g,".*?"),l[0]==="-"?r.skips.push(new RegExp("^"+l.slice(1)+"$")):r.names.push(new RegExp("^"+l+"$")))}function a(){const l=[...r.names.map(o),...r.skips.map(o).map(p=>"-"+p)].join(",");return r.enable(""),l}function s(l){if(l[l.length-1]==="*")return!0;let p,v;for(p=0,v=r.skips.length;p<v;p++)if(r.skips[p].test(l))return!1;for(p=0,v=r.names.length;p<v;p++)if(r.names[p].test(l))return!0;return!1}function o(l){return l.toString().substring(2,l.toString().length-2).replace(/\.\*\?$/,"*")}function u(l){return l instanceof Error?l.stack||l.message:l}function c(){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 r.enable(r.load()),r}var QQ=XQ;(function(e,t){t.formatArgs=n,t.save=i,t.load=a,t.useColors=r,t.storage=s(),t.destroy=(()=>{let u=!1;return()=>{u||(u=!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`."))}})(),t.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 r(){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 u;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&&(u=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(u[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function n(u){if(u[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+u[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const c="color: "+this.color;u.splice(1,0,c,"color: inherit");let l=0,p=0;u[0].replace(/%[a-zA-Z%]/g,v=>{v!=="%%"&&(l++,v==="%c"&&(p=l))}),u.splice(p,0,c)}t.log=console.debug||console.log||(()=>{});function i(u){try{u?t.storage.setItem("debug",u):t.storage.removeItem("debug")}catch{}}function a(){let u;try{u=t.storage.getItem("debug")}catch{}return!u&&typeof process<"u"&&"env"in process&&(u=process.env.DEBUG),u}function s(){try{return localStorage}catch{}}e.exports=QQ(t);const{formatters:o}=e.exports;o.j=function(u){try{return JSON.stringify(u)}catch(c){return"[UnexpectedJSONParseError]: "+c.message}}})(kv,kv.exports);var ui=kv.exports,ZQ=je&&je.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Ki,"__esModule",{value:!0});Ki.Transport=Ki.TransportError=void 0;const eZ=To,tZ=Co,rZ=oi,nZ=ec,iZ=ZQ(ui),aZ=(0,iZ.default)("engine.io-client:transport");class x$ extends Error{constructor(t,r,n){super(t),this.description=r,this.context=n,this.type="TransportError"}}Ki.TransportError=x$;class sZ extends tZ.Emitter{constructor(t){super(),this.writable=!1,(0,rZ.installTimerFunctions)(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,r,n){return super.emitReserved("error",new x$(t,r,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(t){this.readyState==="open"?this.write(t):aZ("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const r=(0,eZ.decodePacket)(t,this.socket.binaryType);this.onPacket(r)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,r={}){return t+"://"+this._hostname()+this._port()+this.opts.path+this._query(r)}_hostname(){const t=this.opts.hostname;return t.indexOf(":")===-1?t:"["+t+"]"}_port(){return this.opts.port&&(this.opts.secure&&+(this.opts.port!==443)||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(t){const r=(0,nZ.encode)(t);return r.length?"?"+r:""}}Ki.Transport=sZ;var oZ=je&&je.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Qu,"__esModule",{value:!0});Qu.Polling=void 0;const uZ=Ki,cZ=oi,A0=To,lZ=oZ(ui),Kn=(0,lZ.default)("engine.io-client:polling");class fZ extends uZ.Transport{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(t){this.readyState="pausing";const r=()=>{Kn("paused"),this.readyState="paused",t()};if(this._polling||!this.writable){let n=0;this._polling&&(Kn("we are currently polling - waiting to pause"),n++,this.once("pollComplete",function(){Kn("pre-pause polling complete"),--n||r()})),this.writable||(Kn("we are currently writing - waiting to pause"),n++,this.once("drain",function(){Kn("pre-pause writing complete"),--n||r()}))}else r()}_poll(){Kn("polling"),this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){Kn("polling got data %s",t);const r=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,A0.decodePayload)(t,this.socket.binaryType).forEach(r),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"?this._poll():Kn('ignoring poll - transport state "%s"',this.readyState))}doClose(){const t=()=>{Kn("writing close packet"),this.write([{type:"close"}])};this.readyState==="open"?(Kn("transport open - closing"),t()):(Kn("transport not open - deferring close"),this.once("open",t))}write(t){this.writable=!1,(0,A0.encodePayload)(t,r=>{this.doWrite(r,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",r=this.query||{};return this.opts.timestampRequests!==!1&&(r[this.opts.timestampParam]=(0,cZ.randomString)()),!this.supportsBinary&&!r.sid&&(r.b64=1),this.createUri(t,r)}}Qu.Polling=fZ;var Vf={};Object.defineProperty(Vf,"__esModule",{value:!0});Vf.hasCORS=void 0;let N$=!1;try{N$=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}Vf.hasCORS=N$;var dZ=je&&je.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(yi,"__esModule",{value:!0});yi.XHR=yi.Request=yi.BaseXHR=void 0;const pZ=Qu,hZ=Co,P0=oi,L$=pn,vZ=Vf,mZ=dZ(ui),Rv=(0,mZ.default)("engine.io-client:polling");function gZ(){}class D$ extends pZ.Polling{constructor(t){if(super(t),typeof location<"u"){const r=location.protocol==="https:";let n=location.port;n||(n=r?"443":"80"),this.xd=typeof location<"u"&&t.hostname!==location.hostname||n!==t.port}}doWrite(t,r){const n=this.request({method:"POST",data:t});n.on("success",r),n.on("error",(i,a)=>{this.onError("xhr post error",i,a)})}doPoll(){Rv("xhr poll");const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(r,n)=>{this.onError("xhr poll error",r,n)}),this.pollXhr=t}}yi.BaseXHR=D$;class ni extends hZ.Emitter{constructor(t,r,n){super(),this.createRequest=t,(0,P0.installTimerFunctions)(this,n),this._opts=n,this._method=n.method||"GET",this._uri=r,this._data=n.data!==void 0?n.data:null,this._create()}_create(){var t;const r=(0,P0.pick)(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");r.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(r);try{Rv("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{}(t=this._opts.cookieJar)===null||t===void 0||t.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))},Rv("xhr data %s",this._data),n.send(this._data)}catch(i){this.setTimeoutFn(()=>{this._onError(i)},0);return}typeof document<"u"&&(this._index=ni.requestsCount++,ni.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=gZ,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete ni.requests[this._index],this._xhr=null}}_onLoad(){const t=this._xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}yi.Request=ni;ni.requestsCount=0;ni.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",M0);else if(typeof addEventListener=="function"){const e="onpagehide"in L$.globalThisShim?"pagehide":"unload";addEventListener(e,M0,!1)}}function M0(){for(let e in ni.requests)ni.requests.hasOwnProperty(e)&&ni.requests[e].abort()}const yZ=function(){const e=j$({xdomain:!1});return e&&e.responseType!==null}();class bZ extends D${constructor(t){super(t);const r=t&&t.forceBase64;this.supportsBinary=yZ&&!r}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new ni(j$,this.uri(),t)}}yi.XHR=bZ;function j$(e){const t=e.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||vZ.hasCORS))return new XMLHttpRequest}catch{}if(!t)try{return new L$.globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}var Ra={},_Z=je&&je.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Ra,"__esModule",{value:!0});Ra.WS=Ra.BaseWS=void 0;const wZ=Ki,x0=oi,SZ=To,$v=pn,TZ=_Z(ui),CZ=(0,TZ.default)("engine.io-client:websocket"),F$=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class U$ extends wZ.Transport{get name(){return"websocket"}doOpen(){const t=this.uri(),r=this.opts.protocols,n=F$?{}:(0,x0.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(t,r,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=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let r=0;r<t.length;r++){const n=t[r],i=r===t.length-1;(0,SZ.encodePacket)(n,this.supportsBinary,a=>{try{this.doWrite(n,a)}catch{CZ("websocket closed before onclose event")}i&&(0,$v.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 t=this.opts.secure?"wss":"ws",r=this.query||{};return this.opts.timestampRequests&&(r[this.opts.timestampParam]=(0,x0.randomString)()),this.supportsBinary||(r.b64=1),this.createUri(t,r)}}Ra.BaseWS=U$;const oh=$v.globalThisShim.WebSocket||$v.globalThisShim.MozWebSocket;class EZ extends U${createSocket(t,r,n){return F$?new oh(t,r,n):r?new oh(t,r):new oh(t)}doWrite(t,r){this.ws.send(r)}}Ra.WS=EZ;var tc={},kZ=je&&je.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(tc,"__esModule",{value:!0});tc.WT=void 0;const RZ=Ki,$Z=pn,N0=To,IZ=kZ(ui),Ko=(0,IZ.default)("engine.io-client:webtransport");class OZ extends RZ.Transport{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this._transport.closed.then(()=>{Ko("transport closed gracefully"),this.onClose()}).catch(t=>{Ko("transport closed due to %s",t),this.onError("webtransport error",t)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(t=>{const r=(0,N0.createPacketDecoderStream)(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=t.readable.pipeThrough(r).getReader(),i=(0,N0.createPacketEncoderStream)();i.readable.pipeTo(t.writable),this._writer=i.writable.getWriter();const a=()=>{n.read().then(({done:o,value:u})=>{if(o){Ko("session is closed");return}Ko("received chunk: %o",u),this.onPacket(u),a()}).catch(o=>{Ko("an error occurred while reading: %s",o)})};a();const s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this._writer.write(s).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let r=0;r<t.length;r++){const n=t[r],i=r===t.length-1;this._writer.write(n).then(()=>{i&&(0,$Z.nextTick)(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}}tc.WT=OZ;Object.defineProperty(Xu,"__esModule",{value:!0});Xu.transports=void 0;const AZ=yi,PZ=Ra,MZ=tc;Xu.transports={websocket:PZ.WS,webtransport:MZ.WT,polling:AZ.XHR};var Kf={};Object.defineProperty(Kf,"__esModule",{value:!0});Kf.parse=LZ;const xZ=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,NZ=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function LZ(e){if(e.length>8e3)throw"URI too long";const t=e,r=e.indexOf("["),n=e.indexOf("]");r!=-1&&n!=-1&&(e=e.substring(0,r)+e.substring(r,n).replace(/:/g,";")+e.substring(n,e.length));let i=xZ.exec(e||""),a={},s=14;for(;s--;)a[NZ[s]]=i[s]||"";return r!=-1&&n!=-1&&(a.source=t,a.host=a.host.substring(1,a.host.length-1).replace(/;/g,":"),a.authority=a.authority.replace("[","").replace("]","").replace(/;/g,":"),a.ipv6uri=!0),a.pathNames=DZ(a,a.path),a.queryKey=jZ(a,a.query),a}function DZ(e,t){const r=/\/{2,9}/g,n=t.replace(r,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&n.splice(0,1),t.slice(-1)=="/"&&n.splice(n.length-1,1),n}function jZ(e,t){const r={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,i,a){i&&(r[i]=a)}),r}var FZ=je&&je.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(zi,"__esModule",{value:!0});zi.Socket=zi.SocketWithUpgrade=zi.SocketWithoutUpgrade=void 0;const UZ=Xu,L0=oi,BZ=ec,D0=Kf,qZ=Co,B$=To,uh=pn,zZ=FZ(ui),rr=(0,zZ.default)("engine.io-client:socket"),Iv=typeof addEventListener=="function"&&typeof removeEventListener=="function",lu=[];Iv&&addEventListener("offline",()=>{rr("closing %d connection(s) because the network was lost",lu.length),lu.forEach(e=>e())},!1);class Wi extends qZ.Emitter{constructor(t,r){if(super(),this.binaryType=uh.defaultBinaryType,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,t&&typeof t=="object"&&(r=t,t=null),t){const n=(0,D0.parse)(t);r.hostname=n.host,r.secure=n.protocol==="https"||n.protocol==="wss",r.port=n.port,n.query&&(r.query=n.query)}else r.host&&(r.hostname=(0,D0.parse)(r.host).host);(0,L0.installTimerFunctions)(this,r),this.secure=r.secure!=null?r.secure:typeof location<"u"&&location.protocol==="https:",r.hostname&&!r.port&&(r.port=this.secure?"443":"80"),this.hostname=r.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=r.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},r.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},r),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=(0,BZ.decode)(this.opts.query)),Iv&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(rr("adding listener for the 'offline' event"),this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},lu.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=(0,uh.createCookieJar)()),this._open()}createTransport(t){rr('creating transport "%s"',t);const r=Object.assign({},this.opts.query);r.EIO=B$.protocol,r.transport=t,this.id&&(r.sid=this.id);const n=Object.assign({},this.opts,{query:r,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return rr("options: %j",n),new this._transportsByName[t](n)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const t=this.opts.rememberUpgrade&&Wi.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const r=this.createTransport(t);r.open(),this.setTransport(r)}setTransport(t){rr("setting transport %s",t.name),this.transport&&(rr("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",r=>this._onClose("transport close",r))}onOpen(){rr("socket open"),this.readyState="open",Wi.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(rr('socket receive: type "%s", data "%s"',t.type,t.data),this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const r=new Error("server error");r.code=t.data,this._onError(r);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data);break}else rr('packet received with socket readyState "%s"',this.readyState)}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),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 t=this._getWritablePackets();rr("flushing %d packets in socket",t.length),this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let r=1;for(let n=0;n<this.writeBuffer.length;n++){const i=this.writeBuffer[n].data;if(i&&(r+=(0,L0.byteLength)(i)),n>0&&r>this._maxPayload)return rr("only send %d out of %d packets",n,this.writeBuffer.length),this.writeBuffer.slice(0,n);r+=2}return rr("payload size is %d (max: %d)",r,this._maxPayload),this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const t=Date.now()>this._pingTimeoutTime;return t&&(rr("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,(0,uh.nextTick)(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,r,n){return this._sendPacket("message",t,r,n),this}send(t,r,n){return this._sendPacket("message",t,r,n),this}_sendPacket(t,r,n,i){if(typeof r=="function"&&(i=r,r=void 0),typeof n=="function"&&(i=n,n=null),this.readyState==="closing"||this.readyState==="closed")return;n=n||{},n.compress=n.compress!==!1;const a={type:t,data:r,options:n};this.emitReserved("packetCreate",a),this.writeBuffer.push(a),i&&this.once("flush",i),this.flush()}close(){const t=()=>{this._onClose("forced close"),rr("socket closing - telling transport to close"),this.transport.close()},r=()=>{this.off("upgrade",r),this.off("upgradeError",r),t()},n=()=>{this.once("upgrade",r),this.once("upgradeError",r)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():t()}):this.upgrading?n():t()),this}_onError(t){if(rr("socket error %j",t),Wi.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return rr("trying next transport"),this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,r){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(rr('socket close with reason: "%s"',t),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Iv&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const n=lu.indexOf(this._offlineEventListener);n!==-1&&(rr("removing listener for the 'offline' event"),lu.splice(n,1))}this.readyState="closed",this.id=null,this.emitReserved("close",t,r),this.writeBuffer=[],this._prevBufferLen=0}}}zi.SocketWithoutUpgrade=Wi;Wi.protocol=B$.protocol;class q$ extends Wi{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){rr("starting upgrade probes");for(let t=0;t<this._upgrades.length;t++)this._probe(this._upgrades[t])}}_probe(t){rr('probing transport "%s"',t);let r=this.createTransport(t),n=!1;Wi.priorWebsocketSuccess=!1;const i=()=>{n||(rr('probe transport "%s" opened',t),r.send([{type:"ping",data:"probe"}]),r.once("packet",p=>{if(!n)if(p.type==="pong"&&p.data==="probe"){if(rr('probe transport "%s" pong',t),this.upgrading=!0,this.emitReserved("upgrading",r),!r)return;Wi.priorWebsocketSuccess=r.name==="websocket",rr('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{n||this.readyState!=="closed"&&(rr("changing transport and sending upgrade packet"),l(),this.setTransport(r),r.send([{type:"upgrade"}]),this.emitReserved("upgrade",r),r=null,this.upgrading=!1,this.flush())})}else{rr('probe transport "%s" failed',t);const v=new Error("probe error");v.transport=r.name,this.emitReserved("upgradeError",v)}}))};function a(){n||(n=!0,l(),r.close(),r=null)}const s=p=>{const v=new Error("probe error: "+p);v.transport=r.name,a(),rr('probe transport "%s" failed because of error: %s',t,p),this.emitReserved("upgradeError",v)};function o(){s("transport closed")}function u(){s("socket closed")}function c(p){r&&p.name!==r.name&&(rr('"%s" works - aborting "%s"',p.name,r.name),a())}const l=()=>{r.removeListener("open",i),r.removeListener("error",s),r.removeListener("close",o),this.off("close",u),this.off("upgrading",c)};r.once("open",i),r.once("error",s),r.once("close",o),this.once("close",u),this.once("upgrading",c),this._upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{n||r.open()},200):r.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const r=[];for(let n=0;n<t.length;n++)~this.transports.indexOf(t[n])&&r.push(t[n]);return r}}zi.SocketWithUpgrade=q$;let WZ=class extends q${constructor(t,r={}){const n=typeof t=="object"?t:r;(!n.transports||n.transports&&typeof n.transports[0]=="string")&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(i=>UZ.transports[i]).filter(i=>!!i)),super(t,n)}};zi.Socket=WZ;var Jf={};Object.defineProperty(Jf,"__esModule",{value:!0});Jf.Fetch=void 0;const GZ=Qu;class HZ extends GZ.Polling{doPoll(){this._fetch().then(t=>{if(!t.ok)return this.onError("fetch read error",t.status,t);t.text().then(r=>this.onData(r))}).catch(t=>{this.onError("fetch read error",t)})}doWrite(t,r){this._fetch(t).then(n=>{if(!n.ok)return this.onError("fetch write error",n.status,n);r()}).catch(n=>{this.onError("fetch write error",n)})}_fetch(t){var r;const n=t!==void 0,i=new Headers(this.opts.extraHeaders);return n&&i.set("content-type","text/plain;charset=UTF-8"),(r=this.socket._cookieJar)===null||r===void 0||r.appendCookies(i),fetch(this.uri(),{method:n?"POST":"GET",body:n?t:null,headers:i,credentials:this.opts.withCredentials?"include":"omit"}).then(a=>{var s;return(s=this.socket._cookieJar)===null||s===void 0||s.parseCookies(a.headers.getSetCookie()),a})}}Jf.Fetch=HZ;(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.WebTransport=e.WebSocket=e.NodeWebSocket=e.XHR=e.NodeXHR=e.Fetch=e.nextTick=e.parse=e.installTimerFunctions=e.transports=e.TransportError=e.Transport=e.protocol=e.SocketWithUpgrade=e.SocketWithoutUpgrade=e.Socket=void 0;const t=zi;Object.defineProperty(e,"Socket",{enumerable:!0,get:function(){return t.Socket}});var r=zi;Object.defineProperty(e,"SocketWithoutUpgrade",{enumerable:!0,get:function(){return r.SocketWithoutUpgrade}}),Object.defineProperty(e,"SocketWithUpgrade",{enumerable:!0,get:function(){return r.SocketWithUpgrade}}),e.protocol=t.Socket.protocol;var n=Ki;Object.defineProperty(e,"Transport",{enumerable:!0,get:function(){return n.Transport}}),Object.defineProperty(e,"TransportError",{enumerable:!0,get:function(){return n.TransportError}});var i=Xu;Object.defineProperty(e,"transports",{enumerable:!0,get:function(){return i.transports}});var a=oi;Object.defineProperty(e,"installTimerFunctions",{enumerable:!0,get:function(){return a.installTimerFunctions}});var s=Kf;Object.defineProperty(e,"parse",{enumerable:!0,get:function(){return s.parse}});var o=pn;Object.defineProperty(e,"nextTick",{enumerable:!0,get:function(){return o.nextTick}});var u=Jf;Object.defineProperty(e,"Fetch",{enumerable:!0,get:function(){return u.Fetch}});var c=yi;Object.defineProperty(e,"NodeXHR",{enumerable:!0,get:function(){return c.XHR}});var l=yi;Object.defineProperty(e,"XHR",{enumerable:!0,get:function(){return l.XHR}});var p=Ra;Object.defineProperty(e,"NodeWebSocket",{enumerable:!0,get:function(){return p.WS}});var v=Ra;Object.defineProperty(e,"WebSocket",{enumerable:!0,get:function(){return v.WS}});var m=tc;Object.defineProperty(e,"WebTransport",{enumerable:!0,get:function(){return m.WT}})})(Gf);var VZ=je&&je.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Gg,"__esModule",{value:!0});Gg.url=YZ;const KZ=Gf,JZ=VZ(ui),j0=(0,JZ.default)("socket.io-client:url");function YZ(e,t="",r){let n=e;r=r||typeof location<"u"&&location,e==null&&(e=r.protocol+"//"+r.host),typeof e=="string"&&(e.charAt(0)==="/"&&(e.charAt(1)==="/"?e=r.protocol+e:e=r.host+e),/^(https?|wss?):\/\//.test(e)||(j0("protocol-less url %s",e),typeof r<"u"?e=r.protocol+"//"+e:e="https://"+e),j0("parse %s",e),n=(0,KZ.parse)(e)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const a=n.host.indexOf(":")!==-1?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+a+":"+n.port+t,n.href=n.protocol+"://"+a+(r&&r.port===n.port?"":":"+n.port),n}var Yf={},rc={},Xf={},fo={},cs={};Object.defineProperty(cs,"__esModule",{value:!0});cs.hasBinary=cs.isBinary=void 0;const XZ=typeof ArrayBuffer=="function",QZ=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,z$=Object.prototype.toString,ZZ=typeof Blob=="function"||typeof Blob<"u"&&z$.call(Blob)==="[object BlobConstructor]",eee=typeof File=="function"||typeof File<"u"&&z$.call(File)==="[object FileConstructor]";function W$(e){return XZ&&(e instanceof ArrayBuffer||QZ(e))||ZZ&&e instanceof Blob||eee&&e instanceof File}cs.isBinary=W$;function Tl(e,t){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let r=0,n=e.length;r<n;r++)if(Tl(e[r]))return!0;return!1}if(W$(e))return!0;if(e.toJSON&&typeof e.toJSON=="function"&&arguments.length===1)return Tl(e.toJSON(),!0);for(const r in e)if(Object.prototype.hasOwnProperty.call(e,r)&&Tl(e[r]))return!0;return!1}cs.hasBinary=Tl;Object.defineProperty(fo,"__esModule",{value:!0});fo.reconstructPacket=fo.deconstructPacket=void 0;const tee=cs;function ree(e){const t=[],r=e.data,n=e;return n.data=Ov(r,t),n.attachments=t.length,{packet:n,buffers:t}}fo.deconstructPacket=ree;function Ov(e,t){if(!e)return e;if((0,tee.isBinary)(e)){const r={_placeholder:!0,num:t.length};return t.push(e),r}else if(Array.isArray(e)){const r=new Array(e.length);for(let n=0;n<e.length;n++)r[n]=Ov(e[n],t);return r}else if(typeof e=="object"&&!(e instanceof Date)){const r={};for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=Ov(e[n],t));return r}return e}function nee(e,t){return e.data=Av(e.data,t),delete e.attachments,e}fo.reconstructPacket=nee;function Av(e,t){if(!e)return e;if(e&&e._placeholder===!0){if(typeof e.num=="number"&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}else if(Array.isArray(e))for(let r=0;r<e.length;r++)e[r]=Av(e[r],t);else if(typeof e=="object")for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e[r]=Av(e[r],t));return e}(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Decoder=e.Encoder=e.PacketType=e.protocol=void 0;const t=Co,r=fo,n=cs,a=(0,ui.default)("socket.io-parser"),s=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];e.protocol=5;var o;(function(v){v[v.CONNECT=0]="CONNECT",v[v.DISCONNECT=1]="DISCONNECT",v[v.EVENT=2]="EVENT",v[v.ACK=3]="ACK",v[v.CONNECT_ERROR=4]="CONNECT_ERROR",v[v.BINARY_EVENT=5]="BINARY_EVENT",v[v.BINARY_ACK=6]="BINARY_ACK"})(o=e.PacketType||(e.PacketType={}));class u{constructor(m){this.replacer=m}encode(m){return a("encoding packet %j",m),(m.type===o.EVENT||m.type===o.ACK)&&(0,n.hasBinary)(m)?this.encodeAsBinary({type:m.type===o.EVENT?o.BINARY_EVENT:o.BINARY_ACK,nsp:m.nsp,data:m.data,id:m.id}):[this.encodeAsString(m)]}encodeAsString(m){let b=""+m.type;return(m.type===o.BINARY_EVENT||m.type===o.BINARY_ACK)&&(b+=m.attachments+"-"),m.nsp&&m.nsp!=="/"&&(b+=m.nsp+","),m.id!=null&&(b+=m.id),m.data!=null&&(b+=JSON.stringify(m.data,this.replacer)),a("encoded %j as %s",m,b),b}encodeAsBinary(m){const b=(0,r.deconstructPacket)(m),T=this.encodeAsString(b.packet),I=b.buffers;return I.unshift(T),I}}e.Encoder=u;function c(v){return Object.prototype.toString.call(v)==="[object Object]"}class l extends t.Emitter{constructor(m){super(),this.reviver=m}add(m){let b;if(typeof m=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");b=this.decodeString(m);const T=b.type===o.BINARY_EVENT;T||b.type===o.BINARY_ACK?(b.type=T?o.EVENT:o.ACK,this.reconstructor=new p(b),b.attachments===0&&super.emitReserved("decoded",b)):super.emitReserved("decoded",b)}else if((0,n.isBinary)(m)||m.base64)if(this.reconstructor)b=this.reconstructor.takeBinaryData(m),b&&(this.reconstructor=null,super.emitReserved("decoded",b));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+m)}decodeString(m){let b=0;const T={type:Number(m.charAt(0))};if(o[T.type]===void 0)throw new Error("unknown packet type "+T.type);if(T.type===o.BINARY_EVENT||T.type===o.BINARY_ACK){const R=b+1;for(;m.charAt(++b)!=="-"&&b!=m.length;);const x=m.substring(R,b);if(x!=Number(x)||m.charAt(b)!=="-")throw new Error("Illegal attachments");T.attachments=Number(x)}if(m.charAt(b+1)==="/"){const R=b+1;for(;++b&&!(m.charAt(b)===","||b===m.length););T.nsp=m.substring(R,b)}else T.nsp="/";const I=m.charAt(b+1);if(I!==""&&Number(I)==I){const R=b+1;for(;++b;){const x=m.charAt(b);if(x==null||Number(x)!=x){--b;break}if(b===m.length)break}T.id=Number(m.substring(R,b+1))}if(m.charAt(++b)){const R=this.tryParse(m.substr(b));if(l.isPayloadValid(T.type,R))T.data=R;else throw new Error("invalid payload")}return a("decoded %s as %j",m,T),T}tryParse(m){try{return JSON.parse(m,this.reviver)}catch{return!1}}static isPayloadValid(m,b){switch(m){case o.CONNECT:return c(b);case o.DISCONNECT:return b===void 0;case o.CONNECT_ERROR:return typeof b=="string"||c(b);case o.EVENT:case o.BINARY_EVENT:return Array.isArray(b)&&(typeof b[0]=="number"||typeof b[0]=="string"&&s.indexOf(b[0])===-1);case o.ACK:case o.BINARY_ACK:return Array.isArray(b)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}e.Decoder=l;class p{constructor(m){this.packet=m,this.buffers=[],this.reconPack=m}takeBinaryData(m){if(this.buffers.push(m),this.buffers.length===this.reconPack.attachments){const b=(0,r.reconstructPacket)(this.reconPack,this.buffers);return this.finishedReconstruction(),b}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}})(Xf);var Qf={};Object.defineProperty(Qf,"__esModule",{value:!0});Qf.on=iee;function iee(e,t,r){return e.on(t,r),function(){e.off(t,r)}}var aee=je&&je.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(rc,"__esModule",{value:!0});rc.Socket=void 0;const Jn=Xf,Jc=Qf,see=Co,oee=aee(ui),xr=(0,oee.default)("socket.io-client:socket"),uee=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class cee extends see.Emitter{constructor(t,r,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=t,this.nsp=r,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 t=this.io;this.subs=[(0,Jc.on)(t,"open",this.onopen.bind(this)),(0,Jc.on)(t,"packet",this.onpacket.bind(this)),(0,Jc.on)(t,"error",this.onerror.bind(this)),(0,Jc.on)(t,"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(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...r){var n,i,a;if(uee.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(r.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(r),this;const s={type:Jn.PacketType.EVENT,data:r};if(s.options={},s.options.compress=this.flags.compress!==!1,typeof r[r.length-1]=="function"){const l=this.ids++;xr("emitting packet with ack id %d",l);const p=r.pop();this._registerAckCallback(l,p),s.id=l}const o=(i=(n=this.io.engine)===null||n===void 0?void 0:n.transport)===null||i===void 0?void 0:i.writable,u=this.connected&&!(!((a=this.io.engine)===null||a===void 0)&&a._hasPingExpired());return this.flags.volatile&&!o?xr("discard packet as the transport is not currently writable"):u?(this.notifyOutgoingListeners(s),this.packet(s)):this.sendBuffer.push(s),this.flags={},this}_registerAckCallback(t,r){var n;const i=(n=this.flags.timeout)!==null&&n!==void 0?n:this._opts.ackTimeout;if(i===void 0){this.acks[t]=r;return}const a=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let o=0;o<this.sendBuffer.length;o++)this.sendBuffer[o].id===t&&(xr("removing packet with ack id %d from the buffer",t),this.sendBuffer.splice(o,1));xr("event with ack id %d has timed out after %d ms",t,i),r.call(this,new Error("operation has timed out"))},i),s=(...o)=>{this.io.clearTimeoutFn(a),r.apply(this,o)};s.withError=!0,this.acks[t]=s}emitWithAck(t,...r){return new Promise((n,i)=>{const a=(s,o)=>s?i(s):n(o);a.withError=!0,r.push(a),this.emit(t,...r)})}_addToQueue(t){let r;typeof t[t.length-1]=="function"&&(r=t.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((i,...a)=>n!==this._queue[0]?void 0:(i!==null?n.tryCount>this._opts.retries&&(xr("packet [%d] is discarded after %d tries",n.id,n.tryCount),this._queue.shift(),r&&r(i)):(xr("packet [%d] was successfully sent",n.id),this._queue.shift(),r&&r(null,...a)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(t=!1){if(xr("draining queue"),!this.connected||this._queue.length===0)return;const r=this._queue[0];if(r.pending&&!t){xr("packet [%d] has already been sent and is waiting for an ack",r.id);return}r.pending=!0,r.tryCount++,xr("sending packet [%d] (try n°%d)",r.id,r.tryCount),this.flags=r.flags,this.emit.apply(this,r.args)}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){xr("transport is open - connecting"),typeof this.auth=="function"?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:Jn.PacketType.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,r){xr("close (%s)",t),this.connected=!1,delete this.id,this.emitReserved("disconnect",t,r),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(n=>String(n.id)===t)){const n=this.acks[t];delete this.acks[t],n.withError&&n.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case Jn.PacketType.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.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 Jn.PacketType.EVENT:case Jn.PacketType.BINARY_EVENT:this.onevent(t);break;case Jn.PacketType.ACK:case Jn.PacketType.BINARY_ACK:this.onack(t);break;case Jn.PacketType.DISCONNECT:this.ondisconnect();break;case Jn.PacketType.CONNECT_ERROR:this.destroy();const n=new Error(t.data.message);n.data=t.data.data,this.emitReserved("connect_error",n);break}}onevent(t){const r=t.data||[];xr("emitting event %j",r),t.id!=null&&(xr("attaching ack callback to event"),r.push(this.ack(t.id))),this.connected?this.emitEvent(r):this.receiveBuffer.push(Object.freeze(r))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const r=this._anyListeners.slice();for(const n of r)n.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&typeof t[t.length-1]=="string"&&(this._lastOffset=t[t.length-1])}ack(t){const r=this;let n=!1;return function(...i){n||(n=!0,xr("sending ack %j",i),r.packet({type:Jn.PacketType.ACK,id:t,data:i}))}}onack(t){const r=this.acks[t.id];if(typeof r!="function"){xr("bad ack %s",t.id);return}delete this.acks[t.id],xr("calling ack %s with %j",t.id,t.data),r.withError&&t.data.unshift(null),r.apply(this,t.data)}onconnect(t,r){xr("socket connected with id %s",t),this.id=t,this.recovered=r&&this._pid===r,this._pid=r,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){xr("server disconnect (%s)",this.nsp),this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&(xr("performing disconnect (%s)",this.nsp),this.packet({type:Jn.PacketType.DISCONNECT})),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const r=this._anyListeners;for(let n=0;n<r.length;n++)if(t===r[n])return r.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(t),this}prependAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(t),this}offAnyOutgoing(t){if(!this._anyOutgoingListeners)return this;if(t){const r=this._anyOutgoingListeners;for(let n=0;n<r.length;n++)if(t===r[n])return r.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(t){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const r=this._anyOutgoingListeners.slice();for(const n of r)n.apply(this,t.data)}}}rc.Socket=cee;var Hg={};Object.defineProperty(Hg,"__esModule",{value:!0});Hg.Backoff=Eo;function Eo(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}Eo.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),r=Math.floor(t*this.jitter*e);e=Math.floor(t*10)&1?e+r:e-r}return Math.min(e,this.max)|0};Eo.prototype.reset=function(){this.attempts=0};Eo.prototype.setMin=function(e){this.ms=e};Eo.prototype.setMax=function(e){this.max=e};Eo.prototype.setJitter=function(e){this.jitter=e};var lee=je&&je.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),fee=je&&je.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),dee=je&&je.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&lee(t,e,r);return fee(t,e),t},pee=je&&je.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Yf,"__esModule",{value:!0});Yf.Manager=void 0;const ch=Gf,hee=rc,vee=dee(Xf),Xa=Qf,mee=Hg,gee=Co,yee=pee(ui),Kr=(0,yee.default)("socket.io-client:manager");class bee extends gee.Emitter{constructor(t,r){var n;super(),this.nsps={},this.subs=[],t&&typeof t=="object"&&(r=t,t=void 0),r=r||{},r.path=r.path||"/socket.io",this.opts=r,(0,ch.installTimerFunctions)(this,r),this.reconnection(r.reconnection!==!1),this.reconnectionAttempts(r.reconnectionAttempts||1/0),this.reconnectionDelay(r.reconnectionDelay||1e3),this.reconnectionDelayMax(r.reconnectionDelayMax||5e3),this.randomizationFactor((n=r.randomizationFactor)!==null&&n!==void 0?n:.5),this.backoff=new mee.Backoff({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(r.timeout==null?2e4:r.timeout),this._readyState="closed",this.uri=t;const i=r.parser||vee;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=r.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return t===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var r;return t===void 0?this._reconnectionDelay:(this._reconnectionDelay=t,(r=this.backoff)===null||r===void 0||r.setMin(t),this)}randomizationFactor(t){var r;return t===void 0?this._randomizationFactor:(this._randomizationFactor=t,(r=this.backoff)===null||r===void 0||r.setJitter(t),this)}reconnectionDelayMax(t){var r;return t===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,(r=this.backoff)===null||r===void 0||r.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(t){if(Kr("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;Kr("opening %s",this.uri),this.engine=new ch.Socket(this.uri,this.opts);const r=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const i=(0,Xa.on)(r,"open",function(){n.onopen(),t&&t()}),a=o=>{Kr("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",o),t?t(o):this.maybeReconnectOnOpen()},s=(0,Xa.on)(r,"error",a);if(this._timeout!==!1){const o=this._timeout;Kr("connect attempt will timeout after %d",o);const u=this.setTimeoutFn(()=>{Kr("connect attempt timed out after %d",o),i(),a(new Error("timeout")),r.close()},o);this.opts.autoUnref&&u.unref(),this.subs.push(()=>{this.clearTimeoutFn(u)})}return this.subs.push(i),this.subs.push(s),this}connect(t){return this.open(t)}onopen(){Kr("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push((0,Xa.on)(t,"ping",this.onping.bind(this)),(0,Xa.on)(t,"data",this.ondata.bind(this)),(0,Xa.on)(t,"error",this.onerror.bind(this)),(0,Xa.on)(t,"close",this.onclose.bind(this)),(0,Xa.on)(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(r){this.onclose("parse error",r)}}ondecoded(t){(0,ch.nextTick)(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){Kr("error",t),this.emitReserved("error",t)}socket(t,r){let n=this.nsps[t];return n?this._autoConnect&&!n.active&&n.connect():(n=new hee.Socket(this,t,r),this.nsps[t]=n),n}_destroy(t){const r=Object.keys(this.nsps);for(const n of r)if(this.nsps[n].active){Kr("socket %s is still active, skipping close",n);return}this._close()}_packet(t){Kr("writing packet %j",t);const r=this.encoder.encode(t);for(let n=0;n<r.length;n++)this.engine.write(r[n],t.options)}cleanup(){Kr("cleanup"),this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}_close(){Kr("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,r){var n;Kr("closed due to %s",t),this.cleanup(),(n=this.engine)===null||n===void 0||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,r),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)Kr("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const r=this.backoff.duration();Kr("will wait %dms before reconnect attempt",r),this._reconnecting=!0;const n=this.setTimeoutFn(()=>{t.skipReconnect||(Kr("attempting reconnect"),this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(i=>{i?(Kr("reconnect attempt error"),t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",i)):(Kr("reconnect success"),t.onreconnect())}))},r);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}Yf.Manager=bee;(function(e,t){var r=je&&je.__importDefault||function(v){return v&&v.__esModule?v:{default:v}};Object.defineProperty(t,"__esModule",{value:!0}),t.WebTransport=t.WebSocket=t.NodeWebSocket=t.XHR=t.NodeXHR=t.Fetch=t.Socket=t.Manager=t.protocol=void 0,t.io=c,t.connect=c,t.default=c;const n=Gg,i=Yf;Object.defineProperty(t,"Manager",{enumerable:!0,get:function(){return i.Manager}});const a=rc;Object.defineProperty(t,"Socket",{enumerable:!0,get:function(){return a.Socket}});const o=(0,r(ui).default)("socket.io-client"),u={};function c(v,m){typeof v=="object"&&(m=v,v=void 0),m=m||{};const b=(0,n.url)(v,m.path||"/socket.io"),T=b.source,I=b.id,R=b.path,x=u[I]&&R in u[I].nsps,N=m.forceNew||m["force new connection"]||m.multiplex===!1||x;let j;return N?(o("ignoring socket cache for %s",T),j=new i.Manager(T,m)):(u[I]||(o("new io instance for %s",T),u[I]=new i.Manager(T,m)),j=u[I]),b.query&&!m.query&&(m.query=b.queryKey),j.socket(b.path,m)}Object.assign(c,{Manager:i.Manager,Socket:a.Socket,io:c,connect:c});var l=Xf;Object.defineProperty(t,"protocol",{enumerable:!0,get:function(){return l.protocol}});var p=Gf;Object.defineProperty(t,"Fetch",{enumerable:!0,get:function(){return p.Fetch}}),Object.defineProperty(t,"NodeXHR",{enumerable:!0,get:function(){return p.NodeXHR}}),Object.defineProperty(t,"XHR",{enumerable:!0,get:function(){return p.XHR}}),Object.defineProperty(t,"NodeWebSocket",{enumerable:!0,get:function(){return p.NodeWebSocket}}),Object.defineProperty(t,"WebSocket",{enumerable:!0,get:function(){return p.WebSocket}}),Object.defineProperty(t,"WebTransport",{enumerable:!0,get:function(){return p.WebTransport}}),e.exports=c})(Ev,Ev.exports);var G$=Ev.exports,H$={exports:{}};(function(e,t){(function(r){e.exports=r()})(function(){var r=function(f,d,h){for(var y=h,g=0,_=f.length;g<_;g++)y=d(y,f[g],g,f);return y},n=function(f,d){return r(f,function(h,y,g,_){return d(y,g,_)?h.concat(y):h},[])},i=function(f,d){return r(f,function(h,y,g,_){return h.concat(d(y,g,_))},[])},a=function(f,d){return r(f,function(h,y,g,_){return h===!0||y===d},!1)},s=!{toString:null}.propertyIsEnumerable("toString"),o=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],u=function(f){var d=[],h;for(h in f)Object.prototype.hasOwnProperty.call(f,h)&&d.push(h);if(!s)return d;for(var y=0,g=o.length;y<g;y++)Object.prototype.hasOwnProperty.call(f,o[y])&&d.push(o[y]);return d},c=function(f){return Object.prototype.toString.call(f)==="[object Array]"},l=function(f){return f<10?"0"+f:f},p=function(){var f=new Date;return f.getUTCFullYear()+"-"+l(f.getUTCMonth()+1)+"-"+l(f.getUTCDate())+"T"+l(f.getUTCHours())+":"+l(f.getUTCMinutes())+":"+l(f.getUTCSeconds())+"."+(f.getUTCMilliseconds()/1e3).toFixed(3).slice(2,5)+"Z"},v={map:i,reduce:r,filter:n,includes:a,keys:u,isArray:c,isoDate:p},m={};m.intRange=function(f,d){return f===void 0&&(f=1),d===void 0&&(d=1/0),function(h){return typeof h=="number"&&parseInt(""+h,10)===h&&h>=f&&h<=d}},m.stringWithLength=function(f){return typeof f=="string"&&!!f.length};var b={},T=v.filter,I=v.reduce,R=v.keys,x=v.isArray,N=v.includes,j=m.intRange,X=m.stringWithLength;b.schema={apiKey:{defaultValue:function(){return null},message:"is required",validate:X},appVersion:{defaultValue:function(){return null},message:"should be a string",validate:function(f){return f===null||X(f)}},appType:{defaultValue:function(){return null},message:"should be a string",validate:function(f){return f===null||X(f)}},autoNotify:{defaultValue:function(){return!0},message:"should be true|false",validate:function(f){return f===!0||f===!1}},beforeSend:{defaultValue:function(){return[]},message:"should be a function or array of functions",validate:function(f){return typeof f=="function"||x(f)&&T(f,function(d){return typeof d=="function"}).length===f.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(f,d){return f&&typeof f=="object"&&X(f.notify)&&(d.autoCaptureSessions===!1||X(f.sessions))&&T(R(f),function(h){return!N(["notify","sessions"],h)}).length===0}},autoCaptureSessions:{defaultValue:function(f,d){return d.endpoints===void 0||!!d.endpoints&&!!d.endpoints.sessions},message:"should be true|false",validate:function(f){return f===!0||f===!1}},notifyReleaseStages:{defaultValue:function(){return null},message:"should be an array of strings",validate:function(f){return f===null||x(f)&&T(f,function(d){return typeof d=="string"}).length===f.length}},releaseStage:{defaultValue:function(){return"production"},message:"should be a string",validate:function(f){return typeof f=="string"&&f.length}},maxBreadcrumbs:{defaultValue:function(){return 20},message:"should be a number ≤40",validate:function(f){return j(0,40)(f)}},autoBreadcrumbs:{defaultValue:function(){return!0},message:"should be true|false",validate:function(f){return typeof f=="boolean"}},user:{defaultValue:function(){return null},message:"(object) user should be an object",validate:function(f){return typeof f=="object"}},metaData:{defaultValue:function(){return null},message:"should be an object",validate:function(f){return typeof f=="object"}},logger:{defaultValue:function(){},message:"should be null or an object with methods { debug, info, warn, error }",validate:function(f){return!f||f&&I(["debug","info","warn","error"],function(d,h){return d&&typeof f[h]=="function"},!0)}},filters:{defaultValue:function(){return["password"]},message:"should be an array of strings|regexes",validate:function(f){return x(f)&&f.length===T(f,function(d){return typeof d=="string"||d&&typeof d.test=="function"}).length}}},b.mergeDefaults=function(f,d){if(!f||!d)throw new Error("opts and schema objects are required");return I(R(d),function(h,y){return h[y]=f[y]!==void 0?f[y]:d[y].defaultValue(f[y],f),h},{})},b.validate=function(f,d){if(!f||!d)throw new Error("opts and schema objects are required");var h=I(R(d),function(y,g){return d[g].validate(f[g],f)?y:y.concat({key:g,message:d[g].message,value:f[g]})},[]);return{valid:!h.length,errors:h}};function J(){return J=Object.assign||function(f){for(var d=1;d<arguments.length;d++){var h=arguments[d];for(var y in h)Object.prototype.hasOwnProperty.call(h,y)&&(f[y]=h[y])}return f},J.apply(this,arguments)}var V=b.schema,D=v.map,te=m.stringWithLength,ue={releaseStage:{defaultValue:function(){return/^localhost(:\d+)?$/.test(window.location.host)?"development":"production"},message:"should be set",validate:te},logger:J({},V.logger,{defaultValue:function(){return typeof console<"u"&&typeof console.debug=="function"?ee():void 0}})},ee=function(){var f={},d=console.log;return D(["debug","info","warn","error"],function(h){var y=console[h];f[h]=typeof y=="function"?y.bind(console,"[bugsnag]"):d.bind(console,"[bugsnag]")}),f},ge=v.isoDate,L=function(){function f(h,y,g,_){h===void 0&&(h="[anonymous]"),y===void 0&&(y={}),g===void 0&&(g="manual"),_===void 0&&(_=ge()),this.type=g,this.name=h,this.metaData=y,this.timestamp=_}var d=f.prototype;return d.toJSON=function(){return{type:this.type,name:this.name,timestamp:this.timestamp,metaData:this.metaData}},f}(),pe=L,Te=function(f,d,h){var y=f.length,g=0,_=function(){if(g>=y)return h(null,!1);d(f[g],function(w,S){if(w)return h(w,!1);if(S===!0)return h(null,!0);g++,_()})};_()},rt=function(f){return f.app&&typeof f.app.releaseStage=="string"?f.app.releaseStage:f.config.releaseStage},Ke=Se;function Se(f){switch(Object.prototype.toString.call(f)){case"[object Error]":return!0;case"[object Exception]":return!0;case"[object DOMException]":return!0;default:return f instanceof Error}}var ce=Ke,he=function(f,d){return function(h,y){if(typeof h!="function")return y(null,!1);try{if(h.length!==2){var g=h(f);return g&&typeof g.then=="function"?g.then(function(_){return setTimeout(function(){return y(null,P(f,_))},0)},function(_){setTimeout(function(){return d(_),y(null,!1)})}):y(null,P(f,g))}h(f,function(_,w){if(_)return d(_),y(null,!1);y(null,P(f,w))})}catch(_){d(_),y(null,!1)}}},P=function(f,d){return f.isIgnored()||d===!1},Ie={};(function(f,d){typeof Ie=="object"?Ie=d():f.StackFrame=d()})(this,function(){function f(G){return!isNaN(parseFloat(G))&&isFinite(G)}function d(G){return G.charAt(0).toUpperCase()+G.substring(1)}function h(G){return function(){return this[G]}}var y=["isConstructor","isEval","isNative","isToplevel"],g=["columnNumber","lineNumber"],_=["fileName","functionName","source"],w=["args"],S=y.concat(g,_,w);function C(G){if(G instanceof Object)for(var Le=0;Le<S.length;Le++)G.hasOwnProperty(S[Le])&&G[S[Le]]!==void 0&&this["set"+d(S[Le])](G[S[Le]])}C.prototype={getArgs:function(){return this.args},setArgs:function(G){if(Object.prototype.toString.call(G)!=="[object Array]")throw new TypeError("Args must be an Array");this.args=G},getEvalOrigin:function(){return this.evalOrigin},setEvalOrigin:function(G){if(G instanceof C)this.evalOrigin=G;else if(G instanceof Object)this.evalOrigin=new C(G);else throw new TypeError("Eval Origin must be an Object or StackFrame")},toString:function(){var G=this.getFunctionName()||"{anonymous}",Le="("+(this.getArgs()||[]).join(",")+")",Xe=this.getFileName()?"@"+this.getFileName():"",We=f(this.getLineNumber())?":"+this.getLineNumber():"",Ve=f(this.getColumnNumber())?":"+this.getColumnNumber():"";return G+Le+Xe+We+Ve}};for(var B=0;B<y.length;B++)C.prototype["get"+d(y[B])]=h(y[B]),C.prototype["set"+d(y[B])]=function(G){return function(Le){this[G]=!!Le}}(y[B]);for(var U=0;U<g.length;U++)C.prototype["get"+d(g[U])]=h(g[U]),C.prototype["set"+d(g[U])]=function(G){return function(Le){if(!f(Le))throw new TypeError(G+" must be a Number");this[G]=Number(Le)}}(g[U]);for(var H=0;H<_.length;H++)C.prototype["get"+d(_[H])]=h(_[H]),C.prototype["set"+d(_[H])]=function(G){return function(Le){this[G]=String(Le)}}(_[H]);return C});var qe={};(function(f,d){typeof qe=="object"?qe=d(Ie):f.ErrorStackParser=d(f.StackFrame)})(this,function(d){var h=/(^|@)\S+\:\d+/,y=/^\s*at .*(\S+\:\d+|\(native\))/m,g=/^(eval@)?(\[native code\])?$/;return{parse:function(w){if(typeof w.stacktrace<"u"||typeof w["opera#sourceloc"]<"u")return this.parseOpera(w);if(w.stack&&w.stack.match(y))return this.parseV8OrIE(w);if(w.stack)return this.parseFFOrSafari(w);throw new Error("Cannot parse given Error object")},extractLocation:function(w){if(w.indexOf(":")===-1)return[w];var S=/(.+?)(?:\:(\d+))?(?:\:(\d+))?$/,C=S.exec(w.replace(/[\(\)]/g,""));return[C[1],C[2]||void 0,C[3]||void 0]},parseV8OrIE:function(w){var S=w.stack.split(`
473
473
  `).filter(function(C){return!!C.match(y)},this);return S.map(function(C){C.indexOf("(eval ")>-1&&(C=C.replace(/eval code/g,"eval").replace(/(\(eval at [^\()]*)|(\)\,.*$)/g,""));var B=C.replace(/^\s+/,"").replace(/\(eval code/g,"("),U=B.match(/ (\((.+):(\d+):(\d+)\)$)/);B=U?B.replace(U[0],""):B;var H=B.split(/\s+/).slice(1),G=this.extractLocation(U?U[1]:H.pop()),Le=H.join(" ")||void 0,Xe=["eval","<anonymous>"].indexOf(G[0])>-1?void 0:G[0];return new d({functionName:Le,fileName:Xe,lineNumber:G[1],columnNumber:G[2],source:C})},this)},parseFFOrSafari:function(w){var S=w.stack.split(`
474
474
  `).filter(function(C){return!C.match(g)},this);return S.map(function(C){if(C.indexOf(" > eval")>-1&&(C=C.replace(/ line (\d+)(?: > eval line \d+)* > eval\:\d+\:\d+/g,":$1")),C.indexOf("@")===-1&&C.indexOf(":")===-1)return new d({functionName:C});var B=/((.*".+"[^@]*)?[^@]*)(?:@)/,U=C.match(B),H=U&&U[1]?U[1]:void 0,G=this.extractLocation(C.replace(B,""));return new d({functionName:H,fileName:G[0],lineNumber:G[1],columnNumber:G[2],source:C})},this)},parseOpera:function(w){return!w.stacktrace||w.message.indexOf(`
475
475
  `)>-1&&w.message.split(`
@@ -481,10 +481,10 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
481
481
  `+lr(f,function(d){return'"'+d.key+'" '+d.message+`
482
482
  got `+K(d.value)}).join(`
483
483
 
484
- `)},ae=function(f){return"notify() expected error/opts parameters, got "+f},K=function(f){return typeof f=="object"?JSON.stringify(f):String(f)},oe=le,Y=function(f,d,h,y){var g=y&&y.filterKeys?y.filterKeys:[],_=y&&y.filterPaths?y.filterPaths:[];return JSON.stringify(yr(f,g,_),d,h)},De=20,Re=25e3,Je=8,Ge="...";function He(f){return f instanceof Error||/^\[object (Error|(Dom)?Exception)\]$/.test(Object.prototype.toString.call(f))}function et(f){return"[Throws: "+(f?f.message:"?")+"]"}function nt(f,d){for(var h=0,y=f.length;h<y;h++)if(f[h]===d)return!0;return!1}function Qe(f,d){for(var h=0,y=f.length;h<y;h++)if(d.indexOf(f[h])===0)return!0;return!1}function tt(f,d){for(var h=0,y=f.length;h<y;h++)if(typeof f[h]=="string"&&f[h]===d||f[h]&&typeof f[h].test=="function"&&f[h].test(d))return!0;return!1}function at(f){return Object.prototype.toString.call(f)==="[object Array]"}function st(f,d){try{return f[d]}catch(h){return et(h)}}function yr(f,d,h){var y=[],g=0;function _(w,S){function C(){return S.length>Je&&g>Re}if(g++,S.length>De||C())return Ge;if(w===null||typeof w!="object")return w;if(nt(y,w))return"[Circular]";if(y.push(w),typeof w.toJSON=="function")try{g--;var B=_(w.toJSON(),S);return y.pop(),B}catch(Nt){return et(Nt)}var U=He(w);if(U){g--;var H=_({name:w.name,message:w.message},S);return y.pop(),H}if(at(w)){for(var G=[],Le=0,Xe=w.length;Le<Xe;Le++){if(C()){G.push(Ge);break}G.push(_(w[Le],S.concat("[]")))}return y.pop(),G}var We={};try{for(var Ve in w)if(Object.prototype.hasOwnProperty.call(w,Ve)){if(Qe(h,S.join("."))&&tt(d,Ve)){We[Ve]="[Filtered]";continue}if(C()){We[Ve]=Ge;break}We[Ve]=_(st(w,Ve),S.concat(Ve))}}catch{}return y.pop(),We}return _(f,[])}var fr={},dt=["events.[].app","events.[].metaData","events.[].user","events.[].breadcrumbs","events.[].request","events.[].device"],Wr=["device","app","user"];fr.report=function(f,d){var h=Y(f,null,null,{filterPaths:dt,filterKeys:d});if(h.length>1e6&&(delete f.events[0].metaData,f.events[0].metaData={notifier:`WARNING!
484
+ `)},ae=function(f){return"notify() expected error/opts parameters, got "+f},K=function(f){return typeof f=="object"?JSON.stringify(f):String(f)},oe=le,Y=function(f,d,h,y){var g=y&&y.filterKeys?y.filterKeys:[],_=y&&y.filterPaths?y.filterPaths:[];return JSON.stringify(yr(f,g,_),d,h)},De=20,Re=25e3,Je=8,Ge="...";function He(f){return f instanceof Error||/^\[object (Error|(Dom)?Exception)\]$/.test(Object.prototype.toString.call(f))}function et(f){return"[Throws: "+(f?f.message:"?")+"]"}function nt(f,d){for(var h=0,y=f.length;h<y;h++)if(f[h]===d)return!0;return!1}function Qe(f,d){for(var h=0,y=f.length;h<y;h++)if(d.indexOf(f[h])===0)return!0;return!1}function tt(f,d){for(var h=0,y=f.length;h<y;h++)if(typeof f[h]=="string"&&f[h]===d||f[h]&&typeof f[h].test=="function"&&f[h].test(d))return!0;return!1}function at(f){return Object.prototype.toString.call(f)==="[object Array]"}function st(f,d){try{return f[d]}catch(h){return et(h)}}function yr(f,d,h){var y=[],g=0;function _(w,S){function C(){return S.length>Je&&g>Re}if(g++,S.length>De||C())return Ge;if(w===null||typeof w!="object")return w;if(nt(y,w))return"[Circular]";if(y.push(w),typeof w.toJSON=="function")try{g--;var B=_(w.toJSON(),S);return y.pop(),B}catch(Nt){return et(Nt)}var U=He(w);if(U){g--;var H=_({name:w.name,message:w.message},S);return y.pop(),H}if(at(w)){for(var G=[],Le=0,Xe=w.length;Le<Xe;Le++){if(C()){G.push(Ge);break}G.push(_(w[Le],S.concat("[]")))}return y.pop(),G}var We={};try{for(var Ve in w)if(Object.prototype.hasOwnProperty.call(w,Ve)){if(Qe(h,S.join("."))&&tt(d,Ve)){We[Ve]="[Filtered]";continue}if(C()){We[Ve]=Ge;break}We[Ve]=_(st(w,Ve),S.concat(Ve))}}catch{}return y.pop(),We}return _(f,[])}var fr={},dt=["events.[].app","events.[].metaData","events.[].user","events.[].breadcrumbs","events.[].request","events.[].device"],Gr=["device","app","user"];fr.report=function(f,d){var h=Y(f,null,null,{filterPaths:dt,filterKeys:d});if(h.length>1e6&&(delete f.events[0].metaData,f.events[0].metaData={notifier:`WARNING!
485
485
  Serialized payload was `+h.length/1e6+`MB (limit = 1MB)
486
- metaData was removed`},h=Y(f,null,null,{filterPaths:dt,filterKeys:d}),h.length>1e6))throw new Error("payload exceeded 1MB limit");return h},fr.session=function(f,d){var h=Y(f,null,null,{filterPaths:Wr,filterKeys:d});if(h.length>1e6)throw new Error("payload exceeded 1MB limit");return h};var cn={},it=v.isoDate;cn=function(f,d){return d===void 0&&(d=window),{sendReport:function(h,y){y===void 0&&(y=function(){});var g=Z(f.config,"notify","4",d),_=new d.XDomainRequest;_.onload=function(){y(null)},_.open("POST",g),setTimeout(function(){try{_.send(fr.report(h,f.config.filters))}catch(w){f._logger.error(w),y(w)}},0)},sendSession:function(h,y){y===void 0&&(y=function(){});var g=Z(f.config,"sessions","1",d),_=new d.XDomainRequest;_.onload=function(){y(null)},_.open("POST",g),setTimeout(function(){try{_.send(fr.session(h,f.config.filters))}catch(w){f._logger.error(w),y(w)}},0)}}};var Z=function(f,d,h,y){return xe(f.endpoints[d],y.location.protocol)+"?apiKey="+encodeURIComponent(f.apiKey)+"&payloadVersion="+h+"&sentAt="+encodeURIComponent(it())},xe=cn._matchPageProtocol=function(f,d){return d==="http:"?f.replace(/^https:/,"http:"):f},Ye=v.isoDate,Mt=function(f,d){return d===void 0&&(d=window),{sendReport:function(h,y){y===void 0&&(y=function(){});try{var g=f.config.endpoints.notify,_=new d.XMLHttpRequest;_.onreadystatechange=function(){_.readyState===d.XMLHttpRequest.DONE&&y(null)},_.open("POST",g),_.setRequestHeader("Content-Type","application/json"),_.setRequestHeader("Bugsnag-Api-Key",h.apiKey||f.config.apiKey),_.setRequestHeader("Bugsnag-Payload-Version","4"),_.setRequestHeader("Bugsnag-Sent-At",Ye()),_.send(fr.report(h,f.config.filters))}catch(w){f._logger.error(w)}},sendSession:function(h,y){y===void 0&&(y=function(){});try{var g=f.config.endpoints.sessions,_=new d.XMLHttpRequest;_.onreadystatechange=function(){_.readyState===d.XMLHttpRequest.DONE&&y(null)},_.open("POST",g),_.setRequestHeader("Content-Type","application/json"),_.setRequestHeader("Bugsnag-Api-Key",f.config.apiKey),_.setRequestHeader("Bugsnag-Payload-Version","1"),_.setRequestHeader("Bugsnag-Sent-At",Ye()),_.send(fr.session(h,f.config.filters))}catch(w){f._logger.error(w)}}}},nr={init:function(f,d){d===void 0&&(d=window),f.config.beforeSend.unshift(function(h){h.context||(h.context=d.location.pathname)})}};function Ot(){return Ot=Object.assign||function(f){for(var d=1;d<arguments.length;d++){var h=arguments[d];for(var y in h)Object.prototype.hasOwnProperty.call(h,y)&&(f[y]=h[y])}return f},Ot.apply(this,arguments)}var ir=v.isoDate,Pr={init:function(f,d){d===void 0&&(d=navigator);var h={locale:d.browserLanguage||d.systemLanguage||d.userLanguage||d.language,userAgent:d.userAgent};f.device=Ot({},h,f.device),f.config.beforeSend.unshift(function(y){y.device=Ot({},y.device,{time:ir()})})}};function Mr(){return Mr=Object.assign||function(f){for(var d=1;d<arguments.length;d++){var h=arguments[d];for(var y in h)Object.prototype.hasOwnProperty.call(h,y)&&(f[y]=h[y])}return f},Mr.apply(this,arguments)}var dr={init:function(f,d){d===void 0&&(d=window),f.config.beforeSend.unshift(function(h){h.request&&h.request.url||(h.request=Mr({},h.request,{url:d.location.href}))})}};function $n(){return $n=Object.assign||function(f){for(var d=1;d<arguments.length;d++){var h=arguments[d];for(var y in h)Object.prototype.hasOwnProperty.call(h,y)&&(f[y]=h[y])}return f},$n.apply(this,arguments)}var Gr=v.isArray,oa=v.includes,ja={init:function(f){return f.sessionDelegate(Fa)}},Fa={startSession:function(f){var d=f;d._session=new f.BugsnagSession;var h=rt(d);return Gr(d.config.notifyReleaseStages)&&!oa(d.config.notifyReleaseStages,h)?(d._logger.warn("Session not sent due to releaseStage/notifyReleaseStages configuration"),d):d.config.endpoints.sessions?(d._delivery.sendSession({notifier:d.notifier,device:d.device,app:$n({},{releaseStage:h},d.app),sessions:[{id:d._session.id,startedAt:d._session.startedAt,user:d.user}]}),d):(d._logger.warn("Session not sent due to missing endpoints.sessions configuration"),d)}};function Er(){return Er=Object.assign||function(f){for(var d=1;d<arguments.length;d++){var h=arguments[d];for(var y in h)Object.prototype.hasOwnProperty.call(h,y)&&(f[y]=h[y])}return f},Er.apply(this,arguments)}var Ua={init:function(f){f.config.collectUserIp||f.config.beforeSend.push(function(d){d.user&&typeof d.user.id>"u"&&delete d.user.id,d.user=Er({id:"[NOT COLLECTED]"},d.user),d.request=Er({clientIp:"[NOT COLLECTED]"},d.request)})},configSchema:{collectUserIp:{defaultValue:function(){return!0},message:"should be true|false",validate:function(f){return f===!0||f===!1}}}},ci={},or=v.map,Ba=v.reduce,gn=v.filter;ci.init=function(f){var d=/^dev(elopment)?$/.test(f.config.releaseStage),h=f.config.consoleBreadcrumbsEnabled===!1,y=(f.config.autoBreadcrumbs===!1||d)&&f.config.consoleBreadcrumbsEnabled!==!0;h||y||or(Oi,function(g){var _=console[g];console[g]=function(){for(var w=arguments.length,S=new Array(w),C=0;C<w;C++)S[C]=arguments[C];f.leaveBreadcrumb("Console output",Ba(S,function(B,U,H){var G="[Unknown value]";try{G=String(U)}catch{}if(G==="[object Object]")try{G=JSON.stringify(U)}catch{}return B["["+H+"]"]=G,B},{severity:g.indexOf("group")===0?"log":g}),"log"),_.apply(console,S)},console[g]._restore=function(){console[g]=_}})},ci.configSchema={consoleBreadcrumbsEnabled:{defaultValue:function(){},validate:function(f){return f===!0||f===!1||f===void 0},message:"should be true|false"}};var Oi=gn(["log","debug","info","warn","error"],function(f){return typeof console<"u"&&typeof console[f]=="function"}),Ai=v.map,qa=v.reduce,yn=v.filter,At=200,ua=5e5,ca={init:function(f,d,h){if(d===void 0&&(d=document),h===void 0&&(h=window),!f.config.trackInlineScripts)return;var y=h.location.href,g="",_=!1,w=function(){return d.documentElement.outerHTML};g=w();var S=d.onreadystatechange;d.onreadystatechange=function(){d.readyState==="interactive"&&(g=w(),_=!0);try{S.apply(this,arguments)}catch{}};var C=null,B=function(We){C=We},U=function(){var We=d.currentScript||C;if(!We&&!_){var Ve=d.scripts||d.getElementsByTagName("script");We=Ve[Ve.length-1]}return We},H=function(We){(!_||!g)&&(g=w());var Ve=["<!-- DOC START -->"].concat(g.split(`
487
- `)),Nt=We-1,Tt=Math.max(Nt-3,0),pt=Math.min(Nt+3,Ve.length);return qa(Ve.slice(Tt,pt),function(hr,fi,ut){return hr[Tt+1+ut]=fi.length<=At?fi:fi.substr(0,At),hr},{})};f.config.beforeSend.unshift(function(We){We.stacktrace=yn(We.stacktrace,function(pt){return!/__trace__$/.test(pt.method)});var Ve=We.stacktrace[0];if(!(Ve&&Ve.file&&Ve.file.replace(/#.*$/,"")!==y.replace(/#.*$/,""))){var Nt=U();if(Nt){var Tt=Nt.innerHTML;We.updateMetaData("script","content",Tt.length<=ua?Tt:Tt.substr(0,ua))}!Ve||!Ve.lineNumber||(Ve.code=H(Ve.lineNumber))}});var G=Ai(["setTimeout","setInterval","setImmediate","requestAnimationFrame"],function(We){return Pi(h,We,function(Ve){return Xe(Ve,function(Nt){return{get:function(){return Nt[0]},replace:function(Tt){Nt[0]=Tt}}})})}),Le=G[0];Ai(["EventTarget","Window","Node","ApplicationCache","AudioTrackList","ChannelMergerNode","CryptoOperation","EventSource","FileReader","HTMLUnknownElement","IDBDatabase","IDBRequest","IDBTransaction","KeyOperation","MediaController","MessagePort","ModalWindow","Notification","SVGElementInstance","Screen","TextTrack","TextTrackCue","TextTrackList","WebSocket","WebSocketWorker","Worker","XMLHttpRequest","XMLHttpRequestEventTarget","XMLHttpRequestUpload"],function(We){!h[We]||!h[We].prototype||!h[We].prototype.hasOwnProperty||!h[We].prototype.hasOwnProperty("addEventListener")||(Pi(h[We].prototype,"addEventListener",function(Ve){return Xe(Ve,Mi)}),Pi(h[We].prototype,"removeEventListener",function(Ve){return Xe(Ve,Mi,!0)}))});function Xe(We,Ve,Nt){return Nt===void 0&&(Nt=!1),function(){var Tt=Array.prototype.slice.call(arguments);try{var pt=Ve(Tt),hr=pt.get();if(Nt&&We.apply(this,Tt),typeof hr!="function")return We.apply(this,Tt);if(hr.__trace__)pt.replace(hr.__trace__);else{var fi=U();hr.__trace__=function(){B(fi),Le(function(){B(null)},0);var di=hr.apply(this,arguments);return B(null),di},hr.__trace__.__trace__=hr.__trace__,pt.replace(hr.__trace__)}}catch{}if(We.apply)return We.apply(this,Tt);switch(Tt.length){case 1:return We(Tt[0]);case 2:return We(Tt[0],Tt[1]);default:return We()}}}},configSchema:{trackInlineScripts:{validate:function(f){return f===!0||f===!1},defaultValue:function(){return!0},message:"should be true|false"}}};function Pi(f,d,h){var y=f[d];if(!y)return y;var g=h(y);return f[d]=g,y}function Mi(f){var d=!!f[1]&&typeof f[1].handleEvent=="function";return{get:function(){return d?f[1].handleEvent:f[1]},replace:function(h){d?f[1].handleEvent=h:f[1]=h}}}var li={init:function(f,d){if(d===void 0&&(d=window),"addEventListener"in d){var h=f.config.interactionBreadcrumbsEnabled===!1,y=f.config.autoBreadcrumbs===!1&&f.config.interactionBreadcrumbsEnabled!==!0;h||y||d.addEventListener("click",function(g){var _,w;try{_=Hn(g.target),w=kr(g.target,d)}catch{_="[hidden]",w="[hidden]",f._logger.error("Cross domain error when tracking click event. See docs: https://tinyurl.com/yy3rn63z")}f.leaveBreadcrumb("UI click",{targetText:_,targetSelector:w},"user")},!0)}},configSchema:{interactionBreadcrumbsEnabled:{defaultValue:function(){},validate:function(f){return f===!0||f===!1||f===void 0},message:"should be true|false"}}},Hn=function(f){var d=f.textContent||f.innerText||"";return!d&&(f.type==="submit"||f.type==="button")&&(d=f.value),d=d.replace(/^\s+|\s+$/g,""),la(d,140)};function kr(f,d){var h=[f.tagName];if(f.id&&h.push("#"+f.id),f.className&&f.className.length&&h.push("."+f.className.split(" ").join(".")),!d.document.querySelectorAll||!Array.prototype.indexOf)return h.join("");try{if(d.document.querySelectorAll(h.join("")).length===1)return h.join("")}catch{return h.join("")}if(f.parentNode.childNodes.length>1){var y=Array.prototype.indexOf.call(f.parentNode.childNodes,f)+1;h.push(":nth-child("+y+")")}return d.document.querySelectorAll(h.join("")).length===1?h.join(""):f.parentNode?kr(f.parentNode,d)+" > "+h.join(""):h.join("")}function la(f,d){var h="(...)";return f&&f.length<=d?f:f.slice(0,d-h.length)+h}var Rr={};Rr.init=function(f,d){if(d===void 0&&(d=window),"addEventListener"in d){var h=f.config.navigationBreadcrumbsEnabled===!1,y=f.config.autoBreadcrumbs===!1&&f.config.navigationBreadcrumbsEnabled!==!0;if(!(h||y)){var g=function(_){return function(){return f.leaveBreadcrumb(_,{},"navigation")}};d.addEventListener("pagehide",g("Page hidden"),!0),d.addEventListener("pageshow",g("Page shown"),!0),d.addEventListener("load",g("Page loaded"),!0),d.document.addEventListener("DOMContentLoaded",g("DOMContentLoaded"),!0),d.addEventListener("load",function(){return d.addEventListener("popstate",g("Navigated back"),!0)}),d.addEventListener("hashchange",function(_){var w=_.oldURL?{from:Hr(_.oldURL,d),to:Hr(_.newURL,d),state:F(d)}:{to:Hr(d.location.href,d)};f.leaveBreadcrumb("Hash changed",w,"navigation")},!0),d.history.replaceState&&fa(f,d.history,"replaceState",d),d.history.pushState&&fa(f,d.history,"pushState",d),f.leaveBreadcrumb("Bugsnag loaded",{},"navigation")}}},Rr.configSchema={navigationBreadcrumbsEnabled:{defaultValue:function(){},validate:function(f){return f===!0||f===!1||f===void 0},message:"should be true|false"}};var Hr=function(f,d){var h=d.document.createElement("A");return h.href=f,""+h.pathname+h.search+h.hash},bn=function(f,d,h,y){var g=Hr(f.location.href,f);return{title:h,state:d,prevState:F(f),to:y||g,from:g}},fa=function(f,d,h,y){var g=d[h];d[h]=function(_,w,S){f.leaveBreadcrumb("History "+h,bn(y,_,w,S),"navigation"),typeof f.refresh=="function"&&f.refresh(),f.config.autoCaptureSessions&&f.startSession(),g.apply(d,[_,w].concat(S!==void 0?S:[]))}},F=function(f){try{return f.history.state}catch{}},z={},$="request",k="BS~~S",E="BS~~U",q="BS~~M",M=v.includes,ve,fe,Ae,Be=function(){return[ve.config.endpoints.notify,ve.config.endpoints.sessions]};z.name="networkBreadcrumbs",z.init=function(f,d,h){d===void 0&&(d=Be),h===void 0&&(h=window);var y=f.config.networkBreadcrumbsEnabled===!1,g=f.config.autoBreadcrumbs===!1&&f.config.networkBreadcrumbsEnabled!==!0;y||g||(ve=f,fe=h,Ae=d,ot(),br())},z.configSchema={networkBreadcrumbsEnabled:{defaultValue:function(){},validate:function(f){return f===!0||f===!1||f===void 0},message:"should be true|false"}};var ot=function(){if("addEventListener"in fe.XMLHttpRequest.prototype){var f=fe.XMLHttpRequest.prototype.open;fe.XMLHttpRequest.prototype.open=function(h,y){this[E]=y,this[q]=h,this[k]&&(this.removeEventListener("load",$r),this.removeEventListener("error",ln)),this.addEventListener("load",$r),this.addEventListener("error",ln),this[k]=!0,f.apply(this,arguments)}}};function $r(){if(!M(Ae(),this[E])){var f={status:this.status,request:this[q]+" "+this[E]};this.status>=400?ve.leaveBreadcrumb("XMLHttpRequest failed",f,$):ve.leaveBreadcrumb("XMLHttpRequest succeeded",f,$)}}function ln(){M(Ae,this[E])||ve.leaveBreadcrumb("XMLHttpRequest error",{request:this[q]+" "+this[E]},$)}var br=function(){if(!(!("fetch"in fe)||fe.fetch.polyfill)){var f=fe.fetch;fe.fetch=function(){var h=arguments,y=arguments[0],g=arguments[1],_,w=null;return y&&typeof y=="object"?(w=y.url,g&&"method"in g?_=g.method:y&&"method"in y&&(_=y.method)):(w=y,g&&"method"in g&&(_=g.method)),_===void 0&&(_="GET"),new Promise(function(S,C){f.apply(void 0,h).then(function(B){_n(B,_,w),S(B)}).catch(function(B){Cs(_,w),C(B)})})}}},_n=function(f,d,h){var y={status:f.status,request:d+" "+h};f.status>=400?ve.leaveBreadcrumb("fetch() failed",y,$):ve.leaveBreadcrumb("fetch() succeeded",y,$)},Cs=function(f,d){ve.leaveBreadcrumb("fetch() error",{request:f+" "+d},$)},ko=m.intRange,W={init:function(f){var d=0;f.config.beforeSend.push(function(h){if(d>=f.config.maxEvents)return h.ignore();d++}),f.refresh=function(){d=0}},configSchema:{maxEvents:{defaultValue:function(){return 10},message:"should be a positive integer ≤100",validate:function(f){return ko(1,100)(f)}}}},ie={};function Ee(){return Ee=Object.assign||function(f){for(var d=1;d<arguments.length;d++){var h=arguments[d];for(var y in h)Object.prototype.hasOwnProperty.call(h,y)&&(f[y]=h[y])}return f},Ee.apply(this,arguments)}var Ze=v.map;ie={init:function(f){f.config.beforeSend.push(function(d){d.stacktrace=Ze(d.stacktrace,function(h){return Ee({},h,{file:Kt(h.file)})})})}};var Kt=ie._strip=function(f){return typeof f=="string"?f.replace(/\?.*$/,"").replace(/#.*$/,""):f},_t={init:function(f,d){d===void 0&&(d=window);function h(g,_,w,S,C){if(w===0&&/Script error\.?/.test(g))f._logger.warn("Ignoring cross-domain or eval script error. See docs: https://tinyurl.com/yy3rn63z");else{var B={severity:"error",unhandled:!0,severityReason:{type:"unhandledException"}},U;if(C)C.name&&C.message?U=new f.BugsnagReport(C.name,C.message,Jt(f.BugsnagReport.getStacktrace(C),_,w,S),B,C):(U=new f.BugsnagReport("window.onerror",String(C),Jt(f.BugsnagReport.getStacktrace(C,1),_,w,S),B,C),U.updateMetaData("window onerror",{error:C}));else if(typeof g=="object"&&g!==null&&(!_||typeof _!="string")&&!w&&!S&&!C){var H=g.type?"Event: "+g.type:"window.onerror",G=g.message||g.detail||"";U=new f.BugsnagReport(H,G,f.BugsnagReport.getStacktrace(new Error,1).slice(1),B,g),U.updateMetaData("window onerror",{event:g,extraParameters:_})}else U=new f.BugsnagReport("window.onerror",String(g),Jt(f.BugsnagReport.getStacktrace(C,1),_,w,S),B,g),U.updateMetaData("window onerror",{event:g});f.notify(U)}typeof y=="function"&&y.apply(this,arguments)}var y=d.onerror;d.onerror=h}},Jt=function(f,d,h,y){var g=f[0];return g&&(!g.fileName&&typeof d=="string"&&g.setFileName(d),!g.lineNumber&&ur(h)&&g.setLineNumber(h),g.columnNumber||(ur(y)?g.setColumnNumber(y):window.event&&ur(window.event.errorCharacter)&&g.setColumnNumber(window.event.errorCharacter))),f},ur=function(f){return typeof f=="number"&&String.call(f)!=="NaN"},_r={},lt=v.reduce;_r.init=function(f,d){d===void 0&&(d=window);var h=function(y){var g=y.reason,_=!1;try{y.detail&&y.detail.reason&&(g=y.detail.reason,_=!0)}catch{}var w={severity:"error",unhandled:!0,severityReason:{type:"unhandledPromiseRejection"}},S;if(g&&_e(g))S=new f.BugsnagReport(g.name,g.message,Ne.parse(g),w,g),_&&(S.stacktrace=lt(S.stacktrace,Fr(g),[]));else{var C='Rejection reason was not an Error. See "Promise" tab for more detail.';S=new f.BugsnagReport(g&&g.name?g.name:"UnhandledRejection",g&&g.message?g.message:C,[],w,g),S.updateMetaData("promise","rejection reason",jr(g))}f.notify(S)};"addEventListener"in d?d.addEventListener("unhandledrejection",h):d.onunhandledrejection=function(y,g){h({detail:{reason:y,promise:g}})}};var jr=function(f){if(f==null)return"undefined (or null)";if(ce(f)){var d;return d={},d[Object.prototype.toString.call(f)]={name:f.name,message:f.message,code:f.code,stack:f.stack},d}else return f},Fr=function(f){return function(d,h){return h.file===f.toString()?d:(h.method&&(h.method=h.method.replace(/^\s+/,"")),d.concat(h))}},pr={};function Ur(){return Ur=Object.assign||function(f){for(var d=1;d<arguments.length;d++){var h=arguments[d];for(var y in h)Object.prototype.hasOwnProperty.call(h,y)&&(f[y]=h[y])}return f},Ur.apply(this,arguments)}var gt="Bugsnag JavaScript",In="6.5.2",O="https://github.com/bugsnag/bugsnag-js",A=Ur({},b.schema,ue);return pr=function(f){typeof f=="string"&&(f={apiKey:f});var d="";f.endpoints&&f.endpoints.notify&&!f.endpoints.sessions&&(d+="notify endpoint is set but sessions endpoint is not. No sessions will be sent.");var h=new oe({name:gt,version:In,url:O});return h.setOptions(f),h.delivery(window.XDomainRequest?cn:Mt),h.configure(A),d&&h._logger.warn(d),h.use(Pr),h.use(nr),h.use(dr),h.use(W),h.use(ja),h.use(Ua),h.use(ie),h.config.autoNotify!==!1&&(h.use(_t),h.use(_r)),h.use(Rr),h.use(li),h.use(z),h.use(ci),h.use(ca),h._logger.debug("Loaded!"),h.config.autoCaptureSessions?h.startSession():h},pr.Bugsnag={Client:oe,Report:St,Session:gr,Breadcrumb:pe},pr.default=pr,pr})})(H$);var _ee=H$.exports,wee=_ee,Pv={exports:{}};const F0="[a-fA-F\\d:]",_a=e=>e&&e.includeBoundaries?`(?:(?<=\\s|^)(?=${F0})|(?<=${F0})(?=\\s|$))`:"",Qn="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",Ir="[a-fA-F\\d]{1,4}",Zf=`
486
+ metaData was removed`},h=Y(f,null,null,{filterPaths:dt,filterKeys:d}),h.length>1e6))throw new Error("payload exceeded 1MB limit");return h},fr.session=function(f,d){var h=Y(f,null,null,{filterPaths:Gr,filterKeys:d});if(h.length>1e6)throw new Error("payload exceeded 1MB limit");return h};var cn={},it=v.isoDate;cn=function(f,d){return d===void 0&&(d=window),{sendReport:function(h,y){y===void 0&&(y=function(){});var g=Z(f.config,"notify","4",d),_=new d.XDomainRequest;_.onload=function(){y(null)},_.open("POST",g),setTimeout(function(){try{_.send(fr.report(h,f.config.filters))}catch(w){f._logger.error(w),y(w)}},0)},sendSession:function(h,y){y===void 0&&(y=function(){});var g=Z(f.config,"sessions","1",d),_=new d.XDomainRequest;_.onload=function(){y(null)},_.open("POST",g),setTimeout(function(){try{_.send(fr.session(h,f.config.filters))}catch(w){f._logger.error(w),y(w)}},0)}}};var Z=function(f,d,h,y){return xe(f.endpoints[d],y.location.protocol)+"?apiKey="+encodeURIComponent(f.apiKey)+"&payloadVersion="+h+"&sentAt="+encodeURIComponent(it())},xe=cn._matchPageProtocol=function(f,d){return d==="http:"?f.replace(/^https:/,"http:"):f},Ye=v.isoDate,Mt=function(f,d){return d===void 0&&(d=window),{sendReport:function(h,y){y===void 0&&(y=function(){});try{var g=f.config.endpoints.notify,_=new d.XMLHttpRequest;_.onreadystatechange=function(){_.readyState===d.XMLHttpRequest.DONE&&y(null)},_.open("POST",g),_.setRequestHeader("Content-Type","application/json"),_.setRequestHeader("Bugsnag-Api-Key",h.apiKey||f.config.apiKey),_.setRequestHeader("Bugsnag-Payload-Version","4"),_.setRequestHeader("Bugsnag-Sent-At",Ye()),_.send(fr.report(h,f.config.filters))}catch(w){f._logger.error(w)}},sendSession:function(h,y){y===void 0&&(y=function(){});try{var g=f.config.endpoints.sessions,_=new d.XMLHttpRequest;_.onreadystatechange=function(){_.readyState===d.XMLHttpRequest.DONE&&y(null)},_.open("POST",g),_.setRequestHeader("Content-Type","application/json"),_.setRequestHeader("Bugsnag-Api-Key",f.config.apiKey),_.setRequestHeader("Bugsnag-Payload-Version","1"),_.setRequestHeader("Bugsnag-Sent-At",Ye()),_.send(fr.session(h,f.config.filters))}catch(w){f._logger.error(w)}}}},nr={init:function(f,d){d===void 0&&(d=window),f.config.beforeSend.unshift(function(h){h.context||(h.context=d.location.pathname)})}};function Ot(){return Ot=Object.assign||function(f){for(var d=1;d<arguments.length;d++){var h=arguments[d];for(var y in h)Object.prototype.hasOwnProperty.call(h,y)&&(f[y]=h[y])}return f},Ot.apply(this,arguments)}var ir=v.isoDate,Pr={init:function(f,d){d===void 0&&(d=navigator);var h={locale:d.browserLanguage||d.systemLanguage||d.userLanguage||d.language,userAgent:d.userAgent};f.device=Ot({},h,f.device),f.config.beforeSend.unshift(function(y){y.device=Ot({},y.device,{time:ir()})})}};function Mr(){return Mr=Object.assign||function(f){for(var d=1;d<arguments.length;d++){var h=arguments[d];for(var y in h)Object.prototype.hasOwnProperty.call(h,y)&&(f[y]=h[y])}return f},Mr.apply(this,arguments)}var dr={init:function(f,d){d===void 0&&(d=window),f.config.beforeSend.unshift(function(h){h.request&&h.request.url||(h.request=Mr({},h.request,{url:d.location.href}))})}};function $n(){return $n=Object.assign||function(f){for(var d=1;d<arguments.length;d++){var h=arguments[d];for(var y in h)Object.prototype.hasOwnProperty.call(h,y)&&(f[y]=h[y])}return f},$n.apply(this,arguments)}var Hr=v.isArray,oa=v.includes,ja={init:function(f){return f.sessionDelegate(Fa)}},Fa={startSession:function(f){var d=f;d._session=new f.BugsnagSession;var h=rt(d);return Hr(d.config.notifyReleaseStages)&&!oa(d.config.notifyReleaseStages,h)?(d._logger.warn("Session not sent due to releaseStage/notifyReleaseStages configuration"),d):d.config.endpoints.sessions?(d._delivery.sendSession({notifier:d.notifier,device:d.device,app:$n({},{releaseStage:h},d.app),sessions:[{id:d._session.id,startedAt:d._session.startedAt,user:d.user}]}),d):(d._logger.warn("Session not sent due to missing endpoints.sessions configuration"),d)}};function Er(){return Er=Object.assign||function(f){for(var d=1;d<arguments.length;d++){var h=arguments[d];for(var y in h)Object.prototype.hasOwnProperty.call(h,y)&&(f[y]=h[y])}return f},Er.apply(this,arguments)}var Ua={init:function(f){f.config.collectUserIp||f.config.beforeSend.push(function(d){d.user&&typeof d.user.id>"u"&&delete d.user.id,d.user=Er({id:"[NOT COLLECTED]"},d.user),d.request=Er({clientIp:"[NOT COLLECTED]"},d.request)})},configSchema:{collectUserIp:{defaultValue:function(){return!0},message:"should be true|false",validate:function(f){return f===!0||f===!1}}}},ci={},or=v.map,Ba=v.reduce,gn=v.filter;ci.init=function(f){var d=/^dev(elopment)?$/.test(f.config.releaseStage),h=f.config.consoleBreadcrumbsEnabled===!1,y=(f.config.autoBreadcrumbs===!1||d)&&f.config.consoleBreadcrumbsEnabled!==!0;h||y||or(Oi,function(g){var _=console[g];console[g]=function(){for(var w=arguments.length,S=new Array(w),C=0;C<w;C++)S[C]=arguments[C];f.leaveBreadcrumb("Console output",Ba(S,function(B,U,H){var G="[Unknown value]";try{G=String(U)}catch{}if(G==="[object Object]")try{G=JSON.stringify(U)}catch{}return B["["+H+"]"]=G,B},{severity:g.indexOf("group")===0?"log":g}),"log"),_.apply(console,S)},console[g]._restore=function(){console[g]=_}})},ci.configSchema={consoleBreadcrumbsEnabled:{defaultValue:function(){},validate:function(f){return f===!0||f===!1||f===void 0},message:"should be true|false"}};var Oi=gn(["log","debug","info","warn","error"],function(f){return typeof console<"u"&&typeof console[f]=="function"}),Ai=v.map,qa=v.reduce,yn=v.filter,At=200,ua=5e5,ca={init:function(f,d,h){if(d===void 0&&(d=document),h===void 0&&(h=window),!f.config.trackInlineScripts)return;var y=h.location.href,g="",_=!1,w=function(){return d.documentElement.outerHTML};g=w();var S=d.onreadystatechange;d.onreadystatechange=function(){d.readyState==="interactive"&&(g=w(),_=!0);try{S.apply(this,arguments)}catch{}};var C=null,B=function(We){C=We},U=function(){var We=d.currentScript||C;if(!We&&!_){var Ve=d.scripts||d.getElementsByTagName("script");We=Ve[Ve.length-1]}return We},H=function(We){(!_||!g)&&(g=w());var Ve=["<!-- DOC START -->"].concat(g.split(`
487
+ `)),Nt=We-1,Tt=Math.max(Nt-3,0),pt=Math.min(Nt+3,Ve.length);return qa(Ve.slice(Tt,pt),function(hr,fi,ut){return hr[Tt+1+ut]=fi.length<=At?fi:fi.substr(0,At),hr},{})};f.config.beforeSend.unshift(function(We){We.stacktrace=yn(We.stacktrace,function(pt){return!/__trace__$/.test(pt.method)});var Ve=We.stacktrace[0];if(!(Ve&&Ve.file&&Ve.file.replace(/#.*$/,"")!==y.replace(/#.*$/,""))){var Nt=U();if(Nt){var Tt=Nt.innerHTML;We.updateMetaData("script","content",Tt.length<=ua?Tt:Tt.substr(0,ua))}!Ve||!Ve.lineNumber||(Ve.code=H(Ve.lineNumber))}});var G=Ai(["setTimeout","setInterval","setImmediate","requestAnimationFrame"],function(We){return Pi(h,We,function(Ve){return Xe(Ve,function(Nt){return{get:function(){return Nt[0]},replace:function(Tt){Nt[0]=Tt}}})})}),Le=G[0];Ai(["EventTarget","Window","Node","ApplicationCache","AudioTrackList","ChannelMergerNode","CryptoOperation","EventSource","FileReader","HTMLUnknownElement","IDBDatabase","IDBRequest","IDBTransaction","KeyOperation","MediaController","MessagePort","ModalWindow","Notification","SVGElementInstance","Screen","TextTrack","TextTrackCue","TextTrackList","WebSocket","WebSocketWorker","Worker","XMLHttpRequest","XMLHttpRequestEventTarget","XMLHttpRequestUpload"],function(We){!h[We]||!h[We].prototype||!h[We].prototype.hasOwnProperty||!h[We].prototype.hasOwnProperty("addEventListener")||(Pi(h[We].prototype,"addEventListener",function(Ve){return Xe(Ve,Mi)}),Pi(h[We].prototype,"removeEventListener",function(Ve){return Xe(Ve,Mi,!0)}))});function Xe(We,Ve,Nt){return Nt===void 0&&(Nt=!1),function(){var Tt=Array.prototype.slice.call(arguments);try{var pt=Ve(Tt),hr=pt.get();if(Nt&&We.apply(this,Tt),typeof hr!="function")return We.apply(this,Tt);if(hr.__trace__)pt.replace(hr.__trace__);else{var fi=U();hr.__trace__=function(){B(fi),Le(function(){B(null)},0);var di=hr.apply(this,arguments);return B(null),di},hr.__trace__.__trace__=hr.__trace__,pt.replace(hr.__trace__)}}catch{}if(We.apply)return We.apply(this,Tt);switch(Tt.length){case 1:return We(Tt[0]);case 2:return We(Tt[0],Tt[1]);default:return We()}}}},configSchema:{trackInlineScripts:{validate:function(f){return f===!0||f===!1},defaultValue:function(){return!0},message:"should be true|false"}}};function Pi(f,d,h){var y=f[d];if(!y)return y;var g=h(y);return f[d]=g,y}function Mi(f){var d=!!f[1]&&typeof f[1].handleEvent=="function";return{get:function(){return d?f[1].handleEvent:f[1]},replace:function(h){d?f[1].handleEvent=h:f[1]=h}}}var li={init:function(f,d){if(d===void 0&&(d=window),"addEventListener"in d){var h=f.config.interactionBreadcrumbsEnabled===!1,y=f.config.autoBreadcrumbs===!1&&f.config.interactionBreadcrumbsEnabled!==!0;h||y||d.addEventListener("click",function(g){var _,w;try{_=Hn(g.target),w=kr(g.target,d)}catch{_="[hidden]",w="[hidden]",f._logger.error("Cross domain error when tracking click event. See docs: https://tinyurl.com/yy3rn63z")}f.leaveBreadcrumb("UI click",{targetText:_,targetSelector:w},"user")},!0)}},configSchema:{interactionBreadcrumbsEnabled:{defaultValue:function(){},validate:function(f){return f===!0||f===!1||f===void 0},message:"should be true|false"}}},Hn=function(f){var d=f.textContent||f.innerText||"";return!d&&(f.type==="submit"||f.type==="button")&&(d=f.value),d=d.replace(/^\s+|\s+$/g,""),la(d,140)};function kr(f,d){var h=[f.tagName];if(f.id&&h.push("#"+f.id),f.className&&f.className.length&&h.push("."+f.className.split(" ").join(".")),!d.document.querySelectorAll||!Array.prototype.indexOf)return h.join("");try{if(d.document.querySelectorAll(h.join("")).length===1)return h.join("")}catch{return h.join("")}if(f.parentNode.childNodes.length>1){var y=Array.prototype.indexOf.call(f.parentNode.childNodes,f)+1;h.push(":nth-child("+y+")")}return d.document.querySelectorAll(h.join("")).length===1?h.join(""):f.parentNode?kr(f.parentNode,d)+" > "+h.join(""):h.join("")}function la(f,d){var h="(...)";return f&&f.length<=d?f:f.slice(0,d-h.length)+h}var Rr={};Rr.init=function(f,d){if(d===void 0&&(d=window),"addEventListener"in d){var h=f.config.navigationBreadcrumbsEnabled===!1,y=f.config.autoBreadcrumbs===!1&&f.config.navigationBreadcrumbsEnabled!==!0;if(!(h||y)){var g=function(_){return function(){return f.leaveBreadcrumb(_,{},"navigation")}};d.addEventListener("pagehide",g("Page hidden"),!0),d.addEventListener("pageshow",g("Page shown"),!0),d.addEventListener("load",g("Page loaded"),!0),d.document.addEventListener("DOMContentLoaded",g("DOMContentLoaded"),!0),d.addEventListener("load",function(){return d.addEventListener("popstate",g("Navigated back"),!0)}),d.addEventListener("hashchange",function(_){var w=_.oldURL?{from:Vr(_.oldURL,d),to:Vr(_.newURL,d),state:F(d)}:{to:Vr(d.location.href,d)};f.leaveBreadcrumb("Hash changed",w,"navigation")},!0),d.history.replaceState&&fa(f,d.history,"replaceState",d),d.history.pushState&&fa(f,d.history,"pushState",d),f.leaveBreadcrumb("Bugsnag loaded",{},"navigation")}}},Rr.configSchema={navigationBreadcrumbsEnabled:{defaultValue:function(){},validate:function(f){return f===!0||f===!1||f===void 0},message:"should be true|false"}};var Vr=function(f,d){var h=d.document.createElement("A");return h.href=f,""+h.pathname+h.search+h.hash},bn=function(f,d,h,y){var g=Vr(f.location.href,f);return{title:h,state:d,prevState:F(f),to:y||g,from:g}},fa=function(f,d,h,y){var g=d[h];d[h]=function(_,w,S){f.leaveBreadcrumb("History "+h,bn(y,_,w,S),"navigation"),typeof f.refresh=="function"&&f.refresh(),f.config.autoCaptureSessions&&f.startSession(),g.apply(d,[_,w].concat(S!==void 0?S:[]))}},F=function(f){try{return f.history.state}catch{}},z={},$="request",k="BS~~S",E="BS~~U",q="BS~~M",M=v.includes,ve,fe,Ae,Be=function(){return[ve.config.endpoints.notify,ve.config.endpoints.sessions]};z.name="networkBreadcrumbs",z.init=function(f,d,h){d===void 0&&(d=Be),h===void 0&&(h=window);var y=f.config.networkBreadcrumbsEnabled===!1,g=f.config.autoBreadcrumbs===!1&&f.config.networkBreadcrumbsEnabled!==!0;y||g||(ve=f,fe=h,Ae=d,ot(),br())},z.configSchema={networkBreadcrumbsEnabled:{defaultValue:function(){},validate:function(f){return f===!0||f===!1||f===void 0},message:"should be true|false"}};var ot=function(){if("addEventListener"in fe.XMLHttpRequest.prototype){var f=fe.XMLHttpRequest.prototype.open;fe.XMLHttpRequest.prototype.open=function(h,y){this[E]=y,this[q]=h,this[k]&&(this.removeEventListener("load",$r),this.removeEventListener("error",ln)),this.addEventListener("load",$r),this.addEventListener("error",ln),this[k]=!0,f.apply(this,arguments)}}};function $r(){if(!M(Ae(),this[E])){var f={status:this.status,request:this[q]+" "+this[E]};this.status>=400?ve.leaveBreadcrumb("XMLHttpRequest failed",f,$):ve.leaveBreadcrumb("XMLHttpRequest succeeded",f,$)}}function ln(){M(Ae,this[E])||ve.leaveBreadcrumb("XMLHttpRequest error",{request:this[q]+" "+this[E]},$)}var br=function(){if(!(!("fetch"in fe)||fe.fetch.polyfill)){var f=fe.fetch;fe.fetch=function(){var h=arguments,y=arguments[0],g=arguments[1],_,w=null;return y&&typeof y=="object"?(w=y.url,g&&"method"in g?_=g.method:y&&"method"in y&&(_=y.method)):(w=y,g&&"method"in g&&(_=g.method)),_===void 0&&(_="GET"),new Promise(function(S,C){f.apply(void 0,h).then(function(B){_n(B,_,w),S(B)}).catch(function(B){Cs(_,w),C(B)})})}}},_n=function(f,d,h){var y={status:f.status,request:d+" "+h};f.status>=400?ve.leaveBreadcrumb("fetch() failed",y,$):ve.leaveBreadcrumb("fetch() succeeded",y,$)},Cs=function(f,d){ve.leaveBreadcrumb("fetch() error",{request:f+" "+d},$)},ko=m.intRange,W={init:function(f){var d=0;f.config.beforeSend.push(function(h){if(d>=f.config.maxEvents)return h.ignore();d++}),f.refresh=function(){d=0}},configSchema:{maxEvents:{defaultValue:function(){return 10},message:"should be a positive integer ≤100",validate:function(f){return ko(1,100)(f)}}}},ie={};function Ee(){return Ee=Object.assign||function(f){for(var d=1;d<arguments.length;d++){var h=arguments[d];for(var y in h)Object.prototype.hasOwnProperty.call(h,y)&&(f[y]=h[y])}return f},Ee.apply(this,arguments)}var Ze=v.map;ie={init:function(f){f.config.beforeSend.push(function(d){d.stacktrace=Ze(d.stacktrace,function(h){return Ee({},h,{file:Kt(h.file)})})})}};var Kt=ie._strip=function(f){return typeof f=="string"?f.replace(/\?.*$/,"").replace(/#.*$/,""):f},_t={init:function(f,d){d===void 0&&(d=window);function h(g,_,w,S,C){if(w===0&&/Script error\.?/.test(g))f._logger.warn("Ignoring cross-domain or eval script error. See docs: https://tinyurl.com/yy3rn63z");else{var B={severity:"error",unhandled:!0,severityReason:{type:"unhandledException"}},U;if(C)C.name&&C.message?U=new f.BugsnagReport(C.name,C.message,Jt(f.BugsnagReport.getStacktrace(C),_,w,S),B,C):(U=new f.BugsnagReport("window.onerror",String(C),Jt(f.BugsnagReport.getStacktrace(C,1),_,w,S),B,C),U.updateMetaData("window onerror",{error:C}));else if(typeof g=="object"&&g!==null&&(!_||typeof _!="string")&&!w&&!S&&!C){var H=g.type?"Event: "+g.type:"window.onerror",G=g.message||g.detail||"";U=new f.BugsnagReport(H,G,f.BugsnagReport.getStacktrace(new Error,1).slice(1),B,g),U.updateMetaData("window onerror",{event:g,extraParameters:_})}else U=new f.BugsnagReport("window.onerror",String(g),Jt(f.BugsnagReport.getStacktrace(C,1),_,w,S),B,g),U.updateMetaData("window onerror",{event:g});f.notify(U)}typeof y=="function"&&y.apply(this,arguments)}var y=d.onerror;d.onerror=h}},Jt=function(f,d,h,y){var g=f[0];return g&&(!g.fileName&&typeof d=="string"&&g.setFileName(d),!g.lineNumber&&ur(h)&&g.setLineNumber(h),g.columnNumber||(ur(y)?g.setColumnNumber(y):window.event&&ur(window.event.errorCharacter)&&g.setColumnNumber(window.event.errorCharacter))),f},ur=function(f){return typeof f=="number"&&String.call(f)!=="NaN"},_r={},lt=v.reduce;_r.init=function(f,d){d===void 0&&(d=window);var h=function(y){var g=y.reason,_=!1;try{y.detail&&y.detail.reason&&(g=y.detail.reason,_=!0)}catch{}var w={severity:"error",unhandled:!0,severityReason:{type:"unhandledPromiseRejection"}},S;if(g&&_e(g))S=new f.BugsnagReport(g.name,g.message,Ne.parse(g),w,g),_&&(S.stacktrace=lt(S.stacktrace,Fr(g),[]));else{var C='Rejection reason was not an Error. See "Promise" tab for more detail.';S=new f.BugsnagReport(g&&g.name?g.name:"UnhandledRejection",g&&g.message?g.message:C,[],w,g),S.updateMetaData("promise","rejection reason",jr(g))}f.notify(S)};"addEventListener"in d?d.addEventListener("unhandledrejection",h):d.onunhandledrejection=function(y,g){h({detail:{reason:y,promise:g}})}};var jr=function(f){if(f==null)return"undefined (or null)";if(ce(f)){var d;return d={},d[Object.prototype.toString.call(f)]={name:f.name,message:f.message,code:f.code,stack:f.stack},d}else return f},Fr=function(f){return function(d,h){return h.file===f.toString()?d:(h.method&&(h.method=h.method.replace(/^\s+/,"")),d.concat(h))}},pr={};function Ur(){return Ur=Object.assign||function(f){for(var d=1;d<arguments.length;d++){var h=arguments[d];for(var y in h)Object.prototype.hasOwnProperty.call(h,y)&&(f[y]=h[y])}return f},Ur.apply(this,arguments)}var gt="Bugsnag JavaScript",In="6.5.2",O="https://github.com/bugsnag/bugsnag-js",A=Ur({},b.schema,ue);return pr=function(f){typeof f=="string"&&(f={apiKey:f});var d="";f.endpoints&&f.endpoints.notify&&!f.endpoints.sessions&&(d+="notify endpoint is set but sessions endpoint is not. No sessions will be sent.");var h=new oe({name:gt,version:In,url:O});return h.setOptions(f),h.delivery(window.XDomainRequest?cn:Mt),h.configure(A),d&&h._logger.warn(d),h.use(Pr),h.use(nr),h.use(dr),h.use(W),h.use(ja),h.use(Ua),h.use(ie),h.config.autoNotify!==!1&&(h.use(_t),h.use(_r)),h.use(Rr),h.use(li),h.use(z),h.use(ci),h.use(ca),h._logger.debug("Loaded!"),h.config.autoCaptureSessions?h.startSession():h},pr.Bugsnag={Client:oe,Report:St,Session:gr,Breadcrumb:pe},pr.default=pr,pr})})(H$);var _ee=H$.exports,wee=_ee,Pv={exports:{}};const F0="[a-fA-F\\d:]",_a=e=>e&&e.includeBoundaries?`(?:(?<=\\s|^)(?=${F0})|(?<=${F0})(?=\\s|$))`:"",Qn="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",Ir="[a-fA-F\\d]{1,4}",Zf=`
488
488
  (?:
489
489
  (?:${Ir}:){7}(?:${Ir}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8
490
490
  (?:${Ir}:){6}(?:${Qn}|:${Ir}|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4
@@ -531,4 +531,4 @@ a=extmap-allow-mixed`)!==-1){const a=i.sdp.split(`
531
531
  `).filter(s=>s.trim()!=="a=extmap-allow-mixed").join(`
532
532
  `);e.RTCSessionDescription&&i instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:i.type,sdp:a}):i.sdp=a}return r.apply(this,arguments)}}function $l(e,t){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;const r=e.RTCPeerConnection.prototype.addIceCandidate;!r||r.length===0||(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(t.browser==="chrome"&&t.version<78||t.browser==="firefox"&&t.version<68||t.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():r.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function Il(e,t){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;const r=e.RTCPeerConnection.prototype.setLocalDescription;!r||r.length===0||(e.RTCPeerConnection.prototype.setLocalDescription=function(){let i=arguments[0]||{};if(typeof i!="object"||i.type&&i.sdp)return r.apply(this,arguments);if(i={type:i.type,sdp:i.sdp},!i.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":i.type="offer";break;default:i.type="answer";break}return i.sdp||i.type!=="offer"&&i.type!=="answer"?r.apply(this,[i]):(i.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(s=>r.apply(this,[s]))})}const Wee=Object.freeze(Object.defineProperty({__proto__:null,removeExtmapAllowMixed:qv,shimAddIceCandidateNullOrEmpty:$l,shimConnectionState:Bv,shimMaxMessageSize:kl,shimParameterlessSetLocalDescription:Il,shimRTCIceCandidate:El,shimRTCIceCandidateRelayProtocol:Uv,shimSendThrowTypeError:Rl},Symbol.toStringTag,{value:"Module"}));function Gee({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const r=eI,n=Bee(e),i={browserDetails:n,commonShim:Wee,extractVersion:Cl,disableLog:Fee,disableWarnings:Uee,sdp:zee};switch(n.browser){case"chrome":if(!J0||!jv||!t.shimChrome)return r("Chrome shim is not included in this adapter release."),i;if(n.version===null)return r("Chrome shim can not determine version, not shimming."),i;r("adapter.js shimming chrome."),i.browserShim=J0,$l(e,n),Il(e),rI(e,n),nI(e),jv(e,n),iI(e),uI(e,n),aI(e),sI(e),cI(e,n),El(e),Uv(e),Bv(e),kl(e,n),Rl(e),qv(e,n);break;case"firefox":if(!Y0||!Fv||!t.shimFirefox)return r("Firefox shim is not included in this adapter release."),i;r("adapter.js shimming firefox."),i.browserShim=Y0,$l(e,n),Il(e),lI(e,n),Fv(e,n),fI(e),hI(e),dI(e),pI(e),vI(e),mI(e),gI(e),yI(e),bI(e),El(e),Bv(e),kl(e,n),Rl(e);break;case"safari":if(!X0||!t.shimSafari)return r("Safari shim is not included in this adapter release."),i;r("adapter.js shimming safari."),i.browserShim=X0,$l(e,n),Il(e),EI(e),RI(e),SI(e),_I(e),wI(e),kI(e),TI(e),$I(e),El(e),Uv(e),kl(e,n),Rl(e),qv(e,n);break;default:r("Unsupported browser!");break}return i}Gee({window:typeof window>"u"?void 0:window});var aa={},AI={},PI={exports:{}},Q0=PI.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(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.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(e){return e.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(e){return e.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(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return e.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(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=e.raddr!=null?" raddr %s rport %d":"%v%v",t+=e.tcptype!=null?" tcptype %s":"%v",e.generation!=null&&(t+=" generation %d"),t+=e["network-id"]!=null?" network-id %d":"%v",t+=e["network-cost"]!=null?" network-cost %d":"%v",t}},{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(e){var t="ssrc:%d";return e.attribute!=null&&(t+=" %s",e.value!=null&&(t+=":%s")),t}},{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(e){return e.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(e){return e.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(e){return"imageattr:%s %s %s"+(e.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(e){return"simulcast:%s %s"+(e.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(e){return"ts-refclk:%s"+(e.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=e.id!=null?"id=%s %s":"%v%s",t+=e.mediaClockValue!=null?"=%s":"",t+=e.rateNumerator!=null?" rate=%s":"",t+=e.rateDenominator!=null?"/%s":"",t}},{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(Q0).forEach(function(e){var t=Q0[e];t.forEach(function(r){r.reg||(r.reg=/(.*)/),r.format||(r.format="%s")})});var MI=PI.exports;(function(e){var t=function(o){return String(Number(o))===o?Number(o):o},r=function(o,u,c,l){if(l&&!c)u[l]=t(o[1]);else for(var p=0;p<c.length;p+=1)o[p+1]!=null&&(u[c[p]]=t(o[p+1]))},n=function(o,u,c){var l=o.name&&o.names;o.push&&!u[o.push]?u[o.push]=[]:l&&!u[o.name]&&(u[o.name]={});var p=o.push?{}:l?u[o.name]:u;r(c.match(o.reg),p,o.names,o.name),o.push&&u[o.push].push(p)},i=MI,a=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(o){var u={},c=[],l=u;return o.split(/(\r\n|\r|\n)/).filter(a).forEach(function(p){var v=p[0],m=p.slice(2);v==="m"&&(c.push({rtp:[],fmtp:[]}),l=c[c.length-1]);for(var b=0;b<(i[v]||[]).length;b+=1){var T=i[v][b];if(T.reg.test(m))return n(T,l,m)}}),u.media=c,u};var s=function(o,u){var c=u.split(/=(.+)/,2);return c.length===2?o[c[0]]=t(c[1]):c.length===1&&u.length>1&&(o[c[0]]=void 0),o};e.parseParams=function(o){return o.split(/;\s?/).reduce(s,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(o){return o.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(o){for(var u=[],c=o.split(" ").map(t),l=0;l<c.length;l+=3)u.push({component:c[l],ip:c[l+1],port:c[l+2]});return u},e.parseImageAttributes=function(o){return o.split(" ").map(function(u){return u.substring(1,u.length-1).split(",").reduce(s,{})})},e.parseSimulcastStreamList=function(o){return o.split(";").map(function(u){return u.split(",").map(function(c){var l,p=!1;return c[0]!=="~"?l=t(c):(l=t(c.substring(1,c.length)),p=!0),{scid:l,paused:p}})})}})(AI);var ph=MI,Hee=/%[sdv%]/g,Vee=function(e){var t=1,r=arguments,n=r.length;return e.replace(Hee,function(i){if(t>=n)return i;var a=r[t];switch(t+=1,i){case"%%":return"%";case"%s":return String(a);case"%d":return Number(a);case"%v":return""}})},Jo=function(e,t,r){var n=t.format instanceof Function?t.format(t.push?r:r[t.name]):t.format,i=[e+"="+n];if(t.names)for(var a=0;a<t.names.length;a+=1){var s=t.names[a];t.name?i.push(r[t.name][s]):i.push(r[t.names[a]])}else i.push(r[t.name]);return Vee.apply(null,i)},Kee=["v","o","s","i","u","e","p","c","b","t","r","z","a"],Jee=["i","c","b","a"],Yee=function(e,t){t=t||{},e.version==null&&(e.version=0),e.name==null&&(e.name=" "),e.media.forEach(function(a){a.payloads==null&&(a.payloads="")});var r=t.outerOrder||Kee,n=t.innerOrder||Jee,i=[];return r.forEach(function(a){ph[a].forEach(function(s){s.name in e&&e[s.name]!=null?i.push(Jo(a,s,e)):s.push in e&&e[s.push]!=null&&e[s.push].forEach(function(o){i.push(Jo(a,s,o))})})}),e.media.forEach(function(a){i.push(Jo("m",ph.m[0],a)),n.forEach(function(s){ph[s].forEach(function(o){o.name in a&&a[o.name]!=null?i.push(Jo(s,o,a)):o.push in a&&a[o.push]!=null&&a[o.push].forEach(function(u){i.push(Jo(s,o,u))})})})}),i.join(`\r
533
533
  `)+`\r
534
- `},Ts=AI,Xee=Yee;aa.write=Xee;aa.parse=Ts.parse;aa.parseParams=Ts.parseParams;aa.parseFmtpConfig=Ts.parseFmtpConfig;aa.parsePayloads=Ts.parsePayloads;aa.parseRemoteCandidates=Ts.parseRemoteCandidates;aa.parseImageAttributes=Ts.parseImageAttributes;aa.parseSimulcastStreamList=Ts.parseSimulcastStreamList;var sa={},Qee=je&&je.__spreadArrays||function(){for(var e=0,t=0,r=arguments.length;t<r;t++)e+=arguments[t].length;for(var n=Array(e),i=0,t=0;t<r;t++)for(var a=arguments[t],s=0,o=a.length;s<o;s++,i++)n[i]=a[s];return n};Object.defineProperty(sa,"__esModule",{value:!0});var xI=function(){function e(t,r,n){this.name=t,this.version=r,this.os=n}return e}();sa.BrowserInfo=xI;var NI=function(){function e(t){this.version=t,this.name="node",this.os=process.platform}return e}();sa.NodeInfo=NI;var LI=function(){function e(){this.bot=!0,this.name="bot",this.version=null,this.os=null}return e}();sa.BotInfo=LI;var Zee=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,ete=/(nuhk)|(Googlebot)|(Yammybot)|(Openbot)|(Slurp)|(MSNBot)|(Ask Jeeves\/Teoma)|(ia_archiver)/,Z0=3,tte=[["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",Zee]],eT=[["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",ete]];function rte(e){return e?zv(e):typeof navigator<"u"?zv(navigator.userAgent):jI()}sa.detect=rte;function zv(e){var t=e!==""&&tte.reduce(function(a,s){var o=s[0],u=s[1];if(a)return a;var c=u.exec(e);return!!c&&[o,c]},!1);if(!t)return null;var r=t[0],n=t[1];if(r==="searchbot")return new LI;var i=n[1]&&n[1].split(/[._]/).slice(0,3);return i?i.length<Z0&&(i=Qee(i,nte(Z0-i.length))):i=[],new xI(r,i.join("."),DI(e))}sa.parseUserAgent=zv;function DI(e){for(var t=0,r=eT.length;t<r;t++){var n=eT[t],i=n[0],a=n[1],s=a.test(e);if(s)return i}return null}sa.detectOS=DI;function jI(){var e=typeof process<"u"&&process.version;return e?new NI(process.version.slice(1)):null}sa.getNodeVersion=jI;function nte(e){for(var t=[],r=0;r<e;r++)t.push("0");return t}var il={exports:{}};function ite(e,t){if(typeof e[Symbol.iterator]=="function")for(const r of e){const n=Array.isArray(r)?r[1]:r;t(n)}else for(const r in e)if(e.hasOwnProperty(r)){const n=e[r];t(n)}}var FI={iterateReports:ite};const ate={"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"}},ste={"remote-candidate":function(e){return al(e)},"inbound-rtp":function(e){return al(e)},"outbound-rtp":function(e){return al(e)},"remote-inbound-rtp":function(e){return al(e)}},al=e=>{const{type:t}=e,r=ate[t],n={};for(let i in r)if(i in e){let a;typeof r[i]=="function"?a=r[i](e):a=r[i],n[a]=e[i]}else n[r[i]]=null;return n};var ote={parsers:ste};const{iterateReports:ute}=FI;function cte(e){let t=0,r=0,n=0,i=100,a=0,s,o,u;return ute(e,c=>{c.type==="inbound-rtp"&&(t=c.jitter,n=c.packetsLost,r=c.packetsReceived)}),r+n>0&&(a=100*(n/(r+n))),s=i+t*2+10,s<160?o=93.2-s/40:o=93.2-(s-120)/10,o=o-a*2.5,o<1&&(o=1),u=1+.035*o+7e-6*o*(o-60)*(100-o),parseFloat(u).toFixed(6)}var UI=cte;const{iterateReports:lte}=FI,{parsers:tT}=ote,fte=UI;function dte(e){const t={};return lte(e,r=>{if(r.type in tT){const n=tT[r.type](r);Object.assign(t,n)}}),t.networkMos=parseFloat(fte(e)),t}var pte=dte,rT;function hte(){return rT||(rT=1,function(e,t){var r=je&&je.__importDefault||function(o){return o&&o.__esModule?o:{default:o}};Object.defineProperty(t,"__esModule",{value:!0});const n=pte,i=UI,a=r(Ii());class s{constructor(u){this.mos_report={min:5,max:0},this._reportsCount=0,this._mosSum=0,this.intervals=[],this._deprecationWarningSent=!1,!(!u||!u.application||!u.rtc_id||!u.pc)&&(this.conversation=null,this.application_id=null,this.attachHandlers(u),this.startSendingStats(u),this.startEmittingStats(u))}attachHandlers(u){const{pc:c}=u;c.addEventListener("connectionstatechange",()=>{switch(c.connectionState){case"disconnected":case"failed":case"closed":this.removeIntervals(),this.emitLastReport(u)}}),u.conversation?u.conversation.on("member:media",(p,v)=>{!this.application_id&&(u==null?void 0:u.rtc_id)===v.body.channel.id&&(this.application_id=v.application_id)}):u.application.on("member:joined",(p,v)=>{(!this.conversation||!this.application_id)&&(u==null?void 0:u.rtc_id)===v.body.channel.id&&(this.conversation=p.conversation,this.application_id=v.application_id)})}emitLastReport(u){const{application:c,conversation:l=null,rtc_id:p,config:{emit_events:v,emit_rtc_analytics:m}}=u,b=this.getMOSReport(),T=b.last;T&&(m&&c.emit("rtcstats:analytics",{type:"mos_report",mos:T,rtc_id:p,mos_report:b,api_key:c.session.apiKey,...this.application_id&&{application_id:this.application_id},...l&&{conversation_id:l.id,conversation_name:l.name}}),v&&(this._deprecationWarningSent||(this._deprecationWarningSent=!0,console.warn('"rtcstats:report" event is deprecated. Use "rtcstats:analytics" instead')),c.emit("rtcstats:report",T,null,l,b)))}startSendingStats(u){const{application:c,conversation:l=null,pc:p,rtc_id:v,config:{remote_collection:m,remote_collection_url:b,remote_collection_interval:T}}=u;if(!m)return;const I=setInterval(()=>{p.getStats(null).then(R=>{var x;const N=(x=l??this.conversation)!==null&&x!==void 0?x:null;a.default.networkRequest({url:b,type:"POST",data:{...n(R),legId:v,apiKey:c.session.apiKey,...this.application_id&&{applicationId:this.application_id},...N&&{conversationId:N.id,conversationName:N.name}}}).catch(()=>{})}).catch(()=>{}),(p.connectionState==="closed"||p.signalingState==="closed")&&this.removeIntervals()},T);this.intervals.push(I)}startEmittingStats(u){const{application:c,conversation:l=null,pc:p,rtc_id:v,config:{emit_events:m,emit_rtc_analytics:b,emit_interval:T}}=u;if(!m&&!b)return;const I=setInterval(()=>{var R;p.getStats(null).then(x=>{var N;const j=this.getMos(x);if(!j)return;const X=(N=l??this.conversation)!==null&&N!==void 0?N:null;b&&c.emit("rtcstats:analytics",{type:"mos",mos:j,report:x,rtc_id:v,api_key:c.session.apiKey,...this.application_id&&{application_id:this.application_id},...X&&{conversation_id:X.id,conversation_name:X.name}}),m&&(this._deprecationWarningSent||(this._deprecationWarningSent=!0,console.warn('"rtcstats:report" event is deprecated. Use "rtcstats:analytics" instead')),c.emit("rtcstats:report",j,x,l))}).catch(()=>{}),(p.connectionState==="closed"||p.signalingState==="closed")&&(this.removeIntervals(),this.emitLastReport({...u,conversation:(R=l??this.conversation)!==null&&R!==void 0?R:null}))},T);this.intervals.push(I)}removeIntervals(){this.intervals.forEach(u=>clearInterval(u)),this.intervals=[]}getMos(u){const c=i(u);return this.updateMOSReport(parseInt(c)),c}updateMOSReport(u){this._reportsCount++,this._mosSum+=u,this.mos_report.last=u,this.mos_report.min=u<this.mos_report.min?u:this.mos_report.min,this.mos_report.max=u>this.mos_report.max?u:this.mos_report.max,this.mos_report.average=this._mosSum/this._reportsCount}getMOSReport(){return this.mos_report.min=s.normaliseFloat(this.mos_report.min),this.mos_report.max=s.normaliseFloat(this.mos_report.max),this.mos_report.last=s.normaliseFloat(this.mos_report.last),this.mos_report.average=s.normaliseFloat(this.mos_report.average),this.mos_report}static normaliseFloat(u){return parseFloat(u).toFixed(6)}}t.default=s,e.exports=s}(il,il.exports)),il.exports}var nT;function ed(){return nT||(nT=1,function(e,t){var r=je&&je.__createBinding||(Object.create?function(m,b,T,I){I===void 0&&(I=T),Object.defineProperty(m,I,{enumerable:!0,get:function(){return b[T]}})}:function(m,b,T,I){I===void 0&&(I=T),m[I]=b[T]}),n=je&&je.__setModuleDefault||(Object.create?function(m,b){Object.defineProperty(m,"default",{enumerable:!0,value:b})}:function(m,b){m.default=b}),i=je&&je.__importStar||function(m){if(m&&m.__esModule)return m;var b={};if(m!=null)for(var T in m)T!=="default"&&Object.hasOwnProperty.call(m,T)&&r(b,m,T);return n(b,m),b},a=je&&je.__importDefault||function(m){return m&&m.__esModule?m:{default:m}};Object.defineProperty(t,"__esModule",{value:!0});const s=aa,o=Ar,u=i(sa),c=Gn,l=a(hte()),p=2e4;class v{constructor(){this.log=o.getLogger(this.constructor.name)}static getUserAudio(b=!0){let T={video:!1,audio:b};return navigator.mediaDevices.getUserMedia(T)}createRTCPeerConnection(b){const T=new RTCPeerConnection(b);return T.trace=()=>{},T}_getWindowLocationProtocol(){return window.location.protocol}static _getBrowserName(){return u.detect().name}static isNode(){return this._getBrowserName()==="node"}checkValidKeys(b,T){let I=!0;return Object.keys(b).forEach(R=>{T.hasOwnProperty(R)||(I=!1)}),I}static cleanCallMediaIfFailed(b){setTimeout(()=>{b.conversation||(this.cleanMediaProperties(b),b.status=b.CALL_STATUS.FAILED,b.application.emit("call:status:changed",b))},5e3)}static callDisconnectHandler(b,T){const I=[b.CALL_STATUS.ANSWERED,b.CALL_STATUS.STARTED,b.CALL_STATUS.RINGING];if(!(T.connectionState!=="disconnected"||!b||!b.conversation))return setTimeout(()=>{T.connectionState==="connected"||I.indexOf(b.status)==-1||(this.cleanMediaProperties(b),b.status=b.CALL_STATUS.COMPLETED,b.application.emit("call:status:changed",b))},p)}static cleanMediaProperties(b){if(b.rtcObjects)for(const T in b.rtcObjects)b.rtcObjects[T].pc.close(),delete b.rtcObjects[T].pc,v.closeStream(b.rtcObjects[T].stream);b.application.activeStreams=[],b.rtcObjects={},b.conversation&&b.conversation.media&&(b.conversation.media.rtcStats=null)}static cleanConversationMediaProperties(b,T){T&&v.closeStream(T),b&&b.close()}static playAudioStream(b){const T=new Audio;return T.srcObject=b,T.autoplay=!0,T}static createDummyCandidateSDP(b){const T={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=s.parse(b.localDescription.sdp);return I.media[0].candidates=[T],s.write(I)}static createRTCPeerConnectionConfig(b){return{iceTransportPolicy:"all",bundlePolicy:"balanced",rtcpMuxPolicy:"require",iceCandidatePoolSize:"0",...b.session.config&&b.session.config.iceServers&&{iceServers:b.session.config.iceServers}}}static setupPeerConnectionApplicationListeners(b,T){T.addEventListener("icecandidateerror",I=>b.emit("rtc:icecandidateerror",I)),T.addEventListener("icegatheringstatechange",()=>b.emit("rtc:icegatheringstatechange",T.iceGatheringState)),T.addEventListener("signalingstatechange",()=>b.emit("rtc:signalingstatechange",T.signalingState)),T.addEventListener("iceconnectionstatechange",()=>b.emit("rtc:iceconnectionstatechange",T.iceConnectionState)),T.addEventListener("connectionstatechange",()=>b.emit("rtc:peerconnectionstatechange",T.connectionState))}static createPeerConnection(b){const T=this.createRTCPeerConnectionConfig(b),I=new RTCPeerConnection(T);return this.setupPeerConnectionApplicationListeners(b,I),I}static sendOffer(b,T,I,R){const N={sdp:this.createDummyCandidateSDP(T)};let j={from:I.me.id,body:{offer:N}},X=`conversations/${I.id}/rtc`;return R&&(X+=`/${R}/offer`),b.session.sendNetworkRequest({type:"POST",path:X,data:j})}static sendAnswer(b,T,I,R){const x=this.createDummyCandidateSDP(T);let N={from:I.me.id,body:{answer:x}},j=`conversations/${I.id}/rtc/${R}/answer`;return b.session.sendNetworkRequest({type:"POST",path:j,data:N})}static createLeg(b,T){const R={sdp:this.createDummyCandidateSDP(T),type:"offer"};return b.session.sendNetworkRequest({type:"POST",path:"legs",version:"beta",data:{body:{offer:R}}})}static closeStream(b){b.getTracks().forEach(T=>{T.stop()})}static emitMediaStream(b,T,I){b.emit("media:stream:on",{pc:T,stream:I,type:"audio",streamIndex:0})}static _initStatsEvents(b){var T,I,R;if(!v.isNode()&&!((R=(I=(T=b==null?void 0:b.application)===null||T===void 0?void 0:T.session)===null||I===void 0?void 0:I.config)===null||R===void 0)&&R.rtcstats){const x=b.application.session.config.rtcstats,{emit_events:N,remote_collection:j,emit_rtc_analytics:X}=x;if(N||j||X){const J={...b,config:{...x}};return new l.default(J)}}}static attachConversationEventHandlers(b){const{conversation:T,pc:I,log:R}=b;T.once("rtc:answer",x=>{if(!I){R.warn("RTC: received an answer too late");return}I.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:x.body.answer}))})}static doAnswer(b,T,I){const{application:R,conversation:x,pc:N,reject:j,localStream:X}=b;this.addPeerConnectionListeners(b,()=>v.sendAnswer(R,N,x,I).then(()=>({rtc_id:I}))),N.setRemoteDescription(new RTCSessionDescription({type:"offer",sdp:T})).then(()=>N.createAnswer()).then(J=>N.setLocalDescription(J)).catch(J=>{v.cleanConversationMediaProperties(N,X),j(J)})}static attachPeerConnectionEventHandlers(b){const{application:T,conversation:I,pc:R,reconnectRtcId:x}=b;this.addPeerConnectionListeners(b,()=>v.sendOffer(T,R,I,x))}static addPeerConnectionListeners(b,T){const{application:I,conversation:R,pc:x,streamIndex:N,localStream:j,log:X,rtcObjects:J,resolve:V,reject:D}=b;let te,ue=!1,ee;R.id&&(ee=I.calls.get(R.id)),x.ontrack=ge=>{te=ge.streams[0],I.activeStreams.push(te),v.emitMediaStream(R.me,x,te)},x.addEventListener("connectionstatechange",ge=>this.onconnectionstatechangeHandler(x,X,ee,()=>V(te),()=>{v.cleanConversationMediaProperties(x,j),D()})),x.addEventListener("negotiationneeded",()=>this.onnegotiationneededHandler(x,ge=>{v.cleanConversationMediaProperties(x,j),D(ge)})),x.addEventListener("iceconnectionstatechange",ge=>this.oniceconnectionstatechange(ge,x,X,L=>{v.cleanConversationMediaProperties(x,j),D(L)})),x.addEventListener("icecandidate",async ge=>{if(ge.candidate&&!ue&&x){ue=!0;try{const{rtc_id:L}=await T();v._initStatsEvents({application:I,rtc_id:L,pc:x,conversation:R}),x.trace&&x.trace("rtc_id",L),J[L]={rtc_id:L,pc:x,stream:j,type:"audio",streamIndex:N}}catch(L){v.cleanConversationMediaProperties(x,j),D(new c.NexmoClientError(L))}}}),j.getTracks().forEach(ge=>x.addTrack(ge))}static prewarmLeg(b){const T=b.application;return new Promise(async(I,R)=>{let x=!1,N,j,X={},J,V;const D=o.getLogger(this.constructor.name);try{V=await this.getUserAudio(),J=this.createPeerConnection(T),J.ontrack=te=>{N=te.streams[0],T.activeStreams.push(N)},J.addEventListener("connectionstatechange",te=>this.onconnectionstatechangeHandler(J,D,b,()=>I({stream:N,legId:j,rtcObjects:X}),()=>{v.cleanConversationMediaProperties(J,V),R()})),J.addEventListener("negotiationneeded",()=>this.onnegotiationneededHandler(J,te=>{v.cleanConversationMediaProperties(J,V),R(te)})),J.addEventListener("iceconnectionstatechange",te=>this.oniceconnectionstatechange(te,J,D,ue=>{v.cleanConversationMediaProperties(J,V),R(ue)})),J.addEventListener("icecandidate",async te=>{if(te.candidate&&!x&&J){x=!0;const{rtc_id:ue,sdp:ee}=await this.createLeg(T,J);return v._initStatsEvents({application:T,rtc_id:ue,pc:J}),j=ue,X[j]={rtc_id:ue,pc:J,stream:V,type:"audio",streamIndex:1},J.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:ee}))}}),V.getTracks().forEach(te=>J.addTrack(te))}catch(te){v.cleanConversationMediaProperties(J,V),R(new c.NexmoClientError(te))}})}}t.default=v,v.onconnectionstatechangeHandler=(m,b,T,I,R)=>{switch(m.connectionState){case"connected":b.info("The connection has become fully connected"),I();break;case"disconnected":if(!T)break;T.call_disconnect_timeout&&clearTimeout(T.call_disconnect_timeout),T.call_disconnect_timeout=v.callDisconnectHandler(T,m);break;case"failed":R(),b.info("One or more transports has terminated unexpectedly or in an error");break;case"closed":b.info("The connection has been closed");break}},v.oniceconnectionstatechange=(m,b,T,I)=>{switch(b.iceConnectionState){case"disconnected":T.warn("One or more transports is disconnected",b.iceConnectionState);break;case"failed":I(new c.NexmoClientError(m)),T.warn("One or more transports has terminated unexpectedly or in an error",m);break;default:T.info("The ice connection status changed",b.iceConnectionState)}},v.onnegotiationneededHandler=async(m,b)=>{try{const T=await m.createOffer();return m.setLocalDescription(T)}catch(T){b(new c.NexmoClientError(T))}},e.exports=v}(nl,nl.exports)),nl.exports}var iT;function vte(){return iT||(iT=1,function(e,t){var r=je&&je.__importDefault||function(p){return p&&p.__esModule?p:{default:p}};Object.defineProperty(t,"__esModule",{value:!0});const n=Ar,i=Gn,a=r(ed()),s=r(Ii()),o=r(ia),u=r(zI()),c=r(rd());class l{constructor(v){var m,b,T;const I=v instanceof u.default?v:null,R=v instanceof c.default?v:null;this.log=n.getLogger(this.constructor.name),I?(this.rtcHelper=new a.default,this.application=I.application,this.application.activeStreams=this.application.activeStreams||[],this.parentConversation=I,this.rtcObjects={},this.streamIndex=0,this.rtcstats_conf=((T=(b=(m=this.application)===null||m===void 0?void 0:m.session)===null||b===void 0?void 0:b.config)===null||T===void 0?void 0:T.rtcStats)||{},this.rtcStats=null):R?(this.rtcHelper=new a.default,this.application=R):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 m;if(this.parentConversation.members.has(v.from))m=this.parentConversation.members.get(v.from);else try{m=await this.parentConversation.getMember(v.from)}catch(b){this.log.warn(`There is an error getting the member ${b}`)}m.user.id===this.application.me.id&&this.application.activeStreams.length&&this._cleanMediaProperties(),m.user.id===this.application.me.id&&m.transferred_from&&m.transferred_from.media._cleanMediaProperties(),m.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=a.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={},m){return new Promise(async(b,T)=>{const I=this.streamIndex;this.streamIndex++;const{audioConstraints:R}=v;try{const x=await a.default.getUserAudio(R),N=a.default.createPeerConnection(this.application);this.pc=N;const{application:j,log:X,parentConversation:J,rtcObjects:V}=this,D={pc:N,streamIndex:I,localStream:x,application:j,conversation:J,log:X,rtcObjects:V};m({...D,resolve:b,reject:T}),a.default.attachConversationEventHandlers(D),this._attachEndingEventHandlers()}catch(x){T(new i.NexmoClientError(x))}})}_execAnswer(v={}){const{offer:{sdp:m,leg_id:b}}=v;return this._audioInitHandler(v,T=>a.default.doAnswer(T,m,b))}_handleAudio(v={}){const{reconnectRtcId:m}=v;return this._audioInitHandler(v,b=>a.default.attachPeerConnectionEventHandlers({...b,reconnectRtcId:m}))}_findRtcObjectByType(v){return Object.values(this.rtcObjects).find(m=>m.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)a.default.closeStream(this.rtcObjects[v].stream);delete this.pc,this.rtcStats=null,this.application.activeStreams=[],this.rtcObjects={},this.listeningToRtcEvent=!1}async _disableLeg(v){const m=new Promise(async(T,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"}),T("rtc:terminate:success")}catch(R){I(new i.NexmoApiError(R))}}),b=new Promise(T=>{this.rtcObjects[v].pc&&this.rtcObjects[v].pc.close(),this.rtcObjects[v].stream&&a.default.closeStream(this.rtcObjects[v].stream),T()});try{return await Promise.all([m,b]),this.parentConversation.me.emit("media:stream:off",this.rtcObjects[v].streamIndex),delete this.rtcObjects[v],"rtc:terminate:success"}catch(T){throw T}}_enableMediaTracks(v,m){v.forEach(b=>{b.enabled=m})}async _setMediaTracksAndMute(v,m,b,T){this._enableMediaTracks(m,!b);try{return await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.parentConversation.id}/events`,data:{type:T,to:this.parentConversation.me.id,from:this.parentConversation.me.id,body:{rtc_id:v}}})}catch(I){throw this._enableMediaTracks(m,b),new i.NexmoApiError(I)}}async updateAudioConstraints(v={}){let m=this._findRtcObjectByType("audio");if(m&&m.pc)try{const b=await a.default.getUserAudio(v);return b.getTracks().forEach(T=>{const I=m.pc.getSenders().find(R=>R.track.kind===T.kind);I&&(T.enabled=I.track.enabled,I.replaceTrack(T))}),a.default.closeStream(m.stream),m.stream=b,b}catch(b){return b}else throw new i.NexmoApiError("error:media:stream:not-found")}mute(v=!1,m=null){const T="audio:mute:"+(v?"on":"off");let I=[],R={};if(m!==null){if(R[0]=Object.values(this.rtcObjects).find(x=>x.streamIndex===m),!R[0])throw new i.NexmoClientError("error:media:stream:not-found")}else R=this.rtcObjects;return Object.values(R).forEach(x=>{const N=x.stream.getAudioTracks(),j=this._setMediaTracksAndMute(x.rtc_id,N,v,T);I.push(j)}),Promise.all(I)}async earmuff(v){try{if(this.me===null)throw new i.NexmoClientError("error:self");{let m="audio:earmuff:off";v&&(m="audio:earmuff:on");const{response:b}=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.parentConversation.id}/events`,data:{type:m,to:this.parentConversation.me.id}});return b}}catch(m){throw new i.NexmoApiError(m)}}async enable(v){try{if(this.parentConversation.me===null)throw new i.NexmoClientError("error:self");{const{offer:m}=v??{};let b=await(m!==void 0?this._execAnswer(v):this._handleAudio(v)),T=v&&(v.autoPlayAudio||v.autoPlayAudio===void 0);return(!v||T)&&a.default.playAudioStream(b),b}}catch(m){throw m}}disable(){let v=[];v.push(this._cleanConversationProperties());for(const m in this.rtcObjects)v.push(this._disableLeg(m));return Promise.all(v)}async sayText(v){try{const m=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 o.default(this.parentConversation,m)}catch(m){throw new i.NexmoApiError(m)}}async sendDTMF(v){try{if(!s.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:b,timestamp:T}=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:b,timestamp:T,type:"audio:dtmf"},R=new o.default(this.parentConversation,I);return this.parentConversation.events.set(I.id,R),R}catch(m){throw new i.NexmoApiError(m)}}async playStream(v){try{const m=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.parentConversation.id}/events`,data:{type:"audio:play",body:v}});return new o.default(this.parentConversation,m)}catch(m){throw new i.NexmoApiError(m)}}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 o.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 o.default(this.parentConversation,v)}catch(v){throw new i.NexmoApiError(v)}}}t.default=l,e.exports=l}(rl,rl.exports)),rl.exports}var sl={exports:{}},ol={exports:{}},aT;function BI(){return aT||(aT=1,function(e,t){var r=je&&je.__importDefault||function(o){return o&&o.__esModule?o:{default:o}};Object.defineProperty(t,"__esModule",{value:!0});const n=r(Ii()),i=Ar,a=r(ia);class s extends a.default{constructor(u,c){super(u,c),this.log=i.getLogger(this.constructor.name),this.type="image",this.conversation=u,this.state={seen_by:{},delivered_to:{}},c&&c.body&&c.body.timestamp&&(this.timestamp=c.body.timestamp),Object.assign(this,c)}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(u="thumbnail",c=this.body.representations){try{return n.default._fetchImage(c[u].url,this.conversation.application.session.config.token)}catch(l){throw this.log.error(l),l}}}t.default=s,e.exports=s}(ol,ol.exports)),ol.exports}var sT;function mte(){return sT||(sT=1,function(e,t){var r=je&&je.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(t,"__esModule",{value:!0});const n=Ar,i=r(ia),a=r(Xg),s=r(BI()),o=r(Qg());class u{constructor(l,p){this.log=n.getLogger(this.constructor.name),this.application=l,this.conversation=p,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(l){return this._handleEventMap.hasOwnProperty(l.type)?this._handleEventMap[l.type].call(this,l)||new i.default(this.conversation,l):new i.default(this.conversation,l)}_processDelivered(l){let p=this.conversation.events.get(l.body.event_id);return p?(p.state=p.state||{},p.state.delivered_to=p.state.delivered_to||{},p.state.delivered_to[l.from]=l.timestamp,p):(this.log.warn("NXMEvent not found"),null)}_processDelete(l){var p;let v=this.conversation.events.get((p=l==null?void 0:l.body)===null||p===void 0?void 0:p.event_id);return v?(v.body.text&&(v.body.text=""),v.body.representations&&(v.body.representations=""),v.body.timestamp={deleted:l.timestamp},v):(this.log.warn("NXMEvent not found"),null)}_processImage(l){var p;const v=new s.default(this.conversation,l);return((p=this.conversation.me)===null||p===void 0?void 0:p.id)!==v.from&&v.delivered(),v}_processMember(l){return this.application.calls.has(this.conversation.id)&&this.application.calls.get(this.conversation.id)._handleStatusChange(l),this.conversation.members.has(l.from)&&this.conversation.members.get(l.from)._handleEvent(l),new i.default(this.conversation,l)}_processLegStatus(l){return this.conversation.members.has(l.from)&&this.conversation.members.get(l.from)._handleEvent(l),new i.default(this.conversation,l)}_processMedia(l){return this.conversation.members.has(l.from)&&this.conversation.members.get(l.from)._handleEvent(l),null}_processMuteForMedia(l){return this.conversation.media.rtcObjects[l.body.rtc_id]?l.streamIndex=this.conversation.media.rtcObjects[l.body.rtc_id].streamIndex:this.log.warn("No audio stream was found"),null}_processSeen(l){let p=this.conversation.events.get(l.body.event_id);return p?(p.state=p.state||{},p.state.seen_by=p.state.seen_by||{},p.state.seen_by[l.from]=l.timestamp,p):(this.log.warn("NXMEvent not found"),null)}_processText(l){var p,v;const m=new a.default(this.conversation,l);return((v=(p=this.conversation)===null||p===void 0?void 0:p.me)===null||v===void 0?void 0:v.id)!==m.from&&m.delivered(),m}_processMessage(l){var p,v;const m=new o.default(this.conversation,l);return((v=(p=this.conversation)===null||p===void 0?void 0:p.me)===null||v===void 0?void 0:v.id)!==m.from&&m.delivered(),m}_processSubmitted(l){let p=this.conversation.events.get(l.body.event_id);return p?(p.state=p.state||{},p.state.submitted_to=p.state.submitted_to||{},p.state.submitted_to[l.from]=l.timestamp,p):(this.log.warn("NXMEvent not found"),null)}_processRejected(l){let p=this.conversation.events.get(l.body.event_id);return p?(p.state=p.state||{},p.state.rejected_by=p.state.rejected_by||{},p.state.rejected_by[l.from]=l.timestamp,p):(this.log.warn("NXMEvent not found"),null)}_processUndeliverable(l){let p=this.conversation.events.get(l.body.event_id);return p?(p.state=p.state||{},p.state.undeliverable_to=p.state.undeliverable_to||{},p.state.undeliverable_to[l.from]=l.timestamp,p):(this.log.warn("NXMEvent not found"),null)}}t.default=u,e.exports=u}(sl,sl.exports)),sl.exports}var Wv={exports:{}};(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});class r{constructor(i={}){this.page_size=i.page_size||10,this.order=i.order||"asc",this.cursor=i.cursor||"",this.state=i.state||"",i.event_type&&(this.event_type=i.event_type)}}t.default=r,e.exports=r})(Wv,Wv.exports);var qI=Wv.exports,ul={exports:{}},Gv={exports:{}};(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r=Gn;class n{constructor(a={}){this.page_size=a.page_size,this.order=a.order,this.cursor=a.cursor,this.application=a.application,a.event_type&&a.event_type.length>0&&(this.event_type=a.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(a){return{page_size:this.page_size,order:this.order,cursor:a,...this.event_type&&{event_type:this.event_type}}}_getError(){return Promise.reject(new r.NexmoClientError("error:invalid-cursor"))}}t.default=n,e.exports=n})(Gv,Gv.exports);var td=Gv.exports,oT;function gte(){return oT||(oT=1,function(e,t){var r=je&&je.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(t,"__esModule",{value:!0});const n=r(td),i=r(ia),a=r(Xg),s=r(BI()),o=r(Qg());class u extends n.default{constructor(l){super(l),this.items=new Map,this.conversation=l.conversation,l.items.forEach(p=>{switch(p.type){case"text":this.items.set(p.id,new a.default(this.conversation,p));break;case"image":this.items.set(p.id,new s.default(this.conversation,p));break;case"message":this.items.set(p.id,new o.default(this.conversation,p));break;default:this.items.set(p.id,new i.default(this.conversation,p));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()}}t.default=u,e.exports=u}(ul,ul.exports)),ul.exports}var cl={exports:{}},uT;function yte(){return uT||(uT=1,function(e,t){var r=je&&je.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(t,"__esModule",{value:!0});const n=r(td),i=r(Yg());class a extends n.default{constructor(o){super(o),this.conversation=o.conversation,this.items=new Map,o.items.forEach(u=>{this.items.set(u.id,new i.default(this.conversation,u))})}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()}}t.default=a,e.exports=a}(cl,cl.exports)),cl.exports}var cT;function zI(){return cT||(cT=1,function(e,t){var r=je&&je.__importDefault||function(x){return x&&x.__esModule?x:{default:x}};Object.defineProperty(t,"__esModule",{value:!0});const n=Da,i=Ar,a=Gn,s=r(Yg()),o=r(ia),u=r(Xg),c=r(Qg()),l=r(vte()),p=r(mte()),v=r(Ii()),m=r(qI),b=r(gte()),T=r(yte()),I=r(rd());class R{constructor(N,j){this.log=i.getLogger(this.constructor.name),this.application=N,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 m.default(((this.application.session||{}).config||{}).events_page_config),this.events_page_last=null,this.members_page_last=null,this.conversationEventHandler=new p.default(N,this),this.media=new l.default(this),this.me=null,this._updateObjectInstance(j),n.mixin(R)}_updateObjectInstance(N){for(let j in N)switch(j){case"id":this.id=N.id;break;case"name":this.name=N.name;break;case"display_name":this.display_name=N.display_name;break;case"members":N.members.forEach(J=>{if(this.members.has(J.member_id))this.members.get(J.member_id)._normalise(J),J.user_id===this.application.me.id&&J.state!=="LEFT"&&(this.me=this.members.get(J.member_id),this.members.set(this.me.id,this.me));else{const V=new s.default(this,J);J.user_id===this.application.me.id&&J.state!=="LEFT"&&(this.me=V),this.members.set(V.id,V)}});break;case"timestamp":this.timestamp=N.timestamp;break;case"sequence_number":this.sequence_number=N.sequence_number;break;case"member_id":const X={id:N.member_id,state:N.state,user:this.application.me};if(this.members.has(N.member_id)){const J=this.members.get(N.member_id);Object.assign(J,X)}else{const J=new s.default(this,X);this.me=J,this.members.set(J.id,J)}break}}async join(N){var j,X;try{let J={state:"joined",channel:{type:"app"},user:{...!N&&{name:this.application.me.name,id:this.application.me.id},...N&&N.user_name&&{name:N.user_name},...N&&N.user_id&&{id:N.user_id}}};!((j=this===null||this===void 0?void 0:this.me)===null||j===void 0)&&j.id&&((X=this===null||this===void 0?void 0:this.me)===null||X===void 0?void 0:X.state)!=="LEFT"&&(J.from=this.me.id);const V=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.id}/members`,version:"v0.3",data:J}),D=new s.default(this,V);return V._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(J){throw new a.NexmoApiError(J)}}async del(){try{const N=await this.application.session.sendNetworkRequest({type:"DELETE",path:`conversations/${this.id}`});return this.application.conversations.delete(this.id),N}catch(N){throw new a.NexmoApiError(N)}}deleteEvent(N){return N.del()}async invite(N){var j,X;if(!N||!N.id&&!N.user_name)throw new a.NexmoClientError("error:invite:missing:params");const J={state:"invited",user:{...N.id&&{id:N.id},...N.user_name&&{name:N.user_name}},media:N.media,channel:{from:{type:"app"},to:{type:"app"},type:"app"}};!((j=this===null||this===void 0?void 0:this.me)===null||j===void 0)&&j.id&&((X=this===null||this===void 0?void 0:this.me)===null||X===void 0?void 0:X.state)!=="LEFT"&&(J.from=this.me.id);try{const V=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.id}/members`,version:"v0.3",data:J});return new s.default(this,V)}catch(V){throw new a.NexmoApiError(V)}}inviteWithAudio(N){return!N||!N.id&&!N.user_name?Promise.reject(new a.NexmoClientError("error:invite:missing:params")):(N.media={audio_settings:{enabled:!0,muted:!1,earmuffed:!1}},this.invite(N))}leave(N){return this.me.kick(N)}async sendText(N){try{if(this.me===null)throw new a.NexmoClientError("error:self");const j={type:"text",cid:this.id,from:this.me.id,body:{text:N}},{id:X,timestamp:J}=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.id}/events`,data:j});return j.id=X,j.body.timestamp=J,new u.default(this,j)}catch(j){throw new a.NexmoApiError(j)}}async sendCustomEvent({type:N,body:j}){try{if(this.me===null)throw new a.NexmoClientError("error:self");if(!N||typeof N!="string"||N.length<1)throw new a.NexmoClientError("error:custom-event:invalid");const X={type:`custom:${N}`,cid:this.id,from:this.me.id,body:j},{id:J,timestamp:V}=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.id}/events`,data:X});return X.id=J,X.timestamp=V,new o.default(this,X)}catch(X){throw new a.NexmoApiError(X)}}async sendEphemeralEvent(N){try{if(this.me===null)throw new a.NexmoClientError("error:self");const j={type:"ephemeral",cid:this.id,from:this.me.id,body:N},{id:X,timestamp:J}=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.id}/events`,data:j});return j.timestamp=J,new o.default(this,j)}catch(j){throw new a.NexmoApiError(j)}}async uploadImage(N,j={quality_ratio:"100",medium_size_ratio:"50",thumbnail_size_ratio:"30"}){const X=new FormData;X.append("file",N),X.append("quality_ratio",j.quality_ratio),X.append("medium_size_ratio",j.medium_size_ratio),X.append("thumbnail_size_ratio",j.thumbnail_size_ratio);const J=await v.default.networkRequest({type:"POST",url:this.application.session.config.ips_url,data:X,token:this.application.session.config.token});return J.upload.addEventListener("progress",V=>{V.lengthComputable&&this.log.debug("uploading image "+V.loaded+"/"+V.total)},!1),J.onreadystatechange=()=>{J.status!==200&&this.log.error(J)},J}async sendImage(N,j={quality_ratio:"100",medium_size_ratio:"50",thumbnail_size_ratio:"30"}){const X=await this.uploadImage(N,j);return X.onreadystatechange=()=>{if(X.readyState===4&&X.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(X.responseText)}}}),this.log.info(X)}catch(J){this.log.error(new a.NexmoApiError(J))}},X}abortSendImage(N){return N instanceof XMLHttpRequest?N.abort():new a.NexmoClientError("error:invalid:param:type")}async sendMessage(N){if(this.me===null)throw new a.NexmoClientError("error:self");if(!(N!=null&&N.message_type))throw new a.NexmoClientError("error:message-event:invalid");try{const j={type:"message",cid:this.id,from:this.me.id,body:{...N}},{id:X,timestamp:J}=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.id}/events`,data:j});return j.id=X,j.body.timestamp=J,new c.default(this,j)}catch(j){throw new a.NexmoApiError(j)}}async _typing(N){const j={cid:this.id,from:this.me.id};try{return await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.id}/events`,data:j}),`text:typing:${N}:success`}catch(X){throw new a.NexmoApiError(X)}}startTyping(){return this._typing("on")}stopTyping(){return this._typing("off")}async getEvents(N={}){const j=`${this.application.session.config.nexmo_api_url}/beta2/conversations/${this.id}/events`;let X=Object.keys(N).length===0?this.pageConfig:new m.default(N);try{const J=await v.default.paginationRequest(j,X,this.application.session.config.token);J.application=this.application,J.conversation=this;const V=new b.default(J);return this.events_page_last=V,V}catch(J){throw new a.NexmoApiError(J)}}async getMembers(N={}){const j=`${this.application.session.config.nexmo_api_url}/beta2/conversations/${this.id}/members`;let X=Object.keys(N).length===0?this.pageConfig:new m.default(N);try{const J=await v.default.paginationRequest(j,X,this.application.session.config.token);J.application=this.application,J.conversation=this;const V=new T.default(J);return this.members_page_last=V,V}catch(J){throw new a.NexmoApiError(J)}}async getMyMember(){try{const N=await this.application.session.sendNetworkRequest({type:"GET",path:`conversations/${this.id}/members/me`,version:"v0.3"});return new s.default(this,N)}catch(N){throw new a.NexmoApiError(N)}}async getMember(N){try{const j=await this.application.session.sendNetworkRequest({type:"GET",path:`conversations/${this.id}/members/${N}`,version:"v0.3"});return new s.default(this,j)}catch(j){throw new a.NexmoApiError(j)}}_handleEvent(N){var j,X;if(N.type.startsWith("rtc"))return this.emit(N.type,N),Promise.resolve(N);this.sequence_number++,N.body&&N.body.event_id&&typeof N.body.event_id=="string"&&(N.body.event_id=parseInt(N.body.event_id));let J={memberId:N.from};if(!((j=N==null?void 0:N.body)===null||j===void 0)&&j.user){const{id:D,name:te,display_name:ue,image_url:ee,custom_data:ge}=N.body.user;J={...J,...D&&{userId:D},...te&&{userName:te},...ue&&{displayName:ue},...ee&&{imageUrl:ee},...ge&&{customData:ge}}}else if(!((X=N==null?void 0:N._embedded)===null||X===void 0)&&X.from_user){const{id:D,name:te,display_name:ue,image_url:ee,custom_data:ge}=N._embedded.from_user;J={...J,...D&&{userId:D},...te&&{userName:te},...ue&&{displayName:ue},...ee&&{imageUrl:ee},...ge&&{customData:ge}}}let V=this.conversationEventHandler.handleEvent(N);return["text:typing:on","text:typing:off","ephemeral"].includes(N.type)||this.events.set(V.id,V),N.type.startsWith("custom:")?(this.emit(V.type,J,V),Promise.resolve(N)):(this.emit(N.type,J,V),Promise.resolve(N))}}t.default=R,e.exports=R}(Zc,Zc.exports)),Zc.exports}var ll={exports:{}},lT;function WI(){return lT||(lT=1,function(e,t){var r=je&&je.__importDefault||function(u){return u&&u.__esModule?u:{default:u}};Object.defineProperty(t,"__esModule",{value:!0});const n=Da,i=Ar,a=Gn,s=r(ed());class o{constructor(c,l,p){this.application=c,this.log=i.getLogger(this.constructor.name),this.from=p,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(l),n.mixin(o)}_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",(c,l)=>{this.application.calls&&this.application.calls.has(this.conversation.id)&&this.application.calls.get(this.conversation.id)._handleStatusChange(l)})}catch(c){this.log.error("_attachCallListeners_error: ",{e:c})}}_isValidStatusTransition(c){if(!c)throw new a.NexmoClientError(`Provide the status to validate the transition from '${this.status}'`);if(!this.status)return!0;const l=this.status.toUpperCase();return!this.STATUS_PERMITTED_FLOW.has(l)||this.status===c?!1:this.STATUS_PERMITTED_FLOW.get(l).has(c)}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 c of this.conversation.members.values())if(c.state!=="LEFT"&&this.conversation.me.user.id!==c.user.id)return Promise.resolve();return this.hangUp()}_setupConversationObject(c,l){c&&(this.conversation=c,c.me?(this.to=new Map(c.members),this.from&&this.to.delete(this.from.id)):this.log.warn("missing own member object"),this._attachCallListeners())}_setFrom(c){this.from=c}_setOffer(c){this.offer=c}_handleStatusChange(c){var l;const p=this.conversation?((l=this.conversation.me)===null||l===void 0?void 0:l.id)===c.from:!0,v=this.direction===this.CALL_DIRECTION.OUTBOUND;this.log.debug("_handleStatusChange: ",{event:c},`_isEventFromMe: ${p} _isOutbound: ${v}`);let m=new Map;if(m.set("member:joined",async()=>{if(c.body.channel&&c.body.channel.id)try{this._setStatusAndEmit(this.CALL_STATUS.STARTED);return}catch(b){throw this._setStatusAndEmit(this.CALL_STATUS.FAILED),this.log.error(b),b}return Promise.resolve()}),m.set("member:invited",()=>(c.body.invited_by===null&&c.body.user.media&&c.body.user.media.audio_settings&&this._setStatusAndEmit(this.CALL_STATUS.STARTED),Promise.resolve())),m.set("rtc:hangup",()=>this.status===this.CALL_STATUS.ANSWERED?(this._setStatusAndEmit(this.CALL_STATUS.COMPLETED),Promise.resolve()):p&&v||!p&&!v?(this._setStatusAndEmit(this.CALL_STATUS.UNANSWERED),Promise.resolve()):(this._setStatusAndEmit(this.CALL_STATUS.REJECTED),Promise.resolve())),m.set("member:left",()=>{if(!c.body.timestamp.hasOwnProperty("joined")&&this.status!==this.CALL_STATUS.ANSWERED)return p&&v||!p&&!v?(this._setStatusAndEmit(this.CALL_STATUS.UNANSWERED),Promise.resolve()):(this._setStatusAndEmit(this.CALL_STATUS.REJECTED),Promise.resolve())}),m.set("member:media",()=>(this.status!==this.CALL_STATUS.ANSWERED&&c.body.audio&&(p&&c.body.channel&&(this.id=c.body.channel.id),(!p||!v)&&this.id&&this._setStatusAndEmit(this.CALL_STATUS.ANSWERED)),Promise.resolve())),m.set("sip:ringing",()=>(this.status!==this.CALL_STATUS.RINGING&&this._setStatusAndEmit(this.CALL_STATUS.RINGING),Promise.resolve())),m.set("sip:hangup",()=>{switch(c.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()}),m.set("knocking:delete:success",()=>(this._setStatusAndEmit(this.CALL_STATUS.UNANSWERED),Promise.resolve())),m.has(c.type))return m.get(c.type).call(this)}_setStatusAndEmit(c){this._isValidStatusTransition(c)&&(this.status=c,this.log.debug(`_setStatusAndEmit: ${c}`,{nxmCall:this}),this.application.emit("call:status:changed",this))}async answer(c=!0){if(this.log.debug(`answer: { autoPlayAudio: ${c}`),this.conversation)try{await this.conversation.join();const l=await this.conversation.media.enable({autoPlayAudio:c,offer:this.offer});return this.offer=void 0,l}catch(l){throw this._setStatusAndEmit(this.CALL_STATUS.FAILED),this.log.error(l),l}else throw new a.NexmoClientError("error:call:answer")}async createCall(c,l=!0){if(this.log.debug(`createCall: { usernames: ${c}, autoPlayAudio: ${l} }`),!c||!Array.isArray(c)||c.length===0)return Promise.reject(new a.NexmoClientError("error:application:call:params"));try{const p=await this.application.newConversationAndJoin({display_name:"CALL_"+this.application.me.name+"_"+c.join("_").replace(" ","")});p.members.set(p.me.id,p.me),this.from=p.me,this.successful_invited_members=new Map;const v=c.map(async b=>{try{const T=await p.inviteWithAudio({user_name:b});return p.members.set(T.id,T),this.successful_invited_members.set(T.id,T),T}catch(T){return this.log.error(T),T}}),m=async()=>{if(this.successful_invited_members.size>0)return await p.media.enable({audio:{muted:!1,earmuffed:!1},autoPlayAudio:l}),this.application.calls.set(p.id,this),v;throw v};return await Promise.all(v),this._setupConversationObject(p),await m()}catch(p){throw this.log.error(p),this._setStatusAndEmit(this.CALL_STATUS.FAILED),p}}async createServerCall(c,l,p){this.log.debug(`createServerCall: { user: ${c}, type: ${l}, custom_data: `,{custom_data:p});const v={type:l};l==="phone"?v.number=c:v.user=c;try{const{stream:m,legId:b,rtcObjects:T}=await s.default.prewarmLeg(this);this.log.debug("createServerCall: ",{stream:m},{legId:b},{rtcObjects:T}),this.rtcObjects=T,this.stream=m,this.id=b,this.application._call_draft_list.set(b,this),s.default.playAudioStream(m);const I={type:"POST",path:"knocking",data:{channel:{type:"app",from:{type:"app"},to:v,id:b||null},...p&&Object.keys(p).length&&{properties:{custom_data:p}}}};try{const R=await this.application.session.sendNetworkRequest(I);this.knocking_id=R.id}catch(R){throw new a.NexmoApiError(R)}return s.default.cleanCallMediaIfFailed(this),m}catch(m){throw s.default.cleanMediaProperties(this),m}}async hangUp(c){if(this.log.debug(`hangUp: { reason: ${c} }`),this.conversation&&await this.conversation.media.disable(),!this.knocking_id&&this.conversation)return this.conversation.leave(c).catch(l=>{if(l.type!=="conversation:error:invalid-member-state")return Promise.reject(l)});{let l=`knocking/${this.knocking_id}`;if(c){let p=new URLSearchParams;Object.keys(c).forEach(v=>{p.append(v,c[v])}),l+=`?${p.toString()}`}try{const p=await this.application.session.sendNetworkRequest({type:"DELETE",path:l});return this.application._call_draft_list.get(this.client_ref)._handleStatusChange(p),this.application._call_draft_list.delete(this.client_ref),p}catch(p){if(this.conversation)return this.log.error(new a.NexmoApiError(p)),this.conversation.leave(c).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",p);return}}}reject(c){return this.log.debug(`reject: { reason: ${c} }`),this.conversation?this.conversation.leave(c):Promise.reject(new a.NexmoClientError("error:call:reject"))}}t.default=o,e.exports=o}(ll,ll.exports)),ll.exports}var Hv={exports:{}};(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r=Ar;class n{constructor(a){this.log=r.getLogger(this.constructor.name),this.application=a,this._handleSipCallEventMap={"sip:hangup":this._processSipHangup,"sip:ringing":this._processSipRinging}}_handleSipCallEvent(a){if(this.log.debug("_handleSipCallEvent: ",{event:a}),!this.application.calls.has(a.cid)){this.log.warn("There is no call object for this Conversation id.");return}const s=this.application.calls.get(a.cid);if(this._handleSipCallEventMap.hasOwnProperty(a.type))return this._handleSipCallEventMap[a.type].call(this,s,a)}_processSipHangup(a,s){this.log.debug("_processSipHangup: ",s),a._handleStatusChange(s)}_processSipRinging(a,s){this.log.debug("_processSipRinging: ",s),a._handleStatusChange(s)}}t.default=n,e.exports=n})(Hv,Hv.exports);var bte=Hv.exports,Vv={exports:{}};(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r=Ar;class n{constructor(a){this.log=r.getLogger(this.constructor.name),this.application=a,this._handleRtcEventMap={"rtc:transfer":this._processRtcTransfer,"rtc:answer":this._processRtcAnswer,"rtc:hangup":this._processRtcHangup}}_handleRtcEvent(a){if(this._handleRtcEventMap.hasOwnProperty(a.type))return this._handleRtcEventMap[a.type].call(this,a)}_processRtcTransfer(a){this.log.debug("_processRtcTransfer: ",{event:a});const s=this.application.conversations.get(a.body.transferred_from),o=this.application.conversations.get(a.cid),u=this.application.calls.get(a.body.transferred_from);if(!u){this.log.warn("NXMCall transfer for unknown nxmCall");return}u.conversation.members.get(a.body.was_member).transferred_to=o,u._setupConversationObject(o),u.transferred=!0,this.application.calls.set(a.cid,u),this.application.calls.delete(a.body.transferred_from),s&&(o.members.get(a.from).transferred_from=s,o.media._attachEndingEventHandlers(),Object.entries(o.media.rtcObjects).length===0&&Object.entries(s.media.rtcObjects).length!==0&&Object.assign(o.media.rtcObjects,s.media.rtcObjects),!o.media.pc&&s.media.pc&&Object.assign(o.media.pc=s.media.pc),o.application.activeStreams.length===0&&s.application.activeStreams.length>0&&(o.application.activeStreams=s.application.activeStreams))}_processRtcAnswer(a){this.log.debug("_processRtcAnswer: ",{event:a}),this.application.calls.has(a.cid)&&(this.application.calls.get(a.cid).id=a.body.rtc_id)}_processRtcHangup(a){this.log.debug("_processRtcHangup: ",{event:a}),this.application.calls.has(a.cid)&&this.application.calls.get(a.cid)._handleStatusChange(a)}}t.default=n,e.exports=n})(Vv,Vv.exports);var _te=Vv.exports,fl={exports:{}},fT;function wte(){return fT||(fT=1,function(e,t){var r=je&&je.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(t,"__esModule",{value:!0});const n=Ar,i=r(ia),a=r(WI()),s=r(Ii()),o=r(ed());class u{constructor(l){this.log=n.getLogger(this.constructor.name),this.application=l,this._handleApplicationEventMap={"member:joined":this._processMemberJoined,"member:invited":this._processMemberInvited}}handleEvent(l){const p=this.application.conversations.get(l.cid),v=Object.assign({},l);return this._handleApplicationEventMap.hasOwnProperty(l.type)?this._handleApplicationEventMap[l.type].call(this,p,new i.default(p,v),l):new i.default(p,v)}_processMemberJoined(l,p,v){try{if(p.body.channel&&this.application._call_draft_list.has(p.body.channel.id)){this.log.debug("_processMemberJoined: outbound serverCall from sdk",{event:p});const m=this.application._call_draft_list.get(p.body.channel.id);let b=((m.rtcObjects||{})[p.body.channel.id]||{}).pc;if(m._setFrom(l.me),m._setupConversationObject(l,p.body.channel.id),l.media._attachEndingEventHandlers(),Object.entries(l.media.rtcObjects).length===0&&Object.entries(m.rtcObjects).length!==0&&Object.assign(l.media.rtcObjects,m.rtcObjects),!l.media.pc&&b&&Object.assign(l.media.pc=b),l.application.activeStreams.length===0&&m.application.activeStreams.length>0&&(l.application.activeStreams=m.application.activeStreams),delete m.client_ref,delete m.knocking_id,m.rtcStats&&(l.media.rtcStats=m.rtcStats),this.application._call_draft_list.delete(p.body.channel.id),this.application.calls.set(l.id,m),m._handleStatusChange(p),this.log.debug("_processMemberJoined: processedCall ",{nxmCall:m}),l.members&&p.body.member_id){const T=l.members.get(p.body.member_id);T&&this.application.emit("member:call",T,m)}setTimeout(()=>{l!=null&&l.me&&o.default.emitMediaStream(l.me,b,m.stream)},200)}return this.log.debug("_processMemberJoined: default member joined: ",{event:p}),p}catch(m){this.log.error("_processMemberJoined: ",{e:m})}}_processMemberInvited(l,p){var v,m,b,T,I,R;try{if(!l)return this.log.warn(`no conversation object for ${p.type}`),p;if(((v=l.me)===null||v===void 0?void 0:v.user.id)===p.body.invited_by||!(!((b=(m=p.body.user.media)===null||m===void 0?void 0:m.audio_settings)===null||b===void 0)&&b.enabled))return p;const x=s.default.getMemberNumberFromEventOrNull(p.body.channel)||s.default.getMemberFromNameOrNull(l,p.body.invited_by)||"unknown",N=new a.default(this.application,l,x);return this.application.calls.set(l.id,N),!((T=p.body)===null||T===void 0)&&T.sdp&&this.application.session.config.enableInboundOffer&&N._setOffer({sdp:p.body.sdp,leg_id:p.body.channel.id}),!((I=l.display_name)===null||I===void 0)&&I.startsWith("CALL_")||N._handleStatusChange(p),this.application.emit("member:call",this.application.conversations.get(p.cid).members.get((R=p.body)===null||R===void 0?void 0:R.member_id),N),p}catch(x){this.log.error("_processMemberInvited: ",{e:x})}}}t.default=u,e.exports=u}(fl,fl.exports)),fl.exports}var Kv={exports:{}};(function(e,t){var r=je&&je.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(t,"__esModule",{value:!0});const n=r(td);class i extends n.default{constructor(s){super(s),this.items=new Map,s.items.forEach(o=>{const u=this.application.updateOrCreateConversation(o);this.items.set(u.id,u)})}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()}}t.default=i,e.exports=i})(Kv,Kv.exports);var Ste=Kv.exports,Jv={exports:{}},Yv={exports:{}};(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r=Da;class n{constructor(a,s){var o,u;this.application=a,this.id=(o=s==null?void 0:s.id)!==null&&o!==void 0?o:null,this._embedded=(u=s==null?void 0:s._embedded)!==null&&u!==void 0?u:null,r.mixin(n)}}t.default=n,e.exports=n})(Yv,Yv.exports);var Tte=Yv.exports;(function(e,t){var r=je&&je.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(t,"__esModule",{value:!0});const n=r(td),i=r(Tte);class a extends n.default{constructor(o){super(o),this.items=new Map,o.items.forEach(u=>{this.items.set(u.id,new i.default(this.application,u))})}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()}}t.default=a,e.exports=a})(Jv,Jv.exports);var Cte=Jv.exports,dl={exports:{}},dT;function Ete(){return dT||(dT=1,function(e,t){var r=je&&je.__importDefault||function(u){return u&&u.__esModule?u:{default:u}};Object.defineProperty(t,"__esModule",{value:!0}),t.ConversationEventsProcessor=t.EventsQueue=void 0;const n=Gn,i=r(Ii()),a=Ar;class s{constructor(c){this.callback=c,this.cidMap=new Map,this.log=a.getLogger(this.constructor.name)}async enqueue(c,l){var p,v,m,b,T,I,R,x;const{cid:N,id:j}=c,X=Number(j);if(!N||isNaN(X))return this.callback(c);if(((v=(p=l.conversations.get(N))===null||p===void 0?void 0:p.me)===null||v===void 0?void 0:v.state)==="LEFT")return this.callback(c);if(!this.cidMap.get(N)){this.log.debug(`enqueue: create new ConversationEventsProcessor for ${N}`);const V=new o(N,X-1,l);if(this.cidMap.set(N,V),c.type=="member:media"&&(!((b=(m=c.body)===null||m===void 0?void 0:m.media)===null||b===void 0)&&b.audio)||c.type=="member:joined"&&(!((I=(T=c.body)===null||T===void 0?void 0:T.channel)===null||I===void 0)&&I.id)&&((x=(R=c.body)===null||R===void 0?void 0:R.channel)===null||x===void 0?void 0:x.knocking_id)===void 0){V.processing=!0,V.lastEventIdProcessed=0;try{await new Promise(ee=>setTimeout(ee,V.eventRequestWaitTime));const D=ee=>{var ge;return(ge=ee.find(L=>(L==null?void 0:L.type)==="rtc:transfer"&&(L==null?void 0:L.from)===c.from))===null||ge===void 0?void 0:ge.id};let te=[Array.from(Array(5).keys()).map(ee=>X+1+ee),Array.from(Array(5).keys()).map(ee=>X-1-ee)].flatMap(ee=>ee).map(ee=>V.eventsMap.get(ee)).filter(ee=>ee),ue;if((ue=D(te))===void 0){const ee=Math.max(X-20,1);te=await V.fetchConversationEvents(ee,20)}(ue=D(te))!==void 0&&(ue=Number(ue),V.lastEventIdProcessed=Math.max(ue-1,0),te.slice(ue).forEach(ee=>V.enqueue(Number(ee.id),ee)))}finally{V.processing=!1}}}const J=this.cidMap.get(N);J.enqueue(X,c),J.processing||(J.processing=!0,await J.processEvents())}}t.EventsQueue=s;class o{constructor(c,l,p){this.cid=c,this.eventsMap=new Map,this.callback=v=>p._handleEvent(v),this.lastEventIdProcessed=l,this.largestEventIdInQueue=l,this.processing=!1,this.application=p,this.eventsFetchRange=9,this.eventRequestWaitTime=p.session.config.eventQueueWaitTime,this.log=a.getLogger(this.constructor.name)}enqueue(c,l){return c>this.largestEventIdInQueue&&(this.largestEventIdInQueue=c),c>this.lastEventIdProcessed&&this.eventsMap.set(c,l),l}dequeue(c){const l=this.eventsMap.get(c);return this.eventsMap.delete(c),l}async processEvents(){const c=()=>(this.eventsMap.clear(),this.log.debug("processEvents: Done Processing"),this.processing=!1);if(this.eventsMap.size<1)return c();const l=this.lastEventIdProcessed+1,p=await this.processNextEvent(l,1);return p?(this.lastEventIdProcessed=Number(p.id),this.processEvents()):c()}async processNextEvent(c,l){this.log.debug(`processNextEvent: processing event number ${c}`);const p=this.dequeue(c);try{if(p)return await this.callback(p),p;if(l>0)return await new Promise(v=>setTimeout(v,this.eventRequestWaitTime)),this.processNextEvent(c,l-1);if(this.largestEventIdInQueue>c){this.log.debug(`processNextEvent: largestEventIdInQueue-${this.largestEventIdInQueue} > eventId-${c}`);const v=await this.fetchEventsAndProcess(c);return v?(this.log.debug("processNextEvent: foundEvent ",{foundEvent:v}),await this.callback(v),v):(this.log.debug(`processNextEvent: not found process next ${c+1}`),this.processNextEvent(c+1,l))}return}catch{return}}async fetchEventsAndProcess(c){try{const l=await this.fetchConversationEvents(c,this.eventsFetchRange);this.log.debug("fetchEventsAndProcess: fetched events list ",{eventsList:l});let p;return l.forEach(v=>{v.cid=this.cid;const m=Number(v.id);isNaN(m)||m<c||(m>c?(this.log.debug(`fetchEventsAndProcess: event > missingEvent ${m} `,{missingEvent:c}),this.enqueue(m,v)):(this.log.debug("fetchEventsAndProcess: foundEvent ",{event:v}),p=v))}),p}catch(l){this.log.debug("fetchEventsAndProcess: error ",{e:l});return}}async fetchConversationEvents(c,l){this.log.debug("fetchConversationEvents: ",this.cid,c);const p=this.largestEventIdInQueue>c?this.largestEventIdInQueue+l:c+l,v=`${this.application.session.config.nexmo_api_url}/beta2/conversations/${this.cid}/events`;try{return(await i.default.paginationRequest(v,{start_id:c,end_id:p},this.application.session.config.token)).items}catch(m){throw new n.NexmoApiError(m)}}}t.ConversationEventsProcessor=o,e.exports={EventsQueue:s,ConversationEventsProcessor:o}}(dl,dl.exports)),dl.exports}var pT;function rd(){return pT||(pT=1,function(e,t){var r=je&&je.__importDefault||function(J){return J&&J.__esModule?J:{default:J}};Object.defineProperty(t,"__esModule",{value:!0});const n=Da,i=Ar,a=Gn,s=r(X$),o=r(zI()),u=r(WI()),c=r(bte),l=r(_te),p=r(wte()),v=r(Ii()),m=r(qI),b=r(Ste),T=r(Cte),I=Ete(),R=r(Yg());let x=null,N=null,j=null;class X{constructor(V,D){this.log=i.getLogger(this.constructor.name),this.session=V,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 m.default((V.config||{}).conversations_page_config),this.conversations_page_last=null,this.activeStreams=[],x=new c.default(this),N=new l.default(this),j=new p.default(this),this.me=null,Object.assign(this,D),n.mixin(X)}updateOrCreateConversation(V){const D=this.conversations.get(V.id);return D?(D._updateObjectInstance(V),this.conversations.set(V.id,D)):this.conversations.set(V.id,new o.default(this,V)),this.conversations.get(V.id)}async _enqueueEvent(V){this.session.config.enableEventsQueue?(this.eventsQueue||(this.eventsQueue=new I.EventsQueue(D=>this._handleEvent(D))),this.eventsQueue.enqueue(V,this)):this._handleEvent(V)}async _handleEvent(V){var D,te,ue,ee,ge,L,pe;const Te=!((D=V._embedded)===null||D===void 0)&&D.from_user?((ue=(te=V._embedded)===null||te===void 0?void 0:te.from_user)===null||ue===void 0?void 0:ue.id)===((ee=this.me)===null||ee===void 0?void 0:ee.id):((L=(ge=V.body)===null||ge===void 0?void 0:ge.user)===null||L===void 0?void 0:L.user_id)===((pe=this.me)===null||pe===void 0?void 0:pe.id),rt=v.default._checkIfUserIsReInvited(this.conversations,V);if(V.type.startsWith("sip"))return x._handleSipCallEvent(V),V;if(this.conversations.has(V.cid)&&V.type!=="rtc:transfer"&&!rt)return V.type.startsWith("rtc")&&N._handleRtcEvent(V),this.conversations.get(V.cid)._handleEvent(V),(V.type==="member:joined"||V.type==="member:invited")&&Te&&this._handleApplicationEvent(V),V;if(V.cid)try{rt&&this.conversations.delete(V.cid);let Ke;return v.default._isCallEvent(V)?Ke=await this.getConversation(V.cid,X.CONVERSATION_API_VERSION.v1):Ke=await this.getConversation(V.cid,X.CONVERSATION_API_VERSION.v3),this.conversations.set(V.cid,Ke),await Ke._handleEvent(V),await this._handleApplicationEvent(V),V.type.startsWith("rtc")&&N._handleRtcEvent(V),Promise.resolve(V)}catch(Ke){return this.log.error(Ke),Promise.reject(Ke)}}async updateToken(V){if(this.session.connection&&this.session.connection.disconnected)return this.session.config.token=V,this.session.connection.io.opts.query.token=V,Promise.resolve();const D={url:`${this.session.config.nexmo_api_url}/v0.2/sessions/${this.session.session_id}`,type:"PUT",token:V};try{await v.default.networkRequest(D),this.me&&(this.session.config.token=V,this.session.connection.io.opts.query.token=V)}catch(te){throw new a.NexmoApiError(te)}}async _handleApplicationEvent(V){try{this.log.debug("_handleApplicationEvent: ",{event:V});const D=j.handleEvent(V),te=this.conversations.get(V.cid);let ue;if(te.members.has((D||{}).from))ue=te.members.get(D.from);else if(V.type==="member:joined"||V.type==="member:invited"){const ee={...V.body,...V.from&&{member_id:V.from}};ue=new R.default(te,ee)}else try{ue=await te.getMember(D.from)}catch(ee){this.log.warn(`There is an error getting the member ${ee}`)}return this.emit(D.type,ue,D),V}catch(D){throw this.log.error("_handleApplicationEvent: ",D),D}}async inAppCall(V){if(!V||!Array.isArray(V)||V.length===0)return Promise.reject(new a.NexmoClientError("error:application:call:params"));try{const D=new u.default(this);return await D.createCall(V),D.direction=D.CALL_DIRECTION.OUTBOUND,D}catch(D){throw D}}async callServer(V,D="phone",te={}){try{const ue=new u.default(this);return ue.direction=ue.CALL_DIRECTION.OUTBOUND,await ue.createServerCall(V,D,te),ue}catch(ue){throw ue}}async reconnectCall(V,D,te={}){try{if(!V||!D)throw new a.NexmoClientError("error:missing:params");const ue=await this.getConversation(V,X.CONVERSATION_API_VERSION.v1);await ue.media.enable({...te,reconnectRtcId:D});const ee=new u.default(this,ue),ge=Array.from(ue.events.values()).map(L=>L.type);return ge.includes("sip:answered")?ee.status=ee.CALL_STATUS.ANSWERED:ge.includes("sip:ringing")?ee.status=ee.CALL_STATUS.RINGING:ee.status=ee.CALL_STATUS.STARTED,ee.rtcObjects=ue.media.rtcObjects,this.calls.set(ue.id,ee),ee}catch(ue){throw ue}}async newConversation(V={}){try{const D=await this.session.sendNetworkRequest({type:"POST",path:"conversations",data:V}),te=new o.default(this,D);return this.conversations.set(te.id,te),this.getConversation(te.id,X.CONVERSATION_API_VERSION.v1)}catch(D){throw new a.NexmoApiError(D)}}async newConversationAndJoin(V){const D=await this.newConversation(V);return await D.join(),D}async getConversation(V,D=X.CONVERSATION_API_VERSION.v3){if(D!==X.CONVERSATION_API_VERSION.v1&&D!==X.CONVERSATION_API_VERSION.v3)throw new a.NexmoClientError("error:conversation-service:version");let te;if(D===X.CONVERSATION_API_VERSION.v1)try{te=await this.session.sendNetworkRequest({type:"GET",path:`conversations/${V}`}),te.id=te.uuid,delete te.uuid}catch(ee){throw new a.NexmoApiError(ee)}else try{te=await this.session.sendNetworkRequest({type:"GET",path:`conversations/${V}`,version:"v0.3"})}catch(ee){throw new a.NexmoApiError(ee)}const ue=this.updateOrCreateConversation(te);if(D===X.CONVERSATION_API_VERSION.v3&&!ue.me)try{const ee=await ue.getMyMember();ue.me=ee,ue.members.set(ee.id,ee)}catch{try{const ge=await ue.getMyMember();ue.me=ge,ue.members.set(ge.id,ge)}catch{this.log.warn(`You don't have any membership in ${ue.id}`)}}if(this.session.config.sync==="full"){const{items:ee}=await ue.getEvents();return ue.events=ee,ue}else return ue}async getConversations(V={}){const D=`${this.session.config.nexmo_api_url}/beta2/users/${this.me.id}/conversations`;let te=Object.keys(V).length===0?this.pageConfig:new m.default(V);try{const ue=await v.default.paginationRequest(D,te,this.session.config.token);ue.application=this;const ee=new b.default(ue);return this.conversations_page_last=ee,ee}catch(ue){throw new a.NexmoApiError(ue)}}syncConversations(V){const D=Array.from(V.values()),te=D.length,ue=new Date;this.start_sync_time=typeof window<"u"&&window.performance?window.performance.now():ue.getTime();const ee=async()=>{this.synced_conversations_percentage=Number((this.synced_conversations_count/te*100).toFixed(2));const ge={sync_progress:this.synced_conversations_percentage};if(this.emit("sync:progress",ge),this.log.info("Loading sync progress: "+this.synced_conversations_count+"/"+te+" - "+this.synced_conversations_percentage+"%"),this.synced_conversations_percentage>=100){const L=new Date;this.stop_sync_time=typeof window<"u"&&window.performance?window.performance.now():L.getTime(),this.log.info("Loaded conversations in "+(this.stop_sync_time-this.start_sync_time)+"ms")}this.synced_conversations_count<te&&(await this.getConversation(D[this.synced_conversations_count].id),ee(),this.synced_conversations_count++,this.sync_progress_buffer++)};ee()}async getUser(V=this.me.id){try{const D=await this.session.sendNetworkRequest({type:"GET",path:`users/${V}`});return new s.default(this,D)}catch(D){throw new a.NexmoApiError(D)}}async getUserSessions(V={}){var D;const te=((D=V)===null||D===void 0?void 0:D.user_id)||this.me.id,ue=`${this.session.config.nexmo_api_url}/v0.3/users/${te}/sessions`;let ee=Object.keys(V).length===0?this.pageConfig:new m.default(V);try{const ge=await v.default.paginationRequest(ue,ee,this.session.config.token,X.CONVERSATION_API_VERSION.v3);ge.application=this;const L=new T.default(ge);return this.user_sessions_page_last=L,L}catch(ge){throw new a.NexmoApiError(ge)}}}t.default=X,X.CONVERSATION_API_VERSION={v1:"v0.1",v3:"v0.3"},e.exports=X}(Qc,Qc.exports)),Qc.exports}var hT;function Ii(){return hT||(hT=1,function(e,t){var r=je&&je.__importDefault||function(p){return p&&p.__esModule?p:{default:p}};Object.defineProperty(t,"__esModule",{value:!0});const n=r(jee),i=r(G$),a=r(rd()),s=4e4,o=2e4,u=new RegExp(`"|'|<|>|&|\\|/`),c=new RegExp(`"|'|<|>|\\|javascript:`);class l{static getMemberFromNameOrNull(v,m){if(!v||!m)return null;for(let b of v.members.values())if(b.user.name===m)return b;return null}static getMemberNumberFromEventOrNull(v){const m=v&&v.from;return m&&(m.number||m.uri)?m.number||m.uri:null}static isSanitizedInput(v){return!u.test(v)}static isSanitizedUrlInput(v){return!c.test(v)}static checkIsSanitized([v,m]){if(m==null)return!0;switch(typeof m){case"string":return v.includes("url")||v.includes("uri")?l.isSanitizedUrlInput(m):l.isSanitizedInput(m);case"object":return Array.isArray(m)?m.every(b=>l.checkIsSanitized(["dummy",b])):Object.entries(m).every(l.checkIsSanitized);default:return!0}}static networkRequest(v){return new Promise((m,b)=>{!v.token&&!v.url.includes("logging")&&!v.url.includes("ping")&&b({response:{type:"error:user:token",description:"network error on request. Please create a new session."}});const T=new XMLHttpRequest;let I;T.open(v.type,v.url,!0),v.token&&T.setRequestHeader("Authorization","Bearer "+v.token),v&&v.url.includes("image")?(T.responseType="",I=v.data,T.onloadstart=()=>{m(T)}):(T.responseType=v.responseType||"json",I=v.data?JSON.stringify(v.data):null,T.setRequestHeader("Content-type","application/json; charset=utf-8")),T.onload=()=>{T.status===200||T.status===201||T.status===204?m(T):b(T)},T.onerror=R=>{b(R)},T.send(I)})}static async paginationRequest(v,m,b,T=a.default.CONVERSATION_API_VERSION.v1){try{const I=await l.networkRequest({type:"GET",url:l.addUrlSearchParams(v,m),token:b}),{page_size:R,_embedded:x,_links:N}=I.response,j=v.split("/").pop().trim();return{items:T===a.default.CONVERSATION_API_VERSION.v1?x.data[j]:x[j],cursor:{prev:N.prev?new URLSearchParams(N.prev.href).get("cursor"):"",next:N.next?new URLSearchParams(N.next.href).get("cursor"):"",self:N.self?new URLSearchParams(N.self.href).get("cursor"):""},page_size:R,order:m.order||"asc",event_type:m.event_type||null}}catch({response:I}){const R=I||{type:"error:network:get-request",description:"network error on nexmo get request"};throw R.validation&&(R.description=R.validation[Object.keys(R.validation)[0]]),R}}static addUrlSearchParams(v,m={}){let b=new URL(v);return Object.keys(m).forEach(T=>{m[T]&&!(typeof m[T]=="string"&&m[T].length<1)&&m[T]!==null&&b.searchParams.set(T,m[T])}),b.href}static deepMergeObj(v,m){const b=JSON.parse(JSON.stringify(v));for(let T in m)Object.prototype.toString.call(m[T])==="[object Object]"?b[T]=l.deepMergeObj(b[T],m[T]):b[T]=m[T];return b}static injectScript(v,m){if(typeof document<"u"){let b=document.getElementsByTagName("head")[0],T=document.createElement("script");T.async=!0,T.src=v,T.onload=T.onreadystatechange=()=>{(!T.readyState||/loaded|complete/.test(T.readyState))&&(T.onload=T.onreadystatechange=null,T=null,m&&m())},b.insertBefore(T,b.firstChild)}}static allocateUUID(){return n.default.v4()}static validateDTMF(v){return typeof v=="string"?/^[\da-dA-D#*pP]{1,45}$$/.test(v):!1}static _getBugsnagKey(){return"76498fc1ca8d9b0a173a44e2b873d7ed"}static updateMemberLegs(v,m){if(v){const b=v.find(T=>T.leg_id===m.body.leg_id);if(!b)v.push({leg_id:m.body.leg_id,status:m.body.status});else if(b.status!==m.body.status){let T=v.indexOf(b);v.fill(b.status=m.body.status,T,T++)}}else v=[{leg_id:m.body.leg_id,status:m.body.status}];return v}static _isCallEvent(v){const{channel:m,media:b}=v.body;return!!(v.type==="rtc:transfer"||m&&(b&&b.audio_settings&&b.audio_settings.enabled||b&&b.audio&&b.audio.enabled||m.knocking_id))}static async _fetchImage(v,m){const{response:b}=await l.networkRequest({type:"GET",url:v,responseType:"arraybuffer",token:m}),T=new Uint8Array(b);let I="";const R=8*1024;let x;for(x=0;x<T.length/R;x++)I+=String.fromCharCode.apply(null,T.subarray(x*R,(x+1)*R));return I+=String.fromCharCode.apply(null,T.subarray(x*R)),"data:image/jpeg;base64,"+btoa(I)}static async _checkHttpConnectivity(v){const m=Date.now();try{await l.networkRequest({type:"GET",url:v});const b=Date.now()-m;return{url:v,canConnect:!0,connectionTime:b}}catch(b){return{url:v,canConnect:!1,error:b}}}static _checkWsConnectivity(v,m,b){return new Promise((T,I)=>{const R=Object.assign({path:m},b),x=Date.now(),N=i.default.connect(v,R),j=setTimeout(()=>T({url:v,canConnect:!1}),o);N.on("connect",()=>{const X=Date.now()-x;N.disconnect(),clearTimeout(j),T({url:v,canConnect:!0,connectionTime:X})}),N.on("error",X=>{N.disconnect(),clearTimeout(j),T({url:v,canConnect:!1,error:X})})})}static async _checkMediaServers(v,m,b){try{const{response:T}=await l.networkRequest({type:"GET",url:`${m}/v0.3/discovery/media/${b}`,token:v}),I=T.map(R=>l._checkMediaConnectivity(R.ip,R.port));return await Promise.all(I)}catch{return[]}}static async _checkMediaConnectivity(v,m){return new Promise(async(b,T)=>{const I={iceServers:[{urls:`stun:${v}:${m}`}]},R=new RTCPeerConnection(I),x=Date.now(),N=await R.createOffer({offerToReceiveAudio:!0});R.setLocalDescription(N);const j=setTimeout(()=>{R.close(),b({ip:v,canConnect:!1})},s);R.addEventListener("icecandidate",X=>{var J;if(((J=X==null?void 0:X.candidate)===null||J===void 0?void 0:J.type)==="srflx"){const V=Date.now()-x;clearTimeout(j),R.close(),b({ip:v,canConnect:!0,connectionTime:V})}}),R.addEventListener("icecandidateerror",X=>{X.errorCode&&(R.close(),clearTimeout(j),b({ip:v,canConnect:!1,error:X}))})})}static _checkIfUserIsReInvited(v,m){var b;if(!v.has(m.cid)||!(m.type==="member:invited"||m.type==="member:joined"))return!1;const T=(b=v.get(m.cid))===null||b===void 0?void 0:b.me;return T?T.user.name===m.body.user.name&&T.state==="LEFT":!1}}t.default=l,e.exports=l}(Yc,Yc.exports)),Yc.exports}var Xv={exports:{}};(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r=Ar,n=Gn;class i{constructor(s){if(this.log=r.getLogger(this.constructor.name),!s)throw new n.NexmoClientError("no emitter object passed for the Error Emitter");this.emitter=s,this.LISTENER_GROUP="NXM-errors"}emitResponseIfError(s){if(this._isTypeError(s.type))return this.emitter.emit(s.type,this.LISTENER_GROUP,s)}cleanup(){return this.emitter.releaseGroup(this.LISTENER_GROUP)}_isTypeError(s){return s.indexOf("error")!==-1}}t.default=i,e.exports=i})(Xv,Xv.exports);var kte=Xv.exports;(function(e,t){var r=je&&je.__importDefault||function(I){return I&&I.__esModule?I:{default:I}};Object.defineProperty(t,"__esModule",{value:!0});const n=Da,i=r(kQ),a=r(Ar),s=Gn,o=r(G$),u=r(wee),c=r(Ree),l=r(Ii()),p=r(rd()),v=r(kte),m=r(X$),b=r(ed());i.default.reg(a.default),i.default.apply(a.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 T{constructor(R={}){const x=R;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.6.1",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,eventQueueWaitTime:50,enableInboundOffer:!1,acknowledgeEvents:!0,token:null},this.config.socket_io.query={token:"",SDK_version:this.config.SDK_version,session_version:R.enableInboundOffer?"0.0.3":"0.0.1",acknowledge_events:this.config.acknowledgeEvents,OS_family:"js",OS_revision:typeof navigator<"u"?navigator.userAgent:typeof window<"u"?window.navigator.userAgent:"Generic JS navigator"},this.sessionReady=!1,this.disconnectTimestamp=null,this.session_id=null,this.apiKey=null,this.requests={},this.application=null,["debug","info","warn","error"].includes(x.debug)?a.default.setLevel(x.debug):x.debug===!0?a.default.setLevel("debug"):a.default.setLevel("silent"),this.log=a.default.noConflict(),this.config=l.default.deepMergeObj(this.config,this._sanitizeConfig(x)),this.config.log_reporter.enabled){const N={apiKey:this.config.log_reporter.bugsnag_key||l.default._getBugsnagKey(),appVersion:this.config.socket_io.query.SDK_version,releaseStage:this.config.environment};je.NXMbugsnagClient=u.default(N)}n.mixin(T)}_createAndSetConnection(){let R,x=Object.assign({path:this.config.path},this.config.socket_io);return R=o.default.connect(this.config.url,x),this.connection=R,R.on("connect",()=>{this.emit("ready"),this.sessionReady=!0,this.log.info("websocket ready")}),R.on("disconnect",(N,j)=>{this.emit("disconnect",N==="io client disconnect"?T.DISCONNECT_REASON.ClientDisconnected:N==="io server disconnect"&&this.session_id?T.DISCONNECT_REASON.TokenExpired:T.DISCONNECT_REASON.ConnectionError),this.disconnectTimestamp=Date.now(),this.log.info("websocket disconnected",N,j)}),R.io.on("reconnect",N=>{this.emit("reconnect",N),this.log.info("websocket reconnect",N),l.default.networkRequest({url:`${this.config.url.replace("wss://","https://")}/v2/rtc/metrics`,type:"POST",token:this.config.token,data:{sessionId:this.session_id,metrics:[{name:"TIME_TO_RECONNECT_SUCCESS",time:this.disconnectTimestamp?Date.now()-this.disconnectTimestamp:void 0,attempt:N}]}}).catch(j=>{this.log.warn("Failed to publish socket reconnection metrics",j)})}),R.io.on("reconnect_attempt",N=>{this.emit("reconnecting",N),this.log.info("websocket reconnecting",N)}),R.on("connect_error",N=>{this.emit("error",new s.NexmoClientError(N)),this.log.error("Socket.io reported a generic error",N)}),R.io.on("reconnect_failed",()=>{this.emit("error",new s.NexmoClientError("error:client:reconnection_failed")),this.log.error("websocket reconnection error")}),R.io.on("packet",N=>{if(N.type!==2||N.data[0]==="echo")return;const j=N.data[2];j&&typeof j=="function"&&j();const X=N.data[1];if(X.type=N.data[0],this.log.debug("<--",X.type,X),this.requests["session:login"]){const J=this.requests["session:login"].callback;delete this.requests["session:login"],J(X)}else if(X.rid in this.requests){const J=this.requests[X.rid].callback;delete this.requests[X.rid],delete X.delay,this.errorsEmitter&&this.errorsEmitter.emitResponseIfError(X),J(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)}),R}_sanitizeConfig(R){let x=R;return R.sync&&["none","lite","full"].indexOf(R.sync)===-1&&(this.log.warn(`invalid param '${R.sync}' for sync, reverting to ${this.config.sync}`),x.sync=this.config.sync),x}sendRequest(R,x){R.tid=l.default.allocateUUID();const N=R.type;delete R.type,this.log.debug("-->",N,R),this.log.info("-->",N,R.tid),this.connection.emit(N,R),this.requests[R.tid]={type:N,request:R,callback:x}}async sendNetworkRequest(R){const x=R.version||"beta",N=`${this.config.nexmo_api_url}/${x}/${R.path}`;if(!(R.type==="GET"||R.type==="DELETE")&&(R.data={...R.data,originating_session:this.session_id},!l.default.checkIsSanitized(["data",R.data])))throw new s.NexmoClientError("error:input:unsanitized");try{const j={type:R.type,url:N,data:R.data?R.data:null,token:(R.data||{}).token?R.data.token:this.config.token||null};this.log.debug("sendNetworkRequest: ",{request:j});const{response:X}=await l.default.networkRequest(j);return X}catch({response:j}){throw j}}createSession(R){return this.config.socket_io.query.token=R,this._createAndSetConnection(),new Promise((x,N)=>{this.log.info(`Client-SDK Version: ${this.config.SDK_version}`),this.config.token=null,this.requests["session:login"]={type:"session:login",callback:async j=>{if(j.type==="session:success")if(this.session_id=j.body.id,this.apiKey=j.body.api_key,this.config.token=R,this.connection.io.opts.query={session_id:this.session_id,token:this.config.token},(!this.application||this.application.me&&this.application.me.id!==j.body.user_id)&&(this.application=new p.default(this,{})),this.application.me||(this.application.me=new m.default(this.application,{id:j.body.user_id,name:j.body.name})),this.errorsEmitter||(this.errorsEmitter=new v.default(this.application)),this.config.log_reporter.enabled&&(je.NXMbugsnagClient.user={id:this.application.me.id,name:this.application.me.name,session_id:j.body.id}),this.config.sync!=="none")try{await this.application.getConversations(),x(this.application)}catch(X){N(X)}else x(this.application);else N(new s.NexmoApiError(j))}}})}deleteSession(){return new Promise(async(R,x)=>{const N=()=>this.sendRequest({type:"session:logout",body:{}},j=>{j.type==="session:logged-out"||j.type==="session:terminated"?(this.disconnect(),delete this.errorsEmitter,delete this.application,delete this.connection,this.requests={},this.sessionReady=!1,R(j)):x(j)});if(this.application){let j=[];if(this.application.conversations.size)for(let X of this.application.conversations.values())j.push(X.media.disable());try{await Promise.all(j)}catch(X){this.log.error("deleteSession: ",X)}return N()}else return N()})}updateSession(R){R.type==="session:success"&&(this.session_id=R.body.id,this.connection.io.opts.query.session_id=R.body.id,this.application&&R.body.pending_events&&R.body.pending_events.forEach(x=>this.application._enqueueEvent(x)))}disconnect(){return this.connection.disconnect()}connect(){return this.connection.connect()}async connectivityReport(R,x){const j={machineInfo:{ip:b.default.isNode()?void 0:await c.default.v4()},connectivityReport:[]};try{const{response:X}=await l.default.networkRequest({type:"GET",url:`${this.config.nexmo_api_url}/v0.3/discovery/api`,token:R});let J=X;x!=null&&x.dcListCallback&&(J=x.dcListCallback(J));for(const V in J){const D=J[V].endpoint,te=J[V].https,ue=J[V].ws;try{const ee=await l.default._checkHttpConnectivity(te),ge=await l.default._checkWsConnectivity(ue,this.config.path,this.config.socket_io),L=await l.default._checkMediaServers(R,D,V),pe={name:V,signalConnectionReport:{https:ee,ws:ge},mediaConnectionReport:L};j.connectivityReport.push(pe)}catch(ee){this.log.error(`Error generating report for ${V}`,ee)}}}catch(X){this.log.error("Error fetching nexmo servers information",X)}return j}async checkMediaServers(R,x,N){return await l.default._checkMediaServers(R,x,N)}async checkMediaConnectivity(R,x){return await l.default._checkMediaConnectivity(R,x)}}t.default=T,T.DISCONNECT_REASON={ClientDisconnected:"ClientDisconnected",TokenExpired:"TokenExpired",ConnectionError:"ConnectionError"},e.exports=T})(Tv,Tv.exports);var Rte=Tv.exports;const $te=jT(Rte),Li=new $a("nexmo-chat"),Ite=["us-3","us-4","eu-3","eu-4","ap-3","ap-4"];class GI extends tm{constructor(){super(...arguments);ht(this,"rtc");ht(this,"application");ht(this,"conversation")}get _client(){if(this.rtc)return this.rtc;const r=Ote(this.region);return this.rtc=new $te({nexmo_api_url:`https://api-${this.region}.${r}`,url:`wss://ws-${this.region}.${r}`}),this.rtc}async create(){const{identity:r,token:n}=await this.issueChatToken();Li.info(`Connecting chat, identity: ${r}, token: ${n}`),this.identity=r,this.application=await this._client.createSession(n)}async destroy(){this.rtc&&(await this.rtc.deleteSession(),this.rtc=null,this.application=null,this.conversation=null)}async join(r){const n=await this.application.getConversation(r);n.me.state==="JOINED"?Li.info("already joined conversation:",r):(await n.join(),Li.info("success joined conversation:",r)),this.registerEvents(n),this.conversation=n}async preview(r){await this.conversation.sendCustomEvent({type:"ujet_preview",body:{chat_preview:r,chat_preview_updated_at:new Date().toJSON()}})}async fetchMessages(r){const n=await this.conversation.getEvents({event_type:"message",order:"desc",page_size:100}),i=[];return n.items.forEach(a=>{const s=a._embedded.from_user.name,o=vT(a,s);r[o.$index]&&(o.file=r[o.$index]),this.trackInTask(o),i.push(o)}),i.reverse()}async sendMessage(r){try{const n=await this.conversation.sendMessage({message_type:"text",text:JSON.stringify(r)});return Li.info(`Message sent from ${this.conversation.id}, id: ${n.id}`),parseInt(n.id,10)}catch(n){Li.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(r){r.on("message",(n,i)=>{const a=vT(i,n.userName);Li.info(`Message added from ${this.conversation.id}, index: ${a.$index}, sid: ${a.$sid}, timestamp: ${a.$timestamp}, user type: ${a.$userType}`),a.$userType!=="end_user"&&this.ping(),this.trackInTask(a),this.events.triggerEvent("message",a)}),r.on("member:joined",n=>{Li.info("conversation: memberJoined",n),this.events.triggerEvent("memberJoined",n.userName)}),r.on("member:left",n=>{Li.info("conversation: memberLeft",n),this.events.triggerEvent("memberLeft",n.userName)}),r.on("text:typing:on",n=>{/^end_user/.test(n.userName)||this.events.triggerEvent("typingStarted",n.userName)}),r.on("text:typing:off",n=>{/^end_user/.test(n.userName)||this.events.triggerEvent("typingEnded",n.userName)})}}ht(GI,"type","nexmo_conversations");rm(GI);function Ote(e){return Ite.indexOf(e)>-1?"vonage.com":"nexmo.com"}function vT(e,t){const{id:r,timestamp:n,body:i}=e,[a,s]=t.split("-");let o=0;s&&(o=parseInt(s,10));const u={$index:parseInt(r,10),$sid:r,$timestamp:new Date(Date.parse(n)),$userType:a,$userId:o};try{const c=JSON.parse(i.text);return c.message&&!c.type?{...u,...c,type:"message"}:{...u,...c}}catch(c){return Li.warn("Format message failed",{error:c,data:i.text}),{...u,type:"text",content:i.text}}}exports.Client=gP;exports.ENVIRONMENT=JI;exports.EventManager=em;exports.Logger=$a;exports.MediaStore=CT;exports.OPTIONS=Br;exports.PostSessionStatus=to;exports.VERSION=Qv;exports.addProviderType=rm;exports.consoleLoggerHandler=kO;
534
+ `},Ts=AI,Xee=Yee;aa.write=Xee;aa.parse=Ts.parse;aa.parseParams=Ts.parseParams;aa.parseFmtpConfig=Ts.parseFmtpConfig;aa.parsePayloads=Ts.parsePayloads;aa.parseRemoteCandidates=Ts.parseRemoteCandidates;aa.parseImageAttributes=Ts.parseImageAttributes;aa.parseSimulcastStreamList=Ts.parseSimulcastStreamList;var sa={},Qee=je&&je.__spreadArrays||function(){for(var e=0,t=0,r=arguments.length;t<r;t++)e+=arguments[t].length;for(var n=Array(e),i=0,t=0;t<r;t++)for(var a=arguments[t],s=0,o=a.length;s<o;s++,i++)n[i]=a[s];return n};Object.defineProperty(sa,"__esModule",{value:!0});var xI=function(){function e(t,r,n){this.name=t,this.version=r,this.os=n}return e}();sa.BrowserInfo=xI;var NI=function(){function e(t){this.version=t,this.name="node",this.os=process.platform}return e}();sa.NodeInfo=NI;var LI=function(){function e(){this.bot=!0,this.name="bot",this.version=null,this.os=null}return e}();sa.BotInfo=LI;var Zee=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,ete=/(nuhk)|(Googlebot)|(Yammybot)|(Openbot)|(Slurp)|(MSNBot)|(Ask Jeeves\/Teoma)|(ia_archiver)/,Z0=3,tte=[["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",Zee]],eT=[["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",ete]];function rte(e){return e?zv(e):typeof navigator<"u"?zv(navigator.userAgent):jI()}sa.detect=rte;function zv(e){var t=e!==""&&tte.reduce(function(a,s){var o=s[0],u=s[1];if(a)return a;var c=u.exec(e);return!!c&&[o,c]},!1);if(!t)return null;var r=t[0],n=t[1];if(r==="searchbot")return new LI;var i=n[1]&&n[1].split(/[._]/).slice(0,3);return i?i.length<Z0&&(i=Qee(i,nte(Z0-i.length))):i=[],new xI(r,i.join("."),DI(e))}sa.parseUserAgent=zv;function DI(e){for(var t=0,r=eT.length;t<r;t++){var n=eT[t],i=n[0],a=n[1],s=a.test(e);if(s)return i}return null}sa.detectOS=DI;function jI(){var e=typeof process<"u"&&process.version;return e?new NI(process.version.slice(1)):null}sa.getNodeVersion=jI;function nte(e){for(var t=[],r=0;r<e;r++)t.push("0");return t}var il={exports:{}};function ite(e,t){if(typeof e[Symbol.iterator]=="function")for(const r of e){const n=Array.isArray(r)?r[1]:r;t(n)}else for(const r in e)if(e.hasOwnProperty(r)){const n=e[r];t(n)}}var FI={iterateReports:ite};const ate={"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"}},ste={"remote-candidate":function(e){return al(e)},"inbound-rtp":function(e){return al(e)},"outbound-rtp":function(e){return al(e)},"remote-inbound-rtp":function(e){return al(e)}},al=e=>{const{type:t}=e,r=ate[t],n={};for(let i in r)if(i in e){let a;typeof r[i]=="function"?a=r[i](e):a=r[i],n[a]=e[i]}else n[r[i]]=null;return n};var ote={parsers:ste};const{iterateReports:ute}=FI;function cte(e){let t=0,r=0,n=0,i=100,a=0,s,o,u;return ute(e,c=>{c.type==="inbound-rtp"&&(t=c.jitter,n=c.packetsLost,r=c.packetsReceived)}),r+n>0&&(a=100*(n/(r+n))),s=i+t*2+10,s<160?o=93.2-s/40:o=93.2-(s-120)/10,o=o-a*2.5,o<1&&(o=1),u=1+.035*o+7e-6*o*(o-60)*(100-o),parseFloat(u).toFixed(6)}var UI=cte;const{iterateReports:lte}=FI,{parsers:tT}=ote,fte=UI;function dte(e){const t={};return lte(e,r=>{if(r.type in tT){const n=tT[r.type](r);Object.assign(t,n)}}),t.networkMos=parseFloat(fte(e)),t}var pte=dte,rT;function hte(){return rT||(rT=1,function(e,t){var r=je&&je.__importDefault||function(o){return o&&o.__esModule?o:{default:o}};Object.defineProperty(t,"__esModule",{value:!0});const n=pte,i=UI,a=r(Ii());class s{constructor(u){this.mos_report={min:5,max:0},this._reportsCount=0,this._mosSum=0,this.intervals=[],this._deprecationWarningSent=!1,!(!u||!u.application||!u.rtc_id||!u.pc)&&(this.conversation=null,this.application_id=null,this.attachHandlers(u),this.startSendingStats(u),this.startEmittingStats(u))}attachHandlers(u){const{pc:c}=u;c.addEventListener("connectionstatechange",()=>{switch(c.connectionState){case"disconnected":case"failed":case"closed":this.removeIntervals(),this.emitLastReport(u)}}),u.conversation?u.conversation.on("member:media",(p,v)=>{!this.application_id&&(u==null?void 0:u.rtc_id)===v.body.channel.id&&(this.application_id=v.application_id)}):u.application.on("member:joined",(p,v)=>{(!this.conversation||!this.application_id)&&(u==null?void 0:u.rtc_id)===v.body.channel.id&&(this.conversation=p.conversation,this.application_id=v.application_id)})}emitLastReport(u){const{application:c,conversation:l=null,rtc_id:p,config:{emit_events:v,emit_rtc_analytics:m}}=u,b=this.getMOSReport(),T=b.last;T&&(m&&c.emit("rtcstats:analytics",{type:"mos_report",mos:T,rtc_id:p,mos_report:b,api_key:c.session.apiKey,...this.application_id&&{application_id:this.application_id},...l&&{conversation_id:l.id,conversation_name:l.name}}),v&&(this._deprecationWarningSent||(this._deprecationWarningSent=!0,console.warn('"rtcstats:report" event is deprecated. Use "rtcstats:analytics" instead')),c.emit("rtcstats:report",T,null,l,b)))}startSendingStats(u){const{application:c,conversation:l=null,pc:p,rtc_id:v,config:{remote_collection:m,remote_collection_url:b,remote_collection_interval:T}}=u;if(!m)return;const I=setInterval(()=>{p.getStats(null).then(R=>{var x;const N=(x=l??this.conversation)!==null&&x!==void 0?x:null;a.default.networkRequest({url:b,type:"POST",data:{...n(R),legId:v,apiKey:c.session.apiKey,...this.application_id&&{applicationId:this.application_id},...N&&{conversationId:N.id,conversationName:N.name}}}).catch(()=>{})}).catch(()=>{}),(p.connectionState==="closed"||p.signalingState==="closed")&&this.removeIntervals()},T);this.intervals.push(I)}startEmittingStats(u){const{application:c,conversation:l=null,pc:p,rtc_id:v,config:{emit_events:m,emit_rtc_analytics:b,emit_interval:T}}=u;if(!m&&!b)return;const I=setInterval(()=>{var R;p.getStats(null).then(x=>{var N;const j=this.getMos(x);if(!j)return;const X=(N=l??this.conversation)!==null&&N!==void 0?N:null;b&&c.emit("rtcstats:analytics",{type:"mos",mos:j,report:x,rtc_id:v,api_key:c.session.apiKey,...this.application_id&&{application_id:this.application_id},...X&&{conversation_id:X.id,conversation_name:X.name}}),m&&(this._deprecationWarningSent||(this._deprecationWarningSent=!0,console.warn('"rtcstats:report" event is deprecated. Use "rtcstats:analytics" instead')),c.emit("rtcstats:report",j,x,l))}).catch(()=>{}),(p.connectionState==="closed"||p.signalingState==="closed")&&(this.removeIntervals(),this.emitLastReport({...u,conversation:(R=l??this.conversation)!==null&&R!==void 0?R:null}))},T);this.intervals.push(I)}removeIntervals(){this.intervals.forEach(u=>clearInterval(u)),this.intervals=[]}getMos(u){const c=i(u);return this.updateMOSReport(parseInt(c)),c}updateMOSReport(u){this._reportsCount++,this._mosSum+=u,this.mos_report.last=u,this.mos_report.min=u<this.mos_report.min?u:this.mos_report.min,this.mos_report.max=u>this.mos_report.max?u:this.mos_report.max,this.mos_report.average=this._mosSum/this._reportsCount}getMOSReport(){return this.mos_report.min=s.normaliseFloat(this.mos_report.min),this.mos_report.max=s.normaliseFloat(this.mos_report.max),this.mos_report.last=s.normaliseFloat(this.mos_report.last),this.mos_report.average=s.normaliseFloat(this.mos_report.average),this.mos_report}static normaliseFloat(u){return parseFloat(u).toFixed(6)}}t.default=s,e.exports=s}(il,il.exports)),il.exports}var nT;function ed(){return nT||(nT=1,function(e,t){var r=je&&je.__createBinding||(Object.create?function(m,b,T,I){I===void 0&&(I=T),Object.defineProperty(m,I,{enumerable:!0,get:function(){return b[T]}})}:function(m,b,T,I){I===void 0&&(I=T),m[I]=b[T]}),n=je&&je.__setModuleDefault||(Object.create?function(m,b){Object.defineProperty(m,"default",{enumerable:!0,value:b})}:function(m,b){m.default=b}),i=je&&je.__importStar||function(m){if(m&&m.__esModule)return m;var b={};if(m!=null)for(var T in m)T!=="default"&&Object.hasOwnProperty.call(m,T)&&r(b,m,T);return n(b,m),b},a=je&&je.__importDefault||function(m){return m&&m.__esModule?m:{default:m}};Object.defineProperty(t,"__esModule",{value:!0});const s=aa,o=Ar,u=i(sa),c=Gn,l=a(hte()),p=2e4;class v{constructor(){this.log=o.getLogger(this.constructor.name)}static getUserAudio(b=!0){let T={video:!1,audio:b};return navigator.mediaDevices.getUserMedia(T)}createRTCPeerConnection(b){const T=new RTCPeerConnection(b);return T.trace=()=>{},T}_getWindowLocationProtocol(){return window.location.protocol}static _getBrowserName(){return u.detect().name}static isNode(){return this._getBrowserName()==="node"}checkValidKeys(b,T){let I=!0;return Object.keys(b).forEach(R=>{T.hasOwnProperty(R)||(I=!1)}),I}static cleanCallMediaIfFailed(b){setTimeout(()=>{b.conversation||(this.cleanMediaProperties(b),b.status=b.CALL_STATUS.FAILED,b.application.emit("call:status:changed",b))},5e3)}static callDisconnectHandler(b,T){const I=[b.CALL_STATUS.ANSWERED,b.CALL_STATUS.STARTED,b.CALL_STATUS.RINGING];if(!(T.connectionState!=="disconnected"||!b||!b.conversation))return setTimeout(()=>{T.connectionState==="connected"||I.indexOf(b.status)==-1||(this.cleanMediaProperties(b),b.status=b.CALL_STATUS.COMPLETED,b.application.emit("call:status:changed",b))},p)}static cleanMediaProperties(b){if(b.rtcObjects)for(const T in b.rtcObjects)b.rtcObjects[T].pc.close(),delete b.rtcObjects[T].pc,v.closeStream(b.rtcObjects[T].stream);b.application.activeStreams=[],b.rtcObjects={},b.conversation&&b.conversation.media&&(b.conversation.media.rtcStats=null)}static cleanConversationMediaProperties(b,T){T&&v.closeStream(T),b&&b.close()}static playAudioStream(b){const T=new Audio;return T.srcObject=b,T.autoplay=!0,T}static createDummyCandidateSDP(b){const T={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=s.parse(b.localDescription.sdp);return I.media[0].candidates=[T],s.write(I)}static createRTCPeerConnectionConfig(b){return{iceTransportPolicy:"all",bundlePolicy:"balanced",rtcpMuxPolicy:"require",iceCandidatePoolSize:"0",...b.session.config&&b.session.config.iceServers&&{iceServers:b.session.config.iceServers}}}static setupPeerConnectionApplicationListeners(b,T){T.addEventListener("icecandidateerror",I=>b.emit("rtc:icecandidateerror",I)),T.addEventListener("icegatheringstatechange",()=>b.emit("rtc:icegatheringstatechange",T.iceGatheringState)),T.addEventListener("signalingstatechange",()=>b.emit("rtc:signalingstatechange",T.signalingState)),T.addEventListener("iceconnectionstatechange",()=>b.emit("rtc:iceconnectionstatechange",T.iceConnectionState)),T.addEventListener("connectionstatechange",()=>b.emit("rtc:peerconnectionstatechange",T.connectionState))}static createPeerConnection(b){const T=this.createRTCPeerConnectionConfig(b),I=new RTCPeerConnection(T);return this.setupPeerConnectionApplicationListeners(b,I),I}static sendOffer(b,T,I,R){const N={sdp:this.createDummyCandidateSDP(T)};let j={from:I.me.id,body:{offer:N}},X=`conversations/${I.id}/rtc`;return R&&(X+=`/${R}/offer`),b.session.sendNetworkRequest({type:"POST",path:X,data:j})}static sendAnswer(b,T,I,R){const x=this.createDummyCandidateSDP(T);let N={from:I.me.id,body:{answer:x}},j=`conversations/${I.id}/rtc/${R}/answer`;return b.session.sendNetworkRequest({type:"POST",path:j,data:N})}static createLeg(b,T){const R={sdp:this.createDummyCandidateSDP(T),type:"offer"};return b.session.sendNetworkRequest({type:"POST",path:"legs",version:"beta",data:{body:{offer:R}}})}static closeStream(b){b.getTracks().forEach(T=>{T.stop()})}static emitMediaStream(b,T,I){b.emit("media:stream:on",{pc:T,stream:I,type:"audio",streamIndex:0})}static _initStatsEvents(b){var T,I,R;if(!v.isNode()&&!((R=(I=(T=b==null?void 0:b.application)===null||T===void 0?void 0:T.session)===null||I===void 0?void 0:I.config)===null||R===void 0)&&R.rtcstats){const x=b.application.session.config.rtcstats,{emit_events:N,remote_collection:j,emit_rtc_analytics:X}=x;if(N||j||X){const J={...b,config:{...x}};return new l.default(J)}}}static attachConversationEventHandlers(b){const{conversation:T,pc:I,log:R}=b;T.once("rtc:answer",x=>{if(!I){R.warn("RTC: received an answer too late");return}I.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:x.body.answer}))})}static doAnswer(b,T,I){const{application:R,conversation:x,pc:N,reject:j,localStream:X}=b;this.addPeerConnectionListeners(b,()=>v.sendAnswer(R,N,x,I).then(()=>({rtc_id:I}))),N.setRemoteDescription(new RTCSessionDescription({type:"offer",sdp:T})).then(()=>N.createAnswer()).then(J=>N.setLocalDescription(J)).catch(J=>{v.cleanConversationMediaProperties(N,X),j(J)})}static attachPeerConnectionEventHandlers(b){const{application:T,conversation:I,pc:R,reconnectRtcId:x}=b;this.addPeerConnectionListeners(b,()=>v.sendOffer(T,R,I,x))}static addPeerConnectionListeners(b,T){const{application:I,conversation:R,pc:x,streamIndex:N,localStream:j,log:X,rtcObjects:J,resolve:V,reject:D}=b;let te,ue=!1,ee;R.id&&(ee=I.calls.get(R.id)),x.ontrack=ge=>{te=ge.streams[0],I.activeStreams.push(te),v.emitMediaStream(R.me,x,te)},x.addEventListener("connectionstatechange",ge=>this.onconnectionstatechangeHandler(x,X,ee,()=>V(te),()=>{v.cleanConversationMediaProperties(x,j),D()})),x.addEventListener("negotiationneeded",()=>this.onnegotiationneededHandler(x,ge=>{v.cleanConversationMediaProperties(x,j),D(ge)})),x.addEventListener("iceconnectionstatechange",ge=>this.oniceconnectionstatechange(ge,x,X,L=>{v.cleanConversationMediaProperties(x,j),D(L)})),x.addEventListener("icecandidate",async ge=>{if(ge.candidate&&!ue&&x){ue=!0;try{const{rtc_id:L}=await T();v._initStatsEvents({application:I,rtc_id:L,pc:x,conversation:R}),x.trace&&x.trace("rtc_id",L),J[L]={rtc_id:L,pc:x,stream:j,type:"audio",streamIndex:N}}catch(L){v.cleanConversationMediaProperties(x,j),D(new c.NexmoClientError(L))}}}),j.getTracks().forEach(ge=>x.addTrack(ge))}static prewarmLeg(b){const T=b.application;return new Promise(async(I,R)=>{let x=!1,N,j,X={},J,V;const D=o.getLogger(this.constructor.name);try{V=await this.getUserAudio(),J=this.createPeerConnection(T),J.ontrack=te=>{N=te.streams[0],T.activeStreams.push(N)},J.addEventListener("connectionstatechange",te=>this.onconnectionstatechangeHandler(J,D,b,()=>I({stream:N,legId:j,rtcObjects:X}),()=>{v.cleanConversationMediaProperties(J,V),R()})),J.addEventListener("negotiationneeded",()=>this.onnegotiationneededHandler(J,te=>{v.cleanConversationMediaProperties(J,V),R(te)})),J.addEventListener("iceconnectionstatechange",te=>this.oniceconnectionstatechange(te,J,D,ue=>{v.cleanConversationMediaProperties(J,V),R(ue)})),J.addEventListener("icecandidate",async te=>{if(te.candidate&&!x&&J){x=!0;const{rtc_id:ue,sdp:ee}=await this.createLeg(T,J);return v._initStatsEvents({application:T,rtc_id:ue,pc:J}),j=ue,X[j]={rtc_id:ue,pc:J,stream:V,type:"audio",streamIndex:1},J.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:ee}))}}),V.getTracks().forEach(te=>J.addTrack(te))}catch(te){v.cleanConversationMediaProperties(J,V),R(new c.NexmoClientError(te))}})}}t.default=v,v.onconnectionstatechangeHandler=(m,b,T,I,R)=>{switch(m.connectionState){case"connected":b.info("The connection has become fully connected"),I();break;case"disconnected":if(!T)break;T.call_disconnect_timeout&&clearTimeout(T.call_disconnect_timeout),T.call_disconnect_timeout=v.callDisconnectHandler(T,m);break;case"failed":R(),b.info("One or more transports has terminated unexpectedly or in an error");break;case"closed":b.info("The connection has been closed");break}},v.oniceconnectionstatechange=(m,b,T,I)=>{switch(b.iceConnectionState){case"disconnected":T.warn("One or more transports is disconnected",b.iceConnectionState);break;case"failed":I(new c.NexmoClientError(m)),T.warn("One or more transports has terminated unexpectedly or in an error",m);break;default:T.info("The ice connection status changed",b.iceConnectionState)}},v.onnegotiationneededHandler=async(m,b)=>{try{const T=await m.createOffer();return m.setLocalDescription(T)}catch(T){b(new c.NexmoClientError(T))}},e.exports=v}(nl,nl.exports)),nl.exports}var iT;function vte(){return iT||(iT=1,function(e,t){var r=je&&je.__importDefault||function(p){return p&&p.__esModule?p:{default:p}};Object.defineProperty(t,"__esModule",{value:!0});const n=Ar,i=Gn,a=r(ed()),s=r(Ii()),o=r(ia),u=r(zI()),c=r(rd());class l{constructor(v){var m,b,T;const I=v instanceof u.default?v:null,R=v instanceof c.default?v:null;this.log=n.getLogger(this.constructor.name),I?(this.rtcHelper=new a.default,this.application=I.application,this.application.activeStreams=this.application.activeStreams||[],this.parentConversation=I,this.rtcObjects={},this.streamIndex=0,this.rtcstats_conf=((T=(b=(m=this.application)===null||m===void 0?void 0:m.session)===null||b===void 0?void 0:b.config)===null||T===void 0?void 0:T.rtcStats)||{},this.rtcStats=null):R?(this.rtcHelper=new a.default,this.application=R):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 m;if(this.parentConversation.members.has(v.from))m=this.parentConversation.members.get(v.from);else try{m=await this.parentConversation.getMember(v.from)}catch(b){this.log.warn(`There is an error getting the member ${b}`)}m.user.id===this.application.me.id&&this.application.activeStreams.length&&this._cleanMediaProperties(),m.user.id===this.application.me.id&&m.transferred_from&&m.transferred_from.media._cleanMediaProperties(),m.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=a.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={},m){return new Promise(async(b,T)=>{const I=this.streamIndex;this.streamIndex++;const{audioConstraints:R}=v;try{const x=await a.default.getUserAudio(R),N=a.default.createPeerConnection(this.application);this.pc=N;const{application:j,log:X,parentConversation:J,rtcObjects:V}=this,D={pc:N,streamIndex:I,localStream:x,application:j,conversation:J,log:X,rtcObjects:V};m({...D,resolve:b,reject:T}),a.default.attachConversationEventHandlers(D),this._attachEndingEventHandlers()}catch(x){T(new i.NexmoClientError(x))}})}_execAnswer(v={}){const{offer:{sdp:m,leg_id:b}}=v;return this._audioInitHandler(v,T=>a.default.doAnswer(T,m,b))}_handleAudio(v={}){const{reconnectRtcId:m}=v;return this._audioInitHandler(v,b=>a.default.attachPeerConnectionEventHandlers({...b,reconnectRtcId:m}))}_findRtcObjectByType(v){return Object.values(this.rtcObjects).find(m=>m.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)a.default.closeStream(this.rtcObjects[v].stream);delete this.pc,this.rtcStats=null,this.application.activeStreams=[],this.rtcObjects={},this.listeningToRtcEvent=!1}async _disableLeg(v){const m=new Promise(async(T,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"}),T("rtc:terminate:success")}catch(R){I(new i.NexmoApiError(R))}}),b=new Promise(T=>{this.rtcObjects[v].pc&&this.rtcObjects[v].pc.close(),this.rtcObjects[v].stream&&a.default.closeStream(this.rtcObjects[v].stream),T()});try{return await Promise.all([m,b]),this.parentConversation.me.emit("media:stream:off",this.rtcObjects[v].streamIndex),delete this.rtcObjects[v],"rtc:terminate:success"}catch(T){throw T}}_enableMediaTracks(v,m){v.forEach(b=>{b.enabled=m})}async _setMediaTracksAndMute(v,m,b,T){this._enableMediaTracks(m,!b);try{return await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.parentConversation.id}/events`,data:{type:T,to:this.parentConversation.me.id,from:this.parentConversation.me.id,body:{rtc_id:v}}})}catch(I){throw this._enableMediaTracks(m,b),new i.NexmoApiError(I)}}async updateAudioConstraints(v={}){let m=this._findRtcObjectByType("audio");if(m&&m.pc)try{const b=await a.default.getUserAudio(v);return b.getTracks().forEach(T=>{const I=m.pc.getSenders().find(R=>R.track.kind===T.kind);I&&(T.enabled=I.track.enabled,I.replaceTrack(T))}),a.default.closeStream(m.stream),m.stream=b,b}catch(b){return b}else throw new i.NexmoApiError("error:media:stream:not-found")}mute(v=!1,m=null){const T="audio:mute:"+(v?"on":"off");let I=[],R={};if(m!==null){if(R[0]=Object.values(this.rtcObjects).find(x=>x.streamIndex===m),!R[0])throw new i.NexmoClientError("error:media:stream:not-found")}else R=this.rtcObjects;return Object.values(R).forEach(x=>{const N=x.stream.getAudioTracks(),j=this._setMediaTracksAndMute(x.rtc_id,N,v,T);I.push(j)}),Promise.all(I)}async earmuff(v){try{if(this.me===null)throw new i.NexmoClientError("error:self");{let m="audio:earmuff:off";v&&(m="audio:earmuff:on");const{response:b}=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.parentConversation.id}/events`,data:{type:m,to:this.parentConversation.me.id}});return b}}catch(m){throw new i.NexmoApiError(m)}}async enable(v){try{if(this.parentConversation.me===null)throw new i.NexmoClientError("error:self");{const{offer:m}=v??{};let b=await(m!==void 0?this._execAnswer(v):this._handleAudio(v)),T=v&&(v.autoPlayAudio||v.autoPlayAudio===void 0);return(!v||T)&&a.default.playAudioStream(b),b}}catch(m){throw m}}disable(){let v=[];v.push(this._cleanConversationProperties());for(const m in this.rtcObjects)v.push(this._disableLeg(m));return Promise.all(v)}async sayText(v){try{const m=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 o.default(this.parentConversation,m)}catch(m){throw new i.NexmoApiError(m)}}async sendDTMF(v){try{if(!s.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:b,timestamp:T}=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:b,timestamp:T,type:"audio:dtmf"},R=new o.default(this.parentConversation,I);return this.parentConversation.events.set(I.id,R),R}catch(m){throw new i.NexmoApiError(m)}}async playStream(v){try{const m=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.parentConversation.id}/events`,data:{type:"audio:play",body:v}});return new o.default(this.parentConversation,m)}catch(m){throw new i.NexmoApiError(m)}}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 o.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 o.default(this.parentConversation,v)}catch(v){throw new i.NexmoApiError(v)}}}t.default=l,e.exports=l}(rl,rl.exports)),rl.exports}var sl={exports:{}},ol={exports:{}},aT;function BI(){return aT||(aT=1,function(e,t){var r=je&&je.__importDefault||function(o){return o&&o.__esModule?o:{default:o}};Object.defineProperty(t,"__esModule",{value:!0});const n=r(Ii()),i=Ar,a=r(ia);class s extends a.default{constructor(u,c){super(u,c),this.log=i.getLogger(this.constructor.name),this.type="image",this.conversation=u,this.state={seen_by:{},delivered_to:{}},c&&c.body&&c.body.timestamp&&(this.timestamp=c.body.timestamp),Object.assign(this,c)}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(u="thumbnail",c=this.body.representations){try{return n.default._fetchImage(c[u].url,this.conversation.application.session.config.token)}catch(l){throw this.log.error(l),l}}}t.default=s,e.exports=s}(ol,ol.exports)),ol.exports}var sT;function mte(){return sT||(sT=1,function(e,t){var r=je&&je.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(t,"__esModule",{value:!0});const n=Ar,i=r(ia),a=r(Xg),s=r(BI()),o=r(Qg());class u{constructor(l,p){this.log=n.getLogger(this.constructor.name),this.application=l,this.conversation=p,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(l){return this._handleEventMap.hasOwnProperty(l.type)?this._handleEventMap[l.type].call(this,l)||new i.default(this.conversation,l):new i.default(this.conversation,l)}_processDelivered(l){let p=this.conversation.events.get(l.body.event_id);return p?(p.state=p.state||{},p.state.delivered_to=p.state.delivered_to||{},p.state.delivered_to[l.from]=l.timestamp,p):(this.log.warn("NXMEvent not found"),null)}_processDelete(l){var p;let v=this.conversation.events.get((p=l==null?void 0:l.body)===null||p===void 0?void 0:p.event_id);return v?(v.body.text&&(v.body.text=""),v.body.representations&&(v.body.representations=""),v.body.timestamp={deleted:l.timestamp},v):(this.log.warn("NXMEvent not found"),null)}_processImage(l){var p;const v=new s.default(this.conversation,l);return((p=this.conversation.me)===null||p===void 0?void 0:p.id)!==v.from&&v.delivered(),v}_processMember(l){return this.application.calls.has(this.conversation.id)&&this.application.calls.get(this.conversation.id)._handleStatusChange(l),this.conversation.members.has(l.from)&&this.conversation.members.get(l.from)._handleEvent(l),new i.default(this.conversation,l)}_processLegStatus(l){return this.conversation.members.has(l.from)&&this.conversation.members.get(l.from)._handleEvent(l),new i.default(this.conversation,l)}_processMedia(l){return this.conversation.members.has(l.from)&&this.conversation.members.get(l.from)._handleEvent(l),null}_processMuteForMedia(l){return this.conversation.media.rtcObjects[l.body.rtc_id]?l.streamIndex=this.conversation.media.rtcObjects[l.body.rtc_id].streamIndex:this.log.warn("No audio stream was found"),null}_processSeen(l){let p=this.conversation.events.get(l.body.event_id);return p?(p.state=p.state||{},p.state.seen_by=p.state.seen_by||{},p.state.seen_by[l.from]=l.timestamp,p):(this.log.warn("NXMEvent not found"),null)}_processText(l){var p,v;const m=new a.default(this.conversation,l);return((v=(p=this.conversation)===null||p===void 0?void 0:p.me)===null||v===void 0?void 0:v.id)!==m.from&&m.delivered(),m}_processMessage(l){var p,v;const m=new o.default(this.conversation,l);return((v=(p=this.conversation)===null||p===void 0?void 0:p.me)===null||v===void 0?void 0:v.id)!==m.from&&m.delivered(),m}_processSubmitted(l){let p=this.conversation.events.get(l.body.event_id);return p?(p.state=p.state||{},p.state.submitted_to=p.state.submitted_to||{},p.state.submitted_to[l.from]=l.timestamp,p):(this.log.warn("NXMEvent not found"),null)}_processRejected(l){let p=this.conversation.events.get(l.body.event_id);return p?(p.state=p.state||{},p.state.rejected_by=p.state.rejected_by||{},p.state.rejected_by[l.from]=l.timestamp,p):(this.log.warn("NXMEvent not found"),null)}_processUndeliverable(l){let p=this.conversation.events.get(l.body.event_id);return p?(p.state=p.state||{},p.state.undeliverable_to=p.state.undeliverable_to||{},p.state.undeliverable_to[l.from]=l.timestamp,p):(this.log.warn("NXMEvent not found"),null)}}t.default=u,e.exports=u}(sl,sl.exports)),sl.exports}var Wv={exports:{}};(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});class r{constructor(i={}){this.page_size=i.page_size||10,this.order=i.order||"asc",this.cursor=i.cursor||"",this.state=i.state||"",i.event_type&&(this.event_type=i.event_type)}}t.default=r,e.exports=r})(Wv,Wv.exports);var qI=Wv.exports,ul={exports:{}},Gv={exports:{}};(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r=Gn;class n{constructor(a={}){this.page_size=a.page_size,this.order=a.order,this.cursor=a.cursor,this.application=a.application,a.event_type&&a.event_type.length>0&&(this.event_type=a.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(a){return{page_size:this.page_size,order:this.order,cursor:a,...this.event_type&&{event_type:this.event_type}}}_getError(){return Promise.reject(new r.NexmoClientError("error:invalid-cursor"))}}t.default=n,e.exports=n})(Gv,Gv.exports);var td=Gv.exports,oT;function gte(){return oT||(oT=1,function(e,t){var r=je&&je.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(t,"__esModule",{value:!0});const n=r(td),i=r(ia),a=r(Xg),s=r(BI()),o=r(Qg());class u extends n.default{constructor(l){super(l),this.items=new Map,this.conversation=l.conversation,l.items.forEach(p=>{switch(p.type){case"text":this.items.set(p.id,new a.default(this.conversation,p));break;case"image":this.items.set(p.id,new s.default(this.conversation,p));break;case"message":this.items.set(p.id,new o.default(this.conversation,p));break;default:this.items.set(p.id,new i.default(this.conversation,p));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()}}t.default=u,e.exports=u}(ul,ul.exports)),ul.exports}var cl={exports:{}},uT;function yte(){return uT||(uT=1,function(e,t){var r=je&&je.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(t,"__esModule",{value:!0});const n=r(td),i=r(Yg());class a extends n.default{constructor(o){super(o),this.conversation=o.conversation,this.items=new Map,o.items.forEach(u=>{this.items.set(u.id,new i.default(this.conversation,u))})}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()}}t.default=a,e.exports=a}(cl,cl.exports)),cl.exports}var cT;function zI(){return cT||(cT=1,function(e,t){var r=je&&je.__importDefault||function(x){return x&&x.__esModule?x:{default:x}};Object.defineProperty(t,"__esModule",{value:!0});const n=Da,i=Ar,a=Gn,s=r(Yg()),o=r(ia),u=r(Xg),c=r(Qg()),l=r(vte()),p=r(mte()),v=r(Ii()),m=r(qI),b=r(gte()),T=r(yte()),I=r(rd());class R{constructor(N,j){this.log=i.getLogger(this.constructor.name),this.application=N,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 m.default(((this.application.session||{}).config||{}).events_page_config),this.events_page_last=null,this.members_page_last=null,this.conversationEventHandler=new p.default(N,this),this.media=new l.default(this),this.me=null,this._updateObjectInstance(j),n.mixin(R)}_updateObjectInstance(N){for(let j in N)switch(j){case"id":this.id=N.id;break;case"name":this.name=N.name;break;case"display_name":this.display_name=N.display_name;break;case"members":N.members.forEach(J=>{if(this.members.has(J.member_id))this.members.get(J.member_id)._normalise(J),J.user_id===this.application.me.id&&J.state!=="LEFT"&&(this.me=this.members.get(J.member_id),this.members.set(this.me.id,this.me));else{const V=new s.default(this,J);J.user_id===this.application.me.id&&J.state!=="LEFT"&&(this.me=V),this.members.set(V.id,V)}});break;case"timestamp":this.timestamp=N.timestamp;break;case"sequence_number":this.sequence_number=N.sequence_number;break;case"member_id":const X={id:N.member_id,state:N.state,user:this.application.me};if(this.members.has(N.member_id)){const J=this.members.get(N.member_id);Object.assign(J,X)}else{const J=new s.default(this,X);this.me=J,this.members.set(J.id,J)}break}}async join(N){var j,X;try{let J={state:"joined",channel:{type:"app"},user:{...!N&&{name:this.application.me.name,id:this.application.me.id},...N&&N.user_name&&{name:N.user_name},...N&&N.user_id&&{id:N.user_id}}};!((j=this===null||this===void 0?void 0:this.me)===null||j===void 0)&&j.id&&((X=this===null||this===void 0?void 0:this.me)===null||X===void 0?void 0:X.state)!=="LEFT"&&(J.from=this.me.id);const V=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.id}/members`,version:"v0.3",data:J}),D=new s.default(this,V);return V._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(J){throw new a.NexmoApiError(J)}}async del(){try{const N=await this.application.session.sendNetworkRequest({type:"DELETE",path:`conversations/${this.id}`});return this.application.conversations.delete(this.id),N}catch(N){throw new a.NexmoApiError(N)}}deleteEvent(N){return N.del()}async invite(N){var j,X;if(!N||!N.id&&!N.user_name)throw new a.NexmoClientError("error:invite:missing:params");const J={state:"invited",user:{...N.id&&{id:N.id},...N.user_name&&{name:N.user_name}},media:N.media,channel:{from:{type:"app"},to:{type:"app"},type:"app"}};!((j=this===null||this===void 0?void 0:this.me)===null||j===void 0)&&j.id&&((X=this===null||this===void 0?void 0:this.me)===null||X===void 0?void 0:X.state)!=="LEFT"&&(J.from=this.me.id);try{const V=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.id}/members`,version:"v0.3",data:J});return new s.default(this,V)}catch(V){throw new a.NexmoApiError(V)}}inviteWithAudio(N){return!N||!N.id&&!N.user_name?Promise.reject(new a.NexmoClientError("error:invite:missing:params")):(N.media={audio_settings:{enabled:!0,muted:!1,earmuffed:!1}},this.invite(N))}leave(N){return this.me.kick(N)}async sendText(N){try{if(this.me===null)throw new a.NexmoClientError("error:self");const j={type:"text",cid:this.id,from:this.me.id,body:{text:N}},{id:X,timestamp:J}=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.id}/events`,data:j});return j.id=X,j.body.timestamp=J,new u.default(this,j)}catch(j){throw new a.NexmoApiError(j)}}async sendCustomEvent({type:N,body:j}){try{if(this.me===null)throw new a.NexmoClientError("error:self");if(!N||typeof N!="string"||N.length<1)throw new a.NexmoClientError("error:custom-event:invalid");const X={type:`custom:${N}`,cid:this.id,from:this.me.id,body:j},{id:J,timestamp:V}=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.id}/events`,data:X});return X.id=J,X.timestamp=V,new o.default(this,X)}catch(X){throw new a.NexmoApiError(X)}}async sendEphemeralEvent(N){try{if(this.me===null)throw new a.NexmoClientError("error:self");const j={type:"ephemeral",cid:this.id,from:this.me.id,body:N},{id:X,timestamp:J}=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.id}/events`,data:j});return j.timestamp=J,new o.default(this,j)}catch(j){throw new a.NexmoApiError(j)}}async uploadImage(N,j={quality_ratio:"100",medium_size_ratio:"50",thumbnail_size_ratio:"30"}){const X=new FormData;X.append("file",N),X.append("quality_ratio",j.quality_ratio),X.append("medium_size_ratio",j.medium_size_ratio),X.append("thumbnail_size_ratio",j.thumbnail_size_ratio);const J=await v.default.networkRequest({type:"POST",url:this.application.session.config.ips_url,data:X,token:this.application.session.config.token});return J.upload.addEventListener("progress",V=>{V.lengthComputable&&this.log.debug("uploading image "+V.loaded+"/"+V.total)},!1),J.onreadystatechange=()=>{J.status!==200&&this.log.error(J)},J}async sendImage(N,j={quality_ratio:"100",medium_size_ratio:"50",thumbnail_size_ratio:"30"}){const X=await this.uploadImage(N,j);return X.onreadystatechange=()=>{if(X.readyState===4&&X.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(X.responseText)}}}),this.log.info(X)}catch(J){this.log.error(new a.NexmoApiError(J))}},X}abortSendImage(N){return N instanceof XMLHttpRequest?N.abort():new a.NexmoClientError("error:invalid:param:type")}async sendMessage(N){if(this.me===null)throw new a.NexmoClientError("error:self");if(!(N!=null&&N.message_type))throw new a.NexmoClientError("error:message-event:invalid");try{const j={type:"message",cid:this.id,from:this.me.id,body:{...N}},{id:X,timestamp:J}=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.id}/events`,data:j});return j.id=X,j.body.timestamp=J,new c.default(this,j)}catch(j){throw new a.NexmoApiError(j)}}async _typing(N){const j={cid:this.id,from:this.me.id};try{return await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.id}/events`,data:j}),`text:typing:${N}:success`}catch(X){throw new a.NexmoApiError(X)}}startTyping(){return this._typing("on")}stopTyping(){return this._typing("off")}async getEvents(N={}){const j=`${this.application.session.config.nexmo_api_url}/beta2/conversations/${this.id}/events`;let X=Object.keys(N).length===0?this.pageConfig:new m.default(N);try{const J=await v.default.paginationRequest(j,X,this.application.session.config.token);J.application=this.application,J.conversation=this;const V=new b.default(J);return this.events_page_last=V,V}catch(J){throw new a.NexmoApiError(J)}}async getMembers(N={}){const j=`${this.application.session.config.nexmo_api_url}/beta2/conversations/${this.id}/members`;let X=Object.keys(N).length===0?this.pageConfig:new m.default(N);try{const J=await v.default.paginationRequest(j,X,this.application.session.config.token);J.application=this.application,J.conversation=this;const V=new T.default(J);return this.members_page_last=V,V}catch(J){throw new a.NexmoApiError(J)}}async getMyMember(){try{const N=await this.application.session.sendNetworkRequest({type:"GET",path:`conversations/${this.id}/members/me`,version:"v0.3"});return new s.default(this,N)}catch(N){throw new a.NexmoApiError(N)}}async getMember(N){try{const j=await this.application.session.sendNetworkRequest({type:"GET",path:`conversations/${this.id}/members/${N}`,version:"v0.3"});return new s.default(this,j)}catch(j){throw new a.NexmoApiError(j)}}_handleEvent(N){var j,X;if(N.type.startsWith("rtc"))return this.emit(N.type,N),Promise.resolve(N);this.sequence_number++,N.body&&N.body.event_id&&typeof N.body.event_id=="string"&&(N.body.event_id=parseInt(N.body.event_id));let J={memberId:N.from};if(!((j=N==null?void 0:N.body)===null||j===void 0)&&j.user){const{id:D,name:te,display_name:ue,image_url:ee,custom_data:ge}=N.body.user;J={...J,...D&&{userId:D},...te&&{userName:te},...ue&&{displayName:ue},...ee&&{imageUrl:ee},...ge&&{customData:ge}}}else if(!((X=N==null?void 0:N._embedded)===null||X===void 0)&&X.from_user){const{id:D,name:te,display_name:ue,image_url:ee,custom_data:ge}=N._embedded.from_user;J={...J,...D&&{userId:D},...te&&{userName:te},...ue&&{displayName:ue},...ee&&{imageUrl:ee},...ge&&{customData:ge}}}let V=this.conversationEventHandler.handleEvent(N);return["text:typing:on","text:typing:off","ephemeral"].includes(N.type)||this.events.set(V.id,V),N.type.startsWith("custom:")?(this.emit(V.type,J,V),Promise.resolve(N)):(this.emit(N.type,J,V),Promise.resolve(N))}}t.default=R,e.exports=R}(Zc,Zc.exports)),Zc.exports}var ll={exports:{}},lT;function WI(){return lT||(lT=1,function(e,t){var r=je&&je.__importDefault||function(u){return u&&u.__esModule?u:{default:u}};Object.defineProperty(t,"__esModule",{value:!0});const n=Da,i=Ar,a=Gn,s=r(ed());class o{constructor(c,l,p){this.application=c,this.log=i.getLogger(this.constructor.name),this.from=p,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(l),n.mixin(o)}_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",(c,l)=>{this.application.calls&&this.application.calls.has(this.conversation.id)&&this.application.calls.get(this.conversation.id)._handleStatusChange(l)})}catch(c){this.log.error("_attachCallListeners_error: ",{e:c})}}_isValidStatusTransition(c){if(!c)throw new a.NexmoClientError(`Provide the status to validate the transition from '${this.status}'`);if(!this.status)return!0;const l=this.status.toUpperCase();return!this.STATUS_PERMITTED_FLOW.has(l)||this.status===c?!1:this.STATUS_PERMITTED_FLOW.get(l).has(c)}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 c of this.conversation.members.values())if(c.state!=="LEFT"&&this.conversation.me.user.id!==c.user.id)return Promise.resolve();return this.hangUp()}_setupConversationObject(c,l){c&&(this.conversation=c,c.me?(this.to=new Map(c.members),this.from&&this.to.delete(this.from.id)):this.log.warn("missing own member object"),this._attachCallListeners())}_setFrom(c){this.from=c}_setOffer(c){this.offer=c}_handleStatusChange(c){var l;const p=this.conversation?((l=this.conversation.me)===null||l===void 0?void 0:l.id)===c.from:!0,v=this.direction===this.CALL_DIRECTION.OUTBOUND;this.log.debug("_handleStatusChange: ",{event:c},`_isEventFromMe: ${p} _isOutbound: ${v}`);let m=new Map;if(m.set("member:joined",async()=>{if(c.body.channel&&c.body.channel.id)try{this._setStatusAndEmit(this.CALL_STATUS.STARTED);return}catch(b){throw this._setStatusAndEmit(this.CALL_STATUS.FAILED),this.log.error(b),b}return Promise.resolve()}),m.set("member:invited",()=>(c.body.invited_by===null&&c.body.user.media&&c.body.user.media.audio_settings&&this._setStatusAndEmit(this.CALL_STATUS.STARTED),Promise.resolve())),m.set("rtc:hangup",()=>this.status===this.CALL_STATUS.ANSWERED?(this._setStatusAndEmit(this.CALL_STATUS.COMPLETED),Promise.resolve()):p&&v||!p&&!v?(this._setStatusAndEmit(this.CALL_STATUS.UNANSWERED),Promise.resolve()):(this._setStatusAndEmit(this.CALL_STATUS.REJECTED),Promise.resolve())),m.set("member:left",()=>{if(!c.body.timestamp.hasOwnProperty("joined")&&this.status!==this.CALL_STATUS.ANSWERED)return p&&v||!p&&!v?(this._setStatusAndEmit(this.CALL_STATUS.UNANSWERED),Promise.resolve()):(this._setStatusAndEmit(this.CALL_STATUS.REJECTED),Promise.resolve())}),m.set("member:media",()=>(this.status!==this.CALL_STATUS.ANSWERED&&c.body.audio&&(p&&c.body.channel&&(this.id=c.body.channel.id),(!p||!v)&&this.id&&this._setStatusAndEmit(this.CALL_STATUS.ANSWERED)),Promise.resolve())),m.set("sip:ringing",()=>(this.status!==this.CALL_STATUS.RINGING&&this._setStatusAndEmit(this.CALL_STATUS.RINGING),Promise.resolve())),m.set("sip:hangup",()=>{switch(c.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()}),m.set("knocking:delete:success",()=>(this._setStatusAndEmit(this.CALL_STATUS.UNANSWERED),Promise.resolve())),m.has(c.type))return m.get(c.type).call(this)}_setStatusAndEmit(c){this._isValidStatusTransition(c)&&(this.status=c,this.log.debug(`_setStatusAndEmit: ${c}`,{nxmCall:this}),this.application.emit("call:status:changed",this))}async answer(c=!0){if(this.log.debug(`answer: { autoPlayAudio: ${c}`),this.conversation)try{await this.conversation.join();const l=await this.conversation.media.enable({autoPlayAudio:c,offer:this.offer});return this.offer=void 0,l}catch(l){throw this._setStatusAndEmit(this.CALL_STATUS.FAILED),this.log.error(l),l}else throw new a.NexmoClientError("error:call:answer")}async createCall(c,l=!0){if(this.log.debug(`createCall: { usernames: ${c}, autoPlayAudio: ${l} }`),!c||!Array.isArray(c)||c.length===0)return Promise.reject(new a.NexmoClientError("error:application:call:params"));try{const p=await this.application.newConversationAndJoin({display_name:"CALL_"+this.application.me.name+"_"+c.join("_").replace(" ","")});p.members.set(p.me.id,p.me),this.from=p.me,this.successful_invited_members=new Map;const v=c.map(async b=>{try{const T=await p.inviteWithAudio({user_name:b});return p.members.set(T.id,T),this.successful_invited_members.set(T.id,T),T}catch(T){return this.log.error(T),T}}),m=async()=>{if(this.successful_invited_members.size>0)return await p.media.enable({audio:{muted:!1,earmuffed:!1},autoPlayAudio:l}),this.application.calls.set(p.id,this),v;throw v};return await Promise.all(v),this._setupConversationObject(p),await m()}catch(p){throw this.log.error(p),this._setStatusAndEmit(this.CALL_STATUS.FAILED),p}}async createServerCall(c,l,p){this.log.debug(`createServerCall: { user: ${c}, type: ${l}, custom_data: `,{custom_data:p});const v={type:l};l==="phone"?v.number=c:v.user=c;try{const{stream:m,legId:b,rtcObjects:T}=await s.default.prewarmLeg(this);this.log.debug("createServerCall: ",{stream:m},{legId:b},{rtcObjects:T}),this.rtcObjects=T,this.stream=m,this.id=b,this.application._call_draft_list.set(b,this),s.default.playAudioStream(m);const I={type:"POST",path:"knocking",data:{channel:{type:"app",from:{type:"app"},to:v,id:b||null},...p&&Object.keys(p).length&&{properties:{custom_data:p}}}};try{const R=await this.application.session.sendNetworkRequest(I);this.knocking_id=R.id}catch(R){throw new a.NexmoApiError(R)}return s.default.cleanCallMediaIfFailed(this),m}catch(m){throw s.default.cleanMediaProperties(this),m}}async hangUp(c){if(this.log.debug(`hangUp: { reason: ${c} }`),this.conversation&&await this.conversation.media.disable(),!this.knocking_id&&this.conversation)return this.conversation.leave(c).catch(l=>{if(l.type!=="conversation:error:invalid-member-state")return Promise.reject(l)});{let l=`knocking/${this.knocking_id}`;if(c){let p=new URLSearchParams;Object.keys(c).forEach(v=>{p.append(v,c[v])}),l+=`?${p.toString()}`}try{const p=await this.application.session.sendNetworkRequest({type:"DELETE",path:l});return this.application._call_draft_list.get(this.client_ref)._handleStatusChange(p),this.application._call_draft_list.delete(this.client_ref),p}catch(p){if(this.conversation)return this.log.error(new a.NexmoApiError(p)),this.conversation.leave(c).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",p);return}}}reject(c){return this.log.debug(`reject: { reason: ${c} }`),this.conversation?this.conversation.leave(c):Promise.reject(new a.NexmoClientError("error:call:reject"))}}t.default=o,e.exports=o}(ll,ll.exports)),ll.exports}var Hv={exports:{}};(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r=Ar;class n{constructor(a){this.log=r.getLogger(this.constructor.name),this.application=a,this._handleSipCallEventMap={"sip:hangup":this._processSipHangup,"sip:ringing":this._processSipRinging}}_handleSipCallEvent(a){if(this.log.debug("_handleSipCallEvent: ",{event:a}),!this.application.calls.has(a.cid)){this.log.warn("There is no call object for this Conversation id.");return}const s=this.application.calls.get(a.cid);if(this._handleSipCallEventMap.hasOwnProperty(a.type))return this._handleSipCallEventMap[a.type].call(this,s,a)}_processSipHangup(a,s){this.log.debug("_processSipHangup: ",s),a._handleStatusChange(s)}_processSipRinging(a,s){this.log.debug("_processSipRinging: ",s),a._handleStatusChange(s)}}t.default=n,e.exports=n})(Hv,Hv.exports);var bte=Hv.exports,Vv={exports:{}};(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r=Ar;class n{constructor(a){this.log=r.getLogger(this.constructor.name),this.application=a,this._handleRtcEventMap={"rtc:transfer":this._processRtcTransfer,"rtc:answer":this._processRtcAnswer,"rtc:hangup":this._processRtcHangup}}_handleRtcEvent(a){if(this._handleRtcEventMap.hasOwnProperty(a.type))return this._handleRtcEventMap[a.type].call(this,a)}_processRtcTransfer(a){this.log.debug("_processRtcTransfer: ",{event:a});const s=this.application.conversations.get(a.body.transferred_from),o=this.application.conversations.get(a.cid),u=this.application.calls.get(a.body.transferred_from);if(!u){this.log.warn("NXMCall transfer for unknown nxmCall");return}u.conversation.members.get(a.body.was_member).transferred_to=o,u._setupConversationObject(o),u.transferred=!0,this.application.calls.set(a.cid,u),this.application.calls.delete(a.body.transferred_from),s&&(o.members.get(a.from).transferred_from=s,o.media._attachEndingEventHandlers(),Object.entries(o.media.rtcObjects).length===0&&Object.entries(s.media.rtcObjects).length!==0&&Object.assign(o.media.rtcObjects,s.media.rtcObjects),!o.media.pc&&s.media.pc&&Object.assign(o.media.pc=s.media.pc),o.application.activeStreams.length===0&&s.application.activeStreams.length>0&&(o.application.activeStreams=s.application.activeStreams))}_processRtcAnswer(a){this.log.debug("_processRtcAnswer: ",{event:a}),this.application.calls.has(a.cid)&&(this.application.calls.get(a.cid).id=a.body.rtc_id)}_processRtcHangup(a){this.log.debug("_processRtcHangup: ",{event:a}),this.application.calls.has(a.cid)&&this.application.calls.get(a.cid)._handleStatusChange(a)}}t.default=n,e.exports=n})(Vv,Vv.exports);var _te=Vv.exports,fl={exports:{}},fT;function wte(){return fT||(fT=1,function(e,t){var r=je&&je.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(t,"__esModule",{value:!0});const n=Ar,i=r(ia),a=r(WI()),s=r(Ii()),o=r(ed());class u{constructor(l){this.log=n.getLogger(this.constructor.name),this.application=l,this._handleApplicationEventMap={"member:joined":this._processMemberJoined,"member:invited":this._processMemberInvited}}handleEvent(l){const p=this.application.conversations.get(l.cid),v=Object.assign({},l);return this._handleApplicationEventMap.hasOwnProperty(l.type)?this._handleApplicationEventMap[l.type].call(this,p,new i.default(p,v),l):new i.default(p,v)}_processMemberJoined(l,p,v){try{if(p.body.channel&&this.application._call_draft_list.has(p.body.channel.id)){this.log.debug("_processMemberJoined: outbound serverCall from sdk",{event:p});const m=this.application._call_draft_list.get(p.body.channel.id);let b=((m.rtcObjects||{})[p.body.channel.id]||{}).pc;if(m._setFrom(l.me),m._setupConversationObject(l,p.body.channel.id),l.media._attachEndingEventHandlers(),Object.entries(l.media.rtcObjects).length===0&&Object.entries(m.rtcObjects).length!==0&&Object.assign(l.media.rtcObjects,m.rtcObjects),!l.media.pc&&b&&Object.assign(l.media.pc=b),l.application.activeStreams.length===0&&m.application.activeStreams.length>0&&(l.application.activeStreams=m.application.activeStreams),delete m.client_ref,delete m.knocking_id,m.rtcStats&&(l.media.rtcStats=m.rtcStats),this.application._call_draft_list.delete(p.body.channel.id),this.application.calls.set(l.id,m),m._handleStatusChange(p),this.log.debug("_processMemberJoined: processedCall ",{nxmCall:m}),l.members&&p.body.member_id){const T=l.members.get(p.body.member_id);T&&this.application.emit("member:call",T,m)}setTimeout(()=>{l!=null&&l.me&&o.default.emitMediaStream(l.me,b,m.stream)},200)}return this.log.debug("_processMemberJoined: default member joined: ",{event:p}),p}catch(m){this.log.error("_processMemberJoined: ",{e:m})}}_processMemberInvited(l,p){var v,m,b,T,I,R;try{if(!l)return this.log.warn(`no conversation object for ${p.type}`),p;if(((v=l.me)===null||v===void 0?void 0:v.user.id)===p.body.invited_by||!(!((b=(m=p.body.user.media)===null||m===void 0?void 0:m.audio_settings)===null||b===void 0)&&b.enabled))return p;const x=s.default.getMemberNumberFromEventOrNull(p.body.channel)||s.default.getMemberFromNameOrNull(l,p.body.invited_by)||"unknown",N=new a.default(this.application,l,x);return this.application.calls.set(l.id,N),!((T=p.body)===null||T===void 0)&&T.sdp&&this.application.session.config.enableInboundOffer&&N._setOffer({sdp:p.body.sdp,leg_id:p.body.channel.id}),!((I=l.display_name)===null||I===void 0)&&I.startsWith("CALL_")||N._handleStatusChange(p),this.application.emit("member:call",this.application.conversations.get(p.cid).members.get((R=p.body)===null||R===void 0?void 0:R.member_id),N),p}catch(x){this.log.error("_processMemberInvited: ",{e:x})}}}t.default=u,e.exports=u}(fl,fl.exports)),fl.exports}var Kv={exports:{}};(function(e,t){var r=je&&je.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(t,"__esModule",{value:!0});const n=r(td);class i extends n.default{constructor(s){super(s),this.items=new Map,s.items.forEach(o=>{const u=this.application.updateOrCreateConversation(o);this.items.set(u.id,u)})}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()}}t.default=i,e.exports=i})(Kv,Kv.exports);var Ste=Kv.exports,Jv={exports:{}},Yv={exports:{}};(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r=Da;class n{constructor(a,s){var o,u;this.application=a,this.id=(o=s==null?void 0:s.id)!==null&&o!==void 0?o:null,this._embedded=(u=s==null?void 0:s._embedded)!==null&&u!==void 0?u:null,r.mixin(n)}}t.default=n,e.exports=n})(Yv,Yv.exports);var Tte=Yv.exports;(function(e,t){var r=je&&je.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(t,"__esModule",{value:!0});const n=r(td),i=r(Tte);class a extends n.default{constructor(o){super(o),this.items=new Map,o.items.forEach(u=>{this.items.set(u.id,new i.default(this.application,u))})}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()}}t.default=a,e.exports=a})(Jv,Jv.exports);var Cte=Jv.exports,dl={exports:{}},dT;function Ete(){return dT||(dT=1,function(e,t){var r=je&&je.__importDefault||function(u){return u&&u.__esModule?u:{default:u}};Object.defineProperty(t,"__esModule",{value:!0}),t.ConversationEventsProcessor=t.EventsQueue=void 0;const n=Gn,i=r(Ii()),a=Ar;class s{constructor(c){this.callback=c,this.cidMap=new Map,this.log=a.getLogger(this.constructor.name)}async enqueue(c,l){var p,v,m,b,T,I,R,x;const{cid:N,id:j}=c,X=Number(j);if(!N||isNaN(X))return this.callback(c);if(((v=(p=l.conversations.get(N))===null||p===void 0?void 0:p.me)===null||v===void 0?void 0:v.state)==="LEFT")return this.callback(c);if(!this.cidMap.get(N)){this.log.debug(`enqueue: create new ConversationEventsProcessor for ${N}`);const V=new o(N,X-1,l);if(this.cidMap.set(N,V),c.type=="member:media"&&(!((b=(m=c.body)===null||m===void 0?void 0:m.media)===null||b===void 0)&&b.audio)||c.type=="member:joined"&&(!((I=(T=c.body)===null||T===void 0?void 0:T.channel)===null||I===void 0)&&I.id)&&((x=(R=c.body)===null||R===void 0?void 0:R.channel)===null||x===void 0?void 0:x.knocking_id)===void 0){V.processing=!0,V.lastEventIdProcessed=0;try{await new Promise(ee=>setTimeout(ee,V.eventRequestWaitTime));const D=ee=>{var ge;return(ge=ee.find(L=>(L==null?void 0:L.type)==="rtc:transfer"&&(L==null?void 0:L.from)===c.from))===null||ge===void 0?void 0:ge.id};let te=[Array.from(Array(5).keys()).map(ee=>X+1+ee),Array.from(Array(5).keys()).map(ee=>X-1-ee)].flatMap(ee=>ee).map(ee=>V.eventsMap.get(ee)).filter(ee=>ee),ue;if((ue=D(te))===void 0){const ee=Math.max(X-20,1);te=await V.fetchConversationEvents(ee,20)}(ue=D(te))!==void 0&&(ue=Number(ue),V.lastEventIdProcessed=Math.max(ue-1,0),te.slice(ue).forEach(ee=>V.enqueue(Number(ee.id),ee)))}finally{V.processing=!1}}}const J=this.cidMap.get(N);J.enqueue(X,c),J.processing||(J.processing=!0,await J.processEvents())}}t.EventsQueue=s;class o{constructor(c,l,p){this.cid=c,this.eventsMap=new Map,this.callback=v=>p._handleEvent(v),this.lastEventIdProcessed=l,this.largestEventIdInQueue=l,this.processing=!1,this.application=p,this.eventsFetchRange=9,this.eventRequestWaitTime=p.session.config.eventQueueWaitTime,this.log=a.getLogger(this.constructor.name)}enqueue(c,l){return c>this.largestEventIdInQueue&&(this.largestEventIdInQueue=c),c>this.lastEventIdProcessed&&this.eventsMap.set(c,l),l}dequeue(c){const l=this.eventsMap.get(c);return this.eventsMap.delete(c),l}async processEvents(){const c=()=>(this.eventsMap.clear(),this.log.debug("processEvents: Done Processing"),this.processing=!1);if(this.eventsMap.size<1)return c();const l=this.lastEventIdProcessed+1,p=await this.processNextEvent(l,1);return p?(this.lastEventIdProcessed=Number(p.id),this.processEvents()):c()}async processNextEvent(c,l){this.log.debug(`processNextEvent: processing event number ${c}`);const p=this.dequeue(c);try{if(p)return await this.callback(p),p;if(l>0)return await new Promise(v=>setTimeout(v,this.eventRequestWaitTime)),this.processNextEvent(c,l-1);if(this.largestEventIdInQueue>c){this.log.debug(`processNextEvent: largestEventIdInQueue-${this.largestEventIdInQueue} > eventId-${c}`);const v=await this.fetchEventsAndProcess(c);return v?(this.log.debug("processNextEvent: foundEvent ",{foundEvent:v}),await this.callback(v),v):(this.log.debug(`processNextEvent: not found process next ${c+1}`),this.processNextEvent(c+1,l))}return}catch{return}}async fetchEventsAndProcess(c){try{const l=await this.fetchConversationEvents(c,this.eventsFetchRange);this.log.debug("fetchEventsAndProcess: fetched events list ",{eventsList:l});let p;return l.forEach(v=>{v.cid=this.cid;const m=Number(v.id);isNaN(m)||m<c||(m>c?(this.log.debug(`fetchEventsAndProcess: event > missingEvent ${m} `,{missingEvent:c}),this.enqueue(m,v)):(this.log.debug("fetchEventsAndProcess: foundEvent ",{event:v}),p=v))}),p}catch(l){this.log.debug("fetchEventsAndProcess: error ",{e:l});return}}async fetchConversationEvents(c,l){this.log.debug("fetchConversationEvents: ",this.cid,c);const p=this.largestEventIdInQueue>c?this.largestEventIdInQueue+l:c+l,v=`${this.application.session.config.nexmo_api_url}/beta2/conversations/${this.cid}/events`;try{return(await i.default.paginationRequest(v,{start_id:c,end_id:p},this.application.session.config.token)).items}catch(m){throw new n.NexmoApiError(m)}}}t.ConversationEventsProcessor=o,e.exports={EventsQueue:s,ConversationEventsProcessor:o}}(dl,dl.exports)),dl.exports}var pT;function rd(){return pT||(pT=1,function(e,t){var r=je&&je.__importDefault||function(J){return J&&J.__esModule?J:{default:J}};Object.defineProperty(t,"__esModule",{value:!0});const n=Da,i=Ar,a=Gn,s=r(X$),o=r(zI()),u=r(WI()),c=r(bte),l=r(_te),p=r(wte()),v=r(Ii()),m=r(qI),b=r(Ste),T=r(Cte),I=Ete(),R=r(Yg());let x=null,N=null,j=null;class X{constructor(V,D){this.log=i.getLogger(this.constructor.name),this.session=V,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 m.default((V.config||{}).conversations_page_config),this.conversations_page_last=null,this.activeStreams=[],x=new c.default(this),N=new l.default(this),j=new p.default(this),this.me=null,Object.assign(this,D),n.mixin(X)}updateOrCreateConversation(V){const D=this.conversations.get(V.id);return D?(D._updateObjectInstance(V),this.conversations.set(V.id,D)):this.conversations.set(V.id,new o.default(this,V)),this.conversations.get(V.id)}async _enqueueEvent(V){this.session.config.enableEventsQueue?(this.eventsQueue||(this.eventsQueue=new I.EventsQueue(D=>this._handleEvent(D))),this.eventsQueue.enqueue(V,this)):this._handleEvent(V)}async _handleEvent(V){var D,te,ue,ee,ge,L,pe;const Te=!((D=V._embedded)===null||D===void 0)&&D.from_user?((ue=(te=V._embedded)===null||te===void 0?void 0:te.from_user)===null||ue===void 0?void 0:ue.id)===((ee=this.me)===null||ee===void 0?void 0:ee.id):((L=(ge=V.body)===null||ge===void 0?void 0:ge.user)===null||L===void 0?void 0:L.user_id)===((pe=this.me)===null||pe===void 0?void 0:pe.id),rt=v.default._checkIfUserIsReInvited(this.conversations,V);if(V.type.startsWith("sip"))return x._handleSipCallEvent(V),V;if(this.conversations.has(V.cid)&&V.type!=="rtc:transfer"&&!rt)return V.type.startsWith("rtc")&&N._handleRtcEvent(V),this.conversations.get(V.cid)._handleEvent(V),(V.type==="member:joined"||V.type==="member:invited")&&Te&&this._handleApplicationEvent(V),V;if(V.cid)try{rt&&this.conversations.delete(V.cid);let Ke;return v.default._isCallEvent(V)?Ke=await this.getConversation(V.cid,X.CONVERSATION_API_VERSION.v1):Ke=await this.getConversation(V.cid,X.CONVERSATION_API_VERSION.v3),this.conversations.set(V.cid,Ke),await Ke._handleEvent(V),await this._handleApplicationEvent(V),V.type.startsWith("rtc")&&N._handleRtcEvent(V),Promise.resolve(V)}catch(Ke){return this.log.error(Ke),Promise.reject(Ke)}}async updateToken(V){if(this.session.connection&&this.session.connection.disconnected)return this.session.config.token=V,this.session.connection.io.opts.query.token=V,Promise.resolve();const D={url:`${this.session.config.nexmo_api_url}/v0.2/sessions/${this.session.session_id}`,type:"PUT",token:V};try{await v.default.networkRequest(D),this.me&&(this.session.config.token=V,this.session.connection.io.opts.query.token=V)}catch(te){throw new a.NexmoApiError(te)}}async _handleApplicationEvent(V){try{this.log.debug("_handleApplicationEvent: ",{event:V});const D=j.handleEvent(V),te=this.conversations.get(V.cid);let ue;if(te.members.has((D||{}).from))ue=te.members.get(D.from);else if(V.type==="member:joined"||V.type==="member:invited"){const ee={...V.body,...V.from&&{member_id:V.from}};ue=new R.default(te,ee)}else try{ue=await te.getMember(D.from)}catch(ee){this.log.warn(`There is an error getting the member ${ee}`)}return this.emit(D.type,ue,D),V}catch(D){throw this.log.error("_handleApplicationEvent: ",D),D}}async inAppCall(V){if(!V||!Array.isArray(V)||V.length===0)return Promise.reject(new a.NexmoClientError("error:application:call:params"));try{const D=new u.default(this);return await D.createCall(V),D.direction=D.CALL_DIRECTION.OUTBOUND,D}catch(D){throw D}}async callServer(V,D="phone",te={}){try{const ue=new u.default(this);return ue.direction=ue.CALL_DIRECTION.OUTBOUND,await ue.createServerCall(V,D,te),ue}catch(ue){throw ue}}async reconnectCall(V,D,te={}){try{if(!V||!D)throw new a.NexmoClientError("error:missing:params");const ue=await this.getConversation(V,X.CONVERSATION_API_VERSION.v1);await ue.media.enable({...te,reconnectRtcId:D});const ee=new u.default(this,ue),ge=Array.from(ue.events.values()).map(L=>L.type);return ge.includes("sip:answered")?ee.status=ee.CALL_STATUS.ANSWERED:ge.includes("sip:ringing")?ee.status=ee.CALL_STATUS.RINGING:ee.status=ee.CALL_STATUS.STARTED,ee.rtcObjects=ue.media.rtcObjects,this.calls.set(ue.id,ee),ee}catch(ue){throw ue}}async newConversation(V={}){try{const D=await this.session.sendNetworkRequest({type:"POST",path:"conversations",data:V}),te=new o.default(this,D);return this.conversations.set(te.id,te),this.getConversation(te.id,X.CONVERSATION_API_VERSION.v1)}catch(D){throw new a.NexmoApiError(D)}}async newConversationAndJoin(V){const D=await this.newConversation(V);return await D.join(),D}async getConversation(V,D=X.CONVERSATION_API_VERSION.v3){if(D!==X.CONVERSATION_API_VERSION.v1&&D!==X.CONVERSATION_API_VERSION.v3)throw new a.NexmoClientError("error:conversation-service:version");let te;if(D===X.CONVERSATION_API_VERSION.v1)try{te=await this.session.sendNetworkRequest({type:"GET",path:`conversations/${V}`}),te.id=te.uuid,delete te.uuid}catch(ee){throw new a.NexmoApiError(ee)}else try{te=await this.session.sendNetworkRequest({type:"GET",path:`conversations/${V}`,version:"v0.3"})}catch(ee){throw new a.NexmoApiError(ee)}const ue=this.updateOrCreateConversation(te);if(D===X.CONVERSATION_API_VERSION.v3&&!ue.me)try{const ee=await ue.getMyMember();ue.me=ee,ue.members.set(ee.id,ee)}catch{try{const ge=await ue.getMyMember();ue.me=ge,ue.members.set(ge.id,ge)}catch{this.log.warn(`You don't have any membership in ${ue.id}`)}}if(this.session.config.sync==="full"){const{items:ee}=await ue.getEvents();return ue.events=ee,ue}else return ue}async getConversations(V={}){const D=`${this.session.config.nexmo_api_url}/beta2/users/${this.me.id}/conversations`;let te=Object.keys(V).length===0?this.pageConfig:new m.default(V);try{const ue=await v.default.paginationRequest(D,te,this.session.config.token);ue.application=this;const ee=new b.default(ue);return this.conversations_page_last=ee,ee}catch(ue){throw new a.NexmoApiError(ue)}}syncConversations(V){const D=Array.from(V.values()),te=D.length,ue=new Date;this.start_sync_time=typeof window<"u"&&window.performance?window.performance.now():ue.getTime();const ee=async()=>{this.synced_conversations_percentage=Number((this.synced_conversations_count/te*100).toFixed(2));const ge={sync_progress:this.synced_conversations_percentage};if(this.emit("sync:progress",ge),this.log.info("Loading sync progress: "+this.synced_conversations_count+"/"+te+" - "+this.synced_conversations_percentage+"%"),this.synced_conversations_percentage>=100){const L=new Date;this.stop_sync_time=typeof window<"u"&&window.performance?window.performance.now():L.getTime(),this.log.info("Loaded conversations in "+(this.stop_sync_time-this.start_sync_time)+"ms")}this.synced_conversations_count<te&&(await this.getConversation(D[this.synced_conversations_count].id),ee(),this.synced_conversations_count++,this.sync_progress_buffer++)};ee()}async getUser(V=this.me.id){try{const D=await this.session.sendNetworkRequest({type:"GET",path:`users/${V}`});return new s.default(this,D)}catch(D){throw new a.NexmoApiError(D)}}async getUserSessions(V={}){var D;const te=((D=V)===null||D===void 0?void 0:D.user_id)||this.me.id,ue=`${this.session.config.nexmo_api_url}/v0.3/users/${te}/sessions`;let ee=Object.keys(V).length===0?this.pageConfig:new m.default(V);try{const ge=await v.default.paginationRequest(ue,ee,this.session.config.token,X.CONVERSATION_API_VERSION.v3);ge.application=this;const L=new T.default(ge);return this.user_sessions_page_last=L,L}catch(ge){throw new a.NexmoApiError(ge)}}}t.default=X,X.CONVERSATION_API_VERSION={v1:"v0.1",v3:"v0.3"},e.exports=X}(Qc,Qc.exports)),Qc.exports}var hT;function Ii(){return hT||(hT=1,function(e,t){var r=je&&je.__importDefault||function(p){return p&&p.__esModule?p:{default:p}};Object.defineProperty(t,"__esModule",{value:!0});const n=r(jee),i=r(G$),a=r(rd()),s=4e4,o=2e4,u=new RegExp(`"|'|<|>|&|\\|/`),c=new RegExp(`"|'|<|>|\\|javascript:`);class l{static getMemberFromNameOrNull(v,m){if(!v||!m)return null;for(let b of v.members.values())if(b.user.name===m)return b;return null}static getMemberNumberFromEventOrNull(v){const m=v&&v.from;return m&&(m.number||m.uri)?m.number||m.uri:null}static isSanitizedInput(v){return!u.test(v)}static isSanitizedUrlInput(v){return!c.test(v)}static checkIsSanitized([v,m]){if(m==null)return!0;switch(typeof m){case"string":return v.includes("url")||v.includes("uri")?l.isSanitizedUrlInput(m):l.isSanitizedInput(m);case"object":return Array.isArray(m)?m.every(b=>l.checkIsSanitized(["dummy",b])):Object.entries(m).every(l.checkIsSanitized);default:return!0}}static networkRequest(v){return new Promise((m,b)=>{!v.token&&!v.url.includes("logging")&&!v.url.includes("ping")&&b({response:{type:"error:user:token",description:"network error on request. Please create a new session."}});const T=new XMLHttpRequest;let I;T.open(v.type,v.url,!0),v.token&&T.setRequestHeader("Authorization","Bearer "+v.token),v&&v.url.includes("image")?(T.responseType="",I=v.data,T.onloadstart=()=>{m(T)}):(T.responseType=v.responseType||"json",I=v.data?JSON.stringify(v.data):null,T.setRequestHeader("Content-type","application/json; charset=utf-8")),T.onload=()=>{T.status===200||T.status===201||T.status===204?m(T):b(T)},T.onerror=R=>{b(R)},T.send(I)})}static async paginationRequest(v,m,b,T=a.default.CONVERSATION_API_VERSION.v1){try{const I=await l.networkRequest({type:"GET",url:l.addUrlSearchParams(v,m),token:b}),{page_size:R,_embedded:x,_links:N}=I.response,j=v.split("/").pop().trim();return{items:T===a.default.CONVERSATION_API_VERSION.v1?x.data[j]:x[j],cursor:{prev:N.prev?new URLSearchParams(N.prev.href).get("cursor"):"",next:N.next?new URLSearchParams(N.next.href).get("cursor"):"",self:N.self?new URLSearchParams(N.self.href).get("cursor"):""},page_size:R,order:m.order||"asc",event_type:m.event_type||null}}catch({response:I}){const R=I||{type:"error:network:get-request",description:"network error on nexmo get request"};throw R.validation&&(R.description=R.validation[Object.keys(R.validation)[0]]),R}}static addUrlSearchParams(v,m={}){let b=new URL(v);return Object.keys(m).forEach(T=>{m[T]&&!(typeof m[T]=="string"&&m[T].length<1)&&m[T]!==null&&b.searchParams.set(T,m[T])}),b.href}static deepMergeObj(v,m){const b=JSON.parse(JSON.stringify(v));for(let T in m)Object.prototype.toString.call(m[T])==="[object Object]"?b[T]=l.deepMergeObj(b[T],m[T]):b[T]=m[T];return b}static injectScript(v,m){if(typeof document<"u"){let b=document.getElementsByTagName("head")[0],T=document.createElement("script");T.async=!0,T.src=v,T.onload=T.onreadystatechange=()=>{(!T.readyState||/loaded|complete/.test(T.readyState))&&(T.onload=T.onreadystatechange=null,T=null,m&&m())},b.insertBefore(T,b.firstChild)}}static allocateUUID(){return n.default.v4()}static validateDTMF(v){return typeof v=="string"?/^[\da-dA-D#*pP]{1,45}$$/.test(v):!1}static _getBugsnagKey(){return"76498fc1ca8d9b0a173a44e2b873d7ed"}static updateMemberLegs(v,m){if(v){const b=v.find(T=>T.leg_id===m.body.leg_id);if(!b)v.push({leg_id:m.body.leg_id,status:m.body.status});else if(b.status!==m.body.status){let T=v.indexOf(b);v.fill(b.status=m.body.status,T,T++)}}else v=[{leg_id:m.body.leg_id,status:m.body.status}];return v}static _isCallEvent(v){const{channel:m,media:b}=v.body;return!!(v.type==="rtc:transfer"||m&&(b&&b.audio_settings&&b.audio_settings.enabled||b&&b.audio&&b.audio.enabled||m.knocking_id))}static async _fetchImage(v,m){const{response:b}=await l.networkRequest({type:"GET",url:v,responseType:"arraybuffer",token:m}),T=new Uint8Array(b);let I="";const R=8*1024;let x;for(x=0;x<T.length/R;x++)I+=String.fromCharCode.apply(null,T.subarray(x*R,(x+1)*R));return I+=String.fromCharCode.apply(null,T.subarray(x*R)),"data:image/jpeg;base64,"+btoa(I)}static async _checkHttpConnectivity(v){const m=Date.now();try{await l.networkRequest({type:"GET",url:v});const b=Date.now()-m;return{url:v,canConnect:!0,connectionTime:b}}catch(b){return{url:v,canConnect:!1,error:b}}}static _checkWsConnectivity(v,m,b){return new Promise((T,I)=>{const R=Object.assign({path:m},b),x=Date.now(),N=i.default.connect(v,R),j=setTimeout(()=>T({url:v,canConnect:!1}),o);N.on("connect",()=>{const X=Date.now()-x;N.disconnect(),clearTimeout(j),T({url:v,canConnect:!0,connectionTime:X})}),N.on("error",X=>{N.disconnect(),clearTimeout(j),T({url:v,canConnect:!1,error:X})})})}static async _checkMediaServers(v,m,b){try{const{response:T}=await l.networkRequest({type:"GET",url:`${m}/v0.3/discovery/media/${b}`,token:v}),I=T.map(R=>l._checkMediaConnectivity(R.ip,R.port));return await Promise.all(I)}catch{return[]}}static async _checkMediaConnectivity(v,m){return new Promise(async(b,T)=>{const I={iceServers:[{urls:`stun:${v}:${m}`}]},R=new RTCPeerConnection(I),x=Date.now(),N=await R.createOffer({offerToReceiveAudio:!0});R.setLocalDescription(N);const j=setTimeout(()=>{R.close(),b({ip:v,canConnect:!1})},s);R.addEventListener("icecandidate",X=>{var J;if(((J=X==null?void 0:X.candidate)===null||J===void 0?void 0:J.type)==="srflx"){const V=Date.now()-x;clearTimeout(j),R.close(),b({ip:v,canConnect:!0,connectionTime:V})}}),R.addEventListener("icecandidateerror",X=>{X.errorCode&&(R.close(),clearTimeout(j),b({ip:v,canConnect:!1,error:X}))})})}static _checkIfUserIsReInvited(v,m){var b;if(!v.has(m.cid)||!(m.type==="member:invited"||m.type==="member:joined"))return!1;const T=(b=v.get(m.cid))===null||b===void 0?void 0:b.me;return T?T.user.name===m.body.user.name&&T.state==="LEFT":!1}}t.default=l,e.exports=l}(Yc,Yc.exports)),Yc.exports}var Xv={exports:{}};(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r=Ar,n=Gn;class i{constructor(s){if(this.log=r.getLogger(this.constructor.name),!s)throw new n.NexmoClientError("no emitter object passed for the Error Emitter");this.emitter=s,this.LISTENER_GROUP="NXM-errors"}emitResponseIfError(s){if(this._isTypeError(s.type))return this.emitter.emit(s.type,this.LISTENER_GROUP,s)}cleanup(){return this.emitter.releaseGroup(this.LISTENER_GROUP)}_isTypeError(s){return s.indexOf("error")!==-1}}t.default=i,e.exports=i})(Xv,Xv.exports);var kte=Xv.exports;(function(e,t){var r=je&&je.__importDefault||function(I){return I&&I.__esModule?I:{default:I}};Object.defineProperty(t,"__esModule",{value:!0});const n=Da,i=r(kQ),a=r(Ar),s=Gn,o=r(G$),u=r(wee),c=r(Ree),l=r(Ii()),p=r(rd()),v=r(kte),m=r(X$),b=r(ed());i.default.reg(a.default),i.default.apply(a.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 T{constructor(R={}){const x=R;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.6.1",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,eventQueueWaitTime:50,enableInboundOffer:!1,acknowledgeEvents:!0,token:null},this.config.socket_io.query={token:"",SDK_version:this.config.SDK_version,session_version:R.enableInboundOffer?"0.0.3":"0.0.1",acknowledge_events:this.config.acknowledgeEvents,OS_family:"js",OS_revision:typeof navigator<"u"?navigator.userAgent:typeof window<"u"?window.navigator.userAgent:"Generic JS navigator"},this.sessionReady=!1,this.disconnectTimestamp=null,this.session_id=null,this.apiKey=null,this.requests={},this.application=null,["debug","info","warn","error"].includes(x.debug)?a.default.setLevel(x.debug):x.debug===!0?a.default.setLevel("debug"):a.default.setLevel("silent"),this.log=a.default.noConflict(),this.config=l.default.deepMergeObj(this.config,this._sanitizeConfig(x)),this.config.log_reporter.enabled){const N={apiKey:this.config.log_reporter.bugsnag_key||l.default._getBugsnagKey(),appVersion:this.config.socket_io.query.SDK_version,releaseStage:this.config.environment};je.NXMbugsnagClient=u.default(N)}n.mixin(T)}_createAndSetConnection(){let R,x=Object.assign({path:this.config.path},this.config.socket_io);return R=o.default.connect(this.config.url,x),this.connection=R,R.on("connect",()=>{this.emit("ready"),this.sessionReady=!0,this.log.info("websocket ready")}),R.on("disconnect",(N,j)=>{this.emit("disconnect",N==="io client disconnect"?T.DISCONNECT_REASON.ClientDisconnected:N==="io server disconnect"&&this.session_id?T.DISCONNECT_REASON.TokenExpired:T.DISCONNECT_REASON.ConnectionError),this.disconnectTimestamp=Date.now(),this.log.info("websocket disconnected",N,j)}),R.io.on("reconnect",N=>{this.emit("reconnect",N),this.log.info("websocket reconnect",N),l.default.networkRequest({url:`${this.config.url.replace("wss://","https://")}/v2/rtc/metrics`,type:"POST",token:this.config.token,data:{sessionId:this.session_id,metrics:[{name:"TIME_TO_RECONNECT_SUCCESS",time:this.disconnectTimestamp?Date.now()-this.disconnectTimestamp:void 0,attempt:N}]}}).catch(j=>{this.log.warn("Failed to publish socket reconnection metrics",j)})}),R.io.on("reconnect_attempt",N=>{this.emit("reconnecting",N),this.log.info("websocket reconnecting",N)}),R.on("connect_error",N=>{this.emit("error",new s.NexmoClientError(N)),this.log.error("Socket.io reported a generic error",N)}),R.io.on("reconnect_failed",()=>{this.emit("error",new s.NexmoClientError("error:client:reconnection_failed")),this.log.error("websocket reconnection error")}),R.io.on("packet",N=>{if(N.type!==2||N.data[0]==="echo")return;const j=N.data[2];j&&typeof j=="function"&&j();const X=N.data[1];if(X.type=N.data[0],this.log.debug("<--",X.type,X),this.requests["session:login"]){const J=this.requests["session:login"].callback;delete this.requests["session:login"],J(X)}else if(X.rid in this.requests){const J=this.requests[X.rid].callback;delete this.requests[X.rid],delete X.delay,this.errorsEmitter&&this.errorsEmitter.emitResponseIfError(X),J(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)}),R}_sanitizeConfig(R){let x=R;return R.sync&&["none","lite","full"].indexOf(R.sync)===-1&&(this.log.warn(`invalid param '${R.sync}' for sync, reverting to ${this.config.sync}`),x.sync=this.config.sync),x}sendRequest(R,x){R.tid=l.default.allocateUUID();const N=R.type;delete R.type,this.log.debug("-->",N,R),this.log.info("-->",N,R.tid),this.connection.emit(N,R),this.requests[R.tid]={type:N,request:R,callback:x}}async sendNetworkRequest(R){const x=R.version||"beta",N=`${this.config.nexmo_api_url}/${x}/${R.path}`;if(!(R.type==="GET"||R.type==="DELETE")&&(R.data={...R.data,originating_session:this.session_id},!l.default.checkIsSanitized(["data",R.data])))throw new s.NexmoClientError("error:input:unsanitized");try{const j={type:R.type,url:N,data:R.data?R.data:null,token:(R.data||{}).token?R.data.token:this.config.token||null};this.log.debug("sendNetworkRequest: ",{request:j});const{response:X}=await l.default.networkRequest(j);return X}catch({response:j}){throw j}}createSession(R){return this.config.socket_io.query.token=R,this._createAndSetConnection(),new Promise((x,N)=>{this.log.info(`Client-SDK Version: ${this.config.SDK_version}`),this.config.token=null,this.requests["session:login"]={type:"session:login",callback:async j=>{if(j.type==="session:success")if(this.session_id=j.body.id,this.apiKey=j.body.api_key,this.config.token=R,this.connection.io.opts.query={session_id:this.session_id,token:this.config.token},(!this.application||this.application.me&&this.application.me.id!==j.body.user_id)&&(this.application=new p.default(this,{})),this.application.me||(this.application.me=new m.default(this.application,{id:j.body.user_id,name:j.body.name})),this.errorsEmitter||(this.errorsEmitter=new v.default(this.application)),this.config.log_reporter.enabled&&(je.NXMbugsnagClient.user={id:this.application.me.id,name:this.application.me.name,session_id:j.body.id}),this.config.sync!=="none")try{await this.application.getConversations(),x(this.application)}catch(X){N(X)}else x(this.application);else N(new s.NexmoApiError(j))}}})}deleteSession(){return new Promise(async(R,x)=>{const N=()=>this.sendRequest({type:"session:logout",body:{}},j=>{j.type==="session:logged-out"||j.type==="session:terminated"?(this.disconnect(),delete this.errorsEmitter,delete this.application,delete this.connection,this.requests={},this.sessionReady=!1,R(j)):x(j)});if(this.application){let j=[];if(this.application.conversations.size)for(let X of this.application.conversations.values())j.push(X.media.disable());try{await Promise.all(j)}catch(X){this.log.error("deleteSession: ",X)}return N()}else return N()})}updateSession(R){R.type==="session:success"&&(this.session_id=R.body.id,this.connection.io.opts.query.session_id=R.body.id,this.application&&R.body.pending_events&&R.body.pending_events.forEach(x=>this.application._enqueueEvent(x)))}disconnect(){return this.connection.disconnect()}connect(){return this.connection.connect()}async connectivityReport(R,x){const j={machineInfo:{ip:b.default.isNode()?void 0:await c.default.v4()},connectivityReport:[]};try{const{response:X}=await l.default.networkRequest({type:"GET",url:`${this.config.nexmo_api_url}/v0.3/discovery/api`,token:R});let J=X;x!=null&&x.dcListCallback&&(J=x.dcListCallback(J));for(const V in J){const D=J[V].endpoint,te=J[V].https,ue=J[V].ws;try{const ee=await l.default._checkHttpConnectivity(te),ge=await l.default._checkWsConnectivity(ue,this.config.path,this.config.socket_io),L=await l.default._checkMediaServers(R,D,V),pe={name:V,signalConnectionReport:{https:ee,ws:ge},mediaConnectionReport:L};j.connectivityReport.push(pe)}catch(ee){this.log.error(`Error generating report for ${V}`,ee)}}}catch(X){this.log.error("Error fetching nexmo servers information",X)}return j}async checkMediaServers(R,x,N){return await l.default._checkMediaServers(R,x,N)}async checkMediaConnectivity(R,x){return await l.default._checkMediaConnectivity(R,x)}}t.default=T,T.DISCONNECT_REASON={ClientDisconnected:"ClientDisconnected",TokenExpired:"TokenExpired",ConnectionError:"ConnectionError"},e.exports=T})(Tv,Tv.exports);var Rte=Tv.exports;const $te=jT(Rte),Li=new $a("nexmo-chat"),Ite=["us-3","us-4","eu-3","eu-4","ap-3","ap-4"];class GI extends tm{constructor(){super(...arguments);ht(this,"rtc");ht(this,"application");ht(this,"conversation")}get _client(){if(this.rtc)return this.rtc;const r=Ote(this.region);return this.rtc=new $te({nexmo_api_url:`https://api-${this.region}.${r}`,url:`wss://ws-${this.region}.${r}`}),this.rtc}async create(){const{identity:r,token:n}=await this.issueChatToken();Li.info(`Connecting chat, identity: ${r}, token: ${n}`),this.identity=r,this.application=await this._client.createSession(n)}async destroy(){this.rtc&&(await this.rtc.deleteSession(),this.rtc=null,this.application=null,this.conversation=null)}async join(r){const n=await this.application.getConversation(r);n.me.state==="JOINED"?Li.info("already joined conversation:",r):(await n.join(),Li.info("success joined conversation:",r)),this.registerEvents(n),this.conversation=n}async preview(r){await this.conversation.sendCustomEvent({type:"ujet_preview",body:{chat_preview:r,chat_preview_updated_at:new Date().toJSON()}})}async fetchMessages(r){const n=await this.conversation.getEvents({event_type:"message",order:"desc",page_size:100}),i=[];return n.items.forEach(a=>{const s=a._embedded.from_user.name,o=vT(a,s);r[o.$index]&&(o.file=r[o.$index]),this.trackInTask(o),i.push(o)}),i.reverse()}async sendMessage(r){try{const n=await this.conversation.sendMessage({message_type:"text",text:JSON.stringify(r)});return Li.info(`Message sent from ${this.conversation.id}, id: ${n.id}`),parseInt(n.id,10)}catch(n){Li.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(r){r.on("message",(n,i)=>{const a=vT(i,n.userName);Li.info(`Message added from ${this.conversation.id}, index: ${a.$index}, sid: ${a.$sid}, timestamp: ${a.$timestamp}, user type: ${a.$userType}`),a.$userType!=="end_user"&&this.ping(),this.trackInTask(a),this.events.triggerEvent("message",a)}),r.on("member:joined",n=>{Li.info("conversation: memberJoined",n),this.events.triggerEvent("memberJoined",n.userName)}),r.on("member:left",n=>{Li.info("conversation: memberLeft",n),this.events.triggerEvent("memberLeft",n.userName)}),r.on("text:typing:on",n=>{/^end_user/.test(n.userName)||this.events.triggerEvent("typingStarted",n.userName)}),r.on("text:typing:off",n=>{/^end_user/.test(n.userName)||this.events.triggerEvent("typingEnded",n.userName)})}}ht(GI,"type","nexmo_conversations");rm(GI);function Ote(e){return Ite.indexOf(e)>-1?"vonage.com":"nexmo.com"}function vT(e,t){const{id:r,timestamp:n,body:i}=e,[a,s]=t.split("-");let o=0;s&&(o=parseInt(s,10));const u={$index:parseInt(r,10),$sid:r,$timestamp:new Date(Date.parse(n)),$userType:a,$userId:o};try{const c=JSON.parse(i.text);return c.message&&!c.type?{...u,...c,type:"message"}:{...u,...c}}catch(c){return Li.warn("Format message failed",{error:c,data:i.text}),{...u,type:"text",content:i.text}}}exports.Client=gP;exports.ENVIRONMENT=YI;exports.EventManager=em;exports.Logger=$a;exports.MediaStore=ET;exports.OPTIONS=qr;exports.PostSessionStatus=to;exports.VERSION=Qv;exports.addProviderType=rm;exports.consoleLoggerHandler=RO;