@creativeorange/azure-text-to-speech 2.2.3 → 3.0.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.
@@ -1,9 +1,9 @@
1
- (function(H,L){typeof exports=="object"&&typeof module!="undefined"?L(exports):typeof define=="function"&&define.amd?define(["exports"],L):(H=typeof globalThis!="undefined"?globalThis:H||self,L(H.CreativeOrangeAzureTextToSpeech={}))})(this,function(H){"use strict";var L={},V,Si=new Uint8Array(16);function mi(){if(!V&&(V=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto!="undefined"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!V))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return V(Si)}var yi=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function wi(r){return typeof r=="string"&&yi.test(r)}for(var x=[],rt=0;rt<256;++rt)x.push((rt+256).toString(16).substr(1));function Ci(r){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,t=(x[r[e+0]]+x[r[e+1]]+x[r[e+2]]+x[r[e+3]]+"-"+x[r[e+4]]+x[r[e+5]]+"-"+x[r[e+6]]+x[r[e+7]]+"-"+x[r[e+8]]+x[r[e+9]]+"-"+x[r[e+10]]+x[r[e+11]]+x[r[e+12]]+x[r[e+13]]+x[r[e+14]]+x[r[e+15]]).toLowerCase();if(!wi(t))throw TypeError("Stringified UUID is invalid");return t}function bi(r,e,t){r=r||{};var i=r.random||(r.rng||mi)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,e){t=t||0;for(var n=0;n<16;++n)e[t+n]=i[n];return e}return Ci(i)}const Ti=()=>bi(),E=()=>Ti().replace(new RegExp("-","g"),"").toUpperCase();var w;(function(r){r[r.Debug=0]="Debug",r[r.Info=1]="Info",r[r.Warning=2]="Warning",r[r.Error=3]="Error",r[r.None=4]="None"})(w||(w={}));class se{constructor(e,t){this.privName=e,this.privEventId=E(),this.privEventTime=new Date().toISOString(),this.privEventType=t,this.privMetadata={}}get name(){return this.privName}get eventId(){return this.privEventId}get eventTime(){return this.privEventTime}get eventType(){return this.privEventType}get metadata(){return this.privMetadata}}class Se extends se{constructor(e,t,i=w.Info){super(e,i),this.privAudioSourceId=t}get audioSourceId(){return this.privAudioSourceId}}class xe extends Se{constructor(e){super("AudioSourceInitializingEvent",e)}}class me extends Se{constructor(e){super("AudioSourceReadyEvent",e)}}class Mt extends Se{constructor(e){super("AudioSourceOffEvent",e)}}class Ne extends Se{constructor(e,t){super("AudioSourceErrorEvent",e,w.Error),this.privError=t}get error(){return this.privError}}class ze extends Se{constructor(e,t,i){super(e,t),this.privAudioNodeId=i}get audioNodeId(){return this.privAudioNodeId}}class ye extends ze{constructor(e,t){super("AudioStreamNodeAttachingEvent",e,t)}}class we extends ze{constructor(e,t){super("AudioStreamNodeAttachedEvent",e,t)}}class G extends ze{constructor(e,t){super("AudioStreamNodeDetachedEvent",e,t)}}class nt extends ze{constructor(e,t,i){super("AudioStreamNodeErrorEvent",e,t),this.privError=i}get error(){return this.privError}}class Dt extends se{constructor(e,t,i=w.Info){super(e,i),this.privJsonResult=t}get jsonString(){return this.privJsonResult}}class oe extends se{constructor(e,t,i=w.Info){super(e,i),this.privConnectionId=t}get connectionId(){return this.privConnectionId}}class kt extends oe{constructor(e,t,i){super("ConnectionStartEvent",e),this.privUri=t,this.privHeaders=i}get uri(){return this.privUri}get headers(){return this.privHeaders}}class xt extends oe{constructor(e){super("ConnectionEstablishedEvent",e)}}class Ei extends oe{constructor(e,t,i){super("ConnectionClosedEvent",e,w.Debug),this.privReason=i,this.privStatusCode=t}get reason(){return this.privReason}get statusCode(){return this.privStatusCode}}class Ri extends oe{constructor(e,t,i){super("ConnectionErrorEvent",e,w.Debug),this.privMessage=t,this.privType=i}get message(){return this.privMessage}get type(){return this.privType}}class Pi extends oe{constructor(e,t,i){super("ConnectionEstablishErrorEvent",e,w.Error),this.privStatusCode=t,this.privReason=i}get reason(){return this.privReason}get statusCode(){return this.privStatusCode}}class st extends oe{constructor(e,t,i){super("ConnectionMessageReceivedEvent",e),this.privNetworkReceivedTime=t,this.privMessage=i}get networkReceivedTime(){return this.privNetworkReceivedTime}get message(){return this.privMessage}}class Ai extends oe{constructor(e,t,i){super("ConnectionMessageSentEvent",e),this.privNetworkSentTime=t,this.privMessage=i}get networkSentTime(){return this.privNetworkSentTime}get message(){return this.privMessage}}class I extends Error{constructor(e){super(e),this.name="ArgumentNull",this.message=e}}class q extends Error{constructor(e){super(e),this.name="InvalidOperation",this.message=e}}class ot extends Error{constructor(e,t){super(t),this.name=e+"ObjectDisposed",this.message=t}}var m;(function(r){r[r.Text=0]="Text",r[r.Binary=1]="Binary"})(m||(m={}));class at{constructor(e,t,i,n){if(this.privBody=null,e===m.Text&&t&&typeof t!="string")throw new q("Payload must be a string");if(e===m.Binary&&t&&!(t instanceof ArrayBuffer))throw new q("Payload must be ArrayBuffer");switch(this.privMessageType=e,this.privBody=t,this.privHeaders=i||{},this.privId=n||E(),this.messageType){case m.Binary:this.privSize=this.binaryBody!==null?this.binaryBody.byteLength:0;break;case m.Text:this.privSize=this.textBody.length}}get messageType(){return this.privMessageType}get headers(){return this.privHeaders}get body(){return this.privBody}get textBody(){if(this.privMessageType===m.Binary)throw new q("Not supported for binary message");return this.privBody}get binaryBody(){if(this.privMessageType===m.Text)throw new q("Not supported for text message");return this.privBody}get id(){return this.privId}}class ct{constructor(e,t){this.privStatusCode=e,this.privReason=t}get statusCode(){return this.privStatusCode}get reason(){return this.privReason}}class j{constructor(e){this.privEventListeners={},this.privIsDisposed=!1,this.privConsoleListener=void 0,this.privMetadata=e}onEvent(e){if(this.isDisposed())throw new ot("EventSource");if(this.metadata)for(const t in this.metadata)t&&e.metadata&&(e.metadata[t]||(e.metadata[t]=this.metadata[t]));for(const t in this.privEventListeners)t&&this.privEventListeners[t]&&this.privEventListeners[t](e)}attach(e){const t=E();return this.privEventListeners[t]=e,{detach:()=>(delete this.privEventListeners[t],Promise.resolve())}}attachListener(e){return this.attach(t=>e.onEvent(t))}attachConsoleListener(e){return this.privConsoleListener&&this.privConsoleListener.detach(),this.privConsoleListener=this.attach(t=>e.onEvent(t)),this.privConsoleListener}isDisposed(){return this.privIsDisposed}dispose(){this.privEventListeners=null,this.privIsDisposed=!0}get metadata(){return this.privMetadata}}class N{static setEventSource(e){if(!e)throw new I("eventSource");N.privInstance=e}static get instance(){return N.privInstance}}N.privInstance=new j;var M;(function(r){r[r.None=0]="None",r[r.Connected=1]="Connected",r[r.Connecting=2]="Connecting",r[r.Disconnected=3]="Disconnected"})(M||(M={}));class F{constructor(e){if(this.privSubscriptionIdCounter=0,this.privAddSubscriptions={},this.privRemoveSubscriptions={},this.privDisposedSubscriptions={},this.privDisposeReason=null,this.privList=[],e)for(const t of e)this.privList.push(t)}get(e){return this.throwIfDisposed(),this.privList[e]}first(){return this.get(0)}last(){return this.get(this.length()-1)}add(e){this.throwIfDisposed(),this.insertAt(this.privList.length,e)}insertAt(e,t){this.throwIfDisposed(),e===0?this.privList.unshift(t):e===this.privList.length?this.privList.push(t):this.privList.splice(e,0,t),this.triggerSubscriptions(this.privAddSubscriptions)}removeFirst(){return this.throwIfDisposed(),this.removeAt(0)}removeLast(){return this.throwIfDisposed(),this.removeAt(this.length()-1)}removeAt(e){return this.throwIfDisposed(),this.remove(e,1)[0]}remove(e,t){this.throwIfDisposed();const i=this.privList.splice(e,t);return this.triggerSubscriptions(this.privRemoveSubscriptions),i}clear(){this.throwIfDisposed(),this.remove(0,this.length())}length(){return this.throwIfDisposed(),this.privList.length}onAdded(e){this.throwIfDisposed();const t=this.privSubscriptionIdCounter++;return this.privAddSubscriptions[t]=e,{detach:()=>(delete this.privAddSubscriptions[t],Promise.resolve())}}onRemoved(e){this.throwIfDisposed();const t=this.privSubscriptionIdCounter++;return this.privRemoveSubscriptions[t]=e,{detach:()=>(delete this.privRemoveSubscriptions[t],Promise.resolve())}}onDisposed(e){this.throwIfDisposed();const t=this.privSubscriptionIdCounter++;return this.privDisposedSubscriptions[t]=e,{detach:()=>(delete this.privDisposedSubscriptions[t],Promise.resolve())}}join(e){return this.throwIfDisposed(),this.privList.join(e)}toArray(){const e=Array();return this.privList.forEach(t=>{e.push(t)}),e}any(e){return this.throwIfDisposed(),e?this.where(e).length()>0:this.length()>0}all(e){return this.throwIfDisposed(),this.where(e).length()===this.length()}forEach(e){this.throwIfDisposed();for(let t=0;t<this.length();t++)e(this.privList[t],t)}select(e){this.throwIfDisposed();const t=[];for(let i=0;i<this.privList.length;i++)t.push(e(this.privList[i],i));return new F(t)}where(e){this.throwIfDisposed();const t=new F;for(let i=0;i<this.privList.length;i++)e(this.privList[i],i)&&t.add(this.privList[i]);return t}orderBy(e){this.throwIfDisposed();const i=this.toArray().sort(e);return new F(i)}orderByDesc(e){return this.throwIfDisposed(),this.orderBy((t,i)=>e(i,t))}clone(){return this.throwIfDisposed(),new F(this.toArray())}concat(e){return this.throwIfDisposed(),new F(this.privList.concat(e.toArray()))}concatArray(e){return this.throwIfDisposed(),new F(this.privList.concat(e))}isDisposed(){return this.privList==null}dispose(e){this.isDisposed()||(this.privDisposeReason=e,this.privList=null,this.privAddSubscriptions=null,this.privRemoveSubscriptions=null,this.triggerSubscriptions(this.privDisposedSubscriptions))}throwIfDisposed(){if(this.isDisposed())throw new ot("List",this.privDisposeReason)}triggerSubscriptions(e){if(e)for(const t in e)t&&e[t]()}}var Nt;(function(r){r[r.None=0]="None",r[r.Resolved=1]="Resolved",r[r.Rejected=2]="Rejected"})(Nt||(Nt={}));class D{constructor(){this.resolve=e=>(this.privResolve(e),this),this.reject=e=>(this.privReject(e),this),this.privPromise=new Promise((e,t)=>{this.privResolve=e,this.privReject=t})}get promise(){return this.privPromise}}function J(r,e,t){r.then(i=>{try{e&&e(i)}catch(n){if(t)try{if(n instanceof Error){const s=n;t(s.name+": "+s.message)}else t(n)}catch{}}},i=>{if(t)try{if(i instanceof Error){const n=i;t(n.name+": "+n.message)}else t(i)}catch{}})}var zt=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})},Ce;(function(r){r[r.Dequeue=0]="Dequeue",r[r.Peek=1]="Peek"})(Ce||(Ce={}));class be{constructor(e){this.privPromiseStore=new F,this.privIsDrainInProgress=!1,this.privIsDisposing=!1,this.privDisposeReason=null,this.privList=e||new F,this.privDetachables=[],this.privSubscribers=new F,this.privDetachables.push(this.privList.onAdded(()=>this.drain()))}enqueue(e){this.throwIfDispose(),this.enqueueFromPromise(new Promise(t=>t(e)))}enqueueFromPromise(e){this.throwIfDispose(),e.then(t=>{this.privList.add(t)},()=>{})}dequeue(){this.throwIfDispose();const e=new D;return this.privSubscribers&&(this.privSubscribers.add({deferral:e,type:Ce.Dequeue}),this.drain()),e.promise}peek(){this.throwIfDispose();const e=new D;return this.privSubscribers&&(this.privSubscribers.add({deferral:e,type:Ce.Peek}),this.drain()),e.promise}length(){return this.throwIfDispose(),this.privList.length()}isDisposed(){return this.privSubscribers==null}drainAndDispose(e,t){return zt(this,void 0,void 0,function*(){if(!this.isDisposed()&&!this.privIsDisposing){this.privDisposeReason=t,this.privIsDisposing=!0;const i=this.privSubscribers;if(i){for(;i.length()>0;)i.removeFirst().deferral.resolve(void 0);this.privSubscribers===i&&(this.privSubscribers=i)}for(const n of this.privDetachables)yield n.detach();if(this.privPromiseStore.length()>0&&e){const n=[];return this.privPromiseStore.toArray().forEach(s=>{n.push(s)}),Promise.all(n).finally(()=>{this.privSubscribers=null,this.privList.forEach(s=>{e(s)}),this.privList=null}).then()}else this.privSubscribers=null,this.privList=null}})}dispose(e){return zt(this,void 0,void 0,function*(){yield this.drainAndDispose(null,e)})}drain(){if(!this.privIsDrainInProgress&&!this.privIsDisposing){this.privIsDrainInProgress=!0;const e=this.privSubscribers,t=this.privList;if(e&&t){for(;t.length()>0&&e.length()>0&&!this.privIsDisposing;){const i=e.removeFirst();if(i.type===Ce.Peek)i.deferral.resolve(t.first());else{const n=t.removeFirst();i.deferral.resolve(n)}}this.privSubscribers===e&&(this.privSubscribers=e),this.privList===t&&(this.privList=t)}this.privIsDrainInProgress=!1}}throwIfDispose(){if(this.isDisposed())throw this.privDisposeReason?new q(this.privDisposeReason):new ot("Queue");if(this.privIsDisposing)throw new q("Queue disposing")}}class Le{constructor(e,t,i){if(this.privPayload=null,!t)throw new I("payload");if(e===m.Binary&&t.__proto__.constructor.name!=="ArrayBuffer")throw new q("Payload must be ArrayBuffer");if(e===m.Text&&typeof t!="string")throw new q("Payload must be a string");this.privMessageType=e,this.privPayload=t,this.privId=i||E()}get messageType(){return this.privMessageType}get payload(){return this.privPayload}get textContent(){if(this.privMessageType===m.Binary)throw new q("Not supported for binary message");return this.privPayload}get binaryContent(){if(this.privMessageType===m.Text)throw new q("Not supported for text message");return this.privPayload}get id(){return this.privId}}class Ii{constructor(e,t){this.privActualSampleRate=e,this.privDesiredSampleRate=t}encode(e){const t=this.downSampleAudioFrame(e,this.privActualSampleRate,this.privDesiredSampleRate);if(!t)return null;const i=t.length*2,n=new ArrayBuffer(i),s=new DataView(n);return this.floatTo16BitPCM(s,0,t),n}setString(e,t,i){for(let n=0;n<i.length;n++)e.setUint8(t+n,i.charCodeAt(n))}floatTo16BitPCM(e,t,i){for(let n=0;n<i.length;n++,t+=2){const s=Math.max(-1,Math.min(1,i[n]));e.setInt16(t,s<0?s*32768:s*32767,!0)}}downSampleAudioFrame(e,t,i){if(!e)return null;if(i===t||i>t)return e;const n=t/i,s=Math.round(e.length/n),o=new Float32Array(s);let a=0,u=0;for(;u<s;){const h=Math.round((u+1)*n);let c=0,d=0;for(;a<h&&a<e.length;)c+=e[a++],d++;o[u++]=c/d}return o}}var Mi=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};class Lt{constructor(e){this.privIsWriteEnded=!1,this.privIsReadEnded=!1,this.privId=e||E(),this.privReaderQueue=new be}get isClosed(){return this.privIsWriteEnded}get isReadEnded(){return this.privIsReadEnded}get id(){return this.privId}close(){this.privIsWriteEnded||(this.writeStreamChunk({buffer:null,isEnd:!0,timeReceived:Date.now()}),this.privIsWriteEnded=!0)}writeStreamChunk(e){if(this.throwIfClosed(),!this.privReaderQueue.isDisposed())try{this.privReaderQueue.enqueue(e)}catch{}}read(){if(this.privIsReadEnded)throw new q("Stream read has already finished");return this.privReaderQueue.dequeue().then(e=>Mi(this,void 0,void 0,function*(){return(e===void 0||e.isEnd)&&(yield this.privReaderQueue.dispose("End of stream reached")),e}))}readEnded(){this.privIsReadEnded||(this.privIsReadEnded=!0,this.privReaderQueue=new be)}throwIfClosed(){if(this.privIsWriteEnded)throw new q("Stream closed")}}var Te;(function(r){r[r.Success=0]="Success",r[r.Error=1]="Error"})(Te||(Te={}));class ht extends Lt{constructor(e,t){super(t),this.privTargetChunkSize=e,this.privNextBufferReadyBytes=0}writeStreamChunk(e){if(e.isEnd||this.privNextBufferReadyBytes===0&&e.buffer.byteLength===this.privTargetChunkSize){super.writeStreamChunk(e);return}let t=0;for(;t<e.buffer.byteLength;){this.privNextBufferToWrite===void 0&&(this.privNextBufferToWrite=new ArrayBuffer(this.privTargetChunkSize),this.privNextBufferStartTime=e.timeReceived);const i=Math.min(e.buffer.byteLength-t,this.privTargetChunkSize-this.privNextBufferReadyBytes),n=new Uint8Array(this.privNextBufferToWrite),s=new Uint8Array(e.buffer.slice(t,i+t));n.set(s,this.privNextBufferReadyBytes),this.privNextBufferReadyBytes+=i,t+=i,this.privNextBufferReadyBytes===this.privTargetChunkSize&&(super.writeStreamChunk({buffer:this.privNextBufferToWrite,isEnd:!1,timeReceived:this.privNextBufferStartTime}),this.privNextBufferReadyBytes=0,this.privNextBufferToWrite=void 0)}}close(){this.privNextBufferReadyBytes!==0&&!this.isClosed&&super.writeStreamChunk({buffer:this.privNextBufferToWrite.slice(0,this.privNextBufferReadyBytes),isEnd:!1,timeReceived:this.privNextBufferStartTime}),super.close()}}class z{static load(e){const t=new Map([[0,()=>{}]]),i=new Map,n=new Worker(e);return n.addEventListener("message",({data:a})=>{if(z.isCallNotification(a)){const{params:{timerId:u}}=a,h=t.get(u);if(typeof h=="number"){const c=i.get(h);if(c===void 0||c!==u)throw new Error("The timer is in an undefined state.")}else if(typeof h!="undefined")h(),t.delete(u);else throw new Error("The timer is in an undefined state.")}else if(z.isClearResponse(a)){const{id:u}=a,h=i.get(u);if(h===void 0)throw new Error("The timer is in an undefined state.");i.delete(u),t.delete(h)}else{const{error:{message:u}}=a;throw new Error(u)}}),{clearTimeout:a=>{const u=Math.random();i.set(u,a),t.set(a,u),n.postMessage({id:u,method:"clear",params:{timerId:a}})},setTimeout:(a,u)=>{const h=Math.random();return t.set(h,a),n.postMessage({id:null,method:"set",params:{delay:u,now:performance.now(),timerId:h}}),h}}}static loadWorkerTimers(){const e=`!function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=14)}([function(e,t,n){"use strict";n.d(t,"a",(function(){return i})),n.d(t,"b",(function(){return u})),n.d(t,"c",(function(){return a})),n.d(t,"d",(function(){return d}));const r=new Map,o=new Map,i=e=>{const t=r.get(e);if(void 0===t)throw new Error('There is no interval scheduled with the given id "'.concat(e,'".'));clearTimeout(t),r.delete(e)},u=e=>{const t=o.get(e);if(void 0===t)throw new Error('There is no timeout scheduled with the given id "'.concat(e,'".'));clearTimeout(t),o.delete(e)},f=(e,t)=>{let n,r;if("performance"in self){const o=performance.now();n=o,r=e-Math.max(0,o-t)}else n=Date.now(),r=e;return{expected:n+r,remainingDelay:r}},c=(e,t,n,r)=>{const o="performance"in self?performance.now():Date.now();o>n?postMessage({id:null,method:"call",params:{timerId:t}}):e.set(t,setTimeout(c,n-o,e,t,n))},a=(e,t,n)=>{const{expected:o,remainingDelay:i}=f(e,n);r.set(t,setTimeout(c,i,r,t,o))},d=(e,t,n)=>{const{expected:r,remainingDelay:i}=f(e,n);o.set(t,setTimeout(c,i,o,t,r))}},function(e,t,n){"use strict";n.r(t);var r=n(2);for(var o in r)"default"!==o&&function(e){n.d(t,e,(function(){return r[e]}))}(o);var i=n(3);for(var o in i)"default"!==o&&function(e){n.d(t,e,(function(){return i[e]}))}(o);var u=n(4);for(var o in u)"default"!==o&&function(e){n.d(t,e,(function(){return u[e]}))}(o);var f=n(5);for(var o in f)"default"!==o&&function(e){n.d(t,e,(function(){return f[e]}))}(o);var c=n(6);for(var o in c)"default"!==o&&function(e){n.d(t,e,(function(){return c[e]}))}(o);var a=n(7);for(var o in a)"default"!==o&&function(e){n.d(t,e,(function(){return a[e]}))}(o);var d=n(8);for(var o in d)"default"!==o&&function(e){n.d(t,e,(function(){return d[e]}))}(o);var s=n(9);for(var o in s)"default"!==o&&function(e){n.d(t,e,(function(){return s[e]}))}(o)},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t,n){"use strict";n.r(t);var r=n(11);for(var o in r)"default"!==o&&function(e){n.d(t,e,(function(){return r[e]}))}(o);var i=n(12);for(var o in i)"default"!==o&&function(e){n.d(t,e,(function(){return i[e]}))}(o);var u=n(13);for(var o in u)"default"!==o&&function(e){n.d(t,e,(function(){return u[e]}))}(o)},function(e,t){},function(e,t){},function(e,t){},function(e,t,n){"use strict";var Lr=Object.defineProperty;var Br=(H,L,V)=>L in H?Lr(H,L,{enumerable:!0,configurable:!0,writable:!0,value:V}):H[L]=V;var y=(H,L,V)=>(Br(H,typeof L!="symbol"?L+"":L,V),V);n.r(t);var r=n(0),o=n(1);for(var i in o)"default"!==i&&function(e){n.d(t,e,(function(){return o[e]}))}(i);var u=n(10);for(var i in u)"default"!==i&&function(e){n.d(t,e,(function(){return u[e]}))}(i);addEventListener("message",({data:e})=>{try{if("clear"===e.method){const{id:t,params:{timerId:n}}=e;Object(r.b)(n),postMessage({error:null,id:t})}else{if("set"!==e.method)throw new Error('The given method "'.concat(e.method,'" is not supported'));{const{params:{delay:t,now:n,timerId:o}}=e;Object(r.d)(t,o,n)}}}catch(t){postMessage({error:{message:t.message},id:e.id,result:null})}})}]);`;return()=>{if(z.workerTimers!==null)return z.workerTimers;const t=new Blob([e],{type:"application/javascript; charset=utf-8"}),i=URL.createObjectURL(t);return z.workerTimers=z.load(i),z.workerTimers.setTimeout(()=>URL.revokeObjectURL(i),0),z.workerTimers}}static isCallNotification(e){return e.method!==void 0&&e.method==="call"}static isClearResponse(e){return e.error===null&&typeof e.id=="number"}}z.workerTimers=null,z.clearTimeout=r=>z.timers().clearTimeout(r),z.setTimeout=(r,e)=>z.timers().setTimeout(r,e),z.timers=z.loadWorkerTimers();class B extends se{constructor(e,t,i){super(e,t),this.privSignature=i}}class Di extends B{constructor(e){super("OCSPMemoryCacheHitEvent",w.Debug,e)}}class ki extends B{constructor(e){super("OCSPCacheMissEvent",w.Debug,e)}}class xi extends B{constructor(e){super("OCSPDiskCacheHitEvent",w.Debug,e)}}class Ni extends B{constructor(e){super("OCSPCacheUpdateNeededEvent",w.Debug,e)}}class zi extends B{constructor(e){super("OCSPMemoryCacheStoreEvent",w.Debug,e)}}class Li extends B{constructor(e){super("OCSPDiskCacheStoreEvent",w.Debug,e)}}class Bi extends B{constructor(e){super("OCSPCacheUpdateCompleteEvent",w.Debug,e)}}class Oi extends B{constructor(){super("OCSPStapleReceivedEvent",w.Debug,"")}}class _i extends B{constructor(e,t){super("OCSPCacheEntryExpiredEvent",w.Debug,e),this.privExpireTime=t}}class Hi extends B{constructor(e,t,i){super("OCSPCacheEntryNeedsRefreshEvent",w.Debug,e),this.privExpireTime=i,this.privStartTime=t}}class Ki extends B{constructor(e,t,i){super("OCSPCacheHitEvent",w.Debug,e),this.privExpireTime=i,this.privExpireTimeString=new Date(i).toLocaleDateString(),this.privStartTime=t,this.privStartTimeString=new Date(t).toLocaleTimeString()}}class qi extends B{constructor(e,t){super("OCSPVerificationFailedEvent",w.Debug,e),this.privError=t}}class Bt extends B{constructor(e,t){super("OCSPCacheFetchErrorEvent",w.Debug,e),this.privError=t}}class Ui extends B{constructor(e){super("OCSPResponseRetrievedEvent",w.Debug,e)}}class Wi extends B{constructor(e,t){super("OCSPCacheUpdateErrorEvent",w.Debug,e),this.privError=t}}class Ee extends se{constructor(e){super("BackgroundEvent",w.Error),this.privError=e}get error(){return this.privError}}class l{static throwIfNullOrUndefined(e,t){if(e==null)throw new Error("throwIfNullOrUndefined:"+t)}static throwIfNull(e,t){if(e===null)throw new Error("throwIfNull:"+t)}static throwIfNullOrWhitespace(e,t){if(l.throwIfNullOrUndefined(e,t),(""+e).trim().length<1)throw new Error("throwIfNullOrWhitespace:"+t)}static throwIfDisposed(e){if(e)throw new Error("the object is already disposed")}static throwIfArrayEmptyOrWhitespace(e,t){if(l.throwIfNullOrUndefined(e,t),e.length===0)throw new Error("throwIfArrayEmptyOrWhitespace:"+t);for(const i of e)l.throwIfNullOrWhitespace(i,t)}static throwIfFileDoesNotExist(e,t){l.throwIfNullOrWhitespace(e,t)}static throwIfNotUndefined(e,t){if(e!==void 0)throw new Error("throwIfNotUndefined:"+t)}}class T{}T.AuthKey="Ocp-Apim-Subscription-Key",T.ConnectionId="X-ConnectionId",T.ContentType="Content-Type",T.CustomCommandsAppId="X-CommandsAppId",T.Path="Path",T.RequestId="X-RequestId",T.RequestStreamId="X-StreamId",T.RequestTimestamp="X-Timestamp";class ut{constructor(e,t){this.privHeaderName=e,this.privToken=t}get headerName(){return this.privHeaderName}get token(){return this.privToken}}class Ot{constructor(e){if(!e)throw new I("subscriptionKey");this.privAuthInfo=new ut(T.AuthKey,e)}fetch(e){return Promise.resolve(this.privAuthInfo)}fetchOnExpiry(e){return Promise.resolve(this.privAuthInfo)}}const _t="Authorization";class ue{constructor(e,t){if(!e)throw new I("fetchCallback");if(!t)throw new I("fetchOnExpiryCallback");this.privFetchCallback=e,this.privFetchOnExpiryCallback=t}fetch(e){return this.privFetchCallback(e).then(t=>new ut(_t,ue.privTokenPrefix+t))}fetchOnExpiry(e){return this.privFetchOnExpiryCallback(e).then(t=>new ut(_t,ue.privTokenPrefix+t))}}ue.privTokenPrefix="bearer ";class Ht{constructor(e){l.throwIfNullOrUndefined(void 0,`
2
- File System access not available, please use Push or PullAudioOutputStream`),this.privFd=(void 0)(e,"w")}set format(e){l.throwIfNotUndefined(this.privAudioFormat,"format is already set"),this.privAudioFormat=e;let t=0;this.privAudioFormat.hasHeader&&(t=this.privAudioFormat.header.byteLength),this.privFd!==void 0&&(this.privWriteStream=(void 0)("",{fd:this.privFd,start:t,autoClose:!1}))}write(e){l.throwIfNullOrUndefined(this.privAudioFormat,"must set format before writing."),this.privWriteStream!==void 0&&this.privWriteStream.write(new Uint8Array(e.slice(0)))}close(){this.privFd!==void 0&&(this.privWriteStream.on("finish",()=>{this.privAudioFormat.hasHeader&&(this.privAudioFormat.updateHeader(this.privWriteStream.bytesWritten),(void 0)(this.privFd,new Int8Array(this.privAudioFormat.header),0,this.privAudioFormat.header.byteLength,0)),(void 0)(this.privFd),this.privFd=void 0}),this.privWriteStream.end())}id(){return this.privId}}var v;(function(r){r[r.PCM=1]="PCM",r[r.MuLaw=2]="MuLaw",r[r.Siren=3]="Siren",r[r.MP3=4]="MP3",r[r.SILKSkype=5]="SILKSkype",r[r.OGG_OPUS=6]="OGG_OPUS",r[r.WEBM_OPUS=7]="WEBM_OPUS",r[r.ALaw=8]="ALaw",r[r.FLAC=9]="FLAC",r[r.OPUS=10]="OPUS"})(v||(v={}));class Be{static getDefaultInputFormat(){return Y.getDefaultInputFormat()}static getWaveFormat(e,t,i,n){return new Y(e,t,i,n)}static getWaveFormatPCM(e,t,i){return new Y(e,t,i)}}class Y extends Be{constructor(e=16e3,t=16,i=1,n=v.PCM){super();let s=!0;switch(n){case v.PCM:this.formatTag=1;break;case v.ALaw:this.formatTag=6;break;case v.MuLaw:this.formatTag=7;break;default:s=!1}if(this.bitsPerSample=t,this.samplesPerSec=e,this.channels=i,this.avgBytesPerSec=this.samplesPerSec*this.channels*(this.bitsPerSample/8),this.blockAlign=this.channels*Math.max(this.bitsPerSample,8),s){this.privHeader=new ArrayBuffer(44);const o=new DataView(this.privHeader);this.setString(o,0,"RIFF"),o.setUint32(4,0,!0),this.setString(o,8,"WAVEfmt "),o.setUint32(16,16,!0),o.setUint16(20,this.formatTag,!0),o.setUint16(22,this.channels,!0),o.setUint32(24,this.samplesPerSec,!0),o.setUint32(28,this.avgBytesPerSec,!0),o.setUint16(32,this.channels*(this.bitsPerSample/8),!0),o.setUint16(34,this.bitsPerSample,!0),this.setString(o,36,"data"),o.setUint32(40,0,!0)}}static getDefaultInputFormat(){return new Y}static getAudioContext(e){const t=window.AudioContext||window.webkitAudioContext||!1;if(t)return e!==void 0&&navigator.mediaDevices.getSupportedConstraints().sampleRate?new t({sampleRate:e}):new t;throw new Error("Browser does not support Web Audio API (AudioContext is not available).")}close(){}get header(){return this.privHeader}setString(e,t,i){for(let n=0;n<i.length;n++)e.setUint8(t+n,i.charCodeAt(n))}}var pt=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};class dt{constructor(){}static createPushStream(e){return Kt.create(e)}static createPullStream(e,t){return qt.create(e,t)}}class Kt extends dt{static create(e){return new Vi(e)}}class Vi extends Kt{constructor(e){super(),e===void 0?this.privFormat=Y.getDefaultInputFormat():this.privFormat=e,this.privEvents=new j,this.privId=E(),this.privStream=new ht(this.privFormat.avgBytesPerSec/10)}get format(){return Promise.resolve(this.privFormat)}write(e){this.privStream.writeStreamChunk({buffer:e,isEnd:!1,timeReceived:Date.now()})}close(){this.privStream.close()}id(){return this.privId}get blob(){return this.attach("id").then(e=>{const t=[];let i=Buffer.from("");const n=()=>e.read().then(s=>!s||s.isEnd?typeof XMLHttpRequest!="undefined"&&typeof Blob!="undefined"?Promise.resolve(new Blob(t)):Promise.resolve(Buffer.from(i)):(typeof Blob!="undefined"?t.push(s.buffer):i=Buffer.concat([i,this.toBuffer(s.buffer)]),n()));return n()})}turnOn(){this.onEvent(new xe(this.privId)),this.onEvent(new me(this.privId))}attach(e){return pt(this,void 0,void 0,function*(){this.onEvent(new ye(this.privId,e)),yield this.turnOn();const t=this.privStream;return this.onEvent(new we(this.privId,e)),{detach:()=>pt(this,void 0,void 0,function*(){return this.onEvent(new G(this.privId,e)),this.turnOff()}),id:()=>e,read:()=>t.read()}})}detach(e){this.onEvent(new G(this.privId,e))}turnOff(){}get events(){return this.privEvents}get deviceInfo(){return Promise.resolve({bitspersample:this.privFormat.bitsPerSample,channelcount:this.privFormat.channels,connectivity:fe.Unknown,manufacturer:"Speech SDK",model:"PushStream",samplerate:this.privFormat.samplesPerSec,type:ce.Stream})}onEvent(e){this.privEvents.onEvent(e),N.instance.onEvent(e)}toBuffer(e){const t=Buffer.alloc(e.byteLength),i=new Uint8Array(e);for(let n=0;n<t.length;++n)t[n]=i[n];return t}}class qt extends dt{constructor(){super()}static create(e,t){return new Ut(e,t)}}class Ut extends qt{constructor(e,t){super(),t===void 0?this.privFormat=Be.getDefaultInputFormat():this.privFormat=t,this.privEvents=new j,this.privId=E(),this.privCallback=e,this.privIsClosed=!1,this.privBufferSize=this.privFormat.avgBytesPerSec/10}get format(){return Promise.resolve(this.privFormat)}close(){this.privIsClosed=!0,this.privCallback.close()}id(){return this.privId}get blob(){return Promise.reject("Not implemented")}turnOn(){this.onEvent(new xe(this.privId)),this.onEvent(new me(this.privId))}attach(e){return pt(this,void 0,void 0,function*(){return this.onEvent(new ye(this.privId,e)),yield this.turnOn(),this.onEvent(new we(this.privId,e)),{detach:()=>(this.privCallback.close(),this.onEvent(new G(this.privId,e)),this.turnOff()),id:()=>e,read:()=>{let t=0,i;for(;t<this.privBufferSize;){const n=new ArrayBuffer(this.privBufferSize-t),s=this.privCallback.read(n);if(i===void 0?i=n:new Int8Array(i).set(new Int8Array(n),t),s===0)break;t+=s}return Promise.resolve({buffer:i.slice(0,t),isEnd:this.privIsClosed||t===0,timeReceived:Date.now()})}}})}detach(e){this.onEvent(new G(this.privId,e))}turnOff(){}get events(){return this.privEvents}get deviceInfo(){return Promise.resolve({bitspersample:this.privFormat.bitsPerSample,channelcount:this.privFormat.channels,connectivity:fe.Unknown,manufacturer:"Speech SDK",model:"PullStream",samplerate:this.privFormat.samplesPerSec,type:ce.Stream})}onEvent(e){this.privEvents.onEvent(e),N.instance.onEvent(e)}}var g;(function(r){r[r.Raw8Khz8BitMonoMULaw=0]="Raw8Khz8BitMonoMULaw",r[r.Riff16Khz16KbpsMonoSiren=1]="Riff16Khz16KbpsMonoSiren",r[r.Audio16Khz16KbpsMonoSiren=2]="Audio16Khz16KbpsMonoSiren",r[r.Audio16Khz32KBitRateMonoMp3=3]="Audio16Khz32KBitRateMonoMp3",r[r.Audio16Khz128KBitRateMonoMp3=4]="Audio16Khz128KBitRateMonoMp3",r[r.Audio16Khz64KBitRateMonoMp3=5]="Audio16Khz64KBitRateMonoMp3",r[r.Audio24Khz48KBitRateMonoMp3=6]="Audio24Khz48KBitRateMonoMp3",r[r.Audio24Khz96KBitRateMonoMp3=7]="Audio24Khz96KBitRateMonoMp3",r[r.Audio24Khz160KBitRateMonoMp3=8]="Audio24Khz160KBitRateMonoMp3",r[r.Raw16Khz16BitMonoTrueSilk=9]="Raw16Khz16BitMonoTrueSilk",r[r.Riff16Khz16BitMonoPcm=10]="Riff16Khz16BitMonoPcm",r[r.Riff8Khz16BitMonoPcm=11]="Riff8Khz16BitMonoPcm",r[r.Riff24Khz16BitMonoPcm=12]="Riff24Khz16BitMonoPcm",r[r.Riff8Khz8BitMonoMULaw=13]="Riff8Khz8BitMonoMULaw",r[r.Raw16Khz16BitMonoPcm=14]="Raw16Khz16BitMonoPcm",r[r.Raw24Khz16BitMonoPcm=15]="Raw24Khz16BitMonoPcm",r[r.Raw8Khz16BitMonoPcm=16]="Raw8Khz16BitMonoPcm",r[r.Ogg16Khz16BitMonoOpus=17]="Ogg16Khz16BitMonoOpus",r[r.Ogg24Khz16BitMonoOpus=18]="Ogg24Khz16BitMonoOpus",r[r.Raw48Khz16BitMonoPcm=19]="Raw48Khz16BitMonoPcm",r[r.Riff48Khz16BitMonoPcm=20]="Riff48Khz16BitMonoPcm",r[r.Audio48Khz96KBitRateMonoMp3=21]="Audio48Khz96KBitRateMonoMp3",r[r.Audio48Khz192KBitRateMonoMp3=22]="Audio48Khz192KBitRateMonoMp3",r[r.Ogg48Khz16BitMonoOpus=23]="Ogg48Khz16BitMonoOpus",r[r.Webm16Khz16BitMonoOpus=24]="Webm16Khz16BitMonoOpus",r[r.Webm24Khz16BitMonoOpus=25]="Webm24Khz16BitMonoOpus",r[r.Raw24Khz16BitMonoTrueSilk=26]="Raw24Khz16BitMonoTrueSilk",r[r.Raw8Khz8BitMonoALaw=27]="Raw8Khz8BitMonoALaw",r[r.Riff8Khz8BitMonoALaw=28]="Riff8Khz8BitMonoALaw",r[r.Webm24Khz16Bit24KbpsMonoOpus=29]="Webm24Khz16Bit24KbpsMonoOpus",r[r.Audio16Khz16Bit32KbpsMonoOpus=30]="Audio16Khz16Bit32KbpsMonoOpus",r[r.Audio24Khz16Bit48KbpsMonoOpus=31]="Audio24Khz16Bit48KbpsMonoOpus",r[r.Audio24Khz16Bit24KbpsMonoOpus=32]="Audio24Khz16Bit24KbpsMonoOpus",r[r.Raw22050Hz16BitMonoPcm=33]="Raw22050Hz16BitMonoPcm",r[r.Riff22050Hz16BitMonoPcm=34]="Riff22050Hz16BitMonoPcm",r[r.Raw44100Hz16BitMonoPcm=35]="Raw44100Hz16BitMonoPcm",r[r.Riff44100Hz16BitMonoPcm=36]="Riff44100Hz16BitMonoPcm"})(g||(g={}));class f extends Y{constructor(e,t,i,n,s,o,a,u,h){super(i,o,t,e),this.formatTag=e,this.avgBytesPerSec=n,this.blockAlign=s,this.priAudioFormatString=a,this.priRequestAudioFormatString=u,this.priHasHeader=h}static fromSpeechSynthesisOutputFormat(e){return e===void 0?f.getDefaultOutputFormat():f.fromSpeechSynthesisOutputFormatString(f.SpeechSynthesisOutputFormatToString[e])}static fromSpeechSynthesisOutputFormatString(e){switch(e){case"raw-8khz-8bit-mono-mulaw":return new f(v.MuLaw,1,8e3,8e3,1,8,e,e,!1);case"riff-16khz-16kbps-mono-siren":return new f(v.Siren,1,16e3,2e3,40,0,e,"audio-16khz-16kbps-mono-siren",!0);case"audio-16khz-16kbps-mono-siren":return new f(v.Siren,1,16e3,2e3,40,0,e,e,!1);case"audio-16khz-32kbitrate-mono-mp3":return new f(v.MP3,1,16e3,32<<7,2,16,e,e,!1);case"audio-16khz-128kbitrate-mono-mp3":return new f(v.MP3,1,16e3,128<<7,2,16,e,e,!1);case"audio-16khz-64kbitrate-mono-mp3":return new f(v.MP3,1,16e3,64<<7,2,16,e,e,!1);case"audio-24khz-48kbitrate-mono-mp3":return new f(v.MP3,1,24e3,48<<7,2,16,e,e,!1);case"audio-24khz-96kbitrate-mono-mp3":return new f(v.MP3,1,24e3,96<<7,2,16,e,e,!1);case"audio-24khz-160kbitrate-mono-mp3":return new f(v.MP3,1,24e3,160<<7,2,16,e,e,!1);case"raw-16khz-16bit-mono-truesilk":return new f(v.SILKSkype,1,16e3,32e3,2,16,e,e,!1);case"riff-8khz-16bit-mono-pcm":return new f(v.PCM,1,8e3,16e3,2,16,e,"raw-8khz-16bit-mono-pcm",!0);case"riff-24khz-16bit-mono-pcm":return new f(v.PCM,1,24e3,48e3,2,16,e,"raw-24khz-16bit-mono-pcm",!0);case"riff-8khz-8bit-mono-mulaw":return new f(v.MuLaw,1,8e3,8e3,1,8,e,"raw-8khz-8bit-mono-mulaw",!0);case"raw-16khz-16bit-mono-pcm":return new f(v.PCM,1,16e3,32e3,2,16,e,"raw-16khz-16bit-mono-pcm",!1);case"raw-24khz-16bit-mono-pcm":return new f(v.PCM,1,24e3,48e3,2,16,e,"raw-24khz-16bit-mono-pcm",!1);case"raw-8khz-16bit-mono-pcm":return new f(v.PCM,1,8e3,16e3,2,16,e,"raw-8khz-16bit-mono-pcm",!1);case"ogg-16khz-16bit-mono-opus":return new f(v.OGG_OPUS,1,16e3,8192,2,16,e,e,!1);case"ogg-24khz-16bit-mono-opus":return new f(v.OGG_OPUS,1,24e3,8192,2,16,e,e,!1);case"raw-48khz-16bit-mono-pcm":return new f(v.PCM,1,48e3,96e3,2,16,e,"raw-48khz-16bit-mono-pcm",!1);case"riff-48khz-16bit-mono-pcm":return new f(v.PCM,1,48e3,96e3,2,16,e,"raw-48khz-16bit-mono-pcm",!0);case"audio-48khz-96kbitrate-mono-mp3":return new f(v.MP3,1,48e3,96<<7,2,16,e,e,!1);case"audio-48khz-192kbitrate-mono-mp3":return new f(v.MP3,1,48e3,192<<7,2,16,e,e,!1);case"ogg-48khz-16bit-mono-opus":return new f(v.OGG_OPUS,1,48e3,12e3,2,16,e,e,!1);case"webm-16khz-16bit-mono-opus":return new f(v.WEBM_OPUS,1,16e3,4e3,2,16,e,e,!1);case"webm-24khz-16bit-mono-opus":return new f(v.WEBM_OPUS,1,24e3,6e3,2,16,e,e,!1);case"webm-24khz-16bit-24kbps-mono-opus":return new f(v.WEBM_OPUS,1,24e3,3e3,2,16,e,e,!1);case"audio-16khz-16bit-32kbps-mono-opus":return new f(v.OPUS,1,16e3,4e3,2,16,e,e,!1);case"audio-24khz-16bit-48kbps-mono-opus":return new f(v.OPUS,1,24e3,6e3,2,16,e,e,!1);case"audio-24khz-16bit-24kbps-mono-opus":return new f(v.OPUS,1,24e3,3e3,2,16,e,e,!1);case"audio-24khz-16bit-mono-flac":return new f(v.FLAC,1,24e3,24e3,2,16,e,e,!1);case"audio-48khz-16bit-mono-flac":return new f(v.FLAC,1,48e3,3e4,2,16,e,e,!1);case"raw-24khz-16bit-mono-truesilk":return new f(v.SILKSkype,1,24e3,48e3,2,16,e,e,!1);case"raw-8khz-8bit-mono-alaw":return new f(v.ALaw,1,8e3,8e3,1,8,e,e,!1);case"riff-8khz-8bit-mono-alaw":return new f(v.ALaw,1,8e3,8e3,1,8,e,"raw-8khz-8bit-mono-alaw",!0);case"raw-22050hz-16bit-mono-pcm":return new f(v.PCM,1,22050,44100,2,16,e,e,!1);case"riff-22050hz-16bit-mono-pcm":return new f(v.PCM,1,22050,44100,2,16,e,"raw-22050hz-16bit-mono-pcm",!0);case"raw-44100hz-16bit-mono-pcm":return new f(v.PCM,1,44100,88200,2,16,e,e,!1);case"riff-44100hz-16bit-mono-pcm":return new f(v.PCM,1,44100,88200,2,16,e,"raw-44100hz-16bit-mono-pcm",!0);case"riff-16khz-16bit-mono-pcm":default:return new f(v.PCM,1,16e3,32e3,2,16,"riff-16khz-16bit-mono-pcm","raw-16khz-16bit-mono-pcm",!0)}}static getDefaultOutputFormat(){return f.fromSpeechSynthesisOutputFormatString(typeof window!="undefined"?"audio-24khz-48kbitrate-mono-mp3":"riff-16khz-16bit-mono-pcm")}get hasHeader(){return this.priHasHeader}get header(){if(this.hasHeader)return this.privHeader}updateHeader(e){if(this.priHasHeader){const t=new DataView(this.privHeader);t.setUint32(4,e+this.privHeader.byteLength-8,!0),t.setUint32(40,e,!0)}}get requestAudioFormatString(){return this.priRequestAudioFormatString}}f.SpeechSynthesisOutputFormatToString={[g.Raw8Khz8BitMonoMULaw]:"raw-8khz-8bit-mono-mulaw",[g.Riff16Khz16KbpsMonoSiren]:"riff-16khz-16kbps-mono-siren",[g.Audio16Khz16KbpsMonoSiren]:"audio-16khz-16kbps-mono-siren",[g.Audio16Khz32KBitRateMonoMp3]:"audio-16khz-32kbitrate-mono-mp3",[g.Audio16Khz128KBitRateMonoMp3]:"audio-16khz-128kbitrate-mono-mp3",[g.Audio16Khz64KBitRateMonoMp3]:"audio-16khz-64kbitrate-mono-mp3",[g.Audio24Khz48KBitRateMonoMp3]:"audio-24khz-48kbitrate-mono-mp3",[g.Audio24Khz96KBitRateMonoMp3]:"audio-24khz-96kbitrate-mono-mp3",[g.Audio24Khz160KBitRateMonoMp3]:"audio-24khz-160kbitrate-mono-mp3",[g.Raw16Khz16BitMonoTrueSilk]:"raw-16khz-16bit-mono-truesilk",[g.Riff16Khz16BitMonoPcm]:"riff-16khz-16bit-mono-pcm",[g.Riff8Khz16BitMonoPcm]:"riff-8khz-16bit-mono-pcm",[g.Riff24Khz16BitMonoPcm]:"riff-24khz-16bit-mono-pcm",[g.Riff8Khz8BitMonoMULaw]:"riff-8khz-8bit-mono-mulaw",[g.Raw16Khz16BitMonoPcm]:"raw-16khz-16bit-mono-pcm",[g.Raw24Khz16BitMonoPcm]:"raw-24khz-16bit-mono-pcm",[g.Raw8Khz16BitMonoPcm]:"raw-8khz-16bit-mono-pcm",[g.Ogg16Khz16BitMonoOpus]:"ogg-16khz-16bit-mono-opus",[g.Ogg24Khz16BitMonoOpus]:"ogg-24khz-16bit-mono-opus",[g.Raw48Khz16BitMonoPcm]:"raw-48khz-16bit-mono-pcm",[g.Riff48Khz16BitMonoPcm]:"riff-48khz-16bit-mono-pcm",[g.Audio48Khz96KBitRateMonoMp3]:"audio-48khz-96kbitrate-mono-mp3",[g.Audio48Khz192KBitRateMonoMp3]:"audio-48khz-192kbitrate-mono-mp3",[g.Ogg48Khz16BitMonoOpus]:"ogg-48khz-16bit-mono-opus",[g.Webm16Khz16BitMonoOpus]:"webm-16khz-16bit-mono-opus",[g.Webm24Khz16BitMonoOpus]:"webm-24khz-16bit-mono-opus",[g.Webm24Khz16Bit24KbpsMonoOpus]:"webm-24khz-16bit-24kbps-mono-opus",[g.Raw24Khz16BitMonoTrueSilk]:"raw-24khz-16bit-mono-truesilk",[g.Raw8Khz8BitMonoALaw]:"raw-8khz-8bit-mono-alaw",[g.Riff8Khz8BitMonoALaw]:"riff-8khz-8bit-mono-alaw",[g.Audio16Khz16Bit32KbpsMonoOpus]:"audio-16khz-16bit-32kbps-mono-opus",[g.Audio24Khz16Bit48KbpsMonoOpus]:"audio-24khz-16bit-48kbps-mono-opus",[g.Audio24Khz16Bit24KbpsMonoOpus]:"audio-24khz-16bit-24kbps-mono-opus",[g.Raw22050Hz16BitMonoPcm]:"raw-22050hz-16bit-mono-pcm",[g.Riff22050Hz16BitMonoPcm]:"riff-22050hz-16bit-mono-pcm",[g.Raw44100Hz16BitMonoPcm]:"raw-44100hz-16bit-mono-pcm",[g.Riff44100Hz16BitMonoPcm]:"riff-44100hz-16bit-mono-pcm"};var ji=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};class Wt{constructor(){}static createPullStream(){return Oe.create()}}class Oe extends Wt{static create(){return new vt}}class vt extends Oe{constructor(){super(),this.privId=E(),this.privStream=new Lt}set format(e){e==null&&(this.privFormat=f.getDefaultOutputFormat()),this.privFormat=e}get format(){return this.privFormat}get isClosed(){return this.privStream.isClosed}id(){return this.privId}read(e){return ji(this,void 0,void 0,function*(){const t=new Int8Array(e);let i=0;if(this.privLastChunkView!==void 0){if(this.privLastChunkView.length>e.byteLength)return t.set(this.privLastChunkView.slice(0,e.byteLength)),this.privLastChunkView=this.privLastChunkView.slice(e.byteLength),Promise.resolve(e.byteLength);t.set(this.privLastChunkView),i=this.privLastChunkView.length,this.privLastChunkView=void 0}for(;i<e.byteLength&&!this.privStream.isReadEnded;){const n=yield this.privStream.read();if(n!==void 0&&!n.isEnd){let s;n.buffer.byteLength>e.byteLength-i?(s=n.buffer.slice(0,e.byteLength-i),this.privLastChunkView=new Int8Array(n.buffer.slice(e.byteLength-i))):s=n.buffer,t.set(new Int8Array(s),i),i+=s.byteLength}else this.privStream.readEnded()}return i})}write(e){l.throwIfNullOrUndefined(this.privStream,"must set format before writing"),this.privStream.writeStreamChunk({buffer:e,isEnd:!1,timeReceived:Date.now()})}close(){this.privStream.close()}}class Vt extends Wt{constructor(){super()}static create(e){return new lt(e)}}class lt extends Vt{constructor(e){super(),this.privId=E(),this.privCallback=e}set format(e){}write(e){this.privCallback.write&&this.privCallback.write(e)}close(){this.privCallback.close&&this.privCallback.close()}id(){return this.privId}}class ee{static fromDefaultMicrophoneInput(){const e=new At(!0);return new pe(new W(e))}static fromMicrophoneInput(e){const t=new At(!0);return new pe(new W(t,e))}static fromWavFileInput(e,t="unnamedBuffer.wav"){return new pe(new Tr(e,t))}static fromStreamInput(e){if(e instanceof Fi)return new pe(new Ut(e));if(e instanceof dt)return new pe(e);if(typeof MediaStream!="undefined"&&e instanceof MediaStream){const t=new At(!1);return new pe(new W(t,null,null,e))}throw new Error("Not Supported Type")}static fromDefaultSpeakerOutput(){return new de(new yt)}static fromSpeakerOutput(e){if(e===void 0)return ee.fromDefaultSpeakerOutput();if(e instanceof yt)return new de(e);throw new Error("Not Supported Type")}static fromAudioFileOutput(e){return new de(new Ht(e))}static fromStreamOutput(e){if(e instanceof jt)return new de(new lt(e));if(e instanceof Vt)return new de(e);if(e instanceof Oe)return new de(e);throw new Error("Not Supported Type")}}class pe extends ee{constructor(e){super(),this.privSource=e}get format(){return this.privSource.format}close(e,t){this.privSource.turnOff().then(()=>{e&&e()},i=>{t&&t(i)})}id(){return this.privSource.id()}get blob(){return this.privSource.blob}turnOn(){return this.privSource.turnOn()}attach(e){return this.privSource.attach(e)}detach(e){return this.privSource.detach(e)}turnOff(){return this.privSource.turnOff()}get events(){return this.privSource.events}setProperty(e,t){if(l.throwIfNull(t,"value"),this.privSource.setProperty!==void 0)this.privSource.setProperty(e,t);else throw new Error("This AudioConfig instance does not support setting properties.")}getProperty(e,t){if(this.privSource.getProperty!==void 0)return this.privSource.getProperty(e,t);throw new Error("This AudioConfig instance does not support getting properties.")}get deviceInfo(){return this.privSource.deviceInfo}}class de extends ee{constructor(e){super(),this.privDestination=e}set format(e){this.privDestination.format=e}write(e){this.privDestination.write(e)}close(){this.privDestination.close()}id(){return this.privDestination.id()}setProperty(){throw new Error("This AudioConfig instance does not support setting properties.")}getProperty(){throw new Error("This AudioConfig instance does not support getting properties.")}}var K;(function(r){r[r.Error=0]="Error",r[r.EndOfStream=1]="EndOfStream"})(K||(K={}));class Fi{}class jt{}class ve{constructor(e){this.privSessionId=e}get sessionId(){return this.privSessionId}}class ft extends ve{constructor(e,t){super(t),this.privOffset=e}get offset(){return this.privOffset}}var te;(function(r){r[r.Simple=0]="Simple",r[r.Detailed=1]="Detailed"})(te||(te={}));class $i{constructor(e,t,i,n,s,o,a,u,h,c){this.privResultId=e,this.privReason=t,this.privText=i,this.privDuration=n,this.privOffset=s,this.privLanguage=o,this.privLanguageDetectionConfidence=a,this.privErrorDetails=u,this.privJson=h,this.privProperties=c}get resultId(){return this.privResultId}get reason(){return this.privReason}get text(){return this.privText}get duration(){return this.privDuration}get offset(){return this.privOffset}get language(){return this.privLanguage}get languageDetectionConfidence(){return this.privLanguageDetectionConfidence}get errorDetails(){return this.privErrorDetails}get json(){return this.privJson}get properties(){return this.privProperties}}class Gi extends $i{constructor(e,t,i,n,s,o,a,u,h,c,d){super(e,t,i,n,s,o,a,h,c,d),this.privSpeakerId=u}get speakerId(){return this.privSpeakerId}}class Ft extends ft{constructor(e,t,i){super(t,i),this.privResult=e}get result(){return this.privResult}}class $t extends ve{constructor(e,t){super(t),this.privResult=e}get result(){return this.privResult}}class gt extends Gi{constructor(e,t,i,n,s,o,a,u,h){super(t,i,n,s,o,void 0,void 0,void 0,a,u,h),this.privTranslations=e}get translations(){return this.privTranslations}}class Gt{constructor(e,t){this.privReason=e,this.privAudio=t}get audio(){return this.privAudio}get reason(){return this.privReason}}var P;(function(r){r[r.NoMatch=0]="NoMatch",r[r.Canceled=1]="Canceled",r[r.RecognizingSpeech=2]="RecognizingSpeech",r[r.RecognizedSpeech=3]="RecognizedSpeech",r[r.RecognizedKeyword=4]="RecognizedKeyword",r[r.RecognizingIntent=5]="RecognizingIntent",r[r.RecognizedIntent=6]="RecognizedIntent",r[r.TranslatingSpeech=7]="TranslatingSpeech",r[r.TranslatedSpeech=8]="TranslatedSpeech",r[r.SynthesizingAudio=9]="SynthesizingAudio",r[r.SynthesizingAudioCompleted=10]="SynthesizingAudioCompleted",r[r.SynthesizingAudioStarted=11]="SynthesizingAudioStarted",r[r.EnrollingVoiceProfile=12]="EnrollingVoiceProfile",r[r.EnrolledVoiceProfile=13]="EnrolledVoiceProfile",r[r.RecognizedSpeakers=14]="RecognizedSpeakers",r[r.RecognizedSpeaker=15]="RecognizedSpeaker",r[r.ResetVoiceProfile=16]="ResetVoiceProfile",r[r.DeletedVoiceProfile=17]="DeletedVoiceProfile",r[r.VoicesListRetrieved=18]="VoicesListRetrieved"})(P||(P={}));class _e{constructor(){}static fromSubscription(e,t){l.throwIfNullOrWhitespace(e,"subscriptionKey"),l.throwIfNullOrWhitespace(t,"region");const i=new le;return i.setProperty(p.SpeechServiceConnection_Region,t),i.setProperty(p.SpeechServiceConnection_IntentRegion,t),i.setProperty(p.SpeechServiceConnection_Key,e),i}static fromEndpoint(e,t){l.throwIfNull(e,"endpoint");const i=new le;return i.setProperty(p.SpeechServiceConnection_Endpoint,e.href),t!==void 0&&i.setProperty(p.SpeechServiceConnection_Key,t),i}static fromHost(e,t){l.throwIfNull(e,"hostName");const i=new le;return i.setProperty(p.SpeechServiceConnection_Host,e.protocol+"//"+e.hostname+(e.port===""?"":":"+e.port)),t!==void 0&&i.setProperty(p.SpeechServiceConnection_Key,t),i}static fromAuthorizationToken(e,t){l.throwIfNull(e,"authorizationToken"),l.throwIfNullOrWhitespace(t,"region");const i=new le;return i.setProperty(p.SpeechServiceConnection_Region,t),i.setProperty(p.SpeechServiceConnection_IntentRegion,t),i.authorizationToken=e,i}close(){}}class le extends _e{constructor(){super(),this.privProperties=new U,this.speechRecognitionLanguage="en-US",this.outputFormat=te.Simple}get properties(){return this.privProperties}get endPoint(){return new URL(this.privProperties.getProperty(p.SpeechServiceConnection_Endpoint))}get subscriptionKey(){return this.privProperties.getProperty(p.SpeechServiceConnection_Key)}get region(){return this.privProperties.getProperty(p.SpeechServiceConnection_Region)}get authorizationToken(){return this.privProperties.getProperty(p.SpeechServiceAuthorization_Token)}set authorizationToken(e){this.privProperties.setProperty(p.SpeechServiceAuthorization_Token,e)}get speechRecognitionLanguage(){return this.privProperties.getProperty(p.SpeechServiceConnection_RecoLanguage)}set speechRecognitionLanguage(e){this.privProperties.setProperty(p.SpeechServiceConnection_RecoLanguage,e)}get autoDetectSourceLanguages(){return this.privProperties.getProperty(p.SpeechServiceConnection_AutoDetectSourceLanguages)}set autoDetectSourceLanguages(e){this.privProperties.setProperty(p.SpeechServiceConnection_AutoDetectSourceLanguages,e)}get outputFormat(){return te[this.privProperties.getProperty(Ye,void 0)]}set outputFormat(e){this.privProperties.setProperty(Ye,te[e])}get endpointId(){return this.privProperties.getProperty(p.SpeechServiceConnection_EndpointId)}set endpointId(e){this.privProperties.setProperty(p.SpeechServiceConnection_EndpointId,e)}setProperty(e,t){l.throwIfNull(t,"value"),this.privProperties.setProperty(e,t)}getProperty(e,t){return this.privProperties.getProperty(e,t)}setProxy(e,t,i,n){this.setProperty(p[p.SpeechServiceConnection_ProxyHostName],e),this.setProperty(p[p.SpeechServiceConnection_ProxyPort],t),this.setProperty(p[p.SpeechServiceConnection_ProxyUserName],i),this.setProperty(p[p.SpeechServiceConnection_ProxyPassword],n)}setServiceProperty(e,t){const i=JSON.parse(this.privProperties.getProperty(Me,"{}"));i[e]=t,this.privProperties.setProperty(Me,JSON.stringify(i))}setProfanity(e){this.privProperties.setProperty(p.SpeechServiceResponse_ProfanityOption,Ue[e])}enableAudioLogging(){this.privProperties.setProperty(p.SpeechServiceConnection_EnableAudioLogging,"true")}requestWordLevelTimestamps(){this.privProperties.setProperty(p.SpeechServiceResponse_RequestWordLevelTimestamps,"true")}enableDictation(){this.privProperties.setProperty(li,"true")}clone(){const e=new le;return e.privProperties=this.privProperties.clone(),e}get speechSynthesisLanguage(){return this.privProperties.getProperty(p.SpeechServiceConnection_SynthLanguage)}set speechSynthesisLanguage(e){this.privProperties.setProperty(p.SpeechServiceConnection_SynthLanguage,e)}get speechSynthesisVoiceName(){return this.privProperties.getProperty(p.SpeechServiceConnection_SynthVoice)}set speechSynthesisVoiceName(e){this.privProperties.setProperty(p.SpeechServiceConnection_SynthVoice,e)}get speechSynthesisOutputFormat(){return g[this.privProperties.getProperty(p.SpeechServiceConnection_SynthOutputFormat,void 0)]}set speechSynthesisOutputFormat(e){this.privProperties.setProperty(p.SpeechServiceConnection_SynthOutputFormat,g[e])}}class Jt extends _e{constructor(){super()}static fromSubscription(e,t){l.throwIfNullOrWhitespace(e,"subscriptionKey"),l.throwIfNullOrWhitespace(t,"region");const i=new He;return i.properties.setProperty(p.SpeechServiceConnection_Key,e),i.properties.setProperty(p.SpeechServiceConnection_Region,t),i}static fromAuthorizationToken(e,t){l.throwIfNullOrWhitespace(e,"authorizationToken"),l.throwIfNullOrWhitespace(t,"region");const i=new He;return i.properties.setProperty(p.SpeechServiceAuthorization_Token,e),i.properties.setProperty(p.SpeechServiceConnection_Region,t),i}static fromHost(e,t){l.throwIfNull(e,"hostName");const i=new He;return i.setProperty(p.SpeechServiceConnection_Host,e.protocol+"//"+e.hostname+(e.port===""?"":":"+e.port)),t!==void 0&&i.setProperty(p.SpeechServiceConnection_Key,t),i}static fromEndpoint(e,t){l.throwIfNull(e,"endpoint"),l.throwIfNull(t,"subscriptionKey");const i=new He;return i.properties.setProperty(p.SpeechServiceConnection_Endpoint,e.href),i.properties.setProperty(p.SpeechServiceConnection_Key,t),i}}class He extends Jt{constructor(){super(),this.privSpeechProperties=new U,this.outputFormat=te.Simple}set authorizationToken(e){l.throwIfNullOrWhitespace(e,"value"),this.privSpeechProperties.setProperty(p.SpeechServiceAuthorization_Token,e)}set speechRecognitionLanguage(e){l.throwIfNullOrWhitespace(e,"value"),this.privSpeechProperties.setProperty(p.SpeechServiceConnection_RecoLanguage,e)}get speechRecognitionLanguage(){return this.privSpeechProperties.getProperty(p[p.SpeechServiceConnection_RecoLanguage])}get subscriptionKey(){return this.privSpeechProperties.getProperty(p[p.SpeechServiceConnection_Key])}get outputFormat(){return te[this.privSpeechProperties.getProperty(Ye,void 0)]}set outputFormat(e){this.privSpeechProperties.setProperty(Ye,te[e])}get endpointId(){return this.privSpeechProperties.getProperty(p.SpeechServiceConnection_EndpointId)}set endpointId(e){this.privSpeechProperties.setProperty(p.SpeechServiceConnection_EndpointId,e)}addTargetLanguage(e){l.throwIfNullOrWhitespace(e,"value");const t=this.targetLanguages;t.push(e),this.privSpeechProperties.setProperty(p.SpeechServiceConnection_TranslationToLanguages,t.join(","))}get targetLanguages(){return this.privSpeechProperties.getProperty(p.SpeechServiceConnection_TranslationToLanguages,void 0)!==void 0?this.privSpeechProperties.getProperty(p.SpeechServiceConnection_TranslationToLanguages).split(","):[]}get voiceName(){return this.getProperty(p[p.SpeechServiceConnection_TranslationVoice])}set voiceName(e){l.throwIfNullOrWhitespace(e,"value"),this.privSpeechProperties.setProperty(p.SpeechServiceConnection_TranslationVoice,e)}get region(){return this.privSpeechProperties.getProperty(p.SpeechServiceConnection_Region)}setProxy(e,t,i,n){this.setProperty(p[p.SpeechServiceConnection_ProxyHostName],e),this.setProperty(p[p.SpeechServiceConnection_ProxyPort],t),this.setProperty(p[p.SpeechServiceConnection_ProxyUserName],i),this.setProperty(p[p.SpeechServiceConnection_ProxyPassword],n)}getProperty(e,t){return this.privSpeechProperties.getProperty(e,t)}setProperty(e,t){this.privSpeechProperties.setProperty(e,t)}get properties(){return this.privSpeechProperties}close(){}setServiceProperty(e,t){const i=JSON.parse(this.privSpeechProperties.getProperty(Me,"{}"));i[e]=t,this.privSpeechProperties.setProperty(Me,JSON.stringify(i))}setProfanity(e){this.privSpeechProperties.setProperty(p.SpeechServiceResponse_ProfanityOption,Ue[e])}enableAudioLogging(){this.privSpeechProperties.setProperty(p.SpeechServiceConnection_EnableAudioLogging,"true")}requestWordLevelTimestamps(){this.privSpeechProperties.setProperty(p.SpeechServiceResponse_RequestWordLevelTimestamps,"true")}enableDictation(){this.privSpeechProperties.setProperty(li,"true")}get speechSynthesisLanguage(){return this.privSpeechProperties.getProperty(p.SpeechServiceConnection_SynthLanguage)}set speechSynthesisLanguage(e){this.privSpeechProperties.setProperty(p.SpeechServiceConnection_SynthLanguage,e)}get speechSynthesisVoiceName(){return this.privSpeechProperties.getProperty(p.SpeechServiceConnection_SynthVoice)}set speechSynthesisVoiceName(e){this.privSpeechProperties.setProperty(p.SpeechServiceConnection_SynthVoice,e)}get speechSynthesisOutputFormat(){return g[this.privSpeechProperties.getProperty(p.SpeechServiceConnection_SynthOutputFormat,void 0)]}set speechSynthesisOutputFormat(e){this.privSpeechProperties.setProperty(p.SpeechServiceConnection_SynthOutputFormat,g[e])}}class U{constructor(){this.privKeys=[],this.privValues=[]}getProperty(e,t){let i;typeof e=="string"?i=e:i=p[e];for(let n=0;n<this.privKeys.length;n++)if(this.privKeys[n]===i)return this.privValues[n];if(t!==void 0)return String(t)}setProperty(e,t){let i;typeof e=="string"?i=e:i=p[e];for(let n=0;n<this.privKeys.length;n++)if(this.privKeys[n]===i){this.privValues[n]=t;return}this.privKeys.push(i),this.privValues.push(t)}clone(){const e=new U;for(let t=0;t<this.privKeys.length;t++)e.privKeys.push(this.privKeys[t]),e.privValues.push(this.privValues[t]);return e}mergeTo(e){this.privKeys.forEach(t=>{if(e.getProperty(t,void 0)===void 0){const i=this.getProperty(t);e.setProperty(t,i)}})}get keys(){return this.privKeys}}var p;(function(r){r[r.SpeechServiceConnection_Key=0]="SpeechServiceConnection_Key",r[r.SpeechServiceConnection_Endpoint=1]="SpeechServiceConnection_Endpoint",r[r.SpeechServiceConnection_Region=2]="SpeechServiceConnection_Region",r[r.SpeechServiceAuthorization_Token=3]="SpeechServiceAuthorization_Token",r[r.SpeechServiceAuthorization_Type=4]="SpeechServiceAuthorization_Type",r[r.SpeechServiceConnection_EndpointId=5]="SpeechServiceConnection_EndpointId",r[r.SpeechServiceConnection_TranslationToLanguages=6]="SpeechServiceConnection_TranslationToLanguages",r[r.SpeechServiceConnection_TranslationVoice=7]="SpeechServiceConnection_TranslationVoice",r[r.SpeechServiceConnection_TranslationFeatures=8]="SpeechServiceConnection_TranslationFeatures",r[r.SpeechServiceConnection_IntentRegion=9]="SpeechServiceConnection_IntentRegion",r[r.SpeechServiceConnection_ProxyHostName=10]="SpeechServiceConnection_ProxyHostName",r[r.SpeechServiceConnection_ProxyPort=11]="SpeechServiceConnection_ProxyPort",r[r.SpeechServiceConnection_ProxyUserName=12]="SpeechServiceConnection_ProxyUserName",r[r.SpeechServiceConnection_ProxyPassword=13]="SpeechServiceConnection_ProxyPassword",r[r.SpeechServiceConnection_RecoMode=14]="SpeechServiceConnection_RecoMode",r[r.SpeechServiceConnection_RecoLanguage=15]="SpeechServiceConnection_RecoLanguage",r[r.Speech_SessionId=16]="Speech_SessionId",r[r.SpeechServiceConnection_SynthLanguage=17]="SpeechServiceConnection_SynthLanguage",r[r.SpeechServiceConnection_SynthVoice=18]="SpeechServiceConnection_SynthVoice",r[r.SpeechServiceConnection_SynthOutputFormat=19]="SpeechServiceConnection_SynthOutputFormat",r[r.SpeechServiceConnection_AutoDetectSourceLanguages=20]="SpeechServiceConnection_AutoDetectSourceLanguages",r[r.SpeechServiceResponse_RequestDetailedResultTrueFalse=21]="SpeechServiceResponse_RequestDetailedResultTrueFalse",r[r.SpeechServiceResponse_RequestProfanityFilterTrueFalse=22]="SpeechServiceResponse_RequestProfanityFilterTrueFalse",r[r.SpeechServiceResponse_JsonResult=23]="SpeechServiceResponse_JsonResult",r[r.SpeechServiceResponse_JsonErrorDetails=24]="SpeechServiceResponse_JsonErrorDetails",r[r.CancellationDetails_Reason=25]="CancellationDetails_Reason",r[r.CancellationDetails_ReasonText=26]="CancellationDetails_ReasonText",r[r.CancellationDetails_ReasonDetailedText=27]="CancellationDetails_ReasonDetailedText",r[r.LanguageUnderstandingServiceResponse_JsonResult=28]="LanguageUnderstandingServiceResponse_JsonResult",r[r.SpeechServiceConnection_Url=29]="SpeechServiceConnection_Url",r[r.SpeechServiceConnection_InitialSilenceTimeoutMs=30]="SpeechServiceConnection_InitialSilenceTimeoutMs",r[r.SpeechServiceConnection_EndSilenceTimeoutMs=31]="SpeechServiceConnection_EndSilenceTimeoutMs",r[r.Speech_SegmentationSilenceTimeoutMs=32]="Speech_SegmentationSilenceTimeoutMs",r[r.SpeechServiceConnection_EnableAudioLogging=33]="SpeechServiceConnection_EnableAudioLogging",r[r.SpeechServiceConnection_AtStartLanguageIdPriority=34]="SpeechServiceConnection_AtStartLanguageIdPriority",r[r.SpeechServiceConnection_ContinuousLanguageIdPriority=35]="SpeechServiceConnection_ContinuousLanguageIdPriority",r[r.SpeechServiceConnection_RecognitionEndpointVersion=36]="SpeechServiceConnection_RecognitionEndpointVersion",r[r.SpeechServiceResponse_ProfanityOption=37]="SpeechServiceResponse_ProfanityOption",r[r.SpeechServiceResponse_PostProcessingOption=38]="SpeechServiceResponse_PostProcessingOption",r[r.SpeechServiceResponse_RequestWordLevelTimestamps=39]="SpeechServiceResponse_RequestWordLevelTimestamps",r[r.SpeechServiceResponse_StablePartialResultThreshold=40]="SpeechServiceResponse_StablePartialResultThreshold",r[r.SpeechServiceResponse_OutputFormatOption=41]="SpeechServiceResponse_OutputFormatOption",r[r.SpeechServiceResponse_TranslationRequestStablePartialResult=42]="SpeechServiceResponse_TranslationRequestStablePartialResult",r[r.SpeechServiceResponse_RequestWordBoundary=43]="SpeechServiceResponse_RequestWordBoundary",r[r.SpeechServiceResponse_RequestPunctuationBoundary=44]="SpeechServiceResponse_RequestPunctuationBoundary",r[r.SpeechServiceResponse_RequestSentenceBoundary=45]="SpeechServiceResponse_RequestSentenceBoundary",r[r.Conversation_ApplicationId=46]="Conversation_ApplicationId",r[r.Conversation_DialogType=47]="Conversation_DialogType",r[r.Conversation_Initial_Silence_Timeout=48]="Conversation_Initial_Silence_Timeout",r[r.Conversation_From_Id=49]="Conversation_From_Id",r[r.Conversation_Conversation_Id=50]="Conversation_Conversation_Id",r[r.Conversation_Custom_Voice_Deployment_Ids=51]="Conversation_Custom_Voice_Deployment_Ids",r[r.Conversation_Speech_Activity_Template=52]="Conversation_Speech_Activity_Template",r[r.Conversation_Request_Bot_Status_Messages=53]="Conversation_Request_Bot_Status_Messages",r[r.Conversation_Agent_Connection_Id=54]="Conversation_Agent_Connection_Id",r[r.SpeechServiceConnection_Host=55]="SpeechServiceConnection_Host",r[r.ConversationTranslator_Host=56]="ConversationTranslator_Host",r[r.ConversationTranslator_Name=57]="ConversationTranslator_Name",r[r.ConversationTranslator_CorrelationId=58]="ConversationTranslator_CorrelationId",r[r.ConversationTranslator_Token=59]="ConversationTranslator_Token",r[r.PronunciationAssessment_ReferenceText=60]="PronunciationAssessment_ReferenceText",r[r.PronunciationAssessment_GradingSystem=61]="PronunciationAssessment_GradingSystem",r[r.PronunciationAssessment_Granularity=62]="PronunciationAssessment_Granularity",r[r.PronunciationAssessment_EnableMiscue=63]="PronunciationAssessment_EnableMiscue",r[r.PronunciationAssessment_Json=64]="PronunciationAssessment_Json",r[r.PronunciationAssessment_Params=65]="PronunciationAssessment_Params",r[r.SpeakerRecognition_Api_Version=66]="SpeakerRecognition_Api_Version"})(p||(p={}));var Re=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};class St{constructor(e,t,i){this.audioConfig=e!==void 0?e:ee.fromDefaultMicrophoneInput(),this.privDisposed=!1,this.privProperties=t.clone(),this.privConnectionFactory=i,this.implCommonRecognizerSetup()}close(e,t){l.throwIfDisposed(this.privDisposed),J(this.dispose(!0),e,t)}get internalData(){return this.privReco}dispose(e){return Re(this,void 0,void 0,function*(){this.privDisposed||(this.privDisposed=!0,e&&this.privReco&&(yield this.privReco.audioSource.turnOff(),yield this.privReco.dispose()))})}static get telemetryEnabled(){return $.telemetryDataEnabled}static enableTelemetry(e){$.telemetryDataEnabled=e}implCommonRecognizerSetup(){let e=typeof window!="undefined"?"Browser":"Node",t="unknown",i="unknown";typeof navigator!="undefined"&&(e=e+"/"+navigator.platform,t=navigator.userAgent,i=navigator.appVersion);const n=this.createRecognizerConfig(new Ge(new Je(new ci(e,t,i))));this.privReco=this.createServiceRecognizer(St.getAuthFromProperties(this.privProperties),this.privConnectionFactory,this.audioConfig,n)}recognizeOnceAsyncImpl(e){return Re(this,void 0,void 0,function*(){l.throwIfDisposed(this.privDisposed);const t=new D;yield this.implRecognizerStop(),yield this.privReco.recognize(e,t.resolve,t.reject);const i=yield t.promise;return yield this.implRecognizerStop(),i})}startContinuousRecognitionAsyncImpl(e){return Re(this,void 0,void 0,function*(){l.throwIfDisposed(this.privDisposed),yield this.implRecognizerStop(),yield this.privReco.recognize(e,void 0,void 0)})}stopContinuousRecognitionAsyncImpl(){return Re(this,void 0,void 0,function*(){l.throwIfDisposed(this.privDisposed),yield this.implRecognizerStop()})}implRecognizerStop(){return Re(this,void 0,void 0,function*(){this.privReco&&(yield this.privReco.stopRecognizing())})}static getAuthFromProperties(e){const t=e.getProperty(p.SpeechServiceConnection_Key,void 0);return t&&t!==""?new Ot(t):new ue(()=>{const n=e.getProperty(p.SpeechServiceAuthorization_Token,void 0);return Promise.resolve(n)},()=>{const n=e.getProperty(p.SpeechServiceAuthorization_Token,void 0);return Promise.resolve(n)})}}class Qt{constructor(e){this.privConnectionMessage=e,this.privProperties=new U,this.privConnectionMessage.headers[T.ConnectionId]&&this.privProperties.setProperty(p.Speech_SessionId,this.privConnectionMessage.headers[T.ConnectionId]),Object.keys(this.privConnectionMessage.headers).forEach(t=>{this.privProperties.setProperty(t,this.privConnectionMessage.headers[t])})}get path(){return this.privConnectionMessage.headers[Object.keys(this.privConnectionMessage.headers).find(e=>e.toLowerCase()==="path".toLowerCase())]}get isTextMessage(){return this.privConnectionMessage.messageType===m.Text}get isBinaryMessage(){return this.privConnectionMessage.messageType===m.Binary}get TextMessage(){return this.privConnectionMessage.textBody}get binaryMessage(){return this.privConnectionMessage.binaryBody}get properties(){return this.privProperties}toString(){return""}}class Ke{static fromRecognizer(e){const t=e.internalData,i=new Ke;return i.privInternalData=t,i.setupEvents(),i}static fromSynthesizer(e){const t=e.internalData,i=new Ke;return i.privInternalData=t,i.setupEvents(),i}openConnection(e,t){J(this.privInternalData.connect(),e,t)}closeConnection(e,t){if(this.privInternalData instanceof ne)throw new Error("Disconnecting a synthesizer's connection is currently not supported");J(this.privInternalData.disconnect(),e,t)}setMessageProperty(e,t,i){if(l.throwIfNullOrWhitespace(t,"propertyName"),this.privInternalData instanceof $){if(e.toLowerCase()!=="speech.context")throw new Error("Only speech.context message property sets are currently supported for recognizer");this.privInternalData.speechContext.setSection(t,i)}else if(this.privInternalData instanceof ne){if(e.toLowerCase()!=="synthesis.context")throw new Error("Only synthesis.context message property sets are currently supported for synthesizer");this.privInternalData.synthesisContext.setSection(t,i)}}sendMessageAsync(e,t,i,n){J(this.privInternalData.sendNetworkMessage(e,t),i,n)}close(){}setupEvents(){this.privEventListener=this.privInternalData.connectionEvents.attach(e=>{e.name==="ConnectionEstablishedEvent"?this.connected&&this.connected(new Yt(e.connectionId)):e.name==="ConnectionClosedEvent"?this.disconnected&&this.disconnected(new Yt(e.connectionId)):e.name==="ConnectionMessageSentEvent"?this.messageSent&&this.messageSent(new ei(new Qt(e.message))):e.name==="ConnectionMessageReceivedEvent"&&this.messageReceived&&this.messageReceived(new ei(new Qt(e.message)))}),this.privServiceEventListener=this.privInternalData.serviceEvents.attach(e=>{this.receivedServiceMessage&&this.receivedServiceMessage(new Xi(e.jsonString,e.name))})}}var Xt=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};class Ji extends St{constructor(e,t){const i=e;l.throwIfNull(i,"speechConfig"),super(t,i.properties,new cr),this.privDisposedTranslationRecognizer=!1,this.properties.getProperty(p.SpeechServiceConnection_TranslationVoice,void 0)!==void 0&&l.throwIfNullOrWhitespace(this.properties.getProperty(p.SpeechServiceConnection_TranslationVoice),p[p.SpeechServiceConnection_TranslationVoice]),l.throwIfNullOrWhitespace(this.properties.getProperty(p.SpeechServiceConnection_TranslationToLanguages),p[p.SpeechServiceConnection_TranslationToLanguages]),l.throwIfNullOrWhitespace(this.properties.getProperty(p.SpeechServiceConnection_RecoLanguage),p[p.SpeechServiceConnection_RecoLanguage])}get speechRecognitionLanguage(){return l.throwIfDisposed(this.privDisposedTranslationRecognizer),this.properties.getProperty(p.SpeechServiceConnection_RecoLanguage)}get targetLanguages(){return l.throwIfDisposed(this.privDisposedTranslationRecognizer),this.properties.getProperty(p.SpeechServiceConnection_TranslationToLanguages).split(",")}get voiceName(){return l.throwIfDisposed(this.privDisposedTranslationRecognizer),this.properties.getProperty(p.SpeechServiceConnection_TranslationVoice,void 0)}get properties(){return this.privProperties}get authorizationToken(){return this.properties.getProperty(p.SpeechServiceAuthorization_Token)}set authorizationToken(e){this.properties.setProperty(p.SpeechServiceAuthorization_Token,e)}recognizeOnceAsync(e,t){l.throwIfDisposed(this.privDisposedTranslationRecognizer),J(this.recognizeOnceAsyncImpl(ae.Conversation),e,t)}startContinuousRecognitionAsync(e,t){J(this.startContinuousRecognitionAsyncImpl(ae.Conversation),e,t)}stopContinuousRecognitionAsync(e,t){J(this.stopContinuousRecognitionAsyncImpl(),e,t)}removeTargetLanguage(e){if(l.throwIfNullOrUndefined(e,"language to be removed"),this.properties.getProperty(p.SpeechServiceConnection_TranslationToLanguages,void 0)!==void 0){const t=this.properties.getProperty(p.SpeechServiceConnection_TranslationToLanguages).split(","),i=t.indexOf(e);i>-1&&(t.splice(i,1),this.properties.setProperty(p.SpeechServiceConnection_TranslationToLanguages,t.join(",")),this.updateLanguages(t))}}addTargetLanguage(e){l.throwIfNullOrUndefined(e,"language to be added");let t=[];this.properties.getProperty(p.SpeechServiceConnection_TranslationToLanguages,void 0)!==void 0?(t=this.properties.getProperty(p.SpeechServiceConnection_TranslationToLanguages).split(","),t.includes(e)||(t.push(e),this.properties.setProperty(p.SpeechServiceConnection_TranslationToLanguages,t.join(",")))):(this.properties.setProperty(p.SpeechServiceConnection_TranslationToLanguages,e),t=[e]),this.updateLanguages(t)}close(e,t){l.throwIfDisposed(this.privDisposedTranslationRecognizer),J(this.dispose(!0),e,t)}onConnection(){}onDisconnection(){return Xt(this,void 0,void 0,function*(){})}dispose(e){const t=Object.create(null,{dispose:{get:()=>super.dispose}});return Xt(this,void 0,void 0,function*(){this.privDisposedTranslationRecognizer||(this.privDisposedTranslationRecognizer=!0,e&&(yield this.implRecognizerStop(),yield t.dispose.call(this,e)))})}createRecognizerConfig(e){return new or(e,this.properties)}createServiceRecognizer(e,t,i,n){const s=i;return new ur(e,t,s,n,this)}updateLanguages(e){const t=Ke.fromRecognizer(this);t&&(t.setMessageProperty("speech.context","translationcontext",{to:e}),t.sendMessageAsync("event",JSON.stringify({id:"translation",name:"updateLanguage",to:e})))}}class Qi{constructor(){this.privMap=new U}get languages(){return this.privMap.keys}get(e,t){return this.privMap.getProperty(e,t)}set(e,t){this.privMap.setProperty(e,t)}}class Zt{constructor(e,t,i,n,s){this.privCancelReason=t,this.privErrorDetails=i,this.privResult=s,this.privSessionId=e,this.privErrorCode=n}get result(){return this.privResult}get sessionId(){return this.privSessionId}get reason(){return this.privCancelReason}get errorCode(){return this.privErrorCode}get errorDetails(){return this.privErrorDetails}}var R;(function(r){r[r.NoError=0]="NoError",r[r.AuthenticationFailure=1]="AuthenticationFailure",r[r.BadRequestParameters=2]="BadRequestParameters",r[r.TooManyRequests=3]="TooManyRequests",r[r.ConnectionFailure=4]="ConnectionFailure",r[r.ServiceTimeout=5]="ServiceTimeout",r[r.ServiceError=6]="ServiceError",r[r.RuntimeError=7]="RuntimeError",r[r.Forbidden=8]="Forbidden"})(R||(R={}));class Yt extends ve{}class Xi extends ve{constructor(e,t,i){super(i),this.privJsonResult=e,this.privEventName=t}get jsonString(){return this.privJsonResult}get eventName(){return this.privEventName}}class C{}C.BotId="botid",C.CustomSpeechDeploymentId="cid",C.CustomVoiceDeploymentId="deploymentId",C.EnableAudioLogging="storeAudio",C.EnableLanguageId="lidEnabled",C.EnableWordLevelTimestamps="wordLevelTimestamps",C.EndSilenceTimeoutMs="endSilenceTimeoutMs",C.SegmentationSilenceTimeoutMs="segmentationSilenceTimeoutMs",C.Format="format",C.InitialSilenceTimeoutMs="initialSilenceTimeoutMs",C.Language="language",C.Profanity="profanity",C.RequestBotStatusMessages="enableBotMessageStatus",C.StableIntermediateThreshold="stableIntermediateThreshold",C.StableTranslation="stableTranslation",C.TestHooks="testhooks",C.Postprocessing="postprocessing";class qe{static getHostSuffix(e){if(e){if(e.toLowerCase().startsWith("china"))return".azure.cn";if(e.toLowerCase().startsWith("usgov"))return".azure.us"}return".microsoft.com"}setCommonUrlParams(e,t,i){new Map([[p.Speech_SegmentationSilenceTimeoutMs,C.SegmentationSilenceTimeoutMs],[p.SpeechServiceConnection_EnableAudioLogging,C.EnableAudioLogging],[p.SpeechServiceConnection_EndSilenceTimeoutMs,C.EndSilenceTimeoutMs],[p.SpeechServiceConnection_InitialSilenceTimeoutMs,C.InitialSilenceTimeoutMs],[p.SpeechServiceResponse_PostProcessingOption,C.Postprocessing],[p.SpeechServiceResponse_ProfanityOption,C.Profanity],[p.SpeechServiceResponse_RequestWordLevelTimestamps,C.EnableWordLevelTimestamps],[p.SpeechServiceResponse_StablePartialResultThreshold,C.StableIntermediateThreshold]]).forEach((o,a)=>{this.setUrlParameter(a,o,e,t,i)});const s=JSON.parse(e.parameters.getProperty(Me,"{}"));Object.keys(s).forEach(o=>{t[o]=s[o]})}setUrlParameter(e,t,i,n,s){const o=i.parameters.getProperty(e,void 0);o&&(!s||s.search(t)===-1)&&(n[t]=o.toLocaleLowerCase())}}var Ue;(function(r){r[r.Masked=0]="Masked",r[r.Removed=1]="Removed",r[r.Raw=2]="Raw"})(Ue||(Ue={}));class ei{constructor(e){this.privConnectionMessage=e}get message(){return this.privConnectionMessage}toString(){return"Message: "+this.privConnectionMessage.toString()}}var We=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};class Pe{constructor(e,t){const i=e;l.throwIfNull(i,"speechConfig"),t!==null&&(t===void 0?this.audioConfig=typeof window=="undefined"?void 0:ee.fromDefaultSpeakerOutput():this.audioConfig=t),this.privProperties=i.properties.clone(),this.privDisposed=!1,this.privSynthesizing=!1,this.privConnectionFactory=new hr,this.synthesisRequestQueue=new be,this.implCommonSynthesizeSetup()}get authorizationToken(){return this.properties.getProperty(p.SpeechServiceAuthorization_Token)}set authorizationToken(e){l.throwIfNullOrWhitespace(e,"token"),this.properties.setProperty(p.SpeechServiceAuthorization_Token,e)}get properties(){return this.privProperties}get autoDetectSourceLanguage(){return this.properties.getProperty(p.SpeechServiceConnection_AutoDetectSourceLanguages)===Cr}static FromConfig(e,t,i){const n=e;return t.properties.mergeTo(n.properties),new Pe(e,i)}buildSsml(e){const t={["af-ZA"]:"af-ZA-AdriNeural",["am-ET"]:"am-ET-AmehaNeural",["ar-AE"]:"ar-AE-FatimaNeural",["ar-BH"]:"ar-BH-AliNeural",["ar-DZ"]:"ar-DZ-AminaNeural",["ar-EG"]:"ar-EG-SalmaNeural",["ar-IQ"]:"ar-IQ-BasselNeural",["ar-JO"]:"ar-JO-SanaNeural",["ar-KW"]:"ar-KW-FahedNeural",["ar-LY"]:"ar-LY-ImanNeural",["ar-MA"]:"ar-MA-JamalNeural",["ar-QA"]:"ar-QA-AmalNeural",["ar-SA"]:"ar-SA-HamedNeural",["ar-SY"]:"ar-SY-AmanyNeural",["ar-TN"]:"ar-TN-HediNeural",["ar-YE"]:"ar-YE-MaryamNeural",["bg-BG"]:"bg-BG-BorislavNeural",["bn-BD"]:"bn-BD-NabanitaNeural",["bn-IN"]:"bn-IN-BashkarNeural",["ca-ES"]:"ca-ES-JoanaNeural",["cs-CZ"]:"cs-CZ-AntoninNeural",["cy-GB"]:"cy-GB-AledNeural",["da-DK"]:"da-DK-ChristelNeural",["de-AT"]:"de-AT-IngridNeural",["de-CH"]:"de-CH-JanNeural",["de-DE"]:"de-DE-KatjaNeural",["el-GR"]:"el-GR-AthinaNeural",["en-AU"]:"en-AU-NatashaNeural",["en-CA"]:"en-CA-ClaraNeural",["en-GB"]:"en-GB-LibbyNeural",["en-HK"]:"en-HK-SamNeural",["en-IE"]:"en-IE-ConnorNeural",["en-IN"]:"en-IN-NeerjaNeural",["en-KE"]:"en-KE-AsiliaNeural",["en-NG"]:"en-NG-AbeoNeural",["en-NZ"]:"en-NZ-MitchellNeural",["en-PH"]:"en-PH-JamesNeural",["en-SG"]:"en-SG-LunaNeural",["en-TZ"]:"en-TZ-ElimuNeural",["en-US"]:"en-US-JennyNeural",["en-ZA"]:"en-ZA-LeahNeural",["es-AR"]:"es-AR-ElenaNeural",["es-BO"]:"es-BO-MarceloNeural",["es-CL"]:"es-CL-CatalinaNeural",["es-CO"]:"es-CO-GonzaloNeural",["es-CR"]:"es-CR-JuanNeural",["es-CU"]:"es-CU-BelkysNeural",["es-DO"]:"es-DO-EmilioNeural",["es-EC"]:"es-EC-AndreaNeural",["es-ES"]:"es-ES-AlvaroNeural",["es-GQ"]:"es-GQ-JavierNeural",["es-GT"]:"es-GT-AndresNeural",["es-HN"]:"es-HN-CarlosNeural",["es-MX"]:"es-MX-DaliaNeural",["es-NI"]:"es-NI-FedericoNeural",["es-PA"]:"es-PA-MargaritaNeural",["es-PE"]:"es-PE-AlexNeural",["es-PR"]:"es-PR-KarinaNeural",["es-PY"]:"es-PY-MarioNeural",["es-SV"]:"es-SV-LorenaNeural",["es-US"]:"es-US-AlonsoNeural",["es-UY"]:"es-UY-MateoNeural",["es-VE"]:"es-VE-PaolaNeural",["et-EE"]:"et-EE-AnuNeural",["fa-IR"]:"fa-IR-DilaraNeural",["fi-FI"]:"fi-FI-SelmaNeural",["fil-PH"]:"fil-PH-AngeloNeural",["fr-BE"]:"fr-BE-CharlineNeural",["fr-CA"]:"fr-CA-SylvieNeural",["fr-CH"]:"fr-CH-ArianeNeural",["fr-FR"]:"fr-FR-DeniseNeural",["ga-IE"]:"ga-IE-ColmNeural",["gl-ES"]:"gl-ES-RoiNeural",["gu-IN"]:"gu-IN-DhwaniNeural",["he-IL"]:"he-IL-AvriNeural",["hi-IN"]:"hi-IN-MadhurNeural",["hr-HR"]:"hr-HR-GabrijelaNeural",["hu-HU"]:"hu-HU-NoemiNeural",["id-ID"]:"id-ID-ArdiNeural",["is-IS"]:"is-IS-GudrunNeural",["it-IT"]:"it-IT-IsabellaNeural",["ja-JP"]:"ja-JP-NanamiNeural",["jv-ID"]:"jv-ID-DimasNeural",["kk-KZ"]:"kk-KZ-AigulNeural",["km-KH"]:"km-KH-PisethNeural",["kn-IN"]:"kn-IN-GaganNeural",["ko-KR"]:"ko-KR-SunHiNeural",["lo-LA"]:"lo-LA-ChanthavongNeural",["lt-LT"]:"lt-LT-LeonasNeural",["lv-LV"]:"lv-LV-EveritaNeural",["mk-MK"]:"mk-MK-AleksandarNeural",["ml-IN"]:"ml-IN-MidhunNeural",["mr-IN"]:"mr-IN-AarohiNeural",["ms-MY"]:"ms-MY-OsmanNeural",["mt-MT"]:"mt-MT-GraceNeural",["my-MM"]:"my-MM-NilarNeural",["nb-NO"]:"nb-NO-PernilleNeural",["nl-BE"]:"nl-BE-ArnaudNeural",["nl-NL"]:"nl-NL-ColetteNeural",["pl-PL"]:"pl-PL-AgnieszkaNeural",["ps-AF"]:"ps-AF-GulNawazNeural",["pt-BR"]:"pt-BR-FranciscaNeural",["pt-PT"]:"pt-PT-DuarteNeural",["ro-RO"]:"ro-RO-AlinaNeural",["ru-RU"]:"ru-RU-SvetlanaNeural",["si-LK"]:"si-LK-SameeraNeural",["sk-SK"]:"sk-SK-LukasNeural",["sl-SI"]:"sl-SI-PetraNeural",["so-SO"]:"so-SO-MuuseNeural",["sr-RS"]:"sr-RS-NicholasNeural",["su-ID"]:"su-ID-JajangNeural",["sv-SE"]:"sv-SE-SofieNeural",["sw-KE"]:"sw-KE-RafikiNeural",["sw-TZ"]:"sw-TZ-DaudiNeural",["ta-IN"]:"ta-IN-PallaviNeural",["ta-LK"]:"ta-LK-KumarNeural",["ta-SG"]:"ta-SG-AnbuNeural",["te-IN"]:"te-IN-MohanNeural",["th-TH"]:"th-TH-PremwadeeNeural",["tr-TR"]:"tr-TR-AhmetNeural",["uk-UA"]:"uk-UA-OstapNeural",["ur-IN"]:"ur-IN-GulNeural",["ur-PK"]:"ur-PK-AsadNeural",["uz-UZ"]:"uz-UZ-MadinaNeural",["vi-VN"]:"vi-VN-HoaiMyNeural",["zh-CN"]:"zh-CN-XiaoxiaoNeural",["zh-HK"]:"zh-HK-HiuMaanNeural",["zh-TW"]:"zh-TW-HsiaoChenNeural",["zu-ZA"]:"zu-ZA-ThandoNeural"};let i=this.properties.getProperty(p.SpeechServiceConnection_SynthLanguage,"en-US"),n=this.properties.getProperty(p.SpeechServiceConnection_SynthVoice,""),s=Pe.XMLEncode(e);return this.autoDetectSourceLanguage?i="en-US":n=n||t[i],n&&(s=`<voice name='${n}'>${s}</voice>`),s=`<speak version='1.0' xmlns='http://www.w3.org/2001/10/synthesis' xmlns:mstts='http://www.w3.org/2001/mstts' xmlns:emo='http://www.w3.org/2009/10/emotionml' xml:lang='${i}'>${s}</speak>`,s}speakTextAsync(e,t,i,n){this.speakImpl(e,!1,t,i,n)}speakSsmlAsync(e,t,i,n){this.speakImpl(e,!0,t,i,n)}getVoicesAsync(e=""){return We(this,void 0,void 0,function*(){return this.getVoices(e)})}close(e,t){l.throwIfDisposed(this.privDisposed),J(this.dispose(!0),e,t)}get internalData(){return this.privAdapter}dispose(e){return We(this,void 0,void 0,function*(){this.privDisposed||(e&&this.privAdapter&&(yield this.privAdapter.dispose()),this.privDisposed=!0)})}createSynthesizerConfig(e){return new yr(e,this.privProperties)}createSynthesisAdapter(e,t,i,n){return new ne(e,t,n,this,this.audioConfig)}implCommonSynthesizeSetup(){let e=typeof window!="undefined"?"Browser":"Node",t="unknown",i="unknown";typeof navigator!="undefined"&&(e=e+"/"+navigator.platform,t=navigator.userAgent,i=navigator.appVersion);const n=this.createSynthesizerConfig(new Ge(new Je(new ci(e,t,i)))),s=this.privProperties.getProperty(p.SpeechServiceConnection_Key,void 0),o=s&&s!==""?new Ot(s):new ue(()=>{const a=this.privProperties.getProperty(p.SpeechServiceAuthorization_Token,void 0);return Promise.resolve(a)},()=>{const a=this.privProperties.getProperty(p.SpeechServiceAuthorization_Token,void 0);return Promise.resolve(a)});this.privAdapter=this.createSynthesisAdapter(o,this.privConnectionFactory,this.audioConfig,n),this.privAdapter.audioOutputFormat=f.fromSpeechSynthesisOutputFormat(g[this.properties.getProperty(p.SpeechServiceConnection_SynthOutputFormat,void 0)]),this.privRestAdapter=new mr(n)}speakImpl(e,t,i,n,s){try{l.throwIfDisposed(this.privDisposed);const o=E();let a;s instanceof jt?a=new lt(s):s instanceof Oe?a=s:s!==void 0?a=new Ht(s):a=void 0,this.synthesisRequestQueue.enqueue(new Zi(o,e,t,u=>{if(this.privSynthesizing=!1,i)try{i(u)}catch(h){n&&n(h)}i=void 0,this.adapterSpeak().catch(()=>{})},u=>{n&&n(u)},a)),this.adapterSpeak().catch(()=>{})}catch(o){if(n)if(o instanceof Error){const a=o;n(a.name+": "+a.message)}else n(o);this.dispose(!0).catch(()=>{})}}getVoices(e){return We(this,void 0,void 0,function*(){const t=E(),i=yield this.privRestAdapter.getVoicesList(t);if(i.ok&&Array.isArray(i.json)){let n=i.json;return!!e&&e.length>0&&(n=n.filter(s=>!!s.Locale&&s.Locale.toLowerCase()===e.toLowerCase())),new ii(t,n,void 0)}else return new ii(t,void 0,`Error: ${i.status}: ${i.statusText}`)})}adapterSpeak(){return We(this,void 0,void 0,function*(){if(!this.privDisposed&&!this.privSynthesizing){this.privSynthesizing=!0;const e=yield this.synthesisRequestQueue.dequeue();return this.privAdapter.Speak(e.text,e.isSSML,e.requestId,e.cb,e.err,e.dataStream)}})}static XMLEncode(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}}class Zi{constructor(e,t,i,n,s,o){this.requestId=e,this.text=t,this.isSSML=i,this.cb=n,this.err=s,this.dataStream=o}}class ti{constructor(e,t,i,n){this.privResultId=e,this.privReason=t,this.privErrorDetails=i,this.privProperties=n}get resultId(){return this.privResultId}get reason(){return this.privReason}get errorDetails(){return this.privErrorDetails}get properties(){return this.privProperties}}class Ve extends ti{constructor(e,t,i,n,s,o){super(e,t,n,s),this.privAudioData=i,this.privAudioDuration=o}get audioData(){return this.privAudioData}get audioDuration(){return this.privAudioDuration}}class je{constructor(e){this.privResult=e}get result(){return this.privResult}}class Yi{constructor(e,t,i,n,s,o){this.privAudioOffset=e,this.privDuration=t,this.privText=i,this.privWordLength=n,this.privTextOffset=s,this.privBoundaryType=o}get audioOffset(){return this.privAudioOffset}get duration(){return this.privDuration}get text(){return this.privText}get wordLength(){return this.privWordLength}get textOffset(){return this.privTextOffset}get boundaryType(){return this.privBoundaryType}}class er{constructor(e,t){this.privAudioOffset=e,this.privText=t}get audioOffset(){return this.privAudioOffset}get text(){return this.privText}}class tr{constructor(e,t,i){this.privAudioOffset=e,this.privVisemeId=t,this.privAnimation=i}get audioOffset(){return this.privAudioOffset}get visemeId(){return this.privVisemeId}get animation(){return this.privAnimation}}class ii extends ti{constructor(e,t,i){if(Array.isArray(t)){super(e,P.VoicesListRetrieved,void 0,new U),this.privVoices=[];for(const n of t)this.privVoices.push(new ir(n))}else super(e,P.Canceled,i||"Error information unavailable",new U)}get voices(){return this.privVoices}}var Ae;(function(r){r[r.Unknown=0]="Unknown",r[r.Female=1]="Female",r[r.Male=2]="Male"})(Ae||(Ae={}));var Fe;(function(r){r[r.OnlineNeural=1]="OnlineNeural",r[r.OnlineStandard=2]="OnlineStandard",r[r.OfflineNeural=3]="OfflineNeural",r[r.OfflineStandard=4]="OfflineStandard"})(Fe||(Fe={}));class ir{constructor(e){if(this.privStyleList=[],this.privVoicePath="",e&&(this.privName=e.Name,this.privLocale=e.Locale,this.privShortName=e.ShortName,this.privLocalName=e.LocalName,this.privVoiceType=e.VoiceType.endsWith("Standard")?Fe.OnlineStandard:Fe.OnlineNeural,this.privGender=e.Gender==="Male"?Ae.Male:e.Gender==="Female"?Ae.Female:Ae.Unknown,!!e.StyleList&&Array.isArray(e.StyleList)))for(const t of e.StyleList)this.privStyleList.push(t)}get name(){return this.privName}get locale(){return this.privLocale}get shortName(){return this.privShortName}get localName(){return this.privLocalName}get gender(){return this.privGender}get voiceType(){return this.privVoiceType}get styleList(){return this.privStyleList}get voicePath(){return this.privVoicePath}}var mt=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};const rr=60*30,ri={[v.PCM]:"audio/wav",[v.MuLaw]:"audio/x-wav",[v.MP3]:"audio/mpeg",[v.OGG_OPUS]:"audio/ogg",[v.WEBM_OPUS]:"audio/webm; codecs=opus",[v.ALaw]:"audio/x-wav",[v.FLAC]:"audio/flac"};class yt{constructor(e){this.privPlaybackStarted=!1,this.privAppendingToBuffer=!1,this.privMediaSourceOpened=!1,this.privBytesReceived=0,this.privId=e||E(),this.privIsPaused=!1,this.privIsClosed=!1}id(){return this.privId}write(e,t,i){this.privAudioBuffer!==void 0?(this.privAudioBuffer.push(e),this.updateSourceBuffer().then(()=>{t&&t()},n=>{i&&i(n)})):this.privAudioOutputStream!==void 0&&(this.privAudioOutputStream.write(e),this.privBytesReceived+=e.byteLength)}close(e,t){if(this.privIsClosed=!0,this.privSourceBuffer!==void 0)this.handleSourceBufferUpdateEnd().then(()=>{e&&e()},i=>{t&&t(i)});else if(this.privAudioOutputStream!==void 0&&typeof window!="undefined")if((this.privFormat.formatTag===v.PCM||this.privFormat.formatTag===v.MuLaw||this.privFormat.formatTag===v.ALaw)&&this.privFormat.hasHeader===!1)console.warn("Play back is not supported for raw PCM, mulaw or alaw format without header."),this.onAudioEnd&&this.onAudioEnd(this);else{let i=new ArrayBuffer(this.privBytesReceived);this.privAudioOutputStream.read(i).then(()=>{i=ne.addHeader(i,this.privFormat);const n=new Blob([i],{type:ri[this.privFormat.formatTag]});this.privAudio.src=window.URL.createObjectURL(n),this.notifyPlayback().then(()=>{e&&e()},s=>{t&&t(s)})},n=>{t&&t(n)})}else this.onAudioEnd&&this.onAudioEnd(this)}set format(e){if(typeof AudioContext!="undefined"||typeof window!="undefined"&&typeof window.webkitAudioContext!="undefined"){this.privFormat=e;const t=ri[this.privFormat.formatTag];t===void 0?console.warn(`Unknown mimeType for format ${v[this.privFormat.formatTag]}; playback is not supported.`):typeof MediaSource!="undefined"&&MediaSource.isTypeSupported(t)?(this.privAudio=new Audio,this.privAudioBuffer=[],this.privMediaSource=new MediaSource,this.privAudio.src=URL.createObjectURL(this.privMediaSource),this.privAudio.load(),this.privMediaSource.onsourceopen=()=>{this.privMediaSourceOpened=!0,this.privMediaSource.duration=rr,this.privSourceBuffer=this.privMediaSource.addSourceBuffer(t),this.privSourceBuffer.onupdate=()=>{this.updateSourceBuffer().catch(i=>{N.instance.onEvent(new Ee(i))})},this.privSourceBuffer.onupdateend=()=>{this.handleSourceBufferUpdateEnd().catch(i=>{N.instance.onEvent(new Ee(i))})},this.privSourceBuffer.onupdatestart=()=>{this.privAppendingToBuffer=!1}},this.updateSourceBuffer().catch(i=>{N.instance.onEvent(new Ee(i))})):(console.warn(`Format ${v[this.privFormat.formatTag]} could not be played by MSE, streaming playback is not enabled.`),this.privAudioOutputStream=new vt,this.privAudioOutputStream.format=this.privFormat,this.privAudio=new Audio)}}get volume(){var e,t;return(t=(e=this.privAudio)===null||e===void 0?void 0:e.volume)!==null&&t!==void 0?t:-1}set volume(e){this.privAudio&&(this.privAudio.volume=e)}mute(){this.privAudio&&(this.privAudio.muted=!0)}unmute(){this.privAudio&&(this.privAudio.muted=!1)}get isClosed(){return this.privIsClosed}get currentTime(){return this.privAudio!==void 0?this.privAudio.currentTime:-1}pause(){!this.privIsPaused&&this.privAudio!==void 0&&(this.privAudio.pause(),this.privIsPaused=!0)}resume(e,t){this.privIsPaused&&this.privAudio!==void 0&&(this.privAudio.play().then(()=>{e&&e()},i=>{t&&t(i)}),this.privIsPaused=!1)}get internalAudio(){return this.privAudio}updateSourceBuffer(){return mt(this,void 0,void 0,function*(){if(this.privAudioBuffer!==void 0&&this.privAudioBuffer.length>0&&this.sourceBufferAvailable()){this.privAppendingToBuffer=!0;const e=this.privAudioBuffer.shift();try{this.privSourceBuffer.appendBuffer(e)}catch{this.privAudioBuffer.unshift(e),console.log("buffer filled, pausing addition of binaries until space is made");return}yield this.notifyPlayback()}else this.canEndStream()&&(yield this.handleSourceBufferUpdateEnd())})}handleSourceBufferUpdateEnd(){return mt(this,void 0,void 0,function*(){this.canEndStream()&&this.sourceBufferAvailable()&&(this.privMediaSource.endOfStream(),yield this.notifyPlayback())})}notifyPlayback(){return mt(this,void 0,void 0,function*(){!this.privPlaybackStarted&&this.privAudio!==void 0&&(this.privPlaybackStarted=!0,this.onAudioStart&&this.onAudioStart(this),this.privAudio.onended=()=>{this.onAudioEnd&&this.onAudioEnd(this)},this.privIsPaused||(yield this.privAudio.play()))})}canEndStream(){return this.isClosed&&this.privSourceBuffer!==void 0&&this.privAudioBuffer.length===0&&this.privMediaSourceOpened&&!this.privAppendingToBuffer&&this.privMediaSource.readyState==="open"}sourceBufferAvailable(){return this.privSourceBuffer!==void 0&&!this.privSourceBuffer.updating}}class $e extends se{constructor(e,t,i,n=w.Info){super(e,n),this.privRequestId=t,this.privSessionId=i}get requestId(){return this.privRequestId}get sessionId(){return this.privSessionId}}class ni extends $e{constructor(e,t,i,n){super("RecognitionTriggeredEvent",e,t),this.privAudioSourceId=i,this.privAudioNodeId=n}get audioSourceId(){return this.privAudioSourceId}get audioNodeId(){return this.privAudioNodeId}}class nr extends $e{constructor(e,t,i,n){super("ListeningStartedEvent",e,t),this.privAudioSourceId=i,this.privAudioNodeId=n}get audioSourceId(){return this.privAudioSourceId}get audioNodeId(){return this.privAudioNodeId}}class si extends $e{constructor(e,t,i){super("ConnectingToServiceEvent",e,i),this.privAuthFetchEventid=t}get authFetchEventid(){return this.privAuthFetchEventid}}class sr extends $e{constructor(e,t,i,n,s){super("RecognitionStartedEvent",e,s),this.privAudioSourceId=t,this.privAudioNodeId=i,this.privAuthFetchEventId=n}get audioSourceId(){return this.privAudioSourceId}get audioNodeId(){return this.privAudioNodeId}get authFetchEventId(){return this.privAuthFetchEventId}}var oi;(function(r){r[r.Success=0]="Success",r[r.AudioSourceError=1]="AudioSourceError",r[r.AudioSourceTimeout=2]="AudioSourceTimeout",r[r.AuthTokenFetchError=3]="AuthTokenFetchError",r[r.AuthTokenFetchTimeout=4]="AuthTokenFetchTimeout",r[r.UnAuthorized=5]="UnAuthorized",r[r.ConnectTimeout=6]="ConnectTimeout",r[r.ConnectError=7]="ConnectError",r[r.ClientRecognitionActivityTimeout=8]="ClientRecognitionActivityTimeout",r[r.UnknownError=9]="UnknownError"})(oi||(oi={}));class O extends at{constructor(e,t,i,n,s,o,a,u){if(!t)throw new I("path");if(!i)throw new I("requestId");const h={};if(h[T.Path]=t,h[T.RequestId]=i,h[T.RequestTimestamp]=new Date().toISOString(),n&&(h[T.ContentType]=n),o&&(h[T.RequestStreamId]=o),a)for(const c in a)c&&(h[c]=a[c]);u?super(e,s,h,u):super(e,s,h),this.privPath=t,this.privRequestId=i,this.privContentType=n,this.privStreamId=o,this.privAdditionalHeaders=a}get path(){return this.privPath}get requestId(){return this.privRequestId}get contentType(){return this.privContentType}get streamId(){return this.privStreamId}get additionalHeaders(){return this.privAdditionalHeaders}static fromConnectionMessage(e){let t=null,i=null,n=null,s=null;const o={};if(e.headers)for(const a in e.headers)a&&(a.toLowerCase()===T.Path.toLowerCase()?t=e.headers[a]:a.toLowerCase()===T.RequestId.toLowerCase()?i=e.headers[a]:a.toLowerCase()===T.ContentType.toLowerCase()?n=e.headers[a]:a.toLowerCase()===T.RequestStreamId.toLowerCase()?s=e.headers[a]:o[a]=e.headers[a]);return new O(e.messageType,t,i,n,e.body,s,o,e.id)}}var k=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};class ${constructor(e,t,i,n,s){if(this.privConnectionConfigurationPromise=void 0,this.privConnectionPromise=void 0,this.privSetTimeout=setTimeout,this.privIsLiveAudio=!1,this.recognizeOverride=void 0,this.disconnectOverride=void 0,this.receiveMessageOverride=void 0,this.sendPrePayloadJSONOverride=void 0,this.postConnectImplOverride=void 0,this.configConnectionOverride=void 0,!e)throw new I("authentication");if(!t)throw new I("connectionFactory");if(!i)throw new I("audioSource");if(!n)throw new I("recognizerConfig");this.privMustReportEndOfStream=!1,this.privAuthentication=e,this.privConnectionFactory=t,this.privAudioSource=i,this.privRecognizerConfig=n,this.privIsDisposed=!1,this.privRecognizer=s,this.privRequestSession=new dr(this.privAudioSource.id()),this.privConnectionEvents=new j,this.privServiceEvents=new j,this.privDynamicGrammar=new lr,this.privSpeechContext=new vr(this.privDynamicGrammar),this.privAgentConfig=new di,typeof Blob!="undefined"&&typeof Worker!="undefined"&&(this.privSetTimeout=z.setTimeout),this.connectionEvents.attach(o=>{if(o.name==="ConnectionClosedEvent"){const a=o;(a.statusCode===1003||a.statusCode===1007||a.statusCode===1002||a.statusCode===4e3||this.privRequestSession.numConnectionAttempts>this.privRecognizerConfig.maxRetryCount)&&this.cancelRecognitionLocal(K.Error,a.statusCode===1007?R.BadRequestParameters:R.ConnectionFailure,`${a.reason} websocket error code: ${a.statusCode}`)}})}get audioSource(){return this.privAudioSource}get speechContext(){return this.privSpeechContext}get dynamicGrammar(){return this.privDynamicGrammar}get agentConfig(){return this.privAgentConfig}set conversationTranslatorToken(e){this.privRecognizerConfig.parameters.setProperty(p.ConversationTranslator_Token,e)}set authentication(e){this.privAuthentication=this.authentication}isDisposed(){return this.privIsDisposed}dispose(e){return k(this,void 0,void 0,function*(){if(this.privIsDisposed=!0,this.privConnectionConfigurationPromise!==void 0)try{yield(yield this.privConnectionConfigurationPromise).dispose(e)}catch{return}})}get connectionEvents(){return this.privConnectionEvents}get serviceEvents(){return this.privServiceEvents}get recognitionMode(){return this.privRecognizerConfig.recognitionMode}recognize(e,t,i){return k(this,void 0,void 0,function*(){if(this.recognizeOverride!==void 0){yield this.recognizeOverride(e,t,i);return}this.privConnectionConfigurationPromise=void 0,this.privRecognizerConfig.recognitionMode=e,this.privSuccessCallback=t,this.privErrorCallback=i,this.privRequestSession.startNewRecognition(),this.privRequestSession.listenForServiceTelemetry(this.privAudioSource.events);const n=this.connectImpl();let s;try{const u=yield this.audioSource.attach(this.privRequestSession.audioNodeId),h=yield this.audioSource.format,c=yield this.audioSource.deviceInfo;this.privIsLiveAudio=c.type&&c.type===ce.Microphones,s=new Rr(u,h.avgBytesPerSec),yield this.privRequestSession.onAudioSourceAttachCompleted(s,!1),this.privRecognizerConfig.SpeechServiceConfig.Context.audio={source:c}}catch(u){throw yield this.privRequestSession.onStopRecognizing(),u}try{yield n}catch(u){yield this.cancelRecognitionLocal(K.Error,R.ConnectionFailure,u);return}const o=new ve(this.privRequestSession.sessionId);this.privRecognizer.sessionStarted&&this.privRecognizer.sessionStarted(this.privRecognizer,o),this.receiveMessage(),this.sendAudio(s).catch(u=>k(this,void 0,void 0,function*(){yield this.cancelRecognitionLocal(K.Error,R.RuntimeError,u)}))})}stopRecognizing(){return k(this,void 0,void 0,function*(){if(this.privRequestSession.isRecognizing)try{yield this.audioSource.turnOff(),yield this.sendFinalAudio(),yield this.privRequestSession.onStopRecognizing(),yield this.privRequestSession.turnCompletionPromise}finally{yield this.privRequestSession.dispose()}})}connect(){return k(this,void 0,void 0,function*(){return yield this.connectImpl(),Promise.resolve()})}connectAsync(e,t){this.connectImpl().then(()=>{try{e&&e()}catch(i){t&&t(i)}},i=>{try{t&&t(i)}catch{}})}disconnect(){return k(this,void 0,void 0,function*(){if(yield this.cancelRecognitionLocal(K.Error,R.NoError,"Disconnecting"),this.disconnectOverride!==void 0&&(yield this.disconnectOverride()),this.privConnectionPromise!==void 0)try{yield(yield this.privConnectionPromise).dispose()}catch{}this.privConnectionPromise=void 0})}sendMessage(e){}sendNetworkMessage(e,t){return k(this,void 0,void 0,function*(){const i=typeof t=="string"?m.Text:m.Binary,n=typeof t=="string"?"application/json":"";return(yield this.fetchConnection()).send(new O(i,e,this.privRequestSession.requestId,n,t))})}set activityTemplate(e){this.privActivityTemplate=e}get activityTemplate(){return this.privActivityTemplate}sendTelemetryData(){return k(this,void 0,void 0,function*(){const e=this.privRequestSession.getTelemetry();if($.telemetryDataEnabled!==!0||this.privIsDisposed||e===null)return;if($.telemetryData)try{$.telemetryData(e)}catch{}yield(yield this.fetchConnection()).send(new O(m.Text,"telemetry",this.privRequestSession.requestId,"application/json",e))})}cancelRecognitionLocal(e,t,i){return k(this,void 0,void 0,function*(){this.privRequestSession.isRecognizing&&(yield this.privRequestSession.onStopRecognizing(),this.cancelRecognition(this.privRequestSession.sessionId,this.privRequestSession.requestId,e,t,i))})}receiveMessage(){return k(this,void 0,void 0,function*(){try{if(this.privIsDisposed)return;let e=yield this.fetchConnection();const t=yield e.read();if(this.receiveMessageOverride!==void 0)return this.receiveMessageOverride();if(!t)return this.privRequestSession.isRecognizing?this.receiveMessage():void 0;this.privServiceHasSentMessage=!0;const i=O.fromConnectionMessage(t);if(i.requestId.toLowerCase()===this.privRequestSession.requestId.toLowerCase())switch(i.path.toLowerCase()){case"turn.start":this.privMustReportEndOfStream=!0,this.privRequestSession.onServiceTurnStartResponse();break;case"speech.startdetected":const n=Xe.fromJSON(i.textBody),s=new ft(n.Offset,this.privRequestSession.sessionId);this.privRecognizer.speechStartDetected&&this.privRecognizer.speechStartDetected(this.privRecognizer,s);break;case"speech.enddetected":let o;i.textBody.length>0?o=i.textBody:o="{ Offset: 0 }";const a=Xe.fromJSON(o);this.privRecognizerConfig.isContinuousRecognition&&this.privRequestSession.onServiceRecognized(a.Offset+this.privRequestSession.currentTurnAudioOffset);const u=new ft(a.Offset+this.privRequestSession.currentTurnAudioOffset,this.privRequestSession.sessionId);this.privRecognizer.speechEndDetected&&this.privRecognizer.speechEndDetected(this.privRecognizer,u);break;case"turn.end":yield this.sendTelemetryData(),this.privRequestSession.isSpeechEnded&&this.privMustReportEndOfStream&&(this.privMustReportEndOfStream=!1,yield this.cancelRecognitionLocal(K.EndOfStream,R.NoError,void 0));const h=new ve(this.privRequestSession.sessionId);if(yield this.privRequestSession.onServiceTurnEndResponse(this.privRecognizerConfig.isContinuousRecognition),!this.privRecognizerConfig.isContinuousRecognition||this.privRequestSession.isSpeechEnded||!this.privRequestSession.isRecognizing){this.privRecognizer.sessionStopped&&this.privRecognizer.sessionStopped(this.privRecognizer,h);return}else e=yield this.fetchConnection(),yield this.sendPrePayloadJSON(e);break;default:(yield this.processTypeSpecificMessages(i))||this.privServiceEvents&&this.serviceEvents.onEvent(new Dt(i.path.toLowerCase(),i.textBody))}return this.receiveMessage()}catch{return null}})}sendSpeechContext(e,t){const i=this.speechContext.toJSON();if(t&&this.privRequestSession.onSpeechContext(),i)return e.send(new O(m.Text,"speech.context",this.privRequestSession.requestId,"application/json",i))}sendPrePayloadJSON(e,t=!0){return k(this,void 0,void 0,function*(){if(this.sendPrePayloadJSONOverride!==void 0)return this.sendPrePayloadJSONOverride(e);yield this.sendSpeechContext(e,t),yield this.sendWaveHeader(e)})}sendWaveHeader(e){return k(this,void 0,void 0,function*(){const t=yield this.audioSource.format;return e.send(new O(m.Binary,"audio",this.privRequestSession.requestId,"audio/x-wav",t.header))})}connectImpl(){return this.privConnectionPromise!==void 0?this.privConnectionPromise.then(e=>e.state()===M.Disconnected?(this.privConnectionId=null,this.privConnectionPromise=void 0,this.privServiceHasSentMessage=!1,this.connectImpl()):this.privConnectionPromise,()=>(this.privConnectionId=null,this.privConnectionPromise=void 0,this.privServiceHasSentMessage=!1,this.connectImpl())):(this.privConnectionPromise=this.retryableConnect(),this.privConnectionPromise.catch(()=>{}),this.postConnectImplOverride!==void 0?this.postConnectImplOverride(this.privConnectionPromise):this.privConnectionPromise)}sendSpeechServiceConfig(e,t,i){if(t.onSpeechContext(),$.telemetryDataEnabled!==!0){const s={context:{system:JSON.parse(i).context.system}};i=JSON.stringify(s)}if(this.privRecognizerConfig.parameters.getProperty("TranscriptionService_SingleChannel","false").toLowerCase()==="true"){const n=JSON.parse(i);n.context.DisableReferenceChannel="True",n.context.MicSpec="1_0_0",i=JSON.stringify(n)}if(i)return e.send(new O(m.Text,"speech.config",t.requestId,"application/json",i))}fetchConnection(){return k(this,void 0,void 0,function*(){return this.privConnectionConfigurationPromise!==void 0?this.privConnectionConfigurationPromise.then(e=>e.state()===M.Disconnected?(this.privConnectionId=null,this.privConnectionConfigurationPromise=void 0,this.privServiceHasSentMessage=!1,this.fetchConnection()):this.privConnectionConfigurationPromise,()=>(this.privConnectionId=null,this.privConnectionConfigurationPromise=void 0,this.privServiceHasSentMessage=!1,this.fetchConnection())):(this.privConnectionConfigurationPromise=this.configureConnection(),yield this.privConnectionConfigurationPromise)})}sendAudio(e){return k(this,void 0,void 0,function*(){const t=yield this.audioSource.format;let i=Date.now();const n=this.privRecognizerConfig.parameters.getProperty("SPEECH-TransmitLengthBeforThrottleMs","5000"),s=t.avgBytesPerSec/1e3*parseInt(n,10),o=this.privRequestSession.recogNumber,a=()=>k(this,void 0,void 0,function*(){if(!this.privIsDisposed&&!this.privRequestSession.isSpeechEnded&&this.privRequestSession.isRecognizing&&this.privRequestSession.recogNumber===o){const u=yield this.fetchConnection(),h=yield e.read();if(this.privRequestSession.isSpeechEnded)return;let c,d;if(!h||h.isEnd?(c=null,d=0):(c=h.buffer,this.privRequestSession.onAudioSent(c.byteLength),s>=this.privRequestSession.bytesSent?d=0:d=Math.max(0,i-Date.now())),d!==0&&(yield this.delay(d)),c!==null&&(i=Date.now()+c.byteLength*1e3/(t.avgBytesPerSec*2)),!this.privIsDisposed&&!this.privRequestSession.isSpeechEnded&&this.privRequestSession.isRecognizing&&this.privRequestSession.recogNumber===o)if(u.send(new O(m.Binary,"audio",this.privRequestSession.requestId,null,c)).catch(()=>{this.privRequestSession.onServiceTurnEndResponse(this.privRecognizerConfig.isContinuousRecognition).catch(()=>{})}),h!=null&&h.isEnd)this.privIsLiveAudio||this.privRequestSession.onSpeechEnded();else return a()}});return a()})}retryableConnect(){return k(this,void 0,void 0,function*(){let e=!1;this.privAuthFetchEventId=E();const t=this.privRequestSession.sessionId;this.privConnectionId=t!==void 0?t:E(),this.privRequestSession.onPreConnectionStart(this.privAuthFetchEventId,this.privConnectionId);let i=0,n="";for(;this.privRequestSession.numConnectionAttempts<=this.privRecognizerConfig.maxRetryCount;){const o=yield e?this.privAuthentication.fetchOnExpiry(this.privAuthFetchEventId):this.privAuthentication.fetch(this.privAuthFetchEventId);yield this.privRequestSession.onAuthCompleted(!1);const a=this.privConnectionFactory.create(this.privRecognizerConfig,o,this.privConnectionId);this.privRequestSession.listenForServiceTelemetry(a.events),a.events.attach(h=>{this.connectionEvents.onEvent(h)});const u=yield a.open();if(u.statusCode===200)return yield this.privRequestSession.onConnectionEstablishCompleted(u.statusCode),Promise.resolve(a);u.statusCode===1006&&(e=!0),i=u.statusCode,n=u.reason,this.privRequestSession.onRetryConnection()}return yield this.privRequestSession.onConnectionEstablishCompleted(i,n),Promise.reject(`Unable to contact server. StatusCode: ${i}, ${this.privRecognizerConfig.parameters.getProperty(p.SpeechServiceConnection_Endpoint)} Reason: ${n}`)})}delay(e){return new Promise(t=>this.privSetTimeout(t,e))}writeBufferToConsole(e){let t="Buffer Size: ";if(e===null)t+="null";else{const i=new Uint8Array(e);t+=`${e.byteLength}\r
3
- `;for(let n=0;n<e.byteLength;n++)t+=i[n].toString(16).padStart(2,"0")+" "}console.info(t)}sendFinalAudio(){return k(this,void 0,void 0,function*(){yield(yield this.fetchConnection()).send(new O(m.Binary,"audio",this.privRequestSession.requestId,null,null))})}configureConnection(){return k(this,void 0,void 0,function*(){const e=yield this.connectImpl();return this.configConnectionOverride!==void 0?this.configConnectionOverride(e):(yield this.sendSpeechServiceConfig(e,this.privRequestSession,this.privRecognizerConfig.SpeechServiceConfig.serialize()),yield this.sendPrePayloadJSON(e,!1),e)})}}$.telemetryDataEnabled=!0;var ae;(function(r){r[r.Interactive=0]="Interactive",r[r.Conversation=1]="Conversation",r[r.Dictation=2]="Dictation"})(ae||(ae={}));var ai;(function(r){r[r.Simple=0]="Simple",r[r.Detailed=1]="Detailed"})(ai||(ai={}));class or{constructor(e,t){this.privSpeechServiceConfig=e||new Ge(new Je(null)),this.privParameters=t,this.privMaxRetryCount=parseInt(t.getProperty("SPEECH-Error-MaxRetryCount","4"),10),this.privLanguageIdPriority=t.getProperty(p.SpeechServiceConnection_ContinuousLanguageIdPriority,void 0),this.privLanguageIdMode=this.privLanguageIdPriority==="Latency"?"DetectContinuous":"DetectAtAudioStart",this.privLanguageIdMode==="DetectAtAudioStart"&&(this.privLanguageIdPriority=t.getProperty(p.SpeechServiceConnection_AtStartLanguageIdPriority,void 0))}get parameters(){return this.privParameters}get recognitionMode(){return this.privRecognitionMode}set recognitionMode(e){this.privRecognitionMode=e,this.privRecognitionActivityTimeout=e===ae.Interactive?8e3:25e3,this.privSpeechServiceConfig.Recognition=ae[e]}get SpeechServiceConfig(){return this.privSpeechServiceConfig}get recognitionActivityTimeout(){return this.privRecognitionActivityTimeout}get isContinuousRecognition(){return this.privRecognitionMode!==ae.Interactive}get languageIdPriority(){return this.privLanguageIdPriority?`Prioritize${this.privLanguageIdPriority}`:""}get languageIdMode(){return this.privLanguageIdMode}get autoDetectSourceLanguages(){return this.parameters.getProperty(p.SpeechServiceConnection_AutoDetectSourceLanguages,void 0)}get recognitionEndpointVersion(){return this.parameters.getProperty(p.SpeechServiceConnection_RecognitionEndpointVersion,void 0)}get sourceLanguageModels(){const e=[];let t=!1;if(this.autoDetectSourceLanguages!==void 0)for(const i of this.autoDetectSourceLanguages.split(",")){const n=i+p.SpeechServiceConnection_EndpointId.toString(),s=this.parameters.getProperty(n,void 0);s!==void 0?(e.push({language:i,endpoint:s}),t=!0):e.push({language:i,endpoint:""})}return t?e:void 0}get maxRetryCount(){return this.privMaxRetryCount}}class Ge{constructor(e){this.context=e}serialize(){return JSON.stringify(this,(e,t)=>{if(t&&typeof t=="object"){const i={};for(const n in t)Object.hasOwnProperty.call(t,n)&&(i[n&&n.charAt(0).toLowerCase()+n.substring(1)]=t[n]);return i}return t})}get Context(){return this.context}get Recognition(){return this.recognition}set Recognition(e){this.recognition=e.toLowerCase()}}class Je{constructor(e){this.system=new ar,this.os=e}}class ar{constructor(){const e="1.22.0";this.name="SpeechSDK",this.version=e,this.build="JavaScript",this.lang="JavaScript"}}class ci{constructor(e,t,i){this.platform=e,this.name=t,this.version=i}}var fe;(function(r){r.Bluetooth="Bluetooth",r.Wired="Wired",r.WiFi="WiFi",r.Cellular="Cellular",r.InBuilt="InBuilt",r.Unknown="Unknown"})(fe||(fe={}));var ce;(function(r){r.Phone="Phone",r.Speaker="Speaker",r.Car="Car",r.Headset="Headset",r.Thermostat="Thermostat",r.Microphones="Microphones",r.Deskphone="Deskphone",r.RemoteControl="RemoteControl",r.Unknown="Unknown",r.File="File",r.Stream="Stream"})(ce||(ce={}));const hi=`\r
4
- `;class ui{toConnectionMessage(e){const t=new D;try{if(e.messageType===m.Text){const i=e.textContent;let n={},s=null;if(i){const o=i.split(`\r
1
+ (function(M,K){typeof exports=="object"&&typeof module!="undefined"?K(exports):typeof define=="function"&&define.amd?define(["exports"],K):(M=typeof globalThis!="undefined"?globalThis:M||self,K(M.CreativeOrangeAzureTextToSpeech={}))})(this,function(M){"use strict";function Z(r){var s;const e=typeof r.tokenEndpoint=="string"&&r.tokenEndpoint.trim()!=="",t=typeof r.getAuthorizationToken=="function";if(e&&t)throw new Error("Provide either tokenEndpoint or getAuthorizationToken, not both.");if(!e&&!t)throw new Error("A tokenEndpoint or getAuthorizationToken provider is required.");if(t)return r.getAuthorizationToken;const i=r.tokenEndpoint.trim(),n=(s=r.tokenRequestOptions)!=null?s:{};return async()=>{var u,h,c;let o;try{o=await fetch(i,{method:"GET",cache:(u=n.cache)!=null?u:"no-store",credentials:(h=n.credentials)!=null?h:"same-origin",headers:{Accept:"application/json",...(c=n.headers)!=null?c:{}}})}catch{throw se("Could not reach the speech token endpoint.","TOKEN_ENDPOINT_UNREACHABLE")}if(!o.ok)throw se(`Speech token endpoint returned HTTP ${o.status}.`,"TOKEN_ENDPOINT_HTTP_ERROR");let a;try{a=await o.json()}catch{throw se("Speech token endpoint returned invalid JSON.","TOKEN_ENDPOINT_INVALID_JSON")}return ct(a)}}function ct(r){if(!r||typeof r!="object")throw se("Speech authorization response must be an object.","TOKEN_INVALID_RESPONSE");const e=r,t=typeof e.token=="string"?e.token.trim():"",i=typeof e.region=="string"?e.region.trim():"";if(t==="")throw se("Speech authorization token is missing or empty.","TOKEN_EMPTY");if(i==="")throw se("Speech authorization region is missing or empty.","TOKEN_REGION_MISSING");return{token:t,region:i}}function se(r,e){const t=new Error(we(r));return t.message=we(r),e&&(t.code=e),t}function ye(r){if(typeof r=="string")return{message:r.trim()!==""?we(r):"An unexpected speech error occurred."};if(r&&typeof r=="object"){const e=r,t=[typeof e.message=="string"?e.message:"",typeof e.errorDetails=="string"?e.errorDetails:"",typeof e.reason=="string"?e.reason:""].filter(s=>s.trim()!=="").join(" "),n={message:t!==""?we(t):"An unexpected speech error occurred."};return typeof e.code=="string"&&e.code.trim()!==""?n.code=e.code:typeof e.code=="number"&&(n.code=String(e.code)),n}return{message:"An unexpected speech error occurred."}}function we(r){return r.replace(/Authorization\s*:\s*Bearer\s+\S+/gi,"Authorization: Bearer [redacted]").replace(/Bearer\s+\S+/gi,"Bearer [redacted]").replace(/authorization[_-]?token["']?\s*[:=]\s*["']?[^"',\s}]+/gi,"authorizationToken=[redacted]").replace(/access[_-]?token["']?\s*[:=]\s*["']?[^"',\s}]+/gi,"accessToken=[redacted]").replace(/["']token["']\s*:\s*["'][^"']+["']/gi,'"token":"[redacted]"').replace(/token["']?\s*[:=]\s*["']?[^"',\s}]+/gi,"token=[redacted]")}function oe(r){var i;const e=ye(r),t=`${e.message} ${(i=e.code)!=null?i:""}`.toLowerCase();return t.includes("unauthorized")||t.includes("authentication")||t.includes("authorization")||t.includes("invalid token")||t.includes("token expired")||t.includes("expired token")||t.includes("403")||t.includes("401")||e.code==="TOKEN_REFRESH_ERROR"}class ht{constructor(e){m(this,"authorization");m(this,"authorizationExpiresAt",0);m(this,"authorizationRequest");m(this,"provider");m(this,"tokenLifetimeMs");this.provider=Z(e),this.tokenLifetimeMs=e.tokenLifetimeMs&&e.tokenLifetimeMs>0?e.tokenLifetimeMs:48e4}getTokenLifetimeMs(){return this.tokenLifetimeMs}async getAuthorization(){return this.authorization&&Date.now()<this.authorizationExpiresAt?this.authorization:this.authorizationRequest?this.authorizationRequest:(this.authorizationRequest=this.fetchAuthorization().then(e=>(this.authorization=e,this.authorizationExpiresAt=Date.now()+this.tokenLifetimeMs,e)).finally(()=>{this.authorizationRequest=void 0}),this.authorizationRequest)}async refreshAuthorization(){return this.authorization=void 0,this.authorizationExpiresAt=0,this.authorizationRequest?this.authorizationRequest:this.getAuthorization()}clearAuthorization(){this.authorization=void 0,this.authorizationExpiresAt=0}async fetchAuthorization(){try{const e=await this.provider();return ct(e)}catch(e){this.clearAuthorization();const t=ye(e);throw se(t.message,t.code)}}}var Oe={},Be,Ri=new Uint8Array(16);function Ai(){if(!Be&&(Be=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto!="undefined"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!Be))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Be(Ri)}var Pi=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function Ii(r){return typeof r=="string"&&Pi.test(r)}for(var N=[],ut=0;ut<256;++ut)N.push((ut+256).toString(16).substr(1));function Mi(r){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,t=(N[r[e+0]]+N[r[e+1]]+N[r[e+2]]+N[r[e+3]]+"-"+N[r[e+4]]+N[r[e+5]]+"-"+N[r[e+6]]+N[r[e+7]]+"-"+N[r[e+8]]+N[r[e+9]]+"-"+N[r[e+10]]+N[r[e+11]]+N[r[e+12]]+N[r[e+13]]+N[r[e+14]]+N[r[e+15]]).toLowerCase();if(!Ii(t))throw TypeError("Stringified UUID is invalid");return t}function zi(r,e,t){r=r||{};var i=r.random||(r.rng||Ai)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,e){t=t||0;for(var n=0;n<16;++n)e[t+n]=i[n];return e}return Mi(i)}const ki=()=>zi(),R=()=>ki().replace(new RegExp("-","g"),"").toUpperCase();var w;(function(r){r[r.Debug=0]="Debug",r[r.Info=1]="Info",r[r.Warning=2]="Warning",r[r.Error=3]="Error",r[r.None=4]="None"})(w||(w={}));class ae{constructor(e,t){this.privName=e,this.privEventId=R(),this.privEventTime=new Date().toISOString(),this.privEventType=t,this.privMetadata={}}get name(){return this.privName}get eventId(){return this.privEventId}get eventTime(){return this.privEventTime}get eventType(){return this.privEventType}get metadata(){return this.privMetadata}}class Ce extends ae{constructor(e,t,i=w.Info){super(e,i),this.privAudioSourceId=t}get audioSourceId(){return this.privAudioSourceId}}class _e extends Ce{constructor(e){super("AudioSourceInitializingEvent",e)}}class Ee extends Ce{constructor(e){super("AudioSourceReadyEvent",e)}}class Bt extends Ce{constructor(e){super("AudioSourceOffEvent",e)}}class He extends Ce{constructor(e,t){super("AudioSourceErrorEvent",e,w.Error),this.privError=t}get error(){return this.privError}}class Ke extends Ce{constructor(e,t,i){super(e,t),this.privAudioNodeId=i}get audioNodeId(){return this.privAudioNodeId}}class Te extends Ke{constructor(e,t){super("AudioStreamNodeAttachingEvent",e,t)}}class be extends Ke{constructor(e,t){super("AudioStreamNodeAttachedEvent",e,t)}}class $ extends Ke{constructor(e,t){super("AudioStreamNodeDetachedEvent",e,t)}}class pt extends Ke{constructor(e,t,i){super("AudioStreamNodeErrorEvent",e,t),this.privError=i}get error(){return this.privError}}class _t extends ae{constructor(e,t,i=w.Info){super(e,i),this.privJsonResult=t}get jsonString(){return this.privJsonResult}}class ce extends ae{constructor(e,t,i=w.Info){super(e,i),this.privConnectionId=t}get connectionId(){return this.privConnectionId}}class Ht extends ce{constructor(e,t,i){super("ConnectionStartEvent",e),this.privUri=t,this.privHeaders=i}get uri(){return this.privUri}get headers(){return this.privHeaders}}class Kt extends ce{constructor(e){super("ConnectionEstablishedEvent",e)}}class Di extends ce{constructor(e,t,i){super("ConnectionClosedEvent",e,w.Debug),this.privReason=i,this.privStatusCode=t}get reason(){return this.privReason}get statusCode(){return this.privStatusCode}}class xi extends ce{constructor(e,t,i){super("ConnectionErrorEvent",e,w.Debug),this.privMessage=t,this.privType=i}get message(){return this.privMessage}get type(){return this.privType}}class Ni extends ce{constructor(e,t,i){super("ConnectionEstablishErrorEvent",e,w.Error),this.privStatusCode=t,this.privReason=i}get reason(){return this.privReason}get statusCode(){return this.privStatusCode}}class dt extends ce{constructor(e,t,i){super("ConnectionMessageReceivedEvent",e),this.privNetworkReceivedTime=t,this.privMessage=i}get networkReceivedTime(){return this.privNetworkReceivedTime}get message(){return this.privMessage}}class Li extends ce{constructor(e,t,i){super("ConnectionMessageSentEvent",e),this.privNetworkSentTime=t,this.privMessage=i}get networkSentTime(){return this.privNetworkSentTime}get message(){return this.privMessage}}class z extends Error{constructor(e){super(e),this.name="ArgumentNull",this.message=e}}class q extends Error{constructor(e){super(e),this.name="InvalidOperation",this.message=e}}class vt extends Error{constructor(e,t){super(t),this.name=e+"ObjectDisposed",this.message=t}}var y;(function(r){r[r.Text=0]="Text",r[r.Binary=1]="Binary"})(y||(y={}));class lt{constructor(e,t,i,n){if(this.privBody=null,e===y.Text&&t&&typeof t!="string")throw new q("Payload must be a string");if(e===y.Binary&&t&&!(t instanceof ArrayBuffer))throw new q("Payload must be ArrayBuffer");switch(this.privMessageType=e,this.privBody=t,this.privHeaders=i||{},this.privId=n||R(),this.messageType){case y.Binary:this.privSize=this.binaryBody!==null?this.binaryBody.byteLength:0;break;case y.Text:this.privSize=this.textBody.length}}get messageType(){return this.privMessageType}get headers(){return this.privHeaders}get body(){return this.privBody}get textBody(){if(this.privMessageType===y.Binary)throw new q("Not supported for binary message");return this.privBody}get binaryBody(){if(this.privMessageType===y.Text)throw new q("Not supported for text message");return this.privBody}get id(){return this.privId}}class ft{constructor(e,t){this.privStatusCode=e,this.privReason=t}get statusCode(){return this.privStatusCode}get reason(){return this.privReason}}class F{constructor(e){this.privEventListeners={},this.privIsDisposed=!1,this.privConsoleListener=void 0,this.privMetadata=e}onEvent(e){if(this.isDisposed())throw new vt("EventSource");if(this.metadata)for(const t in this.metadata)t&&e.metadata&&(e.metadata[t]||(e.metadata[t]=this.metadata[t]));for(const t in this.privEventListeners)t&&this.privEventListeners[t]&&this.privEventListeners[t](e)}attach(e){const t=R();return this.privEventListeners[t]=e,{detach:()=>(delete this.privEventListeners[t],Promise.resolve())}}attachListener(e){return this.attach(t=>e.onEvent(t))}attachConsoleListener(e){return this.privConsoleListener&&this.privConsoleListener.detach(),this.privConsoleListener=this.attach(t=>e.onEvent(t)),this.privConsoleListener}isDisposed(){return this.privIsDisposed}dispose(){this.privEventListeners=null,this.privIsDisposed=!0}get metadata(){return this.privMetadata}}class L{static setEventSource(e){if(!e)throw new z("eventSource");L.privInstance=e}static get instance(){return L.privInstance}}L.privInstance=new F;var k;(function(r){r[r.None=0]="None",r[r.Connected=1]="Connected",r[r.Connecting=2]="Connecting",r[r.Disconnected=3]="Disconnected"})(k||(k={}));class j{constructor(e){if(this.privSubscriptionIdCounter=0,this.privAddSubscriptions={},this.privRemoveSubscriptions={},this.privDisposedSubscriptions={},this.privDisposeReason=null,this.privList=[],e)for(const t of e)this.privList.push(t)}get(e){return this.throwIfDisposed(),this.privList[e]}first(){return this.get(0)}last(){return this.get(this.length()-1)}add(e){this.throwIfDisposed(),this.insertAt(this.privList.length,e)}insertAt(e,t){this.throwIfDisposed(),e===0?this.privList.unshift(t):e===this.privList.length?this.privList.push(t):this.privList.splice(e,0,t),this.triggerSubscriptions(this.privAddSubscriptions)}removeFirst(){return this.throwIfDisposed(),this.removeAt(0)}removeLast(){return this.throwIfDisposed(),this.removeAt(this.length()-1)}removeAt(e){return this.throwIfDisposed(),this.remove(e,1)[0]}remove(e,t){this.throwIfDisposed();const i=this.privList.splice(e,t);return this.triggerSubscriptions(this.privRemoveSubscriptions),i}clear(){this.throwIfDisposed(),this.remove(0,this.length())}length(){return this.throwIfDisposed(),this.privList.length}onAdded(e){this.throwIfDisposed();const t=this.privSubscriptionIdCounter++;return this.privAddSubscriptions[t]=e,{detach:()=>(delete this.privAddSubscriptions[t],Promise.resolve())}}onRemoved(e){this.throwIfDisposed();const t=this.privSubscriptionIdCounter++;return this.privRemoveSubscriptions[t]=e,{detach:()=>(delete this.privRemoveSubscriptions[t],Promise.resolve())}}onDisposed(e){this.throwIfDisposed();const t=this.privSubscriptionIdCounter++;return this.privDisposedSubscriptions[t]=e,{detach:()=>(delete this.privDisposedSubscriptions[t],Promise.resolve())}}join(e){return this.throwIfDisposed(),this.privList.join(e)}toArray(){const e=Array();return this.privList.forEach(t=>{e.push(t)}),e}any(e){return this.throwIfDisposed(),e?this.where(e).length()>0:this.length()>0}all(e){return this.throwIfDisposed(),this.where(e).length()===this.length()}forEach(e){this.throwIfDisposed();for(let t=0;t<this.length();t++)e(this.privList[t],t)}select(e){this.throwIfDisposed();const t=[];for(let i=0;i<this.privList.length;i++)t.push(e(this.privList[i],i));return new j(t)}where(e){this.throwIfDisposed();const t=new j;for(let i=0;i<this.privList.length;i++)e(this.privList[i],i)&&t.add(this.privList[i]);return t}orderBy(e){this.throwIfDisposed();const i=this.toArray().sort(e);return new j(i)}orderByDesc(e){return this.throwIfDisposed(),this.orderBy((t,i)=>e(i,t))}clone(){return this.throwIfDisposed(),new j(this.toArray())}concat(e){return this.throwIfDisposed(),new j(this.privList.concat(e.toArray()))}concatArray(e){return this.throwIfDisposed(),new j(this.privList.concat(e))}isDisposed(){return this.privList==null}dispose(e){this.isDisposed()||(this.privDisposeReason=e,this.privList=null,this.privAddSubscriptions=null,this.privRemoveSubscriptions=null,this.triggerSubscriptions(this.privDisposedSubscriptions))}throwIfDisposed(){if(this.isDisposed())throw new vt("List",this.privDisposeReason)}triggerSubscriptions(e){if(e)for(const t in e)t&&e[t]()}}var qt;(function(r){r[r.None=0]="None",r[r.Resolved=1]="Resolved",r[r.Rejected=2]="Rejected"})(qt||(qt={}));class D{constructor(){this.resolve=e=>(this.privResolve(e),this),this.reject=e=>(this.privReject(e),this),this.privPromise=new Promise((e,t)=>{this.privResolve=e,this.privReject=t})}get promise(){return this.privPromise}}function J(r,e,t){r.then(i=>{try{e&&e(i)}catch(n){if(t)try{if(n instanceof Error){const s=n;t(s.name+": "+s.message)}else t(n)}catch{}}},i=>{if(t)try{if(i instanceof Error){const n=i;t(n.name+": "+n.message)}else t(i)}catch{}})}var Ut=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})},Re;(function(r){r[r.Dequeue=0]="Dequeue",r[r.Peek=1]="Peek"})(Re||(Re={}));class Ae{constructor(e){this.privPromiseStore=new j,this.privIsDrainInProgress=!1,this.privIsDisposing=!1,this.privDisposeReason=null,this.privList=e||new j,this.privDetachables=[],this.privSubscribers=new j,this.privDetachables.push(this.privList.onAdded(()=>this.drain()))}enqueue(e){this.throwIfDispose(),this.enqueueFromPromise(new Promise(t=>t(e)))}enqueueFromPromise(e){this.throwIfDispose(),e.then(t=>{this.privList.add(t)},()=>{})}dequeue(){this.throwIfDispose();const e=new D;return this.privSubscribers&&(this.privSubscribers.add({deferral:e,type:Re.Dequeue}),this.drain()),e.promise}peek(){this.throwIfDispose();const e=new D;return this.privSubscribers&&(this.privSubscribers.add({deferral:e,type:Re.Peek}),this.drain()),e.promise}length(){return this.throwIfDispose(),this.privList.length()}isDisposed(){return this.privSubscribers==null}drainAndDispose(e,t){return Ut(this,void 0,void 0,function*(){if(!this.isDisposed()&&!this.privIsDisposing){this.privDisposeReason=t,this.privIsDisposing=!0;const i=this.privSubscribers;if(i){for(;i.length()>0;)i.removeFirst().deferral.resolve(void 0);this.privSubscribers===i&&(this.privSubscribers=i)}for(const n of this.privDetachables)yield n.detach();if(this.privPromiseStore.length()>0&&e){const n=[];return this.privPromiseStore.toArray().forEach(s=>{n.push(s)}),Promise.all(n).finally(()=>{this.privSubscribers=null,this.privList.forEach(s=>{e(s)}),this.privList=null}).then()}else this.privSubscribers=null,this.privList=null}})}dispose(e){return Ut(this,void 0,void 0,function*(){yield this.drainAndDispose(null,e)})}drain(){if(!this.privIsDrainInProgress&&!this.privIsDisposing){this.privIsDrainInProgress=!0;const e=this.privSubscribers,t=this.privList;if(e&&t){for(;t.length()>0&&e.length()>0&&!this.privIsDisposing;){const i=e.removeFirst();if(i.type===Re.Peek)i.deferral.resolve(t.first());else{const n=t.removeFirst();i.deferral.resolve(n)}}this.privSubscribers===e&&(this.privSubscribers=e),this.privList===t&&(this.privList=t)}this.privIsDrainInProgress=!1}}throwIfDispose(){if(this.isDisposed())throw this.privDisposeReason?new q(this.privDisposeReason):new vt("Queue");if(this.privIsDisposing)throw new q("Queue disposing")}}class qe{constructor(e,t,i){if(this.privPayload=null,!t)throw new z("payload");if(e===y.Binary&&t.__proto__.constructor.name!=="ArrayBuffer")throw new q("Payload must be ArrayBuffer");if(e===y.Text&&typeof t!="string")throw new q("Payload must be a string");this.privMessageType=e,this.privPayload=t,this.privId=i||R()}get messageType(){return this.privMessageType}get payload(){return this.privPayload}get textContent(){if(this.privMessageType===y.Binary)throw new q("Not supported for binary message");return this.privPayload}get binaryContent(){if(this.privMessageType===y.Text)throw new q("Not supported for text message");return this.privPayload}get id(){return this.privId}}class Oi{constructor(e,t){this.privActualSampleRate=e,this.privDesiredSampleRate=t}encode(e){const t=this.downSampleAudioFrame(e,this.privActualSampleRate,this.privDesiredSampleRate);if(!t)return null;const i=t.length*2,n=new ArrayBuffer(i),s=new DataView(n);return this.floatTo16BitPCM(s,0,t),n}setString(e,t,i){for(let n=0;n<i.length;n++)e.setUint8(t+n,i.charCodeAt(n))}floatTo16BitPCM(e,t,i){for(let n=0;n<i.length;n++,t+=2){const s=Math.max(-1,Math.min(1,i[n]));e.setInt16(t,s<0?s*32768:s*32767,!0)}}downSampleAudioFrame(e,t,i){if(!e)return null;if(i===t||i>t)return e;const n=t/i,s=Math.round(e.length/n),o=new Float32Array(s);let a=0,u=0;for(;u<s;){const h=Math.round((u+1)*n);let c=0,d=0;for(;a<h&&a<e.length;)c+=e[a++],d++;o[u++]=c/d}return o}}var Bi=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};class Wt{constructor(e){this.privIsWriteEnded=!1,this.privIsReadEnded=!1,this.privId=e||R(),this.privReaderQueue=new Ae}get isClosed(){return this.privIsWriteEnded}get isReadEnded(){return this.privIsReadEnded}get id(){return this.privId}close(){this.privIsWriteEnded||(this.writeStreamChunk({buffer:null,isEnd:!0,timeReceived:Date.now()}),this.privIsWriteEnded=!0)}writeStreamChunk(e){if(this.throwIfClosed(),!this.privReaderQueue.isDisposed())try{this.privReaderQueue.enqueue(e)}catch{}}read(){if(this.privIsReadEnded)throw new q("Stream read has already finished");return this.privReaderQueue.dequeue().then(e=>Bi(this,void 0,void 0,function*(){return(e===void 0||e.isEnd)&&(yield this.privReaderQueue.dispose("End of stream reached")),e}))}readEnded(){this.privIsReadEnded||(this.privIsReadEnded=!0,this.privReaderQueue=new Ae)}throwIfClosed(){if(this.privIsWriteEnded)throw new q("Stream closed")}}var Pe;(function(r){r[r.Success=0]="Success",r[r.Error=1]="Error"})(Pe||(Pe={}));class gt extends Wt{constructor(e,t){super(t),this.privTargetChunkSize=e,this.privNextBufferReadyBytes=0}writeStreamChunk(e){if(e.isEnd||this.privNextBufferReadyBytes===0&&e.buffer.byteLength===this.privTargetChunkSize){super.writeStreamChunk(e);return}let t=0;for(;t<e.buffer.byteLength;){this.privNextBufferToWrite===void 0&&(this.privNextBufferToWrite=new ArrayBuffer(this.privTargetChunkSize),this.privNextBufferStartTime=e.timeReceived);const i=Math.min(e.buffer.byteLength-t,this.privTargetChunkSize-this.privNextBufferReadyBytes),n=new Uint8Array(this.privNextBufferToWrite),s=new Uint8Array(e.buffer.slice(t,i+t));n.set(s,this.privNextBufferReadyBytes),this.privNextBufferReadyBytes+=i,t+=i,this.privNextBufferReadyBytes===this.privTargetChunkSize&&(super.writeStreamChunk({buffer:this.privNextBufferToWrite,isEnd:!1,timeReceived:this.privNextBufferStartTime}),this.privNextBufferReadyBytes=0,this.privNextBufferToWrite=void 0)}}close(){this.privNextBufferReadyBytes!==0&&!this.isClosed&&super.writeStreamChunk({buffer:this.privNextBufferToWrite.slice(0,this.privNextBufferReadyBytes),isEnd:!1,timeReceived:this.privNextBufferStartTime}),super.close()}}class O{static load(e){const t=new Map([[0,()=>{}]]),i=new Map,n=new Worker(e);return n.addEventListener("message",({data:a})=>{if(O.isCallNotification(a)){const{params:{timerId:u}}=a,h=t.get(u);if(typeof h=="number"){const c=i.get(h);if(c===void 0||c!==u)throw new Error("The timer is in an undefined state.")}else if(typeof h!="undefined")h(),t.delete(u);else throw new Error("The timer is in an undefined state.")}else if(O.isClearResponse(a)){const{id:u}=a,h=i.get(u);if(h===void 0)throw new Error("The timer is in an undefined state.");i.delete(u),t.delete(h)}else{const{error:{message:u}}=a;throw new Error(u)}}),{clearTimeout:a=>{const u=Math.random();i.set(u,a),t.set(a,u),n.postMessage({id:u,method:"clear",params:{timerId:a}})},setTimeout:(a,u)=>{const h=Math.random();return t.set(h,a),n.postMessage({id:null,method:"set",params:{delay:u,now:performance.now(),timerId:h}}),h}}}static loadWorkerTimers(){const e=`!function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=14)}([function(e,t,n){"use strict";n.d(t,"a",(function(){return i})),n.d(t,"b",(function(){return u})),n.d(t,"c",(function(){return a})),n.d(t,"d",(function(){return d}));const r=new Map,o=new Map,i=e=>{const t=r.get(e);if(void 0===t)throw new Error('There is no interval scheduled with the given id "'.concat(e,'".'));clearTimeout(t),r.delete(e)},u=e=>{const t=o.get(e);if(void 0===t)throw new Error('There is no timeout scheduled with the given id "'.concat(e,'".'));clearTimeout(t),o.delete(e)},f=(e,t)=>{let n,r;if("performance"in self){const o=performance.now();n=o,r=e-Math.max(0,o-t)}else n=Date.now(),r=e;return{expected:n+r,remainingDelay:r}},c=(e,t,n,r)=>{const o="performance"in self?performance.now():Date.now();o>n?postMessage({id:null,method:"call",params:{timerId:t}}):e.set(t,setTimeout(c,n-o,e,t,n))},a=(e,t,n)=>{const{expected:o,remainingDelay:i}=f(e,n);r.set(t,setTimeout(c,i,r,t,o))},d=(e,t,n)=>{const{expected:r,remainingDelay:i}=f(e,n);o.set(t,setTimeout(c,i,o,t,r))}},function(e,t,n){"use strict";n.r(t);var r=n(2);for(var o in r)"default"!==o&&function(e){n.d(t,e,(function(){return r[e]}))}(o);var i=n(3);for(var o in i)"default"!==o&&function(e){n.d(t,e,(function(){return i[e]}))}(o);var u=n(4);for(var o in u)"default"!==o&&function(e){n.d(t,e,(function(){return u[e]}))}(o);var f=n(5);for(var o in f)"default"!==o&&function(e){n.d(t,e,(function(){return f[e]}))}(o);var c=n(6);for(var o in c)"default"!==o&&function(e){n.d(t,e,(function(){return c[e]}))}(o);var a=n(7);for(var o in a)"default"!==o&&function(e){n.d(t,e,(function(){return a[e]}))}(o);var d=n(8);for(var o in d)"default"!==o&&function(e){n.d(t,e,(function(){return d[e]}))}(o);var s=n(9);for(var o in s)"default"!==o&&function(e){n.d(t,e,(function(){return s[e]}))}(o)},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t,n){"use strict";n.r(t);var r=n(11);for(var o in r)"default"!==o&&function(e){n.d(t,e,(function(){return r[e]}))}(o);var i=n(12);for(var o in i)"default"!==o&&function(e){n.d(t,e,(function(){return i[e]}))}(o);var u=n(13);for(var o in u)"default"!==o&&function(e){n.d(t,e,(function(){return u[e]}))}(o)},function(e,t){},function(e,t){},function(e,t){},function(e,t,n){"use strict";var Wr=Object.defineProperty;var Vr=(M,K,Z)=>K in M?Wr(M,K,{enumerable:!0,configurable:!0,writable:!0,value:Z}):M[K]=Z;var m=(M,K,Z)=>(Vr(M,typeof K!="symbol"?K+"":K,Z),Z);n.r(t);var r=n(0),o=n(1);for(var i in o)"default"!==i&&function(e){n.d(t,e,(function(){return o[e]}))}(i);var u=n(10);for(var i in u)"default"!==i&&function(e){n.d(t,e,(function(){return u[e]}))}(i);addEventListener("message",({data:e})=>{try{if("clear"===e.method){const{id:t,params:{timerId:n}}=e;Object(r.b)(n),postMessage({error:null,id:t})}else{if("set"!==e.method)throw new Error('The given method "'.concat(e.method,'" is not supported'));{const{params:{delay:t,now:n,timerId:o}}=e;Object(r.d)(t,o,n)}}}catch(t){postMessage({error:{message:t.message},id:e.id,result:null})}})}]);`;return()=>{if(O.workerTimers!==null)return O.workerTimers;const t=new Blob([e],{type:"application/javascript; charset=utf-8"}),i=URL.createObjectURL(t);return O.workerTimers=O.load(i),O.workerTimers.setTimeout(()=>URL.revokeObjectURL(i),0),O.workerTimers}}static isCallNotification(e){return e.method!==void 0&&e.method==="call"}static isClearResponse(e){return e.error===null&&typeof e.id=="number"}}O.workerTimers=null,O.clearTimeout=r=>O.timers().clearTimeout(r),O.setTimeout=(r,e)=>O.timers().setTimeout(r,e),O.timers=O.loadWorkerTimers();class B extends ae{constructor(e,t,i){super(e,t),this.privSignature=i}}class _i extends B{constructor(e){super("OCSPMemoryCacheHitEvent",w.Debug,e)}}class Hi extends B{constructor(e){super("OCSPCacheMissEvent",w.Debug,e)}}class Ki extends B{constructor(e){super("OCSPDiskCacheHitEvent",w.Debug,e)}}class qi extends B{constructor(e){super("OCSPCacheUpdateNeededEvent",w.Debug,e)}}class Ui extends B{constructor(e){super("OCSPMemoryCacheStoreEvent",w.Debug,e)}}class Wi extends B{constructor(e){super("OCSPDiskCacheStoreEvent",w.Debug,e)}}class Vi extends B{constructor(e){super("OCSPCacheUpdateCompleteEvent",w.Debug,e)}}class Fi extends B{constructor(){super("OCSPStapleReceivedEvent",w.Debug,"")}}class ji extends B{constructor(e,t){super("OCSPCacheEntryExpiredEvent",w.Debug,e),this.privExpireTime=t}}class Gi extends B{constructor(e,t,i){super("OCSPCacheEntryNeedsRefreshEvent",w.Debug,e),this.privExpireTime=i,this.privStartTime=t}}class $i extends B{constructor(e,t,i){super("OCSPCacheHitEvent",w.Debug,e),this.privExpireTime=i,this.privExpireTimeString=new Date(i).toLocaleDateString(),this.privStartTime=t,this.privStartTimeString=new Date(t).toLocaleTimeString()}}class Ji extends B{constructor(e,t){super("OCSPVerificationFailedEvent",w.Debug,e),this.privError=t}}class Vt extends B{constructor(e,t){super("OCSPCacheFetchErrorEvent",w.Debug,e),this.privError=t}}class Qi extends B{constructor(e){super("OCSPResponseRetrievedEvent",w.Debug,e)}}class Xi extends B{constructor(e,t){super("OCSPCacheUpdateErrorEvent",w.Debug,e),this.privError=t}}class Ie extends ae{constructor(e){super("BackgroundEvent",w.Error),this.privError=e}get error(){return this.privError}}class l{static throwIfNullOrUndefined(e,t){if(e==null)throw new Error("throwIfNullOrUndefined:"+t)}static throwIfNull(e,t){if(e===null)throw new Error("throwIfNull:"+t)}static throwIfNullOrWhitespace(e,t){if(l.throwIfNullOrUndefined(e,t),(""+e).trim().length<1)throw new Error("throwIfNullOrWhitespace:"+t)}static throwIfDisposed(e){if(e)throw new Error("the object is already disposed")}static throwIfArrayEmptyOrWhitespace(e,t){if(l.throwIfNullOrUndefined(e,t),e.length===0)throw new Error("throwIfArrayEmptyOrWhitespace:"+t);for(const i of e)l.throwIfNullOrWhitespace(i,t)}static throwIfFileDoesNotExist(e,t){l.throwIfNullOrWhitespace(e,t)}static throwIfNotUndefined(e,t){if(e!==void 0)throw new Error("throwIfNotUndefined:"+t)}}class b{}b.AuthKey="Ocp-Apim-Subscription-Key",b.ConnectionId="X-ConnectionId",b.ContentType="Content-Type",b.CustomCommandsAppId="X-CommandsAppId",b.Path="Path",b.RequestId="X-RequestId",b.RequestStreamId="X-StreamId",b.RequestTimestamp="X-Timestamp";class St{constructor(e,t){this.privHeaderName=e,this.privToken=t}get headerName(){return this.privHeaderName}get token(){return this.privToken}}class Ft{constructor(e){if(!e)throw new z("subscriptionKey");this.privAuthInfo=new St(b.AuthKey,e)}fetch(e){return Promise.resolve(this.privAuthInfo)}fetchOnExpiry(e){return Promise.resolve(this.privAuthInfo)}}const jt="Authorization";class de{constructor(e,t){if(!e)throw new z("fetchCallback");if(!t)throw new z("fetchOnExpiryCallback");this.privFetchCallback=e,this.privFetchOnExpiryCallback=t}fetch(e){return this.privFetchCallback(e).then(t=>new St(jt,de.privTokenPrefix+t))}fetchOnExpiry(e){return this.privFetchOnExpiryCallback(e).then(t=>new St(jt,de.privTokenPrefix+t))}}de.privTokenPrefix="bearer ";class Gt{constructor(e){l.throwIfNullOrUndefined(void 0,`
2
+ File System access not available, please use Push or PullAudioOutputStream`),this.privFd=(void 0)(e,"w")}set format(e){l.throwIfNotUndefined(this.privAudioFormat,"format is already set"),this.privAudioFormat=e;let t=0;this.privAudioFormat.hasHeader&&(t=this.privAudioFormat.header.byteLength),this.privFd!==void 0&&(this.privWriteStream=(void 0)("",{fd:this.privFd,start:t,autoClose:!1}))}write(e){l.throwIfNullOrUndefined(this.privAudioFormat,"must set format before writing."),this.privWriteStream!==void 0&&this.privWriteStream.write(new Uint8Array(e.slice(0)))}close(){this.privFd!==void 0&&(this.privWriteStream.on("finish",()=>{this.privAudioFormat.hasHeader&&(this.privAudioFormat.updateHeader(this.privWriteStream.bytesWritten),(void 0)(this.privFd,new Int8Array(this.privAudioFormat.header),0,this.privAudioFormat.header.byteLength,0)),(void 0)(this.privFd),this.privFd=void 0}),this.privWriteStream.end())}id(){return this.privId}}var v;(function(r){r[r.PCM=1]="PCM",r[r.MuLaw=2]="MuLaw",r[r.Siren=3]="Siren",r[r.MP3=4]="MP3",r[r.SILKSkype=5]="SILKSkype",r[r.OGG_OPUS=6]="OGG_OPUS",r[r.WEBM_OPUS=7]="WEBM_OPUS",r[r.ALaw=8]="ALaw",r[r.FLAC=9]="FLAC",r[r.OPUS=10]="OPUS"})(v||(v={}));class Ue{static getDefaultInputFormat(){return Y.getDefaultInputFormat()}static getWaveFormat(e,t,i,n){return new Y(e,t,i,n)}static getWaveFormatPCM(e,t,i){return new Y(e,t,i)}}class Y extends Ue{constructor(e=16e3,t=16,i=1,n=v.PCM){super();let s=!0;switch(n){case v.PCM:this.formatTag=1;break;case v.ALaw:this.formatTag=6;break;case v.MuLaw:this.formatTag=7;break;default:s=!1}if(this.bitsPerSample=t,this.samplesPerSec=e,this.channels=i,this.avgBytesPerSec=this.samplesPerSec*this.channels*(this.bitsPerSample/8),this.blockAlign=this.channels*Math.max(this.bitsPerSample,8),s){this.privHeader=new ArrayBuffer(44);const o=new DataView(this.privHeader);this.setString(o,0,"RIFF"),o.setUint32(4,0,!0),this.setString(o,8,"WAVEfmt "),o.setUint32(16,16,!0),o.setUint16(20,this.formatTag,!0),o.setUint16(22,this.channels,!0),o.setUint32(24,this.samplesPerSec,!0),o.setUint32(28,this.avgBytesPerSec,!0),o.setUint16(32,this.channels*(this.bitsPerSample/8),!0),o.setUint16(34,this.bitsPerSample,!0),this.setString(o,36,"data"),o.setUint32(40,0,!0)}}static getDefaultInputFormat(){return new Y}static getAudioContext(e){const t=window.AudioContext||window.webkitAudioContext||!1;if(t)return e!==void 0&&navigator.mediaDevices.getSupportedConstraints().sampleRate?new t({sampleRate:e}):new t;throw new Error("Browser does not support Web Audio API (AudioContext is not available).")}close(){}get header(){return this.privHeader}setString(e,t,i){for(let n=0;n<i.length;n++)e.setUint8(t+n,i.charCodeAt(n))}}var mt=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};class yt{constructor(){}static createPushStream(e){return $t.create(e)}static createPullStream(e,t){return Jt.create(e,t)}}class $t extends yt{static create(e){return new Zi(e)}}class Zi extends $t{constructor(e){super(),e===void 0?this.privFormat=Y.getDefaultInputFormat():this.privFormat=e,this.privEvents=new F,this.privId=R(),this.privStream=new gt(this.privFormat.avgBytesPerSec/10)}get format(){return Promise.resolve(this.privFormat)}write(e){this.privStream.writeStreamChunk({buffer:e,isEnd:!1,timeReceived:Date.now()})}close(){this.privStream.close()}id(){return this.privId}get blob(){return this.attach("id").then(e=>{const t=[];let i=Buffer.from("");const n=()=>e.read().then(s=>!s||s.isEnd?typeof XMLHttpRequest!="undefined"&&typeof Blob!="undefined"?Promise.resolve(new Blob(t)):Promise.resolve(Buffer.from(i)):(typeof Blob!="undefined"?t.push(s.buffer):i=Buffer.concat([i,this.toBuffer(s.buffer)]),n()));return n()})}turnOn(){this.onEvent(new _e(this.privId)),this.onEvent(new Ee(this.privId))}attach(e){return mt(this,void 0,void 0,function*(){this.onEvent(new Te(this.privId,e)),yield this.turnOn();const t=this.privStream;return this.onEvent(new be(this.privId,e)),{detach:()=>mt(this,void 0,void 0,function*(){return this.onEvent(new $(this.privId,e)),this.turnOff()}),id:()=>e,read:()=>t.read()}})}detach(e){this.onEvent(new $(this.privId,e))}turnOff(){}get events(){return this.privEvents}get deviceInfo(){return Promise.resolve({bitspersample:this.privFormat.bitsPerSample,channelcount:this.privFormat.channels,connectivity:Se.Unknown,manufacturer:"Speech SDK",model:"PushStream",samplerate:this.privFormat.samplesPerSec,type:ue.Stream})}onEvent(e){this.privEvents.onEvent(e),L.instance.onEvent(e)}toBuffer(e){const t=Buffer.alloc(e.byteLength),i=new Uint8Array(e);for(let n=0;n<t.length;++n)t[n]=i[n];return t}}class Jt extends yt{constructor(){super()}static create(e,t){return new Qt(e,t)}}class Qt extends Jt{constructor(e,t){super(),t===void 0?this.privFormat=Ue.getDefaultInputFormat():this.privFormat=t,this.privEvents=new F,this.privId=R(),this.privCallback=e,this.privIsClosed=!1,this.privBufferSize=this.privFormat.avgBytesPerSec/10}get format(){return Promise.resolve(this.privFormat)}close(){this.privIsClosed=!0,this.privCallback.close()}id(){return this.privId}get blob(){return Promise.reject("Not implemented")}turnOn(){this.onEvent(new _e(this.privId)),this.onEvent(new Ee(this.privId))}attach(e){return mt(this,void 0,void 0,function*(){return this.onEvent(new Te(this.privId,e)),yield this.turnOn(),this.onEvent(new be(this.privId,e)),{detach:()=>(this.privCallback.close(),this.onEvent(new $(this.privId,e)),this.turnOff()),id:()=>e,read:()=>{let t=0,i;for(;t<this.privBufferSize;){const n=new ArrayBuffer(this.privBufferSize-t),s=this.privCallback.read(n);if(i===void 0?i=n:new Int8Array(i).set(new Int8Array(n),t),s===0)break;t+=s}return Promise.resolve({buffer:i.slice(0,t),isEnd:this.privIsClosed||t===0,timeReceived:Date.now()})}}})}detach(e){this.onEvent(new $(this.privId,e))}turnOff(){}get events(){return this.privEvents}get deviceInfo(){return Promise.resolve({bitspersample:this.privFormat.bitsPerSample,channelcount:this.privFormat.channels,connectivity:Se.Unknown,manufacturer:"Speech SDK",model:"PullStream",samplerate:this.privFormat.samplesPerSec,type:ue.Stream})}onEvent(e){this.privEvents.onEvent(e),L.instance.onEvent(e)}}var S;(function(r){r[r.Raw8Khz8BitMonoMULaw=0]="Raw8Khz8BitMonoMULaw",r[r.Riff16Khz16KbpsMonoSiren=1]="Riff16Khz16KbpsMonoSiren",r[r.Audio16Khz16KbpsMonoSiren=2]="Audio16Khz16KbpsMonoSiren",r[r.Audio16Khz32KBitRateMonoMp3=3]="Audio16Khz32KBitRateMonoMp3",r[r.Audio16Khz128KBitRateMonoMp3=4]="Audio16Khz128KBitRateMonoMp3",r[r.Audio16Khz64KBitRateMonoMp3=5]="Audio16Khz64KBitRateMonoMp3",r[r.Audio24Khz48KBitRateMonoMp3=6]="Audio24Khz48KBitRateMonoMp3",r[r.Audio24Khz96KBitRateMonoMp3=7]="Audio24Khz96KBitRateMonoMp3",r[r.Audio24Khz160KBitRateMonoMp3=8]="Audio24Khz160KBitRateMonoMp3",r[r.Raw16Khz16BitMonoTrueSilk=9]="Raw16Khz16BitMonoTrueSilk",r[r.Riff16Khz16BitMonoPcm=10]="Riff16Khz16BitMonoPcm",r[r.Riff8Khz16BitMonoPcm=11]="Riff8Khz16BitMonoPcm",r[r.Riff24Khz16BitMonoPcm=12]="Riff24Khz16BitMonoPcm",r[r.Riff8Khz8BitMonoMULaw=13]="Riff8Khz8BitMonoMULaw",r[r.Raw16Khz16BitMonoPcm=14]="Raw16Khz16BitMonoPcm",r[r.Raw24Khz16BitMonoPcm=15]="Raw24Khz16BitMonoPcm",r[r.Raw8Khz16BitMonoPcm=16]="Raw8Khz16BitMonoPcm",r[r.Ogg16Khz16BitMonoOpus=17]="Ogg16Khz16BitMonoOpus",r[r.Ogg24Khz16BitMonoOpus=18]="Ogg24Khz16BitMonoOpus",r[r.Raw48Khz16BitMonoPcm=19]="Raw48Khz16BitMonoPcm",r[r.Riff48Khz16BitMonoPcm=20]="Riff48Khz16BitMonoPcm",r[r.Audio48Khz96KBitRateMonoMp3=21]="Audio48Khz96KBitRateMonoMp3",r[r.Audio48Khz192KBitRateMonoMp3=22]="Audio48Khz192KBitRateMonoMp3",r[r.Ogg48Khz16BitMonoOpus=23]="Ogg48Khz16BitMonoOpus",r[r.Webm16Khz16BitMonoOpus=24]="Webm16Khz16BitMonoOpus",r[r.Webm24Khz16BitMonoOpus=25]="Webm24Khz16BitMonoOpus",r[r.Raw24Khz16BitMonoTrueSilk=26]="Raw24Khz16BitMonoTrueSilk",r[r.Raw8Khz8BitMonoALaw=27]="Raw8Khz8BitMonoALaw",r[r.Riff8Khz8BitMonoALaw=28]="Riff8Khz8BitMonoALaw",r[r.Webm24Khz16Bit24KbpsMonoOpus=29]="Webm24Khz16Bit24KbpsMonoOpus",r[r.Audio16Khz16Bit32KbpsMonoOpus=30]="Audio16Khz16Bit32KbpsMonoOpus",r[r.Audio24Khz16Bit48KbpsMonoOpus=31]="Audio24Khz16Bit48KbpsMonoOpus",r[r.Audio24Khz16Bit24KbpsMonoOpus=32]="Audio24Khz16Bit24KbpsMonoOpus",r[r.Raw22050Hz16BitMonoPcm=33]="Raw22050Hz16BitMonoPcm",r[r.Riff22050Hz16BitMonoPcm=34]="Riff22050Hz16BitMonoPcm",r[r.Raw44100Hz16BitMonoPcm=35]="Raw44100Hz16BitMonoPcm",r[r.Riff44100Hz16BitMonoPcm=36]="Riff44100Hz16BitMonoPcm"})(S||(S={}));class g extends Y{constructor(e,t,i,n,s,o,a,u,h){super(i,o,t,e),this.formatTag=e,this.avgBytesPerSec=n,this.blockAlign=s,this.priAudioFormatString=a,this.priRequestAudioFormatString=u,this.priHasHeader=h}static fromSpeechSynthesisOutputFormat(e){return e===void 0?g.getDefaultOutputFormat():g.fromSpeechSynthesisOutputFormatString(g.SpeechSynthesisOutputFormatToString[e])}static fromSpeechSynthesisOutputFormatString(e){switch(e){case"raw-8khz-8bit-mono-mulaw":return new g(v.MuLaw,1,8e3,8e3,1,8,e,e,!1);case"riff-16khz-16kbps-mono-siren":return new g(v.Siren,1,16e3,2e3,40,0,e,"audio-16khz-16kbps-mono-siren",!0);case"audio-16khz-16kbps-mono-siren":return new g(v.Siren,1,16e3,2e3,40,0,e,e,!1);case"audio-16khz-32kbitrate-mono-mp3":return new g(v.MP3,1,16e3,32<<7,2,16,e,e,!1);case"audio-16khz-128kbitrate-mono-mp3":return new g(v.MP3,1,16e3,128<<7,2,16,e,e,!1);case"audio-16khz-64kbitrate-mono-mp3":return new g(v.MP3,1,16e3,64<<7,2,16,e,e,!1);case"audio-24khz-48kbitrate-mono-mp3":return new g(v.MP3,1,24e3,48<<7,2,16,e,e,!1);case"audio-24khz-96kbitrate-mono-mp3":return new g(v.MP3,1,24e3,96<<7,2,16,e,e,!1);case"audio-24khz-160kbitrate-mono-mp3":return new g(v.MP3,1,24e3,160<<7,2,16,e,e,!1);case"raw-16khz-16bit-mono-truesilk":return new g(v.SILKSkype,1,16e3,32e3,2,16,e,e,!1);case"riff-8khz-16bit-mono-pcm":return new g(v.PCM,1,8e3,16e3,2,16,e,"raw-8khz-16bit-mono-pcm",!0);case"riff-24khz-16bit-mono-pcm":return new g(v.PCM,1,24e3,48e3,2,16,e,"raw-24khz-16bit-mono-pcm",!0);case"riff-8khz-8bit-mono-mulaw":return new g(v.MuLaw,1,8e3,8e3,1,8,e,"raw-8khz-8bit-mono-mulaw",!0);case"raw-16khz-16bit-mono-pcm":return new g(v.PCM,1,16e3,32e3,2,16,e,"raw-16khz-16bit-mono-pcm",!1);case"raw-24khz-16bit-mono-pcm":return new g(v.PCM,1,24e3,48e3,2,16,e,"raw-24khz-16bit-mono-pcm",!1);case"raw-8khz-16bit-mono-pcm":return new g(v.PCM,1,8e3,16e3,2,16,e,"raw-8khz-16bit-mono-pcm",!1);case"ogg-16khz-16bit-mono-opus":return new g(v.OGG_OPUS,1,16e3,8192,2,16,e,e,!1);case"ogg-24khz-16bit-mono-opus":return new g(v.OGG_OPUS,1,24e3,8192,2,16,e,e,!1);case"raw-48khz-16bit-mono-pcm":return new g(v.PCM,1,48e3,96e3,2,16,e,"raw-48khz-16bit-mono-pcm",!1);case"riff-48khz-16bit-mono-pcm":return new g(v.PCM,1,48e3,96e3,2,16,e,"raw-48khz-16bit-mono-pcm",!0);case"audio-48khz-96kbitrate-mono-mp3":return new g(v.MP3,1,48e3,96<<7,2,16,e,e,!1);case"audio-48khz-192kbitrate-mono-mp3":return new g(v.MP3,1,48e3,192<<7,2,16,e,e,!1);case"ogg-48khz-16bit-mono-opus":return new g(v.OGG_OPUS,1,48e3,12e3,2,16,e,e,!1);case"webm-16khz-16bit-mono-opus":return new g(v.WEBM_OPUS,1,16e3,4e3,2,16,e,e,!1);case"webm-24khz-16bit-mono-opus":return new g(v.WEBM_OPUS,1,24e3,6e3,2,16,e,e,!1);case"webm-24khz-16bit-24kbps-mono-opus":return new g(v.WEBM_OPUS,1,24e3,3e3,2,16,e,e,!1);case"audio-16khz-16bit-32kbps-mono-opus":return new g(v.OPUS,1,16e3,4e3,2,16,e,e,!1);case"audio-24khz-16bit-48kbps-mono-opus":return new g(v.OPUS,1,24e3,6e3,2,16,e,e,!1);case"audio-24khz-16bit-24kbps-mono-opus":return new g(v.OPUS,1,24e3,3e3,2,16,e,e,!1);case"audio-24khz-16bit-mono-flac":return new g(v.FLAC,1,24e3,24e3,2,16,e,e,!1);case"audio-48khz-16bit-mono-flac":return new g(v.FLAC,1,48e3,3e4,2,16,e,e,!1);case"raw-24khz-16bit-mono-truesilk":return new g(v.SILKSkype,1,24e3,48e3,2,16,e,e,!1);case"raw-8khz-8bit-mono-alaw":return new g(v.ALaw,1,8e3,8e3,1,8,e,e,!1);case"riff-8khz-8bit-mono-alaw":return new g(v.ALaw,1,8e3,8e3,1,8,e,"raw-8khz-8bit-mono-alaw",!0);case"raw-22050hz-16bit-mono-pcm":return new g(v.PCM,1,22050,44100,2,16,e,e,!1);case"riff-22050hz-16bit-mono-pcm":return new g(v.PCM,1,22050,44100,2,16,e,"raw-22050hz-16bit-mono-pcm",!0);case"raw-44100hz-16bit-mono-pcm":return new g(v.PCM,1,44100,88200,2,16,e,e,!1);case"riff-44100hz-16bit-mono-pcm":return new g(v.PCM,1,44100,88200,2,16,e,"raw-44100hz-16bit-mono-pcm",!0);case"riff-16khz-16bit-mono-pcm":default:return new g(v.PCM,1,16e3,32e3,2,16,"riff-16khz-16bit-mono-pcm","raw-16khz-16bit-mono-pcm",!0)}}static getDefaultOutputFormat(){return g.fromSpeechSynthesisOutputFormatString(typeof window!="undefined"?"audio-24khz-48kbitrate-mono-mp3":"riff-16khz-16bit-mono-pcm")}get hasHeader(){return this.priHasHeader}get header(){if(this.hasHeader)return this.privHeader}updateHeader(e){if(this.priHasHeader){const t=new DataView(this.privHeader);t.setUint32(4,e+this.privHeader.byteLength-8,!0),t.setUint32(40,e,!0)}}get requestAudioFormatString(){return this.priRequestAudioFormatString}}g.SpeechSynthesisOutputFormatToString={[S.Raw8Khz8BitMonoMULaw]:"raw-8khz-8bit-mono-mulaw",[S.Riff16Khz16KbpsMonoSiren]:"riff-16khz-16kbps-mono-siren",[S.Audio16Khz16KbpsMonoSiren]:"audio-16khz-16kbps-mono-siren",[S.Audio16Khz32KBitRateMonoMp3]:"audio-16khz-32kbitrate-mono-mp3",[S.Audio16Khz128KBitRateMonoMp3]:"audio-16khz-128kbitrate-mono-mp3",[S.Audio16Khz64KBitRateMonoMp3]:"audio-16khz-64kbitrate-mono-mp3",[S.Audio24Khz48KBitRateMonoMp3]:"audio-24khz-48kbitrate-mono-mp3",[S.Audio24Khz96KBitRateMonoMp3]:"audio-24khz-96kbitrate-mono-mp3",[S.Audio24Khz160KBitRateMonoMp3]:"audio-24khz-160kbitrate-mono-mp3",[S.Raw16Khz16BitMonoTrueSilk]:"raw-16khz-16bit-mono-truesilk",[S.Riff16Khz16BitMonoPcm]:"riff-16khz-16bit-mono-pcm",[S.Riff8Khz16BitMonoPcm]:"riff-8khz-16bit-mono-pcm",[S.Riff24Khz16BitMonoPcm]:"riff-24khz-16bit-mono-pcm",[S.Riff8Khz8BitMonoMULaw]:"riff-8khz-8bit-mono-mulaw",[S.Raw16Khz16BitMonoPcm]:"raw-16khz-16bit-mono-pcm",[S.Raw24Khz16BitMonoPcm]:"raw-24khz-16bit-mono-pcm",[S.Raw8Khz16BitMonoPcm]:"raw-8khz-16bit-mono-pcm",[S.Ogg16Khz16BitMonoOpus]:"ogg-16khz-16bit-mono-opus",[S.Ogg24Khz16BitMonoOpus]:"ogg-24khz-16bit-mono-opus",[S.Raw48Khz16BitMonoPcm]:"raw-48khz-16bit-mono-pcm",[S.Riff48Khz16BitMonoPcm]:"riff-48khz-16bit-mono-pcm",[S.Audio48Khz96KBitRateMonoMp3]:"audio-48khz-96kbitrate-mono-mp3",[S.Audio48Khz192KBitRateMonoMp3]:"audio-48khz-192kbitrate-mono-mp3",[S.Ogg48Khz16BitMonoOpus]:"ogg-48khz-16bit-mono-opus",[S.Webm16Khz16BitMonoOpus]:"webm-16khz-16bit-mono-opus",[S.Webm24Khz16BitMonoOpus]:"webm-24khz-16bit-mono-opus",[S.Webm24Khz16Bit24KbpsMonoOpus]:"webm-24khz-16bit-24kbps-mono-opus",[S.Raw24Khz16BitMonoTrueSilk]:"raw-24khz-16bit-mono-truesilk",[S.Raw8Khz8BitMonoALaw]:"raw-8khz-8bit-mono-alaw",[S.Riff8Khz8BitMonoALaw]:"riff-8khz-8bit-mono-alaw",[S.Audio16Khz16Bit32KbpsMonoOpus]:"audio-16khz-16bit-32kbps-mono-opus",[S.Audio24Khz16Bit48KbpsMonoOpus]:"audio-24khz-16bit-48kbps-mono-opus",[S.Audio24Khz16Bit24KbpsMonoOpus]:"audio-24khz-16bit-24kbps-mono-opus",[S.Raw22050Hz16BitMonoPcm]:"raw-22050hz-16bit-mono-pcm",[S.Riff22050Hz16BitMonoPcm]:"riff-22050hz-16bit-mono-pcm",[S.Raw44100Hz16BitMonoPcm]:"raw-44100hz-16bit-mono-pcm",[S.Riff44100Hz16BitMonoPcm]:"riff-44100hz-16bit-mono-pcm"};var Yi=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};class Xt{constructor(){}static createPullStream(){return We.create()}}class We extends Xt{static create(){return new wt}}class wt extends We{constructor(){super(),this.privId=R(),this.privStream=new Wt}set format(e){e==null&&(this.privFormat=g.getDefaultOutputFormat()),this.privFormat=e}get format(){return this.privFormat}get isClosed(){return this.privStream.isClosed}id(){return this.privId}read(e){return Yi(this,void 0,void 0,function*(){const t=new Int8Array(e);let i=0;if(this.privLastChunkView!==void 0){if(this.privLastChunkView.length>e.byteLength)return t.set(this.privLastChunkView.slice(0,e.byteLength)),this.privLastChunkView=this.privLastChunkView.slice(e.byteLength),Promise.resolve(e.byteLength);t.set(this.privLastChunkView),i=this.privLastChunkView.length,this.privLastChunkView=void 0}for(;i<e.byteLength&&!this.privStream.isReadEnded;){const n=yield this.privStream.read();if(n!==void 0&&!n.isEnd){let s;n.buffer.byteLength>e.byteLength-i?(s=n.buffer.slice(0,e.byteLength-i),this.privLastChunkView=new Int8Array(n.buffer.slice(e.byteLength-i))):s=n.buffer,t.set(new Int8Array(s),i),i+=s.byteLength}else this.privStream.readEnded()}return i})}write(e){l.throwIfNullOrUndefined(this.privStream,"must set format before writing"),this.privStream.writeStreamChunk({buffer:e,isEnd:!1,timeReceived:Date.now()})}close(){this.privStream.close()}}class Zt extends Xt{constructor(){super()}static create(e){return new Ct(e)}}class Ct extends Zt{constructor(e){super(),this.privId=R(),this.privCallback=e}set format(e){}write(e){this.privCallback.write&&this.privCallback.write(e)}close(){this.privCallback.close&&this.privCallback.close()}id(){return this.privId}}class ee{static fromDefaultMicrophoneInput(){const e=new Lt(!0);return new ve(new V(e))}static fromMicrophoneInput(e){const t=new Lt(!0);return new ve(new V(t,e))}static fromWavFileInput(e,t="unnamedBuffer.wav"){return new ve(new kr(e,t))}static fromStreamInput(e){if(e instanceof er)return new ve(new Qt(e));if(e instanceof yt)return new ve(e);if(typeof MediaStream!="undefined"&&e instanceof MediaStream){const t=new Lt(!1);return new ve(new V(t,null,null,e))}throw new Error("Not Supported Type")}static fromDefaultSpeakerOutput(){return new le(new Pt)}static fromSpeakerOutput(e){if(e===void 0)return ee.fromDefaultSpeakerOutput();if(e instanceof Pt)return new le(e);throw new Error("Not Supported Type")}static fromAudioFileOutput(e){return new le(new Gt(e))}static fromStreamOutput(e){if(e instanceof Yt)return new le(new Ct(e));if(e instanceof Zt)return new le(e);if(e instanceof We)return new le(e);throw new Error("Not Supported Type")}}class ve extends ee{constructor(e){super(),this.privSource=e}get format(){return this.privSource.format}close(e,t){this.privSource.turnOff().then(()=>{e&&e()},i=>{t&&t(i)})}id(){return this.privSource.id()}get blob(){return this.privSource.blob}turnOn(){return this.privSource.turnOn()}attach(e){return this.privSource.attach(e)}detach(e){return this.privSource.detach(e)}turnOff(){return this.privSource.turnOff()}get events(){return this.privSource.events}setProperty(e,t){if(l.throwIfNull(t,"value"),this.privSource.setProperty!==void 0)this.privSource.setProperty(e,t);else throw new Error("This AudioConfig instance does not support setting properties.")}getProperty(e,t){if(this.privSource.getProperty!==void 0)return this.privSource.getProperty(e,t);throw new Error("This AudioConfig instance does not support getting properties.")}get deviceInfo(){return this.privSource.deviceInfo}}class le extends ee{constructor(e){super(),this.privDestination=e}set format(e){this.privDestination.format=e}write(e){this.privDestination.write(e)}close(){this.privDestination.close()}id(){return this.privDestination.id()}setProperty(){throw new Error("This AudioConfig instance does not support setting properties.")}getProperty(){throw new Error("This AudioConfig instance does not support getting properties.")}}var H;(function(r){r[r.Error=0]="Error",r[r.EndOfStream=1]="EndOfStream"})(H||(H={}));class er{}class Yt{}class fe{constructor(e){this.privSessionId=e}get sessionId(){return this.privSessionId}}class Et extends fe{constructor(e,t){super(t),this.privOffset=e}get offset(){return this.privOffset}}var te;(function(r){r[r.Simple=0]="Simple",r[r.Detailed=1]="Detailed"})(te||(te={}));class tr{constructor(e,t,i,n,s,o,a,u,h,c){this.privResultId=e,this.privReason=t,this.privText=i,this.privDuration=n,this.privOffset=s,this.privLanguage=o,this.privLanguageDetectionConfidence=a,this.privErrorDetails=u,this.privJson=h,this.privProperties=c}get resultId(){return this.privResultId}get reason(){return this.privReason}get text(){return this.privText}get duration(){return this.privDuration}get offset(){return this.privOffset}get language(){return this.privLanguage}get languageDetectionConfidence(){return this.privLanguageDetectionConfidence}get errorDetails(){return this.privErrorDetails}get json(){return this.privJson}get properties(){return this.privProperties}}class ir extends tr{constructor(e,t,i,n,s,o,a,u,h,c,d){super(e,t,i,n,s,o,a,h,c,d),this.privSpeakerId=u}get speakerId(){return this.privSpeakerId}}class ei extends Et{constructor(e,t,i){super(t,i),this.privResult=e}get result(){return this.privResult}}class ti extends fe{constructor(e,t){super(t),this.privResult=e}get result(){return this.privResult}}class Tt extends ir{constructor(e,t,i,n,s,o,a,u,h){super(t,i,n,s,o,void 0,void 0,void 0,a,u,h),this.privTranslations=e}get translations(){return this.privTranslations}}class ii{constructor(e,t){this.privReason=e,this.privAudio=t}get audio(){return this.privAudio}get reason(){return this.privReason}}var P;(function(r){r[r.NoMatch=0]="NoMatch",r[r.Canceled=1]="Canceled",r[r.RecognizingSpeech=2]="RecognizingSpeech",r[r.RecognizedSpeech=3]="RecognizedSpeech",r[r.RecognizedKeyword=4]="RecognizedKeyword",r[r.RecognizingIntent=5]="RecognizingIntent",r[r.RecognizedIntent=6]="RecognizedIntent",r[r.TranslatingSpeech=7]="TranslatingSpeech",r[r.TranslatedSpeech=8]="TranslatedSpeech",r[r.SynthesizingAudio=9]="SynthesizingAudio",r[r.SynthesizingAudioCompleted=10]="SynthesizingAudioCompleted",r[r.SynthesizingAudioStarted=11]="SynthesizingAudioStarted",r[r.EnrollingVoiceProfile=12]="EnrollingVoiceProfile",r[r.EnrolledVoiceProfile=13]="EnrolledVoiceProfile",r[r.RecognizedSpeakers=14]="RecognizedSpeakers",r[r.RecognizedSpeaker=15]="RecognizedSpeaker",r[r.ResetVoiceProfile=16]="ResetVoiceProfile",r[r.DeletedVoiceProfile=17]="DeletedVoiceProfile",r[r.VoicesListRetrieved=18]="VoicesListRetrieved"})(P||(P={}));class bt{constructor(){}static fromSubscription(e,t){l.throwIfNullOrWhitespace(e,"subscriptionKey"),l.throwIfNullOrWhitespace(t,"region");const i=new ge;return i.setProperty(p.SpeechServiceConnection_Region,t),i.setProperty(p.SpeechServiceConnection_IntentRegion,t),i.setProperty(p.SpeechServiceConnection_Key,e),i}static fromEndpoint(e,t){l.throwIfNull(e,"endpoint");const i=new ge;return i.setProperty(p.SpeechServiceConnection_Endpoint,e.href),t!==void 0&&i.setProperty(p.SpeechServiceConnection_Key,t),i}static fromHost(e,t){l.throwIfNull(e,"hostName");const i=new ge;return i.setProperty(p.SpeechServiceConnection_Host,e.protocol+"//"+e.hostname+(e.port===""?"":":"+e.port)),t!==void 0&&i.setProperty(p.SpeechServiceConnection_Key,t),i}static fromAuthorizationToken(e,t){l.throwIfNull(e,"authorizationToken"),l.throwIfNullOrWhitespace(t,"region");const i=new ge;return i.setProperty(p.SpeechServiceConnection_Region,t),i.setProperty(p.SpeechServiceConnection_IntentRegion,t),i.authorizationToken=e,i}close(){}}class ge extends bt{constructor(){super(),this.privProperties=new W,this.speechRecognitionLanguage="en-US",this.outputFormat=te.Simple}get properties(){return this.privProperties}get endPoint(){return new URL(this.privProperties.getProperty(p.SpeechServiceConnection_Endpoint))}get subscriptionKey(){return this.privProperties.getProperty(p.SpeechServiceConnection_Key)}get region(){return this.privProperties.getProperty(p.SpeechServiceConnection_Region)}get authorizationToken(){return this.privProperties.getProperty(p.SpeechServiceAuthorization_Token)}set authorizationToken(e){this.privProperties.setProperty(p.SpeechServiceAuthorization_Token,e)}get speechRecognitionLanguage(){return this.privProperties.getProperty(p.SpeechServiceConnection_RecoLanguage)}set speechRecognitionLanguage(e){this.privProperties.setProperty(p.SpeechServiceConnection_RecoLanguage,e)}get autoDetectSourceLanguages(){return this.privProperties.getProperty(p.SpeechServiceConnection_AutoDetectSourceLanguages)}set autoDetectSourceLanguages(e){this.privProperties.setProperty(p.SpeechServiceConnection_AutoDetectSourceLanguages,e)}get outputFormat(){return te[this.privProperties.getProperty(nt,void 0)]}set outputFormat(e){this.privProperties.setProperty(nt,te[e])}get endpointId(){return this.privProperties.getProperty(p.SpeechServiceConnection_EndpointId)}set endpointId(e){this.privProperties.setProperty(p.SpeechServiceConnection_EndpointId,e)}setProperty(e,t){l.throwIfNull(t,"value"),this.privProperties.setProperty(e,t)}getProperty(e,t){return this.privProperties.getProperty(e,t)}setProxy(e,t,i,n){this.setProperty(p[p.SpeechServiceConnection_ProxyHostName],e),this.setProperty(p[p.SpeechServiceConnection_ProxyPort],t),this.setProperty(p[p.SpeechServiceConnection_ProxyUserName],i),this.setProperty(p[p.SpeechServiceConnection_ProxyPassword],n)}setServiceProperty(e,t){const i=JSON.parse(this.privProperties.getProperty(xe,"{}"));i[e]=t,this.privProperties.setProperty(xe,JSON.stringify(i))}setProfanity(e){this.privProperties.setProperty(p.SpeechServiceResponse_ProfanityOption,Ge[e])}enableAudioLogging(){this.privProperties.setProperty(p.SpeechServiceConnection_EnableAudioLogging,"true")}requestWordLevelTimestamps(){this.privProperties.setProperty(p.SpeechServiceResponse_RequestWordLevelTimestamps,"true")}enableDictation(){this.privProperties.setProperty(Ei,"true")}clone(){const e=new ge;return e.privProperties=this.privProperties.clone(),e}get speechSynthesisLanguage(){return this.privProperties.getProperty(p.SpeechServiceConnection_SynthLanguage)}set speechSynthesisLanguage(e){this.privProperties.setProperty(p.SpeechServiceConnection_SynthLanguage,e)}get speechSynthesisVoiceName(){return this.privProperties.getProperty(p.SpeechServiceConnection_SynthVoice)}set speechSynthesisVoiceName(e){this.privProperties.setProperty(p.SpeechServiceConnection_SynthVoice,e)}get speechSynthesisOutputFormat(){return S[this.privProperties.getProperty(p.SpeechServiceConnection_SynthOutputFormat,void 0)]}set speechSynthesisOutputFormat(e){this.privProperties.setProperty(p.SpeechServiceConnection_SynthOutputFormat,S[e])}}class ri extends bt{constructor(){super()}static fromSubscription(e,t){l.throwIfNullOrWhitespace(e,"subscriptionKey"),l.throwIfNullOrWhitespace(t,"region");const i=new Ve;return i.properties.setProperty(p.SpeechServiceConnection_Key,e),i.properties.setProperty(p.SpeechServiceConnection_Region,t),i}static fromAuthorizationToken(e,t){l.throwIfNullOrWhitespace(e,"authorizationToken"),l.throwIfNullOrWhitespace(t,"region");const i=new Ve;return i.properties.setProperty(p.SpeechServiceAuthorization_Token,e),i.properties.setProperty(p.SpeechServiceConnection_Region,t),i}static fromHost(e,t){l.throwIfNull(e,"hostName");const i=new Ve;return i.setProperty(p.SpeechServiceConnection_Host,e.protocol+"//"+e.hostname+(e.port===""?"":":"+e.port)),t!==void 0&&i.setProperty(p.SpeechServiceConnection_Key,t),i}static fromEndpoint(e,t){l.throwIfNull(e,"endpoint"),l.throwIfNull(t,"subscriptionKey");const i=new Ve;return i.properties.setProperty(p.SpeechServiceConnection_Endpoint,e.href),i.properties.setProperty(p.SpeechServiceConnection_Key,t),i}}class Ve extends ri{constructor(){super(),this.privSpeechProperties=new W,this.outputFormat=te.Simple}set authorizationToken(e){l.throwIfNullOrWhitespace(e,"value"),this.privSpeechProperties.setProperty(p.SpeechServiceAuthorization_Token,e)}set speechRecognitionLanguage(e){l.throwIfNullOrWhitespace(e,"value"),this.privSpeechProperties.setProperty(p.SpeechServiceConnection_RecoLanguage,e)}get speechRecognitionLanguage(){return this.privSpeechProperties.getProperty(p[p.SpeechServiceConnection_RecoLanguage])}get subscriptionKey(){return this.privSpeechProperties.getProperty(p[p.SpeechServiceConnection_Key])}get outputFormat(){return te[this.privSpeechProperties.getProperty(nt,void 0)]}set outputFormat(e){this.privSpeechProperties.setProperty(nt,te[e])}get endpointId(){return this.privSpeechProperties.getProperty(p.SpeechServiceConnection_EndpointId)}set endpointId(e){this.privSpeechProperties.setProperty(p.SpeechServiceConnection_EndpointId,e)}addTargetLanguage(e){l.throwIfNullOrWhitespace(e,"value");const t=this.targetLanguages;t.push(e),this.privSpeechProperties.setProperty(p.SpeechServiceConnection_TranslationToLanguages,t.join(","))}get targetLanguages(){return this.privSpeechProperties.getProperty(p.SpeechServiceConnection_TranslationToLanguages,void 0)!==void 0?this.privSpeechProperties.getProperty(p.SpeechServiceConnection_TranslationToLanguages).split(","):[]}get voiceName(){return this.getProperty(p[p.SpeechServiceConnection_TranslationVoice])}set voiceName(e){l.throwIfNullOrWhitespace(e,"value"),this.privSpeechProperties.setProperty(p.SpeechServiceConnection_TranslationVoice,e)}get region(){return this.privSpeechProperties.getProperty(p.SpeechServiceConnection_Region)}setProxy(e,t,i,n){this.setProperty(p[p.SpeechServiceConnection_ProxyHostName],e),this.setProperty(p[p.SpeechServiceConnection_ProxyPort],t),this.setProperty(p[p.SpeechServiceConnection_ProxyUserName],i),this.setProperty(p[p.SpeechServiceConnection_ProxyPassword],n)}getProperty(e,t){return this.privSpeechProperties.getProperty(e,t)}setProperty(e,t){this.privSpeechProperties.setProperty(e,t)}get properties(){return this.privSpeechProperties}close(){}setServiceProperty(e,t){const i=JSON.parse(this.privSpeechProperties.getProperty(xe,"{}"));i[e]=t,this.privSpeechProperties.setProperty(xe,JSON.stringify(i))}setProfanity(e){this.privSpeechProperties.setProperty(p.SpeechServiceResponse_ProfanityOption,Ge[e])}enableAudioLogging(){this.privSpeechProperties.setProperty(p.SpeechServiceConnection_EnableAudioLogging,"true")}requestWordLevelTimestamps(){this.privSpeechProperties.setProperty(p.SpeechServiceResponse_RequestWordLevelTimestamps,"true")}enableDictation(){this.privSpeechProperties.setProperty(Ei,"true")}get speechSynthesisLanguage(){return this.privSpeechProperties.getProperty(p.SpeechServiceConnection_SynthLanguage)}set speechSynthesisLanguage(e){this.privSpeechProperties.setProperty(p.SpeechServiceConnection_SynthLanguage,e)}get speechSynthesisVoiceName(){return this.privSpeechProperties.getProperty(p.SpeechServiceConnection_SynthVoice)}set speechSynthesisVoiceName(e){this.privSpeechProperties.setProperty(p.SpeechServiceConnection_SynthVoice,e)}get speechSynthesisOutputFormat(){return S[this.privSpeechProperties.getProperty(p.SpeechServiceConnection_SynthOutputFormat,void 0)]}set speechSynthesisOutputFormat(e){this.privSpeechProperties.setProperty(p.SpeechServiceConnection_SynthOutputFormat,S[e])}}class W{constructor(){this.privKeys=[],this.privValues=[]}getProperty(e,t){let i;typeof e=="string"?i=e:i=p[e];for(let n=0;n<this.privKeys.length;n++)if(this.privKeys[n]===i)return this.privValues[n];if(t!==void 0)return String(t)}setProperty(e,t){let i;typeof e=="string"?i=e:i=p[e];for(let n=0;n<this.privKeys.length;n++)if(this.privKeys[n]===i){this.privValues[n]=t;return}this.privKeys.push(i),this.privValues.push(t)}clone(){const e=new W;for(let t=0;t<this.privKeys.length;t++)e.privKeys.push(this.privKeys[t]),e.privValues.push(this.privValues[t]);return e}mergeTo(e){this.privKeys.forEach(t=>{if(e.getProperty(t,void 0)===void 0){const i=this.getProperty(t);e.setProperty(t,i)}})}get keys(){return this.privKeys}}var p;(function(r){r[r.SpeechServiceConnection_Key=0]="SpeechServiceConnection_Key",r[r.SpeechServiceConnection_Endpoint=1]="SpeechServiceConnection_Endpoint",r[r.SpeechServiceConnection_Region=2]="SpeechServiceConnection_Region",r[r.SpeechServiceAuthorization_Token=3]="SpeechServiceAuthorization_Token",r[r.SpeechServiceAuthorization_Type=4]="SpeechServiceAuthorization_Type",r[r.SpeechServiceConnection_EndpointId=5]="SpeechServiceConnection_EndpointId",r[r.SpeechServiceConnection_TranslationToLanguages=6]="SpeechServiceConnection_TranslationToLanguages",r[r.SpeechServiceConnection_TranslationVoice=7]="SpeechServiceConnection_TranslationVoice",r[r.SpeechServiceConnection_TranslationFeatures=8]="SpeechServiceConnection_TranslationFeatures",r[r.SpeechServiceConnection_IntentRegion=9]="SpeechServiceConnection_IntentRegion",r[r.SpeechServiceConnection_ProxyHostName=10]="SpeechServiceConnection_ProxyHostName",r[r.SpeechServiceConnection_ProxyPort=11]="SpeechServiceConnection_ProxyPort",r[r.SpeechServiceConnection_ProxyUserName=12]="SpeechServiceConnection_ProxyUserName",r[r.SpeechServiceConnection_ProxyPassword=13]="SpeechServiceConnection_ProxyPassword",r[r.SpeechServiceConnection_RecoMode=14]="SpeechServiceConnection_RecoMode",r[r.SpeechServiceConnection_RecoLanguage=15]="SpeechServiceConnection_RecoLanguage",r[r.Speech_SessionId=16]="Speech_SessionId",r[r.SpeechServiceConnection_SynthLanguage=17]="SpeechServiceConnection_SynthLanguage",r[r.SpeechServiceConnection_SynthVoice=18]="SpeechServiceConnection_SynthVoice",r[r.SpeechServiceConnection_SynthOutputFormat=19]="SpeechServiceConnection_SynthOutputFormat",r[r.SpeechServiceConnection_AutoDetectSourceLanguages=20]="SpeechServiceConnection_AutoDetectSourceLanguages",r[r.SpeechServiceResponse_RequestDetailedResultTrueFalse=21]="SpeechServiceResponse_RequestDetailedResultTrueFalse",r[r.SpeechServiceResponse_RequestProfanityFilterTrueFalse=22]="SpeechServiceResponse_RequestProfanityFilterTrueFalse",r[r.SpeechServiceResponse_JsonResult=23]="SpeechServiceResponse_JsonResult",r[r.SpeechServiceResponse_JsonErrorDetails=24]="SpeechServiceResponse_JsonErrorDetails",r[r.CancellationDetails_Reason=25]="CancellationDetails_Reason",r[r.CancellationDetails_ReasonText=26]="CancellationDetails_ReasonText",r[r.CancellationDetails_ReasonDetailedText=27]="CancellationDetails_ReasonDetailedText",r[r.LanguageUnderstandingServiceResponse_JsonResult=28]="LanguageUnderstandingServiceResponse_JsonResult",r[r.SpeechServiceConnection_Url=29]="SpeechServiceConnection_Url",r[r.SpeechServiceConnection_InitialSilenceTimeoutMs=30]="SpeechServiceConnection_InitialSilenceTimeoutMs",r[r.SpeechServiceConnection_EndSilenceTimeoutMs=31]="SpeechServiceConnection_EndSilenceTimeoutMs",r[r.Speech_SegmentationSilenceTimeoutMs=32]="Speech_SegmentationSilenceTimeoutMs",r[r.SpeechServiceConnection_EnableAudioLogging=33]="SpeechServiceConnection_EnableAudioLogging",r[r.SpeechServiceConnection_AtStartLanguageIdPriority=34]="SpeechServiceConnection_AtStartLanguageIdPriority",r[r.SpeechServiceConnection_ContinuousLanguageIdPriority=35]="SpeechServiceConnection_ContinuousLanguageIdPriority",r[r.SpeechServiceConnection_RecognitionEndpointVersion=36]="SpeechServiceConnection_RecognitionEndpointVersion",r[r.SpeechServiceResponse_ProfanityOption=37]="SpeechServiceResponse_ProfanityOption",r[r.SpeechServiceResponse_PostProcessingOption=38]="SpeechServiceResponse_PostProcessingOption",r[r.SpeechServiceResponse_RequestWordLevelTimestamps=39]="SpeechServiceResponse_RequestWordLevelTimestamps",r[r.SpeechServiceResponse_StablePartialResultThreshold=40]="SpeechServiceResponse_StablePartialResultThreshold",r[r.SpeechServiceResponse_OutputFormatOption=41]="SpeechServiceResponse_OutputFormatOption",r[r.SpeechServiceResponse_TranslationRequestStablePartialResult=42]="SpeechServiceResponse_TranslationRequestStablePartialResult",r[r.SpeechServiceResponse_RequestWordBoundary=43]="SpeechServiceResponse_RequestWordBoundary",r[r.SpeechServiceResponse_RequestPunctuationBoundary=44]="SpeechServiceResponse_RequestPunctuationBoundary",r[r.SpeechServiceResponse_RequestSentenceBoundary=45]="SpeechServiceResponse_RequestSentenceBoundary",r[r.Conversation_ApplicationId=46]="Conversation_ApplicationId",r[r.Conversation_DialogType=47]="Conversation_DialogType",r[r.Conversation_Initial_Silence_Timeout=48]="Conversation_Initial_Silence_Timeout",r[r.Conversation_From_Id=49]="Conversation_From_Id",r[r.Conversation_Conversation_Id=50]="Conversation_Conversation_Id",r[r.Conversation_Custom_Voice_Deployment_Ids=51]="Conversation_Custom_Voice_Deployment_Ids",r[r.Conversation_Speech_Activity_Template=52]="Conversation_Speech_Activity_Template",r[r.Conversation_Request_Bot_Status_Messages=53]="Conversation_Request_Bot_Status_Messages",r[r.Conversation_Agent_Connection_Id=54]="Conversation_Agent_Connection_Id",r[r.SpeechServiceConnection_Host=55]="SpeechServiceConnection_Host",r[r.ConversationTranslator_Host=56]="ConversationTranslator_Host",r[r.ConversationTranslator_Name=57]="ConversationTranslator_Name",r[r.ConversationTranslator_CorrelationId=58]="ConversationTranslator_CorrelationId",r[r.ConversationTranslator_Token=59]="ConversationTranslator_Token",r[r.PronunciationAssessment_ReferenceText=60]="PronunciationAssessment_ReferenceText",r[r.PronunciationAssessment_GradingSystem=61]="PronunciationAssessment_GradingSystem",r[r.PronunciationAssessment_Granularity=62]="PronunciationAssessment_Granularity",r[r.PronunciationAssessment_EnableMiscue=63]="PronunciationAssessment_EnableMiscue",r[r.PronunciationAssessment_Json=64]="PronunciationAssessment_Json",r[r.PronunciationAssessment_Params=65]="PronunciationAssessment_Params",r[r.SpeakerRecognition_Api_Version=66]="SpeakerRecognition_Api_Version"})(p||(p={}));var Me=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};class Rt{constructor(e,t,i){this.audioConfig=e!==void 0?e:ee.fromDefaultMicrophoneInput(),this.privDisposed=!1,this.privProperties=t.clone(),this.privConnectionFactory=i,this.implCommonRecognizerSetup()}close(e,t){l.throwIfDisposed(this.privDisposed),J(this.dispose(!0),e,t)}get internalData(){return this.privReco}dispose(e){return Me(this,void 0,void 0,function*(){this.privDisposed||(this.privDisposed=!0,e&&this.privReco&&(yield this.privReco.audioSource.turnOff(),yield this.privReco.dispose()))})}static get telemetryEnabled(){return G.telemetryDataEnabled}static enableTelemetry(e){G.telemetryDataEnabled=e}implCommonRecognizerSetup(){let e=typeof window!="undefined"?"Browser":"Node",t="unknown",i="unknown";typeof navigator!="undefined"&&(e=e+"/"+navigator.platform,t=navigator.userAgent,i=navigator.appVersion);const n=this.createRecognizerConfig(new Ye(new et(new gi(e,t,i))));this.privReco=this.createServiceRecognizer(Rt.getAuthFromProperties(this.privProperties),this.privConnectionFactory,this.audioConfig,n)}recognizeOnceAsyncImpl(e){return Me(this,void 0,void 0,function*(){l.throwIfDisposed(this.privDisposed);const t=new D;yield this.implRecognizerStop(),yield this.privReco.recognize(e,t.resolve,t.reject);const i=yield t.promise;return yield this.implRecognizerStop(),i})}startContinuousRecognitionAsyncImpl(e){return Me(this,void 0,void 0,function*(){l.throwIfDisposed(this.privDisposed),yield this.implRecognizerStop(),yield this.privReco.recognize(e,void 0,void 0)})}stopContinuousRecognitionAsyncImpl(){return Me(this,void 0,void 0,function*(){l.throwIfDisposed(this.privDisposed),yield this.implRecognizerStop()})}implRecognizerStop(){return Me(this,void 0,void 0,function*(){this.privReco&&(yield this.privReco.stopRecognizing())})}static getAuthFromProperties(e){const t=e.getProperty(p.SpeechServiceConnection_Key,void 0);return t&&t!==""?new Ft(t):new de(()=>{const n=e.getProperty(p.SpeechServiceAuthorization_Token,void 0);return Promise.resolve(n)},()=>{const n=e.getProperty(p.SpeechServiceAuthorization_Token,void 0);return Promise.resolve(n)})}}class ni{constructor(e){this.privConnectionMessage=e,this.privProperties=new W,this.privConnectionMessage.headers[b.ConnectionId]&&this.privProperties.setProperty(p.Speech_SessionId,this.privConnectionMessage.headers[b.ConnectionId]),Object.keys(this.privConnectionMessage.headers).forEach(t=>{this.privProperties.setProperty(t,this.privConnectionMessage.headers[t])})}get path(){return this.privConnectionMessage.headers[Object.keys(this.privConnectionMessage.headers).find(e=>e.toLowerCase()==="path".toLowerCase())]}get isTextMessage(){return this.privConnectionMessage.messageType===y.Text}get isBinaryMessage(){return this.privConnectionMessage.messageType===y.Binary}get TextMessage(){return this.privConnectionMessage.textBody}get binaryMessage(){return this.privConnectionMessage.binaryBody}get properties(){return this.privProperties}toString(){return""}}class Fe{static fromRecognizer(e){const t=e.internalData,i=new Fe;return i.privInternalData=t,i.setupEvents(),i}static fromSynthesizer(e){const t=e.internalData,i=new Fe;return i.privInternalData=t,i.setupEvents(),i}openConnection(e,t){J(this.privInternalData.connect(),e,t)}closeConnection(e,t){if(this.privInternalData instanceof ne)throw new Error("Disconnecting a synthesizer's connection is currently not supported");J(this.privInternalData.disconnect(),e,t)}setMessageProperty(e,t,i){if(l.throwIfNullOrWhitespace(t,"propertyName"),this.privInternalData instanceof G){if(e.toLowerCase()!=="speech.context")throw new Error("Only speech.context message property sets are currently supported for recognizer");this.privInternalData.speechContext.setSection(t,i)}else if(this.privInternalData instanceof ne){if(e.toLowerCase()!=="synthesis.context")throw new Error("Only synthesis.context message property sets are currently supported for synthesizer");this.privInternalData.synthesisContext.setSection(t,i)}}sendMessageAsync(e,t,i,n){J(this.privInternalData.sendNetworkMessage(e,t),i,n)}close(){}setupEvents(){this.privEventListener=this.privInternalData.connectionEvents.attach(e=>{e.name==="ConnectionEstablishedEvent"?this.connected&&this.connected(new ai(e.connectionId)):e.name==="ConnectionClosedEvent"?this.disconnected&&this.disconnected(new ai(e.connectionId)):e.name==="ConnectionMessageSentEvent"?this.messageSent&&this.messageSent(new ci(new ni(e.message))):e.name==="ConnectionMessageReceivedEvent"&&this.messageReceived&&this.messageReceived(new ci(new ni(e.message)))}),this.privServiceEventListener=this.privInternalData.serviceEvents.attach(e=>{this.receivedServiceMessage&&this.receivedServiceMessage(new sr(e.jsonString,e.name))})}}var si=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};class rr extends Rt{constructor(e,t){const i=e;l.throwIfNull(i,"speechConfig"),super(t,i.properties,new gr),this.privDisposedTranslationRecognizer=!1,this.properties.getProperty(p.SpeechServiceConnection_TranslationVoice,void 0)!==void 0&&l.throwIfNullOrWhitespace(this.properties.getProperty(p.SpeechServiceConnection_TranslationVoice),p[p.SpeechServiceConnection_TranslationVoice]),l.throwIfNullOrWhitespace(this.properties.getProperty(p.SpeechServiceConnection_TranslationToLanguages),p[p.SpeechServiceConnection_TranslationToLanguages]),l.throwIfNullOrWhitespace(this.properties.getProperty(p.SpeechServiceConnection_RecoLanguage),p[p.SpeechServiceConnection_RecoLanguage])}get speechRecognitionLanguage(){return l.throwIfDisposed(this.privDisposedTranslationRecognizer),this.properties.getProperty(p.SpeechServiceConnection_RecoLanguage)}get targetLanguages(){return l.throwIfDisposed(this.privDisposedTranslationRecognizer),this.properties.getProperty(p.SpeechServiceConnection_TranslationToLanguages).split(",")}get voiceName(){return l.throwIfDisposed(this.privDisposedTranslationRecognizer),this.properties.getProperty(p.SpeechServiceConnection_TranslationVoice,void 0)}get properties(){return this.privProperties}get authorizationToken(){return this.properties.getProperty(p.SpeechServiceAuthorization_Token)}set authorizationToken(e){this.properties.setProperty(p.SpeechServiceAuthorization_Token,e)}recognizeOnceAsync(e,t){l.throwIfDisposed(this.privDisposedTranslationRecognizer),J(this.recognizeOnceAsyncImpl(he.Conversation),e,t)}startContinuousRecognitionAsync(e,t){J(this.startContinuousRecognitionAsyncImpl(he.Conversation),e,t)}stopContinuousRecognitionAsync(e,t){J(this.stopContinuousRecognitionAsyncImpl(),e,t)}removeTargetLanguage(e){if(l.throwIfNullOrUndefined(e,"language to be removed"),this.properties.getProperty(p.SpeechServiceConnection_TranslationToLanguages,void 0)!==void 0){const t=this.properties.getProperty(p.SpeechServiceConnection_TranslationToLanguages).split(","),i=t.indexOf(e);i>-1&&(t.splice(i,1),this.properties.setProperty(p.SpeechServiceConnection_TranslationToLanguages,t.join(",")),this.updateLanguages(t))}}addTargetLanguage(e){l.throwIfNullOrUndefined(e,"language to be added");let t=[];this.properties.getProperty(p.SpeechServiceConnection_TranslationToLanguages,void 0)!==void 0?(t=this.properties.getProperty(p.SpeechServiceConnection_TranslationToLanguages).split(","),t.includes(e)||(t.push(e),this.properties.setProperty(p.SpeechServiceConnection_TranslationToLanguages,t.join(",")))):(this.properties.setProperty(p.SpeechServiceConnection_TranslationToLanguages,e),t=[e]),this.updateLanguages(t)}close(e,t){l.throwIfDisposed(this.privDisposedTranslationRecognizer),J(this.dispose(!0),e,t)}onConnection(){}onDisconnection(){return si(this,void 0,void 0,function*(){})}dispose(e){const t=Object.create(null,{dispose:{get:()=>super.dispose}});return si(this,void 0,void 0,function*(){this.privDisposedTranslationRecognizer||(this.privDisposedTranslationRecognizer=!0,e&&(yield this.implRecognizerStop(),yield t.dispose.call(this,e)))})}createRecognizerConfig(e){return new lr(e,this.properties)}createServiceRecognizer(e,t,i,n){const s=i;return new mr(e,t,s,n,this)}updateLanguages(e){const t=Fe.fromRecognizer(this);t&&(t.setMessageProperty("speech.context","translationcontext",{to:e}),t.sendMessageAsync("event",JSON.stringify({id:"translation",name:"updateLanguage",to:e})))}}class nr{constructor(){this.privMap=new W}get languages(){return this.privMap.keys}get(e,t){return this.privMap.getProperty(e,t)}set(e,t){this.privMap.setProperty(e,t)}}class oi{constructor(e,t,i,n,s){this.privCancelReason=t,this.privErrorDetails=i,this.privResult=s,this.privSessionId=e,this.privErrorCode=n}get result(){return this.privResult}get sessionId(){return this.privSessionId}get reason(){return this.privCancelReason}get errorCode(){return this.privErrorCode}get errorDetails(){return this.privErrorDetails}}var A;(function(r){r[r.NoError=0]="NoError",r[r.AuthenticationFailure=1]="AuthenticationFailure",r[r.BadRequestParameters=2]="BadRequestParameters",r[r.TooManyRequests=3]="TooManyRequests",r[r.ConnectionFailure=4]="ConnectionFailure",r[r.ServiceTimeout=5]="ServiceTimeout",r[r.ServiceError=6]="ServiceError",r[r.RuntimeError=7]="RuntimeError",r[r.Forbidden=8]="Forbidden"})(A||(A={}));class ai extends fe{}class sr extends fe{constructor(e,t,i){super(i),this.privJsonResult=e,this.privEventName=t}get jsonString(){return this.privJsonResult}get eventName(){return this.privEventName}}class C{}C.BotId="botid",C.CustomSpeechDeploymentId="cid",C.CustomVoiceDeploymentId="deploymentId",C.EnableAudioLogging="storeAudio",C.EnableLanguageId="lidEnabled",C.EnableWordLevelTimestamps="wordLevelTimestamps",C.EndSilenceTimeoutMs="endSilenceTimeoutMs",C.SegmentationSilenceTimeoutMs="segmentationSilenceTimeoutMs",C.Format="format",C.InitialSilenceTimeoutMs="initialSilenceTimeoutMs",C.Language="language",C.Profanity="profanity",C.RequestBotStatusMessages="enableBotMessageStatus",C.StableIntermediateThreshold="stableIntermediateThreshold",C.StableTranslation="stableTranslation",C.TestHooks="testhooks",C.Postprocessing="postprocessing";class je{static getHostSuffix(e){if(e){if(e.toLowerCase().startsWith("china"))return".azure.cn";if(e.toLowerCase().startsWith("usgov"))return".azure.us"}return".microsoft.com"}setCommonUrlParams(e,t,i){new Map([[p.Speech_SegmentationSilenceTimeoutMs,C.SegmentationSilenceTimeoutMs],[p.SpeechServiceConnection_EnableAudioLogging,C.EnableAudioLogging],[p.SpeechServiceConnection_EndSilenceTimeoutMs,C.EndSilenceTimeoutMs],[p.SpeechServiceConnection_InitialSilenceTimeoutMs,C.InitialSilenceTimeoutMs],[p.SpeechServiceResponse_PostProcessingOption,C.Postprocessing],[p.SpeechServiceResponse_ProfanityOption,C.Profanity],[p.SpeechServiceResponse_RequestWordLevelTimestamps,C.EnableWordLevelTimestamps],[p.SpeechServiceResponse_StablePartialResultThreshold,C.StableIntermediateThreshold]]).forEach((o,a)=>{this.setUrlParameter(a,o,e,t,i)});const s=JSON.parse(e.parameters.getProperty(xe,"{}"));Object.keys(s).forEach(o=>{t[o]=s[o]})}setUrlParameter(e,t,i,n,s){const o=i.parameters.getProperty(e,void 0);o&&(!s||s.search(t)===-1)&&(n[t]=o.toLocaleLowerCase())}}var Ge;(function(r){r[r.Masked=0]="Masked",r[r.Removed=1]="Removed",r[r.Raw=2]="Raw"})(Ge||(Ge={}));class ci{constructor(e){this.privConnectionMessage=e}get message(){return this.privConnectionMessage}toString(){return"Message: "+this.privConnectionMessage.toString()}}var $e=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};class ze{constructor(e,t){const i=e;l.throwIfNull(i,"speechConfig"),t!==null&&(t===void 0?this.audioConfig=typeof window=="undefined"?void 0:ee.fromDefaultSpeakerOutput():this.audioConfig=t),this.privProperties=i.properties.clone(),this.privDisposed=!1,this.privSynthesizing=!1,this.privConnectionFactory=new Sr,this.synthesisRequestQueue=new Ae,this.implCommonSynthesizeSetup()}get authorizationToken(){return this.properties.getProperty(p.SpeechServiceAuthorization_Token)}set authorizationToken(e){l.throwIfNullOrWhitespace(e,"token"),this.properties.setProperty(p.SpeechServiceAuthorization_Token,e)}get properties(){return this.privProperties}get autoDetectSourceLanguage(){return this.properties.getProperty(p.SpeechServiceConnection_AutoDetectSourceLanguages)===Mr}static FromConfig(e,t,i){const n=e;return t.properties.mergeTo(n.properties),new ze(e,i)}buildSsml(e){const t={["af-ZA"]:"af-ZA-AdriNeural",["am-ET"]:"am-ET-AmehaNeural",["ar-AE"]:"ar-AE-FatimaNeural",["ar-BH"]:"ar-BH-AliNeural",["ar-DZ"]:"ar-DZ-AminaNeural",["ar-EG"]:"ar-EG-SalmaNeural",["ar-IQ"]:"ar-IQ-BasselNeural",["ar-JO"]:"ar-JO-SanaNeural",["ar-KW"]:"ar-KW-FahedNeural",["ar-LY"]:"ar-LY-ImanNeural",["ar-MA"]:"ar-MA-JamalNeural",["ar-QA"]:"ar-QA-AmalNeural",["ar-SA"]:"ar-SA-HamedNeural",["ar-SY"]:"ar-SY-AmanyNeural",["ar-TN"]:"ar-TN-HediNeural",["ar-YE"]:"ar-YE-MaryamNeural",["bg-BG"]:"bg-BG-BorislavNeural",["bn-BD"]:"bn-BD-NabanitaNeural",["bn-IN"]:"bn-IN-BashkarNeural",["ca-ES"]:"ca-ES-JoanaNeural",["cs-CZ"]:"cs-CZ-AntoninNeural",["cy-GB"]:"cy-GB-AledNeural",["da-DK"]:"da-DK-ChristelNeural",["de-AT"]:"de-AT-IngridNeural",["de-CH"]:"de-CH-JanNeural",["de-DE"]:"de-DE-KatjaNeural",["el-GR"]:"el-GR-AthinaNeural",["en-AU"]:"en-AU-NatashaNeural",["en-CA"]:"en-CA-ClaraNeural",["en-GB"]:"en-GB-LibbyNeural",["en-HK"]:"en-HK-SamNeural",["en-IE"]:"en-IE-ConnorNeural",["en-IN"]:"en-IN-NeerjaNeural",["en-KE"]:"en-KE-AsiliaNeural",["en-NG"]:"en-NG-AbeoNeural",["en-NZ"]:"en-NZ-MitchellNeural",["en-PH"]:"en-PH-JamesNeural",["en-SG"]:"en-SG-LunaNeural",["en-TZ"]:"en-TZ-ElimuNeural",["en-US"]:"en-US-JennyNeural",["en-ZA"]:"en-ZA-LeahNeural",["es-AR"]:"es-AR-ElenaNeural",["es-BO"]:"es-BO-MarceloNeural",["es-CL"]:"es-CL-CatalinaNeural",["es-CO"]:"es-CO-GonzaloNeural",["es-CR"]:"es-CR-JuanNeural",["es-CU"]:"es-CU-BelkysNeural",["es-DO"]:"es-DO-EmilioNeural",["es-EC"]:"es-EC-AndreaNeural",["es-ES"]:"es-ES-AlvaroNeural",["es-GQ"]:"es-GQ-JavierNeural",["es-GT"]:"es-GT-AndresNeural",["es-HN"]:"es-HN-CarlosNeural",["es-MX"]:"es-MX-DaliaNeural",["es-NI"]:"es-NI-FedericoNeural",["es-PA"]:"es-PA-MargaritaNeural",["es-PE"]:"es-PE-AlexNeural",["es-PR"]:"es-PR-KarinaNeural",["es-PY"]:"es-PY-MarioNeural",["es-SV"]:"es-SV-LorenaNeural",["es-US"]:"es-US-AlonsoNeural",["es-UY"]:"es-UY-MateoNeural",["es-VE"]:"es-VE-PaolaNeural",["et-EE"]:"et-EE-AnuNeural",["fa-IR"]:"fa-IR-DilaraNeural",["fi-FI"]:"fi-FI-SelmaNeural",["fil-PH"]:"fil-PH-AngeloNeural",["fr-BE"]:"fr-BE-CharlineNeural",["fr-CA"]:"fr-CA-SylvieNeural",["fr-CH"]:"fr-CH-ArianeNeural",["fr-FR"]:"fr-FR-DeniseNeural",["ga-IE"]:"ga-IE-ColmNeural",["gl-ES"]:"gl-ES-RoiNeural",["gu-IN"]:"gu-IN-DhwaniNeural",["he-IL"]:"he-IL-AvriNeural",["hi-IN"]:"hi-IN-MadhurNeural",["hr-HR"]:"hr-HR-GabrijelaNeural",["hu-HU"]:"hu-HU-NoemiNeural",["id-ID"]:"id-ID-ArdiNeural",["is-IS"]:"is-IS-GudrunNeural",["it-IT"]:"it-IT-IsabellaNeural",["ja-JP"]:"ja-JP-NanamiNeural",["jv-ID"]:"jv-ID-DimasNeural",["kk-KZ"]:"kk-KZ-AigulNeural",["km-KH"]:"km-KH-PisethNeural",["kn-IN"]:"kn-IN-GaganNeural",["ko-KR"]:"ko-KR-SunHiNeural",["lo-LA"]:"lo-LA-ChanthavongNeural",["lt-LT"]:"lt-LT-LeonasNeural",["lv-LV"]:"lv-LV-EveritaNeural",["mk-MK"]:"mk-MK-AleksandarNeural",["ml-IN"]:"ml-IN-MidhunNeural",["mr-IN"]:"mr-IN-AarohiNeural",["ms-MY"]:"ms-MY-OsmanNeural",["mt-MT"]:"mt-MT-GraceNeural",["my-MM"]:"my-MM-NilarNeural",["nb-NO"]:"nb-NO-PernilleNeural",["nl-BE"]:"nl-BE-ArnaudNeural",["nl-NL"]:"nl-NL-ColetteNeural",["pl-PL"]:"pl-PL-AgnieszkaNeural",["ps-AF"]:"ps-AF-GulNawazNeural",["pt-BR"]:"pt-BR-FranciscaNeural",["pt-PT"]:"pt-PT-DuarteNeural",["ro-RO"]:"ro-RO-AlinaNeural",["ru-RU"]:"ru-RU-SvetlanaNeural",["si-LK"]:"si-LK-SameeraNeural",["sk-SK"]:"sk-SK-LukasNeural",["sl-SI"]:"sl-SI-PetraNeural",["so-SO"]:"so-SO-MuuseNeural",["sr-RS"]:"sr-RS-NicholasNeural",["su-ID"]:"su-ID-JajangNeural",["sv-SE"]:"sv-SE-SofieNeural",["sw-KE"]:"sw-KE-RafikiNeural",["sw-TZ"]:"sw-TZ-DaudiNeural",["ta-IN"]:"ta-IN-PallaviNeural",["ta-LK"]:"ta-LK-KumarNeural",["ta-SG"]:"ta-SG-AnbuNeural",["te-IN"]:"te-IN-MohanNeural",["th-TH"]:"th-TH-PremwadeeNeural",["tr-TR"]:"tr-TR-AhmetNeural",["uk-UA"]:"uk-UA-OstapNeural",["ur-IN"]:"ur-IN-GulNeural",["ur-PK"]:"ur-PK-AsadNeural",["uz-UZ"]:"uz-UZ-MadinaNeural",["vi-VN"]:"vi-VN-HoaiMyNeural",["zh-CN"]:"zh-CN-XiaoxiaoNeural",["zh-HK"]:"zh-HK-HiuMaanNeural",["zh-TW"]:"zh-TW-HsiaoChenNeural",["zu-ZA"]:"zu-ZA-ThandoNeural"};let i=this.properties.getProperty(p.SpeechServiceConnection_SynthLanguage,"en-US"),n=this.properties.getProperty(p.SpeechServiceConnection_SynthVoice,""),s=ze.XMLEncode(e);return this.autoDetectSourceLanguage?i="en-US":n=n||t[i],n&&(s=`<voice name='${n}'>${s}</voice>`),s=`<speak version='1.0' xmlns='http://www.w3.org/2001/10/synthesis' xmlns:mstts='http://www.w3.org/2001/mstts' xmlns:emo='http://www.w3.org/2009/10/emotionml' xml:lang='${i}'>${s}</speak>`,s}speakTextAsync(e,t,i,n){this.speakImpl(e,!1,t,i,n)}speakSsmlAsync(e,t,i,n){this.speakImpl(e,!0,t,i,n)}getVoicesAsync(e=""){return $e(this,void 0,void 0,function*(){return this.getVoices(e)})}close(e,t){l.throwIfDisposed(this.privDisposed),J(this.dispose(!0),e,t)}get internalData(){return this.privAdapter}dispose(e){return $e(this,void 0,void 0,function*(){this.privDisposed||(e&&this.privAdapter&&(yield this.privAdapter.dispose()),this.privDisposed=!0)})}createSynthesizerConfig(e){return new Pr(e,this.privProperties)}createSynthesisAdapter(e,t,i,n){return new ne(e,t,n,this,this.audioConfig)}implCommonSynthesizeSetup(){let e=typeof window!="undefined"?"Browser":"Node",t="unknown",i="unknown";typeof navigator!="undefined"&&(e=e+"/"+navigator.platform,t=navigator.userAgent,i=navigator.appVersion);const n=this.createSynthesizerConfig(new Ye(new et(new gi(e,t,i)))),s=this.privProperties.getProperty(p.SpeechServiceConnection_Key,void 0),o=s&&s!==""?new Ft(s):new de(()=>{const a=this.privProperties.getProperty(p.SpeechServiceAuthorization_Token,void 0);return Promise.resolve(a)},()=>{const a=this.privProperties.getProperty(p.SpeechServiceAuthorization_Token,void 0);return Promise.resolve(a)});this.privAdapter=this.createSynthesisAdapter(o,this.privConnectionFactory,this.audioConfig,n),this.privAdapter.audioOutputFormat=g.fromSpeechSynthesisOutputFormat(S[this.properties.getProperty(p.SpeechServiceConnection_SynthOutputFormat,void 0)]),this.privRestAdapter=new Ar(n)}speakImpl(e,t,i,n,s){try{l.throwIfDisposed(this.privDisposed);const o=R();let a;s instanceof Yt?a=new Ct(s):s instanceof We?a=s:s!==void 0?a=new Gt(s):a=void 0,this.synthesisRequestQueue.enqueue(new or(o,e,t,u=>{if(this.privSynthesizing=!1,i)try{i(u)}catch(h){n&&n(h)}i=void 0,this.adapterSpeak().catch(()=>{})},u=>{n&&n(u)},a)),this.adapterSpeak().catch(()=>{})}catch(o){if(n)if(o instanceof Error){const a=o;n(a.name+": "+a.message)}else n(o);this.dispose(!0).catch(()=>{})}}getVoices(e){return $e(this,void 0,void 0,function*(){const t=R(),i=yield this.privRestAdapter.getVoicesList(t);if(i.ok&&Array.isArray(i.json)){let n=i.json;return!!e&&e.length>0&&(n=n.filter(s=>!!s.Locale&&s.Locale.toLowerCase()===e.toLowerCase())),new ui(t,n,void 0)}else return new ui(t,void 0,`Error: ${i.status}: ${i.statusText}`)})}adapterSpeak(){return $e(this,void 0,void 0,function*(){if(!this.privDisposed&&!this.privSynthesizing){this.privSynthesizing=!0;const e=yield this.synthesisRequestQueue.dequeue();return this.privAdapter.Speak(e.text,e.isSSML,e.requestId,e.cb,e.err,e.dataStream)}})}static XMLEncode(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}}class or{constructor(e,t,i,n,s,o){this.requestId=e,this.text=t,this.isSSML=i,this.cb=n,this.err=s,this.dataStream=o}}class hi{constructor(e,t,i,n){this.privResultId=e,this.privReason=t,this.privErrorDetails=i,this.privProperties=n}get resultId(){return this.privResultId}get reason(){return this.privReason}get errorDetails(){return this.privErrorDetails}get properties(){return this.privProperties}}class Je extends hi{constructor(e,t,i,n,s,o){super(e,t,n,s),this.privAudioData=i,this.privAudioDuration=o}get audioData(){return this.privAudioData}get audioDuration(){return this.privAudioDuration}}class Qe{constructor(e){this.privResult=e}get result(){return this.privResult}}class ar{constructor(e,t,i,n,s,o){this.privAudioOffset=e,this.privDuration=t,this.privText=i,this.privWordLength=n,this.privTextOffset=s,this.privBoundaryType=o}get audioOffset(){return this.privAudioOffset}get duration(){return this.privDuration}get text(){return this.privText}get wordLength(){return this.privWordLength}get textOffset(){return this.privTextOffset}get boundaryType(){return this.privBoundaryType}}class cr{constructor(e,t){this.privAudioOffset=e,this.privText=t}get audioOffset(){return this.privAudioOffset}get text(){return this.privText}}class hr{constructor(e,t,i){this.privAudioOffset=e,this.privVisemeId=t,this.privAnimation=i}get audioOffset(){return this.privAudioOffset}get visemeId(){return this.privVisemeId}get animation(){return this.privAnimation}}class ui extends hi{constructor(e,t,i){if(Array.isArray(t)){super(e,P.VoicesListRetrieved,void 0,new W),this.privVoices=[];for(const n of t)this.privVoices.push(new ur(n))}else super(e,P.Canceled,i||"Error information unavailable",new W)}get voices(){return this.privVoices}}var ke;(function(r){r[r.Unknown=0]="Unknown",r[r.Female=1]="Female",r[r.Male=2]="Male"})(ke||(ke={}));var Xe;(function(r){r[r.OnlineNeural=1]="OnlineNeural",r[r.OnlineStandard=2]="OnlineStandard",r[r.OfflineNeural=3]="OfflineNeural",r[r.OfflineStandard=4]="OfflineStandard"})(Xe||(Xe={}));class ur{constructor(e){if(this.privStyleList=[],this.privVoicePath="",e&&(this.privName=e.Name,this.privLocale=e.Locale,this.privShortName=e.ShortName,this.privLocalName=e.LocalName,this.privVoiceType=e.VoiceType.endsWith("Standard")?Xe.OnlineStandard:Xe.OnlineNeural,this.privGender=e.Gender==="Male"?ke.Male:e.Gender==="Female"?ke.Female:ke.Unknown,!!e.StyleList&&Array.isArray(e.StyleList)))for(const t of e.StyleList)this.privStyleList.push(t)}get name(){return this.privName}get locale(){return this.privLocale}get shortName(){return this.privShortName}get localName(){return this.privLocalName}get gender(){return this.privGender}get voiceType(){return this.privVoiceType}get styleList(){return this.privStyleList}get voicePath(){return this.privVoicePath}}var At=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};const pr=60*30,pi={[v.PCM]:"audio/wav",[v.MuLaw]:"audio/x-wav",[v.MP3]:"audio/mpeg",[v.OGG_OPUS]:"audio/ogg",[v.WEBM_OPUS]:"audio/webm; codecs=opus",[v.ALaw]:"audio/x-wav",[v.FLAC]:"audio/flac"};class Pt{constructor(e){this.privPlaybackStarted=!1,this.privAppendingToBuffer=!1,this.privMediaSourceOpened=!1,this.privBytesReceived=0,this.privId=e||R(),this.privIsPaused=!1,this.privIsClosed=!1}id(){return this.privId}write(e,t,i){this.privAudioBuffer!==void 0?(this.privAudioBuffer.push(e),this.updateSourceBuffer().then(()=>{t&&t()},n=>{i&&i(n)})):this.privAudioOutputStream!==void 0&&(this.privAudioOutputStream.write(e),this.privBytesReceived+=e.byteLength)}close(e,t){if(this.privIsClosed=!0,this.privSourceBuffer!==void 0)this.handleSourceBufferUpdateEnd().then(()=>{e&&e()},i=>{t&&t(i)});else if(this.privAudioOutputStream!==void 0&&typeof window!="undefined")if((this.privFormat.formatTag===v.PCM||this.privFormat.formatTag===v.MuLaw||this.privFormat.formatTag===v.ALaw)&&this.privFormat.hasHeader===!1)console.warn("Play back is not supported for raw PCM, mulaw or alaw format without header."),this.onAudioEnd&&this.onAudioEnd(this);else{let i=new ArrayBuffer(this.privBytesReceived);this.privAudioOutputStream.read(i).then(()=>{i=ne.addHeader(i,this.privFormat);const n=new Blob([i],{type:pi[this.privFormat.formatTag]});this.privAudio.src=window.URL.createObjectURL(n),this.notifyPlayback().then(()=>{e&&e()},s=>{t&&t(s)})},n=>{t&&t(n)})}else this.onAudioEnd&&this.onAudioEnd(this)}set format(e){if(typeof AudioContext!="undefined"||typeof window!="undefined"&&typeof window.webkitAudioContext!="undefined"){this.privFormat=e;const t=pi[this.privFormat.formatTag];t===void 0?console.warn(`Unknown mimeType for format ${v[this.privFormat.formatTag]}; playback is not supported.`):typeof MediaSource!="undefined"&&MediaSource.isTypeSupported(t)?(this.privAudio=new Audio,this.privAudioBuffer=[],this.privMediaSource=new MediaSource,this.privAudio.src=URL.createObjectURL(this.privMediaSource),this.privAudio.load(),this.privMediaSource.onsourceopen=()=>{this.privMediaSourceOpened=!0,this.privMediaSource.duration=pr,this.privSourceBuffer=this.privMediaSource.addSourceBuffer(t),this.privSourceBuffer.onupdate=()=>{this.updateSourceBuffer().catch(i=>{L.instance.onEvent(new Ie(i))})},this.privSourceBuffer.onupdateend=()=>{this.handleSourceBufferUpdateEnd().catch(i=>{L.instance.onEvent(new Ie(i))})},this.privSourceBuffer.onupdatestart=()=>{this.privAppendingToBuffer=!1}},this.updateSourceBuffer().catch(i=>{L.instance.onEvent(new Ie(i))})):(console.warn(`Format ${v[this.privFormat.formatTag]} could not be played by MSE, streaming playback is not enabled.`),this.privAudioOutputStream=new wt,this.privAudioOutputStream.format=this.privFormat,this.privAudio=new Audio)}}get volume(){var e,t;return(t=(e=this.privAudio)===null||e===void 0?void 0:e.volume)!==null&&t!==void 0?t:-1}set volume(e){this.privAudio&&(this.privAudio.volume=e)}mute(){this.privAudio&&(this.privAudio.muted=!0)}unmute(){this.privAudio&&(this.privAudio.muted=!1)}get isClosed(){return this.privIsClosed}get currentTime(){return this.privAudio!==void 0?this.privAudio.currentTime:-1}pause(){!this.privIsPaused&&this.privAudio!==void 0&&(this.privAudio.pause(),this.privIsPaused=!0)}resume(e,t){this.privIsPaused&&this.privAudio!==void 0&&(this.privAudio.play().then(()=>{e&&e()},i=>{t&&t(i)}),this.privIsPaused=!1)}get internalAudio(){return this.privAudio}updateSourceBuffer(){return At(this,void 0,void 0,function*(){if(this.privAudioBuffer!==void 0&&this.privAudioBuffer.length>0&&this.sourceBufferAvailable()){this.privAppendingToBuffer=!0;const e=this.privAudioBuffer.shift();try{this.privSourceBuffer.appendBuffer(e)}catch{this.privAudioBuffer.unshift(e),console.log("buffer filled, pausing addition of binaries until space is made");return}yield this.notifyPlayback()}else this.canEndStream()&&(yield this.handleSourceBufferUpdateEnd())})}handleSourceBufferUpdateEnd(){return At(this,void 0,void 0,function*(){this.canEndStream()&&this.sourceBufferAvailable()&&(this.privMediaSource.endOfStream(),yield this.notifyPlayback())})}notifyPlayback(){return At(this,void 0,void 0,function*(){!this.privPlaybackStarted&&this.privAudio!==void 0&&(this.privPlaybackStarted=!0,this.onAudioStart&&this.onAudioStart(this),this.privAudio.onended=()=>{this.onAudioEnd&&this.onAudioEnd(this)},this.privIsPaused||(yield this.privAudio.play()))})}canEndStream(){return this.isClosed&&this.privSourceBuffer!==void 0&&this.privAudioBuffer.length===0&&this.privMediaSourceOpened&&!this.privAppendingToBuffer&&this.privMediaSource.readyState==="open"}sourceBufferAvailable(){return this.privSourceBuffer!==void 0&&!this.privSourceBuffer.updating}}class Ze extends ae{constructor(e,t,i,n=w.Info){super(e,n),this.privRequestId=t,this.privSessionId=i}get requestId(){return this.privRequestId}get sessionId(){return this.privSessionId}}class di extends Ze{constructor(e,t,i,n){super("RecognitionTriggeredEvent",e,t),this.privAudioSourceId=i,this.privAudioNodeId=n}get audioSourceId(){return this.privAudioSourceId}get audioNodeId(){return this.privAudioNodeId}}class dr extends Ze{constructor(e,t,i,n){super("ListeningStartedEvent",e,t),this.privAudioSourceId=i,this.privAudioNodeId=n}get audioSourceId(){return this.privAudioSourceId}get audioNodeId(){return this.privAudioNodeId}}class vi extends Ze{constructor(e,t,i){super("ConnectingToServiceEvent",e,i),this.privAuthFetchEventid=t}get authFetchEventid(){return this.privAuthFetchEventid}}class vr extends Ze{constructor(e,t,i,n,s){super("RecognitionStartedEvent",e,s),this.privAudioSourceId=t,this.privAudioNodeId=i,this.privAuthFetchEventId=n}get audioSourceId(){return this.privAudioSourceId}get audioNodeId(){return this.privAudioNodeId}get authFetchEventId(){return this.privAuthFetchEventId}}var li;(function(r){r[r.Success=0]="Success",r[r.AudioSourceError=1]="AudioSourceError",r[r.AudioSourceTimeout=2]="AudioSourceTimeout",r[r.AuthTokenFetchError=3]="AuthTokenFetchError",r[r.AuthTokenFetchTimeout=4]="AuthTokenFetchTimeout",r[r.UnAuthorized=5]="UnAuthorized",r[r.ConnectTimeout=6]="ConnectTimeout",r[r.ConnectError=7]="ConnectError",r[r.ClientRecognitionActivityTimeout=8]="ClientRecognitionActivityTimeout",r[r.UnknownError=9]="UnknownError"})(li||(li={}));class _ extends lt{constructor(e,t,i,n,s,o,a,u){if(!t)throw new z("path");if(!i)throw new z("requestId");const h={};if(h[b.Path]=t,h[b.RequestId]=i,h[b.RequestTimestamp]=new Date().toISOString(),n&&(h[b.ContentType]=n),o&&(h[b.RequestStreamId]=o),a)for(const c in a)c&&(h[c]=a[c]);u?super(e,s,h,u):super(e,s,h),this.privPath=t,this.privRequestId=i,this.privContentType=n,this.privStreamId=o,this.privAdditionalHeaders=a}get path(){return this.privPath}get requestId(){return this.privRequestId}get contentType(){return this.privContentType}get streamId(){return this.privStreamId}get additionalHeaders(){return this.privAdditionalHeaders}static fromConnectionMessage(e){let t=null,i=null,n=null,s=null;const o={};if(e.headers)for(const a in e.headers)a&&(a.toLowerCase()===b.Path.toLowerCase()?t=e.headers[a]:a.toLowerCase()===b.RequestId.toLowerCase()?i=e.headers[a]:a.toLowerCase()===b.ContentType.toLowerCase()?n=e.headers[a]:a.toLowerCase()===b.RequestStreamId.toLowerCase()?s=e.headers[a]:o[a]=e.headers[a]);return new _(e.messageType,t,i,n,e.body,s,o,e.id)}}var x=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};class G{constructor(e,t,i,n,s){if(this.privConnectionConfigurationPromise=void 0,this.privConnectionPromise=void 0,this.privSetTimeout=setTimeout,this.privIsLiveAudio=!1,this.recognizeOverride=void 0,this.disconnectOverride=void 0,this.receiveMessageOverride=void 0,this.sendPrePayloadJSONOverride=void 0,this.postConnectImplOverride=void 0,this.configConnectionOverride=void 0,!e)throw new z("authentication");if(!t)throw new z("connectionFactory");if(!i)throw new z("audioSource");if(!n)throw new z("recognizerConfig");this.privMustReportEndOfStream=!1,this.privAuthentication=e,this.privConnectionFactory=t,this.privAudioSource=i,this.privRecognizerConfig=n,this.privIsDisposed=!1,this.privRecognizer=s,this.privRequestSession=new wr(this.privAudioSource.id()),this.privConnectionEvents=new F,this.privServiceEvents=new F,this.privDynamicGrammar=new Er,this.privSpeechContext=new Cr(this.privDynamicGrammar),this.privAgentConfig=new wi,typeof Blob!="undefined"&&typeof Worker!="undefined"&&(this.privSetTimeout=O.setTimeout),this.connectionEvents.attach(o=>{if(o.name==="ConnectionClosedEvent"){const a=o;(a.statusCode===1003||a.statusCode===1007||a.statusCode===1002||a.statusCode===4e3||this.privRequestSession.numConnectionAttempts>this.privRecognizerConfig.maxRetryCount)&&this.cancelRecognitionLocal(H.Error,a.statusCode===1007?A.BadRequestParameters:A.ConnectionFailure,`${a.reason} websocket error code: ${a.statusCode}`)}})}get audioSource(){return this.privAudioSource}get speechContext(){return this.privSpeechContext}get dynamicGrammar(){return this.privDynamicGrammar}get agentConfig(){return this.privAgentConfig}set conversationTranslatorToken(e){this.privRecognizerConfig.parameters.setProperty(p.ConversationTranslator_Token,e)}set authentication(e){this.privAuthentication=this.authentication}isDisposed(){return this.privIsDisposed}dispose(e){return x(this,void 0,void 0,function*(){if(this.privIsDisposed=!0,this.privConnectionConfigurationPromise!==void 0)try{yield(yield this.privConnectionConfigurationPromise).dispose(e)}catch{return}})}get connectionEvents(){return this.privConnectionEvents}get serviceEvents(){return this.privServiceEvents}get recognitionMode(){return this.privRecognizerConfig.recognitionMode}recognize(e,t,i){return x(this,void 0,void 0,function*(){if(this.recognizeOverride!==void 0){yield this.recognizeOverride(e,t,i);return}this.privConnectionConfigurationPromise=void 0,this.privRecognizerConfig.recognitionMode=e,this.privSuccessCallback=t,this.privErrorCallback=i,this.privRequestSession.startNewRecognition(),this.privRequestSession.listenForServiceTelemetry(this.privAudioSource.events);const n=this.connectImpl();let s;try{const u=yield this.audioSource.attach(this.privRequestSession.audioNodeId),h=yield this.audioSource.format,c=yield this.audioSource.deviceInfo;this.privIsLiveAudio=c.type&&c.type===ue.Microphones,s=new xr(u,h.avgBytesPerSec),yield this.privRequestSession.onAudioSourceAttachCompleted(s,!1),this.privRecognizerConfig.SpeechServiceConfig.Context.audio={source:c}}catch(u){throw yield this.privRequestSession.onStopRecognizing(),u}try{yield n}catch(u){yield this.cancelRecognitionLocal(H.Error,A.ConnectionFailure,u);return}const o=new fe(this.privRequestSession.sessionId);this.privRecognizer.sessionStarted&&this.privRecognizer.sessionStarted(this.privRecognizer,o),this.receiveMessage(),this.sendAudio(s).catch(u=>x(this,void 0,void 0,function*(){yield this.cancelRecognitionLocal(H.Error,A.RuntimeError,u)}))})}stopRecognizing(){return x(this,void 0,void 0,function*(){if(this.privRequestSession.isRecognizing)try{yield this.audioSource.turnOff(),yield this.sendFinalAudio(),yield this.privRequestSession.onStopRecognizing(),yield this.privRequestSession.turnCompletionPromise}finally{yield this.privRequestSession.dispose()}})}connect(){return x(this,void 0,void 0,function*(){return yield this.connectImpl(),Promise.resolve()})}connectAsync(e,t){this.connectImpl().then(()=>{try{e&&e()}catch(i){t&&t(i)}},i=>{try{t&&t(i)}catch{}})}disconnect(){return x(this,void 0,void 0,function*(){if(yield this.cancelRecognitionLocal(H.Error,A.NoError,"Disconnecting"),this.disconnectOverride!==void 0&&(yield this.disconnectOverride()),this.privConnectionPromise!==void 0)try{yield(yield this.privConnectionPromise).dispose()}catch{}this.privConnectionPromise=void 0})}sendMessage(e){}sendNetworkMessage(e,t){return x(this,void 0,void 0,function*(){const i=typeof t=="string"?y.Text:y.Binary,n=typeof t=="string"?"application/json":"";return(yield this.fetchConnection()).send(new _(i,e,this.privRequestSession.requestId,n,t))})}set activityTemplate(e){this.privActivityTemplate=e}get activityTemplate(){return this.privActivityTemplate}sendTelemetryData(){return x(this,void 0,void 0,function*(){const e=this.privRequestSession.getTelemetry();if(G.telemetryDataEnabled!==!0||this.privIsDisposed||e===null)return;if(G.telemetryData)try{G.telemetryData(e)}catch{}yield(yield this.fetchConnection()).send(new _(y.Text,"telemetry",this.privRequestSession.requestId,"application/json",e))})}cancelRecognitionLocal(e,t,i){return x(this,void 0,void 0,function*(){this.privRequestSession.isRecognizing&&(yield this.privRequestSession.onStopRecognizing(),this.cancelRecognition(this.privRequestSession.sessionId,this.privRequestSession.requestId,e,t,i))})}receiveMessage(){return x(this,void 0,void 0,function*(){try{if(this.privIsDisposed)return;let e=yield this.fetchConnection();const t=yield e.read();if(this.receiveMessageOverride!==void 0)return this.receiveMessageOverride();if(!t)return this.privRequestSession.isRecognizing?this.receiveMessage():void 0;this.privServiceHasSentMessage=!0;const i=_.fromConnectionMessage(t);if(i.requestId.toLowerCase()===this.privRequestSession.requestId.toLowerCase())switch(i.path.toLowerCase()){case"turn.start":this.privMustReportEndOfStream=!0,this.privRequestSession.onServiceTurnStartResponse();break;case"speech.startdetected":const n=it.fromJSON(i.textBody),s=new Et(n.Offset,this.privRequestSession.sessionId);this.privRecognizer.speechStartDetected&&this.privRecognizer.speechStartDetected(this.privRecognizer,s);break;case"speech.enddetected":let o;i.textBody.length>0?o=i.textBody:o="{ Offset: 0 }";const a=it.fromJSON(o);this.privRecognizerConfig.isContinuousRecognition&&this.privRequestSession.onServiceRecognized(a.Offset+this.privRequestSession.currentTurnAudioOffset);const u=new Et(a.Offset+this.privRequestSession.currentTurnAudioOffset,this.privRequestSession.sessionId);this.privRecognizer.speechEndDetected&&this.privRecognizer.speechEndDetected(this.privRecognizer,u);break;case"turn.end":yield this.sendTelemetryData(),this.privRequestSession.isSpeechEnded&&this.privMustReportEndOfStream&&(this.privMustReportEndOfStream=!1,yield this.cancelRecognitionLocal(H.EndOfStream,A.NoError,void 0));const h=new fe(this.privRequestSession.sessionId);if(yield this.privRequestSession.onServiceTurnEndResponse(this.privRecognizerConfig.isContinuousRecognition),!this.privRecognizerConfig.isContinuousRecognition||this.privRequestSession.isSpeechEnded||!this.privRequestSession.isRecognizing){this.privRecognizer.sessionStopped&&this.privRecognizer.sessionStopped(this.privRecognizer,h);return}else e=yield this.fetchConnection(),yield this.sendPrePayloadJSON(e);break;default:(yield this.processTypeSpecificMessages(i))||this.privServiceEvents&&this.serviceEvents.onEvent(new _t(i.path.toLowerCase(),i.textBody))}return this.receiveMessage()}catch{return null}})}sendSpeechContext(e,t){const i=this.speechContext.toJSON();if(t&&this.privRequestSession.onSpeechContext(),i)return e.send(new _(y.Text,"speech.context",this.privRequestSession.requestId,"application/json",i))}sendPrePayloadJSON(e,t=!0){return x(this,void 0,void 0,function*(){if(this.sendPrePayloadJSONOverride!==void 0)return this.sendPrePayloadJSONOverride(e);yield this.sendSpeechContext(e,t),yield this.sendWaveHeader(e)})}sendWaveHeader(e){return x(this,void 0,void 0,function*(){const t=yield this.audioSource.format;return e.send(new _(y.Binary,"audio",this.privRequestSession.requestId,"audio/x-wav",t.header))})}connectImpl(){return this.privConnectionPromise!==void 0?this.privConnectionPromise.then(e=>e.state()===k.Disconnected?(this.privConnectionId=null,this.privConnectionPromise=void 0,this.privServiceHasSentMessage=!1,this.connectImpl()):this.privConnectionPromise,()=>(this.privConnectionId=null,this.privConnectionPromise=void 0,this.privServiceHasSentMessage=!1,this.connectImpl())):(this.privConnectionPromise=this.retryableConnect(),this.privConnectionPromise.catch(()=>{}),this.postConnectImplOverride!==void 0?this.postConnectImplOverride(this.privConnectionPromise):this.privConnectionPromise)}sendSpeechServiceConfig(e,t,i){if(t.onSpeechContext(),G.telemetryDataEnabled!==!0){const s={context:{system:JSON.parse(i).context.system}};i=JSON.stringify(s)}if(this.privRecognizerConfig.parameters.getProperty("TranscriptionService_SingleChannel","false").toLowerCase()==="true"){const n=JSON.parse(i);n.context.DisableReferenceChannel="True",n.context.MicSpec="1_0_0",i=JSON.stringify(n)}if(i)return e.send(new _(y.Text,"speech.config",t.requestId,"application/json",i))}fetchConnection(){return x(this,void 0,void 0,function*(){return this.privConnectionConfigurationPromise!==void 0?this.privConnectionConfigurationPromise.then(e=>e.state()===k.Disconnected?(this.privConnectionId=null,this.privConnectionConfigurationPromise=void 0,this.privServiceHasSentMessage=!1,this.fetchConnection()):this.privConnectionConfigurationPromise,()=>(this.privConnectionId=null,this.privConnectionConfigurationPromise=void 0,this.privServiceHasSentMessage=!1,this.fetchConnection())):(this.privConnectionConfigurationPromise=this.configureConnection(),yield this.privConnectionConfigurationPromise)})}sendAudio(e){return x(this,void 0,void 0,function*(){const t=yield this.audioSource.format;let i=Date.now();const n=this.privRecognizerConfig.parameters.getProperty("SPEECH-TransmitLengthBeforThrottleMs","5000"),s=t.avgBytesPerSec/1e3*parseInt(n,10),o=this.privRequestSession.recogNumber,a=()=>x(this,void 0,void 0,function*(){if(!this.privIsDisposed&&!this.privRequestSession.isSpeechEnded&&this.privRequestSession.isRecognizing&&this.privRequestSession.recogNumber===o){const u=yield this.fetchConnection(),h=yield e.read();if(this.privRequestSession.isSpeechEnded)return;let c,d;if(!h||h.isEnd?(c=null,d=0):(c=h.buffer,this.privRequestSession.onAudioSent(c.byteLength),s>=this.privRequestSession.bytesSent?d=0:d=Math.max(0,i-Date.now())),d!==0&&(yield this.delay(d)),c!==null&&(i=Date.now()+c.byteLength*1e3/(t.avgBytesPerSec*2)),!this.privIsDisposed&&!this.privRequestSession.isSpeechEnded&&this.privRequestSession.isRecognizing&&this.privRequestSession.recogNumber===o)if(u.send(new _(y.Binary,"audio",this.privRequestSession.requestId,null,c)).catch(()=>{this.privRequestSession.onServiceTurnEndResponse(this.privRecognizerConfig.isContinuousRecognition).catch(()=>{})}),h!=null&&h.isEnd)this.privIsLiveAudio||this.privRequestSession.onSpeechEnded();else return a()}});return a()})}retryableConnect(){return x(this,void 0,void 0,function*(){let e=!1;this.privAuthFetchEventId=R();const t=this.privRequestSession.sessionId;this.privConnectionId=t!==void 0?t:R(),this.privRequestSession.onPreConnectionStart(this.privAuthFetchEventId,this.privConnectionId);let i=0,n="";for(;this.privRequestSession.numConnectionAttempts<=this.privRecognizerConfig.maxRetryCount;){const o=yield e?this.privAuthentication.fetchOnExpiry(this.privAuthFetchEventId):this.privAuthentication.fetch(this.privAuthFetchEventId);yield this.privRequestSession.onAuthCompleted(!1);const a=this.privConnectionFactory.create(this.privRecognizerConfig,o,this.privConnectionId);this.privRequestSession.listenForServiceTelemetry(a.events),a.events.attach(h=>{this.connectionEvents.onEvent(h)});const u=yield a.open();if(u.statusCode===200)return yield this.privRequestSession.onConnectionEstablishCompleted(u.statusCode),Promise.resolve(a);u.statusCode===1006&&(e=!0),i=u.statusCode,n=u.reason,this.privRequestSession.onRetryConnection()}return yield this.privRequestSession.onConnectionEstablishCompleted(i,n),Promise.reject(`Unable to contact server. StatusCode: ${i}, ${this.privRecognizerConfig.parameters.getProperty(p.SpeechServiceConnection_Endpoint)} Reason: ${n}`)})}delay(e){return new Promise(t=>this.privSetTimeout(t,e))}writeBufferToConsole(e){let t="Buffer Size: ";if(e===null)t+="null";else{const i=new Uint8Array(e);t+=`${e.byteLength}\r
3
+ `;for(let n=0;n<e.byteLength;n++)t+=i[n].toString(16).padStart(2,"0")+" "}console.info(t)}sendFinalAudio(){return x(this,void 0,void 0,function*(){yield(yield this.fetchConnection()).send(new _(y.Binary,"audio",this.privRequestSession.requestId,null,null))})}configureConnection(){return x(this,void 0,void 0,function*(){const e=yield this.connectImpl();return this.configConnectionOverride!==void 0?this.configConnectionOverride(e):(yield this.sendSpeechServiceConfig(e,this.privRequestSession,this.privRecognizerConfig.SpeechServiceConfig.serialize()),yield this.sendPrePayloadJSON(e,!1),e)})}}G.telemetryDataEnabled=!0;var he;(function(r){r[r.Interactive=0]="Interactive",r[r.Conversation=1]="Conversation",r[r.Dictation=2]="Dictation"})(he||(he={}));var fi;(function(r){r[r.Simple=0]="Simple",r[r.Detailed=1]="Detailed"})(fi||(fi={}));class lr{constructor(e,t){this.privSpeechServiceConfig=e||new Ye(new et(null)),this.privParameters=t,this.privMaxRetryCount=parseInt(t.getProperty("SPEECH-Error-MaxRetryCount","4"),10),this.privLanguageIdPriority=t.getProperty(p.SpeechServiceConnection_ContinuousLanguageIdPriority,void 0),this.privLanguageIdMode=this.privLanguageIdPriority==="Latency"?"DetectContinuous":"DetectAtAudioStart",this.privLanguageIdMode==="DetectAtAudioStart"&&(this.privLanguageIdPriority=t.getProperty(p.SpeechServiceConnection_AtStartLanguageIdPriority,void 0))}get parameters(){return this.privParameters}get recognitionMode(){return this.privRecognitionMode}set recognitionMode(e){this.privRecognitionMode=e,this.privRecognitionActivityTimeout=e===he.Interactive?8e3:25e3,this.privSpeechServiceConfig.Recognition=he[e]}get SpeechServiceConfig(){return this.privSpeechServiceConfig}get recognitionActivityTimeout(){return this.privRecognitionActivityTimeout}get isContinuousRecognition(){return this.privRecognitionMode!==he.Interactive}get languageIdPriority(){return this.privLanguageIdPriority?`Prioritize${this.privLanguageIdPriority}`:""}get languageIdMode(){return this.privLanguageIdMode}get autoDetectSourceLanguages(){return this.parameters.getProperty(p.SpeechServiceConnection_AutoDetectSourceLanguages,void 0)}get recognitionEndpointVersion(){return this.parameters.getProperty(p.SpeechServiceConnection_RecognitionEndpointVersion,void 0)}get sourceLanguageModels(){const e=[];let t=!1;if(this.autoDetectSourceLanguages!==void 0)for(const i of this.autoDetectSourceLanguages.split(",")){const n=i+p.SpeechServiceConnection_EndpointId.toString(),s=this.parameters.getProperty(n,void 0);s!==void 0?(e.push({language:i,endpoint:s}),t=!0):e.push({language:i,endpoint:""})}return t?e:void 0}get maxRetryCount(){return this.privMaxRetryCount}}class Ye{constructor(e){this.context=e}serialize(){return JSON.stringify(this,(e,t)=>{if(t&&typeof t=="object"){const i={};for(const n in t)Object.hasOwnProperty.call(t,n)&&(i[n&&n.charAt(0).toLowerCase()+n.substring(1)]=t[n]);return i}return t})}get Context(){return this.context}get Recognition(){return this.recognition}set Recognition(e){this.recognition=e.toLowerCase()}}class et{constructor(e){this.system=new fr,this.os=e}}class fr{constructor(){const e="1.22.0";this.name="SpeechSDK",this.version=e,this.build="JavaScript",this.lang="JavaScript"}}class gi{constructor(e,t,i){this.platform=e,this.name=t,this.version=i}}var Se;(function(r){r.Bluetooth="Bluetooth",r.Wired="Wired",r.WiFi="WiFi",r.Cellular="Cellular",r.InBuilt="InBuilt",r.Unknown="Unknown"})(Se||(Se={}));var ue;(function(r){r.Phone="Phone",r.Speaker="Speaker",r.Car="Car",r.Headset="Headset",r.Thermostat="Thermostat",r.Microphones="Microphones",r.Deskphone="Deskphone",r.RemoteControl="RemoteControl",r.Unknown="Unknown",r.File="File",r.Stream="Stream"})(ue||(ue={}));const Si=`\r
4
+ `;class mi{toConnectionMessage(e){const t=new D;try{if(e.messageType===y.Text){const i=e.textContent;let n={},s=null;if(i){const o=i.split(`\r
5
5
  \r
6
- `);o&&o.length>0&&(n=this.parseHeaders(o[0]),o.length>1&&(s=o[1]))}t.resolve(new at(e.messageType,s,n,e.id))}else if(e.messageType===m.Binary){const i=e.binaryContent;let n={},s=null;if(!i||i.byteLength<2)throw new Error("Invalid binary message format. Header length missing.");const o=new DataView(i),a=o.getInt16(0);if(i.byteLength<a+2)throw new Error("Invalid binary message format. Header content missing.");let u="";for(let h=0;h<a;h++)u+=String.fromCharCode(o.getInt8(h+2));n=this.parseHeaders(u),i.byteLength>a+2&&(s=i.slice(2+a)),t.resolve(new at(e.messageType,s,n,e.id))}}catch(i){t.reject(`Error formatting the message. Error: ${i}`)}return t.promise}fromConnectionMessage(e){const t=new D;try{if(e.messageType===m.Text){const i=`${this.makeHeaders(e)}${hi}${e.textBody?e.textBody:""}`;t.resolve(new Le(m.Text,i,e.id))}else if(e.messageType===m.Binary){const i=this.makeHeaders(e),n=e.binaryBody,s=this.stringToArrayBuffer(i),o=new Int8Array(s),a=o.byteLength,u=new Int8Array(2+a+(n?n.byteLength:0));if(u[0]=a>>8&255,u[1]=a&255,u.set(o,2),n){const c=new Int8Array(n);u.set(c,2+a)}const h=u.buffer;t.resolve(new Le(m.Binary,h,e.id))}}catch(i){t.reject(`Error formatting the message. ${i}`)}return t.promise}makeHeaders(e){let t="";if(e.headers)for(const i in e.headers)i&&(t+=`${i}: ${e.headers[i]}${hi}`);return t}parseHeaders(e){const t={};if(e){const i=e.match(/[^\r\n]+/g);if(t){for(const n of i)if(n){const s=n.indexOf(":"),o=s>0?n.substr(0,s).trim().toLowerCase():n,a=s>0&&n.length>s+1?n.substr(s+1).trim():"";t[o]=a}}}return t}stringToArrayBuffer(e){const t=new ArrayBuffer(e.length),i=new DataView(t);for(let n=0;n<e.length;n++)i.setUint8(n,e.charCodeAt(n));return t}}class cr extends qe{create(e,t,i){let n=e.parameters.getProperty(p.SpeechServiceConnection_Endpoint,void 0);if(!n){const c=e.parameters.getProperty(p.SpeechServiceConnection_Region,void 0),d=qe.getHostSuffix(c);n=e.parameters.getProperty(p.SpeechServiceConnection_Host,"wss://"+c+".s2s.speech"+d)+"/speech/translation/cognitiveservices/v1"}const s={from:e.parameters.getProperty(p.SpeechServiceConnection_RecoLanguage),to:e.parameters.getProperty(p.SpeechServiceConnection_TranslationToLanguages)};this.setCommonUrlParams(e,s,n),this.setUrlParameter(p.SpeechServiceResponse_TranslationRequestStablePartialResult,C.StableTranslation,e,s,n);const o="voice",a="features";e.parameters.getProperty(p.SpeechServiceConnection_TranslationVoice,void 0)!==void 0&&(s[o]=e.parameters.getProperty(p.SpeechServiceConnection_TranslationVoice),s[a]="texttospeech");const u={};t.token!==void 0&&t.token!==""&&(u[t.headerName]=t.token),u[T.ConnectionId]=i,e.parameters.setProperty(p.SpeechServiceConnection_Url,n);const h=e.parameters.getProperty("SPEECH-EnableWebsocketCompression","false")==="true";return new gi(n,s,u,new ui,it.fromRecognizerConfig(e),h,i)}}class hr{constructor(){this.synthesisUri="/cognitiveservices/websocket/v1"}create(e,t,i){let n=e.parameters.getProperty(p.SpeechServiceConnection_Endpoint,void 0);const s=e.parameters.getProperty(p.SpeechServiceConnection_Region,void 0),o=qe.getHostSuffix(s),a=e.parameters.getProperty(p.SpeechServiceConnection_EndpointId,void 0),u=a===void 0?"tts":"voice",h=e.parameters.getProperty(p.SpeechServiceConnection_Host,"wss://"+s+"."+u+".speech"+o),c={};n||(n=h+this.synthesisUri);const d={};t.token!==void 0&&t.token!==""&&(d[t.headerName]=t.token),d[T.ConnectionId]=i,a!==void 0&&(d[C.CustomVoiceDeploymentId]=a),e.parameters.setProperty(p.SpeechServiceConnection_Url,n);const S=e.parameters.getProperty("SPEECH-EnableWebsocketCompression","false")==="true";return new gi(n,c,d,new ui,it.fromParameters(e.parameters),S,i)}}class Qe{static implTranslateRecognitionResult(e){let t=P.Canceled;switch(e){case b.Success:t=P.RecognizedSpeech;break;case b.NoMatch:case b.InitialSilenceTimeout:case b.BabbleTimeout:case b.EndOfDictation:t=P.NoMatch;break;case b.Error:case b.BadRequest:case b.Forbidden:default:t=P.Canceled;break}return t}static implTranslateCancelResult(e){let t=K.EndOfStream;switch(e){case b.Success:case b.EndOfDictation:case b.NoMatch:t=K.EndOfStream;break;case b.InitialSilenceTimeout:case b.BabbleTimeout:case b.Error:case b.BadRequest:case b.Forbidden:default:t=K.Error;break}return t}static implTranslateCancelErrorCode(e){let t=R.NoError;switch(e){case b.Error:t=R.ServiceError;break;case b.TooManyRequests:t=R.TooManyRequests;break;case b.BadRequest:t=R.BadRequestParameters;break;case b.Forbidden:t=R.Forbidden;break;default:t=R.NoError;break}return t}static implTranslateErrorDetails(e){let t="The speech service encountered an internal error and could not continue.";switch(e){case R.Forbidden:t="The recognizer is using a free subscription that ran out of quota.";break;case R.BadRequestParameters:t="Invalid parameter or unsupported audio format in the request.";break;case R.TooManyRequests:t="The number of parallel requests exceeded the number of allowed concurrent transcriptions.";break}return t}}var Ie;(function(r){r[r.Success=0]="Success",r[r.SynthesisEnd=1]="SynthesisEnd",r[r.Error=2]="Error"})(Ie||(Ie={}));var b;(function(r){r[r.Success=0]="Success",r[r.NoMatch=1]="NoMatch",r[r.InitialSilenceTimeout=2]="InitialSilenceTimeout",r[r.BabbleTimeout=3]="BabbleTimeout",r[r.Error=4]="Error",r[r.EndOfDictation=5]="EndOfDictation",r[r.TooManyRequests=6]="TooManyRequests",r[r.BadRequest=7]="BadRequest",r[r.Forbidden=8]="Forbidden"})(b||(b={}));class wt{constructor(e){this.privSynthesisEnd=JSON.parse(e),this.privSynthesisEnd.SynthesisStatus=Ie[this.privSynthesisEnd.SynthesisStatus]}static fromJSON(e){return new wt(e)}get SynthesisStatus(){return this.privSynthesisEnd.SynthesisStatus}get FailureReason(){return this.privSynthesisEnd.FailureReason}}class Ct{constructor(e){this.privTranslationHypothesis=JSON.parse(e),this.privTranslationHypothesis.Translation.TranslationStatus=Te[this.privTranslationHypothesis.Translation.TranslationStatus]}static fromJSON(e){return new Ct(e)}get Duration(){return this.privTranslationHypothesis.Duration}get Offset(){return this.privTranslationHypothesis.Offset}get Text(){return this.privTranslationHypothesis.Text}get Translation(){return this.privTranslationHypothesis.Translation}}class ge{constructor(e){this.privTranslationPhrase=e,this.privTranslationPhrase.RecognitionStatus=b[this.privTranslationPhrase.RecognitionStatus],this.privTranslationPhrase.Translation!==void 0&&(this.privTranslationPhrase.Translation.TranslationStatus=Te[this.privTranslationPhrase.Translation.TranslationStatus])}static fromJSON(e){return new ge(JSON.parse(e))}static fromTranslationResponse(e){l.throwIfNullOrUndefined(e,"translationResponse");const t=e.SpeechPhrase;return e.SpeechPhrase=void 0,t.Translation=e,t.Text=t.DisplayText,new ge(t)}get RecognitionStatus(){return this.privTranslationPhrase.RecognitionStatus}get Offset(){return this.privTranslationPhrase.Offset}get Duration(){return this.privTranslationPhrase.Duration}get Text(){return this.privTranslationPhrase.Text}get Translation(){return this.privTranslationPhrase.Translation}}var pi=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};class ur extends ${constructor(e,t,i,n,s){super(e,t,i,n,s),this.privTranslationRecognizer=s,this.connectionEvents.attach(o=>{o.name==="ConnectionEstablishedEvent"?this.privTranslationRecognizer.onConnection():o.name==="ConnectionClosedEvent"&&this.privTranslationRecognizer.onDisconnection()})}processTypeSpecificMessages(e){return pi(this,void 0,void 0,function*(){const t=new U;let i=!1;const n=s=>pi(this,void 0,void 0,function*(){if(this.privRequestSession.onPhraseRecognized(this.privRequestSession.currentTurnAudioOffset+s.Offset+s.Duration),s.RecognitionStatus===b.Success){const o=this.fireEventForResult(s,t);if(this.privTranslationRecognizer.recognized)try{this.privTranslationRecognizer.recognized(this.privTranslationRecognizer,o)}catch{}if(this.privSuccessCallback){try{this.privSuccessCallback(o.result)}catch(a){this.privErrorCallback&&this.privErrorCallback(a)}this.privSuccessCallback=void 0,this.privErrorCallback=void 0}}else{const o=Qe.implTranslateRecognitionResult(s.RecognitionStatus),a=new gt(void 0,this.privRequestSession.requestId,o,s.Text,s.Duration,this.privRequestSession.currentTurnAudioOffset+s.Offset,void 0,e.textBody,t);if(o===P.Canceled){const u=Qe.implTranslateCancelResult(s.RecognitionStatus),h=Qe.implTranslateCancelErrorCode(s.RecognitionStatus);yield this.cancelRecognitionLocal(u,h,Qe.implTranslateErrorDetails(h))}else{if(!(this.privRequestSession.isSpeechEnded&&o===P.NoMatch&&s.RecognitionStatus!==b.InitialSilenceTimeout)){const u=new Ft(a,a.offset,this.privRequestSession.sessionId);if(this.privTranslationRecognizer.recognized)try{this.privTranslationRecognizer.recognized(this.privTranslationRecognizer,u)}catch{}}if(this.privSuccessCallback){try{this.privSuccessCallback(a)}catch(u){this.privErrorCallback&&this.privErrorCallback(u)}this.privSuccessCallback=void 0,this.privErrorCallback=void 0}}i=!0}});switch(e.messageType===m.Text&&t.setProperty(p.SpeechServiceResponse_JsonResult,e.textBody),e.path.toLowerCase()){case"translation.hypothesis":const s=this.fireEventForResult(Ct.fromJSON(e.textBody),t);if(this.privRequestSession.onHypothesis(this.privRequestSession.currentTurnAudioOffset+s.offset),this.privTranslationRecognizer.recognizing)try{this.privTranslationRecognizer.recognizing(this.privTranslationRecognizer,s)}catch{}i=!0;break;case"translation.response":const o=JSON.parse(e.textBody);o.SpeechPhrase&&(yield n(ge.fromTranslationResponse(o)));break;case"translation.phrase":yield n(ge.fromJSON(e.textBody));break;case"translation.synthesis":this.sendSynthesisAudio(e.binaryBody,this.privRequestSession.sessionId),i=!0;break;case"translation.synthesis.end":const a=wt.fromJSON(e.textBody);switch(a.SynthesisStatus){case Ie.Error:if(this.privTranslationRecognizer.synthesizing){const u=new Gt(P.Canceled,void 0),h=new $t(u,this.privRequestSession.sessionId);try{this.privTranslationRecognizer.synthesizing(this.privTranslationRecognizer,h)}catch{}}if(this.privTranslationRecognizer.canceled){const u=new Zt(this.privRequestSession.sessionId,K.Error,a.FailureReason,R.ServiceError,null);try{this.privTranslationRecognizer.canceled(this.privTranslationRecognizer,u)}catch{}}break;case Ie.Success:this.sendSynthesisAudio(void 0,this.privRequestSession.sessionId);break}i=!0;break}return i})}cancelRecognition(e,t,i,n,s){const o=new U;if(o.setProperty(vi,R[n]),this.privTranslationRecognizer.canceled){const a=new Zt(e,i,s,n,void 0);try{this.privTranslationRecognizer.canceled(this.privTranslationRecognizer,a)}catch{}}if(this.privSuccessCallback){const a=new gt(void 0,t,P.Canceled,void 0,void 0,void 0,s,void 0,o);try{this.privSuccessCallback(a),this.privSuccessCallback=void 0}catch{}}}fireEventForResult(e,t){let i;if(e.Translation.Translations!==void 0){i=new Qi;for(const u of e.Translation.Translations)i.set(u.Language,u.Text||u.DisplayText)}let n;e instanceof ge?e.Translation.TranslationStatus===Te.Success?n=P.TranslatedSpeech:n=P.RecognizedSpeech:n=P.TranslatingSpeech;const s=e.Offset+this.privRequestSession.currentTurnAudioOffset,o=new gt(i,this.privRequestSession.requestId,n,e.Text,e.Duration,s,e.Translation.FailureReason,JSON.stringify(e),t);return new Ft(o,s,this.privRequestSession.sessionId)}sendSynthesisAudio(e,t){const i=e===void 0?P.SynthesizingAudioCompleted:P.SynthesizingAudio,n=new Gt(i,e),s=new $t(n,t);if(this.privTranslationRecognizer.synthesizing)try{this.privTranslationRecognizer.synthesizing(this.privTranslationRecognizer,s)}catch{}}}class Xe{constructor(e){this.privSpeechStartDetected=JSON.parse(e)}static fromJSON(e){return new Xe(e)}get Offset(){return this.privSpeechStartDetected.Offset}}class pr{constructor(e,t,i){this.privIsDisposed=!1,this.privListeningTriggerMetric=null,this.privMicMetric=null,this.privConnectionEstablishMetric=null,this.privRequestId=e,this.privAudioSourceId=t,this.privAudioNodeId=i,this.privReceivedMessages={},this.privPhraseLatencies=[],this.privHypothesisLatencies=[]}phraseReceived(e){e>0&&this.privPhraseLatencies.push(Date.now()-e)}hypothesisReceived(e){e>0&&this.privHypothesisLatencies.push(Date.now()-e)}onEvent(e){if(!this.privIsDisposed&&(e instanceof ni&&e.requestId===this.privRequestId&&(this.privListeningTriggerMetric={End:e.eventTime,Name:"ListeningTrigger",Start:e.eventTime}),e instanceof ye&&e.audioSourceId===this.privAudioSourceId&&e.audioNodeId===this.privAudioNodeId&&(this.privMicStartTime=e.eventTime),e instanceof we&&e.audioSourceId===this.privAudioSourceId&&e.audioNodeId===this.privAudioNodeId&&(this.privMicStartTime=e.eventTime),e instanceof Ne&&e.audioSourceId===this.privAudioSourceId&&(this.privMicMetric||(this.privMicMetric={End:e.eventTime,Error:e.error,Name:"Microphone",Start:this.privMicStartTime})),e instanceof nt&&e.audioSourceId===this.privAudioSourceId&&e.audioNodeId===this.privAudioNodeId&&(this.privMicMetric||(this.privMicMetric={End:e.eventTime,Error:e.error,Name:"Microphone",Start:this.privMicStartTime})),e instanceof G&&e.audioSourceId===this.privAudioSourceId&&e.audioNodeId===this.privAudioNodeId&&(this.privMicMetric||(this.privMicMetric={End:e.eventTime,Name:"Microphone",Start:this.privMicStartTime})),e instanceof si&&e.requestId===this.privRequestId&&(this.privConnectionId=e.sessionId),e instanceof kt&&e.connectionId===this.privConnectionId&&(this.privConnectionStartTime=e.eventTime),e instanceof xt&&e.connectionId===this.privConnectionId&&(this.privConnectionEstablishMetric||(this.privConnectionEstablishMetric={End:e.eventTime,Id:this.privConnectionId,Name:"Connection",Start:this.privConnectionStartTime})),e instanceof Pi&&e.connectionId===this.privConnectionId&&(this.privConnectionEstablishMetric||(this.privConnectionEstablishMetric={End:e.eventTime,Error:this.getConnectionError(e.statusCode),Id:this.privConnectionId,Name:"Connection",Start:this.privConnectionStartTime})),e instanceof st&&e.connectionId===this.privConnectionId&&e.message&&e.message.headers&&e.message.headers.path)){this.privReceivedMessages[e.message.headers.path]||(this.privReceivedMessages[e.message.headers.path]=new Array);const t=50;this.privReceivedMessages[e.message.headers.path].length<t&&this.privReceivedMessages[e.message.headers.path].push(e.networkReceivedTime)}}getTelemetry(){const e=new Array;this.privListeningTriggerMetric&&e.push(this.privListeningTriggerMetric),this.privMicMetric&&e.push(this.privMicMetric),this.privConnectionEstablishMetric&&e.push(this.privConnectionEstablishMetric),this.privPhraseLatencies.length>0&&e.push({PhraseLatencyMs:this.privPhraseLatencies}),this.privHypothesisLatencies.length>0&&e.push({FirstHypothesisLatencyMs:this.privHypothesisLatencies});const t={Metrics:e,ReceivedMessages:this.privReceivedMessages},i=JSON.stringify(t);return this.privReceivedMessages={},this.privListeningTriggerMetric=null,this.privMicMetric=null,this.privConnectionEstablishMetric=null,this.privPhraseLatencies=[],this.privHypothesisLatencies=[],i}get hasTelemetry(){return Object.keys(this.privReceivedMessages).length!==0||this.privListeningTriggerMetric!==null||this.privMicMetric!==null||this.privConnectionEstablishMetric!==null||this.privPhraseLatencies.length!==0||this.privHypothesisLatencies.length!==0}dispose(){this.privIsDisposed=!0}getConnectionError(e){switch(e){case 400:case 1002:case 1003:case 1005:case 1007:case 1008:case 1009:return"BadRequest";case 401:return"Unauthorized";case 403:return"Forbidden";case 503:case 1001:return"ServerUnavailable";case 500:case 1011:return"ServerError";case 408:case 504:return"Timeout";default:return"statuscode:"+e.toString()}}}var ie=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};class dr{constructor(e){this.privIsDisposed=!1,this.privDetachables=new Array,this.privIsAudioNodeDetached=!1,this.privIsRecognizing=!1,this.privIsSpeechEnded=!1,this.privTurnStartAudioOffset=0,this.privLastRecoOffset=0,this.privHypothesisReceived=!1,this.privBytesSent=0,this.privRecogNumber=0,this.privInTurn=!1,this.privConnectionAttempts=0,this.privAudioSourceId=e,this.privRequestId=E(),this.privAudioNodeId=E(),this.privTurnDeferral=new D,this.privTurnDeferral.resolve()}get sessionId(){return this.privSessionId}get requestId(){return this.privRequestId}get audioNodeId(){return this.privAudioNodeId}get turnCompletionPromise(){return this.privTurnDeferral.promise}get isSpeechEnded(){return this.privIsSpeechEnded}get isRecognizing(){return this.privIsRecognizing}get currentTurnAudioOffset(){return this.privTurnStartAudioOffset}get recogNumber(){return this.privRecogNumber}get numConnectionAttempts(){return this.privConnectionAttempts}get bytesSent(){return this.privBytesSent}listenForServiceTelemetry(e){this.privServiceTelemetryListener&&this.privDetachables.push(e.attachListener(this.privServiceTelemetryListener))}startNewRecognition(){this.privIsSpeechEnded=!1,this.privIsRecognizing=!0,this.privTurnStartAudioOffset=0,this.privLastRecoOffset=0,this.privRecogNumber++,this.privServiceTelemetryListener=new pr(this.privRequestId,this.privAudioSourceId,this.privAudioNodeId),this.onEvent(new ni(this.requestId,this.privSessionId,this.privAudioSourceId,this.privAudioNodeId))}onAudioSourceAttachCompleted(e,t){return ie(this,void 0,void 0,function*(){this.privAudioNode=e,this.privIsAudioNodeDetached=!1,t?yield this.onComplete():this.onEvent(new nr(this.privRequestId,this.privSessionId,this.privAudioSourceId,this.privAudioNodeId))})}onPreConnectionStart(e,t){this.privAuthFetchEventId=e,this.privSessionId=t,this.onEvent(new si(this.privRequestId,this.privAuthFetchEventId,this.privSessionId))}onAuthCompleted(e){return ie(this,void 0,void 0,function*(){e&&(yield this.onComplete())})}onConnectionEstablishCompleted(e,t){return ie(this,void 0,void 0,function*(){if(e===200){this.onEvent(new sr(this.requestId,this.privAudioSourceId,this.privAudioNodeId,this.privAuthFetchEventId,this.privSessionId)),this.privAudioNode&&this.privAudioNode.replay(),this.privTurnStartAudioOffset=this.privLastRecoOffset,this.privBytesSent=0;return}else e===403&&(yield this.onComplete())})}onServiceTurnEndResponse(e){return ie(this,void 0,void 0,function*(){this.privTurnDeferral.resolve(),!e||this.isSpeechEnded?(yield this.onComplete(),this.privInTurn=!1):(this.privTurnStartAudioOffset=this.privLastRecoOffset,this.privAudioNode.replay())})}onSpeechContext(){this.privRequestId=E()}onServiceTurnStartResponse(){!!this.privTurnDeferral&&!!this.privInTurn&&(this.privTurnDeferral.reject("Another turn started before current completed."),this.privTurnDeferral.promise.then().catch(()=>{})),this.privInTurn=!0,this.privTurnDeferral=new D}onHypothesis(e){this.privHypothesisReceived||(this.privHypothesisReceived=!0,this.privServiceTelemetryListener.hypothesisReceived(this.privAudioNode.findTimeAtOffset(e)))}onPhraseRecognized(e){this.privServiceTelemetryListener.phraseReceived(this.privAudioNode.findTimeAtOffset(e)),this.onServiceRecognized(e)}onServiceRecognized(e){this.privLastRecoOffset=e,this.privHypothesisReceived=!1,this.privAudioNode.shrinkBuffers(e),this.privConnectionAttempts=0}onAudioSent(e){this.privBytesSent+=e}onRetryConnection(){this.privConnectionAttempts++}dispose(){return ie(this,void 0,void 0,function*(){if(!this.privIsDisposed){this.privIsDisposed=!0;for(const e of this.privDetachables)yield e.detach();this.privServiceTelemetryListener&&this.privServiceTelemetryListener.dispose(),this.privIsRecognizing=!1}})}getTelemetry(){return this.privServiceTelemetryListener.hasTelemetry?this.privServiceTelemetryListener.getTelemetry():null}onStopRecognizing(){return ie(this,void 0,void 0,function*(){yield this.onComplete()})}onSpeechEnded(){this.privIsSpeechEnded=!0}onEvent(e){this.privServiceTelemetryListener&&this.privServiceTelemetryListener.onEvent(e),N.instance.onEvent(e)}onComplete(){return ie(this,void 0,void 0,function*(){this.privIsRecognizing&&(this.privIsRecognizing=!1,yield this.detachAudioNode())})}detachAudioNode(){return ie(this,void 0,void 0,function*(){this.privIsAudioNodeDetached||(this.privIsAudioNodeDetached=!0,this.privAudioNode&&(yield this.privAudioNode.detach()))})}}class vr{constructor(e){this.privContext={},this.privDynamicGrammar=e}setSection(e,t){this.privContext[e]=t}setPronunciationAssessmentParams(e){this.privContext.phraseDetection===void 0&&(this.privContext.phraseDetection={enrichment:{pronunciationAssessment:{}}}),this.privContext.phraseDetection.enrichment.pronunciationAssessment=JSON.parse(e),this.setWordLevelTimings(),this.privContext.phraseOutput.detailed.options.push("PronunciationAssessment"),this.privContext.phraseOutput.detailed.options.indexOf("SNR")===-1&&this.privContext.phraseOutput.detailed.options.push("SNR")}setWordLevelTimings(){this.privContext.phraseOutput===void 0&&(this.privContext.phraseOutput={detailed:{options:[]},format:{}}),this.privContext.phraseOutput.detailed===void 0&&(this.privContext.phraseOutput.detailed={options:[]}),this.privContext.phraseOutput.format="Detailed",this.privContext.phraseOutput.detailed.options.indexOf("WordTimings")===-1&&this.privContext.phraseOutput.detailed.options.push("WordTimings")}toJSON(){const e=this.privDynamicGrammar.generateGrammarObject();return this.setSection("dgi",e),JSON.stringify(this.privContext)}}class lr{addPhrase(e){this.privPhrases||(this.privPhrases=[]),e instanceof Array?this.privPhrases=this.privPhrases.concat(e):this.privPhrases.push(e)}clearPhrases(){this.privPhrases=void 0}addReferenceGrammar(e){this.privGrammars||(this.privGrammars=[]),e instanceof Array?this.privGrammars=this.privGrammars.concat(e):this.privGrammars.push(e)}clearGrammars(){this.privGrammars=void 0}generateGrammarObject(){if(this.privGrammars===void 0&&this.privPhrases===void 0)return;const e={};if(e.ReferenceGrammars=this.privGrammars,this.privPhrases!==void 0&&this.privPhrases.length!==0){const t=[];this.privPhrases.forEach(i=>{t.push({Text:i})}),e.Groups=[{Type:"Generic",Items:t}]}return e}}class di{toJsonString(){return JSON.stringify(this.iPrivConfig)}get(){return this.iPrivConfig}set(e){this.iPrivConfig=e}}class Q{static get requestOptions(){return Q.privDefaultRequestOptions}static get configParams(){return Q.privDefaultParams}static get restErrors(){return Q.privRestErrors}}Q.privDefaultRequestOptions={headers:{Accept:"application/json"},ignoreCache:!1,timeout:1e4},Q.privRestErrors={authInvalidSubscriptionKey:"You must specify either an authentication token to use, or a Cognitive Speech subscription key.",authInvalidSubscriptionRegion:"You must specify the Cognitive Speech region to use.",invalidArgs:"Required input not found: {arg}.",invalidCreateJoinConversationResponse:"Creating/Joining conversation failed with HTTP {status}.",invalidParticipantRequest:"The requested participant was not found.",permissionDeniedConnect:"Required credentials not found.",permissionDeniedConversation:"Invalid operation: only the host can {command} the conversation.",permissionDeniedParticipant:"Invalid operation: only the host can {command} a participant.",permissionDeniedSend:"Invalid operation: the conversation is not in a connected state.",permissionDeniedStart:"Invalid operation: there is already an active conversation."},Q.privDefaultParams={apiVersion:"api-version",authorization:"Authorization",clientAppId:"X-ClientAppId",contentTypeKey:"Content-Type",correlationId:"X-CorrelationId",languageCode:"language",nickname:"nickname",profanity:"profanity",requestId:"X-RequestId",roomId:"roomid",sessionToken:"token",subscriptionKey:"Ocp-Apim-Subscription-Key",subscriptionRegion:"Ocp-Apim-Subscription-Region",token:"X-CapitoToken"};var X;(function(r){r.WordBoundary="WordBoundary",r.Bookmark="Bookmark",r.Viseme="Viseme",r.SentenceBoundary="SentenceBoundary",r.SessionEnd="SessionEnd"})(X||(X={}));class bt{constructor(e){this.privSynthesisAudioMetadata=JSON.parse(e)}static fromJSON(e){return new bt(e)}get Metadata(){return this.privSynthesisAudioMetadata.Metadata}}var re=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};class ne{constructor(e,t,i,n,s){if(this.speakOverride=void 0,this.receiveMessageOverride=void 0,this.connectImplOverride=void 0,this.configConnectionOverride=void 0,this.privConnectionConfigurationPromise=void 0,!e)throw new I("authentication");if(!t)throw new I("connectionFactory");if(!i)throw new I("synthesizerConfig");this.privAuthentication=e,this.privConnectionFactory=t,this.privSynthesizerConfig=i,this.privIsDisposed=!1,this.privSpeechSynthesizer=n,this.privSessionAudioDestination=s,this.privSynthesisTurn=new Ze,this.privConnectionEvents=new j,this.privServiceEvents=new j,this.privSynthesisContext=new wr(this.privSpeechSynthesizer),this.privAgentConfig=new di,this.connectionEvents.attach(o=>{if(o.name==="ConnectionClosedEvent"){const a=o;a.statusCode!==1e3&&this.cancelSynthesisLocal(K.Error,a.statusCode===1007?R.BadRequestParameters:R.ConnectionFailure,`${a.reason} websocket error code: ${a.statusCode}`)}})}get synthesisContext(){return this.privSynthesisContext}get agentConfig(){return this.privAgentConfig}get connectionEvents(){return this.privConnectionEvents}get serviceEvents(){return this.privServiceEvents}set activityTemplate(e){this.privActivityTemplate=e}get activityTemplate(){return this.privActivityTemplate}set audioOutputFormat(e){this.privAudioOutputFormat=e,this.privSynthesisTurn.audioOutputFormat=e,this.privSessionAudioDestination!==void 0&&(this.privSessionAudioDestination.format=e),this.synthesisContext!==void 0&&(this.synthesisContext.audioOutputFormat=e)}static addHeader(e,t){if(!t.hasHeader)return e;t.updateHeader(e.byteLength);const i=new Uint8Array(e.byteLength+t.header.byteLength);return i.set(new Uint8Array(t.header),0),i.set(new Uint8Array(e),t.header.byteLength),i.buffer}isDisposed(){return this.privIsDisposed}dispose(e){return re(this,void 0,void 0,function*(){this.privIsDisposed=!0,this.privSessionAudioDestination!==void 0&&this.privSessionAudioDestination.close(),this.privConnectionConfigurationPromise!==void 0&&(yield(yield this.privConnectionConfigurationPromise).dispose(e))})}connect(){return re(this,void 0,void 0,function*(){yield this.connectImpl()})}sendNetworkMessage(e,t){return re(this,void 0,void 0,function*(){const i=typeof t=="string"?m.Text:m.Binary,n=typeof t=="string"?"application/json":"";return(yield this.fetchConnection()).send(new O(i,e,this.privSynthesisTurn.requestId,n,t))})}Speak(e,t,i,n,s,o){return re(this,void 0,void 0,function*(){let a;if(t?a=e:a=this.privSpeechSynthesizer.buildSsml(e),this.speakOverride!==void 0)return this.speakOverride(a,i,n,s);this.privSuccessCallback=n,this.privErrorCallback=s,this.privSynthesisTurn.startNewSynthesis(i,e,t,o);try{yield this.connectImpl();const u=yield this.fetchConnection();yield this.sendSynthesisContext(u),yield this.sendSsmlMessage(u,a,i);const h=new je(new Ve(i,P.SynthesizingAudioStarted));this.privSpeechSynthesizer.synthesisStarted&&this.privSpeechSynthesizer.synthesisStarted(this.privSpeechSynthesizer,h),this.receiveMessage()}catch(u){return this.cancelSynthesisLocal(K.Error,R.ConnectionFailure,u),Promise.reject(u)}})}cancelSynthesis(e,t,i,n){const s=new U;s.setProperty(vi,R[i]);const o=new Ve(e,P.Canceled,void 0,n,s);if(this.privSpeechSynthesizer.SynthesisCanceled){const a=new je(o);try{this.privSpeechSynthesizer.SynthesisCanceled(this.privSpeechSynthesizer,a)}catch{}}if(this.privSuccessCallback)try{this.privSuccessCallback(o)}catch{}}cancelSynthesisLocal(e,t,i){this.privSynthesisTurn.isSynthesizing&&(this.privSynthesisTurn.onStopSynthesizing(),this.cancelSynthesis(this.privSynthesisTurn.requestId,e,t,i))}processTypeSpecificMessages(e){return!0}receiveMessage(){return re(this,void 0,void 0,function*(){try{const t=yield(yield this.fetchConnection()).read();if(this.receiveMessageOverride!==void 0)return this.receiveMessageOverride();if(this.privIsDisposed)return;if(!t)return this.privSynthesisTurn.isSynthesizing?this.receiveMessage():void 0;const i=O.fromConnectionMessage(t);if(i.requestId.toLowerCase()===this.privSynthesisTurn.requestId.toLowerCase())switch(i.path.toLowerCase()){case"turn.start":this.privSynthesisTurn.onServiceTurnStartResponse();break;case"response":this.privSynthesisTurn.onServiceResponseMessage(i.textBody);break;case"audio":if(this.privSynthesisTurn.streamId.toLowerCase()===i.streamId.toLowerCase()&&!!i.binaryBody){if(this.privSynthesisTurn.onAudioChunkReceived(i.binaryBody),this.privSpeechSynthesizer.synthesizing)try{const o=ne.addHeader(i.binaryBody,this.privSynthesisTurn.audioOutputFormat),a=new je(new Ve(this.privSynthesisTurn.requestId,P.SynthesizingAudio,o));this.privSpeechSynthesizer.synthesizing(this.privSpeechSynthesizer,a)}catch{}this.privSessionAudioDestination!==void 0&&this.privSessionAudioDestination.write(i.binaryBody)}break;case"audio.metadata":const n=bt.fromJSON(i.textBody).Metadata;for(const o of n)switch(o.Type){case X.WordBoundary:case X.SentenceBoundary:this.privSynthesisTurn.onTextBoundaryEvent(o);const a=new Yi(o.Data.Offset,o.Data.Duration,o.Data.text.Text,o.Data.text.Length,o.Type===X.WordBoundary?this.privSynthesisTurn.currentTextOffset:this.privSynthesisTurn.currentSentenceOffset,o.Data.text.BoundaryType);if(this.privSpeechSynthesizer.wordBoundary)try{this.privSpeechSynthesizer.wordBoundary(this.privSpeechSynthesizer,a)}catch{}break;case X.Bookmark:const u=new er(o.Data.Offset,o.Data.Bookmark);if(this.privSpeechSynthesizer.bookmarkReached)try{this.privSpeechSynthesizer.bookmarkReached(this.privSpeechSynthesizer,u)}catch{}break;case X.Viseme:if(this.privSynthesisTurn.onVisemeMetadataReceived(o),o.Data.IsLastAnimation){const h=new tr(o.Data.Offset,o.Data.VisemeId,this.privSynthesisTurn.getAndClearVisemeAnimation());if(this.privSpeechSynthesizer.visemeReceived)try{this.privSpeechSynthesizer.visemeReceived(this.privSpeechSynthesizer,h)}catch{}}break;case X.SessionEnd:this.privSynthesisTurn.onSessionEnd(o);break}break;case"turn.end":this.privSynthesisTurn.onServiceTurnEndResponse();let s;try{const o=yield this.privSynthesisTurn.getAllReceivedAudioWithHeader();s=new Ve(this.privSynthesisTurn.requestId,P.SynthesizingAudioCompleted,o,void 0,void 0,this.privSynthesisTurn.audioDuration),this.privSuccessCallback&&this.privSuccessCallback(s)}catch(o){this.privErrorCallback&&this.privErrorCallback(o)}if(this.privSpeechSynthesizer.synthesisCompleted)try{this.privSpeechSynthesizer.synthesisCompleted(this.privSpeechSynthesizer,new je(s))}catch{}break;default:this.processTypeSpecificMessages(i)||this.privServiceEvents&&this.serviceEvents.onEvent(new Dt(i.path.toLowerCase(),i.textBody))}return this.receiveMessage()}catch{}})}sendSynthesisContext(e){const t=this.synthesisContext.toJSON();if(t)return e.send(new O(m.Text,"synthesis.context",this.privSynthesisTurn.requestId,"application/json",t))}connectImpl(e=!1){if(this.privConnectionPromise!=null)return this.privConnectionPromise.then(i=>i.state()===M.Disconnected?(this.privConnectionId=null,this.privConnectionPromise=null,this.connectImpl()):this.privConnectionPromise,()=>(this.privConnectionId=null,this.privConnectionPromise=null,this.connectImpl()));this.privAuthFetchEventId=E(),this.privConnectionId=E(),this.privSynthesisTurn.onPreConnectionStart(this.privAuthFetchEventId);const t=e?this.privAuthentication.fetchOnExpiry(this.privAuthFetchEventId):this.privAuthentication.fetch(this.privAuthFetchEventId);return this.privConnectionPromise=t.then(i=>re(this,void 0,void 0,function*(){this.privSynthesisTurn.onAuthCompleted(!1);const n=this.privConnectionFactory.create(this.privSynthesizerConfig,i,this.privConnectionId);n.events.attach(o=>{this.connectionEvents.onEvent(o)});const s=yield n.open();return s.statusCode===200?(this.privSynthesisTurn.onConnectionEstablishCompleted(s.statusCode),Promise.resolve(n)):s.statusCode===403&&!e?this.connectImpl(!0):(this.privSynthesisTurn.onConnectionEstablishCompleted(s.statusCode),Promise.reject(`Unable to contact server. StatusCode: ${s.statusCode}, ${this.privSynthesizerConfig.parameters.getProperty(p.SpeechServiceConnection_Endpoint)} Reason: ${s.reason}`))}),i=>{throw this.privSynthesisTurn.onAuthCompleted(!0),new Error(i)}),this.privConnectionPromise.catch(()=>{}),this.privConnectionPromise}sendSpeechServiceConfig(e,t){if(t)return e.send(new O(m.Text,"speech.config",this.privSynthesisTurn.requestId,"application/json",t))}sendSsmlMessage(e,t,i){return e.send(new O(m.Text,"ssml",i,"application/ssml+xml",t))}fetchConnection(){return re(this,void 0,void 0,function*(){return this.privConnectionConfigurationPromise!==void 0?this.privConnectionConfigurationPromise.then(e=>e.state()===M.Disconnected?(this.privConnectionId=null,this.privConnectionConfigurationPromise=void 0,this.fetchConnection()):this.privConnectionConfigurationPromise,()=>(this.privConnectionId=null,this.privConnectionConfigurationPromise=void 0,this.fetchConnection())):(this.privConnectionConfigurationPromise=this.configureConnection(),yield this.privConnectionConfigurationPromise)})}configureConnection(){return re(this,void 0,void 0,function*(){const e=yield this.connectImpl();return this.configConnectionOverride!==void 0?this.configConnectionOverride(e):(yield this.sendSpeechServiceConfig(e,this.privSynthesizerConfig.SpeechServiceConfig.serialize()),e)})}}ne.telemetryDataEnabled=!0;class Tt extends se{constructor(e,t,i=w.Info){super(e,i),this.privRequestId=t}get requestId(){return this.privRequestId}}class fr extends Tt{constructor(e,t,i){super("SynthesisTriggeredEvent",e),this.privSessionAudioDestinationId=t,this.privTurnAudioDestinationId=i}get audioSessionDestinationId(){return this.privSessionAudioDestinationId}get audioTurnDestinationId(){return this.privTurnAudioDestinationId}}class gr extends Tt{constructor(e,t){super("ConnectingToSynthesisServiceEvent",e),this.privAuthFetchEventId=t}get authFetchEventId(){return this.privAuthFetchEventId}}class Sr extends Tt{constructor(e,t){super("SynthesisStartedEvent",e),this.privAuthFetchEventId=t}get authFetchEventId(){return this.privAuthFetchEventId}}var Et=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};class Ze{constructor(){this.privIsDisposed=!1,this.privIsSynthesizing=!1,this.privIsSynthesisEnded=!1,this.privBytesReceived=0,this.privInTurn=!1,this.privTextOffset=0,this.privNextSearchTextIndex=0,this.privSentenceOffset=0,this.privNextSearchSentenceIndex=0,this.privRequestId=E(),this.privTurnDeferral=new D,this.privTurnDeferral.resolve()}get requestId(){return this.privRequestId}get streamId(){return this.privStreamId}set streamId(e){this.privStreamId=e}get audioOutputFormat(){return this.privAudioOutputFormat}set audioOutputFormat(e){this.privAudioOutputFormat=e}get turnCompletionPromise(){return this.privTurnDeferral.promise}get isSynthesisEnded(){return this.privIsSynthesisEnded}get isSynthesizing(){return this.privIsSynthesizing}get currentTextOffset(){return this.privTextOffset}get currentSentenceOffset(){return this.privSentenceOffset}get bytesReceived(){return this.privBytesReceived}get audioDuration(){return this.privAudioDuration}getAllReceivedAudio(){return Et(this,void 0,void 0,function*(){return this.privReceivedAudio?Promise.resolve(this.privReceivedAudio):this.privIsSynthesisEnded?(yield this.readAllAudioFromStream(),Promise.resolve(this.privReceivedAudio)):null})}getAllReceivedAudioWithHeader(){return Et(this,void 0,void 0,function*(){if(this.privReceivedAudioWithHeader)return this.privReceivedAudioWithHeader;if(!this.privIsSynthesisEnded)return null;if(this.audioOutputFormat.hasHeader){const e=yield this.getAllReceivedAudio();return this.privReceivedAudioWithHeader=ne.addHeader(e,this.audioOutputFormat),this.privReceivedAudioWithHeader}else return this.getAllReceivedAudio()})}startNewSynthesis(e,t,i,n){this.privIsSynthesisEnded=!1,this.privIsSynthesizing=!0,this.privRequestId=e,this.privRawText=t,this.privIsSSML=i,this.privAudioOutputStream=new vt,this.privAudioOutputStream.format=this.privAudioOutputFormat,this.privReceivedAudio=null,this.privReceivedAudioWithHeader=null,this.privBytesReceived=0,this.privTextOffset=0,this.privNextSearchTextIndex=0,this.privSentenceOffset=0,this.privNextSearchSentenceIndex=0,this.privPartialVisemeAnimation="",n!==void 0&&(this.privTurnAudioDestination=n,this.privTurnAudioDestination.format=this.privAudioOutputFormat),this.onEvent(new fr(this.requestId,void 0,n===void 0?void 0:n.id()))}onPreConnectionStart(e){this.privAuthFetchEventId=e,this.onEvent(new gr(this.privRequestId,this.privAuthFetchEventId))}onAuthCompleted(e){e&&this.onComplete()}onConnectionEstablishCompleted(e){if(e===200){this.onEvent(new Sr(this.requestId,this.privAuthFetchEventId)),this.privBytesReceived=0;return}else e===403&&this.onComplete()}onServiceResponseMessage(e){const t=JSON.parse(e);this.streamId=t.audio.streamId}onServiceTurnEndResponse(){this.privInTurn=!1,this.privTurnDeferral.resolve(),this.onComplete()}onServiceTurnStartResponse(){!!this.privTurnDeferral&&!!this.privInTurn&&(this.privTurnDeferral.reject("Another turn started before current completed."),this.privTurnDeferral.promise.then().catch(()=>{})),this.privInTurn=!0,this.privTurnDeferral=new D}onAudioChunkReceived(e){this.isSynthesizing&&(this.privAudioOutputStream.write(e),this.privBytesReceived+=e.byteLength,this.privTurnAudioDestination!==void 0&&this.privTurnAudioDestination.write(e))}onTextBoundaryEvent(e){this.updateTextOffset(e.Data.text.Text,e.Type)}onVisemeMetadataReceived(e){e.Data.AnimationChunk!==void 0&&(this.privPartialVisemeAnimation+=e.Data.AnimationChunk)}onSessionEnd(e){this.privAudioDuration=e.Data.Offset}dispose(){this.privIsDisposed||(this.privIsDisposed=!0)}onStopSynthesizing(){this.onComplete()}getAndClearVisemeAnimation(){const e=this.privPartialVisemeAnimation;return this.privPartialVisemeAnimation="",e}onEvent(e){N.instance.onEvent(e)}static isXmlTag(e){return e.length>=2&&e[0]==="<"&&e[e.length-1]===">"}updateTextOffset(e,t){t===X.WordBoundary?(this.privTextOffset=this.privRawText.indexOf(e,this.privNextSearchTextIndex),this.privTextOffset>=0&&(this.privNextSearchTextIndex=this.privTextOffset+e.length,this.privIsSSML&&this.withinXmlTag(this.privTextOffset)&&!Ze.isXmlTag(e)&&this.updateTextOffset(e,t))):(this.privSentenceOffset=this.privRawText.indexOf(e,this.privNextSearchSentenceIndex),this.privSentenceOffset>=0&&(this.privNextSearchSentenceIndex=this.privSentenceOffset+e.length,this.privIsSSML&&this.withinXmlTag(this.privSentenceOffset)&&!Ze.isXmlTag(e)&&this.updateTextOffset(e,t)))}onComplete(){this.privIsSynthesizing&&(this.privIsSynthesizing=!1,this.privIsSynthesisEnded=!0,this.privAudioOutputStream.close(),this.privInTurn=!1,this.privTurnAudioDestination!==void 0&&(this.privTurnAudioDestination.close(),this.privTurnAudioDestination=void 0))}readAllAudioFromStream(){return Et(this,void 0,void 0,function*(){if(this.privIsSynthesisEnded){this.privReceivedAudio=new ArrayBuffer(this.bytesReceived);try{yield this.privAudioOutputStream.read(this.privReceivedAudio)}catch{this.privReceivedAudio=new ArrayBuffer(0)}}})}withinXmlTag(e){return this.privRawText.indexOf("<",e+1)>this.privRawText.indexOf(">",e+1)}}class mr{constructor(e){let t=e.parameters.getProperty(p.SpeechServiceConnection_Endpoint,void 0);if(!t){const n=e.parameters.getProperty(p.SpeechServiceConnection_Region,"westus"),s=qe.getHostSuffix(n);t=e.parameters.getProperty(p.SpeechServiceConnection_Host,`https://${n}.tts.speech${s}`)}this.privUri=`${t}/cognitiveservices/voices/list`;const i=Q.requestOptions;i.headers[Q.configParams.subscriptionKey]=e.parameters.getProperty(p.SpeechServiceConnection_Key,void 0),this.privRestAdapter=new xr(i)}getVoicesList(e){return this.privRestAdapter.setHeaders(T.ConnectionId,e),this.privRestAdapter.request(he.Get,this.privUri)}}var Rt;(function(r){r[r.Standard=0]="Standard",r[r.Custom=1]="Custom"})(Rt||(Rt={}));class yr{constructor(e,t){this.privSynthesisServiceType=Rt.Standard,this.privSpeechServiceConfig=e||new Ge(new Je(null)),this.privParameters=t}get parameters(){return this.privParameters}get synthesisServiceType(){return this.privSynthesisServiceType}set synthesisServiceType(e){this.privSynthesisServiceType=e}get SpeechServiceConfig(){return this.privSpeechServiceConfig}}class wr{constructor(e){this.privContext={},this.privSpeechSynthesizer=e}setSection(e,t){this.privContext[e]=t}set audioOutputFormat(e){this.privAudioOutputFormat=e}toJSON(){const e=this.buildSynthesisContext();return this.setSection("synthesis",e),JSON.stringify(this.privContext)}buildSynthesisContext(){return{audio:{metadataOptions:{bookmarkEnabled:!!this.privSpeechSynthesizer.bookmarkReached,punctuationBoundaryEnabled:this.privSpeechSynthesizer.properties.getProperty(p.SpeechServiceResponse_RequestPunctuationBoundary,!!this.privSpeechSynthesizer.wordBoundary),sentenceBoundaryEnabled:this.privSpeechSynthesizer.properties.getProperty(p.SpeechServiceResponse_RequestSentenceBoundary,!1),sessionEndEnabled:!0,visemeEnabled:!!this.privSpeechSynthesizer.visemeReceived,wordBoundaryEnabled:this.privSpeechSynthesizer.properties.getProperty(p.SpeechServiceResponse_RequestWordBoundary,!!this.privSpeechSynthesizer.wordBoundary)},outputFormat:this.privAudioOutputFormat.requestAudioFormatString},language:{autoDetection:this.privSpeechSynthesizer.autoDetectSourceLanguage}}}}const Ye="OutputFormat",vi="CancellationErrorCode",Me="ServiceProperties",li="ForceDictation",Cr="OpenRange";var et=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};const br="MICROPHONE-WorkletSourceUrl";class W{constructor(e,t,i,n){this.privRecorder=e,this.deviceId=t,this.privStreams={},this.privOutputChunkSize=W.AUDIOFORMAT.avgBytesPerSec/10,this.privId=i||E(),this.privEvents=new j,this.privMediaStream=n||null,this.privIsClosing=!1}get format(){return Promise.resolve(W.AUDIOFORMAT)}get blob(){return Promise.reject("Not implemented for Mic input")}turnOn(){if(this.privInitializeDeferral)return this.privInitializeDeferral.promise;this.privInitializeDeferral=new D;try{this.createAudioContext()}catch(i){if(i instanceof Error){const n=i;this.privInitializeDeferral.reject(n.name+": "+n.message)}else this.privInitializeDeferral.reject(i);return this.privInitializeDeferral.promise}const e=window.navigator;let t=e.getUserMedia||e.webkitGetUserMedia||e.mozGetUserMedia||e.msGetUserMedia;if(e.mediaDevices&&(t=(i,n,s)=>{e.mediaDevices.getUserMedia(i).then(n).catch(s)}),t){const i=()=>{this.onEvent(new xe(this.privId)),this.privMediaStream&&this.privMediaStream.active?(this.onEvent(new me(this.privId)),this.privInitializeDeferral.resolve()):t({audio:this.deviceId?{deviceId:this.deviceId}:!0,video:!1},n=>{this.privMediaStream=n,this.onEvent(new me(this.privId)),this.privInitializeDeferral.resolve()},n=>{const s=`Error occurred during microphone initialization: ${n}`;this.privInitializeDeferral.reject(s),this.onEvent(new Ne(this.privId,s))})};this.privContext.state==="suspended"?this.privContext.resume().then(i).catch(n=>{this.privInitializeDeferral.reject(`Failed to initialize audio context: ${n}`)}):i()}else{const i="Browser does not support getUserMedia.";this.privInitializeDeferral.reject(i),this.onEvent(new Ne(i,""))}return this.privInitializeDeferral.promise}id(){return this.privId}attach(e){return this.onEvent(new ye(this.privId,e)),this.listen(e).then(t=>(this.onEvent(new we(this.privId,e)),{detach:()=>et(this,void 0,void 0,function*(){return t.readEnded(),delete this.privStreams[e],this.onEvent(new G(this.privId,e)),this.turnOff()}),id:()=>e,read:()=>t.read()}))}detach(e){e&&this.privStreams[e]&&(this.privStreams[e].close(),delete this.privStreams[e],this.onEvent(new G(this.privId,e)))}turnOff(){return et(this,void 0,void 0,function*(){for(const e in this.privStreams)if(e){const t=this.privStreams[e];t&&t.close()}this.onEvent(new Mt(this.privId)),this.privInitializeDeferral&&(yield this.privInitializeDeferral,this.privInitializeDeferral=null),yield this.destroyAudioContext()})}get events(){return this.privEvents}get deviceInfo(){return this.getMicrophoneLabel().then(e=>({bitspersample:W.AUDIOFORMAT.bitsPerSample,channelcount:W.AUDIOFORMAT.channels,connectivity:fe.Unknown,manufacturer:"Speech SDK",model:e,samplerate:W.AUDIOFORMAT.samplesPerSec,type:ce.Microphones}))}setProperty(e,t){if(e===br)this.privRecorder.setWorkletUrl(t);else throw new Error("Property '"+e+"' is not supported on Microphone.")}getMicrophoneLabel(){const e="microphone";if(this.privMicrophoneLabel!==void 0)return Promise.resolve(this.privMicrophoneLabel);if(this.privMediaStream===void 0||!this.privMediaStream.active)return Promise.resolve(e);this.privMicrophoneLabel=e;const t=this.privMediaStream.getTracks()[0].getSettings().deviceId;if(t===void 0)return Promise.resolve(this.privMicrophoneLabel);const i=new D;return navigator.mediaDevices.enumerateDevices().then(n=>{for(const s of n)if(s.deviceId===t){this.privMicrophoneLabel=s.label;break}i.resolve(this.privMicrophoneLabel)},()=>i.resolve(this.privMicrophoneLabel)),i.promise}listen(e){return et(this,void 0,void 0,function*(){yield this.turnOn();const t=new ht(this.privOutputChunkSize,e);this.privStreams[e]=t;try{this.privRecorder.record(this.privContext,this.privMediaStream,t)}catch(n){throw this.onEvent(new nt(this.privId,e,n)),n}return t})}onEvent(e){this.privEvents.onEvent(e),N.instance.onEvent(e)}createAudioContext(){this.privContext||(this.privContext=Y.getAudioContext(W.AUDIOFORMAT.samplesPerSec))}destroyAudioContext(){return et(this,void 0,void 0,function*(){if(!this.privContext)return;this.privRecorder.releaseMediaResources(this.privContext);let e=!1;"close"in this.privContext&&(e=!0),e?this.privIsClosing||(this.privIsClosing=!0,yield this.privContext.close(),this.privContext=null,this.privIsClosing=!1):this.privContext!==null&&this.privContext.state==="running"&&(yield this.privContext.suspend())})}}W.AUDIOFORMAT=Be.getDefaultInputFormat();var Pt=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};class Tr{constructor(e,t,i){this.privStreams={},this.privHeaderEnd=44,this.privId=i||E(),this.privEvents=new j,this.privSource=e,typeof window!="undefined"&&typeof Blob!="undefined"&&this.privSource instanceof Blob?this.privFilename=e.name:this.privFilename=t||"unknown.wav",this.privAudioFormatPromise=this.readHeader()}get format(){return this.privAudioFormatPromise}get blob(){return Promise.resolve(this.privSource)}turnOn(){if(this.privFilename.lastIndexOf(".wav")!==this.privFilename.length-4){const e=this.privFilename+" is not supported. Only WAVE files are allowed at the moment.";return this.onEvent(new Ne(e,"")),Promise.reject(e)}this.onEvent(new xe(this.privId)),this.onEvent(new me(this.privId))}id(){return this.privId}attach(e){return Pt(this,void 0,void 0,function*(){this.onEvent(new ye(this.privId,e));const t=yield this.upload(e);return this.onEvent(new we(this.privId,e)),Promise.resolve({detach:()=>Pt(this,void 0,void 0,function*(){t.readEnded(),delete this.privStreams[e],this.onEvent(new G(this.privId,e)),yield this.turnOff()}),id:()=>e,read:()=>t.read()})})}detach(e){e&&this.privStreams[e]&&(this.privStreams[e].close(),delete this.privStreams[e],this.onEvent(new G(this.privId,e)))}turnOff(){for(const e in this.privStreams)if(e){const t=this.privStreams[e];t&&!t.isClosed&&t.close()}return this.onEvent(new Mt(this.privId)),Promise.resolve()}get events(){return this.privEvents}get deviceInfo(){return this.privAudioFormatPromise.then(e=>Promise.resolve({bitspersample:e.bitsPerSample,channelcount:e.channels,connectivity:fe.Unknown,manufacturer:"Speech SDK",model:"File",samplerate:e.samplesPerSec,type:ce.File}))}readHeader(){const t=this.privSource.slice(0,512),i=new D,n=s=>{const o=new DataView(s),a=_=>String.fromCharCode(o.getUint8(_),o.getUint8(_+1),o.getUint8(_+2),o.getUint8(_+3));if(a(0)!=="RIFF"){i.reject("Invalid WAV header in file, RIFF was not found");return}if(a(8)!=="WAVE"||a(12)!=="fmt "){i.reject("Invalid WAV header in file, WAVEfmt was not found");return}const u=o.getInt32(16,!0),h=o.getUint16(22,!0),c=o.getUint32(24,!0),d=o.getUint16(34,!0);let S=36+Math.max(u-16,0);for(;a(S)!=="data";S+=2)if(S>512-8){i.reject("Invalid WAV header in file, data block was not found");return}this.privHeaderEnd=S+8,i.resolve(Be.getWaveFormatPCM(c,d,h))};if(typeof window!="undefined"&&typeof Blob!="undefined"&&t instanceof Blob){const s=new FileReader;s.onload=o=>{const a=o.target.result;n(a)},s.readAsArrayBuffer(t)}else{const s=t;n(s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength))}return i.promise}upload(e){return Pt(this,void 0,void 0,function*(){const t=i=>{const n=`Error occurred while processing '${this.privFilename}'. ${i}`;throw this.onEvent(new nt(this.privId,e,n)),new Error(n)};try{yield this.turnOn();const i=yield this.privAudioFormatPromise,n=new ht(i.avgBytesPerSec/10,e);this.privStreams[e]=n;const s=this.privSource.slice(this.privHeaderEnd),o=a=>{n.isClosed||(n.writeStreamChunk({buffer:a,isEnd:!1,timeReceived:Date.now()}),n.close())};if(typeof window!="undefined"&&typeof Blob!="undefined"&&s instanceof Blob){const a=new FileReader;a.onerror=u=>t(u.toString()),a.onload=u=>{const h=u.target.result;o(h)},a.readAsArrayBuffer(s)}else{const a=s;o(a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength))}return n}catch(i){t(i)}})}onEvent(e){this.privEvents.onEvent(e),N.instance.onEvent(e)}}class At{constructor(e){this.privStopInputOnRelease=e}record(e,t,i){const s=new Ii(e.sampleRate,16e3),o=e.createMediaStreamSource(t);if(!this.privSpeechProcessorScript){const u=`class SP extends AudioWorkletProcessor {
6
+ `);o&&o.length>0&&(n=this.parseHeaders(o[0]),o.length>1&&(s=o[1]))}t.resolve(new lt(e.messageType,s,n,e.id))}else if(e.messageType===y.Binary){const i=e.binaryContent;let n={},s=null;if(!i||i.byteLength<2)throw new Error("Invalid binary message format. Header length missing.");const o=new DataView(i),a=o.getInt16(0);if(i.byteLength<a+2)throw new Error("Invalid binary message format. Header content missing.");let u="";for(let h=0;h<a;h++)u+=String.fromCharCode(o.getInt8(h+2));n=this.parseHeaders(u),i.byteLength>a+2&&(s=i.slice(2+a)),t.resolve(new lt(e.messageType,s,n,e.id))}}catch(i){t.reject(`Error formatting the message. Error: ${i}`)}return t.promise}fromConnectionMessage(e){const t=new D;try{if(e.messageType===y.Text){const i=`${this.makeHeaders(e)}${Si}${e.textBody?e.textBody:""}`;t.resolve(new qe(y.Text,i,e.id))}else if(e.messageType===y.Binary){const i=this.makeHeaders(e),n=e.binaryBody,s=this.stringToArrayBuffer(i),o=new Int8Array(s),a=o.byteLength,u=new Int8Array(2+a+(n?n.byteLength:0));if(u[0]=a>>8&255,u[1]=a&255,u.set(o,2),n){const c=new Int8Array(n);u.set(c,2+a)}const h=u.buffer;t.resolve(new qe(y.Binary,h,e.id))}}catch(i){t.reject(`Error formatting the message. ${i}`)}return t.promise}makeHeaders(e){let t="";if(e.headers)for(const i in e.headers)i&&(t+=`${i}: ${e.headers[i]}${Si}`);return t}parseHeaders(e){const t={};if(e){const i=e.match(/[^\r\n]+/g);if(t){for(const n of i)if(n){const s=n.indexOf(":"),o=s>0?n.substr(0,s).trim().toLowerCase():n,a=s>0&&n.length>s+1?n.substr(s+1).trim():"";t[o]=a}}}return t}stringToArrayBuffer(e){const t=new ArrayBuffer(e.length),i=new DataView(t);for(let n=0;n<e.length;n++)i.setUint8(n,e.charCodeAt(n));return t}}class gr extends je{create(e,t,i){let n=e.parameters.getProperty(p.SpeechServiceConnection_Endpoint,void 0);if(!n){const c=e.parameters.getProperty(p.SpeechServiceConnection_Region,void 0),d=je.getHostSuffix(c);n=e.parameters.getProperty(p.SpeechServiceConnection_Host,"wss://"+c+".s2s.speech"+d)+"/speech/translation/cognitiveservices/v1"}const s={from:e.parameters.getProperty(p.SpeechServiceConnection_RecoLanguage),to:e.parameters.getProperty(p.SpeechServiceConnection_TranslationToLanguages)};this.setCommonUrlParams(e,s,n),this.setUrlParameter(p.SpeechServiceResponse_TranslationRequestStablePartialResult,C.StableTranslation,e,s,n);const o="voice",a="features";e.parameters.getProperty(p.SpeechServiceConnection_TranslationVoice,void 0)!==void 0&&(s[o]=e.parameters.getProperty(p.SpeechServiceConnection_TranslationVoice),s[a]="texttospeech");const u={};t.token!==void 0&&t.token!==""&&(u[t.headerName]=t.token),u[b.ConnectionId]=i,e.parameters.setProperty(p.SpeechServiceConnection_Url,n);const h=e.parameters.getProperty("SPEECH-EnableWebsocketCompression","false")==="true";return new bi(n,s,u,new mi,at.fromRecognizerConfig(e),h,i)}}class Sr{constructor(){this.synthesisUri="/cognitiveservices/websocket/v1"}create(e,t,i){let n=e.parameters.getProperty(p.SpeechServiceConnection_Endpoint,void 0);const s=e.parameters.getProperty(p.SpeechServiceConnection_Region,void 0),o=je.getHostSuffix(s),a=e.parameters.getProperty(p.SpeechServiceConnection_EndpointId,void 0),u=a===void 0?"tts":"voice",h=e.parameters.getProperty(p.SpeechServiceConnection_Host,"wss://"+s+"."+u+".speech"+o),c={};n||(n=h+this.synthesisUri);const d={};t.token!==void 0&&t.token!==""&&(d[t.headerName]=t.token),d[b.ConnectionId]=i,a!==void 0&&(d[C.CustomVoiceDeploymentId]=a),e.parameters.setProperty(p.SpeechServiceConnection_Url,n);const f=e.parameters.getProperty("SPEECH-EnableWebsocketCompression","false")==="true";return new bi(n,c,d,new mi,at.fromParameters(e.parameters),f,i)}}class tt{static implTranslateRecognitionResult(e){let t=P.Canceled;switch(e){case E.Success:t=P.RecognizedSpeech;break;case E.NoMatch:case E.InitialSilenceTimeout:case E.BabbleTimeout:case E.EndOfDictation:t=P.NoMatch;break;case E.Error:case E.BadRequest:case E.Forbidden:default:t=P.Canceled;break}return t}static implTranslateCancelResult(e){let t=H.EndOfStream;switch(e){case E.Success:case E.EndOfDictation:case E.NoMatch:t=H.EndOfStream;break;case E.InitialSilenceTimeout:case E.BabbleTimeout:case E.Error:case E.BadRequest:case E.Forbidden:default:t=H.Error;break}return t}static implTranslateCancelErrorCode(e){let t=A.NoError;switch(e){case E.Error:t=A.ServiceError;break;case E.TooManyRequests:t=A.TooManyRequests;break;case E.BadRequest:t=A.BadRequestParameters;break;case E.Forbidden:t=A.Forbidden;break;default:t=A.NoError;break}return t}static implTranslateErrorDetails(e){let t="The speech service encountered an internal error and could not continue.";switch(e){case A.Forbidden:t="The recognizer is using a free subscription that ran out of quota.";break;case A.BadRequestParameters:t="Invalid parameter or unsupported audio format in the request.";break;case A.TooManyRequests:t="The number of parallel requests exceeded the number of allowed concurrent transcriptions.";break}return t}}var De;(function(r){r[r.Success=0]="Success",r[r.SynthesisEnd=1]="SynthesisEnd",r[r.Error=2]="Error"})(De||(De={}));var E;(function(r){r[r.Success=0]="Success",r[r.NoMatch=1]="NoMatch",r[r.InitialSilenceTimeout=2]="InitialSilenceTimeout",r[r.BabbleTimeout=3]="BabbleTimeout",r[r.Error=4]="Error",r[r.EndOfDictation=5]="EndOfDictation",r[r.TooManyRequests=6]="TooManyRequests",r[r.BadRequest=7]="BadRequest",r[r.Forbidden=8]="Forbidden"})(E||(E={}));class It{constructor(e){this.privSynthesisEnd=JSON.parse(e),this.privSynthesisEnd.SynthesisStatus=De[this.privSynthesisEnd.SynthesisStatus]}static fromJSON(e){return new It(e)}get SynthesisStatus(){return this.privSynthesisEnd.SynthesisStatus}get FailureReason(){return this.privSynthesisEnd.FailureReason}}class Mt{constructor(e){this.privTranslationHypothesis=JSON.parse(e),this.privTranslationHypothesis.Translation.TranslationStatus=Pe[this.privTranslationHypothesis.Translation.TranslationStatus]}static fromJSON(e){return new Mt(e)}get Duration(){return this.privTranslationHypothesis.Duration}get Offset(){return this.privTranslationHypothesis.Offset}get Text(){return this.privTranslationHypothesis.Text}get Translation(){return this.privTranslationHypothesis.Translation}}class me{constructor(e){this.privTranslationPhrase=e,this.privTranslationPhrase.RecognitionStatus=E[this.privTranslationPhrase.RecognitionStatus],this.privTranslationPhrase.Translation!==void 0&&(this.privTranslationPhrase.Translation.TranslationStatus=Pe[this.privTranslationPhrase.Translation.TranslationStatus])}static fromJSON(e){return new me(JSON.parse(e))}static fromTranslationResponse(e){l.throwIfNullOrUndefined(e,"translationResponse");const t=e.SpeechPhrase;return e.SpeechPhrase=void 0,t.Translation=e,t.Text=t.DisplayText,new me(t)}get RecognitionStatus(){return this.privTranslationPhrase.RecognitionStatus}get Offset(){return this.privTranslationPhrase.Offset}get Duration(){return this.privTranslationPhrase.Duration}get Text(){return this.privTranslationPhrase.Text}get Translation(){return this.privTranslationPhrase.Translation}}var yi=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};class mr extends G{constructor(e,t,i,n,s){super(e,t,i,n,s),this.privTranslationRecognizer=s,this.connectionEvents.attach(o=>{o.name==="ConnectionEstablishedEvent"?this.privTranslationRecognizer.onConnection():o.name==="ConnectionClosedEvent"&&this.privTranslationRecognizer.onDisconnection()})}processTypeSpecificMessages(e){return yi(this,void 0,void 0,function*(){const t=new W;let i=!1;const n=s=>yi(this,void 0,void 0,function*(){if(this.privRequestSession.onPhraseRecognized(this.privRequestSession.currentTurnAudioOffset+s.Offset+s.Duration),s.RecognitionStatus===E.Success){const o=this.fireEventForResult(s,t);if(this.privTranslationRecognizer.recognized)try{this.privTranslationRecognizer.recognized(this.privTranslationRecognizer,o)}catch{}if(this.privSuccessCallback){try{this.privSuccessCallback(o.result)}catch(a){this.privErrorCallback&&this.privErrorCallback(a)}this.privSuccessCallback=void 0,this.privErrorCallback=void 0}}else{const o=tt.implTranslateRecognitionResult(s.RecognitionStatus),a=new Tt(void 0,this.privRequestSession.requestId,o,s.Text,s.Duration,this.privRequestSession.currentTurnAudioOffset+s.Offset,void 0,e.textBody,t);if(o===P.Canceled){const u=tt.implTranslateCancelResult(s.RecognitionStatus),h=tt.implTranslateCancelErrorCode(s.RecognitionStatus);yield this.cancelRecognitionLocal(u,h,tt.implTranslateErrorDetails(h))}else{if(!(this.privRequestSession.isSpeechEnded&&o===P.NoMatch&&s.RecognitionStatus!==E.InitialSilenceTimeout)){const u=new ei(a,a.offset,this.privRequestSession.sessionId);if(this.privTranslationRecognizer.recognized)try{this.privTranslationRecognizer.recognized(this.privTranslationRecognizer,u)}catch{}}if(this.privSuccessCallback){try{this.privSuccessCallback(a)}catch(u){this.privErrorCallback&&this.privErrorCallback(u)}this.privSuccessCallback=void 0,this.privErrorCallback=void 0}}i=!0}});switch(e.messageType===y.Text&&t.setProperty(p.SpeechServiceResponse_JsonResult,e.textBody),e.path.toLowerCase()){case"translation.hypothesis":const s=this.fireEventForResult(Mt.fromJSON(e.textBody),t);if(this.privRequestSession.onHypothesis(this.privRequestSession.currentTurnAudioOffset+s.offset),this.privTranslationRecognizer.recognizing)try{this.privTranslationRecognizer.recognizing(this.privTranslationRecognizer,s)}catch{}i=!0;break;case"translation.response":const o=JSON.parse(e.textBody);o.SpeechPhrase&&(yield n(me.fromTranslationResponse(o)));break;case"translation.phrase":yield n(me.fromJSON(e.textBody));break;case"translation.synthesis":this.sendSynthesisAudio(e.binaryBody,this.privRequestSession.sessionId),i=!0;break;case"translation.synthesis.end":const a=It.fromJSON(e.textBody);switch(a.SynthesisStatus){case De.Error:if(this.privTranslationRecognizer.synthesizing){const u=new ii(P.Canceled,void 0),h=new ti(u,this.privRequestSession.sessionId);try{this.privTranslationRecognizer.synthesizing(this.privTranslationRecognizer,h)}catch{}}if(this.privTranslationRecognizer.canceled){const u=new oi(this.privRequestSession.sessionId,H.Error,a.FailureReason,A.ServiceError,null);try{this.privTranslationRecognizer.canceled(this.privTranslationRecognizer,u)}catch{}}break;case De.Success:this.sendSynthesisAudio(void 0,this.privRequestSession.sessionId);break}i=!0;break}return i})}cancelRecognition(e,t,i,n,s){const o=new W;if(o.setProperty(Ci,A[n]),this.privTranslationRecognizer.canceled){const a=new oi(e,i,s,n,void 0);try{this.privTranslationRecognizer.canceled(this.privTranslationRecognizer,a)}catch{}}if(this.privSuccessCallback){const a=new Tt(void 0,t,P.Canceled,void 0,void 0,void 0,s,void 0,o);try{this.privSuccessCallback(a),this.privSuccessCallback=void 0}catch{}}}fireEventForResult(e,t){let i;if(e.Translation.Translations!==void 0){i=new nr;for(const u of e.Translation.Translations)i.set(u.Language,u.Text||u.DisplayText)}let n;e instanceof me?e.Translation.TranslationStatus===Pe.Success?n=P.TranslatedSpeech:n=P.RecognizedSpeech:n=P.TranslatingSpeech;const s=e.Offset+this.privRequestSession.currentTurnAudioOffset,o=new Tt(i,this.privRequestSession.requestId,n,e.Text,e.Duration,s,e.Translation.FailureReason,JSON.stringify(e),t);return new ei(o,s,this.privRequestSession.sessionId)}sendSynthesisAudio(e,t){const i=e===void 0?P.SynthesizingAudioCompleted:P.SynthesizingAudio,n=new ii(i,e),s=new ti(n,t);if(this.privTranslationRecognizer.synthesizing)try{this.privTranslationRecognizer.synthesizing(this.privTranslationRecognizer,s)}catch{}}}class it{constructor(e){this.privSpeechStartDetected=JSON.parse(e)}static fromJSON(e){return new it(e)}get Offset(){return this.privSpeechStartDetected.Offset}}class yr{constructor(e,t,i){this.privIsDisposed=!1,this.privListeningTriggerMetric=null,this.privMicMetric=null,this.privConnectionEstablishMetric=null,this.privRequestId=e,this.privAudioSourceId=t,this.privAudioNodeId=i,this.privReceivedMessages={},this.privPhraseLatencies=[],this.privHypothesisLatencies=[]}phraseReceived(e){e>0&&this.privPhraseLatencies.push(Date.now()-e)}hypothesisReceived(e){e>0&&this.privHypothesisLatencies.push(Date.now()-e)}onEvent(e){if(!this.privIsDisposed&&(e instanceof di&&e.requestId===this.privRequestId&&(this.privListeningTriggerMetric={End:e.eventTime,Name:"ListeningTrigger",Start:e.eventTime}),e instanceof Te&&e.audioSourceId===this.privAudioSourceId&&e.audioNodeId===this.privAudioNodeId&&(this.privMicStartTime=e.eventTime),e instanceof be&&e.audioSourceId===this.privAudioSourceId&&e.audioNodeId===this.privAudioNodeId&&(this.privMicStartTime=e.eventTime),e instanceof He&&e.audioSourceId===this.privAudioSourceId&&(this.privMicMetric||(this.privMicMetric={End:e.eventTime,Error:e.error,Name:"Microphone",Start:this.privMicStartTime})),e instanceof pt&&e.audioSourceId===this.privAudioSourceId&&e.audioNodeId===this.privAudioNodeId&&(this.privMicMetric||(this.privMicMetric={End:e.eventTime,Error:e.error,Name:"Microphone",Start:this.privMicStartTime})),e instanceof $&&e.audioSourceId===this.privAudioSourceId&&e.audioNodeId===this.privAudioNodeId&&(this.privMicMetric||(this.privMicMetric={End:e.eventTime,Name:"Microphone",Start:this.privMicStartTime})),e instanceof vi&&e.requestId===this.privRequestId&&(this.privConnectionId=e.sessionId),e instanceof Ht&&e.connectionId===this.privConnectionId&&(this.privConnectionStartTime=e.eventTime),e instanceof Kt&&e.connectionId===this.privConnectionId&&(this.privConnectionEstablishMetric||(this.privConnectionEstablishMetric={End:e.eventTime,Id:this.privConnectionId,Name:"Connection",Start:this.privConnectionStartTime})),e instanceof Ni&&e.connectionId===this.privConnectionId&&(this.privConnectionEstablishMetric||(this.privConnectionEstablishMetric={End:e.eventTime,Error:this.getConnectionError(e.statusCode),Id:this.privConnectionId,Name:"Connection",Start:this.privConnectionStartTime})),e instanceof dt&&e.connectionId===this.privConnectionId&&e.message&&e.message.headers&&e.message.headers.path)){this.privReceivedMessages[e.message.headers.path]||(this.privReceivedMessages[e.message.headers.path]=new Array);const t=50;this.privReceivedMessages[e.message.headers.path].length<t&&this.privReceivedMessages[e.message.headers.path].push(e.networkReceivedTime)}}getTelemetry(){const e=new Array;this.privListeningTriggerMetric&&e.push(this.privListeningTriggerMetric),this.privMicMetric&&e.push(this.privMicMetric),this.privConnectionEstablishMetric&&e.push(this.privConnectionEstablishMetric),this.privPhraseLatencies.length>0&&e.push({PhraseLatencyMs:this.privPhraseLatencies}),this.privHypothesisLatencies.length>0&&e.push({FirstHypothesisLatencyMs:this.privHypothesisLatencies});const t={Metrics:e,ReceivedMessages:this.privReceivedMessages},i=JSON.stringify(t);return this.privReceivedMessages={},this.privListeningTriggerMetric=null,this.privMicMetric=null,this.privConnectionEstablishMetric=null,this.privPhraseLatencies=[],this.privHypothesisLatencies=[],i}get hasTelemetry(){return Object.keys(this.privReceivedMessages).length!==0||this.privListeningTriggerMetric!==null||this.privMicMetric!==null||this.privConnectionEstablishMetric!==null||this.privPhraseLatencies.length!==0||this.privHypothesisLatencies.length!==0}dispose(){this.privIsDisposed=!0}getConnectionError(e){switch(e){case 400:case 1002:case 1003:case 1005:case 1007:case 1008:case 1009:return"BadRequest";case 401:return"Unauthorized";case 403:return"Forbidden";case 503:case 1001:return"ServerUnavailable";case 500:case 1011:return"ServerError";case 408:case 504:return"Timeout";default:return"statuscode:"+e.toString()}}}var ie=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};class wr{constructor(e){this.privIsDisposed=!1,this.privDetachables=new Array,this.privIsAudioNodeDetached=!1,this.privIsRecognizing=!1,this.privIsSpeechEnded=!1,this.privTurnStartAudioOffset=0,this.privLastRecoOffset=0,this.privHypothesisReceived=!1,this.privBytesSent=0,this.privRecogNumber=0,this.privInTurn=!1,this.privConnectionAttempts=0,this.privAudioSourceId=e,this.privRequestId=R(),this.privAudioNodeId=R(),this.privTurnDeferral=new D,this.privTurnDeferral.resolve()}get sessionId(){return this.privSessionId}get requestId(){return this.privRequestId}get audioNodeId(){return this.privAudioNodeId}get turnCompletionPromise(){return this.privTurnDeferral.promise}get isSpeechEnded(){return this.privIsSpeechEnded}get isRecognizing(){return this.privIsRecognizing}get currentTurnAudioOffset(){return this.privTurnStartAudioOffset}get recogNumber(){return this.privRecogNumber}get numConnectionAttempts(){return this.privConnectionAttempts}get bytesSent(){return this.privBytesSent}listenForServiceTelemetry(e){this.privServiceTelemetryListener&&this.privDetachables.push(e.attachListener(this.privServiceTelemetryListener))}startNewRecognition(){this.privIsSpeechEnded=!1,this.privIsRecognizing=!0,this.privTurnStartAudioOffset=0,this.privLastRecoOffset=0,this.privRecogNumber++,this.privServiceTelemetryListener=new yr(this.privRequestId,this.privAudioSourceId,this.privAudioNodeId),this.onEvent(new di(this.requestId,this.privSessionId,this.privAudioSourceId,this.privAudioNodeId))}onAudioSourceAttachCompleted(e,t){return ie(this,void 0,void 0,function*(){this.privAudioNode=e,this.privIsAudioNodeDetached=!1,t?yield this.onComplete():this.onEvent(new dr(this.privRequestId,this.privSessionId,this.privAudioSourceId,this.privAudioNodeId))})}onPreConnectionStart(e,t){this.privAuthFetchEventId=e,this.privSessionId=t,this.onEvent(new vi(this.privRequestId,this.privAuthFetchEventId,this.privSessionId))}onAuthCompleted(e){return ie(this,void 0,void 0,function*(){e&&(yield this.onComplete())})}onConnectionEstablishCompleted(e,t){return ie(this,void 0,void 0,function*(){if(e===200){this.onEvent(new vr(this.requestId,this.privAudioSourceId,this.privAudioNodeId,this.privAuthFetchEventId,this.privSessionId)),this.privAudioNode&&this.privAudioNode.replay(),this.privTurnStartAudioOffset=this.privLastRecoOffset,this.privBytesSent=0;return}else e===403&&(yield this.onComplete())})}onServiceTurnEndResponse(e){return ie(this,void 0,void 0,function*(){this.privTurnDeferral.resolve(),!e||this.isSpeechEnded?(yield this.onComplete(),this.privInTurn=!1):(this.privTurnStartAudioOffset=this.privLastRecoOffset,this.privAudioNode.replay())})}onSpeechContext(){this.privRequestId=R()}onServiceTurnStartResponse(){!!this.privTurnDeferral&&!!this.privInTurn&&(this.privTurnDeferral.reject("Another turn started before current completed."),this.privTurnDeferral.promise.then().catch(()=>{})),this.privInTurn=!0,this.privTurnDeferral=new D}onHypothesis(e){this.privHypothesisReceived||(this.privHypothesisReceived=!0,this.privServiceTelemetryListener.hypothesisReceived(this.privAudioNode.findTimeAtOffset(e)))}onPhraseRecognized(e){this.privServiceTelemetryListener.phraseReceived(this.privAudioNode.findTimeAtOffset(e)),this.onServiceRecognized(e)}onServiceRecognized(e){this.privLastRecoOffset=e,this.privHypothesisReceived=!1,this.privAudioNode.shrinkBuffers(e),this.privConnectionAttempts=0}onAudioSent(e){this.privBytesSent+=e}onRetryConnection(){this.privConnectionAttempts++}dispose(){return ie(this,void 0,void 0,function*(){if(!this.privIsDisposed){this.privIsDisposed=!0;for(const e of this.privDetachables)yield e.detach();this.privServiceTelemetryListener&&this.privServiceTelemetryListener.dispose(),this.privIsRecognizing=!1}})}getTelemetry(){return this.privServiceTelemetryListener.hasTelemetry?this.privServiceTelemetryListener.getTelemetry():null}onStopRecognizing(){return ie(this,void 0,void 0,function*(){yield this.onComplete()})}onSpeechEnded(){this.privIsSpeechEnded=!0}onEvent(e){this.privServiceTelemetryListener&&this.privServiceTelemetryListener.onEvent(e),L.instance.onEvent(e)}onComplete(){return ie(this,void 0,void 0,function*(){this.privIsRecognizing&&(this.privIsRecognizing=!1,yield this.detachAudioNode())})}detachAudioNode(){return ie(this,void 0,void 0,function*(){this.privIsAudioNodeDetached||(this.privIsAudioNodeDetached=!0,this.privAudioNode&&(yield this.privAudioNode.detach()))})}}class Cr{constructor(e){this.privContext={},this.privDynamicGrammar=e}setSection(e,t){this.privContext[e]=t}setPronunciationAssessmentParams(e){this.privContext.phraseDetection===void 0&&(this.privContext.phraseDetection={enrichment:{pronunciationAssessment:{}}}),this.privContext.phraseDetection.enrichment.pronunciationAssessment=JSON.parse(e),this.setWordLevelTimings(),this.privContext.phraseOutput.detailed.options.push("PronunciationAssessment"),this.privContext.phraseOutput.detailed.options.indexOf("SNR")===-1&&this.privContext.phraseOutput.detailed.options.push("SNR")}setWordLevelTimings(){this.privContext.phraseOutput===void 0&&(this.privContext.phraseOutput={detailed:{options:[]},format:{}}),this.privContext.phraseOutput.detailed===void 0&&(this.privContext.phraseOutput.detailed={options:[]}),this.privContext.phraseOutput.format="Detailed",this.privContext.phraseOutput.detailed.options.indexOf("WordTimings")===-1&&this.privContext.phraseOutput.detailed.options.push("WordTimings")}toJSON(){const e=this.privDynamicGrammar.generateGrammarObject();return this.setSection("dgi",e),JSON.stringify(this.privContext)}}class Er{addPhrase(e){this.privPhrases||(this.privPhrases=[]),e instanceof Array?this.privPhrases=this.privPhrases.concat(e):this.privPhrases.push(e)}clearPhrases(){this.privPhrases=void 0}addReferenceGrammar(e){this.privGrammars||(this.privGrammars=[]),e instanceof Array?this.privGrammars=this.privGrammars.concat(e):this.privGrammars.push(e)}clearGrammars(){this.privGrammars=void 0}generateGrammarObject(){if(this.privGrammars===void 0&&this.privPhrases===void 0)return;const e={};if(e.ReferenceGrammars=this.privGrammars,this.privPhrases!==void 0&&this.privPhrases.length!==0){const t=[];this.privPhrases.forEach(i=>{t.push({Text:i})}),e.Groups=[{Type:"Generic",Items:t}]}return e}}class wi{toJsonString(){return JSON.stringify(this.iPrivConfig)}get(){return this.iPrivConfig}set(e){this.iPrivConfig=e}}class Q{static get requestOptions(){return Q.privDefaultRequestOptions}static get configParams(){return Q.privDefaultParams}static get restErrors(){return Q.privRestErrors}}Q.privDefaultRequestOptions={headers:{Accept:"application/json"},ignoreCache:!1,timeout:1e4},Q.privRestErrors={authInvalidSubscriptionKey:"You must specify either an authentication token to use, or a Cognitive Speech subscription key.",authInvalidSubscriptionRegion:"You must specify the Cognitive Speech region to use.",invalidArgs:"Required input not found: {arg}.",invalidCreateJoinConversationResponse:"Creating/Joining conversation failed with HTTP {status}.",invalidParticipantRequest:"The requested participant was not found.",permissionDeniedConnect:"Required credentials not found.",permissionDeniedConversation:"Invalid operation: only the host can {command} the conversation.",permissionDeniedParticipant:"Invalid operation: only the host can {command} a participant.",permissionDeniedSend:"Invalid operation: the conversation is not in a connected state.",permissionDeniedStart:"Invalid operation: there is already an active conversation."},Q.privDefaultParams={apiVersion:"api-version",authorization:"Authorization",clientAppId:"X-ClientAppId",contentTypeKey:"Content-Type",correlationId:"X-CorrelationId",languageCode:"language",nickname:"nickname",profanity:"profanity",requestId:"X-RequestId",roomId:"roomid",sessionToken:"token",subscriptionKey:"Ocp-Apim-Subscription-Key",subscriptionRegion:"Ocp-Apim-Subscription-Region",token:"X-CapitoToken"};var X;(function(r){r.WordBoundary="WordBoundary",r.Bookmark="Bookmark",r.Viseme="Viseme",r.SentenceBoundary="SentenceBoundary",r.SessionEnd="SessionEnd"})(X||(X={}));class zt{constructor(e){this.privSynthesisAudioMetadata=JSON.parse(e)}static fromJSON(e){return new zt(e)}get Metadata(){return this.privSynthesisAudioMetadata.Metadata}}var re=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};class ne{constructor(e,t,i,n,s){if(this.speakOverride=void 0,this.receiveMessageOverride=void 0,this.connectImplOverride=void 0,this.configConnectionOverride=void 0,this.privConnectionConfigurationPromise=void 0,!e)throw new z("authentication");if(!t)throw new z("connectionFactory");if(!i)throw new z("synthesizerConfig");this.privAuthentication=e,this.privConnectionFactory=t,this.privSynthesizerConfig=i,this.privIsDisposed=!1,this.privSpeechSynthesizer=n,this.privSessionAudioDestination=s,this.privSynthesisTurn=new rt,this.privConnectionEvents=new F,this.privServiceEvents=new F,this.privSynthesisContext=new Ir(this.privSpeechSynthesizer),this.privAgentConfig=new wi,this.connectionEvents.attach(o=>{if(o.name==="ConnectionClosedEvent"){const a=o;a.statusCode!==1e3&&this.cancelSynthesisLocal(H.Error,a.statusCode===1007?A.BadRequestParameters:A.ConnectionFailure,`${a.reason} websocket error code: ${a.statusCode}`)}})}get synthesisContext(){return this.privSynthesisContext}get agentConfig(){return this.privAgentConfig}get connectionEvents(){return this.privConnectionEvents}get serviceEvents(){return this.privServiceEvents}set activityTemplate(e){this.privActivityTemplate=e}get activityTemplate(){return this.privActivityTemplate}set audioOutputFormat(e){this.privAudioOutputFormat=e,this.privSynthesisTurn.audioOutputFormat=e,this.privSessionAudioDestination!==void 0&&(this.privSessionAudioDestination.format=e),this.synthesisContext!==void 0&&(this.synthesisContext.audioOutputFormat=e)}static addHeader(e,t){if(!t.hasHeader)return e;t.updateHeader(e.byteLength);const i=new Uint8Array(e.byteLength+t.header.byteLength);return i.set(new Uint8Array(t.header),0),i.set(new Uint8Array(e),t.header.byteLength),i.buffer}isDisposed(){return this.privIsDisposed}dispose(e){return re(this,void 0,void 0,function*(){this.privIsDisposed=!0,this.privSessionAudioDestination!==void 0&&this.privSessionAudioDestination.close(),this.privConnectionConfigurationPromise!==void 0&&(yield(yield this.privConnectionConfigurationPromise).dispose(e))})}connect(){return re(this,void 0,void 0,function*(){yield this.connectImpl()})}sendNetworkMessage(e,t){return re(this,void 0,void 0,function*(){const i=typeof t=="string"?y.Text:y.Binary,n=typeof t=="string"?"application/json":"";return(yield this.fetchConnection()).send(new _(i,e,this.privSynthesisTurn.requestId,n,t))})}Speak(e,t,i,n,s,o){return re(this,void 0,void 0,function*(){let a;if(t?a=e:a=this.privSpeechSynthesizer.buildSsml(e),this.speakOverride!==void 0)return this.speakOverride(a,i,n,s);this.privSuccessCallback=n,this.privErrorCallback=s,this.privSynthesisTurn.startNewSynthesis(i,e,t,o);try{yield this.connectImpl();const u=yield this.fetchConnection();yield this.sendSynthesisContext(u),yield this.sendSsmlMessage(u,a,i);const h=new Qe(new Je(i,P.SynthesizingAudioStarted));this.privSpeechSynthesizer.synthesisStarted&&this.privSpeechSynthesizer.synthesisStarted(this.privSpeechSynthesizer,h),this.receiveMessage()}catch(u){return this.cancelSynthesisLocal(H.Error,A.ConnectionFailure,u),Promise.reject(u)}})}cancelSynthesis(e,t,i,n){const s=new W;s.setProperty(Ci,A[i]);const o=new Je(e,P.Canceled,void 0,n,s);if(this.privSpeechSynthesizer.SynthesisCanceled){const a=new Qe(o);try{this.privSpeechSynthesizer.SynthesisCanceled(this.privSpeechSynthesizer,a)}catch{}}if(this.privSuccessCallback)try{this.privSuccessCallback(o)}catch{}}cancelSynthesisLocal(e,t,i){this.privSynthesisTurn.isSynthesizing&&(this.privSynthesisTurn.onStopSynthesizing(),this.cancelSynthesis(this.privSynthesisTurn.requestId,e,t,i))}processTypeSpecificMessages(e){return!0}receiveMessage(){return re(this,void 0,void 0,function*(){try{const t=yield(yield this.fetchConnection()).read();if(this.receiveMessageOverride!==void 0)return this.receiveMessageOverride();if(this.privIsDisposed)return;if(!t)return this.privSynthesisTurn.isSynthesizing?this.receiveMessage():void 0;const i=_.fromConnectionMessage(t);if(i.requestId.toLowerCase()===this.privSynthesisTurn.requestId.toLowerCase())switch(i.path.toLowerCase()){case"turn.start":this.privSynthesisTurn.onServiceTurnStartResponse();break;case"response":this.privSynthesisTurn.onServiceResponseMessage(i.textBody);break;case"audio":if(this.privSynthesisTurn.streamId.toLowerCase()===i.streamId.toLowerCase()&&!!i.binaryBody){if(this.privSynthesisTurn.onAudioChunkReceived(i.binaryBody),this.privSpeechSynthesizer.synthesizing)try{const o=ne.addHeader(i.binaryBody,this.privSynthesisTurn.audioOutputFormat),a=new Qe(new Je(this.privSynthesisTurn.requestId,P.SynthesizingAudio,o));this.privSpeechSynthesizer.synthesizing(this.privSpeechSynthesizer,a)}catch{}this.privSessionAudioDestination!==void 0&&this.privSessionAudioDestination.write(i.binaryBody)}break;case"audio.metadata":const n=zt.fromJSON(i.textBody).Metadata;for(const o of n)switch(o.Type){case X.WordBoundary:case X.SentenceBoundary:this.privSynthesisTurn.onTextBoundaryEvent(o);const a=new ar(o.Data.Offset,o.Data.Duration,o.Data.text.Text,o.Data.text.Length,o.Type===X.WordBoundary?this.privSynthesisTurn.currentTextOffset:this.privSynthesisTurn.currentSentenceOffset,o.Data.text.BoundaryType);if(this.privSpeechSynthesizer.wordBoundary)try{this.privSpeechSynthesizer.wordBoundary(this.privSpeechSynthesizer,a)}catch{}break;case X.Bookmark:const u=new cr(o.Data.Offset,o.Data.Bookmark);if(this.privSpeechSynthesizer.bookmarkReached)try{this.privSpeechSynthesizer.bookmarkReached(this.privSpeechSynthesizer,u)}catch{}break;case X.Viseme:if(this.privSynthesisTurn.onVisemeMetadataReceived(o),o.Data.IsLastAnimation){const h=new hr(o.Data.Offset,o.Data.VisemeId,this.privSynthesisTurn.getAndClearVisemeAnimation());if(this.privSpeechSynthesizer.visemeReceived)try{this.privSpeechSynthesizer.visemeReceived(this.privSpeechSynthesizer,h)}catch{}}break;case X.SessionEnd:this.privSynthesisTurn.onSessionEnd(o);break}break;case"turn.end":this.privSynthesisTurn.onServiceTurnEndResponse();let s;try{const o=yield this.privSynthesisTurn.getAllReceivedAudioWithHeader();s=new Je(this.privSynthesisTurn.requestId,P.SynthesizingAudioCompleted,o,void 0,void 0,this.privSynthesisTurn.audioDuration),this.privSuccessCallback&&this.privSuccessCallback(s)}catch(o){this.privErrorCallback&&this.privErrorCallback(o)}if(this.privSpeechSynthesizer.synthesisCompleted)try{this.privSpeechSynthesizer.synthesisCompleted(this.privSpeechSynthesizer,new Qe(s))}catch{}break;default:this.processTypeSpecificMessages(i)||this.privServiceEvents&&this.serviceEvents.onEvent(new _t(i.path.toLowerCase(),i.textBody))}return this.receiveMessage()}catch{}})}sendSynthesisContext(e){const t=this.synthesisContext.toJSON();if(t)return e.send(new _(y.Text,"synthesis.context",this.privSynthesisTurn.requestId,"application/json",t))}connectImpl(e=!1){if(this.privConnectionPromise!=null)return this.privConnectionPromise.then(i=>i.state()===k.Disconnected?(this.privConnectionId=null,this.privConnectionPromise=null,this.connectImpl()):this.privConnectionPromise,()=>(this.privConnectionId=null,this.privConnectionPromise=null,this.connectImpl()));this.privAuthFetchEventId=R(),this.privConnectionId=R(),this.privSynthesisTurn.onPreConnectionStart(this.privAuthFetchEventId);const t=e?this.privAuthentication.fetchOnExpiry(this.privAuthFetchEventId):this.privAuthentication.fetch(this.privAuthFetchEventId);return this.privConnectionPromise=t.then(i=>re(this,void 0,void 0,function*(){this.privSynthesisTurn.onAuthCompleted(!1);const n=this.privConnectionFactory.create(this.privSynthesizerConfig,i,this.privConnectionId);n.events.attach(o=>{this.connectionEvents.onEvent(o)});const s=yield n.open();return s.statusCode===200?(this.privSynthesisTurn.onConnectionEstablishCompleted(s.statusCode),Promise.resolve(n)):s.statusCode===403&&!e?this.connectImpl(!0):(this.privSynthesisTurn.onConnectionEstablishCompleted(s.statusCode),Promise.reject(`Unable to contact server. StatusCode: ${s.statusCode}, ${this.privSynthesizerConfig.parameters.getProperty(p.SpeechServiceConnection_Endpoint)} Reason: ${s.reason}`))}),i=>{throw this.privSynthesisTurn.onAuthCompleted(!0),new Error(i)}),this.privConnectionPromise.catch(()=>{}),this.privConnectionPromise}sendSpeechServiceConfig(e,t){if(t)return e.send(new _(y.Text,"speech.config",this.privSynthesisTurn.requestId,"application/json",t))}sendSsmlMessage(e,t,i){return e.send(new _(y.Text,"ssml",i,"application/ssml+xml",t))}fetchConnection(){return re(this,void 0,void 0,function*(){return this.privConnectionConfigurationPromise!==void 0?this.privConnectionConfigurationPromise.then(e=>e.state()===k.Disconnected?(this.privConnectionId=null,this.privConnectionConfigurationPromise=void 0,this.fetchConnection()):this.privConnectionConfigurationPromise,()=>(this.privConnectionId=null,this.privConnectionConfigurationPromise=void 0,this.fetchConnection())):(this.privConnectionConfigurationPromise=this.configureConnection(),yield this.privConnectionConfigurationPromise)})}configureConnection(){return re(this,void 0,void 0,function*(){const e=yield this.connectImpl();return this.configConnectionOverride!==void 0?this.configConnectionOverride(e):(yield this.sendSpeechServiceConfig(e,this.privSynthesizerConfig.SpeechServiceConfig.serialize()),e)})}}ne.telemetryDataEnabled=!0;class kt extends ae{constructor(e,t,i=w.Info){super(e,i),this.privRequestId=t}get requestId(){return this.privRequestId}}class Tr extends kt{constructor(e,t,i){super("SynthesisTriggeredEvent",e),this.privSessionAudioDestinationId=t,this.privTurnAudioDestinationId=i}get audioSessionDestinationId(){return this.privSessionAudioDestinationId}get audioTurnDestinationId(){return this.privTurnAudioDestinationId}}class br extends kt{constructor(e,t){super("ConnectingToSynthesisServiceEvent",e),this.privAuthFetchEventId=t}get authFetchEventId(){return this.privAuthFetchEventId}}class Rr extends kt{constructor(e,t){super("SynthesisStartedEvent",e),this.privAuthFetchEventId=t}get authFetchEventId(){return this.privAuthFetchEventId}}var Dt=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};class rt{constructor(){this.privIsDisposed=!1,this.privIsSynthesizing=!1,this.privIsSynthesisEnded=!1,this.privBytesReceived=0,this.privInTurn=!1,this.privTextOffset=0,this.privNextSearchTextIndex=0,this.privSentenceOffset=0,this.privNextSearchSentenceIndex=0,this.privRequestId=R(),this.privTurnDeferral=new D,this.privTurnDeferral.resolve()}get requestId(){return this.privRequestId}get streamId(){return this.privStreamId}set streamId(e){this.privStreamId=e}get audioOutputFormat(){return this.privAudioOutputFormat}set audioOutputFormat(e){this.privAudioOutputFormat=e}get turnCompletionPromise(){return this.privTurnDeferral.promise}get isSynthesisEnded(){return this.privIsSynthesisEnded}get isSynthesizing(){return this.privIsSynthesizing}get currentTextOffset(){return this.privTextOffset}get currentSentenceOffset(){return this.privSentenceOffset}get bytesReceived(){return this.privBytesReceived}get audioDuration(){return this.privAudioDuration}getAllReceivedAudio(){return Dt(this,void 0,void 0,function*(){return this.privReceivedAudio?Promise.resolve(this.privReceivedAudio):this.privIsSynthesisEnded?(yield this.readAllAudioFromStream(),Promise.resolve(this.privReceivedAudio)):null})}getAllReceivedAudioWithHeader(){return Dt(this,void 0,void 0,function*(){if(this.privReceivedAudioWithHeader)return this.privReceivedAudioWithHeader;if(!this.privIsSynthesisEnded)return null;if(this.audioOutputFormat.hasHeader){const e=yield this.getAllReceivedAudio();return this.privReceivedAudioWithHeader=ne.addHeader(e,this.audioOutputFormat),this.privReceivedAudioWithHeader}else return this.getAllReceivedAudio()})}startNewSynthesis(e,t,i,n){this.privIsSynthesisEnded=!1,this.privIsSynthesizing=!0,this.privRequestId=e,this.privRawText=t,this.privIsSSML=i,this.privAudioOutputStream=new wt,this.privAudioOutputStream.format=this.privAudioOutputFormat,this.privReceivedAudio=null,this.privReceivedAudioWithHeader=null,this.privBytesReceived=0,this.privTextOffset=0,this.privNextSearchTextIndex=0,this.privSentenceOffset=0,this.privNextSearchSentenceIndex=0,this.privPartialVisemeAnimation="",n!==void 0&&(this.privTurnAudioDestination=n,this.privTurnAudioDestination.format=this.privAudioOutputFormat),this.onEvent(new Tr(this.requestId,void 0,n===void 0?void 0:n.id()))}onPreConnectionStart(e){this.privAuthFetchEventId=e,this.onEvent(new br(this.privRequestId,this.privAuthFetchEventId))}onAuthCompleted(e){e&&this.onComplete()}onConnectionEstablishCompleted(e){if(e===200){this.onEvent(new Rr(this.requestId,this.privAuthFetchEventId)),this.privBytesReceived=0;return}else e===403&&this.onComplete()}onServiceResponseMessage(e){const t=JSON.parse(e);this.streamId=t.audio.streamId}onServiceTurnEndResponse(){this.privInTurn=!1,this.privTurnDeferral.resolve(),this.onComplete()}onServiceTurnStartResponse(){!!this.privTurnDeferral&&!!this.privInTurn&&(this.privTurnDeferral.reject("Another turn started before current completed."),this.privTurnDeferral.promise.then().catch(()=>{})),this.privInTurn=!0,this.privTurnDeferral=new D}onAudioChunkReceived(e){this.isSynthesizing&&(this.privAudioOutputStream.write(e),this.privBytesReceived+=e.byteLength,this.privTurnAudioDestination!==void 0&&this.privTurnAudioDestination.write(e))}onTextBoundaryEvent(e){this.updateTextOffset(e.Data.text.Text,e.Type)}onVisemeMetadataReceived(e){e.Data.AnimationChunk!==void 0&&(this.privPartialVisemeAnimation+=e.Data.AnimationChunk)}onSessionEnd(e){this.privAudioDuration=e.Data.Offset}dispose(){this.privIsDisposed||(this.privIsDisposed=!0)}onStopSynthesizing(){this.onComplete()}getAndClearVisemeAnimation(){const e=this.privPartialVisemeAnimation;return this.privPartialVisemeAnimation="",e}onEvent(e){L.instance.onEvent(e)}static isXmlTag(e){return e.length>=2&&e[0]==="<"&&e[e.length-1]===">"}updateTextOffset(e,t){t===X.WordBoundary?(this.privTextOffset=this.privRawText.indexOf(e,this.privNextSearchTextIndex),this.privTextOffset>=0&&(this.privNextSearchTextIndex=this.privTextOffset+e.length,this.privIsSSML&&this.withinXmlTag(this.privTextOffset)&&!rt.isXmlTag(e)&&this.updateTextOffset(e,t))):(this.privSentenceOffset=this.privRawText.indexOf(e,this.privNextSearchSentenceIndex),this.privSentenceOffset>=0&&(this.privNextSearchSentenceIndex=this.privSentenceOffset+e.length,this.privIsSSML&&this.withinXmlTag(this.privSentenceOffset)&&!rt.isXmlTag(e)&&this.updateTextOffset(e,t)))}onComplete(){this.privIsSynthesizing&&(this.privIsSynthesizing=!1,this.privIsSynthesisEnded=!0,this.privAudioOutputStream.close(),this.privInTurn=!1,this.privTurnAudioDestination!==void 0&&(this.privTurnAudioDestination.close(),this.privTurnAudioDestination=void 0))}readAllAudioFromStream(){return Dt(this,void 0,void 0,function*(){if(this.privIsSynthesisEnded){this.privReceivedAudio=new ArrayBuffer(this.bytesReceived);try{yield this.privAudioOutputStream.read(this.privReceivedAudio)}catch{this.privReceivedAudio=new ArrayBuffer(0)}}})}withinXmlTag(e){return this.privRawText.indexOf("<",e+1)>this.privRawText.indexOf(">",e+1)}}class Ar{constructor(e){let t=e.parameters.getProperty(p.SpeechServiceConnection_Endpoint,void 0);if(!t){const n=e.parameters.getProperty(p.SpeechServiceConnection_Region,"westus"),s=je.getHostSuffix(n);t=e.parameters.getProperty(p.SpeechServiceConnection_Host,`https://${n}.tts.speech${s}`)}this.privUri=`${t}/cognitiveservices/voices/list`;const i=Q.requestOptions;i.headers[Q.configParams.subscriptionKey]=e.parameters.getProperty(p.SpeechServiceConnection_Key,void 0),this.privRestAdapter=new Kr(i)}getVoicesList(e){return this.privRestAdapter.setHeaders(b.ConnectionId,e),this.privRestAdapter.request(pe.Get,this.privUri)}}var xt;(function(r){r[r.Standard=0]="Standard",r[r.Custom=1]="Custom"})(xt||(xt={}));class Pr{constructor(e,t){this.privSynthesisServiceType=xt.Standard,this.privSpeechServiceConfig=e||new Ye(new et(null)),this.privParameters=t}get parameters(){return this.privParameters}get synthesisServiceType(){return this.privSynthesisServiceType}set synthesisServiceType(e){this.privSynthesisServiceType=e}get SpeechServiceConfig(){return this.privSpeechServiceConfig}}class Ir{constructor(e){this.privContext={},this.privSpeechSynthesizer=e}setSection(e,t){this.privContext[e]=t}set audioOutputFormat(e){this.privAudioOutputFormat=e}toJSON(){const e=this.buildSynthesisContext();return this.setSection("synthesis",e),JSON.stringify(this.privContext)}buildSynthesisContext(){return{audio:{metadataOptions:{bookmarkEnabled:!!this.privSpeechSynthesizer.bookmarkReached,punctuationBoundaryEnabled:this.privSpeechSynthesizer.properties.getProperty(p.SpeechServiceResponse_RequestPunctuationBoundary,!!this.privSpeechSynthesizer.wordBoundary),sentenceBoundaryEnabled:this.privSpeechSynthesizer.properties.getProperty(p.SpeechServiceResponse_RequestSentenceBoundary,!1),sessionEndEnabled:!0,visemeEnabled:!!this.privSpeechSynthesizer.visemeReceived,wordBoundaryEnabled:this.privSpeechSynthesizer.properties.getProperty(p.SpeechServiceResponse_RequestWordBoundary,!!this.privSpeechSynthesizer.wordBoundary)},outputFormat:this.privAudioOutputFormat.requestAudioFormatString},language:{autoDetection:this.privSpeechSynthesizer.autoDetectSourceLanguage}}}}const nt="OutputFormat",Ci="CancellationErrorCode",xe="ServiceProperties",Ei="ForceDictation",Mr="OpenRange";var st=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};const zr="MICROPHONE-WorkletSourceUrl";class V{constructor(e,t,i,n){this.privRecorder=e,this.deviceId=t,this.privStreams={},this.privOutputChunkSize=V.AUDIOFORMAT.avgBytesPerSec/10,this.privId=i||R(),this.privEvents=new F,this.privMediaStream=n||null,this.privIsClosing=!1}get format(){return Promise.resolve(V.AUDIOFORMAT)}get blob(){return Promise.reject("Not implemented for Mic input")}turnOn(){if(this.privInitializeDeferral)return this.privInitializeDeferral.promise;this.privInitializeDeferral=new D;try{this.createAudioContext()}catch(i){if(i instanceof Error){const n=i;this.privInitializeDeferral.reject(n.name+": "+n.message)}else this.privInitializeDeferral.reject(i);return this.privInitializeDeferral.promise}const e=window.navigator;let t=e.getUserMedia||e.webkitGetUserMedia||e.mozGetUserMedia||e.msGetUserMedia;if(e.mediaDevices&&(t=(i,n,s)=>{e.mediaDevices.getUserMedia(i).then(n).catch(s)}),t){const i=()=>{this.onEvent(new _e(this.privId)),this.privMediaStream&&this.privMediaStream.active?(this.onEvent(new Ee(this.privId)),this.privInitializeDeferral.resolve()):t({audio:this.deviceId?{deviceId:this.deviceId}:!0,video:!1},n=>{this.privMediaStream=n,this.onEvent(new Ee(this.privId)),this.privInitializeDeferral.resolve()},n=>{const s=`Error occurred during microphone initialization: ${n}`;this.privInitializeDeferral.reject(s),this.onEvent(new He(this.privId,s))})};this.privContext.state==="suspended"?this.privContext.resume().then(i).catch(n=>{this.privInitializeDeferral.reject(`Failed to initialize audio context: ${n}`)}):i()}else{const i="Browser does not support getUserMedia.";this.privInitializeDeferral.reject(i),this.onEvent(new He(i,""))}return this.privInitializeDeferral.promise}id(){return this.privId}attach(e){return this.onEvent(new Te(this.privId,e)),this.listen(e).then(t=>(this.onEvent(new be(this.privId,e)),{detach:()=>st(this,void 0,void 0,function*(){return t.readEnded(),delete this.privStreams[e],this.onEvent(new $(this.privId,e)),this.turnOff()}),id:()=>e,read:()=>t.read()}))}detach(e){e&&this.privStreams[e]&&(this.privStreams[e].close(),delete this.privStreams[e],this.onEvent(new $(this.privId,e)))}turnOff(){return st(this,void 0,void 0,function*(){for(const e in this.privStreams)if(e){const t=this.privStreams[e];t&&t.close()}this.onEvent(new Bt(this.privId)),this.privInitializeDeferral&&(yield this.privInitializeDeferral,this.privInitializeDeferral=null),yield this.destroyAudioContext()})}get events(){return this.privEvents}get deviceInfo(){return this.getMicrophoneLabel().then(e=>({bitspersample:V.AUDIOFORMAT.bitsPerSample,channelcount:V.AUDIOFORMAT.channels,connectivity:Se.Unknown,manufacturer:"Speech SDK",model:e,samplerate:V.AUDIOFORMAT.samplesPerSec,type:ue.Microphones}))}setProperty(e,t){if(e===zr)this.privRecorder.setWorkletUrl(t);else throw new Error("Property '"+e+"' is not supported on Microphone.")}getMicrophoneLabel(){const e="microphone";if(this.privMicrophoneLabel!==void 0)return Promise.resolve(this.privMicrophoneLabel);if(this.privMediaStream===void 0||!this.privMediaStream.active)return Promise.resolve(e);this.privMicrophoneLabel=e;const t=this.privMediaStream.getTracks()[0].getSettings().deviceId;if(t===void 0)return Promise.resolve(this.privMicrophoneLabel);const i=new D;return navigator.mediaDevices.enumerateDevices().then(n=>{for(const s of n)if(s.deviceId===t){this.privMicrophoneLabel=s.label;break}i.resolve(this.privMicrophoneLabel)},()=>i.resolve(this.privMicrophoneLabel)),i.promise}listen(e){return st(this,void 0,void 0,function*(){yield this.turnOn();const t=new gt(this.privOutputChunkSize,e);this.privStreams[e]=t;try{this.privRecorder.record(this.privContext,this.privMediaStream,t)}catch(n){throw this.onEvent(new pt(this.privId,e,n)),n}return t})}onEvent(e){this.privEvents.onEvent(e),L.instance.onEvent(e)}createAudioContext(){this.privContext||(this.privContext=Y.getAudioContext(V.AUDIOFORMAT.samplesPerSec))}destroyAudioContext(){return st(this,void 0,void 0,function*(){if(!this.privContext)return;this.privRecorder.releaseMediaResources(this.privContext);let e=!1;"close"in this.privContext&&(e=!0),e?this.privIsClosing||(this.privIsClosing=!0,yield this.privContext.close(),this.privContext=null,this.privIsClosing=!1):this.privContext!==null&&this.privContext.state==="running"&&(yield this.privContext.suspend())})}}V.AUDIOFORMAT=Ue.getDefaultInputFormat();var Nt=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};class kr{constructor(e,t,i){this.privStreams={},this.privHeaderEnd=44,this.privId=i||R(),this.privEvents=new F,this.privSource=e,typeof window!="undefined"&&typeof Blob!="undefined"&&this.privSource instanceof Blob?this.privFilename=e.name:this.privFilename=t||"unknown.wav",this.privAudioFormatPromise=this.readHeader()}get format(){return this.privAudioFormatPromise}get blob(){return Promise.resolve(this.privSource)}turnOn(){if(this.privFilename.lastIndexOf(".wav")!==this.privFilename.length-4){const e=this.privFilename+" is not supported. Only WAVE files are allowed at the moment.";return this.onEvent(new He(e,"")),Promise.reject(e)}this.onEvent(new _e(this.privId)),this.onEvent(new Ee(this.privId))}id(){return this.privId}attach(e){return Nt(this,void 0,void 0,function*(){this.onEvent(new Te(this.privId,e));const t=yield this.upload(e);return this.onEvent(new be(this.privId,e)),Promise.resolve({detach:()=>Nt(this,void 0,void 0,function*(){t.readEnded(),delete this.privStreams[e],this.onEvent(new $(this.privId,e)),yield this.turnOff()}),id:()=>e,read:()=>t.read()})})}detach(e){e&&this.privStreams[e]&&(this.privStreams[e].close(),delete this.privStreams[e],this.onEvent(new $(this.privId,e)))}turnOff(){for(const e in this.privStreams)if(e){const t=this.privStreams[e];t&&!t.isClosed&&t.close()}return this.onEvent(new Bt(this.privId)),Promise.resolve()}get events(){return this.privEvents}get deviceInfo(){return this.privAudioFormatPromise.then(e=>Promise.resolve({bitspersample:e.bitsPerSample,channelcount:e.channels,connectivity:Se.Unknown,manufacturer:"Speech SDK",model:"File",samplerate:e.samplesPerSec,type:ue.File}))}readHeader(){const t=this.privSource.slice(0,512),i=new D,n=s=>{const o=new DataView(s),a=T=>String.fromCharCode(o.getUint8(T),o.getUint8(T+1),o.getUint8(T+2),o.getUint8(T+3));if(a(0)!=="RIFF"){i.reject("Invalid WAV header in file, RIFF was not found");return}if(a(8)!=="WAVE"||a(12)!=="fmt "){i.reject("Invalid WAV header in file, WAVEfmt was not found");return}const u=o.getInt32(16,!0),h=o.getUint16(22,!0),c=o.getUint32(24,!0),d=o.getUint16(34,!0);let f=36+Math.max(u-16,0);for(;a(f)!=="data";f+=2)if(f>512-8){i.reject("Invalid WAV header in file, data block was not found");return}this.privHeaderEnd=f+8,i.resolve(Ue.getWaveFormatPCM(c,d,h))};if(typeof window!="undefined"&&typeof Blob!="undefined"&&t instanceof Blob){const s=new FileReader;s.onload=o=>{const a=o.target.result;n(a)},s.readAsArrayBuffer(t)}else{const s=t;n(s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength))}return i.promise}upload(e){return Nt(this,void 0,void 0,function*(){const t=i=>{const n=`Error occurred while processing '${this.privFilename}'. ${i}`;throw this.onEvent(new pt(this.privId,e,n)),new Error(n)};try{yield this.turnOn();const i=yield this.privAudioFormatPromise,n=new gt(i.avgBytesPerSec/10,e);this.privStreams[e]=n;const s=this.privSource.slice(this.privHeaderEnd),o=a=>{n.isClosed||(n.writeStreamChunk({buffer:a,isEnd:!1,timeReceived:Date.now()}),n.close())};if(typeof window!="undefined"&&typeof Blob!="undefined"&&s instanceof Blob){const a=new FileReader;a.onerror=u=>t(u.toString()),a.onload=u=>{const h=u.target.result;o(h)},a.readAsArrayBuffer(s)}else{const a=s;o(a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength))}return n}catch(i){t(i)}})}onEvent(e){this.privEvents.onEvent(e),L.instance.onEvent(e)}}class Lt{constructor(e){this.privStopInputOnRelease=e}record(e,t,i){const s=new Oi(e.sampleRate,16e3),o=e.createMediaStreamSource(t);if(!this.privSpeechProcessorScript){const u=`class SP extends AudioWorkletProcessor {
7
7
  constructor(options) {
8
8
  super(options);
9
9
  }
@@ -17,9 +17,9 @@ File System access not available, please use Push or PullAudioOutputStream`),thi
17
17
  return true;
18
18
  }
19
19
  }
20
- registerProcessor('speech-processor', SP);`,h=new Blob([u],{type:"application/javascript; charset=utf-8"});this.privSpeechProcessorScript=URL.createObjectURL(h)}const a=()=>{const u=(()=>{let h=0;try{return e.createScriptProcessor(h,1,1)}catch{h=2048;let d=e.sampleRate;for(;h<16384&&d>=32e3;)h<<=1,d>>=1;return e.createScriptProcessor(h,1,1)}})();u.onaudioprocess=h=>{const c=h.inputBuffer.getChannelData(0);if(i&&!i.isClosed){const d=s.encode(c);d&&i.writeStreamChunk({buffer:d,isEnd:!1,timeReceived:Date.now()})}},o.connect(u),u.connect(e.destination),this.privMediaResources={scriptProcessorNode:u,source:o,stream:t}};if(!!this.privSpeechProcessorScript&&!!e.audioWorklet)e.audioWorklet.addModule(this.privSpeechProcessorScript).then(()=>{const u=new AudioWorkletNode(e,"speech-processor");u.port.onmessage=h=>{const c=h.data;if(i&&!i.isClosed){const d=s.encode(c);d&&i.writeStreamChunk({buffer:d,isEnd:!1,timeReceived:Date.now()})}},o.connect(u),u.connect(e.destination),this.privMediaResources={scriptProcessorNode:u,source:o,stream:t}}).catch(()=>{a()});else try{a()}catch(u){throw new Error(`Unable to start audio worklet node for PCMRecorder: ${u}`)}}releaseMediaResources(e){this.privMediaResources&&(this.privMediaResources.scriptProcessorNode&&(this.privMediaResources.scriptProcessorNode.disconnect(e.destination),this.privMediaResources.scriptProcessorNode=null),this.privMediaResources.source&&(this.privMediaResources.source.disconnect(),this.privStopInputOnRelease&&this.privMediaResources.stream.getTracks().forEach(t=>t.stop()),this.privMediaResources.source=null))}setWorkletUrl(e){this.privSpeechProcessorScript=e}}var De=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};class A{constructor(e){e&&(this.privProxyInfo=e),A.privDiskCache||(A.privDiskCache=new L("microsoft-cognitiveservices-speech-sdk-cache",{supportBuffer:!0,location:typeof process!="undefined"&&!!{}.SPEECH_OCSP_CACHE_ROOT?{}.SPEECH_OCSP_CACHE_ROOT:void 0}))}static forceReinitDiskCache(){A.privDiskCache=void 0,A.privMemCache={}}GetAgent(e){const t=new L.Agent(this.CreateConnection);if(this.privProxyInfo!==void 0&&this.privProxyInfo.HostName!==void 0&&this.privProxyInfo.Port>0){const i="privProxyInfo";t[i]=this.privProxyInfo}return t}static GetProxyAgent(e){const t={host:e.HostName,port:e.Port};return e.UserName?t.headers={"Proxy-Authentication":"Basic "+new Buffer(`${e.UserName}:${e.Password===void 0?"":e.Password}`).toString("base64")}:t.headers={},t.headers.requestOCSP="true",new L(t)}static OCSPCheck(e,t){return De(this,void 0,void 0,function*(){let i,n,s=!1;const o=yield e;o.cork();const a=o;return new Promise((u,h)=>{o.on("OCSPResponse",c=>{c&&(this.onEvent(new Oi),n=c)}),o.on("error",c=>{s||(s=!0,o.destroy(),h(c))}),a.on("secure",()=>De(this,void 0,void 0,function*(){const c=a.getPeerCertificate(!0);try{const d=yield this.GetIssuer(c);i=(void 0)(c.raw,d.raw);const S=i.id.toString("hex");n||(n=yield A.GetResponseFromCache(S,i,t)),yield this.VerifyOCSPResponse(n,i,t),o.uncork(),s=!0,u(o)}catch(d){o.destroy(),s=!0,h(d)}}))})})}static GetIssuer(e){return e.issuerCertificate?Promise.resolve(e.issuerCertificate):new Promise((t,i)=>{new(void 0)({}).fetchIssuer(e,null,(s,o)=>{if(s){i(s);return}t(o)})})}static GetResponseFromCache(e,t,i){return De(this,void 0,void 0,function*(){let n=A.privMemCache[e];if(n&&this.onEvent(new Di(e)),!n)try{const s=yield A.privDiskCache.get(e);s.isCached&&(A.onEvent(new xi(e)),A.StoreMemoryCacheEntry(e,s.value),n=s.value)}catch{n=null}if(!n)return n;try{const a=(void 0)(n).value.tbsResponseData;if(a.responses.length<1){this.onEvent(new Bt(e,"Not enough data in cached response"));return}const u=a.responses[0].thisUpdate,h=a.responses[0].nextUpdate;if(h<Date.now()+this.testTimeOffset-6e4)this.onEvent(new _i(e,h)),n=null;else{const c=Math.min(864e5,(h-u)/2);h-(Date.now()+this.testTimeOffset)<c?(this.onEvent(new Hi(e,u,h)),this.UpdateCache(t,i).catch(d=>{this.onEvent(new Wi(e,d.toString()))})):this.onEvent(new Ki(e,u,h))}}catch(s){this.onEvent(new Bt(e,s)),n=null}return n||this.onEvent(new ki(e)),n})}static VerifyOCSPResponse(e,t,i){return De(this,void 0,void 0,function*(){let n=e;return n||(n=yield A.GetOCSPResponse(t,i)),new Promise((s,o)=>{(void 0)({request:t,response:n},a=>{a?(A.onEvent(new qi(t.id.toString("hex"),a)),e?this.VerifyOCSPResponse(null,t,i).then(()=>{s()},u=>{o(u)}):o(a)):(e||A.StoreCacheEntry(t.id.toString("hex"),n),s())})})})}static UpdateCache(e,t){return De(this,void 0,void 0,function*(){const i=e.id.toString("hex");this.onEvent(new Ni(i));const n=yield this.GetOCSPResponse(e,t);this.StoreCacheEntry(i,n),this.onEvent(new Bi(e.id.toString("hex")))})}static StoreCacheEntry(e,t){this.StoreMemoryCacheEntry(e,t),this.StoreDiskCacheEntry(e,t)}static StoreMemoryCacheEntry(e,t){this.privMemCache[e]=t,this.onEvent(new zi(e))}static StoreDiskCacheEntry(e,t){this.privDiskCache.set(e,t).then(()=>{this.onEvent(new Li(e))})}static GetOCSPResponse(e,t){const i="1.3.6.1.5.5.7.48.1";let n={};if(t){const s=A.GetProxyAgent(t);n.agent=s}return new Promise((s,o)=>{(void 0)(e.cert,i,(a,u)=>{if(a){o(a);return}const h=new URL(u);n=Object.assign(Object.assign({},n),{host:h.host,protocol:h.protocol,port:h.port,path:h.pathname,hostname:h.host}),(void 0)(n,e.data,(c,d)=>{if(c){o(c);return}const S=e.certID;this.onEvent(new Ui(S.toString("hex"))),s(d)})})})}static onEvent(e){N.instance.onEvent(e)}CreateConnection(e,t){const i=typeof process!="undefined"&&{}.NODE_TLS_REJECT_UNAUTHORIZED!=="0"&&{}.SPEECH_CONDUCT_OCSP_CHECK!=="0"&&t.secureEndpoint;let n;if(t=Object.assign(Object.assign({},t),{requestOCSP:!A.forceDisableOCSPStapling,servername:t.host}),this.privProxyInfo){const o=A.GetProxyAgent(this.privProxyInfo);n=new Promise((a,u)=>{o.callback(e,t,(h,c)=>{h?u(h):a(c)})})}else t.secureEndpoint,n=Promise.resolve((void 0)(t));return i?A.OCSPCheck(n,this.privProxyInfo):n}}A.testTimeOffset=0,A.forceDisableOCSPStapling=!1,A.privMemCache={};var fi=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};class tt{constructor(e,t,i,n,s,o){if(!e)throw new I("uri");if(!i)throw new I("messageFormatter");this.proxyInfo=n,this.privConnectionEvents=new j,this.privConnectionId=t,this.privMessageFormatter=i,this.privConnectionState=M.None,this.privUri=e,this.privHeaders=s,this.privEnableCompression=o,this.privHeaders[T.ConnectionId]=this.privConnectionId,this.privLastErrorReceived=""}get state(){return this.privConnectionState}open(){if(this.privConnectionState===M.Disconnected)return Promise.reject(`Cannot open a connection that is in ${this.privConnectionState} state`);if(this.privConnectionEstablishDeferral)return this.privConnectionEstablishDeferral.promise;this.privConnectionEstablishDeferral=new D,this.privCertificateValidatedDeferral=new D,this.privConnectionState=M.Connecting;try{if(typeof WebSocket!="undefined"&&!tt.forceNpmWebSocket)this.privCertificateValidatedDeferral.resolve(),this.privWebsocketClient=new WebSocket(this.privUri);else{const e={headers:this.privHeaders,perMessageDeflate:this.privEnableCompression};this.privCertificateValidatedDeferral.resolve();const t=new A(this.proxyInfo);e.agent=t.GetAgent();let n=new URL(this.privUri).protocol;(n==null?void 0:n.toLocaleLowerCase())==="wss:"?n="https:":(n==null?void 0:n.toLocaleLowerCase())==="ws:"&&(n="http:"),e.agent.protocol=n,this.privWebsocketClient=new L(this.privUri,e)}this.privWebsocketClient.binaryType="arraybuffer",this.privReceivingMessageQueue=new be,this.privDisconnectDeferral=new D,this.privSendMessageQueue=new be,this.processSendQueue().catch(e=>{N.instance.onEvent(new Ee(e))})}catch(e){return this.privConnectionEstablishDeferral.resolve(new ct(500,e)),this.privConnectionEstablishDeferral.promise}return this.onEvent(new kt(this.privConnectionId,this.privUri)),this.privWebsocketClient.onopen=()=>{this.privCertificateValidatedDeferral.promise.then(()=>{this.privConnectionState=M.Connected,this.onEvent(new xt(this.privConnectionId)),this.privConnectionEstablishDeferral.resolve(new ct(200,""))},e=>{this.privConnectionEstablishDeferral.reject(e)})},this.privWebsocketClient.onerror=e=>{this.onEvent(new Ri(this.privConnectionId,e.message,e.type)),this.privLastErrorReceived=e.message},this.privWebsocketClient.onclose=e=>{this.privConnectionState===M.Connecting?(this.privConnectionState=M.Disconnected,this.privConnectionEstablishDeferral.resolve(new ct(e.code,e.reason+" "+this.privLastErrorReceived))):(this.privConnectionState=M.Disconnected,this.privWebsocketClient=null,this.onEvent(new Ei(this.privConnectionId,e.code,e.reason))),this.onClose(e.code,e.reason).catch(t=>{N.instance.onEvent(new Ee(t))})},this.privWebsocketClient.onmessage=e=>{const t=new Date().toISOString();if(this.privConnectionState===M.Connected){const i=new D;if(this.privReceivingMessageQueue.enqueueFromPromise(i.promise),e.data instanceof ArrayBuffer){const n=new Le(m.Binary,e.data);this.privMessageFormatter.toConnectionMessage(n).then(s=>{this.onEvent(new st(this.privConnectionId,t,s)),i.resolve(s)},s=>{i.reject(`Invalid binary message format. Error: ${s}`)})}else{const n=new Le(m.Text,e.data);this.privMessageFormatter.toConnectionMessage(n).then(s=>{this.onEvent(new st(this.privConnectionId,t,s)),i.resolve(s)},s=>{i.reject(`Invalid text message format. Error: ${s}`)})}}},this.privConnectionEstablishDeferral.promise}send(e){if(this.privConnectionState!==M.Connected)return Promise.reject(`Cannot send on connection that is in ${M[this.privConnectionState]} state`);const t=new D,i=new D;return this.privSendMessageQueue.enqueueFromPromise(i.promise),this.privMessageFormatter.fromConnectionMessage(e).then(n=>{i.resolve({Message:e,RawWebsocketMessage:n,sendStatusDeferral:t})},n=>{i.reject(`Error formatting the message. ${n}`)}),t.promise}read(){return this.privConnectionState!==M.Connected?Promise.reject(`Cannot read on connection that is in ${this.privConnectionState} state`):this.privReceivingMessageQueue.dequeue()}close(e){if(this.privWebsocketClient)this.privConnectionState!==M.Disconnected&&this.privWebsocketClient.close(1e3,e||"Normal closure by client");else return Promise.resolve();return this.privDisconnectDeferral.promise}get events(){return this.privConnectionEvents}sendRawMessage(e){try{if(!e)return Promise.resolve();if(this.onEvent(new Ai(this.privConnectionId,new Date().toISOString(),e.Message)),this.isWebsocketOpen)this.privWebsocketClient.send(e.RawWebsocketMessage.payload);else return Promise.reject("websocket send error: Websocket not ready "+this.privConnectionId+" "+e.Message.id+" "+new Error().stack);return Promise.resolve()}catch(t){return Promise.reject(`websocket send error: ${t}`)}}onClose(e,t){return fi(this,void 0,void 0,function*(){const i=`Connection closed. ${e}: ${t}`;this.privConnectionState=M.Disconnected,this.privDisconnectDeferral.resolve(),yield this.privReceivingMessageQueue.drainAndDispose(()=>{},i),yield this.privSendMessageQueue.drainAndDispose(n=>{n.sendStatusDeferral.reject(i)},i)})}processSendQueue(){return fi(this,void 0,void 0,function*(){for(;;){const t=yield this.privSendMessageQueue.dequeue();if(!t)return;try{yield this.sendRawMessage(t),t.sendStatusDeferral.resolve()}catch(i){t.sendStatusDeferral.reject(i)}}})}onEvent(e){this.privConnectionEvents.onEvent(e),N.instance.onEvent(e)}get isWebsocketOpen(){return this.privWebsocketClient&&this.privWebsocketClient.readyState===this.privWebsocketClient.OPEN}}tt.forceNpmWebSocket=!1;var Er=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};class gi{constructor(e,t,i,n,s,o=!1,a){if(this.privIsDisposed=!1,!e)throw new I("uri");if(!n)throw new I("messageFormatter");this.privMessageFormatter=n;let u="",h=0;if(t){for(const c in t)if(c){u+=h===0&&e.indexOf("?")===-1?"?":"&";const d=encodeURIComponent(t[c]);u+=`${c}=${d}`,h++}}if(i){for(const c in i)if(c){u+=h===0&&e.indexOf("?")===-1?"?":"&";const d=encodeURIComponent(i[c]);u+=`${c}=${d}`,h++}}this.privUri=e+u,this.privId=a||E(),this.privConnectionMessageAdapter=new tt(this.privUri,this.id,this.privMessageFormatter,s,i,o)}dispose(){return Er(this,void 0,void 0,function*(){this.privIsDisposed=!0,this.privConnectionMessageAdapter&&(yield this.privConnectionMessageAdapter.close())})}isDisposed(){return this.privIsDisposed}get id(){return this.privId}state(){return this.privConnectionMessageAdapter.state}open(){return this.privConnectionMessageAdapter.open()}send(e){return this.privConnectionMessageAdapter.send(e)}read(){return this.privConnectionMessageAdapter.read()}get events(){return this.privConnectionMessageAdapter.events}}class Rr{constructor(e,t){this.privBuffers=[],this.privReplayOffset=0,this.privLastShrinkOffset=0,this.privBufferStartOffset=0,this.privBufferSerial=0,this.privBufferedBytes=0,this.privReplay=!1,this.privLastChunkAcquiredTime=0,this.privAudioNode=e,this.privBytesPerSecond=t}id(){return this.privAudioNode.id()}read(){if(!!this.privReplay&&this.privBuffers.length!==0){const e=this.privReplayOffset-this.privBufferStartOffset;let t=Math.round(e*this.privBytesPerSecond*1e-7);t%2!==0&&t++;let i=0;for(;i<this.privBuffers.length&&t>=this.privBuffers[i].chunk.buffer.byteLength;)t-=this.privBuffers[i++].chunk.buffer.byteLength;if(i<this.privBuffers.length){const n=this.privBuffers[i].chunk.buffer.slice(t);return this.privReplayOffset+=n.byteLength/this.privBytesPerSecond*1e7,i===this.privBuffers.length-1&&(this.privReplay=!1),Promise.resolve({buffer:n,isEnd:!1,timeReceived:this.privBuffers[i].chunk.timeReceived})}}return this.privAudioNode.read().then(e=>(e&&e.buffer&&(this.privBuffers.push(new Pr(e,this.privBufferSerial++,this.privBufferedBytes)),this.privBufferedBytes+=e.buffer.byteLength),e))}detach(){return this.privBuffers=void 0,this.privAudioNode.detach()}replay(){this.privBuffers&&this.privBuffers.length!==0&&(this.privReplay=!0,this.privReplayOffset=this.privLastShrinkOffset)}shrinkBuffers(e){if(this.privBuffers===void 0||this.privBuffers.length===0)return;this.privLastShrinkOffset=e;const t=e-this.privBufferStartOffset;let i=Math.round(t*this.privBytesPerSecond*1e-7),n=0;for(;n<this.privBuffers.length&&i>=this.privBuffers[n].chunk.buffer.byteLength;)i-=this.privBuffers[n++].chunk.buffer.byteLength;this.privBufferStartOffset=Math.round(e-i/this.privBytesPerSecond*1e7),this.privBuffers=this.privBuffers.slice(n)}findTimeAtOffset(e){if(e<this.privBufferStartOffset||this.privBuffers===void 0)return 0;for(const t of this.privBuffers){const i=t.byteOffset/this.privBytesPerSecond*1e7,n=i+t.chunk.buffer.byteLength/this.privBytesPerSecond*1e7;if(e>=i&&e<=n)return t.chunk.timeReceived}return 0}}class Pr{constructor(e,t,i){this.chunk=e,this.serial=t,this.byteOffset=i}}class it{constructor(e,t,i,n){this.privProxyHostName=e,this.privProxyPort=t,this.privProxyUserName=i,this.privProxyPassword=n}static fromParameters(e){return new it(e.getProperty(p.SpeechServiceConnection_ProxyHostName),parseInt(e.getProperty(p.SpeechServiceConnection_ProxyPort),10),e.getProperty(p.SpeechServiceConnection_ProxyUserName),e.getProperty(p.SpeechServiceConnection_ProxyPassword))}static fromRecognizerConfig(e){return this.fromParameters(e.parameters)}get HostName(){return this.privProxyHostName}get Port(){return this.privProxyPort}get UserName(){return this.privProxyUserName}get Password(){return this.privProxyPassword}}const Ar=new Set(["json","buffer","string"]);var Ir=r=>(...e)=>{const t=new Set;let i,n,s,o="";return e.forEach(a=>{if(typeof a=="string")if(a.toUpperCase()===a)if(i){const u=`Can't set method to ${a}, already set to ${i}.`;throw new Error(u)}else i=a;else if(a.startsWith("http:")||a.startsWith("https:"))o=a;else if(Ar.has(a))n=a;else throw new Error(`Unknown encoding, ${a}`);else if(typeof a=="number")t.add(a);else if(typeof a=="object")if(Array.isArray(a)||a instanceof Set)a.forEach(u=>t.add(u));else{if(s)throw new Error("Cannot set headers twice.");s=a}else throw new Error(`Unknown type: ${typeof a}`)}),i||(i="GET"),t.size===0&&t.add(200),r(t,i,n,s,o)};const Mr=Ir;class It extends Error{constructor(e,...t){super(...t),Error.captureStackTrace&&Error.captureStackTrace(this,It),this.name="StatusError",this.message=e.statusMessage,this.statusCode=e.status,this.res=e,this.json=e.json.bind(e),this.text=e.text.bind(e),this.arrayBuffer=e.arrayBuffer.bind(e);let i;Object.defineProperty(this,"responseBody",{get:()=>(i||(i=this.arrayBuffer()),i)}),this.headers={};for(const[s,o]of e.headers.entries())this.headers[s.toLowerCase()]=o}}var Dr=Mr((r,e,t,i,n)=>async(s,o,a={})=>{s=n+(s||"");let u=new URL(s);if(i||(i={}),u.username&&(i.Authorization="Basic "+btoa(u.username+":"+u.password),u=new URL(u.protocol+"//"+u.host+u.pathname+u.search)),u.protocol!=="https:"&&u.protocol!=="http:")throw new Error(`Unknown protocol, ${u.protocol}`);if(o&&!(o instanceof ArrayBuffer||ArrayBuffer.isView(o)||typeof o=="string"))if(typeof o=="object")o=JSON.stringify(o),i["Content-Type"]="application/json";else throw new Error("Unknown body type.");a=new Headers({...i||{},...a});const h=await fetch(u,{method:e,headers:a,body:o});if(h.statusCode=h.status,!r.has(h.status))throw new It(h);return t==="json"?h.json():t==="buffer"?h.arrayBuffer():t==="string"?h.text():h}),kr=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})},he;(function(r){r.Get="GET",r.Post="POST",r.Delete="DELETE",r.File="file"})(he||(he={}));class xr{constructor(e){if(!e)throw new I("configParams");this.privHeaders=e.headers,this.privIgnoreCache=e.ignoreCache}static extractHeaderValue(e,t){let i="";try{const n=t.trim().split(/[\r\n]+/),s={};n.forEach(o=>{const a=o.split(": "),u=a.shift().toLowerCase(),h=a.join(": ");s[u]=h}),i=s[e.toLowerCase()]}catch{}return i}set options(e){this.privHeaders=e.headers,this.privIgnoreCache=e.ignoreCache}setHeaders(e,t){this.privHeaders[e]=t}request(e,t,i={},n=null,s=null){const o=new D,a=e===he.File?"POST":e,u=(d,S={})=>{const _=d;return{data:JSON.stringify(S),headers:JSON.stringify(d.headers),json:S,ok:d.statusCode>=200&&d.statusCode<300,status:d.statusCode,statusText:S.error?S.error.message:_.statusText?_.statusText:_.statusMessage}},h=d=>{const S=new FileReader;return S.readAsArrayBuffer(d),new Promise(_=>{S.onloadend=()=>{_(S.result)}})},c=d=>{const S=Dr(t,a,this.privHeaders,200,201,202,204,400,401,402,403,404),_=this.queryParams(i)===""?"":`?${this.queryParams(i)}`;S(_,d).then(Z=>kr(this,void 0,void 0,function*(){if(e===he.Delete||Z.statusCode===204)o.resolve(u(Z));else try{const ke=yield Z.json();o.resolve(u(Z,ke))}catch{o.resolve(u(Z))}})).catch(Z=>{o.reject(Z)})};if(this.privIgnoreCache&&(this.privHeaders["Cache-Control"]="no-cache"),e===he.File&&s){const d="multipart/form-data";this.privHeaders["content-type"]=d,this.privHeaders["Content-Type"]=d,typeof Blob!="undefined"&&s instanceof Blob?h(s).then(S=>{c(S)}).catch(S=>{o.reject(S)}):c(s)}else e===he.Post&&n&&(this.privHeaders["content-type"]="application/json",this.privHeaders["Content-Type"]="application/json"),c(n);return o.promise}withQuery(e,t={}){const i=this.queryParams(t);return i?e+(e.indexOf("?")===-1?"?":"&")+i:e}queryParams(e={}){return Object.keys(e).map(t=>encodeURIComponent(t)+"="+encodeURIComponent(e[t])).join("&")}}class Nr{constructor(e,t,i,n=null){y(this,"key");y(this,"region");y(this,"sourceLanguage");y(this,"targetLanguage");y(this,"recognizer");this.key=e,this.region=t,this.sourceLanguage=i,this.targetLanguage=n!==null?n:i}async start(){await this.registerBindings(document)}async registerBindings(e){const t=e.childNodes;for(let i=0;i<t.length;i++){if(!t[i])continue;const n=t[i];n.attributes&&(n.attributes.getNamedItem("co-stt.start")?await this.handleStartModifier(n,n.attributes.getNamedItem("co-stt.start")):n.attributes.getNamedItem("co-stt.stop")&&await this.handleStopModifier(n,n.attributes.getNamedItem("co-stt.stop"))),n.childNodes.length>0&&await this.registerBindings(n)}}async handleStartModifier(e,t){e.addEventListener("click",async i=>{const n=Jt.fromSubscription(this.key,this.region);n.speechRecognitionLanguage=this.sourceLanguage,n.addTargetLanguage(this.targetLanguage);const s=ee.fromDefaultMicrophoneInput();this.recognizer=new Ji(n,s),document.dispatchEvent(new CustomEvent("COAzureSTTStartedRecording",{}));const o=[];this.recognizer.recognizing=(a,u)=>{const h=u.result;if(h&&h.reason===P.TranslatingSpeech){const c=h.translations.get(this.targetLanguage);o["result_"+h.privOffset.toString()]=c;const d=Object.values(o).join(". "),S=document.getElementById(t.value);S!==null&&(S instanceof HTMLInputElement?S.value=`${d} `:S.innerHTML=`${d} `)}},this.recognizer.startContinuousRecognitionAsync(a=>{},a=>{console.log(a),this.stop()})})}async handleStopModifier(e,t){e.addEventListener("click",async i=>{await this.stop()})}async stop(){this.recognizer!==void 0&&(this.recognizer.stopContinuousRecognitionAsync(),this.recognizer.close(),this.recognizer=void 0),document.dispatchEvent(new CustomEvent("COAzureSTTStoppedRecording",{}))}}class zr{constructor(e,t,i,n=0,s=0,o=""){y(this,"key");y(this,"region");y(this,"voice");y(this,"rate");y(this,"pitch");y(this,"textToRead","");y(this,"wordBoundryList",[]);y(this,"clickedNode");y(this,"highlightDiv");y(this,"speechConfig");y(this,"audioConfig");y(this,"player");y(this,"synthesizer");y(this,"previousWordBoundary");y(this,"interval");y(this,"wordEncounters",[]);y(this,"originalHighlightDivInnerHTML","");y(this,"currentWord","");y(this,"currentOffset",0);y(this,"wordBoundaryOffset",0);y(this,"playbackTextOffsetBase");y(this,"prevTextOffset",0);y(this,"url","");y(this,"prefetchedAudio",new Map);y(this,"prefetchPromises",new Map);y(this,"activePrefetchedAudioUrl","");y(this,"playbackSegments",[]);this.key=e,this.region=t,this.voice=i,this.rate=n,this.pitch=s,this.url=o}async start(){await this.registerBindings(document)}setVoice(e){return this.voice=e,this.clearPrefetchedAudio(),this}setRate(e){return this.rate=e,this.clearPrefetchedAudio(),this}setPitch(e){return this.pitch=e,this.clearPrefetchedAudio(),this}async registerBindings(e){const t=e.childNodes;for(let i=0;i<t.length;i++){if(!t[i])continue;const n=t[i];n.attributes&&(n.attributes.getNamedItem("co-tts.id")?await this.handleIdModifier(n,n.attributes.getNamedItem("co-tts.id")):n.attributes.getNamedItem("co-tts.ajax")?await this.handleAjaxModifier(n,n.attributes.getNamedItem("co-tts.ajax")):n.attributes.getNamedItem("co-tts")?await this.handleDefault(n,n.attributes.getNamedItem("co-tts")):n.attributes.getNamedItem("co-tts.stop")?await this.handleStopModifier(n,n.attributes.getNamedItem("co-tts.stop")):n.attributes.getNamedItem("co-tts.resume")?await this.handleResumeModifier(n,n.attributes.getNamedItem("co-tts.resume")):n.attributes.getNamedItem("co-tts.pause")&&await this.handlePauseModifier(n,n.attributes.getNamedItem("co-tts.pause"))),n.childNodes.length>0&&await this.registerBindings(n)}}async handleIdModifier(e,t){e.addEventListener("click",async i=>{var s,o;this.stopPlayer(),await this.createInterval();const n=document.getElementById(t.value);if(this.clickedNode=n,!!n){if(n.hasAttribute("co-tts.text")&&n.getAttribute("co-tts.text")!==""?this.textToRead=(s=n.getAttribute("co-tts.text"))!=null?s:"":this.textToRead=n.innerText,n.hasAttribute("co-tts.highlight"))if(((o=n.attributes.getNamedItem("co-tts.highlight"))==null?void 0:o.value)!==""){const a=document.getElementById(n.attributes.getNamedItem("co-tts.highlight").value);this.highlightDiv=a,this.originalHighlightDivInnerHTML=a.innerHTML}else this.highlightDiv=n,this.originalHighlightDivInnerHTML=n.innerHTML;this.startSynthesizer(e,t)}})}async handleAjaxModifier(e,t){e.addEventListener("click",async i=>{this.stopPlayer(),await this.createInterval(),this.clickedNode=e;const n=await fetch(t.value,{method:"GET"});this.textToRead=await n.text(),this.startSynthesizer(e,t)})}async handleDefault(e,t){e.addEventListener("click",async i=>{var n;if(this.stopPlayer(),await this.createInterval(),this.clickedNode=e,e.hasAttribute("co-tts.highlight"))if(((n=e.attributes.getNamedItem("co-tts.highlight"))==null?void 0:n.value)!==""){const s=document.getElementById(e.attributes.getNamedItem("co-tts.highlight").value);this.highlightDiv=s,this.originalHighlightDivInnerHTML=s.innerHTML}else this.highlightDiv=e,this.originalHighlightDivInnerHTML=e.innerHTML;t.value===""?this.textToRead=e.innerText:this.textToRead=t.value,this.startSynthesizer(e,t)})}async handleWithoutClick(e,t){var i;if(this.stopPlayer(),await this.createInterval(),this.clickedNode=e,e.hasAttribute("co-tts.highlight"))if(((i=e.attributes.getNamedItem("co-tts.highlight"))==null?void 0:i.value)!==""){const n=document.getElementById(e.attributes.getNamedItem("co-tts.highlight").value);this.highlightDiv=n,n!==null&&(this.originalHighlightDivInnerHTML=n.innerHTML)}else this.highlightDiv=e,this.originalHighlightDivInnerHTML=e.innerHTML;t.value===""?this.textToRead=e.innerText:this.textToRead=t.value,this.startSynthesizer(e,t)}async handleStopModifier(e,t){e.addEventListener("click",async i=>{await this.stopPlayer(),document.dispatchEvent(new CustomEvent("COAzureTTSStoppedPlaying",{}))})}async handlePauseModifier(e,t){e.addEventListener("click",async i=>{await this.clearInterval(),await this.player.pause(),document.dispatchEvent(new CustomEvent("COAzureTTSPausedPlaying",{}))})}async handleResumeModifier(e,t){e.addEventListener("click",async i=>{await this.createInterval(),await this.player.resume(),document.dispatchEvent(new CustomEvent("COAzureTTSResumedPlaying",{}))})}async stopPlayer(){await this.clearInterval(),this.highlightDiv!==void 0&&(this.highlightDiv.innerHTML=this.originalHighlightDivInnerHTML),this.textToRead="",this.currentWord="",this.originalHighlightDivInnerHTML="",this.wordBoundryList=[],this.wordEncounters=[],this.resetPlaybackSegments(),this.playbackSegments=[],this.player!==void 0&&this.player.pause(),this.activePrefetchedAudioUrl!==""&&(URL.revokeObjectURL(this.activePrefetchedAudioUrl),this.activePrefetchedAudioUrl=""),this.player=void 0,this.highlightDiv=void 0,this.prevTextOffset=0,this.playbackTextOffsetBase=void 0}async startSynthesizer(e,t){this.speechConfig=_e.fromSubscription(this.key,this.region),this.speechConfig.speechSynthesisVoiceName=`Microsoft Server Speech Text to Speech Voice (${this.voice})`,this.speechConfig.speechSynthesisOutputFormat=g.Audio24Khz160KBitRateMonoMp3,this.player=new yt,this.audioConfig=ee.fromSpeakerOutput(this.player),this.synthesizer=new Pe(this.speechConfig,this.audioConfig),this.synthesizer.wordBoundary=(s,o)=>{this.wordBoundryList.push(o)};const i=this.collectPlaybackChain(this.clickedNode),n=i.length>1;n?this.preparePlaybackChain(i):this.playbackSegments=[],this.player.onAudioEnd=async()=>{const s=this.playbackSegments.length>0;if(this.stopPlayer(),s){document.dispatchEvent(new CustomEvent("COAzureTTSFinishedPlaying",{}));return}if(this.clickedNode.hasAttribute("co-tts.next")){const o=document.getElementById(this.clickedNode.getAttribute("co-tts.next"));if(o&&await this.playPrefetchedNode(o))return;o&&o.attributes.getNamedItem("co-tts.text")?this.handleWithoutClick(o,o.attributes.getNamedItem("co-tts.text")):o&&o.dispatchEvent(new Event("click"))}else document.dispatchEvent(new CustomEvent("COAzureTTSFinishedPlaying",{}))},this.player.onAudioStart=async()=>{document.dispatchEvent(new CustomEvent("COAzureTTSStartedPlaying",{}))},n||this.prefetchNextNode(this.clickedNode),this.synthesizer.speakSsmlAsync(this.buildSSML(this.textToRead),()=>{this.synthesizer.close(),this.synthesizer=void 0},()=>{this.synthesizer.close(),this.synthesizer=void 0})}collectPlaybackChain(e){var o,a;const t=[],i=new Set;let n=e,s=0;for(;n&&!i.has(n.id);){i.add(n.id);const u=(o=n.attributes.getNamedItem("co-tts.text"))!=null?o:n.attributes.getNamedItem("co-tts"),h=this.getNodeText(n,u);if(h==="")break;const c=this.getHighlightDivForNode(n);if(t.push({node:n,text:h,start:s,end:s+h.length,highlightDiv:c,originalHighlightDivInnerHTML:(a=c==null?void 0:c.innerHTML)!=null?a:""}),s+=h.length+1,!n.hasAttribute("co-tts.next"))break;n=document.getElementById(n.getAttribute("co-tts.next"))}return t}preparePlaybackChain(e){this.playbackSegments=e,this.textToRead=e.map(t=>t.text).join(" "),this.highlightDiv=void 0,this.originalHighlightDivInnerHTML="",this.wordEncounters=[],this.previousWordBoundary=void 0,this.prevTextOffset=0,this.playbackTextOffsetBase=void 0,this.currentWord="",this.currentOffset=0,this.wordBoundaryOffset=0}getHighlightDivForNode(e){var t;if(!!e.hasAttribute("co-tts.highlight"))return((t=e.attributes.getNamedItem("co-tts.highlight"))==null?void 0:t.value)!==""?document.getElementById(e.attributes.getNamedItem("co-tts.highlight").value):e}resetPlaybackSegments(){this.playbackSegments.forEach(e=>{e.highlightDiv&&(e.highlightDiv.innerHTML=e.originalHighlightDivInnerHTML)})}updateChainedHighlight(e){var h;if(~[".",",","!","?","*","(",")","&","\\","/","^","[","]","<",">",":"].indexOf(e.text)&&(e=(h=this.previousWordBoundary)!=null?h:void 0),!e){this.resetPlaybackSegments();return}this.playbackTextOffsetBase===void 0&&(this.playbackTextOffsetBase=e.textOffset);const t=Math.max(0,e.textOffset-this.playbackTextOffsetBase),i=this.playbackSegments.find(c=>t>=c.start&&t<c.end);if(this.resetPlaybackSegments(),!(i!=null&&i.highlightDiv)){this.previousWordBoundary=e;return}const n=t-i.start,s=this.getPosition(i.originalHighlightDivInnerHTML,e.text,n);if(s===Number.MAX_SAFE_INTEGER){this.previousWordBoundary=e;return}const o=i.originalHighlightDivInnerHTML.substring(0,s),a=s+e.wordLength,u=i.originalHighlightDivInnerHTML.substring(a);i.highlightDiv.innerHTML=`
20
+ registerProcessor('speech-processor', SP);`,h=new Blob([u],{type:"application/javascript; charset=utf-8"});this.privSpeechProcessorScript=URL.createObjectURL(h)}const a=()=>{const u=(()=>{let h=0;try{return e.createScriptProcessor(h,1,1)}catch{h=2048;let d=e.sampleRate;for(;h<16384&&d>=32e3;)h<<=1,d>>=1;return e.createScriptProcessor(h,1,1)}})();u.onaudioprocess=h=>{const c=h.inputBuffer.getChannelData(0);if(i&&!i.isClosed){const d=s.encode(c);d&&i.writeStreamChunk({buffer:d,isEnd:!1,timeReceived:Date.now()})}},o.connect(u),u.connect(e.destination),this.privMediaResources={scriptProcessorNode:u,source:o,stream:t}};if(!!this.privSpeechProcessorScript&&!!e.audioWorklet)e.audioWorklet.addModule(this.privSpeechProcessorScript).then(()=>{const u=new AudioWorkletNode(e,"speech-processor");u.port.onmessage=h=>{const c=h.data;if(i&&!i.isClosed){const d=s.encode(c);d&&i.writeStreamChunk({buffer:d,isEnd:!1,timeReceived:Date.now()})}},o.connect(u),u.connect(e.destination),this.privMediaResources={scriptProcessorNode:u,source:o,stream:t}}).catch(()=>{a()});else try{a()}catch(u){throw new Error(`Unable to start audio worklet node for PCMRecorder: ${u}`)}}releaseMediaResources(e){this.privMediaResources&&(this.privMediaResources.scriptProcessorNode&&(this.privMediaResources.scriptProcessorNode.disconnect(e.destination),this.privMediaResources.scriptProcessorNode=null),this.privMediaResources.source&&(this.privMediaResources.source.disconnect(),this.privStopInputOnRelease&&this.privMediaResources.stream.getTracks().forEach(t=>t.stop()),this.privMediaResources.source=null))}setWorkletUrl(e){this.privSpeechProcessorScript=e}}var Ne=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};class I{constructor(e){e&&(this.privProxyInfo=e),I.privDiskCache||(I.privDiskCache=new Oe("microsoft-cognitiveservices-speech-sdk-cache",{supportBuffer:!0,location:typeof process!="undefined"&&!!{}.SPEECH_OCSP_CACHE_ROOT?{}.SPEECH_OCSP_CACHE_ROOT:void 0}))}static forceReinitDiskCache(){I.privDiskCache=void 0,I.privMemCache={}}GetAgent(e){const t=new Oe.Agent(this.CreateConnection);if(this.privProxyInfo!==void 0&&this.privProxyInfo.HostName!==void 0&&this.privProxyInfo.Port>0){const i="privProxyInfo";t[i]=this.privProxyInfo}return t}static GetProxyAgent(e){const t={host:e.HostName,port:e.Port};return e.UserName?t.headers={"Proxy-Authentication":"Basic "+new Buffer(`${e.UserName}:${e.Password===void 0?"":e.Password}`).toString("base64")}:t.headers={},t.headers.requestOCSP="true",new Oe(t)}static OCSPCheck(e,t){return Ne(this,void 0,void 0,function*(){let i,n,s=!1;const o=yield e;o.cork();const a=o;return new Promise((u,h)=>{o.on("OCSPResponse",c=>{c&&(this.onEvent(new Fi),n=c)}),o.on("error",c=>{s||(s=!0,o.destroy(),h(c))}),a.on("secure",()=>Ne(this,void 0,void 0,function*(){const c=a.getPeerCertificate(!0);try{const d=yield this.GetIssuer(c);i=(void 0)(c.raw,d.raw);const f=i.id.toString("hex");n||(n=yield I.GetResponseFromCache(f,i,t)),yield this.VerifyOCSPResponse(n,i,t),o.uncork(),s=!0,u(o)}catch(d){o.destroy(),s=!0,h(d)}}))})})}static GetIssuer(e){return e.issuerCertificate?Promise.resolve(e.issuerCertificate):new Promise((t,i)=>{new(void 0)({}).fetchIssuer(e,null,(s,o)=>{if(s){i(s);return}t(o)})})}static GetResponseFromCache(e,t,i){return Ne(this,void 0,void 0,function*(){let n=I.privMemCache[e];if(n&&this.onEvent(new _i(e)),!n)try{const s=yield I.privDiskCache.get(e);s.isCached&&(I.onEvent(new Ki(e)),I.StoreMemoryCacheEntry(e,s.value),n=s.value)}catch{n=null}if(!n)return n;try{const a=(void 0)(n).value.tbsResponseData;if(a.responses.length<1){this.onEvent(new Vt(e,"Not enough data in cached response"));return}const u=a.responses[0].thisUpdate,h=a.responses[0].nextUpdate;if(h<Date.now()+this.testTimeOffset-6e4)this.onEvent(new ji(e,h)),n=null;else{const c=Math.min(864e5,(h-u)/2);h-(Date.now()+this.testTimeOffset)<c?(this.onEvent(new Gi(e,u,h)),this.UpdateCache(t,i).catch(d=>{this.onEvent(new Xi(e,d.toString()))})):this.onEvent(new $i(e,u,h))}}catch(s){this.onEvent(new Vt(e,s)),n=null}return n||this.onEvent(new Hi(e)),n})}static VerifyOCSPResponse(e,t,i){return Ne(this,void 0,void 0,function*(){let n=e;return n||(n=yield I.GetOCSPResponse(t,i)),new Promise((s,o)=>{(void 0)({request:t,response:n},a=>{a?(I.onEvent(new Ji(t.id.toString("hex"),a)),e?this.VerifyOCSPResponse(null,t,i).then(()=>{s()},u=>{o(u)}):o(a)):(e||I.StoreCacheEntry(t.id.toString("hex"),n),s())})})})}static UpdateCache(e,t){return Ne(this,void 0,void 0,function*(){const i=e.id.toString("hex");this.onEvent(new qi(i));const n=yield this.GetOCSPResponse(e,t);this.StoreCacheEntry(i,n),this.onEvent(new Vi(e.id.toString("hex")))})}static StoreCacheEntry(e,t){this.StoreMemoryCacheEntry(e,t),this.StoreDiskCacheEntry(e,t)}static StoreMemoryCacheEntry(e,t){this.privMemCache[e]=t,this.onEvent(new Ui(e))}static StoreDiskCacheEntry(e,t){this.privDiskCache.set(e,t).then(()=>{this.onEvent(new Wi(e))})}static GetOCSPResponse(e,t){const i="1.3.6.1.5.5.7.48.1";let n={};if(t){const s=I.GetProxyAgent(t);n.agent=s}return new Promise((s,o)=>{(void 0)(e.cert,i,(a,u)=>{if(a){o(a);return}const h=new URL(u);n=Object.assign(Object.assign({},n),{host:h.host,protocol:h.protocol,port:h.port,path:h.pathname,hostname:h.host}),(void 0)(n,e.data,(c,d)=>{if(c){o(c);return}const f=e.certID;this.onEvent(new Qi(f.toString("hex"))),s(d)})})})}static onEvent(e){L.instance.onEvent(e)}CreateConnection(e,t){const i=typeof process!="undefined"&&{}.NODE_TLS_REJECT_UNAUTHORIZED!=="0"&&{}.SPEECH_CONDUCT_OCSP_CHECK!=="0"&&t.secureEndpoint;let n;if(t=Object.assign(Object.assign({},t),{requestOCSP:!I.forceDisableOCSPStapling,servername:t.host}),this.privProxyInfo){const o=I.GetProxyAgent(this.privProxyInfo);n=new Promise((a,u)=>{o.callback(e,t,(h,c)=>{h?u(h):a(c)})})}else t.secureEndpoint,n=Promise.resolve((void 0)(t));return i?I.OCSPCheck(n,this.privProxyInfo):n}}I.testTimeOffset=0,I.forceDisableOCSPStapling=!1,I.privMemCache={};var Ti=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};class ot{constructor(e,t,i,n,s,o){if(!e)throw new z("uri");if(!i)throw new z("messageFormatter");this.proxyInfo=n,this.privConnectionEvents=new F,this.privConnectionId=t,this.privMessageFormatter=i,this.privConnectionState=k.None,this.privUri=e,this.privHeaders=s,this.privEnableCompression=o,this.privHeaders[b.ConnectionId]=this.privConnectionId,this.privLastErrorReceived=""}get state(){return this.privConnectionState}open(){if(this.privConnectionState===k.Disconnected)return Promise.reject(`Cannot open a connection that is in ${this.privConnectionState} state`);if(this.privConnectionEstablishDeferral)return this.privConnectionEstablishDeferral.promise;this.privConnectionEstablishDeferral=new D,this.privCertificateValidatedDeferral=new D,this.privConnectionState=k.Connecting;try{if(typeof WebSocket!="undefined"&&!ot.forceNpmWebSocket)this.privCertificateValidatedDeferral.resolve(),this.privWebsocketClient=new WebSocket(this.privUri);else{const e={headers:this.privHeaders,perMessageDeflate:this.privEnableCompression};this.privCertificateValidatedDeferral.resolve();const t=new I(this.proxyInfo);e.agent=t.GetAgent();let n=new URL(this.privUri).protocol;(n==null?void 0:n.toLocaleLowerCase())==="wss:"?n="https:":(n==null?void 0:n.toLocaleLowerCase())==="ws:"&&(n="http:"),e.agent.protocol=n,this.privWebsocketClient=new Oe(this.privUri,e)}this.privWebsocketClient.binaryType="arraybuffer",this.privReceivingMessageQueue=new Ae,this.privDisconnectDeferral=new D,this.privSendMessageQueue=new Ae,this.processSendQueue().catch(e=>{L.instance.onEvent(new Ie(e))})}catch(e){return this.privConnectionEstablishDeferral.resolve(new ft(500,e)),this.privConnectionEstablishDeferral.promise}return this.onEvent(new Ht(this.privConnectionId,this.privUri)),this.privWebsocketClient.onopen=()=>{this.privCertificateValidatedDeferral.promise.then(()=>{this.privConnectionState=k.Connected,this.onEvent(new Kt(this.privConnectionId)),this.privConnectionEstablishDeferral.resolve(new ft(200,""))},e=>{this.privConnectionEstablishDeferral.reject(e)})},this.privWebsocketClient.onerror=e=>{this.onEvent(new xi(this.privConnectionId,e.message,e.type)),this.privLastErrorReceived=e.message},this.privWebsocketClient.onclose=e=>{this.privConnectionState===k.Connecting?(this.privConnectionState=k.Disconnected,this.privConnectionEstablishDeferral.resolve(new ft(e.code,e.reason+" "+this.privLastErrorReceived))):(this.privConnectionState=k.Disconnected,this.privWebsocketClient=null,this.onEvent(new Di(this.privConnectionId,e.code,e.reason))),this.onClose(e.code,e.reason).catch(t=>{L.instance.onEvent(new Ie(t))})},this.privWebsocketClient.onmessage=e=>{const t=new Date().toISOString();if(this.privConnectionState===k.Connected){const i=new D;if(this.privReceivingMessageQueue.enqueueFromPromise(i.promise),e.data instanceof ArrayBuffer){const n=new qe(y.Binary,e.data);this.privMessageFormatter.toConnectionMessage(n).then(s=>{this.onEvent(new dt(this.privConnectionId,t,s)),i.resolve(s)},s=>{i.reject(`Invalid binary message format. Error: ${s}`)})}else{const n=new qe(y.Text,e.data);this.privMessageFormatter.toConnectionMessage(n).then(s=>{this.onEvent(new dt(this.privConnectionId,t,s)),i.resolve(s)},s=>{i.reject(`Invalid text message format. Error: ${s}`)})}}},this.privConnectionEstablishDeferral.promise}send(e){if(this.privConnectionState!==k.Connected)return Promise.reject(`Cannot send on connection that is in ${k[this.privConnectionState]} state`);const t=new D,i=new D;return this.privSendMessageQueue.enqueueFromPromise(i.promise),this.privMessageFormatter.fromConnectionMessage(e).then(n=>{i.resolve({Message:e,RawWebsocketMessage:n,sendStatusDeferral:t})},n=>{i.reject(`Error formatting the message. ${n}`)}),t.promise}read(){return this.privConnectionState!==k.Connected?Promise.reject(`Cannot read on connection that is in ${this.privConnectionState} state`):this.privReceivingMessageQueue.dequeue()}close(e){if(this.privWebsocketClient)this.privConnectionState!==k.Disconnected&&this.privWebsocketClient.close(1e3,e||"Normal closure by client");else return Promise.resolve();return this.privDisconnectDeferral.promise}get events(){return this.privConnectionEvents}sendRawMessage(e){try{if(!e)return Promise.resolve();if(this.onEvent(new Li(this.privConnectionId,new Date().toISOString(),e.Message)),this.isWebsocketOpen)this.privWebsocketClient.send(e.RawWebsocketMessage.payload);else return Promise.reject("websocket send error: Websocket not ready "+this.privConnectionId+" "+e.Message.id+" "+new Error().stack);return Promise.resolve()}catch(t){return Promise.reject(`websocket send error: ${t}`)}}onClose(e,t){return Ti(this,void 0,void 0,function*(){const i=`Connection closed. ${e}: ${t}`;this.privConnectionState=k.Disconnected,this.privDisconnectDeferral.resolve(),yield this.privReceivingMessageQueue.drainAndDispose(()=>{},i),yield this.privSendMessageQueue.drainAndDispose(n=>{n.sendStatusDeferral.reject(i)},i)})}processSendQueue(){return Ti(this,void 0,void 0,function*(){for(;;){const t=yield this.privSendMessageQueue.dequeue();if(!t)return;try{yield this.sendRawMessage(t),t.sendStatusDeferral.resolve()}catch(i){t.sendStatusDeferral.reject(i)}}})}onEvent(e){this.privConnectionEvents.onEvent(e),L.instance.onEvent(e)}get isWebsocketOpen(){return this.privWebsocketClient&&this.privWebsocketClient.readyState===this.privWebsocketClient.OPEN}}ot.forceNpmWebSocket=!1;var Dr=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};class bi{constructor(e,t,i,n,s,o=!1,a){if(this.privIsDisposed=!1,!e)throw new z("uri");if(!n)throw new z("messageFormatter");this.privMessageFormatter=n;let u="",h=0;if(t){for(const c in t)if(c){u+=h===0&&e.indexOf("?")===-1?"?":"&";const d=encodeURIComponent(t[c]);u+=`${c}=${d}`,h++}}if(i){for(const c in i)if(c){u+=h===0&&e.indexOf("?")===-1?"?":"&";const d=encodeURIComponent(i[c]);u+=`${c}=${d}`,h++}}this.privUri=e+u,this.privId=a||R(),this.privConnectionMessageAdapter=new ot(this.privUri,this.id,this.privMessageFormatter,s,i,o)}dispose(){return Dr(this,void 0,void 0,function*(){this.privIsDisposed=!0,this.privConnectionMessageAdapter&&(yield this.privConnectionMessageAdapter.close())})}isDisposed(){return this.privIsDisposed}get id(){return this.privId}state(){return this.privConnectionMessageAdapter.state}open(){return this.privConnectionMessageAdapter.open()}send(e){return this.privConnectionMessageAdapter.send(e)}read(){return this.privConnectionMessageAdapter.read()}get events(){return this.privConnectionMessageAdapter.events}}class xr{constructor(e,t){this.privBuffers=[],this.privReplayOffset=0,this.privLastShrinkOffset=0,this.privBufferStartOffset=0,this.privBufferSerial=0,this.privBufferedBytes=0,this.privReplay=!1,this.privLastChunkAcquiredTime=0,this.privAudioNode=e,this.privBytesPerSecond=t}id(){return this.privAudioNode.id()}read(){if(!!this.privReplay&&this.privBuffers.length!==0){const e=this.privReplayOffset-this.privBufferStartOffset;let t=Math.round(e*this.privBytesPerSecond*1e-7);t%2!==0&&t++;let i=0;for(;i<this.privBuffers.length&&t>=this.privBuffers[i].chunk.buffer.byteLength;)t-=this.privBuffers[i++].chunk.buffer.byteLength;if(i<this.privBuffers.length){const n=this.privBuffers[i].chunk.buffer.slice(t);return this.privReplayOffset+=n.byteLength/this.privBytesPerSecond*1e7,i===this.privBuffers.length-1&&(this.privReplay=!1),Promise.resolve({buffer:n,isEnd:!1,timeReceived:this.privBuffers[i].chunk.timeReceived})}}return this.privAudioNode.read().then(e=>(e&&e.buffer&&(this.privBuffers.push(new Nr(e,this.privBufferSerial++,this.privBufferedBytes)),this.privBufferedBytes+=e.buffer.byteLength),e))}detach(){return this.privBuffers=void 0,this.privAudioNode.detach()}replay(){this.privBuffers&&this.privBuffers.length!==0&&(this.privReplay=!0,this.privReplayOffset=this.privLastShrinkOffset)}shrinkBuffers(e){if(this.privBuffers===void 0||this.privBuffers.length===0)return;this.privLastShrinkOffset=e;const t=e-this.privBufferStartOffset;let i=Math.round(t*this.privBytesPerSecond*1e-7),n=0;for(;n<this.privBuffers.length&&i>=this.privBuffers[n].chunk.buffer.byteLength;)i-=this.privBuffers[n++].chunk.buffer.byteLength;this.privBufferStartOffset=Math.round(e-i/this.privBytesPerSecond*1e7),this.privBuffers=this.privBuffers.slice(n)}findTimeAtOffset(e){if(e<this.privBufferStartOffset||this.privBuffers===void 0)return 0;for(const t of this.privBuffers){const i=t.byteOffset/this.privBytesPerSecond*1e7,n=i+t.chunk.buffer.byteLength/this.privBytesPerSecond*1e7;if(e>=i&&e<=n)return t.chunk.timeReceived}return 0}}class Nr{constructor(e,t,i){this.chunk=e,this.serial=t,this.byteOffset=i}}class at{constructor(e,t,i,n){this.privProxyHostName=e,this.privProxyPort=t,this.privProxyUserName=i,this.privProxyPassword=n}static fromParameters(e){return new at(e.getProperty(p.SpeechServiceConnection_ProxyHostName),parseInt(e.getProperty(p.SpeechServiceConnection_ProxyPort),10),e.getProperty(p.SpeechServiceConnection_ProxyUserName),e.getProperty(p.SpeechServiceConnection_ProxyPassword))}static fromRecognizerConfig(e){return this.fromParameters(e.parameters)}get HostName(){return this.privProxyHostName}get Port(){return this.privProxyPort}get UserName(){return this.privProxyUserName}get Password(){return this.privProxyPassword}}const Lr=new Set(["json","buffer","string"]);var Or=r=>(...e)=>{const t=new Set;let i,n,s,o="";return e.forEach(a=>{if(typeof a=="string")if(a.toUpperCase()===a)if(i){const u=`Can't set method to ${a}, already set to ${i}.`;throw new Error(u)}else i=a;else if(a.startsWith("http:")||a.startsWith("https:"))o=a;else if(Lr.has(a))n=a;else throw new Error(`Unknown encoding, ${a}`);else if(typeof a=="number")t.add(a);else if(typeof a=="object")if(Array.isArray(a)||a instanceof Set)a.forEach(u=>t.add(u));else{if(s)throw new Error("Cannot set headers twice.");s=a}else throw new Error(`Unknown type: ${typeof a}`)}),i||(i="GET"),t.size===0&&t.add(200),r(t,i,n,s,o)};const Br=Or;class Ot extends Error{constructor(e,...t){super(...t),Error.captureStackTrace&&Error.captureStackTrace(this,Ot),this.name="StatusError",this.message=e.statusMessage,this.statusCode=e.status,this.res=e,this.json=e.json.bind(e),this.text=e.text.bind(e),this.arrayBuffer=e.arrayBuffer.bind(e);let i;Object.defineProperty(this,"responseBody",{get:()=>(i||(i=this.arrayBuffer()),i)}),this.headers={};for(const[s,o]of e.headers.entries())this.headers[s.toLowerCase()]=o}}var _r=Br((r,e,t,i,n)=>async(s,o,a={})=>{s=n+(s||"");let u=new URL(s);if(i||(i={}),u.username&&(i.Authorization="Basic "+btoa(u.username+":"+u.password),u=new URL(u.protocol+"//"+u.host+u.pathname+u.search)),u.protocol!=="https:"&&u.protocol!=="http:")throw new Error(`Unknown protocol, ${u.protocol}`);if(o&&!(o instanceof ArrayBuffer||ArrayBuffer.isView(o)||typeof o=="string"))if(typeof o=="object")o=JSON.stringify(o),i["Content-Type"]="application/json";else throw new Error("Unknown body type.");a=new Headers({...i||{},...a});const h=await fetch(u,{method:e,headers:a,body:o});if(h.statusCode=h.status,!r.has(h.status))throw new Ot(h);return t==="json"?h.json():t==="buffer"?h.arrayBuffer():t==="string"?h.text():h}),Hr=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})},pe;(function(r){r.Get="GET",r.Post="POST",r.Delete="DELETE",r.File="file"})(pe||(pe={}));class Kr{constructor(e){if(!e)throw new z("configParams");this.privHeaders=e.headers,this.privIgnoreCache=e.ignoreCache}static extractHeaderValue(e,t){let i="";try{const n=t.trim().split(/[\r\n]+/),s={};n.forEach(o=>{const a=o.split(": "),u=a.shift().toLowerCase(),h=a.join(": ");s[u]=h}),i=s[e.toLowerCase()]}catch{}return i}set options(e){this.privHeaders=e.headers,this.privIgnoreCache=e.ignoreCache}setHeaders(e,t){this.privHeaders[e]=t}request(e,t,i={},n=null,s=null){const o=new D,a=e===pe.File?"POST":e,u=(d,f={})=>{const T=d;return{data:JSON.stringify(f),headers:JSON.stringify(d.headers),json:f,ok:d.statusCode>=200&&d.statusCode<300,status:d.statusCode,statusText:f.error?f.error.message:T.statusText?T.statusText:T.statusMessage}},h=d=>{const f=new FileReader;return f.readAsArrayBuffer(d),new Promise(T=>{f.onloadend=()=>{T(f.result)}})},c=d=>{const f=_r(t,a,this.privHeaders,200,201,202,204,400,401,402,403,404),T=this.queryParams(i)===""?"":`?${this.queryParams(i)}`;f(T,d).then(U=>Hr(this,void 0,void 0,function*(){if(e===pe.Delete||U.statusCode===204)o.resolve(u(U));else try{const Le=yield U.json();o.resolve(u(U,Le))}catch{o.resolve(u(U))}})).catch(U=>{o.reject(U)})};if(this.privIgnoreCache&&(this.privHeaders["Cache-Control"]="no-cache"),e===pe.File&&s){const d="multipart/form-data";this.privHeaders["content-type"]=d,this.privHeaders["Content-Type"]=d,typeof Blob!="undefined"&&s instanceof Blob?h(s).then(f=>{c(f)}).catch(f=>{o.reject(f)}):c(s)}else e===pe.Post&&n&&(this.privHeaders["content-type"]="application/json",this.privHeaders["Content-Type"]="application/json"),c(n);return o.promise}withQuery(e,t={}){const i=this.queryParams(t);return i?e+(e.indexOf("?")===-1?"?":"&")+i:e}queryParams(e={}){return Object.keys(e).map(t=>encodeURIComponent(t)+"="+encodeURIComponent(e[t])).join("&")}}class qr{constructor(e){m(this,"region","");m(this,"sourceLanguage");m(this,"targetLanguage");m(this,"recognizer");m(this,"authorizationManager");m(this,"authorizationRefreshIntervalMs");m(this,"authorizationRefreshTimer");m(this,"stopPromise");var t;if(!e||typeof e.sourceLanguage!="string"||e.sourceLanguage.trim()==="")throw new Error("A sourceLanguage is required.");this.authorizationManager=new ht(e),this.authorizationRefreshIntervalMs=e.tokenLifetimeMs&&e.tokenLifetimeMs>0?e.tokenLifetimeMs:48e4,this.sourceLanguage=e.sourceLanguage,this.targetLanguage=(t=e.targetLanguage)!=null?t:e.sourceLanguage}async start(){await this.registerBindings(document)}async registerBindings(e){const t=e.childNodes;for(let i=0;i<t.length;i++){if(!t[i])continue;const n=t[i];n.attributes&&(n.attributes.getNamedItem("co-stt.start")?await this.handleStartModifier(n,n.attributes.getNamedItem("co-stt.start")):n.attributes.getNamedItem("co-stt.stop")&&await this.handleStopModifier(n,n.attributes.getNamedItem("co-stt.stop"))),n.childNodes.length>0&&await this.registerBindings(n)}}async createSpeechTranslationConfig(){const e=await this.authorizationManager.getAuthorization(),t=ri.fromAuthorizationToken(e.token,e.region);return t.speechRecognitionLanguage=this.sourceLanguage,t.addTargetLanguage(this.targetLanguage),this.region=e.region,t}async handleStartModifier(e,t){e.addEventListener("click",async i=>{try{await this.stop();const n=await this.createSpeechTranslationConfig(),s=ee.fromDefaultMicrophoneInput();this.recognizer=new rr(n,s),document.dispatchEvent(new CustomEvent("COAzureSTTStartedRecording",{}));const o={};this.recognizer.recognizing=(a,u)=>{const h=u.result;if(h&&h.reason===P.TranslatingSpeech){const c=h.translations.get(this.targetLanguage);o["result_"+h.privOffset.toString()]=c;const d=Object.values(o).join(". "),f=document.getElementById(t.value);f!==null&&(f instanceof HTMLInputElement?f.value=`${d} `:f.innerHTML=`${d} `)}},this.recognizer.startContinuousRecognitionAsync(()=>{this.scheduleAuthorizationRefresh()},a=>{oe(a)&&this.authorizationManager.clearAuthorization(),this.dispatchError(a,"RECOGNITION_ERROR"),this.stop()})}catch(n){this.clearAuthorizationRefreshTimer(),oe(n)&&this.authorizationManager.clearAuthorization(),this.dispatchError(n),await this.stop()}})}async handleStopModifier(e,t){e.addEventListener("click",async i=>{await this.stop()})}async stop(){if(this.stopPromise)return this.stopPromise;this.clearAuthorizationRefreshTimer();const e=this.recognizer;if(!!e)return this.recognizer=void 0,this.stopPromise=this.stopRecognizer(e).finally(()=>{this.stopPromise=void 0,document.dispatchEvent(new CustomEvent("COAzureSTTStoppedRecording",{}))}),this.stopPromise}scheduleAuthorizationRefresh(){this.clearAuthorizationRefreshTimer(),this.authorizationRefreshTimer=setTimeout(async()=>{if(!!this.recognizer)try{const e=await this.authorizationManager.refreshAuthorization();if(!this.recognizer)return;this.recognizer.authorizationToken=e.token,this.region=e.region,this.scheduleAuthorizationRefresh()}catch(e){this.dispatchError(e,"TOKEN_REFRESH_ERROR"),await this.stop()}},this.authorizationRefreshIntervalMs)}clearAuthorizationRefreshTimer(){!this.authorizationRefreshTimer||(clearTimeout(this.authorizationRefreshTimer),this.authorizationRefreshTimer=void 0)}stopRecognizer(e){return new Promise(t=>{let i=!1;const n=()=>{if(i){t();return}i=!0;try{e.close()}catch{}finally{t()}};try{e.stopContinuousRecognitionAsync(()=>{n()},()=>{n()})}catch{n()}})}dispatchError(e,t){const i=ye(e);t&&!i.code&&(i.code=t),document.dispatchEvent(new CustomEvent("COAzureSTTError",{detail:{error:i}}))}}class Ur{constructor(e){m(this,"region","");m(this,"voice");m(this,"rate");m(this,"pitch");m(this,"textToRead","");m(this,"wordBoundryList",[]);m(this,"clickedNode");m(this,"highlightDiv");m(this,"speechConfig");m(this,"audioConfig");m(this,"player");m(this,"synthesizer");m(this,"previousWordBoundary");m(this,"interval");m(this,"wordEncounters",[]);m(this,"originalHighlightDivInnerHTML","");m(this,"currentWord","");m(this,"currentOffset",0);m(this,"wordBoundaryOffset",0);m(this,"playbackTextOffsetBase");m(this,"prevTextOffset",0);m(this,"url","");m(this,"prefetchedAudio",new Map);m(this,"prefetchPromises",new Map);m(this,"activePrefetchedAudioUrl","");m(this,"playbackSegments",[]);m(this,"authorizationManager");m(this,"stopPromise");var t,i,n;if(!e||typeof e.voice!="string"||e.voice.trim()==="")throw new Error("A voice is required.");this.authorizationManager=new ht(e),this.voice=e.voice,this.rate=(t=e.rate)!=null?t:0,this.pitch=(i=e.pitch)!=null?i:0,this.url=(n=e.url)!=null?n:""}async start(){await this.registerBindings(document)}setVoice(e){return this.voice=e,this.clearPrefetchedAudio(),this}setRate(e){return this.rate=e,this.clearPrefetchedAudio(),this}setPitch(e){return this.pitch=e,this.clearPrefetchedAudio(),this}async registerBindings(e){const t=e.childNodes;for(let i=0;i<t.length;i++){if(!t[i])continue;const n=t[i];n.attributes&&(n.attributes.getNamedItem("co-tts.id")?await this.handleIdModifier(n,n.attributes.getNamedItem("co-tts.id")):n.attributes.getNamedItem("co-tts.ajax")?await this.handleAjaxModifier(n,n.attributes.getNamedItem("co-tts.ajax")):n.attributes.getNamedItem("co-tts")?await this.handleDefault(n,n.attributes.getNamedItem("co-tts")):n.attributes.getNamedItem("co-tts.stop")?await this.handleStopModifier(n,n.attributes.getNamedItem("co-tts.stop")):n.attributes.getNamedItem("co-tts.resume")?await this.handleResumeModifier(n,n.attributes.getNamedItem("co-tts.resume")):n.attributes.getNamedItem("co-tts.pause")&&await this.handlePauseModifier(n,n.attributes.getNamedItem("co-tts.pause"))),n.childNodes.length>0&&await this.registerBindings(n)}}async handleIdModifier(e,t){e.addEventListener("click",async i=>{var s,o,a,u,h,c;await this.stopPlayer(),await this.createInterval();const n=document.getElementById(t.value);if(this.clickedNode=n,!!n){if(n.hasAttribute("co-tts.text")&&n.getAttribute("co-tts.text")!==""?this.textToRead=(s=n.getAttribute("co-tts.text"))!=null?s:"":this.textToRead=(a=(o=n.innerText)!=null?o:n.textContent)!=null?a:"",n.hasAttribute("co-tts.highlight")){const d=(h=(u=n.attributes.getNamedItem("co-tts.highlight"))==null?void 0:u.value)!=null?h:"";if(d!==""){const f=document.getElementById(d);this.highlightDiv=f,this.originalHighlightDivInnerHTML=(c=f==null?void 0:f.innerHTML)!=null?c:""}else this.highlightDiv=n,this.originalHighlightDivInnerHTML=n.innerHTML}await this.startSynthesizer(e,t)}})}async handleAjaxModifier(e,t){e.addEventListener("click",async i=>{await this.stopPlayer(),await this.createInterval(),this.clickedNode=e;const n=await fetch(t.value,{method:"GET"});this.textToRead=await n.text(),await this.startSynthesizer(e,t)})}async handleDefault(e,t){e.addEventListener("click",async i=>{var n,s,o,a,u;if(await this.stopPlayer(),await this.createInterval(),this.clickedNode=e,e.hasAttribute("co-tts.highlight")){const h=(s=(n=e.attributes.getNamedItem("co-tts.highlight"))==null?void 0:n.value)!=null?s:"";if(h!==""){const c=document.getElementById(h);this.highlightDiv=c,this.originalHighlightDivInnerHTML=(o=c==null?void 0:c.innerHTML)!=null?o:""}else this.highlightDiv=e,this.originalHighlightDivInnerHTML=e.innerHTML}t.value===""?this.textToRead=(u=(a=e.innerText)!=null?a:e.textContent)!=null?u:"":this.textToRead=t.value,await this.startSynthesizer(e,t)})}async handleWithoutClick(e,t){var i,n,s;if(await this.stopPlayer(),await this.createInterval(),this.clickedNode=e,e.hasAttribute("co-tts.highlight"))if(((i=e.attributes.getNamedItem("co-tts.highlight"))==null?void 0:i.value)!==""){const o=document.getElementById(e.attributes.getNamedItem("co-tts.highlight").value);this.highlightDiv=o,o!==null&&(this.originalHighlightDivInnerHTML=o.innerHTML)}else this.highlightDiv=e,this.originalHighlightDivInnerHTML=e.innerHTML;t.value===""?this.textToRead=(s=(n=e.innerText)!=null?n:e.textContent)!=null?s:"":this.textToRead=t.value,await this.startSynthesizer(e,t)}async handleStopModifier(e,t){e.addEventListener("click",async i=>{await this.stopPlayer(),document.dispatchEvent(new CustomEvent("COAzureTTSStoppedPlaying",{}))})}async handlePauseModifier(e,t){e.addEventListener("click",async i=>{!this.player||typeof this.player.pause!="function"||(await this.clearInterval(),await this.player.pause(),document.dispatchEvent(new CustomEvent("COAzureTTSPausedPlaying",{})))})}async handleResumeModifier(e,t){e.addEventListener("click",async i=>{if(!!this.player){if(await this.createInterval(),typeof this.player.resume=="function")await this.player.resume();else if(typeof this.player.play=="function")await this.player.play();else return;document.dispatchEvent(new CustomEvent("COAzureTTSResumedPlaying",{}))}})}async stopPlayer(){return this.stopPromise?this.stopPromise:(this.stopPromise=this.performStopPlayer().finally(()=>{this.stopPromise=void 0}),this.stopPromise)}async performStopPlayer(){await this.clearInterval(),this.highlightDiv!==void 0&&(this.highlightDiv.innerHTML=this.originalHighlightDivInnerHTML),this.resetPlaybackSegments();const e=this.player,t=this.activePrefetchedAudioUrl,i=this.synthesizer;if(this.textToRead="",this.currentWord="",this.originalHighlightDivInnerHTML="",this.wordBoundryList=[],this.wordEncounters=[],this.playbackSegments=[],this.highlightDiv=void 0,this.prevTextOffset=0,this.playbackTextOffsetBase=void 0,this.audioConfig=void 0,this.speechConfig=void 0,this.player===e&&(this.player=void 0),this.activePrefetchedAudioUrl===t&&(this.activePrefetchedAudioUrl=""),this.synthesizer===i&&(this.synthesizer=void 0),e!==void 0&&typeof e.pause=="function")try{e.pause()}catch{}t!==""&&URL.revokeObjectURL(t),this.closeResource(i)}async createSpeechConfig(){const e=await this.authorizationManager.getAuthorization(),t=bt.fromAuthorizationToken(e.token,e.region);return t.speechSynthesisVoiceName=`Microsoft Server Speech Text to Speech Voice (${this.voice})`,t.speechSynthesisOutputFormat=S.Audio24Khz160KBitRateMonoMp3,this.region=e.region,t}async startSynthesizer(e,t){try{this.speechConfig=await this.createSpeechConfig(),this.player=new Pt,this.audioConfig=ee.fromSpeakerOutput(this.player),this.synthesizer=new ze(this.speechConfig,this.audioConfig),this.synthesizer.wordBoundary=(s,o)=>{this.wordBoundryList.push(o)};const i=this.collectPlaybackChain(this.clickedNode),n=i.length>1;n?this.preparePlaybackChain(i):this.playbackSegments=[],this.player.onAudioEnd=async()=>{var u;const s=this.clickedNode,o=this.playbackSegments.length>0,a=(u=s==null?void 0:s.hasAttribute)!=null&&u.call(s,"co-tts.next")?s.getAttribute("co-tts.next"):null;if(await this.stopPlayer(),o){document.dispatchEvent(new CustomEvent("COAzureTTSFinishedPlaying",{}));return}if(a){const h=document.getElementById(a);if(h&&await this.playPrefetchedNode(h))return;const c=h==null?void 0:h.attributes.getNamedItem("co-tts.text");h&&c?await this.handleWithoutClick(h,c):h&&h.dispatchEvent(new Event("click"))}else document.dispatchEvent(new CustomEvent("COAzureTTSFinishedPlaying",{}))},this.player.onAudioStart=async()=>{document.dispatchEvent(new CustomEvent("COAzureTTSStartedPlaying",{}))},n||this.prefetchNextNode(this.clickedNode),this.synthesizer.speakSsmlAsync(this.buildSSML(this.textToRead),()=>{this.closeSynthesizer()},s=>{oe(s)&&this.authorizationManager.clearAuthorization(),this.dispatchError(s,"SYNTHESIS_ERROR"),this.closeSynthesizer(),this.stopPlayer()})}catch(i){oe(i)&&this.authorizationManager.clearAuthorization(),this.dispatchError(i),await this.stopPlayer()}}collectPlaybackChain(e){var o,a;const t=[],i=new Set;let n=e,s=0;for(;n&&!i.has(n.id);){i.add(n.id);const u=(o=n.attributes.getNamedItem("co-tts.text"))!=null?o:n.attributes.getNamedItem("co-tts"),h=this.getNodeText(n,u);if(h==="")break;const c=this.getHighlightDivForNode(n);if(t.push({node:n,text:h,start:s,end:s+h.length,highlightDiv:c,originalHighlightDivInnerHTML:(a=c==null?void 0:c.innerHTML)!=null?a:""}),s+=h.length+1,!n.hasAttribute("co-tts.next"))break;n=document.getElementById(n.getAttribute("co-tts.next"))}return t}preparePlaybackChain(e){this.playbackSegments=e,this.textToRead=e.map(t=>t.text).join(" "),this.highlightDiv=void 0,this.originalHighlightDivInnerHTML="",this.wordEncounters=[],this.previousWordBoundary=void 0,this.prevTextOffset=0,this.playbackTextOffsetBase=void 0,this.currentWord="",this.currentOffset=0,this.wordBoundaryOffset=0}getHighlightDivForNode(e){var t;if(!!e.hasAttribute("co-tts.highlight"))return((t=e.attributes.getNamedItem("co-tts.highlight"))==null?void 0:t.value)!==""?document.getElementById(e.attributes.getNamedItem("co-tts.highlight").value):e}resetPlaybackSegments(){this.playbackSegments.forEach(e=>{e.highlightDiv&&(e.highlightDiv.innerHTML=e.originalHighlightDivInnerHTML)})}updateChainedHighlight(e){var h,c;if(~[".",",","!","?","*","(",")","&","\\","/","^","[","]","<",">",":"].indexOf(e.text)&&(e=(h=this.previousWordBoundary)!=null?h:void 0),!e){this.resetPlaybackSegments();return}this.playbackTextOffsetBase===void 0&&(this.playbackTextOffsetBase=e.textOffset);const t=Math.max(0,e.textOffset-((c=this.playbackTextOffsetBase)!=null?c:0)),i=this.playbackSegments.find(d=>t>=d.start&&t<d.end);if(this.resetPlaybackSegments(),!(i!=null&&i.highlightDiv)){this.previousWordBoundary=e;return}const n=t-i.start,s=this.getPosition(i.originalHighlightDivInnerHTML,e.text,n);if(s===Number.MAX_SAFE_INTEGER){this.previousWordBoundary=e;return}const o=i.originalHighlightDivInnerHTML.substring(0,s),a=s+e.wordLength,u=i.originalHighlightDivInnerHTML.substring(a);i.highlightDiv.innerHTML=`
21
21
  ${o}<mark class='co-tts-highlight'>${e.text}</mark>${u}
22
- `,this.previousWordBoundary=e}getNodeText(e,t){var i;return t&&t.value!==""?t.value:e.hasAttribute("co-tts.text")&&e.getAttribute("co-tts.text")!==""?(i=e.getAttribute("co-tts.text"))!=null?i:"":e.innerText}getPrefetchKey(e,t){return[e.id,t,this.voice,this.rate,this.pitch,this.url].join("|")}clearPrefetchedAudio(){this.prefetchedAudio.forEach(e=>{e.url&&URL.revokeObjectURL(e.url)}),this.prefetchedAudio.clear(),this.prefetchPromises.clear()}async prefetchNextNode(e){var c;if(!e||!e.hasAttribute("co-tts.next"))return;const t=document.getElementById(e.getAttribute("co-tts.next"));if(!t)return;const i=(c=t.attributes.getNamedItem("co-tts.text"))!=null?c:t.attributes.getNamedItem("co-tts"),n=this.getNodeText(t,i);if(n==="")return;const s=this.getPrefetchKey(t,n);if(this.prefetchedAudio.has(s)||this.prefetchPromises.has(s))return;const o=_e.fromSubscription(this.key,this.region);o.speechSynthesisVoiceName=`Microsoft Server Speech Text to Speech Voice (${this.voice})`,o.speechSynthesisOutputFormat=g.Audio24Khz160KBitRateMonoMp3;const a=new Pe(o,null),u=[];a.wordBoundary=(d,S)=>{u.push(S)};const h=new Promise(d=>{a.speakSsmlAsync(this.buildSSML(n),S=>{if(a.close(),!(S!=null&&S.audioData)){d(null);return}const _=new Blob([S.audioData],{type:"audio/mpeg"}),Z=URL.createObjectURL(_),ke={key:s,nodeId:t.id,text:n,url:Z,wordBoundryList:u};this.prefetchedAudio.set(s,ke),d(ke)},()=>{a.close(),d(null)})}).finally(()=>{this.prefetchPromises.delete(s)});this.prefetchPromises.set(s,h)}async playPrefetchedNode(e){var a,u,h;const t=(a=e.attributes.getNamedItem("co-tts.text"))!=null?a:e.attributes.getNamedItem("co-tts"),i=this.getNodeText(e,t),n=this.getPrefetchKey(e,i),s=(u=this.prefetchedAudio.get(n))!=null?u:await this.prefetchPromises.get(n);if(!s)return!1;if(this.prefetchedAudio.delete(n),this.clickedNode=e,this.textToRead=s.text,this.wordBoundryList=s.wordBoundryList,this.wordEncounters=[],this.previousWordBoundary=void 0,this.prevTextOffset=0,this.currentWord="",this.currentOffset=0,this.wordBoundaryOffset=0,e.hasAttribute("co-tts.highlight"))if(((h=e.attributes.getNamedItem("co-tts.highlight"))==null?void 0:h.value)!==""){const c=document.getElementById(e.attributes.getNamedItem("co-tts.highlight").value);this.highlightDiv=c,c!==null&&(this.originalHighlightDivInnerHTML=c.innerHTML)}else this.highlightDiv=e,this.originalHighlightDivInnerHTML=e.innerHTML;await this.createInterval();const o=new Audio(s.url);return this.activePrefetchedAudioUrl=s.url,this.player=o,o.addEventListener("play",()=>{document.dispatchEvent(new CustomEvent("COAzureTTSStartedPlaying",{}))},{once:!0}),o.addEventListener("ended",async()=>{if(this.stopPlayer(),this.clickedNode.hasAttribute("co-tts.next")){const c=document.getElementById(this.clickedNode.getAttribute("co-tts.next"));if(c&&await this.playPrefetchedNode(c))return;c&&c.attributes.getNamedItem("co-tts.text")?this.handleWithoutClick(c,c.attributes.getNamedItem("co-tts.text")):c&&c.dispatchEvent(new Event("click"))}else document.dispatchEvent(new CustomEvent("COAzureTTSFinishedPlaying",{}))},{once:!0}),this.prefetchNextNode(e),await o.play(),!0}async clearInterval(){clearInterval(this.interval)}async createInterval(){this.interval=setInterval(()=>{var e;if(this.player!==void 0&&(this.highlightDiv||this.playbackSegments.length>0)){const t=this.player.currentTime;let i;for(const n of this.wordBoundryList)if(t*1e3>n.audioOffset/1e4)i=n;else break;if(i!==void 0){if(this.playbackSegments.length>0){this.updateChainedHighlight(i);return}if(~[".",",","!","?","*","(",")","&","\\","/","^","[","]","<",">",":"].indexOf(i.text)&&(i=(e=this.previousWordBoundary)!=null?e:void 0),i===void 0||this.prevTextOffset>i.prevTextOffset)this.highlightDiv.innerHTML=this.originalHighlightDivInnerHTML;else if(this.wordEncounters[i.text]||(this.wordEncounters[i.text]=0),this.prevTextOffset=i.prevTextOffset,(this.currentWord!==i.text||this.wordBoundaryOffset!==i.textOffset)&&(this.currentOffset=this.getPosition(this.originalHighlightDivInnerHTML,i.text,i.textOffset),this.wordEncounters[i.text]=this.currentOffset+i.wordLength,this.currentWord=i.text,this.wordBoundaryOffset=i.textOffset),this.currentOffset===Number.MAX_SAFE_INTEGER)this.highlightDiv.innerHTML=this.originalHighlightDivInnerHTML;else{this.previousWordBoundary=i;const n=this.originalHighlightDivInnerHTML.substring(0,this.currentOffset),s=this.currentOffset+i.wordLength,o=this.originalHighlightDivInnerHTML.substring(s);this.highlightDiv.innerHTML=`
22
+ `,this.previousWordBoundary=e}getNodeText(e,t){var i,n,s;return t&&t.value!==""?t.value:e.hasAttribute("co-tts.text")&&e.getAttribute("co-tts.text")!==""?(i=e.getAttribute("co-tts.text"))!=null?i:"":(s=(n=e.innerText)!=null?n:e.textContent)!=null?s:""}getPrefetchKey(e,t){return[e.id,t,this.voice,this.rate,this.pitch,this.url].join("|")}clearPrefetchedAudio(){this.prefetchedAudio.forEach(e=>{e.url&&URL.revokeObjectURL(e.url)}),this.prefetchedAudio.clear(),this.prefetchPromises.clear()}async prefetchNextNode(e){var u;if(!e||!e.hasAttribute("co-tts.next"))return;const t=document.getElementById(e.getAttribute("co-tts.next"));if(!t)return;const i=(u=t.attributes.getNamedItem("co-tts.text"))!=null?u:t.attributes.getNamedItem("co-tts"),n=this.getNodeText(t,i);if(n==="")return;const s=this.getPrefetchKey(t,n);if(this.prefetchedAudio.has(s)||this.prefetchPromises.has(s))return;let o;const a=(async()=>{try{const h=await this.createSpeechConfig();o=new ze(h,void 0);const c=[];return o.wordBoundary=(d,f)=>{c.push(f)},await new Promise(d=>{o==null||o.speakSsmlAsync(this.buildSSML(n),f=>{if(this.closeResource(o),o=void 0,!(f!=null&&f.audioData)){d(null);return}const T=new Blob([f.audioData],{type:"audio/mpeg"}),U=URL.createObjectURL(T),Le={key:s,nodeId:t.id,text:n,url:U,wordBoundryList:c};this.prefetchedAudio.set(s,Le),d(Le)},f=>{this.closeResource(o),o=void 0,oe(f)&&this.authorizationManager.clearAuthorization(),this.dispatchError(f,"PREFETCH_ERROR"),d(null)})})}catch(h){return this.closeResource(o),o=void 0,oe(h)&&this.authorizationManager.clearAuthorization(),this.dispatchError(h),null}})().finally(()=>{this.prefetchPromises.delete(s)});this.prefetchPromises.set(s,a)}async playPrefetchedNode(e){var o,a,u;const t=(o=e.attributes.getNamedItem("co-tts.text"))!=null?o:e.attributes.getNamedItem("co-tts"),i=this.getNodeText(e,t),n=this.getPrefetchKey(e,i),s=(a=this.prefetchedAudio.get(n))!=null?a:await this.prefetchPromises.get(n);if(!s)return!1;if(this.prefetchedAudio.delete(n),this.clickedNode=e,this.textToRead=s.text,this.wordBoundryList=s.wordBoundryList,this.wordEncounters=[],this.previousWordBoundary=void 0,this.prevTextOffset=0,this.currentWord="",this.currentOffset=0,this.wordBoundaryOffset=0,e.hasAttribute("co-tts.highlight"))if(((u=e.attributes.getNamedItem("co-tts.highlight"))==null?void 0:u.value)!==""){const h=document.getElementById(e.attributes.getNamedItem("co-tts.highlight").value);this.highlightDiv=h,h!==null&&(this.originalHighlightDivInnerHTML=h.innerHTML)}else this.highlightDiv=e,this.originalHighlightDivInnerHTML=e.innerHTML;await this.createInterval();try{const h=new Audio(s.url);return this.activePrefetchedAudioUrl=s.url,this.player=h,h.addEventListener("play",()=>{document.dispatchEvent(new CustomEvent("COAzureTTSStartedPlaying",{}))},{once:!0}),h.addEventListener("ended",async()=>{var f;const c=this.clickedNode,d=(f=c==null?void 0:c.hasAttribute)!=null&&f.call(c,"co-tts.next")?c.getAttribute("co-tts.next"):null;if(await this.stopPlayer(),d){const T=document.getElementById(d);if(T&&await this.playPrefetchedNode(T))return;const U=T==null?void 0:T.attributes.getNamedItem("co-tts.text");T&&U?await this.handleWithoutClick(T,U):T&&T.dispatchEvent(new Event("click"))}else document.dispatchEvent(new CustomEvent("COAzureTTSFinishedPlaying",{}))},{once:!0}),h.addEventListener("error",()=>{this.dispatchError(new Error("Prefetched audio resource closed unexpectedly."),"AUDIO_RESOURCE_ERROR"),this.stopPlayer()},{once:!0}),this.prefetchNextNode(e),await h.play(),!0}catch(h){return this.dispatchError(h,"AUDIO_RESOURCE_ERROR"),await this.stopPlayer(),!1}}async clearInterval(){clearInterval(this.interval)}async createInterval(){this.interval=setInterval(()=>{var e;if(this.player!==void 0&&(this.highlightDiv||this.playbackSegments.length>0)){const t=this.player.currentTime;let i;for(const n of this.wordBoundryList)if(t*1e3>n.audioOffset/1e4)i=n;else break;if(i!==void 0){if(this.playbackSegments.length>0){this.updateChainedHighlight(i);return}if(~[".",",","!","?","*","(",")","&","\\","/","^","[","]","<",">",":"].indexOf(i.text)&&(i=(e=this.previousWordBoundary)!=null?e:void 0),i===void 0||this.prevTextOffset>i.prevTextOffset)this.highlightDiv.innerHTML=this.originalHighlightDivInnerHTML;else if(this.wordEncounters[i.text]||(this.wordEncounters[i.text]=0),this.prevTextOffset=i.prevTextOffset,(this.currentWord!==i.text||this.wordBoundaryOffset!==i.textOffset)&&(this.currentOffset=this.getPosition(this.originalHighlightDivInnerHTML,i.text,i.textOffset),this.wordEncounters[i.text]=this.currentOffset+i.wordLength,this.currentWord=i.text,this.wordBoundaryOffset=i.textOffset),this.currentOffset===Number.MAX_SAFE_INTEGER)this.highlightDiv.innerHTML=this.originalHighlightDivInnerHTML;else{this.previousWordBoundary=i;const n=this.originalHighlightDivInnerHTML.substring(0,this.currentOffset),s=this.currentOffset+i.wordLength,o=this.originalHighlightDivInnerHTML.substring(s);this.highlightDiv.innerHTML=`
23
23
  ${n}<mark class='co-tts-highlight'>${i.text}</mark>${o}
24
24
  `}}else this.playbackSegments.length>0?this.resetPlaybackSegments():this.highlightDiv.innerHTML=this.originalHighlightDivInnerHTML}},50)}getPosition(e,t,i){let n=0,s=!1;for(let o=0;o<e.length;o++){const a=e[o];if(a==="<"&&(s=!0),!s){if(n===i)return o;n++}a===">"&&(s=!1)}return e.indexOf(t)}buildSSML(e){let t=`<speak xmlns="http://www.w3.org/2001/10/synthesis"
25
25
  xmlns:mstts="http://www.w3.org/2001/mstts"
@@ -28,4 +28,4 @@ File System access not available, please use Push or PullAudioOutputStream`),thi
28
28
  xml:lang="en-US">
29
29
  <voice name="${this.voice}">`;return this.url!==""&&(t+=`<lexicon uri="${this.url}"/>`),t+=`<prosody rate="${this.rate}%" pitch="${this.pitch}%">
30
30
  ${this.convertHtmlEntities(e)}
31
- </prosody></voice></speak>`,t}convertHtmlEntities(e){const t=document.createElement("p");return t.textContent=e,t.innerHTML}}H.SpeechToText=Nr,H.TextToSpeech=zr,Object.defineProperties(H,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
31
+ </prosody></voice></speak>`,t}convertHtmlEntities(e){const t=document.createElement("p");return t.textContent=e,t.innerHTML}closeSynthesizer(){this.closeResource(this.synthesizer),this.synthesizer=void 0}closeResource(e){if(!(!e||typeof e.close!="function"))try{e.close()}catch{}}dispatchError(e,t){const i=ye(e);t&&!i.code&&(i.code=t),document.dispatchEvent(new CustomEvent("COAzureTTSError",{detail:{error:i}}))}}M.DEFAULT_TOKEN_LIFETIME_MS=48e4,M.SpeechAuthorizationManager=ht,M.SpeechToText=qr,M.TextToSpeech=Ur,M.createSpeechAuthorizationProvider=Z,M.isLikelyAuthorizationError=oe,M.sanitizeErrorText=we,M.toSafeErrorDetail=ye,M.validateSpeechAuthorization=ct,Object.defineProperties(M,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});