@beterdichtbij/component-library 0.66.0-alpha → 0.66.0-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1692,7 +1692,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
1692
1692
|
}
|
|
1693
1693
|
`,classes:{root:function(e){return[`p-fileupload p-fileupload-${e.props.mode} p-component`]},header:`p-fileupload-header`,pcChooseButton:`p-fileupload-choose-button`,pcUploadButton:`p-fileupload-upload-button`,pcCancelButton:`p-fileupload-cancel-button`,content:`p-fileupload-content`,fileList:`p-fileupload-file-list`,file:`p-fileupload-file`,fileThumbnail:`p-fileupload-file-thumbnail`,fileInfo:`p-fileupload-file-info`,fileName:`p-fileupload-file-name`,fileSize:`p-fileupload-file-size`,pcFileBadge:`p-fileupload-file-badge`,fileActions:`p-fileupload-file-actions`,pcFileRemoveButton:`p-fileupload-file-remove-button`,basicContent:`p-fileupload-basic-content`}}),ty={name:`BaseFileUpload`,extends:bp,props:{name:{type:String,default:null},url:{type:String,default:null},mode:{type:String,default:`advanced`},multiple:{type:Boolean,default:!1},accept:{type:String,default:null},disabled:{type:Boolean,default:!1},auto:{type:Boolean,default:!1},maxFileSize:{type:Number,default:null},invalidFileSizeMessage:{type:String,default:`{0}: Invalid file size, file size should be smaller than {1}.`},invalidFileTypeMessage:{type:String,default:`{0}: Invalid file type, allowed file types: {1}.`},fileLimit:{type:Number,default:null},invalidFileLimitMessage:{type:String,default:`Maximum number of files exceeded, limit is {0} at most.`},withCredentials:{type:Boolean,default:!1},previewWidth:{type:Number,default:50},chooseLabel:{type:String,default:null},uploadLabel:{type:String,default:null},cancelLabel:{type:String,default:null},customUpload:{type:Boolean,default:!1},showUploadButton:{type:Boolean,default:!0},showCancelButton:{type:Boolean,default:!0},chooseIcon:{type:String,default:void 0},uploadIcon:{type:String,default:void 0},cancelIcon:{type:String,default:void 0},style:null,class:null,chooseButtonProps:{type:null,default:null},uploadButtonProps:{type:Object,default:function(){return{severity:`secondary`}}},cancelButtonProps:{type:Object,default:function(){return{severity:`secondary`}}}},style:ey,provide:function(){return{$pcFileUpload:this,$parentInstance:this}}},ny={name:`FileContent`,hostName:`FileUpload`,extends:bp,emits:[`remove`],props:{files:{type:Array,default:function(){return[]}},badgeSeverity:{type:String,default:`warn`},badgeValue:{type:String,default:null},previewWidth:{type:Number,default:50},templates:{type:null,default:null}},methods:{formatSize:function(e){var t=1024,n=3,r=this.$primevue.config.locale?.fileSizeTypes||[`B`,`KB`,`MB`,`GB`,`TB`,`PB`,`EB`,`ZB`,`YB`];if(e===0)return`0 ${r[0]}`;var i=Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/t**+i).toFixed(n))} ${r[i]}`}},components:{Button:Rm,Badge:Zp,TimesIcon:fv}},ry=[`alt`,`src`,`width`];function iy(e,t,n,r,i,a){var o=(0,u.resolveComponent)(`Badge`),s=(0,u.resolveComponent)(`TimesIcon`),c=(0,u.resolveComponent)(`Button`);return(0,u.openBlock)(!0),(0,u.createElementBlock)(u.Fragment,null,(0,u.renderList)(n.files,function(t,r){return(0,u.openBlock)(),(0,u.createElementBlock)(`div`,(0,u.mergeProps)({key:t.name+t.type+t.size,class:e.cx(`file`)},{ref_for:!0},e.ptm(`file`)),[(0,u.createElementVNode)(`img`,(0,u.mergeProps)({role:`presentation`,class:e.cx(`fileThumbnail`),alt:t.name,src:t.objectURL,width:n.previewWidth},{ref_for:!0},e.ptm(`fileThumbnail`)),null,16,ry),(0,u.createElementVNode)(`div`,(0,u.mergeProps)({class:e.cx(`fileInfo`)},{ref_for:!0},e.ptm(`fileInfo`)),[(0,u.createElementVNode)(`div`,(0,u.mergeProps)({class:e.cx(`fileName`)},{ref_for:!0},e.ptm(`fileName`)),(0,u.toDisplayString)(t.name),17),(0,u.createElementVNode)(`span`,(0,u.mergeProps)({class:e.cx(`fileSize`)},{ref_for:!0},e.ptm(`fileSize`)),(0,u.toDisplayString)(a.formatSize(t.size)),17)],16),(0,u.createVNode)(o,{value:n.badgeValue,class:(0,u.normalizeClass)(e.cx(`pcFileBadge`)),severity:n.badgeSeverity,unstyled:e.unstyled,pt:e.ptm(`pcFileBadge`)},null,8,[`value`,`class`,`severity`,`unstyled`,`pt`]),(0,u.createElementVNode)(`div`,(0,u.mergeProps)({class:e.cx(`fileActions`)},{ref_for:!0},e.ptm(`fileActions`)),[(0,u.createVNode)(c,{onClick:function(t){return e.$emit(`remove`,r)},text:``,rounded:``,severity:`danger`,class:(0,u.normalizeClass)(e.cx(`pcFileRemoveButton`)),unstyled:e.unstyled,pt:e.ptm(`pcFileRemoveButton`)},{icon:(0,u.withCtx)(function(i){return[n.templates.fileremoveicon?((0,u.openBlock)(),(0,u.createBlock)((0,u.resolveDynamicComponent)(n.templates.fileremoveicon),{key:0,class:(0,u.normalizeClass)(i.class),file:t,index:r},null,8,[`class`,`file`,`index`])):((0,u.openBlock)(),(0,u.createBlock)(s,(0,u.mergeProps)({key:1,class:i.class,"aria-hidden":`true`},{ref_for:!0},e.ptm(`pcFileRemoveButton`).icon),null,16,[`class`]))]}),_:2},1032,[`onClick`,`class`,`unstyled`,`pt`])],16)],16)}),128)}ny.render=iy;function ay(e){return cy(e)||sy(e)||uy(e)||oy()}function oy(){throw TypeError(`Invalid attempt to spread non-iterable instance.
|
|
1694
1694
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function sy(e){if(typeof Symbol<`u`&&e[Symbol.iterator]!=null||e[`@@iterator`]!=null)return Array.from(e)}function cy(e){if(Array.isArray(e))return dy(e)}function ly(e,t){var n=typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(!n){if(Array.isArray(e)||(n=uy(e))||t){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw TypeError(`Invalid attempt to iterate non-iterable instance.
|
|
1695
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var a,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,a=e},f:function(){try{o||n.return==null||n.return()}finally{if(s)throw a}}}}function uy(e,t){if(e){if(typeof e==`string`)return dy(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?dy(e,t):void 0}}function dy(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}var fy={name:`FileUpload`,extends:ty,inheritAttrs:!1,emits:[`select`,`uploader`,`before-upload`,`progress`,`upload`,`error`,`before-send`,`clear`,`remove`,`remove-uploaded-file`],duplicateIEEvent:!1,data:function(){return{uploadedFileCount:0,files:[],messages:[],focused:!1,progress:null,uploadedFiles:[]}},methods:{upload:function(){this.hasFiles&&this.uploader()},onBasicUploaderClick:function(e){e.button===0&&this.$refs.fileInput.click()},onFileSelect:function(e){if(e.type!==`drop`&&this.isIE11()&&this.duplicateIEEvent){this.duplicateIEEvent=!1;return}this.isBasic&&this.hasFiles&&(this.files=[]),this.messages=[],this.files=this.files||[];var t=ly(e.dataTransfer?e.dataTransfer.files:e.target.files),n;try{for(t.s();!(n=t.n()).done;){var r=n.value;!this.isFileSelected(r)&&!this.isFileLimitExceeded()&&this.validate(r)&&(this.isImage(r)&&(r.objectURL=window.URL.createObjectURL(r)),this.files.push(r))}}catch(e){t.e(e)}finally{t.f()}this.$emit(`select`,{originalEvent:e,files:this.files}),this.fileLimit&&this.checkFileLimit(),this.auto&&this.hasFiles&&!this.isFileLimitExceeded()&&this.uploader(),e.type!==`drop`&&this.isIE11()?this.clearIEInput():this.clearInputElement()},choose:function(){this.$refs.fileInput.click()},uploader:function(){var e=this;if(this.customUpload)this.fileLimit&&(this.uploadedFileCount+=this.files.length),this.$emit(`uploader`,{files:this.files});else{var t=new XMLHttpRequest,n=new FormData;this.$emit(`before-upload`,{xhr:t,formData:n});var r=ly(this.files),i;try{for(r.s();!(i=r.n()).done;){var a=i.value;n.append(this.name,a,a.name)}}catch(e){r.e(e)}finally{r.f()}t.upload.addEventListener(`progress`,function(t){t.lengthComputable&&(e.progress=Math.round(t.loaded*100/t.total)),e.$emit(`progress`,{originalEvent:t,progress:e.progress})}),t.onreadystatechange=function(){if(t.readyState===4){if(e.progress=0,t.status>=200&&t.status<300){var n;e.fileLimit&&(e.uploadedFileCount+=e.files.length),e.$emit(`upload`,{xhr:t,files:e.files}),(n=e.uploadedFiles).push.apply(n,ay(e.files))}else e.$emit(`error`,{xhr:t,files:e.files});e.clear()}},this.url&&(t.open(`POST`,this.url,!0),this.$emit(`before-send`,{xhr:t,formData:n}),t.withCredentials=this.withCredentials,t.send(n))}},clear:function(){this.files=[],this.messages=null,this.$emit(`clear`),this.isAdvanced&&this.clearInputElement()},onFocus:function(){this.focused=!0},onBlur:function(){this.focused=!1},isFileSelected:function(e){if(this.files&&this.files.length){var t=ly(this.files),n;try{for(t.s();!(n=t.n()).done;){var r=n.value;if(r.name+r.type+r.size===e.name+e.type+e.size)return!0}}catch(e){t.e(e)}finally{t.f()}}return!1},isIE11:function(){return!!window.MSInputMethodContext&&!!document.documentMode},validate:function(e){return this.accept&&!this.isFileTypeValid(e)?(this.messages.push(this.invalidFileTypeMessage.replace(`{0}`,e.name).replace(`{1}`,this.accept)),!1):this.maxFileSize&&e.size>this.maxFileSize?(this.messages.push(this.invalidFileSizeMessage.replace(`{0}`,e.name).replace(`{1}`,this.formatSize(this.maxFileSize))),!1):!0},isFileTypeValid:function(e){var t=ly(this.accept.split(`,`).map(function(e){return e.trim()})),n;try{for(t.s();!(n=t.n()).done;){var r=n.value;if(this.isWildcard(r)?this.getTypeClass(e.type)===this.getTypeClass(r):e.type==r||this.getFileExtension(e).toLowerCase()===r.toLowerCase())return!0}}catch(e){t.e(e)}finally{t.f()}return!1},getTypeClass:function(e){return e.substring(0,e.indexOf(`/`))},isWildcard:function(e){return e.indexOf(`*`)!==-1},getFileExtension:function(e){return`.`+e.name.split(`.`).pop()},isImage:function(e){return/^image\//.test(e.type)},onDragEnter:function(e){!this.disabled&&(!this.hasFiles||this.multiple)&&(e.stopPropagation(),e.preventDefault())},onDragOver:function(e){!this.disabled&&(!this.hasFiles||this.multiple)&&(!this.isUnstyled&&md(this.$refs.content,`p-fileupload-highlight`),this.$refs.content&&this.$refs.content.setAttribute(`data-p-highlight`,!0),e.stopPropagation(),e.preventDefault())},onDragLeave:function(){this.disabled||(!this.isUnstyled&&hd(this.$refs.content,`p-fileupload-highlight`),this.$refs.content&&this.$refs.content.setAttribute(`data-p-highlight`,!1))},onDrop:function(e){if(!this.disabled){!this.isUnstyled&&hd(this.$refs.content,`p-fileupload-highlight`),this.$refs.content&&this.$refs.content.setAttribute(`data-p-highlight`,!1),e.stopPropagation(),e.preventDefault();var t=e.dataTransfer?e.dataTransfer.files:e.target.files;(this.multiple||t&&t.length===1)&&this.onFileSelect(e)}},remove:function(e){this.clearInputElement();var t=this.files.splice(e,1)[0];this.files=ay(this.files),this.$emit(`remove`,{file:t,files:this.files})},removeUploadedFile:function(e){var t=this.uploadedFiles.splice(e,1)[0];this.uploadedFiles=ay(this.uploadedFiles),this.$emit(`remove-uploaded-file`,{file:t,files:this.uploadedFiles})},clearInputElement:function(){this.$refs.fileInput.value=``},clearIEInput:function(){this.$refs.fileInput&&(this.duplicateIEEvent=!0,this.$refs.fileInput.value=``)},formatSize:function(e){var t=1024,n=3,r=this.$primevue.config.locale?.fileSizeTypes||[`B`,`KB`,`MB`,`GB`,`TB`,`PB`,`EB`,`ZB`,`YB`];if(e===0)return`0 ${r[0]}`;var i=Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/t**+i).toFixed(n))} ${r[i]}`},isFileLimitExceeded:function(){return this.fileLimit&&this.fileLimit<=this.files.length+this.uploadedFileCount&&this.focused&&(this.focused=!1),this.fileLimit&&this.fileLimit<this.files.length+this.uploadedFileCount},checkFileLimit:function(){this.isFileLimitExceeded()&&this.messages.push(this.invalidFileLimitMessage.replace(`{0}`,this.fileLimit.toString()))},onMessageClose:function(){this.messages=null}},computed:{isAdvanced:function(){return this.mode===`advanced`},isBasic:function(){return this.mode===`basic`},chooseButtonClass:function(){return[this.cx(`pcChooseButton`),this.class]},basicFileChosenLabel:function(){if(this.auto)return this.chooseButtonLabel;if(this.hasFiles){var e;return this.files&&this.files.length===1?this.files[0].name:(e=this.$primevue.config.locale)==null||(e=e.fileChosenMessage)==null?void 0:e.replace(`{0}`,this.files.length)}return this.$primevue.config.locale?.noFileChosenMessage||``},hasFiles:function(){return this.files&&this.files.length>0},hasUploadedFiles:function(){return this.uploadedFiles&&this.uploadedFiles.length>0},chooseDisabled:function(){return this.disabled||this.fileLimit&&this.fileLimit<=this.files.length+this.uploadedFileCount},uploadDisabled:function(){return this.disabled||!this.hasFiles||this.fileLimit&&this.fileLimit<this.files.length},cancelDisabled:function(){return this.disabled||!this.hasFiles},chooseButtonLabel:function(){return this.chooseLabel||this.$primevue.config.locale.choose},uploadButtonLabel:function(){return this.uploadLabel||this.$primevue.config.locale.upload},cancelButtonLabel:function(){return this.cancelLabel||this.$primevue.config.locale.cancel},completedLabel:function(){return this.$primevue.config.locale.completed},pendingLabel:function(){return this.$primevue.config.locale.pending}},components:{Button:Rm,ProgressBar:Jv,Message:Pv,FileContent:ny,PlusIcon:iv,UploadIcon:bv,TimesIcon:fv},directives:{ripple:Em}},py=[`multiple`,`accept`,`disabled`],my=[`accept`,`disabled`,`multiple`];function hy(e,t,n,r,i,a){var o=(0,u.resolveComponent)(`Button`),s=(0,u.resolveComponent)(`ProgressBar`),c=(0,u.resolveComponent)(`Message`),l=(0,u.resolveComponent)(`FileContent`);return a.isAdvanced?((0,u.openBlock)(),(0,u.createElementBlock)(`div`,(0,u.mergeProps)({key:0,class:e.cx(`root`)},e.ptmi(`root`)),[(0,u.createElementVNode)(`input`,(0,u.mergeProps)({ref:`fileInput`,type:`file`,onChange:t[0]||=function(){return a.onFileSelect&&a.onFileSelect.apply(a,arguments)},multiple:e.multiple,accept:e.accept,disabled:a.chooseDisabled},e.ptm(`input`)),null,16,py),(0,u.createElementVNode)(`div`,(0,u.mergeProps)({class:e.cx(`header`)},e.ptm(`header`)),[(0,u.renderSlot)(e.$slots,`header`,{files:i.files,uploadedFiles:i.uploadedFiles,chooseCallback:a.choose,uploadCallback:a.uploader,clearCallback:a.clear},function(){return[(0,u.createVNode)(o,(0,u.mergeProps)({label:a.chooseButtonLabel,class:a.chooseButtonClass,style:e.style,disabled:e.disabled,unstyled:e.unstyled,onClick:a.choose,onKeydown:(0,u.withKeys)(a.choose,[`enter`]),onFocus:a.onFocus,onBlur:a.onBlur},e.chooseButtonProps,{pt:e.ptm(`pcChooseButton`)}),{icon:(0,u.withCtx)(function(t){return[(0,u.renderSlot)(e.$slots,`chooseicon`,{},function(){return[((0,u.openBlock)(),(0,u.createBlock)((0,u.resolveDynamicComponent)(e.chooseIcon?`span`:`PlusIcon`),(0,u.mergeProps)({class:[t.class,e.chooseIcon],"aria-hidden":`true`},e.ptm(`pcChooseButton`).icon),null,16,[`class`]))]})]}),_:3},16,[`label`,`class`,`style`,`disabled`,`unstyled`,`onClick`,`onKeydown`,`onFocus`,`onBlur`,`pt`]),e.showUploadButton?((0,u.openBlock)(),(0,u.createBlock)(o,(0,u.mergeProps)({key:0,class:e.cx(`pcUploadButton`),label:a.uploadButtonLabel,onClick:a.uploader,disabled:a.uploadDisabled,unstyled:e.unstyled},e.uploadButtonProps,{pt:e.ptm(`pcUploadButton`)}),{icon:(0,u.withCtx)(function(t){return[(0,u.renderSlot)(e.$slots,`uploadicon`,{},function(){return[((0,u.openBlock)(),(0,u.createBlock)((0,u.resolveDynamicComponent)(e.uploadIcon?`span`:`UploadIcon`),(0,u.mergeProps)({class:[t.class,e.uploadIcon],"aria-hidden":`true`},e.ptm(`pcUploadButton`).icon,{"data-pc-section":`uploadbuttonicon`}),null,16,[`class`]))]})]}),_:3},16,[`class`,`label`,`onClick`,`disabled`,`unstyled`,`pt`])):(0,u.createCommentVNode)(``,!0),e.showCancelButton?((0,u.openBlock)(),(0,u.createBlock)(o,(0,u.mergeProps)({key:1,class:e.cx(`pcCancelButton`),label:a.cancelButtonLabel,onClick:a.clear,disabled:a.cancelDisabled,unstyled:e.unstyled},e.cancelButtonProps,{pt:e.ptm(`pcCancelButton`)}),{icon:(0,u.withCtx)(function(t){return[(0,u.renderSlot)(e.$slots,`cancelicon`,{},function(){return[((0,u.openBlock)(),(0,u.createBlock)((0,u.resolveDynamicComponent)(e.cancelIcon?`span`:`TimesIcon`),(0,u.mergeProps)({class:[t.class,e.cancelIcon],"aria-hidden":`true`},e.ptm(`pcCancelButton`).icon,{"data-pc-section":`cancelbuttonicon`}),null,16,[`class`]))]})]}),_:3},16,[`class`,`label`,`onClick`,`disabled`,`unstyled`,`pt`])):(0,u.createCommentVNode)(``,!0)]})],16),(0,u.createElementVNode)(`div`,(0,u.mergeProps)({ref:`content`,class:e.cx(`content`),onDragenter:t[1]||=function(){return a.onDragEnter&&a.onDragEnter.apply(a,arguments)},onDragover:t[2]||=function(){return a.onDragOver&&a.onDragOver.apply(a,arguments)},onDragleave:t[3]||=function(){return a.onDragLeave&&a.onDragLeave.apply(a,arguments)},onDrop:t[4]||=function(){return a.onDrop&&a.onDrop.apply(a,arguments)}},e.ptm(`content`),{"data-p-highlight":!1}),[(0,u.renderSlot)(e.$slots,`content`,{files:i.files,uploadedFiles:i.uploadedFiles,removeUploadedFileCallback:a.removeUploadedFile,removeFileCallback:a.remove,progress:i.progress,messages:i.messages},function(){return[a.hasFiles?((0,u.openBlock)(),(0,u.createBlock)(s,{key:0,value:i.progress,showValue:!1,unstyled:e.unstyled,pt:e.ptm(`pcProgressbar`)},null,8,[`value`,`unstyled`,`pt`])):(0,u.createCommentVNode)(``,!0),((0,u.openBlock)(!0),(0,u.createElementBlock)(u.Fragment,null,(0,u.renderList)(i.messages,function(t){return(0,u.openBlock)(),(0,u.createBlock)(c,{key:t,severity:`error`,onClose:a.onMessageClose,unstyled:e.unstyled,pt:e.ptm(`pcMessage`)},{default:(0,u.withCtx)(function(){return[(0,u.createTextVNode)((0,u.toDisplayString)(t),1)]}),_:2},1032,[`onClose`,`unstyled`,`pt`])}),128)),a.hasFiles?((0,u.openBlock)(),(0,u.createElementBlock)(`div`,{key:1,class:(0,u.normalizeClass)(e.cx(`fileList`))},[(0,u.createVNode)(l,{files:i.files,onRemove:a.remove,badgeValue:a.pendingLabel,previewWidth:e.previewWidth,templates:e.$slots,unstyled:e.unstyled,pt:e.pt},null,8,[`files`,`onRemove`,`badgeValue`,`previewWidth`,`templates`,`unstyled`,`pt`])],2)):(0,u.createCommentVNode)(``,!0),a.hasUploadedFiles?((0,u.openBlock)(),(0,u.createElementBlock)(`div`,{key:2,class:(0,u.normalizeClass)(e.cx(`fileList`))},[(0,u.createVNode)(l,{files:i.uploadedFiles,onRemove:a.removeUploadedFile,badgeValue:a.completedLabel,badgeSeverity:`success`,previewWidth:e.previewWidth,templates:e.$slots,unstyled:e.unstyled,pt:e.pt},null,8,[`files`,`onRemove`,`badgeValue`,`previewWidth`,`templates`,`unstyled`,`pt`])],2)):(0,u.createCommentVNode)(``,!0)]}),e.$slots.empty&&!a.hasFiles&&!a.hasUploadedFiles?((0,u.openBlock)(),(0,u.createElementBlock)(`div`,(0,u.normalizeProps)((0,u.mergeProps)({key:0},e.ptm(`empty`))),[(0,u.renderSlot)(e.$slots,`empty`)],16)):(0,u.createCommentVNode)(``,!0)],16)],16)):a.isBasic?((0,u.openBlock)(),(0,u.createElementBlock)(`div`,(0,u.mergeProps)({key:1,class:e.cx(`root`)},e.ptmi(`root`)),[((0,u.openBlock)(!0),(0,u.createElementBlock)(u.Fragment,null,(0,u.renderList)(i.messages,function(t){return(0,u.openBlock)(),(0,u.createBlock)(c,{key:t,severity:`error`,onClose:a.onMessageClose,unstyled:e.unstyled,pt:e.ptm(`pcMessage`)},{default:(0,u.withCtx)(function(){return[(0,u.createTextVNode)((0,u.toDisplayString)(t),1)]}),_:2},1032,[`onClose`,`unstyled`,`pt`])}),128)),(0,u.createElementVNode)(`div`,(0,u.mergeProps)({class:e.cx(`basicContent`)},e.ptm(`basicContent`)),[(0,u.createVNode)(o,(0,u.mergeProps)({label:a.chooseButtonLabel,class:a.chooseButtonClass,style:e.style,disabled:e.disabled,unstyled:e.unstyled,onMouseup:a.onBasicUploaderClick,onKeydown:(0,u.withKeys)(a.choose,[`enter`]),onFocus:a.onFocus,onBlur:a.onBlur},e.chooseButtonProps,{pt:e.ptm(`pcChooseButton`)}),{icon:(0,u.withCtx)(function(t){return[(0,u.renderSlot)(e.$slots,`chooseicon`,{},function(){return[((0,u.openBlock)(),(0,u.createBlock)((0,u.resolveDynamicComponent)(e.chooseIcon?`span`:`PlusIcon`),(0,u.mergeProps)({class:[t.class,e.chooseIcon],"aria-hidden":`true`},e.ptm(`pcChooseButton`).icon),null,16,[`class`]))]})]}),_:3},16,[`label`,`class`,`style`,`disabled`,`unstyled`,`onMouseup`,`onKeydown`,`onFocus`,`onBlur`,`pt`]),e.auto?(0,u.createCommentVNode)(``,!0):(0,u.renderSlot)(e.$slots,`filelabel`,{key:0,class:(0,u.normalizeClass)(e.cx(`filelabel`)),files:i.files},function(){return[(0,u.createElementVNode)(`span`,{class:(0,u.normalizeClass)(e.cx(`filelabel`))},(0,u.toDisplayString)(a.basicFileChosenLabel),3)]}),(0,u.createElementVNode)(`input`,(0,u.mergeProps)({ref:`fileInput`,type:`file`,accept:e.accept,disabled:e.disabled,multiple:e.multiple,onChange:t[5]||=function(){return a.onFileSelect&&a.onFileSelect.apply(a,arguments)},onFocus:t[6]||=function(){return a.onFocus&&a.onFocus.apply(a,arguments)},onBlur:t[7]||=function(){return a.onBlur&&a.onBlur.apply(a,arguments)}},e.ptm(`input`)),null,16,my)],16)],16)):(0,u.createCommentVNode)(``,!0)}fy.render=hy;var gy={notFoundTemplate:{title:`Page not found`,description:`The page you're looking for couldn't be found. Check the URL or go back to the mainpage.`,buttonDefault:`Back to mainpage`},practitionerHeader:{tooltipAcademy:`BeterDichtbij Academie`,menuItemAcademy:`Academie`}},_y={activeFilters:{title:`Actieve filters`,clearAll:`Wis alle filters`},assignConversationModal:{title:`Gesprek overdragen`,submitButton:`Gesprek overdragen`,conclude:`Afhandelen bij de overdracht`,concludeTooltip:`Het gesprek blijft beschikbaar, deze wordt getoond als het filter "afgehandeld" is geselecteerd. Je patiënt kan ook nog gewoon reageren.`,makeUnread:`Gesprek op ongelezen zetten`},attachmentUploadModal:{title:`Bijlage toevoegen`,submitButton:`Toevoegen`,infoMessage:`Kies je bestand.`,addAttachmentButton:`Bijlage toevoegen`,errorMessage:`Fout opgetreden`,fileTooBigErrorMessage:`Bestand is te groot.`,fileSizeExceededMessage:`Bestanden mogen maximaal 10 MB groot zijn.`},changePasswordTemplate:{toasters:{reset:`De velden zijn geleegd.`}},contentLibraryCard:{insert:`Invoegen`},contentLibraryCardMessageTemplate:{insert:`Invoegen`,collapseOpen:`Inklappen`,collapseClosed:`Lees meer`,popoverIsSharedByOtherUser:`Dit bericht kan alleen door de eigenaar of beheerder aangepast worden`,delete:`Verwijderen`,edit:`Wijzigen`},contentLibraryOverview:{noResults:`Er zijn geen berichten gevonden voor deze zoekterm of filters; pas ze aan om opnieuw te zoeken.`},contentLibrarySplitButton:{messageTemplatesTitle:`Standaardberichten`},contentLibraryTemplate:{changeCategoryButtonLabel:`Mijn categorieën aanpassen`,newMessageText:`Nieuw bericht`,message:`Bericht`,messages:`Berichten`,more:`Meer`,less:`Minder`,searchPlaceholder:`Zoek een bericht`,searchPlaceholderSearch:`Vul een zoekterm in om resultaten te tonen`},conversationToTextModal:{copyButton:`Kopieer selectie naar klembord`,copySuccess:`Het gesprek is gekopieerd naar het klembord.`,onBehalfOf:`namens`,prefix:`Communicatie vanuit BeterDichtbij`,selectAll:`Alles selecteren`,systemMessage:`Tussentijdse mededeling`},imageAttachmentModal:{download:`Download afbeelding`,loading:`Afbeelding aan het laden`},fileUpload:{errorMessage:`Er is een fout opgetreden tijdens het uploaden van het bestand.`},filterCard:{more:`Meer`,less:`Minder`},messageTemplateFormModal:{createTitle:`Standaardbericht toevoegen`,editTitle:`Standaardbericht wijzigen`,titleLabel:`Titel`,titlePlaceHolder:`Zwelling na botbreuk`,replyTemplateLabel:`Standaardbericht`,replyTemplatePlaceHolder:`Schrijf hier jouw bericht naar de patiënt`,sharedWithLabel:`Delen met`,owner:`Eigenaar`,ownerPlaceholder:`Selecteer eigenaar`,tooltipOwner:`Als het bericht met meerdere instanties (teams) gedeeld wordt, kunje alleen zelf eigenaar worden`,categoryLabel:`Categorie`,categoryPlaceholderDropdown:`Selecteer categorie of maak een nieuwe aan`,validation:`Dit veld is verplicht.`},notFoundTemplate:{title:`Pagina niet gevonden`,description:`De pagina die je zoekt kon niet gevonden worden. Controleer de URL of ga terug naar de hoofdpagina.`,buttonDefault:`Terug naar hoofdpagina`},practitionerHeader:{academyTooltip:`BeterDichtbij Academie`,academyMenuItem:`Academie`},videoCallConfirmationModal:{title:`Beeldbellen`,cancel:`Nee`,close:`Sluiten`,ok:`Ja`,message:`Weet je zeker dat je wilt beeldbellen?`,participantMessage:`Weet je zeker dat je wilt beeldbellen met`,testMessage:`Doe de beeldbeltest`,noMobileActivationMessage:`gebruikt BeterDichtbij via de web applicatie waardoor beeldbellen niet mogelijk is. Vraag de patiënt om de app te installeren op een mobiele telefoon of tablet.`,noCompatibleDevices:`gebruikt mogelijk een mobiele telefoon of tablet die beeldbellen niet ondersteunt. Het is daarom momenteel niet mogelijk om te beeldbellen met deze patiënt.`,generalWarning:`Beeldbellen is niet mogelijk om de volgende redenen:`,cameraPermissionMissing:`Je hebt geen toestemming gegeven voor gebruik van de camera door BeterDichtbij.`,microphonePermissionMissing:`Je hebt geen toestemming gegeven voor gebruik van de microfoon door BeterDichtbij.`,helpMessage:`om te controleren of je camera en microfoon goed werken.`}},vy=Iu({legacy:!1,locale:`nl`,messages:{en:{...gy},nl:{..._y}}}),yy=`bottom`,by=`right`,xy=`left`,Sy=`auto`,Cy=[`top`,yy,by,xy],wy=`start`,Ty=`clippingParents`,Ey=`viewport`,Dy=`popper`,Oy=`reference`,ky=Cy.reduce(function(e,t){return e.concat([t+`-`+wy,t+`-end`])},[]),Ay=[].concat(Cy,[Sy]).reduce(function(e,t){return e.concat([t,t+`-`+wy,t+`-end`])},[]),jy=`beforeRead`,My=`read`,Ny=`afterRead`,Py=`beforeMain`,Fy=`main`,Iy=`afterMain`,Ly=`beforeWrite`,Ry=`write`,zy=`afterWrite`,By=[jy,My,Ny,Py,Fy,Iy,Ly,Ry,zy];function Vy(e){return e?(e.nodeName||``).toLowerCase():null}function Hy(e){if(e==null)return window;if(e.toString()!==`[object Window]`){var t=e.ownerDocument;return t&&t.defaultView||window}return e}function Uy(e){return e instanceof Hy(e).Element||e instanceof Element}function Wy(e){return e instanceof Hy(e).HTMLElement||e instanceof HTMLElement}function Gy(e){return typeof ShadowRoot>`u`?!1:e instanceof Hy(e).ShadowRoot||e instanceof ShadowRoot}function Ky(e){var t=e.state;Object.keys(t.elements).forEach(function(e){var n=t.styles[e]||{},r=t.attributes[e]||{},i=t.elements[e];!Wy(i)||!Vy(i)||(Object.assign(i.style,n),Object.keys(r).forEach(function(e){var t=r[e];t===!1?i.removeAttribute(e):i.setAttribute(e,t===!0?``:t)}))})}function qy(e){var t=e.state,n={popper:{position:t.options.strategy,left:`0`,top:`0`,margin:`0`},arrow:{position:`absolute`},reference:{}};return Object.assign(t.elements.popper.style,n.popper),t.styles=n,t.elements.arrow&&Object.assign(t.elements.arrow.style,n.arrow),function(){Object.keys(t.elements).forEach(function(e){var r=t.elements[e],i=t.attributes[e]||{},a=Object.keys(t.styles.hasOwnProperty(e)?t.styles[e]:n[e]).reduce(function(e,t){return e[t]=``,e},{});!Wy(r)||!Vy(r)||(Object.assign(r.style,a),Object.keys(i).forEach(function(e){r.removeAttribute(e)}))})}}var Jy={name:`applyStyles`,enabled:!0,phase:`write`,fn:Ky,effect:qy,requires:[`computeStyles`]};function Yy(e){return e.split(`-`)[0]}var Xy=Math.max,Zy=Math.min,Qy=Math.round;function $y(){var e=navigator.userAgentData;return e!=null&&e.brands&&Array.isArray(e.brands)?e.brands.map(function(e){return e.brand+`/`+e.version}).join(` `):navigator.userAgent}function eb(){return!/^((?!chrome|android).)*safari/i.test($y())}function tb(e,t,n){t===void 0&&(t=!1),n===void 0&&(n=!1);var r=e.getBoundingClientRect(),i=1,a=1;t&&Wy(e)&&(i=e.offsetWidth>0&&Qy(r.width)/e.offsetWidth||1,a=e.offsetHeight>0&&Qy(r.height)/e.offsetHeight||1);var o=(Uy(e)?Hy(e):window).visualViewport,s=!eb()&&n,c=(r.left+(s&&o?o.offsetLeft:0))/i,l=(r.top+(s&&o?o.offsetTop:0))/a,u=r.width/i,d=r.height/a;return{width:u,height:d,top:l,right:c+u,bottom:l+d,left:c,x:c,y:l}}function nb(e){var t=tb(e),n=e.offsetWidth,r=e.offsetHeight;return Math.abs(t.width-n)<=1&&(n=t.width),Math.abs(t.height-r)<=1&&(r=t.height),{x:e.offsetLeft,y:e.offsetTop,width:n,height:r}}function rb(e,t){var n=t.getRootNode&&t.getRootNode();if(e.contains(t))return!0;if(n&&Gy(n)){var r=t;do{if(r&&e.isSameNode(r))return!0;r=r.parentNode||r.host}while(r)}return!1}function ib(e){return Hy(e).getComputedStyle(e)}function ab(e){return[`table`,`td`,`th`].indexOf(Vy(e))>=0}function ob(e){return((Uy(e)?e.ownerDocument:e.document)||window.document).documentElement}function sb(e){return Vy(e)===`html`?e:e.assignedSlot||e.parentNode||(Gy(e)?e.host:null)||ob(e)}function cb(e){return!Wy(e)||ib(e).position===`fixed`?null:e.offsetParent}function lb(e){var t=/firefox/i.test($y());if(/Trident/i.test($y())&&Wy(e)&&ib(e).position===`fixed`)return null;var n=sb(e);for(Gy(n)&&(n=n.host);Wy(n)&&[`html`,`body`].indexOf(Vy(n))<0;){var r=ib(n);if(r.transform!==`none`||r.perspective!==`none`||r.contain===`paint`||[`transform`,`perspective`].indexOf(r.willChange)!==-1||t&&r.willChange===`filter`||t&&r.filter&&r.filter!==`none`)return n;n=n.parentNode}return null}function ub(e){for(var t=Hy(e),n=cb(e);n&&ab(n)&&ib(n).position===`static`;)n=cb(n);return n&&(Vy(n)===`html`||Vy(n)===`body`&&ib(n).position===`static`)?t:n||lb(e)||t}function q(e){return[`top`,`bottom`].indexOf(e)>=0?`x`:`y`}function db(e,t,n){return Xy(e,Zy(t,n))}function fb(e,t,n){var r=db(e,t,n);return r>n?n:r}function pb(){return{top:0,right:0,bottom:0,left:0}}function mb(e){return Object.assign({},pb(),e)}function hb(e,t){return t.reduce(function(t,n){return t[n]=e,t},{})}var gb=function(e,t){return e=typeof e==`function`?e(Object.assign({},t.rects,{placement:t.placement})):e,mb(typeof e==`number`?hb(e,Cy):e)};function _b(e){var t,n=e.state,r=e.name,i=e.options,a=n.elements.arrow,o=n.modifiersData.popperOffsets,s=Yy(n.placement),c=q(s),l=[`left`,`right`].indexOf(s)>=0?`height`:`width`;if(!(!a||!o)){var u=gb(i.padding,n),d=nb(a),f=c===`y`?`top`:xy,p=c===`y`?yy:by,m=n.rects.reference[l]+n.rects.reference[c]-o[c]-n.rects.popper[l],h=o[c]-n.rects.reference[c],g=ub(a),_=g?c===`y`?g.clientHeight||0:g.clientWidth||0:0,v=m/2-h/2,y=u[f],b=_-d[l]-u[p],x=_/2-d[l]/2+v,S=db(y,x,b),C=c;n.modifiersData[r]=(t={},t[C]=S,t.centerOffset=S-x,t)}}function vb(e){var t=e.state,n=e.options.element,r=n===void 0?`[data-popper-arrow]`:n;r!=null&&(typeof r==`string`&&(r=t.elements.popper.querySelector(r),!r)||rb(t.elements.popper,r)&&(t.elements.arrow=r))}var yb={name:`arrow`,enabled:!0,phase:`main`,fn:_b,effect:vb,requires:[`popperOffsets`],requiresIfExists:[`preventOverflow`]};function bb(e){return e.split(`-`)[1]}var xb={top:`auto`,right:`auto`,bottom:`auto`,left:`auto`};function Sb(e,t){var n=e.x,r=e.y,i=t.devicePixelRatio||1;return{x:Qy(n*i)/i||0,y:Qy(r*i)/i||0}}function Cb(e){var t,n=e.popper,r=e.popperRect,i=e.placement,a=e.variation,o=e.offsets,s=e.position,c=e.gpuAcceleration,l=e.adaptive,u=e.roundOffsets,d=e.isFixed,f=o.x,p=f===void 0?0:f,m=o.y,h=m===void 0?0:m,g=typeof u==`function`?u({x:p,y:h}):{x:p,y:h};p=g.x,h=g.y;var _=o.hasOwnProperty(`x`),v=o.hasOwnProperty(`y`),y=xy,b=`top`,x=window;if(l){var S=ub(n),C=`clientHeight`,w=`clientWidth`;if(S===Hy(n)&&(S=ob(n),ib(S).position!==`static`&&s===`absolute`&&(C=`scrollHeight`,w=`scrollWidth`)),S=S,i===`top`||(i===`left`||i===`right`)&&a===`end`){b=yy;var T=d&&S===x&&x.visualViewport?x.visualViewport.height:S[C];h-=T-r.height,h*=c?1:-1}if(i===`left`||(i===`top`||i===`bottom`)&&a===`end`){y=by;var E=d&&S===x&&x.visualViewport?x.visualViewport.width:S[w];p-=E-r.width,p*=c?1:-1}}var ee=Object.assign({position:s},l&&xb),D=u===!0?Sb({x:p,y:h},Hy(n)):{x:p,y:h};if(p=D.x,h=D.y,c){var O;return Object.assign({},ee,(O={},O[b]=v?`0`:``,O[y]=_?`0`:``,O.transform=(x.devicePixelRatio||1)<=1?`translate(`+p+`px, `+h+`px)`:`translate3d(`+p+`px, `+h+`px, 0)`,O))}return Object.assign({},ee,(t={},t[b]=v?h+`px`:``,t[y]=_?p+`px`:``,t.transform=``,t))}function wb(e){var t=e.state,n=e.options,r=n.gpuAcceleration,i=r===void 0?!0:r,a=n.adaptive,o=a===void 0?!0:a,s=n.roundOffsets,c=s===void 0?!0:s,l={placement:Yy(t.placement),variation:bb(t.placement),popper:t.elements.popper,popperRect:t.rects.popper,gpuAcceleration:i,isFixed:t.options.strategy===`fixed`};t.modifiersData.popperOffsets!=null&&(t.styles.popper=Object.assign({},t.styles.popper,Cb(Object.assign({},l,{offsets:t.modifiersData.popperOffsets,position:t.options.strategy,adaptive:o,roundOffsets:c})))),t.modifiersData.arrow!=null&&(t.styles.arrow=Object.assign({},t.styles.arrow,Cb(Object.assign({},l,{offsets:t.modifiersData.arrow,position:`absolute`,adaptive:!1,roundOffsets:c})))),t.attributes.popper=Object.assign({},t.attributes.popper,{"data-popper-placement":t.placement})}var Tb={name:`computeStyles`,enabled:!0,phase:`beforeWrite`,fn:wb,data:{}},Eb={passive:!0};function Db(e){var t=e.state,n=e.instance,r=e.options,i=r.scroll,a=i===void 0?!0:i,o=r.resize,s=o===void 0?!0:o,c=Hy(t.elements.popper),l=[].concat(t.scrollParents.reference,t.scrollParents.popper);return a&&l.forEach(function(e){e.addEventListener(`scroll`,n.update,Eb)}),s&&c.addEventListener(`resize`,n.update,Eb),function(){a&&l.forEach(function(e){e.removeEventListener(`scroll`,n.update,Eb)}),s&&c.removeEventListener(`resize`,n.update,Eb)}}var Ob={name:`eventListeners`,enabled:!0,phase:`write`,fn:function(){},effect:Db,data:{}},kb={left:`right`,right:`left`,bottom:`top`,top:`bottom`};function Ab(e){return e.replace(/left|right|bottom|top/g,function(e){return kb[e]})}var jb={start:`end`,end:`start`};function Mb(e){return e.replace(/start|end/g,function(e){return jb[e]})}function Nb(e){var t=Hy(e);return{scrollLeft:t.pageXOffset,scrollTop:t.pageYOffset}}function Pb(e){return tb(ob(e)).left+Nb(e).scrollLeft}function Fb(e,t){var n=Hy(e),r=ob(e),i=n.visualViewport,a=r.clientWidth,o=r.clientHeight,s=0,c=0;if(i){a=i.width,o=i.height;var l=eb();(l||!l&&t===`fixed`)&&(s=i.offsetLeft,c=i.offsetTop)}return{width:a,height:o,x:s+Pb(e),y:c}}function Ib(e){var t=ob(e),n=Nb(e),r=e.ownerDocument?.body,i=Xy(t.scrollWidth,t.clientWidth,r?r.scrollWidth:0,r?r.clientWidth:0),a=Xy(t.scrollHeight,t.clientHeight,r?r.scrollHeight:0,r?r.clientHeight:0),o=-n.scrollLeft+Pb(e),s=-n.scrollTop;return ib(r||t).direction===`rtl`&&(o+=Xy(t.clientWidth,r?r.clientWidth:0)-i),{width:i,height:a,x:o,y:s}}function Lb(e){var t=ib(e),n=t.overflow,r=t.overflowX,i=t.overflowY;return/auto|scroll|overlay|hidden/.test(n+i+r)}function Rb(e){return[`html`,`body`,`#document`].indexOf(Vy(e))>=0?e.ownerDocument.body:Wy(e)&&Lb(e)?e:Rb(sb(e))}function zb(e,t){t===void 0&&(t=[]);var n=Rb(e),r=n===e.ownerDocument?.body,i=Hy(n),a=r?[i].concat(i.visualViewport||[],Lb(n)?n:[]):n,o=t.concat(a);return r?o:o.concat(zb(sb(a)))}function Bb(e){return Object.assign({},e,{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height})}function Vb(e,t){var n=tb(e,!1,t===`fixed`);return n.top+=e.clientTop,n.left+=e.clientLeft,n.bottom=n.top+e.clientHeight,n.right=n.left+e.clientWidth,n.width=e.clientWidth,n.height=e.clientHeight,n.x=n.left,n.y=n.top,n}function Hb(e,t,n){return t===`viewport`?Bb(Fb(e,n)):Uy(t)?Vb(t,n):Bb(Ib(ob(e)))}function Ub(e){var t=zb(sb(e)),n=[`absolute`,`fixed`].indexOf(ib(e).position)>=0&&Wy(e)?ub(e):e;return Uy(n)?t.filter(function(e){return Uy(e)&&rb(e,n)&&Vy(e)!==`body`}):[]}function Wb(e,t,n,r){var i=t===`clippingParents`?Ub(e):[].concat(t),a=[].concat(i,[n]),o=a[0],s=a.reduce(function(t,n){var i=Hb(e,n,r);return t.top=Xy(i.top,t.top),t.right=Zy(i.right,t.right),t.bottom=Zy(i.bottom,t.bottom),t.left=Xy(i.left,t.left),t},Hb(e,o,r));return s.width=s.right-s.left,s.height=s.bottom-s.top,s.x=s.left,s.y=s.top,s}function Gb(e){var t=e.reference,n=e.element,r=e.placement,i=r?Yy(r):null,a=r?bb(r):null,o=t.x+t.width/2-n.width/2,s=t.y+t.height/2-n.height/2,c;switch(i){case`top`:c={x:o,y:t.y-n.height};break;case yy:c={x:o,y:t.y+t.height};break;case by:c={x:t.x+t.width,y:s};break;case xy:c={x:t.x-n.width,y:s};break;default:c={x:t.x,y:t.y}}var l=i?q(i):null;if(l!=null){var u=l===`y`?`height`:`width`;switch(a){case wy:c[l]=c[l]-(t[u]/2-n[u]/2);break;case`end`:c[l]=c[l]+(t[u]/2-n[u]/2);break;default:}}return c}function Kb(e,t){t===void 0&&(t={});var n=t,r=n.placement,i=r===void 0?e.placement:r,a=n.strategy,o=a===void 0?e.strategy:a,s=n.boundary,c=s===void 0?Ty:s,l=n.rootBoundary,u=l===void 0?Ey:l,d=n.elementContext,f=d===void 0?Dy:d,p=n.altBoundary,m=p===void 0?!1:p,h=n.padding,g=h===void 0?0:h,_=mb(typeof g==`number`?hb(g,Cy):g),v=f===`popper`?Oy:Dy,y=e.rects.popper,b=e.elements[m?v:f],x=Wb(Uy(b)?b:b.contextElement||ob(e.elements.popper),c,u,o),S=tb(e.elements.reference),C=Gb({reference:S,element:y,strategy:`absolute`,placement:i}),w=Bb(Object.assign({},y,C)),T=f===`popper`?w:S,E={top:x.top-T.top+_.top,bottom:T.bottom-x.bottom+_.bottom,left:x.left-T.left+_.left,right:T.right-x.right+_.right},ee=e.modifiersData.offset;if(f===`popper`&&ee){var D=ee[i];Object.keys(E).forEach(function(e){var t=[`right`,`bottom`].indexOf(e)>=0?1:-1,n=[`top`,`bottom`].indexOf(e)>=0?`y`:`x`;E[e]+=D[n]*t})}return E}function qb(e,t){t===void 0&&(t={});var n=t,r=n.placement,i=n.boundary,a=n.rootBoundary,o=n.padding,s=n.flipVariations,c=n.allowedAutoPlacements,l=c===void 0?Ay:c,u=bb(r),d=u?s?ky:ky.filter(function(e){return bb(e)===u}):Cy,f=d.filter(function(e){return l.indexOf(e)>=0});f.length===0&&(f=d);var p=f.reduce(function(t,n){return t[n]=Kb(e,{placement:n,boundary:i,rootBoundary:a,padding:o})[Yy(n)],t},{});return Object.keys(p).sort(function(e,t){return p[e]-p[t]})}function Jb(e){if(Yy(e)===`auto`)return[];var t=Ab(e);return[Mb(e),t,Mb(t)]}function Yb(e){var t=e.state,n=e.options,r=e.name;if(!t.modifiersData[r]._skip){for(var i=n.mainAxis,a=i===void 0?!0:i,o=n.altAxis,s=o===void 0?!0:o,c=n.fallbackPlacements,l=n.padding,u=n.boundary,d=n.rootBoundary,f=n.altBoundary,p=n.flipVariations,m=p===void 0?!0:p,h=n.allowedAutoPlacements,g=t.options.placement,_=Yy(g)===g,v=c||(_||!m?[Ab(g)]:Jb(g)),y=[g].concat(v).reduce(function(e,n){return e.concat(Yy(n)===`auto`?qb(t,{placement:n,boundary:u,rootBoundary:d,padding:l,flipVariations:m,allowedAutoPlacements:h}):n)},[]),b=t.rects.reference,x=t.rects.popper,S=new Map,C=!0,w=y[0],T=0;T<y.length;T++){var E=y[T],ee=Yy(E),D=bb(E)===wy,O=[`top`,yy].indexOf(ee)>=0,k=O?`width`:`height`,A=Kb(t,{placement:E,boundary:u,rootBoundary:d,altBoundary:f,padding:l}),j=O?D?by:xy:D?yy:`top`;b[k]>x[k]&&(j=Ab(j));var te=Ab(j),ne=[];if(a&&ne.push(A[ee]<=0),s&&ne.push(A[j]<=0,A[te]<=0),ne.every(function(e){return e})){w=E,C=!1;break}S.set(E,ne)}if(C)for(var re=m?3:1,ie=function(e){var t=y.find(function(t){var n=S.get(t);if(n)return n.slice(0,e).every(function(e){return e})});if(t)return w=t,`break`},ae=re;ae>0&&ie(ae)!==`break`;ae--);t.placement!==w&&(t.modifiersData[r]._skip=!0,t.placement=w,t.reset=!0)}}var Xb={name:`flip`,enabled:!0,phase:`main`,fn:Yb,requiresIfExists:[`offset`],data:{_skip:!1}};function Zb(e,t,n){return n===void 0&&(n={x:0,y:0}),{top:e.top-t.height-n.y,right:e.right-t.width+n.x,bottom:e.bottom-t.height+n.y,left:e.left-t.width-n.x}}function Qb(e){return[`top`,by,yy,xy].some(function(t){return e[t]>=0})}function $b(e){var t=e.state,n=e.name,r=t.rects.reference,i=t.rects.popper,a=t.modifiersData.preventOverflow,o=Kb(t,{elementContext:`reference`}),s=Kb(t,{altBoundary:!0}),c=Zb(o,r),l=Zb(s,i,a),u=Qb(c),d=Qb(l);t.modifiersData[n]={referenceClippingOffsets:c,popperEscapeOffsets:l,isReferenceHidden:u,hasPopperEscaped:d},t.attributes.popper=Object.assign({},t.attributes.popper,{"data-popper-reference-hidden":u,"data-popper-escaped":d})}var ex={name:`hide`,enabled:!0,phase:`main`,requiresIfExists:[`preventOverflow`],fn:$b};function tx(e,t,n){var r=Yy(e),i=[`left`,`top`].indexOf(r)>=0?-1:1,a=typeof n==`function`?n(Object.assign({},t,{placement:e})):n,o=a[0],s=a[1];return o||=0,s=(s||0)*i,[`left`,`right`].indexOf(r)>=0?{x:s,y:o}:{x:o,y:s}}function nx(e){var t=e.state,n=e.options,r=e.name,i=n.offset,a=i===void 0?[0,0]:i,o=Ay.reduce(function(e,n){return e[n]=tx(n,t.rects,a),e},{}),s=o[t.placement],c=s.x,l=s.y;t.modifiersData.popperOffsets!=null&&(t.modifiersData.popperOffsets.x+=c,t.modifiersData.popperOffsets.y+=l),t.modifiersData[r]=o}var rx={name:`offset`,enabled:!0,phase:`main`,requires:[`popperOffsets`],fn:nx};function ix(e){var t=e.state,n=e.name;t.modifiersData[n]=Gb({reference:t.rects.reference,element:t.rects.popper,strategy:`absolute`,placement:t.placement})}var ax={name:`popperOffsets`,enabled:!0,phase:`read`,fn:ix,data:{}};function ox(e){return e===`x`?`y`:`x`}function sx(e){var t=e.state,n=e.options,r=e.name,i=n.mainAxis,a=i===void 0?!0:i,o=n.altAxis,s=o===void 0?!1:o,c=n.boundary,l=n.rootBoundary,u=n.altBoundary,d=n.padding,f=n.tether,p=f===void 0?!0:f,m=n.tetherOffset,h=m===void 0?0:m,g=Kb(t,{boundary:c,rootBoundary:l,padding:d,altBoundary:u}),_=Yy(t.placement),v=bb(t.placement),y=!v,b=q(_),x=ox(b),S=t.modifiersData.popperOffsets,C=t.rects.reference,w=t.rects.popper,T=typeof h==`function`?h(Object.assign({},t.rects,{placement:t.placement})):h,E=typeof T==`number`?{mainAxis:T,altAxis:T}:Object.assign({mainAxis:0,altAxis:0},T),ee=t.modifiersData.offset?t.modifiersData.offset[t.placement]:null,D={x:0,y:0};if(S){if(a){var O=b===`y`?`top`:xy,k=b===`y`?yy:by,A=b===`y`?`height`:`width`,j=S[b],te=j+g[O],ne=j-g[k],re=p?-w[A]/2:0,ie=v===`start`?C[A]:w[A],ae=v===`start`?-w[A]:-C[A],M=t.elements.arrow,oe=p&&M?nb(M):{width:0,height:0},se=t.modifiersData[`arrow#persistent`]?t.modifiersData[`arrow#persistent`].padding:pb(),ce=se[O],le=se[k],ue=db(0,C[A],oe[A]),de=y?C[A]/2-re-ue-ce-E.mainAxis:ie-ue-ce-E.mainAxis,fe=y?-C[A]/2+re+ue+le+E.mainAxis:ae+ue+le+E.mainAxis,N=t.elements.arrow&&ub(t.elements.arrow),pe=N?b===`y`?N.clientTop||0:N.clientLeft||0:0,me=ee?.[b]??0,he=j+de-me-pe,ge=j+fe-me,_e=db(p?Zy(te,he):te,j,p?Xy(ne,ge):ne);S[b]=_e,D[b]=_e-j}if(s){var P=b===`x`?`top`:xy,ve=b===`x`?yy:by,F=S[x],ye=x===`y`?`height`:`width`,be=F+g[P],I=F-g[ve],L=[`top`,xy].indexOf(_)!==-1,xe=ee?.[x]??0,R=L?be:F-C[ye]-w[ye]-xe+E.altAxis,z=L?F+C[ye]+w[ye]-xe-E.altAxis:I,Se=p&&L?fb(R,F,z):db(p?R:be,F,p?z:I);S[x]=Se,D[x]=Se-F}t.modifiersData[r]=D}}var cx={name:`preventOverflow`,enabled:!0,phase:`main`,fn:sx,requiresIfExists:[`offset`]};function lx(e){return{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}}function ux(e){return e===Hy(e)||!Wy(e)?Nb(e):lx(e)}function dx(e){var t=e.getBoundingClientRect(),n=Qy(t.width)/e.offsetWidth||1,r=Qy(t.height)/e.offsetHeight||1;return n!==1||r!==1}function fx(e,t,n){n===void 0&&(n=!1);var r=Wy(t),i=Wy(t)&&dx(t),a=ob(t),o=tb(e,i,n),s={scrollLeft:0,scrollTop:0},c={x:0,y:0};return(r||!r&&!n)&&((Vy(t)!==`body`||Lb(a))&&(s=ux(t)),Wy(t)?(c=tb(t,!0),c.x+=t.clientLeft,c.y+=t.clientTop):a&&(c.x=Pb(a))),{x:o.left+s.scrollLeft-c.x,y:o.top+s.scrollTop-c.y,width:o.width,height:o.height}}function px(e){var t=new Map,n=new Set,r=[];e.forEach(function(e){t.set(e.name,e)});function i(e){n.add(e.name),[].concat(e.requires||[],e.requiresIfExists||[]).forEach(function(e){if(!n.has(e)){var r=t.get(e);r&&i(r)}}),r.push(e)}return e.forEach(function(e){n.has(e.name)||i(e)}),r}function mx(e){var t=px(e);return By.reduce(function(e,n){return e.concat(t.filter(function(e){return e.phase===n}))},[])}function hx(e){var t;return function(){return t||=new Promise(function(n){Promise.resolve().then(function(){t=void 0,n(e())})}),t}}function gx(e){var t=e.reduce(function(e,t){var n=e[t.name];return e[t.name]=n?Object.assign({},n,t,{options:Object.assign({},n.options,t.options),data:Object.assign({},n.data,t.data)}):t,e},{});return Object.keys(t).map(function(e){return t[e]})}var _x={placement:`bottom`,modifiers:[],strategy:`absolute`};function vx(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return!t.some(function(e){return!(e&&typeof e.getBoundingClientRect==`function`)})}function yx(e){e===void 0&&(e={});var t=e,n=t.defaultModifiers,r=n===void 0?[]:n,i=t.defaultOptions,a=i===void 0?_x:i;return function(e,t,n){n===void 0&&(n=a);var i={placement:`bottom`,orderedModifiers:[],options:Object.assign({},_x,a),modifiersData:{},elements:{reference:e,popper:t},attributes:{},styles:{}},o=[],s=!1,c={state:i,setOptions:function(n){var o=typeof n==`function`?n(i.options):n;u(),i.options=Object.assign({},a,i.options,o),i.scrollParents={reference:Uy(e)?zb(e):e.contextElement?zb(e.contextElement):[],popper:zb(t)};var s=mx(gx([].concat(r,i.options.modifiers)));return i.orderedModifiers=s.filter(function(e){return e.enabled}),l(),c.update()},forceUpdate:function(){if(!s){var e=i.elements,t=e.reference,n=e.popper;if(vx(t,n)){i.rects={reference:fx(t,ub(n),i.options.strategy===`fixed`),popper:nb(n)},i.reset=!1,i.placement=i.options.placement,i.orderedModifiers.forEach(function(e){return i.modifiersData[e.name]=Object.assign({},e.data)});for(var r=0;r<i.orderedModifiers.length;r++){if(i.reset===!0){i.reset=!1,r=-1;continue}var a=i.orderedModifiers[r],o=a.fn,l=a.options,u=l===void 0?{}:l,d=a.name;typeof o==`function`&&(i=o({state:i,options:u,name:d,instance:c})||i)}}}},update:hx(function(){return new Promise(function(e){c.forceUpdate(),e(i)})}),destroy:function(){u(),s=!0}};if(!vx(e,t))return c;c.setOptions(n).then(function(e){!s&&n.onFirstUpdate&&n.onFirstUpdate(e)});function l(){i.orderedModifiers.forEach(function(e){var t=e.name,n=e.options,r=n===void 0?{}:n,a=e.effect;if(typeof a==`function`){var s=a({state:i,name:t,instance:c,options:r});o.push(s||function(){})}})}function u(){o.forEach(function(e){return e()}),o=[]}return c}}var bx=yx(),xx=yx({defaultModifiers:[Ob,ax,Tb,Jy]}),Sx=yx({defaultModifiers:[Ob,ax,Tb,Jy,rx,Xb,cx,yb,ex]}),Cx=s({afterMain:()=>Iy,afterRead:()=>Ny,afterWrite:()=>zy,applyStyles:()=>Jy,arrow:()=>yb,auto:()=>Sy,basePlacements:()=>Cy,beforeMain:()=>Py,beforeRead:()=>jy,beforeWrite:()=>Ly,bottom:()=>yy,clippingParents:()=>Ty,computeStyles:()=>Tb,createPopper:()=>Sx,createPopperBase:()=>bx,createPopperLite:()=>xx,detectOverflow:()=>Kb,end:()=>`end`,eventListeners:()=>Ob,flip:()=>Xb,hide:()=>ex,left:()=>xy,main:()=>Fy,modifierPhases:()=>By,offset:()=>rx,placements:()=>Ay,popper:()=>Dy,popperGenerator:()=>yx,popperOffsets:()=>ax,preventOverflow:()=>cx,read:()=>My,reference:()=>Oy,right:()=>by,start:()=>wy,top:()=>`top`,variationPlacements:()=>ky,viewport:()=>Ey,write:()=>Ry}),wx=new Map,Tx={set(e,t,n){wx.has(e)||wx.set(e,new Map);let r=wx.get(e);if(!r.has(t)&&r.size!==0){console.error(`Bootstrap doesn't allow more than one instance per element. Bound instance: ${Array.from(r.keys())[0]}.`);return}r.set(t,n)},get(e,t){return wx.has(e)&&wx.get(e).get(t)||null},remove(e,t){if(!wx.has(e))return;let n=wx.get(e);n.delete(t),n.size===0&&wx.delete(e)}},Ex=1e6,Dx=1e3,Ox=`transitionend`,kx=e=>(e&&window.CSS&&window.CSS.escape&&(e=e.replace(/#([^\s"#']+)/g,(e,t)=>`#${CSS.escape(t)}`)),e),Ax=e=>e==null?`${e}`:Object.prototype.toString.call(e).match(/\s([a-z]+)/i)[1].toLowerCase(),jx=e=>{do e+=Math.floor(Math.random()*Ex);while(document.getElementById(e));return e},Mx=e=>{if(!e)return 0;let{transitionDuration:t,transitionDelay:n}=window.getComputedStyle(e);return!Number.parseFloat(t)&&!Number.parseFloat(n)?0:(t=t.split(`,`)[0],n=n.split(`,`)[0],(Number.parseFloat(t)+Number.parseFloat(n))*Dx)},Nx=e=>{e.dispatchEvent(new Event(Ox))},Px=e=>!e||typeof e!=`object`?!1:(e.jquery!==void 0&&(e=e[0]),e.nodeType!==void 0),Fx=e=>Px(e)?e.jquery?e[0]:e:typeof e==`string`&&e.length>0?document.querySelector(kx(e)):null,Ix=e=>{if(!Px(e)||e.getClientRects().length===0)return!1;let t=getComputedStyle(e).getPropertyValue(`visibility`)===`visible`,n=e.closest(`details:not([open])`);if(!n)return t;if(n!==e){let t=e.closest(`summary`);if(t&&t.parentNode!==n||t===null)return!1}return t},Lx=e=>!e||e.nodeType!==Node.ELEMENT_NODE||e.classList.contains(`disabled`)?!0:e.disabled===void 0?e.hasAttribute(`disabled`)&&e.getAttribute(`disabled`)!==`false`:e.disabled,Rx=e=>{if(!document.documentElement.attachShadow)return null;if(typeof e.getRootNode==`function`){let t=e.getRootNode();return t instanceof ShadowRoot?t:null}return e instanceof ShadowRoot?e:e.parentNode?Rx(e.parentNode):null},zx=()=>{},Bx=e=>{e.offsetHeight},Vx=()=>window.jQuery&&!document.body.hasAttribute(`data-bs-no-jquery`)?window.jQuery:null,Hx=[],Ux=e=>{document.readyState===`loading`?(Hx.length||document.addEventListener(`DOMContentLoaded`,()=>{for(let e of Hx)e()}),Hx.push(e)):e()},Wx=()=>document.documentElement.dir===`rtl`,Gx=e=>{Ux(()=>{let t=Vx();if(t){let n=e.NAME,r=t.fn[n];t.fn[n]=e.jQueryInterface,t.fn[n].Constructor=e,t.fn[n].noConflict=()=>(t.fn[n]=r,e.jQueryInterface)}})},Kx=(e,t=[],n=e)=>typeof e==`function`?e.call(...t):n,qx=(e,t,n=!0)=>{if(!n){Kx(e);return}let r=Mx(t)+5,i=!1,a=({target:n})=>{n===t&&(i=!0,t.removeEventListener(Ox,a),Kx(e))};t.addEventListener(Ox,a),setTimeout(()=>{i||Nx(t)},r)},Jx=(e,t,n,r)=>{let i=e.length,a=e.indexOf(t);return a===-1?!n&&r?e[i-1]:e[0]:(a+=n?1:-1,r&&(a=(a+i)%i),e[Math.max(0,Math.min(a,i-1))])},Yx=/[^.]*(?=\..*)\.|.*/,Xx=/\..*/,Zx=/::\d+$/,Qx={},$x=1,eS={mouseenter:`mouseover`,mouseleave:`mouseout`},tS=new Set(`click.dblclick.mouseup.mousedown.contextmenu.mousewheel.DOMMouseScroll.mouseover.mouseout.mousemove.selectstart.selectend.keydown.keypress.keyup.orientationchange.touchstart.touchmove.touchend.touchcancel.pointerdown.pointermove.pointerup.pointerleave.pointercancel.gesturestart.gesturechange.gestureend.focus.blur.change.reset.select.submit.focusin.focusout.load.unload.beforeunload.resize.move.DOMContentLoaded.readystatechange.error.abort.scroll`.split(`.`));function nS(e,t){return t&&`${t}::${$x++}`||e.uidEvent||$x++}function rS(e){let t=nS(e);return e.uidEvent=t,Qx[t]=Qx[t]||{},Qx[t]}function iS(e,t){return function n(r){return pS(r,{delegateTarget:e}),n.oneOff&&fS.off(e,r.type,t),t.apply(e,[r])}}function aS(e,t,n){return function r(i){let a=e.querySelectorAll(t);for(let{target:o}=i;o&&o!==this;o=o.parentNode)for(let s of a)if(s===o)return pS(i,{delegateTarget:o}),r.oneOff&&fS.off(e,i.type,t,n),n.apply(o,[i])}}function oS(e,t,n=null){return Object.values(e).find(e=>e.callable===t&&e.delegationSelector===n)}function sS(e,t,n){let r=typeof t==`string`,i=r?n:t||n,a=dS(e);return tS.has(a)||(a=e),[r,i,a]}function cS(e,t,n,r,i){if(typeof t!=`string`||!e)return;let[a,o,s]=sS(t,n,r);t in eS&&(o=(e=>function(t){if(!t.relatedTarget||t.relatedTarget!==t.delegateTarget&&!t.delegateTarget.contains(t.relatedTarget))return e.call(this,t)})(o));let c=rS(e),l=c[s]||(c[s]={}),u=oS(l,o,a?n:null);if(u){u.oneOff=u.oneOff&&i;return}let d=nS(o,t.replace(Yx,``)),f=a?aS(e,n,o):iS(e,o);f.delegationSelector=a?n:null,f.callable=o,f.oneOff=i,f.uidEvent=d,l[d]=f,e.addEventListener(s,f,a)}function lS(e,t,n,r,i){let a=oS(t[n],r,i);a&&(e.removeEventListener(n,a,!!i),delete t[n][a.uidEvent])}function uS(e,t,n,r){let i=t[n]||{};for(let[a,o]of Object.entries(i))a.includes(r)&&lS(e,t,n,o.callable,o.delegationSelector)}function dS(e){return e=e.replace(Xx,``),eS[e]||e}var fS={on(e,t,n,r){cS(e,t,n,r,!1)},one(e,t,n,r){cS(e,t,n,r,!0)},off(e,t,n,r){if(typeof t!=`string`||!e)return;let[i,a,o]=sS(t,n,r),s=o!==t,c=rS(e),l=c[o]||{},u=t.startsWith(`.`);if(a!==void 0){if(!Object.keys(l).length)return;lS(e,c,o,a,i?n:null);return}if(u)for(let n of Object.keys(c))uS(e,c,n,t.slice(1));for(let[n,r]of Object.entries(l)){let i=n.replace(Zx,``);(!s||t.includes(i))&&lS(e,c,o,r.callable,r.delegationSelector)}},trigger(e,t,n){if(typeof t!=`string`||!e)return null;let r=Vx(),i=t!==dS(t),a=null,o=!0,s=!0,c=!1;i&&r&&(a=r.Event(t,n),r(e).trigger(a),o=!a.isPropagationStopped(),s=!a.isImmediatePropagationStopped(),c=a.isDefaultPrevented());let l=pS(new Event(t,{bubbles:o,cancelable:!0}),n);return c&&l.preventDefault(),s&&e.dispatchEvent(l),l.defaultPrevented&&a&&a.preventDefault(),l}};function pS(e,t={}){for(let[n,r]of Object.entries(t))try{e[n]=r}catch{Object.defineProperty(e,n,{configurable:!0,get(){return r}})}return e}function mS(e){if(e===`true`)return!0;if(e===`false`)return!1;if(e===Number(e).toString())return Number(e);if(e===``||e===`null`)return null;if(typeof e!=`string`)return e;try{return JSON.parse(decodeURIComponent(e))}catch{return e}}function hS(e){return e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}var gS={setDataAttribute(e,t,n){e.setAttribute(`data-bs-${hS(t)}`,n)},removeDataAttribute(e,t){e.removeAttribute(`data-bs-${hS(t)}`)},getDataAttributes(e){if(!e)return{};let t={},n=Object.keys(e.dataset).filter(e=>e.startsWith(`bs`)&&!e.startsWith(`bsConfig`));for(let r of n){let n=r.replace(/^bs/,``);n=n.charAt(0).toLowerCase()+n.slice(1),t[n]=mS(e.dataset[r])}return t},getDataAttribute(e,t){return mS(e.getAttribute(`data-bs-${hS(t)}`))}},_S=class{static get Default(){return{}}static get DefaultType(){return{}}static get NAME(){throw Error(`You have to implement the static method "NAME", for each component!`)}_getConfig(e){return e=this._mergeConfigObj(e),e=this._configAfterMerge(e),this._typeCheckConfig(e),e}_configAfterMerge(e){return e}_mergeConfigObj(e,t){let n=Px(t)?gS.getDataAttribute(t,`config`):{};return{...this.constructor.Default,...typeof n==`object`?n:{},...Px(t)?gS.getDataAttributes(t):{},...typeof e==`object`?e:{}}}_typeCheckConfig(e,t=this.constructor.DefaultType){for(let[n,r]of Object.entries(t)){let t=e[n],i=Px(t)?`element`:Ax(t);if(!new RegExp(r).test(i))throw TypeError(`${this.constructor.NAME.toUpperCase()}: Option "${n}" provided type "${i}" but expected type "${r}".`)}}},vS=`5.3.8`,yS=class extends _S{constructor(e,t){super(),e=Fx(e),e&&(this._element=e,this._config=this._getConfig(t),Tx.set(this._element,this.constructor.DATA_KEY,this))}dispose(){Tx.remove(this._element,this.constructor.DATA_KEY),fS.off(this._element,this.constructor.EVENT_KEY);for(let e of Object.getOwnPropertyNames(this))this[e]=null}_queueCallback(e,t,n=!0){qx(e,t,n)}_getConfig(e){return e=this._mergeConfigObj(e,this._element),e=this._configAfterMerge(e),this._typeCheckConfig(e),e}static getInstance(e){return Tx.get(Fx(e),this.DATA_KEY)}static getOrCreateInstance(e,t={}){return this.getInstance(e)||new this(e,typeof t==`object`?t:null)}static get VERSION(){return vS}static get DATA_KEY(){return`bs.${this.NAME}`}static get EVENT_KEY(){return`.${this.DATA_KEY}`}static eventName(e){return`${e}${this.EVENT_KEY}`}},bS=e=>{let t=e.getAttribute(`data-bs-target`);if(!t||t===`#`){let n=e.getAttribute(`href`);if(!n||!n.includes(`#`)&&!n.startsWith(`.`))return null;n.includes(`#`)&&!n.startsWith(`#`)&&(n=`#${n.split(`#`)[1]}`),t=n&&n!==`#`?n.trim():null}return t?t.split(`,`).map(e=>kx(e)).join(`,`):null},xS={find(e,t=document.documentElement){return[].concat(...Element.prototype.querySelectorAll.call(t,e))},findOne(e,t=document.documentElement){return Element.prototype.querySelector.call(t,e)},children(e,t){return[].concat(...e.children).filter(e=>e.matches(t))},parents(e,t){let n=[],r=e.parentNode.closest(t);for(;r;)n.push(r),r=r.parentNode.closest(t);return n},prev(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return[n];n=n.previousElementSibling}return[]},next(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return[n];n=n.nextElementSibling}return[]},focusableChildren(e){let t=[`a`,`button`,`input`,`textarea`,`select`,`details`,`[tabindex]`,`[contenteditable="true"]`].map(e=>`${e}:not([tabindex^="-"])`).join(`,`);return this.find(t,e).filter(e=>!Lx(e)&&Ix(e))},getSelectorFromElement(e){let t=bS(e);return t&&xS.findOne(t)?t:null},getElementFromSelector(e){let t=bS(e);return t?xS.findOne(t):null},getMultipleElementsFromSelector(e){let t=bS(e);return t?xS.find(t):[]}},SS=(e,t=`hide`)=>{let n=`click.dismiss${e.EVENT_KEY}`,r=e.NAME;fS.on(document,n,`[data-bs-dismiss="${r}"]`,function(n){if([`A`,`AREA`].includes(this.tagName)&&n.preventDefault(),Lx(this))return;let i=xS.getElementFromSelector(this)||this.closest(`.${r}`);e.getOrCreateInstance(i)[t]()})},CS=`alert`,wS=`.bs.alert`,TS=`close${wS}`,ES=`closed${wS}`,DS=`fade`,OS=`show`,kS=class e extends yS{static get NAME(){return CS}close(){if(fS.trigger(this._element,TS).defaultPrevented)return;this._element.classList.remove(OS);let e=this._element.classList.contains(DS);this._queueCallback(()=>this._destroyElement(),this._element,e)}_destroyElement(){this._element.remove(),fS.trigger(this._element,ES),this.dispose()}static jQueryInterface(t){return this.each(function(){let n=e.getOrCreateInstance(this);if(typeof t==`string`){if(n[t]===void 0||t.startsWith(`_`)||t===`constructor`)throw TypeError(`No method named "${t}"`);n[t](this)}})}};SS(kS,`close`),Gx(kS);var AS=`button`,jS=`.bs.button`,MS=`.data-api`,NS=`active`,PS=`[data-bs-toggle="button"]`,FS=`click${jS}${MS}`,IS=class e extends yS{static get NAME(){return AS}toggle(){this._element.setAttribute(`aria-pressed`,this._element.classList.toggle(NS))}static jQueryInterface(t){return this.each(function(){let n=e.getOrCreateInstance(this);t===`toggle`&&n[t]()})}};fS.on(document,FS,PS,e=>{e.preventDefault();let t=e.target.closest(PS);IS.getOrCreateInstance(t).toggle()}),Gx(IS);var LS=`swipe`,RS=`.bs.swipe`,zS=`touchstart${RS}`,BS=`touchmove${RS}`,VS=`touchend${RS}`,HS=`pointerdown${RS}`,US=`pointerup${RS}`,WS=`touch`,GS=`pen`,KS=`pointer-event`,qS=40,JS={endCallback:null,leftCallback:null,rightCallback:null},YS={endCallback:`(function|null)`,leftCallback:`(function|null)`,rightCallback:`(function|null)`},XS=class e extends _S{constructor(t,n){super(),this._element=t,!(!t||!e.isSupported())&&(this._config=this._getConfig(n),this._deltaX=0,this._supportPointerEvents=!!window.PointerEvent,this._initEvents())}static get Default(){return JS}static get DefaultType(){return YS}static get NAME(){return LS}dispose(){fS.off(this._element,RS)}_start(e){if(!this._supportPointerEvents){this._deltaX=e.touches[0].clientX;return}this._eventIsPointerPenTouch(e)&&(this._deltaX=e.clientX)}_end(e){this._eventIsPointerPenTouch(e)&&(this._deltaX=e.clientX-this._deltaX),this._handleSwipe(),Kx(this._config.endCallback)}_move(e){this._deltaX=e.touches&&e.touches.length>1?0:e.touches[0].clientX-this._deltaX}_handleSwipe(){let e=Math.abs(this._deltaX);if(e<=qS)return;let t=e/this._deltaX;this._deltaX=0,t&&Kx(t>0?this._config.rightCallback:this._config.leftCallback)}_initEvents(){this._supportPointerEvents?(fS.on(this._element,HS,e=>this._start(e)),fS.on(this._element,US,e=>this._end(e)),this._element.classList.add(KS)):(fS.on(this._element,zS,e=>this._start(e)),fS.on(this._element,BS,e=>this._move(e)),fS.on(this._element,VS,e=>this._end(e)))}_eventIsPointerPenTouch(e){return this._supportPointerEvents&&(e.pointerType===GS||e.pointerType===WS)}static isSupported(){return`ontouchstart`in document.documentElement||navigator.maxTouchPoints>0}},ZS=`carousel`,QS=`.bs.carousel`,$S=`.data-api`,eC=`ArrowLeft`,tC=`ArrowRight`,nC=500,rC=`next`,iC=`prev`,aC=`left`,oC=`right`,sC=`slide${QS}`,cC=`slid${QS}`,lC=`keydown${QS}`,uC=`mouseenter${QS}`,dC=`mouseleave${QS}`,fC=`dragstart${QS}`,pC=`load${QS}${$S}`,mC=`click${QS}${$S}`,hC=`carousel`,gC=`active`,_C=`slide`,vC=`carousel-item-end`,yC=`carousel-item-start`,bC=`carousel-item-next`,xC=`carousel-item-prev`,SC=`.active`,CC=`.carousel-item`,wC=`.active.carousel-item`,TC=`.carousel-item img`,EC=`.carousel-indicators`,DC=`[data-bs-slide], [data-bs-slide-to]`,OC=`[data-bs-ride="carousel"]`,kC={[eC]:oC,[tC]:aC},AC={interval:5e3,keyboard:!0,pause:`hover`,ride:!1,touch:!0,wrap:!0},jC={interval:`(number|boolean)`,keyboard:`boolean`,pause:`(string|boolean)`,ride:`(boolean|string)`,touch:`boolean`,wrap:`boolean`},MC=class e extends yS{constructor(e,t){super(e,t),this._interval=null,this._activeElement=null,this._isSliding=!1,this.touchTimeout=null,this._swipeHelper=null,this._indicatorsElement=xS.findOne(EC,this._element),this._addEventListeners(),this._config.ride===hC&&this.cycle()}static get Default(){return AC}static get DefaultType(){return jC}static get NAME(){return ZS}next(){this._slide(rC)}nextWhenVisible(){!document.hidden&&Ix(this._element)&&this.next()}prev(){this._slide(iC)}pause(){this._isSliding&&Nx(this._element),this._clearInterval()}cycle(){this._clearInterval(),this._updateInterval(),this._interval=setInterval(()=>this.nextWhenVisible(),this._config.interval)}_maybeEnableCycle(){if(this._config.ride){if(this._isSliding){fS.one(this._element,cC,()=>this.cycle());return}this.cycle()}}to(e){let t=this._getItems();if(e>t.length-1||e<0)return;if(this._isSliding){fS.one(this._element,cC,()=>this.to(e));return}let n=this._getItemIndex(this._getActive());if(n===e)return;let r=e>n?rC:iC;this._slide(r,t[e])}dispose(){this._swipeHelper&&this._swipeHelper.dispose(),super.dispose()}_configAfterMerge(e){return e.defaultInterval=e.interval,e}_addEventListeners(){this._config.keyboard&&fS.on(this._element,lC,e=>this._keydown(e)),this._config.pause===`hover`&&(fS.on(this._element,uC,()=>this.pause()),fS.on(this._element,dC,()=>this._maybeEnableCycle())),this._config.touch&&XS.isSupported()&&this._addTouchEventListeners()}_addTouchEventListeners(){for(let e of xS.find(TC,this._element))fS.on(e,fC,e=>e.preventDefault());let e={leftCallback:()=>this._slide(this._directionToOrder(aC)),rightCallback:()=>this._slide(this._directionToOrder(oC)),endCallback:()=>{this._config.pause===`hover`&&(this.pause(),this.touchTimeout&&clearTimeout(this.touchTimeout),this.touchTimeout=setTimeout(()=>this._maybeEnableCycle(),nC+this._config.interval))}};this._swipeHelper=new XS(this._element,e)}_keydown(e){if(/input|textarea/i.test(e.target.tagName))return;let t=kC[e.key];t&&(e.preventDefault(),this._slide(this._directionToOrder(t)))}_getItemIndex(e){return this._getItems().indexOf(e)}_setActiveIndicatorElement(e){if(!this._indicatorsElement)return;let t=xS.findOne(SC,this._indicatorsElement);t.classList.remove(gC),t.removeAttribute(`aria-current`);let n=xS.findOne(`[data-bs-slide-to="${e}"]`,this._indicatorsElement);n&&(n.classList.add(gC),n.setAttribute(`aria-current`,`true`))}_updateInterval(){let e=this._activeElement||this._getActive();if(!e)return;let t=Number.parseInt(e.getAttribute(`data-bs-interval`),10);this._config.interval=t||this._config.defaultInterval}_slide(e,t=null){if(this._isSliding)return;let n=this._getActive(),r=e===rC,i=t||Jx(this._getItems(),n,r,this._config.wrap);if(i===n)return;let a=this._getItemIndex(i),o=t=>fS.trigger(this._element,t,{relatedTarget:i,direction:this._orderToDirection(e),from:this._getItemIndex(n),to:a});if(o(sC).defaultPrevented||!n||!i)return;let s=!!this._interval;this.pause(),this._isSliding=!0,this._setActiveIndicatorElement(a),this._activeElement=i;let c=r?yC:vC,l=r?bC:xC;i.classList.add(l),Bx(i),n.classList.add(c),i.classList.add(c),this._queueCallback(()=>{i.classList.remove(c,l),i.classList.add(gC),n.classList.remove(gC,l,c),this._isSliding=!1,o(cC)},n,this._isAnimated()),s&&this.cycle()}_isAnimated(){return this._element.classList.contains(_C)}_getActive(){return xS.findOne(wC,this._element)}_getItems(){return xS.find(CC,this._element)}_clearInterval(){this._interval&&=(clearInterval(this._interval),null)}_directionToOrder(e){return Wx()?e===aC?iC:rC:e===aC?rC:iC}_orderToDirection(e){return Wx()?e===iC?aC:oC:e===iC?oC:aC}static jQueryInterface(t){return this.each(function(){let n=e.getOrCreateInstance(this,t);if(typeof t==`number`){n.to(t);return}if(typeof t==`string`){if(n[t]===void 0||t.startsWith(`_`)||t===`constructor`)throw TypeError(`No method named "${t}"`);n[t]()}})}};fS.on(document,mC,DC,function(e){let t=xS.getElementFromSelector(this);if(!t||!t.classList.contains(hC))return;e.preventDefault();let n=MC.getOrCreateInstance(t),r=this.getAttribute(`data-bs-slide-to`);if(r){n.to(r),n._maybeEnableCycle();return}if(gS.getDataAttribute(this,`slide`)===`next`){n.next(),n._maybeEnableCycle();return}n.prev(),n._maybeEnableCycle()}),fS.on(window,pC,()=>{let e=xS.find(OC);for(let t of e)MC.getOrCreateInstance(t)}),Gx(MC);var NC=`collapse`,PC=`.bs.collapse`,FC=`.data-api`,IC=`show${PC}`,LC=`shown${PC}`,RC=`hide${PC}`,zC=`hidden${PC}`,BC=`click${PC}${FC}`,VC=`show`,HC=`collapse`,UC=`collapsing`,WC=`collapsed`,GC=`:scope .${HC} .${HC}`,KC=`collapse-horizontal`,qC=`width`,JC=`height`,YC=`.collapse.show, .collapse.collapsing`,XC=`[data-bs-toggle="collapse"]`,ZC={parent:null,toggle:!0},QC={parent:`(null|element)`,toggle:`boolean`},$C=class e extends yS{constructor(e,t){super(e,t),this._isTransitioning=!1,this._triggerArray=[];let n=xS.find(XC);for(let e of n){let t=xS.getSelectorFromElement(e),n=xS.find(t).filter(e=>e===this._element);t!==null&&n.length&&this._triggerArray.push(e)}this._initializeChildren(),this._config.parent||this._addAriaAndCollapsedClass(this._triggerArray,this._isShown()),this._config.toggle&&this.toggle()}static get Default(){return ZC}static get DefaultType(){return QC}static get NAME(){return NC}toggle(){this._isShown()?this.hide():this.show()}show(){if(this._isTransitioning||this._isShown())return;let t=[];if(this._config.parent&&(t=this._getFirstLevelChildren(YC).filter(e=>e!==this._element).map(t=>e.getOrCreateInstance(t,{toggle:!1}))),t.length&&t[0]._isTransitioning||fS.trigger(this._element,IC).defaultPrevented)return;for(let e of t)e.hide();let n=this._getDimension();this._element.classList.remove(HC),this._element.classList.add(UC),this._element.style[n]=0,this._addAriaAndCollapsedClass(this._triggerArray,!0),this._isTransitioning=!0;let r=()=>{this._isTransitioning=!1,this._element.classList.remove(UC),this._element.classList.add(HC,VC),this._element.style[n]=``,fS.trigger(this._element,LC)},i=`scroll${n[0].toUpperCase()+n.slice(1)}`;this._queueCallback(r,this._element,!0),this._element.style[n]=`${this._element[i]}px`}hide(){if(this._isTransitioning||!this._isShown()||fS.trigger(this._element,RC).defaultPrevented)return;let e=this._getDimension();this._element.style[e]=`${this._element.getBoundingClientRect()[e]}px`,Bx(this._element),this._element.classList.add(UC),this._element.classList.remove(HC,VC);for(let e of this._triggerArray){let t=xS.getElementFromSelector(e);t&&!this._isShown(t)&&this._addAriaAndCollapsedClass([e],!1)}this._isTransitioning=!0;let t=()=>{this._isTransitioning=!1,this._element.classList.remove(UC),this._element.classList.add(HC),fS.trigger(this._element,zC)};this._element.style[e]=``,this._queueCallback(t,this._element,!0)}_isShown(e=this._element){return e.classList.contains(VC)}_configAfterMerge(e){return e.toggle=!!e.toggle,e.parent=Fx(e.parent),e}_getDimension(){return this._element.classList.contains(KC)?qC:JC}_initializeChildren(){if(!this._config.parent)return;let e=this._getFirstLevelChildren(XC);for(let t of e){let e=xS.getElementFromSelector(t);e&&this._addAriaAndCollapsedClass([t],this._isShown(e))}}_getFirstLevelChildren(e){let t=xS.find(GC,this._config.parent);return xS.find(e,this._config.parent).filter(e=>!t.includes(e))}_addAriaAndCollapsedClass(e,t){if(e.length)for(let n of e)n.classList.toggle(WC,!t),n.setAttribute(`aria-expanded`,t)}static jQueryInterface(t){let n={};return typeof t==`string`&&/show|hide/.test(t)&&(n.toggle=!1),this.each(function(){let r=e.getOrCreateInstance(this,n);if(typeof t==`string`){if(r[t]===void 0)throw TypeError(`No method named "${t}"`);r[t]()}})}};fS.on(document,BC,XC,function(e){(e.target.tagName===`A`||e.delegateTarget&&e.delegateTarget.tagName===`A`)&&e.preventDefault();for(let e of xS.getMultipleElementsFromSelector(this))$C.getOrCreateInstance(e,{toggle:!1}).toggle()}),Gx($C);var ew=`dropdown`,tw=`.bs.dropdown`,nw=`.data-api`,rw=`Escape`,iw=`Tab`,aw=`ArrowUp`,ow=`ArrowDown`,sw=2,cw=`hide${tw}`,lw=`hidden${tw}`,uw=`show${tw}`,dw=`shown${tw}`,fw=`click${tw}${nw}`,pw=`keydown${tw}${nw}`,mw=`keyup${tw}${nw}`,hw=`show`,gw=`dropup`,_w=`dropend`,vw=`dropstart`,yw=`dropup-center`,bw=`dropdown-center`,xw=`[data-bs-toggle="dropdown"]:not(.disabled):not(:disabled)`,Sw=`${xw}.${hw}`,Cw=`.dropdown-menu`,ww=`.navbar`,Tw=`.navbar-nav`,Ew=`.dropdown-menu .dropdown-item:not(.disabled):not(:disabled)`,Dw=Wx()?`top-end`:`top-start`,Ow=Wx()?`top-start`:`top-end`,kw=Wx()?`bottom-end`:`bottom-start`,Aw=Wx()?`bottom-start`:`bottom-end`,jw=Wx()?`left-start`:`right-start`,Mw=Wx()?`right-start`:`left-start`,Nw=`top`,Pw=`bottom`,Fw={autoClose:!0,boundary:`clippingParents`,display:`dynamic`,offset:[0,2],popperConfig:null,reference:`toggle`},Iw={autoClose:`(boolean|string)`,boundary:`(string|element)`,display:`string`,offset:`(array|string|function)`,popperConfig:`(null|object|function)`,reference:`(string|element|object)`},Lw=class e extends yS{constructor(e,t){super(e,t),this._popper=null,this._parent=this._element.parentNode,this._menu=xS.next(this._element,Cw)[0]||xS.prev(this._element,Cw)[0]||xS.findOne(Cw,this._parent),this._inNavbar=this._detectNavbar()}static get Default(){return Fw}static get DefaultType(){return Iw}static get NAME(){return ew}toggle(){return this._isShown()?this.hide():this.show()}show(){if(Lx(this._element)||this._isShown())return;let e={relatedTarget:this._element};if(!fS.trigger(this._element,uw,e).defaultPrevented){if(this._createPopper(),`ontouchstart`in document.documentElement&&!this._parent.closest(Tw))for(let e of[].concat(...document.body.children))fS.on(e,`mouseover`,zx);this._element.focus(),this._element.setAttribute(`aria-expanded`,!0),this._menu.classList.add(hw),this._element.classList.add(hw),fS.trigger(this._element,dw,e)}}hide(){if(Lx(this._element)||!this._isShown())return;let e={relatedTarget:this._element};this._completeHide(e)}dispose(){this._popper&&this._popper.destroy(),super.dispose()}update(){this._inNavbar=this._detectNavbar(),this._popper&&this._popper.update()}_completeHide(e){if(!fS.trigger(this._element,cw,e).defaultPrevented){if(`ontouchstart`in document.documentElement)for(let e of[].concat(...document.body.children))fS.off(e,`mouseover`,zx);this._popper&&this._popper.destroy(),this._menu.classList.remove(hw),this._element.classList.remove(hw),this._element.setAttribute(`aria-expanded`,`false`),gS.removeDataAttribute(this._menu,`popper`),fS.trigger(this._element,lw,e)}}_getConfig(e){if(e=super._getConfig(e),typeof e.reference==`object`&&!Px(e.reference)&&typeof e.reference.getBoundingClientRect!=`function`)throw TypeError(`${ew.toUpperCase()}: Option "reference" provided type "object" without a required "getBoundingClientRect" method.`);return e}_createPopper(){if(Cx===void 0)throw TypeError(`Bootstrap's dropdowns require Popper (https://popper.js.org/docs/v2/)`);let e=this._element;this._config.reference===`parent`?e=this._parent:Px(this._config.reference)?e=Fx(this._config.reference):typeof this._config.reference==`object`&&(e=this._config.reference);let t=this._getPopperConfig();this._popper=Sx(e,this._menu,t)}_isShown(){return this._menu.classList.contains(hw)}_getPlacement(){let e=this._parent;if(e.classList.contains(_w))return jw;if(e.classList.contains(vw))return Mw;if(e.classList.contains(yw))return Nw;if(e.classList.contains(bw))return Pw;let t=getComputedStyle(this._menu).getPropertyValue(`--bs-position`).trim()===`end`;return e.classList.contains(gw)?t?Ow:Dw:t?Aw:kw}_detectNavbar(){return this._element.closest(ww)!==null}_getOffset(){let{offset:e}=this._config;return typeof e==`string`?e.split(`,`).map(e=>Number.parseInt(e,10)):typeof e==`function`?t=>e(t,this._element):e}_getPopperConfig(){let e={placement:this._getPlacement(),modifiers:[{name:`preventOverflow`,options:{boundary:this._config.boundary}},{name:`offset`,options:{offset:this._getOffset()}}]};return(this._inNavbar||this._config.display===`static`)&&(gS.setDataAttribute(this._menu,`popper`,`static`),e.modifiers=[{name:`applyStyles`,enabled:!1}]),{...e,...Kx(this._config.popperConfig,[void 0,e])}}_selectMenuItem({key:e,target:t}){let n=xS.find(Ew,this._menu).filter(e=>Ix(e));n.length&&Jx(n,t,e===ow,!n.includes(t)).focus()}static jQueryInterface(t){return this.each(function(){let n=e.getOrCreateInstance(this,t);if(typeof t==`string`){if(n[t]===void 0)throw TypeError(`No method named "${t}"`);n[t]()}})}static clearMenus(t){if(t.button===sw||t.type===`keyup`&&t.key!==iw)return;let n=xS.find(Sw);for(let r of n){let n=e.getInstance(r);if(!n||n._config.autoClose===!1)continue;let i=t.composedPath(),a=i.includes(n._menu);if(i.includes(n._element)||n._config.autoClose===`inside`&&!a||n._config.autoClose===`outside`&&a||n._menu.contains(t.target)&&(t.type===`keyup`&&t.key===iw||/input|select|option|textarea|form/i.test(t.target.tagName)))continue;let o={relatedTarget:n._element};t.type===`click`&&(o.clickEvent=t),n._completeHide(o)}}static dataApiKeydownHandler(t){let n=/input|textarea/i.test(t.target.tagName),r=t.key===rw,i=[aw,ow].includes(t.key);if(!i&&!r||n&&!r)return;t.preventDefault();let a=this.matches(xw)?this:xS.prev(this,xw)[0]||xS.next(this,xw)[0]||xS.findOne(xw,t.delegateTarget.parentNode),o=e.getOrCreateInstance(a);if(i){t.stopPropagation(),o.show(),o._selectMenuItem(t);return}o._isShown()&&(t.stopPropagation(),o.hide(),a.focus())}};fS.on(document,pw,xw,Lw.dataApiKeydownHandler),fS.on(document,pw,Cw,Lw.dataApiKeydownHandler),fS.on(document,fw,Lw.clearMenus),fS.on(document,mw,Lw.clearMenus),fS.on(document,fw,xw,function(e){e.preventDefault(),Lw.getOrCreateInstance(this).toggle()}),Gx(Lw);var Rw=`backdrop`,zw=`fade`,Bw=`show`,Vw=`mousedown.bs.${Rw}`,Hw={className:`modal-backdrop`,clickCallback:null,isAnimated:!1,isVisible:!0,rootElement:`body`},Uw={className:`string`,clickCallback:`(function|null)`,isAnimated:`boolean`,isVisible:`boolean`,rootElement:`(element|string)`},Ww=class extends _S{constructor(e){super(),this._config=this._getConfig(e),this._isAppended=!1,this._element=null}static get Default(){return Hw}static get DefaultType(){return Uw}static get NAME(){return Rw}show(e){if(!this._config.isVisible){Kx(e);return}this._append();let t=this._getElement();this._config.isAnimated&&Bx(t),t.classList.add(Bw),this._emulateAnimation(()=>{Kx(e)})}hide(e){if(!this._config.isVisible){Kx(e);return}this._getElement().classList.remove(Bw),this._emulateAnimation(()=>{this.dispose(),Kx(e)})}dispose(){this._isAppended&&=(fS.off(this._element,Vw),this._element.remove(),!1)}_getElement(){if(!this._element){let e=document.createElement(`div`);e.className=this._config.className,this._config.isAnimated&&e.classList.add(zw),this._element=e}return this._element}_configAfterMerge(e){return e.rootElement=Fx(e.rootElement),e}_append(){if(this._isAppended)return;let e=this._getElement();this._config.rootElement.append(e),fS.on(e,Vw,()=>{Kx(this._config.clickCallback)}),this._isAppended=!0}_emulateAnimation(e){qx(e,this._getElement(),this._config.isAnimated)}},Gw=`focustrap`,Kw=`.bs.focustrap`,qw=`focusin${Kw}`,Jw=`keydown.tab${Kw}`,Yw=`Tab`,Xw=`forward`,Zw=`backward`,Qw={autofocus:!0,trapElement:null},$w={autofocus:`boolean`,trapElement:`element`},eT=class extends _S{constructor(e){super(),this._config=this._getConfig(e),this._isActive=!1,this._lastTabNavDirection=null}static get Default(){return Qw}static get DefaultType(){return $w}static get NAME(){return Gw}activate(){this._isActive||=(this._config.autofocus&&this._config.trapElement.focus(),fS.off(document,Kw),fS.on(document,qw,e=>this._handleFocusin(e)),fS.on(document,Jw,e=>this._handleKeydown(e)),!0)}deactivate(){this._isActive&&(this._isActive=!1,fS.off(document,Kw))}_handleFocusin(e){let{trapElement:t}=this._config;if(e.target===document||e.target===t||t.contains(e.target))return;let n=xS.focusableChildren(t);n.length===0?t.focus():this._lastTabNavDirection===Zw?n[n.length-1].focus():n[0].focus()}_handleKeydown(e){e.key===Yw&&(this._lastTabNavDirection=e.shiftKey?Zw:Xw)}},tT=`.fixed-top, .fixed-bottom, .is-fixed, .sticky-top`,nT=`.sticky-top`,rT=`padding-right`,iT=`margin-right`,aT=class{constructor(){this._element=document.body}getWidth(){let e=document.documentElement.clientWidth;return Math.abs(window.innerWidth-e)}hide(){let e=this.getWidth();this._disableOverFlow(),this._setElementAttributes(this._element,rT,t=>t+e),this._setElementAttributes(tT,rT,t=>t+e),this._setElementAttributes(nT,iT,t=>t-e)}reset(){this._resetElementAttributes(this._element,`overflow`),this._resetElementAttributes(this._element,rT),this._resetElementAttributes(tT,rT),this._resetElementAttributes(nT,iT)}isOverflowing(){return this.getWidth()>0}_disableOverFlow(){this._saveInitialAttribute(this._element,`overflow`),this._element.style.overflow=`hidden`}_setElementAttributes(e,t,n){let r=this.getWidth();this._applyManipulationCallback(e,e=>{if(e!==this._element&&window.innerWidth>e.clientWidth+r)return;this._saveInitialAttribute(e,t);let i=window.getComputedStyle(e).getPropertyValue(t);e.style.setProperty(t,`${n(Number.parseFloat(i))}px`)})}_saveInitialAttribute(e,t){let n=e.style.getPropertyValue(t);n&&gS.setDataAttribute(e,t,n)}_resetElementAttributes(e,t){this._applyManipulationCallback(e,e=>{let n=gS.getDataAttribute(e,t);if(n===null){e.style.removeProperty(t);return}gS.removeDataAttribute(e,t),e.style.setProperty(t,n)})}_applyManipulationCallback(e,t){if(Px(e)){t(e);return}for(let n of xS.find(e,this._element))t(n)}},oT=`modal`,sT=`.bs.modal`,cT=`.data-api`,lT=`Escape`,uT=`hide${sT}`,dT=`hidePrevented${sT}`,fT=`hidden${sT}`,pT=`show${sT}`,mT=`shown${sT}`,hT=`resize${sT}`,gT=`click.dismiss${sT}`,_T=`mousedown.dismiss${sT}`,vT=`keydown.dismiss${sT}`,yT=`click${sT}${cT}`,bT=`modal-open`,xT=`fade`,ST=`show`,CT=`modal-static`,wT=`.modal.show`,TT=`.modal-dialog`,ET=`.modal-body`,DT=`[data-bs-toggle="modal"]`,OT={backdrop:!0,focus:!0,keyboard:!0},kT={backdrop:`(boolean|string)`,focus:`boolean`,keyboard:`boolean`},AT=class e extends yS{constructor(e,t){super(e,t),this._dialog=xS.findOne(TT,this._element),this._backdrop=this._initializeBackDrop(),this._focustrap=this._initializeFocusTrap(),this._isShown=!1,this._isTransitioning=!1,this._scrollBar=new aT,this._addEventListeners()}static get Default(){return OT}static get DefaultType(){return kT}static get NAME(){return oT}toggle(e){return this._isShown?this.hide():this.show(e)}show(e){this._isShown||this._isTransitioning||fS.trigger(this._element,pT,{relatedTarget:e}).defaultPrevented||(this._isShown=!0,this._isTransitioning=!0,this._scrollBar.hide(),document.body.classList.add(bT),this._adjustDialog(),this._backdrop.show(()=>this._showElement(e)))}hide(){!this._isShown||this._isTransitioning||fS.trigger(this._element,uT).defaultPrevented||(this._isShown=!1,this._isTransitioning=!0,this._focustrap.deactivate(),this._element.classList.remove(ST),this._queueCallback(()=>this._hideModal(),this._element,this._isAnimated()))}dispose(){fS.off(window,sT),fS.off(this._dialog,sT),this._backdrop.dispose(),this._focustrap.deactivate(),super.dispose()}handleUpdate(){this._adjustDialog()}_initializeBackDrop(){return new Ww({isVisible:!!this._config.backdrop,isAnimated:this._isAnimated()})}_initializeFocusTrap(){return new eT({trapElement:this._element})}_showElement(e){document.body.contains(this._element)||document.body.append(this._element),this._element.style.display=`block`,this._element.removeAttribute(`aria-hidden`),this._element.setAttribute(`aria-modal`,!0),this._element.setAttribute(`role`,`dialog`),this._element.scrollTop=0;let t=xS.findOne(ET,this._dialog);t&&(t.scrollTop=0),Bx(this._element),this._element.classList.add(ST),this._queueCallback(()=>{this._config.focus&&this._focustrap.activate(),this._isTransitioning=!1,fS.trigger(this._element,mT,{relatedTarget:e})},this._dialog,this._isAnimated())}_addEventListeners(){fS.on(this._element,vT,e=>{if(e.key===lT){if(this._config.keyboard){this.hide();return}this._triggerBackdropTransition()}}),fS.on(window,hT,()=>{this._isShown&&!this._isTransitioning&&this._adjustDialog()}),fS.on(this._element,_T,e=>{fS.one(this._element,gT,t=>{if(!(this._element!==e.target||this._element!==t.target)){if(this._config.backdrop===`static`){this._triggerBackdropTransition();return}this._config.backdrop&&this.hide()}})})}_hideModal(){this._element.style.display=`none`,this._element.setAttribute(`aria-hidden`,!0),this._element.removeAttribute(`aria-modal`),this._element.removeAttribute(`role`),this._isTransitioning=!1,this._backdrop.hide(()=>{document.body.classList.remove(bT),this._resetAdjustments(),this._scrollBar.reset(),fS.trigger(this._element,fT)})}_isAnimated(){return this._element.classList.contains(xT)}_triggerBackdropTransition(){if(fS.trigger(this._element,dT).defaultPrevented)return;let e=this._element.scrollHeight>document.documentElement.clientHeight,t=this._element.style.overflowY;t===`hidden`||this._element.classList.contains(CT)||(e||(this._element.style.overflowY=`hidden`),this._element.classList.add(CT),this._queueCallback(()=>{this._element.classList.remove(CT),this._queueCallback(()=>{this._element.style.overflowY=t},this._dialog)},this._dialog),this._element.focus())}_adjustDialog(){let e=this._element.scrollHeight>document.documentElement.clientHeight,t=this._scrollBar.getWidth(),n=t>0;if(n&&!e){let e=Wx()?`paddingLeft`:`paddingRight`;this._element.style[e]=`${t}px`}if(!n&&e){let e=Wx()?`paddingRight`:`paddingLeft`;this._element.style[e]=`${t}px`}}_resetAdjustments(){this._element.style.paddingLeft=``,this._element.style.paddingRight=``}static jQueryInterface(t,n){return this.each(function(){let r=e.getOrCreateInstance(this,t);if(typeof t==`string`){if(r[t]===void 0)throw TypeError(`No method named "${t}"`);r[t](n)}})}};fS.on(document,yT,DT,function(e){let t=xS.getElementFromSelector(this);[`A`,`AREA`].includes(this.tagName)&&e.preventDefault(),fS.one(t,pT,e=>{e.defaultPrevented||fS.one(t,fT,()=>{Ix(this)&&this.focus()})});let n=xS.findOne(wT);n&&AT.getInstance(n).hide(),AT.getOrCreateInstance(t).toggle(this)}),SS(AT),Gx(AT);var jT=`offcanvas`,MT=`.bs.offcanvas`,NT=`.data-api`,PT=`load${MT}${NT}`,FT=`Escape`,IT=`show`,LT=`showing`,RT=`hiding`,zT=`offcanvas-backdrop`,BT=`.offcanvas.show`,VT=`show${MT}`,HT=`shown${MT}`,UT=`hide${MT}`,WT=`hidePrevented${MT}`,GT=`hidden${MT}`,KT=`resize${MT}`,qT=`click${MT}${NT}`,JT=`keydown.dismiss${MT}`,YT=`[data-bs-toggle="offcanvas"]`,XT={backdrop:!0,keyboard:!0,scroll:!1},ZT={backdrop:`(boolean|string)`,keyboard:`boolean`,scroll:`boolean`},QT=class e extends yS{constructor(e,t){super(e,t),this._isShown=!1,this._backdrop=this._initializeBackDrop(),this._focustrap=this._initializeFocusTrap(),this._addEventListeners()}static get Default(){return XT}static get DefaultType(){return ZT}static get NAME(){return jT}toggle(e){return this._isShown?this.hide():this.show(e)}show(e){this._isShown||fS.trigger(this._element,VT,{relatedTarget:e}).defaultPrevented||(this._isShown=!0,this._backdrop.show(),this._config.scroll||new aT().hide(),this._element.setAttribute(`aria-modal`,!0),this._element.setAttribute(`role`,`dialog`),this._element.classList.add(LT),this._queueCallback(()=>{(!this._config.scroll||this._config.backdrop)&&this._focustrap.activate(),this._element.classList.add(IT),this._element.classList.remove(LT),fS.trigger(this._element,HT,{relatedTarget:e})},this._element,!0))}hide(){!this._isShown||fS.trigger(this._element,UT).defaultPrevented||(this._focustrap.deactivate(),this._element.blur(),this._isShown=!1,this._element.classList.add(RT),this._backdrop.hide(),this._queueCallback(()=>{this._element.classList.remove(IT,RT),this._element.removeAttribute(`aria-modal`),this._element.removeAttribute(`role`),this._config.scroll||new aT().reset(),fS.trigger(this._element,GT)},this._element,!0))}dispose(){this._backdrop.dispose(),this._focustrap.deactivate(),super.dispose()}_initializeBackDrop(){let e=()=>{if(this._config.backdrop===`static`){fS.trigger(this._element,WT);return}this.hide()},t=!!this._config.backdrop;return new Ww({className:zT,isVisible:t,isAnimated:!0,rootElement:this._element.parentNode,clickCallback:t?e:null})}_initializeFocusTrap(){return new eT({trapElement:this._element})}_addEventListeners(){fS.on(this._element,JT,e=>{if(e.key===FT){if(this._config.keyboard){this.hide();return}fS.trigger(this._element,WT)}})}static jQueryInterface(t){return this.each(function(){let n=e.getOrCreateInstance(this,t);if(typeof t==`string`){if(n[t]===void 0||t.startsWith(`_`)||t===`constructor`)throw TypeError(`No method named "${t}"`);n[t](this)}})}};fS.on(document,qT,YT,function(e){let t=xS.getElementFromSelector(this);if([`A`,`AREA`].includes(this.tagName)&&e.preventDefault(),Lx(this))return;fS.one(t,GT,()=>{Ix(this)&&this.focus()});let n=xS.findOne(BT);n&&n!==t&&QT.getInstance(n).hide(),QT.getOrCreateInstance(t).toggle(this)}),fS.on(window,PT,()=>{for(let e of xS.find(BT))QT.getOrCreateInstance(e).show()}),fS.on(window,KT,()=>{for(let e of xS.find(`[aria-modal][class*=show][class*=offcanvas-]`))getComputedStyle(e).position!==`fixed`&&QT.getOrCreateInstance(e).hide()}),SS(QT),Gx(QT);var $T={"*":[`class`,`dir`,`id`,`lang`,`role`,/^aria-[\w-]*$/i],a:[`target`,`href`,`title`,`rel`],area:[],b:[],br:[],col:[],code:[],dd:[],div:[],dl:[],dt:[],em:[],hr:[],h1:[],h2:[],h3:[],h4:[],h5:[],h6:[],i:[],img:[`src`,`srcset`,`alt`,`title`,`width`,`height`],li:[],ol:[],p:[],pre:[],s:[],small:[],span:[],sub:[],sup:[],strong:[],u:[],ul:[]},eE=new Set([`background`,`cite`,`href`,`itemtype`,`longdesc`,`poster`,`src`,`xlink:href`]),tE=/^(?!javascript:)(?:[a-z0-9+.-]+:|[^&:/?#]*(?:[/?#]|$))/i,nE=(e,t)=>{let n=e.nodeName.toLowerCase();return t.includes(n)?eE.has(n)?!!tE.test(e.nodeValue):!0:t.filter(e=>e instanceof RegExp).some(e=>e.test(n))};function rE(e,t,n){if(!e.length)return e;if(n&&typeof n==`function`)return n(e);let r=new window.DOMParser().parseFromString(e,`text/html`),i=[].concat(...r.body.querySelectorAll(`*`));for(let e of i){let n=e.nodeName.toLowerCase();if(!Object.keys(t).includes(n)){e.remove();continue}let r=[].concat(...e.attributes),i=[].concat(t[`*`]||[],t[n]||[]);for(let t of r)nE(t,i)||e.removeAttribute(t.nodeName)}return r.body.innerHTML}var iE=`TemplateFactory`,aE={allowList:$T,content:{},extraClass:``,html:!1,sanitize:!0,sanitizeFn:null,template:`<div></div>`},oE={allowList:`object`,content:`object`,extraClass:`(string|function)`,html:`boolean`,sanitize:`boolean`,sanitizeFn:`(null|function)`,template:`string`},sE={entry:`(string|element|function|null)`,selector:`(string|element)`},cE=class extends _S{constructor(e){super(),this._config=this._getConfig(e)}static get Default(){return aE}static get DefaultType(){return oE}static get NAME(){return iE}getContent(){return Object.values(this._config.content).map(e=>this._resolvePossibleFunction(e)).filter(Boolean)}hasContent(){return this.getContent().length>0}changeContent(e){return this._checkContent(e),this._config.content={...this._config.content,...e},this}toHtml(){let e=document.createElement(`div`);e.innerHTML=this._maybeSanitize(this._config.template);for(let[t,n]of Object.entries(this._config.content))this._setContent(e,n,t);let t=e.children[0],n=this._resolvePossibleFunction(this._config.extraClass);return n&&t.classList.add(...n.split(` `)),t}_typeCheckConfig(e){super._typeCheckConfig(e),this._checkContent(e.content)}_checkContent(e){for(let[t,n]of Object.entries(e))super._typeCheckConfig({selector:t,entry:n},sE)}_setContent(e,t,n){let r=xS.findOne(n,e);if(r){if(t=this._resolvePossibleFunction(t),!t){r.remove();return}if(Px(t)){this._putElementInTemplate(Fx(t),r);return}if(this._config.html){r.innerHTML=this._maybeSanitize(t);return}r.textContent=t}}_maybeSanitize(e){return this._config.sanitize?rE(e,this._config.allowList,this._config.sanitizeFn):e}_resolvePossibleFunction(e){return Kx(e,[void 0,this])}_putElementInTemplate(e,t){if(this._config.html){t.innerHTML=``,t.append(e);return}t.textContent=e.textContent}},lE=`tooltip`,uE=new Set([`sanitize`,`allowList`,`sanitizeFn`]),dE=`fade`,fE=`modal`,pE=`show`,mE=`.tooltip-inner`,hE=`.${fE}`,gE=`hide.bs.modal`,_E=`hover`,vE=`focus`,yE=`click`,bE=`manual`,xE=`hide`,SE=`hidden`,CE=`show`,wE=`shown`,TE=`inserted`,EE=`click`,DE=`focusin`,OE=`focusout`,kE=`mouseenter`,AE=`mouseleave`,jE={AUTO:`auto`,TOP:`top`,RIGHT:Wx()?`left`:`right`,BOTTOM:`bottom`,LEFT:Wx()?`right`:`left`},ME={allowList:$T,animation:!0,boundary:`clippingParents`,container:!1,customClass:``,delay:0,fallbackPlacements:[`top`,`right`,`bottom`,`left`],html:!1,offset:[0,6],placement:`top`,popperConfig:null,sanitize:!0,sanitizeFn:null,selector:!1,template:`<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>`,title:``,trigger:`hover focus`},NE={allowList:`object`,animation:`boolean`,boundary:`(string|element)`,container:`(string|element|boolean)`,customClass:`(string|function)`,delay:`(number|object)`,fallbackPlacements:`array`,html:`boolean`,offset:`(array|string|function)`,placement:`(string|function)`,popperConfig:`(null|object|function)`,sanitize:`boolean`,sanitizeFn:`(null|function)`,selector:`(string|boolean)`,template:`string`,title:`(string|element|function)`,trigger:`string`},PE=class e extends yS{constructor(e,t){if(Cx===void 0)throw TypeError(`Bootstrap's tooltips require Popper (https://popper.js.org/docs/v2/)`);super(e,t),this._isEnabled=!0,this._timeout=0,this._isHovered=null,this._activeTrigger={},this._popper=null,this._templateFactory=null,this._newContent=null,this.tip=null,this._setListeners(),this._config.selector||this._fixTitle()}static get Default(){return ME}static get DefaultType(){return NE}static get NAME(){return lE}enable(){this._isEnabled=!0}disable(){this._isEnabled=!1}toggleEnabled(){this._isEnabled=!this._isEnabled}toggle(){if(this._isEnabled){if(this._isShown()){this._leave();return}this._enter()}}dispose(){clearTimeout(this._timeout),fS.off(this._element.closest(hE),gE,this._hideModalHandler),this._element.getAttribute(`data-bs-original-title`)&&this._element.setAttribute(`title`,this._element.getAttribute(`data-bs-original-title`)),this._disposePopper(),super.dispose()}show(){if(this._element.style.display===`none`)throw Error(`Please use show on visible elements`);if(!(this._isWithContent()&&this._isEnabled))return;let e=fS.trigger(this._element,this.constructor.eventName(CE)),t=(Rx(this._element)||this._element.ownerDocument.documentElement).contains(this._element);if(e.defaultPrevented||!t)return;this._disposePopper();let n=this._getTipElement();this._element.setAttribute(`aria-describedby`,n.getAttribute(`id`));let{container:r}=this._config;if(this._element.ownerDocument.documentElement.contains(this.tip)||(r.append(n),fS.trigger(this._element,this.constructor.eventName(TE))),this._popper=this._createPopper(n),n.classList.add(pE),`ontouchstart`in document.documentElement)for(let e of[].concat(...document.body.children))fS.on(e,`mouseover`,zx);this._queueCallback(()=>{fS.trigger(this._element,this.constructor.eventName(wE)),this._isHovered===!1&&this._leave(),this._isHovered=!1},this.tip,this._isAnimated())}hide(){if(!(!this._isShown()||fS.trigger(this._element,this.constructor.eventName(xE)).defaultPrevented)){if(this._getTipElement().classList.remove(pE),`ontouchstart`in document.documentElement)for(let e of[].concat(...document.body.children))fS.off(e,`mouseover`,zx);this._activeTrigger[yE]=!1,this._activeTrigger[vE]=!1,this._activeTrigger[_E]=!1,this._isHovered=null,this._queueCallback(()=>{this._isWithActiveTrigger()||(this._isHovered||this._disposePopper(),this._element.removeAttribute(`aria-describedby`),fS.trigger(this._element,this.constructor.eventName(SE)))},this.tip,this._isAnimated())}}update(){this._popper&&this._popper.update()}_isWithContent(){return!!this._getTitle()}_getTipElement(){return this.tip||=this._createTipElement(this._newContent||this._getContentForTemplate()),this.tip}_createTipElement(e){let t=this._getTemplateFactory(e).toHtml();if(!t)return null;t.classList.remove(dE,pE),t.classList.add(`bs-${this.constructor.NAME}-auto`);let n=jx(this.constructor.NAME).toString();return t.setAttribute(`id`,n),this._isAnimated()&&t.classList.add(dE),t}setContent(e){this._newContent=e,this._isShown()&&(this._disposePopper(),this.show())}_getTemplateFactory(e){return this._templateFactory?this._templateFactory.changeContent(e):this._templateFactory=new cE({...this._config,content:e,extraClass:this._resolvePossibleFunction(this._config.customClass)}),this._templateFactory}_getContentForTemplate(){return{[mE]:this._getTitle()}}_getTitle(){return this._resolvePossibleFunction(this._config.title)||this._element.getAttribute(`data-bs-original-title`)}_initializeOnDelegatedTarget(e){return this.constructor.getOrCreateInstance(e.delegateTarget,this._getDelegateConfig())}_isAnimated(){return this._config.animation||this.tip&&this.tip.classList.contains(dE)}_isShown(){return this.tip&&this.tip.classList.contains(pE)}_createPopper(e){let t=jE[Kx(this._config.placement,[this,e,this._element]).toUpperCase()];return Sx(this._element,e,this._getPopperConfig(t))}_getOffset(){let{offset:e}=this._config;return typeof e==`string`?e.split(`,`).map(e=>Number.parseInt(e,10)):typeof e==`function`?t=>e(t,this._element):e}_resolvePossibleFunction(e){return Kx(e,[this._element,this._element])}_getPopperConfig(e){let t={placement:e,modifiers:[{name:`flip`,options:{fallbackPlacements:this._config.fallbackPlacements}},{name:`offset`,options:{offset:this._getOffset()}},{name:`preventOverflow`,options:{boundary:this._config.boundary}},{name:`arrow`,options:{element:`.${this.constructor.NAME}-arrow`}},{name:`preSetPlacement`,enabled:!0,phase:`beforeMain`,fn:e=>{this._getTipElement().setAttribute(`data-popper-placement`,e.state.placement)}}]};return{...t,...Kx(this._config.popperConfig,[void 0,t])}}_setListeners(){let e=this._config.trigger.split(` `);for(let t of e)if(t===`click`)fS.on(this._element,this.constructor.eventName(EE),this._config.selector,e=>{let t=this._initializeOnDelegatedTarget(e);t._activeTrigger[yE]=!(t._isShown()&&t._activeTrigger[yE]),t.toggle()});else if(t!==bE){let e=t===_E?this.constructor.eventName(kE):this.constructor.eventName(DE),n=t===_E?this.constructor.eventName(AE):this.constructor.eventName(OE);fS.on(this._element,e,this._config.selector,e=>{let t=this._initializeOnDelegatedTarget(e);t._activeTrigger[e.type===`focusin`?vE:_E]=!0,t._enter()}),fS.on(this._element,n,this._config.selector,e=>{let t=this._initializeOnDelegatedTarget(e);t._activeTrigger[e.type===`focusout`?vE:_E]=t._element.contains(e.relatedTarget),t._leave()})}this._hideModalHandler=()=>{this._element&&this.hide()},fS.on(this._element.closest(hE),gE,this._hideModalHandler)}_fixTitle(){let e=this._element.getAttribute(`title`);e&&(!this._element.getAttribute(`aria-label`)&&!this._element.textContent.trim()&&this._element.setAttribute(`aria-label`,e),this._element.setAttribute(`data-bs-original-title`,e),this._element.removeAttribute(`title`))}_enter(){if(this._isShown()||this._isHovered){this._isHovered=!0;return}this._isHovered=!0,this._setTimeout(()=>{this._isHovered&&this.show()},this._config.delay.show)}_leave(){this._isWithActiveTrigger()||(this._isHovered=!1,this._setTimeout(()=>{this._isHovered||this.hide()},this._config.delay.hide))}_setTimeout(e,t){clearTimeout(this._timeout),this._timeout=setTimeout(e,t)}_isWithActiveTrigger(){return Object.values(this._activeTrigger).includes(!0)}_getConfig(e){let t=gS.getDataAttributes(this._element);for(let e of Object.keys(t))uE.has(e)&&delete t[e];return e={...t,...typeof e==`object`&&e?e:{}},e=this._mergeConfigObj(e),e=this._configAfterMerge(e),this._typeCheckConfig(e),e}_configAfterMerge(e){return e.container=e.container===!1?document.body:Fx(e.container),typeof e.delay==`number`&&(e.delay={show:e.delay,hide:e.delay}),typeof e.title==`number`&&(e.title=e.title.toString()),typeof e.content==`number`&&(e.content=e.content.toString()),e}_getDelegateConfig(){let e={};for(let[t,n]of Object.entries(this._config))this.constructor.Default[t]!==n&&(e[t]=n);return e.selector=!1,e.trigger=`manual`,e}_disposePopper(){this._popper&&=(this._popper.destroy(),null),this.tip&&=(this.tip.remove(),null)}static jQueryInterface(t){return this.each(function(){let n=e.getOrCreateInstance(this,t);if(typeof t==`string`){if(n[t]===void 0)throw TypeError(`No method named "${t}"`);n[t]()}})}};Gx(PE);var FE=`popover`,IE=`.popover-header`,LE=`.popover-body`,RE={...PE.Default,content:``,offset:[0,8],placement:`right`,template:`<div class="popover" role="tooltip"><div class="popover-arrow"></div><h3 class="popover-header"></h3><div class="popover-body"></div></div>`,trigger:`click`},zE={...PE.DefaultType,content:`(null|string|element|function)`},BE=class e extends PE{static get Default(){return RE}static get DefaultType(){return zE}static get NAME(){return FE}_isWithContent(){return this._getTitle()||this._getContent()}_getContentForTemplate(){return{[IE]:this._getTitle(),[LE]:this._getContent()}}_getContent(){return this._resolvePossibleFunction(this._config.content)}static jQueryInterface(t){return this.each(function(){let n=e.getOrCreateInstance(this,t);if(typeof t==`string`){if(n[t]===void 0)throw TypeError(`No method named "${t}"`);n[t]()}})}};Gx(BE);var VE=`scrollspy`,HE=`.bs.scrollspy`,UE=`.data-api`,WE=`activate${HE}`,GE=`click${HE}`,KE=`load${HE}${UE}`,qE=`dropdown-item`,JE=`active`,YE=`[data-bs-spy="scroll"]`,XE=`[href]`,ZE=`.nav, .list-group`,QE=`.nav-link`,$E=`${QE}, .nav-item > ${QE}, .list-group-item`,eD=`.dropdown`,tD=`.dropdown-toggle`,nD={offset:null,rootMargin:`0px 0px -25%`,smoothScroll:!1,target:null,threshold:[.1,.5,1]},rD={offset:`(number|null)`,rootMargin:`string`,smoothScroll:`boolean`,target:`element`,threshold:`array`},iD=class e extends yS{constructor(e,t){super(e,t),this._targetLinks=new Map,this._observableSections=new Map,this._rootElement=getComputedStyle(this._element).overflowY===`visible`?null:this._element,this._activeTarget=null,this._observer=null,this._previousScrollData={visibleEntryTop:0,parentScrollTop:0},this.refresh()}static get Default(){return nD}static get DefaultType(){return rD}static get NAME(){return VE}refresh(){this._initializeTargetsAndObservables(),this._maybeEnableSmoothScroll(),this._observer?this._observer.disconnect():this._observer=this._getNewObserver();for(let e of this._observableSections.values())this._observer.observe(e)}dispose(){this._observer.disconnect(),super.dispose()}_configAfterMerge(e){return e.target=Fx(e.target)||document.body,e.rootMargin=e.offset?`${e.offset}px 0px -30%`:e.rootMargin,typeof e.threshold==`string`&&(e.threshold=e.threshold.split(`,`).map(e=>Number.parseFloat(e))),e}_maybeEnableSmoothScroll(){this._config.smoothScroll&&(fS.off(this._config.target,GE),fS.on(this._config.target,GE,XE,e=>{let t=this._observableSections.get(e.target.hash);if(t){e.preventDefault();let n=this._rootElement||window,r=t.offsetTop-this._element.offsetTop;if(n.scrollTo){n.scrollTo({top:r,behavior:`smooth`});return}n.scrollTop=r}}))}_getNewObserver(){let e={root:this._rootElement,threshold:this._config.threshold,rootMargin:this._config.rootMargin};return new IntersectionObserver(e=>this._observerCallback(e),e)}_observerCallback(e){let t=e=>this._targetLinks.get(`#${e.target.id}`),n=e=>{this._previousScrollData.visibleEntryTop=e.target.offsetTop,this._process(t(e))},r=(this._rootElement||document.documentElement).scrollTop,i=r>=this._previousScrollData.parentScrollTop;this._previousScrollData.parentScrollTop=r;for(let a of e){if(!a.isIntersecting){this._activeTarget=null,this._clearActiveClass(t(a));continue}let e=a.target.offsetTop>=this._previousScrollData.visibleEntryTop;if(i&&e){if(n(a),!r)return;continue}!i&&!e&&n(a)}}_initializeTargetsAndObservables(){this._targetLinks=new Map,this._observableSections=new Map;let e=xS.find(XE,this._config.target);for(let t of e){if(!t.hash||Lx(t))continue;let e=xS.findOne(decodeURI(t.hash),this._element);Ix(e)&&(this._targetLinks.set(decodeURI(t.hash),t),this._observableSections.set(t.hash,e))}}_process(e){this._activeTarget!==e&&(this._clearActiveClass(this._config.target),this._activeTarget=e,e.classList.add(JE),this._activateParents(e),fS.trigger(this._element,WE,{relatedTarget:e}))}_activateParents(e){if(e.classList.contains(qE)){xS.findOne(tD,e.closest(eD)).classList.add(JE);return}for(let t of xS.parents(e,ZE))for(let e of xS.prev(t,$E))e.classList.add(JE)}_clearActiveClass(e){e.classList.remove(JE);let t=xS.find(`${XE}.${JE}`,e);for(let e of t)e.classList.remove(JE)}static jQueryInterface(t){return this.each(function(){let n=e.getOrCreateInstance(this,t);if(typeof t==`string`){if(n[t]===void 0||t.startsWith(`_`)||t===`constructor`)throw TypeError(`No method named "${t}"`);n[t]()}})}};fS.on(window,KE,()=>{for(let e of xS.find(YE))iD.getOrCreateInstance(e)}),Gx(iD);var aD=`tab`,oD=`.bs.tab`,sD=`hide${oD}`,cD=`hidden${oD}`,lD=`show${oD}`,uD=`shown${oD}`,dD=`click${oD}`,fD=`keydown${oD}`,pD=`load${oD}`,mD=`ArrowLeft`,hD=`ArrowRight`,gD=`ArrowUp`,_D=`ArrowDown`,vD=`Home`,yD=`End`,bD=`active`,xD=`fade`,SD=`show`,CD=`dropdown`,wD=`.dropdown-toggle`,TD=`.dropdown-menu`,ED=`:not(${wD})`,DD=`.list-group, .nav, [role="tablist"]`,OD=`.nav-item, .list-group-item`,kD=`.nav-link${ED}, .list-group-item${ED}, [role="tab"]${ED}`,AD=`[data-bs-toggle="tab"], [data-bs-toggle="pill"], [data-bs-toggle="list"]`,jD=`${kD}, ${AD}`,MD=`.${bD}[data-bs-toggle="tab"], .${bD}[data-bs-toggle="pill"], .${bD}[data-bs-toggle="list"]`,ND=class e extends yS{constructor(e){super(e),this._parent=this._element.closest(DD),this._parent&&(this._setInitialAttributes(this._parent,this._getChildren()),fS.on(this._element,fD,e=>this._keydown(e)))}static get NAME(){return aD}show(){let e=this._element;if(this._elemIsActive(e))return;let t=this._getActiveElem(),n=t?fS.trigger(t,sD,{relatedTarget:e}):null;fS.trigger(e,lD,{relatedTarget:t}).defaultPrevented||n&&n.defaultPrevented||(this._deactivate(t,e),this._activate(e,t))}_activate(e,t){e&&(e.classList.add(bD),this._activate(xS.getElementFromSelector(e)),this._queueCallback(()=>{if(e.getAttribute(`role`)!==`tab`){e.classList.add(SD);return}e.removeAttribute(`tabindex`),e.setAttribute(`aria-selected`,!0),this._toggleDropDown(e,!0),fS.trigger(e,uD,{relatedTarget:t})},e,e.classList.contains(xD)))}_deactivate(e,t){e&&(e.classList.remove(bD),e.blur(),this._deactivate(xS.getElementFromSelector(e)),this._queueCallback(()=>{if(e.getAttribute(`role`)!==`tab`){e.classList.remove(SD);return}e.setAttribute(`aria-selected`,!1),e.setAttribute(`tabindex`,`-1`),this._toggleDropDown(e,!1),fS.trigger(e,cD,{relatedTarget:t})},e,e.classList.contains(xD)))}_keydown(t){if(![mD,hD,gD,_D,vD,yD].includes(t.key))return;t.stopPropagation(),t.preventDefault();let n=this._getChildren().filter(e=>!Lx(e)),r;if([vD,yD].includes(t.key))r=n[t.key===vD?0:n.length-1];else{let e=[hD,_D].includes(t.key);r=Jx(n,t.target,e,!0)}r&&(r.focus({preventScroll:!0}),e.getOrCreateInstance(r).show())}_getChildren(){return xS.find(jD,this._parent)}_getActiveElem(){return this._getChildren().find(e=>this._elemIsActive(e))||null}_setInitialAttributes(e,t){this._setAttributeIfNotExists(e,`role`,`tablist`);for(let e of t)this._setInitialAttributesOnChild(e)}_setInitialAttributesOnChild(e){e=this._getInnerElement(e);let t=this._elemIsActive(e),n=this._getOuterElement(e);e.setAttribute(`aria-selected`,t),n!==e&&this._setAttributeIfNotExists(n,`role`,`presentation`),t||e.setAttribute(`tabindex`,`-1`),this._setAttributeIfNotExists(e,`role`,`tab`),this._setInitialAttributesOnTargetPanel(e)}_setInitialAttributesOnTargetPanel(e){let t=xS.getElementFromSelector(e);t&&(this._setAttributeIfNotExists(t,`role`,`tabpanel`),e.id&&this._setAttributeIfNotExists(t,`aria-labelledby`,`${e.id}`))}_toggleDropDown(e,t){let n=this._getOuterElement(e);if(!n.classList.contains(CD))return;let r=(e,r)=>{let i=xS.findOne(e,n);i&&i.classList.toggle(r,t)};r(wD,bD),r(TD,SD),n.setAttribute(`aria-expanded`,t)}_setAttributeIfNotExists(e,t,n){e.hasAttribute(t)||e.setAttribute(t,n)}_elemIsActive(e){return e.classList.contains(bD)}_getInnerElement(e){return e.matches(jD)?e:xS.findOne(jD,e)}_getOuterElement(e){return e.closest(OD)||e}static jQueryInterface(t){return this.each(function(){let n=e.getOrCreateInstance(this);if(typeof t==`string`){if(n[t]===void 0||t.startsWith(`_`)||t===`constructor`)throw TypeError(`No method named "${t}"`);n[t]()}})}};fS.on(document,dD,AD,function(e){[`A`,`AREA`].includes(this.tagName)&&e.preventDefault(),!Lx(this)&&ND.getOrCreateInstance(this).show()}),fS.on(window,pD,()=>{for(let e of xS.find(MD))ND.getOrCreateInstance(e)}),Gx(ND);var PD=`toast`,FD=`.bs.toast`,ID=`mouseover${FD}`,LD=`mouseout${FD}`,RD=`focusin${FD}`,zD=`focusout${FD}`,BD=`hide${FD}`,VD=`hidden${FD}`,HD=`show${FD}`,UD=`shown${FD}`,WD=`fade`,GD=`hide`,KD=`show`,qD=`showing`,JD={animation:`boolean`,autohide:`boolean`,delay:`number`},YD={animation:!0,autohide:!0,delay:5e3},XD=class e extends yS{constructor(e,t){super(e,t),this._timeout=null,this._hasMouseInteraction=!1,this._hasKeyboardInteraction=!1,this._setListeners()}static get Default(){return YD}static get DefaultType(){return JD}static get NAME(){return PD}show(){fS.trigger(this._element,HD).defaultPrevented||(this._clearTimeout(),this._config.animation&&this._element.classList.add(WD),this._element.classList.remove(GD),Bx(this._element),this._element.classList.add(KD,qD),this._queueCallback(()=>{this._element.classList.remove(qD),fS.trigger(this._element,UD),this._maybeScheduleHide()},this._element,this._config.animation))}hide(){!this.isShown()||fS.trigger(this._element,BD).defaultPrevented||(this._element.classList.add(qD),this._queueCallback(()=>{this._element.classList.add(GD),this._element.classList.remove(qD,KD),fS.trigger(this._element,VD)},this._element,this._config.animation))}dispose(){this._clearTimeout(),this.isShown()&&this._element.classList.remove(KD),super.dispose()}isShown(){return this._element.classList.contains(KD)}_maybeScheduleHide(){this._config.autohide&&(this._hasMouseInteraction||this._hasKeyboardInteraction||(this._timeout=setTimeout(()=>{this.hide()},this._config.delay)))}_onInteraction(e,t){switch(e.type){case`mouseover`:case`mouseout`:this._hasMouseInteraction=t;break;case`focusin`:case`focusout`:this._hasKeyboardInteraction=t;break}if(t){this._clearTimeout();return}let n=e.relatedTarget;this._element===n||this._element.contains(n)||this._maybeScheduleHide()}_setListeners(){fS.on(this._element,ID,e=>this._onInteraction(e,!0)),fS.on(this._element,LD,e=>this._onInteraction(e,!1)),fS.on(this._element,RD,e=>this._onInteraction(e,!0)),fS.on(this._element,zD,e=>this._onInteraction(e,!1))}_clearTimeout(){clearTimeout(this._timeout),this._timeout=null}static jQueryInterface(t){return this.each(function(){let n=e.getOrCreateInstance(this,t);if(typeof t==`string`){if(n[t]===void 0)throw TypeError(`No method named "${t}"`);n[t](this)}})}};SS(XD),Gx(XD);function ZD(e=void 0){let t=e=>a(`Succesvol`,e,c_.SUCCESS),n=e=>a(`Waarschuwing`,e,c_.WARNING),r=e=>a(`Informatie`,e,c_.INFO),i=e=>a(`Mislukt`,e,c_.DANGER);function a(t,n,r){let i=`toast-${ba()}`,a={id:i,variant:r,title:t,text:n},s=document.querySelector(`.toast-container`);if(!s){console.error(`There was no element with class 'toast-container' found, which is required for useToaster.`);return}let c=(0,u.h)(f_,a),l=(0,u.createApp)({render:()=>c}).mount(document.createElement(`div`));s.appendChild(l.$el);let d=document.querySelector(`#${i}`);d&&(XD.getOrCreateInstance(d,e).show(),o(d))}function o(e){function t(e,t){e.forEach(e=>{if(e.attributeName!=`class`)return;let n=e.target;if(n.classList.contains(`hide`)){n.remove(),t.disconnect();return}})}new MutationObserver(t).observe(e,{attributes:!0})}return{showSuccessToast:t,showInformationToast:r,showWarningToast:n,showDangerToast:i}}var QD={class:`bd-file-upload`},$D={class:`flex align-items-center justify-content-between gap-2`},eO={key:0,class:`preview-container`},tO=(0,u.defineComponent)({__name:`BDFileUpload`,props:{modelValue:{},buttonText:{default:void 0},multiple:{type:Boolean,default:!1},errorMessage:{default:void 0},fileSizeExceededMessage:{default:void 0},acceptedFiles:{default:`.jpg`},url:{default:``},tag:{default:`form`},token:{default:``}},emits:[`update:modelValue`],setup(e,{emit:t}){let{showDangerToast:n}=ZD(),{t:r}=vy.global,i=e,a=t,o=(0,u.ref)(null),s=(0,u.ref)([]);(0,u.watch)(()=>i.modelValue,e=>{o.value&&(o.value.files=o.value.files.filter(t=>e.files.some(e=>e.Naam===t.name)))},{deep:!0});let c=(0,u.computed)(()=>({variant:ia.PRIMARY,size:pa.SM})),l=cg(i,`modelValue`,a),d=async e=>{let t=Array.isArray(e.files)?e.files:[e.files];s.value.push(...t.map(e=>({name:e.name,previewUrl:e.objectURL})));for(let e of t){let t=new FormData;t.append(`file`,e);try{let n={method:`POST`,headers:{RequestVerificationToken:i.token},body:t};f(e,await(await fetch(i.url,n)).json())}catch{n(i.errorMessage||r(`fileUpload.errorMessage`))}}s.value=[]},f=(e,t)=>{let n=s.value.findIndex(t=>t.name==e.name);n!==-1&&s.value.splice(n,1),l.value.files.push({previewUrl:e.objectURL,UUID:e.name,CorrelationId:t.CorrelationId,name:t.Naam,Naam:t.Naam})},p=e=>{let t=l.value.files.indexOf(e);t!==-1&&l.value.files.splice(t,1),t=s.value.indexOf(e),t!==-1&&s.value.splice(t,1)};return(e,t)=>((0,u.openBlock)(),(0,u.createElementBlock)(`div`,QD,[(0,u.createVNode)((0,u.unref)(fy),{ref_key:`fileUploadRef`,ref:o,multiple:i.multiple,"max-file-size":10485760,accept:i.acceptedFiles,auto:!0,"max-files":i.multiple?10:1,"custom-upload":!0,name:`file`,onUploader:d},{header:(0,u.withCtx)(({chooseCallback:e})=>[(0,u.createElementVNode)(`div`,$D,[(0,u.createVNode)(ha,(0,u.mergeProps)(c.value,{onClick:e}),{default:(0,u.withCtx)(()=>[(0,u.createVNode)((0,u.unref)(k)),(0,u.createTextVNode)(` `+(0,u.toDisplayString)(i.buttonText),1)]),_:1},16,[`onClick`])])]),content:(0,u.withCtx)(()=>[s.value||(0,u.unref)(l)&&(0,u.unref)(l).files&&(0,u.unref)(l).files.length!==0?((0,u.openBlock)(),(0,u.createElementBlock)(`div`,eO,[(0,u.unref)(l)&&(0,u.unref)(l).files?((0,u.openBlock)(!0),(0,u.createElementBlock)(u.Fragment,{key:0},(0,u.renderList)((0,u.unref)(l).files,(e,t)=>((0,u.openBlock)(),(0,u.createBlock)(rv,{key:t,file:e,"is-pending":!1,onRemove:p},null,8,[`file`]))),128)):(0,u.createCommentVNode)(``,!0),s.value?((0,u.openBlock)(!0),(0,u.createElementBlock)(u.Fragment,{key:1},(0,u.renderList)(s.value,(e,t)=>((0,u.openBlock)(),(0,u.createBlock)(rv,{key:t,file:e,"is-pending":!0,onRemove:p},null,8,[`file`]))),128)):(0,u.createCommentVNode)(``,!0)])):(0,u.createCommentVNode)(``,!0)]),_:1},8,[`multiple`,`accept`,`max-files`])]))}}),nO=[`id`,`value`,`disabled`],rO=[`for`],iO={class:`invalid-feedback`},aO={__name:`BDFormMultipleCheckbox`,props:{modelValue:{type:Array,required:!0},options:{type:Array,required:!0},selectAllText:{type:String,default:null},state:{type:Boolean,default:!0},errorMessage:{type:String,default:null},overflow:{type:Boolean,default:!1}},emits:[`update:modelValue`,`on-input`,`change-department`],setup(e,{emit:t}){let n=e,r=t,{t:i}=Lu(),a=(0,u.ref)(n.modelValue),o=(0,u.computed)(()=>n.selectAllText?n.selectAllText:i(`form.multipleCheckbox.defaultButton`)),s=(0,u.computed)(()=>{let e=`bd-form-multiple-checkbox`;return n.state||(e+=` is-invalid`),n.overflow&&(e+=` overflow-form-control`),e}),c=(0,u.computed)(()=>n.errorMessage?n.errorMessage:i(`form.multipleCheckbox.defaultErrorMessage`));(0,u.watch)(()=>n.modelValue,e=>{a.value=e}),(0,u.watch)(a,e=>{r(`update:modelValue`,e),r(`on-input`,e),r(`change-department`,e)});function l(){a.value=n.options.map(e=>e.value),d()}function d(){r(`on-input`,a.value)}return(t,n)=>((0,u.openBlock)(),(0,u.createElementBlock)(u.Fragment,null,[(0,u.createElementVNode)(`div`,{class:(0,u.normalizeClass)(s.value)},[(0,u.createVNode)(ha,{variant:`outline-primary`,size:`sm`,onClick:l},{default:(0,u.withCtx)(()=>[(0,u.createTextVNode)((0,u.toDisplayString)(o.value),1)]),_:1}),((0,u.openBlock)(!0),(0,u.createElementBlock)(u.Fragment,null,(0,u.renderList)(e.options,e=>((0,u.openBlock)(),(0,u.createElementBlock)(`div`,{class:`form-check`,key:e.value},[(0,u.withDirectives)((0,u.createElementVNode)(`input`,{class:`form-check-input`,type:`checkbox`,id:e.value,value:e.value,"onUpdate:modelValue":n[0]||=e=>a.value=e,disabled:e.disabled},null,8,nO),[[u.vModelCheckbox,a.value]]),(0,u.createElementVNode)(`label`,{class:`form-check-label`,for:e.value},(0,u.toDisplayString)(e.text),9,rO)]))),128))],2),(0,u.createElementVNode)(`div`,iO,[(0,u.createVNode)(Pt),(0,u.createTextVNode)(` `+(0,u.toDisplayString)(c.value),1)])],64))}};function oO(e){this.content=e}oO.prototype={constructor:oO,find:function(e){for(var t=0;t<this.content.length;t+=2)if(this.content[t]===e)return t;return-1},get:function(e){var t=this.find(e);return t==-1?void 0:this.content[t+1]},update:function(e,t,n){var r=n&&n!=e?this.remove(n):this,i=r.find(e),a=r.content.slice();return i==-1?a.push(n||e,t):(a[i+1]=t,n&&(a[i]=n)),new oO(a)},remove:function(e){var t=this.find(e);if(t==-1)return this;var n=this.content.slice();return n.splice(t,2),new oO(n)},addToStart:function(e,t){return new oO([e,t].concat(this.remove(e).content))},addToEnd:function(e,t){var n=this.remove(e).content.slice();return n.push(e,t),new oO(n)},addBefore:function(e,t,n){var r=this.remove(t),i=r.content.slice(),a=r.find(e);return i.splice(a==-1?i.length:a,0,t,n),new oO(i)},forEach:function(e){for(var t=0;t<this.content.length;t+=2)e(this.content[t],this.content[t+1])},prepend:function(e){return e=oO.from(e),e.size?new oO(e.content.concat(this.subtract(e).content)):this},append:function(e){return e=oO.from(e),e.size?new oO(this.subtract(e).content.concat(e.content)):this},subtract:function(e){var t=this;e=oO.from(e);for(var n=0;n<e.content.length;n+=2)t=t.remove(e.content[n]);return t},toObject:function(){var e={};return this.forEach(function(t,n){e[t]=n}),e},get size(){return this.content.length>>1}},oO.from=function(e){if(e instanceof oO)return e;var t=[];if(e)for(var n in e)t.push(n,e[n]);return new oO(t)};function sO(e,t,n){for(let r=0;;r++){if(r==e.childCount||r==t.childCount)return e.childCount==t.childCount?null:n;let i=e.child(r),a=t.child(r);if(i==a){n+=i.nodeSize;continue}if(!i.sameMarkup(a))return n;if(i.isText&&i.text!=a.text){let e=i.text,t=a.text,r=0;for(;e[r]==t[r];r++)n++;return r&&r<e.length&&r<t.length&&uO(e.charCodeAt(r-1))&&lO(e.charCodeAt(r))&&n--,n}if(i.content.size||a.content.size){let e=sO(i.content,a.content,n+1);if(e!=null)return e}n+=i.nodeSize}}function cO(e,t,n,r){for(let i=e.childCount,a=t.childCount;;){if(i==0||a==0)return i==a?null:{a:n,b:r};let o=e.child(--i),s=t.child(--a),c=o.nodeSize;if(o==s){n-=c,r-=c;continue}if(!o.sameMarkup(s))return{a:n,b:r};if(o.isText&&o.text!=s.text){let e=o.text,t=s.text,i=e.length,a=t.length;for(;i>0&&a>0&&e[i-1]==t[a-1];)i--,a--,n--,r--;return i&&a&&i<e.length&&uO(e.charCodeAt(i-1))&&lO(e.charCodeAt(i))&&(n++,r++),{a:n,b:r}}if(o.content.size||s.content.size){let e=cO(o.content,s.content,n-1,r-1);if(e)return e}n-=c,r-=c}}function lO(e){return e>=56320&&e<57344}function uO(e){return e>=55296&&e<56320}var dO=class e{constructor(e,t){if(this.content=e,this.size=t||0,t==null)for(let t=0;t<e.length;t++)this.size+=e[t].nodeSize}nodesBetween(e,t,n,r=0,i){for(let a=0,o=0;o<t;a++){let s=this.content[a],c=o+s.nodeSize;if(c>e&&n(s,r+o,i||null,a)!==!1&&s.content.size){let i=o+1;s.nodesBetween(Math.max(0,e-i),Math.min(s.content.size,t-i),n,r+i)}o=c}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,t,n,r){let i=``,a=!0;return this.nodesBetween(e,t,(o,s)=>{let c=o.isText?o.text.slice(Math.max(e,s)-s,t-s):o.isLeaf?r?typeof r==`function`?r(o):r:o.type.spec.leafText?o.type.spec.leafText(o):``:``;o.isBlock&&(o.isLeaf&&c||o.isTextblock)&&n&&(a?a=!1:i+=n),i+=c},0),i}append(t){if(!t.size)return this;if(!this.size)return t;let n=this.lastChild,r=t.firstChild,i=this.content.slice(),a=0;for(n.isText&&n.sameMarkup(r)&&(i[i.length-1]=n.withText(n.text+r.text),a=1);a<t.content.length;a++)i.push(t.content[a]);return new e(i,this.size+t.size)}cut(t,n=this.size){if(t==0&&n==this.size)return this;let r=[],i=0;if(n>t)for(let e=0,a=0;a<n;e++){let o=this.content[e],s=a+o.nodeSize;s>t&&((a<t||s>n)&&(o=o.isText?o.cut(Math.max(0,t-a),Math.min(o.text.length,n-a)):o.cut(Math.max(0,t-a-1),Math.min(o.content.size,n-a-1))),r.push(o),i+=o.nodeSize),a=s}return new e(r,i)}cutByIndex(t,n){return t==n?e.empty:t==0&&n==this.content.length?this:new e(this.content.slice(t,n))}replaceChild(t,n){let r=this.content[t];if(r==n)return this;let i=this.content.slice(),a=this.size+n.nodeSize-r.nodeSize;return i[t]=n,new e(i,a)}addToStart(t){return new e([t].concat(this.content),this.size+t.nodeSize)}addToEnd(t){return new e(this.content.concat(t),this.size+t.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let t=0;t<this.content.length;t++)if(!this.content[t].eq(e.content[t]))return!1;return!0}get firstChild(){return this.content.length?this.content[0]:null}get lastChild(){return this.content.length?this.content[this.content.length-1]:null}get childCount(){return this.content.length}child(e){let t=this.content[e];if(!t)throw RangeError(`Index `+e+` out of range for `+this);return t}maybeChild(e){return this.content[e]||null}forEach(e){for(let t=0,n=0;t<this.content.length;t++){let r=this.content[t];e(r,n,t),n+=r.nodeSize}}findDiffStart(e,t=0){return sO(this,e,t)}findDiffEnd(e,t=this.size,n=e.size){return cO(this,e,t,n)}findIndex(e){if(e==0)return pO(0,e);if(e==this.size)return pO(this.content.length,e);if(e>this.size||e<0)throw RangeError(`Position ${e} outside of fragment (${this})`);for(let t=0,n=0;;t++){let r=this.child(t),i=n+r.nodeSize;if(i>=e)return i==e?pO(t+1,i):pO(t,n);n=i}}toString(){return`<`+this.toStringInner()+`>`}toStringInner(){return this.content.join(`, `)}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(t,n){if(!n)return e.empty;if(!Array.isArray(n))throw RangeError(`Invalid input for Fragment.fromJSON`);return e.fromArray(n.map(t.nodeFromJSON))}static fromArray(t){if(!t.length)return e.empty;let n,r=0;for(let e=0;e<t.length;e++){let i=t[e];r+=i.nodeSize,e&&i.isText&&t[e-1].sameMarkup(i)?(n||=t.slice(0,e),n[n.length-1]=i.withText(n[n.length-1].text+i.text)):n&&n.push(i)}return new e(n||t,r)}static from(t){if(!t)return e.empty;if(t instanceof e)return t;if(Array.isArray(t))return this.fromArray(t);if(t.attrs)return new e([t],t.nodeSize);throw RangeError(`Can not convert `+t+` to a Fragment`+(t.nodesBetween?` (looks like multiple versions of prosemirror-model were loaded)`:``))}};dO.empty=new dO([],0);var fO={index:0,offset:0};function pO(e,t){return fO.index=e,fO.offset=t,fO}function mO(e,t){if(e===t)return!0;if(!(e&&typeof e==`object`)||!(t&&typeof t==`object`))return!1;let n=Array.isArray(e);if(Array.isArray(t)!=n)return!1;if(n){if(e.length!=t.length)return!1;for(let n=0;n<e.length;n++)if(!mO(e[n],t[n]))return!1}else{for(let n in e)if(!(n in t)||!mO(e[n],t[n]))return!1;for(let n in t)if(!(n in e))return!1}return!0}var hO=class e{constructor(e,t){this.type=e,this.attrs=t}addToSet(e){let t,n=!1;for(let r=0;r<e.length;r++){let i=e[r];if(this.eq(i))return e;if(this.type.excludes(i.type))t||=e.slice(0,r);else if(i.type.excludes(this.type))return e;else !n&&i.type.rank>this.type.rank&&(t||=e.slice(0,r),t.push(this),n=!0),t&&t.push(i)}return t||=e.slice(),n||t.push(this),t}removeFromSet(e){for(let t=0;t<e.length;t++)if(this.eq(e[t]))return e.slice(0,t).concat(e.slice(t+1));return e}isInSet(e){for(let t=0;t<e.length;t++)if(this.eq(e[t]))return!0;return!1}eq(e){return this==e||this.type==e.type&&mO(this.attrs,e.attrs)}toJSON(){let e={type:this.type.name};for(let t in this.attrs){e.attrs=this.attrs;break}return e}static fromJSON(e,t){if(!t)throw RangeError(`Invalid input for Mark.fromJSON`);let n=e.marks[t.type];if(!n)throw RangeError(`There is no mark type ${t.type} in this schema`);let r=n.create(t.attrs);return n.checkAttrs(r.attrs),r}static sameSet(e,t){if(e==t)return!0;if(e.length!=t.length)return!1;for(let n=0;n<e.length;n++)if(!e[n].eq(t[n]))return!1;return!0}static setFrom(t){if(!t||Array.isArray(t)&&t.length==0)return e.none;if(t instanceof e)return[t];let n=t.slice();return n.sort((e,t)=>e.type.rank-t.type.rank),n}};hO.none=[];var gO=class extends Error{},_O=class e{constructor(e,t,n){this.content=e,this.openStart=t,this.openEnd=n}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(t,n){let r=yO(this.content,t+this.openStart,n,this.openStart+1,this.openEnd+1);return r&&new e(r,this.openStart,this.openEnd)}removeBetween(t,n){return new e(vO(this.content,t+this.openStart,n+this.openStart),this.openStart,this.openEnd)}eq(e){return this.content.eq(e.content)&&this.openStart==e.openStart&&this.openEnd==e.openEnd}toString(){return this.content+`(`+this.openStart+`,`+this.openEnd+`)`}toJSON(){if(!this.content.size)return null;let e={content:this.content.toJSON()};return this.openStart>0&&(e.openStart=this.openStart),this.openEnd>0&&(e.openEnd=this.openEnd),e}static fromJSON(t,n){if(!n)return e.empty;let r=n.openStart||0,i=n.openEnd||0;if(typeof r!=`number`||typeof i!=`number`)throw RangeError(`Invalid input for Slice.fromJSON`);return new e(dO.fromJSON(t,n.content),r,i)}static maxOpen(t,n=!0){let r=0,i=0;for(let e=t.firstChild;e&&!e.isLeaf&&(n||!e.type.spec.isolating);e=e.firstChild)r++;for(let e=t.lastChild;e&&!e.isLeaf&&(n||!e.type.spec.isolating);e=e.lastChild)i++;return new e(t,r,i)}};_O.empty=new _O(dO.empty,0,0);function vO(e,t,n){let{index:r,offset:i}=e.findIndex(t),a=e.maybeChild(r),{index:o,offset:s}=e.findIndex(n);if(i==t||a.isText){if(s!=n&&!e.child(o).isText)throw RangeError(`Removing non-flat range`);return e.cut(0,t).append(e.cut(n))}if(r!=o)throw RangeError(`Removing non-flat range`);return e.replaceChild(r,a.copy(vO(a.content,t-i-1,n-i-1)))}function yO(e,t,n,r,i,a){let{index:o,offset:s}=e.findIndex(t),c=e.maybeChild(o);if(s==t||c.isText)return a&&r<=0&&i<=0&&!a.canReplace(o,o,n)?null:e.cut(0,t).append(n).append(e.cut(t));let l=yO(c.content,t-s-1,n,o==0?r-1:0,o==e.childCount-1?i-1:0,c);return l&&e.replaceChild(o,c.copy(l))}function bO(e,t,n){if(n.openStart>e.depth)throw new gO(`Inserted content deeper than insertion position`);if(e.depth-n.openStart!=t.depth-n.openEnd)throw new gO(`Inconsistent open depths`);return xO(e,t,n,0)}function xO(e,t,n,r){let i=e.index(r),a=e.node(r);if(i==t.index(r)&&r<e.depth-n.openStart){let o=xO(e,t,n,r+1);return a.copy(a.content.replaceChild(i,o))}else if(!n.content.size)return EO(a,OO(e,t,r));else if(!n.openStart&&!n.openEnd&&e.depth==r&&t.depth==r){let r=e.parent,i=r.content;return EO(r,i.cut(0,e.parentOffset).append(n.content).append(i.cut(t.parentOffset)))}else{let{start:i,end:o}=kO(n,e);return EO(a,DO(e,i,o,t,r))}}function SO(e,t){if(!t.type.compatibleContent(e.type))throw new gO(`Cannot join `+t.type.name+` onto `+e.type.name)}function CO(e,t,n){let r=e.node(n);return SO(r,t.node(n)),r}function wO(e,t){let n=t.length-1;n>=0&&e.isText&&e.sameMarkup(t[n])?t[n]=e.withText(t[n].text+e.text):t.push(e)}function TO(e,t,n,r){let i=(t||e).node(n),a=0,o=t?t.index(n):i.childCount;e&&(a=e.index(n),e.depth>n?a++:e.textOffset&&(wO(e.nodeAfter,r),a++));for(let e=a;e<o;e++)wO(i.child(e),r);t&&t.depth==n&&t.textOffset&&wO(t.nodeBefore,r)}function EO(e,t){if(!e.type.validContent(t))throw new gO(`Invalid content for node `+e.type.name);return e.copy(t)}function DO(e,t,n,r,i){let a=e.depth>i&&CO(e,t,i+1),o=r.depth>i&&CO(n,r,i+1),s=[];return TO(null,e,i,s),a&&o&&t.index(i)==n.index(i)?(SO(a,o),wO(EO(a,DO(e,t,n,r,i+1)),s)):(a&&wO(EO(a,OO(e,t,i+1)),s),TO(t,n,i,s),o&&wO(EO(o,OO(n,r,i+1)),s)),TO(r,null,i,s),new dO(s)}function OO(e,t,n){let r=[];return TO(null,e,n,r),e.depth>n&&wO(EO(CO(e,t,n+1),OO(e,t,n+1)),r),TO(t,null,n,r),new dO(r)}function kO(e,t){let n=t.depth-e.openStart,r=t.node(n).copy(e.content);for(let e=n-1;e>=0;e--)r=t.node(e).copy(dO.from(r));return{start:r.resolveNoCache(e.openStart+n),end:r.resolveNoCache(r.content.size-e.openEnd-n)}}var AO=class e{constructor(e,t,n){this.pos=e,this.path=t,this.parentOffset=n,this.depth=t.length/3-1}resolveDepth(e){return e==null?this.depth:e<0?this.depth+e:e}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(e){return this.path[this.resolveDepth(e)*3]}index(e){return this.path[this.resolveDepth(e)*3+1]}indexAfter(e){return e=this.resolveDepth(e),this.index(e)+(e==this.depth&&!this.textOffset?0:1)}start(e){return e=this.resolveDepth(e),e==0?0:this.path[e*3-1]+1}end(e){return e=this.resolveDepth(e),this.start(e)+this.node(e).content.size}before(e){if(e=this.resolveDepth(e),!e)throw RangeError(`There is no position before the top-level node`);return e==this.depth+1?this.pos:this.path[e*3-1]}after(e){if(e=this.resolveDepth(e),!e)throw RangeError(`There is no position after the top-level node`);return e==this.depth+1?this.pos:this.path[e*3-1]+this.path[e*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let e=this.parent,t=this.index(this.depth);if(t==e.childCount)return null;let n=this.pos-this.path[this.path.length-1],r=e.child(t);return n?e.child(t).cut(n):r}get nodeBefore(){let e=this.index(this.depth),t=this.pos-this.path[this.path.length-1];return t?this.parent.child(e).cut(0,t):e==0?null:this.parent.child(e-1)}posAtIndex(e,t){t=this.resolveDepth(t);let n=this.path[t*3],r=t==0?0:this.path[t*3-1]+1;for(let t=0;t<e;t++)r+=n.child(t).nodeSize;return r}marks(){let e=this.parent,t=this.index();if(e.content.size==0)return hO.none;if(this.textOffset)return e.child(t).marks;let n=e.maybeChild(t-1),r=e.maybeChild(t);if(!n){let e=n;n=r,r=e}let i=n.marks;for(var a=0;a<i.length;a++)i[a].type.spec.inclusive===!1&&(!r||!i[a].isInSet(r.marks))&&(i=i[a--].removeFromSet(i));return i}marksAcross(e){let t=this.parent.maybeChild(this.index());if(!t||!t.isInline)return null;let n=t.marks,r=e.parent.maybeChild(e.index());for(var i=0;i<n.length;i++)n[i].type.spec.inclusive===!1&&(!r||!n[i].isInSet(r.marks))&&(n=n[i--].removeFromSet(n));return n}sharedDepth(e){for(let t=this.depth;t>0;t--)if(this.start(t)<=e&&this.end(t)>=e)return t;return 0}blockRange(e=this,t){if(e.pos<this.pos)return e.blockRange(this);for(let n=this.depth-(this.parent.inlineContent||this.pos==e.pos?1:0);n>=0;n--)if(e.pos<=this.end(n)&&(!t||t(this.node(n))))return new PO(this,e,n);return null}sameParent(e){return this.pos-this.parentOffset==e.pos-e.parentOffset}max(e){return e.pos>this.pos?e:this}min(e){return e.pos<this.pos?e:this}toString(){let e=``;for(let t=1;t<=this.depth;t++)e+=(e?`/`:``)+this.node(t).type.name+`_`+this.index(t-1);return e+`:`+this.parentOffset}static resolve(t,n){if(!(n>=0&&n<=t.content.size))throw RangeError(`Position `+n+` out of range`);let r=[],i=0,a=n;for(let e=t;;){let{index:t,offset:n}=e.content.findIndex(a),o=a-n;if(r.push(e,t,i+n),!o||(e=e.child(t),e.isText))break;a=o-1,i+=n+1}return new e(n,r,a)}static resolveCached(t,n){let r=NO.get(t);if(r)for(let e=0;e<r.elts.length;e++){let t=r.elts[e];if(t.pos==n)return t}else NO.set(t,r=new jO);let i=r.elts[r.i]=e.resolve(t,n);return r.i=(r.i+1)%MO,i}},jO=class{constructor(){this.elts=[],this.i=0}},MO=12,NO=new WeakMap,PO=class{constructor(e,t,n){this.$from=e,this.$to=t,this.depth=n}get start(){return this.$from.before(this.depth+1)}get end(){return this.$to.after(this.depth+1)}get parent(){return this.$from.node(this.depth)}get startIndex(){return this.$from.index(this.depth)}get endIndex(){return this.$to.indexAfter(this.depth)}},FO=Object.create(null),IO=class e{constructor(e,t,n,r=hO.none){this.type=e,this.attrs=t,this.marks=r,this.content=n||dO.empty}get children(){return this.content.content}get nodeSize(){return this.isLeaf?1:2+this.content.size}get childCount(){return this.content.childCount}child(e){return this.content.child(e)}maybeChild(e){return this.content.maybeChild(e)}forEach(e){this.content.forEach(e)}nodesBetween(e,t,n,r=0){this.content.nodesBetween(e,t,n,r,this)}descendants(e){this.nodesBetween(0,this.content.size,e)}get textContent(){return this.isLeaf&&this.type.spec.leafText?this.type.spec.leafText(this):this.textBetween(0,this.content.size,``)}textBetween(e,t,n,r){return this.content.textBetween(e,t,n,r)}get firstChild(){return this.content.firstChild}get lastChild(){return this.content.lastChild}eq(e){return this==e||this.sameMarkup(e)&&this.content.eq(e.content)}sameMarkup(e){return this.hasMarkup(e.type,e.attrs,e.marks)}hasMarkup(e,t,n){return this.type==e&&mO(this.attrs,t||e.defaultAttrs||FO)&&hO.sameSet(this.marks,n||hO.none)}copy(t=null){return t==this.content?this:new e(this.type,this.attrs,t,this.marks)}mark(t){return t==this.marks?this:new e(this.type,this.attrs,this.content,t)}cut(e,t=this.content.size){return e==0&&t==this.content.size?this:this.copy(this.content.cut(e,t))}slice(e,t=this.content.size,n=!1){if(e==t)return _O.empty;let r=this.resolve(e),i=this.resolve(t),a=n?0:r.sharedDepth(t),o=r.start(a);return new _O(r.node(a).content.cut(r.pos-o,i.pos-o),r.depth-a,i.depth-a)}replace(e,t,n){return bO(this.resolve(e),this.resolve(t),n)}nodeAt(e){for(let t=this;;){let{index:n,offset:r}=t.content.findIndex(e);if(t=t.maybeChild(n),!t)return null;if(r==e||t.isText)return t;e-=r+1}}childAfter(e){let{index:t,offset:n}=this.content.findIndex(e);return{node:this.content.maybeChild(t),index:t,offset:n}}childBefore(e){if(e==0)return{node:null,index:0,offset:0};let{index:t,offset:n}=this.content.findIndex(e);if(n<e)return{node:this.content.child(t),index:t,offset:n};let r=this.content.child(t-1);return{node:r,index:t-1,offset:n-r.nodeSize}}resolve(e){return AO.resolveCached(this,e)}resolveNoCache(e){return AO.resolve(this,e)}rangeHasMark(e,t,n){let r=!1;return t>e&&this.nodesBetween(e,t,e=>(n.isInSet(e.marks)&&(r=!0),!r)),r}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let e=this.type.name;return this.content.size&&(e+=`(`+this.content.toStringInner()+`)`),RO(this.marks,e)}contentMatchAt(e){let t=this.type.contentMatch.matchFragment(this.content,0,e);if(!t)throw Error(`Called contentMatchAt on a node with invalid content`);return t}canReplace(e,t,n=dO.empty,r=0,i=n.childCount){let a=this.contentMatchAt(e).matchFragment(n,r,i),o=a&&a.matchFragment(this.content,t);if(!o||!o.validEnd)return!1;for(let e=r;e<i;e++)if(!this.type.allowsMarks(n.child(e).marks))return!1;return!0}canReplaceWith(e,t,n,r){if(r&&!this.type.allowsMarks(r))return!1;let i=this.contentMatchAt(e).matchType(n),a=i&&i.matchFragment(this.content,t);return a?a.validEnd:!1}canAppend(e){return e.content.size?this.canReplace(this.childCount,this.childCount,e.content):this.type.compatibleContent(e.type)}check(){this.type.checkContent(this.content),this.type.checkAttrs(this.attrs);let e=hO.none;for(let t=0;t<this.marks.length;t++){let n=this.marks[t];n.type.checkAttrs(n.attrs),e=n.addToSet(e)}if(!hO.sameSet(e,this.marks))throw RangeError(`Invalid collection of marks for node ${this.type.name}: ${this.marks.map(e=>e.type.name)}`);this.content.forEach(e=>e.check())}toJSON(){let e={type:this.type.name};for(let t in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(e=>e.toJSON())),e}static fromJSON(e,t){if(!t)throw RangeError(`Invalid input for Node.fromJSON`);let n;if(t.marks){if(!Array.isArray(t.marks))throw RangeError(`Invalid mark data for Node.fromJSON`);n=t.marks.map(e.markFromJSON)}if(t.type==`text`){if(typeof t.text!=`string`)throw RangeError(`Invalid text node in JSON`);return e.text(t.text,n)}let r=dO.fromJSON(e,t.content),i=e.nodeType(t.type).create(t.attrs,r,n);return i.type.checkAttrs(i.attrs),i}};IO.prototype.text=void 0;var LO=class e extends IO{constructor(e,t,n,r){if(super(e,t,null,r),!n)throw RangeError(`Empty text nodes are not allowed`);this.text=n}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):RO(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(e,t){return this.text.slice(e,t)}get nodeSize(){return this.text.length}mark(t){return t==this.marks?this:new e(this.type,this.attrs,this.text,t)}withText(t){return t==this.text?this:new e(this.type,this.attrs,t,this.marks)}cut(e=0,t=this.text.length){return e==0&&t==this.text.length?this:this.withText(this.text.slice(e,t))}eq(e){return this.sameMarkup(e)&&this.text==e.text}toJSON(){let e=super.toJSON();return e.text=this.text,e}};function RO(e,t){for(let n=e.length-1;n>=0;n--)t=e[n].type.name+`(`+t+`)`;return t}var zO=class e{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(t,n){let r=new BO(t,n);if(r.next==null)return e.empty;let i=VO(r);r.next&&r.err(`Unexpected trailing text`);let a=ZO(JO(i));return QO(a,r),a}matchType(e){for(let t=0;t<this.next.length;t++)if(this.next[t].type==e)return this.next[t].next;return null}matchFragment(e,t=0,n=e.childCount){let r=this;for(let i=t;r&&i<n;i++)r=r.matchType(e.child(i).type);return r}get inlineContent(){return this.next.length!=0&&this.next[0].type.isInline}get defaultType(){for(let e=0;e<this.next.length;e++){let{type:t}=this.next[e];if(!(t.isText||t.hasRequiredAttrs()))return t}return null}compatible(e){for(let t=0;t<this.next.length;t++)for(let n=0;n<e.next.length;n++)if(this.next[t].type==e.next[n].type)return!0;return!1}fillBefore(e,t=!1,n=0){let r=[this];function i(a,o){let s=a.matchFragment(e,n);if(s&&(!t||s.validEnd))return dO.from(o.map(e=>e.createAndFill()));for(let e=0;e<a.next.length;e++){let{type:t,next:n}=a.next[e];if(!(t.isText||t.hasRequiredAttrs())&&r.indexOf(n)==-1){r.push(n);let e=i(n,o.concat(t));if(e)return e}}return null}return i(this,[])}findWrapping(e){for(let t=0;t<this.wrapCache.length;t+=2)if(this.wrapCache[t]==e)return this.wrapCache[t+1];let t=this.computeWrapping(e);return this.wrapCache.push(e,t),t}computeWrapping(e){let t=Object.create(null),n=[{match:this,type:null,via:null}];for(;n.length;){let r=n.shift(),i=r.match;if(i.matchType(e)){let e=[];for(let t=r;t.type;t=t.via)e.push(t.type);return e.reverse()}for(let e=0;e<i.next.length;e++){let{type:a,next:o}=i.next[e];!a.isLeaf&&!a.hasRequiredAttrs()&&!(a.name in t)&&(!r.type||o.validEnd)&&(n.push({match:a.contentMatch,type:a,via:r}),t[a.name]=!0)}}return null}get edgeCount(){return this.next.length}edge(e){if(e>=this.next.length)throw RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function t(n){e.push(n);for(let r=0;r<n.next.length;r++)e.indexOf(n.next[r].next)==-1&&t(n.next[r].next)}return t(this),e.map((t,n)=>{let r=n+(t.validEnd?`*`:` `)+` `;for(let n=0;n<t.next.length;n++)r+=(n?`, `:``)+t.next[n].type.name+`->`+e.indexOf(t.next[n].next);return r}).join(`
|
|
1695
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var a,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,a=e},f:function(){try{o||n.return==null||n.return()}finally{if(s)throw a}}}}function uy(e,t){if(e){if(typeof e==`string`)return dy(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?dy(e,t):void 0}}function dy(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}var fy={name:`FileUpload`,extends:ty,inheritAttrs:!1,emits:[`select`,`uploader`,`before-upload`,`progress`,`upload`,`error`,`before-send`,`clear`,`remove`,`remove-uploaded-file`],duplicateIEEvent:!1,data:function(){return{uploadedFileCount:0,files:[],messages:[],focused:!1,progress:null,uploadedFiles:[]}},methods:{upload:function(){this.hasFiles&&this.uploader()},onBasicUploaderClick:function(e){e.button===0&&this.$refs.fileInput.click()},onFileSelect:function(e){if(e.type!==`drop`&&this.isIE11()&&this.duplicateIEEvent){this.duplicateIEEvent=!1;return}this.isBasic&&this.hasFiles&&(this.files=[]),this.messages=[],this.files=this.files||[];var t=ly(e.dataTransfer?e.dataTransfer.files:e.target.files),n;try{for(t.s();!(n=t.n()).done;){var r=n.value;!this.isFileSelected(r)&&!this.isFileLimitExceeded()&&this.validate(r)&&(this.isImage(r)&&(r.objectURL=window.URL.createObjectURL(r)),this.files.push(r))}}catch(e){t.e(e)}finally{t.f()}this.$emit(`select`,{originalEvent:e,files:this.files}),this.fileLimit&&this.checkFileLimit(),this.auto&&this.hasFiles&&!this.isFileLimitExceeded()&&this.uploader(),e.type!==`drop`&&this.isIE11()?this.clearIEInput():this.clearInputElement()},choose:function(){this.$refs.fileInput.click()},uploader:function(){var e=this;if(this.customUpload)this.fileLimit&&(this.uploadedFileCount+=this.files.length),this.$emit(`uploader`,{files:this.files});else{var t=new XMLHttpRequest,n=new FormData;this.$emit(`before-upload`,{xhr:t,formData:n});var r=ly(this.files),i;try{for(r.s();!(i=r.n()).done;){var a=i.value;n.append(this.name,a,a.name)}}catch(e){r.e(e)}finally{r.f()}t.upload.addEventListener(`progress`,function(t){t.lengthComputable&&(e.progress=Math.round(t.loaded*100/t.total)),e.$emit(`progress`,{originalEvent:t,progress:e.progress})}),t.onreadystatechange=function(){if(t.readyState===4){if(e.progress=0,t.status>=200&&t.status<300){var n;e.fileLimit&&(e.uploadedFileCount+=e.files.length),e.$emit(`upload`,{xhr:t,files:e.files}),(n=e.uploadedFiles).push.apply(n,ay(e.files))}else e.$emit(`error`,{xhr:t,files:e.files});e.clear()}},this.url&&(t.open(`POST`,this.url,!0),this.$emit(`before-send`,{xhr:t,formData:n}),t.withCredentials=this.withCredentials,t.send(n))}},clear:function(){this.files=[],this.messages=null,this.$emit(`clear`),this.isAdvanced&&this.clearInputElement()},onFocus:function(){this.focused=!0},onBlur:function(){this.focused=!1},isFileSelected:function(e){if(this.files&&this.files.length){var t=ly(this.files),n;try{for(t.s();!(n=t.n()).done;){var r=n.value;if(r.name+r.type+r.size===e.name+e.type+e.size)return!0}}catch(e){t.e(e)}finally{t.f()}}return!1},isIE11:function(){return!!window.MSInputMethodContext&&!!document.documentMode},validate:function(e){return this.accept&&!this.isFileTypeValid(e)?(this.messages.push(this.invalidFileTypeMessage.replace(`{0}`,e.name).replace(`{1}`,this.accept)),!1):this.maxFileSize&&e.size>this.maxFileSize?(this.messages.push(this.invalidFileSizeMessage.replace(`{0}`,e.name).replace(`{1}`,this.formatSize(this.maxFileSize))),!1):!0},isFileTypeValid:function(e){var t=ly(this.accept.split(`,`).map(function(e){return e.trim()})),n;try{for(t.s();!(n=t.n()).done;){var r=n.value;if(this.isWildcard(r)?this.getTypeClass(e.type)===this.getTypeClass(r):e.type==r||this.getFileExtension(e).toLowerCase()===r.toLowerCase())return!0}}catch(e){t.e(e)}finally{t.f()}return!1},getTypeClass:function(e){return e.substring(0,e.indexOf(`/`))},isWildcard:function(e){return e.indexOf(`*`)!==-1},getFileExtension:function(e){return`.`+e.name.split(`.`).pop()},isImage:function(e){return/^image\//.test(e.type)},onDragEnter:function(e){!this.disabled&&(!this.hasFiles||this.multiple)&&(e.stopPropagation(),e.preventDefault())},onDragOver:function(e){!this.disabled&&(!this.hasFiles||this.multiple)&&(!this.isUnstyled&&md(this.$refs.content,`p-fileupload-highlight`),this.$refs.content&&this.$refs.content.setAttribute(`data-p-highlight`,!0),e.stopPropagation(),e.preventDefault())},onDragLeave:function(){this.disabled||(!this.isUnstyled&&hd(this.$refs.content,`p-fileupload-highlight`),this.$refs.content&&this.$refs.content.setAttribute(`data-p-highlight`,!1))},onDrop:function(e){if(!this.disabled){!this.isUnstyled&&hd(this.$refs.content,`p-fileupload-highlight`),this.$refs.content&&this.$refs.content.setAttribute(`data-p-highlight`,!1),e.stopPropagation(),e.preventDefault();var t=e.dataTransfer?e.dataTransfer.files:e.target.files;(this.multiple||t&&t.length===1)&&this.onFileSelect(e)}},remove:function(e){this.clearInputElement();var t=this.files.splice(e,1)[0];this.files=ay(this.files),this.$emit(`remove`,{file:t,files:this.files})},removeUploadedFile:function(e){var t=this.uploadedFiles.splice(e,1)[0];this.uploadedFiles=ay(this.uploadedFiles),this.$emit(`remove-uploaded-file`,{file:t,files:this.uploadedFiles})},clearInputElement:function(){this.$refs.fileInput.value=``},clearIEInput:function(){this.$refs.fileInput&&(this.duplicateIEEvent=!0,this.$refs.fileInput.value=``)},formatSize:function(e){var t=1024,n=3,r=this.$primevue.config.locale?.fileSizeTypes||[`B`,`KB`,`MB`,`GB`,`TB`,`PB`,`EB`,`ZB`,`YB`];if(e===0)return`0 ${r[0]}`;var i=Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/t**+i).toFixed(n))} ${r[i]}`},isFileLimitExceeded:function(){return this.fileLimit&&this.fileLimit<=this.files.length+this.uploadedFileCount&&this.focused&&(this.focused=!1),this.fileLimit&&this.fileLimit<this.files.length+this.uploadedFileCount},checkFileLimit:function(){this.isFileLimitExceeded()&&this.messages.push(this.invalidFileLimitMessage.replace(`{0}`,this.fileLimit.toString()))},onMessageClose:function(){this.messages=null}},computed:{isAdvanced:function(){return this.mode===`advanced`},isBasic:function(){return this.mode===`basic`},chooseButtonClass:function(){return[this.cx(`pcChooseButton`),this.class]},basicFileChosenLabel:function(){if(this.auto)return this.chooseButtonLabel;if(this.hasFiles){var e;return this.files&&this.files.length===1?this.files[0].name:(e=this.$primevue.config.locale)==null||(e=e.fileChosenMessage)==null?void 0:e.replace(`{0}`,this.files.length)}return this.$primevue.config.locale?.noFileChosenMessage||``},hasFiles:function(){return this.files&&this.files.length>0},hasUploadedFiles:function(){return this.uploadedFiles&&this.uploadedFiles.length>0},chooseDisabled:function(){return this.disabled||this.fileLimit&&this.fileLimit<=this.files.length+this.uploadedFileCount},uploadDisabled:function(){return this.disabled||!this.hasFiles||this.fileLimit&&this.fileLimit<this.files.length},cancelDisabled:function(){return this.disabled||!this.hasFiles},chooseButtonLabel:function(){return this.chooseLabel||this.$primevue.config.locale.choose},uploadButtonLabel:function(){return this.uploadLabel||this.$primevue.config.locale.upload},cancelButtonLabel:function(){return this.cancelLabel||this.$primevue.config.locale.cancel},completedLabel:function(){return this.$primevue.config.locale.completed},pendingLabel:function(){return this.$primevue.config.locale.pending}},components:{Button:Rm,ProgressBar:Jv,Message:Pv,FileContent:ny,PlusIcon:iv,UploadIcon:bv,TimesIcon:fv},directives:{ripple:Em}},py=[`multiple`,`accept`,`disabled`],my=[`accept`,`disabled`,`multiple`];function hy(e,t,n,r,i,a){var o=(0,u.resolveComponent)(`Button`),s=(0,u.resolveComponent)(`ProgressBar`),c=(0,u.resolveComponent)(`Message`),l=(0,u.resolveComponent)(`FileContent`);return a.isAdvanced?((0,u.openBlock)(),(0,u.createElementBlock)(`div`,(0,u.mergeProps)({key:0,class:e.cx(`root`)},e.ptmi(`root`)),[(0,u.createElementVNode)(`input`,(0,u.mergeProps)({ref:`fileInput`,type:`file`,onChange:t[0]||=function(){return a.onFileSelect&&a.onFileSelect.apply(a,arguments)},multiple:e.multiple,accept:e.accept,disabled:a.chooseDisabled},e.ptm(`input`)),null,16,py),(0,u.createElementVNode)(`div`,(0,u.mergeProps)({class:e.cx(`header`)},e.ptm(`header`)),[(0,u.renderSlot)(e.$slots,`header`,{files:i.files,uploadedFiles:i.uploadedFiles,chooseCallback:a.choose,uploadCallback:a.uploader,clearCallback:a.clear},function(){return[(0,u.createVNode)(o,(0,u.mergeProps)({label:a.chooseButtonLabel,class:a.chooseButtonClass,style:e.style,disabled:e.disabled,unstyled:e.unstyled,onClick:a.choose,onKeydown:(0,u.withKeys)(a.choose,[`enter`]),onFocus:a.onFocus,onBlur:a.onBlur},e.chooseButtonProps,{pt:e.ptm(`pcChooseButton`)}),{icon:(0,u.withCtx)(function(t){return[(0,u.renderSlot)(e.$slots,`chooseicon`,{},function(){return[((0,u.openBlock)(),(0,u.createBlock)((0,u.resolveDynamicComponent)(e.chooseIcon?`span`:`PlusIcon`),(0,u.mergeProps)({class:[t.class,e.chooseIcon],"aria-hidden":`true`},e.ptm(`pcChooseButton`).icon),null,16,[`class`]))]})]}),_:3},16,[`label`,`class`,`style`,`disabled`,`unstyled`,`onClick`,`onKeydown`,`onFocus`,`onBlur`,`pt`]),e.showUploadButton?((0,u.openBlock)(),(0,u.createBlock)(o,(0,u.mergeProps)({key:0,class:e.cx(`pcUploadButton`),label:a.uploadButtonLabel,onClick:a.uploader,disabled:a.uploadDisabled,unstyled:e.unstyled},e.uploadButtonProps,{pt:e.ptm(`pcUploadButton`)}),{icon:(0,u.withCtx)(function(t){return[(0,u.renderSlot)(e.$slots,`uploadicon`,{},function(){return[((0,u.openBlock)(),(0,u.createBlock)((0,u.resolveDynamicComponent)(e.uploadIcon?`span`:`UploadIcon`),(0,u.mergeProps)({class:[t.class,e.uploadIcon],"aria-hidden":`true`},e.ptm(`pcUploadButton`).icon,{"data-pc-section":`uploadbuttonicon`}),null,16,[`class`]))]})]}),_:3},16,[`class`,`label`,`onClick`,`disabled`,`unstyled`,`pt`])):(0,u.createCommentVNode)(``,!0),e.showCancelButton?((0,u.openBlock)(),(0,u.createBlock)(o,(0,u.mergeProps)({key:1,class:e.cx(`pcCancelButton`),label:a.cancelButtonLabel,onClick:a.clear,disabled:a.cancelDisabled,unstyled:e.unstyled},e.cancelButtonProps,{pt:e.ptm(`pcCancelButton`)}),{icon:(0,u.withCtx)(function(t){return[(0,u.renderSlot)(e.$slots,`cancelicon`,{},function(){return[((0,u.openBlock)(),(0,u.createBlock)((0,u.resolveDynamicComponent)(e.cancelIcon?`span`:`TimesIcon`),(0,u.mergeProps)({class:[t.class,e.cancelIcon],"aria-hidden":`true`},e.ptm(`pcCancelButton`).icon,{"data-pc-section":`cancelbuttonicon`}),null,16,[`class`]))]})]}),_:3},16,[`class`,`label`,`onClick`,`disabled`,`unstyled`,`pt`])):(0,u.createCommentVNode)(``,!0)]})],16),(0,u.createElementVNode)(`div`,(0,u.mergeProps)({ref:`content`,class:e.cx(`content`),onDragenter:t[1]||=function(){return a.onDragEnter&&a.onDragEnter.apply(a,arguments)},onDragover:t[2]||=function(){return a.onDragOver&&a.onDragOver.apply(a,arguments)},onDragleave:t[3]||=function(){return a.onDragLeave&&a.onDragLeave.apply(a,arguments)},onDrop:t[4]||=function(){return a.onDrop&&a.onDrop.apply(a,arguments)}},e.ptm(`content`),{"data-p-highlight":!1}),[(0,u.renderSlot)(e.$slots,`content`,{files:i.files,uploadedFiles:i.uploadedFiles,removeUploadedFileCallback:a.removeUploadedFile,removeFileCallback:a.remove,progress:i.progress,messages:i.messages},function(){return[a.hasFiles?((0,u.openBlock)(),(0,u.createBlock)(s,{key:0,value:i.progress,showValue:!1,unstyled:e.unstyled,pt:e.ptm(`pcProgressbar`)},null,8,[`value`,`unstyled`,`pt`])):(0,u.createCommentVNode)(``,!0),((0,u.openBlock)(!0),(0,u.createElementBlock)(u.Fragment,null,(0,u.renderList)(i.messages,function(t){return(0,u.openBlock)(),(0,u.createBlock)(c,{key:t,severity:`error`,onClose:a.onMessageClose,unstyled:e.unstyled,pt:e.ptm(`pcMessage`)},{default:(0,u.withCtx)(function(){return[(0,u.createTextVNode)((0,u.toDisplayString)(t),1)]}),_:2},1032,[`onClose`,`unstyled`,`pt`])}),128)),a.hasFiles?((0,u.openBlock)(),(0,u.createElementBlock)(`div`,{key:1,class:(0,u.normalizeClass)(e.cx(`fileList`))},[(0,u.createVNode)(l,{files:i.files,onRemove:a.remove,badgeValue:a.pendingLabel,previewWidth:e.previewWidth,templates:e.$slots,unstyled:e.unstyled,pt:e.pt},null,8,[`files`,`onRemove`,`badgeValue`,`previewWidth`,`templates`,`unstyled`,`pt`])],2)):(0,u.createCommentVNode)(``,!0),a.hasUploadedFiles?((0,u.openBlock)(),(0,u.createElementBlock)(`div`,{key:2,class:(0,u.normalizeClass)(e.cx(`fileList`))},[(0,u.createVNode)(l,{files:i.uploadedFiles,onRemove:a.removeUploadedFile,badgeValue:a.completedLabel,badgeSeverity:`success`,previewWidth:e.previewWidth,templates:e.$slots,unstyled:e.unstyled,pt:e.pt},null,8,[`files`,`onRemove`,`badgeValue`,`previewWidth`,`templates`,`unstyled`,`pt`])],2)):(0,u.createCommentVNode)(``,!0)]}),e.$slots.empty&&!a.hasFiles&&!a.hasUploadedFiles?((0,u.openBlock)(),(0,u.createElementBlock)(`div`,(0,u.normalizeProps)((0,u.mergeProps)({key:0},e.ptm(`empty`))),[(0,u.renderSlot)(e.$slots,`empty`)],16)):(0,u.createCommentVNode)(``,!0)],16)],16)):a.isBasic?((0,u.openBlock)(),(0,u.createElementBlock)(`div`,(0,u.mergeProps)({key:1,class:e.cx(`root`)},e.ptmi(`root`)),[((0,u.openBlock)(!0),(0,u.createElementBlock)(u.Fragment,null,(0,u.renderList)(i.messages,function(t){return(0,u.openBlock)(),(0,u.createBlock)(c,{key:t,severity:`error`,onClose:a.onMessageClose,unstyled:e.unstyled,pt:e.ptm(`pcMessage`)},{default:(0,u.withCtx)(function(){return[(0,u.createTextVNode)((0,u.toDisplayString)(t),1)]}),_:2},1032,[`onClose`,`unstyled`,`pt`])}),128)),(0,u.createElementVNode)(`div`,(0,u.mergeProps)({class:e.cx(`basicContent`)},e.ptm(`basicContent`)),[(0,u.createVNode)(o,(0,u.mergeProps)({label:a.chooseButtonLabel,class:a.chooseButtonClass,style:e.style,disabled:e.disabled,unstyled:e.unstyled,onMouseup:a.onBasicUploaderClick,onKeydown:(0,u.withKeys)(a.choose,[`enter`]),onFocus:a.onFocus,onBlur:a.onBlur},e.chooseButtonProps,{pt:e.ptm(`pcChooseButton`)}),{icon:(0,u.withCtx)(function(t){return[(0,u.renderSlot)(e.$slots,`chooseicon`,{},function(){return[((0,u.openBlock)(),(0,u.createBlock)((0,u.resolveDynamicComponent)(e.chooseIcon?`span`:`PlusIcon`),(0,u.mergeProps)({class:[t.class,e.chooseIcon],"aria-hidden":`true`},e.ptm(`pcChooseButton`).icon),null,16,[`class`]))]})]}),_:3},16,[`label`,`class`,`style`,`disabled`,`unstyled`,`onMouseup`,`onKeydown`,`onFocus`,`onBlur`,`pt`]),e.auto?(0,u.createCommentVNode)(``,!0):(0,u.renderSlot)(e.$slots,`filelabel`,{key:0,class:(0,u.normalizeClass)(e.cx(`filelabel`)),files:i.files},function(){return[(0,u.createElementVNode)(`span`,{class:(0,u.normalizeClass)(e.cx(`filelabel`))},(0,u.toDisplayString)(a.basicFileChosenLabel),3)]}),(0,u.createElementVNode)(`input`,(0,u.mergeProps)({ref:`fileInput`,type:`file`,accept:e.accept,disabled:e.disabled,multiple:e.multiple,onChange:t[5]||=function(){return a.onFileSelect&&a.onFileSelect.apply(a,arguments)},onFocus:t[6]||=function(){return a.onFocus&&a.onFocus.apply(a,arguments)},onBlur:t[7]||=function(){return a.onBlur&&a.onBlur.apply(a,arguments)}},e.ptm(`input`)),null,16,my)],16)],16)):(0,u.createCommentVNode)(``,!0)}fy.render=hy;var gy={notFoundTemplate:{title:`Page not found`,description:`The page you're looking for couldn't be found. Check the URL or go back to the mainpage.`,buttonDefault:`Back to mainpage`},practitionerHeader:{tooltipAcademy:`BeterDichtbij Academie`,menuItemAcademy:`Academie`}},_y={activeFilters:{title:`Actieve filters`,clearAll:`Wis alle filters`},assignConversationModal:{title:`Gesprek overdragen`,submitButton:`Gesprek overdragen`,conclude:`Afhandelen bij de overdracht`,concludeTooltip:`Het gesprek blijft beschikbaar, deze wordt getoond als het filter "afgehandeld" is geselecteerd. Je patiënt kan ook nog gewoon reageren.`,makeUnread:`Gesprek op ongelezen zetten`},attachmentUploadModal:{title:`Bijlage toevoegen`,submitButton:`Toevoegen`,infoMessage:`Kies je bestand.`,addAttachmentButton:`Bijlage toevoegen`,errorMessage:`Fout opgetreden`,fileTooBigErrorMessage:`Bestand is te groot.`,fileSizeExceededMessage:`Bestanden mogen maximaal 10 MB groot zijn.`},changePasswordTemplate:{toasters:{reset:`De velden zijn geleegd.`}},contentLibraryCard:{insert:`Invoegen`},contentLibraryCardMessageTemplate:{insert:`Invoegen`,collapseOpen:`Inklappen`,collapseClosed:`Lees meer`,popoverIsSharedByOtherUser:`Dit bericht kan alleen door de eigenaar of beheerder aangepast worden`,delete:`Verwijderen`,edit:`Wijzigen`},contentLibraryOverview:{noResults:`Er zijn geen berichten gevonden voor deze zoekterm of filters; pas ze aan om opnieuw te zoeken.`},contentLibrarySplitButton:{messageTemplatesTitle:`Standaardberichten`},contentLibraryTemplate:{changeCategoryButtonLabel:`Mijn categorieën aanpassen`,newMessageText:`Nieuw bericht`,message:`Bericht`,messages:`Berichten`,more:`Meer`,less:`Minder`,searchPlaceholder:`Zoek een bericht`,searchPlaceholderSearch:`Vul een zoekterm in om resultaten te tonen`},conversationToTextModal:{copyButton:`Kopieer selectie naar klembord`,copySuccess:`Het gesprek is gekopieerd naar het klembord.`,onBehalfOf:`namens`,prefix:`Communicatie vanuit BeterDichtbij`,selectAll:`Alles selecteren`,systemMessage:`Tussentijdse mededeling`},imageAttachmentModal:{download:`Download afbeelding`,loading:`Afbeelding aan het laden`},fileUpload:{errorMessage:`Er is een fout opgetreden tijdens het uploaden van het bestand.`},filterCard:{more:`Meer`,less:`Minder`},messageTemplateFormModal:{createTitle:`Standaardbericht toevoegen`,editTitle:`Standaardbericht wijzigen`,titleLabel:`Titel`,titlePlaceHolder:`Zwelling na botbreuk`,replyTemplateLabel:`Standaardbericht`,replyTemplatePlaceHolder:`Schrijf hier jouw bericht naar de patiënt`,sharedWithLabel:`Delen met`,owner:`Eigenaar`,ownerPlaceholder:`Selecteer eigenaar`,tooltipOwner:`Als het bericht met meerdere instanties (teams) gedeeld wordt, kunje alleen zelf eigenaar worden`,categoryLabel:`Categorie`,categoryPlaceholderDropdown:`Selecteer categorie of maak een nieuwe aan`,validation:`Dit veld is verplicht.`},notFoundTemplate:{title:`Pagina niet gevonden`,description:`De pagina die je zoekt kon niet gevonden worden. Controleer de URL of ga terug naar de hoofdpagina.`,buttonDefault:`Terug naar hoofdpagina`},practitionerHeader:{academyTooltip:`BeterDichtbij Academie`,academyMenuItem:`Academie`},videoCallConfirmationModal:{title:`Beeldbellen`,cancel:`Nee`,close:`Sluiten`,ok:`Ja`,message:`Weet je zeker dat je wilt beeldbellen?`,participantMessage:`Weet je zeker dat je wilt beeldbellen met`,testMessage:`Doe de beeldbeltest`,noMobileActivationMessage:`gebruikt BeterDichtbij via de web applicatie waardoor beeldbellen niet mogelijk is. Vraag de patiënt om de app te installeren op een mobiele telefoon of tablet.`,noCompatibleDevices:`gebruikt mogelijk een mobiele telefoon of tablet die beeldbellen niet ondersteunt. Het is daarom momenteel niet mogelijk om te beeldbellen met deze patiënt.`,generalWarning:`Beeldbellen is niet mogelijk om de volgende redenen:`,cameraPermissionMissing:`Je hebt geen toestemming gegeven voor gebruik van de camera door BeterDichtbij.`,microphonePermissionMissing:`Je hebt geen toestemming gegeven voor gebruik van de microfoon door BeterDichtbij.`,helpMessage:`om te controleren of je camera en microfoon goed werken.`}},vy=Iu({legacy:!1,locale:`nl`,messages:{en:{...gy},nl:{..._y}}}),yy=`bottom`,by=`right`,xy=`left`,Sy=`auto`,Cy=[`top`,yy,by,xy],wy=`start`,Ty=`clippingParents`,Ey=`viewport`,Dy=`popper`,Oy=`reference`,ky=Cy.reduce(function(e,t){return e.concat([t+`-`+wy,t+`-end`])},[]),Ay=[].concat(Cy,[Sy]).reduce(function(e,t){return e.concat([t,t+`-`+wy,t+`-end`])},[]),jy=`beforeRead`,My=`read`,Ny=`afterRead`,Py=`beforeMain`,Fy=`main`,Iy=`afterMain`,Ly=`beforeWrite`,Ry=`write`,zy=`afterWrite`,By=[jy,My,Ny,Py,Fy,Iy,Ly,Ry,zy];function Vy(e){return e?(e.nodeName||``).toLowerCase():null}function Hy(e){if(e==null)return window;if(e.toString()!==`[object Window]`){var t=e.ownerDocument;return t&&t.defaultView||window}return e}function Uy(e){return e instanceof Hy(e).Element||e instanceof Element}function Wy(e){return e instanceof Hy(e).HTMLElement||e instanceof HTMLElement}function Gy(e){return typeof ShadowRoot>`u`?!1:e instanceof Hy(e).ShadowRoot||e instanceof ShadowRoot}function Ky(e){var t=e.state;Object.keys(t.elements).forEach(function(e){var n=t.styles[e]||{},r=t.attributes[e]||{},i=t.elements[e];!Wy(i)||!Vy(i)||(Object.assign(i.style,n),Object.keys(r).forEach(function(e){var t=r[e];t===!1?i.removeAttribute(e):i.setAttribute(e,t===!0?``:t)}))})}function qy(e){var t=e.state,n={popper:{position:t.options.strategy,left:`0`,top:`0`,margin:`0`},arrow:{position:`absolute`},reference:{}};return Object.assign(t.elements.popper.style,n.popper),t.styles=n,t.elements.arrow&&Object.assign(t.elements.arrow.style,n.arrow),function(){Object.keys(t.elements).forEach(function(e){var r=t.elements[e],i=t.attributes[e]||{},a=Object.keys(t.styles.hasOwnProperty(e)?t.styles[e]:n[e]).reduce(function(e,t){return e[t]=``,e},{});!Wy(r)||!Vy(r)||(Object.assign(r.style,a),Object.keys(i).forEach(function(e){r.removeAttribute(e)}))})}}var Jy={name:`applyStyles`,enabled:!0,phase:`write`,fn:Ky,effect:qy,requires:[`computeStyles`]};function Yy(e){return e.split(`-`)[0]}var Xy=Math.max,Zy=Math.min,Qy=Math.round;function $y(){var e=navigator.userAgentData;return e!=null&&e.brands&&Array.isArray(e.brands)?e.brands.map(function(e){return e.brand+`/`+e.version}).join(` `):navigator.userAgent}function eb(){return!/^((?!chrome|android).)*safari/i.test($y())}function tb(e,t,n){t===void 0&&(t=!1),n===void 0&&(n=!1);var r=e.getBoundingClientRect(),i=1,a=1;t&&Wy(e)&&(i=e.offsetWidth>0&&Qy(r.width)/e.offsetWidth||1,a=e.offsetHeight>0&&Qy(r.height)/e.offsetHeight||1);var o=(Uy(e)?Hy(e):window).visualViewport,s=!eb()&&n,c=(r.left+(s&&o?o.offsetLeft:0))/i,l=(r.top+(s&&o?o.offsetTop:0))/a,u=r.width/i,d=r.height/a;return{width:u,height:d,top:l,right:c+u,bottom:l+d,left:c,x:c,y:l}}function nb(e){var t=tb(e),n=e.offsetWidth,r=e.offsetHeight;return Math.abs(t.width-n)<=1&&(n=t.width),Math.abs(t.height-r)<=1&&(r=t.height),{x:e.offsetLeft,y:e.offsetTop,width:n,height:r}}function rb(e,t){var n=t.getRootNode&&t.getRootNode();if(e.contains(t))return!0;if(n&&Gy(n)){var r=t;do{if(r&&e.isSameNode(r))return!0;r=r.parentNode||r.host}while(r)}return!1}function ib(e){return Hy(e).getComputedStyle(e)}function ab(e){return[`table`,`td`,`th`].indexOf(Vy(e))>=0}function ob(e){return((Uy(e)?e.ownerDocument:e.document)||window.document).documentElement}function sb(e){return Vy(e)===`html`?e:e.assignedSlot||e.parentNode||(Gy(e)?e.host:null)||ob(e)}function cb(e){return!Wy(e)||ib(e).position===`fixed`?null:e.offsetParent}function lb(e){var t=/firefox/i.test($y());if(/Trident/i.test($y())&&Wy(e)&&ib(e).position===`fixed`)return null;var n=sb(e);for(Gy(n)&&(n=n.host);Wy(n)&&[`html`,`body`].indexOf(Vy(n))<0;){var r=ib(n);if(r.transform!==`none`||r.perspective!==`none`||r.contain===`paint`||[`transform`,`perspective`].indexOf(r.willChange)!==-1||t&&r.willChange===`filter`||t&&r.filter&&r.filter!==`none`)return n;n=n.parentNode}return null}function ub(e){for(var t=Hy(e),n=cb(e);n&&ab(n)&&ib(n).position===`static`;)n=cb(n);return n&&(Vy(n)===`html`||Vy(n)===`body`&&ib(n).position===`static`)?t:n||lb(e)||t}function q(e){return[`top`,`bottom`].indexOf(e)>=0?`x`:`y`}function db(e,t,n){return Xy(e,Zy(t,n))}function fb(e,t,n){var r=db(e,t,n);return r>n?n:r}function pb(){return{top:0,right:0,bottom:0,left:0}}function mb(e){return Object.assign({},pb(),e)}function hb(e,t){return t.reduce(function(t,n){return t[n]=e,t},{})}var gb=function(e,t){return e=typeof e==`function`?e(Object.assign({},t.rects,{placement:t.placement})):e,mb(typeof e==`number`?hb(e,Cy):e)};function _b(e){var t,n=e.state,r=e.name,i=e.options,a=n.elements.arrow,o=n.modifiersData.popperOffsets,s=Yy(n.placement),c=q(s),l=[`left`,`right`].indexOf(s)>=0?`height`:`width`;if(!(!a||!o)){var u=gb(i.padding,n),d=nb(a),f=c===`y`?`top`:xy,p=c===`y`?yy:by,m=n.rects.reference[l]+n.rects.reference[c]-o[c]-n.rects.popper[l],h=o[c]-n.rects.reference[c],g=ub(a),_=g?c===`y`?g.clientHeight||0:g.clientWidth||0:0,v=m/2-h/2,y=u[f],b=_-d[l]-u[p],x=_/2-d[l]/2+v,S=db(y,x,b),C=c;n.modifiersData[r]=(t={},t[C]=S,t.centerOffset=S-x,t)}}function vb(e){var t=e.state,n=e.options.element,r=n===void 0?`[data-popper-arrow]`:n;r!=null&&(typeof r==`string`&&(r=t.elements.popper.querySelector(r),!r)||rb(t.elements.popper,r)&&(t.elements.arrow=r))}var yb={name:`arrow`,enabled:!0,phase:`main`,fn:_b,effect:vb,requires:[`popperOffsets`],requiresIfExists:[`preventOverflow`]};function bb(e){return e.split(`-`)[1]}var xb={top:`auto`,right:`auto`,bottom:`auto`,left:`auto`};function Sb(e,t){var n=e.x,r=e.y,i=t.devicePixelRatio||1;return{x:Qy(n*i)/i||0,y:Qy(r*i)/i||0}}function Cb(e){var t,n=e.popper,r=e.popperRect,i=e.placement,a=e.variation,o=e.offsets,s=e.position,c=e.gpuAcceleration,l=e.adaptive,u=e.roundOffsets,d=e.isFixed,f=o.x,p=f===void 0?0:f,m=o.y,h=m===void 0?0:m,g=typeof u==`function`?u({x:p,y:h}):{x:p,y:h};p=g.x,h=g.y;var _=o.hasOwnProperty(`x`),v=o.hasOwnProperty(`y`),y=xy,b=`top`,x=window;if(l){var S=ub(n),C=`clientHeight`,w=`clientWidth`;if(S===Hy(n)&&(S=ob(n),ib(S).position!==`static`&&s===`absolute`&&(C=`scrollHeight`,w=`scrollWidth`)),S=S,i===`top`||(i===`left`||i===`right`)&&a===`end`){b=yy;var T=d&&S===x&&x.visualViewport?x.visualViewport.height:S[C];h-=T-r.height,h*=c?1:-1}if(i===`left`||(i===`top`||i===`bottom`)&&a===`end`){y=by;var E=d&&S===x&&x.visualViewport?x.visualViewport.width:S[w];p-=E-r.width,p*=c?1:-1}}var ee=Object.assign({position:s},l&&xb),D=u===!0?Sb({x:p,y:h},Hy(n)):{x:p,y:h};if(p=D.x,h=D.y,c){var O;return Object.assign({},ee,(O={},O[b]=v?`0`:``,O[y]=_?`0`:``,O.transform=(x.devicePixelRatio||1)<=1?`translate(`+p+`px, `+h+`px)`:`translate3d(`+p+`px, `+h+`px, 0)`,O))}return Object.assign({},ee,(t={},t[b]=v?h+`px`:``,t[y]=_?p+`px`:``,t.transform=``,t))}function wb(e){var t=e.state,n=e.options,r=n.gpuAcceleration,i=r===void 0?!0:r,a=n.adaptive,o=a===void 0?!0:a,s=n.roundOffsets,c=s===void 0?!0:s,l={placement:Yy(t.placement),variation:bb(t.placement),popper:t.elements.popper,popperRect:t.rects.popper,gpuAcceleration:i,isFixed:t.options.strategy===`fixed`};t.modifiersData.popperOffsets!=null&&(t.styles.popper=Object.assign({},t.styles.popper,Cb(Object.assign({},l,{offsets:t.modifiersData.popperOffsets,position:t.options.strategy,adaptive:o,roundOffsets:c})))),t.modifiersData.arrow!=null&&(t.styles.arrow=Object.assign({},t.styles.arrow,Cb(Object.assign({},l,{offsets:t.modifiersData.arrow,position:`absolute`,adaptive:!1,roundOffsets:c})))),t.attributes.popper=Object.assign({},t.attributes.popper,{"data-popper-placement":t.placement})}var Tb={name:`computeStyles`,enabled:!0,phase:`beforeWrite`,fn:wb,data:{}},Eb={passive:!0};function Db(e){var t=e.state,n=e.instance,r=e.options,i=r.scroll,a=i===void 0?!0:i,o=r.resize,s=o===void 0?!0:o,c=Hy(t.elements.popper),l=[].concat(t.scrollParents.reference,t.scrollParents.popper);return a&&l.forEach(function(e){e.addEventListener(`scroll`,n.update,Eb)}),s&&c.addEventListener(`resize`,n.update,Eb),function(){a&&l.forEach(function(e){e.removeEventListener(`scroll`,n.update,Eb)}),s&&c.removeEventListener(`resize`,n.update,Eb)}}var Ob={name:`eventListeners`,enabled:!0,phase:`write`,fn:function(){},effect:Db,data:{}},kb={left:`right`,right:`left`,bottom:`top`,top:`bottom`};function Ab(e){return e.replace(/left|right|bottom|top/g,function(e){return kb[e]})}var jb={start:`end`,end:`start`};function Mb(e){return e.replace(/start|end/g,function(e){return jb[e]})}function Nb(e){var t=Hy(e);return{scrollLeft:t.pageXOffset,scrollTop:t.pageYOffset}}function Pb(e){return tb(ob(e)).left+Nb(e).scrollLeft}function Fb(e,t){var n=Hy(e),r=ob(e),i=n.visualViewport,a=r.clientWidth,o=r.clientHeight,s=0,c=0;if(i){a=i.width,o=i.height;var l=eb();(l||!l&&t===`fixed`)&&(s=i.offsetLeft,c=i.offsetTop)}return{width:a,height:o,x:s+Pb(e),y:c}}function Ib(e){var t=ob(e),n=Nb(e),r=e.ownerDocument?.body,i=Xy(t.scrollWidth,t.clientWidth,r?r.scrollWidth:0,r?r.clientWidth:0),a=Xy(t.scrollHeight,t.clientHeight,r?r.scrollHeight:0,r?r.clientHeight:0),o=-n.scrollLeft+Pb(e),s=-n.scrollTop;return ib(r||t).direction===`rtl`&&(o+=Xy(t.clientWidth,r?r.clientWidth:0)-i),{width:i,height:a,x:o,y:s}}function Lb(e){var t=ib(e),n=t.overflow,r=t.overflowX,i=t.overflowY;return/auto|scroll|overlay|hidden/.test(n+i+r)}function Rb(e){return[`html`,`body`,`#document`].indexOf(Vy(e))>=0?e.ownerDocument.body:Wy(e)&&Lb(e)?e:Rb(sb(e))}function zb(e,t){t===void 0&&(t=[]);var n=Rb(e),r=n===e.ownerDocument?.body,i=Hy(n),a=r?[i].concat(i.visualViewport||[],Lb(n)?n:[]):n,o=t.concat(a);return r?o:o.concat(zb(sb(a)))}function Bb(e){return Object.assign({},e,{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height})}function Vb(e,t){var n=tb(e,!1,t===`fixed`);return n.top+=e.clientTop,n.left+=e.clientLeft,n.bottom=n.top+e.clientHeight,n.right=n.left+e.clientWidth,n.width=e.clientWidth,n.height=e.clientHeight,n.x=n.left,n.y=n.top,n}function Hb(e,t,n){return t===`viewport`?Bb(Fb(e,n)):Uy(t)?Vb(t,n):Bb(Ib(ob(e)))}function Ub(e){var t=zb(sb(e)),n=[`absolute`,`fixed`].indexOf(ib(e).position)>=0&&Wy(e)?ub(e):e;return Uy(n)?t.filter(function(e){return Uy(e)&&rb(e,n)&&Vy(e)!==`body`}):[]}function Wb(e,t,n,r){var i=t===`clippingParents`?Ub(e):[].concat(t),a=[].concat(i,[n]),o=a[0],s=a.reduce(function(t,n){var i=Hb(e,n,r);return t.top=Xy(i.top,t.top),t.right=Zy(i.right,t.right),t.bottom=Zy(i.bottom,t.bottom),t.left=Xy(i.left,t.left),t},Hb(e,o,r));return s.width=s.right-s.left,s.height=s.bottom-s.top,s.x=s.left,s.y=s.top,s}function Gb(e){var t=e.reference,n=e.element,r=e.placement,i=r?Yy(r):null,a=r?bb(r):null,o=t.x+t.width/2-n.width/2,s=t.y+t.height/2-n.height/2,c;switch(i){case`top`:c={x:o,y:t.y-n.height};break;case yy:c={x:o,y:t.y+t.height};break;case by:c={x:t.x+t.width,y:s};break;case xy:c={x:t.x-n.width,y:s};break;default:c={x:t.x,y:t.y}}var l=i?q(i):null;if(l!=null){var u=l===`y`?`height`:`width`;switch(a){case wy:c[l]=c[l]-(t[u]/2-n[u]/2);break;case`end`:c[l]=c[l]+(t[u]/2-n[u]/2);break;default:}}return c}function Kb(e,t){t===void 0&&(t={});var n=t,r=n.placement,i=r===void 0?e.placement:r,a=n.strategy,o=a===void 0?e.strategy:a,s=n.boundary,c=s===void 0?Ty:s,l=n.rootBoundary,u=l===void 0?Ey:l,d=n.elementContext,f=d===void 0?Dy:d,p=n.altBoundary,m=p===void 0?!1:p,h=n.padding,g=h===void 0?0:h,_=mb(typeof g==`number`?hb(g,Cy):g),v=f===`popper`?Oy:Dy,y=e.rects.popper,b=e.elements[m?v:f],x=Wb(Uy(b)?b:b.contextElement||ob(e.elements.popper),c,u,o),S=tb(e.elements.reference),C=Gb({reference:S,element:y,strategy:`absolute`,placement:i}),w=Bb(Object.assign({},y,C)),T=f===`popper`?w:S,E={top:x.top-T.top+_.top,bottom:T.bottom-x.bottom+_.bottom,left:x.left-T.left+_.left,right:T.right-x.right+_.right},ee=e.modifiersData.offset;if(f===`popper`&&ee){var D=ee[i];Object.keys(E).forEach(function(e){var t=[`right`,`bottom`].indexOf(e)>=0?1:-1,n=[`top`,`bottom`].indexOf(e)>=0?`y`:`x`;E[e]+=D[n]*t})}return E}function qb(e,t){t===void 0&&(t={});var n=t,r=n.placement,i=n.boundary,a=n.rootBoundary,o=n.padding,s=n.flipVariations,c=n.allowedAutoPlacements,l=c===void 0?Ay:c,u=bb(r),d=u?s?ky:ky.filter(function(e){return bb(e)===u}):Cy,f=d.filter(function(e){return l.indexOf(e)>=0});f.length===0&&(f=d);var p=f.reduce(function(t,n){return t[n]=Kb(e,{placement:n,boundary:i,rootBoundary:a,padding:o})[Yy(n)],t},{});return Object.keys(p).sort(function(e,t){return p[e]-p[t]})}function Jb(e){if(Yy(e)===`auto`)return[];var t=Ab(e);return[Mb(e),t,Mb(t)]}function Yb(e){var t=e.state,n=e.options,r=e.name;if(!t.modifiersData[r]._skip){for(var i=n.mainAxis,a=i===void 0?!0:i,o=n.altAxis,s=o===void 0?!0:o,c=n.fallbackPlacements,l=n.padding,u=n.boundary,d=n.rootBoundary,f=n.altBoundary,p=n.flipVariations,m=p===void 0?!0:p,h=n.allowedAutoPlacements,g=t.options.placement,_=Yy(g)===g,v=c||(_||!m?[Ab(g)]:Jb(g)),y=[g].concat(v).reduce(function(e,n){return e.concat(Yy(n)===`auto`?qb(t,{placement:n,boundary:u,rootBoundary:d,padding:l,flipVariations:m,allowedAutoPlacements:h}):n)},[]),b=t.rects.reference,x=t.rects.popper,S=new Map,C=!0,w=y[0],T=0;T<y.length;T++){var E=y[T],ee=Yy(E),D=bb(E)===wy,O=[`top`,yy].indexOf(ee)>=0,k=O?`width`:`height`,A=Kb(t,{placement:E,boundary:u,rootBoundary:d,altBoundary:f,padding:l}),j=O?D?by:xy:D?yy:`top`;b[k]>x[k]&&(j=Ab(j));var te=Ab(j),ne=[];if(a&&ne.push(A[ee]<=0),s&&ne.push(A[j]<=0,A[te]<=0),ne.every(function(e){return e})){w=E,C=!1;break}S.set(E,ne)}if(C)for(var re=m?3:1,ie=function(e){var t=y.find(function(t){var n=S.get(t);if(n)return n.slice(0,e).every(function(e){return e})});if(t)return w=t,`break`},ae=re;ae>0&&ie(ae)!==`break`;ae--);t.placement!==w&&(t.modifiersData[r]._skip=!0,t.placement=w,t.reset=!0)}}var Xb={name:`flip`,enabled:!0,phase:`main`,fn:Yb,requiresIfExists:[`offset`],data:{_skip:!1}};function Zb(e,t,n){return n===void 0&&(n={x:0,y:0}),{top:e.top-t.height-n.y,right:e.right-t.width+n.x,bottom:e.bottom-t.height+n.y,left:e.left-t.width-n.x}}function Qb(e){return[`top`,by,yy,xy].some(function(t){return e[t]>=0})}function $b(e){var t=e.state,n=e.name,r=t.rects.reference,i=t.rects.popper,a=t.modifiersData.preventOverflow,o=Kb(t,{elementContext:`reference`}),s=Kb(t,{altBoundary:!0}),c=Zb(o,r),l=Zb(s,i,a),u=Qb(c),d=Qb(l);t.modifiersData[n]={referenceClippingOffsets:c,popperEscapeOffsets:l,isReferenceHidden:u,hasPopperEscaped:d},t.attributes.popper=Object.assign({},t.attributes.popper,{"data-popper-reference-hidden":u,"data-popper-escaped":d})}var ex={name:`hide`,enabled:!0,phase:`main`,requiresIfExists:[`preventOverflow`],fn:$b};function tx(e,t,n){var r=Yy(e),i=[`left`,`top`].indexOf(r)>=0?-1:1,a=typeof n==`function`?n(Object.assign({},t,{placement:e})):n,o=a[0],s=a[1];return o||=0,s=(s||0)*i,[`left`,`right`].indexOf(r)>=0?{x:s,y:o}:{x:o,y:s}}function nx(e){var t=e.state,n=e.options,r=e.name,i=n.offset,a=i===void 0?[0,0]:i,o=Ay.reduce(function(e,n){return e[n]=tx(n,t.rects,a),e},{}),s=o[t.placement],c=s.x,l=s.y;t.modifiersData.popperOffsets!=null&&(t.modifiersData.popperOffsets.x+=c,t.modifiersData.popperOffsets.y+=l),t.modifiersData[r]=o}var rx={name:`offset`,enabled:!0,phase:`main`,requires:[`popperOffsets`],fn:nx};function ix(e){var t=e.state,n=e.name;t.modifiersData[n]=Gb({reference:t.rects.reference,element:t.rects.popper,strategy:`absolute`,placement:t.placement})}var ax={name:`popperOffsets`,enabled:!0,phase:`read`,fn:ix,data:{}};function ox(e){return e===`x`?`y`:`x`}function sx(e){var t=e.state,n=e.options,r=e.name,i=n.mainAxis,a=i===void 0?!0:i,o=n.altAxis,s=o===void 0?!1:o,c=n.boundary,l=n.rootBoundary,u=n.altBoundary,d=n.padding,f=n.tether,p=f===void 0?!0:f,m=n.tetherOffset,h=m===void 0?0:m,g=Kb(t,{boundary:c,rootBoundary:l,padding:d,altBoundary:u}),_=Yy(t.placement),v=bb(t.placement),y=!v,b=q(_),x=ox(b),S=t.modifiersData.popperOffsets,C=t.rects.reference,w=t.rects.popper,T=typeof h==`function`?h(Object.assign({},t.rects,{placement:t.placement})):h,E=typeof T==`number`?{mainAxis:T,altAxis:T}:Object.assign({mainAxis:0,altAxis:0},T),ee=t.modifiersData.offset?t.modifiersData.offset[t.placement]:null,D={x:0,y:0};if(S){if(a){var O=b===`y`?`top`:xy,k=b===`y`?yy:by,A=b===`y`?`height`:`width`,j=S[b],te=j+g[O],ne=j-g[k],re=p?-w[A]/2:0,ie=v===`start`?C[A]:w[A],ae=v===`start`?-w[A]:-C[A],M=t.elements.arrow,oe=p&&M?nb(M):{width:0,height:0},se=t.modifiersData[`arrow#persistent`]?t.modifiersData[`arrow#persistent`].padding:pb(),ce=se[O],le=se[k],ue=db(0,C[A],oe[A]),de=y?C[A]/2-re-ue-ce-E.mainAxis:ie-ue-ce-E.mainAxis,fe=y?-C[A]/2+re+ue+le+E.mainAxis:ae+ue+le+E.mainAxis,N=t.elements.arrow&&ub(t.elements.arrow),pe=N?b===`y`?N.clientTop||0:N.clientLeft||0:0,me=ee?.[b]??0,he=j+de-me-pe,ge=j+fe-me,_e=db(p?Zy(te,he):te,j,p?Xy(ne,ge):ne);S[b]=_e,D[b]=_e-j}if(s){var P=b===`x`?`top`:xy,ve=b===`x`?yy:by,F=S[x],ye=x===`y`?`height`:`width`,be=F+g[P],I=F-g[ve],L=[`top`,xy].indexOf(_)!==-1,xe=ee?.[x]??0,R=L?be:F-C[ye]-w[ye]-xe+E.altAxis,z=L?F+C[ye]+w[ye]-xe-E.altAxis:I,Se=p&&L?fb(R,F,z):db(p?R:be,F,p?z:I);S[x]=Se,D[x]=Se-F}t.modifiersData[r]=D}}var cx={name:`preventOverflow`,enabled:!0,phase:`main`,fn:sx,requiresIfExists:[`offset`]};function lx(e){return{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}}function ux(e){return e===Hy(e)||!Wy(e)?Nb(e):lx(e)}function dx(e){var t=e.getBoundingClientRect(),n=Qy(t.width)/e.offsetWidth||1,r=Qy(t.height)/e.offsetHeight||1;return n!==1||r!==1}function fx(e,t,n){n===void 0&&(n=!1);var r=Wy(t),i=Wy(t)&&dx(t),a=ob(t),o=tb(e,i,n),s={scrollLeft:0,scrollTop:0},c={x:0,y:0};return(r||!r&&!n)&&((Vy(t)!==`body`||Lb(a))&&(s=ux(t)),Wy(t)?(c=tb(t,!0),c.x+=t.clientLeft,c.y+=t.clientTop):a&&(c.x=Pb(a))),{x:o.left+s.scrollLeft-c.x,y:o.top+s.scrollTop-c.y,width:o.width,height:o.height}}function px(e){var t=new Map,n=new Set,r=[];e.forEach(function(e){t.set(e.name,e)});function i(e){n.add(e.name),[].concat(e.requires||[],e.requiresIfExists||[]).forEach(function(e){if(!n.has(e)){var r=t.get(e);r&&i(r)}}),r.push(e)}return e.forEach(function(e){n.has(e.name)||i(e)}),r}function mx(e){var t=px(e);return By.reduce(function(e,n){return e.concat(t.filter(function(e){return e.phase===n}))},[])}function hx(e){var t;return function(){return t||=new Promise(function(n){Promise.resolve().then(function(){t=void 0,n(e())})}),t}}function gx(e){var t=e.reduce(function(e,t){var n=e[t.name];return e[t.name]=n?Object.assign({},n,t,{options:Object.assign({},n.options,t.options),data:Object.assign({},n.data,t.data)}):t,e},{});return Object.keys(t).map(function(e){return t[e]})}var _x={placement:`bottom`,modifiers:[],strategy:`absolute`};function vx(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return!t.some(function(e){return!(e&&typeof e.getBoundingClientRect==`function`)})}function yx(e){e===void 0&&(e={});var t=e,n=t.defaultModifiers,r=n===void 0?[]:n,i=t.defaultOptions,a=i===void 0?_x:i;return function(e,t,n){n===void 0&&(n=a);var i={placement:`bottom`,orderedModifiers:[],options:Object.assign({},_x,a),modifiersData:{},elements:{reference:e,popper:t},attributes:{},styles:{}},o=[],s=!1,c={state:i,setOptions:function(n){var o=typeof n==`function`?n(i.options):n;u(),i.options=Object.assign({},a,i.options,o),i.scrollParents={reference:Uy(e)?zb(e):e.contextElement?zb(e.contextElement):[],popper:zb(t)};var s=mx(gx([].concat(r,i.options.modifiers)));return i.orderedModifiers=s.filter(function(e){return e.enabled}),l(),c.update()},forceUpdate:function(){if(!s){var e=i.elements,t=e.reference,n=e.popper;if(vx(t,n)){i.rects={reference:fx(t,ub(n),i.options.strategy===`fixed`),popper:nb(n)},i.reset=!1,i.placement=i.options.placement,i.orderedModifiers.forEach(function(e){return i.modifiersData[e.name]=Object.assign({},e.data)});for(var r=0;r<i.orderedModifiers.length;r++){if(i.reset===!0){i.reset=!1,r=-1;continue}var a=i.orderedModifiers[r],o=a.fn,l=a.options,u=l===void 0?{}:l,d=a.name;typeof o==`function`&&(i=o({state:i,options:u,name:d,instance:c})||i)}}}},update:hx(function(){return new Promise(function(e){c.forceUpdate(),e(i)})}),destroy:function(){u(),s=!0}};if(!vx(e,t))return c;c.setOptions(n).then(function(e){!s&&n.onFirstUpdate&&n.onFirstUpdate(e)});function l(){i.orderedModifiers.forEach(function(e){var t=e.name,n=e.options,r=n===void 0?{}:n,a=e.effect;if(typeof a==`function`){var s=a({state:i,name:t,instance:c,options:r});o.push(s||function(){})}})}function u(){o.forEach(function(e){return e()}),o=[]}return c}}var bx=yx(),xx=yx({defaultModifiers:[Ob,ax,Tb,Jy]}),Sx=yx({defaultModifiers:[Ob,ax,Tb,Jy,rx,Xb,cx,yb,ex]}),Cx=s({afterMain:()=>Iy,afterRead:()=>Ny,afterWrite:()=>zy,applyStyles:()=>Jy,arrow:()=>yb,auto:()=>Sy,basePlacements:()=>Cy,beforeMain:()=>Py,beforeRead:()=>jy,beforeWrite:()=>Ly,bottom:()=>yy,clippingParents:()=>Ty,computeStyles:()=>Tb,createPopper:()=>Sx,createPopperBase:()=>bx,createPopperLite:()=>xx,detectOverflow:()=>Kb,end:()=>`end`,eventListeners:()=>Ob,flip:()=>Xb,hide:()=>ex,left:()=>xy,main:()=>Fy,modifierPhases:()=>By,offset:()=>rx,placements:()=>Ay,popper:()=>Dy,popperGenerator:()=>yx,popperOffsets:()=>ax,preventOverflow:()=>cx,read:()=>My,reference:()=>Oy,right:()=>by,start:()=>wy,top:()=>`top`,variationPlacements:()=>ky,viewport:()=>Ey,write:()=>Ry}),wx=new Map,Tx={set(e,t,n){wx.has(e)||wx.set(e,new Map);let r=wx.get(e);if(!r.has(t)&&r.size!==0){console.error(`Bootstrap doesn't allow more than one instance per element. Bound instance: ${Array.from(r.keys())[0]}.`);return}r.set(t,n)},get(e,t){return wx.has(e)&&wx.get(e).get(t)||null},remove(e,t){if(!wx.has(e))return;let n=wx.get(e);n.delete(t),n.size===0&&wx.delete(e)}},Ex=1e6,Dx=1e3,Ox=`transitionend`,kx=e=>(e&&window.CSS&&window.CSS.escape&&(e=e.replace(/#([^\s"#']+)/g,(e,t)=>`#${CSS.escape(t)}`)),e),Ax=e=>e==null?`${e}`:Object.prototype.toString.call(e).match(/\s([a-z]+)/i)[1].toLowerCase(),jx=e=>{do e+=Math.floor(Math.random()*Ex);while(document.getElementById(e));return e},Mx=e=>{if(!e)return 0;let{transitionDuration:t,transitionDelay:n}=window.getComputedStyle(e);return!Number.parseFloat(t)&&!Number.parseFloat(n)?0:(t=t.split(`,`)[0],n=n.split(`,`)[0],(Number.parseFloat(t)+Number.parseFloat(n))*Dx)},Nx=e=>{e.dispatchEvent(new Event(Ox))},Px=e=>!e||typeof e!=`object`?!1:(e.jquery!==void 0&&(e=e[0]),e.nodeType!==void 0),Fx=e=>Px(e)?e.jquery?e[0]:e:typeof e==`string`&&e.length>0?document.querySelector(kx(e)):null,Ix=e=>{if(!Px(e)||e.getClientRects().length===0)return!1;let t=getComputedStyle(e).getPropertyValue(`visibility`)===`visible`,n=e.closest(`details:not([open])`);if(!n)return t;if(n!==e){let t=e.closest(`summary`);if(t&&t.parentNode!==n||t===null)return!1}return t},Lx=e=>!e||e.nodeType!==Node.ELEMENT_NODE||e.classList.contains(`disabled`)?!0:e.disabled===void 0?e.hasAttribute(`disabled`)&&e.getAttribute(`disabled`)!==`false`:e.disabled,Rx=e=>{if(!document.documentElement.attachShadow)return null;if(typeof e.getRootNode==`function`){let t=e.getRootNode();return t instanceof ShadowRoot?t:null}return e instanceof ShadowRoot?e:e.parentNode?Rx(e.parentNode):null},zx=()=>{},Bx=e=>{e.offsetHeight},Vx=()=>window.jQuery&&!document.body.hasAttribute(`data-bs-no-jquery`)?window.jQuery:null,Hx=[],Ux=e=>{document.readyState===`loading`?(Hx.length||document.addEventListener(`DOMContentLoaded`,()=>{for(let e of Hx)e()}),Hx.push(e)):e()},Wx=()=>document.documentElement.dir===`rtl`,Gx=e=>{Ux(()=>{let t=Vx();if(t){let n=e.NAME,r=t.fn[n];t.fn[n]=e.jQueryInterface,t.fn[n].Constructor=e,t.fn[n].noConflict=()=>(t.fn[n]=r,e.jQueryInterface)}})},Kx=(e,t=[],n=e)=>typeof e==`function`?e.call(...t):n,qx=(e,t,n=!0)=>{if(!n){Kx(e);return}let r=Mx(t)+5,i=!1,a=({target:n})=>{n===t&&(i=!0,t.removeEventListener(Ox,a),Kx(e))};t.addEventListener(Ox,a),setTimeout(()=>{i||Nx(t)},r)},Jx=(e,t,n,r)=>{let i=e.length,a=e.indexOf(t);return a===-1?!n&&r?e[i-1]:e[0]:(a+=n?1:-1,r&&(a=(a+i)%i),e[Math.max(0,Math.min(a,i-1))])},Yx=/[^.]*(?=\..*)\.|.*/,Xx=/\..*/,Zx=/::\d+$/,Qx={},$x=1,eS={mouseenter:`mouseover`,mouseleave:`mouseout`},tS=new Set(`click.dblclick.mouseup.mousedown.contextmenu.mousewheel.DOMMouseScroll.mouseover.mouseout.mousemove.selectstart.selectend.keydown.keypress.keyup.orientationchange.touchstart.touchmove.touchend.touchcancel.pointerdown.pointermove.pointerup.pointerleave.pointercancel.gesturestart.gesturechange.gestureend.focus.blur.change.reset.select.submit.focusin.focusout.load.unload.beforeunload.resize.move.DOMContentLoaded.readystatechange.error.abort.scroll`.split(`.`));function nS(e,t){return t&&`${t}::${$x++}`||e.uidEvent||$x++}function rS(e){let t=nS(e);return e.uidEvent=t,Qx[t]=Qx[t]||{},Qx[t]}function iS(e,t){return function n(r){return pS(r,{delegateTarget:e}),n.oneOff&&fS.off(e,r.type,t),t.apply(e,[r])}}function aS(e,t,n){return function r(i){let a=e.querySelectorAll(t);for(let{target:o}=i;o&&o!==this;o=o.parentNode)for(let s of a)if(s===o)return pS(i,{delegateTarget:o}),r.oneOff&&fS.off(e,i.type,t,n),n.apply(o,[i])}}function oS(e,t,n=null){return Object.values(e).find(e=>e.callable===t&&e.delegationSelector===n)}function sS(e,t,n){let r=typeof t==`string`,i=r?n:t||n,a=dS(e);return tS.has(a)||(a=e),[r,i,a]}function cS(e,t,n,r,i){if(typeof t!=`string`||!e)return;let[a,o,s]=sS(t,n,r);t in eS&&(o=(e=>function(t){if(!t.relatedTarget||t.relatedTarget!==t.delegateTarget&&!t.delegateTarget.contains(t.relatedTarget))return e.call(this,t)})(o));let c=rS(e),l=c[s]||(c[s]={}),u=oS(l,o,a?n:null);if(u){u.oneOff=u.oneOff&&i;return}let d=nS(o,t.replace(Yx,``)),f=a?aS(e,n,o):iS(e,o);f.delegationSelector=a?n:null,f.callable=o,f.oneOff=i,f.uidEvent=d,l[d]=f,e.addEventListener(s,f,a)}function lS(e,t,n,r,i){let a=oS(t[n],r,i);a&&(e.removeEventListener(n,a,!!i),delete t[n][a.uidEvent])}function uS(e,t,n,r){let i=t[n]||{};for(let[a,o]of Object.entries(i))a.includes(r)&&lS(e,t,n,o.callable,o.delegationSelector)}function dS(e){return e=e.replace(Xx,``),eS[e]||e}var fS={on(e,t,n,r){cS(e,t,n,r,!1)},one(e,t,n,r){cS(e,t,n,r,!0)},off(e,t,n,r){if(typeof t!=`string`||!e)return;let[i,a,o]=sS(t,n,r),s=o!==t,c=rS(e),l=c[o]||{},u=t.startsWith(`.`);if(a!==void 0){if(!Object.keys(l).length)return;lS(e,c,o,a,i?n:null);return}if(u)for(let n of Object.keys(c))uS(e,c,n,t.slice(1));for(let[n,r]of Object.entries(l)){let i=n.replace(Zx,``);(!s||t.includes(i))&&lS(e,c,o,r.callable,r.delegationSelector)}},trigger(e,t,n){if(typeof t!=`string`||!e)return null;let r=Vx(),i=t!==dS(t),a=null,o=!0,s=!0,c=!1;i&&r&&(a=r.Event(t,n),r(e).trigger(a),o=!a.isPropagationStopped(),s=!a.isImmediatePropagationStopped(),c=a.isDefaultPrevented());let l=pS(new Event(t,{bubbles:o,cancelable:!0}),n);return c&&l.preventDefault(),s&&e.dispatchEvent(l),l.defaultPrevented&&a&&a.preventDefault(),l}};function pS(e,t={}){for(let[n,r]of Object.entries(t))try{e[n]=r}catch{Object.defineProperty(e,n,{configurable:!0,get(){return r}})}return e}function mS(e){if(e===`true`)return!0;if(e===`false`)return!1;if(e===Number(e).toString())return Number(e);if(e===``||e===`null`)return null;if(typeof e!=`string`)return e;try{return JSON.parse(decodeURIComponent(e))}catch{return e}}function hS(e){return e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}var gS={setDataAttribute(e,t,n){e.setAttribute(`data-bs-${hS(t)}`,n)},removeDataAttribute(e,t){e.removeAttribute(`data-bs-${hS(t)}`)},getDataAttributes(e){if(!e)return{};let t={},n=Object.keys(e.dataset).filter(e=>e.startsWith(`bs`)&&!e.startsWith(`bsConfig`));for(let r of n){let n=r.replace(/^bs/,``);n=n.charAt(0).toLowerCase()+n.slice(1),t[n]=mS(e.dataset[r])}return t},getDataAttribute(e,t){return mS(e.getAttribute(`data-bs-${hS(t)}`))}},_S=class{static get Default(){return{}}static get DefaultType(){return{}}static get NAME(){throw Error(`You have to implement the static method "NAME", for each component!`)}_getConfig(e){return e=this._mergeConfigObj(e),e=this._configAfterMerge(e),this._typeCheckConfig(e),e}_configAfterMerge(e){return e}_mergeConfigObj(e,t){let n=Px(t)?gS.getDataAttribute(t,`config`):{};return{...this.constructor.Default,...typeof n==`object`?n:{},...Px(t)?gS.getDataAttributes(t):{},...typeof e==`object`?e:{}}}_typeCheckConfig(e,t=this.constructor.DefaultType){for(let[n,r]of Object.entries(t)){let t=e[n],i=Px(t)?`element`:Ax(t);if(!new RegExp(r).test(i))throw TypeError(`${this.constructor.NAME.toUpperCase()}: Option "${n}" provided type "${i}" but expected type "${r}".`)}}},vS=`5.3.8`,yS=class extends _S{constructor(e,t){super(),e=Fx(e),e&&(this._element=e,this._config=this._getConfig(t),Tx.set(this._element,this.constructor.DATA_KEY,this))}dispose(){Tx.remove(this._element,this.constructor.DATA_KEY),fS.off(this._element,this.constructor.EVENT_KEY);for(let e of Object.getOwnPropertyNames(this))this[e]=null}_queueCallback(e,t,n=!0){qx(e,t,n)}_getConfig(e){return e=this._mergeConfigObj(e,this._element),e=this._configAfterMerge(e),this._typeCheckConfig(e),e}static getInstance(e){return Tx.get(Fx(e),this.DATA_KEY)}static getOrCreateInstance(e,t={}){return this.getInstance(e)||new this(e,typeof t==`object`?t:null)}static get VERSION(){return vS}static get DATA_KEY(){return`bs.${this.NAME}`}static get EVENT_KEY(){return`.${this.DATA_KEY}`}static eventName(e){return`${e}${this.EVENT_KEY}`}},bS=e=>{let t=e.getAttribute(`data-bs-target`);if(!t||t===`#`){let n=e.getAttribute(`href`);if(!n||!n.includes(`#`)&&!n.startsWith(`.`))return null;n.includes(`#`)&&!n.startsWith(`#`)&&(n=`#${n.split(`#`)[1]}`),t=n&&n!==`#`?n.trim():null}return t?t.split(`,`).map(e=>kx(e)).join(`,`):null},xS={find(e,t=document.documentElement){return[].concat(...Element.prototype.querySelectorAll.call(t,e))},findOne(e,t=document.documentElement){return Element.prototype.querySelector.call(t,e)},children(e,t){return[].concat(...e.children).filter(e=>e.matches(t))},parents(e,t){let n=[],r=e.parentNode.closest(t);for(;r;)n.push(r),r=r.parentNode.closest(t);return n},prev(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return[n];n=n.previousElementSibling}return[]},next(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return[n];n=n.nextElementSibling}return[]},focusableChildren(e){let t=[`a`,`button`,`input`,`textarea`,`select`,`details`,`[tabindex]`,`[contenteditable="true"]`].map(e=>`${e}:not([tabindex^="-"])`).join(`,`);return this.find(t,e).filter(e=>!Lx(e)&&Ix(e))},getSelectorFromElement(e){let t=bS(e);return t&&xS.findOne(t)?t:null},getElementFromSelector(e){let t=bS(e);return t?xS.findOne(t):null},getMultipleElementsFromSelector(e){let t=bS(e);return t?xS.find(t):[]}},SS=(e,t=`hide`)=>{let n=`click.dismiss${e.EVENT_KEY}`,r=e.NAME;fS.on(document,n,`[data-bs-dismiss="${r}"]`,function(n){if([`A`,`AREA`].includes(this.tagName)&&n.preventDefault(),Lx(this))return;let i=xS.getElementFromSelector(this)||this.closest(`.${r}`);e.getOrCreateInstance(i)[t]()})},CS=`alert`,wS=`.bs.alert`,TS=`close${wS}`,ES=`closed${wS}`,DS=`fade`,OS=`show`,kS=class e extends yS{static get NAME(){return CS}close(){if(fS.trigger(this._element,TS).defaultPrevented)return;this._element.classList.remove(OS);let e=this._element.classList.contains(DS);this._queueCallback(()=>this._destroyElement(),this._element,e)}_destroyElement(){this._element.remove(),fS.trigger(this._element,ES),this.dispose()}static jQueryInterface(t){return this.each(function(){let n=e.getOrCreateInstance(this);if(typeof t==`string`){if(n[t]===void 0||t.startsWith(`_`)||t===`constructor`)throw TypeError(`No method named "${t}"`);n[t](this)}})}};SS(kS,`close`),Gx(kS);var AS=`button`,jS=`.bs.button`,MS=`.data-api`,NS=`active`,PS=`[data-bs-toggle="button"]`,FS=`click${jS}${MS}`,IS=class e extends yS{static get NAME(){return AS}toggle(){this._element.setAttribute(`aria-pressed`,this._element.classList.toggle(NS))}static jQueryInterface(t){return this.each(function(){let n=e.getOrCreateInstance(this);t===`toggle`&&n[t]()})}};fS.on(document,FS,PS,e=>{e.preventDefault();let t=e.target.closest(PS);IS.getOrCreateInstance(t).toggle()}),Gx(IS);var LS=`swipe`,RS=`.bs.swipe`,zS=`touchstart${RS}`,BS=`touchmove${RS}`,VS=`touchend${RS}`,HS=`pointerdown${RS}`,US=`pointerup${RS}`,WS=`touch`,GS=`pen`,KS=`pointer-event`,qS=40,JS={endCallback:null,leftCallback:null,rightCallback:null},YS={endCallback:`(function|null)`,leftCallback:`(function|null)`,rightCallback:`(function|null)`},XS=class e extends _S{constructor(t,n){super(),this._element=t,!(!t||!e.isSupported())&&(this._config=this._getConfig(n),this._deltaX=0,this._supportPointerEvents=!!window.PointerEvent,this._initEvents())}static get Default(){return JS}static get DefaultType(){return YS}static get NAME(){return LS}dispose(){fS.off(this._element,RS)}_start(e){if(!this._supportPointerEvents){this._deltaX=e.touches[0].clientX;return}this._eventIsPointerPenTouch(e)&&(this._deltaX=e.clientX)}_end(e){this._eventIsPointerPenTouch(e)&&(this._deltaX=e.clientX-this._deltaX),this._handleSwipe(),Kx(this._config.endCallback)}_move(e){this._deltaX=e.touches&&e.touches.length>1?0:e.touches[0].clientX-this._deltaX}_handleSwipe(){let e=Math.abs(this._deltaX);if(e<=qS)return;let t=e/this._deltaX;this._deltaX=0,t&&Kx(t>0?this._config.rightCallback:this._config.leftCallback)}_initEvents(){this._supportPointerEvents?(fS.on(this._element,HS,e=>this._start(e)),fS.on(this._element,US,e=>this._end(e)),this._element.classList.add(KS)):(fS.on(this._element,zS,e=>this._start(e)),fS.on(this._element,BS,e=>this._move(e)),fS.on(this._element,VS,e=>this._end(e)))}_eventIsPointerPenTouch(e){return this._supportPointerEvents&&(e.pointerType===GS||e.pointerType===WS)}static isSupported(){return`ontouchstart`in document.documentElement||navigator.maxTouchPoints>0}},ZS=`carousel`,QS=`.bs.carousel`,$S=`.data-api`,eC=`ArrowLeft`,tC=`ArrowRight`,nC=500,rC=`next`,iC=`prev`,aC=`left`,oC=`right`,sC=`slide${QS}`,cC=`slid${QS}`,lC=`keydown${QS}`,uC=`mouseenter${QS}`,dC=`mouseleave${QS}`,fC=`dragstart${QS}`,pC=`load${QS}${$S}`,mC=`click${QS}${$S}`,hC=`carousel`,gC=`active`,_C=`slide`,vC=`carousel-item-end`,yC=`carousel-item-start`,bC=`carousel-item-next`,xC=`carousel-item-prev`,SC=`.active`,CC=`.carousel-item`,wC=`.active.carousel-item`,TC=`.carousel-item img`,EC=`.carousel-indicators`,DC=`[data-bs-slide], [data-bs-slide-to]`,OC=`[data-bs-ride="carousel"]`,kC={[eC]:oC,[tC]:aC},AC={interval:5e3,keyboard:!0,pause:`hover`,ride:!1,touch:!0,wrap:!0},jC={interval:`(number|boolean)`,keyboard:`boolean`,pause:`(string|boolean)`,ride:`(boolean|string)`,touch:`boolean`,wrap:`boolean`},MC=class e extends yS{constructor(e,t){super(e,t),this._interval=null,this._activeElement=null,this._isSliding=!1,this.touchTimeout=null,this._swipeHelper=null,this._indicatorsElement=xS.findOne(EC,this._element),this._addEventListeners(),this._config.ride===hC&&this.cycle()}static get Default(){return AC}static get DefaultType(){return jC}static get NAME(){return ZS}next(){this._slide(rC)}nextWhenVisible(){!document.hidden&&Ix(this._element)&&this.next()}prev(){this._slide(iC)}pause(){this._isSliding&&Nx(this._element),this._clearInterval()}cycle(){this._clearInterval(),this._updateInterval(),this._interval=setInterval(()=>this.nextWhenVisible(),this._config.interval)}_maybeEnableCycle(){if(this._config.ride){if(this._isSliding){fS.one(this._element,cC,()=>this.cycle());return}this.cycle()}}to(e){let t=this._getItems();if(e>t.length-1||e<0)return;if(this._isSliding){fS.one(this._element,cC,()=>this.to(e));return}let n=this._getItemIndex(this._getActive());if(n===e)return;let r=e>n?rC:iC;this._slide(r,t[e])}dispose(){this._swipeHelper&&this._swipeHelper.dispose(),super.dispose()}_configAfterMerge(e){return e.defaultInterval=e.interval,e}_addEventListeners(){this._config.keyboard&&fS.on(this._element,lC,e=>this._keydown(e)),this._config.pause===`hover`&&(fS.on(this._element,uC,()=>this.pause()),fS.on(this._element,dC,()=>this._maybeEnableCycle())),this._config.touch&&XS.isSupported()&&this._addTouchEventListeners()}_addTouchEventListeners(){for(let e of xS.find(TC,this._element))fS.on(e,fC,e=>e.preventDefault());let e={leftCallback:()=>this._slide(this._directionToOrder(aC)),rightCallback:()=>this._slide(this._directionToOrder(oC)),endCallback:()=>{this._config.pause===`hover`&&(this.pause(),this.touchTimeout&&clearTimeout(this.touchTimeout),this.touchTimeout=setTimeout(()=>this._maybeEnableCycle(),nC+this._config.interval))}};this._swipeHelper=new XS(this._element,e)}_keydown(e){if(/input|textarea/i.test(e.target.tagName))return;let t=kC[e.key];t&&(e.preventDefault(),this._slide(this._directionToOrder(t)))}_getItemIndex(e){return this._getItems().indexOf(e)}_setActiveIndicatorElement(e){if(!this._indicatorsElement)return;let t=xS.findOne(SC,this._indicatorsElement);t.classList.remove(gC),t.removeAttribute(`aria-current`);let n=xS.findOne(`[data-bs-slide-to="${e}"]`,this._indicatorsElement);n&&(n.classList.add(gC),n.setAttribute(`aria-current`,`true`))}_updateInterval(){let e=this._activeElement||this._getActive();if(!e)return;let t=Number.parseInt(e.getAttribute(`data-bs-interval`),10);this._config.interval=t||this._config.defaultInterval}_slide(e,t=null){if(this._isSliding)return;let n=this._getActive(),r=e===rC,i=t||Jx(this._getItems(),n,r,this._config.wrap);if(i===n)return;let a=this._getItemIndex(i),o=t=>fS.trigger(this._element,t,{relatedTarget:i,direction:this._orderToDirection(e),from:this._getItemIndex(n),to:a});if(o(sC).defaultPrevented||!n||!i)return;let s=!!this._interval;this.pause(),this._isSliding=!0,this._setActiveIndicatorElement(a),this._activeElement=i;let c=r?yC:vC,l=r?bC:xC;i.classList.add(l),Bx(i),n.classList.add(c),i.classList.add(c),this._queueCallback(()=>{i.classList.remove(c,l),i.classList.add(gC),n.classList.remove(gC,l,c),this._isSliding=!1,o(cC)},n,this._isAnimated()),s&&this.cycle()}_isAnimated(){return this._element.classList.contains(_C)}_getActive(){return xS.findOne(wC,this._element)}_getItems(){return xS.find(CC,this._element)}_clearInterval(){this._interval&&=(clearInterval(this._interval),null)}_directionToOrder(e){return Wx()?e===aC?iC:rC:e===aC?rC:iC}_orderToDirection(e){return Wx()?e===iC?aC:oC:e===iC?oC:aC}static jQueryInterface(t){return this.each(function(){let n=e.getOrCreateInstance(this,t);if(typeof t==`number`){n.to(t);return}if(typeof t==`string`){if(n[t]===void 0||t.startsWith(`_`)||t===`constructor`)throw TypeError(`No method named "${t}"`);n[t]()}})}};fS.on(document,mC,DC,function(e){let t=xS.getElementFromSelector(this);if(!t||!t.classList.contains(hC))return;e.preventDefault();let n=MC.getOrCreateInstance(t),r=this.getAttribute(`data-bs-slide-to`);if(r){n.to(r),n._maybeEnableCycle();return}if(gS.getDataAttribute(this,`slide`)===`next`){n.next(),n._maybeEnableCycle();return}n.prev(),n._maybeEnableCycle()}),fS.on(window,pC,()=>{let e=xS.find(OC);for(let t of e)MC.getOrCreateInstance(t)}),Gx(MC);var NC=`collapse`,PC=`.bs.collapse`,FC=`.data-api`,IC=`show${PC}`,LC=`shown${PC}`,RC=`hide${PC}`,zC=`hidden${PC}`,BC=`click${PC}${FC}`,VC=`show`,HC=`collapse`,UC=`collapsing`,WC=`collapsed`,GC=`:scope .${HC} .${HC}`,KC=`collapse-horizontal`,qC=`width`,JC=`height`,YC=`.collapse.show, .collapse.collapsing`,XC=`[data-bs-toggle="collapse"]`,ZC={parent:null,toggle:!0},QC={parent:`(null|element)`,toggle:`boolean`},$C=class e extends yS{constructor(e,t){super(e,t),this._isTransitioning=!1,this._triggerArray=[];let n=xS.find(XC);for(let e of n){let t=xS.getSelectorFromElement(e),n=xS.find(t).filter(e=>e===this._element);t!==null&&n.length&&this._triggerArray.push(e)}this._initializeChildren(),this._config.parent||this._addAriaAndCollapsedClass(this._triggerArray,this._isShown()),this._config.toggle&&this.toggle()}static get Default(){return ZC}static get DefaultType(){return QC}static get NAME(){return NC}toggle(){this._isShown()?this.hide():this.show()}show(){if(this._isTransitioning||this._isShown())return;let t=[];if(this._config.parent&&(t=this._getFirstLevelChildren(YC).filter(e=>e!==this._element).map(t=>e.getOrCreateInstance(t,{toggle:!1}))),t.length&&t[0]._isTransitioning||fS.trigger(this._element,IC).defaultPrevented)return;for(let e of t)e.hide();let n=this._getDimension();this._element.classList.remove(HC),this._element.classList.add(UC),this._element.style[n]=0,this._addAriaAndCollapsedClass(this._triggerArray,!0),this._isTransitioning=!0;let r=()=>{this._isTransitioning=!1,this._element.classList.remove(UC),this._element.classList.add(HC,VC),this._element.style[n]=``,fS.trigger(this._element,LC)},i=`scroll${n[0].toUpperCase()+n.slice(1)}`;this._queueCallback(r,this._element,!0),this._element.style[n]=`${this._element[i]}px`}hide(){if(this._isTransitioning||!this._isShown()||fS.trigger(this._element,RC).defaultPrevented)return;let e=this._getDimension();this._element.style[e]=`${this._element.getBoundingClientRect()[e]}px`,Bx(this._element),this._element.classList.add(UC),this._element.classList.remove(HC,VC);for(let e of this._triggerArray){let t=xS.getElementFromSelector(e);t&&!this._isShown(t)&&this._addAriaAndCollapsedClass([e],!1)}this._isTransitioning=!0;let t=()=>{this._isTransitioning=!1,this._element.classList.remove(UC),this._element.classList.add(HC),fS.trigger(this._element,zC)};this._element.style[e]=``,this._queueCallback(t,this._element,!0)}_isShown(e=this._element){return e.classList.contains(VC)}_configAfterMerge(e){return e.toggle=!!e.toggle,e.parent=Fx(e.parent),e}_getDimension(){return this._element.classList.contains(KC)?qC:JC}_initializeChildren(){if(!this._config.parent)return;let e=this._getFirstLevelChildren(XC);for(let t of e){let e=xS.getElementFromSelector(t);e&&this._addAriaAndCollapsedClass([t],this._isShown(e))}}_getFirstLevelChildren(e){let t=xS.find(GC,this._config.parent);return xS.find(e,this._config.parent).filter(e=>!t.includes(e))}_addAriaAndCollapsedClass(e,t){if(e.length)for(let n of e)n.classList.toggle(WC,!t),n.setAttribute(`aria-expanded`,t)}static jQueryInterface(t){let n={};return typeof t==`string`&&/show|hide/.test(t)&&(n.toggle=!1),this.each(function(){let r=e.getOrCreateInstance(this,n);if(typeof t==`string`){if(r[t]===void 0)throw TypeError(`No method named "${t}"`);r[t]()}})}};fS.on(document,BC,XC,function(e){(e.target.tagName===`A`||e.delegateTarget&&e.delegateTarget.tagName===`A`)&&e.preventDefault();for(let e of xS.getMultipleElementsFromSelector(this))$C.getOrCreateInstance(e,{toggle:!1}).toggle()}),Gx($C);var ew=`dropdown`,tw=`.bs.dropdown`,nw=`.data-api`,rw=`Escape`,iw=`Tab`,aw=`ArrowUp`,ow=`ArrowDown`,sw=2,cw=`hide${tw}`,lw=`hidden${tw}`,uw=`show${tw}`,dw=`shown${tw}`,fw=`click${tw}${nw}`,pw=`keydown${tw}${nw}`,mw=`keyup${tw}${nw}`,hw=`show`,gw=`dropup`,_w=`dropend`,vw=`dropstart`,yw=`dropup-center`,bw=`dropdown-center`,xw=`[data-bs-toggle="dropdown"]:not(.disabled):not(:disabled)`,Sw=`${xw}.${hw}`,Cw=`.dropdown-menu`,ww=`.navbar`,Tw=`.navbar-nav`,Ew=`.dropdown-menu .dropdown-item:not(.disabled):not(:disabled)`,Dw=Wx()?`top-end`:`top-start`,Ow=Wx()?`top-start`:`top-end`,kw=Wx()?`bottom-end`:`bottom-start`,Aw=Wx()?`bottom-start`:`bottom-end`,jw=Wx()?`left-start`:`right-start`,Mw=Wx()?`right-start`:`left-start`,Nw=`top`,Pw=`bottom`,Fw={autoClose:!0,boundary:`clippingParents`,display:`dynamic`,offset:[0,2],popperConfig:null,reference:`toggle`},Iw={autoClose:`(boolean|string)`,boundary:`(string|element)`,display:`string`,offset:`(array|string|function)`,popperConfig:`(null|object|function)`,reference:`(string|element|object)`},Lw=class e extends yS{constructor(e,t){super(e,t),this._popper=null,this._parent=this._element.parentNode,this._menu=xS.next(this._element,Cw)[0]||xS.prev(this._element,Cw)[0]||xS.findOne(Cw,this._parent),this._inNavbar=this._detectNavbar()}static get Default(){return Fw}static get DefaultType(){return Iw}static get NAME(){return ew}toggle(){return this._isShown()?this.hide():this.show()}show(){if(Lx(this._element)||this._isShown())return;let e={relatedTarget:this._element};if(!fS.trigger(this._element,uw,e).defaultPrevented){if(this._createPopper(),`ontouchstart`in document.documentElement&&!this._parent.closest(Tw))for(let e of[].concat(...document.body.children))fS.on(e,`mouseover`,zx);this._element.focus(),this._element.setAttribute(`aria-expanded`,!0),this._menu.classList.add(hw),this._element.classList.add(hw),fS.trigger(this._element,dw,e)}}hide(){if(Lx(this._element)||!this._isShown())return;let e={relatedTarget:this._element};this._completeHide(e)}dispose(){this._popper&&this._popper.destroy(),super.dispose()}update(){this._inNavbar=this._detectNavbar(),this._popper&&this._popper.update()}_completeHide(e){if(!fS.trigger(this._element,cw,e).defaultPrevented){if(`ontouchstart`in document.documentElement)for(let e of[].concat(...document.body.children))fS.off(e,`mouseover`,zx);this._popper&&this._popper.destroy(),this._menu.classList.remove(hw),this._element.classList.remove(hw),this._element.setAttribute(`aria-expanded`,`false`),gS.removeDataAttribute(this._menu,`popper`),fS.trigger(this._element,lw,e)}}_getConfig(e){if(e=super._getConfig(e),typeof e.reference==`object`&&!Px(e.reference)&&typeof e.reference.getBoundingClientRect!=`function`)throw TypeError(`${ew.toUpperCase()}: Option "reference" provided type "object" without a required "getBoundingClientRect" method.`);return e}_createPopper(){if(Cx===void 0)throw TypeError(`Bootstrap's dropdowns require Popper (https://popper.js.org/docs/v2/)`);let e=this._element;this._config.reference===`parent`?e=this._parent:Px(this._config.reference)?e=Fx(this._config.reference):typeof this._config.reference==`object`&&(e=this._config.reference);let t=this._getPopperConfig();this._popper=Sx(e,this._menu,t)}_isShown(){return this._menu.classList.contains(hw)}_getPlacement(){let e=this._parent;if(e.classList.contains(_w))return jw;if(e.classList.contains(vw))return Mw;if(e.classList.contains(yw))return Nw;if(e.classList.contains(bw))return Pw;let t=getComputedStyle(this._menu).getPropertyValue(`--bs-position`).trim()===`end`;return e.classList.contains(gw)?t?Ow:Dw:t?Aw:kw}_detectNavbar(){return this._element.closest(ww)!==null}_getOffset(){let{offset:e}=this._config;return typeof e==`string`?e.split(`,`).map(e=>Number.parseInt(e,10)):typeof e==`function`?t=>e(t,this._element):e}_getPopperConfig(){let e={placement:this._getPlacement(),modifiers:[{name:`preventOverflow`,options:{boundary:this._config.boundary}},{name:`offset`,options:{offset:this._getOffset()}}]};return(this._inNavbar||this._config.display===`static`)&&(gS.setDataAttribute(this._menu,`popper`,`static`),e.modifiers=[{name:`applyStyles`,enabled:!1}]),{...e,...Kx(this._config.popperConfig,[void 0,e])}}_selectMenuItem({key:e,target:t}){let n=xS.find(Ew,this._menu).filter(e=>Ix(e));n.length&&Jx(n,t,e===ow,!n.includes(t)).focus()}static jQueryInterface(t){return this.each(function(){let n=e.getOrCreateInstance(this,t);if(typeof t==`string`){if(n[t]===void 0)throw TypeError(`No method named "${t}"`);n[t]()}})}static clearMenus(t){if(t.button===sw||t.type===`keyup`&&t.key!==iw)return;let n=xS.find(Sw);for(let r of n){let n=e.getInstance(r);if(!n||n._config.autoClose===!1)continue;let i=t.composedPath(),a=i.includes(n._menu);if(i.includes(n._element)||n._config.autoClose===`inside`&&!a||n._config.autoClose===`outside`&&a||n._menu.contains(t.target)&&(t.type===`keyup`&&t.key===iw||/input|select|option|textarea|form/i.test(t.target.tagName)))continue;let o={relatedTarget:n._element};t.type===`click`&&(o.clickEvent=t),n._completeHide(o)}}static dataApiKeydownHandler(t){let n=/input|textarea/i.test(t.target.tagName),r=t.key===rw,i=[aw,ow].includes(t.key);if(!i&&!r||n&&!r)return;t.preventDefault();let a=this.matches(xw)?this:xS.prev(this,xw)[0]||xS.next(this,xw)[0]||xS.findOne(xw,t.delegateTarget.parentNode),o=e.getOrCreateInstance(a);if(i){t.stopPropagation(),o.show(),o._selectMenuItem(t);return}o._isShown()&&(t.stopPropagation(),o.hide(),a.focus())}};fS.on(document,pw,xw,Lw.dataApiKeydownHandler),fS.on(document,pw,Cw,Lw.dataApiKeydownHandler),fS.on(document,fw,Lw.clearMenus),fS.on(document,mw,Lw.clearMenus),fS.on(document,fw,xw,function(e){e.preventDefault(),Lw.getOrCreateInstance(this).toggle()}),Gx(Lw);var Rw=`backdrop`,zw=`fade`,Bw=`show`,Vw=`mousedown.bs.${Rw}`,Hw={className:`modal-backdrop`,clickCallback:null,isAnimated:!1,isVisible:!0,rootElement:`body`},Uw={className:`string`,clickCallback:`(function|null)`,isAnimated:`boolean`,isVisible:`boolean`,rootElement:`(element|string)`},Ww=class extends _S{constructor(e){super(),this._config=this._getConfig(e),this._isAppended=!1,this._element=null}static get Default(){return Hw}static get DefaultType(){return Uw}static get NAME(){return Rw}show(e){if(!this._config.isVisible){Kx(e);return}this._append();let t=this._getElement();this._config.isAnimated&&Bx(t),t.classList.add(Bw),this._emulateAnimation(()=>{Kx(e)})}hide(e){if(!this._config.isVisible){Kx(e);return}this._getElement().classList.remove(Bw),this._emulateAnimation(()=>{this.dispose(),Kx(e)})}dispose(){this._isAppended&&=(fS.off(this._element,Vw),this._element.remove(),!1)}_getElement(){if(!this._element){let e=document.createElement(`div`);e.className=this._config.className,this._config.isAnimated&&e.classList.add(zw),this._element=e}return this._element}_configAfterMerge(e){return e.rootElement=Fx(e.rootElement),e}_append(){if(this._isAppended)return;let e=this._getElement();this._config.rootElement.append(e),fS.on(e,Vw,()=>{Kx(this._config.clickCallback)}),this._isAppended=!0}_emulateAnimation(e){qx(e,this._getElement(),this._config.isAnimated)}},Gw=`focustrap`,Kw=`.bs.focustrap`,qw=`focusin${Kw}`,Jw=`keydown.tab${Kw}`,Yw=`Tab`,Xw=`forward`,Zw=`backward`,Qw={autofocus:!0,trapElement:null},$w={autofocus:`boolean`,trapElement:`element`},eT=class extends _S{constructor(e){super(),this._config=this._getConfig(e),this._isActive=!1,this._lastTabNavDirection=null}static get Default(){return Qw}static get DefaultType(){return $w}static get NAME(){return Gw}activate(){this._isActive||=(this._config.autofocus&&this._config.trapElement.focus(),fS.off(document,Kw),fS.on(document,qw,e=>this._handleFocusin(e)),fS.on(document,Jw,e=>this._handleKeydown(e)),!0)}deactivate(){this._isActive&&(this._isActive=!1,fS.off(document,Kw))}_handleFocusin(e){let{trapElement:t}=this._config;if(e.target===document||e.target===t||t.contains(e.target))return;let n=xS.focusableChildren(t);n.length===0?t.focus():this._lastTabNavDirection===Zw?n[n.length-1].focus():n[0].focus()}_handleKeydown(e){e.key===Yw&&(this._lastTabNavDirection=e.shiftKey?Zw:Xw)}},tT=`.fixed-top, .fixed-bottom, .is-fixed, .sticky-top`,nT=`.sticky-top`,rT=`padding-right`,iT=`margin-right`,aT=class{constructor(){this._element=document.body}getWidth(){let e=document.documentElement.clientWidth;return Math.abs(window.innerWidth-e)}hide(){let e=this.getWidth();this._disableOverFlow(),this._setElementAttributes(this._element,rT,t=>t+e),this._setElementAttributes(tT,rT,t=>t+e),this._setElementAttributes(nT,iT,t=>t-e)}reset(){this._resetElementAttributes(this._element,`overflow`),this._resetElementAttributes(this._element,rT),this._resetElementAttributes(tT,rT),this._resetElementAttributes(nT,iT)}isOverflowing(){return this.getWidth()>0}_disableOverFlow(){this._saveInitialAttribute(this._element,`overflow`),this._element.style.overflow=`hidden`}_setElementAttributes(e,t,n){let r=this.getWidth();this._applyManipulationCallback(e,e=>{if(e!==this._element&&window.innerWidth>e.clientWidth+r)return;this._saveInitialAttribute(e,t);let i=window.getComputedStyle(e).getPropertyValue(t);e.style.setProperty(t,`${n(Number.parseFloat(i))}px`)})}_saveInitialAttribute(e,t){let n=e.style.getPropertyValue(t);n&&gS.setDataAttribute(e,t,n)}_resetElementAttributes(e,t){this._applyManipulationCallback(e,e=>{let n=gS.getDataAttribute(e,t);if(n===null){e.style.removeProperty(t);return}gS.removeDataAttribute(e,t),e.style.setProperty(t,n)})}_applyManipulationCallback(e,t){if(Px(e)){t(e);return}for(let n of xS.find(e,this._element))t(n)}},oT=`modal`,sT=`.bs.modal`,cT=`.data-api`,lT=`Escape`,uT=`hide${sT}`,dT=`hidePrevented${sT}`,fT=`hidden${sT}`,pT=`show${sT}`,mT=`shown${sT}`,hT=`resize${sT}`,gT=`click.dismiss${sT}`,_T=`mousedown.dismiss${sT}`,vT=`keydown.dismiss${sT}`,yT=`click${sT}${cT}`,bT=`modal-open`,xT=`fade`,ST=`show`,CT=`modal-static`,wT=`.modal.show`,TT=`.modal-dialog`,ET=`.modal-body`,DT=`[data-bs-toggle="modal"]`,OT={backdrop:!0,focus:!0,keyboard:!0},kT={backdrop:`(boolean|string)`,focus:`boolean`,keyboard:`boolean`},AT=class e extends yS{constructor(e,t){super(e,t),this._dialog=xS.findOne(TT,this._element),this._backdrop=this._initializeBackDrop(),this._focustrap=this._initializeFocusTrap(),this._isShown=!1,this._isTransitioning=!1,this._scrollBar=new aT,this._addEventListeners()}static get Default(){return OT}static get DefaultType(){return kT}static get NAME(){return oT}toggle(e){return this._isShown?this.hide():this.show(e)}show(e){this._isShown||this._isTransitioning||fS.trigger(this._element,pT,{relatedTarget:e}).defaultPrevented||(this._isShown=!0,this._isTransitioning=!0,this._scrollBar.hide(),document.body.classList.add(bT),this._adjustDialog(),this._backdrop.show(()=>this._showElement(e)))}hide(){!this._isShown||this._isTransitioning||fS.trigger(this._element,uT).defaultPrevented||(this._isShown=!1,this._isTransitioning=!0,this._focustrap.deactivate(),this._element.classList.remove(ST),this._queueCallback(()=>this._hideModal(),this._element,this._isAnimated()))}dispose(){fS.off(window,sT),fS.off(this._dialog,sT),this._backdrop.dispose(),this._focustrap.deactivate(),super.dispose()}handleUpdate(){this._adjustDialog()}_initializeBackDrop(){return new Ww({isVisible:!!this._config.backdrop,isAnimated:this._isAnimated()})}_initializeFocusTrap(){return new eT({trapElement:this._element})}_showElement(e){document.body.contains(this._element)||document.body.append(this._element),this._element.style.display=`block`,this._element.removeAttribute(`aria-hidden`),this._element.setAttribute(`aria-modal`,!0),this._element.setAttribute(`role`,`dialog`),this._element.scrollTop=0;let t=xS.findOne(ET,this._dialog);t&&(t.scrollTop=0),Bx(this._element),this._element.classList.add(ST),this._queueCallback(()=>{this._config.focus&&this._focustrap.activate(),this._isTransitioning=!1,fS.trigger(this._element,mT,{relatedTarget:e})},this._dialog,this._isAnimated())}_addEventListeners(){fS.on(this._element,vT,e=>{if(e.key===lT){if(this._config.keyboard){this.hide();return}this._triggerBackdropTransition()}}),fS.on(window,hT,()=>{this._isShown&&!this._isTransitioning&&this._adjustDialog()}),fS.on(this._element,_T,e=>{fS.one(this._element,gT,t=>{if(!(this._element!==e.target||this._element!==t.target)){if(this._config.backdrop===`static`){this._triggerBackdropTransition();return}this._config.backdrop&&this.hide()}})})}_hideModal(){this._element.style.display=`none`,this._element.setAttribute(`aria-hidden`,!0),this._element.removeAttribute(`aria-modal`),this._element.removeAttribute(`role`),this._isTransitioning=!1,this._backdrop.hide(()=>{document.body.classList.remove(bT),this._resetAdjustments(),this._scrollBar.reset(),fS.trigger(this._element,fT)})}_isAnimated(){return this._element.classList.contains(xT)}_triggerBackdropTransition(){if(fS.trigger(this._element,dT).defaultPrevented)return;let e=this._element.scrollHeight>document.documentElement.clientHeight,t=this._element.style.overflowY;t===`hidden`||this._element.classList.contains(CT)||(e||(this._element.style.overflowY=`hidden`),this._element.classList.add(CT),this._queueCallback(()=>{this._element.classList.remove(CT),this._queueCallback(()=>{this._element.style.overflowY=t},this._dialog)},this._dialog),this._element.focus())}_adjustDialog(){let e=this._element.scrollHeight>document.documentElement.clientHeight,t=this._scrollBar.getWidth(),n=t>0;if(n&&!e){let e=Wx()?`paddingLeft`:`paddingRight`;this._element.style[e]=`${t}px`}if(!n&&e){let e=Wx()?`paddingRight`:`paddingLeft`;this._element.style[e]=`${t}px`}}_resetAdjustments(){this._element.style.paddingLeft=``,this._element.style.paddingRight=``}static jQueryInterface(t,n){return this.each(function(){let r=e.getOrCreateInstance(this,t);if(typeof t==`string`){if(r[t]===void 0)throw TypeError(`No method named "${t}"`);r[t](n)}})}};fS.on(document,yT,DT,function(e){let t=xS.getElementFromSelector(this);[`A`,`AREA`].includes(this.tagName)&&e.preventDefault(),fS.one(t,pT,e=>{e.defaultPrevented||fS.one(t,fT,()=>{Ix(this)&&this.focus()})});let n=xS.findOne(wT);n&&AT.getInstance(n).hide(),AT.getOrCreateInstance(t).toggle(this)}),SS(AT),Gx(AT);var jT=`offcanvas`,MT=`.bs.offcanvas`,NT=`.data-api`,PT=`load${MT}${NT}`,FT=`Escape`,IT=`show`,LT=`showing`,RT=`hiding`,zT=`offcanvas-backdrop`,BT=`.offcanvas.show`,VT=`show${MT}`,HT=`shown${MT}`,UT=`hide${MT}`,WT=`hidePrevented${MT}`,GT=`hidden${MT}`,KT=`resize${MT}`,qT=`click${MT}${NT}`,JT=`keydown.dismiss${MT}`,YT=`[data-bs-toggle="offcanvas"]`,XT={backdrop:!0,keyboard:!0,scroll:!1},ZT={backdrop:`(boolean|string)`,keyboard:`boolean`,scroll:`boolean`},QT=class e extends yS{constructor(e,t){super(e,t),this._isShown=!1,this._backdrop=this._initializeBackDrop(),this._focustrap=this._initializeFocusTrap(),this._addEventListeners()}static get Default(){return XT}static get DefaultType(){return ZT}static get NAME(){return jT}toggle(e){return this._isShown?this.hide():this.show(e)}show(e){this._isShown||fS.trigger(this._element,VT,{relatedTarget:e}).defaultPrevented||(this._isShown=!0,this._backdrop.show(),this._config.scroll||new aT().hide(),this._element.setAttribute(`aria-modal`,!0),this._element.setAttribute(`role`,`dialog`),this._element.classList.add(LT),this._queueCallback(()=>{(!this._config.scroll||this._config.backdrop)&&this._focustrap.activate(),this._element.classList.add(IT),this._element.classList.remove(LT),fS.trigger(this._element,HT,{relatedTarget:e})},this._element,!0))}hide(){!this._isShown||fS.trigger(this._element,UT).defaultPrevented||(this._focustrap.deactivate(),this._element.blur(),this._isShown=!1,this._element.classList.add(RT),this._backdrop.hide(),this._queueCallback(()=>{this._element.classList.remove(IT,RT),this._element.removeAttribute(`aria-modal`),this._element.removeAttribute(`role`),this._config.scroll||new aT().reset(),fS.trigger(this._element,GT)},this._element,!0))}dispose(){this._backdrop.dispose(),this._focustrap.deactivate(),super.dispose()}_initializeBackDrop(){let e=()=>{if(this._config.backdrop===`static`){fS.trigger(this._element,WT);return}this.hide()},t=!!this._config.backdrop;return new Ww({className:zT,isVisible:t,isAnimated:!0,rootElement:this._element.parentNode,clickCallback:t?e:null})}_initializeFocusTrap(){return new eT({trapElement:this._element})}_addEventListeners(){fS.on(this._element,JT,e=>{if(e.key===FT){if(this._config.keyboard){this.hide();return}fS.trigger(this._element,WT)}})}static jQueryInterface(t){return this.each(function(){let n=e.getOrCreateInstance(this,t);if(typeof t==`string`){if(n[t]===void 0||t.startsWith(`_`)||t===`constructor`)throw TypeError(`No method named "${t}"`);n[t](this)}})}};fS.on(document,qT,YT,function(e){let t=xS.getElementFromSelector(this);if([`A`,`AREA`].includes(this.tagName)&&e.preventDefault(),Lx(this))return;fS.one(t,GT,()=>{Ix(this)&&this.focus()});let n=xS.findOne(BT);n&&n!==t&&QT.getInstance(n).hide(),QT.getOrCreateInstance(t).toggle(this)}),fS.on(window,PT,()=>{for(let e of xS.find(BT))QT.getOrCreateInstance(e).show()}),fS.on(window,KT,()=>{for(let e of xS.find(`[aria-modal][class*=show][class*=offcanvas-]`))getComputedStyle(e).position!==`fixed`&&QT.getOrCreateInstance(e).hide()}),SS(QT),Gx(QT);var $T={"*":[`class`,`dir`,`id`,`lang`,`role`,/^aria-[\w-]*$/i],a:[`target`,`href`,`title`,`rel`],area:[],b:[],br:[],col:[],code:[],dd:[],div:[],dl:[],dt:[],em:[],hr:[],h1:[],h2:[],h3:[],h4:[],h5:[],h6:[],i:[],img:[`src`,`srcset`,`alt`,`title`,`width`,`height`],li:[],ol:[],p:[],pre:[],s:[],small:[],span:[],sub:[],sup:[],strong:[],u:[],ul:[]},eE=new Set([`background`,`cite`,`href`,`itemtype`,`longdesc`,`poster`,`src`,`xlink:href`]),tE=/^(?!javascript:)(?:[a-z0-9+.-]+:|[^&:/?#]*(?:[/?#]|$))/i,nE=(e,t)=>{let n=e.nodeName.toLowerCase();return t.includes(n)?eE.has(n)?!!tE.test(e.nodeValue):!0:t.filter(e=>e instanceof RegExp).some(e=>e.test(n))};function rE(e,t,n){if(!e.length)return e;if(n&&typeof n==`function`)return n(e);let r=new window.DOMParser().parseFromString(e,`text/html`),i=[].concat(...r.body.querySelectorAll(`*`));for(let e of i){let n=e.nodeName.toLowerCase();if(!Object.keys(t).includes(n)){e.remove();continue}let r=[].concat(...e.attributes),i=[].concat(t[`*`]||[],t[n]||[]);for(let t of r)nE(t,i)||e.removeAttribute(t.nodeName)}return r.body.innerHTML}var iE=`TemplateFactory`,aE={allowList:$T,content:{},extraClass:``,html:!1,sanitize:!0,sanitizeFn:null,template:`<div></div>`},oE={allowList:`object`,content:`object`,extraClass:`(string|function)`,html:`boolean`,sanitize:`boolean`,sanitizeFn:`(null|function)`,template:`string`},sE={entry:`(string|element|function|null)`,selector:`(string|element)`},cE=class extends _S{constructor(e){super(),this._config=this._getConfig(e)}static get Default(){return aE}static get DefaultType(){return oE}static get NAME(){return iE}getContent(){return Object.values(this._config.content).map(e=>this._resolvePossibleFunction(e)).filter(Boolean)}hasContent(){return this.getContent().length>0}changeContent(e){return this._checkContent(e),this._config.content={...this._config.content,...e},this}toHtml(){let e=document.createElement(`div`);e.innerHTML=this._maybeSanitize(this._config.template);for(let[t,n]of Object.entries(this._config.content))this._setContent(e,n,t);let t=e.children[0],n=this._resolvePossibleFunction(this._config.extraClass);return n&&t.classList.add(...n.split(` `)),t}_typeCheckConfig(e){super._typeCheckConfig(e),this._checkContent(e.content)}_checkContent(e){for(let[t,n]of Object.entries(e))super._typeCheckConfig({selector:t,entry:n},sE)}_setContent(e,t,n){let r=xS.findOne(n,e);if(r){if(t=this._resolvePossibleFunction(t),!t){r.remove();return}if(Px(t)){this._putElementInTemplate(Fx(t),r);return}if(this._config.html){r.innerHTML=this._maybeSanitize(t);return}r.textContent=t}}_maybeSanitize(e){return this._config.sanitize?rE(e,this._config.allowList,this._config.sanitizeFn):e}_resolvePossibleFunction(e){return Kx(e,[void 0,this])}_putElementInTemplate(e,t){if(this._config.html){t.innerHTML=``,t.append(e);return}t.textContent=e.textContent}},lE=`tooltip`,uE=new Set([`sanitize`,`allowList`,`sanitizeFn`]),dE=`fade`,fE=`modal`,pE=`show`,mE=`.tooltip-inner`,hE=`.${fE}`,gE=`hide.bs.modal`,_E=`hover`,vE=`focus`,yE=`click`,bE=`manual`,xE=`hide`,SE=`hidden`,CE=`show`,wE=`shown`,TE=`inserted`,EE=`click`,DE=`focusin`,OE=`focusout`,kE=`mouseenter`,AE=`mouseleave`,jE={AUTO:`auto`,TOP:`top`,RIGHT:Wx()?`left`:`right`,BOTTOM:`bottom`,LEFT:Wx()?`right`:`left`},ME={allowList:$T,animation:!0,boundary:`clippingParents`,container:!1,customClass:``,delay:0,fallbackPlacements:[`top`,`right`,`bottom`,`left`],html:!1,offset:[0,6],placement:`top`,popperConfig:null,sanitize:!0,sanitizeFn:null,selector:!1,template:`<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>`,title:``,trigger:`hover focus`},NE={allowList:`object`,animation:`boolean`,boundary:`(string|element)`,container:`(string|element|boolean)`,customClass:`(string|function)`,delay:`(number|object)`,fallbackPlacements:`array`,html:`boolean`,offset:`(array|string|function)`,placement:`(string|function)`,popperConfig:`(null|object|function)`,sanitize:`boolean`,sanitizeFn:`(null|function)`,selector:`(string|boolean)`,template:`string`,title:`(string|element|function)`,trigger:`string`},PE=class e extends yS{constructor(e,t){if(Cx===void 0)throw TypeError(`Bootstrap's tooltips require Popper (https://popper.js.org/docs/v2/)`);super(e,t),this._isEnabled=!0,this._timeout=0,this._isHovered=null,this._activeTrigger={},this._popper=null,this._templateFactory=null,this._newContent=null,this.tip=null,this._setListeners(),this._config.selector||this._fixTitle()}static get Default(){return ME}static get DefaultType(){return NE}static get NAME(){return lE}enable(){this._isEnabled=!0}disable(){this._isEnabled=!1}toggleEnabled(){this._isEnabled=!this._isEnabled}toggle(){if(this._isEnabled){if(this._isShown()){this._leave();return}this._enter()}}dispose(){clearTimeout(this._timeout),fS.off(this._element.closest(hE),gE,this._hideModalHandler),this._element.getAttribute(`data-bs-original-title`)&&this._element.setAttribute(`title`,this._element.getAttribute(`data-bs-original-title`)),this._disposePopper(),super.dispose()}show(){if(this._element.style.display===`none`)throw Error(`Please use show on visible elements`);if(!(this._isWithContent()&&this._isEnabled))return;let e=fS.trigger(this._element,this.constructor.eventName(CE)),t=(Rx(this._element)||this._element.ownerDocument.documentElement).contains(this._element);if(e.defaultPrevented||!t)return;this._disposePopper();let n=this._getTipElement();this._element.setAttribute(`aria-describedby`,n.getAttribute(`id`));let{container:r}=this._config;if(this._element.ownerDocument.documentElement.contains(this.tip)||(r.append(n),fS.trigger(this._element,this.constructor.eventName(TE))),this._popper=this._createPopper(n),n.classList.add(pE),`ontouchstart`in document.documentElement)for(let e of[].concat(...document.body.children))fS.on(e,`mouseover`,zx);this._queueCallback(()=>{fS.trigger(this._element,this.constructor.eventName(wE)),this._isHovered===!1&&this._leave(),this._isHovered=!1},this.tip,this._isAnimated())}hide(){if(!(!this._isShown()||fS.trigger(this._element,this.constructor.eventName(xE)).defaultPrevented)){if(this._getTipElement().classList.remove(pE),`ontouchstart`in document.documentElement)for(let e of[].concat(...document.body.children))fS.off(e,`mouseover`,zx);this._activeTrigger[yE]=!1,this._activeTrigger[vE]=!1,this._activeTrigger[_E]=!1,this._isHovered=null,this._queueCallback(()=>{this._isWithActiveTrigger()||(this._isHovered||this._disposePopper(),this._element.removeAttribute(`aria-describedby`),fS.trigger(this._element,this.constructor.eventName(SE)))},this.tip,this._isAnimated())}}update(){this._popper&&this._popper.update()}_isWithContent(){return!!this._getTitle()}_getTipElement(){return this.tip||=this._createTipElement(this._newContent||this._getContentForTemplate()),this.tip}_createTipElement(e){let t=this._getTemplateFactory(e).toHtml();if(!t)return null;t.classList.remove(dE,pE),t.classList.add(`bs-${this.constructor.NAME}-auto`);let n=jx(this.constructor.NAME).toString();return t.setAttribute(`id`,n),this._isAnimated()&&t.classList.add(dE),t}setContent(e){this._newContent=e,this._isShown()&&(this._disposePopper(),this.show())}_getTemplateFactory(e){return this._templateFactory?this._templateFactory.changeContent(e):this._templateFactory=new cE({...this._config,content:e,extraClass:this._resolvePossibleFunction(this._config.customClass)}),this._templateFactory}_getContentForTemplate(){return{[mE]:this._getTitle()}}_getTitle(){return this._resolvePossibleFunction(this._config.title)||this._element.getAttribute(`data-bs-original-title`)}_initializeOnDelegatedTarget(e){return this.constructor.getOrCreateInstance(e.delegateTarget,this._getDelegateConfig())}_isAnimated(){return this._config.animation||this.tip&&this.tip.classList.contains(dE)}_isShown(){return this.tip&&this.tip.classList.contains(pE)}_createPopper(e){let t=jE[Kx(this._config.placement,[this,e,this._element]).toUpperCase()];return Sx(this._element,e,this._getPopperConfig(t))}_getOffset(){let{offset:e}=this._config;return typeof e==`string`?e.split(`,`).map(e=>Number.parseInt(e,10)):typeof e==`function`?t=>e(t,this._element):e}_resolvePossibleFunction(e){return Kx(e,[this._element,this._element])}_getPopperConfig(e){let t={placement:e,modifiers:[{name:`flip`,options:{fallbackPlacements:this._config.fallbackPlacements}},{name:`offset`,options:{offset:this._getOffset()}},{name:`preventOverflow`,options:{boundary:this._config.boundary}},{name:`arrow`,options:{element:`.${this.constructor.NAME}-arrow`}},{name:`preSetPlacement`,enabled:!0,phase:`beforeMain`,fn:e=>{this._getTipElement().setAttribute(`data-popper-placement`,e.state.placement)}}]};return{...t,...Kx(this._config.popperConfig,[void 0,t])}}_setListeners(){let e=this._config.trigger.split(` `);for(let t of e)if(t===`click`)fS.on(this._element,this.constructor.eventName(EE),this._config.selector,e=>{let t=this._initializeOnDelegatedTarget(e);t._activeTrigger[yE]=!(t._isShown()&&t._activeTrigger[yE]),t.toggle()});else if(t!==bE){let e=t===_E?this.constructor.eventName(kE):this.constructor.eventName(DE),n=t===_E?this.constructor.eventName(AE):this.constructor.eventName(OE);fS.on(this._element,e,this._config.selector,e=>{let t=this._initializeOnDelegatedTarget(e);t._activeTrigger[e.type===`focusin`?vE:_E]=!0,t._enter()}),fS.on(this._element,n,this._config.selector,e=>{let t=this._initializeOnDelegatedTarget(e);t._activeTrigger[e.type===`focusout`?vE:_E]=t._element.contains(e.relatedTarget),t._leave()})}this._hideModalHandler=()=>{this._element&&this.hide()},fS.on(this._element.closest(hE),gE,this._hideModalHandler)}_fixTitle(){let e=this._element.getAttribute(`title`);e&&(!this._element.getAttribute(`aria-label`)&&!this._element.textContent.trim()&&this._element.setAttribute(`aria-label`,e),this._element.setAttribute(`data-bs-original-title`,e),this._element.removeAttribute(`title`))}_enter(){if(this._isShown()||this._isHovered){this._isHovered=!0;return}this._isHovered=!0,this._setTimeout(()=>{this._isHovered&&this.show()},this._config.delay.show)}_leave(){this._isWithActiveTrigger()||(this._isHovered=!1,this._setTimeout(()=>{this._isHovered||this.hide()},this._config.delay.hide))}_setTimeout(e,t){clearTimeout(this._timeout),this._timeout=setTimeout(e,t)}_isWithActiveTrigger(){return Object.values(this._activeTrigger).includes(!0)}_getConfig(e){let t=gS.getDataAttributes(this._element);for(let e of Object.keys(t))uE.has(e)&&delete t[e];return e={...t,...typeof e==`object`&&e?e:{}},e=this._mergeConfigObj(e),e=this._configAfterMerge(e),this._typeCheckConfig(e),e}_configAfterMerge(e){return e.container=e.container===!1?document.body:Fx(e.container),typeof e.delay==`number`&&(e.delay={show:e.delay,hide:e.delay}),typeof e.title==`number`&&(e.title=e.title.toString()),typeof e.content==`number`&&(e.content=e.content.toString()),e}_getDelegateConfig(){let e={};for(let[t,n]of Object.entries(this._config))this.constructor.Default[t]!==n&&(e[t]=n);return e.selector=!1,e.trigger=`manual`,e}_disposePopper(){this._popper&&=(this._popper.destroy(),null),this.tip&&=(this.tip.remove(),null)}static jQueryInterface(t){return this.each(function(){let n=e.getOrCreateInstance(this,t);if(typeof t==`string`){if(n[t]===void 0)throw TypeError(`No method named "${t}"`);n[t]()}})}};Gx(PE);var FE=`popover`,IE=`.popover-header`,LE=`.popover-body`,RE={...PE.Default,content:``,offset:[0,8],placement:`right`,template:`<div class="popover" role="tooltip"><div class="popover-arrow"></div><h3 class="popover-header"></h3><div class="popover-body"></div></div>`,trigger:`click`},zE={...PE.DefaultType,content:`(null|string|element|function)`},BE=class e extends PE{static get Default(){return RE}static get DefaultType(){return zE}static get NAME(){return FE}_isWithContent(){return this._getTitle()||this._getContent()}_getContentForTemplate(){return{[IE]:this._getTitle(),[LE]:this._getContent()}}_getContent(){return this._resolvePossibleFunction(this._config.content)}static jQueryInterface(t){return this.each(function(){let n=e.getOrCreateInstance(this,t);if(typeof t==`string`){if(n[t]===void 0)throw TypeError(`No method named "${t}"`);n[t]()}})}};Gx(BE);var VE=`scrollspy`,HE=`.bs.scrollspy`,UE=`.data-api`,WE=`activate${HE}`,GE=`click${HE}`,KE=`load${HE}${UE}`,qE=`dropdown-item`,JE=`active`,YE=`[data-bs-spy="scroll"]`,XE=`[href]`,ZE=`.nav, .list-group`,QE=`.nav-link`,$E=`${QE}, .nav-item > ${QE}, .list-group-item`,eD=`.dropdown`,tD=`.dropdown-toggle`,nD={offset:null,rootMargin:`0px 0px -25%`,smoothScroll:!1,target:null,threshold:[.1,.5,1]},rD={offset:`(number|null)`,rootMargin:`string`,smoothScroll:`boolean`,target:`element`,threshold:`array`},iD=class e extends yS{constructor(e,t){super(e,t),this._targetLinks=new Map,this._observableSections=new Map,this._rootElement=getComputedStyle(this._element).overflowY===`visible`?null:this._element,this._activeTarget=null,this._observer=null,this._previousScrollData={visibleEntryTop:0,parentScrollTop:0},this.refresh()}static get Default(){return nD}static get DefaultType(){return rD}static get NAME(){return VE}refresh(){this._initializeTargetsAndObservables(),this._maybeEnableSmoothScroll(),this._observer?this._observer.disconnect():this._observer=this._getNewObserver();for(let e of this._observableSections.values())this._observer.observe(e)}dispose(){this._observer.disconnect(),super.dispose()}_configAfterMerge(e){return e.target=Fx(e.target)||document.body,e.rootMargin=e.offset?`${e.offset}px 0px -30%`:e.rootMargin,typeof e.threshold==`string`&&(e.threshold=e.threshold.split(`,`).map(e=>Number.parseFloat(e))),e}_maybeEnableSmoothScroll(){this._config.smoothScroll&&(fS.off(this._config.target,GE),fS.on(this._config.target,GE,XE,e=>{let t=this._observableSections.get(e.target.hash);if(t){e.preventDefault();let n=this._rootElement||window,r=t.offsetTop-this._element.offsetTop;if(n.scrollTo){n.scrollTo({top:r,behavior:`smooth`});return}n.scrollTop=r}}))}_getNewObserver(){let e={root:this._rootElement,threshold:this._config.threshold,rootMargin:this._config.rootMargin};return new IntersectionObserver(e=>this._observerCallback(e),e)}_observerCallback(e){let t=e=>this._targetLinks.get(`#${e.target.id}`),n=e=>{this._previousScrollData.visibleEntryTop=e.target.offsetTop,this._process(t(e))},r=(this._rootElement||document.documentElement).scrollTop,i=r>=this._previousScrollData.parentScrollTop;this._previousScrollData.parentScrollTop=r;for(let a of e){if(!a.isIntersecting){this._activeTarget=null,this._clearActiveClass(t(a));continue}let e=a.target.offsetTop>=this._previousScrollData.visibleEntryTop;if(i&&e){if(n(a),!r)return;continue}!i&&!e&&n(a)}}_initializeTargetsAndObservables(){this._targetLinks=new Map,this._observableSections=new Map;let e=xS.find(XE,this._config.target);for(let t of e){if(!t.hash||Lx(t))continue;let e=xS.findOne(decodeURI(t.hash),this._element);Ix(e)&&(this._targetLinks.set(decodeURI(t.hash),t),this._observableSections.set(t.hash,e))}}_process(e){this._activeTarget!==e&&(this._clearActiveClass(this._config.target),this._activeTarget=e,e.classList.add(JE),this._activateParents(e),fS.trigger(this._element,WE,{relatedTarget:e}))}_activateParents(e){if(e.classList.contains(qE)){xS.findOne(tD,e.closest(eD)).classList.add(JE);return}for(let t of xS.parents(e,ZE))for(let e of xS.prev(t,$E))e.classList.add(JE)}_clearActiveClass(e){e.classList.remove(JE);let t=xS.find(`${XE}.${JE}`,e);for(let e of t)e.classList.remove(JE)}static jQueryInterface(t){return this.each(function(){let n=e.getOrCreateInstance(this,t);if(typeof t==`string`){if(n[t]===void 0||t.startsWith(`_`)||t===`constructor`)throw TypeError(`No method named "${t}"`);n[t]()}})}};fS.on(window,KE,()=>{for(let e of xS.find(YE))iD.getOrCreateInstance(e)}),Gx(iD);var aD=`tab`,oD=`.bs.tab`,sD=`hide${oD}`,cD=`hidden${oD}`,lD=`show${oD}`,uD=`shown${oD}`,dD=`click${oD}`,fD=`keydown${oD}`,pD=`load${oD}`,mD=`ArrowLeft`,hD=`ArrowRight`,gD=`ArrowUp`,_D=`ArrowDown`,vD=`Home`,yD=`End`,bD=`active`,xD=`fade`,SD=`show`,CD=`dropdown`,wD=`.dropdown-toggle`,TD=`.dropdown-menu`,ED=`:not(${wD})`,DD=`.list-group, .nav, [role="tablist"]`,OD=`.nav-item, .list-group-item`,kD=`.nav-link${ED}, .list-group-item${ED}, [role="tab"]${ED}`,AD=`[data-bs-toggle="tab"], [data-bs-toggle="pill"], [data-bs-toggle="list"]`,jD=`${kD}, ${AD}`,MD=`.${bD}[data-bs-toggle="tab"], .${bD}[data-bs-toggle="pill"], .${bD}[data-bs-toggle="list"]`,ND=class e extends yS{constructor(e){super(e),this._parent=this._element.closest(DD),this._parent&&(this._setInitialAttributes(this._parent,this._getChildren()),fS.on(this._element,fD,e=>this._keydown(e)))}static get NAME(){return aD}show(){let e=this._element;if(this._elemIsActive(e))return;let t=this._getActiveElem(),n=t?fS.trigger(t,sD,{relatedTarget:e}):null;fS.trigger(e,lD,{relatedTarget:t}).defaultPrevented||n&&n.defaultPrevented||(this._deactivate(t,e),this._activate(e,t))}_activate(e,t){e&&(e.classList.add(bD),this._activate(xS.getElementFromSelector(e)),this._queueCallback(()=>{if(e.getAttribute(`role`)!==`tab`){e.classList.add(SD);return}e.removeAttribute(`tabindex`),e.setAttribute(`aria-selected`,!0),this._toggleDropDown(e,!0),fS.trigger(e,uD,{relatedTarget:t})},e,e.classList.contains(xD)))}_deactivate(e,t){e&&(e.classList.remove(bD),e.blur(),this._deactivate(xS.getElementFromSelector(e)),this._queueCallback(()=>{if(e.getAttribute(`role`)!==`tab`){e.classList.remove(SD);return}e.setAttribute(`aria-selected`,!1),e.setAttribute(`tabindex`,`-1`),this._toggleDropDown(e,!1),fS.trigger(e,cD,{relatedTarget:t})},e,e.classList.contains(xD)))}_keydown(t){if(![mD,hD,gD,_D,vD,yD].includes(t.key))return;t.stopPropagation(),t.preventDefault();let n=this._getChildren().filter(e=>!Lx(e)),r;if([vD,yD].includes(t.key))r=n[t.key===vD?0:n.length-1];else{let e=[hD,_D].includes(t.key);r=Jx(n,t.target,e,!0)}r&&(r.focus({preventScroll:!0}),e.getOrCreateInstance(r).show())}_getChildren(){return xS.find(jD,this._parent)}_getActiveElem(){return this._getChildren().find(e=>this._elemIsActive(e))||null}_setInitialAttributes(e,t){this._setAttributeIfNotExists(e,`role`,`tablist`);for(let e of t)this._setInitialAttributesOnChild(e)}_setInitialAttributesOnChild(e){e=this._getInnerElement(e);let t=this._elemIsActive(e),n=this._getOuterElement(e);e.setAttribute(`aria-selected`,t),n!==e&&this._setAttributeIfNotExists(n,`role`,`presentation`),t||e.setAttribute(`tabindex`,`-1`),this._setAttributeIfNotExists(e,`role`,`tab`),this._setInitialAttributesOnTargetPanel(e)}_setInitialAttributesOnTargetPanel(e){let t=xS.getElementFromSelector(e);t&&(this._setAttributeIfNotExists(t,`role`,`tabpanel`),e.id&&this._setAttributeIfNotExists(t,`aria-labelledby`,`${e.id}`))}_toggleDropDown(e,t){let n=this._getOuterElement(e);if(!n.classList.contains(CD))return;let r=(e,r)=>{let i=xS.findOne(e,n);i&&i.classList.toggle(r,t)};r(wD,bD),r(TD,SD),n.setAttribute(`aria-expanded`,t)}_setAttributeIfNotExists(e,t,n){e.hasAttribute(t)||e.setAttribute(t,n)}_elemIsActive(e){return e.classList.contains(bD)}_getInnerElement(e){return e.matches(jD)?e:xS.findOne(jD,e)}_getOuterElement(e){return e.closest(OD)||e}static jQueryInterface(t){return this.each(function(){let n=e.getOrCreateInstance(this);if(typeof t==`string`){if(n[t]===void 0||t.startsWith(`_`)||t===`constructor`)throw TypeError(`No method named "${t}"`);n[t]()}})}};fS.on(document,dD,AD,function(e){[`A`,`AREA`].includes(this.tagName)&&e.preventDefault(),!Lx(this)&&ND.getOrCreateInstance(this).show()}),fS.on(window,pD,()=>{for(let e of xS.find(MD))ND.getOrCreateInstance(e)}),Gx(ND);var PD=`toast`,FD=`.bs.toast`,ID=`mouseover${FD}`,LD=`mouseout${FD}`,RD=`focusin${FD}`,zD=`focusout${FD}`,BD=`hide${FD}`,VD=`hidden${FD}`,HD=`show${FD}`,UD=`shown${FD}`,WD=`fade`,GD=`hide`,KD=`show`,qD=`showing`,JD={animation:`boolean`,autohide:`boolean`,delay:`number`},YD={animation:!0,autohide:!0,delay:5e3},XD=class e extends yS{constructor(e,t){super(e,t),this._timeout=null,this._hasMouseInteraction=!1,this._hasKeyboardInteraction=!1,this._setListeners()}static get Default(){return YD}static get DefaultType(){return JD}static get NAME(){return PD}show(){fS.trigger(this._element,HD).defaultPrevented||(this._clearTimeout(),this._config.animation&&this._element.classList.add(WD),this._element.classList.remove(GD),Bx(this._element),this._element.classList.add(KD,qD),this._queueCallback(()=>{this._element.classList.remove(qD),fS.trigger(this._element,UD),this._maybeScheduleHide()},this._element,this._config.animation))}hide(){!this.isShown()||fS.trigger(this._element,BD).defaultPrevented||(this._element.classList.add(qD),this._queueCallback(()=>{this._element.classList.add(GD),this._element.classList.remove(qD,KD),fS.trigger(this._element,VD)},this._element,this._config.animation))}dispose(){this._clearTimeout(),this.isShown()&&this._element.classList.remove(KD),super.dispose()}isShown(){return this._element.classList.contains(KD)}_maybeScheduleHide(){this._config.autohide&&(this._hasMouseInteraction||this._hasKeyboardInteraction||(this._timeout=setTimeout(()=>{this.hide()},this._config.delay)))}_onInteraction(e,t){switch(e.type){case`mouseover`:case`mouseout`:this._hasMouseInteraction=t;break;case`focusin`:case`focusout`:this._hasKeyboardInteraction=t;break}if(t){this._clearTimeout();return}let n=e.relatedTarget;this._element===n||this._element.contains(n)||this._maybeScheduleHide()}_setListeners(){fS.on(this._element,ID,e=>this._onInteraction(e,!0)),fS.on(this._element,LD,e=>this._onInteraction(e,!1)),fS.on(this._element,RD,e=>this._onInteraction(e,!0)),fS.on(this._element,zD,e=>this._onInteraction(e,!1))}_clearTimeout(){clearTimeout(this._timeout),this._timeout=null}static jQueryInterface(t){return this.each(function(){let n=e.getOrCreateInstance(this,t);if(typeof t==`string`){if(n[t]===void 0)throw TypeError(`No method named "${t}"`);n[t](this)}})}};SS(XD),Gx(XD);function ZD(e=void 0){let t=e=>a(`Succesvol`,e,c_.SUCCESS),n=e=>a(`Waarschuwing`,e,c_.WARNING),r=e=>a(`Informatie`,e,c_.INFO),i=e=>a(`Mislukt`,e,c_.DANGER);function a(t,n,r){let i=`toast-${ba()}`,a={id:i,variant:r,title:t,text:n},s=document.querySelector(`.toast-container`);if(!s){console.error(`There was no element with class 'toast-container' found, which is required for useToaster.`);return}let c=(0,u.h)(f_,a),l=(0,u.createApp)({render:()=>c}).mount(document.createElement(`div`));s.appendChild(l.$el);let d=document.querySelector(`#${i}`);d&&(XD.getOrCreateInstance(d,e).show(),o(d))}function o(e){function t(e,t){e.forEach(e=>{if(e.attributeName!=`class`)return;let n=e.target;if(n.classList.contains(`hide`)){n.remove(),t.disconnect();return}})}new MutationObserver(t).observe(e,{attributes:!0})}return{showSuccessToast:t,showInformationToast:r,showWarningToast:n,showDangerToast:i}}var QD={class:`bd-file-upload`},$D={class:`flex align-items-center justify-content-between gap-2`},eO={key:0,class:`preview-container`},tO=(0,u.defineComponent)({__name:`BDFileUpload`,props:{modelValue:{},buttonText:{default:void 0},multiple:{type:Boolean,default:!1},errorMessage:{default:void 0},fileSizeExceededMessage:{default:void 0},acceptedFiles:{default:`.jpg`},url:{default:``},tag:{default:`form`},token:{default:``}},emits:[`update:modelValue`],setup(e,{emit:t}){let{showDangerToast:n}=ZD(),{t:r}=vy.global,i=e,a=t,o=(0,u.ref)(null),s=(0,u.ref)([]);(0,u.watch)(()=>i.modelValue,e=>{o.value&&(o.value.files=o.value.files.filter(t=>e.files.some(e=>e.Naam===t.name)))},{deep:!0});let c=(0,u.computed)(()=>({variant:ia.PRIMARY,size:pa.SM})),l=cg(i,`modelValue`,a),d=async e=>{let t=Array.isArray(e.files)?e.files:[e.files];s.value.push(...t.map(e=>({name:e.name,previewUrl:e.objectURL})));for(let e of t){let t=new FormData;t.append(`file`,e);try{let n={method:`POST`,headers:{RequestVerificationToken:i.token},body:t};f(e,await(await fetch(i.url,n)).json())}catch{n(i.errorMessage||r(`fileUpload.errorMessage`))}}s.value=[],o.value&&o.value.clear()},f=(e,t)=>{let n=s.value.findIndex(t=>t.name==e.name);n!==-1&&s.value.splice(n,1),l.value.files.push({previewUrl:e.objectURL,UUID:e.name,CorrelationId:t.CorrelationId,name:t.Naam,Naam:t.Naam})},p=e=>{let t=l.value.files.indexOf(e);t!==-1&&l.value.files.splice(t,1),t=s.value.indexOf(e),t!==-1&&s.value.splice(t,1)};return(e,t)=>((0,u.openBlock)(),(0,u.createElementBlock)(`div`,QD,[(0,u.createVNode)((0,u.unref)(fy),{ref_key:`fileUploadRef`,ref:o,multiple:i.multiple,"max-file-size":10485760,accept:i.acceptedFiles,auto:!0,"max-files":i.multiple?10:1,"custom-upload":!0,name:`file`,onUploader:d},{header:(0,u.withCtx)(({chooseCallback:e})=>[(0,u.createElementVNode)(`div`,$D,[(0,u.createVNode)(ha,(0,u.mergeProps)(c.value,{onClick:e}),{default:(0,u.withCtx)(()=>[(0,u.createVNode)((0,u.unref)(k)),(0,u.createTextVNode)(` `+(0,u.toDisplayString)(i.buttonText),1)]),_:1},16,[`onClick`])])]),content:(0,u.withCtx)(()=>[s.value||(0,u.unref)(l)&&(0,u.unref)(l).files&&(0,u.unref)(l).files.length!==0?((0,u.openBlock)(),(0,u.createElementBlock)(`div`,eO,[(0,u.unref)(l)&&(0,u.unref)(l).files?((0,u.openBlock)(!0),(0,u.createElementBlock)(u.Fragment,{key:0},(0,u.renderList)((0,u.unref)(l).files,(e,t)=>((0,u.openBlock)(),(0,u.createBlock)(rv,{key:t,file:e,"is-pending":!1,onRemove:p},null,8,[`file`]))),128)):(0,u.createCommentVNode)(``,!0),s.value?((0,u.openBlock)(!0),(0,u.createElementBlock)(u.Fragment,{key:1},(0,u.renderList)(s.value,(e,t)=>((0,u.openBlock)(),(0,u.createBlock)(rv,{key:t,file:e,"is-pending":!0,onRemove:p},null,8,[`file`]))),128)):(0,u.createCommentVNode)(``,!0)])):(0,u.createCommentVNode)(``,!0)]),_:1},8,[`multiple`,`accept`,`max-files`])]))}}),nO=[`id`,`value`,`disabled`],rO=[`for`],iO={class:`invalid-feedback`},aO={__name:`BDFormMultipleCheckbox`,props:{modelValue:{type:Array,required:!0},options:{type:Array,required:!0},selectAllText:{type:String,default:null},state:{type:Boolean,default:!0},errorMessage:{type:String,default:null},overflow:{type:Boolean,default:!1}},emits:[`update:modelValue`,`on-input`,`change-department`],setup(e,{emit:t}){let n=e,r=t,{t:i}=Lu(),a=(0,u.ref)(n.modelValue),o=(0,u.computed)(()=>n.selectAllText?n.selectAllText:i(`form.multipleCheckbox.defaultButton`)),s=(0,u.computed)(()=>{let e=`bd-form-multiple-checkbox`;return n.state||(e+=` is-invalid`),n.overflow&&(e+=` overflow-form-control`),e}),c=(0,u.computed)(()=>n.errorMessage?n.errorMessage:i(`form.multipleCheckbox.defaultErrorMessage`));(0,u.watch)(()=>n.modelValue,e=>{a.value=e}),(0,u.watch)(a,e=>{r(`update:modelValue`,e),r(`on-input`,e),r(`change-department`,e)});function l(){a.value=n.options.map(e=>e.value),d()}function d(){r(`on-input`,a.value)}return(t,n)=>((0,u.openBlock)(),(0,u.createElementBlock)(u.Fragment,null,[(0,u.createElementVNode)(`div`,{class:(0,u.normalizeClass)(s.value)},[(0,u.createVNode)(ha,{variant:`outline-primary`,size:`sm`,onClick:l},{default:(0,u.withCtx)(()=>[(0,u.createTextVNode)((0,u.toDisplayString)(o.value),1)]),_:1}),((0,u.openBlock)(!0),(0,u.createElementBlock)(u.Fragment,null,(0,u.renderList)(e.options,e=>((0,u.openBlock)(),(0,u.createElementBlock)(`div`,{class:`form-check`,key:e.value},[(0,u.withDirectives)((0,u.createElementVNode)(`input`,{class:`form-check-input`,type:`checkbox`,id:e.value,value:e.value,"onUpdate:modelValue":n[0]||=e=>a.value=e,disabled:e.disabled},null,8,nO),[[u.vModelCheckbox,a.value]]),(0,u.createElementVNode)(`label`,{class:`form-check-label`,for:e.value},(0,u.toDisplayString)(e.text),9,rO)]))),128))],2),(0,u.createElementVNode)(`div`,iO,[(0,u.createVNode)(Pt),(0,u.createTextVNode)(` `+(0,u.toDisplayString)(c.value),1)])],64))}};function oO(e){this.content=e}oO.prototype={constructor:oO,find:function(e){for(var t=0;t<this.content.length;t+=2)if(this.content[t]===e)return t;return-1},get:function(e){var t=this.find(e);return t==-1?void 0:this.content[t+1]},update:function(e,t,n){var r=n&&n!=e?this.remove(n):this,i=r.find(e),a=r.content.slice();return i==-1?a.push(n||e,t):(a[i+1]=t,n&&(a[i]=n)),new oO(a)},remove:function(e){var t=this.find(e);if(t==-1)return this;var n=this.content.slice();return n.splice(t,2),new oO(n)},addToStart:function(e,t){return new oO([e,t].concat(this.remove(e).content))},addToEnd:function(e,t){var n=this.remove(e).content.slice();return n.push(e,t),new oO(n)},addBefore:function(e,t,n){var r=this.remove(t),i=r.content.slice(),a=r.find(e);return i.splice(a==-1?i.length:a,0,t,n),new oO(i)},forEach:function(e){for(var t=0;t<this.content.length;t+=2)e(this.content[t],this.content[t+1])},prepend:function(e){return e=oO.from(e),e.size?new oO(e.content.concat(this.subtract(e).content)):this},append:function(e){return e=oO.from(e),e.size?new oO(this.subtract(e).content.concat(e.content)):this},subtract:function(e){var t=this;e=oO.from(e);for(var n=0;n<e.content.length;n+=2)t=t.remove(e.content[n]);return t},toObject:function(){var e={};return this.forEach(function(t,n){e[t]=n}),e},get size(){return this.content.length>>1}},oO.from=function(e){if(e instanceof oO)return e;var t=[];if(e)for(var n in e)t.push(n,e[n]);return new oO(t)};function sO(e,t,n){for(let r=0;;r++){if(r==e.childCount||r==t.childCount)return e.childCount==t.childCount?null:n;let i=e.child(r),a=t.child(r);if(i==a){n+=i.nodeSize;continue}if(!i.sameMarkup(a))return n;if(i.isText&&i.text!=a.text){let e=i.text,t=a.text,r=0;for(;e[r]==t[r];r++)n++;return r&&r<e.length&&r<t.length&&uO(e.charCodeAt(r-1))&&lO(e.charCodeAt(r))&&n--,n}if(i.content.size||a.content.size){let e=sO(i.content,a.content,n+1);if(e!=null)return e}n+=i.nodeSize}}function cO(e,t,n,r){for(let i=e.childCount,a=t.childCount;;){if(i==0||a==0)return i==a?null:{a:n,b:r};let o=e.child(--i),s=t.child(--a),c=o.nodeSize;if(o==s){n-=c,r-=c;continue}if(!o.sameMarkup(s))return{a:n,b:r};if(o.isText&&o.text!=s.text){let e=o.text,t=s.text,i=e.length,a=t.length;for(;i>0&&a>0&&e[i-1]==t[a-1];)i--,a--,n--,r--;return i&&a&&i<e.length&&uO(e.charCodeAt(i-1))&&lO(e.charCodeAt(i))&&(n++,r++),{a:n,b:r}}if(o.content.size||s.content.size){let e=cO(o.content,s.content,n-1,r-1);if(e)return e}n-=c,r-=c}}function lO(e){return e>=56320&&e<57344}function uO(e){return e>=55296&&e<56320}var dO=class e{constructor(e,t){if(this.content=e,this.size=t||0,t==null)for(let t=0;t<e.length;t++)this.size+=e[t].nodeSize}nodesBetween(e,t,n,r=0,i){for(let a=0,o=0;o<t;a++){let s=this.content[a],c=o+s.nodeSize;if(c>e&&n(s,r+o,i||null,a)!==!1&&s.content.size){let i=o+1;s.nodesBetween(Math.max(0,e-i),Math.min(s.content.size,t-i),n,r+i)}o=c}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,t,n,r){let i=``,a=!0;return this.nodesBetween(e,t,(o,s)=>{let c=o.isText?o.text.slice(Math.max(e,s)-s,t-s):o.isLeaf?r?typeof r==`function`?r(o):r:o.type.spec.leafText?o.type.spec.leafText(o):``:``;o.isBlock&&(o.isLeaf&&c||o.isTextblock)&&n&&(a?a=!1:i+=n),i+=c},0),i}append(t){if(!t.size)return this;if(!this.size)return t;let n=this.lastChild,r=t.firstChild,i=this.content.slice(),a=0;for(n.isText&&n.sameMarkup(r)&&(i[i.length-1]=n.withText(n.text+r.text),a=1);a<t.content.length;a++)i.push(t.content[a]);return new e(i,this.size+t.size)}cut(t,n=this.size){if(t==0&&n==this.size)return this;let r=[],i=0;if(n>t)for(let e=0,a=0;a<n;e++){let o=this.content[e],s=a+o.nodeSize;s>t&&((a<t||s>n)&&(o=o.isText?o.cut(Math.max(0,t-a),Math.min(o.text.length,n-a)):o.cut(Math.max(0,t-a-1),Math.min(o.content.size,n-a-1))),r.push(o),i+=o.nodeSize),a=s}return new e(r,i)}cutByIndex(t,n){return t==n?e.empty:t==0&&n==this.content.length?this:new e(this.content.slice(t,n))}replaceChild(t,n){let r=this.content[t];if(r==n)return this;let i=this.content.slice(),a=this.size+n.nodeSize-r.nodeSize;return i[t]=n,new e(i,a)}addToStart(t){return new e([t].concat(this.content),this.size+t.nodeSize)}addToEnd(t){return new e(this.content.concat(t),this.size+t.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let t=0;t<this.content.length;t++)if(!this.content[t].eq(e.content[t]))return!1;return!0}get firstChild(){return this.content.length?this.content[0]:null}get lastChild(){return this.content.length?this.content[this.content.length-1]:null}get childCount(){return this.content.length}child(e){let t=this.content[e];if(!t)throw RangeError(`Index `+e+` out of range for `+this);return t}maybeChild(e){return this.content[e]||null}forEach(e){for(let t=0,n=0;t<this.content.length;t++){let r=this.content[t];e(r,n,t),n+=r.nodeSize}}findDiffStart(e,t=0){return sO(this,e,t)}findDiffEnd(e,t=this.size,n=e.size){return cO(this,e,t,n)}findIndex(e){if(e==0)return pO(0,e);if(e==this.size)return pO(this.content.length,e);if(e>this.size||e<0)throw RangeError(`Position ${e} outside of fragment (${this})`);for(let t=0,n=0;;t++){let r=this.child(t),i=n+r.nodeSize;if(i>=e)return i==e?pO(t+1,i):pO(t,n);n=i}}toString(){return`<`+this.toStringInner()+`>`}toStringInner(){return this.content.join(`, `)}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(t,n){if(!n)return e.empty;if(!Array.isArray(n))throw RangeError(`Invalid input for Fragment.fromJSON`);return e.fromArray(n.map(t.nodeFromJSON))}static fromArray(t){if(!t.length)return e.empty;let n,r=0;for(let e=0;e<t.length;e++){let i=t[e];r+=i.nodeSize,e&&i.isText&&t[e-1].sameMarkup(i)?(n||=t.slice(0,e),n[n.length-1]=i.withText(n[n.length-1].text+i.text)):n&&n.push(i)}return new e(n||t,r)}static from(t){if(!t)return e.empty;if(t instanceof e)return t;if(Array.isArray(t))return this.fromArray(t);if(t.attrs)return new e([t],t.nodeSize);throw RangeError(`Can not convert `+t+` to a Fragment`+(t.nodesBetween?` (looks like multiple versions of prosemirror-model were loaded)`:``))}};dO.empty=new dO([],0);var fO={index:0,offset:0};function pO(e,t){return fO.index=e,fO.offset=t,fO}function mO(e,t){if(e===t)return!0;if(!(e&&typeof e==`object`)||!(t&&typeof t==`object`))return!1;let n=Array.isArray(e);if(Array.isArray(t)!=n)return!1;if(n){if(e.length!=t.length)return!1;for(let n=0;n<e.length;n++)if(!mO(e[n],t[n]))return!1}else{for(let n in e)if(!(n in t)||!mO(e[n],t[n]))return!1;for(let n in t)if(!(n in e))return!1}return!0}var hO=class e{constructor(e,t){this.type=e,this.attrs=t}addToSet(e){let t,n=!1;for(let r=0;r<e.length;r++){let i=e[r];if(this.eq(i))return e;if(this.type.excludes(i.type))t||=e.slice(0,r);else if(i.type.excludes(this.type))return e;else !n&&i.type.rank>this.type.rank&&(t||=e.slice(0,r),t.push(this),n=!0),t&&t.push(i)}return t||=e.slice(),n||t.push(this),t}removeFromSet(e){for(let t=0;t<e.length;t++)if(this.eq(e[t]))return e.slice(0,t).concat(e.slice(t+1));return e}isInSet(e){for(let t=0;t<e.length;t++)if(this.eq(e[t]))return!0;return!1}eq(e){return this==e||this.type==e.type&&mO(this.attrs,e.attrs)}toJSON(){let e={type:this.type.name};for(let t in this.attrs){e.attrs=this.attrs;break}return e}static fromJSON(e,t){if(!t)throw RangeError(`Invalid input for Mark.fromJSON`);let n=e.marks[t.type];if(!n)throw RangeError(`There is no mark type ${t.type} in this schema`);let r=n.create(t.attrs);return n.checkAttrs(r.attrs),r}static sameSet(e,t){if(e==t)return!0;if(e.length!=t.length)return!1;for(let n=0;n<e.length;n++)if(!e[n].eq(t[n]))return!1;return!0}static setFrom(t){if(!t||Array.isArray(t)&&t.length==0)return e.none;if(t instanceof e)return[t];let n=t.slice();return n.sort((e,t)=>e.type.rank-t.type.rank),n}};hO.none=[];var gO=class extends Error{},_O=class e{constructor(e,t,n){this.content=e,this.openStart=t,this.openEnd=n}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(t,n){let r=yO(this.content,t+this.openStart,n,this.openStart+1,this.openEnd+1);return r&&new e(r,this.openStart,this.openEnd)}removeBetween(t,n){return new e(vO(this.content,t+this.openStart,n+this.openStart),this.openStart,this.openEnd)}eq(e){return this.content.eq(e.content)&&this.openStart==e.openStart&&this.openEnd==e.openEnd}toString(){return this.content+`(`+this.openStart+`,`+this.openEnd+`)`}toJSON(){if(!this.content.size)return null;let e={content:this.content.toJSON()};return this.openStart>0&&(e.openStart=this.openStart),this.openEnd>0&&(e.openEnd=this.openEnd),e}static fromJSON(t,n){if(!n)return e.empty;let r=n.openStart||0,i=n.openEnd||0;if(typeof r!=`number`||typeof i!=`number`)throw RangeError(`Invalid input for Slice.fromJSON`);return new e(dO.fromJSON(t,n.content),r,i)}static maxOpen(t,n=!0){let r=0,i=0;for(let e=t.firstChild;e&&!e.isLeaf&&(n||!e.type.spec.isolating);e=e.firstChild)r++;for(let e=t.lastChild;e&&!e.isLeaf&&(n||!e.type.spec.isolating);e=e.lastChild)i++;return new e(t,r,i)}};_O.empty=new _O(dO.empty,0,0);function vO(e,t,n){let{index:r,offset:i}=e.findIndex(t),a=e.maybeChild(r),{index:o,offset:s}=e.findIndex(n);if(i==t||a.isText){if(s!=n&&!e.child(o).isText)throw RangeError(`Removing non-flat range`);return e.cut(0,t).append(e.cut(n))}if(r!=o)throw RangeError(`Removing non-flat range`);return e.replaceChild(r,a.copy(vO(a.content,t-i-1,n-i-1)))}function yO(e,t,n,r,i,a){let{index:o,offset:s}=e.findIndex(t),c=e.maybeChild(o);if(s==t||c.isText)return a&&r<=0&&i<=0&&!a.canReplace(o,o,n)?null:e.cut(0,t).append(n).append(e.cut(t));let l=yO(c.content,t-s-1,n,o==0?r-1:0,o==e.childCount-1?i-1:0,c);return l&&e.replaceChild(o,c.copy(l))}function bO(e,t,n){if(n.openStart>e.depth)throw new gO(`Inserted content deeper than insertion position`);if(e.depth-n.openStart!=t.depth-n.openEnd)throw new gO(`Inconsistent open depths`);return xO(e,t,n,0)}function xO(e,t,n,r){let i=e.index(r),a=e.node(r);if(i==t.index(r)&&r<e.depth-n.openStart){let o=xO(e,t,n,r+1);return a.copy(a.content.replaceChild(i,o))}else if(!n.content.size)return EO(a,OO(e,t,r));else if(!n.openStart&&!n.openEnd&&e.depth==r&&t.depth==r){let r=e.parent,i=r.content;return EO(r,i.cut(0,e.parentOffset).append(n.content).append(i.cut(t.parentOffset)))}else{let{start:i,end:o}=kO(n,e);return EO(a,DO(e,i,o,t,r))}}function SO(e,t){if(!t.type.compatibleContent(e.type))throw new gO(`Cannot join `+t.type.name+` onto `+e.type.name)}function CO(e,t,n){let r=e.node(n);return SO(r,t.node(n)),r}function wO(e,t){let n=t.length-1;n>=0&&e.isText&&e.sameMarkup(t[n])?t[n]=e.withText(t[n].text+e.text):t.push(e)}function TO(e,t,n,r){let i=(t||e).node(n),a=0,o=t?t.index(n):i.childCount;e&&(a=e.index(n),e.depth>n?a++:e.textOffset&&(wO(e.nodeAfter,r),a++));for(let e=a;e<o;e++)wO(i.child(e),r);t&&t.depth==n&&t.textOffset&&wO(t.nodeBefore,r)}function EO(e,t){if(!e.type.validContent(t))throw new gO(`Invalid content for node `+e.type.name);return e.copy(t)}function DO(e,t,n,r,i){let a=e.depth>i&&CO(e,t,i+1),o=r.depth>i&&CO(n,r,i+1),s=[];return TO(null,e,i,s),a&&o&&t.index(i)==n.index(i)?(SO(a,o),wO(EO(a,DO(e,t,n,r,i+1)),s)):(a&&wO(EO(a,OO(e,t,i+1)),s),TO(t,n,i,s),o&&wO(EO(o,OO(n,r,i+1)),s)),TO(r,null,i,s),new dO(s)}function OO(e,t,n){let r=[];return TO(null,e,n,r),e.depth>n&&wO(EO(CO(e,t,n+1),OO(e,t,n+1)),r),TO(t,null,n,r),new dO(r)}function kO(e,t){let n=t.depth-e.openStart,r=t.node(n).copy(e.content);for(let e=n-1;e>=0;e--)r=t.node(e).copy(dO.from(r));return{start:r.resolveNoCache(e.openStart+n),end:r.resolveNoCache(r.content.size-e.openEnd-n)}}var AO=class e{constructor(e,t,n){this.pos=e,this.path=t,this.parentOffset=n,this.depth=t.length/3-1}resolveDepth(e){return e==null?this.depth:e<0?this.depth+e:e}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(e){return this.path[this.resolveDepth(e)*3]}index(e){return this.path[this.resolveDepth(e)*3+1]}indexAfter(e){return e=this.resolveDepth(e),this.index(e)+(e==this.depth&&!this.textOffset?0:1)}start(e){return e=this.resolveDepth(e),e==0?0:this.path[e*3-1]+1}end(e){return e=this.resolveDepth(e),this.start(e)+this.node(e).content.size}before(e){if(e=this.resolveDepth(e),!e)throw RangeError(`There is no position before the top-level node`);return e==this.depth+1?this.pos:this.path[e*3-1]}after(e){if(e=this.resolveDepth(e),!e)throw RangeError(`There is no position after the top-level node`);return e==this.depth+1?this.pos:this.path[e*3-1]+this.path[e*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let e=this.parent,t=this.index(this.depth);if(t==e.childCount)return null;let n=this.pos-this.path[this.path.length-1],r=e.child(t);return n?e.child(t).cut(n):r}get nodeBefore(){let e=this.index(this.depth),t=this.pos-this.path[this.path.length-1];return t?this.parent.child(e).cut(0,t):e==0?null:this.parent.child(e-1)}posAtIndex(e,t){t=this.resolveDepth(t);let n=this.path[t*3],r=t==0?0:this.path[t*3-1]+1;for(let t=0;t<e;t++)r+=n.child(t).nodeSize;return r}marks(){let e=this.parent,t=this.index();if(e.content.size==0)return hO.none;if(this.textOffset)return e.child(t).marks;let n=e.maybeChild(t-1),r=e.maybeChild(t);if(!n){let e=n;n=r,r=e}let i=n.marks;for(var a=0;a<i.length;a++)i[a].type.spec.inclusive===!1&&(!r||!i[a].isInSet(r.marks))&&(i=i[a--].removeFromSet(i));return i}marksAcross(e){let t=this.parent.maybeChild(this.index());if(!t||!t.isInline)return null;let n=t.marks,r=e.parent.maybeChild(e.index());for(var i=0;i<n.length;i++)n[i].type.spec.inclusive===!1&&(!r||!n[i].isInSet(r.marks))&&(n=n[i--].removeFromSet(n));return n}sharedDepth(e){for(let t=this.depth;t>0;t--)if(this.start(t)<=e&&this.end(t)>=e)return t;return 0}blockRange(e=this,t){if(e.pos<this.pos)return e.blockRange(this);for(let n=this.depth-(this.parent.inlineContent||this.pos==e.pos?1:0);n>=0;n--)if(e.pos<=this.end(n)&&(!t||t(this.node(n))))return new PO(this,e,n);return null}sameParent(e){return this.pos-this.parentOffset==e.pos-e.parentOffset}max(e){return e.pos>this.pos?e:this}min(e){return e.pos<this.pos?e:this}toString(){let e=``;for(let t=1;t<=this.depth;t++)e+=(e?`/`:``)+this.node(t).type.name+`_`+this.index(t-1);return e+`:`+this.parentOffset}static resolve(t,n){if(!(n>=0&&n<=t.content.size))throw RangeError(`Position `+n+` out of range`);let r=[],i=0,a=n;for(let e=t;;){let{index:t,offset:n}=e.content.findIndex(a),o=a-n;if(r.push(e,t,i+n),!o||(e=e.child(t),e.isText))break;a=o-1,i+=n+1}return new e(n,r,a)}static resolveCached(t,n){let r=NO.get(t);if(r)for(let e=0;e<r.elts.length;e++){let t=r.elts[e];if(t.pos==n)return t}else NO.set(t,r=new jO);let i=r.elts[r.i]=e.resolve(t,n);return r.i=(r.i+1)%MO,i}},jO=class{constructor(){this.elts=[],this.i=0}},MO=12,NO=new WeakMap,PO=class{constructor(e,t,n){this.$from=e,this.$to=t,this.depth=n}get start(){return this.$from.before(this.depth+1)}get end(){return this.$to.after(this.depth+1)}get parent(){return this.$from.node(this.depth)}get startIndex(){return this.$from.index(this.depth)}get endIndex(){return this.$to.indexAfter(this.depth)}},FO=Object.create(null),IO=class e{constructor(e,t,n,r=hO.none){this.type=e,this.attrs=t,this.marks=r,this.content=n||dO.empty}get children(){return this.content.content}get nodeSize(){return this.isLeaf?1:2+this.content.size}get childCount(){return this.content.childCount}child(e){return this.content.child(e)}maybeChild(e){return this.content.maybeChild(e)}forEach(e){this.content.forEach(e)}nodesBetween(e,t,n,r=0){this.content.nodesBetween(e,t,n,r,this)}descendants(e){this.nodesBetween(0,this.content.size,e)}get textContent(){return this.isLeaf&&this.type.spec.leafText?this.type.spec.leafText(this):this.textBetween(0,this.content.size,``)}textBetween(e,t,n,r){return this.content.textBetween(e,t,n,r)}get firstChild(){return this.content.firstChild}get lastChild(){return this.content.lastChild}eq(e){return this==e||this.sameMarkup(e)&&this.content.eq(e.content)}sameMarkup(e){return this.hasMarkup(e.type,e.attrs,e.marks)}hasMarkup(e,t,n){return this.type==e&&mO(this.attrs,t||e.defaultAttrs||FO)&&hO.sameSet(this.marks,n||hO.none)}copy(t=null){return t==this.content?this:new e(this.type,this.attrs,t,this.marks)}mark(t){return t==this.marks?this:new e(this.type,this.attrs,this.content,t)}cut(e,t=this.content.size){return e==0&&t==this.content.size?this:this.copy(this.content.cut(e,t))}slice(e,t=this.content.size,n=!1){if(e==t)return _O.empty;let r=this.resolve(e),i=this.resolve(t),a=n?0:r.sharedDepth(t),o=r.start(a);return new _O(r.node(a).content.cut(r.pos-o,i.pos-o),r.depth-a,i.depth-a)}replace(e,t,n){return bO(this.resolve(e),this.resolve(t),n)}nodeAt(e){for(let t=this;;){let{index:n,offset:r}=t.content.findIndex(e);if(t=t.maybeChild(n),!t)return null;if(r==e||t.isText)return t;e-=r+1}}childAfter(e){let{index:t,offset:n}=this.content.findIndex(e);return{node:this.content.maybeChild(t),index:t,offset:n}}childBefore(e){if(e==0)return{node:null,index:0,offset:0};let{index:t,offset:n}=this.content.findIndex(e);if(n<e)return{node:this.content.child(t),index:t,offset:n};let r=this.content.child(t-1);return{node:r,index:t-1,offset:n-r.nodeSize}}resolve(e){return AO.resolveCached(this,e)}resolveNoCache(e){return AO.resolve(this,e)}rangeHasMark(e,t,n){let r=!1;return t>e&&this.nodesBetween(e,t,e=>(n.isInSet(e.marks)&&(r=!0),!r)),r}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let e=this.type.name;return this.content.size&&(e+=`(`+this.content.toStringInner()+`)`),RO(this.marks,e)}contentMatchAt(e){let t=this.type.contentMatch.matchFragment(this.content,0,e);if(!t)throw Error(`Called contentMatchAt on a node with invalid content`);return t}canReplace(e,t,n=dO.empty,r=0,i=n.childCount){let a=this.contentMatchAt(e).matchFragment(n,r,i),o=a&&a.matchFragment(this.content,t);if(!o||!o.validEnd)return!1;for(let e=r;e<i;e++)if(!this.type.allowsMarks(n.child(e).marks))return!1;return!0}canReplaceWith(e,t,n,r){if(r&&!this.type.allowsMarks(r))return!1;let i=this.contentMatchAt(e).matchType(n),a=i&&i.matchFragment(this.content,t);return a?a.validEnd:!1}canAppend(e){return e.content.size?this.canReplace(this.childCount,this.childCount,e.content):this.type.compatibleContent(e.type)}check(){this.type.checkContent(this.content),this.type.checkAttrs(this.attrs);let e=hO.none;for(let t=0;t<this.marks.length;t++){let n=this.marks[t];n.type.checkAttrs(n.attrs),e=n.addToSet(e)}if(!hO.sameSet(e,this.marks))throw RangeError(`Invalid collection of marks for node ${this.type.name}: ${this.marks.map(e=>e.type.name)}`);this.content.forEach(e=>e.check())}toJSON(){let e={type:this.type.name};for(let t in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(e=>e.toJSON())),e}static fromJSON(e,t){if(!t)throw RangeError(`Invalid input for Node.fromJSON`);let n;if(t.marks){if(!Array.isArray(t.marks))throw RangeError(`Invalid mark data for Node.fromJSON`);n=t.marks.map(e.markFromJSON)}if(t.type==`text`){if(typeof t.text!=`string`)throw RangeError(`Invalid text node in JSON`);return e.text(t.text,n)}let r=dO.fromJSON(e,t.content),i=e.nodeType(t.type).create(t.attrs,r,n);return i.type.checkAttrs(i.attrs),i}};IO.prototype.text=void 0;var LO=class e extends IO{constructor(e,t,n,r){if(super(e,t,null,r),!n)throw RangeError(`Empty text nodes are not allowed`);this.text=n}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):RO(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(e,t){return this.text.slice(e,t)}get nodeSize(){return this.text.length}mark(t){return t==this.marks?this:new e(this.type,this.attrs,this.text,t)}withText(t){return t==this.text?this:new e(this.type,this.attrs,t,this.marks)}cut(e=0,t=this.text.length){return e==0&&t==this.text.length?this:this.withText(this.text.slice(e,t))}eq(e){return this.sameMarkup(e)&&this.text==e.text}toJSON(){let e=super.toJSON();return e.text=this.text,e}};function RO(e,t){for(let n=e.length-1;n>=0;n--)t=e[n].type.name+`(`+t+`)`;return t}var zO=class e{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(t,n){let r=new BO(t,n);if(r.next==null)return e.empty;let i=VO(r);r.next&&r.err(`Unexpected trailing text`);let a=ZO(JO(i));return QO(a,r),a}matchType(e){for(let t=0;t<this.next.length;t++)if(this.next[t].type==e)return this.next[t].next;return null}matchFragment(e,t=0,n=e.childCount){let r=this;for(let i=t;r&&i<n;i++)r=r.matchType(e.child(i).type);return r}get inlineContent(){return this.next.length!=0&&this.next[0].type.isInline}get defaultType(){for(let e=0;e<this.next.length;e++){let{type:t}=this.next[e];if(!(t.isText||t.hasRequiredAttrs()))return t}return null}compatible(e){for(let t=0;t<this.next.length;t++)for(let n=0;n<e.next.length;n++)if(this.next[t].type==e.next[n].type)return!0;return!1}fillBefore(e,t=!1,n=0){let r=[this];function i(a,o){let s=a.matchFragment(e,n);if(s&&(!t||s.validEnd))return dO.from(o.map(e=>e.createAndFill()));for(let e=0;e<a.next.length;e++){let{type:t,next:n}=a.next[e];if(!(t.isText||t.hasRequiredAttrs())&&r.indexOf(n)==-1){r.push(n);let e=i(n,o.concat(t));if(e)return e}}return null}return i(this,[])}findWrapping(e){for(let t=0;t<this.wrapCache.length;t+=2)if(this.wrapCache[t]==e)return this.wrapCache[t+1];let t=this.computeWrapping(e);return this.wrapCache.push(e,t),t}computeWrapping(e){let t=Object.create(null),n=[{match:this,type:null,via:null}];for(;n.length;){let r=n.shift(),i=r.match;if(i.matchType(e)){let e=[];for(let t=r;t.type;t=t.via)e.push(t.type);return e.reverse()}for(let e=0;e<i.next.length;e++){let{type:a,next:o}=i.next[e];!a.isLeaf&&!a.hasRequiredAttrs()&&!(a.name in t)&&(!r.type||o.validEnd)&&(n.push({match:a.contentMatch,type:a,via:r}),t[a.name]=!0)}}return null}get edgeCount(){return this.next.length}edge(e){if(e>=this.next.length)throw RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function t(n){e.push(n);for(let r=0;r<n.next.length;r++)e.indexOf(n.next[r].next)==-1&&t(n.next[r].next)}return t(this),e.map((t,n)=>{let r=n+(t.validEnd?`*`:` `)+` `;for(let n=0;n<t.next.length;n++)r+=(n?`, `:``)+t.next[n].type.name+`->`+e.indexOf(t.next[n].next);return r}).join(`
|
|
1696
1696
|
`)}};zO.empty=new zO(!0);var BO=class{constructor(e,t){this.string=e,this.nodeTypes=t,this.inline=null,this.pos=0,this.tokens=e.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==``&&this.tokens.pop(),this.tokens[0]==``&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(e){return this.next==e&&(this.pos++||!0)}err(e){throw SyntaxError(e+` (in content expression '`+this.string+`')`)}};function VO(e){let t=[];do t.push(HO(e));while(e.eat(`|`));return t.length==1?t[0]:{type:`choice`,exprs:t}}function HO(e){let t=[];do t.push(UO(e));while(e.next&&e.next!=`)`&&e.next!=`|`);return t.length==1?t[0]:{type:`seq`,exprs:t}}function UO(e){let t=qO(e);for(;;)if(e.eat(`+`))t={type:`plus`,expr:t};else if(e.eat(`*`))t={type:`star`,expr:t};else if(e.eat(`?`))t={type:`opt`,expr:t};else if(e.eat(`{`))t=GO(e,t);else break;return t}function WO(e){/\D/.test(e.next)&&e.err(`Expected number, got '`+e.next+`'`);let t=Number(e.next);return e.pos++,t}function GO(e,t){let n=WO(e),r=n;return e.eat(`,`)&&(r=e.next==`}`?-1:WO(e)),e.eat(`}`)||e.err(`Unclosed braced range`),{type:`range`,min:n,max:r,expr:t}}function KO(e,t){let n=e.nodeTypes,r=n[t];if(r)return[r];let i=[];for(let e in n){let r=n[e];r.isInGroup(t)&&i.push(r)}return i.length==0&&e.err(`No node type or group '`+t+`' found`),i}function qO(e){if(e.eat(`(`)){let t=VO(e);return e.eat(`)`)||e.err(`Missing closing paren`),t}else if(/\W/.test(e.next))e.err(`Unexpected token '`+e.next+`'`);else{let t=KO(e,e.next).map(t=>(e.inline==null?e.inline=t.isInline:e.inline!=t.isInline&&e.err(`Mixing inline and block content`),{type:`name`,value:t}));return e.pos++,t.length==1?t[0]:{type:`choice`,exprs:t}}}function JO(e){let t=[[]];return i(a(e,0),n()),t;function n(){return t.push([])-1}function r(e,n,r){let i={term:r,to:n};return t[e].push(i),i}function i(e,t){e.forEach(e=>e.to=t)}function a(e,t){if(e.type==`choice`)return e.exprs.reduce((e,n)=>e.concat(a(n,t)),[]);if(e.type==`seq`)for(let r=0;;r++){let o=a(e.exprs[r],t);if(r==e.exprs.length-1)return o;i(o,t=n())}else if(e.type==`star`){let o=n();return r(t,o),i(a(e.expr,o),o),[r(o)]}else if(e.type==`plus`){let o=n();return i(a(e.expr,t),o),i(a(e.expr,o),o),[r(o)]}else if(e.type==`opt`)return[r(t)].concat(a(e.expr,t));else if(e.type==`range`){let o=t;for(let t=0;t<e.min;t++){let t=n();i(a(e.expr,o),t),o=t}if(e.max==-1)i(a(e.expr,o),o);else for(let t=e.min;t<e.max;t++){let t=n();r(o,t),i(a(e.expr,o),t),o=t}return[r(o)]}else if(e.type==`name`)return[r(t,void 0,e.value)];else throw Error(`Unknown expr type`)}}function YO(e,t){return t-e}function XO(e,t){let n=[];return r(t),n.sort(YO);function r(t){let i=e[t];if(i.length==1&&!i[0].term)return r(i[0].to);n.push(t);for(let e=0;e<i.length;e++){let{term:t,to:a}=i[e];!t&&n.indexOf(a)==-1&&r(a)}}}function ZO(e){let t=Object.create(null);return n(XO(e,0));function n(r){let i=[];r.forEach(t=>{e[t].forEach(({term:t,to:n})=>{if(!t)return;let r;for(let e=0;e<i.length;e++)i[e][0]==t&&(r=i[e][1]);XO(e,n).forEach(e=>{r||i.push([t,r=[]]),r.indexOf(e)==-1&&r.push(e)})})});let a=t[r.join(`,`)]=new zO(r.indexOf(e.length-1)>-1);for(let e=0;e<i.length;e++){let r=i[e][1].sort(YO);a.next.push({type:i[e][0],next:t[r.join(`,`)]||n(r)})}return a}}function QO(e,t){for(let n=0,r=[e];n<r.length;n++){let e=r[n],i=!e.validEnd,a=[];for(let t=0;t<e.next.length;t++){let{type:n,next:o}=e.next[t];a.push(n.name),i&&!(n.isText||n.hasRequiredAttrs())&&(i=!1),r.indexOf(o)==-1&&r.push(o)}i&&t.err(`Only non-generatable nodes (`+a.join(`, `)+`) in a required position (see https://prosemirror.net/docs/guide/#generatable)`)}}function $O(e){let t=Object.create(null);for(let n in e){let r=e[n];if(!r.hasDefault)return null;t[n]=r.default}return t}function ek(e,t){let n=Object.create(null);for(let r in e){let i=t&&t[r];if(i===void 0){let t=e[r];if(t.hasDefault)i=t.default;else throw RangeError(`No value supplied for attribute `+r)}n[r]=i}return n}function tk(e,t,n,r){for(let i in t)if(!(i in e))throw RangeError(`Unsupported attribute ${i} for ${n} of type ${r}`);for(let n in e)e[n].validate&&e[n].validate(t[n])}function nk(e,t){let n=Object.create(null);if(t)for(let r in t)n[r]=new ak(e,r,t[r]);return n}var rk=class e{constructor(e,t,n){this.name=e,this.schema=t,this.spec=n,this.markSet=null,this.groups=n.group?n.group.split(` `):[],this.attrs=nk(e,n.attrs),this.defaultAttrs=$O(this.attrs),this.contentMatch=null,this.inlineContent=null,this.isBlock=!(n.inline||e==`text`),this.isText=e==`text`}get isInline(){return!this.isBlock}get isTextblock(){return this.isBlock&&this.inlineContent}get isLeaf(){return this.contentMatch==zO.empty}get isAtom(){return this.isLeaf||!!this.spec.atom}isInGroup(e){return this.groups.indexOf(e)>-1}get whitespace(){return this.spec.whitespace||(this.spec.code?`pre`:`normal`)}hasRequiredAttrs(){for(let e in this.attrs)if(this.attrs[e].isRequired)return!0;return!1}compatibleContent(e){return this==e||this.contentMatch.compatible(e.contentMatch)}computeAttrs(e){return!e&&this.defaultAttrs?this.defaultAttrs:ek(this.attrs,e)}create(e=null,t,n){if(this.isText)throw Error(`NodeType.create can't construct text nodes`);return new IO(this,this.computeAttrs(e),dO.from(t),hO.setFrom(n))}createChecked(e=null,t,n){return t=dO.from(t),this.checkContent(t),new IO(this,this.computeAttrs(e),t,hO.setFrom(n))}createAndFill(e=null,t,n){if(e=this.computeAttrs(e),t=dO.from(t),t.size){let e=this.contentMatch.fillBefore(t);if(!e)return null;t=e.append(t)}let r=this.contentMatch.matchFragment(t),i=r&&r.fillBefore(dO.empty,!0);return i?new IO(this,e,t.append(i),hO.setFrom(n)):null}validContent(e){let t=this.contentMatch.matchFragment(e);if(!t||!t.validEnd)return!1;for(let t=0;t<e.childCount;t++)if(!this.allowsMarks(e.child(t).marks))return!1;return!0}checkContent(e){if(!this.validContent(e))throw RangeError(`Invalid content for node ${this.name}: ${e.toString().slice(0,50)}`)}checkAttrs(e){tk(this.attrs,e,`node`,this.name)}allowsMarkType(e){return this.markSet==null||this.markSet.indexOf(e)>-1}allowsMarks(e){if(this.markSet==null)return!0;for(let t=0;t<e.length;t++)if(!this.allowsMarkType(e[t].type))return!1;return!0}allowedMarks(e){if(this.markSet==null)return e;let t;for(let n=0;n<e.length;n++)this.allowsMarkType(e[n].type)?t&&t.push(e[n]):t||=e.slice(0,n);return t?t.length?t:hO.none:e}static compile(t,n){let r=Object.create(null);t.forEach((t,i)=>r[t]=new e(t,n,i));let i=n.spec.topNode||`doc`;if(!r[i])throw RangeError(`Schema is missing its top node type ('`+i+`')`);if(!r.text)throw RangeError(`Every schema needs a 'text' type`);for(let e in r.text.attrs)throw RangeError(`The text node type should not have attributes`);return r}};function ik(e,t,n){let r=n.split(`|`);return n=>{let i=n===null?`null`:typeof n;if(r.indexOf(i)<0)throw RangeError(`Expected value of type ${r} for attribute ${t} on type ${e}, got ${i}`)}}var ak=class{constructor(e,t,n){this.hasDefault=Object.prototype.hasOwnProperty.call(n,`default`),this.default=n.default,this.validate=typeof n.validate==`string`?ik(e,t,n.validate):n.validate}get isRequired(){return!this.hasDefault}},ok=class e{constructor(e,t,n,r){this.name=e,this.rank=t,this.schema=n,this.spec=r,this.attrs=nk(e,r.attrs),this.excluded=null;let i=$O(this.attrs);this.instance=i?new hO(this,i):null}create(e=null){return!e&&this.instance?this.instance:new hO(this,ek(this.attrs,e))}static compile(t,n){let r=Object.create(null),i=0;return t.forEach((t,a)=>r[t]=new e(t,i++,n,a)),r}removeFromSet(e){for(var t=0;t<e.length;t++)e[t].type==this&&(e=e.slice(0,t).concat(e.slice(t+1)),t--);return e}isInSet(e){for(let t=0;t<e.length;t++)if(e[t].type==this)return e[t]}checkAttrs(e){tk(this.attrs,e,`mark`,this.name)}excludes(e){return this.excluded.indexOf(e)>-1}},sk=class{constructor(e){this.linebreakReplacement=null,this.cached=Object.create(null);let t=this.spec={};for(let n in e)t[n]=e[n];t.nodes=oO.from(e.nodes),t.marks=oO.from(e.marks||{}),this.nodes=rk.compile(this.spec.nodes,this),this.marks=ok.compile(this.spec.marks,this);let n=Object.create(null);for(let e in this.nodes){if(e in this.marks)throw RangeError(e+` can not be both a node and a mark`);let t=this.nodes[e],r=t.spec.content||``,i=t.spec.marks;if(t.contentMatch=n[r]||(n[r]=zO.parse(r,this.nodes)),t.inlineContent=t.contentMatch.inlineContent,t.spec.linebreakReplacement){if(this.linebreakReplacement)throw RangeError(`Multiple linebreak nodes defined`);if(!t.isInline||!t.isLeaf)throw RangeError(`Linebreak replacement nodes must be inline leaf nodes`);this.linebreakReplacement=t}t.markSet=i==`_`?null:i?ck(this,i.split(` `)):i==``||!t.inlineContent?[]:null}for(let e in this.marks){let t=this.marks[e],n=t.spec.excludes;t.excluded=n==null?[t]:n==``?[]:ck(this,n.split(` `))}this.nodeFromJSON=e=>IO.fromJSON(this,e),this.markFromJSON=e=>hO.fromJSON(this,e),this.topNodeType=this.nodes[this.spec.topNode||`doc`],this.cached.wrappings=Object.create(null)}node(e,t=null,n,r){if(typeof e==`string`)e=this.nodeType(e);else if(!(e instanceof rk))throw RangeError(`Invalid node type: `+e);else if(e.schema!=this)throw RangeError(`Node type from different schema used (`+e.name+`)`);return e.createChecked(t,n,r)}text(e,t){let n=this.nodes.text;return new LO(n,n.defaultAttrs,e,hO.setFrom(t))}mark(e,t){return typeof e==`string`&&(e=this.marks[e]),e.create(t)}nodeType(e){let t=this.nodes[e];if(!t)throw RangeError(`Unknown node type: `+e);return t}};function ck(e,t){let n=[];for(let r=0;r<t.length;r++){let i=t[r],a=e.marks[i],o=a;if(a)n.push(a);else for(let t in e.marks){let r=e.marks[t];(i==`_`||r.spec.group&&r.spec.group.split(` `).indexOf(i)>-1)&&n.push(o=r)}if(!o)throw SyntaxError(`Unknown mark type: '`+t[r]+`'`)}return n}function lk(e){return e.tag!=null}function uk(e){return e.style!=null}var dk=class e{constructor(e,t){this.schema=e,this.rules=t,this.tags=[],this.styles=[];let n=this.matchedStyles=[];t.forEach(e=>{if(lk(e))this.tags.push(e);else if(uk(e)){let t=/[^=]*/.exec(e.style)[0];n.indexOf(t)<0&&n.push(t),this.styles.push(e)}}),this.normalizeLists=!this.tags.some(t=>{if(!/^(ul|ol)\b/.test(t.tag)||!t.node)return!1;let n=e.nodes[t.node];return n.contentMatch.matchType(n)})}parse(e,t={}){let n=new bk(this,t,!1);return n.addAll(e,hO.none,t.from,t.to),n.finish()}parseSlice(e,t={}){let n=new bk(this,t,!0);return n.addAll(e,hO.none,t.from,t.to),_O.maxOpen(n.finish())}matchTag(e,t,n){for(let r=n?this.tags.indexOf(n)+1:0;r<this.tags.length;r++){let n=this.tags[r];if(Sk(e,n.tag)&&(n.namespace===void 0||e.namespaceURI==n.namespace)&&(!n.context||t.matchesContext(n.context))){if(n.getAttrs){let t=n.getAttrs(e);if(t===!1)continue;n.attrs=t||void 0}return n}}}matchStyle(e,t,n,r){for(let i=r?this.styles.indexOf(r)+1:0;i<this.styles.length;i++){let r=this.styles[i],a=r.style;if(!(a.indexOf(e)!=0||r.context&&!n.matchesContext(r.context)||a.length>e.length&&(a.charCodeAt(e.length)!=61||a.slice(e.length+1)!=t))){if(r.getAttrs){let e=r.getAttrs(t);if(e===!1)continue;r.attrs=e||void 0}return r}}}static schemaRules(e){let t=[];function n(e){let n=e.priority==null?50:e.priority,r=0;for(;r<t.length;r++){let e=t[r];if((e.priority==null?50:e.priority)<n)break}t.splice(r,0,e)}for(let t in e.marks){let r=e.marks[t].spec.parseDOM;r&&r.forEach(e=>{n(e=Ck(e)),e.mark||e.ignore||e.clearMark||(e.mark=t)})}for(let t in e.nodes){let r=e.nodes[t].spec.parseDOM;r&&r.forEach(e=>{n(e=Ck(e)),e.node||e.ignore||e.mark||(e.node=t)})}return t}static fromSchema(t){return t.cached.domParser||(t.cached.domParser=new e(t,e.schemaRules(t)))}},fk={address:!0,article:!0,aside:!0,blockquote:!0,canvas:!0,dd:!0,div:!0,dl:!0,fieldset:!0,figcaption:!0,figure:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,li:!0,noscript:!0,ol:!0,output:!0,p:!0,pre:!0,section:!0,table:!0,tfoot:!0,ul:!0},pk={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},mk={ol:!0,ul:!0},hk=1,gk=2,_k=4;function vk(e,t,n){return t==null?e&&e.whitespace==`pre`?3:n&-5:(t?hk:0)|(t===`full`?gk:0)}var yk=class{constructor(e,t,n,r,i,a){this.type=e,this.attrs=t,this.marks=n,this.solid=r,this.options=a,this.content=[],this.activeMarks=hO.none,this.match=i||(a&_k?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let t=this.type.contentMatch.fillBefore(dO.from(e));if(t)this.match=this.type.contentMatch.matchFragment(t);else{let t=this.type.contentMatch,n;return(n=t.findWrapping(e.type))?(this.match=t,n):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options&hk)){let e=this.content[this.content.length-1],t;if(e&&e.isText&&(t=/[ \t\r\n\u000c]+$/.exec(e.text))){let n=e;e.text.length==t[0].length?this.content.pop():this.content[this.content.length-1]=n.withText(n.text.slice(0,n.text.length-t[0].length))}}let t=dO.from(this.content);return!e&&this.match&&(t=t.append(this.match.fillBefore(dO.empty,!0))),this.type?this.type.create(this.attrs,t,this.marks):t}inlineContext(e){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:e.parentNode&&!fk.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}},bk=class{constructor(e,t,n){this.parser=e,this.options=t,this.isOpen=n,this.open=0,this.localPreserveWS=!1;let r=t.topNode,i,a=vk(null,t.preserveWhitespace,0)|(n?_k:0);i=r?new yk(r.type,r.attrs,hO.none,!0,t.topMatch||r.type.contentMatch,a):n?new yk(null,null,hO.none,!0,null,a):new yk(e.schema.topNodeType,null,hO.none,!0,null,a),this.nodes=[i],this.find=t.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(e,t){e.nodeType==3?this.addTextNode(e,t):e.nodeType==1&&this.addElement(e,t)}addTextNode(e,t){let n=e.nodeValue,r=this.top,i=r.options&gk?`full`:this.localPreserveWS||(r.options&hk)>0,{schema:a}=this.parser;if(i===`full`||r.inlineContext(e)||/[^ \t\r\n\u000c]/.test(n)){if(!i){if(n=n.replace(/[ \t\r\n\u000c]+/g,` `),/^[ \t\r\n\u000c]/.test(n)&&this.open==this.nodes.length-1){let t=r.content[r.content.length-1],i=e.previousSibling;(!t||i&&i.nodeName==`BR`||t.isText&&/[ \t\r\n\u000c]$/.test(t.text))&&(n=n.slice(1))}}else if(i===`full`)n=n.replace(/\r\n?/g,`
|
|
1697
1697
|
`);else if(a.linebreakReplacement&&/[\r\n]/.test(n)&&this.top.findWrapping(a.linebreakReplacement.create())){let e=n.split(/\r?\n|\r/);for(let n=0;n<e.length;n++)n&&this.insertNode(a.linebreakReplacement.create(),t,!0),e[n]&&this.insertNode(a.text(e[n]),t,!/\S/.test(e[n]));n=``}else n=n.replace(/\r?\n|\r/g,` `);n&&this.insertNode(a.text(n),t,!/\S/.test(n)),this.findInText(e)}else this.findInside(e)}addElement(e,t,n){let r=this.localPreserveWS,i=this.top;(e.tagName==`PRE`||/pre/.test(e.style&&e.style.whiteSpace))&&(this.localPreserveWS=!0);let a=e.nodeName.toLowerCase(),o;mk.hasOwnProperty(a)&&this.parser.normalizeLists&&xk(e);let s=this.options.ruleFromNode&&this.options.ruleFromNode(e)||(o=this.parser.matchTag(e,this,n));out:if(s?s.ignore:pk.hasOwnProperty(a))this.findInside(e),this.ignoreFallback(e,t);else if(!s||s.skip||s.closeParent){s&&s.closeParent?this.open=Math.max(0,this.open-1):s&&s.skip.nodeType&&(e=s.skip);let n,r=this.needsBlock;if(fk.hasOwnProperty(a))i.content.length&&i.content[0].isInline&&this.open&&(this.open--,i=this.top),n=!0,i.type||(this.needsBlock=!0);else if(!e.firstChild){this.leafFallback(e,t);break out}let o=s&&s.skip?t:this.readStyles(e,t);o&&this.addAll(e,o),n&&this.sync(i),this.needsBlock=r}else{let n=this.readStyles(e,t);n&&this.addElementByRule(e,s,n,s.consuming===!1?o:void 0)}this.localPreserveWS=r}leafFallback(e,t){e.nodeName==`BR`&&this.top.type&&this.top.type.inlineContent&&this.addTextNode(e.ownerDocument.createTextNode(`
|
|
1698
1698
|
`),t)}ignoreFallback(e,t){e.nodeName==`BR`&&(!this.top.type||!this.top.type.inlineContent)&&this.findPlace(this.parser.schema.text(`-`),t,!0)}readStyles(e,t){let n=e.style;if(n&&n.length)for(let e=0;e<this.parser.matchedStyles.length;e++){let r=this.parser.matchedStyles[e],i=n.getPropertyValue(r);if(i)for(let e;;){let n=this.parser.matchStyle(r,i,this,e);if(!n)break;if(n.ignore)return null;if(t=n.clearMark?t.filter(e=>!n.clearMark(e)):t.concat(this.parser.schema.marks[n.mark].create(n.attrs)),n.consuming===!1)e=n;else break}}return t}addElementByRule(e,t,n,r){let i,a;if(t.node)if(a=this.parser.schema.nodes[t.node],a.isLeaf)this.insertNode(a.create(t.attrs),n,e.nodeName==`BR`)||this.leafFallback(e,n);else{let e=this.enter(a,t.attrs||null,n,t.preserveWhitespace);e&&(i=!0,n=e)}else{let e=this.parser.schema.marks[t.mark];n=n.concat(e.create(t.attrs))}let o=this.top;if(a&&a.isLeaf)this.findInside(e);else if(r)this.addElement(e,n,r);else if(t.getContent)this.findInside(e),t.getContent(e,this.parser.schema).forEach(e=>this.insertNode(e,n,!1));else{let r=e;typeof t.contentElement==`string`?r=e.querySelector(t.contentElement):typeof t.contentElement==`function`?r=t.contentElement(e):t.contentElement&&(r=t.contentElement),this.findAround(e,r,!0),this.addAll(r,n),this.findAround(e,r,!1)}i&&this.sync(o)&&this.open--}addAll(e,t,n,r){let i=n||0;for(let a=n?e.childNodes[n]:e.firstChild,o=r==null?null:e.childNodes[r];a!=o;a=a.nextSibling,++i)this.findAtPoint(e,i),this.addDOM(a,t);this.findAtPoint(e,i)}findPlace(e,t,n){let r,i;for(let t=this.open,a=0;t>=0;t--){let o=this.nodes[t],s=o.findWrapping(e);if(s&&(!r||r.length>s.length+a)&&(r=s,i=o,!s.length))break;if(o.solid){if(n)break;a+=2}}if(!r)return null;this.sync(i);for(let e=0;e<r.length;e++)t=this.enterInner(r[e],null,t,!1);return t}insertNode(e,t,n){if(e.isInline&&this.needsBlock&&!this.top.type){let e=this.textblockFromContext();e&&(t=this.enterInner(e,null,t))}let r=this.findPlace(e,t,n);if(r){this.closeExtra();let t=this.top;t.match&&=t.match.matchType(e.type);let n=hO.none;for(let i of r.concat(e.marks))(t.type?t.type.allowsMarkType(i.type):wk(i.type,e.type))&&(n=i.addToSet(n));return t.content.push(e.mark(n)),!0}return!1}enter(e,t,n,r){let i=this.findPlace(e.create(t),n,!1);return i&&=this.enterInner(e,t,n,!0,r),i}enterInner(e,t,n,r=!1,i){this.closeExtra();let a=this.top;a.match=a.match&&a.match.matchType(e);let o=vk(e,i,a.options);a.options&_k&&a.content.length==0&&(o|=_k);let s=hO.none;return n=n.filter(t=>(a.type?a.type.allowsMarkType(t.type):wk(t.type,e))?(s=t.addToSet(s),!1):!0),this.nodes.push(new yk(e,t,s,r,null,o)),this.open++,n}closeExtra(e=!1){let t=this.nodes.length-1;if(t>this.open){for(;t>this.open;t--)this.nodes[t-1].content.push(this.nodes[t].finish(e));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(e){for(let t=this.open;t>=0;t--)if(this.nodes[t]==e)return this.open=t,!0;else this.localPreserveWS&&(this.nodes[t].options|=hk);return!1}get currentPos(){this.closeExtra();let e=0;for(let t=this.open;t>=0;t--){let n=this.nodes[t].content;for(let t=n.length-1;t>=0;t--)e+=n[t].nodeSize;t&&e++}return e}findAtPoint(e,t){if(this.find)for(let n=0;n<this.find.length;n++)this.find[n].node==e&&this.find[n].offset==t&&(this.find[n].pos=this.currentPos)}findInside(e){if(this.find)for(let t=0;t<this.find.length;t++)this.find[t].pos==null&&e.nodeType==1&&e.contains(this.find[t].node)&&(this.find[t].pos=this.currentPos)}findAround(e,t,n){if(e!=t&&this.find)for(let r=0;r<this.find.length;r++)this.find[r].pos==null&&e.nodeType==1&&e.contains(this.find[r].node)&&t.compareDocumentPosition(this.find[r].node)&(n?2:4)&&(this.find[r].pos=this.currentPos)}findInText(e){if(this.find)for(let t=0;t<this.find.length;t++)this.find[t].node==e&&(this.find[t].pos=this.currentPos-(e.nodeValue.length-this.find[t].offset))}matchesContext(e){if(e.indexOf(`|`)>-1)return e.split(/\s*\|\s*/).some(this.matchesContext,this);let t=e.split(`/`),n=this.options.context,r=!this.isOpen&&(!n||n.parent.type==this.nodes[0].type),i=-(n?n.depth+1:0)+ +!r,a=(e,o)=>{for(;e>=0;e--){let s=t[e];if(s==``){if(e==t.length-1||e==0)continue;for(;o>=i;o--)if(a(e-1,o))return!0;return!1}else{let e=o>0||o==0&&r?this.nodes[o].type:n&&o>=i?n.node(o-i).type:null;if(!e||e.name!=s&&!e.isInGroup(s))return!1;o--}}return!0};return a(t.length-1,this.open)}textblockFromContext(){let e=this.options.context;if(e)for(let t=e.depth;t>=0;t--){let n=e.node(t).contentMatchAt(e.indexAfter(t)).defaultType;if(n&&n.isTextblock&&n.defaultAttrs)return n}for(let e in this.parser.schema.nodes){let t=this.parser.schema.nodes[e];if(t.isTextblock&&t.defaultAttrs)return t}}};function xk(e){for(let t=e.firstChild,n=null;t;t=t.nextSibling){let e=t.nodeType==1?t.nodeName.toLowerCase():null;e&&mk.hasOwnProperty(e)&&n?(n.appendChild(t),t=n):e==`li`?n=t:e&&(n=null)}}function Sk(e,t){return(e.matches||e.msMatchesSelector||e.webkitMatchesSelector||e.mozMatchesSelector).call(e,t)}function Ck(e){let t={};for(let n in e)t[n]=e[n];return t}function wk(e,t){let n=t.schema.nodes;for(let r in n){let i=n[r];if(!i.allowsMarkType(e))continue;let a=[],o=e=>{a.push(e);for(let n=0;n<e.edgeCount;n++){let{type:r,next:i}=e.edge(n);if(r==t||a.indexOf(i)<0&&o(i))return!0}};if(o(i.contentMatch))return!0}}var Tk=class e{constructor(e,t){this.nodes=e,this.marks=t}serializeFragment(e,t={},n){n||=Dk(t).createDocumentFragment();let r=n,i=[];return e.forEach(e=>{if(i.length||e.marks.length){let n=0,a=0;for(;n<i.length&&a<e.marks.length;){let t=e.marks[a];if(!this.marks[t.type.name]){a++;continue}if(!t.eq(i[n][0])||t.type.spec.spanning===!1)break;n++,a++}for(;n<i.length;)r=i.pop()[1];for(;a<e.marks.length;){let n=e.marks[a++],o=this.serializeMark(n,e.isInline,t);o&&(i.push([n,r]),r.appendChild(o.dom),r=o.contentDOM||o.dom)}}r.appendChild(this.serializeNodeInner(e,t))}),n}serializeNodeInner(e,t){if(e.isText)return Dk(t).createTextNode(e.text);let{dom:n,contentDOM:r}=jk(Dk(t),this.nodes[e.type.name](e),null,e.attrs);if(r){if(e.isLeaf)throw RangeError(`Content hole not allowed in a leaf node spec`);this.serializeFragment(e.content,t,r)}return n}serializeNode(e,t={}){let n=this.serializeNodeInner(e,t);for(let r=e.marks.length-1;r>=0;r--){let i=this.serializeMark(e.marks[r],e.isInline,t);i&&((i.contentDOM||i.dom).appendChild(n),n=i.dom)}return n}serializeMark(e,t,n={}){let r=this.marks[e.type.name];return r&&jk(Dk(n),r(e,t),null,e.attrs)}static renderSpec(e,t,n=null,r){return typeof t==`string`?{dom:e.createTextNode(t)}:jk(e,t,n,r)}static fromSchema(t){return t.cached.domSerializer||(t.cached.domSerializer=new e(this.nodesFromSchema(t),this.marksFromSchema(t)))}static nodesFromSchema(e){let t=Ek(e.nodes);return t.text||=e=>e.text,t}static marksFromSchema(e){return Ek(e.marks)}};function Ek(e){let t={};for(let n in e){let r=e[n].spec.toDOM;r&&(t[n]=r)}return t}function Dk(e){return e.document||window.document}var Ok=new WeakMap;function kk(e){let t=Ok.get(e);return t===void 0&&Ok.set(e,t=Ak(e)),t}function Ak(e){let t=null;function n(e){if(e&&typeof e==`object`)if(Array.isArray(e))if(typeof e[0]==`string`)t||=[],t.push(e);else for(let t=0;t<e.length;t++)n(e[t]);else for(let t in e)n(e[t])}return n(e),t}function jk(e,t,n,r){if(t.nodeType==1)return{dom:t};if(t.dom&&t.dom.nodeType==1)return t;let i=t[0],a;if(typeof i!=`string`)throw RangeError(`Invalid array passed to renderSpec`);if(r&&(a=kk(r))&&a.indexOf(t)>-1)throw RangeError(`Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.`);let o=i.indexOf(` `);o>0&&(n=i.slice(0,o),i=i.slice(o+1));let s,c=n?e.createElementNS(n,i):e.createElement(i),l=t[1],u=1;if(l&&typeof l==`object`&&l.nodeType==null&&!Array.isArray(l)){u=2;for(let e in l)if(l[e]!=null){let t=e.indexOf(` `);t>0?c.setAttributeNS(e.slice(0,t),e.slice(t+1),l[e]):e==`style`&&c.style?c.style.cssText=l[e]:c.setAttribute(e,l[e])}}for(let i=u;i<t.length;i++){let a=t[i];if(a===0){if(i<t.length-1||i>u)throw RangeError(`Content hole must be the only child of its parent node`);return{dom:c,contentDOM:c}}else if(typeof a==`string`)c.appendChild(e.createTextNode(a));else{let{dom:t,contentDOM:i}=jk(e,a,n,r);if(c.appendChild(t),i){if(s)throw RangeError(`Multiple content holes`);s=i}}}return{dom:c,contentDOM:s}}var Mk=65535,Nk=2**16;function Pk(e,t){return e+t*Nk}function Fk(e){return e&Mk}function Ik(e){return(e-(e&Mk))/Nk}var Lk=1,Rk=2,zk=4,Bk=8,Vk=class{constructor(e,t,n){this.pos=e,this.delInfo=t,this.recover=n}get deleted(){return(this.delInfo&Bk)>0}get deletedBefore(){return(this.delInfo&5)>0}get deletedAfter(){return(this.delInfo&6)>0}get deletedAcross(){return(this.delInfo&zk)>0}},Hk=class e{constructor(t,n=!1){if(this.ranges=t,this.inverted=n,!t.length&&e.empty)return e.empty}recover(e){let t=0,n=Fk(e);if(!this.inverted)for(let e=0;e<n;e++)t+=this.ranges[e*3+2]-this.ranges[e*3+1];return this.ranges[n*3]+t+Ik(e)}mapResult(e,t=1){return this._map(e,t,!1)}map(e,t=1){return this._map(e,t,!0)}_map(e,t,n){let r=0,i=this.inverted?2:1,a=this.inverted?1:2;for(let o=0;o<this.ranges.length;o+=3){let s=this.ranges[o]-(this.inverted?r:0);if(s>e)break;let c=this.ranges[o+i],l=this.ranges[o+a],u=s+c;if(e<=u){let i=c?e==s?-1:e==u?1:t:t,a=s+r+(i<0?0:l);if(n)return a;let d=e==(t<0?s:u)?null:Pk(o/3,e-s),f=e==s?Rk:e==u?Lk:zk;return(t<0?e!=s:e!=u)&&(f|=Bk),new Vk(a,f,d)}r+=l-c}return n?e+r:new Vk(e+r,0,null)}touches(e,t){let n=0,r=Fk(t),i=this.inverted?2:1,a=this.inverted?1:2;for(let t=0;t<this.ranges.length;t+=3){let o=this.ranges[t]-(this.inverted?n:0);if(o>e)break;let s=this.ranges[t+i];if(e<=o+s&&t==r*3)return!0;n+=this.ranges[t+a]-s}return!1}forEach(e){let t=this.inverted?2:1,n=this.inverted?1:2;for(let r=0,i=0;r<this.ranges.length;r+=3){let a=this.ranges[r],o=a-(this.inverted?i:0),s=a+(this.inverted?0:i),c=this.ranges[r+t],l=this.ranges[r+n];e(o,o+c,s,s+l),i+=l-c}}invert(){return new e(this.ranges,!this.inverted)}toString(){return(this.inverted?`-`:``)+JSON.stringify(this.ranges)}static offset(t){return t==0?e.empty:new e(t<0?[0,-t,0]:[0,0,t])}};Hk.empty=new Hk([]);var Uk=class e{constructor(e,t,n=0,r=e?e.length:0){this.mirror=t,this.from=n,this.to=r,this._maps=e||[],this.ownData=!(e||t)}get maps(){return this._maps}slice(t=0,n=this.maps.length){return new e(this._maps,this.mirror,t,n)}appendMap(e,t){this.ownData||=(this._maps=this._maps.slice(),this.mirror=this.mirror&&this.mirror.slice(),!0),this.to=this._maps.push(e),t!=null&&this.setMirror(this._maps.length-1,t)}appendMapping(e){for(let t=0,n=this._maps.length;t<e._maps.length;t++){let r=e.getMirror(t);this.appendMap(e._maps[t],r!=null&&r<t?n+r:void 0)}}getMirror(e){if(this.mirror){for(let t=0;t<this.mirror.length;t++)if(this.mirror[t]==e)return this.mirror[t+(t%2?-1:1)]}}setMirror(e,t){this.mirror||=[],this.mirror.push(e,t)}appendMappingInverted(e){for(let t=e.maps.length-1,n=this._maps.length+e._maps.length;t>=0;t--){let r=e.getMirror(t);this.appendMap(e._maps[t].invert(),r!=null&&r>t?n-r-1:void 0)}}invert(){let t=new e;return t.appendMappingInverted(this),t}map(e,t=1){if(this.mirror)return this._map(e,t,!0);for(let n=this.from;n<this.to;n++)e=this._maps[n].map(e,t);return e}mapResult(e,t=1){return this._map(e,t,!1)}_map(e,t,n){let r=0;for(let n=this.from;n<this.to;n++){let i=this._maps[n].mapResult(e,t);if(i.recover!=null){let t=this.getMirror(n);if(t!=null&&t>n&&t<this.to){n=t,e=this._maps[t].recover(i.recover);continue}}r|=i.delInfo,e=i.pos}return n?e:new Vk(e,r,null)}},Wk=Object.create(null),Gk=class{getMap(){return Hk.empty}merge(e){return null}static fromJSON(e,t){if(!t||!t.stepType)throw RangeError(`Invalid input for Step.fromJSON`);let n=Wk[t.stepType];if(!n)throw RangeError(`No step type ${t.stepType} defined`);return n.fromJSON(e,t)}static jsonID(e,t){if(e in Wk)throw RangeError(`Duplicate use of step JSON ID `+e);return Wk[e]=t,t.prototype.jsonID=e,t}},Kk=class e{constructor(e,t){this.doc=e,this.failed=t}static ok(t){return new e(t,null)}static fail(t){return new e(null,t)}static fromReplace(t,n,r,i){try{return e.ok(t.replace(n,r,i))}catch(t){if(t instanceof gO)return e.fail(t.message);throw t}}};function qk(e,t,n){let r=[];for(let i=0;i<e.childCount;i++){let a=e.child(i);a.content.size&&(a=a.copy(qk(a.content,t,a))),a.isInline&&(a=t(a,n,i)),r.push(a)}return dO.fromArray(r)}var Jk=class e extends Gk{constructor(e,t,n){super(),this.from=e,this.to=t,this.mark=n}apply(e){let t=e.slice(this.from,this.to),n=e.resolve(this.from),r=n.node(n.sharedDepth(this.to)),i=new _O(qk(t.content,(e,t)=>!e.isAtom||!t.type.allowsMarkType(this.mark.type)?e:e.mark(this.mark.addToSet(e.marks)),r),t.openStart,t.openEnd);return Kk.fromReplace(e,this.from,this.to,i)}invert(){return new Yk(this.from,this.to,this.mark)}map(t){let n=t.mapResult(this.from,1),r=t.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new e(n.pos,r.pos,this.mark)}merge(t){return t instanceof e&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new e(Math.min(this.from,t.from),Math.max(this.to,t.to),this.mark):null}toJSON(){return{stepType:`addMark`,mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(t,n){if(typeof n.from!=`number`||typeof n.to!=`number`)throw RangeError(`Invalid input for AddMarkStep.fromJSON`);return new e(n.from,n.to,t.markFromJSON(n.mark))}};Gk.jsonID(`addMark`,Jk);var Yk=class e extends Gk{constructor(e,t,n){super(),this.from=e,this.to=t,this.mark=n}apply(e){let t=e.slice(this.from,this.to),n=new _O(qk(t.content,e=>e.mark(this.mark.removeFromSet(e.marks)),e),t.openStart,t.openEnd);return Kk.fromReplace(e,this.from,this.to,n)}invert(){return new Jk(this.from,this.to,this.mark)}map(t){let n=t.mapResult(this.from,1),r=t.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new e(n.pos,r.pos,this.mark)}merge(t){return t instanceof e&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new e(Math.min(this.from,t.from),Math.max(this.to,t.to),this.mark):null}toJSON(){return{stepType:`removeMark`,mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(t,n){if(typeof n.from!=`number`||typeof n.to!=`number`)throw RangeError(`Invalid input for RemoveMarkStep.fromJSON`);return new e(n.from,n.to,t.markFromJSON(n.mark))}};Gk.jsonID(`removeMark`,Yk);var Xk=class e extends Gk{constructor(e,t){super(),this.pos=e,this.mark=t}apply(e){let t=e.nodeAt(this.pos);if(!t)return Kk.fail(`No node at mark step's position`);let n=t.type.create(t.attrs,null,this.mark.addToSet(t.marks));return Kk.fromReplace(e,this.pos,this.pos+1,new _O(dO.from(n),0,+!t.isLeaf))}invert(t){let n=t.nodeAt(this.pos);if(n){let t=this.mark.addToSet(n.marks);if(t.length==n.marks.length){for(let r=0;r<n.marks.length;r++)if(!n.marks[r].isInSet(t))return new e(this.pos,n.marks[r]);return new e(this.pos,this.mark)}}return new Zk(this.pos,this.mark)}map(t){let n=t.mapResult(this.pos,1);return n.deletedAfter?null:new e(n.pos,this.mark)}toJSON(){return{stepType:`addNodeMark`,pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(t,n){if(typeof n.pos!=`number`)throw RangeError(`Invalid input for AddNodeMarkStep.fromJSON`);return new e(n.pos,t.markFromJSON(n.mark))}};Gk.jsonID(`addNodeMark`,Xk);var Zk=class e extends Gk{constructor(e,t){super(),this.pos=e,this.mark=t}apply(e){let t=e.nodeAt(this.pos);if(!t)return Kk.fail(`No node at mark step's position`);let n=t.type.create(t.attrs,null,this.mark.removeFromSet(t.marks));return Kk.fromReplace(e,this.pos,this.pos+1,new _O(dO.from(n),0,+!t.isLeaf))}invert(e){let t=e.nodeAt(this.pos);return!t||!this.mark.isInSet(t.marks)?this:new Xk(this.pos,this.mark)}map(t){let n=t.mapResult(this.pos,1);return n.deletedAfter?null:new e(n.pos,this.mark)}toJSON(){return{stepType:`removeNodeMark`,pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(t,n){if(typeof n.pos!=`number`)throw RangeError(`Invalid input for RemoveNodeMarkStep.fromJSON`);return new e(n.pos,t.markFromJSON(n.mark))}};Gk.jsonID(`removeNodeMark`,Zk);var Qk=class e extends Gk{constructor(e,t,n,r=!1){super(),this.from=e,this.to=t,this.slice=n,this.structure=r}apply(e){return this.structure&&eA(e,this.from,this.to)?Kk.fail(`Structure replace would overwrite content`):Kk.fromReplace(e,this.from,this.to,this.slice)}getMap(){return new Hk([this.from,this.to-this.from,this.slice.size])}invert(t){return new e(this.from,this.from+this.slice.size,t.slice(this.from,this.to))}map(t){let n=t.mapResult(this.to,-1),r=this.from==this.to&&e.MAP_BIAS<0?n:t.mapResult(this.from,1);return r.deletedAcross&&n.deletedAcross?null:new e(r.pos,Math.max(r.pos,n.pos),this.slice,this.structure)}merge(t){if(!(t instanceof e)||t.structure||this.structure)return null;if(this.from+this.slice.size==t.from&&!this.slice.openEnd&&!t.slice.openStart){let n=this.slice.size+t.slice.size==0?_O.empty:new _O(this.slice.content.append(t.slice.content),this.slice.openStart,t.slice.openEnd);return new e(this.from,this.to+(t.to-t.from),n,this.structure)}else if(t.to==this.from&&!this.slice.openStart&&!t.slice.openEnd){let n=this.slice.size+t.slice.size==0?_O.empty:new _O(t.slice.content.append(this.slice.content),t.slice.openStart,this.slice.openEnd);return new e(t.from,this.to,n,this.structure)}else return null}toJSON(){let e={stepType:`replace`,from:this.from,to:this.to};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(t,n){if(typeof n.from!=`number`||typeof n.to!=`number`)throw RangeError(`Invalid input for ReplaceStep.fromJSON`);return new e(n.from,n.to,_O.fromJSON(t,n.slice),!!n.structure)}};Qk.MAP_BIAS=1,Gk.jsonID(`replace`,Qk);var $k=class e extends Gk{constructor(e,t,n,r,i,a,o=!1){super(),this.from=e,this.to=t,this.gapFrom=n,this.gapTo=r,this.slice=i,this.insert=a,this.structure=o}apply(e){if(this.structure&&(eA(e,this.from,this.gapFrom)||eA(e,this.gapTo,this.to)))return Kk.fail(`Structure gap-replace would overwrite content`);let t=e.slice(this.gapFrom,this.gapTo);if(t.openStart||t.openEnd)return Kk.fail(`Gap is not a flat range`);let n=this.slice.insertAt(this.insert,t.content);return n?Kk.fromReplace(e,this.from,this.to,n):Kk.fail(`Content does not fit in gap`)}getMap(){return new Hk([this.from,this.gapFrom-this.from,this.insert,this.gapTo,this.to-this.gapTo,this.slice.size-this.insert])}invert(t){let n=this.gapTo-this.gapFrom;return new e(this.from,this.from+this.slice.size+n,this.from+this.insert,this.from+this.insert+n,t.slice(this.from,this.to).removeBetween(this.gapFrom-this.from,this.gapTo-this.from),this.gapFrom-this.from,this.structure)}map(t){let n=t.mapResult(this.from,1),r=t.mapResult(this.to,-1),i=this.from==this.gapFrom?n.pos:t.map(this.gapFrom,-1),a=this.to==this.gapTo?r.pos:t.map(this.gapTo,1);return n.deletedAcross&&r.deletedAcross||i<n.pos||a>r.pos?null:new e(n.pos,r.pos,i,a,this.slice,this.insert,this.structure)}toJSON(){let e={stepType:`replaceAround`,from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(t,n){if(typeof n.from!=`number`||typeof n.to!=`number`||typeof n.gapFrom!=`number`||typeof n.gapTo!=`number`||typeof n.insert!=`number`)throw RangeError(`Invalid input for ReplaceAroundStep.fromJSON`);return new e(n.from,n.to,n.gapFrom,n.gapTo,_O.fromJSON(t,n.slice),n.insert,!!n.structure)}};Gk.jsonID(`replaceAround`,$k);function eA(e,t,n){let r=e.resolve(t),i=n-t,a=r.depth;for(;i>0&&a>0&&r.indexAfter(a)==r.node(a).childCount;)a--,i--;if(i>0){let e=r.node(a).maybeChild(r.indexAfter(a));for(;i>0;){if(!e||e.isLeaf)return!0;e=e.firstChild,i--}}return!1}function tA(e,t,n,r){let i=[],a=[],o,s;e.doc.nodesBetween(t,n,(e,c,l)=>{if(!e.isInline)return;let u=e.marks;if(!r.isInSet(u)&&l.type.allowsMarkType(r.type)){let l=Math.max(c,t),d=Math.min(c+e.nodeSize,n),f=r.addToSet(u);for(let e=0;e<u.length;e++)u[e].isInSet(f)||(o&&o.to==l&&o.mark.eq(u[e])?o.to=d:i.push(o=new Yk(l,d,u[e])));s&&s.to==l?s.to=d:a.push(s=new Jk(l,d,r))}}),i.forEach(t=>e.step(t)),a.forEach(t=>e.step(t))}function nA(e,t,n,r){let i=[],a=0;e.doc.nodesBetween(t,n,(e,o)=>{if(!e.isInline)return;a++;let s=null;if(r instanceof ok){let t=e.marks,n;for(;n=r.isInSet(t);)(s||=[]).push(n),t=n.removeFromSet(t)}else r?r.isInSet(e.marks)&&(s=[r]):s=e.marks;if(s&&s.length){let r=Math.min(o+e.nodeSize,n);for(let e=0;e<s.length;e++){let n=s[e],c;for(let e=0;e<i.length;e++){let t=i[e];t.step==a-1&&n.eq(i[e].style)&&(c=t)}c?(c.to=r,c.step=a):i.push({style:n,from:Math.max(o,t),to:r,step:a})}}}),i.forEach(t=>e.step(new Yk(t.from,t.to,t.style)))}function rA(e,t,n,r=n.contentMatch,i=!0){let a=e.doc.nodeAt(t),o=[],s=t+1;for(let t=0;t<a.childCount;t++){let c=a.child(t),l=s+c.nodeSize,u=r.matchType(c.type);if(!u)o.push(new Qk(s,l,_O.empty));else{r=u;for(let t=0;t<c.marks.length;t++)n.allowsMarkType(c.marks[t].type)||e.step(new Yk(s,l,c.marks[t]));if(i&&c.isText&&n.whitespace!=`pre`){let e,t=/\r?\n|\r/g,r;for(;e=t.exec(c.text);)r||=new _O(dO.from(n.schema.text(` `,n.allowedMarks(c.marks))),0,0),o.push(new Qk(s+e.index,s+e.index+e[0].length,r))}}s=l}if(!r.validEnd){let t=r.fillBefore(dO.empty,!0);e.replace(s,s,new _O(t,0,0))}for(let t=o.length-1;t>=0;t--)e.step(o[t])}function iA(e,t,n){return(t==0||e.canReplace(t,e.childCount))&&(n==e.childCount||e.canReplace(0,n))}function aA(e){let t=e.parent.content.cutByIndex(e.startIndex,e.endIndex);for(let n=e.depth,r=0,i=0;;--n){let a=e.$from.node(n),o=e.$from.index(n)+r,s=e.$to.indexAfter(n)-i;if(n<e.depth&&a.canReplace(o,s,t))return n;if(n==0||a.type.spec.isolating||!iA(a,o,s))break;o&&(r=1),s<a.childCount&&(i=1)}return null}function oA(e,t,n){let{$from:r,$to:i,depth:a}=t,o=r.before(a+1),s=i.after(a+1),c=o,l=s,u=dO.empty,d=0;for(let e=a,t=!1;e>n;e--)t||r.index(e)>0?(t=!0,u=dO.from(r.node(e).copy(u)),d++):c--;let f=dO.empty,p=0;for(let e=a,t=!1;e>n;e--)t||i.after(e+1)<i.end(e)?(t=!0,f=dO.from(i.node(e).copy(f)),p++):l++;e.step(new $k(c,l,o,s,new _O(u.append(f),d,p),u.size-d,!0))}function sA(e,t,n=null,r=e){let i=lA(e,t),a=i&&uA(r,t);return a?i.map(cA).concat({type:t,attrs:n}).concat(a.map(cA)):null}function cA(e){return{type:e,attrs:null}}function lA(e,t){let{parent:n,startIndex:r,endIndex:i}=e,a=n.contentMatchAt(r).findWrapping(t);if(!a)return null;let o=a.length?a[0]:t;return n.canReplaceWith(r,i,o)?a:null}function uA(e,t){let{parent:n,startIndex:r,endIndex:i}=e,a=n.child(r),o=t.contentMatch.findWrapping(a.type);if(!o)return null;let s=(o.length?o[o.length-1]:t).contentMatch;for(let e=r;s&&e<i;e++)s=s.matchType(n.child(e).type);return!s||!s.validEnd?null:o}function dA(e,t,n){let r=dO.empty;for(let e=n.length-1;e>=0;e--){if(r.size){let t=n[e].type.contentMatch.matchFragment(r);if(!t||!t.validEnd)throw RangeError(`Wrapper type given to Transform.wrap does not form valid content of its parent wrapper`)}r=dO.from(n[e].type.create(n[e].attrs,r))}let i=t.start,a=t.end;e.step(new $k(i,a,i,a,new _O(r,0,0),n.length,!0))}function fA(e,t,n,r,i){if(!r.isTextblock)throw RangeError(`Type given to setBlockType should be a textblock`);let a=e.steps.length;e.doc.nodesBetween(t,n,(t,n)=>{let o=typeof i==`function`?i(t):i;if(t.isTextblock&&!t.hasMarkup(r,o)&&hA(e.doc,e.mapping.slice(a).map(n),r)){let i=null;if(r.schema.linebreakReplacement){let e=r.whitespace==`pre`,t=!!r.contentMatch.matchType(r.schema.linebreakReplacement);e&&!t?i=!1:!e&&t&&(i=!0)}i===!1&&mA(e,t,n,a),rA(e,e.mapping.slice(a).map(n,1),r,void 0,i===null);let s=e.mapping.slice(a),c=s.map(n,1),l=s.map(n+t.nodeSize,1);return e.step(new $k(c,l,c+1,l-1,new _O(dO.from(r.create(o,null,t.marks)),0,0),1,!0)),i===!0&&pA(e,t,n,a),!1}})}function pA(e,t,n,r){t.forEach((i,a)=>{if(i.isText){let o,s=/\r?\n|\r/g;for(;o=s.exec(i.text);){let i=e.mapping.slice(r).map(n+1+a+o.index);e.replaceWith(i,i+1,t.type.schema.linebreakReplacement.create())}}})}function mA(e,t,n,r){t.forEach((i,a)=>{if(i.type==i.type.schema.linebreakReplacement){let i=e.mapping.slice(r).map(n+1+a);e.replaceWith(i,i+1,t.type.schema.text(`
|
|
@@ -2160,4 +2160,4 @@ a=fingerprint:sha-256 34:DF:5C:15:60:FF:28:3E:E8:96:4B:F8:85:61:E4:C0:57:D1:60:8
|
|
|
2160
2160
|
}
|
|
2161
2161
|
|
|
2162
2162
|
registerProcessor('player-processor', PlayerProcessor);
|
|
2163
|
-
`],{type:`application/javascript`}),r=URL.createObjectURL(t);await this._playerAudioContext.audioWorklet.addModule(r);let i=new AudioWorkletNode(this._playerAudioContext,`player-processor`,{numberOfOutputs:1,outputChannelCount:[1]});this._logger.log(`Started Audio worklet.`),i.port.onmessage=async t=>{if(t.data.type===`startedProcessing`)this._logger.log(`Player audio buffer started processing audio.`),this.sendTelemetryEvent(+new Date-n,{step:J5.AUDIO_WORKLET_STARTED_PROCESSING,timestampInfo:{attemptTimestamp:n}},[`Success`],200),e(i);else if(t.data.type===`finished`){let e=+new Date;try{if(t.data.value.shutDownType===`speedUpBuffer`){if(!this._playerWorkletNode)throw new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.PLAYERAUDIOBUFFER_UNDEFINED_CANNOT_DISCONNECT_FOR_SPEEDUP});if(!this._playerAudioDestinationNode)throw new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.PLAYERAUDIOBUFFERNODE_UNDEFINED_FOR_SPEEDUP});this._logger.log(`Speeding up the rest of the audio buffer and shutting down player worklet node`);let n=t.data.value.restOfBufferToSpeedUp,r=n.reduce(((e,t)=>e+t[0].length),0);this._speedUpAudioBuffer=this._playerAudioContext.createBuffer(1,r,this._playerAudioContext.sampleRate);let i=0,a=new Float32Array(r),o=0;for(let e of n)i+=e[0].byteLength??0,a.set(e[0],o),o+=e[0].length;this._speedUpAudioBuffer.copyToChannel(a,0),this._playerWorkletNode.disconnect(),this._speedUpAudioBufferSourceNode=this._playerAudioContext.createBufferSource(),this._speedUpAudioBufferSourceNode.buffer=this._speedUpAudioBuffer,this._speedUpAudioBufferSourceNode.playbackRate.value=c.speedUpRate,this._speedUpAudioBufferSourceNode.connect(this._playerAudioDestinationNode),this.sendTelemetryEvent(+new Date-e,{step:J5.SET_SPEEDUP_AUDIO_STREAM,timestampInfo:{attemptTimestamp:e}},[`Success`],200),this._speedUpAudioBufferSourceNode.onended=()=>{this._storeRecording&&(this._recording?.stop(),this._recording=void 0);let n=+new Date;this._isFinished=!0,this._logger.log(`Finished speeding up the reset of the audio buffer and shut down player audio worklet. Will now switch to microphone.`);let r=t.data.value.playTimestamp,a=e-t.data.value.playTimestamp,o=n-e,s=n-t.data.value.playTimestamp,c=t.data.value.totalRawBytesBuffered,l=t.data.value.rawBytesPlayedNormalSpeed;this._statsReport.playTimestamp=r,this._statsReport.playNormalSpeedDurationInMs=a,this._statsReport.playSpeedUpDurationInMs=o,this._statsReport.totalPlayDurationInMs=s,this._statsReport.totalRawBytesBuffered=c,this._statsReport.rawBytesPlayedNormalSpeed=l,this._statsReport.rawBytesPlayedSpedUp=i,this.sendTelemetryEvent(n-e,{step:J5.SHUTDOWN_FINISHED_SPEEDING_UP_REST_OF_BUFFER,timestampInfo:{attemptTimestamp:e},playTimestamp:r,playNormalSpeedDurationInMs:a,playSpeedUpDurationInMs:o,totalPlayDurationInMs:s,totalRawBytesBuffered:c,rawBytesPlayedNormalSpeed:l,rawBytesPlayedSpedUp:i},[`Success`],200),this.disposeInternal().catch((()=>{this._logger.error(`Failed to dispose PreAudio feature after preAudio finished speeding up`)})),this._switchToRealTimeMic()},this._speedUpAudioBufferSourceNode.start()}}catch(t){this._logger.error(`Error handling finished event from player worklet`,t),this.disposeInternal().catch((()=>{this._logger.error(`Failed to dispose PreAudio feature when handling audio buffer speed up error`)})),this._switchToRealTimeMic();let n=new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.PLAYERAUDIOBUFFER_FINISHED_EVENT_FAIL,originalError:t});this._logger.error(n.message),this.sendTelemetryEvent(+new Date-e,{step:J5.SHUTDOWN_FINISHED_SPEEDING_UP_REST_OF_BUFFER,timestampInfo:{attemptTimestamp:e},...K3(n)},n.resultCategories,500)}}},this._logger.log(`Audio worklet initialized successfully`),this.sendTelemetryEvent(+new Date-n,{step:J5.START_AUDIO_WORKLET,timestampInfo:{attemptTimestamp:n}},[`Success`],200),e(i)}catch(e){this._logger.error(`Error initializing audio worklet`,e);let n=new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.PLAYER_AUDIO_BUFFER_INIT_FAIL,originalError:e});this._logger.error(n.message),t(n)}})),u=new Promise((async(e,t)=>{try{this._deviceManager=await this.mediaClient.getDeviceManager();let t=+new Date;if(this._deviceManager.shouldEnumerateDevices){if((await this._deviceManager.getMicrophones())[0]?.id===`microphone:`){this.sendTelemetryEvent(+new Date,{step:J5.AUDIO_PERMISSION_ASKED,timestampInfo:{attemptTimestamp:+new Date}},[`Success`],200);let e=await this._deviceManager.getAskDevicePermissionPromise({audio:!0,video:!1},x3.PreAudio);if(i=+new Date-t,!e.audio)throw new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.AUDIO_NO_PERMISSION})}this.sendTelemetryEvent(+new Date-t,{step:J5.AUDIO_PERMISSION_GRANTED,timestampInfo:{attemptTimestamp:t}},[`Success`],200)}else this._logger.info(`Device enumeration disabled, skipping getMicrophones permission check`);let n=+new Date;this._micLocalAudioStream=await Y5(this._deviceManager,this._logger),this._logger.log(`Got selected or default microphone`),this.sendTelemetryEvent(+new Date-n,{step:J5.SELECT_MICROPHONE,timestampInfo:{attemptTimestamp:n}},[`Success`],200);let r=+new Date;try{this._audioEffectsFeature=this._micLocalAudioStream.feature(R3(a8));let e=t8().engine;await this._audioEffectsFeature.startEffects({noiseSuppression:e===`Chromium`?this._noiseSuppression:e===`Safari`?void 0:`BrowserNoiseSuppression`,echoCancellation:e===`Chromium`?this._echoCancellation:`BrowserEchoCancellation`}),this.sendTelemetryEvent(+new Date-r,{step:J5.SET_NOISE_SUPPRESSION,timestampInfo:{attemptTimestamp:r}},[`Success`],200)}catch(e){this._logger.error(`Failed to start effects sdk noise suppression`,e);let t=new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.START_EFFECTS_FAIL,originalError:e});throw this._logger.error(t.message),t}this._logger.log(`Effects applied to mic stream with audio effects feature`);let a=+new Date,o;this._micIRawStream=this._deviceManager.getRawDeviceMediaStream(0),this._micIRawStream.changed((async()=>{let e=+new Date;try{this._logger.log(`Microphone raw stream changed`);try{this._micRawMediaStream=await this._micIRawStream?.getMediaStream(!0)}catch(e){this._logger.error(`Failed to get updated raw mic media stream from dm on changed event`,e);let t=W3(e,!0,new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.MICROPHONE_RAW_MEDIASTREAM_CHANGED_FAIL,originalError:e}));throw this._logger.error(t.message),t}this._logger.log(`Got updated raw mic stream from dm on changed event`),this._mediaStreamSession&&this._micRawMediaStream&&this._mediaStreamSession.updateOutboundAudioStream(this._micRawMediaStream),this.sendTelemetryEvent(+new Date-e,{step:J5.MICROPHONE_RAW_MEDIASTREAM_CHANGED,timestampInfo:{attemptTimestamp:e}},[`Success`],200)}catch(t){this._logger.error(`Error handling microphone raw stream changed event`,t);let n=new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.MICROPHONE_RAW_MEDIASTREAM_CHANGED_FAIL,originalError:t});this._logger.error(n.message),this.sendTelemetryEvent(+new Date-e,{step:J5.START_RECORD_AUDIO,timestampInfo:{attemptTimestamp:e},...K3(n)},n.resultCategories,500)}}));try{o=await this._micIRawStream.getMediaStream(!0)}catch(e){this._logger.error(`Failed to get raw mic media stream from dm`,e);let t=W3(e,!0,new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.GET_MIC_STREAM_FAIL,originalError:e}));throw this._logger.error(t.message),t}this._logger.log(`Got raw mic stream from dm`),this.sendTelemetryEvent(+new Date-a,{step:J5.GET_MIC_STREAM,timestampInfo:{attemptTimestamp:a}},[`Success`],200),e(o)}catch(e){this._logger.error(`Error getting microphone media stream`,e);let n=new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.GET_MIC_STREAM_FAIL,originalError:e});this._logger.error(n.message),t(n)}})),[d,f]=await Promise.all([l,u]);this._playerWorkletNode=d,this._micRawMediaStream=f;let p=+new Date,m;try{this._playerAudioSourceNode=this._playerAudioContext.createMediaStreamSource(this._micRawMediaStream),this._playerAudioSourceNode.connect(this._playerWorkletNode),m=this._playerAudioContext.createAnalyser(),m.fftSize=2048,this._playerAudioSourceNode.connect(m),this._playerAudioDestinationNode=this._playerAudioContext.createMediaStreamDestination(),this._playerWorkletNode.connect(this._playerAudioDestinationNode),this._playerRawMediaStream=this._playerAudioDestinationNode.stream,this._playerAudioStream=new u8(this._playerRawMediaStream),this._logger.log(`Created local audio stream from player media stream`),c.getMicStreamSettleTimeInMs>0&&await new Promise((e=>{setTimeout((()=>{this._logger.log(`Mic stream settled`),e()}),c.getMicStreamSettleTimeInMs)})),this._logger.log(`Connected microphone media stream to player worklet node`),this.sendTelemetryEvent(+new Date-p,{step:J5.CONNECT_MIC_TO_PLAYERWORKLET,timestampInfo:{attemptTimestamp:p}},[`Success`],200)}catch(e){this._logger.error(`Failed to connect microphone media stream to player worklet node`,e);let t=new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.CONNECT_MIC_TO_PLAYERAUDIOBUFFER_FAIL,originalError:e});throw this._logger.error(t.message),t}let h=!1,g=null,_=null,v=performance.now(),y=+new Date,b;this._logger.log(`Start time of silence detection: ${y}`);let x=c.speechTimeoutInSec,S=c.rmsThreshold,C=n?c.speechDurationThresholdForPreheated:c.speechDurationThreshold,w=c.silenceDurationThreshold;this._logger.log(`Will use the following thresholds for silence detection:\n Speech Timeout: ${x} seconds,\n RMS Threshold: ${S},\n Speech Duration Threshold: ${C} seconds,\n Silence Duration Threshold: ${w} seconds\n `);let T=0,E=c.logging.rmsLogIntervalInMs,ee=0,D=0,O=c.logging.silenceLogIntervalInMs,k=0,A=c.logging.speechLogIntervalInMs;this._statsReport.rmsMaxDetected={rmsLogIntervalInMs:E,rmsIntervals:[]};let j=async()=>{let e=new Uint8Array(m.fftSize);m.getByteTimeDomainData(e);let t=Math.round(1e4*Math.sqrt(e.reduce(((e,t)=>e+(t-128)**2),0)/e.length))/1e4,n=Math.round((performance.now()-v)/1e3*100)/100;t>ee&&(ee=t);let r=performance.now();if(r-T>=E&&(this._logger.log(`RMS: ${ee}, Seconds past silence detection start: ${n}`),this._statsReport.rmsMaxDetected?.rmsIntervals.push({secondsPastSilenceDetectionsStart:n,maxRms:ee}),T=r,ee=0),n>x&&h)return this._logger.log(`PreAudio silence detection timed out after ${x} seconds. Will shut down player audio worklet, speed up rest of the buffer, and then switch to microphone`),this._statsReport.finishType=J5.SHUTTINGDOWN_PLAYERAUDIOWORKLET_SPEEDUP_AFTER_TIMEOUT,this._statsReport.speechSilenceDetectionDurationInMs=+new Date-y,this._playerWorkletNode?.port.postMessage({type:`shutDown`,value:{shutDownType:`speedUpBuffer`}}),void this.sendTelemetryEvent(+new Date-y,{step:J5.SHUTTINGDOWN_PLAYERAUDIOWORKLET_SPEEDUP_AFTER_TIMEOUT,timestampInfo:{attemptTimestamp:y},rmsMaxDetected:this._statsReport.rmsMaxDetected},[`Success`],200);if(this._isFinished||!h&&(this._play||n>x)){let e,t;this._isFinished?(this._logger.log(`PreAudio already finished, will not do any silence detection and will shutdown player audio worklet`),e=J5.SHUTDOWN_ALREADY_FINISHED):!h&&this._play?(this._logger.log(`No speech detected when play was called. Will switch to real-time microphone, and shut down player audio worklet async`),t=`Failed to dispose PreAudio feature after preAudio finished due to no speech detected`,e=J5.SHUTDOWN_NO_SPEECH_DETECTED):!h&&n>x&&(this._logger.log(`PreAudio silence detection timed out after ${x} seconds and no speech was detected. Will shut down player audio worklet and switch to real-time microphone`),t=`Failed to dispose PreAudio feature when no speech was detected after timeout`,e=J5.SHUTDOWN_PLAYERAUDIOWORKLET_NOSPEECHDETECTED_AFTER_TIMEOUT),this._isFinished=!0,this._statsReport.finishType=e,this._statsReport.speechSilenceDetectionDurationInMs=+new Date-y,this.disposeInternal().catch((()=>{this._logger.error(t)})),this.sendTelemetryEvent(+new Date-y,{step:e,timestampInfo:{attemptTimestamp:y},rmsMaxDetected:this._statsReport.rmsMaxDetected},[`Success`],200),this._switchToRealTimeMic();return}if(t>S){if(_===null&&(this._logger.log(`Starting speech timer at ${n} seconds past start`),_=performance.now(),b=Date.now()),g=null,(performance.now()-_)/1e3>=C){h=!0;let e=performance.now();e-k>=A&&(this._logger.log(`Speech detected for at least a duration of ${C} seconds at ${n} seconds past start`),k=e),this._pendingSpeechStartEpoch===void 0&&(this._pendingSpeechStartEpoch=b,this._logger.log(`Captured pending first speech epoch: ${this._pendingSpeechStartEpoch}`),this.applyPendingSpeechStartTimestampToSession(`post-detection`))}}else if(g===null&&(this._logger.log(`Starting silence timer at ${n} seconds past start`),g=performance.now()),(performance.now()-g)/1e3>=w){if(h){this._logger.log(`Silence detected for a duration of at least 1 second at ${n} seconds past start`),this._playerWorkletNode?.port.postMessage({type:`shutDown`,value:{shutDownType:`speedUpBuffer`}});let e=+new Date-y;this._statsReport.totalRtcAudioBufferedDurationInMs=e,this._statsReport.finishType=J5.SHUTTINGDOWN_PLAYERAUDIOWORKLET_SILENCE_DETECTED_AFTER_SPEECH,this._statsReport.speechSilenceDetectionDurationInMs=+new Date-y,this.sendTelemetryEvent(e,{step:J5.SHUTTINGDOWN_PLAYERAUDIOWORKLET_SILENCE_DETECTED_AFTER_SPEECH,timestampInfo:{attemptTimestamp:y},rmsMaxDetected:this._statsReport.rmsMaxDetected,totalRtcAudioBufferedDurationInMs:e},[`Success`],200);return}let e=performance.now();e-D>=O&&(this._logger.log(`Silence detected for at least 1 second, but no speech detected yet. RMS: ${t}. Seconds past start: ${n}`),D=e),_=null,b=void 0}requestAnimationFrame(j)};j(),this._logger.log(`Audio recording started successfully`);let te=+new Date-i;this._statsReport.recordAudioSuccessTimestamp=te,this.sendTelemetryEvent(te-o,{step:J5.START_RECORD_AUDIO,timestampInfo:{attemptTimestamp:o,successTimestamp:te,createMediaSdkStackBaseDuration:a,adpDuration:i}},[`Success`],200)}catch(e){this._recordAudioFailed=!0,this._logger.error(`Audio recording failed`,e),this.disposeInternal().catch((()=>{this._logger.error(`Failed to dispose PreAudio feature when handling audio recording error`)})),this._switchToRealTimeMic();let t=new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.FAILED_TO_RECORD,originalError:e});throw this._logger.error(t.message),this.sendTelemetryEvent(+new Date-o,{step:J5.START_RECORD_AUDIO,timestampInfo:{attemptTimestamp:o},createMediaSdkStackBaseDuration:a,adpDuration:i,...K3(t)},t.resultCategories,500),t}finally{this._recordAudioFinished=!0}}play(){let e=+new Date;try{this._storeRecording&&this._playerRawMediaStream&&(this._recording=new MediaRecorder(this._playerRawMediaStream,{mimeType:this._recordingMimeType}),this._recordingChunks=[],this._recording.ondataavailable=e=>{e.data.size&&(this._logger.log(`Got preaudio recording data`),this._recordingChunks.push(e.data))},this._recording.start()),this._play=!0,this._playerWorkletNode?.port.postMessage({type:`play`,value:!0}),this._logger.log(`Audio playback started`),this.sendTelemetryEvent(+new Date-e,{step:J5.START_PLAY_AUDIO,timestampInfo:{attemptTimestamp:e}},[`Success`],200)}catch(t){this._logger.error(`Audio playback failed`,t),this.disposeInternal().catch((()=>{this._logger.error(`Failed to dispose PreAudio feature when handling audio playback error`)}));let n=new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.FAILED_TO_PLAY,originalError:t});throw this._logger.error(n.message),this.sendTelemetryEvent(+new Date-e,{timestampInfo:{attemptTimestamp:e},step:J5.START_PLAY_AUDIO,...K3(n)},n.resultCategories,500),n}}downloadRecording(){if(!this._storeRecording||!this._recordingMimeType)return;let e=this._recordingMimeType?.includes(`ogg`)?`ogg`:this._recordingMimeType?.includes(`mp4`)?`m4a`:`webm`,t=new Blob(this._recordingChunks,{type:this._recordingMimeType}),n=document.createElement(`a`);n.href=URL.createObjectURL(t),n.download=`preAudio_recording_${+new Date}.${e}`,n.click(),URL.revokeObjectURL(n.href)}async dispose(){return await this.disposeInternal(!1)}_switchToRealTimeMic(){this._internalDisposed&&this._switchToRealTimeMicCallBack?.()}};function X5(e,t,n,r,i,a){let o=a?K3(a):void 0;r&&i&&z3({featureName:`activeCallTransfer`,featureDetails:{name:`activeCallTransfer`,step:t},featureType:`callAgent`,localParticipantId:e,callId:n?.callId??``,correlationId:``,initializationType:`OnFeatureAccess`,additionalDetails:o},r,i)}var lIe=class{constructor(e,t,n,r){this._skypeConversationObjectMaps=new Map,this._callAgent=e,this._tsCallRegistry=t,this._clientLogger=r}async transferActiveCall(e,t,n){let r,i,a=mTe(e);if(r=this._skypeConversationObjectMaps.get(e.callId),!r)throw this._clientLogger.error(`No SkypeConversationObject found for active call with callId: ${e.callId}`),new Y({defaultError:J.FEATURES.ACTIVE_CALL_TRANSFER.CONVERSATION_NOT_FOUND});if(a){let t=e.meetingLocator.organizerId;r={...r,groupCallInitiator:t},i=2}else i=0;let o={skypeConversationObject:r,mediaPeerType:i},s=n?.joinCallOptions?.videoOptions?.localVideoStreams&&n.joinCallOptions.videoOptions.localVideoStreams.length>0,c=!0!==n?.joinCallOptions?.audioOptions?.muted,l={shouldResurrect:`resurrect`,...o},u,d=K0(),f=AG();try{u=await this._tsCallRegistry.createCallAsync({causeId:f,localParticipantId:d,type:`ThreadId`,callId:e.callId,threadId:a?e.meetingLocator.threadId:``});let i=t.createNewCall(e.callId,u);if(mTe(e)?await u.joinWithMeetingData(f,r,l):await u.join(r,l,f),i.bindTsCall(),s&&n?.joinCallOptions?.videoOptions?.localVideoStreams&&i.startVideo(n.joinCallOptions.videoOptions.localVideoStreams[0]),!1===c&&this._callAgent.deviceManager.selectedMicrophone){this._callAgent.deviceManager.selectedMicrophone;let e=new u8(this._callAgent.deviceManager.selectedMicrophone);i.startAudio(e)}if(this._callAgent.addToCallArray(i),this._callAgent.handleCallState(i),n?.isTransfer){let e=u.endpointId;try{await u.removeParticipant(this._callAgent.getUserMri(),f,e,1)}catch(e){throw this._clientLogger.error(`Failed to remove participant from call during transfer: ${e}`),new Y({defaultError:J.FEATURES.ACTIVE_CALL_TRANSFER.FAILED_TO_REMOVE_PARTICIPANT,originalError:e})}}return X5(this._callAgent.getUserMri(),$.success,e),i}catch(e){throw this._clientLogger.error(`Active call transfer failed: ${e}`),new Y({defaultError:J.FEATURES.ACTIVE_CALL_TRANSFER.ACTIVE_CALL_TRANSFER_FAILURE,originalError:e})}}async getActiveCallDetails(e){let t=this._callAgent.getHttpRequestHelper(),n=this._callAgent.getUserMri(),r={headers:{"Content-Type":`application/json`,"X-SkypeToken":e.jwtToken},method:`GET`},i=Z().calling.activeCallTransfer.callStoreUrl,a=await t.send(i+`${n}/conversations`,JSON.stringify({}),r,3),o=await t.extractPayload(a);if(o&&a.status===200){let e=o,t=e[0];e.length>1&&e.forEach((e=>{e.userJoinTime&&t.userJoinTime&&e.userJoinTime>t.userJoinTime&&(t=e)}));let n=e.map((e=>{if(this._skypeConversationObjectMaps.set(e.correlationId,{conversationUrl:e.conversationController,conversationId:e.correlationId}),`meetingInfo`in e)return this._clientLogger.info(`Found active meeting for client with callId: ${e.correlationId}, threadId: ${e.groupContext.threadId}`),{callId:e.correlationId,meetingLocator:{threadId:e.groupContext.threadId,organizerId:e.meetingInfo.organizerId,tenantId:e.meetingInfo.tenantId,messageId:e.meetingInfo.replyChainMessageId??``},userJoinTime:new Date(e.userJoinTime)};{let t=e.participants.map((e=>G2(e)));return{callId:e.correlationId,participants:t,userJoinTime:new Date(e.userJoinTime)}}}));return this._clientLogger.log(`[ActiveCallTransfer] activeCallList:`,n),n}if(o&&a.status>=400)throw this._clientLogger.error(`Failed to get active calls for client with error: ${o.message}`),new Y({defaultError:J.FEATURES.ACTIVE_CALL_TRANSFER.GET_ACTIVE_CALL_DETAILS_INVALID_TOKEN,originalError:Error(o.message)});this._clientLogger.info(`No active calls found for the client`)}},uIe=class extends LEe{initialize(e,t){if(t.info(`Initializing ActiveCallTransferFeatureImpl`),this._logger=t,this._tsCallRegistry=this._callAgent.getInternalCallRegistry(),this._telemetryLogger=e.telemetryLogManager,this._tsCallRegistry?.on(`proxiedPushNotification`,this.handleProxiedNotification),!this._tsCallRegistry||!this._telemetryLogger)throw this._logger?.error(`Failed to initialize ActiveCallTransferFeatureImpl: TS Call Registry or Telemetry Logger is undefined`),new Y({defaultError:J.FEATURES.ACTIVE_CALL_TRANSFER.CALLAGENT_NOT_INITIALIZED});this._activeCallTransferManager=new lIe(this._callAgent,this._tsCallRegistry,this._telemetryLogger,this._logger)}constructor(e){super(e),this.name=`ActiveCallTransfer`,this.handleProxiedNotification=async e=>{let t,n=this._callAgent._caConfigBag.parsedTokenCredential;if(n){if(e.eventId===115&&this._activeCallTransferManager)this._logger?.log(`Received proxied notification with eventId 115`,e),t=await this._activeCallTransferManager?.getActiveCallDetails(n),t&&t.length>0?(this._logger?.log(`Active call found, emitting activeCallsUpdated event`),X5(this._callAgent.getUserMri(),$.success,t[0],this._telemetryLogger,this._logger),this.emitNewActiveCallDetailsEvent(t)):this._logger?.log(`No active call found, not emitting activeCallsUpdated event`);else if(e.eventId===116&&this._activeCallTransferManager){if(this._logger?.log(`Received proxied notification with eventId 116`,e),t=await this._activeCallTransferManager?.getActiveCallDetails(n),t&&t.length>0)return this._logger?.log(`Active call found on eventId 116, emitting activeCallsUpdated event, forgoing noActiveCalls event`),X5(this._callAgent.getUserMri(),$.success,t[0],this._telemetryLogger,this._logger),void this.emitNewActiveCallDetailsEvent(t);this._logger?.log(`No active call found on eventId 116, emitting noActiveCalls event`),X5(this._callAgent.getUserMri(),$.success,void 0,this._telemetryLogger,this._logger),this.emitNoActiveCallsEvent()}}else this._logger?.error(`No valid token found, cannot process active call details`)},this._callAgent=e.callAgent}async activeCallTransfer(e,t){let n;X5(this._callAgent.getUserMri(),$.attempt,e,this._telemetryLogger,this._logger);try{if(!this._activeCallTransferManager){let t=new Y({defaultError:J.FEATURES.ACTIVE_CALL_TRANSFER.MANAGER_UNDEFINED,originalError:Error(`ActiveCallTransferManager not initialized`)});throw X5(this._callAgent.getUserMri(),$.failure,e,this._telemetryLogger,this._logger,t),t}n=await this._activeCallTransferManager.transferActiveCall(e,this._callAgent,t),this._callAgent.handleActiveCallTransfer(n)}catch(t){this._logger?.error(`Failed to handle active call transfer`,t);let n=new Y({defaultError:J.FEATURES.ACTIVE_CALL_TRANSFER.ACTIVE_CALL_TRANSFER_FAILURE,originalError:t});throw X5(this._callAgent.getUserMri(),$.failure,e,this._telemetryLogger,this._logger,n),n}return X5(this._callAgent.getUserMri(),$.success,e,this._telemetryLogger,this._logger),n}async getActiveCallDetails(){X5(this._callAgent.getUserMri(),$.attempt,void 0,this._telemetryLogger,this._logger);let e=this._callAgent._caConfigBag.parsedTokenCredential;if(!this._activeCallTransferManager||!e){this._logger?.error(`Failed to get active call details: ActiveCallTransferManager not initialized or token is invalid`);let e=new Y({defaultError:J.FEATURES.ACTIVE_CALL_TRANSFER.MANAGER_TOKEN_UNDEFINED,originalError:Error(`ActiveCallTransferManager not initialized or token is invalid`)});throw X5(this._callAgent.getUserMri(),$.failure,void 0,this._telemetryLogger,this._logger,e),e}let t;try{t=await this._activeCallTransferManager?.getActiveCallDetails(e)}catch(e){this._logger?.error(`Failed to get active call details`,e);let t=new Y({defaultError:J.FEATURES.ACTIVE_CALL_TRANSFER.GET_ACTIVE_CALL_DETAILS_FAILURE,originalError:e});throw X5(this._callAgent.getUserMri(),$.failure,void 0,this._telemetryLogger,this._logger,t),t}return X5(this._callAgent.getUserMri(),$.success,void 0,this._telemetryLogger,this._logger),t}dispose(){this.eventEmitter.removeAllListeners()}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}emitNewActiveCallDetailsEvent(e){this.eventEmitter.emit(`activeCallsUpdated`,{activeCallDetails:e})}emitNoActiveCallsEvent(){this.eventEmitter.emit(`noActiveCalls`)}},Z5={Recording:I3(COe),Transfer:I3(FOe),Transcription:I3(kOe),Captions:I3(sDe),Copilot:I3(dDe),RaiseHand:I3(pDe),LocalRecording:I3(EOe),Reaction:I3($Pe),Spotlight:I3(FAe),PPTLive:I3(rFe),BreakoutRooms:I3(wFe),Capabilities:I3(wDe),DominantSpeakers:I3(BDe),LiveStream:I3(Dke),ComposedStream:I3(Ake),CallSurvey:I3(LAe),UserFacingDiagnostics:I3(FDe),MediaStats:I3(SOe,{activationEvent:`OnExtendedObjectConstructor`}),DebugInfo:GEe(jDe,{activationEvent:`OnExtendedObjectConstructor`}),PreCallDiagnostics:GEe(yke),VideoEffects:qEe(G6),AudioEffects:R3(a8),DataChannel:I3(PAe),OptimalVideoCount:I3(BAe),UnmixedAudio:I3(rje),AudioZones:I3(RAe),TeamsMeetingAudioConferencing:I3(ije),TogetherMode:I3(mFe),MediaAccess:I3(Q3),RealTimeText:I3(EFe),DataChannelSession:L3($Fe,{activationEvent:`OnExtendedObjectConstructor`}),MediaStatsSession:L3(rIe,{activationEvent:`OnExtendedObjectConstructor`}),UserFacingDiagnosticsSession:L3(iIe,{activationEvent:`OnExtendedObjectConstructor`}),PreAudioSession:KEe(cIe),ActiveCallTransfer:WEe(uIe)};function Q5(e){switch(e){case D3.CallClientFeature:return Object.entries(Z5).filter((e=>!0===e[1].isCallClientFeature)).map((e=>e[1]));case D3.CallAgentFeature:return Object.entries(Z5).filter((e=>!0===e[1].isCallAgentFeature)).map((e=>e[1]));case D3.CallFeature:return Object.entries(Z5).filter((e=>!0===e[1].isCallFeature)).map((e=>e[1]));case D3.MediaClientFeature:return Object.entries(Z5).filter((e=>!0===e[1].isMediaClientFeature)).map((e=>e[1]));case D3.SessionFeature:return Object.entries(Z5).filter((e=>!0===e[1].isSessionFeature)).map((e=>e[1]))}}var dIe=class{constructor(e,t){this._eventBag=[],this.resetEventBag=()=>{this._eventBag=[]},this._logger=e.createChild(`CallStats`),this._telemetryLogManager=t}recordEvent(e){try{if(Z()?.telemetry?.callStatsFlushTimeout<0||Z()?.telemetry?.blockedEvents?.indexOf(e.name)>-1)return;let t={timestamp:+new Date,...e};this._logger.debug(`CallStat recorded=${e.name}`),this._eventBag.push(t),this.scheduleTelemetryFlush()}catch{this._logger.debug(`Failed to record call stats`)}}flushEvents(){if(this._logger.debug(`CallStats sending telemetry, number of events=${this._eventBag.length}`),this._eventBag.length!==0)try{let e=this._eventBag.reduce(((e,t)=>(e[t.localParticipantId]?e[t.localParticipantId].events.push({name:t.name,timestamp:t.timestamp,...t.data}):e[t.localParticipantId]={callId:t.callId,localParticipantId:t.localParticipantId,events:[{name:t.name,timestamp:t.timestamp,...t.data}]},e)),{});Object.keys(e).forEach((t=>{this._telemetryLogManager.sendEvent({name:Q.acs_calling_call_stats,tenant:d2,properties:{...e[t]}})})),this.resetEventBag()}catch{this._logger.debug(`Failed to send call stats`)}}scheduleTelemetryFlush(){this._callStatSendTimeout||=window.setTimeout((()=>{this.flushEvents(),this._callStatSendTimeout=void 0}),Z().telemetry.callStatsFlushTimeout)}};function $5(e,t){if(t===`Connected`)return;let n;if(e==o4.MuteAllRemoteParticipants)n=J.CALL.MUTE_ALL_PARTICIPANTS_CALL_NOT_CONNECTED;else if(e==o4.StopAudio)n=J.CALL.STOP_AUDIO_STREAM_CALL_NOT_CONNECTED;else if(e==o4.AddParticipant)n=J.CALL.ADD_PARTICIPANT_CALL_NOT_CONNECTED;else{if(e!=o4.RemoveParticipant)return;n=J.CALL.REMOVE_PARTICIPANT_CALL_NOT_CONNECTED}throw new Y({defaultError:n})}var fIe=class{constructor(e){this._volumeIndicator=e,this._eventEmitter=new T3}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}get level(){return this._volumeIndicator.level}async setSource(e){this._mediaStream!==e&&(this._mediaStream&&this._volumeIndicator.dispose(),e&&(this._mediaStream=e,await this._volumeIndicator.getVolumeIndicator(e),this._volumeIndicator.on(`levelChanged`,(()=>{this._eventEmitter.emit(`levelChanged`)}))))}dispose(){this._eventEmitter.removeAllListeners()}},pIe=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},mIe=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},hIe=class{constructor(e,t,n,r){this._workQueue=Promise.resolve();let i=KW(`ACS-calling`);this.logger=new z6(i,[()=>`RemoteAudioStream for media stream`]),this._source=e,this._disposed=!1,this._volumeIndicator=new X6(this.logger,`RemoteAudioStream`,t,n,r),e.changed((async()=>{this._volumeProxy&&(this._workQueue=this._workQueue.then((async()=>{await this._volumeProxy?.setSource(await this._source.getMediaStream())})).catch((e=>{this.logger.log(`source changed but failed to update volume indicator: ${e?.message??`unknown error`}`)})))})),this.logger.info(`created`)}async getMediaStream(){return await this._source.getMediaStream()}get source(){return this._source}dispose(){this.logger.log(`dispose`),this._disposed?this.logger.log(`already disposed`):(this._volumeIndicator.dispose(),this._disposed=!0)}async getVolume(){if(!this._volumeProxy){let e=new fIe(this._volumeIndicator),t=this._workQueue.then((async()=>{await e.setSource(await this._source.getMediaStream())}));this._workQueue=t.catch(A4),await t,this._volumeProxy=e}return this._volumeProxy}};pIe([zG,mIe(`design:type`,Object)],hIe.prototype,`logger`,void 0);var gIe=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},_Ie=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},vIe=class{get currentVideoConstraints(){return this._currentVideoConstraints}constructor(e,t,n){this._tsCall=e,this._currentVideoConstraints={send:{frameHeight:{max:void 0},frameRate:{max:void 0},bitrate:{max:void 0}}},this._logger=t.createChild(`MediaConstraintsManager`),this._telemetryLogManager=n}async setVideoConstraints(e,t,n,r){let i=this.getTelemetryPayload({video:e}),a=e=>{let i=e?{failureReason:e?e.message:void 0,code:e?e.code:void 0,...K3(e)}:void 0;z3({correlationId:n,callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:`SetConstraints`,featureType:`Call`,initializationType:`None`,timestampInfo:{deltaTimeInMs:+new Date-r},featureDetails:{name:`setConstraints`,step:e?$.failure:$.success,stage:t},additionalDetails:{constraints:this.getTelemetryPayload({video:this._currentVideoConstraints}),...i}},this._telemetryLogManager,this._logger)};try{if(z3({correlationId:n,callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:`SetConstraints`,featureType:`Call`,initializationType:`None`,timestampInfo:``,featureDetails:{name:`setConstraints`,step:$.attempt,stage:t},additionalDetails:{constraints:i}},this._telemetryLogManager,this._logger),!Z().calling.constraints.enabled)throw this._logger.error(`Setting call constraints is disabled`),new Y({defaultError:J.CALL.MEDIA_CONSTRAINTS_DISABLED});this._updateVideoConstraintsCache(e);let r={outgoingVideoLimit:{maxResolution:this._currentVideoConstraints.send?.frameHeight?.max,maxFramerate:this._currentVideoConstraints.send?.frameRate?.max,maxBitrate:this._currentVideoConstraints.send?.bitrate?.max}},o=this._tsCall.setCallConstraints?.(r);if(t!==`mid-call`)o?.then((()=>{this._logger.info(`Successfully set call constraints at call ${t} - ${JSON.stringify(this._currentVideoConstraints)}`),a()})).catch((e=>{this._logger.error(`Error setting call constraints at call ${t}`),a(new Y({defaultError:J.CALL.SET_CONSTRAINTS_START_OR_ACCEPT,defaultErrorMessageArgs:[t],originalError:e}))}));else try{await o,this._logger.info(`Successfully set call constraints during ${t} - ${JSON.stringify(this._currentVideoConstraints)}`),a()}catch(e){throw new Y({defaultError:J.CALL.SET_CONSTRAINTS_MID_CALL,originalError:e})}return this._currentVideoConstraints}catch(e){let n=new Y({defaultError:J.CALL.SET_CONSTRAINTS,defaultErrorMessageArgs:[t],originalError:e});throw a(n),n}}getTelemetryPayload(e){return{video:{send:{frameHeight:{max:e.video?.send?.frameHeight?.max},frameRate:{max:e.video?.send?.frameRate?.max},bitrate:{max:e.video?.send?.bitrate?.max}}}}}_updateVideoConstraintsCache(e){let t=Z(),n=t.calling.constraints.maxOutgoingResolution,r=t.calling.constraints.maxOutgoingFrameRate,i=t.calling.constraints.maxOutgoingVideoBitrate,a=e?.send?.frameHeight?.max??this._currentVideoConstraints.send?.frameHeight?.max,o=e?.send?.frameRate?.max??this._currentVideoConstraints.send?.frameRate?.max,s=e?.send?.bitrate?.max??this._currentVideoConstraints.send?.bitrate?.max;this._currentVideoConstraints={send:{frameHeight:{max:this._getConstraintValue(n,`maxOutgoingResolution`,a)},frameRate:{max:this._getConstraintValue(r,`maxOutgoingFrameRate`,o)},bitrate:{max:this._getConstraintValue(i,`maxOutgoingBitrate`,s)}}}}_getConstraintValue(e,t,n){return typeof n==`number`?n<1?void this._logger.info(`Received ${t} as 0 or less, removing ${t} constraint`):(e>0&&n>e&&(this._logger.info(`${t} value ${n} is larger than ${e}, resetting to ${e}`),n=e),n):void this._logger.warn(`Received invalid ${t} value, removing ${t} constraint`)}};gIe([zG,_Ie(`design:type`,Object)],vIe.prototype,`_logger`,void 0);var e7=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},t7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},n7=class{constructor(e,t,n,r){this.logger=n.createChild(`Lobby`),this._tsCall=e,this._eventEmitter=new S6(this.logger),this._participants=new Map,this._call=t,this._telemetryLogManager=r,this._lobbySupportedConversationTypes=Z().calling.lobbyAdmitAndReject.supportedConversationTypes,this._isLobbyEnabled=Z().calling.lobbyAdmitAndReject.enabled,this._hasExpectedError=!1,this._isLobbyEnabled&&(this.getInLobbyParticipants(t.remoteParticipants),this._remoteParticipantUpdatedListener=e=>{if(e.added.length!==0&&e.added.forEach((e=>{e.state===`InLobby`&&this.addLobbyParticipant(e),e.on(`stateChanged`,(()=>{e.state===`InLobby`?this.addLobbyParticipant(e):e.state===`Connected`&&this.removeLobbyParticipant(e)}))})),e.removed.length!==0){if(this._call.remoteParticipants.length===0)return void this.removeAllLobbyParticipants();e.removed.forEach((e=>{this.removeLobbyParticipant(e)}))}},this._call.on(`remoteParticipantsUpdated`,this._remoteParticipantUpdatedListener))}on(e,t){if(e!==`lobbyParticipantsUpdated`)throw new Y({defaultError:J.LOBBY.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if(e!==`lobbyParticipantsUpdated`)throw new Y({defaultError:J.LOBBY.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}async admit(e,t){if(!this._isLobbyEnabled)return void this.logger.warn(`Lobby is not enabled`);let n=K0(),r=+new Date;this._sendLobbyAdmitAndRejectUsage(`Start admit participant`,c3.lobbyAdmit,n,$.attempt,void 0);try{q2(e),this.validateLobbyOperation(e),await this._tsCall.admitParticipant(W2(e));let t=+new Date;this._sendLobbyAdmitAndRejectUsage(`Lobby participant admitted successfully`,c3.lobbyAdmit,n,$.success,t-r)}catch(e){let t=u3.Unexpected;this._hasExpectedError&&=(t=u3.Expected,!1),this.handleLobbyAdmitAndRejectFailure(`Failed to admit participant from lobby`,e,n,r,c3.lobbyAdmit,t)}}async reject(e,t){if(!this._isLobbyEnabled)return void this.logger.warn(`Lobby is not enabled`);let n=K0(),r=+new Date;this._sendLobbyAdmitAndRejectUsage(`Start reject participant`,c3.lobbyReject,n,$.attempt,void 0);try{q2(e),this.validateLobbyOperation(e),await this._tsCall.removeParticipant(W2(e));let t=+new Date;this._sendLobbyAdmitAndRejectUsage(`Lobby participant rejected successfully`,c3.lobbyReject,n,$.success,t-r)}catch(e){let t=u3.Unexpected;this._hasExpectedError&&=(t=u3.Expected,!1),this.handleLobbyAdmitAndRejectFailure(`Failed to reject participant from lobby`,e,n,r,c3.lobbyReject,t)}}async admitAll(e){let t=K0(),n=+new Date,r,i=0,a=0;if(!this._isLobbyEnabled)return this.logger.warn(`Lobby is not enabled`),{successCount:i,failureCount:a};this._sendLobbyAdmitAndRejectUsage(`Start admit all participants`,c3.lobbyAdmitAll,t,$.attempt,void 0);try{this.validateLobbyOperation(),await this._tsCall.admit({scope:`all`},AG()).then((e=>{if(r=e,e.result){let t=JSON.parse(e.result);i=t.successCount,a=t.failureCount}}));let e=+new Date;if(a!==0)return this._sendLobbyAdmitAndRejectUsage(`${i} participants are admitted successfully, ${a} participants admit failed. TransactionEnd: ${r}`,c3.lobbyAdmitAll,t,$.success,e-n),{successCount:i,failureCount:a};this._sendLobbyAdmitAndRejectUsage(`All participants are admitted successfully`,c3.lobbyAdmitAll,t,$.success,e-n)}catch(e){let r=u3.Unexpected;this._hasExpectedError&&=(r=u3.Expected,!1),this.handleLobbyAdmitAndRejectFailure(`Failed to admit all participants from lobby`,e,t,n,c3.lobbyAdmitAll,r)}return{successCount:i,failureCount:a}}get participants(){return this._isLobbyEnabled?Array.from(this._participants.values()):(this.logger.warn(`Lobby is not enabled`),[])}getInLobbyParticipants(e){e.forEach((e=>{if(e.state===`InLobby`){let t=W2(e.identifier);this._participants.set(t,e)}}))}removeAllLobbyParticipants(){if(this._participants.size===0)return;let e=Array.from(this._participants.values());this._participants.clear(),this.logger.info(`All participants are removed from lobby`),this._eventEmitter.emit(`lobbyParticipantsUpdated`,{added:[],removed:e})}removeLobbyParticipant(e){let t=W2(e.identifier);this._participants.has(t)&&(this.logger.info(`${wG(e.identifier).kind} is removed from lobby`),this._participants.delete(t),this._eventEmitter.emit(`lobbyParticipantsUpdated`,{added:[],removed:[e]}))}addLobbyParticipant(e){let t=W2(e.identifier);this._participants.has(t)||(this.logger.info(`${wG(e.identifier).kind} is added to lobby`),this._participants.set(t,e),this._eventEmitter.emit(`lobbyParticipantsUpdated`,{added:[e],removed:[]}))}validateLobbyOperation(e){let t=this._tsCall.conversationType?this._tsCall.conversationType:`oneToOneCall`;if(this.logger.info(`Current conversation type is: `,t),!this._lobbySupportedConversationTypes.find((e=>e===t)))throw this._hasExpectedError=!0,new Y({defaultError:J.LOBBY.CONV_UNSUPPORTED});if(e){let t=this._call.remoteParticipants.find((t=>W2(t.identifier)===W2(e)));if(t&&t.state===`Connected`)throw this._hasExpectedError=!0,new Y({defaultError:J.LOBBY.ALREADY_IN_MEETING,defaultErrorMessageArgs:[wG(e).kind]});if(t&&t.state!==`InLobby`||!t)throw this._hasExpectedError=!0,new Y({defaultError:J.LOBBY.NOT_IN_LOBBY,defaultErrorMessageArgs:[wG(e).kind]})}if(this._call.role!==L2.Presenter&&this._call.role!==L2.Organizer&&this._call.role!==L2.Coorganizer)throw this._hasExpectedError=!0,new Y({defaultError:J.LOBBY.UNAUTHORIZED_ADMIT_REJECT})}handleLobbyAdmitAndRejectFailure(e,t,n,r,i,a){let o=+new Date,s=rDe(this.logger,t,e);throw this._sendLobbyAdmitAndRejectUsage(s.message,i,n,$.failure,o-r,a,t),s}_sendLobbyAdmitAndRejectUsage(e,t,n,r,i,a,o){r===$.failure?this.logger.error(e):this.logger.info(e),this.sendLobbyAdmitAndRejectEvent({eventName:Q.acs_calling_lobby_events,callId:this._call.id,localParticipantId:this._tsCall.participantId,correlationId:n,kindOfEvent:r,operation:t,isExpected:a??``,timestampInfo:i?{deltaTimeInMs:i}:``,additionalDetails:o?{failureReason:o.message,code:o.code,subCode:o.subCode,...K3(o)}:``})}sendLobbyAdmitAndRejectEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:d2,properties:e})}catch{this.logger.debug(`Unable to send lobby admit and reject telemetry`)}}};function yIe(){let e=window.navigator.mediaDevices;if(e?.isRemote){let t=e?.MSRDC_MMR_Shim?.remoteObjectManager?.isConnected;if(!0===t)return`connected`;if(!1===t)return`disconnected`}return``}function r7(){let e=window.navigator.mediaDevices,t={isMMREnabled:e?.isRemote??!1};return t.isMMREnabled&&(e?.mmrClientVersion&&(t.mmrClientVersion=e.mmrClientVersion),e?.mmrExtensionVersion&&(t.mmrExtensionVersion=e.mmrExtensionVersion),e?.mmrHostVersion&&(t.mmrHostVersion=e.mmrHostVersion),e?.activityId&&(t.mmrActivityId=e.activityId),e?.connectionId&&(t.mmrConnectionId=e.connectionId),t.mmrRdpState=yIe()),t}e7([zG,t7(`design:type`,Object)],n7.prototype,`logger`,void 0),e7([GG(o4.LobbyAdmitParticipant),t7(`design:type`,Function),t7(`design:paramtypes`,[Object,Object]),t7(`design:returntype`,Promise)],n7.prototype,`admit`,null),e7([GG(o4.LobbyRejectParticipant),t7(`design:type`,Function),t7(`design:paramtypes`,[Object,Object]),t7(`design:returntype`,Promise)],n7.prototype,`reject`,null),e7([GG(o4.LobbyAdmitAll),t7(`design:type`,Function),t7(`design:paramtypes`,[Object]),t7(`design:returntype`,Promise)],n7.prototype,`admitAll`,null);var bIe=class{constructor(e){this._lastState=``,this._callback=e=>{let t=e?.detail?.state??``;t?t!==this._lastState&&(this._logger.info(`connection state is ${t}`),this._eventEmitter.emit(`stateChange`,t),this._lastState=t):this._logger.info(`connection state is unknown`)},this._logger=e.createChild(`MmrRdpConnectionManager`),this._eventEmitter=new w3.EventEmitter;let t=window.navigator.mediaDevices;t?.isRemote&&(t?.addEventListener(`rdpClientConnectionStateChanged`,this._callback),this._logger.info(`listener registered`))}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}get state(){return yIe()}dispose(){let e=window.navigator.mediaDevices;e?.isRemote&&(e?.removeEventListener(`rdpClientConnectionStateChanged`,this._callback),this._logger.info(`event listener unregistered`)),this._eventEmitter.removeAllListeners()}},xIe=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},a7=class extends g8{constructor(e,t,n,r,i,a,o){let s=i.id;super(e,t,n,s,a,`RemoteVideoStream`),this._remoteParticipantIdentifier=o,this._isAvailable=!1,this.setIsAvailable=e=>{e!==this._isAvailable&&(this._isAvailable=!!e,this.logger.log(`isAvailable changed to ${this._isAvailable}`),this._eventEmitter.emit(`isAvailableChanged`,this._isAvailable),this.call.isHandlingLargeMeetingVideoRendering&&this.call.handleDominantSpeakersVideos(),super.sendRemoteVideoStreamTelemetry())};let c=()=>{if(this.mediaStreamType===`Video`&&n.isHandlingLargeMeetingVideoRendering){for(let e of n.getTopNDominantSpeakersWithVideoOn())if(this.tsStream.isAvailable&&W2(e.identifier)===W2(this._remoteParticipantIdentifier))return void this.setIsAvailable(!0);this.setIsAvailable(!1)}else i.state===7?this.setIsAvailable(!1):(i.state===3&&l.dispose(),this.setIsAvailable(this.tsStream.isAvailable))};this._streamChangedHandler=this.tsStream.changed((()=>{c()}));let l=i.changed((()=>{c()}));c()}on(e,t){if(e!==`isAvailableChanged`&&e!==`sizeChanged`&&e!==`isReceivingChanged`)throw new Y({defaultError:J.REMOTE_VIDEO_STREAM.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if(e!==`isAvailableChanged`&&e!==`sizeChanged`&&e!==`isReceivingChanged`)throw new Y({defaultError:J.REMOTE_VIDEO_STREAM.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}get isAvailable(){return this._isAvailable}async getMediaStream(){let e=K0(),t=+new Date,n=this.tsStream.negotiationTag??``,r={correlationId:e,additionalDetails:{remoteStreamMetadata:this.getStreamMetadata(),mediaSourceId:this.tsStream.mediaSourceId,negotiationTag:n},operation:_3.getMediaStream,mediaType:this.getMediaType(),streamType:g3.Remote,timestampInfo:{attemptTimestamp:t},kindOfEvent:$.attempt,localParticipantId:this.call.tsCall.participantId,callId:this.call.id};this.sendMediaStreamEvent(r);try{if(!this.tsStream.getRawStream)throw new Y({defaultError:J.REMOTE_VIDEO_STREAM.GET_RAW_MEDIA_STREAM});if(!this.tsStream.isAvailable)throw new Y({defaultError:J.REMOTE_VIDEO_STREAM.RAWMEDIA_LVS_NOT_AVAILABLE});let r=this.tsStream.getRawStream(),i=await new Promise((async(e,t)=>{let n=setTimeout((()=>{i.dispose(),t(new Y({defaultError:J.REMOTE_VIDEO_STREAM.SUBSCRIBE_MEDIA_STREAM_TIMEOUT}))}),Z().rendering.remoteVideo.getMediaStreamTimeout),i=r.changed((()=>{a()})),a=async()=>{try{let t=await r.getMediaStream();if(!t)return void this.logger.warn(`MediaStream is not yet ready.`);clearTimeout(n),i.dispose(),e(t)}catch(e){this.logger.warn(`MediaStream is not yet ready, error=${e?.message||`unknown`}`)}};a()})),a=i.getVideoTracks()[0];if(!a)throw new Y({defaultError:J.REMOTE_VIDEO_STREAM.GET_TRACK});await new Promise(((e,t)=>{let n=()=>{a.removeEventListener(`unmute`,n,!1),e()};a.addEventListener(`unmute`,n,!1),a.muted?setTimeout((()=>{a.removeEventListener(`unmute`,n,!1),t(new Y({defaultError:J.REMOTE_VIDEO_STREAM.TRACK_UNMUTED_TIMEOUT}))}),Z().rendering.remoteVideo.getMediaStreamTimeout):n()}));let o={correlationId:e,additionalDetails:{remoteStreamMetadata:this.getStreamMetadata(),mediaSourceId:this.tsStream.mediaSourceId,negotiationTag:n},operation:_3.getMediaStream,mediaType:this.getMediaType(),streamType:g3.Remote,timestampInfo:{deltaTimeInMs:+new Date-t},kindOfEvent:$.success,localParticipantId:this.call.tsCall.participantId,callId:this.call.id};return this.sendMediaStreamEvent(o),i}catch(r){let i={correlationId:e,operation:_3.getMediaStream,mediaType:this.getMediaType(),streamType:g3.Remote,additionalDetails:{failureReason:r?.message||``,code:r.code||IG,...K3(r),remoteStreamMetadata:this.getStreamMetadata(),mediaSourceId:this.tsStream.mediaSourceId,negotiationTag:n},timestampInfo:{deltaTimeInMs:+new Date-t},kindOfEvent:$.failure,localParticipantId:this.call.tsCall.participantId,callId:this.call.id};throw this.sendMediaStreamEvent(i),new Y({defaultError:J.REMOTE_VIDEO_STREAM.GET_MEDIA_STREAM,originalError:r})}}getStreamMetadata(){return{callId:this.call?.id,streamType:this.mediaStreamType,localParticipantId:this.call.tsCall.participantId,remoteParticipantId:this.remoteParticipantId,sourceId:this.id,source:`remote`,rank:this.tsStream.rank,isAvailable:this.tsStream.isAvailable,acsIsAvailable:this._isAvailable,isReceiving:this._isReceiving,isStreaming:this.tsStream.isStreaming,viewIdsRegistered:this._renderers.map((e=>e.viewId)).join(`, `),height:this._size.height,width:this._size.width,isDisposed:this._disposed,optimalVideoCount:this.call?.tsCall.optimalVideoCount||1,currentNumberOfVideosRendered:this.call?.activeRemoteVideoStreamViews?.size||0}}dispose(){this.setIsAvailable(!1),super.dispose()}getMediaType(){return this.mediaStreamType===`ScreenSharing`?h3.ScreenSharingRaw:h3.VideoRaw}sendMediaStreamEvent(e){this.telemetryLogManager.sendEvent({name:Q.acs_calling_media_stream,tenant:d2,properties:{timestampInfo:e.timestampInfo,correlationId:e.correlationId,additionalDetails:e.additionalDetails||``,kindOfEvent:e.kindOfEvent||``,mediaType:e.mediaType,streamType:e.streamType,operation:e.operation,localParticipantId:e.localParticipantId||``,callId:e.callId||``}})}};xIe([GG(Awe.GetMediaStream),i7(`design:type`,Function),i7(`design:paramtypes`,[]),i7(`design:returntype`,Promise)],a7.prototype,`getMediaStream`,null);var o7={2:`#050505`,4:`#0a0a0a`,6:`#0f0f0f`,8:`#141414`,10:`#1a1a1a`,12:`#1f1f1f`,14:`#242424`,16:`#292929`,18:`#2e2e2e`,20:`#333333`,22:`#383838`,24:`#3d3d3d`,26:`#424242`,28:`#474747`,30:`#4d4d4d`,32:`#525252`,34:`#575757`,36:`#5c5c5c`,38:`#616161`,40:`#666666`,42:`#6b6b6b`,44:`#707070`,46:`#757575`,48:`#7a7a7a`,50:`#808080`,52:`#858585`,54:`#8a8a8a`,56:`#8f8f8f`,58:`#949494`,60:`#999999`,62:`#9e9e9e`,64:`#a3a3a3`,66:`#a8a8a8`,68:`#adadad`,70:`#b3b3b3`,72:`#b8b8b8`,74:`#bdbdbd`,76:`#c2c2c2`,78:`#c7c7c7`,80:`#cccccc`,82:`#d1d1d1`,84:`#d6d6d6`,86:`#dbdbdb`,88:`#e0e0e0`,90:`#e6e6e6`,92:`#ebebeb`,94:`#f0f0f0`,96:`#f5f5f5`,98:`#fafafa`},s7={5:`rgba(255, 255, 255, 0.05)`,10:`rgba(255, 255, 255, 0.1)`,20:`rgba(255, 255, 255, 0.2)`,30:`rgba(255, 255, 255, 0.3)`,40:`rgba(255, 255, 255, 0.4)`,50:`rgba(255, 255, 255, 0.5)`,60:`rgba(255, 255, 255, 0.6)`,70:`rgba(255, 255, 255, 0.7)`,80:`rgba(255, 255, 255, 0.8)`,90:`rgba(255, 255, 255, 0.9)`},c7={5:`rgba(0, 0, 0, 0.05)`,10:`rgba(0, 0, 0, 0.1)`,20:`rgba(0, 0, 0, 0.2)`,30:`rgba(0, 0, 0, 0.3)`,40:`rgba(0, 0, 0, 0.4)`,50:`rgba(0, 0, 0, 0.5)`,60:`rgba(0, 0, 0, 0.6)`,70:`rgba(0, 0, 0, 0.7)`,80:`rgba(0, 0, 0, 0.8)`,90:`rgba(0, 0, 0, 0.9)`},l7=`#ffffff`,SIe=`#000000`,CIe={shade50:`#200205`,shade40:`#3b0509`,shade30:`#6e0811`,shade20:`#960b18`,shade10:`#b10e1c`,primary:`#c50f1f`,tint10:`#cc2635`,tint20:`#d33f4c`,tint30:`#dc626d`,tint40:`#eeacb2`,tint50:`#f6d1d5`,tint60:`#fdf3f4`},wIe={shade50:`#031403`,shade40:`#052505`,shade30:`#094509`,shade20:`#0c5e0c`,shade10:`#0e700e`,primary:`#107c10`,tint10:`#218c21`,tint20:`#359b35`,tint30:`#54b054`,tint40:`#9fd89f`,tint50:`#c9eac9`,tint60:`#f1faf1`},u7={red:{shade50:`#210809`,shade40:`#3f1011`,shade30:`#751d1f`,shade20:`#9f282b`,shade10:`#bc2f32`,primary:`#d13438`,tint10:`#d7494c`,tint20:`#dc5e62`,tint30:`#e37d80`,tint40:`#f1bbbc`,tint50:`#f8dadb`,tint60:`#fdf6f6`},green:wIe,darkOrange:{shade50:`#230900`,shade40:`#411200`,shade30:`#7a2101`,shade20:`#a62d01`,shade10:`#c43501`,primary:`#da3b01`,tint10:`#de501c`,tint20:`#e36537`,tint30:`#e9835e`,tint40:`#f4bfab`,tint50:`#f9dcd1`,tint60:`#fdf6f3`},yellow:{shade50:`#282400`,shade40:`#4c4400`,shade30:`#817400`,shade20:`#c0ad00`,shade10:`#e4cc00`,primary:`#fde300`,tint10:`#fde61e`,tint20:`#fdea3d`,tint30:`#feee66`,tint40:`#fef7b2`,tint50:`#fffad6`,tint60:`#fffef5`},berry:{shade50:`#1f091d`,shade40:`#3a1136`,shade30:`#6d2064`,shade20:`#932b88`,shade10:`#af33a1`,primary:`#c239b3`,tint10:`#c94cbc`,tint20:`#d161c4`,tint30:`#da7ed0`,tint40:`#edbbe7`,tint50:`#f5daf2`,tint60:`#fdf5fc`},lightGreen:{shade50:`#031a02`,shade40:`#063004`,shade30:`#0b5a08`,shade20:`#0e7a0b`,shade10:`#11910d`,primary:`#13a10e`,tint10:`#27ac22`,tint20:`#3db838`,tint30:`#5ec75a`,tint40:`#a7e3a5`,tint50:`#cef0cd`,tint60:`#f2fbf2`},marigold:{shade50:`#251a00`,shade40:`#463100`,shade30:`#835b00`,shade20:`#b27c00`,shade10:`#d39300`,primary:`#eaa300`,tint10:`#edad1c`,tint20:`#efb839`,tint30:`#f2c661`,tint40:`#f9e2ae`,tint50:`#fcefd3`,tint60:`#fefbf4`}},d7={darkRed:{shade50:`#130204`,shade40:`#230308`,shade30:`#420610`,shade20:`#590815`,shade10:`#690a19`,primary:`#750b1c`,tint10:`#861b2c`,tint20:`#962f3f`,tint30:`#ac4f5e`,tint40:`#d69ca5`,tint50:`#e9c7cd`,tint60:`#f9f0f2`},cranberry:CIe,pumpkin:{shade50:`#200d03`,shade40:`#3d1805`,shade30:`#712d09`,shade20:`#9a3d0c`,shade10:`#b6480e`,primary:`#ca5010`,tint10:`#d06228`,tint20:`#d77440`,tint30:`#df8e64`,tint40:`#efc4ad`,tint50:`#f7dfd2`,tint60:`#fdf7f4`},peach:{shade50:`#291600`,shade40:`#4d2a00`,shade30:`#8f4e00`,shade20:`#c26a00`,shade10:`#e67e00`,primary:`#ff8c00`,tint10:`#ff9a1f`,tint20:`#ffa83d`,tint30:`#ffba66`,tint40:`#ffddb3`,tint50:`#ffedd6`,tint60:`#fffaf5`},gold:{shade50:`#1f1900`,shade40:`#3a2f00`,shade30:`#6c5700`,shade20:`#937700`,shade10:`#ae8c00`,primary:`#c19c00`,tint10:`#c8a718`,tint20:`#d0b232`,tint30:`#dac157`,tint40:`#ecdfa5`,tint50:`#f5eece`,tint60:`#fdfbf2`},brass:{shade50:`#181202`,shade40:`#2e2103`,shade30:`#553e06`,shade20:`#745408`,shade10:`#89640a`,primary:`#986f0b`,tint10:`#a47d1e`,tint20:`#b18c34`,tint30:`#c1a256`,tint40:`#e0cea2`,tint50:`#efe4cb`,tint60:`#fbf8f2`},brown:{shade50:`#170e07`,shade40:`#2b1a0e`,shade30:`#50301a`,shade20:`#6c4123`,shade10:`#804d29`,primary:`#8e562e`,tint10:`#9c663f`,tint20:`#a97652`,tint30:`#bb8f6f`,tint40:`#ddc3b0`,tint50:`#edded3`,tint60:`#faf7f4`},forest:{shade50:`#0c1501`,shade40:`#162702`,shade30:`#294903`,shade20:`#376304`,shade10:`#427505`,primary:`#498205`,tint10:`#599116`,tint20:`#6ba02b`,tint30:`#85b44c`,tint40:`#bdd99b`,tint50:`#dbebc7`,tint60:`#f6faf0`},seafoam:{shade50:`#002111`,shade40:`#003d20`,shade30:`#00723b`,shade20:`#009b51`,shade10:`#00b85f`,primary:`#00cc6a`,tint10:`#19d279`,tint20:`#34d889`,tint30:`#5ae0a0`,tint40:`#a8f0cd`,tint50:`#cff7e4`,tint60:`#f3fdf8`},darkGreen:{shade50:`#021102`,shade40:`#032003`,shade30:`#063b06`,shade20:`#085108`,shade10:`#0a5f0a`,primary:`#0b6a0b`,tint10:`#1a7c1a`,tint20:`#2d8e2d`,tint30:`#4da64d`,tint40:`#9ad29a`,tint50:`#c6e7c6`,tint60:`#f0f9f0`},lightTeal:{shade50:`#001d1f`,shade40:`#00373a`,shade30:`#00666d`,shade20:`#008b94`,shade10:`#00a5af`,primary:`#00b7c3`,tint10:`#18bfca`,tint20:`#32c8d1`,tint30:`#58d3db`,tint40:`#a6e9ed`,tint50:`#cef3f5`,tint60:`#f2fcfd`},teal:{shade50:`#001516`,shade40:`#012728`,shade30:`#02494c`,shade20:`#026467`,shade10:`#037679`,primary:`#038387`,tint10:`#159195`,tint20:`#2aa0a4`,tint30:`#4cb4b7`,tint40:`#9bd9db`,tint50:`#c7ebec`,tint60:`#f0fafa`},steel:{shade50:`#000f12`,shade40:`#001b22`,shade30:`#00333f`,shade20:`#004555`,shade10:`#005265`,primary:`#005b70`,tint10:`#0f6c81`,tint20:`#237d92`,tint30:`#4496a9`,tint40:`#94c8d4`,tint50:`#c3e1e8`,tint60:`#eff7f9`},blue:{shade50:`#001322`,shade40:`#002440`,shade30:`#004377`,shade20:`#005ba1`,shade10:`#006cbf`,primary:`#0078d4`,tint10:`#1a86d9`,tint20:`#3595de`,tint30:`#5caae5`,tint40:`#a9d3f2`,tint50:`#d0e7f8`,tint60:`#f3f9fd`},royalBlue:{shade50:`#000c16`,shade40:`#00172a`,shade30:`#002c4e`,shade20:`#003b6a`,shade10:`#00467e`,primary:`#004e8c`,tint10:`#125e9a`,tint20:`#286fa8`,tint30:`#4a89ba`,tint40:`#9abfdc`,tint50:`#c7dced`,tint60:`#f0f6fa`},cornflower:{shade50:`#0d1126`,shade40:`#182047`,shade30:`#2c3c85`,shade20:`#3c51b4`,shade10:`#4760d5`,primary:`#4f6bed`,tint10:`#637cef`,tint20:`#778df1`,tint30:`#93a4f4`,tint40:`#c8d1fa`,tint50:`#e1e6fc`,tint60:`#f7f9fe`},navy:{shade50:`#00061d`,shade40:`#000c36`,shade30:`#001665`,shade20:`#001e89`,shade10:`#0023a2`,primary:`#0027b4`,tint10:`#173bbd`,tint20:`#3050c6`,tint30:`#546fd2`,tint40:`#a3b2e8`,tint50:`#ccd5f3`,tint60:`#f2f4fc`},lavender:{shade50:`#120f25`,shade40:`#221d46`,shade30:`#3f3682`,shade20:`#5649b0`,shade10:`#6656d1`,primary:`#7160e8`,tint10:`#8172eb`,tint20:`#9184ee`,tint30:`#a79cf1`,tint40:`#d2ccf8`,tint50:`#e7e4fb`,tint60:`#f9f8fe`},purple:{shade50:`#0f0717`,shade40:`#1c0e2b`,shade30:`#341a51`,shade20:`#46236e`,shade10:`#532982`,primary:`#5c2e91`,tint10:`#6b3f9e`,tint20:`#7c52ab`,tint30:`#9470bd`,tint40:`#c6b1de`,tint50:`#e0d3ed`,tint60:`#f7f4fb`},grape:{shade50:`#160418`,shade40:`#29072e`,shade30:`#4c0d55`,shade20:`#671174`,shade10:`#7a1589`,primary:`#881798`,tint10:`#952aa4`,tint20:`#a33fb1`,tint30:`#b55fc1`,tint40:`#d9a7e0`,tint50:`#eaceef`,tint60:`#faf2fb`},lilac:{shade50:`#1c0b1f`,shade40:`#35153a`,shade30:`#63276d`,shade20:`#863593`,shade10:`#9f3faf`,primary:`#b146c2`,tint10:`#ba58c9`,tint20:`#c36bd1`,tint30:`#cf87da`,tint40:`#e6bfed`,tint50:`#f2dcf5`,tint60:`#fcf6fd`},pink:{shade50:`#24091b`,shade40:`#441232`,shade30:`#80215d`,shade20:`#ad2d7e`,shade10:`#cd3595`,primary:`#e43ba6`,tint10:`#e750b0`,tint20:`#ea66ba`,tint30:`#ef85c8`,tint40:`#f7c0e3`,tint50:`#fbddf0`,tint60:`#fef6fb`},magenta:{shade50:`#1f0013`,shade40:`#390024`,shade30:`#6b0043`,shade20:`#91005a`,shade10:`#ac006b`,primary:`#bf0077`,tint10:`#c71885`,tint20:`#ce3293`,tint30:`#d957a8`,tint40:`#eca5d1`,tint50:`#f5cee6`,tint60:`#fcf2f9`},plum:{shade50:`#13000c`,shade40:`#240017`,shade30:`#43002b`,shade20:`#5a003b`,shade10:`#6b0045`,primary:`#77004d`,tint10:`#87105d`,tint20:`#98246f`,tint30:`#ad4589`,tint40:`#d696c0`,tint50:`#e9c4dc`,tint60:`#faf0f6`},beige:{shade50:`#141313`,shade40:`#252323`,shade30:`#444241`,shade20:`#5d5958`,shade10:`#6e6968`,primary:`#7a7574`,tint10:`#8a8584`,tint20:`#9a9594`,tint30:`#afabaa`,tint40:`#d7d4d4`,tint50:`#eae8e8`,tint60:`#faf9f9`},mink:{shade50:`#0f0e0e`,shade40:`#1c1b1a`,shade30:`#343231`,shade20:`#474443`,shade10:`#54514f`,primary:`#5d5a58`,tint10:`#706d6b`,tint20:`#84817e`,tint30:`#9e9b99`,tint40:`#cecccb`,tint50:`#e5e4e3`,tint60:`#f8f8f8`},platinum:{shade50:`#111314`,shade40:`#1f2426`,shade30:`#3b4447`,shade20:`#505c60`,shade10:`#5f6d71`,primary:`#69797e`,tint10:`#79898d`,tint20:`#89989d`,tint30:`#a0adb2`,tint40:`#cdd6d8`,tint50:`#e4e9ea`,tint60:`#f8f9fa`},anchor:{shade50:`#090a0b`,shade40:`#111315`,shade30:`#202427`,shade20:`#2b3135`,shade10:`#333a3f`,primary:`#394146`,tint10:`#4d565c`,tint20:`#626c72`,tint30:`#808a90`,tint40:`#bcc3c7`,tint50:`#dbdfe1`,tint60:`#f6f7f8`}},f7={cranberry:CIe,green:wIe,orange:{shade50:`#271002`,shade40:`#4a1e04`,shade30:`#8a3707`,shade20:`#bc4b09`,shade10:`#de590b`,primary:`#f7630c`,tint10:`#f87528`,tint20:`#f98845`,tint30:`#faa06b`,tint40:`#fdcfb4`,tint50:`#fee5d7`,tint60:`#fff9f5`}},TIe=`darkRed.cranberry.pumpkin.peach.gold.brass.brown.forest.seafoam.darkGreen.lightTeal.teal.steel.blue.royalBlue.cornflower.navy.lavender.purple.grape.lilac.pink.magenta.plum.beige.mink.platinum.anchor`.split(`.`),p7={success:`green`,warning:`orange`,danger:`cranberry`},m7=[`red`,`green`,`darkOrange`,`yellow`,`berry`,`lightGreen`,`marigold`].reduce(((e,t)=>{let n=t.slice(0,1).toUpperCase()+t.slice(1),r={[`colorPalette${n}Background1`]:u7[t].tint60,[`colorPalette${n}Background2`]:u7[t].tint40,[`colorPalette${n}Background3`]:u7[t].primary,[`colorPalette${n}Foreground1`]:u7[t].shade10,[`colorPalette${n}Foreground2`]:u7[t].shade30,[`colorPalette${n}Foreground3`]:u7[t].primary,[`colorPalette${n}BorderActive`]:u7[t].primary,[`colorPalette${n}Border1`]:u7[t].tint40,[`colorPalette${n}Border2`]:u7[t].primary};return Object.assign(e,r)}),{});m7.colorPaletteYellowForeground1=u7.yellow.shade30,m7.colorPaletteRedForegroundInverted=u7.red.tint20,m7.colorPaletteGreenForegroundInverted=u7.green.tint20,m7.colorPaletteYellowForegroundInverted=u7.yellow.tint40;var EIe=TIe.reduce(((e,t)=>{let n=t.slice(0,1).toUpperCase()+t.slice(1),r={[`colorPalette${n}Background2`]:d7[t].tint40,[`colorPalette${n}Foreground2`]:d7[t].shade30,[`colorPalette${n}BorderActive`]:d7[t].primary};return Object.assign(e,r)}),{}),DIe={...m7,...EIe},h7=Object.entries(p7).reduce(((e,[t,n])=>{let r=t.slice(0,1).toUpperCase()+t.slice(1),i={[`colorStatus${r}Background1`]:f7[n].tint60,[`colorStatus${r}Background2`]:f7[n].tint40,[`colorStatus${r}Background3`]:f7[n].primary,[`colorStatus${r}Foreground1`]:f7[n].shade10,[`colorStatus${r}Foreground2`]:f7[n].shade30,[`colorStatus${r}Foreground3`]:f7[n].primary,[`colorStatus${r}ForegroundInverted`]:f7[n].tint30,[`colorStatus${r}BorderActive`]:f7[n].primary,[`colorStatus${r}Border1`]:f7[n].tint40,[`colorStatus${r}Border2`]:f7[n].primary};return Object.assign(e,i)}),{});h7.colorStatusDangerBackground3Hover=f7[p7.danger].shade10,h7.colorStatusDangerBackground3Pressed=f7[p7.danger].shade20,h7.colorStatusWarningForeground1=f7[p7.warning].shade20,h7.colorStatusWarningForeground3=f7[p7.warning].shade20,h7.colorStatusWarningBorder2=f7[p7.warning].shade20;var OIe=e=>({colorNeutralForeground1:o7[14],colorNeutralForeground1Hover:o7[14],colorNeutralForeground1Pressed:o7[14],colorNeutralForeground1Selected:o7[14],colorNeutralForeground2:o7[26],colorNeutralForeground2Hover:o7[14],colorNeutralForeground2Pressed:o7[14],colorNeutralForeground2Selected:o7[14],colorNeutralForeground2BrandHover:e[80],colorNeutralForeground2BrandPressed:e[70],colorNeutralForeground2BrandSelected:e[80],colorNeutralForeground3:o7[38],colorNeutralForeground3Hover:o7[26],colorNeutralForeground3Pressed:o7[26],colorNeutralForeground3Selected:o7[26],colorNeutralForeground3BrandHover:e[80],colorNeutralForeground3BrandPressed:e[70],colorNeutralForeground3BrandSelected:e[80],colorNeutralForeground4:o7[44],colorNeutralForegroundDisabled:o7[74],colorNeutralForegroundInvertedDisabled:s7[40],colorBrandForegroundLink:e[70],colorBrandForegroundLinkHover:e[60],colorBrandForegroundLinkPressed:e[40],colorBrandForegroundLinkSelected:e[70],colorNeutralForeground2Link:o7[26],colorNeutralForeground2LinkHover:o7[14],colorNeutralForeground2LinkPressed:o7[14],colorNeutralForeground2LinkSelected:o7[14],colorCompoundBrandForeground1:e[80],colorCompoundBrandForeground1Hover:e[70],colorCompoundBrandForeground1Pressed:e[60],colorBrandForeground1:e[80],colorBrandForeground2:e[70],colorBrandForeground2Hover:e[60],colorBrandForeground2Pressed:e[30],colorNeutralForeground1Static:o7[14],colorNeutralForegroundStaticInverted:l7,colorNeutralForegroundInverted:l7,colorNeutralForegroundInvertedHover:l7,colorNeutralForegroundInvertedPressed:l7,colorNeutralForegroundInvertedSelected:l7,colorNeutralForegroundInverted2:l7,colorNeutralForegroundOnBrand:l7,colorNeutralForegroundInvertedLink:l7,colorNeutralForegroundInvertedLinkHover:l7,colorNeutralForegroundInvertedLinkPressed:l7,colorNeutralForegroundInvertedLinkSelected:l7,colorBrandForegroundInverted:e[100],colorBrandForegroundInvertedHover:e[110],colorBrandForegroundInvertedPressed:e[100],colorBrandForegroundOnLight:e[80],colorBrandForegroundOnLightHover:e[70],colorBrandForegroundOnLightPressed:e[50],colorBrandForegroundOnLightSelected:e[60],colorNeutralBackground1:l7,colorNeutralBackground1Hover:o7[96],colorNeutralBackground1Pressed:o7[88],colorNeutralBackground1Selected:o7[92],colorNeutralBackground2:o7[98],colorNeutralBackground2Hover:o7[94],colorNeutralBackground2Pressed:o7[86],colorNeutralBackground2Selected:o7[90],colorNeutralBackground3:o7[96],colorNeutralBackground3Hover:o7[92],colorNeutralBackground3Pressed:o7[84],colorNeutralBackground3Selected:o7[88],colorNeutralBackground4:o7[94],colorNeutralBackground4Hover:o7[98],colorNeutralBackground4Pressed:o7[96],colorNeutralBackground4Selected:l7,colorNeutralBackground5:o7[92],colorNeutralBackground5Hover:o7[96],colorNeutralBackground5Pressed:o7[94],colorNeutralBackground5Selected:o7[98],colorNeutralBackground6:o7[90],colorNeutralBackgroundInverted:o7[16],colorNeutralBackgroundStatic:o7[20],colorNeutralBackgroundAlpha:s7[50],colorNeutralBackgroundAlpha2:s7[80],colorSubtleBackground:`transparent`,colorSubtleBackgroundHover:o7[96],colorSubtleBackgroundPressed:o7[88],colorSubtleBackgroundSelected:o7[92],colorSubtleBackgroundLightAlphaHover:s7[70],colorSubtleBackgroundLightAlphaPressed:s7[50],colorSubtleBackgroundLightAlphaSelected:`transparent`,colorSubtleBackgroundInverted:`transparent`,colorSubtleBackgroundInvertedHover:c7[10],colorSubtleBackgroundInvertedPressed:c7[30],colorSubtleBackgroundInvertedSelected:c7[20],colorTransparentBackground:`transparent`,colorTransparentBackgroundHover:`transparent`,colorTransparentBackgroundPressed:`transparent`,colorTransparentBackgroundSelected:`transparent`,colorNeutralBackgroundDisabled:o7[94],colorNeutralBackgroundInvertedDisabled:s7[10],colorNeutralStencil1:o7[90],colorNeutralStencil2:o7[98],colorNeutralStencil1Alpha:c7[10],colorNeutralStencil2Alpha:c7[5],colorBackgroundOverlay:c7[40],colorScrollbarOverlay:c7[50],colorBrandBackground:e[80],colorBrandBackgroundHover:e[70],colorBrandBackgroundPressed:e[40],colorBrandBackgroundSelected:e[60],colorCompoundBrandBackground:e[80],colorCompoundBrandBackgroundHover:e[70],colorCompoundBrandBackgroundPressed:e[60],colorBrandBackgroundStatic:e[80],colorBrandBackground2:e[160],colorBrandBackground2Hover:e[150],colorBrandBackground2Pressed:e[130],colorBrandBackground3Static:e[60],colorBrandBackground4Static:e[40],colorBrandBackgroundInverted:l7,colorBrandBackgroundInvertedHover:e[160],colorBrandBackgroundInvertedPressed:e[140],colorBrandBackgroundInvertedSelected:e[150],colorNeutralCardBackground:o7[98],colorNeutralCardBackgroundHover:l7,colorNeutralCardBackgroundPressed:o7[96],colorNeutralCardBackgroundSelected:o7[92],colorNeutralCardBackgroundDisabled:o7[94],colorNeutralStrokeAccessible:o7[38],colorNeutralStrokeAccessibleHover:o7[34],colorNeutralStrokeAccessiblePressed:o7[30],colorNeutralStrokeAccessibleSelected:e[80],colorNeutralStroke1:o7[82],colorNeutralStroke1Hover:o7[78],colorNeutralStroke1Pressed:o7[70],colorNeutralStroke1Selected:o7[74],colorNeutralStroke2:o7[88],colorNeutralStroke3:o7[94],colorNeutralStrokeSubtle:o7[88],colorNeutralStrokeOnBrand:l7,colorNeutralStrokeOnBrand2:l7,colorNeutralStrokeOnBrand2Hover:l7,colorNeutralStrokeOnBrand2Pressed:l7,colorNeutralStrokeOnBrand2Selected:l7,colorBrandStroke1:e[80],colorBrandStroke2:e[140],colorBrandStroke2Hover:e[120],colorBrandStroke2Pressed:e[80],colorBrandStroke2Contrast:e[140],colorCompoundBrandStroke:e[80],colorCompoundBrandStrokeHover:e[70],colorCompoundBrandStrokePressed:e[60],colorNeutralStrokeDisabled:o7[88],colorNeutralStrokeInvertedDisabled:s7[40],colorTransparentStroke:`transparent`,colorTransparentStrokeInteractive:`transparent`,colorTransparentStrokeDisabled:`transparent`,colorNeutralStrokeAlpha:c7[5],colorNeutralStrokeAlpha2:s7[20],colorStrokeFocus1:l7,colorStrokeFocus2:SIe,colorNeutralShadowAmbient:`rgba(0,0,0,0.12)`,colorNeutralShadowKey:`rgba(0,0,0,0.14)`,colorNeutralShadowAmbientLighter:`rgba(0,0,0,0.06)`,colorNeutralShadowKeyLighter:`rgba(0,0,0,0.07)`,colorNeutralShadowAmbientDarker:`rgba(0,0,0,0.20)`,colorNeutralShadowKeyDarker:`rgba(0,0,0,0.24)`,colorBrandShadowAmbient:`rgba(0,0,0,0.30)`,colorBrandShadowKey:`rgba(0,0,0,0.25)`}),kIe={borderRadiusNone:`0`,borderRadiusSmall:`2px`,borderRadiusMedium:`4px`,borderRadiusLarge:`6px`,borderRadiusXLarge:`8px`,borderRadiusCircular:`10000px`},AIe={curveAccelerateMax:`cubic-bezier(0.9,0.1,1,0.2)`,curveAccelerateMid:`cubic-bezier(1,0,1,1)`,curveAccelerateMin:`cubic-bezier(0.8,0,0.78,1)`,curveDecelerateMax:`cubic-bezier(0.1,0.9,0.2,1)`,curveDecelerateMid:`cubic-bezier(0,0,0,1)`,curveDecelerateMin:`cubic-bezier(0.33,0,0.1,1)`,curveEasyEaseMax:`cubic-bezier(0.8,0,0.2,1)`,curveEasyEase:`cubic-bezier(0.33,0,0.67,1)`,curveLinear:`cubic-bezier(0,0,1,1)`},jIe={durationUltraFast:`50ms`,durationFaster:`100ms`,durationFast:`150ms`,durationNormal:`200ms`,durationGentle:`250ms`,durationSlow:`300ms`,durationSlower:`400ms`,durationUltraSlow:`500ms`},MIe={fontSizeBase100:`10px`,fontSizeBase200:`12px`,fontSizeBase300:`14px`,fontSizeBase400:`16px`,fontSizeBase500:`20px`,fontSizeBase600:`24px`,fontSizeHero700:`28px`,fontSizeHero800:`32px`,fontSizeHero900:`40px`,fontSizeHero1000:`68px`},NIe={lineHeightBase100:`14px`,lineHeightBase200:`16px`,lineHeightBase300:`20px`,lineHeightBase400:`22px`,lineHeightBase500:`28px`,lineHeightBase600:`32px`,lineHeightHero700:`36px`,lineHeightHero800:`40px`,lineHeightHero900:`52px`,lineHeightHero1000:`92px`},PIe={fontWeightRegular:400,fontWeightMedium:500,fontWeightSemibold:600,fontWeightBold:700},FIe={fontFamilyBase:`'Segoe UI', 'Segoe UI Web (West European)', -apple-system, BlinkMacSystemFont, Roboto, 'Helvetica Neue', sans-serif`,fontFamilyMonospace:`Consolas, 'Courier New', Courier, monospace`,fontFamilyNumeric:`Bahnschrift, 'Segoe UI', 'Segoe UI Web (West European)', -apple-system, BlinkMacSystemFont, Roboto, 'Helvetica Neue', sans-serif`},g7={none:`0`,xxs:`2px`,xs:`4px`,sNudge:`6px`,s:`8px`,mNudge:`10px`,m:`12px`,l:`16px`,xl:`20px`,xxl:`24px`,xxxl:`32px`},IIe={spacingHorizontalNone:g7.none,spacingHorizontalXXS:g7.xxs,spacingHorizontalXS:g7.xs,spacingHorizontalSNudge:g7.sNudge,spacingHorizontalS:g7.s,spacingHorizontalMNudge:g7.mNudge,spacingHorizontalM:g7.m,spacingHorizontalL:g7.l,spacingHorizontalXL:g7.xl,spacingHorizontalXXL:g7.xxl,spacingHorizontalXXXL:g7.xxxl},LIe={spacingVerticalNone:g7.none,spacingVerticalXXS:g7.xxs,spacingVerticalXS:g7.xs,spacingVerticalSNudge:g7.sNudge,spacingVerticalS:g7.s,spacingVerticalMNudge:g7.mNudge,spacingVerticalM:g7.m,spacingVerticalL:g7.l,spacingVerticalXL:g7.xl,spacingVerticalXXL:g7.xxl,spacingVerticalXXXL:g7.xxxl},RIe={strokeWidthThin:`1px`,strokeWidthThick:`2px`,strokeWidthThicker:`3px`,strokeWidthThickest:`4px`};function zIe(e,t,n=``){return{[`shadow2${n}`]:`0 0 2px ${e}, 0 1px 2px ${t}`,[`shadow4${n}`]:`0 0 2px ${e}, 0 2px 4px ${t}`,[`shadow8${n}`]:`0 0 2px ${e}, 0 4px 8px ${t}`,[`shadow16${n}`]:`0 0 2px ${e}, 0 8px 16px ${t}`,[`shadow28${n}`]:`0 0 8px ${e}, 0 14px 28px ${t}`,[`shadow64${n}`]:`0 0 8px ${e}, 0 32px 64px ${t}`}}var BIe=(e=>{let t=OIe(e);return{...kIe,...MIe,...NIe,...FIe,...PIe,...RIe,...IIe,...LIe,...jIe,...AIe,...t,...DIe,...h7,...zIe(t.colorNeutralShadowAmbient,t.colorNeutralShadowKey),...zIe(t.colorBrandShadowAmbient,t.colorBrandShadowKey,`Brand`)}})({10:`#061724`,20:`#082338`,30:`#0a2e4a`,40:`#0c3b5e`,50:`#0e4775`,60:`#0f548c`,70:`#115ea3`,80:`#0f6cbd`,90:`#2886de`,100:`#479ef5`,110:`#62abf5`,120:`#77b7f7`,130:`#96c6fa`,140:`#b4d6fa`,150:`#cfe4fa`,160:`#ebf3fc`}),VIe=1,HIe=class{constructor(e,t,n,r,i){this._container=e,this._videoStream=t,this._viewId=n,this._streamTelemetryEventSender=i,this._watermarkCapability=null,this.WATERMARK_TEXT_COMMON_STYLES={fontFamily:BIe.fontFamilyBase,fontWeight:`bold`,stroke:`black`,strokeOpacity:`0.1`,fill:BIe.colorNeutralStrokeOnBrand2},this.WATERMARK_CONTAINER_STYLES={position:`absolute`,pointerEvents:`none`,width:`100%`,height:`100%`,top:`0`,left:`0`},this.TEXT_ROTATION=30,this.SHADOW_OPACITY_RATIO=3,this.RANGE_MAX=100,this.BORDER_SIZE=18,this.BORDER_SIZE_FRAC=1/this.BORDER_SIZE,this.SPACE_USE=.9,this.MAX_BORDER=2,this.SINGLE_PATTERN_FONT_SIZE_FACTOR=.07,this._svgContainerHidden=``,this._svgWatermarkUseTextScale=0,this._svgWatermarkUseTextBorderSize=0,this._svgTextTiledScaledSize=0,this._svgTextTiledScaledStrokeWidth=0,this._svgFirstPatternWidth=0,this._svgFirstPatternHeight=0,this._svgSecondPatternWidth=0,this._svgSecondPatternHeight=0,this._svgSecondPatternOffsetX=0,this._svgSecondPatternOffsetY=0,this._computeTextDiagonal=wwe(this.TEXT_ROTATION),this._isApple=!1,this._getScaledPatternDimensions=(e,t,n,r)=>({width:e*(n+1.1),height:t*(r+1.1)}),this._call=this._videoStream.call,this._logger=r.createChild(`WatermarkOverlayProvider`+ VIe++);let a=this._call.getMeetingCapabilitiesInternal();if(!a){this._logger.warn(`No watermark capabilities found. Likely not received from service.`);let e=new Y({defaultError:J.VIEW.NO_WATERMARK_CAPABILITY_RECEIVED}),t=K0();this._streamTelemetryEventSender.sendMediaStreamEvent({correlationId:t,callId:this._call.id,timestampInfo:{attemptTimestamp:Date.now()},operation:_3.watermark,kindOfEvent:$.failure,mediaType:this._videoStream.mediaStreamType,streamType:g3.Remote,additionalDetails:{failureReason:e.message,code:e.code,...K3(e),watermark:{...this._getWatermarkUsageTelemetryPayload()}}});return}this._watermarkCapability=a.waterMarkCapability;let o=this._call.deviceManager.getOSNameInternal();this._isApple=o===`ios`||o===`mac`,this._resizeObserver=new ResizeObserver((e=>{for(let t of e)if(t.contentRect?.width>1){let e=t.contentRect.width,n=t.contentRect.height;this._updateWatermarkScalingValues(e,n)}})),this._resizeObserver.observe(this._container)}attach(){let e=K0(),t=Date.now();try{if(!this._watermarkCapability)return void this._logger.warn(`No watermark capabilities found. No-op.`);if(this._videoStream.mediaStreamType!==`Video`&&this._videoStream.mediaStreamType!==`ScreenSharing`)throw Error(`Unsupported media type for watermark`);this._watermarkIsReceivingSub=()=>{this._videoStream.isReceiving&&(this._generateWatermark(this._videoStream.mediaStreamType,e),this._updateWatermarkScalingValues(this._container.getBoundingClientRect().width,this._container.getBoundingClientRect().height))},this._videoStream.on(`isReceivingChanged`,this._watermarkIsReceivingSub)}catch(n){let r=new Y({defaultError:J.VIEW.WATERMARK_ATTACH_FAIL,originalError:n});throw this._streamTelemetryEventSender.sendMediaStreamEvent({correlationId:e,callId:this._call.id,timestampInfo:{deltaTimeInMs:Date.now()-t},operation:_3.watermark,kindOfEvent:$.failure,mediaType:this._videoStream.mediaStreamType,streamType:g3.Remote,additionalDetails:{failureReason:r.message,code:r.code,...K3(r),watermark:{...this._getWatermarkUsageTelemetryPayload()}}}),r}}dispose(){this._resizeObserver&&this._resizeObserver.disconnect(),this._mutationObserver&&this._mutationObserver.disconnect(),this._audioOnlyCallback&&this._call.offWatermarkAudioOnlyFallbackTriggeredChanged(`watermarkAudioOnlyFallbackTriggeredChanged`,this._audioOnlyCallback),this._svgContainer&&(this._container.removeChild(this._svgContainer),this._svgContainer=void 0,this._svgContainerHidden=``),this._watermarkIsReceivingSub&&this._videoStream.off(`isReceivingChanged`,this._watermarkIsReceivingSub),this._logger.info(`watermark overlay provider disposed for viewid: ${this._viewId}`)}_updateWatermarkScalingValues(e,t){this._getSelectedWatermarkPattern()===`Single`?this._updateWatermarkUseTextScalingSingle(e,t):this._getSelectedWatermarkPattern()===`Tiled`&&this._updateWatermarkPatternScalingTiled(e,t)}_generateWatermark(e,t){let n=Date.now();try{if(!this._watermarkCapability)return void this._logger.warn(`No watermark capabilities found. No-op.`);if(this._call.watermarkAudioOnlyFallbackTriggered)return this._logger.warn(`Watermark audio only fallback was triggered, disposing remote stream`),void this._videoStream.dispose();let r;if(e===`Video`&&this._watermarkCapability.enabledForVideo)r=this._watermarkCapability.videoSettings;else{if(e!==`ScreenSharing`||!this._watermarkCapability.enabledForVbss)return void this._logger.info(`No watermark operations to be done on viewId: ${this._viewId}`);r=this._watermarkCapability.vbssSettings}if(this._streamTelemetryEventSender.sendMediaStreamEvent({correlationId:t,callId:this._call.id,timestampInfo:{attemptTimestamp:n},operation:_3.watermark,kindOfEvent:$.attempt,mediaType:this._videoStream.mediaStreamType,streamType:g3.Remote,additionalDetails:{watermark:{...this._getWatermarkUsageTelemetryPayload()}}}),!r||!r.opacity||!r.pattern||typeof r.opacity!=`number`||typeof r.pattern!=`string`)throw this._logger.debug(`Unexpected watermark settings`),new Y({defaultError:J.VIEW.WATERMARK_UNEXPECTED_VALUES});let i=this._getClampedUsername(),a;if(r.pattern===`Single`)a=this._generateSinglePatternWatermark(i,r);else{if(r.pattern!==`Tiled`)throw this._logger.debug(`Unexpected watermark pattern setting`),new Y({defaultError:J.VIEW.WATERMARK_UNEXPECTED_VALUES});a=this._generateTiledPatternWatermark(i,r)}this._svgContainerHidden=a.outerHTML,this._container.appendChild(a),this._audioOnlyCallback=()=>{this._call.watermarkAudioOnlyFallbackTriggered&&(this._logger.debug(`Watermark audio only fallback triggered by one of the renderers`),this._logger.debug(`Disposing remote stream with viewId ${this._viewId}`),this._videoStream.dispose(),this._streamTelemetryEventSender.sendMediaStreamEvent({correlationId:t,callId:this._call.id,timestampInfo:{attemptTimestamp:Date.now()},operation:_3.watermark,kindOfEvent:$.event,mediaType:this._videoStream.mediaStreamType,streamType:g3.Remote,additionalDetails:{watermark:{...this._getWatermarkUsageTelemetryPayload()}}}))},this._call.onWatermarkAudioOnlyFallbackTriggeredChanged(`watermarkAudioOnlyFallbackTriggeredChanged`,this._audioOnlyCallback),this._mutationObserver=new MutationObserver((e=>{this._svgContainer?.outerHTML!==this._svgContainerHidden&&(this._logger.debug(`watermark mutation detected, falling back to audio only!`),this._triggerAudioOnlyFallback(),this._streamTelemetryEventSender.sendMediaStreamEvent({correlationId:t,callId:this._call.id,timestampInfo:{attemptTimestamp:Date.now()},operation:_3.watermark,kindOfEvent:$.event,mediaType:this._videoStream.mediaStreamType,streamType:g3.Remote,additionalDetails:{watermark:{...this._getWatermarkUsageTelemetryPayload(this._viewId)}}}))})),this._mutationObserver.observe(this._container,{attributes:!0,subtree:!0,childList:!0}),this._logger.info(`watermark attached for viewId: ${this._viewId}`),this._streamTelemetryEventSender.sendMediaStreamEvent({correlationId:t,callId:this._call.id,timestampInfo:{deltaTimeInMs:Date.now()-n},operation:_3.watermark,kindOfEvent:$.success,mediaType:this._videoStream.mediaStreamType,streamType:g3.Remote,additionalDetails:{watermark:{...this._getWatermarkUsageTelemetryPayload()}}})}catch(e){let r=new Y({defaultError:J.VIEW.WATERMARK_ATTACH_FAIL,originalError:e});throw this._triggerAudioOnlyFallback(),this._streamTelemetryEventSender.sendMediaStreamEvent({correlationId:t,callId:this._call.id,timestampInfo:{deltaTimeInMs:Date.now()-n},operation:_3.watermark,kindOfEvent:$.failure,mediaType:this._videoStream.mediaStreamType,streamType:g3.Remote,additionalDetails:{failureReason:r.message,code:r.code,...K3(r),watermark:{...this._getWatermarkUsageTelemetryPayload(this._viewId)}}}),r}}_triggerAudioOnlyFallback(){this._logger.debug(`audio only fallback triggered by viewId ${this._viewId}`),this._logger.debug(`Disposing remote stream with viewId ${this._viewId}`),this._videoStream.dispose(),this._call.setWatermarkAudioOnlyFallbackTriggered(!0)}_addStyleAttributesToSvgElement(e,t){for(let[n,r]of Object.entries(t))e.style[`${n}`]=r}_generateSinglePatternWatermark(e,t){let n=this._getWatermarkContainer(t);this._svgContainer=n;let r=t.opacity/this.RANGE_MAX,i=r/this.SHADOW_OPACITY_RATIO,a=K0(),o=`url(#${a})`,s=document.createElementNS(`http://www.w3.org/2000/svg`,`defs`),c=this._getSvgFilter(a,i),l=document.createElementNS(`http://www.w3.org/2000/svg`,`text`);l.id=K0(),this._addStyleAttributesToSvgElement(l,this.WATERMARK_TEXT_COMMON_STYLES),l.setAttribute(`filter`,o),l.setAttribute(`text-anchor`,`middle`),l.setAttribute(`dominant-baseline`,`middle`),l.setAttribute(`fill-opacity`,`${r}`),l.style.transform=`rotate(-30deg)`;let u=document.createTextNode(e);l.appendChild(u),this._svgTextDefElement=l,s.appendChild(c),s.appendChild(l);let d=document.createElementNS(`http://www.w3.org/2000/svg`,`use`);return d.id=K0(),this._svgWatermarkUseTagSinglePattern=d,d.setAttribute(`href`,`#${this._svgTextDefElement.id}`),d.setAttribute(`x`,`50%`),d.setAttribute(`y`,`50%`),d.setAttribute(`width`,`100%`),d.setAttribute(`height`,`100%`),d.setAttribute(`font-size`,`${this._svgWatermarkUseTextScale}`),d.setAttribute(`stroke-width`,`${this._svgWatermarkUseTextBorderSize}`),n.appendChild(s),n.appendChild(d),this._updateWatermarkUseTextScalingSingle(this._container.getBoundingClientRect().width,this._container.getBoundingClientRect().height),n}_updateWatermarkUseTextScalingSingle(e,t){if(this._svgContainer&&this._svgWatermarkUseTagSinglePattern){let n=this._computeTextDiagonal(e,t);this._svgWatermarkUseTextScale=this.SPACE_USE*n*this.SINGLE_PATTERN_FONT_SIZE_FACTOR,this._svgWatermarkUseTextBorderSize=Math.max(1,Math.min(this.MAX_BORDER,this._svgWatermarkUseTextScale*this.BORDER_SIZE_FRAC)),this._svgWatermarkUseTagSinglePattern.setAttribute(`font-size`,`${this._svgWatermarkUseTextScale}`),this._svgWatermarkUseTagSinglePattern.setAttribute(`stroke-width`,`${this._svgWatermarkUseTextBorderSize}`),this._svgContainerHidden=this._svgContainer.outerHTML;return}this._logger.warn(`svg watermark element missing, cannot update`)}_updateWatermarkPatternScalingTiled(e,t){if(this._svgContainer&&this._svgTextDefElement&&this._svgFirstPattern&&this._svgSecondPattern){let n=Cwe(e,t,this._isApple);this._svgTextTiledScaledSize=n.scaledFontSize,this._svgTextTiledScaledStrokeWidth=n.scaledBorderSize,this._svgTextDefElement.setAttribute(`font-size`,`${this._svgTextTiledScaledSize}`),this._svgTextDefElement.setAttribute(`stroke-width`,`${this._svgTextTiledScaledStrokeWidth}`);let r=this._svgTextDefElement.getBoundingClientRect().width,i=this._svgTextDefElement.getBoundingClientRect().height,{width:a,height:o}=this._getScaledPatternDimensions(r,i,n.scaledHorizontalGap,n.scaledVerticalGap),s=.5*a,c=.5*o;this._svgFirstPatternWidth=a,this._svgFirstPatternHeight=o,this._svgSecondPatternWidth=a,this._svgSecondPatternHeight=o,this._svgSecondPatternOffsetX=s,this._svgSecondPatternOffsetY=c,this._svgFirstPattern.setAttribute(`width`,`${this._svgFirstPatternWidth}`),this._svgFirstPattern.setAttribute(`height`,`${this._svgFirstPatternHeight}`),this._svgSecondPattern.setAttribute(`width`,`${this._svgSecondPatternWidth}`),this._svgSecondPattern.setAttribute(`height`,`${this._svgSecondPatternHeight}`),this._svgSecondPattern.setAttribute(`x`,`${this._svgSecondPatternOffsetX}`),this._svgSecondPattern.setAttribute(`y`,`${this._svgSecondPatternOffsetY}`),this._svgContainerHidden=this._svgContainer.outerHTML;return}this._logger.warn(`svg watermark element missing, cannot update`)}_generateTiledPatternWatermark(e,t){let n=this._getWatermarkContainer(t);this._svgContainer=n;let r=t.opacity/this.RANGE_MAX,i=r/this.SHADOW_OPACITY_RATIO,a=K0(),o=K0(),s=K0(),c=`url(#${a})`,l=document.createElementNS(`http://www.w3.org/2000/svg`,`defs`),u=this._getSvgFilter(a,i),d=document.createElementNS(`http://www.w3.org/2000/svg`,`text`);this._svgTextDefElement=d,d.id=K0(),this._addStyleAttributesToSvgElement(d,this.WATERMARK_TEXT_COMMON_STYLES),d.setAttribute(`filter`,c),d.setAttribute(`dominant-baseline`,`hanging`),d.setAttribute(`fill-opacity`,`${r}`),d.setAttribute(`font-size`,`${this._svgTextTiledScaledSize}`),d.setAttribute(`stroke-width`,`${this._svgTextTiledScaledStrokeWidth}`);let f=document.createTextNode(e);d.appendChild(f);let p=document.createElementNS(`http://www.w3.org/2000/svg`,`pattern`);this._svgFirstPattern=p,p.id=o,p.setAttribute(`patternUnits`,`userSpaceOnUse`),p.setAttribute(`patternTransform`,`rotate(-30)`),p.setAttribute(`width`,`${this._svgFirstPatternWidth}`),p.setAttribute(`height`,`${this._svgFirstPatternHeight}`);let m=document.createElementNS(`http://www.w3.org/2000/svg`,`use`);m.setAttribute(`href`,`#${this._svgTextDefElement.id}`),p.appendChild(m);let h=document.createElementNS(`http://www.w3.org/2000/svg`,`pattern`);this._svgSecondPattern=h,h.id=s,h.setAttribute(`patternUnits`,`userSpaceOnUse`),h.setAttribute(`patternTransform`,`rotate(-30)`),h.setAttribute(`width`,`${this._svgSecondPatternWidth}`),h.setAttribute(`height`,`${this._svgSecondPatternHeight}`),h.setAttribute(`x`,`${this._svgSecondPatternOffsetX}`),h.setAttribute(`y`,`${this._svgSecondPatternOffsetY}`);let g=m.cloneNode(!0);h.appendChild(g),l.appendChild(u),l.appendChild(d),l.appendChild(p),l.appendChild(h);let _=this._getRect(0,0,100,100,o),v=this._getRect(0,0,100,100,s);return n.appendChild(l),n.appendChild(_),n.appendChild(v),this._updateWatermarkPatternScalingTiled(this._container.getBoundingClientRect().width,this._container.getBoundingClientRect().height),n}_getWatermarkContainer(e){let t=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);return this._addStyleAttributesToSvgElement(t,this.WATERMARK_CONTAINER_STYLES),t.setAttribute(`xmlns`,`http://www.w3.org/2000/svg`),t}_getSvgFilter(e,t){let n=document.createElementNS(`http://www.w3.org/2000/svg`,`filter`);n.id=e;let r=document.createElementNS(`http://www.w3.org/2000/svg`,`feDropShadow`);return r.setAttribute(`dx`,`0.5`),r.setAttribute(`dy`,`0.5`),r.setAttribute(`stdDeviation`,`1`),r.setAttribute(`flood-color`,`black`),r.setAttribute(`flood-opacity`,`${t}`),n.appendChild(r),n}_getRect(e,t,n,r,i){let a=document.createElementNS(`http://www.w3.org/2000/svg`,`rect`);return a.setAttribute(`x`,`${e}%`),a.setAttribute(`y`,`${t}%`),a.setAttribute(`width`,`${n}%`),a.setAttribute(`height`,`${r}%`),a.setAttribute(`fill`,`url(#${i})`),a}_getClampedUsername(){let e=``,t=this._call.callAgent,n=Z().calling.watermark,r=n.watermarkMaxUsernameLength,i=n.watermarkEmptyDisplayNamePlaceholder;if(t?.isEnterpriseUser()){let n=t.getUserProperties()?.sipUri;n&&typeof n==`string`&&(e=n.replace(`sip:`,``))}else e=t?.displayName??``,e||=i;return Swe(e,r)}_getSelectedWatermarkPattern(){return this._videoStream.mediaStreamType===`Video`&&this._watermarkCapability?.enabledForVideo&&this._watermarkCapability?.videoSettings?.pattern?this._watermarkCapability.videoSettings.pattern:this._videoStream.mediaStreamType===`ScreenSharing`&&this._watermarkCapability?.enabledForVbss&&this._watermarkCapability?.vbssSettings?.pattern?this._watermarkCapability.vbssSettings.pattern:``}_getWatermarkUsageTelemetryPayload(e=``){return{endpointSupportsWatermark:this._call.callAgent.isWatermarkSupported(),audioOnlyFallbackTriggered:this._call.watermarkAudioOnlyFallbackTriggered,audioOnlyFallbackTriggeredByViewId:e,watermarkUsage:{video:{enabled:this._watermarkCapability?.enabledForVideo,opacity:this._watermarkCapability?.videoSettings.opacity,pattern:this._watermarkCapability?.videoSettings.pattern},screenshare:{enabled:this._watermarkCapability?.enabledForVbss,opacity:this._watermarkCapability?.vbssSettings.opacity,pattern:this._watermarkCapability?.vbssSettings.pattern}},viewId:this._viewId}}},_7=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},v7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},UIe=1,y7=class{get isRendering(){return this._isRendering}get scalingMode(){return this._scalingMode}get isMirrored(){return this._isMirrored}get target(){return this._target}get viewId(){return this._viewId}get isDisposed(){return this._disposed}get retryErrorEvents(){return this._retryErrorEvents}get size(){return{height:this._size.height,width:this._size.width}}constructor(e,t,n,r,i,a,o){this._target=e,this._viewId=t,this._videoStream=n,this._onDisposedCallback=i,this._createViewSteps=a,this._eventEmitter=new w3.EventEmitter,this._isRendering=!1,this._scalingMode=`Stretch`,this._isMirrored=!1,this._createViewResolvedOnPlayEvent=!1,this._hasRenderingEvent=!1,this._hasPlayEvent=!1,this._size={height:0,width:0},this._disposed=!1,this.resolveRenderingPendingPromise=(e=!1)=>{this._renderingDeferred?.isPending()&&(this._renderingDeferred.resolve(),e&&(this.logger.log(`video element play event was fired and promise was resolved and isRendering is: ${this._tsRenderer?.isRendering}`),this._createViewResolvedOnPlayEvent=!0)),e?this._hasPlayEvent||(this._hasPlayEvent=!0,this._createViewSteps.isPlayedTimestamp=Date.now(),this._createViewSteps.isPlayedTimeDeltaSinceAttemptMs=this._createViewSteps.attemptTimestamp===void 0?0:this._createViewSteps.isPlayedTimestamp-this._createViewSteps.attemptTimestamp):!this._hasRenderingEvent&&this._isRendering&&(this._hasRenderingEvent=!0,this._createViewSteps.isRenderedTimestamp=Date.now(),this._createViewSteps.isRenderedTimeDeltaSinceAttemptMs=this._createViewSteps.attemptTimestamp===void 0?0:this._createViewSteps.isRenderedTimestamp-this._createViewSteps.attemptTimestamp)},this._handleTsRendererChanged=e=>{if(this.logger.debug(`rendering state is ${this._isRendering}, changed to ${this._tsRenderer?.isRendering}`),this._tsRenderer)if(this._tsRenderer.isRendering!==this._isRendering&&(this._isRendering=this._tsRenderer.isRendering,this._videoStream.updateIsReceiving(),this._isRendering&&this.resolveRenderingPendingPromise(),e.log(`isRendering change to ${this._isRendering}`)),this._tsRenderer.isRendering){let e=this._tsRenderer.streamSize?.height||u2.HEIGHT,t=this._tsRenderer.streamSize?.width||u2.WIDTH;e===this._size.height&&t===this._size.width||this.setAndUpdateSize(),this.resolveRenderingPendingPromise()}else this._size.height=0,this._size.width=0,this._videoStream.updateSize();this.sendRendererTelemetry()},this.sendRendererTelemetry=()=>{if(this._tsRenderer)try{let e={isRendering:this._tsRenderer.isRendering,streamWidth:this._tsRenderer.streamSize.width,streamHeight:this._tsRenderer.streamSize.height,isVideoAttached:this._target.isConnected,rendererWidth:this._target?.offsetWidth,rendererHeight:this._target?.offsetHeight};if(this.previousStats){if(Kwe(this.previousStats,e))return}else this.previousStats=e;this.previousStats=e;let{callId:t,localParticipantId:n,isDisposed:r,viewIdsRegistered:i,height:a,width:o,...s}=this._videoStream.getStreamMetadata(),c={...e,...s,viewId:this._viewId,disposed:this._disposed};this._videoStream.call.stats.recordEvent({name:s3.remote_view,callId:t,localParticipantId:n,data:c})}catch{}},this._unsubscribeAvailabilityCallback=()=>{this._availableCallback&&=(this._videoStream.kind===`RemoteVideoStream`&&this._videoStream?.off(`isAvailableChanged`,this._availableCallback),void 0)},this._disposeTsRendererChangedObservable=()=>{this._tsRendererChanged&&=(this._tsRendererChanged.dispose(),void 0)},this._attemptToDisposeTsRenderer=()=>{if(this._tsRenderer){this.logger.debug(`disposing underlying remote renderer`);try{this._tsRenderer?.dispose(),this._tsRenderer=void 0}catch(e){throw this.logger.warn(`underlying remote renderer dispose failed with ${e?.message} error`),new Y({defaultError:J.VIEW.REMOTE_RENDERER_DISPOSE_FAIL})}}},this.logger=r.createChild(`RemoteStreamRenderer`+ UIe++),this.logger.log(`created`),o?.scalingMode!==void 0&&(this._scalingMode=o.scalingMode),o?.isMirrored!==void 0&&(this._isMirrored=o.isMirrored),this._remoteStreamTelemetryEventSender=new V6(this._videoStream.telemetryLogManager),this._watermarkOverlayProvider=new HIe(this._target,this._videoStream,this._viewId,this.logger,this._remoteStreamTelemetryEventSender),this._watermarkOverlayProvider.attach(),this._retryErrorEvents=new Set([J.VIEW.TIMEOUT.subCode,J.VIEW.SUBSCRIBE.subCode])}async start(){let e=K0(),t=+new Date,n=this.logger.createFnLogger(m4.Start),r={timestampInfo:{attemptTimestamp:t},correlationId:e,operation:_3.render,kindOfEvent:$.attempt,mediaType:this._videoStream.mediaStreamType,streamType:g3.Remote};if(this._remoteStreamTelemetryEventSender.sendMediaStreamEvent(r),this._disposed)throw this.logger.warn(`already disposed`),new Y({defaultError:J.VIEW.START_ALREADY_DISPOSED});this._createViewTimeout&&=(clearTimeout(this._createViewTimeout),void 0);try{n.info(`scalingMode=${E4(this._scalingMode)}`),this._videoStream.registerRenderer(this),this._renderingDeferred=e3(),this._renderingDeferred.promise.catch(A4),this._videoStream.kind===`RemoteVideoStream`&&(this._availableCallback=()=>{this._videoStream.isAvailable||(n.warn(`stream isAvailable changed to false, attempting to reject operation`),this._renderingDeferred?.isPending()&&!this._disposed&&this._renderingDeferred?.reject(new Y({defaultError:J.VIEW.STREAM_BECAME_UNAVAILABLE})))},this._videoStream.on(`isAvailableChanged`,this._availableCallback)),this._createViewSteps.startSubscriptionTimestamp=Date.now(),this._createViewSteps.startSubscriptionTimeDeltaSinceAttemptMs=this._createViewSteps.attemptTimestamp===void 0?0:this._createViewSteps.startSubscriptionTimestamp-this._createViewSteps.attemptTimestamp,this._videoStream.tsStream.start(this._target,{scalingMode:E4(this._scalingMode),transparent:!1}).then((e=>{if(this._createViewSteps.rendererIsAvailableTimestamp=Date.now(),this._createViewSteps.rendererIsAvailableTimeDeltaSinceAttemptMs=this._createViewSteps.attemptTimestamp===void 0?0:this._createViewSteps.rendererIsAvailableTimestamp-this._createViewSteps.attemptTimestamp,this._isMirrored&&(this._target.style.transform=`rotateY(180deg)`,this._target.style.webkitTransform=`rotateY(180deg)`),this._tsRenderer=e,this.logger.info(`subscribed to video, waiting for the first frame`),this._disposed)throw this.logger.warn(`already disposed, dispose underlying renderer`),this._attemptToDisposeTsRenderer(),new Y({defaultError:J.VIEW.START_ALREADY_DISPOSED});if(this.logger.info(`current state of rendering is ${this._tsRenderer.isRendering}`),this.sendRendererTelemetry(),Z().rendering.remoteVideo.createViewTimeout!==-1&&(this._createViewTimeout=setTimeout((()=>{if(this._renderingDeferred?.isPending())try{this._renderingDeferred.reject(new Y({defaultError:J.VIEW.TIMEOUT})),this._createViewTimeout&&=(clearTimeout(this._createViewTimeout),void 0)}catch{}}),Z().rendering.remoteVideo.createViewTimeout)),Z().rendering.remoteVideo.speedupCreateViewWithPlayEvent){let e=this._target&&this._target.children.length>0&&this._target.children[0];e?e.addEventListener(`play`,this.videoPlayEventListener.bind(this)):this.logger.warn(`video element was not found while trying to listen to play event`)}this._tsRendererChanged=this._tsRenderer.changed((()=>this._handleTsRendererChanged(n))),this._tsRenderer.isRendering&&(this._isRendering=!0,this._videoStream.updateIsReceiving(),this.setAndUpdateSize(),this.resolveRenderingPendingPromise())})).catch((e=>{if(this.logger.info(`Failed to subscribe to video`),this._renderingDeferred?.isPending()){let t=new Y({defaultError:J.VIEW.SUBSCRIBE,originalError:e});this._renderingDeferred.reject(t)}})),await this._renderingDeferred.promise,this._videoStream.flushIsReceiving(),this._unsubscribeAvailabilityCallback(),Z().rendering.remoteVideo.forceCheckIfVideoWasAttachedToDom&&this._checkIfVideoWasAttachedToDom();let r={timestampInfo:{deltaTimeInMs:+new Date-t},correlationId:e,operation:_3.render,kindOfEvent:$.success,mediaType:this._videoStream.mediaStreamType,streamType:g3.Remote,createViewResolvedOnPlayEvent:this._createViewResolvedOnPlayEvent};return this._remoteStreamTelemetryEventSender.sendMediaStreamEvent(r),this}catch(n){this.logger.warn(`Failed to render, message=${n}`);try{this._retryErrorEvents.has(n?.subCode)||this.dispose()}catch(e){this.logger.warn(`dispose failed with ${e?.message} error`)}let r=new Y({defaultError:J.VIEW.START,originalError:n});if(r.message!==J.VIEW.LARGE_MEETING_VIEW_DISPOSED.message&&r.message!==J.VIEW.REMOTE_VIDEO_STREAM_DISPOSED.message){let n={timestampInfo:{deltaTimeInMs:+new Date-t},correlationId:e,operation:_3.render,additionalDetails:{failureReason:r.message,code:FG,...K3(r)},kindOfEvent:$.failure,mediaType:this._videoStream.mediaStreamType,streamType:g3.Remote,createViewResolvedOnPlayEvent:this._createViewResolvedOnPlayEvent};this._remoteStreamTelemetryEventSender.sendMediaStreamEvent(n)}throw r}}videoPlayEventListener(){this.logger.log(`video element play event was fired`),this.resolveRenderingPendingPromise(!0)}setAndUpdateSize(){try{this._size.width=this._tsRenderer?.streamSize.width||u2.WIDTH,this._size.height=this._tsRenderer?.streamSize.height||u2.HEIGHT,this._videoStream.updateSize()}catch(e){this.logger.error(`Failed to update video stream size with error ${e}`)}}async setScalingMode(e){if(!this._tsRenderer)throw new Y({defaultError:J.VIEW.SCALING_MODE});await this._tsRenderer.setScalingMode(E4(e)),this._scalingMode=e}_clearTimeouts(){this._checkIfVideoWasAttachedToDomTimeout&&=(clearTimeout(this._checkIfVideoWasAttachedToDomTimeout),void 0),this._createViewTimeout&&=(clearTimeout(this._createViewTimeout),void 0)}dispose(e=b3.Public_App){if(this._disposed)throw new Y({defaultError:J.VIEW.RENDERER_DISPOSE_ALREADY_DISPOSED});if(this._disposed=!0,this._disposeTsRendererChangedObservable(),this._unsubscribeAvailabilityCallback(),this._attemptToDisposeTsRenderer(),this._renderingDeferred?.isPending()){let t;switch(e){case b3.Internal_LargeMeetingVideoRendering:t=J.VIEW.LARGE_MEETING_VIEW_DISPOSED;break;case b3.Internal_RemoteVideoStreamDisposed:t=J.VIEW.REMOTE_VIDEO_STREAM_DISPOSED;break;default:t=J.VIEW.APP_VIEW_DISPOSED}this._renderingDeferred.reject(new Y({defaultError:t}))}if(this._target){let e=this._target.children&&this._target.children.length>0&&this._target.children[0];e&&e.removeEventListener(`play`,this.videoPlayEventListener),this._target.remove()}try{e!==b3.Public_App&&this._onDisposedCallback(e)}catch(e){this.logger.debug(`dispose callback failed with ${e?.message} error`)}this._watermarkOverlayProvider.dispose(),this._videoStream.unregisterRenderer(this),this._size.height=0,this._size.width=0,this._videoStream.updateSize(),this._isRendering=!1,this._videoStream.updateIsReceiving(),this._eventEmitter.removeAllListeners(),this._renderingDeferred=void 0,this._clearTimeouts()}_checkIfVideoWasAttachedToDom(){if(this._checkIfVideoWasAttachedToDomTimeout&&=(clearTimeout(this._checkIfVideoWasAttachedToDomTimeout),void 0),Z().rendering.remoteVideo.checkIfVideoAttachedToDom_poll){let e=Z().rendering.remoteVideo.checkIfVideoAttachedToDom_intervalMaxTries,t=()=>{this._target.isConnected||e<=0?this.sendRendererTelemetry():(e--,e>=0&&(this._checkIfVideoWasAttachedToDomTimeout=setTimeout((()=>t()),Z().rendering.remoteVideo.checkIfVideoAttachedToDom_intervalTime)))};t()}else this._checkIfVideoWasAttachedToDomTimeout=setTimeout((()=>{this._target.isConnected&&this.sendRendererTelemetry()}),Z().rendering.remoteVideo.checkIfVideoAttachedToDom_timeout)}};_7([zG,v7(`design:type`,Object)],y7.prototype,`logger`,void 0),_7([GG(m4.Start),v7(`design:type`,Function),v7(`design:paramtypes`,[]),v7(`design:returntype`,Promise)],y7.prototype,`start`,null),_7([WG(m4.Dispose),v7(`design:type`,Function),v7(`design:paramtypes`,[String]),v7(`design:returntype`,void 0)],y7.prototype,`dispose`,null);var b7=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},x7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},S7=class{get isRendering(){return this._isRendering}get scalingMode(){return this._scalingMode}get isMirrored(){return this._isMirrored}get target(){return this._target}get isDisposed(){return this._disposed}constructor(e,t,n,r,i){this._target=e,this._videoStream=t,this._onDisposed=r,this._eventEmitter=new w3.EventEmitter,this._isRendering=!1,this._scalingMode=`Stretch`,this._isMirrored=!0,this._disposed=!1,this.logger=n.createChild(`LocalStreamRenderer`),this.logger.log(`created`),i?.scalingMode!==void 0&&(this._scalingMode=i.scalingMode),i?.isMirrored===void 0?this._videoStream.mediaStreamType===`ScreenSharing`&&(this._isMirrored=!1):this._isMirrored=i.isMirrored,this._localStreamTelemetryEventSender=new V6(this._videoStream.telemetryLogManager)}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}async start(){let e=K0(),t=this.logger.createFnLogger(m4.Start),n=+new Date,r={timestampInfo:{attemptTimestamp:n},correlationId:e,operation:_3.render,kindOfEvent:$.attempt,mediaType:this._videoStream.mediaStreamType,streamType:g3.Local};this._localStreamTelemetryEventSender.sendMediaStreamEvent(r);try{if(t.info(`attempting to select new device as a source`),this._videoStream.source instanceof L6&&this._videoStream.mediaStreamType===`Video`){let e=this._videoStream.source.deviceManager.getTsDeviceManager();e.selectDevices({camera:this._videoStream.source.id}),t.info(`device selected`),t.info(`creating preview`),this._tsRenderer=await e.createPreview(this._target,{kind:`camera`},{scalingMode:E4(this._scalingMode),transparent:!1,ignoreMirroring:!1,disposeRendererWhenStreamisNotAvailable:()=>!0})}else{if(this._videoStream.mediaStreamType!==`RawMedia`&&this._videoStream.mediaStreamType!==`ScreenSharing`)throw new Y({defaultError:J.VIEW.UNKNOWN_STREAM_TYPE});{this._rawMediaOrSS_previewVideo=document.createElement(`video`),this._rawMediaOrSS_previewVideo.style.width=`100%`,this._rawMediaOrSS_previewVideo.style.height=`100%`,this._rawMediaOrSS_previewVideo.style.objectFit=`contain`,this._rawMediaOrSS_previewVideo.setAttribute(`playsinline`,`true`),this._rawMediaOrSS_previewVideo.disablePictureInPicture=!0,this._rawMediaOrSS_previewVideo.autoplay=!0;let e=await this._videoStream.getMediaStream(),t=new MediaStream(e.getVideoTracks());this._rawMediaOrSS_previewVideo.srcObject=t,this._rawMediaOrSS_previewVideo.play(),this._target.appendChild(this._rawMediaOrSS_previewVideo)}}this._isMirrored&&(this._target.style.transform=`rotateY(180deg)`,this._target.style.webkitTransform=`rotateY(180deg)`),this._videoStream.registerRenderer(this);let r={timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:e,operation:_3.render,kindOfEvent:$.success,mediaType:this._videoStream.mediaStreamType,streamType:g3.Local};return this._localStreamTelemetryEventSender.sendMediaStreamEvent(r),this}catch(r){this.dispose();let i=U3(t,r),a={timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:e,operation:_3.render,additionalDetails:{failureReason:i.message,code:i.code,subCode:i.subCode,...K3(i)},kindOfEvent:$.failure,mediaType:this._videoStream.mediaStreamType,streamType:g3.Local};throw this._localStreamTelemetryEventSender.sendMediaStreamEvent(a),i}}setScalingMode(e){if(this._tsRenderer)this._tsRenderer.setScalingMode(E4(e)),this._scalingMode=e;else{if(!this._rawMediaOrSS_previewVideo)throw new Y({defaultError:J.VIEW.SCALING_MODE});switch(e){case`Stretch`:this._rawMediaOrSS_previewVideo.style.objectFit=`fill`;break;case`Crop`:this._rawMediaOrSS_previewVideo.style.objectFit=`cover`;break;default:this._rawMediaOrSS_previewVideo.style.objectFit=`contain`}}}setSourceObject(e){this.disposeScreenSharingMediaStream();let t=this._target.querySelector(`video`);t&&(t.srcObject=e,t.play())}dispose(){if(!this._disposed){if(this._tsRenderer)try{this.logger.log(`disposing underlying local renderer`),this._tsRenderer.dispose(),this._tsRenderer=void 0}catch(e){throw this.logger.warn(`underlying local renderer dispose failed with ${e?.message} error`),new Y({defaultError:J.VIEW.LOCAL_RENDERER_DISPOSE_FAIL})}this.disposeScreenSharingMediaStream(),this._target.remove(),this._onDisposed&&this._onDisposed(this),this._eventEmitter.removeAllListeners(),this._disposed=!0}}disposeScreenSharingMediaStream(){if(this._videoStream.getCall()?.localScreenSharingStream){let e=this._target.querySelector(`video`),t=e?.srcObject;t&&(t.getVideoTracks().forEach((e=>{e.stop()})),e.srcObject=null,this.logger.info(`disposed of ScreenSharing MediaStream`))}}};b7([zG,x7(`design:type`,Object)],S7.prototype,`logger`,void 0),b7([GG(h4.Start),x7(`design:type`,Function),x7(`design:paramtypes`,[]),x7(`design:returntype`,Promise)],S7.prototype,`start`,null),b7([WG(h4.SetScalingMode),x7(`design:type`,Function),x7(`design:paramtypes`,[String]),x7(`design:returntype`,void 0)],S7.prototype,`setScalingMode`,null),b7([WG(h4.SetSourceObject),x7(`design:type`,Function),x7(`design:paramtypes`,[MediaStream]),x7(`design:returntype`,void 0)],S7.prototype,`setSourceObject`,null),b7([WG(h4.Dispose),x7(`design:type`,Function),x7(`design:paramtypes`,[]),x7(`design:returntype`,void 0)],S7.prototype,`dispose`,null);var C7=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},w7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},WIe=1,T7=class e{get scalingMode(){return this._streamRenderer.scalingMode}get isMirrored(){return this._streamRenderer.isMirrored}get disposed(){return this._disposed}constructor(e,t,n,r,i){if(this._videoStream=e,this._viewId=n,this._options=i,this._disposed=!1,this._isRetryErrorSubCode=e=>`retryErrorEvents`in this._streamRenderer&&this._streamRenderer.retryErrorEvents.has(e.subCode),this._deleteActiveRemoteVideoStreamView=(e,t)=>{if(e.call.activeRemoteVideoStreamViews?.has(e.id)){let n=e.call.activeRemoteVideoStreamViews?.get(e.id);n?.delete(t),n?.size==0&&e.call.activeRemoteVideoStreamViews?.delete(e.id)}},this.logger=t.createChild(`VideoStreamRendererView`+ WIe++),this.target=document.createElement(`div`),this.target.style.width=`100%`,this.target.style.height=`100%`,this._videoStream instanceof g8)this._streamRenderer=new y7(this.target,this._viewId,this._videoStream,this.logger,(e=>{this._disposed||this.dispose(e)}),r,this._options);else{if(!(this._videoStream instanceof J6))throw new Y({defaultError:J.VIEW.VIEW_WRONG_STREAM_TYPE});this._streamRenderer=new S7(this.target,this._videoStream,this.logger,(()=>this.dispose),this._options)}this._telemetryLogManager=this._videoStream.telemetryLogManager,this.logger.info(`created`)}async render(){let e=this.logger.createFnLogger(this._videoStream instanceof g8?u4.RenderRemoteStream:u4.RenderLocalStream);if(this._disposed)throw e.log(`failed, stream disposed!`),new Y({defaultError:J.VIEW.RENDER_FAIL_STREAM_DISPOSED});let t=Z().rendering.remoteVideo.maxRendererRetries,n=1,r=(e,t)=>e().catch((i=>{if(t>0&&this._isRetryErrorSubCode(i))return n+=1,r(e,t-1);throw this._streamRenderer.isDisposed||this._streamRenderer.dispose(),i})),i=()=>this._streamRenderer.start();try{await r(i,t-1)}catch(t){throw e.error(`Failed to render stream ${this._viewId} after ${n} retries.`),this._isRetryErrorSubCode(t)&&n>1&&(t.message+=`\nFailed to render stream ${this._viewId} after ${n} retries.`),t}return n}async updateScalingMode(e){if(this._disposed)throw new Y({defaultError:J.VIEW.SCALING_MODE_DISPOSED});if(e!==`Crop`&&e!==`Fit`&&e!==`Stretch`)throw new Y({defaultError:J.VIEW.SCALING_MODE_WRONG_VAL});try{await this._streamRenderer.setScalingMode(e)}catch(e){throw new Y({defaultError:J.VIEW.SCALING_MODE,originalError:e})}}dispose(t=b3.Public_App){if(this._disposed)throw new Y({defaultError:J.VIEW.VIEW_ALREADY_DISPOSED});this._disposed=!0;let n=+new Date,r=K0();try{t===b3.Public_App&&this.sendDisposeViewEvent({eventName:Q.acs_calling_dispose_view_attempt,correlationId:r,timestampInfo:{attemptTimestamp:n}}),this.logger.debug(`attempt to dispose stream renderer`),this._streamRenderer.dispose(t),this.target?.remove(),this._videoStream instanceof a7&&(this._deleteActiveRemoteVideoStreamView(this._videoStream,this._viewId),Z()?.rendering.remoteVideo.decrementOvcOnRemoteSsRendering&&this._videoStream.mediaStreamType===`ScreenSharing`&&(e.remoteScreenSharingViews.delete(this._viewId),e.remoteScreenSharingViews.size<=0&&this._videoStream.call.setIsRenderingRemoteScreenShare(!1)));let i=+new Date;t===b3.Public_App&&this.sendDisposeViewEvent({eventName:Q.acs_calling_dispose_view_success,correlationId:r,timestampInfo:{deltaTimeInMs:i-n}})}catch(e){let i=new Y({defaultError:J.VIEW.DISPOSE_FAIL,originalError:e});if(t===b3.Public_App){let e=+new Date;this.sendDisposeViewEvent({eventName:Q.acs_calling_dispose_view_failure,correlationId:r,timestampInfo:{deltaTimeInMS:e-n}},i)}throw i}}sendDisposeViewEvent(e,t){try{let n,r;t&&(n=typeof t?.message==`string`?t?.message:``,r={...K3(t)}),this._telemetryLogManager.sendEvent({name:e.eventName,tenant:d2,properties:{...this._videoStream.getStreamMetadata(),viewId:this._viewId,correlationId:e.correlationId,timestampInfo:e.timestampInfo,failureReason:n,additionalDetails:r}})}catch{this.logger.debug(`Unable to send telemtery`)}}};T7.remoteScreenSharingViews=new Map,C7([zG,w7(`design:type`,Object)],T7.prototype,`logger`,void 0),C7([GG(u4.Render),w7(`design:type`,Function),w7(`design:paramtypes`,[]),w7(`design:returntype`,Promise)],T7.prototype,`render`,null),C7([GG(u4.UpdateScalingMode),w7(`design:type`,Function),w7(`design:paramtypes`,[String]),w7(`design:returntype`,Promise)],T7.prototype,`updateScalingMode`,null),C7([WG(u4.Dispose),w7(`design:type`,Function),w7(`design:paramtypes`,[String]),w7(`design:returntype`,void 0)],T7.prototype,`dispose`,null);var GIe=V5();function KIe(e,t,n,r){let i=[`audioBitrate`,`videoBitrate`,`downloadBitrate`,`bufferLengthInMs`,`videoHeight`,`videoWidth`,`currentPlayPosition`],a=t[n.toString()];a!==void 0&&i.forEach((t=>{let n=t,i=t;if(a[n]!==void 0){let t=a[n];e[i]===void 0?e[i]=[t]:(e[i]?.length>=r&&e[i]?.shift(),e[i]?.push(t))}}))}var qIe=class{get createViewStats(){return this._createViewStats}get initialCreateViewStats(){return this._initialCreateViewStats}constructor(e,t,n,r,i){this._statsCollector=e,this._streamId=t,this._logger=n,this._call=r,this._attemptTimestamp=i,this._createViewFailureStats={},this._createViewStats={},this._initialCreateViewStats={},this._statsCollector.on(`sampleReported`,(e=>{vke(this.createViewStats,this.initialCreateViewStats,e,this._streamId)}))}getCreateViewFailureStats(){try{let e=0,t=NaN;this.createViewStats.video?.framesDropped!==void 0&&this.initialCreateViewStats.video?.framesDropped!==void 0&&(e=this.createViewStats.video?.framesDropped.length,t=this.createViewStats.video?.framesDropped[e-1]-this.initialCreateViewStats.video?.framesDropped[0]);let n=NaN;this.createViewStats.video?.framesReceived!==void 0&&this.initialCreateViewStats.video?.framesReceived!==void 0&&(e=this.createViewStats.video.framesReceived.length,n=this.createViewStats.video.framesReceived[e-1]-this.initialCreateViewStats.video?.framesReceived[0]);let r=NaN;this.createViewStats.video?.framesDecoded!==void 0&&this.initialCreateViewStats.video?.framesDecoded!==void 0&&(e=this.createViewStats.video.framesDecoded.length,r=this.createViewStats.video.framesDecoded[e-1]-this.initialCreateViewStats.video?.framesDecoded[0]);let i=NaN;this.createViewStats.video?.keyFramesDecoded!==void 0&&this.initialCreateViewStats.video?.keyFramesDecoded!==void 0&&(e=this.createViewStats.video.keyFramesDecoded.length,i=this.createViewStats.video.keyFramesDecoded[e-1]-this.initialCreateViewStats.video?.keyFramesDecoded[0]);let a=0;!isNaN(t)&&n>0&&(a=Number((t/n*100).toFixed(7)));let o=!1;n>0&&r===0&&(o=!0);let s=!1;!isNaN(r)&&!isNaN(i)&&r>0&&r===i&&(s=!0);let c=[],l=this._call.networkQualityUfdEventDetails,u=Z().rendering.remoteVideo.createViewFailureNetworkUfdCheckWindowInMs;l.forEach((e=>{Math.abs(e.timestampInfo-this._attemptTimestamp)<=u&&c.push(e)}));let d=n===0;this._createViewFailureStats.video={framesDroppedPercentage:a,framesReceivedButNothingDecoded:o,onlyKeyFramesDecoded:s,networkQualityEventsDuringAttempt:c,zeroFramesReceived:d}}catch{this._logger.debug(`Error calculating create view failure stats!`)}return this._createViewFailureStats}},JIe=class{constructor(e,t){this._liveStreamStatsCollector=e,this._streamId=t,this._liveStreamStats={},this._initialLiveStreamStats={};let n=Z()?.rendering.remoteVideo.createViewSendMediaStatsMaxLength;this._liveStreamStatsCollector.on(`sampleReported`,(e=>{KIe(this._liveStreamStats,e,this._streamId,n),Q2.isEmpty(this._initialLiveStreamStats)&&(this._initialLiveStreamStats=this._liveStreamStats)}))}get initialCreateViewLiveStreamStats(){return this._initialLiveStreamStats}get createViewLiveStreamStats(){return this._liveStreamStats}},E7=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},D7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},O7=class{get _createViewStats(){return this._videoStream.kind!==`RemoteVideoStream`&&this._videoStream.kind!==`ComposedVideoStream`||!this._createViewTelemetryHelper?this._videoStream.kind===`LiveVideoStream`&&this._createViewLiveStreamTelemetryHelper?this._createViewLiveStreamTelemetryHelper.createViewLiveStreamStats:{}:this._createViewTelemetryHelper.createViewStats}constructor(e){if(this.size={height:0,width:0},this.views=new Map,this.disposed=!1,this._attemptToDisposeView=e=>{try{e?.dispose()}catch(e){this.logger.warn(e?.message||`Failed to dispose, unknown error`)}},this._addActiveRemoteVideoStreamView=(e,t,n)=>{if(e.call.activeRemoteVideoStreamViews?.has(e.id)){let r=e.call.activeRemoteVideoStreamViews?.get(e.id);r&&r.set(t,n)}else{let r=new Map;r.set(t,n),e.call.activeRemoteVideoStreamViews?.set(e.id,r)}},!(e instanceof J6||e instanceof g8||e instanceof a7))throw new Y({defaultError:J.VIEW.RENDERER_WRONG_STREAM_TYPE});let t=KW(`ACS`);this._videoStream=e,this._telemetryLogManager=e.telemetryLogManager,this.logger=new z6(t,e instanceof J6?[()=>`VideoStreamRenderer:LocalVideoStream:${GIe.pii.Omit(e?.source?.id)}`]:[()=>`VideoStreamRenderer:${e.kind}:${e?.id}`]),this.logger.info(`created`)}async createView(e){if(this.disposed)throw new Y({defaultError:J.VIEW.RENDERER_DISPOSED});let t={},n=+new Date,r=K0(),i=K0(),a,o;try{let s=1;if(t.attemptTimestamp=n,this.sendCreateViewEvent({eventName:Q.acs_calling_create_view_attempt,viewId:r,correlationId:i,timestampInfo:{attemptTimestamp:n},isMirrored:e?.isMirrored,scalingMode:e?.scalingMode,stepsInfo:t}),this._videoStream.kind===`RemoteVideoStream`&&!this._videoStream.isAvailable)throw new Y({defaultError:J.VIEW.ISAVAILABLE_FALSE});let c=Z(),l=w4();if(this._videoStream.kind===`RemoteVideoStream`&&this._videoStream.mediaStreamType!==`ScreenSharing`&&c?.calling.applyViewLimit&&l?.numVideoChannelsGvc){let e=l?.numVideoChannelsGvc,t=this._videoStream;if(!t.call.activeRemoteVideoStreamViews?.has(t.id)&&t.call.activeRemoteVideoStreamViews?.size>=e)throw new Y({defaultError:J.VIEW.MAX_NUM_OF_VIEWS_REACHED,defaultErrorMessageArgs:[e]})}if(c?.rendering.remoteVideo.createViewSendMediaStats){if(this._videoStream.kind===`RemoteVideoStream`||this._videoStream.kind===`ComposedVideoStream`){let e=this._videoStream,t=e.call;o=e.call.feature(Z5.MediaStats).createCollector();let r=e.id;this._createViewTelemetryHelper=new qIe(o,r,this.logger,t,n)}else if(this._videoStream.kind===`LiveVideoStream`){let e=this._videoStream;o=e.call.feature(Z5.LiveStream).createStatsCollector();let t=e.id;this._createViewLiveStreamTelemetryHelper=new JIe(o,t)}}a=new T7(this._videoStream,this.logger,r,t,e),this.views.set(r,a),s=await a.render(),this._videoStream.kind===`RemoteVideoStream`&&this._videoStream.mediaStreamType!==`ScreenSharing`&&this._addActiveRemoteVideoStreamView(this._videoStream,r,a),this._videoStream.kind===`RemoteVideoStream`&&this._videoStream.mediaStreamType===`ScreenSharing`&&c?.rendering.remoteVideo.decrementOvcOnRemoteSsRendering&&(this._videoStream.call.setIsRenderingRemoteScreenShare(!0),T7.remoteScreenSharingViews.set(r,a));let u=+new Date;return this.sendCreateViewEvent({eventName:Q.acs_calling_create_view_success,viewId:r,correlationId:i,timestampInfo:{deltaTimeInMs:u-n},additionalProperties:{isRetry:!!s&&s>1,attemptNumber:s},stepsInfo:t}),a}catch(e){let o=new Y({defaultError:J.VIEW.CREATE_VIEW_FAILED,originalError:e});if(this.views.delete(r),this._attemptToDisposeView(a),o.message!==J.VIEW.LARGE_MEETING_VIEW_DISPOSED.message&&o.message!==J.VIEW.REMOTE_VIDEO_STREAM_DISPOSED.message){let e=Date.now();this.sendCreateViewEvent({eventName:Q.acs_calling_create_view_failure,viewId:r,correlationId:i,timestampInfo:{deltaTimeInMs:e-n},stepsInfo:t},o)}throw o}finally{o?.dispose()}}async sendCreateViewEvent(e,t){try{let n={},r={},i={};if(Z()?.rendering.remoteVideo.createViewSendMediaStats&&(e.eventName===Q.acs_calling_create_view_failure||e.eventName===Q.acs_calling_create_view_success)){if(this._videoStream.kind===`RemoteVideoStream`){let t=this._videoStream.call,r=await t.tsCall.getMediaSessionStatsAsync?.();n={isRetry:e.additionalProperties?.isRetry??!1,attemptNumber:e.additionalProperties?.attemptNumber??1,videoSubscriptionEvents:r?.extensions?.Video_SubscriptionEvents,screenSharingSubscriptionEvents:r?.extensions?.Sharing_SubscriptionEvents,videoSendMaxCapabilities:r?.extensions?.Video_send_MaxCapabilities,screenSharingSendMaxCapabilities:r?.extensions?.Sharing_send_MaxCapabilities,iceConnectedStateTime:r?.metrics?.IceConnectedStateTime,relayCandidate:r?.extensions?.RelayCandidate,videoRecvTimeToFirstFrame:r?.extensions?.Video_recv_TimeToFirstFrame,screenSharingRecvTimeToFirstFrame:r?.extensions?.Sharing_recv_TimeToFirstFrame,optimalVideoCount:t.tsCall.optimalVideoCount||1,currentNumberOfVideosRendered:t.activeRemoteVideoStreamViews?.size||0}}e.eventName===Q.acs_calling_create_view_failure&&(i=this._createViewTelemetryHelper?.getCreateViewFailureStats()??{},r=this._createViewStats)}n.visibilityState=document.visibilityState,e.isMirrored!==void 0&&(n.isMirrored=e.isMirrored),e.scalingMode!==void 0&&(n.scalingMode=e.scalingMode),e.eventName!==Q.acs_calling_create_view_failure&&e.eventName!==Q.acs_calling_create_view_success||this._videoStream.kind!==`RemoteVideoStream`&&this._videoStream.kind!==`ComposedVideoStream`||Q2.forOwn(e.stepsInfo,((e,t)=>{e!==void 0&&(n[t]=e)}));let a=``,o={};t&&(a=typeof t?.message==`string`?t?.message:``,o={...K3(t)}),this._telemetryLogManager.sendEvent({name:e.eventName,tenant:d2,properties:{viewId:e.viewId,correlationId:e.correlationId,timestampInfo:e.timestampInfo,...this._videoStream.getStreamMetadata(),failureReason:a,additionalProperties:n,additionalDetails:o,stats:r,createViewFailureDebugStats:i,videoStreamKind:this._videoStream.kind}})}catch{this.logger.debug(`Unable to send telemtery`)}}dispose(){if(this.disposed)throw new Y({defaultError:J.VIEW.RENDERER_ALREADY_DISPOSED});this.disposed=!0,this.views.forEach(this._attemptToDisposeView),this.views.clear()}};E7([zG,D7(`design:type`,Object)],O7.prototype,`logger`,void 0),E7([GG(d4.CreateView),D7(`design:type`,Function),D7(`design:paramtypes`,[Object]),D7(`design:returntype`,Promise)],O7.prototype,`createView`,null),E7([WG(d4.Dispose),D7(`design:type`,Function),D7(`design:paramtypes`,[]),D7(`design:returntype`,void 0)],O7.prototype,`dispose`,null);var YIe=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},k7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},A7=class{get identifier(){return this._identifier}get endpointDetails(){return this._tsParticipant?.endpoints?.endpointDetails.map((e=>({participantId:e.participantId,deviceType:e.deviceType,clientEndpointCapabilities:e.clientEndpointCapabilities,endpointMetadata:e.endpointMetadata})))||[]}get state(){return this._state}get videoStreams(){return[...this._mappedStreams.values()]}get isMuted(){return this._isMuted}get isSpeaking(){return this._isSpeaking}get callEndReason(){return this._callEndReason}get displayName(){return this._displayName}get hasDisplayNameChanged(){return this._hasDisplayNameChanged}get role(){return this._role}constructor(e,t,n,r,i){this._mappedStreams=new Map,this._state=`Idle`,this._lastTsParticipantState=0,this._isMuted=!1,this._isSpeaking=!1,this._displayName=``,this._realDisplayName=``,this._hasDisplayNameChanged=!1,this._role=`Unknown`,this.acsToTsStreamType=e=>e===`Video`?0:e===`ScreenSharing`?1:void 0,this.getParticipantDisplayNameOverride=()=>this._tsParticipant?.propertyBag?.displayNameOverride?.value?.displayNameOverrideValue,this._identifier=e,this.logger=t.createChild((()=>`RemoteParticipant{${this._identifier.kind}}`)),this._telemetryLogManager=i,this._eventEmitter=new S6(this.logger),this._callAgent=r,this._call=n,this.logger.log(`created`),this._renderers={Video:{renderingState:{}},ScreenSharing:{renderingState:{}}}}on(e,t){if(e!==`stateChanged`&&e!==`isMutedChanged`&&e!==`isSpeakingChanged`&&e!==`displayNameChanged`&&e!==`roleChanged`&&e!==`videoStreamsUpdated`)throw new Y({defaultError:J.REMOTE_PARTICIPANT.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if(e!==`stateChanged`&&e!==`isMutedChanged`&&e!==`isSpeakingChanged`&&e!==`displayNameChanged`&&e!==`roleChanged`&&e!==`videoStreamsUpdated`)throw new Y({defaultError:J.REMOTE_PARTICIPANT.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}async mute(){let e=Z();if(!e.calling.enableMuteOthers)throw new Y({defaultError:J.REMOTE_PARTICIPANT.MUTE_PARTICIPANT_DISABLED});if(!this._call.tsCall.conversationType&&this._call.callInfo.context===v4.TwoParty)throw new Y({defaultError:J.REMOTE_PARTICIPANT.MUTE_PARTICIPANT_1_TO_1_UNSUPPORTED});if(![`Connected`,`Hold`].some((e=>e===this._state)))throw new Y({defaultError:J.REMOTE_PARTICIPANT.MUTE_PARTICIPANT_NONCONNECTED_UNSUPPORTED});let t=this.logger.createFnLogger(s4.Mute),n=+new Date,r=K0();if(this.sendAudioEvent({eventName:Q.acs_calling_mute_attempt,eventType:l3.MuteSpecificParticipant,timestampInfo:{attemptTimestamp:n},correlationId:r,step:`mid-call`}),!e.calling.allowMutePstnRemoteParticipant&&this._identifier.kind===`phoneNumber`){let e=+new Date,i=J.REMOTE_PARTICIPANT.MUTE_PARTICIPANT_PSTN_UNSUPPORTED;t.warn(i.message);let a=new Y({defaultError:i});throw this.sendAudioEvent({eventName:Q.acs_calling_mute_failure,eventType:l3.MuteSpecificParticipant,timestampInfo:{deltaTimeInMs:e-n},correlationId:r,step:`mid-call`},a),a}try{t.info(`remote mute specific`),this._tsParticipant===void 0?t.warn(`no participant to mute in attempt to mute specific remote participant`):await this._call.tsCall.muteParticipants(1,[this._tsParticipant]),t.info(`remote mute specific success`);let e=+new Date;this.sendAudioEvent({eventName:Q.acs_calling_mute_success,eventType:l3.MuteSpecificParticipant,timestampInfo:{deltaTimeInMs:e-n},correlationId:r,step:`mid-call`})}catch(e){let i=new Y({defaultError:J.REMOTE_PARTICIPANT.MUTE_PARTICIPANT_FAILED,originalError:e});t.error(i.message);let a=+new Date;throw this.sendAudioEvent({eventName:Q.acs_calling_mute_failure,eventType:l3.MuteSpecificParticipant,timestampInfo:{deltaTimeInMs:a-n},correlationId:r,step:`mid-call`},i),i}}_dispose(){this.logger.log(`dispose`),this._participantChangedHandler&&this._participantChangedHandler.dispose(),this._mappedStreams.forEach((e=>e.dispose())),this._eventEmitter.emit(`stateChanged`,this._state),this._eventEmitter.removeAllListeners(),this._disposeVideo(0),this._disposeVideo(1)}get tsRemoteParticipant(){return this._tsParticipant}get kind(){return`RemoteParticipant`}setCallEndReason(e){this._callEndReason=e}observeParticipant(e){if(this._tsParticipant)return;let t=Z();this._tsParticipant=e,this._displayName=e.displayName,this._realDisplayName=e.displayName,this._isMuted=e.isServerMuted;let n=this.getParticipantDisplayNameOverride();t.calling.rename.enableShowEditedDisplayName&&n&&n!==this._displayName&&(this._displayName=n,this._hasDisplayNameChanged=!0),this._participantChangedHandler=this._tsParticipant.changed((()=>{this._tsParticipant&&this._tsParticipant.state!==this._lastTsParticipantState&&(this._lastTsParticipantState=this._tsParticipant.state,this._mapTsParticipantState(this._tsParticipant.state)),this._mapStreams(),this._tsParticipant&&this._tsParticipant.isServerMuted!==this._isMuted&&(this._isMuted=this._tsParticipant.isServerMuted,this._eventEmitter.emit(`isMutedChanged`));let n=this.getParticipantDisplayNameOverride();if(t.calling.rename.enableShowEditedDisplayName&&n&&n!==this._displayName){let e=K0(),t=this._displayName;this._displayName=n,this._hasDisplayNameChanged=n!==this._realDisplayName,this.logger.log(`display name changed ${t}=>${n}, correlationId=${e}`),this._eventEmitter.emit(`displayNameChanged`,{newValue:this._displayName,oldValue:t,reason:`editedDisplayName`}),this.sendDisplayNameOverrideEvent(e)}else if((!n||!t.calling.rename.enableShowEditedDisplayName)&&this._tsParticipant?.displayName&&this._tsParticipant.displayName!==this._displayName){let t=this._displayName;this._displayName=e.displayName,this._realDisplayName=e.displayName,this._eventEmitter.emit(`displayNameChanged`,{newValue:this._displayName,oldValue:t})}if(this._tsParticipant&&this._tsParticipant.advancedMeetingRole!==this._lastTsParticipantAdvancedRole&&(this._lastTsParticipantAdvancedRole=e.advancedMeetingRole,this._setParticipantRole(this._tsParticipant.advancedMeetingRole)),this._tsParticipant){let e=this._tsParticipant.voiceLevel!==0;e!==this._isSpeaking&&(this._isSpeaking=e,this._eventEmitter.emit(`isSpeakingChanged`))}})),this._mapTsParticipantState(this._tsParticipant.state),this._mapStreams(),this._lastTsParticipantAdvancedRole=this._tsParticipant.advancedMeetingRole,this._setParticipantRole(this._tsParticipant.advancedMeetingRole),this._displayName||!CG(this._identifier)&&!SG(this._identifier)||this.getRemoteParticipantProperties().then((e=>{e?.displayName&&(this._displayName=e.displayName,this._eventEmitter.emit(`displayNameChanged`))})).catch((e=>{this.logger.error(`Failed to get remote participant properties: ${e}`)}))}setParticipantState(e){e!==this._state&&(this.logger.log(`state changed ${this._state}=>${this.state}`),this._state=e,this._state==`Disconnected`?this._dispose():this._eventEmitter.emit(`stateChanged`,this._state))}async stopRenderingVideo(){this._disposeVideo(0)}async renderVideo(e,t){return typeof e==`function`?this._updateRenderingState(e,`Video`,t):await this._renderStreamForParticipant(e,0,t)}async _updateRenderingState(e,t,n){if(typeof e==`function`){let r,i=t===`Video`?0:1;this._tsParticipant&&(r=n?.stream?n.stream:new a7(this._tsParticipant.streams[i][0],this.logger,this._call,this._callAgent,this._tsParticipant,this._telemetryLogManager,this._identifier),r.on(`isReceivingChanged`,(()=>{this._renderers[t].renderingState.isFrozen=!r.isReceiving,e(this._renderers[t].renderingState)})),r.on(`isAvailableChanged`,(async()=>{this._renderers[t].renderingState.isStreaming!==r?.isAvailable&&(this._renderers[t].renderingState.isStreaming=r.isAvailable,this._renderers[t].renderingState.isStreaming&&!this._renderers[t].renderer&&(this._renderers[t].renderer=this._renderers[t]?.renderer?this._renderers[t].renderer:new O7(r),this._renderers[t].view||(this._renderers[t].view=await this._renderers[t].renderer?.createView(n?.viewOptions)),this._renderers[t].renderingState.videoTarget=this._renderers[t].view?.target)),e(this._renderers[t].renderingState)})))}}async renderScreenShare(e,t){return typeof e==`function`?this._updateRenderingState(e,`ScreenSharing`,t):this._renderStreamForParticipant(e,1,t)}async _renderStreamForParticipant(e,t,n){if(this._tsParticipant){let r=t===0?`Video`:`ScreenSharing`,i=n?.stream?n.stream:new a7(this._tsParticipant.streams[t][0],this.logger,this._call,this._callAgent,this._tsParticipant,this._telemetryLogManager,this._identifier);return i.isAvailable&&(this._renderers[r].view=await this._appendVideo(e,t,i,n?.viewOptions)),i.on(`isAvailableChanged`,(async()=>{i.isAvailable?this._renderers[r].view=await this._appendVideo(e,t,i,n?.viewOptions):this._renderers[r]?.view&&this._renderers[r].view?.target&&this._renderers[r].view?.target.parentNode?.removeChild(this._renderers[r].view?.target)})),Promise.resolve({stream:i,view:this._renderers[r]?.view})}return Promise.reject()}async _appendVideo(e,t,n,r){try{let i=t===0?`Video`:`ScreenSharing`;if(t===0&&(this._renderers[i]?.renderer||(this._renderers[i].renderer=this._renderers[i]?.renderer?this._renderers[i].renderer:new O7(n),this._renderers[i].view=await this._renderers[i].renderer?.createView(r)),this._renderers[i].view))return e.appendChild(this._renderers[i].view?.target||document.createElement(`emptyNode`)),Promise.resolve(this._renderers[i].view)}catch(e){return Promise.reject(e)}return Promise.reject()}async _disposeVideo(e){let t=e===0?`Video`:`ScreenSharing`;this._renderers[t].view?.dispose(),this._renderers[t].renderer?.dispose(),this._renderers[t]={renderingState:{}}}_setParticipantRole(e){let t=iTe(Z(),e);t===`Unknown`?this.logger.log(`tsParticipant advancedMeetingRole=${e} had no mapping`):this.logger.log(`mapped tsParticipant advancedMeetingRole=${e}=>${t}`),this._role!=t&&(this.logger.log(`role changed ${this._role}=>${e}`),this._role=t,this._eventEmitter.emit(`roleChanged`))}_mapTsParticipantState(e){let t,n={0:`Idle`,1:`Connecting`,2:`Ringing`,3:`Connected`,4:`Disconnected`,5:`Hold`,7:`InLobby`,6:`EarlyMedia`};n[e]?(t=n[e],this.logger.log(`mapped tsParticipant ${e}=>${this._state}`),this.setParticipantState(t)):this.logger.log(`unable to map tsCall state=${e} to call state`)}_mapStreams(){let e=[],t=[],n=e=>{this._mappedStreams.set(e.id,e)},r=e=>{let t=this._mappedStreams.get(e.id);t&&(this.logger.log(`stream removed, type==${t.mediaStreamType} id=${e.id}`),this._mappedStreams.delete(e.id),t.dispose())},i=n=>{if(this._tsParticipant)if(this._tsParticipant.streams&&ywe(this._tsParticipant.streams[n])){let r=[];this._tsParticipant&&(r=this._tsParticipant.streams[n]),r.forEach((t=>{if(!this._mappedStreams.get(t.id)){let n=new a7(t,this.logger,this._call,this._callAgent,this._tsParticipant,this._telemetryLogManager,this._identifier);this.logger.log(`stream created, type==${n.mediaStreamType} id=${t.id}`),e.push(n)}})),this._mappedStreams.forEach((e=>{this.acsToTsStreamType(e.mediaStreamType)===n&&(r.some((t=>t.id===e.id))||t.push(e))}))}else this._mappedStreams.forEach((e=>{this.acsToTsStreamType(e.mediaStreamType)===n&&t.push(e)}))};i(0),i(1),(e.length>0||t.length>0)&&(e.forEach(n),t.forEach(r),this._eventEmitter.emit(`videoStreamsUpdated`,{added:e,removed:t}))}sendAudioEvent(e,t){try{let n,r;t&&(n=t.message,r=K3(t));let i={callId:this._call.id,timestampInfo:e.timestampInfo,correlationId:e.correlationId,step:e.step||``,failureReason:n||``,additionalDetails:{...r}};e.eventType!==void 0&&(i.eventType=e.eventType),this._telemetryLogManager.sendEvent({name:e.eventName,tenant:d2,properties:i})}catch{this.logger.debug(`Unable to send mute others audio telemetry`)}}sendDisplayNameOverrideEvent(e){if(this._telemetryLogManager)try{let t={callId:this._call.id,timestampInfo:{attemptTimestamp:+new Date},correlationId:e,step:`event`};this._telemetryLogManager.sendEvent({name:Q.acs_calling_edited_display_name,tenant:d2,properties:t})}catch{this.logger.debug(`Unable to send display name override event telemetry`)}}getRemoteParticipantProperties(){return new Promise((e=>{let t={policyUrlSuffix:Z().MiddleTier.policyUrlSuffixV2,userPolicies:[`TeamsMeetingPolicy`],userProperties:[`displayName`]};this._callAgent.mtPolicyService.requestUserPoliciesFromAcsMiddleTier(this._call.id,W2(this.identifier),t,this._callAgent.getUserMri()).then((t=>{e(t.userAggregatedPolicySettingData?.userProperties)}))}))}};YIe([zG,k7(`design:type`,Object)],A7.prototype,`logger`,void 0),YIe([GG(s4.Mute),k7(`design:type`,Function),k7(`design:paramtypes`,[]),k7(`design:returntype`,Promise)],A7.prototype,`mute`,null);var XIe=class{constructor(e){this._deviceManager=e,this._eventEmitter=new w3.EventEmitter,this._selectedDeviceListeners=new Map,this._selectedDevices=new Map,this._deviceInfoMapper=this._deviceManager.deviceInfoMapper;let t=e=>()=>{let t=this._selectedDevices.get(e),n=e===`Speaker`?this._deviceManager.selectedSpeaker:e===`Microphone`?this._deviceManager.selectedMicrophone:void 0,r=n===void 0?void 0:{id:this._deviceInfoMapper.getDeviceId(n.id),name:this._deviceInfoMapper.scrubDeviceLabel(n.name)};this._selectedDevices.set(e,r),this._eventEmitter.emit(`selectedDeviceChanged`,{selectedDeviceType:e,oldDevice:t,newDevice:r})},n=t(`Speaker`);this._selectedDeviceListeners.set(`Speaker`,n),this._deviceManager.on(`selectedSpeakerChanged`,n),n();let r=t(`Microphone`);this._selectedDeviceListeners.set(`Microphone`,r),this._deviceManager.on(`selectedMicrophoneChanged`,r),r()}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}selectedDevice(e){return this._selectedDevices.get(e)}dispose(){let e=this._selectedDeviceListeners.get(`Speaker`);e&&this._deviceManager.off(`selectedSpeakerChanged`,e);let t=this._selectedDeviceListeners.get(`Microphone`);t&&this._deviceManager.off(`selectedMicrophoneChanged`,t),this._eventEmitter.removeAllListeners()}};function j7(e,t,n,r){let i=r===I2.RoomCall||e.kind===VG.Call&&e.direction==`Incoming`&&!e.tsCall.groupId&&!!e.tsCall.meetingData?.meetingCode&&!e.tsCall.threadId,a=!i&&r===I2.TeamsMeetingLink||r===I2.TeamsMeetingId||r===I2.TeamsCoordinates||e.direction==`Incoming`&&!e.tsCall.groupId&&!!e.tsCall.meetingData&&!!e.tsCall.threadId,o={audio:``,video:``},s=e.localAudioStreams?.[0];s&&(o.audio=s.getEffectsCurrentStateRecord()??``);let c=e.localVideoStreams?.[0];return c&&(o.video=c.getEffectsCurrentStateRecord()??``),{timestampInfo:{attemptTimestamp:+new Date},correlationId:n,localParticipantId:e.tsCall.participantId||``,isAcsTeamsCall:e.isAcsTeamsCall,callId:e.tsCall.callId||``,callType:e.tsCall.callType||``,callDirection:e.direction,state:e.state===`Ringing`?`Ringing`:$Ee[e.tsCall.state],groupJoin:!!e.tsCall.groupId,roomJoin:i,meetingJoin:a,callEndDiagnosticsInfo:e.tsCall.callEndDiagnosticsInfo||{},isSupportedEnvironment:t?.runningEnvironmentInfo?.isSupportedEnvironment,effectsStateInfo:o,hostRegion:e.tsCall.region||``,diagnosticInfo:{...e.tsCall.callEndDiagnosticsInfo,telemetryPayloadBytesOriginal:f3.telemetryPayloadBytesOriginal,telemetryPayloadBytesCompressed:f3.telemetryPayloadBytesCompressed}}}function M7(e,t,n){try{n.step===`state-changed`&&n.newState===`Connecting`&&(f3.telemetryPayloadBytesOriginal=0,f3.telemetryPayloadBytesCompressed=0),e.sendEvent({name:Q.acs_calling_call_progress,tenant:d2,properties:n})}catch{t.error(`Failed to send event: ${Q.acs_calling_call_progress} step: ${n.step}`)}}var ZIe=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},N7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},P7=class{get threadId(){return this._threadId}get roomId(){return this._roomId}get groupId(){return this._groupId}get participantId(){return this._tsCall.participantId}get isPstnInterop(){return this._isPstnInterop}get isTeamsInterop(){return this._isTeamsInterop}get callScenario(){if(this._tsCall.callQueueInfo)return _4.CallQueue;if(this.transferorKind!==`unknown`){if(this._tsCall.incomingCallType===`transfer`)return _4.TransferToParticipant;if(this._tsCall.incomingCallType===`replaces`)return _4.TransferToCall}return this.direction===`Incoming`?`AcceptCall`:this.direction===`Outgoing`&&this.context==`Rooms`?_4.JoinRoom:this.direction===`Outgoing`&&this.context==`TeamsMeeting`?_4.JoinTeamMeeting:this.direction===`Outgoing`&&this.context==`GroupIdCall`?_4.JoinWithGroupId:_4.PlaceCall}get context(){return this._tsCall.callType==1||this._currentCallContext==v4.TwoParty?v4.TwoParty:this._tsCall.groupId?v4.GroupIdCall:this._tsCall.conversationType==`groupCall`||this._currentCallContext==v4.MultiParty?v4.MultiParty:this._config?.roomId||this._roomId||this._tsCall.meetingData?.meetingCode?.startsWith(`994`)||this._tsCall.meetingData?.meetingCode?.startsWith(`995`)||this._tsCall.meetingData?.meetingCode?.startsWith(`996`)?v4.Rooms:this._tsCall.meetingData?.meetingUrl||this._tsCall.meetingData?.passcode||this._tsCall.conversationType==`scheduledMeeting`?v4.TeamsMeeting:(this._tsCall.callType,v4.MultiParty)}get transferorKind(){return this._tsCall.transferorMri?G2(this._tsCall.transferorMri||``).kind:``}get direction(){return this._config?.isIncoming?r4.Incoming:r4.Outgoing}get initiatorKind(){return G2(this._tsCall.callerMri?this._tsCall.callerMri:``).kind}get targetKind(){return this._tsCall.groupId?this._tsCall.groupId:this._config?.roomId?this._config.roomId:this._tsCall.meetingData?.meetingUrl||this._tsCall.meetingData?.meetingCode?`TeamsMeetingJoinLink`:this._tsCall.transferorMri?`Transferee`:this._tsCall.participants.length===1?G2(this._tsCall.participants[0].id).kind:this._tsCall.participants.filter((e=>e.id!==this._tsCall.callerMri)).map((e=>G2(e.id).kind)).toString()}constructor(e,t={}){this._tsCall=e,this._threadId=this._tsCall.threadId;let n=this._tsCall.groupId;this._groupId=!n||n.startsWith(`19:`)||n.startsWith(`99:`)?void 0:n,this._roomId=t?.config?.roomId,this._config=t.config,this._isPstnInterop=!1,this._isTeamsInterop=!1}setThreadId(e){this._threadId=e}initialize(e,t,n){this._logger=t,this._eventEmitter=e,this._threadId=this._tsCall.threadId,this._tsCallChangedListener=this._tsCall.changed((()=>this.threadIdChanged(this._tsCall))),this._p2pCallListener=this._tsCall.changed((()=>this.p2pCallHandler())),this._isPstnInterop=this.isPSTNUserInCall,this._isTeamsInterop=this.isTeamsUserInCall,this._participantUpdatedListener=this._tsCall.on(`participantCountsUpdated`,(()=>{this.interoperabilityChangeHandler(),this.p2pCallEscalationHandler()}))}async getServerCallId(){let e=JSON.parse(await this._tsCall.getJoinBlob())?.conversationUrl;if(!e)throw new Y({defaultError:J.CALL.GET_SERVER_CALL_ID});return xFe(e)}p2pCallHandler(){this._currentCallContext==null&&this._tsCall.callType==1&&(this._currentCallContext=v4.TwoParty)}p2pCallEscalationHandler(){this._currentCallContext==v4.TwoParty&&F4(this._tsCall)>2&&(this._currentCallContext=v4.MultiParty,this._eventEmitter.emit(`callInfoChanged`),this._p2pCallListener?.dispose())}get isTeamsUserInCall(){if(!this._tsCall.participants)return!1;for(let e of this._tsCall.participants)if(G2(e.id).kind===`microsoftTeamsUser`)return!0;return!1}get isPSTNUserInCall(){if(!this._tsCall.participants)return!1;for(let e of this._tsCall.participants)if(G2(e.id).kind===`phoneNumber`)return!0;return!1}interoperabilityChangeHandler(){!this._isPstnInterop&&this.isPSTNUserInCall&&(this._isPstnInterop=!0,this._eventEmitter.emit(`callInfoChanged`)),!this._isTeamsInterop&&this.isTeamsUserInCall&&(this._isTeamsInterop=!0,this._eventEmitter.emit(`callInfoChanged`))}threadIdChanged(e){this._tsCall.threadId!==this._threadId&&(this._logger.log(`threadId changed from ${this._threadId} to ${e?.threadId}`),this._threadId=this._tsCall.threadId,this._eventEmitter.emit(`threadIdChanged`))}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}onCallInfoChanged(e,t){this._eventEmitter.on(e,t)}offCallInfoChanged(e,t){this._eventEmitter.off(e,t)}dispose(){this._tsCallChangedListener?.dispose(),this._eventEmitter.removeAllListeners(),this._p2pCallListener?.dispose(),this._participantUpdatedListener?.dispose()}};ZIe([GG(Owe.GetServerCallId),N7(`design:type`,Function),N7(`design:paramtypes`,[]),N7(`design:returntype`,Promise)],P7.prototype,`getServerCallId`,null);var QIe=class e{constructor(){this.CAUSE_ID_TO_NETWORK_INFO={}}static getInstance(){return this.instance||=new e,this.instance}deleteNetworkInfo(e){delete this.CAUSE_ID_TO_NETWORK_INFO[e]}ifCauseIdExistsRemoveNetworkInfo(e){return this.CAUSE_ID_TO_NETWORK_INFO[e]&&this.CAUSE_ID_TO_NETWORK_INFO[e].length===0?!!this.getRemoveCauseIdToNetworkInfo(e):!!this.CAUSE_ID_TO_NETWORK_INFO[e]}getRemoveCauseIdToNetworkInfo(e){if(!Z().telemetry.sendNetworkInfo)return;let t=this.CAUSE_ID_TO_NETWORK_INFO[e];return t&&this.deleteNetworkInfo(e),t}setCauseIdToNetworkInfo(e,t){Object.keys(this.CAUSE_ID_TO_NETWORK_INFO).length>100&&(this.CAUSE_ID_TO_NETWORK_INFO={}),t?this.CAUSE_ID_TO_NETWORK_INFO[e]?this.CAUSE_ID_TO_NETWORK_INFO[e].push({url:t.url,statusCode:t.statusCode,start:t.start,end:t.end,deltaTimeInMs:t.deltaTimeInMs,causeId:t.causeId}):this.CAUSE_ID_TO_NETWORK_INFO[e]=[{url:t.url,statusCode:t.statusCode,start:t.start,end:t.end,deltaTimeInMs:t.deltaTimeInMs,causeId:t.causeId}]:this.CAUSE_ID_TO_NETWORK_INFO[e]=[]}};QIe.instance=null;var F7=QIe.getInstance(),$Ie=class e{constructor(e,t,n,r){this._recordingConsentEnabled=!1,this._consentActivelyRequired=!1,this._localParticipantConsentPublishState=!1,this._isExplicitConsentEnabled=!1,this._isInitialized=!1,this._isExplicitConsentEnabled=Z().calling.explicitConsentFeatureEnabled.enabled,this.initialize(e,t,n,r)}dispose(){this._isInitialized=!1,this._recordingConsentEnabled=!1,this._consentActivelyRequired=!1,this._localParticipantConsentPublishState=!1,e.instance=null}isConsentRequiredInCall(){if(!this._isExplicitConsentEnabled)return!1;let e=this._recordingConsentEnabled&&!this._localParticipantConsentPublishState;return this._logger.info(`ExplicitConsentCallStateManager: isConsentRequiredInCall: Recording Consent Enabled: `+this._recordingConsentEnabled+` Local Participant Consent Publish State: `+this._localParticipantConsentPublishState),this._logger.log(`ExplicitConsentCallStateManager: isConsentRequiredInCall: `+e),e}async consent(e){if(this._isExplicitConsentEnabled){if(e.context===v4.TwoParty)throw this._logger.warn(`Consent for recording is not supported for 1:1 calls`),new Y({defaultError:J.CALL.CONSENT_NOT_SUPPORTED_1TO1});if(!this.isConsentRequiredInCall())throw new Y({defaultError:J.CALL.CONSENT_ALREADY_SET_OR_NOT_REQUIRED});try{if(!await this._tsCall.publishState({level:`user`,type:`consentToRecording`,content:`{}`},AG()))throw this._logger.error(`Consent failure to set publish state for user`),new Y({defaultError:J.CALL.FAILED_TO_SET_CONSENT});this._logger.log(`ExplicitConsentCallStateManager: Consent for the call provided successfully`)}catch(e){throw this._logger.error(`Consent failure to set publish state for user on service side`),e}}}areCoreCapabilitiesConsentRestricted(){if(!this._isExplicitConsentEnabled)return!1;let e=this._consentActivelyRequired&&!this._localParticipantConsentPublishState;return this._logger.info(`ExplicitConsentCallStateManager: areCoreCapabilitiesConsentRestricted: Consent Actively Required: `+this._consentActivelyRequired+` Local Participant Consent Publish State: `+this._localParticipantConsentPublishState),this._logger.log(`ExplicitConsentCallStateManager: areCoreCapabilitiesConsentRestricted: `+e),e}offConsentRestrictionChanged(e,t){if(e!==`consentRestrictionChanged`)throw Error(`ExplicitConsentCallStateManager: OffConsentRestrictionChanged - Invalid event`);this._logger.log(`ExplicitConsentCallStateManager: Unsubscribing to consentRestrictionChanged event`),this._eventEmitter.off(e,t)}onConsentRestrictionChanged(e,t){if(e!==`consentRestrictionChanged`)throw Error(`ExplicitConsentCallStateManager: onConsentRestrictionChanged - Invalid event`);this._logger.log(`ExplicitConsentCallStateManager: Subscribing to consentRestrictionChanged event`),this._eventEmitter.on(e,t)}initialize(e,t,n,r){this._isExplicitConsentEnabled&&(this._isInitialized||=(this._logger=r.createChild((()=>`Explicit Consent::Call(id='${e.callId}', state='${e.state}')`)),this._tsCall=e,this._callAgent=t,this._eventEmitter=n,e.changed((()=>{if(!0===e.meetingDetails?.recordingConsentDetails?.explicitRecordingConsentEnabled){this._recordingConsentEnabled=!0;let t=!0===e.meetingDetails?.recordingConsentDetails?.consentActivelyRequired;t!==this._consentActivelyRequired&&(this._consentActivelyRequired=t,this._eventEmitter.emit(`consentRestrictionChanged`))}})),e.on(`publishedStatesChanged`,(async e=>{this._localParticipantConsentPublishState=!1,this._handleConsentStateChange(e)})),!0))}_handleConsentStateChange(e){if(!0!==this._localParticipantConsentPublishState){let n=this._callAgent.getUserMri();var t=!1;e&&this._getPublishedState(e).forEach((e=>{e.participantStates.forEach((e=>{if(e.id===n)return this._logger.log(`ExplicitConsentCallStateManager: Handle Consent State changes: Local participant has provided the consent`),void(t=!0)}))})),this._localParticipantConsentPublishState=t,t&&this._eventEmitter.emit(`consentRestrictionChanged`)}}_getPublishedState(e){return e.typeStates.filter((e=>[`consentToRecording`].includes(e.type)))}};$Ie.instance=null;var eLe=class{constructor(e,t){this._interval=0,this._ufds=new Map,this._interval=t,e.forEach((e=>{this._ufds.set(e,{_lastRecovered:new Date,_shouldNotifyError:!0,_shouldNotifyRecovery:!0})}))}updateLastRecoveredTime(e,t){let n=this._ufds.get(e);n&&(n._lastRecovered=new Date(t.getTime()+this._interval),n._shouldNotifyError=!0,n._shouldNotifyRecovery=!1)}shouldLogError(e,t){let n=this._ufds.get(e);if(n){let e=n._lastRecovered<=t&&n._shouldNotifyError;return e&&(n._shouldNotifyError=!1,n._shouldNotifyRecovery=!0),e}return!0}shouldLogRecovery(e,t){let n=this._ufds.get(e);if(n){let r=n._shouldNotifyRecovery;return r&&this.updateLastRecoveredTime(e,t),r}return!0}},tLe,I7=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},L7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},R7=class e{get id(){return this._id}get callerInfo(){return{identifier:this._callerIdentity,displayName:this._callerDisplayName}}get transferorInfo(){if(this._transferorIdentity)return{identifier:this._transferorIdentity,displayName:this._transferorDisplayName}}get state(){return this._state}get role(){return this._role}get callEndReason(){return this._callEndReason}get kind(){return this._kind}get direction(){return this._direction}get isMuted(){return this._isMuted}get isScreenSharingOn(){return this._isScreenSharingOn}get isLocalVideoStarted(){return this._isLocalVideoStarted}get localVideoStreams(){return this._localVideoStreams}get localAudioStreams(){return this._localAudioStreams}get isIncomingAudioMuted(){return this._isIncomingAudioMuted}get remoteParticipants(){return this._remoteParticipants}get totalParticipantCount(){return this._totalParticipantCount}get lobby(){return this._lobby}get isAcsTeamsCall(){return this._isAcsTeamsCall}get isIPAudioEnabled(){return this.callInfo.context===v4.TwoParty||this._allowIPAudio}get isIPVideoEnabled(){return this.callInfo.context===v4.TwoParty||this._allowIPVideo}get isEnterpriseTeamsCall(){return this._isEnterpriseTeamsCall}subscribeToGetRemoteAudioStream(){if(!this._rawAudioStreamChangedSubscription)try{let e=this.tsCall.getIncomingRawAudioStream(),t=async()=>{try{if(this._remoteAudioStreams.length===0){if(!await e.getMediaStream())throw new Y({defaultError:J.CALL.REMOTE_AUDIO_GET_MEDIA_STREAM_UNDEFINED});this._remoteAudioStreams.push(new hIe(e,this._telemetryLogManager,this.id,this.tsCall.participantId)),this._eventEmitter.emit(`remoteAudioStreamsUpdated`,{added:this._remoteAudioStreams,removed:[]})}else if(await e.getMediaStream())this._eventEmitter.emit(`remoteAudioStreamsUpdated`,{added:[],removed:[]});else{let e=this._remoteAudioStreams[0];e.dispose(),this._remoteAudioStreams=[],this._eventEmitter.emit(`remoteAudioStreamsUpdated`,{added:[],removed:[e]})}}catch(e){throw new Y({defaultError:J.CALL.REMOTE_AUDIO_GET_MEDIA_STREAM_RETURNED_ERROR,originalError:e})}};this._rawAudioStreamChangedSubscription=e.changed((()=>{this.logger.info(`Changed fired ${this.tsCall.state}, ${this.state}`),t().catch(A4)})),t().catch((()=>{this.logger.info(`Failed to update remote audio stream collection, retrying on changed`)}))}catch{this.logger.info(`Failed to get raw audio stream from the stack`)}}get remoteAudioStreams(){if(!Z().calling.allowAccessRawMediaStream)throw new Y({defaultError:J.CALL.REMOTE_AUDIO_GET_MEDIA_STREAM_DISABLED});return this._remoteAudioStreams}get deviceManager(){return this._callAgent.deviceManager}get mediaConstraintsManager(){return this._mediaConstraintsManager}get isHandlingLargeMeetingVideoRendering(){return this._isHandlingLargeMeetingVideoRendering}get callInfo(){return this._callInfo}get networkQualityUfdEventDetails(){return this._networkQualityUfdEventDetails}get acsProxy(){return this._callAgent.acsProxy}get acsCustomRelayManager(){return this._callAgent.acsCustomRelayManager}get audioEffectsProcessorStats(){return this._audioEffectsProcessorStats}get callAgent(){return this._callAgent}get iceServers(){return this._getIceServersCalledOnce||(this._getIceServersCalledOnce=!0,this._iceServers=this.tsCall.getMediaSessionStats()?.extensions?.IceServers),this._iceServers}get watermarkAudioOnlyFallbackTriggered(){return this._watermarkAudioOnlyFallbackTriggered}constructor(e,t,n,r,i,a){this._callAgent=t,this._isMuted=!1,this._isMuted_correlationIdCache=K0(),this._isIncomingAudioMuted=!1,this._isIncomingAudioMuted_correlationIdCache=K0(),this._isScreenSharingOn=!1,this._isLocalVideoStarted=!1,this._localVideoStreams=[],this._localAudioStreams=[],this._remoteAudioStreams=[],this._totalParticipantCount=1,this._isDeviceNotFunctioningMuted=!1,this.__attemptedToRecoverMicNotFunctioningBySDK=!1,this._isMicrophoneMuted=!1,this._disposed=!1,this._lastTsCallState=0,this._isSpeakerMuted=!1,this._callMode=0,this._role=w2,this._lastTsCallMeetingDetails={},this._isHandlingLargeMeetingVideoRendering=!1,this._joinContextDescription=I2.Unknown,this._remoteParticipantsChangedListeners=[],this._localRingingStateSet=!1,this._networkQualityUfdEventDetails=[],this._audioEffectsProcessorStats=null,this._getIceServersCalledOnce=!1,this._watermarkAudioOnlyFallbackTriggered=!1,this._transportStateTimestamp=new Map,this._setOrUpdateDeviceEventsTask=Promise.resolve(),this._isAcsTeamsCall=!1,this._isEnterpriseTeamsCall=this._callAgent.isEnterpriseUser(),this._isTeamsExtensionUser=this._callAgent.isTeamsExtensionUser(),this._mriToRemoteParticipantMap=new Map,this._remoteParticipants=[],this._state=`None`,this._transportState=`None`,this._allowIPAudio=!0,this._allowIPVideo=!0,this.localVideoStream=void 0,this.localScreenSharingStream=void 0,this.isRenderingRemoteScreenShare=!1,this._handleMuteChanges=()=>{let e=[v4.Rooms,v4.GroupIdCall,v4.MultiParty,v4.TeamsMeeting].some((e=>e===this._callInfo.context)),t=this.tsCall.conversationType||e?!!(this.tsCall.isMuted||this.tsCall.state!==10&&this.tsCall.isServerMuted||this._isDeviceNotFunctioningMuted):!(!this.tsCall.isMuted&&!this._isDeviceNotFunctioningMuted);if(this._isMuted!=t){this.logger.info(`isMuted changed from ${this._isMuted} to ${t}`);let e=[];this.tsCall.isMuted&&e.push(`isMicrophoneMuted`),this.tsCall.isServerMuted&&(e.push(`isServerMuted`),[3,4,5].some((e=>e===this.tsCall.state))&&this._eventEmitter.emit(`mutedByOthers`),this.explicitConsentStateImp.areCoreCapabilitiesConsentRestricted()&&this.handleConsentCapabilitiesChanges()),this._isDeviceNotFunctioningMuted&&e.push(`isDeviceNotFunctioningMuted`);let n=``;e.length>=1&&(n=e.join(`, `)),t&&(this._isMuted_correlationIdCache=K0()),M7(this._telemetryLogManager,this.logger,{...j7(this,this._callAgent,this._isMuted_correlationIdCache,this._joinContextDescription),step:`isMuted-changed`,oldIsMuted:this._isMuted,newIsMuted:t,reason:n}),this._isMuted=t,this._eventEmitter.emit(`isMutedChanged`)}},this.audioSourceChanged=async e=>{this._telemetryLogManager.sendEvent({name:Q.acs_calling_local_audio_source_changed,tenant:d2,properties:{callId:this.id,localParticipantId:this.tsCall.participantId,timestampInfo:+new Date,correlationId:K0(),localAudioStream:e.source?.source instanceof MediaStream?`MediaStream`:`Device`}}),e.source instanceof Y6?(this.localAudioStreams[0]&&this.localAudioStreams[0].mediaStreamType===`RawMedia`&&this.stopAudioInternal(!0),await(await this._callAgent.tsStack?.getDeviceManagerAsync?.())?.selectDevicesAsync?.({microphone:e.source.id})):await this.startAudioInternal(e.source,!0)},this._handleIncomingAudioMuteChanges=()=>{let e=this._isSpeakerMuted;this._isIncomingAudioMuted!=e&&(this.logger.info(`newIncomingAudioMuted changed from ${this._isIncomingAudioMuted} to ${e}`),e&&(this._isIncomingAudioMuted_correlationIdCache=K0()),M7(this._telemetryLogManager,this.logger,{...j7(this,this._callAgent,this._isIncomingAudioMuted_correlationIdCache,this._joinContextDescription),step:`isIncomingAudioMuted-changed`,oldIsMuted:this._isIncomingAudioMuted,newIsMuted:e,reason:``}),this._isIncomingAudioMuted=e,this._eventEmitter.emit(`isIncomingAudioMutedChanged`))},this._id=e.callId,this.tsCall=n,this._direction=e.isIncoming?`Incoming`:`Outgoing`,this._config=e,this.logger=this._callAgent.logger.createChild((()=>`Call:${this._id}:${this._state}`)),this._telemetryLogManager=r,this.stats=new dIe(this.logger,this._telemetryLogManager),this._eventEmitter=new S6(this.logger),this.activeRemoteVideoStreamViews=new Map,this.isSubscribedCall=!1,this.isBreakoutRoomCall=!1,this._mediaMetricsDeviceEvents={},this._kind=i,this._optimalVideoCount=1,this._ufdsCorrelationIdCache=dTe(),this._callInfo=new P7(n,{config:e}),this._callInfo.initialize(this._eventEmitter,this.logger,this._telemetryLogManager),this._ufdLogThrottler=new eLe([27],Z().telemetry.speakingWhileMutedThrottleInterval),Z().calling.mediaMetricsDeviceEventsEnabled&&(async()=>{let e=await this._callAgent.tsStack?.getDeviceManagerAsync?.();e&&(this._dmDevicesChangedSub=e.on(`devicesChanged`,(()=>{this._setOrUpdateDeviceEventsTask=this._setOrUpdateDeviceEventsTask.then((()=>this.setOrUpdateMediaMetricsDeviceEvents().catch(A4)))})))})().catch((e=>{this.logger.error(`Failed to register devicesChanged event: ${e}`)})),this._extensibleApi=new N3(this.logger,{call:this,callAgent:this._callAgent,callInfo:this._callInfo},{tsCall:this.tsCall,callAgent:this._callAgent,call:this,telemetryLogManager:this._telemetryLogManager}),this.explicitConsentStateImp=new $Ie(this.tsCall,t,this._eventEmitter,this.logger),this._capabilityResolver=new CDe(this._eventEmitter,this.logger,this,this._callInfo,t,n),this._lobby=new n7(this.tsCall,this,this.logger,this._telemetryLogManager);let o=Q5(D3.CallFeature);for(let e of o)e.activationOptions.activationEvent===`OnExtendedObjectConstructor`&&this.feature(e);this._mmrRdpConnectionManager=new bIe(this.logger),Z().telemetry.sendNetworkChangedTelemetry&&this._sendNetworkChangedTelemetry(),Z().telemetry.deviceChangedEvents.enabled&&(this._selectedDeviceManager=new XIe(this.deviceManager),this._setupSelectedDeviceChangedTelemetry()),this._mediaConstraintsManager=new vIe(this.tsCall,this.logger,this._telemetryLogManager),this._isAcsTeamsCall=a??!1,this.feature(Z5.MediaAccess).on(`localParticipantMediaAccessChanged`,(e=>{this.logger.info(`Call common, time when received localParticipantMediaAccessChanged event: ${new Date().getTime()}, isAudioPermitted=${e.mediaAccess.isAudioPermitted}, isVideoPermitted=${e.mediaAccess.isVideoPermitted}`),!1===e.mediaAccess.isVideoPermitted&&this.localVideoStream&&this.stopVideo(this.localVideoStream)})),this.explicitConsentStateImp.onConsentRestrictionChanged(`consentRestrictionChanged`,(()=>{this.logger.info(`Call common, time when received explicitConsentStateChanged event:=\n ${this.explicitConsentStateImp.areCoreCapabilitiesConsentRestricted()}`),this.handleConsentCapabilitiesChanges()}))}async accept(e={}){let t=e.audioOptions?.muted??!1,n=this.getLocalVideoStreamFromCallOptions(e),r=this.getLocalAudioStreamFromCallOptions(e),i=+new Date,a=this._callAgent.getEcsConfigIds(),o=fTe(this.tsCall),s=K0(),c=jG(s),l=this.createVideoNegotiationTag(s,`Video`),u={joinContextDescription:``,additionalProperties:{EmergencyCountryCode:this._callAgent._caConfigBag?.emergencyCountryCode||``,IsUserEmergencyCountryCode:this._callAgent._caConfigBag?.IsUserEmergencyCountryCode||!1,IsEmergencyCall:this._isEmergencyCall,trouterState:this._callAgent.getTrouterState(),muted:t,withVideo:this.isIPVideoEnabled&&!!n,withAudio:this.isIPAudioEnabled&&r?.mediaStreamType?r?.mediaStreamType:``,...r7(),AcsCallingSDKWeb_ecsConfigId:a.AcsCallingSDKWeb,SkypeWebMedia_ecsConfigId:a.SkypeWebMedia,customContext:{userToUserPresent:!!o?.userToUser,xHeadersPresent:!!o?.xHeaders&&o.xHeaders.length>0},mediaModalities:this.getMediaModalityTelemetry(e?.mediaModalities),negotiationTag:l,causeId:c},additionalDetails:{}},d=(e,t,a)=>{let o=+new Date,d={...u},f;if(t){let t={message:J.CALL.ACCEPT_INCOMING_CALL.message,code:J.CALL.ACCEPT_INCOMING_CALL.code,subCode:J.CALL.ACCEPT_INCOMING_CALL.subCode,resultCategories:J.CALL.ACCEPT_INCOMING_CALL.resultCategories},{callEndReason:n,callingCommunicationError:r,hasDiagnosticsInfo:i}=V3(this,e,t);i?d.additionalDetails.callEndReason=n:d.additionalDetails.communicationServicesError=K3(r).communicationServicesError,f=r}else f=new Y({defaultError:J.CALL.ACCEPT_INCOMING_CALL,originalError:e}),d.additionalDetails.communicationServicesError=K3(f).communicationServicesError;if(this.sendCallStageEvent({eventName:Q.acs_calling_call_accept_failed,correlationId:s,timestampInfo:{deltaTimeInMs:o-i},additionalPayload:d},f,void 0,a?F7.getRemoveCauseIdToNetworkInfo(a):void 0),n){let e=+new Date;f=new Y({defaultError:J.LOCAL_VIDEO_STREAM.CALL_NOT_FOUND}),this.logger.error(f.message),this.sendVideoEvent({correlationId:s,eventName:Q.acs_calling_start_video_failure,timestampInfo:{deltaTimeInMs:e-i},localVideoStream:n,step:`accept`,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:l,causeId:c}},f),this.removeLocalVideoStream(n)}return r&&this.removeLocalAudioStream(r),f};try{if(e?.videoOptions?.constraints){let t=this._mediaConstraintsManager.getTelemetryPayload({video:e?.videoOptions?.constraints});u.additionalProperties.constraints=t}u.additionalProperties.negotiationTag=l,u.additionalProperties.causeId=c,this.sendCallStageEvent({eventName:Q.acs_calling_call_accept_attempt,correlationId:s,timestampInfo:{attemptTimestamp:i},additionalPayload:u});let a={...u};if(n&&this.setLocalVideoStream(n),this.setLocalAudioStream(r),n&&this.sendVideoEvent({eventName:Q.acs_calling_start_video_attempt,timestampInfo:{attemptTimestamp:i},correlationId:s,step:`accept`,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:l,causeId:c}}),this.tsCall.state!==1)throw new Y({defaultError:J.CALL.ACCEPT_NOT_RINGING});try{if(e?.videoOptions?.constraints){let t=await this._mediaConstraintsManager.setVideoConstraints(e?.videoOptions?.constraints,`accept`,s,i),n=this._mediaConstraintsManager.getTelemetryPayload({video:t});a.additionalProperties.constraints=n}}catch(e){let t=new Y({defaultError:J.CALL.ACCEPT_VIDEO_CONSTRAINTS,originalError:e});this.logger.error(`${t.message}`)}let o={withVideo:!!n&&this.isIPVideoEnabled,muted:t};if(t&&(o.muteFlags=1),o.sendMediaModalities=this.setMediaModalities(e?.mediaModalities),Z()?.calling?.enableCustomTurnUsage&&this.acsCustomRelayManager?.customRelayManagerInUse&&(o.mediaConfiguration={connectionType:`NoDirectConnection`}),r&&await this.startAudioInternal(r,!0).catch((e=>{this.logger.error(`Failed to start localAudioStream, message=${e?.message}`)})),n?.mediaStreamType===`RawMedia`)try{await this._setRawStream(n,1)}catch(e){let t=+new Date,r=new Y({defaultError:J.LOCAL_VIDEO_STREAM.VIDEO_GET_MEDIA_STREAM,originalError:e});this.sendVideoEvent({correlationId:s,eventName:Q.acs_calling_media_stream,timestampInfo:{deltaTimeInMs:t-i},localVideoStream:n,step:`accept`,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:l,causeId:c}},r),this.removeLocalVideoStream(n)}let f=AG();return F7.setCauseIdToNetworkInfo(f),this.tsCall.accept(o,f).then((async()=>{let e=+new Date;n&&this.shallRemoveLvsAfterConnectedSuccessfully(n,`accept`,s,e,i,l,c),r&&this.shallRemoveLasAfterConnectedSuccessfully(r,`accept`,s,e,i),a.additionalProperties.negotiationTag=l,a.additionalProperties.causeId=c,this.sendCallStageEvent({eventName:Q.acs_calling_call_accept_connected,correlationId:s,timestampInfo:{deltaTimeInMs:e-i},additionalPayload:a},void 0,void 0,F7.getRemoveCauseIdToNetworkInfo(f))})).catch((e=>{d(e,!0,f)})),this}catch(e){throw d(e,!1)}}async reject(){let e=+new Date,t=K0();this.sendCallStageEvent({eventName:Q.acs_calling_call_reject_attempt,correlationId:t,timestampInfo:{attemptTimestamp:e}});let n=this._callAgent.getEcsConfigIds(),r={additionalProperties:{EmergencyCountryCode:this._callAgent._caConfigBag?.emergencyCountryCode||``,IsUserEmergencyCountryCode:this._callAgent._caConfigBag?.IsUserEmergencyCountryCode||!1,IsEmergencyCall:this._isEmergencyCall,trouterState:this._callAgent.getTrouterState(),AcsCallingSDKWeb_ecsConfigId:n.AcsCallingSDKWeb,SkypeWebMedia_ecsConfigId:n.SkypeWebMedia},additionalDetails:{}};if(this.tsCall.state!==1){let n=new Y({defaultError:J.CALL.REJECT_NOT_RINGING});r.additionalDetails.communicationServicesError=K3(n).communicationServicesError;let i=+new Date;throw this.sendCallStageEvent({eventName:Q.acs_calling_call_reject_failed,correlationId:t,timestampInfo:{deltaTimeInMs:i-e},additionalPayload:r},n),n}let i=AG();return F7.setCauseIdToNetworkInfo(i),this.tsCall.reject(i).then((()=>{let n=+new Date;this.sendCallStageEvent({eventName:Q.acs_calling_call_reject_success,correlationId:t,timestampInfo:{deltaTimeInMs:n-e}},void 0,void 0,F7.getRemoveCauseIdToNetworkInfo(i))})).catch((n=>{let a=+new Date,o={message:J.CALL.REJECT_CALL_FAILED.message,code:J.CALL.REJECT_CALL_FAILED.code,subCode:J.CALL.REJECT_CALL_FAILED.subCode,resultCategories:J.CALL.REJECT_CALL_FAILED.resultCategories},{callEndReason:s,callingCommunicationError:c,hasDiagnosticsInfo:l}=V3(this,n,o);throw l?r.additionalDetails.callEndReason=s:r.additionalDetails.communicationServicesError=K3(c).communicationServicesError,this.sendCallStageEvent({eventName:Q.acs_calling_call_reject_failed,correlationId:t,timestampInfo:{deltaTimeInMs:a-e},additionalPayload:r},c,void 0,F7.getRemoveCauseIdToNetworkInfo(i)),c}))}dispose(){this._disposed||=(this._dmDevicesChangedSub&&this._dmDevicesChangedSub.dispose(),this._dmDevicesChangedSub=void 0,this._extensibleApi.dispose(),this._eventEmitter.removeAllListeners(),this._onlineListener&&window.removeEventListener(`online`,this._onlineListener),this._offlineListener&&window.removeEventListener(`offline`,this._offlineListener),this._trouterStateChangedListener&&this._callAgent.offTrouterStateChanged(this._trouterStateChangedListener),this._mmrRdpConnectionManager.dispose(),this._selectedDeviceManager?.dispose(),this.explicitConsentStateImp.dispose(),!0)}async startAudioInternal(e,t=!1){let n=K0(),r=+new Date,i=AG();F7.setCauseIdToNetworkInfo(i);try{if(this.isInternalApiCallWithoutRawMedia(e,t))return;this.sendRawMediaEvent({eventName:Q.acs_calling_start_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:n,kindOfEvent:$.attempt,isInternal:t,timestampInfo:``,additionalDetails:``}),this.validateRawMedia(e,J.CALL.START_AUDIO_LAS_NOT_RAW_MEDIA),this._userProvidedLocalAudioStreamCache=e;let a=await this.createMediaStream(e),o=await this._callAgent.tsStack?.getDeviceManagerAsync?.();if(!Z()?.calling?.allowAccessRawMediaStream||!o?.setRawMediaStream)throw new Y({defaultError:J.CALL.LOCAL_AUDIO_SET_MEDIA_STREAM});o?.setRawMediaStream(a,0),this.removeLocalAudioStream(this.localAudioStreams[0]),this.setLocalAudioStream(e);let s=+new Date;this.sendRawMediaEvent({eventName:Q.acs_calling_start_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:n,kindOfEvent:$.success,isInternal:t,localAudioStream:this.localAudioStreams[0],timestampInfo:{deltaTimeInMs:s-r},additionalDetails:{networkInfo:F7.getRemoveCauseIdToNetworkInfo(i)}})}catch(e){let a=new Y({defaultError:J.CALL.START_AUDIO_STREAM_FAILED,originalError:e});this.logger.error(`Failed to start raw media audio: ${a.message}`);let o=+new Date;throw this.sendRawMediaEvent({eventName:Q.acs_calling_start_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:n,isInternal:t,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:o-r},additionalDetails:{failureReason:a.message||``,code:a.code,subCode:a.subCode,...K3(a),networkInfo:F7.getRemoveCauseIdToNetworkInfo(i)}}),a}}isInternalApiCallWithoutRawMedia(e,t){return!(e?.mediaStreamType===`RawMedia`||!t)&&(this.logger.info(`startAudioInternal internal call: LocalAudioStream media type is raw media, skipping raw audio startAudioInternal`),!0)}validateRawMedia(e,t){if(e?.mediaStreamType!==`RawMedia`)throw new Y({defaultError:t})}async createMediaStream(e){let t;try{t=await e.getMediaStream()}catch(e){throw new Y({defaultError:J.CALL.LOCAL_AUDIO_GET_MEDIA_STREAM,originalError:e})}return new MediaStream(t)}stopAudioInternal(e=!1){let t=K0(),n=+new Date,r=AG();F7.setCauseIdToNetworkInfo(r);try{let i=this._localAudioStreams[0];if(this.isInternalApiCallWithoutRawMedia(i,e))return;this.sendRawMediaEvent({eventName:Q.acs_calling_stop_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,kindOfEvent:$.attempt,isInternal:e,timestampInfo:``,additionalDetails:``}),e||$5(o4.StopAudio,this.state),this.validateRawMedia(i,J.CALL.STOP_AUDIO_LAS_NOT_RAW_MEDIA);let a=this._callAgent.tsStack?.getDeviceManager();if(!Z()?.calling?.allowAccessRawMediaStream||!a?.unsetRawMediaStream)throw new Y({defaultError:J.CALL.LOCAL_AUDIO_UNSET_MEDIA_STREAM});a.unsetRawMediaStream(0),this._userProvidedLocalAudioStreamCache=void 0,this.removeLocalAudioStream(this.localAudioStreams[0]),this.setLocalAudioStream();let o=+new Date;this.sendRawMediaEvent({eventName:Q.acs_calling_stop_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,kindOfEvent:$.success,isInternal:e,localAudioStream:this.localAudioStreams[0],timestampInfo:{deltaTimeInMs:o-n},additionalDetails:{networkInfo:F7.getRemoveCauseIdToNetworkInfo(r)}})}catch(i){let a=new Y({defaultError:J.CALL.STOP_AUDIO_STREAM_FAILED,originalError:i});this.logger.error(`Failed to stop raw media audio: ${a.message}`);let o=+new Date;throw this.sendRawMediaEvent({eventName:Q.acs_calling_stop_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,isInternal:e,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:o-n},additionalDetails:{failureReason:a.message||``,code:a.code,subCode:a.subCode,...K3(a),networkInfo:F7.getRemoveCauseIdToNetworkInfo(r)}}),a}}bindTsCall(){let e=[];this.tsCall.callerMri!==void 0&&(this._callerIdentity=G2(this.tsCall.callerMri),this._callerDisplayName=this.tsCall.participants.find((e=>e.id===this.tsCall.callerMri))?.displayName),this._lastTsCallState=this.tsCall.state,this.mapTsCallState(this.tsCall.state),this._setCallRole(this.tsCall.advancedMeetingRole),this.tsCall.callQueueInfo?(this._callerIdentity=G2(this.tsCall.callQueueInfo.onBehalfOf.id),this._callerDisplayName=this.tsCall.callQueueInfo.onBehalfOf.displayName?this.tsCall.callQueueInfo.onBehalfOf.displayName:this.tsCall.participants.find((e=>e.id===this.tsCall.callQueueInfo?.details.id))?.displayName,this._transferorIdentity=G2(this.tsCall.callQueueInfo.details.id),this._transferorDisplayName=this.tsCall.callQueueInfo.details.displayName?this.tsCall.callQueueInfo.details.displayName:this.tsCall.participants.find((e=>e.id===this.tsCall.callQueueInfo?.details.id))?.displayName):this.tsCall.transferorMri&&(this._transferorIdentity=G2(this.tsCall.transferorMri),this._transferorDisplayName=this.tsCall.transferorDisplayName),this.updateCallMode(),e.push(this.tsCall.changed((()=>{this.tsCall.callId!==this._id&&(this.logger.log(`tsCall callId changed from ${this._id} to ${this.tsCall.callId}`),M7(this._telemetryLogManager,this.logger,{...j7(this,this._callAgent,K0(),this._joinContextDescription),step:`id-changed`,isAcsTeamsCall:this.isAcsTeamsCall,oldCallId:this._id,newCallId:this.tsCall.callId}),this._id=this.tsCall.callId,this._eventEmitter.emit(`idChanged`)),this.tsCall.state!==this._lastTsCallState&&(this.logger.log(`tsCall state changed=${this.tsCall.state}`),this._lastTsCallState=this.tsCall.state,this.mapTsCallState(this.tsCall.state),this._handleMuteChanges()),this._isScreenSharingOn!==this.tsCall.isScreenSharingOn&&(this.logger.log(`tsCall isScreenSharingOn changed=${this.tsCall.isScreenSharingOn}`),this._isScreenSharingOn=this.tsCall.isScreenSharingOn,this._isScreenSharingOn||this.removeScreenSharingStream(),this._eventEmitter.emit(`isScreenSharingOnChanged`)),this._isMicrophoneMuted!==this.tsCall.isMuted&&(this.logger.log(`tsCall isMuted changed=${this.tsCall.isMuted}`),this._isMicrophoneMuted=this.tsCall.isMuted,this._handleMuteChanges()),this._isSpeakerMuted!==this.tsCall.isSpeakerMuted&&(this.logger.log(`tsCall _isSpeakerMuted changed=${this.tsCall.isSpeakerMuted}`),this._isSpeakerMuted=this.tsCall.isSpeakerMuted,this._handleIncomingAudioMuteChanges()),this.tsCall.advancedMeetingRole!==this._lastTsCallAdvancedMeetingRole&&(this.logger.log(`tsCall advancedMeetingRole changed=${this.tsCall.advancedMeetingRole}`),this._setCallRole(this.tsCall.advancedMeetingRole)),(this.tsCall.meetingData?.meetingUrl||this.tsCall.meetingData?.passcode||this.tsCall.conversationType==`scheduledMeeting`)&&this.tsCall.meetingDetails&&aTe(this.tsCall.meetingDetails,this._lastTsCallMeetingDetails)&&this._setMeetingCapabilities(this.tsCall.meetingDetails),this.updateCallMode()}))),e.push(this.tsCall.on(`optimalVideoReceiversCountChanged`,this.optimalVideoCountChanged)),e.push(this.tsCall.on(`serverMutedChanged`,(()=>{this.logger.log(`tsCall isServerMuted changed=${this.tsCall.isServerMuted}`),this._handleMuteChanges()}))),this._totalParticipantCount=F4(this.tsCall),e.push(this.tsCall.on(`participantCountsUpdated`,(()=>{let e=F4(this.tsCall);if(this._totalParticipantCount!==e){let t=this._totalParticipantCount;this._totalParticipantCount=e,this.logger.log(`tsCall totalParticipantCount changed from ${t} to ${this._totalParticipantCount}`),Z().rendering.remoteVideo.largeMeeting.handleVideoRendering&&this._enableOrDisable_largeMeeting_videoRendering(),this._eventEmitter.emit(`totalParticipantCountChanged`);try{this.stats.recordEvent({name:s3.number_of_participants,callId:this.id,localParticipantId:this.tsCall.participantId,data:{totalParticipantCount:this._totalParticipantCount,participantCounts:this.tsCall.participantCounts||{},previousParticipantCount:t}})}catch{this.logger.error(`failed to send participant count change telemetry`)}}})));let t=(e,t)=>{if(e!==t){this.logger.log(`transportState changed from ${this._transportState} to ${t}`);let n=this._transportStateTimestamp.get(`Connected`)===void 0?this._connectedTimestamp:void 0;this._transportStateTimestamp.delete(t);let r=Q2.omitBy({connectedTimetamp:n,transportConnectedTimestamp:this._transportStateTimestamp.get(`Connected`),transportDisconnectedTimestamp:this._transportStateTimestamp.get(`Disconnected`),transportFailedTimestamp:this._transportStateTimestamp.get(`Failed`)},Q2.isUndefined),i=Q2.merge(j7(this,this._callAgent,K0(),this._joinContextDescription),{timestampInfo:r});M7(this._telemetryLogManager,this.logger,{...i,step:`transportState-changed`,oldState:e,newState:t}),this._transportStateTimestamp.set(t,Date.now()),this._transportState=t}};e.push(this.tsCall.on(`transportConnected`,(()=>{t(this._transportState,`Connected`)}))),e.push(this.tsCall.on(`transportDisconnected`,(()=>{t(this._transportState,`Disconnected`)}))),e.push(this.tsCall.on(`transportFailed`,(()=>{t(this._transportState,`Failed`)}))),e.push(this.tsCall.on(`callQualityChanged`,(async e=>{try{let t;e.type===5||e.type===32||e.type===2||e.type===1||e.type===37?(t=s3.network_quality,this._trackNetworkQualityUfdEventDetails(e.type)):t=e.type===44||e.type===43||e.type===9||e.type===25||e.type===45||e.type===33||e.type===34||e.type===55||e.type===26||e.type===47||e.type===27?s3.video_device_issue:s3.other_diagnostic,e.value===3||e.value===2?(this._ufdLogThrottler.shouldLogError(e.type,new Date)&&this.logger.warn(`Ufd error raised!, ufd=${e.type}, value=${e.value}, kind=${t}`),t===s3.network_quality&&window.dispatchEvent(new CustomEvent(`online`,{detail:!1}))):(this._ufdLogThrottler.shouldLogRecovery(e.type,new Date)&&this.logger.warn(`Ufd error recovered!, ufd=${e.type}, value=${e.value}, kind=${t}`),t===s3.network_quality&&window.dispatchEvent(new CustomEvent(`online`,{detail:!0})));let n=``,r=this._ufdsCorrelationIdCache[e.type][e.mediaType];e.value==3||e.value==2?r?n=r:(n=K0(),this._ufdsCorrelationIdCache[e.type][e.mediaType]=n):(r&&(n=r),this._ufdsCorrelationIdCache[e.type][e.mediaType]=void 0);let i={type:e.type.toString(),level:e.value,mediaType:e.mediaType,correlationId:n};if(this.stats.recordEvent({name:t,callId:this.id,localParticipantId:this.tsCall.participantId,data:i}),this.shallStopVideo(e)){let t=+new Date,n=K0();this.logger.warn(`Attempting to stop video gracefully due to video ufd being raised.UFD: ${e.type}, value: ${e.value}, call direction: ${this._direction}`),this.sendAudioEvent({eventName:Q.acs_calling_stop_video_on_ufd_attempt,timestampInfo:{attemptTimestamp:t},correlationId:n,step:`mid-call`});try{this.localVideoStream&&this.stopVideo(this.localVideoStream)}catch{let t=`Failed to stop video on video device start failed or capture mute event ${e.type} with value ${e.value}`;this.logger.error(t)}}if(this.shallRemoveLocalVideoStreamOnBadUfd(e)){let t=new Y({defaultError:J.CALL.REMOVE_LOCAL_VIDEO_ON_BAD_UFD,defaultErrorMessageArgs:[e.type,e.value,this._direction]});if(this.localVideoStream){let e=jG(n),r=this.createVideoNegotiationTag(n,`Video`);this.sendVideoEvent({eventName:Q.acs_calling_start_video_failure,correlationId:K0(),timestampInfo:{attemptTimestamp:+new Date},step:`start`,additionalDetails:{...K3(t),negotiationTag:r,causeId:e},localVideoStream:this.localVideoStream,isScreenSharingOnFlag:this.isScreenSharingOn},t),this.removeLocalVideoStream(this.localVideoStream)}this.logger.error(t.message)}if(this.shallStopAudio(e)){let t=+new Date,n=K0();if(Z()?.calling?.allowMuteOnBadUfd&&!this.tsCall.isMuted){this.sendAudioEvent({eventName:Q.acs_calling_mute_on_ufd_attempt,timestampInfo:{attemptTimestamp:t},correlationId:n,step:`mid-call`});try{await this.mute()}catch{let t=`Failed to mute on microphone device not functioning or capture mute event ${e.type} with value ${e.value}`;this.logger.error(t)}}if(Z()?.calling?.preventStopAudio)return this.sendAudioEvent({eventName:Q.acs_calling_prevent_stop_audio,timestampInfo:{attemptTimestamp:t},correlationId:n,step:`mid-call`}),void(!Z()?.calling?.preventFakeMute&&this.markCallMuted());this.sendAudioEvent({eventName:Q.acs_calling_stop_audio_attempt,timestampInfo:{attemptTimestamp:t},correlationId:n,step:`mid-call`});try{await this.tsCall.stopAudio(),this.markCallMuted();let e=+new Date;this.sendAudioEvent({eventName:Q.acs_calling_stop_audio_success,timestampInfo:{deltaTimeInMs:e-t},correlationId:n,step:`mid-call`})}catch(r){let i=new Y({defaultError:J.CALL.STOP_AUDIO_ON_BAD_UFD,defaultErrorMessageArgs:[e.type,e.value],originalError:r});this.logger.error(i.message);let a=+new Date;this.sendAudioEvent({eventName:Q.acs_calling_stop_audio_failure,timestampInfo:{deltaTimeInMs:a-t},correlationId:n,step:`mid-call`},i)}}this.muteUnmuteOnMicrophoneNotFunctioningUfd(e),this.audioDidAutoRecover(e)&&(this._isDeviceNotFunctioningMuted=!1,this._handleMuteChanges())}catch{this.logger.error(`Failed to send ufd telemetry`)}}))),e.push(this.tsCall.on(`participantAdded`,(async e=>{this.logger.debug(`tsCall participant added`);let t=[];e.endpoints?.endpointDetails.forEach((e=>t.push(e.participantId))),t.length===0&&t.push(`remoteParticipantId unavailable`);let n=G2(e.id);if(this._isEnterpriseTeamsCall=this._isEnterpriseTeamsCall||n.kind===`microsoftTeamsUser`,this.sendParticipantAddedOrRemovedEvent({remoteParticipantIds:t,participantAddedOrRemoved:`added`,kindOfEvent:$.event}),I4(e))this.logger.info(`Add participant: Handle hidden calling application`);else{this.checkAndUpdateCopilotDisplayName(e),this._handleLocalRingingCallState(e);try{let t=this.getOrCreateRemoteParticipant(n,e);this._eventEmitter.emit(`remoteParticipantsUpdated`,{added:[t],removed:[]})}catch{this.logger.log(`unable to map call participant to ACS user`)}}}))),this.logger.debug(`tsCall current participant count=${this.tsCall?.participants?.length}`);let n=e=>{let t=G2(e.id);this._isEnterpriseTeamsCall=this._isEnterpriseTeamsCall||t.kind===`microsoftTeamsUser`;let n=this.getOrCreateRemoteParticipant(t,e);this._handleLocalRingingCallState(e),n.on(`displayNameChanged`,(()=>{this._callerIdentity&&W2(this._callerIdentity)===W2(n.identifier)&&(this._callerDisplayName=n.displayName,this._eventEmitter.emit(`callerInfoChanged`)),this._transferorIdentity&&W2(this._transferorIdentity)===W2(n.identifier)&&(this._transferorDisplayName=n.displayName,this._eventEmitter.emit(`transferorInfoChanged`))}))},r=[];this.tsCall.participants.forEach((e=>{Z().calling.checkHiddenBotOnCallStart&&I4(e)||n(e);try{e.endpoints?.endpointDetails.forEach((e=>r.push(e.participantId)))}catch{this.logger.error(`Unable to get participantId from from remote participant`)}}));try{this.sendParticipantAddedOrRemovedEvent({remoteParticipantIds:r,participantAddedOrRemoved:`added`,kindOfEvent:$.initialize})}catch{this.logger.error(`Unable to send participant added telemtery`)}return e.push(this.tsCall.on(`participantRemoved`,(async e=>{this.logger.debug(`tsCall participant removed`);let t=[];if(e.endpoints?.endpointDetails.forEach((e=>t.push(e.participantId))),t.length===0&&t.push(`remoteParticipantId unavailable`),I4(e))return this.logger.info(`Remove participant: Ignore calling application`),void this.sendParticipantAddedOrRemovedEvent({remoteParticipantIds:t,participantAddedOrRemoved:`removed`,kindOfEvent:$.event});let n=e.id;if(n){let r=this._remoteParticipants.find((e=>W2(e.identifier)===n));if(r){let{callEndReason:n}=H3(this,e);r.setCallEndReason(n),this.deleteRemoteParticipant(r),this._eventEmitter.emit(`remoteParticipantsUpdated`,{added:[],removed:[r]}),this.sendParticipantAddedOrRemovedEvent({remoteParticipantIds:t,participantAddedOrRemoved:`removed`,kindOfEvent:$.event,additionalDetails:{...q3(n)}})}else this.logger.log(`unable to find participant to remove`)}}))),e}_trackNetworkQualityUfdEventDetails(e){let t=+new Date,n=``;switch(e){case 5:n=n6;break;case 32:n=a6;break;case 2:n=r6;break;case 1:n=i6;break;case 37:n=o6}this._networkQualityUfdEventDetails.push({eventName:n,timestampInfo:t})}async muteUnmuteOnMicrophoneNotFunctioningUfd(e){try{let t=Z().calling;if(!t.muteUnmuteOnMicrophoneNotFunctioning||this._isMuted||e.type!==9||e.value!==3)return;this.__attemptedToRecoverMicNotFunctioningBySDK=!0,await this.mute(),t.unmuteDelayForMicrophoneNotFunctioningInMs>=0&&await t3(t.unmuteDelayForMicrophoneNotFunctioningInMs),await this.unmute()}catch(e){this.logger.info(`Unable to perform mute and unmute to recover microphoneNotFunctioning`,e)}finally{this.__attemptedToRecoverMicNotFunctioningBySDK=!1}}updateCallMode(){this.tsCall.callMode&&this._callMode!==this.tsCall.callMode&&(this.logger.log(`tsCall callMode changed from ${this._callMode} to ${this.tsCall.callMode}`),M7(this._telemetryLogManager,this.logger,{...j7(this,this._callAgent,K0(),this._joinContextDescription),step:`callMode-changed`,oldState:eDe[this._callMode],newState:eDe[this.tsCall.callMode]}),this._callMode=this.tsCall.callMode)}checkAndUpdateCopilotDisplayName(e){this.tsCall.meetingDetails&&(W2(e)!==m2||e.displayName!==``&&e.displayName!==void 0||(e.displayName=_2))}async startCallInternal(e,t,n,r,i,a){let o=!!e?.audioOptions?.muted,s=this.getLocalVideoStreamFromCallOptions(e),c=this.getLocalAudioStreamFromCallOptions(e),l,u=i?.attemptTimestamp??+new Date,d=K0();this._joinContextDescription=nTe(n);let f=this._callAgent.getEcsConfigIds(),p=this.tsCall.participants.length===1&&!this.tsCall.threadId&&!t,m=!!p||this._allowIPAudio,h=!!p||this._allowIPVideo,g=U6(this.tsCall),_=i?.correlationId??K0(),v=jG(_),y=this.createVideoNegotiationTag(_,`Video`),b={joinContextDescription:this._joinContextDescription,additionalProperties:{EmergencyCountryCode:this._callAgent._caConfigBag?.emergencyCountryCode||``,IsUserEmergencyCountryCode:this._callAgent._caConfigBag?.IsUserEmergencyCountryCode||!1,IsEmergencyCall:r?.isEmergency||!1,dialedEmergencyNumber:r?.isEmergency?this.tsCall.participants?.[0]?.id:void 0,trouterState:this._callAgent.getTrouterState(),muted:o,withVideo:h&&!!s,withAudio:m&&c?.mediaStreamType?c.mediaStreamType:``,...r7(),AcsCallingSDKWeb_ecsConfigId:f.AcsCallingSDKWeb,SkypeWebMedia_ecsConfigId:f.SkypeWebMedia,customContext:{userToUserPresent:!!e?.customContext?.userToUser,xHeadersPresent:!!e?.customContext?.xHeaders&&e.customContext.xHeaders.length>0},firstPartyOptions:{isDeviceTypeEnabled:Z().calling.setDeviceType,deviceType:this._callAgent.getDeviceType(),isImmersiveMode:e?.firstPartyOptions?.isImmersiveMode,accessToImmersiveEvents:e?.firstPartyOptions?.accessToImmersiveEvents},mediaModalities:this.getMediaModalityTelemetry(e?.mediaModalities),negotiationTag:y,causeId:v},additionalDetails:{}};e?.videoOptions?.constraints&&(b.additionalProperties.constraints=this._mediaConstraintsManager.getTelemetryPayload({video:e?.videoOptions?.constraints})),r?.meetingInfo?.tenantId&&(this._teamsMeetingTenantId=r.meetingInfo.tenantId,b.additionalProperties.teamsMeetingTenantId=r.meetingInfo.tenantId),r?.threadId&&(this._teamsMeetingThreadId=r.threadId,b.additionalProperties.teamsMeetingThreadId=r.threadId),r?.onBehalfOf&&(b.additionalProperties.onBehalfOfProvided=!0,b.additionalProperties.onBehalfOfIdKind=G2(r.onBehalfOf).kind,this.logger.info(`onBehalfOf provided kind: ${b.additionalProperties.onBehalfOfIdKind}`));let x={...b},S={...b};this.sendCallStageEvent({eventName:Q.acs_calling_call_attempt,correlationId:_,timestampInfo:{attemptTimestamp:u},additionalPayload:b},void 0,void 0,void 0,`attempt`);try{this._isMicrophoneMuted=o,e?.alternateCallerId&&(l=W2(e.alternateCallerId)),s&&this.setLocalVideoStream(s),this.setLocalAudioStream(c)}catch(e){a?.reject(e);let t=+new Date,n=new Y({defaultError:J.CALL.INSTANTIATE_CALL,originalError:e});throw x.additionalDetails.communicationServicesError=K3(n).communicationServicesError,this.sendCallStageEvent({eventName:Q.acs_calling_call_failed,correlationId:_,timestampInfo:{deltaTimeInMs:t-u},additionalPayload:x},n,void 0,void 0,`failure`),this.logger.error(n.message),n}let C=AG();F7.setCauseIdToNetworkInfo(C);try{let n={...r};!Z().calling.setDeviceType||this._callAgent.getDeviceType()!==`mesh`&&this._callAgent.getDeviceType()!==`meshV2`||(n.endpointMetadata=JSON.stringify({meshapp:!0})),g?(await this.tsCall.initAsync?.(n),a?.resolve()):this.tsCall.init(n),s&&this.sendVideoEvent({correlationId:d,eventName:Q.acs_calling_start_video_attempt,timestampInfo:{attemptTimestamp:u},localVideoStream:s,step:`start`,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:y,causeId:v}});try{if(e?.videoOptions?.constraints){let t=await this._mediaConstraintsManager.setVideoConstraints(e?.videoOptions?.constraints,`start`,d,u),n=this._mediaConstraintsManager.getTelemetryPayload({video:t});S.additionalProperties.constraints=n}}catch(e){let t=new Y({defaultError:J.CALL.CALLSTART_VIDEO_CONSTRAINTS,originalError:e});this.logger.error(`${t.message}`)}let i=this.setClientCallStartOptions(e);if(Z()?.calling?.enableCustomTurnUsage&&this.acsCustomRelayManager?.customRelayManagerInUse&&(i.mediaConfiguration={connectionType:`NoDirectConnection`}),o&&(i.muteFlags=1),e?.firstPartyOptions?.disableAudioMixing&&(i.muteFlags===void 0?i.muteFlags=2:i.muteFlags|=2),e?.firstPartyOptions?.enableSpatialAudio!==void 0&&(i.mediaConfiguration=i.mediaConfiguration||{},i.mediaConfiguration.enableSpatialAudio=e.firstPartyOptions.enableSpatialAudio,this._callAgent.tsStack?await this._callAgent.tsStack.setMediaConfig({enableSpatialAudio:e.firstPartyOptions.enableSpatialAudio}):this.logger.error(`Could not set enableSpatialAudio to ${e.firstPartyOptions.enableSpatialAudio} since this._callAgent.tsStack is null`)),i.customHeaderContext=V4(e),c&&await this.startAudioInternal(c,!0).catch((e=>{this.logger.error(`Failed to start localAudioStream, message=${e?.message}`)})),s?.mediaStreamType===`RawMedia`)try{await this._setRawStream(s,1)}catch(e){let t=+new Date,n=new Y({defaultError:J.LOCAL_VIDEO_STREAM.VIDEO_GET_MEDIA_STREAM,originalError:e});this.sendVideoEvent({correlationId:d,eventName:Q.acs_calling_media_stream,timestampInfo:{deltaTimeInMs:t-u},localVideoStream:s,step:`start`,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:y}},n),this.removeLocalVideoStream(s)}t?await this.tsCall.startWithMeetingData(C,{withVideo:!!s&&this.isIPVideoEnabled,muted:o,ringOthers:!0,alternateId:l,shouldResurrect:`resurrect`,...i}):(i.negotiationTag=this.createVideoNegotiationTag(_,`Video`),await this.tsCall.start({withVideo:!!s&&this.isIPVideoEnabled,muted:o,ringOthers:!0,alternateId:l,...i},C)),S.additionalProperties.negotiationTag=y,S.additionalProperties.causeId=v;let f=+new Date;this.sendCallStageEvent({eventName:Q.acs_calling_call_connected,correlationId:_,timestampInfo:{deltaTimeInMs:f-u},additionalPayload:S},void 0,void 0,F7.getRemoveCauseIdToNetworkInfo(C),`success`),c&&this.shallRemoveLasAfterConnectedSuccessfully(c,`start`,_,f,u),s&&this.shallRemoveLvsAfterConnectedSuccessfully(s,`start`,_,f,u,y,v),this._handleAudioEffectsOperations()}catch(e){a?.reject(e);let t=+new Date,{callEndReason:n,callingCommunicationError:r}=V3(this,e);if(s){let n=new Y({defaultError:J.LOCAL_VIDEO_STREAM.CALL_NOT_FOUND,originalError:e});this.sendVideoEvent({correlationId:d,eventName:Q.acs_calling_start_video_failure,timestampInfo:{deltaTimeInMs:t-u},localVideoStream:s,step:`start`,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:y,causeId:v}},n),this.removeLocalVideoStream(s)}throw c&&this.removeLocalAudioStream(c),x.additionalDetails.callEndReason=q3(n).callEndReason,x.additionalProperties.negotiationTag=y,x.additionalProperties.causeId=v,this.sendCallStageEvent({eventName:Q.acs_calling_call_failed,correlationId:_,timestampInfo:{deltaTimeInMs:t-u},additionalPayload:x},r,void 0,F7.getRemoveCauseIdToNetworkInfo(C),`failure`),this.logger.error(`Failed to start the call, message=${n?.message}, code=${n?.code}, subCode=${n?.subCode}, resultCategories=${n?.resultCategories}`),r}}getMediaModalityTelemetry(e){return e?{audio:e.audio,video:e.video,screenShare:e.screenShare}:void 0}getTopNDominantSpeakersWithVideoOn(){if(this._internalDominantSpeakersListener){let e=this._internalDominantSpeakersListener.dominantSpeakers.speakersList.map((e=>this._mriToRemoteParticipantMap.get(W2(e)))).filter((e=>!!e)).filter((e=>!!e.videoStreams.filter((e=>e.mediaStreamType===`Video`)).find((e=>e.tsStream.isAvailable))));if(this.logger.info(`There are currently ${e.length} top-n dominant speakers with video on in the large meeting where topCount is ${Z().rendering.remoteVideo.largeMeeting.dominantSpeakersWithVideoOn_topCount}`),e.length<Z().rendering.remoteVideo.largeMeeting.dominantSpeakersWithVideoOn_topCount){let t=this._remoteParticipants.filter((e=>!!e.videoStreams.filter((e=>e.mediaStreamType===`Video`)).find((e=>e.tsStream.isAvailable)))).filter((t=>!e.includes(t)));t.sort(((e,t)=>{let n=e.tsRemoteParticipant?.endpoints?.endpointDetails[0]?.mediaStreams?.filter((e=>e.type===`audio`)).map((e=>e.sourceId))??[],r=n.length>0?Math.min(...n):void 0,i=t.tsRemoteParticipant?.endpoints?.endpointDetails[0]?.mediaStreams?.filter((e=>e.type===`audio`)).map((e=>e.sourceId))??[],a=i.length>0?Math.min(...i):void 0;return r!==void 0&&a!=null?r-a:0}));for(let n of t){if(e.length===Z().rendering.remoteVideo.largeMeeting.dominantSpeakersWithVideoOn_topCount)break;e.push(n)}}else e.splice(Z().rendering.remoteVideo.largeMeeting.dominantSpeakersWithVideoOn_topCount);return e}return[]}getParticipantCapabilities(){let e=this._capabilityResolver.getCapabilities();return this.logger.log(`participant capabilities are ${e}`),e}getMeetingCapabilitiesInternal(){let e=this._capabilityResolver.getMeetingsCapabilitiesInternal();return this.logger.info(`meeting capabilities are ${e}`),e}feature(e){return this._extensibleApi.getApiObjectInstance(e.callApiCtor)}async hangUp(e){let t=+new Date,n=K0(),r=AG();return F7.setCauseIdToNetworkInfo(r),this.sendCallStageEvent({eventName:Q.acs_calling_call_hangup_attempt,correlationId:n,timestampInfo:{attemptTimestamp:t}}),this.tsCall.stop(e?.forEveryone,r).then((()=>{let e=+new Date;this.sendCallStageEvent({eventName:Q.acs_calling_call_hangup_success,correlationId:n,timestampInfo:{deltaTimeInMs:e-t}},void 0,void 0,F7.getRemoveCauseIdToNetworkInfo(r))})).catch((e=>{let i=+new Date,{callEndReason:a,callingCommunicationError:o,hasDiagnosticsInfo:s}=V3(this,e),c=this._callAgent.getEcsConfigIds(),l={additionalProperties:{EmergencyCountryCode:this._callAgent._caConfigBag?.emergencyCountryCode||``,IsUserEmergencyCountryCode:this._callAgent._caConfigBag?.IsUserEmergencyCountryCode||!1,IsEmergencyCall:this._isEmergencyCall,trouterState:this._callAgent.getTrouterState(),AcsCallingSDKWeb_ecsConfigId:c.AcsCallingSDKWeb,SkypeWebMedia_ecsConfigId:c.SkypeWebMedia},additionalDetails:{}};if(s)l.additionalDetails={...q3(a)};else{let t=new Y({defaultError:J.CALL.OPERATION_FAILED,originalError:e});l.additionalDetails.communicationServicesError=K3(t).communicationServicesError}throw this.sendCallStageEvent({eventName:Q.acs_calling_call_hangup_failure,correlationId:n,timestampInfo:{deltaTimeInMs:i-t},additionalPayload:l},o,void 0,F7.getRemoveCauseIdToNetworkInfo(r)),o}))}async mute(){let e=this.logger.createFnLogger(o4.Mute),t=+new Date,n=K0(),r=AG();F7.setCauseIdToNetworkInfo(r),this.sendAudioEvent({eventName:Q.acs_calling_mute_attempt,eventType:l3.MuteMicrophone,timestampInfo:{attemptTimestamp:t},correlationId:n,step:`mid-call`,initiatedBySdk:this.__attemptedToRecoverMicNotFunctioningBySDK});try{e.info(`mute`),await this.tsCall.mute(r),e.info(`mute success`);let i=+new Date;this.sendAudioEvent({eventName:Q.acs_calling_mute_success,eventType:l3.MuteMicrophone,timestampInfo:{deltaTimeInMs:i-t},correlationId:n,step:`mid-call`,initiatedBySdk:this.__attemptedToRecoverMicNotFunctioningBySDK,networkInfo:F7.getRemoveCauseIdToNetworkInfo(r)})}catch(i){let a=new Y({defaultError:J.CALL.MIC_MUTE,originalError:i});e.error(`Failed to mute microphone`);let o=+new Date;throw this.sendAudioEvent({eventName:Q.acs_calling_mute_failure,eventType:l3.MuteMicrophone,timestampInfo:{deltaTimeInMs:o-t},correlationId:n,step:`mid-call`,initiatedBySdk:this.__attemptedToRecoverMicNotFunctioningBySDK,networkInfo:F7.getRemoveCauseIdToNetworkInfo(r)},a),a}}async unmute(){let e=this.logger.createFnLogger(o4.Unmute),t=+new Date,n=K0(),r=!1,i=AG();if(F7.setCauseIdToNetworkInfo(i),this.sendAudioEvent({eventName:Q.acs_calling_unmute_attempt,eventType:l3.UnmuteMicrophone,timestampInfo:{attemptTimestamp:t},correlationId:n,step:`mid-call`,initiatedBySdk:this.__attemptedToRecoverMicNotFunctioningBySDK}),!this.isAudioPermitted()){let t=`cannot unmute as microphone is disabled`;throw e.error(t),new Y({defaultError:J.CALL.MIC_DISABLED,originalError:t})}if(!this.isIPAudioEnabled){let t=`cannot unmute as IP audio in Teams Meeting Policy is disabled`;throw e.error(t),new Y({defaultError:J.CALL.IP_AUDIO_NOT_ALLOWED,originalError:t})}if(this.explicitConsentStateImp.areCoreCapabilitiesConsentRestricted()){let t=`cannot unmute as consent is required to be recorded or transcribed`;throw e.error(t),new Y({defaultError:J.CALL.UNMUTE_CONSENT_RESTRICTED,originalError:t})}try{e.info(`unmute`),await this.tsCall.unmute(i),e.info(`unmute success`);let a=+new Date;this.sendAudioEvent({eventName:Q.acs_calling_unmute_success,eventType:l3.UnmuteMicrophone,timestampInfo:{deltaTimeInMs:a-t},correlationId:n,step:`mid-call`,initiatedBySdk:this.__attemptedToRecoverMicNotFunctioningBySDK,networkInfo:F7.getRemoveCauseIdToNetworkInfo(i)});let o=+new Date;if(!Z()?.calling?.preventStopAudio&&this._isDeviceNotFunctioningMuted){this.sendAudioEvent({eventName:Q.acs_calling_start_audio_attempt,timestampInfo:{attemptTimestamp:o},correlationId:n,step:`mid-call`,networkInfo:F7.getRemoveCauseIdToNetworkInfo(i)}),r=!0,e.info(`start audio`),await this.tsCall.startAudio(),e.info(`start audio success`);let t=+new Date;this._isDeviceNotFunctioningMuted=!1,this._handleMuteChanges(),this.sendAudioEvent({eventName:Q.acs_calling_start_audio_success,timestampInfo:{deltaTimeInMs:t-o},correlationId:n,step:`mid-call`,networkInfo:F7.getRemoveCauseIdToNetworkInfo(i)})}this.setLocalAudioStream()}catch(a){let o=r?J.CALL.MIC_UNMUTE_AND_STARTAUDIO:J.CALL.MIC_UNMUTE,s=new Y({defaultError:o,originalError:a});e.error(o.message);let c=+new Date;throw this.sendAudioEvent({eventName:r?Q.acs_calling_start_audio_failure:Q.acs_calling_unmute_failure,eventType:r?void 0:l3.UnmuteMicrophone,timestampInfo:{deltaTimeInMs:c-t},correlationId:n,step:`mid-call`,initiatedBySdk:this.__attemptedToRecoverMicNotFunctioningBySDK&&!r,networkInfo:F7.getRemoveCauseIdToNetworkInfo(i)},s),s}}async muteAllRemoteParticipants(){let e=Z();if(!e.calling.enableMuteOthers)throw new Y({defaultError:J.CALL.MUTE_ALL_PARTICIPANTS_DISABLED});if(!this.tsCall.conversationType&&this._callInfo.context===v4.TwoParty)throw new Y({defaultError:J.CALL.MUTE_ALL_PARTICIPANTS_1_TO_1_UNSUPPORTED});let t=this.logger.createFnLogger(o4.MuteAllRemoteParticipants),n=+new Date,r=K0();this.sendAudioEvent({eventName:Q.acs_calling_mute_attempt,eventType:l3.MuteAllRemoteParticipants,timestampInfo:{attemptTimestamp:n},correlationId:r,step:`mid-call`});try{t.info(`mute all others`),$5(o4.MuteAllRemoteParticipants,this.state);let i=[];if(this._remoteParticipants.length!==0){let n=!1,r=!1,a=``;if(this._remoteParticipants.map((o=>{let s=o.tsRemoteParticipant;e.calling.allowMutePstnRemoteParticipant||o.identifier.kind!==`phoneNumber`?[3,5].some((e=>e===s?.state))?s!==void 0&&(i.push(s),a+=W2(o.identifier)+`, `):(t.warn(`non-connected participants cannot be muted by others`),r=!0):(t.warn(`PSTN participants cannot be muted by others`),n=!0)})),i.length===0?t.error(`all remote participants are not supported to be muted by others`):(await this.tsCall.muteParticipants(1,i),t.info(`called mute function on the following participants: ${a}`)),n){if(!this._isTeamsExtensionUser||!Z().calling.teamsExtensionSettings.enableServerMutePSTNParticipant)throw new Y({defaultError:J.CALL.MUTE_ALL_PARTICIPANTS_PSTN_UNSUPPORTED});t.info(`Enable server muting of PSTN participant for TeamsExtension user`)}if(r)throw new Y({defaultError:J.CALL.MUTE_ALL_PARTICIPANTS_NONCONNECTED_UNSUPPORTED})}else t.info(`no participants to mute in attempt to mute all remote participants`);t.info(`mute all others success`);let a=+new Date;this.sendAudioEvent({eventName:Q.acs_calling_mute_success,eventType:l3.MuteAllRemoteParticipants,timestampInfo:{deltaTimeInMs:a-n},correlationId:r,step:`mid-call`})}catch(e){let i=new Y({defaultError:J.CALL.MUTE_ALL_PARTICIPANTS,originalError:e});t.error(i.message);let a=+new Date;throw this.sendAudioEvent({eventName:Q.acs_calling_mute_failure,eventType:l3.MuteAllRemoteParticipants,timestampInfo:{deltaTimeInMs:a-n},correlationId:r,step:`mid-call`},i),i}}async muteIncomingAudio(){let e=this.logger.createFnLogger(o4.MuteIncomingAudio),t=+new Date,n=K0();this.sendAudioEvent({eventName:Q.acs_calling_mute_attempt,eventType:l3.MuteIncomingAudio,timestampInfo:{attemptTimestamp:t},correlationId:n,step:`mid-call`});try{await this.tsCall.muteSpeaker();let e=+new Date;this.sendAudioEvent({eventName:Q.acs_calling_mute_success,eventType:l3.MuteIncomingAudio,timestampInfo:{deltaTimeInMs:e-t},correlationId:n,step:`mid-call`})}catch(r){let i=new Y({defaultError:J.CALL.MUTE_INCOMING_AUDIO,originalError:r});e.error(i.message);let a=+new Date;throw this.sendAudioEvent({eventName:Q.acs_calling_mute_failure,eventType:l3.MuteIncomingAudio,timestampInfo:{deltaTimeInMs:a-t},correlationId:n,step:`mid-call`},i),i}}async unmuteIncomingAudio(){let e=this.logger.createFnLogger(o4.MuteIncomingAudio),t=+new Date,n=K0();this.sendAudioEvent({eventName:Q.acs_calling_unmute_attempt,eventType:l3.UnmuteIncomingAudio,timestampInfo:{attemptTimestamp:t},correlationId:n,step:`mid-call`});try{await this.tsCall.unmuteSpeaker();let e=+new Date;this.sendAudioEvent({eventName:Q.acs_calling_unmute_success,eventType:l3.UnmuteIncomingAudio,timestampInfo:{deltaTimeInMs:e-t},correlationId:n,step:`mid-call`})}catch(r){let i=new Y({defaultError:J.CALL.UNMUTE_INCOMING_AUDIO,originalError:r});e.error(i.message);let a=+new Date;throw this.sendAudioEvent({eventName:Q.acs_calling_unmute_failure,eventType:l3.UnmuteIncomingAudio,timestampInfo:{deltaTimeInMs:a-t},correlationId:n,step:`mid-call`},i),i}}async sendDtmf(e){let t=tDe(e);return this.tsCall.sendDtmfTone(t).catch((e=>{throw this.logger.error(`Failed to send DTMF tone`),new Y({defaultError:J.CALL.DTMF_TONE})}))}async startVideo(e){let t=this.logger.createFnLogger(o4.StartVideo),n=+new Date,r=Z()?.calling?.preventStopAudio,i=K0(),a=jG(i),o=this.createVideoNegotiationTag(i,`Video`);if(this.sendVideoEvent({eventName:Q.acs_calling_start_video_attempt,timestampInfo:{attemptTimestamp:n},localVideoStream:e,correlationId:i,step:`mid-call`,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:o,causeId:a}}),!this.isVideoPermitted()){let e=`cannot start video as camera is disabled by the Presenter or Organizer of the meeting`;throw t.error(e),new Y({defaultError:J.CALL.CAMERA_DISABLED,originalError:e})}if(!this.isIPVideoEnabled){let e=`cannot start video as IP video is not allowed`;throw t.error(e),new Y({defaultError:J.CALL.IP_VIDEO_NOT_ALLOWED,originalError:e})}if(this.explicitConsentStateImp.areCoreCapabilitiesConsentRestricted()){let e=`cannot start video as consent is restricted`;throw t.error(e),new Y({defaultError:J.CALL.VIDEOSTART_CONSENT_RESTRICTED,originalError:e})}if(this._isDeviceNotFunctioningMuted&&!r){this.sendAudioEvent({eventName:Q.acs_calling_start_audio_attempt,timestampInfo:{attemptTimestamp:n},correlationId:i,step:`mid-call`});try{t.info(`start audio before starting video`),await this.tsCall.startAudio(),t.info(`start audio success before starting video`);let e=+new Date;this._isDeviceNotFunctioningMuted=!1,this._handleMuteChanges(),this.sendAudioEvent({eventName:Q.acs_calling_start_audio_success,timestampInfo:{deltaTimeInMs:e-n},correlationId:i,step:`mid-call`})}catch(e){let r=new Y({defaultError:J.CALL.START_AUDIO_BEFORE_VIDEO,originalError:e});t.error(`Failed to start audio before starting video`);let a=+new Date;throw this.sendAudioEvent({eventName:Q.acs_calling_start_audio_failure,timestampInfo:{deltaTimeInMs:a-n},correlationId:i,step:`mid-call`},r),r}}try{if(!e)throw new Y({defaultError:J.CALL.STREAM_NULL});if(!(e instanceof J6))throw new Y({defaultError:J.CALL.STREAM_IS_NOT_LVS});if(this.tsCall.isVideoOn)throw new Y({defaultError:J.CALL.VIDEO_ALREADY_ON});e?.mediaStreamType===`RawMedia`&&await this._setRawStream(e,1),this.setLocalVideoStream(e)}catch(t){let r=new Y({defaultError:J.CALL.START_VIDEO,originalError:t});throw this.sendVideoEvent({correlationId:i,eventName:Q.acs_calling_start_video_failure,timestampInfo:{attemptTimestamp:n},localVideoStream:e,step:`mid-call`,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:o,causeId:a}},r),r}F7.setCauseIdToNetworkInfo(a);try{t.info(`start video`),await this.tsCall.startVideo(o,a);let r=+new Date;this.sendVideoEvent({correlationId:i,eventName:Q.acs_calling_start_video_success,timestampInfo:{deltaTimeInMs:r-n},localVideoStream:e,step:`mid-call`,isScreenSharingOnFlag:this._isScreenSharingOn,networkInfo:F7.getRemoveCauseIdToNetworkInfo(a),additionalDetails:{negotiationTag:o,causeId:a}}),t.info(`video started`)}catch(r){let s=+new Date,c=U3(t,r);throw this.sendVideoEvent({correlationId:i,eventName:Q.acs_calling_start_video_failure,timestampInfo:{deltaTimeInMs:s-n},localVideoStream:e,step:`mid-call`,isScreenSharingOnFlag:this._isScreenSharingOn,networkInfo:F7.getRemoveCauseIdToNetworkInfo(a),additionalDetails:{negotiationTag:o,causeId:a}},c),this.removeLocalVideoStream(e),c}}async stopVideo(e){let t=this.logger.createFnLogger(o4.StopVideo),n=+new Date,r=K0(),i=jG(r),a=this.createVideoNegotiationTag(r,`Video`);this.sendVideoEvent({correlationId:r,eventName:Q.acs_calling_stop_video_attempt,timestampInfo:{attemptTimestamp:n},localVideoStream:e,step:`mid-call`,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:a,causeId:i}});let o=this.tsCall.state===4||this.tsCall.state===5;if(!o&&!this.tsCall.isVideoOn||o&&!this.localVideoStream){let t=new Y({defaultError:J.CALL.VIDEO_ALREADY_OFF});throw this.sendVideoEvent({correlationId:r,eventName:Q.acs_calling_stop_video_failure,timestampInfo:{attemptTimestamp:n},localVideoStream:e,step:`mid-call`,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:a,causeId:i}},t),t}if(this.localVideoStream!==void 0&&this.localVideoStream!==e){let t=new Y({defaultError:J.CALL.STOP_WRONG_STREAM});throw this.sendVideoEvent({correlationId:r,eventName:Q.acs_calling_stop_video_failure,timestampInfo:{attemptTimestamp:n},localVideoStream:e,step:`mid-call`,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:a,causeId:i}},t),t}let s=()=>{try{if(Z().calling.allowAccessRawMediaStream&&e.mediaStreamType===`RawMedia`){let e=this._callAgent.tsStack?.getDeviceManager();e&&e.unsetRawMediaStream&&e.unsetRawMediaStream(1)}}catch(e){this.logger.info(`Unset raw video stream: ${e?.message??`Unkown error`}`)}};F7.setCauseIdToNetworkInfo(i);try{t.info(`stop video`),await this.tsCall.stopVideo(a,i),s();let o=+new Date;this.sendVideoEvent({correlationId:r,eventName:Q.acs_calling_stop_video_success,timestampInfo:{deltaTimeInMs:o-n},localVideoStream:e,step:`mid-call`,isScreenSharingOnFlag:this._isScreenSharingOn,networkInfo:F7.getRemoveCauseIdToNetworkInfo(i),additionalDetails:{negotiationTag:a,causeId:i}}),t.info(`video stopped`),this.removeLocalVideoStream(e)}catch(o){s();let c=+new Date,l=U3(t,o,!0);throw this.sendVideoEvent({correlationId:r,eventName:Q.acs_calling_stop_video_failure,timestampInfo:{deltaTimeInMs:c-n},localVideoStream:e,step:`mid-call`,isScreenSharingOnFlag:this._isScreenSharingOn,networkInfo:F7.getRemoveCauseIdToNetworkInfo(i),additionalDetails:{negotiationTag:a,causeId:i}},l),l}}startAudio(e){return this.startAudioInternal(e)}stopAudio(){return this.stopAudioInternal()}async hold(){let e=+new Date,t=K0(),n=AG();F7.setCauseIdToNetworkInfo(n);try{this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:o4.Hold,kindOfEvent:$.attempt,timestampInfo:{deltaTimeInMs:e},additionalDetails:{holdType:b4.Standard,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn}}),Z().calling.turnOffScreenShareBeforeHold&&this.tsCall.isScreenSharingOn&&await this.tsCall.stopScreenSharing().then((()=>{this.logger.log(`Successfully turned off screen sharing before hold`)})).catch((()=>{this.logger.error(`Failed to turn off screensharing before hold`)})),await this.tsCall.hold(void 0,n),this.removeLocalAudioStream(this._localAudioStreams[0]);let r=+new Date;this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:o4.Hold,kindOfEvent:$.success,timestampInfo:{deltaTimeInMs:r-e},additionalDetails:{holdType:b4.Standard,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn},networkInfo:F7.getRemoveCauseIdToNetworkInfo(n)})}catch{let r=+new Date,i=new Y({defaultError:J.CALL.HOLD_CALL});throw this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:o4.Hold,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:r-e},additionalDetails:{failureReason:i.message,code:i.code,subCode:i.subCode,holdType:b4.Standard,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn,...K3(i)},networkInfo:F7.getRemoveCauseIdToNetworkInfo(n)}),i}}async resume(){let e=+new Date,t=K0(),n=AG();F7.setCauseIdToNetworkInfo(n);try{this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:o4.Resume,kindOfEvent:$.attempt,timestampInfo:{deltaTimeInMs:e},additionalDetails:{holdType:b4.Standard,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn}}),await this.tsCall.unhold(void 0,n),this.setLocalAudioStream();let r=+new Date;this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:o4.Resume,kindOfEvent:$.success,timestampInfo:{deltaTimeInMs:r-e},additionalDetails:{isScreenSharingOnFlag:this.tsCall.isScreenSharingOn,holdType:b4.Standard},networkInfo:F7.getRemoveCauseIdToNetworkInfo(n)})}catch{let r=+new Date,i=new Y({defaultError:J.CALL.RESUME_CALL});throw this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:o4.Resume,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:r-e},additionalDetails:{failureReason:i.message,code:i.code,subCode:i.subCode,holdType:b4.Standard,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn,...K3(i)},networkInfo:F7.getRemoveCauseIdToNetworkInfo(n)}),i}}async startScreenSharing(e){let t=this.logger.createFnLogger(o4.StartScreenShare),n=+new Date,r=K0(),i=jG(r),a=this.createVideoNegotiationTag(r,`ScreenSharing`);try{if(this.sendScreenShareEvent({eventName:Q.acs_calling_start_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:r,kindOfEvent:$.attempt,timestampInfo:``,isVideoOn:this._isLocalVideoStarted,localVideoStream:e,additionalDetails:{negotiationTag:a,causeId:i}}),this.tsCall.state!==3)throw new Y({defaultError:J.CALL.START_SS_CALL_NOT_CONNECTED});if(this.tsCall.isScreenSharingOn)throw new Y({defaultError:J.CALL.SS_ALREADY_ON});if(this.explicitConsentStateImp.areCoreCapabilitiesConsentRestricted()){let e=`screen sharing cannot be started as consent is required to be recorded or transcribed`;throw t.error(e),new Y({defaultError:J.CALL.SCREENSHARE_CONSENT_RESTRICTED,originalError:e})}if(e){if(!(e instanceof J6))throw new Y({defaultError:J.CALL.SS_RAW_STREAM_IS_NOT_LVS});if(e.mediaStreamType!==`RawMedia`)throw new Y({defaultError:J.CALL.SS_RAW_STREAM_LVS_IS_NOT_RAW_MEDIA});let t=await e.getMediaStream();if(!t||t.getVideoTracks().length===0)throw new Y({defaultError:J.CALL.SS_RAW_STREAM_IS_NOT_VALID_STREAM});if(!1===t.active)throw new Y({defaultError:J.CALL.SS_RAW_STREAM_IS_NOT_ACTIVE_STREAM});t.getTracks().forEach((e=>{e.stop()})),await this._setRawStream(e,2),this.localScreenSharingStream=e}else this.localScreenSharingStream=new J6(new L6(swe.ScreenSharing,K0(),swe.ScreenSharing,this._callAgent.deviceManager))}catch(e){let t=+new Date;this.removeScreenSharingStream();let o=new Y({defaultError:J.CALL.START_SS,originalError:e});throw this.sendScreenShareEvent({eventName:Q.acs_calling_start_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:r,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:t-n},additionalDetails:{failureReason:o.message,code:o.code,subCode:o.subCode,...K3(o),negotiationTag:a,causeId:i},isVideoOn:this._isLocalVideoStarted,localVideoStream:this.localScreenSharingStream}),o}return this.tsCall.startScreenSharing(void 0,void 0,a).then((()=>{let e=+new Date;this.localScreenSharingStream&&this._localVideoStreams.indexOf(this.localScreenSharingStream)===-1&&(this.localScreenSharingStream.addCall(this),this._localVideoStreams.push(this.localScreenSharingStream),this._eventEmitter.emit(`localVideoStreamsUpdated`,{added:[this.localScreenSharingStream],removed:[]})),this.sendScreenShareEvent({eventName:Q.acs_calling_start_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:r,kindOfEvent:$.success,timestampInfo:{deltaTimeInMs:e-n},isVideoOn:this._isLocalVideoStarted,localVideoStream:this.localScreenSharingStream,additionalDetails:{negotiationTag:a,causeId:i}})})).catch((e=>{let o=+new Date;this.removeScreenSharingStream();let s=U3(t,e);throw this.sendScreenShareEvent({eventName:Q.acs_calling_start_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:r,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:o-n},additionalDetails:{failureReason:s.message,code:s.code,subCode:s.subCode,...K3(s),negotiationTag:a,causeId:i},isVideoOn:this._isLocalVideoStarted,localVideoStream:this.localScreenSharingStream}),s}))}async stopScreenSharing(){let e=this.logger.createFnLogger(o4.StopScreenShare),t=+new Date,n=K0(),r=jG(n),i=this.createVideoNegotiationTag(n,`ScreenSharing`);if(this.sendScreenShareEvent({eventName:Q.acs_calling_stop_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:n,kindOfEvent:$.attempt,timestampInfo:``,isVideoOn:this._isLocalVideoStarted,localVideoStream:this.localScreenSharingStream,additionalDetails:{negotiationTag:i,causeId:r}}),this.tsCall.state!==3)throw new Y({defaultError:J.CALL.STOP_SS_CALL_NOT_CONNECTED});if(!this.tsCall.isScreenSharingOn){let e=+new Date,a=new Y({defaultError:J.CALL.SS_ALREADY_OFF});throw this.sendScreenShareEvent({eventName:Q.acs_calling_stop_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:n,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:e-t},additionalDetails:{failureReason:a.message,code:a.code,subCode:a.subCode,...K3(a),negotiationTag:i,causeId:r},isVideoOn:this._isLocalVideoStarted,localVideoStream:this.localScreenSharingStream}),a}return this.tsCall.stopScreenSharing(void 0,i).then((()=>{let e=+new Date,a=Q2.cloneDeep(this.localScreenSharingStream);this.removeScreenSharingStream(),this.sendScreenShareEvent({eventName:Q.acs_calling_stop_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:n,kindOfEvent:$.success,timestampInfo:{deltaTimeInMs:e-t},isVideoOn:this._isLocalVideoStarted,localVideoStream:a,additionalDetails:{negotiationTag:i,causeId:r}})})).catch((a=>{let o=+new Date,s=U3(e,a,!0),c=typeof s?.message==`string`?s?.message:void 0;throw this.sendScreenShareEvent({eventName:Q.acs_calling_stop_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:n,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:o-t},additionalDetails:{failureReason:c||``,code:s.code,subCode:s.subCode,...K3(s),negotiationTag:i,causeId:r},isVideoOn:this._isLocalVideoStarted,localVideoStream:this.localScreenSharingStream}),s}))}async setConstraints(e){let t=+new Date,n=K0();try{let r=await this._mediaConstraintsManager.setVideoConstraints(e?.video,`mid-call`,n,t);this.logger.info(`Video constraints set - ${JSON.stringify(r)}`)}catch(e){throw new Y({defaultError:J.CALL.SET_VIDEO_CONSTRAINTS,originalError:e})}}on(e,t){if(e!==`stateChanged`&&e!==`idChanged`&&e!==`isMutedChanged`&&e!==`isIncomingAudioMutedChanged`&&e!==`isScreenSharingOnChanged`&&e!==`isLocalVideoStartedChanged`&&e!==`remoteParticipantsUpdated`&&e!==`localVideoStreamsUpdated`&&e!==`localAudioStreamsUpdated`&&e!==`remoteAudioStreamsUpdated`&&e!==`totalParticipantCountChanged`&&e!==`roleChanged`&&e!==`mutedByOthers`&&e!==`callerInfoChanged`&&e!==`transferorInfoChanged`)throw new Y({defaultError:J.CALL.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if(e!==`stateChanged`&&e!==`idChanged`&&e!==`isMutedChanged`&&e!=`isIncomingAudioMutedChanged`&&e!==`isScreenSharingOnChanged`&&e!==`isLocalVideoStartedChanged`&&e!==`remoteParticipantsUpdated`&&e!==`localVideoStreamsUpdated`&&e!==`localAudioStreamsUpdated`&&e!==`remoteAudioStreamsUpdated`&&e!==`totalParticipantCountChanged`&&e!==`roleChanged`&&e!==`mutedByOthers`&&e!==`callerInfoChanged`&&e!==`transferorInfoChanged`)throw new Y({defaultError:J.CALL.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}onMeetingCapabilitiesChanged(e,t){if(e!==`meetingCapabilitiesChanged`)throw new Y({defaultError:J.CALL.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}offMeetingCapabilitiesChanged(e,t){if(e!=`meetingCapabilitiesChanged`)throw new Y({defaultError:J.CALL.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}onParticipantCapabilitiesChanged(e,t){this.logger.log(`participant capabilities change event listener registered`),this._eventEmitter.on(e,t)}offParticipantCapabilitiesChanged(e,t){this.logger.log(`participant capabilities change event listener unregistered`),this._eventEmitter.off(e,t)}setWatermarkAudioOnlyFallbackTriggered(e){this._watermarkAudioOnlyFallbackTriggered=e,this._eventEmitter.emit(`watermarkAudioOnlyFallbackTriggeredChanged`)}onWatermarkAudioOnlyFallbackTriggeredChanged(e,t){this.logger.log(`watermark audio only fallback triggered listener registered`),this._eventEmitter.on(e,t)}offWatermarkAudioOnlyFallbackTriggeredChanged(e,t){this.logger.log(`watermark audio only fallback triggered listener unregistered`),this._eventEmitter.off(e,t)}setIsRenderingRemoteScreenShare(e){this.isRenderingRemoteScreenShare!==e&&(this.isRenderingRemoteScreenShare=e,this._eventEmitter.emit(`isRenderingRemoteScreenShareChanged`))}onIsRenderingRemoteScreenShareChanged(e,t){this._eventEmitter.on(e,t)}offIsRenderingRemoteScreenShareChanged(e,t){this._eventEmitter.off(e,t)}getOrCreateRemoteParticipant(e,t){let n=this._remoteParticipants.find((t=>W2(t.identifier)===W2(e)));return n||(n=new A7(e,this.logger,this,this._callAgent,this._telemetryLogManager),this._remoteParticipants.push(n),this._mriToRemoteParticipantMap.set(W2(n.identifier),n)),t&&n.observeParticipant(t),n}deleteRemoteParticipant(e){let t=!0;return this._remoteParticipants.splice(this._remoteParticipants.indexOf(e),1).length!==1&&(this.logger.warn(`Deleted remote participant array is not 1`),t=!1),this._mriToRemoteParticipantMap.delete(W2(e.identifier))||(this.logger.warn(`Deleted remote participant was not found in mri-to-remoteparticipant map`),t=!1),t}sendCallOnHoldAndResumedEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:d2,properties:e})}catch{this.logger.debug(`Unable to send call hold or resume telemetry`)}}sendVideoEvent(e,t){try{let n,r;try{n=e.localVideoStream?.getStreamMetadata()}catch{this.logger.error(`Unable to get stream meta data on send video event`)}t&&(r=typeof t?.message==`string`?t?.message:void 0,(e.additionalDetails??{}).communicationServicesError=K3(t).communicationServicesError),this._telemetryLogManager.sendEvent({name:e.eventName,tenant:d2,properties:{...n,callId:this.id,localParticipantId:this.tsCall.participantId,timestampInfo:e.timestampInfo,correlationId:e.correlationId,step:e.step||``,failureReason:r||``,isScreenSharingOnFlag:e.isScreenSharingOnFlag,additionalDetails:e.additionalDetails||{},networkInfo:e.networkInfo||[]}})}catch{this.logger.debug(`Unable to send video telemetry`)}}sendScreenShareEvent(e){let t;try{t=e.localVideoStream?.getStreamMetadata()}catch{this.logger.error(`Unable to get stream meta data on send video event`)}try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:d2,properties:{...t,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:e.correlationId,kindOfEvent:e.kindOfEvent,timestampInfo:e.timestampInfo,additionalDetails:e.additionalDetails,isVideoOn:e.isVideoOn}})}catch{this.logger.debug(`Unable to send screen share telemetry`)}}sendRawMediaEvent(e){let t={...e};t.localAudioStream=e.localAudioStream?.source instanceof MediaStream?`MediaStream`:`Device`;try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:d2,properties:t})}catch{this.logger.debug(`Unable to send raw media telemetry`)}}sendAudioEvent(e,t){try{let n;t&&(n=typeof t?.message==`string`?t?.message:void 0,e.additionalDetails={...K3(t)});let r={callId:this.id,localParticipantId:this.tsCall.participantId,timestampInfo:e.timestampInfo,correlationId:e.correlationId,step:e.step||``,failureReason:n||``,additionalDetails:e.additionalDetails||{},networkInfo:e.networkInfo||[]};e.eventType!==void 0&&(r.eventType=e.eventType),e.initiatedBySdk&&(r.initiatedBySdk=!0),this._telemetryLogManager.sendEvent({name:e.eventName,tenant:d2,properties:r})}catch{this.logger.debug(`Unable to send audio telemetry`)}}sendCallStageEvent(e,t,n,r,i){try{let a,o=``;t&&(a=this?.tsCall?.callEndDiagnosticsInfo||n||{},o=t.message);let s=this._joinContextDescription===I2.RoomCall||this.kind===VG.Call&&this._direction===`Incoming`&&!this.tsCall.groupId&&!!this.tsCall.meetingData?.meetingCode&&!this.tsCall.threadId,c=!s&&this._joinContextDescription===I2.TeamsMeetingLink||this._joinContextDescription===I2.TeamsMeetingId||this._joinContextDescription===I2.TeamsCoordinates||this._direction==`Incoming`&&!this.tsCall.groupId&&!!this.tsCall.meetingData&&!!this.tsCall.threadId,l={localParticipantId:this?.tsCall?.participantId||``,callId:this?.tsCall?.callId||``,callType:this?.tsCall?.callType||``,callDirection:this._direction,failureReason:o,callEndDiagnosticsInfo:a,calleeIdentityType:this.getParticipantIdentityType(),groupJoin:!!this?.tsCall?.groupId,roomJoin:s,meetingJoin:c,hostRegion:this?.tsCall?.region||``,correlationId:e.correlationId,timestampInfo:e.timestampInfo,...e.additionalPayload,networkInfo:r||[],negotiationTag:e.additionalPayload?.additionalProperties.negotiationTag??``,causeId:e.additionalPayload?.additionalProperties.causeId??``};this._telemetryLogManager.sendEvent({name:e.eventName,tenant:d2,properties:l},void 0,i)}catch{}}getParticipantIdentityType(){if(this.tsCall?.participants.length>1)return U2.group;if(this.tsCall?.participants.length===0)return U2.unknown;let e=this.tsCall?.participants[0];return G2(e.id).kind}optimalVideoCountChanged(e,t){let n=this._optimalVideoCount,r=e||this.tsCall.optimalVideoCount,i=Z().telemetry.progressEvents.enableOvcChangedEvent;if(r&&n!==r&&i)try{M7(this._telemetryLogManager,this.logger,{...j7(this,this._callAgent,K0(),this._joinContextDescription),step:`optimalVideoCount-changed`,previousOptimalVideoCount:n,newOptimalVideoCount:r,changeReason:t,currentNumberOfVideosRendered:this.activeRemoteVideoStreamViews?.size||0})}catch{this.logger.error(`Failed to send optimal video count change telemetry`)}finally{this._optimalVideoCount=r??1}}_sendNetworkChangedTelemetry(){try{let e=(e,t,n)=>{M7(this._telemetryLogManager,this.logger,{...j7(this,this._callAgent,K0(),this._joinContextDescription),step:`network-changed`,trouterState:e,onLine:t,rdpState:n})};this._trouterStateChangedListener=t=>{e(t,navigator.onLine,this._mmrRdpConnectionManager.state)},this._callAgent.onTrouterStateChanged(this._trouterStateChangedListener),this._onlineListener=t=>{e(this._callAgent.getTrouterState(),!0,this._mmrRdpConnectionManager.state)},window.addEventListener(`online`,this._onlineListener),this._offlineListener=t=>{e(this._callAgent.getTrouterState(),!1,this._mmrRdpConnectionManager.state)},window.addEventListener(`offline`,this._offlineListener),this._mmrRdpConnectionManager.on(`stateChange`,(t=>{e(this._callAgent.getTrouterState(),!1,t)})),e(this._callAgent.getTrouterState(),navigator.onLine,this._mmrRdpConnectionManager.state)}catch{this.logger.warn(`Failed to subscribe to network changed`)}}_setupSelectedDeviceChangedTelemetry(){try{let e=e=>{M7(this._telemetryLogManager,this.logger,{...j7(this,this._callAgent,K0(),this._joinContextDescription),step:`selectedDevice-changed`,selectedDeviceType:e.selectedDeviceType,oldDevice:e.oldDevice,newDevice:e.newDevice})};if(this._selectedDeviceManager){this._selectedDeviceManager.on(`selectedDeviceChanged`,e);let t=this._selectedDeviceManager.selectedDevice(`Speaker`),n=this._selectedDeviceManager.selectedDevice(`Microphone`);e({selectedDeviceType:`Speaker`,oldDevice:void 0,newDevice:t}),e({selectedDeviceType:`Microphone`,oldDevice:void 0,newDevice:n})}}catch{this.logger.warn(`Failed to subscribe to selectedDevice changed`)}}setLocalVideoStream(e){if(!this._callAgent.tsStack)throw new Y({defaultError:J.CALL.VIDEO_UNDEFINED_STACK});if(!this.localVideoStream&&e&&!this._localVideoStreams.find((t=>t===e))){this.localVideoStream=e,this._localVideoStreams.push(this.localVideoStream),this.localVideoStream.mediaStreamType!==`RawMedia`&&this._callAgent.tsStack.getDeviceManager()?.selectDevices({camera:e.source.id}),this.localVideoStream.addCall(this);try{this._eventEmitter.emit(`localVideoStreamsUpdated`,{added:[this.localVideoStream],removed:[]})}catch{this.logger.warn(`Application threw on emit localVideoStreamsUpdated added`)}this.logger.log(`isLocalVideoStarted changed=true`),this._isLocalVideoStarted=!0,this._eventEmitter.emit(`isLocalVideoStartedChanged`)}}removeLocalVideoStream(e){if(this.localVideoStream&&e===this.localVideoStream&&this.localVideoStreams.find((e=>e===this.localVideoStream))){if(this.logger.log(`Attempting to remove local video stream`),this._localVideoStreams.splice(this._localVideoStreams.indexOf(this.localVideoStream),1).length===0)return void this.logger.warn(`Stream not found, failed to remove stream from localVideoStreams collection`);this.logger.log(`Local video stream removed successfully`),this.localVideoStream.removeCall(this),this.localVideoStream.autoDisposeOnCallEnd&&this.localVideoStream.dispose();let e=this.localVideoStream;this.localVideoStream=void 0;try{this._eventEmitter.emit(`localVideoStreamsUpdated`,{added:[],removed:[e]})}catch{this.logger.warn(`Application threw on emit localVideoStreamsUpdated removed`)}this.logger.log(`isLocalVideoStarted changed=false`),this._isLocalVideoStarted=!1,this._eventEmitter.emit(`isLocalVideoStartedChanged`)}}setLocalAudioStream(e){if(!this._callAgent.tsStack)throw new Y({defaultError:J.CALL.LOCAL_AUDIO_UNDEFINED_STACK});if(e)e.on(`audioSourceChanged`,this.audioSourceChanged),this._localAudioStreams.push(e),e.addCall(this),this._eventEmitter.emit(`localAudioStreamsUpdated`,{added:[e],removed:[]});else if(this._localAudioStreams.length===0){if(this._userProvidedLocalAudioStreamCache)return(e=this._userProvidedLocalAudioStreamCache).on(`audioSourceChanged`,this.audioSourceChanged),this._localAudioStreams.push(e),e.addCall(this),void this._eventEmitter.emit(`localAudioStreamsUpdated`,{added:[e],removed:[]});let t=this.deviceManager?.selectedMicrophone;if(t){let e=new u8(t);e.on(`audioSourceChanged`,this.audioSourceChanged),this._localAudioStreams.push(e),e.addCall(this),this._eventEmitter.emit(`localAudioStreamsUpdated`,{added:[e],removed:[]})}else this.logger.warn(`Could not get current selected microphone to update localAudioStreams collection`)}else this.logger.warn(`No localAudioStream provided and the collection is not empty, doing nothing`)}removeLocalAudioStream(e){if(e){if(this.logger.log(`Attempting to remove local audio stream`),e.off(`audioSourceChanged`,this.audioSourceChanged),e.autoDisposeOnCallEnd&&e.dispose(),this._localAudioStreams.splice(this._localAudioStreams.indexOf(e),1).length===0)return void this.logger.warn(`Stream not found, failed to remove stream from localAudioStreams collection`);e.removeCall(this),this.logger.log(`Local audio stream removed successfully`),this._eventEmitter.emit(`localAudioStreamsUpdated`,{added:[],removed:[e]})}}_handleAudioEffectsOperations(){try{let e=this._localAudioStreams?.[0];if(!e)return void this.logger.debug(`No LocalAudioStream found in the call, cannot handle call audio effects operations`);this._audioEffectsStatsListener=e=>{this._audioEffectsProcessorStats=e},e.feature(Z5.AudioEffects)?.on(`effectsProcessorStatsUpdated`,this._audioEffectsStatsListener)}catch(e){this.logger.warn(`Error handling audio effects operations during call start: ${e}`)}}isAudioPermitted(){return!!this.feature(Z5.MediaAccess)?.getLocalParticipantMediaAccess().isAudioPermitted}isVideoPermitted(){return!!this.feature(Z5.MediaAccess)?.getLocalParticipantMediaAccess().isVideoPermitted}removeScreenSharingStream(){if(this.localScreenSharingStream&&this.localVideoStreams.find((e=>e===this.localScreenSharingStream))){if(Z()?.calling?.allowAccessRawMediaStream&&this.localScreenSharingStream?.mediaStreamType===`RawMedia`){let e=this._callAgent.tsStack?.getDeviceManager();e?.unsetRawMediaStream&&e.unsetRawMediaStream(2)}this.localScreenSharingStream.dispose(),this.localScreenSharingStream.removeCall(this);let e=this._localVideoStreams.indexOf(this.localScreenSharingStream);this._localVideoStreams.splice(e,1);let t=this.localScreenSharingStream;this.localScreenSharingStream=void 0,this._isScreenSharingOn=!1,this._eventEmitter.emit(`localVideoStreamsUpdated`,{added:[],removed:[t]})}}mapTsCallState(e){let t=$Ee[e];switch(t){case`Unknown`:case void 0:this.logger.log(`Ignored tsCall state \`${e}\``);break;case`Disconnected`:{this._callEndReason=V3(this).callEndReason,this._remoteParticipants.forEach((e=>{e.setCallEndReason(H3(this,e.tsRemoteParticipant).callEndReason),e.setParticipantState(`Disconnected`)}));let n=this._remoteParticipants.map((e=>e));this._remoteParticipants=[],this._mriToRemoteParticipantMap.clear(),this._eventEmitter.emit(`remoteParticipantsUpdated`,{added:[],removed:n}),this.localVideoStream&&this.removeLocalVideoStream(this.localVideoStream),this.localAudioStreams[0]&&this.removeLocalAudioStream(this.localAudioStreams[0]),this._rawAudioStreamChangedSubscription?.dispose&&this._rawAudioStreamChangedSubscription.dispose(),Z().calling.allowAccessRawMediaStream&&this.remoteAudioStreams[0]&&this.removeRemoteAudioStream(this.remoteAudioStreams[0]),this._userProvidedLocalAudioStreamCache=void 0,this.logger.log(`Mapped tsCall state:${e} to ${t}`),this._setCallState(t),this._telemetryLogManager.flushAllEvents(this.id).then((()=>{this.logger.log(`Telemetry flushed`)})).catch((e=>{this.logger.warn(`Failed to flush telemetry log manager events`)}));break}case`Connected`:this.logger.log(`Mapped tsCall state:${e} to ${t}`),this._remoteParticipantsChangedListeners.forEach((e=>{e.dispose()})),this._setCallState(t),this._setOrUpdateDeviceEventsTask=this._setOrUpdateDeviceEventsTask.then((()=>this.setOrUpdateMediaMetricsDeviceEvents().catch(A4))),Z().calling.allowAccessRawMediaStream&&this.subscribeToGetRemoteAudioStream();break;case`Incoming Call`:{this.logger.log(`state changed from ${this._state} to 'Incoming Call'`);let e=new P7(this.tsCall,{config:this._config});M7(this._telemetryLogManager,this.logger,{...j7(this,this._callAgent,K0(),this._joinContextDescription),step:`state-changed`,oldState:this._state,newState:`Incoming Call`,callTypeInfo:{initiatorKind:e.initiatorKind,targetKind:e.targetKind,transferor:e.transferorKind,context:e.context,callScenario:e.callScenario,direction:e.direction},teamsMeetingTenantId:this._teamsMeetingTenantId||``,teamsMeetingThreadId:this._teamsMeetingThreadId||``,callDurationInSeconds:this.tsCall.callStartedAt?Math.floor((Date.now()-this.tsCall.callStartedAt?.getTime())/1e3):-1});break}default:this.logger.log(`Mapped tsCall state:${e} to ${t}`),this._setCallState(t)}}shallStopVideo(e){let t=Z()?.calling?.deviceNotFunctioningMuted,n=Z()?.calling?.deviceCaptureMutedVideo,r=Z()?.calling?.preventStopVideo,i=e.type===25&&e.value===3,a=i&&e.mediaType===1,o=e.type===33&&e.value===3,s=t8(),c=n8()===`ios`&&s.engine===`Safari`,l=n8()===`android`,u=this.tsCall.state===3;return r?u&&this.tsCall.isVideoOn&&o:t&&u&&this.tsCall.isVideoOn&&(o||c&&i||n&&l&&a)}shallRemoveLocalVideoStreamOnBadUfd(e){let t=this.tsCall.localMediaStreams.find((e=>e.mediaType===1)),n=e.mediaType===1&&e.value===3&&e.type===25,r=this.tsCall.state==4||this.tsCall.state===5;if(t8().formFactor===`Mobile`&&(n||document.visibilityState==`hidden`)&&this.localVideoStream&&r&&!t||!Z()?.calling?.removeLvsCheckOnCallStartAndCallAccept)return!1;let i=this.tsCall.state===3;return e.mediaType===1&&e.value===3&&(e.type===33||e.type===25||e.type===34)&&!!this.localVideoStream&&!i&&!t}shallStopAudio(e){let t=Z()?.calling?.deviceNotFunctioningMuted,n=Z()?.calling?.osAutoRecoverAudio,r=e.type===25&&e.value===3&&e.mediaType===0,i=e.type===9&&e.value===3,a=t8(),o=n8()===`ios`&&a.engine===`Safari`,s=this.tsCall.state===3;return n?t&&s&&i:t&&!this._isDeviceNotFunctioningMuted&&s&&(i||o&&r)}markCallMuted(){this._isDeviceNotFunctioningMuted=!0,this._handleMuteChanges()}audioDidAutoRecover(e){let t=Z()?.calling?.deviceCaptureMuteRecover&&!Z()?.calling?.preventFakeMute,n=e.type===25&&e.value===1&&e.mediaType===0,r=this.tsCall.state===3,i=t8(),a=n8()===`ios`&&i.engine===`Safari`,o=e.type===9&&e.value===1;return t&&this._isDeviceNotFunctioningMuted&&r&&(o||a&&n)}sendParticipantAddedOrRemovedEvent(e){try{this._telemetryLogManager.sendEvent({name:Q.acs_calling_participant_added_or_removed,tenant:d2,properties:{callId:this.id,remotePerticipantId:Array.isArray(e?.remoteParticipantIds)?e?.remoteParticipantIds.slice(0,Z().telemetry.maxExistingReportedParticipants):[],participantAddedOrRemoved:e.participantAddedOrRemoved,localParticipantId:this.tsCall.participantId,kindOfEvent:e.kindOfEvent,correlationId:e.correlationId||``,timestampInfo:e.timestampInfo||``,additionalDetails:e.additionalDetails||{},networkInfo:e.networkInfo||[]}})}catch{this.logger.debug(`Unable to send participant added or removed telemtery`)}}_handleLocalRingingCallState(e){this._state===`Connected`||this._direction!==`Outgoing`||this._localRingingStateSet||this._remoteParticipantsChangedListeners.push(e.changed((()=>{e.state!==2||this._state===`Connected`||this._localRingingStateSet||(this._setCallState(`Ringing`),this._localRingingStateSet=!0,this._remoteParticipantsChangedListeners.forEach((e=>{e.dispose()})))})))}_setCallState(e){if(e!==this._state){let t=this._state,n=e,r=new P7(this.tsCall,{config:this._config});this.logger.log(`state changed from ${t} to ${n}`),this._state=n,n===`Connected`&&(this._connectedTimestamp=Date.now()),this._eventEmitter.emit(`stateChanged`),M7(this._telemetryLogManager,this.logger,{...j7(this,this._callAgent,K0(),this._joinContextDescription),step:`state-changed`,oldState:t,newState:n,callTypeInfo:{initiatorKind:r.initiatorKind,targetKind:r.targetKind,transferor:r.transferorKind,context:r.context,callScenario:r.callScenario,direction:r.direction},teamsMeetingTenantId:this._teamsMeetingTenantId||``,teamsMeetingThreadId:this._teamsMeetingThreadId||``,callDurationInSeconds:this.tsCall.callStartedAt?Math.floor((Date.now()-this.tsCall.callStartedAt?.getTime())/1e3):-1,additionalDetails:this._state===`Disconnected`&&this._callEndReason?{...q3(this._callEndReason)}:void 0})}}_setCallRole(e){if(e!==this._lastTsCallAdvancedMeetingRole){let t=iTe(Z(),e);t===w2?this.logger.log(`tsParticipant advancedMeetingRole=${this._role} had no mapping`):this.logger.log(`mapped tsParticipant advancedMeetingRole=${e}=>${t}`),M7(this._telemetryLogManager,this.logger,{...j7(this,this._callAgent,K0(),this._joinContextDescription),step:`role-changed`,oldAcsRole:this._role,newAcsRole:t,serviceRole:e||``}),this._role!=t&&(this.logger.log(`self-role changed ${this._role}=>${e}`),this._role=t,this._lastTsCallAdvancedMeetingRole=e,this._capabilityResolver.resolveCapabilitiesBasedOnRole(),this._eventEmitter.emit(`roleChanged`))}}_setMeetingCapabilities(e){oTe(e,this._lastTsCallMeetingDetails)&&(M7(this._telemetryLogManager,this.logger,{...j7(this,this._callAgent,K0(),this._joinContextDescription),step:`meetingCapabilities-changed`,oldMeetingDetails:this._lastTsCallMeetingDetails,newMeetingDetails:e}),this.logger.log(`Core Meeting Capabilities has changed to: ${JSON.stringify(e)}`),this._capabilityResolver.resolveCapabilitiesBasedOnMeetingCapabilities(),this._eventEmitter.emit(`meetingCapabilitiesChanged`)),Object.assign(this._lastTsCallMeetingDetails,e)}removeRemoteAudioStream(e){if(e){if(this.logger.log(`Attempting to remove remote audio stream`),this._remoteAudioStreams.splice(this._remoteAudioStreams.indexOf(e),1).length===0)return void this.logger.warn(`Stream not found, failed to remove stream from remoteAudioStreams collection`);this.logger.log(`remote audio stream removed successfully`),this._eventEmitter.emit(`remoteAudioStreamsUpdated`,{added:[],removed:[e]})}}async setOrUpdateMediaMetricsDeviceEvents(){if(Z().calling.mediaMetricsDeviceEventsEnabled)try{let e=await this.tsCall.getMediaSessionStatsAsync?.();if(e?.metrics?.DeviceEvents!==void 0){let t=JSON.parse(e.metrics.DeviceEvents),n=rTe(this._mediaMetricsDeviceEvents||{},t);n.length>0&&(this._mediaMetricsDeviceEvents=t,this.stats.recordEvent({name:s3.media_metrics_device_events,callId:this.id,localParticipantId:this.tsCall.participantId,data:{metricsDeviceEvents:n||{},metricsDevicesChangeCount:t?.metrics_DevicesChangeCount||0,metricsDevicesCount:t?.metrics_DevicesCount||{}}}))}else this.logger.info(`Failed to set media metrics device events telemetry: no valid events data`)}catch{this.logger.error(`Failed to set media metrics device events telemetry`)}}setClientCallStartOptions(e){let t={},n=0;return e?.firstPartyOptions?.isImmersiveMode&&(n|=32768),e?.firstPartyOptions?.accessToImmersiveEvents&&(n|=2097152),Z()?.calling?.supportLiveStreaming&&(n|=32),Z()?.calling.sharedLineAppearance.enabled&&(n|=128),Z()?.reaction?.enableReactionsThroughNGC&&(n|=524288),this._allowBreakoutRoomJoin&&(n|=4098),n>0&&(t.clientEndpointCapabilities=n),t.sendMediaModalities=this.setMediaModalities(e?.mediaModalities),t}setMediaModalities(e){if(e){let t={mediaStates:[]};return e.audio&&t.mediaStates.push({mediaType:0}),e.video?t.mediaStates.push({mediaType:1}):t.mediaStates.push({mediaType:1,isDisabled:!0}),e.screenShare||t.mediaStates.push({mediaType:2,isDisabled:!0}),t}}getLocalVideoStreamFromCallOptions(e){let t;if(Array.isArray(e?.videoOptions?.localVideoStreams)){if(e?.videoOptions?.localVideoStreams.length!==1)throw new Y({defaultError:J.CALL.ONLY_SINGLE_VIDEO_STREAM});if(t=e?.videoOptions?.localVideoStreams[0],!(t instanceof J6))throw new Y({defaultError:J.CALL.NOT_INSTANCE_OF_LVS})}return t}getLocalAudioStreamFromCallOptions(e){let t;if(Array.isArray(e?.audioOptions?.localAudioStreams)){if(e?.audioOptions?.localAudioStreams.length!==1)throw new Y({defaultError:J.CALL.ONLY_SINGLE_AUDIO_STREAM});if(t=e?.audioOptions?.localAudioStreams[0],!(t instanceof u8))throw new Y({defaultError:J.CALL.NOT_INSTANCE_OF_LAS})}return t&&(this._userProvidedLocalAudioStreamCache=t),t}async _setRawStream(e,t){if(!Z().calling.allowAccessRawMediaStream)throw new Y({defaultError:J.CALL.ACCESS_RAW_MEDIA_STREAM_DISABLED});let n=await this._callAgent.tsStack?.getDeviceManagerAsync?.();if(!n?.setRawMediaStream)throw new Y({defaultError:J.CALL.ACCESS_RAW_MEDIA_STREAM_UNDEFINED_FUNC});try{let r=await e.getMediaStream();if(!r)throw new Y({defaultError:J.CALL.SS_RAW_STREAM_UNDEFINED});n.setRawMediaStream(r,t)}catch(e){if(t===1)throw new Y({defaultError:J.CALL.VIDEO_SET_MEDIA_STREAM,originalError:e});if(t===2)throw new Y({defaultError:J.CALL.SS_RAW_STREAM_SET,originalError:e})}}shallRemoveLvsAfterConnectedSuccessfully(e,t,n,r,i,a,o){if(this.tsCall.localMediaStreams.find((e=>e.mediaType===1)))this.sendVideoEvent({correlationId:n,eventName:Q.acs_calling_start_video_success,timestampInfo:{deltaTimeInMs:r-i},localVideoStream:e,step:t,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:a,causeId:o}});else{if(!Z()?.calling?.removeLvsCheckOnCallStartAndCallAccept)return;this.localVideoStream&&this.removeLocalVideoStream(this.localVideoStream);let r=+new Date,s=new Y({defaultError:J.CALL.VIDEO_FAILED_TO_START,defaultErrorMessageArgs:[t]});this.logger.error(s.message),this.sendVideoEvent({correlationId:n,eventName:Q.acs_calling_start_video_failure,timestampInfo:{deltaTimeInMs:r-i},localVideoStream:e,step:t,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:a,causeId:o}},s)}}shallRemoveLasAfterConnectedSuccessfully(e,t,n,r,i){if(this.tsCall.localMediaStreams.find((e=>e.mediaType===0)))this.sendRawMediaEvent({eventName:Q.acs_calling_start_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:n,kindOfEvent:$.success,localAudioStream:e,timestampInfo:{deltaTimeInMs:r-i},additionalDetails:``});else{if(!Z().calling.removeLocalAudioStreamCheckOnCallStartAndCallAccept)return;this.removeLocalAudioStream(this.localAudioStreams[0]);let r=+new Date;this.logger.error(`Removing local audio stream because audio failed to start during call-${t} process.`);let a=new Y({defaultError:J.CALL.AUDIO_FAILED_TO_START,defaultErrorMessageArgs:[t]});this.sendRawMediaEvent({eventName:Q.acs_calling_start_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:n,localAudioStream:e,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:r-i},additionalDetails:{failureReason:a.message||``,code:a.code,subCode:a.subCode,...K3(a)}})}}createVideoNegotiationTag(t,n){let r=0,i=``;return n===`Video`?(r=++e.videoId,i=`v`):(r=++e.screenShareVideoId,i=`ss`),`${t};${i}_${r}`}_enableOrDisable_largeMeeting_videoRendering(){try{!this._isHandlingLargeMeetingVideoRendering&&this._totalParticipantCount-1>=Z().rendering.remoteVideo.largeMeeting.participantCountThreshold?(this._isHandlingLargeMeetingVideoRendering=!0,this._internalDominantSpeakersListener=new VDe(new S6(this.logger.createChild((()=>`DominanSpeakersFeatureInternal:: Call(id=${this.tsCall.callId})`)))),this._internalDominantSpeakersListener.initialize(this.tsCall,this._callAgent,this._telemetryLogManager,this.logger,!0),this.logger.info(`Initialized internal dominant speakers listener`),this._internalDominantSpeakersListener.on(`dominantSpeakersChanged`,(()=>{this.handleDominantSpeakersVideos()})),this.handleDominantSpeakersVideos(),this.logger.info(`Initialized large meeting video rendering handler`)):this._isHandlingLargeMeetingVideoRendering&&(this._totalParticipantCount-1>=Z().rendering.remoteVideo.largeMeeting.participantCountThreshold?this.handleDominantSpeakersVideos():(this._isHandlingLargeMeetingVideoRendering=!1,this._internalDominantSpeakersListener?.dispose(),this._internalDominantSpeakersListener=void 0,this.logger.info(`Disposed of internal dominant speakers listener`),this.remoteParticipants.forEach((e=>{e.videoStreams.forEach((e=>{e.setIsAvailable(e.tsStream.isAvailable)}))})),this.logger.info(`All remote streams isAvailable flags were reset`),this.logger.info(`Disposed large meeting video rendering handler`)))}catch(e){this.logger.error(`Failed to handle large meeting video rendering`,e)}}async handleConsentCapabilitiesChanges(){this.explicitConsentStateImp.areCoreCapabilitiesConsentRestricted()&&(this.isMuted||this.mute().then((()=>{this.logger.log(`ExplicitConsentCallStateManager: Handle Capabilities changes: Mic is turned off :`,this.isMuted)})).catch((e=>{this.logger.error(`ExplicitConsentCallStateManager: Handle Capabilities changes: Error stopping mic`,e)})),this.isLocalVideoStarted&&this.localVideoStream&&this.stopVideo(this.localVideoStream).then((()=>{this.logger.log(`ExplicitConsentCallStateManager: Handle Capabilities changes: Video is turned off :`,this.isLocalVideoStarted)})).catch((e=>{this.logger.error(`ExplicitConsentCallStateManager: Handle Capabilities changes: Error stopping video`,e)})),this.isScreenSharingOn&&this.stopScreenSharing().then((()=>{this.logger.log(`ExplicitConsentCallStateManager: Handle Capabilities changes: Screenshare is turned off :`,this.isScreenSharingOn)})).catch((e=>{this.logger.error(`ExplicitConsentCallStateManager: Handle Capabilities changes: Error stopping screenshare`,e)})))}handleDominantSpeakersVideos(){this.logger.info(`Dominant speakers changed during large meeting`);let e=this.getTopNDominantSpeakersWithVideoOn();this.logger.info(`There are currently ${e.length} top-n speakers with video on in the large meeting`),e.forEach((e=>{e.videoStreams.filter((e=>e.mediaStreamType===`Video`)).forEach((e=>{e.setIsAvailable(e.tsStream.isAvailable)}))})),this._remoteParticipants.filter((t=>!e.includes(t))).forEach((e=>{e.videoStreams.filter((e=>e.mediaStreamType===`Video`)).forEach((e=>{try{e.setIsAvailable(!1)}catch(e){let t=new Y({defaultError:J.CALL.LARGE_MEETING_FORCE_ISAVAILABLE,originalError:e});this.logger.warn(t.message)}let t=this.activeRemoteVideoStreamViews.get(e.id);t&&t.forEach((e=>{try{e.disposed||(e.dispose(b3.Internal_LargeMeetingVideoRendering),this.logger.info(`Successfully disposed of view during large meeting`))}catch(e){let t=new Y({defaultError:J.CALL.LARGE_MEETING_DISPOSE_VIEW,originalError:e});this.logger.warn(t.message)}}))}))}))}};R7.videoId=0,R7.screenShareVideoId=0,I7([zG,L7(`design:type`,Object)],R7.prototype,`logger`,void 0),I7([WG(o4.BindToCall),L7(`design:type`,Function),L7(`design:paramtypes`,[]),L7(`design:returntype`,Array)],R7.prototype,`bindTsCall`,null),I7([WG(o4.Feature),L7(`design:type`,Function),L7(`design:paramtypes`,[Object]),L7(`design:returntype`,typeof(tLe=typeof TFeature<`u`&&TFeature)==`function`?tLe:Object)],R7.prototype,`feature`,null),I7([GG(o4.HangUp),L7(`design:type`,Function),L7(`design:paramtypes`,[Object]),L7(`design:returntype`,Promise)],R7.prototype,`hangUp`,null),I7([GG(o4.Mute),L7(`design:type`,Function),L7(`design:paramtypes`,[]),L7(`design:returntype`,Promise)],R7.prototype,`mute`,null),I7([GG(o4.Unmute),L7(`design:type`,Function),L7(`design:paramtypes`,[]),L7(`design:returntype`,Promise)],R7.prototype,`unmute`,null),I7([GG(o4.MuteAllRemoteParticipants),L7(`design:type`,Function),L7(`design:paramtypes`,[]),L7(`design:returntype`,Promise)],R7.prototype,`muteAllRemoteParticipants`,null),I7([GG(o4.MuteIncomingAudio),L7(`design:type`,Function),L7(`design:paramtypes`,[]),L7(`design:returntype`,Promise)],R7.prototype,`muteIncomingAudio`,null),I7([GG(o4.UnmuteIncomingAudio),L7(`design:type`,Function),L7(`design:paramtypes`,[]),L7(`design:returntype`,Promise)],R7.prototype,`unmuteIncomingAudio`,null),I7([GG(o4.SendDtmf),L7(`design:type`,Function),L7(`design:paramtypes`,[String]),L7(`design:returntype`,Promise)],R7.prototype,`sendDtmf`,null),I7([GG(o4.StartVideo),L7(`design:type`,Function),L7(`design:paramtypes`,[J6]),L7(`design:returntype`,Promise)],R7.prototype,`startVideo`,null),I7([GG(o4.StopVideo),L7(`design:type`,Function),L7(`design:paramtypes`,[J6]),L7(`design:returntype`,Promise)],R7.prototype,`stopVideo`,null),I7([GG(o4.StartAudio),L7(`design:type`,Function),L7(`design:paramtypes`,[u8]),L7(`design:returntype`,Promise)],R7.prototype,`startAudio`,null),I7([KG(o4.Hold),GG(o4.Hold),L7(`design:type`,Function),L7(`design:paramtypes`,[]),L7(`design:returntype`,Promise)],R7.prototype,`hold`,null),I7([KG(o4.Resume),GG(o4.Resume),L7(`design:type`,Function),L7(`design:paramtypes`,[]),L7(`design:returntype`,Promise)],R7.prototype,`resume`,null),I7([GG(o4.StartScreenShare),L7(`design:type`,Function),L7(`design:paramtypes`,[J6]),L7(`design:returntype`,Promise)],R7.prototype,`startScreenSharing`,null),I7([GG(o4.StopScreenShare),L7(`design:type`,Function),L7(`design:paramtypes`,[]),L7(`design:returntype`,Promise)],R7.prototype,`stopScreenSharing`,null),I7([GG(o4.SetConstraints),L7(`design:type`,Function),L7(`design:paramtypes`,[Object]),L7(`design:returntype`,Promise)],R7.prototype,`setConstraints`,null);var nLe=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},z7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},B7=class extends R7{get info(){return this._info}constructor(e,t,n,r,i){super(e,t,n,r,VG.Call,i),this._info=this.callInfo,this._allowBreakoutRoomJoin=Z().calling.breakoutRooms.enabled}dispose(){super.dispose(),this._extensibleApi.dispose()}addParticipant(e,t){let n,r,i=t,a=t,o=t,s=+new Date,c=K0();if(this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.attempt,participantAddedOrRemoved:`add`,correlationId:c,timestampInfo:{attemptTimestamp:s},additionalDetails:{customContext:{userToUserPresent:!!i?.customContext?.userToUser,xHeadersPresent:!!i?.customContext?.xHeaders&&i?.customContext.xHeaders.length>0}}}),this._callAgent.isEnterpriseUser())switch(this.validateThreadId(e,t),wG(e).kind){case`communicationUser`:r=i.threadId;break;case`microsoftTeamsUser`:r=o.threadId;break;case`phoneNumber`:r=a.threadId;break;default:{let e=new Y({defaultError:J.CALL.ADD_UNKNOWN});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`add`,correlationId:c,timestampInfo:{deltaTimeInMs:+new Date-s},additionalDetails:{code:e.code,failureReason:e.message,...K3(e)}}),e}}let l;a?.alternateCallerId&&(q2(a.alternateCallerId),n=W2(a.alternateCallerId));try{if($5(o4.AddParticipant,this.state),l=q2(e),!R4(this.acsProxy,this.acsCustomRelayManager,!1,l))throw new Y({defaultError:J.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN})}catch(e){throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`add`,correlationId:c,timestampInfo:{deltaTimeInMs:+new Date-s},additionalDetails:{code:e.code,failureReason:e.message,...K3(e)}}),e}if(this._remoteParticipants.find((t=>W2(t.identifier)===W2(e)))){let t=new Y({defaultError:J.CALL.PARTICIPANT_ALREADY_IN_CALL,defaultErrorMessageArgs:[wG(e).kind]});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`add`,correlationId:c,timestampInfo:{deltaTimeInMs:+new Date-s},additionalDetails:{code:t.code,failureReason:t.message,...K3(t)}}),t}let u=[...this.remoteParticipants.values()].map((e=>e.identifier));this._isAcsTeamsCall=z4([...u,e],this._callAgent.kind),Z().calling.enableSmePassFakeConversation&&this._isAcsTeamsCall&&!r&&(r=this.tsCall.threadId||B4());let d=sTe(lTe(this),wG(e));Z().calling.enableOpsSmePassFakeConversation&&d&&!r&&(r=this.tsCall.threadId||B4());let f=AG();F6.setCauseIdToNetworkInfo(f);let p=this.getOrCreateRemoteParticipant(G2(W2(e)));return this.tsCall.addParticipant(W2(e),{alternateId:n,threadId:r,customHeaderContext:V4(a)},f).then((()=>{this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.success,participantAddedOrRemoved:`add`,correlationId:c,timestampInfo:{deltaTimeInMs:+new Date-s},networkInfo:F6.getRemoveCauseIdToNetworkInfo(f)})})).catch((t=>{let{callEndReason:n}=H3(this,p.tsRemoteParticipant,t);p.callEndReason||p.setCallEndReason(n);let r=q3(n);this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`add`,correlationId:c,timestampInfo:{deltaTimeInMs:+new Date-s},additionalDetails:{code:r?.callEndReason.code,subCode:r?.callEndReason.subCode,failureReason:r?.callEndReason.message,...r},networkInfo:F6.getRemoveCauseIdToNetworkInfo(f)}),this._remoteParticipants.find((t=>W2(t.identifier)===W2(e)))&&(this.deleteRemoteParticipant(p),this._eventEmitter.emit(`remoteParticipantsUpdated`,{added:[],removed:[p]}))})),p}async removeParticipant(e,t){let n=+new Date,r=K0();this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.attempt,participantAddedOrRemoved:`remove`,correlationId:r,timestampInfo:{attemptTimestamp:n}});try{$5(o4.RemoveParticipant,this.state),q2(e)}catch(e){let t=new Y({defaultError:J.IDENTIFIER.PARSE_INVALID_IDENTIFIER,originalError:e});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`remove`,correlationId:r,timestampInfo:{deltaTimeInMs:+new Date-n},additionalDetails:{code:e.code,failureReason:e.message,...K3(t)}}),t}let i=this._remoteParticipants.find((t=>W2(t.identifier)===W2(e)));if(!i){let t=new Y({defaultError:J.CALL.PARTICIPANT_NOT_IN_CALL,defaultErrorMessageArgs:[wG(e).kind]});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`remove`,correlationId:r,timestampInfo:{deltaTimeInMs:+new Date-n},additionalDetails:{code:t.code,subCode:t.subCode,failureReason:t.message,...K3(t)}}),t}let a=AG();F6.setCauseIdToNetworkInfo(a);try{await this.tsCall.removeParticipant(W2(e)),this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.success,participantAddedOrRemoved:`remove`,correlationId:r,timestampInfo:{deltaTimeInMs:+new Date-n},networkInfo:F6.getRemoveCauseIdToNetworkInfo(a)})}catch(e){let t=H3(this,i.tsRemoteParticipant,e).callEndReason;i.callEndReason||i.setCallEndReason(t);let o=q3(t);throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`remove`,correlationId:r,timestampInfo:{deltaTimeInMs:+new Date-n},additionalDetails:{code:o?.callEndReason.code,subCode:o?.callEndReason.subCode,failureReason:o?.callEndReason.message,...o},networkInfo:F6.getRemoveCauseIdToNetworkInfo(a)}),new Y({defaultError:{message:t.message,code:t.code,subCode:t.subCode||0,resultCategories:t.resultCategories},originalError:e})}}validateThreadId(e,t){if(!t?.threadId)throw new Y({defaultError:J.CALL.CTE_ADDPARTICIPANT_NO_THREAD_ID})}};nLe([WG(o4.AddParticipant),z7(`design:type`,Function),z7(`design:paramtypes`,[Object,Object]),z7(`design:returntype`,Object)],B7.prototype,`addParticipant`,null),nLe([GG(o4.RemoveParticipant),z7(`design:type`,Function),z7(`design:paramtypes`,[Object,Object]),z7(`design:returntype`,Promise)],B7.prototype,`removeParticipant`,null);var rLe=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},V7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},H7=class{get kind(){return this._kind}get id(){return this._callCommon.id}get callerInfo(){return this._callCommon.callerInfo}get transferorInfo(){return this._callCommon.transferorInfo}get callEndReason(){return this._callCommon.callEndReason}get customContext(){return this._customContext}constructor(e,t){this._callCommon=e,this._eventEmitter=new w3.EventEmitter,this._kind=t,this._callConnected=this._callCommon.state===`Connected`,this._customContext=fTe(this._callCommon.tsCall),this._callCommon.on(`stateChanged`,(()=>{this._callCommon.state===`Connected`?this._callConnected=!0:this._callCommon.state!==`Disconnected`||this._callConnected||this._eventEmitter.emit(`callEnded`,{callEndReason:this._callCommon.callEndReason})})),this._callCommon.on(`callerInfoChanged`,(()=>{this._eventEmitter.emit(`callerInfoChanged`)})),this._callCommon.on(`transferorInfoChanged`,(()=>{this._eventEmitter.emit(`transferorInfoChanged`)}))}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}reject(){return this._callCommon.reject()}};rLe([GG(),V7(`design:type`,Function),V7(`design:paramtypes`,[]),V7(`design:returntype`,Promise)],H7.prototype,`reject`,null);var iLe=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},U7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},aLe=class extends H7{get info(){return this._call.info}constructor(e){super(e,HG.IncomingCall),this._call=e}async accept(e){if(this.info?.initiatorKind===`microsoftTeamsUser`&&!R4(this._call.acsProxy,this._call.acsCustomRelayManager,!0))throw new Y({defaultError:J.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN});return await this._call.accept(e),this._call}};iLe([GG(o4.Accept),U7(`design:type`,Function),U7(`design:paramtypes`,[Object]),U7(`design:returntype`,Promise)],aLe.prototype,`accept`,null);var W7={callNotification:`callNotification`,conversationInvitation:`conversationInvitation`,debugContent:`debugContent`,groupContext:`groupContext`},oLe=class{get callId(){return this._callId}get localParticipantId(){return this._localParticipantId}constructor(e,t,n){if(this._callId=``,this._localParticipantId=``,this._logger=n.createChild(`IncomingCallPushNotificationHandler`),!e.incomingCallContext)throw new Y({defaultError:J.CALL_AGENT.INCOMING_PUSH_NOTIFICATION_INVALID_PAYLOAD_NO_CONTEXT_PROVIDED});if(Object.keys(e).length>1)throw new Y({defaultError:J.CALL_AGENT.INCOMING_PUSH_NOTIFICATION_PAYLOAD_TOO_MANY_KEYS});if(this._payload=e,this._incomingCallContext=this._payload.incomingCallContext,this._tsCallRegistry=t,this._gp=JSON.parse($4.inflate(atob(this._incomingCallContext),{to:`string`})),!(this._gp.hasOwnProperty(W7.callNotification)&&this._gp.hasOwnProperty(W7.conversationInvitation)&&this._gp.hasOwnProperty(W7.debugContent)&&this._gp.hasOwnProperty(W7.groupContext)))throw this._logger.error(`Missing incoming call context data. Found: ${Object.keys(this._gp)}`),new Y({defaultError:J.CALL_AGENT.INCOMING_PUSH_NOTIFICATION_INVALID_PAYLOAD});this._callId=this._gp.debugContent.callId,this._localParticipantId=this._gp.debugContent.participantId}async process(){try{if(this._tsCallRegistry.calls.some((e=>e.callId==this._callId)))throw new Y({defaultError:J.CALL_AGENT.INCOMING_PUSH_NOTIFICATION_ALREADY_PROCESSED});let e=e3(),t=t=>{let n=()=>{t.callId===this._callId&&t.participantId===this._localParticipantId&&t.state===1&&e.resolve()};this._tsCallStateSub=t.on(`callStateChanged`,n),n()};this._tsCallRegistrySub=this._tsCallRegistry.on(`callAdded`,t);let n={eventId:ZCe,body:{gp:this._gp}};if(!this._tsCallRegistry.incomingCallMessageHandler.handleMessage(n))throw new Y({defaultError:J.CALL_AGENT.INCOMING_PUSH_NOTIFICATION_FAILED_TO_PROCESS});setTimeout((()=>{e.isPending()&&e.reject(new Y({defaultError:J.CALL_AGENT.INCOMING_PUSH_NOTIFICATION_CALL_MISSED}))}),5e3),await e.promise}catch(e){throw e}finally{this._tsCallRegistrySub?.dispose(),this._tsCallStateSub?.dispose()}}},G7=0,sLe=220004,cLe=220005,lLe=220006,uLe=220007,dLe=class{constructor(e){this._httpRequestHelper=e,this._isPolicyFetchApplicable=!1,this._policySettingData={},this._threadIdData={};let t=KW(`ACS`);this._logger=new z6(t)}initialize(e){this._localParticipant=e.localParticipant,this._jwtTokenProvider=e.jwtTokenProvider,this._telemetryLogManager=e.telemetryLogManager}userDialedNumber(e){this._userDialedPstnNumber=e,this._emergencyNumber=this._userDialedPstnNumber}async CreateChatThreadId(e,t){this._callId=e;let n=+new Date,r=t?.createThreadIdSuffix??Z().MiddleTier.serverManagedThreadIdApiConfiguration.createThreadSuffix;this.sendMiddleTierApiEvent({eventName:Q.acs_calling_middletier_gateway_api,suffix:r,kindOfEvent:$.attempt});let i=await this.getAcsMiddletierServiceRequestHeaderForThreadApi(),a=new URL(r,Z().MiddleTier.baseServiceUrl);t?.participants.push({id:this._localParticipant});let o={Participants:t?.participants};try{let e=await this._httpRequestHelper.send(a.toString(),o,{method:F3.POST,headers:i},Z().MiddleTier.maxRetry);if(this._threadIdData=await this._httpRequestHelper.extractPayload(e),!this._threadIdData)throw Error(`ThreadIdData is null or undefined`);return this._logger.info(`Successfully created chat thread using ACS MiddleTier Service.`),this.sendMiddleTierApiEvent({eventName:Q.acs_calling_middletier_gateway_api,suffix:r,kindOfEvent:$.success,timestampInfo:{deltaTimeInMs:new Date().getTime()-n},additionalDetails:{phrase:`Thread Id was successfully created from ACS MiddleTier Service`,code:G7,subCode:lLe}}),Promise.resolve(this._threadIdData.threadId)}catch{this._logger.error(`Error creating thread Id from ACS MiddleTier Service`);let e=new Y({defaultError:J.CTE_MID_TIER_POLICY_SERVICE.CREATETHREAD_FAILED});throw this.sendMiddleTierApiEvent({eventName:Q.acs_calling_middletier_gateway_api,suffix:r,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:new Date().getTime()-n},additionalDetails:{failureReason:e.message,code:e.code,subCode:e.subCode,...K3(e)}}),e}}async AddParticipantsToThread(e,t){this._callId=e;let n=+new Date,r=t?.addParticipantsSuffix??Z().MiddleTier.serverManagedThreadIdApiConfiguration.addParticipantSuffix;this.sendMiddleTierApiEvent({eventName:Q.acs_calling_middletier_gateway_api,suffix:r,kindOfEvent:$.attempt});let i=await this.getAcsMiddletierServiceRequestHeaderForThreadApi(),a=new URL(r,Z().MiddleTier.baseServiceUrl),o={threadId:t?.threadId,Participants:t?.participants};try{let e=await this._httpRequestHelper.send(a.toString(),o,{method:F3.POST,headers:i},Z().MiddleTier.maxRetry),t=await this._httpRequestHelper.extractPayload(e);if(!t)throw Error(`AddParticipantToThreadResponseData is null or undefined`);if(this._logger.info(`Call to add participants to chat thread using ACS MiddleTier Service`),t!==null){if(!t.isSuccess)throw new Y({defaultError:J.CTE_MID_TIER_POLICY_SERVICE.ADD_PARTICIPANTS_TO_THREAD_FAILED});t.multipleStatus.length>0&&t.multipleStatus[0].statusCode==735&&this._logger.info(`Trying to add the same participant to the thread id`)}return this.sendMiddleTierApiEvent({eventName:Q.acs_calling_middletier_gateway_api,suffix:r,kindOfEvent:$.success,timestampInfo:{deltaTimeInMs:new Date().getTime()-n},additionalDetails:{phrase:`Successfully add participants from ACS MiddleTier Service`,code:G7,subCode:uLe}}),Promise.resolve(t.isSuccess)}catch{this._logger.error(`Fail to add participant error from ACS MiddleTier Service`);let e=new Y({defaultError:J.CTE_MID_TIER_POLICY_SERVICE.ADD_PARTICIPANTS_TO_THREAD_FAILED});throw this.sendMiddleTierApiEvent({eventName:Q.acs_calling_middletier_gateway_api,suffix:r,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:new Date().getTime()-n},additionalDetails:{failureReason:e.message,code:e.code,subCode:e.subCode,...K3(e)}}),e}}async fetchUserPoliciesFromAcsMiddleTier(e,t,n){this._policySettingData=await this.requestUserPoliciesFromAcsMiddleTier(e,t,n)}async requestUserPoliciesFromAcsMiddleTier(e,t,n,r){this._callId=e;let i=+new Date;if(this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_fetch_policy,kindOfEvent:$.attempt},t),!t){let e=new Y({defaultError:J.CTE_MID_TIER_POLICY_SERVICE.TEAMS_USER_ID_NOT_PROVIDED});throw this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_fetch_policy,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:new Date().getTime()-i},additionalDetails:{failureReason:e.message,code:e.code,subCode:e.subCode,...K3(e)}}),e}let a,o={},s=Z().MiddleTier.baseServiceUrl;n?(a=new URL(n.policyUrlSuffix,s),o={id:t,dialstring:this._userDialedPstnNumber,userPolicies:n.userPolicies,userProperties:n.userProperties}):(a=new URL(Z().MiddleTier.policyUrlSuffix,s),o={id:t});let c=await this.getAcsMiddletierServiceRequestHeaderForThreadApi(r);try{let e=await this._httpRequestHelper.send(a.toString(),o,{method:F3.POST,headers:c},Z().MiddleTier.maxRetry);this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_fetch_policy,kindOfEvent:$.success,timestampInfo:{deltaTimeInMs:new Date().getTime()-i},additionalDetails:{phrase:`Teams user policy was fetched successfully from ACS MiddleTier Service`,code:G7,subCode:sLe}},t);let n=await this._httpRequestHelper.extractPayload(e);if(!n)throw Error(`PolicySettingsData is null or undefined`);return n}catch(e){let n=iDe(e,J.CTE_MID_TIER_POLICY_SERVICE.FETCH_POLICY);throw this._logger.error(n.message),this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_fetch_policy,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:new Date().getTime()-i},additionalDetails:{failureReason:n.message,code:n.code,subCode:n.subCode,...K3(n)}},t),n}}isEvEnabled(){return this._policySettingData?.userAggregatedPolicySettingData?.userProperties?.evEnabled||!1}isMoHEnabled(){let e=this._policySettingData?.userAggregatedPolicySettingData?.userPolicies?.teamsCallingPolicy?.musicOnHoldEnabledType;return this._logger.info(`Checking Music on Hold Policy, Enabled Type is: `+e),e===(y4.Enabled||y4.UserOverride)}isBreakoutRoomsAllowed(){let e=this._policySettingData?.userAggregatedPolicySettingData?.userPolicies?.teamsMeetingPolicy?.allowBreakoutRooms;return this._logger.info(`Allow Breakout rooms from Teams meeting policy is `+e),e??=!0,e}isIPAudioAllowed(){if(!Z().calling.mediaAccess.ipMediaPolicyEnabled)return this._logger.info(`Allow IP audio is true as feature flag ipAudioVideoPolicyEnabled is false`),!0;let e=this._policySettingData?.userAggregatedPolicySettingData?.userPolicies?.teamsMeetingPolicy?.ipAudioMode!==x4.Disabled;return this._logger.info(`Allow IP audio from Teams meeting policy is `+e),e}isIPVideoAllowed(){if(!Z().calling.mediaAccess.ipMediaPolicyEnabled)return this._logger.info(`Allow IP video is true as feature flag ipAudioVideoPolicyEnabled is false`),!0;let e=this._policySettingData?.userAggregatedPolicySettingData?.userPolicies?.teamsMeetingPolicy?.ipVideoMode!==x4.Disabled;return this._logger.info(`Allow IP video from Teams meeting policy is `+e),e}getTeamsUserCaptionsPoliciesData(){let e=+new Date,t=``;this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_fetch_user_policies_for_captions,kindOfEvent:$.attempt});let n=this._policySettingData.userAggregatedPolicySettingData,r=n?.userPolicies,i=n?.userProperties;if(!r?.teamsCallingPolicy){let t=new Y({defaultError:J.CTE_MID_TIER_POLICY_SERVICE.TEAMSUSER_CALLINGPOLICY_FETCHING_FAILED});this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_fetch_user_policies_for_captions,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:new Date().getTime()-e},additionalDetails:{failureReason:t.message,code:t.code,subCode:t.subCode,...K3(t)}})}if(!r?.teamsMeetingPolicy){let t=new Y({defaultError:J.CTE_MID_TIER_POLICY_SERVICE.TEAMSUSER_MEETINGPOLICY_FETCHING_FAILED});this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_fetch_user_policies_for_captions,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:new Date().getTime()-e},additionalDetails:{failureReason:t.message,code:t.code,subCode:t.subCode,...K3(t)}})}if(!i?.featureTypes){let t=new Y({defaultError:J.CTE_MID_TIER_POLICY_SERVICE.TEAMSUSER_FEATURETYPE_TEAMSPROMGMT_FETCHING_FAILED});this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_fetch_user_policies_for_captions,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:new Date().getTime()-e},additionalDetails:{failureReason:t.message,code:t.code,subCode:t.subCode,...K3(t)}})}return(r?.teamsCallingPolicy||r?.teamsMeetingPolicy||i?.featureTypes?.includes(V2.TeamsProMgmt))&&(t=JSON.stringify({isLiveCaptionsEnabledForCalling:r?.teamsCallingPolicy?.liveCaptionsEnabledTypeForCalling===H2.DisabledUserOverride,isLiveCaptionsEnabledForMeeting:r?.teamsMeetingPolicy?.liveCaptionsEnabledType===H2.DisabledUserOverride,isTeamsProMgmtSkuAvailable:i?.featureTypes?.includes(V2.TeamsProMgmt)??!1}),this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_fetch_user_policies_for_captions,kindOfEvent:$.success,timestampInfo:{deltaTimeInMs:new Date().getTime()-e},additionalDetails:{phrase:`Fetching Captions policy from ACS MiddleTier Service response was successful`,code:G7}}),this._logger.info(`Fetching user's captions policy content = ${t}`)),t}getEmergencyContent(){let e=+new Date;this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_emergency_content,kindOfEvent:$.attempt});let t=``;try{let n=this._policySettingData.userAggregatedPolicySettingData,r=n?.userPolicies,i=this.getEmergencyPolicyDetails(r,this._userDialedPstnNumber,n);i.foundEmergencyNumberMatch&&(t=JSON.stringify(i.emergencyContent));let a=i.foundEmergencyNumberMatch?`Created Emergency policy using ${i.logInfo}`:`This is NOT an emergency call`;return this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_emergency_content,kindOfEvent:$.success,timestampInfo:{deltaTimeInMs:new Date().getTime()-e},additionalDetails:{phrase:`Deriving Emergency policy from ACS MiddleTier Service response was successful`,code:G7,subCode:cLe}}),this._logger.info(`Deriving emergency policy message = ${a}. Emergency Content = ${t}`),t}catch(t){let n=new Y({defaultError:J.CTE_MID_TIER_POLICY_SERVICE.DERIVE_EMERGENCY_POLICY,originalError:t});throw this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_emergency_content,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:new Date().getTime()-e},additionalDetails:{failureReason:n.message,code:n.code,subCode:n.subCode,...K3(n)}}),n}}isEmergencyNumber(e,t){if(!t)return this._logger.info(`Not an emergency number, no participants`),!1;if(!this.isFetchUserPoliciesAndSettingsApplicable(e,t))return this._logger.info(`Fetch user policies and settings not applicable`),!1;let n=Array.isArray(t)&&t.length>0?t[0].phoneNumber:t.phoneNumber,r=this._policySettingData.userAggregatedPolicySettingData,i=r?.userPolicies,a=this.getEmergencyPolicyDetails(i,n,r);return this._logger.info(`Emergency number check result: ${a.foundEmergencyNumberMatch}`),a.foundEmergencyNumberMatch}getEmergencyPolicyDetails(e,t,n){let r=!1,i=``,a={};if(e?.locationPolicy?.emergencyNumbers){let o=e.locationPolicy.emergencyNumbers||[];this.isPhoneNumberInLocationPolicy(o,t)&&(r=!0,a={enableSecurityMemberNotifications:this.isSecurityDeskEnabled(),callerLocation:n?.userProperties.region,locationPolicyTag:e?.locationPolicy?.policyDocument,teamsEmergencyCallingPolicyTag:e?.teamsEmergencyCallingPolicy?.policyDocument},i=`LocationPolicy`)}if(!r&&e?.teamsEmergencyCallRoutingPolicy){let o=e?.teamsEmergencyCallRoutingPolicy?.emergencyNumbers||[];this.isPhoneNumberInTeamsEmergenencyRoutingPolicy(o,t)&&(r=!0,a={enableSecurityMemberNotifications:this.isSecurityDeskEnabled(),callerLocation:n?.userProperties.region,teamsEmergencyCallRoutingPolicyTag:e?.teamsEmergencyCallRoutingPolicy?.policyDocument,teamsEmergencyCallingPolicyTag:e?.teamsEmergencyCallingPolicy?.policyDocument},i=`TeamsEmergencyCallingRoutingPolicy`)}return{foundEmergencyNumberMatch:r,logInfo:i,emergencyContent:a}}isFetchUserPoliciesAndSettingsApplicable(e,t){return t4(e)||t4(t)||(this._isPolicyFetchApplicable=this.verifyFetchUserPoliciesSettings(e,t)),this._isPolicyFetchApplicable}getEmergencyNumber(){return this._emergencyNumber}getUserDialedPstnNumber(){return this._userDialedPstnNumber}getUserPolicy(){return this._policySettingData.userAggregatedPolicySettingData?.userPolicies}getUserProperties(){return this._policySettingData.userAggregatedPolicySettingData?.userProperties}isPhoneNumberInLocationPolicy(e,t){if(!t4(e)&&t){for(let n of e)if(n.dialString===t||!t4(n.dialMask?.split(`;`).find((e=>e===t))))return this._emergencyNumber=n.dialString,!0}return!1}isPhoneNumberInTeamsEmergenencyRoutingPolicy(e,t){if(!t4(e&&t)){for(let n of e)if(n.emergencyDialString===t||!t4(n.emergencyDialMask?.split(`;`).find((e=>e===t))))return this._emergencyNumber=n.emergencyDialString,!0}return!1}verifyFetchUserPoliciesSettings(e,t){let n=Z().MiddleTier;return n.enabled?n.userPolicySettingsApi?e?Array.isArray(t)&&(t.length>1||!xG(t[0]))?(this._logger.info(`Target particpant (Callee) is not a PSTN Number`),!1):Array.isArray(t)||xG(t)?(this._logger.info(`Teams user is eligible to fetch policies and settings from MiddleTier Service `),!0):(this._logger.info(`Target particpant (Callee) is not a PSTN Number`),!1):(this._logger.info(`Originator (Caller) is not a Teams User`),!1):(this._logger.info(`ACS MiddleTier Policy API is disabled`),n.userPolicySettingsApi):(this._logger.info(`ACS MiddleTier service is disabled`),n.enabled)}isSecurityDeskEnabled(){let e=this._policySettingData.userAggregatedPolicySettingData?.userPolicies?.teamsEmergencyCallingPolicy;return!(t4(e?.notificationGroup)&&t4(e?.notificationDialOutNumber)||e?.notificationGroup?.trim().length==0&&e?.notificationDialOutNumber?.trim().length==0)}async getAcsMiddletierServiceRequestHeader(){return{"Content-Type":`application/json`,"X-Skypetoken":this._jwtTokenProvider?await this._jwtTokenProvider():``,"Access-Control-Allow-Origin":`*`,"X-Microsoft-Skype-Chain-ID":this._callId}}async getAcsMiddletierServiceRequestHeaderForThreadApi(e){let t={};return t=await this.getAcsMiddletierServiceRequestHeader(),t.onbehalfOfUser=e??this._localParticipant,t}sendMiddleTierPolicyEvent(e,t){try{this.setDefaultEventData(e,t),this._telemetryLogManager?.sendEvent({name:e.eventName,tenant:d2,properties:e})}catch{this._logger.debug(`Unable to send AcsMiddleTierPolicyService telemetry`)}}sendMiddleTierApiEvent(e){try{this.setDefaultEventData(e),this._telemetryLogManager?.sendEvent({name:e.eventName,tenant:d2,properties:e})}catch{this._logger.debug(`Unable to send MiddleTier Api telemetry`)}}setDefaultEventData(e,t){e.callId=this._callId,e.localParticipantId=this._localParticipant,e.requestedParticipantMRI=t??this._localParticipant,e.timestampInfo=e.timestampInfo??``,e.additionalDetails=e.additionalDetails??``}},fLe=class{constructor(e){this._logger=e}get gpu(){let e={};try{let t=document.createElement(`canvas`),n=t.getContext(`webgl`)||t.getContext(`experimental-webgl`);if(n){let t=n.getExtension(`WEBGL_debug_renderer_info`);t?(e.vendor=n.getParameter(t.UNMASKED_VENDOR_WEBGL),e.renderer=n.getParameter(t.UNMASKED_RENDERER_WEBGL)):this._logger?.info(`Unable to get GPU info: debug renderer info is not supported`)}else this._logger?.info(`Unable to get GPU info: WebGL is not supported`)}catch(e){this._logger?.info(`Unable to get GPU info: ${e}`)}return e}get hardwareConcurrency(){return navigator.hardwareConcurrency}},K7;(function(e){e.deviceSelection=`deviceSelection`,e.createCallAgent=`createCallAgent`,e.createTeamsCallAgent=`createTeamsCallAgent`,e.disposeCallAgent=`disposeCallAgent`,e.disposeTeamsCallAgent=`disposeTeamsCallAgent`,e.disposeCallClient=`disposeCallClient`,e.handleIncomingCall=`handleIncomingCall`,e.startPreheatDevices=`startPreheatDevices`,e.stopPreheatDevices=`stopPreheatDevices`})(K7||={});var pLe,q7=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},J7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},mLe=1,Y7=class{get customContext(){return this._customContext}get kind(){return this._kind}get connectionState(){return this._connectionState}constructor(e,t,n,r,i,a,o){this._callClient=e,this._customContext={callId:``,customContext:{}},this._pushHandlingDeltaTimeInMs=new Map,this._disposed=!1,this.tokenProvider=async e=>{let t=+new Date,n;try{if(this.sendTokenChangedEvent({kindOfEvent:`attempt`,timestampInfo:{attemptTimestamp:t},oldTokenExpiration:this._oldTokenExpiration}),!this._communicationTokenCredential)throw new Y({defaultError:J.CALL_AGENT.GET_TOKEN_BEFORE_INIT});n=await M4(this._communicationTokenCredential,Z().calling.eudb.isRgnClaimEnabledForACS,{abortSignal:this._abortController.signal}),n.acsResourceId===this._parsedTokenCredential?.acsResourceId&&n.identityMri===this._parsedTokenCredential?.identityMri||k4(J.CALL_AGENT.REFRESHED_TOKEN_INVALID_USERID,this.logger),e?this._tokenFetchTries+=1:this._tokenFetchTries=0,this._tokenFetchTries>this._maxNmberOfRetries&&(this.updateConnectionState(`invalidToken`),this._disposed||await this.dispose(),k4(J.CALL_AGENT.REFRESHED_TOKEN_RETRIES,this.logger));let r=+new Date;return this.sendTokenChangedEvent({kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:r-t},oldTokenExpiration:this._oldTokenExpiration,newTokenExpiration:n.exp,isTokenChanged:this._oldToken!==n.jwtToken}),this._oldToken=n.jwtToken,this._oldTokenExpiration=n.exp,n.jwtToken}catch(e){let r={kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:+new Date-t},oldTokenExpiration:this._oldTokenExpiration};throw n&&(r.newTokenExpiration=n.exp,r.isTokenChanged=this._oldToken!==n.jwtToken,this._oldToken=n.jwtToken,this._oldTokenExpiration=n.exp),this.sendTokenChangedEvent(r,e),e}},this.sendTokenChangedEvent=(e,t)=>{try{let n={kindOfEvent:e.kindOfEvent,timestampInfo:e.timestampInfo,oldTokenExpiration:e.oldTokenExpiration};e.newTokenExpiration!==void 0&&(n.newTokenExpiration=e.newTokenExpiration),e.isTokenChanged!==void 0&&(n.isTokenChanged=e.isTokenChanged),t&&(n={...n,...K3(t)}),this._telemetryLogManager.sendEvent({name:Q.acs_calling_token_expiration_changed,tenant:d2,properties:n})}catch{this.logger.debug(`Unable to send token change telemetry`)}},this.pushHandlingStarted=e=>{let t=K0();this._pushHandlingDeltaTimeInMs.set(e,{correlationId:t,timestamp:+new Date}),this.logger.log(`Incoming call state started`,e),F6.setCauseIdToNetworkInfo(e),this.sendIncomingNotificationEvent({eventName:Q.acs_calling_client_operations,operation:K7.handleIncomingCall,networkInfo:[],kindOfEvent:`attempt`,timestampInfo:{deltaTimeInMs:void 0},correlationId:t,additionalDetails:{},callId:``,participantId:``})},this.pushNotificationParsed=(e,t)=>{if(this.logger.debug(`pushNotificationParsed event received ${e}`),t.customContext.sipHeaders||t.customContext.voipHeaders){let{sipHeaders:e,voipHeaders:n}=t.customContext,r={sipHeaders:H4(e),voipHeaders:H4(n)},i=e=>`sipHeaders: ${e?.sipHeaders?.length||0}, voipHeaders: ${e?.voipHeaders?.length||0}`;if(!Q2.isEqual(this._customContext.customContext,r)){this.sendCallAgentInfoEvent({eventName:Q.acs_calling_call_agent,additionalDetails:{step:`customContext-changed`,callId:t.callId,oldState:i(this._customContext.customContext),newState:i(r)}});let e={...this._customContext};this._customContext={callId:t.callId,customContext:r},this._eventEmitter.emit(`customContextChanged`,{oldValue:e,newValue:{...this._customContext}})}}},this.pushHandlingEnded=(e,t)=>{let n=t?.code!==void 0&&[0,200].includes(t?.code),r=e=>{if(n)return new Y({defaultError:{code:e?.code??0,subCode:e?.subCode??0,message:`Success`,resultCategories:[`Success`]}});let t=[J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_INVALID_NOTIFICATION_PAYLOAD,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_FAILED_TO_EXTRACT_PAYLOAD,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_ALREADY_HANDLED,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_IGNORING_DUPLICATE_NOTIFICATION,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_FAILED_TO_HANDLE_NOTIFICATION_FOR_GROUPID_CALL,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_BAD_NOTIFICATION_PAYLOAD,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_SETUP_SUCCEEDED,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_SETUP_FAILED,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_BAD_NOTIFICATION_EVENT_TYPE,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_ALREADY_EXISTS,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_FAILED_CANNOT_CONNECT,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_FAILED_NO_SIGNALING,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_FAILED_CONFLICT,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_FAILED_PUSH_IGNORED,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_FAILED_ANSWERED_ELSEWHERE,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_FAILED_CALL_ALREADY_ENDED,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_SETUP_IN_PROGRESS];return new Y({defaultError:Q2.find(t,(t=>t.subCode===e?.subCode))??J.CALL_AGENT.INVALID_PUSH_NOTIFICATION_DATA})};this.logger.log(`Incoming call state ended`,e,t);let i=F6.getRemoveCauseIdToNetworkInfo(e),a=this._pushHandlingDeltaTimeInMs.get(e)?.correlationId||`unknown`,o=r(t);this.sendIncomingNotificationEvent({eventName:Q.acs_calling_client_operations,operation:K7.handleIncomingCall,networkInfo:i||[],kindOfEvent:n?`success`:`failure`,timestampInfo:{deltaTimeInMs:this._pushHandlingDeltaTimeInMs.has(e)?+new Date-this._pushHandlingDeltaTimeInMs.get(e)?.timestamp:void 0},correlationId:a,additionalDetails:{...K3(o)},callId:t.callId||``,participantId:t.participantId||``}),this._pushHandlingDeltaTimeInMs.delete(e),this._eventEmitter.emit(`handleIncomingCall`,{callId:t.callId||``,participantId:t.participantId||``,...q3({code:o.code,subCode:o.subCode,message:o.message,resultCategories:o.resultCategories})})},this.logger=t.createChild(`CallAgent`+ mLe++),this._telemetryLogManager=r,this._kind=a,this._connectionState=`Disconnected`,this._eventEmitter=new S6(this.logger),this._internalEventEmitter=new w3.EventEmitter,this.clientId=n,this._abortController=new AbortController,this._maxDisplayNameLength=Z()?.calling?.maxDisplayNameLength||XCe,this._oldToken=``,this._oldTokenExpiration=0,this._tokenFetchTries=0,this._maxNmberOfRetries=Z()?.calling?.maxNumberOfTokenFetchRetries||zCe,this._callStack=i,this.callClient=this._callClient,this.deviceManager=o,this.acsProxy=this.callClient.acsProxy,this.acsCustomRelayManager=this.callClient.acsCustomRelayManager,this._httpRequestHelper=new UEe(this.logger,this.acsProxy),this.mtPolicyService=new dLe(this._httpRequestHelper),this._parsedTokenCredential=eTe(),this._caConfigBag={clientId:``,acsResourceId:this._parsedTokenCredential.acsResourceId,identityMri:this._parsedTokenCredential.identityMri,cloudType:this._parsedTokenCredential.cloudType,identityType:this._parsedTokenCredential.isEnterpriseUser?$0.Enterprise:$0.Consumer,region:this._parsedTokenCredential.region,emergencyCountryCode:void 0,IsUserEmergencyCountryCode:!1,mriType:this._parsedTokenCredential.mriType,parsedTokenCredential:this._parsedTokenCredential},this._extensibleApi=new N3(this.logger,{callClient:this.callClient,callAgent:this},{tsStack:this.tsStack,callAgent:this,telemetryLogManager:this._telemetryLogManager});let s=Q5(D3.CallAgentFeature);for(let e of s)e.activationOptions.activationEvent===`OnExtendedObjectConstructor`&&this.feature(e);this._trouterStateChangeCallback=e=>{this.logger.log(`Callback Trouter state changed to ${e}`),this.updateConnectionState(`trouterChanged`)},this._registrarStateChangeCallback=e=>{this.logger.log(`Callback Registrar state changed to ${e}`),this.updateConnectionState(`registrarChanged`)}}getHttpRequestHelper(){return this._httpRequestHelper}getTrouterState(){return this._callStack?this._callStack.getTrouterState():`Unknown`}onTrouterStateChanged(e){return this._callStack.onTrouterStateChanged(e)}offTrouterStateChanged(e){return this._callStack.offTrouterStateChanged(e)}onDisposed(e){this._internalEventEmitter.on(`disposed`,e)}getAcsResourceId(){return this._parsedTokenCredential?.acsResourceId||``}getUserMri(){return`8:${this._parsedTokenCredential?.identityMri}`||``}getUserPolicy(){return this._userPolicies}getUserProperties(){return this._userProperties}getInternalCallRegistry(){return this._tsCallRegistry}async initialize(e,t){let n=+new Date,r=new fLe(this.logger),i={gpu:r.gpu,hardwareConcurrency:r.hardwareConcurrency};try{if(this.sendCallAgentInitializiedEvent(Q.acs_calling_call_agent_init_attempt,{attemptTimestamp:n},i),this._communicationTokenCredential=e,this._parsedTokenCredential=await M4(e,Z().calling.eudb.isRgnClaimEnabledForACS,{abortSignal:this._abortController.signal}),this._kind!==BG.TeamsCallAgent||this._parsedTokenCredential.isEnterpriseUser?this._kind===BG.CallAgent&&this._parsedTokenCredential.isEnterpriseUser&&k4(J.CALL_AGENT.ACS_CALLAGENT_TOKEN_ONLY,this.logger):k4(J.CALL_AGENT.TEAMS_CALLAGENT_TOKEN_ONLY,this.logger),t?.displayName){if(this._parsedTokenCredential.isEnterpriseUser)throw new Y({defaultError:J.CALL_AGENT.ENTERPRISE_DISPLAY_NAME});if(t?.displayName.length>this._maxDisplayNameLength)throw new Y({defaultError:J.CALL_AGENT.DISPLAY_NAME_TOO_LONG})}if(this._parsedTokenCredential.cloudType===J0.Public&&(!this._parsedTokenCredential.region||this._parsedTokenCredential.region===``)){try{let e=+new Date-n;this._telemetryLogManager.sendEvent({name:Q.acs_calling_token_has_no_data_location,tenant:d2,properties:{deltaTimeInMs:e}})}catch{this.logger.debug(`Unable to send token has no data location assigned`)}this._parsedTokenCredential.region=this._parsedTokenCredential.rgnClaimExists?wSe[0]:t2[0],this.logger.info(`Used default data location because token has no data location assigned`)}this._caConfigBag={clientId:this.clientId,acsResourceId:this._parsedTokenCredential.acsResourceId,identityMri:this._parsedTokenCredential.identityMri,cloudType:this._parsedTokenCredential.cloudType,identityType:this._parsedTokenCredential.isEnterpriseUser?$0.Enterprise:$0.Consumer,emergencyCountryCode:t?.emergencyCallOptions?.countryCode,region:this._parsedTokenCredential.region,IsUserEmergencyCountryCode:!!t?.emergencyCallOptions?.countryCode,mriType:this._parsedTokenCredential.mriType,parsedTokenCredential:this._parsedTokenCredential},this.addToCallAgentsMap(this._parsedTokenCredential),this._disposed=!1;try{this.runningEnvironmentInfo=await this.callClient.getEnvironmentInfoInternal()}catch{this.logger.debug(`Unable to get the running environment info`)}if(this.tsStack=await this._callStack.initializeStackForUser(this.tokenProvider,this._caConfigBag),this._parsedTokenCredential.rgnClaimExists)try{await this.updateParsedTokenCredentials(e)}catch(e){this.logger.debug(`Failed to update parsed token credentials. Error message = ${e?.message||``}`)}await this.setUserPoliciesOnAgentInitialization(),this.isEnterpriseUser()&&(t={...t,displayName:this._userProperties?.displayName??void 0}),this._telemetryLogManager.initialize(this._caConfigBag),this._tsCallRegistry=await this.initializeCallRegistry(this.tsStack,t),this.registerConnectionStateEventHandlers();let r=+new Date;this.sendCallAgentInitializiedEvent(Q.acs_calling_call_agent_init_success,{deltaTimeInMs:r-n},i)}catch(e){this._caConfigBag&&!this._telemetryLogManager.isInitialized()&&this._telemetryLogManager.initialize(this._caConfigBag);let t=new Y({defaultError:J.CALL_AGENT.INIT_FAIL,originalError:e});this.removeFromCallAgentsMap(this._parsedTokenCredential);let r=+new Date;throw this.sendCallAgentInitializiedEvent(Q.acs_calling_call_agent_init_failure,{deltaTimeInMs:r-n},i,t),t}}handleActiveCallTransfer(e){this.logger.info(`CallAgent handling active call transfer for callId=${e.id}`),this._eventEmitter.emit(`callsUpdated`,{added:[e],removed:[]})}async setUserPoliciesOnAgentInitialization(){this.mtPolicyService.initialize({localParticipant:this.getUserMri(),jwtTokenProvider:this.tokenProvider,telemetryLogManager:this._telemetryLogManager})}isEnterpriseUser(){return this._parsedTokenCredential?.isEnterpriseUser!==void 0&&this._parsedTokenCredential?.isEnterpriseUser}isTeamsExtensionUser(){return this._parsedTokenCredential?.mriType!==void 0&&this._parsedTokenCredential?.mriType==e2.TeamsExtensionUser}getClientId(){return this.clientId}getCallByCallId(e,t){return t?this._tsCallRegistry.getCall(e,t):this._tsCallRegistry.calls.filter((t=>t.callId===e))?.[0]}async createTransferTargetCall(e){let t=AG(),n=K0(),r=K0(),i=await this._tsCallRegistry.createCallAsync({callId:n,localParticipantId:r,causeId:t,type:`ThreadId`,threadId:``}),a=this.createNewCall(n,i);return this.addToCallArray(a),this.handleCallState(a),i.addParticipant(e.targetMri).catch((()=>{this.logger.error(`Failed to add participant for transer call`)})),U6(i)?await Promise.all(a.bindTsCall()):a.bindTsCall(),this._eventEmitter.emit(`callsUpdated`,{added:[a],removed:[]}),a}async subscribeCallWithoutModality(e){let t=AG(),n=await this._tsCallRegistry.createCallAsync({callId:e.callId,localParticipantId:e.participantId,causeId:t,type:`ThreadId`,threadId:e.threadId,messageId:e.messageId}),r=this.createNewCall(e.callId,n),i={conversationUrl:e.meetingUrl,conversationId:e.callId};return this.addToCallArray(r),this.handleCallState(r),n.joinCallWithoutCallModality(i,{},t).then((()=>{this.logger.info(`Successfully joined call without modalities`)})).catch((e=>{throw this.logger.error(`Error while joining call without modalities`,e),new Y({defaultError:J.CALL_AGENT.INVALID_JOIN_LOCATOR,originalError:e})})),U6(n)?await Promise.all(r.bindTsCall()):r.bindTsCall(),r}getEcsConfigIds(){return this._callStack.getEcsConfigIds()}getDeviceType(){let e=this.callClient?.firstPartyOptions?.acsDeviceType;return e?iwe[e]:`default`}isWatermarkSupported(){return this.isEnterpriseUser()?Z().calling.watermark.watermarkEnabledForCteUsers:Z().calling.watermark.watermarkEnabledForAcsUsers}feature(e){return this._extensibleApi.getApiObjectInstance(e.callAgentApiCtor)}async handlePushNotification(e){let t=K0(),n=+new Date,r;try{if(this.sendHandlePushNotificationEvent({eventName:Q.acs_calling_handle_push_notification,correlationId:t,featureName:`handlePushNotification`,operationName:`handleIncomingCallPushNotification`,callId:``,localParticipantId:``,kindOfEvent:`attempt`,timestampInfo:``,additionalDetails:``}),!e.incomingCallContext)throw new Y({defaultError:J.CALL_AGENT.INVALID_PUSH_NOTIFICATION_DATA});r=new oLe(e,this._tsCallRegistry,this.logger),await r.process(),this.sendHandlePushNotificationEvent({eventName:Q.acs_calling_handle_push_notification,correlationId:t,featureName:`handlePushNotification`,operationName:`handleIncomingCallPushNotification`,callId:r.callId,localParticipantId:r.localParticipantId,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:+new Date-n},additionalDetails:``})}catch(e){let i=new Y({defaultError:J.CALL_AGENT.PUSH_NOTIFICATION_FAIL,originalError:e});throw this.sendHandlePushNotificationEvent({eventName:Q.acs_calling_handle_push_notification,correlationId:t,featureName:`handlePushNotification`,operationName:`handleIncomingCallPushNotification`,callId:r?.callId||``,localParticipantId:r?.localParticipantId||``,kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:+new Date-n},additionalDetails:{failureReason:i.message,code:i.code,...K3(i)}}),i}}sendCallAgentDisposeEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:d2,properties:e})}catch{this.logger.debug(`Unable to send CallClient dispose telemetry event`)}}trackCallEndTimeToStopTelemetry(e){e.length===0?f3.callEndTimestamp=Date.now():f3.callEndTimestamp=2**53-1}updateConnectionState(e){let t=this.getCallAgentConnectionState(),n=this.getTrouterState(),r=this._callStack?.isRegistered()?`Connected`:`Disconnected`,i=t===`Connected`?void 0:e==`invalidToken`?`invalidToken`:`connectionIssue`;if(this.sendCallAgentInfoEvent({eventName:Q.acs_calling_call_agent,additionalDetails:{step:`connectionState-changed`,oldState:this._connectionState,newState:t,trouterState:n,registrarState:r,reason:i,connectionStateSource:e}}),t!==this._connectionState||i!==this._connectionStateReason){let e={oldValue:this._connectionState,newValue:t,reason:i};this._connectionState=t,this._connectionStateReason=i,this._eventEmitter.emit(`connectionStateChanged`,e)}}sendCallAgentInfoEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:d2,properties:{...e.additionalDetails}})}catch(e){this.logger.debug(`Failed to send connection state changed event`,e)}}sendCallAgentInitializiedEvent(e,t,n,r){try{let i=typeof r?.message==`string`?r?.message:void 0;e!==Q.acs_calling_call_agent_init_failure&&(i=void 0);let a=r?K3(r):void 0,o=this.getEcsConfigIds(),s=e===Q.acs_calling_call_agent_init_attempt?void 0:this._callStack?.getVdi3StateInfo(),c=r7();this._telemetryLogManager.sendEvent({name:e,tenant:d2,properties:{...t,isSupportedEnvironment:this.runningEnvironmentInfo?.isSupportedEnvironment,failureReason:i,additionalProperties:{AcsCallingSDKWeb_ecsConfigIds:o.AcsCallingSDKWeb,SkypeWebMedia_ecsConfigIds:o.SkypeWebMedia},additionalInformation:{trouterState:this.getTrouterState(),hardwareInfo:n},additionalDetails:{...a,firstPartyOptions:{isDeviceTypeEnabled:Z().calling.setDeviceType,deviceTypeRawStrlen:this.callClient?.firstPartyOptions?.acsDeviceType?.length,deviceType:this.getDeviceType()},aadPftClaimExists:this._parsedTokenCredential.aadpftClaimExists,...s?{vdi3StateInfo:s}:{},...c.isMMREnabled?{mmrInfo:c}:{}}}})}catch{this.logger.debug(`Unable to send telemtery`)}}sendHandlePushNotificationEvent(e){try{this._telemetryLogManager?.sendEvent({name:e.eventName,tenant:d2,properties:e})}catch{this.logger.debug(`Unable to send handle push notification telemetry`)}}async initializeCallRegistry(e,t){let n=t?.displayName,r=await this.getCallRegistry(e,this._parsedTokenCredential,this.tokenProvider,n);return this.logger.info(`registry created for version number=${Y2()}`),r}async getCallRegistry(e,t,n,r){let i={id:t.identityMri,displayName:r||``,tokenProvider:n},a=await e.createCallRegistry(i);await a.login(i);let o=(this._callClient?.firstPartyOptions?.ring??Z()?.tsCalling?.accountConfiguration?.ring)||void 0,s=t.isEnterpriseUser?$0.Enterprise:$0.Consumer,c=t.acsResourceId,l=t.region,u={acsResourceId:c,clientType:s,ring:o};if(Z().calling.setDeviceType)u.deviceType=this.getDeviceType();else if(this.callClient.firstPartyOptions?.acsDeviceType)throw new Y({defaultError:J.CALL_AGENT.SET_DEVICE_TYPE_NOT_ALLOWED});let d=Z().calling.eudb;return d.isEnabled&&d.sendRegionToNgc&&(d.isRgnClaimEnabledForACS||t.isEnterpriseUser)&&(u={...u,region:l}),Z()?.calling.supportLiveStreaming&&(u.clientSupportsUms=!0),u.clientSupportsWatermark=this.isWatermarkSupported(),await a.setConfiguration(u),a.on(`callAdded`,this.handleCallAdded),a.on(`callRemoved`,this.handleCallRemoved),a.on(`pushHandlingStarted`,this.pushHandlingStarted),a.on(`pushHandlingEnded`,this.pushHandlingEnded),a.on(`pushNotificationParsed`,this.pushNotificationParsed),r&&await a.updateDisplayName(r),a}async updateParsedTokenCredentials(e){this._parsedTokenCredential=await M4(e,Z().calling.eudb.isRgnClaimEnabledForACS,{abortSignal:this._abortController.signal}),this._caConfigBag.region=this._parsedTokenCredential.region,this._caConfigBag.parsedTokenCredential=this._parsedTokenCredential}registerConnectionStateEventHandlers(){this._callStack.onRegisteredChanged(this._registrarStateChangeCallback),this.onTrouterStateChanged(this._trouterStateChangeCallback)}getCallAgentConnectionState(){return this._callStack?.isRegistered()&&this.getTrouterState()===`Connected`?`Connected`:`Disconnected`}sendIncomingNotificationEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:d2,properties:e})}catch{this.logger.debug(`Unable to send incoming call notification telemetry`)}}};q7([zG,J7(`design:type`,Object)],Y7.prototype,`logger`,void 0),q7([GG(a4.Initialize),J7(`design:type`,Function),J7(`design:paramtypes`,[Object,Object]),J7(`design:returntype`,Promise)],Y7.prototype,`initialize`,null),q7([WG(a4.Feature),J7(`design:type`,Function),J7(`design:paramtypes`,[Object]),J7(`design:returntype`,typeof(pLe=typeof TFeature<`u`&&TFeature)==`function`?pLe:Object)],Y7.prototype,`feature`,null),q7([GG(a4.HandlePushNotification),J7(`design:type`,Function),J7(`design:paramtypes`,[Object]),J7(`design:returntype`,Promise)],Y7.prototype,`handlePushNotification`,null);var hLe=class{constructor(e){this._call=e}setTarget(e){this._call=e}getTarget(){return this._call}startVideo(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}stopVideo(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}startScreenSharing(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}stopScreenSharing(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}setConstraints(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}};function X7(e){let t=new hLe(e);return new Proxy({},{get:(e,n)=>{let r,i,a=t.getTarget();if(n in t)r=t[n],i=t;else{if(a===void 0)throw new Y({defaultError:J.FEATURES.VDI3.CALL_INITIALIZING});if(!(n in a))return;r=a[n],i=a}return typeof r==`function`?function(...e){return r.apply(i,e)}:r},has:(e,n)=>{let r=t.getTarget();return n in t||r!==void 0&&n in r}})}var Z7,Q7=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},$7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},e9=class e extends Y7{get calls(){return this._calls}constructor(e,t,n,r,i,a,o){super(e,t,r,i,n,BG.CallAgent,a),this._calls=[],this.handleCallRemoved=e=>{this.logger.info(`removing callId=${e.callId}`);let t=this._calls.find((t=>t.id===e.callId));if(t){if(t.isBreakoutRoomCall){let e=Z().calling.breakoutRooms.hangUpCallDelayInMilliSeconds;setTimeout((()=>{this.disposeCall(t)}),e)}else this.disposeCall(t);this._eventEmitter.emit(`callsUpdated`,{added:[],removed:[t]}),this.logger.info(`call removed`)}},this.handleCallAdded=e=>{if(!this._calls.find((t=>t.id===e.callId))){let t=e.on(`callStateChanged`,(async()=>{if(e.state===1){let n=U6(e),r=e.callId;t.dispose();let i=new B7({callId:r,isIncoming:!0},this,e,this._telemetryLogManager);n&&(i=X7(i));let a=new aLe(i);this.handleCallState(i),n?await Promise.all(i.bindTsCall()):i.bindTsCall(),this._eventEmitter.emit(`incomingCall`,{incomingCall:a})}}))}},this.handleCallState=e=>{e.on(`stateChanged`,(async()=>{try{e.state===`Disconnected`?this.tsStack?(await this._tsCallRegistry.deleteCallAsync?.(e.tsCall)||this.logger.info(`The call has been removed from registry, call id: ${e.id}`),e.stats.flushEvents(),this._telemetryLogManager.flushAllEvents(e.id).catch((()=>{this.logger.error(`Failed to flush telemetry log manager events`)}))):this.logger.info(`Unable to remove call from registry`):e.state===`Connecting`&&e.direction==`Incoming`&&(this.addToCallArray(e),this._eventEmitter.emit(`callsUpdated`,{added:[e],removed:[]}))}catch{this.logger.error(`Failed to handle call state changed event`)}}))},this.displayName=o?.displayName}addToCallAgentsMap(t){e.callAgents.get(t?.identityMri)&&k4(J.CALL_AGENT.ACS_CALLAGENT_ALREADY_EXSISTS,this.logger),e.callAgents.set(t?.identityMri,this)}removeFromCallAgentsMap(t){t?.identityMri&&e.callAgents.get(t?.identityMri)===this&&e.callAgents.delete(t?.identityMri)}disposeCall(e){let t=this._calls.indexOf(e);t!==-1&&this._calls.splice(t,1),e.dispose(),this.trackCallEndTimeToStopTelemetry(this._calls)}async getExistingCallAgentWithToken(t){try{let n=await M4(t,Z().calling.eudb.isRgnClaimEnabledForACS);return e.callAgents.get(n.identityMri)}catch(e){throw new Y({defaultError:J.CALL_AGENT.PARSE_ACCESSTOKEN,originalError:e})}}createNewCall(e,t){let n=new B7({callId:e},this,t,this._telemetryLogManager);return U6(t)?X7(n):n}addToCallArray(e){this._calls.push(e),this.trackCallEndTimeToStopTelemetry(this._calls)}async disposeInternal(t){let n=+new Date,r=K0();this.sendCallAgentDisposeEvent({eventName:Q.acs_calling_client_operations,operation:K7.disposeCallAgent,kindOfEvent:`attempt`,timestampInfo:{},correlationId:r,additionalDetails:``});try{if(this._disposed)throw new Y({defaultError:J.CALL_AGENT.ACS_ALREADY_DISPOSED});this._disposed=!0,this._abortController.abort(),this._extensibleApi.dispose(),this._parsedTokenCredential?.identityMri&&e.callAgents.delete(this._parsedTokenCredential?.identityMri);for(let e of this._calls)e.state!==`Disconnected`&&await e.hangUp().catch((()=>{this.logger.error(`Failed to hangup call during call agent dispose`)}));await this._tsCallRegistry?.dispose();let t=this._tokenFetchTries>this._maxNmberOfRetries;await this._callStack.disposeUserStack(t),this.offTrouterStateChanged(this._trouterStateChangeCallback),this._callStack.offRegisteredChanged(this._registrarStateChangeCallback),this._eventEmitter.removeAllListeners(),this._internalEventEmitter.emit(`disposed`),this._internalEventEmitter.removeAllListeners(),this.sendCallAgentDisposeEvent({eventName:Q.acs_calling_client_operations,operation:K7.disposeCallAgent,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:``})}catch(e){let t=new Y({defaultError:J.CALL_AGENT.DISPOSE_FAIL,originalError:e});throw this.sendCallAgentDisposeEvent({eventName:Q.acs_calling_client_operations,operation:K7.disposeCallAgent,kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{failureReason:t.message,code:t.code,subCode:t.subCode,...K3(t)}}),t}finally{t&&this._telemetryLogManager.clearTelemetryLoggers()}}startCall(e,t){let n=K0(),r=+new Date,i={correlationId:n,timestampInfo:{attemptTimestamp:r}};this._telemetryLogManager.sendEvent({name:Q.acs_calling_call_attempt,tenant:d2,properties:i},void 0,`attempt`);try{if(this.assertCallUserIds(e),t?.alternateCallerId&&q2(t.alternateCallerId),e.find((e=>W2(e)===this.getUserMri())))throw new Y({defaultError:J.CALL_AGENT.CANT_CALL_YOURSELF});let i=t?.audioOptions?.muted;return i===void 0&&(i=!1),this.logger.info(`startCall with video=${!!t?.videoOptions},muted=${i}`),this.createCall({participants:e,startCallOptions:t},{correlationId:n,attemptTimestamp:r})}catch(e){let t,i;throw e instanceof Y&&(t=typeof e?.message==`string`?e?.message:void 0,i={...K3(e)}),this._telemetryLogManager.sendEvent({name:Q.acs_calling_call_failed,tenant:d2,properties:{correlationId:n,timestampInfo:{deltaTimeInMs:+new Date-r},failureReason:t||``,additionalDetails:i||{}}},void 0,`failure`),e}finally{this._telemetryLogManager.deleteEventMapByCorrelationId(n)}}join(e,t){if(!R4(this.acsProxy,this.acsCustomRelayManager,!1,void 0,e))throw new Y({defaultError:J.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN});this.assertCallContext(e);let n=t?.audioOptions?.muted;return n===void 0&&(n=!1),this.logger.info(`join with video=${!!t?.videoOptions},muted=${n}`),this.createCall({callContext:e,startCallOptions:t})}async dispose(){await this.disposeInternal(!0)}on(e,t){if(e!==`handleIncomingCall`&&e!==`incomingCall`&&e!==`callsUpdated`&&e!==`connectionStateChanged`&&e!==`customContextChanged`)throw new Y({defaultError:J.CALL_AGENT.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if(e!==`handleIncomingCall`&&e!==`incomingCall`&&e!==`callsUpdated`&&e!==`connectionStateChanged`&&e!==`customContextChanged`)throw new Y({defaultError:J.CALL_AGENT.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}createCall(e,t){if(e?.startCallOptions?.firstPartyOptions?.isImmersiveMode&&this.getDeviceType()!==`meshV2`)throw new Y({defaultError:J.CALL_AGENT.MESH_DEVICETYPE_V2});if(!this.tsStack)throw new Y({defaultError:J.CALL_AGENT.STACK_NOT_INIT});let n,r,i,a=e?.callContext?.threadId||e?.startCallOptions?.threadId,o=!1,s=e?.callContext?.groupId,c=e?.callContext?.roomId,l=e?.callContext?.meetingLink,u=e?.callContext?.meetingId,d=e?.callContext?.passcode||``;if(s&&s.startsWith(`19:`)&&(a=s,s=``),l)if(vFe(l))r=M5(l);else{if(!yFe(l,this.logger))throw new Y({defaultError:J.CALL_AGENT.INVALID_MEETING_LINK});if(bFe(l.trim().toLocaleLowerCase(),Z().calling.tfl.hosts)&&!Z().calling.tfl.isEnabled)throw new Y({defaultError:J.CALL_AGENT.UNSUPPORTED_TFL_MEETING_JOIN});o=!0}e?.callContext?.threadId&&e?.callContext?.organizerId&&e?.callContext?.tenantId&&(r={threadId:e?.callContext?.threadId,messageId:e?.callContext?.messageId?e?.callContext?.messageId.toString():`0`,organizerId:e?.callContext?.organizerId,tenantId:e?.callContext?.tenantId}),r&&(i={meetingType:r.messageId===`0`?1:2,tenantId:r.tenantId,organizerId:r.organizerId,replyChainMessageId:r.messageId},a=r.threadId,n=r.messageId);let f=AG(),p=K0(),m=K0(),h={threadId:a||``,messageId:n||``,meetingInfo:i,mediaPeerType:2},g=!1;if(U6(this._tsCallRegistry)){let r=X7();return(async()=>{let i;s?i=await this._tsCallRegistry.createCallAsync({type:`GroupId`,groupId:s,callId:p,localParticipantId:m,causeId:f}):u?i=await this._tsCallRegistry.createCallAsync({callId:p,localParticipantId:m,causeId:f,type:`MeetingData`,meetingData:{meetingCode:u,passcode:d,threadId:a}}):c?i=await this._tsCallRegistry.createCallAsync({callId:p,localParticipantId:m,causeId:f,type:`MeetingData`,meetingData:{meetingCode:c}}):o?i=await this._tsCallRegistry.createCallAsync({callId:p,localParticipantId:m,causeId:f,type:`MeetingData`,meetingData:{meetingUrl:l}}):(g=!!e?.participants&&e.participants.length>=2&&z4(e.participants,this.kind),Z().calling.enableSmePassFakeConversation&&!a&&g&&(a=`${LG}${K0()}`),i=await this._tsCallRegistry.createCallAsync({callId:p,localParticipantId:m,causeId:f,type:`ThreadId`,threadId:a||``,messageId:n}));let _=new B7({callId:p,roomId:c},this,i,this._telemetryLogManager,g);r.setTarget(_),this.addToCallArray(r),this.handleCallState(r),e?.participants&&e?.participants.forEach((e=>{i.addParticipant(W2(e)).catch((()=>{this.logger.error(`Failed to add participant during call start`)}))}));let v=e3();_.startCallInternal(e?.startCallOptions,!!u||!!c,e?.callContext,h,t,v).catch(A4),await Promise.all(_.bindTsCall()),await v.promise,this._eventEmitter.emit(`callsUpdated`,{added:[r],removed:[]})})().catch((e=>{})),r}{let r,i=!1;s?r=this._tsCallRegistry.createCallWithGroupId(s,p,m,f):u?r=this._tsCallRegistry.createCallWithMeetingData({meetingCode:u,passcode:d,threadId:a},p,m,f):c?r=this._tsCallRegistry.createCallWithMeetingData({meetingCode:c},p,m,f):o?r=this._tsCallRegistry.createCallWithMeetingData({meetingUrl:l},p,m,f):(i=!!e?.participants&&e.participants.length>=2&&z4(e.participants,this.kind),Z().calling.enableSmePassFakeConversation&&!a&&i&&(a=`${LG}${K0()}`),r=this._tsCallRegistry.createCall(a||``,p,m,n,f));let g=new B7({callId:p,roomId:c},this,r,this._telemetryLogManager,i);return this.addToCallArray(g),this.handleCallState(g),e?.participants&&e?.participants.forEach((e=>{r.addParticipant(W2(e)).catch((()=>{this.logger.error(`Failed to add participant during call start`)}))})),g.startCallInternal(e?.startCallOptions,!!u||!!c,e?.callContext,h,t).catch(A4),g.bindTsCall(),this._eventEmitter.emit(`callsUpdated`,{added:[g],removed:[]}),g}}assertCallContext(e){if(!e||this.checkForAtLeastOneValidCallConfig(e)||this.checkIfMultiplesConfigsWereSpecified(e)||this.checkForInvalidTeamsMeetingCoordinates(e))throw new Y({defaultError:J.CALL_AGENT.INVALID_JOIN_LOCATOR})}checkForAtLeastOneValidCallConfig(e){return!(e.threadId||e.meetingLink||e.groupId||e.meetingId||e.roomId)}checkIfMultiplesConfigsWereSpecified(e){return e.threadId&&e.groupId||e.groupId&&e.meetingLink}checkForInvalidTeamsMeetingCoordinates(e){return!e.threadId&&e.tenantId&&e.organizerId||e.threadId&&(e.organizerId&&!e.tenantId||!e.organizerId&&e.tenantId)}assertCallUserIds(e){Ywe(e,J.CALL_AGENT.USERIDS_MUST_BE_OBJECTS),Jwe(e,J.CALL_AGENT.USERIDS_CANNOT_BE_NULL),dwe(e),e.forEach((e=>{let t=q2(e);if(!R4(this.acsProxy,this.acsCustomRelayManager,!1,t))throw new Y({defaultError:J.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN})}))}};e9.callAgents=new Map,Q7([WG(a4.StartCall),$7(`design:type`,Function),$7(`design:paramtypes`,[Array,Object]),$7(`design:returntype`,Object)],e9.prototype,`startCall`,null),Q7([WG(a4.Join),$7(`design:type`,Function),$7(`design:paramtypes`,[Object,Object]),$7(`design:returntype`,Object)],e9.prototype,`join`,null),Q7([GG(a4.Dispose),$7(`design:type`,Function),$7(`design:paramtypes`,[]),$7(`design:returntype`,Promise)],e9.prototype,`dispose`,null),function(e){e.alpha=`alpha`,e.beta=`beta`,e.stable=`stable`,e.unknown=`unknown`}(Z7||={});var gLe=class{constructor(){this.browserInfo=t8();let e=J2();e.includes(`alpha`)||e.includes(`alpharc`)?this.sdkFlavor=Z7.alpha:e.includes(`beta`)||e.includes(`betarc`)?this.sdkFlavor=Z7.beta:e.includes(`stable`)||e.includes(`stablerc`)?this.sdkFlavor=Z7.stable:this.sdkFlavor=Z7.alpha}getInitialJamaSettings(){let e=$2.merge({},MSe),t=this.getFormFactorBaseSettings();e=$2.merge(e,t);let n=this.getSdkFlavorBaseSettings();e=$2.merge(e,n);let r=this.getSdkFlavorFormFactorSettings();e=$2.merge(e,r);let i=this.getBrowserEngineSpecificSettings();return e=$2.merge(e,i),e}getFormFactorBaseSettings(){switch(this.browserInfo.formFactor){case`Desktop`:return NSe;case`Mobile`:return ISe;default:return MSe}}getSdkFlavorBaseSettings(){switch(this.sdkFlavor){case Z7.stable:return BSe;case Z7.beta:return zSe;case Z7.alpha:default:return RSe}}getSdkFlavorFormFactorSettings(){let e=this.browserInfo.formFactor;if(this.sdkFlavor===Z7.stable)switch(e){case`Desktop`:return USe;case`Mobile`:return KSe;default:return BSe}else if(this.sdkFlavor===Z7.beta)switch(e){case`Desktop`:return HSe;case`Mobile`:return GSe;default:return zSe}else switch(e){case`Desktop`:return VSe;case`Mobile`:return WSe;default:return RSe}}getBrowserEngineSpecificSettings(){let e=this.browserInfo.engine,t=n8(),n=this.browserInfo.formFactor;return t===`ios`&&e===`Safari`?LSe:n===`Desktop`&&e===`Chromium`?PSe:e===`Firefox`?FSe:{}}},t9=class{constructor(e,t,n){this.setConfigOrDefault=(e,t)=>{e&&Object.keys(e).forEach((n=>{e[n]!==void 0&&(t[n]=e[n])}))},this._logger=e,this.sdkDiagnosticInformation=t,this._acsProxy=n,this._jamaSettingsProvider=new gLe;let r=Z().calling.applicationSettingsUrls,i=Z().calling.pnhTemplateVersion;this._trouterSettings={version:`${l2()}/${J2()}`,productName:`AcsWeb`,trouterServiceUrl:r.Public_TrouterServiceUrl,registrarServiceUrl:r.Public_RegistrarServiceUrl,maxRegistrationTimeInMs:36e5,pnhAppId:`AcsWeb`,pnhTemplate:i,environment:`Prod`,platform:e8()},this._JsCsaConfig={languageCode:`en`,emergencyCallCountry:``,autoResolveConflictedCall:!1,handleRosterFromCreateAndJoin:!0,conversationServiceUrl:n.proxyfyUrl(r.Public_ConversationServiceUrl),useInternalHttpDispatcher:!0,supportsHostlessGroupCalls:!0,doHostlessCalling:!0,shouldServiceSendCallEventMessages:!0,shouldServiceSendNGCUpgradeMessages:!0,supportsCompressedServicePayload:!0,handleNewOfferRequest:!0,handleMediaOfferFromPushNotification:!0,isWebRtcEnabled:!0,supportsSynchronousTrouterResponse:!0,autoJoinOnConflict:!0,brokerEnabledOutgoing:!0,brokerEnabledIncoming:!0,brokerExclusively:!1,brokerRequestBatching:!0,isGVCOutgoingEnabled:!0,isGVCJoiningEnabled:!0,enableTokenCache:!1,nullifyAuthTokenManagerOnReset:!1},this._JamaSettings=this._jamaSettingsProvider.getInitialJamaSettings(),this._MDNTrapSettings={Service:{url:n.proxyfyUrl(r.Public_MdnTrapServiceUrl),tokenUrl:n.proxyfyUrl(r.Public_MdnTrapServiceTokenUrl)},Relay:{Skype:{addresses:[],fqdns:[r.Public_MdnTrapRelaySkypeFqdns],tcpPort:443,udpPort:3478},Turn:{addresses:[],fqdns:[r.Public_MdnTrapRelayTurnFqdns],tcpPort:443,udpPort:3478,url:r.Public_MdnTrapRelayTurnUrl}},Http:{connectionTimeout:30,requestTimeout:60},Token:{earlyRefreshMinutes:1080,earlyRefreshPercentage:25}},this._TrouterJScriptClient={TelemetryEnabled:!1,ClientTelemetryEventEnabled:{trouter_js_client_connected:!1,trouter_js_client_disconnected:!1,trouter_js_client_error:!1,trouter_js_client_progress:!1,trouter_js_client_response:!1,trouter_js_client_check_connection:!1,trouter_js_client_registration:!1,trouter_js_client_unregistration:!1,logHealthCheckError:!1,logSendPingError:!1,numberOfStepsToMaintain:0,sendProgressTimeoutSecs:0}}}getTrouterTelemetryConfig(){return{enabled:this._TrouterJScriptClient.TelemetryEnabled,...this._TrouterJScriptClient.ClientTelemetryEventEnabled}}getJamaSettings(){return this._JamaSettings}getClientInformation(){let e=Z().telemetry.reportSdkUaToService,t=Z().telemetry.reportEnvToService;return`ACSWeb(${l2()}/${J2()})`+(t?`/${cke()}`:``)+(e?`/(${this.sdkDiagnosticInformation})`:``)}getJsCsaConfig(){return this._JsCsaConfig.useInternalHttpDispatcher=!(this._acsProxy.hasProxyUrl()||Z().telemetry.sendNetworkInfo),{...this._JsCsaConfig,clientInformation:this.getClientInformation()}}getMdnTrapSettings(){return this._MDNTrapSettings}getTrouterSettings(){return this._trouterSettings}setConfig(e,t){this._logger.info(`Update ECS settings`);let n=Z().calling.applicationSettingsUrls,r=Z().calling.applicationSettingsEudbUrls,i=e&&j4(e.identityType,e.region);if(e?.identityType==$0.Enterprise)i?(this._trouterSettings.trouterServiceUrl=r.Enterprise_TrouterServiceUrl_EUDB,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(r.Enterprise_RegistrarServiceUrl_EUDB)):(this._trouterSettings.trouterServiceUrl=n.Enterprise_TrouterServiceUrl,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(n.Enterprise_RegistrarServiceUrl));else switch(e?.cloudType){case J0.Public:i&&(this._trouterSettings.trouterServiceUrl=r.Public_TrouterServiceUrl_EUDB,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(r.Public_RegistrarServiceUrl_EUDB),this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(r.Public_ConversationServiceUrl_EUDB),this._MDNTrapSettings.Service.url=this._acsProxy.proxyfyUrl(r.Public_MdnTrapServiceUrl_EUDB),this._MDNTrapSettings.Service.tokenUrl=this._acsProxy.proxyfyUrl(r.Public_MdnTrapServiceTokenUrl_EUDB),this._MDNTrapSettings.Relay.Skype.fqdns=[r.Public_MdnTrapRelaySkypeFqdns_EUDB],this._MDNTrapSettings.Relay.Turn.fqdns=[r.Public_MdnTrapRelayTurnFqdns_EUDB],this._MDNTrapSettings.Relay.Turn.url=r.Public_MdnTrapRelayTurnUrl_EUDB);break;case J0.GccHigh:this._trouterSettings.trouterServiceUrl=n.GccHigh_TrouterServiceUrl,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(n.GccHigh_RegistrarServiceUrl);break;case J0.Dod:this._trouterSettings.trouterServiceUrl=n.Dod_TrouterServiceUrl,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(n.Dod_RegistrarServiceUrl);break;case J0.AirGap08:this._trouterSettings.trouterServiceUrl=n.AirGap08_TrouterServiceUrl,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(n.AirGap08_RegistrarServiceUrl);break;case J0.AirGap09:this._trouterSettings.trouterServiceUrl=n.AirGap09_TrouterServiceUrl,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(n.AirGap09_RegistrarServiceUrl)}if(t)this.setConfigOrDefault(t?.SkypeCalling,this._JsCsaConfig),this.setConfigOrDefault(t?.MDN_TRAP,this._MDNTrapSettings),this.setConfigOrDefault(t?.SkypeWebMedia?.mediaAgent,this._JamaSettings),this.setConfigOrDefault(t?.TrouterJScriptClient,this._TrouterJScriptClient);else if(e?.identityType===$0.Enterprise)i?(this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(r.Enterprise_ConversationServiceUrl_EUDB),this._MDNTrapSettings.Service.url=this._acsProxy.proxyfyUrl(r.Enterprise_MdnTrapServiceUrl_EUDB),this._MDNTrapSettings.Service.tokenUrl=this._acsProxy.proxyfyUrl(r.Enterprise_MdnTrapServiceTokenUrl_EUDB),this._MDNTrapSettings.Relay.Skype.fqdns=[r.Enterprise_MdnTrapRelaySkypeFqdns_EUDB],this._MDNTrapSettings.Relay.Turn.fqdns=[r.Enterprise_MdnTrapRelayTurnFqdns_EUDB],this._MDNTrapSettings.Relay.Turn.url=r.Enterprise_MdnTrapRelayTurnUrl_EUDB):(this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(n.Enterprise_ConversationServiceUrl),this._MDNTrapSettings.Service.url=this._acsProxy.proxyfyUrl(n.Enterprise_MdnTrapServiceUrl),this._MDNTrapSettings.Service.tokenUrl=this._acsProxy.proxyfyUrl(n.Enterprise_MdnTrapServiceTokenUrl),this._MDNTrapSettings.Relay.Skype.fqdns=[n.Enterprise_MdnTrapRelaySkypeFqdns],this._MDNTrapSettings.Relay.Turn.fqdns=[n.Enterprise_MdnTrapRelayTurnFqdns],this._MDNTrapSettings.Relay.Turn.url=n.Enterprise_MdnTrapRelayTurnUrl);else switch(e?.cloudType){case J0.Public:i&&(this._trouterSettings.trouterServiceUrl=r.Public_TrouterServiceUrl_EUDB,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(r.Public_RegistrarServiceUrl_EUDB),this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(r.Public_ConversationServiceUrl_EUDB),this._MDNTrapSettings.Service.url=this._acsProxy.proxyfyUrl(r.Public_MdnTrapServiceUrl_EUDB),this._MDNTrapSettings.Service.tokenUrl=this._acsProxy.proxyfyUrl(r.Public_MdnTrapServiceTokenUrl_EUDB),this._MDNTrapSettings.Relay.Skype.fqdns=[r.Public_MdnTrapRelaySkypeFqdns_EUDB],this._MDNTrapSettings.Relay.Turn.fqdns=[r.Public_MdnTrapRelayTurnFqdns_EUDB],this._MDNTrapSettings.Relay.Turn.url=r.Public_MdnTrapRelayTurnUrl_EUDB);break;case J0.GccHigh:this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(n.GccHigh_ConversationServiceUrl),this._MDNTrapSettings.Service.url=this._acsProxy.proxyfyUrl(n.GccHigh_MdnTrapServiceUrl),this._MDNTrapSettings.Service.tokenUrl=this._acsProxy.proxyfyUrl(n.GccHigh_MdnTrapServiceTokenUrl),this._MDNTrapSettings.Relay.Skype.fqdns=[n.GccHigh_MdnTrapRelaySkypeFqdns],this._MDNTrapSettings.Relay.Turn.fqdns=[n.GccHigh_MdnTrapRelayTurnFqdns],this._MDNTrapSettings.Relay.Turn.url=n.GccHigh_MdnTrapRelayTurnUrl;break;case J0.Dod:this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(n.Dod_ConversationServiceUrl),this._MDNTrapSettings.Service.url=this._acsProxy.proxyfyUrl(n.Dod_MdnTrapServiceUrl),this._MDNTrapSettings.Service.tokenUrl=this._acsProxy.proxyfyUrl(n.Dod_MdnTrapServiceTokenUrl),this._MDNTrapSettings.Relay.Skype.fqdns=[n.Dod_MdnTrapRelaySkypeFqdns],this._MDNTrapSettings.Relay.Turn.fqdns=[n.Dod_MdnTrapRelayTurnFqdns],this._MDNTrapSettings.Relay.Turn.url=n.Dod_MdnTrapRelayTurnUrl;break;case J0.AirGap08:this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(n.AirGap08_ConversationServiceUrl);break;case J0.AirGap09:this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(n.AirGap09_ConversationServiceUrl)}}static assertConfigs(e){let t=[];if(e?.SkypeCalling||t.push(`SkypeCalling`),e?.MDN_TRAP||t.push(`MDN_TRAP`),e?.SkypeWebMedia?e?.SkypeWebMedia?.mediaAgent||t.push(`SkypeWebMedia.mediaAgent`):t.push(`SkypeWebMedia`),e?.TrouterJScriptClient||t.push(`TrouterJScriptClient`),t.length>0)throw new Y({defaultError:J.CALL_STACK.FOUND_UNDEFINED_CONFIGS,defaultErrorMessageArgs:[t.join(`, `)]})}},_Le,n9={exports:{}},r9={exports:{}};r9.exports;function vLe(){return _Le||(_Le=1,e=r9,r9.exports,t=()=>{return e={659:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toJson=t.fetchWithTimeout=void 0,t.fetchWithTimeout=function(e,t){var n,r=new Promise((function(t,r){fetch(e).then((function(e){n!==void 0&&clearTimeout(n),t(e)})).catch((function(e){n!==void 0&&clearTimeout(n),r(e)}))}));if(t!==0){var i=new Promise((function(r,i){n=setTimeout(i,t,Error(`Fetch for '${e.url}' timed out`))}));return Promise.race([r,i])}return r},t.toJson=function(e){try{return JSON.stringify(e)}catch{return`Unable to serialize object of type ${typeof e}`}}},912:function(e,t,n){var r,i=this&&this.__extends||(r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},r(e,t)},function(e,t){if(typeof t!=`function`&&t!==null)throw TypeError(`Class extends value `+String(t)+` is not a constructor or null`);function n(){this.constructor=e}r(e,t),e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}),a=this&&this.__assign||function(){return a=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},a.apply(this,arguments)},o=this&&this.__awaiter||function(e,t,n,r){return new(n||=Promise)((function(i,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((r=r.apply(e,t||[])).next())}))},s=this&&this.__generator||function(e,t){var n,r,i,a,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol==`function`&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(c){return function(s){if(n)throw TypeError(`Generator is already executing.`);for(;a&&(a=0,s[0]&&(o=0)),o;)try{if(n=1,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,r=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((i=(i=o.trys).length>0&&i[i.length-1])||s[0]!==6&&s[0]!==2)){o=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){o.label=s[1];break}if(s[0]===6&&o.label<i[1]){o.label=i[1],i=s;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(s);break}i[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],r=0}finally{n=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}};Object.defineProperty(t,"__esModule",{value:!0}),t.createRegistrarClient=t.RegistrarClient=void 0;var c=n(659),l=[`skype`,`aad`,`cae`],u=function(e){function t(t){var n=e.call(this,t)||this;return n.name=`CancelationError`,n}return i(t,e),t}(Error),d=function(){function e(t,n,r){this.logger=t,this.maxBackoffInMs=n,this.initialDelay=r,this.backoffCount=0,this.id=++e.idCounter}return e.prototype.delay=function(e){var t=this;if(this.timerHandle!==void 0)throw Error(`Retry sequence logical failure`);if(this.backoffCount===-1)return new Promise((function(e,t){t(new u(`Cancelled`))}));var n=this.calculateNextBackoffMs();return this.backoffCount++,this.logger.info(`[RegistrarClient] Backing off ${e} for ${n} milliseconds with ID ${this.id}`),new Promise((function(r,i){t.cancelFunc=i,t.timerHandle=setTimeout((function(){t.logger.info(`[RegistrarClient] Back off for ${e} with ID ${t.id} complete`),t.timerHandle=void 0,r()}),n)}))},e.prototype.cancel=function(){this.timerHandle!==void 0&&(this.logger.debug(`Resetting back off`),clearTimeout(this.timerHandle),this.cancelFunc!==void 0&&this.cancelFunc(new u(`Cancelled`))),this.backoffCount=-1},e.prototype.calculateNextBackoffMs=function(){var e=1+.4*(Math.random()-.5),t=this.initialDelay*2**this.backoffCount*e;return t=Math.round(t),Math.min(this.maxBackoffInMs,t)},e.idCounter=0,e}(),f=function(){function e(e,t,n){this.logger=e,this.tokenProvider=t,this.options=n,this.DEFAULT_MAX_RETRIES_FOR_GET_TOKEN=15,this.DEFAULT_MAX_BACKOFF_TIME_IN_MS=3e5,this.backoffs={},this.maxBackOffTime=this.options.maxRetryDelayMs>0?this.options.maxRetryDelayMs:this.DEFAULT_MAX_BACKOFF_TIME_IN_MS,this.maxRetriesForGetToken=n.maxRetriesForGetToken===void 0||n.maxRetriesForGetToken===null?this.DEFAULT_MAX_RETRIES_FOR_GET_TOKEN:n.maxRetriesForGetToken,this.proxyUrlRewrite=n.proxyUrlRewrite??function(e){return e}}return e.prototype.register=function(e,t){return o(this,void 0,void 0,(function(){return s(this,(function(n){switch(n.label){case 0:return[4,this.performRegistration(e,t)];case 1:return n.sent(),this.cachedRegistrationParams=[e,t],[2]}}))}))},e.prototype.unregister=function(){return o(this,void 0,void 0,(function(){var e;return s(this,(function(t){switch(t.label){case 0:return this.logger.info(`[RegistrarClient] sending unregister request`),e=new Request(this.proxyUrlRewrite(`${this.options.registrarUrl}/${this.options.registrationId}`),{method:`DELETE`,mode:`cors`,headers:new Headers(a(a({},this.options.extraRegistrationHeaders),{accept:`application/json, text/javascript`}))}),[4,this.callRegistrar(e)];case 1:return t.sent(),[2]}}))}))},e.prototype.cancelPendingRequests=function(){var e=this;Object.keys(this.backoffs).forEach((function(t){e.backoffs[t].cancel()})),this.backoffs={}},e.prototype.resendRegistration=function(){return o(this,void 0,void 0,(function(){return s(this,(function(e){switch(e.label){case 0:if(!this.cachedRegistrationParams)throw Error(`Re-registration failed because there is no registration parameters cached`);return[4,this.performRegistration(this.cachedRegistrationParams[0],this.cachedRegistrationParams[1])];case 1:return e.sent(),[2]}}))}))},e.prototype.performRegistration=function(e,t){return o(this,void 0,void 0,(function(){var n,r;return s(this,(function(i){switch(i.label){case 0:return this.logger.info(`[RegistrarClient] Sending register request`),n={clientDescription:e,registrationId:this.options.registrationId,nodeId:``,transports:t},r=new Request(this.proxyUrlRewrite(this.options.registrarUrl),{method:`POST`,mode:`cors`,headers:new Headers(a(a({},this.options.extraRegistrationHeaders),{"content-type":`application/json`,accept:`application/json, text/javascript`})),body:(0,c.toJson)(n)}),[4,this.callRegistrar(r)];case 1:return i.sent(),[2]}}))}))},e.prototype.startBackoff=function(){var e=new d(this.logger,this.maxBackOffTime,this.options.initialRetryDelayMs);return this.backoffs[e.id]=e,e},e.prototype.stopBackoff=function(e){e.cancel(),delete this.backoffs[e.id]},e.prototype.getToken=function(e){return o(this,void 0,void 0,(function(){var t,n,r,i,a,o,c;return s(this,(function(s){switch(s.label){case 0:t=this.startBackoff(),n=0,s.label=1;case 1:return s.trys.push([1,3,,8]),this.logger.info(`[RegistrarClient] Asking for a new token`),[4,this.tokenProvider({needFresh:!0,supportedTokenTypes:l,wwwAuthenticateHeader:e,purpose:`registrar`})];case 2:return r=s.sent(),this.stopBackoff(t),[2,r];case 3:i=s.sent(),s.label=4;case 4:return s.trys.push([4,6,,7]),n++,a=JSON.stringify(i),n>this.maxRetriesForGetToken?(o=`[RegistrarClient] getToken retry limit hit. Will not retry now. Error: ${a}`,this.logger.error(o),this.stopBackoff(t),[2,Promise.reject(o)]):(this.logger.warn(`[RegistrarClient] Retrying for a new token. Retry Count: ${n} Error: ${a}`),[4,t.delay(`Fetching a new token`)]);case 5:return s.sent(),[3,8];case 6:throw c=s.sent(),this.stopBackoff(t),c;case 7:return[3,8];case 8:return[3,1];case 9:return[2]}}))}))},e.prototype.callRegistrar=function(e){return o(this,void 0,void 0,(function(){var t,n,r,i,a,o,u,d,f,p,m,h,g,_,v;return s(this,(function(s){switch(s.label){case 0:return t=this.startBackoff(),[4,this.tokenProvider({needFresh:!1,supportedTokenTypes:l,wwwAuthenticateHeader:void 0,purpose:`registrar`})];case 1:n=s.sent(),this.setTokenHeader(e,n),r=0,s.label=2;case 2:i=void 0,s.label=3;case 3:return s.trys.push([3,10,,15]),a=e.clone(),[4,(0,c.fetchWithTimeout)(a,this.options.requestTimeoutMs)];case 4:return(i=s.sent()).status===401?++r>this.maxRetriesForGetToken?(o=`[RegistrarClient] getSkypeToken retry limit hit. Will not retry now. Request '${e.url}' failed with ${i.status} ${i.statusText}`,this.logger.error(o),this.stopBackoff(t),[2,Promise.reject(o)]):(this.logger.warn(`[RegistrarClient] Retry Count ${r}. Request '${e.url}' failed with ${i.status} ${i.statusText}`),u=i.headers?.get(`www-authenticate`)??void 0,d=this.setTokenHeader,f=[e],[4,this.getToken(u)]):[3,8];case 5:return d.apply(this,f.concat([s.sent()])),r>1?[4,t.delay(`Registrar call retry after 401`)]:[3,7];case 6:s.sent(),s.label=7;case 7:return[3,21];case 8:if(i.status>=500&&i.status<600)throw Error(`Fetch for '${e.url}' failed with ${i.status} ${i.statusText}`);s.label=9;case 9:return[3,15];case 10:p=s.sent(),this.logger.error(`[RegistrarClient] Request failed with ${p}`),s.label=11;case 11:return s.trys.push([11,13,,14]),[4,t.delay(`Registrar call retry`)];case 12:return s.sent(),[3,21];case 13:throw m=s.sent(),this.logger.error(`[RegistrarClient] Request cancelled`),this.stopBackoff(t),m;case 14:return[3,15];case 15:return this.stopBackoff(t),i.ok?[2,i]:[3,16];case 16:h=void 0,s.label=17;case 17:return s.trys.push([17,19,,20]),_=(g=JSON).stringify,[4,i.json()];case 18:return h=_.apply(g,[s.sent()]),[3,20];case 19:return s.sent(),h=`no details`,[3,20];case 20:throw v=`Fetch for '${e.url}' failed with ${i.status} ${i.statusText} (${h}, MS-CV: ${i.headers?.get(`MS-CV`)})`,this.logger.error(`[RegistrarClient] ${v}`),Error(v);case 21:return[3,2];case 22:return[2]}}))}))},e.prototype.setTokenHeader=function(e,t){switch(e.headers.delete(`X-Skypetoken`),e.headers.delete(`Authorization`),e.headers.delete(`X-MS-Migration`),t.tokenType.toLowerCase()){case`skype`:e.headers.set(`X-Skypetoken`,t.token);break;case`aad`:case`cae`:e.headers.set(`Authorization`,`Bearer ${t.token}`);break;default:throw Error(`unsupported token type: ${t.tokenType}`)}!1===this.options.usingLegacyTokenApi&&e.headers.set(`X-MS-Migration`,`True`)},e}();t.RegistrarClient=f,t.createRegistrarClient=function(e,t,n){return new f(e,t,n)}}},t={},function n(r){var i=t[r];if(i!==void 0)return i.exports;var a=t[r]={exports:{}};return e[r].call(a.exports,a,a.exports,n),a.exports}(912);var e,t},e.exports=t()),r9.exports;var e,t}var yLe;n9.exports;function bLe(){return yLe||(yLe=1,e=n9,n9.exports,t=e=>(()=>{var t={10:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterManagerFsm=void 0;var r=n(234),i=n(423),a=n(642),o=n(573);t.TrouterManagerFsm=function(){function e(e,t){this.worker=t,this.state=i.TrouterManagerState.Unknown,this.logger=new a.Logger(`ManagerFsm`,e)}return e.prototype.start=function(){this.state===i.TrouterManagerState.Unknown?(this.setState(i.TrouterManagerState.Disconnected),this.worker.forceStopLingeringConnection(),this.worker.startFirstConnection()):(this.logger.info(`start called in state '${i.TrouterManagerState[this.state]}', expediting pending backoffs, if any`),this.worker.expediteBackoffOnConnections())},e.prototype.stop=function(e){this.state===i.TrouterManagerState.Unknown?this.showIgnored(`stop`):(this.setState(i.TrouterManagerState.Unknown),this.worker.stopFirstConnection(!0===e),this.worker.stopSecondConnection(!0===e))},e.prototype.getState=function(){switch(this.state){case i.TrouterManagerState.Unknown:case i.TrouterManagerState.Connected:case i.TrouterManagerState.Disconnected:case i.TrouterManagerState.Switching:return this.state;case i.TrouterManagerState.TerminalError:return r.TrouterState.Disconnected}},e.prototype.getInternalState=function(){return this.state},e.prototype.onConnected=function(e){this.state===i.TrouterManagerState.Disconnected&&e?this.worker.doesSecondConnectionExist()?this.setState(i.TrouterManagerState.Switching):(this.setState(i.TrouterManagerState.Connected),this.worker.dispatchConnected()):this.showIgnored(`onConnected(${e})`)},e.prototype.onRegistered=function(e){this.state!==i.TrouterManagerState.Disconnected||e?this.state!==i.TrouterManagerState.Switching||e?this.state===i.TrouterManagerState.Disconnected&&e&&(this.setState(i.TrouterManagerState.Connected),this.worker.dispatchConnected()):(this.setState(i.TrouterManagerState.Connected),this.worker.switchConnections(),this.worker.stopSecondConnectionDelayed(),this.worker.dispatchConnected()):(this.setState(i.TrouterManagerState.Connected),this.worker.switchConnections(),this.worker.stopSecondConnection(!0),this.worker.dispatchConnected()),this.worker.dispatchRegistrationState(!0)},e.prototype.onUnregistered=function(e){e&&this.worker.dispatchRegistrationState(!1)},e.prototype.onReconnecting=function(e){this.state!==i.TrouterManagerState.Connected&&this.state!==i.TrouterManagerState.Switching||!e?this.showIgnored(`onReconnecting(${e})`):(this.setState(i.TrouterManagerState.Disconnected),this.worker.dispatchDisconnected())},e.prototype.onReconnectionRequired=function(e,t,n){this.state===i.TrouterManagerState.Connected&&e?(this.setState(i.TrouterManagerState.Switching),this.worker.startSecondConnection(t)):this.state===i.TrouterManagerState.Disconnected&&e?this.worker.startSecondConnection(t):this.state===i.TrouterManagerState.Switching&&e&&n===o.ReconnectReason.Configuration?(this.logger.debug(`onReconnectionRequired: switch requested while already in Switching state`),this.worker.stopSecondConnection(!0),this.worker.startSecondConnection(t)):this.showIgnored(`onReconnectionRequired(${e})`)},e.prototype.onDisconnected=function(e){this.state==i.TrouterManagerState.Unknown&&e?this.worker.dispatchDisconnected():this.state==i.TrouterManagerState.Switching&&e?(this.worker.switchConnections(),this.worker.stopSecondConnection(!1),this.setState(i.TrouterManagerState.Disconnected),this.worker.dispatchDisconnected()):this.showIgnored(`onDisconnected(${e})`)},e.prototype.onTerminalError=function(){this.setState(i.TrouterManagerState.TerminalError),this.worker.dispatchTerminalError()},e.prototype.showIgnored=function(e){this.logger.info(`Ignoring event '${e}' in state '${i.TrouterManagerState[this.state]}'`)},e.prototype.setState=function(e){this.logger.info(`Switching from state '${i.TrouterManagerState[this.state]}' to state '${i.TrouterManagerState[e]}'`),this.state===e?this.logger.error(`Attempt to switch to the current state '${i.TrouterManagerState[e]}'`):this.state=e},e}()},107:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExponentialBackoff=void 0,t.ExponentialBackoff=function(){function e(e,t,n){n===void 0&&(n={tolerance:2,minimumWaitMs:1e4}),this.logger=e,this.maxBackoffInMs=t,this.gapDetectionSettings=n,this.backoffId=0,this.backoffCount=0}return e.calculateNextBackoffMs=function(e,t){var n=1+.4*(Math.random()-.5),r=1e3*2**e*n;return r=Math.round(r),Math.min(t,r)},e.prototype.setMaxBackoffMs=function(e){this.maxBackoffInMs=e},e.prototype.backoff=function(t,n){var r=this;if(this.timerHandle!==void 0&&(this.logger.debug(`Clearing current back off`),clearTimeout(this.timerHandle),this.timerHandle=void 0),this.previousCompleteTime!==void 0){var i=Date.now()-this.previousCompleteTime;i>this.maxBackoffInMs*this.gapDetectionSettings.tolerance&&i>this.gapDetectionSettings.minimumWaitMs&&(this.logger.info(`Back off for ${t} with ID ${this.backoffId} will be reset due to a lot of time having passed since the previous backoff (${i} ms)`),this.backoffCount=0,this.previousCompleteTime=void 0)}var a=e.calculateNextBackoffMs(this.backoffCount,this.maxBackoffInMs);this.backoffId++,this.backoffCount++,this.logger.info(`Backing off ${t} for ${a} milliseconds with ID ${this.backoffId}`),this.callback=function(e,i){(function(e,t,n){if(e===void 0||t===void 0)return!1;var r=Date.now()-e;return r>t*n.tolerance&&r>n.minimumWaitMs})(e,i,r.gapDetectionSettings)&&(r.logger.info(`Back off for ${t} with ID ${r.backoffId} will be reset due to the wait (${Date.now()-(e??0)} ms) being longer than expected (${i} ms)`),r.backoffCount=0),r.logger.info(`Back off for ${t} with ID ${r.backoffId} complete, invoking handler`),r.timerHandle=void 0,r.callback=void 0,r.previousCompleteTime=Date.now(),n()};var o=Date.now();this.timerHandle=setTimeout((function(){return r.callback?.call(r,o,a)}),a)},e.prototype.reset=function(){this.timerHandle!==void 0&&(this.logger.debug(`Resetting back off with ID ${this.backoffId}`),clearTimeout(this.timerHandle),this.timerHandle=void 0,this.callback=void 0),this.backoffCount=0},e.prototype.expediteIfPending=function(){if(this.backoffCount=0,this.timerHandle!==void 0){this.logger.debug(`Expediting back off with ID ${this.backoffId}`),clearTimeout(this.timerHandle),this.timerHandle=void 0;var e=this.callback;this.callback=void 0,e&&e()}},e}()},220:function(e,t){var n=this&&this.__awaiter||function(e,t,n,r){return new(n||=Promise)((function(i,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((r=r.apply(e,t||[])).next())}))},r=this&&this.__generator||function(e,t){var n,r,i,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},o=Object.create((typeof Iterator==`function`?Iterator:Object).prototype);return o.next=s(0),o.throw=s(1),o.return=s(2),typeof Symbol==`function`&&(o[Symbol.iterator]=function(){return this}),o;function s(s){return function(c){return function(s){if(n)throw TypeError(`Generator is already executing.`);for(;o&&(o=0,s[0]&&(a=0)),a;)try{if(n=1,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,r=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((i=(i=a.trys).length>0&&i[i.length-1])||s[0]!==6&&s[0]!==2)){a=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){a.label=s[1];break}if(s[0]===6&&a.label<i[1]){a.label=i[1],i=s;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(s);break}i[2]&&a.ops.pop(),a.trys.pop();continue}s=t.call(e,a)}catch(e){s=[6,e],r=0}finally{n=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}};Object.defineProperty(t,"__esModule",{value:!0}),t.addCacheAsBackupTo=function(e){var t,i=this;return function(a){return n(i,void 0,void 0,(function(){return r(this,(function(n){return a&&(t=void 0),[2,new Promise((function(n,r){e(a).then((function(e){t=e,n(e)})).catch((function(e){t!==void 0&&t.length>0&&n(t),r(e)}))}))]}))}))}}},234:(e,t)=>{var n,r;Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterState=t.UserActivityState=void 0,function(e){e[e.Unknown=0]=`Unknown`,e[e.Active=1]=`Active`,e[e.Inactive=2]=`Inactive`}(n||(t.UserActivityState=n={})),function(e){e[e.Unknown=0]=`Unknown`,e[e.Connected=2]=`Connected`,e[e.Disconnected=3]=`Disconnected`,e[e.Switching=9]=`Switching`}(r||(t.TrouterState=r={}))},235:function(e,t,n){var r=this&&this.__spreadArray||function(e,t,n){if(n||arguments.length===2)for(var r,i=0,a=t.length;i<a;i++)!r&&i in t||(r||=Array.prototype.slice.call(t,0,i),r[i]=t[i]);return e.concat(r||Array.prototype.slice.call(t))};Object.defineProperty(t,"__esModule",{value:!0}),t.LoggingManagerConsumer=t.RegistrationEnforcer=void 0;var i=n(335);t.RegistrationEnforcer=function(){function e(e,t,n){this.wrapped=e,this.shouldConnectionDependOnRegistration=t,this.shouldHoldBackEvents=n,this.isRegistered=!1,this.heldBackEvents=[]}return e.prototype.onDownstreamRequest=function(e,t,n){this.passIfRegisteredOrNotNeeded(`onDownstreamRequest`,e,t,n)},e.prototype.onConnected=function(e){this.passIfRegisteredOrNotNeeded(`onConnected`,e)},e.prototype.onRegistered=function(e){this.isRegistered=!0,this.wrapped.onRegistered(e),this.fireHeldBackEvents()},e.prototype.onUnregistered=function(e){var t=this.isRegistered;this.isRegistered=!1,this.wrapped.onUnregistered(e),t&&e.getState()===i.State.Connected&&this.shouldConnectionDependOnRegistration()&&e.forceReconnectDueToNoRegistration()},e.prototype.onReconnecting=function(e){this.wrapped.onReconnecting(e)},e.prototype.onReconnectIsRequired=function(e,t,n){this.wrapped.onReconnectIsRequired(e,t,n)},e.prototype.onDisconnected=function(e){this.isRegistered=!1,this.dropHeldBackEvents(),this.wrapped.onDisconnected(e)},e.prototype.onTerminalError=function(e){this.wrapped.onTerminalError(e)},e.prototype.onConnectionParametersUpdated=function(e){this.wrapped.onConnectionParametersUpdated(e)},e.prototype.onTrouterMessageLost=function(e){this.passIfRegisteredOrNotNeeded(`onTrouterMessageLost`,e)},e.prototype.onUserActivityStateAccepted=function(e){this.passIfRegisteredOrNotNeeded(`onUserActivityStateAccepted`,e)},e.prototype.onAudiencesSetResolved=function(e,t){this.passIfRegisteredOrNotNeeded(`onAudiencesSetResolved`,e,t)},e.prototype.getState=function(){return this.wrapped.getState()},e.prototype.holdBackEvent=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];this.heldBackEvents.push({kind:e,args:t})},e.prototype.passIfRegisteredOrNotNeeded=function(e){for(var t,n=[],i=1;i<arguments.length;i++)n[i-1]=arguments[i];var a=this.shouldConnectionDependOnRegistration(),o=this.shouldHoldBackEvents();a&&o||this.fireHeldBackEvents(a?function(e){return e.kind!==`onConnected`}:void 0),this.isRegistered||!a||!1===o&&e!==`onConnected`?(t=this.wrapped)[e].apply(t,n):this.holdBackEvent.apply(this,r([e],n,!1))},e.prototype.fireHeldBackEvents=function(e){for(var t,n=0,r=this.heldBackEvents;n<r.length;n++){var i=r[n];(e===void 0||e(i))&&(t=this.wrapped)[i.kind].apply(t,i.args)}this.heldBackEvents=e===void 0?[]:this.heldBackEvents.filter((function(t){return!e(t)}))},e.prototype.dropHeldBackEvents=function(){this.heldBackEvents=[]},e}(),t.LoggingManagerConsumer=function(){function e(e,t,n,r){this.wrapped=e,this.prefix=t,this.logger=n,this.onEventAction=r}return e.prototype.onEvent=function(e,t){this.onEventAction===void 0?(this.logger??console).log(`${this.prefix} TracingEnforcer: ${e}(${t})`):this.onEventAction(e,t)},e.prototype.onDownstreamRequest=function(e,t,n){this.onEvent(`onDownstreamRequest`,JSON.stringify({request:t,response:n})),this.wrapped.onDownstreamRequest(e,t,n)},e.prototype.onConnected=function(e){this.onEvent(`onConnected`,e.getState().toString()),this.wrapped.onConnected(e)},e.prototype.onRegistered=function(e){this.onEvent(`onRegistered`,e.getState().toString()),this.wrapped.onRegistered(e)},e.prototype.onUnregistered=function(e){this.onEvent(`onUnregistered`,e.getState().toString()),this.wrapped.onUnregistered(e)},e.prototype.onReconnecting=function(e){this.onEvent(`onReconnecting`,e.getState().toString()),this.wrapped.onReconnecting(e)},e.prototype.onReconnectIsRequired=function(e,t,n){this.onEvent(`onReconnectIsRequired`,JSON.stringify({connection:e.getState().toString(),useConnectParamsFromCache:t,reason:n})),this.wrapped.onReconnectIsRequired(e,t,n)},e.prototype.onDisconnected=function(e){this.onEvent(`onDisconnected`,e.getState().toString()),this.wrapped.onDisconnected(e)},e.prototype.onTerminalError=function(e){this.onEvent(`onTerminalError`,JSON.stringify({connection:e})),this.wrapped.onTerminalError(e)},e.prototype.onConnectionParametersUpdated=function(e){this.onEvent(`onConnectionParametersUpdated`,JSON.stringify({connectParams:e})),this.wrapped.onConnectionParametersUpdated(e)},e.prototype.onTrouterMessageLost=function(e){this.onEvent(`onTrouterMessageLost`,JSON.stringify({flowTags:e})),this.wrapped.onTrouterMessageLost(e)},e.prototype.onUserActivityStateAccepted=function(e){this.onEvent(`onUserActivityStateAccepted`,JSON.stringify({cv:e})),this.wrapped.onUserActivityStateAccepted(e)},e.prototype.onAudiencesSetResolved=function(e,t){this.onEvent(`onAudiencesSetResolved`,JSON.stringify({audienceSubscriptionsResponse:e,cv:t})),this.wrapped.onAudiencesSetResolved(e,t)},e.prototype.getState=function(){return this.wrapped.getState()},e}()},335:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterFsm=t.State=void 0;var r,i,a=n(423),o=n(642),s=n(902);(function(e){e[e.Initial=0]=`Initial`,e[e.RetrievingToken=1]=`RetrievingToken`,e[e.Allocating=2]=`Allocating`,e[e.Handshaking=3]=`Handshaking`,e[e.Connecting=4]=`Connecting`,e[e.AnonymousConnecting=5]=`AnonymousConnecting`,e[e.WebsocketAuthenticating=6]=`WebsocketAuthenticating`,e[e.Connected=7]=`Connected`,e[e.Unregistering=8]=`Unregistering`,e[e.TerminalError=9]=`TerminalError`})(r||(t.State=r={})),function(e){e[e.Initial=0]=`Initial`,e[e.Registering=1]=`Registering`,e[e.RegisteringButResendPending=2]=`RegisteringButResendPending`,e[e.Retrying=3]=`Retrying`,e[e.Registered=4]=`Registered`,e[e.RegistrationDisabled=5]=`RegistrationDisabled`}(i||={}),t.TrouterFsm=function(){function e(e,t,n,a){this.worker=t,this.incallModeEnabled=n,this.protocolSelector=a,this.state=r.Initial,this.autoReconnect=!0,this.logger=new o.Logger(`ConnectionFsm`,e),this.registrationState=i.Initial}return e.prototype.getState=function(){return this.state},e.prototype.isActive=function(){return this.state===r.Allocating||this.state===r.Connected||this.state===r.Handshaking||this.state===r.Connecting||this.state===r.RetrievingToken||this.state===r.AnonymousConnecting||this.state===r.WebsocketAuthenticating},e.prototype.isConnecting=function(){return this.state===r.Allocating||this.state===r.Handshaking||this.state===r.Connecting||this.state===r.AnonymousConnecting},e.prototype.start=function(){return this.state===r.Initial?(this.setState(r.RetrievingToken),this.worker.getToken(!0,!1,void 0),!0):(this.showIgnored(`start`),!1)},e.prototype.stop=function(e,t){e&&(this.registrationState=i.Initial),this.worker.isIncallMode()&&this.worker.exitIncallMode(),this.worker.resetTokenBackoff(),this.worker.cancelPendingRegistrationRequests(),this.worker.stopConnectionTimer(),this.worker.stopPingTimer(),this.worker.clearSentEventTimers(),this.worker.stopRegistrationTimer(),this.worker.stopSocketIo(),this.state===r.Connected&&this.worker.sendDisconnectTelemetryEvent(`connection stopped`),this.registrationState!==i.Registered&&this.registrationState!==i.Registering&&this.registrationState!==i.RegisteringButResendPending||this.state===r.Unregistering?t?(this.setState(r.TerminalError),this.worker.dispatchTerminalError()):(this.setState(r.Initial),this.worker.dispatchDisconnected()):(this.registrationState=i.Initial,this.setState(r.Unregistering),this.worker.sendUnregisterRequest())},e.prototype.onTokenReceived=function(e,t,n){this.state===r.RetrievingToken?(0,s.usedProtocolAfterFallback)(this.protocolSelector(e.tokenType,n),t)===`v4c`?(this.setState(r.AnonymousConnecting),this.worker.startConnectionTimer(),this.worker.connectV4c(e,t)):(this.setState(r.Allocating),this.worker.startConnectionTimer(),this.worker.sendAllocateRequest(e)):this.showIgnored(`onTokenReceived`)},e.prototype.checkConnection=function(e){e&&this.onPingInterval()},e.prototype.onAllocationSucceed=function(e){return this.state===r.Allocating&&this.registrationState===i.Registered&&this.worker.dispatchUnregistered(),this.state===r.Allocating?(this.setState(r.Handshaking),this.registrationState=i.Initial,this.worker.startSocketIo(e),!0):(this.showIgnored(`onAllocationSucceed`),!1)},e.prototype.onAllocationFailed=function(e,t){this.state===r.Allocating?this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!e,claimsChallenge:t}):this.showIgnored(`onAllocationFailed`)},e.prototype.onV4cConnectivityCheckFailed=function(){this.state===r.AnonymousConnecting?this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!0}):this.showIgnored(`onV4cConnectivityCheckFailed`)},e.prototype.onV4cException=function(){this.state!==r.AnonymousConnecting&&this.state!==r.WebsocketAuthenticating||(this.logger.error(`v4c exception, falling back to longpoll`),this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!0,fallbackReason:{kind:`v4c-websocket-failure`}}))},e.prototype.onConnectingTimeout=function(){this.state===r.Allocating||this.state===r.Connecting||this.state===r.Handshaking||this.state===r.AnonymousConnecting||this.state===r.WebsocketAuthenticating?this.cleanUpAndInitiateReconnect({backoff:!1,allowCachedToken:!0}):this.showIgnored(`onConnectingTimeout`)},e.prototype.onConnecting=function(){this.state===r.Handshaking?this.setState(r.Connecting):this.showIgnored(`onConnecting`)},e.prototype.onSocketConnect=function(e){this.state===r.AnonymousConnecting?(this.setState(r.WebsocketAuthenticating),this.worker.sendV4cAuthenticationEvent(e)):this.showIgnored(`onSocketConnect`)},e.prototype.onConnectingFailed=function(){this.state===r.Connecting?this.onConnectingTimeout():this.state===r.Handshaking?(this.logger.error(`Unexpected error in Socket.io - no valid transports`),this.onConnectingTimeout()):this.state===r.AnonymousConnecting||this.state===r.WebsocketAuthenticating?(this.logger.info(`/v4/c falling back to longpoll`),this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!0,fallbackReason:{kind:`v4c-websocket-failure`}})):this.showIgnored(`onConnectingFailed`)},e.prototype.onSocketDisconnect=function(e){this.state===r.Handshaking||this.state===r.Connected||this.state===r.WebsocketAuthenticating?(this.state===r.Connected&&this.worker.sendDisconnectTelemetryEvent(e?.toTelemetryString()),this.state===r.WebsocketAuthenticating&&this.worker.countDisconnectBeforeConnectionEstablishment(),e?.reason===`skypetoken-deprecated`?(this.logger.error(`Skypetoken deprecated response, not retrying any further`),this.onTerminalError()):this.cleanUpAndInitiateReconnect({backoff:this.state!==r.Connected&&e?.reason!==`dup`,allowCachedToken:e?.reason!==`unauthorized`,claimsChallenge:e?.claims})):this.showIgnored(`onSocketDisconnect`)},e.prototype.onTrouterConnected=function(){this.state===r.Connecting||this.state===r.WebsocketAuthenticating?(this.setState(r.Connected),this.worker.resetTokenBackoff(),this.worker.stopConnectionTimer(),this.worker.sendUserActivityState(a.UserActivityEventReason.Connected,!0),this.worker.startPingTimer(),this.worker.dispatchConnected(),this.worker.shouldSkipRegistration()?(this.registrationState=i.RegistrationDisabled,this.worker.dispatchRegistered()):(this.registrationState=i.Registering,this.worker.sendRegisterRequest())):this.showIgnored(`onTrouterConnected`)},e.prototype.onReconnectRequired=function(e,t,n){this.state===r.AnonymousConnecting||this.state===r.WebsocketAuthenticating?n===void 0||n.target!==`host`||n.url===void 0||n.url===``?(this.logger.error(`unexpected reconnect arguments: ${n?.target} ${n?.url}, reconnecting without cache`),this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!0,fallbackReason:{kind:`redirect-no-host`}})):this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!0,fallbackReason:{kind:`redirect`,host:n.url}}):this.worker.dispatchReconnectIsRequired(e,t)},e.prototype.disableAutoReconnect=function(){this.autoReconnect=!1},e.prototype.onDownstreamRequest=function(e){this.state===r.Connected?(this.switchToIncallModeIfEnabled(),this.worker.dispatchDownstreamRequest(e)):this.showIgnored(`onDownstreamRequest`)},e.prototype.onTrouterMessageLost=function(e){this.state===r.Connected?this.worker.dispatchTrouterMessageLost(e):this.showIgnored(`onTrouterMessageLost`)},e.prototype.onPingInterval=function(){this.state===r.Connected?this.worker.sendPingRequest():this.showIgnored(`onPingInterval`)},e.prototype.onPingResponseTimeout=function(){this.onMissedResponse(`onPingResponseTimeout`)},e.prototype.onPingResponse=function(){this.state===r.Connected||this.showIgnored(`onPingResponse`)},e.prototype.onRegistrationFailed=function(){this.state===r.Connected&&this.registrationState===i.Registering?(this.worker.dispatchUnregistered(),this.registrationState=i.Retrying,this.worker.startRegistrationRetryTimer()):this.state===r.Connected&&this.registrationState===i.RegisteringButResendPending?(this.registrationState=i.Registering,this.worker.sendRegisterRequest()):this.showIgnored(`onRegistrationFailed`)},e.prototype.onRetryRegistration=function(){this.state===r.Connected&&this.registrationState===i.Retrying?(this.registrationState=i.Registering,this.worker.sendRegisterRequest()):this.showIgnored(`onRetryRegistration`)},e.prototype.onRegistrationSucceeded=function(){this.state===r.Connected&&this.registrationState===i.Registering?(this.registrationState=i.Registered,this.worker.dispatchRegistered(),this.worker.startRegistrationTimer()):this.state===r.Connected&&this.registrationState===i.RegisteringButResendPending?(this.registrationState=i.Registering,this.worker.sendRegisterRequest()):this.showIgnored(`onRegistrationSucceeded`)},e.prototype.onRegistrationNearExpiry=function(){this.state===r.Connected&&this.registrationState===i.Registered?(this.registrationState=i.Registering,this.worker.sendRegisterRequest()):this.showIgnored(`onRegistrationNearExpiry`)},e.prototype.onUnregistrationDone=function(){this.state===r.Unregistering?(this.setState(r.Initial),this.worker.dispatchUnregistered(),this.worker.dispatchDisconnected()):this.showIgnored(`onUnregistrationDone`)},e.prototype.onResendRegistration=function(){this.worker.dispatchUnregistered(),this.state===r.Connected&&this.registrationState===i.Registered?(this.registrationState=i.Registering,this.worker.stopRegistrationTimer(),this.worker.sendRegisterRequest()):this.state===r.Connected&&this.registrationState===i.Registering&&(this.registrationState=i.RegisteringButResendPending)},e.prototype.onExtraTransportsUpdated=function(){this.state===r.Connected?this.registrationState===i.Registered?(this.registrationState=i.Registering,this.worker.stopRegistrationTimer(),this.worker.sendRegisterRequest()):this.registrationState===i.Registering&&(this.registrationState=i.RegisteringButResendPending):this.state===r.Unregistering||this.state===r.Initial?this.logger.warn(`onExtraTransportsUpdated called while Trouter is stopped, will not be applied until it is next started`):(this.logger.info(`extra transports will be registered when Trouter successfully connects`),this.showIgnored(`onExtraTransportsUpdated`))},e.prototype.onIncallModeTimer=function(){this.worker.exitIncallMode(),this.state===r.Connected?(this.worker.stopPingTimer(),this.worker.startPingTimer()):this.showIgnored(`onIncallModeTimer`)},e.prototype.onSetNewUserActivityState=function(){this.worker.sendUserActivityState(a.UserActivityEventReason.Modified,this.state===r.Connected)},e.prototype.onActivityStateResponseTimeout=function(){this.onMissedResponse(`onActivityStateResponseTimeout`)},e.prototype.forceReconnect=function(e){this.state===r.Connected&&this.worker.sendDisconnectTelemetryEvent(e),this.worker.resetTokenBackoff(),this.cleanUpAndInitiateReconnect({backoff:!1,allowCachedToken:!0})},e.prototype.onTerminalError=function(){this.logger.error(`Cannot proceed, reached terminal state. Switching from state '${r[this.state]}' to ${r[r.TerminalError]}`),this.stop(!0,!0),this.setState(r.TerminalError)},e.prototype.onMissedResponse=function(e){this.state===r.Connected?(this.worker.sendDisconnectTelemetryEvent(e),this.cleanUpAndInitiateReconnect({backoff:!1,allowCachedToken:!0})):this.showIgnored(e)},e.prototype.showIgnored=function(e){this.logger.debug(`Ignoring event '${e}' in state '${r[this.state]}'`)},e.prototype.setState=function(e){this.logger.info(`Switching from state '${r[this.state]}' to state '${r[e]}'`),this.state===e?this.logger.error(`Attempt to switch to the current state '${r[e]}'`):this.state=e},e.prototype.switchToIncallModeIfEnabled=function(){this.incallModeEnabled&&(this.worker.isIncallMode()||(this.worker.enterIncallMode(),this.worker.stopPingTimer(),this.worker.startPingTimer()),this.worker.restartIncallModeTimer())},e.prototype.cleanUpAndInitiateReconnect=function(e){if(!this.autoReconnect)return this.logger.info(`Automatic reconnect is disabled, stopping this connection`),void this.stop(!0);this.worker.cancelPendingRegistrationRequests(),this.worker.stopConnectionTimer(),this.worker.stopPingTimer(),this.worker.clearSentEventTimers(),this.worker.stopRegistrationTimer(),this.worker.stopSocketIo(),this.setState(r.RetrievingToken),this.worker.dispatchReconnecting(),this.worker.getToken(e.allowCachedToken,e.backoff,e.claimsChallenge,e.fallbackReason)},e}()},396:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ConnectionTracker=t.Properties=t.TrackerStep=t.ClientEventName=t.ResponseData=void 0;var r,i=n(659),a=n(509),o=n(642);t.ResponseData=function(e){this.id=e,this.status=200,this.headers={},this.body=``},function(e){e.Connected=`trouter_js_client_connected`,e.Disconnected=`trouter_js_client_disconnected`,e.Error=`trouter_js_client_error`,e.Progress=`trouter_js_client_progress`,e.Response=`trouter_js_client_response`,e.CheckConnection=`trouter_js_client_check_connection`}(r||(t.ClientEventName=r={}));var s=function(e,t,n,r,i){this.stepName=e,this.operation=t,this.delta=n,this.ts=r,this.error=i};t.TrackerStep=s,t.Properties=function(){};var c=function(){this.numberOfPingReplies=0,this.connectedTimestamp=0,this.isNewUrl=!1,this.transportType=``,this.connectionNumber=0},l=function(){this.enabled=!1,this.numberOfStepsToMaintain=40,this.logHealthCheckError=!1,this.sendProgressTimeoutSecs=55,this.logSendPingError=!1,this.maxBackoffInMs=12e4,this.trouter_js_client_connected=!1,this.trouter_js_client_disconnected=!1,this.trouter_js_client_error=!1,this.trouter_js_client_progress=!1,this.trouter_js_client_response=!1,this.trouter_js_client_request=!1,this.trouter_js_client_registration=!1,this.trouter_js_client_unregistration=!1,this.trouter_js_client_check_connection=!0};t.ConnectionTracker=function(){function e(e,t,n,r,a,s,u){this.clientId=t,this.clientInfo=n,this.getServerState=r,this.endpointId=a,this.clientCorrelationID=s,this.environment=u,this.logger=new o.Logger(`ConnectionTracker`,e),this.clientCorrelationID=s===void 0?``:s,this.steps=[],this.connectionAttempt=0,this.totalStepCount=0,this.beginTimestamp=new i.Timespan,this.eventLogSettings=new l,this.connectedInfo=new c}return e.prototype.enable=function(e){this.eventLogSettings.enabled=!0,this.eventLogger=e},e.prototype.disable=function(){this.eventLogSettings.enabled=!1},e.prototype.sendProgress=function(e){this.steps.length>0&&this.sendTelemetry(r.Progress,e,this.steps)},e.prototype.cancelProgressTimer=function(){this.progressTimeout!==void 0&&(clearTimeout(this.progressTimeout),this.progressTimeout=void 0)},e.prototype.resetProgressSendTimer=function(){var e=this;this.cancelProgressTimer(),this.eventLogSettings.sendProgressTimeoutSecs!==void 0&&this.eventLogSettings.sendProgressTimeoutSecs>0&&(this.progressTimeout=setTimeout((function(){e.sendProgress({reason:`timeout`,timeoutSecs:e.eventLogSettings.sendProgressTimeoutSecs})}),1e3*this.eventLogSettings.sendProgressTimeoutSecs))},e.prototype.setConnectedInfo=function(e,t){this.connectedInfo.numberOfPingReplies=0,this.connectedInfo.connectedTimestamp=Date.now(),this.connectedInfo.isNewUrl=e,this.connectedInfo.transportType=t,++this.connectedInfo.connectionNumber},e.prototype.clearConnectedInfo=function(){this.connectedInfo.numberOfPingReplies=0,this.connectedInfo.connectedTimestamp=0,this.connectedInfo.isNewUrl=!0,this.connectedInfo.transportType=``},e.prototype.copyProperties=function(e,t){for(var n=0,r=Object.keys(t);n<r.length;n++){var i=r[n];t[i]!==void 0&&(e[i.replace(/-/g,`_`)]={value:t[i]})}},e.prototype.increasePingResponseCount=function(){++this.connectedInfo.numberOfPingReplies},e.prototype.sendTelemetry=function(e,t,n){try{if(!0===this.eventLogSettings.enabled&&!0===this.eventLogSettings[e]&&this.eventLogger!==void 0){var r=this.getServerState(),o={name:e,properties:{connectionAttempt:{value:this.connectionAttempt},epid:{value:this.endpointId},clientCorrelationID:{value:this.clientCorrelationID},steps:{value:(0,i.toJson)(n)},clientID:{value:this.clientId},eventVersion:{value:3},environment:{value:this.environment},cv:{value:a.CLIENT_VERSION},ua:{value:this.clientInfo.ua},connectionId:{value:r.connectionId},connectedClientId:{value:r.connectedClientId},domId:{value:r.domId},url:{value:r.url},ttlInSecs:{value:r.getRemainingTtlInSec()},numberOfPingReplies:{value:this.connectedInfo.numberOfPingReplies},connectedTimestamp:{value:this.connectedInfo.connectedTimestamp},isNewUrl:{value:this.connectedInfo.isNewUrl},transportType:{value:this.connectedInfo.transportType},connectionNumber:{value:this.connectedInfo.connectionNumber}}};this.copyProperties(o.properties,t),this.eventLogger.logEvent(o)}}catch(t){this.logger.warn(`error in sending event ${e}: ${(0,i.toJson)(t)}`)}},e.prototype.createStep=function(e,t,n){return new s(e,t,this.beginTimestamp.duration,Date.now(),n)},e.prototype.addStep=function(e,t,n){if(!1!==this.eventLogSettings.enabled&&(this.steps.length===0&&this.beginTimestamp.reset(),this.steps.push(this.createStep(e,t,n)),++this.totalStepCount,this.eventLogSettings.numberOfStepsToMaintain!==void 0&&this.steps.length>this.eventLogSettings.numberOfStepsToMaintain)){var i=this.steps.slice(0);this.steps.length=0,this.sendTelemetry(r.Progress,{reason:`flush`},i)}},e.prototype.trackStart=function(e){this.addStep(e,`start`)},e.prototype.trackEnd=function(e){this.addStep(e,`end`)},e.prototype.trackError=function(e,t,n,i){n===void 0&&(n=!0),e===`health`&&!0!==this.eventLogSettings.logHealthCheckError||e===`ping`&&!1===this.eventLogSettings.logSendPingError||(i===void 0&&(i=`error`),!0===n&&this.addStep(e,i,t),this.sendTelemetry(r.Error,{},[this.createStep(e,i,t)]))},e.prototype.trackProgress=function(e,t){this.addStep(e,t)},e.prototype.trackConnected=function(e,t){this.setConnectedInfo(e,t);var n=this.steps.slice(0),i=this.totalStepCount,a=this.beginTimestamp.duration;this.steps.length=0,this.totalStepCount=0,this.sendTelemetry(r.Connected,{stepCount:n.length,totalStepCount:i,connectionEstablishmentMs_Total:a},n),this.cancelProgressTimer()},e.prototype.getSessionLength=function(){return Date.now()-this.connectedInfo.connectedTimestamp},e.prototype.trackDisconnected=function(e){e.sessionLengthMS=this.getSessionLength(),this.sendTelemetry(r.Disconnected,e,[]),this.resetProgressSendTimer()},e.prototype.trackNewConnection=function(){++this.connectionAttempt},e.prototype.trackResponse=function(e,t,n,a){var o={};a!==void 0&&(o.hasError=!0,o.error=a);try{o.responseTimestamp=n===void 0?Date.now():n.sentTS,e&&(o.requestID=e.id,o.httpMethod=e.method,o.shortUrl=(0,i.anonymizeShortUrl)(e.shortUrl),o.correlationVector=e.correlationVector,o.requestHeaders=(0,i.headersToLog)(e.headers)),n&&(o.latencyMS=t,o.responseCode=n.status,o.responseLength=n.body.length)}catch(e){o.hasError=!0,o.error=`${o.error} error creating response context ${(0,i.toJson)(e)}`}this.sendTelemetry(r.Response,o,[])},e.prototype.sendResponseError=function(e,t,n){this.trackResponse(t,void 0,n,e)},e.prototype.close=function(){this.sendProgress({reason:`closed`}),this.steps.length=0,this.cancelProgressTimer()},e.prototype.mergeSettings=function(e){if(e){this.eventLogSettings.numberOfStepsToMaintain=Math.min(40,Math.max(10,e.numberOfStepsToMaintain===void 0?0:e.numberOfStepsToMaintain));var t=Math.min(3600,Math.max(55,e.sendProgressTimeoutSecs===void 0?0:e.sendProgressTimeoutSecs));this.eventLogSettings.logHealthCheckError=e.logHealthCheckError,this.eventLogSettings.logSendPingError=e.logSendPingError;for(var n=0,i=Object.keys(r).map((function(e){return r[e]}));n<i.length;n++){var a=i[n];e[a]!==void 0&&(this.eventLogSettings[a]=e[a])}this.eventLogSettings.sendProgressTimeoutSecs!==t&&(this.eventLogSettings.sendProgressTimeoutSecs=t,this.resetProgressSendTimer())}},e}()},423:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterManagerState=t.UserActivityEventReason=t.ServerState=void 0;var r,i,a=n(659);t.ServerState=function(){function e(e,t,n,r,i,a){this.connectionId=e,this.connectedClientId=t,this.domId=n,this.url=r,this.c2cUrlBase=i,this.expirationTsSec=a}return e.prototype.getRemainingTtlInSec=function(){return(0,a.calculateTtlInSec)(this.expirationTsSec)},e}(),function(e){e[e.Unknown=0]=`Unknown`,e[e.Modified=1]=`Modified`,e[e.Snapshot=2]=`Snapshot`,e[e.Connected=3]=`Connected`}(r||(t.UserActivityEventReason=r={})),function(e){e[e.Unknown=0]=`Unknown`,e[e.Connected=2]=`Connected`,e[e.Disconnected=3]=`Disconnected`,e[e.Switching=9]=`Switching`,e[e.TerminalError=10]=`TerminalError`}(i||(t.TrouterManagerState=i={}))},509:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.USER_AUTHENTICATE_EVENT_NAME=t.SUPPORTED_TOKEN_TYPES=t.FAILED_MESSAGE_ACK=t.UNHANDLED_MESSAGE_ACK=t.HANDLED_MESSAGE_ACK=t.CLIENT_VERSION=t.constants=void 0,t.constants={TROUTER_INIT:`trouterinit`,TROUTER_READY_EVENT:`trouterReadyEvent`,TROUTER_READY_TIMEOUT:`trouterReadyTimeout`,TROUTER_TOKEN_REQUEST:`trouterTokenRequest`,TROUTER_TOKEN_GET_SUCCEEDED:`trouterTokenGetSucceeded`,TROUTER_TOKEN_GET_FAILED:`trouterTokenGetFailed`,TROUTER_RECONNECTING:`trouterReconnecting`,RENEWAL:`renewal`,NEW_CONNECTION:`newConnection`,ENDPOINT_REGISTRATION_FAILED:`endpointRegistrationFailed`,SUBSCRIPTIONS_DEFAULT_SCOPE:`defaultScope`},t.CLIENT_VERSION=`2026.03.01.8`,t.HANDLED_MESSAGE_ACK=200,t.UNHANDLED_MESSAGE_ACK=404,t.FAILED_MESSAGE_ACK=500,t.SUPPORTED_TOKEN_TYPES=[`skype`,`aad`,`cae`],t.USER_AUTHENTICATE_EVENT_NAME=`user.authenticate`},573:function(e,t,n){var r=this&&this.__assign||function(){return r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},r.apply(this,arguments)},i=this&&this.__awaiter||function(e,t,n,r){return new(n||=Promise)((function(i,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((r=r.apply(e,t||[])).next())}))},a=this&&this.__generator||function(e,t){var n,r,i,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},o=Object.create((typeof Iterator==`function`?Iterator:Object).prototype);return o.next=s(0),o.throw=s(1),o.return=s(2),typeof Symbol==`function`&&(o[Symbol.iterator]=function(){return this}),o;function s(s){return function(c){return function(s){if(n)throw TypeError(`Generator is already executing.`);for(;o&&(o=0,s[0]&&(a=0)),a;)try{if(n=1,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,r=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((i=(i=a.trys).length>0&&i[i.length-1])||s[0]!==6&&s[0]!==2)){a=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){a.label=s[1];break}if(s[0]===6&&a.label<i[1]){a.label=i[1],i=s;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(s);break}i[2]&&a.ops.pop(),a.trys.pop();continue}s=t.call(e,a)}catch(e){s=[6,e],r=0}finally{n=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}};Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterConnection=t.ReconnectReason=void 0;var o,s=n(673),c=n(659),l=n(396),u=n(509),d=n(764),f=n(107),p=n(234),m=n(423),h=n(642),g=n(902),_=n(335),v=n(705),y=n(983),b=function(){this.cv=u.CLIENT_VERSION,this.ua=``,this.hr=``,this.v=``},x=function(){function e(){this[`force new connection`]=!0,this.reconnect=!1,this.query=``,this.ackTimeoutMs=5e3}return e.prototype.rewriteUrlForProxy=function(e){return e},e}(),S=`MS-CV`,C=function(){function e(e,t){this.logger=t,this.cvCounter=0;var n=JSON.parse(e);this.startTS=this.safeJsonNumber(n,`startTS`,0),this.url=this.safeJsonString(n,`url`,``),this.shortUrl=this.safeJsonString(n,`shortUrl`,``),this.body=this.safeJsonString(n,`body`,``),this.headers=this.safeJsonRecord(n,`headers`,{}),this.id=this.safeJsonNumber(n,`id`,-1),this.method=this.safeJsonString(n,`method`,``),this.replied=!1,this.timedout=!1,this.receivedCv=this.headers[S],this.updateCvHeader()}return Object.defineProperty(e.prototype,"correlationVector",{get:function(){return this.receivedCv?`${this.receivedCv}.${this.cvCounter}`:``},enumerable:!1,configurable:!0}),e.prototype.on=function(e,t){e===`data`?this.dataCallback=t:e===`end`&&(typeof this.dataCallback==`function`&&this.dataCallback(this.body),t())},e.prototype.incrementCorrelationVector=function(){++this.cvCounter,this.updateCvHeader()},e.prototype.updateCvHeader=function(){var e=this.correlationVector;e&&(this.headers[S]=e)},e.prototype.safeJsonNumber=function(e,t,n){var r;if(e!=null&&Object.prototype.hasOwnProperty.call(e,t)){var i=e;if(typeof i[t]==`number`)return i[t];if(typeof i[t]==`string`)return parseFloat(i[t]);(r=this.logger)==null||r.warn(`unexpected type of '${t}': ${typeof i[t]}`)}return n},e.prototype.safeJsonString=function(e,t,n){var r;if(e!=null&&Object.prototype.hasOwnProperty.call(e,t)){var i=e;if(typeof i[t]==`string`)return i[t];(r=this.logger)==null||r.warn(`unexpected type of '${t}': ${typeof i[t]}`)}return n},e.prototype.safeJsonRecord=function(e,t,n){var r;if(e!=null&&Object.prototype.hasOwnProperty.call(e,t)){var i=e;if(typeof i[t]==`object`)return i[t];(r=this.logger)==null||r.warn(`unexpected type of '${t}': ${typeof i[t]}`)}return n},e}(),w=function(){function e(e,t,n){this.request=e,this.responseData=t,this.sendResponse=n}return e.prototype.writeHead=function(e,t){this.responseData.status=e,this.responseData.headers=t},e.prototype.write=function(e){this.responseData.body+=e},e.prototype.end=function(e){return e&&(this.responseData.body+=e),this.sendResponse(this.request,this.responseData)},e}(),T=function(e){this.name=e,this.args={},this.timeoutTimerId=0};(function(e){e[e.Configuration=0]=`Configuration`,e[e.ServerInitiated=1]=`ServerInitiated`})(o||(t.ReconnectReason=o={}));var E=function(){function e(e,t,n,r,i,a,o,c){var d,p=this;this.logProvider=e,this.options=t,this.manager=n,this.tokenProvider=r,this.usingLegacyTokenApi=i,this.protocolSelector=o,this.audienceSubscriptionState=c,this.WEBSOCKET_TRANSPORT_NAME=`websocket`,this.XHR_POLLING_TRANSPORT_NAME=`xhr-polling`,this.AUDIENCE_SUBSCRIPTION_RESULT_ERROR=`Error`,this.AUDIENCE_SUBSCRIPTION_RESULT_UNSUBSCRIBED=`Unsubscribed`,this.AUDIENCE_SUBSCRIPTION_RESULT_TIMEOUT=`Timeout`,this.AUDIENCE_SUBSCRIPTION_RESULT_BAD_REQUEST=`BadRequest`,this.AUDIENCE_SUBSCRIPTION_STATE_QUERY_PARAM_REGEX=/&audienceSubscriptionState=[^&]*|^audienceSubscriptionState=[^&]*&?/,this.USER_ACTIVITY_QUERY_PARAM_REGEX=/userActivity=[^&]*/,this.connectionId=``,this.inIncallMode=!1,this.connectionAttempt=0,this.connectedClientId=``,this.isNavigatorOnline=!0,this.onNavigatorOnlineStatusUpdateBound=this.onNavigatorOnlineStatusUpdate.bind(this),this.c2cUrlBase=``,this.connectingErrorsInRow=0,this.connectivityCheckFailuresInARow=0,this.unauthorizedErrorCount=0,this.pendingSentEventTimers={},this.extraTransports={},this.clientDescriptionOverride={},this.lastDisconnectReason=``,this.UNKNOWN_TRANSPORT=`unknown_transport`,this.connectingErrorsThreshold=3,this.pendingAudienceSubscription=void 0,this.areSubscriptionsEqual=function(e,t){if(e.length!==t.length)return!1;e=e.sort((function(e,t){return e.id.localeCompare(t.id)})),t=t.sort((function(e,t){return e.id.localeCompare(t.id)}));for(var n=0;n<e.length;n++)if(e[n].id!==t[n].id)return!1;return!0},this.logger=new h.Logger(`Connection`,e),this.timeoutOptions=this.options.timeoutOptions,this.tokenBackoff=new f.ExponentialBackoff(this.logger,this.timeoutOptions.maxBackoffMs),this.clientID=Date.now(),typeof window<`u`&&window.location&&(this.domId=window.location.hostname);var m=new b;m.cv=u.CLIENT_VERSION,m.ua=``,(d=this.options)!=null&&d.clientInfo&&(m.ua=this.safeString(this.options.clientInfo.ua),m.v=this.safeString(this.options.clientInfo.v)),this.clientInfo=m,this.connectionTracker=new l.ConnectionTracker(e,this.clientID,this.clientInfo,(function(){return p.getServerState()}),this.options.endpointId,this.options.clientCorrelationID,this.options.environment),this.applyConnectionTrackerOptions(t);var g=this.options.incallModeTimeoutMs>0;if(this.fsm=new _.TrouterFsm(e,this,g,this.protocolSelector),t.registration&&!t.registration.useRegistrarUrlFromAllocate){var v={registrarUrl:t.registration.registrarUrl,proxyUrlRewrite:t.rewriteUrlForProxy,registrationId:t.registration.registrationId,requestTimeoutMs:t.timeoutOptions.fetchTimeoutMs,initialRetryDelayMs:1e3,maxRetryDelayMs:t.timeoutOptions.maxBackoffMs,usingLegacyTokenApi:this.usingLegacyTokenApi,maxRetriesForGetToken:t.retryLimitOnTokenFetch,extraRegistrationHeaders:t.extraConnectionHeaders};this.registrarClient=(0,s.createRegistrarClient)(e,this.tokenProvider,v)}this.userActivityState=a}return e.prototype.start=function(e,t,n){this.logger.info(`Starting`),this.reconnectParams=e,this.extraTransports=t??{},this.clientDescriptionOverride=n??{},typeof window<`u`&&window.navigator&&window.addEventListener?(this.isNavigatorOnline=window.navigator.onLine,window.addEventListener(`online`,this.onNavigatorOnlineStatusUpdateBound),window.addEventListener(`offline`,this.onNavigatorOnlineStatusUpdateBound),this.logger.debug(`Registered for browser online notifications - current state: ${this.isNavigatorOnline}`)):this.isNavigatorOnline=!0,this.fsm.start()},e.prototype.stop=function(e){this.logger.info(`Stopping`),typeof window<`u`&&window.navigator&&(window.removeEventListener(`online`,this.onNavigatorOnlineStatusUpdateBound),window.removeEventListener(`offline`,this.onNavigatorOnlineStatusUpdateBound)),this.fsm.stop(e),this.connectionTracker.close()},e.prototype.configure=function(e){var t=this.options.trouterUrl!==e.trouterUrl;this.options=e,this.applyConnectionTrackerOptions(e),t&&(this.logger.info(`Configuration changed. Reconnection required.`),this.fsm.onReconnectRequired(!1,o.Configuration))},e.prototype.checkConnection=function(e){this.logger.info(`checkConnection called with ${e}`),this.fsm.checkConnection(e),e&&this.connectionTracker.sendTelemetry(l.ClientEventName.CheckConnection,{disconnectDetected:e},[])},e.prototype.disableRegistrationsAndAutoReconnect=function(){this.stopRegistrationTimer(),this.cancelPendingRegistrationRequests(),this.fsm.disableAutoReconnect()},e.prototype.getServerState=function(){return new m.ServerState(this.connectionId,this.connectedClientId,this.domId?this.domId:``,this.allocateResult?this.allocateResult.surl:``,this.c2cUrlBase,this.connectionExpireTimestampInSecs)},e.prototype.getState=function(){return this.fsm.getState()},e.prototype.getToken=function(e,t,n,r,i){var a=this;i===void 0&&(i=0),this.logger.info(`Getting token ${t?`with backoff`:`without backoff`}`);var o=function(){a.connectionTracker.trackStart(`token`);var t={needFresh:!e,wwwAuthenticateHeader:n,supportedTokenTypes:u.SUPPORTED_TOKEN_TYPES,purpose:`trouter`};a.logger.info(`Requesting token: needFresh=${t.needFresh} types=[${u.SUPPORTED_TOKEN_TYPES}], wwwAuthenticateHeader is ${t.wwwAuthenticateHeader?`non empty`:`empty`}`),a.tokenProvider(t).then((function(e){a.logger.debug(`${e.tokenType} token is received`),a.connectionTracker.trackEnd(`token`),a.fsm.onTokenReceived(e,r,a.reconnectParams)})).catch((function(t){var o=(0,c.toJson)(t.stack);if(a.logger.error(`Getting token failed, will retry after timeout. Error: ${o}`),a.connectionTracker.trackError(`token`,o),!a.canRetryTokenFetchRequest(i+a.unauthorizedErrorCount))return a.connectionTracker.trackError(`token`,`getToken retry limit hit, reached terminal error state`),a.resetTokenBackoff(),void a.fsm.onTerminalError();a.getToken(e,!0,n,r,i+1)}))};t?this.tokenBackoff.backoff(`getting token`,o):(this.resetTokenBackoff(),o())},e.prototype.startConnectionTimer=function(){var e=this;this.stopConnectionTimer(),this.logger.debug(`Starting connection timeout for ${this.timeoutOptions.connectionTimeoutMs} ms`),this.connectionTimeoutId=setTimeout((function(){e.logger.info(`Connection timeout is fired`),e.fsm.onConnectingTimeout()}),this.timeoutOptions.connectionTimeoutMs)},e.prototype.stopConnectionTimer=function(){this.connectionTimeoutId&&=(this.logger.debug(`Stopping connection timeout`),clearTimeout(this.connectionTimeoutId),void 0)},e.prototype.startPingTimer=function(){var e=this;this.transportTypeName===`websocket`?(this.logger.debug(`Starting ping timeout for ${this.timeoutOptions.pingTimeoutMs} ms`),this.pingTimerId=setInterval((function(){e.logger.info(`Ping interval fired`),e.fsm.onPingInterval()}),this.timeoutOptions.pingTimeoutMs)):this.logger.debug(`Not starting ping for transport ${this.transportTypeName}`)},e.prototype.stopPingTimer=function(){this.pingTimerId&&=(this.logger.debug(`Stopping ping timeout`),this.clearPingResponseTimer(),clearInterval(this.pingTimerId),void 0)},e.prototype.shouldSkipRegistration=function(){return this.options.registration===void 0},e.prototype.hasCustomRegistrationTtl=function(){return this.options.registration?.registrarTtlSec!==void 0&&this.options.registration?.registrarTtlSec!==0},e.prototype.startRegistrationTimer=function(){var e=this;this.stopRegistrationTimer();var t=this.getRegistrationTtl(),n=t[0],r=t[1];if(n<=30||!r)return this.logger.debug(`Starting registration expiration timer (TTL ${n} sec)`),void(this.registrationTimerId=setTimeout((function(){e.registrationTimerId=void 0,e.logger.warn(`Registration expired but the connection is still alive. Should never happen`),e.dispatchUnregistered()}),1e3*n));var i=n-30;this.logger.debug(`Starting registration extension timer for ${i} sec`),this.registrationTimerId=setTimeout((function(){e.logger.info(`Registration extension timer fired`),e.registrationTimerId=setTimeout((function(){e.registrationTimerId=void 0,e.logger.debug(`Registration extension did not happen in time`),e.dispatchUnregistered()}),3e4),e.fsm.onRegistrationNearExpiry()}),1e3*i)},e.prototype.startRegistrationRetryTimer=function(){var e=this;this.stopRegistrationTimer(),this.registrationTimerId=setTimeout((function(){e.registrationTimerId=void 0,e.fsm.onRetryRegistration()}),123e3)},e.prototype.stopRegistrationTimer=function(){this.registrationTimerId&&=(this.logger.debug(`Stopping registration timeout`),clearTimeout(this.registrationTimerId),void 0)},e.prototype.resendRegistration=function(){if(!this.registrarClient)throw Error(`Trouter Client not configured to handle registrations`);return this.fsm.onResendRegistration(),Promise.resolve()},e.prototype.registerExtraTransports=function(e,t){this.logger.info(`Registering ${Object.keys(e).length} extra transports`),this.extraTransports=e,this.clientDescriptionOverride=t??{},this.fsm.onExtraTransportsUpdated()},e.prototype.buildSocketIoUrlParams=function(e,t){if(!this.allocateResult)throw Error(`Allocate result is undefined in buildSocketIoUrlParams()`);for(var n={},r=this.allocateResult.connectparams,i=0,a=Object.keys(r);i<a.length;i++){var o=a[i];if(r[o]!==void 0){var s=r[o];typeof s==`string`||typeof s==`number`?n[o]=s:this.logger.error(`signatureData[${o}] has unsupported type ${typeof s}`)}}return n.v=`v4`,n.tc=encodeURI((0,c.toJson)(this.clientInfo)),n.timeout=this.timeoutOptions.pingTimeoutMs/1e3,n.auth=`true`,this.options.endpointId&&(n.epid=this.options.endpointId),e&&(n.userActivity=encodeURIComponent((0,c.toJson)(e))),t&&(n.audienceSubscriptionState=encodeURIComponent((0,c.toJson)(t))),this.appendConnectedClientIds(this.buildQuery(n),!0)},e.prototype.startSocketIo=function(e){if(this.logger.debug(`Starting socket io`),this.connectionTracker.trackStart(`connectSocket`),!this.allocateResult)throw Error(`Allocate result is undefined in startSocketIo()`);var t=this.options.ioOptions?r({},this.options.ioOptions):new x,n=this.userActivityState.state===p.UserActivityState.Unknown?void 0:this.userActivityState.increaseCvAndGetEventObject(),i=this.audienceSubscriptionState?.increaseCvAndGetEventObject();if(t[`force new connection`]=!0,t.reconnect=!1,t.rewriteUrlForProxy=this.options.rewriteUrlForProxy,t.requestHeaders=r(r({},this.options.extraConnectionHeaders),ee(e,this.usingLegacyTokenApi)),t.query=this.buildSocketIoUrlParams(n,i),this.logger.info(`connecting to ${this.allocateResult.socketio}`),this.stopSocketIo(),this.socket=(this.options.io??y).connect(this.allocateResult.socketio,t),this.socket===void 0)throw Error(`Can't create Socket.io object`);this.attachSocketIoHandlers(this.socket,e,n,i)},e.prototype.stopSocketIo=function(){if(this.socket){this.logger.debug(`clearing socket.io`);try{for(var e=0,t=[`connecting`,`connect`,`connect_failed`,`close_during_connecting`,`disconnect`,`reconnect`,`reconnect_failed`,`reconnecting`,`error`,`message`,`trouter.connected`,`trouter.reconnect`,`trouter.message_loss`,`audience.subscriptionresult`];e<t.length;e++){var n=t[e];this.socket.removeAllListeners(n)}this.socket.disconnect(),this.logger.debug(`cleared socket`),this.socket=void 0}catch(e){this.logger.error(`exception in disconnecting previous socket. Error: ${D(e)}`)}}},e.prototype.dispatchConnected=function(){this.logger.info(`dispatching connected`),this.manager.onConnected(this)},e.prototype.dispatchRegistered=function(){this.logger.info(`dispatching registered`),this.manager.onRegistered(this)},e.prototype.dispatchUnregistered=function(){this.logger.info(`dispatching unregistered`),this.manager.onUnregistered(this)},e.prototype.dispatchDownstreamRequest=function(e){var t=this;this.logger.debug(`dispatching downstream request`);try{var n=new w(e,new l.ResponseData(e.id),(function(e,n){return t.logger.debug(`sending response to downstream`),t.sendResponse(e,n)}));this.manager.onDownstreamRequest(this,e,n)}catch(e){this.logger.error(`exception in socket.on message. Error : ${D(e)}`)}},e.prototype.dispatchReconnecting=function(){this.logger.info(`dispatching reconnecting`),this.manager.onReconnecting(this)},e.prototype.dispatchReconnectIsRequired=function(e,t){this.logger.info(`dispatching reconnect is required by server`),this.manager.onReconnectIsRequired(this,e,t)},e.prototype.dispatchDisconnected=function(){this.logger.info(`dispatching disconnected`),this.manager.onDisconnected(this)},e.prototype.dispatchTerminalError=function(){this.logger.info(`dispatching terminal error`),this.manager.onTerminalError(this)},e.prototype.dispatchTrouterMessageLost=function(e){this.logger.info(`dispatching trouter message lost`),this.manager.onTrouterMessageLost(e)},e.prototype.countDisconnectBeforeConnectionEstablishment=function(){this.logger.warn(`counting disconnect before connection was fully established as a connection failure`),this.connectingErrorsInRow++,this.connectingErrorsInRow>=this.connectingErrorsThreshold&&this.resetReconnectParamsOnErrorThreshold()},e.prototype.sendProcessedDroppedIndicators=function(e){var t=this;try{this.logger.debug(`emitting processed flow tags to the server`);var n=new T(`trouter.processed_message_loss`);n.args={droppedIndicators:e},this.sendDownstreamEvent(n,(function(){t.logger.info(`emitted processed flow tags to the server`)}))}catch(e){var r=D(e);this.logger.error(`unable to send processed message loss event. Error: ${r}`),this.connectionTracker.trackError(`trouter.processed_message_loss`,r,!1)}},e.prototype.sendAllocateRequest=function(e){var t=this;this.connectionAttempt++,this.connectionTracker.trackNewConnection();var n,i=this.options.trouterUrl,a=this.reconnectParams,o=typeof a?.se==`string`?parseInt(a.se,10):typeof a?.se==`number`?a.se:void 0;o&&o<=Date.now()+36e5&&(this.logger.warn(`Dropping expired cached connection parameters: ${new Date(o)}`),this.reconnectParams=a=void 0),a&&a.serviceUrl!==i&&(this.logger.warn(`Dropping cached connection parameters for a different environment (${a.serviceUrl}, now ${i})`),this.reconnectParams=a=void 0),a!=null&&a.reconnectUrl&&(i=a.reconnectUrl),n=a?r(r({},a),{serviceUrl:void 0,reconnectUrl:void 0}):null,i=(0,g.adaptUrl)(i,`v4a`),i=this.appendCorrelationIds(i,!1),i=this.appendEndpointId(i,!1);var s=i=this.appendClientInfo(i,!1);n&&(i+=`&${this.buildQuery(n)}`,n.v||(i+=`&v=v4`)),i=this.options.rewriteUrlForProxy(i);var l=new Request(i,{method:`POST`,mode:`cors`,headers:new Headers(r(r({"Content-Type":`text/plain`},this.options.extraConnectionHeaders),ee(e,this.usingLegacyTokenApi)))});this.logger.info(`sendAllocateRequest: POST ${this.options.rewriteUrlForProxy(s)} (connectparams redacted)}`),this.connectionTracker.trackStart(`allocation`);var u,d=Date.now(),f=-1,p=!1;(0,c.fetchWithTimeout)(l,this.timeoutOptions.fetchTimeoutMs).then((function(e){if(f=e.status,!e.ok)throw u=e.headers.get(`www-authenticate`)??void 0,p=e.headers.get(`x-trouter-skypetoken-deprecated`)===`1`,t.logger.warn(`Allocation request got response status ${e.status}, www-authenticate header was ${u?`not empty`:`empty`}`),Error(e.statusText);var n=e.headers.get(`content-type`);if(!n||n!==`application/json`&&!n.startsWith(`application/json;`))throw Error(`Content-type '${n}' is unexpected`);return t.connectionTracker.trackEnd(`allocation`),e.json()})).then((function(n){t.unauthorizedErrorCount=0,t.onAllocationResponse(n,e)})).catch((function(e){t.connectingErrorsInRow++;var n=`${e}${f>=0?`, status code ${f}`:``}`;if(t.logger.error(`${t.connectingErrorsInRow} failed connecting attempt(s) in a row. ${n}`),t.connectionTracker.trackError(`allocation`,n),p){var r=`Skypetoken deprecated response, not retrying any further`;t.logger.error(r),t.connectionTracker.trackError(`allocation`,r),t.fsm.onTerminalError();return}if(f===401&&t.unauthorizedErrorCount++,!t.canRetryTokenFetchRequest(t.unauthorizedErrorCount))return r=`getToken retry limit hit, reached terminal error state`,t.connectionTracker.trackError(`allocation`,r),void t.fsm.onTerminalError();if(f!==-1||t.isNavigatorOnline){if(t.reconnectParams&&t.connectingErrorsInRow>=t.connectingErrorsThreshold){if(f>=400&&f<=599)t.resetReconnectParamsOnErrorThreshold();else if(t.reconnectParams.reconnectUrl&&t.connectingErrorsInRow%3==0){t.logger.warn(`${t.connectingErrorsInRow} connection attempts, testing nominal service URL`);var i=Math.min(t.timeoutOptions.connectionTimeoutMs-(Date.now()-d)-500,t.timeoutOptions.fetchTimeoutMs);t.testNominalUrlConnectivity(i).then((function(e){t.connectionTracker.trackProgress(`nomcheck`,e?`ok`:`failed`),e?(t.logger.warn(`Nominal service URL is reachable, erasing cached reconnect URL`),t.reconnectParams&&delete t.reconnectParams.reconnectUrl):t.logger.warn(`Nominal service URL is not reachable either, keeping cached reconnect URL`),t.fsm.onAllocationFailed(!1,void 0)}),(function(){t.fsm.onAllocationFailed(!1,void 0)}));return}}}else t.logger.info(`Expected failure, the browser says it is not online at the moment`);t.fsm.onAllocationFailed(f===401,u)}))},e.prototype.testNominalUrlConnectivity=function(e){var t,n=this;if(e<1e3)return this.logger.warn(`There is no time left to reasonably perform the nominal service URL connectivity check (${e} ms), falling back to assuming that the connectivity is fine`),Promise.resolve(!0);try{var r=new URL(this.options.trouterUrl);r.pathname=r.pathname.replace(/\/v4\/.*/,`/`),r.search=`?`+this.buildQuery({check:Date.now(),cor_id:encodeURIComponent(this.options.clientCorrelationID),epid:encodeURIComponent(this.options.endpointId?this.options.endpointId:``),tc:encodeURIComponent((0,c.toJson)(this.clientInfo))}),r.protocol===`wss:`&&(r.protocol=`https:`),t=new Request(this.options.rewriteUrlForProxy(r.toString()),{method:`GET`,headers:{Accept:`text/plain`}})}catch(e){return this.logger.warn(`Nominal service URL connectivity test request could not be created (${e}), falling back to assuming that the connectivity is fine`),Promise.resolve(!0)}return(0,c.fetchWithTimeout)(t,e).then((function(e){if(e.status!==200)throw Error(`Not 200 OK: ${e.status} ${e.statusText}`);return e.text()})).then((function(e){if(e!==`Trouter`)throw Error(`Not "Trouter": ${e.substring(0,16)}${e.length>16?`...`:``}`);return!0})).catch((function(e){return n.logger.error(`Nominal service URL connectivity test failed: ${e}`),!1}))},e.prototype.sendPingRequest=function(){var e=this;if(this.socket&&this.pingResponseTimerId===void 0)try{this.logger.debug(`emitting ping event`);var t=!1;this.socket.emit(`ping`,(function(){!0!==t&&e.onPingResponse()})),this.pingResponseTimerId=setTimeout((function(){e.logger.error(`Ping response timeout is fired`),t=!0,e.clearPingResponseTimer(),e.fsm.onPingResponseTimeout()}),this.timeoutOptions.pongTimeoutMs)}catch(e){var n=D(e);this.logger.error(`unable to send ping. Error: ${n}`),this.connectionTracker.trackError(`ping`,n,!1)}},e.prototype.connectV4c=function(e,t){return i(this,void 0,void 0,(function(){var n,i,o,s,c;return a(this,(function(a){switch(a.label){case 0:return[4,this.performV4cInitialConnectivityCheck()];case 1:if(!1===a.sent())return[2];(n=this.options.ioOptions?r({},this.options.ioOptions):new x)[`force new connection`]=!0,n.reconnect=!1,(c=this.reconnectParams)!=null&&c.serviceUrl&&(0,g.adaptUrl)(this.reconnectParams.serviceUrl,`v4c`)!==(0,g.adaptUrl)(this.options.trouterUrl,`v4c`)&&(this.logger.warn(`Dropping cached connection parameters for a different environment (${this.reconnectParams.serviceUrl}, now ${this.options.trouterUrl})`),this.reconnectParams=void 0),i=(0,g.redirectUrlIfPresent)(t)??(t?.kind===`redirect-no-host`?void 0:this.reconnectParams?.reconnectUrl)??this.options.trouterUrl,o=(0,g.adaptUrl)(i,`v4c`),n[`skipped handshake data`]={timeout:70,websocketUrl:o},n.query=this.buildV4cUrlParams(),n.rewriteUrlForProxy=this.options.rewriteUrlForProxy;try{if(this.stopSocketIo(),this.transportTypeName=`websocket`,this.socket=(this.options.io??y).connect(this.options.trouterUrl,n),this.socket===void 0)throw Error(`failed to create Socket.io object`);s=this.audienceSubscriptionState?.increaseCvAndGetEventObject(),this.attachSocketIoHandlers(this.socket,e,void 0,s)}catch(e){this.logger.error(`${e}`),this.connectionTracker.trackError(`v4c`,`${e}`),this.fsm.onV4cException()}return[2]}}))}))},e.prototype.performV4cInitialConnectivityCheck=function(){return i(this,void 0,void 0,(function(){return a(this,(function(e){switch(e.label){case 0:return this.options.initialConnectivityCheck?(this.logger.info(`checking connectivity to configured URL (go URL) before a connection attempt`),[4,this.testNominalUrlConnectivity(3e3)]):[2,!0];case 1:return e.sent()?(this.connectivityCheckFailuresInARow=0,[2,!0]):this.connectivityCheckFailuresInARow>=3?(this.connectivityCheckFailuresInARow=0,this.logger.error(`three connectivity checks failed in a row, will attempt with the fallback protocol`),this.fsm.onV4cException(),[2,!1]):(this.logger.warn(`connectivity check failed, will retry after backoff`),this.connectivityCheckFailuresInARow++,this.fsm.onV4cConnectivityCheckFailed(),[2,!1])}}))}))},e.prototype.sendV4cAuthenticationEvent=function(e){var t,n={headers:r(r({},this.options.extraConnectionHeaders),ee(e,this.usingLegacyTokenApi)),connectparams:(0,g.reconnectParamsWithoutUrls)(this.reconnectParams)};(t=this.socket)==null||t.emit(u.USER_AUTHENTICATE_EVENT_NAME,n)},e.prototype.setUserActivityState=function(e){var t=e.state!==this.userActivityState.state;this.userActivityState=e,t?(this.logger.info(`Changing user activity state to '${e.toEventJSON()}'`),this.fsm.onSetNewUserActivityState()):(this.logger.debug(`Not changing the same user activity state '${e.toEventJSON()}'`),this.manager.onUserActivityStateAccepted(e.correlationVector.value()))},e.prototype.sendUserActivityState=function(e,t){if(this.userActivityState.state!==p.UserActivityState.Unknown){if(this.options.updateUserActivityDuringConnectionAttempt&&this.socket){var n=this.userActivityState.toEventObject(),r=this.socket.socket.options.query;if(r){var i=`userActivity=${encodeURIComponent((0,c.toJson)(n))}`;r.search(this.USER_ACTIVITY_QUERY_PARAM_REGEX)==-1?this.socket.socket.options.query=r.concat(`&`,i):this.socket.socket.options.query=r.replace(this.USER_ACTIVITY_QUERY_PARAM_REGEX,i)}}this.transportTypeName===`websocket`&&t?e===m.UserActivityEventReason.Connected?this.sendUserActivityStateMultiple(2):this.sendUserActivityStateMultiple(1):this.transportTypeName===`xhr-polling`&&e===m.UserActivityEventReason.Modified&&this.fsm.forceReconnect(`user activity/force reconnect`)}},e.prototype.setAudienceSubscriptionsAsync=function(e,t){var n=this.audienceSubscriptionState;if(this.audienceSubscriptionState=e,this.transportTypeName===this.WEBSOCKET_TRANSPORT_NAME)return this.setAudienceSubscriptionsInternalAsync(e.increaseCvAndGetEventObject(),t);if(this.transportTypeName===this.XHR_POLLING_TRANSPORT_NAME){var r=this.setAudienceSubscriptionsLongpollInternalAsync(e.increaseCvAndGetEventObject(),t,n);return this.fsm.forceReconnect(`set audience subscription force reconnect`),r}throw Error(`set audience subscription executed on an unknown transport`)},e.prototype.setAudienceSubscriptionsUnsafeAsync=function(e){if(e)return this.transportTypeName===this.WEBSOCKET_TRANSPORT_NAME?this.setAudienceSubscriptionsInternalAsync(e,15e3):void 0},e.prototype.onAudienceSubscriptionResult=function(e){if(this.logger.info(`onAudienceSubscriptionResult`),this.pendingAudienceSubscription)return clearTimeout(this.pendingAudienceSubscription.timeoutId),this.pendingAudienceSubscription.audienceSetResolve(e),void(this.pendingAudienceSubscription=void 0);if(this.audienceSubscriptionState&&this.transportTypeName===this.XHR_POLLING_TRANSPORT_NAME){var t=new Set(this.audienceSubscriptionState.toListOfSubscriptions().map((function(e){return e.id}))??[]),n=this.audienceSubscriptionState.correlationVector.value();this.cleanPollingAudienceSubscriptionStateQueryParam(t,e,n),this.manager.onAudiencesSetResolved(e,n)}},e.prototype.setAudienceSubscriptionsInternalAsync=function(e,t){return i(this,void 0,void 0,(function(){var n,r,i=this;return a(this,(function(a){switch(a.label){case 0:return this.logger.info(`[WebSocket] Audience subscription set requested.`),(n=new T(`audience.subscribe`)).args=e,[4,new Promise((function(r){var a=!1,o=setTimeout((function(){return a=!0,r(i.buildAudienceSubscriptionsTimeoutResponse(e))}),t);i.sendDownstreamEvent(n,(function(e,t){a||(clearTimeout(o),i.logger.debug(`[Websocket] Audience subscription response: ${t}`),i.pendingAudienceSubscription&&i.onAudienceSubscriptionResult(t),r(t))}))}))];case 1:return r=a.sent(),this.manager.onAudiencesSetResolved(r,e.cv),[2,r]}}))}))},e.prototype.setAudienceSubscriptionsLongpollInternalAsync=function(e,t,n){return i(this,void 0,void 0,(function(){var r,i,o,s,c=this;return a(this,(function(a){switch(a.label){case 0:return this.logger.info(`[XHR Polling] Audience subscription set requested.`),this.pendingAudienceSubscription&&(this.logger.error(`Racing audience subscriptions occured. This situation resolves into undefined scenario and/or nasal demons.`),clearTimeout(this.pendingAudienceSubscription.timeoutId)),[4,new Promise((function(n){c.pendingAudienceSubscription={audienceSetResolve:n,timeoutId:setTimeout((function(){return c.pendingAudienceSubscription=void 0,n(c.buildAudienceSubscriptionsTimeoutResponse(e))}),t)}}))];case 1:return r=a.sent(),this.manager.getState()===p.TrouterState.Unknown||this.transportTypeName===this.WEBSOCKET_TRANSPORT_NAME||(this.logger.debug(`[XHR Polling] Audience subscription response: ${r}`),i=new Set(e.audiences.map((function(e){return e.id}))??[]),this.cleanPollingAudienceSubscriptionStateQueryParam(i,r,e.cv),o=this.handleAudienceUnsubscribeLongpoll(e,n),(s=r.responses).push.apply(s,o),this.manager.onAudiencesSetResolved(r,e.cv)),[2,r]}}))}))},e.prototype.cleanPollingAudienceSubscriptionStateQueryParam=function(e,t,n){var r=this,i=t.responses.filter((function(t){return t.result.audienceSubscriptionState===r.AUDIENCE_SUBSCRIPTION_RESULT_BAD_REQUEST&&e.has(t.audienceId)})),a=t.responses.filter((function(t){return t.result.audienceSubscriptionState===r.AUDIENCE_SUBSCRIPTION_RESULT_ERROR&&e.has(t.audienceId)})),o=t.responses.filter((function(t){return t.result.audienceSubscriptionState===r.AUDIENCE_SUBSCRIPTION_RESULT_TIMEOUT&&e.has(t.audienceId)})),s=i.map((function(e){return e.audienceId})),c=a.map((function(e){return e.audienceId})),l=o.map((function(e){return e.audienceId})),u=Array.from(e).filter((function(e){return s.indexOf(e)===-1&&c.indexOf(e)===-1&&l.indexOf(e)===-1})).map((function(e){return{id:e}}));u.length===0?this.clearAudienceSubscriptionStateQueryParam():this.updateAudienceSubscriptionStateQueryParam(u,n)},e.prototype.clearAudienceSubscriptionStateQueryParam=function(){var e;(e=this.socket?.socket?.options)!=null&&e.query&&(this.socket.socket.options.query=this.socket.socket.options.query.replace(this.AUDIENCE_SUBSCRIPTION_STATE_QUERY_PARAM_REGEX,``))},e.prototype.updateAudienceSubscriptionStateQueryParam=function(e,t){if(this.socket?.socket?.options?.query){var n=encodeURIComponent(JSON.stringify({audiences:e,cv:t})),r=this.socket.socket.options.query,i=(0,v.updateAudienceSubscriptionQuery)(r,n);this.socket.socket.options.query=i}},e.prototype.handleAudienceUnsubscribeLongpoll=function(e,t){var n=[],r=t?.toListOfSubscriptions()??[],i=!this.areSubscriptionsEqual(r,e.audiences);if(r.length>0&&i&&t){var a=r.filter((function(t){return e.audiences.find((function(e){return e.id===t.id}))===void 0})),o=this.mapToSyntheticAudienceSubscriptionResponses(a,this.AUDIENCE_SUBSCRIPTION_RESULT_UNSUBSCRIBED,200);n.push.apply(n,o)}return n},e.prototype.buildAudienceSubscriptionsTimeoutResponse=function(e){return this.logger.error(`Audience subscription attempt has timed out.`),{responses:this.mapToSyntheticAudienceSubscriptionResponses(e.audiences,this.AUDIENCE_SUBSCRIPTION_RESULT_TIMEOUT)}},e.prototype.mapToSyntheticAudienceSubscriptionResponses=function(e,t,n){return e===void 0?[]:e.map((function(e){return{audienceId:e.id,result:{audienceSubscriptionState:t,responseStatus:n}}}))},e.prototype.expediteBackoff=function(){this.tokenBackoff.expediteIfPending()},e.prototype.sendRegisterRequest=function(){var e=this;if(!this.options.registration)throw Error(`Internal error - options.registration is undefined`);if(!this.allocateResult)throw Error(`Allocate result is undefined in sendRegisterRequest()`);if(this.options.registration.useRegistrarUrlFromAllocate&&!this.registrarClient){if(!this.allocateResult.registrarUrl)throw Error(`Internal error - useRegistrarUrlFromAllocate is true, but allocateResult did not include registrarUrl`);var t={registrarUrl:this.allocateResult.registrarUrl,proxyUrlRewrite:this.options.rewriteUrlForProxy,registrationId:this.options.registration.registrationId,requestTimeoutMs:this.options.timeoutOptions.fetchTimeoutMs,initialRetryDelayMs:1e3,maxRetryDelayMs:this.options.timeoutOptions.maxBackoffMs,usingLegacyTokenApi:this.usingLegacyTokenApi,maxRetriesForGetToken:this.options.retryLimitOnTokenFetch,extraRegistrationHeaders:this.options.extraConnectionHeaders};this.registrarClient=(0,s.createRegistrarClient)(this.logProvider,this.tokenProvider,t)}if(!this.registrarClient)throw Error(`Internal error - registrarClient is undefined`);this.logger.info(`sending register request with ${1+Object.keys(this.extraTransports).length} transports and ${Object.keys(this.clientDescriptionOverride).length} overridden client description properties`),this.connectionTracker.trackStart(`registration`);var n=this.getRegistrationTtl()[0];this.registrarClient.register(r({appId:this.options.registration.pnhAppId,aesKey:``,languageId:`en-US`,platform:this.options.registration.platform,templateKey:this.options.registration.pnhTemplateKey,platformUIVersion:this.options.registration.platformUIVersion,productContext:this.options.registration.productContext},this.clientDescriptionOverride),r({TROUTER:[{context:this.options.registration.context,path:this.allocateResult.surl,ttl:n}]},this.extraTransports)).then((function(){e.logger.info(`Register request successful`),e.connectionTracker.trackEnd(`registration`),e.fsm.onRegistrationSucceeded()})).catch((function(t){e.logger.error(`Register request failed. Error: ${t}`),e.connectionTracker.trackError(`registration`,O(t)),e.fsm.onRegistrationFailed()}))},e.prototype.sendUnregisterRequest=function(){var e=this;if(Object.keys(this.extraTransports).length>0&&this.logger.warn(`explicit unregister called while there are extra transports`),this.logger.info(`sending unregister request`),!this.options.registration||!this.registrarClient)throw Error(`Internal error - options.registration is undefined`);this.connectionTracker.trackStart(`unregistration`),this.registrarClient.unregister().then((function(){e.logger.info(`Unregister request successful`),e.connectionTracker.trackEnd(`unregistration`),e.fsm.onUnregistrationDone()})).catch((function(t){e.logger.error(`Unregister request failed. Error: ${t}`),e.connectionTracker.trackError(`unregistration`,O(t)),e.fsm.onUnregistrationDone()}))},e.prototype.resetTokenBackoff=function(){this.tokenBackoff.reset()},e.prototype.cancelPendingRegistrationRequests=function(){this.registrarClient&&this.registrarClient.cancelPendingRequests()},e.prototype.clearSentEventTimers=function(){var e=Object.keys(this.pendingSentEventTimers);if(e.length>0){this.logger.debug(`Clearing all pending downstream events related timers`);for(var t=0,n=e;t<n.length;t++){var r=n[t];this.clearSentEventTimer(Number(r))}}},e.prototype.restartIncallModeTimer=function(){var e=this;this.clearIncallModeTimerId(),this.logger.debug(`Restarting incall mode timer`),this.incallModeTimerId=setTimeout((function(){e.logger.info(`Call mode timer fired`),e.fsm.onIncallModeTimer()}),this.options.incallModeTimeoutMs)},e.prototype.enterIncallMode=function(){this.logger.info(`Entering incall mode`),this.timeoutOptions=this.options.incallTimeoutOptions,this.tokenBackoff.setMaxBackoffMs(this.timeoutOptions.maxBackoffMs),this.inIncallMode=!0},e.prototype.exitIncallMode=function(){this.logger.info(`Exiting incall mode`),this.clearIncallModeTimerId(),this.timeoutOptions=this.options.timeoutOptions,this.tokenBackoff.setMaxBackoffMs(this.timeoutOptions.maxBackoffMs),this.inIncallMode=!1},e.prototype.isIncallMode=function(){return this.inIncallMode},e.prototype.sendDisconnectTelemetryEvent=function(e){var t={reason:e,serverClosed:!this.fsm.isActive()};this.connectionTracker.trackDisconnected(t),this.connectionTracker.clearConnectedInfo()},e.prototype.forceReconnectDueToNoRegistration=function(){this.fsm.forceReconnect(`force reconnect due to no registration`)},e.prototype.resetReconnectParamsOnErrorThreshold=function(){this.logger.warn(`${this.connectingErrorsInRow} connection attempts, server-side failure: erasing cached connection parameters`),this.reconnectParams=void 0},e.prototype.onSocketConnecting=function(e){this.logger.info(`onSocketConnecting(${e})`),this.transportTypeName=e,this.connectionTracker.trackProgress(`connecting`,this.transportTypeName),this.fsm.onConnecting()},e.prototype.onSocketConnect=function(e){this.logger.info(`onSocketConnect`),this.fsm.onSocketConnect(e)},e.prototype.onSocketConnectFailed=function(e){this.logger.error(`onSocketConnectFailed`),this.connectionTracker.trackError(`connect_failed`,e,!0,this.transportTypeName?this.transportTypeName:this.UNKNOWN_TRANSPORT),this.fsm.onConnectingFailed()},e.prototype.onSocketDisconnect=function(e){var t=this.connectionTracker.getSessionLength()||0,n=d.DisconnectReason.fromRawReason(e);this.logger.error(`onSocketDisconnect, reason: ${n.reason}`),n.reason===`dup`&&this.lastDisconnectReason===`dup`&&t<this.options.duplicateDisconnectThresholdMs&&(this.logger.warn(`Socket was closed by server as Duplicate for the second time in a row after ${t} ms which is below the threshold of ${this.options.duplicateDisconnectThresholdMs} ms. Resetting cached connection parameters and making a new allocation.`),this.reconnectParams=void 0),this.lastDisconnectReason=n.reason,this.fsm.onSocketDisconnect(n),this.connectionExpireTimestampInSecs=void 0},e.prototype.onSocketReconnect=function(){this.logger.error(`onSocketReconnect`),this.fsm.onTrouterConnected()},e.prototype.onSocketReconnectFailed=function(e){this.logger.error(`onSocketReconnectFailed with '${e}'`),this.fsm.onSocketDisconnect(d.DisconnectReason.fromSocketIoEventData(`reconnecterror`,e))},e.prototype.onSocketReconnecting=function(){this.logger.error(`onSocketReconnecting`)},e.prototype.onSocketError=function(e){var t;this.logger.error(`onSocketError with '${(0,c.toJson)(e)}'`),this.fsm.isConnecting()&&(this.connectingErrorsInRow++,this.connectingErrorsInRow>=this.connectingErrorsThreshold&&this.resetReconnectParamsOnErrorThreshold()),this.connectionTracker.trackError(`connectSocket`,(t=e)!=null&&typeof t.toString==`function`?t.toString():`[${typeof t}]`),this.fsm.onSocketDisconnect(d.DisconnectReason.fromSocketIoEventData(`socketerror`,e))},e.prototype.onSocketMessage=function(e){var t,n=this;this.logger.debug(`onSocketMessage`);try{var r=(t=new C(e,this.logger)).headers?.[`X-Microsoft-Skype-Chain-ID`],i=r?` Chain-Id ${r}`:``;this.logger.info(`Received request N ${t.id}${i} CV ${t.correlationVector} to '${t.url}'`),t.startTS=Date.now(),t.url&&this.urlPath&&t.url.startsWith(this.urlPath)&&(t.shortUrl=t.url.substring(this.urlPath.length))}catch(e){var a=D(e);this.logger.error(`unable to parse request. Error: ${a}`),this.connectionTracker.sendResponseError(`unable to parse request, error: ${e}`);return}t.timeoutTimerId=setTimeout((function(){if(!t.replied){n.logger.error(`Request ${t.id} timed out`);var e=new l.ResponseData(t.id);e.status=504,e.headers={"Trouter-Responder":`ClientLib`},n.sendResponse(t,e),t.timedout=!0}}),this.timeoutOptions.requestTimeoutMs);try{this.fsm.onDownstreamRequest(t)}catch(e){this.logger.error(`exception in socket.on message. Error: ${D(e)}`),this.connectionTracker.sendResponseError(O(e),t,void 0)}},e.prototype.onTrouterConnected=function(e,t,n){var i,a,o=this;if((0,g.isV4ConnectEvent)(e)){var s=e;this.allocateResult=r(r({},s),{ttl:e.ttl.toString()}),this.populateAndCacheReconnectParams(s,s.reconnectUrl),this.populateConnectionStateFields(s)}else if(!this.allocateResult)return void this.logger.error(`Invalid internal state - received onTrouterConnected while allocateResult is not set`);this.connectingErrorsInRow=0,this.logger.info(`onTrouterConnected: ${this.allocateResult.surl}`),this.options.updateUserActivityDuringConnectionAttempt?this.transportTypeName===`xhr-polling`&&((t?.state??`unknown`)===this.userActivityState.getStateString()?t&&this.manager.onUserActivityStateAccepted(t.cv):(this.logger.info(`XHR user activity changed during connection attempt, from '${(0,c.toJson)(t)}' to '${this.userActivityState.toEventJSON()}', updating`),this.sendUserActivityStateIgnoreResponse())):this.transportTypeName===`xhr-polling`&&t&&this.manager.onUserActivityStateAccepted(t.cv),(i=this.socket?.socket?.options)!=null&&i.query&&(this.socket.socket.options.query+=`&connected=true`),this.urlPath=this.allocateResult.surl.replace(/https?:\/\/([A-z0-9\:\$\-\_\.\+\!\*\"\(\)\,]*)\//,`/`);var l=this.connectedUrl!==this.allocateResult.surl;this.connectedUrl=this.allocateResult.surl,this.connectionExpireTimestampInSecs=(0,c.calculateExpireTsInSec)((0,g.ensureNumber)(e.ttl)),this.connectionTracker.trackEnd(`connectSocket`),this.connectionTracker.trackConnected(l,this.transportTypeName?this.transportTypeName:this.UNKNOWN_TRANSPORT),(a=this.setAudienceSubscriptionsUnsafeAsync(n))==null||a.catch((function(e){return o.logger.error(`Re-subscribe to audiences has failed with ${e}`)})),this.fsm.onTrouterConnected()},e.prototype.onTrouterReconnect=function(e){var t=e.target;this.logger.info(`onTrouterReconnect target: ${t}`),t===`self`?this.fsm.onReconnectRequired(!0,o.ServerInitiated):this.fsm.onReconnectRequired(!1,o.ServerInitiated,e)},e.prototype.onTrouterMessageLoss=function(e){this.logger.debug(`onTrouterMessageLoss`),this.fsm.onTrouterMessageLost(e.droppedIndicators)},e.prototype.buildV4cUrlParams=function(){var e={};return e.tc=encodeURI((0,c.toJson)(this.clientInfo)),e.timeout=Math.floor(this.timeoutOptions.pingTimeoutMs/1e3),this.options.endpointId&&(e.epid=this.options.endpointId),this.appendConnectedClientIds(this.buildQuery(e),!0)},e.prototype.attachSocketIoHandlers=function(e,t,n,r){var i=this;e.on(`connecting`,(function(e){i.onSocketConnecting(e)})),e.on(`connect`,(function(){i.onSocketConnect(t)})),e.on(`connect_failed`,(function(e){i.onSocketConnectFailed(e)})),e.on(`close_during_connecting`,(function(e){i.onSocketConnectFailed(e)})),e.on(`disconnect`,(function(e){i.onSocketDisconnect(e)})),e.on(`reconnect`,(function(){i.onSocketReconnect()})),e.on(`reconnect_failed`,(function(e){i.onSocketReconnectFailed(e)})),e.on(`reconnecting`,(function(){i.onSocketReconnecting()})),e.on(`error`,(function(e){i.onSocketError(e)})),e.on(`message`,(function(e){i.onSocketMessage(e)})),e.on(`trouter.connected`,(function(e){i.onTrouterConnected(e,n,r)})),e.on(`trouter.reconnect`,(function(e){i.onTrouterReconnect(e)})),e.on(`trouter.message_loss`,(function(e){i.onTrouterMessageLoss(e)})),e.on(`audience.subscriptionresult`,(function(e,t){i.onAudienceSubscriptionResult(t)}))},e.prototype.onNavigatorOnlineStatusUpdate=function(){var e=window.navigator.onLine;this.logger.debug(`Browser online status update - new state: ${e}, previously: ${this.isNavigatorOnline}`),e&&!this.isNavigatorOnline?(this.isNavigatorOnline=!0,this.tokenBackoff.expediteIfPending(),this.connectionTracker.trackProgress(`browserNet`,`online`)):!e&&this.isNavigatorOnline&&(this.isNavigatorOnline=!1,this.connectionTracker.trackProgress(`browserNet`,`offline`))},e.prototype.onAllocationResponse=function(e,t){this.logger.info(`Received allocation response ${JSON.stringify(r(r({},e),{connectparams:void 0}))} (connectparams redacted)`),this.allocateResult=e,this.populateAndCacheReconnectParams(this.allocateResult,`${this.allocateResult.socketio}v4/a`),this.populateConnectionStateFields(this.allocateResult),this.fsm.onAllocationSucceed(t)},e.prototype.populateAndCacheReconnectParams=function(e,t){this.reconnectParams=r({serviceUrl:this.options.trouterUrl,reconnectUrl:t},e.connectparams),this.manager.onConnectionParametersUpdated(this.reconnectParams)},e.prototype.populateConnectionStateFields=function(e){var t=typeof e.ttl==`string`?parseInt(e.ttl,10):e.ttl;if(this.connectionExpireTimestampInSecs=(0,c.calculateExpireTsInSec)(t),this.connectionId=e.id??``,this.connectedClientId=e.ccid,this.logger.debug(`connected client id set {connectedClientId:${this.connectedClientId}}`),this.c2cUrlBase=e.curlb??``,this.c2cUrlBase===``){var n=e.surl.indexOf(`://`);n>=0&&(n=e.surl.indexOf(`/`,n+3))>=5&&e.surl.substr(n-5,5)===`:3443`&&(this.c2cUrlBase=e.surl.substr(0,n-5))}},e.prototype.onPingResponse=function(){this.logger.debug(`onPingResponse`),this.connectionTracker.increasePingResponseCount(),this.clearPingResponseTimer(),this.fsm.onPingResponse()},e.prototype.clearPingResponseTimer=function(){this.pingResponseTimerId!==void 0&&(clearTimeout(this.pingResponseTimerId),this.pingResponseTimerId=void 0)},e.prototype.buildQuery=function(e){for(var t=[],n=0,r=Object.keys(e);n<r.length;n++){var i=r[n];e[i]!==void 0&&t.push(`${i}=${e[i]}`)}return t.join(`&`)},e.prototype.appendConnectedClientIds=function(e,t){var n=``;e.includes(`ccid=`)||(n=`ccid=${this.connectedClientId}&`),this.domId&&(n+=`dom=${this.domId}&`),n.length>0&&(n=n.slice(0,-1));var r=t||e.includes(`?`)?`&`:`?`;return this.appendCorrelationIds(e+r+n,t)},e.prototype.appendEndpointId=function(e,t){var n=t||e.includes(`?`)?`&`:`?`;return!e.includes(`epid`)&&this.options.endpointId?`${e}${n}epid=${this.options.endpointId}`:e},e.prototype.appendCorrelationIds=function(e,t){var n=t||e.includes(`?`)?`&`:`?`;return e.includes(`cor_id`)?e:`${e}${n}cor_id=${this.options.clientCorrelationID}&con_num=${this.clientID}_${this.connectionAttempt}`},e.prototype.appendClientInfo=function(e,t){var n=t||e.includes(`?`)?`&`:`?`,r=encodeURIComponent((0,c.toJson)(this.clientInfo));return e.includes(`tc=`)?e:`${e}${n}tc=${r}`},e.prototype.safeString=function(e){return typeof e==`string`?e:``},e.prototype.sendResponse=function(e,t){var n,r;if(e.timedout)return this.logger.error(`Request ${e.id} already timed out`),1;if(e.replied)return this.logger.error(`Response for request ${e.id} already sent`),2;clearTimeout(e.timeoutTimerId),e.timeoutTimerId=void 0,e.replied=!0,t.headers=t.headers??{};var i=e.correlationVector;this.logger.info(`Sending response N ${e.id} CV ${i} with status ${t.status}`),i&&(t.headers[S]=i),(n=e.headers)!=null&&n[`trouter-request`]&&(t.headers[`trouter-request`]=e.headers[`trouter-request`]);var a=Date.now()-e.startTS;if(t.headers[`trouter-client`]=(0,c.toJson)({cd:a}),(r=e.headers)!=null&&r[`trouter-is-broadcast`]&&(t.headers[`trouter-is-broadcast`]=e.headers[`trouter-is-broadcast`]),!this.socket)return this.connectionTracker.sendResponseError(`no socket`,e,t),4;try{return this.socket.send((0,c.toJson)(t)),t.sentTS=Date.now(),e.incrementCorrelationVector(),this.connectionTracker.trackResponse(e,a,t),this.transportTypeName===`websocket`&&this.sendPingRequest(),0}catch(n){var o=`unable to send data on response.end. Error: ${D(n)}`;return this.logger.error(o),this.connectionTracker.sendResponseError(o,e,t),4}},e.prototype.sendUserActivityStateMultiple=function(e){var t=this,n=new T(`user.activity`),r=this.userActivityState.increaseCvAndGetEventObject();n.args=r,this.logger.debug(`Sending user activity '${this.userActivityState.toEventJSON()}', remaining ${e-1}`);var i=!1;this.sendDownstreamEvent(n,(function(){if(!0!==i&&(t.logger.info(`User activity state: ${r.state}, cv: ${r.cv} accepted`),t.manager.onUserActivityStateAccepted(r.cv),t.clearSentEventTimer(n.timeoutTimerId),e>1)){var a=setTimeout((function(){t.clearSentEventTimer(a),t.sendUserActivityStateMultiple(e-1)}),t.options.userActivitySecondResendDelayMs);t.registerSentEventTimer(a,`user.activity/resend`)}})),n.timeoutTimerId=setTimeout((function(){t.logger.error(`Activity state response timeout is fired`),i=!0,t.fsm.onActivityStateResponseTimeout(),t.clearSentEventTimer(n.timeoutTimerId)}),this.timeoutOptions.userActivityResponseTimeoutMs),this.registerSentEventTimer(n.timeoutTimerId,`user.activity/response`)},e.prototype.sendUserActivityStateIgnoreResponse=function(){var e=new T(`user.activity`),t=this.userActivityState.toEventObject();e.args=t,this.socket&&(this.logger.info(`Sending user activity after XHR connect, ${t.state}, cv: ${t.cv}, treating it as accepted`),this.socket.emit(e.name,e.args),this.manager.onUserActivityStateAccepted(t.cv))},e.prototype.sendDownstreamEvent=function(e,t){this.logger.debug(`Sending downstream event ${e.name}`),this.socket&&this.socket.emit(e.name,e.args,t)},e.prototype.registerSentEventTimer=function(e,t){this.logger.debug(`registering timer ${e} -> ${t}`),this.pendingSentEventTimers[e]=t},e.prototype.clearSentEventTimer=function(e){var t=this.pendingSentEventTimers[e];this.logger.debug(`clearing timer ${e} -> ${t}`),delete this.pendingSentEventTimers[e],clearTimeout(e)},e.prototype.getRegistrationTtl=function(){var e=(0,c.calculateTtlInSec)(this.connectionExpireTimestampInSecs);if(this.logger.debug(`Current connectionID will expire in ${e} seconds`),this.options.registration?.registrarTtlSec&&e>0){var t=this.options.registration.registrarTtlSec<e;return[Math.min(this.options.registration.registrarTtlSec,e),t]}return this.options.registration?.registrarTtlSec?[this.options.registration.registrarTtlSec,!1]:e>0?[e,!1]:[3600,!1]},e.prototype.clearIncallModeTimerId=function(){this.incallModeTimerId!==void 0&&(this.logger.debug(`Clearing in-call mode timer`),clearTimeout(this.incallModeTimerId),this.incallModeTimerId=void 0)},e.prototype.applyConnectionTrackerOptions=function(e){try{e.eventLogger&&typeof e.eventLogger.logEvent==`function`?(this.connectionTracker.mergeSettings(e.telemetrySettings),this.connectionTracker.enable(e.eventLogger)):this.logger.warn(`Trouter client event logging disabled due to invalid configuration.`)}catch(e){this.logger.warn(`Trouter client event logging disabled. Error: ${D(e)}`),this.connectionTracker.disable()}},e.prototype.canRetryTokenFetchRequest=function(e){var t=this.options.retryLimitOnTokenFetch;return t==null||e<t||(this.logger.warn(`Reached limit on maximum number of token fetch request. Current count: ${e}, retry limit: ${t}`),!1)},e}();function ee(e,t){var n=t?void 0:{"X-MS-Migration":`True`};switch(e.tokenType.toLowerCase()){case`skype`:return r({"X-Skypetoken":e.token},n);case`aad`:case`cae`:return r({Authorization:`Bearer ${e.token}`},n);default:throw Error(`unsupported token type: ${e.tokenType}`)}}function D(e){return typeof e==`object`&&e&&e.stack!==void 0?(0,c.toJson)(e.stack):`"(no error.stack)"`}function O(e){return typeof e==`object`&&e&&typeof e.message==`string`?e.message:`(no error.message)`}t.TrouterConnection=E},616:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterUrlPromise=void 0;var r=n(642);t.TrouterUrlPromise=function(){function e(e){this.logger=new r.Logger(`UrlPromise`,e)}return e.prototype.getPromise=function(){var e=this;return this.url===void 0?(this.pendingPromise===void 0?(this.logger.debug(`creating and returning promise`),this.pendingPromise=new Promise((function(t,n){e.pendingPromiseResolveRef=t,e.pendingPromiseRejectRef=n}))):this.logger.debug(`returning existing promise`),this.pendingPromise):(this.logger.debug(`returning previously resolved url: ${this.url}`),Promise.resolve(this.url))},e.prototype.resolveUrl=function(e){this.url=e,this.logger.debug(`got url: ${this.url}`);var t=this.pendingPromiseResolveRef;this.pendingPromise=void 0,this.pendingPromiseResolveRef=void 0,this.pendingPromiseRejectRef=void 0,t!==void 0&&(this.logger.debug(`resolving promise`),t(e))},e.prototype.rejectUrl=function(e){this.logger.debug(`aborting`);var t=this.pendingPromiseRejectRef;this.url=void 0,this.pendingPromise=void 0,this.pendingPromiseResolveRef=void 0,this.pendingPromiseRejectRef=void 0,t!==void 0&&(this.logger.debug(`rejecting promise`),t(e))},e.prototype.resetUrl=function(){this.logger.debug(`resetting url`),this.url=void 0},e}()},619:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MessageHandlerRegistry=void 0;var r=n(509),i=n(642);t.MessageHandlerRegistry=function(){function e(e){this.messageHandlers=[],this.logger=new i.Logger(`MessageHandlers`,e)}return e.prototype.register=function(e){if(this.messageHandlers.some((function(t){return t===e})))throw Error(`Registering the same handler twice is not allowed`);this.messageHandlers.push(e)},e.prototype.clear=function(){this.logger.debug(`Clearing message handlers`),this.messageHandlers=[]},e.prototype.active=function(){return this.messageHandlers.length>0},e.prototype.handleMessage=function(e){for(var t={resultCode:r.UNHANDLED_MESSAGE_ACK,isHandled:!1},n=0,i=this.messageHandlers;n<i.length;n++){var a=i[n],o=this.safeExecuteHandle(a,e);if(o!==void 0&&(o.isHandled===void 0||o.isHandled))return o.resultCode===void 0&&(o.resultCode=r.HANDLED_MESSAGE_ACK),o}return t},e.prototype.safeExecuteHandle=function(e,t){try{return e.handleMessage(t)}catch(e){this.logger.warn(`Trouter message handler threw an exception: ${e}`);return}},e}()},634:function(e,t,n){var r=this&&this.__awaiter||function(e,t,n,r){return new(n||=Promise)((function(i,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((r=r.apply(e,t||[])).next())}))},i=this&&this.__generator||function(e,t){var n,r,i,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},o=Object.create((typeof Iterator==`function`?Iterator:Object).prototype);return o.next=s(0),o.throw=s(1),o.return=s(2),typeof Symbol==`function`&&(o[Symbol.iterator]=function(){return this}),o;function s(s){return function(c){return function(s){if(n)throw TypeError(`Generator is already executing.`);for(;o&&(o=0,s[0]&&(a=0)),a;)try{if(n=1,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,r=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((i=(i=a.trys).length>0&&i[i.length-1])||s[0]!==6&&s[0]!==2)){a=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){a.label=s[1];break}if(s[0]===6&&a.label<i[1]){a.label=i[1],i=s;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(s);break}i[2]&&a.ops.pop(),a.trys.pop();continue}s=t.call(e,a)}catch(e){s=[6,e],r=0}finally{n=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}};Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterManager=t.AudienceSubscriptionState=t.UserActivityObject=void 0;var a=n(659),o=n(234),s=n(423),c=n(642),l=n(902),u=n(235),d=n(573),f=n(335),p=n(10),m=n(509),h=function(){function e(e,t){this.state=e,this.correlationVector=t===void 0?a.CorrelationVector.extend():t}return e.prototype.getStateString=function(){switch(this.state){case o.UserActivityState.Active:return`active`;case o.UserActivityState.Inactive:return`inactive`;case o.UserActivityState.Unknown:return`unknown`;default:return`undefined`}},e.prototype.increaseCvAndGetEventObject=function(){return this.correlationVector.increase(),this.toEventObject()},e.prototype.toEventObject=function(){return{state:this.getStateString(),cv:this.correlationVector.value()}},e.prototype.toEventJSON=function(){return(0,a.toJson)(this.toEventObject())},e}();t.UserActivityObject=h;var g=function(){function e(e,t){t===void 0&&(t=a.CorrelationVector.extend()),this.subscirpitonsPerScope=e,this.correlationVector=t}return e.prototype.increaseCvAndGetEventObject=function(){return this.correlationVector.increase(),this.toEventObject()},e.prototype.toEventObject=function(){return{audiences:this.toListOfSubscriptions(),cv:this.correlationVector.value()}},e.prototype.toEventJSON=function(){return(0,a.toJson)(this.toEventObject())},e.prototype.toListOfSubscriptions=function(){for(var e=[],t=0,n=Object.keys(this.subscirpitonsPerScope);t<n.length;t++){var r=n[t];e.push.apply(e,this.subscirpitonsPerScope[r])}return e},e}();t.AudienceSubscriptionState=g;var _=`extraTransports`;t.TrouterManager=function(){function e(e,t,n,r,i,s){this.logFunc=e,this.options=t,this.tokenProvider=n,this.usingLegacyTokenApi=r,this.listener=i,this.extraTransportVersionWithinProcess=0,this.logger=new c.Logger(`Manager`,e),this.logger.info(`Created TrouterManager with options ${(0,a.toJson)(this.options)}`),this.fsm=new p.TrouterManagerFsm(e,this),this.baseEndpointUrl=``,this.processedMessageLoss={},this.userActivityObject=new h(o.UserActivityState.Unknown),this.protocolSelector=s??this.tokenTypeProtocolSelector.bind(this)}return e.prototype.start=function(){this.fsm.start()},e.prototype.stop=function(e){this.fsm.stop(e)},e.prototype.configure=function(e){this.options=e,this.firstConnection!==void 0&&this.firstConnection.configure(e),this.secondConnection!==void 0&&this.secondConnection.configure(e),this.logger.info(`Reconfigured TrouterManager with options ${(0,a.toJson)(this.options)}`)},e.prototype.checkConnection=function(e){this.firstConnection!==void 0&&this.firstConnection.checkConnection(e),this.secondConnection!==void 0&&this.secondConnection.checkConnection(e)},e.prototype.resendRegistration=function(){return r(this,void 0,void 0,(function(){return i(this,(function(e){return this.secondConnection===void 0?this.firstConnection===void 0?(this.logger.info(`No connection to resend registration on, will be done upon (re)connect`),[2]):(this.logger.info(`Resending registration on the first/current connection`),[2,this.firstConnection.resendRegistration()]):(this.logger.info(`Resending registration on the second/new connection`),[2,this.secondConnection.resendRegistration()])}))}))},e.prototype.registerExtraTransports=function(e,t){var n,r=this;this.extraTransportsState={transports:e,clientDescriptionOverride:t},this.extraTransportVersionWithinProcess++,(n=this.options.keyValueCache)==null||n.setCacheForKey(_,JSON.stringify(this.extraTransportsState)).catch((function(){r.logger.error(`Failed to store extra transports in cache`)})),this.secondConnection===void 0?this.firstConnection===void 0?this.logger.warn(`No connection to register extra transports on, will be done upon (re)connect`):(this.logger.info(`Registering extra transports ${JSON.stringify(Object.keys(e))} and ${Object.keys(t??{}).length} overridden client description properties on the first/current connection`),this.firstConnection.registerExtraTransports(e,t)):(this.logger.info(`Registering extra transports ${JSON.stringify(Object.keys(e))} and ${Object.keys(t??{}).length} overridden client description properties on the second/new connection`),this.secondConnection.registerExtraTransports(e,t))},e.prototype.getServerState=function(){if(this.firstConnection!==void 0)return this.firstConnection.getServerState()},e.prototype.getState=function(){return this.fsm.getState()},e.prototype.isInTerminalState=function(){return this.fsm.getInternalState()===s.TrouterManagerState.TerminalError},e.prototype.reportStateInfo=function(){var e=this.firstConnection?f.State[this.firstConnection.getState()]:`Unknown`,t=s.TrouterManagerState[this.fsm.getInternalState()];return this.secondConnection?`Manager ${t}; 1st ${e}; 2nd ${f.State[this.secondConnection.getState()]}`:`Manager ${t}; Connection ${e}`},e.prototype.startFirstConnection=function(){var e=this,t=new d.TrouterConnection(this.logFunc,this.options,this.configuredTrouterManager(),this.tokenProvider,this.usingLegacyTokenApi,this.userActivityObject,this.protocolSelector,this.audienceSubscriptionState);this.firstConnection=t,Promise.all([this.getConnectionCache(),this.fetchExtraTransportsCache()]).then((function(n){var r=n[0];t.start(r,e.extraTransportsState?.transports,e.extraTransportsState?.clientDescriptionOverride)})).catch((function(){e.logger.error(`unexpected error while starting first connection (wrapped cache read functions should never throw)`)}))},e.prototype.startSecondConnection=function(e){var t=this,n=new d.TrouterConnection(this.logFunc,this.options,this.configuredTrouterManager(),this.tokenProvider,this.usingLegacyTokenApi,this.userActivityObject,this.protocolSelector,this.audienceSubscriptionState);this.secondConnection=n,this.firstConnection!==void 0&&this.firstConnection.disableRegistrationsAndAutoReconnect(),e?Promise.all([this.getConnectionCache(),this.fetchExtraTransportsCache()]).then((function(e){var r=e[0];n.start(r,t.extraTransportsState?.transports,t.extraTransportsState?.clientDescriptionOverride)})).catch((function(){t.logger.error(`unexpected error while starting second connection (wrapped cache read functions should never throw)`)})):this.fetchExtraTransportsCache().then((function(){n.start(void 0,t.extraTransportsState?.transports,t.extraTransportsState?.clientDescriptionOverride)})).catch((function(){t.logger.error(`unexpected error while starting second connection (wrapped cache read functions should never throw)`)}))},e.prototype.stopFirstConnection=function(e){this.firstConnection!==void 0&&(this.storedFirstConnection=this.firstConnection,this.firstConnection.stop(e),this.firstConnection=void 0)},e.prototype.stopSecondConnection=function(e){this.secondConnection!==void 0&&(this.secondConnection.stop(e),this.secondConnection=void 0)},e.prototype.stopSecondConnectionDelayed=function(){if(this.secondConnection!==void 0){var e=this.secondConnection;this.secondConnection=void 0,this.logger.info(`Closing an inactive connection in ${Math.round(this.options.lingeringConnectionDelayMs/1e3)}s`),setTimeout((function(){e.stop(!0)}),this.options.lingeringConnectionDelayMs)}},e.prototype.forceStopLingeringConnection=function(){this.storedFirstConnection&&=(this.storedFirstConnection.stop(!1),void 0)},e.prototype.switchConnections=function(){var e=this.firstConnection;this.firstConnection=this.secondConnection,this.secondConnection=e},e.prototype.doesSecondConnectionExist=function(){return this.secondConnection!==void 0},e.prototype.dispatchConnected=function(){if(this.firstConnection!==void 0){var e=this.firstConnection.getServerState(),t=e.url.endsWith(`/`)?e.url.slice(0,-1):e.url,n={baseEndpointUrl:t,newEndpointUrl:t!==this.baseEndpointUrl,c2cUrlBase:e.c2cUrlBase,clientId:e.connectedClientId,connectionId:e.connectionId,connectionTtlSec:e.getRemainingTtlInSec()};this.baseEndpointUrl=t,this.listener.onTrouterConnected(e.url,n)}},e.prototype.dispatchDisconnected=function(){this.listener.onTrouterDisconnected&&this.listener.onTrouterDisconnected()},e.prototype.dispatchTerminalError=function(){this.listener.onTrouterDisconnected&&this.listener.onTrouterDisconnected()},e.prototype.dispatchRegistrationState=function(e){this.options.registrationStateCallback&&this.options.registrationStateCallback(e)},e.prototype.expediteBackoffOnConnections=function(){this.lastExpediteBackoffCallAt!==void 0&&Date.now()-this.lastExpediteBackoffCallAt<(this.options.expediteBackoffOnStartMinimumDelayMs??1e4)?this.logger.info(`Expedite backoff due to start() too frequent, skipping`):(this.lastExpediteBackoffCallAt=Date.now(),this.firstConnection!==void 0&&this.firstConnection.expediteBackoff(),this.secondConnection!==void 0&&this.secondConnection.expediteBackoff())},e.prototype.onDownstreamRequest=function(e,t,n){var r={id:t.id,method:t.method,path:`/${t.shortUrl}`,body:t.body,headers:t.headers},i={id:t.id,status:0,headers:{},body:``,send:function(){return i.status<=100||i.status>=999?3:(n.writeHead(i.status,i.headers),n.end(i.body))}};this.listener.onTrouterRequest(r,i)},e.prototype.onConnected=function(e){this.fsm.onConnected(e===this.firstConnection)},e.prototype.onRegistered=function(e){this.fsm.onRegistered(e===this.firstConnection)},e.prototype.onUnregistered=function(e){this.fsm.onUnregistered(e===this.firstConnection||e===this.storedFirstConnection)},e.prototype.onReconnecting=function(e){this.fsm.onReconnecting(e===this.firstConnection)},e.prototype.onReconnectIsRequired=function(e,t,n){this.fsm.onReconnectionRequired(e===this.firstConnection,t,n)},e.prototype.onDisconnected=function(e){this.fsm.onDisconnected(e===this.firstConnection||e==this.storedFirstConnection),this.storedFirstConnection=void 0},e.prototype.onTerminalError=function(){this.fsm.onTerminalError(),this.storedFirstConnection=void 0},e.prototype.onUserActivityStateAccepted=function(e){this.listener.onTrouterUserActivityStateAccepted&&this.listener.onTrouterUserActivityStateAccepted(e)},e.prototype.onAudiencesSetResolved=function(e,t){var n,r;(r=(n=this.listener).onAudiencesSetResolved)==null||r.call(n,e,t)},e.prototype.onConnectionParametersUpdated=function(e){this.setConnectionCache(e)},e.prototype.setUserActivityState=function(e,t){this.userActivityObject=new h(e,a.CorrelationVector.extend(t)),this.secondConnection===void 0?this.firstConnection!==void 0&&(this.logger.info(`Setting user activity ${this.userActivityObject.toEventJSON()} on the first/current connection`),this.firstConnection.setUserActivityState(this.userActivityObject)):(this.logger.info(`Setting user activity ${this.userActivityObject.toEventJSON()} on the second/new connection`),this.secondConnection.setUserActivityState(this.userActivityObject))},e.prototype.setAudienceSubscriptionsAsync=function(e,t,n){var r=e.scope??m.constants.SUBSCRIPTIONS_DEFAULT_SCOPE,i=this.GetUpdatedAsState(e,r);if(this.audienceSubscriptionState=new g(i,a.CorrelationVector.extend(n)),this.secondConnection)return this.logger.info(`Setting audience subscriptions ${this.audienceSubscriptionState.toEventJSON()} on second/new connection`),this.secondConnection.setAudienceSubscriptionsAsync(this.audienceSubscriptionState,t);if(this.firstConnection)return this.logger.info(`Setting audience subscriptions ${this.audienceSubscriptionState.toEventJSON()} on first/current connection`),this.firstConnection.setAudienceSubscriptionsAsync(this.audienceSubscriptionState,t);throw Error(`No connection found`)},e.prototype.GetUpdatedAsState=function(e,t){var n={};return this.audienceSubscriptionState!==void 0&&(n=structuredClone(this.audienceSubscriptionState.subscirpitonsPerScope)),n[t]=e.audienceSubscriptions,n},e.prototype.onTrouterMessageLost=function(e){var t=this;if(this.listener.onTrouterMessageLoss)if(e?.length){var n=e.filter((function(e){return t.processedMessageLoss[`${e.tag}-${e.etag}`]!==void 0}));if(n.length&&(this.logger.info(`onTrouterMessageLoss - immediately acknowledging ${n.length} seen dropped indicators`),this.sendProcessedDroppedIndicators(n),!(e=e.filter((function(e){return t.processedMessageLoss[`${e.tag}-${e.etag}`]===void 0}))).length))return void this.logger.info(`onTrouterMessageLoss - all declared dropped indicators have been seen before`);if(!this.listener.onTrouterMessageLoss(e.map((function(e){return e.tag}))))return void this.logger.warn(`onTrouterMessageLoss - some flow tag(s) have not been processed by listeners`);e.forEach((function(e){t.processedMessageLoss[`${e.tag}-${e.etag}`]=``})),this.sendProcessedDroppedIndicators(e)}else this.logger.warn(`onTrouterMessageLoss - no flow tags have been provided`)},e.prototype.getConnectionCache=function(){var e=this;return this.options.connectionCache?(this.logger.debug(`Querying host's connection cache`),this.options.connectionCache.onGetTrouterConnectionCache().then((function(e){var t=e?JSON.parse(e):void 0;return typeof t==`object`?t:void 0})).catch((function(t){return e.logger.warn(`Invalid connection cache content provided: ${t}`),e.connectionCache}))):Promise.resolve(this.connectionCache)},e.prototype.fetchExtraTransportsCache=function(){var e=this,t=this.extraTransportVersionWithinProcess;return this.options.keyValueCache&&this.extraTransportsState===void 0?this.options.keyValueCache.getCacheForKey(_).then((function(n){if(t===e.extraTransportVersionWithinProcess){if(n){var r=JSON.parse(n);typeof r==`object`&&r&&(Object.prototype.hasOwnProperty.call(r,`transports`)?e.extraTransportsState=r:e.extraTransportsState={transports:r,clientDescriptionOverride:void 0}),e.extraTransportVersionWithinProcess++}}else e.logger.info(`Extra transports cache was updated while fetching it, returning the current state`)})).catch((function(){e.logger.error(`Failed to retrieve extra transports from cache`)})):Promise.resolve()},e.prototype.setConnectionCache=function(e){if(this.connectionCache=e,this.options.connectionCache)try{this.options.connectionCache.onSetTrouterConnectionCache(JSON.stringify(e))}catch(e){this.logger.warn(`Error setting external connection cache: ${e}`)}},e.prototype.sendProcessedDroppedIndicators=function(e){this.firstConnection===void 0?this.secondConnection===void 0||this.secondConnection.sendProcessedDroppedIndicators(e):this.firstConnection.sendProcessedDroppedIndicators(e)},e.prototype.configuredTrouterManager=function(){return new u.RegistrationEnforcer(this,this.options.connectionDependsOnRegistration,this.options.delayEventsUntilRegistered)},e.prototype.tokenTypeProtocolSelector=function(e,t){return this.options.forceV4aProtocol||this.options.forceV4aProtocolForSkypetoken&&e===`skype`&&(0,l.safeToString)(t?.scae)!==`1`?`v4a`:`v4c`},e}()},642:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Logger=void 0,t.Logger=function(){function e(e,t){this.name=e,this.logger=t}return e.prototype.debug=function(e){this.logger.debug(`[${this.name}] ${e}`)},e.prototype.info=function(e){this.logger.info(`[${this.name}] ${e}`)},e.prototype.warn=function(e){this.logger.warn(`[${this.name}] ${e}`)},e.prototype.error=function(e){this.logger.error(`[${this.name}] ${e}`)},e}()},659:function(e,t){var n=this&&this.__awaiter||function(e,t,n,r){return new(n||=Promise)((function(i,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((r=r.apply(e,t||[])).next())}))},r=this&&this.__generator||function(e,t){var n,r,i,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},o=Object.create((typeof Iterator==`function`?Iterator:Object).prototype);return o.next=s(0),o.throw=s(1),o.return=s(2),typeof Symbol==`function`&&(o[Symbol.iterator]=function(){return this}),o;function s(s){return function(c){return function(s){if(n)throw TypeError(`Generator is already executing.`);for(;o&&(o=0,s[0]&&(a=0)),a;)try{if(n=1,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,r=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((i=(i=a.trys).length>0&&i[i.length-1])||s[0]!==6&&s[0]!==2)){a=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){a.label=s[1];break}if(s[0]===6&&a.label<i[1]){a.label=i[1],i=s;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(s);break}i[2]&&a.ops.pop(),a.trys.pop();continue}s=t.call(e,a)}catch(e){s=[6,e],r=0}finally{n=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}};function i(e){try{return JSON.stringify(e)}catch{return`Unable to serialize object of type ${typeof e}`}}Object.defineProperty(t,"__esModule",{value:!0}),t.Timespan=t.CorrelationVector=void 0,t.toJson=i,t.anonymizeShortUrl=function(e){var t=/^(TeamsUnifiedPresenceService|acceptance|addParticipant\w*|balanceUpdate|call(Agent)?|controlVideoStreaming|conversation\w*|dominantSpeakerInfo|end|join|media\w*|messaging|progress|rejection|retargetCompletion|rosterUpdate|update|ups)$/i;return e.split(`/`).map((function(e){return!e||t.test(e)||e.length<3?e:`${e.slice(0,2)}...`})).join(`/`)},t.headersToLog=function(e){for(var t=/^(Host|User-Agent|Content-Length|Content-Type|X-Microsoft-Skype-\S+|(X-)?Trouter.*|X-CallingProxy|MS-CV|traceparent|Priority)$/i,n={},r=0,a=Object.keys(e);r<a.length;r++){var o=a[r];t.test(o)&&(n[o]=e[o])}return i(n)},t.calculateTtlInSec=function(e){var t=Math.round(new Date().getTime()/1e3);return e!==void 0&&e>t?e-t:0},t.calculateExpireTsInSec=function(e){return Math.round(new Date().getTime()/1e3)+e},t.fetchWithTimeout=function(e,t){return n(this,void 0,void 0,(function(){var n,i,a;return r(this,(function(r){return i=new Promise((function(t,r){fetch(e).then((function(e){clearTimeout(n),t(e)})).catch((function(e){clearTimeout(n),r(e)}))})),t===0?[2,i]:(a=new Promise((function(r,i){var a=new URL(e.url),o=Error(`${e.method} ${a.origin}${a.pathname} timed out`);n=setTimeout(i,t,o)})),[2,Promise.race([i,a])])}))}))},t.CorrelationVector=function(){function e(e){this.base=e===void 0?this.createCorrelationVectorBase():e,this.extension=0}return e.extend=function(t){return new e(t)},e.prototype.increase=function(){this.extension++},e.prototype.value=function(){return`${this.base}.${this.extension}`},e.prototype.createCorrelationVectorBase=function(){for(var e=``,t=0;t<21;t++)e+=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0987654321/+`.charAt(Math.floor(64*Math.random()));return e+`AQgw`.charAt(Math.floor(4*Math.random()))},e}(),t.Timespan=function(){function e(){this.start=Date.now()}return Object.defineProperty(e.prototype,"duration",{get:function(){return Date.now()-this.start},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"startTime",{get:function(){return this.start},enumerable:!1,configurable:!0}),e.prototype.reset=function(){this.start=Date.now()},e}()},673:t=>{t.exports=e},705:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.updateAudienceSubscriptionQuery=function(e,t){return e.replace(/([?&]audienceSubscriptionState=)[^&]*/,`\$1${t}`)}},764:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DisconnectReason=void 0,t.DisconnectReason=function(){function e(e,t,n){this.reason=e,this.claims=t,this.details=n}return e.fromRawReason=function(t,n){if(t===``||t===`dup`)return new e(t);try{var r=JSON.parse(t);return typeof r!=`object`||r.reason===void 0?(n?.error(`invalid disconnect reason format`),new e(`unknown`,void 0,t)):new e(r.reason,r.claims,r.details)}catch{return new e(`disconnect`,void 0,t)}},e.fromSocketIoEventData=function(t,n){return typeof n==`string`?new e(t,void 0,n):void 0},e.prototype.toTelemetryString=function(){return this.reason===`socketerror`||this.reason===`reconnecterror`||this.reason===`disconnect`?this.details:this.reason},e}()},882:function(e,t,n){var r=this&&this.__assign||function(){return r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},r.apply(this,arguments)},i=this&&this.__awaiter||function(e,t,n,r){return new(n||=Promise)((function(i,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((r=r.apply(e,t||[])).next())}))},a=this&&this.__generator||function(e,t){var n,r,i,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},o=Object.create((typeof Iterator==`function`?Iterator:Object).prototype);return o.next=s(0),o.throw=s(1),o.return=s(2),typeof Symbol==`function`&&(o[Symbol.iterator]=function(){return this}),o;function s(s){return function(c){return function(s){if(n)throw TypeError(`Generator is already executing.`);for(;o&&(o=0,s[0]&&(a=0)),a;)try{if(n=1,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,r=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((i=(i=a.trys).length>0&&i[i.length-1])||s[0]!==6&&s[0]!==2)){a=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){a.label=s[1];break}if(s[0]===6&&a.label<i[1]){a.label=i[1],i=s;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(s);break}i[2]&&a.ops.pop(),a.trys.pop();continue}s=t.call(e,a)}catch(e){s=[6,e],r=0}finally{n=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}};Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterService=t.UserActivityState=t.TrouterState=void 0,t.createTrouterService=function(e){return new h(e)},t.getTrouterServiceVersion=function(){return o.CLIENT_VERSION},t.replaceTrouterUrlBase=function(e,t){var n=e.indexOf(`://`);if(n>=0){var r=e.indexOf(`/`,n+3);if(r>=0)return t+e.substr(r)}return``};var o=n(509),s=n(234);Object.defineProperty(t,"TrouterState",{enumerable:!0,get:function(){return s.TrouterState}}),Object.defineProperty(t,"UserActivityState",{enumerable:!0,get:function(){return s.UserActivityState}});var c=n(642),l=n(619),u=n(220),d=n(634),f=n(616);function p(e,t){if(!t)return e;var n=r(r({},e),{enabled:t.TelemetryEnabled});return t.ClientTelemetryEventEnabled!==void 0&&(n=r(r({},n),t.ClientTelemetryEventEnabled)),n}function m(e,t,n){var i,a,o,s=function(n){return e.proxyUrlRewrite?(t.info(`Using rewritten URL for proxy`),e.proxyUrlRewrite(n)):n};return{clientInfo:{ua:e.trouterSettings.productName,v:e.trouterSettings.version},ioOptions:{ackTimeoutMs:5e3,rewriteUrlForProxy:s},clientCorrelationID:e.trouterSettings.sessionId,environment:e.trouterSettings.environment,telemetrySettings:p(e.telemetryConfig.settings,n),eventLogger:e.telemetryConfig.eventLogger,endpointId:e.trouterSettings.registrationId,trouterUrl:n?.TrouterConnectionUrl||e.trouterSettings.trouterServiceUrl,registration:e.trouterSettings.registrarServiceUrl||e.trouterSettings.useRegistrarUrlFromAllocate?{registrarUrl:e.trouterSettings.registrarServiceUrl??``,useRegistrarUrlFromAllocate:(i=e.trouterSettings.useRegistrarUrlFromAllocate)!=null&&i,registrationId:e.trouterSettings.registrationId??``,pnhAppId:e.trouterSettings.pnhAppId??``,platform:e.trouterSettings.platform??``,pnhTemplateKey:e.trouterSettings.pnhTemplate??``,platformUIVersion:e.trouterSettings.platformUIVersion??``,productContext:e.trouterSettings.pnhProductContext||void 0,context:e.trouterSettings.pnhContext??``,registrarTtlSec:(e.trouterSettings.maxRegistrationTimeInMs??0)/1e3}:void 0,connectionDependsOnRegistration:e.trouterSettings.registrarServiceUrl===void 0?function(){return!1}:e.trouterSettings.connectionDependsOnRegistration??function(){return!1},delayEventsUntilRegistered:e.trouterSettings.delayEventsUntilRegistered??function(){return!1},timeoutOptions:r({connectionTimeoutMs:e.trouterSettings.trouterConnectTimeoutInMs||3e4,fetchTimeoutMs:1e4,pingTimeoutMs:4e4,pongTimeoutMs:5e3,maxBackoffMs:e.trouterSettings.productName===`TeamsCDL`?3e5:3e4,requestTimeoutMs:5e3,userActivityResponseTimeoutMs:1e4},e.trouterSettings.timeoutOptions),incallTimeoutOptions:r({connectionTimeoutMs:1e4,fetchTimeoutMs:5e3,pingTimeoutMs:5e3,pongTimeoutMs:2e3,maxBackoffMs:e.trouterSettings.productName===`TeamsCDL`?3e5:1e4,requestTimeoutMs:5e3,userActivityResponseTimeoutMs:1e4},e.trouterSettings.incallTimeoutOptions),incallModeTimeoutMs:e.trouterSettings.incallModeTimeoutMs??0,lingeringConnectionDelayMs:6e4,userActivitySecondResendDelayMs:e.trouterSettings.userActivitySecondResendDelayMs||1e4,duplicateDisconnectThresholdMs:1e4,connectionCache:e.connectionCache,keyValueCache:e.keyValueCache,registrationStateCallback:e.registrationStateCallbackForAcsDoNotUse,rewriteUrlForProxy:s,retryLimitOnTokenFetch:e.trouterSettings.retryLimitOnTokenFetch,extraConnectionHeaders:e.trouterSettings.extraConnectionHeaders,expediteBackoffOnStartMinimumDelayMs:1e4,updateUserActivityDuringConnectionAttempt:(a=e.trouterSettings.updateUserActivityDuringConnectionAttempt)==null||a,initialConnectivityCheck:(o=e.trouterSettings.initialConnectivityCheck)==null||o,toJSON:function(){return r(r({},this),{connectionCache:this.connectionCache?{}:this.connectionCache,keyValueCache:this.keyValueCache?{}:this.keyValueCache})}}}var h=function(){function e(e){this.logProvider=e,this.stateChangedListeners=[],this.logger=new c.Logger(`Trouter`,e),this.trouterUrlPromise=new f.TrouterUrlPromise(e),this.messageHandlers=new l.MessageHandlerRegistry(e),this.listeners={},this.connectionInfo=null,this.logger.info(`Created TrouterService version ${o.CLIENT_VERSION}`)}return e.prototype.start=function(e){if(this.logger.info(`Start`),!e.skypeTokenProvider&&!e.authTokenProvider)throw Error(`no token provider has been configured, either skypeTokenProvider or authTokenProvider must be populated`);e.skypeTokenProvider&&!e.trouterSettings.disableInternalSkypeTokenCache&&(e.skypeTokenProvider=(0,u.addCacheAsBackupTo)(e.skypeTokenProvider)),this.trouterCfg=e;var t=m(e,this.logger,this.ecsCfg);!1===e.internalEnableV4cProtocol&&(t.forceV4aProtocol=!0),!1===e.internalUseV4aForSkypetoken&&(t.forceV4aProtocolForSkypetoken=!0);var n=function(e,t){var n,r=this;return function(o){return i(r,void 0,void 0,(function(){var r,i,s;return a(this,(function(a){switch(a.label){case 0:r=new Date,i=setInterval((function(){var t=Math.round((Date.now()-r.getTime())/6e4);e.warn(`Note: Trouter auth token request promise from ${r.toISOString()} has not been resolved for ${t} minutes. The client is blocked from operating properly`)}),3e5),a.label=1;case 1:return a.trys.push([1,,3,4]),[4,t(o)];case 2:return s=a.sent(),o.needFresh&&s.token===n&&e.error(`API violation: Trouter auth token provider got a request with needRefresh=true, but returned the same token as last time anyway. Please fix the host app`),n=s.token,[2,s];case 3:return clearInterval(i),[7];case 4:return[2]}}))}))}}(this.logger,e.authTokenProvider??function(e){var t=this;return function(n){return i(t,void 0,void 0,(function(){var t;return a(this,(function(r){switch(r.label){case 0:return t={},[4,e(n.needFresh)];case 1:return[2,(t.token=r.sent(),t.tokenType=`skype`,t)]}}))}))}}(e.skypeTokenProvider));this.trouterServer===void 0&&(this.trouterServer=new d.TrouterManager(this.logProvider,t,n,e.authTokenProvider===void 0,this)),this.pendingActivityState!==void 0&&(this.trouterServer.setUserActivityState(this.pendingActivityState[0],this.pendingActivityState[1]),this.pendingActivityState=void 0),this.pendingExtraTransports!==void 0&&(this.trouterServer.registerExtraTransports(this.pendingExtraTransports.transports,this.pendingExtraTransports.clientDescriptionOverride),this.pendingExtraTransports=void 0),this.trouterServer.start()},e.prototype.stop=function(e){this.logger.info(`close connection`),this.trouterUrlPromise.rejectUrl(Error(`TrouterService is stopped`)),this.trouterServer!==void 0&&this.trouterServer.stop(e)},e.prototype.setEcsConfig=function(e){return i(this,void 0,void 0,(function(){var t=this;return a(this,(function(n){return[2,new Promise((function(n){if(t.ecsCfg=e.TrouterJScriptClient,t.logger.info(`Setting ECS configuration to ${JSON.stringify(t.ecsCfg)}`),t.trouterServer!==void 0&&t.trouterCfg!==void 0){var r=m(t.trouterCfg,t.logger,t.ecsCfg);t.trouterServer.configure(r)}n()}))]}))}))},e.prototype.checkConnection=function(e){this.trouterServer!==void 0&&this.trouterServer.checkConnection(e!=null&&e)},e.prototype.resendRegistration=function(){return i(this,void 0,void 0,(function(){return a(this,(function(e){if(!this.trouterServer)throw Error(`resendRegistration called too early`);return[2,this.trouterServer.resendRegistration()]}))}))},e.prototype.registerExtraTransports=function(e,t){if(this.trouterServer===void 0)return this.pendingExtraTransports={transports:e,clientDescriptionOverride:t},void this.logger.warn(`registerExtraTransports called before start()`);this.logger.info(`registerExtraTransports called`),this.pendingExtraTransports=void 0,this.trouterServer.registerExtraTransports(e,t)},e.prototype.registerListener=function(e,t){return t===``||!t.startsWith(`/`)||t.includes(`?`)||t.includes(`#`)?(this.logger.error(`Listener path '${t}' is not valid`),!1):this.listeners[t]?(this.logger.error(`Another listener is already registered for path '${t}'`),!1):(this.listeners[t]=e,this.logger.debug(`Listener for path '${t}' registered`),this.connectionInfo&&e.onTrouterConnected(this.connectionInfo.baseEndpointUrl+t,this.connectionInfo),!0)},e.prototype.unregisterListener=function(e){for(var t=[],n=0,r=Object.keys(this.listeners);n<r.length;n++){var i=r[n];this.listeners[i]===e&&t.push(i)}if(t.length===0)return!1;for(var a=0,o=t;a<o.length;a++)i=o[a],delete this.listeners[i];return this.logger.debug(`Listener for path(s) '${t.join(`', '`)}' unregistered`),!0},e.prototype.onTrouterConnected=function(e,t){this.logger.debug(`Trouter is now connected`);for(var n=0,r=Object.keys(this.listeners);n<r.length;n++){var i=r[n];try{this.listeners[i].onTrouterConnected(t.baseEndpointUrl+i,t)}catch(e){this.logger.error(`Listener '${i}' threw an exception from onTrouterConnected(): ${e}`)}}this.connectionInfo=t,this.trouterUrlPromise.resolveUrl(e),this.notifyStateChanged(s.TrouterState.Connected,{url:e,getRemainingTtlInSec:function(){return t.connectionTtlSec}})},e.prototype.onTrouterDisconnected=function(){this.logger.debug(`Trouter is now disconnected`),this.connectionInfo=null;for(var e=0,t=Object.keys(this.listeners);e<t.length;e++){var n=t[e],r=this.listeners[n];if(r.onTrouterDisconnected)try{r.onTrouterDisconnected()}catch(e){this.logger.error(`Listener '${n}' threw an exception from onTrouterDisconnected(): ${e}`)}}this.notifyStateChanged(s.TrouterState.Disconnected)},e.prototype.onTrouterRequest=function(e,t){for(var n=``,r=0,i=Object.keys(this.listeners);r<i.length;r++){var a=i[r];e.path.startsWith(a)&&a.length>n.length&&(n=a)}if(n===``)this.tryMessageHandlers(e,t)||(t.status=404,t.headers={"Trouter-Responder":`ClientLib`},t.send());else try{this.listeners[n].onTrouterRequest(e,t)}catch(e){this.logger.error(`Listener '${n}' threw an exception from onTrouterRequest(): ${e}`),t.status=500,t.headers={"Trouter-Responder":`ClientLib`},t.send()}},e.prototype.onTrouterMessageLoss=function(e){this.logger.info(`onTrouterMessageLoss called with tags [${e}]`);for(var t=!0,n=0,r=Object.keys(this.listeners);n<r.length;n++){var i=r[n],a=this.listeners[i];if(a.onTrouterMessageLoss)try{(t=a.onTrouterMessageLoss(e)&&t)===void 0&&(this.logger.error(`Listener '${i}' did not return a boolean value from onTrouterMessageLoss()`),t=!1)}catch(e){this.logger.error(`Listener '${i}' threw an exception from onTrouterMessageLoss(): ${e}`),t=!1}}return t},e.prototype.onTrouterUserActivityStateAccepted=function(e){this.logger.debug(`onTrouterUserActivityStateAccepted cv: ${e}`);for(var t=0,n=Object.keys(this.listeners);t<n.length;t++){var r=n[t],i=this.listeners[r];if(i.onTrouterUserActivityStateAccepted)try{i.onTrouterUserActivityStateAccepted(e)}catch(e){this.logger.error(`Listener '${r}' threw an exception from onTrouterUserActivityStateAccepted(): ${e}`)}}},e.prototype.onAudiencesSetResolved=function(e,t){this.logger.debug(`onAudiencesSetResolved cv: ${t}`);for(var n=0,r=Object.keys(this.listeners);n<r.length;n++){var i=r[n],a=this.listeners[i];if(a.onAudiencesSetResolved)try{a.onAudiencesSetResolved(e,t)}catch(e){this.logger.error(`Listener '${i}' threw an exception from onAudienceSubscribed(): ${e}`)}}},e.prototype.setUserActivityState=function(e,t){if(e!==s.UserActivityState.Active&&e!==s.UserActivityState.Inactive)throw Error(`setUserActivityState called with unsupported value ${e}`);this.logger.info(`setUserActivityState called with value ${s.UserActivityState[e]}`),this.trouterServer&&this.state()!==s.TrouterState.Unknown?this.trouterServer.setUserActivityState(e,t):(this.pendingActivityState=[e,t],this.logger.warn(`setUserActivityState called before start() or after stop()`))},e.prototype.setAudienceSubscriptions=function(e,t){if(this.trouterServer&&this.state()!==s.TrouterState.Unknown)return this.trouterServer.setAudienceSubscriptionsAsync(e,15e3,t);throw Error(`audience subscribe called before start() or after stop()`)},e.prototype.state=function(){return this.trouterServer===void 0?s.TrouterState.Unknown:this.trouterServer.getState()},e.prototype.isInTerminalState=function(){return this.trouterServer!==void 0&&this.trouterServer.isInTerminalState()},e.prototype.reportStateInfo=function(){return this.trouterServer===void 0?``:this.trouterServer.reportStateInfo()},e.prototype.getServerState=function(){if(this.trouterServer!==void 0)return this.trouterServer.getServerState()},e.prototype.getTrouterUrlAsync=function(){return this.trouterServer===void 0?Promise.reject(Error(`TrouterService has not been started`)):this.trouterUrlPromise.getPromise()},e.prototype.onStateChanged=function(e){if(this.logger.info(`onStateChanged called`),e===void 0)this.stateChangedListeners=this.stateChangedListeners.filter((function(e){return e.wrappedCallback===void 0}));else{this.offStateChanged(e);var t=function(t,n){e(t,n?n.url:``)};t.wrappedCallback=e,this.stateChangedListeners.push(t)}},e.prototype.offStateChanged=function(e){this.logger.info(`offStateChanged called`);var t=this.stateChangedListeners.length;return this.stateChangedListeners=this.stateChangedListeners.filter((function(t){return t.wrappedCallback!==e})),t>this.stateChangedListeners.length},e.prototype.addCallback=function(e){this.logger.info(`addListener called`),this.stateChangedListeners.indexOf(e,0)===-1&&e!==void 0&&this.stateChangedListeners.push(e)},e.prototype.removeCallback=function(e){this.logger.info(`removeListener called`);var t=this.stateChangedListeners.indexOf(e,0);return t>-1&&(this.stateChangedListeners.splice(t,1),!0)},e.prototype.registerMessageHandler=function(e){this.logger.info(`registerMessageHandler is called`),this.messageHandlers.register(e)},e.prototype.clearMessageHandlers=function(){this.logger.info(`clearMessageHandlers is called`),this.messageHandlers.clear()},e.prototype.notifyStateChanged=function(e,t){var n=this;this.logger.info(`notifyStateChanged called, will forward to ${this.stateChangedListeners.length} listeners`),this.stateChangedListeners.forEach((function(r){try{r(e,t)}catch(e){n.logger.error(`Error in callback ${e}`)}}))},e.prototype.tryMessageHandlers=function(e,t){if(!this.messageHandlers.active())return!1;var n,r=null;try{r=(n=JSON.parse(e.body))&&(n.evt||n.eventId)||null}catch{}var i={eventId:r,url:(this.connectionInfo?this.connectionInfo.baseEndpointUrl:``)+e.path,body:n,rawBody:e.body,headers:e.headers},a=this.messageHandlers.handleMessage(i);return!!a.isHandled&&(t.status=a.resultCode,a.responseHeaders&&(t.headers=a.responseHeaders),a.responseBody&&(t.body=a.responseBody),t.send(),!0)},e}();t.TrouterService=h},902:function(e,t){var n=this&&this.__assign||function(){return n=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},n.apply(this,arguments)};Object.defineProperty(t,"__esModule",{value:!0}),t.safeToString=function(e){return typeof e==`string`?e:typeof e==`number`?e.toString():void 0},t.usedProtocolAfterFallback=function(e,t){return t?.kind===`v4c-websocket-failure`?`v4a`:e},t.isV4ConnectEvent=function(e){return Object.prototype.hasOwnProperty.call(e,`connectparams`)},t.adaptUrl=function(e,t){return t===`v4a`?e.replace(/\/v4\/c\b/,`/v4/a`).replace(`wss://`,`https://`).replace(`ws://`,`http://`):e.replace(/\/v4\/a\b/,`/v4/c`).replace(`https://`,`wss://`).replace(`http://`,`ws://`)},t.reconnectParamsWithoutUrls=function(e){if(e!==void 0)return n(n({},e),{reconnectUrl:void 0,serviceUrl:void 0})},t.ensureNumber=function(e){return typeof e==`string`?parseInt(e,10):e},t.redirectUrlIfPresent=function(e){if(e?.kind===`redirect`&&e.host!==void 0){var t=e.host;return t.endsWith(`/`)&&(t=t.substring(0,t.length-1)),t.endsWith(`/v4/c`)||t.endsWith(`/v4/a`)||(t+=`/v4/c`),t}}},983:(e,t,n)=>{(function(e,t){var n=e;n.version=`0.9.6`,n.protocol=1,n.transports=[],n.j=[],n.sockets={},n.connect=function(e,r){var i,a,o=n.util.parseUri(e);t&&t.location&&(o.protocol=o.protocol||t.location.protocol.slice(0,-1),o.host=o.host||(t.document?t.document.domain:t.location.hostname),o.port=o.port||t.location.port),i=n.util.uniqueUri(o);var s={host:o.host,secure:o.protocol==`https`,port:o.port||(o.protocol==`https`?443:80),query:o.query||``};return n.util.merge(s,r),!s[`force new connection`]&&n.sockets[i]||(a=new n.Socket(s)),!s[`force new connection`]&&a&&(n.sockets[i]=a),a||=n.sockets[i],s[`skipped handshake data`]?a.of(``):a.of(o.path.length>1?o.path:``)}})((e=n.nmd(e)).exports,OG===void 0?window:OG);var r=e.exports;(function(e,t){var n=e.util={},r=/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,i=[`source`,`protocol`,`authority`,`userInfo`,`user`,`password`,`host`,`port`,`relative`,`path`,`directory`,`file`,`query`,`anchor`];n.parseUri=function(e){for(var t=r.exec(e||``),n={},a=14;a--;)n[i[a]]=t[a]||``;return n},n.uniqueUri=function(e){var n=e.protocol,r=e.host,i=e.port;return`document`in t?(r||=document.domain,i||=n==`https`&&document.location.protocol!==`https:`?443:document.location.port):(r||=`localhost`,i||n!=`https`||(i=443)),(n||`http`)+`://`+r+`:`+(i||80)},n.query=function(e,t){var r=n.chunkQuery(e||``),i=[];for(var a in n.merge(r,n.chunkQuery(t||``)),r)r.hasOwnProperty(a)&&i.push(a+`=`+r[a]);return i.length?`?`+i.join(`&`):``},n.chunkQuery=function(e){for(var t,n={},r=e.split(`&`),i=0,a=r.length;i<a;++i)(t=r[i].split(`=`))[0]&&(n[t[0]]=t[1]);return n};var a=!1;n.load=function(e){if(`document`in t&&document.readyState===`complete`||a)return e();n.on(t,`load`,e,!1)},n.on=function(e,t,n,r){e.attachEvent?e.attachEvent(`on`+t,n):e.addEventListener&&e.addEventListener(t,n,r)},n.request=function(e){if(e&&typeof XDomainRequest<`u`)return new XDomainRequest;if(typeof XMLHttpRequest<`u`&&(!e||n.ua.hasCORS))return new XMLHttpRequest;if(!e)try{return new window[[`Active`,`Object`].join(`X`)](`Microsoft.XMLHTTP`)}catch{}return null},typeof window<`u`&&n.load((function(){a=!0})),n.defer=function(e){if(!n.ua.webkit||typeof importScripts<`u`)return e();n.load((function(){setTimeout(e,100)}))},n.merge=function(e,t,r,i){var a,o=i||[],s=r===void 0?2:r;for(a in t)t.hasOwnProperty(a)&&n.indexOf(o,a)<0&&(typeof e[a]==`object`&&s?n.merge(e[a],t[a],s-1,o):(e[a]=t[a],o.push(t[a])));return e},n.mixin=function(e,t){n.merge(e.prototype,t.prototype)},n.inherit=function(e,t){function n(){}n.prototype=t.prototype,e.prototype=new n},n.isArray=Array.isArray||function(e){return Object.prototype.toString.call(e)===`[object Array]`},n.intersect=function(e,t){for(var r=[],i=e.length>t.length?e:t,a=e.length>t.length?t:e,o=0,s=a.length;o<s;o++)~n.indexOf(i,a[o])&&r.push(a[o]);return r},n.indexOf=function(e,t,n){var r=e.length;for(n=n<0?n+r<0?0:n+r:n||0;n<r&&e[n]!==t;n++);return r<=n?-1:n},n.toArray=function(e){for(var t=[],n=0,r=e.length;n<r;n++)t.push(e[n]);return t},n.ua={},n.ua.hasCORS=typeof XMLHttpRequest<`u`&&function(){try{var e=new XMLHttpRequest}catch{return!1}return e.withCredentials!=null}(),n.ua.webkit=typeof navigator<`u`&&/webkit/i.test(navigator.userAgent)})(r===void 0?e.exports:r,OG===void 0?window:OG),function(e,t){function n(){}e.EventEmitter=n,n.prototype.on=function(e,n){return this.$events||={},this.$events[e]?t.util.isArray(this.$events[e])?this.$events[e].push(n):this.$events[e]=[this.$events[e],n]:this.$events[e]=n,this},n.prototype.addListener=n.prototype.on,n.prototype.once=function(e,t){var n=this;function r(){n.removeListener(e,r),t.apply(this,arguments)}return r.listener=t,this.on(e,r),this},n.prototype.removeListener=function(e,n){if(this.$events&&this.$events[e]){var r=this.$events[e];if(t.util.isArray(r)){for(var i=-1,a=0,o=r.length;a<o;a++)if(r[a]===n||r[a].listener&&r[a].listener===n){i=a;break}if(i<0)return this;r.splice(i,1),r.length||delete this.$events[e]}else (r===n||r.listener&&r.listener===n)&&delete this.$events[e]}return this},n.prototype.removeAllListeners=function(e){return this.$events&&this.$events[e]&&(this.$events[e]=null),this},n.prototype.listeners=function(e){return this.$events||={},this.$events[e]||(this.$events[e]=[]),t.util.isArray(this.$events[e])||(this.$events[e]=[this.$events[e]]),this.$events[e]},n.prototype.emit=function(e){if(!this.$events)return!1;var n=this.$events[e];if(!n)return!1;var r=Array.prototype.slice.call(arguments,1);if(typeof n==`function`)n.apply(this,r);else{if(!t.util.isArray(n))return!1;for(var i=n.slice(),a=0,o=i.length;a<o;a++)i[a].apply(this,r)}return!0}}(r===void 0?e.exports:r,r===void 0?e.parent.exports:r),function(e,t){if(t&&t.parse)return e.JSON={parse:t.parse,stringify:t.stringify};throw Error(`JSON not available`)}(r===void 0?e.exports:r,typeof JSON<`u`?JSON:void 0),function(e,t){var n=e.parser={},r=n.packets=[`disconnect`,`connect`,`heartbeat`,`message`,`json`,`event`,`ack`,`error`,`noop`],i=n.reasons=[`transport not supported`,`client not handshaken`,`unauthorized`],a=n.advice=[`reconnect`],o=t.JSON,s=t.util.indexOf;n.encodePacket=function(e){var t=s(r,e.type),n=e.id||``,c=e.endpoint||``,l=e.ack,u=null;switch(e.type){case`error`:var d=e.reason?s(i,e.reason):``,f=e.advice?s(a,e.advice):``;d===``&&f===``||(u=d+(f===``?``:`+`+f));break;case`message`:e.data!==``&&(u=e.data);break;case`event`:var p={name:e.name};e.args&&e.args.length&&(p.args=e.args),u=o.stringify(p);break;case`json`:u=o.stringify(e.data);break;case`connect`:e.qs&&(u=e.qs);break;case`ack`:u=e.ackId+(e.args&&e.args.length?`+`+o.stringify(e.args):``)}var m=[t,n+(l==`data`?`+`:``),c];return u!=null&&m.push(u),m.join(`:`)},n.encodePayload=function(e){var t=``;if(e.length==1)return e[0];for(var n=0,r=e.length;n<r;n++)t+=`�`+e[n].length+`�`+e[n];return t};var c=/([^:]+):([0-9]+)?(\+)?:([^:]+)?:?([\s\S]*)?/;n.decodePacket=function(e){if(!(s=e.match(c)))return{};var t=s[2]||``,n=(e=s[5]||``,{type:r[s[1]],endpoint:s[4]||``});switch(t&&(n.id=t,s[3]?n.ack=`data`:n.ack=!0),n.type){case`error`:var s=e.split(`+`);n.reason=i[s[0]]||``,n.advice=a[s[1]]||``;break;case`message`:n.data=e||``;break;case`event`:try{var l=o.parse(e);n.name=l.name,n.args=l.args}catch{}n.args=n.args||[];break;case`json`:try{n.data=o.parse(e)}catch{}break;case`connect`:n.qs=e||``;break;case`ack`:if((s=e.match(/^([0-9]+)(\+)?(.*)/))&&(n.ackId=s[1],n.args=[],s[3]))try{n.args=s[3]?o.parse(s[3]):[]}catch{}break;case`disconnect`:n.reason=e}return n},n.decodePayload=function(e){if(e.charAt(0)==`�`){for(var t=[],r=1,i=``;r<e.length;r++)e.charAt(r)==`�`?(t.push(n.decodePacket(e.substr(r+1).substr(0,i))),r+=Number(i)+1,i=``):i+=e.charAt(r);return t}return[n.decodePacket(e)]}}(r===void 0?e.exports:r,r===void 0?e.parent.exports:r),function(e,t){function n(e,t){this.socket=e,this.sessid=t,this.connectErrorCallback=void 0,this.isOpened=!1}e.Transport=n,t.util.mixin(n,t.EventEmitter),n.prototype.onData=function(e){if(this.clearCloseTimeout(),(this.socket.connected||this.socket.connecting||this.socket.reconnecting)&&this.setCloseTimeout(),e!==``){var n=t.parser.decodePayload(e);if(n&&n.length)for(var r=0,i=n.length;r<i;r++)this.onPacket(n[r])}return this},n.prototype.onPacket=function(e){return this.socket.setHeartbeatTimeout(),e.type==`heartbeat`?this.onHeartbeat():(e.type==`connect`&&e.endpoint==``&&this.onConnect(),e.type==`error`&&e.advice==`reconnect`&&(this.isOpened=!1),this.socket.onPacket(e),this)},n.prototype.setCloseTimeout=function(){if(!this.closeTimeout){var e=this;this.closeTimeout=setTimeout((function(){e.onDisconnect()}),this.socket.closeTimeout)}},n.prototype.onDisconnect=function(){return this.close&&this.isOpened&&this.close(),this.clearTimeouts(),this.socket.onDisconnect(),this},n.prototype.onConnect=function(){return this.socket.onConnect(),this.connectErrorCallback=void 0,this},n.prototype.clearCloseTimeout=function(){this.closeTimeout&&=(clearTimeout(this.closeTimeout),null)},n.prototype.clearTimeouts=function(){this.clearCloseTimeout(),this.reopenTimeout&&clearTimeout(this.reopenTimeout)},n.prototype.packet=function(e){this.send(t.parser.encodePacket(e))},n.prototype.onHeartbeat=function(e){this.packet({type:`heartbeat`})},n.prototype.onOpen=function(){this.isOpened=!0,this.clearCloseTimeout(),this.socket.onOpen()},n.prototype.onClose=function(){this.isOpened=!1,this.socket.onClose(),this.onDisconnect()},n.prototype.prepareUrl=function(e){var n=this.socket.options;if(n[`skipped handshake data`])return n.rewriteUrlForProxy(n[`skipped handshake data`].websocketUrl+(e||``));var r=this.scheme()+`://`+n.host+`:`+n.port+`/`+n.resource+`/`+t.protocol+`/`+this.name+`/`+this.sessid+(e||``);return n.rewriteUrlForProxy(r)},n.prototype.ready=function(e,t){t.call(this)},n.prototype.clearEventHandlers=function(){return this}}(r===void 0?e.exports:r,r===void 0?e.parent.exports:r),function(e,t,n){function r(e){if(this.options={port:80,secure:!1,document:`document`in n&&document,resource:`socket.io`,transports:t.transports.slice(),"connect timeout":1e4,"try multiple transports":!0,reconnect:!0,"reconnection delay":500,"reconnection limit":1/0,"reopen delay":3e3,"max reconnection attempts":10,"sync disconnect on unload":!0,"auto connect":!0,"flash policy port":10843},t.util.merge(this.options,e),this.connected=!1,this.open=!1,this.connecting=!1,this.reconnecting=!1,this.namespaces={},this.buffer=[],this.doBuffer=!1,this.disconnected=!1,this.options[`sync disconnect on unload`]&&(!this.isXDomain()||t.util.ua.hasCORS)){var r=this;t.util.on(n,`unload`,(function(){r.disconnectSync()}),!1)}this.options[`auto connect`]&&this.connect()}function i(){}e.Socket=r,t.util.mixin(r,t.EventEmitter),r.prototype.of=function(e){return this.namespaces[e]||(this.namespaces[e]=new t.SocketNamespace(this,e),e!==``&&this.namespaces[e].packet({type:`connect`})),this.namespaces[e]},r.prototype.publish=function(){var e;for(var t in this.emit.apply(this,arguments),this.namespaces)this.namespaces.hasOwnProperty(t)&&(e=this.of(t)).$emit.apply(e,arguments)},r.prototype.handshake=function(e){var n=this,r=this.options;if(!n.disconnected){var a=r.rewriteUrlForProxy([`http`+(r.secure?`s`:``)+`:/`,r.host+`:`+r.port,r.resource,t.protocol,t.util.query(this.options.query,`t=`+ +new Date)].join(`/`));if(this.isXDomain()&&!t.util.ua.hasCORS){var o=document.getElementsByTagName(`script`)[0],s=document.createElement(`script`);s.src=a+`&jsonp=`+t.j.length,o.parentNode.insertBefore(s,o),t.j.push((function(e){u(e),s.parentNode.removeChild(s)}))}else{var c=t.util.request();c.open(`GET`,a,!0);var l=this.options.requestHeaders;l!==void 0&&Object.keys(l).forEach((function(e){c.setRequestHeader(e,l[e])})),c.onreadystatechange=function(){c.readyState==4&&(c.onreadystatechange=i,c.status==200?u(c.responseText):!n.reconnecting&&n.onError(c.responseText))},c.send(null)}}function u(t){t instanceof Error?n.onError(t.message):e.apply(null,t.split(`:`))}},r.prototype.getTransport=function(e){for(var n,r=e||this.transports,i=0;n=r[i];i++)if(t.Transport[n]&&t.Transport[n].check(this)&&(!this.isXDomain()||t.Transport[n].xdomainCheck()))return new t.Transport[n](this,this.sessionid);return null},r.prototype.connect=function(e){if(this.connecting||this.disconnected)return this;var n=this,r=function(r,i,a,o){function s(){if(!n.connected&&!n.disconnected)if(n.connecting=!1,clearTimeout(n.connectTimeoutTimer),n.options[`try multiple transports`]){for(;n.remainingTransports.length>0&&n.remainingTransports.splice(0,1)[0]!=n.transport.name;);n.remainingTransports.length?c(n.remainingTransports):n.publish(`connect_failed`)}else n.publish(`connect_failed`)}function c(e){if(n.transport&&(n.transport.clearTimeouts(),n.transport.clearEventHandlers()),n.transport=n.getTransport(e),!n.transport||n.disconnected)return n.publish(`connect_failed`);n.transport.ready(n,(function(){n.connecting=!0,n.publish(`connecting`,n.transport.name),n.transport.open(s),n.options[`connect timeout`]&&(n.connectTimeoutTimer=setTimeout((function(){s()}),n.options[`connect timeout`]))}))}n.sessionid=r,n.closeTimeout=1e3*a+2e3,n.heartbeatTimeout=1e3*i+2e3,n.transports=o?t.util.intersect(o.split(`,`),n.options.transports):n.options.transports,n.setHeartbeatTimeout(),n.remainingTransports=n.transports.slice(0),c(n.transports),n.once(`connect`,(function(){clearTimeout(n.connectTimeoutTimer),e&&typeof e==`function`&&e()}))};if(this.options[`skipped handshake data`]){var i=this.options[`skipped handshake data`];r(`v4c-`+new Date().getTime(),i.timeout,i.timeout,`websocket`)}else this.handshake(r);return this},r.prototype.setHeartbeatTimeout=function(){clearTimeout(this.heartbeatTimeoutTimer);var e=this;this.heartbeatTimeoutTimer=setTimeout((function(){e.transport.onClose()}),this.heartbeatTimeout)},r.prototype.packet=function(e){return this.connected&&!this.doBuffer?this.transport.packet(e):this.buffer.push(e),this},r.prototype.setBuffer=function(e){this.doBuffer=e,!e&&this.connected&&this.buffer.length&&(this.transport.payload(this.buffer),this.buffer=[])},r.prototype.disconnect=function(){return(this.connected||this.connecting)&&(this.open&&this.of(``).packet({type:`disconnect`}),this.onDisconnect(`booted`)),this.disconnected=!0,this},r.prototype.disconnectSync=function(){var e=t.util.request(),n=this.resource+`/`+t.protocol+`/`+this.sessionid;e.open(`GET`,n,!0),this.onDisconnect(`booted`)},r.prototype.isXDomain=function(){var e=n.location.port||(n.location.protocol==`https:`?443:80);return this.options.host!==n.location.hostname||this.options.port!=e},r.prototype.onConnect=function(){this.connected||(this.connected=!0,this.connecting=!1,this.doBuffer||this.setBuffer(!1),this.emit(`connect`))},r.prototype.onOpen=function(){this.open=!0},r.prototype.onClose=function(){this.open=!1,clearTimeout(this.heartbeatTimeoutTimer)},r.prototype.onPacket=function(e){this.of(e.endpoint).onPacket(e)},r.prototype.onError=function(e){e&&e.advice&&e.advice===`reconnect`&&(this.connected||this.connecting)&&(this.disconnect(),this.options.reconnect&&this.reconnect()),this.publish(`error`,e&&e.reason?e.reason:e)},r.prototype.onDisconnect=function(e){var t=this.connected,n=this.connecting;this.connected=!1,this.connecting=!1,this.open=!1,(t||n)&&(this.transport.close(),this.transport.clearTimeouts(),t?(this.publish(`disconnect`,e),e!=`booted`&&this.options.reconnect&&!this.reconnecting&&this.reconnect()):this.publish(`close_during_connecting`,e))},r.prototype.reconnect=function(){this.reconnecting=!0,this.reconnectionAttempts=0,this.reconnectionDelay=this.options[`reconnection delay`];var e=this,t=this.options[`max reconnection attempts`],n=this.options[`try multiple transports`],r=this.options[`reconnection limit`];function i(){if(e.connected){for(var t in e.namespaces)e.namespaces.hasOwnProperty(t)&&t!==``&&e.namespaces[t].packet({type:`connect`});e.publish(`reconnect`,e.transport.name,e.reconnectionAttempts)}clearTimeout(e.reconnectionTimer),e.removeListener(`connect_failed`,a),e.removeListener(`connect`,a),e.reconnecting=!1,delete e.reconnectionAttempts,delete e.reconnectionDelay,delete e.reconnectionTimer,delete e.redoTransports,e.options[`try multiple transports`]=n}function a(){if(e.reconnecting)return e.connected?i():e.connecting&&e.reconnecting?e.reconnectionTimer=setTimeout(a,1e3):void(e.reconnectionAttempts++>=t?e.redoTransports?(e.publish(`reconnect_failed`),i()):(e.on(`connect_failed`,a),e.options[`try multiple transports`]=!0,e.transport=e.getTransport(),e.redoTransports=!0,e.connect()):(e.reconnectionDelay<r&&(e.reconnectionDelay*=2),e.connect(),e.publish(`reconnecting`,e.reconnectionDelay,e.reconnectionAttempts),e.reconnectionTimer=setTimeout(a,e.reconnectionDelay)))}this.options[`try multiple transports`]=!1,this.reconnectionTimer=setTimeout(a,this.reconnectionDelay),this.on(`connect`,a)}}(r===void 0?e.exports:r,r===void 0?e.parent.exports:r,OG===void 0?window:OG),function(e,t){function n(e,t){this.socket=e,this.name=t||``,this.flags={},this.json=new r(this,`json`),this.ackPackets=0,this.acks={}}function r(e,t){this.namespace=e,this.name=t}e.SocketNamespace=n,t.util.mixin(n,t.EventEmitter),n.prototype.$emit=t.EventEmitter.prototype.emit,n.prototype.of=function(){return this.socket.of.apply(this.socket,arguments)},n.prototype.packet=function(e){return e.endpoint=this.name,this.socket.packet(e),this.flags={},this},n.prototype.send=function(e,t){var n={type:this.flags.json?`json`:`message`,data:e};return typeof t==`function`&&(n.id=++this.ackPackets,n.ack=!0,this.acks[n.id]=t),this.packet(n)},n.prototype.emit=function(e){var t=Array.prototype.slice.call(arguments,1),n=t[t.length-1],r={type:`event`,name:e};return typeof n==`function`&&(r.id=++this.ackPackets,r.ack=`data`,this.acks[r.id]=n,t=t.slice(0,t.length-1)),r.args=t,this.packet(r)},n.prototype.disconnect=function(){return this.name===``?this.socket.disconnect():(this.packet({type:`disconnect`}),this.$emit(`disconnect`)),this},n.prototype.onPacket=function(e){var n=this;function r(){n.packet({type:`ack`,args:t.util.toArray(arguments),ackId:e.id})}switch(e.type){case`connect`:this.$emit(`connect`);break;case`disconnect`:this.name===``?this.socket.onDisconnect(e.reason||`booted`):this.$emit(`disconnect`,e.reason||``);break;case`message`:case`json`:var i=[`message`,e.data];e.ack==`data`?i.push(r):e.ack&&this.packet({type:`ack`,ackId:e.id}),this.$emit.apply(this,i);break;case`event`:i=[e.name].concat(e.args),e.ack==`data`&&i.push(r),this.$emit.apply(this,i);break;case`ack`:this.acks[e.ackId]&&(this.acks[e.ackId].apply(this,e.args),delete this.acks[e.ackId]);break;case`error`:e.advice?this.socket.onError(e):e.reason==`unauthorized`?this.$emit(`connect_failed`,e.reason):this.$emit(`error`,e.reason)}},r.prototype.send=function(){this.namespace.flags[this.name]=!0,this.namespace.send.apply(this.namespace,arguments)},r.prototype.emit=function(){this.namespace.flags[this.name]=!0,this.namespace.emit.apply(this.namespace,arguments)}}(r===void 0?e.exports:r,r===void 0?e.parent.exports:r),function(e,t,n){function r(e){t.Transport.apply(this,arguments)}function i(){}e.websocket=r,t.util.inherit(r,t.Transport),r.prototype.name=`websocket`,r.prototype.open=function(e){var r,i=t.util.query(this.socket.options.query),a=this;return this.connectErrorCallback=e,r||=n.MozWebSocket||n.WebSocket,this.websocket=new r(this.prepareUrl(i)),this.websocket.onopen=function(){a.onOpen(),a.socket.setBuffer(!1)},this.websocket.onmessage=function(e){a.onData(e.data)},this.websocket.onclose=function(){a.onClose(),a.socket.setBuffer(!0)},this.websocket.onerror=function(e){a.onError(e)},this},r.prototype.send=function(e){return this.websocket.send(e),this},r.prototype.payload=function(e){for(var t=0,n=e.length;t<n;t++)this.packet(e[t]);return this},r.prototype.close=function(){return this.websocket.close(),this},r.prototype.onError=function(e){this.connectErrorCallback!==void 0&&(this.connectErrorCallback(),this.connectErrorCallback=void 0),this.socket.onError(e)},r.prototype.scheme=function(){return this.socket.options.secure?`wss`:`ws`},r.check=function(){return`WebSocket`in n&&!(`__addTask`in WebSocket)||`MozWebSocket`in n},r.xdomainCheck=function(){return!0},r.prototype.clearEventHandlers=function(){return this.websocket&&(this.websocket.onopen=this.websocket.onmessage=this.websocket.onclose=this.websocket.onerror=i),this},t.transports.push(`websocket`)}(r===void 0?e.exports:r.Transport,r===void 0?e.parent.exports:r,OG===void 0?window:OG),function(e,t,n){function r(e){e&&t.Transport.apply(this,arguments)}function i(){}e.XHR=r,t.util.inherit(r,t.Transport),r.prototype.open=function(){return this.socket.setBuffer(!1),this.onOpen(),this.get(),this.setCloseTimeout(),this},r.prototype.payload=function(e){for(var n=[],r=0,i=e.length;r<i;r++)n.push(t.parser.encodePacket(e[r]));this.send(t.parser.encodePayload(n))},r.prototype.send=function(e){return this.post(e),this},r.prototype.post=function(e){var t=this;this.socket.setBuffer(!0),this.sendXHR=this.request(`POST`),n.XDomainRequest&&this.sendXHR instanceof XDomainRequest?this.sendXHR.onload=this.sendXHR.onerror=function(){this.onload=i,t.socket.setBuffer(!1)}:this.sendXHR.onreadystatechange=function(){this.readyState==4&&(this.onreadystatechange=i,this.status==200?(clearTimeout(this.ackTimeoutTimer),t.socket.setBuffer(!1)):t.onClose())},this.sendXHR.send(e),t.sendXHR.ackTimeoutTimer=setTimeout((function(){t.onClose()}),t.socket.options.ackTimeoutMs)},r.prototype.close=function(){return this.onClose(),this},r.prototype.request=function(e){var n=t.util.request(this.socket.isXDomain()),r=t.util.query(this.socket.options.query,`t=`+ +new Date);n.open(e||`GET`,this.prepareUrl(r),!0);var i=this.socket.options.requestHeaders;if(i!==void 0&&Object.keys(i).forEach((function(e){n.setRequestHeader(e,i[e])})),e==`POST`)try{n.setRequestHeader?n.setRequestHeader(`Content-type`,`text/plain;charset=UTF-8`):n.contentType=`text/plain`}catch{}return n},r.prototype.scheme=function(){return this.socket.options.secure?`https`:`http`},r.check=function(e,r){try{var i=t.util.request(r),a=n.XDomainRequest&&i instanceof XDomainRequest,o=(e&&e.options&&e.options.secure?`https:`:`http:`)!=n.location.protocol;if(i&&(!a||!o))return!0}catch{}return!1},r.xdomainCheck=function(){return r.check(null,!0)},r.prototype.clearEventHandlers=function(){return this.sendXHR&&(this.sendXHR.onreadystatechange=this.sendXHR.onload=i),this}}(r===void 0?e.exports:r.Transport,r===void 0?e.parent.exports:r,OG===void 0?window:OG),function(e,t,n){function r(){t.Transport.XHR.apply(this,arguments)}function i(){}e[`xhr-polling`]=r,t.util.inherit(r,t.Transport.XHR),t.util.merge(r,t.Transport.XHR),r.prototype.name=`xhr-polling`,r.prototype.open=function(e){return this.connectErrorCallback=e,t.Transport.XHR.prototype.open.call(this),!1},r.prototype.get=function(){if(this.isOpened){var e=this;this.xhr=this.request(),n.XDomainRequest&&this.xhr instanceof XDomainRequest?(this.xhr.onload=function(){e.connectErrorCallback=void 0,this.onload=i,this.onerror=i,e.onData(this.responseText),e.get()},this.xhr.onerror=function(){e.onClose(),e.connectErrorCallback!==void 0&&(e.connectErrorCallback(),e.connectErrorCallback=void 0)}):this.xhr.onreadystatechange=function(){this.readyState==4&&(this.onreadystatechange=i,this.status==200?(e.connectErrorCallback=void 0,e.onData(this.responseText),e.get()):(e.onClose(),e.connectErrorCallback!==void 0&&(e.connectErrorCallback(),e.connectErrorCallback=void 0)))},this.xhr.send(null)}},r.prototype.onClose=function(){if(t.Transport.XHR.prototype.onClose.call(this),this.xhr){this.xhr.onreadystatechange=this.xhr.onload=this.xhr.onerror=i;try{this.xhr.abort()}catch{}this.xhr=null}},r.prototype.ready=function(e,n){var r=this;t.util.defer((function(){n.call(r)}))},r.prototype.clearEventHandlers=function(){return t.Transport.XHR.prototype.clearEventHandlers.call(this),this.xhr&&(this.xhr.onreadystatechange=this.xhr.onload=this.xhr.onerror=i),this},t.transports.push(`xhr-polling`)}(r===void 0?e.exports:r.Transport,r===void 0?e.parent.exports:r,OG===void 0?window:OG),t.io=r}},n={};function r(e){var i=n[e];if(i!==void 0)return i.exports;var a=n[e]={id:e,loaded:!1,exports:{}};return t[e].call(a.exports,a,a.exports,r),a.loaded=!0,a.exports}return r.nmd=e=>(e.paths=[],e.children||=[],e),r(882)})(),e.exports=t(vLe())),n9.exports;var e,t}var i9,xLe,a9=bLe(),SLe=class{constructor(e,t){this.logEvent=e=>{this._logger.debug(e),this._telemetryLogManager.sendEvent({name:e.name,tenant:DCe,properties:{...e.properties}})},this._logger=e.createChild(`TelemetrySender`),this._telemetryLogManager=t}};function CLe(e){return{registrationId:K0(),registrarServiceUrl:e.getTrouterSettings().registrarServiceUrl,registrarTtlInSeconds:e.getTrouterSettings().registrarTtlInSeconds,maxRegistrationTimeInMs:e.getTrouterSettings().maxRegistrationTimeInMs,registrarRefreshTimeoutInMs:e.getTrouterSettings().registrarRefreshTimeoutInMs,pnhAppId:e.getTrouterSettings().pnhAppId,pnhTemplate:e.getTrouterSettings().pnhTemplate,platform:e.getTrouterSettings().platform,platformUIVersion:e.getTrouterSettings().version,trouterServiceUrl:e.getTrouterSettings().trouterServiceUrl,version:e.getTrouterSettings().version,trouterConnectTimeoutInMs:e.getTrouterSettings().trouterConnectTimeoutInMs,productName:e.getTrouterSettings().productName,sessionId:K0(),environment:e.getTrouterSettings().environment,timeoutOptions:e.getTrouterSettings().timeoutOptions}}var wLe=class{constructor(e,t,n,r,i){this._ecsProvider=t,this._tokenProvider=n,this._isRegistered=!1,this._registeredChangedListeners=[],this._logger=e.createChild(`Trouter`),this._logger.info(`init`),this._initialRegistrationCompleteDefer=e3(),this._telemetryLogManager=r,this._acsProxy=i}async start(e){let t;if(this._trouterService)throw this._logger.error(`Trouterservice already initialized`),new Y({defaultError:J.CALL_STACK.SIGNALING_SERVICE_ALREADY_INITIALIZED});{let n=new Promise((async(t,n)=>{try{if(this._logger.info(`Trouterservice start`),this._trouterService=a9.createTrouterService(this._logger),!this._trouterService)throw this._logger.error(`Failed to create trouter service`),new Y({defaultError:J.CALL_STACK.SIGNALING_SERVICE_CREATE_FAIL});this._options=this._getTrouterConfig(this._logger,this._tokenProvider),e&&(this._options.trouterSettings.environment=e.environment||``,this._options.trouterSettings.sessionId=e.sessionId);let n,r,i=+new Date;this._trouterService.start(this._options),this._trouterService.onStateChanged(((e,t)=>{e===a9.TrouterState.Connected&&(n=+new Date)})),await this._initialRegistrationCompleteDefer.promise;let a=+new Date;n??=+new Date,r=n,t({trouterRequestCompletionTimeDeltaMs:Math.max(0,n-i),registrarRequestCompletionTimeDeltaMs:Math.max(0,a-r)})}catch(e){n(e)}}));try{t=await n3((()=>n),ZSe)}catch(e){throw e.code===408?(this._logger.error(`Signaling init timeout`),new Y({defaultError:J.CALL_STACK.SIGNALING_SERVICE_CREATE_TIMEOUT,defaultErrorMessageArgs:[ZSe]})):(this._logger.error(`Signaling init failed`),new Y({defaultError:J.CALL_STACK.SIGNALING_INIT_FAIL}))}}return t}isRegistered(){return this._isRegistered}onRegisteredChanged(e){this._logger.info(`TrouterService onRegisteredChanged`),this._registeredChangedListeners.push(e)}offRegisteredChanged(e){let t=this._registeredChangedListeners.indexOf(e);this._logger.info(`TrouterService offRegisteredChanged: ${t}`),t>-1&&this._registeredChangedListeners.splice(t,1)}stop(e){this._logger.info(`Trouterservice stop`),this._trouterService?(this._trouterService.onStateChanged(void 0),this._trouterService.stop(e),this._trouterService=void 0):this._logger.error(`Trouterservice not inited`)}registerMessageHandler(e){this._logger.info(`Trouterservice registerMessageHandler`),this._trouterService&&this._trouterService.registerMessageHandler(e)}clearMessageHandlers(){this._trouterService&&this._trouterService.clearMessageHandlers()}checkConnection(){this._trouterService&&this._trouterService.checkConnection()}state(){return this._logger.info(`Trouterservice state`),this._trouterService?this._trouterService.state():a9.TrouterState.Unknown}onStateChanged(e){this._logger.info(`Trouterservice onStateChanged`),this._trouterService&&this._trouterService.onStateChanged(e)}offStateChanged(e){this._logger.info(`Trouterservice offStateChanged`),this._trouterService&&this._trouterService.offStateChanged(e)}getTrouterUrlAsync(){return this._trouterService?(this._logger.info(`getTrouterUrlAsync called`),this._trouterService.getTrouterUrlAsync()):Promise.reject(`Trouterservice not started yet`)}getTrouterSettings(){return this._options.trouterSettings}_getSettings(){return CLe(this._ecsProvider)}_createTrouterTelemetryConfig(e){return{eventLogger:new SLe(e.createChild(`TrouterTelemetry`),this._telemetryLogManager),settings:{enabled:this._ecsProvider.getTrouterTelemetryConfig().enabled,logHealthCheckError:this._ecsProvider.getTrouterTelemetryConfig().logHealthCheckError,trouter_js_client_connected:this._ecsProvider.getTrouterTelemetryConfig().trouter_js_client_connected,trouter_js_client_disconnected:this._ecsProvider.getTrouterTelemetryConfig().trouter_js_client_disconnected,trouter_js_client_error:this._ecsProvider.getTrouterTelemetryConfig().trouter_js_client_error,trouter_js_client_progress:this._ecsProvider.getTrouterTelemetryConfig().trouter_js_client_progress,trouter_js_client_response:this._ecsProvider.getTrouterTelemetryConfig().trouter_js_client_response,numberOfStepsToMaintain:this._ecsProvider.getTrouterTelemetryConfig().numberOfStepsToMaintain,sendProgressTimeoutSecs:this._ecsProvider.getTrouterTelemetryConfig().sendProgressTimeoutSecs}}}_getTrouterConfig(e,t){return{trouterSettings:this._getSettings(),proxyUrlRewrite:this._acsProxy.hasProxyUrl()?e=>this._acsProxy.proxyfyUrl(e):void 0,skypeTokenProvider:t,telemetryConfig:this._createTrouterTelemetryConfig(e),registrationStateCallbackForAcsDoNotUse:e=>{this._logger.info(`TrouterService registrationStateCallbackForAcs: ${e}`),this._isRegistered=e,this._initialRegistrationCompleteDefer.isPending()&&this._isRegistered?this._initialRegistrationCompleteDefer.resolve():this._isRegistered?this._logger.info(`Signaling service is currently registered`):this._logger.error(`Signaling service is currently not registered. Unable to receive incoming calls`),this._onRegisteredChanged(e)}}}_onRegisteredChanged(e){this._logger.info(`TrouterService onRegisteredChanged: ${e}`),this._registeredChangedListeners.forEach((t=>{t(e)}))}},TLe=class{constructor(e){this._eventToTenantId={skypecosi_concore_web_csa_conversation_httprequest:f2,skypecosi_concore_web_ts_calling_in_call_session:f2,skypecosi_concore_web_ts_calling_call_setup_session:f2,skypecosi_concore_native_ts_calling_in_call_session:f2,skypecosi_concore_native_ts_calling_call_setup_session:f2,skypecosi_concore_web_pluginless_call_session:f2,skypecosi_concore_web_pluginless_modality_session:f2,skypecosi_concore_web_csa_conversation_callmodality:f2,skypecosi_concore_web_ts_calling_registry:f2,mdsc_webrtc_session:p2,mdsc_webrtc_session_initial:p2,live_events:ECe,mdsc_ortc_reports:p2,mdsc_ortc_reports_initial:p2,mdsc_rt_log:p2},this.getTenant=e=>this._eventToTenantId[e]?this._eventToTenantId[e]:``,this.getCallingAdapter=()=>({sendEvent:(e,t)=>{this._telemetryLogManager.sendEvent({tenant:this.getTenant(e),name:e,properties:t})}}),this.getGenericTelemetryLogger=e=>({sendEvent:e=>{this._telemetryLogManager.sendEvent({tenant:this.getTenant(e.eventName),name:e.eventName,properties:e.props})}}),this.getMediaAdapter=()=>({sendEvent:(e,t)=>{this._telemetryLogManager.sendEvent({tenant:this.getTenant(e),name:e,properties:t})}}),this.sendEvents=e=>(e.forEach((e=>{this._telemetryLogManager.sendEvent({tenant:this.getTenant(e.eventName),name:e.eventName,properties:e.props})})),Promise.resolve()),this._telemetryLogManager=e}},ELe=class{constructor(){this._timedVideoEffectProviderPromise=qwe(uue),this._timedModelConfigPromise=qwe(uue)}get videoEffectProviderDeferredPromise(){return this._timedVideoEffectProviderPromise.deferredPromise}get modelConfigDeferredPromise(){return this._timedModelConfigPromise.deferredPromise}async getVideoEffectProvider(){return this._timedVideoEffectProviderPromise.timerStart(),this._timedVideoEffectProviderPromise.deferredPromise.promise}async getModelConfig(){return this._timedModelConfigPromise.deferredPromise.resolve({modelUrl:``,weightPathPrefix:``}),this._timedModelConfigPromise.deferredPromise.promise}},DLe=class{constructor(e){this._encodedStreamsJsPath=e}async getWorkerUrl(){return this._encodedStreamsJsPath}},OLe=class{constructor(e,t){t||typeof e.createChild!=`function`?this.logger=e:this.logger=e.createChild(`HttpRequestDispatcher::`),this.proxy=t}getRequestOptions(e,t,n,r,i){return{headers:t||{},timeout:r,payload:n||null,responseType:i}}getAsync(e,t){return this.send(e,t,F3.GET)}postAsync(e,t){return this.send(e,t,F3.POST)}putAsync(e,t){return this.send(e,t,F3.PUT)}removeAsync(e,t){return this.send(e,t,F3.DELETE)}async send(e,t={headers:{}},n){let r=this.logger.createChild(`[${t.causeId||K0()}] HttpRequestDispatcher::`),i=K0();r.info(`Send, httpRequestId: ${i}, ${n} ${e}`),this.proxy&&(e=this.proxy.proxyfyUrl(e));let a=new AbortController,o=()=>{r.info(`Send, httpRequestId: ${i}, aborting`),a.abort()};r.info(`Send, httpRequestId: ${i}, responseType: ${t.responseType}`),t.headers=t.headers||{};let s=t.headers;s[`Content-Type`]||=t.contentType||`application/json`;let c={method:n,headers:t.headers,credentials:t.withCredentials?`include`:`same-origin`,keepalive:t.keepAlive||!1,signal:a.signal},l=Date.now(),u={url:e,start:new Date(l).toISOString(),end:``,statusCode:0,deltaTimeInMs:0,causeId:``},d=Z().telemetry.apiCauseIdHeader;try{n!==`GET`&&(c.body=t.payload||``);let a=fetch(e,c);if(typeof t.timeout==`number`&&t.timeout>0){let e=setTimeout((()=>o()),t.timeout);a=a.finally((()=>clearTimeout(e)))}bwe(t.timeout)&&t.timeout.then((()=>{o()}),(()=>{r.info(`Send, httpRequestId: ${i}, timeout promise rejected`)}));let s=await a;if(r.info(`Send, httpRequestId: ${i}, \n response status: ${s.status}`),t.headers[d]){let e=t.headers[d].split(`-`)[0];F6.getRemoveCauseIdToNetworkInfo(e)&&this.setCauseIdToNetworkInfo(u,s.status,e)}let f;try{f=await this.extractPayload(s,i,r)}catch(e){r.error(`Send, httpRequestId: ${i}, failed to parse response, error: ${e.message}`)}let p={};return s.headers.forEach(((e,t)=>{p[t]=e})),{response:f,request:{status:s.status,statusText:s.statusText,headers:p,responseURL:s.url,response:f,withCredentials:t.withCredentials},duration:Date.now()-l}}catch(n){if(r.error(`Send, httpRequestId: ${i}, \n failed ${c.method} ${e}, error: ${n.message}`),t.headers[d]){let e=t.headers[d].split(`-`)[0];F6.ifCauseIdExistsRemoveNetworkInfo(e)&&this.setCauseIdToNetworkInfo(u,n.code,e)}throw n.name===`AbortError`?(r.warn(`Send, httpRequestId: ${i}, aborted`),{aborted:!0}):(n.response?r.warn(`Send, httpRequestId: ${i}, \n response: ${n4(n.response)}`):n.request?r.warn(`Send, httpRequestId: ${i}, \n no response, request: ${n4(n.request)}`):r.warn(`Send, httpRequestId: ${i}, \n request not made, error: ${n4(n)}`),n||Error(`HttpRequestId: ${i}, failed`))}}async extractPayload(e,t,n){let r=this.getHeader(e,`content-type`,n),i=this.getHeader(e,`content-length`,n);switch(n.info(`ExtractPayload, httpRequestId: ${t}, \n parsing content type: ${r}, content length: ${i}`),r){case`application/json`:return i?await e.json():{};case`application/text`:return i?await e.text():``;case`application/octet-stream`:return i?await e.blob():new Blob;case`application/arraybuffer`:return i?await e.arrayBuffer():new ArrayBuffer(0);default:return e.json().catch((()=>{throw Error(`HttpRequestId: ${t}, unsupported content type: ${r}`)}))}}getHeader(e,t,n){n.info(`GetHeader, header: ${t}`);let r=e.headers.get(t.toLowerCase()),i;return r!==null&&(i=r),i}setCauseIdToNetworkInfo(e,t,n){e={...e,end:new Date().toISOString(),statusCode:t,deltaTimeInMs:Date.now()-new Date(e.start).getTime(),causeId:n},F6.setCauseIdToNetworkInfo(n,e)}},kLe=class{constructor(){this._activeEffects=[],this.eventEmitter=new w3.EventEmitter}on(e,t){if(e!==`statusChanged`)throw new Y({defaultError:J.FEATURES.VIDEO_EFFECTS.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.on(e,t)}off(e,t){if(e!==`statusChanged`)throw new Y({defaultError:J.FEATURES.VIDEO_EFFECTS.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.off(e,t)}getActiveEffects(){return this._activeEffects}setActiveEffects(e){let t=this._activeEffects;this._activeEffects=e,this.eventEmitter.emit(`statusChanged`,t,this._activeEffects)}},ALe=class{constructor(){this._activeEffects={echoCancellation:[],noiseSuppression:[],autoGainControl:[]},this.eventEmitter=new w3.EventEmitter}on(e,t){if(e!==`statusChanged`)throw new Y({defaultError:J.FEATURES.AUDIO_EFFECTS.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.on(e,t)}off(e,t){if(e!==`statusChanged`)throw new Y({defaultError:J.FEATURES.AUDIO_EFFECTS.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.off(e,t)}getActiveEffects(){return this._activeEffects}setActiveEffects(e,t){let n={...this._activeEffects};this._activeEffects={...e},this.eventEmitter.emit(`statusChanged`,n,this._activeEffects,t)}},jLe=class{constructor(){this._providerValue=null}get providerValue(){return this._providerValue}set providerValue(e){this._providerValue=e}async getAudioEffectProvider(){return this.providerValue}};function MLe(){if(xLe)return i9;xLe=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,i=(i,a,o,s)=>{if(a&&typeof a==`object`||typeof a==`function`)for(let c of n(a))r.call(i,c)||c===o||e(i,c,{get:()=>a[c],enumerable:!(s=t(a,c))||s.enumerable});return i},a=t=>i(e({},`__esModule`,{value:!0}),t),o={};function s(e){return new Promise((t=>setTimeout(t,e)))}((t,n)=>{for(var r in n)e(t,r,{get:n[r],enumerable:!0})})(o,{mmrAdapter:()=>f}),i9=a(o);var c=class{constructor(){this.observers=new Set}subscribe(e){return typeof e==`function`&&(e={next:e}),this.observers.add(e),{unsubscribe:()=>{this.observers.delete(e)}}}},l=class extends c{constructor(e){super(),this.logger=e,this._state=3}get state(){return this._state}handleMessage(e){this.observers.forEach((t=>{t.next?.(e)}))}},u=`config`,d=class extends l{constructor(e,t){super(e),this.config=t,this.waitForChannel()}get tsCallingChannel(){return window.navigator.mediaDevices?.tsCallingChannel}getConfig(){return this.config}next(e){this.tsCallingChannel?this.tsCallingChannel.sendTsCallingMessage(e):this.logger.error(`tsCallingChannel is not available.`)}async waitForChannel(){do this.initializeTsCallingChannel(),await s(500);while(this.state!==1)}initializeTsCallingChannel(){if(!this.tsCallingChannel)return;this._state=1,this.tsCallingChannel.addEventListener(`messagerecv`,(e=>{e.detail?.message&&this.handleMessage(e.detail.message)}));let e=this.createConnectionURL();this.logger.log(`connectionUrl: ${e}`),this.tsCallingChannel.sendTsCallingMessage({WebViewRemotingControlChannel:{url:e.toString()}})}createConnectionURL(){let{loaderUrl:e,...t}=this.config;if(!e)throw this.logger.error(`loaderUrl was not passed in config.`),Error(`loaderUrl was not passed in config.`);try{let n=new URL(e);return n.searchParams.set(u,JSON.stringify(t)),n}catch(e){throw this.logger.error(`Failed to create connection URL`,e),e}}},f=(e,t)=>new d(e,t);return i9}var NLe=MLe();function PLe(){return!!navigator.mediaDevices?.tsCallingChannel}function FLe(e,t){let n=Z().vdi3,r=window.vdi3Debug??{},i=r.cdnUrl??n.cdnUrl;if(!i){let e=n.customTsVersion||H5.stackFactory.getVersion().build;if(e.includes(`_`))throw new Y({defaultError:J.FEATURES.VDI3.INVALID_CDN_URL});i=`${n.cdnBaseUrl}${e}/`}let a=r.connectionUrl??new URL(n.loaderHtmlPath,i).toString(),o=r.pluginlessUrl??new URL(n.pluginlessJsPath,i).toString();return{vdi3Config:{transport:NLe.mmrAdapter(e,{staleTimeout:n.transportConnectionTimeoutInMs,executionTimeout:n.remoteExecutionTimeoutInMs,messageChunkSize:n.chunkSize,writeLogToConsole:r.writeLogToConsole??t?.writeLogToConsole??n.writeLogToConsole,loaderUrl:a}),trouterSettings:{},pluginlessUrl:o,cdnUrl:i}}}var ILe={AcsCallingSDKWeb:{telemetry:{telemetryFlushTimeout:1e4,mediaStatsConfig:{enableVideoLeakInformation:!1,enableRenderCountCheck:!1}},calling:{allowAccessRawMediaStream:!1,deviceSelectionTimeoutInMs:1e4}},SkypeWebMedia:{mediaAgent:{useOneDsLogger:!0}}},LLe=class{constructor(){this._mapping=new WeakMap,this._eventEmitter=new T3,this._isRemoteStackActive=!0}get(e){return this._mapping.get(e)?.deref()}create(e){let t=this._createProxy(e);if(t===void 0)throw Error(`The type is not supported for proxy`);return this._mapping.set(e,new WeakRef(t)),t}replaceProxyToRaw(e){if(typeof e==`object`){if(Array.isArray(e))return e.map((e=>this.replaceProxyToRaw(e)));if(H6 in e)return e[H6]}return e}replaceRawToProxy(e,t){if(t===void 0&&(t=new Map),typeof e==`object`){if(e===null)return e;if(t.has(e))return t.get(e);if(H6 in e)return e;if(Array.isArray(e)){let n=e.map((e=>this.replaceRawToProxy(e,t)));return t.set(e,n),n}if(e instanceof Promise)return e.then((e=>this.replaceRawToProxy(e,t)));if(e instanceof ArrayBuffer||e instanceof Uint8Array||e instanceof Date||e instanceof RegExp)return e;if(this.isSupportedType(e)){let n=this.get(e);return n===void 0&&(n=this.create(e)),t.set(e,n),n}if(HOe(e))return t.set(e,e),e;let n={};t.set(e,n);for(let[r,i]of Object.entries(e))n[r]=this.replaceRawToProxy(i,t);return n[H6]=e,n}return e}on(e,t){this._eventEmitter.on(e,t)}once(e,t){this._eventEmitter.once(e,t)}dispose(){this._eventEmitter.removeAllListeners()}};function o9(e,t,n,r={}){return new Proxy(e,{get:(i,a)=>{let o,s;if(a===H6)return e;if(a in t)o=t[a],s=t;else{if(!(a in e))return;o=e[a],s=e}let c=r[a]??{input:!0,output:!0};if(typeof o==`function`){if(!n.isRemoteStackActive()&&s===e)throw new Y({defaultError:J.FEATURES.VDI3.REMOTE_STACK_TERMINATED});return new Proxy(o,{apply:(e,t,r)=>{let i=r.map((e=>typeof e==`function`?(...t)=>e.apply(null,n.replaceRawToProxy(t)):c.input?n.replaceProxyToRaw(e):e)),a=Reflect.apply(e,s,i);return c.output?n.replaceRawToProxy(a):a}})}return c.output?n.replaceRawToProxy(o):o},has:(n,r)=>r===H6||r in t||r in e})}var s9=class{constructor(e,t){this._proxyReferenceManager=e,this._tsObject=t,this._eventEmitter=new T3,this._handles=new Map,this._skipEvents=[`optimalVideoReceiversCountChanged`]}_proxyCall(e,t){let n=this._tsObject[e];if(n!==void 0)return n.apply(this._tsObject,t)}get instance(){return this._tsObject}changed(e){let t=`changed`,n=this._handles.get(t);n===void 0&&(n=this._proxyCall(`changedAsync`,[(...e)=>{this._eventEmitter.emit(t,...e)}]),this._handles.set(t,n));let r=(...t)=>{e.apply(null,t)};return this._eventEmitter.on(t,r),{dispose:()=>{this._eventEmitter.off(t,r),this._eventEmitter.listenerCount(t)===0&&(n?.then((e=>e.disposeAsync?.())).catch(A4),this._handles.delete(t))}}}on(e,t){if(this._skipEvents.includes(e))return{dispose:A4};let n=`on_${e}`,r=this._handles.get(n);r===void 0&&(r=this._proxyCall(`onAsync`,[e,(...e)=>{this._eventEmitter.emit(n,...e)}]),this._handles.set(n,r));let i=(...e)=>{t.apply(null,e)};return this._eventEmitter.on(n,i),{dispose:()=>{this._eventEmitter.off(n,i),this._eventEmitter.listenerCount(n)===0&&(r?.then((e=>e.disposeAsync?.())).catch(A4),this._handles.delete(n))}}}once(e,t){if(this._skipEvents.includes(e))return{dispose:A4};let n=`once_${e}`,r=this._handles.get(n);r===void 0&&(r=this._proxyCall(`onceAsync`,[e,(...e)=>{this._eventEmitter.emit(n,...e)}]),this._handles.set(n,r));let i=(...e)=>{t.apply(null,e)};return this._eventEmitter.on(n,i),{dispose:()=>{this._eventEmitter.off(n,i),this._eventEmitter.listenerCount(n)===0&&(r?.then((e=>e.disposeAsync?.())).catch(A4),this._handles.delete(n))}}}async changedAsync(e){let t=`changed`,n=this._handles.get(t);n===void 0&&(n=this._proxyCall(`changedAsync`,[(...e)=>{this._eventEmitter.emit(t,...e)}]),this._handles.set(t,n));let r=(...t)=>{e.apply(null,t)};return this._eventEmitter.on(t,r),await n,{dispose:()=>{this._eventEmitter.off(t,r),this._eventEmitter.listenerCount(t)===0&&(n?.then((e=>e.disposeAsync?.())).catch(A4),this._handles.delete(t))}}}async onAsync(e,t){if(this._skipEvents.includes(e))return{dispose:A4};let n=`on_${e}`,r=this._handles.get(n);r===void 0&&(r=this._proxyCall(`onAsync`,[e,(...e)=>{this._eventEmitter.emit(n,...e)}]),this._handles.set(n,r));let i=(...e)=>{t.apply(null,e)};return this._eventEmitter.on(n,i),await r,{dispose:()=>{this._eventEmitter.off(n,i),this._eventEmitter.listenerCount(n)===0&&(r?.then((e=>e.disposeAsync?.())).catch(A4),this._handles.delete(n))}}}},RLe=class extends s9{constructor(e,t){super(e,t),e.once(`remoteStackTerminated`,(()=>{this._eventEmitter.emit(`changed`),this._eventEmitter.emit(`on_callStateChanged`)}))}get state(){return this._proxyReferenceManager.isRemoteStackActive()?this._tsObject.state:7}get callEndDiagnosticsInfo(){return this._proxyReferenceManager.isRemoteStackActive()||this._tsObject.state===7?this._tsObject.callEndDiagnosticsInfo:{callControllerCode:0,callControllerSubCode:4521,phrase:`call ended due to RDP disconnection`,resultCategories:[`ExpectedError`]}}get ptzHandler(){throw new Y({defaultError:J.FEATURES.VDI3.PROPERTY_UNAVAILABLE})}get broadcastMeeting(){throw new Y({defaultError:J.FEATURES.VDI3.PROPERTY_UNAVAILABLE})}get videoLayout(){throw new Y({defaultError:J.FEATURES.VDI3.PROPERTY_UNAVAILABLE})}getIncomingRawAudioStream(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getUnmixedAudioProvider(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}init(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}setDeviceManager(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}forceUpdate(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}startVideo(e,t){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}stopVideo(e,t){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}startScreenSharing(e,t,n,r){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}changeCropRegion(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}stopScreenSharing(e,t,n){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}callSafeTransfer(e,t,n){return n===void 0&&(n={disableForwardingAndUnanswered:!1}),this._tsObject.callSafeTransfer(e,t,n)}setPlatformCallConstraints(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createStageAsync(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createStage(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}sendLastKnownStats(){this._proxyReferenceManager.isRemoteStackActive()&&this._tsObject.sendLastKnownStats().catch((e=>{}))}},zLe=class extends s9{constructor(e,t){super(e,t)}getSourceIdForMediaType(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getDiagnosticData(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}},BLe=class extends s9{constructor(e,t){super(e,t)}getRawStream(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}start(e,t){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}stop(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}selectVideoTrack(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}setVideoStreamConfig(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getDiagnosticData(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getStats(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}},VLe=class extends s9{constructor(e,t){super(e,t),this._deletedCalls=[]}get calls(){return Q2.difference(this._tsObject.calls,this._deletedCalls)}updateSkypeToken(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getSetup(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getCall(e,t,n){return this._tsObject.calls.find((t=>t.callId===e))}createDownloader(e,t,n,r,i){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createCall(e,t,n,r,i){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createCallWithGroupId(e,t,n,r){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createCallWithMeetingData(e,t,n,r){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}deleteCall(e,t,n){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}async deleteCallAsync(e,t,n){return this._proxyReferenceManager.isRemoteStackActive()?await this._tsObject.deleteCallAsync?.apply(this._tsObject,arguments)??!1:!(!e||!this._tsObject.calls.includes(e))&&(this._deletedCalls.push(e),this._eventEmitter.emit(`on_callRemoved`,e),!0)}enableWindowUninitEventHandler(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}disableWindowUninitEventHandler(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}},HLe=class extends s9{constructor(e,t){super(e,t)}getPermissionState(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}selectDevices(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getSelectedDevices(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createPreview(e,t,n,r){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createPreviewRenderer(e,t,n){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createScreenSharingPreviewRenderer(e,t,n){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}setBackgroundImageAsync(e,t,n){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getImagePropertyAsync(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}transformImageAsync(e,t,n,r){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}sendMessageDeviceVideoEffectsAsync(e,t){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}sendMessageDeviceVideoExtensibilityAsync(e,t){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}setVideoCaptureConfigAsync(e,t){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}captureVideoFrameWithoutEffectsAsync(e,t,n){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getRawDeviceMediaStream(e,t,n){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}setRawMediaStream(e,t,n){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}unsetRawMediaStream(e,t){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createAudioRenderer(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getPersonalizedNoiseSuppression(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}setAudioProcessingFlags(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}},ULe=class extends s9{constructor(e,t){super(e,t)}getPlatformSupportLevel(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}setPlatformCallConstraints(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createCompositor(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getCallRegistry(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}cancelOperation(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getDeviceManager(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createDeviceManager(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getScreenSharingManager(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getSetup(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getEcsProvider(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getCallFeedback(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getAiMdp(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getVersion(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getMediaStatus(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getVideoCapabilityLimits(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}fireIntent(e,t){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}setAllowPrivacySensitiveApis(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getLiveStreamClient(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getUmsStream(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createVoipCallCoordinator(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getDebugDump(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createAiCameraManager(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}},c9=class e extends LLe{constructor(e){super(),this._logger=e.createChild(`TsProxyReferenceManager`),this._mmrRdpConnectionManager=new bIe(this._logger),this._mmrRdpConnectionManager.on(`stateChange`,(e=>{e==`disconnected`&&this._remoteStackTerminated(`MMR RDP connection disconnected`)}))}static create(t){let n=new e(t);return this.proxyReferenceManagers.add(n),n}static notifyRemoteStackTermination(e){this.proxyReferenceManagers.forEach((t=>{t._remoteStackTerminated(e)}))}dispose(){this._mmrRdpConnectionManager.dispose(),e.proxyReferenceManagers.delete(this),super.dispose()}_remoteStackTerminated(e){!1!==this._isRemoteStackActive&&(this._logger.warn(`remote stack is terminated: ${e}`),this._isRemoteStackActive=!1,this._eventEmitter.emit(`remoteStackTerminated`))}_createProxy(e){let t=VOe(e);if(t!==B6.None){if(t===B6.ICall)return o9(e,new RLe(this,e),this);if(t===B6.ICallParticipant)return o9(e,new zLe(this,e),this);if(t===B6.ICallParticipantStream)return o9(e,new BLe(this,e),this);if(t===B6.ICallRegistry)return o9(e,new VLe(this,e),this);if(t===B6.IPluginlessCallingStack)return o9(e,new ULe(this,e),this);if(t===B6.IDeviceManager)return o9(e,new HLe(this,e),this)}}isSupportedType(e){return VOe(e)!==B6.None}isRemoteStackActive(){return!!this._isRemoteStackActive}};c9.proxyReferenceManagers=new Set,H5.monitor.onConnectionTerminated((()=>{c9.notifyRemoteStackTermination(`Disconnection detected by monitor`)}));var WLe=class{constructor(){this._eventEmitter=new w3.EventEmitter,this._shellTrouter=new H5.ShellTrouter,this._state=a9.TrouterState.Unknown,this._registeredState=!1,this._disposeAsync=[]}async initialize(){let e=(e,t)=>{this._state=e,this._eventEmitter.emit(`stateChanged`,e,t)},t=e=>{this._registeredState=e,this._eventEmitter.emit(`registeredChanged`,e)};await this._shellTrouter.onStateChanged(e),await this._shellTrouter.onRegisteredStateChanged(t),this._disposeAsync.push((async()=>{await this._shellTrouter.offStateChanged(e),await this._shellTrouter.offRegisteredStateChanged(t)}))}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}async dispose(){for(let e of this._disposeAsync)await e().catch((e=>{}));this._eventEmitter.removeAllListeners()}state(){return this._state}registeredState(){return this._registeredState}get instance(){return this._shellTrouter}},GLe,l9={},u9={};function KLe(){if(GLe)return u9;GLe=1,Object.defineProperty(u9,"__esModule",{value:!0});var e=R5();return u9.default=function(){function t(){this._isAllowed=!1}return t.prototype.putBackgroundFetchAllowed=function(e){if(this._isAllowed=e,this.isBackgroundFetchAllowed()&&this._isAllowedDeferral){var t=this._isAllowedDeferral;this._isAllowedDeferral=void 0,t.resolve(void 0)}},t.prototype.isBackgroundFetchAllowed=function(){return this._isAllowed},t.prototype.waitForBackgroundFetchAllowed=function(){return this.isBackgroundFetchAllowed()?e.Resolved():(this._isAllowedDeferral||=e.Defer(),this._isAllowedDeferral.promise())},t}(),u9}var qLe,d9={};function JLe(){if(qLe)return d9;qLe=1,Object.defineProperty(d9,"__esModule",{value:!0});var e=R5();return d9.default=function(){function t(){this._isActive=!1}return t.prototype.putAppActive=function(e){if(this._isActive=e,this.isAppActive()&&this._appActiveDeferral){var t=this._appActiveDeferral;this._appActiveDeferral=void 0,t.resolve(void 0)}},t.prototype.isAppActive=function(){return this._isActive},t.prototype.waitForAppActive=function(){return this.isAppActive()?e.Resolved():(this._appActiveDeferral||=e.Defer(),this._appActiveDeferral.promise())},t}(),d9}var YLe,XLe,f9={},ZLe=function(){function e(e,t){this._event=e,this._callback=t}return e.prototype.unsubscribe=function(){this._event.unsubscribe(this._callback)},e}(),QLe=function(){function e(e){e===void 0&&(e=!1);var t=this;this._allowStopPropagation=e,this.fire=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];for(var r=t._subscribers,i=r.length-1;i>=0;i--){var a=r[i].apply(null,e);if(t._allowStopPropagation&&a)return!0}return!1},this._subscribers=[]}return e.prototype.dispose=function(){this._subscribers=[]},e.prototype.subscribe=function(e){return this._subscribers=this._subscribers.concat(e),new ZLe(this,e)},e.prototype.unsubscribe=function(e){this._subscribers=this._subscribers.filter((function(t){return t!==e}))},e}(),p9=tue(Object.freeze({__proto__:null,SubscriptionToken:ZLe,default:QLe})),$Le={};function m9(){return YLe||(YLe=1,e=$Le,Object.defineProperty(e,"__esModule",{value:!0}),(t=e.EcsConfigType||={})[t.Default=0]=`Default`,t[t.User=1]=`User`),$Le;var e,t}function eRe(){if(XLe)return f9;XLe=1,Object.defineProperty(f9,"__esModule",{value:!0});var e=p9,t=R5(),n=m9();return f9.default=function(){function r(t){this._config=t,this.configUpdated=new e.default,this._cachedConfigs={}}return r.prototype.initialize=function(){return this.updateConfigsToFetch()},r.prototype.updateConfigsToFetch=function(){var e=this,n=this._config.getConfig(),r=n.databaseInterface,i=n.configsToFetch;if(!r)return t.Resolved();for(var a=[],o=function(n){if(s._cachedConfigs[n])return`continue`;a.push(r.getData(n).then((function(t){t&&(e._cachedConfigs[n]=t)})).catch((function(){return t.Resolved()})))},s=this,c=0,l=i;c<l.length;c++)o(l[c]);return t.all(a).then((function(){a.length>0&&e.configUpdated.fire()}))},r.prototype.getEcsConfig=function(){return this._cachedConfigs[n.EcsConfigType.User]||this._cachedConfigs[n.EcsConfigType.Default]},r.prototype.getEcsConfigByType=function(e){return this._cachedConfigs[e]},r.prototype.putConfig=function(e){var n=this.getEcsConfig();this._cachedConfigs[e.configType]=e;var r=this.getEcsConfig();(r&&r.configType===e.configType||n&&r&&n.configType!==r.configType)&&this.configUpdated.fire();var i=this._config.getConfig().databaseInterface;return i?i.putData(e.configType,e):t.Resolved()},r}(),f9}var tRe,h9={};function nRe(){if(tRe)return h9;tRe=1;var e=h9&&h9.__assign||function(){return e=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},e.apply(this,arguments)};return Object.defineProperty(h9,"__esModule",{value:!0}),h9.default=function(){function t(){}return t.prototype.initialize=function(e){if(this._config)throw Error(`ECS Configuration already initialized`);this._config=e},t.prototype.getConfig=function(){if(!this._config)throw Error(`ECS Configuration not yet initialized`);return this._config},t.prototype.setConfigsToFetch=function(t){if(!this._config)throw Error(`ECS Configuration not yet initialized`);this._config=e(e({},this._config),{configsToFetch:t})},t.prototype.setFetchTimeout=function(t){if(!this._config)throw Error(`ECS Configuration not yet initialized`);this._config=e(e({},this._config),{fetchTimeout:t})},t}(),h9}var rRe,iRe,g9={},_9={},aRe={},oRe={},v9={};function y9(){return rRe||(rRe=1,e=v9,t=v9&&v9.__assign||function(){return t=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},t.apply(this,arguments)},Object.defineProperty(e,"__esModule",{value:!0}),e.assert=function(e,t){if(!e)throw Error(t)},e.isObject=function(e){return typeof e==`object`&&!!e},e.isString=function(e){return typeof e==`string`},e.attempt=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];try{return e.apply(void 0,t)}catch(e){return Error(e)}},e.remove=function(e,t){for(var n=e.length-1;n>=0;n--)e[n]===t&&e.splice(n,1)},e.clone=function(n){return Array.isArray(n)?n.map(e.clone):e.isObject(n)?Object.keys(n).reduce((function(r,i){var a;return t(t({},r),((a={})[i]=e.clone(n[i]),a))}),{}):n}),v9;var e,t}function sRe(){return iRe||(iRe=1,function(e){Object.defineProperty(e,"__esModule",{value:!0});var t=y9();e.DEFAULT_TIME_GROW_FACTOR=2.718281828459045,e.DEFAULT_TIME_JITTER=.11962656472,e.ExponentialTime=function(){function n(n,r,i,a){i===void 0&&(i=e.DEFAULT_TIME_GROW_FACTOR),a===void 0&&(a=e.DEFAULT_TIME_JITTER),this._initialTime=n,this._maxTime=r,this._growFactor=i,this._jitterFactor=a,t.assert(this._initialTime>0,`Initial delay must be positive`),t.assert(this._maxTime>0,`Delay upper bound must be positive`),t.assert(this._growFactor>=0,`Ratio must be non-negative`),t.assert(this._jitterFactor>=0,`Jitter factor must be non-negative`),this.reset()}return n.prototype.reset=function(){this._incrementCount=0,this._currentTime=Math.round(this._initialTime*(1+Math.random()*this._jitterFactor))},n.prototype.getTime=function(){return this._currentTime},n.prototype.getIncrementCount=function(){return this._incrementCount},n.prototype.calculateNext=function(){var e=this._currentTime*this._growFactor;return e>this._maxTime&&(e=this._maxTime),this._jitterFactor<1e-5?this._currentTime=e:this._currentTime=Math.round(Math.random()*e*this._jitterFactor+e),this._currentTime<this._initialTime&&(this._currentTime=this._initialTime),this._currentTime>this._maxTime&&(this._currentTime=this._maxTime),this._incrementCount++,this._currentTime},n.prototype.getTimeAndCalculateNext=function(){var e=this.getTime();return this.calculateNext(),e},n}()}(oRe)),oRe}var cRe,lRe,uRe,dRe,fRe,b9={},x9={};function pRe(){return cRe||(cRe=1,function(e){var t,n=x9&&x9.__extends||(t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},t(e,n)},function(e,n){function r(){this.constructor=e}t(e,n),e.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}),r=x9&&x9.__assign||function(){return r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},r.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var i,a,o=R5(),s=y9(),c=sRe();function l(e){return!!e&&e.indexOf(`application/json`)===0}function u(e){return!!e&&e.indexOf(`application/x-www-form-urlencoded`)===0}function d(e){return!!e&&e.indexOf(`multipart/form-data`)===0}function f(e,t){return t.canceled||!t.statusCode||t.statusCode>=400&&t.statusCode<600?a.DoNotRetry:a.RetryCountedWithBackoff}(function(e){e[e.DontCare=0]=`DontCare`,e[e.Low=1]=`Low`,e[e.Normal=2]=`Normal`,e[e.High=3]=`High`,e[e.Critical=4]=`Critical`})(i=e.WebRequestPriority||={}),function(e){e[e.DoNotRetry=0]=`DoNotRetry`,e[e.RetryUncountedImmediately=1]=`RetryUncountedImmediately`,e[e.RetryUncountedWithBackoff=2]=`RetryUncountedWithBackoff`,e[e.RetryCountedWithBackoff=3]=`RetryCountedWithBackoff`,e[e.PauseUntilResumed=4]=`PauseUntilResumed`}(a=e.ErrorHandlingType||={}),e.DefaultOptions={priority:i.Normal},e.SimpleWebRequestOptions={MaxSimultaneousRequests:5,HungRequestCleanupIntervalMs:1e4,setTimeout:function(e,t){return setTimeout(e,t)},clearTimeout:function(e){return clearTimeout(e)}},e.DefaultErrorHandler=f;var p,m=[],h=[],g=[],_=0,v=0,y=function(){function t(t,n,i,a,o){this._action=t,this._url=n,this.options=i,this._getHeaders=a,this._blockRequestUntil=o,this._aborted=!1,this._timedOut=!1,this._paused=!1,this._created=Date.now(),this._finishHandled=!1,this._retryExponentialTime=new c.ExponentialTime(1e3,3e5),this._options=r(r({},e.DefaultOptions),i)}return t.prototype.getPriority=function(){return this._options.priority||i.DontCare},t.checkQueueProcessing=function(){for(var t=function(){var t=m.shift();h.push(t),(t._blockRequestUntil&&t._blockRequestUntil()||o.Resolved()).finally((function(){s.remove(h,t)})).then((function(){g.length<e.SimpleWebRequestOptions.MaxSimultaneousRequests&&!t._aborted?(g.push(t),b._scheduleHungRequestCleanupIfNeeded(),t._fire()):t._enqueue()}),(function(e){t._respond(`_blockRequestUntil rejected: `+e)}))};m.length>0&&g.length<e.SimpleWebRequestOptions.MaxSimultaneousRequests;)t()},t._scheduleHungRequestCleanupIfNeeded=function(){g.length>0&&p===void 0?p=e.SimpleWebRequestOptions.setTimeout(this._hungRequestCleanupTimerCallback,e.SimpleWebRequestOptions.HungRequestCleanupIntervalMs):g.length===0&&p&&(e.SimpleWebRequestOptions.clearTimeout(p),p=void 0)},t.prototype._removeFromQueue=function(){s.remove(g,this),s.remove(m,this)},t.prototype._assertAndClean=function(e,t){e||(this._removeFromQueue(),console.error(t),s.assert(e,t))},t.prototype._fire=function(){var n=this;this._xhr=new XMLHttpRequest,this._xhrRequestHeaders={};var r=s.attempt((function(){n._xhr.open(n._action,n._url,!0)}));if(r)this._respond(r.toString());else{if(this._options.timeout){var i=v;i!==3&&(this._assertAndClean(!this._requestTimeoutTimer,`Double-fired requestTimeoutTimer`),this._requestTimeoutTimer=e.SimpleWebRequestOptions.setTimeout((function(){n._requestTimeoutTimer=void 0,n._timedOut=!0,n.abort()}),this._options.timeout)),(i===3||i<=1)&&(this._xhr.timeout=this._options.timeout,this._xhr.ontimeout=function(){v=3,i===3&&(n._timedOut=!0,n._aborted=!0,n._respond(`TimedOut`))})}var a=_;a===3?this._options.streamingDownloadProgress&&(this._xhr.onreadystatechange=function(){n._xhr&&n._xhr.readyState===3&&n._options.streamingDownloadProgress&&!n._aborted&&n._options.streamingDownloadProgress(n._xhr.responseText)}):(a===0&&(_=1),this._xhr.onreadystatechange=function(){n._xhr&&(n._xhr.readyState!==3||!n._options.streamingDownloadProgress||n._aborted?n._xhr.readyState===4&&(a===0&&_===1&&e.SimpleWebRequestOptions.setTimeout((function(){_!==3&&(_=2)}),1e4),n._respond()):n._options.streamingDownloadProgress(n._xhr.responseText))}),a!==2&&(this._xhr.onload=function(){_=3,a===3&&n._respond()},this._xhr.onerror=function(){_=3,a===3&&n._respond()}),this._xhr.onabort=function(){n._aborted=!0,n._respond(`Aborted`)},this._xhr.upload&&this._options.onProgress&&(this._xhr.upload.onprogress=this._options.onProgress);var o=this._options.acceptType||`json`,c=this._options.customResponseType||t._getResponseType(o),l=s.attempt((function(){n._xhr.responseType=c}));if(l&&c!==`json`)throw l;b._setRequestHeader(this._xhr,this._xhrRequestHeaders,`Accept`,t.mapContentType(o)),this._xhr.withCredentials=!!this._options.withCredentials;var u=this.getRequestHeaders(),d={};if(Object.keys(u).forEach((function(e){var t=u[e],r=e.toLowerCase();r===`content-type`?n._assertAndClean(!1,`Don't set Content-Type with options.headers -- use it with the options.contentType property`):r===`accept`?n._assertAndClean(!1,`Don't set Accept with options.headers -- use it with the options.acceptType property`):(n._assertAndClean(!d[r],`Setting duplicate header key: `+d[r]+` and `+e),t==null?console.warn(`Tried to set header "`+e+`" on request with "`+t+`" value, header will be dropped`):(d[r]=!0,b._setRequestHeader(n._xhr,n._xhrRequestHeaders,e,t)))})),this._options.sendData){var f=t.mapContentType(this._options.contentType||`json`);b._setRequestHeader(this._xhr,this._xhrRequestHeaders,`Content-Type`,f);var p=t.mapBody(this._options.sendData,f);this._xhr.send(p)}else this._xhr.send()}},t._setRequestHeader=function(e,t,n,r){e.setRequestHeader(n,r),t[n]=r},t.mapContentType=function(e){return e===`json`?`application/json`:e===`form`?`application/x-www-form-urlencoded`:e},t.mapBody=function(e,t){if(l(t)){if(!s.isString(e))return JSON.stringify(e)}else if(u(t)){if(!s.isString(e)&&s.isObject(e)){var n=e;return Object.keys(n).map((function(e){return encodeURIComponent(e)+(n[e]?`=`+encodeURIComponent(n[e].toString()):``)})).join(`&`)}}else if(d(t)){if(s.isObject(e)){var r=new FormData,i=e;return Object.keys(i).forEach((function(e){return r.append(e,i[e])})),r}s.assert(!1,`contentType multipart/form-data must include an object as sendData`)}return e},t.prototype.setUrl=function(e){this._url=e},t.prototype.setHeader=function(e,t){this._options.augmentHeaders||(this._options.augmentHeaders={}),t?this._options.augmentHeaders[e]=t:delete this._options.augmentHeaders[e]},t.prototype.getRequestHeaders=function(){var e={};return!this._getHeaders||this._options.overrideGetHeaders||this._options.headers||(e=r(r({},e),this._getHeaders())),this._options.overrideGetHeaders&&(e=r(r({},e),this._options.overrideGetHeaders)),this._options.headers&&(e=r(r({},e),this._options.headers)),this._options.augmentHeaders&&(e=r(r({},e),this._options.augmentHeaders)),e},t.prototype.getOptions=function(){return s.clone(this._options)},t.prototype.setPriority=function(e){this._options.priority!==e&&(this._options.priority=e,this._paused||this._xhr||(s.remove(m,this),this._enqueue()))},t.prototype.resumeRetrying=function(){this._paused?(this._paused=!1,this._enqueue()):s.assert(!1,`resumeRetrying() called but not paused!`)},t.prototype._enqueue=function(){var e=this;if(!this._aborted&&!(g.indexOf(this)>=0||h.indexOf(this)>=0||m.indexOf(this)>=0)){var n=m.findIndex((function(t){return t.getPriority()===e.getPriority()&&t._created>e._created||t.getPriority()<e.getPriority()}));n>-1?m.splice(n,0,this):m.push(this),t.checkQueueProcessing()}},t._getResponseType=function(e){return e===`blob`?`arraybuffer`:e===`text/xml`||e===`application/xml`?`document`:e===`text/plain`?`text`:`json`},t._hungRequestCleanupTimerCallback=function(){p=void 0,g.filter((function(e){return!(!e._xhr||e._xhr.readyState!==4)&&(console.warn(`SimpleWebRequests found a completed XHR that hasn't invoked it's callback functions, manually responding`),!0)})).forEach((function(e){e._respond()})),b._scheduleHungRequestCleanupIfNeeded()},t}();e.SimpleWebRequestBase=y;var b=function(t){function r(e,n,r,i,a){return t.call(this,e,n,r,i,a)||this}return n(r,t),r.prototype.abort=function(){this._aborted?s.assert(!1,`Already aborted `+this._action+` request to `+this._url):(this._aborted=!0,this._retryTimer&&=(e.SimpleWebRequestOptions.clearTimeout(this._retryTimer),void 0),this._requestTimeoutTimer&&=(e.SimpleWebRequestOptions.clearTimeout(this._requestTimeoutTimer),void 0),this._deferred?(this._respond(`Aborted`),this._xhr&&this._xhr.abort()):s.assert(!1,`Haven't even fired start() yet -- can't abort`))},r.prototype.start=function(){var e=this;return this._deferred?(s.assert(!1,`WebRequest already started`),o.Rejected(`WebRequest already started`)):(this._deferred=o.Defer(),this._deferred.onCancel((function(){e.abort()})),this._enqueue(),this._deferred.promise())},r.prototype._respond=function(t){var n=this;if(!this._finishHandled){this._finishHandled=!0,this._removeFromQueue(),this._retryTimer&&=(e.SimpleWebRequestOptions.clearTimeout(this._retryTimer),void 0),this._requestTimeoutTimer&&=(e.SimpleWebRequestOptions.clearTimeout(this._requestTimeoutTimer),void 0);var r,i=0;if(this._xhr)try{i=this._xhr.status,r=this._xhr.statusText||t}catch{}else r=t||`Browser Error - Possible CORS or Connectivity Issue`;var o,c,u={};if(this._xhr){if((this._xhr.getAllResponseHeaders()||``).split(/\r?\n/).forEach((function(e){if(e.length!==0){var t=e.indexOf(`:`);t===-1?u[e]=``:u[e.substr(0,t).toLowerCase()]=e.substr(t+1).trim()}})),!u[`content-type`]){var d=this._xhr.getResponseHeader(`content-type`);d&&(u[`content-type`]=d)}if(o=this._xhr.response,u[`content-type`]&&l(u[`content-type`])&&(!o||!s.isObject(o))&&(this._xhr.responseType===`text`||this._xhr.responseType===``)&&this._xhr.responseText)try{o=JSON.parse(this._xhr.responseText)}catch(e){c=e,console.warn(`Failed to parse XHR JSON response`)}}if(this._xhr&&this._xhr.readyState===4&&(i>=200&&i<300||i===304)){var p={url:this._xhr.responseURL||this._url,method:this._action,requestOptions:this._options,requestHeaders:this._xhrRequestHeaders||{},statusCode:i,statusText:r,headers:u,body:o,responseParsingException:c};this._deferred.resolve(p)}else{var m={url:(this._xhr?this._xhr.responseURL:void 0)||this._url,method:this._action,requestOptions:this._options,requestHeaders:this._xhrRequestHeaders||{},statusCode:i,statusText:r,headers:u,body:o,canceled:this._aborted,timedOut:this._timedOut,responseParsingException:c};this._options.augmentErrorResponse&&this._options.augmentErrorResponse(m);var h=this._options.customErrorHandler?this._options.customErrorHandler(this,m):f(this,m);h!==a.DoNotRetry&&(this._options.retries&&this._options.retries>0||h===a.PauseUntilResumed||h===a.RetryUncountedImmediately||h===a.RetryUncountedWithBackoff)?(h===a.RetryCountedWithBackoff&&this._options.retries--,this._requestTimeoutTimer&&=(e.SimpleWebRequestOptions.clearTimeout(this._requestTimeoutTimer),void 0),this._aborted=!1,this._timedOut=!1,this._finishHandled=!1,this._xhr&&(this._xhr.onabort=null,this._xhr.onerror=null,this._xhr.onload=null,this._xhr.onprogress=null,this._xhr.onreadystatechange=null,this._xhr.ontimeout=null,this._xhr=void 0,this._xhrRequestHeaders=void 0),h===a.PauseUntilResumed?this._paused=!0:h===a.RetryUncountedImmediately?this._enqueue():this._retryTimer=e.SimpleWebRequestOptions.setTimeout((function(){n._retryTimer=void 0,n._enqueue()}),this._retryExponentialTime.getTimeAndCalculateNext())):this._deferred.reject(m)}y.checkQueueProcessing()}},r}(y);e.SimpleWebRequest=b}(x9)),x9}function mRe(){if(lRe)return b9;lRe=1;var e=b9&&b9.__assign||function(){return e=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},e.apply(this,arguments)};Object.defineProperty(b9,"__esModule",{value:!0});var t=y9(),n=pRe();return b9.GenericRestClient=function(){function r(e){this._defaultOptions={excludeEndpointUrl:!1,withCredentials:!1,retries:0},this._endpointUrl=e}return r.prototype._performApiCall=function(r,i,a,o){var s=this;o===void 0&&(o={});var c=e(e({},this._defaultOptions),o);a&&(c.sendData=a),c.eTag&&(c.augmentHeaders||={},c.augmentHeaders[`If-None-Match`]=c.eTag),c.contentType||=t.isString(c.sendData)?`form`:`json`;var l=c.excludeEndpointUrl?r:this._endpointUrl+r;return new n.SimpleWebRequest(i,l,c,(function(){return s._getHeaders(c)}),(function(){return s._blockRequestUntil(c)})).start().then((function(e){return s._processSuccessResponse(e),e}))},r.prototype._getHeaders=function(e){return{}},r.prototype._blockRequestUntil=function(e){},r.prototype._processSuccessResponse=function(e){},r.prototype.performApiGet=function(e,t){return this.performApiGetDetailed(e,t).then((function(e){return e.body}))},r.prototype.performApiGetDetailed=function(e,t){return this._performApiCall(e,`GET`,void 0,t)},r.prototype.performApiPost=function(e,t,n){return this.performApiPostDetailed(e,t,n).then((function(e){return e.body}))},r.prototype.performApiPostDetailed=function(e,t,n){return this._performApiCall(e,`POST`,t,n)},r.prototype.performApiPatch=function(e,t,n){return this.performApiPatchDetailed(e,t,n).then((function(e){return e.body}))},r.prototype.performApiPatchDetailed=function(e,t,n){return this._performApiCall(e,`PATCH`,t,n)},r.prototype.performApiPut=function(e,t,n){return this.performApiPutDetailed(e,t,n).then((function(e){return e.body}))},r.prototype.performApiPutDetailed=function(e,t,n){return this._performApiCall(e,`PUT`,t,n)},r.prototype.performApiDelete=function(e,t,n){return this.performApiDeleteDetailed(e,t,n).then((function(e){return e.body}))},r.prototype.performApiDeleteDetailed=function(e,t,n){return this._performApiCall(e,`DELETE`,t,n)},r}(),b9}function hRe(){return uRe||(uRe=1,function(e){function t(t){for(var n in t)e.hasOwnProperty(n)||(e[n]=t[n])}Object.defineProperty(e,"__esModule",{value:!0}),t(sRe()),t(mRe()),t(pRe())}(aRe)),aRe}function gRe(){return fRe?dRe:(fRe=1,dRe=hRe())}var _Re,vRe,yRe,bRe,S9={},C9={};function xRe(){return _Re?C9:(_Re=1,Object.defineProperty(C9,"__esModule",{value:!0}),C9.TelemetryEventBase=function(){function e(){}return e.prototype.getAttributes=function(){return{Source:`ecs_client`}},e}(),C9)}function SRe(){if(vRe)return S9;vRe=1;var e,t=S9&&S9.__extends||(e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},e(t,n)},function(t,n){function r(){this.constructor=t}e(t,n),t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)});return Object.defineProperty(S9,"__esModule",{value:!0}),S9.EcsConfigFetchResponse=function(e){function n(t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_){var v=e.call(this)||this;return v._responseTime=t,v._responseCode=n,v._fetchAttempts=r,v._hasValidToken=i,v._serverEndpoint=a,v._fetchDurationValid=o,v._cacheAvailable=s,v._responseSize=c,v._configAge=l,v._configExpired=u,v._fetchStart=d,v._fetchEnd=f,v._isUserConfig=p,v._etag=m,v._timedOut=h,v._responseParsingException=g,v._errorMessage=_,v}return t(n,e),n.prototype.getEventName=function(){return`ecs_tsclient_fetch_config`},n.prototype.getAttributes=function(){var t=e.prototype.getAttributes.call(this);return t.fetch_delay_ms=this._responseTime,t.fetch_response_code=this._responseCode,t.fetch_attempts=this._fetchAttempts,t.authenticated_user=this._hasValidToken,t.url=this._serverEndpoint,t.fetch_duration_valid=this._fetchDurationValid,t.cache_available=this._cacheAvailable,t.response_size=this._responseSize,t.config_age=this._configAge,t.config_expired=this._configExpired,t.fetch_start=this._fetchStart,t.fetch_end=this._fetchEnd,t.is_user_config=this._isUserConfig,this._etag&&(t.fetched_etag=this._etag),this._timedOut!==void 0&&(t.fetch_timed_out=this._timedOut),this._responseParsingException&&(t.fetch_response_parsing_error=this._responseParsingException.message),this._errorMessage&&(t.fetch_error_message=this._errorMessage),t},n}(xRe().TelemetryEventBase),S9}function CRe(){if(yRe)return _9;yRe=1;var e,t=_9&&_9.__extends||(e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},e(t,n)},function(t,n){function r(){this.constructor=t}e(t,n),t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}),n=_9&&_9.__assign||function(){return n=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},n.apply(this,arguments)};Object.defineProperty(_9,"__esModule",{value:!0});var r,i,a=gRe(),o=R5(),s=m9(),c=SRe(),l=1728e5,u=18e5,d=31536e6,f=3e4,p=function(e){function n(t,n,r,i,a,o,s,c){var l=e.call(this,t)||this;l._config=n,l._skypeTokenData=r,l._appActiveData=i,l._allowBackgroundFetchData=a,l._etag=o,l._getUserConfig=s;var u=l._config.getConfig();if(l._apiPath=u.clientTeam?`/config/v1/`+u.clientName+`/`+u.clientVersion+`/`+u.clientTeam:`/config/v1/`+u.clientName+`/`+u.clientVersion,c){var d=Object.keys(c).map((function(e){return encodeURIComponent(e)+`=`+encodeURIComponent(c[e].toString())}));d&&(l._apiPath+=`?`+d.join(`&`))}return l}return t(n,e),n.prototype._blockRequestUntil=function(e){var t=this;if(this._getUserConfig&&!this._skypeTokenData.isSkypeTokenValid()&&console.log(`ECS - Delaying User config fetch until we have a valid SkypeToken`),!this._appActiveData.isAppActive()&&!this._allowBackgroundFetchData.isBackgroundFetchAllowed()){var n=this._getUserConfig?`User config`:`config`;console.log(`ECS - Delaying `+n+` fetch until the app is active (or background fetch is allowed)`)}return o.race([this._appActiveData.waitForAppActive(),this._allowBackgroundFetchData.waitForBackgroundFetchAllowed()]).then((function(){if(t._getUserConfig)return t._skypeTokenData.waitForValidSkypeToken()})).then((function(){i=Date.now()}))},n.prototype._getHeaders=function(){var e={};return this._etag&&(e[`If-None-Match`]=this._etag),this._getUserConfig&&(e.Authorization=this._skypeTokenData.getSkypeToken()),e},n.prototype.getConfig=function(){var t=this._config.getConfig().fetchTimeout;return t!==void 0&&(t<0?t=0:t>0&&t<f&&(t=f)),e.prototype.performApiGetDetailed.call(this,this._apiPath,{timeout:t})},n}(a.GenericRestClient);return _9.default=function(){function e(e,t,n,r,i){this._config=e,this._skypeTokenData=t,this._appActiveData=n,this._allowBackgroundFetchData=r,this._telemetryManager=i,this._ecsFailureBackoffTimer=new a.ExponentialTime(1e3,3e5),this._cacheMaxAgeRegex=/.*max-age=(\d+).*/gi,this._serverIndex=NaN}return e.prototype.getConfig=function(e,t,r){var a=this,l=this._config.getConfig().hosts;if((isNaN(this._serverIndex)||this._serverIndex>l.length-1)&&(this._serverIndex=Math.floor(Math.random()*l.length)),!l||!l.length)return o.Rejected(Error(`no configuration service endpoint`));var u=o.Defer(),d=0,f=function(){var m=e&&e.eTag?e.eTag:void 0,h=new p(l[a._serverIndex],a._config,a._skypeTokenData,a._appActiveData,a._allowBackgroundFetchData,m,t,r);d++,h.getConfig().then((function(r){var f=r.headers.etag,p=r.headers.expires;r.body&&r.body.Headers&&(f||=r.body.Headers.ETag,p||=r.body.Headers.Expires);var h=a._calculateResponseTimeInfo(e);if(!f||!p)return console.warn(`ECS - Service returned an empty ETag or Expiration header: `+JSON.stringify(r)),o.Rejected({timedOut:!1,responseParsingException:Error(`ECS Service returned empty ETag or Expiration header`),responseCode:r.statusCode});var g,_=new Date(a._calculateExpirationDate(r.headers)).getTime();if(r.statusCode===304&&e)(g=n({},e)).configType=t?s.EcsConfigType.User:s.EcsConfigType.Default,g.eTag=f,g.expiration=_,g.cacheUpdateTime=h.lastResponseTime,g.lastFetchTokenHash=a._skypeTokenData.getSkypeTokenHash(r.requestHeaders.Authorization);else{if(typeof r.body!=`object`)return console.warn(`ECS - Service returned invalid response `+JSON.stringify(r)),o.Rejected({timedOut:!1,responseParsingException:Error(`ECS Service returned invalid response body`),responseCode:r.statusCode});g={config:r.body,configType:t?s.EcsConfigType.User:s.EcsConfigType.Default,eTag:f,expiration:_,cacheUpdateTime:i,lastFetchTokenHash:a._skypeTokenData.getSkypeTokenHash(r.requestHeaders.Authorization),appVersion:a._config.getConfig().clientVersion}}a._telemetryManager.sendTelemetryEvent(new c.EcsConfigFetchResponse(h.fetchDelayMs,r.statusCode,d,a._skypeTokenData.isSkypeTokenValid(),l[a._serverIndex],h.fetchDurationValid,!!m,JSON.stringify(r).length,h.cacheAge,!(e&&e.expiration-Date.now()>0),i,h.lastResponseTime,t,f)),a._ecsFailureBackoffTimer.reset(),u.resolve(g)})).catch((function(n){var r={timedOut:n&&n.timedOut||!1,responseParseError:n&&n.responseParsingException,responseCode:n&&n.statusCode||0,message:a._getErrorMessage(n)};console.error(`ECS - Service request failed to return a response (timedOut: `+r.timedOut+`, responseParseError: `+r.responseParseError+`)`);var o=a._calculateResponseTimeInfo(e);a._telemetryManager.sendTelemetryEvent(new c.EcsConfigFetchResponse(o.fetchDelayMs,r.responseCode,d,a._skypeTokenData.isSkypeTokenValid(),l[a._serverIndex],o.fetchDurationValid,!!m,0,o.cacheAge,!(e&&e.expiration-Date.now()>0),i,o.lastResponseTime,t,void 0,r.timedOut,r.responseParseError,r.message));var s=a._config.getConfig().fetchAttemptMax;s&&d>s||setTimeout((function(){f()}),a._ecsFailureBackoffTimer.getTimeAndCalculateNext())}))};return f(),u.promise()},e.prototype._calculateExpirationDate=function(e){var t=Date.now()+l;if(e.date&&e.expires){var n=new Date(e.date).getTime(),r=Date.now()-n,i=new Date(e.expires).getTime();return isNaN(i)?t:Math.min(t,i+r)}var a=this._cacheMaxAgeRegex.exec(e[`cache-control`]);return this._cacheMaxAgeRegex.lastIndex=0,a&&a.length===2?Math.min(t,Date.now()+1e3*Number(a[1])):Date.now()+u},e.prototype._calculateResponseTimeInfo=function(e){var t=(r=Date.now())-i;return{lastResponseTime:r,fetchDelayMs:t,fetchDurationValid:!(t<0||t>d),cacheAge:e?r-e.cacheUpdateTime:0}},e.prototype._getErrorMessage=function(e){if(e)return typeof e==`string`?e:typeof e==`object`&&(e.statusText||e.message)?e.statusText||e.message:void 0},e}(),_9}function wRe(){if(bRe)return g9;bRe=1,Object.defineProperty(g9,"__esModule",{value:!0});var e=m9(),t=CRe();return g9.default=function(){function n(n,r,i,a,o,s){var c=this;this._config=n,this._skypeTokenData=r,this._cache=i,this._isFetchingSettings={},this._pendingFetch={},this._pendingTimers={},this._subscriptionToken=null,this._paused=!1,this._fetchEcsSettingsIfNeeded=function(t){var n=c._config.getConfig(),r=c._cache.getEcsConfigByType(t);if(n.configsToFetch.indexOf(t)!==-1&&!c._isFetchingSettings[t])if(r||!c._pendingFetch[t]){var i=r?r.expiration-Date.now():-1;i<=0||r&&t===e.EcsConfigType.User&&c._skypeTokenData.isSkypeTokenValid()&&r.lastFetchTokenHash!==c._skypeTokenData.getSkypeTokenHash(c._skypeTokenData.getSkypeToken())?c._fetchSkypeEcsSettings(t):n.Killswitches?.isSkypeTokenDataLeakFixEnabled?(c._pendingTimers[t]>0&&clearTimeout(c._pendingTimers[t]),c._pendingTimers[t]=window.setTimeout((function(){return c._fetchEcsSettingsIfNeeded(t)}),i)):window.setTimeout((function(){return c._fetchEcsSettingsIfNeeded(t)}),i)}else c._fetchSkypeEcsSettings(t)},this._fetchSkypeEcsSettings=function(t,n){n===void 0&&(n=!1),c._isFetchingSettings[t]||c._paused&&!n?c._pendingFetch[t]=!0:(c._pendingFetch[t]=!1,c._isFetchingSettings[t]=!0,c._config.getConfig().getEcsParameters().catch((function(){return console.warn(`ECS - Failed to fetch ECS fetching parameters`),{}})).then((function(n){return c._ecsClient.getConfig(c._cache.getEcsConfig(),t===e.EcsConfigType.User,n)})).then((function(e){console.log(`ECS - Config fetch complete`),c._isFetchingSettings[t]=!1,c._cache.putConfig(e),c._fetchEcsSettingsIfNeeded(t)})))},this._ecsClient=new t.default(this._config,this._skypeTokenData,a,o,s)}return n.prototype.initialize=function(){var t=this;this.updateConfigsToFetch(),this._subscriptionToken=this._skypeTokenData.skypeTokenChanged.subscribe((function(){return t._fetchEcsSettingsIfNeeded(e.EcsConfigType.User)}))},n.prototype.dispose=function(){var e,t=this._config.getConfig();if(t.Killswitches?.isSkypeTokenDataLeakFixEnabled){for(var n=0,r=t.configsToFetch;n<r.length;n++){var i=r[n];clearTimeout(this._pendingTimers[i]),this._pendingTimers[i]=0}(e=this._subscriptionToken)==null||e.unsubscribe(),this._subscriptionToken=null,this._skypeTokenData.skypeTokenChanged.dispose()}},n.prototype.updateConfigsToFetch=function(){for(var e=this._config.getConfig(),t=0,n=e.configsToFetch;t<n.length;t++)(a=n[t])in this._isFetchingSettings||(this._isFetchingSettings[a]=!1),a in this._isFetchingSettings||(this._pendingFetch[a]=!1);for(var r=0,i=e.configsToFetch;r<i.length;r++){var a=i[r],o=this._cache.getEcsConfigByType(a);!o||o.appVersion&&o.appVersion!==e.clientVersion?this._fetchSkypeEcsSettings(a,!0):this._fetchEcsSettingsIfNeeded(a)}},n.prototype.requestUpdate=function(){for(var e=0,t=this._config.getConfig().configsToFetch;e<t.length;e++){var n=t[e];this._fetchSkypeEcsSettings(n)}},n.prototype.pause=function(){this._paused=!0},n.prototype.resume=function(){this._paused=!1;for(var e=0,t=this._config.getConfig().configsToFetch;e<t.length;e++){var n=t[e];this._fetchEcsSettingsIfNeeded(n)}},n}(),g9}var TRe,w9={};function ERe(){if(TRe)return w9;TRe=1,Object.defineProperty(w9,"__esModule",{value:!0});var e=p9,t=R5();return w9.default=function(){function n(){this.skypeTokenChanged=new e.default}return n.prototype.putSkypeTokenData=function(e){if(this._data=e,this.isSkypeTokenValid()&&this.skypeTokenChanged.fire(),this.isSkypeTokenValid()&&this._validSkypeTokenDeferral){var t=this._validSkypeTokenDeferral;this._validSkypeTokenDeferral=void 0,t.resolve(void 0)}},n.prototype.isSkypeTokenValid=function(){var e=this._data;return!!e&&!!e.skypeToken&&e.skypeTokenExpiration>Date.now()},n.prototype.getSkypeToken=function(){var e=this._data;if(!e||!e.skypeToken)throw Error(`No Skype Token provided`);return e.skypeToken},n.prototype.getSkypeTokenHash=function(e){return e===void 0?0:e.split(``).reduce((function(e,t){return(101*e+t.charCodeAt(0))%999727999}),e.length)},n.prototype.waitForValidSkypeToken=function(){return this.isSkypeTokenValid()?t.Resolved():(this._validSkypeTokenDeferral||=t.Defer(),this._validSkypeTokenDeferral.promise())},n}(),w9}var DRe,ORe,T9={};function kRe(){if(DRe)return T9;DRe=1,Object.defineProperty(T9,"__esModule",{value:!0});var e=p9;return T9.default=function(){function t(t){this._cache=t,this.telemetryEventAdded=new e.default}return t.prototype.sendTelemetryEvent=function(e){var n=e.getEventName(),r=e.getAttributes(),i=!1,a=this._cache.getEcsConfig();if(a){if(t._containsEcsClientTelemetryConfig(a.config)){var o=a.config.ECSCONFIG;o&&o.ecsClientTelemetry&&(i=!!o.ecsClientTelemetry[n])}}else console.warn(`No previously cached ECS telemetry config exists - fallback to sending event`),i=!0;i&&this.telemetryEventAdded.fire(n,r)},t._containsEcsClientTelemetryConfig=function(e){return!!e&&!!e.ECSCONFIG&&!!e.ECSCONFIG.ecsClientTelemetry},t}(),T9}function ARe(){if(ORe)return l9;ORe=1,Object.defineProperty(l9,"__esModule",{value:!0});var e=KLe(),t=JLe(),n=eRe(),r=nRe();l9.Models=m9();var i=wRe(),a=ERe(),o=kRe();return l9.default=function(){function s(){this._allowBackgroundFetchData=new e.default,this._appActiveData=new t.default,this._config=new r.default,this._cache=new n.default(this._config),this._skypeTokenData=new a.default,this._telemetryManager=new o.default(this._cache),this._scheduler=new i.default(this._config,this._skypeTokenData,this._cache,this._appActiveData,this._allowBackgroundFetchData,this._telemetryManager),this.telemetryEventAdded=this._telemetryManager.telemetryEventAdded,this.configUpdated=this._cache.configUpdated}return s.prototype.initialize=function(e){var t=this;return this._config.initialize(e),this._skypeTokenData.putSkypeTokenData(e.initialSkypeTokenData),this._appActiveData.putAppActive(e.initialAppActiveState),this._cache.initialize().then((function(){t._scheduler.initialize()}))},s.prototype.dispose=function(){var e;(e=this._config.getConfig().Killswitches)!=null&&e.isSkypeTokenDataLeakFixEnabled&&this._scheduler.dispose()},s.prototype.getConfig=function(){return this._cache.getEcsConfig()},s.prototype.getConfigType=function(){var e=this._cache.getEcsConfig();if(e)return e.configType},s.prototype.requestUpdate=function(){this._scheduler.requestUpdate()},s.prototype.pause=function(){this._scheduler.pause()},s.prototype.resume=function(){this._scheduler.resume()},s.prototype.setAllowBackgroundFetch=function(e){this._allowBackgroundFetchData.putBackgroundFetchAllowed(e)},s.prototype.useSkypeToken=function(e,t){this._skypeTokenData.putSkypeTokenData({skypeToken:e,skypeTokenExpiration:t})},s.prototype.setAppActive=function(e){this._appActiveData.putAppActive(e)},s.prototype.setConfigsToFetch=function(e){var t=this;return this._config.setConfigsToFetch(e),this._cache.updateConfigsToFetch().then((function(){t._scheduler.updateConfigsToFetch()}))},s.prototype.setFetchTimeout=function(e){this._config.setFetchTimeout(e)},s}(),l9}var E9,D9=ARe(),jRe=kG(D9),MRe=R5();function NRe(e,t){let n={},r=e.OsName??``,i=e.OsVer??``,a=r&&i?`${r}-${i}`:``;return n.CLRelease=`${e.CLRelease??``}`,n.BrowserName=Q2.toLower(`${e.BrowserName??``}`),n.BrowserEngine=`${e.BrowserEngine??``}`,n.BrowserVersion=`${e.BrowserVersion??``}`,n.FormFactor=`${e.FormFactor??``}`,n.IdentityType=$0.Consumer,n.Cloud=J0.Public,n.OSVer=Q2.toLower(a),n.BrowserName===`edge`&&(n.BrowserName=`edgeanaheim`),t&&(n.Cloud=t.cloudType,n.IdentityType=t.identityType),Q2.omitBy(n,(e=>e==null||e===``))}function PRe(e,t){let n={[J0.Public]:Z0.Public_EcsServer_Url,[J0.Dod]:Z0.Dod_EcsServer_Url,[J0.GccHigh]:Z0.GccHigh_EcsServer_Url,[J0.AirGap08]:Z0.AirGap08_EcsServer_Url,[J0.AirGap09]:Z0.AirGap09_EcsServer_Url},r=Z0.Public_EcsServer_Url;return t&&(r=t.identityType===$0.Enterprise?Z0.Enterprise_Ecs_ServerUrl:n[t.cloudType]??Z0.Public_EcsServer_Url),e?.proxyfyUrl(r)??r}(function(e){e.Default=`Default`,e.User=`User`})(E9||={});var FRe=class{constructor(e,t,n,r){this._isWBMediaClient=e,this._acsProxy=n,this._sourceTag=r,this._throttlingTimeoutHandle=0,this._eventEmitter=new w3.EventEmitter,this._logger=t.createChild(`EcsClient`)}_resetThrottlingTimeout(){this._throttlingTimeoutHandle&&=(window.clearTimeout(this._throttlingTimeoutHandle),0)}_resetEcsClient(){this._ecsClient&&=(this._ecsClient.configUpdated.dispose(),void 0)}async _fetchConfig(e){this._resetEcsClient(),this._resetThrottlingTimeout();let t=new jRe,n=e3();try{await t.initialize(e);let r=[],i=!1,a=0;t.configUpdated.subscribe((()=>{if(n.isPending())n.resolve();else{r.push(Date.now());let e=t.getConfig();if(e?.config){let t=e?.configType===D9.Models.EcsConfigType.User?E9.User:E9.Default;this._cachedConfig=e,this._eventEmitter.emit(`configUpdated`,{config:e?.config,fetchType:t,sourceTag:this._sourceTag})}let n=Z().ecsClient.throttling;r.length>n.triggerCount&&(r=r.slice(r.length-n.triggerCount));let o=r[r.length-1]-r[0];i?(r.length<n.triggerCount||o>=n.coolDownDuration)&&(i=!1,a=0,r=[],this._resetThrottlingTimeout()):r.length===n.triggerCount&&o<n.triggerDuration&&(i=!0),i&&(a=a===0?n.startingDelay:Math.min(Math.ceil(a*n.delayFactor),n.maxDelay),t.pause(),this._throttlingTimeoutHandle=window.setTimeout((()=>{this._throttlingTimeoutHandle=0,t.resume()}),a))}})),this._ecsClient=t,await n3((()=>n.promise),OCe);let o=t.getConfig();if(!o?.config)throw new Y({defaultError:J.INTERNAL.ECS_CONFIG_EMPTY});return this._cachedConfig=o,o.config}catch(e){throw n.reject(e),this._logger.error(`${e}`),e}}async fetchDefaultConfig(e,t){let n=`${this._isWBMediaClient?s2:o2}_${J2()}`,r={hosts:[PRe(this._acsProxy,t)],clientName:bSe,clientVersion:n,configsToFetch:[D9.Models.EcsConfigType.Default],getEcsParameters:()=>MRe.Resolved(e),initialAppActiveState:!0};return this._fetchConfig(r)}async fetchUserConfig(e,t,n){let r=`${this._isWBMediaClient?s2:o2}_${J2()}`,i=await n(),a=1e3*Xwe(i).exp,o={hosts:[PRe(this._acsProxy,t)],clientName:bSe,clientVersion:r,configsToFetch:[D9.Models.EcsConfigType.User],getEcsParameters:()=>MRe.Resolved(e),initialAppActiveState:!0,initialSkypeTokenData:{skypeToken:i,skypeTokenExpiration:a}};return this._fetchConfig(o)}get eTag(){return this._cachedConfig?.eTag??``}get sourceTag(){return this._sourceTag}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}dispose(){this._eventEmitter.removeAllListeners(),this._resetThrottlingTimeout(),this._resetEcsClient()}getConfigIds(e){return(this._cachedConfig?.config)?.ConfigIDs?.[e]}},IRe=class{constructor(e){this._telemetryLogManager=e,this._seq=0}sendAttemptEvent(e,t,n){this._seq++,this._telemetryLogManager.sendEvent({name:Q.acs_calling_config_fetched_attempt,tenant:d2,properties:{attemptTimestamp:e,ecsFetchType:t,correlationId:n,eventSeq:this._seq}})}sendSuccessEvent(e,t,n,r){let i=Date.now();this._seq++;let a=e===void 0?0:i-e;this._telemetryLogManager.sendEvent({name:Q.acs_calling_config_fetched_success,tenant:d2,properties:{...e===void 0?void 0:{attemptTimestamp:e},successTimestamp:i,deltaTimeInMs:a,ecsFetchType:t,correlationId:n,eventSeq:this._seq,ecsConfigIds_AcsCallingSDKWeb:r?.AcsCallingSDKWeb||``,ecsConfigIds_SkypeWebMedia:r?.SkypeWebMedia||``}})}sendFailureEvent(e,t,n,r){let i=Date.now();this._seq++;let a=e===void 0?0:i-e,o=r.message,s=K3(r);this._telemetryLogManager.sendEvent({name:Q.acs_calling_config_fetched_failure,tenant:d2,properties:{...e===void 0?void 0:{attemptTimestamp:e},failureTimestamp:i,deltaTimeInMs:a,ecsFetchType:t,correlationId:n,eventSeq:this._seq,failureReason:o,additionalDetails:{...s}}})}};function LRe(e,...t){Q2.merge(e,...t)}function RRe(e,t){let n={};try{n.CLRelease=H5.stackFactory.getVersion().build;let e=t8();n.BrowserName=e.name,n.BrowserEngine=e.engine,n.BrowserVersion=e.version,n.FormFactor=e.formFactor,n.IdentityType=$0.Consumer,n.Cloud=J0.Public,n.OSVer=`${n8()}-${lke()}`,t&&(n.Cloud=t.cloudType,n.IdentityType=t.identityType),n.CLRelease===`_TS_BUILD_VERSION_`?n.CLRelease=`9999.99`:n.CLRelease.match(/^\d+\.\d+\.\d+\.\d+$/)||delete n.CLRelease}catch(t){throw e.error(t),new Y({defaultError:J.CALL_STACK.SET_STACK_PARAMS,originalError:t})}return n}var O9=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},k9=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},A9=class{constructor(e,t,n,r,i,a,o,s,c=!1){if(this._baseStackDisposed=!1,this._userStackDisposed=!1,this._trouterStateChangedListenersRegistered=new Map,this._signalingAgentInitialized=!1,this._hardcodedEcsConfigApplied=!1,this._clientId=t,this.sdkDiagnosticInformation=r,this.logger=e.createChild(`CallStack`),this._telemetryLogManager=n,this._acsProxy=i,this._acsCustomRelayManager=a,this._vdi3Options=s,this._webcvProvider=new ELe,this._wasmvqeProvider=new jLe,this._isWBMediaClient=c,location.protocol!==`https:`&&location.protocol!==`file:`&&location.hostname!==`localhost`)throw new Y({defaultError:J.CALL_STACK.BAD_PROTOCOL});this._telemetryService=new TLe(this._telemetryLogManager),this._ecsTelemetryLogger=new IRe(n),this._ecsProvider=new t9(this.logger,this.sdkDiagnosticInformation,this._acsProxy),this._ecsClient=new FRe(this._isWBMediaClient,this.logger,this._acsProxy,`EcsClient`),this._videoEffectsStatusManager=new kLe,this._audioEffectsStatusManager=new ALe,o!==void 0&&(this._encodedStreamsWorkerProvider=new DLe(o))}getVdi3StateInfo(){return this._vdi3StateInfo}getClientId(){return this._clientId}getCaConfigBag(){return this._caConfigBag}getTrouterState(){let e=this._trouterService?.state()??this._shellTrouter?.state();return this.mapTsTrouterState(e)}getEcsConfigIds(){return this._ecsClientRdc?{AcsCallingSDKWeb:this._ecsClient?.getConfigIds(`AcsCallingSDKWeb`)??``,SkypeWebMedia:this._ecsClientRdc?.getConfigIds(`SkypeWebMedia`)??``}:{AcsCallingSDKWeb:this._ecsClient?.getConfigIds(`AcsCallingSDKWeb`)??``,SkypeWebMedia:this._ecsClient?.getConfigIds(`SkypeWebMedia`)??``}}isRegistered(){return this._trouterService?.isRegistered()??this._shellTrouter?.registeredState()??!1}onRegisteredChanged(e){this._trouterService?.onRegisteredChanged(e),this._shellTrouter?.on(`registeredChanged`,e)}offRegisteredChanged(e){this._trouterService?.offRegisteredChanged(e),this._shellTrouter?.off(`registeredChanged`,e)}onTrouterStateChanged(e){let t=(t,n)=>{e(this.mapTsTrouterState(t))};return this._trouterService?.onStateChanged(t),this._shellTrouter?.on(`stateChanged`,t),this._trouterStateChangedListenersRegistered.set(e,t),{listener:e,tsTrouterStateChangedListener:t}}offTrouterStateChanged(e){let t=this._trouterStateChangedListenersRegistered.get(e);if(t)return this._trouterService?.offStateChanged(t),this._shellTrouter?.off(`stateChanged`,t),this._trouterStateChangedListenersRegistered.delete(e),{listener:e,tsTrouterStateChangedListener:t}}mapTsTrouterState(e){let t=`Uninitialized`;if(e!==void 0)switch(e){case 0:t=`Unknown`;break;case 2:t=`Connected`;break;case 3:t=`Disconnected`;break;case 9:t=`Switching`}return t}get webcvProvider(){return this._webcvProvider}get wasmvqeProvider(){return this._wasmvqeProvider}get videoEffectsStatusManager(){return this._videoEffectsStatusManager}get audioEffectsStatusManager(){return this._audioEffectsStatusManager}async applyHardcodedEcsConfigAndSetStack(e,t){if(this._hardcodedEcsConfigApplied)return void this.logger.info(`Hardcoded ECS config already applied, skipping`);let n=Hwe();await this.updateConfig(n,t);let r=+new Date;await this._setStackConfig();let i=+new Date-r;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:K0(),operationName:e,durationInMs:i,operationPayload:{},resultCategories:[`Success`],resultSignature:200}),this._hardcodedEcsConfigApplied=!0}async createStackBase(e){if(this._createStackBaseWaitPromise)return this._createStackBaseWaitPromise;this._baseStackDisposed=!1;let t=new Promise((async(t,n)=>{try{let n=this._getBaseStackConfig();if(this._vdi3StateInfo={supported:PLe(),requested:!1,enabled:!1},this._vdi3StateInfo.supported&&!0===this._vdi3Options?.enabled){this._vdi3StateInfo.requested=!0,this._shellTrouter&&await this._shellTrouter.dispose(),this._shellTrouter=new WLe;let e=FLe(this.logger,this._vdi3Options);e.vdi3Config&&(e.vdi3Config.shellTrouter=this._shellTrouter.instance);let t=await H5.stackFactory.buildBaseStack({stackType:1,...n,...e});if(this._proxyReferenceManager=c9.create(this.logger),this._tsStack=this._proxyReferenceManager.create(t),this._vdi3StateInfo.enabled=!0,Z().vdi3.fetchEcs)try{let e=await this._tsStack?.getEcsProviderAsync?.();this._ecsQueryParametersRdc=JSON.parse(await e?.getEcsQueryParameters()??`null`)||void 0,this._ecsQueryParametersRdc&&(this._ecsQueryParametersRdc=NRe(this._ecsQueryParametersRdc),this._ecsClientRdc=new FRe(this._isWBMediaClient,this.logger,this._acsProxy,`EcsClientRdc`))}catch(e){this.logger.error(`Failed to get query parameters ${e}`)}}else this._tsStack=await H5.stackFactory.buildBaseStack({stackType:0,...n});let r=async(e,t,n)=>{if(e!==void 0||t!==void 0)try{if(e!==void 0&&e===t){await this.updateConfig(e,this._caConfigBag);let t=Z();UG.updateConfig(t?.errors,this.logger)}else await this.updateConfigForVdi(e,t,this._caConfigBag);t!==void 0&&(await this._setStackConfig(),this._checkEcsConfigValue(t,{attemptTimestamp:void 0,ecsFetchType:n,correlationId:``})),this._ecsTelemetryLogger.sendSuccessEvent(void 0,n,``,this.getEcsConfigIds())}catch(e){let t=new Y({defaultError:J.CALL_STACK.PARSE_CONFIG,originalError:e});this._ecsTelemetryLogger.sendFailureEvent(void 0,n,``,t)}};this._ecsClientRdc?(this._ecsClient.on(`configUpdated`,(async e=>{await r(e.config,void 0,e.fetchType)})),this._ecsClientRdc.on(`configUpdated`,(async e=>{await r(void 0,e.config,e.fetchType)}))):this._ecsClient.on(`configUpdated`,(async e=>{await r(e.config,e.config,e.fetchType)})),await this.initializeEcsBase(e),await this._setStackConfig(),t(this._tsStack)}catch(e){n(e)}}));try{this._createStackBaseWaitPromise=n3((()=>t),YSe);let e=await this._createStackBaseWaitPromise;return this.logger.log(`Base stack init success`),e}catch(e){throw await this.disposeBaseStack(),e.code===PG?new Y({defaultError:J.CALL_STACK.BASE_STACK_INIT_TIMEOUT}):new Y({defaultError:J.CALL_STACK.BASE_STACK_INIT_FAILED,originalError:e})}}async createMediaSdkStackBase(e,t,n){if(this._createMediaSdkStackBaseWaitPromise)return this._createMediaSdkStackBaseWaitPromise;this._baseStackDisposed=!1;let r=new Promise((async(r,i)=>{try{let i=this._getMediaStackConfig(e),a=+new Date;this._tsStack=await H5.stackFactory.build(i);let o=+new Date-a;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:K0(),operationName:`BuildMediaStack`,durationInMs:o,operationPayload:{},resultCategories:[`Success`],resultSignature:200});let s=async(e,t,n)=>{if(e!==void 0||t!==void 0)try{e!==void 0&&e===t?await this.updateConfig(e,this._caConfigBag):await this.updateConfigForVdi(e,t,this._caConfigBag),t!==void 0&&(await this._setStackConfig(),this._checkEcsConfigValue(t,{attemptTimestamp:void 0,ecsFetchType:n,correlationId:``})),this._ecsTelemetryLogger.sendSuccessEvent(void 0,n,``,this.getEcsConfigIds())}catch(e){let t=new Y({defaultError:J.CALL_STACK.PARSE_CONFIG,originalError:e});this._ecsTelemetryLogger.sendFailureEvent(void 0,n,``,t)}};if(this._ecsClient.on(`configUpdated`,(async e=>{await s(e.config,e.config,e.fetchType)})),!n){await this.applyHardcodedEcsConfigAndSetStack(`SetStackConfigBase`,t);let e=+new Date;this.initializeEcsBase(t).then((async()=>{let t=+new Date-e;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:K0(),operationName:`InitializeEcsBase`,durationInMs:t,operationPayload:{},resultCategories:[`Success`],resultSignature:200}),Z().waimeabay.backgroundEcsFetchTsStackSet&&await this._setStackConfig()})).catch((t=>{let n=+new Date-e;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:K0(),operationName:`InitializeEcsBase`,durationInMs:n,operationPayload:{},resultCategories:[`Failure`],resultSignature:500}),this.logger.warn(`Background ECS fetch failed`,t)}))}r(this._tsStack)}catch(e){i(e)}}));try{this._createMediaSdkStackBaseWaitPromise=n3((()=>r),YSe);let e=await this._createMediaSdkStackBaseWaitPromise;return this.logger.log(`Base stack init success`),e}catch(e){throw await this.disposeBaseStack(),e.code===PG?new Y({defaultError:J.CALL_STACK.BASE_STACK_INIT_TIMEOUT}):new Y({defaultError:J.CALL_STACK.BASE_STACK_INIT_FAILED,originalError:e})}}async initializeStackForUser(e,t){if(this._initializeStackForUserWaitPromise)return this._initializeStackForUserWaitPromise;this._caConfigBag=t,this._tsStack=await this.createStackBase(t),this._userStackDisposed=!1;let n=new Promise((async(n,o)=>{try{this._tsStack?(this._ecsProvider=new t9(this.logger,this.sdkDiagnosticInformation,this._acsProxy),await this.initializeEcsForUser(t,e),z6.overrideDefaultLogDump(),U6(this._tsStack)||(Z().calling.doNotWaitForTrouter?this._initTrouter(e).then((()=>{this.logger.log(`Signaling initialized successfully.`)})).catch((()=>{this.logger.warn(J.CALL_STACK.SIGNALING_UNINITIALIZED.message)})):(await this._initTrouter(e),this.logger.log(`Signaling initialized successfully.`))),await r(e,this._tsStack),await i(e,this._tsStack),await a(this._tsStack),n(this._tsStack)):(this.logger.error(`Base stack failed to create`),o(new Y({defaultError:J.CALL_STACK.USER_STACK_NO_BASE_STACK})))}catch(e){o(e)}})),r=async(e,t)=>{try{if(await t.initializeMediaAgent({httpRequestDispatcher:this.getRequestDispatcher(),tokenProvider:e,relayManager:this.getCustomRelayManager(),configProvider:{getSkypeConfig:()=>Promise.resolve({}),getRelayConfig:()=>{let e=this._ecsProvider.getMdnTrapSettings();return Promise.resolve(e)}},appStateProvider:this._getAppStateProvider(),clientInformation:this._ecsProvider.getJsCsaConfig().clientInformation}),Z().calling.platformSupportValidation&&await t.getPlatformSupportLevelAsync()===0){let e=new Y({defaultError:J.CALL_STACK.USER_STACK_MEDIA_INIT_FAILED_PLATFORM_NOT_SUPPORTED});throw this.logger.error(e.message),e}}catch(e){throw this.logger.error(`Failed to initialize media stack`,e),new Y({defaultError:J.CALL_STACK.USER_STACK_MEDIA_INIT_FAILED,originalError:e})}},i=async(e,t)=>{try{let n=U6(t),r={signalingAgentConfig:this._getSignalingConfig(e),...n?{trouterSettings:CLe(this._ecsProvider),trouterService:{}}:{trouterService:this._trouterService}};this._signalingAgentInitialized?(await t.updateSignalingAgentProviderConfig(r),this.logger.log(`Signaling agent updated successfully`)):(await t.initializeSignalingAgentProvider(r),this._signalingAgentInitialized=!0,this.logger.log(`Signaling agent initialized successfully`)),n&&(await this._shellTrouter?.initialize(),this.logger.log(`Signaling initialized successfully for VDI3.`))}catch(e){throw this.logger.error(`Failed to initialize signaling agent`,e),new Y({defaultError:J.CALL_STACK.USER_STACK_SIGNALING_INIT_FAILED,originalError:e})}},a=async e=>{try{await e.init(),await this._setStackConfig()}catch(e){throw this.logger.error(`Failed to initialize calling stack`,e),new Y({defaultError:J.CALL_STACK.USER_STACK_INTERNAL_INIT_FAILED,originalError:e})}};try{this._initializeStackForUserWaitPromise=n3((()=>n),XSe);let e=await this._initializeStackForUserWaitPromise;return this.sendStackInitEvent(!0),this.logger.log(`User stack init success`),e}catch(e){throw await this.disposeUserStack(),e.code===PG?(this.sendStackInitEvent(!1,`User stack init timeout`,e),new Y({defaultError:J.CALL_STACK.USER_STACK_INIT_TIMEOUT})):!(e instanceof Y)&&this.getTrouterState()===`Uninitialized`?new Y({defaultError:J.CALL_STACK.SIGNALING_UNINITIALIZED,originalError:e}):(this.sendStackInitEvent(!1,`User stack init failed`,e),new Y({defaultError:J.CALL_STACK.USER_STACK_INIT_FAILED,originalError:e}))}}async initializeMediaSdkStackForUser(e,t){if(this._caConfigBag=t,this._initializeMediaStackForUserWaitPromise)return this._initializeMediaStackForUserWaitPromise;this._tsStack=await this.createMediaSdkStackBase(e,t,!0);let n=this._getMediaStackConfig(e);this._tsStack.initializeMediaAgent(n.mediaAgentFactoryConfig),this._userStackDisposed=!1;let r=new Promise((async(n,r)=>{try{if(this._tsStack){await this.applyHardcodedEcsConfigAndSetStack(`SetStackConfigUser`,t);let r=+new Date;this.initializeEcsForUser(t,e).then((async()=>{let e=+new Date-r;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:K0(),operationName:`InitializeEcsForUser`,durationInMs:e,operationPayload:{},resultCategories:[`Success`],resultSignature:200}),z6.overrideDefaultLogDump(),Z().waimeabay.backgroundEcsFetchTsStackSet&&await this._setStackConfig()})).catch((e=>{let t=+new Date-r;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:K0(),operationName:`InitializeEcsForUser`,durationInMs:t,operationPayload:{},resultCategories:[`Failure`],resultSignature:500}),this.logger.warn(`Background user ECS fetch failed`,e)})),this.logger.log(`ECS initialized successfully.`);let a=+new Date;await i(this._tsStack);let o=+new Date-a;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:K0(),operationName:`InitializeTsStack`,durationInMs:o,operationPayload:{},resultCategories:[`Success`],resultSignature:200}),n(this._tsStack)}else this.logger.error(`Media SDK Base stack failed to create`),r(new Y({defaultError:J.CALL_STACK.USER_STACK_NO_BASE_STACK}))}catch(e){r(e)}})),i=async e=>{try{await e.init(),await this._setStackConfig()}catch(e){throw this.logger.error(`Failed to initialize Media SDK stack`,e),new Y({defaultError:J.CALL_STACK.USER_STACK_INTERNAL_INIT_FAILED,originalError:e})}};try{this._initializeMediaStackForUserWaitPromise=n3((()=>r),XSe);let e=await this._initializeMediaStackForUserWaitPromise;return this.sendStackInitEvent(!0),this.logger.log(`Media SDK User stack init success`),e}catch(e){throw await this.disposeUserStack(),e.code===PG?(this.sendStackInitEvent(!1,`Media SDK user stack init timeout`,e),new Y({defaultError:J.CALL_STACK.USER_STACK_INIT_TIMEOUT})):(this.sendStackInitEvent(!1,`Media SDK user stack init failed`,e),new Y({defaultError:J.CALL_STACK.USER_STACK_INIT_FAILED,originalError:e}))}}getRequestDispatcher(){return this._acsProxy.hasProxyUrl()?(this.logger.info(`Using custom proxy for network requests (non media)`),new OLe(this.logger,this._acsProxy)):Z().telemetry.sendNetworkInfo?new OLe(this.logger):new H5.HttpRequestDispatcherImplementation(this.logger)}async updateConfig(e,t){e?.Headers?.CountryCode&&this.updateEmergencyCallCountry(e?.Headers?.CountryCode);try{Vwe(e),this._ecsProvider.setConfig(t,e),Uwe(this._ecsProvider.getJamaSettings()),this._fetchedEcsConfigValue=e;let n=Z();UG.updateConfig(n?.errors,this.logger)}catch(e){throw this.logger.warn(`Unable to update ECS configuration ${e}`),new Y({defaultError:J.CALL_STACK.PARSE_CONFIG,originalError:e})}}async updateConfigForVdi(e,t,n){e?.Headers?.CountryCode&&this.updateEmergencyCallCountry(e?.Headers?.CountryCode);let r=t=>{LRe(t,ILe);let n=e?.AcsCallingSDKWeb?.vdi3?.customEcsConfig;if(n)try{LRe(e,JSON.parse(n))}catch(e){this.logger.error(`Failed to parse customEcsConfig: ${e}`)}};try{e&&(r(e),Vwe(e)),t&&(r(t),this._ecsProvider.setConfig(n,t),Uwe(this._ecsProvider.getJamaSettings()),this._fetchedEcsConfigValue=t)}catch(e){throw this.logger.warn(`Unable to update ECS configuration ${e}`),new Y({defaultError:J.CALL_STACK.PARSE_CONFIG,originalError:e})}}async _setStackConfig(){let e=Date.now();try{this._tsStack&&this._fetchedEcsConfigValue&&Object.keys(this._fetchedEcsConfigValue).length>0&&(this.logger.info(`Setting ECS configuration on the calling stack.`),await(await this._tsStack?.getEcsProviderAsync?.())?.setEcsConfig({ecsBlob:JSON.stringify(this._fetchedEcsConfigValue),userIdentity:``,etag:this._ecsClient.eTag}))}catch(t){let n=new Y({defaultError:J.CALL_STACK.SET_STACK_PARAMS,originalError:t}),r=Date.now(),i=e===void 0?0:r-e,a=n.message,o=K3(n);this.logger.warn(`Unable to set ECS configuration on the calling stack`),this._telemetryLogManager.sendEvent({name:Q.acs_calling_config_fetched_failure,tenant:d2,properties:{...e===void 0?void 0:{attemptTimestamp:e},failureTimestamp:r,deltaTimeInMs:i,failureReason:a,additionalDetails:{...o}}})}}_checkEcsConfigValue(e,t){let{attemptTimestamp:n,correlationId:r,ecsFetchType:i}=t;try{t9.assertConfigs(e)}catch(e){this.logger.error(`ECS config assertion failed: ${e?.message??`Unknown error`}`),this._ecsTelemetryLogger.sendFailureEvent(n,i,r,e)}}async initializeEcsBase(e){let t=Date.now(),n=K0();this._ecsTelemetryLogger.sendAttemptEvent(t,E9.Default,n);let r=J.CALL_STACK.FETCH_CONFIG;try{let i=await this._ecsClient.fetchDefaultConfig(RRe(this.logger,e),e);this.logger.info(`Fetched base settings from ECS.`);let a=i;if(U6(this._tsStack)&&this._ecsClientRdc&&this._ecsQueryParametersRdc){let t=await this._ecsClientRdc.fetchDefaultConfig(this._ecsQueryParametersRdc,e);a=t,r=J.CALL_STACK.PARSE_CONFIG,await this.updateConfigForVdi(i,t,e)}else r=J.CALL_STACK.PARSE_CONFIG,await this.updateConfig(i,e);this._ecsTelemetryLogger.sendSuccessEvent(t,E9.Default,n,this.getEcsConfigIds()),this._checkEcsConfigValue(a,{attemptTimestamp:t,correlationId:n,ecsFetchType:E9.Default})}catch(i){this.logger.warn(`Failed to fetch base settings. Stack will initialize with default settings`,i),this._ecsProvider.setConfig(e,void 0);let a=new Y({defaultError:r,originalError:i});this._ecsTelemetryLogger.sendFailureEvent(t,E9.Default,n,a)}}async initializeEcsForUser(e,t){let n=Date.now(),r=K0();this._ecsTelemetryLogger.sendAttemptEvent(n,E9.User,r);let i=J.CALL_STACK.FETCH_CONFIG;try{let a=await this._ecsClient.fetchUserConfig(RRe(this.logger,e),e,t);this.logger.info(`Fetched user settings from ECS.`);let o=a;if(U6(this._tsStack)&&this._ecsClientRdc&&this._ecsQueryParametersRdc){let n=await this._ecsClientRdc.fetchUserConfig(this._ecsQueryParametersRdc,e,t);o=n,i=J.CALL_STACK.PARSE_CONFIG,await this.updateConfigForVdi(a,n,e)}else i=J.CALL_STACK.PARSE_CONFIG,await this.updateConfig(a,e),this._ecsTelemetryLogger.sendSuccessEvent(n,E9.User,r,this.getEcsConfigIds());this._ecsTelemetryLogger.sendSuccessEvent(n,E9.User,r,this.getEcsConfigIds()),this._checkEcsConfigValue(o,{attemptTimestamp:n,correlationId:r,ecsFetchType:E9.User})}catch(e){this.logger.warn(`Failed to fetch user settings.`,e);let t=new Y({defaultError:i,originalError:e});this._ecsTelemetryLogger.sendFailureEvent(n,E9.User,r,t)}}async getDeviceManager(){if(this._createMediaSdkStackBaseWaitPromise){let e=await this._createMediaSdkStackBaseWaitPromise;return this.logger.info(`Getting ts device manager from media sdk stack`),e.getDeviceManagerAsync()}if(this._createStackBaseWaitPromise){let e=await this._createStackBaseWaitPromise;return this.logger.info(`Getting ts device manager from stack`),e.getDeviceManagerAsync()}throw new Y({defaultError:J.CALL_STACK.GET_DM})}async disposeBaseStack(){if(!this._baseStackDisposed){if(this._tsStack)try{await this._tsStack.dispose(),this._tsStack=void 0}catch{this.logger.error(`Failed to dispose calling stack`)}this._proxyReferenceManager?.dispose(),this._ecsClient.dispose(),this._ecsClientRdc?.dispose(),this._createStackBaseWaitPromise=void 0,this._baseStackDisposed=!0,this.logger.info(`Base call stack disposed`)}}async disposeUserStack(e){if(!this._userStackDisposed){if(this._trouterService)try{this._trouterService.clearMessageHandlers(),this._trouterService.stop(e),this._trouterService=void 0}catch{this.logger.error(`Failed to dispose signaling`)}if(this._shellTrouter)try{await this._shellTrouter.dispose(),this._shellTrouter=void 0}catch{this.logger.error(`Failed to dispose shellTrouter`)}try{await this._tsStack?.disposeMediaAgent(K0())}catch{this.logger.error(`Failed to dispose media agent`)}this._initializeStackForUserWaitPromise=void 0,this._userStackDisposed=!0,this.logger.info(`User calling stack disposed`)}}updateEmergencyCallCountry(e){this._caConfigBag&&!this._caConfigBag.emergencyCountryCode&&!this._caConfigBag.IsUserEmergencyCountryCode&&e&&(this._caConfigBag.emergencyCountryCode=e)}async _initTrouter(e){let t=+new Date;try{this._trouterService=new wLe(this.logger,this._ecsProvider,(t=>e(t)),this._telemetryLogManager,this._acsProxy),t=+new Date;let n=await this._trouterService.start(),r=this._trouterService.getTrouterSettings();this.sendSignalingInitEvent(!0,+new Date-t,r.registrationId??``,r.sessionId,n.trouterRequestCompletionTimeDeltaMs,n.registrarRequestCompletionTimeDeltaMs);return}catch(e){throw this.sendSignalingInitEvent(!1,+new Date-t,``,``,void 0,void 0,e),e}}_getBaseStackConfig(){let e=this._getMediaProviderConfig(),t={clientInformation:this._ecsProvider.getClientInformation(),logger:this.logger,mediaSettings:e.mediaSettings,platformType:e8(),callSettings:{useLwjForAllCalls:!1},usePlatformSupportApi:!0,telemetryTenants:{media:`mediaAgent`,signaling:`signalingAgent`,tlePlayer:YCe},telemetryService:this._telemetryService,webcvProvider:this._webcvProvider,wasmVqeProvider:this._wasmvqeProvider};return this._encodedStreamsWorkerProvider!==void 0&&(t.encodedStreamsWorkerProvider=this._encodedStreamsWorkerProvider),t}_getMediaStackConfig(e){return{stackType:2,mediaAgentFactoryConfig:{logger:this.logger,tokenProvider:e,configProvider:{getSkypeConfig:()=>Promise.resolve({}),getRelayConfig:()=>{let e=this._ecsProvider.getMdnTrapSettings();return Promise.resolve(e)}},settings:this._getMediaAgentConfig(),wasmVqeProvider:this._wasmvqeProvider,appStateProvider:this._getAppStateProvider()},signalingAgentConfig:this._getSignalingConfig(e),logger:this.logger,telemetryService:this._telemetryService,platformType:e8()}}_getSignalingConfig(e){let t={...this._ecsProvider.getJsCsaConfig(),httpRequestDispatcher:this.getRequestDispatcher(),telemetryManager:this._telemetryService.getCallingAdapter(),logger:this.logger,skypeToken:e,trouterServiceProvider:this._trouterService,ecsEtag:this._ecsClient.eTag};return this._caConfigBag?.emergencyCountryCode&&(t.emergencyCallCountry=this._caConfigBag?.emergencyCountryCode),t}_getMediaProviderConfig(){return{logger:this.logger,mediaSettings:this._getMediaAgentConfig()}}_getMediaAgentConfig(){return{...this._ecsProvider.getJamaSettings(),useOneDsLogger:!0,collectorUrl:q0.Public,telemetryTenants:{signaling:f2,gtcAudit:f2,media:p2,realtimeMedia:TCe,tlePlayer:ECe}}}_getAppStateProvider(){return{isOnline:()=>!0}}sendStackInitEvent(e,t,n){try{let r,i;n&&(r=n.message,i=K3(n)),this._telemetryLogManager.sendEvent({name:Q.acs_calling_stack_init,tenant:d2,properties:{success:e,reason:t,failureReason:r||`unknown`,additionalDetails:{...i}}})}catch{}}sendSignalingInitEvent(e,t,n,r,i,a,o){try{let s,c;o&&(s=o.message,c=K3(o)),this._telemetryLogManager.sendEvent({name:Q.acs_calling_signaling_init,tenant:d2,properties:{success:e,failureReason:s||`unknown`,timestampInfo:{deltaTimeInMs:t,deltaTimeInMsTrouterRequest:i,deltaTimeInMsRegistrarRequest:a},additionalDetails:{...c,registrationId:n,sessionId:r}}})}catch{}}getCustomRelayManager(){if(this._tsCustomRelayManager=this._acsCustomRelayManager.getTsRelayManager(),this._tsCustomRelayManager&&Z().calling.enableCustomTurnUsage)return this.logger.info(`Using custom relays for media traffic`),this._acsCustomRelayManager.customRelayManagerInUse=!0,this._tsCustomRelayManager}};O9([zG,k9(`design:type`,Object)],A9.prototype,`logger`,void 0),O9([GG(c4.CreateStackBase),k9(`design:type`,Function),k9(`design:paramtypes`,[Object]),k9(`design:returntype`,Promise)],A9.prototype,`createStackBase`,null),O9([GG(c4.CreateStackBase),k9(`design:type`,Function),k9(`design:paramtypes`,[Function,Object,Boolean]),k9(`design:returntype`,Promise)],A9.prototype,`createMediaSdkStackBase`,null),O9([GG(c4.InitializeStackForUser),k9(`design:type`,Function),k9(`design:paramtypes`,[Function,Object]),k9(`design:returntype`,Promise)],A9.prototype,`initializeStackForUser`,null),O9([GG(c4.InitializeMediaSdkStackForUser),k9(`design:type`,Function),k9(`design:paramtypes`,[Function,Object]),k9(`design:returntype`,Promise)],A9.prototype,`initializeMediaSdkStackForUser`,null),O9([GG(c4.GetDeviceManager),k9(`design:type`,Function),k9(`design:paramtypes`,[]),k9(`design:returntype`,Promise)],A9.prototype,`getDeviceManager`,null);var zRe=class{constructor(){this._eventEmitter=new w3.EventEmitter}notifyAll(e){this._eventEmitter.emit(e)}waitFor(e,t){return new Promise(((n,r)=>{let i=0,a=()=>{n(),clearTimeout(i)};this._eventEmitter.once(e,a),i=window.setTimeout((()=>{this._eventEmitter.off(e,a),r(Error(`timeout`))}),t)}))}},BRe=class{constructor(){this._deviceIdMapping=new Map,this._deviceId=1,this._keywords=Z().telemetry.deviceChangedEvents.piiSafeWords}getDeviceId(e){let t=this._deviceIdMapping.get(e);return t===void 0?(++this._deviceId,t=`${e.split(`:`)[0]??``}:${this._deviceId}`,this._deviceIdMapping.set(e,t),t):t}scrubDeviceLabel(e){return VRe(e,this._keywords)}};function VRe(e,t){if(!e)return``;if(e.length<3)return e;let n=[],r=e.match(/\(([0-9a-zA-Z]+:[0-9a-zA-Z]+)\)/);r&&n.push(r[1]);try{if(!t?.length)return`no_keywords`;{let r=RegExp(`(${t.join(`|`)})`,`gi`),i=r.exec(e);for(;i;)n.push(i[1]),i=r.exec(e)}}catch(e){n.push(`Error: ${(e=>Q2.isString(e)?e:e?.message??``)(e)}`)}return n.length===0?`unknown`:n.join(` `)}var j9=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},M9=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},N9=class{constructor(e,t,n,r=!1,i){this._callStack=t,this._isWBMediaClient=r,this._videoDevices=[],this._audioDevices=[],this._disposed=!1,this._tsDeviceTypeToAudioDeviceType={2:`Microphone`,3:`Speaker`,4:`CompositeAudioDevice`},this.logger=e.createChild(`DeviceManager`),this._telemetryLogManager=n,this._eventEmitter=new S6(this.logger),this._browserInfo=t8(),this._safariVideoPermissionState=`unknown`,this._combinedDevicePermission=new Map,this._deviceInfoMapper=new BRe,this._deviceSelectionNotifications=new zRe,this._permissionChangedTasks=Promise.resolve(),this._shouldEnumerateDevices=i??!0}get telemetryLogManager(){return this._telemetryLogManager}get isWBMediaClient(){return this._isWBMediaClient}get shouldEnumerateDevices(){return this._shouldEnumerateDevices}getRawDeviceMediaStream(e){let t=K0(),n=+new Date;if(this.sendRawMediaEvent({eventName:Q.acs_calling_get_raw_device_media_stream,correlationId:t,kindOfEvent:`attempt`,mediaType:e,timestampInfo:``,additionalDetails:``}),!this._tsDeviceManager?.getRawDeviceMediaStream){let r=new Y({defaultError:J.DEVICE_MANAGER.GET_MEDIA_STREAM_TRACK});this.logger.error(`Failed to get raw device stream track`);let i=+new Date;throw this.sendRawMediaEvent({eventName:Q.acs_calling_get_raw_device_media_stream,correlationId:t,kindOfEvent:`failure`,mediaType:e,timestampInfo:{deltaTimeInMs:i-n},additionalDetails:{failureReason:r.message||``,code:r.code,subCode:r.subCode,...K3(r)}}),r}let r;try{r=this._tsDeviceManager?.getRawDeviceMediaStream(e);let i=+new Date;return this.sendRawMediaEvent({eventName:Q.acs_calling_get_raw_device_media_stream,correlationId:t,kindOfEvent:`success`,mediaType:e,timestampInfo:{deltaTimeInMs:i-n},additionalDetails:``}),r}catch(r){let i=new Y({defaultError:J.DEVICE_MANAGER.GET_MEDIA_STREAM_DEVICE_UNAVAILABLE,originalError:r}),a=W3(r,this.isWBMediaClient,i);this.logger.error(`Failed to get raw device stream: `,a.message);let o=+new Date;throw this.sendRawMediaEvent({eventName:Q.acs_calling_get_raw_device_media_stream,correlationId:t,kindOfEvent:`failure`,mediaType:e,timestampInfo:{deltaTimeInMs:o-n},additionalDetails:{failureReason:a.message||``,code:a.code,subCode:a.subCode,...K3(a)}}),a}}getClientId(){return this._callStack.getClientId()}async getDeviceManager(){if(this._tsDeviceManager)return this._tsDeviceManager;let e=+new Date,t=K0();try{this.sendGetDeviceManagerEvent({eventName:Q.acs_calling_get_device_manager,kindOfEvent:`attempt`,timestampInfo:``,additionalDetails:``});let n=+new Date;if(this.isWBMediaClient){await this._callStack.createMediaSdkStackBase();let e=+new Date-n;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:K0(),operationName:`CreateMediaStackBase`,durationInMs:e,operationPayload:{},resultCategories:[`Success`],resultSignature:200})}else await this._callStack.createStackBase();let r=+new Date;if(this._tsDeviceManager=await this._callStack.getDeviceManager(),this.isWBMediaClient){let e=+new Date-r;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:K0(),operationName:`GetTsDeviceManager`,durationInMs:e,operationPayload:{},resultCategories:[`Success`],resultSignature:200})}if(this._shouldEnumerateDevices){let e=+new Date;try{let t=await this.enumerateDevicesAsync();if(this.isWBMediaClient){let n=+new Date-e;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:K0(),operationName:`EnumerateDevices`,durationInMs:n,operationPayload:{deviceCount:t.length},resultCategories:[`Success`],resultSignature:200})}this.logger.info(`tsDevicesList:${JSON.stringify(t)}`),t.forEach((e=>{if(e.kind===1){let t=e;this._videoDevices.push(new L6(t.label,t.id,`UsbCamera`,this))}else if(e.kind===2||e.kind===3){let t=e,n=new Y6(t.label,t.id,t.isSystemDefault,this._tsDeviceTypeToAudioDeviceType[t.kind],this);this._audioDevices.push(n)}}))}catch(t){if(this.isWBMediaClient){let n=+new Date-e,r=new Y({defaultError:J.DEVICE_MANAGER.DEVICE_ENUMERATING_FAIL,originalError:t});this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:K0(),operationName:`EnumerateDevices`,durationInMs:n,operationPayload:{...K3(r).communicationServicesError},resultCategories:r.resultCategories,resultSignature:500})}if(!1===Z().calling.ignoreEnumerateDevicesError)throw`Ignore enumerateDevicesError ${t}`}let t=+new Date,n=await this._tsDeviceManager.getSelectedDevicesAsync?.();if(this.isWBMediaClient){let e=+new Date-t;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:K0(),operationName:`GetSelectedDevices`,durationInMs:e,operationPayload:{hasMicrophone:!!n?.microphone,hasSpeaker:!!n?.speaker},resultCategories:[`Success`],resultSignature:200})}n&&(this._selectedMicrophone=this._audioDevices.find((e=>e.id===n.microphone)),this._selectedSpeaker=this._audioDevices.find((e=>e.id===n.speaker)))}else this.logger.info(`Skipping device enumeration (enumerateDevices is disabled)`);if(this._dmDevicesChangedSub=this._tsDeviceManager.on(`devicesChanged`,(async()=>{try{await this.syncDeviceList(await this.enumerateDevicesAsync()),await this.checkForSelectedDevicesChanges()}catch(t){this.logger.warn(`Unable to handle devicesChanged, error=${t?.message}, code=${t?.code}`);let n=+new Date;this.sendGetDeviceManagerEvent({eventName:Q.acs_calling_get_device_manager,kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:n-e},additionalDetails:{failureReason:t?.message,code:t?.code,...K3(t),context:`devicesChanged`}})}})),Z().calling.devicePermissions.getCurrentState){let e=+new Date,t=await this._tsDeviceManager?.getPermissionStateAsync?.(`microphone`,``),n=await this._tsDeviceManager?.getPermissionStateAsync?.(`camera`,``);if(this.isWBMediaClient){let r=+new Date-e;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:K0(),operationName:`GetPermissionState`,durationInMs:r,operationPayload:{microphoneState:String(t??`undefined`),cameraState:String(n??`undefined`)},resultCategories:[`Success`],resultSignature:200})}this._audioDevicePermission=P4(t,this.logger),this._videoDevicePermission=P4(n,this.logger)}this.logger.info(`Initial permission state audio:`,this._audioDevicePermission,`video:`,this._videoDevicePermission),this._dmDevicesPermissionChangedSub=this._tsDeviceManager.on(`onPermissionStateChanged`,(()=>{this._permissionChangedTasks=this._permissionChangedTasks.then((()=>this.permissionsChanged().catch(A4)))}));let i=+new Date-e;this.sendGetDeviceManagerEvent({eventName:Q.acs_calling_get_device_manager,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:i},additionalDetails:``}),this.isWBMediaClient&&this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`GetDeviceManager`,durationInMs:i,operationPayload:{videoDeviceCount:this._videoDevices.length,audioDeviceCount:this._audioDevices.length},resultCategories:[`Success`],resultSignature:200})}catch(n){let r=new Y({defaultError:J.DEVICE_MANAGER.GET_DM,originalError:n});this.logger.error(r.message);let i=+new Date-e;throw this.sendGetDeviceManagerEvent({eventName:Q.acs_calling_get_device_manager,kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:i},additionalDetails:{failureReason:r.message,code:r.code,...K3(r)}}),this.isWBMediaClient&&this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`GetDeviceManager`,durationInMs:i,operationPayload:{...K3(r).communicationServicesError},resultCategories:r.resultCategories,resultSignature:500}),r}return this._tsDeviceManager}getTsDeviceManager(){if(!this._tsDeviceManager)throw new Y({defaultError:J.DEVICE_MANAGER.ACCESS_DM});return this._tsDeviceManager}getSafariPermissionState(){return this._browserInfo.engine===`Safari`?this._safariVideoPermissionState:`unknown`}getAcsResourceId(){return this._callStack?.getCaConfigBag()?.acsResourceId}getAudioDevicePermission(){return this._audioDevicePermission}getVideoDevicePermission(){return this._videoDevicePermission}get callStackWebCvProvider(){return this._callStack.webcvProvider}get callStackWasmVqeProvider(){return this._callStack.wasmvqeProvider}get callStackVideoEffectsStatusManager(){return this._callStack.videoEffectsStatusManager}get callStackAudioEffectsStatusManager(){return this._callStack.audioEffectsStatusManager}get deviceInfoMapper(){return this._deviceInfoMapper}getEnvironmentInfoInternal(){return this._environmentInfo||=hke(),this._environmentInfo}getOSNameInternal(){return n8()}dispose(){this._disposed=!0,this._dmDevicesChangedSub&&this._dmDevicesChangedSub.dispose(),this._dmDevicesPermissionChangedSub&&this._dmDevicesPermissionChangedSub.dispose(),this._dmDevicesPermissionChangedSub=void 0,this._dmDevicesChangedSub=void 0,this._eventEmitter.removeAllListeners(),this._tsDeviceManager=void 0}on(e,t){if(e!==`videoDevicesUpdated`&&e!==`audioDevicesUpdated`&&e!==`selectedMicrophoneChanged`&&e!==`selectedSpeakerChanged`)throw new Y({defaultError:J.DEVICE_MANAGER.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if(e!==`videoDevicesUpdated`&&e!==`audioDevicesUpdated`&&e!==`selectedMicrophoneChanged`&&e!==`selectedSpeakerChanged`)throw new Y({defaultError:J.DEVICE_MANAGER.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}sendRawMediaEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:d2,properties:e})}catch{this.logger.debug(`Unable to send raw media telemetry`)}}sendGetDeviceManagerEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:d2,properties:e})}catch{this.logger.debug(`Unable to send get_device_manager telemetry`)}}async permissionsChanged(e,t){let n=this._audioDevicePermission,r=this._videoDevicePermission,i,a;if(Z().calling.devicePermissions.getCurrentState){let e=await this._tsDeviceManager?.getPermissionStateAsync?.(`microphone`,``),t=await this._tsDeviceManager?.getPermissionStateAsync?.(`camera`,``);i=P4(e,this.logger),a=P4(t,this.logger)}else i=n,a=r;this._audioDevicePermission=i||!!e?.audio,this._videoDevicePermission=a||!!e?.video,t&&(t.audio&&(this._audioDevicePermission=e?.audio??!1),t.video&&(this._videoDevicePermission=e?.video??!1)),n===this._audioDevicePermission&&r===this._videoDevicePermission||(this.logger.info(`permission state changed from audio: ${n}, video: ${r}\n to audio: ${this._audioDevicePermission}, video: ${this._videoDevicePermission}`),this._telemetryLogManager.sendEvent({name:Q.acs_calling_device_permission_changed,tenant:d2,properties:{previousAudioDevicePermission:this.nullHandler(n),previousVideoDevicePermission:this.nullHandler(r),newAudioDevicePermission:this.nullHandler(this._audioDevicePermission),newVideoDevicePermission:this.nullHandler(this._videoDevicePermission)}}))}async checkForSelectedDevicesChanges(){if(this.logger.info(`checkForSelectedDevicesChanges`),this._tsDeviceManager){let e=await this._tsDeviceManager.getSelectedDevicesAsync?.();e&&(e.microphone!==this._selectedMicrophone?.id&&(this._selectedMicrophone=this._audioDevices.find((t=>t.id===e.microphone)),this._eventEmitter.emit(`selectedMicrophoneChanged`),e.microphone!==void 0&&this._deviceSelectionNotifications.notifyAll(e.microphone)),e.speaker!==this._selectedSpeaker?.id&&(this._selectedSpeaker=this._audioDevices.find((t=>t.id===e.speaker)),this._eventEmitter.emit(`selectedSpeakerChanged`),e.speaker!==void 0&&this._deviceSelectionNotifications.notifyAll(e.speaker)))}else this.logger.warn(`DeviceManager is undefined, Unable to check selected devices`)}isACSDeviceEqualToTSDevice(e,t){return e.id===t.id}async syncDeviceList(e){if(!this._tsDeviceManager)throw new Y({defaultError:J.DEVICE_MANAGER.ACCESS_DM});if(this.logger.info(`syncDeviceList`),!this._shouldEnumerateDevices)return void this.logger.info(`Device enumeration disabled, skipping syncDeviceList`);e===void 0&&(e=await this.enumerateDevicesAsync());let t=[],n=[],r=[],i=[];e.map((e=>{if(e.kind===1){let n=this._videoDevices.find((t=>this.isACSDeviceEqualToTSDevice(t,e)));if(n)n.setName(e.label),n.setId(e.id),n.setDeviceType(`UsbCamera`);else{let n=new L6(e.label,e.id,`UsbCamera`,this);t.push(n),this._videoDevices.push(n)}}else if(e.kind===2||e.kind===3){let t=this._audioDevices.find((t=>this.isACSDeviceEqualToTSDevice(t,e)));if(t){let n=e;t.setName(n.label),t.setId(n.id),t.setIsSystemDefault(n.isSystemDefault),t.setDeviceType(this._tsDeviceTypeToAudioDeviceType[n.kind])}else{let t=new Y6(e.label,e.id,e.isSystemDefault,this._tsDeviceTypeToAudioDeviceType[e.kind],this);r.push(t),this._audioDevices.push(t)}}}));let a=t=>{let n=t.filter((t=>!e.find((e=>this.isACSDeviceEqualToTSDevice(t,e)))));return n.map((e=>{t.splice(t.indexOf(e),1)})),n};n=a(this._videoDevices),i=a(this._audioDevices),(t.length>0||n.length>0)&&this._eventEmitter.emit(`videoDevicesUpdated`,{added:t,removed:n}),(r.length>0||i.length>0)&&this._eventEmitter.emit(`audioDevicesUpdated`,{added:r,removed:i})}async enumerateDevicesAsync(){if(!this._tsDeviceManager)throw new Y({defaultError:J.DEVICE_MANAGER.ACCESS_DM});try{return await this._tsDeviceManager.enumerateDevicesAsync()}catch{throw new Y({defaultError:J.DEVICE_MANAGER.DEVICE_ENUMERATING_FAIL})}}get isSpeakerSelectionAvailable(){if(!this._tsDeviceManager)throw new Y({defaultError:J.DEVICE_MANAGER.ACCESS_DM});return this._tsDeviceManager.isAudioOutputSelectionSupported}get selectedMicrophone(){return this._selectedMicrophone}get selectedSpeaker(){return this._selectedSpeaker}async getCameras(){if(this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});return await this.syncDeviceList(),this._videoDevices}async getMicrophones(){if(this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});return await this.syncDeviceList(),this._audioDevices.filter((e=>e.deviceType===`Microphone`))}async getSpeakers(){if(this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});if(this.isSpeakerSelectionAvailable)return await this.syncDeviceList(),this._audioDevices.filter((e=>e.deviceType===`Speaker`));throw new Y({defaultError:J.DEVICE_MANAGER.SPEAKER_ENUMERATION_UNSUPPORTED})}async selectMicrophone(e){if(this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});if(!this._tsDeviceManager)throw new Y({defaultError:J.DEVICE_MANAGER.ACCESS_DM});if(!e||!e.id)throw new Y({defaultError:J.DEVICE_MANAGER.INVALID_DEVICE});if(e.id===`microphone:`)throw new Y({defaultError:J.DEVICE_MANAGER.DEVICE_NOT_SELECTABLE});if(this.logger.info(`selectMicrophone called`),this._selectedMicrophone?.id!==e.id){let t=Z().calling.deviceSelectionTimeoutInMs,n=this._deviceSelectionNotifications.waitFor(e.id,t),r=this._deviceInfoMapper.getDeviceId(e.id),i=this._deviceInfoMapper.scrubDeviceLabel(e.name),a=K0(),o=(e,t,n)=>{this.sendDeviceManagerEvent({eventName:Q.acs_calling_client_operations,operation:K7.deviceSelection,kindOfEvent:e,correlationId:a,timestampInfo:t===void 0?{}:{deltaTimeInMs:t},additionalDetails:n===void 0?``:{failureReason:n.message,code:n.code,...K3(n)},deviceSelection:{deviceId:r,deviceName:i,deviceType:`Microphone`}})};o(`attempt`);let s=Date.now();try{await this._tsDeviceManager.selectDevicesAsync?.({microphone:e.id}),await n.catch((t=>{if(this._selectedMicrophone?.id!==e.id)throw t})),o(`success`,Date.now()-s)}catch(e){let t;throw t=new Y(e?.message===`timeout`?{defaultError:J.DEVICE_MANAGER.SELECT_MICROPHONE_TIMEOUT}:{defaultError:J.DEVICE_MANAGER.SELECT_MICROPHONE_FAIL,originalError:e}),o(`failure`,Date.now()-s,t),t}}else this.logger.warn(`microphoneDevice is already active`)}async selectSpeaker(e){if(this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});let t=this.logger.createFnLogger(l4.SelectSpeaker);if(!this._tsDeviceManager)throw new Y({defaultError:J.DEVICE_MANAGER.ACCESS_DM});if(!this.isSpeakerSelectionAvailable)throw new Y({defaultError:J.DEVICE_MANAGER.SPEAKER_SELECTION_UNSUPPORTED});if(!e||!e.id)throw new Y({defaultError:J.DEVICE_MANAGER.INVALID_DEVICE});if(e.id===`speaker:`)throw new Y({defaultError:J.DEVICE_MANAGER.DEVICE_NOT_SELECTABLE});if(t.info(`selectSpeaker called`),this._selectedSpeaker?.id!==e.id){let t=Z().calling.deviceSelectionTimeoutInMs,n=this._deviceSelectionNotifications.waitFor(e.id,t),r=this._deviceInfoMapper.getDeviceId(e.id),i=this._deviceInfoMapper.scrubDeviceLabel(e.name),a=K0(),o=(e,t,n)=>{this.sendDeviceManagerEvent({eventName:Q.acs_calling_client_operations,operation:K7.deviceSelection,kindOfEvent:e,correlationId:a,timestampInfo:t===void 0?{}:{deltaTimeInMs:t},additionalDetails:n===void 0?``:{failureReason:n.message,code:n.code,...K3(n)},deviceSelection:{deviceId:r,deviceName:i,deviceType:`Speaker`}})};o(`attempt`);let s=Date.now();try{await this._tsDeviceManager.selectDevicesAsync?.({speaker:e.id}),await n.catch((t=>{if(this._selectedSpeaker?.id!==e.id)throw t})),o(`success`,Date.now()-s)}catch(e){let t;throw t=new Y(e?.message===`timeout`?{defaultError:J.DEVICE_MANAGER.SELECT_SPEAKER_TIMEOUT}:{defaultError:J.DEVICE_MANAGER.SELECT_SPEAKER_FAIL,originalError:e}),o(`failure`,Date.now()-s,t),t}}else t.warn(`device is already selected`)}async askDevicePermission(e){return this.getAskDevicePermissionPromise(e,x3.Public_App)}async startPreheatDevices(e){let{audio:t,video:n}=e,r=Date.now(),i=K0(),a=(e,a)=>{this.sendDeviceManagerEvent({eventName:Q.acs_calling_client_operations,operation:K7.startPreheatDevices,kindOfEvent:`failure`,audio:{preheat:t?.preheat||!1,timeoutInSec:t?.timeoutInSec||-1},video:{preheat:n?.preheat||!1,timeoutInSec:n?.timeoutInSec||-1},timestampInfo:{deltaTimeInMs:Date.now()-r},additionalDetails:{failureReason:e.message,code:e.code,subCode:e.subCode,...K3(e),context:a},correlationId:i})};try{if(this.sendDeviceManagerEvent({eventName:Q.acs_calling_client_operations,operation:K7.startPreheatDevices,kindOfEvent:`attempt`,audio:{preheat:t?.preheat||!1,timeoutInSec:t?.timeoutInSec||-1},video:{preheat:n?.preheat||!1,timeoutInSec:n?.timeoutInSec||-1},timestampInfo:{},additionalDetails:{},correlationId:i}),this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});if(!Z().calling.devicePermissions.isPreheatEnabled)throw new Y({defaultError:J.DEVICE_MANAGER.PREHEAT_DISABLED});if(!t?.preheat&&!n?.preheat||t?.preheat&&typeof t?.preheat!=`boolean`||n?.preheat&&typeof n?.preheat!=`boolean`||t?.timeoutInSec&&!t.preheat||n?.timeoutInSec&&!n?.preheat||t?.timeoutInSec&&isNaN(t?.timeoutInSec)||t?.timeoutInSec&&t?.timeoutInSec<=0||n?.timeoutInSec&&isNaN(n?.timeoutInSec)||n?.timeoutInSec&&n?.timeoutInSec<=0)throw new Y({defaultError:J.DEVICE_MANAGER.PREHEAT_INVALID_CONFIG});if(t?.preheat&&this._tsRawAudioStream)throw new Y({defaultError:J.DEVICE_MANAGER.AUDIO_ALREADY_PREHEATED});if(n?.preheat&&this._tsRawVideoStream)throw new Y({defaultError:J.DEVICE_MANAGER.VIDEO_ALREADY_PREHEATED})}catch(e){let a=new Y({defaultError:J.DEVICE_MANAGER.PREHEAT_FAIL,originalError:e});throw this.logger.error(a.message),this.sendDeviceManagerEvent({eventName:Q.acs_calling_client_operations,operation:K7.startPreheatDevices,kindOfEvent:`failure`,audio:{preheat:t?.preheat||!1,timeoutInSec:t?.timeoutInSec||-1},video:{preheat:n?.preheat||!1,timeoutInSec:n?.timeoutInSec||-1},timestampInfo:{deltaTimeInMs:Date.now()-r},additionalDetails:{failureReason:a.message,code:a.code,subCode:a.subCode,...K3(a)},correlationId:i}),a}try{if(!this._tsDeviceManager)throw new Y({defaultError:J.DEVICE_MANAGER.ACCESS_DM});let e=[];try{e=await this._tsDeviceManager.enumerateDevicesAsync()}catch(e){let t=new Y({defaultError:J.DEVICE_MANAGER.PREAHEAT_ENUMERATE_DEVICES_FAIL,originalError:e});throw this.logger.error(t.message),t}let o=!1,s=!1;if(t?.preheat){let t=e.filter((e=>e.kind===2)),n=e.filter((e=>e.kind===3));t[0]?.id!==`microphone:`&&n[0]?.id!==`speaker:`||(o=!0)}if(n?.preheat&&e.filter((e=>e.kind===1))[0]?.id===`camera:`&&(s=!0),o||s){let e=await this.getAskDevicePermissionPromise({audio:o,video:s},x3.StartPreheatDevices);if(o&&!e.audio)throw new Y({defaultError:J.DEVICE_MANAGER.AUDIO_PREHEAT_NO_PERMISSION});if(s&&!e.video)throw new Y({defaultError:J.DEVICE_MANAGER.VIDEO_PREHEAT_NO_PERMISSION})}if(t?.preheat){try{this._tsRawAudioStream=this.getRawDeviceMediaStream(0)}catch(e){let t=new Y({defaultError:J.DEVICE_MANAGER.PREHEAT_GET_DM_AUDIO_STREAM_FAIL,originalError:e});throw this.logger.error(t.message),t}this._tsRawAudioStream?.changed((()=>{this._tsRawAudioStream?.getMediaStream().catch((e=>{let t=new Y({defaultError:J.DEVICE_MANAGER.PREHEAT_GET_AUDIO_STREAM_FAIL,originalError:e}),n=W3(e,this.isWBMediaClient,t);this.logger.error(n.message),a(n,`changed event`)}))}));try{await this._tsRawAudioStream?.getMediaStream()}catch(e){let t=new Y({defaultError:J.DEVICE_MANAGER.PREHEAT_GET_AUDIO_STREAM_FAIL,originalError:e}),n=W3(e,this.isWBMediaClient,t);throw this.logger.error(n.message),n}t?.timeoutInSec&&t.timeoutInSec>0&&(this._preheatedAudioStreamTimeout=setTimeout((()=>{this._tsRawAudioStream?.dispose(),this._tsRawAudioStream=void 0}),1e3*t?.timeoutInSec))}if(n?.preheat){try{this._tsRawVideoStream=this.getRawDeviceMediaStream(1)}catch(e){let t=new Y({defaultError:J.DEVICE_MANAGER.PREHEAT_GET_DM_VIDEO_STREAM_FAIL,originalError:e});throw this.logger.error(t.message),t}this._tsRawVideoStream?.changed((()=>{this._tsRawVideoStream?.getMediaStream().catch((e=>{let t=new Y({defaultError:J.DEVICE_MANAGER.PREHEAT_GET_VIDEO_STREAM_FAIL,originalError:e});this.logger.error(t.message),a(t,`changed event`)}))}));try{await this._tsRawVideoStream?.getMediaStream()}catch(e){let t=new Y({defaultError:J.DEVICE_MANAGER.PREHEAT_GET_VIDEO_STREAM_FAIL,originalError:e});throw this.logger.error(t.message),t}n?.timeoutInSec&&n?.timeoutInSec>0&&(this._preheatedVideoStreamTimeout=setTimeout((()=>{this._tsRawVideoStream?.dispose(),this._tsRawVideoStream=void 0}),1e3*n?.timeoutInSec))}this.sendDeviceManagerEvent({eventName:Q.acs_calling_client_operations,operation:K7.startPreheatDevices,kindOfEvent:`success`,audio:{preheat:t?.preheat||!1,timeoutInSec:t?.timeoutInSec||-1},video:{preheat:n?.preheat||!1,timeoutInSec:n?.timeoutInSec||-1},timestampInfo:{deltaTimeInMs:Date.now()-r},additionalDetails:{},correlationId:i})}catch(e){if(t?.preheat)try{this._tsRawAudioStream?.dispose()}catch{}finally{this._tsRawAudioStream=void 0,this._preheatedAudioStreamTimeout&&=(clearTimeout(this._preheatedAudioStreamTimeout),void 0)}if(n?.preheat)try{this._tsRawVideoStream?.dispose()}catch{}finally{this._tsRawVideoStream=void 0,this._preheatedVideoStreamTimeout&&=(clearTimeout(this._preheatedVideoStreamTimeout),void 0)}let r=new Y({defaultError:J.DEVICE_MANAGER.PREHEAT_FAIL,originalError:e});throw this.logger.error(r.message),a(r,`api call`),r}}stopPreheatDevices(e){if(this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});let{audio:t,video:n}=e,r=Date.now(),i=K0();try{this.sendDeviceManagerEvent({eventName:Q.acs_calling_client_operations,operation:K7.stopPreheatDevices,kindOfEvent:`attempt`,audio:t||!1,video:n||!1,timestampInfo:{},additionalDetails:{},correlationId:i}),t&&(this._tsRawAudioStream?.dispose(),this._tsRawAudioStream=void 0,this._preheatedAudioStreamTimeout&&=(clearTimeout(this._preheatedAudioStreamTimeout),void 0)),n&&(this._tsRawVideoStream?.dispose(),this._tsRawVideoStream=void 0,this._preheatedVideoStreamTimeout&&=(clearTimeout(this._preheatedVideoStreamTimeout),void 0)),this.sendDeviceManagerEvent({eventName:Q.acs_calling_client_operations,operation:K7.stopPreheatDevices,kindOfEvent:`success`,audio:t||!1,video:n||!1,timestampInfo:{deltaTimeInMs:Date.now()-r},additionalDetails:{},correlationId:i})}catch(e){let a=new Y({defaultError:J.DEVICE_MANAGER.STOP_PREHEAT_FAIL,originalError:e});throw this.sendDeviceManagerEvent({eventName:Q.acs_calling_client_operations,operation:K7.stopPreheatDevices,kindOfEvent:`failure`,audio:t||!1,video:n||!1,timestampInfo:{deltaTimeInMs:Date.now()-r},additionalDetails:{failureReason:a.message,code:a.code,subCode:a.subCode,...K3(a)},correlationId:i}),a}}getAskDevicePermissionPromise(e,t){if(this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});let n={audio:!!e.audio,video:!!e.video};if(!e.audio&&!e.video)throw new Y({defaultError:J.DEVICE_MANAGER.ONE_PERMISSION_ATLEAST});let r=this.getKeyForConstrains(n),i=this._combinedDevicePermission.get(r);return i?this.logger.info(`askDevicePermission attempt: audio:${n.audio}, video:${n.video} on pending existing request ${N4(i)}`):(i=this.askDevicePermissionInternal(n,t),this._combinedDevicePermission.set(r,i),i.finally((()=>{this._combinedDevicePermission.delete(r)}))),i}getKeyForConstrains(e){return Object.keys(e).filter((t=>e[t])).toString()}async askDevicePermissionInternal(e,t){this.logger.info(`askDevicePermission attempt: audio:${e.audio}, video:${e.video}`);let n=K0(),r=+new Date;this.sendAskDevicePermissionEvent({eventName:Q.acs_calling_adp_attempt,correlationId:n,audioPermissionRequested:e.audio,videoPermissionRequested:e.video,cause:t});try{if(!this._tsDeviceManager)throw new Y({defaultError:J.DEVICE_MANAGER.ACCESS_DM});let i=[];if(Z().calling.devicePermissions.splitAskAudioVideo){this.logger.info(`askDevicePermission, split permission check`);let t=[];e.audio&&(this.logger.info(`askDevicePermission, split permission audio`),t.push(this._tsDeviceManager.askDevicePermission({audio:e.audio,video:!1}))),e.video&&t.push((async t=>new Promise(((n,r)=>{let i=async()=>{if(this.logger.info(`askDevicePermission, split permission video`),!this._tsDeviceManager){let e=`askDevicePermission, split permission video failed device manager not found`;this.logger.error(e),r(e);return}try{n(await this._tsDeviceManager.askDevicePermission({audio:!1,video:e.video}))}catch(e){r(e)}};t?window.setTimeout(i,t):i()})))(Z().calling.devicePermissions.timeoutInBetween));let n=await Promise.allSettled(t),r={audio:!1,video:!1};n.forEach((e=>{e.status===`fulfilled`&&e?.value&&(r={audio:r.audio||!!e?.value?.audio,video:r.video||!!e?.value?.video}),e.status===`rejected`&&e?.reason&&i.push(e.reason)}));let a=this._permissionChangedTasks.then((()=>this.permissionsChanged(r,e)));this._permissionChangedTasks=a,this._permissionChangedTasks.catch(A4),await a,this._safariVideoPermissionState=this._videoDevicePermission?`granted`:`denied`}else{let t=await this._tsDeviceManager.askDevicePermission({audio:e.audio,video:e.video}),n=this._permissionChangedTasks.then((()=>this.permissionsChanged(t,e)));this._permissionChangedTasks=n,this._permissionChangedTasks.catch(A4),await n}if(e?.audio&&!this._audioDevicePermission||e?.video&&!this._videoDevicePermission)this.sendAskDevicePermissionEvent({eventName:Q.acs_calling_adp_failure,correlationId:n,audioPermissionRequested:e.audio,videoPermissionRequested:e.video,audioPermissionGranted:this._audioDevicePermission,videoPermissionGranted:this._videoDevicePermission,cause:t},new Y({defaultError:J.DEVICE_MANAGER.PERMISSION_NOT_GRANTED_OR_FAILED,defaultErrorMessageArgs:[N4(i)]}));else{let i=+new Date;this.sendAskDevicePermissionEvent({eventName:Q.acs_calling_adp_success,correlationId:n,audioPermissionRequested:e.audio,videoPermissionRequested:e.video,audioPermissionGranted:this._audioDevicePermission,videoPermissionGranted:this._videoDevicePermission,deltaTimeInMs:i-r,cause:t})}}catch(i){let a=new Y({defaultError:J.DEVICE_MANAGER.ADP_FAIL,originalError:i}),o=+new Date;this.sendAskDevicePermissionEvent({eventName:Q.acs_calling_adp_failure,correlationId:n,audioPermissionRequested:e.audio,videoPermissionRequested:e.video,audioPermissionGranted:this._audioDevicePermission,videoPermissionGranted:this._videoDevicePermission,deltaTimeInMs:o-r,cause:t},a)}return{audio:!!this._audioDevicePermission,video:!!this._videoDevicePermission}}sendAskDevicePermissionEvent(e,t){try{let n,r,i;t&&(n=typeof t?.message==`string`?t?.message:void 0,r=K3(t)),e.deltaTimeInMs&&(i=e.deltaTimeInMs>25e3),this._telemetryLogManager.sendEvent({name:e.eventName,tenant:d2,properties:{audioPermissionGranted:this.nullHandler(e.audioPermissionGranted),videoPermissionGranted:this.nullHandler(e.videoPermissionGranted),audioPermissionRequested:e.audioPermissionRequested,videoPermissionRequested:e.videoPermissionRequested,correlationId:e.correlationId||``,failureReason:n||``,deltaTimeInMs:e.deltaTimeInMs||``,deltaTimeGreaterThanJAMATimeout:this.nullHandler(i),cause:e.cause||``,additionalDetails:{...r}}})}catch{this.logger.debug(`Unable to send audio video permission failure success telemtery`)}}sendDeviceManagerEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:d2,properties:e})}catch{this.logger.debug(`Unable to send device selection telemetry`)}}nullHandler(e){return e===void 0?``:e}};j9([zG,M9(`design:type`,Object)],N9.prototype,`logger`,void 0),j9([GG(l4.GetCameras),M9(`design:type`,Function),M9(`design:paramtypes`,[]),M9(`design:returntype`,Promise)],N9.prototype,`getCameras`,null),j9([GG(l4.GetMicrophones),M9(`design:type`,Function),M9(`design:paramtypes`,[]),M9(`design:returntype`,Promise)],N9.prototype,`getMicrophones`,null),j9([WG(l4.GetSpeakers),M9(`design:type`,Function),M9(`design:paramtypes`,[]),M9(`design:returntype`,Promise)],N9.prototype,`getSpeakers`,null),j9([GG(l4.SelectMicrophone),M9(`design:type`,Function),M9(`design:paramtypes`,[Object]),M9(`design:returntype`,Promise)],N9.prototype,`selectMicrophone`,null),j9([GG(l4.SelectSpeaker),M9(`design:type`,Function),M9(`design:paramtypes`,[Object]),M9(`design:returntype`,Promise)],N9.prototype,`selectSpeaker`,null),j9([GG(l4.AskDevicePermission),M9(`design:type`,Function),M9(`design:paramtypes`,[Object]),M9(`design:returntype`,Promise)],N9.prototype,`askDevicePermission`,null),j9([GG(l4.StartPreheatDevices),M9(`design:type`,Function),M9(`design:paramtypes`,[Object]),M9(`design:returntype`,Promise)],N9.prototype,`startPreheatDevices`,null),j9([WG(l4.StopPreheatDevices),M9(`design:type`,Function),M9(`design:paramtypes`,[Object]),M9(`design:returntype`,void 0)],N9.prototype,`stopPreheatDevices`,null);var HRe=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},P9=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},URe=class extends H7{get info(){return this._teamsCall.info}constructor(e){super(e,HG.TeamsIncomingCall),this._teamsCall=e}async accept(e){if(!R4(this._teamsCall.acsProxy,this._teamsCall.acsCustomRelayManager,!0))throw new Y({defaultError:J.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN});return await this._teamsCall.accept(e),this._teamsCall}};HRe([GG(o4.Accept),P9(`design:type`,Function),P9(`design:paramtypes`,[Object]),P9(`design:returntype`,Promise)],URe.prototype,`accept`,null);var F9=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},I9=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},L9=class extends R7{get info(){return this._info}constructor(e,t,n,r){super(e,t,n,r,VG.TeamsCall),this._musicOnHoldEnabled=!1,this._hasFetchedPolicies=!1,this._info=this.callInfo,this._isEmergencyCall=e.isEmergencyNumber,this._mtPolicyService=t.mtPolicyService}async startCallInternal(e,t,n,r,i,a,o){if(this.logger.info(`==> Emergency startCallInternal:TeamsCall.ts`),this._mtPolicyService&&this._mtPolicyService.isFetchUserPoliciesAndSettingsApplicable(!0,o)){this._mtPolicyService.userDialedNumber(Array.isArray(o)?o[0].phoneNumber:o.phoneNumber);let e=``,t=!0;try{this.logger.info(`Fetching Teams User policy from MiddleTier Service`);let e={policyUrlSuffix:Z().MiddleTier.policyUrlSuffixV2,userPolicies:[`EmergencyPolicies`],userProperties:[`evEnabled`,`PoliciesMetadata`]};await this._mtPolicyService.fetchUserPoliciesFromAcsMiddleTier(this.tsCall.callId,this._callAgent.getUserMri(),e)}catch(e){t=!1,this.logger.warn(`Fetching Teams user policy from ACS MiddleTier Service failed.\n Error message = ${e?.message}, code = ${e?.code}, subcode = ${e?.subCode}.\n Proceeding as normal pstn call`)}if(t){try{this.enforcePolicyAndLicenseRestrictions()}catch(e){this.handlePolicyAndLicenseRestrictionsFailure(e);return}try{this.logger.info(`Deriving emergency content from fetched policies and settings`),e=this._mtPolicyService.getEmergencyContent()}catch(e){this.logger.warn(`Error deriving emergency content from fetched policies and settings. \n Error message = ${e?.message}, code = ${e?.code}, subcode = ${e?.subCode}. Proceeding as normal pstn call`)}r&&(r.emergencyContent=e||``,r.isEmergency=e?.trim().length>0||!1,this._isEmergencyCall=r.isEmergency)}}if(o){let t=[];Array.isArray(o)?t=o:t.push(o),this._isEmergencyCall&&t.length==1&&(this.logger.info(`user dialed number (${t[0].phoneNumber}) resolved to actual emergency number (${this._mtPolicyService.getEmergencyNumber()} during startCall`),t[0]={phoneNumber:this._mtPolicyService.getEmergencyNumber()}),t.length>1&&await this.setupThreadIdWhenStartingGroupCall(t,e,r),t.forEach((e=>{this.tsCall.addParticipant(W2(e)).catch((()=>{this.logger.error(`Failed to add participant during call start`)}))})),this.logger.info(`Paticipant added during startCall`)}return this._allowBreakoutRoomJoin=Z().calling.breakoutRooms.enabled&&this._mtPolicyService.isBreakoutRoomsAllowed()&&!!n,this._allowIPAudio=this._mtPolicyService.isIPAudioAllowed(),this._allowIPVideo=this._mtPolicyService.isIPVideoAllowed(),super.startCallInternal(e,t,n,r,i,a)}dispose(){super.dispose(),this._extensibleApi.dispose()}get isEmergencyCall(){return this._isEmergencyCall}addParticipant(e,t){let n=+new Date,r=K0();this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.attempt,participantAddedOrRemoved:`add`,correlationId:r,timestampInfo:{attemptTimestamp:n},additionalDetails:{customContext:{userToUserPresent:!!t?.customContext?.userToUser,xHeadersPresent:!!t?.customContext?.xHeaders&&t?.customContext.xHeaders.length>0}}});try{$5(o4.AddParticipant,this.state),q2(e)}catch(e){let t=new Y({defaultError:J.IDENTIFIER.PARSE_INVALID_IDENTIFIER,originalError:e});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`add`,correlationId:r,timestampInfo:{deltaTimeInMs:+new Date-n},additionalDetails:{code:e.code,failureReason:e.message,...K3(t)}}),t}if(!R4(this.acsProxy,this.acsCustomRelayManager,!0)){let e=new Y({defaultError:J.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`add`,correlationId:r,timestampInfo:{deltaTimeInMs:+new Date-n},additionalDetails:{code:e.code,failureReason:e.message,...K3(e)}}),e}if(this._remoteParticipants.find((t=>W2(t.identifier)===W2(e)))){let t=new Y({defaultError:J.CALL.PARTICIPANT_ALREADY_IN_CALL,defaultErrorMessageArgs:[wG(e).kind]});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`add`,correlationId:r,timestampInfo:{deltaTimeInMs:+new Date-n},additionalDetails:{code:t.code,failureReason:t.message,...K3(t)}}),t}if(this.tsCall.threadId&&cTe(this.tsCall.threadId))try{if(this.IsTargetUserAllowed(e))throw new Y({defaultError:J.CALL_AGENT.UNSUPPORTED_TARGET_TYPE})}catch(e){throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`add`,correlationId:r,timestampInfo:{deltaTimeInMs:+new Date-n},additionalDetails:{code:e.code,failureReason:e.message,...K3(e)}}),this.logger.error(e),e}let i=this.getOrCreateRemoteParticipant(G2(W2(e))),a=``;return this.GetOrCreateGroupChatThread(!!t?.threadId,e,t).then((o=>{o&&((t??={}).threadId=o,a=o,this._info.setThreadId(o)),this.addParticipantToTsCall(e,a,t,i,r,n)})).catch((e=>{throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`add`,correlationId:r,timestampInfo:{deltaTimeInMs:+new Date-n},additionalDetails:{code:e.code,failureReason:e.message,...K3(e)}}),e})),i}async removeParticipant(e){let t=+new Date,n=K0();this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.attempt,participantAddedOrRemoved:`remove`,correlationId:n,timestampInfo:{attemptTimestamp:t}});try{$5(o4.RemoveParticipant,this.state),q2(e)}catch(e){let r=new Y({defaultError:J.IDENTIFIER.PARSE_INVALID_IDENTIFIER,originalError:e});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`remove`,correlationId:n,timestampInfo:{deltaTimeInMs:+new Date-t},additionalDetails:{code:e.code,failureReason:e.message,...K3(r)}}),r}let r=this._remoteParticipants.find((t=>W2(t.identifier)===W2(e)));if(!r){let r=new Y({defaultError:J.CALL.PARTICIPANT_NOT_IN_CALL,originalError:[wG(e).kind]});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`remove`,correlationId:n,timestampInfo:{deltaTimeInMs:+new Date-t},additionalDetails:{code:r.code,subCode:r.subCode,failureReason:r.message,...K3(r)}}),r}try{await this.tsCall.removeParticipant(W2(e)),this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.success,participantAddedOrRemoved:`remove`,correlationId:n,timestampInfo:{deltaTimeInMs:+new Date-t}})}catch(e){let{callEndReason:i}=H3(this,r.tsRemoteParticipant,e);r.callEndReason||r.setCallEndReason(i);let a=q3(i);throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`remove`,correlationId:n,timestampInfo:{deltaTimeInMs:+new Date-t},additionalDetails:{code:a?.callEndReason.code,subCode:a?.callEndReason.subCode,failureReason:a?.callEndReason.message,...a}}),new Y({defaultError:{message:i.message,code:i.code,subCode:i.subCode||0,resultCategories:i.resultCategories},originalError:e})}}async mute(){super.mute()}async unmute(){super.unmute()}async hold(){if(this.tsCall.state===4)return void this.logger.info(`Call already on hold`);if(!Z().calling.musicOnHoldEnabled)return this.logger.warn(`Music on Hold is not enabled`),super.hold();let e=+new Date,t=K0();if(this._causeId=AG(),this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:o4.Hold,kindOfEvent:$.attempt,timestampInfo:{deltaTimeInMs:e},additionalDetails:{holdType:b4.MusicOnHold,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn}}),!this._hasFetchedPolicies)try{this.logger.info(`Fetching Teams Calling Policy from Azure Communication Services`),await this._mtPolicyService.fetchUserPoliciesFromAcsMiddleTier(this.tsCall.callId,this._callAgent.getUserMri(),{policyUrlSuffix:Z().MiddleTier.policyUrlSuffixV2,userPolicies:[`TeamsCallingPolicy`]}),this._hasFetchedPolicies=!0,this._isTeamsExtensionUser&&!Z().calling.teamsExtensionSettings.enableMoh?(this._musicOnHoldEnabled=!1,this.logger.info(`Music on Hold is disabled for Teams Extension User`)):this._musicOnHoldEnabled=this._mtPolicyService.isMoHEnabled(),this.logger.info(`Music on Hold is `+(this._musicOnHoldEnabled?`enabled`:`disabled`))}catch(e){this.logger.warn(`Fetching Teams Calling Policy from Azure Communication Services failed.\n Error message = ${e?.message}, code = ${e?.code}, subcode = ${e?.subCode}.`)}return this._musicOnHoldEnabled?(Z().calling.turnOffScreenShareBeforeHold&&this.tsCall.isScreenSharingOn&&await this.tsCall.stopScreenSharing().then((()=>{this.logger.log(`Successfully turned off screen sharing before hold`)})).catch((()=>{this.logger.error(`Failed to turn off screensharing before hold`)})),await this.tsCall.hold(void 0,this._causeId,{isLocal:!0},1).then((async()=>{this.logger.info(`Successfully detached devices as part of Hold`),await this.tsCall.park(3,this._causeId).then((()=>{let n=+new Date;this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:o4.Hold,kindOfEvent:$.success,timestampInfo:{deltaTimeInMs:n-e},additionalDetails:{holdType:b4.MusicOnHold,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn}}),this.logger.info(`Successful park() as part of hold, Music on Hold completed successfully`)}))})).catch((()=>{let n=+new Date,r=new Y({defaultError:J.CALL.HOLD_CALL});throw this.logger.warn(`Attempting to perform Music on Hold failed.\n Error message = ${r.message}, code = ${r.code}, subcode = ${r.subCode}`),this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:o4.Hold,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:n-e},additionalDetails:{failureReason:r.message,code:r.code,subCode:r.subCode,holdType:b4.MusicOnHold,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn,...K3(r)}}),r}))):(this.logger.info(`Fetching of Teams Calling Policy failed or Music on Hold Disabled, proceeding with standard hold`),super.hold())}async resume(){if(this._musicOnHoldEnabled){let e=+new Date,t=K0();return this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:o4.Resume,kindOfEvent:$.attempt,timestampInfo:{deltaTimeInMs:e},additionalDetails:{holdType:b4.MusicOnHold,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn}}),await this.tsCall.unpark(3,this._causeId).then((async()=>{this.logger.info(`Successful unpark() as part of resume`),await this.tsCall.unhold(void 0,this._causeId).then((()=>{let n=+new Date;this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:o4.Resume,kindOfEvent:$.success,timestampInfo:{deltaTimeInMs:n-e},additionalDetails:{holdType:b4.MusicOnHold,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn}}),this.logger.info(`Successful unhold() as part of resume, resume completed successfully`)}))})).catch((()=>{let n=+new Date,r=new Y({defaultError:J.CALL.RESUME_CALL});throw this.logger.warn(`Attempting to perform resume from Music on Hold failed.\n Error message = ${r.message}, code = ${r.code}, subcode = ${r.subCode}`),this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:o4.Resume,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:n-e},additionalDetails:{failureReason:r.message,code:r.code,subCode:r.subCode,holdType:b4.MusicOnHold,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn,...K3(r)}}),r}))}return this.logger.info(`Music on Hold Disabled, proceeding with standard resume`),super.resume()}validateAndSetThreadId(e,t){if(!t?.threadId){let e=new Y({defaultError:J.CALL.CTE_ADDPARTICIPANT_NO_THREAD_ID});throw this.logger.error(`Error Message = ${e.message}, code = ${e.code}, subcode = ${e.subCode}`),e}return this.validateThreadIdFormat(t?.threadId),t?.threadId}validateThreadIdFormat(e){if(!e.startsWith(`19`)){let e=new Y({defaultError:J.CALL.TEAMS_INVALID_THREAD_ID});throw this.logger.error(`Error Message = ${e.message}, code = ${e.code}, subcode = ${e.subCode}`),e}}enforcePolicyAndLicenseRestrictions(){let e=+new Date;if(!this._mtPolicyService.isEvEnabled()){let t=+new Date,n=new Y({defaultError:J.CALL.CTE_VOICE_NOT_ENABLED});this.logger.error(`Error Message = ${n.message}, code = ${n.code}, subcode = ${n.subCode}`);let r=this._callAgent.getEcsConfigIds();throw this.sendCallStageEvent({eventName:Q.acs_calling_call_failed,correlationId:K0(),timestampInfo:{deltaTimeInMs:t-e},additionalPayload:{additionalProperties:{EmergencyCountryCode:this._callAgent._caConfigBag?.emergencyCountryCode||``,IsUserEmergencyCountryCode:this._callAgent._caConfigBag?.IsUserEmergencyCountryCode||!1,IsEmergencyCall:this.isEmergencyCall,trouterState:this._callAgent.getTrouterState(),AcsCallingSDKWeb_ecsConfigId:r.AcsCallingSDKWeb,SkypeWebMedia_ecsConfigId:r.SkypeWebMedia},additionalDetails:{...K3(n)}}},n,{code:n.code,subCode:n.subCode,phrase:n.message}),n}}handlePolicyAndLicenseRestrictionsFailure(e){this._callEndReason={message:`Unknown`,code:e?.code,subCode:e?.subCode,resultCategories:e?.resultCategories},this._state=`Disconnected`,this._eventEmitter.emit(`stateChanged`),this._callAgent.handleCallRemoved(this.tsCall)}async setupThreadIdWhenStartingGroupCall(e,t,n){if(t&&t.threadId&&(this.validateThreadIdFormat(t.threadId),this.logger.info(`ThreadId is already provided in the options parameter: `+JSON.stringify(t))),t===void 0||!t.threadId){let r=[];e.forEach((e=>{r.push({id:W2(e)})}));try{let e=await this._mtPolicyService.CreateChatThreadId(this.tsCall.callId,{createThreadIdSuffix:Z().MiddleTier.serverManagedThreadIdApiConfiguration.createThreadSuffix,participants:r});t||={},t.threadId=e,e&&this._info.setThreadId(e),n&&e&&(n.threadId=e)}catch(e){if(!Z().MiddleTier.serverManagedThreadIdApiConfiguration.decoupleChatThreadFromCalls)throw new Y({defaultError:J.CTE_MID_TIER_POLICY_SERVICE.CREATETHREAD_FAILED});this.logger.warn(`Failed to create thread Id for Teams group call `+e)}}}async GetOrCreateGroupChatThread(e,t,n){let r=``;if(Zle(t))return this.logger.info(`Adding TeamsExtensionUserIdentifierto call`),Promise.resolve(r);if(e)return this.logger.info(`Customer provided threadId in options: `+JSON.stringify(n)),r=this.validateAndSetThreadId(t,n),Promise.resolve(r);let i=sTe(lTe(this),wG(t));if(Z().calling.enableOpsSmePassFakeConversation&&i)return r=this.tsCall.threadId||B4(),Promise.resolve(r);if(!Z().MiddleTier.serverManagedThreadIdApiConfiguration.allowServerThreadCreation)throw new Y({defaultError:J.CALL.CTE_ADDPARTICIPANT_NO_THREAD_ID});if(this._info.threadId!==null&&this._info.threadId!==void 0){r=this._info.threadId;let e=[];return e.push({id:W2(t)}),await this._mtPolicyService.AddParticipantsToThread(this.tsCall.callId,{threadId:r,addParticipantsSuffix:Z().MiddleTier.serverManagedThreadIdApiConfiguration.addParticipantSuffix,participants:e}).catch((t=>{this.logger.warn(`Error when adding participants `+JSON.stringify(e)+` to thread. `+t)})),Promise.resolve(r)}{let e=[];return this._remoteParticipants.forEach((t=>{e.push({id:W2(t.identifier)})})),e.push({id:W2(t)}),await this._mtPolicyService.CreateChatThreadId(this.tsCall.callId,{createThreadIdSuffix:Z().MiddleTier.serverManagedThreadIdApiConfiguration.createThreadSuffix,participants:e}).then((e=>{r=e,this.logger.info(`Add participant into 1on1 call to convert it into Teams group call. Create thread id: `+r)})).catch((e=>{let n=`Error when adding participants `+W2(t)+` to thread to create a Teams group call. `;if(!Z().MiddleTier.serverManagedThreadIdApiConfiguration.decoupleChatThreadFromCalls)throw new Y({defaultError:J.CTE_MID_TIER_POLICY_SERVICE.CREATETHREAD_FAILED});this.logger.warn(n+e)})),Promise.resolve(r)}}addParticipantToTsCall(e,t,n,r,i,a){this.tsCall.addParticipant(W2(e),{threadId:t,customHeaderContext:V4(n)}).then((()=>{this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.success,participantAddedOrRemoved:`add`,correlationId:i,timestampInfo:{deltaTimeInMs:+new Date-a}})})).catch((t=>{let{callEndReason:n}=H3(this,r.tsRemoteParticipant,t);r.callEndReason||r.setCallEndReason(n);let o=q3(n);this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`add`,correlationId:i,timestampInfo:{deltaTimeInMs:+new Date-a},additionalDetails:{code:o?.callEndReason.code,subCode:o?.callEndReason.subCode,failureReason:o?.callEndReason.message,...o}}),this._remoteParticipants.find((t=>W2(t.identifier)===W2(e)))&&(this.deleteRemoteParticipant(r),this._eventEmitter.emit(`remoteParticipantsUpdated`,{added:[],removed:[r]}))}))}IsTargetUserAllowed(e){return Qle(e)||xG(e)||bG(e)}};F9([KG(o4.AddParticipant),WG(o4.AddParticipant),I9(`design:type`,Function),I9(`design:paramtypes`,[Object,Object]),I9(`design:returntype`,Object)],L9.prototype,`addParticipant`,null),F9([KG(o4.RemoveParticipant),GG(o4.RemoveParticipant),I9(`design:type`,Function),I9(`design:paramtypes`,[Object]),I9(`design:returntype`,Promise)],L9.prototype,`removeParticipant`,null),F9([KG(o4.Mute),I9(`design:type`,Function),I9(`design:paramtypes`,[]),I9(`design:returntype`,Promise)],L9.prototype,`mute`,null),F9([KG(o4.Unmute),I9(`design:type`,Function),I9(`design:paramtypes`,[]),I9(`design:returntype`,Promise)],L9.prototype,`unmute`,null),F9([KG(o4.Hold),GG(o4.Hold),I9(`design:type`,Function),I9(`design:paramtypes`,[]),I9(`design:returntype`,Promise)],L9.prototype,`hold`,null),F9([KG(o4.Resume),GG(o4.Resume),I9(`design:type`,Function),I9(`design:paramtypes`,[]),I9(`design:returntype`,Promise)],L9.prototype,`resume`,null);var R9=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},z9=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},B9=class e extends Y7{get calls(){return this._calls}constructor(e,t,n,r,i,a){super(e,t,r,i,n,BG.TeamsCallAgent,a),this._calls=[],this.handleCallAdded=e=>{if(!this._calls.find((t=>t.id===e.callId))){let t=e.on(`callStateChanged`,(async()=>{if(e.state===1){let n=U6(e),r=e.callId;t.dispose();let i=new L9({callId:r,isIncoming:!0},this,e,this._telemetryLogManager);n&&(i=X7(i));let a=new URe(i);this.handleCallState(i),n?await Promise.all(i.bindTsCall()):i.bindTsCall(),this._eventEmitter.emit(`incomingCall`,{incomingCall:a})}}))}},this.handleCallRemoved=e=>{this.logger.info(`removing callId=${e.callId}`);let t=this._calls.find((t=>t.id===e.callId));if(t){if(t.isBreakoutRoomCall){let e=Z().calling.breakoutRooms.hangUpCallDelayInMilliSeconds;setTimeout((()=>{this.disposeCall(t)}),e)}else this.disposeCall(t);this._eventEmitter.emit(`callsUpdated`,{added:[],removed:[t]}),this.logger.info(`call removed`)}},this.handleCallState=e=>{e.on(`stateChanged`,(async()=>{try{e.state===`Disconnected`?this.tsStack?(await this._tsCallRegistry.deleteCallAsync?.(e.tsCall)||this.logger.info(`The call has been removed from registry, call id: ${e.id}`),e.stats.flushEvents(),this._telemetryLogManager.flushAllEvents(e.id).catch((()=>{this.logger.error(`Failed to flush telemetry log manager events`)}))):this.logger.info(`Unable to remove call from registry`):e.state===`Connecting`&&e.direction==`Incoming`&&(this.addToCallArray(e),this._eventEmitter.emit(`callsUpdated`,{added:[e],removed:[]}))}catch{this.logger.error(`Failed to handle call state changed event`)}}))},this.logger=t}createNewCall(e,t){let n=new L9({callId:e},this,t,this._telemetryLogManager);return U6(t)?X7(n):n}addToCallArray(e){this._calls.push(e),this.trackCallEndTimeToStopTelemetry(this._calls)}addToCallAgentsMap(t){e.teamsCallAgents.get(t?.identityMri)&&k4(J.CALL_AGENT.TEAMS_CALLAGENT_ALREADY_EXSISTS,this.logger),e.teamsCallAgents.set(t?.identityMri,this)}removeFromCallAgentsMap(t){t?.identityMri&&e.teamsCallAgents.get(t?.identityMri)===this&&e.teamsCallAgents.delete(t?.identityMri)}disposeCall(e){let t=this._calls.indexOf(e);t!==-1&&this._calls.splice(t,1),e.dispose(),this.trackCallEndTimeToStopTelemetry(this._calls)}getMiddleTierServiceInstance(){return this.mtPolicyService}async setUserPoliciesOnAgentInitialization(){super.setUserPoliciesOnAgentInitialization();try{if(this.isEnterpriseUser()){let e=K0();this.logger.info(`ACS MiddleTier service called on Teams Call Agent initialization with call Id=${e}`),await this.mtPolicyService.fetchUserPoliciesFromAcsMiddleTier(e,this.getUserMri(),{policyUrlSuffix:Z().MiddleTier.policyUrlSuffixV2,userPolicies:[`EmergencyPolicies`,`TeamsCallingPolicy`,`TeamsMeetingPolicy`],userProperties:[`FeatureTypes`,`PoliciesMetadata`,`phoneNumber`,`sipUri`,`hostType`,`accountEnabled`,`useTeamsCalling`,`evEnabled`,`region`,`routingType`,`preferredDataLocation`,`featureTypes`,`displayName`]}),this._userPolicies=this.mtPolicyService.getUserPolicy(),this._userProperties=this.mtPolicyService.getUserProperties(),this.logger.info(`****User policy initialized to ${JSON.stringify(this._userPolicies)}`),this.logger.info(`****User properties initialized to ${JSON.stringify(this._userProperties)}`)}}catch(e){this.logger.warn(`Fetching Teams user policy and Properties from ACS MiddleTier Service failed.\n Error message = ${e?.message}, code = ${e?.code}, subcode = ${e?.subCode}.`)}}async disposeInternal(t){let n=+new Date,r=K0();this.sendCallAgentDisposeEvent({eventName:Q.acs_calling_client_operations,operation:K7.disposeTeamsCallAgent,kindOfEvent:`attempt`,timestampInfo:{},correlationId:r,additionalDetails:``});try{if(this._disposed)throw new Y({defaultError:J.CALL_AGENT.CTE_ALREADY_DISPOSED});this._disposed=!0,this._abortController.abort(),this._extensibleApi.dispose(),this._parsedTokenCredential?.identityMri&&e.teamsCallAgents.delete(this._parsedTokenCredential?.identityMri);for(let e of this._calls)e.state!==`Disconnected`&&await e.hangUp().catch((()=>{this.logger.error(`Failed to hangup call during Teams call agent dispose`)}));await this._tsCallRegistry?.dispose();let t=this._tokenFetchTries>this._maxNmberOfRetries;await this._callStack.disposeUserStack(t),this.offTrouterStateChanged(this._trouterStateChangeCallback),this._callStack.offRegisteredChanged(this._registrarStateChangeCallback),this._eventEmitter.removeAllListeners(),this._internalEventEmitter.emit(`disposed`),this._internalEventEmitter.removeAllListeners(),this.sendCallAgentDisposeEvent({eventName:Q.acs_calling_client_operations,operation:K7.disposeTeamsCallAgent,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:``})}catch(e){let t=new Y({defaultError:J.CALL_AGENT.TEAMS_DISPOSE_FAIL,originalError:e});throw this.sendCallAgentDisposeEvent({eventName:Q.acs_calling_client_operations,operation:K7.disposeTeamsCallAgent,kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{failureReason:t.message,code:t.code,subCode:t.subCode,...K3(t)}}),t}finally{t&&this._telemetryLogManager.clearTelemetryLoggers()}}startCall(e,t){let n=K0(),r=+new Date,i={correlationId:n,timestampInfo:{attemptTimestamp:r}};this._telemetryLogManager.sendEvent({name:Q.acs_calling_call_attempt,tenant:d2,properties:i},void 0,`attempt`);try{let i;if(this.assertParticipants(e),Array.isArray(e)){if(this.isTeamsExtensionUser()&&!Z().calling.teamsExtensionSettings.enableJoinCall)throw new Y({defaultError:J.FEATURES.ONE_PHONE_SYSTEM.CALL_CANNOT_BE_STARTED});if(i=t,e.length>1&&!Z().MiddleTier.serverManagedThreadIdApiConfiguration.allowServerThreadCreation&&!i?.threadId)throw new Y({defaultError:J.CALL_AGENT.GROUPCALL_THREADID});if(e.length==1&&i?.threadId)throw new Y({defaultError:J.CALL_AGENT.ONE_TO_ONE_THREADID})}else{if(this.isTeamsExtensionUser()&&!Z().calling.teamsExtensionSettings.enableStartCall)throw new Y({defaultError:J.FEATURES.ONE_PHONE_SYSTEM.CALL_CANNOT_BE_STARTED});i=t}if(Z().calling.enableSmePassFakeConversation&&this.isAcsToTeamsInteropCall(e)&&!this.isTeamsExtensionUser())throw new Y({defaultError:J.CALL_AGENT.UNSUPPORTED_TARGET_TYPE});let a=i?.audioOptions?.muted;return a===void 0&&(a=!1),this.logger.info(`startCall with video=${!!i?.videoOptions},muted=${a}`),this.createCall({participants:e,startCallOptions:i},{correlationId:n,attemptTimestamp:r})}catch(e){let t,i;throw e instanceof Y&&(t=typeof e?.message==`string`?e?.message:void 0,i={...K3(e)}),this._telemetryLogManager.sendEvent({name:Q.acs_calling_call_failed,tenant:d2,properties:{correlationId:n,timestampInfo:{deltaTimeInMs:+new Date-r},failureReason:t||``,additionalDetails:i||{}}},void 0,`failure`),e}finally{this._telemetryLogManager.deleteEventMapByCorrelationId(n)}}join(e,t){this.assertCallContext(e);let n=!!t?.audioOptions?.muted;return this.logger.info(`join with video=${!!t?.videoOptions},muted=${n}`),this.createCall({teamsCallContext:e,startCallOptions:t})}async dispose(){await this.disposeInternal(!0)}on(e,t){if(e!==`incomingCall`&&e!==`callsUpdated`&&e!==`connectionStateChanged`&&e!==`customContextChanged`)throw new Y({defaultError:J.CALL_AGENT.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if(e!==`incomingCall`&&e!==`callsUpdated`&&e!==`connectionStateChanged`&&e!==`customContextChanged`)throw new Y({defaultError:J.CALL_AGENT.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}createCall(e,t){if(!this.tsStack)throw new Y({defaultError:J.CALL_AGENT.STACK_NOT_INIT});let n,r,i,a=e?.teamsCallContext?.threadId,o=!1,s=e?.teamsCallContext?.meetingLink,c=e?.teamsCallContext?.meetingId,l=e?.teamsCallContext?.passcode||``,u=!!e?.participants&&Array.isArray(e?.participants)&&e?.participants.length>1;if(this.isEnterpriseUser()&&u&&(a=(e?.startCallOptions).threadId),!R4(this.acsProxy,this.acsCustomRelayManager,!0))throw new Y({defaultError:J.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN});if(s)if(vFe(s))r=M5(s);else{if(!yFe(s,this.logger))throw new Y({defaultError:J.CALL_AGENT.INVALID_MEETING_LINK});if(bFe(s.trim().toLocaleLowerCase(),Z().calling.tfl.hosts))throw new Y({defaultError:J.CALL_AGENT.UNSUPPORTED_TFL_MEETING_JOIN});o=!0}e?.teamsCallContext?.threadId&&e?.teamsCallContext?.organizerId&&e?.teamsCallContext?.tenantId&&(r={threadId:e?.teamsCallContext?.threadId,messageId:e?.teamsCallContext?.messageId?e?.teamsCallContext?.messageId.toString():`0`,organizerId:e?.teamsCallContext?.organizerId,tenantId:e?.teamsCallContext?.tenantId}),r&&(i={meetingType:r.messageId===`0`?1:2,tenantId:r.tenantId,organizerId:r.organizerId,replyChainMessageId:r.messageId},a=r.threadId,n=r.messageId);let d=this.mtPolicyService.isEmergencyNumber(this.isEnterpriseUser(),e?.participants),f=this.getOnBehalfOfMri(e,u,d),p={threadId:a||``,messageId:n||``,meetingInfo:i,mediaPeerType:2,onBehalfOf:f},m=U6(this._tsCallRegistry),h=AG(),g=K0(),_=K0();if(m){let r=X7();return(async()=>{let i;i=c?await this._tsCallRegistry.createCallAsync({callId:g,localParticipantId:_,causeId:h,type:`MeetingData`,meetingData:{meetingCode:c,passcode:l,threadId:a}}):o?await this._tsCallRegistry.createCallAsync({callId:g,localParticipantId:_,causeId:h,type:`MeetingData`,meetingData:{meetingUrl:s}}):await this._tsCallRegistry.createCallAsync({callId:g,localParticipantId:_,causeId:h,type:`ThreadId`,threadId:a||``,messageId:n});let u=new L9({callId:g,isEmergencyNumber:d},this,i,this._telemetryLogManager);r.setTarget(u),this.addToCallArray(r),this.handleCallState(r);let f=e3();u.startCallInternal(e?.startCallOptions,!!c,e?.teamsCallContext,p,t,f,e?.participants).catch(A4),await Promise.all(u.bindTsCall()),await f.promise,this._eventEmitter.emit(`callsUpdated`,{added:[r],removed:[]})})().catch((e=>{})),r}{let r;r=c?this._tsCallRegistry.createCallWithMeetingData({meetingCode:c,passcode:l,threadId:a},g,_,h):o?this._tsCallRegistry.createCallWithMeetingData({meetingUrl:s},g,_,h):this._tsCallRegistry.createCall(a||``,g,_,n,h);let i=new L9({callId:g,isEmergencyNumber:d},this,r,this._telemetryLogManager);return this.addToCallArray(i),this.handleCallState(i),i.startCallInternal(e?.startCallOptions,!!c,e?.teamsCallContext,p,t,void 0,e?.participants).catch(A4),i.bindTsCall(),this._eventEmitter.emit(`callsUpdated`,{added:[i],removed:[]}),i}}getOnBehalfOfMri(e,t,n){let r=e?.startCallOptions?.onBehalfOfOptions?.userId;if(r){if(!Z().calling.sharedLineAppearance.enabled)throw this.logger.error(`SharedLineAppearance is disabled by ECS flag`),new Y({defaultError:J.FEATURES.SHAREDLINE_APPEARANCE.DISABLED});if((e?.startCallOptions).customContext&&!Z().calling.teamsExtensionSettings.enableCustomContext)throw new Y({defaultError:J.FEATURES.ONE_PHONE_SYSTEM.CUSTOM_CONTEXT_NOT_SUPPORTED});if(t)throw new Y({defaultError:J.FEATURES.SHAREDLINE_APPEARANCE.GROUP_CALLS_NOT_SUPPORTED});if(!n){if(CG(r)&&!Z().calling.sharedLineAppearance.appOnBehalfOfEnabled)throw this.logger.error(`Start Teams call with onBehalfOf MicrosoftTeamsAppIdentifier is disabled by ECS flag`),new Y({defaultError:J.FEATURES.SHAREDLINE_APPEARANCE.DISABLED_FOR_APPLICATIONS});if(SG(r)){if(!Z().calling.sharedLineAppearance.userOnBehalfOfEnabled)throw this.logger.error(`Start Teams call with onBehalfOf MicrosoftTeamsUserIdentifier is disabled by ECS flag`),new Y({defaultError:J.FEATURES.SHAREDLINE_APPEARANCE.DISABLED});if(!this.getUserPolicy()?.teamsCallingPolicy?.allowDelegation)throw this.logger.error(`Start Teams call with onBehalfOf MicrosoftTeamsUserIdentifier is disabled by Teams calling policy`),new Y({defaultError:J.FEATURES.SHAREDLINE_APPEARANCE.DISABLED_BY_CALLING_POLICY})}return $le(r)}this.logger.warn(`Emergency call cannot be made on behalf of another user, dropping the onBehalfOf options`)}}assertParticipants(e){Ywe(e,J.CALL_AGENT.USERIDS_MUST_BE_OBJECTS),Jwe(e,J.CALL_AGENT.USERIDS_CANNOT_BE_NULL)}assertCallContext(e){if(!e||this.checkForAtLeastOneValidCallConfig(e)||this.checkForInvalidTeamsMeetingCoordinates(e))throw new Y({defaultError:J.CALL_AGENT.INVALID_JOIN_LOCATOR})}checkForAtLeastOneValidCallConfig(e){return!e.threadId&&!e.meetingLink&&!e.meetingId}checkForInvalidTeamsMeetingCoordinates(e){return!e.threadId&&e.tenantId&&e.organizerId||e.threadId&&(e.organizerId&&!e.tenantId||!e.organizerId&&e.tenantId)}isAcsToTeamsInteropCall(e){let t=!1;return this.isEnterpriseUser()&&(Array.isArray(e)?e.length>=1&&e.find((e=>bG(e)))&&(t=!0):bG(e)&&(t=!0)),t}};B9.teamsCallAgents=new Map,R9([WG(a4.StartCall),z9(`design:type`,Function),z9(`design:paramtypes`,[Object,Object]),z9(`design:returntype`,Object)],B9.prototype,`startCall`,null),R9([WG(a4.Join),z9(`design:type`,Function),z9(`design:paramtypes`,[Object,Object]),z9(`design:returntype`,Object)],B9.prototype,`join`,null),R9([GG(a4.Dispose),z9(`design:type`,Function),z9(`design:paramtypes`,[]),z9(`design:returntype`,Promise)],B9.prototype,`dispose`,null);var WRe=class{constructor(){this._proxyInUse=!1;let e=KW(`ACS-calling`);this.logger=new z6(e,[()=>`AcsProxy`])}get proxyInUse(){return this._proxyInUse}set proxyInUse(e){this._proxyInUse=e}get proxyUrl(){return this._proxyUrl?.toString()||``}set proxyUrl(e){if(e.length<4)throw new Y({defaultError:J.CALL_CLIENT.PROXY_SHORT_URL});e.slice(-1)!==`/`&&(e=e.concat(``,`/`));try{let t=new URL(e);if(t.protocol!==`https:`&&t.protocol!==`http:`)throw new Y({defaultError:J.CALL_CLIENT.PROXY_PROTOCOL});this._proxyUrl=t}catch(t){let n=new Y({defaultError:J.CALL_CLIENT.SETUP_PROXY,defaultErrorMessageArgs:[e],originalError:t});throw this.logger.error(n.message),n}}hasProxyUrl(){return!!this._proxyUrl}proxyfyUrl(e){let t=e;if(!this._proxyUrl)return this.logger.info(`Proxy url not defined, return original ${e4(t)}`),t;try{let e=new URL(t);t=`${`${e.protocol}//${this._proxyUrl.host}${this._proxyUrl.pathname}`}${e.host}${e.pathname}${e.search}`,this.logger.info(`Proxyfing url from ${e4(e)} to ${e4(t)}`)}catch(e){let t=`Failed proxyfy url with error: ${JSON.stringify(e)}, returning original`;this.logger.error(t)}return this._proxyInUse=!0,t}},GRe=class{constructor(){this._hasCustomRelay=!1,this._customRelayManagerInUse=!1;let e=KW(`ACS-calling`);this._logger=new z6(e,[()=>`AcsCustomRelayManager`])}getRelayConfig(){return this._relayConfig}setRelayConfig(e){this._relayConfig={...e},this._logger.info(`Custom relay config provided`),this._hasCustomRelay=!0,this._createTsRelayManager()}get hasRelayConfig(){return this._hasCustomRelay}get customRelayManagerInUse(){return this._customRelayManagerInUse}set customRelayManagerInUse(e){this._customRelayManagerInUse=e}getTsRelayManager(){return this._tsRelayManager}_createTsRelayManager(){if(!this._hasCustomRelay||!this._relayConfig||this._relayConfig.iceServers.length<1)return void this._logger.warn(`No relay config provided. No op.`);let e=[];this._relayConfig.iceServers.forEach((t=>{t.urls.forEach((n=>{let r=this._getIndividualRelay(n,t?.username,t?.credential);e.push(r)}))})),this._tsRelayManager={initialize(){},queryRelaysAsync:t=>Promise.resolve(e)}}_getIndividualRelay(e,t,n){let r=3478,i=[],a=[],o=[v3.turn,v3.turns,v3.stun],s=[y3.tcp,y3.tls,y3.udp],c;try{c=new URL(e)}catch(t){throw new Y({defaultError:J.CALL_CLIENT.RELAY_INFO,defaultErrorMessageArgs:[e],originalError:t})}let l=c.protocol.replace(`:`,``);if(!o.includes(l))throw new Y({defaultError:J.CALL_CLIENT.RELAY_UNRECOGNIZED_SCHEMA});let u,d=``;try{d=c.href.replace(/((turn)s?|stun):/,`https:`),u=new URL(d)}catch(e){throw new Y({defaultError:J.CALL_CLIENT.RELAY_INFO,defaultErrorMessageArgs:[d],originalError:e})}let f=u.searchParams.get(`transport`)??``;s.includes(f)||(this._logger.warn(`Unknown transport protocol detected for the provided turn, defaulting to ${y3.udp}`),f=y3.udp);let p=u.port===``?this._extractPortFromUrl(c):Number(u.port);p||=(this._logger.warn(`Could not read port from relay url, defaulting to ${r}`),r);let m=u.hostname;return xwe(m)?i.push(m):a.push(m),{addresses:i,udpPort:f===y3.udp?p:void 0,tcpPort:f===y3.tcp?p:void 0,tlsPort:f===y3.tls?p:void 0,username:t??``,password:n??``,type:`turn`,fqdns:a}}_extractPortFromUrl(e){let t=e.href.match(owe)?.[0];return Number(t?.replace(`:`,``))}},KRe=class{constructor(e,t,n){this._eventEmitter=new w3.EventEmitter,this._removeListeners=[];let r=(e,r)=>{n()&&t.sendEvent({name:Q.acs_calling_page_hidden,tenant:d2,properties:{eventName:e,pageHidden:r}})},i=()=>{document.visibilityState===`hidden`?(e.debug(`Visibility changed to hidden`),r(`visibilityChange`,!0),this._eventEmitter.emit(`visibilityChange`,!0)):(e.debug(`Visibility changed to visible`),r(`visibilityChange`,!1),this._eventEmitter.emit(`visibilityChange`,!0))},a=()=>{e.debug(`Page show`),r(`pageShow`,!1),this._eventEmitter.emit(`pageShow`)},o=()=>{e.debug(`Page hide`),r(`pageHide`,!0),this._eventEmitter.emit(`pageHide`)};window.addEventListener(`visibilitychange`,i),this._removeListeners.push((()=>window.removeEventListener(`visibilitychange`,i))),window.addEventListener(`pageshow`,a),this._removeListeners.push((()=>window.removeEventListener(`pageshow`,a))),window.addEventListener(`pagehide`,o),this._removeListeners.push((()=>window.removeEventListener(`pagehide`,o)));let s=(e,r)=>{n()&&t.sendEvent({name:Q.acs_calling_orientation_changed,tenant:d2,properties:{orientation:e,isInitial:r}})},c=()=>{let t=screen.orientation.type;e.debug(`Orientation changed to ${t}`),s(t,!1),this._eventEmitter.emit(`orientationChanged`,t)},l=()=>window.innerHeight>window.innerWidth?`portrait-primary`:`landscape-primary`,u=``,d=()=>{let t=l();u!==t&&(e.debug(`Orientation changed to ${t}`),u=t,s(t,!1),this._eventEmitter.emit(`orientationChanged`,t))};screen?.orientation?.type?(screen.orientation.addEventListener(`change`,c),this._removeListeners.push((()=>screen.orientation.removeEventListener(`change`,c))),s(screen.orientation.type,!0)):(window.addEventListener(`resize`,d),this._removeListeners.push((()=>window.removeEventListener(`resize`,d))),s(l(),!0))}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}dispose(){this._eventEmitter.removeAllListeners(),this._removeListeners.forEach((e=>e()))}},qRe,V9=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},H9=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},JRe=1,U9=class e{get callAgent(){return this._callAgent}get teamsCallAgent(){return this._teamsCallAgent}get sdkDiagnosticInformation(){return this._sdkDiagnosticInformation}get telemetryLogManager(){return this._telemetryLogManager}setCallAgent(e){this._callAgent=e}setTeamsCallAgent(e){this._teamsCallAgent=e}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}constructor(e){this._disposed=!1,this._customProxyAndTurnInformation={proxy:null,turn:null},this.sendTelemetry=()=>{try{if(Z().telemetry.telemetryBeforeUnload&&this._callAgent&&this._callAgent._calls)for(let e of this._callAgent._calls)e.tsCall.sendLastKnownStats()}catch(e){this.logger.debug(`Error logging telemetry`,e)}};let t=+new Date;this.clientId=K0();let n=e?.logger||KW(`ACS-calling`),r=JRe++;if(this._acsProxy=new WRe,this._acsCustomRelayManager=new GRe,this._vdi3Options=e?.vdi3,e?.networkConfiguration){e.networkConfiguration.proxy?.url&&(this._customProxyAndTurnInformation.proxy={...e.networkConfiguration.proxy},this._acsProxy.proxyUrl=this._customProxyAndTurnInformation.proxy.url),e.networkConfiguration.turn&&(this._customProxyAndTurnInformation.turn={...e.networkConfiguration.turn},this._acsCustomRelayManager.setRelayConfig(this._customProxyAndTurnInformation.turn));let t=this.getTelemetryTag();e.diagnostics?e.diagnostics.tags?e.diagnostics.tags.push(t):e.diagnostics.tags=[t]:e.diagnostics={tags:[t]}}this.logger=new z6(n,[()=>`CallClient${r}[${this.clientId}]`]),this._eventEmitter=new S6(this.logger),this._sdkDiagnosticInformation=tTe(Y2(),this.logger,e),this.diagnosticOptions=e?.diagnostics,this.firstPartyOptions=e?.firstPartyOptions,this._telemetryLogManager=new f3(this.logger,this._sdkDiagnosticInformation,this._acsProxy,this._acsCustomRelayManager);try{this.sendCallClientInitEvent({eventName:Q.acs_calling_call_client_init,kindOfEvent:`attempt`,timestampInfo:``,additionalDetails:``}),Object.defineProperty(globalThis,x2,{value:r,writable:!0,enumerable:!1}),r===1&&Object.defineProperty(globalThis,b2,{value:this._telemetryLogManager,writable:!1,enumerable:!1}),this.logger.info(`created`),this._callStack=new A9(this.logger,this.clientId,this._telemetryLogManager,this._sdkDiagnosticInformation,this._acsProxy,this._acsCustomRelayManager,this.firstPartyOptions?.encodedStreamsJsPath,this._vdi3Options),this._deviceManager=new N9(this.logger,this._callStack,this._telemetryLogManager),window.addEventListener(`beforeunload`,this.sendTelemetry),this._screenDeviceManager=new KRe(this.logger,this._telemetryLogManager,(()=>this._callAgent?.calls?this._callAgent.calls.length>0:!!this._teamsCallAgent?.calls&&this._teamsCallAgent.calls.length>0)),this._screenDeviceManager.on(`visibilityChange`,(e=>{if(e)try{t8().formFactor===`Mobile`&&Z().calling.hangUpCallOnPageHide&&(this._callAgent?.calls.forEach((e=>e.hangUp())),this._teamsCallAgent?.calls.forEach((e=>e.hangUp())))}catch(e){this.logger.error(`Unable to hangup call on page hide due to ${e}`)}})),this._extensibleApi=new N3(this.logger,{callClient:this},{callClient:this,telemetryLogManager:this._telemetryLogManager});let e=Q5(D3.CallClientFeature);for(let t of e)t.activationOptions.activationEvent===`OnExtendedObjectConstructor`&&this.feature(t);this.sendCallClientInitEvent({eventName:Q.acs_calling_call_client_init,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:+new Date-t},additionalDetails:``})}catch(e){let n=new Y({defaultError:J.CALL_CLIENT.INIT_CALL_CLIENT,originalError:e});throw this.sendCallClientInitEvent({eventName:Q.acs_calling_call_client_init,kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:+new Date-t},additionalDetails:{failureReason:n.message,code:n.code,subCode:n.subCode,...K3(n)}}),n}}createInstance(t){return new e(t)}get acsProxy(){return this._acsProxy}get acsCustomRelayManager(){return this._acsCustomRelayManager}getSDKVersion(){return Y2()}async getEnvironmentInfoInternal(){return this._environmentInfos||=(await this._callStack.createStackBase(),hke()),this._environmentInfos}feature(e){return this._extensibleApi.getApiObjectInstance(e.callClientApiCtor)}async createCallAgent(e,t){if(this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});let n=+new Date,r=K0();this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:K7.createCallAgent,kindOfEvent:`attempt`,timestampInfo:{},correlationId:r,additionalDetails:``});let{identityMri:i}=await M4(e);if(this._callAgent?._caConfigBag?.identityMri===i)return this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:K7.createCallAgent,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{context:`ACS CallAgent already exists in this call client for the given identity.`}}),this._callAgent;if(this._callAgent||this._teamsCallAgent){let e=new Y({defaultError:J.CALL_CLIENT.ONE_CALL_AGENT_PER_CALL_CLIENT});this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:K7.createCallAgent,kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{context:`ACS CallAgent already exists in this call client.`,failureReason:e.message,code:e.code,subCode:e.subCode,...K3(e)}}),k4(J.CALL_CLIENT.ONE_CALL_AGENT_PER_CALL_CLIENT,this.logger)}if(this._callAgent=e9.callAgents.get(i),this._callAgent)return this._callAgent.onDisposed((()=>{this._callAgent=void 0})),this._eventEmitter.emit(`callAgentCreated`),this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:K7.createCallAgent,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{context:`ACS Call Agent already exists for the given identity. Maybe have been created by another call client instance.`}}),this._callAgent;this.validateEmergencyCountryCode(t);try{return this._callAgent=new e9(this,this.logger,this._callStack,this.clientId,this._telemetryLogManager,this._deviceManager,t),await this._callAgent.initialize(e,t),this._callAgent.onDisposed((()=>{this._callAgent=void 0})),this._eventEmitter.emit(`callAgentCreated`),this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:K7.createCallAgent,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{context:`ACS CallAgent created and initialized successfully.`}}),this._callAgent}catch(e){this._callAgent=void 0;let t=new Y({defaultError:J.CALL_CLIENT.CREATE_CALL_AGENT,originalError:e});throw this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:K7.createCallAgent,kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{failureReason:t.message,code:t.code,subCode:t.subCode,...K3(t)}}),this._telemetryLogManager.clearTelemetryLoggers(),t}}async createTeamsCallAgent(e,t){if(this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});let n=+new Date,r=K0();this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:K7.createTeamsCallAgent,kindOfEvent:`attempt`,timestampInfo:{},correlationId:r,additionalDetails:``});let{identityMri:i,mriType:a}=await M4(e);if(a==e2.TeamsExtensionUser?this.logger.info(`TeamsCallAgent is TeamsExtensionUser type`):this.logger.info(`TeamsCallAgent is not TeamsUser type`),this._teamsCallAgent?._caConfigBag?.identityMri===i)return this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:K7.createTeamsCallAgent,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{context:`Teams Call Agent already exists in this call client for the given identity.`}}),this._teamsCallAgent;if(this._callAgent||this._teamsCallAgent){let e=new Y({defaultError:J.CALL_CLIENT.ONE_CALL_AGENT_PER_CALL_CLIENT});this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:K7.createTeamsCallAgent,kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{context:`Teams Call Agent already exists in this call client.`,failureReason:e.message,code:e.code,subCode:e.subCode,...K3(e)}}),k4(J.CALL_CLIENT.ONE_CALL_AGENT_PER_CALL_CLIENT,this.logger)}if(this._teamsCallAgent=B9.teamsCallAgents.get(i),this._teamsCallAgent)return this._teamsCallAgent.onDisposed((()=>{this._teamsCallAgent=void 0})),this._eventEmitter.emit(`teamsCallAgentCreated`),this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:K7.createTeamsCallAgent,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{context:`Teams Call Agent already exists for the given identity. Maybe have been created by another call client instance.`}}),this._teamsCallAgent;try{return this._teamsCallAgent=new B9(this,this.logger,this._callStack,this.clientId,this._telemetryLogManager,this._deviceManager),await this._teamsCallAgent.initialize(e,t),this._teamsCallAgent.onDisposed((()=>{this._teamsCallAgent=void 0})),this._eventEmitter.emit(`teamsCallAgentCreated`),this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:K7.createTeamsCallAgent,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{context:`TeamsCallAgent created and initialized successfully.`}}),this._teamsCallAgent}catch(e){this._teamsCallAgent=void 0;let t=new Y({defaultError:J.CALL_CLIENT.CREATE_TEAMS_CALL_AGENT,originalError:e});throw this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:K7.createTeamsCallAgent,kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{failureReason:t.message,code:t.code,subCode:t.subCode,...K3(t)}}),this._telemetryLogManager.clearTelemetryLoggers(),t}}async getDeviceManager(){if(this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});return this._callAgent&&this._callAgent?.callClient!==this?(await this._callAgent?.deviceManager.getDeviceManager(),this._callAgent?.deviceManager):(await this._deviceManager.getDeviceManager(),this._deviceManager)}async dispose(){if(this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});let e=+new Date,t=K0();try{this._disposed=!0,this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:K7.disposeCallClient,kindOfEvent:`attempt`,timestampInfo:{},correlationId:t,additionalDetails:``});try{this._deviceManager.dispose(),this.logger.info(`Device Manager disposed`)}catch{this.logger.error(`Call Client failed to dispose Device Manager`)}try{this._callAgent?await this._callAgent.disposeInternal(!1).then((()=>{this.logger.info(`ACS Call Agent disposed`)})):this._teamsCallAgent&&await this._teamsCallAgent.disposeInternal(!1).then((()=>{this.logger.info(`Teams Call Agent disposed`)}))}catch(e){e.subCode!==J.CALL_AGENT.ACS_ALREADY_DISPOSED.subCode&&e.subCode!==J.CALL_AGENT.CTE_ALREADY_DISPOSED.subCode||this.logger.debug(`Call Client failed to dispose Call Agent as it is already disposed`),this.logger.error(`Call Client failed to dispose Call Agent`)}try{this._screenDeviceManager.dispose()}catch{this.logger.error(`Call Client failed to dispose ScreenDevice Manager`)}try{await this._callStack.disposeBaseStack(),this.logger.info(`Base call stack disposed`)}catch{this.logger.error(`Call Client failed to dispose base call stack`)}this._eventEmitter.removeAllListeners(),window.removeEventListener(`beforeunload`,this.sendTelemetry),this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:K7.disposeCallClient,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:+new Date-e},correlationId:t,additionalDetails:``})}catch(n){let r=new Y({defaultError:J.CALL_CLIENT.DISPOSE_FAIL,originalError:n});throw this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:K7.disposeCallClient,kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:+new Date-e},correlationId:t,additionalDetails:{failureReason:r.message,code:r.code,subCode:r.subCode,...K3(r)}}),r}finally{this._telemetryLogManager.clearTelemetryLoggers()}}validateEmergencyCountryCode(e){e?.emergencyCallOptions?.countryCode&&e.emergencyCallOptions?.countryCode.length>kCe&&k4(J.CALL_CLIENT.EMERGENCY_CODE_TOO_LONG,this.logger)}sendCallClientInitEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:d2,properties:e})}catch{this.logger.debug(`Unable to send CallClient initialized telemetry event`)}}sendCallClientOperationEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:d2,properties:e})}catch{this.logger.debug(`Unable to send CallClient dispose telemetry event`)}}getTelemetryTag(){return this._customProxyAndTurnInformation.proxy&&this._customProxyAndTurnInformation.turn?R2.usedProxyAndNonMsftTurn:this._customProxyAndTurnInformation.proxy?R2.onlyUsedProxy:this._customProxyAndTurnInformation.turn?R2.onlyUsedNonMsftTurn:``}};V9([zG,H9(`design:type`,Object)],U9.prototype,`logger`,void 0),V9([WG(i4.Feature),H9(`design:type`,Function),H9(`design:paramtypes`,[Object]),H9(`design:returntype`,typeof(qRe=typeof TFeature<`u`&&TFeature)==`function`?qRe:Object)],U9.prototype,`feature`,null),V9([GG(i4.CreateCallAgent),H9(`design:type`,Function),H9(`design:paramtypes`,[Object,Object]),H9(`design:returntype`,Promise)],U9.prototype,`createCallAgent`,null),V9([GG(i4.CreateTeamsCallAgent),H9(`design:type`,Function),H9(`design:paramtypes`,[Object,Object]),H9(`design:returntype`,Promise)],U9.prototype,`createTeamsCallAgent`,null),V9([GG(i4.GetDeviceManager),H9(`design:type`,Function),H9(`design:paramtypes`,[]),H9(`design:returntype`,Promise)],U9.prototype,`getDeviceManager`,null),V9([GG(i4.Dispose),H9(`design:type`,Function),H9(`design:paramtypes`,[]),H9(`design:returntype`,Promise)],U9.prototype,`dispose`,null);var YRe=class{constructor(e,t,n,r,i){if(this._width=0,this._height=0,this._eventEmitter=new w3.EventEmitter,this._loopId=0,this._isDisposed=!1,e.getVideoTracks().length===0)throw Error(`Video stream must have at least one video track`);this._videoStream=e.clone(),this._refreshInterval=r,this._logger=i.createChild(`VideoStreamCanvasEncoder`),this._video=document.createElement(`video`),this._canvas=document.createElement(`canvas`),this._video.srcObject=this._videoStream,this._video.addEventListener(`resize`,(()=>{let e=this._video.videoWidth||t,r=this._video.videoHeight||n;this._width===e&&this._height===r||(this._width=e,this._height=r,this._canvas.width=e,this._canvas.height=r,this._logger.info(`Video stream resized to ${e}x${r}`))})),this._video.addEventListener(`play`,(()=>{this._loopId||=window.setInterval((()=>{if(!this._isDisposed&&!this._video.paused&&!this._video.ended){this._context.drawImage(this._video,0,0,this._width,this._height);let e=Uint8Array.from(this._canvas.toDataURL(`image/jpeg`),(e=>e.charCodeAt(0)));this._eventEmitter.emit(`data`,e)}}),this._refreshInterval)})),this._video.addEventListener(`pause`,(()=>{this._loopId&&=(clearInterval(this._loopId),0)})),this._video.play().catch((e=>{this._logger.error(`Error playing video stream: ${e}`)})),this._context=this._canvas.getContext(`2d`)}on(e,t){this._eventEmitter.on(e,t)}dispose(){this._isDisposed||(this._isDisposed=!0,this._loopId&&=(clearInterval(this._loopId),0),this._video.pause(),this._video.srcObject=null,this._videoStream.getTracks().forEach((e=>{e.stop()})),this._eventEmitter.removeAllListeners())}},XRe=3,ZRe=class{constructor(e,t,n){this._eventEmitter=new w3.EventEmitter,this._loopId=0,this._isDisposed=!1,this._dataQueue=[],this._timeoutCounter=0,this._timeoutCount=0,this._canvas=document.createElement(`canvas`),this._canvas.width=0,this._canvas.height=0,this._context=this._canvas.getContext(`2d`),this._logger=t.createChild(`VideoStreamCanvasDecoder`),this._mediaStream=this._canvas.captureStream(Math.max(1,Math.ceil(1e3/e))),this._timeoutCount=n;let r=e=>new Promise(((t,n)=>{try{let r=new TextDecoder().decode(e),i=new Image;i.onload=()=>{i.width===this._canvas.width&&i.height===this._canvas.height||(this._canvas.width=i.width,this._canvas.height=i.height),this._context.drawImage(i,0,0,this._canvas.width,this._canvas.height),t(new VideoFrame(this._canvas,{timestamp:0}))},i.onerror=e=>{n(e)},i.src=r}catch(e){n(e)}})),i=async()=>{let t=performance.now();if(this._dataQueue.length>0){this._timeoutCounter=0;let e=this._dataQueue.shift();if(e)try{let t=await r(e);this._eventEmitter.emit(`frame`,t),t.close()}catch{this._logger.error(`Error decoding frame`)}}else if(this._timeoutCounter++,this._timeoutCounter>this._timeoutCount)return this._logger.warn(`No data to decode, stopping video stream`),this._eventEmitter.emit(`dispose`),void this.dispose();let n=performance.now(),a=Math.max(e-(n-t),0);this._loopId=window.setTimeout(i,a)};i()}on(e,t){this._eventEmitter.on(e,t)}decode(e){this._isDisposed||(this._dataQueue.length>XRe&&(this._logger.warn(`Data queue is full, dropping oldest frame`),this._dataQueue.shift()),this._dataQueue.push(e))}getMediaStream(){if(this._isDisposed)throw Error(`VideoStreamCanvasDecoder has been disposed`);return this._mediaStream}dispose(){this._isDisposed||(this._isDisposed=!0,this._loopId&&=(clearTimeout(this._loopId),0),this._eventEmitter.removeAllListeners())}},W9;function G9(e,t){let n=t?t.length:0,r=performance.now(),i=new ArrayBuffer(9+n),a=new DataView(i);if(a.setUint8(0,e),a.setFloat64(1,r),t){let e=new Uint8Array(i,9);for(let n=0;n<t.length;n++)e[n]=t[n]}return new Uint8Array(i)}function QRe(e){let t=new DataView(e.buffer);return{messageType:t.getUint8(0),timestamp:t.getFloat64(1),data:new Uint8Array(e.buffer,9,e.length-9)}}(function(e){e[e.VideoFrame=1]=`VideoFrame`,e[e.StopVideo=2]=`StopVideo`})(W9||={});var $Re=class{constructor(e,t,n,r){this.audioContext=null,this.analyserNode=null,this.sourceNode=null,this.dataArray=null,this.processingIntervalId=null,this.isCurrentlySpeaking=!1,this.consecutiveSpeechSamples=0,this.consecutiveSilenceSamples=0,this.lastSpeechActivityTimestamp=-1/0,this.callbackFiredForCurrentSegment=!1,this.processAudio=()=>{if(!this.analyserNode||!this.dataArray)return void(this.processingIntervalId!==null&&(clearInterval(this.processingIntervalId),this.processingIntervalId=null,this.logger.warn(`AudioAnalyzer stopped due to missing nodes.`)));this.analyserNode.getByteTimeDomainData(this.dataArray);let e=0;for(let t=0;t<this.dataArray.length;t++){let n=(this.dataArray[t]-128)/128;e+=n*n}let t=Math.sqrt(e/this.dataArray.length),n=this.options.speechConfirmSamples,r=this.options.silenceConfirmSamples,i=this.options.minCallbackIntervalMs;if(t>this.options.silenceThreshold){if(this.consecutiveSpeechSamples++,this.consecutiveSilenceSamples=0,this.consecutiveSpeechSamples>=n){let e=Date.now(),n=e-this.lastSpeechActivityTimestamp;!this.callbackFiredForCurrentSegment&&n>i&&(this.logger.info(`AudioAnalyzer: First audio render callback fired. Silence duration: ${n}ms`),this.onSpeechStartCallback(),this.callbackFiredForCurrentSegment=!0),this.lastSpeechActivityTimestamp=e,this.isCurrentlySpeaking||(this.isCurrentlySpeaking=!0,this.logger.info(`AudioAnalyzer: Speech confirmed after ${this.consecutiveSpeechSamples} consecutive samples, avgVolume: ${t.toFixed(4)}, threshold: ${this.options.silenceThreshold}.`))}}else this.consecutiveSilenceSamples++,this.consecutiveSpeechSamples=0,this.consecutiveSilenceSamples>=r&&this.isCurrentlySpeaking&&(this.isCurrentlySpeaking=!1,this.callbackFiredForCurrentSegment=!1,this.logger.debug(`AudioAnalyzer: Silence confirmed after ${this.consecutiveSilenceSamples} consecutive samples. Ready for next turn.`))},this.stream=e,this.logger=t,this.onSpeechStartCallback=n;let i=Z().waimeabay.audioAnalyzer;this.options={...i,...r},this.stream.getAudioTracks().length?this.initialize():this.logger.warn(`AudioAnalyzer: No audio tracks found in the provided stream.`)}initialize(){try{this.audioContext=new AudioContext,this.analyserNode=this.audioContext.createAnalyser(),this.analyserNode.fftSize=this.options.fftSize,this.analyserNode.smoothingTimeConstant=this.options.smoothingTimeConstant,this.sourceNode=this.audioContext.createMediaStreamSource(this.stream),this.sourceNode.connect(this.analyserNode),this.dataArray=new Uint8Array(this.analyserNode.fftSize),this.logger.info(`AudioAnalyzer initialized.`)}catch(e){this.logger.error(`AudioAnalyzer initialization failed: ${e}`),this.dispose()}}start(){this.audioContext&&this.analyserNode&&this.dataArray?this.processingIntervalId===null&&(this.logger.info(`AudioAnalyzer started monitoring with interval ${this.options.processingIntervalMs}ms.`),this.processingIntervalId=window.setInterval(this.processAudio,this.options.processingIntervalMs)):this.logger.warn(`AudioAnalyzer cannot start, not properly initialized.`)}stop(){this.processingIntervalId!==null&&(clearInterval(this.processingIntervalId),this.processingIntervalId=null,this.logger.info(`AudioAnalyzer stopped monitoring.`))}dispose(){this.stop();try{this.sourceNode?.disconnect(),this.analyserNode?.disconnect(),this.audioContext?.close().catch((e=>this.logger.error(`Error closing AudioContext: ${e}`)))}catch(e){this.logger.error(`AudioAnalyzer dispose error: ${e}`)}finally{this.audioContext=null,this.analyserNode=null,this.sourceNode=null,this.dataArray=null,this.consecutiveSpeechSamples=0,this.consecutiveSilenceSamples=0,this.callbackFiredForCurrentSegment=!1,this.logger.info(`AudioAnalyzer disposed.`)}}};function K9(e){return isNaN(e)?e:Math.round(10*e)/10}var q9=class e{static get instance(){return e._instance||=new e,e._instance}register(e,t){this._requests.set(e,{...t,requestTime:performance.now()})}unregister(e){this._requests.delete(e)}constructor(){this._requests=new Map,globalThis.PerformanceObserver!==void 0&&(this._observer=new PerformanceObserver((e=>{e.getEntries().forEach((e=>{if(e.entryType===`resource`){let t=e;if((t.requestStart??0)<=0)return;let n=e.name,r=this._requests.get(n);if(r){let e=r.path;this.unregister(n);let i={path:e,duration:K9(t.duration),initiatorType:t.initiatorType,nextHopProtocol:t.nextHopProtocol,fetchStart:K9(t.fetchStart),domainLookupStart:K9(t.domainLookupStart),domainLookupEnd:K9(t.domainLookupEnd),connectStart:K9(t.connectStart),secureConnectionStart:K9(t.secureConnectionStart),connectEnd:K9(t.connectEnd),requestStart:K9(t.requestStart),responseStart:K9(t.responseStart),responseEnd:K9(t.responseEnd),transferSize:t.transferSize,encodedBodySize:t.encodedBodySize,responseStatus:t.responseStatus};r.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:r.correlationId,operationName:`FetchTimingInfo`,durationInMs:i.duration,operationPayload:{...i},resultCategories:[`Success`],resultSignature:200,sessionId:r.sessionId,endpointId:r.endpointId})}}}))})),this._observer.observe({type:`resource`,buffered:!1}))}dispose(){e._instance&&=(this._requests.clear(),this._observer?.disconnect(),null)}};q9._instance=null;var eze,tze=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},J9=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},nze=e=>{try{return new URL(e)}catch{return}},rze=e=>{let t=`Request`;if(e instanceof URL)return{href:e.toString(),pathname:e.pathname??``};if(typeof Request<`u`&&e instanceof Request)return rze(e.url);if(typeof e==`string`){let n=nze(e);return n?{href:n.href,pathname:n.pathname??``}:{href:e||t,pathname:``}}return{href:t,pathname:``}},ize=class{constructor(e){this._params=e,this._state=DG.Connecting,this._initializeRefTime=0,this._isMuted=!1,this._remoteAudioStreams=new Map,this._remoteVideoStreams=new Map,this._joinSessionDefer=e3(),this._feedViewDefer=e3(),this._audioRenderers=new Map,this._audioAnalyzers=new Map,this._endpointId=``,this._wbSessionStats={localCandidateType:``,relayCandidateCount:0},this._localAudioStreams=new Set,this._localVideoStreams=new Set,this._audioEffectsProcessorStats=[],this._audioEffectsStatsListener=null,this._audioEffectsSubscribedStream=null,this._videoChannel=void 0,this._videoStreamEncoder=void 0,this._videoStreamDecoder=new Map,this._telemetryChannel=void 0,this._telemetryChannelInitializationPromise=void 0,this._sessionConnectedTimestamp=void 0,this._sessionConnectedSignalSent=!1,this.startAudio=async(e,t)=>{let n=performance.now(),r=K0();try{if(this._params.logger.debug(`SessionImpl: startAudio called`),this._joinSessionDefer&&(setTimeout((()=>{if(this._joinSessionDefer?.isPending())return this._joinSessionDefer.reject(new Y({defaultError:J.WB_MEDIA_SDK.SESSION.STARTAUDIO_SESSION_TIMEDOUT}))}),Z().waimeabay.audio.startAudioSessionTimeoutMs),await this._joinSessionDefer.promise),this._outboundAudio&&this._outgoingMediaStream&&!this._isMuted)try{let e=this._outgoingMediaStream.getAudioTracks()[0];e&&(this._outboundAudio.setMediaSource(e),this._params.logger.info(`Applied pending outbound audio stream with stream ID: ${this._outgoingMediaStream.id}`))}catch(e){this._params.logger.error(`Failed to apply pending outbound audio stream: ${e instanceof Error?e.message:String(e)}`)}let i=!1,a=async()=>{i=!0,this._params.logger.debug(`Use normal real-time LocalAudioStream in session`);let e=this._params.options?.localAudioStream?this._params.options?.localAudioStream:await Y5(this._params.deviceManagerInternal,this._params.logger);await this.handleLocalAudioStream(e,!0,r,t)};try{this._preAudioFeature=e;let t=+new Date;if(this._preAudioFeature)if(this._preAudioFeature.recordAudioFailed||!this._preAudioFeature.recordAudioFinished){let e=+new Date,t=new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.USE_NORMALMIC_OR_RAWAUDIO_BECAUSE_RECORDAUDIO_FAILED});this._preAudioFeature.recordAudioFinished||(t=new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.USE_NORMALMIC_OR_RAWAUDIO_BECAUSE_RECORDAUDIO_FAILED})),this._preAudioFeature.logger.error(t.message),await this._preAudioFeature?.disposeInternal(),await this._preAudioFeature?.disposeRtcMic(),await a(),this._preAudioFeature.sendTelemetryEvent(+new Date-e,{timestampInfo:{attemptTimestamp:e},...K3(t)},t.resultCategories,500)}else{let{micLocalAudioStream:e,micRawMediaStream:n}=this._preAudioFeature.getMicMediaStream();if(this._preAudioFeature.isFinished){if(this._preAudioFeature.logger.debug(`PreAudio already finished, will use it's real-time mic for session start`),this._sessionConnectedTimestamp===void 0){let e=this._preAudioFeature.getFirstSpeechTimestamp();e!==void 0&&(this.setFirstClientAudioTimestamp(e),this._params.logger.debug(`Applied finished preAudio speech timestamp ${e}`))}await this.handleLocalAudioStream(e)}else{this._params.logger.debug(`Get PreAudio's player audio stream to use for session start`);let t=await this._preAudioFeature.getPlayerLocalAudioStream(this,(async()=>{let r=+new Date;try{if(!this._preAudioFeature)throw new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.SWITCH_TO_RTCMIC_FAIL_PREAUDIO_UNDEFINED});this._preAudioFeature.logger.debug(`PreAudio player mediastream finished flushing`),this._preAudioFeature.logger.debug(`Now switching to real-time microphone in session`),this._preAudioFeature.disposeInternal().catch((()=>{this._preAudioFeature?.logger.error(`Failed to dispose PreAudio feature after preAudio finished and got called back.`)})),this._localAudioStreams.delete(t),await this.handleLocalAudioStream(e,!1),this.updateOutboundAudioStream(n),n.getAudioTracks().forEach((e=>{e.enabled=!0})),this._eventEmitter.emit(`localAudioStreamsUpdated`,{added:[],removed:[t]}),this._preAudioFeature.logger.debug(`Switched to default real-time microphone in session`),this._preAudioFeature.sendTelemetryEvent(+new Date-r,{step:J5.SWITCHED_TO_REALTIME_MIC,timestampInfo:{attemptTimestamp:r}},[`Success`],200)}catch(e){this._preAudioFeature?.logger.error(`Failed to switch to default real-time microphone after preAudio player mediastream finished flushing`,e);let t=new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.SWITCH_TO_RTC_MIC_FAIL,originalError:e});this._preAudioFeature?this._preAudioFeature.sendTelemetryEvent(+new Date-r,{timestampInfo:{attemptTimestamp:r},...K3(t)},[`Failure`],500):this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:``,operationName:`PreAudio`,durationInMs:+new Date-r,operationPayload:{timestampInfo:{attemptTimestamp:r},...K3(t)},resultCategories:[`Failure`],resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId})}}));await this.handleLocalAudioStream(t)}this._preAudioFeature.setEchoRefStream(this),this.subscribeToAudioEffectsStats(e),this._preAudioFeature.logger.debug(`Set PreAudio's ${this._preAudioFeature.isFinished?`real-time mic`:`player audio stream`} for session start`),this._preAudioFeature.sendTelemetryEvent(+new Date-t,{step:this._preAudioFeature.isFinished?J5.START_SESSION_WITH_RTC_MIC:J5.START_SESSION_WITH_PLAYER_AUDIO_STREAM,timestampInfo:{attemptTimestamp:t}},[`Success`],200)}else await a()}catch(e){if(i)throw e;await a()}this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:r,operationName:`StartAudio`,durationInMs:performance.now()-n,operationPayload:{},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId})}catch(e){let t=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.START_AUDIO_FAILED,originalError:e});throw this._params.logger.error(`SessionImpl: startAudio error`,t),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:r,operationName:`StartAudio`,durationInMs:performance.now()-n,operationPayload:{...K3(t).communicationServicesError},resultCategories:t.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId}),t}},this.createIncomingAudioHandler=async e=>{e.inboundAudio.getAllSourceMedia().firesAll((e=>{let{isLocal:t,endpointId:n,sourceId:r}=e.metadata;if(this._params.logger.debug(`Inbound firesAll media received from ${n}, isLocal: ${t}`),!t)try{e.provider.acquire().fires((e=>{try{if(e.track){this._sessionConnectedTimestamp===void 0&&(this._sessionConnectedTimestamp=Date.now(),this._params.logger.info(`SessionConnectedTimestamp set on first remote audio track arrival: ${this._sessionConnectedTimestamp}`));let t=new MediaStream;t.addTrack(e.track);let i=this._params.tsStack.getDeviceManager().createAudioRenderer?.();if(i?.play(t),this._audioRenderers.set(n,i),Z().waimeabay.sendTelemetrySignal){this._sessionConnectedSignalSent||this._sessionConnectedTimestamp===void 0||(this.sendTelemetrySignal(S4.SessionConnected,this._sessionConnectedTimestamp),this._sessionConnectedSignalSent=!0);let e=new $Re(t,this._params.logger,(()=>{this.sendTelemetrySignal(S4.FirstAudioRender)}));e.start(),this._audioAnalyzers.set(n,e)}let a={sourceId:r,endpointId:n,type:`Audio`,mediaStream:t};this._remoteAudioStreams.set(n,a),this.sendStreamsUpdatedTelemetry(a,`added`),this._eventEmitter.emit(`streamsUpdated`,{added:[a],removed:[]})}}catch(e){let t=e instanceof Error?e.message:JSON.stringify(e);this._params.logger.error(`Error handling media track event from ${n}: ${t}`),this.sendStreamsUpdatedFailureTelemetry({endpointId:n,sourceId:r,type:`Audio`,action:`added`,failureType:`mediaTrackEvent`,failureReason:t})}}))}catch(e){let t=e instanceof Error?e.message:JSON.stringify(e);this._params.logger.error(`Error acquiring audio track queue from ${n}: ${t}`),this.sendStreamsUpdatedFailureTelemetry({endpointId:n,sourceId:r,type:`Audio`,action:`added`,failureType:`acquireMediaTrackQueue`,failureReason:t})}try{let t=e.provider.acquire();(async()=>{try{let e=await t;for(;!e.done;)e=await e.next;let r=this._remoteAudioStreams.get(n),i=this._audioRenderers.get(n),a=this._audioAnalyzers.get(n);a&&(a.dispose(),this._audioAnalyzers.delete(n)),t.dispose(),i&&(i.dispose(),this._audioRenderers.delete(n)),r&&(this._remoteAudioStreams.delete(n),this.sendStreamsUpdatedTelemetry(r,`removed`),this._eventEmitter.emit(`streamsUpdated`,{added:[],removed:[r]}))}catch(e){let t=e instanceof Error?e.message:JSON.stringify(e);this._params.logger.error(`Error processing audio track queue from ${n}: ${t}`),this.sendStreamsUpdatedFailureTelemetry({endpointId:n,sourceId:r,type:`Audio`,action:`removed`,failureType:`processMediaTrackQueue`,failureReason:t})}})()}catch(e){let t=e instanceof Error?e.message:JSON.stringify(e);this._params.logger.error(`Error acquiring audio track queue from ${n}: ${t}`),this.sendStreamsUpdatedFailureTelemetry({endpointId:n,sourceId:r,type:`Audio`,action:`removed`,failureType:`acquireMediaTrackQueue`,failureReason:t})}}))},this.handleLocalAudioStream=async(e,t=!0,n,r)=>{if(this._localAudioStreams.add(e),e.addSession(this),r&&e.mediaStreamType===`Audio`){let t=!1;try{await this.startAudioEffects(e,r)}catch{this._params.logger.error(`Failed to start effects for normal audio.`),t=!0}if(!t)try{this.subscribeToAudioEffectsStats(e)}catch{this._params.logger.error(`Failed to subscribe to audio effects stats for normal audio.`)}}if(t){let t;if(e.mediaStreamType===`RawMedia`)t=await e.getMediaStream();else{let e=async(e,t=!1)=>{let r=+new Date;try{let n=await e.getMediaStream(!0);if(!n)throw t?new Y({defaultError:J.WB_MEDIA_SDK.LOCAL_AUDIO_STREAM.LOCAL_AUDIO_GET_MEDIA_STREAM_UNDEFINED_FIRSTATTEMPT_ONCHANGED}):new Y({defaultError:J.WB_MEDIA_SDK.LOCAL_AUDIO_STREAM.LOCAL_AUDIO_GET_MEDIA_STREAM_UNDEFINED_FIRSTATTEMPT});return n}catch(i){let a=W3(i,!0,new Y({defaultError:J.WB_MEDIA_SDK.SESSION.FAILED_TO_GETMEDIASTREAM,originalError:i}));this._params.logger.error(`Error getting media stream, trying again`,a.message),this.sendHandleLocalAudioStreamFailureTelemetry(a,r,{...K3(a).communicationServicesError},n);try{let n=await e.getMediaStream();if(!n)throw t?new Y({defaultError:J.WB_MEDIA_SDK.LOCAL_AUDIO_STREAM.LOCAL_AUDIO_GET_MEDIA_STREAM_UNDEFINED_SECONDATTEMPT_ONCHANGED}):new Y({defaultError:J.WB_MEDIA_SDK.LOCAL_AUDIO_STREAM.LOCAL_AUDIO_GET_MEDIA_STREAM_UNDEFINED_SECONDATTEMPT});return n}catch(e){let t=W3(e,!0,new Y({defaultError:J.WB_MEDIA_SDK.SESSION.FAILED_TO_GETMEDIASTREAM,originalError:e}));throw this._params.logger.error(`Error getting media stream on second attempt`,t.message),t}}},r=async()=>{let t=+new Date;try{if(!this._tsRawStream){let e=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.NO_TS_RAW_STREAM_PRESENT_ONCHANGED});throw this._params.logger.error(e.message),e}{let t=await e(this._tsRawStream,!0);this.updateOutboundAudioStream(t),this._isMuted&&(this._isMuted=!1,this.mute())}}catch(e){let r=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.FAILED_TO_GETMEDIASTREAM_ONCHANGED,originalError:e});this.sendHandleLocalAudioStreamFailureTelemetry(r,t,{...K3(r).communicationServicesError},n)}};this._tsRawStream=this._params.deviceManagerInternal.getRawDeviceMediaStream(0),this._tsRawStream.changed((()=>{this._params.logger.log(`RawDeviceMediaStream changed`),r()})),t=await e(this._tsRawStream)}this.updateOutboundAudioStream(t)}this._eventEmitter.emit(`localAudioStreamsUpdated`,{added:[e],removed:[]})},this.createVideoHandler=async()=>{let e=Z().waimeabay.video,t=new W5(this,{payloadType:e.payloadType,transmissionMode:G5.PartiallyReliable,isLargeData:!0},this._params.logger,this._params.telemetryLogManager);await t.initialize(),t.on(`message`,(e=>{let{data:t,endpointId:n}=e;this._params.logger.log(`video data received: ${t.length} bytes from ${n}`);let r=QRe(t);if(r.messageType!==W9.StopVideo){if(r.messageType===W9.VideoFrame){if(!this._videoStreamDecoder.has(n)){let e=Z().waimeabay.video.timeoutCount,t=new ZRe(1e3,this._params.logger,e),r={sourceId:0,endpointId:n,type:`Video`,mediaStream:t.getMediaStream()};this._remoteVideoStreams.set(n,r),t.on(`dispose`,(()=>{this._videoStreamDecoder.delete(n),this._remoteVideoStreams.delete(n),this.sendStreamsUpdatedTelemetry(r,`removed`),this._eventEmitter.emit(`streamsUpdated`,{added:[],removed:[r]})})),this.sendStreamsUpdatedTelemetry(r,`added`),this._eventEmitter.emit(`streamsUpdated`,{added:[r],removed:[]}),t.on(`frame`,(e=>{this._params.logger.log(`video frame received: ${e.displayWidth}x${e.displayHeight} from ${n}`)})),this._videoStreamDecoder.set(n,t)}this._videoStreamDecoder.get(n).decode(r.data)}}else{let e=this._videoStreamDecoder.get(n);if(e){e.dispose(),this._videoStreamDecoder.delete(n);let t=this._remoteVideoStreams.get(n);t&&(this._remoteVideoStreams.delete(n),this.sendStreamsUpdatedTelemetry(t,`removed`),this._eventEmitter.emit(`streamsUpdated`,{added:[],removed:[t]}))}}})),this._videoChannel=t},this.sendHandleLocalAudioStreamFailureTelemetry=(e,t,n,r)=>{this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:r||``,operationName:`StartAudio`,durationInMs:+new Date-t,operationPayload:{...K3(e).communicationServicesError},resultCategories:e.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId})},e.logger.debug(`SessionImpl: constructor called with sessionId: ${e.sessionId}, localAudioSteam: ${!!e.options?.localAudioStream}, localVideoStream: ${!!e.options?.localVideoStream}`),this._eventEmitter=new S6(this._params.logger),this._extensibleApi=new N3(e.logger,{session:this,sessionAgent:e.sessionAgent},{tsSession:e.tsWbSession,sessionAgent:e.sessionAgent,session:this,telemetryLogManager:e.telemetryLogManager})}get audioEffectsProcessorStats(){return this._audioEffectsProcessorStats}clearAudioEffectsProcessorStats(){this._audioEffectsProcessorStats=[]}feature(e){return this._extensibleApi.getApiObjectInstance(e.sessionApiCtor)}get localAudioStreams(){return Array.from(this._localAudioStreams)}get localVideoStreams(){return Array.from(this._localVideoStreams)}get state(){return this._state}get isMuted(){return this._isMuted}get remoteAudioStreams(){return Array.from(this._remoteAudioStreams.values())}get remoteVideoStreams(){return Array.from(this._remoteVideoStreams.values())}get endpointId(){return this._endpointId}get sessionId(){return this._params.sessionId}get feedSession(){return this._session}mute(){let e=performance.now(),t=K0();try{this._params.logger.debug(`SessionImpl: mute called`,t),this.validateSessionState(o4.Mute),this._preAudioFeature&&!this._preAudioFeature.isFinished?(this._preAudioFeature.muteRtcMic(),this._isMuted=!0):this._isMuted||this.toggleAudioMuteState(),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`Mute`,durationInMs:performance.now()-e,operationPayload:{wasMuted:this._isMuted},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId})}catch(n){let r=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.MUTE_FAILED,originalError:n});throw this._params.logger.error(`SessionImpl: mute error`,n),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`Mute`,durationInMs:performance.now()-e,operationPayload:{...K3(r).communicationServicesError},resultCategories:r.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId}),r}}unmute(){let e=performance.now(),t=K0();try{this._params.logger.debug(`SessionImpl: unmute called`,t),this.validateSessionState(o4.Unmute),this._preAudioFeature&&!this._preAudioFeature.isFinished?(this._preAudioFeature.unmuteRtcMic(),this._isMuted=!1):this._isMuted&&this.toggleAudioMuteState(),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`Unmute`,durationInMs:performance.now()-e,operationPayload:{wasMuted:!this._isMuted},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId})}catch(n){let r=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.UNMUTE_FAILED,originalError:n});throw this._params.logger.error(`SessionImpl: unmute error`,n),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`Unmute`,durationInMs:performance.now()-e,operationPayload:{...K3(r).communicationServicesError},resultCategories:r.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId}),r}}async startRawAudio(e){try{if(this.validateSessionState(o4.StartAudio),this._params.logger.debug(`SessionImpl: startAudio called`),e?.mediaStreamType!==`RawMedia`)throw new Y({defaultError:J.WB_MEDIA_SDK.SESSION.START_RAW_AUDIO_LAS_NOT_RAW_MEDIA});this._outboundAudio&&this._outboundAudio.clearMediaSource();let t=Array.from(this._localAudioStreams)[0];t&&(this._localAudioStreams.delete(t),this._eventEmitter.emit(`localAudioStreamsUpdated`,{added:[],removed:[t]}),this._cachedLocalAudioStreamBeforeRawAudioStarted=t),await this.handleLocalAudioStream(e),this.sendTelemetrySignal(S4.StartRawAudio)}catch(e){let t=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.START_RAW_AUDIO_FAILED,originalError:e});throw this._params.logger.error(`SessionImpl: startAudio error`,e),t}}async stopRawAudio(){try{this.validateSessionState(o4.StopAudio),this._params.logger.debug(`SessionImpl: stopAudio called`);let e=Array.from(this._localAudioStreams)[0];if(e?.mediaStreamType!==`RawMedia`)throw new Y({defaultError:J.WB_MEDIA_SDK.SESSION.STOP_RAW_AUDIO_LAS_NOT_RAW_MEDIA});this._outboundAudio&&this._outboundAudio.clearMediaSource(),this._localAudioStreams.delete(e),this._eventEmitter.emit(`localAudioStreamsUpdated`,{added:[],removed:[e]});let t=this._cachedLocalAudioStreamBeforeRawAudioStarted||await Y5(this._params.deviceManagerInternal,this._params.logger);await this.handleLocalAudioStream(t),this._cachedLocalAudioStreamBeforeRawAudioStarted=void 0,this.sendTelemetrySignal(S4.StopRawAudio)}catch(e){let t=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.STOP_RAW_AUDIO_FAILED,originalError:e});throw this._params.logger.error(`SessionImpl: stopAudio error`,e),t}}muteIncomingAudio(){let e=performance.now(),t=K0();try{this._params.logger.debug(`SessionImpl: muteIncomingAudio called`,t),this.validateSessionState(o4.MuteIncomingAudio),this._audioRenderers.forEach((e=>e.setMuted(!0))),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`MuteIncomingAudio`,durationInMs:performance.now()-e,operationPayload:{audioRenderersCount:this._audioRenderers.size},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId})}catch(n){let r=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.MUTE_INCOMING_AUDIO_FAILED,originalError:n});throw this._params.logger.error(`SessionImpl: muteIncomingAudio error`,n),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`MuteIncomingAudio`,durationInMs:performance.now()-e,operationPayload:{...K3(r).communicationServicesError},resultCategories:r.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId}),r}}unmuteIncomingAudio(){let e=performance.now(),t=K0();try{this._params.logger.debug(`SessionImpl: unmuteIncomingAudio called`,t),this.validateSessionState(o4.UnmuteIncomingAudio),this._audioRenderers.forEach((e=>e.setMuted(!1))),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`UnmuteIncomingAudio`,durationInMs:performance.now()-e,operationPayload:{audioRenderersCount:this._audioRenderers.size},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId})}catch(n){let r=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.UNMUTE_INCOMING_AUDIO_FAILED,originalError:n});throw this._params.logger.error(`SessionImpl: unmuteIncomingAudio error`,n),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`UnmuteIncomingAudio`,durationInMs:performance.now()-e,operationPayload:{...K3(r).communicationServicesError},resultCategories:r.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId}),r}}async startVideo(e){try{if(this.validateSessionState(o4.StartVideo),this._videoStreamEncoder){let e=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.VIDEO_ALREADY_STARTED});throw this._params.logger.error(e.message),e}this._localVideoStreams.add(e);let t=await e.getMediaStream(),n=Z().waimeabay.video.defaultWidth,r=Z().waimeabay.video.defaultHeight,i=Z().waimeabay.video.refreshInterval;this._videoStreamEncoder=new YRe(t,n,r,i,this._params.logger),this._videoStreamEncoder.on(`data`,(e=>{this._videoChannel?.send(G9(W9.VideoFrame,e))})),e.mediaStreamType===`Video`&&e.disposeRawStream()}catch(e){let t=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.START_VIDEO_FAILED,originalError:e});throw this._params.logger.error(`SessionImpl: startVideo error`,e),t}}stopVideo(){try{this._videoStreamEncoder&&(this._videoStreamEncoder.dispose(),this._videoStreamEncoder=void 0,this._videoChannel?.send(G9(W9.StopVideo))),Array.from(this._localVideoStreams.values()).forEach((e=>{this._localVideoStreams.delete(e)}))}catch(e){let t=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.STOP_VIDEO_FAILED,originalError:e});throw this._params.logger.error(`SessionImpl: stopVideo error`,e),t}}cleanup(){try{this._joinSessionDefer&&this._joinSessionDefer.dispose(),this._joinSessionDefer=void 0,this._audioRenderers.forEach((e=>e.dispose())),this._audioRenderers.clear(),this._audioAnalyzers.forEach((e=>e.dispose())),this._audioAnalyzers.clear(),this._videoStreamEncoder&&(this._videoStreamEncoder.dispose(),this._videoStreamEncoder=void 0,this._videoChannel?.send(G9(W9.StopVideo))),this.localVideoStreams.forEach((e=>{e.autoDisposeOnCallEnd&&e.dispose(),this._localVideoStreams.delete(e)})),this._params.sessionAgent.removeSession({sessionId:this._params.sessionId}),this._outboundAudio?.dispose(),this._feedView?.dispose();let e=this._state;if(this._state=DG.Disconnected,e!==this._state){let t=this._initializeRefTime>0?performance.now()-this._initializeRefTime:0,n=K0();this.logTelemetryWithEndpointId(n,t,e),this._params.logger.info(`Session state changed from ${e} to ${this._state}`),this._eventEmitter.emit(`stateChanged`)}this._eventEmitter.removeAllListeners(),this._extensibleApi.dispose()}catch(e){this._params.logger.error(`SessionImpl: Failed to cleanup with error: ${e instanceof Error?e.message:String(e)}`)}}disconnectInternal(e){let t=K0(),n=performance.now();this._params.logger.debug(`SessionImpl: hangUp called`,t);try{if(this._audioEffectsStatsListener&&this._audioEffectsSubscribedStream){try{this._audioEffectsSubscribedStream.feature(Z5.AudioEffects)?.off(`effectsProcessorStatsUpdated`,this._audioEffectsStatsListener)}catch(e){this._params.logger.warn(`Error cleaning up audio effects stats subscription on disconnect: ${e}`)}this._audioEffectsStatsListener=null}this._audioEffectsProcessorStats=[],this._audioEffectsSubscribedStream=null,this.localAudioStreams.forEach((e=>{e.removeSession(this),e.autoDisposeOnCallEnd&&e.dispose()})),this._localAudioStreams.clear(),this._tsRawStream&&=(this._tsRawStream.dispose(),void 0),this._preAudioFeature?.disposeRtcMic().catch((e=>{this._params.logger.error(`Error disposing rtc mic in preAudioFeature`,e)})),this._telemetryChannel&&=(this._telemetryChannel.dispose(),void 0),this._sessionConnectedTimestamp=void 0,this._sessionConnectedSignalSent=!1,this._session?.dispose(),this.cleanup(),this._params.logger.debug(`SessionImpl: hangUp success`,t),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`DisconnectSession`,durationInMs:performance.now()-n,operationPayload:{source:e},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId})}catch(r){let i=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.DISCONNECT_FAILED,originalError:r});throw this._params.logger.error(`SessionImpl: hangUp error`,r),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`DisconnectSession`,durationInMs:performance.now()-n,operationPayload:{...K3(i).communicationServicesError,source:e},resultCategories:i.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId}),i}}disconnect(){this.disconnectInternal(`client`)}disconnectFromUnload(e){this.disconnectInternal(e)}on(e,t){this._params.logger.debug(`Raising event: ${e}`),e!==`stateChanged`&&e!==`streamsUpdated`&&e!==`configureRequest`&&e!==`localAudioStreamsUpdated`||this._eventEmitter.on(e,t)}off(e,t){this._params.logger.debug(`Unsubscribing from event: ${e}`),e!==`stateChanged`&&e!==`streamsUpdated`&&e!==`configureRequest`&&e!==`localAudioStreamsUpdated`||this._eventEmitter.off(e,t)}async createDataChannel(e,t){let n=e.payloadType,r;switch(this._feedView||await this._feedViewDefer.promise,this._feedView.setInboundDataConfig(n,{maxStreams:Z().waimeabay.dataChannel.maxStreams,messageDeserializer:e=>e}).getInboundData(n).getAllSourceMedia().firesAll((({metadata:e,onMessageEvent:n,onDispose:r})=>{let i=e.endpointId;n.fires((e=>{t(i,e)})),r.then((()=>{this._params.logger.log(`Data stream got disposed`,i)}))})),e.transmissionMode){case G5.Realtime:r=H5.MediaTransmissionMode.REALTIME;break;case G5.PartiallyReliable:r=H5.MediaTransmissionMode.PARTIALLY_RELIABLE;break;default:r=void 0}return this._session.createOutboundData({payloadType:n,messageSerializer:e=>e,initialState:new Uint8Array,...r===void 0?{}:{transmissionMode:r}}).setFeedIds(Z().waimeabay.feedId)}async initialize(e){try{await this._internalInitialize(e)}catch(e){throw this._feedView?this._feedViewDefer.resolve():this._feedViewDefer.reject(e),e}}async _internalInitialize(e){let t=performance.now();this._initializeRefTime=t;let n=K0();this._params.logger.debug(`SessionImpl: initialize called`,n),this._params.tsWbSession.on(`callQualityChanged`,(e=>{this._params.logger.debug(`SessionQualityChanged: ${JSON.stringify(e)}`)}));let r={sendEvent:e=>{this._params.telemetryLogManager.sendWbEvent({...this._endpointId?{endpointId:this._endpointId}:{},sessionId:this._params.sessionId,eventData:e})}},i=performance.now();try{this._session=await this._params.tsWbSession.createFeedSession({serviceOrigin:this.getServiceOrigin(),telemetryLogger:r,authorizationHeaderProvider:async()=>`Bearer `+await this._params.sessionAgent.tokenProvider(),httpFetch:async(e,t)=>{let r=performance.now(),{href:i,pathname:a}=rze(e),o=(e,t)=>{let o=performance.now()-r,s=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.JOIN_FAILED,originalError:e.error}),c=e.headers?.get(`X-Azure-Ref`),l=e.headers?.get(`x-ms-request-id`),u=e.headers?.get(`x-cache`),d=e.headers?.get(`ms-region-name`),f=e.headers?.get(`ms-stamp-name`),p=e.headers?.get(`ms-ring-name`);this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:n,operationName:`HTTPRequest`,durationInMs:o,operationPayload:{...e.status===void 0?{}:{status:e.status},...e.statusText===void 0?{}:{statusText:e.statusText},...c?{"X-Azure-Ref":c}:{},...l?{xMsRequestId:l}:{},...u?{xCache:u}:{},...d?{msRegionName:d}:{},...f?{msStampName:f}:{},...p?{msRingName:p}:{},pathName:a,...K3(s).communicationServicesError},resultCategories:s.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId});let m=e.status===void 0?e.error:`status ${e.status}`;if(this._params.logger.error(`HTTP fetch failed for ${i}:`,m),t)throw s},s=(e,t,o)=>{let s=performance.now()-r,c=o.get(`X-Azure-Ref`),l=o.get(`x-ms-request-id`),u=o.get(`x-cache`),d=o.get(`ms-region-name`),f=o.get(`ms-stamp-name`),p=o.get(`ms-ring-name`);this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:n,operationName:`HTTPRequest`,durationInMs:s,operationPayload:{status:e,statusText:t,...c?{"X-Azure-Ref":c}:{},...l?{xMsRequestId:l}:{},...u?{xCache:u}:{},...d?{msRegionName:d}:{},...f?{msStampName:f}:{},...p?{msRingName:p}:{},pathName:a},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId}),this._params.logger.debug(`HTTP fetch succeeded for ${i} - Status: ${e}`)},c={...t?.headers instanceof Headers?(()=>{let e={};return t.headers.forEach(((t,n)=>{e[n]=t})),e})():t?.headers,"X-Microsoft-Skype-Chain-ID":this._params.sessionId};try{q9.instance.register(i,{path:a,correlationId:n,sessionId:this._params.sessionId,endpointId:this._endpointId,telemetryLogManager:this._params.telemetryLogManager});let r=await globalThis.fetch(e,{...t,headers:c});return this._params.logger.debug(`HTTP fetch to ${e} - Status: ${r.status}`),r.ok?s(r.status,r.statusText,r.headers):o({error:Error(`HTTP request failed with status ${r.status}`),status:r.status,statusText:r.statusText,headers:r.headers},!1),r}catch(e){return o({error:e},!0)}},applicationInfo:this._params.clientTypeInfo}),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:n,operationName:`CreateFeedSession`,durationInMs:performance.now()-i,operationPayload:{},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId})}catch(e){let t=performance.now()-i,r=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.JOIN_FAILED,originalError:e});throw this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:n,operationName:`CreateFeedSession`,durationInMs:t,operationPayload:{...K3(r).communicationServicesError},resultCategories:r.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId}),this._params.logger.error(`CreateFeedSession failed`,r),r}let a=e=>{if(this._connectionState===e)return;let r=performance.now()-t,i=e=>{if(e===void 0)return`Initial`;switch(e){case H5.SessionConnectionState.CONNECTING:return`Connecting`;case H5.SessionConnectionState.CONNECTED:return`Connected`;case H5.SessionConnectionState.FAILOVER:return`Failover`;case H5.SessionConnectionState.DISCONNECTED:return`Disconnected`;default:return`UNKNOWN`}},a=i(this._connectionState),o=i(e);this._connectionState=e,this._params.logger.info(`Session transport state changed: ${a} -> ${o}`);let s={eventName:Q.acs_wb_session_events,operationId:n,operationName:`TransportStateChanged`,durationInMs:r,operationPayload:{oldState:a,newState:o,...this._wbSessionStats},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId};this._params.telemetryLogManager.sendWbSessionEvent(s)},o,s;this._session.stats.fires((e=>{let t=e.localCandidateType??``;this._wbSessionStats.localCandidateType!==t&&(this._wbSessionStats.localCandidateType=t,this._params.logger.info(`Local candidate type of active connection is ${this._wbSessionStats.localCandidateType}`)),this._wbSessionStats.relayCandidateCount=e.relayCandidateCount??0})),this._session.connectionState.fires((e=>{a(e)})),a(this._session.connectionState.value),this._session.metadata.then((e=>{let r=performance.now()-t;this._joinSessionDefer&&this._joinSessionDefer.resolve(this._session),this._endpointId=e.endpointId,this._params.logger.debug(`Session metadata received in ${r} ms for endpointId ${this._endpointId} `),this._params.tsWbSession.setAdditionalTelemetryFields({WB_SessionId:this._params.sessionId,WB_EndpointId:this._endpointId,WB_RoomId:this._params.sessionId}),this._params.logger.debug(`MediaStreamSession: setAdditionalTelemetryFields on _tsWbSession with sessionId: ${this._params.sessionId}, endpointId: ${this._endpointId}`),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:n,operationName:`AllocateSession`,durationInMs:r,operationPayload:{},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId}),this.emitConfigureRequest(e)})).catch((e=>{let r=performance.now()-t,i=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.JOIN_FAILED,originalError:e});this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:n,operationName:`AllocateSession`,durationInMs:r,operationPayload:{...K3(i).communicationServicesError},resultCategories:i.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId}),this._params.logger.error(`Session metadata error`,i)})),this._feedView=this._session.createFeedView().setFeedId(Z().waimeabay.feedId).setInboundAudioConfig({maxStreams:Z().waimeabay.audio.maxStreams,reflectionMode:H5.MediaReflectionMode.NONE}),this._feedViewDefer.resolve(),this._session.onConnect.then((async()=>{let r=performance.now()-t;if(this._params.logger.debug(`WB Connected in ${r} ms for endpointId ${this._endpointId} `),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:n,operationName:`JoinSession`,durationInMs:r,operationPayload:{feedId:Z().waimeabay.feedId,isPreheated:!!e,isDisconnected:this._state===DG.Disconnected},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId}),this._state!==DG.Disconnected){let t=this._state;this._state=e&&t!==DG.Connected?DG.Preheated:DG.Connected,this.logTelemetryWithEndpointId(n,r,t),t!==this._state&&(this._params.logger.info(`Session state changed from ${t} to ${this._state}`),this._eventEmitter.emit(`stateChanged`))}})).catch((e=>{let r=performance.now()-t,i=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.JOIN_FAILED,originalError:e});this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:n,operationName:`AllocateSession`,durationInMs:r,operationPayload:{...K3(i).communicationServicesError},resultCategories:i.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId}),this._params.logger.error(`Session connection error`,i),this._joinSessionDefer&&this._joinSessionDefer.isPending()&&this._joinSessionDefer.reject(e)})),this._session.onDisconnect.then((e=>{o=e})).catch((e=>{let t=e instanceof Error?e.message:JSON.stringify(e);this._params.logger.error(`Session disconnected with an error: ${t}`),s={...o,errorMessage:t}})).finally((()=>{let e=performance.now()-t;this._params.logger.debug(`Session disconnected in ${e} ms, cause: ${JSON.stringify(o)}`),setTimeout((async()=>{let e=await this._params.tsWbSession.getMediaTelemetry();this._params.logger.info(`WBStats mediaTelemetry ${JSON.stringify(e)}`),this._params.tsWbSession.reportMediaTelemetry(),this._params.logger.info(`reportMediaTelemetry called on disconnect.`)}),3e3);let r=this._state;r!==DG.Disconnected&&(this._state=DG.Disconnected,this.logTelemetryWithEndpointId(n,e,r,s||o),this._params.logger.info(`Session state changed from ${r} to ${this._state}`),this._eventEmitter.emit(`stateChanged`),this.cleanup())}));let c=Q5(D3.SessionFeature);for(let e of c)e.activationOptions.activationEvent===`OnExtendedObjectConstructor`&&this.feature(e);if(e||await this.startMedia(!1),Z().waimeabay.sendTelemetrySignal)try{await this.initializeTelemetryChannel(),this._params.logger.info(`Initialize: TelemetryChannel initialized successfully by main initialize flow!`)}catch(e){this._params.logger.error(`Initialize: Main initialize flow failed to initialize TelemetryChannel: ${e instanceof Error?e.message:String(e)}`)}}async startMedia(e,t){let n=performance.now(),r=K0();if(this._state===DG.Disconnected)return this._params.logger.error(`SessionImpl: startMedia called in invalid state: ${this._state}`),void this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:r,operationName:`StartMedia`,durationInMs:performance.now()-n,operationPayload:{isPreheated:!!e},resultCategories:[`UnexpectedClientError`],resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId});t&&this._params.setOptions(t);try{this.createIncomingAudioHandler(this._feedView),this._outboundAudio||=this._session.createOutboundAudio().setFeedIds(Z().waimeabay.feedId);let t=this._state;this._state=DG.Connected;let i=performance.now()-n;this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:r,operationName:`StartMedia`,durationInMs:i,operationPayload:{isPreheated:!!e,state:this._state},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId}),e&&this.logTelemetryWithEndpointId(r,i,t),t!==this._state&&(this._params.logger.info(`Session state changed from ${t} to ${this._state}`),this._eventEmitter.emit(`stateChanged`)),Z().waimeabay.enableVideoHandler&&await this.createVideoHandler()}catch(t){let i=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.START_MEDIA_FAILED,originalError:t});throw this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:r,operationName:`StartMedia`,durationInMs:performance.now()-n,operationPayload:{isPreheated:!!e,state:this._state,...K3(i).communicationServicesError},resultCategories:i.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId}),this._params.logger.error(`Failed to create audio/video handler: ${t instanceof Error?t.message:String(t)}`),i}}updateOutboundAudioStream(e){let t=this.localAudioStreams[0];if(t){let n=e.clone();t.setWBMediaStream(n)}if(this._outgoingMediaStream=e,this._outboundAudio)if(this._outboundAudio.clearMediaSource(),this._isMuted)this._params.logger.debug(`updateOutboundAudioStream: stream ${e.id} set while muted; track not attached until unmute.`);else{let t=e.getAudioTracks()[0];t&&this._outboundAudio.setMediaSource(t),this._params.logger.info(`Updated outbound audio stream with stream ID: ${e.id}`)}else this._params.logger.debug(`updateOutboundAudioStream: _outboundAudio not created yet, stream ${e.id} will be set when startMedia is called`)}logTelemetryWithEndpointId(e,t,n,r){this._endpointId===``&&this._params.logger.error(`Session metadata error the endpointId is empty, cannot log telemetry with endpointId yet.`);let i=n===DG.Connecting&&this._state===DG.Disconnected,a=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.JOIN_FAILED}),o={eventName:Q.acs_wb_session_events,operationId:e,operationName:`StateChanged`,durationInMs:t,operationPayload:{oldState:n,newState:this._state,disconnectedCause:r??``},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId};i&&(o.resultSignature=500,o.resultCategories=a.resultCategories,o.operationPayload={...o.operationPayload,...K3(a).communicationServicesError},this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:e,operationName:`JoinSession`,durationInMs:t,operationPayload:{feedId:Z().waimeabay.feedId,...K3(a).communicationServicesError,disconnectedCause:r?{...r}:``},resultCategories:a.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId})),this._params.telemetryLogManager.sendWbSessionEvent(o)}emitConfigureRequest(e){let t={feedId:Z().waimeabay.feedId,sessionId:this._params.sessionId,endpointId:this._endpointId,endpointSecret:e.secretToken,activationUrl:this.getServiceOrigin()+Z().waimeabay.activationPath},n=K0(),r=performance.now();this._eventEmitter.emit(`configureRequest`,t,((e,t)=>{if(e)this._params.logger.debug(`SessionImpl: configureRequest success`),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:n,operationName:`ConfigureRequest`,durationInMs:performance.now()-r,operationPayload:{},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId});else{let e=t||`Unknown error`;this._params.logger.error(`SessionImpl: configureRequest failed: ${e}`);let i=new Y({defaultError:J.CALL.OPERATION_FAILED,defaultErrorMessageArgs:[`ConfigureRequest`]});this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:n,operationName:`ConfigureRequest`,durationInMs:performance.now()-r,operationPayload:{configurationFailureReason:e,...K3(i).communicationServicesError},resultCategories:[`UnexpectedClientError`],resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId})}}))}getServiceOrigin(){return this._params.serviceOrigin&&this._params.serviceOrigin.trim()!==``?this._params.serviceOrigin:Z().waimeabay.origin}async startAudioEffects(e,t){let n=e.feature(Z5.AudioEffects),r=t8().engine;await n.startEffects({noiseSuppression:r===`Chromium`?t.noiseSuppression:r===`Safari`?void 0:`BrowserNoiseSuppression`,echoCancellation:r===`Chromium`?t.echoCancellation:`BrowserEchoCancellation`})}async subscribeToAudioEffectsStats(e){try{if(this._params.logger.debug(`MediaStreamSession: subscribeToAudioEffectsStats - effectsStarted event received, waiting briefly for internal stats subscription to be set up`),await new Promise((e=>setTimeout(e,100))),this._params.logger.debug(`MediaStreamSession: subscribeToAudioEffectsStats - Setting up audio effects stats subscription after delay`),!e||this._audioEffectsSubscribedStream===e&&this._audioEffectsStatsListener)return;if(this._audioEffectsStatsListener&&this._audioEffectsSubscribedStream&&this._audioEffectsSubscribedStream!==e)try{this._audioEffectsSubscribedStream.feature(Z5.AudioEffects)?.off(`effectsProcessorStatsUpdated`,this._audioEffectsStatsListener)}catch(e){this._params.logger.warn(`MediaStreamSession: subscribeToAudioEffectsStats - Error cleaning up existing audio effects stats subscription: ${e}`)}let t=e.feature(Z5.AudioEffects);if(!this._audioEffectsStatsListener||this._audioEffectsSubscribedStream!==e){this._audioEffectsStatsListener=e=>{e&&this._audioEffectsProcessorStats.push(e)},t?.on(`effectsProcessorStatsUpdated`,this._audioEffectsStatsListener);let n=t?.audioEffectsProcessorStats;n&&this._audioEffectsProcessorStats.push(n),this._audioEffectsSubscribedStream=e}}catch(e){this._params.logger.warn(`MediaStreamSession: subscribeToAudioEffectsStats - Error handling audio effects stats subscription: ${e}`)}}initializeTelemetryChannel(){if(this._telemetryChannelInitializationPromise)return this._telemetryChannelInitializationPromise;let e=Z().waimeabay.telemetry;return this._telemetryChannelInitializationPromise=(async()=>{try{if(this._telemetryChannel)return;this._telemetryChannel=new W5(this,{payloadType:e.payloadType,...e.mode===1?{isLargeData:!1,transmissionMode:G5.Realtime}:e.mode===2?{isLargeData:!1,transmissionMode:G5.PartiallyReliable}:{isLargeData:!0,transmissionMode:G5.Realtime}},this._params.logger,this._params.telemetryLogManager),await this._telemetryChannel.initialize(),this._params.logger.info(`initializeTelemetryChannel: DataChannelAdapter initialized.`),this._telemetryChannel.on(`message`,(e=>{try{let t=Lwe(e.data);this._params.logger.info(`MediaStreamSession: Telemetry data received from endpoint ${e.endpointId}: `,JSON.stringify(t))}catch(t){this._params.logger.error(`MediaStreamSession: Error decoding telemetry message from ${e.endpointId}: ${t instanceof Error?t.message:String(t)}`)}}))}catch(e){this._params.logger.error(`initializeTelemetryChannel: Failed to initialize: ${e instanceof Error?e.message:String(e)}`),this._telemetryChannel=void 0,this._telemetryChannelInitializationPromise=void 0}})(),this._telemetryChannelInitializationPromise}async sendTelemetrySignal(e,t){let n=t===void 0?Date.now():t;if(Z().waimeabay.sendTelemetrySignal)try{if(await this.initializeTelemetryChannel(),!this._telemetryChannel)return void this._params.logger.warn(`sendTelemetrySignal: Telemetry channel is not available after attempting initialization.`);if(this._telemetryChannel.state<D8.Initialized)return void this._params.logger.warn(`sendTelemetrySignal: Telemetry channel adapter state is ${this._telemetryChannel.state}, not ready to send signal ${e}.`);let t=Fwe(e,n),r=Iwe(t);this._telemetryChannel.send(r),this._params.logger.info(`sendTelemetrySignal: Successfully sent signal: ${e}, message: ${JSON.stringify(t)}`)}catch(t){this._params.logger.error(`sendTelemetrySignal: Failed to send telemetry signal ${e}: ${t instanceof Error?t.message:String(t)}`,t)}}toggleAudioMuteState(){if(this._isMuted=!this._isMuted,this._isMuted)this._outboundAudio&&this._outboundAudio.clearMediaSource();else try{this._outboundAudio&&this._outboundAudio.setMediaSource(this._outgoingMediaStream.getAudioTracks()[0])}catch(e){this._params.logger.error(`Failed to unmute audio: ${e instanceof Error?e.message:String(e)}`)}}validateSessionState(e){if(this._state!==DG.Connected&&(this._state!==DG.Connecting||e!=o4.Mute&&e!=o4.Unmute)){if(this._state===DG.Disconnected)throw new Y({defaultError:J.WB_MEDIA_SDK.SESSION.DISCONNECTED_JOIN_AGAIN,defaultErrorMessageArgs:[e]});if(this._state===DG.Connecting)throw new Y({defaultError:J.WB_MEDIA_SDK.SESSION.CONNECTING_WAIT,defaultErrorMessageArgs:[e]})}}async sendStreamsUpdatedTelemetry(e,t){this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:``,operationName:`StreamsUpdated`,durationInMs:0,operationPayload:{sourceId:e.sourceId,remoteEndpointId:e.endpointId,type:e.type,action:t},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId})}async sendStreamsUpdatedFailureTelemetry(e){this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:``,operationName:`StreamsUpdated`,durationInMs:0,operationPayload:{sourceId:e.sourceId,remoteEndpointId:e.endpointId,type:e.type,action:e.action,failureType:e.failureType,failureReason:e.failureReason},resultCategories:[`UnexpectedClientError`],resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId})}setFirstClientAudioTimestamp(e){this._sessionConnectedTimestamp===void 0&&(this._sessionConnectedTimestamp=e,this._params.logger.info(`SessionConnectedTimestamp set via setFirstClientAudioTimestamp: ${e}`))}};tze([WG(Dwe.Feature),J9(`design:type`,Function),J9(`design:paramtypes`,[Object]),J9(`design:returntype`,typeof(eze=typeof TFeature<`u`&&TFeature)==`function`?eze:Object)],ize.prototype,`feature`,null);var aze=class e{static create(){return new e}setTsStack(e){return this._tsStack=e,this}setDeviceManagerInternal(e){return this._deviceManagerInternal=e,this}setClientTypeInfo(e){return this._clientTypeInfo=e,this}setTsWbSession(e){return this._tsWbSession=e,this}setLogger(e){return this._logger=e,this}setTelemetryLogManager(e){return this._telemetryLogManager=e,this}setClientId(e){return this._clientId=e,this}setServiceOrigin(e){return this._serviceOrigin=e,this}setSessionId(e){return this._sessionId=e,this}setOptions(e){return this._options=e,this}setSessionAgent(e){return this._sessionAgent=e,this}get sessionAgent(){return this._sessionAgent}get tsStack(){return this._tsStack}get deviceManagerInternal(){return this._deviceManagerInternal}get clientTypeInfo(){return this._clientTypeInfo}get tsWbSession(){return this._tsWbSession}get logger(){return this._logger}get telemetryLogManager(){return this._telemetryLogManager}get clientId(){return this._clientId}get serviceOrigin(){return this._serviceOrigin}get sessionId(){return this._sessionId}get options(){return this._options}},oze=class{constructor(e,t,n,r,i,a,o,s){this._logger=e,this._telemetryLogManager=t,this._clientId=n,this._tokenCredential=r,this._callStack=i,this._deviceManagerInternal=a,this._clientTypeInfo=o,this._options=s,this._tokenFetchTries=0,this._sessionMap=new Map,this.tokenProvider=async e=>{if(!this._tokenCredential)throw new Y({defaultError:J.CALL_AGENT.GET_TOKEN_BEFORE_INIT});let t=await M4(this._tokenCredential,Z().calling.eudb.isRgnClaimEnabledForACS);return t.acsResourceId===this._parsedTokenCredential?.acsResourceId&&t.identityMri===this._parsedTokenCredential?.identityMri||k4(J.CALL_AGENT.REFRESHED_TOKEN_INVALID_USERID,this._logger),e?this._tokenFetchTries+=1:this._tokenFetchTries=0,this._tokenFetchTries>this._maxNumberOfRetries&&k4(J.CALL_AGENT.REFRESHED_TOKEN_RETRIES,this._logger),t.jwtToken},this._logger.debug(`MediaSessionAgentImpl: constructor called token: ${!!this._tokenCredential} options: ${JSON.stringify(this._options)}`),this._parsedTokenCredential=eTe(),this._maxNumberOfRetries=Z().calling.maxNumberOfTokenFetchRetries||zCe;let c=new TLe(this._telemetryLogManager);this._telemetryLogger=c.getGenericTelemetryLogger(`waimeabay`),s?.sessionAgentConfig?.allowDisconnectOnBeforeUnload&&(window.addEventListener(`beforeunload`,(()=>{this._disconnectAllSessions(`unload`)})),this._logger.debug(`MediaSessionAgent: Page unload listener registered (beforeunload)`))}_getSessionParams(e,t,n,r){let i=n?.sessionId??K0(),a=aze.create().setTsStack(this._tsWbStack).setDeviceManagerInternal(this._deviceManagerInternal).setClientTypeInfo(this._clientTypeInfo).setTsWbSession(t);return a.setClientId(this._clientId).setSessionAgent(this).setLogger(this._logger).setTelemetryLogManager(this._telemetryLogManager).setSessionId(i),e||a.setOptions(r),this._options?.serviceOrigin&&a.setServiceOrigin(this._options.serviceOrigin),a}_getOrCreateMediaSession(e,t,n){if(!this._tsWbStack)throw Error(`MediaSessionAgent is not initialized`);let r=this._getSessionKey(t),i=this._sessionMap.get(r);if(i)return this._logger.debug(`MediaSessionAgentImpl: Returning existing session for key: ${r}, total sessions: ${this._sessionMap.size}`),e||i.session.state!==DG.Preheated&&i.session.state!==DG.Connecting||i.session.startMedia(!0,n),i.session;let a=this._tsWbStack.getWBSessionObject(r,{media:this._telemetryLogger});if(!a)throw new Y({defaultError:J.WB_MEDIA_SDK.AGENT.TS_STACK_FAILD_TO_GET_WB_SESSION});let o=new ize(this._getSessionParams(!1,a,t,n)),s=performance.now(),c=K0();return o.initialize(e).then((()=>{this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:c,operationName:`MediaSessionInit`,durationInMs:performance.now()-s,operationPayload:{},resultCategories:[`Success`],resultSignature:200})})).catch((e=>{this._logger.error(`Session initialization failed: ${e}`);let t=new Y({defaultError:J.WB_MEDIA_SDK.CLIENT.INIT,originalError:e});this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:c,operationName:`MediaSessionInit`,durationInMs:performance.now()-s,operationPayload:{...K3(t).communicationServicesError},resultCategories:t.resultCategories,resultSignature:500})})),this._sessionMap.set(r,{session:o,tsWbSession:a}),this._logger.debug(`MediaSessionAgentImpl: Created and stored new session for key: ${r}, total sessions: ${this._sessionMap.size}`),o}joinSession(e,t){return this._getOrCreateMediaSession(!1,e,t)}preheatSession(e){return this._getOrCreateMediaSession(!0,e)}async initialize(){let e=performance.now(),t=K0();try{this._parsedTokenCredential=await M4(this._tokenCredential,Z().calling.eudb.isRgnClaimEnabledForACS);let n={clientId:this._clientId,acsResourceId:this._parsedTokenCredential.acsResourceId,identityMri:this._parsedTokenCredential.identityMri,cloudType:this._parsedTokenCredential.cloudType,identityType:this._parsedTokenCredential.isEnterpriseUser?$0.Enterprise:$0.Consumer,region:this._parsedTokenCredential.region,IsUserEmergencyCountryCode:!1,mriType:this._parsedTokenCredential.mriType};this._tsWbStack=await this._callStack.initializeMediaSdkStackForUser(this.tokenProvider,n),this._telemetryLogManager.initialize(n),this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`MediaSessionAgentInit`,durationInMs:performance.now()-e,operationPayload:{serviceOrigin:this._options?.serviceOrigin??``},resultCategories:[`Success`],resultSignature:200})}catch(n){let r=new Y({defaultError:J.WB_MEDIA_SDK.CLIENT.INIT,originalError:n});throw this._logger.error(`MediaClient: Error initializing CallStack: ${r}`),this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`MediaSessionAgentInit`,durationInMs:performance.now()-e,operationPayload:{...K3(r).communicationServicesError},resultCategories:r.resultCategories,resultSignature:500}),r}}_getSessionKey(e){return e&&e.sessionId?e.sessionId:`default`}getSession(e){let t=this._getSessionKey(e);return this._sessionMap.get(t)?.session}removeSession(e){let t=this._getSessionKey(e),n=this._sessionMap.get(t),r=!!n;return n&&(this._clearTsWbSession(n.tsWbSession,t),r=this._sessionMap.delete(t),this._logger.debug(`MediaSessionAgentImpl: Removed session for key: ${t}, remaining sessions: ${this._sessionMap.size}`)),r}get sessions(){return Array.from(this._sessionMap.values()).map((e=>e.session))}_clearAllSessions(){this._sessionMap.clear(),this._logger.debug(`MediaSessionAgentImpl: Cleared all sessions from map`)}_clearTsWbSession(e,t){if(e)try{e.dispose(),this._tsWbStack.mediaAgent.disposeSession(t),this._logger.debug(`MediaSessionAgentImpl: Disposed tsWbSession after last session removed`)}catch(e){this._logger.error(`MediaSessionAgentImpl: Error disposing tsWbSession: ${e}`)}}_disconnectAllSessions(e){if(this._sessionMap.size===0)return;let t=Array.from(this._sessionMap.values());for(let n of t)try{n.session.disconnectFromUnload(e)}catch(e){this._logger.error(`MediaSessionAgent: Error disconnecting session: ${e}`)}}dispose(){this._logger.debug(`MediaSessionAgentImpl: Disposing agent and all sessions`),this._disconnectAllSessions(`dispose`),this._tsWbStack.dispose(),this._telemetryLogManager.clearTelemetryLoggers(),this._clearAllSessions(),q9.instance.dispose()}},sze=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},cze=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},lze=1,uze=class{get initializedDeviceManager(){return this._initializedDeviceManager}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}constructor(e){this._initializedDeviceManager=!1,qSe(c2.MediaStreaming);let t=performance.now();this._clientId=K0();let n=lze++,r=e?.logger||KW(`ACS-calling`);this.logger=new z6(r,[()=>`MediaClient${n}[${this._clientId}]`]),this._mediaSdkDiagnosticInformation=tTe(Y2(),this.logger,e),this._clientTypeInfo={name:lue,version:Y2(),details:this._mediaSdkDiagnosticInformation},this._eventEmitter=new S6(this.logger),this._telemetryLogManager=new f3(this.logger,this._mediaSdkDiagnosticInformation);try{this._callStack=new A9(this.logger,this._clientId,this._telemetryLogManager,this._mediaSdkDiagnosticInformation,new WRe,new GRe,void 0,void 0,!1),this._deviceManager=new N9(this.logger,this._callStack,this._telemetryLogManager,!0,e?.enumerateDevices??!1),this._extensibleApi=new N3(this.logger,{mediaClient:this},{mediaClient:this,telemetryLogManager:this._telemetryLogManager,callStack:this._callStack}),this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:this._clientId,operationName:`MediaClientInit`,durationInMs:performance.now()-t,operationPayload:{},resultCategories:[`Success`],resultSignature:200})}catch(e){let n=new Y({defaultError:J.WB_MEDIA_SDK.CLIENT.INIT,originalError:e});throw this.logger.error(`MediaClient: Error initializing CallStack: ${n}`),this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:this._clientId,operationName:`MediaClientInit`,durationInMs:performance.now()-t,operationPayload:{...K3(n).communicationServicesError},resultCategories:n.resultCategories,resultSignature:500}),n}}feature(e){return this._extensibleApi.getApiObjectInstance(e.mediaClientApiCtor)}async createSessionAgent(e,t){let n=new oze(this.logger,this._telemetryLogManager,this._clientId,e,this._callStack,this._deviceManager,this._clientTypeInfo,t);return await n.initialize(),n}async getDeviceManager(){return await this._deviceManager.getDeviceManager(),this._initializedDeviceManager=!0,this._eventEmitter.emit(`initializedDeviceManager`),this._deviceManager}getSdkVersion(){return Y2()}async checkDevicePermissions(e){let t=new Map,n=performance.now();e.forEach((e=>{t.set(e,EG.Prompt)}));try{if(!navigator.permissions||typeof navigator.permissions.query!=`function`){let e={};return t.forEach(((t,n)=>{e[n]=t})),this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:this._clientId,operationName:`DevicePermissionAccess`,durationInMs:performance.now()-n,operationPayload:e,resultCategories:[`Success`],resultSignature:200}),t}for(let n of e)try{let e=await navigator.permissions.query({name:n});t.set(n,e.state)}catch(e){this.logger.warn(`Failed to query ${n} permission: ${e}`),t.set(n,EG.Prompt)}let r={};return t.forEach(((e,t)=>{r[t]=e})),this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:this._clientId,operationName:`DevicePermissionAccess`,durationInMs:performance.now()-n,operationPayload:r,resultCategories:[`Success`],resultSignature:200}),t}catch(e){let r=new Y({defaultError:J.WB_MEDIA_SDK.CLIENT.INIT,originalError:e});return this.logger.error(`MediaClient::checkDevicePermissions, error checking device permissions ${r}`),this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:this._clientId,operationName:`DevicePermissionAccess`,durationInMs:performance.now()-n,operationPayload:{...K3(r).communicationServicesError},resultCategories:r.resultCategories,resultSignature:500}),t}}};sze([zG,cze(`design:type`,Object)],uze.prototype,`logger`,void 0);var dze=`hangedUp`,Y9=`declined`,X9=`connected`,Z9=`loading`,Q9=`devicePermissionDenied`,fze=2e3,pze={name:`BDVideoCallTemplate`,components:{BDConversationCard:BH,BDLoader:yae,BDButton:ha,BDCol:d,BDContainer:f,BDRow:p,IconEndCall:At,IconShareScreen:di},props:{messageWhenLoading:String,participant:{type:Object,default:null},isCallee:{type:Boolean,default:!1},videoTestUrl:{type:String,default:null}},data(){return{azureLogs:[],l:this.$localization.template.videoCall,isScreenShared:!1,screenshareAvailable:!1,signalStrength:2,devicePermissions:{},videoCallState:Z9,userFacingDiagnostics:null,acsConfig:{client:null,agent:null,deviceManager:null,incomingCall:null,call:null},localVideoStream:null,screenShareView:null,availableCamerasCount:0,cameraIndex:0,isBrowserFirefox:navigator.userAgent.indexOf(`Firefox`)>-1}},computed:{AvailableCamerasCountMessage(){switch(this.availableCamerasCount){case 0:return this.l.hasNoAvailableCamera;case 1:return this.l.hasOneAvailableCamera;default:return this.l.hasMultipleAvailableCameras}},IsLocalVideoStreamSwitchAvailable(){let e=navigator.userAgent;return/Mobi/.test(e)&&!this.isScreenShared},DeviceSupportsScreenShare(){let e=navigator.userAgent,t=e.indexOf(`Android`)!==-1,n=/Mobi/.test(e),r=/iPad|iPhone|iPod/.test(e)&&!window.MSStream;return!(t&&n||r)},IsVideoDisabled(){return!this.devicePermissions?.video&&this.DevicePermissionsDenied},IsAudioDisabled(){return!this.devicePermissions?.audio&&this.DevicePermissionsDenied},CallStateClass(){return this.videoCallState===Y9?`incoming--declined`:`incoming--loading`},PermissionMissingToStartCall(){return this.browserPermissionDeniedForAudio||this.browserPermissionDeniedForVideo},signalStrengthClass(){switch(this.signalStrength){case 0:return`weak`;case 1:return`steady`;case 2:return`strong`;default:return null}},signalStrengthLabel(){switch(this.signalStrength){case 0:return this.l.signalStrength.weak;case 1:return this.l.signalStrength.steady;case 2:return this.l.signalStrength.strong;default:return null}},ShareScreenLabel(){return this.isScreenShared?this.l.stopSharingScreen:this.l.shareScreen},settingsHelpTitleLabel(){return this.l.placeholderSettingsHelpTitle},settingsHelpMessageLabel(){return this.l.placeholderSettingsHelpMessage},IsLoading(){return this.videoCallState===Z9},IsDeclined(){return this.videoCallState===Y9},IsHangedUp(){return this.videoCallState===dze},IsConnected(){return this.videoCallState===X9},ShowLoader(){return this.videoCallState!==X9},DevicePermissionsDenied(){return this.videoCallState===Q9},LoaderMessage(){return this.IsHangedUp?this.l.messageWhenVideoCallHangedUp:this.IsDeclined?this.l.messageWhenVideoCallDeclined:this.DevicePermissionsDenied?this.l.messageWhenDevicePermissionDenied:this.messageWhenLoading},VideoStreamClassToSelect(){return this.screenshareAvailable?`.incoming__screenshare`:`.incoming__video`}},created(){this.InitAzureLogger()},unmounted(){this.EndVideoCall()},methods:{CallDeclined(){this.videoCallState=Y9},CallAnswered(){},CallStartVideoCall(){this.videoCallState!==Q9&&this.StartCall()},async CallHangUp(){this.videoCallState=dze,this.devicePermissions.video&&this.DisplayAvailableLocalVideoStream()},async InitializeAcsConnection(e){this.acsConfig.client=(0,u.markRaw)(new U9);let t=await new Xle(e);this.acsConfig.agent=(0,u.markRaw)(await this.acsConfig.client.createCallAgent(t)),this.acsConfig.deviceManager=await this.acsConfig.client.getDeviceManager(),this.devicePermissions=await this.acsConfig.deviceManager.askDevicePermission({video:!0,audio:!0}),window.setInterval(this.DisplayAvailableLocalVideoStream,5e3),(!this.devicePermissions.audio||!this.devicePermissions.video)&&(this.videoCallState=Q9),this.isCallee&&(this.acsConfig.agent.on(`incomingCall`,this.SetIncomingCall),this.$emit(`ready`))},async SetIncomingCall(e){try{this.acsConfig.incomingCall=e.incomingCall,this.AcceptCall()}catch{console.log(`error occured during starting call`)}},async CreateNewVideoOptions(){let e=await this.CreateLocalVideoStream();return e?{localVideoStreams:[e]}:void 0},async StartCall(){try{let e=await this.CreateNewVideoOptions(),t={communicationUserId:this.participant.videoCallIdentityId};this.acsConfig.call=this.acsConfig.agent.startCall([t],{videoOptions:e}),this.SubscribeToDiagnostics(),this.SubscribeToCall()}catch(e){console.error(e)}},async AcceptCall(){let e=await this.CreateNewVideoOptions();this.acsConfig.call=await this.acsConfig.incomingCall.accept({videoOptions:e}),this.SubscribeToDiagnostics(),this.SubscribeToCall()},async CreateLocalVideoStream(){let e=(await this.acsConfig.deviceManager.getCameras())[0];if(e)return new J6(e);console.error(`No camera device found on the system`)},SubscribeToCall(){this.acsConfig.call.on(`stateChanged`,this.CallStateIsChanged),this.acsConfig.call.on(`localVideoStreamsUpdated`,e=>{e.added.forEach(this.DisplayLocalScreenShareStream),e.removed.forEach(this.RemoveLocalScreenShareStream)}),this.acsConfig.call.remoteParticipants.forEach(this.SubscribeToRemoteParticipant),this.acsConfig.call.on(`remoteParticipantsUpdated`,e=>{e.added.forEach(this.SubscribeToRemoteParticipant)}),this.acsConfig.call.on(`isScreenSharingOnChanged`,()=>{this.isScreenShared=this.acsConfig.call.isScreenSharingOn})},SubscribeToDiagnostics(){this.userFacingDiagnostics=this.acsConfig.call.feature(Z5.UserFacingDiagnostics),this.userFacingDiagnostics.media.on(`diagnosticChanged`,this.DiagnosticChangedListener),this.userFacingDiagnostics.network.on(`diagnosticChanged`,this.DiagnosticChangedListener)},DiagnosticChangedListener(e){(e.diagnostic===`networkReceiveQuality`||e.diagnostic===`networkSendQuality`)&&(e.value===e6.Bad?(console.error(`${e.diagnostic} is bad quality`),this.signalStrength=0):e.value===e6.Poor?(console.error(`${e.diagnostic} is poor quality`),this.signalStrength=1):this.signalStrength=2)},CallStateIsChanged(){switch(this.acsConfig.call.state){case`EarlyMedia`:this.videoCallState=Z9;break;case`Ringing`:this.videoCallState=Z9;break;case`Connected`:this.videoCallState=X9;break;case`Disconnected`:this.CallHangUp();break}},async RemoveLocalScreenShareStream(e){if(!e||!e.mediaStreamType==`ScreenSharing`||!this.screenShareView)return;this.screenShareView.dispose();let t=document.querySelector(`.outgoing__screenshare`);t.style.display=`none`;let n=document.querySelector(`.outgoing__video`);n.style.display=`flex`},async DisplayLocalScreenShareStream(e){if(!e||!e.mediaStreamType==`ScreenSharing`)return;let t=new O7(e);this.screenShareView=await t.createView();let n=document.querySelector(`.outgoing__screenshare`);n.replaceChildren(this.screenShareView.target),n.style.display=`flex`;let r=document.querySelector(`.outgoing__video`);r.style.display=`none`;let i=n.querySelector(`video`);i.style.objectFit=`contain`},async DisplayLocalVideoStream(e){if(e&&e.source&&this.localVideoStream&&this.localVideoStream.source&&this.localVideoStream.source.id==e.source.id)return!0;try{this.localVideoStreamRenderer=new O7(e);let t=await this.localVideoStreamRenderer.createView(),n=document.querySelector(`.outgoing__video`);n.querySelector(`video`)&&(n.innerHTML=``),n.hidden=!1,n.replaceChildren(t.target)}catch{return!1}return this.localVideoStream=e,!0},async SubscribeToRemoteParticipant(e){e.videoStreams.forEach(this.DisplayRemoteVideoStream),e.on(`videoStreamsUpdated`,e=>{e.added.forEach(this.DisplayRemoteVideoStream)})},async DisplayRemoteVideoStream(e){if(e.mediaStreamType===`Video`&&(await this.RenderVideo(e),e.on(`isAvailableChanged`,async()=>await this.RenderVideo(e))),e.mediaStreamType===`ScreenSharing`&&e.on(`isAvailableChanged`,this.ScreenSharingAvailabilityChanged),e.mediaStreamType===`ScreenSharing`&&e.isAvailable){this.remoteStreamRenderer=new O7(e);let t=await this.remoteStreamRenderer.createView(),n=document.querySelector(`.incoming__screenshare`);this.HideCameraStream(!0),this.screenshareAvailable=!0,this.EnableMiniPlayerOnVideoElement(`.incoming__screenshare`),n.replaceChildren(t.target)}},async RenderVideo(e){if(!e.isAvailable)return;this.remoteStreamRenderer=new O7(e);let t=await this.remoteStreamRenderer.createView(),n=document.querySelector(`.incoming__video`);n.hidden=!1,n.replaceChildren(t.target),this.EnableMiniPlayerOnVideoElement(`.incoming__video`),this.HideCameraStream(!1)},HideCameraStream(e){let t=document.querySelector(`.incoming__video`),n=document.querySelector(`.incoming__screenshare`);t.style.display=e?`none`:`block`,n.style.display=e?`flex`:`none`},ScreenSharingAvailabilityChanged(){this.screenshareAvailable=!1,this.HideCameraStream(!1)},async SwitchLocalVideoStream(){this.DisplayAvailableLocalVideoStream(!0)},async DisplayAvailableLocalVideoStream(e=!1){let t=(await this.acsConfig.deviceManager.getCameras()).filter(e=>e.name!=`OBS Virtual Camera`);this.availableCamerasCount=t.length;for(let n=0;n<this.availableCamerasCount;n++){(e||n!=0)&&(this.cameraIndex=(this.cameraIndex+1)%this.availableCamerasCount);let r=t[this.cameraIndex],i=new J6(r);if(await this.DisplayLocalVideoStream(i))break}},EnableMiniPlayerOnVideoElement(e){let t=document.querySelector(e);if(!t)return;let n=t.querySelector(`video`);n&&(n.style.objectFit=`contain`,n.disablePictureInPicture=!1)},async EndVideoCall(){this.acsConfig.call&&this.acsConfig.call.state!==`Disconnected`&&(await this.acsConfig.call.hangUp({forEveryone:!0}),await this.acsConfig.agent.dispose()),this.$emit(`end-video-call`),window.close()},CloseWindow(){window.close()},InitAzureLogger(){Tae(`verbose`),GW.log=(...e)=>{let t=[...e];this.azureLogs=this.azureLogs.splice(1-fze).concat(t)}},ChangeToFullscreen(){document.querySelector(this.VideoStreamClassToSelect).querySelector(`video`).requestFullscreen()},ChangeToMiniPlayer(){let e=document.querySelector(this.VideoStreamClassToSelect).querySelector(`video`);document.pictureInPictureElement?e.exitPictureInPicture():document.pictureInPictureEnabled&&e.requestPictureInPicture()},async OnShareScreen(){this.acsConfig.call&&this.acsConfig.call.isScreenSharingOn?await this.acsConfig.call.stopScreenSharing():await this.acsConfig.call.startScreenSharing()}}},mze={class:`video-call-template`},hze={key:0,class:`card`},gze={key:0,class:`permissions-denied__audio`},_ze={class:`permissions-denied__audio-disabled`},vze={key:1,class:`permissions-denied__video`},yze={class:`permissions-denied__video-disabled`},bze={key:1,class:`card`},xze={class:`incoming__settings`},Sze={class:`side`},Cze={class:`outgoing`},wze={class:`card`},Tze={key:0,class:`outgoing__video`},Eze={class:`outgoing__available-cameras-count text-center`},Dze={key:3,class:`permissions-denied__video`},Oze={class:`permissions-denied__video-disabled`},kze={class:`settings`},Aze={class:`settings__help`},jze=[`href`],Mze={href:`https://www.beterdichtbij.nl/service-contact/`,target:`blank`,rel:`noopener noreferrer`};function Nze(e,t,n,r,i,a){let o=(0,u.resolveComponent)(`BDConversationCard`),s=(0,u.resolveComponent)(`BDCol`),c=(0,u.resolveComponent)(`BDRow`),l=(0,u.resolveComponent)(`BDLoader`),d=(0,u.resolveComponent)(`IconMicrophoneSlash`),f=(0,u.resolveComponent)(`IconVideoDisabled`),p=(0,u.resolveComponent)(`BDButton`),m=(0,u.resolveComponent)(`IconShareScreen`),h=(0,u.resolveComponent)(`IconEndCall`),g=(0,u.resolveComponent)(`BDContainer`);return(0,u.openBlock)(),(0,u.createElementBlock)(`div`,mze,[(0,u.createVNode)(g,null,{default:(0,u.withCtx)(()=>[(0,u.createVNode)(c,null,{default:(0,u.withCtx)(()=>[(0,u.createVNode)(s,null,{default:(0,u.withCtx)(()=>[(0,u.createVNode)(o,{smallState:!0,contactInfo:n.participant.contact},null,8,[`contactInfo`])]),_:1})]),_:1}),(0,u.createVNode)(c,null,{default:(0,u.withCtx)(()=>[(0,u.createVNode)(s,{sm:`12`,lg:a.IsDeclined?`12`:`8`},{default:(0,u.withCtx)(()=>[(0,u.createElementVNode)(`div`,{class:(0,u.normalizeClass)([`incoming`,a.CallStateClass])},[a.ShowLoader?((0,u.openBlock)(),(0,u.createElementBlock)(`div`,hze,[(0,u.createVNode)(l,{size:`lg`,message:a.LoaderMessage,stopAnimation:a.IsDeclined||a.IsHangedUp||a.DevicePermissionsDenied},null,8,[`message`,`stopAnimation`]),a.IsAudioDisabled?((0,u.openBlock)(),(0,u.createElementBlock)(`div`,gze,[(0,u.createElementVNode)(`div`,_ze,[(0,u.createVNode)(d,{class:`icon-xl icon-state-error`})]),(0,u.createElementVNode)(`span`,null,(0,u.toDisplayString)(i.l.permissionDeniedForAudio),1)])):(0,u.createCommentVNode)(``,!0),a.IsVideoDisabled?((0,u.openBlock)(),(0,u.createElementBlock)(`div`,vze,[(0,u.createElementVNode)(`div`,yze,[(0,u.createVNode)(f,{class:`icon-xl icon-state-error`})]),(0,u.createElementVNode)(`span`,null,(0,u.toDisplayString)(i.l.permissionDeniedForVideo),1)])):(0,u.createCommentVNode)(``,!0),a.IsDeclined||a.IsHangedUp||a.DevicePermissionsDenied?((0,u.openBlock)(),(0,u.createBlock)(p,{key:2,variant:`primary`,class:`text-center`,onClick:a.CloseWindow},{default:(0,u.withCtx)(()=>[(0,u.createTextVNode)((0,u.toDisplayString)(i.l.closeWindow),1)]),_:1},8,[`onClick`])):(0,u.createCommentVNode)(``,!0)])):((0,u.openBlock)(),(0,u.createElementBlock)(`div`,bze,[t[0]||=(0,u.createElementVNode)(`div`,{class:`incoming__video`},null,-1),t[1]||=(0,u.createElementVNode)(`div`,{class:`incoming__screenshare`},null,-1),(0,u.createElementVNode)(`div`,xze,[(0,u.createVNode)(p,{variant:`primary`,class:`text-center`,onClick:a.ChangeToFullscreen},{default:(0,u.withCtx)(()=>[(0,u.createVNode)(m),(0,u.createElementVNode)(`span`,null,(0,u.toDisplayString)(i.l.fullScreen),1)]),_:1},8,[`onClick`]),!i.isBrowserFirefox&&!e.screenAlreadyShared?((0,u.openBlock)(),(0,u.createBlock)(p,{key:0,variant:`primary`,class:`text-center`,onClick:a.ChangeToMiniPlayer},{default:(0,u.withCtx)(()=>[(0,u.createVNode)(m),(0,u.createElementVNode)(`span`,null,(0,u.toDisplayString)(i.l.miniPlayer),1)]),_:1},8,[`onClick`])):(0,u.createCommentVNode)(``,!0)])]))],2)]),_:1},8,[`lg`]),a.IsDeclined?(0,u.createCommentVNode)(``,!0):((0,u.openBlock)(),(0,u.createBlock)(s,{key:0,sm:`12`,lg:`4`},{default:(0,u.withCtx)(()=>[(0,u.createElementVNode)(`div`,Sze,[(0,u.createElementVNode)(`div`,null,[(0,u.createElementVNode)(`div`,Cze,[(0,u.createElementVNode)(`div`,wze,[a.DevicePermissionsDenied?(0,u.createCommentVNode)(``,!0):((0,u.openBlock)(),(0,u.createElementBlock)(`div`,Tze)),t[2]||=(0,u.createElementVNode)(`div`,{class:`outgoing__screenshare`},null,-1),a.DeviceSupportsScreenShare&&!a.DevicePermissionsDenied&&!e.screenAlreadyShared&&!a.ShowLoader?((0,u.openBlock)(),(0,u.createBlock)(p,{key:1,variant:i.isScreenShared?`danger`:`primary`,class:`text-center`,onClick:a.OnShareScreen},{default:(0,u.withCtx)(()=>[(0,u.createVNode)(m),(0,u.createElementVNode)(`span`,null,(0,u.toDisplayString)(a.ShareScreenLabel),1)]),_:1},8,[`variant`,`onClick`])):(0,u.createCommentVNode)(``,!0),a.IsLocalVideoStreamSwitchAvailable?((0,u.openBlock)(),(0,u.createElementBlock)(u.Fragment,{key:2},[(0,u.createVNode)(p,{class:`text-center`,onClick:a.SwitchLocalVideoStream},{default:(0,u.withCtx)(()=>[(0,u.createTextVNode)((0,u.toDisplayString)(i.l.switchCamera),1)]),_:1},8,[`onClick`]),(0,u.createElementVNode)(`p`,Eze,(0,u.toDisplayString)(a.AvailableCamerasCountMessage),1)],64)):(0,u.createCommentVNode)(``,!0),a.IsVideoDisabled?((0,u.openBlock)(),(0,u.createElementBlock)(`div`,Dze,[(0,u.createElementVNode)(`div`,Oze,[(0,u.createVNode)(f,{class:`icon-xxl icon-state-error`})]),(0,u.createElementVNode)(`span`,null,(0,u.toDisplayString)(i.l.permissionDeniedForVideo),1)])):(0,u.createCommentVNode)(``,!0)])]),(0,u.createElementVNode)(`div`,kze,[(0,u.createElementVNode)(`div`,{class:(0,u.normalizeClass)([`settings__signal`,a.signalStrengthClass])},[t[3]||=(0,u.createElementVNode)(`ul`,{class:`indicator`},[(0,u.createElementVNode)(`li`),(0,u.createElementVNode)(`li`),(0,u.createElementVNode)(`li`)],-1),(0,u.createElementVNode)(`p`,null,(0,u.toDisplayString)(a.signalStrengthLabel),1)],2),(0,u.createElementVNode)(`div`,Aze,[(0,u.createElementVNode)(`p`,null,[(0,u.createElementVNode)(`b`,null,(0,u.toDisplayString)(a.settingsHelpTitleLabel),1)]),(0,u.createElementVNode)(`p`,null,(0,u.toDisplayString)(a.settingsHelpMessageLabel),1),(0,u.createElementVNode)(`p`,null,[(0,u.createElementVNode)(`a`,{href:n.videoTestUrl,target:`blank`,rel:`noopener noreferrer`},(0,u.toDisplayString)(i.l.testCall),9,jze),t[4]||=(0,u.createTextVNode)(` • `,-1),(0,u.createElementVNode)(`a`,Mze,(0,u.toDisplayString)(i.l.serviceDesk),1)])])])]),!a.IsHangedUp&&!a.DevicePermissionsDenied?((0,u.openBlock)(),(0,u.createBlock)(p,{key:0,variant:`danger`,class:`text-center w-100`,onClick:a.EndVideoCall},{default:(0,u.withCtx)(()=>[(0,u.createVNode)(h),(0,u.createElementVNode)(`span`,null,(0,u.toDisplayString)(i.l.endCall),1)]),_:1},8,[`onClick`])):(0,u.createCommentVNode)(``,!0)])]),_:1}))]),_:1})]),_:1})])}var Pze=m(pze,[[`render`,Nze]]),Fze={class:`template not-found-template`},Ize={class:`center-screen`},Lze={class:`container-warning`},Rze=[`textContent`],zze=[`textContent`],$9=(0,u.defineComponent)({__name:`BDNotFoundTemplate`,props:{buttonText:{type:String}},emits:[`navigate`],setup(e,{emit:t}){let{t:n}=Lu(),r=e,i=t,a=(0,u.computed)(()=>r.buttonText||n(`notFoundTemplate.buttonDefault`)),o=(0,u.computed)(()=>n(`notFoundTemplate.title`)),s=(0,u.computed)(()=>n(`notFoundTemplate.description`)),c=()=>i(`navigate`);return(e,t)=>((0,u.openBlock)(),(0,u.createElementBlock)(`main`,Fze,[(0,u.createVNode)(f,{class:`container-xl`},{default:(0,u.withCtx)(()=>[(0,u.createElementVNode)(`div`,Ize,[(0,u.createElementVNode)(`div`,Lze,[(0,u.createVNode)(Ri),(0,u.createElementVNode)(`h5`,{textContent:(0,u.toDisplayString)(o.value)},null,8,Rze),(0,u.createElementVNode)(`p`,{textContent:(0,u.toDisplayString)(s.value)},null,8,zze),(0,u.createVNode)(ha,{onClick:c,variant:`primary`,type:`button`,textContent:(0,u.toDisplayString)(a.value)},null,8,[`textContent`])])])]),_:1})]))}}),Bze=e=>{let t=/<a\b[^>]*>.*?<\/a>/gi,n=[],r;for(;(r=t.exec(e))!==null;)n.push({start:r.index,end:r.index+r[0].length});return e.replace(/(https?:\/\/[^\s<>"',]+|www\.[^\s<>"',]+)/g,(e,t,r)=>n.some(e=>r>=e.start&&r<e.end)?e:`<a href="${e.startsWith(`www.`)?`http://${e}`:e}" target="_blank" rel="noopener noreferrer">${e}</a>`)},Vze=(e,t)=>`<p><a href="${e}" title="${t}" target="_blank" rel="noopener noreferrer">${t}</a></p>`,Hze=e=>e.startsWith(`http://`)||e.startsWith(`https://`),Uze={install:e=>{e.component(`BDAlert`,oa),e.component(`BDArticle`,la),e.component(`BDAssignConversationModal`,FU),e.component(`BDAttachmentPreviewList`,T_),e.component(`BDAttachmentUploadModal`,IU),e.component(`BDBadge`,fa),e.component(`BDButton`,ha),e.component(`BDCard`,wa),e.component(`BDChangePasswordTemplate`,TW),e.component(`BDChatCloud`,Y_),e.component(`BDCol`,d),e.component(`BDCollapsableCard`,Oa),e.component(`BDConfirmationModal`,LU),e.component(`BDContainer`,f),e.component(`BDContentLibraryModal`,Tie),e.component(`BDContentLibrarySplitButton`,Eh),e.component(`BDContentLibraryTemplate`,gW),e.component(`BDConversationToTextModal`,yW),e.component(`BDDate`,Gh),e.component(`BDDropdown`,rU),e.component(`BDDropdownItem`,X_),e.component(`BDFileUpload`,tO),e.component(`BDForm`,Kh),e.component(`BDFormCheckbox`,ug),e.component(`BDFormInput`,Mg),e.component(`BDFormInvalidFeedback`,fg),e.component(`BDFormMultipleCheckbox`,aO),e.component(`BDFormSelect`,Lg),e.component(`BDHeader`,cU),e.component(`BDImageAttachmentModal`,xW),e.component(`BDImageAttachmentPreviewList`,P_),e.component(`BDInputGroup`,Bg),e.component(`BDLink`,ma),e.component(`BDLogo`,Ug),e.component(`BDMarkdownEditor`,jH),e.component(`BDMessageTemplateFormModal`,SW),e.component(`BDMobileMenu`,FH),e.component(`BDModal`,gU),e.component(`BDNotFoundTemplate`,$9),e.component(`BDPagination`,Xg),e.component(`BDPhoneNumberEditModal`,xU),e.component(`BDPill`,i_),e.component(`BDPractitionerHeader`,MU),e.component(`BDProfileImage`,s_),e.component(`BDRow`,p),e.component(`BDSessionTimeOutModal`,PU),e.component(`BDSmallConversationCard`,BH),e.component(`BDTable`,GH),e.component(`BDToast`,f_),e.component(`BDUser`,KH),e.component(`BDUserInformation`,__),e.component(`BDVideoCallConfirmationModal`,CW),e.component(`BDVideoCallTemplate`,Pze),e.component(`BDVideoCallToast`,nU),e.component(`BDZoomslider`,b_),e.component(`IconAcademy`,v),e.component(`IconArrowDown`,S),e.component(`IconArrowUp`,E),e.component(`IconAttachment`,k),e.component(`IconBold`,ne),e.component(`IconBulletList`,M),e.component(`IconCalendar`,le),e.component(`IconCall`,N),e.component(`IconCallReject`,ge),e.component(`IconCardView`,F),e.component(`IconCaretDown`,L),e.component(`IconCaretLeft`,Se),e.component(`IconCaretRight`,Ee),e.component(`IconCheck`,Ae),e.component(`IconClipboard`,Me),e.component(`IconClose`,Ie),e.component(`IconComment`,Be),e.component(`IconCommentActive`,We),e.component(`IconCommentStatic`,Je),e.component(`IconCommonFileEmpty`,Qe),e.component(`IconCommonFileWarning`,nt),e.component(`IconContactPerson`,ot),e.component(`IconCopy`,ut),e.component(`IconDelete`,mt),e.component(`IconDoubleCheck`,vt),e.component(`IconDownloadImage`,St),e.component(`IconEdit`,Et),e.component(`IconEndCall`,At),e.component(`IconError`,Pt),e.component(`IconExternal`,Rt),e.component(`IconEyeShow`,Ht),e.component(`IconEyeSlash`,Kt),e.component(`IconFile`,Xt),e.component(`IconFileAdded`,en),e.component(`IconForward`,an),e.component(`IconHix`,ln),e.component(`IconHyperlink`,pn),e.component(`IconImageFileLandscape`,_n),e.component(`IconImageFileWarning`,xn),e.component(`IconInbox`,Tn),e.component(`IconInfo`,H),e.component(`IconInformationCircle`,Mn),e.component(`IconItalic`,In),e.component(`IconListView`,Bn),e.component(`IconLock`,Wn),e.component(`IconLusciiEscalated`,Jn),e.component(`IconLusciiLogo`,Qn),e.component(`IconLusciiOpen`,nr),e.component(`IconLusciiPriorityHigh`,or),e.component(`IconLusciiPriorityLow`,ur),e.component(`IconLusciiPriorityMedium`,mr),e.component(`IconMenu`,vr),e.component(`IconMessage`,Sr),e.component(`IconMessageForward`,Er),e.component(`IconMicrophoneSlash`,kr),e.component(`IconMicrosoftTeams`,Nr),e.component(`IconMin`,Ir),e.component(`IconOrderedList`,Br),e.component(`IconPlus`,Wr),e.component(`IconRefresh`,Jr),e.component(`IconRemove`,Qr),e.component(`IconSananetLogo`,ri),e.component(`IconService`,si),e.component(`IconShareScreen`,di),e.component(`IconSingleNeutral`,mi),e.component(`IconSort`,vi),e.component(`IconSortAsc`,Si),e.component(`IconSortDesc`,Ei),e.component(`IconSortNone`,Ai),e.component(`IconTriangleDown`,Pi),e.component(`IconTriangleExclamation`,Ri),e.component(`IconUnderline`,Hi),e.component(`IconVideoDisabled`,Yi),e.component(`IconVideocall`,Ki),e.component(`IconWarning`,$i),e.component(`IconZorgkaart`,ra),e.directive(`bd-tooltip`,kH)}};exports.BDAlert=oa,exports.BDArticle=la,exports.BDAssignConversationModal=FU,exports.BDAttachmentPreviewList=T_,exports.BDAttachmentUploadModal=IU,exports.BDBadge=fa,exports.BDButton=ha,exports.BDCard=wa,exports.BDChangePasswordTemplate=TW,exports.BDChatCloud=Y_,exports.BDCol=d,exports.BDCollapsableCard=Oa,exports.BDConfirmationModal=LU,exports.BDContainer=f,exports.BDContentLibraryModal=Tie,exports.BDContentLibrarySplitButton=Eh,exports.BDContentLibraryTemplate=gW,exports.BDConversationToTextModal=yW,exports.BDDate=Gh,exports.BDDropdown=rU,exports.BDDropdownItem=X_,exports.BDFileUpload=tO,exports.BDForm=Kh,exports.BDFormCheckbox=ug,exports.BDFormInput=Mg,exports.BDFormInvalidFeedback=fg,exports.BDFormMultipleCheckbox=aO,exports.BDFormSelect=Lg,exports.BDHeader=cU,exports.BDImageAttachmentModal=xW,exports.BDImageAttachmentPreviewList=P_,exports.BDInputGroup=Bg,exports.BDLink=ma,exports.BDLogo=Ug,exports.BDMarkdownEditor=jH,exports.BDMessageTemplateFormModal=SW,exports.BDMobileMenu=FH,exports.BDModal=gU,exports.BDNotFoundTemplate=$9,exports.BDPagination=Xg,exports.BDPhoneNumberEditModal=xU,exports.BDPill=i_,exports.BDPractitionerHeader=MU,exports.BDProfileImage=s_,exports.BDRow=p,exports.BDSessionTimeOutModal=PU,exports.BDSmallConversationCard=BH,exports.BDTable=GH,exports.BDToast=f_,exports.BDUser=KH,exports.BDUserInformation=__,exports.BDVideoCallConfirmationModal=CW,exports.BDVideoCallTemplate=Pze,exports.BDVideoCallToast=nU,exports.BDZoomslider=b_,exports.CopyChatMessageToClipboard=Pie,exports.CopyChatMessagesToClipboard=Fie,exports.CopyHl7MessagesToClipboard=Iie,exports.CreateHyperlinkParagraph=Vze,exports.CreateThumbnailUri=R_,exports.IconAcademy=v,exports.IconArrowDown=S,exports.IconArrowUp=E,exports.IconAttachment=k,exports.IconBold=ne,exports.IconBulletList=M,exports.IconCalendar=le,exports.IconCall=N,exports.IconCallReject=ge,exports.IconCardView=F,exports.IconCaretDown=L,exports.IconCaretLeft=Se,exports.IconCaretRight=Ee,exports.IconCheck=Ae,exports.IconClipboard=Me,exports.IconClose=Ie,exports.IconComment=Be,exports.IconCommentActive=We,exports.IconCommentStatic=Je,exports.IconCommonFileEmpty=Qe,exports.IconCommonFileWarning=nt,exports.IconContactPerson=ot,exports.IconCopy=ut,exports.IconDelete=mt,exports.IconDoubleCheck=vt,exports.IconDownloadImage=St,exports.IconEdit=Et,exports.IconEndCall=At,exports.IconError=Pt,exports.IconExternal=Rt,exports.IconEyeShow=Ht,exports.IconEyeSlash=Kt,exports.IconFile=Xt,exports.IconFileAdded=en,exports.IconForward=an,exports.IconHix=ln,exports.IconHyperlink=pn,exports.IconImageFileLandscape=_n,exports.IconImageFileWarning=xn,exports.IconInbox=Tn,exports.IconInfo=H,exports.IconInformationCircle=Mn,exports.IconItalic=In,exports.IconListView=Bn,exports.IconLock=Wn,exports.IconLusciiEscalated=Jn,exports.IconLusciiLogo=Qn,exports.IconLusciiOpen=nr,exports.IconLusciiPriorityHigh=or,exports.IconLusciiPriorityLow=ur,exports.IconLusciiPriorityMedium=mr,exports.IconMenu=vr,exports.IconMessage=Sr,exports.IconMessageForward=Er,exports.IconMicrophoneSlash=kr,exports.IconMicrosoftTeams=Nr,exports.IconMin=Ir,exports.IconOrderedList=Br,exports.IconPlus=Wr,exports.IconRefresh=Jr,exports.IconRemove=Qr,exports.IconSananetLogo=ri,exports.IconService=si,exports.IconShareScreen=di,exports.IconSingleNeutral=mi,exports.IconSort=vi,exports.IconSortAsc=Si,exports.IconSortDesc=Ei,exports.IconSortNone=Ai,exports.IconTriangleDown=Pi,exports.IconTriangleExclamation=Ri,exports.IconUnderline=Hi,exports.IconVideoDisabled=Yi,exports.IconVideocall=Ki,exports.IconWarning=$i,exports.IconZorgkaart=ra,exports.MapAttachmentsForApi=F_,exports.MapToAttachmentObjects=V_,exports.TransformHyperlinks=Bze,exports.ValidateUrl=Hze,exports.default=Uze,exports.getDisplayDateNumeric=Uh,exports.getDisplayDateTextual=Bh,exports.getDisplayDateTimeNumeric=Hh,exports.getDisplayDateTimeTextual=Vh,exports.useModal=_U,exports.usePopover=EU,exports.useServerErrors=vU,exports.useSessionTimeOut=NU,exports.useToaster=ZD,exports.useValidation=wW,exports.useWindow=wU,exports.useZoom=bW,exports.vBdTooltip=kH;
|
|
2163
|
+
`],{type:`application/javascript`}),r=URL.createObjectURL(t);await this._playerAudioContext.audioWorklet.addModule(r);let i=new AudioWorkletNode(this._playerAudioContext,`player-processor`,{numberOfOutputs:1,outputChannelCount:[1]});this._logger.log(`Started Audio worklet.`),i.port.onmessage=async t=>{if(t.data.type===`startedProcessing`)this._logger.log(`Player audio buffer started processing audio.`),this.sendTelemetryEvent(+new Date-n,{step:J5.AUDIO_WORKLET_STARTED_PROCESSING,timestampInfo:{attemptTimestamp:n}},[`Success`],200),e(i);else if(t.data.type===`finished`){let e=+new Date;try{if(t.data.value.shutDownType===`speedUpBuffer`){if(!this._playerWorkletNode)throw new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.PLAYERAUDIOBUFFER_UNDEFINED_CANNOT_DISCONNECT_FOR_SPEEDUP});if(!this._playerAudioDestinationNode)throw new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.PLAYERAUDIOBUFFERNODE_UNDEFINED_FOR_SPEEDUP});this._logger.log(`Speeding up the rest of the audio buffer and shutting down player worklet node`);let n=t.data.value.restOfBufferToSpeedUp,r=n.reduce(((e,t)=>e+t[0].length),0);this._speedUpAudioBuffer=this._playerAudioContext.createBuffer(1,r,this._playerAudioContext.sampleRate);let i=0,a=new Float32Array(r),o=0;for(let e of n)i+=e[0].byteLength??0,a.set(e[0],o),o+=e[0].length;this._speedUpAudioBuffer.copyToChannel(a,0),this._playerWorkletNode.disconnect(),this._speedUpAudioBufferSourceNode=this._playerAudioContext.createBufferSource(),this._speedUpAudioBufferSourceNode.buffer=this._speedUpAudioBuffer,this._speedUpAudioBufferSourceNode.playbackRate.value=c.speedUpRate,this._speedUpAudioBufferSourceNode.connect(this._playerAudioDestinationNode),this.sendTelemetryEvent(+new Date-e,{step:J5.SET_SPEEDUP_AUDIO_STREAM,timestampInfo:{attemptTimestamp:e}},[`Success`],200),this._speedUpAudioBufferSourceNode.onended=()=>{this._storeRecording&&(this._recording?.stop(),this._recording=void 0);let n=+new Date;this._isFinished=!0,this._logger.log(`Finished speeding up the reset of the audio buffer and shut down player audio worklet. Will now switch to microphone.`);let r=t.data.value.playTimestamp,a=e-t.data.value.playTimestamp,o=n-e,s=n-t.data.value.playTimestamp,c=t.data.value.totalRawBytesBuffered,l=t.data.value.rawBytesPlayedNormalSpeed;this._statsReport.playTimestamp=r,this._statsReport.playNormalSpeedDurationInMs=a,this._statsReport.playSpeedUpDurationInMs=o,this._statsReport.totalPlayDurationInMs=s,this._statsReport.totalRawBytesBuffered=c,this._statsReport.rawBytesPlayedNormalSpeed=l,this._statsReport.rawBytesPlayedSpedUp=i,this.sendTelemetryEvent(n-e,{step:J5.SHUTDOWN_FINISHED_SPEEDING_UP_REST_OF_BUFFER,timestampInfo:{attemptTimestamp:e},playTimestamp:r,playNormalSpeedDurationInMs:a,playSpeedUpDurationInMs:o,totalPlayDurationInMs:s,totalRawBytesBuffered:c,rawBytesPlayedNormalSpeed:l,rawBytesPlayedSpedUp:i},[`Success`],200),this.disposeInternal().catch((()=>{this._logger.error(`Failed to dispose PreAudio feature after preAudio finished speeding up`)})),this._switchToRealTimeMic()},this._speedUpAudioBufferSourceNode.start()}}catch(t){this._logger.error(`Error handling finished event from player worklet`,t),this.disposeInternal().catch((()=>{this._logger.error(`Failed to dispose PreAudio feature when handling audio buffer speed up error`)})),this._switchToRealTimeMic();let n=new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.PLAYERAUDIOBUFFER_FINISHED_EVENT_FAIL,originalError:t});this._logger.error(n.message),this.sendTelemetryEvent(+new Date-e,{step:J5.SHUTDOWN_FINISHED_SPEEDING_UP_REST_OF_BUFFER,timestampInfo:{attemptTimestamp:e},...K3(n)},n.resultCategories,500)}}},this._logger.log(`Audio worklet initialized successfully`),this.sendTelemetryEvent(+new Date-n,{step:J5.START_AUDIO_WORKLET,timestampInfo:{attemptTimestamp:n}},[`Success`],200),e(i)}catch(e){this._logger.error(`Error initializing audio worklet`,e);let n=new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.PLAYER_AUDIO_BUFFER_INIT_FAIL,originalError:e});this._logger.error(n.message),t(n)}})),u=new Promise((async(e,t)=>{try{this._deviceManager=await this.mediaClient.getDeviceManager();let t=+new Date;if(this._deviceManager.shouldEnumerateDevices){if((await this._deviceManager.getMicrophones())[0]?.id===`microphone:`){this.sendTelemetryEvent(+new Date,{step:J5.AUDIO_PERMISSION_ASKED,timestampInfo:{attemptTimestamp:+new Date}},[`Success`],200);let e=await this._deviceManager.getAskDevicePermissionPromise({audio:!0,video:!1},x3.PreAudio);if(i=+new Date-t,!e.audio)throw new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.AUDIO_NO_PERMISSION})}this.sendTelemetryEvent(+new Date-t,{step:J5.AUDIO_PERMISSION_GRANTED,timestampInfo:{attemptTimestamp:t}},[`Success`],200)}else this._logger.info(`Device enumeration disabled, skipping getMicrophones permission check`);let n=+new Date;this._micLocalAudioStream=await Y5(this._deviceManager,this._logger),this._logger.log(`Got selected or default microphone`),this.sendTelemetryEvent(+new Date-n,{step:J5.SELECT_MICROPHONE,timestampInfo:{attemptTimestamp:n}},[`Success`],200);let r=+new Date;try{this._audioEffectsFeature=this._micLocalAudioStream.feature(R3(a8));let e=t8().engine;await this._audioEffectsFeature.startEffects({noiseSuppression:e===`Chromium`?this._noiseSuppression:e===`Safari`?void 0:`BrowserNoiseSuppression`,echoCancellation:e===`Chromium`?this._echoCancellation:`BrowserEchoCancellation`}),this.sendTelemetryEvent(+new Date-r,{step:J5.SET_NOISE_SUPPRESSION,timestampInfo:{attemptTimestamp:r}},[`Success`],200)}catch(e){this._logger.error(`Failed to start effects sdk noise suppression`,e);let t=new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.START_EFFECTS_FAIL,originalError:e});throw this._logger.error(t.message),t}this._logger.log(`Effects applied to mic stream with audio effects feature`);let a=+new Date,o;this._micIRawStream=this._deviceManager.getRawDeviceMediaStream(0),this._micIRawStream.changed((async()=>{let e=+new Date;try{this._logger.log(`Microphone raw stream changed`);try{this._micRawMediaStream=await this._micIRawStream?.getMediaStream(!0)}catch(e){this._logger.error(`Failed to get updated raw mic media stream from dm on changed event`,e);let t=W3(e,!0,new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.MICROPHONE_RAW_MEDIASTREAM_CHANGED_FAIL,originalError:e}));throw this._logger.error(t.message),t}this._logger.log(`Got updated raw mic stream from dm on changed event`),this._mediaStreamSession&&this._micRawMediaStream&&this._mediaStreamSession.updateOutboundAudioStream(this._micRawMediaStream),this.sendTelemetryEvent(+new Date-e,{step:J5.MICROPHONE_RAW_MEDIASTREAM_CHANGED,timestampInfo:{attemptTimestamp:e}},[`Success`],200)}catch(t){this._logger.error(`Error handling microphone raw stream changed event`,t);let n=new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.MICROPHONE_RAW_MEDIASTREAM_CHANGED_FAIL,originalError:t});this._logger.error(n.message),this.sendTelemetryEvent(+new Date-e,{step:J5.START_RECORD_AUDIO,timestampInfo:{attemptTimestamp:e},...K3(n)},n.resultCategories,500)}}));try{o=await this._micIRawStream.getMediaStream(!0)}catch(e){this._logger.error(`Failed to get raw mic media stream from dm`,e);let t=W3(e,!0,new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.GET_MIC_STREAM_FAIL,originalError:e}));throw this._logger.error(t.message),t}this._logger.log(`Got raw mic stream from dm`),this.sendTelemetryEvent(+new Date-a,{step:J5.GET_MIC_STREAM,timestampInfo:{attemptTimestamp:a}},[`Success`],200),e(o)}catch(e){this._logger.error(`Error getting microphone media stream`,e);let n=new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.GET_MIC_STREAM_FAIL,originalError:e});this._logger.error(n.message),t(n)}})),[d,f]=await Promise.all([l,u]);this._playerWorkletNode=d,this._micRawMediaStream=f;let p=+new Date,m;try{this._playerAudioSourceNode=this._playerAudioContext.createMediaStreamSource(this._micRawMediaStream),this._playerAudioSourceNode.connect(this._playerWorkletNode),m=this._playerAudioContext.createAnalyser(),m.fftSize=2048,this._playerAudioSourceNode.connect(m),this._playerAudioDestinationNode=this._playerAudioContext.createMediaStreamDestination(),this._playerWorkletNode.connect(this._playerAudioDestinationNode),this._playerRawMediaStream=this._playerAudioDestinationNode.stream,this._playerAudioStream=new u8(this._playerRawMediaStream),this._logger.log(`Created local audio stream from player media stream`),c.getMicStreamSettleTimeInMs>0&&await new Promise((e=>{setTimeout((()=>{this._logger.log(`Mic stream settled`),e()}),c.getMicStreamSettleTimeInMs)})),this._logger.log(`Connected microphone media stream to player worklet node`),this.sendTelemetryEvent(+new Date-p,{step:J5.CONNECT_MIC_TO_PLAYERWORKLET,timestampInfo:{attemptTimestamp:p}},[`Success`],200)}catch(e){this._logger.error(`Failed to connect microphone media stream to player worklet node`,e);let t=new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.CONNECT_MIC_TO_PLAYERAUDIOBUFFER_FAIL,originalError:e});throw this._logger.error(t.message),t}let h=!1,g=null,_=null,v=performance.now(),y=+new Date,b;this._logger.log(`Start time of silence detection: ${y}`);let x=c.speechTimeoutInSec,S=c.rmsThreshold,C=n?c.speechDurationThresholdForPreheated:c.speechDurationThreshold,w=c.silenceDurationThreshold;this._logger.log(`Will use the following thresholds for silence detection:\n Speech Timeout: ${x} seconds,\n RMS Threshold: ${S},\n Speech Duration Threshold: ${C} seconds,\n Silence Duration Threshold: ${w} seconds\n `);let T=0,E=c.logging.rmsLogIntervalInMs,ee=0,D=0,O=c.logging.silenceLogIntervalInMs,k=0,A=c.logging.speechLogIntervalInMs;this._statsReport.rmsMaxDetected={rmsLogIntervalInMs:E,rmsIntervals:[]};let j=async()=>{let e=new Uint8Array(m.fftSize);m.getByteTimeDomainData(e);let t=Math.round(1e4*Math.sqrt(e.reduce(((e,t)=>e+(t-128)**2),0)/e.length))/1e4,n=Math.round((performance.now()-v)/1e3*100)/100;t>ee&&(ee=t);let r=performance.now();if(r-T>=E&&(this._logger.log(`RMS: ${ee}, Seconds past silence detection start: ${n}`),this._statsReport.rmsMaxDetected?.rmsIntervals.push({secondsPastSilenceDetectionsStart:n,maxRms:ee}),T=r,ee=0),n>x&&h)return this._logger.log(`PreAudio silence detection timed out after ${x} seconds. Will shut down player audio worklet, speed up rest of the buffer, and then switch to microphone`),this._statsReport.finishType=J5.SHUTTINGDOWN_PLAYERAUDIOWORKLET_SPEEDUP_AFTER_TIMEOUT,this._statsReport.speechSilenceDetectionDurationInMs=+new Date-y,this._playerWorkletNode?.port.postMessage({type:`shutDown`,value:{shutDownType:`speedUpBuffer`}}),void this.sendTelemetryEvent(+new Date-y,{step:J5.SHUTTINGDOWN_PLAYERAUDIOWORKLET_SPEEDUP_AFTER_TIMEOUT,timestampInfo:{attemptTimestamp:y},rmsMaxDetected:this._statsReport.rmsMaxDetected},[`Success`],200);if(this._isFinished||!h&&(this._play||n>x)){let e,t;this._isFinished?(this._logger.log(`PreAudio already finished, will not do any silence detection and will shutdown player audio worklet`),e=J5.SHUTDOWN_ALREADY_FINISHED):!h&&this._play?(this._logger.log(`No speech detected when play was called. Will switch to real-time microphone, and shut down player audio worklet async`),t=`Failed to dispose PreAudio feature after preAudio finished due to no speech detected`,e=J5.SHUTDOWN_NO_SPEECH_DETECTED):!h&&n>x&&(this._logger.log(`PreAudio silence detection timed out after ${x} seconds and no speech was detected. Will shut down player audio worklet and switch to real-time microphone`),t=`Failed to dispose PreAudio feature when no speech was detected after timeout`,e=J5.SHUTDOWN_PLAYERAUDIOWORKLET_NOSPEECHDETECTED_AFTER_TIMEOUT),this._isFinished=!0,this._statsReport.finishType=e,this._statsReport.speechSilenceDetectionDurationInMs=+new Date-y,this.disposeInternal().catch((()=>{this._logger.error(t)})),this.sendTelemetryEvent(+new Date-y,{step:e,timestampInfo:{attemptTimestamp:y},rmsMaxDetected:this._statsReport.rmsMaxDetected},[`Success`],200),this._switchToRealTimeMic();return}if(t>S){if(_===null&&(this._logger.log(`Starting speech timer at ${n} seconds past start`),_=performance.now(),b=Date.now()),g=null,(performance.now()-_)/1e3>=C){h=!0;let e=performance.now();e-k>=A&&(this._logger.log(`Speech detected for at least a duration of ${C} seconds at ${n} seconds past start`),k=e),this._pendingSpeechStartEpoch===void 0&&(this._pendingSpeechStartEpoch=b,this._logger.log(`Captured pending first speech epoch: ${this._pendingSpeechStartEpoch}`),this.applyPendingSpeechStartTimestampToSession(`post-detection`))}}else if(g===null&&(this._logger.log(`Starting silence timer at ${n} seconds past start`),g=performance.now()),(performance.now()-g)/1e3>=w){if(h){this._logger.log(`Silence detected for a duration of at least 1 second at ${n} seconds past start`),this._playerWorkletNode?.port.postMessage({type:`shutDown`,value:{shutDownType:`speedUpBuffer`}});let e=+new Date-y;this._statsReport.totalRtcAudioBufferedDurationInMs=e,this._statsReport.finishType=J5.SHUTTINGDOWN_PLAYERAUDIOWORKLET_SILENCE_DETECTED_AFTER_SPEECH,this._statsReport.speechSilenceDetectionDurationInMs=+new Date-y,this.sendTelemetryEvent(e,{step:J5.SHUTTINGDOWN_PLAYERAUDIOWORKLET_SILENCE_DETECTED_AFTER_SPEECH,timestampInfo:{attemptTimestamp:y},rmsMaxDetected:this._statsReport.rmsMaxDetected,totalRtcAudioBufferedDurationInMs:e},[`Success`],200);return}let e=performance.now();e-D>=O&&(this._logger.log(`Silence detected for at least 1 second, but no speech detected yet. RMS: ${t}. Seconds past start: ${n}`),D=e),_=null,b=void 0}requestAnimationFrame(j)};j(),this._logger.log(`Audio recording started successfully`);let te=+new Date-i;this._statsReport.recordAudioSuccessTimestamp=te,this.sendTelemetryEvent(te-o,{step:J5.START_RECORD_AUDIO,timestampInfo:{attemptTimestamp:o,successTimestamp:te,createMediaSdkStackBaseDuration:a,adpDuration:i}},[`Success`],200)}catch(e){this._recordAudioFailed=!0,this._logger.error(`Audio recording failed`,e),this.disposeInternal().catch((()=>{this._logger.error(`Failed to dispose PreAudio feature when handling audio recording error`)})),this._switchToRealTimeMic();let t=new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.FAILED_TO_RECORD,originalError:e});throw this._logger.error(t.message),this.sendTelemetryEvent(+new Date-o,{step:J5.START_RECORD_AUDIO,timestampInfo:{attemptTimestamp:o},createMediaSdkStackBaseDuration:a,adpDuration:i,...K3(t)},t.resultCategories,500),t}finally{this._recordAudioFinished=!0}}play(){let e=+new Date;try{this._storeRecording&&this._playerRawMediaStream&&(this._recording=new MediaRecorder(this._playerRawMediaStream,{mimeType:this._recordingMimeType}),this._recordingChunks=[],this._recording.ondataavailable=e=>{e.data.size&&(this._logger.log(`Got preaudio recording data`),this._recordingChunks.push(e.data))},this._recording.start()),this._play=!0,this._playerWorkletNode?.port.postMessage({type:`play`,value:!0}),this._logger.log(`Audio playback started`),this.sendTelemetryEvent(+new Date-e,{step:J5.START_PLAY_AUDIO,timestampInfo:{attemptTimestamp:e}},[`Success`],200)}catch(t){this._logger.error(`Audio playback failed`,t),this.disposeInternal().catch((()=>{this._logger.error(`Failed to dispose PreAudio feature when handling audio playback error`)}));let n=new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.FAILED_TO_PLAY,originalError:t});throw this._logger.error(n.message),this.sendTelemetryEvent(+new Date-e,{timestampInfo:{attemptTimestamp:e},step:J5.START_PLAY_AUDIO,...K3(n)},n.resultCategories,500),n}}downloadRecording(){if(!this._storeRecording||!this._recordingMimeType)return;let e=this._recordingMimeType?.includes(`ogg`)?`ogg`:this._recordingMimeType?.includes(`mp4`)?`m4a`:`webm`,t=new Blob(this._recordingChunks,{type:this._recordingMimeType}),n=document.createElement(`a`);n.href=URL.createObjectURL(t),n.download=`preAudio_recording_${+new Date}.${e}`,n.click(),URL.revokeObjectURL(n.href)}async dispose(){return await this.disposeInternal(!1)}_switchToRealTimeMic(){this._internalDisposed&&this._switchToRealTimeMicCallBack?.()}};function X5(e,t,n,r,i,a){let o=a?K3(a):void 0;r&&i&&z3({featureName:`activeCallTransfer`,featureDetails:{name:`activeCallTransfer`,step:t},featureType:`callAgent`,localParticipantId:e,callId:n?.callId??``,correlationId:``,initializationType:`OnFeatureAccess`,additionalDetails:o},r,i)}var lIe=class{constructor(e,t,n,r){this._skypeConversationObjectMaps=new Map,this._callAgent=e,this._tsCallRegistry=t,this._clientLogger=r}async transferActiveCall(e,t,n){let r,i,a=mTe(e);if(r=this._skypeConversationObjectMaps.get(e.callId),!r)throw this._clientLogger.error(`No SkypeConversationObject found for active call with callId: ${e.callId}`),new Y({defaultError:J.FEATURES.ACTIVE_CALL_TRANSFER.CONVERSATION_NOT_FOUND});if(a){let t=e.meetingLocator.organizerId;r={...r,groupCallInitiator:t},i=2}else i=0;let o={skypeConversationObject:r,mediaPeerType:i},s=n?.joinCallOptions?.videoOptions?.localVideoStreams&&n.joinCallOptions.videoOptions.localVideoStreams.length>0,c=!0!==n?.joinCallOptions?.audioOptions?.muted,l={shouldResurrect:`resurrect`,...o},u,d=K0(),f=AG();try{u=await this._tsCallRegistry.createCallAsync({causeId:f,localParticipantId:d,type:`ThreadId`,callId:e.callId,threadId:a?e.meetingLocator.threadId:``});let i=t.createNewCall(e.callId,u);if(mTe(e)?await u.joinWithMeetingData(f,r,l):await u.join(r,l,f),i.bindTsCall(),s&&n?.joinCallOptions?.videoOptions?.localVideoStreams&&i.startVideo(n.joinCallOptions.videoOptions.localVideoStreams[0]),!1===c&&this._callAgent.deviceManager.selectedMicrophone){this._callAgent.deviceManager.selectedMicrophone;let e=new u8(this._callAgent.deviceManager.selectedMicrophone);i.startAudio(e)}if(this._callAgent.addToCallArray(i),this._callAgent.handleCallState(i),n?.isTransfer){let e=u.endpointId;try{await u.removeParticipant(this._callAgent.getUserMri(),f,e,1)}catch(e){throw this._clientLogger.error(`Failed to remove participant from call during transfer: ${e}`),new Y({defaultError:J.FEATURES.ACTIVE_CALL_TRANSFER.FAILED_TO_REMOVE_PARTICIPANT,originalError:e})}}return X5(this._callAgent.getUserMri(),$.success,e),i}catch(e){throw this._clientLogger.error(`Active call transfer failed: ${e}`),new Y({defaultError:J.FEATURES.ACTIVE_CALL_TRANSFER.ACTIVE_CALL_TRANSFER_FAILURE,originalError:e})}}async getActiveCallDetails(e){let t=this._callAgent.getHttpRequestHelper(),n=this._callAgent.getUserMri(),r={headers:{"Content-Type":`application/json`,"X-SkypeToken":e.jwtToken},method:`GET`},i=Z().calling.activeCallTransfer.callStoreUrl,a=await t.send(i+`${n}/conversations`,JSON.stringify({}),r,3),o=await t.extractPayload(a);if(o&&a.status===200){let e=o,t=e[0];e.length>1&&e.forEach((e=>{e.userJoinTime&&t.userJoinTime&&e.userJoinTime>t.userJoinTime&&(t=e)}));let n=e.map((e=>{if(this._skypeConversationObjectMaps.set(e.correlationId,{conversationUrl:e.conversationController,conversationId:e.correlationId}),`meetingInfo`in e)return this._clientLogger.info(`Found active meeting for client with callId: ${e.correlationId}, threadId: ${e.groupContext.threadId}`),{callId:e.correlationId,meetingLocator:{threadId:e.groupContext.threadId,organizerId:e.meetingInfo.organizerId,tenantId:e.meetingInfo.tenantId,messageId:e.meetingInfo.replyChainMessageId??``},userJoinTime:new Date(e.userJoinTime)};{let t=e.participants.map((e=>G2(e)));return{callId:e.correlationId,participants:t,userJoinTime:new Date(e.userJoinTime)}}}));return this._clientLogger.log(`[ActiveCallTransfer] activeCallList:`,n),n}if(o&&a.status>=400)throw this._clientLogger.error(`Failed to get active calls for client with error: ${o.message}`),new Y({defaultError:J.FEATURES.ACTIVE_CALL_TRANSFER.GET_ACTIVE_CALL_DETAILS_INVALID_TOKEN,originalError:Error(o.message)});this._clientLogger.info(`No active calls found for the client`)}},uIe=class extends LEe{initialize(e,t){if(t.info(`Initializing ActiveCallTransferFeatureImpl`),this._logger=t,this._tsCallRegistry=this._callAgent.getInternalCallRegistry(),this._telemetryLogger=e.telemetryLogManager,this._tsCallRegistry?.on(`proxiedPushNotification`,this.handleProxiedNotification),!this._tsCallRegistry||!this._telemetryLogger)throw this._logger?.error(`Failed to initialize ActiveCallTransferFeatureImpl: TS Call Registry or Telemetry Logger is undefined`),new Y({defaultError:J.FEATURES.ACTIVE_CALL_TRANSFER.CALLAGENT_NOT_INITIALIZED});this._activeCallTransferManager=new lIe(this._callAgent,this._tsCallRegistry,this._telemetryLogger,this._logger)}constructor(e){super(e),this.name=`ActiveCallTransfer`,this.handleProxiedNotification=async e=>{let t,n=this._callAgent._caConfigBag.parsedTokenCredential;if(n){if(e.eventId===115&&this._activeCallTransferManager)this._logger?.log(`Received proxied notification with eventId 115`,e),t=await this._activeCallTransferManager?.getActiveCallDetails(n),t&&t.length>0?(this._logger?.log(`Active call found, emitting activeCallsUpdated event`),X5(this._callAgent.getUserMri(),$.success,t[0],this._telemetryLogger,this._logger),this.emitNewActiveCallDetailsEvent(t)):this._logger?.log(`No active call found, not emitting activeCallsUpdated event`);else if(e.eventId===116&&this._activeCallTransferManager){if(this._logger?.log(`Received proxied notification with eventId 116`,e),t=await this._activeCallTransferManager?.getActiveCallDetails(n),t&&t.length>0)return this._logger?.log(`Active call found on eventId 116, emitting activeCallsUpdated event, forgoing noActiveCalls event`),X5(this._callAgent.getUserMri(),$.success,t[0],this._telemetryLogger,this._logger),void this.emitNewActiveCallDetailsEvent(t);this._logger?.log(`No active call found on eventId 116, emitting noActiveCalls event`),X5(this._callAgent.getUserMri(),$.success,void 0,this._telemetryLogger,this._logger),this.emitNoActiveCallsEvent()}}else this._logger?.error(`No valid token found, cannot process active call details`)},this._callAgent=e.callAgent}async activeCallTransfer(e,t){let n;X5(this._callAgent.getUserMri(),$.attempt,e,this._telemetryLogger,this._logger);try{if(!this._activeCallTransferManager){let t=new Y({defaultError:J.FEATURES.ACTIVE_CALL_TRANSFER.MANAGER_UNDEFINED,originalError:Error(`ActiveCallTransferManager not initialized`)});throw X5(this._callAgent.getUserMri(),$.failure,e,this._telemetryLogger,this._logger,t),t}n=await this._activeCallTransferManager.transferActiveCall(e,this._callAgent,t),this._callAgent.handleActiveCallTransfer(n)}catch(t){this._logger?.error(`Failed to handle active call transfer`,t);let n=new Y({defaultError:J.FEATURES.ACTIVE_CALL_TRANSFER.ACTIVE_CALL_TRANSFER_FAILURE,originalError:t});throw X5(this._callAgent.getUserMri(),$.failure,e,this._telemetryLogger,this._logger,n),n}return X5(this._callAgent.getUserMri(),$.success,e,this._telemetryLogger,this._logger),n}async getActiveCallDetails(){X5(this._callAgent.getUserMri(),$.attempt,void 0,this._telemetryLogger,this._logger);let e=this._callAgent._caConfigBag.parsedTokenCredential;if(!this._activeCallTransferManager||!e){this._logger?.error(`Failed to get active call details: ActiveCallTransferManager not initialized or token is invalid`);let e=new Y({defaultError:J.FEATURES.ACTIVE_CALL_TRANSFER.MANAGER_TOKEN_UNDEFINED,originalError:Error(`ActiveCallTransferManager not initialized or token is invalid`)});throw X5(this._callAgent.getUserMri(),$.failure,void 0,this._telemetryLogger,this._logger,e),e}let t;try{t=await this._activeCallTransferManager?.getActiveCallDetails(e)}catch(e){this._logger?.error(`Failed to get active call details`,e);let t=new Y({defaultError:J.FEATURES.ACTIVE_CALL_TRANSFER.GET_ACTIVE_CALL_DETAILS_FAILURE,originalError:e});throw X5(this._callAgent.getUserMri(),$.failure,void 0,this._telemetryLogger,this._logger,t),t}return X5(this._callAgent.getUserMri(),$.success,void 0,this._telemetryLogger,this._logger),t}dispose(){this.eventEmitter.removeAllListeners()}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}emitNewActiveCallDetailsEvent(e){this.eventEmitter.emit(`activeCallsUpdated`,{activeCallDetails:e})}emitNoActiveCallsEvent(){this.eventEmitter.emit(`noActiveCalls`)}},Z5={Recording:I3(COe),Transfer:I3(FOe),Transcription:I3(kOe),Captions:I3(sDe),Copilot:I3(dDe),RaiseHand:I3(pDe),LocalRecording:I3(EOe),Reaction:I3($Pe),Spotlight:I3(FAe),PPTLive:I3(rFe),BreakoutRooms:I3(wFe),Capabilities:I3(wDe),DominantSpeakers:I3(BDe),LiveStream:I3(Dke),ComposedStream:I3(Ake),CallSurvey:I3(LAe),UserFacingDiagnostics:I3(FDe),MediaStats:I3(SOe,{activationEvent:`OnExtendedObjectConstructor`}),DebugInfo:GEe(jDe,{activationEvent:`OnExtendedObjectConstructor`}),PreCallDiagnostics:GEe(yke),VideoEffects:qEe(G6),AudioEffects:R3(a8),DataChannel:I3(PAe),OptimalVideoCount:I3(BAe),UnmixedAudio:I3(rje),AudioZones:I3(RAe),TeamsMeetingAudioConferencing:I3(ije),TogetherMode:I3(mFe),MediaAccess:I3(Q3),RealTimeText:I3(EFe),DataChannelSession:L3($Fe,{activationEvent:`OnExtendedObjectConstructor`}),MediaStatsSession:L3(rIe,{activationEvent:`OnExtendedObjectConstructor`}),UserFacingDiagnosticsSession:L3(iIe,{activationEvent:`OnExtendedObjectConstructor`}),PreAudioSession:KEe(cIe),ActiveCallTransfer:WEe(uIe)};function Q5(e){switch(e){case D3.CallClientFeature:return Object.entries(Z5).filter((e=>!0===e[1].isCallClientFeature)).map((e=>e[1]));case D3.CallAgentFeature:return Object.entries(Z5).filter((e=>!0===e[1].isCallAgentFeature)).map((e=>e[1]));case D3.CallFeature:return Object.entries(Z5).filter((e=>!0===e[1].isCallFeature)).map((e=>e[1]));case D3.MediaClientFeature:return Object.entries(Z5).filter((e=>!0===e[1].isMediaClientFeature)).map((e=>e[1]));case D3.SessionFeature:return Object.entries(Z5).filter((e=>!0===e[1].isSessionFeature)).map((e=>e[1]))}}var dIe=class{constructor(e,t){this._eventBag=[],this.resetEventBag=()=>{this._eventBag=[]},this._logger=e.createChild(`CallStats`),this._telemetryLogManager=t}recordEvent(e){try{if(Z()?.telemetry?.callStatsFlushTimeout<0||Z()?.telemetry?.blockedEvents?.indexOf(e.name)>-1)return;let t={timestamp:+new Date,...e};this._logger.debug(`CallStat recorded=${e.name}`),this._eventBag.push(t),this.scheduleTelemetryFlush()}catch{this._logger.debug(`Failed to record call stats`)}}flushEvents(){if(this._logger.debug(`CallStats sending telemetry, number of events=${this._eventBag.length}`),this._eventBag.length!==0)try{let e=this._eventBag.reduce(((e,t)=>(e[t.localParticipantId]?e[t.localParticipantId].events.push({name:t.name,timestamp:t.timestamp,...t.data}):e[t.localParticipantId]={callId:t.callId,localParticipantId:t.localParticipantId,events:[{name:t.name,timestamp:t.timestamp,...t.data}]},e)),{});Object.keys(e).forEach((t=>{this._telemetryLogManager.sendEvent({name:Q.acs_calling_call_stats,tenant:d2,properties:{...e[t]}})})),this.resetEventBag()}catch{this._logger.debug(`Failed to send call stats`)}}scheduleTelemetryFlush(){this._callStatSendTimeout||=window.setTimeout((()=>{this.flushEvents(),this._callStatSendTimeout=void 0}),Z().telemetry.callStatsFlushTimeout)}};function $5(e,t){if(t===`Connected`)return;let n;if(e==o4.MuteAllRemoteParticipants)n=J.CALL.MUTE_ALL_PARTICIPANTS_CALL_NOT_CONNECTED;else if(e==o4.StopAudio)n=J.CALL.STOP_AUDIO_STREAM_CALL_NOT_CONNECTED;else if(e==o4.AddParticipant)n=J.CALL.ADD_PARTICIPANT_CALL_NOT_CONNECTED;else{if(e!=o4.RemoveParticipant)return;n=J.CALL.REMOVE_PARTICIPANT_CALL_NOT_CONNECTED}throw new Y({defaultError:n})}var fIe=class{constructor(e){this._volumeIndicator=e,this._eventEmitter=new T3}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}get level(){return this._volumeIndicator.level}async setSource(e){this._mediaStream!==e&&(this._mediaStream&&this._volumeIndicator.dispose(),e&&(this._mediaStream=e,await this._volumeIndicator.getVolumeIndicator(e),this._volumeIndicator.on(`levelChanged`,(()=>{this._eventEmitter.emit(`levelChanged`)}))))}dispose(){this._eventEmitter.removeAllListeners()}},pIe=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},mIe=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},hIe=class{constructor(e,t,n,r){this._workQueue=Promise.resolve();let i=KW(`ACS-calling`);this.logger=new z6(i,[()=>`RemoteAudioStream for media stream`]),this._source=e,this._disposed=!1,this._volumeIndicator=new X6(this.logger,`RemoteAudioStream`,t,n,r),e.changed((async()=>{this._volumeProxy&&(this._workQueue=this._workQueue.then((async()=>{await this._volumeProxy?.setSource(await this._source.getMediaStream())})).catch((e=>{this.logger.log(`source changed but failed to update volume indicator: ${e?.message??`unknown error`}`)})))})),this.logger.info(`created`)}async getMediaStream(){return await this._source.getMediaStream()}get source(){return this._source}dispose(){this.logger.log(`dispose`),this._disposed?this.logger.log(`already disposed`):(this._volumeIndicator.dispose(),this._disposed=!0)}async getVolume(){if(!this._volumeProxy){let e=new fIe(this._volumeIndicator),t=this._workQueue.then((async()=>{await e.setSource(await this._source.getMediaStream())}));this._workQueue=t.catch(A4),await t,this._volumeProxy=e}return this._volumeProxy}};pIe([zG,mIe(`design:type`,Object)],hIe.prototype,`logger`,void 0);var gIe=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},_Ie=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},vIe=class{get currentVideoConstraints(){return this._currentVideoConstraints}constructor(e,t,n){this._tsCall=e,this._currentVideoConstraints={send:{frameHeight:{max:void 0},frameRate:{max:void 0},bitrate:{max:void 0}}},this._logger=t.createChild(`MediaConstraintsManager`),this._telemetryLogManager=n}async setVideoConstraints(e,t,n,r){let i=this.getTelemetryPayload({video:e}),a=e=>{let i=e?{failureReason:e?e.message:void 0,code:e?e.code:void 0,...K3(e)}:void 0;z3({correlationId:n,callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:`SetConstraints`,featureType:`Call`,initializationType:`None`,timestampInfo:{deltaTimeInMs:+new Date-r},featureDetails:{name:`setConstraints`,step:e?$.failure:$.success,stage:t},additionalDetails:{constraints:this.getTelemetryPayload({video:this._currentVideoConstraints}),...i}},this._telemetryLogManager,this._logger)};try{if(z3({correlationId:n,callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:`SetConstraints`,featureType:`Call`,initializationType:`None`,timestampInfo:``,featureDetails:{name:`setConstraints`,step:$.attempt,stage:t},additionalDetails:{constraints:i}},this._telemetryLogManager,this._logger),!Z().calling.constraints.enabled)throw this._logger.error(`Setting call constraints is disabled`),new Y({defaultError:J.CALL.MEDIA_CONSTRAINTS_DISABLED});this._updateVideoConstraintsCache(e);let r={outgoingVideoLimit:{maxResolution:this._currentVideoConstraints.send?.frameHeight?.max,maxFramerate:this._currentVideoConstraints.send?.frameRate?.max,maxBitrate:this._currentVideoConstraints.send?.bitrate?.max}},o=this._tsCall.setCallConstraints?.(r);if(t!==`mid-call`)o?.then((()=>{this._logger.info(`Successfully set call constraints at call ${t} - ${JSON.stringify(this._currentVideoConstraints)}`),a()})).catch((e=>{this._logger.error(`Error setting call constraints at call ${t}`),a(new Y({defaultError:J.CALL.SET_CONSTRAINTS_START_OR_ACCEPT,defaultErrorMessageArgs:[t],originalError:e}))}));else try{await o,this._logger.info(`Successfully set call constraints during ${t} - ${JSON.stringify(this._currentVideoConstraints)}`),a()}catch(e){throw new Y({defaultError:J.CALL.SET_CONSTRAINTS_MID_CALL,originalError:e})}return this._currentVideoConstraints}catch(e){let n=new Y({defaultError:J.CALL.SET_CONSTRAINTS,defaultErrorMessageArgs:[t],originalError:e});throw a(n),n}}getTelemetryPayload(e){return{video:{send:{frameHeight:{max:e.video?.send?.frameHeight?.max},frameRate:{max:e.video?.send?.frameRate?.max},bitrate:{max:e.video?.send?.bitrate?.max}}}}}_updateVideoConstraintsCache(e){let t=Z(),n=t.calling.constraints.maxOutgoingResolution,r=t.calling.constraints.maxOutgoingFrameRate,i=t.calling.constraints.maxOutgoingVideoBitrate,a=e?.send?.frameHeight?.max??this._currentVideoConstraints.send?.frameHeight?.max,o=e?.send?.frameRate?.max??this._currentVideoConstraints.send?.frameRate?.max,s=e?.send?.bitrate?.max??this._currentVideoConstraints.send?.bitrate?.max;this._currentVideoConstraints={send:{frameHeight:{max:this._getConstraintValue(n,`maxOutgoingResolution`,a)},frameRate:{max:this._getConstraintValue(r,`maxOutgoingFrameRate`,o)},bitrate:{max:this._getConstraintValue(i,`maxOutgoingBitrate`,s)}}}}_getConstraintValue(e,t,n){return typeof n==`number`?n<1?void this._logger.info(`Received ${t} as 0 or less, removing ${t} constraint`):(e>0&&n>e&&(this._logger.info(`${t} value ${n} is larger than ${e}, resetting to ${e}`),n=e),n):void this._logger.warn(`Received invalid ${t} value, removing ${t} constraint`)}};gIe([zG,_Ie(`design:type`,Object)],vIe.prototype,`_logger`,void 0);var e7=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},t7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},n7=class{constructor(e,t,n,r){this.logger=n.createChild(`Lobby`),this._tsCall=e,this._eventEmitter=new S6(this.logger),this._participants=new Map,this._call=t,this._telemetryLogManager=r,this._lobbySupportedConversationTypes=Z().calling.lobbyAdmitAndReject.supportedConversationTypes,this._isLobbyEnabled=Z().calling.lobbyAdmitAndReject.enabled,this._hasExpectedError=!1,this._isLobbyEnabled&&(this.getInLobbyParticipants(t.remoteParticipants),this._remoteParticipantUpdatedListener=e=>{if(e.added.length!==0&&e.added.forEach((e=>{e.state===`InLobby`&&this.addLobbyParticipant(e),e.on(`stateChanged`,(()=>{e.state===`InLobby`?this.addLobbyParticipant(e):e.state===`Connected`&&this.removeLobbyParticipant(e)}))})),e.removed.length!==0){if(this._call.remoteParticipants.length===0)return void this.removeAllLobbyParticipants();e.removed.forEach((e=>{this.removeLobbyParticipant(e)}))}},this._call.on(`remoteParticipantsUpdated`,this._remoteParticipantUpdatedListener))}on(e,t){if(e!==`lobbyParticipantsUpdated`)throw new Y({defaultError:J.LOBBY.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if(e!==`lobbyParticipantsUpdated`)throw new Y({defaultError:J.LOBBY.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}async admit(e,t){if(!this._isLobbyEnabled)return void this.logger.warn(`Lobby is not enabled`);let n=K0(),r=+new Date;this._sendLobbyAdmitAndRejectUsage(`Start admit participant`,c3.lobbyAdmit,n,$.attempt,void 0);try{q2(e),this.validateLobbyOperation(e),await this._tsCall.admitParticipant(W2(e));let t=+new Date;this._sendLobbyAdmitAndRejectUsage(`Lobby participant admitted successfully`,c3.lobbyAdmit,n,$.success,t-r)}catch(e){let t=u3.Unexpected;this._hasExpectedError&&=(t=u3.Expected,!1),this.handleLobbyAdmitAndRejectFailure(`Failed to admit participant from lobby`,e,n,r,c3.lobbyAdmit,t)}}async reject(e,t){if(!this._isLobbyEnabled)return void this.logger.warn(`Lobby is not enabled`);let n=K0(),r=+new Date;this._sendLobbyAdmitAndRejectUsage(`Start reject participant`,c3.lobbyReject,n,$.attempt,void 0);try{q2(e),this.validateLobbyOperation(e),await this._tsCall.removeParticipant(W2(e));let t=+new Date;this._sendLobbyAdmitAndRejectUsage(`Lobby participant rejected successfully`,c3.lobbyReject,n,$.success,t-r)}catch(e){let t=u3.Unexpected;this._hasExpectedError&&=(t=u3.Expected,!1),this.handleLobbyAdmitAndRejectFailure(`Failed to reject participant from lobby`,e,n,r,c3.lobbyReject,t)}}async admitAll(e){let t=K0(),n=+new Date,r,i=0,a=0;if(!this._isLobbyEnabled)return this.logger.warn(`Lobby is not enabled`),{successCount:i,failureCount:a};this._sendLobbyAdmitAndRejectUsage(`Start admit all participants`,c3.lobbyAdmitAll,t,$.attempt,void 0);try{this.validateLobbyOperation(),await this._tsCall.admit({scope:`all`},AG()).then((e=>{if(r=e,e.result){let t=JSON.parse(e.result);i=t.successCount,a=t.failureCount}}));let e=+new Date;if(a!==0)return this._sendLobbyAdmitAndRejectUsage(`${i} participants are admitted successfully, ${a} participants admit failed. TransactionEnd: ${r}`,c3.lobbyAdmitAll,t,$.success,e-n),{successCount:i,failureCount:a};this._sendLobbyAdmitAndRejectUsage(`All participants are admitted successfully`,c3.lobbyAdmitAll,t,$.success,e-n)}catch(e){let r=u3.Unexpected;this._hasExpectedError&&=(r=u3.Expected,!1),this.handleLobbyAdmitAndRejectFailure(`Failed to admit all participants from lobby`,e,t,n,c3.lobbyAdmitAll,r)}return{successCount:i,failureCount:a}}get participants(){return this._isLobbyEnabled?Array.from(this._participants.values()):(this.logger.warn(`Lobby is not enabled`),[])}getInLobbyParticipants(e){e.forEach((e=>{if(e.state===`InLobby`){let t=W2(e.identifier);this._participants.set(t,e)}}))}removeAllLobbyParticipants(){if(this._participants.size===0)return;let e=Array.from(this._participants.values());this._participants.clear(),this.logger.info(`All participants are removed from lobby`),this._eventEmitter.emit(`lobbyParticipantsUpdated`,{added:[],removed:e})}removeLobbyParticipant(e){let t=W2(e.identifier);this._participants.has(t)&&(this.logger.info(`${wG(e.identifier).kind} is removed from lobby`),this._participants.delete(t),this._eventEmitter.emit(`lobbyParticipantsUpdated`,{added:[],removed:[e]}))}addLobbyParticipant(e){let t=W2(e.identifier);this._participants.has(t)||(this.logger.info(`${wG(e.identifier).kind} is added to lobby`),this._participants.set(t,e),this._eventEmitter.emit(`lobbyParticipantsUpdated`,{added:[e],removed:[]}))}validateLobbyOperation(e){let t=this._tsCall.conversationType?this._tsCall.conversationType:`oneToOneCall`;if(this.logger.info(`Current conversation type is: `,t),!this._lobbySupportedConversationTypes.find((e=>e===t)))throw this._hasExpectedError=!0,new Y({defaultError:J.LOBBY.CONV_UNSUPPORTED});if(e){let t=this._call.remoteParticipants.find((t=>W2(t.identifier)===W2(e)));if(t&&t.state===`Connected`)throw this._hasExpectedError=!0,new Y({defaultError:J.LOBBY.ALREADY_IN_MEETING,defaultErrorMessageArgs:[wG(e).kind]});if(t&&t.state!==`InLobby`||!t)throw this._hasExpectedError=!0,new Y({defaultError:J.LOBBY.NOT_IN_LOBBY,defaultErrorMessageArgs:[wG(e).kind]})}if(this._call.role!==L2.Presenter&&this._call.role!==L2.Organizer&&this._call.role!==L2.Coorganizer)throw this._hasExpectedError=!0,new Y({defaultError:J.LOBBY.UNAUTHORIZED_ADMIT_REJECT})}handleLobbyAdmitAndRejectFailure(e,t,n,r,i,a){let o=+new Date,s=rDe(this.logger,t,e);throw this._sendLobbyAdmitAndRejectUsage(s.message,i,n,$.failure,o-r,a,t),s}_sendLobbyAdmitAndRejectUsage(e,t,n,r,i,a,o){r===$.failure?this.logger.error(e):this.logger.info(e),this.sendLobbyAdmitAndRejectEvent({eventName:Q.acs_calling_lobby_events,callId:this._call.id,localParticipantId:this._tsCall.participantId,correlationId:n,kindOfEvent:r,operation:t,isExpected:a??``,timestampInfo:i?{deltaTimeInMs:i}:``,additionalDetails:o?{failureReason:o.message,code:o.code,subCode:o.subCode,...K3(o)}:``})}sendLobbyAdmitAndRejectEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:d2,properties:e})}catch{this.logger.debug(`Unable to send lobby admit and reject telemetry`)}}};function yIe(){let e=window.navigator.mediaDevices;if(e?.isRemote){let t=e?.MSRDC_MMR_Shim?.remoteObjectManager?.isConnected;if(!0===t)return`connected`;if(!1===t)return`disconnected`}return``}function r7(){let e=window.navigator.mediaDevices,t={isMMREnabled:e?.isRemote??!1};return t.isMMREnabled&&(e?.mmrClientVersion&&(t.mmrClientVersion=e.mmrClientVersion),e?.mmrExtensionVersion&&(t.mmrExtensionVersion=e.mmrExtensionVersion),e?.mmrHostVersion&&(t.mmrHostVersion=e.mmrHostVersion),e?.activityId&&(t.mmrActivityId=e.activityId),e?.connectionId&&(t.mmrConnectionId=e.connectionId),t.mmrRdpState=yIe()),t}e7([zG,t7(`design:type`,Object)],n7.prototype,`logger`,void 0),e7([GG(o4.LobbyAdmitParticipant),t7(`design:type`,Function),t7(`design:paramtypes`,[Object,Object]),t7(`design:returntype`,Promise)],n7.prototype,`admit`,null),e7([GG(o4.LobbyRejectParticipant),t7(`design:type`,Function),t7(`design:paramtypes`,[Object,Object]),t7(`design:returntype`,Promise)],n7.prototype,`reject`,null),e7([GG(o4.LobbyAdmitAll),t7(`design:type`,Function),t7(`design:paramtypes`,[Object]),t7(`design:returntype`,Promise)],n7.prototype,`admitAll`,null);var bIe=class{constructor(e){this._lastState=``,this._callback=e=>{let t=e?.detail?.state??``;t?t!==this._lastState&&(this._logger.info(`connection state is ${t}`),this._eventEmitter.emit(`stateChange`,t),this._lastState=t):this._logger.info(`connection state is unknown`)},this._logger=e.createChild(`MmrRdpConnectionManager`),this._eventEmitter=new w3.EventEmitter;let t=window.navigator.mediaDevices;t?.isRemote&&(t?.addEventListener(`rdpClientConnectionStateChanged`,this._callback),this._logger.info(`listener registered`))}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}get state(){return yIe()}dispose(){let e=window.navigator.mediaDevices;e?.isRemote&&(e?.removeEventListener(`rdpClientConnectionStateChanged`,this._callback),this._logger.info(`event listener unregistered`)),this._eventEmitter.removeAllListeners()}},xIe=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},a7=class extends g8{constructor(e,t,n,r,i,a,o){let s=i.id;super(e,t,n,s,a,`RemoteVideoStream`),this._remoteParticipantIdentifier=o,this._isAvailable=!1,this.setIsAvailable=e=>{e!==this._isAvailable&&(this._isAvailable=!!e,this.logger.log(`isAvailable changed to ${this._isAvailable}`),this._eventEmitter.emit(`isAvailableChanged`,this._isAvailable),this.call.isHandlingLargeMeetingVideoRendering&&this.call.handleDominantSpeakersVideos(),super.sendRemoteVideoStreamTelemetry())};let c=()=>{if(this.mediaStreamType===`Video`&&n.isHandlingLargeMeetingVideoRendering){for(let e of n.getTopNDominantSpeakersWithVideoOn())if(this.tsStream.isAvailable&&W2(e.identifier)===W2(this._remoteParticipantIdentifier))return void this.setIsAvailable(!0);this.setIsAvailable(!1)}else i.state===7?this.setIsAvailable(!1):(i.state===3&&l.dispose(),this.setIsAvailable(this.tsStream.isAvailable))};this._streamChangedHandler=this.tsStream.changed((()=>{c()}));let l=i.changed((()=>{c()}));c()}on(e,t){if(e!==`isAvailableChanged`&&e!==`sizeChanged`&&e!==`isReceivingChanged`)throw new Y({defaultError:J.REMOTE_VIDEO_STREAM.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if(e!==`isAvailableChanged`&&e!==`sizeChanged`&&e!==`isReceivingChanged`)throw new Y({defaultError:J.REMOTE_VIDEO_STREAM.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}get isAvailable(){return this._isAvailable}async getMediaStream(){let e=K0(),t=+new Date,n=this.tsStream.negotiationTag??``,r={correlationId:e,additionalDetails:{remoteStreamMetadata:this.getStreamMetadata(),mediaSourceId:this.tsStream.mediaSourceId,negotiationTag:n},operation:_3.getMediaStream,mediaType:this.getMediaType(),streamType:g3.Remote,timestampInfo:{attemptTimestamp:t},kindOfEvent:$.attempt,localParticipantId:this.call.tsCall.participantId,callId:this.call.id};this.sendMediaStreamEvent(r);try{if(!this.tsStream.getRawStream)throw new Y({defaultError:J.REMOTE_VIDEO_STREAM.GET_RAW_MEDIA_STREAM});if(!this.tsStream.isAvailable)throw new Y({defaultError:J.REMOTE_VIDEO_STREAM.RAWMEDIA_LVS_NOT_AVAILABLE});let r=this.tsStream.getRawStream(),i=await new Promise((async(e,t)=>{let n=setTimeout((()=>{i.dispose(),t(new Y({defaultError:J.REMOTE_VIDEO_STREAM.SUBSCRIBE_MEDIA_STREAM_TIMEOUT}))}),Z().rendering.remoteVideo.getMediaStreamTimeout),i=r.changed((()=>{a()})),a=async()=>{try{let t=await r.getMediaStream();if(!t)return void this.logger.warn(`MediaStream is not yet ready.`);clearTimeout(n),i.dispose(),e(t)}catch(e){this.logger.warn(`MediaStream is not yet ready, error=${e?.message||`unknown`}`)}};a()})),a=i.getVideoTracks()[0];if(!a)throw new Y({defaultError:J.REMOTE_VIDEO_STREAM.GET_TRACK});await new Promise(((e,t)=>{let n=()=>{a.removeEventListener(`unmute`,n,!1),e()};a.addEventListener(`unmute`,n,!1),a.muted?setTimeout((()=>{a.removeEventListener(`unmute`,n,!1),t(new Y({defaultError:J.REMOTE_VIDEO_STREAM.TRACK_UNMUTED_TIMEOUT}))}),Z().rendering.remoteVideo.getMediaStreamTimeout):n()}));let o={correlationId:e,additionalDetails:{remoteStreamMetadata:this.getStreamMetadata(),mediaSourceId:this.tsStream.mediaSourceId,negotiationTag:n},operation:_3.getMediaStream,mediaType:this.getMediaType(),streamType:g3.Remote,timestampInfo:{deltaTimeInMs:+new Date-t},kindOfEvent:$.success,localParticipantId:this.call.tsCall.participantId,callId:this.call.id};return this.sendMediaStreamEvent(o),i}catch(r){let i={correlationId:e,operation:_3.getMediaStream,mediaType:this.getMediaType(),streamType:g3.Remote,additionalDetails:{failureReason:r?.message||``,code:r.code||IG,...K3(r),remoteStreamMetadata:this.getStreamMetadata(),mediaSourceId:this.tsStream.mediaSourceId,negotiationTag:n},timestampInfo:{deltaTimeInMs:+new Date-t},kindOfEvent:$.failure,localParticipantId:this.call.tsCall.participantId,callId:this.call.id};throw this.sendMediaStreamEvent(i),new Y({defaultError:J.REMOTE_VIDEO_STREAM.GET_MEDIA_STREAM,originalError:r})}}getStreamMetadata(){return{callId:this.call?.id,streamType:this.mediaStreamType,localParticipantId:this.call.tsCall.participantId,remoteParticipantId:this.remoteParticipantId,sourceId:this.id,source:`remote`,rank:this.tsStream.rank,isAvailable:this.tsStream.isAvailable,acsIsAvailable:this._isAvailable,isReceiving:this._isReceiving,isStreaming:this.tsStream.isStreaming,viewIdsRegistered:this._renderers.map((e=>e.viewId)).join(`, `),height:this._size.height,width:this._size.width,isDisposed:this._disposed,optimalVideoCount:this.call?.tsCall.optimalVideoCount||1,currentNumberOfVideosRendered:this.call?.activeRemoteVideoStreamViews?.size||0}}dispose(){this.setIsAvailable(!1),super.dispose()}getMediaType(){return this.mediaStreamType===`ScreenSharing`?h3.ScreenSharingRaw:h3.VideoRaw}sendMediaStreamEvent(e){this.telemetryLogManager.sendEvent({name:Q.acs_calling_media_stream,tenant:d2,properties:{timestampInfo:e.timestampInfo,correlationId:e.correlationId,additionalDetails:e.additionalDetails||``,kindOfEvent:e.kindOfEvent||``,mediaType:e.mediaType,streamType:e.streamType,operation:e.operation,localParticipantId:e.localParticipantId||``,callId:e.callId||``}})}};xIe([GG(Awe.GetMediaStream),i7(`design:type`,Function),i7(`design:paramtypes`,[]),i7(`design:returntype`,Promise)],a7.prototype,`getMediaStream`,null);var o7={2:`#050505`,4:`#0a0a0a`,6:`#0f0f0f`,8:`#141414`,10:`#1a1a1a`,12:`#1f1f1f`,14:`#242424`,16:`#292929`,18:`#2e2e2e`,20:`#333333`,22:`#383838`,24:`#3d3d3d`,26:`#424242`,28:`#474747`,30:`#4d4d4d`,32:`#525252`,34:`#575757`,36:`#5c5c5c`,38:`#616161`,40:`#666666`,42:`#6b6b6b`,44:`#707070`,46:`#757575`,48:`#7a7a7a`,50:`#808080`,52:`#858585`,54:`#8a8a8a`,56:`#8f8f8f`,58:`#949494`,60:`#999999`,62:`#9e9e9e`,64:`#a3a3a3`,66:`#a8a8a8`,68:`#adadad`,70:`#b3b3b3`,72:`#b8b8b8`,74:`#bdbdbd`,76:`#c2c2c2`,78:`#c7c7c7`,80:`#cccccc`,82:`#d1d1d1`,84:`#d6d6d6`,86:`#dbdbdb`,88:`#e0e0e0`,90:`#e6e6e6`,92:`#ebebeb`,94:`#f0f0f0`,96:`#f5f5f5`,98:`#fafafa`},s7={5:`rgba(255, 255, 255, 0.05)`,10:`rgba(255, 255, 255, 0.1)`,20:`rgba(255, 255, 255, 0.2)`,30:`rgba(255, 255, 255, 0.3)`,40:`rgba(255, 255, 255, 0.4)`,50:`rgba(255, 255, 255, 0.5)`,60:`rgba(255, 255, 255, 0.6)`,70:`rgba(255, 255, 255, 0.7)`,80:`rgba(255, 255, 255, 0.8)`,90:`rgba(255, 255, 255, 0.9)`},c7={5:`rgba(0, 0, 0, 0.05)`,10:`rgba(0, 0, 0, 0.1)`,20:`rgba(0, 0, 0, 0.2)`,30:`rgba(0, 0, 0, 0.3)`,40:`rgba(0, 0, 0, 0.4)`,50:`rgba(0, 0, 0, 0.5)`,60:`rgba(0, 0, 0, 0.6)`,70:`rgba(0, 0, 0, 0.7)`,80:`rgba(0, 0, 0, 0.8)`,90:`rgba(0, 0, 0, 0.9)`},l7=`#ffffff`,SIe=`#000000`,CIe={shade50:`#200205`,shade40:`#3b0509`,shade30:`#6e0811`,shade20:`#960b18`,shade10:`#b10e1c`,primary:`#c50f1f`,tint10:`#cc2635`,tint20:`#d33f4c`,tint30:`#dc626d`,tint40:`#eeacb2`,tint50:`#f6d1d5`,tint60:`#fdf3f4`},wIe={shade50:`#031403`,shade40:`#052505`,shade30:`#094509`,shade20:`#0c5e0c`,shade10:`#0e700e`,primary:`#107c10`,tint10:`#218c21`,tint20:`#359b35`,tint30:`#54b054`,tint40:`#9fd89f`,tint50:`#c9eac9`,tint60:`#f1faf1`},u7={red:{shade50:`#210809`,shade40:`#3f1011`,shade30:`#751d1f`,shade20:`#9f282b`,shade10:`#bc2f32`,primary:`#d13438`,tint10:`#d7494c`,tint20:`#dc5e62`,tint30:`#e37d80`,tint40:`#f1bbbc`,tint50:`#f8dadb`,tint60:`#fdf6f6`},green:wIe,darkOrange:{shade50:`#230900`,shade40:`#411200`,shade30:`#7a2101`,shade20:`#a62d01`,shade10:`#c43501`,primary:`#da3b01`,tint10:`#de501c`,tint20:`#e36537`,tint30:`#e9835e`,tint40:`#f4bfab`,tint50:`#f9dcd1`,tint60:`#fdf6f3`},yellow:{shade50:`#282400`,shade40:`#4c4400`,shade30:`#817400`,shade20:`#c0ad00`,shade10:`#e4cc00`,primary:`#fde300`,tint10:`#fde61e`,tint20:`#fdea3d`,tint30:`#feee66`,tint40:`#fef7b2`,tint50:`#fffad6`,tint60:`#fffef5`},berry:{shade50:`#1f091d`,shade40:`#3a1136`,shade30:`#6d2064`,shade20:`#932b88`,shade10:`#af33a1`,primary:`#c239b3`,tint10:`#c94cbc`,tint20:`#d161c4`,tint30:`#da7ed0`,tint40:`#edbbe7`,tint50:`#f5daf2`,tint60:`#fdf5fc`},lightGreen:{shade50:`#031a02`,shade40:`#063004`,shade30:`#0b5a08`,shade20:`#0e7a0b`,shade10:`#11910d`,primary:`#13a10e`,tint10:`#27ac22`,tint20:`#3db838`,tint30:`#5ec75a`,tint40:`#a7e3a5`,tint50:`#cef0cd`,tint60:`#f2fbf2`},marigold:{shade50:`#251a00`,shade40:`#463100`,shade30:`#835b00`,shade20:`#b27c00`,shade10:`#d39300`,primary:`#eaa300`,tint10:`#edad1c`,tint20:`#efb839`,tint30:`#f2c661`,tint40:`#f9e2ae`,tint50:`#fcefd3`,tint60:`#fefbf4`}},d7={darkRed:{shade50:`#130204`,shade40:`#230308`,shade30:`#420610`,shade20:`#590815`,shade10:`#690a19`,primary:`#750b1c`,tint10:`#861b2c`,tint20:`#962f3f`,tint30:`#ac4f5e`,tint40:`#d69ca5`,tint50:`#e9c7cd`,tint60:`#f9f0f2`},cranberry:CIe,pumpkin:{shade50:`#200d03`,shade40:`#3d1805`,shade30:`#712d09`,shade20:`#9a3d0c`,shade10:`#b6480e`,primary:`#ca5010`,tint10:`#d06228`,tint20:`#d77440`,tint30:`#df8e64`,tint40:`#efc4ad`,tint50:`#f7dfd2`,tint60:`#fdf7f4`},peach:{shade50:`#291600`,shade40:`#4d2a00`,shade30:`#8f4e00`,shade20:`#c26a00`,shade10:`#e67e00`,primary:`#ff8c00`,tint10:`#ff9a1f`,tint20:`#ffa83d`,tint30:`#ffba66`,tint40:`#ffddb3`,tint50:`#ffedd6`,tint60:`#fffaf5`},gold:{shade50:`#1f1900`,shade40:`#3a2f00`,shade30:`#6c5700`,shade20:`#937700`,shade10:`#ae8c00`,primary:`#c19c00`,tint10:`#c8a718`,tint20:`#d0b232`,tint30:`#dac157`,tint40:`#ecdfa5`,tint50:`#f5eece`,tint60:`#fdfbf2`},brass:{shade50:`#181202`,shade40:`#2e2103`,shade30:`#553e06`,shade20:`#745408`,shade10:`#89640a`,primary:`#986f0b`,tint10:`#a47d1e`,tint20:`#b18c34`,tint30:`#c1a256`,tint40:`#e0cea2`,tint50:`#efe4cb`,tint60:`#fbf8f2`},brown:{shade50:`#170e07`,shade40:`#2b1a0e`,shade30:`#50301a`,shade20:`#6c4123`,shade10:`#804d29`,primary:`#8e562e`,tint10:`#9c663f`,tint20:`#a97652`,tint30:`#bb8f6f`,tint40:`#ddc3b0`,tint50:`#edded3`,tint60:`#faf7f4`},forest:{shade50:`#0c1501`,shade40:`#162702`,shade30:`#294903`,shade20:`#376304`,shade10:`#427505`,primary:`#498205`,tint10:`#599116`,tint20:`#6ba02b`,tint30:`#85b44c`,tint40:`#bdd99b`,tint50:`#dbebc7`,tint60:`#f6faf0`},seafoam:{shade50:`#002111`,shade40:`#003d20`,shade30:`#00723b`,shade20:`#009b51`,shade10:`#00b85f`,primary:`#00cc6a`,tint10:`#19d279`,tint20:`#34d889`,tint30:`#5ae0a0`,tint40:`#a8f0cd`,tint50:`#cff7e4`,tint60:`#f3fdf8`},darkGreen:{shade50:`#021102`,shade40:`#032003`,shade30:`#063b06`,shade20:`#085108`,shade10:`#0a5f0a`,primary:`#0b6a0b`,tint10:`#1a7c1a`,tint20:`#2d8e2d`,tint30:`#4da64d`,tint40:`#9ad29a`,tint50:`#c6e7c6`,tint60:`#f0f9f0`},lightTeal:{shade50:`#001d1f`,shade40:`#00373a`,shade30:`#00666d`,shade20:`#008b94`,shade10:`#00a5af`,primary:`#00b7c3`,tint10:`#18bfca`,tint20:`#32c8d1`,tint30:`#58d3db`,tint40:`#a6e9ed`,tint50:`#cef3f5`,tint60:`#f2fcfd`},teal:{shade50:`#001516`,shade40:`#012728`,shade30:`#02494c`,shade20:`#026467`,shade10:`#037679`,primary:`#038387`,tint10:`#159195`,tint20:`#2aa0a4`,tint30:`#4cb4b7`,tint40:`#9bd9db`,tint50:`#c7ebec`,tint60:`#f0fafa`},steel:{shade50:`#000f12`,shade40:`#001b22`,shade30:`#00333f`,shade20:`#004555`,shade10:`#005265`,primary:`#005b70`,tint10:`#0f6c81`,tint20:`#237d92`,tint30:`#4496a9`,tint40:`#94c8d4`,tint50:`#c3e1e8`,tint60:`#eff7f9`},blue:{shade50:`#001322`,shade40:`#002440`,shade30:`#004377`,shade20:`#005ba1`,shade10:`#006cbf`,primary:`#0078d4`,tint10:`#1a86d9`,tint20:`#3595de`,tint30:`#5caae5`,tint40:`#a9d3f2`,tint50:`#d0e7f8`,tint60:`#f3f9fd`},royalBlue:{shade50:`#000c16`,shade40:`#00172a`,shade30:`#002c4e`,shade20:`#003b6a`,shade10:`#00467e`,primary:`#004e8c`,tint10:`#125e9a`,tint20:`#286fa8`,tint30:`#4a89ba`,tint40:`#9abfdc`,tint50:`#c7dced`,tint60:`#f0f6fa`},cornflower:{shade50:`#0d1126`,shade40:`#182047`,shade30:`#2c3c85`,shade20:`#3c51b4`,shade10:`#4760d5`,primary:`#4f6bed`,tint10:`#637cef`,tint20:`#778df1`,tint30:`#93a4f4`,tint40:`#c8d1fa`,tint50:`#e1e6fc`,tint60:`#f7f9fe`},navy:{shade50:`#00061d`,shade40:`#000c36`,shade30:`#001665`,shade20:`#001e89`,shade10:`#0023a2`,primary:`#0027b4`,tint10:`#173bbd`,tint20:`#3050c6`,tint30:`#546fd2`,tint40:`#a3b2e8`,tint50:`#ccd5f3`,tint60:`#f2f4fc`},lavender:{shade50:`#120f25`,shade40:`#221d46`,shade30:`#3f3682`,shade20:`#5649b0`,shade10:`#6656d1`,primary:`#7160e8`,tint10:`#8172eb`,tint20:`#9184ee`,tint30:`#a79cf1`,tint40:`#d2ccf8`,tint50:`#e7e4fb`,tint60:`#f9f8fe`},purple:{shade50:`#0f0717`,shade40:`#1c0e2b`,shade30:`#341a51`,shade20:`#46236e`,shade10:`#532982`,primary:`#5c2e91`,tint10:`#6b3f9e`,tint20:`#7c52ab`,tint30:`#9470bd`,tint40:`#c6b1de`,tint50:`#e0d3ed`,tint60:`#f7f4fb`},grape:{shade50:`#160418`,shade40:`#29072e`,shade30:`#4c0d55`,shade20:`#671174`,shade10:`#7a1589`,primary:`#881798`,tint10:`#952aa4`,tint20:`#a33fb1`,tint30:`#b55fc1`,tint40:`#d9a7e0`,tint50:`#eaceef`,tint60:`#faf2fb`},lilac:{shade50:`#1c0b1f`,shade40:`#35153a`,shade30:`#63276d`,shade20:`#863593`,shade10:`#9f3faf`,primary:`#b146c2`,tint10:`#ba58c9`,tint20:`#c36bd1`,tint30:`#cf87da`,tint40:`#e6bfed`,tint50:`#f2dcf5`,tint60:`#fcf6fd`},pink:{shade50:`#24091b`,shade40:`#441232`,shade30:`#80215d`,shade20:`#ad2d7e`,shade10:`#cd3595`,primary:`#e43ba6`,tint10:`#e750b0`,tint20:`#ea66ba`,tint30:`#ef85c8`,tint40:`#f7c0e3`,tint50:`#fbddf0`,tint60:`#fef6fb`},magenta:{shade50:`#1f0013`,shade40:`#390024`,shade30:`#6b0043`,shade20:`#91005a`,shade10:`#ac006b`,primary:`#bf0077`,tint10:`#c71885`,tint20:`#ce3293`,tint30:`#d957a8`,tint40:`#eca5d1`,tint50:`#f5cee6`,tint60:`#fcf2f9`},plum:{shade50:`#13000c`,shade40:`#240017`,shade30:`#43002b`,shade20:`#5a003b`,shade10:`#6b0045`,primary:`#77004d`,tint10:`#87105d`,tint20:`#98246f`,tint30:`#ad4589`,tint40:`#d696c0`,tint50:`#e9c4dc`,tint60:`#faf0f6`},beige:{shade50:`#141313`,shade40:`#252323`,shade30:`#444241`,shade20:`#5d5958`,shade10:`#6e6968`,primary:`#7a7574`,tint10:`#8a8584`,tint20:`#9a9594`,tint30:`#afabaa`,tint40:`#d7d4d4`,tint50:`#eae8e8`,tint60:`#faf9f9`},mink:{shade50:`#0f0e0e`,shade40:`#1c1b1a`,shade30:`#343231`,shade20:`#474443`,shade10:`#54514f`,primary:`#5d5a58`,tint10:`#706d6b`,tint20:`#84817e`,tint30:`#9e9b99`,tint40:`#cecccb`,tint50:`#e5e4e3`,tint60:`#f8f8f8`},platinum:{shade50:`#111314`,shade40:`#1f2426`,shade30:`#3b4447`,shade20:`#505c60`,shade10:`#5f6d71`,primary:`#69797e`,tint10:`#79898d`,tint20:`#89989d`,tint30:`#a0adb2`,tint40:`#cdd6d8`,tint50:`#e4e9ea`,tint60:`#f8f9fa`},anchor:{shade50:`#090a0b`,shade40:`#111315`,shade30:`#202427`,shade20:`#2b3135`,shade10:`#333a3f`,primary:`#394146`,tint10:`#4d565c`,tint20:`#626c72`,tint30:`#808a90`,tint40:`#bcc3c7`,tint50:`#dbdfe1`,tint60:`#f6f7f8`}},f7={cranberry:CIe,green:wIe,orange:{shade50:`#271002`,shade40:`#4a1e04`,shade30:`#8a3707`,shade20:`#bc4b09`,shade10:`#de590b`,primary:`#f7630c`,tint10:`#f87528`,tint20:`#f98845`,tint30:`#faa06b`,tint40:`#fdcfb4`,tint50:`#fee5d7`,tint60:`#fff9f5`}},TIe=`darkRed.cranberry.pumpkin.peach.gold.brass.brown.forest.seafoam.darkGreen.lightTeal.teal.steel.blue.royalBlue.cornflower.navy.lavender.purple.grape.lilac.pink.magenta.plum.beige.mink.platinum.anchor`.split(`.`),p7={success:`green`,warning:`orange`,danger:`cranberry`},m7=[`red`,`green`,`darkOrange`,`yellow`,`berry`,`lightGreen`,`marigold`].reduce(((e,t)=>{let n=t.slice(0,1).toUpperCase()+t.slice(1),r={[`colorPalette${n}Background1`]:u7[t].tint60,[`colorPalette${n}Background2`]:u7[t].tint40,[`colorPalette${n}Background3`]:u7[t].primary,[`colorPalette${n}Foreground1`]:u7[t].shade10,[`colorPalette${n}Foreground2`]:u7[t].shade30,[`colorPalette${n}Foreground3`]:u7[t].primary,[`colorPalette${n}BorderActive`]:u7[t].primary,[`colorPalette${n}Border1`]:u7[t].tint40,[`colorPalette${n}Border2`]:u7[t].primary};return Object.assign(e,r)}),{});m7.colorPaletteYellowForeground1=u7.yellow.shade30,m7.colorPaletteRedForegroundInverted=u7.red.tint20,m7.colorPaletteGreenForegroundInverted=u7.green.tint20,m7.colorPaletteYellowForegroundInverted=u7.yellow.tint40;var EIe=TIe.reduce(((e,t)=>{let n=t.slice(0,1).toUpperCase()+t.slice(1),r={[`colorPalette${n}Background2`]:d7[t].tint40,[`colorPalette${n}Foreground2`]:d7[t].shade30,[`colorPalette${n}BorderActive`]:d7[t].primary};return Object.assign(e,r)}),{}),DIe={...m7,...EIe},h7=Object.entries(p7).reduce(((e,[t,n])=>{let r=t.slice(0,1).toUpperCase()+t.slice(1),i={[`colorStatus${r}Background1`]:f7[n].tint60,[`colorStatus${r}Background2`]:f7[n].tint40,[`colorStatus${r}Background3`]:f7[n].primary,[`colorStatus${r}Foreground1`]:f7[n].shade10,[`colorStatus${r}Foreground2`]:f7[n].shade30,[`colorStatus${r}Foreground3`]:f7[n].primary,[`colorStatus${r}ForegroundInverted`]:f7[n].tint30,[`colorStatus${r}BorderActive`]:f7[n].primary,[`colorStatus${r}Border1`]:f7[n].tint40,[`colorStatus${r}Border2`]:f7[n].primary};return Object.assign(e,i)}),{});h7.colorStatusDangerBackground3Hover=f7[p7.danger].shade10,h7.colorStatusDangerBackground3Pressed=f7[p7.danger].shade20,h7.colorStatusWarningForeground1=f7[p7.warning].shade20,h7.colorStatusWarningForeground3=f7[p7.warning].shade20,h7.colorStatusWarningBorder2=f7[p7.warning].shade20;var OIe=e=>({colorNeutralForeground1:o7[14],colorNeutralForeground1Hover:o7[14],colorNeutralForeground1Pressed:o7[14],colorNeutralForeground1Selected:o7[14],colorNeutralForeground2:o7[26],colorNeutralForeground2Hover:o7[14],colorNeutralForeground2Pressed:o7[14],colorNeutralForeground2Selected:o7[14],colorNeutralForeground2BrandHover:e[80],colorNeutralForeground2BrandPressed:e[70],colorNeutralForeground2BrandSelected:e[80],colorNeutralForeground3:o7[38],colorNeutralForeground3Hover:o7[26],colorNeutralForeground3Pressed:o7[26],colorNeutralForeground3Selected:o7[26],colorNeutralForeground3BrandHover:e[80],colorNeutralForeground3BrandPressed:e[70],colorNeutralForeground3BrandSelected:e[80],colorNeutralForeground4:o7[44],colorNeutralForegroundDisabled:o7[74],colorNeutralForegroundInvertedDisabled:s7[40],colorBrandForegroundLink:e[70],colorBrandForegroundLinkHover:e[60],colorBrandForegroundLinkPressed:e[40],colorBrandForegroundLinkSelected:e[70],colorNeutralForeground2Link:o7[26],colorNeutralForeground2LinkHover:o7[14],colorNeutralForeground2LinkPressed:o7[14],colorNeutralForeground2LinkSelected:o7[14],colorCompoundBrandForeground1:e[80],colorCompoundBrandForeground1Hover:e[70],colorCompoundBrandForeground1Pressed:e[60],colorBrandForeground1:e[80],colorBrandForeground2:e[70],colorBrandForeground2Hover:e[60],colorBrandForeground2Pressed:e[30],colorNeutralForeground1Static:o7[14],colorNeutralForegroundStaticInverted:l7,colorNeutralForegroundInverted:l7,colorNeutralForegroundInvertedHover:l7,colorNeutralForegroundInvertedPressed:l7,colorNeutralForegroundInvertedSelected:l7,colorNeutralForegroundInverted2:l7,colorNeutralForegroundOnBrand:l7,colorNeutralForegroundInvertedLink:l7,colorNeutralForegroundInvertedLinkHover:l7,colorNeutralForegroundInvertedLinkPressed:l7,colorNeutralForegroundInvertedLinkSelected:l7,colorBrandForegroundInverted:e[100],colorBrandForegroundInvertedHover:e[110],colorBrandForegroundInvertedPressed:e[100],colorBrandForegroundOnLight:e[80],colorBrandForegroundOnLightHover:e[70],colorBrandForegroundOnLightPressed:e[50],colorBrandForegroundOnLightSelected:e[60],colorNeutralBackground1:l7,colorNeutralBackground1Hover:o7[96],colorNeutralBackground1Pressed:o7[88],colorNeutralBackground1Selected:o7[92],colorNeutralBackground2:o7[98],colorNeutralBackground2Hover:o7[94],colorNeutralBackground2Pressed:o7[86],colorNeutralBackground2Selected:o7[90],colorNeutralBackground3:o7[96],colorNeutralBackground3Hover:o7[92],colorNeutralBackground3Pressed:o7[84],colorNeutralBackground3Selected:o7[88],colorNeutralBackground4:o7[94],colorNeutralBackground4Hover:o7[98],colorNeutralBackground4Pressed:o7[96],colorNeutralBackground4Selected:l7,colorNeutralBackground5:o7[92],colorNeutralBackground5Hover:o7[96],colorNeutralBackground5Pressed:o7[94],colorNeutralBackground5Selected:o7[98],colorNeutralBackground6:o7[90],colorNeutralBackgroundInverted:o7[16],colorNeutralBackgroundStatic:o7[20],colorNeutralBackgroundAlpha:s7[50],colorNeutralBackgroundAlpha2:s7[80],colorSubtleBackground:`transparent`,colorSubtleBackgroundHover:o7[96],colorSubtleBackgroundPressed:o7[88],colorSubtleBackgroundSelected:o7[92],colorSubtleBackgroundLightAlphaHover:s7[70],colorSubtleBackgroundLightAlphaPressed:s7[50],colorSubtleBackgroundLightAlphaSelected:`transparent`,colorSubtleBackgroundInverted:`transparent`,colorSubtleBackgroundInvertedHover:c7[10],colorSubtleBackgroundInvertedPressed:c7[30],colorSubtleBackgroundInvertedSelected:c7[20],colorTransparentBackground:`transparent`,colorTransparentBackgroundHover:`transparent`,colorTransparentBackgroundPressed:`transparent`,colorTransparentBackgroundSelected:`transparent`,colorNeutralBackgroundDisabled:o7[94],colorNeutralBackgroundInvertedDisabled:s7[10],colorNeutralStencil1:o7[90],colorNeutralStencil2:o7[98],colorNeutralStencil1Alpha:c7[10],colorNeutralStencil2Alpha:c7[5],colorBackgroundOverlay:c7[40],colorScrollbarOverlay:c7[50],colorBrandBackground:e[80],colorBrandBackgroundHover:e[70],colorBrandBackgroundPressed:e[40],colorBrandBackgroundSelected:e[60],colorCompoundBrandBackground:e[80],colorCompoundBrandBackgroundHover:e[70],colorCompoundBrandBackgroundPressed:e[60],colorBrandBackgroundStatic:e[80],colorBrandBackground2:e[160],colorBrandBackground2Hover:e[150],colorBrandBackground2Pressed:e[130],colorBrandBackground3Static:e[60],colorBrandBackground4Static:e[40],colorBrandBackgroundInverted:l7,colorBrandBackgroundInvertedHover:e[160],colorBrandBackgroundInvertedPressed:e[140],colorBrandBackgroundInvertedSelected:e[150],colorNeutralCardBackground:o7[98],colorNeutralCardBackgroundHover:l7,colorNeutralCardBackgroundPressed:o7[96],colorNeutralCardBackgroundSelected:o7[92],colorNeutralCardBackgroundDisabled:o7[94],colorNeutralStrokeAccessible:o7[38],colorNeutralStrokeAccessibleHover:o7[34],colorNeutralStrokeAccessiblePressed:o7[30],colorNeutralStrokeAccessibleSelected:e[80],colorNeutralStroke1:o7[82],colorNeutralStroke1Hover:o7[78],colorNeutralStroke1Pressed:o7[70],colorNeutralStroke1Selected:o7[74],colorNeutralStroke2:o7[88],colorNeutralStroke3:o7[94],colorNeutralStrokeSubtle:o7[88],colorNeutralStrokeOnBrand:l7,colorNeutralStrokeOnBrand2:l7,colorNeutralStrokeOnBrand2Hover:l7,colorNeutralStrokeOnBrand2Pressed:l7,colorNeutralStrokeOnBrand2Selected:l7,colorBrandStroke1:e[80],colorBrandStroke2:e[140],colorBrandStroke2Hover:e[120],colorBrandStroke2Pressed:e[80],colorBrandStroke2Contrast:e[140],colorCompoundBrandStroke:e[80],colorCompoundBrandStrokeHover:e[70],colorCompoundBrandStrokePressed:e[60],colorNeutralStrokeDisabled:o7[88],colorNeutralStrokeInvertedDisabled:s7[40],colorTransparentStroke:`transparent`,colorTransparentStrokeInteractive:`transparent`,colorTransparentStrokeDisabled:`transparent`,colorNeutralStrokeAlpha:c7[5],colorNeutralStrokeAlpha2:s7[20],colorStrokeFocus1:l7,colorStrokeFocus2:SIe,colorNeutralShadowAmbient:`rgba(0,0,0,0.12)`,colorNeutralShadowKey:`rgba(0,0,0,0.14)`,colorNeutralShadowAmbientLighter:`rgba(0,0,0,0.06)`,colorNeutralShadowKeyLighter:`rgba(0,0,0,0.07)`,colorNeutralShadowAmbientDarker:`rgba(0,0,0,0.20)`,colorNeutralShadowKeyDarker:`rgba(0,0,0,0.24)`,colorBrandShadowAmbient:`rgba(0,0,0,0.30)`,colorBrandShadowKey:`rgba(0,0,0,0.25)`}),kIe={borderRadiusNone:`0`,borderRadiusSmall:`2px`,borderRadiusMedium:`4px`,borderRadiusLarge:`6px`,borderRadiusXLarge:`8px`,borderRadiusCircular:`10000px`},AIe={curveAccelerateMax:`cubic-bezier(0.9,0.1,1,0.2)`,curveAccelerateMid:`cubic-bezier(1,0,1,1)`,curveAccelerateMin:`cubic-bezier(0.8,0,0.78,1)`,curveDecelerateMax:`cubic-bezier(0.1,0.9,0.2,1)`,curveDecelerateMid:`cubic-bezier(0,0,0,1)`,curveDecelerateMin:`cubic-bezier(0.33,0,0.1,1)`,curveEasyEaseMax:`cubic-bezier(0.8,0,0.2,1)`,curveEasyEase:`cubic-bezier(0.33,0,0.67,1)`,curveLinear:`cubic-bezier(0,0,1,1)`},jIe={durationUltraFast:`50ms`,durationFaster:`100ms`,durationFast:`150ms`,durationNormal:`200ms`,durationGentle:`250ms`,durationSlow:`300ms`,durationSlower:`400ms`,durationUltraSlow:`500ms`},MIe={fontSizeBase100:`10px`,fontSizeBase200:`12px`,fontSizeBase300:`14px`,fontSizeBase400:`16px`,fontSizeBase500:`20px`,fontSizeBase600:`24px`,fontSizeHero700:`28px`,fontSizeHero800:`32px`,fontSizeHero900:`40px`,fontSizeHero1000:`68px`},NIe={lineHeightBase100:`14px`,lineHeightBase200:`16px`,lineHeightBase300:`20px`,lineHeightBase400:`22px`,lineHeightBase500:`28px`,lineHeightBase600:`32px`,lineHeightHero700:`36px`,lineHeightHero800:`40px`,lineHeightHero900:`52px`,lineHeightHero1000:`92px`},PIe={fontWeightRegular:400,fontWeightMedium:500,fontWeightSemibold:600,fontWeightBold:700},FIe={fontFamilyBase:`'Segoe UI', 'Segoe UI Web (West European)', -apple-system, BlinkMacSystemFont, Roboto, 'Helvetica Neue', sans-serif`,fontFamilyMonospace:`Consolas, 'Courier New', Courier, monospace`,fontFamilyNumeric:`Bahnschrift, 'Segoe UI', 'Segoe UI Web (West European)', -apple-system, BlinkMacSystemFont, Roboto, 'Helvetica Neue', sans-serif`},g7={none:`0`,xxs:`2px`,xs:`4px`,sNudge:`6px`,s:`8px`,mNudge:`10px`,m:`12px`,l:`16px`,xl:`20px`,xxl:`24px`,xxxl:`32px`},IIe={spacingHorizontalNone:g7.none,spacingHorizontalXXS:g7.xxs,spacingHorizontalXS:g7.xs,spacingHorizontalSNudge:g7.sNudge,spacingHorizontalS:g7.s,spacingHorizontalMNudge:g7.mNudge,spacingHorizontalM:g7.m,spacingHorizontalL:g7.l,spacingHorizontalXL:g7.xl,spacingHorizontalXXL:g7.xxl,spacingHorizontalXXXL:g7.xxxl},LIe={spacingVerticalNone:g7.none,spacingVerticalXXS:g7.xxs,spacingVerticalXS:g7.xs,spacingVerticalSNudge:g7.sNudge,spacingVerticalS:g7.s,spacingVerticalMNudge:g7.mNudge,spacingVerticalM:g7.m,spacingVerticalL:g7.l,spacingVerticalXL:g7.xl,spacingVerticalXXL:g7.xxl,spacingVerticalXXXL:g7.xxxl},RIe={strokeWidthThin:`1px`,strokeWidthThick:`2px`,strokeWidthThicker:`3px`,strokeWidthThickest:`4px`};function zIe(e,t,n=``){return{[`shadow2${n}`]:`0 0 2px ${e}, 0 1px 2px ${t}`,[`shadow4${n}`]:`0 0 2px ${e}, 0 2px 4px ${t}`,[`shadow8${n}`]:`0 0 2px ${e}, 0 4px 8px ${t}`,[`shadow16${n}`]:`0 0 2px ${e}, 0 8px 16px ${t}`,[`shadow28${n}`]:`0 0 8px ${e}, 0 14px 28px ${t}`,[`shadow64${n}`]:`0 0 8px ${e}, 0 32px 64px ${t}`}}var BIe=(e=>{let t=OIe(e);return{...kIe,...MIe,...NIe,...FIe,...PIe,...RIe,...IIe,...LIe,...jIe,...AIe,...t,...DIe,...h7,...zIe(t.colorNeutralShadowAmbient,t.colorNeutralShadowKey),...zIe(t.colorBrandShadowAmbient,t.colorBrandShadowKey,`Brand`)}})({10:`#061724`,20:`#082338`,30:`#0a2e4a`,40:`#0c3b5e`,50:`#0e4775`,60:`#0f548c`,70:`#115ea3`,80:`#0f6cbd`,90:`#2886de`,100:`#479ef5`,110:`#62abf5`,120:`#77b7f7`,130:`#96c6fa`,140:`#b4d6fa`,150:`#cfe4fa`,160:`#ebf3fc`}),VIe=1,HIe=class{constructor(e,t,n,r,i){this._container=e,this._videoStream=t,this._viewId=n,this._streamTelemetryEventSender=i,this._watermarkCapability=null,this.WATERMARK_TEXT_COMMON_STYLES={fontFamily:BIe.fontFamilyBase,fontWeight:`bold`,stroke:`black`,strokeOpacity:`0.1`,fill:BIe.colorNeutralStrokeOnBrand2},this.WATERMARK_CONTAINER_STYLES={position:`absolute`,pointerEvents:`none`,width:`100%`,height:`100%`,top:`0`,left:`0`},this.TEXT_ROTATION=30,this.SHADOW_OPACITY_RATIO=3,this.RANGE_MAX=100,this.BORDER_SIZE=18,this.BORDER_SIZE_FRAC=1/this.BORDER_SIZE,this.SPACE_USE=.9,this.MAX_BORDER=2,this.SINGLE_PATTERN_FONT_SIZE_FACTOR=.07,this._svgContainerHidden=``,this._svgWatermarkUseTextScale=0,this._svgWatermarkUseTextBorderSize=0,this._svgTextTiledScaledSize=0,this._svgTextTiledScaledStrokeWidth=0,this._svgFirstPatternWidth=0,this._svgFirstPatternHeight=0,this._svgSecondPatternWidth=0,this._svgSecondPatternHeight=0,this._svgSecondPatternOffsetX=0,this._svgSecondPatternOffsetY=0,this._computeTextDiagonal=wwe(this.TEXT_ROTATION),this._isApple=!1,this._getScaledPatternDimensions=(e,t,n,r)=>({width:e*(n+1.1),height:t*(r+1.1)}),this._call=this._videoStream.call,this._logger=r.createChild(`WatermarkOverlayProvider`+ VIe++);let a=this._call.getMeetingCapabilitiesInternal();if(!a){this._logger.warn(`No watermark capabilities found. Likely not received from service.`);let e=new Y({defaultError:J.VIEW.NO_WATERMARK_CAPABILITY_RECEIVED}),t=K0();this._streamTelemetryEventSender.sendMediaStreamEvent({correlationId:t,callId:this._call.id,timestampInfo:{attemptTimestamp:Date.now()},operation:_3.watermark,kindOfEvent:$.failure,mediaType:this._videoStream.mediaStreamType,streamType:g3.Remote,additionalDetails:{failureReason:e.message,code:e.code,...K3(e),watermark:{...this._getWatermarkUsageTelemetryPayload()}}});return}this._watermarkCapability=a.waterMarkCapability;let o=this._call.deviceManager.getOSNameInternal();this._isApple=o===`ios`||o===`mac`,this._resizeObserver=new ResizeObserver((e=>{for(let t of e)if(t.contentRect?.width>1){let e=t.contentRect.width,n=t.contentRect.height;this._updateWatermarkScalingValues(e,n)}})),this._resizeObserver.observe(this._container)}attach(){let e=K0(),t=Date.now();try{if(!this._watermarkCapability)return void this._logger.warn(`No watermark capabilities found. No-op.`);if(this._videoStream.mediaStreamType!==`Video`&&this._videoStream.mediaStreamType!==`ScreenSharing`)throw Error(`Unsupported media type for watermark`);this._watermarkIsReceivingSub=()=>{this._videoStream.isReceiving&&(this._generateWatermark(this._videoStream.mediaStreamType,e),this._updateWatermarkScalingValues(this._container.getBoundingClientRect().width,this._container.getBoundingClientRect().height))},this._videoStream.on(`isReceivingChanged`,this._watermarkIsReceivingSub)}catch(n){let r=new Y({defaultError:J.VIEW.WATERMARK_ATTACH_FAIL,originalError:n});throw this._streamTelemetryEventSender.sendMediaStreamEvent({correlationId:e,callId:this._call.id,timestampInfo:{deltaTimeInMs:Date.now()-t},operation:_3.watermark,kindOfEvent:$.failure,mediaType:this._videoStream.mediaStreamType,streamType:g3.Remote,additionalDetails:{failureReason:r.message,code:r.code,...K3(r),watermark:{...this._getWatermarkUsageTelemetryPayload()}}}),r}}dispose(){this._resizeObserver&&this._resizeObserver.disconnect(),this._mutationObserver&&this._mutationObserver.disconnect(),this._audioOnlyCallback&&this._call.offWatermarkAudioOnlyFallbackTriggeredChanged(`watermarkAudioOnlyFallbackTriggeredChanged`,this._audioOnlyCallback),this._svgContainer&&(this._container.removeChild(this._svgContainer),this._svgContainer=void 0,this._svgContainerHidden=``),this._watermarkIsReceivingSub&&this._videoStream.off(`isReceivingChanged`,this._watermarkIsReceivingSub),this._logger.info(`watermark overlay provider disposed for viewid: ${this._viewId}`)}_updateWatermarkScalingValues(e,t){this._getSelectedWatermarkPattern()===`Single`?this._updateWatermarkUseTextScalingSingle(e,t):this._getSelectedWatermarkPattern()===`Tiled`&&this._updateWatermarkPatternScalingTiled(e,t)}_generateWatermark(e,t){let n=Date.now();try{if(!this._watermarkCapability)return void this._logger.warn(`No watermark capabilities found. No-op.`);if(this._call.watermarkAudioOnlyFallbackTriggered)return this._logger.warn(`Watermark audio only fallback was triggered, disposing remote stream`),void this._videoStream.dispose();let r;if(e===`Video`&&this._watermarkCapability.enabledForVideo)r=this._watermarkCapability.videoSettings;else{if(e!==`ScreenSharing`||!this._watermarkCapability.enabledForVbss)return void this._logger.info(`No watermark operations to be done on viewId: ${this._viewId}`);r=this._watermarkCapability.vbssSettings}if(this._streamTelemetryEventSender.sendMediaStreamEvent({correlationId:t,callId:this._call.id,timestampInfo:{attemptTimestamp:n},operation:_3.watermark,kindOfEvent:$.attempt,mediaType:this._videoStream.mediaStreamType,streamType:g3.Remote,additionalDetails:{watermark:{...this._getWatermarkUsageTelemetryPayload()}}}),!r||!r.opacity||!r.pattern||typeof r.opacity!=`number`||typeof r.pattern!=`string`)throw this._logger.debug(`Unexpected watermark settings`),new Y({defaultError:J.VIEW.WATERMARK_UNEXPECTED_VALUES});let i=this._getClampedUsername(),a;if(r.pattern===`Single`)a=this._generateSinglePatternWatermark(i,r);else{if(r.pattern!==`Tiled`)throw this._logger.debug(`Unexpected watermark pattern setting`),new Y({defaultError:J.VIEW.WATERMARK_UNEXPECTED_VALUES});a=this._generateTiledPatternWatermark(i,r)}this._svgContainerHidden=a.outerHTML,this._container.appendChild(a),this._audioOnlyCallback=()=>{this._call.watermarkAudioOnlyFallbackTriggered&&(this._logger.debug(`Watermark audio only fallback triggered by one of the renderers`),this._logger.debug(`Disposing remote stream with viewId ${this._viewId}`),this._videoStream.dispose(),this._streamTelemetryEventSender.sendMediaStreamEvent({correlationId:t,callId:this._call.id,timestampInfo:{attemptTimestamp:Date.now()},operation:_3.watermark,kindOfEvent:$.event,mediaType:this._videoStream.mediaStreamType,streamType:g3.Remote,additionalDetails:{watermark:{...this._getWatermarkUsageTelemetryPayload()}}}))},this._call.onWatermarkAudioOnlyFallbackTriggeredChanged(`watermarkAudioOnlyFallbackTriggeredChanged`,this._audioOnlyCallback),this._mutationObserver=new MutationObserver((e=>{this._svgContainer?.outerHTML!==this._svgContainerHidden&&(this._logger.debug(`watermark mutation detected, falling back to audio only!`),this._triggerAudioOnlyFallback(),this._streamTelemetryEventSender.sendMediaStreamEvent({correlationId:t,callId:this._call.id,timestampInfo:{attemptTimestamp:Date.now()},operation:_3.watermark,kindOfEvent:$.event,mediaType:this._videoStream.mediaStreamType,streamType:g3.Remote,additionalDetails:{watermark:{...this._getWatermarkUsageTelemetryPayload(this._viewId)}}}))})),this._mutationObserver.observe(this._container,{attributes:!0,subtree:!0,childList:!0}),this._logger.info(`watermark attached for viewId: ${this._viewId}`),this._streamTelemetryEventSender.sendMediaStreamEvent({correlationId:t,callId:this._call.id,timestampInfo:{deltaTimeInMs:Date.now()-n},operation:_3.watermark,kindOfEvent:$.success,mediaType:this._videoStream.mediaStreamType,streamType:g3.Remote,additionalDetails:{watermark:{...this._getWatermarkUsageTelemetryPayload()}}})}catch(e){let r=new Y({defaultError:J.VIEW.WATERMARK_ATTACH_FAIL,originalError:e});throw this._triggerAudioOnlyFallback(),this._streamTelemetryEventSender.sendMediaStreamEvent({correlationId:t,callId:this._call.id,timestampInfo:{deltaTimeInMs:Date.now()-n},operation:_3.watermark,kindOfEvent:$.failure,mediaType:this._videoStream.mediaStreamType,streamType:g3.Remote,additionalDetails:{failureReason:r.message,code:r.code,...K3(r),watermark:{...this._getWatermarkUsageTelemetryPayload(this._viewId)}}}),r}}_triggerAudioOnlyFallback(){this._logger.debug(`audio only fallback triggered by viewId ${this._viewId}`),this._logger.debug(`Disposing remote stream with viewId ${this._viewId}`),this._videoStream.dispose(),this._call.setWatermarkAudioOnlyFallbackTriggered(!0)}_addStyleAttributesToSvgElement(e,t){for(let[n,r]of Object.entries(t))e.style[`${n}`]=r}_generateSinglePatternWatermark(e,t){let n=this._getWatermarkContainer(t);this._svgContainer=n;let r=t.opacity/this.RANGE_MAX,i=r/this.SHADOW_OPACITY_RATIO,a=K0(),o=`url(#${a})`,s=document.createElementNS(`http://www.w3.org/2000/svg`,`defs`),c=this._getSvgFilter(a,i),l=document.createElementNS(`http://www.w3.org/2000/svg`,`text`);l.id=K0(),this._addStyleAttributesToSvgElement(l,this.WATERMARK_TEXT_COMMON_STYLES),l.setAttribute(`filter`,o),l.setAttribute(`text-anchor`,`middle`),l.setAttribute(`dominant-baseline`,`middle`),l.setAttribute(`fill-opacity`,`${r}`),l.style.transform=`rotate(-30deg)`;let u=document.createTextNode(e);l.appendChild(u),this._svgTextDefElement=l,s.appendChild(c),s.appendChild(l);let d=document.createElementNS(`http://www.w3.org/2000/svg`,`use`);return d.id=K0(),this._svgWatermarkUseTagSinglePattern=d,d.setAttribute(`href`,`#${this._svgTextDefElement.id}`),d.setAttribute(`x`,`50%`),d.setAttribute(`y`,`50%`),d.setAttribute(`width`,`100%`),d.setAttribute(`height`,`100%`),d.setAttribute(`font-size`,`${this._svgWatermarkUseTextScale}`),d.setAttribute(`stroke-width`,`${this._svgWatermarkUseTextBorderSize}`),n.appendChild(s),n.appendChild(d),this._updateWatermarkUseTextScalingSingle(this._container.getBoundingClientRect().width,this._container.getBoundingClientRect().height),n}_updateWatermarkUseTextScalingSingle(e,t){if(this._svgContainer&&this._svgWatermarkUseTagSinglePattern){let n=this._computeTextDiagonal(e,t);this._svgWatermarkUseTextScale=this.SPACE_USE*n*this.SINGLE_PATTERN_FONT_SIZE_FACTOR,this._svgWatermarkUseTextBorderSize=Math.max(1,Math.min(this.MAX_BORDER,this._svgWatermarkUseTextScale*this.BORDER_SIZE_FRAC)),this._svgWatermarkUseTagSinglePattern.setAttribute(`font-size`,`${this._svgWatermarkUseTextScale}`),this._svgWatermarkUseTagSinglePattern.setAttribute(`stroke-width`,`${this._svgWatermarkUseTextBorderSize}`),this._svgContainerHidden=this._svgContainer.outerHTML;return}this._logger.warn(`svg watermark element missing, cannot update`)}_updateWatermarkPatternScalingTiled(e,t){if(this._svgContainer&&this._svgTextDefElement&&this._svgFirstPattern&&this._svgSecondPattern){let n=Cwe(e,t,this._isApple);this._svgTextTiledScaledSize=n.scaledFontSize,this._svgTextTiledScaledStrokeWidth=n.scaledBorderSize,this._svgTextDefElement.setAttribute(`font-size`,`${this._svgTextTiledScaledSize}`),this._svgTextDefElement.setAttribute(`stroke-width`,`${this._svgTextTiledScaledStrokeWidth}`);let r=this._svgTextDefElement.getBoundingClientRect().width,i=this._svgTextDefElement.getBoundingClientRect().height,{width:a,height:o}=this._getScaledPatternDimensions(r,i,n.scaledHorizontalGap,n.scaledVerticalGap),s=.5*a,c=.5*o;this._svgFirstPatternWidth=a,this._svgFirstPatternHeight=o,this._svgSecondPatternWidth=a,this._svgSecondPatternHeight=o,this._svgSecondPatternOffsetX=s,this._svgSecondPatternOffsetY=c,this._svgFirstPattern.setAttribute(`width`,`${this._svgFirstPatternWidth}`),this._svgFirstPattern.setAttribute(`height`,`${this._svgFirstPatternHeight}`),this._svgSecondPattern.setAttribute(`width`,`${this._svgSecondPatternWidth}`),this._svgSecondPattern.setAttribute(`height`,`${this._svgSecondPatternHeight}`),this._svgSecondPattern.setAttribute(`x`,`${this._svgSecondPatternOffsetX}`),this._svgSecondPattern.setAttribute(`y`,`${this._svgSecondPatternOffsetY}`),this._svgContainerHidden=this._svgContainer.outerHTML;return}this._logger.warn(`svg watermark element missing, cannot update`)}_generateTiledPatternWatermark(e,t){let n=this._getWatermarkContainer(t);this._svgContainer=n;let r=t.opacity/this.RANGE_MAX,i=r/this.SHADOW_OPACITY_RATIO,a=K0(),o=K0(),s=K0(),c=`url(#${a})`,l=document.createElementNS(`http://www.w3.org/2000/svg`,`defs`),u=this._getSvgFilter(a,i),d=document.createElementNS(`http://www.w3.org/2000/svg`,`text`);this._svgTextDefElement=d,d.id=K0(),this._addStyleAttributesToSvgElement(d,this.WATERMARK_TEXT_COMMON_STYLES),d.setAttribute(`filter`,c),d.setAttribute(`dominant-baseline`,`hanging`),d.setAttribute(`fill-opacity`,`${r}`),d.setAttribute(`font-size`,`${this._svgTextTiledScaledSize}`),d.setAttribute(`stroke-width`,`${this._svgTextTiledScaledStrokeWidth}`);let f=document.createTextNode(e);d.appendChild(f);let p=document.createElementNS(`http://www.w3.org/2000/svg`,`pattern`);this._svgFirstPattern=p,p.id=o,p.setAttribute(`patternUnits`,`userSpaceOnUse`),p.setAttribute(`patternTransform`,`rotate(-30)`),p.setAttribute(`width`,`${this._svgFirstPatternWidth}`),p.setAttribute(`height`,`${this._svgFirstPatternHeight}`);let m=document.createElementNS(`http://www.w3.org/2000/svg`,`use`);m.setAttribute(`href`,`#${this._svgTextDefElement.id}`),p.appendChild(m);let h=document.createElementNS(`http://www.w3.org/2000/svg`,`pattern`);this._svgSecondPattern=h,h.id=s,h.setAttribute(`patternUnits`,`userSpaceOnUse`),h.setAttribute(`patternTransform`,`rotate(-30)`),h.setAttribute(`width`,`${this._svgSecondPatternWidth}`),h.setAttribute(`height`,`${this._svgSecondPatternHeight}`),h.setAttribute(`x`,`${this._svgSecondPatternOffsetX}`),h.setAttribute(`y`,`${this._svgSecondPatternOffsetY}`);let g=m.cloneNode(!0);h.appendChild(g),l.appendChild(u),l.appendChild(d),l.appendChild(p),l.appendChild(h);let _=this._getRect(0,0,100,100,o),v=this._getRect(0,0,100,100,s);return n.appendChild(l),n.appendChild(_),n.appendChild(v),this._updateWatermarkPatternScalingTiled(this._container.getBoundingClientRect().width,this._container.getBoundingClientRect().height),n}_getWatermarkContainer(e){let t=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);return this._addStyleAttributesToSvgElement(t,this.WATERMARK_CONTAINER_STYLES),t.setAttribute(`xmlns`,`http://www.w3.org/2000/svg`),t}_getSvgFilter(e,t){let n=document.createElementNS(`http://www.w3.org/2000/svg`,`filter`);n.id=e;let r=document.createElementNS(`http://www.w3.org/2000/svg`,`feDropShadow`);return r.setAttribute(`dx`,`0.5`),r.setAttribute(`dy`,`0.5`),r.setAttribute(`stdDeviation`,`1`),r.setAttribute(`flood-color`,`black`),r.setAttribute(`flood-opacity`,`${t}`),n.appendChild(r),n}_getRect(e,t,n,r,i){let a=document.createElementNS(`http://www.w3.org/2000/svg`,`rect`);return a.setAttribute(`x`,`${e}%`),a.setAttribute(`y`,`${t}%`),a.setAttribute(`width`,`${n}%`),a.setAttribute(`height`,`${r}%`),a.setAttribute(`fill`,`url(#${i})`),a}_getClampedUsername(){let e=``,t=this._call.callAgent,n=Z().calling.watermark,r=n.watermarkMaxUsernameLength,i=n.watermarkEmptyDisplayNamePlaceholder;if(t?.isEnterpriseUser()){let n=t.getUserProperties()?.sipUri;n&&typeof n==`string`&&(e=n.replace(`sip:`,``))}else e=t?.displayName??``,e||=i;return Swe(e,r)}_getSelectedWatermarkPattern(){return this._videoStream.mediaStreamType===`Video`&&this._watermarkCapability?.enabledForVideo&&this._watermarkCapability?.videoSettings?.pattern?this._watermarkCapability.videoSettings.pattern:this._videoStream.mediaStreamType===`ScreenSharing`&&this._watermarkCapability?.enabledForVbss&&this._watermarkCapability?.vbssSettings?.pattern?this._watermarkCapability.vbssSettings.pattern:``}_getWatermarkUsageTelemetryPayload(e=``){return{endpointSupportsWatermark:this._call.callAgent.isWatermarkSupported(),audioOnlyFallbackTriggered:this._call.watermarkAudioOnlyFallbackTriggered,audioOnlyFallbackTriggeredByViewId:e,watermarkUsage:{video:{enabled:this._watermarkCapability?.enabledForVideo,opacity:this._watermarkCapability?.videoSettings.opacity,pattern:this._watermarkCapability?.videoSettings.pattern},screenshare:{enabled:this._watermarkCapability?.enabledForVbss,opacity:this._watermarkCapability?.vbssSettings.opacity,pattern:this._watermarkCapability?.vbssSettings.pattern}},viewId:this._viewId}}},_7=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},v7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},UIe=1,y7=class{get isRendering(){return this._isRendering}get scalingMode(){return this._scalingMode}get isMirrored(){return this._isMirrored}get target(){return this._target}get viewId(){return this._viewId}get isDisposed(){return this._disposed}get retryErrorEvents(){return this._retryErrorEvents}get size(){return{height:this._size.height,width:this._size.width}}constructor(e,t,n,r,i,a,o){this._target=e,this._viewId=t,this._videoStream=n,this._onDisposedCallback=i,this._createViewSteps=a,this._eventEmitter=new w3.EventEmitter,this._isRendering=!1,this._scalingMode=`Stretch`,this._isMirrored=!1,this._createViewResolvedOnPlayEvent=!1,this._hasRenderingEvent=!1,this._hasPlayEvent=!1,this._size={height:0,width:0},this._disposed=!1,this.resolveRenderingPendingPromise=(e=!1)=>{this._renderingDeferred?.isPending()&&(this._renderingDeferred.resolve(),e&&(this.logger.log(`video element play event was fired and promise was resolved and isRendering is: ${this._tsRenderer?.isRendering}`),this._createViewResolvedOnPlayEvent=!0)),e?this._hasPlayEvent||(this._hasPlayEvent=!0,this._createViewSteps.isPlayedTimestamp=Date.now(),this._createViewSteps.isPlayedTimeDeltaSinceAttemptMs=this._createViewSteps.attemptTimestamp===void 0?0:this._createViewSteps.isPlayedTimestamp-this._createViewSteps.attemptTimestamp):!this._hasRenderingEvent&&this._isRendering&&(this._hasRenderingEvent=!0,this._createViewSteps.isRenderedTimestamp=Date.now(),this._createViewSteps.isRenderedTimeDeltaSinceAttemptMs=this._createViewSteps.attemptTimestamp===void 0?0:this._createViewSteps.isRenderedTimestamp-this._createViewSteps.attemptTimestamp)},this._handleTsRendererChanged=e=>{if(this.logger.debug(`rendering state is ${this._isRendering}, changed to ${this._tsRenderer?.isRendering}`),this._tsRenderer)if(this._tsRenderer.isRendering!==this._isRendering&&(this._isRendering=this._tsRenderer.isRendering,this._videoStream.updateIsReceiving(),this._isRendering&&this.resolveRenderingPendingPromise(),e.log(`isRendering change to ${this._isRendering}`)),this._tsRenderer.isRendering){let e=this._tsRenderer.streamSize?.height||u2.HEIGHT,t=this._tsRenderer.streamSize?.width||u2.WIDTH;e===this._size.height&&t===this._size.width||this.setAndUpdateSize(),this.resolveRenderingPendingPromise()}else this._size.height=0,this._size.width=0,this._videoStream.updateSize();this.sendRendererTelemetry()},this.sendRendererTelemetry=()=>{if(this._tsRenderer)try{let e={isRendering:this._tsRenderer.isRendering,streamWidth:this._tsRenderer.streamSize.width,streamHeight:this._tsRenderer.streamSize.height,isVideoAttached:this._target.isConnected,rendererWidth:this._target?.offsetWidth,rendererHeight:this._target?.offsetHeight};if(this.previousStats){if(Kwe(this.previousStats,e))return}else this.previousStats=e;this.previousStats=e;let{callId:t,localParticipantId:n,isDisposed:r,viewIdsRegistered:i,height:a,width:o,...s}=this._videoStream.getStreamMetadata(),c={...e,...s,viewId:this._viewId,disposed:this._disposed};this._videoStream.call.stats.recordEvent({name:s3.remote_view,callId:t,localParticipantId:n,data:c})}catch{}},this._unsubscribeAvailabilityCallback=()=>{this._availableCallback&&=(this._videoStream.kind===`RemoteVideoStream`&&this._videoStream?.off(`isAvailableChanged`,this._availableCallback),void 0)},this._disposeTsRendererChangedObservable=()=>{this._tsRendererChanged&&=(this._tsRendererChanged.dispose(),void 0)},this._attemptToDisposeTsRenderer=()=>{if(this._tsRenderer){this.logger.debug(`disposing underlying remote renderer`);try{this._tsRenderer?.dispose(),this._tsRenderer=void 0}catch(e){throw this.logger.warn(`underlying remote renderer dispose failed with ${e?.message} error`),new Y({defaultError:J.VIEW.REMOTE_RENDERER_DISPOSE_FAIL})}}},this.logger=r.createChild(`RemoteStreamRenderer`+ UIe++),this.logger.log(`created`),o?.scalingMode!==void 0&&(this._scalingMode=o.scalingMode),o?.isMirrored!==void 0&&(this._isMirrored=o.isMirrored),this._remoteStreamTelemetryEventSender=new V6(this._videoStream.telemetryLogManager),this._watermarkOverlayProvider=new HIe(this._target,this._videoStream,this._viewId,this.logger,this._remoteStreamTelemetryEventSender),this._watermarkOverlayProvider.attach(),this._retryErrorEvents=new Set([J.VIEW.TIMEOUT.subCode,J.VIEW.SUBSCRIBE.subCode])}async start(){let e=K0(),t=+new Date,n=this.logger.createFnLogger(m4.Start),r={timestampInfo:{attemptTimestamp:t},correlationId:e,operation:_3.render,kindOfEvent:$.attempt,mediaType:this._videoStream.mediaStreamType,streamType:g3.Remote};if(this._remoteStreamTelemetryEventSender.sendMediaStreamEvent(r),this._disposed)throw this.logger.warn(`already disposed`),new Y({defaultError:J.VIEW.START_ALREADY_DISPOSED});this._createViewTimeout&&=(clearTimeout(this._createViewTimeout),void 0);try{n.info(`scalingMode=${E4(this._scalingMode)}`),this._videoStream.registerRenderer(this),this._renderingDeferred=e3(),this._renderingDeferred.promise.catch(A4),this._videoStream.kind===`RemoteVideoStream`&&(this._availableCallback=()=>{this._videoStream.isAvailable||(n.warn(`stream isAvailable changed to false, attempting to reject operation`),this._renderingDeferred?.isPending()&&!this._disposed&&this._renderingDeferred?.reject(new Y({defaultError:J.VIEW.STREAM_BECAME_UNAVAILABLE})))},this._videoStream.on(`isAvailableChanged`,this._availableCallback)),this._createViewSteps.startSubscriptionTimestamp=Date.now(),this._createViewSteps.startSubscriptionTimeDeltaSinceAttemptMs=this._createViewSteps.attemptTimestamp===void 0?0:this._createViewSteps.startSubscriptionTimestamp-this._createViewSteps.attemptTimestamp,this._videoStream.tsStream.start(this._target,{scalingMode:E4(this._scalingMode),transparent:!1}).then((e=>{if(this._createViewSteps.rendererIsAvailableTimestamp=Date.now(),this._createViewSteps.rendererIsAvailableTimeDeltaSinceAttemptMs=this._createViewSteps.attemptTimestamp===void 0?0:this._createViewSteps.rendererIsAvailableTimestamp-this._createViewSteps.attemptTimestamp,this._isMirrored&&(this._target.style.transform=`rotateY(180deg)`,this._target.style.webkitTransform=`rotateY(180deg)`),this._tsRenderer=e,this.logger.info(`subscribed to video, waiting for the first frame`),this._disposed)throw this.logger.warn(`already disposed, dispose underlying renderer`),this._attemptToDisposeTsRenderer(),new Y({defaultError:J.VIEW.START_ALREADY_DISPOSED});if(this.logger.info(`current state of rendering is ${this._tsRenderer.isRendering}`),this.sendRendererTelemetry(),Z().rendering.remoteVideo.createViewTimeout!==-1&&(this._createViewTimeout=setTimeout((()=>{if(this._renderingDeferred?.isPending())try{this._renderingDeferred.reject(new Y({defaultError:J.VIEW.TIMEOUT})),this._createViewTimeout&&=(clearTimeout(this._createViewTimeout),void 0)}catch{}}),Z().rendering.remoteVideo.createViewTimeout)),Z().rendering.remoteVideo.speedupCreateViewWithPlayEvent){let e=this._target&&this._target.children.length>0&&this._target.children[0];e?e.addEventListener(`play`,this.videoPlayEventListener.bind(this)):this.logger.warn(`video element was not found while trying to listen to play event`)}this._tsRendererChanged=this._tsRenderer.changed((()=>this._handleTsRendererChanged(n))),this._tsRenderer.isRendering&&(this._isRendering=!0,this._videoStream.updateIsReceiving(),this.setAndUpdateSize(),this.resolveRenderingPendingPromise())})).catch((e=>{if(this.logger.info(`Failed to subscribe to video`),this._renderingDeferred?.isPending()){let t=new Y({defaultError:J.VIEW.SUBSCRIBE,originalError:e});this._renderingDeferred.reject(t)}})),await this._renderingDeferred.promise,this._videoStream.flushIsReceiving(),this._unsubscribeAvailabilityCallback(),Z().rendering.remoteVideo.forceCheckIfVideoWasAttachedToDom&&this._checkIfVideoWasAttachedToDom();let r={timestampInfo:{deltaTimeInMs:+new Date-t},correlationId:e,operation:_3.render,kindOfEvent:$.success,mediaType:this._videoStream.mediaStreamType,streamType:g3.Remote,createViewResolvedOnPlayEvent:this._createViewResolvedOnPlayEvent};return this._remoteStreamTelemetryEventSender.sendMediaStreamEvent(r),this}catch(n){this.logger.warn(`Failed to render, message=${n}`);try{this._retryErrorEvents.has(n?.subCode)||this.dispose()}catch(e){this.logger.warn(`dispose failed with ${e?.message} error`)}let r=new Y({defaultError:J.VIEW.START,originalError:n});if(r.message!==J.VIEW.LARGE_MEETING_VIEW_DISPOSED.message&&r.message!==J.VIEW.REMOTE_VIDEO_STREAM_DISPOSED.message){let n={timestampInfo:{deltaTimeInMs:+new Date-t},correlationId:e,operation:_3.render,additionalDetails:{failureReason:r.message,code:FG,...K3(r)},kindOfEvent:$.failure,mediaType:this._videoStream.mediaStreamType,streamType:g3.Remote,createViewResolvedOnPlayEvent:this._createViewResolvedOnPlayEvent};this._remoteStreamTelemetryEventSender.sendMediaStreamEvent(n)}throw r}}videoPlayEventListener(){this.logger.log(`video element play event was fired`),this.resolveRenderingPendingPromise(!0)}setAndUpdateSize(){try{this._size.width=this._tsRenderer?.streamSize.width||u2.WIDTH,this._size.height=this._tsRenderer?.streamSize.height||u2.HEIGHT,this._videoStream.updateSize()}catch(e){this.logger.error(`Failed to update video stream size with error ${e}`)}}async setScalingMode(e){if(!this._tsRenderer)throw new Y({defaultError:J.VIEW.SCALING_MODE});await this._tsRenderer.setScalingMode(E4(e)),this._scalingMode=e}_clearTimeouts(){this._checkIfVideoWasAttachedToDomTimeout&&=(clearTimeout(this._checkIfVideoWasAttachedToDomTimeout),void 0),this._createViewTimeout&&=(clearTimeout(this._createViewTimeout),void 0)}dispose(e=b3.Public_App){if(this._disposed)throw new Y({defaultError:J.VIEW.RENDERER_DISPOSE_ALREADY_DISPOSED});if(this._disposed=!0,this._disposeTsRendererChangedObservable(),this._unsubscribeAvailabilityCallback(),this._attemptToDisposeTsRenderer(),this._renderingDeferred?.isPending()){let t;switch(e){case b3.Internal_LargeMeetingVideoRendering:t=J.VIEW.LARGE_MEETING_VIEW_DISPOSED;break;case b3.Internal_RemoteVideoStreamDisposed:t=J.VIEW.REMOTE_VIDEO_STREAM_DISPOSED;break;default:t=J.VIEW.APP_VIEW_DISPOSED}this._renderingDeferred.reject(new Y({defaultError:t}))}if(this._target){let e=this._target.children&&this._target.children.length>0&&this._target.children[0];e&&e.removeEventListener(`play`,this.videoPlayEventListener),this._target.remove()}try{e!==b3.Public_App&&this._onDisposedCallback(e)}catch(e){this.logger.debug(`dispose callback failed with ${e?.message} error`)}this._watermarkOverlayProvider.dispose(),this._videoStream.unregisterRenderer(this),this._size.height=0,this._size.width=0,this._videoStream.updateSize(),this._isRendering=!1,this._videoStream.updateIsReceiving(),this._eventEmitter.removeAllListeners(),this._renderingDeferred=void 0,this._clearTimeouts()}_checkIfVideoWasAttachedToDom(){if(this._checkIfVideoWasAttachedToDomTimeout&&=(clearTimeout(this._checkIfVideoWasAttachedToDomTimeout),void 0),Z().rendering.remoteVideo.checkIfVideoAttachedToDom_poll){let e=Z().rendering.remoteVideo.checkIfVideoAttachedToDom_intervalMaxTries,t=()=>{this._target.isConnected||e<=0?this.sendRendererTelemetry():(e--,e>=0&&(this._checkIfVideoWasAttachedToDomTimeout=setTimeout((()=>t()),Z().rendering.remoteVideo.checkIfVideoAttachedToDom_intervalTime)))};t()}else this._checkIfVideoWasAttachedToDomTimeout=setTimeout((()=>{this._target.isConnected&&this.sendRendererTelemetry()}),Z().rendering.remoteVideo.checkIfVideoAttachedToDom_timeout)}};_7([zG,v7(`design:type`,Object)],y7.prototype,`logger`,void 0),_7([GG(m4.Start),v7(`design:type`,Function),v7(`design:paramtypes`,[]),v7(`design:returntype`,Promise)],y7.prototype,`start`,null),_7([WG(m4.Dispose),v7(`design:type`,Function),v7(`design:paramtypes`,[String]),v7(`design:returntype`,void 0)],y7.prototype,`dispose`,null);var b7=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},x7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},S7=class{get isRendering(){return this._isRendering}get scalingMode(){return this._scalingMode}get isMirrored(){return this._isMirrored}get target(){return this._target}get isDisposed(){return this._disposed}constructor(e,t,n,r,i){this._target=e,this._videoStream=t,this._onDisposed=r,this._eventEmitter=new w3.EventEmitter,this._isRendering=!1,this._scalingMode=`Stretch`,this._isMirrored=!0,this._disposed=!1,this.logger=n.createChild(`LocalStreamRenderer`),this.logger.log(`created`),i?.scalingMode!==void 0&&(this._scalingMode=i.scalingMode),i?.isMirrored===void 0?this._videoStream.mediaStreamType===`ScreenSharing`&&(this._isMirrored=!1):this._isMirrored=i.isMirrored,this._localStreamTelemetryEventSender=new V6(this._videoStream.telemetryLogManager)}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}async start(){let e=K0(),t=this.logger.createFnLogger(m4.Start),n=+new Date,r={timestampInfo:{attemptTimestamp:n},correlationId:e,operation:_3.render,kindOfEvent:$.attempt,mediaType:this._videoStream.mediaStreamType,streamType:g3.Local};this._localStreamTelemetryEventSender.sendMediaStreamEvent(r);try{if(t.info(`attempting to select new device as a source`),this._videoStream.source instanceof L6&&this._videoStream.mediaStreamType===`Video`){let e=this._videoStream.source.deviceManager.getTsDeviceManager();e.selectDevices({camera:this._videoStream.source.id}),t.info(`device selected`),t.info(`creating preview`),this._tsRenderer=await e.createPreview(this._target,{kind:`camera`},{scalingMode:E4(this._scalingMode),transparent:!1,ignoreMirroring:!1,disposeRendererWhenStreamisNotAvailable:()=>!0})}else{if(this._videoStream.mediaStreamType!==`RawMedia`&&this._videoStream.mediaStreamType!==`ScreenSharing`)throw new Y({defaultError:J.VIEW.UNKNOWN_STREAM_TYPE});{this._rawMediaOrSS_previewVideo=document.createElement(`video`),this._rawMediaOrSS_previewVideo.style.width=`100%`,this._rawMediaOrSS_previewVideo.style.height=`100%`,this._rawMediaOrSS_previewVideo.style.objectFit=`contain`,this._rawMediaOrSS_previewVideo.setAttribute(`playsinline`,`true`),this._rawMediaOrSS_previewVideo.disablePictureInPicture=!0,this._rawMediaOrSS_previewVideo.autoplay=!0;let e=await this._videoStream.getMediaStream(),t=new MediaStream(e.getVideoTracks());this._rawMediaOrSS_previewVideo.srcObject=t,this._rawMediaOrSS_previewVideo.play(),this._target.appendChild(this._rawMediaOrSS_previewVideo)}}this._isMirrored&&(this._target.style.transform=`rotateY(180deg)`,this._target.style.webkitTransform=`rotateY(180deg)`),this._videoStream.registerRenderer(this);let r={timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:e,operation:_3.render,kindOfEvent:$.success,mediaType:this._videoStream.mediaStreamType,streamType:g3.Local};return this._localStreamTelemetryEventSender.sendMediaStreamEvent(r),this}catch(r){this.dispose();let i=U3(t,r),a={timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:e,operation:_3.render,additionalDetails:{failureReason:i.message,code:i.code,subCode:i.subCode,...K3(i)},kindOfEvent:$.failure,mediaType:this._videoStream.mediaStreamType,streamType:g3.Local};throw this._localStreamTelemetryEventSender.sendMediaStreamEvent(a),i}}setScalingMode(e){if(this._tsRenderer)this._tsRenderer.setScalingMode(E4(e)),this._scalingMode=e;else{if(!this._rawMediaOrSS_previewVideo)throw new Y({defaultError:J.VIEW.SCALING_MODE});switch(e){case`Stretch`:this._rawMediaOrSS_previewVideo.style.objectFit=`fill`;break;case`Crop`:this._rawMediaOrSS_previewVideo.style.objectFit=`cover`;break;default:this._rawMediaOrSS_previewVideo.style.objectFit=`contain`}}}setSourceObject(e){this.disposeScreenSharingMediaStream();let t=this._target.querySelector(`video`);t&&(t.srcObject=e,t.play())}dispose(){if(!this._disposed){if(this._tsRenderer)try{this.logger.log(`disposing underlying local renderer`),this._tsRenderer.dispose(),this._tsRenderer=void 0}catch(e){throw this.logger.warn(`underlying local renderer dispose failed with ${e?.message} error`),new Y({defaultError:J.VIEW.LOCAL_RENDERER_DISPOSE_FAIL})}this.disposeScreenSharingMediaStream(),this._target.remove(),this._onDisposed&&this._onDisposed(this),this._eventEmitter.removeAllListeners(),this._disposed=!0}}disposeScreenSharingMediaStream(){if(this._videoStream.getCall()?.localScreenSharingStream){let e=this._target.querySelector(`video`),t=e?.srcObject;t&&(t.getVideoTracks().forEach((e=>{e.stop()})),e.srcObject=null,this.logger.info(`disposed of ScreenSharing MediaStream`))}}};b7([zG,x7(`design:type`,Object)],S7.prototype,`logger`,void 0),b7([GG(h4.Start),x7(`design:type`,Function),x7(`design:paramtypes`,[]),x7(`design:returntype`,Promise)],S7.prototype,`start`,null),b7([WG(h4.SetScalingMode),x7(`design:type`,Function),x7(`design:paramtypes`,[String]),x7(`design:returntype`,void 0)],S7.prototype,`setScalingMode`,null),b7([WG(h4.SetSourceObject),x7(`design:type`,Function),x7(`design:paramtypes`,[MediaStream]),x7(`design:returntype`,void 0)],S7.prototype,`setSourceObject`,null),b7([WG(h4.Dispose),x7(`design:type`,Function),x7(`design:paramtypes`,[]),x7(`design:returntype`,void 0)],S7.prototype,`dispose`,null);var C7=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},w7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},WIe=1,T7=class e{get scalingMode(){return this._streamRenderer.scalingMode}get isMirrored(){return this._streamRenderer.isMirrored}get disposed(){return this._disposed}constructor(e,t,n,r,i){if(this._videoStream=e,this._viewId=n,this._options=i,this._disposed=!1,this._isRetryErrorSubCode=e=>`retryErrorEvents`in this._streamRenderer&&this._streamRenderer.retryErrorEvents.has(e.subCode),this._deleteActiveRemoteVideoStreamView=(e,t)=>{if(e.call.activeRemoteVideoStreamViews?.has(e.id)){let n=e.call.activeRemoteVideoStreamViews?.get(e.id);n?.delete(t),n?.size==0&&e.call.activeRemoteVideoStreamViews?.delete(e.id)}},this.logger=t.createChild(`VideoStreamRendererView`+ WIe++),this.target=document.createElement(`div`),this.target.style.width=`100%`,this.target.style.height=`100%`,this._videoStream instanceof g8)this._streamRenderer=new y7(this.target,this._viewId,this._videoStream,this.logger,(e=>{this._disposed||this.dispose(e)}),r,this._options);else{if(!(this._videoStream instanceof J6))throw new Y({defaultError:J.VIEW.VIEW_WRONG_STREAM_TYPE});this._streamRenderer=new S7(this.target,this._videoStream,this.logger,(()=>this.dispose),this._options)}this._telemetryLogManager=this._videoStream.telemetryLogManager,this.logger.info(`created`)}async render(){let e=this.logger.createFnLogger(this._videoStream instanceof g8?u4.RenderRemoteStream:u4.RenderLocalStream);if(this._disposed)throw e.log(`failed, stream disposed!`),new Y({defaultError:J.VIEW.RENDER_FAIL_STREAM_DISPOSED});let t=Z().rendering.remoteVideo.maxRendererRetries,n=1,r=(e,t)=>e().catch((i=>{if(t>0&&this._isRetryErrorSubCode(i))return n+=1,r(e,t-1);throw this._streamRenderer.isDisposed||this._streamRenderer.dispose(),i})),i=()=>this._streamRenderer.start();try{await r(i,t-1)}catch(t){throw e.error(`Failed to render stream ${this._viewId} after ${n} retries.`),this._isRetryErrorSubCode(t)&&n>1&&(t.message+=`\nFailed to render stream ${this._viewId} after ${n} retries.`),t}return n}async updateScalingMode(e){if(this._disposed)throw new Y({defaultError:J.VIEW.SCALING_MODE_DISPOSED});if(e!==`Crop`&&e!==`Fit`&&e!==`Stretch`)throw new Y({defaultError:J.VIEW.SCALING_MODE_WRONG_VAL});try{await this._streamRenderer.setScalingMode(e)}catch(e){throw new Y({defaultError:J.VIEW.SCALING_MODE,originalError:e})}}dispose(t=b3.Public_App){if(this._disposed)throw new Y({defaultError:J.VIEW.VIEW_ALREADY_DISPOSED});this._disposed=!0;let n=+new Date,r=K0();try{t===b3.Public_App&&this.sendDisposeViewEvent({eventName:Q.acs_calling_dispose_view_attempt,correlationId:r,timestampInfo:{attemptTimestamp:n}}),this.logger.debug(`attempt to dispose stream renderer`),this._streamRenderer.dispose(t),this.target?.remove(),this._videoStream instanceof a7&&(this._deleteActiveRemoteVideoStreamView(this._videoStream,this._viewId),Z()?.rendering.remoteVideo.decrementOvcOnRemoteSsRendering&&this._videoStream.mediaStreamType===`ScreenSharing`&&(e.remoteScreenSharingViews.delete(this._viewId),e.remoteScreenSharingViews.size<=0&&this._videoStream.call.setIsRenderingRemoteScreenShare(!1)));let i=+new Date;t===b3.Public_App&&this.sendDisposeViewEvent({eventName:Q.acs_calling_dispose_view_success,correlationId:r,timestampInfo:{deltaTimeInMs:i-n}})}catch(e){let i=new Y({defaultError:J.VIEW.DISPOSE_FAIL,originalError:e});if(t===b3.Public_App){let e=+new Date;this.sendDisposeViewEvent({eventName:Q.acs_calling_dispose_view_failure,correlationId:r,timestampInfo:{deltaTimeInMS:e-n}},i)}throw i}}sendDisposeViewEvent(e,t){try{let n,r;t&&(n=typeof t?.message==`string`?t?.message:``,r={...K3(t)}),this._telemetryLogManager.sendEvent({name:e.eventName,tenant:d2,properties:{...this._videoStream.getStreamMetadata(),viewId:this._viewId,correlationId:e.correlationId,timestampInfo:e.timestampInfo,failureReason:n,additionalDetails:r}})}catch{this.logger.debug(`Unable to send telemtery`)}}};T7.remoteScreenSharingViews=new Map,C7([zG,w7(`design:type`,Object)],T7.prototype,`logger`,void 0),C7([GG(u4.Render),w7(`design:type`,Function),w7(`design:paramtypes`,[]),w7(`design:returntype`,Promise)],T7.prototype,`render`,null),C7([GG(u4.UpdateScalingMode),w7(`design:type`,Function),w7(`design:paramtypes`,[String]),w7(`design:returntype`,Promise)],T7.prototype,`updateScalingMode`,null),C7([WG(u4.Dispose),w7(`design:type`,Function),w7(`design:paramtypes`,[String]),w7(`design:returntype`,void 0)],T7.prototype,`dispose`,null);var GIe=V5();function KIe(e,t,n,r){let i=[`audioBitrate`,`videoBitrate`,`downloadBitrate`,`bufferLengthInMs`,`videoHeight`,`videoWidth`,`currentPlayPosition`],a=t[n.toString()];a!==void 0&&i.forEach((t=>{let n=t,i=t;if(a[n]!==void 0){let t=a[n];e[i]===void 0?e[i]=[t]:(e[i]?.length>=r&&e[i]?.shift(),e[i]?.push(t))}}))}var qIe=class{get createViewStats(){return this._createViewStats}get initialCreateViewStats(){return this._initialCreateViewStats}constructor(e,t,n,r,i){this._statsCollector=e,this._streamId=t,this._logger=n,this._call=r,this._attemptTimestamp=i,this._createViewFailureStats={},this._createViewStats={},this._initialCreateViewStats={},this._statsCollector.on(`sampleReported`,(e=>{vke(this.createViewStats,this.initialCreateViewStats,e,this._streamId)}))}getCreateViewFailureStats(){try{let e=0,t=NaN;this.createViewStats.video?.framesDropped!==void 0&&this.initialCreateViewStats.video?.framesDropped!==void 0&&(e=this.createViewStats.video?.framesDropped.length,t=this.createViewStats.video?.framesDropped[e-1]-this.initialCreateViewStats.video?.framesDropped[0]);let n=NaN;this.createViewStats.video?.framesReceived!==void 0&&this.initialCreateViewStats.video?.framesReceived!==void 0&&(e=this.createViewStats.video.framesReceived.length,n=this.createViewStats.video.framesReceived[e-1]-this.initialCreateViewStats.video?.framesReceived[0]);let r=NaN;this.createViewStats.video?.framesDecoded!==void 0&&this.initialCreateViewStats.video?.framesDecoded!==void 0&&(e=this.createViewStats.video.framesDecoded.length,r=this.createViewStats.video.framesDecoded[e-1]-this.initialCreateViewStats.video?.framesDecoded[0]);let i=NaN;this.createViewStats.video?.keyFramesDecoded!==void 0&&this.initialCreateViewStats.video?.keyFramesDecoded!==void 0&&(e=this.createViewStats.video.keyFramesDecoded.length,i=this.createViewStats.video.keyFramesDecoded[e-1]-this.initialCreateViewStats.video?.keyFramesDecoded[0]);let a=0;!isNaN(t)&&n>0&&(a=Number((t/n*100).toFixed(7)));let o=!1;n>0&&r===0&&(o=!0);let s=!1;!isNaN(r)&&!isNaN(i)&&r>0&&r===i&&(s=!0);let c=[],l=this._call.networkQualityUfdEventDetails,u=Z().rendering.remoteVideo.createViewFailureNetworkUfdCheckWindowInMs;l.forEach((e=>{Math.abs(e.timestampInfo-this._attemptTimestamp)<=u&&c.push(e)}));let d=n===0;this._createViewFailureStats.video={framesDroppedPercentage:a,framesReceivedButNothingDecoded:o,onlyKeyFramesDecoded:s,networkQualityEventsDuringAttempt:c,zeroFramesReceived:d}}catch{this._logger.debug(`Error calculating create view failure stats!`)}return this._createViewFailureStats}},JIe=class{constructor(e,t){this._liveStreamStatsCollector=e,this._streamId=t,this._liveStreamStats={},this._initialLiveStreamStats={};let n=Z()?.rendering.remoteVideo.createViewSendMediaStatsMaxLength;this._liveStreamStatsCollector.on(`sampleReported`,(e=>{KIe(this._liveStreamStats,e,this._streamId,n),Q2.isEmpty(this._initialLiveStreamStats)&&(this._initialLiveStreamStats=this._liveStreamStats)}))}get initialCreateViewLiveStreamStats(){return this._initialLiveStreamStats}get createViewLiveStreamStats(){return this._liveStreamStats}},E7=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},D7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},O7=class{get _createViewStats(){return this._videoStream.kind!==`RemoteVideoStream`&&this._videoStream.kind!==`ComposedVideoStream`||!this._createViewTelemetryHelper?this._videoStream.kind===`LiveVideoStream`&&this._createViewLiveStreamTelemetryHelper?this._createViewLiveStreamTelemetryHelper.createViewLiveStreamStats:{}:this._createViewTelemetryHelper.createViewStats}constructor(e){if(this.size={height:0,width:0},this.views=new Map,this.disposed=!1,this._attemptToDisposeView=e=>{try{e?.dispose()}catch(e){this.logger.warn(e?.message||`Failed to dispose, unknown error`)}},this._addActiveRemoteVideoStreamView=(e,t,n)=>{if(e.call.activeRemoteVideoStreamViews?.has(e.id)){let r=e.call.activeRemoteVideoStreamViews?.get(e.id);r&&r.set(t,n)}else{let r=new Map;r.set(t,n),e.call.activeRemoteVideoStreamViews?.set(e.id,r)}},!(e instanceof J6||e instanceof g8||e instanceof a7))throw new Y({defaultError:J.VIEW.RENDERER_WRONG_STREAM_TYPE});let t=KW(`ACS`);this._videoStream=e,this._telemetryLogManager=e.telemetryLogManager,this.logger=new z6(t,e instanceof J6?[()=>`VideoStreamRenderer:LocalVideoStream:${GIe.pii.Omit(e?.source?.id)}`]:[()=>`VideoStreamRenderer:${e.kind}:${e?.id}`]),this.logger.info(`created`)}async createView(e){if(this.disposed)throw new Y({defaultError:J.VIEW.RENDERER_DISPOSED});let t={},n=+new Date,r=K0(),i=K0(),a,o;try{let s=1;if(t.attemptTimestamp=n,this.sendCreateViewEvent({eventName:Q.acs_calling_create_view_attempt,viewId:r,correlationId:i,timestampInfo:{attemptTimestamp:n},isMirrored:e?.isMirrored,scalingMode:e?.scalingMode,stepsInfo:t}),this._videoStream.kind===`RemoteVideoStream`&&!this._videoStream.isAvailable)throw new Y({defaultError:J.VIEW.ISAVAILABLE_FALSE});let c=Z(),l=w4();if(this._videoStream.kind===`RemoteVideoStream`&&this._videoStream.mediaStreamType!==`ScreenSharing`&&c?.calling.applyViewLimit&&l?.numVideoChannelsGvc){let e=l?.numVideoChannelsGvc,t=this._videoStream;if(!t.call.activeRemoteVideoStreamViews?.has(t.id)&&t.call.activeRemoteVideoStreamViews?.size>=e)throw new Y({defaultError:J.VIEW.MAX_NUM_OF_VIEWS_REACHED,defaultErrorMessageArgs:[e]})}if(c?.rendering.remoteVideo.createViewSendMediaStats){if(this._videoStream.kind===`RemoteVideoStream`||this._videoStream.kind===`ComposedVideoStream`){let e=this._videoStream,t=e.call;o=e.call.feature(Z5.MediaStats).createCollector();let r=e.id;this._createViewTelemetryHelper=new qIe(o,r,this.logger,t,n)}else if(this._videoStream.kind===`LiveVideoStream`){let e=this._videoStream;o=e.call.feature(Z5.LiveStream).createStatsCollector();let t=e.id;this._createViewLiveStreamTelemetryHelper=new JIe(o,t)}}a=new T7(this._videoStream,this.logger,r,t,e),this.views.set(r,a),s=await a.render(),this._videoStream.kind===`RemoteVideoStream`&&this._videoStream.mediaStreamType!==`ScreenSharing`&&this._addActiveRemoteVideoStreamView(this._videoStream,r,a),this._videoStream.kind===`RemoteVideoStream`&&this._videoStream.mediaStreamType===`ScreenSharing`&&c?.rendering.remoteVideo.decrementOvcOnRemoteSsRendering&&(this._videoStream.call.setIsRenderingRemoteScreenShare(!0),T7.remoteScreenSharingViews.set(r,a));let u=+new Date;return this.sendCreateViewEvent({eventName:Q.acs_calling_create_view_success,viewId:r,correlationId:i,timestampInfo:{deltaTimeInMs:u-n},additionalProperties:{isRetry:!!s&&s>1,attemptNumber:s},stepsInfo:t}),a}catch(e){let o=new Y({defaultError:J.VIEW.CREATE_VIEW_FAILED,originalError:e});if(this.views.delete(r),this._attemptToDisposeView(a),o.message!==J.VIEW.LARGE_MEETING_VIEW_DISPOSED.message&&o.message!==J.VIEW.REMOTE_VIDEO_STREAM_DISPOSED.message){let e=Date.now();this.sendCreateViewEvent({eventName:Q.acs_calling_create_view_failure,viewId:r,correlationId:i,timestampInfo:{deltaTimeInMs:e-n},stepsInfo:t},o)}throw o}finally{o?.dispose()}}async sendCreateViewEvent(e,t){try{let n={},r={},i={};if(Z()?.rendering.remoteVideo.createViewSendMediaStats&&(e.eventName===Q.acs_calling_create_view_failure||e.eventName===Q.acs_calling_create_view_success)){if(this._videoStream.kind===`RemoteVideoStream`){let t=this._videoStream.call,r=await t.tsCall.getMediaSessionStatsAsync?.();n={isRetry:e.additionalProperties?.isRetry??!1,attemptNumber:e.additionalProperties?.attemptNumber??1,videoSubscriptionEvents:r?.extensions?.Video_SubscriptionEvents,screenSharingSubscriptionEvents:r?.extensions?.Sharing_SubscriptionEvents,videoSendMaxCapabilities:r?.extensions?.Video_send_MaxCapabilities,screenSharingSendMaxCapabilities:r?.extensions?.Sharing_send_MaxCapabilities,iceConnectedStateTime:r?.metrics?.IceConnectedStateTime,relayCandidate:r?.extensions?.RelayCandidate,videoRecvTimeToFirstFrame:r?.extensions?.Video_recv_TimeToFirstFrame,screenSharingRecvTimeToFirstFrame:r?.extensions?.Sharing_recv_TimeToFirstFrame,optimalVideoCount:t.tsCall.optimalVideoCount||1,currentNumberOfVideosRendered:t.activeRemoteVideoStreamViews?.size||0}}e.eventName===Q.acs_calling_create_view_failure&&(i=this._createViewTelemetryHelper?.getCreateViewFailureStats()??{},r=this._createViewStats)}n.visibilityState=document.visibilityState,e.isMirrored!==void 0&&(n.isMirrored=e.isMirrored),e.scalingMode!==void 0&&(n.scalingMode=e.scalingMode),e.eventName!==Q.acs_calling_create_view_failure&&e.eventName!==Q.acs_calling_create_view_success||this._videoStream.kind!==`RemoteVideoStream`&&this._videoStream.kind!==`ComposedVideoStream`||Q2.forOwn(e.stepsInfo,((e,t)=>{e!==void 0&&(n[t]=e)}));let a=``,o={};t&&(a=typeof t?.message==`string`?t?.message:``,o={...K3(t)}),this._telemetryLogManager.sendEvent({name:e.eventName,tenant:d2,properties:{viewId:e.viewId,correlationId:e.correlationId,timestampInfo:e.timestampInfo,...this._videoStream.getStreamMetadata(),failureReason:a,additionalProperties:n,additionalDetails:o,stats:r,createViewFailureDebugStats:i,videoStreamKind:this._videoStream.kind}})}catch{this.logger.debug(`Unable to send telemtery`)}}dispose(){if(this.disposed)throw new Y({defaultError:J.VIEW.RENDERER_ALREADY_DISPOSED});this.disposed=!0,this.views.forEach(this._attemptToDisposeView),this.views.clear()}};E7([zG,D7(`design:type`,Object)],O7.prototype,`logger`,void 0),E7([GG(d4.CreateView),D7(`design:type`,Function),D7(`design:paramtypes`,[Object]),D7(`design:returntype`,Promise)],O7.prototype,`createView`,null),E7([WG(d4.Dispose),D7(`design:type`,Function),D7(`design:paramtypes`,[]),D7(`design:returntype`,void 0)],O7.prototype,`dispose`,null);var YIe=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},k7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},A7=class{get identifier(){return this._identifier}get endpointDetails(){return this._tsParticipant?.endpoints?.endpointDetails.map((e=>({participantId:e.participantId,deviceType:e.deviceType,clientEndpointCapabilities:e.clientEndpointCapabilities,endpointMetadata:e.endpointMetadata})))||[]}get state(){return this._state}get videoStreams(){return[...this._mappedStreams.values()]}get isMuted(){return this._isMuted}get isSpeaking(){return this._isSpeaking}get callEndReason(){return this._callEndReason}get displayName(){return this._displayName}get hasDisplayNameChanged(){return this._hasDisplayNameChanged}get role(){return this._role}constructor(e,t,n,r,i){this._mappedStreams=new Map,this._state=`Idle`,this._lastTsParticipantState=0,this._isMuted=!1,this._isSpeaking=!1,this._displayName=``,this._realDisplayName=``,this._hasDisplayNameChanged=!1,this._role=`Unknown`,this.acsToTsStreamType=e=>e===`Video`?0:e===`ScreenSharing`?1:void 0,this.getParticipantDisplayNameOverride=()=>this._tsParticipant?.propertyBag?.displayNameOverride?.value?.displayNameOverrideValue,this._identifier=e,this.logger=t.createChild((()=>`RemoteParticipant{${this._identifier.kind}}`)),this._telemetryLogManager=i,this._eventEmitter=new S6(this.logger),this._callAgent=r,this._call=n,this.logger.log(`created`),this._renderers={Video:{renderingState:{}},ScreenSharing:{renderingState:{}}}}on(e,t){if(e!==`stateChanged`&&e!==`isMutedChanged`&&e!==`isSpeakingChanged`&&e!==`displayNameChanged`&&e!==`roleChanged`&&e!==`videoStreamsUpdated`)throw new Y({defaultError:J.REMOTE_PARTICIPANT.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if(e!==`stateChanged`&&e!==`isMutedChanged`&&e!==`isSpeakingChanged`&&e!==`displayNameChanged`&&e!==`roleChanged`&&e!==`videoStreamsUpdated`)throw new Y({defaultError:J.REMOTE_PARTICIPANT.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}async mute(){let e=Z();if(!e.calling.enableMuteOthers)throw new Y({defaultError:J.REMOTE_PARTICIPANT.MUTE_PARTICIPANT_DISABLED});if(!this._call.tsCall.conversationType&&this._call.callInfo.context===v4.TwoParty)throw new Y({defaultError:J.REMOTE_PARTICIPANT.MUTE_PARTICIPANT_1_TO_1_UNSUPPORTED});if(![`Connected`,`Hold`].some((e=>e===this._state)))throw new Y({defaultError:J.REMOTE_PARTICIPANT.MUTE_PARTICIPANT_NONCONNECTED_UNSUPPORTED});let t=this.logger.createFnLogger(s4.Mute),n=+new Date,r=K0();if(this.sendAudioEvent({eventName:Q.acs_calling_mute_attempt,eventType:l3.MuteSpecificParticipant,timestampInfo:{attemptTimestamp:n},correlationId:r,step:`mid-call`}),!e.calling.allowMutePstnRemoteParticipant&&this._identifier.kind===`phoneNumber`){let e=+new Date,i=J.REMOTE_PARTICIPANT.MUTE_PARTICIPANT_PSTN_UNSUPPORTED;t.warn(i.message);let a=new Y({defaultError:i});throw this.sendAudioEvent({eventName:Q.acs_calling_mute_failure,eventType:l3.MuteSpecificParticipant,timestampInfo:{deltaTimeInMs:e-n},correlationId:r,step:`mid-call`},a),a}try{t.info(`remote mute specific`),this._tsParticipant===void 0?t.warn(`no participant to mute in attempt to mute specific remote participant`):await this._call.tsCall.muteParticipants(1,[this._tsParticipant]),t.info(`remote mute specific success`);let e=+new Date;this.sendAudioEvent({eventName:Q.acs_calling_mute_success,eventType:l3.MuteSpecificParticipant,timestampInfo:{deltaTimeInMs:e-n},correlationId:r,step:`mid-call`})}catch(e){let i=new Y({defaultError:J.REMOTE_PARTICIPANT.MUTE_PARTICIPANT_FAILED,originalError:e});t.error(i.message);let a=+new Date;throw this.sendAudioEvent({eventName:Q.acs_calling_mute_failure,eventType:l3.MuteSpecificParticipant,timestampInfo:{deltaTimeInMs:a-n},correlationId:r,step:`mid-call`},i),i}}_dispose(){this.logger.log(`dispose`),this._participantChangedHandler&&this._participantChangedHandler.dispose(),this._mappedStreams.forEach((e=>e.dispose())),this._eventEmitter.emit(`stateChanged`,this._state),this._eventEmitter.removeAllListeners(),this._disposeVideo(0),this._disposeVideo(1)}get tsRemoteParticipant(){return this._tsParticipant}get kind(){return`RemoteParticipant`}setCallEndReason(e){this._callEndReason=e}observeParticipant(e){if(this._tsParticipant)return;let t=Z();this._tsParticipant=e,this._displayName=e.displayName,this._realDisplayName=e.displayName,this._isMuted=e.isServerMuted;let n=this.getParticipantDisplayNameOverride();t.calling.rename.enableShowEditedDisplayName&&n&&n!==this._displayName&&(this._displayName=n,this._hasDisplayNameChanged=!0),this._participantChangedHandler=this._tsParticipant.changed((()=>{this._tsParticipant&&this._tsParticipant.state!==this._lastTsParticipantState&&(this._lastTsParticipantState=this._tsParticipant.state,this._mapTsParticipantState(this._tsParticipant.state)),this._mapStreams(),this._tsParticipant&&this._tsParticipant.isServerMuted!==this._isMuted&&(this._isMuted=this._tsParticipant.isServerMuted,this._eventEmitter.emit(`isMutedChanged`));let n=this.getParticipantDisplayNameOverride();if(t.calling.rename.enableShowEditedDisplayName&&n&&n!==this._displayName){let e=K0(),t=this._displayName;this._displayName=n,this._hasDisplayNameChanged=n!==this._realDisplayName,this.logger.log(`display name changed ${t}=>${n}, correlationId=${e}`),this._eventEmitter.emit(`displayNameChanged`,{newValue:this._displayName,oldValue:t,reason:`editedDisplayName`}),this.sendDisplayNameOverrideEvent(e)}else if((!n||!t.calling.rename.enableShowEditedDisplayName)&&this._tsParticipant?.displayName&&this._tsParticipant.displayName!==this._displayName){let t=this._displayName;this._displayName=e.displayName,this._realDisplayName=e.displayName,this._eventEmitter.emit(`displayNameChanged`,{newValue:this._displayName,oldValue:t})}if(this._tsParticipant&&this._tsParticipant.advancedMeetingRole!==this._lastTsParticipantAdvancedRole&&(this._lastTsParticipantAdvancedRole=e.advancedMeetingRole,this._setParticipantRole(this._tsParticipant.advancedMeetingRole)),this._tsParticipant){let e=this._tsParticipant.voiceLevel!==0;e!==this._isSpeaking&&(this._isSpeaking=e,this._eventEmitter.emit(`isSpeakingChanged`))}})),this._mapTsParticipantState(this._tsParticipant.state),this._mapStreams(),this._lastTsParticipantAdvancedRole=this._tsParticipant.advancedMeetingRole,this._setParticipantRole(this._tsParticipant.advancedMeetingRole),this._displayName||!CG(this._identifier)&&!SG(this._identifier)||this.getRemoteParticipantProperties().then((e=>{e?.displayName&&(this._displayName=e.displayName,this._eventEmitter.emit(`displayNameChanged`))})).catch((e=>{this.logger.error(`Failed to get remote participant properties: ${e}`)}))}setParticipantState(e){e!==this._state&&(this.logger.log(`state changed ${this._state}=>${this.state}`),this._state=e,this._state==`Disconnected`?this._dispose():this._eventEmitter.emit(`stateChanged`,this._state))}async stopRenderingVideo(){this._disposeVideo(0)}async renderVideo(e,t){return typeof e==`function`?this._updateRenderingState(e,`Video`,t):await this._renderStreamForParticipant(e,0,t)}async _updateRenderingState(e,t,n){if(typeof e==`function`){let r,i=t===`Video`?0:1;this._tsParticipant&&(r=n?.stream?n.stream:new a7(this._tsParticipant.streams[i][0],this.logger,this._call,this._callAgent,this._tsParticipant,this._telemetryLogManager,this._identifier),r.on(`isReceivingChanged`,(()=>{this._renderers[t].renderingState.isFrozen=!r.isReceiving,e(this._renderers[t].renderingState)})),r.on(`isAvailableChanged`,(async()=>{this._renderers[t].renderingState.isStreaming!==r?.isAvailable&&(this._renderers[t].renderingState.isStreaming=r.isAvailable,this._renderers[t].renderingState.isStreaming&&!this._renderers[t].renderer&&(this._renderers[t].renderer=this._renderers[t]?.renderer?this._renderers[t].renderer:new O7(r),this._renderers[t].view||(this._renderers[t].view=await this._renderers[t].renderer?.createView(n?.viewOptions)),this._renderers[t].renderingState.videoTarget=this._renderers[t].view?.target)),e(this._renderers[t].renderingState)})))}}async renderScreenShare(e,t){return typeof e==`function`?this._updateRenderingState(e,`ScreenSharing`,t):this._renderStreamForParticipant(e,1,t)}async _renderStreamForParticipant(e,t,n){if(this._tsParticipant){let r=t===0?`Video`:`ScreenSharing`,i=n?.stream?n.stream:new a7(this._tsParticipant.streams[t][0],this.logger,this._call,this._callAgent,this._tsParticipant,this._telemetryLogManager,this._identifier);return i.isAvailable&&(this._renderers[r].view=await this._appendVideo(e,t,i,n?.viewOptions)),i.on(`isAvailableChanged`,(async()=>{i.isAvailable?this._renderers[r].view=await this._appendVideo(e,t,i,n?.viewOptions):this._renderers[r]?.view&&this._renderers[r].view?.target&&this._renderers[r].view?.target.parentNode?.removeChild(this._renderers[r].view?.target)})),Promise.resolve({stream:i,view:this._renderers[r]?.view})}return Promise.reject()}async _appendVideo(e,t,n,r){try{let i=t===0?`Video`:`ScreenSharing`;if(t===0&&(this._renderers[i]?.renderer||(this._renderers[i].renderer=this._renderers[i]?.renderer?this._renderers[i].renderer:new O7(n),this._renderers[i].view=await this._renderers[i].renderer?.createView(r)),this._renderers[i].view))return e.appendChild(this._renderers[i].view?.target||document.createElement(`emptyNode`)),Promise.resolve(this._renderers[i].view)}catch(e){return Promise.reject(e)}return Promise.reject()}async _disposeVideo(e){let t=e===0?`Video`:`ScreenSharing`;this._renderers[t].view?.dispose(),this._renderers[t].renderer?.dispose(),this._renderers[t]={renderingState:{}}}_setParticipantRole(e){let t=iTe(Z(),e);t===`Unknown`?this.logger.log(`tsParticipant advancedMeetingRole=${e} had no mapping`):this.logger.log(`mapped tsParticipant advancedMeetingRole=${e}=>${t}`),this._role!=t&&(this.logger.log(`role changed ${this._role}=>${e}`),this._role=t,this._eventEmitter.emit(`roleChanged`))}_mapTsParticipantState(e){let t,n={0:`Idle`,1:`Connecting`,2:`Ringing`,3:`Connected`,4:`Disconnected`,5:`Hold`,7:`InLobby`,6:`EarlyMedia`};n[e]?(t=n[e],this.logger.log(`mapped tsParticipant ${e}=>${this._state}`),this.setParticipantState(t)):this.logger.log(`unable to map tsCall state=${e} to call state`)}_mapStreams(){let e=[],t=[],n=e=>{this._mappedStreams.set(e.id,e)},r=e=>{let t=this._mappedStreams.get(e.id);t&&(this.logger.log(`stream removed, type==${t.mediaStreamType} id=${e.id}`),this._mappedStreams.delete(e.id),t.dispose())},i=n=>{if(this._tsParticipant)if(this._tsParticipant.streams&&ywe(this._tsParticipant.streams[n])){let r=[];this._tsParticipant&&(r=this._tsParticipant.streams[n]),r.forEach((t=>{if(!this._mappedStreams.get(t.id)){let n=new a7(t,this.logger,this._call,this._callAgent,this._tsParticipant,this._telemetryLogManager,this._identifier);this.logger.log(`stream created, type==${n.mediaStreamType} id=${t.id}`),e.push(n)}})),this._mappedStreams.forEach((e=>{this.acsToTsStreamType(e.mediaStreamType)===n&&(r.some((t=>t.id===e.id))||t.push(e))}))}else this._mappedStreams.forEach((e=>{this.acsToTsStreamType(e.mediaStreamType)===n&&t.push(e)}))};i(0),i(1),(e.length>0||t.length>0)&&(e.forEach(n),t.forEach(r),this._eventEmitter.emit(`videoStreamsUpdated`,{added:e,removed:t}))}sendAudioEvent(e,t){try{let n,r;t&&(n=t.message,r=K3(t));let i={callId:this._call.id,timestampInfo:e.timestampInfo,correlationId:e.correlationId,step:e.step||``,failureReason:n||``,additionalDetails:{...r}};e.eventType!==void 0&&(i.eventType=e.eventType),this._telemetryLogManager.sendEvent({name:e.eventName,tenant:d2,properties:i})}catch{this.logger.debug(`Unable to send mute others audio telemetry`)}}sendDisplayNameOverrideEvent(e){if(this._telemetryLogManager)try{let t={callId:this._call.id,timestampInfo:{attemptTimestamp:+new Date},correlationId:e,step:`event`};this._telemetryLogManager.sendEvent({name:Q.acs_calling_edited_display_name,tenant:d2,properties:t})}catch{this.logger.debug(`Unable to send display name override event telemetry`)}}getRemoteParticipantProperties(){return new Promise((e=>{let t={policyUrlSuffix:Z().MiddleTier.policyUrlSuffixV2,userPolicies:[`TeamsMeetingPolicy`],userProperties:[`displayName`]};this._callAgent.mtPolicyService.requestUserPoliciesFromAcsMiddleTier(this._call.id,W2(this.identifier),t,this._callAgent.getUserMri()).then((t=>{e(t.userAggregatedPolicySettingData?.userProperties)}))}))}};YIe([zG,k7(`design:type`,Object)],A7.prototype,`logger`,void 0),YIe([GG(s4.Mute),k7(`design:type`,Function),k7(`design:paramtypes`,[]),k7(`design:returntype`,Promise)],A7.prototype,`mute`,null);var XIe=class{constructor(e){this._deviceManager=e,this._eventEmitter=new w3.EventEmitter,this._selectedDeviceListeners=new Map,this._selectedDevices=new Map,this._deviceInfoMapper=this._deviceManager.deviceInfoMapper;let t=e=>()=>{let t=this._selectedDevices.get(e),n=e===`Speaker`?this._deviceManager.selectedSpeaker:e===`Microphone`?this._deviceManager.selectedMicrophone:void 0,r=n===void 0?void 0:{id:this._deviceInfoMapper.getDeviceId(n.id),name:this._deviceInfoMapper.scrubDeviceLabel(n.name)};this._selectedDevices.set(e,r),this._eventEmitter.emit(`selectedDeviceChanged`,{selectedDeviceType:e,oldDevice:t,newDevice:r})},n=t(`Speaker`);this._selectedDeviceListeners.set(`Speaker`,n),this._deviceManager.on(`selectedSpeakerChanged`,n),n();let r=t(`Microphone`);this._selectedDeviceListeners.set(`Microphone`,r),this._deviceManager.on(`selectedMicrophoneChanged`,r),r()}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}selectedDevice(e){return this._selectedDevices.get(e)}dispose(){let e=this._selectedDeviceListeners.get(`Speaker`);e&&this._deviceManager.off(`selectedSpeakerChanged`,e);let t=this._selectedDeviceListeners.get(`Microphone`);t&&this._deviceManager.off(`selectedMicrophoneChanged`,t),this._eventEmitter.removeAllListeners()}};function j7(e,t,n,r){let i=r===I2.RoomCall||e.kind===VG.Call&&e.direction==`Incoming`&&!e.tsCall.groupId&&!!e.tsCall.meetingData?.meetingCode&&!e.tsCall.threadId,a=!i&&r===I2.TeamsMeetingLink||r===I2.TeamsMeetingId||r===I2.TeamsCoordinates||e.direction==`Incoming`&&!e.tsCall.groupId&&!!e.tsCall.meetingData&&!!e.tsCall.threadId,o={audio:``,video:``},s=e.localAudioStreams?.[0];s&&(o.audio=s.getEffectsCurrentStateRecord()??``);let c=e.localVideoStreams?.[0];return c&&(o.video=c.getEffectsCurrentStateRecord()??``),{timestampInfo:{attemptTimestamp:+new Date},correlationId:n,localParticipantId:e.tsCall.participantId||``,isAcsTeamsCall:e.isAcsTeamsCall,callId:e.tsCall.callId||``,callType:e.tsCall.callType||``,callDirection:e.direction,state:e.state===`Ringing`?`Ringing`:$Ee[e.tsCall.state],groupJoin:!!e.tsCall.groupId,roomJoin:i,meetingJoin:a,callEndDiagnosticsInfo:e.tsCall.callEndDiagnosticsInfo||{},isSupportedEnvironment:t?.runningEnvironmentInfo?.isSupportedEnvironment,effectsStateInfo:o,hostRegion:e.tsCall.region||``,diagnosticInfo:{...e.tsCall.callEndDiagnosticsInfo,telemetryPayloadBytesOriginal:f3.telemetryPayloadBytesOriginal,telemetryPayloadBytesCompressed:f3.telemetryPayloadBytesCompressed}}}function M7(e,t,n){try{n.step===`state-changed`&&n.newState===`Connecting`&&(f3.telemetryPayloadBytesOriginal=0,f3.telemetryPayloadBytesCompressed=0),e.sendEvent({name:Q.acs_calling_call_progress,tenant:d2,properties:n})}catch{t.error(`Failed to send event: ${Q.acs_calling_call_progress} step: ${n.step}`)}}var ZIe=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},N7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},P7=class{get threadId(){return this._threadId}get roomId(){return this._roomId}get groupId(){return this._groupId}get participantId(){return this._tsCall.participantId}get isPstnInterop(){return this._isPstnInterop}get isTeamsInterop(){return this._isTeamsInterop}get callScenario(){if(this._tsCall.callQueueInfo)return _4.CallQueue;if(this.transferorKind!==`unknown`){if(this._tsCall.incomingCallType===`transfer`)return _4.TransferToParticipant;if(this._tsCall.incomingCallType===`replaces`)return _4.TransferToCall}return this.direction===`Incoming`?`AcceptCall`:this.direction===`Outgoing`&&this.context==`Rooms`?_4.JoinRoom:this.direction===`Outgoing`&&this.context==`TeamsMeeting`?_4.JoinTeamMeeting:this.direction===`Outgoing`&&this.context==`GroupIdCall`?_4.JoinWithGroupId:_4.PlaceCall}get context(){return this._tsCall.callType==1||this._currentCallContext==v4.TwoParty?v4.TwoParty:this._tsCall.groupId?v4.GroupIdCall:this._tsCall.conversationType==`groupCall`||this._currentCallContext==v4.MultiParty?v4.MultiParty:this._config?.roomId||this._roomId||this._tsCall.meetingData?.meetingCode?.startsWith(`994`)||this._tsCall.meetingData?.meetingCode?.startsWith(`995`)||this._tsCall.meetingData?.meetingCode?.startsWith(`996`)?v4.Rooms:this._tsCall.meetingData?.meetingUrl||this._tsCall.meetingData?.passcode||this._tsCall.conversationType==`scheduledMeeting`?v4.TeamsMeeting:(this._tsCall.callType,v4.MultiParty)}get transferorKind(){return this._tsCall.transferorMri?G2(this._tsCall.transferorMri||``).kind:``}get direction(){return this._config?.isIncoming?r4.Incoming:r4.Outgoing}get initiatorKind(){return G2(this._tsCall.callerMri?this._tsCall.callerMri:``).kind}get targetKind(){return this._tsCall.groupId?this._tsCall.groupId:this._config?.roomId?this._config.roomId:this._tsCall.meetingData?.meetingUrl||this._tsCall.meetingData?.meetingCode?`TeamsMeetingJoinLink`:this._tsCall.transferorMri?`Transferee`:this._tsCall.participants.length===1?G2(this._tsCall.participants[0].id).kind:this._tsCall.participants.filter((e=>e.id!==this._tsCall.callerMri)).map((e=>G2(e.id).kind)).toString()}constructor(e,t={}){this._tsCall=e,this._threadId=this._tsCall.threadId;let n=this._tsCall.groupId;this._groupId=!n||n.startsWith(`19:`)||n.startsWith(`99:`)?void 0:n,this._roomId=t?.config?.roomId,this._config=t.config,this._isPstnInterop=!1,this._isTeamsInterop=!1}setThreadId(e){this._threadId=e}initialize(e,t,n){this._logger=t,this._eventEmitter=e,this._threadId=this._tsCall.threadId,this._tsCallChangedListener=this._tsCall.changed((()=>this.threadIdChanged(this._tsCall))),this._p2pCallListener=this._tsCall.changed((()=>this.p2pCallHandler())),this._isPstnInterop=this.isPSTNUserInCall,this._isTeamsInterop=this.isTeamsUserInCall,this._participantUpdatedListener=this._tsCall.on(`participantCountsUpdated`,(()=>{this.interoperabilityChangeHandler(),this.p2pCallEscalationHandler()}))}async getServerCallId(){let e=JSON.parse(await this._tsCall.getJoinBlob())?.conversationUrl;if(!e)throw new Y({defaultError:J.CALL.GET_SERVER_CALL_ID});return xFe(e)}p2pCallHandler(){this._currentCallContext==null&&this._tsCall.callType==1&&(this._currentCallContext=v4.TwoParty)}p2pCallEscalationHandler(){this._currentCallContext==v4.TwoParty&&F4(this._tsCall)>2&&(this._currentCallContext=v4.MultiParty,this._eventEmitter.emit(`callInfoChanged`),this._p2pCallListener?.dispose())}get isTeamsUserInCall(){if(!this._tsCall.participants)return!1;for(let e of this._tsCall.participants)if(G2(e.id).kind===`microsoftTeamsUser`)return!0;return!1}get isPSTNUserInCall(){if(!this._tsCall.participants)return!1;for(let e of this._tsCall.participants)if(G2(e.id).kind===`phoneNumber`)return!0;return!1}interoperabilityChangeHandler(){!this._isPstnInterop&&this.isPSTNUserInCall&&(this._isPstnInterop=!0,this._eventEmitter.emit(`callInfoChanged`)),!this._isTeamsInterop&&this.isTeamsUserInCall&&(this._isTeamsInterop=!0,this._eventEmitter.emit(`callInfoChanged`))}threadIdChanged(e){this._tsCall.threadId!==this._threadId&&(this._logger.log(`threadId changed from ${this._threadId} to ${e?.threadId}`),this._threadId=this._tsCall.threadId,this._eventEmitter.emit(`threadIdChanged`))}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}onCallInfoChanged(e,t){this._eventEmitter.on(e,t)}offCallInfoChanged(e,t){this._eventEmitter.off(e,t)}dispose(){this._tsCallChangedListener?.dispose(),this._eventEmitter.removeAllListeners(),this._p2pCallListener?.dispose(),this._participantUpdatedListener?.dispose()}};ZIe([GG(Owe.GetServerCallId),N7(`design:type`,Function),N7(`design:paramtypes`,[]),N7(`design:returntype`,Promise)],P7.prototype,`getServerCallId`,null);var QIe=class e{constructor(){this.CAUSE_ID_TO_NETWORK_INFO={}}static getInstance(){return this.instance||=new e,this.instance}deleteNetworkInfo(e){delete this.CAUSE_ID_TO_NETWORK_INFO[e]}ifCauseIdExistsRemoveNetworkInfo(e){return this.CAUSE_ID_TO_NETWORK_INFO[e]&&this.CAUSE_ID_TO_NETWORK_INFO[e].length===0?!!this.getRemoveCauseIdToNetworkInfo(e):!!this.CAUSE_ID_TO_NETWORK_INFO[e]}getRemoveCauseIdToNetworkInfo(e){if(!Z().telemetry.sendNetworkInfo)return;let t=this.CAUSE_ID_TO_NETWORK_INFO[e];return t&&this.deleteNetworkInfo(e),t}setCauseIdToNetworkInfo(e,t){Object.keys(this.CAUSE_ID_TO_NETWORK_INFO).length>100&&(this.CAUSE_ID_TO_NETWORK_INFO={}),t?this.CAUSE_ID_TO_NETWORK_INFO[e]?this.CAUSE_ID_TO_NETWORK_INFO[e].push({url:t.url,statusCode:t.statusCode,start:t.start,end:t.end,deltaTimeInMs:t.deltaTimeInMs,causeId:t.causeId}):this.CAUSE_ID_TO_NETWORK_INFO[e]=[{url:t.url,statusCode:t.statusCode,start:t.start,end:t.end,deltaTimeInMs:t.deltaTimeInMs,causeId:t.causeId}]:this.CAUSE_ID_TO_NETWORK_INFO[e]=[]}};QIe.instance=null;var F7=QIe.getInstance(),$Ie=class e{constructor(e,t,n,r){this._recordingConsentEnabled=!1,this._consentActivelyRequired=!1,this._localParticipantConsentPublishState=!1,this._isExplicitConsentEnabled=!1,this._isInitialized=!1,this._isExplicitConsentEnabled=Z().calling.explicitConsentFeatureEnabled.enabled,this.initialize(e,t,n,r)}dispose(){this._isInitialized=!1,this._recordingConsentEnabled=!1,this._consentActivelyRequired=!1,this._localParticipantConsentPublishState=!1,e.instance=null}isConsentRequiredInCall(){if(!this._isExplicitConsentEnabled)return!1;let e=this._recordingConsentEnabled&&!this._localParticipantConsentPublishState;return this._logger.info(`ExplicitConsentCallStateManager: isConsentRequiredInCall: Recording Consent Enabled: `+this._recordingConsentEnabled+` Local Participant Consent Publish State: `+this._localParticipantConsentPublishState),this._logger.log(`ExplicitConsentCallStateManager: isConsentRequiredInCall: `+e),e}async consent(e){if(this._isExplicitConsentEnabled){if(e.context===v4.TwoParty)throw this._logger.warn(`Consent for recording is not supported for 1:1 calls`),new Y({defaultError:J.CALL.CONSENT_NOT_SUPPORTED_1TO1});if(!this.isConsentRequiredInCall())throw new Y({defaultError:J.CALL.CONSENT_ALREADY_SET_OR_NOT_REQUIRED});try{if(!await this._tsCall.publishState({level:`user`,type:`consentToRecording`,content:`{}`},AG()))throw this._logger.error(`Consent failure to set publish state for user`),new Y({defaultError:J.CALL.FAILED_TO_SET_CONSENT});this._logger.log(`ExplicitConsentCallStateManager: Consent for the call provided successfully`)}catch(e){throw this._logger.error(`Consent failure to set publish state for user on service side`),e}}}areCoreCapabilitiesConsentRestricted(){if(!this._isExplicitConsentEnabled)return!1;let e=this._consentActivelyRequired&&!this._localParticipantConsentPublishState;return this._logger.info(`ExplicitConsentCallStateManager: areCoreCapabilitiesConsentRestricted: Consent Actively Required: `+this._consentActivelyRequired+` Local Participant Consent Publish State: `+this._localParticipantConsentPublishState),this._logger.log(`ExplicitConsentCallStateManager: areCoreCapabilitiesConsentRestricted: `+e),e}offConsentRestrictionChanged(e,t){if(e!==`consentRestrictionChanged`)throw Error(`ExplicitConsentCallStateManager: OffConsentRestrictionChanged - Invalid event`);this._logger.log(`ExplicitConsentCallStateManager: Unsubscribing to consentRestrictionChanged event`),this._eventEmitter.off(e,t)}onConsentRestrictionChanged(e,t){if(e!==`consentRestrictionChanged`)throw Error(`ExplicitConsentCallStateManager: onConsentRestrictionChanged - Invalid event`);this._logger.log(`ExplicitConsentCallStateManager: Subscribing to consentRestrictionChanged event`),this._eventEmitter.on(e,t)}initialize(e,t,n,r){this._isExplicitConsentEnabled&&(this._isInitialized||=(this._logger=r.createChild((()=>`Explicit Consent::Call(id='${e.callId}', state='${e.state}')`)),this._tsCall=e,this._callAgent=t,this._eventEmitter=n,e.changed((()=>{if(!0===e.meetingDetails?.recordingConsentDetails?.explicitRecordingConsentEnabled){this._recordingConsentEnabled=!0;let t=!0===e.meetingDetails?.recordingConsentDetails?.consentActivelyRequired;t!==this._consentActivelyRequired&&(this._consentActivelyRequired=t,this._eventEmitter.emit(`consentRestrictionChanged`))}})),e.on(`publishedStatesChanged`,(async e=>{this._localParticipantConsentPublishState=!1,this._handleConsentStateChange(e)})),!0))}_handleConsentStateChange(e){if(!0!==this._localParticipantConsentPublishState){let n=this._callAgent.getUserMri();var t=!1;e&&this._getPublishedState(e).forEach((e=>{e.participantStates.forEach((e=>{if(e.id===n)return this._logger.log(`ExplicitConsentCallStateManager: Handle Consent State changes: Local participant has provided the consent`),void(t=!0)}))})),this._localParticipantConsentPublishState=t,t&&this._eventEmitter.emit(`consentRestrictionChanged`)}}_getPublishedState(e){return e.typeStates.filter((e=>[`consentToRecording`].includes(e.type)))}};$Ie.instance=null;var eLe=class{constructor(e,t){this._interval=0,this._ufds=new Map,this._interval=t,e.forEach((e=>{this._ufds.set(e,{_lastRecovered:new Date,_shouldNotifyError:!0,_shouldNotifyRecovery:!0})}))}updateLastRecoveredTime(e,t){let n=this._ufds.get(e);n&&(n._lastRecovered=new Date(t.getTime()+this._interval),n._shouldNotifyError=!0,n._shouldNotifyRecovery=!1)}shouldLogError(e,t){let n=this._ufds.get(e);if(n){let e=n._lastRecovered<=t&&n._shouldNotifyError;return e&&(n._shouldNotifyError=!1,n._shouldNotifyRecovery=!0),e}return!0}shouldLogRecovery(e,t){let n=this._ufds.get(e);if(n){let r=n._shouldNotifyRecovery;return r&&this.updateLastRecoveredTime(e,t),r}return!0}},tLe,I7=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},L7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},R7=class e{get id(){return this._id}get callerInfo(){return{identifier:this._callerIdentity,displayName:this._callerDisplayName}}get transferorInfo(){if(this._transferorIdentity)return{identifier:this._transferorIdentity,displayName:this._transferorDisplayName}}get state(){return this._state}get role(){return this._role}get callEndReason(){return this._callEndReason}get kind(){return this._kind}get direction(){return this._direction}get isMuted(){return this._isMuted}get isScreenSharingOn(){return this._isScreenSharingOn}get isLocalVideoStarted(){return this._isLocalVideoStarted}get localVideoStreams(){return this._localVideoStreams}get localAudioStreams(){return this._localAudioStreams}get isIncomingAudioMuted(){return this._isIncomingAudioMuted}get remoteParticipants(){return this._remoteParticipants}get totalParticipantCount(){return this._totalParticipantCount}get lobby(){return this._lobby}get isAcsTeamsCall(){return this._isAcsTeamsCall}get isIPAudioEnabled(){return this.callInfo.context===v4.TwoParty||this._allowIPAudio}get isIPVideoEnabled(){return this.callInfo.context===v4.TwoParty||this._allowIPVideo}get isEnterpriseTeamsCall(){return this._isEnterpriseTeamsCall}subscribeToGetRemoteAudioStream(){if(!this._rawAudioStreamChangedSubscription)try{let e=this.tsCall.getIncomingRawAudioStream(),t=async()=>{try{if(this._remoteAudioStreams.length===0){if(!await e.getMediaStream())throw new Y({defaultError:J.CALL.REMOTE_AUDIO_GET_MEDIA_STREAM_UNDEFINED});this._remoteAudioStreams.push(new hIe(e,this._telemetryLogManager,this.id,this.tsCall.participantId)),this._eventEmitter.emit(`remoteAudioStreamsUpdated`,{added:this._remoteAudioStreams,removed:[]})}else if(await e.getMediaStream())this._eventEmitter.emit(`remoteAudioStreamsUpdated`,{added:[],removed:[]});else{let e=this._remoteAudioStreams[0];e.dispose(),this._remoteAudioStreams=[],this._eventEmitter.emit(`remoteAudioStreamsUpdated`,{added:[],removed:[e]})}}catch(e){throw new Y({defaultError:J.CALL.REMOTE_AUDIO_GET_MEDIA_STREAM_RETURNED_ERROR,originalError:e})}};this._rawAudioStreamChangedSubscription=e.changed((()=>{this.logger.info(`Changed fired ${this.tsCall.state}, ${this.state}`),t().catch(A4)})),t().catch((()=>{this.logger.info(`Failed to update remote audio stream collection, retrying on changed`)}))}catch{this.logger.info(`Failed to get raw audio stream from the stack`)}}get remoteAudioStreams(){if(!Z().calling.allowAccessRawMediaStream)throw new Y({defaultError:J.CALL.REMOTE_AUDIO_GET_MEDIA_STREAM_DISABLED});return this._remoteAudioStreams}get deviceManager(){return this._callAgent.deviceManager}get mediaConstraintsManager(){return this._mediaConstraintsManager}get isHandlingLargeMeetingVideoRendering(){return this._isHandlingLargeMeetingVideoRendering}get callInfo(){return this._callInfo}get networkQualityUfdEventDetails(){return this._networkQualityUfdEventDetails}get acsProxy(){return this._callAgent.acsProxy}get acsCustomRelayManager(){return this._callAgent.acsCustomRelayManager}get audioEffectsProcessorStats(){return this._audioEffectsProcessorStats}get callAgent(){return this._callAgent}get iceServers(){return this._getIceServersCalledOnce||(this._getIceServersCalledOnce=!0,this._iceServers=this.tsCall.getMediaSessionStats()?.extensions?.IceServers),this._iceServers}get watermarkAudioOnlyFallbackTriggered(){return this._watermarkAudioOnlyFallbackTriggered}constructor(e,t,n,r,i,a){this._callAgent=t,this._isMuted=!1,this._isMuted_correlationIdCache=K0(),this._isIncomingAudioMuted=!1,this._isIncomingAudioMuted_correlationIdCache=K0(),this._isScreenSharingOn=!1,this._isLocalVideoStarted=!1,this._localVideoStreams=[],this._localAudioStreams=[],this._remoteAudioStreams=[],this._totalParticipantCount=1,this._isDeviceNotFunctioningMuted=!1,this.__attemptedToRecoverMicNotFunctioningBySDK=!1,this._isMicrophoneMuted=!1,this._disposed=!1,this._lastTsCallState=0,this._isSpeakerMuted=!1,this._callMode=0,this._role=w2,this._lastTsCallMeetingDetails={},this._isHandlingLargeMeetingVideoRendering=!1,this._joinContextDescription=I2.Unknown,this._remoteParticipantsChangedListeners=[],this._localRingingStateSet=!1,this._networkQualityUfdEventDetails=[],this._audioEffectsProcessorStats=null,this._getIceServersCalledOnce=!1,this._watermarkAudioOnlyFallbackTriggered=!1,this._transportStateTimestamp=new Map,this._setOrUpdateDeviceEventsTask=Promise.resolve(),this._isAcsTeamsCall=!1,this._isEnterpriseTeamsCall=this._callAgent.isEnterpriseUser(),this._isTeamsExtensionUser=this._callAgent.isTeamsExtensionUser(),this._mriToRemoteParticipantMap=new Map,this._remoteParticipants=[],this._state=`None`,this._transportState=`None`,this._allowIPAudio=!0,this._allowIPVideo=!0,this.localVideoStream=void 0,this.localScreenSharingStream=void 0,this.isRenderingRemoteScreenShare=!1,this._handleMuteChanges=()=>{let e=[v4.Rooms,v4.GroupIdCall,v4.MultiParty,v4.TeamsMeeting].some((e=>e===this._callInfo.context)),t=this.tsCall.conversationType||e?!!(this.tsCall.isMuted||this.tsCall.state!==10&&this.tsCall.isServerMuted||this._isDeviceNotFunctioningMuted):!(!this.tsCall.isMuted&&!this._isDeviceNotFunctioningMuted);if(this._isMuted!=t){this.logger.info(`isMuted changed from ${this._isMuted} to ${t}`);let e=[];this.tsCall.isMuted&&e.push(`isMicrophoneMuted`),this.tsCall.isServerMuted&&(e.push(`isServerMuted`),[3,4,5].some((e=>e===this.tsCall.state))&&this._eventEmitter.emit(`mutedByOthers`),this.explicitConsentStateImp.areCoreCapabilitiesConsentRestricted()&&this.handleConsentCapabilitiesChanges()),this._isDeviceNotFunctioningMuted&&e.push(`isDeviceNotFunctioningMuted`);let n=``;e.length>=1&&(n=e.join(`, `)),t&&(this._isMuted_correlationIdCache=K0()),M7(this._telemetryLogManager,this.logger,{...j7(this,this._callAgent,this._isMuted_correlationIdCache,this._joinContextDescription),step:`isMuted-changed`,oldIsMuted:this._isMuted,newIsMuted:t,reason:n}),this._isMuted=t,this._eventEmitter.emit(`isMutedChanged`)}},this.audioSourceChanged=async e=>{this._telemetryLogManager.sendEvent({name:Q.acs_calling_local_audio_source_changed,tenant:d2,properties:{callId:this.id,localParticipantId:this.tsCall.participantId,timestampInfo:+new Date,correlationId:K0(),localAudioStream:e.source?.source instanceof MediaStream?`MediaStream`:`Device`}}),e.source instanceof Y6?(this.localAudioStreams[0]&&this.localAudioStreams[0].mediaStreamType===`RawMedia`&&this.stopAudioInternal(!0),await(await this._callAgent.tsStack?.getDeviceManagerAsync?.())?.selectDevicesAsync?.({microphone:e.source.id})):await this.startAudioInternal(e.source,!0)},this._handleIncomingAudioMuteChanges=()=>{let e=this._isSpeakerMuted;this._isIncomingAudioMuted!=e&&(this.logger.info(`newIncomingAudioMuted changed from ${this._isIncomingAudioMuted} to ${e}`),e&&(this._isIncomingAudioMuted_correlationIdCache=K0()),M7(this._telemetryLogManager,this.logger,{...j7(this,this._callAgent,this._isIncomingAudioMuted_correlationIdCache,this._joinContextDescription),step:`isIncomingAudioMuted-changed`,oldIsMuted:this._isIncomingAudioMuted,newIsMuted:e,reason:``}),this._isIncomingAudioMuted=e,this._eventEmitter.emit(`isIncomingAudioMutedChanged`))},this._id=e.callId,this.tsCall=n,this._direction=e.isIncoming?`Incoming`:`Outgoing`,this._config=e,this.logger=this._callAgent.logger.createChild((()=>`Call:${this._id}:${this._state}`)),this._telemetryLogManager=r,this.stats=new dIe(this.logger,this._telemetryLogManager),this._eventEmitter=new S6(this.logger),this.activeRemoteVideoStreamViews=new Map,this.isSubscribedCall=!1,this.isBreakoutRoomCall=!1,this._mediaMetricsDeviceEvents={},this._kind=i,this._optimalVideoCount=1,this._ufdsCorrelationIdCache=dTe(),this._callInfo=new P7(n,{config:e}),this._callInfo.initialize(this._eventEmitter,this.logger,this._telemetryLogManager),this._ufdLogThrottler=new eLe([27],Z().telemetry.speakingWhileMutedThrottleInterval),Z().calling.mediaMetricsDeviceEventsEnabled&&(async()=>{let e=await this._callAgent.tsStack?.getDeviceManagerAsync?.();e&&(this._dmDevicesChangedSub=e.on(`devicesChanged`,(()=>{this._setOrUpdateDeviceEventsTask=this._setOrUpdateDeviceEventsTask.then((()=>this.setOrUpdateMediaMetricsDeviceEvents().catch(A4)))})))})().catch((e=>{this.logger.error(`Failed to register devicesChanged event: ${e}`)})),this._extensibleApi=new N3(this.logger,{call:this,callAgent:this._callAgent,callInfo:this._callInfo},{tsCall:this.tsCall,callAgent:this._callAgent,call:this,telemetryLogManager:this._telemetryLogManager}),this.explicitConsentStateImp=new $Ie(this.tsCall,t,this._eventEmitter,this.logger),this._capabilityResolver=new CDe(this._eventEmitter,this.logger,this,this._callInfo,t,n),this._lobby=new n7(this.tsCall,this,this.logger,this._telemetryLogManager);let o=Q5(D3.CallFeature);for(let e of o)e.activationOptions.activationEvent===`OnExtendedObjectConstructor`&&this.feature(e);this._mmrRdpConnectionManager=new bIe(this.logger),Z().telemetry.sendNetworkChangedTelemetry&&this._sendNetworkChangedTelemetry(),Z().telemetry.deviceChangedEvents.enabled&&(this._selectedDeviceManager=new XIe(this.deviceManager),this._setupSelectedDeviceChangedTelemetry()),this._mediaConstraintsManager=new vIe(this.tsCall,this.logger,this._telemetryLogManager),this._isAcsTeamsCall=a??!1,this.feature(Z5.MediaAccess).on(`localParticipantMediaAccessChanged`,(e=>{this.logger.info(`Call common, time when received localParticipantMediaAccessChanged event: ${new Date().getTime()}, isAudioPermitted=${e.mediaAccess.isAudioPermitted}, isVideoPermitted=${e.mediaAccess.isVideoPermitted}`),!1===e.mediaAccess.isVideoPermitted&&this.localVideoStream&&this.stopVideo(this.localVideoStream)})),this.explicitConsentStateImp.onConsentRestrictionChanged(`consentRestrictionChanged`,(()=>{this.logger.info(`Call common, time when received explicitConsentStateChanged event:=\n ${this.explicitConsentStateImp.areCoreCapabilitiesConsentRestricted()}`),this.handleConsentCapabilitiesChanges()}))}async accept(e={}){let t=e.audioOptions?.muted??!1,n=this.getLocalVideoStreamFromCallOptions(e),r=this.getLocalAudioStreamFromCallOptions(e),i=+new Date,a=this._callAgent.getEcsConfigIds(),o=fTe(this.tsCall),s=K0(),c=jG(s),l=this.createVideoNegotiationTag(s,`Video`),u={joinContextDescription:``,additionalProperties:{EmergencyCountryCode:this._callAgent._caConfigBag?.emergencyCountryCode||``,IsUserEmergencyCountryCode:this._callAgent._caConfigBag?.IsUserEmergencyCountryCode||!1,IsEmergencyCall:this._isEmergencyCall,trouterState:this._callAgent.getTrouterState(),muted:t,withVideo:this.isIPVideoEnabled&&!!n,withAudio:this.isIPAudioEnabled&&r?.mediaStreamType?r?.mediaStreamType:``,...r7(),AcsCallingSDKWeb_ecsConfigId:a.AcsCallingSDKWeb,SkypeWebMedia_ecsConfigId:a.SkypeWebMedia,customContext:{userToUserPresent:!!o?.userToUser,xHeadersPresent:!!o?.xHeaders&&o.xHeaders.length>0},mediaModalities:this.getMediaModalityTelemetry(e?.mediaModalities),negotiationTag:l,causeId:c},additionalDetails:{}},d=(e,t,a)=>{let o=+new Date,d={...u},f;if(t){let t={message:J.CALL.ACCEPT_INCOMING_CALL.message,code:J.CALL.ACCEPT_INCOMING_CALL.code,subCode:J.CALL.ACCEPT_INCOMING_CALL.subCode,resultCategories:J.CALL.ACCEPT_INCOMING_CALL.resultCategories},{callEndReason:n,callingCommunicationError:r,hasDiagnosticsInfo:i}=V3(this,e,t);i?d.additionalDetails.callEndReason=n:d.additionalDetails.communicationServicesError=K3(r).communicationServicesError,f=r}else f=new Y({defaultError:J.CALL.ACCEPT_INCOMING_CALL,originalError:e}),d.additionalDetails.communicationServicesError=K3(f).communicationServicesError;if(this.sendCallStageEvent({eventName:Q.acs_calling_call_accept_failed,correlationId:s,timestampInfo:{deltaTimeInMs:o-i},additionalPayload:d},f,void 0,a?F7.getRemoveCauseIdToNetworkInfo(a):void 0),n){let e=+new Date;f=new Y({defaultError:J.LOCAL_VIDEO_STREAM.CALL_NOT_FOUND}),this.logger.error(f.message),this.sendVideoEvent({correlationId:s,eventName:Q.acs_calling_start_video_failure,timestampInfo:{deltaTimeInMs:e-i},localVideoStream:n,step:`accept`,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:l,causeId:c}},f),this.removeLocalVideoStream(n)}return r&&this.removeLocalAudioStream(r),f};try{if(e?.videoOptions?.constraints){let t=this._mediaConstraintsManager.getTelemetryPayload({video:e?.videoOptions?.constraints});u.additionalProperties.constraints=t}u.additionalProperties.negotiationTag=l,u.additionalProperties.causeId=c,this.sendCallStageEvent({eventName:Q.acs_calling_call_accept_attempt,correlationId:s,timestampInfo:{attemptTimestamp:i},additionalPayload:u});let a={...u};if(n&&this.setLocalVideoStream(n),this.setLocalAudioStream(r),n&&this.sendVideoEvent({eventName:Q.acs_calling_start_video_attempt,timestampInfo:{attemptTimestamp:i},correlationId:s,step:`accept`,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:l,causeId:c}}),this.tsCall.state!==1)throw new Y({defaultError:J.CALL.ACCEPT_NOT_RINGING});try{if(e?.videoOptions?.constraints){let t=await this._mediaConstraintsManager.setVideoConstraints(e?.videoOptions?.constraints,`accept`,s,i),n=this._mediaConstraintsManager.getTelemetryPayload({video:t});a.additionalProperties.constraints=n}}catch(e){let t=new Y({defaultError:J.CALL.ACCEPT_VIDEO_CONSTRAINTS,originalError:e});this.logger.error(`${t.message}`)}let o={withVideo:!!n&&this.isIPVideoEnabled,muted:t};if(t&&(o.muteFlags=1),o.sendMediaModalities=this.setMediaModalities(e?.mediaModalities),Z()?.calling?.enableCustomTurnUsage&&this.acsCustomRelayManager?.customRelayManagerInUse&&(o.mediaConfiguration={connectionType:`NoDirectConnection`}),r&&await this.startAudioInternal(r,!0).catch((e=>{this.logger.error(`Failed to start localAudioStream, message=${e?.message}`)})),n?.mediaStreamType===`RawMedia`)try{await this._setRawStream(n,1)}catch(e){let t=+new Date,r=new Y({defaultError:J.LOCAL_VIDEO_STREAM.VIDEO_GET_MEDIA_STREAM,originalError:e});this.sendVideoEvent({correlationId:s,eventName:Q.acs_calling_media_stream,timestampInfo:{deltaTimeInMs:t-i},localVideoStream:n,step:`accept`,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:l,causeId:c}},r),this.removeLocalVideoStream(n)}let f=AG();return F7.setCauseIdToNetworkInfo(f),this.tsCall.accept(o,f).then((async()=>{let e=+new Date;n&&this.shallRemoveLvsAfterConnectedSuccessfully(n,`accept`,s,e,i,l,c),r&&this.shallRemoveLasAfterConnectedSuccessfully(r,`accept`,s,e,i),a.additionalProperties.negotiationTag=l,a.additionalProperties.causeId=c,this.sendCallStageEvent({eventName:Q.acs_calling_call_accept_connected,correlationId:s,timestampInfo:{deltaTimeInMs:e-i},additionalPayload:a},void 0,void 0,F7.getRemoveCauseIdToNetworkInfo(f))})).catch((e=>{d(e,!0,f)})),this}catch(e){throw d(e,!1)}}async reject(){let e=+new Date,t=K0();this.sendCallStageEvent({eventName:Q.acs_calling_call_reject_attempt,correlationId:t,timestampInfo:{attemptTimestamp:e}});let n=this._callAgent.getEcsConfigIds(),r={additionalProperties:{EmergencyCountryCode:this._callAgent._caConfigBag?.emergencyCountryCode||``,IsUserEmergencyCountryCode:this._callAgent._caConfigBag?.IsUserEmergencyCountryCode||!1,IsEmergencyCall:this._isEmergencyCall,trouterState:this._callAgent.getTrouterState(),AcsCallingSDKWeb_ecsConfigId:n.AcsCallingSDKWeb,SkypeWebMedia_ecsConfigId:n.SkypeWebMedia},additionalDetails:{}};if(this.tsCall.state!==1){let n=new Y({defaultError:J.CALL.REJECT_NOT_RINGING});r.additionalDetails.communicationServicesError=K3(n).communicationServicesError;let i=+new Date;throw this.sendCallStageEvent({eventName:Q.acs_calling_call_reject_failed,correlationId:t,timestampInfo:{deltaTimeInMs:i-e},additionalPayload:r},n),n}let i=AG();return F7.setCauseIdToNetworkInfo(i),this.tsCall.reject(i).then((()=>{let n=+new Date;this.sendCallStageEvent({eventName:Q.acs_calling_call_reject_success,correlationId:t,timestampInfo:{deltaTimeInMs:n-e}},void 0,void 0,F7.getRemoveCauseIdToNetworkInfo(i))})).catch((n=>{let a=+new Date,o={message:J.CALL.REJECT_CALL_FAILED.message,code:J.CALL.REJECT_CALL_FAILED.code,subCode:J.CALL.REJECT_CALL_FAILED.subCode,resultCategories:J.CALL.REJECT_CALL_FAILED.resultCategories},{callEndReason:s,callingCommunicationError:c,hasDiagnosticsInfo:l}=V3(this,n,o);throw l?r.additionalDetails.callEndReason=s:r.additionalDetails.communicationServicesError=K3(c).communicationServicesError,this.sendCallStageEvent({eventName:Q.acs_calling_call_reject_failed,correlationId:t,timestampInfo:{deltaTimeInMs:a-e},additionalPayload:r},c,void 0,F7.getRemoveCauseIdToNetworkInfo(i)),c}))}dispose(){this._disposed||=(this._dmDevicesChangedSub&&this._dmDevicesChangedSub.dispose(),this._dmDevicesChangedSub=void 0,this._extensibleApi.dispose(),this._eventEmitter.removeAllListeners(),this._onlineListener&&window.removeEventListener(`online`,this._onlineListener),this._offlineListener&&window.removeEventListener(`offline`,this._offlineListener),this._trouterStateChangedListener&&this._callAgent.offTrouterStateChanged(this._trouterStateChangedListener),this._mmrRdpConnectionManager.dispose(),this._selectedDeviceManager?.dispose(),this.explicitConsentStateImp.dispose(),!0)}async startAudioInternal(e,t=!1){let n=K0(),r=+new Date,i=AG();F7.setCauseIdToNetworkInfo(i);try{if(this.isInternalApiCallWithoutRawMedia(e,t))return;this.sendRawMediaEvent({eventName:Q.acs_calling_start_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:n,kindOfEvent:$.attempt,isInternal:t,timestampInfo:``,additionalDetails:``}),this.validateRawMedia(e,J.CALL.START_AUDIO_LAS_NOT_RAW_MEDIA),this._userProvidedLocalAudioStreamCache=e;let a=await this.createMediaStream(e),o=await this._callAgent.tsStack?.getDeviceManagerAsync?.();if(!Z()?.calling?.allowAccessRawMediaStream||!o?.setRawMediaStream)throw new Y({defaultError:J.CALL.LOCAL_AUDIO_SET_MEDIA_STREAM});o?.setRawMediaStream(a,0),this.removeLocalAudioStream(this.localAudioStreams[0]),this.setLocalAudioStream(e);let s=+new Date;this.sendRawMediaEvent({eventName:Q.acs_calling_start_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:n,kindOfEvent:$.success,isInternal:t,localAudioStream:this.localAudioStreams[0],timestampInfo:{deltaTimeInMs:s-r},additionalDetails:{networkInfo:F7.getRemoveCauseIdToNetworkInfo(i)}})}catch(e){let a=new Y({defaultError:J.CALL.START_AUDIO_STREAM_FAILED,originalError:e});this.logger.error(`Failed to start raw media audio: ${a.message}`);let o=+new Date;throw this.sendRawMediaEvent({eventName:Q.acs_calling_start_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:n,isInternal:t,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:o-r},additionalDetails:{failureReason:a.message||``,code:a.code,subCode:a.subCode,...K3(a),networkInfo:F7.getRemoveCauseIdToNetworkInfo(i)}}),a}}isInternalApiCallWithoutRawMedia(e,t){return!(e?.mediaStreamType===`RawMedia`||!t)&&(this.logger.info(`startAudioInternal internal call: LocalAudioStream media type is raw media, skipping raw audio startAudioInternal`),!0)}validateRawMedia(e,t){if(e?.mediaStreamType!==`RawMedia`)throw new Y({defaultError:t})}async createMediaStream(e){let t;try{t=await e.getMediaStream()}catch(e){throw new Y({defaultError:J.CALL.LOCAL_AUDIO_GET_MEDIA_STREAM,originalError:e})}return new MediaStream(t)}stopAudioInternal(e=!1){let t=K0(),n=+new Date,r=AG();F7.setCauseIdToNetworkInfo(r);try{let i=this._localAudioStreams[0];if(this.isInternalApiCallWithoutRawMedia(i,e))return;this.sendRawMediaEvent({eventName:Q.acs_calling_stop_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,kindOfEvent:$.attempt,isInternal:e,timestampInfo:``,additionalDetails:``}),e||$5(o4.StopAudio,this.state),this.validateRawMedia(i,J.CALL.STOP_AUDIO_LAS_NOT_RAW_MEDIA);let a=this._callAgent.tsStack?.getDeviceManager();if(!Z()?.calling?.allowAccessRawMediaStream||!a?.unsetRawMediaStream)throw new Y({defaultError:J.CALL.LOCAL_AUDIO_UNSET_MEDIA_STREAM});a.unsetRawMediaStream(0),this._userProvidedLocalAudioStreamCache=void 0,this.removeLocalAudioStream(this.localAudioStreams[0]),this.setLocalAudioStream();let o=+new Date;this.sendRawMediaEvent({eventName:Q.acs_calling_stop_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,kindOfEvent:$.success,isInternal:e,localAudioStream:this.localAudioStreams[0],timestampInfo:{deltaTimeInMs:o-n},additionalDetails:{networkInfo:F7.getRemoveCauseIdToNetworkInfo(r)}})}catch(i){let a=new Y({defaultError:J.CALL.STOP_AUDIO_STREAM_FAILED,originalError:i});this.logger.error(`Failed to stop raw media audio: ${a.message}`);let o=+new Date;throw this.sendRawMediaEvent({eventName:Q.acs_calling_stop_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,isInternal:e,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:o-n},additionalDetails:{failureReason:a.message||``,code:a.code,subCode:a.subCode,...K3(a),networkInfo:F7.getRemoveCauseIdToNetworkInfo(r)}}),a}}bindTsCall(){let e=[];this.tsCall.callerMri!==void 0&&(this._callerIdentity=G2(this.tsCall.callerMri),this._callerDisplayName=this.tsCall.participants.find((e=>e.id===this.tsCall.callerMri))?.displayName),this._lastTsCallState=this.tsCall.state,this.mapTsCallState(this.tsCall.state),this._setCallRole(this.tsCall.advancedMeetingRole),this.tsCall.callQueueInfo?(this._callerIdentity=G2(this.tsCall.callQueueInfo.onBehalfOf.id),this._callerDisplayName=this.tsCall.callQueueInfo.onBehalfOf.displayName?this.tsCall.callQueueInfo.onBehalfOf.displayName:this.tsCall.participants.find((e=>e.id===this.tsCall.callQueueInfo?.details.id))?.displayName,this._transferorIdentity=G2(this.tsCall.callQueueInfo.details.id),this._transferorDisplayName=this.tsCall.callQueueInfo.details.displayName?this.tsCall.callQueueInfo.details.displayName:this.tsCall.participants.find((e=>e.id===this.tsCall.callQueueInfo?.details.id))?.displayName):this.tsCall.transferorMri&&(this._transferorIdentity=G2(this.tsCall.transferorMri),this._transferorDisplayName=this.tsCall.transferorDisplayName),this.updateCallMode(),e.push(this.tsCall.changed((()=>{this.tsCall.callId!==this._id&&(this.logger.log(`tsCall callId changed from ${this._id} to ${this.tsCall.callId}`),M7(this._telemetryLogManager,this.logger,{...j7(this,this._callAgent,K0(),this._joinContextDescription),step:`id-changed`,isAcsTeamsCall:this.isAcsTeamsCall,oldCallId:this._id,newCallId:this.tsCall.callId}),this._id=this.tsCall.callId,this._eventEmitter.emit(`idChanged`)),this.tsCall.state!==this._lastTsCallState&&(this.logger.log(`tsCall state changed=${this.tsCall.state}`),this._lastTsCallState=this.tsCall.state,this.mapTsCallState(this.tsCall.state),this._handleMuteChanges()),this._isScreenSharingOn!==this.tsCall.isScreenSharingOn&&(this.logger.log(`tsCall isScreenSharingOn changed=${this.tsCall.isScreenSharingOn}`),this._isScreenSharingOn=this.tsCall.isScreenSharingOn,this._isScreenSharingOn||this.removeScreenSharingStream(),this._eventEmitter.emit(`isScreenSharingOnChanged`)),this._isMicrophoneMuted!==this.tsCall.isMuted&&(this.logger.log(`tsCall isMuted changed=${this.tsCall.isMuted}`),this._isMicrophoneMuted=this.tsCall.isMuted,this._handleMuteChanges()),this._isSpeakerMuted!==this.tsCall.isSpeakerMuted&&(this.logger.log(`tsCall _isSpeakerMuted changed=${this.tsCall.isSpeakerMuted}`),this._isSpeakerMuted=this.tsCall.isSpeakerMuted,this._handleIncomingAudioMuteChanges()),this.tsCall.advancedMeetingRole!==this._lastTsCallAdvancedMeetingRole&&(this.logger.log(`tsCall advancedMeetingRole changed=${this.tsCall.advancedMeetingRole}`),this._setCallRole(this.tsCall.advancedMeetingRole)),(this.tsCall.meetingData?.meetingUrl||this.tsCall.meetingData?.passcode||this.tsCall.conversationType==`scheduledMeeting`)&&this.tsCall.meetingDetails&&aTe(this.tsCall.meetingDetails,this._lastTsCallMeetingDetails)&&this._setMeetingCapabilities(this.tsCall.meetingDetails),this.updateCallMode()}))),e.push(this.tsCall.on(`optimalVideoReceiversCountChanged`,this.optimalVideoCountChanged)),e.push(this.tsCall.on(`serverMutedChanged`,(()=>{this.logger.log(`tsCall isServerMuted changed=${this.tsCall.isServerMuted}`),this._handleMuteChanges()}))),this._totalParticipantCount=F4(this.tsCall),e.push(this.tsCall.on(`participantCountsUpdated`,(()=>{let e=F4(this.tsCall);if(this._totalParticipantCount!==e){let t=this._totalParticipantCount;this._totalParticipantCount=e,this.logger.log(`tsCall totalParticipantCount changed from ${t} to ${this._totalParticipantCount}`),Z().rendering.remoteVideo.largeMeeting.handleVideoRendering&&this._enableOrDisable_largeMeeting_videoRendering(),this._eventEmitter.emit(`totalParticipantCountChanged`);try{this.stats.recordEvent({name:s3.number_of_participants,callId:this.id,localParticipantId:this.tsCall.participantId,data:{totalParticipantCount:this._totalParticipantCount,participantCounts:this.tsCall.participantCounts||{},previousParticipantCount:t}})}catch{this.logger.error(`failed to send participant count change telemetry`)}}})));let t=(e,t)=>{if(e!==t){this.logger.log(`transportState changed from ${this._transportState} to ${t}`);let n=this._transportStateTimestamp.get(`Connected`)===void 0?this._connectedTimestamp:void 0;this._transportStateTimestamp.delete(t);let r=Q2.omitBy({connectedTimetamp:n,transportConnectedTimestamp:this._transportStateTimestamp.get(`Connected`),transportDisconnectedTimestamp:this._transportStateTimestamp.get(`Disconnected`),transportFailedTimestamp:this._transportStateTimestamp.get(`Failed`)},Q2.isUndefined),i=Q2.merge(j7(this,this._callAgent,K0(),this._joinContextDescription),{timestampInfo:r});M7(this._telemetryLogManager,this.logger,{...i,step:`transportState-changed`,oldState:e,newState:t}),this._transportStateTimestamp.set(t,Date.now()),this._transportState=t}};e.push(this.tsCall.on(`transportConnected`,(()=>{t(this._transportState,`Connected`)}))),e.push(this.tsCall.on(`transportDisconnected`,(()=>{t(this._transportState,`Disconnected`)}))),e.push(this.tsCall.on(`transportFailed`,(()=>{t(this._transportState,`Failed`)}))),e.push(this.tsCall.on(`callQualityChanged`,(async e=>{try{let t;e.type===5||e.type===32||e.type===2||e.type===1||e.type===37?(t=s3.network_quality,this._trackNetworkQualityUfdEventDetails(e.type)):t=e.type===44||e.type===43||e.type===9||e.type===25||e.type===45||e.type===33||e.type===34||e.type===55||e.type===26||e.type===47||e.type===27?s3.video_device_issue:s3.other_diagnostic,e.value===3||e.value===2?(this._ufdLogThrottler.shouldLogError(e.type,new Date)&&this.logger.warn(`Ufd error raised!, ufd=${e.type}, value=${e.value}, kind=${t}`),t===s3.network_quality&&window.dispatchEvent(new CustomEvent(`online`,{detail:!1}))):(this._ufdLogThrottler.shouldLogRecovery(e.type,new Date)&&this.logger.warn(`Ufd error recovered!, ufd=${e.type}, value=${e.value}, kind=${t}`),t===s3.network_quality&&window.dispatchEvent(new CustomEvent(`online`,{detail:!0})));let n=``,r=this._ufdsCorrelationIdCache[e.type][e.mediaType];e.value==3||e.value==2?r?n=r:(n=K0(),this._ufdsCorrelationIdCache[e.type][e.mediaType]=n):(r&&(n=r),this._ufdsCorrelationIdCache[e.type][e.mediaType]=void 0);let i={type:e.type.toString(),level:e.value,mediaType:e.mediaType,correlationId:n};if(this.stats.recordEvent({name:t,callId:this.id,localParticipantId:this.tsCall.participantId,data:i}),this.shallStopVideo(e)){let t=+new Date,n=K0();this.logger.warn(`Attempting to stop video gracefully due to video ufd being raised.UFD: ${e.type}, value: ${e.value}, call direction: ${this._direction}`),this.sendAudioEvent({eventName:Q.acs_calling_stop_video_on_ufd_attempt,timestampInfo:{attemptTimestamp:t},correlationId:n,step:`mid-call`});try{this.localVideoStream&&this.stopVideo(this.localVideoStream)}catch{let t=`Failed to stop video on video device start failed or capture mute event ${e.type} with value ${e.value}`;this.logger.error(t)}}if(this.shallRemoveLocalVideoStreamOnBadUfd(e)){let t=new Y({defaultError:J.CALL.REMOVE_LOCAL_VIDEO_ON_BAD_UFD,defaultErrorMessageArgs:[e.type,e.value,this._direction]});if(this.localVideoStream){let e=jG(n),r=this.createVideoNegotiationTag(n,`Video`);this.sendVideoEvent({eventName:Q.acs_calling_start_video_failure,correlationId:K0(),timestampInfo:{attemptTimestamp:+new Date},step:`start`,additionalDetails:{...K3(t),negotiationTag:r,causeId:e},localVideoStream:this.localVideoStream,isScreenSharingOnFlag:this.isScreenSharingOn},t),this.removeLocalVideoStream(this.localVideoStream)}this.logger.error(t.message)}if(this.shallStopAudio(e)){let t=+new Date,n=K0();if(Z()?.calling?.allowMuteOnBadUfd&&!this.tsCall.isMuted){this.sendAudioEvent({eventName:Q.acs_calling_mute_on_ufd_attempt,timestampInfo:{attemptTimestamp:t},correlationId:n,step:`mid-call`});try{await this.mute()}catch{let t=`Failed to mute on microphone device not functioning or capture mute event ${e.type} with value ${e.value}`;this.logger.error(t)}}if(Z()?.calling?.preventStopAudio)return this.sendAudioEvent({eventName:Q.acs_calling_prevent_stop_audio,timestampInfo:{attemptTimestamp:t},correlationId:n,step:`mid-call`}),void(!Z()?.calling?.preventFakeMute&&this.markCallMuted());this.sendAudioEvent({eventName:Q.acs_calling_stop_audio_attempt,timestampInfo:{attemptTimestamp:t},correlationId:n,step:`mid-call`});try{await this.tsCall.stopAudio(),this.markCallMuted();let e=+new Date;this.sendAudioEvent({eventName:Q.acs_calling_stop_audio_success,timestampInfo:{deltaTimeInMs:e-t},correlationId:n,step:`mid-call`})}catch(r){let i=new Y({defaultError:J.CALL.STOP_AUDIO_ON_BAD_UFD,defaultErrorMessageArgs:[e.type,e.value],originalError:r});this.logger.error(i.message);let a=+new Date;this.sendAudioEvent({eventName:Q.acs_calling_stop_audio_failure,timestampInfo:{deltaTimeInMs:a-t},correlationId:n,step:`mid-call`},i)}}this.muteUnmuteOnMicrophoneNotFunctioningUfd(e),this.audioDidAutoRecover(e)&&(this._isDeviceNotFunctioningMuted=!1,this._handleMuteChanges())}catch{this.logger.error(`Failed to send ufd telemetry`)}}))),e.push(this.tsCall.on(`participantAdded`,(async e=>{this.logger.debug(`tsCall participant added`);let t=[];e.endpoints?.endpointDetails.forEach((e=>t.push(e.participantId))),t.length===0&&t.push(`remoteParticipantId unavailable`);let n=G2(e.id);if(this._isEnterpriseTeamsCall=this._isEnterpriseTeamsCall||n.kind===`microsoftTeamsUser`,this.sendParticipantAddedOrRemovedEvent({remoteParticipantIds:t,participantAddedOrRemoved:`added`,kindOfEvent:$.event}),I4(e))this.logger.info(`Add participant: Handle hidden calling application`);else{this.checkAndUpdateCopilotDisplayName(e),this._handleLocalRingingCallState(e);try{let t=this.getOrCreateRemoteParticipant(n,e);this._eventEmitter.emit(`remoteParticipantsUpdated`,{added:[t],removed:[]})}catch{this.logger.log(`unable to map call participant to ACS user`)}}}))),this.logger.debug(`tsCall current participant count=${this.tsCall?.participants?.length}`);let n=e=>{let t=G2(e.id);this._isEnterpriseTeamsCall=this._isEnterpriseTeamsCall||t.kind===`microsoftTeamsUser`;let n=this.getOrCreateRemoteParticipant(t,e);this._handleLocalRingingCallState(e),n.on(`displayNameChanged`,(()=>{this._callerIdentity&&W2(this._callerIdentity)===W2(n.identifier)&&(this._callerDisplayName=n.displayName,this._eventEmitter.emit(`callerInfoChanged`)),this._transferorIdentity&&W2(this._transferorIdentity)===W2(n.identifier)&&(this._transferorDisplayName=n.displayName,this._eventEmitter.emit(`transferorInfoChanged`))}))},r=[];this.tsCall.participants.forEach((e=>{Z().calling.checkHiddenBotOnCallStart&&I4(e)||n(e);try{e.endpoints?.endpointDetails.forEach((e=>r.push(e.participantId)))}catch{this.logger.error(`Unable to get participantId from from remote participant`)}}));try{this.sendParticipantAddedOrRemovedEvent({remoteParticipantIds:r,participantAddedOrRemoved:`added`,kindOfEvent:$.initialize})}catch{this.logger.error(`Unable to send participant added telemtery`)}return e.push(this.tsCall.on(`participantRemoved`,(async e=>{this.logger.debug(`tsCall participant removed`);let t=[];if(e.endpoints?.endpointDetails.forEach((e=>t.push(e.participantId))),t.length===0&&t.push(`remoteParticipantId unavailable`),I4(e))return this.logger.info(`Remove participant: Ignore calling application`),void this.sendParticipantAddedOrRemovedEvent({remoteParticipantIds:t,participantAddedOrRemoved:`removed`,kindOfEvent:$.event});let n=e.id;if(n){let r=this._remoteParticipants.find((e=>W2(e.identifier)===n));if(r){let{callEndReason:n}=H3(this,e);r.setCallEndReason(n),this.deleteRemoteParticipant(r),this._eventEmitter.emit(`remoteParticipantsUpdated`,{added:[],removed:[r]}),this.sendParticipantAddedOrRemovedEvent({remoteParticipantIds:t,participantAddedOrRemoved:`removed`,kindOfEvent:$.event,additionalDetails:{...q3(n)}})}else this.logger.log(`unable to find participant to remove`)}}))),e}_trackNetworkQualityUfdEventDetails(e){let t=+new Date,n=``;switch(e){case 5:n=n6;break;case 32:n=a6;break;case 2:n=r6;break;case 1:n=i6;break;case 37:n=o6}this._networkQualityUfdEventDetails.push({eventName:n,timestampInfo:t})}async muteUnmuteOnMicrophoneNotFunctioningUfd(e){try{let t=Z().calling;if(!t.muteUnmuteOnMicrophoneNotFunctioning||this._isMuted||e.type!==9||e.value!==3)return;this.__attemptedToRecoverMicNotFunctioningBySDK=!0,await this.mute(),t.unmuteDelayForMicrophoneNotFunctioningInMs>=0&&await t3(t.unmuteDelayForMicrophoneNotFunctioningInMs),await this.unmute()}catch(e){this.logger.info(`Unable to perform mute and unmute to recover microphoneNotFunctioning`,e)}finally{this.__attemptedToRecoverMicNotFunctioningBySDK=!1}}updateCallMode(){this.tsCall.callMode&&this._callMode!==this.tsCall.callMode&&(this.logger.log(`tsCall callMode changed from ${this._callMode} to ${this.tsCall.callMode}`),M7(this._telemetryLogManager,this.logger,{...j7(this,this._callAgent,K0(),this._joinContextDescription),step:`callMode-changed`,oldState:eDe[this._callMode],newState:eDe[this.tsCall.callMode]}),this._callMode=this.tsCall.callMode)}checkAndUpdateCopilotDisplayName(e){this.tsCall.meetingDetails&&(W2(e)!==m2||e.displayName!==``&&e.displayName!==void 0||(e.displayName=_2))}async startCallInternal(e,t,n,r,i,a){let o=!!e?.audioOptions?.muted,s=this.getLocalVideoStreamFromCallOptions(e),c=this.getLocalAudioStreamFromCallOptions(e),l,u=i?.attemptTimestamp??+new Date,d=K0();this._joinContextDescription=nTe(n);let f=this._callAgent.getEcsConfigIds(),p=this.tsCall.participants.length===1&&!this.tsCall.threadId&&!t,m=!!p||this._allowIPAudio,h=!!p||this._allowIPVideo,g=U6(this.tsCall),_=i?.correlationId??K0(),v=jG(_),y=this.createVideoNegotiationTag(_,`Video`),b={joinContextDescription:this._joinContextDescription,additionalProperties:{EmergencyCountryCode:this._callAgent._caConfigBag?.emergencyCountryCode||``,IsUserEmergencyCountryCode:this._callAgent._caConfigBag?.IsUserEmergencyCountryCode||!1,IsEmergencyCall:r?.isEmergency||!1,dialedEmergencyNumber:r?.isEmergency?this.tsCall.participants?.[0]?.id:void 0,trouterState:this._callAgent.getTrouterState(),muted:o,withVideo:h&&!!s,withAudio:m&&c?.mediaStreamType?c.mediaStreamType:``,...r7(),AcsCallingSDKWeb_ecsConfigId:f.AcsCallingSDKWeb,SkypeWebMedia_ecsConfigId:f.SkypeWebMedia,customContext:{userToUserPresent:!!e?.customContext?.userToUser,xHeadersPresent:!!e?.customContext?.xHeaders&&e.customContext.xHeaders.length>0},firstPartyOptions:{isDeviceTypeEnabled:Z().calling.setDeviceType,deviceType:this._callAgent.getDeviceType(),isImmersiveMode:e?.firstPartyOptions?.isImmersiveMode,accessToImmersiveEvents:e?.firstPartyOptions?.accessToImmersiveEvents},mediaModalities:this.getMediaModalityTelemetry(e?.mediaModalities),negotiationTag:y,causeId:v},additionalDetails:{}};e?.videoOptions?.constraints&&(b.additionalProperties.constraints=this._mediaConstraintsManager.getTelemetryPayload({video:e?.videoOptions?.constraints})),r?.meetingInfo?.tenantId&&(this._teamsMeetingTenantId=r.meetingInfo.tenantId,b.additionalProperties.teamsMeetingTenantId=r.meetingInfo.tenantId),r?.threadId&&(this._teamsMeetingThreadId=r.threadId,b.additionalProperties.teamsMeetingThreadId=r.threadId),r?.onBehalfOf&&(b.additionalProperties.onBehalfOfProvided=!0,b.additionalProperties.onBehalfOfIdKind=G2(r.onBehalfOf).kind,this.logger.info(`onBehalfOf provided kind: ${b.additionalProperties.onBehalfOfIdKind}`));let x={...b},S={...b};this.sendCallStageEvent({eventName:Q.acs_calling_call_attempt,correlationId:_,timestampInfo:{attemptTimestamp:u},additionalPayload:b},void 0,void 0,void 0,`attempt`);try{this._isMicrophoneMuted=o,e?.alternateCallerId&&(l=W2(e.alternateCallerId)),s&&this.setLocalVideoStream(s),this.setLocalAudioStream(c)}catch(e){a?.reject(e);let t=+new Date,n=new Y({defaultError:J.CALL.INSTANTIATE_CALL,originalError:e});throw x.additionalDetails.communicationServicesError=K3(n).communicationServicesError,this.sendCallStageEvent({eventName:Q.acs_calling_call_failed,correlationId:_,timestampInfo:{deltaTimeInMs:t-u},additionalPayload:x},n,void 0,void 0,`failure`),this.logger.error(n.message),n}let C=AG();F7.setCauseIdToNetworkInfo(C);try{let n={...r};!Z().calling.setDeviceType||this._callAgent.getDeviceType()!==`mesh`&&this._callAgent.getDeviceType()!==`meshV2`||(n.endpointMetadata=JSON.stringify({meshapp:!0})),g?(await this.tsCall.initAsync?.(n),a?.resolve()):this.tsCall.init(n),s&&this.sendVideoEvent({correlationId:d,eventName:Q.acs_calling_start_video_attempt,timestampInfo:{attemptTimestamp:u},localVideoStream:s,step:`start`,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:y,causeId:v}});try{if(e?.videoOptions?.constraints){let t=await this._mediaConstraintsManager.setVideoConstraints(e?.videoOptions?.constraints,`start`,d,u),n=this._mediaConstraintsManager.getTelemetryPayload({video:t});S.additionalProperties.constraints=n}}catch(e){let t=new Y({defaultError:J.CALL.CALLSTART_VIDEO_CONSTRAINTS,originalError:e});this.logger.error(`${t.message}`)}let i=this.setClientCallStartOptions(e);if(Z()?.calling?.enableCustomTurnUsage&&this.acsCustomRelayManager?.customRelayManagerInUse&&(i.mediaConfiguration={connectionType:`NoDirectConnection`}),o&&(i.muteFlags=1),e?.firstPartyOptions?.disableAudioMixing&&(i.muteFlags===void 0?i.muteFlags=2:i.muteFlags|=2),e?.firstPartyOptions?.enableSpatialAudio!==void 0&&(i.mediaConfiguration=i.mediaConfiguration||{},i.mediaConfiguration.enableSpatialAudio=e.firstPartyOptions.enableSpatialAudio,this._callAgent.tsStack?await this._callAgent.tsStack.setMediaConfig({enableSpatialAudio:e.firstPartyOptions.enableSpatialAudio}):this.logger.error(`Could not set enableSpatialAudio to ${e.firstPartyOptions.enableSpatialAudio} since this._callAgent.tsStack is null`)),i.customHeaderContext=V4(e),c&&await this.startAudioInternal(c,!0).catch((e=>{this.logger.error(`Failed to start localAudioStream, message=${e?.message}`)})),s?.mediaStreamType===`RawMedia`)try{await this._setRawStream(s,1)}catch(e){let t=+new Date,n=new Y({defaultError:J.LOCAL_VIDEO_STREAM.VIDEO_GET_MEDIA_STREAM,originalError:e});this.sendVideoEvent({correlationId:d,eventName:Q.acs_calling_media_stream,timestampInfo:{deltaTimeInMs:t-u},localVideoStream:s,step:`start`,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:y}},n),this.removeLocalVideoStream(s)}t?await this.tsCall.startWithMeetingData(C,{withVideo:!!s&&this.isIPVideoEnabled,muted:o,ringOthers:!0,alternateId:l,shouldResurrect:`resurrect`,...i}):(i.negotiationTag=this.createVideoNegotiationTag(_,`Video`),await this.tsCall.start({withVideo:!!s&&this.isIPVideoEnabled,muted:o,ringOthers:!0,alternateId:l,...i},C)),S.additionalProperties.negotiationTag=y,S.additionalProperties.causeId=v;let f=+new Date;this.sendCallStageEvent({eventName:Q.acs_calling_call_connected,correlationId:_,timestampInfo:{deltaTimeInMs:f-u},additionalPayload:S},void 0,void 0,F7.getRemoveCauseIdToNetworkInfo(C),`success`),c&&this.shallRemoveLasAfterConnectedSuccessfully(c,`start`,_,f,u),s&&this.shallRemoveLvsAfterConnectedSuccessfully(s,`start`,_,f,u,y,v),this._handleAudioEffectsOperations()}catch(e){a?.reject(e);let t=+new Date,{callEndReason:n,callingCommunicationError:r}=V3(this,e);if(s){let n=new Y({defaultError:J.LOCAL_VIDEO_STREAM.CALL_NOT_FOUND,originalError:e});this.sendVideoEvent({correlationId:d,eventName:Q.acs_calling_start_video_failure,timestampInfo:{deltaTimeInMs:t-u},localVideoStream:s,step:`start`,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:y,causeId:v}},n),this.removeLocalVideoStream(s)}throw c&&this.removeLocalAudioStream(c),x.additionalDetails.callEndReason=q3(n).callEndReason,x.additionalProperties.negotiationTag=y,x.additionalProperties.causeId=v,this.sendCallStageEvent({eventName:Q.acs_calling_call_failed,correlationId:_,timestampInfo:{deltaTimeInMs:t-u},additionalPayload:x},r,void 0,F7.getRemoveCauseIdToNetworkInfo(C),`failure`),this.logger.error(`Failed to start the call, message=${n?.message}, code=${n?.code}, subCode=${n?.subCode}, resultCategories=${n?.resultCategories}`),r}}getMediaModalityTelemetry(e){return e?{audio:e.audio,video:e.video,screenShare:e.screenShare}:void 0}getTopNDominantSpeakersWithVideoOn(){if(this._internalDominantSpeakersListener){let e=this._internalDominantSpeakersListener.dominantSpeakers.speakersList.map((e=>this._mriToRemoteParticipantMap.get(W2(e)))).filter((e=>!!e)).filter((e=>!!e.videoStreams.filter((e=>e.mediaStreamType===`Video`)).find((e=>e.tsStream.isAvailable))));if(this.logger.info(`There are currently ${e.length} top-n dominant speakers with video on in the large meeting where topCount is ${Z().rendering.remoteVideo.largeMeeting.dominantSpeakersWithVideoOn_topCount}`),e.length<Z().rendering.remoteVideo.largeMeeting.dominantSpeakersWithVideoOn_topCount){let t=this._remoteParticipants.filter((e=>!!e.videoStreams.filter((e=>e.mediaStreamType===`Video`)).find((e=>e.tsStream.isAvailable)))).filter((t=>!e.includes(t)));t.sort(((e,t)=>{let n=e.tsRemoteParticipant?.endpoints?.endpointDetails[0]?.mediaStreams?.filter((e=>e.type===`audio`)).map((e=>e.sourceId))??[],r=n.length>0?Math.min(...n):void 0,i=t.tsRemoteParticipant?.endpoints?.endpointDetails[0]?.mediaStreams?.filter((e=>e.type===`audio`)).map((e=>e.sourceId))??[],a=i.length>0?Math.min(...i):void 0;return r!==void 0&&a!=null?r-a:0}));for(let n of t){if(e.length===Z().rendering.remoteVideo.largeMeeting.dominantSpeakersWithVideoOn_topCount)break;e.push(n)}}else e.splice(Z().rendering.remoteVideo.largeMeeting.dominantSpeakersWithVideoOn_topCount);return e}return[]}getParticipantCapabilities(){let e=this._capabilityResolver.getCapabilities();return this.logger.log(`participant capabilities are ${e}`),e}getMeetingCapabilitiesInternal(){let e=this._capabilityResolver.getMeetingsCapabilitiesInternal();return this.logger.info(`meeting capabilities are ${e}`),e}feature(e){return this._extensibleApi.getApiObjectInstance(e.callApiCtor)}async hangUp(e){let t=+new Date,n=K0(),r=AG();return F7.setCauseIdToNetworkInfo(r),this.sendCallStageEvent({eventName:Q.acs_calling_call_hangup_attempt,correlationId:n,timestampInfo:{attemptTimestamp:t}}),this.tsCall.stop(e?.forEveryone,r).then((()=>{let e=+new Date;this.sendCallStageEvent({eventName:Q.acs_calling_call_hangup_success,correlationId:n,timestampInfo:{deltaTimeInMs:e-t}},void 0,void 0,F7.getRemoveCauseIdToNetworkInfo(r))})).catch((e=>{let i=+new Date,{callEndReason:a,callingCommunicationError:o,hasDiagnosticsInfo:s}=V3(this,e),c=this._callAgent.getEcsConfigIds(),l={additionalProperties:{EmergencyCountryCode:this._callAgent._caConfigBag?.emergencyCountryCode||``,IsUserEmergencyCountryCode:this._callAgent._caConfigBag?.IsUserEmergencyCountryCode||!1,IsEmergencyCall:this._isEmergencyCall,trouterState:this._callAgent.getTrouterState(),AcsCallingSDKWeb_ecsConfigId:c.AcsCallingSDKWeb,SkypeWebMedia_ecsConfigId:c.SkypeWebMedia},additionalDetails:{}};if(s)l.additionalDetails={...q3(a)};else{let t=new Y({defaultError:J.CALL.OPERATION_FAILED,originalError:e});l.additionalDetails.communicationServicesError=K3(t).communicationServicesError}throw this.sendCallStageEvent({eventName:Q.acs_calling_call_hangup_failure,correlationId:n,timestampInfo:{deltaTimeInMs:i-t},additionalPayload:l},o,void 0,F7.getRemoveCauseIdToNetworkInfo(r)),o}))}async mute(){let e=this.logger.createFnLogger(o4.Mute),t=+new Date,n=K0(),r=AG();F7.setCauseIdToNetworkInfo(r),this.sendAudioEvent({eventName:Q.acs_calling_mute_attempt,eventType:l3.MuteMicrophone,timestampInfo:{attemptTimestamp:t},correlationId:n,step:`mid-call`,initiatedBySdk:this.__attemptedToRecoverMicNotFunctioningBySDK});try{e.info(`mute`),await this.tsCall.mute(r),e.info(`mute success`);let i=+new Date;this.sendAudioEvent({eventName:Q.acs_calling_mute_success,eventType:l3.MuteMicrophone,timestampInfo:{deltaTimeInMs:i-t},correlationId:n,step:`mid-call`,initiatedBySdk:this.__attemptedToRecoverMicNotFunctioningBySDK,networkInfo:F7.getRemoveCauseIdToNetworkInfo(r)})}catch(i){let a=new Y({defaultError:J.CALL.MIC_MUTE,originalError:i});e.error(`Failed to mute microphone`);let o=+new Date;throw this.sendAudioEvent({eventName:Q.acs_calling_mute_failure,eventType:l3.MuteMicrophone,timestampInfo:{deltaTimeInMs:o-t},correlationId:n,step:`mid-call`,initiatedBySdk:this.__attemptedToRecoverMicNotFunctioningBySDK,networkInfo:F7.getRemoveCauseIdToNetworkInfo(r)},a),a}}async unmute(){let e=this.logger.createFnLogger(o4.Unmute),t=+new Date,n=K0(),r=!1,i=AG();if(F7.setCauseIdToNetworkInfo(i),this.sendAudioEvent({eventName:Q.acs_calling_unmute_attempt,eventType:l3.UnmuteMicrophone,timestampInfo:{attemptTimestamp:t},correlationId:n,step:`mid-call`,initiatedBySdk:this.__attemptedToRecoverMicNotFunctioningBySDK}),!this.isAudioPermitted()){let t=`cannot unmute as microphone is disabled`;throw e.error(t),new Y({defaultError:J.CALL.MIC_DISABLED,originalError:t})}if(!this.isIPAudioEnabled){let t=`cannot unmute as IP audio in Teams Meeting Policy is disabled`;throw e.error(t),new Y({defaultError:J.CALL.IP_AUDIO_NOT_ALLOWED,originalError:t})}if(this.explicitConsentStateImp.areCoreCapabilitiesConsentRestricted()){let t=`cannot unmute as consent is required to be recorded or transcribed`;throw e.error(t),new Y({defaultError:J.CALL.UNMUTE_CONSENT_RESTRICTED,originalError:t})}try{e.info(`unmute`),await this.tsCall.unmute(i),e.info(`unmute success`);let a=+new Date;this.sendAudioEvent({eventName:Q.acs_calling_unmute_success,eventType:l3.UnmuteMicrophone,timestampInfo:{deltaTimeInMs:a-t},correlationId:n,step:`mid-call`,initiatedBySdk:this.__attemptedToRecoverMicNotFunctioningBySDK,networkInfo:F7.getRemoveCauseIdToNetworkInfo(i)});let o=+new Date;if(!Z()?.calling?.preventStopAudio&&this._isDeviceNotFunctioningMuted){this.sendAudioEvent({eventName:Q.acs_calling_start_audio_attempt,timestampInfo:{attemptTimestamp:o},correlationId:n,step:`mid-call`,networkInfo:F7.getRemoveCauseIdToNetworkInfo(i)}),r=!0,e.info(`start audio`),await this.tsCall.startAudio(),e.info(`start audio success`);let t=+new Date;this._isDeviceNotFunctioningMuted=!1,this._handleMuteChanges(),this.sendAudioEvent({eventName:Q.acs_calling_start_audio_success,timestampInfo:{deltaTimeInMs:t-o},correlationId:n,step:`mid-call`,networkInfo:F7.getRemoveCauseIdToNetworkInfo(i)})}this.setLocalAudioStream()}catch(a){let o=r?J.CALL.MIC_UNMUTE_AND_STARTAUDIO:J.CALL.MIC_UNMUTE,s=new Y({defaultError:o,originalError:a});e.error(o.message);let c=+new Date;throw this.sendAudioEvent({eventName:r?Q.acs_calling_start_audio_failure:Q.acs_calling_unmute_failure,eventType:r?void 0:l3.UnmuteMicrophone,timestampInfo:{deltaTimeInMs:c-t},correlationId:n,step:`mid-call`,initiatedBySdk:this.__attemptedToRecoverMicNotFunctioningBySDK&&!r,networkInfo:F7.getRemoveCauseIdToNetworkInfo(i)},s),s}}async muteAllRemoteParticipants(){let e=Z();if(!e.calling.enableMuteOthers)throw new Y({defaultError:J.CALL.MUTE_ALL_PARTICIPANTS_DISABLED});if(!this.tsCall.conversationType&&this._callInfo.context===v4.TwoParty)throw new Y({defaultError:J.CALL.MUTE_ALL_PARTICIPANTS_1_TO_1_UNSUPPORTED});let t=this.logger.createFnLogger(o4.MuteAllRemoteParticipants),n=+new Date,r=K0();this.sendAudioEvent({eventName:Q.acs_calling_mute_attempt,eventType:l3.MuteAllRemoteParticipants,timestampInfo:{attemptTimestamp:n},correlationId:r,step:`mid-call`});try{t.info(`mute all others`),$5(o4.MuteAllRemoteParticipants,this.state);let i=[];if(this._remoteParticipants.length!==0){let n=!1,r=!1,a=``;if(this._remoteParticipants.map((o=>{let s=o.tsRemoteParticipant;e.calling.allowMutePstnRemoteParticipant||o.identifier.kind!==`phoneNumber`?[3,5].some((e=>e===s?.state))?s!==void 0&&(i.push(s),a+=W2(o.identifier)+`, `):(t.warn(`non-connected participants cannot be muted by others`),r=!0):(t.warn(`PSTN participants cannot be muted by others`),n=!0)})),i.length===0?t.error(`all remote participants are not supported to be muted by others`):(await this.tsCall.muteParticipants(1,i),t.info(`called mute function on the following participants: ${a}`)),n){if(!this._isTeamsExtensionUser||!Z().calling.teamsExtensionSettings.enableServerMutePSTNParticipant)throw new Y({defaultError:J.CALL.MUTE_ALL_PARTICIPANTS_PSTN_UNSUPPORTED});t.info(`Enable server muting of PSTN participant for TeamsExtension user`)}if(r)throw new Y({defaultError:J.CALL.MUTE_ALL_PARTICIPANTS_NONCONNECTED_UNSUPPORTED})}else t.info(`no participants to mute in attempt to mute all remote participants`);t.info(`mute all others success`);let a=+new Date;this.sendAudioEvent({eventName:Q.acs_calling_mute_success,eventType:l3.MuteAllRemoteParticipants,timestampInfo:{deltaTimeInMs:a-n},correlationId:r,step:`mid-call`})}catch(e){let i=new Y({defaultError:J.CALL.MUTE_ALL_PARTICIPANTS,originalError:e});t.error(i.message);let a=+new Date;throw this.sendAudioEvent({eventName:Q.acs_calling_mute_failure,eventType:l3.MuteAllRemoteParticipants,timestampInfo:{deltaTimeInMs:a-n},correlationId:r,step:`mid-call`},i),i}}async muteIncomingAudio(){let e=this.logger.createFnLogger(o4.MuteIncomingAudio),t=+new Date,n=K0();this.sendAudioEvent({eventName:Q.acs_calling_mute_attempt,eventType:l3.MuteIncomingAudio,timestampInfo:{attemptTimestamp:t},correlationId:n,step:`mid-call`});try{await this.tsCall.muteSpeaker();let e=+new Date;this.sendAudioEvent({eventName:Q.acs_calling_mute_success,eventType:l3.MuteIncomingAudio,timestampInfo:{deltaTimeInMs:e-t},correlationId:n,step:`mid-call`})}catch(r){let i=new Y({defaultError:J.CALL.MUTE_INCOMING_AUDIO,originalError:r});e.error(i.message);let a=+new Date;throw this.sendAudioEvent({eventName:Q.acs_calling_mute_failure,eventType:l3.MuteIncomingAudio,timestampInfo:{deltaTimeInMs:a-t},correlationId:n,step:`mid-call`},i),i}}async unmuteIncomingAudio(){let e=this.logger.createFnLogger(o4.MuteIncomingAudio),t=+new Date,n=K0();this.sendAudioEvent({eventName:Q.acs_calling_unmute_attempt,eventType:l3.UnmuteIncomingAudio,timestampInfo:{attemptTimestamp:t},correlationId:n,step:`mid-call`});try{await this.tsCall.unmuteSpeaker();let e=+new Date;this.sendAudioEvent({eventName:Q.acs_calling_unmute_success,eventType:l3.UnmuteIncomingAudio,timestampInfo:{deltaTimeInMs:e-t},correlationId:n,step:`mid-call`})}catch(r){let i=new Y({defaultError:J.CALL.UNMUTE_INCOMING_AUDIO,originalError:r});e.error(i.message);let a=+new Date;throw this.sendAudioEvent({eventName:Q.acs_calling_unmute_failure,eventType:l3.UnmuteIncomingAudio,timestampInfo:{deltaTimeInMs:a-t},correlationId:n,step:`mid-call`},i),i}}async sendDtmf(e){let t=tDe(e);return this.tsCall.sendDtmfTone(t).catch((e=>{throw this.logger.error(`Failed to send DTMF tone`),new Y({defaultError:J.CALL.DTMF_TONE})}))}async startVideo(e){let t=this.logger.createFnLogger(o4.StartVideo),n=+new Date,r=Z()?.calling?.preventStopAudio,i=K0(),a=jG(i),o=this.createVideoNegotiationTag(i,`Video`);if(this.sendVideoEvent({eventName:Q.acs_calling_start_video_attempt,timestampInfo:{attemptTimestamp:n},localVideoStream:e,correlationId:i,step:`mid-call`,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:o,causeId:a}}),!this.isVideoPermitted()){let e=`cannot start video as camera is disabled by the Presenter or Organizer of the meeting`;throw t.error(e),new Y({defaultError:J.CALL.CAMERA_DISABLED,originalError:e})}if(!this.isIPVideoEnabled){let e=`cannot start video as IP video is not allowed`;throw t.error(e),new Y({defaultError:J.CALL.IP_VIDEO_NOT_ALLOWED,originalError:e})}if(this.explicitConsentStateImp.areCoreCapabilitiesConsentRestricted()){let e=`cannot start video as consent is restricted`;throw t.error(e),new Y({defaultError:J.CALL.VIDEOSTART_CONSENT_RESTRICTED,originalError:e})}if(this._isDeviceNotFunctioningMuted&&!r){this.sendAudioEvent({eventName:Q.acs_calling_start_audio_attempt,timestampInfo:{attemptTimestamp:n},correlationId:i,step:`mid-call`});try{t.info(`start audio before starting video`),await this.tsCall.startAudio(),t.info(`start audio success before starting video`);let e=+new Date;this._isDeviceNotFunctioningMuted=!1,this._handleMuteChanges(),this.sendAudioEvent({eventName:Q.acs_calling_start_audio_success,timestampInfo:{deltaTimeInMs:e-n},correlationId:i,step:`mid-call`})}catch(e){let r=new Y({defaultError:J.CALL.START_AUDIO_BEFORE_VIDEO,originalError:e});t.error(`Failed to start audio before starting video`);let a=+new Date;throw this.sendAudioEvent({eventName:Q.acs_calling_start_audio_failure,timestampInfo:{deltaTimeInMs:a-n},correlationId:i,step:`mid-call`},r),r}}try{if(!e)throw new Y({defaultError:J.CALL.STREAM_NULL});if(!(e instanceof J6))throw new Y({defaultError:J.CALL.STREAM_IS_NOT_LVS});if(this.tsCall.isVideoOn)throw new Y({defaultError:J.CALL.VIDEO_ALREADY_ON});e?.mediaStreamType===`RawMedia`&&await this._setRawStream(e,1),this.setLocalVideoStream(e)}catch(t){let r=new Y({defaultError:J.CALL.START_VIDEO,originalError:t});throw this.sendVideoEvent({correlationId:i,eventName:Q.acs_calling_start_video_failure,timestampInfo:{attemptTimestamp:n},localVideoStream:e,step:`mid-call`,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:o,causeId:a}},r),r}F7.setCauseIdToNetworkInfo(a);try{t.info(`start video`),await this.tsCall.startVideo(o,a);let r=+new Date;this.sendVideoEvent({correlationId:i,eventName:Q.acs_calling_start_video_success,timestampInfo:{deltaTimeInMs:r-n},localVideoStream:e,step:`mid-call`,isScreenSharingOnFlag:this._isScreenSharingOn,networkInfo:F7.getRemoveCauseIdToNetworkInfo(a),additionalDetails:{negotiationTag:o,causeId:a}}),t.info(`video started`)}catch(r){let s=+new Date,c=U3(t,r);throw this.sendVideoEvent({correlationId:i,eventName:Q.acs_calling_start_video_failure,timestampInfo:{deltaTimeInMs:s-n},localVideoStream:e,step:`mid-call`,isScreenSharingOnFlag:this._isScreenSharingOn,networkInfo:F7.getRemoveCauseIdToNetworkInfo(a),additionalDetails:{negotiationTag:o,causeId:a}},c),this.removeLocalVideoStream(e),c}}async stopVideo(e){let t=this.logger.createFnLogger(o4.StopVideo),n=+new Date,r=K0(),i=jG(r),a=this.createVideoNegotiationTag(r,`Video`);this.sendVideoEvent({correlationId:r,eventName:Q.acs_calling_stop_video_attempt,timestampInfo:{attemptTimestamp:n},localVideoStream:e,step:`mid-call`,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:a,causeId:i}});let o=this.tsCall.state===4||this.tsCall.state===5;if(!o&&!this.tsCall.isVideoOn||o&&!this.localVideoStream){let t=new Y({defaultError:J.CALL.VIDEO_ALREADY_OFF});throw this.sendVideoEvent({correlationId:r,eventName:Q.acs_calling_stop_video_failure,timestampInfo:{attemptTimestamp:n},localVideoStream:e,step:`mid-call`,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:a,causeId:i}},t),t}if(this.localVideoStream!==void 0&&this.localVideoStream!==e){let t=new Y({defaultError:J.CALL.STOP_WRONG_STREAM});throw this.sendVideoEvent({correlationId:r,eventName:Q.acs_calling_stop_video_failure,timestampInfo:{attemptTimestamp:n},localVideoStream:e,step:`mid-call`,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:a,causeId:i}},t),t}let s=()=>{try{if(Z().calling.allowAccessRawMediaStream&&e.mediaStreamType===`RawMedia`){let e=this._callAgent.tsStack?.getDeviceManager();e&&e.unsetRawMediaStream&&e.unsetRawMediaStream(1)}}catch(e){this.logger.info(`Unset raw video stream: ${e?.message??`Unkown error`}`)}};F7.setCauseIdToNetworkInfo(i);try{t.info(`stop video`),await this.tsCall.stopVideo(a,i),s();let o=+new Date;this.sendVideoEvent({correlationId:r,eventName:Q.acs_calling_stop_video_success,timestampInfo:{deltaTimeInMs:o-n},localVideoStream:e,step:`mid-call`,isScreenSharingOnFlag:this._isScreenSharingOn,networkInfo:F7.getRemoveCauseIdToNetworkInfo(i),additionalDetails:{negotiationTag:a,causeId:i}}),t.info(`video stopped`),this.removeLocalVideoStream(e)}catch(o){s();let c=+new Date,l=U3(t,o,!0);throw this.sendVideoEvent({correlationId:r,eventName:Q.acs_calling_stop_video_failure,timestampInfo:{deltaTimeInMs:c-n},localVideoStream:e,step:`mid-call`,isScreenSharingOnFlag:this._isScreenSharingOn,networkInfo:F7.getRemoveCauseIdToNetworkInfo(i),additionalDetails:{negotiationTag:a,causeId:i}},l),l}}startAudio(e){return this.startAudioInternal(e)}stopAudio(){return this.stopAudioInternal()}async hold(){let e=+new Date,t=K0(),n=AG();F7.setCauseIdToNetworkInfo(n);try{this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:o4.Hold,kindOfEvent:$.attempt,timestampInfo:{deltaTimeInMs:e},additionalDetails:{holdType:b4.Standard,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn}}),Z().calling.turnOffScreenShareBeforeHold&&this.tsCall.isScreenSharingOn&&await this.tsCall.stopScreenSharing().then((()=>{this.logger.log(`Successfully turned off screen sharing before hold`)})).catch((()=>{this.logger.error(`Failed to turn off screensharing before hold`)})),await this.tsCall.hold(void 0,n),this.removeLocalAudioStream(this._localAudioStreams[0]);let r=+new Date;this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:o4.Hold,kindOfEvent:$.success,timestampInfo:{deltaTimeInMs:r-e},additionalDetails:{holdType:b4.Standard,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn},networkInfo:F7.getRemoveCauseIdToNetworkInfo(n)})}catch{let r=+new Date,i=new Y({defaultError:J.CALL.HOLD_CALL});throw this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:o4.Hold,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:r-e},additionalDetails:{failureReason:i.message,code:i.code,subCode:i.subCode,holdType:b4.Standard,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn,...K3(i)},networkInfo:F7.getRemoveCauseIdToNetworkInfo(n)}),i}}async resume(){let e=+new Date,t=K0(),n=AG();F7.setCauseIdToNetworkInfo(n);try{this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:o4.Resume,kindOfEvent:$.attempt,timestampInfo:{deltaTimeInMs:e},additionalDetails:{holdType:b4.Standard,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn}}),await this.tsCall.unhold(void 0,n),this.setLocalAudioStream();let r=+new Date;this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:o4.Resume,kindOfEvent:$.success,timestampInfo:{deltaTimeInMs:r-e},additionalDetails:{isScreenSharingOnFlag:this.tsCall.isScreenSharingOn,holdType:b4.Standard},networkInfo:F7.getRemoveCauseIdToNetworkInfo(n)})}catch{let r=+new Date,i=new Y({defaultError:J.CALL.RESUME_CALL});throw this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:o4.Resume,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:r-e},additionalDetails:{failureReason:i.message,code:i.code,subCode:i.subCode,holdType:b4.Standard,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn,...K3(i)},networkInfo:F7.getRemoveCauseIdToNetworkInfo(n)}),i}}async startScreenSharing(e){let t=this.logger.createFnLogger(o4.StartScreenShare),n=+new Date,r=K0(),i=jG(r),a=this.createVideoNegotiationTag(r,`ScreenSharing`);try{if(this.sendScreenShareEvent({eventName:Q.acs_calling_start_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:r,kindOfEvent:$.attempt,timestampInfo:``,isVideoOn:this._isLocalVideoStarted,localVideoStream:e,additionalDetails:{negotiationTag:a,causeId:i}}),this.tsCall.state!==3)throw new Y({defaultError:J.CALL.START_SS_CALL_NOT_CONNECTED});if(this.tsCall.isScreenSharingOn)throw new Y({defaultError:J.CALL.SS_ALREADY_ON});if(this.explicitConsentStateImp.areCoreCapabilitiesConsentRestricted()){let e=`screen sharing cannot be started as consent is required to be recorded or transcribed`;throw t.error(e),new Y({defaultError:J.CALL.SCREENSHARE_CONSENT_RESTRICTED,originalError:e})}if(e){if(!(e instanceof J6))throw new Y({defaultError:J.CALL.SS_RAW_STREAM_IS_NOT_LVS});if(e.mediaStreamType!==`RawMedia`)throw new Y({defaultError:J.CALL.SS_RAW_STREAM_LVS_IS_NOT_RAW_MEDIA});let t=await e.getMediaStream();if(!t||t.getVideoTracks().length===0)throw new Y({defaultError:J.CALL.SS_RAW_STREAM_IS_NOT_VALID_STREAM});if(!1===t.active)throw new Y({defaultError:J.CALL.SS_RAW_STREAM_IS_NOT_ACTIVE_STREAM});t.getTracks().forEach((e=>{e.stop()})),await this._setRawStream(e,2),this.localScreenSharingStream=e}else this.localScreenSharingStream=new J6(new L6(swe.ScreenSharing,K0(),swe.ScreenSharing,this._callAgent.deviceManager))}catch(e){let t=+new Date;this.removeScreenSharingStream();let o=new Y({defaultError:J.CALL.START_SS,originalError:e});throw this.sendScreenShareEvent({eventName:Q.acs_calling_start_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:r,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:t-n},additionalDetails:{failureReason:o.message,code:o.code,subCode:o.subCode,...K3(o),negotiationTag:a,causeId:i},isVideoOn:this._isLocalVideoStarted,localVideoStream:this.localScreenSharingStream}),o}return this.tsCall.startScreenSharing(void 0,void 0,a).then((()=>{let e=+new Date;this.localScreenSharingStream&&this._localVideoStreams.indexOf(this.localScreenSharingStream)===-1&&(this.localScreenSharingStream.addCall(this),this._localVideoStreams.push(this.localScreenSharingStream),this._eventEmitter.emit(`localVideoStreamsUpdated`,{added:[this.localScreenSharingStream],removed:[]})),this.sendScreenShareEvent({eventName:Q.acs_calling_start_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:r,kindOfEvent:$.success,timestampInfo:{deltaTimeInMs:e-n},isVideoOn:this._isLocalVideoStarted,localVideoStream:this.localScreenSharingStream,additionalDetails:{negotiationTag:a,causeId:i}})})).catch((e=>{let o=+new Date;this.removeScreenSharingStream();let s=U3(t,e);throw this.sendScreenShareEvent({eventName:Q.acs_calling_start_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:r,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:o-n},additionalDetails:{failureReason:s.message,code:s.code,subCode:s.subCode,...K3(s),negotiationTag:a,causeId:i},isVideoOn:this._isLocalVideoStarted,localVideoStream:this.localScreenSharingStream}),s}))}async stopScreenSharing(){let e=this.logger.createFnLogger(o4.StopScreenShare),t=+new Date,n=K0(),r=jG(n),i=this.createVideoNegotiationTag(n,`ScreenSharing`);if(this.sendScreenShareEvent({eventName:Q.acs_calling_stop_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:n,kindOfEvent:$.attempt,timestampInfo:``,isVideoOn:this._isLocalVideoStarted,localVideoStream:this.localScreenSharingStream,additionalDetails:{negotiationTag:i,causeId:r}}),this.tsCall.state!==3)throw new Y({defaultError:J.CALL.STOP_SS_CALL_NOT_CONNECTED});if(!this.tsCall.isScreenSharingOn){let e=+new Date,a=new Y({defaultError:J.CALL.SS_ALREADY_OFF});throw this.sendScreenShareEvent({eventName:Q.acs_calling_stop_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:n,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:e-t},additionalDetails:{failureReason:a.message,code:a.code,subCode:a.subCode,...K3(a),negotiationTag:i,causeId:r},isVideoOn:this._isLocalVideoStarted,localVideoStream:this.localScreenSharingStream}),a}return this.tsCall.stopScreenSharing(void 0,i).then((()=>{let e=+new Date,a=Q2.cloneDeep(this.localScreenSharingStream);this.removeScreenSharingStream(),this.sendScreenShareEvent({eventName:Q.acs_calling_stop_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:n,kindOfEvent:$.success,timestampInfo:{deltaTimeInMs:e-t},isVideoOn:this._isLocalVideoStarted,localVideoStream:a,additionalDetails:{negotiationTag:i,causeId:r}})})).catch((a=>{let o=+new Date,s=U3(e,a,!0),c=typeof s?.message==`string`?s?.message:void 0;throw this.sendScreenShareEvent({eventName:Q.acs_calling_stop_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:n,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:o-t},additionalDetails:{failureReason:c||``,code:s.code,subCode:s.subCode,...K3(s),negotiationTag:i,causeId:r},isVideoOn:this._isLocalVideoStarted,localVideoStream:this.localScreenSharingStream}),s}))}async setConstraints(e){let t=+new Date,n=K0();try{let r=await this._mediaConstraintsManager.setVideoConstraints(e?.video,`mid-call`,n,t);this.logger.info(`Video constraints set - ${JSON.stringify(r)}`)}catch(e){throw new Y({defaultError:J.CALL.SET_VIDEO_CONSTRAINTS,originalError:e})}}on(e,t){if(e!==`stateChanged`&&e!==`idChanged`&&e!==`isMutedChanged`&&e!==`isIncomingAudioMutedChanged`&&e!==`isScreenSharingOnChanged`&&e!==`isLocalVideoStartedChanged`&&e!==`remoteParticipantsUpdated`&&e!==`localVideoStreamsUpdated`&&e!==`localAudioStreamsUpdated`&&e!==`remoteAudioStreamsUpdated`&&e!==`totalParticipantCountChanged`&&e!==`roleChanged`&&e!==`mutedByOthers`&&e!==`callerInfoChanged`&&e!==`transferorInfoChanged`)throw new Y({defaultError:J.CALL.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if(e!==`stateChanged`&&e!==`idChanged`&&e!==`isMutedChanged`&&e!=`isIncomingAudioMutedChanged`&&e!==`isScreenSharingOnChanged`&&e!==`isLocalVideoStartedChanged`&&e!==`remoteParticipantsUpdated`&&e!==`localVideoStreamsUpdated`&&e!==`localAudioStreamsUpdated`&&e!==`remoteAudioStreamsUpdated`&&e!==`totalParticipantCountChanged`&&e!==`roleChanged`&&e!==`mutedByOthers`&&e!==`callerInfoChanged`&&e!==`transferorInfoChanged`)throw new Y({defaultError:J.CALL.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}onMeetingCapabilitiesChanged(e,t){if(e!==`meetingCapabilitiesChanged`)throw new Y({defaultError:J.CALL.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}offMeetingCapabilitiesChanged(e,t){if(e!=`meetingCapabilitiesChanged`)throw new Y({defaultError:J.CALL.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}onParticipantCapabilitiesChanged(e,t){this.logger.log(`participant capabilities change event listener registered`),this._eventEmitter.on(e,t)}offParticipantCapabilitiesChanged(e,t){this.logger.log(`participant capabilities change event listener unregistered`),this._eventEmitter.off(e,t)}setWatermarkAudioOnlyFallbackTriggered(e){this._watermarkAudioOnlyFallbackTriggered=e,this._eventEmitter.emit(`watermarkAudioOnlyFallbackTriggeredChanged`)}onWatermarkAudioOnlyFallbackTriggeredChanged(e,t){this.logger.log(`watermark audio only fallback triggered listener registered`),this._eventEmitter.on(e,t)}offWatermarkAudioOnlyFallbackTriggeredChanged(e,t){this.logger.log(`watermark audio only fallback triggered listener unregistered`),this._eventEmitter.off(e,t)}setIsRenderingRemoteScreenShare(e){this.isRenderingRemoteScreenShare!==e&&(this.isRenderingRemoteScreenShare=e,this._eventEmitter.emit(`isRenderingRemoteScreenShareChanged`))}onIsRenderingRemoteScreenShareChanged(e,t){this._eventEmitter.on(e,t)}offIsRenderingRemoteScreenShareChanged(e,t){this._eventEmitter.off(e,t)}getOrCreateRemoteParticipant(e,t){let n=this._remoteParticipants.find((t=>W2(t.identifier)===W2(e)));return n||(n=new A7(e,this.logger,this,this._callAgent,this._telemetryLogManager),this._remoteParticipants.push(n),this._mriToRemoteParticipantMap.set(W2(n.identifier),n)),t&&n.observeParticipant(t),n}deleteRemoteParticipant(e){let t=!0;return this._remoteParticipants.splice(this._remoteParticipants.indexOf(e),1).length!==1&&(this.logger.warn(`Deleted remote participant array is not 1`),t=!1),this._mriToRemoteParticipantMap.delete(W2(e.identifier))||(this.logger.warn(`Deleted remote participant was not found in mri-to-remoteparticipant map`),t=!1),t}sendCallOnHoldAndResumedEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:d2,properties:e})}catch{this.logger.debug(`Unable to send call hold or resume telemetry`)}}sendVideoEvent(e,t){try{let n,r;try{n=e.localVideoStream?.getStreamMetadata()}catch{this.logger.error(`Unable to get stream meta data on send video event`)}t&&(r=typeof t?.message==`string`?t?.message:void 0,(e.additionalDetails??{}).communicationServicesError=K3(t).communicationServicesError),this._telemetryLogManager.sendEvent({name:e.eventName,tenant:d2,properties:{...n,callId:this.id,localParticipantId:this.tsCall.participantId,timestampInfo:e.timestampInfo,correlationId:e.correlationId,step:e.step||``,failureReason:r||``,isScreenSharingOnFlag:e.isScreenSharingOnFlag,additionalDetails:e.additionalDetails||{},networkInfo:e.networkInfo||[]}})}catch{this.logger.debug(`Unable to send video telemetry`)}}sendScreenShareEvent(e){let t;try{t=e.localVideoStream?.getStreamMetadata()}catch{this.logger.error(`Unable to get stream meta data on send video event`)}try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:d2,properties:{...t,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:e.correlationId,kindOfEvent:e.kindOfEvent,timestampInfo:e.timestampInfo,additionalDetails:e.additionalDetails,isVideoOn:e.isVideoOn}})}catch{this.logger.debug(`Unable to send screen share telemetry`)}}sendRawMediaEvent(e){let t={...e};t.localAudioStream=e.localAudioStream?.source instanceof MediaStream?`MediaStream`:`Device`;try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:d2,properties:t})}catch{this.logger.debug(`Unable to send raw media telemetry`)}}sendAudioEvent(e,t){try{let n;t&&(n=typeof t?.message==`string`?t?.message:void 0,e.additionalDetails={...K3(t)});let r={callId:this.id,localParticipantId:this.tsCall.participantId,timestampInfo:e.timestampInfo,correlationId:e.correlationId,step:e.step||``,failureReason:n||``,additionalDetails:e.additionalDetails||{},networkInfo:e.networkInfo||[]};e.eventType!==void 0&&(r.eventType=e.eventType),e.initiatedBySdk&&(r.initiatedBySdk=!0),this._telemetryLogManager.sendEvent({name:e.eventName,tenant:d2,properties:r})}catch{this.logger.debug(`Unable to send audio telemetry`)}}sendCallStageEvent(e,t,n,r,i){try{let a,o=``;t&&(a=this?.tsCall?.callEndDiagnosticsInfo||n||{},o=t.message);let s=this._joinContextDescription===I2.RoomCall||this.kind===VG.Call&&this._direction===`Incoming`&&!this.tsCall.groupId&&!!this.tsCall.meetingData?.meetingCode&&!this.tsCall.threadId,c=!s&&this._joinContextDescription===I2.TeamsMeetingLink||this._joinContextDescription===I2.TeamsMeetingId||this._joinContextDescription===I2.TeamsCoordinates||this._direction==`Incoming`&&!this.tsCall.groupId&&!!this.tsCall.meetingData&&!!this.tsCall.threadId,l={localParticipantId:this?.tsCall?.participantId||``,callId:this?.tsCall?.callId||``,callType:this?.tsCall?.callType||``,callDirection:this._direction,failureReason:o,callEndDiagnosticsInfo:a,calleeIdentityType:this.getParticipantIdentityType(),groupJoin:!!this?.tsCall?.groupId,roomJoin:s,meetingJoin:c,hostRegion:this?.tsCall?.region||``,correlationId:e.correlationId,timestampInfo:e.timestampInfo,...e.additionalPayload,networkInfo:r||[],negotiationTag:e.additionalPayload?.additionalProperties.negotiationTag??``,causeId:e.additionalPayload?.additionalProperties.causeId??``};this._telemetryLogManager.sendEvent({name:e.eventName,tenant:d2,properties:l},void 0,i)}catch{}}getParticipantIdentityType(){if(this.tsCall?.participants.length>1)return U2.group;if(this.tsCall?.participants.length===0)return U2.unknown;let e=this.tsCall?.participants[0];return G2(e.id).kind}optimalVideoCountChanged(e,t){let n=this._optimalVideoCount,r=e||this.tsCall.optimalVideoCount,i=Z().telemetry.progressEvents.enableOvcChangedEvent;if(r&&n!==r&&i)try{M7(this._telemetryLogManager,this.logger,{...j7(this,this._callAgent,K0(),this._joinContextDescription),step:`optimalVideoCount-changed`,previousOptimalVideoCount:n,newOptimalVideoCount:r,changeReason:t,currentNumberOfVideosRendered:this.activeRemoteVideoStreamViews?.size||0})}catch{this.logger.error(`Failed to send optimal video count change telemetry`)}finally{this._optimalVideoCount=r??1}}_sendNetworkChangedTelemetry(){try{let e=(e,t,n)=>{M7(this._telemetryLogManager,this.logger,{...j7(this,this._callAgent,K0(),this._joinContextDescription),step:`network-changed`,trouterState:e,onLine:t,rdpState:n})};this._trouterStateChangedListener=t=>{e(t,navigator.onLine,this._mmrRdpConnectionManager.state)},this._callAgent.onTrouterStateChanged(this._trouterStateChangedListener),this._onlineListener=t=>{e(this._callAgent.getTrouterState(),!0,this._mmrRdpConnectionManager.state)},window.addEventListener(`online`,this._onlineListener),this._offlineListener=t=>{e(this._callAgent.getTrouterState(),!1,this._mmrRdpConnectionManager.state)},window.addEventListener(`offline`,this._offlineListener),this._mmrRdpConnectionManager.on(`stateChange`,(t=>{e(this._callAgent.getTrouterState(),!1,t)})),e(this._callAgent.getTrouterState(),navigator.onLine,this._mmrRdpConnectionManager.state)}catch{this.logger.warn(`Failed to subscribe to network changed`)}}_setupSelectedDeviceChangedTelemetry(){try{let e=e=>{M7(this._telemetryLogManager,this.logger,{...j7(this,this._callAgent,K0(),this._joinContextDescription),step:`selectedDevice-changed`,selectedDeviceType:e.selectedDeviceType,oldDevice:e.oldDevice,newDevice:e.newDevice})};if(this._selectedDeviceManager){this._selectedDeviceManager.on(`selectedDeviceChanged`,e);let t=this._selectedDeviceManager.selectedDevice(`Speaker`),n=this._selectedDeviceManager.selectedDevice(`Microphone`);e({selectedDeviceType:`Speaker`,oldDevice:void 0,newDevice:t}),e({selectedDeviceType:`Microphone`,oldDevice:void 0,newDevice:n})}}catch{this.logger.warn(`Failed to subscribe to selectedDevice changed`)}}setLocalVideoStream(e){if(!this._callAgent.tsStack)throw new Y({defaultError:J.CALL.VIDEO_UNDEFINED_STACK});if(!this.localVideoStream&&e&&!this._localVideoStreams.find((t=>t===e))){this.localVideoStream=e,this._localVideoStreams.push(this.localVideoStream),this.localVideoStream.mediaStreamType!==`RawMedia`&&this._callAgent.tsStack.getDeviceManager()?.selectDevices({camera:e.source.id}),this.localVideoStream.addCall(this);try{this._eventEmitter.emit(`localVideoStreamsUpdated`,{added:[this.localVideoStream],removed:[]})}catch{this.logger.warn(`Application threw on emit localVideoStreamsUpdated added`)}this.logger.log(`isLocalVideoStarted changed=true`),this._isLocalVideoStarted=!0,this._eventEmitter.emit(`isLocalVideoStartedChanged`)}}removeLocalVideoStream(e){if(this.localVideoStream&&e===this.localVideoStream&&this.localVideoStreams.find((e=>e===this.localVideoStream))){if(this.logger.log(`Attempting to remove local video stream`),this._localVideoStreams.splice(this._localVideoStreams.indexOf(this.localVideoStream),1).length===0)return void this.logger.warn(`Stream not found, failed to remove stream from localVideoStreams collection`);this.logger.log(`Local video stream removed successfully`),this.localVideoStream.removeCall(this),this.localVideoStream.autoDisposeOnCallEnd&&this.localVideoStream.dispose();let e=this.localVideoStream;this.localVideoStream=void 0;try{this._eventEmitter.emit(`localVideoStreamsUpdated`,{added:[],removed:[e]})}catch{this.logger.warn(`Application threw on emit localVideoStreamsUpdated removed`)}this.logger.log(`isLocalVideoStarted changed=false`),this._isLocalVideoStarted=!1,this._eventEmitter.emit(`isLocalVideoStartedChanged`)}}setLocalAudioStream(e){if(!this._callAgent.tsStack)throw new Y({defaultError:J.CALL.LOCAL_AUDIO_UNDEFINED_STACK});if(e)e.on(`audioSourceChanged`,this.audioSourceChanged),this._localAudioStreams.push(e),e.addCall(this),this._eventEmitter.emit(`localAudioStreamsUpdated`,{added:[e],removed:[]});else if(this._localAudioStreams.length===0){if(this._userProvidedLocalAudioStreamCache)return(e=this._userProvidedLocalAudioStreamCache).on(`audioSourceChanged`,this.audioSourceChanged),this._localAudioStreams.push(e),e.addCall(this),void this._eventEmitter.emit(`localAudioStreamsUpdated`,{added:[e],removed:[]});let t=this.deviceManager?.selectedMicrophone;if(t){let e=new u8(t);e.on(`audioSourceChanged`,this.audioSourceChanged),this._localAudioStreams.push(e),e.addCall(this),this._eventEmitter.emit(`localAudioStreamsUpdated`,{added:[e],removed:[]})}else this.logger.warn(`Could not get current selected microphone to update localAudioStreams collection`)}else this.logger.warn(`No localAudioStream provided and the collection is not empty, doing nothing`)}removeLocalAudioStream(e){if(e){if(this.logger.log(`Attempting to remove local audio stream`),e.off(`audioSourceChanged`,this.audioSourceChanged),e.autoDisposeOnCallEnd&&e.dispose(),this._localAudioStreams.splice(this._localAudioStreams.indexOf(e),1).length===0)return void this.logger.warn(`Stream not found, failed to remove stream from localAudioStreams collection`);e.removeCall(this),this.logger.log(`Local audio stream removed successfully`),this._eventEmitter.emit(`localAudioStreamsUpdated`,{added:[],removed:[e]})}}_handleAudioEffectsOperations(){try{let e=this._localAudioStreams?.[0];if(!e)return void this.logger.debug(`No LocalAudioStream found in the call, cannot handle call audio effects operations`);this._audioEffectsStatsListener=e=>{this._audioEffectsProcessorStats=e},e.feature(Z5.AudioEffects)?.on(`effectsProcessorStatsUpdated`,this._audioEffectsStatsListener)}catch(e){this.logger.warn(`Error handling audio effects operations during call start: ${e}`)}}isAudioPermitted(){return!!this.feature(Z5.MediaAccess)?.getLocalParticipantMediaAccess().isAudioPermitted}isVideoPermitted(){return!!this.feature(Z5.MediaAccess)?.getLocalParticipantMediaAccess().isVideoPermitted}removeScreenSharingStream(){if(this.localScreenSharingStream&&this.localVideoStreams.find((e=>e===this.localScreenSharingStream))){if(Z()?.calling?.allowAccessRawMediaStream&&this.localScreenSharingStream?.mediaStreamType===`RawMedia`){let e=this._callAgent.tsStack?.getDeviceManager();e?.unsetRawMediaStream&&e.unsetRawMediaStream(2)}this.localScreenSharingStream.dispose(),this.localScreenSharingStream.removeCall(this);let e=this._localVideoStreams.indexOf(this.localScreenSharingStream);this._localVideoStreams.splice(e,1);let t=this.localScreenSharingStream;this.localScreenSharingStream=void 0,this._isScreenSharingOn=!1,this._eventEmitter.emit(`localVideoStreamsUpdated`,{added:[],removed:[t]})}}mapTsCallState(e){let t=$Ee[e];switch(t){case`Unknown`:case void 0:this.logger.log(`Ignored tsCall state \`${e}\``);break;case`Disconnected`:{this._callEndReason=V3(this).callEndReason,this._remoteParticipants.forEach((e=>{e.setCallEndReason(H3(this,e.tsRemoteParticipant).callEndReason),e.setParticipantState(`Disconnected`)}));let n=this._remoteParticipants.map((e=>e));this._remoteParticipants=[],this._mriToRemoteParticipantMap.clear(),this._eventEmitter.emit(`remoteParticipantsUpdated`,{added:[],removed:n}),this.localVideoStream&&this.removeLocalVideoStream(this.localVideoStream),this.localAudioStreams[0]&&this.removeLocalAudioStream(this.localAudioStreams[0]),this._rawAudioStreamChangedSubscription?.dispose&&this._rawAudioStreamChangedSubscription.dispose(),Z().calling.allowAccessRawMediaStream&&this.remoteAudioStreams[0]&&this.removeRemoteAudioStream(this.remoteAudioStreams[0]),this._userProvidedLocalAudioStreamCache=void 0,this.logger.log(`Mapped tsCall state:${e} to ${t}`),this._setCallState(t),this._telemetryLogManager.flushAllEvents(this.id).then((()=>{this.logger.log(`Telemetry flushed`)})).catch((e=>{this.logger.warn(`Failed to flush telemetry log manager events`)}));break}case`Connected`:this.logger.log(`Mapped tsCall state:${e} to ${t}`),this._remoteParticipantsChangedListeners.forEach((e=>{e.dispose()})),this._setCallState(t),this._setOrUpdateDeviceEventsTask=this._setOrUpdateDeviceEventsTask.then((()=>this.setOrUpdateMediaMetricsDeviceEvents().catch(A4))),Z().calling.allowAccessRawMediaStream&&this.subscribeToGetRemoteAudioStream();break;case`Incoming Call`:{this.logger.log(`state changed from ${this._state} to 'Incoming Call'`);let e=new P7(this.tsCall,{config:this._config});M7(this._telemetryLogManager,this.logger,{...j7(this,this._callAgent,K0(),this._joinContextDescription),step:`state-changed`,oldState:this._state,newState:`Incoming Call`,callTypeInfo:{initiatorKind:e.initiatorKind,targetKind:e.targetKind,transferor:e.transferorKind,context:e.context,callScenario:e.callScenario,direction:e.direction},teamsMeetingTenantId:this._teamsMeetingTenantId||``,teamsMeetingThreadId:this._teamsMeetingThreadId||``,callDurationInSeconds:this.tsCall.callStartedAt?Math.floor((Date.now()-this.tsCall.callStartedAt?.getTime())/1e3):-1});break}default:this.logger.log(`Mapped tsCall state:${e} to ${t}`),this._setCallState(t)}}shallStopVideo(e){let t=Z()?.calling?.deviceNotFunctioningMuted,n=Z()?.calling?.deviceCaptureMutedVideo,r=Z()?.calling?.preventStopVideo,i=e.type===25&&e.value===3,a=i&&e.mediaType===1,o=e.type===33&&e.value===3,s=t8(),c=n8()===`ios`&&s.engine===`Safari`,l=n8()===`android`,u=this.tsCall.state===3;return r?u&&this.tsCall.isVideoOn&&o:t&&u&&this.tsCall.isVideoOn&&(o||c&&i||n&&l&&a)}shallRemoveLocalVideoStreamOnBadUfd(e){let t=this.tsCall.localMediaStreams.find((e=>e.mediaType===1)),n=e.mediaType===1&&e.value===3&&e.type===25,r=this.tsCall.state==4||this.tsCall.state===5;if(t8().formFactor===`Mobile`&&(n||document.visibilityState==`hidden`)&&this.localVideoStream&&r&&!t||!Z()?.calling?.removeLvsCheckOnCallStartAndCallAccept)return!1;let i=this.tsCall.state===3;return e.mediaType===1&&e.value===3&&(e.type===33||e.type===25||e.type===34)&&!!this.localVideoStream&&!i&&!t}shallStopAudio(e){let t=Z()?.calling?.deviceNotFunctioningMuted,n=Z()?.calling?.osAutoRecoverAudio,r=e.type===25&&e.value===3&&e.mediaType===0,i=e.type===9&&e.value===3,a=t8(),o=n8()===`ios`&&a.engine===`Safari`,s=this.tsCall.state===3;return n?t&&s&&i:t&&!this._isDeviceNotFunctioningMuted&&s&&(i||o&&r)}markCallMuted(){this._isDeviceNotFunctioningMuted=!0,this._handleMuteChanges()}audioDidAutoRecover(e){let t=Z()?.calling?.deviceCaptureMuteRecover&&!Z()?.calling?.preventFakeMute,n=e.type===25&&e.value===1&&e.mediaType===0,r=this.tsCall.state===3,i=t8(),a=n8()===`ios`&&i.engine===`Safari`,o=e.type===9&&e.value===1;return t&&this._isDeviceNotFunctioningMuted&&r&&(o||a&&n)}sendParticipantAddedOrRemovedEvent(e){try{this._telemetryLogManager.sendEvent({name:Q.acs_calling_participant_added_or_removed,tenant:d2,properties:{callId:this.id,remotePerticipantId:Array.isArray(e?.remoteParticipantIds)?e?.remoteParticipantIds.slice(0,Z().telemetry.maxExistingReportedParticipants):[],participantAddedOrRemoved:e.participantAddedOrRemoved,localParticipantId:this.tsCall.participantId,kindOfEvent:e.kindOfEvent,correlationId:e.correlationId||``,timestampInfo:e.timestampInfo||``,additionalDetails:e.additionalDetails||{},networkInfo:e.networkInfo||[]}})}catch{this.logger.debug(`Unable to send participant added or removed telemtery`)}}_handleLocalRingingCallState(e){this._state===`Connected`||this._direction!==`Outgoing`||this._localRingingStateSet||this._remoteParticipantsChangedListeners.push(e.changed((()=>{e.state!==2||this._state===`Connected`||this._localRingingStateSet||(this._setCallState(`Ringing`),this._localRingingStateSet=!0,this._remoteParticipantsChangedListeners.forEach((e=>{e.dispose()})))})))}_setCallState(e){if(e!==this._state){let t=this._state,n=e,r=new P7(this.tsCall,{config:this._config});this.logger.log(`state changed from ${t} to ${n}`),this._state=n,n===`Connected`&&(this._connectedTimestamp=Date.now()),this._eventEmitter.emit(`stateChanged`),M7(this._telemetryLogManager,this.logger,{...j7(this,this._callAgent,K0(),this._joinContextDescription),step:`state-changed`,oldState:t,newState:n,callTypeInfo:{initiatorKind:r.initiatorKind,targetKind:r.targetKind,transferor:r.transferorKind,context:r.context,callScenario:r.callScenario,direction:r.direction},teamsMeetingTenantId:this._teamsMeetingTenantId||``,teamsMeetingThreadId:this._teamsMeetingThreadId||``,callDurationInSeconds:this.tsCall.callStartedAt?Math.floor((Date.now()-this.tsCall.callStartedAt?.getTime())/1e3):-1,additionalDetails:this._state===`Disconnected`&&this._callEndReason?{...q3(this._callEndReason)}:void 0})}}_setCallRole(e){if(e!==this._lastTsCallAdvancedMeetingRole){let t=iTe(Z(),e);t===w2?this.logger.log(`tsParticipant advancedMeetingRole=${this._role} had no mapping`):this.logger.log(`mapped tsParticipant advancedMeetingRole=${e}=>${t}`),M7(this._telemetryLogManager,this.logger,{...j7(this,this._callAgent,K0(),this._joinContextDescription),step:`role-changed`,oldAcsRole:this._role,newAcsRole:t,serviceRole:e||``}),this._role!=t&&(this.logger.log(`self-role changed ${this._role}=>${e}`),this._role=t,this._lastTsCallAdvancedMeetingRole=e,this._capabilityResolver.resolveCapabilitiesBasedOnRole(),this._eventEmitter.emit(`roleChanged`))}}_setMeetingCapabilities(e){oTe(e,this._lastTsCallMeetingDetails)&&(M7(this._telemetryLogManager,this.logger,{...j7(this,this._callAgent,K0(),this._joinContextDescription),step:`meetingCapabilities-changed`,oldMeetingDetails:this._lastTsCallMeetingDetails,newMeetingDetails:e}),this.logger.log(`Core Meeting Capabilities has changed to: ${JSON.stringify(e)}`),this._capabilityResolver.resolveCapabilitiesBasedOnMeetingCapabilities(),this._eventEmitter.emit(`meetingCapabilitiesChanged`)),Object.assign(this._lastTsCallMeetingDetails,e)}removeRemoteAudioStream(e){if(e){if(this.logger.log(`Attempting to remove remote audio stream`),this._remoteAudioStreams.splice(this._remoteAudioStreams.indexOf(e),1).length===0)return void this.logger.warn(`Stream not found, failed to remove stream from remoteAudioStreams collection`);this.logger.log(`remote audio stream removed successfully`),this._eventEmitter.emit(`remoteAudioStreamsUpdated`,{added:[],removed:[e]})}}async setOrUpdateMediaMetricsDeviceEvents(){if(Z().calling.mediaMetricsDeviceEventsEnabled)try{let e=await this.tsCall.getMediaSessionStatsAsync?.();if(e?.metrics?.DeviceEvents!==void 0){let t=JSON.parse(e.metrics.DeviceEvents),n=rTe(this._mediaMetricsDeviceEvents||{},t);n.length>0&&(this._mediaMetricsDeviceEvents=t,this.stats.recordEvent({name:s3.media_metrics_device_events,callId:this.id,localParticipantId:this.tsCall.participantId,data:{metricsDeviceEvents:n||{},metricsDevicesChangeCount:t?.metrics_DevicesChangeCount||0,metricsDevicesCount:t?.metrics_DevicesCount||{}}}))}else this.logger.info(`Failed to set media metrics device events telemetry: no valid events data`)}catch{this.logger.error(`Failed to set media metrics device events telemetry`)}}setClientCallStartOptions(e){let t={},n=0;return e?.firstPartyOptions?.isImmersiveMode&&(n|=32768),e?.firstPartyOptions?.accessToImmersiveEvents&&(n|=2097152),Z()?.calling?.supportLiveStreaming&&(n|=32),Z()?.calling.sharedLineAppearance.enabled&&(n|=128),Z()?.reaction?.enableReactionsThroughNGC&&(n|=524288),this._allowBreakoutRoomJoin&&(n|=4098),n>0&&(t.clientEndpointCapabilities=n),t.sendMediaModalities=this.setMediaModalities(e?.mediaModalities),t}setMediaModalities(e){if(e){let t={mediaStates:[]};return e.audio&&t.mediaStates.push({mediaType:0}),e.video?t.mediaStates.push({mediaType:1}):t.mediaStates.push({mediaType:1,isDisabled:!0}),e.screenShare||t.mediaStates.push({mediaType:2,isDisabled:!0}),t}}getLocalVideoStreamFromCallOptions(e){let t;if(Array.isArray(e?.videoOptions?.localVideoStreams)){if(e?.videoOptions?.localVideoStreams.length!==1)throw new Y({defaultError:J.CALL.ONLY_SINGLE_VIDEO_STREAM});if(t=e?.videoOptions?.localVideoStreams[0],!(t instanceof J6))throw new Y({defaultError:J.CALL.NOT_INSTANCE_OF_LVS})}return t}getLocalAudioStreamFromCallOptions(e){let t;if(Array.isArray(e?.audioOptions?.localAudioStreams)){if(e?.audioOptions?.localAudioStreams.length!==1)throw new Y({defaultError:J.CALL.ONLY_SINGLE_AUDIO_STREAM});if(t=e?.audioOptions?.localAudioStreams[0],!(t instanceof u8))throw new Y({defaultError:J.CALL.NOT_INSTANCE_OF_LAS})}return t&&(this._userProvidedLocalAudioStreamCache=t),t}async _setRawStream(e,t){if(!Z().calling.allowAccessRawMediaStream)throw new Y({defaultError:J.CALL.ACCESS_RAW_MEDIA_STREAM_DISABLED});let n=await this._callAgent.tsStack?.getDeviceManagerAsync?.();if(!n?.setRawMediaStream)throw new Y({defaultError:J.CALL.ACCESS_RAW_MEDIA_STREAM_UNDEFINED_FUNC});try{let r=await e.getMediaStream();if(!r)throw new Y({defaultError:J.CALL.SS_RAW_STREAM_UNDEFINED});n.setRawMediaStream(r,t)}catch(e){if(t===1)throw new Y({defaultError:J.CALL.VIDEO_SET_MEDIA_STREAM,originalError:e});if(t===2)throw new Y({defaultError:J.CALL.SS_RAW_STREAM_SET,originalError:e})}}shallRemoveLvsAfterConnectedSuccessfully(e,t,n,r,i,a,o){if(this.tsCall.localMediaStreams.find((e=>e.mediaType===1)))this.sendVideoEvent({correlationId:n,eventName:Q.acs_calling_start_video_success,timestampInfo:{deltaTimeInMs:r-i},localVideoStream:e,step:t,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:a,causeId:o}});else{if(!Z()?.calling?.removeLvsCheckOnCallStartAndCallAccept)return;this.localVideoStream&&this.removeLocalVideoStream(this.localVideoStream);let r=+new Date,s=new Y({defaultError:J.CALL.VIDEO_FAILED_TO_START,defaultErrorMessageArgs:[t]});this.logger.error(s.message),this.sendVideoEvent({correlationId:n,eventName:Q.acs_calling_start_video_failure,timestampInfo:{deltaTimeInMs:r-i},localVideoStream:e,step:t,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:a,causeId:o}},s)}}shallRemoveLasAfterConnectedSuccessfully(e,t,n,r,i){if(this.tsCall.localMediaStreams.find((e=>e.mediaType===0)))this.sendRawMediaEvent({eventName:Q.acs_calling_start_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:n,kindOfEvent:$.success,localAudioStream:e,timestampInfo:{deltaTimeInMs:r-i},additionalDetails:``});else{if(!Z().calling.removeLocalAudioStreamCheckOnCallStartAndCallAccept)return;this.removeLocalAudioStream(this.localAudioStreams[0]);let r=+new Date;this.logger.error(`Removing local audio stream because audio failed to start during call-${t} process.`);let a=new Y({defaultError:J.CALL.AUDIO_FAILED_TO_START,defaultErrorMessageArgs:[t]});this.sendRawMediaEvent({eventName:Q.acs_calling_start_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:n,localAudioStream:e,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:r-i},additionalDetails:{failureReason:a.message||``,code:a.code,subCode:a.subCode,...K3(a)}})}}createVideoNegotiationTag(t,n){let r=0,i=``;return n===`Video`?(r=++e.videoId,i=`v`):(r=++e.screenShareVideoId,i=`ss`),`${t};${i}_${r}`}_enableOrDisable_largeMeeting_videoRendering(){try{!this._isHandlingLargeMeetingVideoRendering&&this._totalParticipantCount-1>=Z().rendering.remoteVideo.largeMeeting.participantCountThreshold?(this._isHandlingLargeMeetingVideoRendering=!0,this._internalDominantSpeakersListener=new VDe(new S6(this.logger.createChild((()=>`DominanSpeakersFeatureInternal:: Call(id=${this.tsCall.callId})`)))),this._internalDominantSpeakersListener.initialize(this.tsCall,this._callAgent,this._telemetryLogManager,this.logger,!0),this.logger.info(`Initialized internal dominant speakers listener`),this._internalDominantSpeakersListener.on(`dominantSpeakersChanged`,(()=>{this.handleDominantSpeakersVideos()})),this.handleDominantSpeakersVideos(),this.logger.info(`Initialized large meeting video rendering handler`)):this._isHandlingLargeMeetingVideoRendering&&(this._totalParticipantCount-1>=Z().rendering.remoteVideo.largeMeeting.participantCountThreshold?this.handleDominantSpeakersVideos():(this._isHandlingLargeMeetingVideoRendering=!1,this._internalDominantSpeakersListener?.dispose(),this._internalDominantSpeakersListener=void 0,this.logger.info(`Disposed of internal dominant speakers listener`),this.remoteParticipants.forEach((e=>{e.videoStreams.forEach((e=>{e.setIsAvailable(e.tsStream.isAvailable)}))})),this.logger.info(`All remote streams isAvailable flags were reset`),this.logger.info(`Disposed large meeting video rendering handler`)))}catch(e){this.logger.error(`Failed to handle large meeting video rendering`,e)}}async handleConsentCapabilitiesChanges(){this.explicitConsentStateImp.areCoreCapabilitiesConsentRestricted()&&(this.isMuted||this.mute().then((()=>{this.logger.log(`ExplicitConsentCallStateManager: Handle Capabilities changes: Mic is turned off :`,this.isMuted)})).catch((e=>{this.logger.error(`ExplicitConsentCallStateManager: Handle Capabilities changes: Error stopping mic`,e)})),this.isLocalVideoStarted&&this.localVideoStream&&this.stopVideo(this.localVideoStream).then((()=>{this.logger.log(`ExplicitConsentCallStateManager: Handle Capabilities changes: Video is turned off :`,this.isLocalVideoStarted)})).catch((e=>{this.logger.error(`ExplicitConsentCallStateManager: Handle Capabilities changes: Error stopping video`,e)})),this.isScreenSharingOn&&this.stopScreenSharing().then((()=>{this.logger.log(`ExplicitConsentCallStateManager: Handle Capabilities changes: Screenshare is turned off :`,this.isScreenSharingOn)})).catch((e=>{this.logger.error(`ExplicitConsentCallStateManager: Handle Capabilities changes: Error stopping screenshare`,e)})))}handleDominantSpeakersVideos(){this.logger.info(`Dominant speakers changed during large meeting`);let e=this.getTopNDominantSpeakersWithVideoOn();this.logger.info(`There are currently ${e.length} top-n speakers with video on in the large meeting`),e.forEach((e=>{e.videoStreams.filter((e=>e.mediaStreamType===`Video`)).forEach((e=>{e.setIsAvailable(e.tsStream.isAvailable)}))})),this._remoteParticipants.filter((t=>!e.includes(t))).forEach((e=>{e.videoStreams.filter((e=>e.mediaStreamType===`Video`)).forEach((e=>{try{e.setIsAvailable(!1)}catch(e){let t=new Y({defaultError:J.CALL.LARGE_MEETING_FORCE_ISAVAILABLE,originalError:e});this.logger.warn(t.message)}let t=this.activeRemoteVideoStreamViews.get(e.id);t&&t.forEach((e=>{try{e.disposed||(e.dispose(b3.Internal_LargeMeetingVideoRendering),this.logger.info(`Successfully disposed of view during large meeting`))}catch(e){let t=new Y({defaultError:J.CALL.LARGE_MEETING_DISPOSE_VIEW,originalError:e});this.logger.warn(t.message)}}))}))}))}};R7.videoId=0,R7.screenShareVideoId=0,I7([zG,L7(`design:type`,Object)],R7.prototype,`logger`,void 0),I7([WG(o4.BindToCall),L7(`design:type`,Function),L7(`design:paramtypes`,[]),L7(`design:returntype`,Array)],R7.prototype,`bindTsCall`,null),I7([WG(o4.Feature),L7(`design:type`,Function),L7(`design:paramtypes`,[Object]),L7(`design:returntype`,typeof(tLe=typeof TFeature<`u`&&TFeature)==`function`?tLe:Object)],R7.prototype,`feature`,null),I7([GG(o4.HangUp),L7(`design:type`,Function),L7(`design:paramtypes`,[Object]),L7(`design:returntype`,Promise)],R7.prototype,`hangUp`,null),I7([GG(o4.Mute),L7(`design:type`,Function),L7(`design:paramtypes`,[]),L7(`design:returntype`,Promise)],R7.prototype,`mute`,null),I7([GG(o4.Unmute),L7(`design:type`,Function),L7(`design:paramtypes`,[]),L7(`design:returntype`,Promise)],R7.prototype,`unmute`,null),I7([GG(o4.MuteAllRemoteParticipants),L7(`design:type`,Function),L7(`design:paramtypes`,[]),L7(`design:returntype`,Promise)],R7.prototype,`muteAllRemoteParticipants`,null),I7([GG(o4.MuteIncomingAudio),L7(`design:type`,Function),L7(`design:paramtypes`,[]),L7(`design:returntype`,Promise)],R7.prototype,`muteIncomingAudio`,null),I7([GG(o4.UnmuteIncomingAudio),L7(`design:type`,Function),L7(`design:paramtypes`,[]),L7(`design:returntype`,Promise)],R7.prototype,`unmuteIncomingAudio`,null),I7([GG(o4.SendDtmf),L7(`design:type`,Function),L7(`design:paramtypes`,[String]),L7(`design:returntype`,Promise)],R7.prototype,`sendDtmf`,null),I7([GG(o4.StartVideo),L7(`design:type`,Function),L7(`design:paramtypes`,[J6]),L7(`design:returntype`,Promise)],R7.prototype,`startVideo`,null),I7([GG(o4.StopVideo),L7(`design:type`,Function),L7(`design:paramtypes`,[J6]),L7(`design:returntype`,Promise)],R7.prototype,`stopVideo`,null),I7([GG(o4.StartAudio),L7(`design:type`,Function),L7(`design:paramtypes`,[u8]),L7(`design:returntype`,Promise)],R7.prototype,`startAudio`,null),I7([KG(o4.Hold),GG(o4.Hold),L7(`design:type`,Function),L7(`design:paramtypes`,[]),L7(`design:returntype`,Promise)],R7.prototype,`hold`,null),I7([KG(o4.Resume),GG(o4.Resume),L7(`design:type`,Function),L7(`design:paramtypes`,[]),L7(`design:returntype`,Promise)],R7.prototype,`resume`,null),I7([GG(o4.StartScreenShare),L7(`design:type`,Function),L7(`design:paramtypes`,[J6]),L7(`design:returntype`,Promise)],R7.prototype,`startScreenSharing`,null),I7([GG(o4.StopScreenShare),L7(`design:type`,Function),L7(`design:paramtypes`,[]),L7(`design:returntype`,Promise)],R7.prototype,`stopScreenSharing`,null),I7([GG(o4.SetConstraints),L7(`design:type`,Function),L7(`design:paramtypes`,[Object]),L7(`design:returntype`,Promise)],R7.prototype,`setConstraints`,null);var nLe=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},z7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},B7=class extends R7{get info(){return this._info}constructor(e,t,n,r,i){super(e,t,n,r,VG.Call,i),this._info=this.callInfo,this._allowBreakoutRoomJoin=Z().calling.breakoutRooms.enabled}dispose(){super.dispose(),this._extensibleApi.dispose()}addParticipant(e,t){let n,r,i=t,a=t,o=t,s=+new Date,c=K0();if(this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.attempt,participantAddedOrRemoved:`add`,correlationId:c,timestampInfo:{attemptTimestamp:s},additionalDetails:{customContext:{userToUserPresent:!!i?.customContext?.userToUser,xHeadersPresent:!!i?.customContext?.xHeaders&&i?.customContext.xHeaders.length>0}}}),this._callAgent.isEnterpriseUser())switch(this.validateThreadId(e,t),wG(e).kind){case`communicationUser`:r=i.threadId;break;case`microsoftTeamsUser`:r=o.threadId;break;case`phoneNumber`:r=a.threadId;break;default:{let e=new Y({defaultError:J.CALL.ADD_UNKNOWN});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`add`,correlationId:c,timestampInfo:{deltaTimeInMs:+new Date-s},additionalDetails:{code:e.code,failureReason:e.message,...K3(e)}}),e}}let l;a?.alternateCallerId&&(q2(a.alternateCallerId),n=W2(a.alternateCallerId));try{if($5(o4.AddParticipant,this.state),l=q2(e),!R4(this.acsProxy,this.acsCustomRelayManager,!1,l))throw new Y({defaultError:J.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN})}catch(e){throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`add`,correlationId:c,timestampInfo:{deltaTimeInMs:+new Date-s},additionalDetails:{code:e.code,failureReason:e.message,...K3(e)}}),e}if(this._remoteParticipants.find((t=>W2(t.identifier)===W2(e)))){let t=new Y({defaultError:J.CALL.PARTICIPANT_ALREADY_IN_CALL,defaultErrorMessageArgs:[wG(e).kind]});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`add`,correlationId:c,timestampInfo:{deltaTimeInMs:+new Date-s},additionalDetails:{code:t.code,failureReason:t.message,...K3(t)}}),t}let u=[...this.remoteParticipants.values()].map((e=>e.identifier));this._isAcsTeamsCall=z4([...u,e],this._callAgent.kind),Z().calling.enableSmePassFakeConversation&&this._isAcsTeamsCall&&!r&&(r=this.tsCall.threadId||B4());let d=sTe(lTe(this),wG(e));Z().calling.enableOpsSmePassFakeConversation&&d&&!r&&(r=this.tsCall.threadId||B4());let f=AG();F6.setCauseIdToNetworkInfo(f);let p=this.getOrCreateRemoteParticipant(G2(W2(e)));return this.tsCall.addParticipant(W2(e),{alternateId:n,threadId:r,customHeaderContext:V4(a)},f).then((()=>{this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.success,participantAddedOrRemoved:`add`,correlationId:c,timestampInfo:{deltaTimeInMs:+new Date-s},networkInfo:F6.getRemoveCauseIdToNetworkInfo(f)})})).catch((t=>{let{callEndReason:n}=H3(this,p.tsRemoteParticipant,t);p.callEndReason||p.setCallEndReason(n);let r=q3(n);this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`add`,correlationId:c,timestampInfo:{deltaTimeInMs:+new Date-s},additionalDetails:{code:r?.callEndReason.code,subCode:r?.callEndReason.subCode,failureReason:r?.callEndReason.message,...r},networkInfo:F6.getRemoveCauseIdToNetworkInfo(f)}),this._remoteParticipants.find((t=>W2(t.identifier)===W2(e)))&&(this.deleteRemoteParticipant(p),this._eventEmitter.emit(`remoteParticipantsUpdated`,{added:[],removed:[p]}))})),p}async removeParticipant(e,t){let n=+new Date,r=K0();this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.attempt,participantAddedOrRemoved:`remove`,correlationId:r,timestampInfo:{attemptTimestamp:n}});try{$5(o4.RemoveParticipant,this.state),q2(e)}catch(e){let t=new Y({defaultError:J.IDENTIFIER.PARSE_INVALID_IDENTIFIER,originalError:e});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`remove`,correlationId:r,timestampInfo:{deltaTimeInMs:+new Date-n},additionalDetails:{code:e.code,failureReason:e.message,...K3(t)}}),t}let i=this._remoteParticipants.find((t=>W2(t.identifier)===W2(e)));if(!i){let t=new Y({defaultError:J.CALL.PARTICIPANT_NOT_IN_CALL,defaultErrorMessageArgs:[wG(e).kind]});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`remove`,correlationId:r,timestampInfo:{deltaTimeInMs:+new Date-n},additionalDetails:{code:t.code,subCode:t.subCode,failureReason:t.message,...K3(t)}}),t}let a=AG();F6.setCauseIdToNetworkInfo(a);try{await this.tsCall.removeParticipant(W2(e)),this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.success,participantAddedOrRemoved:`remove`,correlationId:r,timestampInfo:{deltaTimeInMs:+new Date-n},networkInfo:F6.getRemoveCauseIdToNetworkInfo(a)})}catch(e){let t=H3(this,i.tsRemoteParticipant,e).callEndReason;i.callEndReason||i.setCallEndReason(t);let o=q3(t);throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`remove`,correlationId:r,timestampInfo:{deltaTimeInMs:+new Date-n},additionalDetails:{code:o?.callEndReason.code,subCode:o?.callEndReason.subCode,failureReason:o?.callEndReason.message,...o},networkInfo:F6.getRemoveCauseIdToNetworkInfo(a)}),new Y({defaultError:{message:t.message,code:t.code,subCode:t.subCode||0,resultCategories:t.resultCategories},originalError:e})}}validateThreadId(e,t){if(!t?.threadId)throw new Y({defaultError:J.CALL.CTE_ADDPARTICIPANT_NO_THREAD_ID})}};nLe([WG(o4.AddParticipant),z7(`design:type`,Function),z7(`design:paramtypes`,[Object,Object]),z7(`design:returntype`,Object)],B7.prototype,`addParticipant`,null),nLe([GG(o4.RemoveParticipant),z7(`design:type`,Function),z7(`design:paramtypes`,[Object,Object]),z7(`design:returntype`,Promise)],B7.prototype,`removeParticipant`,null);var rLe=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},V7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},H7=class{get kind(){return this._kind}get id(){return this._callCommon.id}get callerInfo(){return this._callCommon.callerInfo}get transferorInfo(){return this._callCommon.transferorInfo}get callEndReason(){return this._callCommon.callEndReason}get customContext(){return this._customContext}constructor(e,t){this._callCommon=e,this._eventEmitter=new w3.EventEmitter,this._kind=t,this._callConnected=this._callCommon.state===`Connected`,this._customContext=fTe(this._callCommon.tsCall),this._callCommon.on(`stateChanged`,(()=>{this._callCommon.state===`Connected`?this._callConnected=!0:this._callCommon.state!==`Disconnected`||this._callConnected||this._eventEmitter.emit(`callEnded`,{callEndReason:this._callCommon.callEndReason})})),this._callCommon.on(`callerInfoChanged`,(()=>{this._eventEmitter.emit(`callerInfoChanged`)})),this._callCommon.on(`transferorInfoChanged`,(()=>{this._eventEmitter.emit(`transferorInfoChanged`)}))}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}reject(){return this._callCommon.reject()}};rLe([GG(),V7(`design:type`,Function),V7(`design:paramtypes`,[]),V7(`design:returntype`,Promise)],H7.prototype,`reject`,null);var iLe=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},U7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},aLe=class extends H7{get info(){return this._call.info}constructor(e){super(e,HG.IncomingCall),this._call=e}async accept(e){if(this.info?.initiatorKind===`microsoftTeamsUser`&&!R4(this._call.acsProxy,this._call.acsCustomRelayManager,!0))throw new Y({defaultError:J.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN});return await this._call.accept(e),this._call}};iLe([GG(o4.Accept),U7(`design:type`,Function),U7(`design:paramtypes`,[Object]),U7(`design:returntype`,Promise)],aLe.prototype,`accept`,null);var W7={callNotification:`callNotification`,conversationInvitation:`conversationInvitation`,debugContent:`debugContent`,groupContext:`groupContext`},oLe=class{get callId(){return this._callId}get localParticipantId(){return this._localParticipantId}constructor(e,t,n){if(this._callId=``,this._localParticipantId=``,this._logger=n.createChild(`IncomingCallPushNotificationHandler`),!e.incomingCallContext)throw new Y({defaultError:J.CALL_AGENT.INCOMING_PUSH_NOTIFICATION_INVALID_PAYLOAD_NO_CONTEXT_PROVIDED});if(Object.keys(e).length>1)throw new Y({defaultError:J.CALL_AGENT.INCOMING_PUSH_NOTIFICATION_PAYLOAD_TOO_MANY_KEYS});if(this._payload=e,this._incomingCallContext=this._payload.incomingCallContext,this._tsCallRegistry=t,this._gp=JSON.parse($4.inflate(atob(this._incomingCallContext),{to:`string`})),!(this._gp.hasOwnProperty(W7.callNotification)&&this._gp.hasOwnProperty(W7.conversationInvitation)&&this._gp.hasOwnProperty(W7.debugContent)&&this._gp.hasOwnProperty(W7.groupContext)))throw this._logger.error(`Missing incoming call context data. Found: ${Object.keys(this._gp)}`),new Y({defaultError:J.CALL_AGENT.INCOMING_PUSH_NOTIFICATION_INVALID_PAYLOAD});this._callId=this._gp.debugContent.callId,this._localParticipantId=this._gp.debugContent.participantId}async process(){try{if(this._tsCallRegistry.calls.some((e=>e.callId==this._callId)))throw new Y({defaultError:J.CALL_AGENT.INCOMING_PUSH_NOTIFICATION_ALREADY_PROCESSED});let e=e3(),t=t=>{let n=()=>{t.callId===this._callId&&t.participantId===this._localParticipantId&&t.state===1&&e.resolve()};this._tsCallStateSub=t.on(`callStateChanged`,n),n()};this._tsCallRegistrySub=this._tsCallRegistry.on(`callAdded`,t);let n={eventId:ZCe,body:{gp:this._gp}};if(!this._tsCallRegistry.incomingCallMessageHandler.handleMessage(n))throw new Y({defaultError:J.CALL_AGENT.INCOMING_PUSH_NOTIFICATION_FAILED_TO_PROCESS});setTimeout((()=>{e.isPending()&&e.reject(new Y({defaultError:J.CALL_AGENT.INCOMING_PUSH_NOTIFICATION_CALL_MISSED}))}),5e3),await e.promise}catch(e){throw e}finally{this._tsCallRegistrySub?.dispose(),this._tsCallStateSub?.dispose()}}},G7=0,sLe=220004,cLe=220005,lLe=220006,uLe=220007,dLe=class{constructor(e){this._httpRequestHelper=e,this._isPolicyFetchApplicable=!1,this._policySettingData={},this._threadIdData={};let t=KW(`ACS`);this._logger=new z6(t)}initialize(e){this._localParticipant=e.localParticipant,this._jwtTokenProvider=e.jwtTokenProvider,this._telemetryLogManager=e.telemetryLogManager}userDialedNumber(e){this._userDialedPstnNumber=e,this._emergencyNumber=this._userDialedPstnNumber}async CreateChatThreadId(e,t){this._callId=e;let n=+new Date,r=t?.createThreadIdSuffix??Z().MiddleTier.serverManagedThreadIdApiConfiguration.createThreadSuffix;this.sendMiddleTierApiEvent({eventName:Q.acs_calling_middletier_gateway_api,suffix:r,kindOfEvent:$.attempt});let i=await this.getAcsMiddletierServiceRequestHeaderForThreadApi(),a=new URL(r,Z().MiddleTier.baseServiceUrl);t?.participants.push({id:this._localParticipant});let o={Participants:t?.participants};try{let e=await this._httpRequestHelper.send(a.toString(),o,{method:F3.POST,headers:i},Z().MiddleTier.maxRetry);if(this._threadIdData=await this._httpRequestHelper.extractPayload(e),!this._threadIdData)throw Error(`ThreadIdData is null or undefined`);return this._logger.info(`Successfully created chat thread using ACS MiddleTier Service.`),this.sendMiddleTierApiEvent({eventName:Q.acs_calling_middletier_gateway_api,suffix:r,kindOfEvent:$.success,timestampInfo:{deltaTimeInMs:new Date().getTime()-n},additionalDetails:{phrase:`Thread Id was successfully created from ACS MiddleTier Service`,code:G7,subCode:lLe}}),Promise.resolve(this._threadIdData.threadId)}catch{this._logger.error(`Error creating thread Id from ACS MiddleTier Service`);let e=new Y({defaultError:J.CTE_MID_TIER_POLICY_SERVICE.CREATETHREAD_FAILED});throw this.sendMiddleTierApiEvent({eventName:Q.acs_calling_middletier_gateway_api,suffix:r,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:new Date().getTime()-n},additionalDetails:{failureReason:e.message,code:e.code,subCode:e.subCode,...K3(e)}}),e}}async AddParticipantsToThread(e,t){this._callId=e;let n=+new Date,r=t?.addParticipantsSuffix??Z().MiddleTier.serverManagedThreadIdApiConfiguration.addParticipantSuffix;this.sendMiddleTierApiEvent({eventName:Q.acs_calling_middletier_gateway_api,suffix:r,kindOfEvent:$.attempt});let i=await this.getAcsMiddletierServiceRequestHeaderForThreadApi(),a=new URL(r,Z().MiddleTier.baseServiceUrl),o={threadId:t?.threadId,Participants:t?.participants};try{let e=await this._httpRequestHelper.send(a.toString(),o,{method:F3.POST,headers:i},Z().MiddleTier.maxRetry),t=await this._httpRequestHelper.extractPayload(e);if(!t)throw Error(`AddParticipantToThreadResponseData is null or undefined`);if(this._logger.info(`Call to add participants to chat thread using ACS MiddleTier Service`),t!==null){if(!t.isSuccess)throw new Y({defaultError:J.CTE_MID_TIER_POLICY_SERVICE.ADD_PARTICIPANTS_TO_THREAD_FAILED});t.multipleStatus.length>0&&t.multipleStatus[0].statusCode==735&&this._logger.info(`Trying to add the same participant to the thread id`)}return this.sendMiddleTierApiEvent({eventName:Q.acs_calling_middletier_gateway_api,suffix:r,kindOfEvent:$.success,timestampInfo:{deltaTimeInMs:new Date().getTime()-n},additionalDetails:{phrase:`Successfully add participants from ACS MiddleTier Service`,code:G7,subCode:uLe}}),Promise.resolve(t.isSuccess)}catch{this._logger.error(`Fail to add participant error from ACS MiddleTier Service`);let e=new Y({defaultError:J.CTE_MID_TIER_POLICY_SERVICE.ADD_PARTICIPANTS_TO_THREAD_FAILED});throw this.sendMiddleTierApiEvent({eventName:Q.acs_calling_middletier_gateway_api,suffix:r,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:new Date().getTime()-n},additionalDetails:{failureReason:e.message,code:e.code,subCode:e.subCode,...K3(e)}}),e}}async fetchUserPoliciesFromAcsMiddleTier(e,t,n){this._policySettingData=await this.requestUserPoliciesFromAcsMiddleTier(e,t,n)}async requestUserPoliciesFromAcsMiddleTier(e,t,n,r){this._callId=e;let i=+new Date;if(this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_fetch_policy,kindOfEvent:$.attempt},t),!t){let e=new Y({defaultError:J.CTE_MID_TIER_POLICY_SERVICE.TEAMS_USER_ID_NOT_PROVIDED});throw this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_fetch_policy,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:new Date().getTime()-i},additionalDetails:{failureReason:e.message,code:e.code,subCode:e.subCode,...K3(e)}}),e}let a,o={},s=Z().MiddleTier.baseServiceUrl;n?(a=new URL(n.policyUrlSuffix,s),o={id:t,dialstring:this._userDialedPstnNumber,userPolicies:n.userPolicies,userProperties:n.userProperties}):(a=new URL(Z().MiddleTier.policyUrlSuffix,s),o={id:t});let c=await this.getAcsMiddletierServiceRequestHeaderForThreadApi(r);try{let e=await this._httpRequestHelper.send(a.toString(),o,{method:F3.POST,headers:c},Z().MiddleTier.maxRetry);this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_fetch_policy,kindOfEvent:$.success,timestampInfo:{deltaTimeInMs:new Date().getTime()-i},additionalDetails:{phrase:`Teams user policy was fetched successfully from ACS MiddleTier Service`,code:G7,subCode:sLe}},t);let n=await this._httpRequestHelper.extractPayload(e);if(!n)throw Error(`PolicySettingsData is null or undefined`);return n}catch(e){let n=iDe(e,J.CTE_MID_TIER_POLICY_SERVICE.FETCH_POLICY);throw this._logger.error(n.message),this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_fetch_policy,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:new Date().getTime()-i},additionalDetails:{failureReason:n.message,code:n.code,subCode:n.subCode,...K3(n)}},t),n}}isEvEnabled(){return this._policySettingData?.userAggregatedPolicySettingData?.userProperties?.evEnabled||!1}isMoHEnabled(){let e=this._policySettingData?.userAggregatedPolicySettingData?.userPolicies?.teamsCallingPolicy?.musicOnHoldEnabledType;return this._logger.info(`Checking Music on Hold Policy, Enabled Type is: `+e),e===(y4.Enabled||y4.UserOverride)}isBreakoutRoomsAllowed(){let e=this._policySettingData?.userAggregatedPolicySettingData?.userPolicies?.teamsMeetingPolicy?.allowBreakoutRooms;return this._logger.info(`Allow Breakout rooms from Teams meeting policy is `+e),e??=!0,e}isIPAudioAllowed(){if(!Z().calling.mediaAccess.ipMediaPolicyEnabled)return this._logger.info(`Allow IP audio is true as feature flag ipAudioVideoPolicyEnabled is false`),!0;let e=this._policySettingData?.userAggregatedPolicySettingData?.userPolicies?.teamsMeetingPolicy?.ipAudioMode!==x4.Disabled;return this._logger.info(`Allow IP audio from Teams meeting policy is `+e),e}isIPVideoAllowed(){if(!Z().calling.mediaAccess.ipMediaPolicyEnabled)return this._logger.info(`Allow IP video is true as feature flag ipAudioVideoPolicyEnabled is false`),!0;let e=this._policySettingData?.userAggregatedPolicySettingData?.userPolicies?.teamsMeetingPolicy?.ipVideoMode!==x4.Disabled;return this._logger.info(`Allow IP video from Teams meeting policy is `+e),e}getTeamsUserCaptionsPoliciesData(){let e=+new Date,t=``;this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_fetch_user_policies_for_captions,kindOfEvent:$.attempt});let n=this._policySettingData.userAggregatedPolicySettingData,r=n?.userPolicies,i=n?.userProperties;if(!r?.teamsCallingPolicy){let t=new Y({defaultError:J.CTE_MID_TIER_POLICY_SERVICE.TEAMSUSER_CALLINGPOLICY_FETCHING_FAILED});this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_fetch_user_policies_for_captions,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:new Date().getTime()-e},additionalDetails:{failureReason:t.message,code:t.code,subCode:t.subCode,...K3(t)}})}if(!r?.teamsMeetingPolicy){let t=new Y({defaultError:J.CTE_MID_TIER_POLICY_SERVICE.TEAMSUSER_MEETINGPOLICY_FETCHING_FAILED});this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_fetch_user_policies_for_captions,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:new Date().getTime()-e},additionalDetails:{failureReason:t.message,code:t.code,subCode:t.subCode,...K3(t)}})}if(!i?.featureTypes){let t=new Y({defaultError:J.CTE_MID_TIER_POLICY_SERVICE.TEAMSUSER_FEATURETYPE_TEAMSPROMGMT_FETCHING_FAILED});this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_fetch_user_policies_for_captions,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:new Date().getTime()-e},additionalDetails:{failureReason:t.message,code:t.code,subCode:t.subCode,...K3(t)}})}return(r?.teamsCallingPolicy||r?.teamsMeetingPolicy||i?.featureTypes?.includes(V2.TeamsProMgmt))&&(t=JSON.stringify({isLiveCaptionsEnabledForCalling:r?.teamsCallingPolicy?.liveCaptionsEnabledTypeForCalling===H2.DisabledUserOverride,isLiveCaptionsEnabledForMeeting:r?.teamsMeetingPolicy?.liveCaptionsEnabledType===H2.DisabledUserOverride,isTeamsProMgmtSkuAvailable:i?.featureTypes?.includes(V2.TeamsProMgmt)??!1}),this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_fetch_user_policies_for_captions,kindOfEvent:$.success,timestampInfo:{deltaTimeInMs:new Date().getTime()-e},additionalDetails:{phrase:`Fetching Captions policy from ACS MiddleTier Service response was successful`,code:G7}}),this._logger.info(`Fetching user's captions policy content = ${t}`)),t}getEmergencyContent(){let e=+new Date;this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_emergency_content,kindOfEvent:$.attempt});let t=``;try{let n=this._policySettingData.userAggregatedPolicySettingData,r=n?.userPolicies,i=this.getEmergencyPolicyDetails(r,this._userDialedPstnNumber,n);i.foundEmergencyNumberMatch&&(t=JSON.stringify(i.emergencyContent));let a=i.foundEmergencyNumberMatch?`Created Emergency policy using ${i.logInfo}`:`This is NOT an emergency call`;return this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_emergency_content,kindOfEvent:$.success,timestampInfo:{deltaTimeInMs:new Date().getTime()-e},additionalDetails:{phrase:`Deriving Emergency policy from ACS MiddleTier Service response was successful`,code:G7,subCode:cLe}}),this._logger.info(`Deriving emergency policy message = ${a}. Emergency Content = ${t}`),t}catch(t){let n=new Y({defaultError:J.CTE_MID_TIER_POLICY_SERVICE.DERIVE_EMERGENCY_POLICY,originalError:t});throw this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_emergency_content,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:new Date().getTime()-e},additionalDetails:{failureReason:n.message,code:n.code,subCode:n.subCode,...K3(n)}}),n}}isEmergencyNumber(e,t){if(!t)return this._logger.info(`Not an emergency number, no participants`),!1;if(!this.isFetchUserPoliciesAndSettingsApplicable(e,t))return this._logger.info(`Fetch user policies and settings not applicable`),!1;let n=Array.isArray(t)&&t.length>0?t[0].phoneNumber:t.phoneNumber,r=this._policySettingData.userAggregatedPolicySettingData,i=r?.userPolicies,a=this.getEmergencyPolicyDetails(i,n,r);return this._logger.info(`Emergency number check result: ${a.foundEmergencyNumberMatch}`),a.foundEmergencyNumberMatch}getEmergencyPolicyDetails(e,t,n){let r=!1,i=``,a={};if(e?.locationPolicy?.emergencyNumbers){let o=e.locationPolicy.emergencyNumbers||[];this.isPhoneNumberInLocationPolicy(o,t)&&(r=!0,a={enableSecurityMemberNotifications:this.isSecurityDeskEnabled(),callerLocation:n?.userProperties.region,locationPolicyTag:e?.locationPolicy?.policyDocument,teamsEmergencyCallingPolicyTag:e?.teamsEmergencyCallingPolicy?.policyDocument},i=`LocationPolicy`)}if(!r&&e?.teamsEmergencyCallRoutingPolicy){let o=e?.teamsEmergencyCallRoutingPolicy?.emergencyNumbers||[];this.isPhoneNumberInTeamsEmergenencyRoutingPolicy(o,t)&&(r=!0,a={enableSecurityMemberNotifications:this.isSecurityDeskEnabled(),callerLocation:n?.userProperties.region,teamsEmergencyCallRoutingPolicyTag:e?.teamsEmergencyCallRoutingPolicy?.policyDocument,teamsEmergencyCallingPolicyTag:e?.teamsEmergencyCallingPolicy?.policyDocument},i=`TeamsEmergencyCallingRoutingPolicy`)}return{foundEmergencyNumberMatch:r,logInfo:i,emergencyContent:a}}isFetchUserPoliciesAndSettingsApplicable(e,t){return t4(e)||t4(t)||(this._isPolicyFetchApplicable=this.verifyFetchUserPoliciesSettings(e,t)),this._isPolicyFetchApplicable}getEmergencyNumber(){return this._emergencyNumber}getUserDialedPstnNumber(){return this._userDialedPstnNumber}getUserPolicy(){return this._policySettingData.userAggregatedPolicySettingData?.userPolicies}getUserProperties(){return this._policySettingData.userAggregatedPolicySettingData?.userProperties}isPhoneNumberInLocationPolicy(e,t){if(!t4(e)&&t){for(let n of e)if(n.dialString===t||!t4(n.dialMask?.split(`;`).find((e=>e===t))))return this._emergencyNumber=n.dialString,!0}return!1}isPhoneNumberInTeamsEmergenencyRoutingPolicy(e,t){if(!t4(e&&t)){for(let n of e)if(n.emergencyDialString===t||!t4(n.emergencyDialMask?.split(`;`).find((e=>e===t))))return this._emergencyNumber=n.emergencyDialString,!0}return!1}verifyFetchUserPoliciesSettings(e,t){let n=Z().MiddleTier;return n.enabled?n.userPolicySettingsApi?e?Array.isArray(t)&&(t.length>1||!xG(t[0]))?(this._logger.info(`Target particpant (Callee) is not a PSTN Number`),!1):Array.isArray(t)||xG(t)?(this._logger.info(`Teams user is eligible to fetch policies and settings from MiddleTier Service `),!0):(this._logger.info(`Target particpant (Callee) is not a PSTN Number`),!1):(this._logger.info(`Originator (Caller) is not a Teams User`),!1):(this._logger.info(`ACS MiddleTier Policy API is disabled`),n.userPolicySettingsApi):(this._logger.info(`ACS MiddleTier service is disabled`),n.enabled)}isSecurityDeskEnabled(){let e=this._policySettingData.userAggregatedPolicySettingData?.userPolicies?.teamsEmergencyCallingPolicy;return!(t4(e?.notificationGroup)&&t4(e?.notificationDialOutNumber)||e?.notificationGroup?.trim().length==0&&e?.notificationDialOutNumber?.trim().length==0)}async getAcsMiddletierServiceRequestHeader(){return{"Content-Type":`application/json`,"X-Skypetoken":this._jwtTokenProvider?await this._jwtTokenProvider():``,"Access-Control-Allow-Origin":`*`,"X-Microsoft-Skype-Chain-ID":this._callId}}async getAcsMiddletierServiceRequestHeaderForThreadApi(e){let t={};return t=await this.getAcsMiddletierServiceRequestHeader(),t.onbehalfOfUser=e??this._localParticipant,t}sendMiddleTierPolicyEvent(e,t){try{this.setDefaultEventData(e,t),this._telemetryLogManager?.sendEvent({name:e.eventName,tenant:d2,properties:e})}catch{this._logger.debug(`Unable to send AcsMiddleTierPolicyService telemetry`)}}sendMiddleTierApiEvent(e){try{this.setDefaultEventData(e),this._telemetryLogManager?.sendEvent({name:e.eventName,tenant:d2,properties:e})}catch{this._logger.debug(`Unable to send MiddleTier Api telemetry`)}}setDefaultEventData(e,t){e.callId=this._callId,e.localParticipantId=this._localParticipant,e.requestedParticipantMRI=t??this._localParticipant,e.timestampInfo=e.timestampInfo??``,e.additionalDetails=e.additionalDetails??``}},fLe=class{constructor(e){this._logger=e}get gpu(){let e={};try{let t=document.createElement(`canvas`),n=t.getContext(`webgl`)||t.getContext(`experimental-webgl`);if(n){let t=n.getExtension(`WEBGL_debug_renderer_info`);t?(e.vendor=n.getParameter(t.UNMASKED_VENDOR_WEBGL),e.renderer=n.getParameter(t.UNMASKED_RENDERER_WEBGL)):this._logger?.info(`Unable to get GPU info: debug renderer info is not supported`)}else this._logger?.info(`Unable to get GPU info: WebGL is not supported`)}catch(e){this._logger?.info(`Unable to get GPU info: ${e}`)}return e}get hardwareConcurrency(){return navigator.hardwareConcurrency}},K7;(function(e){e.deviceSelection=`deviceSelection`,e.createCallAgent=`createCallAgent`,e.createTeamsCallAgent=`createTeamsCallAgent`,e.disposeCallAgent=`disposeCallAgent`,e.disposeTeamsCallAgent=`disposeTeamsCallAgent`,e.disposeCallClient=`disposeCallClient`,e.handleIncomingCall=`handleIncomingCall`,e.startPreheatDevices=`startPreheatDevices`,e.stopPreheatDevices=`stopPreheatDevices`})(K7||={});var pLe,q7=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},J7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},mLe=1,Y7=class{get customContext(){return this._customContext}get kind(){return this._kind}get connectionState(){return this._connectionState}constructor(e,t,n,r,i,a,o){this._callClient=e,this._customContext={callId:``,customContext:{}},this._pushHandlingDeltaTimeInMs=new Map,this._disposed=!1,this.tokenProvider=async e=>{let t=+new Date,n;try{if(this.sendTokenChangedEvent({kindOfEvent:`attempt`,timestampInfo:{attemptTimestamp:t},oldTokenExpiration:this._oldTokenExpiration}),!this._communicationTokenCredential)throw new Y({defaultError:J.CALL_AGENT.GET_TOKEN_BEFORE_INIT});n=await M4(this._communicationTokenCredential,Z().calling.eudb.isRgnClaimEnabledForACS,{abortSignal:this._abortController.signal}),n.acsResourceId===this._parsedTokenCredential?.acsResourceId&&n.identityMri===this._parsedTokenCredential?.identityMri||k4(J.CALL_AGENT.REFRESHED_TOKEN_INVALID_USERID,this.logger),e?this._tokenFetchTries+=1:this._tokenFetchTries=0,this._tokenFetchTries>this._maxNmberOfRetries&&(this.updateConnectionState(`invalidToken`),this._disposed||await this.dispose(),k4(J.CALL_AGENT.REFRESHED_TOKEN_RETRIES,this.logger));let r=+new Date;return this.sendTokenChangedEvent({kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:r-t},oldTokenExpiration:this._oldTokenExpiration,newTokenExpiration:n.exp,isTokenChanged:this._oldToken!==n.jwtToken}),this._oldToken=n.jwtToken,this._oldTokenExpiration=n.exp,n.jwtToken}catch(e){let r={kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:+new Date-t},oldTokenExpiration:this._oldTokenExpiration};throw n&&(r.newTokenExpiration=n.exp,r.isTokenChanged=this._oldToken!==n.jwtToken,this._oldToken=n.jwtToken,this._oldTokenExpiration=n.exp),this.sendTokenChangedEvent(r,e),e}},this.sendTokenChangedEvent=(e,t)=>{try{let n={kindOfEvent:e.kindOfEvent,timestampInfo:e.timestampInfo,oldTokenExpiration:e.oldTokenExpiration};e.newTokenExpiration!==void 0&&(n.newTokenExpiration=e.newTokenExpiration),e.isTokenChanged!==void 0&&(n.isTokenChanged=e.isTokenChanged),t&&(n={...n,...K3(t)}),this._telemetryLogManager.sendEvent({name:Q.acs_calling_token_expiration_changed,tenant:d2,properties:n})}catch{this.logger.debug(`Unable to send token change telemetry`)}},this.pushHandlingStarted=e=>{let t=K0();this._pushHandlingDeltaTimeInMs.set(e,{correlationId:t,timestamp:+new Date}),this.logger.log(`Incoming call state started`,e),F6.setCauseIdToNetworkInfo(e),this.sendIncomingNotificationEvent({eventName:Q.acs_calling_client_operations,operation:K7.handleIncomingCall,networkInfo:[],kindOfEvent:`attempt`,timestampInfo:{deltaTimeInMs:void 0},correlationId:t,additionalDetails:{},callId:``,participantId:``})},this.pushNotificationParsed=(e,t)=>{if(this.logger.debug(`pushNotificationParsed event received ${e}`),t.customContext.sipHeaders||t.customContext.voipHeaders){let{sipHeaders:e,voipHeaders:n}=t.customContext,r={sipHeaders:H4(e),voipHeaders:H4(n)},i=e=>`sipHeaders: ${e?.sipHeaders?.length||0}, voipHeaders: ${e?.voipHeaders?.length||0}`;if(!Q2.isEqual(this._customContext.customContext,r)){this.sendCallAgentInfoEvent({eventName:Q.acs_calling_call_agent,additionalDetails:{step:`customContext-changed`,callId:t.callId,oldState:i(this._customContext.customContext),newState:i(r)}});let e={...this._customContext};this._customContext={callId:t.callId,customContext:r},this._eventEmitter.emit(`customContextChanged`,{oldValue:e,newValue:{...this._customContext}})}}},this.pushHandlingEnded=(e,t)=>{let n=t?.code!==void 0&&[0,200].includes(t?.code),r=e=>{if(n)return new Y({defaultError:{code:e?.code??0,subCode:e?.subCode??0,message:`Success`,resultCategories:[`Success`]}});let t=[J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_INVALID_NOTIFICATION_PAYLOAD,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_FAILED_TO_EXTRACT_PAYLOAD,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_ALREADY_HANDLED,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_IGNORING_DUPLICATE_NOTIFICATION,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_FAILED_TO_HANDLE_NOTIFICATION_FOR_GROUPID_CALL,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_BAD_NOTIFICATION_PAYLOAD,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_SETUP_SUCCEEDED,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_SETUP_FAILED,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_BAD_NOTIFICATION_EVENT_TYPE,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_ALREADY_EXISTS,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_FAILED_CANNOT_CONNECT,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_FAILED_NO_SIGNALING,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_FAILED_CONFLICT,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_FAILED_PUSH_IGNORED,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_FAILED_ANSWERED_ELSEWHERE,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_FAILED_CALL_ALREADY_ENDED,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_SETUP_IN_PROGRESS];return new Y({defaultError:Q2.find(t,(t=>t.subCode===e?.subCode))??J.CALL_AGENT.INVALID_PUSH_NOTIFICATION_DATA})};this.logger.log(`Incoming call state ended`,e,t);let i=F6.getRemoveCauseIdToNetworkInfo(e),a=this._pushHandlingDeltaTimeInMs.get(e)?.correlationId||`unknown`,o=r(t);this.sendIncomingNotificationEvent({eventName:Q.acs_calling_client_operations,operation:K7.handleIncomingCall,networkInfo:i||[],kindOfEvent:n?`success`:`failure`,timestampInfo:{deltaTimeInMs:this._pushHandlingDeltaTimeInMs.has(e)?+new Date-this._pushHandlingDeltaTimeInMs.get(e)?.timestamp:void 0},correlationId:a,additionalDetails:{...K3(o)},callId:t.callId||``,participantId:t.participantId||``}),this._pushHandlingDeltaTimeInMs.delete(e),this._eventEmitter.emit(`handleIncomingCall`,{callId:t.callId||``,participantId:t.participantId||``,...q3({code:o.code,subCode:o.subCode,message:o.message,resultCategories:o.resultCategories})})},this.logger=t.createChild(`CallAgent`+ mLe++),this._telemetryLogManager=r,this._kind=a,this._connectionState=`Disconnected`,this._eventEmitter=new S6(this.logger),this._internalEventEmitter=new w3.EventEmitter,this.clientId=n,this._abortController=new AbortController,this._maxDisplayNameLength=Z()?.calling?.maxDisplayNameLength||XCe,this._oldToken=``,this._oldTokenExpiration=0,this._tokenFetchTries=0,this._maxNmberOfRetries=Z()?.calling?.maxNumberOfTokenFetchRetries||zCe,this._callStack=i,this.callClient=this._callClient,this.deviceManager=o,this.acsProxy=this.callClient.acsProxy,this.acsCustomRelayManager=this.callClient.acsCustomRelayManager,this._httpRequestHelper=new UEe(this.logger,this.acsProxy),this.mtPolicyService=new dLe(this._httpRequestHelper),this._parsedTokenCredential=eTe(),this._caConfigBag={clientId:``,acsResourceId:this._parsedTokenCredential.acsResourceId,identityMri:this._parsedTokenCredential.identityMri,cloudType:this._parsedTokenCredential.cloudType,identityType:this._parsedTokenCredential.isEnterpriseUser?$0.Enterprise:$0.Consumer,region:this._parsedTokenCredential.region,emergencyCountryCode:void 0,IsUserEmergencyCountryCode:!1,mriType:this._parsedTokenCredential.mriType,parsedTokenCredential:this._parsedTokenCredential},this._extensibleApi=new N3(this.logger,{callClient:this.callClient,callAgent:this},{tsStack:this.tsStack,callAgent:this,telemetryLogManager:this._telemetryLogManager});let s=Q5(D3.CallAgentFeature);for(let e of s)e.activationOptions.activationEvent===`OnExtendedObjectConstructor`&&this.feature(e);this._trouterStateChangeCallback=e=>{this.logger.log(`Callback Trouter state changed to ${e}`),this.updateConnectionState(`trouterChanged`)},this._registrarStateChangeCallback=e=>{this.logger.log(`Callback Registrar state changed to ${e}`),this.updateConnectionState(`registrarChanged`)}}getHttpRequestHelper(){return this._httpRequestHelper}getTrouterState(){return this._callStack?this._callStack.getTrouterState():`Unknown`}onTrouterStateChanged(e){return this._callStack.onTrouterStateChanged(e)}offTrouterStateChanged(e){return this._callStack.offTrouterStateChanged(e)}onDisposed(e){this._internalEventEmitter.on(`disposed`,e)}getAcsResourceId(){return this._parsedTokenCredential?.acsResourceId||``}getUserMri(){return`8:${this._parsedTokenCredential?.identityMri}`||``}getUserPolicy(){return this._userPolicies}getUserProperties(){return this._userProperties}getInternalCallRegistry(){return this._tsCallRegistry}async initialize(e,t){let n=+new Date,r=new fLe(this.logger),i={gpu:r.gpu,hardwareConcurrency:r.hardwareConcurrency};try{if(this.sendCallAgentInitializiedEvent(Q.acs_calling_call_agent_init_attempt,{attemptTimestamp:n},i),this._communicationTokenCredential=e,this._parsedTokenCredential=await M4(e,Z().calling.eudb.isRgnClaimEnabledForACS,{abortSignal:this._abortController.signal}),this._kind!==BG.TeamsCallAgent||this._parsedTokenCredential.isEnterpriseUser?this._kind===BG.CallAgent&&this._parsedTokenCredential.isEnterpriseUser&&k4(J.CALL_AGENT.ACS_CALLAGENT_TOKEN_ONLY,this.logger):k4(J.CALL_AGENT.TEAMS_CALLAGENT_TOKEN_ONLY,this.logger),t?.displayName){if(this._parsedTokenCredential.isEnterpriseUser)throw new Y({defaultError:J.CALL_AGENT.ENTERPRISE_DISPLAY_NAME});if(t?.displayName.length>this._maxDisplayNameLength)throw new Y({defaultError:J.CALL_AGENT.DISPLAY_NAME_TOO_LONG})}if(this._parsedTokenCredential.cloudType===J0.Public&&(!this._parsedTokenCredential.region||this._parsedTokenCredential.region===``)){try{let e=+new Date-n;this._telemetryLogManager.sendEvent({name:Q.acs_calling_token_has_no_data_location,tenant:d2,properties:{deltaTimeInMs:e}})}catch{this.logger.debug(`Unable to send token has no data location assigned`)}this._parsedTokenCredential.region=this._parsedTokenCredential.rgnClaimExists?wSe[0]:t2[0],this.logger.info(`Used default data location because token has no data location assigned`)}this._caConfigBag={clientId:this.clientId,acsResourceId:this._parsedTokenCredential.acsResourceId,identityMri:this._parsedTokenCredential.identityMri,cloudType:this._parsedTokenCredential.cloudType,identityType:this._parsedTokenCredential.isEnterpriseUser?$0.Enterprise:$0.Consumer,emergencyCountryCode:t?.emergencyCallOptions?.countryCode,region:this._parsedTokenCredential.region,IsUserEmergencyCountryCode:!!t?.emergencyCallOptions?.countryCode,mriType:this._parsedTokenCredential.mriType,parsedTokenCredential:this._parsedTokenCredential},this.addToCallAgentsMap(this._parsedTokenCredential),this._disposed=!1;try{this.runningEnvironmentInfo=await this.callClient.getEnvironmentInfoInternal()}catch{this.logger.debug(`Unable to get the running environment info`)}if(this.tsStack=await this._callStack.initializeStackForUser(this.tokenProvider,this._caConfigBag),this._parsedTokenCredential.rgnClaimExists)try{await this.updateParsedTokenCredentials(e)}catch(e){this.logger.debug(`Failed to update parsed token credentials. Error message = ${e?.message||``}`)}await this.setUserPoliciesOnAgentInitialization(),this.isEnterpriseUser()&&(t={...t,displayName:this._userProperties?.displayName??void 0}),this._telemetryLogManager.initialize(this._caConfigBag),this._tsCallRegistry=await this.initializeCallRegistry(this.tsStack,t),this.registerConnectionStateEventHandlers();let r=+new Date;this.sendCallAgentInitializiedEvent(Q.acs_calling_call_agent_init_success,{deltaTimeInMs:r-n},i)}catch(e){this._caConfigBag&&!this._telemetryLogManager.isInitialized()&&this._telemetryLogManager.initialize(this._caConfigBag);let t=new Y({defaultError:J.CALL_AGENT.INIT_FAIL,originalError:e});this.removeFromCallAgentsMap(this._parsedTokenCredential);let r=+new Date;throw this.sendCallAgentInitializiedEvent(Q.acs_calling_call_agent_init_failure,{deltaTimeInMs:r-n},i,t),t}}handleActiveCallTransfer(e){this.logger.info(`CallAgent handling active call transfer for callId=${e.id}`),this._eventEmitter.emit(`callsUpdated`,{added:[e],removed:[]})}async setUserPoliciesOnAgentInitialization(){this.mtPolicyService.initialize({localParticipant:this.getUserMri(),jwtTokenProvider:this.tokenProvider,telemetryLogManager:this._telemetryLogManager})}isEnterpriseUser(){return this._parsedTokenCredential?.isEnterpriseUser!==void 0&&this._parsedTokenCredential?.isEnterpriseUser}isTeamsExtensionUser(){return this._parsedTokenCredential?.mriType!==void 0&&this._parsedTokenCredential?.mriType==e2.TeamsExtensionUser}getClientId(){return this.clientId}getCallByCallId(e,t){return t?this._tsCallRegistry.getCall(e,t):this._tsCallRegistry.calls.filter((t=>t.callId===e))?.[0]}async createTransferTargetCall(e){let t=AG(),n=K0(),r=K0(),i=await this._tsCallRegistry.createCallAsync({callId:n,localParticipantId:r,causeId:t,type:`ThreadId`,threadId:``}),a=this.createNewCall(n,i);return this.addToCallArray(a),this.handleCallState(a),i.addParticipant(e.targetMri).catch((()=>{this.logger.error(`Failed to add participant for transer call`)})),U6(i)?await Promise.all(a.bindTsCall()):a.bindTsCall(),this._eventEmitter.emit(`callsUpdated`,{added:[a],removed:[]}),a}async subscribeCallWithoutModality(e){let t=AG(),n=await this._tsCallRegistry.createCallAsync({callId:e.callId,localParticipantId:e.participantId,causeId:t,type:`ThreadId`,threadId:e.threadId,messageId:e.messageId}),r=this.createNewCall(e.callId,n),i={conversationUrl:e.meetingUrl,conversationId:e.callId};return this.addToCallArray(r),this.handleCallState(r),n.joinCallWithoutCallModality(i,{},t).then((()=>{this.logger.info(`Successfully joined call without modalities`)})).catch((e=>{throw this.logger.error(`Error while joining call without modalities`,e),new Y({defaultError:J.CALL_AGENT.INVALID_JOIN_LOCATOR,originalError:e})})),U6(n)?await Promise.all(r.bindTsCall()):r.bindTsCall(),r}getEcsConfigIds(){return this._callStack.getEcsConfigIds()}getDeviceType(){let e=this.callClient?.firstPartyOptions?.acsDeviceType;return e?iwe[e]:`default`}isWatermarkSupported(){return this.isEnterpriseUser()?Z().calling.watermark.watermarkEnabledForCteUsers:Z().calling.watermark.watermarkEnabledForAcsUsers}feature(e){return this._extensibleApi.getApiObjectInstance(e.callAgentApiCtor)}async handlePushNotification(e){let t=K0(),n=+new Date,r;try{if(this.sendHandlePushNotificationEvent({eventName:Q.acs_calling_handle_push_notification,correlationId:t,featureName:`handlePushNotification`,operationName:`handleIncomingCallPushNotification`,callId:``,localParticipantId:``,kindOfEvent:`attempt`,timestampInfo:``,additionalDetails:``}),!e.incomingCallContext)throw new Y({defaultError:J.CALL_AGENT.INVALID_PUSH_NOTIFICATION_DATA});r=new oLe(e,this._tsCallRegistry,this.logger),await r.process(),this.sendHandlePushNotificationEvent({eventName:Q.acs_calling_handle_push_notification,correlationId:t,featureName:`handlePushNotification`,operationName:`handleIncomingCallPushNotification`,callId:r.callId,localParticipantId:r.localParticipantId,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:+new Date-n},additionalDetails:``})}catch(e){let i=new Y({defaultError:J.CALL_AGENT.PUSH_NOTIFICATION_FAIL,originalError:e});throw this.sendHandlePushNotificationEvent({eventName:Q.acs_calling_handle_push_notification,correlationId:t,featureName:`handlePushNotification`,operationName:`handleIncomingCallPushNotification`,callId:r?.callId||``,localParticipantId:r?.localParticipantId||``,kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:+new Date-n},additionalDetails:{failureReason:i.message,code:i.code,...K3(i)}}),i}}sendCallAgentDisposeEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:d2,properties:e})}catch{this.logger.debug(`Unable to send CallClient dispose telemetry event`)}}trackCallEndTimeToStopTelemetry(e){e.length===0?f3.callEndTimestamp=Date.now():f3.callEndTimestamp=2**53-1}updateConnectionState(e){let t=this.getCallAgentConnectionState(),n=this.getTrouterState(),r=this._callStack?.isRegistered()?`Connected`:`Disconnected`,i=t===`Connected`?void 0:e==`invalidToken`?`invalidToken`:`connectionIssue`;if(this.sendCallAgentInfoEvent({eventName:Q.acs_calling_call_agent,additionalDetails:{step:`connectionState-changed`,oldState:this._connectionState,newState:t,trouterState:n,registrarState:r,reason:i,connectionStateSource:e}}),t!==this._connectionState||i!==this._connectionStateReason){let e={oldValue:this._connectionState,newValue:t,reason:i};this._connectionState=t,this._connectionStateReason=i,this._eventEmitter.emit(`connectionStateChanged`,e)}}sendCallAgentInfoEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:d2,properties:{...e.additionalDetails}})}catch(e){this.logger.debug(`Failed to send connection state changed event`,e)}}sendCallAgentInitializiedEvent(e,t,n,r){try{let i=typeof r?.message==`string`?r?.message:void 0;e!==Q.acs_calling_call_agent_init_failure&&(i=void 0);let a=r?K3(r):void 0,o=this.getEcsConfigIds(),s=e===Q.acs_calling_call_agent_init_attempt?void 0:this._callStack?.getVdi3StateInfo(),c=r7();this._telemetryLogManager.sendEvent({name:e,tenant:d2,properties:{...t,isSupportedEnvironment:this.runningEnvironmentInfo?.isSupportedEnvironment,failureReason:i,additionalProperties:{AcsCallingSDKWeb_ecsConfigIds:o.AcsCallingSDKWeb,SkypeWebMedia_ecsConfigIds:o.SkypeWebMedia},additionalInformation:{trouterState:this.getTrouterState(),hardwareInfo:n},additionalDetails:{...a,firstPartyOptions:{isDeviceTypeEnabled:Z().calling.setDeviceType,deviceTypeRawStrlen:this.callClient?.firstPartyOptions?.acsDeviceType?.length,deviceType:this.getDeviceType()},aadPftClaimExists:this._parsedTokenCredential.aadpftClaimExists,...s?{vdi3StateInfo:s}:{},...c.isMMREnabled?{mmrInfo:c}:{}}}})}catch{this.logger.debug(`Unable to send telemtery`)}}sendHandlePushNotificationEvent(e){try{this._telemetryLogManager?.sendEvent({name:e.eventName,tenant:d2,properties:e})}catch{this.logger.debug(`Unable to send handle push notification telemetry`)}}async initializeCallRegistry(e,t){let n=t?.displayName,r=await this.getCallRegistry(e,this._parsedTokenCredential,this.tokenProvider,n);return this.logger.info(`registry created for version number=${Y2()}`),r}async getCallRegistry(e,t,n,r){let i={id:t.identityMri,displayName:r||``,tokenProvider:n},a=await e.createCallRegistry(i);await a.login(i);let o=(this._callClient?.firstPartyOptions?.ring??Z()?.tsCalling?.accountConfiguration?.ring)||void 0,s=t.isEnterpriseUser?$0.Enterprise:$0.Consumer,c=t.acsResourceId,l=t.region,u={acsResourceId:c,clientType:s,ring:o};if(Z().calling.setDeviceType)u.deviceType=this.getDeviceType();else if(this.callClient.firstPartyOptions?.acsDeviceType)throw new Y({defaultError:J.CALL_AGENT.SET_DEVICE_TYPE_NOT_ALLOWED});let d=Z().calling.eudb;return d.isEnabled&&d.sendRegionToNgc&&(d.isRgnClaimEnabledForACS||t.isEnterpriseUser)&&(u={...u,region:l}),Z()?.calling.supportLiveStreaming&&(u.clientSupportsUms=!0),u.clientSupportsWatermark=this.isWatermarkSupported(),await a.setConfiguration(u),a.on(`callAdded`,this.handleCallAdded),a.on(`callRemoved`,this.handleCallRemoved),a.on(`pushHandlingStarted`,this.pushHandlingStarted),a.on(`pushHandlingEnded`,this.pushHandlingEnded),a.on(`pushNotificationParsed`,this.pushNotificationParsed),r&&await a.updateDisplayName(r),a}async updateParsedTokenCredentials(e){this._parsedTokenCredential=await M4(e,Z().calling.eudb.isRgnClaimEnabledForACS,{abortSignal:this._abortController.signal}),this._caConfigBag.region=this._parsedTokenCredential.region,this._caConfigBag.parsedTokenCredential=this._parsedTokenCredential}registerConnectionStateEventHandlers(){this._callStack.onRegisteredChanged(this._registrarStateChangeCallback),this.onTrouterStateChanged(this._trouterStateChangeCallback)}getCallAgentConnectionState(){return this._callStack?.isRegistered()&&this.getTrouterState()===`Connected`?`Connected`:`Disconnected`}sendIncomingNotificationEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:d2,properties:e})}catch{this.logger.debug(`Unable to send incoming call notification telemetry`)}}};q7([zG,J7(`design:type`,Object)],Y7.prototype,`logger`,void 0),q7([GG(a4.Initialize),J7(`design:type`,Function),J7(`design:paramtypes`,[Object,Object]),J7(`design:returntype`,Promise)],Y7.prototype,`initialize`,null),q7([WG(a4.Feature),J7(`design:type`,Function),J7(`design:paramtypes`,[Object]),J7(`design:returntype`,typeof(pLe=typeof TFeature<`u`&&TFeature)==`function`?pLe:Object)],Y7.prototype,`feature`,null),q7([GG(a4.HandlePushNotification),J7(`design:type`,Function),J7(`design:paramtypes`,[Object]),J7(`design:returntype`,Promise)],Y7.prototype,`handlePushNotification`,null);var hLe=class{constructor(e){this._call=e}setTarget(e){this._call=e}getTarget(){return this._call}startVideo(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}stopVideo(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}startScreenSharing(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}stopScreenSharing(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}setConstraints(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}};function X7(e){let t=new hLe(e);return new Proxy({},{get:(e,n)=>{let r,i,a=t.getTarget();if(n in t)r=t[n],i=t;else{if(a===void 0)throw new Y({defaultError:J.FEATURES.VDI3.CALL_INITIALIZING});if(!(n in a))return;r=a[n],i=a}return typeof r==`function`?function(...e){return r.apply(i,e)}:r},has:(e,n)=>{let r=t.getTarget();return n in t||r!==void 0&&n in r}})}var Z7,Q7=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},$7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},e9=class e extends Y7{get calls(){return this._calls}constructor(e,t,n,r,i,a,o){super(e,t,r,i,n,BG.CallAgent,a),this._calls=[],this.handleCallRemoved=e=>{this.logger.info(`removing callId=${e.callId}`);let t=this._calls.find((t=>t.id===e.callId));if(t){if(t.isBreakoutRoomCall){let e=Z().calling.breakoutRooms.hangUpCallDelayInMilliSeconds;setTimeout((()=>{this.disposeCall(t)}),e)}else this.disposeCall(t);this._eventEmitter.emit(`callsUpdated`,{added:[],removed:[t]}),this.logger.info(`call removed`)}},this.handleCallAdded=e=>{if(!this._calls.find((t=>t.id===e.callId))){let t=e.on(`callStateChanged`,(async()=>{if(e.state===1){let n=U6(e),r=e.callId;t.dispose();let i=new B7({callId:r,isIncoming:!0},this,e,this._telemetryLogManager);n&&(i=X7(i));let a=new aLe(i);this.handleCallState(i),n?await Promise.all(i.bindTsCall()):i.bindTsCall(),this._eventEmitter.emit(`incomingCall`,{incomingCall:a})}}))}},this.handleCallState=e=>{e.on(`stateChanged`,(async()=>{try{e.state===`Disconnected`?this.tsStack?(await this._tsCallRegistry.deleteCallAsync?.(e.tsCall)||this.logger.info(`The call has been removed from registry, call id: ${e.id}`),e.stats.flushEvents(),this._telemetryLogManager.flushAllEvents(e.id).catch((()=>{this.logger.error(`Failed to flush telemetry log manager events`)}))):this.logger.info(`Unable to remove call from registry`):e.state===`Connecting`&&e.direction==`Incoming`&&(this.addToCallArray(e),this._eventEmitter.emit(`callsUpdated`,{added:[e],removed:[]}))}catch{this.logger.error(`Failed to handle call state changed event`)}}))},this.displayName=o?.displayName}addToCallAgentsMap(t){e.callAgents.get(t?.identityMri)&&k4(J.CALL_AGENT.ACS_CALLAGENT_ALREADY_EXSISTS,this.logger),e.callAgents.set(t?.identityMri,this)}removeFromCallAgentsMap(t){t?.identityMri&&e.callAgents.get(t?.identityMri)===this&&e.callAgents.delete(t?.identityMri)}disposeCall(e){let t=this._calls.indexOf(e);t!==-1&&this._calls.splice(t,1),e.dispose(),this.trackCallEndTimeToStopTelemetry(this._calls)}async getExistingCallAgentWithToken(t){try{let n=await M4(t,Z().calling.eudb.isRgnClaimEnabledForACS);return e.callAgents.get(n.identityMri)}catch(e){throw new Y({defaultError:J.CALL_AGENT.PARSE_ACCESSTOKEN,originalError:e})}}createNewCall(e,t){let n=new B7({callId:e},this,t,this._telemetryLogManager);return U6(t)?X7(n):n}addToCallArray(e){this._calls.push(e),this.trackCallEndTimeToStopTelemetry(this._calls)}async disposeInternal(t){let n=+new Date,r=K0();this.sendCallAgentDisposeEvent({eventName:Q.acs_calling_client_operations,operation:K7.disposeCallAgent,kindOfEvent:`attempt`,timestampInfo:{},correlationId:r,additionalDetails:``});try{if(this._disposed)throw new Y({defaultError:J.CALL_AGENT.ACS_ALREADY_DISPOSED});this._disposed=!0,this._abortController.abort(),this._extensibleApi.dispose(),this._parsedTokenCredential?.identityMri&&e.callAgents.delete(this._parsedTokenCredential?.identityMri);for(let e of this._calls)e.state!==`Disconnected`&&await e.hangUp().catch((()=>{this.logger.error(`Failed to hangup call during call agent dispose`)}));await this._tsCallRegistry?.dispose();let t=this._tokenFetchTries>this._maxNmberOfRetries;await this._callStack.disposeUserStack(t),this.offTrouterStateChanged(this._trouterStateChangeCallback),this._callStack.offRegisteredChanged(this._registrarStateChangeCallback),this._eventEmitter.removeAllListeners(),this._internalEventEmitter.emit(`disposed`),this._internalEventEmitter.removeAllListeners(),this.sendCallAgentDisposeEvent({eventName:Q.acs_calling_client_operations,operation:K7.disposeCallAgent,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:``})}catch(e){let t=new Y({defaultError:J.CALL_AGENT.DISPOSE_FAIL,originalError:e});throw this.sendCallAgentDisposeEvent({eventName:Q.acs_calling_client_operations,operation:K7.disposeCallAgent,kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{failureReason:t.message,code:t.code,subCode:t.subCode,...K3(t)}}),t}finally{t&&this._telemetryLogManager.clearTelemetryLoggers()}}startCall(e,t){let n=K0(),r=+new Date,i={correlationId:n,timestampInfo:{attemptTimestamp:r}};this._telemetryLogManager.sendEvent({name:Q.acs_calling_call_attempt,tenant:d2,properties:i},void 0,`attempt`);try{if(this.assertCallUserIds(e),t?.alternateCallerId&&q2(t.alternateCallerId),e.find((e=>W2(e)===this.getUserMri())))throw new Y({defaultError:J.CALL_AGENT.CANT_CALL_YOURSELF});let i=t?.audioOptions?.muted;return i===void 0&&(i=!1),this.logger.info(`startCall with video=${!!t?.videoOptions},muted=${i}`),this.createCall({participants:e,startCallOptions:t},{correlationId:n,attemptTimestamp:r})}catch(e){let t,i;throw e instanceof Y&&(t=typeof e?.message==`string`?e?.message:void 0,i={...K3(e)}),this._telemetryLogManager.sendEvent({name:Q.acs_calling_call_failed,tenant:d2,properties:{correlationId:n,timestampInfo:{deltaTimeInMs:+new Date-r},failureReason:t||``,additionalDetails:i||{}}},void 0,`failure`),e}finally{this._telemetryLogManager.deleteEventMapByCorrelationId(n)}}join(e,t){if(!R4(this.acsProxy,this.acsCustomRelayManager,!1,void 0,e))throw new Y({defaultError:J.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN});this.assertCallContext(e);let n=t?.audioOptions?.muted;return n===void 0&&(n=!1),this.logger.info(`join with video=${!!t?.videoOptions},muted=${n}`),this.createCall({callContext:e,startCallOptions:t})}async dispose(){await this.disposeInternal(!0)}on(e,t){if(e!==`handleIncomingCall`&&e!==`incomingCall`&&e!==`callsUpdated`&&e!==`connectionStateChanged`&&e!==`customContextChanged`)throw new Y({defaultError:J.CALL_AGENT.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if(e!==`handleIncomingCall`&&e!==`incomingCall`&&e!==`callsUpdated`&&e!==`connectionStateChanged`&&e!==`customContextChanged`)throw new Y({defaultError:J.CALL_AGENT.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}createCall(e,t){if(e?.startCallOptions?.firstPartyOptions?.isImmersiveMode&&this.getDeviceType()!==`meshV2`)throw new Y({defaultError:J.CALL_AGENT.MESH_DEVICETYPE_V2});if(!this.tsStack)throw new Y({defaultError:J.CALL_AGENT.STACK_NOT_INIT});let n,r,i,a=e?.callContext?.threadId||e?.startCallOptions?.threadId,o=!1,s=e?.callContext?.groupId,c=e?.callContext?.roomId,l=e?.callContext?.meetingLink,u=e?.callContext?.meetingId,d=e?.callContext?.passcode||``;if(s&&s.startsWith(`19:`)&&(a=s,s=``),l)if(vFe(l))r=M5(l);else{if(!yFe(l,this.logger))throw new Y({defaultError:J.CALL_AGENT.INVALID_MEETING_LINK});if(bFe(l.trim().toLocaleLowerCase(),Z().calling.tfl.hosts)&&!Z().calling.tfl.isEnabled)throw new Y({defaultError:J.CALL_AGENT.UNSUPPORTED_TFL_MEETING_JOIN});o=!0}e?.callContext?.threadId&&e?.callContext?.organizerId&&e?.callContext?.tenantId&&(r={threadId:e?.callContext?.threadId,messageId:e?.callContext?.messageId?e?.callContext?.messageId.toString():`0`,organizerId:e?.callContext?.organizerId,tenantId:e?.callContext?.tenantId}),r&&(i={meetingType:r.messageId===`0`?1:2,tenantId:r.tenantId,organizerId:r.organizerId,replyChainMessageId:r.messageId},a=r.threadId,n=r.messageId);let f=AG(),p=K0(),m=K0(),h={threadId:a||``,messageId:n||``,meetingInfo:i,mediaPeerType:2},g=!1;if(U6(this._tsCallRegistry)){let r=X7();return(async()=>{let i;s?i=await this._tsCallRegistry.createCallAsync({type:`GroupId`,groupId:s,callId:p,localParticipantId:m,causeId:f}):u?i=await this._tsCallRegistry.createCallAsync({callId:p,localParticipantId:m,causeId:f,type:`MeetingData`,meetingData:{meetingCode:u,passcode:d,threadId:a}}):c?i=await this._tsCallRegistry.createCallAsync({callId:p,localParticipantId:m,causeId:f,type:`MeetingData`,meetingData:{meetingCode:c}}):o?i=await this._tsCallRegistry.createCallAsync({callId:p,localParticipantId:m,causeId:f,type:`MeetingData`,meetingData:{meetingUrl:l}}):(g=!!e?.participants&&e.participants.length>=2&&z4(e.participants,this.kind),Z().calling.enableSmePassFakeConversation&&!a&&g&&(a=`${LG}${K0()}`),i=await this._tsCallRegistry.createCallAsync({callId:p,localParticipantId:m,causeId:f,type:`ThreadId`,threadId:a||``,messageId:n}));let _=new B7({callId:p,roomId:c},this,i,this._telemetryLogManager,g);r.setTarget(_),this.addToCallArray(r),this.handleCallState(r),e?.participants&&e?.participants.forEach((e=>{i.addParticipant(W2(e)).catch((()=>{this.logger.error(`Failed to add participant during call start`)}))}));let v=e3();_.startCallInternal(e?.startCallOptions,!!u||!!c,e?.callContext,h,t,v).catch(A4),await Promise.all(_.bindTsCall()),await v.promise,this._eventEmitter.emit(`callsUpdated`,{added:[r],removed:[]})})().catch((e=>{})),r}{let r,i=!1;s?r=this._tsCallRegistry.createCallWithGroupId(s,p,m,f):u?r=this._tsCallRegistry.createCallWithMeetingData({meetingCode:u,passcode:d,threadId:a},p,m,f):c?r=this._tsCallRegistry.createCallWithMeetingData({meetingCode:c},p,m,f):o?r=this._tsCallRegistry.createCallWithMeetingData({meetingUrl:l},p,m,f):(i=!!e?.participants&&e.participants.length>=2&&z4(e.participants,this.kind),Z().calling.enableSmePassFakeConversation&&!a&&i&&(a=`${LG}${K0()}`),r=this._tsCallRegistry.createCall(a||``,p,m,n,f));let g=new B7({callId:p,roomId:c},this,r,this._telemetryLogManager,i);return this.addToCallArray(g),this.handleCallState(g),e?.participants&&e?.participants.forEach((e=>{r.addParticipant(W2(e)).catch((()=>{this.logger.error(`Failed to add participant during call start`)}))})),g.startCallInternal(e?.startCallOptions,!!u||!!c,e?.callContext,h,t).catch(A4),g.bindTsCall(),this._eventEmitter.emit(`callsUpdated`,{added:[g],removed:[]}),g}}assertCallContext(e){if(!e||this.checkForAtLeastOneValidCallConfig(e)||this.checkIfMultiplesConfigsWereSpecified(e)||this.checkForInvalidTeamsMeetingCoordinates(e))throw new Y({defaultError:J.CALL_AGENT.INVALID_JOIN_LOCATOR})}checkForAtLeastOneValidCallConfig(e){return!(e.threadId||e.meetingLink||e.groupId||e.meetingId||e.roomId)}checkIfMultiplesConfigsWereSpecified(e){return e.threadId&&e.groupId||e.groupId&&e.meetingLink}checkForInvalidTeamsMeetingCoordinates(e){return!e.threadId&&e.tenantId&&e.organizerId||e.threadId&&(e.organizerId&&!e.tenantId||!e.organizerId&&e.tenantId)}assertCallUserIds(e){Ywe(e,J.CALL_AGENT.USERIDS_MUST_BE_OBJECTS),Jwe(e,J.CALL_AGENT.USERIDS_CANNOT_BE_NULL),dwe(e),e.forEach((e=>{let t=q2(e);if(!R4(this.acsProxy,this.acsCustomRelayManager,!1,t))throw new Y({defaultError:J.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN})}))}};e9.callAgents=new Map,Q7([WG(a4.StartCall),$7(`design:type`,Function),$7(`design:paramtypes`,[Array,Object]),$7(`design:returntype`,Object)],e9.prototype,`startCall`,null),Q7([WG(a4.Join),$7(`design:type`,Function),$7(`design:paramtypes`,[Object,Object]),$7(`design:returntype`,Object)],e9.prototype,`join`,null),Q7([GG(a4.Dispose),$7(`design:type`,Function),$7(`design:paramtypes`,[]),$7(`design:returntype`,Promise)],e9.prototype,`dispose`,null),function(e){e.alpha=`alpha`,e.beta=`beta`,e.stable=`stable`,e.unknown=`unknown`}(Z7||={});var gLe=class{constructor(){this.browserInfo=t8();let e=J2();e.includes(`alpha`)||e.includes(`alpharc`)?this.sdkFlavor=Z7.alpha:e.includes(`beta`)||e.includes(`betarc`)?this.sdkFlavor=Z7.beta:e.includes(`stable`)||e.includes(`stablerc`)?this.sdkFlavor=Z7.stable:this.sdkFlavor=Z7.alpha}getInitialJamaSettings(){let e=$2.merge({},MSe),t=this.getFormFactorBaseSettings();e=$2.merge(e,t);let n=this.getSdkFlavorBaseSettings();e=$2.merge(e,n);let r=this.getSdkFlavorFormFactorSettings();e=$2.merge(e,r);let i=this.getBrowserEngineSpecificSettings();return e=$2.merge(e,i),e}getFormFactorBaseSettings(){switch(this.browserInfo.formFactor){case`Desktop`:return NSe;case`Mobile`:return ISe;default:return MSe}}getSdkFlavorBaseSettings(){switch(this.sdkFlavor){case Z7.stable:return BSe;case Z7.beta:return zSe;case Z7.alpha:default:return RSe}}getSdkFlavorFormFactorSettings(){let e=this.browserInfo.formFactor;if(this.sdkFlavor===Z7.stable)switch(e){case`Desktop`:return USe;case`Mobile`:return KSe;default:return BSe}else if(this.sdkFlavor===Z7.beta)switch(e){case`Desktop`:return HSe;case`Mobile`:return GSe;default:return zSe}else switch(e){case`Desktop`:return VSe;case`Mobile`:return WSe;default:return RSe}}getBrowserEngineSpecificSettings(){let e=this.browserInfo.engine,t=n8(),n=this.browserInfo.formFactor;return t===`ios`&&e===`Safari`?LSe:n===`Desktop`&&e===`Chromium`?PSe:e===`Firefox`?FSe:{}}},t9=class{constructor(e,t,n){this.setConfigOrDefault=(e,t)=>{e&&Object.keys(e).forEach((n=>{e[n]!==void 0&&(t[n]=e[n])}))},this._logger=e,this.sdkDiagnosticInformation=t,this._acsProxy=n,this._jamaSettingsProvider=new gLe;let r=Z().calling.applicationSettingsUrls,i=Z().calling.pnhTemplateVersion;this._trouterSettings={version:`${l2()}/${J2()}`,productName:`AcsWeb`,trouterServiceUrl:r.Public_TrouterServiceUrl,registrarServiceUrl:r.Public_RegistrarServiceUrl,maxRegistrationTimeInMs:36e5,pnhAppId:`AcsWeb`,pnhTemplate:i,environment:`Prod`,platform:e8()},this._JsCsaConfig={languageCode:`en`,emergencyCallCountry:``,autoResolveConflictedCall:!1,handleRosterFromCreateAndJoin:!0,conversationServiceUrl:n.proxyfyUrl(r.Public_ConversationServiceUrl),useInternalHttpDispatcher:!0,supportsHostlessGroupCalls:!0,doHostlessCalling:!0,shouldServiceSendCallEventMessages:!0,shouldServiceSendNGCUpgradeMessages:!0,supportsCompressedServicePayload:!0,handleNewOfferRequest:!0,handleMediaOfferFromPushNotification:!0,isWebRtcEnabled:!0,supportsSynchronousTrouterResponse:!0,autoJoinOnConflict:!0,brokerEnabledOutgoing:!0,brokerEnabledIncoming:!0,brokerExclusively:!1,brokerRequestBatching:!0,isGVCOutgoingEnabled:!0,isGVCJoiningEnabled:!0,enableTokenCache:!1,nullifyAuthTokenManagerOnReset:!1},this._JamaSettings=this._jamaSettingsProvider.getInitialJamaSettings(),this._MDNTrapSettings={Service:{url:n.proxyfyUrl(r.Public_MdnTrapServiceUrl),tokenUrl:n.proxyfyUrl(r.Public_MdnTrapServiceTokenUrl)},Relay:{Skype:{addresses:[],fqdns:[r.Public_MdnTrapRelaySkypeFqdns],tcpPort:443,udpPort:3478},Turn:{addresses:[],fqdns:[r.Public_MdnTrapRelayTurnFqdns],tcpPort:443,udpPort:3478,url:r.Public_MdnTrapRelayTurnUrl}},Http:{connectionTimeout:30,requestTimeout:60},Token:{earlyRefreshMinutes:1080,earlyRefreshPercentage:25}},this._TrouterJScriptClient={TelemetryEnabled:!1,ClientTelemetryEventEnabled:{trouter_js_client_connected:!1,trouter_js_client_disconnected:!1,trouter_js_client_error:!1,trouter_js_client_progress:!1,trouter_js_client_response:!1,trouter_js_client_check_connection:!1,trouter_js_client_registration:!1,trouter_js_client_unregistration:!1,logHealthCheckError:!1,logSendPingError:!1,numberOfStepsToMaintain:0,sendProgressTimeoutSecs:0}}}getTrouterTelemetryConfig(){return{enabled:this._TrouterJScriptClient.TelemetryEnabled,...this._TrouterJScriptClient.ClientTelemetryEventEnabled}}getJamaSettings(){return this._JamaSettings}getClientInformation(){let e=Z().telemetry.reportSdkUaToService,t=Z().telemetry.reportEnvToService;return`ACSWeb(${l2()}/${J2()})`+(t?`/${cke()}`:``)+(e?`/(${this.sdkDiagnosticInformation})`:``)}getJsCsaConfig(){return this._JsCsaConfig.useInternalHttpDispatcher=!(this._acsProxy.hasProxyUrl()||Z().telemetry.sendNetworkInfo),{...this._JsCsaConfig,clientInformation:this.getClientInformation()}}getMdnTrapSettings(){return this._MDNTrapSettings}getTrouterSettings(){return this._trouterSettings}setConfig(e,t){this._logger.info(`Update ECS settings`);let n=Z().calling.applicationSettingsUrls,r=Z().calling.applicationSettingsEudbUrls,i=e&&j4(e.identityType,e.region);if(e?.identityType==$0.Enterprise)i?(this._trouterSettings.trouterServiceUrl=r.Enterprise_TrouterServiceUrl_EUDB,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(r.Enterprise_RegistrarServiceUrl_EUDB)):(this._trouterSettings.trouterServiceUrl=n.Enterprise_TrouterServiceUrl,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(n.Enterprise_RegistrarServiceUrl));else switch(e?.cloudType){case J0.Public:i&&(this._trouterSettings.trouterServiceUrl=r.Public_TrouterServiceUrl_EUDB,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(r.Public_RegistrarServiceUrl_EUDB),this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(r.Public_ConversationServiceUrl_EUDB),this._MDNTrapSettings.Service.url=this._acsProxy.proxyfyUrl(r.Public_MdnTrapServiceUrl_EUDB),this._MDNTrapSettings.Service.tokenUrl=this._acsProxy.proxyfyUrl(r.Public_MdnTrapServiceTokenUrl_EUDB),this._MDNTrapSettings.Relay.Skype.fqdns=[r.Public_MdnTrapRelaySkypeFqdns_EUDB],this._MDNTrapSettings.Relay.Turn.fqdns=[r.Public_MdnTrapRelayTurnFqdns_EUDB],this._MDNTrapSettings.Relay.Turn.url=r.Public_MdnTrapRelayTurnUrl_EUDB);break;case J0.GccHigh:this._trouterSettings.trouterServiceUrl=n.GccHigh_TrouterServiceUrl,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(n.GccHigh_RegistrarServiceUrl);break;case J0.Dod:this._trouterSettings.trouterServiceUrl=n.Dod_TrouterServiceUrl,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(n.Dod_RegistrarServiceUrl);break;case J0.AirGap08:this._trouterSettings.trouterServiceUrl=n.AirGap08_TrouterServiceUrl,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(n.AirGap08_RegistrarServiceUrl);break;case J0.AirGap09:this._trouterSettings.trouterServiceUrl=n.AirGap09_TrouterServiceUrl,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(n.AirGap09_RegistrarServiceUrl)}if(t)this.setConfigOrDefault(t?.SkypeCalling,this._JsCsaConfig),this.setConfigOrDefault(t?.MDN_TRAP,this._MDNTrapSettings),this.setConfigOrDefault(t?.SkypeWebMedia?.mediaAgent,this._JamaSettings),this.setConfigOrDefault(t?.TrouterJScriptClient,this._TrouterJScriptClient);else if(e?.identityType===$0.Enterprise)i?(this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(r.Enterprise_ConversationServiceUrl_EUDB),this._MDNTrapSettings.Service.url=this._acsProxy.proxyfyUrl(r.Enterprise_MdnTrapServiceUrl_EUDB),this._MDNTrapSettings.Service.tokenUrl=this._acsProxy.proxyfyUrl(r.Enterprise_MdnTrapServiceTokenUrl_EUDB),this._MDNTrapSettings.Relay.Skype.fqdns=[r.Enterprise_MdnTrapRelaySkypeFqdns_EUDB],this._MDNTrapSettings.Relay.Turn.fqdns=[r.Enterprise_MdnTrapRelayTurnFqdns_EUDB],this._MDNTrapSettings.Relay.Turn.url=r.Enterprise_MdnTrapRelayTurnUrl_EUDB):(this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(n.Enterprise_ConversationServiceUrl),this._MDNTrapSettings.Service.url=this._acsProxy.proxyfyUrl(n.Enterprise_MdnTrapServiceUrl),this._MDNTrapSettings.Service.tokenUrl=this._acsProxy.proxyfyUrl(n.Enterprise_MdnTrapServiceTokenUrl),this._MDNTrapSettings.Relay.Skype.fqdns=[n.Enterprise_MdnTrapRelaySkypeFqdns],this._MDNTrapSettings.Relay.Turn.fqdns=[n.Enterprise_MdnTrapRelayTurnFqdns],this._MDNTrapSettings.Relay.Turn.url=n.Enterprise_MdnTrapRelayTurnUrl);else switch(e?.cloudType){case J0.Public:i&&(this._trouterSettings.trouterServiceUrl=r.Public_TrouterServiceUrl_EUDB,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(r.Public_RegistrarServiceUrl_EUDB),this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(r.Public_ConversationServiceUrl_EUDB),this._MDNTrapSettings.Service.url=this._acsProxy.proxyfyUrl(r.Public_MdnTrapServiceUrl_EUDB),this._MDNTrapSettings.Service.tokenUrl=this._acsProxy.proxyfyUrl(r.Public_MdnTrapServiceTokenUrl_EUDB),this._MDNTrapSettings.Relay.Skype.fqdns=[r.Public_MdnTrapRelaySkypeFqdns_EUDB],this._MDNTrapSettings.Relay.Turn.fqdns=[r.Public_MdnTrapRelayTurnFqdns_EUDB],this._MDNTrapSettings.Relay.Turn.url=r.Public_MdnTrapRelayTurnUrl_EUDB);break;case J0.GccHigh:this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(n.GccHigh_ConversationServiceUrl),this._MDNTrapSettings.Service.url=this._acsProxy.proxyfyUrl(n.GccHigh_MdnTrapServiceUrl),this._MDNTrapSettings.Service.tokenUrl=this._acsProxy.proxyfyUrl(n.GccHigh_MdnTrapServiceTokenUrl),this._MDNTrapSettings.Relay.Skype.fqdns=[n.GccHigh_MdnTrapRelaySkypeFqdns],this._MDNTrapSettings.Relay.Turn.fqdns=[n.GccHigh_MdnTrapRelayTurnFqdns],this._MDNTrapSettings.Relay.Turn.url=n.GccHigh_MdnTrapRelayTurnUrl;break;case J0.Dod:this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(n.Dod_ConversationServiceUrl),this._MDNTrapSettings.Service.url=this._acsProxy.proxyfyUrl(n.Dod_MdnTrapServiceUrl),this._MDNTrapSettings.Service.tokenUrl=this._acsProxy.proxyfyUrl(n.Dod_MdnTrapServiceTokenUrl),this._MDNTrapSettings.Relay.Skype.fqdns=[n.Dod_MdnTrapRelaySkypeFqdns],this._MDNTrapSettings.Relay.Turn.fqdns=[n.Dod_MdnTrapRelayTurnFqdns],this._MDNTrapSettings.Relay.Turn.url=n.Dod_MdnTrapRelayTurnUrl;break;case J0.AirGap08:this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(n.AirGap08_ConversationServiceUrl);break;case J0.AirGap09:this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(n.AirGap09_ConversationServiceUrl)}}static assertConfigs(e){let t=[];if(e?.SkypeCalling||t.push(`SkypeCalling`),e?.MDN_TRAP||t.push(`MDN_TRAP`),e?.SkypeWebMedia?e?.SkypeWebMedia?.mediaAgent||t.push(`SkypeWebMedia.mediaAgent`):t.push(`SkypeWebMedia`),e?.TrouterJScriptClient||t.push(`TrouterJScriptClient`),t.length>0)throw new Y({defaultError:J.CALL_STACK.FOUND_UNDEFINED_CONFIGS,defaultErrorMessageArgs:[t.join(`, `)]})}},_Le,n9={exports:{}},r9={exports:{}};r9.exports;function vLe(){return _Le||(_Le=1,e=r9,r9.exports,t=()=>{return e={659:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toJson=t.fetchWithTimeout=void 0,t.fetchWithTimeout=function(e,t){var n,r=new Promise((function(t,r){fetch(e).then((function(e){n!==void 0&&clearTimeout(n),t(e)})).catch((function(e){n!==void 0&&clearTimeout(n),r(e)}))}));if(t!==0){var i=new Promise((function(r,i){n=setTimeout(i,t,Error(`Fetch for '${e.url}' timed out`))}));return Promise.race([r,i])}return r},t.toJson=function(e){try{return JSON.stringify(e)}catch{return`Unable to serialize object of type ${typeof e}`}}},912:function(e,t,n){var r,i=this&&this.__extends||(r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},r(e,t)},function(e,t){if(typeof t!=`function`&&t!==null)throw TypeError(`Class extends value `+String(t)+` is not a constructor or null`);function n(){this.constructor=e}r(e,t),e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}),a=this&&this.__assign||function(){return a=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},a.apply(this,arguments)},o=this&&this.__awaiter||function(e,t,n,r){return new(n||=Promise)((function(i,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((r=r.apply(e,t||[])).next())}))},s=this&&this.__generator||function(e,t){var n,r,i,a,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol==`function`&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(c){return function(s){if(n)throw TypeError(`Generator is already executing.`);for(;a&&(a=0,s[0]&&(o=0)),o;)try{if(n=1,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,r=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((i=(i=o.trys).length>0&&i[i.length-1])||s[0]!==6&&s[0]!==2)){o=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){o.label=s[1];break}if(s[0]===6&&o.label<i[1]){o.label=i[1],i=s;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(s);break}i[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],r=0}finally{n=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}};Object.defineProperty(t,"__esModule",{value:!0}),t.createRegistrarClient=t.RegistrarClient=void 0;var c=n(659),l=[`skype`,`aad`,`cae`],u=function(e){function t(t){var n=e.call(this,t)||this;return n.name=`CancelationError`,n}return i(t,e),t}(Error),d=function(){function e(t,n,r){this.logger=t,this.maxBackoffInMs=n,this.initialDelay=r,this.backoffCount=0,this.id=++e.idCounter}return e.prototype.delay=function(e){var t=this;if(this.timerHandle!==void 0)throw Error(`Retry sequence logical failure`);if(this.backoffCount===-1)return new Promise((function(e,t){t(new u(`Cancelled`))}));var n=this.calculateNextBackoffMs();return this.backoffCount++,this.logger.info(`[RegistrarClient] Backing off ${e} for ${n} milliseconds with ID ${this.id}`),new Promise((function(r,i){t.cancelFunc=i,t.timerHandle=setTimeout((function(){t.logger.info(`[RegistrarClient] Back off for ${e} with ID ${t.id} complete`),t.timerHandle=void 0,r()}),n)}))},e.prototype.cancel=function(){this.timerHandle!==void 0&&(this.logger.debug(`Resetting back off`),clearTimeout(this.timerHandle),this.cancelFunc!==void 0&&this.cancelFunc(new u(`Cancelled`))),this.backoffCount=-1},e.prototype.calculateNextBackoffMs=function(){var e=1+.4*(Math.random()-.5),t=this.initialDelay*2**this.backoffCount*e;return t=Math.round(t),Math.min(this.maxBackoffInMs,t)},e.idCounter=0,e}(),f=function(){function e(e,t,n){this.logger=e,this.tokenProvider=t,this.options=n,this.DEFAULT_MAX_RETRIES_FOR_GET_TOKEN=15,this.DEFAULT_MAX_BACKOFF_TIME_IN_MS=3e5,this.backoffs={},this.maxBackOffTime=this.options.maxRetryDelayMs>0?this.options.maxRetryDelayMs:this.DEFAULT_MAX_BACKOFF_TIME_IN_MS,this.maxRetriesForGetToken=n.maxRetriesForGetToken===void 0||n.maxRetriesForGetToken===null?this.DEFAULT_MAX_RETRIES_FOR_GET_TOKEN:n.maxRetriesForGetToken,this.proxyUrlRewrite=n.proxyUrlRewrite??function(e){return e}}return e.prototype.register=function(e,t){return o(this,void 0,void 0,(function(){return s(this,(function(n){switch(n.label){case 0:return[4,this.performRegistration(e,t)];case 1:return n.sent(),this.cachedRegistrationParams=[e,t],[2]}}))}))},e.prototype.unregister=function(){return o(this,void 0,void 0,(function(){var e;return s(this,(function(t){switch(t.label){case 0:return this.logger.info(`[RegistrarClient] sending unregister request`),e=new Request(this.proxyUrlRewrite(`${this.options.registrarUrl}/${this.options.registrationId}`),{method:`DELETE`,mode:`cors`,headers:new Headers(a(a({},this.options.extraRegistrationHeaders),{accept:`application/json, text/javascript`}))}),[4,this.callRegistrar(e)];case 1:return t.sent(),[2]}}))}))},e.prototype.cancelPendingRequests=function(){var e=this;Object.keys(this.backoffs).forEach((function(t){e.backoffs[t].cancel()})),this.backoffs={}},e.prototype.resendRegistration=function(){return o(this,void 0,void 0,(function(){return s(this,(function(e){switch(e.label){case 0:if(!this.cachedRegistrationParams)throw Error(`Re-registration failed because there is no registration parameters cached`);return[4,this.performRegistration(this.cachedRegistrationParams[0],this.cachedRegistrationParams[1])];case 1:return e.sent(),[2]}}))}))},e.prototype.performRegistration=function(e,t){return o(this,void 0,void 0,(function(){var n,r;return s(this,(function(i){switch(i.label){case 0:return this.logger.info(`[RegistrarClient] Sending register request`),n={clientDescription:e,registrationId:this.options.registrationId,nodeId:``,transports:t},r=new Request(this.proxyUrlRewrite(this.options.registrarUrl),{method:`POST`,mode:`cors`,headers:new Headers(a(a({},this.options.extraRegistrationHeaders),{"content-type":`application/json`,accept:`application/json, text/javascript`})),body:(0,c.toJson)(n)}),[4,this.callRegistrar(r)];case 1:return i.sent(),[2]}}))}))},e.prototype.startBackoff=function(){var e=new d(this.logger,this.maxBackOffTime,this.options.initialRetryDelayMs);return this.backoffs[e.id]=e,e},e.prototype.stopBackoff=function(e){e.cancel(),delete this.backoffs[e.id]},e.prototype.getToken=function(e){return o(this,void 0,void 0,(function(){var t,n,r,i,a,o,c;return s(this,(function(s){switch(s.label){case 0:t=this.startBackoff(),n=0,s.label=1;case 1:return s.trys.push([1,3,,8]),this.logger.info(`[RegistrarClient] Asking for a new token`),[4,this.tokenProvider({needFresh:!0,supportedTokenTypes:l,wwwAuthenticateHeader:e,purpose:`registrar`})];case 2:return r=s.sent(),this.stopBackoff(t),[2,r];case 3:i=s.sent(),s.label=4;case 4:return s.trys.push([4,6,,7]),n++,a=JSON.stringify(i),n>this.maxRetriesForGetToken?(o=`[RegistrarClient] getToken retry limit hit. Will not retry now. Error: ${a}`,this.logger.error(o),this.stopBackoff(t),[2,Promise.reject(o)]):(this.logger.warn(`[RegistrarClient] Retrying for a new token. Retry Count: ${n} Error: ${a}`),[4,t.delay(`Fetching a new token`)]);case 5:return s.sent(),[3,8];case 6:throw c=s.sent(),this.stopBackoff(t),c;case 7:return[3,8];case 8:return[3,1];case 9:return[2]}}))}))},e.prototype.callRegistrar=function(e){return o(this,void 0,void 0,(function(){var t,n,r,i,a,o,u,d,f,p,m,h,g,_,v;return s(this,(function(s){switch(s.label){case 0:return t=this.startBackoff(),[4,this.tokenProvider({needFresh:!1,supportedTokenTypes:l,wwwAuthenticateHeader:void 0,purpose:`registrar`})];case 1:n=s.sent(),this.setTokenHeader(e,n),r=0,s.label=2;case 2:i=void 0,s.label=3;case 3:return s.trys.push([3,10,,15]),a=e.clone(),[4,(0,c.fetchWithTimeout)(a,this.options.requestTimeoutMs)];case 4:return(i=s.sent()).status===401?++r>this.maxRetriesForGetToken?(o=`[RegistrarClient] getSkypeToken retry limit hit. Will not retry now. Request '${e.url}' failed with ${i.status} ${i.statusText}`,this.logger.error(o),this.stopBackoff(t),[2,Promise.reject(o)]):(this.logger.warn(`[RegistrarClient] Retry Count ${r}. Request '${e.url}' failed with ${i.status} ${i.statusText}`),u=i.headers?.get(`www-authenticate`)??void 0,d=this.setTokenHeader,f=[e],[4,this.getToken(u)]):[3,8];case 5:return d.apply(this,f.concat([s.sent()])),r>1?[4,t.delay(`Registrar call retry after 401`)]:[3,7];case 6:s.sent(),s.label=7;case 7:return[3,21];case 8:if(i.status>=500&&i.status<600)throw Error(`Fetch for '${e.url}' failed with ${i.status} ${i.statusText}`);s.label=9;case 9:return[3,15];case 10:p=s.sent(),this.logger.error(`[RegistrarClient] Request failed with ${p}`),s.label=11;case 11:return s.trys.push([11,13,,14]),[4,t.delay(`Registrar call retry`)];case 12:return s.sent(),[3,21];case 13:throw m=s.sent(),this.logger.error(`[RegistrarClient] Request cancelled`),this.stopBackoff(t),m;case 14:return[3,15];case 15:return this.stopBackoff(t),i.ok?[2,i]:[3,16];case 16:h=void 0,s.label=17;case 17:return s.trys.push([17,19,,20]),_=(g=JSON).stringify,[4,i.json()];case 18:return h=_.apply(g,[s.sent()]),[3,20];case 19:return s.sent(),h=`no details`,[3,20];case 20:throw v=`Fetch for '${e.url}' failed with ${i.status} ${i.statusText} (${h}, MS-CV: ${i.headers?.get(`MS-CV`)})`,this.logger.error(`[RegistrarClient] ${v}`),Error(v);case 21:return[3,2];case 22:return[2]}}))}))},e.prototype.setTokenHeader=function(e,t){switch(e.headers.delete(`X-Skypetoken`),e.headers.delete(`Authorization`),e.headers.delete(`X-MS-Migration`),t.tokenType.toLowerCase()){case`skype`:e.headers.set(`X-Skypetoken`,t.token);break;case`aad`:case`cae`:e.headers.set(`Authorization`,`Bearer ${t.token}`);break;default:throw Error(`unsupported token type: ${t.tokenType}`)}!1===this.options.usingLegacyTokenApi&&e.headers.set(`X-MS-Migration`,`True`)},e}();t.RegistrarClient=f,t.createRegistrarClient=function(e,t,n){return new f(e,t,n)}}},t={},function n(r){var i=t[r];if(i!==void 0)return i.exports;var a=t[r]={exports:{}};return e[r].call(a.exports,a,a.exports,n),a.exports}(912);var e,t},e.exports=t()),r9.exports;var e,t}var yLe;n9.exports;function bLe(){return yLe||(yLe=1,e=n9,n9.exports,t=e=>(()=>{var t={10:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterManagerFsm=void 0;var r=n(234),i=n(423),a=n(642),o=n(573);t.TrouterManagerFsm=function(){function e(e,t){this.worker=t,this.state=i.TrouterManagerState.Unknown,this.logger=new a.Logger(`ManagerFsm`,e)}return e.prototype.start=function(){this.state===i.TrouterManagerState.Unknown?(this.setState(i.TrouterManagerState.Disconnected),this.worker.forceStopLingeringConnection(),this.worker.startFirstConnection()):(this.logger.info(`start called in state '${i.TrouterManagerState[this.state]}', expediting pending backoffs, if any`),this.worker.expediteBackoffOnConnections())},e.prototype.stop=function(e){this.state===i.TrouterManagerState.Unknown?this.showIgnored(`stop`):(this.setState(i.TrouterManagerState.Unknown),this.worker.stopFirstConnection(!0===e),this.worker.stopSecondConnection(!0===e))},e.prototype.getState=function(){switch(this.state){case i.TrouterManagerState.Unknown:case i.TrouterManagerState.Connected:case i.TrouterManagerState.Disconnected:case i.TrouterManagerState.Switching:return this.state;case i.TrouterManagerState.TerminalError:return r.TrouterState.Disconnected}},e.prototype.getInternalState=function(){return this.state},e.prototype.onConnected=function(e){this.state===i.TrouterManagerState.Disconnected&&e?this.worker.doesSecondConnectionExist()?this.setState(i.TrouterManagerState.Switching):(this.setState(i.TrouterManagerState.Connected),this.worker.dispatchConnected()):this.showIgnored(`onConnected(${e})`)},e.prototype.onRegistered=function(e){this.state!==i.TrouterManagerState.Disconnected||e?this.state!==i.TrouterManagerState.Switching||e?this.state===i.TrouterManagerState.Disconnected&&e&&(this.setState(i.TrouterManagerState.Connected),this.worker.dispatchConnected()):(this.setState(i.TrouterManagerState.Connected),this.worker.switchConnections(),this.worker.stopSecondConnectionDelayed(),this.worker.dispatchConnected()):(this.setState(i.TrouterManagerState.Connected),this.worker.switchConnections(),this.worker.stopSecondConnection(!0),this.worker.dispatchConnected()),this.worker.dispatchRegistrationState(!0)},e.prototype.onUnregistered=function(e){e&&this.worker.dispatchRegistrationState(!1)},e.prototype.onReconnecting=function(e){this.state!==i.TrouterManagerState.Connected&&this.state!==i.TrouterManagerState.Switching||!e?this.showIgnored(`onReconnecting(${e})`):(this.setState(i.TrouterManagerState.Disconnected),this.worker.dispatchDisconnected())},e.prototype.onReconnectionRequired=function(e,t,n){this.state===i.TrouterManagerState.Connected&&e?(this.setState(i.TrouterManagerState.Switching),this.worker.startSecondConnection(t)):this.state===i.TrouterManagerState.Disconnected&&e?this.worker.startSecondConnection(t):this.state===i.TrouterManagerState.Switching&&e&&n===o.ReconnectReason.Configuration?(this.logger.debug(`onReconnectionRequired: switch requested while already in Switching state`),this.worker.stopSecondConnection(!0),this.worker.startSecondConnection(t)):this.showIgnored(`onReconnectionRequired(${e})`)},e.prototype.onDisconnected=function(e){this.state==i.TrouterManagerState.Unknown&&e?this.worker.dispatchDisconnected():this.state==i.TrouterManagerState.Switching&&e?(this.worker.switchConnections(),this.worker.stopSecondConnection(!1),this.setState(i.TrouterManagerState.Disconnected),this.worker.dispatchDisconnected()):this.showIgnored(`onDisconnected(${e})`)},e.prototype.onTerminalError=function(){this.setState(i.TrouterManagerState.TerminalError),this.worker.dispatchTerminalError()},e.prototype.showIgnored=function(e){this.logger.info(`Ignoring event '${e}' in state '${i.TrouterManagerState[this.state]}'`)},e.prototype.setState=function(e){this.logger.info(`Switching from state '${i.TrouterManagerState[this.state]}' to state '${i.TrouterManagerState[e]}'`),this.state===e?this.logger.error(`Attempt to switch to the current state '${i.TrouterManagerState[e]}'`):this.state=e},e}()},107:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExponentialBackoff=void 0,t.ExponentialBackoff=function(){function e(e,t,n){n===void 0&&(n={tolerance:2,minimumWaitMs:1e4}),this.logger=e,this.maxBackoffInMs=t,this.gapDetectionSettings=n,this.backoffId=0,this.backoffCount=0}return e.calculateNextBackoffMs=function(e,t){var n=1+.4*(Math.random()-.5),r=1e3*2**e*n;return r=Math.round(r),Math.min(t,r)},e.prototype.setMaxBackoffMs=function(e){this.maxBackoffInMs=e},e.prototype.backoff=function(t,n){var r=this;if(this.timerHandle!==void 0&&(this.logger.debug(`Clearing current back off`),clearTimeout(this.timerHandle),this.timerHandle=void 0),this.previousCompleteTime!==void 0){var i=Date.now()-this.previousCompleteTime;i>this.maxBackoffInMs*this.gapDetectionSettings.tolerance&&i>this.gapDetectionSettings.minimumWaitMs&&(this.logger.info(`Back off for ${t} with ID ${this.backoffId} will be reset due to a lot of time having passed since the previous backoff (${i} ms)`),this.backoffCount=0,this.previousCompleteTime=void 0)}var a=e.calculateNextBackoffMs(this.backoffCount,this.maxBackoffInMs);this.backoffId++,this.backoffCount++,this.logger.info(`Backing off ${t} for ${a} milliseconds with ID ${this.backoffId}`),this.callback=function(e,i){(function(e,t,n){if(e===void 0||t===void 0)return!1;var r=Date.now()-e;return r>t*n.tolerance&&r>n.minimumWaitMs})(e,i,r.gapDetectionSettings)&&(r.logger.info(`Back off for ${t} with ID ${r.backoffId} will be reset due to the wait (${Date.now()-(e??0)} ms) being longer than expected (${i} ms)`),r.backoffCount=0),r.logger.info(`Back off for ${t} with ID ${r.backoffId} complete, invoking handler`),r.timerHandle=void 0,r.callback=void 0,r.previousCompleteTime=Date.now(),n()};var o=Date.now();this.timerHandle=setTimeout((function(){return r.callback?.call(r,o,a)}),a)},e.prototype.reset=function(){this.timerHandle!==void 0&&(this.logger.debug(`Resetting back off with ID ${this.backoffId}`),clearTimeout(this.timerHandle),this.timerHandle=void 0,this.callback=void 0),this.backoffCount=0},e.prototype.expediteIfPending=function(){if(this.backoffCount=0,this.timerHandle!==void 0){this.logger.debug(`Expediting back off with ID ${this.backoffId}`),clearTimeout(this.timerHandle),this.timerHandle=void 0;var e=this.callback;this.callback=void 0,e&&e()}},e}()},220:function(e,t){var n=this&&this.__awaiter||function(e,t,n,r){return new(n||=Promise)((function(i,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((r=r.apply(e,t||[])).next())}))},r=this&&this.__generator||function(e,t){var n,r,i,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},o=Object.create((typeof Iterator==`function`?Iterator:Object).prototype);return o.next=s(0),o.throw=s(1),o.return=s(2),typeof Symbol==`function`&&(o[Symbol.iterator]=function(){return this}),o;function s(s){return function(c){return function(s){if(n)throw TypeError(`Generator is already executing.`);for(;o&&(o=0,s[0]&&(a=0)),a;)try{if(n=1,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,r=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((i=(i=a.trys).length>0&&i[i.length-1])||s[0]!==6&&s[0]!==2)){a=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){a.label=s[1];break}if(s[0]===6&&a.label<i[1]){a.label=i[1],i=s;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(s);break}i[2]&&a.ops.pop(),a.trys.pop();continue}s=t.call(e,a)}catch(e){s=[6,e],r=0}finally{n=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}};Object.defineProperty(t,"__esModule",{value:!0}),t.addCacheAsBackupTo=function(e){var t,i=this;return function(a){return n(i,void 0,void 0,(function(){return r(this,(function(n){return a&&(t=void 0),[2,new Promise((function(n,r){e(a).then((function(e){t=e,n(e)})).catch((function(e){t!==void 0&&t.length>0&&n(t),r(e)}))}))]}))}))}}},234:(e,t)=>{var n,r;Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterState=t.UserActivityState=void 0,function(e){e[e.Unknown=0]=`Unknown`,e[e.Active=1]=`Active`,e[e.Inactive=2]=`Inactive`}(n||(t.UserActivityState=n={})),function(e){e[e.Unknown=0]=`Unknown`,e[e.Connected=2]=`Connected`,e[e.Disconnected=3]=`Disconnected`,e[e.Switching=9]=`Switching`}(r||(t.TrouterState=r={}))},235:function(e,t,n){var r=this&&this.__spreadArray||function(e,t,n){if(n||arguments.length===2)for(var r,i=0,a=t.length;i<a;i++)!r&&i in t||(r||=Array.prototype.slice.call(t,0,i),r[i]=t[i]);return e.concat(r||Array.prototype.slice.call(t))};Object.defineProperty(t,"__esModule",{value:!0}),t.LoggingManagerConsumer=t.RegistrationEnforcer=void 0;var i=n(335);t.RegistrationEnforcer=function(){function e(e,t,n){this.wrapped=e,this.shouldConnectionDependOnRegistration=t,this.shouldHoldBackEvents=n,this.isRegistered=!1,this.heldBackEvents=[]}return e.prototype.onDownstreamRequest=function(e,t,n){this.passIfRegisteredOrNotNeeded(`onDownstreamRequest`,e,t,n)},e.prototype.onConnected=function(e){this.passIfRegisteredOrNotNeeded(`onConnected`,e)},e.prototype.onRegistered=function(e){this.isRegistered=!0,this.wrapped.onRegistered(e),this.fireHeldBackEvents()},e.prototype.onUnregistered=function(e){var t=this.isRegistered;this.isRegistered=!1,this.wrapped.onUnregistered(e),t&&e.getState()===i.State.Connected&&this.shouldConnectionDependOnRegistration()&&e.forceReconnectDueToNoRegistration()},e.prototype.onReconnecting=function(e){this.wrapped.onReconnecting(e)},e.prototype.onReconnectIsRequired=function(e,t,n){this.wrapped.onReconnectIsRequired(e,t,n)},e.prototype.onDisconnected=function(e){this.isRegistered=!1,this.dropHeldBackEvents(),this.wrapped.onDisconnected(e)},e.prototype.onTerminalError=function(e){this.wrapped.onTerminalError(e)},e.prototype.onConnectionParametersUpdated=function(e){this.wrapped.onConnectionParametersUpdated(e)},e.prototype.onTrouterMessageLost=function(e){this.passIfRegisteredOrNotNeeded(`onTrouterMessageLost`,e)},e.prototype.onUserActivityStateAccepted=function(e){this.passIfRegisteredOrNotNeeded(`onUserActivityStateAccepted`,e)},e.prototype.onAudiencesSetResolved=function(e,t){this.passIfRegisteredOrNotNeeded(`onAudiencesSetResolved`,e,t)},e.prototype.getState=function(){return this.wrapped.getState()},e.prototype.holdBackEvent=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];this.heldBackEvents.push({kind:e,args:t})},e.prototype.passIfRegisteredOrNotNeeded=function(e){for(var t,n=[],i=1;i<arguments.length;i++)n[i-1]=arguments[i];var a=this.shouldConnectionDependOnRegistration(),o=this.shouldHoldBackEvents();a&&o||this.fireHeldBackEvents(a?function(e){return e.kind!==`onConnected`}:void 0),this.isRegistered||!a||!1===o&&e!==`onConnected`?(t=this.wrapped)[e].apply(t,n):this.holdBackEvent.apply(this,r([e],n,!1))},e.prototype.fireHeldBackEvents=function(e){for(var t,n=0,r=this.heldBackEvents;n<r.length;n++){var i=r[n];(e===void 0||e(i))&&(t=this.wrapped)[i.kind].apply(t,i.args)}this.heldBackEvents=e===void 0?[]:this.heldBackEvents.filter((function(t){return!e(t)}))},e.prototype.dropHeldBackEvents=function(){this.heldBackEvents=[]},e}(),t.LoggingManagerConsumer=function(){function e(e,t,n,r){this.wrapped=e,this.prefix=t,this.logger=n,this.onEventAction=r}return e.prototype.onEvent=function(e,t){this.onEventAction===void 0?(this.logger??console).log(`${this.prefix} TracingEnforcer: ${e}(${t})`):this.onEventAction(e,t)},e.prototype.onDownstreamRequest=function(e,t,n){this.onEvent(`onDownstreamRequest`,JSON.stringify({request:t,response:n})),this.wrapped.onDownstreamRequest(e,t,n)},e.prototype.onConnected=function(e){this.onEvent(`onConnected`,e.getState().toString()),this.wrapped.onConnected(e)},e.prototype.onRegistered=function(e){this.onEvent(`onRegistered`,e.getState().toString()),this.wrapped.onRegistered(e)},e.prototype.onUnregistered=function(e){this.onEvent(`onUnregistered`,e.getState().toString()),this.wrapped.onUnregistered(e)},e.prototype.onReconnecting=function(e){this.onEvent(`onReconnecting`,e.getState().toString()),this.wrapped.onReconnecting(e)},e.prototype.onReconnectIsRequired=function(e,t,n){this.onEvent(`onReconnectIsRequired`,JSON.stringify({connection:e.getState().toString(),useConnectParamsFromCache:t,reason:n})),this.wrapped.onReconnectIsRequired(e,t,n)},e.prototype.onDisconnected=function(e){this.onEvent(`onDisconnected`,e.getState().toString()),this.wrapped.onDisconnected(e)},e.prototype.onTerminalError=function(e){this.onEvent(`onTerminalError`,JSON.stringify({connection:e})),this.wrapped.onTerminalError(e)},e.prototype.onConnectionParametersUpdated=function(e){this.onEvent(`onConnectionParametersUpdated`,JSON.stringify({connectParams:e})),this.wrapped.onConnectionParametersUpdated(e)},e.prototype.onTrouterMessageLost=function(e){this.onEvent(`onTrouterMessageLost`,JSON.stringify({flowTags:e})),this.wrapped.onTrouterMessageLost(e)},e.prototype.onUserActivityStateAccepted=function(e){this.onEvent(`onUserActivityStateAccepted`,JSON.stringify({cv:e})),this.wrapped.onUserActivityStateAccepted(e)},e.prototype.onAudiencesSetResolved=function(e,t){this.onEvent(`onAudiencesSetResolved`,JSON.stringify({audienceSubscriptionsResponse:e,cv:t})),this.wrapped.onAudiencesSetResolved(e,t)},e.prototype.getState=function(){return this.wrapped.getState()},e}()},335:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterFsm=t.State=void 0;var r,i,a=n(423),o=n(642),s=n(902);(function(e){e[e.Initial=0]=`Initial`,e[e.RetrievingToken=1]=`RetrievingToken`,e[e.Allocating=2]=`Allocating`,e[e.Handshaking=3]=`Handshaking`,e[e.Connecting=4]=`Connecting`,e[e.AnonymousConnecting=5]=`AnonymousConnecting`,e[e.WebsocketAuthenticating=6]=`WebsocketAuthenticating`,e[e.Connected=7]=`Connected`,e[e.Unregistering=8]=`Unregistering`,e[e.TerminalError=9]=`TerminalError`})(r||(t.State=r={})),function(e){e[e.Initial=0]=`Initial`,e[e.Registering=1]=`Registering`,e[e.RegisteringButResendPending=2]=`RegisteringButResendPending`,e[e.Retrying=3]=`Retrying`,e[e.Registered=4]=`Registered`,e[e.RegistrationDisabled=5]=`RegistrationDisabled`}(i||={}),t.TrouterFsm=function(){function e(e,t,n,a){this.worker=t,this.incallModeEnabled=n,this.protocolSelector=a,this.state=r.Initial,this.autoReconnect=!0,this.logger=new o.Logger(`ConnectionFsm`,e),this.registrationState=i.Initial}return e.prototype.getState=function(){return this.state},e.prototype.isActive=function(){return this.state===r.Allocating||this.state===r.Connected||this.state===r.Handshaking||this.state===r.Connecting||this.state===r.RetrievingToken||this.state===r.AnonymousConnecting||this.state===r.WebsocketAuthenticating},e.prototype.isConnecting=function(){return this.state===r.Allocating||this.state===r.Handshaking||this.state===r.Connecting||this.state===r.AnonymousConnecting},e.prototype.start=function(){return this.state===r.Initial?(this.setState(r.RetrievingToken),this.worker.getToken(!0,!1,void 0),!0):(this.showIgnored(`start`),!1)},e.prototype.stop=function(e,t){e&&(this.registrationState=i.Initial),this.worker.isIncallMode()&&this.worker.exitIncallMode(),this.worker.resetTokenBackoff(),this.worker.cancelPendingRegistrationRequests(),this.worker.stopConnectionTimer(),this.worker.stopPingTimer(),this.worker.clearSentEventTimers(),this.worker.stopRegistrationTimer(),this.worker.stopSocketIo(),this.state===r.Connected&&this.worker.sendDisconnectTelemetryEvent(`connection stopped`),this.registrationState!==i.Registered&&this.registrationState!==i.Registering&&this.registrationState!==i.RegisteringButResendPending||this.state===r.Unregistering?t?(this.setState(r.TerminalError),this.worker.dispatchTerminalError()):(this.setState(r.Initial),this.worker.dispatchDisconnected()):(this.registrationState=i.Initial,this.setState(r.Unregistering),this.worker.sendUnregisterRequest())},e.prototype.onTokenReceived=function(e,t,n){this.state===r.RetrievingToken?(0,s.usedProtocolAfterFallback)(this.protocolSelector(e.tokenType,n),t)===`v4c`?(this.setState(r.AnonymousConnecting),this.worker.startConnectionTimer(),this.worker.connectV4c(e,t)):(this.setState(r.Allocating),this.worker.startConnectionTimer(),this.worker.sendAllocateRequest(e)):this.showIgnored(`onTokenReceived`)},e.prototype.checkConnection=function(e){e&&this.onPingInterval()},e.prototype.onAllocationSucceed=function(e){return this.state===r.Allocating&&this.registrationState===i.Registered&&this.worker.dispatchUnregistered(),this.state===r.Allocating?(this.setState(r.Handshaking),this.registrationState=i.Initial,this.worker.startSocketIo(e),!0):(this.showIgnored(`onAllocationSucceed`),!1)},e.prototype.onAllocationFailed=function(e,t){this.state===r.Allocating?this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!e,claimsChallenge:t}):this.showIgnored(`onAllocationFailed`)},e.prototype.onV4cConnectivityCheckFailed=function(){this.state===r.AnonymousConnecting?this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!0}):this.showIgnored(`onV4cConnectivityCheckFailed`)},e.prototype.onV4cException=function(){this.state!==r.AnonymousConnecting&&this.state!==r.WebsocketAuthenticating||(this.logger.error(`v4c exception, falling back to longpoll`),this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!0,fallbackReason:{kind:`v4c-websocket-failure`}}))},e.prototype.onConnectingTimeout=function(){this.state===r.Allocating||this.state===r.Connecting||this.state===r.Handshaking||this.state===r.AnonymousConnecting||this.state===r.WebsocketAuthenticating?this.cleanUpAndInitiateReconnect({backoff:!1,allowCachedToken:!0}):this.showIgnored(`onConnectingTimeout`)},e.prototype.onConnecting=function(){this.state===r.Handshaking?this.setState(r.Connecting):this.showIgnored(`onConnecting`)},e.prototype.onSocketConnect=function(e){this.state===r.AnonymousConnecting?(this.setState(r.WebsocketAuthenticating),this.worker.sendV4cAuthenticationEvent(e)):this.showIgnored(`onSocketConnect`)},e.prototype.onConnectingFailed=function(){this.state===r.Connecting?this.onConnectingTimeout():this.state===r.Handshaking?(this.logger.error(`Unexpected error in Socket.io - no valid transports`),this.onConnectingTimeout()):this.state===r.AnonymousConnecting||this.state===r.WebsocketAuthenticating?(this.logger.info(`/v4/c falling back to longpoll`),this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!0,fallbackReason:{kind:`v4c-websocket-failure`}})):this.showIgnored(`onConnectingFailed`)},e.prototype.onSocketDisconnect=function(e){this.state===r.Handshaking||this.state===r.Connected||this.state===r.WebsocketAuthenticating?(this.state===r.Connected&&this.worker.sendDisconnectTelemetryEvent(e?.toTelemetryString()),this.state===r.WebsocketAuthenticating&&this.worker.countDisconnectBeforeConnectionEstablishment(),e?.reason===`skypetoken-deprecated`?(this.logger.error(`Skypetoken deprecated response, not retrying any further`),this.onTerminalError()):this.cleanUpAndInitiateReconnect({backoff:this.state!==r.Connected&&e?.reason!==`dup`,allowCachedToken:e?.reason!==`unauthorized`,claimsChallenge:e?.claims})):this.showIgnored(`onSocketDisconnect`)},e.prototype.onTrouterConnected=function(){this.state===r.Connecting||this.state===r.WebsocketAuthenticating?(this.setState(r.Connected),this.worker.resetTokenBackoff(),this.worker.stopConnectionTimer(),this.worker.sendUserActivityState(a.UserActivityEventReason.Connected,!0),this.worker.startPingTimer(),this.worker.dispatchConnected(),this.worker.shouldSkipRegistration()?(this.registrationState=i.RegistrationDisabled,this.worker.dispatchRegistered()):(this.registrationState=i.Registering,this.worker.sendRegisterRequest())):this.showIgnored(`onTrouterConnected`)},e.prototype.onReconnectRequired=function(e,t,n){this.state===r.AnonymousConnecting||this.state===r.WebsocketAuthenticating?n===void 0||n.target!==`host`||n.url===void 0||n.url===``?(this.logger.error(`unexpected reconnect arguments: ${n?.target} ${n?.url}, reconnecting without cache`),this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!0,fallbackReason:{kind:`redirect-no-host`}})):this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!0,fallbackReason:{kind:`redirect`,host:n.url}}):this.worker.dispatchReconnectIsRequired(e,t)},e.prototype.disableAutoReconnect=function(){this.autoReconnect=!1},e.prototype.onDownstreamRequest=function(e){this.state===r.Connected?(this.switchToIncallModeIfEnabled(),this.worker.dispatchDownstreamRequest(e)):this.showIgnored(`onDownstreamRequest`)},e.prototype.onTrouterMessageLost=function(e){this.state===r.Connected?this.worker.dispatchTrouterMessageLost(e):this.showIgnored(`onTrouterMessageLost`)},e.prototype.onPingInterval=function(){this.state===r.Connected?this.worker.sendPingRequest():this.showIgnored(`onPingInterval`)},e.prototype.onPingResponseTimeout=function(){this.onMissedResponse(`onPingResponseTimeout`)},e.prototype.onPingResponse=function(){this.state===r.Connected||this.showIgnored(`onPingResponse`)},e.prototype.onRegistrationFailed=function(){this.state===r.Connected&&this.registrationState===i.Registering?(this.worker.dispatchUnregistered(),this.registrationState=i.Retrying,this.worker.startRegistrationRetryTimer()):this.state===r.Connected&&this.registrationState===i.RegisteringButResendPending?(this.registrationState=i.Registering,this.worker.sendRegisterRequest()):this.showIgnored(`onRegistrationFailed`)},e.prototype.onRetryRegistration=function(){this.state===r.Connected&&this.registrationState===i.Retrying?(this.registrationState=i.Registering,this.worker.sendRegisterRequest()):this.showIgnored(`onRetryRegistration`)},e.prototype.onRegistrationSucceeded=function(){this.state===r.Connected&&this.registrationState===i.Registering?(this.registrationState=i.Registered,this.worker.dispatchRegistered(),this.worker.startRegistrationTimer()):this.state===r.Connected&&this.registrationState===i.RegisteringButResendPending?(this.registrationState=i.Registering,this.worker.sendRegisterRequest()):this.showIgnored(`onRegistrationSucceeded`)},e.prototype.onRegistrationNearExpiry=function(){this.state===r.Connected&&this.registrationState===i.Registered?(this.registrationState=i.Registering,this.worker.sendRegisterRequest()):this.showIgnored(`onRegistrationNearExpiry`)},e.prototype.onUnregistrationDone=function(){this.state===r.Unregistering?(this.setState(r.Initial),this.worker.dispatchUnregistered(),this.worker.dispatchDisconnected()):this.showIgnored(`onUnregistrationDone`)},e.prototype.onResendRegistration=function(){this.worker.dispatchUnregistered(),this.state===r.Connected&&this.registrationState===i.Registered?(this.registrationState=i.Registering,this.worker.stopRegistrationTimer(),this.worker.sendRegisterRequest()):this.state===r.Connected&&this.registrationState===i.Registering&&(this.registrationState=i.RegisteringButResendPending)},e.prototype.onExtraTransportsUpdated=function(){this.state===r.Connected?this.registrationState===i.Registered?(this.registrationState=i.Registering,this.worker.stopRegistrationTimer(),this.worker.sendRegisterRequest()):this.registrationState===i.Registering&&(this.registrationState=i.RegisteringButResendPending):this.state===r.Unregistering||this.state===r.Initial?this.logger.warn(`onExtraTransportsUpdated called while Trouter is stopped, will not be applied until it is next started`):(this.logger.info(`extra transports will be registered when Trouter successfully connects`),this.showIgnored(`onExtraTransportsUpdated`))},e.prototype.onIncallModeTimer=function(){this.worker.exitIncallMode(),this.state===r.Connected?(this.worker.stopPingTimer(),this.worker.startPingTimer()):this.showIgnored(`onIncallModeTimer`)},e.prototype.onSetNewUserActivityState=function(){this.worker.sendUserActivityState(a.UserActivityEventReason.Modified,this.state===r.Connected)},e.prototype.onActivityStateResponseTimeout=function(){this.onMissedResponse(`onActivityStateResponseTimeout`)},e.prototype.forceReconnect=function(e){this.state===r.Connected&&this.worker.sendDisconnectTelemetryEvent(e),this.worker.resetTokenBackoff(),this.cleanUpAndInitiateReconnect({backoff:!1,allowCachedToken:!0})},e.prototype.onTerminalError=function(){this.logger.error(`Cannot proceed, reached terminal state. Switching from state '${r[this.state]}' to ${r[r.TerminalError]}`),this.stop(!0,!0),this.setState(r.TerminalError)},e.prototype.onMissedResponse=function(e){this.state===r.Connected?(this.worker.sendDisconnectTelemetryEvent(e),this.cleanUpAndInitiateReconnect({backoff:!1,allowCachedToken:!0})):this.showIgnored(e)},e.prototype.showIgnored=function(e){this.logger.debug(`Ignoring event '${e}' in state '${r[this.state]}'`)},e.prototype.setState=function(e){this.logger.info(`Switching from state '${r[this.state]}' to state '${r[e]}'`),this.state===e?this.logger.error(`Attempt to switch to the current state '${r[e]}'`):this.state=e},e.prototype.switchToIncallModeIfEnabled=function(){this.incallModeEnabled&&(this.worker.isIncallMode()||(this.worker.enterIncallMode(),this.worker.stopPingTimer(),this.worker.startPingTimer()),this.worker.restartIncallModeTimer())},e.prototype.cleanUpAndInitiateReconnect=function(e){if(!this.autoReconnect)return this.logger.info(`Automatic reconnect is disabled, stopping this connection`),void this.stop(!0);this.worker.cancelPendingRegistrationRequests(),this.worker.stopConnectionTimer(),this.worker.stopPingTimer(),this.worker.clearSentEventTimers(),this.worker.stopRegistrationTimer(),this.worker.stopSocketIo(),this.setState(r.RetrievingToken),this.worker.dispatchReconnecting(),this.worker.getToken(e.allowCachedToken,e.backoff,e.claimsChallenge,e.fallbackReason)},e}()},396:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ConnectionTracker=t.Properties=t.TrackerStep=t.ClientEventName=t.ResponseData=void 0;var r,i=n(659),a=n(509),o=n(642);t.ResponseData=function(e){this.id=e,this.status=200,this.headers={},this.body=``},function(e){e.Connected=`trouter_js_client_connected`,e.Disconnected=`trouter_js_client_disconnected`,e.Error=`trouter_js_client_error`,e.Progress=`trouter_js_client_progress`,e.Response=`trouter_js_client_response`,e.CheckConnection=`trouter_js_client_check_connection`}(r||(t.ClientEventName=r={}));var s=function(e,t,n,r,i){this.stepName=e,this.operation=t,this.delta=n,this.ts=r,this.error=i};t.TrackerStep=s,t.Properties=function(){};var c=function(){this.numberOfPingReplies=0,this.connectedTimestamp=0,this.isNewUrl=!1,this.transportType=``,this.connectionNumber=0},l=function(){this.enabled=!1,this.numberOfStepsToMaintain=40,this.logHealthCheckError=!1,this.sendProgressTimeoutSecs=55,this.logSendPingError=!1,this.maxBackoffInMs=12e4,this.trouter_js_client_connected=!1,this.trouter_js_client_disconnected=!1,this.trouter_js_client_error=!1,this.trouter_js_client_progress=!1,this.trouter_js_client_response=!1,this.trouter_js_client_request=!1,this.trouter_js_client_registration=!1,this.trouter_js_client_unregistration=!1,this.trouter_js_client_check_connection=!0};t.ConnectionTracker=function(){function e(e,t,n,r,a,s,u){this.clientId=t,this.clientInfo=n,this.getServerState=r,this.endpointId=a,this.clientCorrelationID=s,this.environment=u,this.logger=new o.Logger(`ConnectionTracker`,e),this.clientCorrelationID=s===void 0?``:s,this.steps=[],this.connectionAttempt=0,this.totalStepCount=0,this.beginTimestamp=new i.Timespan,this.eventLogSettings=new l,this.connectedInfo=new c}return e.prototype.enable=function(e){this.eventLogSettings.enabled=!0,this.eventLogger=e},e.prototype.disable=function(){this.eventLogSettings.enabled=!1},e.prototype.sendProgress=function(e){this.steps.length>0&&this.sendTelemetry(r.Progress,e,this.steps)},e.prototype.cancelProgressTimer=function(){this.progressTimeout!==void 0&&(clearTimeout(this.progressTimeout),this.progressTimeout=void 0)},e.prototype.resetProgressSendTimer=function(){var e=this;this.cancelProgressTimer(),this.eventLogSettings.sendProgressTimeoutSecs!==void 0&&this.eventLogSettings.sendProgressTimeoutSecs>0&&(this.progressTimeout=setTimeout((function(){e.sendProgress({reason:`timeout`,timeoutSecs:e.eventLogSettings.sendProgressTimeoutSecs})}),1e3*this.eventLogSettings.sendProgressTimeoutSecs))},e.prototype.setConnectedInfo=function(e,t){this.connectedInfo.numberOfPingReplies=0,this.connectedInfo.connectedTimestamp=Date.now(),this.connectedInfo.isNewUrl=e,this.connectedInfo.transportType=t,++this.connectedInfo.connectionNumber},e.prototype.clearConnectedInfo=function(){this.connectedInfo.numberOfPingReplies=0,this.connectedInfo.connectedTimestamp=0,this.connectedInfo.isNewUrl=!0,this.connectedInfo.transportType=``},e.prototype.copyProperties=function(e,t){for(var n=0,r=Object.keys(t);n<r.length;n++){var i=r[n];t[i]!==void 0&&(e[i.replace(/-/g,`_`)]={value:t[i]})}},e.prototype.increasePingResponseCount=function(){++this.connectedInfo.numberOfPingReplies},e.prototype.sendTelemetry=function(e,t,n){try{if(!0===this.eventLogSettings.enabled&&!0===this.eventLogSettings[e]&&this.eventLogger!==void 0){var r=this.getServerState(),o={name:e,properties:{connectionAttempt:{value:this.connectionAttempt},epid:{value:this.endpointId},clientCorrelationID:{value:this.clientCorrelationID},steps:{value:(0,i.toJson)(n)},clientID:{value:this.clientId},eventVersion:{value:3},environment:{value:this.environment},cv:{value:a.CLIENT_VERSION},ua:{value:this.clientInfo.ua},connectionId:{value:r.connectionId},connectedClientId:{value:r.connectedClientId},domId:{value:r.domId},url:{value:r.url},ttlInSecs:{value:r.getRemainingTtlInSec()},numberOfPingReplies:{value:this.connectedInfo.numberOfPingReplies},connectedTimestamp:{value:this.connectedInfo.connectedTimestamp},isNewUrl:{value:this.connectedInfo.isNewUrl},transportType:{value:this.connectedInfo.transportType},connectionNumber:{value:this.connectedInfo.connectionNumber}}};this.copyProperties(o.properties,t),this.eventLogger.logEvent(o)}}catch(t){this.logger.warn(`error in sending event ${e}: ${(0,i.toJson)(t)}`)}},e.prototype.createStep=function(e,t,n){return new s(e,t,this.beginTimestamp.duration,Date.now(),n)},e.prototype.addStep=function(e,t,n){if(!1!==this.eventLogSettings.enabled&&(this.steps.length===0&&this.beginTimestamp.reset(),this.steps.push(this.createStep(e,t,n)),++this.totalStepCount,this.eventLogSettings.numberOfStepsToMaintain!==void 0&&this.steps.length>this.eventLogSettings.numberOfStepsToMaintain)){var i=this.steps.slice(0);this.steps.length=0,this.sendTelemetry(r.Progress,{reason:`flush`},i)}},e.prototype.trackStart=function(e){this.addStep(e,`start`)},e.prototype.trackEnd=function(e){this.addStep(e,`end`)},e.prototype.trackError=function(e,t,n,i){n===void 0&&(n=!0),e===`health`&&!0!==this.eventLogSettings.logHealthCheckError||e===`ping`&&!1===this.eventLogSettings.logSendPingError||(i===void 0&&(i=`error`),!0===n&&this.addStep(e,i,t),this.sendTelemetry(r.Error,{},[this.createStep(e,i,t)]))},e.prototype.trackProgress=function(e,t){this.addStep(e,t)},e.prototype.trackConnected=function(e,t){this.setConnectedInfo(e,t);var n=this.steps.slice(0),i=this.totalStepCount,a=this.beginTimestamp.duration;this.steps.length=0,this.totalStepCount=0,this.sendTelemetry(r.Connected,{stepCount:n.length,totalStepCount:i,connectionEstablishmentMs_Total:a},n),this.cancelProgressTimer()},e.prototype.getSessionLength=function(){return Date.now()-this.connectedInfo.connectedTimestamp},e.prototype.trackDisconnected=function(e){e.sessionLengthMS=this.getSessionLength(),this.sendTelemetry(r.Disconnected,e,[]),this.resetProgressSendTimer()},e.prototype.trackNewConnection=function(){++this.connectionAttempt},e.prototype.trackResponse=function(e,t,n,a){var o={};a!==void 0&&(o.hasError=!0,o.error=a);try{o.responseTimestamp=n===void 0?Date.now():n.sentTS,e&&(o.requestID=e.id,o.httpMethod=e.method,o.shortUrl=(0,i.anonymizeShortUrl)(e.shortUrl),o.correlationVector=e.correlationVector,o.requestHeaders=(0,i.headersToLog)(e.headers)),n&&(o.latencyMS=t,o.responseCode=n.status,o.responseLength=n.body.length)}catch(e){o.hasError=!0,o.error=`${o.error} error creating response context ${(0,i.toJson)(e)}`}this.sendTelemetry(r.Response,o,[])},e.prototype.sendResponseError=function(e,t,n){this.trackResponse(t,void 0,n,e)},e.prototype.close=function(){this.sendProgress({reason:`closed`}),this.steps.length=0,this.cancelProgressTimer()},e.prototype.mergeSettings=function(e){if(e){this.eventLogSettings.numberOfStepsToMaintain=Math.min(40,Math.max(10,e.numberOfStepsToMaintain===void 0?0:e.numberOfStepsToMaintain));var t=Math.min(3600,Math.max(55,e.sendProgressTimeoutSecs===void 0?0:e.sendProgressTimeoutSecs));this.eventLogSettings.logHealthCheckError=e.logHealthCheckError,this.eventLogSettings.logSendPingError=e.logSendPingError;for(var n=0,i=Object.keys(r).map((function(e){return r[e]}));n<i.length;n++){var a=i[n];e[a]!==void 0&&(this.eventLogSettings[a]=e[a])}this.eventLogSettings.sendProgressTimeoutSecs!==t&&(this.eventLogSettings.sendProgressTimeoutSecs=t,this.resetProgressSendTimer())}},e}()},423:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterManagerState=t.UserActivityEventReason=t.ServerState=void 0;var r,i,a=n(659);t.ServerState=function(){function e(e,t,n,r,i,a){this.connectionId=e,this.connectedClientId=t,this.domId=n,this.url=r,this.c2cUrlBase=i,this.expirationTsSec=a}return e.prototype.getRemainingTtlInSec=function(){return(0,a.calculateTtlInSec)(this.expirationTsSec)},e}(),function(e){e[e.Unknown=0]=`Unknown`,e[e.Modified=1]=`Modified`,e[e.Snapshot=2]=`Snapshot`,e[e.Connected=3]=`Connected`}(r||(t.UserActivityEventReason=r={})),function(e){e[e.Unknown=0]=`Unknown`,e[e.Connected=2]=`Connected`,e[e.Disconnected=3]=`Disconnected`,e[e.Switching=9]=`Switching`,e[e.TerminalError=10]=`TerminalError`}(i||(t.TrouterManagerState=i={}))},509:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.USER_AUTHENTICATE_EVENT_NAME=t.SUPPORTED_TOKEN_TYPES=t.FAILED_MESSAGE_ACK=t.UNHANDLED_MESSAGE_ACK=t.HANDLED_MESSAGE_ACK=t.CLIENT_VERSION=t.constants=void 0,t.constants={TROUTER_INIT:`trouterinit`,TROUTER_READY_EVENT:`trouterReadyEvent`,TROUTER_READY_TIMEOUT:`trouterReadyTimeout`,TROUTER_TOKEN_REQUEST:`trouterTokenRequest`,TROUTER_TOKEN_GET_SUCCEEDED:`trouterTokenGetSucceeded`,TROUTER_TOKEN_GET_FAILED:`trouterTokenGetFailed`,TROUTER_RECONNECTING:`trouterReconnecting`,RENEWAL:`renewal`,NEW_CONNECTION:`newConnection`,ENDPOINT_REGISTRATION_FAILED:`endpointRegistrationFailed`,SUBSCRIPTIONS_DEFAULT_SCOPE:`defaultScope`},t.CLIENT_VERSION=`2026.03.01.8`,t.HANDLED_MESSAGE_ACK=200,t.UNHANDLED_MESSAGE_ACK=404,t.FAILED_MESSAGE_ACK=500,t.SUPPORTED_TOKEN_TYPES=[`skype`,`aad`,`cae`],t.USER_AUTHENTICATE_EVENT_NAME=`user.authenticate`},573:function(e,t,n){var r=this&&this.__assign||function(){return r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},r.apply(this,arguments)},i=this&&this.__awaiter||function(e,t,n,r){return new(n||=Promise)((function(i,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((r=r.apply(e,t||[])).next())}))},a=this&&this.__generator||function(e,t){var n,r,i,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},o=Object.create((typeof Iterator==`function`?Iterator:Object).prototype);return o.next=s(0),o.throw=s(1),o.return=s(2),typeof Symbol==`function`&&(o[Symbol.iterator]=function(){return this}),o;function s(s){return function(c){return function(s){if(n)throw TypeError(`Generator is already executing.`);for(;o&&(o=0,s[0]&&(a=0)),a;)try{if(n=1,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,r=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((i=(i=a.trys).length>0&&i[i.length-1])||s[0]!==6&&s[0]!==2)){a=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){a.label=s[1];break}if(s[0]===6&&a.label<i[1]){a.label=i[1],i=s;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(s);break}i[2]&&a.ops.pop(),a.trys.pop();continue}s=t.call(e,a)}catch(e){s=[6,e],r=0}finally{n=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}};Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterConnection=t.ReconnectReason=void 0;var o,s=n(673),c=n(659),l=n(396),u=n(509),d=n(764),f=n(107),p=n(234),m=n(423),h=n(642),g=n(902),_=n(335),v=n(705),y=n(983),b=function(){this.cv=u.CLIENT_VERSION,this.ua=``,this.hr=``,this.v=``},x=function(){function e(){this[`force new connection`]=!0,this.reconnect=!1,this.query=``,this.ackTimeoutMs=5e3}return e.prototype.rewriteUrlForProxy=function(e){return e},e}(),S=`MS-CV`,C=function(){function e(e,t){this.logger=t,this.cvCounter=0;var n=JSON.parse(e);this.startTS=this.safeJsonNumber(n,`startTS`,0),this.url=this.safeJsonString(n,`url`,``),this.shortUrl=this.safeJsonString(n,`shortUrl`,``),this.body=this.safeJsonString(n,`body`,``),this.headers=this.safeJsonRecord(n,`headers`,{}),this.id=this.safeJsonNumber(n,`id`,-1),this.method=this.safeJsonString(n,`method`,``),this.replied=!1,this.timedout=!1,this.receivedCv=this.headers[S],this.updateCvHeader()}return Object.defineProperty(e.prototype,"correlationVector",{get:function(){return this.receivedCv?`${this.receivedCv}.${this.cvCounter}`:``},enumerable:!1,configurable:!0}),e.prototype.on=function(e,t){e===`data`?this.dataCallback=t:e===`end`&&(typeof this.dataCallback==`function`&&this.dataCallback(this.body),t())},e.prototype.incrementCorrelationVector=function(){++this.cvCounter,this.updateCvHeader()},e.prototype.updateCvHeader=function(){var e=this.correlationVector;e&&(this.headers[S]=e)},e.prototype.safeJsonNumber=function(e,t,n){var r;if(e!=null&&Object.prototype.hasOwnProperty.call(e,t)){var i=e;if(typeof i[t]==`number`)return i[t];if(typeof i[t]==`string`)return parseFloat(i[t]);(r=this.logger)==null||r.warn(`unexpected type of '${t}': ${typeof i[t]}`)}return n},e.prototype.safeJsonString=function(e,t,n){var r;if(e!=null&&Object.prototype.hasOwnProperty.call(e,t)){var i=e;if(typeof i[t]==`string`)return i[t];(r=this.logger)==null||r.warn(`unexpected type of '${t}': ${typeof i[t]}`)}return n},e.prototype.safeJsonRecord=function(e,t,n){var r;if(e!=null&&Object.prototype.hasOwnProperty.call(e,t)){var i=e;if(typeof i[t]==`object`)return i[t];(r=this.logger)==null||r.warn(`unexpected type of '${t}': ${typeof i[t]}`)}return n},e}(),w=function(){function e(e,t,n){this.request=e,this.responseData=t,this.sendResponse=n}return e.prototype.writeHead=function(e,t){this.responseData.status=e,this.responseData.headers=t},e.prototype.write=function(e){this.responseData.body+=e},e.prototype.end=function(e){return e&&(this.responseData.body+=e),this.sendResponse(this.request,this.responseData)},e}(),T=function(e){this.name=e,this.args={},this.timeoutTimerId=0};(function(e){e[e.Configuration=0]=`Configuration`,e[e.ServerInitiated=1]=`ServerInitiated`})(o||(t.ReconnectReason=o={}));var E=function(){function e(e,t,n,r,i,a,o,c){var d,p=this;this.logProvider=e,this.options=t,this.manager=n,this.tokenProvider=r,this.usingLegacyTokenApi=i,this.protocolSelector=o,this.audienceSubscriptionState=c,this.WEBSOCKET_TRANSPORT_NAME=`websocket`,this.XHR_POLLING_TRANSPORT_NAME=`xhr-polling`,this.AUDIENCE_SUBSCRIPTION_RESULT_ERROR=`Error`,this.AUDIENCE_SUBSCRIPTION_RESULT_UNSUBSCRIBED=`Unsubscribed`,this.AUDIENCE_SUBSCRIPTION_RESULT_TIMEOUT=`Timeout`,this.AUDIENCE_SUBSCRIPTION_RESULT_BAD_REQUEST=`BadRequest`,this.AUDIENCE_SUBSCRIPTION_STATE_QUERY_PARAM_REGEX=/&audienceSubscriptionState=[^&]*|^audienceSubscriptionState=[^&]*&?/,this.USER_ACTIVITY_QUERY_PARAM_REGEX=/userActivity=[^&]*/,this.connectionId=``,this.inIncallMode=!1,this.connectionAttempt=0,this.connectedClientId=``,this.isNavigatorOnline=!0,this.onNavigatorOnlineStatusUpdateBound=this.onNavigatorOnlineStatusUpdate.bind(this),this.c2cUrlBase=``,this.connectingErrorsInRow=0,this.connectivityCheckFailuresInARow=0,this.unauthorizedErrorCount=0,this.pendingSentEventTimers={},this.extraTransports={},this.clientDescriptionOverride={},this.lastDisconnectReason=``,this.UNKNOWN_TRANSPORT=`unknown_transport`,this.connectingErrorsThreshold=3,this.pendingAudienceSubscription=void 0,this.areSubscriptionsEqual=function(e,t){if(e.length!==t.length)return!1;e=e.sort((function(e,t){return e.id.localeCompare(t.id)})),t=t.sort((function(e,t){return e.id.localeCompare(t.id)}));for(var n=0;n<e.length;n++)if(e[n].id!==t[n].id)return!1;return!0},this.logger=new h.Logger(`Connection`,e),this.timeoutOptions=this.options.timeoutOptions,this.tokenBackoff=new f.ExponentialBackoff(this.logger,this.timeoutOptions.maxBackoffMs),this.clientID=Date.now(),typeof window<`u`&&window.location&&(this.domId=window.location.hostname);var m=new b;m.cv=u.CLIENT_VERSION,m.ua=``,(d=this.options)!=null&&d.clientInfo&&(m.ua=this.safeString(this.options.clientInfo.ua),m.v=this.safeString(this.options.clientInfo.v)),this.clientInfo=m,this.connectionTracker=new l.ConnectionTracker(e,this.clientID,this.clientInfo,(function(){return p.getServerState()}),this.options.endpointId,this.options.clientCorrelationID,this.options.environment),this.applyConnectionTrackerOptions(t);var g=this.options.incallModeTimeoutMs>0;if(this.fsm=new _.TrouterFsm(e,this,g,this.protocolSelector),t.registration&&!t.registration.useRegistrarUrlFromAllocate){var v={registrarUrl:t.registration.registrarUrl,proxyUrlRewrite:t.rewriteUrlForProxy,registrationId:t.registration.registrationId,requestTimeoutMs:t.timeoutOptions.fetchTimeoutMs,initialRetryDelayMs:1e3,maxRetryDelayMs:t.timeoutOptions.maxBackoffMs,usingLegacyTokenApi:this.usingLegacyTokenApi,maxRetriesForGetToken:t.retryLimitOnTokenFetch,extraRegistrationHeaders:t.extraConnectionHeaders};this.registrarClient=(0,s.createRegistrarClient)(e,this.tokenProvider,v)}this.userActivityState=a}return e.prototype.start=function(e,t,n){this.logger.info(`Starting`),this.reconnectParams=e,this.extraTransports=t??{},this.clientDescriptionOverride=n??{},typeof window<`u`&&window.navigator&&window.addEventListener?(this.isNavigatorOnline=window.navigator.onLine,window.addEventListener(`online`,this.onNavigatorOnlineStatusUpdateBound),window.addEventListener(`offline`,this.onNavigatorOnlineStatusUpdateBound),this.logger.debug(`Registered for browser online notifications - current state: ${this.isNavigatorOnline}`)):this.isNavigatorOnline=!0,this.fsm.start()},e.prototype.stop=function(e){this.logger.info(`Stopping`),typeof window<`u`&&window.navigator&&(window.removeEventListener(`online`,this.onNavigatorOnlineStatusUpdateBound),window.removeEventListener(`offline`,this.onNavigatorOnlineStatusUpdateBound)),this.fsm.stop(e),this.connectionTracker.close()},e.prototype.configure=function(e){var t=this.options.trouterUrl!==e.trouterUrl;this.options=e,this.applyConnectionTrackerOptions(e),t&&(this.logger.info(`Configuration changed. Reconnection required.`),this.fsm.onReconnectRequired(!1,o.Configuration))},e.prototype.checkConnection=function(e){this.logger.info(`checkConnection called with ${e}`),this.fsm.checkConnection(e),e&&this.connectionTracker.sendTelemetry(l.ClientEventName.CheckConnection,{disconnectDetected:e},[])},e.prototype.disableRegistrationsAndAutoReconnect=function(){this.stopRegistrationTimer(),this.cancelPendingRegistrationRequests(),this.fsm.disableAutoReconnect()},e.prototype.getServerState=function(){return new m.ServerState(this.connectionId,this.connectedClientId,this.domId?this.domId:``,this.allocateResult?this.allocateResult.surl:``,this.c2cUrlBase,this.connectionExpireTimestampInSecs)},e.prototype.getState=function(){return this.fsm.getState()},e.prototype.getToken=function(e,t,n,r,i){var a=this;i===void 0&&(i=0),this.logger.info(`Getting token ${t?`with backoff`:`without backoff`}`);var o=function(){a.connectionTracker.trackStart(`token`);var t={needFresh:!e,wwwAuthenticateHeader:n,supportedTokenTypes:u.SUPPORTED_TOKEN_TYPES,purpose:`trouter`};a.logger.info(`Requesting token: needFresh=${t.needFresh} types=[${u.SUPPORTED_TOKEN_TYPES}], wwwAuthenticateHeader is ${t.wwwAuthenticateHeader?`non empty`:`empty`}`),a.tokenProvider(t).then((function(e){a.logger.debug(`${e.tokenType} token is received`),a.connectionTracker.trackEnd(`token`),a.fsm.onTokenReceived(e,r,a.reconnectParams)})).catch((function(t){var o=(0,c.toJson)(t.stack);if(a.logger.error(`Getting token failed, will retry after timeout. Error: ${o}`),a.connectionTracker.trackError(`token`,o),!a.canRetryTokenFetchRequest(i+a.unauthorizedErrorCount))return a.connectionTracker.trackError(`token`,`getToken retry limit hit, reached terminal error state`),a.resetTokenBackoff(),void a.fsm.onTerminalError();a.getToken(e,!0,n,r,i+1)}))};t?this.tokenBackoff.backoff(`getting token`,o):(this.resetTokenBackoff(),o())},e.prototype.startConnectionTimer=function(){var e=this;this.stopConnectionTimer(),this.logger.debug(`Starting connection timeout for ${this.timeoutOptions.connectionTimeoutMs} ms`),this.connectionTimeoutId=setTimeout((function(){e.logger.info(`Connection timeout is fired`),e.fsm.onConnectingTimeout()}),this.timeoutOptions.connectionTimeoutMs)},e.prototype.stopConnectionTimer=function(){this.connectionTimeoutId&&=(this.logger.debug(`Stopping connection timeout`),clearTimeout(this.connectionTimeoutId),void 0)},e.prototype.startPingTimer=function(){var e=this;this.transportTypeName===`websocket`?(this.logger.debug(`Starting ping timeout for ${this.timeoutOptions.pingTimeoutMs} ms`),this.pingTimerId=setInterval((function(){e.logger.info(`Ping interval fired`),e.fsm.onPingInterval()}),this.timeoutOptions.pingTimeoutMs)):this.logger.debug(`Not starting ping for transport ${this.transportTypeName}`)},e.prototype.stopPingTimer=function(){this.pingTimerId&&=(this.logger.debug(`Stopping ping timeout`),this.clearPingResponseTimer(),clearInterval(this.pingTimerId),void 0)},e.prototype.shouldSkipRegistration=function(){return this.options.registration===void 0},e.prototype.hasCustomRegistrationTtl=function(){return this.options.registration?.registrarTtlSec!==void 0&&this.options.registration?.registrarTtlSec!==0},e.prototype.startRegistrationTimer=function(){var e=this;this.stopRegistrationTimer();var t=this.getRegistrationTtl(),n=t[0],r=t[1];if(n<=30||!r)return this.logger.debug(`Starting registration expiration timer (TTL ${n} sec)`),void(this.registrationTimerId=setTimeout((function(){e.registrationTimerId=void 0,e.logger.warn(`Registration expired but the connection is still alive. Should never happen`),e.dispatchUnregistered()}),1e3*n));var i=n-30;this.logger.debug(`Starting registration extension timer for ${i} sec`),this.registrationTimerId=setTimeout((function(){e.logger.info(`Registration extension timer fired`),e.registrationTimerId=setTimeout((function(){e.registrationTimerId=void 0,e.logger.debug(`Registration extension did not happen in time`),e.dispatchUnregistered()}),3e4),e.fsm.onRegistrationNearExpiry()}),1e3*i)},e.prototype.startRegistrationRetryTimer=function(){var e=this;this.stopRegistrationTimer(),this.registrationTimerId=setTimeout((function(){e.registrationTimerId=void 0,e.fsm.onRetryRegistration()}),123e3)},e.prototype.stopRegistrationTimer=function(){this.registrationTimerId&&=(this.logger.debug(`Stopping registration timeout`),clearTimeout(this.registrationTimerId),void 0)},e.prototype.resendRegistration=function(){if(!this.registrarClient)throw Error(`Trouter Client not configured to handle registrations`);return this.fsm.onResendRegistration(),Promise.resolve()},e.prototype.registerExtraTransports=function(e,t){this.logger.info(`Registering ${Object.keys(e).length} extra transports`),this.extraTransports=e,this.clientDescriptionOverride=t??{},this.fsm.onExtraTransportsUpdated()},e.prototype.buildSocketIoUrlParams=function(e,t){if(!this.allocateResult)throw Error(`Allocate result is undefined in buildSocketIoUrlParams()`);for(var n={},r=this.allocateResult.connectparams,i=0,a=Object.keys(r);i<a.length;i++){var o=a[i];if(r[o]!==void 0){var s=r[o];typeof s==`string`||typeof s==`number`?n[o]=s:this.logger.error(`signatureData[${o}] has unsupported type ${typeof s}`)}}return n.v=`v4`,n.tc=encodeURI((0,c.toJson)(this.clientInfo)),n.timeout=this.timeoutOptions.pingTimeoutMs/1e3,n.auth=`true`,this.options.endpointId&&(n.epid=this.options.endpointId),e&&(n.userActivity=encodeURIComponent((0,c.toJson)(e))),t&&(n.audienceSubscriptionState=encodeURIComponent((0,c.toJson)(t))),this.appendConnectedClientIds(this.buildQuery(n),!0)},e.prototype.startSocketIo=function(e){if(this.logger.debug(`Starting socket io`),this.connectionTracker.trackStart(`connectSocket`),!this.allocateResult)throw Error(`Allocate result is undefined in startSocketIo()`);var t=this.options.ioOptions?r({},this.options.ioOptions):new x,n=this.userActivityState.state===p.UserActivityState.Unknown?void 0:this.userActivityState.increaseCvAndGetEventObject(),i=this.audienceSubscriptionState?.increaseCvAndGetEventObject();if(t[`force new connection`]=!0,t.reconnect=!1,t.rewriteUrlForProxy=this.options.rewriteUrlForProxy,t.requestHeaders=r(r({},this.options.extraConnectionHeaders),ee(e,this.usingLegacyTokenApi)),t.query=this.buildSocketIoUrlParams(n,i),this.logger.info(`connecting to ${this.allocateResult.socketio}`),this.stopSocketIo(),this.socket=(this.options.io??y).connect(this.allocateResult.socketio,t),this.socket===void 0)throw Error(`Can't create Socket.io object`);this.attachSocketIoHandlers(this.socket,e,n,i)},e.prototype.stopSocketIo=function(){if(this.socket){this.logger.debug(`clearing socket.io`);try{for(var e=0,t=[`connecting`,`connect`,`connect_failed`,`close_during_connecting`,`disconnect`,`reconnect`,`reconnect_failed`,`reconnecting`,`error`,`message`,`trouter.connected`,`trouter.reconnect`,`trouter.message_loss`,`audience.subscriptionresult`];e<t.length;e++){var n=t[e];this.socket.removeAllListeners(n)}this.socket.disconnect(),this.logger.debug(`cleared socket`),this.socket=void 0}catch(e){this.logger.error(`exception in disconnecting previous socket. Error: ${D(e)}`)}}},e.prototype.dispatchConnected=function(){this.logger.info(`dispatching connected`),this.manager.onConnected(this)},e.prototype.dispatchRegistered=function(){this.logger.info(`dispatching registered`),this.manager.onRegistered(this)},e.prototype.dispatchUnregistered=function(){this.logger.info(`dispatching unregistered`),this.manager.onUnregistered(this)},e.prototype.dispatchDownstreamRequest=function(e){var t=this;this.logger.debug(`dispatching downstream request`);try{var n=new w(e,new l.ResponseData(e.id),(function(e,n){return t.logger.debug(`sending response to downstream`),t.sendResponse(e,n)}));this.manager.onDownstreamRequest(this,e,n)}catch(e){this.logger.error(`exception in socket.on message. Error : ${D(e)}`)}},e.prototype.dispatchReconnecting=function(){this.logger.info(`dispatching reconnecting`),this.manager.onReconnecting(this)},e.prototype.dispatchReconnectIsRequired=function(e,t){this.logger.info(`dispatching reconnect is required by server`),this.manager.onReconnectIsRequired(this,e,t)},e.prototype.dispatchDisconnected=function(){this.logger.info(`dispatching disconnected`),this.manager.onDisconnected(this)},e.prototype.dispatchTerminalError=function(){this.logger.info(`dispatching terminal error`),this.manager.onTerminalError(this)},e.prototype.dispatchTrouterMessageLost=function(e){this.logger.info(`dispatching trouter message lost`),this.manager.onTrouterMessageLost(e)},e.prototype.countDisconnectBeforeConnectionEstablishment=function(){this.logger.warn(`counting disconnect before connection was fully established as a connection failure`),this.connectingErrorsInRow++,this.connectingErrorsInRow>=this.connectingErrorsThreshold&&this.resetReconnectParamsOnErrorThreshold()},e.prototype.sendProcessedDroppedIndicators=function(e){var t=this;try{this.logger.debug(`emitting processed flow tags to the server`);var n=new T(`trouter.processed_message_loss`);n.args={droppedIndicators:e},this.sendDownstreamEvent(n,(function(){t.logger.info(`emitted processed flow tags to the server`)}))}catch(e){var r=D(e);this.logger.error(`unable to send processed message loss event. Error: ${r}`),this.connectionTracker.trackError(`trouter.processed_message_loss`,r,!1)}},e.prototype.sendAllocateRequest=function(e){var t=this;this.connectionAttempt++,this.connectionTracker.trackNewConnection();var n,i=this.options.trouterUrl,a=this.reconnectParams,o=typeof a?.se==`string`?parseInt(a.se,10):typeof a?.se==`number`?a.se:void 0;o&&o<=Date.now()+36e5&&(this.logger.warn(`Dropping expired cached connection parameters: ${new Date(o)}`),this.reconnectParams=a=void 0),a&&a.serviceUrl!==i&&(this.logger.warn(`Dropping cached connection parameters for a different environment (${a.serviceUrl}, now ${i})`),this.reconnectParams=a=void 0),a!=null&&a.reconnectUrl&&(i=a.reconnectUrl),n=a?r(r({},a),{serviceUrl:void 0,reconnectUrl:void 0}):null,i=(0,g.adaptUrl)(i,`v4a`),i=this.appendCorrelationIds(i,!1),i=this.appendEndpointId(i,!1);var s=i=this.appendClientInfo(i,!1);n&&(i+=`&${this.buildQuery(n)}`,n.v||(i+=`&v=v4`)),i=this.options.rewriteUrlForProxy(i);var l=new Request(i,{method:`POST`,mode:`cors`,headers:new Headers(r(r({"Content-Type":`text/plain`},this.options.extraConnectionHeaders),ee(e,this.usingLegacyTokenApi)))});this.logger.info(`sendAllocateRequest: POST ${this.options.rewriteUrlForProxy(s)} (connectparams redacted)}`),this.connectionTracker.trackStart(`allocation`);var u,d=Date.now(),f=-1,p=!1;(0,c.fetchWithTimeout)(l,this.timeoutOptions.fetchTimeoutMs).then((function(e){if(f=e.status,!e.ok)throw u=e.headers.get(`www-authenticate`)??void 0,p=e.headers.get(`x-trouter-skypetoken-deprecated`)===`1`,t.logger.warn(`Allocation request got response status ${e.status}, www-authenticate header was ${u?`not empty`:`empty`}`),Error(e.statusText);var n=e.headers.get(`content-type`);if(!n||n!==`application/json`&&!n.startsWith(`application/json;`))throw Error(`Content-type '${n}' is unexpected`);return t.connectionTracker.trackEnd(`allocation`),e.json()})).then((function(n){t.unauthorizedErrorCount=0,t.onAllocationResponse(n,e)})).catch((function(e){t.connectingErrorsInRow++;var n=`${e}${f>=0?`, status code ${f}`:``}`;if(t.logger.error(`${t.connectingErrorsInRow} failed connecting attempt(s) in a row. ${n}`),t.connectionTracker.trackError(`allocation`,n),p){var r=`Skypetoken deprecated response, not retrying any further`;t.logger.error(r),t.connectionTracker.trackError(`allocation`,r),t.fsm.onTerminalError();return}if(f===401&&t.unauthorizedErrorCount++,!t.canRetryTokenFetchRequest(t.unauthorizedErrorCount))return r=`getToken retry limit hit, reached terminal error state`,t.connectionTracker.trackError(`allocation`,r),void t.fsm.onTerminalError();if(f!==-1||t.isNavigatorOnline){if(t.reconnectParams&&t.connectingErrorsInRow>=t.connectingErrorsThreshold){if(f>=400&&f<=599)t.resetReconnectParamsOnErrorThreshold();else if(t.reconnectParams.reconnectUrl&&t.connectingErrorsInRow%3==0){t.logger.warn(`${t.connectingErrorsInRow} connection attempts, testing nominal service URL`);var i=Math.min(t.timeoutOptions.connectionTimeoutMs-(Date.now()-d)-500,t.timeoutOptions.fetchTimeoutMs);t.testNominalUrlConnectivity(i).then((function(e){t.connectionTracker.trackProgress(`nomcheck`,e?`ok`:`failed`),e?(t.logger.warn(`Nominal service URL is reachable, erasing cached reconnect URL`),t.reconnectParams&&delete t.reconnectParams.reconnectUrl):t.logger.warn(`Nominal service URL is not reachable either, keeping cached reconnect URL`),t.fsm.onAllocationFailed(!1,void 0)}),(function(){t.fsm.onAllocationFailed(!1,void 0)}));return}}}else t.logger.info(`Expected failure, the browser says it is not online at the moment`);t.fsm.onAllocationFailed(f===401,u)}))},e.prototype.testNominalUrlConnectivity=function(e){var t,n=this;if(e<1e3)return this.logger.warn(`There is no time left to reasonably perform the nominal service URL connectivity check (${e} ms), falling back to assuming that the connectivity is fine`),Promise.resolve(!0);try{var r=new URL(this.options.trouterUrl);r.pathname=r.pathname.replace(/\/v4\/.*/,`/`),r.search=`?`+this.buildQuery({check:Date.now(),cor_id:encodeURIComponent(this.options.clientCorrelationID),epid:encodeURIComponent(this.options.endpointId?this.options.endpointId:``),tc:encodeURIComponent((0,c.toJson)(this.clientInfo))}),r.protocol===`wss:`&&(r.protocol=`https:`),t=new Request(this.options.rewriteUrlForProxy(r.toString()),{method:`GET`,headers:{Accept:`text/plain`}})}catch(e){return this.logger.warn(`Nominal service URL connectivity test request could not be created (${e}), falling back to assuming that the connectivity is fine`),Promise.resolve(!0)}return(0,c.fetchWithTimeout)(t,e).then((function(e){if(e.status!==200)throw Error(`Not 200 OK: ${e.status} ${e.statusText}`);return e.text()})).then((function(e){if(e!==`Trouter`)throw Error(`Not "Trouter": ${e.substring(0,16)}${e.length>16?`...`:``}`);return!0})).catch((function(e){return n.logger.error(`Nominal service URL connectivity test failed: ${e}`),!1}))},e.prototype.sendPingRequest=function(){var e=this;if(this.socket&&this.pingResponseTimerId===void 0)try{this.logger.debug(`emitting ping event`);var t=!1;this.socket.emit(`ping`,(function(){!0!==t&&e.onPingResponse()})),this.pingResponseTimerId=setTimeout((function(){e.logger.error(`Ping response timeout is fired`),t=!0,e.clearPingResponseTimer(),e.fsm.onPingResponseTimeout()}),this.timeoutOptions.pongTimeoutMs)}catch(e){var n=D(e);this.logger.error(`unable to send ping. Error: ${n}`),this.connectionTracker.trackError(`ping`,n,!1)}},e.prototype.connectV4c=function(e,t){return i(this,void 0,void 0,(function(){var n,i,o,s,c;return a(this,(function(a){switch(a.label){case 0:return[4,this.performV4cInitialConnectivityCheck()];case 1:if(!1===a.sent())return[2];(n=this.options.ioOptions?r({},this.options.ioOptions):new x)[`force new connection`]=!0,n.reconnect=!1,(c=this.reconnectParams)!=null&&c.serviceUrl&&(0,g.adaptUrl)(this.reconnectParams.serviceUrl,`v4c`)!==(0,g.adaptUrl)(this.options.trouterUrl,`v4c`)&&(this.logger.warn(`Dropping cached connection parameters for a different environment (${this.reconnectParams.serviceUrl}, now ${this.options.trouterUrl})`),this.reconnectParams=void 0),i=(0,g.redirectUrlIfPresent)(t)??(t?.kind===`redirect-no-host`?void 0:this.reconnectParams?.reconnectUrl)??this.options.trouterUrl,o=(0,g.adaptUrl)(i,`v4c`),n[`skipped handshake data`]={timeout:70,websocketUrl:o},n.query=this.buildV4cUrlParams(),n.rewriteUrlForProxy=this.options.rewriteUrlForProxy;try{if(this.stopSocketIo(),this.transportTypeName=`websocket`,this.socket=(this.options.io??y).connect(this.options.trouterUrl,n),this.socket===void 0)throw Error(`failed to create Socket.io object`);s=this.audienceSubscriptionState?.increaseCvAndGetEventObject(),this.attachSocketIoHandlers(this.socket,e,void 0,s)}catch(e){this.logger.error(`${e}`),this.connectionTracker.trackError(`v4c`,`${e}`),this.fsm.onV4cException()}return[2]}}))}))},e.prototype.performV4cInitialConnectivityCheck=function(){return i(this,void 0,void 0,(function(){return a(this,(function(e){switch(e.label){case 0:return this.options.initialConnectivityCheck?(this.logger.info(`checking connectivity to configured URL (go URL) before a connection attempt`),[4,this.testNominalUrlConnectivity(3e3)]):[2,!0];case 1:return e.sent()?(this.connectivityCheckFailuresInARow=0,[2,!0]):this.connectivityCheckFailuresInARow>=3?(this.connectivityCheckFailuresInARow=0,this.logger.error(`three connectivity checks failed in a row, will attempt with the fallback protocol`),this.fsm.onV4cException(),[2,!1]):(this.logger.warn(`connectivity check failed, will retry after backoff`),this.connectivityCheckFailuresInARow++,this.fsm.onV4cConnectivityCheckFailed(),[2,!1])}}))}))},e.prototype.sendV4cAuthenticationEvent=function(e){var t,n={headers:r(r({},this.options.extraConnectionHeaders),ee(e,this.usingLegacyTokenApi)),connectparams:(0,g.reconnectParamsWithoutUrls)(this.reconnectParams)};(t=this.socket)==null||t.emit(u.USER_AUTHENTICATE_EVENT_NAME,n)},e.prototype.setUserActivityState=function(e){var t=e.state!==this.userActivityState.state;this.userActivityState=e,t?(this.logger.info(`Changing user activity state to '${e.toEventJSON()}'`),this.fsm.onSetNewUserActivityState()):(this.logger.debug(`Not changing the same user activity state '${e.toEventJSON()}'`),this.manager.onUserActivityStateAccepted(e.correlationVector.value()))},e.prototype.sendUserActivityState=function(e,t){if(this.userActivityState.state!==p.UserActivityState.Unknown){if(this.options.updateUserActivityDuringConnectionAttempt&&this.socket){var n=this.userActivityState.toEventObject(),r=this.socket.socket.options.query;if(r){var i=`userActivity=${encodeURIComponent((0,c.toJson)(n))}`;r.search(this.USER_ACTIVITY_QUERY_PARAM_REGEX)==-1?this.socket.socket.options.query=r.concat(`&`,i):this.socket.socket.options.query=r.replace(this.USER_ACTIVITY_QUERY_PARAM_REGEX,i)}}this.transportTypeName===`websocket`&&t?e===m.UserActivityEventReason.Connected?this.sendUserActivityStateMultiple(2):this.sendUserActivityStateMultiple(1):this.transportTypeName===`xhr-polling`&&e===m.UserActivityEventReason.Modified&&this.fsm.forceReconnect(`user activity/force reconnect`)}},e.prototype.setAudienceSubscriptionsAsync=function(e,t){var n=this.audienceSubscriptionState;if(this.audienceSubscriptionState=e,this.transportTypeName===this.WEBSOCKET_TRANSPORT_NAME)return this.setAudienceSubscriptionsInternalAsync(e.increaseCvAndGetEventObject(),t);if(this.transportTypeName===this.XHR_POLLING_TRANSPORT_NAME){var r=this.setAudienceSubscriptionsLongpollInternalAsync(e.increaseCvAndGetEventObject(),t,n);return this.fsm.forceReconnect(`set audience subscription force reconnect`),r}throw Error(`set audience subscription executed on an unknown transport`)},e.prototype.setAudienceSubscriptionsUnsafeAsync=function(e){if(e)return this.transportTypeName===this.WEBSOCKET_TRANSPORT_NAME?this.setAudienceSubscriptionsInternalAsync(e,15e3):void 0},e.prototype.onAudienceSubscriptionResult=function(e){if(this.logger.info(`onAudienceSubscriptionResult`),this.pendingAudienceSubscription)return clearTimeout(this.pendingAudienceSubscription.timeoutId),this.pendingAudienceSubscription.audienceSetResolve(e),void(this.pendingAudienceSubscription=void 0);if(this.audienceSubscriptionState&&this.transportTypeName===this.XHR_POLLING_TRANSPORT_NAME){var t=new Set(this.audienceSubscriptionState.toListOfSubscriptions().map((function(e){return e.id}))??[]),n=this.audienceSubscriptionState.correlationVector.value();this.cleanPollingAudienceSubscriptionStateQueryParam(t,e,n),this.manager.onAudiencesSetResolved(e,n)}},e.prototype.setAudienceSubscriptionsInternalAsync=function(e,t){return i(this,void 0,void 0,(function(){var n,r,i=this;return a(this,(function(a){switch(a.label){case 0:return this.logger.info(`[WebSocket] Audience subscription set requested.`),(n=new T(`audience.subscribe`)).args=e,[4,new Promise((function(r){var a=!1,o=setTimeout((function(){return a=!0,r(i.buildAudienceSubscriptionsTimeoutResponse(e))}),t);i.sendDownstreamEvent(n,(function(e,t){a||(clearTimeout(o),i.logger.debug(`[Websocket] Audience subscription response: ${t}`),i.pendingAudienceSubscription&&i.onAudienceSubscriptionResult(t),r(t))}))}))];case 1:return r=a.sent(),this.manager.onAudiencesSetResolved(r,e.cv),[2,r]}}))}))},e.prototype.setAudienceSubscriptionsLongpollInternalAsync=function(e,t,n){return i(this,void 0,void 0,(function(){var r,i,o,s,c=this;return a(this,(function(a){switch(a.label){case 0:return this.logger.info(`[XHR Polling] Audience subscription set requested.`),this.pendingAudienceSubscription&&(this.logger.error(`Racing audience subscriptions occured. This situation resolves into undefined scenario and/or nasal demons.`),clearTimeout(this.pendingAudienceSubscription.timeoutId)),[4,new Promise((function(n){c.pendingAudienceSubscription={audienceSetResolve:n,timeoutId:setTimeout((function(){return c.pendingAudienceSubscription=void 0,n(c.buildAudienceSubscriptionsTimeoutResponse(e))}),t)}}))];case 1:return r=a.sent(),this.manager.getState()===p.TrouterState.Unknown||this.transportTypeName===this.WEBSOCKET_TRANSPORT_NAME||(this.logger.debug(`[XHR Polling] Audience subscription response: ${r}`),i=new Set(e.audiences.map((function(e){return e.id}))??[]),this.cleanPollingAudienceSubscriptionStateQueryParam(i,r,e.cv),o=this.handleAudienceUnsubscribeLongpoll(e,n),(s=r.responses).push.apply(s,o),this.manager.onAudiencesSetResolved(r,e.cv)),[2,r]}}))}))},e.prototype.cleanPollingAudienceSubscriptionStateQueryParam=function(e,t,n){var r=this,i=t.responses.filter((function(t){return t.result.audienceSubscriptionState===r.AUDIENCE_SUBSCRIPTION_RESULT_BAD_REQUEST&&e.has(t.audienceId)})),a=t.responses.filter((function(t){return t.result.audienceSubscriptionState===r.AUDIENCE_SUBSCRIPTION_RESULT_ERROR&&e.has(t.audienceId)})),o=t.responses.filter((function(t){return t.result.audienceSubscriptionState===r.AUDIENCE_SUBSCRIPTION_RESULT_TIMEOUT&&e.has(t.audienceId)})),s=i.map((function(e){return e.audienceId})),c=a.map((function(e){return e.audienceId})),l=o.map((function(e){return e.audienceId})),u=Array.from(e).filter((function(e){return s.indexOf(e)===-1&&c.indexOf(e)===-1&&l.indexOf(e)===-1})).map((function(e){return{id:e}}));u.length===0?this.clearAudienceSubscriptionStateQueryParam():this.updateAudienceSubscriptionStateQueryParam(u,n)},e.prototype.clearAudienceSubscriptionStateQueryParam=function(){var e;(e=this.socket?.socket?.options)!=null&&e.query&&(this.socket.socket.options.query=this.socket.socket.options.query.replace(this.AUDIENCE_SUBSCRIPTION_STATE_QUERY_PARAM_REGEX,``))},e.prototype.updateAudienceSubscriptionStateQueryParam=function(e,t){if(this.socket?.socket?.options?.query){var n=encodeURIComponent(JSON.stringify({audiences:e,cv:t})),r=this.socket.socket.options.query,i=(0,v.updateAudienceSubscriptionQuery)(r,n);this.socket.socket.options.query=i}},e.prototype.handleAudienceUnsubscribeLongpoll=function(e,t){var n=[],r=t?.toListOfSubscriptions()??[],i=!this.areSubscriptionsEqual(r,e.audiences);if(r.length>0&&i&&t){var a=r.filter((function(t){return e.audiences.find((function(e){return e.id===t.id}))===void 0})),o=this.mapToSyntheticAudienceSubscriptionResponses(a,this.AUDIENCE_SUBSCRIPTION_RESULT_UNSUBSCRIBED,200);n.push.apply(n,o)}return n},e.prototype.buildAudienceSubscriptionsTimeoutResponse=function(e){return this.logger.error(`Audience subscription attempt has timed out.`),{responses:this.mapToSyntheticAudienceSubscriptionResponses(e.audiences,this.AUDIENCE_SUBSCRIPTION_RESULT_TIMEOUT)}},e.prototype.mapToSyntheticAudienceSubscriptionResponses=function(e,t,n){return e===void 0?[]:e.map((function(e){return{audienceId:e.id,result:{audienceSubscriptionState:t,responseStatus:n}}}))},e.prototype.expediteBackoff=function(){this.tokenBackoff.expediteIfPending()},e.prototype.sendRegisterRequest=function(){var e=this;if(!this.options.registration)throw Error(`Internal error - options.registration is undefined`);if(!this.allocateResult)throw Error(`Allocate result is undefined in sendRegisterRequest()`);if(this.options.registration.useRegistrarUrlFromAllocate&&!this.registrarClient){if(!this.allocateResult.registrarUrl)throw Error(`Internal error - useRegistrarUrlFromAllocate is true, but allocateResult did not include registrarUrl`);var t={registrarUrl:this.allocateResult.registrarUrl,proxyUrlRewrite:this.options.rewriteUrlForProxy,registrationId:this.options.registration.registrationId,requestTimeoutMs:this.options.timeoutOptions.fetchTimeoutMs,initialRetryDelayMs:1e3,maxRetryDelayMs:this.options.timeoutOptions.maxBackoffMs,usingLegacyTokenApi:this.usingLegacyTokenApi,maxRetriesForGetToken:this.options.retryLimitOnTokenFetch,extraRegistrationHeaders:this.options.extraConnectionHeaders};this.registrarClient=(0,s.createRegistrarClient)(this.logProvider,this.tokenProvider,t)}if(!this.registrarClient)throw Error(`Internal error - registrarClient is undefined`);this.logger.info(`sending register request with ${1+Object.keys(this.extraTransports).length} transports and ${Object.keys(this.clientDescriptionOverride).length} overridden client description properties`),this.connectionTracker.trackStart(`registration`);var n=this.getRegistrationTtl()[0];this.registrarClient.register(r({appId:this.options.registration.pnhAppId,aesKey:``,languageId:`en-US`,platform:this.options.registration.platform,templateKey:this.options.registration.pnhTemplateKey,platformUIVersion:this.options.registration.platformUIVersion,productContext:this.options.registration.productContext},this.clientDescriptionOverride),r({TROUTER:[{context:this.options.registration.context,path:this.allocateResult.surl,ttl:n}]},this.extraTransports)).then((function(){e.logger.info(`Register request successful`),e.connectionTracker.trackEnd(`registration`),e.fsm.onRegistrationSucceeded()})).catch((function(t){e.logger.error(`Register request failed. Error: ${t}`),e.connectionTracker.trackError(`registration`,O(t)),e.fsm.onRegistrationFailed()}))},e.prototype.sendUnregisterRequest=function(){var e=this;if(Object.keys(this.extraTransports).length>0&&this.logger.warn(`explicit unregister called while there are extra transports`),this.logger.info(`sending unregister request`),!this.options.registration||!this.registrarClient)throw Error(`Internal error - options.registration is undefined`);this.connectionTracker.trackStart(`unregistration`),this.registrarClient.unregister().then((function(){e.logger.info(`Unregister request successful`),e.connectionTracker.trackEnd(`unregistration`),e.fsm.onUnregistrationDone()})).catch((function(t){e.logger.error(`Unregister request failed. Error: ${t}`),e.connectionTracker.trackError(`unregistration`,O(t)),e.fsm.onUnregistrationDone()}))},e.prototype.resetTokenBackoff=function(){this.tokenBackoff.reset()},e.prototype.cancelPendingRegistrationRequests=function(){this.registrarClient&&this.registrarClient.cancelPendingRequests()},e.prototype.clearSentEventTimers=function(){var e=Object.keys(this.pendingSentEventTimers);if(e.length>0){this.logger.debug(`Clearing all pending downstream events related timers`);for(var t=0,n=e;t<n.length;t++){var r=n[t];this.clearSentEventTimer(Number(r))}}},e.prototype.restartIncallModeTimer=function(){var e=this;this.clearIncallModeTimerId(),this.logger.debug(`Restarting incall mode timer`),this.incallModeTimerId=setTimeout((function(){e.logger.info(`Call mode timer fired`),e.fsm.onIncallModeTimer()}),this.options.incallModeTimeoutMs)},e.prototype.enterIncallMode=function(){this.logger.info(`Entering incall mode`),this.timeoutOptions=this.options.incallTimeoutOptions,this.tokenBackoff.setMaxBackoffMs(this.timeoutOptions.maxBackoffMs),this.inIncallMode=!0},e.prototype.exitIncallMode=function(){this.logger.info(`Exiting incall mode`),this.clearIncallModeTimerId(),this.timeoutOptions=this.options.timeoutOptions,this.tokenBackoff.setMaxBackoffMs(this.timeoutOptions.maxBackoffMs),this.inIncallMode=!1},e.prototype.isIncallMode=function(){return this.inIncallMode},e.prototype.sendDisconnectTelemetryEvent=function(e){var t={reason:e,serverClosed:!this.fsm.isActive()};this.connectionTracker.trackDisconnected(t),this.connectionTracker.clearConnectedInfo()},e.prototype.forceReconnectDueToNoRegistration=function(){this.fsm.forceReconnect(`force reconnect due to no registration`)},e.prototype.resetReconnectParamsOnErrorThreshold=function(){this.logger.warn(`${this.connectingErrorsInRow} connection attempts, server-side failure: erasing cached connection parameters`),this.reconnectParams=void 0},e.prototype.onSocketConnecting=function(e){this.logger.info(`onSocketConnecting(${e})`),this.transportTypeName=e,this.connectionTracker.trackProgress(`connecting`,this.transportTypeName),this.fsm.onConnecting()},e.prototype.onSocketConnect=function(e){this.logger.info(`onSocketConnect`),this.fsm.onSocketConnect(e)},e.prototype.onSocketConnectFailed=function(e){this.logger.error(`onSocketConnectFailed`),this.connectionTracker.trackError(`connect_failed`,e,!0,this.transportTypeName?this.transportTypeName:this.UNKNOWN_TRANSPORT),this.fsm.onConnectingFailed()},e.prototype.onSocketDisconnect=function(e){var t=this.connectionTracker.getSessionLength()||0,n=d.DisconnectReason.fromRawReason(e);this.logger.error(`onSocketDisconnect, reason: ${n.reason}`),n.reason===`dup`&&this.lastDisconnectReason===`dup`&&t<this.options.duplicateDisconnectThresholdMs&&(this.logger.warn(`Socket was closed by server as Duplicate for the second time in a row after ${t} ms which is below the threshold of ${this.options.duplicateDisconnectThresholdMs} ms. Resetting cached connection parameters and making a new allocation.`),this.reconnectParams=void 0),this.lastDisconnectReason=n.reason,this.fsm.onSocketDisconnect(n),this.connectionExpireTimestampInSecs=void 0},e.prototype.onSocketReconnect=function(){this.logger.error(`onSocketReconnect`),this.fsm.onTrouterConnected()},e.prototype.onSocketReconnectFailed=function(e){this.logger.error(`onSocketReconnectFailed with '${e}'`),this.fsm.onSocketDisconnect(d.DisconnectReason.fromSocketIoEventData(`reconnecterror`,e))},e.prototype.onSocketReconnecting=function(){this.logger.error(`onSocketReconnecting`)},e.prototype.onSocketError=function(e){var t;this.logger.error(`onSocketError with '${(0,c.toJson)(e)}'`),this.fsm.isConnecting()&&(this.connectingErrorsInRow++,this.connectingErrorsInRow>=this.connectingErrorsThreshold&&this.resetReconnectParamsOnErrorThreshold()),this.connectionTracker.trackError(`connectSocket`,(t=e)!=null&&typeof t.toString==`function`?t.toString():`[${typeof t}]`),this.fsm.onSocketDisconnect(d.DisconnectReason.fromSocketIoEventData(`socketerror`,e))},e.prototype.onSocketMessage=function(e){var t,n=this;this.logger.debug(`onSocketMessage`);try{var r=(t=new C(e,this.logger)).headers?.[`X-Microsoft-Skype-Chain-ID`],i=r?` Chain-Id ${r}`:``;this.logger.info(`Received request N ${t.id}${i} CV ${t.correlationVector} to '${t.url}'`),t.startTS=Date.now(),t.url&&this.urlPath&&t.url.startsWith(this.urlPath)&&(t.shortUrl=t.url.substring(this.urlPath.length))}catch(e){var a=D(e);this.logger.error(`unable to parse request. Error: ${a}`),this.connectionTracker.sendResponseError(`unable to parse request, error: ${e}`);return}t.timeoutTimerId=setTimeout((function(){if(!t.replied){n.logger.error(`Request ${t.id} timed out`);var e=new l.ResponseData(t.id);e.status=504,e.headers={"Trouter-Responder":`ClientLib`},n.sendResponse(t,e),t.timedout=!0}}),this.timeoutOptions.requestTimeoutMs);try{this.fsm.onDownstreamRequest(t)}catch(e){this.logger.error(`exception in socket.on message. Error: ${D(e)}`),this.connectionTracker.sendResponseError(O(e),t,void 0)}},e.prototype.onTrouterConnected=function(e,t,n){var i,a,o=this;if((0,g.isV4ConnectEvent)(e)){var s=e;this.allocateResult=r(r({},s),{ttl:e.ttl.toString()}),this.populateAndCacheReconnectParams(s,s.reconnectUrl),this.populateConnectionStateFields(s)}else if(!this.allocateResult)return void this.logger.error(`Invalid internal state - received onTrouterConnected while allocateResult is not set`);this.connectingErrorsInRow=0,this.logger.info(`onTrouterConnected: ${this.allocateResult.surl}`),this.options.updateUserActivityDuringConnectionAttempt?this.transportTypeName===`xhr-polling`&&((t?.state??`unknown`)===this.userActivityState.getStateString()?t&&this.manager.onUserActivityStateAccepted(t.cv):(this.logger.info(`XHR user activity changed during connection attempt, from '${(0,c.toJson)(t)}' to '${this.userActivityState.toEventJSON()}', updating`),this.sendUserActivityStateIgnoreResponse())):this.transportTypeName===`xhr-polling`&&t&&this.manager.onUserActivityStateAccepted(t.cv),(i=this.socket?.socket?.options)!=null&&i.query&&(this.socket.socket.options.query+=`&connected=true`),this.urlPath=this.allocateResult.surl.replace(/https?:\/\/([A-z0-9\:\$\-\_\.\+\!\*\"\(\)\,]*)\//,`/`);var l=this.connectedUrl!==this.allocateResult.surl;this.connectedUrl=this.allocateResult.surl,this.connectionExpireTimestampInSecs=(0,c.calculateExpireTsInSec)((0,g.ensureNumber)(e.ttl)),this.connectionTracker.trackEnd(`connectSocket`),this.connectionTracker.trackConnected(l,this.transportTypeName?this.transportTypeName:this.UNKNOWN_TRANSPORT),(a=this.setAudienceSubscriptionsUnsafeAsync(n))==null||a.catch((function(e){return o.logger.error(`Re-subscribe to audiences has failed with ${e}`)})),this.fsm.onTrouterConnected()},e.prototype.onTrouterReconnect=function(e){var t=e.target;this.logger.info(`onTrouterReconnect target: ${t}`),t===`self`?this.fsm.onReconnectRequired(!0,o.ServerInitiated):this.fsm.onReconnectRequired(!1,o.ServerInitiated,e)},e.prototype.onTrouterMessageLoss=function(e){this.logger.debug(`onTrouterMessageLoss`),this.fsm.onTrouterMessageLost(e.droppedIndicators)},e.prototype.buildV4cUrlParams=function(){var e={};return e.tc=encodeURI((0,c.toJson)(this.clientInfo)),e.timeout=Math.floor(this.timeoutOptions.pingTimeoutMs/1e3),this.options.endpointId&&(e.epid=this.options.endpointId),this.appendConnectedClientIds(this.buildQuery(e),!0)},e.prototype.attachSocketIoHandlers=function(e,t,n,r){var i=this;e.on(`connecting`,(function(e){i.onSocketConnecting(e)})),e.on(`connect`,(function(){i.onSocketConnect(t)})),e.on(`connect_failed`,(function(e){i.onSocketConnectFailed(e)})),e.on(`close_during_connecting`,(function(e){i.onSocketConnectFailed(e)})),e.on(`disconnect`,(function(e){i.onSocketDisconnect(e)})),e.on(`reconnect`,(function(){i.onSocketReconnect()})),e.on(`reconnect_failed`,(function(e){i.onSocketReconnectFailed(e)})),e.on(`reconnecting`,(function(){i.onSocketReconnecting()})),e.on(`error`,(function(e){i.onSocketError(e)})),e.on(`message`,(function(e){i.onSocketMessage(e)})),e.on(`trouter.connected`,(function(e){i.onTrouterConnected(e,n,r)})),e.on(`trouter.reconnect`,(function(e){i.onTrouterReconnect(e)})),e.on(`trouter.message_loss`,(function(e){i.onTrouterMessageLoss(e)})),e.on(`audience.subscriptionresult`,(function(e,t){i.onAudienceSubscriptionResult(t)}))},e.prototype.onNavigatorOnlineStatusUpdate=function(){var e=window.navigator.onLine;this.logger.debug(`Browser online status update - new state: ${e}, previously: ${this.isNavigatorOnline}`),e&&!this.isNavigatorOnline?(this.isNavigatorOnline=!0,this.tokenBackoff.expediteIfPending(),this.connectionTracker.trackProgress(`browserNet`,`online`)):!e&&this.isNavigatorOnline&&(this.isNavigatorOnline=!1,this.connectionTracker.trackProgress(`browserNet`,`offline`))},e.prototype.onAllocationResponse=function(e,t){this.logger.info(`Received allocation response ${JSON.stringify(r(r({},e),{connectparams:void 0}))} (connectparams redacted)`),this.allocateResult=e,this.populateAndCacheReconnectParams(this.allocateResult,`${this.allocateResult.socketio}v4/a`),this.populateConnectionStateFields(this.allocateResult),this.fsm.onAllocationSucceed(t)},e.prototype.populateAndCacheReconnectParams=function(e,t){this.reconnectParams=r({serviceUrl:this.options.trouterUrl,reconnectUrl:t},e.connectparams),this.manager.onConnectionParametersUpdated(this.reconnectParams)},e.prototype.populateConnectionStateFields=function(e){var t=typeof e.ttl==`string`?parseInt(e.ttl,10):e.ttl;if(this.connectionExpireTimestampInSecs=(0,c.calculateExpireTsInSec)(t),this.connectionId=e.id??``,this.connectedClientId=e.ccid,this.logger.debug(`connected client id set {connectedClientId:${this.connectedClientId}}`),this.c2cUrlBase=e.curlb??``,this.c2cUrlBase===``){var n=e.surl.indexOf(`://`);n>=0&&(n=e.surl.indexOf(`/`,n+3))>=5&&e.surl.substr(n-5,5)===`:3443`&&(this.c2cUrlBase=e.surl.substr(0,n-5))}},e.prototype.onPingResponse=function(){this.logger.debug(`onPingResponse`),this.connectionTracker.increasePingResponseCount(),this.clearPingResponseTimer(),this.fsm.onPingResponse()},e.prototype.clearPingResponseTimer=function(){this.pingResponseTimerId!==void 0&&(clearTimeout(this.pingResponseTimerId),this.pingResponseTimerId=void 0)},e.prototype.buildQuery=function(e){for(var t=[],n=0,r=Object.keys(e);n<r.length;n++){var i=r[n];e[i]!==void 0&&t.push(`${i}=${e[i]}`)}return t.join(`&`)},e.prototype.appendConnectedClientIds=function(e,t){var n=``;e.includes(`ccid=`)||(n=`ccid=${this.connectedClientId}&`),this.domId&&(n+=`dom=${this.domId}&`),n.length>0&&(n=n.slice(0,-1));var r=t||e.includes(`?`)?`&`:`?`;return this.appendCorrelationIds(e+r+n,t)},e.prototype.appendEndpointId=function(e,t){var n=t||e.includes(`?`)?`&`:`?`;return!e.includes(`epid`)&&this.options.endpointId?`${e}${n}epid=${this.options.endpointId}`:e},e.prototype.appendCorrelationIds=function(e,t){var n=t||e.includes(`?`)?`&`:`?`;return e.includes(`cor_id`)?e:`${e}${n}cor_id=${this.options.clientCorrelationID}&con_num=${this.clientID}_${this.connectionAttempt}`},e.prototype.appendClientInfo=function(e,t){var n=t||e.includes(`?`)?`&`:`?`,r=encodeURIComponent((0,c.toJson)(this.clientInfo));return e.includes(`tc=`)?e:`${e}${n}tc=${r}`},e.prototype.safeString=function(e){return typeof e==`string`?e:``},e.prototype.sendResponse=function(e,t){var n,r;if(e.timedout)return this.logger.error(`Request ${e.id} already timed out`),1;if(e.replied)return this.logger.error(`Response for request ${e.id} already sent`),2;clearTimeout(e.timeoutTimerId),e.timeoutTimerId=void 0,e.replied=!0,t.headers=t.headers??{};var i=e.correlationVector;this.logger.info(`Sending response N ${e.id} CV ${i} with status ${t.status}`),i&&(t.headers[S]=i),(n=e.headers)!=null&&n[`trouter-request`]&&(t.headers[`trouter-request`]=e.headers[`trouter-request`]);var a=Date.now()-e.startTS;if(t.headers[`trouter-client`]=(0,c.toJson)({cd:a}),(r=e.headers)!=null&&r[`trouter-is-broadcast`]&&(t.headers[`trouter-is-broadcast`]=e.headers[`trouter-is-broadcast`]),!this.socket)return this.connectionTracker.sendResponseError(`no socket`,e,t),4;try{return this.socket.send((0,c.toJson)(t)),t.sentTS=Date.now(),e.incrementCorrelationVector(),this.connectionTracker.trackResponse(e,a,t),this.transportTypeName===`websocket`&&this.sendPingRequest(),0}catch(n){var o=`unable to send data on response.end. Error: ${D(n)}`;return this.logger.error(o),this.connectionTracker.sendResponseError(o,e,t),4}},e.prototype.sendUserActivityStateMultiple=function(e){var t=this,n=new T(`user.activity`),r=this.userActivityState.increaseCvAndGetEventObject();n.args=r,this.logger.debug(`Sending user activity '${this.userActivityState.toEventJSON()}', remaining ${e-1}`);var i=!1;this.sendDownstreamEvent(n,(function(){if(!0!==i&&(t.logger.info(`User activity state: ${r.state}, cv: ${r.cv} accepted`),t.manager.onUserActivityStateAccepted(r.cv),t.clearSentEventTimer(n.timeoutTimerId),e>1)){var a=setTimeout((function(){t.clearSentEventTimer(a),t.sendUserActivityStateMultiple(e-1)}),t.options.userActivitySecondResendDelayMs);t.registerSentEventTimer(a,`user.activity/resend`)}})),n.timeoutTimerId=setTimeout((function(){t.logger.error(`Activity state response timeout is fired`),i=!0,t.fsm.onActivityStateResponseTimeout(),t.clearSentEventTimer(n.timeoutTimerId)}),this.timeoutOptions.userActivityResponseTimeoutMs),this.registerSentEventTimer(n.timeoutTimerId,`user.activity/response`)},e.prototype.sendUserActivityStateIgnoreResponse=function(){var e=new T(`user.activity`),t=this.userActivityState.toEventObject();e.args=t,this.socket&&(this.logger.info(`Sending user activity after XHR connect, ${t.state}, cv: ${t.cv}, treating it as accepted`),this.socket.emit(e.name,e.args),this.manager.onUserActivityStateAccepted(t.cv))},e.prototype.sendDownstreamEvent=function(e,t){this.logger.debug(`Sending downstream event ${e.name}`),this.socket&&this.socket.emit(e.name,e.args,t)},e.prototype.registerSentEventTimer=function(e,t){this.logger.debug(`registering timer ${e} -> ${t}`),this.pendingSentEventTimers[e]=t},e.prototype.clearSentEventTimer=function(e){var t=this.pendingSentEventTimers[e];this.logger.debug(`clearing timer ${e} -> ${t}`),delete this.pendingSentEventTimers[e],clearTimeout(e)},e.prototype.getRegistrationTtl=function(){var e=(0,c.calculateTtlInSec)(this.connectionExpireTimestampInSecs);if(this.logger.debug(`Current connectionID will expire in ${e} seconds`),this.options.registration?.registrarTtlSec&&e>0){var t=this.options.registration.registrarTtlSec<e;return[Math.min(this.options.registration.registrarTtlSec,e),t]}return this.options.registration?.registrarTtlSec?[this.options.registration.registrarTtlSec,!1]:e>0?[e,!1]:[3600,!1]},e.prototype.clearIncallModeTimerId=function(){this.incallModeTimerId!==void 0&&(this.logger.debug(`Clearing in-call mode timer`),clearTimeout(this.incallModeTimerId),this.incallModeTimerId=void 0)},e.prototype.applyConnectionTrackerOptions=function(e){try{e.eventLogger&&typeof e.eventLogger.logEvent==`function`?(this.connectionTracker.mergeSettings(e.telemetrySettings),this.connectionTracker.enable(e.eventLogger)):this.logger.warn(`Trouter client event logging disabled due to invalid configuration.`)}catch(e){this.logger.warn(`Trouter client event logging disabled. Error: ${D(e)}`),this.connectionTracker.disable()}},e.prototype.canRetryTokenFetchRequest=function(e){var t=this.options.retryLimitOnTokenFetch;return t==null||e<t||(this.logger.warn(`Reached limit on maximum number of token fetch request. Current count: ${e}, retry limit: ${t}`),!1)},e}();function ee(e,t){var n=t?void 0:{"X-MS-Migration":`True`};switch(e.tokenType.toLowerCase()){case`skype`:return r({"X-Skypetoken":e.token},n);case`aad`:case`cae`:return r({Authorization:`Bearer ${e.token}`},n);default:throw Error(`unsupported token type: ${e.tokenType}`)}}function D(e){return typeof e==`object`&&e&&e.stack!==void 0?(0,c.toJson)(e.stack):`"(no error.stack)"`}function O(e){return typeof e==`object`&&e&&typeof e.message==`string`?e.message:`(no error.message)`}t.TrouterConnection=E},616:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterUrlPromise=void 0;var r=n(642);t.TrouterUrlPromise=function(){function e(e){this.logger=new r.Logger(`UrlPromise`,e)}return e.prototype.getPromise=function(){var e=this;return this.url===void 0?(this.pendingPromise===void 0?(this.logger.debug(`creating and returning promise`),this.pendingPromise=new Promise((function(t,n){e.pendingPromiseResolveRef=t,e.pendingPromiseRejectRef=n}))):this.logger.debug(`returning existing promise`),this.pendingPromise):(this.logger.debug(`returning previously resolved url: ${this.url}`),Promise.resolve(this.url))},e.prototype.resolveUrl=function(e){this.url=e,this.logger.debug(`got url: ${this.url}`);var t=this.pendingPromiseResolveRef;this.pendingPromise=void 0,this.pendingPromiseResolveRef=void 0,this.pendingPromiseRejectRef=void 0,t!==void 0&&(this.logger.debug(`resolving promise`),t(e))},e.prototype.rejectUrl=function(e){this.logger.debug(`aborting`);var t=this.pendingPromiseRejectRef;this.url=void 0,this.pendingPromise=void 0,this.pendingPromiseResolveRef=void 0,this.pendingPromiseRejectRef=void 0,t!==void 0&&(this.logger.debug(`rejecting promise`),t(e))},e.prototype.resetUrl=function(){this.logger.debug(`resetting url`),this.url=void 0},e}()},619:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MessageHandlerRegistry=void 0;var r=n(509),i=n(642);t.MessageHandlerRegistry=function(){function e(e){this.messageHandlers=[],this.logger=new i.Logger(`MessageHandlers`,e)}return e.prototype.register=function(e){if(this.messageHandlers.some((function(t){return t===e})))throw Error(`Registering the same handler twice is not allowed`);this.messageHandlers.push(e)},e.prototype.clear=function(){this.logger.debug(`Clearing message handlers`),this.messageHandlers=[]},e.prototype.active=function(){return this.messageHandlers.length>0},e.prototype.handleMessage=function(e){for(var t={resultCode:r.UNHANDLED_MESSAGE_ACK,isHandled:!1},n=0,i=this.messageHandlers;n<i.length;n++){var a=i[n],o=this.safeExecuteHandle(a,e);if(o!==void 0&&(o.isHandled===void 0||o.isHandled))return o.resultCode===void 0&&(o.resultCode=r.HANDLED_MESSAGE_ACK),o}return t},e.prototype.safeExecuteHandle=function(e,t){try{return e.handleMessage(t)}catch(e){this.logger.warn(`Trouter message handler threw an exception: ${e}`);return}},e}()},634:function(e,t,n){var r=this&&this.__awaiter||function(e,t,n,r){return new(n||=Promise)((function(i,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((r=r.apply(e,t||[])).next())}))},i=this&&this.__generator||function(e,t){var n,r,i,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},o=Object.create((typeof Iterator==`function`?Iterator:Object).prototype);return o.next=s(0),o.throw=s(1),o.return=s(2),typeof Symbol==`function`&&(o[Symbol.iterator]=function(){return this}),o;function s(s){return function(c){return function(s){if(n)throw TypeError(`Generator is already executing.`);for(;o&&(o=0,s[0]&&(a=0)),a;)try{if(n=1,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,r=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((i=(i=a.trys).length>0&&i[i.length-1])||s[0]!==6&&s[0]!==2)){a=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){a.label=s[1];break}if(s[0]===6&&a.label<i[1]){a.label=i[1],i=s;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(s);break}i[2]&&a.ops.pop(),a.trys.pop();continue}s=t.call(e,a)}catch(e){s=[6,e],r=0}finally{n=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}};Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterManager=t.AudienceSubscriptionState=t.UserActivityObject=void 0;var a=n(659),o=n(234),s=n(423),c=n(642),l=n(902),u=n(235),d=n(573),f=n(335),p=n(10),m=n(509),h=function(){function e(e,t){this.state=e,this.correlationVector=t===void 0?a.CorrelationVector.extend():t}return e.prototype.getStateString=function(){switch(this.state){case o.UserActivityState.Active:return`active`;case o.UserActivityState.Inactive:return`inactive`;case o.UserActivityState.Unknown:return`unknown`;default:return`undefined`}},e.prototype.increaseCvAndGetEventObject=function(){return this.correlationVector.increase(),this.toEventObject()},e.prototype.toEventObject=function(){return{state:this.getStateString(),cv:this.correlationVector.value()}},e.prototype.toEventJSON=function(){return(0,a.toJson)(this.toEventObject())},e}();t.UserActivityObject=h;var g=function(){function e(e,t){t===void 0&&(t=a.CorrelationVector.extend()),this.subscirpitonsPerScope=e,this.correlationVector=t}return e.prototype.increaseCvAndGetEventObject=function(){return this.correlationVector.increase(),this.toEventObject()},e.prototype.toEventObject=function(){return{audiences:this.toListOfSubscriptions(),cv:this.correlationVector.value()}},e.prototype.toEventJSON=function(){return(0,a.toJson)(this.toEventObject())},e.prototype.toListOfSubscriptions=function(){for(var e=[],t=0,n=Object.keys(this.subscirpitonsPerScope);t<n.length;t++){var r=n[t];e.push.apply(e,this.subscirpitonsPerScope[r])}return e},e}();t.AudienceSubscriptionState=g;var _=`extraTransports`;t.TrouterManager=function(){function e(e,t,n,r,i,s){this.logFunc=e,this.options=t,this.tokenProvider=n,this.usingLegacyTokenApi=r,this.listener=i,this.extraTransportVersionWithinProcess=0,this.logger=new c.Logger(`Manager`,e),this.logger.info(`Created TrouterManager with options ${(0,a.toJson)(this.options)}`),this.fsm=new p.TrouterManagerFsm(e,this),this.baseEndpointUrl=``,this.processedMessageLoss={},this.userActivityObject=new h(o.UserActivityState.Unknown),this.protocolSelector=s??this.tokenTypeProtocolSelector.bind(this)}return e.prototype.start=function(){this.fsm.start()},e.prototype.stop=function(e){this.fsm.stop(e)},e.prototype.configure=function(e){this.options=e,this.firstConnection!==void 0&&this.firstConnection.configure(e),this.secondConnection!==void 0&&this.secondConnection.configure(e),this.logger.info(`Reconfigured TrouterManager with options ${(0,a.toJson)(this.options)}`)},e.prototype.checkConnection=function(e){this.firstConnection!==void 0&&this.firstConnection.checkConnection(e),this.secondConnection!==void 0&&this.secondConnection.checkConnection(e)},e.prototype.resendRegistration=function(){return r(this,void 0,void 0,(function(){return i(this,(function(e){return this.secondConnection===void 0?this.firstConnection===void 0?(this.logger.info(`No connection to resend registration on, will be done upon (re)connect`),[2]):(this.logger.info(`Resending registration on the first/current connection`),[2,this.firstConnection.resendRegistration()]):(this.logger.info(`Resending registration on the second/new connection`),[2,this.secondConnection.resendRegistration()])}))}))},e.prototype.registerExtraTransports=function(e,t){var n,r=this;this.extraTransportsState={transports:e,clientDescriptionOverride:t},this.extraTransportVersionWithinProcess++,(n=this.options.keyValueCache)==null||n.setCacheForKey(_,JSON.stringify(this.extraTransportsState)).catch((function(){r.logger.error(`Failed to store extra transports in cache`)})),this.secondConnection===void 0?this.firstConnection===void 0?this.logger.warn(`No connection to register extra transports on, will be done upon (re)connect`):(this.logger.info(`Registering extra transports ${JSON.stringify(Object.keys(e))} and ${Object.keys(t??{}).length} overridden client description properties on the first/current connection`),this.firstConnection.registerExtraTransports(e,t)):(this.logger.info(`Registering extra transports ${JSON.stringify(Object.keys(e))} and ${Object.keys(t??{}).length} overridden client description properties on the second/new connection`),this.secondConnection.registerExtraTransports(e,t))},e.prototype.getServerState=function(){if(this.firstConnection!==void 0)return this.firstConnection.getServerState()},e.prototype.getState=function(){return this.fsm.getState()},e.prototype.isInTerminalState=function(){return this.fsm.getInternalState()===s.TrouterManagerState.TerminalError},e.prototype.reportStateInfo=function(){var e=this.firstConnection?f.State[this.firstConnection.getState()]:`Unknown`,t=s.TrouterManagerState[this.fsm.getInternalState()];return this.secondConnection?`Manager ${t}; 1st ${e}; 2nd ${f.State[this.secondConnection.getState()]}`:`Manager ${t}; Connection ${e}`},e.prototype.startFirstConnection=function(){var e=this,t=new d.TrouterConnection(this.logFunc,this.options,this.configuredTrouterManager(),this.tokenProvider,this.usingLegacyTokenApi,this.userActivityObject,this.protocolSelector,this.audienceSubscriptionState);this.firstConnection=t,Promise.all([this.getConnectionCache(),this.fetchExtraTransportsCache()]).then((function(n){var r=n[0];t.start(r,e.extraTransportsState?.transports,e.extraTransportsState?.clientDescriptionOverride)})).catch((function(){e.logger.error(`unexpected error while starting first connection (wrapped cache read functions should never throw)`)}))},e.prototype.startSecondConnection=function(e){var t=this,n=new d.TrouterConnection(this.logFunc,this.options,this.configuredTrouterManager(),this.tokenProvider,this.usingLegacyTokenApi,this.userActivityObject,this.protocolSelector,this.audienceSubscriptionState);this.secondConnection=n,this.firstConnection!==void 0&&this.firstConnection.disableRegistrationsAndAutoReconnect(),e?Promise.all([this.getConnectionCache(),this.fetchExtraTransportsCache()]).then((function(e){var r=e[0];n.start(r,t.extraTransportsState?.transports,t.extraTransportsState?.clientDescriptionOverride)})).catch((function(){t.logger.error(`unexpected error while starting second connection (wrapped cache read functions should never throw)`)})):this.fetchExtraTransportsCache().then((function(){n.start(void 0,t.extraTransportsState?.transports,t.extraTransportsState?.clientDescriptionOverride)})).catch((function(){t.logger.error(`unexpected error while starting second connection (wrapped cache read functions should never throw)`)}))},e.prototype.stopFirstConnection=function(e){this.firstConnection!==void 0&&(this.storedFirstConnection=this.firstConnection,this.firstConnection.stop(e),this.firstConnection=void 0)},e.prototype.stopSecondConnection=function(e){this.secondConnection!==void 0&&(this.secondConnection.stop(e),this.secondConnection=void 0)},e.prototype.stopSecondConnectionDelayed=function(){if(this.secondConnection!==void 0){var e=this.secondConnection;this.secondConnection=void 0,this.logger.info(`Closing an inactive connection in ${Math.round(this.options.lingeringConnectionDelayMs/1e3)}s`),setTimeout((function(){e.stop(!0)}),this.options.lingeringConnectionDelayMs)}},e.prototype.forceStopLingeringConnection=function(){this.storedFirstConnection&&=(this.storedFirstConnection.stop(!1),void 0)},e.prototype.switchConnections=function(){var e=this.firstConnection;this.firstConnection=this.secondConnection,this.secondConnection=e},e.prototype.doesSecondConnectionExist=function(){return this.secondConnection!==void 0},e.prototype.dispatchConnected=function(){if(this.firstConnection!==void 0){var e=this.firstConnection.getServerState(),t=e.url.endsWith(`/`)?e.url.slice(0,-1):e.url,n={baseEndpointUrl:t,newEndpointUrl:t!==this.baseEndpointUrl,c2cUrlBase:e.c2cUrlBase,clientId:e.connectedClientId,connectionId:e.connectionId,connectionTtlSec:e.getRemainingTtlInSec()};this.baseEndpointUrl=t,this.listener.onTrouterConnected(e.url,n)}},e.prototype.dispatchDisconnected=function(){this.listener.onTrouterDisconnected&&this.listener.onTrouterDisconnected()},e.prototype.dispatchTerminalError=function(){this.listener.onTrouterDisconnected&&this.listener.onTrouterDisconnected()},e.prototype.dispatchRegistrationState=function(e){this.options.registrationStateCallback&&this.options.registrationStateCallback(e)},e.prototype.expediteBackoffOnConnections=function(){this.lastExpediteBackoffCallAt!==void 0&&Date.now()-this.lastExpediteBackoffCallAt<(this.options.expediteBackoffOnStartMinimumDelayMs??1e4)?this.logger.info(`Expedite backoff due to start() too frequent, skipping`):(this.lastExpediteBackoffCallAt=Date.now(),this.firstConnection!==void 0&&this.firstConnection.expediteBackoff(),this.secondConnection!==void 0&&this.secondConnection.expediteBackoff())},e.prototype.onDownstreamRequest=function(e,t,n){var r={id:t.id,method:t.method,path:`/${t.shortUrl}`,body:t.body,headers:t.headers},i={id:t.id,status:0,headers:{},body:``,send:function(){return i.status<=100||i.status>=999?3:(n.writeHead(i.status,i.headers),n.end(i.body))}};this.listener.onTrouterRequest(r,i)},e.prototype.onConnected=function(e){this.fsm.onConnected(e===this.firstConnection)},e.prototype.onRegistered=function(e){this.fsm.onRegistered(e===this.firstConnection)},e.prototype.onUnregistered=function(e){this.fsm.onUnregistered(e===this.firstConnection||e===this.storedFirstConnection)},e.prototype.onReconnecting=function(e){this.fsm.onReconnecting(e===this.firstConnection)},e.prototype.onReconnectIsRequired=function(e,t,n){this.fsm.onReconnectionRequired(e===this.firstConnection,t,n)},e.prototype.onDisconnected=function(e){this.fsm.onDisconnected(e===this.firstConnection||e==this.storedFirstConnection),this.storedFirstConnection=void 0},e.prototype.onTerminalError=function(){this.fsm.onTerminalError(),this.storedFirstConnection=void 0},e.prototype.onUserActivityStateAccepted=function(e){this.listener.onTrouterUserActivityStateAccepted&&this.listener.onTrouterUserActivityStateAccepted(e)},e.prototype.onAudiencesSetResolved=function(e,t){var n,r;(r=(n=this.listener).onAudiencesSetResolved)==null||r.call(n,e,t)},e.prototype.onConnectionParametersUpdated=function(e){this.setConnectionCache(e)},e.prototype.setUserActivityState=function(e,t){this.userActivityObject=new h(e,a.CorrelationVector.extend(t)),this.secondConnection===void 0?this.firstConnection!==void 0&&(this.logger.info(`Setting user activity ${this.userActivityObject.toEventJSON()} on the first/current connection`),this.firstConnection.setUserActivityState(this.userActivityObject)):(this.logger.info(`Setting user activity ${this.userActivityObject.toEventJSON()} on the second/new connection`),this.secondConnection.setUserActivityState(this.userActivityObject))},e.prototype.setAudienceSubscriptionsAsync=function(e,t,n){var r=e.scope??m.constants.SUBSCRIPTIONS_DEFAULT_SCOPE,i=this.GetUpdatedAsState(e,r);if(this.audienceSubscriptionState=new g(i,a.CorrelationVector.extend(n)),this.secondConnection)return this.logger.info(`Setting audience subscriptions ${this.audienceSubscriptionState.toEventJSON()} on second/new connection`),this.secondConnection.setAudienceSubscriptionsAsync(this.audienceSubscriptionState,t);if(this.firstConnection)return this.logger.info(`Setting audience subscriptions ${this.audienceSubscriptionState.toEventJSON()} on first/current connection`),this.firstConnection.setAudienceSubscriptionsAsync(this.audienceSubscriptionState,t);throw Error(`No connection found`)},e.prototype.GetUpdatedAsState=function(e,t){var n={};return this.audienceSubscriptionState!==void 0&&(n=structuredClone(this.audienceSubscriptionState.subscirpitonsPerScope)),n[t]=e.audienceSubscriptions,n},e.prototype.onTrouterMessageLost=function(e){var t=this;if(this.listener.onTrouterMessageLoss)if(e?.length){var n=e.filter((function(e){return t.processedMessageLoss[`${e.tag}-${e.etag}`]!==void 0}));if(n.length&&(this.logger.info(`onTrouterMessageLoss - immediately acknowledging ${n.length} seen dropped indicators`),this.sendProcessedDroppedIndicators(n),!(e=e.filter((function(e){return t.processedMessageLoss[`${e.tag}-${e.etag}`]===void 0}))).length))return void this.logger.info(`onTrouterMessageLoss - all declared dropped indicators have been seen before`);if(!this.listener.onTrouterMessageLoss(e.map((function(e){return e.tag}))))return void this.logger.warn(`onTrouterMessageLoss - some flow tag(s) have not been processed by listeners`);e.forEach((function(e){t.processedMessageLoss[`${e.tag}-${e.etag}`]=``})),this.sendProcessedDroppedIndicators(e)}else this.logger.warn(`onTrouterMessageLoss - no flow tags have been provided`)},e.prototype.getConnectionCache=function(){var e=this;return this.options.connectionCache?(this.logger.debug(`Querying host's connection cache`),this.options.connectionCache.onGetTrouterConnectionCache().then((function(e){var t=e?JSON.parse(e):void 0;return typeof t==`object`?t:void 0})).catch((function(t){return e.logger.warn(`Invalid connection cache content provided: ${t}`),e.connectionCache}))):Promise.resolve(this.connectionCache)},e.prototype.fetchExtraTransportsCache=function(){var e=this,t=this.extraTransportVersionWithinProcess;return this.options.keyValueCache&&this.extraTransportsState===void 0?this.options.keyValueCache.getCacheForKey(_).then((function(n){if(t===e.extraTransportVersionWithinProcess){if(n){var r=JSON.parse(n);typeof r==`object`&&r&&(Object.prototype.hasOwnProperty.call(r,`transports`)?e.extraTransportsState=r:e.extraTransportsState={transports:r,clientDescriptionOverride:void 0}),e.extraTransportVersionWithinProcess++}}else e.logger.info(`Extra transports cache was updated while fetching it, returning the current state`)})).catch((function(){e.logger.error(`Failed to retrieve extra transports from cache`)})):Promise.resolve()},e.prototype.setConnectionCache=function(e){if(this.connectionCache=e,this.options.connectionCache)try{this.options.connectionCache.onSetTrouterConnectionCache(JSON.stringify(e))}catch(e){this.logger.warn(`Error setting external connection cache: ${e}`)}},e.prototype.sendProcessedDroppedIndicators=function(e){this.firstConnection===void 0?this.secondConnection===void 0||this.secondConnection.sendProcessedDroppedIndicators(e):this.firstConnection.sendProcessedDroppedIndicators(e)},e.prototype.configuredTrouterManager=function(){return new u.RegistrationEnforcer(this,this.options.connectionDependsOnRegistration,this.options.delayEventsUntilRegistered)},e.prototype.tokenTypeProtocolSelector=function(e,t){return this.options.forceV4aProtocol||this.options.forceV4aProtocolForSkypetoken&&e===`skype`&&(0,l.safeToString)(t?.scae)!==`1`?`v4a`:`v4c`},e}()},642:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Logger=void 0,t.Logger=function(){function e(e,t){this.name=e,this.logger=t}return e.prototype.debug=function(e){this.logger.debug(`[${this.name}] ${e}`)},e.prototype.info=function(e){this.logger.info(`[${this.name}] ${e}`)},e.prototype.warn=function(e){this.logger.warn(`[${this.name}] ${e}`)},e.prototype.error=function(e){this.logger.error(`[${this.name}] ${e}`)},e}()},659:function(e,t){var n=this&&this.__awaiter||function(e,t,n,r){return new(n||=Promise)((function(i,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((r=r.apply(e,t||[])).next())}))},r=this&&this.__generator||function(e,t){var n,r,i,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},o=Object.create((typeof Iterator==`function`?Iterator:Object).prototype);return o.next=s(0),o.throw=s(1),o.return=s(2),typeof Symbol==`function`&&(o[Symbol.iterator]=function(){return this}),o;function s(s){return function(c){return function(s){if(n)throw TypeError(`Generator is already executing.`);for(;o&&(o=0,s[0]&&(a=0)),a;)try{if(n=1,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,r=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((i=(i=a.trys).length>0&&i[i.length-1])||s[0]!==6&&s[0]!==2)){a=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){a.label=s[1];break}if(s[0]===6&&a.label<i[1]){a.label=i[1],i=s;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(s);break}i[2]&&a.ops.pop(),a.trys.pop();continue}s=t.call(e,a)}catch(e){s=[6,e],r=0}finally{n=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}};function i(e){try{return JSON.stringify(e)}catch{return`Unable to serialize object of type ${typeof e}`}}Object.defineProperty(t,"__esModule",{value:!0}),t.Timespan=t.CorrelationVector=void 0,t.toJson=i,t.anonymizeShortUrl=function(e){var t=/^(TeamsUnifiedPresenceService|acceptance|addParticipant\w*|balanceUpdate|call(Agent)?|controlVideoStreaming|conversation\w*|dominantSpeakerInfo|end|join|media\w*|messaging|progress|rejection|retargetCompletion|rosterUpdate|update|ups)$/i;return e.split(`/`).map((function(e){return!e||t.test(e)||e.length<3?e:`${e.slice(0,2)}...`})).join(`/`)},t.headersToLog=function(e){for(var t=/^(Host|User-Agent|Content-Length|Content-Type|X-Microsoft-Skype-\S+|(X-)?Trouter.*|X-CallingProxy|MS-CV|traceparent|Priority)$/i,n={},r=0,a=Object.keys(e);r<a.length;r++){var o=a[r];t.test(o)&&(n[o]=e[o])}return i(n)},t.calculateTtlInSec=function(e){var t=Math.round(new Date().getTime()/1e3);return e!==void 0&&e>t?e-t:0},t.calculateExpireTsInSec=function(e){return Math.round(new Date().getTime()/1e3)+e},t.fetchWithTimeout=function(e,t){return n(this,void 0,void 0,(function(){var n,i,a;return r(this,(function(r){return i=new Promise((function(t,r){fetch(e).then((function(e){clearTimeout(n),t(e)})).catch((function(e){clearTimeout(n),r(e)}))})),t===0?[2,i]:(a=new Promise((function(r,i){var a=new URL(e.url),o=Error(`${e.method} ${a.origin}${a.pathname} timed out`);n=setTimeout(i,t,o)})),[2,Promise.race([i,a])])}))}))},t.CorrelationVector=function(){function e(e){this.base=e===void 0?this.createCorrelationVectorBase():e,this.extension=0}return e.extend=function(t){return new e(t)},e.prototype.increase=function(){this.extension++},e.prototype.value=function(){return`${this.base}.${this.extension}`},e.prototype.createCorrelationVectorBase=function(){for(var e=``,t=0;t<21;t++)e+=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0987654321/+`.charAt(Math.floor(64*Math.random()));return e+`AQgw`.charAt(Math.floor(4*Math.random()))},e}(),t.Timespan=function(){function e(){this.start=Date.now()}return Object.defineProperty(e.prototype,"duration",{get:function(){return Date.now()-this.start},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"startTime",{get:function(){return this.start},enumerable:!1,configurable:!0}),e.prototype.reset=function(){this.start=Date.now()},e}()},673:t=>{t.exports=e},705:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.updateAudienceSubscriptionQuery=function(e,t){return e.replace(/([?&]audienceSubscriptionState=)[^&]*/,`\$1${t}`)}},764:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DisconnectReason=void 0,t.DisconnectReason=function(){function e(e,t,n){this.reason=e,this.claims=t,this.details=n}return e.fromRawReason=function(t,n){if(t===``||t===`dup`)return new e(t);try{var r=JSON.parse(t);return typeof r!=`object`||r.reason===void 0?(n?.error(`invalid disconnect reason format`),new e(`unknown`,void 0,t)):new e(r.reason,r.claims,r.details)}catch{return new e(`disconnect`,void 0,t)}},e.fromSocketIoEventData=function(t,n){return typeof n==`string`?new e(t,void 0,n):void 0},e.prototype.toTelemetryString=function(){return this.reason===`socketerror`||this.reason===`reconnecterror`||this.reason===`disconnect`?this.details:this.reason},e}()},882:function(e,t,n){var r=this&&this.__assign||function(){return r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},r.apply(this,arguments)},i=this&&this.__awaiter||function(e,t,n,r){return new(n||=Promise)((function(i,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((r=r.apply(e,t||[])).next())}))},a=this&&this.__generator||function(e,t){var n,r,i,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},o=Object.create((typeof Iterator==`function`?Iterator:Object).prototype);return o.next=s(0),o.throw=s(1),o.return=s(2),typeof Symbol==`function`&&(o[Symbol.iterator]=function(){return this}),o;function s(s){return function(c){return function(s){if(n)throw TypeError(`Generator is already executing.`);for(;o&&(o=0,s[0]&&(a=0)),a;)try{if(n=1,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,r=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((i=(i=a.trys).length>0&&i[i.length-1])||s[0]!==6&&s[0]!==2)){a=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){a.label=s[1];break}if(s[0]===6&&a.label<i[1]){a.label=i[1],i=s;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(s);break}i[2]&&a.ops.pop(),a.trys.pop();continue}s=t.call(e,a)}catch(e){s=[6,e],r=0}finally{n=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}};Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterService=t.UserActivityState=t.TrouterState=void 0,t.createTrouterService=function(e){return new h(e)},t.getTrouterServiceVersion=function(){return o.CLIENT_VERSION},t.replaceTrouterUrlBase=function(e,t){var n=e.indexOf(`://`);if(n>=0){var r=e.indexOf(`/`,n+3);if(r>=0)return t+e.substr(r)}return``};var o=n(509),s=n(234);Object.defineProperty(t,"TrouterState",{enumerable:!0,get:function(){return s.TrouterState}}),Object.defineProperty(t,"UserActivityState",{enumerable:!0,get:function(){return s.UserActivityState}});var c=n(642),l=n(619),u=n(220),d=n(634),f=n(616);function p(e,t){if(!t)return e;var n=r(r({},e),{enabled:t.TelemetryEnabled});return t.ClientTelemetryEventEnabled!==void 0&&(n=r(r({},n),t.ClientTelemetryEventEnabled)),n}function m(e,t,n){var i,a,o,s=function(n){return e.proxyUrlRewrite?(t.info(`Using rewritten URL for proxy`),e.proxyUrlRewrite(n)):n};return{clientInfo:{ua:e.trouterSettings.productName,v:e.trouterSettings.version},ioOptions:{ackTimeoutMs:5e3,rewriteUrlForProxy:s},clientCorrelationID:e.trouterSettings.sessionId,environment:e.trouterSettings.environment,telemetrySettings:p(e.telemetryConfig.settings,n),eventLogger:e.telemetryConfig.eventLogger,endpointId:e.trouterSettings.registrationId,trouterUrl:n?.TrouterConnectionUrl||e.trouterSettings.trouterServiceUrl,registration:e.trouterSettings.registrarServiceUrl||e.trouterSettings.useRegistrarUrlFromAllocate?{registrarUrl:e.trouterSettings.registrarServiceUrl??``,useRegistrarUrlFromAllocate:(i=e.trouterSettings.useRegistrarUrlFromAllocate)!=null&&i,registrationId:e.trouterSettings.registrationId??``,pnhAppId:e.trouterSettings.pnhAppId??``,platform:e.trouterSettings.platform??``,pnhTemplateKey:e.trouterSettings.pnhTemplate??``,platformUIVersion:e.trouterSettings.platformUIVersion??``,productContext:e.trouterSettings.pnhProductContext||void 0,context:e.trouterSettings.pnhContext??``,registrarTtlSec:(e.trouterSettings.maxRegistrationTimeInMs??0)/1e3}:void 0,connectionDependsOnRegistration:e.trouterSettings.registrarServiceUrl===void 0?function(){return!1}:e.trouterSettings.connectionDependsOnRegistration??function(){return!1},delayEventsUntilRegistered:e.trouterSettings.delayEventsUntilRegistered??function(){return!1},timeoutOptions:r({connectionTimeoutMs:e.trouterSettings.trouterConnectTimeoutInMs||3e4,fetchTimeoutMs:1e4,pingTimeoutMs:4e4,pongTimeoutMs:5e3,maxBackoffMs:e.trouterSettings.productName===`TeamsCDL`?3e5:3e4,requestTimeoutMs:5e3,userActivityResponseTimeoutMs:1e4},e.trouterSettings.timeoutOptions),incallTimeoutOptions:r({connectionTimeoutMs:1e4,fetchTimeoutMs:5e3,pingTimeoutMs:5e3,pongTimeoutMs:2e3,maxBackoffMs:e.trouterSettings.productName===`TeamsCDL`?3e5:1e4,requestTimeoutMs:5e3,userActivityResponseTimeoutMs:1e4},e.trouterSettings.incallTimeoutOptions),incallModeTimeoutMs:e.trouterSettings.incallModeTimeoutMs??0,lingeringConnectionDelayMs:6e4,userActivitySecondResendDelayMs:e.trouterSettings.userActivitySecondResendDelayMs||1e4,duplicateDisconnectThresholdMs:1e4,connectionCache:e.connectionCache,keyValueCache:e.keyValueCache,registrationStateCallback:e.registrationStateCallbackForAcsDoNotUse,rewriteUrlForProxy:s,retryLimitOnTokenFetch:e.trouterSettings.retryLimitOnTokenFetch,extraConnectionHeaders:e.trouterSettings.extraConnectionHeaders,expediteBackoffOnStartMinimumDelayMs:1e4,updateUserActivityDuringConnectionAttempt:(a=e.trouterSettings.updateUserActivityDuringConnectionAttempt)==null||a,initialConnectivityCheck:(o=e.trouterSettings.initialConnectivityCheck)==null||o,toJSON:function(){return r(r({},this),{connectionCache:this.connectionCache?{}:this.connectionCache,keyValueCache:this.keyValueCache?{}:this.keyValueCache})}}}var h=function(){function e(e){this.logProvider=e,this.stateChangedListeners=[],this.logger=new c.Logger(`Trouter`,e),this.trouterUrlPromise=new f.TrouterUrlPromise(e),this.messageHandlers=new l.MessageHandlerRegistry(e),this.listeners={},this.connectionInfo=null,this.logger.info(`Created TrouterService version ${o.CLIENT_VERSION}`)}return e.prototype.start=function(e){if(this.logger.info(`Start`),!e.skypeTokenProvider&&!e.authTokenProvider)throw Error(`no token provider has been configured, either skypeTokenProvider or authTokenProvider must be populated`);e.skypeTokenProvider&&!e.trouterSettings.disableInternalSkypeTokenCache&&(e.skypeTokenProvider=(0,u.addCacheAsBackupTo)(e.skypeTokenProvider)),this.trouterCfg=e;var t=m(e,this.logger,this.ecsCfg);!1===e.internalEnableV4cProtocol&&(t.forceV4aProtocol=!0),!1===e.internalUseV4aForSkypetoken&&(t.forceV4aProtocolForSkypetoken=!0);var n=function(e,t){var n,r=this;return function(o){return i(r,void 0,void 0,(function(){var r,i,s;return a(this,(function(a){switch(a.label){case 0:r=new Date,i=setInterval((function(){var t=Math.round((Date.now()-r.getTime())/6e4);e.warn(`Note: Trouter auth token request promise from ${r.toISOString()} has not been resolved for ${t} minutes. The client is blocked from operating properly`)}),3e5),a.label=1;case 1:return a.trys.push([1,,3,4]),[4,t(o)];case 2:return s=a.sent(),o.needFresh&&s.token===n&&e.error(`API violation: Trouter auth token provider got a request with needRefresh=true, but returned the same token as last time anyway. Please fix the host app`),n=s.token,[2,s];case 3:return clearInterval(i),[7];case 4:return[2]}}))}))}}(this.logger,e.authTokenProvider??function(e){var t=this;return function(n){return i(t,void 0,void 0,(function(){var t;return a(this,(function(r){switch(r.label){case 0:return t={},[4,e(n.needFresh)];case 1:return[2,(t.token=r.sent(),t.tokenType=`skype`,t)]}}))}))}}(e.skypeTokenProvider));this.trouterServer===void 0&&(this.trouterServer=new d.TrouterManager(this.logProvider,t,n,e.authTokenProvider===void 0,this)),this.pendingActivityState!==void 0&&(this.trouterServer.setUserActivityState(this.pendingActivityState[0],this.pendingActivityState[1]),this.pendingActivityState=void 0),this.pendingExtraTransports!==void 0&&(this.trouterServer.registerExtraTransports(this.pendingExtraTransports.transports,this.pendingExtraTransports.clientDescriptionOverride),this.pendingExtraTransports=void 0),this.trouterServer.start()},e.prototype.stop=function(e){this.logger.info(`close connection`),this.trouterUrlPromise.rejectUrl(Error(`TrouterService is stopped`)),this.trouterServer!==void 0&&this.trouterServer.stop(e)},e.prototype.setEcsConfig=function(e){return i(this,void 0,void 0,(function(){var t=this;return a(this,(function(n){return[2,new Promise((function(n){if(t.ecsCfg=e.TrouterJScriptClient,t.logger.info(`Setting ECS configuration to ${JSON.stringify(t.ecsCfg)}`),t.trouterServer!==void 0&&t.trouterCfg!==void 0){var r=m(t.trouterCfg,t.logger,t.ecsCfg);t.trouterServer.configure(r)}n()}))]}))}))},e.prototype.checkConnection=function(e){this.trouterServer!==void 0&&this.trouterServer.checkConnection(e!=null&&e)},e.prototype.resendRegistration=function(){return i(this,void 0,void 0,(function(){return a(this,(function(e){if(!this.trouterServer)throw Error(`resendRegistration called too early`);return[2,this.trouterServer.resendRegistration()]}))}))},e.prototype.registerExtraTransports=function(e,t){if(this.trouterServer===void 0)return this.pendingExtraTransports={transports:e,clientDescriptionOverride:t},void this.logger.warn(`registerExtraTransports called before start()`);this.logger.info(`registerExtraTransports called`),this.pendingExtraTransports=void 0,this.trouterServer.registerExtraTransports(e,t)},e.prototype.registerListener=function(e,t){return t===``||!t.startsWith(`/`)||t.includes(`?`)||t.includes(`#`)?(this.logger.error(`Listener path '${t}' is not valid`),!1):this.listeners[t]?(this.logger.error(`Another listener is already registered for path '${t}'`),!1):(this.listeners[t]=e,this.logger.debug(`Listener for path '${t}' registered`),this.connectionInfo&&e.onTrouterConnected(this.connectionInfo.baseEndpointUrl+t,this.connectionInfo),!0)},e.prototype.unregisterListener=function(e){for(var t=[],n=0,r=Object.keys(this.listeners);n<r.length;n++){var i=r[n];this.listeners[i]===e&&t.push(i)}if(t.length===0)return!1;for(var a=0,o=t;a<o.length;a++)i=o[a],delete this.listeners[i];return this.logger.debug(`Listener for path(s) '${t.join(`', '`)}' unregistered`),!0},e.prototype.onTrouterConnected=function(e,t){this.logger.debug(`Trouter is now connected`);for(var n=0,r=Object.keys(this.listeners);n<r.length;n++){var i=r[n];try{this.listeners[i].onTrouterConnected(t.baseEndpointUrl+i,t)}catch(e){this.logger.error(`Listener '${i}' threw an exception from onTrouterConnected(): ${e}`)}}this.connectionInfo=t,this.trouterUrlPromise.resolveUrl(e),this.notifyStateChanged(s.TrouterState.Connected,{url:e,getRemainingTtlInSec:function(){return t.connectionTtlSec}})},e.prototype.onTrouterDisconnected=function(){this.logger.debug(`Trouter is now disconnected`),this.connectionInfo=null;for(var e=0,t=Object.keys(this.listeners);e<t.length;e++){var n=t[e],r=this.listeners[n];if(r.onTrouterDisconnected)try{r.onTrouterDisconnected()}catch(e){this.logger.error(`Listener '${n}' threw an exception from onTrouterDisconnected(): ${e}`)}}this.notifyStateChanged(s.TrouterState.Disconnected)},e.prototype.onTrouterRequest=function(e,t){for(var n=``,r=0,i=Object.keys(this.listeners);r<i.length;r++){var a=i[r];e.path.startsWith(a)&&a.length>n.length&&(n=a)}if(n===``)this.tryMessageHandlers(e,t)||(t.status=404,t.headers={"Trouter-Responder":`ClientLib`},t.send());else try{this.listeners[n].onTrouterRequest(e,t)}catch(e){this.logger.error(`Listener '${n}' threw an exception from onTrouterRequest(): ${e}`),t.status=500,t.headers={"Trouter-Responder":`ClientLib`},t.send()}},e.prototype.onTrouterMessageLoss=function(e){this.logger.info(`onTrouterMessageLoss called with tags [${e}]`);for(var t=!0,n=0,r=Object.keys(this.listeners);n<r.length;n++){var i=r[n],a=this.listeners[i];if(a.onTrouterMessageLoss)try{(t=a.onTrouterMessageLoss(e)&&t)===void 0&&(this.logger.error(`Listener '${i}' did not return a boolean value from onTrouterMessageLoss()`),t=!1)}catch(e){this.logger.error(`Listener '${i}' threw an exception from onTrouterMessageLoss(): ${e}`),t=!1}}return t},e.prototype.onTrouterUserActivityStateAccepted=function(e){this.logger.debug(`onTrouterUserActivityStateAccepted cv: ${e}`);for(var t=0,n=Object.keys(this.listeners);t<n.length;t++){var r=n[t],i=this.listeners[r];if(i.onTrouterUserActivityStateAccepted)try{i.onTrouterUserActivityStateAccepted(e)}catch(e){this.logger.error(`Listener '${r}' threw an exception from onTrouterUserActivityStateAccepted(): ${e}`)}}},e.prototype.onAudiencesSetResolved=function(e,t){this.logger.debug(`onAudiencesSetResolved cv: ${t}`);for(var n=0,r=Object.keys(this.listeners);n<r.length;n++){var i=r[n],a=this.listeners[i];if(a.onAudiencesSetResolved)try{a.onAudiencesSetResolved(e,t)}catch(e){this.logger.error(`Listener '${i}' threw an exception from onAudienceSubscribed(): ${e}`)}}},e.prototype.setUserActivityState=function(e,t){if(e!==s.UserActivityState.Active&&e!==s.UserActivityState.Inactive)throw Error(`setUserActivityState called with unsupported value ${e}`);this.logger.info(`setUserActivityState called with value ${s.UserActivityState[e]}`),this.trouterServer&&this.state()!==s.TrouterState.Unknown?this.trouterServer.setUserActivityState(e,t):(this.pendingActivityState=[e,t],this.logger.warn(`setUserActivityState called before start() or after stop()`))},e.prototype.setAudienceSubscriptions=function(e,t){if(this.trouterServer&&this.state()!==s.TrouterState.Unknown)return this.trouterServer.setAudienceSubscriptionsAsync(e,15e3,t);throw Error(`audience subscribe called before start() or after stop()`)},e.prototype.state=function(){return this.trouterServer===void 0?s.TrouterState.Unknown:this.trouterServer.getState()},e.prototype.isInTerminalState=function(){return this.trouterServer!==void 0&&this.trouterServer.isInTerminalState()},e.prototype.reportStateInfo=function(){return this.trouterServer===void 0?``:this.trouterServer.reportStateInfo()},e.prototype.getServerState=function(){if(this.trouterServer!==void 0)return this.trouterServer.getServerState()},e.prototype.getTrouterUrlAsync=function(){return this.trouterServer===void 0?Promise.reject(Error(`TrouterService has not been started`)):this.trouterUrlPromise.getPromise()},e.prototype.onStateChanged=function(e){if(this.logger.info(`onStateChanged called`),e===void 0)this.stateChangedListeners=this.stateChangedListeners.filter((function(e){return e.wrappedCallback===void 0}));else{this.offStateChanged(e);var t=function(t,n){e(t,n?n.url:``)};t.wrappedCallback=e,this.stateChangedListeners.push(t)}},e.prototype.offStateChanged=function(e){this.logger.info(`offStateChanged called`);var t=this.stateChangedListeners.length;return this.stateChangedListeners=this.stateChangedListeners.filter((function(t){return t.wrappedCallback!==e})),t>this.stateChangedListeners.length},e.prototype.addCallback=function(e){this.logger.info(`addListener called`),this.stateChangedListeners.indexOf(e,0)===-1&&e!==void 0&&this.stateChangedListeners.push(e)},e.prototype.removeCallback=function(e){this.logger.info(`removeListener called`);var t=this.stateChangedListeners.indexOf(e,0);return t>-1&&(this.stateChangedListeners.splice(t,1),!0)},e.prototype.registerMessageHandler=function(e){this.logger.info(`registerMessageHandler is called`),this.messageHandlers.register(e)},e.prototype.clearMessageHandlers=function(){this.logger.info(`clearMessageHandlers is called`),this.messageHandlers.clear()},e.prototype.notifyStateChanged=function(e,t){var n=this;this.logger.info(`notifyStateChanged called, will forward to ${this.stateChangedListeners.length} listeners`),this.stateChangedListeners.forEach((function(r){try{r(e,t)}catch(e){n.logger.error(`Error in callback ${e}`)}}))},e.prototype.tryMessageHandlers=function(e,t){if(!this.messageHandlers.active())return!1;var n,r=null;try{r=(n=JSON.parse(e.body))&&(n.evt||n.eventId)||null}catch{}var i={eventId:r,url:(this.connectionInfo?this.connectionInfo.baseEndpointUrl:``)+e.path,body:n,rawBody:e.body,headers:e.headers},a=this.messageHandlers.handleMessage(i);return!!a.isHandled&&(t.status=a.resultCode,a.responseHeaders&&(t.headers=a.responseHeaders),a.responseBody&&(t.body=a.responseBody),t.send(),!0)},e}();t.TrouterService=h},902:function(e,t){var n=this&&this.__assign||function(){return n=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},n.apply(this,arguments)};Object.defineProperty(t,"__esModule",{value:!0}),t.safeToString=function(e){return typeof e==`string`?e:typeof e==`number`?e.toString():void 0},t.usedProtocolAfterFallback=function(e,t){return t?.kind===`v4c-websocket-failure`?`v4a`:e},t.isV4ConnectEvent=function(e){return Object.prototype.hasOwnProperty.call(e,`connectparams`)},t.adaptUrl=function(e,t){return t===`v4a`?e.replace(/\/v4\/c\b/,`/v4/a`).replace(`wss://`,`https://`).replace(`ws://`,`http://`):e.replace(/\/v4\/a\b/,`/v4/c`).replace(`https://`,`wss://`).replace(`http://`,`ws://`)},t.reconnectParamsWithoutUrls=function(e){if(e!==void 0)return n(n({},e),{reconnectUrl:void 0,serviceUrl:void 0})},t.ensureNumber=function(e){return typeof e==`string`?parseInt(e,10):e},t.redirectUrlIfPresent=function(e){if(e?.kind===`redirect`&&e.host!==void 0){var t=e.host;return t.endsWith(`/`)&&(t=t.substring(0,t.length-1)),t.endsWith(`/v4/c`)||t.endsWith(`/v4/a`)||(t+=`/v4/c`),t}}},983:(e,t,n)=>{(function(e,t){var n=e;n.version=`0.9.6`,n.protocol=1,n.transports=[],n.j=[],n.sockets={},n.connect=function(e,r){var i,a,o=n.util.parseUri(e);t&&t.location&&(o.protocol=o.protocol||t.location.protocol.slice(0,-1),o.host=o.host||(t.document?t.document.domain:t.location.hostname),o.port=o.port||t.location.port),i=n.util.uniqueUri(o);var s={host:o.host,secure:o.protocol==`https`,port:o.port||(o.protocol==`https`?443:80),query:o.query||``};return n.util.merge(s,r),!s[`force new connection`]&&n.sockets[i]||(a=new n.Socket(s)),!s[`force new connection`]&&a&&(n.sockets[i]=a),a||=n.sockets[i],s[`skipped handshake data`]?a.of(``):a.of(o.path.length>1?o.path:``)}})((e=n.nmd(e)).exports,OG===void 0?window:OG);var r=e.exports;(function(e,t){var n=e.util={},r=/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,i=[`source`,`protocol`,`authority`,`userInfo`,`user`,`password`,`host`,`port`,`relative`,`path`,`directory`,`file`,`query`,`anchor`];n.parseUri=function(e){for(var t=r.exec(e||``),n={},a=14;a--;)n[i[a]]=t[a]||``;return n},n.uniqueUri=function(e){var n=e.protocol,r=e.host,i=e.port;return`document`in t?(r||=document.domain,i||=n==`https`&&document.location.protocol!==`https:`?443:document.location.port):(r||=`localhost`,i||n!=`https`||(i=443)),(n||`http`)+`://`+r+`:`+(i||80)},n.query=function(e,t){var r=n.chunkQuery(e||``),i=[];for(var a in n.merge(r,n.chunkQuery(t||``)),r)r.hasOwnProperty(a)&&i.push(a+`=`+r[a]);return i.length?`?`+i.join(`&`):``},n.chunkQuery=function(e){for(var t,n={},r=e.split(`&`),i=0,a=r.length;i<a;++i)(t=r[i].split(`=`))[0]&&(n[t[0]]=t[1]);return n};var a=!1;n.load=function(e){if(`document`in t&&document.readyState===`complete`||a)return e();n.on(t,`load`,e,!1)},n.on=function(e,t,n,r){e.attachEvent?e.attachEvent(`on`+t,n):e.addEventListener&&e.addEventListener(t,n,r)},n.request=function(e){if(e&&typeof XDomainRequest<`u`)return new XDomainRequest;if(typeof XMLHttpRequest<`u`&&(!e||n.ua.hasCORS))return new XMLHttpRequest;if(!e)try{return new window[[`Active`,`Object`].join(`X`)](`Microsoft.XMLHTTP`)}catch{}return null},typeof window<`u`&&n.load((function(){a=!0})),n.defer=function(e){if(!n.ua.webkit||typeof importScripts<`u`)return e();n.load((function(){setTimeout(e,100)}))},n.merge=function(e,t,r,i){var a,o=i||[],s=r===void 0?2:r;for(a in t)t.hasOwnProperty(a)&&n.indexOf(o,a)<0&&(typeof e[a]==`object`&&s?n.merge(e[a],t[a],s-1,o):(e[a]=t[a],o.push(t[a])));return e},n.mixin=function(e,t){n.merge(e.prototype,t.prototype)},n.inherit=function(e,t){function n(){}n.prototype=t.prototype,e.prototype=new n},n.isArray=Array.isArray||function(e){return Object.prototype.toString.call(e)===`[object Array]`},n.intersect=function(e,t){for(var r=[],i=e.length>t.length?e:t,a=e.length>t.length?t:e,o=0,s=a.length;o<s;o++)~n.indexOf(i,a[o])&&r.push(a[o]);return r},n.indexOf=function(e,t,n){var r=e.length;for(n=n<0?n+r<0?0:n+r:n||0;n<r&&e[n]!==t;n++);return r<=n?-1:n},n.toArray=function(e){for(var t=[],n=0,r=e.length;n<r;n++)t.push(e[n]);return t},n.ua={},n.ua.hasCORS=typeof XMLHttpRequest<`u`&&function(){try{var e=new XMLHttpRequest}catch{return!1}return e.withCredentials!=null}(),n.ua.webkit=typeof navigator<`u`&&/webkit/i.test(navigator.userAgent)})(r===void 0?e.exports:r,OG===void 0?window:OG),function(e,t){function n(){}e.EventEmitter=n,n.prototype.on=function(e,n){return this.$events||={},this.$events[e]?t.util.isArray(this.$events[e])?this.$events[e].push(n):this.$events[e]=[this.$events[e],n]:this.$events[e]=n,this},n.prototype.addListener=n.prototype.on,n.prototype.once=function(e,t){var n=this;function r(){n.removeListener(e,r),t.apply(this,arguments)}return r.listener=t,this.on(e,r),this},n.prototype.removeListener=function(e,n){if(this.$events&&this.$events[e]){var r=this.$events[e];if(t.util.isArray(r)){for(var i=-1,a=0,o=r.length;a<o;a++)if(r[a]===n||r[a].listener&&r[a].listener===n){i=a;break}if(i<0)return this;r.splice(i,1),r.length||delete this.$events[e]}else (r===n||r.listener&&r.listener===n)&&delete this.$events[e]}return this},n.prototype.removeAllListeners=function(e){return this.$events&&this.$events[e]&&(this.$events[e]=null),this},n.prototype.listeners=function(e){return this.$events||={},this.$events[e]||(this.$events[e]=[]),t.util.isArray(this.$events[e])||(this.$events[e]=[this.$events[e]]),this.$events[e]},n.prototype.emit=function(e){if(!this.$events)return!1;var n=this.$events[e];if(!n)return!1;var r=Array.prototype.slice.call(arguments,1);if(typeof n==`function`)n.apply(this,r);else{if(!t.util.isArray(n))return!1;for(var i=n.slice(),a=0,o=i.length;a<o;a++)i[a].apply(this,r)}return!0}}(r===void 0?e.exports:r,r===void 0?e.parent.exports:r),function(e,t){if(t&&t.parse)return e.JSON={parse:t.parse,stringify:t.stringify};throw Error(`JSON not available`)}(r===void 0?e.exports:r,typeof JSON<`u`?JSON:void 0),function(e,t){var n=e.parser={},r=n.packets=[`disconnect`,`connect`,`heartbeat`,`message`,`json`,`event`,`ack`,`error`,`noop`],i=n.reasons=[`transport not supported`,`client not handshaken`,`unauthorized`],a=n.advice=[`reconnect`],o=t.JSON,s=t.util.indexOf;n.encodePacket=function(e){var t=s(r,e.type),n=e.id||``,c=e.endpoint||``,l=e.ack,u=null;switch(e.type){case`error`:var d=e.reason?s(i,e.reason):``,f=e.advice?s(a,e.advice):``;d===``&&f===``||(u=d+(f===``?``:`+`+f));break;case`message`:e.data!==``&&(u=e.data);break;case`event`:var p={name:e.name};e.args&&e.args.length&&(p.args=e.args),u=o.stringify(p);break;case`json`:u=o.stringify(e.data);break;case`connect`:e.qs&&(u=e.qs);break;case`ack`:u=e.ackId+(e.args&&e.args.length?`+`+o.stringify(e.args):``)}var m=[t,n+(l==`data`?`+`:``),c];return u!=null&&m.push(u),m.join(`:`)},n.encodePayload=function(e){var t=``;if(e.length==1)return e[0];for(var n=0,r=e.length;n<r;n++)t+=`�`+e[n].length+`�`+e[n];return t};var c=/([^:]+):([0-9]+)?(\+)?:([^:]+)?:?([\s\S]*)?/;n.decodePacket=function(e){if(!(s=e.match(c)))return{};var t=s[2]||``,n=(e=s[5]||``,{type:r[s[1]],endpoint:s[4]||``});switch(t&&(n.id=t,s[3]?n.ack=`data`:n.ack=!0),n.type){case`error`:var s=e.split(`+`);n.reason=i[s[0]]||``,n.advice=a[s[1]]||``;break;case`message`:n.data=e||``;break;case`event`:try{var l=o.parse(e);n.name=l.name,n.args=l.args}catch{}n.args=n.args||[];break;case`json`:try{n.data=o.parse(e)}catch{}break;case`connect`:n.qs=e||``;break;case`ack`:if((s=e.match(/^([0-9]+)(\+)?(.*)/))&&(n.ackId=s[1],n.args=[],s[3]))try{n.args=s[3]?o.parse(s[3]):[]}catch{}break;case`disconnect`:n.reason=e}return n},n.decodePayload=function(e){if(e.charAt(0)==`�`){for(var t=[],r=1,i=``;r<e.length;r++)e.charAt(r)==`�`?(t.push(n.decodePacket(e.substr(r+1).substr(0,i))),r+=Number(i)+1,i=``):i+=e.charAt(r);return t}return[n.decodePacket(e)]}}(r===void 0?e.exports:r,r===void 0?e.parent.exports:r),function(e,t){function n(e,t){this.socket=e,this.sessid=t,this.connectErrorCallback=void 0,this.isOpened=!1}e.Transport=n,t.util.mixin(n,t.EventEmitter),n.prototype.onData=function(e){if(this.clearCloseTimeout(),(this.socket.connected||this.socket.connecting||this.socket.reconnecting)&&this.setCloseTimeout(),e!==``){var n=t.parser.decodePayload(e);if(n&&n.length)for(var r=0,i=n.length;r<i;r++)this.onPacket(n[r])}return this},n.prototype.onPacket=function(e){return this.socket.setHeartbeatTimeout(),e.type==`heartbeat`?this.onHeartbeat():(e.type==`connect`&&e.endpoint==``&&this.onConnect(),e.type==`error`&&e.advice==`reconnect`&&(this.isOpened=!1),this.socket.onPacket(e),this)},n.prototype.setCloseTimeout=function(){if(!this.closeTimeout){var e=this;this.closeTimeout=setTimeout((function(){e.onDisconnect()}),this.socket.closeTimeout)}},n.prototype.onDisconnect=function(){return this.close&&this.isOpened&&this.close(),this.clearTimeouts(),this.socket.onDisconnect(),this},n.prototype.onConnect=function(){return this.socket.onConnect(),this.connectErrorCallback=void 0,this},n.prototype.clearCloseTimeout=function(){this.closeTimeout&&=(clearTimeout(this.closeTimeout),null)},n.prototype.clearTimeouts=function(){this.clearCloseTimeout(),this.reopenTimeout&&clearTimeout(this.reopenTimeout)},n.prototype.packet=function(e){this.send(t.parser.encodePacket(e))},n.prototype.onHeartbeat=function(e){this.packet({type:`heartbeat`})},n.prototype.onOpen=function(){this.isOpened=!0,this.clearCloseTimeout(),this.socket.onOpen()},n.prototype.onClose=function(){this.isOpened=!1,this.socket.onClose(),this.onDisconnect()},n.prototype.prepareUrl=function(e){var n=this.socket.options;if(n[`skipped handshake data`])return n.rewriteUrlForProxy(n[`skipped handshake data`].websocketUrl+(e||``));var r=this.scheme()+`://`+n.host+`:`+n.port+`/`+n.resource+`/`+t.protocol+`/`+this.name+`/`+this.sessid+(e||``);return n.rewriteUrlForProxy(r)},n.prototype.ready=function(e,t){t.call(this)},n.prototype.clearEventHandlers=function(){return this}}(r===void 0?e.exports:r,r===void 0?e.parent.exports:r),function(e,t,n){function r(e){if(this.options={port:80,secure:!1,document:`document`in n&&document,resource:`socket.io`,transports:t.transports.slice(),"connect timeout":1e4,"try multiple transports":!0,reconnect:!0,"reconnection delay":500,"reconnection limit":1/0,"reopen delay":3e3,"max reconnection attempts":10,"sync disconnect on unload":!0,"auto connect":!0,"flash policy port":10843},t.util.merge(this.options,e),this.connected=!1,this.open=!1,this.connecting=!1,this.reconnecting=!1,this.namespaces={},this.buffer=[],this.doBuffer=!1,this.disconnected=!1,this.options[`sync disconnect on unload`]&&(!this.isXDomain()||t.util.ua.hasCORS)){var r=this;t.util.on(n,`unload`,(function(){r.disconnectSync()}),!1)}this.options[`auto connect`]&&this.connect()}function i(){}e.Socket=r,t.util.mixin(r,t.EventEmitter),r.prototype.of=function(e){return this.namespaces[e]||(this.namespaces[e]=new t.SocketNamespace(this,e),e!==``&&this.namespaces[e].packet({type:`connect`})),this.namespaces[e]},r.prototype.publish=function(){var e;for(var t in this.emit.apply(this,arguments),this.namespaces)this.namespaces.hasOwnProperty(t)&&(e=this.of(t)).$emit.apply(e,arguments)},r.prototype.handshake=function(e){var n=this,r=this.options;if(!n.disconnected){var a=r.rewriteUrlForProxy([`http`+(r.secure?`s`:``)+`:/`,r.host+`:`+r.port,r.resource,t.protocol,t.util.query(this.options.query,`t=`+ +new Date)].join(`/`));if(this.isXDomain()&&!t.util.ua.hasCORS){var o=document.getElementsByTagName(`script`)[0],s=document.createElement(`script`);s.src=a+`&jsonp=`+t.j.length,o.parentNode.insertBefore(s,o),t.j.push((function(e){u(e),s.parentNode.removeChild(s)}))}else{var c=t.util.request();c.open(`GET`,a,!0);var l=this.options.requestHeaders;l!==void 0&&Object.keys(l).forEach((function(e){c.setRequestHeader(e,l[e])})),c.onreadystatechange=function(){c.readyState==4&&(c.onreadystatechange=i,c.status==200?u(c.responseText):!n.reconnecting&&n.onError(c.responseText))},c.send(null)}}function u(t){t instanceof Error?n.onError(t.message):e.apply(null,t.split(`:`))}},r.prototype.getTransport=function(e){for(var n,r=e||this.transports,i=0;n=r[i];i++)if(t.Transport[n]&&t.Transport[n].check(this)&&(!this.isXDomain()||t.Transport[n].xdomainCheck()))return new t.Transport[n](this,this.sessionid);return null},r.prototype.connect=function(e){if(this.connecting||this.disconnected)return this;var n=this,r=function(r,i,a,o){function s(){if(!n.connected&&!n.disconnected)if(n.connecting=!1,clearTimeout(n.connectTimeoutTimer),n.options[`try multiple transports`]){for(;n.remainingTransports.length>0&&n.remainingTransports.splice(0,1)[0]!=n.transport.name;);n.remainingTransports.length?c(n.remainingTransports):n.publish(`connect_failed`)}else n.publish(`connect_failed`)}function c(e){if(n.transport&&(n.transport.clearTimeouts(),n.transport.clearEventHandlers()),n.transport=n.getTransport(e),!n.transport||n.disconnected)return n.publish(`connect_failed`);n.transport.ready(n,(function(){n.connecting=!0,n.publish(`connecting`,n.transport.name),n.transport.open(s),n.options[`connect timeout`]&&(n.connectTimeoutTimer=setTimeout((function(){s()}),n.options[`connect timeout`]))}))}n.sessionid=r,n.closeTimeout=1e3*a+2e3,n.heartbeatTimeout=1e3*i+2e3,n.transports=o?t.util.intersect(o.split(`,`),n.options.transports):n.options.transports,n.setHeartbeatTimeout(),n.remainingTransports=n.transports.slice(0),c(n.transports),n.once(`connect`,(function(){clearTimeout(n.connectTimeoutTimer),e&&typeof e==`function`&&e()}))};if(this.options[`skipped handshake data`]){var i=this.options[`skipped handshake data`];r(`v4c-`+new Date().getTime(),i.timeout,i.timeout,`websocket`)}else this.handshake(r);return this},r.prototype.setHeartbeatTimeout=function(){clearTimeout(this.heartbeatTimeoutTimer);var e=this;this.heartbeatTimeoutTimer=setTimeout((function(){e.transport.onClose()}),this.heartbeatTimeout)},r.prototype.packet=function(e){return this.connected&&!this.doBuffer?this.transport.packet(e):this.buffer.push(e),this},r.prototype.setBuffer=function(e){this.doBuffer=e,!e&&this.connected&&this.buffer.length&&(this.transport.payload(this.buffer),this.buffer=[])},r.prototype.disconnect=function(){return(this.connected||this.connecting)&&(this.open&&this.of(``).packet({type:`disconnect`}),this.onDisconnect(`booted`)),this.disconnected=!0,this},r.prototype.disconnectSync=function(){var e=t.util.request(),n=this.resource+`/`+t.protocol+`/`+this.sessionid;e.open(`GET`,n,!0),this.onDisconnect(`booted`)},r.prototype.isXDomain=function(){var e=n.location.port||(n.location.protocol==`https:`?443:80);return this.options.host!==n.location.hostname||this.options.port!=e},r.prototype.onConnect=function(){this.connected||(this.connected=!0,this.connecting=!1,this.doBuffer||this.setBuffer(!1),this.emit(`connect`))},r.prototype.onOpen=function(){this.open=!0},r.prototype.onClose=function(){this.open=!1,clearTimeout(this.heartbeatTimeoutTimer)},r.prototype.onPacket=function(e){this.of(e.endpoint).onPacket(e)},r.prototype.onError=function(e){e&&e.advice&&e.advice===`reconnect`&&(this.connected||this.connecting)&&(this.disconnect(),this.options.reconnect&&this.reconnect()),this.publish(`error`,e&&e.reason?e.reason:e)},r.prototype.onDisconnect=function(e){var t=this.connected,n=this.connecting;this.connected=!1,this.connecting=!1,this.open=!1,(t||n)&&(this.transport.close(),this.transport.clearTimeouts(),t?(this.publish(`disconnect`,e),e!=`booted`&&this.options.reconnect&&!this.reconnecting&&this.reconnect()):this.publish(`close_during_connecting`,e))},r.prototype.reconnect=function(){this.reconnecting=!0,this.reconnectionAttempts=0,this.reconnectionDelay=this.options[`reconnection delay`];var e=this,t=this.options[`max reconnection attempts`],n=this.options[`try multiple transports`],r=this.options[`reconnection limit`];function i(){if(e.connected){for(var t in e.namespaces)e.namespaces.hasOwnProperty(t)&&t!==``&&e.namespaces[t].packet({type:`connect`});e.publish(`reconnect`,e.transport.name,e.reconnectionAttempts)}clearTimeout(e.reconnectionTimer),e.removeListener(`connect_failed`,a),e.removeListener(`connect`,a),e.reconnecting=!1,delete e.reconnectionAttempts,delete e.reconnectionDelay,delete e.reconnectionTimer,delete e.redoTransports,e.options[`try multiple transports`]=n}function a(){if(e.reconnecting)return e.connected?i():e.connecting&&e.reconnecting?e.reconnectionTimer=setTimeout(a,1e3):void(e.reconnectionAttempts++>=t?e.redoTransports?(e.publish(`reconnect_failed`),i()):(e.on(`connect_failed`,a),e.options[`try multiple transports`]=!0,e.transport=e.getTransport(),e.redoTransports=!0,e.connect()):(e.reconnectionDelay<r&&(e.reconnectionDelay*=2),e.connect(),e.publish(`reconnecting`,e.reconnectionDelay,e.reconnectionAttempts),e.reconnectionTimer=setTimeout(a,e.reconnectionDelay)))}this.options[`try multiple transports`]=!1,this.reconnectionTimer=setTimeout(a,this.reconnectionDelay),this.on(`connect`,a)}}(r===void 0?e.exports:r,r===void 0?e.parent.exports:r,OG===void 0?window:OG),function(e,t){function n(e,t){this.socket=e,this.name=t||``,this.flags={},this.json=new r(this,`json`),this.ackPackets=0,this.acks={}}function r(e,t){this.namespace=e,this.name=t}e.SocketNamespace=n,t.util.mixin(n,t.EventEmitter),n.prototype.$emit=t.EventEmitter.prototype.emit,n.prototype.of=function(){return this.socket.of.apply(this.socket,arguments)},n.prototype.packet=function(e){return e.endpoint=this.name,this.socket.packet(e),this.flags={},this},n.prototype.send=function(e,t){var n={type:this.flags.json?`json`:`message`,data:e};return typeof t==`function`&&(n.id=++this.ackPackets,n.ack=!0,this.acks[n.id]=t),this.packet(n)},n.prototype.emit=function(e){var t=Array.prototype.slice.call(arguments,1),n=t[t.length-1],r={type:`event`,name:e};return typeof n==`function`&&(r.id=++this.ackPackets,r.ack=`data`,this.acks[r.id]=n,t=t.slice(0,t.length-1)),r.args=t,this.packet(r)},n.prototype.disconnect=function(){return this.name===``?this.socket.disconnect():(this.packet({type:`disconnect`}),this.$emit(`disconnect`)),this},n.prototype.onPacket=function(e){var n=this;function r(){n.packet({type:`ack`,args:t.util.toArray(arguments),ackId:e.id})}switch(e.type){case`connect`:this.$emit(`connect`);break;case`disconnect`:this.name===``?this.socket.onDisconnect(e.reason||`booted`):this.$emit(`disconnect`,e.reason||``);break;case`message`:case`json`:var i=[`message`,e.data];e.ack==`data`?i.push(r):e.ack&&this.packet({type:`ack`,ackId:e.id}),this.$emit.apply(this,i);break;case`event`:i=[e.name].concat(e.args),e.ack==`data`&&i.push(r),this.$emit.apply(this,i);break;case`ack`:this.acks[e.ackId]&&(this.acks[e.ackId].apply(this,e.args),delete this.acks[e.ackId]);break;case`error`:e.advice?this.socket.onError(e):e.reason==`unauthorized`?this.$emit(`connect_failed`,e.reason):this.$emit(`error`,e.reason)}},r.prototype.send=function(){this.namespace.flags[this.name]=!0,this.namespace.send.apply(this.namespace,arguments)},r.prototype.emit=function(){this.namespace.flags[this.name]=!0,this.namespace.emit.apply(this.namespace,arguments)}}(r===void 0?e.exports:r,r===void 0?e.parent.exports:r),function(e,t,n){function r(e){t.Transport.apply(this,arguments)}function i(){}e.websocket=r,t.util.inherit(r,t.Transport),r.prototype.name=`websocket`,r.prototype.open=function(e){var r,i=t.util.query(this.socket.options.query),a=this;return this.connectErrorCallback=e,r||=n.MozWebSocket||n.WebSocket,this.websocket=new r(this.prepareUrl(i)),this.websocket.onopen=function(){a.onOpen(),a.socket.setBuffer(!1)},this.websocket.onmessage=function(e){a.onData(e.data)},this.websocket.onclose=function(){a.onClose(),a.socket.setBuffer(!0)},this.websocket.onerror=function(e){a.onError(e)},this},r.prototype.send=function(e){return this.websocket.send(e),this},r.prototype.payload=function(e){for(var t=0,n=e.length;t<n;t++)this.packet(e[t]);return this},r.prototype.close=function(){return this.websocket.close(),this},r.prototype.onError=function(e){this.connectErrorCallback!==void 0&&(this.connectErrorCallback(),this.connectErrorCallback=void 0),this.socket.onError(e)},r.prototype.scheme=function(){return this.socket.options.secure?`wss`:`ws`},r.check=function(){return`WebSocket`in n&&!(`__addTask`in WebSocket)||`MozWebSocket`in n},r.xdomainCheck=function(){return!0},r.prototype.clearEventHandlers=function(){return this.websocket&&(this.websocket.onopen=this.websocket.onmessage=this.websocket.onclose=this.websocket.onerror=i),this},t.transports.push(`websocket`)}(r===void 0?e.exports:r.Transport,r===void 0?e.parent.exports:r,OG===void 0?window:OG),function(e,t,n){function r(e){e&&t.Transport.apply(this,arguments)}function i(){}e.XHR=r,t.util.inherit(r,t.Transport),r.prototype.open=function(){return this.socket.setBuffer(!1),this.onOpen(),this.get(),this.setCloseTimeout(),this},r.prototype.payload=function(e){for(var n=[],r=0,i=e.length;r<i;r++)n.push(t.parser.encodePacket(e[r]));this.send(t.parser.encodePayload(n))},r.prototype.send=function(e){return this.post(e),this},r.prototype.post=function(e){var t=this;this.socket.setBuffer(!0),this.sendXHR=this.request(`POST`),n.XDomainRequest&&this.sendXHR instanceof XDomainRequest?this.sendXHR.onload=this.sendXHR.onerror=function(){this.onload=i,t.socket.setBuffer(!1)}:this.sendXHR.onreadystatechange=function(){this.readyState==4&&(this.onreadystatechange=i,this.status==200?(clearTimeout(this.ackTimeoutTimer),t.socket.setBuffer(!1)):t.onClose())},this.sendXHR.send(e),t.sendXHR.ackTimeoutTimer=setTimeout((function(){t.onClose()}),t.socket.options.ackTimeoutMs)},r.prototype.close=function(){return this.onClose(),this},r.prototype.request=function(e){var n=t.util.request(this.socket.isXDomain()),r=t.util.query(this.socket.options.query,`t=`+ +new Date);n.open(e||`GET`,this.prepareUrl(r),!0);var i=this.socket.options.requestHeaders;if(i!==void 0&&Object.keys(i).forEach((function(e){n.setRequestHeader(e,i[e])})),e==`POST`)try{n.setRequestHeader?n.setRequestHeader(`Content-type`,`text/plain;charset=UTF-8`):n.contentType=`text/plain`}catch{}return n},r.prototype.scheme=function(){return this.socket.options.secure?`https`:`http`},r.check=function(e,r){try{var i=t.util.request(r),a=n.XDomainRequest&&i instanceof XDomainRequest,o=(e&&e.options&&e.options.secure?`https:`:`http:`)!=n.location.protocol;if(i&&(!a||!o))return!0}catch{}return!1},r.xdomainCheck=function(){return r.check(null,!0)},r.prototype.clearEventHandlers=function(){return this.sendXHR&&(this.sendXHR.onreadystatechange=this.sendXHR.onload=i),this}}(r===void 0?e.exports:r.Transport,r===void 0?e.parent.exports:r,OG===void 0?window:OG),function(e,t,n){function r(){t.Transport.XHR.apply(this,arguments)}function i(){}e[`xhr-polling`]=r,t.util.inherit(r,t.Transport.XHR),t.util.merge(r,t.Transport.XHR),r.prototype.name=`xhr-polling`,r.prototype.open=function(e){return this.connectErrorCallback=e,t.Transport.XHR.prototype.open.call(this),!1},r.prototype.get=function(){if(this.isOpened){var e=this;this.xhr=this.request(),n.XDomainRequest&&this.xhr instanceof XDomainRequest?(this.xhr.onload=function(){e.connectErrorCallback=void 0,this.onload=i,this.onerror=i,e.onData(this.responseText),e.get()},this.xhr.onerror=function(){e.onClose(),e.connectErrorCallback!==void 0&&(e.connectErrorCallback(),e.connectErrorCallback=void 0)}):this.xhr.onreadystatechange=function(){this.readyState==4&&(this.onreadystatechange=i,this.status==200?(e.connectErrorCallback=void 0,e.onData(this.responseText),e.get()):(e.onClose(),e.connectErrorCallback!==void 0&&(e.connectErrorCallback(),e.connectErrorCallback=void 0)))},this.xhr.send(null)}},r.prototype.onClose=function(){if(t.Transport.XHR.prototype.onClose.call(this),this.xhr){this.xhr.onreadystatechange=this.xhr.onload=this.xhr.onerror=i;try{this.xhr.abort()}catch{}this.xhr=null}},r.prototype.ready=function(e,n){var r=this;t.util.defer((function(){n.call(r)}))},r.prototype.clearEventHandlers=function(){return t.Transport.XHR.prototype.clearEventHandlers.call(this),this.xhr&&(this.xhr.onreadystatechange=this.xhr.onload=this.xhr.onerror=i),this},t.transports.push(`xhr-polling`)}(r===void 0?e.exports:r.Transport,r===void 0?e.parent.exports:r,OG===void 0?window:OG),t.io=r}},n={};function r(e){var i=n[e];if(i!==void 0)return i.exports;var a=n[e]={id:e,loaded:!1,exports:{}};return t[e].call(a.exports,a,a.exports,r),a.loaded=!0,a.exports}return r.nmd=e=>(e.paths=[],e.children||=[],e),r(882)})(),e.exports=t(vLe())),n9.exports;var e,t}var i9,xLe,a9=bLe(),SLe=class{constructor(e,t){this.logEvent=e=>{this._logger.debug(e),this._telemetryLogManager.sendEvent({name:e.name,tenant:DCe,properties:{...e.properties}})},this._logger=e.createChild(`TelemetrySender`),this._telemetryLogManager=t}};function CLe(e){return{registrationId:K0(),registrarServiceUrl:e.getTrouterSettings().registrarServiceUrl,registrarTtlInSeconds:e.getTrouterSettings().registrarTtlInSeconds,maxRegistrationTimeInMs:e.getTrouterSettings().maxRegistrationTimeInMs,registrarRefreshTimeoutInMs:e.getTrouterSettings().registrarRefreshTimeoutInMs,pnhAppId:e.getTrouterSettings().pnhAppId,pnhTemplate:e.getTrouterSettings().pnhTemplate,platform:e.getTrouterSettings().platform,platformUIVersion:e.getTrouterSettings().version,trouterServiceUrl:e.getTrouterSettings().trouterServiceUrl,version:e.getTrouterSettings().version,trouterConnectTimeoutInMs:e.getTrouterSettings().trouterConnectTimeoutInMs,productName:e.getTrouterSettings().productName,sessionId:K0(),environment:e.getTrouterSettings().environment,timeoutOptions:e.getTrouterSettings().timeoutOptions}}var wLe=class{constructor(e,t,n,r,i){this._ecsProvider=t,this._tokenProvider=n,this._isRegistered=!1,this._registeredChangedListeners=[],this._logger=e.createChild(`Trouter`),this._logger.info(`init`),this._initialRegistrationCompleteDefer=e3(),this._telemetryLogManager=r,this._acsProxy=i}async start(e){let t;if(this._trouterService)throw this._logger.error(`Trouterservice already initialized`),new Y({defaultError:J.CALL_STACK.SIGNALING_SERVICE_ALREADY_INITIALIZED});{let n=new Promise((async(t,n)=>{try{if(this._logger.info(`Trouterservice start`),this._trouterService=a9.createTrouterService(this._logger),!this._trouterService)throw this._logger.error(`Failed to create trouter service`),new Y({defaultError:J.CALL_STACK.SIGNALING_SERVICE_CREATE_FAIL});this._options=this._getTrouterConfig(this._logger,this._tokenProvider),e&&(this._options.trouterSettings.environment=e.environment||``,this._options.trouterSettings.sessionId=e.sessionId);let n,r,i=+new Date;this._trouterService.start(this._options),this._trouterService.onStateChanged(((e,t)=>{e===a9.TrouterState.Connected&&(n=+new Date)})),await this._initialRegistrationCompleteDefer.promise;let a=+new Date;n??=+new Date,r=n,t({trouterRequestCompletionTimeDeltaMs:Math.max(0,n-i),registrarRequestCompletionTimeDeltaMs:Math.max(0,a-r)})}catch(e){n(e)}}));try{t=await n3((()=>n),ZSe)}catch(e){throw e.code===408?(this._logger.error(`Signaling init timeout`),new Y({defaultError:J.CALL_STACK.SIGNALING_SERVICE_CREATE_TIMEOUT,defaultErrorMessageArgs:[ZSe]})):(this._logger.error(`Signaling init failed`),new Y({defaultError:J.CALL_STACK.SIGNALING_INIT_FAIL}))}}return t}isRegistered(){return this._isRegistered}onRegisteredChanged(e){this._logger.info(`TrouterService onRegisteredChanged`),this._registeredChangedListeners.push(e)}offRegisteredChanged(e){let t=this._registeredChangedListeners.indexOf(e);this._logger.info(`TrouterService offRegisteredChanged: ${t}`),t>-1&&this._registeredChangedListeners.splice(t,1)}stop(e){this._logger.info(`Trouterservice stop`),this._trouterService?(this._trouterService.onStateChanged(void 0),this._trouterService.stop(e),this._trouterService=void 0):this._logger.error(`Trouterservice not inited`)}registerMessageHandler(e){this._logger.info(`Trouterservice registerMessageHandler`),this._trouterService&&this._trouterService.registerMessageHandler(e)}clearMessageHandlers(){this._trouterService&&this._trouterService.clearMessageHandlers()}checkConnection(){this._trouterService&&this._trouterService.checkConnection()}state(){return this._logger.info(`Trouterservice state`),this._trouterService?this._trouterService.state():a9.TrouterState.Unknown}onStateChanged(e){this._logger.info(`Trouterservice onStateChanged`),this._trouterService&&this._trouterService.onStateChanged(e)}offStateChanged(e){this._logger.info(`Trouterservice offStateChanged`),this._trouterService&&this._trouterService.offStateChanged(e)}getTrouterUrlAsync(){return this._trouterService?(this._logger.info(`getTrouterUrlAsync called`),this._trouterService.getTrouterUrlAsync()):Promise.reject(`Trouterservice not started yet`)}getTrouterSettings(){return this._options.trouterSettings}_getSettings(){return CLe(this._ecsProvider)}_createTrouterTelemetryConfig(e){return{eventLogger:new SLe(e.createChild(`TrouterTelemetry`),this._telemetryLogManager),settings:{enabled:this._ecsProvider.getTrouterTelemetryConfig().enabled,logHealthCheckError:this._ecsProvider.getTrouterTelemetryConfig().logHealthCheckError,trouter_js_client_connected:this._ecsProvider.getTrouterTelemetryConfig().trouter_js_client_connected,trouter_js_client_disconnected:this._ecsProvider.getTrouterTelemetryConfig().trouter_js_client_disconnected,trouter_js_client_error:this._ecsProvider.getTrouterTelemetryConfig().trouter_js_client_error,trouter_js_client_progress:this._ecsProvider.getTrouterTelemetryConfig().trouter_js_client_progress,trouter_js_client_response:this._ecsProvider.getTrouterTelemetryConfig().trouter_js_client_response,numberOfStepsToMaintain:this._ecsProvider.getTrouterTelemetryConfig().numberOfStepsToMaintain,sendProgressTimeoutSecs:this._ecsProvider.getTrouterTelemetryConfig().sendProgressTimeoutSecs}}}_getTrouterConfig(e,t){return{trouterSettings:this._getSettings(),proxyUrlRewrite:this._acsProxy.hasProxyUrl()?e=>this._acsProxy.proxyfyUrl(e):void 0,skypeTokenProvider:t,telemetryConfig:this._createTrouterTelemetryConfig(e),registrationStateCallbackForAcsDoNotUse:e=>{this._logger.info(`TrouterService registrationStateCallbackForAcs: ${e}`),this._isRegistered=e,this._initialRegistrationCompleteDefer.isPending()&&this._isRegistered?this._initialRegistrationCompleteDefer.resolve():this._isRegistered?this._logger.info(`Signaling service is currently registered`):this._logger.error(`Signaling service is currently not registered. Unable to receive incoming calls`),this._onRegisteredChanged(e)}}}_onRegisteredChanged(e){this._logger.info(`TrouterService onRegisteredChanged: ${e}`),this._registeredChangedListeners.forEach((t=>{t(e)}))}},TLe=class{constructor(e){this._eventToTenantId={skypecosi_concore_web_csa_conversation_httprequest:f2,skypecosi_concore_web_ts_calling_in_call_session:f2,skypecosi_concore_web_ts_calling_call_setup_session:f2,skypecosi_concore_native_ts_calling_in_call_session:f2,skypecosi_concore_native_ts_calling_call_setup_session:f2,skypecosi_concore_web_pluginless_call_session:f2,skypecosi_concore_web_pluginless_modality_session:f2,skypecosi_concore_web_csa_conversation_callmodality:f2,skypecosi_concore_web_ts_calling_registry:f2,mdsc_webrtc_session:p2,mdsc_webrtc_session_initial:p2,live_events:ECe,mdsc_ortc_reports:p2,mdsc_ortc_reports_initial:p2,mdsc_rt_log:p2},this.getTenant=e=>this._eventToTenantId[e]?this._eventToTenantId[e]:``,this.getCallingAdapter=()=>({sendEvent:(e,t)=>{this._telemetryLogManager.sendEvent({tenant:this.getTenant(e),name:e,properties:t})}}),this.getGenericTelemetryLogger=e=>({sendEvent:e=>{this._telemetryLogManager.sendEvent({tenant:this.getTenant(e.eventName),name:e.eventName,properties:e.props})}}),this.getMediaAdapter=()=>({sendEvent:(e,t)=>{this._telemetryLogManager.sendEvent({tenant:this.getTenant(e),name:e,properties:t})}}),this.sendEvents=e=>(e.forEach((e=>{this._telemetryLogManager.sendEvent({tenant:this.getTenant(e.eventName),name:e.eventName,properties:e.props})})),Promise.resolve()),this._telemetryLogManager=e}},ELe=class{constructor(){this._timedVideoEffectProviderPromise=qwe(uue),this._timedModelConfigPromise=qwe(uue)}get videoEffectProviderDeferredPromise(){return this._timedVideoEffectProviderPromise.deferredPromise}get modelConfigDeferredPromise(){return this._timedModelConfigPromise.deferredPromise}async getVideoEffectProvider(){return this._timedVideoEffectProviderPromise.timerStart(),this._timedVideoEffectProviderPromise.deferredPromise.promise}async getModelConfig(){return this._timedModelConfigPromise.deferredPromise.resolve({modelUrl:``,weightPathPrefix:``}),this._timedModelConfigPromise.deferredPromise.promise}},DLe=class{constructor(e){this._encodedStreamsJsPath=e}async getWorkerUrl(){return this._encodedStreamsJsPath}},OLe=class{constructor(e,t){t||typeof e.createChild!=`function`?this.logger=e:this.logger=e.createChild(`HttpRequestDispatcher::`),this.proxy=t}getRequestOptions(e,t,n,r,i){return{headers:t||{},timeout:r,payload:n||null,responseType:i}}getAsync(e,t){return this.send(e,t,F3.GET)}postAsync(e,t){return this.send(e,t,F3.POST)}putAsync(e,t){return this.send(e,t,F3.PUT)}removeAsync(e,t){return this.send(e,t,F3.DELETE)}async send(e,t={headers:{}},n){let r=this.logger.createChild(`[${t.causeId||K0()}] HttpRequestDispatcher::`),i=K0();r.info(`Send, httpRequestId: ${i}, ${n} ${e}`),this.proxy&&(e=this.proxy.proxyfyUrl(e));let a=new AbortController,o=()=>{r.info(`Send, httpRequestId: ${i}, aborting`),a.abort()};r.info(`Send, httpRequestId: ${i}, responseType: ${t.responseType}`),t.headers=t.headers||{};let s=t.headers;s[`Content-Type`]||=t.contentType||`application/json`;let c={method:n,headers:t.headers,credentials:t.withCredentials?`include`:`same-origin`,keepalive:t.keepAlive||!1,signal:a.signal},l=Date.now(),u={url:e,start:new Date(l).toISOString(),end:``,statusCode:0,deltaTimeInMs:0,causeId:``},d=Z().telemetry.apiCauseIdHeader;try{n!==`GET`&&(c.body=t.payload||``);let a=fetch(e,c);if(typeof t.timeout==`number`&&t.timeout>0){let e=setTimeout((()=>o()),t.timeout);a=a.finally((()=>clearTimeout(e)))}bwe(t.timeout)&&t.timeout.then((()=>{o()}),(()=>{r.info(`Send, httpRequestId: ${i}, timeout promise rejected`)}));let s=await a;if(r.info(`Send, httpRequestId: ${i}, \n response status: ${s.status}`),t.headers[d]){let e=t.headers[d].split(`-`)[0];F6.getRemoveCauseIdToNetworkInfo(e)&&this.setCauseIdToNetworkInfo(u,s.status,e)}let f;try{f=await this.extractPayload(s,i,r)}catch(e){r.error(`Send, httpRequestId: ${i}, failed to parse response, error: ${e.message}`)}let p={};return s.headers.forEach(((e,t)=>{p[t]=e})),{response:f,request:{status:s.status,statusText:s.statusText,headers:p,responseURL:s.url,response:f,withCredentials:t.withCredentials},duration:Date.now()-l}}catch(n){if(r.error(`Send, httpRequestId: ${i}, \n failed ${c.method} ${e}, error: ${n.message}`),t.headers[d]){let e=t.headers[d].split(`-`)[0];F6.ifCauseIdExistsRemoveNetworkInfo(e)&&this.setCauseIdToNetworkInfo(u,n.code,e)}throw n.name===`AbortError`?(r.warn(`Send, httpRequestId: ${i}, aborted`),{aborted:!0}):(n.response?r.warn(`Send, httpRequestId: ${i}, \n response: ${n4(n.response)}`):n.request?r.warn(`Send, httpRequestId: ${i}, \n no response, request: ${n4(n.request)}`):r.warn(`Send, httpRequestId: ${i}, \n request not made, error: ${n4(n)}`),n||Error(`HttpRequestId: ${i}, failed`))}}async extractPayload(e,t,n){let r=this.getHeader(e,`content-type`,n),i=this.getHeader(e,`content-length`,n);switch(n.info(`ExtractPayload, httpRequestId: ${t}, \n parsing content type: ${r}, content length: ${i}`),r){case`application/json`:return i?await e.json():{};case`application/text`:return i?await e.text():``;case`application/octet-stream`:return i?await e.blob():new Blob;case`application/arraybuffer`:return i?await e.arrayBuffer():new ArrayBuffer(0);default:return e.json().catch((()=>{throw Error(`HttpRequestId: ${t}, unsupported content type: ${r}`)}))}}getHeader(e,t,n){n.info(`GetHeader, header: ${t}`);let r=e.headers.get(t.toLowerCase()),i;return r!==null&&(i=r),i}setCauseIdToNetworkInfo(e,t,n){e={...e,end:new Date().toISOString(),statusCode:t,deltaTimeInMs:Date.now()-new Date(e.start).getTime(),causeId:n},F6.setCauseIdToNetworkInfo(n,e)}},kLe=class{constructor(){this._activeEffects=[],this.eventEmitter=new w3.EventEmitter}on(e,t){if(e!==`statusChanged`)throw new Y({defaultError:J.FEATURES.VIDEO_EFFECTS.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.on(e,t)}off(e,t){if(e!==`statusChanged`)throw new Y({defaultError:J.FEATURES.VIDEO_EFFECTS.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.off(e,t)}getActiveEffects(){return this._activeEffects}setActiveEffects(e){let t=this._activeEffects;this._activeEffects=e,this.eventEmitter.emit(`statusChanged`,t,this._activeEffects)}},ALe=class{constructor(){this._activeEffects={echoCancellation:[],noiseSuppression:[],autoGainControl:[]},this.eventEmitter=new w3.EventEmitter}on(e,t){if(e!==`statusChanged`)throw new Y({defaultError:J.FEATURES.AUDIO_EFFECTS.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.on(e,t)}off(e,t){if(e!==`statusChanged`)throw new Y({defaultError:J.FEATURES.AUDIO_EFFECTS.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.off(e,t)}getActiveEffects(){return this._activeEffects}setActiveEffects(e,t){let n={...this._activeEffects};this._activeEffects={...e},this.eventEmitter.emit(`statusChanged`,n,this._activeEffects,t)}},jLe=class{constructor(){this._providerValue=null}get providerValue(){return this._providerValue}set providerValue(e){this._providerValue=e}async getAudioEffectProvider(){return this.providerValue}};function MLe(){if(xLe)return i9;xLe=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,i=(i,a,o,s)=>{if(a&&typeof a==`object`||typeof a==`function`)for(let c of n(a))r.call(i,c)||c===o||e(i,c,{get:()=>a[c],enumerable:!(s=t(a,c))||s.enumerable});return i},a=t=>i(e({},`__esModule`,{value:!0}),t),o={};function s(e){return new Promise((t=>setTimeout(t,e)))}((t,n)=>{for(var r in n)e(t,r,{get:n[r],enumerable:!0})})(o,{mmrAdapter:()=>f}),i9=a(o);var c=class{constructor(){this.observers=new Set}subscribe(e){return typeof e==`function`&&(e={next:e}),this.observers.add(e),{unsubscribe:()=>{this.observers.delete(e)}}}},l=class extends c{constructor(e){super(),this.logger=e,this._state=3}get state(){return this._state}handleMessage(e){this.observers.forEach((t=>{t.next?.(e)}))}},u=`config`,d=class extends l{constructor(e,t){super(e),this.config=t,this.waitForChannel()}get tsCallingChannel(){return window.navigator.mediaDevices?.tsCallingChannel}getConfig(){return this.config}next(e){this.tsCallingChannel?this.tsCallingChannel.sendTsCallingMessage(e):this.logger.error(`tsCallingChannel is not available.`)}async waitForChannel(){do this.initializeTsCallingChannel(),await s(500);while(this.state!==1)}initializeTsCallingChannel(){if(!this.tsCallingChannel)return;this._state=1,this.tsCallingChannel.addEventListener(`messagerecv`,(e=>{e.detail?.message&&this.handleMessage(e.detail.message)}));let e=this.createConnectionURL();this.logger.log(`connectionUrl: ${e}`),this.tsCallingChannel.sendTsCallingMessage({WebViewRemotingControlChannel:{url:e.toString()}})}createConnectionURL(){let{loaderUrl:e,...t}=this.config;if(!e)throw this.logger.error(`loaderUrl was not passed in config.`),Error(`loaderUrl was not passed in config.`);try{let n=new URL(e);return n.searchParams.set(u,JSON.stringify(t)),n}catch(e){throw this.logger.error(`Failed to create connection URL`,e),e}}},f=(e,t)=>new d(e,t);return i9}var NLe=MLe();function PLe(){return!!navigator.mediaDevices?.tsCallingChannel}function FLe(e,t){let n=Z().vdi3,r=window.vdi3Debug??{},i=r.cdnUrl??n.cdnUrl;if(!i){let e=n.customTsVersion||H5.stackFactory.getVersion().build;if(e.includes(`_`))throw new Y({defaultError:J.FEATURES.VDI3.INVALID_CDN_URL});i=`${n.cdnBaseUrl}${e}/`}let a=r.connectionUrl??new URL(n.loaderHtmlPath,i).toString(),o=r.pluginlessUrl??new URL(n.pluginlessJsPath,i).toString();return{vdi3Config:{transport:NLe.mmrAdapter(e,{staleTimeout:n.transportConnectionTimeoutInMs,executionTimeout:n.remoteExecutionTimeoutInMs,messageChunkSize:n.chunkSize,writeLogToConsole:r.writeLogToConsole??t?.writeLogToConsole??n.writeLogToConsole,loaderUrl:a}),trouterSettings:{},pluginlessUrl:o,cdnUrl:i}}}var ILe={AcsCallingSDKWeb:{telemetry:{telemetryFlushTimeout:1e4,mediaStatsConfig:{enableVideoLeakInformation:!1,enableRenderCountCheck:!1}},calling:{allowAccessRawMediaStream:!1,deviceSelectionTimeoutInMs:1e4}},SkypeWebMedia:{mediaAgent:{useOneDsLogger:!0}}},LLe=class{constructor(){this._mapping=new WeakMap,this._eventEmitter=new T3,this._isRemoteStackActive=!0}get(e){return this._mapping.get(e)?.deref()}create(e){let t=this._createProxy(e);if(t===void 0)throw Error(`The type is not supported for proxy`);return this._mapping.set(e,new WeakRef(t)),t}replaceProxyToRaw(e){if(typeof e==`object`){if(Array.isArray(e))return e.map((e=>this.replaceProxyToRaw(e)));if(H6 in e)return e[H6]}return e}replaceRawToProxy(e,t){if(t===void 0&&(t=new Map),typeof e==`object`){if(e===null)return e;if(t.has(e))return t.get(e);if(H6 in e)return e;if(Array.isArray(e)){let n=e.map((e=>this.replaceRawToProxy(e,t)));return t.set(e,n),n}if(e instanceof Promise)return e.then((e=>this.replaceRawToProxy(e,t)));if(e instanceof ArrayBuffer||e instanceof Uint8Array||e instanceof Date||e instanceof RegExp)return e;if(this.isSupportedType(e)){let n=this.get(e);return n===void 0&&(n=this.create(e)),t.set(e,n),n}if(HOe(e))return t.set(e,e),e;let n={};t.set(e,n);for(let[r,i]of Object.entries(e))n[r]=this.replaceRawToProxy(i,t);return n[H6]=e,n}return e}on(e,t){this._eventEmitter.on(e,t)}once(e,t){this._eventEmitter.once(e,t)}dispose(){this._eventEmitter.removeAllListeners()}};function o9(e,t,n,r={}){return new Proxy(e,{get:(i,a)=>{let o,s;if(a===H6)return e;if(a in t)o=t[a],s=t;else{if(!(a in e))return;o=e[a],s=e}let c=r[a]??{input:!0,output:!0};if(typeof o==`function`){if(!n.isRemoteStackActive()&&s===e)throw new Y({defaultError:J.FEATURES.VDI3.REMOTE_STACK_TERMINATED});return new Proxy(o,{apply:(e,t,r)=>{let i=r.map((e=>typeof e==`function`?(...t)=>e.apply(null,n.replaceRawToProxy(t)):c.input?n.replaceProxyToRaw(e):e)),a=Reflect.apply(e,s,i);return c.output?n.replaceRawToProxy(a):a}})}return c.output?n.replaceRawToProxy(o):o},has:(n,r)=>r===H6||r in t||r in e})}var s9=class{constructor(e,t){this._proxyReferenceManager=e,this._tsObject=t,this._eventEmitter=new T3,this._handles=new Map,this._skipEvents=[`optimalVideoReceiversCountChanged`]}_proxyCall(e,t){let n=this._tsObject[e];if(n!==void 0)return n.apply(this._tsObject,t)}get instance(){return this._tsObject}changed(e){let t=`changed`,n=this._handles.get(t);n===void 0&&(n=this._proxyCall(`changedAsync`,[(...e)=>{this._eventEmitter.emit(t,...e)}]),this._handles.set(t,n));let r=(...t)=>{e.apply(null,t)};return this._eventEmitter.on(t,r),{dispose:()=>{this._eventEmitter.off(t,r),this._eventEmitter.listenerCount(t)===0&&(n?.then((e=>e.disposeAsync?.())).catch(A4),this._handles.delete(t))}}}on(e,t){if(this._skipEvents.includes(e))return{dispose:A4};let n=`on_${e}`,r=this._handles.get(n);r===void 0&&(r=this._proxyCall(`onAsync`,[e,(...e)=>{this._eventEmitter.emit(n,...e)}]),this._handles.set(n,r));let i=(...e)=>{t.apply(null,e)};return this._eventEmitter.on(n,i),{dispose:()=>{this._eventEmitter.off(n,i),this._eventEmitter.listenerCount(n)===0&&(r?.then((e=>e.disposeAsync?.())).catch(A4),this._handles.delete(n))}}}once(e,t){if(this._skipEvents.includes(e))return{dispose:A4};let n=`once_${e}`,r=this._handles.get(n);r===void 0&&(r=this._proxyCall(`onceAsync`,[e,(...e)=>{this._eventEmitter.emit(n,...e)}]),this._handles.set(n,r));let i=(...e)=>{t.apply(null,e)};return this._eventEmitter.on(n,i),{dispose:()=>{this._eventEmitter.off(n,i),this._eventEmitter.listenerCount(n)===0&&(r?.then((e=>e.disposeAsync?.())).catch(A4),this._handles.delete(n))}}}async changedAsync(e){let t=`changed`,n=this._handles.get(t);n===void 0&&(n=this._proxyCall(`changedAsync`,[(...e)=>{this._eventEmitter.emit(t,...e)}]),this._handles.set(t,n));let r=(...t)=>{e.apply(null,t)};return this._eventEmitter.on(t,r),await n,{dispose:()=>{this._eventEmitter.off(t,r),this._eventEmitter.listenerCount(t)===0&&(n?.then((e=>e.disposeAsync?.())).catch(A4),this._handles.delete(t))}}}async onAsync(e,t){if(this._skipEvents.includes(e))return{dispose:A4};let n=`on_${e}`,r=this._handles.get(n);r===void 0&&(r=this._proxyCall(`onAsync`,[e,(...e)=>{this._eventEmitter.emit(n,...e)}]),this._handles.set(n,r));let i=(...e)=>{t.apply(null,e)};return this._eventEmitter.on(n,i),await r,{dispose:()=>{this._eventEmitter.off(n,i),this._eventEmitter.listenerCount(n)===0&&(r?.then((e=>e.disposeAsync?.())).catch(A4),this._handles.delete(n))}}}},RLe=class extends s9{constructor(e,t){super(e,t),e.once(`remoteStackTerminated`,(()=>{this._eventEmitter.emit(`changed`),this._eventEmitter.emit(`on_callStateChanged`)}))}get state(){return this._proxyReferenceManager.isRemoteStackActive()?this._tsObject.state:7}get callEndDiagnosticsInfo(){return this._proxyReferenceManager.isRemoteStackActive()||this._tsObject.state===7?this._tsObject.callEndDiagnosticsInfo:{callControllerCode:0,callControllerSubCode:4521,phrase:`call ended due to RDP disconnection`,resultCategories:[`ExpectedError`]}}get ptzHandler(){throw new Y({defaultError:J.FEATURES.VDI3.PROPERTY_UNAVAILABLE})}get broadcastMeeting(){throw new Y({defaultError:J.FEATURES.VDI3.PROPERTY_UNAVAILABLE})}get videoLayout(){throw new Y({defaultError:J.FEATURES.VDI3.PROPERTY_UNAVAILABLE})}getIncomingRawAudioStream(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getUnmixedAudioProvider(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}init(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}setDeviceManager(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}forceUpdate(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}startVideo(e,t){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}stopVideo(e,t){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}startScreenSharing(e,t,n,r){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}changeCropRegion(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}stopScreenSharing(e,t,n){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}callSafeTransfer(e,t,n){return n===void 0&&(n={disableForwardingAndUnanswered:!1}),this._tsObject.callSafeTransfer(e,t,n)}setPlatformCallConstraints(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createStageAsync(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createStage(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}sendLastKnownStats(){this._proxyReferenceManager.isRemoteStackActive()&&this._tsObject.sendLastKnownStats().catch((e=>{}))}},zLe=class extends s9{constructor(e,t){super(e,t)}getSourceIdForMediaType(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getDiagnosticData(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}},BLe=class extends s9{constructor(e,t){super(e,t)}getRawStream(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}start(e,t){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}stop(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}selectVideoTrack(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}setVideoStreamConfig(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getDiagnosticData(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getStats(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}},VLe=class extends s9{constructor(e,t){super(e,t),this._deletedCalls=[]}get calls(){return Q2.difference(this._tsObject.calls,this._deletedCalls)}updateSkypeToken(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getSetup(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getCall(e,t,n){return this._tsObject.calls.find((t=>t.callId===e))}createDownloader(e,t,n,r,i){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createCall(e,t,n,r,i){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createCallWithGroupId(e,t,n,r){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createCallWithMeetingData(e,t,n,r){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}deleteCall(e,t,n){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}async deleteCallAsync(e,t,n){return this._proxyReferenceManager.isRemoteStackActive()?await this._tsObject.deleteCallAsync?.apply(this._tsObject,arguments)??!1:!(!e||!this._tsObject.calls.includes(e))&&(this._deletedCalls.push(e),this._eventEmitter.emit(`on_callRemoved`,e),!0)}enableWindowUninitEventHandler(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}disableWindowUninitEventHandler(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}},HLe=class extends s9{constructor(e,t){super(e,t)}getPermissionState(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}selectDevices(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getSelectedDevices(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createPreview(e,t,n,r){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createPreviewRenderer(e,t,n){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createScreenSharingPreviewRenderer(e,t,n){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}setBackgroundImageAsync(e,t,n){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getImagePropertyAsync(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}transformImageAsync(e,t,n,r){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}sendMessageDeviceVideoEffectsAsync(e,t){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}sendMessageDeviceVideoExtensibilityAsync(e,t){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}setVideoCaptureConfigAsync(e,t){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}captureVideoFrameWithoutEffectsAsync(e,t,n){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getRawDeviceMediaStream(e,t,n){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}setRawMediaStream(e,t,n){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}unsetRawMediaStream(e,t){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createAudioRenderer(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getPersonalizedNoiseSuppression(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}setAudioProcessingFlags(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}},ULe=class extends s9{constructor(e,t){super(e,t)}getPlatformSupportLevel(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}setPlatformCallConstraints(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createCompositor(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getCallRegistry(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}cancelOperation(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getDeviceManager(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createDeviceManager(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getScreenSharingManager(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getSetup(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getEcsProvider(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getCallFeedback(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getAiMdp(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getVersion(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getMediaStatus(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getVideoCapabilityLimits(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}fireIntent(e,t){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}setAllowPrivacySensitiveApis(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getLiveStreamClient(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getUmsStream(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createVoipCallCoordinator(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getDebugDump(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createAiCameraManager(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}},c9=class e extends LLe{constructor(e){super(),this._logger=e.createChild(`TsProxyReferenceManager`),this._mmrRdpConnectionManager=new bIe(this._logger),this._mmrRdpConnectionManager.on(`stateChange`,(e=>{e==`disconnected`&&this._remoteStackTerminated(`MMR RDP connection disconnected`)}))}static create(t){let n=new e(t);return this.proxyReferenceManagers.add(n),n}static notifyRemoteStackTermination(e){this.proxyReferenceManagers.forEach((t=>{t._remoteStackTerminated(e)}))}dispose(){this._mmrRdpConnectionManager.dispose(),e.proxyReferenceManagers.delete(this),super.dispose()}_remoteStackTerminated(e){!1!==this._isRemoteStackActive&&(this._logger.warn(`remote stack is terminated: ${e}`),this._isRemoteStackActive=!1,this._eventEmitter.emit(`remoteStackTerminated`))}_createProxy(e){let t=VOe(e);if(t!==B6.None){if(t===B6.ICall)return o9(e,new RLe(this,e),this);if(t===B6.ICallParticipant)return o9(e,new zLe(this,e),this);if(t===B6.ICallParticipantStream)return o9(e,new BLe(this,e),this);if(t===B6.ICallRegistry)return o9(e,new VLe(this,e),this);if(t===B6.IPluginlessCallingStack)return o9(e,new ULe(this,e),this);if(t===B6.IDeviceManager)return o9(e,new HLe(this,e),this)}}isSupportedType(e){return VOe(e)!==B6.None}isRemoteStackActive(){return!!this._isRemoteStackActive}};c9.proxyReferenceManagers=new Set,H5.monitor.onConnectionTerminated((()=>{c9.notifyRemoteStackTermination(`Disconnection detected by monitor`)}));var WLe=class{constructor(){this._eventEmitter=new w3.EventEmitter,this._shellTrouter=new H5.ShellTrouter,this._state=a9.TrouterState.Unknown,this._registeredState=!1,this._disposeAsync=[]}async initialize(){let e=(e,t)=>{this._state=e,this._eventEmitter.emit(`stateChanged`,e,t)},t=e=>{this._registeredState=e,this._eventEmitter.emit(`registeredChanged`,e)};await this._shellTrouter.onStateChanged(e),await this._shellTrouter.onRegisteredStateChanged(t),this._disposeAsync.push((async()=>{await this._shellTrouter.offStateChanged(e),await this._shellTrouter.offRegisteredStateChanged(t)}))}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}async dispose(){for(let e of this._disposeAsync)await e().catch((e=>{}));this._eventEmitter.removeAllListeners()}state(){return this._state}registeredState(){return this._registeredState}get instance(){return this._shellTrouter}},GLe,l9={},u9={};function KLe(){if(GLe)return u9;GLe=1,Object.defineProperty(u9,"__esModule",{value:!0});var e=R5();return u9.default=function(){function t(){this._isAllowed=!1}return t.prototype.putBackgroundFetchAllowed=function(e){if(this._isAllowed=e,this.isBackgroundFetchAllowed()&&this._isAllowedDeferral){var t=this._isAllowedDeferral;this._isAllowedDeferral=void 0,t.resolve(void 0)}},t.prototype.isBackgroundFetchAllowed=function(){return this._isAllowed},t.prototype.waitForBackgroundFetchAllowed=function(){return this.isBackgroundFetchAllowed()?e.Resolved():(this._isAllowedDeferral||=e.Defer(),this._isAllowedDeferral.promise())},t}(),u9}var qLe,d9={};function JLe(){if(qLe)return d9;qLe=1,Object.defineProperty(d9,"__esModule",{value:!0});var e=R5();return d9.default=function(){function t(){this._isActive=!1}return t.prototype.putAppActive=function(e){if(this._isActive=e,this.isAppActive()&&this._appActiveDeferral){var t=this._appActiveDeferral;this._appActiveDeferral=void 0,t.resolve(void 0)}},t.prototype.isAppActive=function(){return this._isActive},t.prototype.waitForAppActive=function(){return this.isAppActive()?e.Resolved():(this._appActiveDeferral||=e.Defer(),this._appActiveDeferral.promise())},t}(),d9}var YLe,XLe,f9={},ZLe=function(){function e(e,t){this._event=e,this._callback=t}return e.prototype.unsubscribe=function(){this._event.unsubscribe(this._callback)},e}(),QLe=function(){function e(e){e===void 0&&(e=!1);var t=this;this._allowStopPropagation=e,this.fire=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];for(var r=t._subscribers,i=r.length-1;i>=0;i--){var a=r[i].apply(null,e);if(t._allowStopPropagation&&a)return!0}return!1},this._subscribers=[]}return e.prototype.dispose=function(){this._subscribers=[]},e.prototype.subscribe=function(e){return this._subscribers=this._subscribers.concat(e),new ZLe(this,e)},e.prototype.unsubscribe=function(e){this._subscribers=this._subscribers.filter((function(t){return t!==e}))},e}(),p9=tue(Object.freeze({__proto__:null,SubscriptionToken:ZLe,default:QLe})),$Le={};function m9(){return YLe||(YLe=1,e=$Le,Object.defineProperty(e,"__esModule",{value:!0}),(t=e.EcsConfigType||={})[t.Default=0]=`Default`,t[t.User=1]=`User`),$Le;var e,t}function eRe(){if(XLe)return f9;XLe=1,Object.defineProperty(f9,"__esModule",{value:!0});var e=p9,t=R5(),n=m9();return f9.default=function(){function r(t){this._config=t,this.configUpdated=new e.default,this._cachedConfigs={}}return r.prototype.initialize=function(){return this.updateConfigsToFetch()},r.prototype.updateConfigsToFetch=function(){var e=this,n=this._config.getConfig(),r=n.databaseInterface,i=n.configsToFetch;if(!r)return t.Resolved();for(var a=[],o=function(n){if(s._cachedConfigs[n])return`continue`;a.push(r.getData(n).then((function(t){t&&(e._cachedConfigs[n]=t)})).catch((function(){return t.Resolved()})))},s=this,c=0,l=i;c<l.length;c++)o(l[c]);return t.all(a).then((function(){a.length>0&&e.configUpdated.fire()}))},r.prototype.getEcsConfig=function(){return this._cachedConfigs[n.EcsConfigType.User]||this._cachedConfigs[n.EcsConfigType.Default]},r.prototype.getEcsConfigByType=function(e){return this._cachedConfigs[e]},r.prototype.putConfig=function(e){var n=this.getEcsConfig();this._cachedConfigs[e.configType]=e;var r=this.getEcsConfig();(r&&r.configType===e.configType||n&&r&&n.configType!==r.configType)&&this.configUpdated.fire();var i=this._config.getConfig().databaseInterface;return i?i.putData(e.configType,e):t.Resolved()},r}(),f9}var tRe,h9={};function nRe(){if(tRe)return h9;tRe=1;var e=h9&&h9.__assign||function(){return e=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},e.apply(this,arguments)};return Object.defineProperty(h9,"__esModule",{value:!0}),h9.default=function(){function t(){}return t.prototype.initialize=function(e){if(this._config)throw Error(`ECS Configuration already initialized`);this._config=e},t.prototype.getConfig=function(){if(!this._config)throw Error(`ECS Configuration not yet initialized`);return this._config},t.prototype.setConfigsToFetch=function(t){if(!this._config)throw Error(`ECS Configuration not yet initialized`);this._config=e(e({},this._config),{configsToFetch:t})},t.prototype.setFetchTimeout=function(t){if(!this._config)throw Error(`ECS Configuration not yet initialized`);this._config=e(e({},this._config),{fetchTimeout:t})},t}(),h9}var rRe,iRe,g9={},_9={},aRe={},oRe={},v9={};function y9(){return rRe||(rRe=1,e=v9,t=v9&&v9.__assign||function(){return t=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},t.apply(this,arguments)},Object.defineProperty(e,"__esModule",{value:!0}),e.assert=function(e,t){if(!e)throw Error(t)},e.isObject=function(e){return typeof e==`object`&&!!e},e.isString=function(e){return typeof e==`string`},e.attempt=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];try{return e.apply(void 0,t)}catch(e){return Error(e)}},e.remove=function(e,t){for(var n=e.length-1;n>=0;n--)e[n]===t&&e.splice(n,1)},e.clone=function(n){return Array.isArray(n)?n.map(e.clone):e.isObject(n)?Object.keys(n).reduce((function(r,i){var a;return t(t({},r),((a={})[i]=e.clone(n[i]),a))}),{}):n}),v9;var e,t}function sRe(){return iRe||(iRe=1,function(e){Object.defineProperty(e,"__esModule",{value:!0});var t=y9();e.DEFAULT_TIME_GROW_FACTOR=2.718281828459045,e.DEFAULT_TIME_JITTER=.11962656472,e.ExponentialTime=function(){function n(n,r,i,a){i===void 0&&(i=e.DEFAULT_TIME_GROW_FACTOR),a===void 0&&(a=e.DEFAULT_TIME_JITTER),this._initialTime=n,this._maxTime=r,this._growFactor=i,this._jitterFactor=a,t.assert(this._initialTime>0,`Initial delay must be positive`),t.assert(this._maxTime>0,`Delay upper bound must be positive`),t.assert(this._growFactor>=0,`Ratio must be non-negative`),t.assert(this._jitterFactor>=0,`Jitter factor must be non-negative`),this.reset()}return n.prototype.reset=function(){this._incrementCount=0,this._currentTime=Math.round(this._initialTime*(1+Math.random()*this._jitterFactor))},n.prototype.getTime=function(){return this._currentTime},n.prototype.getIncrementCount=function(){return this._incrementCount},n.prototype.calculateNext=function(){var e=this._currentTime*this._growFactor;return e>this._maxTime&&(e=this._maxTime),this._jitterFactor<1e-5?this._currentTime=e:this._currentTime=Math.round(Math.random()*e*this._jitterFactor+e),this._currentTime<this._initialTime&&(this._currentTime=this._initialTime),this._currentTime>this._maxTime&&(this._currentTime=this._maxTime),this._incrementCount++,this._currentTime},n.prototype.getTimeAndCalculateNext=function(){var e=this.getTime();return this.calculateNext(),e},n}()}(oRe)),oRe}var cRe,lRe,uRe,dRe,fRe,b9={},x9={};function pRe(){return cRe||(cRe=1,function(e){var t,n=x9&&x9.__extends||(t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},t(e,n)},function(e,n){function r(){this.constructor=e}t(e,n),e.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}),r=x9&&x9.__assign||function(){return r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},r.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var i,a,o=R5(),s=y9(),c=sRe();function l(e){return!!e&&e.indexOf(`application/json`)===0}function u(e){return!!e&&e.indexOf(`application/x-www-form-urlencoded`)===0}function d(e){return!!e&&e.indexOf(`multipart/form-data`)===0}function f(e,t){return t.canceled||!t.statusCode||t.statusCode>=400&&t.statusCode<600?a.DoNotRetry:a.RetryCountedWithBackoff}(function(e){e[e.DontCare=0]=`DontCare`,e[e.Low=1]=`Low`,e[e.Normal=2]=`Normal`,e[e.High=3]=`High`,e[e.Critical=4]=`Critical`})(i=e.WebRequestPriority||={}),function(e){e[e.DoNotRetry=0]=`DoNotRetry`,e[e.RetryUncountedImmediately=1]=`RetryUncountedImmediately`,e[e.RetryUncountedWithBackoff=2]=`RetryUncountedWithBackoff`,e[e.RetryCountedWithBackoff=3]=`RetryCountedWithBackoff`,e[e.PauseUntilResumed=4]=`PauseUntilResumed`}(a=e.ErrorHandlingType||={}),e.DefaultOptions={priority:i.Normal},e.SimpleWebRequestOptions={MaxSimultaneousRequests:5,HungRequestCleanupIntervalMs:1e4,setTimeout:function(e,t){return setTimeout(e,t)},clearTimeout:function(e){return clearTimeout(e)}},e.DefaultErrorHandler=f;var p,m=[],h=[],g=[],_=0,v=0,y=function(){function t(t,n,i,a,o){this._action=t,this._url=n,this.options=i,this._getHeaders=a,this._blockRequestUntil=o,this._aborted=!1,this._timedOut=!1,this._paused=!1,this._created=Date.now(),this._finishHandled=!1,this._retryExponentialTime=new c.ExponentialTime(1e3,3e5),this._options=r(r({},e.DefaultOptions),i)}return t.prototype.getPriority=function(){return this._options.priority||i.DontCare},t.checkQueueProcessing=function(){for(var t=function(){var t=m.shift();h.push(t),(t._blockRequestUntil&&t._blockRequestUntil()||o.Resolved()).finally((function(){s.remove(h,t)})).then((function(){g.length<e.SimpleWebRequestOptions.MaxSimultaneousRequests&&!t._aborted?(g.push(t),b._scheduleHungRequestCleanupIfNeeded(),t._fire()):t._enqueue()}),(function(e){t._respond(`_blockRequestUntil rejected: `+e)}))};m.length>0&&g.length<e.SimpleWebRequestOptions.MaxSimultaneousRequests;)t()},t._scheduleHungRequestCleanupIfNeeded=function(){g.length>0&&p===void 0?p=e.SimpleWebRequestOptions.setTimeout(this._hungRequestCleanupTimerCallback,e.SimpleWebRequestOptions.HungRequestCleanupIntervalMs):g.length===0&&p&&(e.SimpleWebRequestOptions.clearTimeout(p),p=void 0)},t.prototype._removeFromQueue=function(){s.remove(g,this),s.remove(m,this)},t.prototype._assertAndClean=function(e,t){e||(this._removeFromQueue(),console.error(t),s.assert(e,t))},t.prototype._fire=function(){var n=this;this._xhr=new XMLHttpRequest,this._xhrRequestHeaders={};var r=s.attempt((function(){n._xhr.open(n._action,n._url,!0)}));if(r)this._respond(r.toString());else{if(this._options.timeout){var i=v;i!==3&&(this._assertAndClean(!this._requestTimeoutTimer,`Double-fired requestTimeoutTimer`),this._requestTimeoutTimer=e.SimpleWebRequestOptions.setTimeout((function(){n._requestTimeoutTimer=void 0,n._timedOut=!0,n.abort()}),this._options.timeout)),(i===3||i<=1)&&(this._xhr.timeout=this._options.timeout,this._xhr.ontimeout=function(){v=3,i===3&&(n._timedOut=!0,n._aborted=!0,n._respond(`TimedOut`))})}var a=_;a===3?this._options.streamingDownloadProgress&&(this._xhr.onreadystatechange=function(){n._xhr&&n._xhr.readyState===3&&n._options.streamingDownloadProgress&&!n._aborted&&n._options.streamingDownloadProgress(n._xhr.responseText)}):(a===0&&(_=1),this._xhr.onreadystatechange=function(){n._xhr&&(n._xhr.readyState!==3||!n._options.streamingDownloadProgress||n._aborted?n._xhr.readyState===4&&(a===0&&_===1&&e.SimpleWebRequestOptions.setTimeout((function(){_!==3&&(_=2)}),1e4),n._respond()):n._options.streamingDownloadProgress(n._xhr.responseText))}),a!==2&&(this._xhr.onload=function(){_=3,a===3&&n._respond()},this._xhr.onerror=function(){_=3,a===3&&n._respond()}),this._xhr.onabort=function(){n._aborted=!0,n._respond(`Aborted`)},this._xhr.upload&&this._options.onProgress&&(this._xhr.upload.onprogress=this._options.onProgress);var o=this._options.acceptType||`json`,c=this._options.customResponseType||t._getResponseType(o),l=s.attempt((function(){n._xhr.responseType=c}));if(l&&c!==`json`)throw l;b._setRequestHeader(this._xhr,this._xhrRequestHeaders,`Accept`,t.mapContentType(o)),this._xhr.withCredentials=!!this._options.withCredentials;var u=this.getRequestHeaders(),d={};if(Object.keys(u).forEach((function(e){var t=u[e],r=e.toLowerCase();r===`content-type`?n._assertAndClean(!1,`Don't set Content-Type with options.headers -- use it with the options.contentType property`):r===`accept`?n._assertAndClean(!1,`Don't set Accept with options.headers -- use it with the options.acceptType property`):(n._assertAndClean(!d[r],`Setting duplicate header key: `+d[r]+` and `+e),t==null?console.warn(`Tried to set header "`+e+`" on request with "`+t+`" value, header will be dropped`):(d[r]=!0,b._setRequestHeader(n._xhr,n._xhrRequestHeaders,e,t)))})),this._options.sendData){var f=t.mapContentType(this._options.contentType||`json`);b._setRequestHeader(this._xhr,this._xhrRequestHeaders,`Content-Type`,f);var p=t.mapBody(this._options.sendData,f);this._xhr.send(p)}else this._xhr.send()}},t._setRequestHeader=function(e,t,n,r){e.setRequestHeader(n,r),t[n]=r},t.mapContentType=function(e){return e===`json`?`application/json`:e===`form`?`application/x-www-form-urlencoded`:e},t.mapBody=function(e,t){if(l(t)){if(!s.isString(e))return JSON.stringify(e)}else if(u(t)){if(!s.isString(e)&&s.isObject(e)){var n=e;return Object.keys(n).map((function(e){return encodeURIComponent(e)+(n[e]?`=`+encodeURIComponent(n[e].toString()):``)})).join(`&`)}}else if(d(t)){if(s.isObject(e)){var r=new FormData,i=e;return Object.keys(i).forEach((function(e){return r.append(e,i[e])})),r}s.assert(!1,`contentType multipart/form-data must include an object as sendData`)}return e},t.prototype.setUrl=function(e){this._url=e},t.prototype.setHeader=function(e,t){this._options.augmentHeaders||(this._options.augmentHeaders={}),t?this._options.augmentHeaders[e]=t:delete this._options.augmentHeaders[e]},t.prototype.getRequestHeaders=function(){var e={};return!this._getHeaders||this._options.overrideGetHeaders||this._options.headers||(e=r(r({},e),this._getHeaders())),this._options.overrideGetHeaders&&(e=r(r({},e),this._options.overrideGetHeaders)),this._options.headers&&(e=r(r({},e),this._options.headers)),this._options.augmentHeaders&&(e=r(r({},e),this._options.augmentHeaders)),e},t.prototype.getOptions=function(){return s.clone(this._options)},t.prototype.setPriority=function(e){this._options.priority!==e&&(this._options.priority=e,this._paused||this._xhr||(s.remove(m,this),this._enqueue()))},t.prototype.resumeRetrying=function(){this._paused?(this._paused=!1,this._enqueue()):s.assert(!1,`resumeRetrying() called but not paused!`)},t.prototype._enqueue=function(){var e=this;if(!this._aborted&&!(g.indexOf(this)>=0||h.indexOf(this)>=0||m.indexOf(this)>=0)){var n=m.findIndex((function(t){return t.getPriority()===e.getPriority()&&t._created>e._created||t.getPriority()<e.getPriority()}));n>-1?m.splice(n,0,this):m.push(this),t.checkQueueProcessing()}},t._getResponseType=function(e){return e===`blob`?`arraybuffer`:e===`text/xml`||e===`application/xml`?`document`:e===`text/plain`?`text`:`json`},t._hungRequestCleanupTimerCallback=function(){p=void 0,g.filter((function(e){return!(!e._xhr||e._xhr.readyState!==4)&&(console.warn(`SimpleWebRequests found a completed XHR that hasn't invoked it's callback functions, manually responding`),!0)})).forEach((function(e){e._respond()})),b._scheduleHungRequestCleanupIfNeeded()},t}();e.SimpleWebRequestBase=y;var b=function(t){function r(e,n,r,i,a){return t.call(this,e,n,r,i,a)||this}return n(r,t),r.prototype.abort=function(){this._aborted?s.assert(!1,`Already aborted `+this._action+` request to `+this._url):(this._aborted=!0,this._retryTimer&&=(e.SimpleWebRequestOptions.clearTimeout(this._retryTimer),void 0),this._requestTimeoutTimer&&=(e.SimpleWebRequestOptions.clearTimeout(this._requestTimeoutTimer),void 0),this._deferred?(this._respond(`Aborted`),this._xhr&&this._xhr.abort()):s.assert(!1,`Haven't even fired start() yet -- can't abort`))},r.prototype.start=function(){var e=this;return this._deferred?(s.assert(!1,`WebRequest already started`),o.Rejected(`WebRequest already started`)):(this._deferred=o.Defer(),this._deferred.onCancel((function(){e.abort()})),this._enqueue(),this._deferred.promise())},r.prototype._respond=function(t){var n=this;if(!this._finishHandled){this._finishHandled=!0,this._removeFromQueue(),this._retryTimer&&=(e.SimpleWebRequestOptions.clearTimeout(this._retryTimer),void 0),this._requestTimeoutTimer&&=(e.SimpleWebRequestOptions.clearTimeout(this._requestTimeoutTimer),void 0);var r,i=0;if(this._xhr)try{i=this._xhr.status,r=this._xhr.statusText||t}catch{}else r=t||`Browser Error - Possible CORS or Connectivity Issue`;var o,c,u={};if(this._xhr){if((this._xhr.getAllResponseHeaders()||``).split(/\r?\n/).forEach((function(e){if(e.length!==0){var t=e.indexOf(`:`);t===-1?u[e]=``:u[e.substr(0,t).toLowerCase()]=e.substr(t+1).trim()}})),!u[`content-type`]){var d=this._xhr.getResponseHeader(`content-type`);d&&(u[`content-type`]=d)}if(o=this._xhr.response,u[`content-type`]&&l(u[`content-type`])&&(!o||!s.isObject(o))&&(this._xhr.responseType===`text`||this._xhr.responseType===``)&&this._xhr.responseText)try{o=JSON.parse(this._xhr.responseText)}catch(e){c=e,console.warn(`Failed to parse XHR JSON response`)}}if(this._xhr&&this._xhr.readyState===4&&(i>=200&&i<300||i===304)){var p={url:this._xhr.responseURL||this._url,method:this._action,requestOptions:this._options,requestHeaders:this._xhrRequestHeaders||{},statusCode:i,statusText:r,headers:u,body:o,responseParsingException:c};this._deferred.resolve(p)}else{var m={url:(this._xhr?this._xhr.responseURL:void 0)||this._url,method:this._action,requestOptions:this._options,requestHeaders:this._xhrRequestHeaders||{},statusCode:i,statusText:r,headers:u,body:o,canceled:this._aborted,timedOut:this._timedOut,responseParsingException:c};this._options.augmentErrorResponse&&this._options.augmentErrorResponse(m);var h=this._options.customErrorHandler?this._options.customErrorHandler(this,m):f(this,m);h!==a.DoNotRetry&&(this._options.retries&&this._options.retries>0||h===a.PauseUntilResumed||h===a.RetryUncountedImmediately||h===a.RetryUncountedWithBackoff)?(h===a.RetryCountedWithBackoff&&this._options.retries--,this._requestTimeoutTimer&&=(e.SimpleWebRequestOptions.clearTimeout(this._requestTimeoutTimer),void 0),this._aborted=!1,this._timedOut=!1,this._finishHandled=!1,this._xhr&&(this._xhr.onabort=null,this._xhr.onerror=null,this._xhr.onload=null,this._xhr.onprogress=null,this._xhr.onreadystatechange=null,this._xhr.ontimeout=null,this._xhr=void 0,this._xhrRequestHeaders=void 0),h===a.PauseUntilResumed?this._paused=!0:h===a.RetryUncountedImmediately?this._enqueue():this._retryTimer=e.SimpleWebRequestOptions.setTimeout((function(){n._retryTimer=void 0,n._enqueue()}),this._retryExponentialTime.getTimeAndCalculateNext())):this._deferred.reject(m)}y.checkQueueProcessing()}},r}(y);e.SimpleWebRequest=b}(x9)),x9}function mRe(){if(lRe)return b9;lRe=1;var e=b9&&b9.__assign||function(){return e=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},e.apply(this,arguments)};Object.defineProperty(b9,"__esModule",{value:!0});var t=y9(),n=pRe();return b9.GenericRestClient=function(){function r(e){this._defaultOptions={excludeEndpointUrl:!1,withCredentials:!1,retries:0},this._endpointUrl=e}return r.prototype._performApiCall=function(r,i,a,o){var s=this;o===void 0&&(o={});var c=e(e({},this._defaultOptions),o);a&&(c.sendData=a),c.eTag&&(c.augmentHeaders||={},c.augmentHeaders[`If-None-Match`]=c.eTag),c.contentType||=t.isString(c.sendData)?`form`:`json`;var l=c.excludeEndpointUrl?r:this._endpointUrl+r;return new n.SimpleWebRequest(i,l,c,(function(){return s._getHeaders(c)}),(function(){return s._blockRequestUntil(c)})).start().then((function(e){return s._processSuccessResponse(e),e}))},r.prototype._getHeaders=function(e){return{}},r.prototype._blockRequestUntil=function(e){},r.prototype._processSuccessResponse=function(e){},r.prototype.performApiGet=function(e,t){return this.performApiGetDetailed(e,t).then((function(e){return e.body}))},r.prototype.performApiGetDetailed=function(e,t){return this._performApiCall(e,`GET`,void 0,t)},r.prototype.performApiPost=function(e,t,n){return this.performApiPostDetailed(e,t,n).then((function(e){return e.body}))},r.prototype.performApiPostDetailed=function(e,t,n){return this._performApiCall(e,`POST`,t,n)},r.prototype.performApiPatch=function(e,t,n){return this.performApiPatchDetailed(e,t,n).then((function(e){return e.body}))},r.prototype.performApiPatchDetailed=function(e,t,n){return this._performApiCall(e,`PATCH`,t,n)},r.prototype.performApiPut=function(e,t,n){return this.performApiPutDetailed(e,t,n).then((function(e){return e.body}))},r.prototype.performApiPutDetailed=function(e,t,n){return this._performApiCall(e,`PUT`,t,n)},r.prototype.performApiDelete=function(e,t,n){return this.performApiDeleteDetailed(e,t,n).then((function(e){return e.body}))},r.prototype.performApiDeleteDetailed=function(e,t,n){return this._performApiCall(e,`DELETE`,t,n)},r}(),b9}function hRe(){return uRe||(uRe=1,function(e){function t(t){for(var n in t)e.hasOwnProperty(n)||(e[n]=t[n])}Object.defineProperty(e,"__esModule",{value:!0}),t(sRe()),t(mRe()),t(pRe())}(aRe)),aRe}function gRe(){return fRe?dRe:(fRe=1,dRe=hRe())}var _Re,vRe,yRe,bRe,S9={},C9={};function xRe(){return _Re?C9:(_Re=1,Object.defineProperty(C9,"__esModule",{value:!0}),C9.TelemetryEventBase=function(){function e(){}return e.prototype.getAttributes=function(){return{Source:`ecs_client`}},e}(),C9)}function SRe(){if(vRe)return S9;vRe=1;var e,t=S9&&S9.__extends||(e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},e(t,n)},function(t,n){function r(){this.constructor=t}e(t,n),t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)});return Object.defineProperty(S9,"__esModule",{value:!0}),S9.EcsConfigFetchResponse=function(e){function n(t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_){var v=e.call(this)||this;return v._responseTime=t,v._responseCode=n,v._fetchAttempts=r,v._hasValidToken=i,v._serverEndpoint=a,v._fetchDurationValid=o,v._cacheAvailable=s,v._responseSize=c,v._configAge=l,v._configExpired=u,v._fetchStart=d,v._fetchEnd=f,v._isUserConfig=p,v._etag=m,v._timedOut=h,v._responseParsingException=g,v._errorMessage=_,v}return t(n,e),n.prototype.getEventName=function(){return`ecs_tsclient_fetch_config`},n.prototype.getAttributes=function(){var t=e.prototype.getAttributes.call(this);return t.fetch_delay_ms=this._responseTime,t.fetch_response_code=this._responseCode,t.fetch_attempts=this._fetchAttempts,t.authenticated_user=this._hasValidToken,t.url=this._serverEndpoint,t.fetch_duration_valid=this._fetchDurationValid,t.cache_available=this._cacheAvailable,t.response_size=this._responseSize,t.config_age=this._configAge,t.config_expired=this._configExpired,t.fetch_start=this._fetchStart,t.fetch_end=this._fetchEnd,t.is_user_config=this._isUserConfig,this._etag&&(t.fetched_etag=this._etag),this._timedOut!==void 0&&(t.fetch_timed_out=this._timedOut),this._responseParsingException&&(t.fetch_response_parsing_error=this._responseParsingException.message),this._errorMessage&&(t.fetch_error_message=this._errorMessage),t},n}(xRe().TelemetryEventBase),S9}function CRe(){if(yRe)return _9;yRe=1;var e,t=_9&&_9.__extends||(e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},e(t,n)},function(t,n){function r(){this.constructor=t}e(t,n),t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}),n=_9&&_9.__assign||function(){return n=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},n.apply(this,arguments)};Object.defineProperty(_9,"__esModule",{value:!0});var r,i,a=gRe(),o=R5(),s=m9(),c=SRe(),l=1728e5,u=18e5,d=31536e6,f=3e4,p=function(e){function n(t,n,r,i,a,o,s,c){var l=e.call(this,t)||this;l._config=n,l._skypeTokenData=r,l._appActiveData=i,l._allowBackgroundFetchData=a,l._etag=o,l._getUserConfig=s;var u=l._config.getConfig();if(l._apiPath=u.clientTeam?`/config/v1/`+u.clientName+`/`+u.clientVersion+`/`+u.clientTeam:`/config/v1/`+u.clientName+`/`+u.clientVersion,c){var d=Object.keys(c).map((function(e){return encodeURIComponent(e)+`=`+encodeURIComponent(c[e].toString())}));d&&(l._apiPath+=`?`+d.join(`&`))}return l}return t(n,e),n.prototype._blockRequestUntil=function(e){var t=this;if(this._getUserConfig&&!this._skypeTokenData.isSkypeTokenValid()&&console.log(`ECS - Delaying User config fetch until we have a valid SkypeToken`),!this._appActiveData.isAppActive()&&!this._allowBackgroundFetchData.isBackgroundFetchAllowed()){var n=this._getUserConfig?`User config`:`config`;console.log(`ECS - Delaying `+n+` fetch until the app is active (or background fetch is allowed)`)}return o.race([this._appActiveData.waitForAppActive(),this._allowBackgroundFetchData.waitForBackgroundFetchAllowed()]).then((function(){if(t._getUserConfig)return t._skypeTokenData.waitForValidSkypeToken()})).then((function(){i=Date.now()}))},n.prototype._getHeaders=function(){var e={};return this._etag&&(e[`If-None-Match`]=this._etag),this._getUserConfig&&(e.Authorization=this._skypeTokenData.getSkypeToken()),e},n.prototype.getConfig=function(){var t=this._config.getConfig().fetchTimeout;return t!==void 0&&(t<0?t=0:t>0&&t<f&&(t=f)),e.prototype.performApiGetDetailed.call(this,this._apiPath,{timeout:t})},n}(a.GenericRestClient);return _9.default=function(){function e(e,t,n,r,i){this._config=e,this._skypeTokenData=t,this._appActiveData=n,this._allowBackgroundFetchData=r,this._telemetryManager=i,this._ecsFailureBackoffTimer=new a.ExponentialTime(1e3,3e5),this._cacheMaxAgeRegex=/.*max-age=(\d+).*/gi,this._serverIndex=NaN}return e.prototype.getConfig=function(e,t,r){var a=this,l=this._config.getConfig().hosts;if((isNaN(this._serverIndex)||this._serverIndex>l.length-1)&&(this._serverIndex=Math.floor(Math.random()*l.length)),!l||!l.length)return o.Rejected(Error(`no configuration service endpoint`));var u=o.Defer(),d=0,f=function(){var m=e&&e.eTag?e.eTag:void 0,h=new p(l[a._serverIndex],a._config,a._skypeTokenData,a._appActiveData,a._allowBackgroundFetchData,m,t,r);d++,h.getConfig().then((function(r){var f=r.headers.etag,p=r.headers.expires;r.body&&r.body.Headers&&(f||=r.body.Headers.ETag,p||=r.body.Headers.Expires);var h=a._calculateResponseTimeInfo(e);if(!f||!p)return console.warn(`ECS - Service returned an empty ETag or Expiration header: `+JSON.stringify(r)),o.Rejected({timedOut:!1,responseParsingException:Error(`ECS Service returned empty ETag or Expiration header`),responseCode:r.statusCode});var g,_=new Date(a._calculateExpirationDate(r.headers)).getTime();if(r.statusCode===304&&e)(g=n({},e)).configType=t?s.EcsConfigType.User:s.EcsConfigType.Default,g.eTag=f,g.expiration=_,g.cacheUpdateTime=h.lastResponseTime,g.lastFetchTokenHash=a._skypeTokenData.getSkypeTokenHash(r.requestHeaders.Authorization);else{if(typeof r.body!=`object`)return console.warn(`ECS - Service returned invalid response `+JSON.stringify(r)),o.Rejected({timedOut:!1,responseParsingException:Error(`ECS Service returned invalid response body`),responseCode:r.statusCode});g={config:r.body,configType:t?s.EcsConfigType.User:s.EcsConfigType.Default,eTag:f,expiration:_,cacheUpdateTime:i,lastFetchTokenHash:a._skypeTokenData.getSkypeTokenHash(r.requestHeaders.Authorization),appVersion:a._config.getConfig().clientVersion}}a._telemetryManager.sendTelemetryEvent(new c.EcsConfigFetchResponse(h.fetchDelayMs,r.statusCode,d,a._skypeTokenData.isSkypeTokenValid(),l[a._serverIndex],h.fetchDurationValid,!!m,JSON.stringify(r).length,h.cacheAge,!(e&&e.expiration-Date.now()>0),i,h.lastResponseTime,t,f)),a._ecsFailureBackoffTimer.reset(),u.resolve(g)})).catch((function(n){var r={timedOut:n&&n.timedOut||!1,responseParseError:n&&n.responseParsingException,responseCode:n&&n.statusCode||0,message:a._getErrorMessage(n)};console.error(`ECS - Service request failed to return a response (timedOut: `+r.timedOut+`, responseParseError: `+r.responseParseError+`)`);var o=a._calculateResponseTimeInfo(e);a._telemetryManager.sendTelemetryEvent(new c.EcsConfigFetchResponse(o.fetchDelayMs,r.responseCode,d,a._skypeTokenData.isSkypeTokenValid(),l[a._serverIndex],o.fetchDurationValid,!!m,0,o.cacheAge,!(e&&e.expiration-Date.now()>0),i,o.lastResponseTime,t,void 0,r.timedOut,r.responseParseError,r.message));var s=a._config.getConfig().fetchAttemptMax;s&&d>s||setTimeout((function(){f()}),a._ecsFailureBackoffTimer.getTimeAndCalculateNext())}))};return f(),u.promise()},e.prototype._calculateExpirationDate=function(e){var t=Date.now()+l;if(e.date&&e.expires){var n=new Date(e.date).getTime(),r=Date.now()-n,i=new Date(e.expires).getTime();return isNaN(i)?t:Math.min(t,i+r)}var a=this._cacheMaxAgeRegex.exec(e[`cache-control`]);return this._cacheMaxAgeRegex.lastIndex=0,a&&a.length===2?Math.min(t,Date.now()+1e3*Number(a[1])):Date.now()+u},e.prototype._calculateResponseTimeInfo=function(e){var t=(r=Date.now())-i;return{lastResponseTime:r,fetchDelayMs:t,fetchDurationValid:!(t<0||t>d),cacheAge:e?r-e.cacheUpdateTime:0}},e.prototype._getErrorMessage=function(e){if(e)return typeof e==`string`?e:typeof e==`object`&&(e.statusText||e.message)?e.statusText||e.message:void 0},e}(),_9}function wRe(){if(bRe)return g9;bRe=1,Object.defineProperty(g9,"__esModule",{value:!0});var e=m9(),t=CRe();return g9.default=function(){function n(n,r,i,a,o,s){var c=this;this._config=n,this._skypeTokenData=r,this._cache=i,this._isFetchingSettings={},this._pendingFetch={},this._pendingTimers={},this._subscriptionToken=null,this._paused=!1,this._fetchEcsSettingsIfNeeded=function(t){var n=c._config.getConfig(),r=c._cache.getEcsConfigByType(t);if(n.configsToFetch.indexOf(t)!==-1&&!c._isFetchingSettings[t])if(r||!c._pendingFetch[t]){var i=r?r.expiration-Date.now():-1;i<=0||r&&t===e.EcsConfigType.User&&c._skypeTokenData.isSkypeTokenValid()&&r.lastFetchTokenHash!==c._skypeTokenData.getSkypeTokenHash(c._skypeTokenData.getSkypeToken())?c._fetchSkypeEcsSettings(t):n.Killswitches?.isSkypeTokenDataLeakFixEnabled?(c._pendingTimers[t]>0&&clearTimeout(c._pendingTimers[t]),c._pendingTimers[t]=window.setTimeout((function(){return c._fetchEcsSettingsIfNeeded(t)}),i)):window.setTimeout((function(){return c._fetchEcsSettingsIfNeeded(t)}),i)}else c._fetchSkypeEcsSettings(t)},this._fetchSkypeEcsSettings=function(t,n){n===void 0&&(n=!1),c._isFetchingSettings[t]||c._paused&&!n?c._pendingFetch[t]=!0:(c._pendingFetch[t]=!1,c._isFetchingSettings[t]=!0,c._config.getConfig().getEcsParameters().catch((function(){return console.warn(`ECS - Failed to fetch ECS fetching parameters`),{}})).then((function(n){return c._ecsClient.getConfig(c._cache.getEcsConfig(),t===e.EcsConfigType.User,n)})).then((function(e){console.log(`ECS - Config fetch complete`),c._isFetchingSettings[t]=!1,c._cache.putConfig(e),c._fetchEcsSettingsIfNeeded(t)})))},this._ecsClient=new t.default(this._config,this._skypeTokenData,a,o,s)}return n.prototype.initialize=function(){var t=this;this.updateConfigsToFetch(),this._subscriptionToken=this._skypeTokenData.skypeTokenChanged.subscribe((function(){return t._fetchEcsSettingsIfNeeded(e.EcsConfigType.User)}))},n.prototype.dispose=function(){var e,t=this._config.getConfig();if(t.Killswitches?.isSkypeTokenDataLeakFixEnabled){for(var n=0,r=t.configsToFetch;n<r.length;n++){var i=r[n];clearTimeout(this._pendingTimers[i]),this._pendingTimers[i]=0}(e=this._subscriptionToken)==null||e.unsubscribe(),this._subscriptionToken=null,this._skypeTokenData.skypeTokenChanged.dispose()}},n.prototype.updateConfigsToFetch=function(){for(var e=this._config.getConfig(),t=0,n=e.configsToFetch;t<n.length;t++)(a=n[t])in this._isFetchingSettings||(this._isFetchingSettings[a]=!1),a in this._isFetchingSettings||(this._pendingFetch[a]=!1);for(var r=0,i=e.configsToFetch;r<i.length;r++){var a=i[r],o=this._cache.getEcsConfigByType(a);!o||o.appVersion&&o.appVersion!==e.clientVersion?this._fetchSkypeEcsSettings(a,!0):this._fetchEcsSettingsIfNeeded(a)}},n.prototype.requestUpdate=function(){for(var e=0,t=this._config.getConfig().configsToFetch;e<t.length;e++){var n=t[e];this._fetchSkypeEcsSettings(n)}},n.prototype.pause=function(){this._paused=!0},n.prototype.resume=function(){this._paused=!1;for(var e=0,t=this._config.getConfig().configsToFetch;e<t.length;e++){var n=t[e];this._fetchEcsSettingsIfNeeded(n)}},n}(),g9}var TRe,w9={};function ERe(){if(TRe)return w9;TRe=1,Object.defineProperty(w9,"__esModule",{value:!0});var e=p9,t=R5();return w9.default=function(){function n(){this.skypeTokenChanged=new e.default}return n.prototype.putSkypeTokenData=function(e){if(this._data=e,this.isSkypeTokenValid()&&this.skypeTokenChanged.fire(),this.isSkypeTokenValid()&&this._validSkypeTokenDeferral){var t=this._validSkypeTokenDeferral;this._validSkypeTokenDeferral=void 0,t.resolve(void 0)}},n.prototype.isSkypeTokenValid=function(){var e=this._data;return!!e&&!!e.skypeToken&&e.skypeTokenExpiration>Date.now()},n.prototype.getSkypeToken=function(){var e=this._data;if(!e||!e.skypeToken)throw Error(`No Skype Token provided`);return e.skypeToken},n.prototype.getSkypeTokenHash=function(e){return e===void 0?0:e.split(``).reduce((function(e,t){return(101*e+t.charCodeAt(0))%999727999}),e.length)},n.prototype.waitForValidSkypeToken=function(){return this.isSkypeTokenValid()?t.Resolved():(this._validSkypeTokenDeferral||=t.Defer(),this._validSkypeTokenDeferral.promise())},n}(),w9}var DRe,ORe,T9={};function kRe(){if(DRe)return T9;DRe=1,Object.defineProperty(T9,"__esModule",{value:!0});var e=p9;return T9.default=function(){function t(t){this._cache=t,this.telemetryEventAdded=new e.default}return t.prototype.sendTelemetryEvent=function(e){var n=e.getEventName(),r=e.getAttributes(),i=!1,a=this._cache.getEcsConfig();if(a){if(t._containsEcsClientTelemetryConfig(a.config)){var o=a.config.ECSCONFIG;o&&o.ecsClientTelemetry&&(i=!!o.ecsClientTelemetry[n])}}else console.warn(`No previously cached ECS telemetry config exists - fallback to sending event`),i=!0;i&&this.telemetryEventAdded.fire(n,r)},t._containsEcsClientTelemetryConfig=function(e){return!!e&&!!e.ECSCONFIG&&!!e.ECSCONFIG.ecsClientTelemetry},t}(),T9}function ARe(){if(ORe)return l9;ORe=1,Object.defineProperty(l9,"__esModule",{value:!0});var e=KLe(),t=JLe(),n=eRe(),r=nRe();l9.Models=m9();var i=wRe(),a=ERe(),o=kRe();return l9.default=function(){function s(){this._allowBackgroundFetchData=new e.default,this._appActiveData=new t.default,this._config=new r.default,this._cache=new n.default(this._config),this._skypeTokenData=new a.default,this._telemetryManager=new o.default(this._cache),this._scheduler=new i.default(this._config,this._skypeTokenData,this._cache,this._appActiveData,this._allowBackgroundFetchData,this._telemetryManager),this.telemetryEventAdded=this._telemetryManager.telemetryEventAdded,this.configUpdated=this._cache.configUpdated}return s.prototype.initialize=function(e){var t=this;return this._config.initialize(e),this._skypeTokenData.putSkypeTokenData(e.initialSkypeTokenData),this._appActiveData.putAppActive(e.initialAppActiveState),this._cache.initialize().then((function(){t._scheduler.initialize()}))},s.prototype.dispose=function(){var e;(e=this._config.getConfig().Killswitches)!=null&&e.isSkypeTokenDataLeakFixEnabled&&this._scheduler.dispose()},s.prototype.getConfig=function(){return this._cache.getEcsConfig()},s.prototype.getConfigType=function(){var e=this._cache.getEcsConfig();if(e)return e.configType},s.prototype.requestUpdate=function(){this._scheduler.requestUpdate()},s.prototype.pause=function(){this._scheduler.pause()},s.prototype.resume=function(){this._scheduler.resume()},s.prototype.setAllowBackgroundFetch=function(e){this._allowBackgroundFetchData.putBackgroundFetchAllowed(e)},s.prototype.useSkypeToken=function(e,t){this._skypeTokenData.putSkypeTokenData({skypeToken:e,skypeTokenExpiration:t})},s.prototype.setAppActive=function(e){this._appActiveData.putAppActive(e)},s.prototype.setConfigsToFetch=function(e){var t=this;return this._config.setConfigsToFetch(e),this._cache.updateConfigsToFetch().then((function(){t._scheduler.updateConfigsToFetch()}))},s.prototype.setFetchTimeout=function(e){this._config.setFetchTimeout(e)},s}(),l9}var E9,D9=ARe(),jRe=kG(D9),MRe=R5();function NRe(e,t){let n={},r=e.OsName??``,i=e.OsVer??``,a=r&&i?`${r}-${i}`:``;return n.CLRelease=`${e.CLRelease??``}`,n.BrowserName=Q2.toLower(`${e.BrowserName??``}`),n.BrowserEngine=`${e.BrowserEngine??``}`,n.BrowserVersion=`${e.BrowserVersion??``}`,n.FormFactor=`${e.FormFactor??``}`,n.IdentityType=$0.Consumer,n.Cloud=J0.Public,n.OSVer=Q2.toLower(a),n.BrowserName===`edge`&&(n.BrowserName=`edgeanaheim`),t&&(n.Cloud=t.cloudType,n.IdentityType=t.identityType),Q2.omitBy(n,(e=>e==null||e===``))}function PRe(e,t){let n={[J0.Public]:Z0.Public_EcsServer_Url,[J0.Dod]:Z0.Dod_EcsServer_Url,[J0.GccHigh]:Z0.GccHigh_EcsServer_Url,[J0.AirGap08]:Z0.AirGap08_EcsServer_Url,[J0.AirGap09]:Z0.AirGap09_EcsServer_Url},r=Z0.Public_EcsServer_Url;return t&&(r=t.identityType===$0.Enterprise?Z0.Enterprise_Ecs_ServerUrl:n[t.cloudType]??Z0.Public_EcsServer_Url),e?.proxyfyUrl(r)??r}(function(e){e.Default=`Default`,e.User=`User`})(E9||={});var FRe=class{constructor(e,t,n,r){this._isWBMediaClient=e,this._acsProxy=n,this._sourceTag=r,this._throttlingTimeoutHandle=0,this._eventEmitter=new w3.EventEmitter,this._logger=t.createChild(`EcsClient`)}_resetThrottlingTimeout(){this._throttlingTimeoutHandle&&=(window.clearTimeout(this._throttlingTimeoutHandle),0)}_resetEcsClient(){this._ecsClient&&=(this._ecsClient.configUpdated.dispose(),void 0)}async _fetchConfig(e){this._resetEcsClient(),this._resetThrottlingTimeout();let t=new jRe,n=e3();try{await t.initialize(e);let r=[],i=!1,a=0;t.configUpdated.subscribe((()=>{if(n.isPending())n.resolve();else{r.push(Date.now());let e=t.getConfig();if(e?.config){let t=e?.configType===D9.Models.EcsConfigType.User?E9.User:E9.Default;this._cachedConfig=e,this._eventEmitter.emit(`configUpdated`,{config:e?.config,fetchType:t,sourceTag:this._sourceTag})}let n=Z().ecsClient.throttling;r.length>n.triggerCount&&(r=r.slice(r.length-n.triggerCount));let o=r[r.length-1]-r[0];i?(r.length<n.triggerCount||o>=n.coolDownDuration)&&(i=!1,a=0,r=[],this._resetThrottlingTimeout()):r.length===n.triggerCount&&o<n.triggerDuration&&(i=!0),i&&(a=a===0?n.startingDelay:Math.min(Math.ceil(a*n.delayFactor),n.maxDelay),t.pause(),this._throttlingTimeoutHandle=window.setTimeout((()=>{this._throttlingTimeoutHandle=0,t.resume()}),a))}})),this._ecsClient=t,await n3((()=>n.promise),OCe);let o=t.getConfig();if(!o?.config)throw new Y({defaultError:J.INTERNAL.ECS_CONFIG_EMPTY});return this._cachedConfig=o,o.config}catch(e){throw n.reject(e),this._logger.error(`${e}`),e}}async fetchDefaultConfig(e,t){let n=`${this._isWBMediaClient?s2:o2}_${J2()}`,r={hosts:[PRe(this._acsProxy,t)],clientName:bSe,clientVersion:n,configsToFetch:[D9.Models.EcsConfigType.Default],getEcsParameters:()=>MRe.Resolved(e),initialAppActiveState:!0};return this._fetchConfig(r)}async fetchUserConfig(e,t,n){let r=`${this._isWBMediaClient?s2:o2}_${J2()}`,i=await n(),a=1e3*Xwe(i).exp,o={hosts:[PRe(this._acsProxy,t)],clientName:bSe,clientVersion:r,configsToFetch:[D9.Models.EcsConfigType.User],getEcsParameters:()=>MRe.Resolved(e),initialAppActiveState:!0,initialSkypeTokenData:{skypeToken:i,skypeTokenExpiration:a}};return this._fetchConfig(o)}get eTag(){return this._cachedConfig?.eTag??``}get sourceTag(){return this._sourceTag}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}dispose(){this._eventEmitter.removeAllListeners(),this._resetThrottlingTimeout(),this._resetEcsClient()}getConfigIds(e){return(this._cachedConfig?.config)?.ConfigIDs?.[e]}},IRe=class{constructor(e){this._telemetryLogManager=e,this._seq=0}sendAttemptEvent(e,t,n){this._seq++,this._telemetryLogManager.sendEvent({name:Q.acs_calling_config_fetched_attempt,tenant:d2,properties:{attemptTimestamp:e,ecsFetchType:t,correlationId:n,eventSeq:this._seq}})}sendSuccessEvent(e,t,n,r){let i=Date.now();this._seq++;let a=e===void 0?0:i-e;this._telemetryLogManager.sendEvent({name:Q.acs_calling_config_fetched_success,tenant:d2,properties:{...e===void 0?void 0:{attemptTimestamp:e},successTimestamp:i,deltaTimeInMs:a,ecsFetchType:t,correlationId:n,eventSeq:this._seq,ecsConfigIds_AcsCallingSDKWeb:r?.AcsCallingSDKWeb||``,ecsConfigIds_SkypeWebMedia:r?.SkypeWebMedia||``}})}sendFailureEvent(e,t,n,r){let i=Date.now();this._seq++;let a=e===void 0?0:i-e,o=r.message,s=K3(r);this._telemetryLogManager.sendEvent({name:Q.acs_calling_config_fetched_failure,tenant:d2,properties:{...e===void 0?void 0:{attemptTimestamp:e},failureTimestamp:i,deltaTimeInMs:a,ecsFetchType:t,correlationId:n,eventSeq:this._seq,failureReason:o,additionalDetails:{...s}}})}};function LRe(e,...t){Q2.merge(e,...t)}function RRe(e,t){let n={};try{n.CLRelease=H5.stackFactory.getVersion().build;let e=t8();n.BrowserName=e.name,n.BrowserEngine=e.engine,n.BrowserVersion=e.version,n.FormFactor=e.formFactor,n.IdentityType=$0.Consumer,n.Cloud=J0.Public,n.OSVer=`${n8()}-${lke()}`,t&&(n.Cloud=t.cloudType,n.IdentityType=t.identityType),n.CLRelease===`_TS_BUILD_VERSION_`?n.CLRelease=`9999.99`:n.CLRelease.match(/^\d+\.\d+\.\d+\.\d+$/)||delete n.CLRelease}catch(t){throw e.error(t),new Y({defaultError:J.CALL_STACK.SET_STACK_PARAMS,originalError:t})}return n}var O9=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},k9=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},A9=class{constructor(e,t,n,r,i,a,o,s,c=!1){if(this._baseStackDisposed=!1,this._userStackDisposed=!1,this._trouterStateChangedListenersRegistered=new Map,this._signalingAgentInitialized=!1,this._hardcodedEcsConfigApplied=!1,this._clientId=t,this.sdkDiagnosticInformation=r,this.logger=e.createChild(`CallStack`),this._telemetryLogManager=n,this._acsProxy=i,this._acsCustomRelayManager=a,this._vdi3Options=s,this._webcvProvider=new ELe,this._wasmvqeProvider=new jLe,this._isWBMediaClient=c,location.protocol!==`https:`&&location.protocol!==`file:`&&location.hostname!==`localhost`)throw new Y({defaultError:J.CALL_STACK.BAD_PROTOCOL});this._telemetryService=new TLe(this._telemetryLogManager),this._ecsTelemetryLogger=new IRe(n),this._ecsProvider=new t9(this.logger,this.sdkDiagnosticInformation,this._acsProxy),this._ecsClient=new FRe(this._isWBMediaClient,this.logger,this._acsProxy,`EcsClient`),this._videoEffectsStatusManager=new kLe,this._audioEffectsStatusManager=new ALe,o!==void 0&&(this._encodedStreamsWorkerProvider=new DLe(o))}getVdi3StateInfo(){return this._vdi3StateInfo}getClientId(){return this._clientId}getCaConfigBag(){return this._caConfigBag}getTrouterState(){let e=this._trouterService?.state()??this._shellTrouter?.state();return this.mapTsTrouterState(e)}getEcsConfigIds(){return this._ecsClientRdc?{AcsCallingSDKWeb:this._ecsClient?.getConfigIds(`AcsCallingSDKWeb`)??``,SkypeWebMedia:this._ecsClientRdc?.getConfigIds(`SkypeWebMedia`)??``}:{AcsCallingSDKWeb:this._ecsClient?.getConfigIds(`AcsCallingSDKWeb`)??``,SkypeWebMedia:this._ecsClient?.getConfigIds(`SkypeWebMedia`)??``}}isRegistered(){return this._trouterService?.isRegistered()??this._shellTrouter?.registeredState()??!1}onRegisteredChanged(e){this._trouterService?.onRegisteredChanged(e),this._shellTrouter?.on(`registeredChanged`,e)}offRegisteredChanged(e){this._trouterService?.offRegisteredChanged(e),this._shellTrouter?.off(`registeredChanged`,e)}onTrouterStateChanged(e){let t=(t,n)=>{e(this.mapTsTrouterState(t))};return this._trouterService?.onStateChanged(t),this._shellTrouter?.on(`stateChanged`,t),this._trouterStateChangedListenersRegistered.set(e,t),{listener:e,tsTrouterStateChangedListener:t}}offTrouterStateChanged(e){let t=this._trouterStateChangedListenersRegistered.get(e);if(t)return this._trouterService?.offStateChanged(t),this._shellTrouter?.off(`stateChanged`,t),this._trouterStateChangedListenersRegistered.delete(e),{listener:e,tsTrouterStateChangedListener:t}}mapTsTrouterState(e){let t=`Uninitialized`;if(e!==void 0)switch(e){case 0:t=`Unknown`;break;case 2:t=`Connected`;break;case 3:t=`Disconnected`;break;case 9:t=`Switching`}return t}get webcvProvider(){return this._webcvProvider}get wasmvqeProvider(){return this._wasmvqeProvider}get videoEffectsStatusManager(){return this._videoEffectsStatusManager}get audioEffectsStatusManager(){return this._audioEffectsStatusManager}async applyHardcodedEcsConfigAndSetStack(e,t){if(this._hardcodedEcsConfigApplied)return void this.logger.info(`Hardcoded ECS config already applied, skipping`);let n=Hwe();await this.updateConfig(n,t);let r=+new Date;await this._setStackConfig();let i=+new Date-r;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:K0(),operationName:e,durationInMs:i,operationPayload:{},resultCategories:[`Success`],resultSignature:200}),this._hardcodedEcsConfigApplied=!0}async createStackBase(e){if(this._createStackBaseWaitPromise)return this._createStackBaseWaitPromise;this._baseStackDisposed=!1;let t=new Promise((async(t,n)=>{try{let n=this._getBaseStackConfig();if(this._vdi3StateInfo={supported:PLe(),requested:!1,enabled:!1},this._vdi3StateInfo.supported&&!0===this._vdi3Options?.enabled){this._vdi3StateInfo.requested=!0,this._shellTrouter&&await this._shellTrouter.dispose(),this._shellTrouter=new WLe;let e=FLe(this.logger,this._vdi3Options);e.vdi3Config&&(e.vdi3Config.shellTrouter=this._shellTrouter.instance);let t=await H5.stackFactory.buildBaseStack({stackType:1,...n,...e});if(this._proxyReferenceManager=c9.create(this.logger),this._tsStack=this._proxyReferenceManager.create(t),this._vdi3StateInfo.enabled=!0,Z().vdi3.fetchEcs)try{let e=await this._tsStack?.getEcsProviderAsync?.();this._ecsQueryParametersRdc=JSON.parse(await e?.getEcsQueryParameters()??`null`)||void 0,this._ecsQueryParametersRdc&&(this._ecsQueryParametersRdc=NRe(this._ecsQueryParametersRdc),this._ecsClientRdc=new FRe(this._isWBMediaClient,this.logger,this._acsProxy,`EcsClientRdc`))}catch(e){this.logger.error(`Failed to get query parameters ${e}`)}}else this._tsStack=await H5.stackFactory.buildBaseStack({stackType:0,...n});let r=async(e,t,n)=>{if(e!==void 0||t!==void 0)try{if(e!==void 0&&e===t){await this.updateConfig(e,this._caConfigBag);let t=Z();UG.updateConfig(t?.errors,this.logger)}else await this.updateConfigForVdi(e,t,this._caConfigBag);t!==void 0&&(await this._setStackConfig(),this._checkEcsConfigValue(t,{attemptTimestamp:void 0,ecsFetchType:n,correlationId:``})),this._ecsTelemetryLogger.sendSuccessEvent(void 0,n,``,this.getEcsConfigIds())}catch(e){let t=new Y({defaultError:J.CALL_STACK.PARSE_CONFIG,originalError:e});this._ecsTelemetryLogger.sendFailureEvent(void 0,n,``,t)}};this._ecsClientRdc?(this._ecsClient.on(`configUpdated`,(async e=>{await r(e.config,void 0,e.fetchType)})),this._ecsClientRdc.on(`configUpdated`,(async e=>{await r(void 0,e.config,e.fetchType)}))):this._ecsClient.on(`configUpdated`,(async e=>{await r(e.config,e.config,e.fetchType)})),await this.initializeEcsBase(e),await this._setStackConfig(),t(this._tsStack)}catch(e){n(e)}}));try{this._createStackBaseWaitPromise=n3((()=>t),YSe);let e=await this._createStackBaseWaitPromise;return this.logger.log(`Base stack init success`),e}catch(e){throw await this.disposeBaseStack(),e.code===PG?new Y({defaultError:J.CALL_STACK.BASE_STACK_INIT_TIMEOUT}):new Y({defaultError:J.CALL_STACK.BASE_STACK_INIT_FAILED,originalError:e})}}async createMediaSdkStackBase(e,t,n){if(this._createMediaSdkStackBaseWaitPromise)return this._createMediaSdkStackBaseWaitPromise;this._baseStackDisposed=!1;let r=new Promise((async(r,i)=>{try{let i=this._getMediaStackConfig(e),a=+new Date;this._tsStack=await H5.stackFactory.build(i);let o=+new Date-a;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:K0(),operationName:`BuildMediaStack`,durationInMs:o,operationPayload:{},resultCategories:[`Success`],resultSignature:200});let s=async(e,t,n)=>{if(e!==void 0||t!==void 0)try{e!==void 0&&e===t?await this.updateConfig(e,this._caConfigBag):await this.updateConfigForVdi(e,t,this._caConfigBag),t!==void 0&&(await this._setStackConfig(),this._checkEcsConfigValue(t,{attemptTimestamp:void 0,ecsFetchType:n,correlationId:``})),this._ecsTelemetryLogger.sendSuccessEvent(void 0,n,``,this.getEcsConfigIds())}catch(e){let t=new Y({defaultError:J.CALL_STACK.PARSE_CONFIG,originalError:e});this._ecsTelemetryLogger.sendFailureEvent(void 0,n,``,t)}};if(this._ecsClient.on(`configUpdated`,(async e=>{await s(e.config,e.config,e.fetchType)})),!n){await this.applyHardcodedEcsConfigAndSetStack(`SetStackConfigBase`,t);let e=+new Date;this.initializeEcsBase(t).then((async()=>{let t=+new Date-e;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:K0(),operationName:`InitializeEcsBase`,durationInMs:t,operationPayload:{},resultCategories:[`Success`],resultSignature:200}),Z().waimeabay.backgroundEcsFetchTsStackSet&&await this._setStackConfig()})).catch((t=>{let n=+new Date-e;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:K0(),operationName:`InitializeEcsBase`,durationInMs:n,operationPayload:{},resultCategories:[`Failure`],resultSignature:500}),this.logger.warn(`Background ECS fetch failed`,t)}))}r(this._tsStack)}catch(e){i(e)}}));try{this._createMediaSdkStackBaseWaitPromise=n3((()=>r),YSe);let e=await this._createMediaSdkStackBaseWaitPromise;return this.logger.log(`Base stack init success`),e}catch(e){throw await this.disposeBaseStack(),e.code===PG?new Y({defaultError:J.CALL_STACK.BASE_STACK_INIT_TIMEOUT}):new Y({defaultError:J.CALL_STACK.BASE_STACK_INIT_FAILED,originalError:e})}}async initializeStackForUser(e,t){if(this._initializeStackForUserWaitPromise)return this._initializeStackForUserWaitPromise;this._caConfigBag=t,this._tsStack=await this.createStackBase(t),this._userStackDisposed=!1;let n=new Promise((async(n,o)=>{try{this._tsStack?(this._ecsProvider=new t9(this.logger,this.sdkDiagnosticInformation,this._acsProxy),await this.initializeEcsForUser(t,e),z6.overrideDefaultLogDump(),U6(this._tsStack)||(Z().calling.doNotWaitForTrouter?this._initTrouter(e).then((()=>{this.logger.log(`Signaling initialized successfully.`)})).catch((()=>{this.logger.warn(J.CALL_STACK.SIGNALING_UNINITIALIZED.message)})):(await this._initTrouter(e),this.logger.log(`Signaling initialized successfully.`))),await r(e,this._tsStack),await i(e,this._tsStack),await a(this._tsStack),n(this._tsStack)):(this.logger.error(`Base stack failed to create`),o(new Y({defaultError:J.CALL_STACK.USER_STACK_NO_BASE_STACK})))}catch(e){o(e)}})),r=async(e,t)=>{try{if(await t.initializeMediaAgent({httpRequestDispatcher:this.getRequestDispatcher(),tokenProvider:e,relayManager:this.getCustomRelayManager(),configProvider:{getSkypeConfig:()=>Promise.resolve({}),getRelayConfig:()=>{let e=this._ecsProvider.getMdnTrapSettings();return Promise.resolve(e)}},appStateProvider:this._getAppStateProvider(),clientInformation:this._ecsProvider.getJsCsaConfig().clientInformation}),Z().calling.platformSupportValidation&&await t.getPlatformSupportLevelAsync()===0){let e=new Y({defaultError:J.CALL_STACK.USER_STACK_MEDIA_INIT_FAILED_PLATFORM_NOT_SUPPORTED});throw this.logger.error(e.message),e}}catch(e){throw this.logger.error(`Failed to initialize media stack`,e),new Y({defaultError:J.CALL_STACK.USER_STACK_MEDIA_INIT_FAILED,originalError:e})}},i=async(e,t)=>{try{let n=U6(t),r={signalingAgentConfig:this._getSignalingConfig(e),...n?{trouterSettings:CLe(this._ecsProvider),trouterService:{}}:{trouterService:this._trouterService}};this._signalingAgentInitialized?(await t.updateSignalingAgentProviderConfig(r),this.logger.log(`Signaling agent updated successfully`)):(await t.initializeSignalingAgentProvider(r),this._signalingAgentInitialized=!0,this.logger.log(`Signaling agent initialized successfully`)),n&&(await this._shellTrouter?.initialize(),this.logger.log(`Signaling initialized successfully for VDI3.`))}catch(e){throw this.logger.error(`Failed to initialize signaling agent`,e),new Y({defaultError:J.CALL_STACK.USER_STACK_SIGNALING_INIT_FAILED,originalError:e})}},a=async e=>{try{await e.init(),await this._setStackConfig()}catch(e){throw this.logger.error(`Failed to initialize calling stack`,e),new Y({defaultError:J.CALL_STACK.USER_STACK_INTERNAL_INIT_FAILED,originalError:e})}};try{this._initializeStackForUserWaitPromise=n3((()=>n),XSe);let e=await this._initializeStackForUserWaitPromise;return this.sendStackInitEvent(!0),this.logger.log(`User stack init success`),e}catch(e){throw await this.disposeUserStack(),e.code===PG?(this.sendStackInitEvent(!1,`User stack init timeout`,e),new Y({defaultError:J.CALL_STACK.USER_STACK_INIT_TIMEOUT})):!(e instanceof Y)&&this.getTrouterState()===`Uninitialized`?new Y({defaultError:J.CALL_STACK.SIGNALING_UNINITIALIZED,originalError:e}):(this.sendStackInitEvent(!1,`User stack init failed`,e),new Y({defaultError:J.CALL_STACK.USER_STACK_INIT_FAILED,originalError:e}))}}async initializeMediaSdkStackForUser(e,t){if(this._caConfigBag=t,this._initializeMediaStackForUserWaitPromise)return this._initializeMediaStackForUserWaitPromise;this._tsStack=await this.createMediaSdkStackBase(e,t,!0);let n=this._getMediaStackConfig(e);this._tsStack.initializeMediaAgent(n.mediaAgentFactoryConfig),this._userStackDisposed=!1;let r=new Promise((async(n,r)=>{try{if(this._tsStack){await this.applyHardcodedEcsConfigAndSetStack(`SetStackConfigUser`,t);let r=+new Date;this.initializeEcsForUser(t,e).then((async()=>{let e=+new Date-r;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:K0(),operationName:`InitializeEcsForUser`,durationInMs:e,operationPayload:{},resultCategories:[`Success`],resultSignature:200}),z6.overrideDefaultLogDump(),Z().waimeabay.backgroundEcsFetchTsStackSet&&await this._setStackConfig()})).catch((e=>{let t=+new Date-r;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:K0(),operationName:`InitializeEcsForUser`,durationInMs:t,operationPayload:{},resultCategories:[`Failure`],resultSignature:500}),this.logger.warn(`Background user ECS fetch failed`,e)})),this.logger.log(`ECS initialized successfully.`);let a=+new Date;await i(this._tsStack);let o=+new Date-a;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:K0(),operationName:`InitializeTsStack`,durationInMs:o,operationPayload:{},resultCategories:[`Success`],resultSignature:200}),n(this._tsStack)}else this.logger.error(`Media SDK Base stack failed to create`),r(new Y({defaultError:J.CALL_STACK.USER_STACK_NO_BASE_STACK}))}catch(e){r(e)}})),i=async e=>{try{await e.init(),await this._setStackConfig()}catch(e){throw this.logger.error(`Failed to initialize Media SDK stack`,e),new Y({defaultError:J.CALL_STACK.USER_STACK_INTERNAL_INIT_FAILED,originalError:e})}};try{this._initializeMediaStackForUserWaitPromise=n3((()=>r),XSe);let e=await this._initializeMediaStackForUserWaitPromise;return this.sendStackInitEvent(!0),this.logger.log(`Media SDK User stack init success`),e}catch(e){throw await this.disposeUserStack(),e.code===PG?(this.sendStackInitEvent(!1,`Media SDK user stack init timeout`,e),new Y({defaultError:J.CALL_STACK.USER_STACK_INIT_TIMEOUT})):(this.sendStackInitEvent(!1,`Media SDK user stack init failed`,e),new Y({defaultError:J.CALL_STACK.USER_STACK_INIT_FAILED,originalError:e}))}}getRequestDispatcher(){return this._acsProxy.hasProxyUrl()?(this.logger.info(`Using custom proxy for network requests (non media)`),new OLe(this.logger,this._acsProxy)):Z().telemetry.sendNetworkInfo?new OLe(this.logger):new H5.HttpRequestDispatcherImplementation(this.logger)}async updateConfig(e,t){e?.Headers?.CountryCode&&this.updateEmergencyCallCountry(e?.Headers?.CountryCode);try{Vwe(e),this._ecsProvider.setConfig(t,e),Uwe(this._ecsProvider.getJamaSettings()),this._fetchedEcsConfigValue=e;let n=Z();UG.updateConfig(n?.errors,this.logger)}catch(e){throw this.logger.warn(`Unable to update ECS configuration ${e}`),new Y({defaultError:J.CALL_STACK.PARSE_CONFIG,originalError:e})}}async updateConfigForVdi(e,t,n){e?.Headers?.CountryCode&&this.updateEmergencyCallCountry(e?.Headers?.CountryCode);let r=t=>{LRe(t,ILe);let n=e?.AcsCallingSDKWeb?.vdi3?.customEcsConfig;if(n)try{LRe(e,JSON.parse(n))}catch(e){this.logger.error(`Failed to parse customEcsConfig: ${e}`)}};try{e&&(r(e),Vwe(e)),t&&(r(t),this._ecsProvider.setConfig(n,t),Uwe(this._ecsProvider.getJamaSettings()),this._fetchedEcsConfigValue=t)}catch(e){throw this.logger.warn(`Unable to update ECS configuration ${e}`),new Y({defaultError:J.CALL_STACK.PARSE_CONFIG,originalError:e})}}async _setStackConfig(){let e=Date.now();try{this._tsStack&&this._fetchedEcsConfigValue&&Object.keys(this._fetchedEcsConfigValue).length>0&&(this.logger.info(`Setting ECS configuration on the calling stack.`),await(await this._tsStack?.getEcsProviderAsync?.())?.setEcsConfig({ecsBlob:JSON.stringify(this._fetchedEcsConfigValue),userIdentity:``,etag:this._ecsClient.eTag}))}catch(t){let n=new Y({defaultError:J.CALL_STACK.SET_STACK_PARAMS,originalError:t}),r=Date.now(),i=e===void 0?0:r-e,a=n.message,o=K3(n);this.logger.warn(`Unable to set ECS configuration on the calling stack`),this._telemetryLogManager.sendEvent({name:Q.acs_calling_config_fetched_failure,tenant:d2,properties:{...e===void 0?void 0:{attemptTimestamp:e},failureTimestamp:r,deltaTimeInMs:i,failureReason:a,additionalDetails:{...o}}})}}_checkEcsConfigValue(e,t){let{attemptTimestamp:n,correlationId:r,ecsFetchType:i}=t;try{t9.assertConfigs(e)}catch(e){this.logger.error(`ECS config assertion failed: ${e?.message??`Unknown error`}`),this._ecsTelemetryLogger.sendFailureEvent(n,i,r,e)}}async initializeEcsBase(e){let t=Date.now(),n=K0();this._ecsTelemetryLogger.sendAttemptEvent(t,E9.Default,n);let r=J.CALL_STACK.FETCH_CONFIG;try{let i=await this._ecsClient.fetchDefaultConfig(RRe(this.logger,e),e);this.logger.info(`Fetched base settings from ECS.`);let a=i;if(U6(this._tsStack)&&this._ecsClientRdc&&this._ecsQueryParametersRdc){let t=await this._ecsClientRdc.fetchDefaultConfig(this._ecsQueryParametersRdc,e);a=t,r=J.CALL_STACK.PARSE_CONFIG,await this.updateConfigForVdi(i,t,e)}else r=J.CALL_STACK.PARSE_CONFIG,await this.updateConfig(i,e);this._ecsTelemetryLogger.sendSuccessEvent(t,E9.Default,n,this.getEcsConfigIds()),this._checkEcsConfigValue(a,{attemptTimestamp:t,correlationId:n,ecsFetchType:E9.Default})}catch(i){this.logger.warn(`Failed to fetch base settings. Stack will initialize with default settings`,i),this._ecsProvider.setConfig(e,void 0);let a=new Y({defaultError:r,originalError:i});this._ecsTelemetryLogger.sendFailureEvent(t,E9.Default,n,a)}}async initializeEcsForUser(e,t){let n=Date.now(),r=K0();this._ecsTelemetryLogger.sendAttemptEvent(n,E9.User,r);let i=J.CALL_STACK.FETCH_CONFIG;try{let a=await this._ecsClient.fetchUserConfig(RRe(this.logger,e),e,t);this.logger.info(`Fetched user settings from ECS.`);let o=a;if(U6(this._tsStack)&&this._ecsClientRdc&&this._ecsQueryParametersRdc){let n=await this._ecsClientRdc.fetchUserConfig(this._ecsQueryParametersRdc,e,t);o=n,i=J.CALL_STACK.PARSE_CONFIG,await this.updateConfigForVdi(a,n,e)}else i=J.CALL_STACK.PARSE_CONFIG,await this.updateConfig(a,e),this._ecsTelemetryLogger.sendSuccessEvent(n,E9.User,r,this.getEcsConfigIds());this._ecsTelemetryLogger.sendSuccessEvent(n,E9.User,r,this.getEcsConfigIds()),this._checkEcsConfigValue(o,{attemptTimestamp:n,correlationId:r,ecsFetchType:E9.User})}catch(e){this.logger.warn(`Failed to fetch user settings.`,e);let t=new Y({defaultError:i,originalError:e});this._ecsTelemetryLogger.sendFailureEvent(n,E9.User,r,t)}}async getDeviceManager(){if(this._createMediaSdkStackBaseWaitPromise){let e=await this._createMediaSdkStackBaseWaitPromise;return this.logger.info(`Getting ts device manager from media sdk stack`),e.getDeviceManagerAsync()}if(this._createStackBaseWaitPromise){let e=await this._createStackBaseWaitPromise;return this.logger.info(`Getting ts device manager from stack`),e.getDeviceManagerAsync()}throw new Y({defaultError:J.CALL_STACK.GET_DM})}async disposeBaseStack(){if(!this._baseStackDisposed){if(this._tsStack)try{await this._tsStack.dispose(),this._tsStack=void 0}catch{this.logger.error(`Failed to dispose calling stack`)}this._proxyReferenceManager?.dispose(),this._ecsClient.dispose(),this._ecsClientRdc?.dispose(),this._createStackBaseWaitPromise=void 0,this._baseStackDisposed=!0,this.logger.info(`Base call stack disposed`)}}async disposeUserStack(e){if(!this._userStackDisposed){if(this._trouterService)try{this._trouterService.clearMessageHandlers(),this._trouterService.stop(e),this._trouterService=void 0}catch{this.logger.error(`Failed to dispose signaling`)}if(this._shellTrouter)try{await this._shellTrouter.dispose(),this._shellTrouter=void 0}catch{this.logger.error(`Failed to dispose shellTrouter`)}try{await this._tsStack?.disposeMediaAgent(K0())}catch{this.logger.error(`Failed to dispose media agent`)}this._initializeStackForUserWaitPromise=void 0,this._userStackDisposed=!0,this.logger.info(`User calling stack disposed`)}}updateEmergencyCallCountry(e){this._caConfigBag&&!this._caConfigBag.emergencyCountryCode&&!this._caConfigBag.IsUserEmergencyCountryCode&&e&&(this._caConfigBag.emergencyCountryCode=e)}async _initTrouter(e){let t=+new Date;try{this._trouterService=new wLe(this.logger,this._ecsProvider,(t=>e(t)),this._telemetryLogManager,this._acsProxy),t=+new Date;let n=await this._trouterService.start(),r=this._trouterService.getTrouterSettings();this.sendSignalingInitEvent(!0,+new Date-t,r.registrationId??``,r.sessionId,n.trouterRequestCompletionTimeDeltaMs,n.registrarRequestCompletionTimeDeltaMs);return}catch(e){throw this.sendSignalingInitEvent(!1,+new Date-t,``,``,void 0,void 0,e),e}}_getBaseStackConfig(){let e=this._getMediaProviderConfig(),t={clientInformation:this._ecsProvider.getClientInformation(),logger:this.logger,mediaSettings:e.mediaSettings,platformType:e8(),callSettings:{useLwjForAllCalls:!1},usePlatformSupportApi:!0,telemetryTenants:{media:`mediaAgent`,signaling:`signalingAgent`,tlePlayer:YCe},telemetryService:this._telemetryService,webcvProvider:this._webcvProvider,wasmVqeProvider:this._wasmvqeProvider};return this._encodedStreamsWorkerProvider!==void 0&&(t.encodedStreamsWorkerProvider=this._encodedStreamsWorkerProvider),t}_getMediaStackConfig(e){return{stackType:2,mediaAgentFactoryConfig:{logger:this.logger,tokenProvider:e,configProvider:{getSkypeConfig:()=>Promise.resolve({}),getRelayConfig:()=>{let e=this._ecsProvider.getMdnTrapSettings();return Promise.resolve(e)}},settings:this._getMediaAgentConfig(),wasmVqeProvider:this._wasmvqeProvider,appStateProvider:this._getAppStateProvider()},signalingAgentConfig:this._getSignalingConfig(e),logger:this.logger,telemetryService:this._telemetryService,platformType:e8()}}_getSignalingConfig(e){let t={...this._ecsProvider.getJsCsaConfig(),httpRequestDispatcher:this.getRequestDispatcher(),telemetryManager:this._telemetryService.getCallingAdapter(),logger:this.logger,skypeToken:e,trouterServiceProvider:this._trouterService,ecsEtag:this._ecsClient.eTag};return this._caConfigBag?.emergencyCountryCode&&(t.emergencyCallCountry=this._caConfigBag?.emergencyCountryCode),t}_getMediaProviderConfig(){return{logger:this.logger,mediaSettings:this._getMediaAgentConfig()}}_getMediaAgentConfig(){return{...this._ecsProvider.getJamaSettings(),useOneDsLogger:!0,collectorUrl:q0.Public,telemetryTenants:{signaling:f2,gtcAudit:f2,media:p2,realtimeMedia:TCe,tlePlayer:ECe}}}_getAppStateProvider(){return{isOnline:()=>!0}}sendStackInitEvent(e,t,n){try{let r,i;n&&(r=n.message,i=K3(n)),this._telemetryLogManager.sendEvent({name:Q.acs_calling_stack_init,tenant:d2,properties:{success:e,reason:t,failureReason:r||`unknown`,additionalDetails:{...i}}})}catch{}}sendSignalingInitEvent(e,t,n,r,i,a,o){try{let s,c;o&&(s=o.message,c=K3(o)),this._telemetryLogManager.sendEvent({name:Q.acs_calling_signaling_init,tenant:d2,properties:{success:e,failureReason:s||`unknown`,timestampInfo:{deltaTimeInMs:t,deltaTimeInMsTrouterRequest:i,deltaTimeInMsRegistrarRequest:a},additionalDetails:{...c,registrationId:n,sessionId:r}}})}catch{}}getCustomRelayManager(){if(this._tsCustomRelayManager=this._acsCustomRelayManager.getTsRelayManager(),this._tsCustomRelayManager&&Z().calling.enableCustomTurnUsage)return this.logger.info(`Using custom relays for media traffic`),this._acsCustomRelayManager.customRelayManagerInUse=!0,this._tsCustomRelayManager}};O9([zG,k9(`design:type`,Object)],A9.prototype,`logger`,void 0),O9([GG(c4.CreateStackBase),k9(`design:type`,Function),k9(`design:paramtypes`,[Object]),k9(`design:returntype`,Promise)],A9.prototype,`createStackBase`,null),O9([GG(c4.CreateStackBase),k9(`design:type`,Function),k9(`design:paramtypes`,[Function,Object,Boolean]),k9(`design:returntype`,Promise)],A9.prototype,`createMediaSdkStackBase`,null),O9([GG(c4.InitializeStackForUser),k9(`design:type`,Function),k9(`design:paramtypes`,[Function,Object]),k9(`design:returntype`,Promise)],A9.prototype,`initializeStackForUser`,null),O9([GG(c4.InitializeMediaSdkStackForUser),k9(`design:type`,Function),k9(`design:paramtypes`,[Function,Object]),k9(`design:returntype`,Promise)],A9.prototype,`initializeMediaSdkStackForUser`,null),O9([GG(c4.GetDeviceManager),k9(`design:type`,Function),k9(`design:paramtypes`,[]),k9(`design:returntype`,Promise)],A9.prototype,`getDeviceManager`,null);var zRe=class{constructor(){this._eventEmitter=new w3.EventEmitter}notifyAll(e){this._eventEmitter.emit(e)}waitFor(e,t){return new Promise(((n,r)=>{let i=0,a=()=>{n(),clearTimeout(i)};this._eventEmitter.once(e,a),i=window.setTimeout((()=>{this._eventEmitter.off(e,a),r(Error(`timeout`))}),t)}))}},BRe=class{constructor(){this._deviceIdMapping=new Map,this._deviceId=1,this._keywords=Z().telemetry.deviceChangedEvents.piiSafeWords}getDeviceId(e){let t=this._deviceIdMapping.get(e);return t===void 0?(++this._deviceId,t=`${e.split(`:`)[0]??``}:${this._deviceId}`,this._deviceIdMapping.set(e,t),t):t}scrubDeviceLabel(e){return VRe(e,this._keywords)}};function VRe(e,t){if(!e)return``;if(e.length<3)return e;let n=[],r=e.match(/\(([0-9a-zA-Z]+:[0-9a-zA-Z]+)\)/);r&&n.push(r[1]);try{if(!t?.length)return`no_keywords`;{let r=RegExp(`(${t.join(`|`)})`,`gi`),i=r.exec(e);for(;i;)n.push(i[1]),i=r.exec(e)}}catch(e){n.push(`Error: ${(e=>Q2.isString(e)?e:e?.message??``)(e)}`)}return n.length===0?`unknown`:n.join(` `)}var j9=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},M9=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},N9=class{constructor(e,t,n,r=!1,i){this._callStack=t,this._isWBMediaClient=r,this._videoDevices=[],this._audioDevices=[],this._disposed=!1,this._tsDeviceTypeToAudioDeviceType={2:`Microphone`,3:`Speaker`,4:`CompositeAudioDevice`},this.logger=e.createChild(`DeviceManager`),this._telemetryLogManager=n,this._eventEmitter=new S6(this.logger),this._browserInfo=t8(),this._safariVideoPermissionState=`unknown`,this._combinedDevicePermission=new Map,this._deviceInfoMapper=new BRe,this._deviceSelectionNotifications=new zRe,this._permissionChangedTasks=Promise.resolve(),this._shouldEnumerateDevices=i??!0}get telemetryLogManager(){return this._telemetryLogManager}get isWBMediaClient(){return this._isWBMediaClient}get shouldEnumerateDevices(){return this._shouldEnumerateDevices}getRawDeviceMediaStream(e){let t=K0(),n=+new Date;if(this.sendRawMediaEvent({eventName:Q.acs_calling_get_raw_device_media_stream,correlationId:t,kindOfEvent:`attempt`,mediaType:e,timestampInfo:``,additionalDetails:``}),!this._tsDeviceManager?.getRawDeviceMediaStream){let r=new Y({defaultError:J.DEVICE_MANAGER.GET_MEDIA_STREAM_TRACK});this.logger.error(`Failed to get raw device stream track`);let i=+new Date;throw this.sendRawMediaEvent({eventName:Q.acs_calling_get_raw_device_media_stream,correlationId:t,kindOfEvent:`failure`,mediaType:e,timestampInfo:{deltaTimeInMs:i-n},additionalDetails:{failureReason:r.message||``,code:r.code,subCode:r.subCode,...K3(r)}}),r}let r;try{r=this._tsDeviceManager?.getRawDeviceMediaStream(e);let i=+new Date;return this.sendRawMediaEvent({eventName:Q.acs_calling_get_raw_device_media_stream,correlationId:t,kindOfEvent:`success`,mediaType:e,timestampInfo:{deltaTimeInMs:i-n},additionalDetails:``}),r}catch(r){let i=new Y({defaultError:J.DEVICE_MANAGER.GET_MEDIA_STREAM_DEVICE_UNAVAILABLE,originalError:r}),a=W3(r,this.isWBMediaClient,i);this.logger.error(`Failed to get raw device stream: `,a.message);let o=+new Date;throw this.sendRawMediaEvent({eventName:Q.acs_calling_get_raw_device_media_stream,correlationId:t,kindOfEvent:`failure`,mediaType:e,timestampInfo:{deltaTimeInMs:o-n},additionalDetails:{failureReason:a.message||``,code:a.code,subCode:a.subCode,...K3(a)}}),a}}getClientId(){return this._callStack.getClientId()}async getDeviceManager(){if(this._tsDeviceManager)return this._tsDeviceManager;let e=+new Date,t=K0();try{this.sendGetDeviceManagerEvent({eventName:Q.acs_calling_get_device_manager,kindOfEvent:`attempt`,timestampInfo:``,additionalDetails:``});let n=+new Date;if(this.isWBMediaClient){await this._callStack.createMediaSdkStackBase();let e=+new Date-n;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:K0(),operationName:`CreateMediaStackBase`,durationInMs:e,operationPayload:{},resultCategories:[`Success`],resultSignature:200})}else await this._callStack.createStackBase();let r=+new Date;if(this._tsDeviceManager=await this._callStack.getDeviceManager(),this.isWBMediaClient){let e=+new Date-r;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:K0(),operationName:`GetTsDeviceManager`,durationInMs:e,operationPayload:{},resultCategories:[`Success`],resultSignature:200})}if(this._shouldEnumerateDevices){let e=+new Date;try{let t=await this.enumerateDevicesAsync();if(this.isWBMediaClient){let n=+new Date-e;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:K0(),operationName:`EnumerateDevices`,durationInMs:n,operationPayload:{deviceCount:t.length},resultCategories:[`Success`],resultSignature:200})}this.logger.info(`tsDevicesList:${JSON.stringify(t)}`),t.forEach((e=>{if(e.kind===1){let t=e;this._videoDevices.push(new L6(t.label,t.id,`UsbCamera`,this))}else if(e.kind===2||e.kind===3){let t=e,n=new Y6(t.label,t.id,t.isSystemDefault,this._tsDeviceTypeToAudioDeviceType[t.kind],this);this._audioDevices.push(n)}}))}catch(t){if(this.isWBMediaClient){let n=+new Date-e,r=new Y({defaultError:J.DEVICE_MANAGER.DEVICE_ENUMERATING_FAIL,originalError:t});this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:K0(),operationName:`EnumerateDevices`,durationInMs:n,operationPayload:{...K3(r).communicationServicesError},resultCategories:r.resultCategories,resultSignature:500})}if(!1===Z().calling.ignoreEnumerateDevicesError)throw`Ignore enumerateDevicesError ${t}`}let t=+new Date,n=await this._tsDeviceManager.getSelectedDevicesAsync?.();if(this.isWBMediaClient){let e=+new Date-t;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:K0(),operationName:`GetSelectedDevices`,durationInMs:e,operationPayload:{hasMicrophone:!!n?.microphone,hasSpeaker:!!n?.speaker},resultCategories:[`Success`],resultSignature:200})}n&&(this._selectedMicrophone=this._audioDevices.find((e=>e.id===n.microphone)),this._selectedSpeaker=this._audioDevices.find((e=>e.id===n.speaker)))}else this.logger.info(`Skipping device enumeration (enumerateDevices is disabled)`);if(this._dmDevicesChangedSub=this._tsDeviceManager.on(`devicesChanged`,(async()=>{try{await this.syncDeviceList(await this.enumerateDevicesAsync()),await this.checkForSelectedDevicesChanges()}catch(t){this.logger.warn(`Unable to handle devicesChanged, error=${t?.message}, code=${t?.code}`);let n=+new Date;this.sendGetDeviceManagerEvent({eventName:Q.acs_calling_get_device_manager,kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:n-e},additionalDetails:{failureReason:t?.message,code:t?.code,...K3(t),context:`devicesChanged`}})}})),Z().calling.devicePermissions.getCurrentState){let e=+new Date,t=await this._tsDeviceManager?.getPermissionStateAsync?.(`microphone`,``),n=await this._tsDeviceManager?.getPermissionStateAsync?.(`camera`,``);if(this.isWBMediaClient){let r=+new Date-e;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:K0(),operationName:`GetPermissionState`,durationInMs:r,operationPayload:{microphoneState:String(t??`undefined`),cameraState:String(n??`undefined`)},resultCategories:[`Success`],resultSignature:200})}this._audioDevicePermission=P4(t,this.logger),this._videoDevicePermission=P4(n,this.logger)}this.logger.info(`Initial permission state audio:`,this._audioDevicePermission,`video:`,this._videoDevicePermission),this._dmDevicesPermissionChangedSub=this._tsDeviceManager.on(`onPermissionStateChanged`,(()=>{this._permissionChangedTasks=this._permissionChangedTasks.then((()=>this.permissionsChanged().catch(A4)))}));let i=+new Date-e;this.sendGetDeviceManagerEvent({eventName:Q.acs_calling_get_device_manager,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:i},additionalDetails:``}),this.isWBMediaClient&&this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`GetDeviceManager`,durationInMs:i,operationPayload:{videoDeviceCount:this._videoDevices.length,audioDeviceCount:this._audioDevices.length},resultCategories:[`Success`],resultSignature:200})}catch(n){let r=new Y({defaultError:J.DEVICE_MANAGER.GET_DM,originalError:n});this.logger.error(r.message);let i=+new Date-e;throw this.sendGetDeviceManagerEvent({eventName:Q.acs_calling_get_device_manager,kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:i},additionalDetails:{failureReason:r.message,code:r.code,...K3(r)}}),this.isWBMediaClient&&this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`GetDeviceManager`,durationInMs:i,operationPayload:{...K3(r).communicationServicesError},resultCategories:r.resultCategories,resultSignature:500}),r}return this._tsDeviceManager}getTsDeviceManager(){if(!this._tsDeviceManager)throw new Y({defaultError:J.DEVICE_MANAGER.ACCESS_DM});return this._tsDeviceManager}getSafariPermissionState(){return this._browserInfo.engine===`Safari`?this._safariVideoPermissionState:`unknown`}getAcsResourceId(){return this._callStack?.getCaConfigBag()?.acsResourceId}getAudioDevicePermission(){return this._audioDevicePermission}getVideoDevicePermission(){return this._videoDevicePermission}get callStackWebCvProvider(){return this._callStack.webcvProvider}get callStackWasmVqeProvider(){return this._callStack.wasmvqeProvider}get callStackVideoEffectsStatusManager(){return this._callStack.videoEffectsStatusManager}get callStackAudioEffectsStatusManager(){return this._callStack.audioEffectsStatusManager}get deviceInfoMapper(){return this._deviceInfoMapper}getEnvironmentInfoInternal(){return this._environmentInfo||=hke(),this._environmentInfo}getOSNameInternal(){return n8()}dispose(){this._disposed=!0,this._dmDevicesChangedSub&&this._dmDevicesChangedSub.dispose(),this._dmDevicesPermissionChangedSub&&this._dmDevicesPermissionChangedSub.dispose(),this._dmDevicesPermissionChangedSub=void 0,this._dmDevicesChangedSub=void 0,this._eventEmitter.removeAllListeners(),this._tsDeviceManager=void 0}on(e,t){if(e!==`videoDevicesUpdated`&&e!==`audioDevicesUpdated`&&e!==`selectedMicrophoneChanged`&&e!==`selectedSpeakerChanged`)throw new Y({defaultError:J.DEVICE_MANAGER.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if(e!==`videoDevicesUpdated`&&e!==`audioDevicesUpdated`&&e!==`selectedMicrophoneChanged`&&e!==`selectedSpeakerChanged`)throw new Y({defaultError:J.DEVICE_MANAGER.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}sendRawMediaEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:d2,properties:e})}catch{this.logger.debug(`Unable to send raw media telemetry`)}}sendGetDeviceManagerEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:d2,properties:e})}catch{this.logger.debug(`Unable to send get_device_manager telemetry`)}}async permissionsChanged(e,t){let n=this._audioDevicePermission,r=this._videoDevicePermission,i,a;if(Z().calling.devicePermissions.getCurrentState){let e=await this._tsDeviceManager?.getPermissionStateAsync?.(`microphone`,``),t=await this._tsDeviceManager?.getPermissionStateAsync?.(`camera`,``);i=P4(e,this.logger),a=P4(t,this.logger)}else i=n,a=r;this._audioDevicePermission=i||!!e?.audio,this._videoDevicePermission=a||!!e?.video,t&&(t.audio&&(this._audioDevicePermission=e?.audio??!1),t.video&&(this._videoDevicePermission=e?.video??!1)),n===this._audioDevicePermission&&r===this._videoDevicePermission||(this.logger.info(`permission state changed from audio: ${n}, video: ${r}\n to audio: ${this._audioDevicePermission}, video: ${this._videoDevicePermission}`),this._telemetryLogManager.sendEvent({name:Q.acs_calling_device_permission_changed,tenant:d2,properties:{previousAudioDevicePermission:this.nullHandler(n),previousVideoDevicePermission:this.nullHandler(r),newAudioDevicePermission:this.nullHandler(this._audioDevicePermission),newVideoDevicePermission:this.nullHandler(this._videoDevicePermission)}}))}async checkForSelectedDevicesChanges(){if(this.logger.info(`checkForSelectedDevicesChanges`),this._tsDeviceManager){let e=await this._tsDeviceManager.getSelectedDevicesAsync?.();e&&(e.microphone!==this._selectedMicrophone?.id&&(this._selectedMicrophone=this._audioDevices.find((t=>t.id===e.microphone)),this._eventEmitter.emit(`selectedMicrophoneChanged`),e.microphone!==void 0&&this._deviceSelectionNotifications.notifyAll(e.microphone)),e.speaker!==this._selectedSpeaker?.id&&(this._selectedSpeaker=this._audioDevices.find((t=>t.id===e.speaker)),this._eventEmitter.emit(`selectedSpeakerChanged`),e.speaker!==void 0&&this._deviceSelectionNotifications.notifyAll(e.speaker)))}else this.logger.warn(`DeviceManager is undefined, Unable to check selected devices`)}isACSDeviceEqualToTSDevice(e,t){return e.id===t.id}async syncDeviceList(e){if(!this._tsDeviceManager)throw new Y({defaultError:J.DEVICE_MANAGER.ACCESS_DM});if(this.logger.info(`syncDeviceList`),!this._shouldEnumerateDevices)return void this.logger.info(`Device enumeration disabled, skipping syncDeviceList`);e===void 0&&(e=await this.enumerateDevicesAsync());let t=[],n=[],r=[],i=[];e.map((e=>{if(e.kind===1){let n=this._videoDevices.find((t=>this.isACSDeviceEqualToTSDevice(t,e)));if(n)n.setName(e.label),n.setId(e.id),n.setDeviceType(`UsbCamera`);else{let n=new L6(e.label,e.id,`UsbCamera`,this);t.push(n),this._videoDevices.push(n)}}else if(e.kind===2||e.kind===3){let t=this._audioDevices.find((t=>this.isACSDeviceEqualToTSDevice(t,e)));if(t){let n=e;t.setName(n.label),t.setId(n.id),t.setIsSystemDefault(n.isSystemDefault),t.setDeviceType(this._tsDeviceTypeToAudioDeviceType[n.kind])}else{let t=new Y6(e.label,e.id,e.isSystemDefault,this._tsDeviceTypeToAudioDeviceType[e.kind],this);r.push(t),this._audioDevices.push(t)}}}));let a=t=>{let n=t.filter((t=>!e.find((e=>this.isACSDeviceEqualToTSDevice(t,e)))));return n.map((e=>{t.splice(t.indexOf(e),1)})),n};n=a(this._videoDevices),i=a(this._audioDevices),(t.length>0||n.length>0)&&this._eventEmitter.emit(`videoDevicesUpdated`,{added:t,removed:n}),(r.length>0||i.length>0)&&this._eventEmitter.emit(`audioDevicesUpdated`,{added:r,removed:i})}async enumerateDevicesAsync(){if(!this._tsDeviceManager)throw new Y({defaultError:J.DEVICE_MANAGER.ACCESS_DM});try{return await this._tsDeviceManager.enumerateDevicesAsync()}catch{throw new Y({defaultError:J.DEVICE_MANAGER.DEVICE_ENUMERATING_FAIL})}}get isSpeakerSelectionAvailable(){if(!this._tsDeviceManager)throw new Y({defaultError:J.DEVICE_MANAGER.ACCESS_DM});return this._tsDeviceManager.isAudioOutputSelectionSupported}get selectedMicrophone(){return this._selectedMicrophone}get selectedSpeaker(){return this._selectedSpeaker}async getCameras(){if(this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});return await this.syncDeviceList(),this._videoDevices}async getMicrophones(){if(this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});return await this.syncDeviceList(),this._audioDevices.filter((e=>e.deviceType===`Microphone`))}async getSpeakers(){if(this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});if(this.isSpeakerSelectionAvailable)return await this.syncDeviceList(),this._audioDevices.filter((e=>e.deviceType===`Speaker`));throw new Y({defaultError:J.DEVICE_MANAGER.SPEAKER_ENUMERATION_UNSUPPORTED})}async selectMicrophone(e){if(this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});if(!this._tsDeviceManager)throw new Y({defaultError:J.DEVICE_MANAGER.ACCESS_DM});if(!e||!e.id)throw new Y({defaultError:J.DEVICE_MANAGER.INVALID_DEVICE});if(e.id===`microphone:`)throw new Y({defaultError:J.DEVICE_MANAGER.DEVICE_NOT_SELECTABLE});if(this.logger.info(`selectMicrophone called`),this._selectedMicrophone?.id!==e.id){let t=Z().calling.deviceSelectionTimeoutInMs,n=this._deviceSelectionNotifications.waitFor(e.id,t),r=this._deviceInfoMapper.getDeviceId(e.id),i=this._deviceInfoMapper.scrubDeviceLabel(e.name),a=K0(),o=(e,t,n)=>{this.sendDeviceManagerEvent({eventName:Q.acs_calling_client_operations,operation:K7.deviceSelection,kindOfEvent:e,correlationId:a,timestampInfo:t===void 0?{}:{deltaTimeInMs:t},additionalDetails:n===void 0?``:{failureReason:n.message,code:n.code,...K3(n)},deviceSelection:{deviceId:r,deviceName:i,deviceType:`Microphone`}})};o(`attempt`);let s=Date.now();try{await this._tsDeviceManager.selectDevicesAsync?.({microphone:e.id}),await n.catch((t=>{if(this._selectedMicrophone?.id!==e.id)throw t})),o(`success`,Date.now()-s)}catch(e){let t;throw t=new Y(e?.message===`timeout`?{defaultError:J.DEVICE_MANAGER.SELECT_MICROPHONE_TIMEOUT}:{defaultError:J.DEVICE_MANAGER.SELECT_MICROPHONE_FAIL,originalError:e}),o(`failure`,Date.now()-s,t),t}}else this.logger.warn(`microphoneDevice is already active`)}async selectSpeaker(e){if(this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});let t=this.logger.createFnLogger(l4.SelectSpeaker);if(!this._tsDeviceManager)throw new Y({defaultError:J.DEVICE_MANAGER.ACCESS_DM});if(!this.isSpeakerSelectionAvailable)throw new Y({defaultError:J.DEVICE_MANAGER.SPEAKER_SELECTION_UNSUPPORTED});if(!e||!e.id)throw new Y({defaultError:J.DEVICE_MANAGER.INVALID_DEVICE});if(e.id===`speaker:`)throw new Y({defaultError:J.DEVICE_MANAGER.DEVICE_NOT_SELECTABLE});if(t.info(`selectSpeaker called`),this._selectedSpeaker?.id!==e.id){let t=Z().calling.deviceSelectionTimeoutInMs,n=this._deviceSelectionNotifications.waitFor(e.id,t),r=this._deviceInfoMapper.getDeviceId(e.id),i=this._deviceInfoMapper.scrubDeviceLabel(e.name),a=K0(),o=(e,t,n)=>{this.sendDeviceManagerEvent({eventName:Q.acs_calling_client_operations,operation:K7.deviceSelection,kindOfEvent:e,correlationId:a,timestampInfo:t===void 0?{}:{deltaTimeInMs:t},additionalDetails:n===void 0?``:{failureReason:n.message,code:n.code,...K3(n)},deviceSelection:{deviceId:r,deviceName:i,deviceType:`Speaker`}})};o(`attempt`);let s=Date.now();try{await this._tsDeviceManager.selectDevicesAsync?.({speaker:e.id}),await n.catch((t=>{if(this._selectedSpeaker?.id!==e.id)throw t})),o(`success`,Date.now()-s)}catch(e){let t;throw t=new Y(e?.message===`timeout`?{defaultError:J.DEVICE_MANAGER.SELECT_SPEAKER_TIMEOUT}:{defaultError:J.DEVICE_MANAGER.SELECT_SPEAKER_FAIL,originalError:e}),o(`failure`,Date.now()-s,t),t}}else t.warn(`device is already selected`)}async askDevicePermission(e){return this.getAskDevicePermissionPromise(e,x3.Public_App)}async startPreheatDevices(e){let{audio:t,video:n}=e,r=Date.now(),i=K0(),a=(e,a)=>{this.sendDeviceManagerEvent({eventName:Q.acs_calling_client_operations,operation:K7.startPreheatDevices,kindOfEvent:`failure`,audio:{preheat:t?.preheat||!1,timeoutInSec:t?.timeoutInSec||-1},video:{preheat:n?.preheat||!1,timeoutInSec:n?.timeoutInSec||-1},timestampInfo:{deltaTimeInMs:Date.now()-r},additionalDetails:{failureReason:e.message,code:e.code,subCode:e.subCode,...K3(e),context:a},correlationId:i})};try{if(this.sendDeviceManagerEvent({eventName:Q.acs_calling_client_operations,operation:K7.startPreheatDevices,kindOfEvent:`attempt`,audio:{preheat:t?.preheat||!1,timeoutInSec:t?.timeoutInSec||-1},video:{preheat:n?.preheat||!1,timeoutInSec:n?.timeoutInSec||-1},timestampInfo:{},additionalDetails:{},correlationId:i}),this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});if(!Z().calling.devicePermissions.isPreheatEnabled)throw new Y({defaultError:J.DEVICE_MANAGER.PREHEAT_DISABLED});if(!t?.preheat&&!n?.preheat||t?.preheat&&typeof t?.preheat!=`boolean`||n?.preheat&&typeof n?.preheat!=`boolean`||t?.timeoutInSec&&!t.preheat||n?.timeoutInSec&&!n?.preheat||t?.timeoutInSec&&isNaN(t?.timeoutInSec)||t?.timeoutInSec&&t?.timeoutInSec<=0||n?.timeoutInSec&&isNaN(n?.timeoutInSec)||n?.timeoutInSec&&n?.timeoutInSec<=0)throw new Y({defaultError:J.DEVICE_MANAGER.PREHEAT_INVALID_CONFIG});if(t?.preheat&&this._tsRawAudioStream)throw new Y({defaultError:J.DEVICE_MANAGER.AUDIO_ALREADY_PREHEATED});if(n?.preheat&&this._tsRawVideoStream)throw new Y({defaultError:J.DEVICE_MANAGER.VIDEO_ALREADY_PREHEATED})}catch(e){let a=new Y({defaultError:J.DEVICE_MANAGER.PREHEAT_FAIL,originalError:e});throw this.logger.error(a.message),this.sendDeviceManagerEvent({eventName:Q.acs_calling_client_operations,operation:K7.startPreheatDevices,kindOfEvent:`failure`,audio:{preheat:t?.preheat||!1,timeoutInSec:t?.timeoutInSec||-1},video:{preheat:n?.preheat||!1,timeoutInSec:n?.timeoutInSec||-1},timestampInfo:{deltaTimeInMs:Date.now()-r},additionalDetails:{failureReason:a.message,code:a.code,subCode:a.subCode,...K3(a)},correlationId:i}),a}try{if(!this._tsDeviceManager)throw new Y({defaultError:J.DEVICE_MANAGER.ACCESS_DM});let e=[];try{e=await this._tsDeviceManager.enumerateDevicesAsync()}catch(e){let t=new Y({defaultError:J.DEVICE_MANAGER.PREAHEAT_ENUMERATE_DEVICES_FAIL,originalError:e});throw this.logger.error(t.message),t}let o=!1,s=!1;if(t?.preheat){let t=e.filter((e=>e.kind===2)),n=e.filter((e=>e.kind===3));t[0]?.id!==`microphone:`&&n[0]?.id!==`speaker:`||(o=!0)}if(n?.preheat&&e.filter((e=>e.kind===1))[0]?.id===`camera:`&&(s=!0),o||s){let e=await this.getAskDevicePermissionPromise({audio:o,video:s},x3.StartPreheatDevices);if(o&&!e.audio)throw new Y({defaultError:J.DEVICE_MANAGER.AUDIO_PREHEAT_NO_PERMISSION});if(s&&!e.video)throw new Y({defaultError:J.DEVICE_MANAGER.VIDEO_PREHEAT_NO_PERMISSION})}if(t?.preheat){try{this._tsRawAudioStream=this.getRawDeviceMediaStream(0)}catch(e){let t=new Y({defaultError:J.DEVICE_MANAGER.PREHEAT_GET_DM_AUDIO_STREAM_FAIL,originalError:e});throw this.logger.error(t.message),t}this._tsRawAudioStream?.changed((()=>{this._tsRawAudioStream?.getMediaStream().catch((e=>{let t=new Y({defaultError:J.DEVICE_MANAGER.PREHEAT_GET_AUDIO_STREAM_FAIL,originalError:e}),n=W3(e,this.isWBMediaClient,t);this.logger.error(n.message),a(n,`changed event`)}))}));try{await this._tsRawAudioStream?.getMediaStream()}catch(e){let t=new Y({defaultError:J.DEVICE_MANAGER.PREHEAT_GET_AUDIO_STREAM_FAIL,originalError:e}),n=W3(e,this.isWBMediaClient,t);throw this.logger.error(n.message),n}t?.timeoutInSec&&t.timeoutInSec>0&&(this._preheatedAudioStreamTimeout=setTimeout((()=>{this._tsRawAudioStream?.dispose(),this._tsRawAudioStream=void 0}),1e3*t?.timeoutInSec))}if(n?.preheat){try{this._tsRawVideoStream=this.getRawDeviceMediaStream(1)}catch(e){let t=new Y({defaultError:J.DEVICE_MANAGER.PREHEAT_GET_DM_VIDEO_STREAM_FAIL,originalError:e});throw this.logger.error(t.message),t}this._tsRawVideoStream?.changed((()=>{this._tsRawVideoStream?.getMediaStream().catch((e=>{let t=new Y({defaultError:J.DEVICE_MANAGER.PREHEAT_GET_VIDEO_STREAM_FAIL,originalError:e});this.logger.error(t.message),a(t,`changed event`)}))}));try{await this._tsRawVideoStream?.getMediaStream()}catch(e){let t=new Y({defaultError:J.DEVICE_MANAGER.PREHEAT_GET_VIDEO_STREAM_FAIL,originalError:e});throw this.logger.error(t.message),t}n?.timeoutInSec&&n?.timeoutInSec>0&&(this._preheatedVideoStreamTimeout=setTimeout((()=>{this._tsRawVideoStream?.dispose(),this._tsRawVideoStream=void 0}),1e3*n?.timeoutInSec))}this.sendDeviceManagerEvent({eventName:Q.acs_calling_client_operations,operation:K7.startPreheatDevices,kindOfEvent:`success`,audio:{preheat:t?.preheat||!1,timeoutInSec:t?.timeoutInSec||-1},video:{preheat:n?.preheat||!1,timeoutInSec:n?.timeoutInSec||-1},timestampInfo:{deltaTimeInMs:Date.now()-r},additionalDetails:{},correlationId:i})}catch(e){if(t?.preheat)try{this._tsRawAudioStream?.dispose()}catch{}finally{this._tsRawAudioStream=void 0,this._preheatedAudioStreamTimeout&&=(clearTimeout(this._preheatedAudioStreamTimeout),void 0)}if(n?.preheat)try{this._tsRawVideoStream?.dispose()}catch{}finally{this._tsRawVideoStream=void 0,this._preheatedVideoStreamTimeout&&=(clearTimeout(this._preheatedVideoStreamTimeout),void 0)}let r=new Y({defaultError:J.DEVICE_MANAGER.PREHEAT_FAIL,originalError:e});throw this.logger.error(r.message),a(r,`api call`),r}}stopPreheatDevices(e){if(this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});let{audio:t,video:n}=e,r=Date.now(),i=K0();try{this.sendDeviceManagerEvent({eventName:Q.acs_calling_client_operations,operation:K7.stopPreheatDevices,kindOfEvent:`attempt`,audio:t||!1,video:n||!1,timestampInfo:{},additionalDetails:{},correlationId:i}),t&&(this._tsRawAudioStream?.dispose(),this._tsRawAudioStream=void 0,this._preheatedAudioStreamTimeout&&=(clearTimeout(this._preheatedAudioStreamTimeout),void 0)),n&&(this._tsRawVideoStream?.dispose(),this._tsRawVideoStream=void 0,this._preheatedVideoStreamTimeout&&=(clearTimeout(this._preheatedVideoStreamTimeout),void 0)),this.sendDeviceManagerEvent({eventName:Q.acs_calling_client_operations,operation:K7.stopPreheatDevices,kindOfEvent:`success`,audio:t||!1,video:n||!1,timestampInfo:{deltaTimeInMs:Date.now()-r},additionalDetails:{},correlationId:i})}catch(e){let a=new Y({defaultError:J.DEVICE_MANAGER.STOP_PREHEAT_FAIL,originalError:e});throw this.sendDeviceManagerEvent({eventName:Q.acs_calling_client_operations,operation:K7.stopPreheatDevices,kindOfEvent:`failure`,audio:t||!1,video:n||!1,timestampInfo:{deltaTimeInMs:Date.now()-r},additionalDetails:{failureReason:a.message,code:a.code,subCode:a.subCode,...K3(a)},correlationId:i}),a}}getAskDevicePermissionPromise(e,t){if(this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});let n={audio:!!e.audio,video:!!e.video};if(!e.audio&&!e.video)throw new Y({defaultError:J.DEVICE_MANAGER.ONE_PERMISSION_ATLEAST});let r=this.getKeyForConstrains(n),i=this._combinedDevicePermission.get(r);return i?this.logger.info(`askDevicePermission attempt: audio:${n.audio}, video:${n.video} on pending existing request ${N4(i)}`):(i=this.askDevicePermissionInternal(n,t),this._combinedDevicePermission.set(r,i),i.finally((()=>{this._combinedDevicePermission.delete(r)}))),i}getKeyForConstrains(e){return Object.keys(e).filter((t=>e[t])).toString()}async askDevicePermissionInternal(e,t){this.logger.info(`askDevicePermission attempt: audio:${e.audio}, video:${e.video}`);let n=K0(),r=+new Date;this.sendAskDevicePermissionEvent({eventName:Q.acs_calling_adp_attempt,correlationId:n,audioPermissionRequested:e.audio,videoPermissionRequested:e.video,cause:t});try{if(!this._tsDeviceManager)throw new Y({defaultError:J.DEVICE_MANAGER.ACCESS_DM});let i=[];if(Z().calling.devicePermissions.splitAskAudioVideo){this.logger.info(`askDevicePermission, split permission check`);let t=[];e.audio&&(this.logger.info(`askDevicePermission, split permission audio`),t.push(this._tsDeviceManager.askDevicePermission({audio:e.audio,video:!1}))),e.video&&t.push((async t=>new Promise(((n,r)=>{let i=async()=>{if(this.logger.info(`askDevicePermission, split permission video`),!this._tsDeviceManager){let e=`askDevicePermission, split permission video failed device manager not found`;this.logger.error(e),r(e);return}try{n(await this._tsDeviceManager.askDevicePermission({audio:!1,video:e.video}))}catch(e){r(e)}};t?window.setTimeout(i,t):i()})))(Z().calling.devicePermissions.timeoutInBetween));let n=await Promise.allSettled(t),r={audio:!1,video:!1};n.forEach((e=>{e.status===`fulfilled`&&e?.value&&(r={audio:r.audio||!!e?.value?.audio,video:r.video||!!e?.value?.video}),e.status===`rejected`&&e?.reason&&i.push(e.reason)}));let a=this._permissionChangedTasks.then((()=>this.permissionsChanged(r,e)));this._permissionChangedTasks=a,this._permissionChangedTasks.catch(A4),await a,this._safariVideoPermissionState=this._videoDevicePermission?`granted`:`denied`}else{let t=await this._tsDeviceManager.askDevicePermission({audio:e.audio,video:e.video}),n=this._permissionChangedTasks.then((()=>this.permissionsChanged(t,e)));this._permissionChangedTasks=n,this._permissionChangedTasks.catch(A4),await n}if(e?.audio&&!this._audioDevicePermission||e?.video&&!this._videoDevicePermission)this.sendAskDevicePermissionEvent({eventName:Q.acs_calling_adp_failure,correlationId:n,audioPermissionRequested:e.audio,videoPermissionRequested:e.video,audioPermissionGranted:this._audioDevicePermission,videoPermissionGranted:this._videoDevicePermission,cause:t},new Y({defaultError:J.DEVICE_MANAGER.PERMISSION_NOT_GRANTED_OR_FAILED,defaultErrorMessageArgs:[N4(i)]}));else{let i=+new Date;this.sendAskDevicePermissionEvent({eventName:Q.acs_calling_adp_success,correlationId:n,audioPermissionRequested:e.audio,videoPermissionRequested:e.video,audioPermissionGranted:this._audioDevicePermission,videoPermissionGranted:this._videoDevicePermission,deltaTimeInMs:i-r,cause:t})}}catch(i){let a=new Y({defaultError:J.DEVICE_MANAGER.ADP_FAIL,originalError:i}),o=+new Date;this.sendAskDevicePermissionEvent({eventName:Q.acs_calling_adp_failure,correlationId:n,audioPermissionRequested:e.audio,videoPermissionRequested:e.video,audioPermissionGranted:this._audioDevicePermission,videoPermissionGranted:this._videoDevicePermission,deltaTimeInMs:o-r,cause:t},a)}return{audio:!!this._audioDevicePermission,video:!!this._videoDevicePermission}}sendAskDevicePermissionEvent(e,t){try{let n,r,i;t&&(n=typeof t?.message==`string`?t?.message:void 0,r=K3(t)),e.deltaTimeInMs&&(i=e.deltaTimeInMs>25e3),this._telemetryLogManager.sendEvent({name:e.eventName,tenant:d2,properties:{audioPermissionGranted:this.nullHandler(e.audioPermissionGranted),videoPermissionGranted:this.nullHandler(e.videoPermissionGranted),audioPermissionRequested:e.audioPermissionRequested,videoPermissionRequested:e.videoPermissionRequested,correlationId:e.correlationId||``,failureReason:n||``,deltaTimeInMs:e.deltaTimeInMs||``,deltaTimeGreaterThanJAMATimeout:this.nullHandler(i),cause:e.cause||``,additionalDetails:{...r}}})}catch{this.logger.debug(`Unable to send audio video permission failure success telemtery`)}}sendDeviceManagerEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:d2,properties:e})}catch{this.logger.debug(`Unable to send device selection telemetry`)}}nullHandler(e){return e===void 0?``:e}};j9([zG,M9(`design:type`,Object)],N9.prototype,`logger`,void 0),j9([GG(l4.GetCameras),M9(`design:type`,Function),M9(`design:paramtypes`,[]),M9(`design:returntype`,Promise)],N9.prototype,`getCameras`,null),j9([GG(l4.GetMicrophones),M9(`design:type`,Function),M9(`design:paramtypes`,[]),M9(`design:returntype`,Promise)],N9.prototype,`getMicrophones`,null),j9([WG(l4.GetSpeakers),M9(`design:type`,Function),M9(`design:paramtypes`,[]),M9(`design:returntype`,Promise)],N9.prototype,`getSpeakers`,null),j9([GG(l4.SelectMicrophone),M9(`design:type`,Function),M9(`design:paramtypes`,[Object]),M9(`design:returntype`,Promise)],N9.prototype,`selectMicrophone`,null),j9([GG(l4.SelectSpeaker),M9(`design:type`,Function),M9(`design:paramtypes`,[Object]),M9(`design:returntype`,Promise)],N9.prototype,`selectSpeaker`,null),j9([GG(l4.AskDevicePermission),M9(`design:type`,Function),M9(`design:paramtypes`,[Object]),M9(`design:returntype`,Promise)],N9.prototype,`askDevicePermission`,null),j9([GG(l4.StartPreheatDevices),M9(`design:type`,Function),M9(`design:paramtypes`,[Object]),M9(`design:returntype`,Promise)],N9.prototype,`startPreheatDevices`,null),j9([WG(l4.StopPreheatDevices),M9(`design:type`,Function),M9(`design:paramtypes`,[Object]),M9(`design:returntype`,void 0)],N9.prototype,`stopPreheatDevices`,null);var HRe=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},P9=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},URe=class extends H7{get info(){return this._teamsCall.info}constructor(e){super(e,HG.TeamsIncomingCall),this._teamsCall=e}async accept(e){if(!R4(this._teamsCall.acsProxy,this._teamsCall.acsCustomRelayManager,!0))throw new Y({defaultError:J.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN});return await this._teamsCall.accept(e),this._teamsCall}};HRe([GG(o4.Accept),P9(`design:type`,Function),P9(`design:paramtypes`,[Object]),P9(`design:returntype`,Promise)],URe.prototype,`accept`,null);var F9=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},I9=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},L9=class extends R7{get info(){return this._info}constructor(e,t,n,r){super(e,t,n,r,VG.TeamsCall),this._musicOnHoldEnabled=!1,this._hasFetchedPolicies=!1,this._info=this.callInfo,this._isEmergencyCall=e.isEmergencyNumber,this._mtPolicyService=t.mtPolicyService}async startCallInternal(e,t,n,r,i,a,o){if(this.logger.info(`==> Emergency startCallInternal:TeamsCall.ts`),this._mtPolicyService&&this._mtPolicyService.isFetchUserPoliciesAndSettingsApplicable(!0,o)){this._mtPolicyService.userDialedNumber(Array.isArray(o)?o[0].phoneNumber:o.phoneNumber);let e=``,t=!0;try{this.logger.info(`Fetching Teams User policy from MiddleTier Service`);let e={policyUrlSuffix:Z().MiddleTier.policyUrlSuffixV2,userPolicies:[`EmergencyPolicies`],userProperties:[`evEnabled`,`PoliciesMetadata`]};await this._mtPolicyService.fetchUserPoliciesFromAcsMiddleTier(this.tsCall.callId,this._callAgent.getUserMri(),e)}catch(e){t=!1,this.logger.warn(`Fetching Teams user policy from ACS MiddleTier Service failed.\n Error message = ${e?.message}, code = ${e?.code}, subcode = ${e?.subCode}.\n Proceeding as normal pstn call`)}if(t){try{this.enforcePolicyAndLicenseRestrictions()}catch(e){this.handlePolicyAndLicenseRestrictionsFailure(e);return}try{this.logger.info(`Deriving emergency content from fetched policies and settings`),e=this._mtPolicyService.getEmergencyContent()}catch(e){this.logger.warn(`Error deriving emergency content from fetched policies and settings. \n Error message = ${e?.message}, code = ${e?.code}, subcode = ${e?.subCode}. Proceeding as normal pstn call`)}r&&(r.emergencyContent=e||``,r.isEmergency=e?.trim().length>0||!1,this._isEmergencyCall=r.isEmergency)}}if(o){let t=[];Array.isArray(o)?t=o:t.push(o),this._isEmergencyCall&&t.length==1&&(this.logger.info(`user dialed number (${t[0].phoneNumber}) resolved to actual emergency number (${this._mtPolicyService.getEmergencyNumber()} during startCall`),t[0]={phoneNumber:this._mtPolicyService.getEmergencyNumber()}),t.length>1&&await this.setupThreadIdWhenStartingGroupCall(t,e,r),t.forEach((e=>{this.tsCall.addParticipant(W2(e)).catch((()=>{this.logger.error(`Failed to add participant during call start`)}))})),this.logger.info(`Paticipant added during startCall`)}return this._allowBreakoutRoomJoin=Z().calling.breakoutRooms.enabled&&this._mtPolicyService.isBreakoutRoomsAllowed()&&!!n,this._allowIPAudio=this._mtPolicyService.isIPAudioAllowed(),this._allowIPVideo=this._mtPolicyService.isIPVideoAllowed(),super.startCallInternal(e,t,n,r,i,a)}dispose(){super.dispose(),this._extensibleApi.dispose()}get isEmergencyCall(){return this._isEmergencyCall}addParticipant(e,t){let n=+new Date,r=K0();this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.attempt,participantAddedOrRemoved:`add`,correlationId:r,timestampInfo:{attemptTimestamp:n},additionalDetails:{customContext:{userToUserPresent:!!t?.customContext?.userToUser,xHeadersPresent:!!t?.customContext?.xHeaders&&t?.customContext.xHeaders.length>0}}});try{$5(o4.AddParticipant,this.state),q2(e)}catch(e){let t=new Y({defaultError:J.IDENTIFIER.PARSE_INVALID_IDENTIFIER,originalError:e});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`add`,correlationId:r,timestampInfo:{deltaTimeInMs:+new Date-n},additionalDetails:{code:e.code,failureReason:e.message,...K3(t)}}),t}if(!R4(this.acsProxy,this.acsCustomRelayManager,!0)){let e=new Y({defaultError:J.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`add`,correlationId:r,timestampInfo:{deltaTimeInMs:+new Date-n},additionalDetails:{code:e.code,failureReason:e.message,...K3(e)}}),e}if(this._remoteParticipants.find((t=>W2(t.identifier)===W2(e)))){let t=new Y({defaultError:J.CALL.PARTICIPANT_ALREADY_IN_CALL,defaultErrorMessageArgs:[wG(e).kind]});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`add`,correlationId:r,timestampInfo:{deltaTimeInMs:+new Date-n},additionalDetails:{code:t.code,failureReason:t.message,...K3(t)}}),t}if(this.tsCall.threadId&&cTe(this.tsCall.threadId))try{if(this.IsTargetUserAllowed(e))throw new Y({defaultError:J.CALL_AGENT.UNSUPPORTED_TARGET_TYPE})}catch(e){throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`add`,correlationId:r,timestampInfo:{deltaTimeInMs:+new Date-n},additionalDetails:{code:e.code,failureReason:e.message,...K3(e)}}),this.logger.error(e),e}let i=this.getOrCreateRemoteParticipant(G2(W2(e))),a=``;return this.GetOrCreateGroupChatThread(!!t?.threadId,e,t).then((o=>{o&&((t??={}).threadId=o,a=o,this._info.setThreadId(o)),this.addParticipantToTsCall(e,a,t,i,r,n)})).catch((e=>{throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`add`,correlationId:r,timestampInfo:{deltaTimeInMs:+new Date-n},additionalDetails:{code:e.code,failureReason:e.message,...K3(e)}}),e})),i}async removeParticipant(e){let t=+new Date,n=K0();this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.attempt,participantAddedOrRemoved:`remove`,correlationId:n,timestampInfo:{attemptTimestamp:t}});try{$5(o4.RemoveParticipant,this.state),q2(e)}catch(e){let r=new Y({defaultError:J.IDENTIFIER.PARSE_INVALID_IDENTIFIER,originalError:e});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`remove`,correlationId:n,timestampInfo:{deltaTimeInMs:+new Date-t},additionalDetails:{code:e.code,failureReason:e.message,...K3(r)}}),r}let r=this._remoteParticipants.find((t=>W2(t.identifier)===W2(e)));if(!r){let r=new Y({defaultError:J.CALL.PARTICIPANT_NOT_IN_CALL,originalError:[wG(e).kind]});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`remove`,correlationId:n,timestampInfo:{deltaTimeInMs:+new Date-t},additionalDetails:{code:r.code,subCode:r.subCode,failureReason:r.message,...K3(r)}}),r}try{await this.tsCall.removeParticipant(W2(e)),this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.success,participantAddedOrRemoved:`remove`,correlationId:n,timestampInfo:{deltaTimeInMs:+new Date-t}})}catch(e){let{callEndReason:i}=H3(this,r.tsRemoteParticipant,e);r.callEndReason||r.setCallEndReason(i);let a=q3(i);throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`remove`,correlationId:n,timestampInfo:{deltaTimeInMs:+new Date-t},additionalDetails:{code:a?.callEndReason.code,subCode:a?.callEndReason.subCode,failureReason:a?.callEndReason.message,...a}}),new Y({defaultError:{message:i.message,code:i.code,subCode:i.subCode||0,resultCategories:i.resultCategories},originalError:e})}}async mute(){super.mute()}async unmute(){super.unmute()}async hold(){if(this.tsCall.state===4)return void this.logger.info(`Call already on hold`);if(!Z().calling.musicOnHoldEnabled)return this.logger.warn(`Music on Hold is not enabled`),super.hold();let e=+new Date,t=K0();if(this._causeId=AG(),this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:o4.Hold,kindOfEvent:$.attempt,timestampInfo:{deltaTimeInMs:e},additionalDetails:{holdType:b4.MusicOnHold,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn}}),!this._hasFetchedPolicies)try{this.logger.info(`Fetching Teams Calling Policy from Azure Communication Services`),await this._mtPolicyService.fetchUserPoliciesFromAcsMiddleTier(this.tsCall.callId,this._callAgent.getUserMri(),{policyUrlSuffix:Z().MiddleTier.policyUrlSuffixV2,userPolicies:[`TeamsCallingPolicy`]}),this._hasFetchedPolicies=!0,this._isTeamsExtensionUser&&!Z().calling.teamsExtensionSettings.enableMoh?(this._musicOnHoldEnabled=!1,this.logger.info(`Music on Hold is disabled for Teams Extension User`)):this._musicOnHoldEnabled=this._mtPolicyService.isMoHEnabled(),this.logger.info(`Music on Hold is `+(this._musicOnHoldEnabled?`enabled`:`disabled`))}catch(e){this.logger.warn(`Fetching Teams Calling Policy from Azure Communication Services failed.\n Error message = ${e?.message}, code = ${e?.code}, subcode = ${e?.subCode}.`)}return this._musicOnHoldEnabled?(Z().calling.turnOffScreenShareBeforeHold&&this.tsCall.isScreenSharingOn&&await this.tsCall.stopScreenSharing().then((()=>{this.logger.log(`Successfully turned off screen sharing before hold`)})).catch((()=>{this.logger.error(`Failed to turn off screensharing before hold`)})),await this.tsCall.hold(void 0,this._causeId,{isLocal:!0},1).then((async()=>{this.logger.info(`Successfully detached devices as part of Hold`),await this.tsCall.park(3,this._causeId).then((()=>{let n=+new Date;this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:o4.Hold,kindOfEvent:$.success,timestampInfo:{deltaTimeInMs:n-e},additionalDetails:{holdType:b4.MusicOnHold,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn}}),this.logger.info(`Successful park() as part of hold, Music on Hold completed successfully`)}))})).catch((()=>{let n=+new Date,r=new Y({defaultError:J.CALL.HOLD_CALL});throw this.logger.warn(`Attempting to perform Music on Hold failed.\n Error message = ${r.message}, code = ${r.code}, subcode = ${r.subCode}`),this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:o4.Hold,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:n-e},additionalDetails:{failureReason:r.message,code:r.code,subCode:r.subCode,holdType:b4.MusicOnHold,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn,...K3(r)}}),r}))):(this.logger.info(`Fetching of Teams Calling Policy failed or Music on Hold Disabled, proceeding with standard hold`),super.hold())}async resume(){if(this._musicOnHoldEnabled){let e=+new Date,t=K0();return this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:o4.Resume,kindOfEvent:$.attempt,timestampInfo:{deltaTimeInMs:e},additionalDetails:{holdType:b4.MusicOnHold,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn}}),await this.tsCall.unpark(3,this._causeId).then((async()=>{this.logger.info(`Successful unpark() as part of resume`),await this.tsCall.unhold(void 0,this._causeId).then((()=>{let n=+new Date;this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:o4.Resume,kindOfEvent:$.success,timestampInfo:{deltaTimeInMs:n-e},additionalDetails:{holdType:b4.MusicOnHold,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn}}),this.logger.info(`Successful unhold() as part of resume, resume completed successfully`)}))})).catch((()=>{let n=+new Date,r=new Y({defaultError:J.CALL.RESUME_CALL});throw this.logger.warn(`Attempting to perform resume from Music on Hold failed.\n Error message = ${r.message}, code = ${r.code}, subcode = ${r.subCode}`),this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:o4.Resume,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:n-e},additionalDetails:{failureReason:r.message,code:r.code,subCode:r.subCode,holdType:b4.MusicOnHold,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn,...K3(r)}}),r}))}return this.logger.info(`Music on Hold Disabled, proceeding with standard resume`),super.resume()}validateAndSetThreadId(e,t){if(!t?.threadId){let e=new Y({defaultError:J.CALL.CTE_ADDPARTICIPANT_NO_THREAD_ID});throw this.logger.error(`Error Message = ${e.message}, code = ${e.code}, subcode = ${e.subCode}`),e}return this.validateThreadIdFormat(t?.threadId),t?.threadId}validateThreadIdFormat(e){if(!e.startsWith(`19`)){let e=new Y({defaultError:J.CALL.TEAMS_INVALID_THREAD_ID});throw this.logger.error(`Error Message = ${e.message}, code = ${e.code}, subcode = ${e.subCode}`),e}}enforcePolicyAndLicenseRestrictions(){let e=+new Date;if(!this._mtPolicyService.isEvEnabled()){let t=+new Date,n=new Y({defaultError:J.CALL.CTE_VOICE_NOT_ENABLED});this.logger.error(`Error Message = ${n.message}, code = ${n.code}, subcode = ${n.subCode}`);let r=this._callAgent.getEcsConfigIds();throw this.sendCallStageEvent({eventName:Q.acs_calling_call_failed,correlationId:K0(),timestampInfo:{deltaTimeInMs:t-e},additionalPayload:{additionalProperties:{EmergencyCountryCode:this._callAgent._caConfigBag?.emergencyCountryCode||``,IsUserEmergencyCountryCode:this._callAgent._caConfigBag?.IsUserEmergencyCountryCode||!1,IsEmergencyCall:this.isEmergencyCall,trouterState:this._callAgent.getTrouterState(),AcsCallingSDKWeb_ecsConfigId:r.AcsCallingSDKWeb,SkypeWebMedia_ecsConfigId:r.SkypeWebMedia},additionalDetails:{...K3(n)}}},n,{code:n.code,subCode:n.subCode,phrase:n.message}),n}}handlePolicyAndLicenseRestrictionsFailure(e){this._callEndReason={message:`Unknown`,code:e?.code,subCode:e?.subCode,resultCategories:e?.resultCategories},this._state=`Disconnected`,this._eventEmitter.emit(`stateChanged`),this._callAgent.handleCallRemoved(this.tsCall)}async setupThreadIdWhenStartingGroupCall(e,t,n){if(t&&t.threadId&&(this.validateThreadIdFormat(t.threadId),this.logger.info(`ThreadId is already provided in the options parameter: `+JSON.stringify(t))),t===void 0||!t.threadId){let r=[];e.forEach((e=>{r.push({id:W2(e)})}));try{let e=await this._mtPolicyService.CreateChatThreadId(this.tsCall.callId,{createThreadIdSuffix:Z().MiddleTier.serverManagedThreadIdApiConfiguration.createThreadSuffix,participants:r});t||={},t.threadId=e,e&&this._info.setThreadId(e),n&&e&&(n.threadId=e)}catch(e){if(!Z().MiddleTier.serverManagedThreadIdApiConfiguration.decoupleChatThreadFromCalls)throw new Y({defaultError:J.CTE_MID_TIER_POLICY_SERVICE.CREATETHREAD_FAILED});this.logger.warn(`Failed to create thread Id for Teams group call `+e)}}}async GetOrCreateGroupChatThread(e,t,n){let r=``;if(Zle(t))return this.logger.info(`Adding TeamsExtensionUserIdentifierto call`),Promise.resolve(r);if(e)return this.logger.info(`Customer provided threadId in options: `+JSON.stringify(n)),r=this.validateAndSetThreadId(t,n),Promise.resolve(r);let i=sTe(lTe(this),wG(t));if(Z().calling.enableOpsSmePassFakeConversation&&i)return r=this.tsCall.threadId||B4(),Promise.resolve(r);if(!Z().MiddleTier.serverManagedThreadIdApiConfiguration.allowServerThreadCreation)throw new Y({defaultError:J.CALL.CTE_ADDPARTICIPANT_NO_THREAD_ID});if(this._info.threadId!==null&&this._info.threadId!==void 0){r=this._info.threadId;let e=[];return e.push({id:W2(t)}),await this._mtPolicyService.AddParticipantsToThread(this.tsCall.callId,{threadId:r,addParticipantsSuffix:Z().MiddleTier.serverManagedThreadIdApiConfiguration.addParticipantSuffix,participants:e}).catch((t=>{this.logger.warn(`Error when adding participants `+JSON.stringify(e)+` to thread. `+t)})),Promise.resolve(r)}{let e=[];return this._remoteParticipants.forEach((t=>{e.push({id:W2(t.identifier)})})),e.push({id:W2(t)}),await this._mtPolicyService.CreateChatThreadId(this.tsCall.callId,{createThreadIdSuffix:Z().MiddleTier.serverManagedThreadIdApiConfiguration.createThreadSuffix,participants:e}).then((e=>{r=e,this.logger.info(`Add participant into 1on1 call to convert it into Teams group call. Create thread id: `+r)})).catch((e=>{let n=`Error when adding participants `+W2(t)+` to thread to create a Teams group call. `;if(!Z().MiddleTier.serverManagedThreadIdApiConfiguration.decoupleChatThreadFromCalls)throw new Y({defaultError:J.CTE_MID_TIER_POLICY_SERVICE.CREATETHREAD_FAILED});this.logger.warn(n+e)})),Promise.resolve(r)}}addParticipantToTsCall(e,t,n,r,i,a){this.tsCall.addParticipant(W2(e),{threadId:t,customHeaderContext:V4(n)}).then((()=>{this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.success,participantAddedOrRemoved:`add`,correlationId:i,timestampInfo:{deltaTimeInMs:+new Date-a}})})).catch((t=>{let{callEndReason:n}=H3(this,r.tsRemoteParticipant,t);r.callEndReason||r.setCallEndReason(n);let o=q3(n);this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`add`,correlationId:i,timestampInfo:{deltaTimeInMs:+new Date-a},additionalDetails:{code:o?.callEndReason.code,subCode:o?.callEndReason.subCode,failureReason:o?.callEndReason.message,...o}}),this._remoteParticipants.find((t=>W2(t.identifier)===W2(e)))&&(this.deleteRemoteParticipant(r),this._eventEmitter.emit(`remoteParticipantsUpdated`,{added:[],removed:[r]}))}))}IsTargetUserAllowed(e){return Qle(e)||xG(e)||bG(e)}};F9([KG(o4.AddParticipant),WG(o4.AddParticipant),I9(`design:type`,Function),I9(`design:paramtypes`,[Object,Object]),I9(`design:returntype`,Object)],L9.prototype,`addParticipant`,null),F9([KG(o4.RemoveParticipant),GG(o4.RemoveParticipant),I9(`design:type`,Function),I9(`design:paramtypes`,[Object]),I9(`design:returntype`,Promise)],L9.prototype,`removeParticipant`,null),F9([KG(o4.Mute),I9(`design:type`,Function),I9(`design:paramtypes`,[]),I9(`design:returntype`,Promise)],L9.prototype,`mute`,null),F9([KG(o4.Unmute),I9(`design:type`,Function),I9(`design:paramtypes`,[]),I9(`design:returntype`,Promise)],L9.prototype,`unmute`,null),F9([KG(o4.Hold),GG(o4.Hold),I9(`design:type`,Function),I9(`design:paramtypes`,[]),I9(`design:returntype`,Promise)],L9.prototype,`hold`,null),F9([KG(o4.Resume),GG(o4.Resume),I9(`design:type`,Function),I9(`design:paramtypes`,[]),I9(`design:returntype`,Promise)],L9.prototype,`resume`,null);var R9=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},z9=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},B9=class e extends Y7{get calls(){return this._calls}constructor(e,t,n,r,i,a){super(e,t,r,i,n,BG.TeamsCallAgent,a),this._calls=[],this.handleCallAdded=e=>{if(!this._calls.find((t=>t.id===e.callId))){let t=e.on(`callStateChanged`,(async()=>{if(e.state===1){let n=U6(e),r=e.callId;t.dispose();let i=new L9({callId:r,isIncoming:!0},this,e,this._telemetryLogManager);n&&(i=X7(i));let a=new URe(i);this.handleCallState(i),n?await Promise.all(i.bindTsCall()):i.bindTsCall(),this._eventEmitter.emit(`incomingCall`,{incomingCall:a})}}))}},this.handleCallRemoved=e=>{this.logger.info(`removing callId=${e.callId}`);let t=this._calls.find((t=>t.id===e.callId));if(t){if(t.isBreakoutRoomCall){let e=Z().calling.breakoutRooms.hangUpCallDelayInMilliSeconds;setTimeout((()=>{this.disposeCall(t)}),e)}else this.disposeCall(t);this._eventEmitter.emit(`callsUpdated`,{added:[],removed:[t]}),this.logger.info(`call removed`)}},this.handleCallState=e=>{e.on(`stateChanged`,(async()=>{try{e.state===`Disconnected`?this.tsStack?(await this._tsCallRegistry.deleteCallAsync?.(e.tsCall)||this.logger.info(`The call has been removed from registry, call id: ${e.id}`),e.stats.flushEvents(),this._telemetryLogManager.flushAllEvents(e.id).catch((()=>{this.logger.error(`Failed to flush telemetry log manager events`)}))):this.logger.info(`Unable to remove call from registry`):e.state===`Connecting`&&e.direction==`Incoming`&&(this.addToCallArray(e),this._eventEmitter.emit(`callsUpdated`,{added:[e],removed:[]}))}catch{this.logger.error(`Failed to handle call state changed event`)}}))},this.logger=t}createNewCall(e,t){let n=new L9({callId:e},this,t,this._telemetryLogManager);return U6(t)?X7(n):n}addToCallArray(e){this._calls.push(e),this.trackCallEndTimeToStopTelemetry(this._calls)}addToCallAgentsMap(t){e.teamsCallAgents.get(t?.identityMri)&&k4(J.CALL_AGENT.TEAMS_CALLAGENT_ALREADY_EXSISTS,this.logger),e.teamsCallAgents.set(t?.identityMri,this)}removeFromCallAgentsMap(t){t?.identityMri&&e.teamsCallAgents.get(t?.identityMri)===this&&e.teamsCallAgents.delete(t?.identityMri)}disposeCall(e){let t=this._calls.indexOf(e);t!==-1&&this._calls.splice(t,1),e.dispose(),this.trackCallEndTimeToStopTelemetry(this._calls)}getMiddleTierServiceInstance(){return this.mtPolicyService}async setUserPoliciesOnAgentInitialization(){super.setUserPoliciesOnAgentInitialization();try{if(this.isEnterpriseUser()){let e=K0();this.logger.info(`ACS MiddleTier service called on Teams Call Agent initialization with call Id=${e}`),await this.mtPolicyService.fetchUserPoliciesFromAcsMiddleTier(e,this.getUserMri(),{policyUrlSuffix:Z().MiddleTier.policyUrlSuffixV2,userPolicies:[`EmergencyPolicies`,`TeamsCallingPolicy`,`TeamsMeetingPolicy`],userProperties:[`FeatureTypes`,`PoliciesMetadata`,`phoneNumber`,`sipUri`,`hostType`,`accountEnabled`,`useTeamsCalling`,`evEnabled`,`region`,`routingType`,`preferredDataLocation`,`featureTypes`,`displayName`]}),this._userPolicies=this.mtPolicyService.getUserPolicy(),this._userProperties=this.mtPolicyService.getUserProperties(),this.logger.info(`****User policy initialized to ${JSON.stringify(this._userPolicies)}`),this.logger.info(`****User properties initialized to ${JSON.stringify(this._userProperties)}`)}}catch(e){this.logger.warn(`Fetching Teams user policy and Properties from ACS MiddleTier Service failed.\n Error message = ${e?.message}, code = ${e?.code}, subcode = ${e?.subCode}.`)}}async disposeInternal(t){let n=+new Date,r=K0();this.sendCallAgentDisposeEvent({eventName:Q.acs_calling_client_operations,operation:K7.disposeTeamsCallAgent,kindOfEvent:`attempt`,timestampInfo:{},correlationId:r,additionalDetails:``});try{if(this._disposed)throw new Y({defaultError:J.CALL_AGENT.CTE_ALREADY_DISPOSED});this._disposed=!0,this._abortController.abort(),this._extensibleApi.dispose(),this._parsedTokenCredential?.identityMri&&e.teamsCallAgents.delete(this._parsedTokenCredential?.identityMri);for(let e of this._calls)e.state!==`Disconnected`&&await e.hangUp().catch((()=>{this.logger.error(`Failed to hangup call during Teams call agent dispose`)}));await this._tsCallRegistry?.dispose();let t=this._tokenFetchTries>this._maxNmberOfRetries;await this._callStack.disposeUserStack(t),this.offTrouterStateChanged(this._trouterStateChangeCallback),this._callStack.offRegisteredChanged(this._registrarStateChangeCallback),this._eventEmitter.removeAllListeners(),this._internalEventEmitter.emit(`disposed`),this._internalEventEmitter.removeAllListeners(),this.sendCallAgentDisposeEvent({eventName:Q.acs_calling_client_operations,operation:K7.disposeTeamsCallAgent,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:``})}catch(e){let t=new Y({defaultError:J.CALL_AGENT.TEAMS_DISPOSE_FAIL,originalError:e});throw this.sendCallAgentDisposeEvent({eventName:Q.acs_calling_client_operations,operation:K7.disposeTeamsCallAgent,kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{failureReason:t.message,code:t.code,subCode:t.subCode,...K3(t)}}),t}finally{t&&this._telemetryLogManager.clearTelemetryLoggers()}}startCall(e,t){let n=K0(),r=+new Date,i={correlationId:n,timestampInfo:{attemptTimestamp:r}};this._telemetryLogManager.sendEvent({name:Q.acs_calling_call_attempt,tenant:d2,properties:i},void 0,`attempt`);try{let i;if(this.assertParticipants(e),Array.isArray(e)){if(this.isTeamsExtensionUser()&&!Z().calling.teamsExtensionSettings.enableJoinCall)throw new Y({defaultError:J.FEATURES.ONE_PHONE_SYSTEM.CALL_CANNOT_BE_STARTED});if(i=t,e.length>1&&!Z().MiddleTier.serverManagedThreadIdApiConfiguration.allowServerThreadCreation&&!i?.threadId)throw new Y({defaultError:J.CALL_AGENT.GROUPCALL_THREADID});if(e.length==1&&i?.threadId)throw new Y({defaultError:J.CALL_AGENT.ONE_TO_ONE_THREADID})}else{if(this.isTeamsExtensionUser()&&!Z().calling.teamsExtensionSettings.enableStartCall)throw new Y({defaultError:J.FEATURES.ONE_PHONE_SYSTEM.CALL_CANNOT_BE_STARTED});i=t}if(Z().calling.enableSmePassFakeConversation&&this.isAcsToTeamsInteropCall(e)&&!this.isTeamsExtensionUser())throw new Y({defaultError:J.CALL_AGENT.UNSUPPORTED_TARGET_TYPE});let a=i?.audioOptions?.muted;return a===void 0&&(a=!1),this.logger.info(`startCall with video=${!!i?.videoOptions},muted=${a}`),this.createCall({participants:e,startCallOptions:i},{correlationId:n,attemptTimestamp:r})}catch(e){let t,i;throw e instanceof Y&&(t=typeof e?.message==`string`?e?.message:void 0,i={...K3(e)}),this._telemetryLogManager.sendEvent({name:Q.acs_calling_call_failed,tenant:d2,properties:{correlationId:n,timestampInfo:{deltaTimeInMs:+new Date-r},failureReason:t||``,additionalDetails:i||{}}},void 0,`failure`),e}finally{this._telemetryLogManager.deleteEventMapByCorrelationId(n)}}join(e,t){this.assertCallContext(e);let n=!!t?.audioOptions?.muted;return this.logger.info(`join with video=${!!t?.videoOptions},muted=${n}`),this.createCall({teamsCallContext:e,startCallOptions:t})}async dispose(){await this.disposeInternal(!0)}on(e,t){if(e!==`incomingCall`&&e!==`callsUpdated`&&e!==`connectionStateChanged`&&e!==`customContextChanged`)throw new Y({defaultError:J.CALL_AGENT.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if(e!==`incomingCall`&&e!==`callsUpdated`&&e!==`connectionStateChanged`&&e!==`customContextChanged`)throw new Y({defaultError:J.CALL_AGENT.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}createCall(e,t){if(!this.tsStack)throw new Y({defaultError:J.CALL_AGENT.STACK_NOT_INIT});let n,r,i,a=e?.teamsCallContext?.threadId,o=!1,s=e?.teamsCallContext?.meetingLink,c=e?.teamsCallContext?.meetingId,l=e?.teamsCallContext?.passcode||``,u=!!e?.participants&&Array.isArray(e?.participants)&&e?.participants.length>1;if(this.isEnterpriseUser()&&u&&(a=(e?.startCallOptions).threadId),!R4(this.acsProxy,this.acsCustomRelayManager,!0))throw new Y({defaultError:J.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN});if(s)if(vFe(s))r=M5(s);else{if(!yFe(s,this.logger))throw new Y({defaultError:J.CALL_AGENT.INVALID_MEETING_LINK});if(bFe(s.trim().toLocaleLowerCase(),Z().calling.tfl.hosts))throw new Y({defaultError:J.CALL_AGENT.UNSUPPORTED_TFL_MEETING_JOIN});o=!0}e?.teamsCallContext?.threadId&&e?.teamsCallContext?.organizerId&&e?.teamsCallContext?.tenantId&&(r={threadId:e?.teamsCallContext?.threadId,messageId:e?.teamsCallContext?.messageId?e?.teamsCallContext?.messageId.toString():`0`,organizerId:e?.teamsCallContext?.organizerId,tenantId:e?.teamsCallContext?.tenantId}),r&&(i={meetingType:r.messageId===`0`?1:2,tenantId:r.tenantId,organizerId:r.organizerId,replyChainMessageId:r.messageId},a=r.threadId,n=r.messageId);let d=this.mtPolicyService.isEmergencyNumber(this.isEnterpriseUser(),e?.participants),f=this.getOnBehalfOfMri(e,u,d),p={threadId:a||``,messageId:n||``,meetingInfo:i,mediaPeerType:2,onBehalfOf:f},m=U6(this._tsCallRegistry),h=AG(),g=K0(),_=K0();if(m){let r=X7();return(async()=>{let i;i=c?await this._tsCallRegistry.createCallAsync({callId:g,localParticipantId:_,causeId:h,type:`MeetingData`,meetingData:{meetingCode:c,passcode:l,threadId:a}}):o?await this._tsCallRegistry.createCallAsync({callId:g,localParticipantId:_,causeId:h,type:`MeetingData`,meetingData:{meetingUrl:s}}):await this._tsCallRegistry.createCallAsync({callId:g,localParticipantId:_,causeId:h,type:`ThreadId`,threadId:a||``,messageId:n});let u=new L9({callId:g,isEmergencyNumber:d},this,i,this._telemetryLogManager);r.setTarget(u),this.addToCallArray(r),this.handleCallState(r);let f=e3();u.startCallInternal(e?.startCallOptions,!!c,e?.teamsCallContext,p,t,f,e?.participants).catch(A4),await Promise.all(u.bindTsCall()),await f.promise,this._eventEmitter.emit(`callsUpdated`,{added:[r],removed:[]})})().catch((e=>{})),r}{let r;r=c?this._tsCallRegistry.createCallWithMeetingData({meetingCode:c,passcode:l,threadId:a},g,_,h):o?this._tsCallRegistry.createCallWithMeetingData({meetingUrl:s},g,_,h):this._tsCallRegistry.createCall(a||``,g,_,n,h);let i=new L9({callId:g,isEmergencyNumber:d},this,r,this._telemetryLogManager);return this.addToCallArray(i),this.handleCallState(i),i.startCallInternal(e?.startCallOptions,!!c,e?.teamsCallContext,p,t,void 0,e?.participants).catch(A4),i.bindTsCall(),this._eventEmitter.emit(`callsUpdated`,{added:[i],removed:[]}),i}}getOnBehalfOfMri(e,t,n){let r=e?.startCallOptions?.onBehalfOfOptions?.userId;if(r){if(!Z().calling.sharedLineAppearance.enabled)throw this.logger.error(`SharedLineAppearance is disabled by ECS flag`),new Y({defaultError:J.FEATURES.SHAREDLINE_APPEARANCE.DISABLED});if((e?.startCallOptions).customContext&&!Z().calling.teamsExtensionSettings.enableCustomContext)throw new Y({defaultError:J.FEATURES.ONE_PHONE_SYSTEM.CUSTOM_CONTEXT_NOT_SUPPORTED});if(t)throw new Y({defaultError:J.FEATURES.SHAREDLINE_APPEARANCE.GROUP_CALLS_NOT_SUPPORTED});if(!n){if(CG(r)&&!Z().calling.sharedLineAppearance.appOnBehalfOfEnabled)throw this.logger.error(`Start Teams call with onBehalfOf MicrosoftTeamsAppIdentifier is disabled by ECS flag`),new Y({defaultError:J.FEATURES.SHAREDLINE_APPEARANCE.DISABLED_FOR_APPLICATIONS});if(SG(r)){if(!Z().calling.sharedLineAppearance.userOnBehalfOfEnabled)throw this.logger.error(`Start Teams call with onBehalfOf MicrosoftTeamsUserIdentifier is disabled by ECS flag`),new Y({defaultError:J.FEATURES.SHAREDLINE_APPEARANCE.DISABLED});if(!this.getUserPolicy()?.teamsCallingPolicy?.allowDelegation)throw this.logger.error(`Start Teams call with onBehalfOf MicrosoftTeamsUserIdentifier is disabled by Teams calling policy`),new Y({defaultError:J.FEATURES.SHAREDLINE_APPEARANCE.DISABLED_BY_CALLING_POLICY})}return $le(r)}this.logger.warn(`Emergency call cannot be made on behalf of another user, dropping the onBehalfOf options`)}}assertParticipants(e){Ywe(e,J.CALL_AGENT.USERIDS_MUST_BE_OBJECTS),Jwe(e,J.CALL_AGENT.USERIDS_CANNOT_BE_NULL)}assertCallContext(e){if(!e||this.checkForAtLeastOneValidCallConfig(e)||this.checkForInvalidTeamsMeetingCoordinates(e))throw new Y({defaultError:J.CALL_AGENT.INVALID_JOIN_LOCATOR})}checkForAtLeastOneValidCallConfig(e){return!e.threadId&&!e.meetingLink&&!e.meetingId}checkForInvalidTeamsMeetingCoordinates(e){return!e.threadId&&e.tenantId&&e.organizerId||e.threadId&&(e.organizerId&&!e.tenantId||!e.organizerId&&e.tenantId)}isAcsToTeamsInteropCall(e){let t=!1;return this.isEnterpriseUser()&&(Array.isArray(e)?e.length>=1&&e.find((e=>bG(e)))&&(t=!0):bG(e)&&(t=!0)),t}};B9.teamsCallAgents=new Map,R9([WG(a4.StartCall),z9(`design:type`,Function),z9(`design:paramtypes`,[Object,Object]),z9(`design:returntype`,Object)],B9.prototype,`startCall`,null),R9([WG(a4.Join),z9(`design:type`,Function),z9(`design:paramtypes`,[Object,Object]),z9(`design:returntype`,Object)],B9.prototype,`join`,null),R9([GG(a4.Dispose),z9(`design:type`,Function),z9(`design:paramtypes`,[]),z9(`design:returntype`,Promise)],B9.prototype,`dispose`,null);var WRe=class{constructor(){this._proxyInUse=!1;let e=KW(`ACS-calling`);this.logger=new z6(e,[()=>`AcsProxy`])}get proxyInUse(){return this._proxyInUse}set proxyInUse(e){this._proxyInUse=e}get proxyUrl(){return this._proxyUrl?.toString()||``}set proxyUrl(e){if(e.length<4)throw new Y({defaultError:J.CALL_CLIENT.PROXY_SHORT_URL});e.slice(-1)!==`/`&&(e=e.concat(``,`/`));try{let t=new URL(e);if(t.protocol!==`https:`&&t.protocol!==`http:`)throw new Y({defaultError:J.CALL_CLIENT.PROXY_PROTOCOL});this._proxyUrl=t}catch(t){let n=new Y({defaultError:J.CALL_CLIENT.SETUP_PROXY,defaultErrorMessageArgs:[e],originalError:t});throw this.logger.error(n.message),n}}hasProxyUrl(){return!!this._proxyUrl}proxyfyUrl(e){let t=e;if(!this._proxyUrl)return this.logger.info(`Proxy url not defined, return original ${e4(t)}`),t;try{let e=new URL(t);t=`${`${e.protocol}//${this._proxyUrl.host}${this._proxyUrl.pathname}`}${e.host}${e.pathname}${e.search}`,this.logger.info(`Proxyfing url from ${e4(e)} to ${e4(t)}`)}catch(e){let t=`Failed proxyfy url with error: ${JSON.stringify(e)}, returning original`;this.logger.error(t)}return this._proxyInUse=!0,t}},GRe=class{constructor(){this._hasCustomRelay=!1,this._customRelayManagerInUse=!1;let e=KW(`ACS-calling`);this._logger=new z6(e,[()=>`AcsCustomRelayManager`])}getRelayConfig(){return this._relayConfig}setRelayConfig(e){this._relayConfig={...e},this._logger.info(`Custom relay config provided`),this._hasCustomRelay=!0,this._createTsRelayManager()}get hasRelayConfig(){return this._hasCustomRelay}get customRelayManagerInUse(){return this._customRelayManagerInUse}set customRelayManagerInUse(e){this._customRelayManagerInUse=e}getTsRelayManager(){return this._tsRelayManager}_createTsRelayManager(){if(!this._hasCustomRelay||!this._relayConfig||this._relayConfig.iceServers.length<1)return void this._logger.warn(`No relay config provided. No op.`);let e=[];this._relayConfig.iceServers.forEach((t=>{t.urls.forEach((n=>{let r=this._getIndividualRelay(n,t?.username,t?.credential);e.push(r)}))})),this._tsRelayManager={initialize(){},queryRelaysAsync:t=>Promise.resolve(e)}}_getIndividualRelay(e,t,n){let r=3478,i=[],a=[],o=[v3.turn,v3.turns,v3.stun],s=[y3.tcp,y3.tls,y3.udp],c;try{c=new URL(e)}catch(t){throw new Y({defaultError:J.CALL_CLIENT.RELAY_INFO,defaultErrorMessageArgs:[e],originalError:t})}let l=c.protocol.replace(`:`,``);if(!o.includes(l))throw new Y({defaultError:J.CALL_CLIENT.RELAY_UNRECOGNIZED_SCHEMA});let u,d=``;try{d=c.href.replace(/((turn)s?|stun):/,`https:`),u=new URL(d)}catch(e){throw new Y({defaultError:J.CALL_CLIENT.RELAY_INFO,defaultErrorMessageArgs:[d],originalError:e})}let f=u.searchParams.get(`transport`)??``;s.includes(f)||(this._logger.warn(`Unknown transport protocol detected for the provided turn, defaulting to ${y3.udp}`),f=y3.udp);let p=u.port===``?this._extractPortFromUrl(c):Number(u.port);p||=(this._logger.warn(`Could not read port from relay url, defaulting to ${r}`),r);let m=u.hostname;return xwe(m)?i.push(m):a.push(m),{addresses:i,udpPort:f===y3.udp?p:void 0,tcpPort:f===y3.tcp?p:void 0,tlsPort:f===y3.tls?p:void 0,username:t??``,password:n??``,type:`turn`,fqdns:a}}_extractPortFromUrl(e){let t=e.href.match(owe)?.[0];return Number(t?.replace(`:`,``))}},KRe=class{constructor(e,t,n){this._eventEmitter=new w3.EventEmitter,this._removeListeners=[];let r=(e,r)=>{n()&&t.sendEvent({name:Q.acs_calling_page_hidden,tenant:d2,properties:{eventName:e,pageHidden:r}})},i=()=>{document.visibilityState===`hidden`?(e.debug(`Visibility changed to hidden`),r(`visibilityChange`,!0),this._eventEmitter.emit(`visibilityChange`,!0)):(e.debug(`Visibility changed to visible`),r(`visibilityChange`,!1),this._eventEmitter.emit(`visibilityChange`,!0))},a=()=>{e.debug(`Page show`),r(`pageShow`,!1),this._eventEmitter.emit(`pageShow`)},o=()=>{e.debug(`Page hide`),r(`pageHide`,!0),this._eventEmitter.emit(`pageHide`)};window.addEventListener(`visibilitychange`,i),this._removeListeners.push((()=>window.removeEventListener(`visibilitychange`,i))),window.addEventListener(`pageshow`,a),this._removeListeners.push((()=>window.removeEventListener(`pageshow`,a))),window.addEventListener(`pagehide`,o),this._removeListeners.push((()=>window.removeEventListener(`pagehide`,o)));let s=(e,r)=>{n()&&t.sendEvent({name:Q.acs_calling_orientation_changed,tenant:d2,properties:{orientation:e,isInitial:r}})},c=()=>{let t=screen.orientation.type;e.debug(`Orientation changed to ${t}`),s(t,!1),this._eventEmitter.emit(`orientationChanged`,t)},l=()=>window.innerHeight>window.innerWidth?`portrait-primary`:`landscape-primary`,u=``,d=()=>{let t=l();u!==t&&(e.debug(`Orientation changed to ${t}`),u=t,s(t,!1),this._eventEmitter.emit(`orientationChanged`,t))};screen?.orientation?.type?(screen.orientation.addEventListener(`change`,c),this._removeListeners.push((()=>screen.orientation.removeEventListener(`change`,c))),s(screen.orientation.type,!0)):(window.addEventListener(`resize`,d),this._removeListeners.push((()=>window.removeEventListener(`resize`,d))),s(l(),!0))}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}dispose(){this._eventEmitter.removeAllListeners(),this._removeListeners.forEach((e=>e()))}},qRe,V9=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},H9=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},JRe=1,U9=class e{get callAgent(){return this._callAgent}get teamsCallAgent(){return this._teamsCallAgent}get sdkDiagnosticInformation(){return this._sdkDiagnosticInformation}get telemetryLogManager(){return this._telemetryLogManager}setCallAgent(e){this._callAgent=e}setTeamsCallAgent(e){this._teamsCallAgent=e}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}constructor(e){this._disposed=!1,this._customProxyAndTurnInformation={proxy:null,turn:null},this.sendTelemetry=()=>{try{if(Z().telemetry.telemetryBeforeUnload&&this._callAgent&&this._callAgent._calls)for(let e of this._callAgent._calls)e.tsCall.sendLastKnownStats()}catch(e){this.logger.debug(`Error logging telemetry`,e)}};let t=+new Date;this.clientId=K0();let n=e?.logger||KW(`ACS-calling`),r=JRe++;if(this._acsProxy=new WRe,this._acsCustomRelayManager=new GRe,this._vdi3Options=e?.vdi3,e?.networkConfiguration){e.networkConfiguration.proxy?.url&&(this._customProxyAndTurnInformation.proxy={...e.networkConfiguration.proxy},this._acsProxy.proxyUrl=this._customProxyAndTurnInformation.proxy.url),e.networkConfiguration.turn&&(this._customProxyAndTurnInformation.turn={...e.networkConfiguration.turn},this._acsCustomRelayManager.setRelayConfig(this._customProxyAndTurnInformation.turn));let t=this.getTelemetryTag();e.diagnostics?e.diagnostics.tags?e.diagnostics.tags.push(t):e.diagnostics.tags=[t]:e.diagnostics={tags:[t]}}this.logger=new z6(n,[()=>`CallClient${r}[${this.clientId}]`]),this._eventEmitter=new S6(this.logger),this._sdkDiagnosticInformation=tTe(Y2(),this.logger,e),this.diagnosticOptions=e?.diagnostics,this.firstPartyOptions=e?.firstPartyOptions,this._telemetryLogManager=new f3(this.logger,this._sdkDiagnosticInformation,this._acsProxy,this._acsCustomRelayManager);try{this.sendCallClientInitEvent({eventName:Q.acs_calling_call_client_init,kindOfEvent:`attempt`,timestampInfo:``,additionalDetails:``}),Object.defineProperty(globalThis,x2,{value:r,writable:!0,enumerable:!1}),r===1&&Object.defineProperty(globalThis,b2,{value:this._telemetryLogManager,writable:!1,enumerable:!1}),this.logger.info(`created`),this._callStack=new A9(this.logger,this.clientId,this._telemetryLogManager,this._sdkDiagnosticInformation,this._acsProxy,this._acsCustomRelayManager,this.firstPartyOptions?.encodedStreamsJsPath,this._vdi3Options),this._deviceManager=new N9(this.logger,this._callStack,this._telemetryLogManager),window.addEventListener(`beforeunload`,this.sendTelemetry),this._screenDeviceManager=new KRe(this.logger,this._telemetryLogManager,(()=>this._callAgent?.calls?this._callAgent.calls.length>0:!!this._teamsCallAgent?.calls&&this._teamsCallAgent.calls.length>0)),this._screenDeviceManager.on(`visibilityChange`,(e=>{if(e)try{t8().formFactor===`Mobile`&&Z().calling.hangUpCallOnPageHide&&(this._callAgent?.calls.forEach((e=>e.hangUp())),this._teamsCallAgent?.calls.forEach((e=>e.hangUp())))}catch(e){this.logger.error(`Unable to hangup call on page hide due to ${e}`)}})),this._extensibleApi=new N3(this.logger,{callClient:this},{callClient:this,telemetryLogManager:this._telemetryLogManager});let e=Q5(D3.CallClientFeature);for(let t of e)t.activationOptions.activationEvent===`OnExtendedObjectConstructor`&&this.feature(t);this.sendCallClientInitEvent({eventName:Q.acs_calling_call_client_init,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:+new Date-t},additionalDetails:``})}catch(e){let n=new Y({defaultError:J.CALL_CLIENT.INIT_CALL_CLIENT,originalError:e});throw this.sendCallClientInitEvent({eventName:Q.acs_calling_call_client_init,kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:+new Date-t},additionalDetails:{failureReason:n.message,code:n.code,subCode:n.subCode,...K3(n)}}),n}}createInstance(t){return new e(t)}get acsProxy(){return this._acsProxy}get acsCustomRelayManager(){return this._acsCustomRelayManager}getSDKVersion(){return Y2()}async getEnvironmentInfoInternal(){return this._environmentInfos||=(await this._callStack.createStackBase(),hke()),this._environmentInfos}feature(e){return this._extensibleApi.getApiObjectInstance(e.callClientApiCtor)}async createCallAgent(e,t){if(this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});let n=+new Date,r=K0();this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:K7.createCallAgent,kindOfEvent:`attempt`,timestampInfo:{},correlationId:r,additionalDetails:``});let{identityMri:i}=await M4(e);if(this._callAgent?._caConfigBag?.identityMri===i)return this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:K7.createCallAgent,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{context:`ACS CallAgent already exists in this call client for the given identity.`}}),this._callAgent;if(this._callAgent||this._teamsCallAgent){let e=new Y({defaultError:J.CALL_CLIENT.ONE_CALL_AGENT_PER_CALL_CLIENT});this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:K7.createCallAgent,kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{context:`ACS CallAgent already exists in this call client.`,failureReason:e.message,code:e.code,subCode:e.subCode,...K3(e)}}),k4(J.CALL_CLIENT.ONE_CALL_AGENT_PER_CALL_CLIENT,this.logger)}if(this._callAgent=e9.callAgents.get(i),this._callAgent)return this._callAgent.onDisposed((()=>{this._callAgent=void 0})),this._eventEmitter.emit(`callAgentCreated`),this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:K7.createCallAgent,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{context:`ACS Call Agent already exists for the given identity. Maybe have been created by another call client instance.`}}),this._callAgent;this.validateEmergencyCountryCode(t);try{return this._callAgent=new e9(this,this.logger,this._callStack,this.clientId,this._telemetryLogManager,this._deviceManager,t),await this._callAgent.initialize(e,t),this._callAgent.onDisposed((()=>{this._callAgent=void 0})),this._eventEmitter.emit(`callAgentCreated`),this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:K7.createCallAgent,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{context:`ACS CallAgent created and initialized successfully.`}}),this._callAgent}catch(e){this._callAgent=void 0;let t=new Y({defaultError:J.CALL_CLIENT.CREATE_CALL_AGENT,originalError:e});throw this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:K7.createCallAgent,kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{failureReason:t.message,code:t.code,subCode:t.subCode,...K3(t)}}),this._telemetryLogManager.clearTelemetryLoggers(),t}}async createTeamsCallAgent(e,t){if(this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});let n=+new Date,r=K0();this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:K7.createTeamsCallAgent,kindOfEvent:`attempt`,timestampInfo:{},correlationId:r,additionalDetails:``});let{identityMri:i,mriType:a}=await M4(e);if(a==e2.TeamsExtensionUser?this.logger.info(`TeamsCallAgent is TeamsExtensionUser type`):this.logger.info(`TeamsCallAgent is not TeamsUser type`),this._teamsCallAgent?._caConfigBag?.identityMri===i)return this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:K7.createTeamsCallAgent,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{context:`Teams Call Agent already exists in this call client for the given identity.`}}),this._teamsCallAgent;if(this._callAgent||this._teamsCallAgent){let e=new Y({defaultError:J.CALL_CLIENT.ONE_CALL_AGENT_PER_CALL_CLIENT});this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:K7.createTeamsCallAgent,kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{context:`Teams Call Agent already exists in this call client.`,failureReason:e.message,code:e.code,subCode:e.subCode,...K3(e)}}),k4(J.CALL_CLIENT.ONE_CALL_AGENT_PER_CALL_CLIENT,this.logger)}if(this._teamsCallAgent=B9.teamsCallAgents.get(i),this._teamsCallAgent)return this._teamsCallAgent.onDisposed((()=>{this._teamsCallAgent=void 0})),this._eventEmitter.emit(`teamsCallAgentCreated`),this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:K7.createTeamsCallAgent,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{context:`Teams Call Agent already exists for the given identity. Maybe have been created by another call client instance.`}}),this._teamsCallAgent;try{return this._teamsCallAgent=new B9(this,this.logger,this._callStack,this.clientId,this._telemetryLogManager,this._deviceManager),await this._teamsCallAgent.initialize(e,t),this._teamsCallAgent.onDisposed((()=>{this._teamsCallAgent=void 0})),this._eventEmitter.emit(`teamsCallAgentCreated`),this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:K7.createTeamsCallAgent,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{context:`TeamsCallAgent created and initialized successfully.`}}),this._teamsCallAgent}catch(e){this._teamsCallAgent=void 0;let t=new Y({defaultError:J.CALL_CLIENT.CREATE_TEAMS_CALL_AGENT,originalError:e});throw this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:K7.createTeamsCallAgent,kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{failureReason:t.message,code:t.code,subCode:t.subCode,...K3(t)}}),this._telemetryLogManager.clearTelemetryLoggers(),t}}async getDeviceManager(){if(this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});return this._callAgent&&this._callAgent?.callClient!==this?(await this._callAgent?.deviceManager.getDeviceManager(),this._callAgent?.deviceManager):(await this._deviceManager.getDeviceManager(),this._deviceManager)}async dispose(){if(this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});let e=+new Date,t=K0();try{this._disposed=!0,this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:K7.disposeCallClient,kindOfEvent:`attempt`,timestampInfo:{},correlationId:t,additionalDetails:``});try{this._deviceManager.dispose(),this.logger.info(`Device Manager disposed`)}catch{this.logger.error(`Call Client failed to dispose Device Manager`)}try{this._callAgent?await this._callAgent.disposeInternal(!1).then((()=>{this.logger.info(`ACS Call Agent disposed`)})):this._teamsCallAgent&&await this._teamsCallAgent.disposeInternal(!1).then((()=>{this.logger.info(`Teams Call Agent disposed`)}))}catch(e){e.subCode!==J.CALL_AGENT.ACS_ALREADY_DISPOSED.subCode&&e.subCode!==J.CALL_AGENT.CTE_ALREADY_DISPOSED.subCode||this.logger.debug(`Call Client failed to dispose Call Agent as it is already disposed`),this.logger.error(`Call Client failed to dispose Call Agent`)}try{this._screenDeviceManager.dispose()}catch{this.logger.error(`Call Client failed to dispose ScreenDevice Manager`)}try{await this._callStack.disposeBaseStack(),this.logger.info(`Base call stack disposed`)}catch{this.logger.error(`Call Client failed to dispose base call stack`)}this._eventEmitter.removeAllListeners(),window.removeEventListener(`beforeunload`,this.sendTelemetry),this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:K7.disposeCallClient,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:+new Date-e},correlationId:t,additionalDetails:``})}catch(n){let r=new Y({defaultError:J.CALL_CLIENT.DISPOSE_FAIL,originalError:n});throw this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:K7.disposeCallClient,kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:+new Date-e},correlationId:t,additionalDetails:{failureReason:r.message,code:r.code,subCode:r.subCode,...K3(r)}}),r}finally{this._telemetryLogManager.clearTelemetryLoggers()}}validateEmergencyCountryCode(e){e?.emergencyCallOptions?.countryCode&&e.emergencyCallOptions?.countryCode.length>kCe&&k4(J.CALL_CLIENT.EMERGENCY_CODE_TOO_LONG,this.logger)}sendCallClientInitEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:d2,properties:e})}catch{this.logger.debug(`Unable to send CallClient initialized telemetry event`)}}sendCallClientOperationEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:d2,properties:e})}catch{this.logger.debug(`Unable to send CallClient dispose telemetry event`)}}getTelemetryTag(){return this._customProxyAndTurnInformation.proxy&&this._customProxyAndTurnInformation.turn?R2.usedProxyAndNonMsftTurn:this._customProxyAndTurnInformation.proxy?R2.onlyUsedProxy:this._customProxyAndTurnInformation.turn?R2.onlyUsedNonMsftTurn:``}};V9([zG,H9(`design:type`,Object)],U9.prototype,`logger`,void 0),V9([WG(i4.Feature),H9(`design:type`,Function),H9(`design:paramtypes`,[Object]),H9(`design:returntype`,typeof(qRe=typeof TFeature<`u`&&TFeature)==`function`?qRe:Object)],U9.prototype,`feature`,null),V9([GG(i4.CreateCallAgent),H9(`design:type`,Function),H9(`design:paramtypes`,[Object,Object]),H9(`design:returntype`,Promise)],U9.prototype,`createCallAgent`,null),V9([GG(i4.CreateTeamsCallAgent),H9(`design:type`,Function),H9(`design:paramtypes`,[Object,Object]),H9(`design:returntype`,Promise)],U9.prototype,`createTeamsCallAgent`,null),V9([GG(i4.GetDeviceManager),H9(`design:type`,Function),H9(`design:paramtypes`,[]),H9(`design:returntype`,Promise)],U9.prototype,`getDeviceManager`,null),V9([GG(i4.Dispose),H9(`design:type`,Function),H9(`design:paramtypes`,[]),H9(`design:returntype`,Promise)],U9.prototype,`dispose`,null);var YRe=class{constructor(e,t,n,r,i){if(this._width=0,this._height=0,this._eventEmitter=new w3.EventEmitter,this._loopId=0,this._isDisposed=!1,e.getVideoTracks().length===0)throw Error(`Video stream must have at least one video track`);this._videoStream=e.clone(),this._refreshInterval=r,this._logger=i.createChild(`VideoStreamCanvasEncoder`),this._video=document.createElement(`video`),this._canvas=document.createElement(`canvas`),this._video.srcObject=this._videoStream,this._video.addEventListener(`resize`,(()=>{let e=this._video.videoWidth||t,r=this._video.videoHeight||n;this._width===e&&this._height===r||(this._width=e,this._height=r,this._canvas.width=e,this._canvas.height=r,this._logger.info(`Video stream resized to ${e}x${r}`))})),this._video.addEventListener(`play`,(()=>{this._loopId||=window.setInterval((()=>{if(!this._isDisposed&&!this._video.paused&&!this._video.ended){this._context.drawImage(this._video,0,0,this._width,this._height);let e=Uint8Array.from(this._canvas.toDataURL(`image/jpeg`),(e=>e.charCodeAt(0)));this._eventEmitter.emit(`data`,e)}}),this._refreshInterval)})),this._video.addEventListener(`pause`,(()=>{this._loopId&&=(clearInterval(this._loopId),0)})),this._video.play().catch((e=>{this._logger.error(`Error playing video stream: ${e}`)})),this._context=this._canvas.getContext(`2d`)}on(e,t){this._eventEmitter.on(e,t)}dispose(){this._isDisposed||(this._isDisposed=!0,this._loopId&&=(clearInterval(this._loopId),0),this._video.pause(),this._video.srcObject=null,this._videoStream.getTracks().forEach((e=>{e.stop()})),this._eventEmitter.removeAllListeners())}},XRe=3,ZRe=class{constructor(e,t,n){this._eventEmitter=new w3.EventEmitter,this._loopId=0,this._isDisposed=!1,this._dataQueue=[],this._timeoutCounter=0,this._timeoutCount=0,this._canvas=document.createElement(`canvas`),this._canvas.width=0,this._canvas.height=0,this._context=this._canvas.getContext(`2d`),this._logger=t.createChild(`VideoStreamCanvasDecoder`),this._mediaStream=this._canvas.captureStream(Math.max(1,Math.ceil(1e3/e))),this._timeoutCount=n;let r=e=>new Promise(((t,n)=>{try{let r=new TextDecoder().decode(e),i=new Image;i.onload=()=>{i.width===this._canvas.width&&i.height===this._canvas.height||(this._canvas.width=i.width,this._canvas.height=i.height),this._context.drawImage(i,0,0,this._canvas.width,this._canvas.height),t(new VideoFrame(this._canvas,{timestamp:0}))},i.onerror=e=>{n(e)},i.src=r}catch(e){n(e)}})),i=async()=>{let t=performance.now();if(this._dataQueue.length>0){this._timeoutCounter=0;let e=this._dataQueue.shift();if(e)try{let t=await r(e);this._eventEmitter.emit(`frame`,t),t.close()}catch{this._logger.error(`Error decoding frame`)}}else if(this._timeoutCounter++,this._timeoutCounter>this._timeoutCount)return this._logger.warn(`No data to decode, stopping video stream`),this._eventEmitter.emit(`dispose`),void this.dispose();let n=performance.now(),a=Math.max(e-(n-t),0);this._loopId=window.setTimeout(i,a)};i()}on(e,t){this._eventEmitter.on(e,t)}decode(e){this._isDisposed||(this._dataQueue.length>XRe&&(this._logger.warn(`Data queue is full, dropping oldest frame`),this._dataQueue.shift()),this._dataQueue.push(e))}getMediaStream(){if(this._isDisposed)throw Error(`VideoStreamCanvasDecoder has been disposed`);return this._mediaStream}dispose(){this._isDisposed||(this._isDisposed=!0,this._loopId&&=(clearTimeout(this._loopId),0),this._eventEmitter.removeAllListeners())}},W9;function G9(e,t){let n=t?t.length:0,r=performance.now(),i=new ArrayBuffer(9+n),a=new DataView(i);if(a.setUint8(0,e),a.setFloat64(1,r),t){let e=new Uint8Array(i,9);for(let n=0;n<t.length;n++)e[n]=t[n]}return new Uint8Array(i)}function QRe(e){let t=new DataView(e.buffer);return{messageType:t.getUint8(0),timestamp:t.getFloat64(1),data:new Uint8Array(e.buffer,9,e.length-9)}}(function(e){e[e.VideoFrame=1]=`VideoFrame`,e[e.StopVideo=2]=`StopVideo`})(W9||={});var $Re=class{constructor(e,t,n,r){this.audioContext=null,this.analyserNode=null,this.sourceNode=null,this.dataArray=null,this.processingIntervalId=null,this.isCurrentlySpeaking=!1,this.consecutiveSpeechSamples=0,this.consecutiveSilenceSamples=0,this.lastSpeechActivityTimestamp=-1/0,this.callbackFiredForCurrentSegment=!1,this.processAudio=()=>{if(!this.analyserNode||!this.dataArray)return void(this.processingIntervalId!==null&&(clearInterval(this.processingIntervalId),this.processingIntervalId=null,this.logger.warn(`AudioAnalyzer stopped due to missing nodes.`)));this.analyserNode.getByteTimeDomainData(this.dataArray);let e=0;for(let t=0;t<this.dataArray.length;t++){let n=(this.dataArray[t]-128)/128;e+=n*n}let t=Math.sqrt(e/this.dataArray.length),n=this.options.speechConfirmSamples,r=this.options.silenceConfirmSamples,i=this.options.minCallbackIntervalMs;if(t>this.options.silenceThreshold){if(this.consecutiveSpeechSamples++,this.consecutiveSilenceSamples=0,this.consecutiveSpeechSamples>=n){let e=Date.now(),n=e-this.lastSpeechActivityTimestamp;!this.callbackFiredForCurrentSegment&&n>i&&(this.logger.info(`AudioAnalyzer: First audio render callback fired. Silence duration: ${n}ms`),this.onSpeechStartCallback(),this.callbackFiredForCurrentSegment=!0),this.lastSpeechActivityTimestamp=e,this.isCurrentlySpeaking||(this.isCurrentlySpeaking=!0,this.logger.info(`AudioAnalyzer: Speech confirmed after ${this.consecutiveSpeechSamples} consecutive samples, avgVolume: ${t.toFixed(4)}, threshold: ${this.options.silenceThreshold}.`))}}else this.consecutiveSilenceSamples++,this.consecutiveSpeechSamples=0,this.consecutiveSilenceSamples>=r&&this.isCurrentlySpeaking&&(this.isCurrentlySpeaking=!1,this.callbackFiredForCurrentSegment=!1,this.logger.debug(`AudioAnalyzer: Silence confirmed after ${this.consecutiveSilenceSamples} consecutive samples. Ready for next turn.`))},this.stream=e,this.logger=t,this.onSpeechStartCallback=n;let i=Z().waimeabay.audioAnalyzer;this.options={...i,...r},this.stream.getAudioTracks().length?this.initialize():this.logger.warn(`AudioAnalyzer: No audio tracks found in the provided stream.`)}initialize(){try{this.audioContext=new AudioContext,this.analyserNode=this.audioContext.createAnalyser(),this.analyserNode.fftSize=this.options.fftSize,this.analyserNode.smoothingTimeConstant=this.options.smoothingTimeConstant,this.sourceNode=this.audioContext.createMediaStreamSource(this.stream),this.sourceNode.connect(this.analyserNode),this.dataArray=new Uint8Array(this.analyserNode.fftSize),this.logger.info(`AudioAnalyzer initialized.`)}catch(e){this.logger.error(`AudioAnalyzer initialization failed: ${e}`),this.dispose()}}start(){this.audioContext&&this.analyserNode&&this.dataArray?this.processingIntervalId===null&&(this.logger.info(`AudioAnalyzer started monitoring with interval ${this.options.processingIntervalMs}ms.`),this.processingIntervalId=window.setInterval(this.processAudio,this.options.processingIntervalMs)):this.logger.warn(`AudioAnalyzer cannot start, not properly initialized.`)}stop(){this.processingIntervalId!==null&&(clearInterval(this.processingIntervalId),this.processingIntervalId=null,this.logger.info(`AudioAnalyzer stopped monitoring.`))}dispose(){this.stop();try{this.sourceNode?.disconnect(),this.analyserNode?.disconnect(),this.audioContext?.close().catch((e=>this.logger.error(`Error closing AudioContext: ${e}`)))}catch(e){this.logger.error(`AudioAnalyzer dispose error: ${e}`)}finally{this.audioContext=null,this.analyserNode=null,this.sourceNode=null,this.dataArray=null,this.consecutiveSpeechSamples=0,this.consecutiveSilenceSamples=0,this.callbackFiredForCurrentSegment=!1,this.logger.info(`AudioAnalyzer disposed.`)}}};function K9(e){return isNaN(e)?e:Math.round(10*e)/10}var q9=class e{static get instance(){return e._instance||=new e,e._instance}register(e,t){this._requests.set(e,{...t,requestTime:performance.now()})}unregister(e){this._requests.delete(e)}constructor(){this._requests=new Map,globalThis.PerformanceObserver!==void 0&&(this._observer=new PerformanceObserver((e=>{e.getEntries().forEach((e=>{if(e.entryType===`resource`){let t=e;if((t.requestStart??0)<=0)return;let n=e.name,r=this._requests.get(n);if(r){let e=r.path;this.unregister(n);let i={path:e,duration:K9(t.duration),initiatorType:t.initiatorType,nextHopProtocol:t.nextHopProtocol,fetchStart:K9(t.fetchStart),domainLookupStart:K9(t.domainLookupStart),domainLookupEnd:K9(t.domainLookupEnd),connectStart:K9(t.connectStart),secureConnectionStart:K9(t.secureConnectionStart),connectEnd:K9(t.connectEnd),requestStart:K9(t.requestStart),responseStart:K9(t.responseStart),responseEnd:K9(t.responseEnd),transferSize:t.transferSize,encodedBodySize:t.encodedBodySize,responseStatus:t.responseStatus};r.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:r.correlationId,operationName:`FetchTimingInfo`,durationInMs:i.duration,operationPayload:{...i},resultCategories:[`Success`],resultSignature:200,sessionId:r.sessionId,endpointId:r.endpointId})}}}))})),this._observer.observe({type:`resource`,buffered:!1}))}dispose(){e._instance&&=(this._requests.clear(),this._observer?.disconnect(),null)}};q9._instance=null;var eze,tze=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},J9=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},nze=e=>{try{return new URL(e)}catch{return}},rze=e=>{let t=`Request`;if(e instanceof URL)return{href:e.toString(),pathname:e.pathname??``};if(typeof Request<`u`&&e instanceof Request)return rze(e.url);if(typeof e==`string`){let n=nze(e);return n?{href:n.href,pathname:n.pathname??``}:{href:e||t,pathname:``}}return{href:t,pathname:``}},ize=class{constructor(e){this._params=e,this._state=DG.Connecting,this._initializeRefTime=0,this._isMuted=!1,this._remoteAudioStreams=new Map,this._remoteVideoStreams=new Map,this._joinSessionDefer=e3(),this._feedViewDefer=e3(),this._audioRenderers=new Map,this._audioAnalyzers=new Map,this._endpointId=``,this._wbSessionStats={localCandidateType:``,relayCandidateCount:0},this._localAudioStreams=new Set,this._localVideoStreams=new Set,this._audioEffectsProcessorStats=[],this._audioEffectsStatsListener=null,this._audioEffectsSubscribedStream=null,this._videoChannel=void 0,this._videoStreamEncoder=void 0,this._videoStreamDecoder=new Map,this._telemetryChannel=void 0,this._telemetryChannelInitializationPromise=void 0,this._sessionConnectedTimestamp=void 0,this._sessionConnectedSignalSent=!1,this.startAudio=async(e,t)=>{let n=performance.now(),r=K0();try{if(this._params.logger.debug(`SessionImpl: startAudio called`),this._joinSessionDefer&&(setTimeout((()=>{if(this._joinSessionDefer?.isPending())return this._joinSessionDefer.reject(new Y({defaultError:J.WB_MEDIA_SDK.SESSION.STARTAUDIO_SESSION_TIMEDOUT}))}),Z().waimeabay.audio.startAudioSessionTimeoutMs),await this._joinSessionDefer.promise),this._outboundAudio&&this._outgoingMediaStream&&!this._isMuted)try{let e=this._outgoingMediaStream.getAudioTracks()[0];e&&(this._outboundAudio.setMediaSource(e),this._params.logger.info(`Applied pending outbound audio stream with stream ID: ${this._outgoingMediaStream.id}`))}catch(e){this._params.logger.error(`Failed to apply pending outbound audio stream: ${e instanceof Error?e.message:String(e)}`)}let i=!1,a=async()=>{i=!0,this._params.logger.debug(`Use normal real-time LocalAudioStream in session`);let e=this._params.options?.localAudioStream?this._params.options?.localAudioStream:await Y5(this._params.deviceManagerInternal,this._params.logger);await this.handleLocalAudioStream(e,!0,r,t)};try{this._preAudioFeature=e;let t=+new Date;if(this._preAudioFeature)if(this._preAudioFeature.recordAudioFailed||!this._preAudioFeature.recordAudioFinished){let e=+new Date,t=new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.USE_NORMALMIC_OR_RAWAUDIO_BECAUSE_RECORDAUDIO_FAILED});this._preAudioFeature.recordAudioFinished||(t=new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.USE_NORMALMIC_OR_RAWAUDIO_BECAUSE_RECORDAUDIO_FAILED})),this._preAudioFeature.logger.error(t.message),await this._preAudioFeature?.disposeInternal(),await this._preAudioFeature?.disposeRtcMic(),await a(),this._preAudioFeature.sendTelemetryEvent(+new Date-e,{timestampInfo:{attemptTimestamp:e},...K3(t)},t.resultCategories,500)}else{let{micLocalAudioStream:e,micRawMediaStream:n}=this._preAudioFeature.getMicMediaStream();if(this._preAudioFeature.isFinished){if(this._preAudioFeature.logger.debug(`PreAudio already finished, will use it's real-time mic for session start`),this._sessionConnectedTimestamp===void 0){let e=this._preAudioFeature.getFirstSpeechTimestamp();e!==void 0&&(this.setFirstClientAudioTimestamp(e),this._params.logger.debug(`Applied finished preAudio speech timestamp ${e}`))}await this.handleLocalAudioStream(e)}else{this._params.logger.debug(`Get PreAudio's player audio stream to use for session start`);let t=await this._preAudioFeature.getPlayerLocalAudioStream(this,(async()=>{let r=+new Date;try{if(!this._preAudioFeature)throw new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.SWITCH_TO_RTCMIC_FAIL_PREAUDIO_UNDEFINED});this._preAudioFeature.logger.debug(`PreAudio player mediastream finished flushing`),this._preAudioFeature.logger.debug(`Now switching to real-time microphone in session`),this._preAudioFeature.disposeInternal().catch((()=>{this._preAudioFeature?.logger.error(`Failed to dispose PreAudio feature after preAudio finished and got called back.`)})),this._localAudioStreams.delete(t),await this.handleLocalAudioStream(e,!1),this.updateOutboundAudioStream(n),n.getAudioTracks().forEach((e=>{e.enabled=!0})),this._eventEmitter.emit(`localAudioStreamsUpdated`,{added:[],removed:[t]}),this._preAudioFeature.logger.debug(`Switched to default real-time microphone in session`),this._preAudioFeature.sendTelemetryEvent(+new Date-r,{step:J5.SWITCHED_TO_REALTIME_MIC,timestampInfo:{attemptTimestamp:r}},[`Success`],200)}catch(e){this._preAudioFeature?.logger.error(`Failed to switch to default real-time microphone after preAudio player mediastream finished flushing`,e);let t=new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.SWITCH_TO_RTC_MIC_FAIL,originalError:e});this._preAudioFeature?this._preAudioFeature.sendTelemetryEvent(+new Date-r,{timestampInfo:{attemptTimestamp:r},...K3(t)},[`Failure`],500):this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:``,operationName:`PreAudio`,durationInMs:+new Date-r,operationPayload:{timestampInfo:{attemptTimestamp:r},...K3(t)},resultCategories:[`Failure`],resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId})}}));await this.handleLocalAudioStream(t)}this._preAudioFeature.setEchoRefStream(this),this.subscribeToAudioEffectsStats(e),this._preAudioFeature.logger.debug(`Set PreAudio's ${this._preAudioFeature.isFinished?`real-time mic`:`player audio stream`} for session start`),this._preAudioFeature.sendTelemetryEvent(+new Date-t,{step:this._preAudioFeature.isFinished?J5.START_SESSION_WITH_RTC_MIC:J5.START_SESSION_WITH_PLAYER_AUDIO_STREAM,timestampInfo:{attemptTimestamp:t}},[`Success`],200)}else await a()}catch(e){if(i)throw e;await a()}this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:r,operationName:`StartAudio`,durationInMs:performance.now()-n,operationPayload:{},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId})}catch(e){let t=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.START_AUDIO_FAILED,originalError:e});throw this._params.logger.error(`SessionImpl: startAudio error`,t),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:r,operationName:`StartAudio`,durationInMs:performance.now()-n,operationPayload:{...K3(t).communicationServicesError},resultCategories:t.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId}),t}},this.createIncomingAudioHandler=async e=>{e.inboundAudio.getAllSourceMedia().firesAll((e=>{let{isLocal:t,endpointId:n,sourceId:r}=e.metadata;if(this._params.logger.debug(`Inbound firesAll media received from ${n}, isLocal: ${t}`),!t)try{e.provider.acquire().fires((e=>{try{if(e.track){this._sessionConnectedTimestamp===void 0&&(this._sessionConnectedTimestamp=Date.now(),this._params.logger.info(`SessionConnectedTimestamp set on first remote audio track arrival: ${this._sessionConnectedTimestamp}`));let t=new MediaStream;t.addTrack(e.track);let i=this._params.tsStack.getDeviceManager().createAudioRenderer?.();if(i?.play(t),this._audioRenderers.set(n,i),Z().waimeabay.sendTelemetrySignal){this._sessionConnectedSignalSent||this._sessionConnectedTimestamp===void 0||(this.sendTelemetrySignal(S4.SessionConnected,this._sessionConnectedTimestamp),this._sessionConnectedSignalSent=!0);let e=new $Re(t,this._params.logger,(()=>{this.sendTelemetrySignal(S4.FirstAudioRender)}));e.start(),this._audioAnalyzers.set(n,e)}let a={sourceId:r,endpointId:n,type:`Audio`,mediaStream:t};this._remoteAudioStreams.set(n,a),this.sendStreamsUpdatedTelemetry(a,`added`),this._eventEmitter.emit(`streamsUpdated`,{added:[a],removed:[]})}}catch(e){let t=e instanceof Error?e.message:JSON.stringify(e);this._params.logger.error(`Error handling media track event from ${n}: ${t}`),this.sendStreamsUpdatedFailureTelemetry({endpointId:n,sourceId:r,type:`Audio`,action:`added`,failureType:`mediaTrackEvent`,failureReason:t})}}))}catch(e){let t=e instanceof Error?e.message:JSON.stringify(e);this._params.logger.error(`Error acquiring audio track queue from ${n}: ${t}`),this.sendStreamsUpdatedFailureTelemetry({endpointId:n,sourceId:r,type:`Audio`,action:`added`,failureType:`acquireMediaTrackQueue`,failureReason:t})}try{let t=e.provider.acquire();(async()=>{try{let e=await t;for(;!e.done;)e=await e.next;let r=this._remoteAudioStreams.get(n),i=this._audioRenderers.get(n),a=this._audioAnalyzers.get(n);a&&(a.dispose(),this._audioAnalyzers.delete(n)),t.dispose(),i&&(i.dispose(),this._audioRenderers.delete(n)),r&&(this._remoteAudioStreams.delete(n),this.sendStreamsUpdatedTelemetry(r,`removed`),this._eventEmitter.emit(`streamsUpdated`,{added:[],removed:[r]}))}catch(e){let t=e instanceof Error?e.message:JSON.stringify(e);this._params.logger.error(`Error processing audio track queue from ${n}: ${t}`),this.sendStreamsUpdatedFailureTelemetry({endpointId:n,sourceId:r,type:`Audio`,action:`removed`,failureType:`processMediaTrackQueue`,failureReason:t})}})()}catch(e){let t=e instanceof Error?e.message:JSON.stringify(e);this._params.logger.error(`Error acquiring audio track queue from ${n}: ${t}`),this.sendStreamsUpdatedFailureTelemetry({endpointId:n,sourceId:r,type:`Audio`,action:`removed`,failureType:`acquireMediaTrackQueue`,failureReason:t})}}))},this.handleLocalAudioStream=async(e,t=!0,n,r)=>{if(this._localAudioStreams.add(e),e.addSession(this),r&&e.mediaStreamType===`Audio`){let t=!1;try{await this.startAudioEffects(e,r)}catch{this._params.logger.error(`Failed to start effects for normal audio.`),t=!0}if(!t)try{this.subscribeToAudioEffectsStats(e)}catch{this._params.logger.error(`Failed to subscribe to audio effects stats for normal audio.`)}}if(t){let t;if(e.mediaStreamType===`RawMedia`)t=await e.getMediaStream();else{let e=async(e,t=!1)=>{let r=+new Date;try{let n=await e.getMediaStream(!0);if(!n)throw t?new Y({defaultError:J.WB_MEDIA_SDK.LOCAL_AUDIO_STREAM.LOCAL_AUDIO_GET_MEDIA_STREAM_UNDEFINED_FIRSTATTEMPT_ONCHANGED}):new Y({defaultError:J.WB_MEDIA_SDK.LOCAL_AUDIO_STREAM.LOCAL_AUDIO_GET_MEDIA_STREAM_UNDEFINED_FIRSTATTEMPT});return n}catch(i){let a=W3(i,!0,new Y({defaultError:J.WB_MEDIA_SDK.SESSION.FAILED_TO_GETMEDIASTREAM,originalError:i}));this._params.logger.error(`Error getting media stream, trying again`,a.message),this.sendHandleLocalAudioStreamFailureTelemetry(a,r,{...K3(a).communicationServicesError},n);try{let n=await e.getMediaStream();if(!n)throw t?new Y({defaultError:J.WB_MEDIA_SDK.LOCAL_AUDIO_STREAM.LOCAL_AUDIO_GET_MEDIA_STREAM_UNDEFINED_SECONDATTEMPT_ONCHANGED}):new Y({defaultError:J.WB_MEDIA_SDK.LOCAL_AUDIO_STREAM.LOCAL_AUDIO_GET_MEDIA_STREAM_UNDEFINED_SECONDATTEMPT});return n}catch(e){let t=W3(e,!0,new Y({defaultError:J.WB_MEDIA_SDK.SESSION.FAILED_TO_GETMEDIASTREAM,originalError:e}));throw this._params.logger.error(`Error getting media stream on second attempt`,t.message),t}}},r=async()=>{let t=+new Date;try{if(!this._tsRawStream){let e=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.NO_TS_RAW_STREAM_PRESENT_ONCHANGED});throw this._params.logger.error(e.message),e}{let t=await e(this._tsRawStream,!0);this.updateOutboundAudioStream(t),this._isMuted&&(this._isMuted=!1,this.mute())}}catch(e){let r=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.FAILED_TO_GETMEDIASTREAM_ONCHANGED,originalError:e});this.sendHandleLocalAudioStreamFailureTelemetry(r,t,{...K3(r).communicationServicesError},n)}};this._tsRawStream=this._params.deviceManagerInternal.getRawDeviceMediaStream(0),this._tsRawStream.changed((()=>{this._params.logger.log(`RawDeviceMediaStream changed`),r()})),t=await e(this._tsRawStream)}this.updateOutboundAudioStream(t)}this._eventEmitter.emit(`localAudioStreamsUpdated`,{added:[e],removed:[]})},this.createVideoHandler=async()=>{let e=Z().waimeabay.video,t=new W5(this,{payloadType:e.payloadType,transmissionMode:G5.PartiallyReliable,isLargeData:!0},this._params.logger,this._params.telemetryLogManager);await t.initialize(),t.on(`message`,(e=>{let{data:t,endpointId:n}=e;this._params.logger.log(`video data received: ${t.length} bytes from ${n}`);let r=QRe(t);if(r.messageType!==W9.StopVideo){if(r.messageType===W9.VideoFrame){if(!this._videoStreamDecoder.has(n)){let e=Z().waimeabay.video.timeoutCount,t=new ZRe(1e3,this._params.logger,e),r={sourceId:0,endpointId:n,type:`Video`,mediaStream:t.getMediaStream()};this._remoteVideoStreams.set(n,r),t.on(`dispose`,(()=>{this._videoStreamDecoder.delete(n),this._remoteVideoStreams.delete(n),this.sendStreamsUpdatedTelemetry(r,`removed`),this._eventEmitter.emit(`streamsUpdated`,{added:[],removed:[r]})})),this.sendStreamsUpdatedTelemetry(r,`added`),this._eventEmitter.emit(`streamsUpdated`,{added:[r],removed:[]}),t.on(`frame`,(e=>{this._params.logger.log(`video frame received: ${e.displayWidth}x${e.displayHeight} from ${n}`)})),this._videoStreamDecoder.set(n,t)}this._videoStreamDecoder.get(n).decode(r.data)}}else{let e=this._videoStreamDecoder.get(n);if(e){e.dispose(),this._videoStreamDecoder.delete(n);let t=this._remoteVideoStreams.get(n);t&&(this._remoteVideoStreams.delete(n),this.sendStreamsUpdatedTelemetry(t,`removed`),this._eventEmitter.emit(`streamsUpdated`,{added:[],removed:[t]}))}}})),this._videoChannel=t},this.sendHandleLocalAudioStreamFailureTelemetry=(e,t,n,r)=>{this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:r||``,operationName:`StartAudio`,durationInMs:+new Date-t,operationPayload:{...K3(e).communicationServicesError},resultCategories:e.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId})},e.logger.debug(`SessionImpl: constructor called with sessionId: ${e.sessionId}, localAudioSteam: ${!!e.options?.localAudioStream}, localVideoStream: ${!!e.options?.localVideoStream}`),this._eventEmitter=new S6(this._params.logger),this._extensibleApi=new N3(e.logger,{session:this,sessionAgent:e.sessionAgent},{tsSession:e.tsWbSession,sessionAgent:e.sessionAgent,session:this,telemetryLogManager:e.telemetryLogManager})}get audioEffectsProcessorStats(){return this._audioEffectsProcessorStats}clearAudioEffectsProcessorStats(){this._audioEffectsProcessorStats=[]}feature(e){return this._extensibleApi.getApiObjectInstance(e.sessionApiCtor)}get localAudioStreams(){return Array.from(this._localAudioStreams)}get localVideoStreams(){return Array.from(this._localVideoStreams)}get state(){return this._state}get isMuted(){return this._isMuted}get remoteAudioStreams(){return Array.from(this._remoteAudioStreams.values())}get remoteVideoStreams(){return Array.from(this._remoteVideoStreams.values())}get endpointId(){return this._endpointId}get sessionId(){return this._params.sessionId}get feedSession(){return this._session}mute(){let e=performance.now(),t=K0();try{this._params.logger.debug(`SessionImpl: mute called`,t),this.validateSessionState(o4.Mute),this._preAudioFeature&&!this._preAudioFeature.isFinished?(this._preAudioFeature.muteRtcMic(),this._isMuted=!0):this._isMuted||this.toggleAudioMuteState(),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`Mute`,durationInMs:performance.now()-e,operationPayload:{wasMuted:this._isMuted},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId})}catch(n){let r=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.MUTE_FAILED,originalError:n});throw this._params.logger.error(`SessionImpl: mute error`,n),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`Mute`,durationInMs:performance.now()-e,operationPayload:{...K3(r).communicationServicesError},resultCategories:r.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId}),r}}unmute(){let e=performance.now(),t=K0();try{this._params.logger.debug(`SessionImpl: unmute called`,t),this.validateSessionState(o4.Unmute),this._preAudioFeature&&!this._preAudioFeature.isFinished?(this._preAudioFeature.unmuteRtcMic(),this._isMuted=!1):this._isMuted&&this.toggleAudioMuteState(),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`Unmute`,durationInMs:performance.now()-e,operationPayload:{wasMuted:!this._isMuted},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId})}catch(n){let r=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.UNMUTE_FAILED,originalError:n});throw this._params.logger.error(`SessionImpl: unmute error`,n),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`Unmute`,durationInMs:performance.now()-e,operationPayload:{...K3(r).communicationServicesError},resultCategories:r.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId}),r}}async startRawAudio(e){try{if(this.validateSessionState(o4.StartAudio),this._params.logger.debug(`SessionImpl: startAudio called`),e?.mediaStreamType!==`RawMedia`)throw new Y({defaultError:J.WB_MEDIA_SDK.SESSION.START_RAW_AUDIO_LAS_NOT_RAW_MEDIA});this._outboundAudio&&this._outboundAudio.clearMediaSource();let t=Array.from(this._localAudioStreams)[0];t&&(this._localAudioStreams.delete(t),this._eventEmitter.emit(`localAudioStreamsUpdated`,{added:[],removed:[t]}),this._cachedLocalAudioStreamBeforeRawAudioStarted=t),await this.handleLocalAudioStream(e),this.sendTelemetrySignal(S4.StartRawAudio)}catch(e){let t=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.START_RAW_AUDIO_FAILED,originalError:e});throw this._params.logger.error(`SessionImpl: startAudio error`,e),t}}async stopRawAudio(){try{this.validateSessionState(o4.StopAudio),this._params.logger.debug(`SessionImpl: stopAudio called`);let e=Array.from(this._localAudioStreams)[0];if(e?.mediaStreamType!==`RawMedia`)throw new Y({defaultError:J.WB_MEDIA_SDK.SESSION.STOP_RAW_AUDIO_LAS_NOT_RAW_MEDIA});this._outboundAudio&&this._outboundAudio.clearMediaSource(),this._localAudioStreams.delete(e),this._eventEmitter.emit(`localAudioStreamsUpdated`,{added:[],removed:[e]});let t=this._cachedLocalAudioStreamBeforeRawAudioStarted||await Y5(this._params.deviceManagerInternal,this._params.logger);await this.handleLocalAudioStream(t),this._cachedLocalAudioStreamBeforeRawAudioStarted=void 0,this.sendTelemetrySignal(S4.StopRawAudio)}catch(e){let t=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.STOP_RAW_AUDIO_FAILED,originalError:e});throw this._params.logger.error(`SessionImpl: stopAudio error`,e),t}}muteIncomingAudio(){let e=performance.now(),t=K0();try{this._params.logger.debug(`SessionImpl: muteIncomingAudio called`,t),this.validateSessionState(o4.MuteIncomingAudio),this._audioRenderers.forEach((e=>e.setMuted(!0))),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`MuteIncomingAudio`,durationInMs:performance.now()-e,operationPayload:{audioRenderersCount:this._audioRenderers.size},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId})}catch(n){let r=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.MUTE_INCOMING_AUDIO_FAILED,originalError:n});throw this._params.logger.error(`SessionImpl: muteIncomingAudio error`,n),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`MuteIncomingAudio`,durationInMs:performance.now()-e,operationPayload:{...K3(r).communicationServicesError},resultCategories:r.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId}),r}}unmuteIncomingAudio(){let e=performance.now(),t=K0();try{this._params.logger.debug(`SessionImpl: unmuteIncomingAudio called`,t),this.validateSessionState(o4.UnmuteIncomingAudio),this._audioRenderers.forEach((e=>e.setMuted(!1))),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`UnmuteIncomingAudio`,durationInMs:performance.now()-e,operationPayload:{audioRenderersCount:this._audioRenderers.size},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId})}catch(n){let r=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.UNMUTE_INCOMING_AUDIO_FAILED,originalError:n});throw this._params.logger.error(`SessionImpl: unmuteIncomingAudio error`,n),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`UnmuteIncomingAudio`,durationInMs:performance.now()-e,operationPayload:{...K3(r).communicationServicesError},resultCategories:r.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId}),r}}async startVideo(e){try{if(this.validateSessionState(o4.StartVideo),this._videoStreamEncoder){let e=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.VIDEO_ALREADY_STARTED});throw this._params.logger.error(e.message),e}this._localVideoStreams.add(e);let t=await e.getMediaStream(),n=Z().waimeabay.video.defaultWidth,r=Z().waimeabay.video.defaultHeight,i=Z().waimeabay.video.refreshInterval;this._videoStreamEncoder=new YRe(t,n,r,i,this._params.logger),this._videoStreamEncoder.on(`data`,(e=>{this._videoChannel?.send(G9(W9.VideoFrame,e))})),e.mediaStreamType===`Video`&&e.disposeRawStream()}catch(e){let t=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.START_VIDEO_FAILED,originalError:e});throw this._params.logger.error(`SessionImpl: startVideo error`,e),t}}stopVideo(){try{this._videoStreamEncoder&&(this._videoStreamEncoder.dispose(),this._videoStreamEncoder=void 0,this._videoChannel?.send(G9(W9.StopVideo))),Array.from(this._localVideoStreams.values()).forEach((e=>{this._localVideoStreams.delete(e)}))}catch(e){let t=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.STOP_VIDEO_FAILED,originalError:e});throw this._params.logger.error(`SessionImpl: stopVideo error`,e),t}}cleanup(){try{this._joinSessionDefer&&this._joinSessionDefer.dispose(),this._joinSessionDefer=void 0,this._audioRenderers.forEach((e=>e.dispose())),this._audioRenderers.clear(),this._audioAnalyzers.forEach((e=>e.dispose())),this._audioAnalyzers.clear(),this._videoStreamEncoder&&(this._videoStreamEncoder.dispose(),this._videoStreamEncoder=void 0,this._videoChannel?.send(G9(W9.StopVideo))),this.localVideoStreams.forEach((e=>{e.autoDisposeOnCallEnd&&e.dispose(),this._localVideoStreams.delete(e)})),this._params.sessionAgent.removeSession({sessionId:this._params.sessionId}),this._outboundAudio?.dispose(),this._feedView?.dispose();let e=this._state;if(this._state=DG.Disconnected,e!==this._state){let t=this._initializeRefTime>0?performance.now()-this._initializeRefTime:0,n=K0();this.logTelemetryWithEndpointId(n,t,e),this._params.logger.info(`Session state changed from ${e} to ${this._state}`),this._eventEmitter.emit(`stateChanged`)}this._eventEmitter.removeAllListeners(),this._extensibleApi.dispose()}catch(e){this._params.logger.error(`SessionImpl: Failed to cleanup with error: ${e instanceof Error?e.message:String(e)}`)}}disconnectInternal(e){let t=K0(),n=performance.now();this._params.logger.debug(`SessionImpl: hangUp called`,t);try{if(this._audioEffectsStatsListener&&this._audioEffectsSubscribedStream){try{this._audioEffectsSubscribedStream.feature(Z5.AudioEffects)?.off(`effectsProcessorStatsUpdated`,this._audioEffectsStatsListener)}catch(e){this._params.logger.warn(`Error cleaning up audio effects stats subscription on disconnect: ${e}`)}this._audioEffectsStatsListener=null}this._audioEffectsProcessorStats=[],this._audioEffectsSubscribedStream=null,this.localAudioStreams.forEach((e=>{e.removeSession(this),e.autoDisposeOnCallEnd&&e.dispose()})),this._localAudioStreams.clear(),this._tsRawStream&&=(this._tsRawStream.dispose(),void 0),this._preAudioFeature?.disposeRtcMic().catch((e=>{this._params.logger.error(`Error disposing rtc mic in preAudioFeature`,e)})),this._telemetryChannel&&=(this._telemetryChannel.dispose(),void 0),this._sessionConnectedTimestamp=void 0,this._sessionConnectedSignalSent=!1,this._session?.dispose(),this.cleanup(),this._params.logger.debug(`SessionImpl: hangUp success`,t),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`DisconnectSession`,durationInMs:performance.now()-n,operationPayload:{source:e},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId})}catch(r){let i=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.DISCONNECT_FAILED,originalError:r});throw this._params.logger.error(`SessionImpl: hangUp error`,r),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`DisconnectSession`,durationInMs:performance.now()-n,operationPayload:{...K3(i).communicationServicesError,source:e},resultCategories:i.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId}),i}}disconnect(){this.disconnectInternal(`client`)}disconnectFromUnload(e){this.disconnectInternal(e)}on(e,t){this._params.logger.debug(`Raising event: ${e}`),e!==`stateChanged`&&e!==`streamsUpdated`&&e!==`configureRequest`&&e!==`localAudioStreamsUpdated`||this._eventEmitter.on(e,t)}off(e,t){this._params.logger.debug(`Unsubscribing from event: ${e}`),e!==`stateChanged`&&e!==`streamsUpdated`&&e!==`configureRequest`&&e!==`localAudioStreamsUpdated`||this._eventEmitter.off(e,t)}async createDataChannel(e,t){let n=e.payloadType,r;switch(this._feedView||await this._feedViewDefer.promise,this._feedView.setInboundDataConfig(n,{maxStreams:Z().waimeabay.dataChannel.maxStreams,messageDeserializer:e=>e}).getInboundData(n).getAllSourceMedia().firesAll((({metadata:e,onMessageEvent:n,onDispose:r})=>{let i=e.endpointId;n.fires((e=>{t(i,e)})),r.then((()=>{this._params.logger.log(`Data stream got disposed`,i)}))})),e.transmissionMode){case G5.Realtime:r=H5.MediaTransmissionMode.REALTIME;break;case G5.PartiallyReliable:r=H5.MediaTransmissionMode.PARTIALLY_RELIABLE;break;default:r=void 0}return this._session.createOutboundData({payloadType:n,messageSerializer:e=>e,initialState:new Uint8Array,...r===void 0?{}:{transmissionMode:r}}).setFeedIds(Z().waimeabay.feedId)}async initialize(e){try{await this._internalInitialize(e)}catch(e){throw this._feedView?this._feedViewDefer.resolve():this._feedViewDefer.reject(e),e}}async _internalInitialize(e){let t=performance.now();this._initializeRefTime=t;let n=K0();this._params.logger.debug(`SessionImpl: initialize called`,n),this._params.tsWbSession.on(`callQualityChanged`,(e=>{this._params.logger.debug(`SessionQualityChanged: ${JSON.stringify(e)}`)}));let r={sendEvent:e=>{this._params.telemetryLogManager.sendWbEvent({...this._endpointId?{endpointId:this._endpointId}:{},sessionId:this._params.sessionId,eventData:e})}},i=performance.now();try{this._session=await this._params.tsWbSession.createFeedSession({serviceOrigin:this.getServiceOrigin(),telemetryLogger:r,authorizationHeaderProvider:async()=>`Bearer `+await this._params.sessionAgent.tokenProvider(),httpFetch:async(e,t)=>{let r=performance.now(),{href:i,pathname:a}=rze(e),o=(e,t)=>{let o=performance.now()-r,s=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.JOIN_FAILED,originalError:e.error}),c=e.headers?.get(`X-Azure-Ref`),l=e.headers?.get(`x-ms-request-id`),u=e.headers?.get(`x-cache`),d=e.headers?.get(`ms-region-name`),f=e.headers?.get(`ms-stamp-name`),p=e.headers?.get(`ms-ring-name`);this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:n,operationName:`HTTPRequest`,durationInMs:o,operationPayload:{...e.status===void 0?{}:{status:e.status},...e.statusText===void 0?{}:{statusText:e.statusText},...c?{"X-Azure-Ref":c}:{},...l?{xMsRequestId:l}:{},...u?{xCache:u}:{},...d?{msRegionName:d}:{},...f?{msStampName:f}:{},...p?{msRingName:p}:{},pathName:a,...K3(s).communicationServicesError},resultCategories:s.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId});let m=e.status===void 0?e.error:`status ${e.status}`;if(this._params.logger.error(`HTTP fetch failed for ${i}:`,m),t)throw s},s=(e,t,o)=>{let s=performance.now()-r,c=o.get(`X-Azure-Ref`),l=o.get(`x-ms-request-id`),u=o.get(`x-cache`),d=o.get(`ms-region-name`),f=o.get(`ms-stamp-name`),p=o.get(`ms-ring-name`);this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:n,operationName:`HTTPRequest`,durationInMs:s,operationPayload:{status:e,statusText:t,...c?{"X-Azure-Ref":c}:{},...l?{xMsRequestId:l}:{},...u?{xCache:u}:{},...d?{msRegionName:d}:{},...f?{msStampName:f}:{},...p?{msRingName:p}:{},pathName:a},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId}),this._params.logger.debug(`HTTP fetch succeeded for ${i} - Status: ${e}`)},c={...t?.headers instanceof Headers?(()=>{let e={};return t.headers.forEach(((t,n)=>{e[n]=t})),e})():t?.headers,"X-Microsoft-Skype-Chain-ID":this._params.sessionId};try{q9.instance.register(i,{path:a,correlationId:n,sessionId:this._params.sessionId,endpointId:this._endpointId,telemetryLogManager:this._params.telemetryLogManager});let r=await globalThis.fetch(e,{...t,headers:c});return this._params.logger.debug(`HTTP fetch to ${e} - Status: ${r.status}`),r.ok?s(r.status,r.statusText,r.headers):o({error:Error(`HTTP request failed with status ${r.status}`),status:r.status,statusText:r.statusText,headers:r.headers},!1),r}catch(e){return o({error:e},!0)}},applicationInfo:this._params.clientTypeInfo}),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:n,operationName:`CreateFeedSession`,durationInMs:performance.now()-i,operationPayload:{},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId})}catch(e){let t=performance.now()-i,r=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.JOIN_FAILED,originalError:e});throw this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:n,operationName:`CreateFeedSession`,durationInMs:t,operationPayload:{...K3(r).communicationServicesError},resultCategories:r.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId}),this._params.logger.error(`CreateFeedSession failed`,r),r}let a=e=>{if(this._connectionState===e)return;let r=performance.now()-t,i=e=>{if(e===void 0)return`Initial`;switch(e){case H5.SessionConnectionState.CONNECTING:return`Connecting`;case H5.SessionConnectionState.CONNECTED:return`Connected`;case H5.SessionConnectionState.FAILOVER:return`Failover`;case H5.SessionConnectionState.DISCONNECTED:return`Disconnected`;default:return`UNKNOWN`}},a=i(this._connectionState),o=i(e);this._connectionState=e,this._params.logger.info(`Session transport state changed: ${a} -> ${o}`);let s={eventName:Q.acs_wb_session_events,operationId:n,operationName:`TransportStateChanged`,durationInMs:r,operationPayload:{oldState:a,newState:o,...this._wbSessionStats},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId};this._params.telemetryLogManager.sendWbSessionEvent(s)},o,s;this._session.stats.fires((e=>{let t=e.localCandidateType??``;this._wbSessionStats.localCandidateType!==t&&(this._wbSessionStats.localCandidateType=t,this._params.logger.info(`Local candidate type of active connection is ${this._wbSessionStats.localCandidateType}`)),this._wbSessionStats.relayCandidateCount=e.relayCandidateCount??0})),this._session.connectionState.fires((e=>{a(e)})),a(this._session.connectionState.value),this._session.metadata.then((e=>{let r=performance.now()-t;this._joinSessionDefer&&this._joinSessionDefer.resolve(this._session),this._endpointId=e.endpointId,this._params.logger.debug(`Session metadata received in ${r} ms for endpointId ${this._endpointId} `),this._params.tsWbSession.setAdditionalTelemetryFields({WB_SessionId:this._params.sessionId,WB_EndpointId:this._endpointId,WB_RoomId:this._params.sessionId}),this._params.logger.debug(`MediaStreamSession: setAdditionalTelemetryFields on _tsWbSession with sessionId: ${this._params.sessionId}, endpointId: ${this._endpointId}`),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:n,operationName:`AllocateSession`,durationInMs:r,operationPayload:{},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId}),this.emitConfigureRequest(e)})).catch((e=>{let r=performance.now()-t,i=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.JOIN_FAILED,originalError:e});this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:n,operationName:`AllocateSession`,durationInMs:r,operationPayload:{...K3(i).communicationServicesError},resultCategories:i.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId}),this._params.logger.error(`Session metadata error`,i)})),this._feedView=this._session.createFeedView().setFeedId(Z().waimeabay.feedId).setInboundAudioConfig({maxStreams:Z().waimeabay.audio.maxStreams,reflectionMode:H5.MediaReflectionMode.NONE}),this._feedViewDefer.resolve(),this._session.onConnect.then((async()=>{let r=performance.now()-t;if(this._params.logger.debug(`WB Connected in ${r} ms for endpointId ${this._endpointId} `),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:n,operationName:`JoinSession`,durationInMs:r,operationPayload:{feedId:Z().waimeabay.feedId,isPreheated:!!e,isDisconnected:this._state===DG.Disconnected},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId}),this._state!==DG.Disconnected){let t=this._state;this._state=e&&t!==DG.Connected?DG.Preheated:DG.Connected,this.logTelemetryWithEndpointId(n,r,t),t!==this._state&&(this._params.logger.info(`Session state changed from ${t} to ${this._state}`),this._eventEmitter.emit(`stateChanged`))}})).catch((e=>{let r=performance.now()-t,i=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.JOIN_FAILED,originalError:e});this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:n,operationName:`AllocateSession`,durationInMs:r,operationPayload:{...K3(i).communicationServicesError},resultCategories:i.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId}),this._params.logger.error(`Session connection error`,i),this._joinSessionDefer&&this._joinSessionDefer.isPending()&&this._joinSessionDefer.reject(e)})),this._session.onDisconnect.then((e=>{o=e})).catch((e=>{let t=e instanceof Error?e.message:JSON.stringify(e);this._params.logger.error(`Session disconnected with an error: ${t}`),s={...o,errorMessage:t}})).finally((()=>{let e=performance.now()-t;this._params.logger.debug(`Session disconnected in ${e} ms, cause: ${JSON.stringify(o)}`),setTimeout((async()=>{let e=await this._params.tsWbSession.getMediaTelemetry();this._params.logger.info(`WBStats mediaTelemetry ${JSON.stringify(e)}`),this._params.tsWbSession.reportMediaTelemetry(),this._params.logger.info(`reportMediaTelemetry called on disconnect.`)}),3e3);let r=this._state;r!==DG.Disconnected&&(this._state=DG.Disconnected,this.logTelemetryWithEndpointId(n,e,r,s||o),this._params.logger.info(`Session state changed from ${r} to ${this._state}`),this._eventEmitter.emit(`stateChanged`),this.cleanup())}));let c=Q5(D3.SessionFeature);for(let e of c)e.activationOptions.activationEvent===`OnExtendedObjectConstructor`&&this.feature(e);if(e||await this.startMedia(!1),Z().waimeabay.sendTelemetrySignal)try{await this.initializeTelemetryChannel(),this._params.logger.info(`Initialize: TelemetryChannel initialized successfully by main initialize flow!`)}catch(e){this._params.logger.error(`Initialize: Main initialize flow failed to initialize TelemetryChannel: ${e instanceof Error?e.message:String(e)}`)}}async startMedia(e,t){let n=performance.now(),r=K0();if(this._state===DG.Disconnected)return this._params.logger.error(`SessionImpl: startMedia called in invalid state: ${this._state}`),void this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:r,operationName:`StartMedia`,durationInMs:performance.now()-n,operationPayload:{isPreheated:!!e},resultCategories:[`UnexpectedClientError`],resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId});t&&this._params.setOptions(t);try{this.createIncomingAudioHandler(this._feedView),this._outboundAudio||=this._session.createOutboundAudio().setFeedIds(Z().waimeabay.feedId);let t=this._state;this._state=DG.Connected;let i=performance.now()-n;this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:r,operationName:`StartMedia`,durationInMs:i,operationPayload:{isPreheated:!!e,state:this._state},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId}),e&&this.logTelemetryWithEndpointId(r,i,t),t!==this._state&&(this._params.logger.info(`Session state changed from ${t} to ${this._state}`),this._eventEmitter.emit(`stateChanged`)),Z().waimeabay.enableVideoHandler&&await this.createVideoHandler()}catch(t){let i=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.START_MEDIA_FAILED,originalError:t});throw this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:r,operationName:`StartMedia`,durationInMs:performance.now()-n,operationPayload:{isPreheated:!!e,state:this._state,...K3(i).communicationServicesError},resultCategories:i.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId}),this._params.logger.error(`Failed to create audio/video handler: ${t instanceof Error?t.message:String(t)}`),i}}updateOutboundAudioStream(e){let t=this.localAudioStreams[0];if(t){let n=e.clone();t.setWBMediaStream(n)}if(this._outgoingMediaStream=e,this._outboundAudio)if(this._outboundAudio.clearMediaSource(),this._isMuted)this._params.logger.debug(`updateOutboundAudioStream: stream ${e.id} set while muted; track not attached until unmute.`);else{let t=e.getAudioTracks()[0];t&&this._outboundAudio.setMediaSource(t),this._params.logger.info(`Updated outbound audio stream with stream ID: ${e.id}`)}else this._params.logger.debug(`updateOutboundAudioStream: _outboundAudio not created yet, stream ${e.id} will be set when startMedia is called`)}logTelemetryWithEndpointId(e,t,n,r){this._endpointId===``&&this._params.logger.error(`Session metadata error the endpointId is empty, cannot log telemetry with endpointId yet.`);let i=n===DG.Connecting&&this._state===DG.Disconnected,a=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.JOIN_FAILED}),o={eventName:Q.acs_wb_session_events,operationId:e,operationName:`StateChanged`,durationInMs:t,operationPayload:{oldState:n,newState:this._state,disconnectedCause:r??``},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId};i&&(o.resultSignature=500,o.resultCategories=a.resultCategories,o.operationPayload={...o.operationPayload,...K3(a).communicationServicesError},this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:e,operationName:`JoinSession`,durationInMs:t,operationPayload:{feedId:Z().waimeabay.feedId,...K3(a).communicationServicesError,disconnectedCause:r?{...r}:``},resultCategories:a.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId})),this._params.telemetryLogManager.sendWbSessionEvent(o)}emitConfigureRequest(e){let t={feedId:Z().waimeabay.feedId,sessionId:this._params.sessionId,endpointId:this._endpointId,endpointSecret:e.secretToken,activationUrl:this.getServiceOrigin()+Z().waimeabay.activationPath},n=K0(),r=performance.now();this._eventEmitter.emit(`configureRequest`,t,((e,t)=>{if(e)this._params.logger.debug(`SessionImpl: configureRequest success`),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:n,operationName:`ConfigureRequest`,durationInMs:performance.now()-r,operationPayload:{},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId});else{let e=t||`Unknown error`;this._params.logger.error(`SessionImpl: configureRequest failed: ${e}`);let i=new Y({defaultError:J.CALL.OPERATION_FAILED,defaultErrorMessageArgs:[`ConfigureRequest`]});this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:n,operationName:`ConfigureRequest`,durationInMs:performance.now()-r,operationPayload:{configurationFailureReason:e,...K3(i).communicationServicesError},resultCategories:[`UnexpectedClientError`],resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId})}}))}getServiceOrigin(){return this._params.serviceOrigin&&this._params.serviceOrigin.trim()!==``?this._params.serviceOrigin:Z().waimeabay.origin}async startAudioEffects(e,t){let n=e.feature(Z5.AudioEffects),r=t8().engine;await n.startEffects({noiseSuppression:r===`Chromium`?t.noiseSuppression:r===`Safari`?void 0:`BrowserNoiseSuppression`,echoCancellation:r===`Chromium`?t.echoCancellation:`BrowserEchoCancellation`})}async subscribeToAudioEffectsStats(e){try{if(this._params.logger.debug(`MediaStreamSession: subscribeToAudioEffectsStats - effectsStarted event received, waiting briefly for internal stats subscription to be set up`),await new Promise((e=>setTimeout(e,100))),this._params.logger.debug(`MediaStreamSession: subscribeToAudioEffectsStats - Setting up audio effects stats subscription after delay`),!e||this._audioEffectsSubscribedStream===e&&this._audioEffectsStatsListener)return;if(this._audioEffectsStatsListener&&this._audioEffectsSubscribedStream&&this._audioEffectsSubscribedStream!==e)try{this._audioEffectsSubscribedStream.feature(Z5.AudioEffects)?.off(`effectsProcessorStatsUpdated`,this._audioEffectsStatsListener)}catch(e){this._params.logger.warn(`MediaStreamSession: subscribeToAudioEffectsStats - Error cleaning up existing audio effects stats subscription: ${e}`)}let t=e.feature(Z5.AudioEffects);if(!this._audioEffectsStatsListener||this._audioEffectsSubscribedStream!==e){this._audioEffectsStatsListener=e=>{e&&this._audioEffectsProcessorStats.push(e)},t?.on(`effectsProcessorStatsUpdated`,this._audioEffectsStatsListener);let n=t?.audioEffectsProcessorStats;n&&this._audioEffectsProcessorStats.push(n),this._audioEffectsSubscribedStream=e}}catch(e){this._params.logger.warn(`MediaStreamSession: subscribeToAudioEffectsStats - Error handling audio effects stats subscription: ${e}`)}}initializeTelemetryChannel(){if(this._telemetryChannelInitializationPromise)return this._telemetryChannelInitializationPromise;let e=Z().waimeabay.telemetry;return this._telemetryChannelInitializationPromise=(async()=>{try{if(this._telemetryChannel)return;this._telemetryChannel=new W5(this,{payloadType:e.payloadType,...e.mode===1?{isLargeData:!1,transmissionMode:G5.Realtime}:e.mode===2?{isLargeData:!1,transmissionMode:G5.PartiallyReliable}:{isLargeData:!0,transmissionMode:G5.Realtime}},this._params.logger,this._params.telemetryLogManager),await this._telemetryChannel.initialize(),this._params.logger.info(`initializeTelemetryChannel: DataChannelAdapter initialized.`),this._telemetryChannel.on(`message`,(e=>{try{let t=Lwe(e.data);this._params.logger.info(`MediaStreamSession: Telemetry data received from endpoint ${e.endpointId}: `,JSON.stringify(t))}catch(t){this._params.logger.error(`MediaStreamSession: Error decoding telemetry message from ${e.endpointId}: ${t instanceof Error?t.message:String(t)}`)}}))}catch(e){this._params.logger.error(`initializeTelemetryChannel: Failed to initialize: ${e instanceof Error?e.message:String(e)}`),this._telemetryChannel=void 0,this._telemetryChannelInitializationPromise=void 0}})(),this._telemetryChannelInitializationPromise}async sendTelemetrySignal(e,t){let n=t===void 0?Date.now():t;if(Z().waimeabay.sendTelemetrySignal)try{if(await this.initializeTelemetryChannel(),!this._telemetryChannel)return void this._params.logger.warn(`sendTelemetrySignal: Telemetry channel is not available after attempting initialization.`);if(this._telemetryChannel.state<D8.Initialized)return void this._params.logger.warn(`sendTelemetrySignal: Telemetry channel adapter state is ${this._telemetryChannel.state}, not ready to send signal ${e}.`);let t=Fwe(e,n),r=Iwe(t);this._telemetryChannel.send(r),this._params.logger.info(`sendTelemetrySignal: Successfully sent signal: ${e}, message: ${JSON.stringify(t)}`)}catch(t){this._params.logger.error(`sendTelemetrySignal: Failed to send telemetry signal ${e}: ${t instanceof Error?t.message:String(t)}`,t)}}toggleAudioMuteState(){if(this._isMuted=!this._isMuted,this._isMuted)this._outboundAudio&&this._outboundAudio.clearMediaSource();else try{this._outboundAudio&&this._outboundAudio.setMediaSource(this._outgoingMediaStream.getAudioTracks()[0])}catch(e){this._params.logger.error(`Failed to unmute audio: ${e instanceof Error?e.message:String(e)}`)}}validateSessionState(e){if(this._state!==DG.Connected&&(this._state!==DG.Connecting||e!=o4.Mute&&e!=o4.Unmute)){if(this._state===DG.Disconnected)throw new Y({defaultError:J.WB_MEDIA_SDK.SESSION.DISCONNECTED_JOIN_AGAIN,defaultErrorMessageArgs:[e]});if(this._state===DG.Connecting)throw new Y({defaultError:J.WB_MEDIA_SDK.SESSION.CONNECTING_WAIT,defaultErrorMessageArgs:[e]})}}async sendStreamsUpdatedTelemetry(e,t){this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:``,operationName:`StreamsUpdated`,durationInMs:0,operationPayload:{sourceId:e.sourceId,remoteEndpointId:e.endpointId,type:e.type,action:t},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId})}async sendStreamsUpdatedFailureTelemetry(e){this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:``,operationName:`StreamsUpdated`,durationInMs:0,operationPayload:{sourceId:e.sourceId,remoteEndpointId:e.endpointId,type:e.type,action:e.action,failureType:e.failureType,failureReason:e.failureReason},resultCategories:[`UnexpectedClientError`],resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId})}setFirstClientAudioTimestamp(e){this._sessionConnectedTimestamp===void 0&&(this._sessionConnectedTimestamp=e,this._params.logger.info(`SessionConnectedTimestamp set via setFirstClientAudioTimestamp: ${e}`))}};tze([WG(Dwe.Feature),J9(`design:type`,Function),J9(`design:paramtypes`,[Object]),J9(`design:returntype`,typeof(eze=typeof TFeature<`u`&&TFeature)==`function`?eze:Object)],ize.prototype,`feature`,null);var aze=class e{static create(){return new e}setTsStack(e){return this._tsStack=e,this}setDeviceManagerInternal(e){return this._deviceManagerInternal=e,this}setClientTypeInfo(e){return this._clientTypeInfo=e,this}setTsWbSession(e){return this._tsWbSession=e,this}setLogger(e){return this._logger=e,this}setTelemetryLogManager(e){return this._telemetryLogManager=e,this}setClientId(e){return this._clientId=e,this}setServiceOrigin(e){return this._serviceOrigin=e,this}setSessionId(e){return this._sessionId=e,this}setOptions(e){return this._options=e,this}setSessionAgent(e){return this._sessionAgent=e,this}get sessionAgent(){return this._sessionAgent}get tsStack(){return this._tsStack}get deviceManagerInternal(){return this._deviceManagerInternal}get clientTypeInfo(){return this._clientTypeInfo}get tsWbSession(){return this._tsWbSession}get logger(){return this._logger}get telemetryLogManager(){return this._telemetryLogManager}get clientId(){return this._clientId}get serviceOrigin(){return this._serviceOrigin}get sessionId(){return this._sessionId}get options(){return this._options}},oze=class{constructor(e,t,n,r,i,a,o,s){this._logger=e,this._telemetryLogManager=t,this._clientId=n,this._tokenCredential=r,this._callStack=i,this._deviceManagerInternal=a,this._clientTypeInfo=o,this._options=s,this._tokenFetchTries=0,this._sessionMap=new Map,this.tokenProvider=async e=>{if(!this._tokenCredential)throw new Y({defaultError:J.CALL_AGENT.GET_TOKEN_BEFORE_INIT});let t=await M4(this._tokenCredential,Z().calling.eudb.isRgnClaimEnabledForACS);return t.acsResourceId===this._parsedTokenCredential?.acsResourceId&&t.identityMri===this._parsedTokenCredential?.identityMri||k4(J.CALL_AGENT.REFRESHED_TOKEN_INVALID_USERID,this._logger),e?this._tokenFetchTries+=1:this._tokenFetchTries=0,this._tokenFetchTries>this._maxNumberOfRetries&&k4(J.CALL_AGENT.REFRESHED_TOKEN_RETRIES,this._logger),t.jwtToken},this._logger.debug(`MediaSessionAgentImpl: constructor called token: ${!!this._tokenCredential} options: ${JSON.stringify(this._options)}`),this._parsedTokenCredential=eTe(),this._maxNumberOfRetries=Z().calling.maxNumberOfTokenFetchRetries||zCe;let c=new TLe(this._telemetryLogManager);this._telemetryLogger=c.getGenericTelemetryLogger(`waimeabay`),s?.sessionAgentConfig?.allowDisconnectOnBeforeUnload&&(window.addEventListener(`beforeunload`,(()=>{this._disconnectAllSessions(`unload`)})),this._logger.debug(`MediaSessionAgent: Page unload listener registered (beforeunload)`))}_getSessionParams(e,t,n,r){let i=n?.sessionId??K0(),a=aze.create().setTsStack(this._tsWbStack).setDeviceManagerInternal(this._deviceManagerInternal).setClientTypeInfo(this._clientTypeInfo).setTsWbSession(t);return a.setClientId(this._clientId).setSessionAgent(this).setLogger(this._logger).setTelemetryLogManager(this._telemetryLogManager).setSessionId(i),e||a.setOptions(r),this._options?.serviceOrigin&&a.setServiceOrigin(this._options.serviceOrigin),a}_getOrCreateMediaSession(e,t,n){if(!this._tsWbStack)throw Error(`MediaSessionAgent is not initialized`);let r=this._getSessionKey(t),i=this._sessionMap.get(r);if(i)return this._logger.debug(`MediaSessionAgentImpl: Returning existing session for key: ${r}, total sessions: ${this._sessionMap.size}`),e||i.session.state!==DG.Preheated&&i.session.state!==DG.Connecting||i.session.startMedia(!0,n),i.session;let a=this._tsWbStack.getWBSessionObject(r,{media:this._telemetryLogger});if(!a)throw new Y({defaultError:J.WB_MEDIA_SDK.AGENT.TS_STACK_FAILD_TO_GET_WB_SESSION});let o=new ize(this._getSessionParams(!1,a,t,n)),s=performance.now(),c=K0();return o.initialize(e).then((()=>{this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:c,operationName:`MediaSessionInit`,durationInMs:performance.now()-s,operationPayload:{},resultCategories:[`Success`],resultSignature:200})})).catch((e=>{this._logger.error(`Session initialization failed: ${e}`);let t=new Y({defaultError:J.WB_MEDIA_SDK.CLIENT.INIT,originalError:e});this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:c,operationName:`MediaSessionInit`,durationInMs:performance.now()-s,operationPayload:{...K3(t).communicationServicesError},resultCategories:t.resultCategories,resultSignature:500})})),this._sessionMap.set(r,{session:o,tsWbSession:a}),this._logger.debug(`MediaSessionAgentImpl: Created and stored new session for key: ${r}, total sessions: ${this._sessionMap.size}`),o}joinSession(e,t){return this._getOrCreateMediaSession(!1,e,t)}preheatSession(e){return this._getOrCreateMediaSession(!0,e)}async initialize(){let e=performance.now(),t=K0();try{this._parsedTokenCredential=await M4(this._tokenCredential,Z().calling.eudb.isRgnClaimEnabledForACS);let n={clientId:this._clientId,acsResourceId:this._parsedTokenCredential.acsResourceId,identityMri:this._parsedTokenCredential.identityMri,cloudType:this._parsedTokenCredential.cloudType,identityType:this._parsedTokenCredential.isEnterpriseUser?$0.Enterprise:$0.Consumer,region:this._parsedTokenCredential.region,IsUserEmergencyCountryCode:!1,mriType:this._parsedTokenCredential.mriType};this._tsWbStack=await this._callStack.initializeMediaSdkStackForUser(this.tokenProvider,n),this._telemetryLogManager.initialize(n),this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`MediaSessionAgentInit`,durationInMs:performance.now()-e,operationPayload:{serviceOrigin:this._options?.serviceOrigin??``},resultCategories:[`Success`],resultSignature:200})}catch(n){let r=new Y({defaultError:J.WB_MEDIA_SDK.CLIENT.INIT,originalError:n});throw this._logger.error(`MediaClient: Error initializing CallStack: ${r}`),this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`MediaSessionAgentInit`,durationInMs:performance.now()-e,operationPayload:{...K3(r).communicationServicesError},resultCategories:r.resultCategories,resultSignature:500}),r}}_getSessionKey(e){return e&&e.sessionId?e.sessionId:`default`}getSession(e){let t=this._getSessionKey(e);return this._sessionMap.get(t)?.session}removeSession(e){let t=this._getSessionKey(e),n=this._sessionMap.get(t),r=!!n;return n&&(this._clearTsWbSession(n.tsWbSession,t),r=this._sessionMap.delete(t),this._logger.debug(`MediaSessionAgentImpl: Removed session for key: ${t}, remaining sessions: ${this._sessionMap.size}`)),r}get sessions(){return Array.from(this._sessionMap.values()).map((e=>e.session))}_clearAllSessions(){this._sessionMap.clear(),this._logger.debug(`MediaSessionAgentImpl: Cleared all sessions from map`)}_clearTsWbSession(e,t){if(e)try{e.dispose(),this._tsWbStack.mediaAgent.disposeSession(t),this._logger.debug(`MediaSessionAgentImpl: Disposed tsWbSession after last session removed`)}catch(e){this._logger.error(`MediaSessionAgentImpl: Error disposing tsWbSession: ${e}`)}}_disconnectAllSessions(e){if(this._sessionMap.size===0)return;let t=Array.from(this._sessionMap.values());for(let n of t)try{n.session.disconnectFromUnload(e)}catch(e){this._logger.error(`MediaSessionAgent: Error disconnecting session: ${e}`)}}dispose(){this._logger.debug(`MediaSessionAgentImpl: Disposing agent and all sessions`),this._disconnectAllSessions(`dispose`),this._tsWbStack.dispose(),this._telemetryLogManager.clearTelemetryLoggers(),this._clearAllSessions(),q9.instance.dispose()}},sze=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},cze=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},lze=1,uze=class{get initializedDeviceManager(){return this._initializedDeviceManager}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}constructor(e){this._initializedDeviceManager=!1,qSe(c2.MediaStreaming);let t=performance.now();this._clientId=K0();let n=lze++,r=e?.logger||KW(`ACS-calling`);this.logger=new z6(r,[()=>`MediaClient${n}[${this._clientId}]`]),this._mediaSdkDiagnosticInformation=tTe(Y2(),this.logger,e),this._clientTypeInfo={name:lue,version:Y2(),details:this._mediaSdkDiagnosticInformation},this._eventEmitter=new S6(this.logger),this._telemetryLogManager=new f3(this.logger,this._mediaSdkDiagnosticInformation);try{this._callStack=new A9(this.logger,this._clientId,this._telemetryLogManager,this._mediaSdkDiagnosticInformation,new WRe,new GRe,void 0,void 0,!1),this._deviceManager=new N9(this.logger,this._callStack,this._telemetryLogManager,!0,e?.enumerateDevices??!1),this._extensibleApi=new N3(this.logger,{mediaClient:this},{mediaClient:this,telemetryLogManager:this._telemetryLogManager,callStack:this._callStack}),this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:this._clientId,operationName:`MediaClientInit`,durationInMs:performance.now()-t,operationPayload:{},resultCategories:[`Success`],resultSignature:200})}catch(e){let n=new Y({defaultError:J.WB_MEDIA_SDK.CLIENT.INIT,originalError:e});throw this.logger.error(`MediaClient: Error initializing CallStack: ${n}`),this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:this._clientId,operationName:`MediaClientInit`,durationInMs:performance.now()-t,operationPayload:{...K3(n).communicationServicesError},resultCategories:n.resultCategories,resultSignature:500}),n}}feature(e){return this._extensibleApi.getApiObjectInstance(e.mediaClientApiCtor)}async createSessionAgent(e,t){let n=new oze(this.logger,this._telemetryLogManager,this._clientId,e,this._callStack,this._deviceManager,this._clientTypeInfo,t);return await n.initialize(),n}async getDeviceManager(){return await this._deviceManager.getDeviceManager(),this._initializedDeviceManager=!0,this._eventEmitter.emit(`initializedDeviceManager`),this._deviceManager}getSdkVersion(){return Y2()}async checkDevicePermissions(e){let t=new Map,n=performance.now();e.forEach((e=>{t.set(e,EG.Prompt)}));try{if(!navigator.permissions||typeof navigator.permissions.query!=`function`){let e={};return t.forEach(((t,n)=>{e[n]=t})),this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:this._clientId,operationName:`DevicePermissionAccess`,durationInMs:performance.now()-n,operationPayload:e,resultCategories:[`Success`],resultSignature:200}),t}for(let n of e)try{let e=await navigator.permissions.query({name:n});t.set(n,e.state)}catch(e){this.logger.warn(`Failed to query ${n} permission: ${e}`),t.set(n,EG.Prompt)}let r={};return t.forEach(((e,t)=>{r[t]=e})),this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:this._clientId,operationName:`DevicePermissionAccess`,durationInMs:performance.now()-n,operationPayload:r,resultCategories:[`Success`],resultSignature:200}),t}catch(e){let r=new Y({defaultError:J.WB_MEDIA_SDK.CLIENT.INIT,originalError:e});return this.logger.error(`MediaClient::checkDevicePermissions, error checking device permissions ${r}`),this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:this._clientId,operationName:`DevicePermissionAccess`,durationInMs:performance.now()-n,operationPayload:{...K3(r).communicationServicesError},resultCategories:r.resultCategories,resultSignature:500}),t}}};sze([zG,cze(`design:type`,Object)],uze.prototype,`logger`,void 0);var dze=`hangedUp`,Y9=`declined`,X9=`connected`,Z9=`loading`,Q9=`devicePermissionDenied`,fze=2e3,pze={name:`BDVideoCallTemplate`,components:{BDSmallConversationCard:BH,BDLoader:yae,BDButton:ha,BDCol:d,BDContainer:f,BDRow:p,IconEndCall:At,IconShareScreen:di},props:{messageWhenLoading:String,participant:{type:Object,default:null},isCallee:{type:Boolean,default:!1},videoTestUrl:{type:String,default:null}},data(){return{azureLogs:[],l:this.$localization.template.videoCall,isScreenShared:!1,screenshareAvailable:!1,signalStrength:2,devicePermissions:{},videoCallState:Z9,userFacingDiagnostics:null,acsConfig:{client:null,agent:null,deviceManager:null,incomingCall:null,call:null},localVideoStream:null,screenShareView:null,availableCamerasCount:0,cameraIndex:0,isBrowserFirefox:navigator.userAgent.indexOf(`Firefox`)>-1}},computed:{AvailableCamerasCountMessage(){switch(this.availableCamerasCount){case 0:return this.l.hasNoAvailableCamera;case 1:return this.l.hasOneAvailableCamera;default:return this.l.hasMultipleAvailableCameras}},IsLocalVideoStreamSwitchAvailable(){let e=navigator.userAgent;return/Mobi/.test(e)&&!this.isScreenShared},DeviceSupportsScreenShare(){let e=navigator.userAgent,t=e.indexOf(`Android`)!==-1,n=/Mobi/.test(e),r=/iPad|iPhone|iPod/.test(e)&&!window.MSStream;return!(t&&n||r)},IsVideoDisabled(){return!this.devicePermissions?.video&&this.DevicePermissionsDenied},IsAudioDisabled(){return!this.devicePermissions?.audio&&this.DevicePermissionsDenied},CallStateClass(){return this.videoCallState===Y9?`incoming--declined`:`incoming--loading`},PermissionMissingToStartCall(){return this.browserPermissionDeniedForAudio||this.browserPermissionDeniedForVideo},signalStrengthClass(){switch(this.signalStrength){case 0:return`weak`;case 1:return`steady`;case 2:return`strong`;default:return null}},signalStrengthLabel(){switch(this.signalStrength){case 0:return this.l.signalStrength.weak;case 1:return this.l.signalStrength.steady;case 2:return this.l.signalStrength.strong;default:return null}},ShareScreenLabel(){return this.isScreenShared?this.l.stopSharingScreen:this.l.shareScreen},settingsHelpTitleLabel(){return this.l.placeholderSettingsHelpTitle},settingsHelpMessageLabel(){return this.l.placeholderSettingsHelpMessage},IsLoading(){return this.videoCallState===Z9},IsDeclined(){return this.videoCallState===Y9},IsHangedUp(){return this.videoCallState===dze},IsConnected(){return this.videoCallState===X9},ShowLoader(){return this.videoCallState!==X9},DevicePermissionsDenied(){return this.videoCallState===Q9},LoaderMessage(){return this.IsHangedUp?this.l.messageWhenVideoCallHangedUp:this.IsDeclined?this.l.messageWhenVideoCallDeclined:this.DevicePermissionsDenied?this.l.messageWhenDevicePermissionDenied:this.messageWhenLoading},VideoStreamClassToSelect(){return this.screenshareAvailable?`.incoming__screenshare`:`.incoming__video`}},created(){this.InitAzureLogger()},unmounted(){this.EndVideoCall()},methods:{CallDeclined(){this.videoCallState=Y9},CallAnswered(){},CallStartVideoCall(){this.videoCallState!==Q9&&this.StartCall()},async CallHangUp(){this.videoCallState=dze,this.devicePermissions.video&&this.DisplayAvailableLocalVideoStream()},async InitializeAcsConnection(e){this.acsConfig.client=(0,u.markRaw)(new U9);let t=await new Xle(e);this.acsConfig.agent=(0,u.markRaw)(await this.acsConfig.client.createCallAgent(t)),this.acsConfig.deviceManager=await this.acsConfig.client.getDeviceManager(),this.devicePermissions=await this.acsConfig.deviceManager.askDevicePermission({video:!0,audio:!0}),window.setInterval(this.DisplayAvailableLocalVideoStream,5e3),(!this.devicePermissions.audio||!this.devicePermissions.video)&&(this.videoCallState=Q9),this.isCallee?(this.acsConfig.agent.on(`incomingCall`,this.SetIncomingCall),this.$emit(`ready`)):this.$emit(`start-call`)},async SetIncomingCall(e){try{this.acsConfig.incomingCall=e.incomingCall,this.AcceptCall()}catch{console.log(`error occured during starting call`)}},async CreateNewVideoOptions(){let e=await this.CreateLocalVideoStream();return e?{localVideoStreams:[e]}:void 0},async StartCall(){try{let e=await this.CreateNewVideoOptions(),t={communicationUserId:this.participant.videoCallIdentityId};this.acsConfig.call=this.acsConfig.agent.startCall([t],{videoOptions:e}),this.SubscribeToDiagnostics(),this.SubscribeToCall()}catch(e){console.error(e)}},async AcceptCall(){let e=await this.CreateNewVideoOptions();this.acsConfig.call=await this.acsConfig.incomingCall.accept({videoOptions:e}),this.SubscribeToDiagnostics(),this.SubscribeToCall()},async CreateLocalVideoStream(){let e=(await this.acsConfig.deviceManager.getCameras())[0];if(e)return new J6(e);console.error(`No camera device found on the system`)},SubscribeToCall(){this.acsConfig.call.on(`stateChanged`,this.CallStateIsChanged),this.acsConfig.call.on(`localVideoStreamsUpdated`,e=>{e.added.forEach(this.DisplayLocalScreenShareStream),e.removed.forEach(this.RemoveLocalScreenShareStream)}),this.acsConfig.call.remoteParticipants.forEach(this.SubscribeToRemoteParticipant),this.acsConfig.call.on(`remoteParticipantsUpdated`,e=>{e.added.forEach(this.SubscribeToRemoteParticipant)}),this.acsConfig.call.on(`isScreenSharingOnChanged`,()=>{this.isScreenShared=this.acsConfig.call.isScreenSharingOn})},SubscribeToDiagnostics(){this.userFacingDiagnostics=this.acsConfig.call.feature(Z5.UserFacingDiagnostics),this.userFacingDiagnostics.media.on(`diagnosticChanged`,this.DiagnosticChangedListener),this.userFacingDiagnostics.network.on(`diagnosticChanged`,this.DiagnosticChangedListener)},DiagnosticChangedListener(e){(e.diagnostic===`networkReceiveQuality`||e.diagnostic===`networkSendQuality`)&&(e.value===e6.Bad?(console.error(`${e.diagnostic} is bad quality`),this.signalStrength=0):e.value===e6.Poor?(console.error(`${e.diagnostic} is poor quality`),this.signalStrength=1):this.signalStrength=2)},CallStateIsChanged(){switch(this.acsConfig.call.state){case`EarlyMedia`:this.videoCallState=Z9;break;case`Ringing`:this.videoCallState=Z9;break;case`Connected`:this.videoCallState=X9;break;case`Disconnected`:this.CallHangUp();break}},async RemoveLocalScreenShareStream(e){if(!e||!e.mediaStreamType==`ScreenSharing`||!this.screenShareView)return;this.screenShareView.dispose();let t=document.querySelector(`.outgoing__screenshare`);t.style.display=`none`;let n=document.querySelector(`.outgoing__video`);n.style.display=`flex`},async DisplayLocalScreenShareStream(e){if(!e||!e.mediaStreamType==`ScreenSharing`)return;let t=new O7(e);this.screenShareView=await t.createView();let n=document.querySelector(`.outgoing__screenshare`);n.replaceChildren(this.screenShareView.target),n.style.display=`flex`;let r=document.querySelector(`.outgoing__video`);r.style.display=`none`;let i=n.querySelector(`video`);i.style.objectFit=`contain`},async DisplayLocalVideoStream(e){if(e&&e.source&&this.localVideoStream&&this.localVideoStream.source&&this.localVideoStream.source.id==e.source.id)return!0;try{this.localVideoStreamRenderer=new O7(e);let t=await this.localVideoStreamRenderer.createView(),n=document.querySelector(`.outgoing__video`);n.querySelector(`video`)&&(n.innerHTML=``),n.hidden=!1,n.replaceChildren(t.target)}catch{return!1}return this.localVideoStream=e,!0},async SubscribeToRemoteParticipant(e){e.videoStreams.forEach(this.DisplayRemoteVideoStream),e.on(`videoStreamsUpdated`,e=>{e.added.forEach(this.DisplayRemoteVideoStream)})},async DisplayRemoteVideoStream(e){if(e.mediaStreamType===`Video`&&(await this.RenderVideo(e),e.on(`isAvailableChanged`,async()=>await this.RenderVideo(e))),e.mediaStreamType===`ScreenSharing`&&e.on(`isAvailableChanged`,this.ScreenSharingAvailabilityChanged),e.mediaStreamType===`ScreenSharing`&&e.isAvailable){this.remoteStreamRenderer=new O7(e);let t=await this.remoteStreamRenderer.createView(),n=document.querySelector(`.incoming__screenshare`);this.HideCameraStream(!0),this.screenshareAvailable=!0,this.EnableMiniPlayerOnVideoElement(`.incoming__screenshare`),n.replaceChildren(t.target)}},async RenderVideo(e){if(!e.isAvailable)return;this.remoteStreamRenderer=new O7(e);let t=await this.remoteStreamRenderer.createView(),n=document.querySelector(`.incoming__video`);n.hidden=!1,n.replaceChildren(t.target),this.EnableMiniPlayerOnVideoElement(`.incoming__video`),this.HideCameraStream(!1)},HideCameraStream(e){let t=document.querySelector(`.incoming__video`),n=document.querySelector(`.incoming__screenshare`);t.style.display=e?`none`:`block`,n.style.display=e?`flex`:`none`},ScreenSharingAvailabilityChanged(){this.screenshareAvailable=!1,this.HideCameraStream(!1)},async SwitchLocalVideoStream(){this.DisplayAvailableLocalVideoStream(!0)},async DisplayAvailableLocalVideoStream(e=!1){let t=(await this.acsConfig.deviceManager.getCameras()).filter(e=>e.name!=`OBS Virtual Camera`);this.availableCamerasCount=t.length;for(let n=0;n<this.availableCamerasCount;n++){(e||n!=0)&&(this.cameraIndex=(this.cameraIndex+1)%this.availableCamerasCount);let r=t[this.cameraIndex],i=new J6(r);if(await this.DisplayLocalVideoStream(i))break}},EnableMiniPlayerOnVideoElement(e){let t=document.querySelector(e);if(!t)return;let n=t.querySelector(`video`);n&&(n.style.objectFit=`contain`,n.disablePictureInPicture=!1)},async EndVideoCall(){this.acsConfig.call&&this.acsConfig.call.state!==`Disconnected`&&(await this.acsConfig.call.hangUp({forEveryone:!0}),await this.acsConfig.agent.dispose()),this.$emit(`end-video-call`),window.close()},CloseWindow(){window.close()},InitAzureLogger(){Tae(`verbose`),GW.log=(...e)=>{let t=[...e];this.azureLogs=this.azureLogs.splice(1-fze).concat(t)}},ChangeToFullscreen(){document.querySelector(this.VideoStreamClassToSelect).querySelector(`video`).requestFullscreen()},ChangeToMiniPlayer(){let e=document.querySelector(this.VideoStreamClassToSelect).querySelector(`video`);document.pictureInPictureElement?e.exitPictureInPicture():document.pictureInPictureEnabled&&e.requestPictureInPicture()},async OnShareScreen(){this.acsConfig.call&&this.acsConfig.call.isScreenSharingOn?await this.acsConfig.call.stopScreenSharing():await this.acsConfig.call.startScreenSharing()}}},mze={class:`video-call-template`},hze={key:0,class:`card`},gze={key:0,class:`permissions-denied__audio`},_ze={class:`permissions-denied__audio-disabled`},vze={key:1,class:`permissions-denied__video`},yze={class:`permissions-denied__video-disabled`},bze={key:1,class:`card`},xze={class:`incoming__settings`},Sze={class:`side`},Cze={class:`outgoing`},wze={class:`card`},Tze={key:0,class:`outgoing__video`},Eze={class:`outgoing__available-cameras-count text-center`},Dze={key:3,class:`permissions-denied__video`},Oze={class:`permissions-denied__video-disabled`},kze={class:`settings`},Aze={class:`settings__help`},jze=[`href`],Mze={href:`https://www.beterdichtbij.nl/service-contact/`,target:`blank`,rel:`noopener noreferrer`};function Nze(e,t,n,r,i,a){let o=(0,u.resolveComponent)(`BDSmallConversationCard`),s=(0,u.resolveComponent)(`BDCol`),c=(0,u.resolveComponent)(`BDRow`),l=(0,u.resolveComponent)(`BDLoader`),d=(0,u.resolveComponent)(`IconMicrophoneSlash`),f=(0,u.resolveComponent)(`IconVideoDisabled`),p=(0,u.resolveComponent)(`BDButton`),m=(0,u.resolveComponent)(`IconShareScreen`),h=(0,u.resolveComponent)(`IconEndCall`),g=(0,u.resolveComponent)(`BDContainer`);return(0,u.openBlock)(),(0,u.createElementBlock)(`div`,mze,[(0,u.createVNode)(g,null,{default:(0,u.withCtx)(()=>[(0,u.createVNode)(c,null,{default:(0,u.withCtx)(()=>[(0,u.createVNode)(s,null,{default:(0,u.withCtx)(()=>[(0,u.createVNode)(o,{smallState:!0,contactInfo:n.participant.contact},null,8,[`contactInfo`])]),_:1})]),_:1}),(0,u.createVNode)(c,null,{default:(0,u.withCtx)(()=>[(0,u.createVNode)(s,{sm:`12`,lg:a.IsDeclined?`12`:`8`},{default:(0,u.withCtx)(()=>[(0,u.createElementVNode)(`div`,{class:(0,u.normalizeClass)([`incoming`,a.CallStateClass])},[a.ShowLoader?((0,u.openBlock)(),(0,u.createElementBlock)(`div`,hze,[(0,u.createVNode)(l,{size:`lg`,message:a.LoaderMessage,stopAnimation:a.IsDeclined||a.IsHangedUp||a.DevicePermissionsDenied},null,8,[`message`,`stopAnimation`]),a.IsAudioDisabled?((0,u.openBlock)(),(0,u.createElementBlock)(`div`,gze,[(0,u.createElementVNode)(`div`,_ze,[(0,u.createVNode)(d,{class:`icon-xl icon-state-error`})]),(0,u.createElementVNode)(`span`,null,(0,u.toDisplayString)(i.l.permissionDeniedForAudio),1)])):(0,u.createCommentVNode)(``,!0),a.IsVideoDisabled?((0,u.openBlock)(),(0,u.createElementBlock)(`div`,vze,[(0,u.createElementVNode)(`div`,yze,[(0,u.createVNode)(f,{class:`icon-xl icon-state-error`})]),(0,u.createElementVNode)(`span`,null,(0,u.toDisplayString)(i.l.permissionDeniedForVideo),1)])):(0,u.createCommentVNode)(``,!0),a.IsDeclined||a.IsHangedUp||a.DevicePermissionsDenied?((0,u.openBlock)(),(0,u.createBlock)(p,{key:2,variant:`primary`,class:`text-center`,onClick:a.CloseWindow},{default:(0,u.withCtx)(()=>[(0,u.createTextVNode)((0,u.toDisplayString)(i.l.closeWindow),1)]),_:1},8,[`onClick`])):(0,u.createCommentVNode)(``,!0)])):((0,u.openBlock)(),(0,u.createElementBlock)(`div`,bze,[t[0]||=(0,u.createElementVNode)(`div`,{class:`incoming__video`},null,-1),t[1]||=(0,u.createElementVNode)(`div`,{class:`incoming__screenshare`},null,-1),(0,u.createElementVNode)(`div`,xze,[(0,u.createVNode)(p,{variant:`primary`,class:`text-center`,onClick:a.ChangeToFullscreen},{default:(0,u.withCtx)(()=>[(0,u.createVNode)(m),(0,u.createElementVNode)(`span`,null,(0,u.toDisplayString)(i.l.fullScreen),1)]),_:1},8,[`onClick`]),!i.isBrowserFirefox&&!e.screenAlreadyShared?((0,u.openBlock)(),(0,u.createBlock)(p,{key:0,variant:`primary`,class:`text-center`,onClick:a.ChangeToMiniPlayer},{default:(0,u.withCtx)(()=>[(0,u.createVNode)(m),(0,u.createElementVNode)(`span`,null,(0,u.toDisplayString)(i.l.miniPlayer),1)]),_:1},8,[`onClick`])):(0,u.createCommentVNode)(``,!0)])]))],2)]),_:1},8,[`lg`]),a.IsDeclined?(0,u.createCommentVNode)(``,!0):((0,u.openBlock)(),(0,u.createBlock)(s,{key:0,sm:`12`,lg:`4`},{default:(0,u.withCtx)(()=>[(0,u.createElementVNode)(`div`,Sze,[(0,u.createElementVNode)(`div`,null,[(0,u.createElementVNode)(`div`,Cze,[(0,u.createElementVNode)(`div`,wze,[a.DevicePermissionsDenied?(0,u.createCommentVNode)(``,!0):((0,u.openBlock)(),(0,u.createElementBlock)(`div`,Tze)),t[2]||=(0,u.createElementVNode)(`div`,{class:`outgoing__screenshare`},null,-1),a.DeviceSupportsScreenShare&&!a.DevicePermissionsDenied&&!e.screenAlreadyShared&&!a.ShowLoader?((0,u.openBlock)(),(0,u.createBlock)(p,{key:1,variant:i.isScreenShared?`danger`:`primary`,class:`text-center`,onClick:a.OnShareScreen},{default:(0,u.withCtx)(()=>[(0,u.createVNode)(m),(0,u.createElementVNode)(`span`,null,(0,u.toDisplayString)(a.ShareScreenLabel),1)]),_:1},8,[`variant`,`onClick`])):(0,u.createCommentVNode)(``,!0),a.IsLocalVideoStreamSwitchAvailable?((0,u.openBlock)(),(0,u.createElementBlock)(u.Fragment,{key:2},[(0,u.createVNode)(p,{class:`text-center`,onClick:a.SwitchLocalVideoStream},{default:(0,u.withCtx)(()=>[(0,u.createTextVNode)((0,u.toDisplayString)(i.l.switchCamera),1)]),_:1},8,[`onClick`]),(0,u.createElementVNode)(`p`,Eze,(0,u.toDisplayString)(a.AvailableCamerasCountMessage),1)],64)):(0,u.createCommentVNode)(``,!0),a.IsVideoDisabled?((0,u.openBlock)(),(0,u.createElementBlock)(`div`,Dze,[(0,u.createElementVNode)(`div`,Oze,[(0,u.createVNode)(f,{class:`icon-xxl icon-state-error`})]),(0,u.createElementVNode)(`span`,null,(0,u.toDisplayString)(i.l.permissionDeniedForVideo),1)])):(0,u.createCommentVNode)(``,!0)])]),(0,u.createElementVNode)(`div`,kze,[(0,u.createElementVNode)(`div`,{class:(0,u.normalizeClass)([`settings__signal`,a.signalStrengthClass])},[t[3]||=(0,u.createElementVNode)(`ul`,{class:`indicator`},[(0,u.createElementVNode)(`li`),(0,u.createElementVNode)(`li`),(0,u.createElementVNode)(`li`)],-1),(0,u.createElementVNode)(`p`,null,(0,u.toDisplayString)(a.signalStrengthLabel),1)],2),(0,u.createElementVNode)(`div`,Aze,[(0,u.createElementVNode)(`p`,null,[(0,u.createElementVNode)(`b`,null,(0,u.toDisplayString)(a.settingsHelpTitleLabel),1)]),(0,u.createElementVNode)(`p`,null,(0,u.toDisplayString)(a.settingsHelpMessageLabel),1),(0,u.createElementVNode)(`p`,null,[(0,u.createElementVNode)(`a`,{href:n.videoTestUrl,target:`blank`,rel:`noopener noreferrer`},(0,u.toDisplayString)(i.l.testCall),9,jze),t[4]||=(0,u.createTextVNode)(` • `,-1),(0,u.createElementVNode)(`a`,Mze,(0,u.toDisplayString)(i.l.serviceDesk),1)])])])]),!a.IsHangedUp&&!a.DevicePermissionsDenied?((0,u.openBlock)(),(0,u.createBlock)(p,{key:0,variant:`danger`,class:`text-center w-100`,onClick:a.EndVideoCall},{default:(0,u.withCtx)(()=>[(0,u.createVNode)(h),(0,u.createElementVNode)(`span`,null,(0,u.toDisplayString)(i.l.endCall),1)]),_:1},8,[`onClick`])):(0,u.createCommentVNode)(``,!0)])]),_:1}))]),_:1})]),_:1})])}var Pze=m(pze,[[`render`,Nze]]),Fze={class:`template not-found-template`},Ize={class:`center-screen`},Lze={class:`container-warning`},Rze=[`textContent`],zze=[`textContent`],$9=(0,u.defineComponent)({__name:`BDNotFoundTemplate`,props:{buttonText:{type:String}},emits:[`navigate`],setup(e,{emit:t}){let{t:n}=Lu(),r=e,i=t,a=(0,u.computed)(()=>r.buttonText||n(`notFoundTemplate.buttonDefault`)),o=(0,u.computed)(()=>n(`notFoundTemplate.title`)),s=(0,u.computed)(()=>n(`notFoundTemplate.description`)),c=()=>i(`navigate`);return(e,t)=>((0,u.openBlock)(),(0,u.createElementBlock)(`main`,Fze,[(0,u.createVNode)(f,{class:`container-xl`},{default:(0,u.withCtx)(()=>[(0,u.createElementVNode)(`div`,Ize,[(0,u.createElementVNode)(`div`,Lze,[(0,u.createVNode)(Ri),(0,u.createElementVNode)(`h5`,{textContent:(0,u.toDisplayString)(o.value)},null,8,Rze),(0,u.createElementVNode)(`p`,{textContent:(0,u.toDisplayString)(s.value)},null,8,zze),(0,u.createVNode)(ha,{onClick:c,variant:`primary`,type:`button`,textContent:(0,u.toDisplayString)(a.value)},null,8,[`textContent`])])])]),_:1})]))}}),Bze=e=>{let t=/<a\b[^>]*>.*?<\/a>/gi,n=[],r;for(;(r=t.exec(e))!==null;)n.push({start:r.index,end:r.index+r[0].length});return e.replace(/(https?:\/\/[^\s<>"',]+|www\.[^\s<>"',]+)/g,(e,t,r)=>n.some(e=>r>=e.start&&r<e.end)?e:`<a href="${e.startsWith(`www.`)?`http://${e}`:e}" target="_blank" rel="noopener noreferrer">${e}</a>`)},Vze=(e,t)=>`<p><a href="${e}" title="${t}" target="_blank" rel="noopener noreferrer">${t}</a></p>`,Hze=e=>e.startsWith(`http://`)||e.startsWith(`https://`),Uze={install:e=>{e.component(`BDAlert`,oa),e.component(`BDArticle`,la),e.component(`BDAssignConversationModal`,FU),e.component(`BDAttachmentPreviewList`,T_),e.component(`BDAttachmentUploadModal`,IU),e.component(`BDBadge`,fa),e.component(`BDButton`,ha),e.component(`BDCard`,wa),e.component(`BDChangePasswordTemplate`,TW),e.component(`BDChatCloud`,Y_),e.component(`BDCol`,d),e.component(`BDCollapsableCard`,Oa),e.component(`BDConfirmationModal`,LU),e.component(`BDContainer`,f),e.component(`BDContentLibraryModal`,Tie),e.component(`BDContentLibrarySplitButton`,Eh),e.component(`BDContentLibraryTemplate`,gW),e.component(`BDConversationToTextModal`,yW),e.component(`BDDate`,Gh),e.component(`BDDropdown`,rU),e.component(`BDDropdownItem`,X_),e.component(`BDFileUpload`,tO),e.component(`BDForm`,Kh),e.component(`BDFormCheckbox`,ug),e.component(`BDFormInput`,Mg),e.component(`BDFormInvalidFeedback`,fg),e.component(`BDFormMultipleCheckbox`,aO),e.component(`BDFormSelect`,Lg),e.component(`BDHeader`,cU),e.component(`BDImageAttachmentModal`,xW),e.component(`BDImageAttachmentPreviewList`,P_),e.component(`BDInputGroup`,Bg),e.component(`BDLink`,ma),e.component(`BDLogo`,Ug),e.component(`BDMarkdownEditor`,jH),e.component(`BDMessageTemplateFormModal`,SW),e.component(`BDMobileMenu`,FH),e.component(`BDModal`,gU),e.component(`BDNotFoundTemplate`,$9),e.component(`BDPagination`,Xg),e.component(`BDPhoneNumberEditModal`,xU),e.component(`BDPill`,i_),e.component(`BDPractitionerHeader`,MU),e.component(`BDProfileImage`,s_),e.component(`BDRow`,p),e.component(`BDSessionTimeOutModal`,PU),e.component(`BDSmallConversationCard`,BH),e.component(`BDTable`,GH),e.component(`BDToast`,f_),e.component(`BDUser`,KH),e.component(`BDUserInformation`,__),e.component(`BDVideoCallConfirmationModal`,CW),e.component(`BDVideoCallTemplate`,Pze),e.component(`BDVideoCallToast`,nU),e.component(`BDZoomslider`,b_),e.component(`IconAcademy`,v),e.component(`IconArrowDown`,S),e.component(`IconArrowUp`,E),e.component(`IconAttachment`,k),e.component(`IconBold`,ne),e.component(`IconBulletList`,M),e.component(`IconCalendar`,le),e.component(`IconCall`,N),e.component(`IconCallReject`,ge),e.component(`IconCardView`,F),e.component(`IconCaretDown`,L),e.component(`IconCaretLeft`,Se),e.component(`IconCaretRight`,Ee),e.component(`IconCheck`,Ae),e.component(`IconClipboard`,Me),e.component(`IconClose`,Ie),e.component(`IconComment`,Be),e.component(`IconCommentActive`,We),e.component(`IconCommentStatic`,Je),e.component(`IconCommonFileEmpty`,Qe),e.component(`IconCommonFileWarning`,nt),e.component(`IconContactPerson`,ot),e.component(`IconCopy`,ut),e.component(`IconDelete`,mt),e.component(`IconDoubleCheck`,vt),e.component(`IconDownloadImage`,St),e.component(`IconEdit`,Et),e.component(`IconEndCall`,At),e.component(`IconError`,Pt),e.component(`IconExternal`,Rt),e.component(`IconEyeShow`,Ht),e.component(`IconEyeSlash`,Kt),e.component(`IconFile`,Xt),e.component(`IconFileAdded`,en),e.component(`IconForward`,an),e.component(`IconHix`,ln),e.component(`IconHyperlink`,pn),e.component(`IconImageFileLandscape`,_n),e.component(`IconImageFileWarning`,xn),e.component(`IconInbox`,Tn),e.component(`IconInfo`,H),e.component(`IconInformationCircle`,Mn),e.component(`IconItalic`,In),e.component(`IconListView`,Bn),e.component(`IconLock`,Wn),e.component(`IconLusciiEscalated`,Jn),e.component(`IconLusciiLogo`,Qn),e.component(`IconLusciiOpen`,nr),e.component(`IconLusciiPriorityHigh`,or),e.component(`IconLusciiPriorityLow`,ur),e.component(`IconLusciiPriorityMedium`,mr),e.component(`IconMenu`,vr),e.component(`IconMessage`,Sr),e.component(`IconMessageForward`,Er),e.component(`IconMicrophoneSlash`,kr),e.component(`IconMicrosoftTeams`,Nr),e.component(`IconMin`,Ir),e.component(`IconOrderedList`,Br),e.component(`IconPlus`,Wr),e.component(`IconRefresh`,Jr),e.component(`IconRemove`,Qr),e.component(`IconSananetLogo`,ri),e.component(`IconService`,si),e.component(`IconShareScreen`,di),e.component(`IconSingleNeutral`,mi),e.component(`IconSort`,vi),e.component(`IconSortAsc`,Si),e.component(`IconSortDesc`,Ei),e.component(`IconSortNone`,Ai),e.component(`IconTriangleDown`,Pi),e.component(`IconTriangleExclamation`,Ri),e.component(`IconUnderline`,Hi),e.component(`IconVideoDisabled`,Yi),e.component(`IconVideocall`,Ki),e.component(`IconWarning`,$i),e.component(`IconZorgkaart`,ra),e.directive(`bd-tooltip`,kH)}};exports.BDAlert=oa,exports.BDArticle=la,exports.BDAssignConversationModal=FU,exports.BDAttachmentPreviewList=T_,exports.BDAttachmentUploadModal=IU,exports.BDBadge=fa,exports.BDButton=ha,exports.BDCard=wa,exports.BDChangePasswordTemplate=TW,exports.BDChatCloud=Y_,exports.BDCol=d,exports.BDCollapsableCard=Oa,exports.BDConfirmationModal=LU,exports.BDContainer=f,exports.BDContentLibraryModal=Tie,exports.BDContentLibrarySplitButton=Eh,exports.BDContentLibraryTemplate=gW,exports.BDConversationToTextModal=yW,exports.BDDate=Gh,exports.BDDropdown=rU,exports.BDDropdownItem=X_,exports.BDFileUpload=tO,exports.BDForm=Kh,exports.BDFormCheckbox=ug,exports.BDFormInput=Mg,exports.BDFormInvalidFeedback=fg,exports.BDFormMultipleCheckbox=aO,exports.BDFormSelect=Lg,exports.BDHeader=cU,exports.BDImageAttachmentModal=xW,exports.BDImageAttachmentPreviewList=P_,exports.BDInputGroup=Bg,exports.BDLink=ma,exports.BDLogo=Ug,exports.BDMarkdownEditor=jH,exports.BDMessageTemplateFormModal=SW,exports.BDMobileMenu=FH,exports.BDModal=gU,exports.BDNotFoundTemplate=$9,exports.BDPagination=Xg,exports.BDPhoneNumberEditModal=xU,exports.BDPill=i_,exports.BDPractitionerHeader=MU,exports.BDProfileImage=s_,exports.BDRow=p,exports.BDSessionTimeOutModal=PU,exports.BDSmallConversationCard=BH,exports.BDTable=GH,exports.BDToast=f_,exports.BDUser=KH,exports.BDUserInformation=__,exports.BDVideoCallConfirmationModal=CW,exports.BDVideoCallTemplate=Pze,exports.BDVideoCallToast=nU,exports.BDZoomslider=b_,exports.CopyChatMessageToClipboard=Pie,exports.CopyChatMessagesToClipboard=Fie,exports.CopyHl7MessagesToClipboard=Iie,exports.CreateHyperlinkParagraph=Vze,exports.CreateThumbnailUri=R_,exports.IconAcademy=v,exports.IconArrowDown=S,exports.IconArrowUp=E,exports.IconAttachment=k,exports.IconBold=ne,exports.IconBulletList=M,exports.IconCalendar=le,exports.IconCall=N,exports.IconCallReject=ge,exports.IconCardView=F,exports.IconCaretDown=L,exports.IconCaretLeft=Se,exports.IconCaretRight=Ee,exports.IconCheck=Ae,exports.IconClipboard=Me,exports.IconClose=Ie,exports.IconComment=Be,exports.IconCommentActive=We,exports.IconCommentStatic=Je,exports.IconCommonFileEmpty=Qe,exports.IconCommonFileWarning=nt,exports.IconContactPerson=ot,exports.IconCopy=ut,exports.IconDelete=mt,exports.IconDoubleCheck=vt,exports.IconDownloadImage=St,exports.IconEdit=Et,exports.IconEndCall=At,exports.IconError=Pt,exports.IconExternal=Rt,exports.IconEyeShow=Ht,exports.IconEyeSlash=Kt,exports.IconFile=Xt,exports.IconFileAdded=en,exports.IconForward=an,exports.IconHix=ln,exports.IconHyperlink=pn,exports.IconImageFileLandscape=_n,exports.IconImageFileWarning=xn,exports.IconInbox=Tn,exports.IconInfo=H,exports.IconInformationCircle=Mn,exports.IconItalic=In,exports.IconListView=Bn,exports.IconLock=Wn,exports.IconLusciiEscalated=Jn,exports.IconLusciiLogo=Qn,exports.IconLusciiOpen=nr,exports.IconLusciiPriorityHigh=or,exports.IconLusciiPriorityLow=ur,exports.IconLusciiPriorityMedium=mr,exports.IconMenu=vr,exports.IconMessage=Sr,exports.IconMessageForward=Er,exports.IconMicrophoneSlash=kr,exports.IconMicrosoftTeams=Nr,exports.IconMin=Ir,exports.IconOrderedList=Br,exports.IconPlus=Wr,exports.IconRefresh=Jr,exports.IconRemove=Qr,exports.IconSananetLogo=ri,exports.IconService=si,exports.IconShareScreen=di,exports.IconSingleNeutral=mi,exports.IconSort=vi,exports.IconSortAsc=Si,exports.IconSortDesc=Ei,exports.IconSortNone=Ai,exports.IconTriangleDown=Pi,exports.IconTriangleExclamation=Ri,exports.IconUnderline=Hi,exports.IconVideoDisabled=Yi,exports.IconVideocall=Ki,exports.IconWarning=$i,exports.IconZorgkaart=ra,exports.MapAttachmentsForApi=F_,exports.MapToAttachmentObjects=V_,exports.TransformHyperlinks=Bze,exports.ValidateUrl=Hze,exports.default=Uze,exports.getDisplayDateNumeric=Uh,exports.getDisplayDateTextual=Bh,exports.getDisplayDateTimeNumeric=Hh,exports.getDisplayDateTimeTextual=Vh,exports.useModal=_U,exports.usePopover=EU,exports.useServerErrors=vU,exports.useSessionTimeOut=NU,exports.useToaster=ZD,exports.useValidation=wW,exports.useWindow=wU,exports.useZoom=bW,exports.vBdTooltip=kH;
|