@creativeorange/azure-text-to-speech 2.2.2 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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(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,Ci=new Uint8Array(16);function Ei(){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(Ci)}var Ti=/^(?:[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 bi(r){return typeof r=="string"&&Ti.test(r)}for(var z=[],rt=0;rt<256;++rt)z.push((rt+256).toString(16).substr(1));function Ri(r){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,t=(z[r[e+0]]+z[r[e+1]]+z[r[e+2]]+z[r[e+3]]+"-"+z[r[e+4]]+z[r[e+5]]+"-"+z[r[e+6]]+z[r[e+7]]+"-"+z[r[e+8]]+z[r[e+9]]+"-"+z[r[e+10]]+z[r[e+11]]+z[r[e+12]]+z[r[e+13]]+z[r[e+14]]+z[r[e+15]]).toLowerCase();if(!bi(t))throw TypeError("Stringified UUID is invalid");return t}function Ai(r,e,t){r=r||{};var i=r.random||(r.rng||Ei)();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 Ri(i)}const Pi=()=>Ai(),b=()=>Pi().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=b(),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 me extends se{constructor(e,t,i=w.Info){super(e,i),this.privAudioSourceId=t}get audioSourceId(){return this.privAudioSourceId}}class xe extends me{constructor(e){super("AudioSourceInitializingEvent",e)}}class ye extends me{constructor(e){super("AudioSourceReadyEvent",e)}}class Dt extends me{constructor(e){super("AudioSourceOffEvent",e)}}class Ne extends me{constructor(e,t){super("AudioSourceErrorEvent",e,w.Error),this.privError=t}get error(){return this.privError}}class Le extends me{constructor(e,t,i){super(e,t),this.privAudioNodeId=i}get audioNodeId(){return this.privAudioNodeId}}class we extends Le{constructor(e,t){super("AudioStreamNodeAttachingEvent",e,t)}}class Ce extends Le{constructor(e,t){super("AudioStreamNodeAttachedEvent",e,t)}}class $ extends Le{constructor(e,t){super("AudioStreamNodeDetachedEvent",e,t)}}class nt extends Le{constructor(e,t,i){super("AudioStreamNodeErrorEvent",e,t),this.privError=i}get error(){return this.privError}}class zt 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 xt 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 Nt extends oe{constructor(e){super("ConnectionEstablishedEvent",e)}}class Ii 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 Mi 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 ki 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 Di 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 K 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 y;(function(r){r[r.Text=0]="Text",r[r.Binary=1]="Binary"})(y||(y={}));class at{constructor(e,t,i,n){if(this.privBody=null,e===y.Text&&t&&typeof t!="string")throw new K("Payload must be a string");if(e===y.Binary&&t&&!(t instanceof ArrayBuffer))throw new K("Payload must be ArrayBuffer");switch(this.privMessageType=e,this.privBody=t,this.privHeaders=i||{},this.privId=n||b(),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 K("Not supported for binary message");return this.privBody}get binaryBody(){if(this.privMessageType===y.Text)throw new K("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=b();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 x{static setEventSource(e){if(!e)throw new I("eventSource");x.privInstance=e}static get instance(){return x.privInstance}}x.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 Lt;(function(r){r[r.None=0]="None",r[r.Resolved=1]="Resolved",r[r.Rejected=2]="Rejected"})(Lt||(Lt={}));class k{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 Ot=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())})},Ee;(function(r){r[r.Dequeue=0]="Dequeue",r[r.Peek=1]="Peek"})(Ee||(Ee={}));class Te{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 k;return this.privSubscribers&&(this.privSubscribers.add({deferral:e,type:Ee.Dequeue}),this.drain()),e.promise}peek(){this.throwIfDispose();const e=new k;return this.privSubscribers&&(this.privSubscribers.add({deferral:e,type:Ee.Peek}),this.drain()),e.promise}length(){return this.throwIfDispose(),this.privList.length()}isDisposed(){return this.privSubscribers==null}drainAndDispose(e,t){return Ot(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 Ot(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===Ee.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 K(this.privDisposeReason):new ot("Queue");if(this.privIsDisposing)throw new K("Queue disposing")}}class Oe{constructor(e,t,i){if(this.privPayload=null,!t)throw new I("payload");if(e===y.Binary&&t.__proto__.constructor.name!=="ArrayBuffer")throw new K("Payload must be ArrayBuffer");if(e===y.Text&&typeof t!="string")throw new K("Payload must be a string");this.privMessageType=e,this.privPayload=t,this.privId=i||b()}get messageType(){return this.privMessageType}get payload(){return this.privPayload}get textContent(){if(this.privMessageType===y.Binary)throw new K("Not supported for binary message");return this.privPayload}get binaryContent(){if(this.privMessageType===y.Text)throw new K("Not supported for text message");return this.privPayload}get id(){return this.privId}}class zi{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 xi=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 Bt{constructor(e){this.privIsWriteEnded=!1,this.privIsReadEnded=!1,this.privId=e||b(),this.privReaderQueue=new Te}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 K("Stream read has already finished");return this.privReaderQueue.dequeue().then(e=>xi(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 Te)}throwIfClosed(){if(this.privIsWriteEnded)throw new K("Stream closed")}}var be;(function(r){r[r.Success=0]="Success",r[r.Error=1]="Error"})(be||(be={}));class ht extends Bt{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 N{static load(e){const t=new Map([[0,()=>{}]]),i=new Map,n=new Worker(e);return n.addEventListener("message",({data:a})=>{if(N.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(N.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 Ur=Object.defineProperty;var Wr=(H,L,V)=>L in H?Ur(H,L,{enumerable:!0,configurable:!0,writable:!0,value:V}):H[L]=V;var m=(H,L,V)=>(Wr(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(N.workerTimers!==null)return N.workerTimers;const t=new Blob([e],{type:"application/javascript; charset=utf-8"}),i=URL.createObjectURL(t);return N.workerTimers=N.load(i),N.workerTimers.setTimeout(()=>URL.revokeObjectURL(i),0),N.workerTimers}}static isCallNotification(e){return e.method!==void 0&&e.method==="call"}static isClearResponse(e){return e.error===null&&typeof e.id=="number"}}N.workerTimers=null,N.clearTimeout=r=>N.timers().clearTimeout(r),N.setTimeout=(r,e)=>N.timers().setTimeout(r,e),N.timers=N.loadWorkerTimers();class O extends se{constructor(e,t,i){super(e,t),this.privSignature=i}}class Ni extends O{constructor(e){super("OCSPMemoryCacheHitEvent",w.Debug,e)}}class Li extends O{constructor(e){super("OCSPCacheMissEvent",w.Debug,e)}}class Oi extends O{constructor(e){super("OCSPDiskCacheHitEvent",w.Debug,e)}}class Bi extends O{constructor(e){super("OCSPCacheUpdateNeededEvent",w.Debug,e)}}class _i extends O{constructor(e){super("OCSPMemoryCacheStoreEvent",w.Debug,e)}}class Hi extends O{constructor(e){super("OCSPDiskCacheStoreEvent",w.Debug,e)}}class qi extends O{constructor(e){super("OCSPCacheUpdateCompleteEvent",w.Debug,e)}}class Ki extends O{constructor(){super("OCSPStapleReceivedEvent",w.Debug,"")}}class Ui extends O{constructor(e,t){super("OCSPCacheEntryExpiredEvent",w.Debug,e),this.privExpireTime=t}}class Wi extends O{constructor(e,t,i){super("OCSPCacheEntryNeedsRefreshEvent",w.Debug,e),this.privExpireTime=i,this.privStartTime=t}}class Vi extends O{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 O{constructor(e,t){super("OCSPVerificationFailedEvent",w.Debug,e),this.privError=t}}class _t extends O{constructor(e,t){super("OCSPCacheFetchErrorEvent",w.Debug,e),this.privError=t}}class Fi extends O{constructor(e){super("OCSPResponseRetrievedEvent",w.Debug,e)}}class Gi extends O{constructor(e,t){super("OCSPCacheUpdateErrorEvent",w.Debug,e),this.privError=t}}class Re 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 Ht{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 qt="Authorization";class pe{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(qt,pe.privTokenPrefix+t))}fetchOnExpiry(e){return this.privFetchOnExpiryCallback(e).then(t=>new ut(qt,pe.privTokenPrefix+t))}}pe.privTokenPrefix="bearer ";class Kt{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 Ut.create(e)}static createPullStream(e,t){return Wt.create(e,t)}}class Ut extends dt{static create(e){return new $i(e)}}class $i extends Ut{constructor(e){super(),e===void 0?this.privFormat=Y.getDefaultInputFormat():this.privFormat=e,this.privEvents=new j,this.privId=b(),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 ye(this.privId))}attach(e){return pt(this,void 0,void 0,function*(){this.onEvent(new we(this.privId,e)),yield this.turnOn();const t=this.privStream;return this.onEvent(new Ce(this.privId,e)),{detach:()=>pt(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:ge.Unknown,manufacturer:"Speech SDK",model:"PushStream",samplerate:this.privFormat.samplesPerSec,type:ce.Stream})}onEvent(e){this.privEvents.onEvent(e),x.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 Wt extends dt{constructor(){super()}static create(e,t){return new Vt(e,t)}}class Vt extends Wt{constructor(e,t){super(),t===void 0?this.privFormat=Be.getDefaultInputFormat():this.privFormat=t,this.privEvents=new j,this.privId=b(),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 ye(this.privId))}attach(e){return pt(this,void 0,void 0,function*(){return this.onEvent(new we(this.privId,e)),yield this.turnOn(),this.onEvent(new Ce(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:ge.Unknown,manufacturer:"Speech SDK",model:"PullStream",samplerate:this.privFormat.samplesPerSec,type:ce.Stream})}onEvent(e){this.privEvents.onEvent(e),x.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 jt{constructor(){}static createPullStream(){return _e.create()}}class _e extends jt{static create(){return new vt}}class vt extends _e{constructor(){super(),this.privId=b(),this.privStream=new Bt}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 Ft extends jt{constructor(){super()}static create(e){return new lt(e)}}class lt extends Ft{constructor(e){super(),this.privId=b(),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 It(!0);return new de(new W(e))}static fromMicrophoneInput(e){const t=new It(!0);return new de(new W(t,e))}static fromWavFileInput(e,t="unnamedBuffer.wav"){return new de(new Pr(e,t))}static fromStreamInput(e){if(e instanceof Qi)return new de(new Vt(e));if(e instanceof dt)return new de(e);if(typeof MediaStream!="undefined"&&e instanceof MediaStream){const t=new It(!1);return new de(new W(t,null,null,e))}throw new Error("Not Supported Type")}static fromDefaultSpeakerOutput(){return new ve(new wt)}static fromSpeakerOutput(e){if(e===void 0)return ee.fromDefaultSpeakerOutput();if(e instanceof wt)return new ve(e);throw new Error("Not Supported Type")}static fromAudioFileOutput(e){return new ve(new Kt(e))}static fromStreamOutput(e){if(e instanceof Gt)return new ve(new lt(e));if(e instanceof Ft)return new ve(e);if(e instanceof _e)return new ve(e);throw new Error("Not Supported Type")}}class de 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 ve 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 q;(function(r){r[r.Error=0]="Error",r[r.EndOfStream=1]="EndOfStream"})(q||(q={}));class Qi{}class Gt{}class le{constructor(e){this.privSessionId=e}get sessionId(){return this.privSessionId}}class ft extends le{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 Xi{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 Zi extends Xi{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 $t extends ft{constructor(e,t,i){super(t,i),this.privResult=e}get result(){return this.privResult}}class Jt extends le{constructor(e,t){super(t),this.privResult=e}get result(){return this.privResult}}class gt extends Zi{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 Qt{constructor(e,t){this.privReason=e,this.privAudio=t}get audio(){return this.privAudio}get reason(){return this.privReason}}var A;(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"})(A||(A={}));class St{constructor(){}static fromSubscription(e,t){l.throwIfNullOrWhitespace(e,"subscriptionKey"),l.throwIfNullOrWhitespace(t,"region");const i=new fe;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 fe;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 fe;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 fe;return i.setProperty(p.SpeechServiceConnection_Region,t),i.setProperty(p.SpeechServiceConnection_IntentRegion,t),i.authorizationToken=e,i}close(){}}class fe extends St{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(ke,"{}"));i[e]=t,this.privProperties.setProperty(ke,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(gi,"true")}clone(){const e=new fe;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 Xt extends St{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 Xt{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(ke,"{}"));i[e]=t,this.privSpeechProperties.setProperty(ke,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(gi,"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 Ae=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 mt{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 Ae(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 $e(new Je(new ui(e,t,i))));this.privReco=this.createServiceRecognizer(mt.getAuthFromProperties(this.privProperties),this.privConnectionFactory,this.audioConfig,n)}recognizeOnceAsyncImpl(e){return Ae(this,void 0,void 0,function*(){l.throwIfDisposed(this.privDisposed);const t=new k;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 Ae(this,void 0,void 0,function*(){l.throwIfDisposed(this.privDisposed),yield this.implRecognizerStop(),yield this.privReco.recognize(e,void 0,void 0)})}stopContinuousRecognitionAsyncImpl(){return Ae(this,void 0,void 0,function*(){l.throwIfDisposed(this.privDisposed),yield this.implRecognizerStop()})}implRecognizerStop(){return Ae(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 Ht(t):new pe(()=>{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 Zt{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===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 qe{static fromRecognizer(e){const t=e.internalData,i=new qe;return i.privInternalData=t,i.setupEvents(),i}static fromSynthesizer(e){const t=e.internalData,i=new qe;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 ti(e.connectionId)):e.name==="ConnectionClosedEvent"?this.disconnected&&this.disconnected(new ti(e.connectionId)):e.name==="ConnectionMessageSentEvent"?this.messageSent&&this.messageSent(new ii(new Zt(e.message))):e.name==="ConnectionMessageReceivedEvent"&&this.messageReceived&&this.messageReceived(new ii(new Zt(e.message)))}),this.privServiceEventListener=this.privInternalData.serviceEvents.attach(e=>{this.receivedServiceMessage&&this.receivedServiceMessage(new tr(e.jsonString,e.name))})}}var Yt=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 Yi extends mt{constructor(e,t){const i=e;l.throwIfNull(i,"speechConfig"),super(t,i.properties,new dr),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 Yt(this,void 0,void 0,function*(){})}dispose(e){const t=Object.create(null,{dispose:{get:()=>super.dispose}});return Yt(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 ur(e,this.properties)}createServiceRecognizer(e,t,i,n){const s=i;return new lr(e,t,s,n,this)}updateLanguages(e){const t=qe.fromRecognizer(this);t&&(t.setMessageProperty("speech.context","translationcontext",{to:e}),t.sendMessageAsync("event",JSON.stringify({id:"translation",name:"updateLanguage",to:e})))}}class er{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 ei{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 ti extends le{}class tr extends le{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 Ke{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(ke,"{}"));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 ii{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 vr,this.synthesisRequestQueue=new Te,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)===Rr}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 Tr(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 $e(new Je(new ui(e,t,i)))),s=this.privProperties.getProperty(p.SpeechServiceConnection_Key,void 0),o=s&&s!==""?new Ht(s):new pe(()=>{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 Er(n)}speakImpl(e,t,i,n,s){try{l.throwIfDisposed(this.privDisposed);const o=b();let a;s instanceof Gt?a=new lt(s):s instanceof _e?a=s:s!==void 0?a=new Kt(s):a=void 0,this.synthesisRequestQueue.enqueue(new ir(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=b(),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 ni(t,n,void 0)}else return new ni(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 ir{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 ri{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 ri{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 rr{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 nr{constructor(e,t){this.privAudioOffset=e,this.privText=t}get audioOffset(){return this.privAudioOffset}get text(){return this.privText}}class sr{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 ni extends ri{constructor(e,t,i){if(Array.isArray(t)){super(e,A.VoicesListRetrieved,void 0,new U),this.privVoices=[];for(const n of t)this.privVoices.push(new or(n))}else super(e,A.Canceled,i||"Error information unavailable",new U)}get voices(){return this.privVoices}}var Ie;(function(r){r[r.Unknown=0]="Unknown",r[r.Female=1]="Female",r[r.Male=2]="Male"})(Ie||(Ie={}));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 or{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"?Ie.Male:e.Gender==="Female"?Ie.Female:Ie.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 yt=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 ar=60*30,si={[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 wt{constructor(e){this.privPlaybackStarted=!1,this.privAppendingToBuffer=!1,this.privMediaSourceOpened=!1,this.privBytesReceived=0,this.privId=e||b(),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:si[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=si[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=ar,this.privSourceBuffer=this.privMediaSource.addSourceBuffer(t),this.privSourceBuffer.onupdate=()=>{this.updateSourceBuffer().catch(i=>{x.instance.onEvent(new Re(i))})},this.privSourceBuffer.onupdateend=()=>{this.handleSourceBufferUpdateEnd().catch(i=>{x.instance.onEvent(new Re(i))})},this.privSourceBuffer.onupdatestart=()=>{this.privAppendingToBuffer=!1}},this.updateSourceBuffer().catch(i=>{x.instance.onEvent(new Re(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 yt(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 yt(this,void 0,void 0,function*(){this.canEndStream()&&this.sourceBufferAvailable()&&(this.privMediaSource.endOfStream(),yield this.notifyPlayback())})}notifyPlayback(){return yt(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 Ge 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 oi extends Ge{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 cr extends Ge{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 ai extends Ge{constructor(e,t,i){super("ConnectingToServiceEvent",e,i),this.privAuthFetchEventid=t}get authFetchEventid(){return this.privAuthFetchEventid}}class hr extends Ge{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 ci;(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"})(ci||(ci={}));class B 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 B(e.messageType,t,i,n,e.body,s,o,e.id)}}var D=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 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 gr(this.privAudioSource.id()),this.privConnectionEvents=new j,this.privServiceEvents=new j,this.privDynamicGrammar=new mr,this.privSpeechContext=new Sr(this.privDynamicGrammar),this.privAgentConfig=new li,typeof Blob!="undefined"&&typeof Worker!="undefined"&&(this.privSetTimeout=N.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(q.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 D(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 D(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 Mr(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(q.Error,R.ConnectionFailure,u);return}const o=new le(this.privRequestSession.sessionId);this.privRecognizer.sessionStarted&&this.privRecognizer.sessionStarted(this.privRecognizer,o),this.receiveMessage(),this.sendAudio(s).catch(u=>D(this,void 0,void 0,function*(){yield this.cancelRecognitionLocal(q.Error,R.RuntimeError,u)}))})}stopRecognizing(){return D(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 D(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 D(this,void 0,void 0,function*(){if(yield this.cancelRecognitionLocal(q.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 D(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 B(i,e,this.privRequestSession.requestId,n,t))})}set activityTemplate(e){this.privActivityTemplate=e}get activityTemplate(){return this.privActivityTemplate}sendTelemetryData(){return D(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 B(y.Text,"telemetry",this.privRequestSession.requestId,"application/json",e))})}cancelRecognitionLocal(e,t,i){return D(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 D(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=B.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(q.EndOfStream,R.NoError,void 0));const h=new le(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 zt(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 B(y.Text,"speech.context",this.privRequestSession.requestId,"application/json",i))}sendPrePayloadJSON(e,t=!0){return D(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 D(this,void 0,void 0,function*(){const t=yield this.audioSource.format;return e.send(new B(y.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(),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 B(y.Text,"speech.config",t.requestId,"application/json",i))}fetchConnection(){return D(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 D(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=()=>D(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 B(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 D(this,void 0,void 0,function*(){let e=!1;this.privAuthFetchEventId=b();const t=this.privRequestSession.sessionId;this.privConnectionId=t!==void 0?t:b(),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 D(this,void 0,void 0,function*(){yield(yield this.fetchConnection()).send(new B(y.Binary,"audio",this.privRequestSession.requestId,null,null))})}configureConnection(){return D(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 ae;(function(r){r[r.Interactive=0]="Interactive",r[r.Conversation=1]="Conversation",r[r.Dictation=2]="Dictation"})(ae||(ae={}));var hi;(function(r){r[r.Simple=0]="Simple",r[r.Detailed=1]="Detailed"})(hi||(hi={}));class ur{constructor(e,t){this.privSpeechServiceConfig=e||new $e(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 $e{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 pr,this.os=e}}class pr{constructor(){const e="1.22.0";this.name="SpeechSDK",this.version=e,this.build="JavaScript",this.lang="JavaScript"}}class ui{constructor(e,t,i){this.platform=e,this.name=t,this.version=i}}var ge;(function(r){r.Bluetooth="Bluetooth",r.Wired="Wired",r.WiFi="WiFi",r.Cellular="Cellular",r.InBuilt="InBuilt",r.Unknown="Unknown"})(ge||(ge={}));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 pi=`\r
4
+ `;class di{toConnectionMessage(e){const t=new k;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 at(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 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 k;try{if(e.messageType===y.Text){const i=`${this.makeHeaders(e)}${pi}${e.textBody?e.textBody:""}`;t.resolve(new Oe(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 Oe(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]}${pi}`);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 dr extends Ke{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=Ke.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 mi(n,s,u,new di,it.fromRecognizerConfig(e),h,i)}}class vr{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=Ke.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 mi(n,c,d,new di,it.fromParameters(e.parameters),S,i)}}class Qe{static implTranslateRecognitionResult(e){let t=A.Canceled;switch(e){case E.Success:t=A.RecognizedSpeech;break;case E.NoMatch:case E.InitialSilenceTimeout:case E.BabbleTimeout:case E.EndOfDictation:t=A.NoMatch;break;case E.Error:case E.BadRequest:case E.Forbidden:default:t=A.Canceled;break}return t}static implTranslateCancelResult(e){let t=q.EndOfStream;switch(e){case E.Success:case E.EndOfDictation:case E.NoMatch:t=q.EndOfStream;break;case E.InitialSilenceTimeout:case E.BabbleTimeout:case E.Error:case E.BadRequest:case E.Forbidden:default:t=q.Error;break}return t}static implTranslateCancelErrorCode(e){let t=R.NoError;switch(e){case E.Error:t=R.ServiceError;break;case E.TooManyRequests:t=R.TooManyRequests;break;case E.BadRequest:t=R.BadRequestParameters;break;case E.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 Me;(function(r){r[r.Success=0]="Success",r[r.SynthesisEnd=1]="SynthesisEnd",r[r.Error=2]="Error"})(Me||(Me={}));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 Ct{constructor(e){this.privSynthesisEnd=JSON.parse(e),this.privSynthesisEnd.SynthesisStatus=Me[this.privSynthesisEnd.SynthesisStatus]}static fromJSON(e){return new Ct(e)}get SynthesisStatus(){return this.privSynthesisEnd.SynthesisStatus}get FailureReason(){return this.privSynthesisEnd.FailureReason}}class Et{constructor(e){this.privTranslationHypothesis=JSON.parse(e),this.privTranslationHypothesis.Translation.TranslationStatus=be[this.privTranslationHypothesis.Translation.TranslationStatus]}static fromJSON(e){return new Et(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 Se{constructor(e){this.privTranslationPhrase=e,this.privTranslationPhrase.RecognitionStatus=E[this.privTranslationPhrase.RecognitionStatus],this.privTranslationPhrase.Translation!==void 0&&(this.privTranslationPhrase.Translation.TranslationStatus=be[this.privTranslationPhrase.Translation.TranslationStatus])}static fromJSON(e){return new Se(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 Se(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 vi=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 lr 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 vi(this,void 0,void 0,function*(){const t=new U;let i=!1;const n=s=>vi(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=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===A.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===A.NoMatch&&s.RecognitionStatus!==E.InitialSilenceTimeout)){const u=new $t(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(Et.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(Se.fromTranslationResponse(o)));break;case"translation.phrase":yield n(Se.fromJSON(e.textBody));break;case"translation.synthesis":this.sendSynthesisAudio(e.binaryBody,this.privRequestSession.sessionId),i=!0;break;case"translation.synthesis.end":const a=Ct.fromJSON(e.textBody);switch(a.SynthesisStatus){case Me.Error:if(this.privTranslationRecognizer.synthesizing){const u=new Qt(A.Canceled,void 0),h=new Jt(u,this.privRequestSession.sessionId);try{this.privTranslationRecognizer.synthesizing(this.privTranslationRecognizer,h)}catch{}}if(this.privTranslationRecognizer.canceled){const u=new ei(this.privRequestSession.sessionId,q.Error,a.FailureReason,R.ServiceError,null);try{this.privTranslationRecognizer.canceled(this.privTranslationRecognizer,u)}catch{}}break;case Me.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(fi,R[n]),this.privTranslationRecognizer.canceled){const a=new ei(e,i,s,n,void 0);try{this.privTranslationRecognizer.canceled(this.privTranslationRecognizer,a)}catch{}}if(this.privSuccessCallback){const a=new gt(void 0,t,A.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 er;for(const u of e.Translation.Translations)i.set(u.Language,u.Text||u.DisplayText)}let n;e instanceof Se?e.Translation.TranslationStatus===be.Success?n=A.TranslatedSpeech:n=A.RecognizedSpeech:n=A.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 $t(o,s,this.privRequestSession.sessionId)}sendSynthesisAudio(e,t){const i=e===void 0?A.SynthesizingAudioCompleted:A.SynthesizingAudio,n=new Qt(i,e),s=new Jt(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 fr{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 oi&&e.requestId===this.privRequestId&&(this.privListeningTriggerMetric={End:e.eventTime,Name:"ListeningTrigger",Start:e.eventTime}),e instanceof we&&e.audioSourceId===this.privAudioSourceId&&e.audioNodeId===this.privAudioNodeId&&(this.privMicStartTime=e.eventTime),e instanceof Ce&&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 $&&e.audioSourceId===this.privAudioSourceId&&e.audioNodeId===this.privAudioNodeId&&(this.privMicMetric||(this.privMicMetric={End:e.eventTime,Name:"Microphone",Start:this.privMicStartTime})),e instanceof ai&&e.requestId===this.privRequestId&&(this.privConnectionId=e.sessionId),e instanceof xt&&e.connectionId===this.privConnectionId&&(this.privConnectionStartTime=e.eventTime),e instanceof Nt&&e.connectionId===this.privConnectionId&&(this.privConnectionEstablishMetric||(this.privConnectionEstablishMetric={End:e.eventTime,Id:this.privConnectionId,Name:"Connection",Start:this.privConnectionStartTime})),e instanceof ki&&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 gr{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=b(),this.privAudioNodeId=b(),this.privTurnDeferral=new k,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 fr(this.privRequestId,this.privAudioSourceId,this.privAudioNodeId),this.onEvent(new oi(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 cr(this.privRequestId,this.privSessionId,this.privAudioSourceId,this.privAudioNodeId))})}onPreConnectionStart(e,t){this.privAuthFetchEventId=e,this.privSessionId=t,this.onEvent(new ai(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 hr(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=b()}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 k}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),x.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 Sr{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 mr{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 li{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 Tt{constructor(e){this.privSynthesisAudioMetadata=JSON.parse(e)}static fromJSON(e){return new Tt(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 br(this.privSpeechSynthesizer),this.privAgentConfig=new li,this.connectionEvents.attach(o=>{if(o.name==="ConnectionClosedEvent"){const a=o;a.statusCode!==1e3&&this.cancelSynthesisLocal(q.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"?y.Text:y.Binary,n=typeof t=="string"?"application/json":"";return(yield this.fetchConnection()).send(new B(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,A.SynthesizingAudioStarted));this.privSpeechSynthesizer.synthesisStarted&&this.privSpeechSynthesizer.synthesisStarted(this.privSpeechSynthesizer,h),this.receiveMessage()}catch(u){return this.cancelSynthesisLocal(q.Error,R.ConnectionFailure,u),Promise.reject(u)}})}cancelSynthesis(e,t,i,n){const s=new U;s.setProperty(fi,R[i]);const o=new Ve(e,A.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=B.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,A.SynthesizingAudio,o));this.privSpeechSynthesizer.synthesizing(this.privSpeechSynthesizer,a)}catch{}this.privSessionAudioDestination!==void 0&&this.privSessionAudioDestination.write(i.binaryBody)}break;case"audio.metadata":const n=Tt.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 rr(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 nr(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 sr(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,A.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 zt(i.path.toLowerCase(),i.textBody))}return this.receiveMessage()}catch{}})}sendSynthesisContext(e){const t=this.synthesisContext.toJSON();if(t)return e.send(new B(y.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=b(),this.privConnectionId=b(),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 B(y.Text,"speech.config",this.privSynthesisTurn.requestId,"application/json",t))}sendSsmlMessage(e,t,i){return e.send(new B(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()===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 bt extends se{constructor(e,t,i=w.Info){super(e,i),this.privRequestId=t}get requestId(){return this.privRequestId}}class yr extends bt{constructor(e,t,i){super("SynthesisTriggeredEvent",e),this.privSessionAudioDestinationId=t,this.privTurnAudioDestinationId=i}get audioSessionDestinationId(){return this.privSessionAudioDestinationId}get audioTurnDestinationId(){return this.privTurnAudioDestinationId}}class wr extends bt{constructor(e,t){super("ConnectingToSynthesisServiceEvent",e),this.privAuthFetchEventId=t}get authFetchEventId(){return this.privAuthFetchEventId}}class Cr extends bt{constructor(e,t){super("SynthesisStartedEvent",e),this.privAuthFetchEventId=t}get authFetchEventId(){return this.privAuthFetchEventId}}var Rt=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=b(),this.privTurnDeferral=new k,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 Rt(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 Rt(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 yr(this.requestId,void 0,n===void 0?void 0:n.id()))}onPreConnectionStart(e){this.privAuthFetchEventId=e,this.onEvent(new wr(this.privRequestId,this.privAuthFetchEventId))}onAuthCompleted(e){e&&this.onComplete()}onConnectionEstablishCompleted(e){if(e===200){this.onEvent(new Cr(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 k}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){x.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 Rt(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 Er{constructor(e){let t=e.parameters.getProperty(p.SpeechServiceConnection_Endpoint,void 0);if(!t){const n=e.parameters.getProperty(p.SpeechServiceConnection_Region,"westus"),s=Ke.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 Or(i)}getVoicesList(e){return this.privRestAdapter.setHeaders(T.ConnectionId,e),this.privRestAdapter.request(he.Get,this.privUri)}}var At;(function(r){r[r.Standard=0]="Standard",r[r.Custom=1]="Custom"})(At||(At={}));class Tr{constructor(e,t){this.privSynthesisServiceType=At.Standard,this.privSpeechServiceConfig=e||new $e(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 br{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",fi="CancellationErrorCode",ke="ServiceProperties",gi="ForceDictation",Rr="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 Ar="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||b(),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 k;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 ye(this.privId)),this.privInitializeDeferral.resolve()):t({audio:this.deviceId?{deviceId:this.deviceId}:!0,video:!1},n=>{this.privMediaStream=n,this.onEvent(new ye(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 we(this.privId,e)),this.listen(e).then(t=>(this.onEvent(new Ce(this.privId,e)),{detach:()=>et(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 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 Dt(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:ge.Unknown,manufacturer:"Speech SDK",model:e,samplerate:W.AUDIOFORMAT.samplesPerSec,type:ce.Microphones}))}setProperty(e,t){if(e===Ar)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 k;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),x.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 Pr{constructor(e,t,i){this.privStreams={},this.privHeaderEnd=44,this.privId=i||b(),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 ye(this.privId))}id(){return this.privId}attach(e){return Pt(this,void 0,void 0,function*(){this.onEvent(new we(this.privId,e));const t=yield this.upload(e);return this.onEvent(new Ce(this.privId,e)),Promise.resolve({detach:()=>Pt(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 Dt(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:ge.Unknown,manufacturer:"Speech SDK",model:"File",samplerate:e.samplesPerSec,type:ce.File}))}readHeader(){const t=this.privSource.slice(0,512),i=new k,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),x.instance.onEvent(e)}}class It{constructor(e){this.privStopInputOnRelease=e}record(e,t,i){const s=new zi(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,15 +17,15 @@ 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,"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}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.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 u;if(~[".",",","!","?","*","(",")","&","\\","/","^","[","]","<",">",":"].indexOf(e.text)&&(e=(u=this.previousWordBoundary)!=null?u:void 0),!e){this.resetPlaybackSegments();return}const t=this.playbackSegments.find(h=>e.textOffset>=h.start&&e.textOffset<h.end);if(this.resetPlaybackSegments(),!(t!=null&&t.highlightDiv)){this.previousWordBoundary=e;return}const i=e.textOffset-t.start,n=this.getPosition(t.originalHighlightDivInnerHTML,e.text,i);if(n===Number.MAX_SAFE_INTEGER){this.previousWordBoundary=e;return}const s=t.originalHighlightDivInnerHTML.substring(0,n),o=n+e.wordLength,a=t.originalHighlightDivInnerHTML.substring(o);t.highlightDiv.innerHTML=`
21
- ${s}<mark class='co-tts-highlight'>${e.text}</mark>${a}
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){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=`
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 P{constructor(e){e&&(this.privProxyInfo=e),P.privDiskCache||(P.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(){P.privDiskCache=void 0,P.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 Ki),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 P.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=P.privMemCache[e];if(n&&this.onEvent(new Ni(e)),!n)try{const s=yield P.privDiskCache.get(e);s.isCached&&(P.onEvent(new Oi(e)),P.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 _t(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 Ui(e,h)),n=null;else{const c=Math.min(864e5,(h-u)/2);h-(Date.now()+this.testTimeOffset)<c?(this.onEvent(new Wi(e,u,h)),this.UpdateCache(t,i).catch(d=>{this.onEvent(new Gi(e,d.toString()))})):this.onEvent(new Vi(e,u,h))}}catch(s){this.onEvent(new _t(e,s)),n=null}return n||this.onEvent(new Li(e)),n})}static VerifyOCSPResponse(e,t,i){return De(this,void 0,void 0,function*(){let n=e;return n||(n=yield P.GetOCSPResponse(t,i)),new Promise((s,o)=>{(void 0)({request:t,response:n},a=>{a?(P.onEvent(new ji(t.id.toString("hex"),a)),e?this.VerifyOCSPResponse(null,t,i).then(()=>{s()},u=>{o(u)}):o(a)):(e||P.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 Bi(i));const n=yield this.GetOCSPResponse(e,t);this.StoreCacheEntry(i,n),this.onEvent(new qi(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 _i(e))}static StoreDiskCacheEntry(e,t){this.privDiskCache.set(e,t).then(()=>{this.onEvent(new Hi(e))})}static GetOCSPResponse(e,t){const i="1.3.6.1.5.5.7.48.1";let n={};if(t){const s=P.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 Fi(S.toString("hex"))),s(d)})})})}static onEvent(e){x.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:!P.forceDisableOCSPStapling,servername:t.host}),this.privProxyInfo){const o=P.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?P.OCSPCheck(n,this.privProxyInfo):n}}P.testTimeOffset=0,P.forceDisableOCSPStapling=!1,P.privMemCache={};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 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 k,this.privCertificateValidatedDeferral=new k,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 P(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 Te,this.privDisconnectDeferral=new k,this.privSendMessageQueue=new Te,this.processSendQueue().catch(e=>{x.instance.onEvent(new Re(e))})}catch(e){return this.privConnectionEstablishDeferral.resolve(new ct(500,e)),this.privConnectionEstablishDeferral.promise}return this.onEvent(new xt(this.privConnectionId,this.privUri)),this.privWebsocketClient.onopen=()=>{this.privCertificateValidatedDeferral.promise.then(()=>{this.privConnectionState=M.Connected,this.onEvent(new Nt(this.privConnectionId)),this.privConnectionEstablishDeferral.resolve(new ct(200,""))},e=>{this.privConnectionEstablishDeferral.reject(e)})},this.privWebsocketClient.onerror=e=>{this.onEvent(new Mi(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 Ii(this.privConnectionId,e.code,e.reason))),this.onClose(e.code,e.reason).catch(t=>{x.instance.onEvent(new Re(t))})},this.privWebsocketClient.onmessage=e=>{const t=new Date().toISOString();if(this.privConnectionState===M.Connected){const i=new k;if(this.privReceivingMessageQueue.enqueueFromPromise(i.promise),e.data instanceof ArrayBuffer){const n=new Oe(y.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 Oe(y.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 k,i=new k;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 Di(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 Si(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 Si(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),x.instance.onEvent(e)}get isWebsocketOpen(){return this.privWebsocketClient&&this.privWebsocketClient.readyState===this.privWebsocketClient.OPEN}}tt.forceNpmWebSocket=!1;var Ir=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 mi{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||b(),this.privConnectionMessageAdapter=new tt(this.privUri,this.id,this.privMessageFormatter,s,i,o)}dispose(){return Ir(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 Mr{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 kr(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 kr{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 Dr=new Set(["json","buffer","string"]);var zr=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(Dr.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 xr=zr;class Mt extends Error{constructor(e,...t){super(...t),Error.captureStackTrace&&Error.captureStackTrace(this,Mt),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 Nr=xr((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 Mt(h);return t==="json"?h.json():t==="buffer"?h.arrayBuffer():t==="string"?h.text():h}),Lr=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 Or{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 k,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=Nr(t,a,this.privHeaders,200,201,202,204,400,401,402,403,404),_=this.queryParams(i)===""?"":`?${this.queryParams(i)}`;S(_,d).then(Z=>Lr(this,void 0,void 0,function*(){if(e===he.Delete||Z.statusCode===204)o.resolve(u(Z));else try{const ze=yield Z.json();o.resolve(u(Z,ze))}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("&")}}const Br=8*60*1e3;function _r(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;let o;try{o=await fetch(i,{method:"GET",credentials:(u=n.credentials)!=null?u:"same-origin",headers:{Accept:"application/json",...(h=n.headers)!=null?h:{}}})}catch{throw ue("Could not reach the speech token endpoint.","TOKEN_ENDPOINT_UNREACHABLE")}if(!o.ok)throw ue(`Speech token endpoint returned HTTP ${o.status}.`,"TOKEN_ENDPOINT_HTTP_ERROR");let a;try{a=await o.json()}catch{throw ue("Speech token endpoint returned invalid JSON.","TOKEN_ENDPOINT_INVALID_JSON")}return yi(a)}}function yi(r){if(!r||typeof r!="object")throw ue("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 ue("Speech authorization token is missing or empty.","TOKEN_EMPTY");if(i==="")throw ue("Speech authorization region is missing or empty.","TOKEN_REGION_MISSING");return{token:t,region:i}}function ue(r,e){const t=new Error(r);return t.message=r,e&&(t.code=e),t}function kt(r){if(r&&typeof r=="object"){const e=r,i={message:typeof e.message=="string"&&e.message.trim()!==""?Hr(e.message):"An unexpected speech error occurred."};return typeof e.code=="string"&&e.code.trim()!==""&&(i.code=e.code),i}return{message:"An unexpected speech error occurred."}}function Hr(r){return r.replace(/Bearer\s+\S+/gi,"Bearer [redacted]").replace(/token["']?\s*[:=]\s*["']?[^"',\s}]+/gi,"token=[redacted]")}class wi{constructor(e){m(this,"authorization");m(this,"authorizationExpiresAt",0);m(this,"authorizationRequest");m(this,"provider");m(this,"tokenLifetimeMs");this.provider=_r(e),this.tokenLifetimeMs=e.tokenLifetimeMs&&e.tokenLifetimeMs>0?e.tokenLifetimeMs:Br}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)}clearAuthorization(){this.authorization=void 0,this.authorizationExpiresAt=0,this.authorizationRequest=void 0}async fetchAuthorization(){try{const e=await this.provider();return yi(e)}catch(e){throw this.clearAuthorization(),ue(kt(e).message,e==null?void 0:e.code)}}}class qr{constructor(e){m(this,"region");m(this,"sourceLanguage");m(this,"targetLanguage");m(this,"recognizer");m(this,"authorizationManager");var t,i,n;if(!e||typeof e.sourceLanguage!="string"||e.sourceLanguage.trim()==="")throw new Error("A sourceLanguage is required.");this.authorizationManager=new wi(e),this.region=(i=(t=e.region)==null?void 0:t.trim())!=null?i:"",this.sourceLanguage=e.sourceLanguage,this.targetLanguage=(n=e.targetLanguage)!=null?n: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=Xt.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{const n=await this.createSpeechTranslationConfig(),s=ee.fromDefaultMicrophoneInput();this.recognizer=new Yi(n,s),document.dispatchEvent(new CustomEvent("COAzureSTTStartedRecording",{}));const o=[];this.recognizer.recognizing=(a,u)=>{const h=u.result;if(h&&h.reason===A.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=>{this.dispatchError(a,"RECOGNITION_ERROR"),this.stop()})}catch(n){this.dispatchError(n),await this.stop()}})}async handleStopModifier(e,t){e.addEventListener("click",async i=>{await this.stop()})}async stop(){if(this.recognizer!==void 0){try{this.recognizer.stopContinuousRecognitionAsync()}catch{}try{this.recognizer.close()}catch{}this.recognizer=void 0}document.dispatchEvent(new CustomEvent("COAzureSTTStoppedRecording",{}))}dispatchError(e,t){const i=kt(e);t&&!i.code&&(i.code=t),document.dispatchEvent(new CustomEvent("COAzureSTTError",{detail:{error:i}}))}}class Kr{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");var t,i,n,s,o;if(!e||typeof e.voice!="string"||e.voice.trim()==="")throw new Error("A voice is required.");this.authorizationManager=new wi(e),this.region=(i=(t=e.region)==null?void 0:t.trim())!=null?i:"",this.voice=e.voice,this.rate=(n=e.rate)!=null?n:0,this.pitch=(s=e.pitch)!=null?s:0,this.url=(o=e.url)!=null?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,a,u;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"))if(((u=n.attributes.getNamedItem("co-tts.highlight"))==null?void 0:u.value)!==""){const h=document.getElementById(n.attributes.getNamedItem("co-tts.highlight").value);this.highlightDiv=h,this.originalHighlightDivInnerHTML=h.innerHTML}else this.highlightDiv=n,this.originalHighlightDivInnerHTML=n.innerHTML;await 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(),await this.startSynthesizer(e,t)})}async handleDefault(e,t){e.addEventListener("click",async i=>{var n,s,o;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 a=document.getElementById(e.attributes.getNamedItem("co-tts.highlight").value);this.highlightDiv=a,this.originalHighlightDivInnerHTML=a.innerHTML}else this.highlightDiv=e,this.originalHighlightDivInnerHTML=e.innerHTML;t.value===""?this.textToRead=(o=(s=e.innerText)!=null?s:e.textContent)!=null?o:"":this.textToRead=t.value,await this.startSynthesizer(e,t)})}async handleWithoutClick(e,t){var i,n,s;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 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=>{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.closeSynthesizer(),this.player=void 0,this.audioConfig=void 0,this.speechConfig=void 0,this.highlightDiv=void 0,this.prevTextOffset=0,this.playbackTextOffsetBase=void 0}async createSpeechConfig(){const e=await this.authorizationManager.getAuthorization(),t=St.fromAuthorizationToken(e.token,e.region);return t.speechSynthesisVoiceName=`Microsoft Server Speech Text to Speech Voice (${this.voice})`,t.speechSynthesisOutputFormat=g.Audio24Khz160KBitRateMonoMp3,this.region=e.region,t}async startSynthesizer(e,t){try{this.speechConfig=await this.createSpeechConfig(),this.player=new wt,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.closeSynthesizer()},s=>{this.dispatchError(s,"SYNTHESIS_ERROR"),this.closeSynthesizer(),this.stopPlayer()})}catch(i){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;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=`
21
+ ${o}<mark class='co-tts-highlight'>${e.text}</mark>${u}
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 Pe(h,null);const c=[];return o.wordBoundary=(d,S)=>{c.push(S)},await new Promise(d=>{o==null||o.speakSsmlAsync(this.buildSSML(n),S=>{if(this.closeResource(o),o=void 0,!(S!=null&&S.audioData)){d(null);return}const _=new Blob([S.audioData],{type:"audio/mpeg"}),Z=URL.createObjectURL(_),ze={key:s,nodeId:t.id,text:n,url:Z,wordBoundryList:c};this.prefetchedAudio.set(s,ze),d(ze)},S=>{this.closeResource(o),o=void 0,this.dispatchError(S,"PREFETCH_ERROR"),d(null)})})}catch(h){return this.closeResource(o),o=void 0,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()=>{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}),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
- `}}else 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"
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"
26
26
  xmlns:emo="http://www.w3.org/2009/10/emotionml"
27
27
  version="1.0"
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=kt(e);t&&!i.code&&(i.code=t),document.dispatchEvent(new CustomEvent("COAzureTTSError",{detail:{error:i}}))}}H.SpeechToText=qr,H.TextToSpeech=Kr,Object.defineProperties(H,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});